diff --git a/MantidPlot/src/ApplicationWindow.cpp b/MantidPlot/src/ApplicationWindow.cpp
index 1213c95e06d3702a4c7061bcf61b26fdb00ee856..bf5a66d2b78476929ac5df49044535ec86aae59c 100644
--- a/MantidPlot/src/ApplicationWindow.cpp
+++ b/MantidPlot/src/ApplicationWindow.cpp
@@ -232,7 +232,6 @@ using Mantid::Kernel::Logger;
 namespace {
 /// static logger
 Logger g_log("ApplicationWindow");
-
 }
 
 extern "C" {
@@ -402,11 +401,10 @@ void ApplicationWindow::init(bool factorySettings, const QStringList &args) {
   folders->header()->hide();
   folders->setSelectionMode(QAbstractItemView::SingleSelection);
 
-  connect(folders, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this,
-          SLOT(folderItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
   connect(folders,
-          SIGNAL(customContextMenuRequested(const QPoint &)),
-          this,
+          SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
+          this, SLOT(folderItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
+  connect(folders, SIGNAL(customContextMenuRequested(const QPoint &)), this,
           SLOT(showFolderPopupMenu(const QPoint &)));
   connect(folders, SIGNAL(deleteSelection()), this,
           SLOT(deleteSelectedItems()));
@@ -542,15 +540,14 @@ void ApplicationWindow::init(bool factorySettings, const QStringList &args) {
   connect(this, SIGNAL(modified()), this, SLOT(modifiedProject()));
   connect(d_workspace, SIGNAL(subWindowActivated(QMdiSubWindow *)), this,
           SLOT(windowActivated(QMdiSubWindow *)));
-  connect(
-      lv, SIGNAL(customContextMenuRequested(const QPoint &)),
-      this, SLOT(showWindowPopupMenu(const QPoint &)));
+  connect(lv, SIGNAL(customContextMenuRequested(const QPoint &)), this,
+          SLOT(showWindowPopupMenu(const QPoint &)));
   connect(lv, SIGNAL(deleteSelection()), this, SLOT(deleteSelectedItems()));
 
-  connect(recentProjectsMenu, SIGNAL(triggered(QAction*)), this,
-          SLOT(openRecentProject(QAction*)));
-  connect(recentFilesMenu, SIGNAL(triggered(QAction*)), this,
-          SLOT(openRecentFile(QAction*)));
+  connect(recentProjectsMenu, SIGNAL(triggered(QAction *)), this,
+          SLOT(openRecentProject(QAction *)));
+  connect(recentFilesMenu, SIGNAL(triggered(QAction *)), this,
+          SLOT(openRecentFile(QAction *)));
 
   // apply user settings
   updateAppFonts();
@@ -1093,7 +1090,12 @@ void ApplicationWindow::insertTranslatedStrings() {
     setWindowTitle(tr("MantidPlot - untitled")); // Mantid
 
   QStringList labels;
-  labels << "Name" << "Type"<<"View" << "Size"<< "Created" << "Label";
+  labels << "Name"
+         << "Type"
+         << "View"
+         << "Size"
+         << "Created"
+         << "Label";
   lv->setHeaderLabels(labels);
   lv->resizeColumnToContents(0);
   lv->resizeColumnToContents(1);
@@ -2594,8 +2596,7 @@ void ApplicationWindow::exportMatrix() {
     QMessageBox::critical(
         this, tr("MantidPlot - Export error"), // Mantid
         tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
-           "you have the right to write to this location!")
-            .arg(file_name));
+           "you have the right to write to this location!").arg(file_name));
     return;
   }
 
@@ -4494,8 +4495,7 @@ ApplicationWindow *ApplicationWindow::open(const QString &fn,
       int choice = QMessageBox::question(
           this, tr("MantidPlot - File opening error"), // Mantid
           tr("The file <b>%1</b> is corrupted, but there exists a backup "
-             "copy.<br>Do you want to open the backup instead?")
-              .arg(fn),
+             "copy.<br>Do you want to open the backup instead?").arg(fn),
           QMessageBox::Yes | QMessageBox::Default,
           QMessageBox::No | QMessageBox::Escape);
       if (choice == QMessageBox::Yes)
@@ -4517,7 +4517,7 @@ ApplicationWindow *ApplicationWindow::open(const QString &fn,
   return app;
 }
 
-void ApplicationWindow::openRecentFile(QAction* action) {
+void ApplicationWindow::openRecentFile(QAction *action) {
   auto fn = action->data().toString();
   // if "," found in the QString
   if (fn.indexOf(",", 0)) {
@@ -4536,8 +4536,7 @@ void ApplicationWindow::openRecentFile(QAction* action) {
       QMessageBox::critical(
           this, tr("MantidPlot - File Open Error"), // Mantid
           tr("The file: <b> %1 </b> <p>is not there anymore!"
-             "<p>It will be removed from the list of recent files.")
-              .arg(fn));
+             "<p>It will be removed from the list of recent files.").arg(fn));
 
       recentFiles.removeAll(fn);
       updateRecentFilesList();
@@ -4548,7 +4547,7 @@ void ApplicationWindow::openRecentFile(QAction* action) {
   saveSettings(); // save new list of recent files
 }
 
-void ApplicationWindow::openRecentProject(QAction* action) {
+void ApplicationWindow::openRecentProject(QAction *action) {
   QString fn = action->text();
   int pos = fn.indexOf(" ", 0);
   fn = fn.right(fn.length() - pos - 1);
@@ -4558,8 +4557,7 @@ void ApplicationWindow::openRecentProject(QAction* action) {
     QMessageBox::critical(
         this, tr("MantidPlot - File Open Error"), // Mantid
         tr("The file: <b> %1 </b> <p>does not exist anymore!"
-           "<p>It will be removed from the list of recent projects.")
-            .arg(fn));
+           "<p>It will be removed from the list of recent projects.").arg(fn));
 
     recentProjects.remove(fn);
     updateRecentProjectsList();
@@ -4611,7 +4609,7 @@ ApplicationWindow *ApplicationWindow::openProject(const QString &filename,
     throw std::runtime_error("Couldn't open project file");
 
   QTextStream fileTS(&file);
-  fileTS.setCodec(QTextCodec::codecForName("UTF-8")) ;
+  fileTS.setCodec(QTextCodec::codecForName("UTF-8"));
 
   QString baseName = fileInfo.fileName();
 
@@ -4961,8 +4959,7 @@ void ApplicationWindow::readSettings() {
   // set logging level to the last saved level
   int lastLoggingLevel =
       settings.value("/LastLoggingLevel",
-                     Mantid::Kernel::Logger::Priority::PRIO_NOTICE)
-          .toInt();
+                     Mantid::Kernel::Logger::Priority::PRIO_NOTICE).toInt();
   Mantid::Kernel::Logger::setLevelForAll(lastLoggingLevel);
 
   d_backup_files = settings.value("/BackupProjects", true).toBool();
@@ -5247,7 +5244,7 @@ void ApplicationWindow::readSettings() {
   applyCurveStyleToMantid = settings.value("/ApplyMantid", true).toBool();
   // Once only for DrawAllErrors set to true, by SSC request
   bool setDrawAllErrorsSetToTrueOnce =
-    settings.value("/DrawAllErrorsSetToTrueOnce", false).toBool();
+      settings.value("/DrawAllErrorsSetToTrueOnce", false).toBool();
   if (!setDrawAllErrorsSetToTrueOnce) {
     settings.setValue("/DrawAllErrors", true);
     settings.setValue("/DrawAllErrorsSetToTrueOnce", true);
@@ -5320,9 +5317,8 @@ void ApplicationWindow::readSettings() {
                       .name();
   plot3DColors << QColor(settings.value("/Axes", "#000000").value<QColor>())
                       .name();
-  plot3DColors << QColor(
-                      settings.value("/Background", "#ffffff").value<QColor>())
-                      .name();
+  plot3DColors << QColor(settings.value("/Background", "#ffffff")
+                             .value<QColor>()).name();
   settings.endGroup(); // Colors
   settings.endGroup();
   /* ----------------- end group 3D Plots --------------------------- */
@@ -5854,8 +5850,7 @@ void ApplicationWindow::exportGraph() {
     QMessageBox::critical(
         this, tr("MantidPlot - Export error"), // Mantid
         tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
-           "you have the right to write to this location!")
-            .arg(file_name));
+           "you have the right to write to this location!").arg(file_name));
     return;
   }
   file.close();
@@ -5918,8 +5913,7 @@ void ApplicationWindow::exportLayer() {
     QMessageBox::critical(
         this, tr("MantidPlot - Export error"), // Mantid
         tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
-           "you have the right to write to this location!")
-            .arg(file_name));
+           "you have the right to write to this location!").arg(file_name));
     return;
   }
   file.close();
@@ -5981,8 +5975,7 @@ void ApplicationWindow::exportAllGraphs() {
         QMessageBox::warning(
             this, tr("MantidPlot - Warning"), // Mantid
             tr("There are no plot layers available in window <b>%1</b>.<br>"
-               "Graph window not exported!")
-                .arg(plot2D->objectName()));
+               "Graph window not exported!").arg(plot2D->objectName()));
         QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
         continue;
       }
@@ -6000,8 +5993,7 @@ void ApplicationWindow::exportAllGraphs() {
       QApplication::restoreOverrideCursor();
 
       QString msg = tr("A file called: <p><b>%1</b><p>already exists. "
-                       "Do you want to overwrite it?")
-                        .arg(file_name);
+                       "Do you want to overwrite it?").arg(file_name);
       QMessageBox msgBox(QMessageBox::Question,
                          tr("MantidPlot - Overwrite file?"), msg, // Mantid
                          QMessageBox::Yes | QMessageBox::YesToAll |
@@ -6241,8 +6233,7 @@ void ApplicationWindow::loadDataFileByName(QString fn) {
 void ApplicationWindow::saveProjectAs(const QString &fileName, bool compress) {
   QString fn = fileName;
   if (fileName.isEmpty()) {
-    QString filter = tr("MantidPlot project") +
-                     " (*.mantid);;"; 
+    QString filter = tr("MantidPlot project") + " (*.mantid);;";
     filter += tr("Compressed MantidPlot project") + " (*.mantid.gz)";
 
     QString selectedFilter;
@@ -6588,8 +6579,7 @@ void ApplicationWindow::exportAllTables(const QString &sep, bool colNames,
           auto result = QMessageBox::question(
               this, tr("MantidPlot - Overwrite file?"),
               tr("A file called: <p><b>%1</b><p>already exists. "
-                 "Do you want to overwrite it?")
-                  .arg(fileName),
+                 "Do you want to overwrite it?").arg(fileName),
               tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1);
 
           if (result == 1)
@@ -7780,8 +7770,7 @@ void ApplicationWindow::exportPDF() {
           this, tr("MantidPlot - Export error"), // Mantid
           tr("Could not write to file: <h4>%1</h4><p>Please verify that you "
              "have the right to write to this location or that the file is not "
-             "being used by another application!")
-              .arg(fname));
+             "being used by another application!").arg(fname));
       return;
     }
 
@@ -8180,7 +8169,7 @@ void ApplicationWindow::showCursor() {
 
 /**  Switch on the multi-peak selecting tool for fitting
  * with the Fit algorithm of multiple peaks on a single background
- */ 
+ */
 void ApplicationWindow::selectMultiPeak(bool showFitPropertyBrowser) {
   MultiLayer *plot = dynamic_cast<MultiLayer *>(activeWindow(MultiLayerWindow));
   if (!plot)
@@ -9189,8 +9178,8 @@ void ApplicationWindow::closeWindow(MdiSubWindow *window) {
   removeWindowFromLists(window);
 
   // update list view in project explorer
-  auto found =
-      lv->findItems(window->objectName(), Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
+  auto found = lv->findItems(window->objectName(),
+                             Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
 
   if (!found.isEmpty())
     lv->takeTopLevelItem(lv->indexOfTopLevelItem(found[0]));
@@ -9417,7 +9406,8 @@ void ApplicationWindow::fileMenuAboutToShow() {
   fileMenu->addSeparator();
   MdiSubWindow *t = activeWindow();
 
-  if (t && (isOfType(t, "Matrix")|| isOfType(t, "Table") || isOfType(t, "MantidMatrix"))) {
+  if (t && (isOfType(t, "Matrix") || isOfType(t, "Table") ||
+            isOfType(t, "MantidMatrix"))) {
     actionShowExportASCIIDialog->setEnabled(true);
   } else {
     actionShowExportASCIIDialog->setEnabled(false);
@@ -9461,7 +9451,8 @@ void ApplicationWindow::windowsMenuAboutToShow() {
   if (!activeWin)
     return;
 
-  if (isOfType(activeWin, "MantidMatrix") || isOfType(activeWin, "InstrumentWindow")) {
+  if (isOfType(activeWin, "MantidMatrix") ||
+      isOfType(activeWin, "InstrumentWindow")) {
     actionCopyWindow->setEnabled(false);
   } else {
     actionCopyWindow->setEnabled(true);
@@ -9472,10 +9463,10 @@ void ApplicationWindow::windowsMenuAboutToShow() {
   windowsMenu->addAction(actionResizeActiveWindow);
   if (activeWin->getFloatingWindow()) {
     windowsMenu->addAction(tr("Change to docked"), this,
-                            SLOT(changeActiveToDocked()));
+                           SLOT(changeActiveToDocked()));
   } else {
     windowsMenu->addAction(tr("Change to floating"), this,
-                            SLOT(changeActiveToFloating()));
+                           SLOT(changeActiveToFloating()));
   }
   windowsMenu->addAction(tr("&Hide Window"), this, SLOT(hideActiveWindow()));
 
@@ -9484,17 +9475,17 @@ void ApplicationWindow::windowsMenuAboutToShow() {
 // have a better solution than this right now.
 #ifdef _WIN32
   windowsMenu->addAction(getQPixmap("close_xpm"), tr("Close &Window"), this,
-                          SLOT(closeActiveWindow()), Qt::CTRL + Qt::Key_W);
+                         SLOT(closeActiveWindow()), Qt::CTRL + Qt::Key_W);
 #else
   windowsMenu->addAction(getQPixmap("close_xpm"), tr("Close &Window"), this,
-                          SLOT(closeActiveWindow()));
+                         SLOT(closeActiveWindow()));
 #endif
 
   if (n > 0 && n < 10) {
     windowsMenu->addSeparator();
     for (int i = 0; i < n; ++i) {
       auto activated = windowsMenu->addAction(windows.at(i)->objectName(), this,
-                                       SLOT(windowsMenuActivated()));
+                                              SLOT(windowsMenuActivated()));
       activated->setData(i);
       auto isChecked = currentFolder()->activeWindow() == windows.at(i);
       activated->setChecked(isChecked);
@@ -9503,14 +9494,14 @@ void ApplicationWindow::windowsMenuAboutToShow() {
     windowsMenu->addSeparator();
     for (int i = 0; i < 9; ++i) {
       auto activated = windowsMenu->addAction(windows.at(i)->objectName(), this,
-                                       SLOT(windowsMenuActivated()));
+                                              SLOT(windowsMenuActivated()));
       activated->setData(i);
       auto isChecked = activeWindow() == windows.at(i);
       activated->setChecked(isChecked);
     }
     windowsMenu->addSeparator();
     windowsMenu->addAction(tr("More windows..."), this,
-                            SLOT(showMoreWindows()));
+                           SLOT(showMoreWindows()));
   }
   reloadCustomActions();
 }
@@ -9611,22 +9602,21 @@ void ApplicationWindow::showMarkerPopupMenu() {
 
   if (g->imageMarkerSelected()) {
     markerMenu.addAction(getQPixmap("pixelProfile_xpm"),
-                          tr("&View Pixel Line profile"), this,
-                          SLOT(pixelLineProfile()));
-    markerMenu.addAction(tr("&Intensity Matrix"), this,
-                          SLOT(intensityTable()));
+                         tr("&View Pixel Line profile"), this,
+                         SLOT(pixelLineProfile()));
+    markerMenu.addAction(tr("&Intensity Matrix"), this, SLOT(intensityTable()));
     markerMenu.addSeparator();
   }
 
   if (!(g->activeTool() && dynamic_cast<PeakPickerTool *>(g->activeTool()))) {
     markerMenu.addAction(getQPixmap("cut_xpm"), tr("&Cut"), this,
-                          SLOT(cutSelection()));
+                         SLOT(cutSelection()));
     markerMenu.addAction(getQPixmap("copy_xpm"), tr("&Copy"), this,
-                          SLOT(copySelection()));
+                         SLOT(copySelection()));
   }
 
   markerMenu.addAction(getQPixmap("erase_xpm"), tr("&Delete"), this,
-                        SLOT(clearSelection()));
+                       SLOT(clearSelection()));
   markerMenu.addSeparator();
   if (g->arrowMarkerSelected())
     markerMenu.addAction(tr("&Properties..."), this, SLOT(showLineDialog()));
@@ -9650,7 +9640,7 @@ void ApplicationWindow::showMoreWindows() {
 void ApplicationWindow::windowsMenuActivated() {
   QList<MdiSubWindow *> windows = currentFolder()->windowsList();
   auto obj = sender();
-  auto action = qobject_cast<QAction*>(obj);
+  auto action = qobject_cast<QAction *>(obj);
   auto id = action->data().asInt();
   MdiSubWindow *w = windows.at(id);
   if (w) {
@@ -9872,7 +9862,7 @@ void ApplicationWindow::showListViewSelectionMenu(const QPoint &p) {
   cm.addAction(tr("&Hide All Windows"), this, SLOT(hideSelectedWindows()));
   cm.addSeparator();
   cm.addAction(tr("&Delete Selection"), this, SLOT(deleteSelectedItems()),
-                Qt::Key_F8);
+               Qt::Key_F8);
   cm.exec(lv->mapToGlobal(p));
 }
 
@@ -9936,13 +9926,13 @@ void ApplicationWindow::showWindowPopupMenu(const QPoint &p) {
     if (!hidden(w))
       cm.addAction(actionHideWindow);
     cm.addAction(getQPixmap("close_xpm"), tr("&Delete Window"), w,
-                  SLOT(close()), Qt::Key_F8);
+                 SLOT(close()), Qt::Key_F8);
     cm.addSeparator();
     cm.addAction(tr("&Rename Window"), this, SLOT(renameWindow()), Qt::Key_F2);
     cm.addAction(actionResizeWindow);
     cm.addSeparator();
     cm.addAction(getQPixmap("fileprint_xpm"), tr("&Print Window"), w,
-                  SLOT(print()));
+                 SLOT(print()));
     cm.addSeparator();
     cm.addAction(tr("&Properties..."), this, SLOT(windowProperties()));
 
@@ -10011,7 +10001,8 @@ void ApplicationWindow::showTable(int i) {
   updateWindowLists(t);
 
   t->showMaximized();
-  auto found = lv->findItems(t->objectName(), Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
+  auto found = lv->findItems(t->objectName(),
+                             Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
   if (!found.isEmpty())
     found[0]->setText(2, tr("Maximized"));
 }
@@ -10027,7 +10018,8 @@ void ApplicationWindow::showTable(const QString &curve) {
   w->table()->clearSelection();
   w->table()->selectColumn(colIndex);
   w->showMaximized();
-  auto found = lv->findItems(w->objectName(), Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
+  auto found = lv->findItems(w->objectName(),
+                             Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
   if (!found.isEmpty())
     found[0]->setText(2, tr("Maximized"));
   emit modified();
@@ -10128,19 +10120,19 @@ void ApplicationWindow::showGraphContextMenu() {
   if (lastCopiedLayer) {
     cm.addSeparator();
     cm.addAction(getQPixmap("paste_xpm"), tr("&Paste Layer"), this,
-                  SLOT(pasteSelection()));
+                 SLOT(pasteSelection()));
   } else if (d_text_copy) {
     cm.addSeparator();
     cm.addAction(getQPixmap("paste_xpm"), tr("&Paste Text"), plot,
-                  SIGNAL(pasteMarker()));
+                 SIGNAL(pasteMarker()));
   } else if (d_arrow_copy) {
     cm.addSeparator();
     cm.addAction(getQPixmap("paste_xpm"), tr("&Paste Line/Arrow"), plot,
-                  SIGNAL(pasteMarker()));
+                 SIGNAL(pasteMarker()));
   } else if (d_image_copy) {
     cm.addSeparator();
     cm.addAction(getQPixmap("paste_xpm"), tr("&Paste Image"), plot,
-                  SIGNAL(pasteMarker()));
+                 SIGNAL(pasteMarker()));
   }
   cm.addSeparator();
 
@@ -10300,21 +10292,21 @@ void ApplicationWindow::showWindowContextMenu() {
       cm.addAction(getQPixmap("copy_xpm"), tr("&Copy"), t,
                    SLOT(copySelection()));
       cm.addAction(getQPixmap("paste_xpm"), tr("&Paste"), t,
-                    SLOT(pasteSelection()));
+                   SLOT(pasteSelection()));
       cm.addSeparator();
       cm.addAction(getQPixmap("insert_row_xpm"), tr("&Insert Row"), t,
-                    SLOT(insertRow()));
+                   SLOT(insertRow()));
       cm.addAction(getQPixmap("insert_column_xpm"), tr("&Insert Column"), t,
-                    SLOT(insertColumn()));
+                   SLOT(insertColumn()));
       if (t->numSelectedRows() > 0)
         cm.addAction(getQPixmap("delete_row_xpm"), tr("&Delete Rows"), t,
-                      SLOT(deleteSelectedRows()));
+                     SLOT(deleteSelectedRows()));
       else if (t->numSelectedColumns() > 0)
         cm.addAction(getQPixmap("delete_column_xpm"), tr("&Delete Columns"), t,
-                      SLOT(deleteSelectedColumns()));
+                     SLOT(deleteSelectedColumns()));
 
       cm.addAction(getQPixmap("erase_xpm"), tr("Clea&r"), t,
-                    SLOT(clearSelection()));
+                   SLOT(clearSelection()));
     } else if (t->viewType() == Matrix::ImageView) {
       cm.addAction(actionImportImage);
       cm.addAction(actionExportMatrix);
@@ -10492,8 +10484,7 @@ void ApplicationWindow::showHelp() {
     QMessageBox::critical(
         this, tr("MantidPlot - Help Profile Not Found!"), // Mantid
         tr("The assistant could not start because the file <b>%1</b> was not "
-           "found in the help file directory!")
-                .arg("qtiplot.adp") +
+           "found in the help file directory!").arg("qtiplot.adp") +
             "<br>" +
             tr("This file is provided with the MantidPlot manual which can be "
                "downloaded from the following internet address:") +
@@ -10502,7 +10493,6 @@ void ApplicationWindow::showHelp() {
             "www.mantidproject.org/MantidPlot:_Help</a></p>");
     return;
   }
-
 }
 
 void ApplicationWindow::showPlotWizard() {
@@ -11197,11 +11187,9 @@ void ApplicationWindow::pixelLineProfile() {
     return;
 
   bool ok;
-  auto res = QInputDialog::getInt(this,
-                                 tr("MantidPlot - Set the number of pixels to average"),
-                                 tr("Number of averaged pixels"),
-                                 1, 1, 2000, 2,
-                                 &ok);
+  auto res = QInputDialog::getInt(
+      this, tr("MantidPlot - Set the number of pixels to average"),
+      tr("Number of averaged pixels"), 1, 1, 2000, 2, &ok);
   if (!ok)
     return;
 
@@ -14023,9 +14011,7 @@ void ApplicationWindow::disregardCol() {
 void ApplicationWindow::showHomePage() {
   QDesktopServices::openUrl(QUrl("http://www.mantidproject.org"));
 }
-void ApplicationWindow::showMantidConcepts() {
-  HelpWindow::showConcept(this);
-}
+void ApplicationWindow::showMantidConcepts() { HelpWindow::showConcept(this); }
 void ApplicationWindow::showalgorithmDescriptions() {
   HelpWindow::showAlgorithm(this);
 }
@@ -14401,7 +14387,8 @@ void ApplicationWindow::saveProjectFile(Folder *folder, const QString &fn,
   text += saveProjectFolder(folder, windowCount, true);
 
   text.prepend("<windows>\t" + QString::number(windowCount) + "\n");
-  text.prepend("<scripting-lang>\t" + QString(scriptingEnv()->objectName()) + "\n");
+  text.prepend("<scripting-lang>\t" + QString(scriptingEnv()->objectName()) +
+               "\n");
   text.prepend("MantidPlot " + QString::number(maj_version) + "." +
                QString::number(min_version) + "." +
                QString::number(patch_version) + " project file\n");
@@ -14445,8 +14432,8 @@ void ApplicationWindow::showFolderPopupMenu(const QPoint &p) {
   showFolderPopupMenu(item, p, true);
 }
 
-void ApplicationWindow::showFolderPopupMenu(QTreeWidgetItem *it, const QPoint &p,
-                                            bool fromFolders) {
+void ApplicationWindow::showFolderPopupMenu(QTreeWidgetItem *it,
+                                            const QPoint &p, bool fromFolders) {
 
   QMenu cm(this);
   QMenu window(this);
@@ -14556,7 +14543,6 @@ void ApplicationWindow::hideAllFolderWindows() {
 
   if ((currentFolder()->children()).isEmpty())
     return;
-
 }
 
 void ApplicationWindow::projectProperties() {
@@ -14749,7 +14735,8 @@ void ApplicationWindow::folderItemDoubleClicked(QTreeWidgetItem *it) {
   folders->setCurrentItem(item);
 }
 
-void ApplicationWindow::folderItemChanged(QTreeWidgetItem *it, QTreeWidgetItem *) {
+void ApplicationWindow::folderItemChanged(QTreeWidgetItem *it,
+                                          QTreeWidgetItem *) {
   if (!it)
     return;
 
@@ -14984,8 +14971,8 @@ void ApplicationWindow::addFolderListViewItem(Folder *f) {
 }
 
 void ApplicationWindow::find(const QString &s, bool windowNames, bool labels,
-                             bool , bool caseSensitive,
-                             bool partialMatch, bool) {
+                             bool, bool caseSensitive, bool partialMatch,
+                             bool) {
   if (windowNames || labels) {
     MdiSubWindow *w = currentFolder()->findWindow(s, windowNames, labels,
                                                   caseSensitive, partialMatch);
@@ -15056,7 +15043,8 @@ void ApplicationWindow::goToRow() {
   if (!w)
     return;
 
-  if (w->inherits("Table") || QString(w->metaObject()->className()) == "Matrix") {
+  if (w->inherits("Table") ||
+      QString(w->metaObject()->className()) == "Matrix") {
     bool ok;
     int row = QInputDialog::getInteger(
         this, tr("MantidPlot - Enter row number"), tr("Row"), // Mantid
@@ -15081,7 +15069,8 @@ void ApplicationWindow::goToColumn() {
   if (!w)
     return;
 
-  if (w->inherits("Table") || QString(w->metaObject()->className()) == "Matrix") {
+  if (w->inherits("Table") ||
+      QString(w->metaObject()->className()) == "Matrix") {
     bool ok;
     int col = QInputDialog::getInteger(
         this, tr("MantidPlot - Enter column number"), tr("Column"), // Mantid
@@ -15549,8 +15538,7 @@ void ApplicationWindow::scriptsDirPathChanged(const QString &path) {
   scriptsDirPath = path;
 }
 
-void ApplicationWindow::makeToolbarsMenu()
-{
+void ApplicationWindow::makeToolbarsMenu() {
   // cppcheck-suppress publicAllocationError
   actionFileTools = new QAction(standardTools->windowTitle(), toolbarsMenu);
   actionFileTools->setCheckable(true);
@@ -15593,7 +15581,8 @@ void ApplicationWindow::setToolbars() {
   plotTools->setVisible(d_plot_tool_bar);
   displayBar->setVisible(d_display_tool_bar);
   formatToolBar->setVisible(d_format_tool_bar);
-  plotTools->setEnabled(w && QString(w->metaObject()->className()) == "MultiLayer");
+  plotTools->setEnabled(w &&
+                        QString(w->metaObject()->className()) == "MultiLayer");
 }
 
 void ApplicationWindow::saveFitFunctions(const QStringList &lst) {
@@ -16054,7 +16043,8 @@ void ApplicationWindow::addUserMenuAction(const QString &parentMenu,
       return;
   }
 
-  QAction *scriptAction = new QAction(tr(niceName.toAscii().constData()), topMenu);
+  QAction *scriptAction =
+      new QAction(tr(niceName.toAscii().constData()), topMenu);
   scriptAction->setData(itemData);
   topMenu->addAction(scriptAction);
   d_user_actions.append(scriptAction);
@@ -16318,14 +16308,14 @@ void ApplicationWindow::CatalogLogin() {
 }
 
 void ApplicationWindow::CatalogSearch() {
-    // Only one ICAT GUI will appear, and that the previous one will be
-    // overridden.
-    // E.g. if a user opens the ICAT GUI without being logged into ICAT they
-    // will need to
-    // login in and then click "Search" again.
-    catalogSearch.reset(new MantidQt::MantidWidgets::CatalogSearch());
-    catalogSearch->show();
-    catalogSearch->raise();
+  // Only one ICAT GUI will appear, and that the previous one will be
+  // overridden.
+  // E.g. if a user opens the ICAT GUI without being logged into ICAT they
+  // will need to
+  // login in and then click "Search" again.
+  catalogSearch.reset(new MantidQt::MantidWidgets::CatalogSearch());
+  catalogSearch->show();
+  catalogSearch->raise();
 }
 
 void ApplicationWindow::CatalogPublish() {
@@ -16655,8 +16645,8 @@ void ApplicationWindow::detachMdiSubwindow(MdiSubWindow *w) {
     currentFolder()->removeWindow(w);
   }
   removeWindowFromLists(w);
-  auto found = lv->findItems(
-      w->objectName(), Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
+  auto found = lv->findItems(w->objectName(),
+                             Qt::MatchExactly | Qt::MatchCaseSensitive, 0);
   if (!found.isEmpty())
     lv->takeTopLevelItem(lv->indexOfTopLevelItem(found[0]));
 
@@ -17016,8 +17006,7 @@ QString ApplicationWindow::saveProjectFolder(Folder *folder, int &windowCount,
   return text;
 }
 
-bool ApplicationWindow::isOfType(const QObject* obj, const char* toCompare) const {
+bool ApplicationWindow::isOfType(const QObject *obj,
+                                 const char *toCompare) const {
   return strcmp(obj->metaObject()->className(), toCompare) == 0;
 }
-
-
diff --git a/MantidPlot/src/ApplicationWindow.h b/MantidPlot/src/ApplicationWindow.h
index 57fb3ffeee58b09be64d9dceb2cf84b2755ebde1..c196e0162b2f896c8051283b5a03927b56a5ae4c 100644
--- a/MantidPlot/src/ApplicationWindow.h
+++ b/MantidPlot/src/ApplicationWindow.h
@@ -64,7 +64,7 @@ class QToolButton;
 class QShortcut;
 class QMenu;
 class QToolBar;
-//class QAssistantClient;
+// class QAssistantClient;
 class QLocale;
 class QMdiArea;
 class QSignalMapper;
@@ -94,79 +94,97 @@ class FloatingWindow;
 class MantidTable;
 class TiledWindow;
 
-// On Mac (and Ubuntu 11 Unity) the menubar must be shared between the main window and other floating windows.
+// On Mac (and Ubuntu 11 Unity) the menubar must be shared between the main
+// window and other floating windows.
 #ifdef Q_OS_MAC
-  #define SHARED_MENUBAR
+#define SHARED_MENUBAR
 #endif
 
-namespace MantidQt
-{
-  namespace API
-  {
-    class Message;
-  }
-  namespace MantidWidgets
-  {
-    class FitPropertyBrowser;
-    class MessageDisplay;
-  }
+namespace MantidQt {
+namespace API {
+class Message;
 }
-//Mantid
+namespace MantidWidgets {
+class FitPropertyBrowser;
+class MessageDisplay;
+}
+}
+// Mantid
 class MantidUI;
 class ScriptingWindow;
 
 /**
 * \brief MantidPlot's main window.
 *
-* This class contains the main part of the user interface as well as the central project management facilities.
+* This class contains the main part of the user interface as well as the central
+*project management facilities.
 *
-* It manages all MdiSubWindow MDI Windows in a project, knows about their organization in Folder objects
-* and contains the parts of the project explorer not implemented in Folder, FolderListItem or FolderListView.
+* It manages all MdiSubWindow MDI Windows in a project, knows about their
+*organization in Folder objects
+* and contains the parts of the project explorer not implemented in Folder,
+*FolderListItem or FolderListView.
 *
-* Furthermore, it is responsible for displaying most MDI Windows' context menus and opening all sorts of dialogs.
+* Furthermore, it is responsible for displaying most MDI Windows' context menus
+*and opening all sorts of dialogs.
 */
-class ApplicationWindow: public QMainWindow, public Scripted
-{
+class ApplicationWindow : public QMainWindow, public Scripted {
   Q_OBJECT
 public:
-  ApplicationWindow(bool factorySettings, const QStringList& args);
+  ApplicationWindow(bool factorySettings, const QStringList &args);
   explicit ApplicationWindow(bool factorySettings = false);
   ~ApplicationWindow() override;
 
-  enum ShowWindowsPolicy{HideAll, ActiveFolder, SubFolders};
-  enum WindowType{NoWindow, TableWindow, MatrixWindow, MultiLayerWindow, NoteWindow, Plot3DWindow};
-  enum MatrixToTableConversion{Direct, XYZ, YXZ};
-  enum EndLineChar{LF=0, CRLF=1, CR=2};
-  enum Analysis{NoAnalysis, Integrate, Diff, FitLinear, FitGauss, FitLorentz, FitSigmoidal};
+  enum ShowWindowsPolicy { HideAll, ActiveFolder, SubFolders };
+  enum WindowType {
+    NoWindow,
+    TableWindow,
+    MatrixWindow,
+    MultiLayerWindow,
+    NoteWindow,
+    Plot3DWindow
+  };
+  enum MatrixToTableConversion { Direct, XYZ, YXZ };
+  enum EndLineChar { LF = 0, CRLF = 1, CR = 2 };
+  enum Analysis {
+    NoAnalysis,
+    Integrate,
+    Diff,
+    FitLinear,
+    FitGauss,
+    FitLorentz,
+    FitSigmoidal
+  };
 
   FolderListView *lv, *folders;
   QDockWidget *logWindow;
 
   /** Generates a new unique name starting with string /param name.
   You can force the output to be a name different from /param name,
-  even if 'name' is not used in the project, by setting /param increment = true (the default)
+  even if 'name' is not used in the project, by setting /param increment = true
+  (the default)
   */
-  QString generateUniqueName(const QString& name, bool increment = true);
-  void saveFitFunctions(const QStringList& lst);
+  QString generateUniqueName(const QString &name, bool increment = true);
+  void saveFitFunctions(const QStringList &lst);
 
   //! \name User custom actions
   //@{
   void loadCustomActions();
   void reloadCustomActions();
   void removeCustomAction(QAction *);
-  void addCustomAction(QAction *, const QString& parentName, int index = -1);
-  QList<QAction *> customActionsList(){return d_user_actions;};
+  void addCustomAction(QAction *, const QString &parentName, int index = -1);
+  QList<QAction *> customActionsList() { return d_user_actions; };
   QList<QMenu *> customizableMenusList();
 
-
   //------ Mantid-------
-  void addUserMenu(const QString &);  //Mantid
-  void addUserMenuAction(const QString & parentMenu, const QString & itemName, const QString & itemData); //Mantid
-  void removeUserMenu(const QString &);  //Mantid
-  void removeUserMenuAction(const QString & menu, const QString & action); //Mantid
-  const QList<QMenu*> & getCustomMenus() const; //Mantid
-  ScriptingWindow* getScriptWindowHandle() { return scriptingWindow; }
-  bool getMenuSettingsFlag(const QString & menu_item);
+  void addUserMenu(const QString &); // Mantid
+  void addUserMenuAction(const QString &parentMenu, const QString &itemName,
+                         const QString &itemData); // Mantid
+  void removeUserMenu(const QString &);            // Mantid
+  void removeUserMenuAction(const QString &menu,
+                            const QString &action); // Mantid
+  const QList<QMenu *> &getCustomMenus() const;     // Mantid
+  ScriptingWindow *getScriptWindowHandle() { return scriptingWindow; }
+  bool getMenuSettingsFlag(const QString &menu_item);
 
   void setExitCode(int code);
   int getExitCode();
@@ -180,18 +198,20 @@ public:
   void addMdiSubWindow(MdiSubWindow *w, bool showNormal = true);
   void addMdiSubWindow(MdiSubWindow *w, bool showFloating, bool showNormal);
 
-  int matrixUndoStackSize(){return d_matrix_undo_stack_size;};
+  int matrixUndoStackSize() { return d_matrix_undo_stack_size; };
   void setMatrixUndoStackSize(int size);
 
   // Check if delete workspace prompt is enabled
   bool isDeleteWorkspacePromptEnabled();
 
   QString endOfLine();
-  bool autoUpdateTableValues(){return d_auto_update_table_values;};
+  bool autoUpdateTableValues() { return d_auto_update_table_values; };
   void setAutoUpdateTableValues(bool on = true);
-  // enables File->Save->Nexus action in the main menu and sets the parameter wsName as input workspace for save alg.
-  void enableSaveNexus(const QString& wsName);
-  // disables File->Save-Nexus action in the main menu. Useful when de-selecting workspaces
+  // enables File->Save->Nexus action in the main menu and sets the parameter
+  // wsName as input workspace for save alg.
+  void enableSaveNexus(const QString &wsName);
+  // disables File->Save-Nexus action in the main menu. Useful when de-selecting
+  // workspaces
   void disableSaveNexus();
 
 public slots:
@@ -199,34 +219,42 @@ public slots:
   //@{
   void exitWithPresetCode();
   void open();
-  ApplicationWindow* open(const QString& fn, bool factorySettings = false, bool newProject = true);
-  ApplicationWindow* openProject(const QString& fn, const int fileVersion);
-  void openProjectFolder(std::string lines, const int fileVersion, bool isTopLevel = false);
-  ApplicationWindow* importOPJ(const QString& fn, bool factorySettings = false, bool newProject = true);
+  ApplicationWindow *open(const QString &fn, bool factorySettings = false,
+                          bool newProject = true);
+  ApplicationWindow *openProject(const QString &fn, const int fileVersion);
+  void openProjectFolder(std::string lines, const int fileVersion,
+                         bool isTopLevel = false);
+  ApplicationWindow *importOPJ(const QString &fn, bool factorySettings = false,
+                               bool newProject = true);
   /// Load mantid data files using generic load algorithm, opening user dialog
   void loadDataFile();
   /// Load mantid data files (generic load algorithm)
   void loadDataFileByName(QString fn);
   /// Open from the list of recent files
-  void openRecentFile(QAction* action);
+  void openRecentFile(QAction *action);
 
   /**
   * \brief Create a new project from a data file.
   *
-  * @param fn :: is read as a data file with the default column separator (as set by the user)
+  * @param fn :: is read as a data file with the default column separator (as
+  *set by the user)
   * and inserted as a table into a new, empty project.
   * This table is then plotted with the Graph::LineSymbols style.
   */
-  ApplicationWindow * plotFile(const QString& fn);
+  ApplicationWindow *plotFile(const QString &fn);
 
   /// Runs a script from a file. Mainly useful for automatically running scripts
-  void executeScriptFile(const QString & filename, const Script::ExecutionMode execMode);
+  void executeScriptFile(const QString &filename,
+                         const Script::ExecutionMode execMode);
   /// Slot to connect the script execution success
-  void onScriptExecuteSuccess(const QString & message);
+  void onScriptExecuteSuccess(const QString &message);
   /// Slot to connect the script execution errors to
-  void onScriptExecuteError(const QString & message, const QString & scriptName, int lineNumber);
-  /// Runs an arbitrary lump of python code, return true/false on success/failure.
-  bool runPythonScript(const QString & code, bool async = false, bool quiet=false, bool redirect=true);
+  void onScriptExecuteError(const QString &message, const QString &scriptName,
+                            int lineNumber);
+  /// Runs an arbitrary lump of python code, return true/false on
+  /// success/failure.
+  bool runPythonScript(const QString &code, bool async = false,
+                       bool quiet = false, bool redirect = true);
 
   QList<MdiSubWindow *> windowsList() const;
   QList<MdiSubWindow *> getAllWindows() const;
@@ -236,17 +264,20 @@ public slots:
   */
   void cascade();
 
-  void saveProjectAs(const QString& fileName = QString(), bool compress = false);
+  void saveProjectAs(const QString &fileName = QString(),
+                     bool compress = false);
   bool saveProject(bool compress = false);
 
   /// Serialises a project folder into its string project file representation
-  QString saveProjectFolder(Folder* folder, int &windowCount, bool isTopLevel = false);
+  QString saveProjectFolder(Folder *folder, int &windowCount,
+                            bool isTopLevel = false);
 
   //! Set the project status to modifed
   void modifiedProject();
   //! Set the project status to saved (not modified)
   void savedProject();
-  //! Set the project status to modified and save 'w' as the last modified widget
+  //! Set the project status to modified and save 'w' as the last modified
+  // widget
   void modifiedProject(MdiSubWindow *w);
   //@}
 
@@ -255,42 +286,45 @@ public slots:
   void readSettings();
   void saveSettings();
   void setSaveSettings(bool autoSaving, int min);
-  void changeAppStyle(const QString& s);
-  void changeAppFont(const QFont& f);
+  void changeAppStyle(const QString &s);
+  void changeAppFont(const QFont &f);
   void updateAppFonts();
-  void setAppColors(const QColor& wc,const QColor& pc,const QColor& tpc, bool force = false);
+  void setAppColors(const QColor &wc, const QColor &pc, const QColor &tpc,
+                    bool force = false);
 
-  QLocale locale(){return d_locale;};
-  void setLocale(const QLocale& l){d_locale = l;};
+  QLocale locale() { return d_locale; };
+  void setLocale(const QLocale &l) { d_locale = l; };
 
   void initWindow();
   //@}
 
   //! \name Multilayer Plots
   //@{
-  MultiLayer* multilayerPlot(int c, int r, int style);
-  MultiLayer* multilayerPlot(Table* w, const QStringList& colList, int style, int startRow = 0, int endRow = -1);
+  MultiLayer *multilayerPlot(int c, int r, int style);
+  MultiLayer *multilayerPlot(Table *w, const QStringList &colList, int style,
+                             int startRow = 0, int endRow = -1);
   //! used when restoring a plot from a project file
-  MultiLayer* multilayerPlot(const QString& caption, int layers = 1, int rows = 1, int cols = 1);
+  MultiLayer *multilayerPlot(const QString &caption, int layers = 1,
+                             int rows = 1, int cols = 1);
   //! used by the plot wizard
-  MultiLayer* multilayerPlot(const QStringList& colList);
-  MultiLayer* waterfallPlot();
-  MultiLayer* waterfallPlot(Table *t, const QStringList& list);
+  MultiLayer *multilayerPlot(const QStringList &colList);
+  MultiLayer *waterfallPlot();
+  MultiLayer *waterfallPlot(Table *t, const QStringList &list);
   void connectMultilayerPlot(MultiLayer *g);
   void addLayer();
   void deleteLayer();
 
   //! Creates a new spectrogram graph
-  MultiLayer* plotSpectrogram(Matrix *m, Graph::CurveType type);
-  MultiLayer* plotGrayScale(Matrix *m = 0);
-  MultiLayer* plotContour(Matrix *m = 0);
-  MultiLayer* plotColorMap(Matrix *m = 0);
-  MultiLayer* plotImage(Matrix *m = 0);
-  MultiLayer* plotNoContourColorMap(Matrix *m = 0);
+  MultiLayer *plotSpectrogram(Matrix *m, Graph::CurveType type);
+  MultiLayer *plotGrayScale(Matrix *m = 0);
+  MultiLayer *plotContour(Matrix *m = 0);
+  MultiLayer *plotColorMap(Matrix *m = 0);
+  MultiLayer *plotImage(Matrix *m = 0);
+  MultiLayer *plotNoContourColorMap(Matrix *m = 0);
 
   //! Rearrange the layersin order to fit to the size of the plot window
   void autoArrangeLayers();
-  void initMultilayerPlot(MultiLayer* g, const QString& name = QString());
+  void initMultilayerPlot(MultiLayer *g, const QString &name = QString());
   void polishGraph(Graph *g, int style);
   void plot2VerticalLayers();
   void plot2HorizontalLayers();
@@ -301,24 +335,29 @@ public slots:
 
   //! \name 3D Data Plots
   //@{
-  Graph3D* newPlot3D();
-  Graph3D* openMatrixPlot3D(const QString& caption, const QString& matrix_name,
-    double xl,double xr,double yl,double yr,double zl,double zr);
-  Graph3D* plotXYZ(Table* table,const QString& zColName, int type);
-  //when reading from .qti file
-  Graph3D* dataPlot3D(const QString& caption,const QString& formula,
-    double xl, double xr, double yl, double yr, double zl, double zr);
-  Graph3D* openPlotXYZ(const QString& caption,const QString& formula,
-    double xl, double xr, double yl, double yr, double zl, double zr);
+  Graph3D *newPlot3D();
+  Graph3D *openMatrixPlot3D(const QString &caption, const QString &matrix_name,
+                            double xl, double xr, double yl, double yr,
+                            double zl, double zr);
+  Graph3D *plotXYZ(Table *table, const QString &zColName, int type);
+  // when reading from .qti file
+  Graph3D *dataPlot3D(const QString &caption, const QString &formula, double xl,
+                      double xr, double yl, double yr, double zl, double zr);
+  Graph3D *openPlotXYZ(const QString &caption, const QString &formula,
+                       double xl, double xr, double yl, double yr, double zl,
+                       double zr);
   //@}
 
   //! \name Surface Plots
   //@{
-  Graph3D* plotSurface(const QString& formula, double xl, double xr,
-    double yl, double yr, double zl, double zr, size_t columns = 40, size_t rows = 30);
-  Graph3D* plotParametricSurface(const QString& xFormula, const QString& yFormula,
-    const QString& zFormula, double ul, double ur, double vl, double vr,
-    int columns, int rows, bool uPeriodic, bool vPeriodic);
+  Graph3D *plotSurface(const QString &formula, double xl, double xr, double yl,
+                       double yr, double zl, double zr, size_t columns = 40,
+                       size_t rows = 30);
+  Graph3D *plotParametricSurface(const QString &xFormula,
+                                 const QString &yFormula,
+                                 const QString &zFormula, double ul, double ur,
+                                 double vl, double vr, int columns, int rows,
+                                 bool uPeriodic, bool vPeriodic);
 
   void connectSurfacePlot(Graph3D *plot);
   void newSurfacePlot();
@@ -327,12 +366,12 @@ public slots:
   void updateMatrixPlots(MdiSubWindow *);
   void add3DData();
   void change3DData();
-  void change3DData(const QString& colName);
+  void change3DData(const QString &colName);
   void change3DMatrix();
-  void change3DMatrix(const QString& matrix_name);
-  void insertNew3DData(const QString& colName);
+  void change3DMatrix(const QString &matrix_name);
+  void insertNew3DData(const QString &colName);
   void add3DMatrixPlot();
-  void insert3DMatrixPlot(const QString& matrix_name);
+  void insert3DMatrixPlot(const QString &matrix_name);
   void initPlot3D(Graph3D *plot);
   void customPlot3D(Graph3D *plot);
   void setPlot3DOptions();
@@ -342,7 +381,7 @@ public slots:
   void plot3DPolygons();
   void plot3DWireSurface();
 
-  Graph3D* plot3DMatrix(Matrix *m = 0, int style = 5);
+  Graph3D *plot3DMatrix(Matrix *m = 0, int style = 5);
 
   void plot3DRibbon();
   void plot3DScatter();
@@ -352,32 +391,34 @@ public slots:
 
   //! \name User-defined Functions
   //@{
-  MultiLayer * newFunctionPlot(QStringList &formulas, double start, double end, int points = 100, const QString& var = "x", int type = 0);
+  MultiLayer *newFunctionPlot(QStringList &formulas, double start, double end,
+                              int points = 100, const QString &var = "x",
+                              int type = 0);
 
-  FunctionDialog* functionDialog(Graph* g = NULL);
-  FunctionDialog* showFunctionDialog();
-  FunctionDialog* showFunctionDialog(Graph * g, int curve);
+  FunctionDialog *functionDialog(Graph *g = NULL);
+  FunctionDialog *showFunctionDialog();
+  FunctionDialog *showFunctionDialog(Graph *g, int curve);
   void addFunctionCurve();
   void clearSurfaceFunctionsList();
   void clearParamFunctionsList();
   void clearPolarFunctionsList();
   void updateFunctionLists(int type, QStringList &formulas);
-  void updateSurfaceFuncList(const QString& s);
+  void updateSurfaceFuncList(const QString &s);
   //@}
 
   //! \name Matrices
   //@{
   //! Creates a new empty matrix
-  Matrix* newMatrix(int rows = 32, int columns = 32);
+  Matrix *newMatrix(int rows = 32, int columns = 32);
   //! To be used when opening a project file only!
-  Matrix* newMatrix(const QString& caption, int r, int c);
-  Matrix* matrix(const QString& name);
-  Matrix* convertTableToMatrix();
+  Matrix *newMatrix(const QString &caption, int r, int c);
+  Matrix *matrix(const QString &name);
+  Matrix *convertTableToMatrix();
   void convertTableToWorkspace();
   void convertTableToMatrixWorkspace();
-  MantidTable* convertTableToTableWorkspace(Table* t);
-  Matrix* tableToMatrix(Table* t);
-  void initMatrix(Matrix* m, const QString& caption);
+  MantidTable *convertTableToTableWorkspace(Table *t);
+  Matrix *tableToMatrix(Table *t);
+  void initMatrix(Matrix *m, const QString &caption);
   void transposeMatrix();
   void invertMatrix();
   void matrixDeterminant();
@@ -399,14 +440,16 @@ public slots:
   //! \name Tables
   //@{
   //! Creates an empty table
-  Table* newTable();
+  Table *newTable();
 
   //! Used when loading a table from a project file
-  Table* newTable(const QString& caption,int r, int c);
-  Table* newTable(int r, int c, const QString& name = QString(),const QString& legend = QString());
-  Table* newTable(const QString& caption, int r, int c, const QString& text);
+  Table *newTable(const QString &caption, int r, int c);
+  Table *newTable(int r, int c, const QString &name = QString(),
+                  const QString &legend = QString());
+  Table *newTable(const QString &caption, int r, int c, const QString &text);
   /**
-  * \brief Create a Table which is initially hidden; used to return the result of an analysis operation.
+  * \brief Create a Table which is initially hidden; used to return the result
+  *of an analysis operation.
   *
   * @param name :: window name (compare MdiSubWindow::MdiSubWindow)
   * @param label :: window label (compare MdiSubWindow::MdiSubWindow)
@@ -414,50 +457,63 @@ public slots:
   * @param c :: number of columns
   * @param text :: tab/newline - seperated initial content; may be empty
   */
-  Table* newHiddenTable(const QString& name, const QString& label, int r, int c, const QString& text=QString());
-  Table* table(const QString& name);
-  Table* convertMatrixToTableDirect();
-  Table* convertMatrixToTableXYZ();
-  Table* convertMatrixToTableYXZ();
-  Table* matrixToTable(Matrix* m, MatrixToTableConversion conversionType = Direct);
+  Table *newHiddenTable(const QString &name, const QString &label, int r, int c,
+                        const QString &text = QString());
+  Table *table(const QString &name);
+  Table *convertMatrixToTableDirect();
+  Table *convertMatrixToTableXYZ();
+  Table *convertMatrixToTableYXZ();
+  Table *matrixToTable(Matrix *m,
+                       MatrixToTableConversion conversionType = Direct);
   QList<MdiSubWindow *> tableList();
   //! Returns true if the project contains tables
   bool hasTable();
   //! Returns a list containing the names of all tables in the project
   QStringList tableNames();
 
-  void connectTable(Table* w);
-  void initTable(Table* w, const QString& caption);
-  void customTable(Table* w);
-  void customizeTables(const QColor& bgColor,const QColor& textColor,
-    const QColor& headerColor,const QFont& textFont,
-    const QFont& headerFont, bool showComments);
+  void connectTable(Table *w);
+  void initTable(Table *w, const QString &caption);
+  void customTable(Table *w);
+  void customizeTables(const QColor &bgColor, const QColor &textColor,
+                       const QColor &headerColor, const QFont &textFont,
+                       const QFont &headerFont, bool showComments);
   /// Turn on/off auto-update of curves from table
   void setUpdateCurvesFromTable(Table *table, bool on);
 
   void importASCII();
-  void importASCII(const QStringList& files, int import_mode, const QString& local_column_separator, int local_ignored_lines, bool local_rename_columns,
-    bool local_strip_spaces, bool local_simplify_spaces, bool local_import_comments, bool update_dec_separators,
-    QLocale local_separators, const QString& local_comment_string, bool import_read_only, int endLineChar,const QString& sepforloadAscii);
-  void exportAllTables(const QString& sep, bool colNames, bool colComments, bool expSelection);
-  void exportASCII(const QString& tableName, const QString& sep, bool colNames, bool colComments, bool expSelection);
+  void importASCII(const QStringList &files, int import_mode,
+                   const QString &local_column_separator,
+                   int local_ignored_lines, bool local_rename_columns,
+                   bool local_strip_spaces, bool local_simplify_spaces,
+                   bool local_import_comments, bool update_dec_separators,
+                   QLocale local_separators,
+                   const QString &local_comment_string, bool import_read_only,
+                   int endLineChar, const QString &sepforloadAscii);
+  void exportAllTables(const QString &sep, bool colNames, bool colComments,
+                       bool expSelection);
+  void exportASCII(const QString &tableName, const QString &sep, bool colNames,
+                   bool colComments, bool expSelection);
 
   //! recalculate selected cells of current table
   void recalculateTable();
 
   TableStatistics *newTableStatistics(Table *base, int type, QList<int>,
-    const QString &caption=QString::null);
+                                      const QString &caption = QString::null);
   //@}
 
   //! \name Graphs
   //@{
-  void setPreferences(Graph* g);
-  void setSpectrogramTickStyle(Graph* g);
-  void setGraphDefaultSettings(bool autoscale,bool scaleFonts,bool resizeLayers,bool antialiasing, bool fixedAspectRatio);
-  void setLegendDefaultSettings(int frame, const QFont& font,
-    const QColor& textCol, const QColor& backgroundCol);
-  void setArrowDefaultSettings(double lineWidth,  const QColor& c, Qt::PenStyle style,
-    int headLength, int headAngle, bool fillHead);
+  void setPreferences(Graph *g);
+  void setSpectrogramTickStyle(Graph *g);
+  void setGraphDefaultSettings(bool autoscale, bool scaleFonts,
+                               bool resizeLayers, bool antialiasing,
+                               bool fixedAspectRatio);
+  void setLegendDefaultSettings(int frame, const QFont &font,
+                                const QColor &textCol,
+                                const QColor &backgroundCol);
+  void setArrowDefaultSettings(double lineWidth, const QColor &c,
+                               Qt::PenStyle style, int headLength,
+                               int headAngle, bool fillHead);
 
   void plotL();
   void plotP();
@@ -470,22 +526,25 @@ public slots:
   void plotHorSteps();
   void plotSpline();
   void plotVerticalDropLines();
-  MultiLayer* plotHistogram();
-  MultiLayer* plotHistogram(Matrix *m);
+  MultiLayer *plotHistogram();
+  MultiLayer *plotHistogram(Matrix *m);
   void plotVectXYXY();
   void plotVectXYAM();
   void plotBoxDiagram();
 
   /// Create a stem plot from a table and return a string representation of it
-  QString stemPlot(Table *t = 0, const QString& colName = QString(), int power = 0, int startRow = 0, int endRow = -1);
+  QString stemPlot(Table *t = 0, const QString &colName = QString(),
+                   int power = 0, int startRow = 0, int endRow = -1);
   Note *newStemPlot();
 
-  //! Check whether a table is valid for a 3D plot and display an appropriate error if not
+  //! Check whether a table is valid for a 3D plot and display an appropriate
+  // error if not
   bool validFor3DPlot(Table *table);
-  //! Check whether a table is valid for a 2D plot and display an appropriate error if not
+  //! Check whether a table is valid for a 2D plot and display an appropriate
+  // error if not
   bool validFor2DPlot(Table *table);
   //! Generate a new 2D graph
-  MultiLayer* generate2DGraph(Graph::CurveType type);
+  MultiLayer *generate2DGraph(Graph::CurveType type);
   //@}
 
   //! \name Image Analysis
@@ -493,8 +552,8 @@ public slots:
   void intensityTable();
   void pixelLineProfile();
   void loadImage();
-  void loadImage(const QString& fn);
-  Matrix* importImage(const QString& = QString());
+  void loadImage(const QString &fn);
+  Matrix *importImage(const QString & = QString());
   //@}
 
   //! \name Script Repository Interaction
@@ -518,7 +577,7 @@ public slots:
 
   //! \name MDI Windows
   //@{
-  MdiSubWindow* clone(MdiSubWindow* w = 0);
+  MdiSubWindow *clone(MdiSubWindow *w = 0);
   void rename();
   void renameWindow();
 
@@ -528,61 +587,62 @@ public slots:
   //!  Checks weather the new window name is valid and modifies the name.
   bool setWindowName(MdiSubWindow *w, const QString &text);
 
-  void maximizeWindow(QTreeWidgetItem * lbi = 0);
-  void activateWindow(QTreeWidgetItem * lbi);
+  void maximizeWindow(QTreeWidgetItem *lbi = 0);
+  void activateWindow(QTreeWidgetItem *lbi);
   void maximizeWindow(MdiSubWindow *w);
   void minimizeWindow(MdiSubWindow *w = 0);
   //! Changes the geometry of the active MDI window
   void setWindowGeometry(int x, int y, int w, int h);
 
-  void updateWindowStatus(MdiSubWindow* );
+  void updateWindowStatus(MdiSubWindow *);
 
-  bool hidden(QWidget* window);
+  bool hidden(QWidget *window);
   void closeActiveWindow();
-  void closeWindow(MdiSubWindow* window);
+  void closeWindow(MdiSubWindow *window);
 
   //!  Does all the cleaning work before actually deleting a window!
-  void removeWindowFromLists(MdiSubWindow* w);
+  void removeWindowFromLists(MdiSubWindow *w);
 
-  void hideWindow(MdiSubWindow* window);
+  void hideWindow(MdiSubWindow *window);
   void hideWindow();
   void hideActiveWindow();
   void activateWindow();
   void activateWindow(MdiSubWindow *, bool activateOuterWindow = true);
-  bool existsWindow(MdiSubWindow* w) const;
+  bool existsWindow(MdiSubWindow *w) const;
   //@}
 
   //! Show about dialog
   static void about();
   //! Return a version string ("QtiPlot x.y.z")
   static QString versionString();
-  void removeCurves(const QString& name);
-  QStringList dependingPlots(const QString& caption);
+  void removeCurves(const QString &name);
+  QStringList dependingPlots(const QString &caption);
   QStringList depending3DPlots(Matrix *m);
   QStringList multilayerDependencies(QWidget *w);
 
   std::string windowGeometryInfo(MdiSubWindow *w);
-  void restoreWindowGeometry(ApplicationWindow *app, MdiSubWindow *w, const QString& s);
+  void restoreWindowGeometry(ApplicationWindow *app, MdiSubWindow *w,
+                             const QString &s);
   void restoreApplicationGeometry();
   void resizeActiveWindow();
   void resizeWindow();
 
   //! \name List View in Project Explorer
   //@{
-  void setListView(const QString& caption,const QString& view);
-  void renameListViewItem(const QString& oldName,const QString& newName);
-  void setListViewDate(const QString& caption,const QString& date);
-  QString listViewDate(const QString& caption);
-  void setListViewSize(const QString& caption,const QString& size);
-  void setListViewLabel(const QString& caption,const QString& label);
+  void setListView(const QString &caption, const QString &view);
+  void renameListViewItem(const QString &oldName, const QString &newName);
+  void setListViewDate(const QString &caption, const QString &date);
+  QString listViewDate(const QString &caption);
+  void setListViewSize(const QString &caption, const QString &size);
+  void setListViewLabel(const QString &caption, const QString &label);
   //@}
 
-  void updateColNames(const QString& oldName, const QString& newName);
-  void updateTableNames(const QString& oldName, const QString& newName);
-  void changeMatrixName(const QString& oldName, const QString& newName);
-  void updateCurves(Table *t, const QString& name);
+  void updateColNames(const QString &oldName, const QString &newName);
+  void updateTableNames(const QString &oldName, const QString &newName);
+  void changeMatrixName(const QString &oldName, const QString &newName);
+  void updateCurves(Table *t, const QString &name);
 
-  void showTable(const QString& curve);
+  void showTable(const QString &curve);
   void showTable(int i);
 
   void addColToTable();
@@ -596,13 +656,15 @@ public slots:
   void newProject();
 
   //! Creates a new empty multilayer plot
-  MultiLayer* newGraph(const QString& caption = tr("Graph"));
+  MultiLayer *newGraph(const QString &caption = tr("Graph"));
 
-  /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings
-  MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph",
-    bool clearWindow = false);
+  /// Prepares MultiLayer for plotting - creates if necessary, clears, applies
+  /// initial settings
+  MultiLayer *prepareMultiLayer(bool &isNew, MultiLayer *window,
+                                const QString &newWindowName = "Graph",
+                                bool clearWindow = false);
 
-  void openRecentProject(QAction* action);
+  void openRecentProject(QAction *action);
 
   //@}
 
@@ -638,11 +700,12 @@ public slots:
   void showScreenReader();
   void pickPointerCursor();
   void disableTools();
-  void selectMultiPeak(bool showFitPropertyBrowser=true);
-  void selectMultiPeak(MultiLayer* plot, bool showFitPropertyBrowser=true, double xmin=0.0, double xmax=0.0);
-  void pickDataTool( QAction* action );
+  void selectMultiPeak(bool showFitPropertyBrowser = true);
+  void selectMultiPeak(MultiLayer *plot, bool showFitPropertyBrowser = true,
+                       double xmin = 0.0, double xmax = 0.0);
+  void pickDataTool(QAction *action);
 
-  void updateLog(const QString& result);
+  void updateLog(const QString &result);
   //@}
 
   //! \name Fitting
@@ -652,9 +715,9 @@ public slots:
   void fitSigmoidal();
   void fitGauss();
   void fitLorentz();
-  //void fitMultiPeak(int profile);
-  //void fitMultiPeakGauss();
-  //void fitMultiPeakLorentz();
+  // void fitMultiPeak(int profile);
+  // void fitMultiPeakGauss();
+  // void fitMultiPeakLorentz();
   //@}
 
   //! \name Calculus
@@ -662,15 +725,17 @@ public slots:
   void integrate();
   void differentiate();
   void analysis(Analysis operation);
-  void analyzeCurve(Graph *g, Analysis operation, const QString& curveTitle);
+  void analyzeCurve(Graph *g, Analysis operation, const QString &curveTitle);
   void showDataSetDialog(Analysis operation);
   //@}
 
   void addErrorBars();
-  void defineErrorBars(const QString& name,int type,const QString& percent,int direction,bool drawAll);
-  void defineErrorBars(const QString& curveName,const QString& errColumnName, int direction);
+  void defineErrorBars(const QString &name, int type, const QString &percent,
+                       int direction, bool drawAll);
+  void defineErrorBars(const QString &curveName, const QString &errColumnName,
+                       int direction);
   void removeErrorBars();
-  void removeErrorBars(const QString& name);
+  void removeErrorBars(const QString &name);
   void movePoints();
   void removePoints();
 
@@ -687,25 +752,28 @@ public slots:
   //! \name Dialogs
   //@{
   void showFindDialogue();
-  //! Show plot style dialog for the active MultiLayer / activeGraph / specified curve or the activeGraph options dialog if no curve is specified (curveKey = -1).
+  //! Show plot style dialog for the active MultiLayer / activeGraph / specified
+  // curve or the activeGraph options dialog if no curve is specified (curveKey
+  // =
+  //-1).
   void showPlotDialog(int curveKey = -1);
-  QDialog* showScaleDialog();
-  QDialog* showPlot3dDialog();
-  AxesDialog* showScalePageFromAxisDialog(int axisPos);
-  AxesDialog* showAxisPageFromAxisDialog(int axisPos);
+  QDialog *showScaleDialog();
+  QDialog *showPlot3dDialog();
+  AxesDialog *showScalePageFromAxisDialog(int axisPos);
+  AxesDialog *showAxisPageFromAxisDialog(int axisPos);
   void showAxisDialog();
   void showGridDialog();
   void showGeneralPlotDialog();
   void showResults(bool ok);
-  void showResults(const QString& s, bool ok=true);
+  void showResults(const QString &s, bool ok = true);
   void showTextDialog();
   void showLineDialog();
   void showTitleDialog();
   void showExportASCIIDialog();
   void showCurvesDialog();
   void showCurveRangeDialog();
-  CurveRangeDialog* showCurveRangeDialog(Graph *g, int curve);
-  AssociationsDialog* showPlotAssociations(int curve);
+  CurveRangeDialog *showCurveRangeDialog(Graph *g, int curve);
+  AssociationsDialog *showPlotAssociations(int curve);
 
   void showAxisTitleDialog();
   void showColumnOptionsDialog();
@@ -725,10 +793,12 @@ public slots:
   void showCurveWorksheet(Graph *g, int curveIndex);
   void showWindowPopupMenu(const QPoint &p);
 
-  //! Connected to the context menu signal from lv; it's called when there are several items selected in the list
+  //! Connected to the context menu signal from lv; it's called when there are
+  // several items selected in the list
   void showListViewSelectionMenu(const QPoint &p);
 
-  //! Connected to the context menu signal from lv; it's called when there are no items selected in the list
+  //! Connected to the context menu signal from lv; it's called when there are
+  // no items selected in the list
   void showListViewPopupMenu(const QPoint &p);
 
   void showScriptWindow(bool forceVisible = false, bool quitting = false);
@@ -769,7 +839,8 @@ public slots:
   void showColorMapDialog();
   //@}
 
-  //! Removes the curve identified by a key stored in the data() of actionRemoveCurve.
+  //! Removes the curve identified by a key stored in the data() of
+  // actionRemoveCurve.
   void removeCurve();
   void hideCurve();
   void hideOtherCurves();
@@ -794,8 +865,9 @@ public slots:
   void moveColumnFirst();
   void moveColumnLast();
 
-  void updateConfirmOptions(bool askTables, bool askMatrixes, bool askPlots2D, bool askPlots3D, bool askNotes,bool askInstrWindow);
-
+  void updateConfirmOptions(bool askTables, bool askMatrixes, bool askPlots2D,
+                            bool askPlots3D, bool askNotes,
+                            bool askInstrWindow);
 
   //! \name Plot3D Tools
   //@{
@@ -826,32 +898,33 @@ public slots:
   void setLeftGrid3DPlot(bool on);
   void setFrontGrid3DPlot(bool on);
   void setBackGrid3DPlot(bool on);
-  void pickPlotStyle( QAction* action );
-  void pickCoordSystem( QAction* action);
-  void pickFloorStyle( QAction* action);
+  void pickPlotStyle(QAction *action);
+  void pickCoordSystem(QAction *action);
+  void pickFloorStyle(QAction *action);
   void custom3DActions(MdiSubWindow *w);
   void custom3DGrids(int grids);
   //@}
 
   //! Updates the recent projects list and menu (but doesn't insert anything)
   void updateRecentProjectsList();
-  //! Inserts file name in the list of recent files (if fname not empty) and updates the "recent files" menu
-  void updateRecentFilesList(QString fname="");
+  //! Inserts file name in the list of recent files (if fname not empty) and
+  // updates the "recent files" menu
+  void updateRecentFilesList(QString fname = "");
   //! Open QtiPlot homepage in external browser
   void showHomePage();
   //! Open bug tracking system at berliOS in external browser
   void showBugTracker();
 
-  void parseCommandLineArguments(const QStringList& args);
+  void parseCommandLineArguments(const QStringList &args);
   void createLanguagesList();
   void switchToLanguage(int param);
-  void switchToLanguage(const QString& locale);
+  void switchToLanguage(const QString &locale);
 
-  bool alreadyUsedName(const QString& label);
+  bool alreadyUsedName(const QString &label);
   bool projectHas2DPlots();
 
   //! Returns a pointer to the window named "name"
-  MdiSubWindow* window(const QString& name);
+  MdiSubWindow *window(const QString &name);
 
   //! Returns a list with the names of all the matrices in the project
   QStringList matrixNames();
@@ -859,25 +932,25 @@ public slots:
   /// returns a list of all the mantid matrix objects in the project
   QStringList mantidmatrixNames();
 
-
   //! \name Notes
   //@{
   //! Creates a new empty note window
-  Note* newNote(const QString& caption = QString());
+  Note *newNote(const QString &caption = QString());
   void saveNoteAs();
   //@}
 
   //! \name Folders
   //@{
   //! Returns a pointer to the current folder in the project
-  Folder* currentFolder() const {return d_current_folder;}
+  Folder *currentFolder() const { return d_current_folder; }
   //! Adds a new folder to the project
   void addFolder();
-  Folder* addFolder(QString name, Folder* parent = NULL);
+  Folder *addFolder(QString name, Folder *parent = NULL);
   //! Deletes the current folder
   void deleteFolder();
 
-  //! Ask confirmation from user, deletes the folder f if user confirms and returns true, otherwise returns false;
+  //! Ask confirmation from user, deletes the folder f if user confirms and
+  // returns true, otherwise returns false;
   bool deleteFolder(Folder *f);
 
   //! Deletes the currently selected items from the list view #lv.
@@ -887,33 +960,43 @@ public slots:
   //! Show the currently selected windows from the list view #lv.
   void showSelectedWindows();
 
-  //! Sets all items in the folders list view to be desactivated (QPixmap = folder_closed_xpm)
+  //! Sets all items in the folders list view to be desactivated (QPixmap =
+  // folder_closed_xpm)
   void desactivateFolders();
 
   //! Changes the current folder. Returns true if successfull
   bool changeFolder(Folder *newFolder, bool force = false);
 
-  //! Changes the current folder when the user changes the current item in the QListView "folders"
+  //! Changes the current folder when the user changes the current item in the
+  // QListView "folders"
   void folderItemChanged(QTreeWidgetItem *it, QTreeWidgetItem *);
-  //! Changes the current folder when the user double-clicks on a folder item in the QListView "lv"
+  //! Changes the current folder when the user double-clicks on a folder item in
+  // the QListView "lv"
   void folderItemDoubleClicked(QTreeWidgetItem *it);
 
   //!  creates and opens the context menu of a folder list view item
   /**
   * @param it :: list view item
   * @param p :: mouse global position
-  * @param fromFolders: true means that the user clicked right mouse buttom on an item from QListView "folders"
-  *					   false means that the user clicked right mouse buttom on an item from QListView "lv"
+  * @param fromFolders: true means that the user clicked right mouse buttom on
+  *an item from QListView "folders"
+  *					   false means that the user clicked
+  *right
+  *mouse
+  *buttom on an item from QListView "lv"
   */
-  void showFolderPopupMenu(QTreeWidgetItem *it, const QPoint &p, bool fromFolders);
+  void showFolderPopupMenu(QTreeWidgetItem *it, const QPoint &p,
+                           bool fromFolders);
 
   //!  connected to the SIGNAL contextMenuRequested from the list views
   void showFolderPopupMenu(const QPoint &p);
 
-  //!  forces showing all windows in the current folder and subfolders, depending on the user's viewing policy
+  //!  forces showing all windows in the current folder and subfolders,
+  // depending on the user's viewing policy
   void showAllFolderWindows();
 
-  //!  forces hidding all windows in the current folder and subfolders, depending on the user's viewing policy
+  //!  forces hidding all windows in the current folder and subfolders,
+  // depending on the user's viewing policy
   void hideAllFolderWindows();
 
   //!  hides all windows in folder f
@@ -928,13 +1011,16 @@ public slots:
   //!  pops up information about the current project
   void projectProperties();
 
-  //! Pops up a file dialog and invokes appendProject(const QString&) on the result.
+  //! Pops up a file dialog and invokes appendProject(const QString&) on the
+  // result.
   void appendProject();
-  //! Open the specified project file and add it as a subfolder to the parentFolder or to the current folder if no parent folder is specified.
-  Folder* appendProject(const QString& file_name, Folder* parentFolder = 0);
+  //! Open the specified project file and add it as a subfolder to the
+  // parentFolder or to the current folder if no parent folder is specified.
+  Folder *appendProject(const QString &file_name, Folder *parentFolder = 0);
   void saveAsProject();
   void saveFolderAsProject(Folder *f);
-  void saveProjectFile(Folder *folder, const QString& fn, bool compress = false);
+  void saveProjectFile(Folder *folder, const QString &fn,
+                       bool compress = false);
 
   //!  adds a folder list item to the list view "lv"
   void addFolderListViewItem(Folder *f);
@@ -942,17 +1028,18 @@ public slots:
   //!  adds a widget list item to the list view "lv"
   void addListViewItem(MdiSubWindow *w);
 
-  //!  hides or shows windows in the current folder and changes the view windows policy
+  //!  hides or shows windows in the current folder and changes the view windows
+  // policy
   void setShowWindowsPolicy(int p);
 
   //!  returns a pointer to the root project folder
-  Folder* projectFolder() const;
+  Folder *projectFolder() const;
 
   //!  used by the findDialog
-  void find(const QString& s, bool windowNames, bool labels, bool folderNames,
-    bool caseSensitive, bool partialMatch, bool subfolders);
+  void find(const QString &s, bool windowNames, bool labels, bool folderNames,
+            bool caseSensitive, bool partialMatch, bool subfolders);
 
-  void foldersMenuActivated( int id );
+  void foldersMenuActivated(int id);
   //@}
 
   //! \name Scripting
@@ -962,40 +1049,42 @@ public slots:
   //! switches to the given scripting language;
   bool setScriptingLanguage(const QString &lang);
 
-  void scriptsDirPathChanged(const QString& path);
+  void scriptsDirPathChanged(const QString &path);
   //@}
 
   void makeToolbarsMenu();
   void savetoNexusFile();
 
-  //Slot for writing to log window
-  void writeToLogWindow(const MantidQt::API::Message& message);
+  // Slot for writing to log window
+  void writeToLogWindow(const MantidQt::API::Message &message);
 
   /// Activate a subwindow (docked or floating) other than current active one
   void activateNewWindow();
 
   //   Methods for Floating windows
-  FloatingWindow* addMdiSubWindowAsFloating(MdiSubWindow* w, QPoint pos = QPoint(-1,-1));
-  QMdiSubWindow* addMdiSubWindowAsDocked(MdiSubWindow* w, QPoint pos = QPoint(-1,-1));
-  void mdiWindowActivated(MdiSubWindow* w);
-  void changeToFloating(MdiSubWindow* w);
-  void changeToDocked(MdiSubWindow* w);
-  void removeFloatingWindow(FloatingWindow* w);
-  FloatingWindow* getActiveFloating() const;
-  bool isDefaultFloating(const MdiSubWindow* w) const;
-  bool isDefaultFloating(const QString& aClassName) const;
-  QMenuBar* myMenuBar();
+  FloatingWindow *addMdiSubWindowAsFloating(MdiSubWindow *w,
+                                            QPoint pos = QPoint(-1, -1));
+  QMdiSubWindow *addMdiSubWindowAsDocked(MdiSubWindow *w,
+                                         QPoint pos = QPoint(-1, -1));
+  void mdiWindowActivated(MdiSubWindow *w);
+  void changeToFloating(MdiSubWindow *w);
+  void changeToDocked(MdiSubWindow *w);
+  void removeFloatingWindow(FloatingWindow *w);
+  FloatingWindow *getActiveFloating() const;
+  bool isDefaultFloating(const MdiSubWindow *w) const;
+  bool isDefaultFloating(const QString &aClassName) const;
+  QMenuBar *myMenuBar();
   void changeActiveToFloating();
   void changeActiveToDocked();
   /// Validate sub-window position coordinates
-  void validateWindowPos(MdiSubWindow* w, int& x, int& y);
+  void validateWindowPos(MdiSubWindow *w, int &x, int &y);
   /// Detach a subwindow from its parent - docked or floating
-  void detachMdiSubwindow(MdiSubWindow* w);
+  void detachMdiSubwindow(MdiSubWindow *w);
 
   /** Sets whether to prompt the user when closing/deleting a folder */
-  void setConfirmFolderClose(bool value)
-  { confirmCloseFolder = value; }
-  /** The very fist method to be executed as soon as the QApplication event loop starts*/
+  void setConfirmFolderClose(bool value) { confirmCloseFolder = value; }
+  /** The very fist method to be executed as soon as the QApplication event loop
+   * starts*/
   void about2Start();
 
   /// Show/hide MantidPlot toolbars.
@@ -1006,14 +1095,14 @@ public slots:
   TiledWindow *newTiledWindow();
   /// Check if there is an open TiledWindow.
   bool hasTiledWindowOpen();
-  TiledWindow *getTiledWindowAtPos( QPoint pos );
+  TiledWindow *getTiledWindowAtPos(QPoint pos);
   /// Check if a point is inside any of visible TiledWindows
-  bool isInTiledWindow( QPoint pos );
+  bool isInTiledWindow(QPoint pos);
   /// Try to drop a subwindow in the TiledWindow which is under point (x,y)
-  void dropInTiledWindow( MdiSubWindow *w, QPoint pos );
+  void dropInTiledWindow(MdiSubWindow *w, QPoint pos);
   //@}
 
-  bool isOfType(const QObject* obj, const char* toCompare) const;
+  bool isOfType(const QObject *obj, const char *toCompare) const;
 
 signals:
   void modified();
@@ -1026,25 +1115,26 @@ private:
   QMenu *createPopupMenu() override { return NULL; }
 
   void populateMantidTreeWidget(const QString &s);
-  void loadWsToMantidTree(const std::string& wsName);
+  void loadWsToMantidTree(const std::string &wsName);
   /// this method saves the data on project save
-  void savedatainNexusFormat(const std::string& wsName,const std::string & fileName);
+  void savedatainNexusFormat(const std::string &wsName,
+                             const std::string &fileName);
   QPoint positionNewFloatingWindow(QSize sz) const;
   QPoint mdiAreaTopLeft() const;
-  bool shouldExecuteAndQuit(const QString& arg);
-  bool isSilentStartup(const QString& arg);
+  bool shouldExecuteAndQuit(const QString &arg);
+  bool isSilentStartup(const QString &arg);
   void handleConfigDir();
 
   //! \name Project File Loading
   //@{
-  void openMantidMatrix     (const std::string& lines);
-
-  void openMatrix           (const std::string& lines, const int fileVersion);
-  void openMultiLayer       (const std::string& lines, const int fileVersion);
-  void openSurfacePlot      (const std::string& lines, const int fileVersion);
-  void openTable            (const std::string& lines, const int fileVersion);
-  void openTableStatistics  (const std::string& lines, const int fileVersion);
-  void openScriptWindow     (const QStringList& lines);
+  void openMantidMatrix(const std::string &lines);
+
+  void openMatrix(const std::string &lines, const int fileVersion);
+  void openMultiLayer(const std::string &lines, const int fileVersion);
+  void openSurfacePlot(const std::string &lines, const int fileVersion);
+  void openTable(const std::string &lines, const int fileVersion);
+  void openTableStatistics(const std::string &lines, const int fileVersion);
+  void openScriptWindow(const QStringList &lines);
   //@}
 
 private slots:
@@ -1054,7 +1144,7 @@ private slots:
   void displayToolbars();
   void insertTranslatedStrings();
   void translateActionsStrings();
-  void init(bool factorySettings, const QStringList& args);
+  void init(bool factorySettings, const QStringList &args);
   void initGlobalConstants();
   void createActions();
   void initMainMenu();
@@ -1063,9 +1153,9 @@ private slots:
   void disableActions();
   void customColumnActions();
   void disableToolbars();
-  void customToolBars(MdiSubWindow* w);
-  void customMultilayerToolButtons(MultiLayer* w);
-  void customMenu(MdiSubWindow* w);
+  void customToolBars(MdiSubWindow *w);
+  void customMultilayerToolButtons(MultiLayer *w);
+  void customMenu(MdiSubWindow *w);
   void windowActivated(QMdiSubWindow *w);
   //@}
 
@@ -1104,7 +1194,7 @@ private slots:
 
   void hideSelectedColumns();
   void showAllColumns();
-  void closedLastCopiedLayer(){lastCopiedLayer = NULL;};
+  void closedLastCopiedLayer() { lastCopiedLayer = NULL; };
   void cleanTextEditor();
   void tileMdiWindows();
   void shakeViewport();
@@ -1130,22 +1220,24 @@ private slots:
   void CatalogLogout();
 
   /// method to create widgets from mantid qt;
-  void setGeometry(MdiSubWindow* usr_win,QWidget* user_interface);
+  void setGeometry(MdiSubWindow *usr_win, QWidget *user_interface);
 
   ///
   void showalgorithmDescriptions();
 
   /// Contains the rules of when to show the FirstTimeSetup UI.
-  bool shouldWeShowFirstTimeSetup(const QStringList& commandArguments);
+  bool shouldWeShowFirstTimeSetup(const QStringList &commandArguments);
   /// Open up the FirstRunSetup dialog
   void showFirstTimeSetup();
-  
-  ApplicationWindow* loadScript(const QString& fn, bool existingProject = false);
+
+  ApplicationWindow *loadScript(const QString &fn,
+                                bool existingProject = false);
 
 public:
   // TODO: a lot of this stuff should be private
   bool d_showFirstTimeSetup;
-  //! End of line convention used for copy/paste operations and when exporting tables/matrices to ASCII files.
+  //! End of line convention used for copy/paste operations and when exporting
+  // tables/matrices to ASCII files.
   EndLineChar d_eol;
   //! Flag telling if the in-place editing of 2D plot labels is enabled
   bool d_in_place_editing;
@@ -1154,7 +1246,8 @@ public:
   //! Flag telling if the application is opening a project file or not
   bool d_opening_file;
   QString customActionsDirPath;
-  bool d_matrix_tool_bar, d_standard_tool_bar, d_column_tool_bar, d_edit_tool_bar;
+  bool d_matrix_tool_bar, d_standard_tool_bar, d_column_tool_bar,
+      d_edit_tool_bar;
   bool d_plot_tool_bar, d_display_tool_bar, d_format_tool_bar;
   bool d_backup_files;
   WindowType d_init_window_type;
@@ -1181,9 +1274,11 @@ public:
   EndLineChar d_ASCII_end_line;
   //! Last selected filter in import ASCII dialog
   QString d_ASCII_file_filter, d_ASCII_comment_string;
-  bool d_import_dec_separators, d_ASCII_import_comments, d_ASCII_import_read_only, d_ASCII_import_preview;
+  bool d_import_dec_separators, d_ASCII_import_comments,
+      d_ASCII_import_read_only, d_ASCII_import_preview;
   int d_ASCII_import_mode, d_preview_lines;
-  //! Specifies if only the Tables/Matrices in the current folder should be displayed in the Add/remove curve dialog.
+  //! Specifies if only the Tables/Matrices in the current folder should be
+  // displayed in the Add/remove curve dialog.
   bool d_show_current_folder;
   bool d_scale_plots_on_print, d_print_cropmarks;
   bool d_show_table_comments;
@@ -1225,20 +1320,24 @@ public:
   //! pointer to the folder marked current in the last loaded project
   Folder *d_loaded_current;
 
-  //! Describes which windows are shown when the folder becomes the current folder
+  //! Describes which windows are shown when the folder becomes the current
+  // folder
   ShowWindowsPolicy show_windows_policy;
-  enum {MaxRecentProjects = 10};
-  enum {MaxRecentFiles = MaxRecentProjects};
+  enum { MaxRecentProjects = 10 };
+  enum { MaxRecentFiles = MaxRecentProjects };
 
   QColor workspaceColor, panelsColor, panelsTextColor;
   QString appStyle, workingDir;
 
   //! Path to the folder where the last template file was opened/saved
   QString templatesDir;
-  bool smooth3DMesh, autoScaleFonts, autoResizeLayers, askForSupport, autoSearchUpdates;
-  bool confirmCloseTable, confirmCloseMatrix, confirmClosePlot2D, confirmClosePlot3D,confirmCloseInstrWindow;
+  bool smooth3DMesh, autoScaleFonts, autoResizeLayers, askForSupport,
+      autoSearchUpdates;
+  bool confirmCloseTable, confirmCloseMatrix, confirmClosePlot2D,
+      confirmClosePlot3D, confirmCloseInstrWindow;
   bool confirmCloseFolder, confirmCloseNotes;
-  bool titleOn, autoSave, autoscale2DPlots, antialiasing2DPlots, fixedAspectRatio2DPlots;
+  bool titleOn, autoSave, autoscale2DPlots, antialiasing2DPlots,
+      fixedAspectRatio2DPlots;
   //! \name User preferences for axes in new 2D plot layers
   //@{
   //! Axes to be shown
@@ -1258,7 +1357,8 @@ public:
   //@}
   bool d_synchronize_graph_scales;
 
-  int majTicksStyle, minTicksStyle, legendFrameStyle, autoSaveTime, canvasFrameWidth;
+  int majTicksStyle, minTicksStyle, legendFrameStyle, autoSaveTime,
+      canvasFrameWidth;
   bool autoDistribution1D;
   QColor legendBackground, legendTextColor, defaultArrowColor;
   int defaultArrowHeadLength, defaultArrowHeadAngle;
@@ -1267,25 +1367,33 @@ public:
   Qt::PenStyle defaultArrowLineStyle;
   int majTicksLength, minTicksLength, defaultPlotMargin;
   int defaultCurveStyle, defaultSymbolSize;
-  bool applyCurveStyleToMantid; ///< if true defaultCurveStyle, defaultSymbolSize are applyed to MantidCurves
-  /// if true all errors are drawn on new plots with error bars, for a particular graph can be overridden
+  bool applyCurveStyleToMantid; ///< if true defaultCurveStyle,
+  /// defaultSymbolSize are applyed to MantidCurves
+  /// if true all errors are drawn on new plots with error bars, for a
+  /// particular graph can be overridden
   /// form Add Error bars dialog
   bool drawAllErrors;
   QFont appFont, plot3DTitleFont, plot3DNumbersFont, plot3DAxesFont;
-  QFont tableTextFont, tableHeaderFont, plotAxesFont, plotLegendFont, plotNumbersFont, plotTitleFont;
+  QFont tableTextFont, tableHeaderFont, plotAxesFont, plotLegendFont,
+      plotNumbersFont, plotTitleFont;
   QColor tableBkgdColor, tableTextColor, tableHeaderColor;
   QString projectname, columnSeparator, helpFilePath, appLanguage;
-  QString configFilePath, fitPluginsPath, fitModelsPath, asciiDirPath, imagesDirPath, scriptsDirPath;
+  QString configFilePath, fitPluginsPath, fitModelsPath, asciiDirPath,
+      imagesDirPath, scriptsDirPath;
   int ignoredLines, savingTimerId, plot3DResolution;
   bool renameColumns, strip_spaces, simplify_spaces;
   QStringList recentProjects, recentFiles;
-  bool saved, showPlot3DProjection, showPlot3DLegend, orthogonal3DPlots, autoscale3DPlots;
+  bool saved, showPlot3DProjection, showPlot3DLegend, orthogonal3DPlots,
+      autoscale3DPlots;
   QStringList plot3DColors, locales;
-  QStringList functions; //user-defined functions;
-  QStringList xFunctions, yFunctions, rFunctions, thetaFunctions; // user functions for parametric and polar plots
-  QStringList surfaceFunc; //user-defined surface functions;
-  QStringList d_param_surface_func; //user-defined parametric surface functions;
-  //! List of tables and matrices renamed in order to avoid conflicts when appending a project to a folder
+  QStringList functions; // user-defined functions;
+  QStringList xFunctions, yFunctions, rFunctions,
+      thetaFunctions;      // user functions for parametric and polar plots
+  QStringList surfaceFunc; // user-defined surface functions;
+  QStringList d_param_surface_func; // user-defined parametric surface
+                                    // functions;
+  //! List of tables and matrices renamed in order to avoid conflicts when
+  // appending a project to a folder
   QStringList renamedTables;
   // List of removed interfaces
   QStringList removed_interfaces;
@@ -1297,7 +1405,8 @@ public:
   ImageMarker *d_image_copy;
   //@}
 
-  //! Equals true if an automatical search for updates was performed on start-up otherwise is set to false;
+  //! Equals true if an automatical search for updates was performed on start-up
+  // otherwise is set to false;
   bool autoSearchUpdatesRequest;
 
   //! The scripting language to use for new projects.
@@ -1308,9 +1417,12 @@ public:
   QSet<QString> allCategories() const { return m_allCategories; }
 
 private:
-  // A collection of the names of each interface as they appear in the menu and also "data"
-  // relating to how each interface can be opened.  Elsewhere, the data is expected to be a
-  // python file name, or else just the name of the interface as known to the InterfaceManager.
+  // A collection of the names of each interface as they appear in the menu and
+  // also "data"
+  // relating to how each interface can be opened.  Elsewhere, the data is
+  // expected to be a
+  // python file name, or else just the name of the interface as known to the
+  // InterfaceManager.
   QList<QPair<QString, QString>> m_interfaceNameDataPairs;
   // Keeping track of all unique categories.
   QSet<QString> m_allCategories;
@@ -1318,11 +1430,12 @@ private:
   QMap<QString, QSet<QString>> m_interfaceCategories;
 
   mutable MdiSubWindow *d_active_window;
-  MdiSubWindow* getActiveWindow() const;
-  void setActiveWindow(MdiSubWindow* w);
+  MdiSubWindow *getActiveWindow() const;
+  void setActiveWindow(MdiSubWindow *w);
   TextEditor *d_text_editor;
   QLocale d_locale;
-  // Flag telling if table values should be automatically recalculated when values in a column are modified.
+  // Flag telling if table values should be automatically recalculated when
+  // values in a column are modified.
   bool d_auto_update_table_values;
   int d_matrix_undo_stack_size;
 
@@ -1333,7 +1446,7 @@ private:
   QSplitter *explorerSplitter;
 
   //	QAssistantClient *assistant;
-  ScriptingWindow *scriptingWindow; //Mantid
+  ScriptingWindow *scriptingWindow; // Mantid
   Script *m_iface_script;
   QTranslator *appTranslator, *qtTranslator;
   QDockWidget *explorerWindow;
@@ -1353,111 +1466,157 @@ private:
 
   QMenu *help, *plot2DMenu, *analysisMenu, *multiPeakMenu, *icat;
   QMenu *matrixMenu, *plot3DMenu, *plotDataMenu, *tablesDepend, *scriptingMenu;
-  QMenu *tableMenu, *fillMenu, *normMenu, *newMenu, *exportPlotMenu, *smoothMenu, *filterMenu, *decayMenu,*saveMenu,*openMenu, *toolbarsMenu;
+  QMenu *tableMenu, *fillMenu, *normMenu, *newMenu, *exportPlotMenu,
+      *smoothMenu, *filterMenu, *decayMenu, *saveMenu, *openMenu, *toolbarsMenu;
   QMenu *tiledWindowMenu;
 
-  QAction *actionFileTools,*actionPlotTools,*actionDisplayBar,*actionFormatToolBar;
-  QAction *actionEditCurveRange, *actionCurveFullRange, *actionShowAllCurves, *actionHideCurve, *actionHideOtherCurves;
-  QAction *actionEditFunction, *actionRemoveCurve, *actionShowCurveWorksheet, *actionShowCurvePlotDialog;
-  QAction *actionNewProject, *actionNewNote, *actionNewTable, *actionNewFunctionPlot,*actionSaveFile;
-  QAction *actionNewSurfacePlot, *actionNewMatrix, *actionNewGraph; //, *actionNewFolder;
-  QAction *actionOpen, *actionLoadImage, *actionScriptRepo, *actionSaveProject, *actionSaveProjectAs, *actionImportImage,*actionLoadFile,*actionOpenProj;
+  QAction *actionFileTools, *actionPlotTools, *actionDisplayBar,
+      *actionFormatToolBar;
+  QAction *actionEditCurveRange, *actionCurveFullRange, *actionShowAllCurves,
+      *actionHideCurve, *actionHideOtherCurves;
+  QAction *actionEditFunction, *actionRemoveCurve, *actionShowCurveWorksheet,
+      *actionShowCurvePlotDialog;
+  QAction *actionNewProject, *actionNewNote, *actionNewTable,
+      *actionNewFunctionPlot, *actionSaveFile;
+  QAction *actionNewSurfacePlot, *actionNewMatrix,
+      *actionNewGraph; //, *actionNewFolder;
+  QAction *actionOpen, *actionLoadImage, *actionScriptRepo, *actionSaveProject,
+      *actionSaveProjectAs, *actionImportImage, *actionLoadFile,
+      *actionOpenProj;
   QAction *actionLoad;
   QAction *actionCopyWindow, *actionShowAllColumns, *actionHideSelectedColumns;
-  QAction *actionCutSelection, *actionCopySelection, *actionPasteSelection, *actionClearSelection;
-  QAction *actionShowExplorer, *actionShowLog, *actionAddLayer, *actionShowLayerDialog, *actionAutomaticLayout,*actionclearAllMemory;
-  QAction *actionCatalogLogin,*actionCatalogSearch, *actionCatalogPublish, *actionCatalogLogout;
-  QAction *actionSwapColumns, *actionMoveColRight, *actionMoveColLeft, *actionMoveColFirst, *actionMoveColLast;
-  QAction *actionExportGraph, *actionExportAllGraphs, *actionPrint, *actionPrintAllPlots, *actionShowExportASCIIDialog;
+  QAction *actionCutSelection, *actionCopySelection, *actionPasteSelection,
+      *actionClearSelection;
+  QAction *actionShowExplorer, *actionShowLog, *actionAddLayer,
+      *actionShowLayerDialog, *actionAutomaticLayout, *actionclearAllMemory;
+  QAction *actionCatalogLogin, *actionCatalogSearch, *actionCatalogPublish,
+      *actionCatalogLogout;
+  QAction *actionSwapColumns, *actionMoveColRight, *actionMoveColLeft,
+      *actionMoveColFirst, *actionMoveColLast;
+  QAction *actionExportGraph, *actionExportAllGraphs, *actionPrint,
+      *actionPrintAllPlots, *actionShowExportASCIIDialog;
   QAction *actionExportPDF, *actionReadOnlyCol, *actionStemPlot;
-  QAction *actionCloseAllWindows, *actionShowPlotWizard, *actionShowConfigureDialog;
-  QAction *actionShowCurvesDialog, *actionAddErrorBars, *actionRemoveErrorBars, *actionAddFunctionCurve, *actionUnzoom, *actionNewLegend, *actionAddImage;
-  QAction *actionPlotL, *actionPlotP, *actionPlotLP, *actionPlotVerticalDropLines, *actionPlotSpline;
+  QAction *actionCloseAllWindows, *actionShowPlotWizard,
+      *actionShowConfigureDialog;
+  QAction *actionShowCurvesDialog, *actionAddErrorBars, *actionRemoveErrorBars,
+      *actionAddFunctionCurve, *actionUnzoom, *actionNewLegend, *actionAddImage;
+  QAction *actionPlotL, *actionPlotP, *actionPlotLP,
+      *actionPlotVerticalDropLines, *actionPlotSpline;
   QAction *actionPlotVertSteps, *actionPlotHorSteps, *actionPlotVerticalBars;
-  QAction *actionPlotHorizontalBars, *actionPlotArea, *actionPlotPie, *actionPlotVectXYAM, *actionPlotVectXYXY;
-  QAction *actionPlotHistogram, *actionPlotStackedHistograms, *actionPlot2VerticalLayers, *actionPlot2HorizontalLayers, *actionPlot4Layers, *actionPlotStackedLayers;
-  QAction *actionPlot3DRibbon, *actionPlot3DBars, *actionPlot3DScatter, *actionPlot3DTrajectory;
-  QAction *actionShowColStatistics, *actionShowRowStatistics, *actionShowIntDialog, *actionIntegrate;
+  QAction *actionPlotHorizontalBars, *actionPlotArea, *actionPlotPie,
+      *actionPlotVectXYAM, *actionPlotVectXYXY;
+  QAction *actionPlotHistogram, *actionPlotStackedHistograms,
+      *actionPlot2VerticalLayers, *actionPlot2HorizontalLayers,
+      *actionPlot4Layers, *actionPlotStackedLayers;
+  QAction *actionPlot3DRibbon, *actionPlot3DBars, *actionPlot3DScatter,
+      *actionPlot3DTrajectory;
+  QAction *actionShowColStatistics, *actionShowRowStatistics,
+      *actionShowIntDialog, *actionIntegrate;
   QAction *actionDifferentiate, *actionFitLinear, *actionShowFitPolynomDialog;
-  QAction *actionShowExpDecayDialog, *actionShowTwoExpDecayDialog, *actionShowExpDecay3Dialog;
-  QAction *actionFitExpGrowth, *actionFitSigmoidal, *actionFitGauss, *actionFitLorentz, *actionShowFitDialog;
+  QAction *actionShowExpDecayDialog, *actionShowTwoExpDecayDialog,
+      *actionShowExpDecay3Dialog;
+  QAction *actionFitExpGrowth, *actionFitSigmoidal, *actionFitGauss,
+      *actionFitLorentz, *actionShowFitDialog;
   QAction *actionShowAxisDialog, *actionShowTitleDialog;
-  QAction *actionShowColumnOptionsDialog, *actionShowColumnValuesDialog, *actionShowColsDialog, *actionShowRowsDialog;
+  QAction *actionShowColumnOptionsDialog, *actionShowColumnValuesDialog,
+      *actionShowColsDialog, *actionShowRowsDialog;
   QAction *actionTableRecalculate;
-  QAction *actionAbout, *actionShowHelp, *actionChooseHelpFolder,*actionMantidConcepts,*actionMantidAlgorithms,*actionmantidplotHelp;
-  QAction *actionRename, *actionCloseWindow, *actionConvertTable, *actionConvertTableToWorkspace, *actionConvertTableToMatrixWorkspace;
+  QAction *actionAbout, *actionShowHelp, *actionChooseHelpFolder,
+      *actionMantidConcepts, *actionMantidAlgorithms, *actionmantidplotHelp;
+  QAction *actionRename, *actionCloseWindow, *actionConvertTable,
+      *actionConvertTableToWorkspace, *actionConvertTableToMatrixWorkspace;
   QAction *actionAddColToTable, *actionDeleteLayer, *actionInterpolate;
   QAction *actionResizeActiveWindow, *actionHideActiveWindow;
-  QAction *actionShowMoreWindows, *actionPixelLineProfile, *actionIntensityTable;
+  QAction *actionShowMoreWindows, *actionPixelLineProfile,
+      *actionIntensityTable;
   QAction *actionShowLineDialog, *actionShowImageDialog, *actionShowTextDialog;
-  QAction *actionActivateWindow, *actionMinimizeWindow, *actionMaximizeWindow, *actionHideWindow, *actionResizeWindow;
+  QAction *actionActivateWindow, *actionMinimizeWindow, *actionMaximizeWindow,
+      *actionHideWindow, *actionResizeWindow;
   QAction *actionEditSurfacePlot, *actionAdd3DData;
-  QAction *actionMatrixDeterminant, *actionSetMatrixProperties, *actionConvertMatrixXYZ, *actionConvertMatrixYXZ;
-  QAction *actionSetMatrixDimensions, *actionConvertMatrixDirect, *actionSetMatrixValues, *actionTransposeMatrix, *actionInvertMatrix;
-  QAction *actionPlot3DWireFrame, *actionPlot3DHiddenLine, *actionPlot3DPolygons, *actionPlot3DWireSurface;
-  QAction *actionColorMap, *actionContourMap, *actionGrayMap, *actionNoContourColorMap;
+  QAction *actionMatrixDeterminant, *actionSetMatrixProperties,
+      *actionConvertMatrixXYZ, *actionConvertMatrixYXZ;
+  QAction *actionSetMatrixDimensions, *actionConvertMatrixDirect,
+      *actionSetMatrixValues, *actionTransposeMatrix, *actionInvertMatrix;
+  QAction *actionPlot3DWireFrame, *actionPlot3DHiddenLine,
+      *actionPlot3DPolygons, *actionPlot3DWireSurface;
+  QAction *actionColorMap, *actionContourMap, *actionGrayMap,
+      *actionNoContourColorMap;
   QAction *actionDeleteFitTables, *actionShowGridDialog, *actionTimeStamp;
-  QAction *actionSmoothSavGol, *actionSmoothFFT, *actionSmoothAverage, *actionFFT;
-  QAction *actionLowPassFilter, *actionHighPassFilter, *actionBandPassFilter, *actionBandBlockFilter;
+  QAction *actionSmoothSavGol, *actionSmoothFFT, *actionSmoothAverage,
+      *actionFFT;
+  QAction *actionLowPassFilter, *actionHighPassFilter, *actionBandPassFilter,
+      *actionBandBlockFilter;
   QAction *actionSortTable, *actionSortSelection, *actionNormalizeSelection;
-  QAction *actionNormalizeTable, *actionConvolute, *actionDeconvolute, *actionCorrelate, *actionAutoCorrelate;
+  QAction *actionNormalizeTable, *actionConvolute, *actionDeconvolute,
+      *actionCorrelate, *actionAutoCorrelate;
   QAction *actionSetAscValues, *actionSetRandomValues;
-  QAction *actionSetXCol, *actionSetYCol, *actionSetZCol, *actionSetLabelCol, *actionDisregardCol, *actionSetXErrCol, *actionSetYErrCol;
+  QAction *actionSetXCol, *actionSetYCol, *actionSetZCol, *actionSetLabelCol,
+      *actionDisregardCol, *actionSetXErrCol, *actionSetYErrCol;
   QAction *actionBoxPlot, *actionCheckUpdates;
-  QAction *actionDonate, *actionHomePage, *actionDownloadManual, *actionTechnicalSupport, *actionTranslations;
+  QAction *actionDonate, *actionHomePage, *actionDownloadManual,
+      *actionTechnicalSupport, *actionTranslations;
   QAction *actionHelpForums, *actionHelpBugReports, *actionAskHelp;
   QAction *actionShowPlotDialog, *actionShowScaleDialog;
   QAction *actionNextWindow, *actionPrevWindow;
-  QAction *actionScriptingLang,*actionClearTable, *actionGoToRow, *actionGoToColumn;
+  QAction *actionScriptingLang, *actionClearTable, *actionGoToRow,
+      *actionGoToColumn;
   QAction *actionSaveNote;
   QAction *actionShowScriptWindow, *actionShowScriptInterpreter;
-  QAction *actionAnimate, *actionPerspective, *actionFitFrame, *actionResetRotation;
+  QAction *actionAnimate, *actionPerspective, *actionFitFrame,
+      *actionResetRotation;
   QAction *actionDeleteRows, *actionDrawPoints;
-  QAction *btnCursor, *btnPicker, *btnRemovePoints, *btnMovePoints, *btnMultiPeakPick;
+  QAction *btnCursor, *btnPicker, *btnRemovePoints, *btnMovePoints,
+      *btnMultiPeakPick;
   QAction *btnZoomIn, *btnZoomOut, *btnPointer, *btnLine, *btnArrow, *btnLabel;
-  QAction *actionFlipMatrixVertically, *actionFlipMatrixHorizontally, *actionRotateMatrix;
+  QAction *actionFlipMatrixVertically, *actionFlipMatrixHorizontally,
+      *actionRotateMatrix;
   QAction *actionViewMatrixImage, *actionViewMatrix, *actionExportMatrix;
-  QAction *actionMatrixGrayScale, *actionMatrixRainbowScale, *actionMatrixCustomScale, *actionRotateMatrixMinus;
+  QAction *actionMatrixGrayScale, *actionMatrixRainbowScale,
+      *actionMatrixCustomScale, *actionRotateMatrixMinus;
   QAction *actionMatrixXY, *actionMatrixColumnRow, *actionImagePlot;
   QAction *actionMatrixFFTDirect, *actionMatrixFFTInverse;
   QAction *actionFontBold, *actionFontItalic, *actionFontBox, *actionFontSize;
-  QAction *actionSuperscript, *actionSubscript, *actionUnderline, *actionGreekSymbol, *actionCustomActionDialog, *actionManageDirs, *actionFirstTimeSetup;
+  QAction *actionSuperscript, *actionSubscript, *actionUnderline,
+      *actionGreekSymbol, *actionCustomActionDialog, *actionManageDirs,
+      *actionFirstTimeSetup;
   QAction *actionGreekMajSymbol, *actionMathSymbol;
   QAction *Box, *Frame, *None;
-  QAction *front, *back, *right, *left, *ceil, *floor, *floordata, *flooriso, *floornone;
-  QAction *wireframe, *hiddenline, *polygon, *filledmesh, *pointstyle, *barstyle, *conestyle, *crossHairStyle;
+  QAction *front, *back, *right, *left, *ceil, *floor, *floordata, *flooriso,
+      *floornone;
+  QAction *wireframe, *hiddenline, *polygon, *filledmesh, *pointstyle,
+      *barstyle, *conestyle, *crossHairStyle;
   QActionGroup *coord, *floorstyle, *grids, *plotstyle, *dataTools;
   QAction *actionPanPlot;
   QAction *actionWaterfallPlot;
   QAction *actionNewTiledWindow;
 
-
   QList<QAction *> d_user_actions;
-  QList<QMenu* > d_user_menus; //Mantid
+  QList<QMenu *> d_user_menus; // Mantid
 
   QList<QAction *> m_interfaceActions;
 
   /// list of mantidmatrix windows opened from project file.
-  QList<MantidMatrix*> m_mantidmatrixWindows;
+  QList<MantidMatrix *> m_mantidmatrixWindows;
 
   friend class MantidUI;
   friend class ConfigDialog;
   QString m_nexusInputWSName;
 
   // Store initialized script environments
-  QHash<QString, ScriptingEnv*> m_script_envs;
+  QHash<QString, ScriptingEnv *> m_script_envs;
   /// Store a list of environments that cannot be used
   QSet<QString> m_bad_script_envs;
 
   // Floating windows
-  QList<FloatingWindow*> m_floatingWindows;
-  // To block activating new window when a floating window is in process of resetting flags
+  QList<FloatingWindow *> m_floatingWindows;
+  // To block activating new window when a floating window is in process of
+  // resetting flags
   bool blockWindowActivation;
   ///
   bool m_enableQtiPlotFitting;
 
 #ifdef SHARED_MENUBAR
-  QMenuBar* m_sharedMenuBar; ///< Pointer to the shared menubar
+  QMenuBar *m_sharedMenuBar; ///< Pointer to the shared menubar
 #endif
 
   /// Exit code to set at application end
diff --git a/MantidPlot/src/ArrowMarker.cpp b/MantidPlot/src/ArrowMarker.cpp
index 3fdaacf7e7cf9acbde81390831782561b5d18362..ce036fddfab98db8c77affbbbcc190f1f8a9726b 100644
--- a/MantidPlot/src/ArrowMarker.cpp
+++ b/MantidPlot/src/ArrowMarker.cpp
@@ -39,358 +39,327 @@
 #include <qwt_plot_canvas.h>
 #include <qwt_painter.h>
 
-ArrowMarker::ArrowMarker():
-    d_start_arrow(false),
-		d_end_arrow(true),
-		d_fill_head(true),
-		d_head_angle(45),
-		d_head_length(4),
-		d_rect(0, 0, 1, 1),
-		d_editable(false),
-		d_op(None)
-{
-}
+ArrowMarker::ArrowMarker()
+    : d_start_arrow(false), d_end_arrow(true), d_fill_head(true),
+      d_head_angle(45), d_head_length(4), d_rect(0, 0, 1, 1), d_editable(false),
+      d_op(None) {}
+
+void ArrowMarker::draw(QPainter *p, const QwtScaleMap &xMap,
+                       const QwtScaleMap &yMap, const QRect &) const {
+  const int x0 = xMap.transform(d_rect.left());
+  const int y0 = yMap.transform(d_rect.top());
+  const int x1 = xMap.transform(d_rect.right());
+  const int y1 = yMap.transform(d_rect.bottom());
+
+  p->save();
+  QPen pen = linePen();
+  p->setPen(pen);
+
+  QBrush brush = QBrush(pen.color(), Qt::SolidPattern);
+  QwtPainter::drawLine(p, x0, y0, x1, y1);
+  p->restore();
+
+  if (d_end_arrow) {
+    p->save();
+    p->translate(x1, y1);
+    const double t = theta(x0, y0, x1, y1);
+    p->rotate(-t);
+
+    QPolygon endArray(3);
+    endArray[0] = QPoint(0, 0);
+
+    int d = (int)floor(d_head_length * tan(M_PI * d_head_angle / 180.0) + 0.5);
+    endArray[1] = QPoint(-d_head_length, d);
+    endArray[2] = QPoint(-d_head_length, -d);
+
+    p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
+    if (d_fill_head)
+      p->setBrush(brush);
+
+    QwtPainter::drawPolygon(p, endArray);
+    p->restore();
+  }
+
+  if (d_start_arrow) {
+    p->save();
+    p->translate(x0, y0);
+    const double t = theta(x0, y0, x1, y1);
+    p->rotate(-t);
+
+    QPolygon startArray(3);
+    startArray[0] = QPoint(0, 0);
 
-void ArrowMarker::draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const
-{
-	const int x0 = xMap.transform(d_rect.left());
-	const int y0 = yMap.transform(d_rect.top());
-	const int x1 = xMap.transform(d_rect.right());
-	const int y1 = yMap.transform(d_rect.bottom());
-
-	p->save();
-	QPen pen = linePen();
-	p->setPen(pen);
-
-	QBrush brush = QBrush(pen.color(), Qt::SolidPattern);
-	QwtPainter::drawLine(p,x0,y0,x1,y1);
-	p->restore();
-
-	if (d_end_arrow)
-		{
-		p->save();
-		p->translate(x1,y1);
-		const double t = theta(x0, y0, x1, y1);
-		p->rotate(-t);
-
-		QPolygon endArray(3);
-		endArray[0] = QPoint(0,0);
-
-		int d=(int)floor(d_head_length*tan(M_PI*d_head_angle/180.0)+0.5);
-		endArray[1] = QPoint(-d_head_length,d);
-		endArray[2] = QPoint(-d_head_length,-d);
-
-		p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
-		if (d_fill_head)
-			p->setBrush(brush);
-
-		QwtPainter::drawPolygon(p,endArray);
-		p->restore();
-		}
-
-	if (d_start_arrow)
-		{
-		p->save();
-		p->translate(x0,y0);
-		const double t = theta(x0, y0, x1, y1);
-		p->rotate(-t);
-
-		QPolygon startArray(3);
-		startArray[0] = QPoint(0,0);
-
-		int d=(int)floor(d_head_length*tan(M_PI*d_head_angle/180.0)+0.5);
-		startArray[1] = QPoint(d_head_length,d);
-		startArray[2] = QPoint(d_head_length,-d);
-
-		p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
-		if (d_fill_head)
-			p->setBrush(brush);
-		QwtPainter::drawPolygon(p,startArray);
-		p->restore();
-		}
-
-	if (d_editable) {
-		p->save();
-		p->setPen(QPen(Qt::black,1,Qt::SolidLine));
-		QRect handler(QPoint(0,0), QSize(10,10));
-		handler.moveCenter(startPoint());
-		p->fillRect(handler, QBrush(Qt::black));
-		handler.moveCenter(endPoint());
-		p->fillRect(handler, QBrush(Qt::black));
-		p->restore();
-	}
+    int d = (int)floor(d_head_length * tan(M_PI * d_head_angle / 180.0) + 0.5);
+    startArray[1] = QPoint(d_head_length, d);
+    startArray[2] = QPoint(d_head_length, -d);
+
+    p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
+    if (d_fill_head)
+      p->setBrush(brush);
+    QwtPainter::drawPolygon(p, startArray);
+    p->restore();
+  }
+
+  if (d_editable) {
+    p->save();
+    p->setPen(QPen(Qt::black, 1, Qt::SolidLine));
+    QRect handler(QPoint(0, 0), QSize(10, 10));
+    handler.moveCenter(startPoint());
+    p->fillRect(handler, QBrush(Qt::black));
+    handler.moveCenter(endPoint());
+    p->fillRect(handler, QBrush(Qt::black));
+    p->restore();
+  }
 }
 
-double ArrowMarker::theta(int xs, int ys, int xe, int ye) const
-{
-double t;
-if (xe == xs)
-	{
-	if (ys > ye)
-		t = 90;
-	else
-		t = 270;
-	}
-else
-	{
-	t = atan2((ye-ys)*1.0,(xe-xs)*1.0)*45/atan(-1.0);
-	if (t<0)
-		t = 360+t;
-	}
-return t;
+double ArrowMarker::theta(int xs, int ys, int xe, int ye) const {
+  double t;
+  if (xe == xs) {
+    if (ys > ye)
+      t = 90;
+    else
+      t = 270;
+  } else {
+    t = atan2((ye - ys) * 1.0, (xe - xs) * 1.0) * 45 / atan(-1.0);
+    if (t < 0)
+      t = 360 + t;
+  }
+  return t;
 }
 
-double ArrowMarker::length()
-{
-	if (!plot())
-		return -1.0;
+double ArrowMarker::length() {
+  if (!plot())
+    return -1.0;
 
-	const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-	const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+  const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+  const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
 
-	const int x0 = xMap.transform(d_rect.left());
-	const int y0 = yMap.transform(d_rect.top());
-	const int x1 = xMap.transform(d_rect.right());
-	const int y1 = yMap.transform(d_rect.bottom());
+  const int x0 = xMap.transform(d_rect.left());
+  const int y0 = yMap.transform(d_rect.top());
+  const int x1 = xMap.transform(d_rect.right());
+  const int y1 = yMap.transform(d_rect.bottom());
 
-	double l=sqrt(double((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0)));
-	return fabs(l);
+  double l = sqrt(double((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)));
+  return fabs(l);
 }
 
-double ArrowMarker::dist(int x, int y)
-{
-	if (!plot())
-		return -1.0;
-
-	const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-	const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
-
-	const int x0 = xMap.transform(d_rect.left());
-	const int y0 = yMap.transform(d_rect.top());
-	const int x1 = xMap.transform(d_rect.right());
-	const int y1 = yMap.transform(d_rect.bottom());
-
-	int xmin=qMin(x0,x1);
-	int xmax=qMax(x0,x1);
-	int ymin=qMin(y0,y1);
-	int ymax=qMax(y0,y1);
-
-	if ( (x>xmax || x<xmin || xmin==xmax) && (ymax<y || ymin>y || ymin==ymax))
-		//return the shortest distance to one of the ends
-		return qMin(sqrt(double((x-x0)*(x-x0)+(y-y0)*(y-y0))),
-				sqrt(double((x-x1)*(x-x1)+(y-y1)*(y-y1))));
-
-	double d;
-	if (x0==x1)
-		d=abs(x-x0);
-	else
-	{
-		double a=(double)(y1-y0)/(double)(x1-x0);
-		double b=y0-a*x0;
-		d=(a*x-y+b)/sqrt(a*a+1);
-	}
-	return fabs(d);
+double ArrowMarker::dist(int x, int y) {
+  if (!plot())
+    return -1.0;
+
+  const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+  const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+
+  const int x0 = xMap.transform(d_rect.left());
+  const int y0 = yMap.transform(d_rect.top());
+  const int x1 = xMap.transform(d_rect.right());
+  const int y1 = yMap.transform(d_rect.bottom());
+
+  int xmin = qMin(x0, x1);
+  int xmax = qMax(x0, x1);
+  int ymin = qMin(y0, y1);
+  int ymax = qMax(y0, y1);
+
+  if ((x > xmax || x < xmin || xmin == xmax) &&
+      (ymax < y || ymin > y || ymin == ymax))
+    // return the shortest distance to one of the ends
+    return qMin(sqrt(double((x - x0) * (x - x0) + (y - y0) * (y - y0))),
+                sqrt(double((x - x1) * (x - x1) + (y - y1) * (y - y1))));
+
+  double d;
+  if (x0 == x1)
+    d = abs(x - x0);
+  else {
+    double a = (double)(y1 - y0) / (double)(x1 - x0);
+    double b = y0 - a * x0;
+    d = (a * x - y + b) / sqrt(a * a + 1);
+  }
+  return fabs(d);
 }
 
-void ArrowMarker::setColor(const QColor& c)
-{
-if (linePen().color() == c)
-	return;
+void ArrowMarker::setColor(const QColor &c) {
+  if (linePen().color() == c)
+    return;
 
-QPen pen = linePen();
-pen.setColor(c);
-setLinePen(pen);
+  QPen pen = linePen();
+  pen.setColor(c);
+  setLinePen(pen);
 }
 
-void ArrowMarker::setWidth(double w)
-{
-if (linePen().width() == w)
-	return;
+void ArrowMarker::setWidth(double w) {
+  if (linePen().width() == w)
+    return;
 
-QPen pen = linePen();
-pen.setWidthF(w);
-setLinePen(pen);
+  QPen pen = linePen();
+  pen.setWidthF(w);
+  setLinePen(pen);
 }
 
-void ArrowMarker::setStyle(Qt::PenStyle style)
-{
-if (linePen().style() == style)
-	return;
+void ArrowMarker::setStyle(Qt::PenStyle style) {
+  if (linePen().style() == style)
+    return;
 
-QPen pen = linePen();
-pen.setStyle(style);
-setLinePen(pen);
+  QPen pen = linePen();
+  pen.setStyle(style);
+  setLinePen(pen);
 }
 
-void ArrowMarker::setHeadLength(int l)
-{
-if (d_head_length == l)
-	return;
+void ArrowMarker::setHeadLength(int l) {
+  if (d_head_length == l)
+    return;
 
-d_head_length=l;
+  d_head_length = l;
 }
 
-void ArrowMarker::setHeadAngle(int a)
-{
-	if (d_head_angle == a)
-		return;
+void ArrowMarker::setHeadAngle(int a) {
+  if (d_head_angle == a)
+    return;
 
-	d_head_angle = a;
+  d_head_angle = a;
 }
 
-void ArrowMarker::fillArrowHead(bool fill)
-{
-if (d_fill_head == fill)
-	return;
+void ArrowMarker::fillArrowHead(bool fill) {
+  if (d_fill_head == fill)
+    return;
 
-d_fill_head=fill;
+  d_fill_head = fill;
 }
 
-void ArrowMarker::setStartPoint(const QPoint& p)
-{
-if (d_start == p)
-	return;
+void ArrowMarker::setStartPoint(const QPoint &p) {
+  if (d_start == p)
+    return;
 
-d_start = p;
+  d_start = p;
 
-if (!plot())
-	return;
+  if (!plot())
+    return;
 
-d_rect.setLeft(plot()->invTransform(xAxis(), p.x()));
-d_rect.setTop(plot()->invTransform(yAxis(), p.y()));
+  d_rect.setLeft(plot()->invTransform(xAxis(), p.x()));
+  d_rect.setTop(plot()->invTransform(yAxis(), p.y()));
 }
 
-void ArrowMarker::setEndPoint(const QPoint& p)
-{
-if (d_end == p)
-	return;
+void ArrowMarker::setEndPoint(const QPoint &p) {
+  if (d_end == p)
+    return;
 
-d_end = p;
+  d_end = p;
 
-if (!plot())
-	return;
+  if (!plot())
+    return;
 
-d_rect.setRight(plot()->invTransform(xAxis(), p.x()));
-d_rect.setBottom(plot()->invTransform(yAxis(), p.y()));
+  d_rect.setRight(plot()->invTransform(xAxis(), p.x()));
+  d_rect.setBottom(plot()->invTransform(yAxis(), p.y()));
 }
 
-QPoint ArrowMarker::startPoint() const
-{
-    if (!plot())
-		return QPoint();
+QPoint ArrowMarker::startPoint() const {
+  if (!plot())
+    return QPoint();
 
-    return QPoint(plot()->transform(xAxis(), d_rect.left()),
+  return QPoint(plot()->transform(xAxis(), d_rect.left()),
                 plot()->transform(yAxis(), d_rect.top()));
 }
 
-QwtDoublePoint ArrowMarker::startPointCoord()
-{
-	return QwtDoublePoint(d_rect.left(), d_rect.top());
+QwtDoublePoint ArrowMarker::startPointCoord() {
+  return QwtDoublePoint(d_rect.left(), d_rect.top());
 }
 
-void ArrowMarker::setStartPoint(double x, double y)
-{
-if (d_rect.left() == x && d_rect.top() == y)
-	return;
+void ArrowMarker::setStartPoint(double x, double y) {
+  if (d_rect.left() == x && d_rect.top() == y)
+    return;
 
-d_rect.setLeft(x);
-d_rect.setTop(y);
+  d_rect.setLeft(x);
+  d_rect.setTop(y);
 
-if (!plot())
-	return;
+  if (!plot())
+    return;
 
-plot()->updateLayout();
-d_start = QPoint(plot()->transform(xAxis(), x), plot()->transform(yAxis(), y));
+  plot()->updateLayout();
+  d_start =
+      QPoint(plot()->transform(xAxis(), x), plot()->transform(yAxis(), y));
 }
 
-QPoint ArrowMarker::endPoint() const
-{
-    if (!plot())
-		return QPoint();
+QPoint ArrowMarker::endPoint() const {
+  if (!plot())
+    return QPoint();
 
-	return QPoint(plot()->transform(xAxis(), d_rect.right()),
-			plot()->transform(yAxis(), d_rect.bottom()));
+  return QPoint(plot()->transform(xAxis(), d_rect.right()),
+                plot()->transform(yAxis(), d_rect.bottom()));
 }
 
-void ArrowMarker::setEndPoint(double x, double y)
-{
-if (d_rect.right() == x && d_rect.bottom() == y)
-	return;
+void ArrowMarker::setEndPoint(double x, double y) {
+  if (d_rect.right() == x && d_rect.bottom() == y)
+    return;
 
-d_rect.setRight(x);
-d_rect.setBottom(y);
+  d_rect.setRight(x);
+  d_rect.setBottom(y);
 
-if (!plot())
-	return;
+  if (!plot())
+    return;
 
-plot()->updateLayout();
-d_end = QPoint(plot()->transform(xAxis(), x), plot()->transform(yAxis(), y));
+  plot()->updateLayout();
+  d_end = QPoint(plot()->transform(xAxis(), x), plot()->transform(yAxis(), y));
 }
 
-QwtDoublePoint ArrowMarker::endPointCoord()
-{
-return QwtDoublePoint(d_rect.right(), d_rect.bottom());
+QwtDoublePoint ArrowMarker::endPointCoord() {
+  return QwtDoublePoint(d_rect.right(), d_rect.bottom());
 }
 
-void ArrowMarker::setBoundingRect(double xs, double ys, double xe, double ye)
-{
-if (d_rect.left() == xs && d_rect.top() == ys &&
-	d_rect.right() == xe && d_rect.bottom() == ye)
-	return;
+void ArrowMarker::setBoundingRect(double xs, double ys, double xe, double ye) {
+  if (d_rect.left() == xs && d_rect.top() == ys && d_rect.right() == xe &&
+      d_rect.bottom() == ye)
+    return;
 
-d_rect.setLeft(xs);
-d_rect.setTop(ys);
-d_rect.setRight(xe);
-d_rect.setBottom(ye);
+  d_rect.setLeft(xs);
+  d_rect.setTop(ys);
+  d_rect.setRight(xe);
+  d_rect.setBottom(ye);
 
-if (!plot())
-	return;
+  if (!plot())
+    return;
 
-plot()->updateLayout();
-d_start = QPoint(plot()->transform(xAxis(), xs), plot()->transform(yAxis(), ys));
-d_end = QPoint(plot()->transform(xAxis(), xe), plot()->transform(yAxis(), ye));
+  plot()->updateLayout();
+  d_start =
+      QPoint(plot()->transform(xAxis(), xs), plot()->transform(yAxis(), ys));
+  d_end =
+      QPoint(plot()->transform(xAxis(), xe), plot()->transform(yAxis(), ye));
 }
 
-QwtDoubleRect ArrowMarker::boundingRect() const
-{
-	const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-	const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
-
-	const int x0 = xMap.transform(d_rect.left());
-	const int y0 = yMap.transform(d_rect.top());
-	const int x1 = xMap.transform(d_rect.right());
-	const int y1 = yMap.transform(d_rect.bottom());
-
-	return QwtDoubleRect(
-			x0<x1 ? d_rect.left() : d_rect.right(),
-			y0<y1 ? d_rect.top() : d_rect.bottom(),
-			qAbs(d_rect.left() - d_rect.right()),
-			qAbs(d_rect.top() - d_rect.bottom()));
+QwtDoubleRect ArrowMarker::boundingRect() const {
+  const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+  const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+
+  const int x0 = xMap.transform(d_rect.left());
+  const int y0 = yMap.transform(d_rect.top());
+  const int x1 = xMap.transform(d_rect.right());
+  const int y1 = yMap.transform(d_rect.bottom());
+
+  return QwtDoubleRect(x0 < x1 ? d_rect.left() : d_rect.right(),
+                       y0 < y1 ? d_rect.top() : d_rect.bottom(),
+                       qAbs(d_rect.left() - d_rect.right()),
+                       qAbs(d_rect.top() - d_rect.bottom()));
 }
 
-void ArrowMarker::updateBoundingRect()
-{
-const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+void ArrowMarker::updateBoundingRect() {
+  const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+  const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
 
-d_rect.setLeft(xMap.invTransform(d_start.x()));
-d_rect.setTop(yMap.invTransform(d_start.y()));
-d_rect.setRight(xMap.invTransform(d_end.x()));
-d_rect.setBottom(yMap.invTransform(d_end.y()));
+  d_rect.setLeft(xMap.invTransform(d_start.x()));
+  d_rect.setTop(yMap.invTransform(d_start.y()));
+  d_rect.setRight(xMap.invTransform(d_end.x()));
+  d_rect.setBottom(yMap.invTransform(d_end.y()));
 }
 
-void ArrowMarker::setEditable(bool yes)
-{
-	if (yes == d_editable)
-		return;
-	if (yes) {
-		d_editable = true;
-		plot()->canvas()->installEventFilter(this);
-	} else {
-		d_editable = false;
-		plot()->canvas()->removeEventFilter(this);
-	}
-	plot()->replot();
+void ArrowMarker::setEditable(bool yes) {
+  if (yes == d_editable)
+    return;
+  if (yes) {
+    d_editable = true;
+    plot()->canvas()->installEventFilter(this);
+  } else {
+    d_editable = false;
+    plot()->canvas()->removeEventFilter(this);
+  }
+  plot()->replot();
 }
 
 bool ArrowMarker::eventFilter(QObject *, QEvent *e) {
diff --git a/MantidPlot/src/ArrowMarker.h b/MantidPlot/src/ArrowMarker.h
index 5e1958c8268c6a9f0b6858e497b22e9f73891405..d407988641fbf8569ade5509a097c35305124d49 100644
--- a/MantidPlot/src/ArrowMarker.h
+++ b/MantidPlot/src/ArrowMarker.h
@@ -34,138 +34,142 @@
 /**\brief Draws lines and arrows on a QwtPlot.
  *
  * \section design Design Ideas
- * Move all the code for editing the end points from CanvasPicker here, so that we have it all in one place.
- * This approach will make adding new editable markers (e.g. polygons) much easier, and it will allow this
+ * Move all the code for editing the end points from CanvasPicker here, so that
+ *we have it all in one place.
+ * This approach will make adding new editable markers (e.g. polygons) much
+ *easier, and it will allow this
  * to be done in plug-ins.
  *
  * \sa ImageMarker, Legend
  */
-class ArrowMarker: public QObject, public QwtPlotMarker
-{
+class ArrowMarker : public QObject, public QwtPlotMarker {
 public:
-	enum Operation { None, MoveStart, MoveEnd, MoveBoth };
-    ArrowMarker();
-
-	//! Pixel coordinates of the start point
-	QPoint startPoint() const;
-	//! Sets the start point in pixel coordinates
-	void setStartPoint(const QPoint& p);
-
-	//! Pixel coordinates of the end point
-	QPoint endPoint() const;
-	//! Sets the end point in pixel coordinates
-	void setEndPoint(const QPoint& p);
-
-	//! Axes values coordinates of the start point
-	QwtDoublePoint startPointCoord();
-	//! Sets the start point in axes values coordinates
-	void setStartPoint(double x, double y);
-
-	//! Axes values coordinates of the end point
-	QwtDoublePoint endPointCoord();
-	//! Sets the end point in axes values coordinates
-	void setEndPoint(double x, double y);
-
-	void setColor(const QColor& c);
-	QColor color(){return linePen().color();};
-
-	//! Sets the width of the arrow line
-	void setWidth(double w);
-	//! The width of the arrow line
-	double width(){return linePen().widthF();};
-
-	//! Sets the pen style for the arrow line
-	void setStyle(Qt::PenStyle s);
-	//! The pen style of the arrow line
-	Qt::PenStyle style(){return linePen().style ();};
-
-	//! Specifies weather the start arrow should be drawn
-	void drawStartArrow(bool on = true){d_start_arrow = on;};
-	bool hasStartArrow(){return d_start_arrow;};
-
-	//! Specifies weather the end arrow should be drawn
-	void drawEndArrow(bool on = true){d_end_arrow = on;};
-	bool hasEndArrow(){return d_end_arrow;};
-
-	//! Length of the arrow head
-	int headLength(){return d_head_length;};
-	//! Sets the length of the arrow head
-	void setHeadLength(int l);
-
-	//! The angle of the arrow head
-	int headAngle(){return d_head_angle;};
-	//! Sets the angle of the arrow head
-	void setHeadAngle(int a);
-
-	bool filledArrowHead(){return d_fill_head;};
-	//! Specifies weather the arrow head should be filled with a brush
-	void fillArrowHead(bool fill = true);
-
-	//! Returns the shortest distance to the arrow line or to one of the arrow heads
-	double dist(int x, int y);
-
-	//! Returns the length of the arrow line
-	double length();
-
-    //! Returns the bounding rectangle in paint coordinates.
-        QRect rect() const {
-          return QRect(startPoint(), endPoint()).normalized();
-        };
-
-        //! Returns the bounding rectangle in plot coordinates.
-        QwtDoubleRect boundingRect() const override;
-        void setBoundingRect(double xs, double ys, double xe, double ye);
-
-	//! Recalculates the bounding rectangle in values coordinates using the pixel coordinats when the scales change
-	void updateBoundingRect();
-
-	//! Returns the state of #d_editable.
-	bool editable() const { return d_editable; }
-	//! Starts/ends editing of end points by the user.
-	void setEditable(bool yes);
-
-	//! Filters events for the canvas while #d_editable is true.
-        bool eventFilter(QObject *o, QEvent *e) override;
+  enum Operation { None, MoveStart, MoveEnd, MoveBoth };
+  ArrowMarker();
+
+  //! Pixel coordinates of the start point
+  QPoint startPoint() const;
+  //! Sets the start point in pixel coordinates
+  void setStartPoint(const QPoint &p);
+
+  //! Pixel coordinates of the end point
+  QPoint endPoint() const;
+  //! Sets the end point in pixel coordinates
+  void setEndPoint(const QPoint &p);
+
+  //! Axes values coordinates of the start point
+  QwtDoublePoint startPointCoord();
+  //! Sets the start point in axes values coordinates
+  void setStartPoint(double x, double y);
+
+  //! Axes values coordinates of the end point
+  QwtDoublePoint endPointCoord();
+  //! Sets the end point in axes values coordinates
+  void setEndPoint(double x, double y);
+
+  void setColor(const QColor &c);
+  QColor color() { return linePen().color(); };
+
+  //! Sets the width of the arrow line
+  void setWidth(double w);
+  //! The width of the arrow line
+  double width() { return linePen().widthF(); };
+
+  //! Sets the pen style for the arrow line
+  void setStyle(Qt::PenStyle s);
+  //! The pen style of the arrow line
+  Qt::PenStyle style() { return linePen().style(); };
+
+  //! Specifies weather the start arrow should be drawn
+  void drawStartArrow(bool on = true) { d_start_arrow = on; };
+  bool hasStartArrow() { return d_start_arrow; };
+
+  //! Specifies weather the end arrow should be drawn
+  void drawEndArrow(bool on = true) { d_end_arrow = on; };
+  bool hasEndArrow() { return d_end_arrow; };
+
+  //! Length of the arrow head
+  int headLength() { return d_head_length; };
+  //! Sets the length of the arrow head
+  void setHeadLength(int l);
+
+  //! The angle of the arrow head
+  int headAngle() { return d_head_angle; };
+  //! Sets the angle of the arrow head
+  void setHeadAngle(int a);
+
+  bool filledArrowHead() { return d_fill_head; };
+  //! Specifies weather the arrow head should be filled with a brush
+  void fillArrowHead(bool fill = true);
+
+  //! Returns the shortest distance to the arrow line or to one of the arrow
+  // heads
+  double dist(int x, int y);
+
+  //! Returns the length of the arrow line
+  double length();
+
+  //! Returns the bounding rectangle in paint coordinates.
+  QRect rect() const { return QRect(startPoint(), endPoint()).normalized(); };
+
+  //! Returns the bounding rectangle in plot coordinates.
+  QwtDoubleRect boundingRect() const override;
+  void setBoundingRect(double xs, double ys, double xe, double ye);
+
+  //! Recalculates the bounding rectangle in values coordinates using the pixel
+  // coordinats when the scales change
+  void updateBoundingRect();
+
+  //! Returns the state of #d_editable.
+  bool editable() const { return d_editable; }
+  //! Starts/ends editing of end points by the user.
+  void setEditable(bool yes);
+
+  //! Filters events for the canvas while #d_editable is true.
+  bool eventFilter(QObject *o, QEvent *e) override;
 
 private:
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &r) const override;
-        double theta(int xs, int ys, int xe, int ye) const;
+  double theta(int xs, int ys, int xe, int ye) const;
 
-	//! Flag specifying if the start arrow is visible
-	bool d_start_arrow;
+  //! Flag specifying if the start arrow is visible
+  bool d_start_arrow;
 
-	//! Flag specifying if the end arrow is visible
-	bool d_end_arrow;
+  //! Flag specifying if the end arrow is visible
+  bool d_end_arrow;
 
-	//! Flag specifying if the arrow head is filled with a brush
-	bool d_fill_head;
+  //! Flag specifying if the arrow head is filled with a brush
+  bool d_fill_head;
 
-	//! Angle of the arrow head
-	int d_head_angle;
+  //! Angle of the arrow head
+  int d_head_angle;
 
-	//! Length of the arrow head
-	int d_head_length;
+  //! Length of the arrow head
+  int d_head_length;
 
-	//! Pixel coordinates of the start point
-	QPoint d_start;
+  //! Pixel coordinates of the start point
+  QPoint d_start;
 
-	//! Pixel coordinates of the end point
-	QPoint d_end;
+  //! Pixel coordinates of the end point
+  QPoint d_end;
 
-	//! Bounding rectangle of the arrow in axes values coordinates
-	QwtDoubleRect d_rect;
-	//! Whether start and end point can be moved by the user.
-	bool d_editable;
+  //! Bounding rectangle of the arrow in axes values coordinates
+  QwtDoubleRect d_rect;
+  //! Whether start and end point can be moved by the user.
+  bool d_editable;
 
-	//! What editing operation is in progress.
-	Operation d_op;
+  //! What editing operation is in progress.
+  Operation d_op;
 
-	/**\brief Difference between mouse position where a MoveBoth operation started and startPoint().
-	 * When only one point is being moved, we can simply setStartPoint() or setEndPoint() to the
-	 * current mouse position, but when the editing starts in the middle of the line, we
-	 * need to remember this bit.
-	 */
-	QPoint d_op_startat;
+  /**\brief Difference between mouse position where a MoveBoth operation started
+   * and startPoint().
+   * When only one point is being moved, we can simply setStartPoint() or
+   * setEndPoint() to the
+   * current mouse position, but when the editing starts in the middle of the
+   * line, we
+   * need to remember this bit.
+   */
+  QPoint d_op_startat;
 };
 #endif
diff --git a/MantidPlot/src/AssociationsDialog.cpp b/MantidPlot/src/AssociationsDialog.cpp
index 7bc9da090b491166e3dbcb304bf25a978d86b0d4..7fbcaa045097abafd263dc9f14fa8539bdc50765 100644
--- a/MantidPlot/src/AssociationsDialog.cpp
+++ b/MantidPlot/src/AssociationsDialog.cpp
@@ -2,7 +2,8 @@
     File                 : AssociationsDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plot associations dialog
 
@@ -45,45 +46,47 @@
 #include <QApplication>
 #include <QMessageBox>
 
-AssociationsDialog::AssociationsDialog( Graph* g, Qt::WFlags fl )
-    : QDialog( g, fl )
-{
+AssociationsDialog::AssociationsDialog(Graph *g, Qt::WFlags fl)
+    : QDialog(g, fl) {
   setObjectName("AssociationsDialog");
-  setWindowTitle( tr( "MantidPlot - Plot Associations" ) );
+  setWindowTitle(tr("MantidPlot - Plot Associations"));
   setModal(true);
   setSizeGripEnabled(true);
   setFocus();
 
   QVBoxLayout *vl = new QVBoxLayout();
 
-  QHBoxLayout *hbox1 = new QHBoxLayout ();
-  hbox1->addWidget(new QLabel(tr( "Spreadsheet: " )));
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->addWidget(new QLabel(tr("Spreadsheet: ")));
 
   tableCaptionLabel = new QLabel();
   hbox1->addWidget(tableCaptionLabel);
   vl->addLayout(hbox1);
 
   table = new QTableWidget(3, 5);
-  table->horizontalHeader()->setClickable( false );
+  table->horizontalHeader()->setClickable(false);
   table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
   table->verticalHeader()->hide();
   table->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
-  table->setMaximumHeight(8*table->rowHeight(0));
-  table->setHorizontalHeaderLabels(QStringList() << tr("Column") << tr("X") << tr("Y") << tr("xErr") << tr("yErr"));
+  table->setMaximumHeight(8 * table->rowHeight(0));
+  table->setHorizontalHeaderLabels(QStringList() << tr("Column") << tr("X")
+                                                 << tr("Y") << tr("xErr")
+                                                 << tr("yErr"));
   vl->addWidget(table);
 
-  connect(table, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(processStateChange(QTableWidgetItem*)));
-  
+  connect(table, SIGNAL(itemClicked(QTableWidgetItem *)), this,
+          SLOT(processStateChange(QTableWidgetItem *)));
+
   associations = new QListWidget();
-  associations->setSelectionMode ( QListWidget::SingleSelection );
+  associations->setSelectionMode(QListWidget::SingleSelection);
   vl->addWidget(associations);
 
-  btnApply = new QPushButton(tr( "&Update curves" ));
-  btnOK = new QPushButton( tr( "&OK" ) );
-  btnOK->setDefault( true );
-  btnCancel = new QPushButton( tr( "&Cancel" ) );
+  btnApply = new QPushButton(tr("&Update curves"));
+  btnOK = new QPushButton(tr("&OK"));
+  btnOK->setDefault(true);
+  btnCancel = new QPushButton(tr("&Cancel"));
 
-  QHBoxLayout *hbox2 = new QHBoxLayout ();
+  QHBoxLayout *hbox2 = new QHBoxLayout();
   hbox2->addStretch();
   hbox2->addWidget(btnApply);
   hbox2->addWidget(btnOK);
@@ -94,23 +97,21 @@ AssociationsDialog::AssociationsDialog( Graph* g, Qt::WFlags fl )
 
   active_table = 0;
 
-  connect(associations, SIGNAL(currentRowChanged(int)), this, SLOT(updateTable(int)));
-  connect(btnOK, SIGNAL(clicked()),this, SLOT(accept()));
-  connect(btnCancel, SIGNAL(clicked()),this, SLOT(close()));
-  connect(btnApply, SIGNAL(clicked()),this, SLOT(updateCurves()));
+  connect(associations, SIGNAL(currentRowChanged(int)), this,
+          SLOT(updateTable(int)));
+  connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
+  connect(btnApply, SIGNAL(clicked()), this, SLOT(updateCurves()));
 
   setGraph(g);
-
 }
 
-void AssociationsDialog::accept()
-{
-updateCurves();
-close();
+void AssociationsDialog::accept() {
+  updateCurves();
+  close();
 }
 
-void AssociationsDialog::updateCurves()
-{
+void AssociationsDialog::updateCurves() {
   if (!graph)
     return;
 
@@ -123,27 +124,27 @@ void AssociationsDialog::updateCurves()
   QApplication::restoreOverrideCursor();
 }
 
-void AssociationsDialog::changePlotAssociation(int curve, const QString& text)
-{
-  DataCurve *c = dynamic_cast<DataCurve *>(graph->curve(curve)); //c_keys[curve]);
+void AssociationsDialog::changePlotAssociation(int curve, const QString &text) {
+  DataCurve *c =
+      dynamic_cast<DataCurve *>(graph->curve(curve)); // c_keys[curve]);
   if (!c)
-        return;
+    return;
 
-    if (c->plotAssociation() == text)
-        return;
+  if (c->plotAssociation() == text)
+    return;
 
   QStringList lst = text.split(",", QString::SkipEmptyParts);
-  if (lst.count() == 1){
+  if (lst.count() == 1) {
     c->setTitle(lst[0]);
-    if (auto b = dynamic_cast<BoxCurve*>(c))
+    if (auto b = dynamic_cast<BoxCurve *>(c))
       b->loadData();
-    else if (auto p = dynamic_cast<QwtPieCurve*>(c))
+    else if (auto p = dynamic_cast<QwtPieCurve *>(c))
       p->loadData();
-  } else if (lst.count() == 2){
+  } 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
+  } else if (lst.count() == 3) { // curve with error bars
     if (QwtErrorPlotCurve *er = dynamic_cast<QwtErrorPlotCurve *>(c)) {
       QString xColName = lst[0].remove("(X)");
       QString yColName = lst[1].remove("(Y)");
@@ -169,7 +170,8 @@ void AssociationsDialog::changePlotAssociation(int curve, const QString& text)
 
       QString xEndCol = lst[2].remove("(X)").remove("(A)");
       QString yEndCol = lst[3].remove("(Y)").remove("(M)");
-      if (v->vectorEndXAColName() != xEndCol || v->vectorEndYMColName() != yEndCol)
+      if (v->vectorEndXAColName() != xEndCol ||
+          v->vectorEndYMColName() != yEndCol)
         v->setVectorEnd(xEndCol, yEndCol);
       else
         v->loadData();
@@ -178,72 +180,68 @@ void AssociationsDialog::changePlotAssociation(int curve, const QString& text)
   graph->notifyChanges();
 }
 
-QString AssociationsDialog::plotAssociation(const QString& text)
-{
-QString s = text;
-QStringList lst = s.split(": ", QString::SkipEmptyParts);
-QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
-
-QString tableName = lst[0];
-s = tableName + "_" + cols[0];
-for (int i=1; i < (int)cols.count(); i++ )
-  s+="," + tableName + "_" + cols[i];
-return s;
+QString AssociationsDialog::plotAssociation(const QString &text) {
+  QString s = text;
+  QStringList lst = s.split(": ", QString::SkipEmptyParts);
+  QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
+
+  QString tableName = lst[0];
+  s = tableName + "_" + cols[0];
+  for (int i = 1; i < (int)cols.count(); i++)
+    s += "," + tableName + "_" + cols[i];
+  return s;
 }
 
-void AssociationsDialog::initTablesList(QList<MdiSubWindow *> lst, int curve)
-{
-tables = lst;
-active_table = 0;
+void AssociationsDialog::initTablesList(QList<MdiSubWindow *> lst, int curve) {
+  tables = lst;
+  active_table = 0;
 
-if (curve < 0 || curve >= static_cast<int>(associations->count()))
-  curve = 0;
+  if (curve < 0 || curve >= static_cast<int>(associations->count()))
+    curve = 0;
 
-associations->setCurrentRow (curve);
+  associations->setCurrentRow(curve);
 }
 
-Table * AssociationsDialog::findTable(int index)
-{
+Table *AssociationsDialog::findTable(int index) {
   QString text = associations->item(index)->text();
-  QStringList lst= text.split(":", QString::SkipEmptyParts);
-  foreach(MdiSubWindow *w, tables){
+  QStringList lst = text.split(":", QString::SkipEmptyParts);
+  foreach (MdiSubWindow *w, tables) {
     if (w->objectName() == lst[0])
       return dynamic_cast<Table *>(w);
   }
   return 0;
 }
 
-void AssociationsDialog::updateTable(int index)
-{
+void AssociationsDialog::updateTable(int index) {
   Table *t = findTable(index);
   if (!t)
     return;
 
-  if (active_table != t)
-  {
+  if (active_table != t) {
     active_table = t;
     tableCaptionLabel->setText(t->objectName());
     table->clearContents();
     table->setRowCount(t->numCols());
 
     QStringList colNames = t->colNames();
-    // this vector will tell which rows should be disabled (cause there's no data in them)
+    // this vector will tell which rows should be disabled (cause there's no
+    // data in them)
     std::vector<bool> disableRow;
     disableRow.resize(table->rowCount(), false);
-    for (int i=0; i<table->rowCount(); i++ )
-    {
+    for (int i = 0; i < table->rowCount(); i++) {
       QTableWidgetItem *cell = new QTableWidgetItem(colNames[i]);
-      cell->setBackground (QBrush(Qt::lightGray));
-      cell->setFlags (Qt::ItemIsEnabled);
+      cell->setBackground(QBrush(Qt::lightGray));
+      cell->setFlags(Qt::ItemIsEnabled);
       table->setItem(i, 0, cell);
 
-      // do we need to disable this row cause the corresponding curve it's empty?
+      // do we need to disable this row cause the corresponding curve it's
+      // empty?
       // (empty curves could cause crashes in many other places)
       bool allEmpty = true;
-      // Note possible confusion, here 'table' is the table that you see in the AssociationsDialog,
+      // Note possible confusion, here 'table' is the table that you see in the
+      // AssociationsDialog,
       // whereas t is the underlying data table (spreadsheet).
-      for (int dataRow = 0; dataRow < t->numRows() && allEmpty; dataRow++)
-      {
+      for (int dataRow = 0; dataRow < t->numRows() && allEmpty; dataRow++) {
         // use i (row in the associations table) as column index
         allEmpty = allEmpty & t->text(dataRow, i).isEmpty();
       }
@@ -251,226 +249,218 @@ void AssociationsDialog::updateTable(int index)
         disableRow[i] = true;
     }
 
-    for (int j=1; j < table->columnCount(); j++)
-    {
-      for (int i=0; i < table->rowCount(); i++ )
-      {
-          QTableWidgetItem *cell = new QTableWidgetItem();
-          cell->setBackground(QBrush(Qt::lightGray));
-          cell->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
-          table->setItem(i, j, cell);
-
-          // disable (but keep the checkbox, as set above)
-          if (disableRow[i])
-            cell->setFlags(Qt::NoItemFlags);
+    for (int j = 1; j < table->columnCount(); j++) {
+      for (int i = 0; i < table->rowCount(); i++) {
+        QTableWidgetItem *cell = new QTableWidgetItem();
+        cell->setBackground(QBrush(Qt::lightGray));
+        cell->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
+        table->setItem(i, j, cell);
+
+        // disable (but keep the checkbox, as set above)
+        if (disableRow[i])
+          cell->setFlags(Qt::NoItemFlags);
       }
     }
   }
   updateColumnTypes();
 }
 
-void AssociationsDialog::updateColumnTypes()
-{
-QString text = associations->currentItem()->text();
-QStringList lst = text.split(": ", QString::SkipEmptyParts);
-QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
+void AssociationsDialog::updateColumnTypes() {
+  QString text = associations->currentItem()->text();
+  QStringList lst = text.split(": ", QString::SkipEmptyParts);
+  QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
 
-QString xColName, yColName;
+  QString xColName, yColName;
 
-int n = (int)cols.count();
-if (n == 2){
-  xColName = cols[0].remove("(X)");
-  yColName = cols[1].remove("(Y)");
+  int n = (int)cols.count();
+  if (n == 2) {
+    xColName = cols[0].remove("(X)");
+    yColName = cols[1].remove("(Y)");
 
     table->showColumn(1);
-  table->hideColumn(3);
-  table->hideColumn(4);
-  }
-else if (n == 1){//box plots
-  yColName = cols[0];
-  table->hideColumn(1);
-  table->hideColumn(3);
-  table->hideColumn(4);
+    table->hideColumn(3);
+    table->hideColumn(4);
+  } else if (n == 1) { // box plots
+    yColName = cols[0];
+    table->hideColumn(1);
+    table->hideColumn(3);
+    table->hideColumn(4);
   }
 
-QTableWidgetItem* it;
-for (int i=0; i < table->rowCount(); i++ )
-{
-  it = table->item(i, 1);
+  QTableWidgetItem *it;
+  for (int i = 0; i < table->rowCount(); i++) {
+    it = table->item(i, 1);
 
-  if (table->item(i, 0)->text() == xColName)
-    it->setCheckState(Qt::Checked);
-  else
-    it->setCheckState(Qt::Unchecked);
+    if (table->item(i, 0)->text() == xColName)
+      it->setCheckState(Qt::Checked);
+    else
+      it->setCheckState(Qt::Unchecked);
 
-  it = table->item(i, 2);
+    it = table->item(i, 2);
 
-  if (table->item(i,0)->text() == yColName)
-    it->setCheckState(Qt::Checked);
-  else
-    it->setCheckState(Qt::Unchecked);
-}
+    if (table->item(i, 0)->text() == yColName)
+      it->setCheckState(Qt::Checked);
+    else
+      it->setCheckState(Qt::Unchecked);
+  }
 
-bool xerr = false, yerr = false, vectors = false;
-QString errColName, xEndColName, yEndColName;
-if (n > 2){
-  table->showColumn(3);
-  table->showColumn(4);
+  bool xerr = false, yerr = false, vectors = false;
+  QString errColName, xEndColName, yEndColName;
+  if (n > 2) {
+    table->showColumn(3);
+    table->showColumn(4);
 
-  if (cols[2].contains("(xErr)") || cols[2].contains("(yErr)")){//if error bars
-    table->horizontalHeaderItem(3)->setText(tr("xErr"));
-    table->horizontalHeaderItem(4)->setText(tr("yErr"));
+    if (cols[2].contains("(xErr)") ||
+        cols[2].contains("(yErr)")) { // if error bars
+      table->horizontalHeaderItem(3)->setText(tr("xErr"));
+      table->horizontalHeaderItem(4)->setText(tr("yErr"));
     }
 
-  if (cols[2].contains("(xErr)")){
-    xerr = true;
-    errColName = cols[2].remove("(xErr)");
-    } else if (cols[2].contains("(yErr)")){
-    yerr = true;
-    errColName = cols[2].remove("(yErr)");
-    } else if (cols.count() > 3 && cols[2].contains("(X)") && cols[3].contains("(Y)")){
-    vectors = true;
-    xEndColName = cols[2].remove("(X)");
-    yEndColName = cols[3].remove("(Y)");
-    table->horizontalHeaderItem(3)->setText(tr("xEnd"));
-    table->horizontalHeaderItem(4)->setText(tr("yEnd"));
-    } else if (cols.count() > 3 && cols[2].contains("(A)") && cols[3].contains("(M)")){
-    vectors = true;
-    xEndColName = cols[2].remove("(A)");
-    yEndColName = cols[3].remove("(M)");
-    table->horizontalHeaderItem(3)->setText(tr("Angle"));
-    table->horizontalHeaderItem(4)->setText(tr("Magn.","Magnitude, vector length"));
+    if (cols[2].contains("(xErr)")) {
+      xerr = true;
+      errColName = cols[2].remove("(xErr)");
+    } else if (cols[2].contains("(yErr)")) {
+      yerr = true;
+      errColName = cols[2].remove("(yErr)");
+    } else if (cols.count() > 3 && cols[2].contains("(X)") &&
+               cols[3].contains("(Y)")) {
+      vectors = true;
+      xEndColName = cols[2].remove("(X)");
+      yEndColName = cols[3].remove("(Y)");
+      table->horizontalHeaderItem(3)->setText(tr("xEnd"));
+      table->horizontalHeaderItem(4)->setText(tr("yEnd"));
+    } else if (cols.count() > 3 && cols[2].contains("(A)") &&
+               cols[3].contains("(M)")) {
+      vectors = true;
+      xEndColName = cols[2].remove("(A)");
+      yEndColName = cols[3].remove("(M)");
+      table->horizontalHeaderItem(3)->setText(tr("Angle"));
+      table->horizontalHeaderItem(4)
+          ->setText(tr("Magn.", "Magnitude, vector length"));
     }
-}
-
+  }
 
-for (int i=0; i < table->rowCount(); i++){
-  it = table->item(i, 3);
-  if (xerr || vectors){
-    if (table->item(i,0)->text() == errColName || table->item(i,0)->text() == xEndColName)
-      it->setCheckState(Qt::Checked);
-    else
-      it->setCheckState(Qt::Unchecked);
+  for (int i = 0; i < table->rowCount(); i++) {
+    it = table->item(i, 3);
+    if (xerr || vectors) {
+      if (table->item(i, 0)->text() == errColName ||
+          table->item(i, 0)->text() == xEndColName)
+        it->setCheckState(Qt::Checked);
+      else
+        it->setCheckState(Qt::Unchecked);
     } else
-    it->setCheckState(Qt::Unchecked);
-
-  it = table->item(i, 4);
-  if (yerr || vectors){
-    if (table->item(i,0)->text() == errColName || table->item(i,0)->text() == yEndColName)
-      it->setCheckState(Qt::Checked);
-    else
       it->setCheckState(Qt::Unchecked);
+
+    it = table->item(i, 4);
+    if (yerr || vectors) {
+      if (table->item(i, 0)->text() == errColName ||
+          table->item(i, 0)->text() == yEndColName)
+        it->setCheckState(Qt::Checked);
+      else
+        it->setCheckState(Qt::Unchecked);
     } else
-    it->setCheckState(Qt::Unchecked);
+      it->setCheckState(Qt::Unchecked);
   }
 }
 
-void AssociationsDialog::uncheckCol(int col)
-{
+void AssociationsDialog::uncheckCol(int col) {
   // Can't uncheck header column
-  if(col == 0)
+  if (col == 0)
     return;
 
-  for (int i = 0; i < table->rowCount(); i++ )
+  for (int i = 0; i < table->rowCount(); i++)
     table->item(i, col)->setCheckState(Qt::Unchecked);
 }
 
-void AssociationsDialog::setGraph(Graph *g)
-{
-    graph = g;
-
-    for (int i=0; i<graph->curves(); i++){
-        const QwtPlotItem *it = (QwtPlotItem *)graph->plotItem(i);
-        if (!it)
-            continue;
-        if (it->rtti() != QwtPlotItem::Rtti_PlotCurve)
-            continue;
-
-        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 + "_");
-            }
-        }
+void AssociationsDialog::setGraph(Graph *g) {
+  graph = g;
+
+  for (int i = 0; i < graph->curves(); i++) {
+    const QwtPlotItem *it = (QwtPlotItem *)graph->plotItem(i);
+    if (!it)
+      continue;
+    if (it->rtti() != QwtPlotItem::Rtti_PlotCurve)
+      continue;
+
+    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 + "_");
+      }
+    }
   }
-    associations->addItems(plotAssociationsList);
-    associations->setMaximumHeight((plotAssociationsList.count()+1)*associations->visualItemRect(associations->item(0)).height());
+  associations->addItems(plotAssociationsList);
+  associations->setMaximumHeight(
+      (plotAssociationsList.count() + 1) *
+      associations->visualItemRect(associations->item(0)).height());
 }
 
-void AssociationsDialog::updatePlotAssociation(int row, int col)
-{
-int index = associations->currentRow();
-QString text = associations->currentItem()->text();
-QStringList lst = text.split(": ", QString::SkipEmptyParts);
-QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
+void AssociationsDialog::updatePlotAssociation(int row, int col) {
+  int index = associations->currentRow();
+  QString text = associations->currentItem()->text();
+  QStringList lst = text.split(": ", QString::SkipEmptyParts);
+  QStringList cols = lst[1].split(",", QString::SkipEmptyParts);
 
-if (col == 1){
-  cols[0] = table->item(row, 0)->text() + "(X)";
-  text = lst[0] + ": " + cols.join(",");
-  }
-else if (col == 2){
-  if (cols.count() >= 2){
-    cols[1] = table->item(row, 0)->text() + "(Y)";
+  if (col == 1) {
+    cols[0] = table->item(row, 0)->text() + "(X)";
     text = lst[0] + ": " + cols.join(",");
-  } else // box or pie plots
-    text = lst[0] + ": " + table->item(row, 0)->text();
-  }
-else if (col == 3){
-  if (text.contains("(A)")){//vect XYAM curve
-    cols[2] = table->item(row, 0)->text() + "(A)";
-    text = lst[0] + ": " + cols.join(",");
-    }
-  else if (!text.contains("(A)") && text.count("(X)") == 1){
-    cols[2] = table->item(row, 0)->text() + "(xErr)";
-    text = lst[0] + ": " + cols.join(",");
-    uncheckCol(4);
+  } else if (col == 2) {
+    if (cols.count() >= 2) {
+      cols[1] = table->item(row, 0)->text() + "(Y)";
+      text = lst[0] + ": " + cols.join(",");
+    } else // box or pie plots
+      text = lst[0] + ": " + table->item(row, 0)->text();
+  } else if (col == 3) {
+    if (text.contains("(A)")) { // vect XYAM curve
+      cols[2] = table->item(row, 0)->text() + "(A)";
+      text = lst[0] + ": " + cols.join(",");
+    } else if (!text.contains("(A)") && text.count("(X)") == 1) {
+      cols[2] = table->item(row, 0)->text() + "(xErr)";
+      text = lst[0] + ": " + cols.join(",");
+      uncheckCol(4);
+    } else if (text.count("(X)") == 2) { // vect XYXY curve
+      cols[2] = table->item(row, 0)->text() + "(X)";
+      text = lst[0] + ": " + cols.join(",");
     }
-  else if (text.count("(X)") == 2){//vect XYXY curve
-    cols[2] = table->item(row, 0)->text() + "(X)";
-    text = lst[0] + ": " + cols.join(",");
-    }
-  }
-else if (col == 4){
-  if (text.contains("(M)")){//vect XYAM curve
-    cols[3] = table->item(row, 0)->text() + "(M)";
-    text = lst[0] + ": " + cols.join(",");
-    }
-  else if (!text.contains("(M)") && text.count("(X)") == 1){
-    cols[2] = table->item(row, 0)->text() + "(yErr)";
-    text = lst[0] + ": " + cols.join(",");
-    uncheckCol(3);
-    }
-  else if (text.count("(Y)") == 2){//vect XYXY curve
-    cols[3] = table->item(row, 0)->text() + "(Y)";
-    text = lst[0] + ": " + cols.join(",");
+  } else if (col == 4) {
+    if (text.contains("(M)")) { // vect XYAM curve
+      cols[3] = table->item(row, 0)->text() + "(M)";
+      text = lst[0] + ": " + cols.join(",");
+    } else if (!text.contains("(M)") && text.count("(X)") == 1) {
+      cols[2] = table->item(row, 0)->text() + "(yErr)";
+      text = lst[0] + ": " + cols.join(",");
+      uncheckCol(3);
+    } else if (text.count("(Y)") == 2) { // vect XYXY curve
+      cols[3] = table->item(row, 0)->text() + "(Y)";
+      text = lst[0] + ": " + cols.join(",");
     }
   }
 
-//change associations for error bars depending on the curve "index"
-QString old_as = plotAssociationsList[index];
-for (int i=0; i<(int)plotAssociationsList.count(); i++){
-  QString as = plotAssociationsList[i];
-  if (as.contains(old_as) && (as.contains("(xErr)") || as.contains("(yErr)"))){
-    QStringList ls = as.split(",", QString::SkipEmptyParts);
-    as = text + "," + ls[2];
-    plotAssociationsList[i] = as;
+  // change associations for error bars depending on the curve "index"
+  QString old_as = plotAssociationsList[index];
+  for (int i = 0; i < (int)plotAssociationsList.count(); i++) {
+    QString as = plotAssociationsList[i];
+    if (as.contains(old_as) &&
+        (as.contains("(xErr)") || as.contains("(yErr)"))) {
+      QStringList ls = as.split(",", QString::SkipEmptyParts);
+      as = text + "," + ls[2];
+      plotAssociationsList[i] = as;
     }
   }
 
-plotAssociationsList [index] = text;
-associations->item(index)->setText(text);
+  plotAssociationsList[index] = text;
+  associations->item(index)->setText(text);
 }
 
-void AssociationsDialog::processStateChange(QTableWidgetItem* item)
-{
+void AssociationsDialog::processStateChange(QTableWidgetItem *item) {
   // Ignore the header column
-  if(item->column() == 0)
+  if (item->column() == 0)
     return;
 
   // Ignore uncheck events
-  if(item->checkState() == Qt::Unchecked)
+  if (item->checkState() == Qt::Unchecked)
     return;
 
   // Make sure that's the only checked item in the columns
diff --git a/MantidPlot/src/AssociationsDialog.h b/MantidPlot/src/AssociationsDialog.h
index 2ffda91937daf0d9c105e3c4db0ec28686732320..76a60c21652a56ca30d275604b7f5614f233f8e7 100644
--- a/MantidPlot/src/AssociationsDialog.h
+++ b/MantidPlot/src/AssociationsDialog.h
@@ -2,7 +2,8 @@
     File                 : AssociationsDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plot associations dialog
 
@@ -42,39 +43,38 @@ class Graph;
 class MdiSubWindow;
 
 //! Plot associations dialog
-class AssociationsDialog : public QDialog
-{
-    Q_OBJECT
+class AssociationsDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    AssociationsDialog( Graph* g, Qt::WFlags fl = 0 );
+  AssociationsDialog(Graph *g, Qt::WFlags fl = 0);
 
-    void initTablesList(QList<MdiSubWindow *> lst, int curve);
+  void initTablesList(QList<MdiSubWindow *> lst, int curve);
 
 private slots:
-    void updateTable(int index);
-    void updateCurves();
-    void accept() override;
-    void processStateChange(QTableWidgetItem* item);
+  void updateTable(int index);
+  void updateCurves();
+  void accept() override;
+  void processStateChange(QTableWidgetItem *item);
 
 private:
-    void setGraph(Graph *g);
-  void changePlotAssociation(int curve, const QString& text);
-    void updateColumnTypes();
-    void uncheckCol(int col);
-    void updatePlotAssociation(int row, int col);
-    QString plotAssociation(const QString& text);
-    Table *findTable(int index);
+  void setGraph(Graph *g);
+  void changePlotAssociation(int curve, const QString &text);
+  void updateColumnTypes();
+  void uncheckCol(int col);
+  void updatePlotAssociation(int row, int col);
+  QString plotAssociation(const QString &text);
+  Table *findTable(int index);
 
-    QList <MdiSubWindow*> tables;
-    Table *active_table;
-    Graph *graph;
-    QStringList plotAssociationsList;
+  QList<MdiSubWindow *> tables;
+  Table *active_table;
+  Graph *graph;
+  QStringList plotAssociationsList;
 
-    QLabel* tableCaptionLabel;
-    QTableWidget *table;
-    QPushButton *btnOK, *btnCancel, *btnApply;
-    QListWidget* associations;
+  QLabel *tableCaptionLabel;
+  QTableWidget *table;
+  QPushButton *btnOK, *btnCancel, *btnApply;
+  QListWidget *associations;
 };
 
 #endif // ASSOCIATIONSDIALOG_H
diff --git a/MantidPlot/src/AxesDialog.cpp b/MantidPlot/src/AxesDialog.cpp
index 26d8f27a5fffd1897571a6f4c806892bfad5ebf0..33cb7295664785404022a4f33f0c10f7d8d09268 100644
--- a/MantidPlot/src/AxesDialog.cpp
+++ b/MantidPlot/src/AxesDialog.cpp
@@ -69,581 +69,903 @@ Description          : General plot options dialog
 #include "MantidQtAPI/ScaleEngine.h"
 
 /* XPM */
-static const char* bottom_scl_xpm[] = { "36 38 75 1", " 	c None", ".	c #FFFFFF",
-  "+	c #818181", "@	c #070707", "#	c #101010", "$	c #EEEEEE", "%	c #1D1D1D",
-  "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292", ";	c #242424",
-  ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A", ")	c #5E5E5E", "!	c #000000",
-  "~	c #C8C8C8", "{	c #D2D2D2", "]	c #090909", "^	c #060606", "/	c #FEFEFE",
-  "(	c #FCFCFC", "_	c #F7F7F7", ":	c #CECECE", "<	c #444444", "[	c #E0E0E0",
-  "}	c #464646", "|	c #E8E8E8", "1	c #282828", "2	c #D3D3D3", "3	c #D1D1D1",
-  "4	c #A4A4A4", "5	c #484848", "6	c #EBEBEB", "7	c #7D7D7D", "8	c #050505",
-  "9	c #7F7F7F", "0	c #FDFDFD", "a	c #7D6F6F", "b	c #F38C82", "c	c #E71E09",
-  "d	c #E82612", "e	c #FDEFEE", "f	c #E9321F", "g	c #F7B3AC", "h	c #E82B17",
-  "i	c #E82814", "j	c #F49C93", "k	c #EA3826", "l	c #FBD8D5", "m	c #F9CEC9",
-  "n	c #EA3E2C", "o	c #EF6D5F", "p	c #E71803", "q	c #F9CDC8", "r	c #FAD6D2",
-  "s	c #E7200B", "t	c #E71D08", "u	c #FEFCFC", "v	c #FEF7F7", "w	c #FAD2CE",
-  "x	c #ED5546", "y	c #FCE2E0", "z	c #ED5748", "A	c #FCEAE8", "B	c #EA3C2A",
-  "C	c #FAD7D3", "D	c #FAD5D1", "E	c #F6ACA5", "F	c #ED594A", "G	c #FDECEB",
-  "H	c #F2897E", "I	c #E71C07", "J	c #F28B80",
-  "....................................",
-  "......+@#+......$%......&*=-........",
-  "......;>,'......)!......%~{]........",
-  "......^/(^......_!........:<........",
-  "......^((^.......!.......[}|........",
-  "......123;.......!......456.........",
-  "......78^9.......!......*!!!........",
-  "+@#+................................",
-  ";>,'...(!0.......!.......!.....+@#+.",
-  "^/(^...!!!!!!!!!!!!!!!!!!!!!!..;>,'.",
-  "^((^...!aaaaaaaaaaaaaaaaaaaa!..^/(^.",
-  "123;..!!aaaaaaaaaaaaaaaaaaaa!!.^((^.",
-  "78^9...!aaaaaaaaaaaaaaaaaaaa!..123;.",
-  ".......!aaaaaaaaaaaaaaaaaaaa!..78^9.",
-  ".......!aaaaaaaaaaaaaaaaaaaa!.......",
-  "$%.....!aaaaaaaaaaaaaaaaaaaa!.......",
-  ")!.....!aaaaaaaaaaaaaaaaaaaa!..$%...",
-  "_!.....!aaaaaaaaaaaaaaaaaaaa!..)!...",
-  ".!....!!aaaaaaaaaaaaaaaaaaaa!!._!...",
-  ".!.....!aaaaaaaaaaaaaaaaaaaa!...!...",
-  ".!.....!aaaaaaaaaaaaaaaaaaaa!...!...",
-  ".......!aaaaaaaaaaaaaaaaaaaa!...!...",
-  "&*=-...!aaaaaaaaaaaaaaaaaaaa!.......",
-  "%~{]...!aaaaaaaaaaaaaaaaaaaa!..&*=-.",
-  "..:<...!aaaaaaaaaaaaaaaaaaaa!..%~{].",
-  ".[}|..!!aaaaaaaaaaaaaaaaaaaa!!...:<.",
-  "456....!aaaaaaaaaaaaaaaaaaaa!...[}|.",
-  "*!!!...!aaaaaaaaaaaaaaaaaaaa!..456..",
-  ".......!!!!!!!!!!!!!!!!!!!!!!..*!!!.",
-  ".........!........!.......!.........",
-  "....................................",
-  "........bcdb.....ef......ghij.......",
-  "........klmn.....op......fqrs.......",
-  "........t/ut.....vp........wx.......",
-  "........tuut......p.......yzA.......",
-  "........BCDk......p......EFG........",
-  "........HItJ......p......hppp.......",
-  "...................................." };
+static const char *bottom_scl_xpm[] = {
+    "36 38 75 1", " 	c None", ".	c #FFFFFF", "+	c #818181",
+    "@	c #070707", "#	c #101010", "$	c #EEEEEE", "%	c #1D1D1D",
+    "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292",
+    ";	c #242424", ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A",
+    ")	c #5E5E5E", "!	c #000000", "~	c #C8C8C8", "{	c #D2D2D2",
+    "]	c #090909", "^	c #060606", "/	c #FEFEFE", "(	c #FCFCFC",
+    "_	c #F7F7F7", ":	c #CECECE", "<	c #444444", "[	c #E0E0E0",
+    "}	c #464646", "|	c #E8E8E8", "1	c #282828", "2	c #D3D3D3",
+    "3	c #D1D1D1", "4	c #A4A4A4", "5	c #484848", "6	c #EBEBEB",
+    "7	c #7D7D7D", "8	c #050505", "9	c #7F7F7F", "0	c #FDFDFD",
+    "a	c #7D6F6F", "b	c #F38C82", "c	c #E71E09", "d	c #E82612",
+    "e	c #FDEFEE", "f	c #E9321F", "g	c #F7B3AC", "h	c #E82B17",
+    "i	c #E82814", "j	c #F49C93", "k	c #EA3826", "l	c #FBD8D5",
+    "m	c #F9CEC9", "n	c #EA3E2C", "o	c #EF6D5F", "p	c #E71803",
+    "q	c #F9CDC8", "r	c #FAD6D2", "s	c #E7200B", "t	c #E71D08",
+    "u	c #FEFCFC", "v	c #FEF7F7", "w	c #FAD2CE", "x	c #ED5546",
+    "y	c #FCE2E0", "z	c #ED5748", "A	c #FCEAE8", "B	c #EA3C2A",
+    "C	c #FAD7D3", "D	c #FAD5D1", "E	c #F6ACA5", "F	c #ED594A",
+    "G	c #FDECEB", "H	c #F2897E", "I	c #E71C07", "J	c #F28B80",
+    "....................................",
+    "......+@#+......$%......&*=-........",
+    "......;>,'......)!......%~{]........",
+    "......^/(^......_!........:<........",
+    "......^((^.......!.......[}|........",
+    "......123;.......!......456.........",
+    "......78^9.......!......*!!!........",
+    "+@#+................................",
+    ";>,'...(!0.......!.......!.....+@#+.",
+    "^/(^...!!!!!!!!!!!!!!!!!!!!!!..;>,'.",
+    "^((^...!aaaaaaaaaaaaaaaaaaaa!..^/(^.",
+    "123;..!!aaaaaaaaaaaaaaaaaaaa!!.^((^.",
+    "78^9...!aaaaaaaaaaaaaaaaaaaa!..123;.",
+    ".......!aaaaaaaaaaaaaaaaaaaa!..78^9.",
+    ".......!aaaaaaaaaaaaaaaaaaaa!.......",
+    "$%.....!aaaaaaaaaaaaaaaaaaaa!.......",
+    ")!.....!aaaaaaaaaaaaaaaaaaaa!..$%...",
+    "_!.....!aaaaaaaaaaaaaaaaaaaa!..)!...",
+    ".!....!!aaaaaaaaaaaaaaaaaaaa!!._!...",
+    ".!.....!aaaaaaaaaaaaaaaaaaaa!...!...",
+    ".!.....!aaaaaaaaaaaaaaaaaaaa!...!...",
+    ".......!aaaaaaaaaaaaaaaaaaaa!...!...",
+    "&*=-...!aaaaaaaaaaaaaaaaaaaa!.......",
+    "%~{]...!aaaaaaaaaaaaaaaaaaaa!..&*=-.",
+    "..:<...!aaaaaaaaaaaaaaaaaaaa!..%~{].",
+    ".[}|..!!aaaaaaaaaaaaaaaaaaaa!!...:<.",
+    "456....!aaaaaaaaaaaaaaaaaaaa!...[}|.",
+    "*!!!...!aaaaaaaaaaaaaaaaaaaa!..456..",
+    ".......!!!!!!!!!!!!!!!!!!!!!!..*!!!.",
+    ".........!........!.......!.........",
+    "....................................",
+    "........bcdb.....ef......ghij.......",
+    "........klmn.....op......fqrs.......",
+    "........t/ut.....vp........wx.......",
+    "........tuut......p.......yzA.......",
+    "........BCDk......p......EFG........",
+    "........HItJ......p......hppp.......",
+    "...................................."};
 
 /* XPM */
-static const char* top_scl_xpm[] = { "36 38 75 1", " 	c None", ".	c #FFFFFF",
-  "+	c #F38C82", "@	c #E71E09", "#	c #E82612", "$	c #FEFAFA", "%	c #E9321F",
-  "&	c #F7B3AC", "*	c #E82B17", "=	c #E82814", "-	c #F49C93", ";	c #EA3826",
-  ">	c #FBD8D5", ",	c #F9CEC9", "'	c #EA3E2C", ")	c #EF6D5F", "!	c #E71803",
-  "~	c #F9CDC8", "{	c #FAD6D2", "]	c #E7200B", "^	c #E71D08", "/	c #FEFEFE",
-  "(	c #FEFCFC", "_	c #FAD2CE", ":	c #ED5546", "<	c #FCE2E0", "[	c #ED5748",
-  "}	c #FCEAE8", "|	c #EA3C2A", "1	c #FAD7D3", "2	c #FAD5D1", "3	c #F6ACA5",
-  "4	c #ED594A", "5	c #FDF2F1", "6	c #F2897E", "7	c #E71C07", "8	c #F28B80",
-  "9	c #818181", "0	c #070707", "a	c #101010", "b	c #242424", "c	c #D5D5D5",
-  "d	c #C9C9C9", "e	c #2A2A2A", "f	c #000000", "g	c #060606", "h	c #FCFCFC",
-  "i	c #7D6F6F", "j	c #282828", "k	c #D3D3D3", "l	c #D1D1D1", "m	c #7D7D7D",
-  "n	c #050505", "o	c #7F7F7F", "p	c #FAFAFA", "q	c #1D1D1D", "r	c #5E5E5E",
-  "s	c #ACACAC", "t	c #151515", "u	c #121212", "v	c #929292", "w	c #C8C8C8",
-  "x	c #D2D2D2", "y	c #090909", "z	c #CECECE", "A	c #444444", "B	c #E0E0E0",
-  "C	c #464646", "D	c #E8E8E8", "E	c #A4A4A4", "F	c #484848", "G	c #F1F1F1",
-  "H	c #EEEEEE", "I	c #F7F7F7", "J	c #EBEBEB",
-  "....................................",
-  ".......+@#+.....$%......&*=-........",
-  ".......;>,'.....)!......%~{]........",
-  ".......^/(^......!........_:........",
-  ".......^((^......!.......<[}........",
-  ".......|12;......!......345.........",
-  ".......67^8......!......*!!!........",
-  "90a9................................",
-  "bcde....f........f.......f.....90a9.",
-  "g/hg...ffffffffffffffffffffff..bcde.",
-  "ghhg...fiiiiiiiiiiiiiiiiiiiif..g/hg.",
-  "jklb..ffiiiiiiiiiiiiiiiiiiiiff.ghhg.",
-  "mngo...fiiiiiiiiiiiiiiiiiiiif..jklb.",
-  ".......fiiiiiiiiiiiiiiiiiiiif..mngo.",
-  ".......fiiiiiiiiiiiiiiiiiiiif.......",
-  "pq.....fiiiiiiiiiiiiiiiiiiiif.......",
-  "rf.....fiiiiiiiiiiiiiiiiiiiif..pq...",
-  ".f.....fiiiiiiiiiiiiiiiiiiiif..rf...",
-  ".f....ffiiiiiiiiiiiiiiiiiiiiff..f...",
-  ".f.....fiiiiiiiiiiiiiiiiiiiif...f...",
-  ".f.....fiiiiiiiiiiiiiiiiiiiif...f...",
-  ".......fiiiiiiiiiiiiiiiiiiiif...f...",
-  "stuv...fiiiiiiiiiiiiiiiiiiiif.......",
-  "qwxy...fiiiiiiiiiiiiiiiiiiiif..stuv.",
-  "..zA...fiiiiiiiiiiiiiiiiiiiif..qwxy.",
-  ".BCD..ffiiiiiiiiiiiiiiiiiiiiff...zA.",
-  "EFG....fiiiiiiiiiiiiiiiiiiiif...BCD.",
-  "tfff...fiiiiiiiiiiiiiiiiiiiif..EFG..",
-  ".......ffffffffffffffffffffff..tfff.",
-  ".........f........f.......f.........",
-  "....................................",
-  ".......90a9......Hq......stuv.......",
-  ".......bcde......rf......qwxy.......",
-  ".......g/hg......If........zA.......",
-  ".......ghhg.......f.......BCD.......",
-  ".......jklb.......f......EFJ........",
-  ".......mngo.......f......tfff.......",
-  "...................................." };
+static const char *top_scl_xpm[] = {
+    "36 38 75 1", " 	c None", ".	c #FFFFFF", "+	c #F38C82",
+    "@	c #E71E09", "#	c #E82612", "$	c #FEFAFA", "%	c #E9321F",
+    "&	c #F7B3AC", "*	c #E82B17", "=	c #E82814", "-	c #F49C93",
+    ";	c #EA3826", ">	c #FBD8D5", ",	c #F9CEC9", "'	c #EA3E2C",
+    ")	c #EF6D5F", "!	c #E71803", "~	c #F9CDC8", "{	c #FAD6D2",
+    "]	c #E7200B", "^	c #E71D08", "/	c #FEFEFE", "(	c #FEFCFC",
+    "_	c #FAD2CE", ":	c #ED5546", "<	c #FCE2E0", "[	c #ED5748",
+    "}	c #FCEAE8", "|	c #EA3C2A", "1	c #FAD7D3", "2	c #FAD5D1",
+    "3	c #F6ACA5", "4	c #ED594A", "5	c #FDF2F1", "6	c #F2897E",
+    "7	c #E71C07", "8	c #F28B80", "9	c #818181", "0	c #070707",
+    "a	c #101010", "b	c #242424", "c	c #D5D5D5", "d	c #C9C9C9",
+    "e	c #2A2A2A", "f	c #000000", "g	c #060606", "h	c #FCFCFC",
+    "i	c #7D6F6F", "j	c #282828", "k	c #D3D3D3", "l	c #D1D1D1",
+    "m	c #7D7D7D", "n	c #050505", "o	c #7F7F7F", "p	c #FAFAFA",
+    "q	c #1D1D1D", "r	c #5E5E5E", "s	c #ACACAC", "t	c #151515",
+    "u	c #121212", "v	c #929292", "w	c #C8C8C8", "x	c #D2D2D2",
+    "y	c #090909", "z	c #CECECE", "A	c #444444", "B	c #E0E0E0",
+    "C	c #464646", "D	c #E8E8E8", "E	c #A4A4A4", "F	c #484848",
+    "G	c #F1F1F1", "H	c #EEEEEE", "I	c #F7F7F7", "J	c #EBEBEB",
+    "....................................",
+    ".......+@#+.....$%......&*=-........",
+    ".......;>,'.....)!......%~{]........",
+    ".......^/(^......!........_:........",
+    ".......^((^......!.......<[}........",
+    ".......|12;......!......345.........",
+    ".......67^8......!......*!!!........",
+    "90a9................................",
+    "bcde....f........f.......f.....90a9.",
+    "g/hg...ffffffffffffffffffffff..bcde.",
+    "ghhg...fiiiiiiiiiiiiiiiiiiiif..g/hg.",
+    "jklb..ffiiiiiiiiiiiiiiiiiiiiff.ghhg.",
+    "mngo...fiiiiiiiiiiiiiiiiiiiif..jklb.",
+    ".......fiiiiiiiiiiiiiiiiiiiif..mngo.",
+    ".......fiiiiiiiiiiiiiiiiiiiif.......",
+    "pq.....fiiiiiiiiiiiiiiiiiiiif.......",
+    "rf.....fiiiiiiiiiiiiiiiiiiiif..pq...",
+    ".f.....fiiiiiiiiiiiiiiiiiiiif..rf...",
+    ".f....ffiiiiiiiiiiiiiiiiiiiiff..f...",
+    ".f.....fiiiiiiiiiiiiiiiiiiiif...f...",
+    ".f.....fiiiiiiiiiiiiiiiiiiiif...f...",
+    ".......fiiiiiiiiiiiiiiiiiiiif...f...",
+    "stuv...fiiiiiiiiiiiiiiiiiiiif.......",
+    "qwxy...fiiiiiiiiiiiiiiiiiiiif..stuv.",
+    "..zA...fiiiiiiiiiiiiiiiiiiiif..qwxy.",
+    ".BCD..ffiiiiiiiiiiiiiiiiiiiiff...zA.",
+    "EFG....fiiiiiiiiiiiiiiiiiiiif...BCD.",
+    "tfff...fiiiiiiiiiiiiiiiiiiiif..EFG..",
+    ".......ffffffffffffffffffffff..tfff.",
+    ".........f........f.......f.........",
+    "....................................",
+    ".......90a9......Hq......stuv.......",
+    ".......bcde......rf......qwxy.......",
+    ".......g/hg......If........zA.......",
+    ".......ghhg.......f.......BCD.......",
+    ".......jklb.......f......EFJ........",
+    ".......mngo.......f......tfff.......",
+    "...................................."};
 
 /* XPM */
-static const char* left_scl_xpm[] = { "36 36 72 1", " 	c None", ".	c #FFFFFF",
-  "+	c #818181", "@	c #070707", "#	c #101010", "$	c #FAFAFA", "%	c #1D1D1D",
-  "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292", ";	c #242424",
-  ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A", ")	c #5E5E5E", "!	c #000000",
-  "~	c #C8C8C8", "{	c #D2D2D2", "]	c #090909", "^	c #060606", "/	c #FEFEFE",
-  "(	c #FCFCFC", "_	c #CECECE", ":	c #444444", "<	c #E0E0E0", "[	c #464646",
-  "}	c #E8E8E8", "|	c #282828", "1	c #D3D3D3", "2	c #D1D1D1", "3	c #A4A4A4",
-  "4	c #484848", "5	c #F1F1F1", "6	c #7D7D7D", "7	c #050505", "8	c #7F7F7F",
-  "9	c #F38C82", "0	c #E71E09", "a	c #E82612", "b	c #EA3826", "c	c #FBD8D5",
-  "d	c #F9CEC9", "e	c #EA3E2C", "f	c #E71D08", "g	c #FEFCFC", "h	c #7D6F6F",
-  "i	c #EA3C2A", "j	c #FAD7D3", "k	c #FAD5D1", "l	c #F2897E", "m	c #E71C07",
-  "n	c #F28B80", "o	c #FEFAFA", "p	c #E9321F", "q	c #EF6D5F", "r	c #E71803",
-  "s	c #F7B3AC", "t	c #E82B17", "u	c #E82814", "v	c #F49C93", "w	c #F9CDC8",
-  "x	c #FAD6D2", "y	c #E7200B", "z	c #FAD2CE", "A	c #ED5546", "B	c #FCE2E0",
-  "C	c #ED5748", "D	c #FCEAE8", "E	c #F6ACA5", "F	c #ED594A", "G	c #FDF2F1",
-  ".......+@#+......$%......&*=-.......",
-  ".......;>,'......)!......%~{].......",
-  ".......^/(^.......!........_:.......",
-  ".......^((^.......!.......<[}.......",
-  ".......|12;.......!......345........",
-  ".......67^8.......!......*!!!.......",
-  "....................................",
-  ".90a9...!........!.......!.....+@#+.",
-  ".bcde..!!!!!!!!!!!!!!!!!!!!!!..;>,'.",
-  ".f/gf..!hhhhhhhhhhhhhhhhhhhh!..^/(^.",
-  ".fggf.!!hhhhhhhhhhhhhhhhhhhh!!.^((^.",
-  ".ijkb..!hhhhhhhhhhhhhhhhhhhh!..|12;.",
-  ".lmfn..!hhhhhhhhhhhhhhhhhhhh!..67^8.",
-  ".......!hhhhhhhhhhhhhhhhhhhh!.......",
-  ".......!hhhhhhhhhhhhhhhhhhhh!.......",
-  "..op...!hhhhhhhhhhhhhhhhhhhh!...%...",
-  "..qr...!hhhhhhhhhhhhhhhhhhhh!..)!...",
-  "...r..!!hhhhhhhhhhhhhhhhhhhh!!..!...",
-  "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
-  "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
-  "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
-  ".......!hhhhhhhhhhhhhhhhhhhh!.......",
-  ".stuv..!hhhhhhhhhhhhhhhhhhhh!..&*=-.",
-  ".pwxy..!hhhhhhhhhhhhhhhhhhhh!..%~{].",
-  "...zA.!!hhhhhhhhhhhhhhhhhhhh!!..._:.",
-  "..BCD..!hhhhhhhhhhhhhhhhhhhh!...<[}.",
-  ".EFG...!hhhhhhhhhhhhhhhhhhhh!..34...",
-  ".trrr..!!!!!!!!!!!!!!!!!!!!!!..*!!!.",
-  ".........!........!.......!.........",
-  "....................................",
-  ".......+@#+......$%......&*=-.......",
-  ".......;>,'......)!......%~{].......",
-  ".......^/(^.......!........_:.......",
-  ".......^((^.......!.......<[}.......",
-  ".......|12;.......!......345........",
-  ".......67^8.......!......*!!!......." };
+static const char *left_scl_xpm[] = {
+    "36 36 72 1", " 	c None", ".	c #FFFFFF", "+	c #818181",
+    "@	c #070707", "#	c #101010", "$	c #FAFAFA", "%	c #1D1D1D",
+    "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292",
+    ";	c #242424", ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A",
+    ")	c #5E5E5E", "!	c #000000", "~	c #C8C8C8", "{	c #D2D2D2",
+    "]	c #090909", "^	c #060606", "/	c #FEFEFE", "(	c #FCFCFC",
+    "_	c #CECECE", ":	c #444444", "<	c #E0E0E0", "[	c #464646",
+    "}	c #E8E8E8", "|	c #282828", "1	c #D3D3D3", "2	c #D1D1D1",
+    "3	c #A4A4A4", "4	c #484848", "5	c #F1F1F1", "6	c #7D7D7D",
+    "7	c #050505", "8	c #7F7F7F", "9	c #F38C82", "0	c #E71E09",
+    "a	c #E82612", "b	c #EA3826", "c	c #FBD8D5", "d	c #F9CEC9",
+    "e	c #EA3E2C", "f	c #E71D08", "g	c #FEFCFC", "h	c #7D6F6F",
+    "i	c #EA3C2A", "j	c #FAD7D3", "k	c #FAD5D1", "l	c #F2897E",
+    "m	c #E71C07", "n	c #F28B80", "o	c #FEFAFA", "p	c #E9321F",
+    "q	c #EF6D5F", "r	c #E71803", "s	c #F7B3AC", "t	c #E82B17",
+    "u	c #E82814", "v	c #F49C93", "w	c #F9CDC8", "x	c #FAD6D2",
+    "y	c #E7200B", "z	c #FAD2CE", "A	c #ED5546", "B	c #FCE2E0",
+    "C	c #ED5748", "D	c #FCEAE8", "E	c #F6ACA5", "F	c #ED594A",
+    "G	c #FDF2F1", ".......+@#+......$%......&*=-.......",
+    ".......;>,'......)!......%~{].......",
+    ".......^/(^.......!........_:.......",
+    ".......^((^.......!.......<[}.......",
+    ".......|12;.......!......345........",
+    ".......67^8.......!......*!!!.......",
+    "....................................",
+    ".90a9...!........!.......!.....+@#+.",
+    ".bcde..!!!!!!!!!!!!!!!!!!!!!!..;>,'.",
+    ".f/gf..!hhhhhhhhhhhhhhhhhhhh!..^/(^.",
+    ".fggf.!!hhhhhhhhhhhhhhhhhhhh!!.^((^.",
+    ".ijkb..!hhhhhhhhhhhhhhhhhhhh!..|12;.",
+    ".lmfn..!hhhhhhhhhhhhhhhhhhhh!..67^8.",
+    ".......!hhhhhhhhhhhhhhhhhhhh!.......",
+    ".......!hhhhhhhhhhhhhhhhhhhh!.......",
+    "..op...!hhhhhhhhhhhhhhhhhhhh!...%...",
+    "..qr...!hhhhhhhhhhhhhhhhhhhh!..)!...",
+    "...r..!!hhhhhhhhhhhhhhhhhhhh!!..!...",
+    "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
+    "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
+    "...r...!hhhhhhhhhhhhhhhhhhhh!...!...",
+    ".......!hhhhhhhhhhhhhhhhhhhh!.......",
+    ".stuv..!hhhhhhhhhhhhhhhhhhhh!..&*=-.",
+    ".pwxy..!hhhhhhhhhhhhhhhhhhhh!..%~{].",
+    "...zA.!!hhhhhhhhhhhhhhhhhhhh!!..._:.",
+    "..BCD..!hhhhhhhhhhhhhhhhhhhh!...<[}.",
+    ".EFG...!hhhhhhhhhhhhhhhhhhhh!..34...",
+    ".trrr..!!!!!!!!!!!!!!!!!!!!!!..*!!!.",
+    ".........!........!.......!.........",
+    "....................................",
+    ".......+@#+......$%......&*=-.......",
+    ".......;>,'......)!......%~{].......",
+    ".......^/(^.......!........_:.......",
+    ".......^((^.......!.......<[}.......",
+    ".......|12;.......!......345........",
+    ".......67^8.......!......*!!!......."};
 
 /* XPM */
-static const char* right_scl_xpm[] = { "36 36 72 1", " 	c None", ".	c #FFFFFF",
-  "+	c #818181", "@	c #070707", "#	c #101010", "$	c #FAFAFA", "%	c #1D1D1D",
-  "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292", ";	c #242424",
-  ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A", ")	c #5E5E5E", "!	c #000000",
-  "~	c #C8C8C8", "{	c #D2D2D2", "]	c #090909", "^	c #060606", "/	c #FEFEFE",
-  "(	c #FCFCFC", "_	c #CECECE", ":	c #444444", "<	c #E0E0E0", "[	c #464646",
-  "}	c #E8E8E8", "|	c #282828", "1	c #D3D3D3", "2	c #D1D1D1", "3	c #A4A4A4",
-  "4	c #484848", "5	c #F1F1F1", "6	c #7D7D7D", "7	c #050505", "8	c #7F7F7F",
-  "9	c #F38C82", "0	c #E71E09", "a	c #E82612", "b	c #EA3826", "c	c #FBD8D5",
-  "d	c #F9CEC9", "e	c #EA3E2C", "f	c #7D6F6F", "g	c #E71D08", "h	c #FEFCFC",
-  "i	c #EA3C2A", "j	c #FAD7D3", "k	c #FAD5D1", "l	c #F2897E", "m	c #E71C07",
-  "n	c #F28B80", "o	c #FEFAFA", "p	c #E9321F", "q	c #EF6D5F", "r	c #E71803",
-  "s	c #F7B3AC", "t	c #E82B17", "u	c #E82814", "v	c #F49C93", "w	c #F9CDC8",
-  "x	c #FAD6D2", "y	c #E7200B", "z	c #FAD2CE", "A	c #ED5546", "B	c #FCE2E0",
-  "C	c #ED5748", "D	c #FCEAE8", "E	c #F6ACA5", "F	c #ED594A", "G	c #FDF2F1",
-  ".......+@#+......$%......&*=-.......",
-  ".......;>,'......)!......%~{].......",
-  ".......^/(^.......!........_:.......",
-  ".......^((^.......!.......<[}.......",
-  ".......|12;.......!......345........",
-  ".......67^8.......!......*!!!.......",
-  "....................................",
-  ".+@#+...!........!.......!.....90a9.",
-  ".;>,'..!!!!!!!!!!!!!!!!!!!!!!..bcde.",
-  ".^/(^..!ffffffffffffffffffff!..g/hg.",
-  ".^((^.!!ffffffffffffffffffff!!.ghhg.",
-  ".|12;..!ffffffffffffffffffff!..ijkb.",
-  ".67^8..!ffffffffffffffffffff!..lmgn.",
-  ".......!ffffffffffffffffffff!.......",
-  ".......!ffffffffffffffffffff!.......",
-  ".$%....!ffffffffffffffffffff!...op..",
-  ".)!....!ffffffffffffffffffff!...qr..",
-  "..!...!!ffffffffffffffffffff!!...r..",
-  "..!....!ffffffffffffffffffff!....r..",
-  "..!....!ffffffffffffffffffff!....r..",
-  "..!....!ffffffffffffffffffff!....r..",
-  ".......!ffffffffffffffffffff!.......",
-  ".&*=-..!ffffffffffffffffffff!..stuv.",
-  ".%~{]..!ffffffffffffffffffff!..pwxy.",
-  "..._:.!!ffffffffffffffffffff!!...zA.",
-  "..<[}..!ffffffffffffffffffff!...BCD.",
-  ".345...!ffffffffffffffffffff!..EFG..",
-  ".*!!!..!!!!!!!!!!!!!!!!!!!!!!..trrr.",
-  ".........!........!.......!.........",
-  "....................................",
-  ".......+@#+......$%......&*=-.......",
-  ".......;>,'......)!......%~{].......",
-  ".......^/(^.......!........_:.......",
-  ".......^((^.......!.......<[}.......",
-  ".......|12;.......!......345........",
-  ".......67^8.......!......*!!!......." };
-
-static const char* image2_data[] =
-{ "74 77 171 2", "  	c None", ". 	c #FFFFFF", "+ 	c #E0E0E0",
-"@ 	c #FAFAFA", "# 	c #363636", "$ 	c #ABABAB", "% 	c #000000",
-"& 	c #BDBDBD", "* 	c #737373", "= 	c #858585", "- 	c #FFE8E8",
-"; 	c #FFF7F7", "> 	c #FFD1D1", ", 	c #FFF0F0", "' 	c #E6E6E6",
-") 	c #FFB2B2", "! 	c #FFE6E6", "~ 	c #FF6666", "{ 	c #FFCCCC",
-"] 	c #C9C9C9", "^ 	c #939493", "/ 	c #808080", "( 	c #878787",
-"_ 	c #D6D6D6", ": 	c #969696", "< 	c #030303", "[ 	c #383838",
-"} 	c #4C4C4C", "| 	c #1A1A1A", "1 	c #080808", "2 	c #C2C2C2",
-"3 	c #EBEBEB", "4 	c #F0F0F0", "5 	c #8C8C8C", "6 	c #7A7A7A",
-"7 	c #A3A3A3", "8 	c #999999", "9 	c #A1A1A1", "0 	c #828282",
-"a 	c #949494", "b 	c #F2F2F2", "c 	c #474747", "d 	c #545454",
-"e 	c #0F0F0F", "f 	c #B5B5B5", "g 	c #CFCFCF", "h 	c #262626",
-"i 	c #333333", "j 	c #DEDEDE", "k 	c #FDFDFD", "l 	c #D7D7D7",
-"m 	c #B7B7B7", "n 	c #C4C4C4", "o 	c #F7F7F7", "p 	c #CCCCCC",
-"q 	c #2E2E2E", "r 	c #B2B2B2", "s 	c #DFDFDF", "t 	c #ACACAC",
-"u 	c #ADADAD", "v 	c #D3D3D3", "w 	c #CDCDCD", "x 	c #AAAAAA",
-"y 	c #D4C3C3", "z 	c #A9A9A9", "A 	c #AAA8A8", "B 	c #DB7F7F",
-"C 	c #E3E3E3", "D 	c #E5E5E5", "E 	c #F2DADA", "F 	c #B19999",
-"G 	c #FFC4C4", "H 	c #D2D2D2", "I 	c #FFD4D4", "J 	c #EA6565",
-"K 	c #E2E2E2", "L 	c #FFA1A1", "M 	c #C8C8C8", "N 	c #AFAFAF",
-"O 	c #FF9999", "P 	c #F5C6C6", "Q 	c #E9E9E9", "R 	c #B6B6B6",
-"S 	c #CFB4B4", "T 	c #B9B9B9", "U 	c #F5F5F5", "V 	c #ACA7A7",
-"W 	c #EAEAEA", "X 	c #F9F9F9", "Y 	c #B8B8B8", "Z 	c #C0A6A6",
-"` 	c #B4B4B4", " .	c #EFEFEF", "..	c #F2C3C3", "+.	c #EEEEEE",
-"@.	c #BCBCBC", "#.	c #C5C5C5", "$.	c #DADADA", "%.	c #BEBEBE",
-"&.	c #B0B0B0", "*.	c #FBFBFB", "=.	c #C6C6C6", "-.	c #B1B1B1",
-";.	c #BABABA", ">.	c #AEAEAE", ",.	c #D0D0D0", "'.	c #FCFCFC",
-").	c #141414", "!.	c #D8D8D8", "~.	c #C7C7C7", "{.	c #575757",
-"].	c #3D3D3D", "^.	c #C3C3C3", "/.	c #5E5E5E", "(.	c #7D7D7D",
-"_.	c #B3B3B3", ":.	c #F6C8C8", "<.	c #757575", "[.	c #919191",
-"}.	c #CAB3B3", "|.	c #EDEDED", "1.	c #ADA8A8", "2.	c #666666",
-"3.	c #2B2B2B", "4.	c #BBBBBB", "5.	c #C9AAAA", "6.	c #292929",
-"7.	c #D4D4D4", "8.	c #FBC9C9", "9.	c #E8E8E8", "0.	c #9C9C9C",
-"a.	c #E4E4E4", "b.	c #E7E7E7", "c.	c #CACACA", "d.	c #C1C1C1",
-"e.	c #E39090", "f.	c #CBCBCB", "g.	c #ADA3A3", "h.	c #C8B0B0",
-"i.	c #F59A9A", "j.	c #C0A9A9", "k.	c #C9BFBF", "l.	c #7A4747",
-"m.	c #A18C8C", "n.	c #8C8282", "o.	c #332929", "p.	c #242424",
-"q.	c #0A0A0A", "r.	c #454545", "s.	c #595959", "t.	c #525252",
-"u.	c #5C5C5C", "v.	c #D9D9D9", "w.	c #121212", "x.	c #8A8A8A",
-"y.	c #171717", "z.	c #A8A8A8", "A.	c #696969", "B.	c #707070",
-"C.	c #9E9E9E", "D.	c #404040", "E.	c #616161", "F.	c #8F8F8F",
-"G.	c #4F4F4F", "H.	c #050505", "I.	c #DBDBDB", "J.	c #4A4A4A",
-"K.	c #212121", "L.	c #3B3B3B", "M.	c #636363", "N.	c #D1D1D1",
-". . . . . . . . . . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . $ % & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . * % = . . . . . . . . . . . - . . . . . . . . . . . ; > . . . . . . . . . . . . , . . . . . . . . . . . - - . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . ] ^ / ( _ . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . : < [ } | 1 ] ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . 2 ' . . 3 % / ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . . 4 % 5 ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . . 6 1 + ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . 7 < 8 @ 5 % 9 . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . 0 < a . b c % d . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . b d e f . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". g h i j . . . . ' % . . . . . . . . . . . . ) . . . . k l m m m n o ! ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-"p 1 q $ r r r g . ' % . . . . . . . . . . . . ) . . . s t u ] v w r x y ~ . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-"7 i i i i i i : . ' % . . . . . . . . . . . . ) . . p z _ . . . . . l A B . . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . ) . C x D . . . . . . . E F ] . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . G . u H . . . . . . . . I J x K . . . . . . . . . . { . . . . . . . . . . . L G . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { M N . . . . . . . . . { ~ _ $ o . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . P x Q . . . . . . . . . { ~ . & R . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . S T . . . . . . . . . . { ~ . U $ _ . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . 4 V W . . . . . . . . . . { ~ . . K x X . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . Y Z . . . . . . . . . . . { ~ . . . ` n . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . .  .x ... . . . . . . . . . . { ~ . . . +.$ +.. . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . @.n { . . . . . . . . . . . { ~ . . . . #.R . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . x +.{ . . . . . . . . . . . { ~ . . . . X z o . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . $.u . { . . . . . . . . . . . { ~ . . . . . %.&.*.. . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . ` =.. { . . . . . . . . . . . { ~ . . . . . . -.=.. . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . 4 z X . { . . . . . . . . . . . { ~ . . . . . . + t . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . #.;.. . { . . . . . . . . . . . { ~ . . . . . . . >.v . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . u $.. . { . . . . . . . . . . . { ~ . . . . . . . _ t . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . n 2 . ' % . . . . . . . + t k . . { . . . . . . . . . . . { ~ . . . . . . . . t ,.. . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . '.& ).5 . ' % . . . . . . . m #.. . . { . . . . . . . . . . . { ~ . . . . . . . . !.t . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . f % % % ~.. ' % . . . . . . . x W . . . { . . . . . . . . . . . { ~ . . . . . . . . . N ] . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . a 1 @ . ' % . . . . . . s u . . . . { . . . . . . . . . . . { ~ . . . . . . . . . l u k { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . {.].. . ' % . . . . . . %.%.. . . . { . . . . . . . . . . . { ~ . . . . . . . . . . r ^.{ . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . | 6 . U /.% (.. . . . . _.' . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . 4 u :.. . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . + % r . o <.% [.. . . . o $ '.. . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . ^.}.. . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . 7 % |.. . ' % . . . . . ,._.. . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . o 1.D . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . 2.3.. . . ' % . . . . . 4.=.. . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . 5.-.. . . . . . . . . . O { . . . . . . . . . . . ",
-". . p p 6.} p + . ' % . . . . . _.7.. . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . 8.t ,.. . . . . . . . . O { . . . . . . . . . . . ",
-". 9.i i i i i 0.. ' % . . . . . x +.. . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { C x a.. . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . x . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . ,.u . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . b.t . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . &.4.. . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . ^.T . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . X u c.. . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . m H . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . +.$ p . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . t C . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . +.x _ . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . z X . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . + x _ . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . U x . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . K x H . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . a.f . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . ' &.d.X O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . $.-.. . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . X _.>.e.{ . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . M 4.. . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . f.g.h.U . . . . . . . . . . ",
-". . . . . . . . . ' % . . . $.,.. . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . i.j.x Y b . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { b.@.x &.~.D . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . U f.m @.. . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ . . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . . ",
-". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . k.l.. . . . . . . . . . . . { . . . . . . . . . . . m.n.. . . . . . . 2 C . . ",
-". . . . . . . . . ' % i i i i i i i i i i i i o.i i i i i i i i i i i p.q.i i i i i i i i i i i i o.i i i i i i i i i i i | ).i i i i i i i ).< r.~.",
-". . . . . . . . . . Y r r r r r r r r r r r r r r r r r r r r r r r r (.p.r r r r r r r r r r r r r r r r r r r r r r r r s.c r r r r r r r t.u.2 . ",
-". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 ] . . . . . . . . . . . . . . . . . . . . . . . . + v.. . . . . . . . . . . ",
-". . . . '.= ).% w.[.. . . . . . . . . . . . . . . . . . . . . . . . . . x.8 . . . . . . . . . . . . . . . . . . . . . ~.2.[ i c 2 . . . . . . . . . ",
-". . . . 2.y.z.p A.< j . . . . . . . . . . . . . . . . . . . . . . b &.B.< C.. . . . . . . . . . . . . . . . . . . . . D.t.[.a 3.1 9.. . . . . . . . ",
-". . . p % &.. . + % r . . . . . . . . . . . . . . . . . . . . . . 2 } i % v.. . . . . . . . . . . . . . . . . . . . . 3 . . . &.% p . . . . . . . . ",
-". . . E.h . . . ' % r . . . . . . . . . . . . . . . . . . . . . . . . / ).. . . . . . . . . . . . . . . . . . . . . . . . . . F.< 9.. . . . . . . . ",
-". . . | * . . . ~.% ~.. . . . . . . . . . . . . . . . . . . . . . . . c G.. . . . . . . . . . . . . . . . . . . . . . . . . + ).E.. . . . . . . . . ",
-". . j % &.. . . a H.U . . . . . . . . . . . . . . . . . . . . . . . '.q.x.. . . . . . . . . . . . . . . . . . . . . . . . j h # U . . . . . . . . . ",
-". . Y % I.. . . G.D.. . . . . . . . . . . . . . . . . . . . . . . . p % ~.. . . . . . . . . . . . . . . . . . . . . . . n y.J.4 . . . . . . . . . . ",
-". . r % ' . . 9.1 8 . . . . . . . . . . . . . . . . . . . . . . . . a 1 o . . . . . . . . . . . . . . . . . . . . . . [.H.<.'.. . . . . . . . . . . ",
-". . & % 2 . '.s.K.U . . . . . . . . . . . . . . . . . . . . . . . . d L.. . . . . . . . . . . . . . . . . . . . . |.t.w.r . . . . . . . . . . . . . ",
-". . @ 6.).} h y.p . . . . . . . . . . . . . . . . . . . . . . @ / / ).# / Y . . . . . . . . . . . . . . . . . . . M.% J.2.2.2.2.N.. . . . . . . . . ",
-". . . 3 F./ a 4 . . . . . . . . . . . . . . . . . . . . . . . |./ / / / / n . . . . . . . . . . . . . . . . . . . 0./ / / / / / 9.. . . . . . . . . " };
-
-static const char* image3_data[] =
-{ "74 77 168 2", "  	c None", ". 	c #FFFFFF", "+ 	c #E0E0E0",
-"@ 	c #FAFAFA", "# 	c #363636", "$ 	c #ABABAB", "% 	c #000000",
-"& 	c #BDBDBD", "* 	c #737373", "= 	c #858585", "- 	c #E6E6E6",
-"; 	c #C9C9C9", "> 	c #939493", ", 	c #808080", "' 	c #878787",
-") 	c #D6D6D6", "! 	c #969696", "~ 	c #030303", "{ 	c #383838",
-"] 	c #4C4C4C", "^ 	c #1A1A1A", "/ 	c #080808", "( 	c #C2C2C2",
-"_ 	c #EBEBEB", ": 	c #F0F0F0", "< 	c #8C8C8C", "[ 	c #7A7A7A",
-"} 	c #A3A3A3", "| 	c #999999", "1 	c #A1A1A1", "2 	c #FFE6E6",
-"3 	c #FFF0F0", "4 	c #828282", "5 	c #949494", "6 	c #F2F2F2",
-"7 	c #474747", "8 	c #545454", "9 	c #FF8080", "0 	c #FFB2B2",
-"a 	c #0F0F0F", "b 	c #B5B5B5", "c 	c #CFCFCF", "d 	c #262626",
-"e 	c #333333", "f 	c #DEDEDE", "g 	c #FDFDFD", "h 	c #D7D7D7",
-"i 	c #B7B7B7", "j 	c #C4C4C4", "k 	c #F7F7F7", "l 	c #CCCCCC",
-"m 	c #2E2E2E", "n 	c #B2B2B2", "o 	c #DFDFDF", "p 	c #ACACAC",
-"q 	c #ADADAD", "r 	c #D3D3D3", "s 	c #CDCDCD", "t 	c #AAAAAA",
-"u 	c #D4D4D4", "v 	c #A9A9A9", "w 	c #DBDBDB", "x 	c #E3E3E3",
-"y 	c #E5E5E5", "z 	c #B1B1B1", "A 	c #D2D2D2", "B 	c #EAEAEA",
-"C 	c #E2E2E2", "D 	c #C8C8C8", "E 	c #AFAFAF", "F 	c #F5F5F5",
-"G 	c #E9E9E9", "H 	c #B6B6B6", "I 	c #B9B9B9", "J 	c #F9F9F9",
-"K 	c #B8B8B8", "L 	c #C0C0C0", "M 	c #B4B4B4", "N 	c #EFD9D9",
-"O 	c #AAA8A8", "P 	c #F2DBDB", "Q 	c #EED6D6", "R 	c #ABA8A8",
-"S 	c #EED8D8", "T 	c #BCB1B1", "U 	c #C4B6B6", "V 	c #C5B7B7",
-"W 	c #B6ADAD", "X 	c #EEEEEE", "Y 	c #DADADA", "Z 	c #BEBEBE",
-"` 	c #B0B0B0", " .	c #FBFBFB", "..	c #C6C6C6", "+.	c #C5C5C5",
-"@.	c #BABABA", "#.	c #AEAEAE", "$.	c #D0D0D0", "%.	c #FCFCFC",
-"&.	c #141414", "*.	c #D8D8D8", "=.	c #C7C7C7", "-.	c #575757",
-";.	c #3D3D3D", ">.	c #C3C3C3", ",.	c #5E5E5E", "'.	c #7D6E6E",
-").	c #FF9999", "!.	c #B39D9D", "~.	c #E69292", "{.	c #F09393",
-"].	c #ADA2A2", "^.	c #F49999", "/.	c #FFC2C2", "(.	c #757575",
-"_.	c #918787", ":.	c #F7AEAE", "<.	c #ABA6A6", "[.	c #FCB2B2",
-"}.	c #C3A0A0", "|.	c #C7A4A4", "1.	c #FFD1D1", "2.	c #EDEDED",
-"3.	c #B3B3B3", "4.	c #666666", "5.	c #2B2B2B", "6.	c #BBBBBB",
-"7.	c #292929", "8.	c #E8E8E8", "9.	c #9C9C9C", "0.	c #E4E4E4",
-"a.	c #E7E7E7", "b.	c #CACACA", "c.	c #E4A7A7", "d.	c #B59F9F",
-"e.	c #E6A7A7", "f.	c #B0A3A3", "g.	c #C19E9E", "h.	c #F9B0B0",
-"i.	c #CBCBCB", "j.	c #F4F4F4", "k.	c #BCBCBC", "l.	c #707070",
-"m.	c #242424", "n.	c #0A0A0A", "o.	c #454545", "p.	c #7D7D7D",
-"q.	c #595959", "r.	c #525252", "s.	c #5C5C5C", "t.	c #D9D9D9",
-"u.	c #121212", "v.	c #919191", "w.	c #8A8A8A", "x.	c #171717",
-"y.	c #A8A8A8", "z.	c #696969", "A.	c #9E9E9E", "B.	c #404040",
-"C.	c #616161", "D.	c #8F8F8F", "E.	c #4F4F4F", "F.	c #050505",
-"G.	c #4A4A4A", "H.	c #212121", "I.	c #3B3B3B", "J.	c #636363",
-"K.	c #D1D1D1",
-". . . . . . . . . . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . $ % & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . * % = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . ; > , ' ) . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . ! ~ { ] ^ / ; - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . ( - . . _ % , - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . : % < - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . [ / + - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . } ~ | @ < % 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . . ",
-". . . . 4 ~ 5 . 6 7 % 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 0 . . . ",
-". . 6 8 a b . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". c d e f . . . . - % . . . . . . . . . . . . . . . . . g h i i i j k . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-"l / m $ n n n c . - % . . . . . . . . . . . . . . . . o p q ; r s n t u . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-"} e e e e e e ! . - % . . . . . . . . . . . . . . . l v ) . . . . . h t w . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . x t y . . . . . . . 6 z ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . q A . . . . . . . . . B t C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . D E . . . . . . . . . . . ) $ k . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . F t G . . . . . . . . . . . . & H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . c I . . . . . . . . . . . . . F $ ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . : p B . . . . . . . . . . . . . . C t J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . K L . . . . . . . . . . . . . . . . M j . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % 2 2 2 2 2 2 2 2 2 2 N O P 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Q R S 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . . ",
-". . . . . . . . . - % 2 2 2 2 2 2 2 2 2 2 T U 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 V W 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . . ",
-". . . . . . . . . - % . . . . . . . . . . t X . . . . . . . . . . . . . . . . . . J v k . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . Y q . . . . . . . . . . . . . . . . . . . . Z `  .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . M ... . . . . . . . . . . . . . . . . . . . . z ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . : v J . . . . . . . . . . . . . . . . . . . . . + p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . +.@.. . . . . . . . . . . . . . . . . . . . . . . #.r . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . q Y . . . . . . . . . . . . . . . . . . . . . . . ) p . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . j ( . - % . . . . . . . + p g . . . . . . . . . . . . . . . . . . . . . . . . p $.. . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . %.& &.< . - % . . . . . . . i +.. . . . . . . . . . . . . . . . . . . . . . . . . *.p . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . b % % % =.. - % . . . . . . . t B . . . . . . . . . . . . . . . . . . . . . . . . . . E ; . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . 5 / @ . - % . . . . . . o q . . . . . . . . . . . . . . . . . . . . . . . . . . . h q g . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . -.;.. . - % . . . . . . Z Z . . . . . . . . . . . . . . . . . . . . . . . . . . . . n >.. . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . ^ [ . F ,.% '.).).).).).!.~.).).).).).).).).).).).).).).).).).).).).).).).).).).).).{.].^.).).).).).).).).).).).).).).).).).).).)./.. . . ",
-". . . . + % n . k (.% _.0 0 0 0 :.<.[.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 }.|.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1.. . . ",
-". . . . } % 2.. . - % . . . . . $.3.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . k p y . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . 4.5.. . . - % . . . . . 6.... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ; z . . . . . . . . . . . . . . . . . . . . . . . ",
-". . l l 7.] l + . - % . . . . . 3.u . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  .p $.. . . . . . . . . . . . . . . . . . . . . . ",
-". 8.e e e e e 9.. - % . . . . . t X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x t 0.. . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $.q . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . a.p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ` 6.. . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . >.I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J q b.. . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . i A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X $ l . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . p x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X t ) . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . v J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + t ) . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . F t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C t A . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % 0 0 0 c.d.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 e.f.g.h.0 0 0 0 0 0 0 0 0 1.. . . ",
-". . . . . . . . . - % . . . Y z . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J 3.#.x . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . D 6.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i.p D F . . . . . . . . . . ",
-". . . . . . . . . - % . . . Y $.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . j.L t K 6 . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . a.k.t ` =.y . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . F i.i k.. . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . ; l.. . . . . . . . . . . . . . . . . . . . . . . . 1 < . . . . . . . ( x . . ",
-". . . . . . . . . - % e e e e e e e e e e e e e e e e e e e e e e e e m.n.e e e e e e e e e e e e e e e e e e e e e e e e ^ &.e e e e e e e &.~ o.=.",
-". . . . . . . . . . K n n n n n n n n n n n n n n n n n n n n n n n n p.m.n n n n n n n n n n n n n n n n n n n n n n n n q.7 n n n n n n n r.s.( . ",
-". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . : ; . . . . . . . . . . . . . . . . . . . . . . . . + t.. . . . . . . . . . . ",
-". . . . %.= &.% u.v.. . . . . . . . . . . . . . . . . . . . . . . . . . w.| . . . . . . . . . . . . . . . . . . . . . =.4.{ e 7 ( . . . . . . . . . ",
-". . . . 4.x.y.l z.~ f . . . . . . . . . . . . . . . . . . . . . . 6 ` l.~ A.. . . . . . . . . . . . . . . . . . . . . B.r.v.5 5./ 8.. . . . . . . . ",
-". . . l % ` . . + % n . . . . . . . . . . . . . . . . . . . . . . ( ] e % t.. . . . . . . . . . . . . . . . . . . . . _ . . . ` % l . . . . . . . . ",
-". . . C.d . . . - % n . . . . . . . . . . . . . . . . . . . . . . . . , &.. . . . . . . . . . . . . . . . . . . . . . . . . . D.~ 8.. . . . . . . . ",
-". . . ^ * . . . =.% =.. . . . . . . . . . . . . . . . . . . . . . . . 7 E.. . . . . . . . . . . . . . . . . . . . . . . . . + &.C.. . . . . . . . . ",
-". . f % ` . . . 5 F.F . . . . . . . . . . . . . . . . . . . . . . . %.n.w.. . . . . . . . . . . . . . . . . . . . . . . . f d # F . . . . . . . . . ",
-". . K % w . . . E.B.. . . . . . . . . . . . . . . . . . . . . . . . l % =.. . . . . . . . . . . . . . . . . . . . . . . j x.G.: . . . . . . . . . . ",
-". . n % - . . 8./ | . . . . . . . . . . . . . . . . . . . . . . . . 5 / k . . . . . . . . . . . . . . . . . . . . . . v.F.(.%.. . . . . . . . . . . ",
-". . & % ( . %.q.H.F . . . . . . . . . . . . . . . . . . . . . . . . 8 I.. . . . . . . . . . . . . . . . . . . . . 2.r.u.n . . . . . . . . . . . . . ",
-". . @ 7.&.] d x.l . . . . . . . . . . . . . . . . . . . . . . @ , , &.# , K . . . . . . . . . . . . . . . . . . . J.% G.4.4.4.4.K.. . . . . . . . . ",
-". . . _ D., 5 : . . . . . . . . . . . . . . . . . . . . . . . 2., , , , , j . . . . . . . . . . . . . . . . . . . 9., , , , , , 8.. . . . . . . . . " };
-
-static const char* image4_data[] =
-{ "35 32 4 1", "# c #000000", "a c #bfbfbf", "b c #ff0000", ". c #ffffff",
-"...................................",
-".........#.....#.....#.....#.......",
-".....#.#.#.#.#.#.#.#.#.#.#.#.......",
-".....#.#.#.#.#.#.#.#.#.#.#.#.......",
-"....##########################.....",
-"....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
-"..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
-"....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
-"..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
-"....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
-".####aaaaaaaaaaaaaaaa#aaaaaaa####..",
-"....#aaaaaaaaaaaaaaa#a#aaaaaa#.....",
-"..###aaaaaaaaaaaaaaa#a#aaaaaa###...",
-"....#aaaaaaaaaaaaaa#aaa#aaaaa#.....",
-"..###aaaaaaa#aaaaaa#aaa#aaaaa###...",
-"....#aaaaaa#a#aaaa#aaaaa#aaaa#.....",
-".####aaaaaa#a#aaaa#aaaaa#aaaa####..",
-"....#aaaaa#aaa#aa#aaaaaaa#aaa#.....",
-"..###aaaaa#aaa###aaaaaaaaa######...",
-"....#aaaa#aaaaa#aaaaaaaaaaaaa#.....",
-"..###aaaa#aaaaa#aaaaaaaaaaaaa###...",
-"....#aaa#aaaaaaa#aaaaaaaaaaaa#.....",
-".#######aaaaaaaaa#####aaaaaaa####..",
-"....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
-"..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
-"....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
-"....bbbbbbbbbbbbbbbbbbbbbbbbbb.....",
-"....bbbbbbbbbbbbbbbbbbbbbbbbbb.....",
-".....b.b.b.b.b.b.b.b.b.b.b.b.......",
-".....b.b.b.b.b.b.b.b.b.b.b.b.......",
-".........b.....b.....b.....b.......",
-"..................................." };
-
-static const char* image5_data[] = { "33 32 4 1", "# c #000000", "b c #bfbfbf",
-  "a c #ff0000", ". c #ffffff", ".................................",
-  ".........#.....#.....#.....#.....", ".....#.#.#.#.#.#.#.#.#.#.#.#.....",
-  ".....#.#.#.#.#.#.#.#.#.#.#.#.....", "....aa########################...",
-  "....aabbbbbbbbbbbbbbbbbbbbbbb#...", "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.",
-  "....aabbbbbbbbbbbbbbbbbbbbbbb#...", "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.",
-  "....aabbbbbbbbbbbbbbbbbbbbbbb#...", ".aaaaabbbbbbbbbbbbbbb#bbbbbbb####",
-  "....aabbbbbbbbbbbbbb#b#bbbbbb#...", "..aaaabbbbbbbbbbbbbb#b#bbbbbb###.",
-  "....aabbbbbbbbbbbbb#bbb#bbbbb#...", "..aaaabbbbbb#bbbbbb#bbb#bbbbb###.",
-  "....aabbbbb#b#bbbb#bbbbb#bbbb#...", ".aaaaabbbbb#b#bbbb#bbbbb#bbbb####",
-  "....aabbbb#bbb#bb#bbbbbbb#bbb#...", "..aaaabbbb#bbb###bbbbbbbbb######.",
-  "....aabbb#bbbbb#bbbbbbbbbbbbb#...", "..aaaabbb#bbbbb#bbbbbbbbbbbbb###.",
-  "....aabb#bbbbbbb#bbbbbbbbbbbb#...", ".aaaaa##bbbbbbbbb#####bbbbbbb####",
-  "....aabbbbbbbbbbbbbbbbbbbbbbb#...", "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.",
-  "....aabbbbbbbbbbbbbbbbbbbbbbb#...", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
-  "....aa########################...", ".....#.#.#.#.#.#.#.#.#.#.#.#.....",
-  ".....#.#.#.#.#.#.#.#.#.#.#.#.....", ".........#.....#.....#.....#.....",
-  "................................." };
-
-static const char* image6_data[] = { "34 34 4 1", "a c #000000", "b c #bfbfbf",
-  "# c #ff0000", ". c #ffffff", "..................................",
-  "..................................", ".........#.....#.....#.....#......",
-  ".....#.#.#.#.#.#.#.#.#.#.#.#......", ".....#.#.#.#.#.#.#.#.#.#.#.#......",
-  "....##########################....", "....##########################....",
-  "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..", "....abbbbbbbbbbbbbbbbbbbbbbbba....",
-  "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..", "....abbbbbbbbbbbbbbbbbbbbbbbba....",
-  ".aaaabbbbbbbbbbbbbbbbabbbbbbbaaaa.", "....abbbbbbbbbbbbbbbababbbbbba....",
-  "..aaabbbbbbbbbbbbbbbababbbbbbaaa..", "....abbbbbbbbbbbbbbabbbabbbbba....",
-  "..aaabbbbbbbabbbbbbabbbabbbbbaaa..", "....abbbbbbababbbbabbbbbabbbba....",
-  ".aaaabbbbbbababbbbabbbbbabbbbaaaa.", "....abbbbbabbbabbabbbbbbbabbba....",
-  "..aaabbbbbabbbaaabbbbbbbbbaaaaaa..", "....abbbbabbbbbabbbbbbbbbbbbba....",
-  "..aaabbbbabbbbbabbbbbbbbbbbbbaaa..", "....abbbabbbbbbbabbbbbbbbbbbba....",
-  ".aaaaaaabbbbbbbbbaaaaabbbbbbbaaaa.", "....abbbbbbbbbbbbbbbbbbbbbbbba....",
-  "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..", "....abbbbbbbbbbbbbbbbbbbbbbbba....",
-  "....abbbbbbbbbbbbbbbbbbbbbbbba....", "....aaaaaaaaaaaaaaaaaaaaaaaaaa....",
-  ".....a.a.a.a.a.a.a.a.a.a.a.a......", ".....a.a.a.a.a.a.a.a.a.a.a.a......",
-  ".........a.....a.....a.....a......", "..................................",
-  ".................................." };
-
-static const char* image7_data[] = { "32 32 4 1", "# c #000000", "b c #bfbfbf",
-  "a c #ff0000", ". c #ffffff", "................................",
-  "........#.....#.....#.....#.....", "....#.#.#.#.#.#.#.#.#.#.#.#.....",
-  "....#.#.#.#.#.#.#.#.#.#.#.#.....", "...########################aa...",
-  "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.",
-  "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.",
-  "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", "####bbbbbbbbbbbbbbbb#bbbbbbaaaaa",
-  "...#bbbbbbbbbbbbbbb#b#bbbbbaa...", ".###bbbbbbbbbbbbbbb#b#bbbbbaaaa.",
-  "...#bbbbbbbbbbbbbb#bbb#bbbbaa...", ".###bbbbbbb#bbbbbb#bbb#bbbbaaaa.",
-  "...#bbbbbb#b#bbbb#bbbbb#bbbaa...", "####bbbbbb#b#bbbb#bbbbb#bbbaaaaa",
-  "...#bbbbb#bbb#bb#bbbbbbb#bbaa...", ".###bbbbb#bbb###bbbbbbbbb##aaaa.",
-  "...#bbbb#bbbbb#bbbbbbbbbbbbaa...", ".###bbbb#bbbbb#bbbbbbbbbbbbaaaa.",
-  "...#bbb#bbbbbbb#bbbbbbbbbbbaa...", "#######bbbbbbbbb#####bbbbbbaaaaa",
-  "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.",
-  "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
-  "...########################aa...", "....#.#.#.#.#.#.#.#.#.#.#.#.....",
-  "....#.#.#.#.#.#.#.#.#.#.#.#.....", "........#.....#.....#.....#.....",
-  "................................" };
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("AxisDialog");
+static const char *right_scl_xpm[] = {
+    "36 36 72 1", " 	c None", ".	c #FFFFFF", "+	c #818181",
+    "@	c #070707", "#	c #101010", "$	c #FAFAFA", "%	c #1D1D1D",
+    "&	c #ACACAC", "*	c #151515", "=	c #121212", "-	c #929292",
+    ";	c #242424", ">	c #D5D5D5", ",	c #C9C9C9", "'	c #2A2A2A",
+    ")	c #5E5E5E", "!	c #000000", "~	c #C8C8C8", "{	c #D2D2D2",
+    "]	c #090909", "^	c #060606", "/	c #FEFEFE", "(	c #FCFCFC",
+    "_	c #CECECE", ":	c #444444", "<	c #E0E0E0", "[	c #464646",
+    "}	c #E8E8E8", "|	c #282828", "1	c #D3D3D3", "2	c #D1D1D1",
+    "3	c #A4A4A4", "4	c #484848", "5	c #F1F1F1", "6	c #7D7D7D",
+    "7	c #050505", "8	c #7F7F7F", "9	c #F38C82", "0	c #E71E09",
+    "a	c #E82612", "b	c #EA3826", "c	c #FBD8D5", "d	c #F9CEC9",
+    "e	c #EA3E2C", "f	c #7D6F6F", "g	c #E71D08", "h	c #FEFCFC",
+    "i	c #EA3C2A", "j	c #FAD7D3", "k	c #FAD5D1", "l	c #F2897E",
+    "m	c #E71C07", "n	c #F28B80", "o	c #FEFAFA", "p	c #E9321F",
+    "q	c #EF6D5F", "r	c #E71803", "s	c #F7B3AC", "t	c #E82B17",
+    "u	c #E82814", "v	c #F49C93", "w	c #F9CDC8", "x	c #FAD6D2",
+    "y	c #E7200B", "z	c #FAD2CE", "A	c #ED5546", "B	c #FCE2E0",
+    "C	c #ED5748", "D	c #FCEAE8", "E	c #F6ACA5", "F	c #ED594A",
+    "G	c #FDF2F1", ".......+@#+......$%......&*=-.......",
+    ".......;>,'......)!......%~{].......",
+    ".......^/(^.......!........_:.......",
+    ".......^((^.......!.......<[}.......",
+    ".......|12;.......!......345........",
+    ".......67^8.......!......*!!!.......",
+    "....................................",
+    ".+@#+...!........!.......!.....90a9.",
+    ".;>,'..!!!!!!!!!!!!!!!!!!!!!!..bcde.",
+    ".^/(^..!ffffffffffffffffffff!..g/hg.",
+    ".^((^.!!ffffffffffffffffffff!!.ghhg.",
+    ".|12;..!ffffffffffffffffffff!..ijkb.",
+    ".67^8..!ffffffffffffffffffff!..lmgn.",
+    ".......!ffffffffffffffffffff!.......",
+    ".......!ffffffffffffffffffff!.......",
+    ".$%....!ffffffffffffffffffff!...op..",
+    ".)!....!ffffffffffffffffffff!...qr..",
+    "..!...!!ffffffffffffffffffff!!...r..",
+    "..!....!ffffffffffffffffffff!....r..",
+    "..!....!ffffffffffffffffffff!....r..",
+    "..!....!ffffffffffffffffffff!....r..",
+    ".......!ffffffffffffffffffff!.......",
+    ".&*=-..!ffffffffffffffffffff!..stuv.",
+    ".%~{]..!ffffffffffffffffffff!..pwxy.",
+    "..._:.!!ffffffffffffffffffff!!...zA.",
+    "..<[}..!ffffffffffffffffffff!...BCD.",
+    ".345...!ffffffffffffffffffff!..EFG..",
+    ".*!!!..!!!!!!!!!!!!!!!!!!!!!!..trrr.",
+    ".........!........!.......!.........",
+    "....................................",
+    ".......+@#+......$%......&*=-.......",
+    ".......;>,'......)!......%~{].......",
+    ".......^/(^.......!........_:.......",
+    ".......^((^.......!.......<[}.......",
+    ".......|12;.......!......345........",
+    ".......67^8.......!......*!!!......."};
+
+static const char *image2_data[] = {
+    "74 77 171 2", "  	c None", ". 	c #FFFFFF", "+ 	c #E0E0E0",
+    "@ 	c #FAFAFA", "# 	c #363636", "$ 	c #ABABAB", "% 	c #000000",
+    "& 	c #BDBDBD", "* 	c #737373", "= 	c #858585", "- 	c #FFE8E8",
+    "; 	c #FFF7F7", "> 	c #FFD1D1", ", 	c #FFF0F0", "' 	c #E6E6E6",
+    ") 	c #FFB2B2", "! 	c #FFE6E6", "~ 	c #FF6666", "{ 	c #FFCCCC",
+    "] 	c #C9C9C9", "^ 	c #939493", "/ 	c #808080", "( 	c #878787",
+    "_ 	c #D6D6D6", ": 	c #969696", "< 	c #030303", "[ 	c #383838",
+    "} 	c #4C4C4C", "| 	c #1A1A1A", "1 	c #080808", "2 	c #C2C2C2",
+    "3 	c #EBEBEB", "4 	c #F0F0F0", "5 	c #8C8C8C", "6 	c #7A7A7A",
+    "7 	c #A3A3A3", "8 	c #999999", "9 	c #A1A1A1", "0 	c #828282",
+    "a 	c #949494", "b 	c #F2F2F2", "c 	c #474747", "d 	c #545454",
+    "e 	c #0F0F0F", "f 	c #B5B5B5", "g 	c #CFCFCF", "h 	c #262626",
+    "i 	c #333333", "j 	c #DEDEDE", "k 	c #FDFDFD", "l 	c #D7D7D7",
+    "m 	c #B7B7B7", "n 	c #C4C4C4", "o 	c #F7F7F7", "p 	c #CCCCCC",
+    "q 	c #2E2E2E", "r 	c #B2B2B2", "s 	c #DFDFDF", "t 	c #ACACAC",
+    "u 	c #ADADAD", "v 	c #D3D3D3", "w 	c #CDCDCD", "x 	c #AAAAAA",
+    "y 	c #D4C3C3", "z 	c #A9A9A9", "A 	c #AAA8A8", "B 	c #DB7F7F",
+    "C 	c #E3E3E3", "D 	c #E5E5E5", "E 	c #F2DADA", "F 	c #B19999",
+    "G 	c #FFC4C4", "H 	c #D2D2D2", "I 	c #FFD4D4", "J 	c #EA6565",
+    "K 	c #E2E2E2", "L 	c #FFA1A1", "M 	c #C8C8C8", "N 	c #AFAFAF",
+    "O 	c #FF9999", "P 	c #F5C6C6", "Q 	c #E9E9E9", "R 	c #B6B6B6",
+    "S 	c #CFB4B4", "T 	c #B9B9B9", "U 	c #F5F5F5", "V 	c #ACA7A7",
+    "W 	c #EAEAEA", "X 	c #F9F9F9", "Y 	c #B8B8B8", "Z 	c #C0A6A6",
+    "` 	c #B4B4B4", " .	c #EFEFEF", "..	c #F2C3C3", "+.	c #EEEEEE",
+    "@.	c #BCBCBC", "#.	c #C5C5C5", "$.	c #DADADA", "%.	c #BEBEBE",
+    "&.	c #B0B0B0", "*.	c #FBFBFB", "=.	c #C6C6C6", "-.	c #B1B1B1",
+    ";.	c #BABABA", ">.	c #AEAEAE", ",.	c #D0D0D0", "'.	c #FCFCFC",
+    ").	c #141414", "!.	c #D8D8D8", "~.	c #C7C7C7", "{.	c #575757",
+    "].	c #3D3D3D", "^.	c #C3C3C3", "/.	c #5E5E5E", "(.	c #7D7D7D",
+    "_.	c #B3B3B3", ":.	c #F6C8C8", "<.	c #757575", "[.	c #919191",
+    "}.	c #CAB3B3", "|.	c #EDEDED", "1.	c #ADA8A8", "2.	c #666666",
+    "3.	c #2B2B2B", "4.	c #BBBBBB", "5.	c #C9AAAA", "6.	c #292929",
+    "7.	c #D4D4D4", "8.	c #FBC9C9", "9.	c #E8E8E8", "0.	c #9C9C9C",
+    "a.	c #E4E4E4", "b.	c #E7E7E7", "c.	c #CACACA", "d.	c #C1C1C1",
+    "e.	c #E39090", "f.	c #CBCBCB", "g.	c #ADA3A3", "h.	c #C8B0B0",
+    "i.	c #F59A9A", "j.	c #C0A9A9", "k.	c #C9BFBF", "l.	c #7A4747",
+    "m.	c #A18C8C", "n.	c #8C8282", "o.	c #332929", "p.	c #242424",
+    "q.	c #0A0A0A", "r.	c #454545", "s.	c #595959", "t.	c #525252",
+    "u.	c #5C5C5C", "v.	c #D9D9D9", "w.	c #121212", "x.	c #8A8A8A",
+    "y.	c #171717", "z.	c #A8A8A8", "A.	c #696969", "B.	c #707070",
+    "C.	c #9E9E9E", "D.	c #404040", "E.	c #616161", "F.	c #8F8F8F",
+    "G.	c #4F4F4F", "H.	c #050505", "I.	c #DBDBDB", "J.	c #4A4A4A",
+    "K.	c #212121", "L.	c #3B3B3B", "M.	c #636363", "N.	c #D1D1D1",
+    ". . . . . . . . . . + . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . @ # . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . $ % & . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . * % = . . . . . . . . . . . - . . . . . . . . . . . ; > "
+    ". . . . . . . . . . . . , . . . . . . . . . . . - - . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . ] ^ / ( _ . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . : < [ } | 1 ] ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . 2 ' . . 3 % / ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . . 4 % 5 ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . . 6 1 + ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . 7 < 8 @ 5 % 9 . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . 0 < a . b c % d . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . b d e f . . . ' % . . . . . . . . . . . . ) . . . . . . . . . . . ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". g h i j . . . . ' % . . . . . . . . . . . . ) . . . . k l m m m n o ! ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    "p 1 q $ r r r g . ' % . . . . . . . . . . . . ) . . . s t u ] v w r x y ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    "7 i i i i i i : . ' % . . . . . . . . . . . . ) . . p z _ . . . . . l A B "
+    ". . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . ) . C x D . . . . . . . E F "
+    "] . . . . . . . . . . . { . . . . . . . . . . . ) ) . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . G . u H . . . . . . . . I J "
+    "x K . . . . . . . . . . { . . . . . . . . . . . L G . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { M N . . . . . . . . . { ~ "
+    "_ $ o . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . P x Q . . . . . . . . . { ~ "
+    ". & R . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . S T . . . . . . . . . . { ~ "
+    ". U $ _ . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . 4 V W . . . . . . . . . . { ~ "
+    ". . K x X . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . Y Z . . . . . . . . . . . { ~ "
+    ". . . ` n . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . .  .x ... . . . . . . . . . . { ~ "
+    ". . . +.$ +.. . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . @.n { . . . . . . . . . . . { ~ "
+    ". . . . #.R . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . x +.{ . . . . . . . . . . . { ~ "
+    ". . . . X z o . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . $.u . { . . . . . . . . . . . { ~ "
+    ". . . . . %.&.*.. . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . ` =.. { . . . . . . . . . . . { ~ "
+    ". . . . . . -.=.. . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . 4 z X . { . . . . . . . . . . . { ~ "
+    ". . . . . . + t . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . #.;.. . { . . . . . . . . . . . { ~ "
+    ". . . . . . . >.v . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . u $.. . { . . . . . . . . . . . { ~ "
+    ". . . . . . . _ t . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . n 2 . ' % . . . . . . . + t k . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . t ,.. . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . '.& ).5 . ' % . . . . . . . m #.. . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . !.t . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . f % % % ~.. ' % . . . . . . . x W . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . N ] . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . a 1 @ . ' % . . . . . . s u . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . l u k { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . {.].. . ' % . . . . . . %.%.. . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . r ^.{ . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . | 6 . U /.% (.. . . . . _.' . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . 4 u :.. . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . + % r . o <.% [.. . . . o $ '.. . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . ^.}.. . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . 7 % |.. . ' % . . . . . ,._.. . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . o 1.D . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . 2.3.. . . ' % . . . . . 4.=.. . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . 5.-.. . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . p p 6.} p + . ' % . . . . . _.7.. . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . 8.t ,.. . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". 9.i i i i i 0.. ' % . . . . . x +.. . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { C x a.. . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . x . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . ,.u . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . b.t . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . &.4.. . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . ^.T . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . X u c.. . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . m H . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . +.$ p . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . t C . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . +.x _ . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . z X . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . + x _ . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . U x . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . K x H . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . a.f . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . ' &.d.X O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . $.-.. . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . X _.>.e.{ . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . M 4.. . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . f.g.h.U . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . $.,.. . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . i.j.x Y b . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { b.@.x &.~.D . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . U f.m @.. . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . { ~ "
+    ". . . . . . . . . . . . { . . . . . . . . . . . O { . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . ' % . . . . . . . . . . . . { . . . . . . . . . . . "
+    "k.l.. . . . . . . . . . . . { . . . . . . . . . . . m.n.. . . . . . . 2 C "
+    ". . ",
+    ". . . . . . . . . ' % i i i i i i i i i i i i o.i i i i i i i i i i i "
+    "p.q.i i i i i i i i i i i i o.i i i i i i i i i i i | ).i i i i i i i ).< "
+    "r.~.",
+    ". . . . . . . . . . Y r r r r r r r r r r r r r r r r r r r r r r r r "
+    "(.p.r r r r r r r r r r r r r r r r r r r r r r r r s.c r r r r r r r "
+    "t.u.2 . ",
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 ] "
+    ". . . . . . . . . . . . . . . . . . . . . . . . + v.. . . . . . . . . . "
+    ". ",
+    ". . . . '.= ).% w.[.. . . . . . . . . . . . . . . . . . . . . . . . . . "
+    "x.8 . . . . . . . . . . . . . . . . . . . . . ~.2.[ i c 2 . . . . . . . . "
+    ". ",
+    ". . . . 2.y.z.p A.< j . . . . . . . . . . . . . . . . . . . . . . b &.B.< "
+    "C.. . . . . . . . . . . . . . . . . . . . . D.t.[.a 3.1 9.. . . . . . . "
+    ". ",
+    ". . . p % &.. . + % r . . . . . . . . . . . . . . . . . . . . . . 2 } i % "
+    "v.. . . . . . . . . . . . . . . . . . . . . 3 . . . &.% p . . . . . . . "
+    ". ",
+    ". . . E.h . . . ' % r . . . . . . . . . . . . . . . . . . . . . . . . / "
+    ").. . . . . . . . . . . . . . . . . . . . . . . . . . F.< 9.. . . . . . . "
+    ". ",
+    ". . . | * . . . ~.% ~.. . . . . . . . . . . . . . . . . . . . . . . . c "
+    "G.. . . . . . . . . . . . . . . . . . . . . . . . . + ).E.. . . . . . . . "
+    ". ",
+    ". . j % &.. . . a H.U . . . . . . . . . . . . . . . . . . . . . . . "
+    "'.q.x.. . . . . . . . . . . . . . . . . . . . . . . . j h # U . . . . . . "
+    ". . . ",
+    ". . Y % I.. . . G.D.. . . . . . . . . . . . . . . . . . . . . . . . p % "
+    "~.. . . . . . . . . . . . . . . . . . . . . . . n y.J.4 . . . . . . . . . "
+    ". ",
+    ". . r % ' . . 9.1 8 . . . . . . . . . . . . . . . . . . . . . . . . a 1 o "
+    ". . . . . . . . . . . . . . . . . . . . . . [.H.<.'.. . . . . . . . . . "
+    ". ",
+    ". . & % 2 . '.s.K.U . . . . . . . . . . . . . . . . . . . . . . . . d L.. "
+    ". . . . . . . . . . . . . . . . . . . . |.t.w.r . . . . . . . . . . . . "
+    ". ",
+    ". . @ 6.).} h y.p . . . . . . . . . . . . . . . . . . . . . . @ / / ).# / "
+    "Y . . . . . . . . . . . . . . . . . . . M.% J.2.2.2.2.N.. . . . . . . . "
+    ". ",
+    ". . . 3 F./ a 4 . . . . . . . . . . . . . . . . . . . . . . . |./ / / / / "
+    "n . . . . . . . . . . . . . . . . . . . 0./ / / / / / 9.. . . . . . . . "
+    ". "};
+
+static const char *image3_data[] = {
+    "74 77 168 2", "  	c None", ". 	c #FFFFFF", "+ 	c #E0E0E0",
+    "@ 	c #FAFAFA", "# 	c #363636", "$ 	c #ABABAB", "% 	c #000000",
+    "& 	c #BDBDBD", "* 	c #737373", "= 	c #858585", "- 	c #E6E6E6",
+    "; 	c #C9C9C9", "> 	c #939493", ", 	c #808080", "' 	c #878787",
+    ") 	c #D6D6D6", "! 	c #969696", "~ 	c #030303", "{ 	c #383838",
+    "] 	c #4C4C4C", "^ 	c #1A1A1A", "/ 	c #080808", "( 	c #C2C2C2",
+    "_ 	c #EBEBEB", ": 	c #F0F0F0", "< 	c #8C8C8C", "[ 	c #7A7A7A",
+    "} 	c #A3A3A3", "| 	c #999999", "1 	c #A1A1A1", "2 	c #FFE6E6",
+    "3 	c #FFF0F0", "4 	c #828282", "5 	c #949494", "6 	c #F2F2F2",
+    "7 	c #474747", "8 	c #545454", "9 	c #FF8080", "0 	c #FFB2B2",
+    "a 	c #0F0F0F", "b 	c #B5B5B5", "c 	c #CFCFCF", "d 	c #262626",
+    "e 	c #333333", "f 	c #DEDEDE", "g 	c #FDFDFD", "h 	c #D7D7D7",
+    "i 	c #B7B7B7", "j 	c #C4C4C4", "k 	c #F7F7F7", "l 	c #CCCCCC",
+    "m 	c #2E2E2E", "n 	c #B2B2B2", "o 	c #DFDFDF", "p 	c #ACACAC",
+    "q 	c #ADADAD", "r 	c #D3D3D3", "s 	c #CDCDCD", "t 	c #AAAAAA",
+    "u 	c #D4D4D4", "v 	c #A9A9A9", "w 	c #DBDBDB", "x 	c #E3E3E3",
+    "y 	c #E5E5E5", "z 	c #B1B1B1", "A 	c #D2D2D2", "B 	c #EAEAEA",
+    "C 	c #E2E2E2", "D 	c #C8C8C8", "E 	c #AFAFAF", "F 	c #F5F5F5",
+    "G 	c #E9E9E9", "H 	c #B6B6B6", "I 	c #B9B9B9", "J 	c #F9F9F9",
+    "K 	c #B8B8B8", "L 	c #C0C0C0", "M 	c #B4B4B4", "N 	c #EFD9D9",
+    "O 	c #AAA8A8", "P 	c #F2DBDB", "Q 	c #EED6D6", "R 	c #ABA8A8",
+    "S 	c #EED8D8", "T 	c #BCB1B1", "U 	c #C4B6B6", "V 	c #C5B7B7",
+    "W 	c #B6ADAD", "X 	c #EEEEEE", "Y 	c #DADADA", "Z 	c #BEBEBE",
+    "` 	c #B0B0B0", " .	c #FBFBFB", "..	c #C6C6C6", "+.	c #C5C5C5",
+    "@.	c #BABABA", "#.	c #AEAEAE", "$.	c #D0D0D0", "%.	c #FCFCFC",
+    "&.	c #141414", "*.	c #D8D8D8", "=.	c #C7C7C7", "-.	c #575757",
+    ";.	c #3D3D3D", ">.	c #C3C3C3", ",.	c #5E5E5E", "'.	c #7D6E6E",
+    ").	c #FF9999", "!.	c #B39D9D", "~.	c #E69292", "{.	c #F09393",
+    "].	c #ADA2A2", "^.	c #F49999", "/.	c #FFC2C2", "(.	c #757575",
+    "_.	c #918787", ":.	c #F7AEAE", "<.	c #ABA6A6", "[.	c #FCB2B2",
+    "}.	c #C3A0A0", "|.	c #C7A4A4", "1.	c #FFD1D1", "2.	c #EDEDED",
+    "3.	c #B3B3B3", "4.	c #666666", "5.	c #2B2B2B", "6.	c #BBBBBB",
+    "7.	c #292929", "8.	c #E8E8E8", "9.	c #9C9C9C", "0.	c #E4E4E4",
+    "a.	c #E7E7E7", "b.	c #CACACA", "c.	c #E4A7A7", "d.	c #B59F9F",
+    "e.	c #E6A7A7", "f.	c #B0A3A3", "g.	c #C19E9E", "h.	c #F9B0B0",
+    "i.	c #CBCBCB", "j.	c #F4F4F4", "k.	c #BCBCBC", "l.	c #707070",
+    "m.	c #242424", "n.	c #0A0A0A", "o.	c #454545", "p.	c #7D7D7D",
+    "q.	c #595959", "r.	c #525252", "s.	c #5C5C5C", "t.	c #D9D9D9",
+    "u.	c #121212", "v.	c #919191", "w.	c #8A8A8A", "x.	c #171717",
+    "y.	c #A8A8A8", "z.	c #696969", "A.	c #9E9E9E", "B.	c #404040",
+    "C.	c #616161", "D.	c #8F8F8F", "E.	c #4F4F4F", "F.	c #050505",
+    "G.	c #4A4A4A", "H.	c #212121", "I.	c #3B3B3B", "J.	c #636363",
+    "K.	c #D1D1D1", ". . . . . . . . . . + . . . . . . . . . . . . . . . . . . "
+                    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+                    ". . . . . . . . . . . . . . . . ",
+    ". . . . . . . . . @ # . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . $ % & . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . * % = . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . ; > , ' ) . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . ! ~ { ] ^ / ; - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . ( - . . _ % , - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . : % < - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . [ / + - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . } ~ | @ < % 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 "
+    "2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . "
+    ". ",
+    ". . . . 4 ~ 5 . 6 7 % 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 "
+    "9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 0 . . "
+    ". ",
+    ". . 6 8 a b . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". c d e f . . . . - % . . . . . . . . . . . . . . . . . g h i i i j k . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    "l / m $ n n n c . - % . . . . . . . . . . . . . . . . o p q ; r s n t u . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    "} e e e e e e ! . - % . . . . . . . . . . . . . . . l v ) . . . . . h t w "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . x t y . . . . . . . 6 z "
+    "; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . q A . . . . . . . . . B "
+    "t C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . D E . . . . . . . . . . . "
+    ") $ k . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . F t G . . . . . . . . . . . "
+    ". & H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . c I . . . . . . . . . . . . "
+    ". F $ ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . : p B . . . . . . . . . . . . "
+    ". . C t J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . K L . . . . . . . . . . . . . "
+    ". . . M j . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % 2 2 2 2 2 2 2 2 2 2 N O P 2 2 2 2 2 2 2 2 2 2 2 2 2 "
+    "2 2 2 Q R S 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . "
+    ". ",
+    ". . . . . . . . . - % 2 2 2 2 2 2 2 2 2 2 T U 2 2 2 2 2 2 2 2 2 2 2 2 2 2 "
+    "2 2 2 2 V W 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . t X . . . . . . . . . . . . . . "
+    ". . . . J v k . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . Y q . . . . . . . . . . . . . . . "
+    ". . . . . Z `  .. . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . M ... . . . . . . . . . . . . . . "
+    ". . . . . . z ... . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . : v J . . . . . . . . . . . . . . . "
+    ". . . . . . + p . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . +.@.. . . . . . . . . . . . . . . . "
+    ". . . . . . . #.r . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . q Y . . . . . . . . . . . . . . . . "
+    ". . . . . . . ) p . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . j ( . - % . . . . . . . + p g . . . . . . . . . . . . . . . . "
+    ". . . . . . . . p $.. . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . %.& &.< . - % . . . . . . . i +.. . . . . . . . . . . . . . . . . "
+    ". . . . . . . . *.p . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . b % % % =.. - % . . . . . . . t B . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . E ; . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . 5 / @ . - % . . . . . . o q . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . h q g . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . -.;.. . - % . . . . . . Z Z . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . n >.. . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . ^ [ . F ,.% "
+    "'.).).).).).!.~.).).).).).).).).).).).).).).).).).).).).).).).).).).).).{."
+    "].^.).).).).).).).).).).).).).).).).).).).)./.. . . ",
+    ". . . . + % n . k (.% _.0 0 0 0 :.<.[.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "
+    "0 0 0 0 0 0 0 0 0 0 0 }.|.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1.. . "
+    ". ",
+    ". . . . } % 2.. . - % . . . . . $.3.. . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . k p y . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . 4.5.. . . - % . . . . . 6.... . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . ; z . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . l l 7.] l + . - % . . . . . 3.u . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . .  .p $.. . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". 8.e e e e e 9.. - % . . . . . t X . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . x t 0.. . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . t . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . $.q . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . a.p . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . ` 6.. . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . >.I . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . J q b.. . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . i A . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . X $ l . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . p x . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . X t ) . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . v J . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . + t ) . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . F t . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . C t A . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % 0 0 0 c.d.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "
+    "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 e.f.g.h.0 0 0 0 0 0 0 0 0 1.. . "
+    ". ",
+    ". . . . . . . . . - % . . . Y z . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . J 3.#.x . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . D 6.. . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . i.p D F . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . Y $.. . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . j.L t K 6 . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . a.k.t ` =.y . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . F i.i k.. . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
+    ". ",
+    ". . . . . . . . . - % . . . . . . . . . . . . . . . . . . . . . . . . ; "
+    "l.. . . . . . . . . . . . . . . . . . . . . . . . 1 < . . . . . . . ( x . "
+    ". ",
+    ". . . . . . . . . - % e e e e e e e e e e e e e e e e e e e e e e e e "
+    "m.n.e e e e e e e e e e e e e e e e e e e e e e e e ^ &.e e e e e e e &.~ "
+    "o.=.",
+    ". . . . . . . . . . K n n n n n n n n n n n n n n n n n n n n n n n n "
+    "p.m.n n n n n n n n n n n n n n n n n n n n n n n n q.7 n n n n n n n "
+    "r.s.( . ",
+    ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . : ; "
+    ". . . . . . . . . . . . . . . . . . . . . . . . + t.. . . . . . . . . . "
+    ". ",
+    ". . . . %.= &.% u.v.. . . . . . . . . . . . . . . . . . . . . . . . . . "
+    "w.| . . . . . . . . . . . . . . . . . . . . . =.4.{ e 7 ( . . . . . . . . "
+    ". ",
+    ". . . . 4.x.y.l z.~ f . . . . . . . . . . . . . . . . . . . . . . 6 ` l.~ "
+    "A.. . . . . . . . . . . . . . . . . . . . . B.r.v.5 5./ 8.. . . . . . . "
+    ". ",
+    ". . . l % ` . . + % n . . . . . . . . . . . . . . . . . . . . . . ( ] e % "
+    "t.. . . . . . . . . . . . . . . . . . . . . _ . . . ` % l . . . . . . . "
+    ". ",
+    ". . . C.d . . . - % n . . . . . . . . . . . . . . . . . . . . . . . . , "
+    "&.. . . . . . . . . . . . . . . . . . . . . . . . . . D.~ 8.. . . . . . . "
+    ". ",
+    ". . . ^ * . . . =.% =.. . . . . . . . . . . . . . . . . . . . . . . . 7 "
+    "E.. . . . . . . . . . . . . . . . . . . . . . . . . + &.C.. . . . . . . . "
+    ". ",
+    ". . f % ` . . . 5 F.F . . . . . . . . . . . . . . . . . . . . . . . "
+    "%.n.w.. . . . . . . . . . . . . . . . . . . . . . . . f d # F . . . . . . "
+    ". . . ",
+    ". . K % w . . . E.B.. . . . . . . . . . . . . . . . . . . . . . . . l % "
+    "=.. . . . . . . . . . . . . . . . . . . . . . . j x.G.: . . . . . . . . . "
+    ". ",
+    ". . n % - . . 8./ | . . . . . . . . . . . . . . . . . . . . . . . . 5 / k "
+    ". . . . . . . . . . . . . . . . . . . . . . v.F.(.%.. . . . . . . . . . "
+    ". ",
+    ". . & % ( . %.q.H.F . . . . . . . . . . . . . . . . . . . . . . . . 8 I.. "
+    ". . . . . . . . . . . . . . . . . . . . 2.r.u.n . . . . . . . . . . . . "
+    ". ",
+    ". . @ 7.&.] d x.l . . . . . . . . . . . . . . . . . . . . . . @ , , &.# , "
+    "K . . . . . . . . . . . . . . . . . . . J.% G.4.4.4.4.K.. . . . . . . . "
+    ". ",
+    ". . . _ D., 5 : . . . . . . . . . . . . . . . . . . . . . . . 2., , , , , "
+    "j . . . . . . . . . . . . . . . . . . . 9., , , , , , 8.. . . . . . . . "
+    ". "};
+
+static const char *image4_data[] = {"35 32 4 1", "# c #000000", "a c #bfbfbf",
+                                    "b c #ff0000", ". c #ffffff",
+                                    "...................................",
+                                    ".........#.....#.....#.....#.......",
+                                    ".....#.#.#.#.#.#.#.#.#.#.#.#.......",
+                                    ".....#.#.#.#.#.#.#.#.#.#.#.#.......",
+                                    "....##########################.....",
+                                    "....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
+                                    "..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
+                                    "....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
+                                    "..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
+                                    "....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
+                                    ".####aaaaaaaaaaaaaaaa#aaaaaaa####..",
+                                    "....#aaaaaaaaaaaaaaa#a#aaaaaa#.....",
+                                    "..###aaaaaaaaaaaaaaa#a#aaaaaa###...",
+                                    "....#aaaaaaaaaaaaaa#aaa#aaaaa#.....",
+                                    "..###aaaaaaa#aaaaaa#aaa#aaaaa###...",
+                                    "....#aaaaaa#a#aaaa#aaaaa#aaaa#.....",
+                                    ".####aaaaaa#a#aaaa#aaaaa#aaaa####..",
+                                    "....#aaaaa#aaa#aa#aaaaaaa#aaa#.....",
+                                    "..###aaaaa#aaa###aaaaaaaaa######...",
+                                    "....#aaaa#aaaaa#aaaaaaaaaaaaa#.....",
+                                    "..###aaaa#aaaaa#aaaaaaaaaaaaa###...",
+                                    "....#aaa#aaaaaaa#aaaaaaaaaaaa#.....",
+                                    ".#######aaaaaaaaa#####aaaaaaa####..",
+                                    "....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
+                                    "..###aaaaaaaaaaaaaaaaaaaaaaaa###...",
+                                    "....#aaaaaaaaaaaaaaaaaaaaaaaa#.....",
+                                    "....bbbbbbbbbbbbbbbbbbbbbbbbbb.....",
+                                    "....bbbbbbbbbbbbbbbbbbbbbbbbbb.....",
+                                    ".....b.b.b.b.b.b.b.b.b.b.b.b.......",
+                                    ".....b.b.b.b.b.b.b.b.b.b.b.b.......",
+                                    ".........b.....b.....b.....b.......",
+                                    "..................................."};
+
+static const char *image5_data[] = {
+    "33 32 4 1", "# c #000000", "b c #bfbfbf", "a c #ff0000", ". c #ffffff",
+    ".................................", ".........#.....#.....#.....#.....",
+    ".....#.#.#.#.#.#.#.#.#.#.#.#.....", ".....#.#.#.#.#.#.#.#.#.#.#.#.....",
+    "....aa########################...", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
+    "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
+    "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
+    ".aaaaabbbbbbbbbbbbbbb#bbbbbbb####", "....aabbbbbbbbbbbbbb#b#bbbbbb#...",
+    "..aaaabbbbbbbbbbbbbb#b#bbbbbb###.", "....aabbbbbbbbbbbbb#bbb#bbbbb#...",
+    "..aaaabbbbbb#bbbbbb#bbb#bbbbb###.", "....aabbbbb#b#bbbb#bbbbb#bbbb#...",
+    ".aaaaabbbbb#b#bbbb#bbbbb#bbbb####", "....aabbbb#bbb#bb#bbbbbbb#bbb#...",
+    "..aaaabbbb#bbb###bbbbbbbbb######.", "....aabbb#bbbbb#bbbbbbbbbbbbb#...",
+    "..aaaabbb#bbbbb#bbbbbbbbbbbbb###.", "....aabb#bbbbbbb#bbbbbbbbbbbb#...",
+    ".aaaaa##bbbbbbbbb#####bbbbbbb####", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
+    "..aaaabbbbbbbbbbbbbbbbbbbbbbb###.", "....aabbbbbbbbbbbbbbbbbbbbbbb#...",
+    "....aabbbbbbbbbbbbbbbbbbbbbbb#...", "....aa########################...",
+    ".....#.#.#.#.#.#.#.#.#.#.#.#.....", ".....#.#.#.#.#.#.#.#.#.#.#.#.....",
+    ".........#.....#.....#.....#.....", "................................."};
+
+static const char *image6_data[] = {
+    "34 34 4 1", "a c #000000", "b c #bfbfbf", "# c #ff0000", ". c #ffffff",
+    "..................................", "..................................",
+    ".........#.....#.....#.....#......", ".....#.#.#.#.#.#.#.#.#.#.#.#......",
+    ".....#.#.#.#.#.#.#.#.#.#.#.#......", "....##########################....",
+    "....##########################....", "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..",
+    "....abbbbbbbbbbbbbbbbbbbbbbbba....", "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..",
+    "....abbbbbbbbbbbbbbbbbbbbbbbba....", ".aaaabbbbbbbbbbbbbbbbabbbbbbbaaaa.",
+    "....abbbbbbbbbbbbbbbababbbbbba....", "..aaabbbbbbbbbbbbbbbababbbbbbaaa..",
+    "....abbbbbbbbbbbbbbabbbabbbbba....", "..aaabbbbbbbabbbbbbabbbabbbbbaaa..",
+    "....abbbbbbababbbbabbbbbabbbba....", ".aaaabbbbbbababbbbabbbbbabbbbaaaa.",
+    "....abbbbbabbbabbabbbbbbbabbba....", "..aaabbbbbabbbaaabbbbbbbbbaaaaaa..",
+    "....abbbbabbbbbabbbbbbbbbbbbba....", "..aaabbbbabbbbbabbbbbbbbbbbbbaaa..",
+    "....abbbabbbbbbbabbbbbbbbbbbba....", ".aaaaaaabbbbbbbbbaaaaabbbbbbbaaaa.",
+    "....abbbbbbbbbbbbbbbbbbbbbbbba....", "..aaabbbbbbbbbbbbbbbbbbbbbbbbaaa..",
+    "....abbbbbbbbbbbbbbbbbbbbbbbba....", "....abbbbbbbbbbbbbbbbbbbbbbbba....",
+    "....aaaaaaaaaaaaaaaaaaaaaaaaaa....", ".....a.a.a.a.a.a.a.a.a.a.a.a......",
+    ".....a.a.a.a.a.a.a.a.a.a.a.a......", ".........a.....a.....a.....a......",
+    "..................................", ".................................."};
+
+static const char *image7_data[] = {
+    "32 32 4 1", "# c #000000", "b c #bfbfbf", "a c #ff0000", ". c #ffffff",
+    "................................", "........#.....#.....#.....#.....",
+    "....#.#.#.#.#.#.#.#.#.#.#.#.....", "....#.#.#.#.#.#.#.#.#.#.#.#.....",
+    "...########################aa...", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
+    ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
+    ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
+    "####bbbbbbbbbbbbbbbb#bbbbbbaaaaa", "...#bbbbbbbbbbbbbbb#b#bbbbbaa...",
+    ".###bbbbbbbbbbbbbbb#b#bbbbbaaaa.", "...#bbbbbbbbbbbbbb#bbb#bbbbaa...",
+    ".###bbbbbbb#bbbbbb#bbb#bbbbaaaa.", "...#bbbbbb#b#bbbb#bbbbb#bbbaa...",
+    "####bbbbbb#b#bbbb#bbbbb#bbbaaaaa", "...#bbbbb#bbb#bb#bbbbbbb#bbaa...",
+    ".###bbbbb#bbb###bbbbbbbbb##aaaa.", "...#bbbb#bbbbb#bbbbbbbbbbbbaa...",
+    ".###bbbb#bbbbb#bbbbbbbbbbbbaaaa.", "...#bbb#bbbbbbb#bbbbbbbbbbbaa...",
+    "#######bbbbbbbbb#####bbbbbbaaaaa", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
+    ".###bbbbbbbbbbbbbbbbbbbbbbbaaaa.", "...#bbbbbbbbbbbbbbbbbbbbbbbaa...",
+    "...#bbbbbbbbbbbbbbbbbbbbbbbaa...", "...########################aa...",
+    "....#.#.#.#.#.#.#.#.#.#.#.#.....", "....#.#.#.#.#.#.#.#.#.#.#.#.....",
+    "........#.....#.....#.....#.....", "................................"};
+
+namespace {
+Mantid::Kernel::Logger g_log("AxisDialog");
 }
 
 ///////////////////
 // Public Functions
 ///////////////////
 
-/** The constructor for a single set of widgets containing parameters for the scale of an axis.
+/** The constructor for a single set of widgets containing parameters for the
+* scale of an axis.
 *  @param app :: the containing application window
 *  @param g :: the graph the dialog is settign the options for
 *  @param fl :: The QT flags fro thsi window
 */
-AxesDialog::AxesDialog(ApplicationWindow* app, Graph* g, Qt::WFlags fl) :
-  QDialog(g, fl), m_app(app), m_graph(g)
-{
-  QPixmap image4((const char**) image4_data);
-  QPixmap image5((const char**) image5_data);
-  QPixmap image6((const char**) image6_data);
-  QPixmap image7((const char**) image7_data);
+AxesDialog::AxesDialog(ApplicationWindow *app, Graph *g, Qt::WFlags fl)
+    : QDialog(g, fl), m_app(app), m_graph(g) {
+  QPixmap image4((const char **)image4_data);
+  QPixmap image5((const char **)image5_data);
+  QPixmap image6((const char **)image6_data);
+  QPixmap image7((const char **)image7_data);
   setWindowTitle(tr("MantidPlot - General Plot Options"));
 
   m_generalDialog = new QTabWidget();
@@ -654,18 +976,19 @@ AxesDialog::AxesDialog(ApplicationWindow* app, Graph* g, Qt::WFlags fl) :
   initGridPage();
   initGeneralPage();
 
-  //Connect scale details to axis details in order to diable scale options when an axis is not shown
+  // Connect scale details to axis details in order to diable scale options when
+  // an axis is not shown
   auto scaleIter = m_Scale_list.begin();
   auto axisIter = m_Axis_list.begin();
-  while((scaleIter != m_Scale_list.end()) && (axisIter != m_Axis_list.end()))
-  {
-    connect(*axisIter, SIGNAL(axisShowChanged(bool)), *scaleIter, SLOT(axisEnabled(bool)));
+  while ((scaleIter != m_Scale_list.end()) && (axisIter != m_Axis_list.end())) {
+    connect(*axisIter, SIGNAL(axisShowChanged(bool)), *scaleIter,
+            SLOT(axisEnabled(bool)));
 
     ++scaleIter;
     ++axisIter;
   }
 
-  QHBoxLayout * bottomButtons = new QHBoxLayout();
+  QHBoxLayout *bottomButtons = new QHBoxLayout();
   bottomButtons->addStretch();
 
   m_btnApply = new QPushButton();
@@ -681,26 +1004,24 @@ AxesDialog::AxesDialog(ApplicationWindow* app, Graph* g, Qt::WFlags fl) :
   m_btnCancel->setText(tr("&Cancel"));
   bottomButtons->addWidget(m_btnCancel);
 
-  QVBoxLayout * mainLayout = new QVBoxLayout(this);
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
   mainLayout->addWidget(m_generalDialog);
   mainLayout->addLayout(bottomButtons);
 
   m_lastPage = m_scalesPage;
-  connect(m_btnOk, SIGNAL( clicked() ), this, SLOT( accept() ));
-  connect(m_btnCancel, SIGNAL( clicked() ), this, SLOT( reject() ));
-  connect(m_btnApply, SIGNAL( clicked() ), this, SLOT(apply() ));
-  connect(m_generalDialog, SIGNAL( currentChanged ( QWidget * ) ), this, SLOT(pageChanged ( QWidget * ) ));
+  connect(m_btnOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(m_btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(m_btnApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(m_generalDialog, SIGNAL(currentChanged(QWidget *)), this,
+          SLOT(pageChanged(QWidget *)));
 }
 
-AxesDialog::~AxesDialog()
-{
-}
+AxesDialog::~AxesDialog() {}
 
 /**Applies changes then closes the dialog
 *
 */
-void AxesDialog::accept()
-{
+void AxesDialog::accept() {
   m_btnOk->setFocus();
   if (pressToGraph())
     close();
@@ -708,18 +1029,15 @@ void AxesDialog::accept()
 /** Applys the changes to the graph without closing the window
 *
 */
-void AxesDialog::apply()
-{
+void AxesDialog::apply() {
   m_btnApply->setFocus();
   pressToGraph();
 }
 /**shows the Axes tab
 *
 */
-void AxesDialog::showAxesPage()
-{
-  if (m_generalDialog->currentWidget() != dynamic_cast<QWidget*>(m_axesPage))
-  {
+void AxesDialog::showAxesPage() {
+  if (m_generalDialog->currentWidget() != dynamic_cast<QWidget *>(m_axesPage)) {
     m_generalDialog->setCurrentWidget(m_axesPage);
   }
 }
@@ -727,10 +1045,8 @@ void AxesDialog::showAxesPage()
 /**shows the Grid tab
 *
 */
-void AxesDialog::showGridPage()
-{
-  if (m_generalDialog->currentWidget() != dynamic_cast<QWidget*>(m_gridPage))
-  {
+void AxesDialog::showGridPage() {
+  if (m_generalDialog->currentWidget() != dynamic_cast<QWidget *>(m_gridPage)) {
     m_generalDialog->setCurrentWidget(m_gridPage);
   }
 }
@@ -746,8 +1062,7 @@ void AxesDialog::showGeneralPage() {
 /**launches the dialog
 *
 */
-int AxesDialog::exec()
-{
+int AxesDialog::exec() {
   m_lstScales->setCurrentRow(0);
   m_lstGrid->setCurrentRow(0);
   m_lstAxes->setCurrentRow(0);
@@ -759,31 +1074,25 @@ int AxesDialog::exec()
 /**sets the current shown axis of scale and axis tabs
 *
 */
-void AxesDialog::setCurrentScale(int axisPos)
-{
+void AxesDialog::setCurrentScale(int axisPos) {
   int axis = -1;
-  switch (axisPos)
-  {
-  case QwtScaleDraw::LeftScale:
-    {
-      axis = 1;
-      break;
-    }
-  case QwtScaleDraw::BottomScale:
-    {
-      axis = 0;
-      break;
-    }
-  case QwtScaleDraw::RightScale:
-    {
-      axis = 3;
-      break;
-    }
-  case QwtScaleDraw::TopScale:
-    {
-      axis = 2;
-      break;
-    }
+  switch (axisPos) {
+  case QwtScaleDraw::LeftScale: {
+    axis = 1;
+    break;
+  }
+  case QwtScaleDraw::BottomScale: {
+    axis = 0;
+    break;
+  }
+  case QwtScaleDraw::RightScale: {
+    axis = 3;
+    break;
+  }
+  case QwtScaleDraw::TopScale: {
+    axis = 2;
+    break;
+  }
   }
   if (m_generalDialog->currentWidget() ==
       dynamic_cast<QWidget *>(m_scalesPage)) {
@@ -795,36 +1104,36 @@ void AxesDialog::setCurrentScale(int axisPos)
 }
 
 ///////////////////
-//Private functions
+// Private functions
 ///////////////////
 
 /**initialises the scales tab
 *
 */
-void AxesDialog::initScalesPage()
-{
+void AxesDialog::initScalesPage() {
   m_scalesPage = new QWidget();
   scalesLayout = new QHBoxLayout(m_scalesPage);
 
-  QPixmap image0((const char**) bottom_scl_xpm);
-  QPixmap image1((const char**) left_scl_xpm);
-  QPixmap image2((const char**) top_scl_xpm);
-  QPixmap image3((const char**) right_scl_xpm);
+  QPixmap image0((const char **)bottom_scl_xpm);
+  QPixmap image1((const char **)left_scl_xpm);
+  QPixmap image2((const char **)top_scl_xpm);
+  QPixmap image3((const char **)right_scl_xpm);
 
   m_lstScales = new QListWidget();
   m_scalePrefsArea = new QStackedLayout();
   scalesLayout->addWidget(m_lstScales);
   scalesLayout->addLayout(m_scalePrefsArea);
 
-  QListWidgetItem* listBottom = new QListWidgetItem(image0, tr("Bottom"));
-  QListWidgetItem* listLeft = new QListWidgetItem(image1, tr("Left"));
-  QListWidgetItem* listTop = new QListWidgetItem(image2, tr("Top"));
-  QListWidgetItem* listRight = new QListWidgetItem(image3, tr("Right"));
+  QListWidgetItem *listBottom = new QListWidgetItem(image0, tr("Bottom"));
+  QListWidgetItem *listLeft = new QListWidgetItem(image1, tr("Left"));
+  QListWidgetItem *listTop = new QListWidgetItem(image2, tr("Top"));
+  QListWidgetItem *listRight = new QListWidgetItem(image3, tr("Right"));
 
-  ScaleDetails* prefsBottom = new ScaleDetails(m_app, m_graph, QwtPlot::xBottom);
-  ScaleDetails* prefsLeft = new ScaleDetails(m_app, m_graph, QwtPlot::yLeft);
-  ScaleDetails* prefsTop = new ScaleDetails(m_app, m_graph, QwtPlot::xTop);
-  ScaleDetails* prefsRight = new ScaleDetails(m_app, m_graph, QwtPlot::yRight);
+  ScaleDetails *prefsBottom =
+      new ScaleDetails(m_app, m_graph, QwtPlot::xBottom);
+  ScaleDetails *prefsLeft = new ScaleDetails(m_app, m_graph, QwtPlot::yLeft);
+  ScaleDetails *prefsTop = new ScaleDetails(m_app, m_graph, QwtPlot::xTop);
+  ScaleDetails *prefsRight = new ScaleDetails(m_app, m_graph, QwtPlot::yRight);
 
   m_scalePrefsArea->addWidget(prefsBottom);
   m_scalePrefsArea->addWidget(prefsLeft);
@@ -841,7 +1150,8 @@ void AxesDialog::initScalesPage()
   m_Scale_list.append(prefsTop);
   m_Scale_list.append(prefsRight);
 
-  m_lstScales->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
+  m_lstScales->setSizePolicy(
+      QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
   m_lstScales->setIconSize(image0.size());
 
   // calculate a sensible width for the items list
@@ -849,10 +1159,8 @@ void AxesDialog::initScalesPage()
   QFontMetrics fm(m_lstScales->font());
   int width = 32;
 
-  for (int i = 0; i < m_lstScales->count(); i++)
-  {
-    if (fm.width(m_lstScales->item(i)->text()) > width)
-    {
+  for (int i = 0; i < m_lstScales->count(); i++) {
+    if (fm.width(m_lstScales->item(i)->text()) > width) {
       width = fm.width(m_lstScales->item(i)->text());
     }
   }
@@ -861,38 +1169,37 @@ void AxesDialog::initScalesPage()
   // resize the list to the maximum width
   m_lstScales->resize(m_lstScales->maximumWidth(), m_lstScales->height());
 
-
   m_generalDialog->addTab(m_scalesPage, tr("Scale"));
-  connect(m_lstScales, SIGNAL(currentRowChanged(int)), m_scalePrefsArea, SLOT(setCurrentIndex(int)));
+  connect(m_lstScales, SIGNAL(currentRowChanged(int)), m_scalePrefsArea,
+          SLOT(setCurrentIndex(int)));
 }
 
 /**initialises the axes tab
 *
 */
-void AxesDialog::initAxesPage()
-{
+void AxesDialog::initAxesPage() {
   m_axesPage = new QWidget();
   axesLayout = new QHBoxLayout(m_axesPage);
-  //axes page
-  QPixmap image4((const char**) image4_data);
-  QPixmap image5((const char**) image5_data);
-  QPixmap image6((const char**) image6_data);
-  QPixmap image7((const char**) image7_data);
+  // axes page
+  QPixmap image4((const char **)image4_data);
+  QPixmap image5((const char **)image5_data);
+  QPixmap image6((const char **)image6_data);
+  QPixmap image7((const char **)image7_data);
 
   m_lstAxes = new QListWidget();
   m_axesPrefsArea = new QStackedLayout();
   axesLayout->addWidget(m_lstAxes);
   axesLayout->addLayout(m_axesPrefsArea);
 
-  QListWidgetItem* listBottom = new QListWidgetItem(image4, tr("Bottom"));
-  QListWidgetItem* listLeft = new QListWidgetItem(image5, tr("Left"));
-  QListWidgetItem* listTop = new QListWidgetItem(image6, tr("Top"));
-  QListWidgetItem* listRight = new QListWidgetItem(image7, tr("Right"));
+  QListWidgetItem *listBottom = new QListWidgetItem(image4, tr("Bottom"));
+  QListWidgetItem *listLeft = new QListWidgetItem(image5, tr("Left"));
+  QListWidgetItem *listTop = new QListWidgetItem(image6, tr("Top"));
+  QListWidgetItem *listRight = new QListWidgetItem(image7, tr("Right"));
 
-  AxisDetails* prefsBottom = new AxisDetails(m_app, m_graph, QwtPlot::xBottom);
-  AxisDetails* prefsLeft = new AxisDetails(m_app, m_graph, QwtPlot::yLeft);
-  AxisDetails* prefsTop = new AxisDetails(m_app, m_graph, QwtPlot::xTop);
-  AxisDetails* prefsRight = new AxisDetails(m_app, m_graph, QwtPlot::yRight);
+  AxisDetails *prefsBottom = new AxisDetails(m_app, m_graph, QwtPlot::xBottom);
+  AxisDetails *prefsLeft = new AxisDetails(m_app, m_graph, QwtPlot::yLeft);
+  AxisDetails *prefsTop = new AxisDetails(m_app, m_graph, QwtPlot::xTop);
+  AxisDetails *prefsRight = new AxisDetails(m_app, m_graph, QwtPlot::yRight);
 
   m_axesPrefsArea->addWidget(prefsBottom);
   m_axesPrefsArea->addWidget(prefsLeft);
@@ -910,51 +1217,48 @@ void AxesDialog::initAxesPage()
   m_Axis_list.append(prefsRight);
 
   m_lstAxes->setIconSize(image6.size());
-  m_lstAxes->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
+  m_lstAxes->setSizePolicy(
+      QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
 
   // calculate a sensible width for the items list
   // (default QListWidget size is 256 which looks too big)
   QFontMetrics fm(m_lstAxes->font());
   int width = 32;
 
-  for (int i = 0; i < m_lstAxes->count(); i++)
-  {
-    if (fm.width(m_lstAxes->item(i)->text()) > width)
-    {
+  for (int i = 0; i < m_lstAxes->count(); i++) {
+    if (fm.width(m_lstAxes->item(i)->text()) > width) {
       width = fm.width(m_lstAxes->item(i)->text());
     }
   }
 
   m_lstAxes->setMaximumWidth(m_lstAxes->iconSize().width() + width + 50);
   // resize the list to the maximum width
-  m_lstAxes->resize(m_lstAxes->maximumWidth(),m_lstAxes->height());
-
+  m_lstAxes->resize(m_lstAxes->maximumWidth(), m_lstAxes->height());
 
   m_generalDialog->addTab(m_axesPage, tr("Axis"));
-  connect(m_lstAxes, SIGNAL(currentRowChanged(int)), m_axesPrefsArea, SLOT(setCurrentIndex(int)));
+  connect(m_lstAxes, SIGNAL(currentRowChanged(int)), m_axesPrefsArea,
+          SLOT(setCurrentIndex(int)));
 }
 
 /**initialises the grid tab
 *
 */
-void AxesDialog::initGridPage()
-{
+void AxesDialog::initGridPage() {
   Grid *grd = dynamic_cast<Grid *>(m_graph->plotWidget()->grid());
-  if (!grd)
-  {
+  if (!grd) {
     return;
   }
   m_gridPage = new QWidget();
 
-  QPixmap image2((const char**) image2_data);
-  QPixmap image3((const char**) image3_data);
+  QPixmap image2((const char **)image2_data);
+  QPixmap image3((const char **)image3_data);
 
-  QVBoxLayout* gridPageLayout = new QVBoxLayout(m_gridPage);
-  QGroupBox * rightBox = new QGroupBox(QString());
+  QVBoxLayout *gridPageLayout = new QVBoxLayout(m_gridPage);
+  QGroupBox *rightBox = new QGroupBox(QString());
   m_gridPrefsArea = new QStackedLayout(rightBox);
 
   m_lstGrid = new QListWidget();
-  QHBoxLayout* topBox = new QHBoxLayout();
+  QHBoxLayout *topBox = new QHBoxLayout();
   topBox->addWidget(m_lstGrid);
   topBox->addWidget(rightBox);
 
@@ -965,10 +1269,8 @@ void AxesDialog::initGridPage()
   // (default QListWidget size is 256 which looks too big)
   QFontMetrics fm(m_lstGrid->font());
   int width = 32, i;
-  for (i = 0; i < m_lstGrid->count(); i++)
-  {
-    if (fm.width(m_lstGrid->item(i)->text()) > width)
-    {
+  for (i = 0; i < m_lstGrid->count(); i++) {
+    if (fm.width(m_lstGrid->item(i)->text()) > width) {
       width = fm.width(m_lstGrid->item(i)->text());
     }
   }
@@ -977,9 +1279,8 @@ void AxesDialog::initGridPage()
   // resize the list to the maximum width
   m_lstGrid->resize(m_lstGrid->maximumWidth(), m_lstGrid->height());
 
-
-  GridDetails* prefsHor = new GridDetails(m_app, m_graph, 0);
-  GridDetails* prefsVert = new GridDetails(m_app, m_graph, 1);
+  GridDetails *prefsHor = new GridDetails(m_app, m_graph, 0);
+  GridDetails *prefsVert = new GridDetails(m_app, m_graph, 1);
 
   m_gridPrefsArea->addWidget(prefsHor);
   m_gridPrefsArea->addWidget(prefsVert);
@@ -987,7 +1288,7 @@ void AxesDialog::initGridPage()
   m_Grid_list.append(prefsHor);
   m_Grid_list.append(prefsVert);
 
-  QGridLayout* bottombox = new QGridLayout();
+  QGridLayout *bottombox = new QGridLayout();
 
   bottombox->addWidget(new QLabel(tr("Apply To")), 0, 0, Qt::AlignRight);
   m_cmbApplyGridFormat = new QComboBox();
@@ -998,33 +1299,36 @@ void AxesDialog::initGridPage()
 
   m_chkAntialiseGrid = new QCheckBox(tr("An&tialised"));
   bottombox->addWidget(m_chkAntialiseGrid, 0, 2, Qt::AlignLeft);
-  m_chkAntialiseGrid->setChecked(grd->testRenderHint(QwtPlotItem::RenderAntialiased));
-  m_chkAntialiseGrid->setToolTip("Attempts to remove visual artifacts caused by plot resolution giving a smoother plot");
+  m_chkAntialiseGrid->setChecked(
+      grd->testRenderHint(QwtPlotItem::RenderAntialiased));
+  m_chkAntialiseGrid->setToolTip("Attempts to remove visual artifacts caused "
+                                 "by plot resolution giving a smoother plot");
 
   gridPageLayout->addLayout(topBox);
   gridPageLayout->addLayout(bottombox);
 
   m_generalDialog->addTab(m_gridPage, tr("Grid"));
 
-  //showGridOptions(m_lstGrid->currentRow());
+  // showGridOptions(m_lstGrid->currentRow());
 
-  //grid page slot connections
-  connect(m_lstGrid, SIGNAL(currentRowChanged(int)),  m_gridPrefsArea, SLOT(setCurrentIndex(int)));
-  connect(m_chkAntialiseGrid, SIGNAL(clicked()),prefsHor,SLOT(setModified()));
-  connect(m_chkAntialiseGrid, SIGNAL(clicked()),prefsVert,SLOT(setModified()));
+  // grid page slot connections
+  connect(m_lstGrid, SIGNAL(currentRowChanged(int)), m_gridPrefsArea,
+          SLOT(setCurrentIndex(int)));
+  connect(m_chkAntialiseGrid, SIGNAL(clicked()), prefsHor, SLOT(setModified()));
+  connect(m_chkAntialiseGrid, SIGNAL(clicked()), prefsVert,
+          SLOT(setModified()));
 }
 
 /**initialises the general tab
 *
 */
-void AxesDialog::initGeneralPage()
-{
+void AxesDialog::initGeneralPage() {
   m_generalPage = new QWidget();
 
   Plot *p = m_graph->plotWidget();
 
-  QGroupBox * boxAxes = new QGroupBox(tr("Axes"));
-  QGridLayout * boxAxesLayout = new QGridLayout(boxAxes);
+  QGroupBox *boxAxes = new QGroupBox(tr("Axes"));
+  QGridLayout *boxAxesLayout = new QGridLayout(boxAxes);
 
   m_chkBackbones = new QCheckBox();
   m_chkBackbones->setText(tr("Draw backbones"));
@@ -1046,7 +1350,7 @@ void AxesDialog::initGeneralPage()
   boxAxesLayout->addWidget(m_spnMinorTicksLength, 3, 1);
   boxAxesLayout->setRowStretch(4, 1);
 
-  QHBoxLayout * mainLayout = new QHBoxLayout(m_generalPage);
+  QHBoxLayout *mainLayout = new QHBoxLayout(m_generalPage);
   mainLayout->addWidget(boxAxes);
 
   m_generalDialog->addTab(m_generalPage, tr("General"));
@@ -1056,31 +1360,33 @@ void AxesDialog::initGeneralPage()
   m_spnMinorTicksLength->setValue(p->minorTickLength());
   m_spnMajorTicksLength->setValue(p->majorTickLength());
 
-  connect(m_spnMajorTicksLength, SIGNAL(valueChanged (int)), this, SLOT(changeMajorTicksLength(int)));
-  connect(m_spnMinorTicksLength, SIGNAL(valueChanged (int)), this, SLOT(changeMinorTicksLength(int)));
-
-  connect(m_spnAxesLinewidth,SIGNAL(valueChanged(int)),this, SLOT(setModified()));
-  connect(m_spnMajorTicksLength,SIGNAL(valueChanged(int)),this, SLOT(setModified()));
-  connect(m_spnMinorTicksLength,SIGNAL(valueChanged(int)),this, SLOT(setModified()));
-  connect(m_chkBackbones,SIGNAL(clicked()),this, SLOT(setModified()));
-  connect(m_chkAntialiseGrid,SIGNAL(clicked()),this, SLOT(setModified()));
-  connect(m_cmbApplyGridFormat,SIGNAL(currentIndexChanged(int)),this, SLOT(setModified()));
+  connect(m_spnMajorTicksLength, SIGNAL(valueChanged(int)), this,
+          SLOT(changeMajorTicksLength(int)));
+  connect(m_spnMinorTicksLength, SIGNAL(valueChanged(int)), this,
+          SLOT(changeMinorTicksLength(int)));
+
+  connect(m_spnAxesLinewidth, SIGNAL(valueChanged(int)), this,
+          SLOT(setModified()));
+  connect(m_spnMajorTicksLength, SIGNAL(valueChanged(int)), this,
+          SLOT(setModified()));
+  connect(m_spnMinorTicksLength, SIGNAL(valueChanged(int)), this,
+          SLOT(setModified()));
+  connect(m_chkBackbones, SIGNAL(clicked()), this, SLOT(setModified()));
+  connect(m_chkAntialiseGrid, SIGNAL(clicked()), this, SLOT(setModified()));
+  connect(m_cmbApplyGridFormat, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(setModified()));
 }
 
 /**sets the flag that shows the general tab has been modified
 *
 */
-void AxesDialog::setModified()
-{
-  m_generalModified = true;
-}
+void AxesDialog::setModified() { m_generalModified = true; }
 
 /** sets the Minimum length of major ticks
 *
 *  @param minLength :: the current value of m_spnMinorTicksLength
 */
-void AxesDialog::changeMinorTicksLength(int minLength)
-{
+void AxesDialog::changeMinorTicksLength(int minLength) {
   m_spnMajorTicksLength->setMinimum(minLength);
 }
 
@@ -1088,8 +1394,7 @@ void AxesDialog::changeMinorTicksLength(int minLength)
 *
 *  @param majLength :: the current value of m_spnMajorTicksLength
 */
-void AxesDialog::changeMajorTicksLength(int majLength)
-{
+void AxesDialog::changeMajorTicksLength(int majLength) {
   m_spnMinorTicksLength->setMaximum(majLength);
 }
 
@@ -1097,15 +1402,11 @@ void AxesDialog::changeMajorTicksLength(int majLength)
 *
 *  @param page :: the tab that has just been switched to
 */
-void AxesDialog::pageChanged(QWidget *page)
-{
-  if (m_lastPage == m_scalesPage && page == m_axesPage)
-  {
+void AxesDialog::pageChanged(QWidget *page) {
+  if (m_lastPage == m_scalesPage && page == m_axesPage) {
     m_lstAxes->setCurrentRow(m_lstScales->currentRow());
     m_lastPage = page;
-  }
-  else if (m_lastPage == m_axesPage && page == m_scalesPage)
-  {
+  } else if (m_lastPage == m_axesPage && page == m_scalesPage) {
     m_lstScales->setCurrentRow(m_lstAxes->currentRow());
     m_lastPage = page;
   }
@@ -1114,98 +1415,81 @@ void AxesDialog::pageChanged(QWidget *page)
 /**updates the grid overlay on the graph
 *
 */
-void AxesDialog::updateGrid()
-{
+void AxesDialog::updateGrid() {
   bool antiAlias = m_chkAntialiseGrid->isChecked();
-  switch (m_cmbApplyGridFormat->currentIndex())
-  {
-  case 0:
-    {
-      for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end(); gridItr++)
-      {
-        if ((*gridItr)->modified())
-        {
-          (*gridItr)->apply(m_graph->plotWidget()->grid(),antiAlias);
-          m_graph->replot();
-          m_graph->notifyChanges();
-        }
+  switch (m_cmbApplyGridFormat->currentIndex()) {
+  case 0: {
+    for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end();
+         gridItr++) {
+      if ((*gridItr)->modified()) {
+        (*gridItr)->apply(m_graph->plotWidget()->grid(), antiAlias);
+        m_graph->replot();
+        m_graph->notifyChanges();
       }
-      break;
     }
-  case 1:
-    {
-      MultiLayer *plot = m_graph->multiLayer();
-      if (!plot)
-      {
-        return;
-      }
-      for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end(); gridItr++)
-      {
-        QList<Graph *> layers = plot->layersList();
-        foreach(Graph *g, layers)
-        {
-          if (g->isPiePlot())
-          {
-            continue;
-          }
-          (*gridItr)->apply(g->plotWidget()->grid(),antiAlias);
-          g->replot();
+    break;
+  }
+  case 1: {
+    MultiLayer *plot = m_graph->multiLayer();
+    if (!plot) {
+      return;
+    }
+    for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end();
+         gridItr++) {
+      QList<Graph *> layers = plot->layersList();
+      foreach (Graph *g, layers) {
+        if (g->isPiePlot()) {
+          continue;
         }
+        (*gridItr)->apply(g->plotWidget()->grid(), antiAlias);
+        g->replot();
       }
-      plot->applicationWindow()->modifiedProject();
-      break;
     }
-  case 2:
-    {
-      if (!m_app)
-      {
-        return;
-      }
-      QList<MdiSubWindow *> windows = m_app->windowsList();
-      foreach(MdiSubWindow *w, windows)
-      {
-        if (auto multi = dynamic_cast<MultiLayer*>(w))
-        {
-          QList<Graph *> layers = multi->layersList();
-          foreach(Graph *g, layers)
-          {
-            if (g->isPiePlot())
-            {
-              continue;
-            }
-            for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end(); gridItr++)
-            {
-              (*gridItr)->apply(g->plotWidget()->grid(),antiAlias,true);
-              g->replot();
-            }
+    plot->applicationWindow()->modifiedProject();
+    break;
+  }
+  case 2: {
+    if (!m_app) {
+      return;
+    }
+    QList<MdiSubWindow *> windows = m_app->windowsList();
+    foreach (MdiSubWindow *w, windows) {
+      if (auto multi = dynamic_cast<MultiLayer *>(w)) {
+        QList<Graph *> layers = multi->layersList();
+        foreach (Graph *g, layers) {
+          if (g->isPiePlot()) {
+            continue;
+          }
+          for (auto gridItr = m_Grid_list.begin(); gridItr != m_Grid_list.end();
+               gridItr++) {
+            (*gridItr)->apply(g->plotWidget()->grid(), antiAlias, true);
+            g->replot();
           }
         }
       }
-      m_app->modifiedProject();
-      break;
     }
+    m_app->modifiedProject();
+    break;
+  }
   }
 }
 
 /**applies the changes throughout the entire dialog to the graph
 *
 */
-bool AxesDialog::pressToGraph()
-{
-  //Check if all tabs and axes are valid first
-  for (auto axisItr = m_Axis_list.begin(); axisItr != m_Axis_list.end(); axisItr++)
-  {
-    if(!((*axisItr)->valid()))
-    {
+bool AxesDialog::pressToGraph() {
+  // Check if all tabs and axes are valid first
+  for (auto axisItr = m_Axis_list.begin(); axisItr != m_Axis_list.end();
+       axisItr++) {
+    if (!((*axisItr)->valid())) {
       g_log.warning("Axis options are invalid!");
       return false;
     }
   }
 
-  for (auto scaleItr = m_Scale_list.begin(); scaleItr != m_Scale_list.end(); scaleItr++)
-  {
-    if(!((*scaleItr)->valid()))
-    {
+  for (auto scaleItr = m_Scale_list.begin(); scaleItr != m_Scale_list.end();
+       scaleItr++) {
+    if (!((*scaleItr)->valid())) {
       g_log.warning("Scale options are invalid!");
       return false;
     }
@@ -1213,19 +1497,19 @@ bool AxesDialog::pressToGraph()
 
   updateGrid();
 
-  for (auto axisItr = m_Axis_list.begin(); axisItr != m_Axis_list.end(); axisItr++)
-  {
+  for (auto axisItr = m_Axis_list.begin(); axisItr != m_Axis_list.end();
+       axisItr++) {
     (*axisItr)->apply();
   }
 
-  for (auto scaleItr = m_Scale_list.begin(); scaleItr != m_Scale_list.end(); scaleItr++)
-  {
+  for (auto scaleItr = m_Scale_list.begin(); scaleItr != m_Scale_list.end();
+       scaleItr++) {
     (*scaleItr)->apply();
   }
 
-  if (m_generalModified)
-  {
-    m_graph->changeTicksLength(m_spnMinorTicksLength->value(), m_spnMajorTicksLength->value());
+  if (m_generalModified) {
+    m_graph->changeTicksLength(m_spnMinorTicksLength->value(),
+                               m_spnMajorTicksLength->value());
     m_graph->drawAxesBackbones(m_chkBackbones->isChecked());
     m_graph->setAxesLinewidth(m_spnAxesLinewidth->value());
     m_generalModified = false;
diff --git a/MantidPlot/src/AxesDialog.h b/MantidPlot/src/AxesDialog.h
index bb3413e9243a8dede049960c44efc0cb729205ff..2e03baca579b295e322f34ff718629ce2d5936bc 100644
--- a/MantidPlot/src/AxesDialog.h
+++ b/MantidPlot/src/AxesDialog.h
@@ -26,7 +26,7 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
- //Heavily edited and refactored to fix bugs by Keith Brown
+// Heavily edited and refactored to fix bugs by Keith Brown
 #ifndef AXESDIALOG_H
 #define AXESDIALOG_H
 
@@ -68,65 +68,63 @@ class ApplicationWindow;
 /**
  * Remark: Don't use this dialog as a non modal dialog!
  */
-class AxesDialog: public QDialog
-{
+class AxesDialog : public QDialog {
   Q_OBJECT
 
-  public:
-    AxesDialog(ApplicationWindow* app, Graph* g, Qt::WFlags fl = 0);
-    ~AxesDialog() override;
+public:
+  AxesDialog(ApplicationWindow *app, Graph *g, Qt::WFlags fl = 0);
+  ~AxesDialog() override;
 
-  public slots:
-    void setCurrentScale(int axisPos);
-    void showGeneralPage();
-    void showAxesPage();
-    void showGridPage();
-    int exec();
+public slots:
+  void setCurrentScale(int axisPos);
+  void showGeneralPage();
+  void showAxesPage();
+  void showGridPage();
+  int exec();
 
-  private slots:
-    bool pressToGraph();
-    void apply();
-    void accept() override;
-    void updateGrid();
-    void changeMinorTicksLength(int minLength);
-    void changeMajorTicksLength(int majLength);
-    void pageChanged(QWidget *page);
-    void setModified();
+private slots:
+  bool pressToGraph();
+  void apply();
+  void accept() override;
+  void updateGrid();
+  void changeMinorTicksLength(int minLength);
+  void changeMajorTicksLength(int majLength);
+  void pageChanged(QWidget *page);
+  void setModified();
 
-  protected:
-    //! generate UI for the axes page
-    void initAxesPage();
-    //! generate UI for the scales page
-    void initScalesPage();
-    //! generate UI for the grid page
-    void initGridPage();
-    //! generate UI for the general page
-    void initGeneralPage();
+protected:
+  //! generate UI for the axes page
+  void initAxesPage();
+  //! generate UI for the scales page
+  void initScalesPage();
+  //! generate UI for the grid page
+  void initGridPage();
+  //! generate UI for the general page
+  void initGeneralPage();
 
-    ApplicationWindow* m_app;
-    Graph *m_graph;
-	  QStackedLayout *m_scalePrefsArea, *m_axesPrefsArea, *m_gridPrefsArea;
+  ApplicationWindow *m_app;
+  Graph *m_graph;
+  QStackedLayout *m_scalePrefsArea, *m_axesPrefsArea, *m_gridPrefsArea;
 
-    //common widgets
-    QPushButton *m_btnApply, *m_btnOk, *m_btnCancel;
-    QTabWidget *m_generalDialog;
-    QWidget *m_scalesPage, *m_gridPage, *m_axesPage, *m_generalPage, *m_lastPage;
+  // common widgets
+  QPushButton *m_btnApply, *m_btnOk, *m_btnCancel;
+  QTabWidget *m_generalDialog;
+  QWidget *m_scalesPage, *m_gridPage, *m_axesPage, *m_generalPage, *m_lastPage;
 
-    QHBoxLayout *scalesLayout, *axesLayout;
-    QListWidget *m_lstScales, *m_lstGrid, *m_lstAxes;
-    QSpinBox *m_spnAxesLinewidth, *m_spnMajorTicksLength, *m_spnMinorTicksLength;
-    QCheckBox *m_chkBackbones, *m_chkAntialiseGrid;
-    QComboBox *m_cmbApplyGridFormat;
+  QHBoxLayout *scalesLayout, *axesLayout;
+  QListWidget *m_lstScales, *m_lstGrid, *m_lstAxes;
+  QSpinBox *m_spnAxesLinewidth, *m_spnMajorTicksLength, *m_spnMinorTicksLength;
+  QCheckBox *m_chkBackbones, *m_chkAntialiseGrid;
+  QComboBox *m_cmbApplyGridFormat;
 
-  private:
-
-    ///A map of QListWidgetItem objects to their Axis details objects
-    QList<AxisDetails*> m_Axis_list;
-    ///A map of QListWidgetItem objects to their Scale details objects
-    QList<ScaleDetails*> m_Scale_list;
-    ///A map of QListWidgetItem objects to their Scale details objects
-    QList<GridDetails*> m_Grid_list;
-    bool m_generalModified;
+private:
+  /// A map of QListWidgetItem objects to their Axis details objects
+  QList<AxisDetails *> m_Axis_list;
+  /// A map of QListWidgetItem objects to their Scale details objects
+  QList<ScaleDetails *> m_Scale_list;
+  /// A map of QListWidgetItem objects to their Scale details objects
+  QList<GridDetails *> m_Grid_list;
+  bool m_generalModified;
 };
 
 #endif
diff --git a/MantidPlot/src/AxisDetails.cpp b/MantidPlot/src/AxisDetails.cpp
index ac0b1223e824bea98dfa3dea7c4dd58ab2f0bced..f800b3f11a635b95a7655a64613528e7a7e0646f 100644
--- a/MantidPlot/src/AxisDetails.cpp
+++ b/MantidPlot/src/AxisDetails.cpp
@@ -34,20 +34,23 @@
 #include <ColorButton.h>
 #include <QFontDialog>
 
-/** The constructor for a single set of widgets containing parameters for the labeling and format of an axis.
+/** The constructor for a single set of widgets containing parameters for the
+* labeling and format of an axis.
 *  @param app :: the containing application window
 *  @param graph :: the graph the dialog is settign the options for
 *  @param mappedaxis :: the QwtPlot::axis value that corresponds to this axis
-*  @param parent :: the QWidget that acts as this widget's parent in the hierachy
+*  @param parent :: the QWidget that acts as this widget's parent in the
+* hierachy
 */
-AxisDetails::AxisDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, QWidget *parent) : QWidget(parent)
-{
+AxisDetails::AxisDetails(ApplicationWindow *app, Graph *graph, int mappedaxis,
+                         QWidget *parent)
+    : QWidget(parent) {
   m_app = app;
   m_graph = graph;
   m_tablesList = m_app->tableNames();
   m_mappedaxis = mappedaxis;
   m_initialised = false;
-  QHBoxLayout * topLayout = new QHBoxLayout();
+  QHBoxLayout *topLayout = new QHBoxLayout();
 
   m_chkShowAxis = new QCheckBox(tr("Show"));
   topLayout->addWidget(m_chkShowAxis);
@@ -69,18 +72,20 @@ AxisDetails::AxisDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, Q
   m_btnLabelFont = new QPushButton(tr("&Font"));
   hl->addWidget(m_btnLabelFont);
 
-  m_formatButtons = new TextFormatButtons(m_txtTitle, TextFormatButtons::AxisLabel);
+  m_formatButtons =
+      new TextFormatButtons(m_txtTitle, TextFormatButtons::AxisLabel);
   hl->addWidget(m_formatButtons);
   hl->addStretch();
 
-  m_txtTitle->setMaximumWidth(m_btnLabelFont->width() + m_formatButtons->width());
+  m_txtTitle->setMaximumWidth(m_btnLabelFont->width() +
+                              m_formatButtons->width());
   titleBoxLayout->addLayout(hl);
 
-  QHBoxLayout * bottomLayout = new QHBoxLayout();
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
 
   m_grpAxisDisplay = new QGroupBox(QString());
   bottomLayout->addWidget(m_grpAxisDisplay);
-  QGridLayout * leftBoxLayout = new QGridLayout(m_grpAxisDisplay);
+  QGridLayout *leftBoxLayout = new QGridLayout(m_grpAxisDisplay);
 
   leftBoxLayout->addWidget(new QLabel(tr("Type")), 0, 0);
 
@@ -180,17 +185,18 @@ AxisDetails::AxisDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, Q
   rightBoxLayout->addWidget(m_txtFormula, 6, 1);
   rightBoxLayout->setRowStretch(7, 1);
 
-  QVBoxLayout * rightLayout = new QVBoxLayout(this);
+  QVBoxLayout *rightLayout = new QVBoxLayout(this);
   rightLayout->addLayout(topLayout);
   rightLayout->addLayout(bottomLayout);
   rightLayout->addStretch(1);
 
   connect(m_chkShowFormula, SIGNAL(clicked()), this, SLOT(enableFormulaBox()));
-  connect(m_cmbAxisType, SIGNAL(activated(int)), this, SLOT(setAxisFormatOptions(int)));
+  connect(m_cmbAxisType, SIGNAL(activated(int)), this,
+          SLOT(setAxisFormatOptions(int)));
 
-  connect(m_grpShowLabels, SIGNAL(clicked(bool)), this,  SLOT(showAxis()));
+  connect(m_grpShowLabels, SIGNAL(clicked(bool)), this, SLOT(showAxis()));
   connect(m_chkShowAxis, SIGNAL(clicked()), this, SLOT(showAxis()));
-  connect(m_cmbFormat, SIGNAL(activated(int)), this,  SLOT(showAxis()));
+  connect(m_cmbFormat, SIGNAL(activated(int)), this, SLOT(showAxis()));
 
   connect(m_btnAxesFont, SIGNAL(clicked()), this, SLOT(setScaleFont()));
   connect(m_btnLabelFont, SIGNAL(clicked()), this, SLOT(setLabelFont()));
@@ -198,24 +204,18 @@ AxisDetails::AxisDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, Q
   initWidgets();
 }
 
-AxisDetails::~AxisDetails()
-{
+AxisDetails::~AxisDetails() {}
 
-}
-
-/** Initialisation method. Sets up all widgets and variables not done in the constructor.
+/** Initialisation method. Sets up all widgets and variables not done in the
+*constructor.
 *
 */
-void AxisDetails::initWidgets()
-{
-  if (m_initialised)
-  {
+void AxisDetails::initWidgets() {
+  if (m_initialised) {
     return;
-  }
-  else
-  {
+  } else {
     Plot *p = m_graph->plotWidget();
-    int style = (int) m_graph->axisType(m_mappedaxis);
+    int style = (int)m_graph->axisType(m_mappedaxis);
 
     bool axisOn = p->axisEnabled(m_mappedaxis);
     const QList<int> majTicks = p->getMajorTicksType();
@@ -226,12 +226,12 @@ void AxisDetails::initWidgets()
 
     int format = p->axisLabelFormat(m_mappedaxis);
 
-    //Top
+    // Top
     m_chkShowAxis->setChecked(axisOn);
     m_txtTitle->setPlainText(m_graph->axisTitle(m_mappedaxis));
     m_labelFont = m_graph->axisTitleFont(m_mappedaxis);
 
-    //bottom left
+    // bottom left
     m_cmbAxisType->setCurrentIndex(style);
     setAxisFormatOptions(style);
     m_scaleFont = p->axisFont(m_mappedaxis);
@@ -241,41 +241,33 @@ void AxisDetails::initWidgets()
     m_cmbMajorTicksType->setCurrentIndex(majTicks[m_mappedaxis]);
     m_cmbMinorTicksType->setCurrentIndex(minTicks[m_mappedaxis]);
 
-    QwtScaleWidget *scale = dynamic_cast<QwtScaleWidget *>(p->axisWidget(m_mappedaxis));
-    if (scale)
-    {
+    QwtScaleWidget *scale =
+        dynamic_cast<QwtScaleWidget *>(p->axisWidget(m_mappedaxis));
+    if (scale) {
       m_spnBaseline->setValue(scale->margin());
-    }
-    else
-    {
+    } else {
       m_spnBaseline->setValue(0);
     }
 
-    //bottom right
+    // bottom right
     m_grpShowLabels->setChecked(labelsOn);
 
     m_cmbFormat->setEnabled(labelsOn && axisOn);
     m_cmbFormat->setCurrentIndex(format);
 
-    if (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric)
-    {
+    if (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric) {
       m_spnPrecision->setValue(p->axisLabelPrecision(m_mappedaxis));
-    }
-    else if (m_cmbAxisType->currentIndex() == ScaleDraw::Text)
-    {
+    } else if (m_cmbAxisType->currentIndex() == ScaleDraw::Text) {
       m_cmbColName->setItemText(m_cmbColName->currentIndex(),
                                 m_graph->axisFormatInfo(m_mappedaxis));
     }
 
     m_spnPrecision->setEnabled(format != 0);
 
-    if (m_mappedaxis == QwtPlot::xBottom || m_mappedaxis == QwtPlot::xTop)
-    {
+    if (m_mappedaxis == QwtPlot::xBottom || m_mappedaxis == QwtPlot::xTop) {
       m_spnAngle->setEnabled(labelsOn && axisOn);
       m_spnAngle->setValue(m_graph->labelsRotation(m_mappedaxis));
-    }
-    else
-    {
+    } else {
       m_spnAngle->setEnabled(false);
       m_spnAngle->setValue(0);
     }
@@ -285,45 +277,60 @@ void AxisDetails::initWidgets()
     QString formula = m_graph->axisFormula(m_mappedaxis);
     m_txtFormula->setFixedWidth(150);
 
-    if (!formula.isEmpty())
-    {
+    if (!formula.isEmpty()) {
       m_chkShowFormula->setChecked(true);
       m_txtFormula->setEnabled(true);
       m_txtFormula->setPlainText(formula);
-    }
-    else
-    {
+    } else {
       m_chkShowFormula->setChecked(false);
       m_txtFormula->setEnabled(false);
     }
     showAxis();
 
-    connect(m_chkShowFormula, SIGNAL(stateChanged(int)), this, SLOT(setModified()));
-    connect(m_chkShowAxis, SIGNAL(stateChanged(int)), this, SLOT(setModified()));
-
-    connect(m_cmbAxisType, SIGNAL(currentIndexChanged(int)), this, SLOT(setModified()));
-    connect(m_cmbAxisType, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_cmbMajorTicksType, SIGNAL(currentIndexChanged(int)), this,  SLOT(setModified()));
-    connect(m_cmbMajorTicksType, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_cmbTableName, SIGNAL(currentIndexChanged(int)), this,  SLOT(setModified()));
-    connect(m_cmbTableName, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_cmbMinorTicksType, SIGNAL(currentIndexChanged(int)), this,  SLOT(setModified()));
-    connect(m_cmbMinorTicksType, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_cmbColName, SIGNAL(currentIndexChanged(int)), this,  SLOT(setModified()));
-    connect(m_cmbColName, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_cmbFormat, SIGNAL(currentIndexChanged(int)), this,  SLOT(setModified()));
-    connect(m_cmbFormat, SIGNAL(editTextChanged(QString)), this, SLOT(setModified()));
-    connect(m_grpShowLabels, SIGNAL(clicked(bool)), this,  SLOT(setModified()));
+    connect(m_chkShowFormula, SIGNAL(stateChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_chkShowAxis, SIGNAL(stateChanged(int)), this,
+            SLOT(setModified()));
+
+    connect(m_cmbAxisType, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbAxisType, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_cmbMajorTicksType, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbMajorTicksType, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_cmbTableName, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbTableName, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_cmbMinorTicksType, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbMinorTicksType, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_cmbColName, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbColName, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_cmbFormat, SIGNAL(currentIndexChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_cmbFormat, SIGNAL(editTextChanged(QString)), this,
+            SLOT(setModified()));
+    connect(m_grpShowLabels, SIGNAL(clicked(bool)), this, SLOT(setModified()));
     connect(m_btnAxesFont, SIGNAL(clicked()), this, SLOT(setModified()));
     connect(m_btnLabelFont, SIGNAL(clicked()), this, SLOT(setModified()));
     connect(m_txtFormula, SIGNAL(textChanged()), this, SLOT(setModified()));
     connect(m_txtTitle, SIGNAL(textChanged()), this, SLOT(setModified()));
-    connect(m_formatButtons, SIGNAL(formattingModified()), this, SLOT(setModified()));
-    connect(m_spnPrecision,SIGNAL(valueChanged(int)), this, SLOT(setModified()));
-    connect(m_spnAngle,SIGNAL(valueChanged(int)), this, SLOT(setModified()));
-    connect(m_spnBaseline,SIGNAL(valueChanged(int)), this, SLOT(setModified()));
+    connect(m_formatButtons, SIGNAL(formattingModified()), this,
+            SLOT(setModified()));
+    connect(m_spnPrecision, SIGNAL(valueChanged(int)), this,
+            SLOT(setModified()));
+    connect(m_spnAngle, SIGNAL(valueChanged(int)), this, SLOT(setModified()));
+    connect(m_spnBaseline, SIGNAL(valueChanged(int)), this,
+            SLOT(setModified()));
     connect(m_cbtnAxisColor, SIGNAL(colorChanged()), this, SLOT(setModified()));
-    connect(m_cbtnAxisNumColor, SIGNAL(colorChanged()), this, SLOT(setModified()));
+    connect(m_cbtnAxisNumColor, SIGNAL(colorChanged()), this,
+            SLOT(setModified()));
 
     m_modified = false;
     m_initialised = true;
@@ -333,83 +340,73 @@ void AxisDetails::initWidgets()
 /** Sets the modifed flag to true so that the changes may be applied.
 *
 */
-void AxisDetails::setModified()
-{
-  m_modified = true;
-}
+void AxisDetails::setModified() { m_modified = true; }
 
 /** Checks to see if this axis has valid parameters
 *
 */
-bool AxisDetails::valid()
-{
-  if (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric)
-  {
-    if (m_chkShowFormula->isChecked())
-    {
+bool AxisDetails::valid() {
+  if (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric) {
+    if (m_chkShowFormula->isChecked()) {
       QString formula = m_txtFormula->toPlainText().toLower();
-      try
-      {
+      try {
         double value = 1.0;
         MyParser parser;
-        if (formula.contains("x"))
-        {
+        if (formula.contains("x")) {
           parser.DefineVar("x", &value);
-        }
-        else if (formula.contains("y"))
-        {
+        } else if (formula.contains("y")) {
           parser.DefineVar("y", &value);
         }
         parser.SetExpr(formula.toLatin1().data());
         parser.Eval();
-      }
-      catch(mu::ParserError &e)
-      {
-        QMessageBox::critical(this, tr("MantidPlot - Formula input error"), QString::fromStdString(e.GetMsg())+"\n"+tr("Valid variables are 'x' for Top/Bottom axes and 'y' for Left/Right axes!"));
+      } catch (mu::ParserError &e) {
+        QMessageBox::critical(this, tr("MantidPlot - Formula input error"),
+                              QString::fromStdString(e.GetMsg()) + "\n" +
+                                  tr("Valid variables are 'x' for Top/Bottom "
+                                     "axes and 'y' for Left/Right axes!"));
         return false;
       }
     }
   }
   Table *w = m_app->table(m_cmbColName->currentText());
-  return m_initialised && 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
 *
 */
-void AxisDetails::apply()
-{
-  if (m_modified && valid())
-  {
+void AxisDetails::apply() {
+  if (m_modified && valid()) {
     Table *w = m_app->table(m_cmbColName->currentText());
 
     QString formula = m_txtFormula->toPlainText();
-    if (!m_chkShowFormula->isChecked())
-    {
+    if (!m_chkShowFormula->isChecked()) {
       formula = QString();
     }
     int type = m_cmbAxisType->currentIndex();
     QString formatInfo = m_cmbColName->currentText();
-    if (type == ScaleDraw::Day || type == ScaleDraw::Month)
-    {
+    if (type == ScaleDraw::Day || type == ScaleDraw::Month) {
       formatInfo = QString::number(m_cmbFormat->currentIndex());
-    }
-    else if (type == ScaleDraw::Time || type == ScaleDraw::Date)
-    {
-      QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis)).split(";", QString::SkipEmptyParts);
-      if ((int)lst.count() >= 2)
-      {
+    } else if (type == ScaleDraw::Time || type == ScaleDraw::Date) {
+      QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis))
+                            .split(";", QString::SkipEmptyParts);
+      if ((int)lst.count() >= 2) {
         lst[1] = m_cmbFormat->currentText();
       }
       formatInfo = lst.join(";");
-    }
-    else if (type == ScaleDraw::ColHeader)
-    {
+    } else if (type == ScaleDraw::ColHeader) {
       formatInfo = m_cmbTableName->currentText();
     }
-    m_graph->showAxis(m_mappedaxis, m_cmbAxisType->currentIndex(), formatInfo, w, m_chkShowAxis->isChecked(), m_cmbMajorTicksType->currentIndex(),
-      m_cmbMinorTicksType->currentIndex(), m_grpShowLabels->isChecked(), m_cbtnAxisColor->color(), m_cmbFormat->currentIndex(), m_spnPrecision->value(),
-      m_spnAngle->value(), m_spnBaseline->value(), formula, m_cbtnAxisNumColor->color());
+    m_graph->showAxis(
+        m_mappedaxis, m_cmbAxisType->currentIndex(), formatInfo, w,
+        m_chkShowAxis->isChecked(), m_cmbMajorTicksType->currentIndex(),
+        m_cmbMinorTicksType->currentIndex(), m_grpShowLabels->isChecked(),
+        m_cbtnAxisColor->color(), m_cmbFormat->currentIndex(),
+        m_spnPrecision->value(), m_spnAngle->value(), m_spnBaseline->value(),
+        formula, m_cbtnAxisNumColor->color());
     m_graph->setAxisTitle(m_mappedaxis, m_txtTitle->toPlainText());
     m_graph->setAxisFont(m_mappedaxis, m_scaleFont);
     m_graph->setAxisTitleFont(m_mappedaxis, m_labelFont);
@@ -420,8 +417,7 @@ void AxisDetails::apply()
 /** Applies the grid paremeters to the graphs
 *
 */
-void AxisDetails::showAxis()
-{
+void AxisDetails::showAxis() {
   bool shown = m_chkShowAxis->isChecked();
   bool labels = m_grpShowLabels->isChecked();
 
@@ -429,16 +425,20 @@ void AxisDetails::showAxis()
   m_grpAxisDisplay->setEnabled(shown);
   m_grpTitle->setEnabled(shown);
 
-  if (shown)
-  {
+  if (shown) {
     m_cmbFormat->setEnabled(labels);
     m_cmbColName->setEnabled(labels);
     m_chkShowFormula->setEnabled(labels);
     m_txtFormula->setEnabled(labels);
 
-    //this should so the work of the below IF but on one line and slightly more efficently as i assume setDisabled negates that given to it
-    m_spnAngle->setEnabled((m_mappedaxis == QwtPlot::xBottom || m_mappedaxis == QwtPlot::xTop) && labels);
-    m_spnPrecision->setEnabled(labels && (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric) && (m_cmbFormat->currentIndex() != 0));
+    // this should so the work of the below IF but on one line and slightly more
+    // efficently as i assume setDisabled negates that given to it
+    m_spnAngle->setEnabled(
+        (m_mappedaxis == QwtPlot::xBottom || m_mappedaxis == QwtPlot::xTop) &&
+        labels);
+    m_spnPrecision->setEnabled(
+        labels && (m_cmbAxisType->currentIndex() == ScaleDraw::Numeric) &&
+        (m_cmbFormat->currentIndex() != 0));
 
     enableFormulaBox();
   }
@@ -446,11 +446,11 @@ void AxisDetails::showAxis()
   emit axisShowChanged(shown);
 }
 
-/** Enables, Disables, Hides or Shows widgets apropriate to the current Axis Format
+/** Enables, Disables, Hides or Shows widgets apropriate to the current Axis
+*Format
 *
 */
-void AxisDetails::setAxisFormatOptions(int type)
-{
+void AxisDetails::setAxisFormatOptions(int type) {
   m_cmbFormat->clear();
   m_cmbFormat->setEditable(false);
   m_cmbFormat->hide();
@@ -464,135 +464,118 @@ void AxisDetails::setAxisFormatOptions(int type)
   m_cmbTableName->hide();
   m_lblTable->hide();
 
-  switch (type)
-  {
-  case 0:
-    {
-      m_lblFormat->show();
-      m_cmbFormat->show();
-      m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Automatic"));
-      m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Decimal: 100.0"));
-      m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Scientific: 1e2"));
-      m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Scientific: 10^2"));
-      m_cmbFormat->setCurrentIndex(
-          m_graph->plotWidget()->axisLabelFormat(m_mappedaxis));
-
-      m_lblPrecision->show();
-      m_spnPrecision->show();
-      m_spnPrecision->setEnabled(m_cmbFormat->currentIndex() != 0);
-      m_chkShowFormula->show();
-      m_txtFormula->show();
-
-      enableFormulaBox();
-      break;
-    }
-  case 1:
-    {
-      m_lblColumn->show();
-      m_cmbColName->show();
-      break;
-    }
-  case 2:
-    {
-      int day = (QDate::currentDate()).dayOfWeek();
-      m_lblFormat->show();
-      m_cmbFormat->show();
-      m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::shortDayName(day));
-      m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::longDayName(day));
-      m_cmbFormat->insertItem(m_cmbFormat->count(),
-                              (QDate::shortDayName(day)).left(1));
-      m_cmbFormat->setCurrentIndex(
-          (m_graph->axisFormatInfo(m_mappedaxis)).toInt());
-      break;
-    }
-  case 3:
-    {
-      int month = (QDate::currentDate()).month();
-      m_lblFormat->show();
-      m_cmbFormat->show();
-      m_cmbFormat->insertItem(m_cmbFormat->count(),
-                              QDate::shortMonthName(month));
-      m_cmbFormat->insertItem(m_cmbFormat->count(),
-                              QDate::longMonthName(month));
-      m_cmbFormat->insertItem(m_cmbFormat->count(),
-                              (QDate::shortMonthName(month)).left(1));
-      m_cmbFormat->setCurrentIndex(
-          (m_graph->axisFormatInfo(m_mappedaxis)).toInt());
-    }
-    break;
-
-  case 4:
-    {
-      m_lblFormat->show();
-      m_cmbFormat->show();
-      m_cmbFormat->setEditable(true);
-
-      QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis)).split(";",
-        QString::KeepEmptyParts);
-      if (lst.count() == 2)
-      {
-        m_cmbFormat->insertItem(m_cmbFormat->count(), lst[1]);
-        m_cmbFormat->setItemText(m_cmbFormat->currentIndex(), lst[1]);
-      }
+  switch (type) {
+  case 0: {
+    m_lblFormat->show();
+    m_cmbFormat->show();
+    m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Automatic"));
+    m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Decimal: 100.0"));
+    m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Scientific: 1e2"));
+    m_cmbFormat->insertItem(m_cmbFormat->count(), tr("Scientific: 10^2"));
+    m_cmbFormat->setCurrentIndex(
+        m_graph->plotWidget()->axisLabelFormat(m_mappedaxis));
+
+    m_lblPrecision->show();
+    m_spnPrecision->show();
+    m_spnPrecision->setEnabled(m_cmbFormat->currentIndex() != 0);
+    m_chkShowFormula->show();
+    m_txtFormula->show();
 
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h ap");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h AP");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm ap");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "hh:mm");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm:ss");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm:ss.zzz");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "mm:ss");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "mm:ss.zzz");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "hmm");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "hmmss");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "hhmmss");
-      break;
-    }
-  case 5:
-    {
-      m_lblFormat->show();
-      m_cmbFormat->show();
-      m_cmbFormat->setEditable(true);
-
-      QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis)).split(";",
-        QString::KeepEmptyParts);
-      if (lst.count() == 2)
-      {
-        m_cmbFormat->insertItem(m_cmbFormat->count(), lst[1]);
-        m_cmbFormat->setItemText(m_cmbFormat->currentIndex(), lst[1]);
-      }
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "yyyy-MM-dd");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "dd.MM.yyyy");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "ddd MMMM d yy");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "dd/MM/yyyy");
-      m_cmbFormat->insertItem(m_cmbFormat->count(), "HH:mm:ss");
-      break;
+    enableFormulaBox();
+    break;
+  }
+  case 1: {
+    m_lblColumn->show();
+    m_cmbColName->show();
+    break;
+  }
+  case 2: {
+    int day = (QDate::currentDate()).dayOfWeek();
+    m_lblFormat->show();
+    m_cmbFormat->show();
+    m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::shortDayName(day));
+    m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::longDayName(day));
+    m_cmbFormat->insertItem(m_cmbFormat->count(),
+                            (QDate::shortDayName(day)).left(1));
+    m_cmbFormat->setCurrentIndex(
+        (m_graph->axisFormatInfo(m_mappedaxis)).toInt());
+    break;
+  }
+  case 3: {
+    int month = (QDate::currentDate()).month();
+    m_lblFormat->show();
+    m_cmbFormat->show();
+    m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::shortMonthName(month));
+    m_cmbFormat->insertItem(m_cmbFormat->count(), QDate::longMonthName(month));
+    m_cmbFormat->insertItem(m_cmbFormat->count(),
+                            (QDate::shortMonthName(month)).left(1));
+    m_cmbFormat->setCurrentIndex(
+        (m_graph->axisFormatInfo(m_mappedaxis)).toInt());
+  } break;
+
+  case 4: {
+    m_lblFormat->show();
+    m_cmbFormat->show();
+    m_cmbFormat->setEditable(true);
+
+    QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis))
+                          .split(";", QString::KeepEmptyParts);
+    if (lst.count() == 2) {
+      m_cmbFormat->insertItem(m_cmbFormat->count(), lst[1]);
+      m_cmbFormat->setItemText(m_cmbFormat->currentIndex(), lst[1]);
     }
-  case 6:
-    {
-      m_lblTable->show();
-      QString tableName = m_graph->axisFormatInfo(m_mappedaxis);
-      if (m_tablesList.contains(tableName))
-        m_cmbTableName->setItemText(m_cmbTableName->currentIndex(), tableName);
-      m_cmbTableName->show();
-      break;
+
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h ap");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h AP");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm ap");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "hh:mm");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm:ss");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "h:mm:ss.zzz");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "mm:ss");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "mm:ss.zzz");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "hmm");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "hmmss");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "hhmmss");
+    break;
+  }
+  case 5: {
+    m_lblFormat->show();
+    m_cmbFormat->show();
+    m_cmbFormat->setEditable(true);
+
+    QStringList lst = (m_graph->axisFormatInfo(m_mappedaxis))
+                          .split(";", QString::KeepEmptyParts);
+    if (lst.count() == 2) {
+      m_cmbFormat->insertItem(m_cmbFormat->count(), lst[1]);
+      m_cmbFormat->setItemText(m_cmbFormat->currentIndex(), lst[1]);
     }
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "yyyy-MM-dd");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "dd.MM.yyyy");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "ddd MMMM d yy");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "dd/MM/yyyy");
+    m_cmbFormat->insertItem(m_cmbFormat->count(), "HH:mm:ss");
+    break;
+  }
+  case 6: {
+    m_lblTable->show();
+    QString tableName = m_graph->axisFormatInfo(m_mappedaxis);
+    if (m_tablesList.contains(tableName))
+      m_cmbTableName->setItemText(m_cmbTableName->currentIndex(), tableName);
+    m_cmbTableName->show();
+    break;
+  }
   }
 }
 
 /** enables or disables the formula text entry fields
 *
 */
-void AxisDetails::enableFormulaBox()
-{
-  if (m_chkShowFormula->isChecked())
-  {
+void AxisDetails::enableFormulaBox() {
+  if (m_chkShowFormula->isChecked()) {
     m_txtFormula->setEnabled(true);
-  }
-  else
-  {
+  } else {
     m_txtFormula->setEnabled(false);
   }
 }
@@ -600,13 +583,11 @@ void AxisDetails::enableFormulaBox()
 /** sets the font to use on the scale title
 *
 */
-void AxisDetails::setLabelFont()
-{
+void AxisDetails::setLabelFont() {
   bool okF;
   QFont oldFont = m_graph->axisTitleFont(m_mappedaxis);
   QFont fnt = QFontDialog::getFont(&okF, oldFont, this);
-  if (okF && fnt != oldFont)
-  {
+  if (okF && fnt != oldFont) {
     m_labelFont = fnt;
   }
 }
@@ -614,13 +595,11 @@ void AxisDetails::setLabelFont()
 /** sets the font to use on the scale numbers
 *
 */
-void AxisDetails::setScaleFont()
-{
+void AxisDetails::setScaleFont() {
   bool okF;
   QFont oldFont = m_graph->axisFont(m_mappedaxis);
   QFont fnt = QFontDialog::getFont(&okF, oldFont, this);
-  if (okF && fnt != oldFont)
-  {
+  if (okF && fnt != oldFont) {
     m_scaleFont = fnt;
-  }  
+  }
 }
diff --git a/MantidPlot/src/AxisDetails.h b/MantidPlot/src/AxisDetails.h
index c1498ff5badfd461818938eebd484454d5ca7bd4..f07991211bf4a964f628aa580388a2ed60d1b648 100644
--- a/MantidPlot/src/AxisDetails.h
+++ b/MantidPlot/src/AxisDetails.h
@@ -1,10 +1,13 @@
 /**
-This class holds the widgets that hold the details for each axis so the contents are only filled once and switching axis only changes a pointer.
+This class holds the widgets that hold the details for each axis so the contents
+are only filled once and switching axis only changes a pointer.
 
-@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory from the University of Derby
+@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory
+from the University of Derby
 @date 15/09/2013
 
-Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -48,21 +51,21 @@ class Graph;
 class TextFormatButtons;
 class ColorButton;
 
-class AxisDetails: public QWidget
-{
+class AxisDetails : public QWidget {
   Q_OBJECT
-    //details for each axis in the Axis tab
+  // details for each axis in the Axis tab
 public:
-  AxisDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, QWidget *parent = 0); // populate and fill in with existing data
+  AxisDetails(ApplicationWindow *app, Graph *graph, int mappedaxis,
+              QWidget *parent = 0); // populate and fill in with existing data
   ~AxisDetails() override;
   void initWidgets();
-  bool modified(){return m_modified;}
+  bool modified() { return m_modified; }
   void apply();
   bool valid();
 
 signals:
   void axisShowChanged(bool enabled);
-    
+
 private slots:
   void enableFormulaBox();
   void showAxis();
@@ -74,14 +77,15 @@ private slots:
 private:
   bool m_modified, m_initialised;
   int m_mappedaxis;
-  ApplicationWindow* m_app;
-  Graph* m_graph;
+  ApplicationWindow *m_app;
+  Graph *m_graph;
   QCheckBox *m_chkShowAxis, *m_chkShowFormula;
   QGroupBox *m_grpTitle, *m_grpShowLabels, *m_grpAxisDisplay;
   QTextEdit *m_txtFormula, *m_txtTitle;
   QPushButton *m_btnLabelFont, *m_btnAxesFont;
   TextFormatButtons *m_formatButtons;
-  QComboBox *m_cmbMajorTicksType, *m_cmbTableName, *m_cmbMinorTicksType, *m_cmbAxisType, *m_cmbFormat, *m_cmbColName;
+  QComboBox *m_cmbMajorTicksType, *m_cmbTableName, *m_cmbMinorTicksType,
+      *m_cmbAxisType, *m_cmbFormat, *m_cmbColName;
   ColorButton *m_cbtnAxisColor, *m_cbtnAxisNumColor;
   QSpinBox *m_spnPrecision, *m_spnAngle, *m_spnBaseline;
   QLabel *m_lblColumn, *m_lblFormat, *m_lblPrecision, *m_lblTable;
diff --git a/MantidPlot/src/Bar.cpp b/MantidPlot/src/Bar.cpp
index 4a5e331b7b57d65e8d7a7b805286251279bedf2e..ebe28303bd1d46170531060f20abd048c163cd5b 100644
--- a/MantidPlot/src/Bar.cpp
+++ b/MantidPlot/src/Bar.cpp
@@ -2,10 +2,11 @@
     File                 : Bar.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : 3D bars (modifed enrichment from QwtPlot3D)
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -34,7 +35,6 @@
 #include <qwt3d_plot.h>
 #include "Bar.h"
 
-
 using namespace Qwt3D;
 
 /////////////////////////////////////////////////////////////////
@@ -43,102 +43,103 @@ using namespace Qwt3D;
 //
 /////////////////////////////////////////////////////////////////
 
-Bar::Bar()
-{
-  configure(0);
-}
+Bar::Bar() { configure(0); }
 
-Bar::Bar(double rad)
-{
-  configure(rad);
-}
+Bar::Bar(double rad) { configure(rad); }
 
-void Bar::configure(double rad)
-{
+void Bar::configure(double rad) {
   plot = 0;
   radius_ = rad;
   diag_ = 0.0;
 }
 
-void Bar::drawBegin()
-{  
-  diag_ = (plot->hull().maxVertex-plot->hull().minVertex).length() * radius_;
-  glLineWidth( GLfloat(plot->meshLineWidth()) );
+void Bar::drawBegin() {
+  diag_ = (plot->hull().maxVertex - plot->hull().minVertex).length() * radius_;
+  glLineWidth(GLfloat(plot->meshLineWidth()));
   glEnable(GL_POLYGON_OFFSET_FILL);
-  glPolygonOffset(1,1);
+  glPolygonOffset(1, 1);
 }
 
-void Bar::drawEnd()
-{
-}
+void Bar::drawEnd() {}
 
-void Bar::draw(Qwt3D::Triple const& pos)
-{
+void Bar::draw(Qwt3D::Triple const &pos) {
   GLdouble minz = plot->hull().minVertex.z;
 
   RGBA rgbat = (*plot->dataColor())(pos);
-	RGBA rgbab = (*plot->dataColor())(pos.x, pos.y, minz);
-	
+  RGBA rgbab = (*plot->dataColor())(pos.x, pos.y, minz);
+
   glBegin(GL_QUADS);
-    glColor4d(rgbab.r,rgbab.g,rgbab.b,rgbab.a);
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y+diag_,minz);
-    glVertex3d(pos.x-diag_,pos.y+diag_,minz);
-
-      glColor4d(rgbat.r,rgbat.g,rgbat.b,rgbat.a);
-	
-    glVertex3d(pos.x-diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x+diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y+diag_,pos.z);
-
-    glColor4d(rgbab.r,rgbab.g,rgbat.b,rgbab.a);
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y-diag_,minz);
-    glColor4d(rgbat.r,rgbat.g,rgbat.b,rgbat.a);
-    glVertex3d(pos.x+diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y-diag_,pos.z);
-
-    glColor4d(rgbab.r,rgbab.g,rgbat.b,rgbab.a);
-    glVertex3d(pos.x-diag_,pos.y+diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y+diag_,minz);
-    glColor4d(rgbat.r,rgbat.g,rgbat.b,rgbat.a);
-    glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y+diag_,pos.z);
-
-    glColor4d(rgbab.r,rgbab.g,rgbat.b,rgbab.a);
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x-diag_,pos.y+diag_,minz);
-    glColor4d(rgbat.r,rgbat.g,rgbat.b,rgbat.a);
-    glVertex3d(pos.x-diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y-diag_,pos.z);
-
-    glColor4d(rgbab.r,rgbab.g,rgbat.b,rgbab.a);
-    glVertex3d(pos.x+diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y+diag_,minz);
-    glColor4d(rgbat.r,rgbat.g,rgbat.b,rgbat.a);
-    glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x+diag_,pos.y-diag_,pos.z);
+  glColor4d(rgbab.r, rgbab.g, rgbab.b, rgbab.a);
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+
+  glColor4d(rgbat.r, rgbat.g, rgbat.b, rgbat.a);
+
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
+
+  glColor4d(rgbab.r, rgbab.g, rgbat.b, rgbab.a);
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glColor4d(rgbat.r, rgbat.g, rgbat.b, rgbat.a);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+
+  glColor4d(rgbab.r, rgbab.g, rgbat.b, rgbab.a);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+  glColor4d(rgbat.r, rgbat.g, rgbat.b, rgbat.a);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
+
+  glColor4d(rgbab.r, rgbab.g, rgbat.b, rgbab.a);
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+  glColor4d(rgbat.r, rgbat.g, rgbat.b, rgbat.a);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+
+  glColor4d(rgbab.r, rgbab.g, rgbat.b, rgbab.a);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+  glColor4d(rgbat.r, rgbat.g, rgbat.b, rgbat.a);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
   glEnd();
 
-	Qwt3D::RGBA meshCol=plot->meshColor();//using mesh color to draw the lines
-    glColor3d(meshCol.r,meshCol.g,meshCol.b);
+  Qwt3D::RGBA meshCol = plot->meshColor(); // using mesh color to draw the lines
+  glColor3d(meshCol.r, meshCol.g, meshCol.b);
 
   glBegin(GL_LINES);
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz); glVertex3d(pos.x+diag_,pos.y-diag_,minz);
-    glVertex3d(pos.x-diag_,pos.y-diag_,pos.z); glVertex3d(pos.x+diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y+diag_,pos.z); glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y+diag_,minz); glVertex3d(pos.x+diag_,pos.y+diag_,minz);
-
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz); glVertex3d(pos.x-diag_,pos.y+diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y-diag_,minz); glVertex3d(pos.x+diag_,pos.y+diag_,minz);
-    glVertex3d(pos.x+diag_,pos.y-diag_,pos.z); glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y-diag_,pos.z); glVertex3d(pos.x-diag_,pos.y+diag_,pos.z);
-
-    glVertex3d(pos.x-diag_,pos.y-diag_,minz); glVertex3d(pos.x-diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x+diag_,pos.y-diag_,minz); glVertex3d(pos.x+diag_,pos.y-diag_,pos.z);
-    glVertex3d(pos.x+diag_,pos.y+diag_,minz); glVertex3d(pos.x+diag_,pos.y+diag_,pos.z);
-    glVertex3d(pos.x-diag_,pos.y+diag_,minz); glVertex3d(pos.x-diag_,pos.y+diag_,pos.z);
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
+
+  glVertex3d(pos.x - diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y - diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
+  glVertex3d(pos.x + diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
+  glVertex3d(pos.x - diag_, pos.y + diag_, minz);
+  glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
   glEnd();
 }
diff --git a/MantidPlot/src/Bar.h b/MantidPlot/src/Bar.h
index b7a63db8bc28b28bccd59604fb580375f85246e0..2094dc6d8beb70cacfa6c9ea10c1bfa0d7705526 100644
--- a/MantidPlot/src/Bar.h
+++ b/MantidPlot/src/Bar.h
@@ -2,10 +2,11 @@
     File                 : Bar.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : 3D bars (modifed enrichment from QwtPlot3D)
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -32,8 +33,7 @@
 #include <qwt3d_plot.h>
 
 //! 3D bars (modifed enrichment from QwtPlot3D)
-class Bar : public Qwt3D::VertexEnrichment
-{
+class Bar : public Qwt3D::VertexEnrichment {
 public:
   Bar();
   explicit Bar(double rad);
@@ -50,5 +50,4 @@ private:
   double diag_;
 };
 
-
 #endif
diff --git a/MantidPlot/src/BoxCurve.cpp b/MantidPlot/src/BoxCurve.cpp
index 88752dd2ceb0c6beb89e2d1664db7ab424a99b1c..7defb084400dc0538eeb6fbf117460ef1c943d6a 100644
--- a/MantidPlot/src/BoxCurve.cpp
+++ b/MantidPlot/src/BoxCurve.cpp
@@ -2,7 +2,8 @@
     File                 : BoxCurve.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Box curve
 
@@ -32,321 +33,297 @@
 #include <gsl/gsl_sort.h>
 #include <gsl/gsl_statistics.h>
 
-BoxCurve::BoxCurve(Table *t, const QString& name, int startRow, int endRow):
-	DataCurve(t, QString(), name, startRow, endRow)
-{
-	mean_style = QwtSymbol::Rect;
-	max_style = QwtSymbol::XCross;
-	min_style = QwtSymbol::XCross;
-	p99_style = QwtSymbol::NoSymbol;
-	p1_style = QwtSymbol::NoSymbol;
-
-	b_style = Rect;
-	b_coeff = 75.0;
-	b_range = r25_75;
-	w_range = r5_95;
-	w_coeff = 95.0;
-	b_width = 80;
-
-	setType(Graph::Box);
-    setStyle(QwtPlotCurve::UserCurve);
+BoxCurve::BoxCurve(Table *t, const QString &name, int startRow, int endRow)
+    : DataCurve(t, QString(), name, startRow, endRow) {
+  mean_style = QwtSymbol::Rect;
+  max_style = QwtSymbol::XCross;
+  min_style = QwtSymbol::XCross;
+  p99_style = QwtSymbol::NoSymbol;
+  p1_style = QwtSymbol::NoSymbol;
+
+  b_style = Rect;
+  b_coeff = 75.0;
+  b_range = r25_75;
+  w_range = r5_95;
+  w_coeff = 95.0;
+  b_width = 80;
+
+  setType(Graph::Box);
+  setStyle(QwtPlotCurve::UserCurve);
 }
 
-void BoxCurve::copy(const BoxCurve *b)
-{
-	mean_style = b->mean_style;
-	max_style = b->max_style;
-	min_style = b->min_style;
-	p99_style = b->p99_style;
-	p1_style = b->p1_style;
-
-	b_style = b->b_style;
-	b_coeff = b->b_coeff;
-	b_range = b->b_range;
-	w_range = b->w_range;
-	w_coeff = b->w_coeff;
-	b_width = b->b_width;
+void BoxCurve::copy(const BoxCurve *b) {
+  mean_style = b->mean_style;
+  max_style = b->max_style;
+  min_style = b->min_style;
+  p99_style = b->p99_style;
+  p1_style = b->p1_style;
+
+  b_style = b->b_style;
+  b_coeff = b->b_coeff;
+  b_range = b->b_range;
+  w_range = b->w_range;
+  w_coeff = b->w_coeff;
+  b_width = b->b_width;
 }
 
-void BoxCurve::draw(QPainter *painter,
-		const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
-	if ( !painter || dataSize() <= 0 )
-		return;
+void BoxCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                    const QwtScaleMap &yMap, int from, int to) const {
+  if (!painter || dataSize() <= 0)
+    return;
 
-	int size = dataSize();
-	if (to < 0)
-		to = size - 1;
+  int size = dataSize();
+  if (to < 0)
+    to = size - 1;
 
-	painter->save();
-	painter->setPen(pen());
+  painter->save();
+  painter->setPen(pen());
 
-	double *dat = new double[size];
-	for (int i = from; i<= to; i++)
-		dat[i] = y(i);
+  double *dat = new double[size];
+  for (int i = from; i <= to; i++)
+    dat[i] = y(i);
 
-	drawBox(painter, xMap, yMap, dat, size);
-	drawSymbols(painter, xMap, yMap, dat, size);
+  drawBox(painter, xMap, yMap, dat, size);
+  drawSymbols(painter, xMap, yMap, dat, size);
 
-	painter->restore();
-	delete[] dat;
+  painter->restore();
+  delete[] dat;
 }
 
 void BoxCurve::drawBox(QPainter *painter, const QwtScaleMap &xMap,
-		const QwtScaleMap &yMap, double *dat, int size) const
-{
-	const int px = xMap.transform(x(0));
-	const int px_min = xMap.transform(x(0) - 0.5);
-	const int px_max = xMap.transform(x(0) + 0.5);
-	const int box_width = 1+(px_max - px_min)*b_width/100;
-	const int hbw = box_width/2;
-	const int median = yMap.transform(gsl_stats_median_from_sorted_data (dat, 1, size));
-	int b_lowerq, b_upperq;
-	double sd = 0, se = 0, mean = 0;
-	if(w_range == SD || w_range == SE || b_range == SD || b_range == SE)
-	{
-		sd = gsl_stats_sd(dat, 1, size);
-		se = sd/sqrt((double)size);
-		mean = gsl_stats_mean(dat, 1, size);
-	}
-
-	if(b_range == SD)
-	{
-		b_lowerq = yMap.transform(mean - sd*b_coeff);
-		b_upperq = yMap.transform(mean + sd*b_coeff);
-	}
-	else if(b_range == SE)
-	{
-		b_lowerq = yMap.transform(mean - se*b_coeff);
-		b_upperq = yMap.transform(mean + se*b_coeff);
-	}
-	else
-	{
-		b_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 1-0.01*b_coeff));
-		b_upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.01*b_coeff));
-	}
-
-	//draw box
-	if (b_style == Rect)
-	{
-		const QRect r = QRect(px - hbw, b_upperq, box_width, b_lowerq - b_upperq + 1);
-		painter->fillRect(r, QwtPlotCurve::brush());
-		painter->drawRect(r);
-	}
-	else if (b_style == Diamond)
-	{
-		QPolygon pa(4);
-		pa[0] = QPoint(px, b_upperq);
-		pa[1] = QPoint(px + hbw, median);
-		pa[2] = QPoint(px, b_lowerq);
-		pa[3] = QPoint(px - hbw, median);
-
-		painter->setBrush(QwtPlotCurve::brush());
-		painter->drawPolygon(pa);
-	}
-	else if (b_style == WindBox)
-	{
-		const int lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.25));
-		const int upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.75));
-		QPolygon pa(8);
-		pa[0] = QPoint(px + hbw, b_upperq);
-		pa[1] = QPoint(static_cast<int>(px + 0.4*box_width), upperq);
-		pa[2] = QPoint(static_cast<int>(px + 0.4*box_width), lowerq);
-		pa[3] = QPoint(px + hbw, b_lowerq);
-		pa[4] = QPoint(px - hbw, b_lowerq);
-		pa[5] = QPoint(static_cast<int>(px - 0.4*box_width), lowerq);
-		pa[6] = QPoint(static_cast<int>(px - 0.4*box_width), upperq);
-		pa[7] = QPoint(px - hbw, b_upperq);
-
-		painter->setBrush(QwtPlotCurve::brush());
-		painter->drawPolygon(pa);
-	}
-	else if (b_style == Notch)
-	{
-		int j = (int)ceil(0.5*(size - 1.96*sqrt((double)size)));
-		int k = (int)ceil(0.5*(size + 1.96*sqrt((double)size)));
-		const int lowerCI = yMap.transform(dat[j]);
-		const int upperCI = yMap.transform(dat[k]);
-
-		QPolygon pa(10);
-		pa[0] = QPoint(px + hbw, b_upperq);
-		pa[1] = QPoint(px + hbw, upperCI);
-		pa[2] = QPoint(static_cast<int>(px + 0.25*hbw), median);
-		pa[3] = QPoint(px + hbw, lowerCI);
-		pa[4] = QPoint(px + hbw, b_lowerq);
-		pa[5] = QPoint(px - hbw, b_lowerq);
-		pa[6] = QPoint(px - hbw, lowerCI);
-		pa[7] = QPoint(static_cast<int>(px - 0.25*hbw), median);
-		pa[8] = QPoint(px - hbw, upperCI);
-		pa[9] = QPoint(px - hbw, b_upperq);
-
-		painter->setBrush(QwtPlotCurve::brush());
-		painter->drawPolygon(pa);
-	}
-
-	if (w_range)
-	{//draw whiskers
-		const int l = static_cast<int>(0.1*box_width);
-		int w_upperq, w_lowerq;
-		if(w_range == SD)
-		{
-			w_lowerq = yMap.transform(mean - sd*w_coeff);
-			w_upperq = yMap.transform(mean + sd*w_coeff);
-		}
-		else if(w_range == SE)
-		{
-			w_lowerq = yMap.transform(mean - se*w_coeff);
-			w_upperq = yMap.transform(mean + se*w_coeff);
-		}
-		else
-		{
-			w_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 1-0.01*w_coeff));
-			w_upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.01*w_coeff));
-		}
-
-		painter->drawLine(px - l, w_lowerq, px + l, w_lowerq);
-		painter->drawLine(px - l, w_upperq, px + l, w_upperq);
-
-		if (b_style)
-		{
-			if (w_upperq != b_upperq)
-				painter->drawLine(px, w_upperq, px, b_upperq);
-			if (w_lowerq != b_lowerq)
-				painter->drawLine(px, w_lowerq, px, b_lowerq);
-		}
-		else
-			painter->drawLine(px, w_upperq, px, w_lowerq);
-	}
-
-	//draw median line
-	if (b_style == Notch || b_style == NoBox)
-		return;
-	if (b_style == WindBox)
-		painter->drawLine(static_cast<int>(px - 0.4*box_width), median, static_cast<int>(px + 0.4*box_width), median);
-	else
-		painter->drawLine(px - hbw, median, px + hbw, median);
+                       const QwtScaleMap &yMap, double *dat, int size) const {
+  const int px = xMap.transform(x(0));
+  const int px_min = xMap.transform(x(0) - 0.5);
+  const int px_max = xMap.transform(x(0) + 0.5);
+  const int box_width = 1 + (px_max - px_min) * b_width / 100;
+  const int hbw = box_width / 2;
+  const int median =
+      yMap.transform(gsl_stats_median_from_sorted_data(dat, 1, size));
+  int b_lowerq, b_upperq;
+  double sd = 0, se = 0, mean = 0;
+  if (w_range == SD || w_range == SE || b_range == SD || b_range == SE) {
+    sd = gsl_stats_sd(dat, 1, size);
+    se = sd / sqrt((double)size);
+    mean = gsl_stats_mean(dat, 1, size);
+  }
+
+  if (b_range == SD) {
+    b_lowerq = yMap.transform(mean - sd * b_coeff);
+    b_upperq = yMap.transform(mean + sd * b_coeff);
+  } else if (b_range == SE) {
+    b_lowerq = yMap.transform(mean - se * b_coeff);
+    b_upperq = yMap.transform(mean + se * b_coeff);
+  } else {
+    b_lowerq = yMap.transform(
+        gsl_stats_quantile_from_sorted_data(dat, 1, size, 1 - 0.01 * b_coeff));
+    b_upperq = yMap.transform(
+        gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.01 * b_coeff));
+  }
+
+  // draw box
+  if (b_style == Rect) {
+    const QRect r =
+        QRect(px - hbw, b_upperq, box_width, b_lowerq - b_upperq + 1);
+    painter->fillRect(r, QwtPlotCurve::brush());
+    painter->drawRect(r);
+  } else if (b_style == Diamond) {
+    QPolygon pa(4);
+    pa[0] = QPoint(px, b_upperq);
+    pa[1] = QPoint(px + hbw, median);
+    pa[2] = QPoint(px, b_lowerq);
+    pa[3] = QPoint(px - hbw, median);
+
+    painter->setBrush(QwtPlotCurve::brush());
+    painter->drawPolygon(pa);
+  } else if (b_style == WindBox) {
+    const int lowerq =
+        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.25));
+    const int upperq =
+        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.75));
+    QPolygon pa(8);
+    pa[0] = QPoint(px + hbw, b_upperq);
+    pa[1] = QPoint(static_cast<int>(px + 0.4 * box_width), upperq);
+    pa[2] = QPoint(static_cast<int>(px + 0.4 * box_width), lowerq);
+    pa[3] = QPoint(px + hbw, b_lowerq);
+    pa[4] = QPoint(px - hbw, b_lowerq);
+    pa[5] = QPoint(static_cast<int>(px - 0.4 * box_width), lowerq);
+    pa[6] = QPoint(static_cast<int>(px - 0.4 * box_width), upperq);
+    pa[7] = QPoint(px - hbw, b_upperq);
+
+    painter->setBrush(QwtPlotCurve::brush());
+    painter->drawPolygon(pa);
+  } else if (b_style == Notch) {
+    int j = (int)ceil(0.5 * (size - 1.96 * sqrt((double)size)));
+    int k = (int)ceil(0.5 * (size + 1.96 * sqrt((double)size)));
+    const int lowerCI = yMap.transform(dat[j]);
+    const int upperCI = yMap.transform(dat[k]);
+
+    QPolygon pa(10);
+    pa[0] = QPoint(px + hbw, b_upperq);
+    pa[1] = QPoint(px + hbw, upperCI);
+    pa[2] = QPoint(static_cast<int>(px + 0.25 * hbw), median);
+    pa[3] = QPoint(px + hbw, lowerCI);
+    pa[4] = QPoint(px + hbw, b_lowerq);
+    pa[5] = QPoint(px - hbw, b_lowerq);
+    pa[6] = QPoint(px - hbw, lowerCI);
+    pa[7] = QPoint(static_cast<int>(px - 0.25 * hbw), median);
+    pa[8] = QPoint(px - hbw, upperCI);
+    pa[9] = QPoint(px - hbw, b_upperq);
+
+    painter->setBrush(QwtPlotCurve::brush());
+    painter->drawPolygon(pa);
+  }
+
+  if (w_range) { // draw whiskers
+    const int l = static_cast<int>(0.1 * box_width);
+    int w_upperq, w_lowerq;
+    if (w_range == SD) {
+      w_lowerq = yMap.transform(mean - sd * w_coeff);
+      w_upperq = yMap.transform(mean + sd * w_coeff);
+    } else if (w_range == SE) {
+      w_lowerq = yMap.transform(mean - se * w_coeff);
+      w_upperq = yMap.transform(mean + se * w_coeff);
+    } else {
+      w_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data(
+          dat, 1, size, 1 - 0.01 * w_coeff));
+      w_upperq = yMap.transform(
+          gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.01 * w_coeff));
+    }
+
+    painter->drawLine(px - l, w_lowerq, px + l, w_lowerq);
+    painter->drawLine(px - l, w_upperq, px + l, w_upperq);
+
+    if (b_style) {
+      if (w_upperq != b_upperq)
+        painter->drawLine(px, w_upperq, px, b_upperq);
+      if (w_lowerq != b_lowerq)
+        painter->drawLine(px, w_lowerq, px, b_lowerq);
+    } else
+      painter->drawLine(px, w_upperq, px, w_lowerq);
+  }
+
+  // draw median line
+  if (b_style == Notch || b_style == NoBox)
+    return;
+  if (b_style == WindBox)
+    painter->drawLine(static_cast<int>(px - 0.4 * box_width), median,
+                      static_cast<int>(px + 0.4 * box_width), median);
+  else
+    painter->drawLine(px - hbw, median, px + hbw, median);
 }
 
 void BoxCurve::drawSymbols(QPainter *painter, const QwtScaleMap &xMap,
-		const QwtScaleMap &yMap, double *dat, int size) const
-{
-	const int px = xMap.transform(x(0));
-
-	QwtSymbol s = this->symbol();
-	if (min_style != QwtSymbol::NoSymbol)
-	{
-		const int py_min = yMap.transform(y(0));
-		s.setStyle(min_style);
-		s.draw(painter, px, py_min);
-	}
-	if (max_style != QwtSymbol::NoSymbol)
-	{
-		const int py_max = yMap.transform(y(size - 1));
-		s.setStyle(max_style);
-		s.draw(painter, px, py_max);
-	}
-	if (p1_style != QwtSymbol::NoSymbol)
-	{
-		const int p1 = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.01));
-		s.setStyle(p1_style);
-		s.draw(painter, px, p1);
-	}
-	if (p99_style != QwtSymbol::NoSymbol)
-	{
-		const int p99 = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.99));
-		s.setStyle(p99_style);
-		s.draw(painter, px, p99);
-	}
-	if (mean_style != QwtSymbol::NoSymbol)
-	{
-		const int mean = yMap.transform(gsl_stats_mean(dat, 1, size));
-		s.setStyle(mean_style);
-		s.draw(painter, px, mean);
-	}
+                           const QwtScaleMap &yMap, double *dat,
+                           int size) const {
+  const int px = xMap.transform(x(0));
+
+  QwtSymbol s = this->symbol();
+  if (min_style != QwtSymbol::NoSymbol) {
+    const int py_min = yMap.transform(y(0));
+    s.setStyle(min_style);
+    s.draw(painter, px, py_min);
+  }
+  if (max_style != QwtSymbol::NoSymbol) {
+    const int py_max = yMap.transform(y(size - 1));
+    s.setStyle(max_style);
+    s.draw(painter, px, py_max);
+  }
+  if (p1_style != QwtSymbol::NoSymbol) {
+    const int p1 =
+        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.01));
+    s.setStyle(p1_style);
+    s.draw(painter, px, p1);
+  }
+  if (p99_style != QwtSymbol::NoSymbol) {
+    const int p99 =
+        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.99));
+    s.setStyle(p99_style);
+    s.draw(painter, px, p99);
+  }
+  if (mean_style != QwtSymbol::NoSymbol) {
+    const int mean = yMap.transform(gsl_stats_mean(dat, 1, size));
+    s.setStyle(mean_style);
+    s.draw(painter, px, mean);
+  }
 }
 
-void BoxCurve::setBoxStyle(int style)
-{
-	if (b_style == style)
-		return;
-	b_style=style;
+void BoxCurve::setBoxStyle(int style) {
+  if (b_style == style)
+    return;
+  b_style = style;
 }
 
-void BoxCurve::setBoxRange(int type, double coeff)
-{
-	if (b_style == WindBox)
-	{
-		b_range = r10_90;
-		b_coeff = 90.0;
-		return;
-	}
-
-	b_range = type;
-
-	if (b_range == r25_75)
-		b_coeff = 75.0;
-	else if (b_range == r10_90)
-		b_coeff = 90.0;
-	else if (b_range == r5_95)
-		b_coeff = 95.0;
-	else if (b_range == r1_99)
-		b_coeff = 99.0;
-	else if (b_range == MinMax)
-		b_coeff = 100.0;
-	else
-		b_coeff = coeff;
+void BoxCurve::setBoxRange(int type, double coeff) {
+  if (b_style == WindBox) {
+    b_range = r10_90;
+    b_coeff = 90.0;
+    return;
+  }
+
+  b_range = type;
+
+  if (b_range == r25_75)
+    b_coeff = 75.0;
+  else if (b_range == r10_90)
+    b_coeff = 90.0;
+  else if (b_range == r5_95)
+    b_coeff = 95.0;
+  else if (b_range == r1_99)
+    b_coeff = 99.0;
+  else if (b_range == MinMax)
+    b_coeff = 100.0;
+  else
+    b_coeff = coeff;
 }
 
-void BoxCurve::setWhiskersRange(int type, double coeff)
-{
-	w_range = type;
-
-	if (w_range == r25_75)
-		w_coeff = 75.0;
-	else if (w_range == r10_90)
-		w_coeff = 90.0;
-	else if (w_range == r5_95)
-		w_coeff = 95.0;
-	else if (w_range == r1_99)
-		w_coeff = 99.0;
-	else if (w_range == MinMax)
-		w_coeff = 100.0;
-	else
-		w_coeff = coeff;
+void BoxCurve::setWhiskersRange(int type, double coeff) {
+  w_range = type;
+
+  if (w_range == r25_75)
+    w_coeff = 75.0;
+  else if (w_range == r10_90)
+    w_coeff = 90.0;
+  else if (w_range == r5_95)
+    w_coeff = 95.0;
+  else if (w_range == r1_99)
+    w_coeff = 99.0;
+  else if (w_range == MinMax)
+    w_coeff = 100.0;
+  else
+    w_coeff = coeff;
 }
 
-QwtDoubleRect BoxCurve::boundingRect() const
-{
-	QwtDoubleRect rect = QwtPlotCurve::boundingRect();
+QwtDoubleRect BoxCurve::boundingRect() const {
+  QwtDoubleRect rect = QwtPlotCurve::boundingRect();
 
-	double dy=0.2*(rect.bottom()-rect.top());
-	rect.setTop(rect.top()-dy);
-	rect.setBottom(rect.bottom()+dy);
+  double dy = 0.2 * (rect.bottom() - rect.top());
+  rect.setTop(rect.top() - dy);
+  rect.setBottom(rect.bottom() + dy);
 
-	rect.setLeft(rect.left()-0.5);
-	rect.setRight(rect.right()+0.5);
-	return rect;
+  rect.setLeft(rect.left() - 0.5);
+  rect.setRight(rect.right() + 0.5);
+  return rect;
 }
 
-void BoxCurve::loadData()
-{
-	QVector<double> Y(abs(d_end_row - d_start_row) + 1);
-    int ycol = d_table->colIndex(title().text());
-	int size = 0;
-	for (int i = d_start_row; i <= d_end_row; i++){
-		QString s = d_table->text(i, ycol);
-        if (!s.isEmpty()){
-            bool valid_data = true;
-            Y[size] = (dynamic_cast<Plot *>(plot()))->locale().toDouble(s, &valid_data);
-            if (valid_data)
-                size++;
-        }
-	}
-
-	if (size>0){
-		Y.resize(size);
-		gsl_sort (Y.data(), 1, size);
-        setData(QwtSingleArrayData(this->x(0), Y, size));
-	} else
-		remove();
+void BoxCurve::loadData() {
+  QVector<double> Y(abs(d_end_row - d_start_row) + 1);
+  int ycol = d_table->colIndex(title().text());
+  int size = 0;
+  for (int i = d_start_row; i <= d_end_row; i++) {
+    QString s = d_table->text(i, ycol);
+    if (!s.isEmpty()) {
+      bool valid_data = true;
+      Y[size] =
+          (dynamic_cast<Plot *>(plot()))->locale().toDouble(s, &valid_data);
+      if (valid_data)
+        size++;
+    }
+  }
+
+  if (size > 0) {
+    Y.resize(size);
+    gsl_sort(Y.data(), 1, size);
+    setData(QwtSingleArrayData(this->x(0), Y, size));
+  } else
+    remove();
 }
diff --git a/MantidPlot/src/BoxCurve.h b/MantidPlot/src/BoxCurve.h
index b3cd3bb368f30f9b80b0e46c0828464c3b142346..fd0a301413343af6e342facf1b8bbc8de5988ffb 100644
--- a/MantidPlot/src/BoxCurve.h
+++ b/MantidPlot/src/BoxCurve.h
@@ -2,7 +2,8 @@
     File                 : BoxCurve.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Box curve
 
@@ -34,86 +35,84 @@
 #include <qwt_symbol.h>
 
 //! Box curve
-class BoxCurve: public DataCurve
-{
+class BoxCurve : public DataCurve {
 public:
-	enum BoxStyle{NoBox, Rect, Diamond, WindBox, Notch};
-	enum Range{None, SD, SE, r25_75, r10_90, r5_95, r1_99, MinMax, UserDef};
+  enum BoxStyle { NoBox, Rect, Diamond, WindBox, Notch };
+  enum Range { None, SD, SE, r25_75, r10_90, r5_95, r1_99, MinMax, UserDef };
 
-	BoxCurve(Table *t, const QString& name, int startRow = 0, int endRow = -1);
+  BoxCurve(Table *t, const QString &name, int startRow = 0, int endRow = -1);
 
-	void copy(const BoxCurve *b);
+  void copy(const BoxCurve *b);
 
-        QwtDoubleRect boundingRect() const override;
+  QwtDoubleRect boundingRect() const override;
 
-        QwtSymbol::Style minStyle(){return min_style;};
-	void setMinStyle(QwtSymbol::Style s){min_style = s;};
+  QwtSymbol::Style minStyle() { return min_style; };
+  void setMinStyle(QwtSymbol::Style s) { min_style = s; };
 
-	QwtSymbol::Style maxStyle(){return max_style;};
-	void setMaxStyle(QwtSymbol::Style s){max_style = s;};
+  QwtSymbol::Style maxStyle() { return max_style; };
+  void setMaxStyle(QwtSymbol::Style s) { max_style = s; };
 
-	void setMeanStyle(QwtSymbol::Style s){mean_style = s;};
-	QwtSymbol::Style meanStyle(){return mean_style;};
+  void setMeanStyle(QwtSymbol::Style s) { mean_style = s; };
+  QwtSymbol::Style meanStyle() { return mean_style; };
 
-	void setP99Style(QwtSymbol::Style s){p99_style = s;};
-	QwtSymbol::Style p99Style(){return p99_style;};
+  void setP99Style(QwtSymbol::Style s) { p99_style = s; };
+  QwtSymbol::Style p99Style() { return p99_style; };
 
-	void setP1Style(QwtSymbol::Style s){p1_style = s;};
-	QwtSymbol::Style p1Style(){return p1_style;};
+  void setP1Style(QwtSymbol::Style s) { p1_style = s; };
+  QwtSymbol::Style p1Style() { return p1_style; };
 
-	int boxStyle(){return b_style;};
-	void setBoxStyle(int style);
+  int boxStyle() { return b_style; };
+  void setBoxStyle(int style);
 
-	int boxWidth(){return b_width;};
-	void setBoxWidth(int width){b_width=width;};
+  int boxWidth() { return b_width; };
+  void setBoxWidth(int width) { b_width = width; };
 
-	double boxRange(){return b_coeff;};
-	int boxRangeType(){return b_range;};
-	void setBoxRange(int type, double coeff);
+  double boxRange() { return b_coeff; };
+  int boxRangeType() { return b_range; };
+  void setBoxRange(int type, double coeff);
 
-	double whiskersRange(){return w_coeff;};
-	int whiskersRangeType(){return w_range;};
-	void setWhiskersRange(int type, double coeff);
+  double whiskersRange() { return w_coeff; };
+  int whiskersRangeType() { return w_range; };
+  void setWhiskersRange(int type, double coeff);
 
-        void loadData() override;
+  void loadData() override;
 
 private:
-	using DataCurve::draw; // Unhide base class method (avoids Intel compiler warning)
-        void draw(QPainter *painter, const QwtScaleMap &xMap,
-                  const QwtScaleMap &yMap, int from, int to) const override;
-        void drawBox(QPainter *painter, const QwtScaleMap &xMap,
-				const QwtScaleMap &yMap, double *dat, int size) const;
-	using DataCurve::drawSymbols; // Unhide base class method (avoids Intel compiler warning)
-	void drawSymbols(QPainter *painter, const QwtScaleMap &xMap,
-				const QwtScaleMap &yMap, double *dat, int size) const;
-
-	QwtSymbol::Style min_style, max_style, mean_style, p99_style, p1_style;
-	double b_coeff, w_coeff;
-	int b_style, b_width, b_range, w_range;
+  using DataCurve::draw; // Unhide base class method (avoids Intel compiler
+                         // warning)
+  void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+            int from, int to) const override;
+  void drawBox(QPainter *painter, const QwtScaleMap &xMap,
+               const QwtScaleMap &yMap, double *dat, int size) const;
+  using DataCurve::drawSymbols; // Unhide base class method (avoids Intel
+                                // compiler warning)
+  void drawSymbols(QPainter *painter, const QwtScaleMap &xMap,
+                   const QwtScaleMap &yMap, double *dat, int size) const;
+
+  QwtSymbol::Style min_style, max_style, mean_style, p99_style, p1_style;
+  double b_coeff, w_coeff;
+  int b_style, b_width, b_range, w_range;
 };
 
-
 //! Single array data (extension to QwtData)
-class QwtSingleArrayData: public QwtData
-{
+class QwtSingleArrayData : public QwtData {
 public:
-    QwtSingleArrayData(const double x, QwtArray<double> y, size_t)
-	{
-		d_y = y;
-		d_x = x;
-	};
+  QwtSingleArrayData(const double x, QwtArray<double> y, size_t) {
+    d_y = y;
+    d_x = x;
+  };
 
-        QwtData *copy() const override {
-          return new QwtSingleArrayData(d_x, d_y, size());
-        };
+  QwtData *copy() const override {
+    return new QwtSingleArrayData(d_x, d_y, size());
+  };
 
-        size_t size() const override { return d_y.size(); };
-        double x(size_t) const override { return d_x; };
-        double y(size_t i) const override { return d_y[static_cast<int>(i)]; };
+  size_t size() const override { return d_y.size(); };
+  double x(size_t) const override { return d_x; };
+  double y(size_t i) const override { return d_y[static_cast<int>(i)]; };
 
 private:
-    QwtArray<double> d_y;
-	double d_x;
+  QwtArray<double> d_y;
+  double d_x;
 };
 
 #endif
diff --git a/MantidPlot/src/CanvasPicker.cpp b/MantidPlot/src/CanvasPicker.cpp
index d08b19bfda345ab7fc075352ee7f12e946fd34a0..0bb0f6db286176bb726e0c66fefb4cc842fa7ed9 100644
--- a/MantidPlot/src/CanvasPicker.cpp
+++ b/MantidPlot/src/CanvasPicker.cpp
@@ -40,16 +40,14 @@
 #include <qwt_text_label.h>
 #include <qwt_plot_canvas.h>
 
-CanvasPicker::CanvasPicker(Graph *graph):
-	QObject(graph)
-{
-	pointSelected = false;
-	d_editing_marker = 0;
+CanvasPicker::CanvasPicker(Graph *graph) : QObject(graph) {
+  pointSelected = false;
+  d_editing_marker = 0;
 
-	plotWidget = graph->plotWidget();
+  plotWidget = graph->plotWidget();
 
-	QwtPlotCanvas *canvas = plotWidget->canvas();
-	canvas->installEventFilter(this);
+  QwtPlotCanvas *canvas = plotWidget->canvas();
+  canvas->installEventFilter(this);
 }
 
 bool CanvasPicker::eventFilter(QObject *object, QEvent *e) {
@@ -209,97 +207,94 @@ bool CanvasPicker::eventFilter(QObject *object, QEvent *e) {
   return QObject::eventFilter(object, e);
 }
 
-void CanvasPicker::disableEditing()
-{
-	if (d_editing_marker) {
-		d_editing_marker->setEditable(false);
-		d_editing_marker = 0;
-	}
+void CanvasPicker::disableEditing() {
+  if (d_editing_marker) {
+    d_editing_marker->setEditable(false);
+    d_editing_marker = 0;
+  }
 }
 
-void CanvasPicker::drawTextMarker(const QPoint& point)
-{
-	LegendWidget t(plotWidget);
-	t.move(point);
-	t.setText(tr("enter your text here"));
-
-	ApplicationWindow *app = plot()->multiLayer()->applicationWindow();
-	if (app){		
-		t.setFrameStyle(app->legendFrameStyle);
-		t.setFont(app->plotLegendFont);
-		t.setTextColor(app->legendTextColor);
-		t.setBackgroundColor(app->legendBackground);
-	}
-
-	LegendWidget *l = plot()->insertText(&t);
-	l->setSelected();
-	l->showTextDialog();
-
-	plot()->drawText(FALSE);
-	emit drawTextOff();
-}
+void CanvasPicker::drawTextMarker(const QPoint &point) {
+  LegendWidget t(plotWidget);
+  t.move(point);
+  t.setText(tr("enter your text here"));
+
+  ApplicationWindow *app = plot()->multiLayer()->applicationWindow();
+  if (app) {
+    t.setFrameStyle(app->legendFrameStyle);
+    t.setFont(app->plotLegendFont);
+    t.setTextColor(app->legendTextColor);
+    t.setBackgroundColor(app->legendBackground);
+  }
+
+  LegendWidget *l = plot()->insertText(&t);
+  l->setSelected();
+  l->showTextDialog();
 
-void CanvasPicker::drawLineMarker(const QPoint& point, bool endArrow)
-{
-	plot()->plotWidget()->canvas()->repaint();
-	ArrowMarker mrk;
-	mrk.attach(plotWidget);
-
-	int clw = plotWidget->canvas()->lineWidth();
-	mrk.setStartPoint(QPoint(startLinePoint.x() + clw, startLinePoint.y() + clw));
-	mrk.setEndPoint(QPoint(point.x() + clw,point.y() + clw));
-	mrk.setWidth(1);
-	mrk.setStyle(Qt::SolidLine);
-	mrk.drawEndArrow(endArrow);
-	mrk.drawStartArrow(false);
-
-	if (plot()->drawLineActive())
-		mrk.setColor(Qt::black);
-	else
-		mrk.setColor(Qt::red);
-
-	plotWidget->replot();
-	mrk.detach();
+  plot()->drawText(FALSE);
+  emit drawTextOff();
 }
 
-bool CanvasPicker::selectMarker(const QMouseEvent *e)
-{
-	const QPoint point = e->pos();
-	foreach(int i, plot()->imageMarkerKeys()) {
-    ImageMarker* m=dynamic_cast<ImageMarker*>(plotWidget->marker(i));
-		if (!m) return false;
-		if (m->rect().contains(point)) {
-			disableEditing();
-			plot()->setSelectedMarker(i, e->modifiers() & Qt::ShiftModifier);
-			return true;
-		}
-	}
-	foreach(int i, plot()->lineMarkerKeys()) {
-    ArrowMarker* mrkL=dynamic_cast<ArrowMarker*>(plotWidget->marker(i));
-		if (!mrkL)
-			return false;
-		int d = qRound(mrkL->width() + floor(mrkL->headLength()*tan(M_PI*mrkL->headAngle()/180.0)+0.5));
-		double dist = mrkL->dist(point.x(),point.y());
-		if (dist <= d){
-			disableEditing();
-			if (e->modifiers() & Qt::ShiftModifier) {
-				plot()->setSelectedMarker(i, true);
-				return true;
-			} else if (e->button() == Qt::RightButton) {
-				mrkL->setEditable(false);
-				plot()->setSelectedMarker(i, false);
-				return true;
-			}
-			plot()->deselectMarker();
-			mrkL->setEditable(true);
-			d_editing_marker = mrkL;
-			return true;
-		}
-	}
-	return false;
+void CanvasPicker::drawLineMarker(const QPoint &point, bool endArrow) {
+  plot()->plotWidget()->canvas()->repaint();
+  ArrowMarker mrk;
+  mrk.attach(plotWidget);
+
+  int clw = plotWidget->canvas()->lineWidth();
+  mrk.setStartPoint(QPoint(startLinePoint.x() + clw, startLinePoint.y() + clw));
+  mrk.setEndPoint(QPoint(point.x() + clw, point.y() + clw));
+  mrk.setWidth(1);
+  mrk.setStyle(Qt::SolidLine);
+  mrk.drawEndArrow(endArrow);
+  mrk.drawStartArrow(false);
+
+  if (plot()->drawLineActive())
+    mrk.setColor(Qt::black);
+  else
+    mrk.setColor(Qt::red);
+
+  plotWidget->replot();
+  mrk.detach();
 }
 
-Graph *CanvasPicker::plot()
-{
-	return dynamic_cast<Graph *>(parent());
+bool CanvasPicker::selectMarker(const QMouseEvent *e) {
+  const QPoint point = e->pos();
+  foreach (int i, plot()->imageMarkerKeys()) {
+    ImageMarker *m = dynamic_cast<ImageMarker *>(plotWidget->marker(i));
+    if (!m)
+      return false;
+    if (m->rect().contains(point)) {
+      disableEditing();
+      plot()->setSelectedMarker(i, e->modifiers() & Qt::ShiftModifier);
+      return true;
+    }
+  }
+  foreach (int i, plot()->lineMarkerKeys()) {
+    ArrowMarker *mrkL = dynamic_cast<ArrowMarker *>(plotWidget->marker(i));
+    if (!mrkL)
+      return false;
+    int d =
+        qRound(mrkL->width() + floor(mrkL->headLength() *
+                                         tan(M_PI * mrkL->headAngle() / 180.0) +
+                                     0.5));
+    double dist = mrkL->dist(point.x(), point.y());
+    if (dist <= d) {
+      disableEditing();
+      if (e->modifiers() & Qt::ShiftModifier) {
+        plot()->setSelectedMarker(i, true);
+        return true;
+      } else if (e->button() == Qt::RightButton) {
+        mrkL->setEditable(false);
+        plot()->setSelectedMarker(i, false);
+        return true;
+      }
+      plot()->deselectMarker();
+      mrkL->setEditable(true);
+      d_editing_marker = mrkL;
+      return true;
+    }
+  }
+  return false;
 }
+
+Graph *CanvasPicker::plot() { return dynamic_cast<Graph *>(parent()); }
diff --git a/MantidPlot/src/CanvasPicker.h b/MantidPlot/src/CanvasPicker.h
index 12a1431e67e890ee10c79bdde3bd5d06f52d20db..2cfc730749c3d590ce3bbebbce00f04d19e990c2 100644
--- a/MantidPlot/src/CanvasPicker.h
+++ b/MantidPlot/src/CanvasPicker.h
@@ -2,7 +2,8 @@
     File                 : CanvasPicker.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Canvas picker
 
@@ -33,66 +34,70 @@ class Graph;
 class ArrowMarker;
 
 /**
- * \brief Handles parts of the user interaction for a Plot by registering itself as an event filter for its QwtPlotCanvas.
+ * \brief Handles parts of the user interaction for a Plot by registering itself
+ *as an event filter for its QwtPlotCanvas.
  *
- * CanvasPicker relies heavily on its parent being the Graph that owns the Plot it operates on.
- * Additionally, parts of the code use Graph::plotWidget instead of CanvasPicker::plotWidget.
+ * CanvasPicker relies heavily on its parent being the Graph that owns the Plot
+ *it operates on.
+ * Additionally, parts of the code use Graph::plotWidget instead of
+ *CanvasPicker::plotWidget.
  */
-class CanvasPicker: public QObject
-{
-    Q_OBJECT
+class CanvasPicker : public QObject {
+  Q_OBJECT
 public:
   explicit CanvasPicker(Graph *plot);
   bool eventFilter(QObject *, QEvent *) override;
-         void selectPoints(int n);
-	 void selectPeak(const QPoint& p);
+  void selectPoints(int n);
+  void selectPeak(const QPoint &p);
 
-	 //! Disable editing of #d_editing_marker on a TAB-key event.
-	 /**\brief Called by Graph::focusNextPrevChild ()
-	 */
-	void disableEditing();
+  //! Disable editing of #d_editing_marker on a TAB-key event.
+  /**\brief Called by Graph::focusNextPrevChild ()
+  */
+  void disableEditing();
 
 private:
-	void drawTextMarker(const QPoint&);
-	void drawLineMarker(const QPoint&, bool endArrow);
+  void drawTextMarker(const QPoint &);
+  void drawLineMarker(const QPoint &, bool endArrow);
 
-	//! Selects and highlights the marker at the given position.
-	/**
-	 * @return whether a marker was found at #pointSelected
-	 */
-	bool selectMarker(const QMouseEvent *e);
+  //! Selects and highlights the marker at the given position.
+  /**
+   * @return whether a marker was found at #pointSelected
+   */
+  bool selectMarker(const QMouseEvent *e);
 
-	/**
-	 * \brief Return my parent as a Graph.
-	 *
-	 * %Note that contrary to the method name, this does NOT return the Plot I operate on.
-	 */
-	Graph *plot();
+  /**
+   * \brief Return my parent as a Graph.
+   *
+   * %Note that contrary to the method name, this does NOT return the Plot I
+   *operate on.
+   */
+  Graph *plot();
 
-	/**
-	 * \brief The Plot I handle user interaction for.
-	 *
-	 * %Note that this has to be owned by my parent Graph.
-	 */
-	Plot* plotWidget;
-	QPoint startLinePoint, endLinePoint;
+  /**
+   * \brief The Plot I handle user interaction for.
+   *
+   * %Note that this has to be owned by my parent Graph.
+   */
+  Plot *plotWidget;
+  QPoint startLinePoint, endLinePoint;
 
 signals:
-	void showPlotDialog(int);
-	void viewLineDialog();
-	void viewImageDialog();
-	void drawTextOff();
-	void showMarkerPopupMenu();
-	void modified();
-	void selectPlot();
+  void showPlotDialog(int);
+  void viewLineDialog();
+  void viewImageDialog();
+  void drawTextOff();
+  void showMarkerPopupMenu();
+  void modified();
+  void selectPlot();
 
 private:
-	bool pointSelected;
-	/**\brief The marker that is currently being edited, or NULL.
-	 * Editing does explicitly _not_ inlude moving and resizing, which are being
-	 * handled by SelectionMoveResizer (see Graph::d_markers_selector).
-	 * Currently, only ArrowMarker provides any other form of editing, but this really
-	 * should be generalized. See ImageMarker for details.
-	 */
-	ArrowMarker *d_editing_marker;
+  bool pointSelected;
+  /**\brief The marker that is currently being edited, or NULL.
+   * Editing does explicitly _not_ inlude moving and resizing, which are being
+   * handled by SelectionMoveResizer (see Graph::d_markers_selector).
+   * Currently, only ArrowMarker provides any other form of editing, but this
+   * really
+   * should be generalized. See ImageMarker for details.
+   */
+  ArrowMarker *d_editing_marker;
 };
diff --git a/MantidPlot/src/ColorMapDialog.cpp b/MantidPlot/src/ColorMapDialog.cpp
index b6fe6444c66ead984750553e4e9749d8162b1708..b6f63d022ac060469977cbc7e15a72d3d22507d0 100644
--- a/MantidPlot/src/ColorMapDialog.cpp
+++ b/MantidPlot/src/ColorMapDialog.cpp
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ColorMapDialog.cpp
-	Project              : QtiPlot
+        File                 : ColorMapDialog.cpp
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2007 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtLinearColorMap Editor Dialog
+        Copyright            : (C) 2007 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A QwtLinearColorMap Editor Dialog
  ***************************************************************************/
 
 /***************************************************************************
@@ -33,51 +33,50 @@
 #include <QPushButton>
 #include <QLayout>
 
-ColorMapDialog::ColorMapDialog(QWidget* parent, Qt::WFlags fl)
-  : QDialog(parent, fl), applyBtn(NULL), closeBtn(NULL), editor(NULL), d_matrix(NULL)
-{
-  setObjectName( "ColorMapDialog" );
+ColorMapDialog::ColorMapDialog(QWidget *parent, Qt::WFlags 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();
-	
+
   applyBtn = new QPushButton(tr("&Apply"));
   connect(applyBtn, SIGNAL(clicked()), this, SLOT(apply()));
 
   closeBtn = new QPushButton(tr("&Close"));
   connect(closeBtn, SIGNAL(clicked()), this, SLOT(reject()));
 
-  QHBoxLayout* hb = new QHBoxLayout();
+  QHBoxLayout *hb = new QHBoxLayout();
   hb->setSpacing(5);
   hb->addStretch();
   hb->addWidget(applyBtn);
   hb->addWidget(closeBtn);
   hb->addStretch();
-	
-  QVBoxLayout* vl = new QVBoxLayout(this);
+
+  QVBoxLayout *vl = new QVBoxLayout(this);
   vl->setSpacing(0);
   vl->addWidget(editor);
   vl->addLayout(hb);
-	
+
   setMaximumWidth(editor->width() + 20);
 }
 
-void ColorMapDialog::setMatrix(Matrix *m)
-{
-	if (!m)
-		return;
-	
-	d_matrix = m;
-	
-	double minValue = 0.0, maxValue = 0.0;
-	m->range(&minValue, &maxValue);
-	
-	editor->setRange(minValue, maxValue);
-	editor->setColorMap(m->colorMap());
+void ColorMapDialog::setMatrix(Matrix *m) {
+  if (!m)
+    return;
+
+  d_matrix = m;
+
+  double minValue = 0.0, maxValue = 0.0;
+  m->range(&minValue, &maxValue);
+
+  editor->setRange(minValue, maxValue);
+  editor->setColorMap(m->colorMap());
 }
 
-void ColorMapDialog::apply()
-{
-	d_matrix->undoStack()->push(new MatrixSetColorMapCommand(d_matrix, d_matrix->colorMapType(), 
-						d_matrix->colorMap(), Matrix::Custom, editor->colorMap(), tr("Set Custom Palette")));
-	d_matrix->setColorMap(editor->colorMap());
+void ColorMapDialog::apply() {
+  d_matrix->undoStack()->push(new MatrixSetColorMapCommand(
+      d_matrix, d_matrix->colorMapType(), d_matrix->colorMap(), Matrix::Custom,
+      editor->colorMap(), tr("Set Custom Palette")));
+  d_matrix->setColorMap(editor->colorMap());
 }
diff --git a/MantidPlot/src/ColorMapDialog.h b/MantidPlot/src/ColorMapDialog.h
index 8e7c034efe07907a9037b4da428b4c999da9dae5..70a2f3cfab5e4885bf5a6452a04f5e0e48351491 100644
--- a/MantidPlot/src/ColorMapDialog.h
+++ b/MantidPlot/src/ColorMapDialog.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ColorMapDialog.h
-	Project              : QtiPlot
+        File                 : ColorMapDialog.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2007 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtLinearColorMap Editor Dialog
+        Copyright            : (C) 2007 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A QwtLinearColorMap Editor Dialog
  ***************************************************************************/
 
 /***************************************************************************
@@ -33,22 +33,21 @@
 class QPushButton;
 class ColorMapEditor;
 class Matrix;
-	
-class ColorMapDialog: public QDialog
-{
-    Q_OBJECT
+
+class ColorMapDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	ColorMapDialog(QWidget* parent=0, Qt::WFlags fl = 0);
-	void setMatrix(Matrix *m);
-	
+  ColorMapDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
+  void setMatrix(Matrix *m);
+
 protected slots:
-	void apply();
+  void apply();
 
 private:
-	QPushButton *applyBtn, *closeBtn;
-	ColorMapEditor *editor;
-	Matrix *d_matrix;
+  QPushButton *applyBtn, *closeBtn;
+  ColorMapEditor *editor;
+  Matrix *d_matrix;
 };
-   
+
 #endif
diff --git a/MantidPlot/src/Cone3D.cpp b/MantidPlot/src/Cone3D.cpp
index 88223664859d27fc85c9e2d065539762d1ceab27..8401a8cebd304421e2dcaeb5ab85f1fcb150a948 100644
--- a/MantidPlot/src/Cone3D.cpp
+++ b/MantidPlot/src/Cone3D.cpp
@@ -4,8 +4,9 @@
     --------------------------------------------------------------------
     Copyright            : (C) 2004-2007 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : 3D cone class (code from Cone class  in QwtPlot3D library with modified destructor)
-                           
+    Description          : 3D cone class (code from Cone class  in QwtPlot3D
+ library with modified destructor)
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -36,61 +37,56 @@ using namespace Qwt3D;
 
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //
-//   Cone3D (code from Cone class  in QwtPlot3D library with modified destructor)
+//   Cone3D (code from Cone class  in QwtPlot3D library with modified
+//   destructor)
 //
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
-Cone3D::Cone3D()
-{
-	hat      = gluNewQuadric();
-	disk     = gluNewQuadric();
+Cone3D::Cone3D() {
+  hat = gluNewQuadric();
+  disk = gluNewQuadric();
 
   configure(0, 3);
 }
 
-Cone3D::Cone3D(double rad, unsigned quality)
-{
-	hat      = gluNewQuadric();
-	disk     = gluNewQuadric();
+Cone3D::Cone3D(double rad, unsigned quality) {
+  hat = gluNewQuadric();
+  disk = gluNewQuadric();
 
   configure(rad, quality);
 }
 
-Cone3D::~Cone3D()
-{
-}
+Cone3D::~Cone3D() {}
 
-void Cone3D::configure(double rad, unsigned quality)
-{
+void Cone3D::configure(double rad, unsigned quality) {
   plot = 0;
   radius_ = rad;
   quality_ = quality;
   oldstate_ = GL_FALSE;
 
-	gluQuadricDrawStyle(hat,GLU_FILL);
-	gluQuadricNormals(hat,GLU_SMOOTH);
-	gluQuadricOrientation(hat,GLU_OUTSIDE);
-	gluQuadricDrawStyle(disk,GLU_FILL);
-	gluQuadricNormals(disk,GLU_SMOOTH);
-	gluQuadricOrientation(disk,GLU_OUTSIDE);
+  gluQuadricDrawStyle(hat, GLU_FILL);
+  gluQuadricNormals(hat, GLU_SMOOTH);
+  gluQuadricOrientation(hat, GLU_OUTSIDE);
+  gluQuadricDrawStyle(disk, GLU_FILL);
+  gluQuadricNormals(disk, GLU_SMOOTH);
+  gluQuadricOrientation(disk, GLU_OUTSIDE);
 }
 
-void Cone3D::draw(Qwt3D::Triple const& pos)
-{  
-	RGBA rgba = (*plot->dataColor())(pos);
-  glColor4d(rgba.r,rgba.g,rgba.b,rgba.a);
+void Cone3D::draw(Qwt3D::Triple const &pos) {
+  RGBA rgba = (*plot->dataColor())(pos);
+  glColor4d(rgba.r, rgba.g, rgba.b, rgba.a);
 
   GLint mode;
-	glGetIntegerv(GL_MATRIX_MODE, &mode);
-	glMatrixMode( GL_MODELVIEW );
+  glGetIntegerv(GL_MATRIX_MODE, &mode);
+  glMatrixMode(GL_MODELVIEW);
   glPushMatrix();
 
   glTranslatef(GLfloat(pos.x), GLfloat(pos.y), GLfloat(pos.z));
 
-  gluCylinder(hat, 0.0, radius_, radius_*2, quality_, 1);
-  glTranslatef(0, 0, GLfloat(radius_*2));
-	gluDisk(disk, 0.0, radius_, quality_, 1);
+  gluCylinder(hat, 0.0, radius_, radius_ * 2, quality_, 1);
+  glTranslatef(0, 0, GLfloat(radius_ * 2));
+  gluDisk(disk, 0.0, radius_, quality_, 1);
 
   glPopMatrix();
-	glMatrixMode(mode);
+  glMatrixMode(mode);
 }
diff --git a/MantidPlot/src/Cone3D.h b/MantidPlot/src/Cone3D.h
index 4e70e22f4749708a312db8a9b6f378669f4b2e11..c437673e9a1d8aa101857bf8f7809c7309035b67 100644
--- a/MantidPlot/src/Cone3D.h
+++ b/MantidPlot/src/Cone3D.h
@@ -2,10 +2,12 @@
     File                 : Cone3D.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
-    Description          : 3D cone class (code from Cone class  in QwtPlot3D library with modified destructor)
-                           
+    Description          : 3D cone class (code from Cone class  in QwtPlot3D
+ library with modified destructor)
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -32,8 +34,7 @@
 #include <qwt3d_plot.h>
 
 //! 3D cone class (based on QwtPlot3D)
-class Cone3D : public Qwt3D::VertexEnrichment
-{
+class Cone3D : public Qwt3D::VertexEnrichment {
 public:
   Cone3D();
   Cone3D(double rad, unsigned quality);
@@ -45,11 +46,11 @@ public:
   void draw(Qwt3D::Triple const &) override;
 
 private:
-  	GLUquadricObj *hat;
-	GLUquadricObj *disk;
-	unsigned quality_;
-	double radius_;
-	GLboolean oldstate_;
+  GLUquadricObj *hat;
+  GLUquadricObj *disk;
+  unsigned quality_;
+  double radius_;
+  GLboolean oldstate_;
 };
 
 #endif
diff --git a/MantidPlot/src/ConfigDialog.cpp b/MantidPlot/src/ConfigDialog.cpp
index fc0994b6537185e580b430e05c2ab6a90285adb5..9beeed4f7ed6d2754ac635744e58f8d1d522236a 100644
--- a/MantidPlot/src/ConfigDialog.cpp
+++ b/MantidPlot/src/ConfigDialog.cpp
@@ -85,11 +85,11 @@ Description          : Preferences dialog
 
 using Mantid::Kernel::ConfigService;
 
-ConfigDialog::ConfigDialog( QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl )
-{
+ConfigDialog::ConfigDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
   // get current values from app window
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   plot3DTitleFont = app->plot3DTitleFont;
   plot3DNumbersFont = app->plot3DNumbersFont;
   plot3DAxesFont = app->plot3DAxesFont;
@@ -105,7 +105,7 @@ ConfigDialog::ConfigDialog( QWidget* parent, Qt::WFlags fl )
   generalDialog = new QStackedWidget();
   itemsList = new QListWidget();
   itemsList->setSpacing(10);
-  itemsList->setAlternatingRowColors( true );
+  itemsList->setAlternatingRowColors(true);
 
   initAppPage();
   initMantidPage();
@@ -123,7 +123,7 @@ ConfigDialog::ConfigDialog( QWidget* parent, Qt::WFlags fl )
   generalDialog->addWidget(fitPage);
   generalDialog->addWidget(mdPlottingTabWidget);
 
-  QVBoxLayout * rightLayout = new QVBoxLayout();
+  QVBoxLayout *rightLayout = new QVBoxLayout();
   lblPageHeader = new QLabel();
   QFont fnt = this->font();
   fnt.setPointSize(fnt.pointSize() + 3);
@@ -132,75 +132,79 @@ ConfigDialog::ConfigDialog( QWidget* parent, Qt::WFlags fl )
   lblPageHeader->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
 
   QPalette pal = lblPageHeader->palette();
-  pal.setColor( QPalette::Window, app->panelsColor );
+  pal.setColor(QPalette::Window, app->panelsColor);
   lblPageHeader->setPalette(pal);
-  lblPageHeader->setAutoFillBackground( true );
+  lblPageHeader->setAutoFillBackground(true);
 
   rightLayout->setSpacing(10);
-  rightLayout->addWidget( lblPageHeader );
-  rightLayout->addWidget( generalDialog );
+  rightLayout->addWidget(lblPageHeader);
+  rightLayout->addWidget(generalDialog);
 
-  QHBoxLayout * topLayout = new QHBoxLayout();
+  QHBoxLayout *topLayout = new QHBoxLayout();
   topLayout->setSpacing(5);
   topLayout->setMargin(5);
-  topLayout->addWidget( itemsList );
-  topLayout->addLayout( rightLayout );
+  topLayout->addWidget(itemsList);
+  topLayout->addLayout(rightLayout);
 
-  QHBoxLayout * bottomButtons = new QHBoxLayout();
+  QHBoxLayout *bottomButtons = new QHBoxLayout();
   bottomButtons->addStretch();
   buttonApply = new QPushButton();
-  buttonApply->setAutoDefault( true );
-  bottomButtons->addWidget( buttonApply );
+  buttonApply->setAutoDefault(true);
+  bottomButtons->addWidget(buttonApply);
 
   buttonOk = new QPushButton();
-  buttonOk->setAutoDefault( true );
-  buttonOk->setDefault( true );
-  bottomButtons->addWidget( buttonOk );
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
+  bottomButtons->addWidget(buttonOk);
 
   buttonCancel = new QPushButton();
-  buttonCancel->setAutoDefault( true );
-  bottomButtons->addWidget( buttonCancel );
+  buttonCancel->setAutoDefault(true);
+  bottomButtons->addWidget(buttonCancel);
 
-  QVBoxLayout * mainLayout = new QVBoxLayout( this );
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
   mainLayout->addLayout(topLayout);
   mainLayout->addLayout(bottomButtons);
 
   languageChange();
 
   // signals and slots connections
-  connect( itemsList, SIGNAL(currentRowChanged(int)), this, SLOT(setCurrentPage(int)));
-  connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-  connect( buttonApply, SIGNAL( clicked() ), this, SLOT( apply() ) );
-  connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-  connect( buttonTextFont, SIGNAL( clicked() ), this, SLOT( pickTextFont() ) );
-  connect( buttonHeaderFont, SIGNAL( clicked() ), this, SLOT( pickHeaderFont() ) );
+  connect(itemsList, SIGNAL(currentRowChanged(int)), this,
+          SLOT(setCurrentPage(int)));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(buttonTextFont, SIGNAL(clicked()), this, SLOT(pickTextFont()));
+  connect(buttonHeaderFont, SIGNAL(clicked()), this, SLOT(pickHeaderFont()));
 
   setCurrentPage(0);
 }
 
-void ConfigDialog::setCurrentPage(int index)
-{
+void ConfigDialog::setCurrentPage(int index) {
   generalDialog->setCurrentIndex(index);
-  if(itemsList->currentItem())
+  if (itemsList->currentItem())
     lblPageHeader->setText(itemsList->currentItem()->text());
 }
 
-void ConfigDialog::initTablesPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initTablesPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   tables = new QWidget();
 
-  QHBoxLayout * topLayout = new QHBoxLayout();
+  QHBoxLayout *topLayout = new QHBoxLayout();
   topLayout->setSpacing(5);
 
   lblSeparator = new QLabel();
-  topLayout->addWidget( lblSeparator );
+  topLayout->addWidget(lblSeparator);
   boxSeparator = new QComboBox();
-  boxSeparator->setEditable( true );
-  topLayout->addWidget( boxSeparator );
+  boxSeparator->setEditable(true);
+  topLayout->addWidget(boxSeparator);
 
-  QString help = tr("The column separator can be customized. \nThe following special codes can be used:\n\\t for a TAB character \n\\s for a SPACE");
-  help += "\n"+tr("The separator must not contain the following characters: \n0-9eE.+-");
+  QString help =
+      tr("The column separator can be customized. \nThe following special "
+         "codes can be used:\n\\t for a TAB character \n\\s for a SPACE");
+  help +=
+      "\n" +
+      tr("The separator must not contain the following characters: \n0-9eE.+-");
 
   boxSeparator->setWhatsThis(help);
   boxSeparator->setToolTip(help);
@@ -208,33 +212,33 @@ void ConfigDialog::initTablesPage()
   lblSeparator->setToolTip(help);
 
   groupBoxTableCol = new QGroupBox();
-  QGridLayout * colorsLayout = new QGridLayout(groupBoxTableCol);
+  QGridLayout *colorsLayout = new QGridLayout(groupBoxTableCol);
 
   lblTableBackground = new QLabel();
-  colorsLayout->addWidget( lblTableBackground, 0, 0 );
-  buttonBackground= new ColorButton();
+  colorsLayout->addWidget(lblTableBackground, 0, 0);
+  buttonBackground = new ColorButton();
   buttonBackground->setColor(app->tableBkgdColor);
-  colorsLayout->addWidget( buttonBackground, 0, 1 );
+  colorsLayout->addWidget(buttonBackground, 0, 1);
 
   lblTextColor = new QLabel();
-  colorsLayout->addWidget( lblTextColor, 1, 0 );
+  colorsLayout->addWidget(lblTextColor, 1, 0);
   buttonText = new ColorButton();
   buttonText->setColor(app->tableTextColor);
-  colorsLayout->addWidget( buttonText, 1, 1 );
+  colorsLayout->addWidget(buttonText, 1, 1);
 
   lblHeaderColor = new QLabel();
-  colorsLayout->addWidget( lblHeaderColor, 2, 0 );
-  buttonHeader= new ColorButton();
+  colorsLayout->addWidget(lblHeaderColor, 2, 0);
+  buttonHeader = new ColorButton();
   buttonHeader->setColor(app->tableHeaderColor);
-  colorsLayout->addWidget( buttonHeader, 2, 1 );
+  colorsLayout->addWidget(buttonHeader, 2, 1);
 
   groupBoxTableFonts = new QGroupBox();
-  QHBoxLayout * bottomLayout = new QHBoxLayout( groupBoxTableFonts );
+  QHBoxLayout *bottomLayout = new QHBoxLayout(groupBoxTableFonts);
 
-  buttonTextFont= new QPushButton();
-  bottomLayout->addWidget( buttonTextFont );
-  buttonHeaderFont= new QPushButton();
-  bottomLayout->addWidget( buttonHeaderFont );
+  buttonTextFont = new QPushButton();
+  bottomLayout->addWidget(buttonTextFont);
+  buttonHeaderFont = new QPushButton();
+  bottomLayout->addWidget(buttonHeaderFont);
 
   boxTableComments = new QCheckBox();
   boxTableComments->setChecked(app->d_show_table_comments);
@@ -242,8 +246,8 @@ void ConfigDialog::initTablesPage()
   boxUpdateTableValues = new QCheckBox();
   boxUpdateTableValues->setChecked(app->autoUpdateTableValues());
 
-  QVBoxLayout * tablesPageLayout = new QVBoxLayout( tables );
-  tablesPageLayout->addLayout(topLayout,1);
+  QVBoxLayout *tablesPageLayout = new QVBoxLayout(tables);
+  tablesPageLayout->addLayout(topLayout, 1);
   tablesPageLayout->addWidget(groupBoxTableCol);
   tablesPageLayout->addWidget(groupBoxTableFonts);
   tablesPageLayout->addWidget(boxTableComments);
@@ -251,11 +255,12 @@ void ConfigDialog::initTablesPage()
   tablesPageLayout->addStretch();
 }
 
-void ConfigDialog::initPlotsPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initPlotsPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   plotsTabWidget = new QTabWidget();
@@ -263,246 +268,243 @@ void ConfigDialog::initPlotsPage()
   initOptionsPage();
 
   initAxesPage();
-  plotsTabWidget->addTab( axesPage, QString() );
+  plotsTabWidget->addTab(axesPage, QString());
 
   initCurvesPage();
-  plotsTabWidget->addTab( curves, QString() );
+  plotsTabWidget->addTab(curves, QString());
 
   plotTicks = new QWidget();
-  QVBoxLayout * plotTicksLayout = new QVBoxLayout( plotTicks );
+  QVBoxLayout *plotTicksLayout = new QVBoxLayout(plotTicks);
 
-  QGroupBox * ticksGroupBox = new QGroupBox();
-  QGridLayout * ticksLayout = new QGridLayout( ticksGroupBox );
-  plotTicksLayout->addWidget( ticksGroupBox );
+  QGroupBox *ticksGroupBox = new QGroupBox();
+  QGridLayout *ticksLayout = new QGridLayout(ticksGroupBox);
+  plotTicksLayout->addWidget(ticksGroupBox);
 
   lblMajTicks = new QLabel();
-  ticksLayout->addWidget( lblMajTicks, 0, 0 );
+  ticksLayout->addWidget(lblMajTicks, 0, 0);
   boxMajTicks = new QComboBox();
-  ticksLayout->addWidget( boxMajTicks, 0, 1 );
+  ticksLayout->addWidget(boxMajTicks, 0, 1);
 
   lblMajTicksLength = new QLabel();
-  ticksLayout->addWidget( lblMajTicksLength, 0, 2 );
+  ticksLayout->addWidget(lblMajTicksLength, 0, 2);
   boxMajTicksLength = new QSpinBox();
   boxMajTicksLength->setRange(0, 100);
   boxMajTicksLength->setValue(app->majTicksLength);
-  ticksLayout->addWidget( boxMajTicksLength, 0, 3 );
+  ticksLayout->addWidget(boxMajTicksLength, 0, 3);
 
   lblMinTicks = new QLabel();
-  ticksLayout->addWidget( lblMinTicks, 1, 0 );
+  ticksLayout->addWidget(lblMinTicks, 1, 0);
   boxMinTicks = new QComboBox();
-  ticksLayout->addWidget( boxMinTicks, 1, 1 );
+  ticksLayout->addWidget(boxMinTicks, 1, 1);
 
   lblMinTicksLength = new QLabel();
-  ticksLayout->addWidget( lblMinTicksLength, 1, 2 );
+  ticksLayout->addWidget(lblMinTicksLength, 1, 2);
   boxMinTicksLength = new QSpinBox();
   boxMinTicksLength->setRange(0, 100);
   boxMinTicksLength->setValue(app->minTicksLength);
-  ticksLayout->addWidget( boxMinTicksLength, 1, 3 );
+  ticksLayout->addWidget(boxMinTicksLength, 1, 3);
 
-  ticksLayout->setRowStretch( 4, 1 );
+  ticksLayout->setRowStretch(4, 1);
 
-  plotsTabWidget->addTab( plotTicks, QString() );
+  plotsTabWidget->addTab(plotTicks, QString());
 
   plotFonts = new QWidget();
-  QVBoxLayout * plotFontsLayout = new QVBoxLayout( plotFonts );
-
-  QGroupBox * groupBox2DFonts = new QGroupBox();
-  plotFontsLayout->addWidget( groupBox2DFonts );
-  QVBoxLayout * fontsLayout = new QVBoxLayout( groupBox2DFonts );
-  buttonTitleFont= new QPushButton();
-  fontsLayout->addWidget( buttonTitleFont );
-  buttonLegendFont= new QPushButton();
-  fontsLayout->addWidget( buttonLegendFont );
-  buttonAxesFont= new QPushButton();
-  fontsLayout->addWidget( buttonAxesFont );
-  buttonNumbersFont= new QPushButton();
-  fontsLayout->addWidget( buttonNumbersFont );
+  QVBoxLayout *plotFontsLayout = new QVBoxLayout(plotFonts);
+
+  QGroupBox *groupBox2DFonts = new QGroupBox();
+  plotFontsLayout->addWidget(groupBox2DFonts);
+  QVBoxLayout *fontsLayout = new QVBoxLayout(groupBox2DFonts);
+  buttonTitleFont = new QPushButton();
+  fontsLayout->addWidget(buttonTitleFont);
+  buttonLegendFont = new QPushButton();
+  fontsLayout->addWidget(buttonLegendFont);
+  buttonAxesFont = new QPushButton();
+  fontsLayout->addWidget(buttonAxesFont);
+  buttonNumbersFont = new QPushButton();
+  fontsLayout->addWidget(buttonNumbersFont);
   fontsLayout->addStretch();
 
-  plotsTabWidget->addTab( plotFonts, QString() );
+  plotsTabWidget->addTab(plotFonts, QString());
 
   plotPrint = new QWidget();
-  QVBoxLayout *printLayout = new QVBoxLayout( plotPrint );
+  QVBoxLayout *printLayout = new QVBoxLayout(plotPrint);
 
   boxScaleLayersOnPrint = new QCheckBox();
   boxScaleLayersOnPrint->setChecked(app->d_scale_plots_on_print);
-  printLayout->addWidget( boxScaleLayersOnPrint );
+  printLayout->addWidget(boxScaleLayersOnPrint);
 
   boxPrintCropmarks = new QCheckBox();
   boxPrintCropmarks->setChecked(app->d_print_cropmarks);
-  printLayout->addWidget( boxPrintCropmarks );
+  printLayout->addWidget(boxPrintCropmarks);
   printLayout->addStretch();
   plotsTabWidget->addTab(plotPrint, QString());
 
-  connect( boxResize, SIGNAL( clicked() ), this, SLOT( enableScaleFonts() ) );
-  connect( boxFrame, SIGNAL( toggled(bool) ), this, SLOT( showFrameWidth(bool) ) );
-  connect( buttonAxesFont, SIGNAL( clicked() ), this, SLOT( pickAxesFont() ) );
-  connect( buttonNumbersFont, SIGNAL( clicked() ), this, SLOT( pickNumbersFont() ) );
-  connect( buttonLegendFont, SIGNAL( clicked() ), this, SLOT( pickLegendFont() ) );
-  connect( buttonTitleFont, SIGNAL( clicked() ), this, SLOT( pickTitleFont() ) );
+  connect(boxResize, SIGNAL(clicked()), this, SLOT(enableScaleFonts()));
+  connect(boxFrame, SIGNAL(toggled(bool)), this, SLOT(showFrameWidth(bool)));
+  connect(buttonAxesFont, SIGNAL(clicked()), this, SLOT(pickAxesFont()));
+  connect(buttonNumbersFont, SIGNAL(clicked()), this, SLOT(pickNumbersFont()));
+  connect(buttonLegendFont, SIGNAL(clicked()), this, SLOT(pickLegendFont()));
+  connect(buttonTitleFont, SIGNAL(clicked()), this, SLOT(pickTitleFont()));
 }
 
-void ConfigDialog::enableScaleFonts()
-{
-  if(boxResize->isChecked())
+void ConfigDialog::enableScaleFonts() {
+  if (boxResize->isChecked())
     boxScaleFonts->setEnabled(false);
   else
     boxScaleFonts->setEnabled(true);
 }
 
-void ConfigDialog::showFrameWidth(bool ok)
-{
-  if (!ok)
-  {
+void ConfigDialog::showFrameWidth(bool ok) {
+  if (!ok) {
     boxFrameWidth->hide();
     labelFrameWidth->hide();
-  }
-  else
-  {
+  } else {
     boxFrameWidth->show();
     labelFrameWidth->show();
   }
 }
 
-void ConfigDialog::initPlots3DPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initPlots3DPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
   plots3D = new QWidget();
 
-  QGroupBox * topBox = new QGroupBox();
-  QGridLayout * topLayout = new QGridLayout( topBox );
+  QGroupBox *topBox = new QGroupBox();
+  QGridLayout *topLayout = new QGridLayout(topBox);
   topLayout->setSpacing(5);
 
   lblResolution = new QLabel();
-  topLayout->addWidget( lblResolution, 0, 0 );
+  topLayout->addWidget(lblResolution, 0, 0);
   boxResolution = new QSpinBox();
   boxResolution->setRange(1, 100);
   boxResolution->setValue(app->plot3DResolution);
-  topLayout->addWidget( boxResolution, 0, 1 );
+  topLayout->addWidget(boxResolution, 0, 1);
 
   boxShowLegend = new QCheckBox();
   boxShowLegend->setChecked(app->showPlot3DLegend);
-  topLayout->addWidget( boxShowLegend, 1, 0 );
+  topLayout->addWidget(boxShowLegend, 1, 0);
 
   boxShowProjection = new QCheckBox();
   boxShowProjection->setChecked(app->showPlot3DProjection);
-  topLayout->addWidget( boxShowProjection, 1, 1 );
+  topLayout->addWidget(boxShowProjection, 1, 1);
 
   boxSmoothMesh = new QCheckBox();
   boxSmoothMesh->setChecked(app->smooth3DMesh);
-  topLayout->addWidget( boxSmoothMesh, 2, 0 );
+  topLayout->addWidget(boxSmoothMesh, 2, 0);
 
   boxOrthogonal = new QCheckBox();
   boxOrthogonal->setChecked(app->orthogonal3DPlots);
-  topLayout->addWidget( boxOrthogonal, 2, 1 );
+  topLayout->addWidget(boxOrthogonal, 2, 1);
 
   boxAutoscale3DPlots = new QCheckBox();
   boxAutoscale3DPlots->setChecked(app->autoscale3DPlots);
-  topLayout->addWidget( boxAutoscale3DPlots, 3, 0 );
+  topLayout->addWidget(boxAutoscale3DPlots, 3, 0);
 
   groupBox3DCol = new QGroupBox();
-  QGridLayout * middleLayout = new QGridLayout( groupBox3DCol );
+  QGridLayout *middleLayout = new QGridLayout(groupBox3DCol);
 
   QStringList plot3DColors = app->plot3DColors;
 
   btnFromColor = new ColorButton();
   btnFromColor->setColor(QColor(plot3DColors[4]));
-  middleLayout->addWidget( btnFromColor, 0, 0 );
+  middleLayout->addWidget(btnFromColor, 0, 0);
   btnLabels = new ColorButton();
   btnLabels->setColor(QColor(plot3DColors[1]));
-  middleLayout->addWidget( btnLabels, 0, 1 );
+  middleLayout->addWidget(btnLabels, 0, 1);
   btnMesh = new ColorButton();
   btnMesh->setColor(QColor(plot3DColors[2]));
-  middleLayout->addWidget( btnMesh, 0, 2 );
+  middleLayout->addWidget(btnMesh, 0, 2);
   btnGrid = new ColorButton();
   btnGrid->setColor(QColor(plot3DColors[3]));
-  middleLayout->addWidget( btnGrid, 0, 3 );
+  middleLayout->addWidget(btnGrid, 0, 3);
   btnToColor = new ColorButton();
   btnToColor->setColor(QColor(plot3DColors[0]));
-  middleLayout->addWidget( btnToColor, 1, 0 );
+  middleLayout->addWidget(btnToColor, 1, 0);
   btnNumbers = new ColorButton();
   btnNumbers->setColor(QColor(plot3DColors[5]));
-  middleLayout->addWidget( btnNumbers, 1, 1 );
+  middleLayout->addWidget(btnNumbers, 1, 1);
   btnAxes = new ColorButton();
   btnAxes->setColor(QColor(plot3DColors[6]));
-  middleLayout->addWidget( btnAxes, 1, 2 );
+  middleLayout->addWidget(btnAxes, 1, 2);
   btnBackground3D = new ColorButton();
   btnBackground3D->setColor(QColor(plot3DColors[7]));
-  middleLayout->addWidget( btnBackground3D, 1, 3 );
+  middleLayout->addWidget(btnBackground3D, 1, 3);
 
   groupBox3DFonts = new QGroupBox();
-  QHBoxLayout * bottomLayout = new QHBoxLayout( groupBox3DFonts );
+  QHBoxLayout *bottomLayout = new QHBoxLayout(groupBox3DFonts);
   btnTitleFnt = new QPushButton();
-  bottomLayout->addWidget( btnTitleFnt );
+  bottomLayout->addWidget(btnTitleFnt);
   btnLabelsFnt = new QPushButton();
-  bottomLayout->addWidget( btnLabelsFnt );
+  bottomLayout->addWidget(btnLabelsFnt);
   btnNumFnt = new QPushButton();
-  bottomLayout->addWidget( btnNumFnt );
+  bottomLayout->addWidget(btnNumFnt);
 
-  QVBoxLayout * plots3DPageLayout = new QVBoxLayout( plots3D );
+  QVBoxLayout *plots3DPageLayout = new QVBoxLayout(plots3D);
   plots3DPageLayout->addWidget(topBox);
   plots3DPageLayout->addWidget(groupBox3DCol);
   plots3DPageLayout->addWidget(groupBox3DFonts);
   plots3DPageLayout->addStretch();
 
-  connect( btnNumFnt, SIGNAL( clicked() ), this, SLOT(pick3DNumbersFont() ) );
-  connect( btnTitleFnt, SIGNAL( clicked() ), this, SLOT(pick3DTitleFont() ) );
-  connect( btnLabelsFnt, SIGNAL( clicked() ), this, SLOT(pick3DAxesFont() ) );
+  connect(btnNumFnt, SIGNAL(clicked()), this, SLOT(pick3DNumbersFont()));
+  connect(btnTitleFnt, SIGNAL(clicked()), this, SLOT(pick3DTitleFont()));
+  connect(btnLabelsFnt, SIGNAL(clicked()), this, SLOT(pick3DAxesFont()));
 }
 
-void ConfigDialog::initAppPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initAppPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
 
   appTabWidget = new QTabWidget(generalDialog);
   appTabWidget->setUsesScrollButtons(false);
 
   application = new QWidget();
-  QVBoxLayout * applicationLayout = new QVBoxLayout( application );
-  QGroupBox * groupBoxApp = new QGroupBox();
+  QVBoxLayout *applicationLayout = new QVBoxLayout(application);
+  QGroupBox *groupBoxApp = new QGroupBox();
   applicationLayout->addWidget(groupBoxApp);
-  QGridLayout * topBoxLayout = new QGridLayout( groupBoxApp );
+  QGridLayout *topBoxLayout = new QGridLayout(groupBoxApp);
 
   lblLanguage = new QLabel();
-  topBoxLayout->addWidget( lblLanguage, 0, 0 );
+  topBoxLayout->addWidget(lblLanguage, 0, 0);
   boxLanguage = new QComboBox();
   insertLanguagesList();
-  topBoxLayout->addWidget( boxLanguage, 0, 1 );
+  topBoxLayout->addWidget(boxLanguage, 0, 1);
 
   lblStyle = new QLabel();
-  topBoxLayout->addWidget( lblStyle, 1, 0 );
+  topBoxLayout->addWidget(lblStyle, 1, 0);
   boxStyle = new QComboBox();
-  topBoxLayout->addWidget( boxStyle, 1, 1 );
+  topBoxLayout->addWidget(boxStyle, 1, 1);
   QStringList styles = QStyleFactory::keys();
   styles.sort();
   boxStyle->addItems(styles);
-  boxStyle->setCurrentIndex(boxStyle->findText(app->appStyle,Qt::MatchWildcard));
+  boxStyle->setCurrentIndex(
+      boxStyle->findText(app->appStyle, Qt::MatchWildcard));
 
   lblFonts = new QLabel();
-  topBoxLayout->addWidget( lblFonts, 2, 0 );
-  fontsBtn= new QPushButton();
-  topBoxLayout->addWidget( fontsBtn, 2, 1 );
+  topBoxLayout->addWidget(lblFonts, 2, 0);
+  fontsBtn = new QPushButton();
+  topBoxLayout->addWidget(fontsBtn, 2, 1);
 
   lblScriptingLanguage = new QLabel();
-  topBoxLayout->addWidget( lblScriptingLanguage, 3, 0 );
+  topBoxLayout->addWidget(lblScriptingLanguage, 3, 0);
   boxScriptingLanguage = new QComboBox();
   QStringList llist = ScriptingLangManager::languages();
   boxScriptingLanguage->insertItems(-1, llist);
   boxScriptingLanguage->setCurrentIndex(
       llist.indexOf(app->defaultScriptingLang));
-  topBoxLayout->addWidget( boxScriptingLanguage, 3, 1 );
+  topBoxLayout->addWidget(boxScriptingLanguage, 3, 1);
 
   lblUndoStackSize = new QLabel();
-  topBoxLayout->addWidget( lblUndoStackSize, 4, 0 );
+  topBoxLayout->addWidget(lblUndoStackSize, 4, 0);
   undoStackSizeBox = new QSpinBox();
   undoStackSizeBox->setValue(app->matrixUndoStackSize());
-  topBoxLayout->addWidget( undoStackSizeBox, 4, 1 );
+  topBoxLayout->addWidget(undoStackSizeBox, 4, 1);
 
   lblEndOfLine = new QLabel();
-  topBoxLayout->addWidget(lblEndOfLine, 5, 0 );
+  topBoxLayout->addWidget(lblEndOfLine, 5, 0);
   boxEndLine = new QComboBox();
   boxEndLine->addItem(tr("LF (Unix)"));
   boxEndLine->addItem(tr("CRLF (Windows)"));
@@ -511,27 +513,27 @@ void ConfigDialog::initAppPage()
   topBoxLayout->addWidget(boxEndLine, 5, 1);
 
   lblInitWindow = new QLabel();
-  topBoxLayout->addWidget( lblInitWindow, 6, 0 );
+  topBoxLayout->addWidget(lblInitWindow, 6, 0);
   boxInitWindow = new QComboBox();
-  topBoxLayout->addWidget( boxInitWindow, 6, 1 );
+  topBoxLayout->addWidget(boxInitWindow, 6, 1);
 
-  boxSave= new QCheckBox();
+  boxSave = new QCheckBox();
   boxSave->setChecked(app->autoSave);
-  topBoxLayout->addWidget( boxSave, 7, 0 );
+  topBoxLayout->addWidget(boxSave, 7, 0);
 
   boxMinutes = new QSpinBox();
   boxMinutes->setRange(1, 100);
   boxMinutes->setValue(app->autoSaveTime);
   boxMinutes->setEnabled(app->autoSave);
-  topBoxLayout->addWidget( boxMinutes, 7, 1 );
+  topBoxLayout->addWidget(boxMinutes, 7, 1);
 
   boxBackupProject = new QCheckBox();
   boxBackupProject->setChecked(app->d_backup_files);
-  topBoxLayout->addWidget( boxBackupProject, 8, 0, 1, 2 );
+  topBoxLayout->addWidget(boxBackupProject, 8, 0, 1, 2);
 
   boxSearchUpdates = new QCheckBox();
   boxSearchUpdates->setChecked(app->autoSearchUpdates);
-  topBoxLayout->addWidget( boxSearchUpdates, 9, 0, 1, 2 );
+  topBoxLayout->addWidget(boxSearchUpdates, 9, 0, 1, 2);
 
   topBoxLayout->setRowStretch(10, 1);
 
@@ -539,41 +541,41 @@ void ConfigDialog::initAppPage()
 
   initConfirmationsPage();
 
-  appTabWidget->addTab( confirm, QString() );
+  appTabWidget->addTab(confirm, QString());
 
   appColors = new QWidget();
-  QVBoxLayout * appColorsLayout = new QVBoxLayout( appColors );
-  QGroupBox * groupBoxAppCol = new QGroupBox();
-  appColorsLayout->addWidget( groupBoxAppCol );
-  QGridLayout * colorsBoxLayout = new QGridLayout( groupBoxAppCol );
+  QVBoxLayout *appColorsLayout = new QVBoxLayout(appColors);
+  QGroupBox *groupBoxAppCol = new QGroupBox();
+  appColorsLayout->addWidget(groupBoxAppCol);
+  QGridLayout *colorsBoxLayout = new QGridLayout(groupBoxAppCol);
 
   lblWorkspace = new QLabel();
-  colorsBoxLayout->addWidget( lblWorkspace, 0, 0 );
+  colorsBoxLayout->addWidget(lblWorkspace, 0, 0);
   btnWorkspace = new ColorButton();
   btnWorkspace->setColor(app->workspaceColor);
-  colorsBoxLayout->addWidget( btnWorkspace, 0, 1 );
+  colorsBoxLayout->addWidget(btnWorkspace, 0, 1);
 
   lblPanels = new QLabel();
-  colorsBoxLayout->addWidget( lblPanels, 1, 0 );
+  colorsBoxLayout->addWidget(lblPanels, 1, 0);
   btnPanels = new ColorButton();
-  colorsBoxLayout->addWidget( btnPanels, 1, 1 );
+  colorsBoxLayout->addWidget(btnPanels, 1, 1);
   btnPanels->setColor(app->panelsColor);
 
   lblPanelsText = new QLabel();
-  colorsBoxLayout->addWidget( lblPanelsText, 2, 0 );
+  colorsBoxLayout->addWidget(lblPanelsText, 2, 0);
   btnPanelsText = new ColorButton();
-  colorsBoxLayout->addWidget( btnPanelsText, 2, 1 );
+  colorsBoxLayout->addWidget(btnPanelsText, 2, 1);
   btnPanelsText->setColor(app->panelsTextColor);
 
-  colorsBoxLayout->setRowStretch( 3, 1 );
+  colorsBoxLayout->setRowStretch(3, 1);
 
-  appTabWidget->addTab( appColors, QString() );
+  appTabWidget->addTab(appColors, QString());
 
   numericFormatPage = new QWidget();
-  QVBoxLayout *numLayout = new QVBoxLayout( numericFormatPage );
+  QVBoxLayout *numLayout = new QVBoxLayout(numericFormatPage);
   QGroupBox *numericFormatBox = new QGroupBox();
-  numLayout->addWidget( numericFormatBox );
-  QGridLayout *numericFormatLayout = new QGridLayout( numericFormatBox );
+  numLayout->addWidget(numericFormatBox);
+  QGridLayout *numericFormatLayout = new QGridLayout(numericFormatBox);
 
   lblAppPrecision = new QLabel();
   numericFormatLayout->addWidget(lblAppPrecision, 0, 0);
@@ -583,7 +585,7 @@ void ConfigDialog::initAppPage()
   numericFormatLayout->addWidget(boxAppPrecision, 0, 1);
 
   lblDecimalSeparator = new QLabel();
-  numericFormatLayout->addWidget(lblDecimalSeparator, 1, 0 );
+  numericFormatLayout->addWidget(lblDecimalSeparator, 1, 0);
   boxDecimalSeparator = new QComboBox();
   boxDecimalSeparator->addItem(tr("System Locale Setting"));
   boxDecimalSeparator->addItem("1,000.0");
@@ -593,7 +595,8 @@ void ConfigDialog::initAppPage()
   numericFormatLayout->addWidget(boxDecimalSeparator, 1, 1);
 
   boxThousandsSeparator = new QCheckBox();
-  boxThousandsSeparator->setChecked(app->locale().numberOptions() & QLocale::OmitGroupSeparator);
+  boxThousandsSeparator->setChecked(app->locale().numberOptions() &
+                                    QLocale::OmitGroupSeparator);
   numericFormatLayout->addWidget(boxThousandsSeparator, 2, 0);
 
   boxUpdateSeparators = new QCheckBox();
@@ -601,7 +604,7 @@ void ConfigDialog::initAppPage()
   numericFormatLayout->addWidget(boxUpdateSeparators, 3, 0);
   numericFormatLayout->setRowStretch(4, 1);
 
-  appTabWidget->addTab( numericFormatPage, QString() );
+  appTabWidget->addTab(numericFormatPage, QString());
 
   initFileLocationsPage();
 
@@ -612,55 +615,59 @@ void ConfigDialog::initAppPage()
   floatLayout->addWidget(floatBox);
   QGridLayout *floatPageLayout = new QGridLayout(floatBox);
 
-  QLabel* comment = new QLabel("Select types of windows to be floating by default.\n"
-    "You can use Windows menu to make a window floating or docked.");
-  floatPageLayout->addWidget(comment,0,0);
+  QLabel *comment = new QLabel(
+      "Select types of windows to be floating by default.\n"
+      "You can use Windows menu to make a window floating or docked.");
+  floatPageLayout->addWidget(comment, 0, 0);
 
   boxFloatingGraph = new QCheckBox("Graphs"); // default to true
   boxFloatingGraph->setChecked(app->isDefaultFloating("MultiLayer"));
-  floatPageLayout->addWidget(boxFloatingGraph,1,0);
+  floatPageLayout->addWidget(boxFloatingGraph, 1, 0);
 
   boxFloatingTable = new QCheckBox("Tables");
   boxFloatingTable->setChecked(app->isDefaultFloating("Table"));
-  floatPageLayout->addWidget(boxFloatingTable,2,0);
+  floatPageLayout->addWidget(boxFloatingTable, 2, 0);
 
-  boxFloatingInstrumentWindow = new QCheckBox("Instrument views"); // default to true
-  boxFloatingInstrumentWindow->setChecked(app->isDefaultFloating("InstrumentWindow"));
-  floatPageLayout->addWidget(boxFloatingInstrumentWindow,3,0);
+  boxFloatingInstrumentWindow =
+      new QCheckBox("Instrument views"); // default to true
+  boxFloatingInstrumentWindow->setChecked(
+      app->isDefaultFloating("InstrumentWindow"));
+  floatPageLayout->addWidget(boxFloatingInstrumentWindow, 3, 0);
 
   boxFloatingMantidMatrix = new QCheckBox("Mantid Matrices");
   boxFloatingMantidMatrix->setChecked(app->isDefaultFloating("MantidMatrix"));
-  floatPageLayout->addWidget(boxFloatingMantidMatrix,4,0);
+  floatPageLayout->addWidget(boxFloatingMantidMatrix, 4, 0);
 
   boxFloatingNote = new QCheckBox("Notes");
   boxFloatingNote->setChecked(app->isDefaultFloating("Note"));
-  floatPageLayout->addWidget(boxFloatingNote,5,0);
+  floatPageLayout->addWidget(boxFloatingNote, 5, 0);
 
   boxFloatingMatrix = new QCheckBox("Matrices");
   boxFloatingMatrix->setChecked(app->isDefaultFloating("Matrix"));
-  floatPageLayout->addWidget(boxFloatingMatrix,6,0);
+  floatPageLayout->addWidget(boxFloatingMatrix, 6, 0);
 
   boxFloatingCustomInterfaces = new QCheckBox("Custom interfaces");
-  boxFloatingCustomInterfaces->setChecked(app->isDefaultFloating("MdiSubWindow"));
-  floatPageLayout->addWidget(boxFloatingCustomInterfaces,7,0);
+  boxFloatingCustomInterfaces->setChecked(
+      app->isDefaultFloating("MdiSubWindow"));
+  floatPageLayout->addWidget(boxFloatingCustomInterfaces, 7, 0);
 
   boxFloatingTiledWindows = new QCheckBox("Tiled Windows");
   boxFloatingTiledWindows->setChecked(app->isDefaultFloating("TiledWindow"));
-  floatPageLayout->addWidget(boxFloatingTiledWindows,8,0);
+  floatPageLayout->addWidget(boxFloatingTiledWindows, 8, 0);
 
-  floatPageLayout->setRowStretch(8,1);
+  floatPageLayout->setRowStretch(8, 1);
   appTabWidget->addTab(floatingWindowsPage, QString());
 
-  connect( boxLanguage, SIGNAL( activated(int) ), this, SLOT( switchToLanguage(int) ) );
-  connect( fontsBtn, SIGNAL( clicked() ), this, SLOT( pickApplicationFont() ) );
-  connect( boxSave, SIGNAL( toggled(bool) ), boxMinutes, SLOT( setEnabled(bool) ) );
+  connect(boxLanguage, SIGNAL(activated(int)), this,
+          SLOT(switchToLanguage(int)));
+  connect(fontsBtn, SIGNAL(clicked()), this, SLOT(pickApplicationFont()));
+  connect(boxSave, SIGNAL(toggled(bool)), boxMinutes, SLOT(setEnabled(bool)));
 }
 
 /**
 * Configure a Mantid page on the config dialog
 */
-void ConfigDialog::initMantidPage()
-{
+void ConfigDialog::initMantidPage() {
   mtdTabWidget = new QTabWidget(generalDialog);
   mtdTabWidget->setUsesScrollButtons(false);
 
@@ -676,46 +683,52 @@ void ConfigDialog::initMantidPage()
   grid->addWidget(facility, 0, 1);
 
   defInstr = new MantidQt::MantidWidgets::InstrumentSelector();
-  // Here we only want the default instrument updated if the user clicks Ok/Apply
+  // Here we only want the default instrument updated if the user clicks
+  // Ok/Apply
   defInstr->updateInstrumentOnSelection(false);
   grid->addWidget(new QLabel("Default Instrument"), 2, 0);
   grid->addWidget(defInstr, 2, 1);
-  grid->setRowStretch(3,1);
+  grid->setRowStretch(3, 1);
 
-  //Ignore paraview.
+  // Ignore paraview.
   ckIgnoreParaView = new QCheckBox("Ignore ParaView");
-  ckIgnoreParaView->setToolTip("Don't bother me with anything to do with ParaView.\nRequires restart of MantidPlot to take effect.");
-  auto& cfgSvc = ConfigService::Instance();
+  ckIgnoreParaView->setToolTip("Don't bother me with anything to do with "
+                               "ParaView.\nRequires restart of MantidPlot to "
+                               "take effect.");
+  auto &cfgSvc = ConfigService::Instance();
   const std::string ignoreParaViewProperty = "paraview.ignore";
-  bool ignoreParaView =  cfgSvc.hasProperty(ignoreParaViewProperty) && bool(atoi(cfgSvc.getString(ignoreParaViewProperty).c_str()));
+  bool ignoreParaView =
+      cfgSvc.hasProperty(ignoreParaViewProperty) &&
+      bool(atoi(cfgSvc.getString(ignoreParaViewProperty).c_str()));
   ckIgnoreParaView->setChecked(ignoreParaView);
   grid->addWidget(ckIgnoreParaView, 3, 0);
 
-  //Change to Crystallography Convention
+  // Change to Crystallography Convention
   ckQconvention = new QCheckBox("Crystallography Convention");
   ckQconvention->setToolTip("Change from default ki-kf to kf-ki.");
   const std::string QconventionProperty = "Q.convention";
-  bool Qconvention =  cfgSvc.hasProperty(QconventionProperty) && bool(cfgSvc.getString(QconventionProperty) == "Crystallography");
+  bool Qconvention =
+      cfgSvc.hasProperty(QconventionProperty) &&
+      bool(cfgSvc.getString(QconventionProperty) == "Crystallography");
   ckQconvention->setChecked(Qconvention);
   grid->addWidget(ckQconvention, 4, 0);
 
   // Populate boxes
-  auto faclist =  cfgSvc.getFacilityNames();
-  for ( auto it = faclist.begin(); it != faclist.end(); ++it )
-  {
+  auto faclist = cfgSvc.getFacilityNames();
+  for (auto it = faclist.begin(); it != faclist.end(); ++it) {
     facility->addItem(QString::fromStdString(*it));
   }
 
   // Set default property
-  QString property = QString::fromStdString( cfgSvc.getFacility().name());
+  QString property = QString::fromStdString(cfgSvc.getFacility().name());
   int index = facility->findText(property);
-  if( index < 0 )
-  {
+  if (index < 0) {
     index = 0;
   }
   facility->setCurrentIndex(index);
   // Ensure update of instrument box with facility change
-  connect(facility, SIGNAL(currentIndexChanged(const QString&)), defInstr, SLOT(fillWithInstrumentsFromFacility(const QString &)));
+  connect(facility, SIGNAL(currentIndexChanged(const QString &)), defInstr,
+          SLOT(fillWithInstrumentsFromFacility(const QString &)));
 
   initDirSearchTab();
   initCurveFittingTab();
@@ -726,8 +739,7 @@ void ConfigDialog::initMantidPage()
 /**
  * Configure a MD Plotting Page
  */
-void ConfigDialog::initMdPlottingPage()
-{
+void ConfigDialog::initMdPlottingPage() {
   mdPlottingTabWidget = new QTabWidget(generalDialog);
   mdPlottingTabWidget->setUsesScrollButtons(false);
 
@@ -740,15 +752,15 @@ void ConfigDialog::initMdPlottingPage()
   // Set the connections
   setupMdPlottingConnections();
 
-  // Update the visibility of the Vsi tab if the General Md Color Map was selected the last time
-  if (m_mdSettings.getUsageGeneralMdColorMap())
-  {
+  // Update the visibility of the Vsi tab if the General Md Color Map was
+  // selected the last time
+  if (m_mdSettings.getUsageGeneralMdColorMap()) {
     changeUsageGeneralMdColorMap();
   }
 
-  // Update the visibility of the Vsi tab if the last session checkbox was selected.
-  if (m_mdSettings.getUsageLastSession())
-  {
+  // Update the visibility of the Vsi tab if the last session checkbox was
+  // selected.
+  if (m_mdSettings.getUsageLastSession()) {
     changeUsageLastSession();
   }
 }
@@ -756,47 +768,49 @@ void ConfigDialog::initMdPlottingPage()
 /**
  * Configure the general MD Plotting tab
  */
-void ConfigDialog::initMdPlottingGeneralTab()
-{
+void ConfigDialog::initMdPlottingGeneralTab() {
   // Ask if uniform colormap
   mdPlottingGeneralPage = new QWidget();
   QVBoxLayout *generalTabLayout = new QVBoxLayout(mdPlottingGeneralPage);
   mdPlottingGeneralFrame = new QGroupBox(mdPlottingGeneralPage);
-  generalTabLayout->addWidget(mdPlottingGeneralFrame );
+  generalTabLayout->addWidget(mdPlottingGeneralFrame);
   mdPlottingTabWidget->addTab(mdPlottingGeneralPage, QString());
 
   // Color Map
   mdPlottingGeneralFrame->setCheckable(true);
   mdPlottingGeneralFrame->setChecked(m_mdSettings.getUsageGeneralMdColorMap());
 
-  QGridLayout *gridVsiGeneralDefaultColorMap = new QGridLayout(mdPlottingGeneralFrame);
+  QGridLayout *gridVsiGeneralDefaultColorMap =
+      new QGridLayout(mdPlottingGeneralFrame);
   mdPlottingGeneralColorMap = new QComboBox();
   lblGeneralDefaultColorMap = new QLabel();
   gridVsiGeneralDefaultColorMap->addWidget(lblGeneralDefaultColorMap, 1, 0);
   gridVsiGeneralDefaultColorMap->addWidget(mdPlottingGeneralColorMap, 1, 1);
 
-  gridVsiGeneralDefaultColorMap->setRowStretch(2,1);
+  gridVsiGeneralDefaultColorMap->setRowStretch(2, 1);
 
-  QLabel* label = new QLabel("<span style=\"font-weight:600;\">Note: Changes will not take effect until MantidPlot has been restarted.</span>");
+  QLabel *label =
+      new QLabel("<span style=\"font-weight:600;\">Note: Changes will not take "
+                 "effect until MantidPlot has been restarted.</span>");
   generalTabLayout->addWidget(label);
 
   // Set the color maps
   MantidQt::API::MdPlottingCmapsProvider mdPlottingCmapsProvider;
   QStringList colorMapNames;
   QStringList colorMapFiles;
-  mdPlottingCmapsProvider.getColorMapsForMdPlotting(colorMapNames, colorMapFiles);
+  mdPlottingCmapsProvider.getColorMapsForMdPlotting(colorMapNames,
+                                                    colorMapFiles);
 
-  if (colorMapNames.size() == colorMapFiles.size())
-  {
-    for (int index = 0; index < colorMapNames.size(); ++index)
-    {
-      mdPlottingGeneralColorMap->addItem(colorMapNames[index], colorMapFiles[index]);
+  if (colorMapNames.size() == colorMapFiles.size()) {
+    for (int index = 0; index < colorMapNames.size(); ++index) {
+      mdPlottingGeneralColorMap->addItem(colorMapNames[index],
+                                         colorMapFiles[index]);
     }
   }
 
-  int currentIndex = mdPlottingGeneralColorMap->findData(m_mdSettings.getGeneralMdColorMapName(), Qt::DisplayRole);
-  if (currentIndex != -1)
-  {
+  int currentIndex = mdPlottingGeneralColorMap->findData(
+      m_mdSettings.getGeneralMdColorMapName(), Qt::DisplayRole);
+  if (currentIndex != -1) {
     mdPlottingGeneralColorMap->setCurrentIndex(currentIndex);
   }
 }
@@ -804,8 +818,7 @@ void ConfigDialog::initMdPlottingGeneralTab()
 /**
  * Configure the VSI tab
  */
-void ConfigDialog::initMdPlottingVsiTab()
-{
+void ConfigDialog::initMdPlottingVsiTab() {
   vsiPage = new QWidget();
   QVBoxLayout *vsiTabLayout = new QVBoxLayout(vsiPage);
 
@@ -843,11 +856,15 @@ void ConfigDialog::initMdPlottingVsiTab()
   const QColor backgroundColor = m_mdSettings.getUserSettingBackgroundColor();
   vsiDefaultBackground->setColor(backgroundColor);
 
-  grid->setRowStretch(4,1);
+  grid->setRowStretch(4, 1);
 
-  QLabel* label1 = new QLabel("<span style=\"font-weight:600;\">Note: The General Tab settings take precedence over the VSI Tab settings.</span>");
+  QLabel *label1 =
+      new QLabel("<span style=\"font-weight:600;\">Note: The General Tab "
+                 "settings take precedence over the VSI Tab settings.</span>");
   vsiTabLayout->addWidget(label1);
-  QLabel* label2 = new QLabel("<span style=\"font-weight:600;\">Note: Changes will not take effect until the VSI has been restarted.</span>");
+  QLabel *label2 =
+      new QLabel("<span style=\"font-weight:600;\">Note: Changes will not take "
+                 "effect until the VSI has been restarted.</span>");
   vsiTabLayout->addWidget(label2);
 
   // Set the color map selection for the VSI
@@ -859,9 +876,9 @@ void ConfigDialog::initMdPlottingVsiTab()
   vsiDefaultColorMap->addItems(mdConstants.getVsiColorMaps());
   vsiDefaultColorMap->addItems(maps);
 
-  int index = vsiDefaultColorMap->findData(m_mdSettings.getUserSettingColorMap(), Qt::DisplayRole);
-  if (index != -1)
-  {
+  int index = vsiDefaultColorMap->findData(
+      m_mdSettings.getUserSettingColorMap(), Qt::DisplayRole);
+  if (index != -1) {
     vsiDefaultColorMap->setCurrentIndex(index);
   }
 
@@ -871,10 +888,10 @@ void ConfigDialog::initMdPlottingVsiTab()
   views = mdConstants.getAllInitialViews();
   vsiInitialView->addItems(views);
 
-  int indexInitialView = vsiInitialView->findData(m_mdSettings.getUserSettingInitialView(), Qt::DisplayRole);
+  int indexInitialView = vsiInitialView->findData(
+      m_mdSettings.getUserSettingInitialView(), Qt::DisplayRole);
 
-  if (indexInitialView != -1)
-  {
+  if (indexInitialView != -1) {
     vsiInitialView->setCurrentIndex(indexInitialView);
   }
 }
@@ -882,33 +899,34 @@ void ConfigDialog::initMdPlottingVsiTab()
 /**
  * Set up the connections for Md Plotting
  */
-void ConfigDialog::setupMdPlottingConnections()
-{
-  QObject::connect(this->mdPlottingGeneralFrame, SIGNAL(toggled(bool)), this, SLOT(changeUsageGeneralMdColorMap()));
-  QObject::connect(this->mdPlottingVsiFrameBottom, SIGNAL(toggled(bool)), this, SLOT(changeUsageLastSession()));
+void ConfigDialog::setupMdPlottingConnections() {
+  QObject::connect(this->mdPlottingGeneralFrame, SIGNAL(toggled(bool)), this,
+                   SLOT(changeUsageGeneralMdColorMap()));
+  QObject::connect(this->mdPlottingVsiFrameBottom, SIGNAL(toggled(bool)), this,
+                   SLOT(changeUsageLastSession()));
 }
 
 /**
  * Handle a change of the General Md Color Map selection.
  */
-void ConfigDialog::changeUsageGeneralMdColorMap()
-{
-  // If the general color map setting is turned off and the vsi colormap is turned on
+void ConfigDialog::changeUsageGeneralMdColorMap() {
+  // If the general color map setting is turned off and the vsi colormap is
+  // turned on
   // then we set the default color map to enabled, else we disable it
-  bool isDefaultColorMapSelectable = (!mdPlottingGeneralFrame->isChecked() && mdPlottingVsiFrameBottom->isChecked());
+  bool isDefaultColorMapSelectable = (!mdPlottingGeneralFrame->isChecked() &&
+                                      mdPlottingVsiFrameBottom->isChecked());
 
   vsiDefaultColorMap->setEnabled(isDefaultColorMapSelectable);
   lblVsiDefaultColorMap->setEnabled(isDefaultColorMapSelectable);
-  //vsiDefaultColorMap->setEnabled(true);
-  //lblVsiDefaultColorMap->setEnabled(true);
+  // vsiDefaultColorMap->setEnabled(true);
+  // lblVsiDefaultColorMap->setEnabled(true);
 }
 
 /**
  * Handle a change of the Last Session selection.
   * @param isDefaultColorMapVsiChecked The state of the vsi default checkbox.
  */
-void ConfigDialog::changeUsageLastSession()
-{
+void ConfigDialog::changeUsageLastSession() {
   // Set the color map of the VSI default
   changeUsageGeneralMdColorMap();
 
@@ -917,88 +935,82 @@ void ConfigDialog::changeUsageLastSession()
   lblVsiDefaultBackground->setEnabled(mdPlottingVsiFrameBottom->isChecked());
 }
 
-
 /**
 * Configure a Mantid Options page on the config dialog
 */
-void ConfigDialog::initMantidOptionsTab()
-{
+void ConfigDialog::initMantidOptionsTab() {
   mantidOptionsPage = new QWidget();
-  mtdTabWidget->addTab(mantidOptionsPage,"Options");
+  mtdTabWidget->addTab(mantidOptionsPage, "Options");
   QVBoxLayout *widgetLayout = new QVBoxLayout(mantidOptionsPage);
   QGroupBox *frame = new QGroupBox();
   widgetLayout->addWidget(frame);
   QGridLayout *grid = new QGridLayout(frame);
 
   // if on, for example all plotSpectrum will go to the same window.
-  m_reusePlotInstances =  new QCheckBox("Re-use plot instances for different types of plots");
+  m_reusePlotInstances =
+      new QCheckBox("Re-use plot instances for different types of plots");
   m_reusePlotInstances->setChecked(false);
-  grid->addWidget(m_reusePlotInstances,0,0);
-  QString setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("MantidOptions.ReusePlotInstances"));
-  if(!setting.compare("On"))
-  {
+  grid->addWidget(m_reusePlotInstances, 0, 0);
+  QString setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "MantidOptions.ReusePlotInstances"));
+  if (!setting.compare("On")) {
     m_reusePlotInstances->setChecked(true);
-  }
-  else if(!setting.compare("Off"))
-  {
+  } else if (!setting.compare("Off")) {
     m_reusePlotInstances->setChecked(false);
   }
-  m_reusePlotInstances->setToolTip("If on, the same plot instance will be re-used for every of the different plots available in the workspaces window (spectrum, slice, color fill, etc.)");
+  m_reusePlotInstances->setToolTip("If on, the same plot instance will be "
+                                   "re-used for every of the different plots "
+                                   "available in the workspaces window "
+                                   "(spectrum, slice, color fill, etc.)");
 
-  //create a checkbox for invisible workspaces options
+  // create a checkbox for invisible workspaces options
   m_invisibleWorkspaces = new QCheckBox("Show Invisible Workspaces");
   m_invisibleWorkspaces->setChecked(false);
-  grid->addWidget(m_invisibleWorkspaces,1,0);
+  grid->addWidget(m_invisibleWorkspaces, 1, 0);
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("MantidOptions.InvisibleWorkspaces"));
-  if(!setting.compare("1"))
-  {
+  setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "MantidOptions.InvisibleWorkspaces"));
+  if (!setting.compare("1")) {
     m_invisibleWorkspaces->setChecked(true);
-  }
-  else if(!setting.compare("0"))
-  {
+  } else if (!setting.compare("0")) {
     m_invisibleWorkspaces->setChecked(false);
   }
 
-  //categories tree widget
+  // categories tree widget
   treeCategories = new QTreeWidget(frame);
   treeCategories->setColumnCount(1);
   treeCategories->setSortingEnabled(false);
   treeCategories->setHeaderLabel("Show Algorithm Categories");
 
-  grid->addWidget(treeCategories,2,0);
+  grid->addWidget(treeCategories, 2, 0);
   refreshTreeCategories();
 
   // create a checkbox for the instrument view OpenGL option
   m_useOpenGL = new QCheckBox("Use OpenGL in Instrument View");
   m_useOpenGL->setChecked(true);
-  grid->addWidget(m_useOpenGL,4,0);
+  grid->addWidget(m_useOpenGL, 4, 0);
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().
-    getString("MantidOptions.InstrumentView.UseOpenGL")).toUpper();
-  if( setting == "ON")
-  {
+  setting = QString::fromStdString(
+                Mantid::Kernel::ConfigService::Instance().getString(
+                    "MantidOptions.InstrumentView.UseOpenGL")).toUpper();
+  if (setting == "ON") {
     m_useOpenGL->setChecked(true);
-  }
-  else
-  {
+  } else {
     m_useOpenGL->setChecked(false);
   }
-
 }
 
-
-void ConfigDialog::initSendToProgramTab()
-{
+void ConfigDialog::initSendToProgramTab() {
   mantidSendToPage = new QWidget();
   mtdTabWidget->addTab(mantidSendToPage, tr("Send To"));
   QVBoxLayout *widgetLayout = new QVBoxLayout(mantidSendToPage);
   QGroupBox *frame = new QGroupBox();
-  widgetLayout ->addWidget(frame);
+  widgetLayout->addWidget(frame);
   QGridLayout *grid = new QGridLayout(frame);
 
-
-  //Add buttons to the bottom of the widget
+  // Add buttons to the bottom of the widget
   deleteButton = new QPushButton(tr("Delete"));
   deleteButton->setEnabled(false);
   connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteDialog()));
@@ -1016,156 +1028,154 @@ void ConfigDialog::initSendToProgramTab()
 
   widgetLayout->addLayout(buttons);
 
-  //create tree diagram for all known programs that can be saved to
+  // create tree diagram for all known programs that can be saved to
   treePrograms = new QTreeWidget(frame);
-  treePrograms->setSelectionMode( QAbstractItemView::ExtendedSelection );
+  treePrograms->setSelectionMode(QAbstractItemView::ExtendedSelection);
   treePrograms->setColumnCount(1);
   treePrograms->setSortingEnabled(false);
   treePrograms->setHeaderLabel(tr("List of Current Programs"));
 
-  grid->addWidget(treePrograms, 0,0);
+  grid->addWidget(treePrograms, 0, 0);
 
   populateProgramTree();
-  connect(treePrograms,SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(itemCheckedChanged(QTreeWidgetItem*)));
-  connect(treePrograms,SIGNAL(itemSelectionChanged()), this, SLOT(enableButtons()));
-
+  connect(treePrograms, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this,
+          SLOT(itemCheckedChanged(QTreeWidgetItem *)));
+  connect(treePrograms, SIGNAL(itemSelectionChanged()), this,
+          SLOT(enableButtons()));
 }
 
-void ConfigDialog::enableButtons()
-{
+void ConfigDialog::enableButtons() {
   QList<QTreeWidgetItem *> selectedItems = treePrograms->selectedItems();
-  //Set the buttons on whether the conditions are met. Reducing the amount of user errors
-  if (selectedItems.size() == 0)
-  {
+  // Set the buttons on whether the conditions are met. Reducing the amount of
+  // user errors
+  if (selectedItems.size() == 0) {
     deleteButton->setEnabled(false);
     editButton->setEnabled(false);
-  }
-  else if (selectedItems.size() == 1)
-  {
+  } else if (selectedItems.size() == 1) {
     deleteButton->setEnabled(true);
     editButton->setEnabled(true);
-  }
-  else
-  {
+  } else {
     deleteButton->setEnabled(true);
     editButton->setEnabled(false);
   }
 }
 
-void ConfigDialog::itemCheckedChanged(QTreeWidgetItem* item)
-{
-  if (item->childCount() > 0)
-  {
+void ConfigDialog::itemCheckedChanged(QTreeWidgetItem *item) {
+  if (item->childCount() > 0) {
     treePrograms->setCurrentItem(item);
   }
-  //enableButtons();
+  // enableButtons();
   std::string visibility = "Yes";
-  if (item->checkState(0) != Qt::Checked)
-  {
+  if (item->checkState(0) != Qt::Checked) {
     visibility = "No";
   }
   auto it = m_sendToSettings.find(item->text(0).toStdString());
-  if (it != m_sendToSettings.end())
-  {
+  if (it != m_sendToSettings.end()) {
     it->second["visible"] = visibility;
     updateChildren(it->second, item);
   }
 }
 
-
-//Add a program
-void ConfigDialog::addDialog()
-{
-  SendToProgramDialog* addProgram = new SendToProgramDialog(this);
+// Add a program
+void ConfigDialog::addDialog() {
+  SendToProgramDialog *addProgram = new SendToProgramDialog(this);
   addProgram->setModal(true);
-  if(addProgram->exec() == 1)
-  {
-    //Get the settings of the program the user just added
-    std::pair<std::string, std::map<std::string,std::string> > tempSettings = addProgram->getSettings();
+  if (addProgram->exec() == 1) {
+    // Get the settings of the program the user just added
+    std::pair<std::string, std::map<std::string, std::string>> tempSettings =
+        addProgram->getSettings();
     m_sendToSettings[tempSettings.first] = tempSettings.second;
   }
 
-  //clear the tree and repopulate it without the programs that have just been deleted
+  // clear the tree and repopulate it without the programs that have just been
+  // deleted
   treePrograms->clear();
   updateProgramTree();
   enableButtons();
 }
 
-//Edit a program
-void ConfigDialog::editDialog()
-{
+// Edit a program
+void ConfigDialog::editDialog() {
   auto firstSelectedItem = treePrograms->selectedItems()[0];
-  auto selectedProgram = m_sendToSettings.find(firstSelectedItem->text(0).toStdString());
+  auto selectedProgram =
+      m_sendToSettings.find(firstSelectedItem->text(0).toStdString());
   // If the program name itself isn't initially selected, recurse up.
-  while ( selectedProgram == m_sendToSettings.end() )
-  {
+  while (selectedProgram == m_sendToSettings.end()) {
     firstSelectedItem = treePrograms->itemAbove(firstSelectedItem);
-    // It shouldn't happen that we get to the top without finding anything, but should this happen just return
-    if ( firstSelectedItem == treePrograms->invisibleRootItem() ) return;
-    selectedProgram = m_sendToSettings.find(firstSelectedItem->text(0).toStdString());
+    // It shouldn't happen that we get to the top without finding anything, but
+    // should this happen just return
+    if (firstSelectedItem == treePrograms->invisibleRootItem())
+      return;
+    selectedProgram =
+        m_sendToSettings.find(firstSelectedItem->text(0).toStdString());
   }
 
-  SendToProgramDialog* editProgram = new SendToProgramDialog(this, firstSelectedItem->text(0), selectedProgram->second);
+  SendToProgramDialog *editProgram = new SendToProgramDialog(
+      this, firstSelectedItem->text(0), selectedProgram->second);
 
   editProgram->setWindowTitle(tr("Edit a Program"));
   editProgram->setModal(true);
-  if(editProgram->exec() == 1)
-  {
-    //Get the settings of the program the user just edited
-    std::pair<std::string, std::map<std::string,std::string> > tempSettings = editProgram->getSettings();
+  if (editProgram->exec() == 1) {
+    // Get the settings of the program the user just edited
+    std::pair<std::string, std::map<std::string, std::string>> tempSettings =
+        editProgram->getSettings();
     m_sendToSettings[tempSettings.first] = tempSettings.second;
   }
 
-  //clear the tree and repopulate it without the programs that have just been deleted
+  // clear the tree and repopulate it without the programs that have just been
+  // deleted
   treePrograms->clear();
   updateProgramTree();
   enableButtons();
 }
 
-
-//Deleting send to options. Deletes them off the mantid.user.properties
-void ConfigDialog::deleteDialog()
-{
+// Deleting send to options. Deletes them off the mantid.user.properties
+void ConfigDialog::deleteDialog() {
   QList<QTreeWidgetItem *> selectedItems = treePrograms->selectedItems();
-  if(selectedItems.size() > 0)
-  {
-    //Question box asking to continue to avoid accidental deletion of program options
-    int status = QMessageBox::question(this, tr("Delete save options?"), tr("Are you sure you want to delete \nthe (%1) selected save option(s)?").arg(selectedItems.size()),
-      QMessageBox::Yes|QMessageBox::Default,
-      QMessageBox::No|QMessageBox::Escape,
-      QMessageBox::NoButton);
-
-    if(status == QMessageBox::Yes)
-    {
-      //For each program selected, remove all details from the user.properties file;
-      for (int i = 0; i<selectedItems.size(); ++i)
-      {
+  if (selectedItems.size() > 0) {
+    // Question box asking to continue to avoid accidental deletion of program
+    // options
+    int status = QMessageBox::question(
+        this, tr("Delete save options?"),
+        tr("Are you sure you want to delete \nthe (%1) selected save "
+           "option(s)?").arg(selectedItems.size()),
+        QMessageBox::Yes | QMessageBox::Default,
+        QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton);
+
+    if (status == QMessageBox::Yes) {
+      // For each program selected, remove all details from the user.properties
+      // file;
+      for (int i = 0; i < selectedItems.size(); ++i) {
         m_sendToSettings.erase(selectedItems[i]->text(0).toStdString());
       }
-      //clear the tree and repopulate it without the programs that have just been deleted
+      // clear the tree and repopulate it without the programs that have just
+      // been deleted
       treePrograms->clear();
       updateProgramTree();
     }
   }
 }
 
+void ConfigDialog::populateProgramTree() {
+  std::vector<std::string> programNames =
+      Mantid::Kernel::ConfigService::Instance().getKeys(
+          "workspace.sendto.name");
 
-void ConfigDialog::populateProgramTree()
-{
-  std::vector<std::string> programNames = Mantid::Kernel::ConfigService::Instance().getKeys("workspace.sendto.name");
-
-  for(size_t i = 0; i<programNames.size(); i++)
-  {
-    //Create a map for the keys and details to go into
-    std::map<std::string,std::string> programKeysAndDetails;
+  for (size_t i = 0; i < programNames.size(); i++) {
+    // Create a map for the keys and details to go into
+    std::map<std::string, std::string> programKeysAndDetails;
 
-    //Get a list of the program detail keys (mandatory - target, saveusing) (optional - arguments, save parameters, workspace type)
-    std::vector<std::string> programKeys = (Mantid::Kernel::ConfigService::Instance().getKeys("workspace.sendto." + programNames[i]));
+    // Get a list of the program detail keys (mandatory - target, saveusing)
+    // (optional - arguments, save parameters, workspace type)
+    std::vector<std::string> programKeys =
+        (Mantid::Kernel::ConfigService::Instance().getKeys("workspace.sendto." +
+                                                           programNames[i]));
 
-    for (size_t j = 0; j<programKeys.size(); j++)
-    {
-      //Assign a key to its value using the map
-      programKeysAndDetails[programKeys[j]] = (Mantid::Kernel::ConfigService::Instance().getString(("workspace.sendto." + programNames[i] + "." + programKeys[j])));
+    for (size_t j = 0; j < programKeys.size(); j++) {
+      // Assign a key to its value using the map
+      programKeysAndDetails[programKeys[j]] =
+          (Mantid::Kernel::ConfigService::Instance().getString(
+              ("workspace.sendto." + programNames[i] + "." + programKeys[j])));
     }
 
     m_sendToSettings.emplace(programNames[i], programKeysAndDetails);
@@ -1173,29 +1183,32 @@ void ConfigDialog::populateProgramTree()
   updateProgramTree();
 }
 
-void ConfigDialog::updateProgramTree()
-{
-  //Store into a map ready to go into config service when apply is clicked
-  std::map<std::string, std::map<std::string,std::string> >::const_iterator itr = m_sendToSettings.begin();
-  for( ; itr != m_sendToSettings.end(); ++itr)
-  {
-    //creating the map of kvps needs to happen first as createing the item requires them.
+void ConfigDialog::updateProgramTree() {
+  // Store into a map ready to go into config service when apply is clicked
+  std::map<std::string, std::map<std::string, std::string>>::const_iterator
+      itr = m_sendToSettings.begin();
+  for (; itr != m_sendToSettings.end(); ++itr) {
+    // creating the map of kvps needs to happen first as createing the item
+    // requires them.
     std::map<std::string, std::string> programKeysAndDetails = itr->second;
 
-    //Populate list
-    QTreeWidgetItem *program = createCheckedTreeItem(QString::fromStdString(itr->first), (programKeysAndDetails.find("visible")->second == "Yes"));
+    // Populate list
+    QTreeWidgetItem *program = createCheckedTreeItem(
+        QString::fromStdString(itr->first),
+        (programKeysAndDetails.find("visible")->second == "Yes"));
     treePrograms->addTopLevelItem(program);
     updateChildren(programKeysAndDetails, program);
   }
 }
 
-void ConfigDialog::updateChildren(std::map<std::string, std::string> &programKeysAndDetails, QTreeWidgetItem* program)
-{
+void ConfigDialog::updateChildren(
+    std::map<std::string, std::string> &programKeysAndDetails,
+    QTreeWidgetItem *program) {
   program->takeChildren();
-  //get the current program's (itr) keys and values (pItr)
-  std::map<std::string,std::string>::const_iterator pItr = programKeysAndDetails.begin();
-  for( ; pItr != programKeysAndDetails.end(); ++pItr)
-  {
+  // get the current program's (itr) keys and values (pItr)
+  std::map<std::string, std::string>::const_iterator pItr =
+      programKeysAndDetails.begin();
+  for (; pItr != programKeysAndDetails.end(); ++pItr) {
     QTreeWidgetItem *item = new QTreeWidgetItem(program);
     QString itemText = QString("   ")
                            .append(QString::fromStdString(pItr->first))
@@ -1206,121 +1219,111 @@ void ConfigDialog::updateChildren(std::map<std::string, std::string> &programKey
   }
 }
 
-void ConfigDialog::updateSendToTab()
-{
-  Mantid::Kernel::ConfigServiceImpl&  cfgSvc = Mantid::Kernel::ConfigService::Instance();
+void ConfigDialog::updateSendToTab() {
+  Mantid::Kernel::ConfigServiceImpl &cfgSvc =
+      Mantid::Kernel::ConfigService::Instance();
 
-  //Add new values to the config service
-  std::map<std::string, std::map<std::string,std::string> >::const_iterator itr = m_sendToSettings.begin();
-  std::vector<std::string> programNames =  cfgSvc.getKeys("workspace.sendto.name");
+  // Add new values to the config service
+  std::map<std::string, std::map<std::string, std::string>>::const_iterator
+      itr = m_sendToSettings.begin();
+  std::vector<std::string> programNames =
+      cfgSvc.getKeys("workspace.sendto.name");
 
-  for( ; itr != m_sendToSettings.end(); ++itr)
-  {
-    for (size_t i = 0; i<programNames.size(); ++i)
-    {
-      if (programNames[i] == itr->first)
-      {
-        //The selected program hasn't been deleted so set to blank string (all those left without blank strings are to be deleted
+  for (; itr != m_sendToSettings.end(); ++itr) {
+    for (size_t i = 0; i < programNames.size(); ++i) {
+      if (programNames[i] == itr->first) {
+        // The selected program hasn't been deleted so set to blank string (all
+        // those left without blank strings are to be deleted
         programNames[i] = "";
       }
     }
 
-     cfgSvc.setString("workspace.sendto.name." + itr->first , "0");
+    cfgSvc.setString("workspace.sendto.name." + itr->first, "0");
 
     std::map<std::string, std::string> programKeysAndDetails = itr->second;
 
-    std::map<std::string, std::string>::const_iterator pItr = programKeysAndDetails.begin();
+    std::map<std::string, std::string>::const_iterator pItr =
+        programKeysAndDetails.begin();
 
-    for( ; pItr != programKeysAndDetails.end(); ++pItr)
-    {
-      if(pItr->second != "")
-         cfgSvc.setString("workspace.sendto." + itr->first + "." + pItr->first, pItr->second);
+    for (; pItr != programKeysAndDetails.end(); ++pItr) {
+      if (pItr->second != "")
+        cfgSvc.setString("workspace.sendto." + itr->first + "." + pItr->first,
+                         pItr->second);
     }
   }
 
-  //Delete the keys that are in the config but not in the temporary m_sendToSettings map
-  for (size_t i = 0; i<programNames.size(); ++i)
-  {
-    if (programNames[i] != "")
-    {
-       cfgSvc.remove("workspace.sendto.name." + programNames[i]);
-      std::vector<std::string> programKeys =  cfgSvc.getKeys("workspace.sendto." + programNames[i]);
-      for (size_t j = 0; j<programKeys.size(); ++j)
-      {
-         cfgSvc.remove("workspace.sendto." + programNames[i] + "." +  programKeys[j]);
+  // Delete the keys that are in the config but not in the temporary
+  // m_sendToSettings map
+  for (size_t i = 0; i < programNames.size(); ++i) {
+    if (programNames[i] != "") {
+      cfgSvc.remove("workspace.sendto.name." + programNames[i]);
+      std::vector<std::string> programKeys =
+          cfgSvc.getKeys("workspace.sendto." + programNames[i]);
+      for (size_t j = 0; j < programKeys.size(); ++j) {
+        cfgSvc.remove("workspace.sendto." + programNames[i] + "." +
+                      programKeys[j]);
       }
     }
   }
 }
 
-void ConfigDialog::refreshTreeCategories()
-{
+void ConfigDialog::refreshTreeCategories() {
   treeCategories->clear();
 
-  typedef std::map<std::string,bool> categoriesType;
-  categoriesType categoryMap = Mantid::API::AlgorithmFactory::Instance().getCategoriesWithState();
+  typedef std::map<std::string, bool> categoriesType;
+  categoriesType categoryMap =
+      Mantid::API::AlgorithmFactory::Instance().getCategoriesWithState();
 
-  QMap<QString,QTreeWidgetItem*> categories;// keeps track of categories added to the tree
+  QMap<QString, QTreeWidgetItem *>
+      categories; // keeps track of categories added to the tree
 
-  for(categoriesType::const_iterator i=categoryMap.begin();i!=categoryMap.end();++i)
-  {
+  for (categoriesType::const_iterator i = categoryMap.begin();
+       i != categoryMap.end(); ++i) {
     QString catName = QString::fromStdString(i->first);
     bool isHidden = i->second;
     QStringList subCats = catName.split('\\');
-    if (subCats.size() == 1)
-    {
-      QTreeWidgetItem *catItem = createCheckedTreeItem(catName,!isHidden);
-      categories.insert(catName,catItem);
+    if (subCats.size() == 1) {
+      QTreeWidgetItem *catItem = createCheckedTreeItem(catName, !isHidden);
+      categories.insert(catName, catItem);
       treeCategories->addTopLevelItem(catItem);
-    }
-    else
-    {
+    } else {
       QString cn = subCats[0];
       QTreeWidgetItem *catItem = 0;
       int n = subCats.size();
-      for(int j=0;j<n;j++)
-      {
-        if (categories.contains(cn))
-        {
+      for (int j = 0; j < n; j++) {
+        if (categories.contains(cn)) {
           catItem = categories[cn];
-        }
-        else
-        {
-          QTreeWidgetItem *newCatItem = createCheckedTreeItem(subCats[j],!isHidden);
-          categories.insert(cn,newCatItem);
-          if (!catItem)
-          {
+        } else {
+          QTreeWidgetItem *newCatItem =
+              createCheckedTreeItem(subCats[j], !isHidden);
+          categories.insert(cn, newCatItem);
+          if (!catItem) {
             treeCategories->addTopLevelItem(newCatItem);
-          }
-          else
-          {
+          } else {
             catItem->addChild(newCatItem);
           }
           catItem = newCatItem;
         }
-        if (j != n-1) cn += "\\" + subCats[j+1];
+        if (j != n - 1)
+          cn += "\\" + subCats[j + 1];
       }
     }
   }
 }
 
-QTreeWidgetItem* ConfigDialog::createCheckedTreeItem(QString name,bool checkBoxState)
-{
+QTreeWidgetItem *ConfigDialog::createCheckedTreeItem(QString name,
+                                                     bool checkBoxState) {
   QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(name));
-  item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
-  if (checkBoxState)
-  {
-    item->setCheckState(0,Qt::Checked);
-  }
-  else
-  {
-    item->setCheckState(0,Qt::Unchecked);
+  item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
+  if (checkBoxState) {
+    item->setCheckState(0, Qt::Checked);
+  } else {
+    item->setCheckState(0, Qt::Unchecked);
   }
   return item;
 }
 
-void ConfigDialog::initDirSearchTab()
-{
+void ConfigDialog::initDirSearchTab() {
 
   directoriesPage = new QWidget();
   QVBoxLayout *dirTabLayout = new QVBoxLayout(directoriesPage);
@@ -1331,10 +1334,11 @@ void ConfigDialog::initDirSearchTab()
 
   /// pythonscripts.directories
 
-  QLabel* label = new QLabel(tr("Python scripts"));
+  QLabel *label = new QLabel(tr("Python scripts"));
   grid->addWidget(label, 0, 0);
 
-  std::string str = Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directories");
+  std::string str = Mantid::Kernel::ConfigService::Instance().getString(
+      "pythonscripts.directories");
   lePythonScriptsDirs = new QLineEdit();
   lePythonScriptsDirs->setText(QString::fromStdString(str));
   grid->addWidget(lePythonScriptsDirs, 0, 1);
@@ -1343,7 +1347,7 @@ void ConfigDialog::initDirSearchTab()
   button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
   grid->addWidget(button, 0, 2);
 
-  connect( button, SIGNAL(clicked()), this, SLOT(addPythonScriptsDirs()) );
+  connect(button, SIGNAL(clicked()), this, SLOT(addPythonScriptsDirs()));
 
   /// pythonscripts.directories
 
@@ -1351,7 +1355,8 @@ void ConfigDialog::initDirSearchTab()
   label->setWordWrap(true);
   grid->addWidget(label, 1, 0);
 
-  str = Mantid::Kernel::ConfigService::Instance().getString("user.python.plugins.directories");
+  str = Mantid::Kernel::ConfigService::Instance().getString(
+      "user.python.plugins.directories");
   lePythonPluginsDirs = new QLineEdit();
   lePythonPluginsDirs->setText(QString::fromStdString(str));
   grid->addWidget(lePythonPluginsDirs, 1, 1);
@@ -1360,13 +1365,14 @@ void ConfigDialog::initDirSearchTab()
   button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
   grid->addWidget(button, 1, 2);
 
-  connect( button, SIGNAL(clicked()), this, SLOT(addPythonPluginDirs()) );
+  connect(button, SIGNAL(clicked()), this, SLOT(addPythonPluginDirs()));
 
   /// instrumentDefinition.directory
   label = new QLabel(tr("Instrument definitions"));
   grid->addWidget(label, 2, 0);
 
-  str = Mantid::Kernel::ConfigService::Instance().getString("instrumentDefinition.directory");
+  str = Mantid::Kernel::ConfigService::Instance().getString(
+      "instrumentDefinition.directory");
   leInstrumentDir = new QLineEdit();
   leInstrumentDir->setText(QString::fromStdString(str));
   grid->addWidget(leInstrumentDir, 2, 1);
@@ -1375,13 +1381,12 @@ void ConfigDialog::initDirSearchTab()
   button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
   grid->addWidget(button, 2, 2);
 
-  connect( button, SIGNAL(clicked()), this, SLOT(addInstrumentDir()) );
+  connect(button, SIGNAL(clicked()), this, SLOT(addInstrumentDir()));
 
-  grid->setRowStretch(3,1);
+  grid->setRowStretch(3, 1);
 }
 
-void ConfigDialog::initCurveFittingTab()
-{
+void ConfigDialog::initCurveFittingTab() {
   curveFittingPage = new QWidget();
   QVBoxLayout *curveTabLayout = new QVBoxLayout(curveFittingPage);
   QGroupBox *frame = new QGroupBox();
@@ -1390,234 +1395,227 @@ void ConfigDialog::initCurveFittingTab()
   mtdTabWidget->addTab(curveFittingPage, "Curve Fitting");
 
   // Background functions list
-  grid->addWidget(new QLabel(tr("Auto background")),0,0);
+  grid->addWidget(new QLabel(tr("Auto background")), 0, 0);
   backgroundFunctions = new QComboBox();
   grid->addWidget(backgroundFunctions, 0, 1);
 
   QLabel *label = new QLabel(tr("Background arguments"));
   QString tip = tr("A space-separated list of name=value arguments, \n"
-    "i.e. a=1 b=2");
+                   "i.e. a=1 b=2");
   label->setToolTip(tip);
-  grid->addWidget(label,1,0);
+  grid->addWidget(label, 1, 0);
   functionArguments = new QLineEdit();
   functionArguments->setToolTip(tip);
-  grid->addWidget(functionArguments, 1,1);
+  grid->addWidget(functionArguments, 1, 1);
 
-  grid->addWidget(new QLabel(tr("Default peak shape")),2,0);
+  grid->addWidget(new QLabel(tr("Default peak shape")), 2, 0);
   defaultPeakShape = new QComboBox();
-  grid->addWidget(defaultPeakShape, 2,1);
+  grid->addWidget(defaultPeakShape, 2, 1);
 
-  grid->addWidget(new QLabel(tr("FindPeaks FWHM")),3,0);
+  grid->addWidget(new QLabel(tr("FindPeaks FWHM")), 3, 0);
   findPeaksFWHM = new QSpinBox();
-  grid->addWidget(findPeaksFWHM, 3,1);
+  grid->addWidget(findPeaksFWHM, 3, 1);
 
-  grid->addWidget(new QLabel(tr("FindPeaks Tolerance")),4,0);
+  grid->addWidget(new QLabel(tr("FindPeaks Tolerance")), 4, 0);
   findPeaksTolerance = new QSpinBox();
   findPeaksTolerance->setMaximum(1000000);
-  grid->addWidget(findPeaksTolerance, 4,1);
+  grid->addWidget(findPeaksTolerance, 4, 1);
 
-  grid->addWidget(new QLabel(tr("Peak Radius (in FWHM)")),5,0);
+  grid->addWidget(new QLabel(tr("Peak Radius (in FWHM)")), 5, 0);
   peakRadius = new QSpinBox();
   peakRadius->setMaximum(std::numeric_limits<int>::max());
-  grid->addWidget(peakRadius, 5,1);
+  grid->addWidget(peakRadius, 5, 1);
 
-  grid->addWidget(new QLabel(tr("Double property decimals")),6,0);
+  grid->addWidget(new QLabel(tr("Double property decimals")), 6, 0);
   decimals = new QSpinBox();
-  grid->addWidget(decimals, 6,1);
+  grid->addWidget(decimals, 6, 1);
 
-  grid->setRowStretch(7,1);
-  label = new QLabel("<span style=\"font-weight:600;\">Note: Changes will not take effect until MantidPlot has been restarted.</span>");
+  grid->setRowStretch(7, 1);
+  label = new QLabel("<span style=\"font-weight:600;\">Note: Changes will not "
+                     "take effect until MantidPlot has been restarted.</span>");
   curveTabLayout->addWidget(label);
 
   // Find list of background functions
   // Add none option
   backgroundFunctions->addItem("None");
-  Mantid::API::FunctionFactoryImpl & function_creator = Mantid::API::FunctionFactory::Instance();
+  Mantid::API::FunctionFactoryImpl &function_creator =
+      Mantid::API::FunctionFactory::Instance();
   std::vector<std::string> allfunctions = function_creator.getKeys();
   size_t nfuncs = allfunctions.size();
-  for( size_t i = 0; i < nfuncs; ++i )
-  {
+  for (size_t i = 0; i < nfuncs; ++i) {
     std::string name = allfunctions[i];
     auto function = function_creator.createFunction(name);
-    if( dynamic_cast<Mantid::API::IBackgroundFunction*>(function.get()) )
-    {
+    if (dynamic_cast<Mantid::API::IBackgroundFunction *>(function.get())) {
       backgroundFunctions->addItem(QString::fromStdString(name));
     }
-    if( dynamic_cast<Mantid::API::IPeakFunction*>(function.get()) )
-    {
+    if (dynamic_cast<Mantid::API::IPeakFunction *>(function.get())) {
       defaultPeakShape->addItem(QString::fromStdString(name));
     }
   }
 
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   // Set the correct default property
-  QString setting = app->mantidUI->fitFunctionBrowser()->getAutoBackgroundString();
+  QString setting =
+      app->mantidUI->fitFunctionBrowser()->getAutoBackgroundString();
   QStringList value = setting.split(' ');
   int index(-1);
-  if( value.isEmpty() )
-  {
+  if (value.isEmpty()) {
     index = 0;
-  }
-  else
-  {
-    index = backgroundFunctions->findText(value[0], Qt::MatchFixedString);// Case insensitive
-    if( value.size() > 1 )
-    {
+  } else {
+    index = backgroundFunctions->findText(
+        value[0], Qt::MatchFixedString); // Case insensitive
+    if (value.size() > 1) {
       value.removeFirst();
       QString args = value.join(" ");
       functionArguments->setText(args);
     }
   }
-  if( index < 0 )
-  {
+  if (index < 0) {
     backgroundFunctions->setCurrentIndex(0);
-  }
-  else
-  {
+  } else {
     backgroundFunctions->setCurrentIndex(index);
   }
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.defaultPeak"));
-  if (setting.isEmpty()) setting = "Gaussian";
+  setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "curvefitting.defaultPeak"));
+  if (setting.isEmpty())
+    setting = "Gaussian";
   index = defaultPeakShape->findText(setting);
-  if (index >= 0)
-  {
+  if (index >= 0) {
     defaultPeakShape->setCurrentIndex(index);
   }
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksFWHM"));
-  if (!setting.isEmpty())
-  {
+  setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "curvefitting.findPeaksFWHM"));
+  if (!setting.isEmpty()) {
     findPeaksFWHM->setValue(setting.toInt());
-  }
-  else
-  {
+  } else {
     findPeaksFWHM->setValue(7);
   }
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksTolerance"));
-  if (!setting.isEmpty())
-  {
+  setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "curvefitting.findPeaksTolerance"));
+  if (!setting.isEmpty()) {
     findPeaksTolerance->setValue(setting.toInt());
-  }
-  else
-  {
+  } else {
     findPeaksTolerance->setValue(4);
   }
 
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.peakRadius"));
-  if (!setting.isEmpty())
-  {
+  setting = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "curvefitting.peakRadius"));
+  if (!setting.isEmpty()) {
     peakRadius->setValue(setting.toInt());
-  }
-  else
-  {
+  } else {
     peakRadius->setValue(5);
   }
 
   decimals->setValue(app->mantidUI->fitFunctionBrowser()->getDecimals());
-
 }
 
-
-void ConfigDialog::initOptionsPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initOptionsPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   plotOptions = new QWidget();
 
-  QVBoxLayout * optionsTabLayout = new QVBoxLayout( plotOptions );
+  QVBoxLayout *optionsTabLayout = new QVBoxLayout(plotOptions);
   optionsTabLayout->setSpacing(5);
 
-  QGroupBox * groupBoxOptions = new QGroupBox();
-  optionsTabLayout->addWidget( groupBoxOptions );
+  QGroupBox *groupBoxOptions = new QGroupBox();
+  optionsTabLayout->addWidget(groupBoxOptions);
 
-  QGridLayout * optionsLayout = new QGridLayout( groupBoxOptions );
+  QGridLayout *optionsLayout = new QGridLayout(groupBoxOptions);
 
   boxAutoscaling = new QCheckBox();
   boxAutoscaling->setChecked(app->autoscale2DPlots);
-  optionsLayout->addWidget( boxAutoscaling, 0, 0 );
+  optionsLayout->addWidget(boxAutoscaling, 0, 0);
 
   boxScaleFonts = new QCheckBox();
   boxScaleFonts->setChecked(app->autoScaleFonts);
-  optionsLayout->addWidget( boxScaleFonts, 0, 1 );
+  optionsLayout->addWidget(boxScaleFonts, 0, 1);
 
   boxTitle = new QCheckBox();
   boxTitle->setChecked(app->titleOn);
-  optionsLayout->addWidget( boxTitle, 1, 0 );
+  optionsLayout->addWidget(boxTitle, 1, 0);
 
   boxAntialiasing = new QCheckBox();
   boxAntialiasing->setChecked(app->antialiasing2DPlots);
-  optionsLayout->addWidget( boxAntialiasing, 1, 1 );
+  optionsLayout->addWidget(boxAntialiasing, 1, 1);
 
-  boxAspectRatio  = new QCheckBox();
+  boxAspectRatio = new QCheckBox();
   boxAspectRatio->setChecked(app->fixedAspectRatio2DPlots);
-  optionsLayout->addWidget( boxAspectRatio, 2, 1);
+  optionsLayout->addWidget(boxAspectRatio, 2, 1);
 #if QWT_VERSION < 0x050200
   boxAspectRatio->setChecked(false);
   boxAspectRatio->setVisible(true);
 #endif
   boxFrame = new QCheckBox();
   boxFrame->setChecked(app->canvasFrameWidth > 0);
-  optionsLayout->addWidget( boxFrame, 2, 0 );
+  optionsLayout->addWidget(boxFrame, 2, 0);
 
   boxDistribution = new QCheckBox();
   boxDistribution->setChecked(app->autoDistribution1D);
-  optionsLayout->addWidget( boxDistribution, 3, 0);
+  optionsLayout->addWidget(boxDistribution, 3, 0);
 
   labelFrameWidth = new QLabel();
-  optionsLayout->addWidget( labelFrameWidth, 4, 0 );
-  boxFrameWidth= new QSpinBox();
-  optionsLayout->addWidget( boxFrameWidth, 4, 1 );
+  optionsLayout->addWidget(labelFrameWidth, 4, 0);
+  boxFrameWidth = new QSpinBox();
+  optionsLayout->addWidget(boxFrameWidth, 4, 1);
   boxFrameWidth->setRange(1, 100);
   boxFrameWidth->setValue(app->canvasFrameWidth);
-  if (!app->canvasFrameWidth)
-  {
+  if (!app->canvasFrameWidth) {
     labelFrameWidth->hide();
     boxFrameWidth->hide();
   }
 
   lblMargin = new QLabel();
-  optionsLayout->addWidget( lblMargin, 5, 0 );
-  boxMargin= new QSpinBox();
+  optionsLayout->addWidget(lblMargin, 5, 0);
+  boxMargin = new QSpinBox();
   boxMargin->setRange(0, 1000);
   boxMargin->setSingleStep(5);
   boxMargin->setValue(app->defaultPlotMargin);
-  optionsLayout->addWidget( boxMargin, 5, 1 );
+  optionsLayout->addWidget(boxMargin, 5, 1);
 
-  optionsLayout->setRowStretch( 7, 1 );
+  optionsLayout->setRowStretch(7, 1);
 
   boxResize = new QCheckBox();
   boxResize->setChecked(!app->autoResizeLayers);
-  if(boxResize->isChecked())
+  if (boxResize->isChecked())
     boxScaleFonts->setEnabled(false);
 
-  optionsTabLayout->addWidget( boxResize );
+  optionsTabLayout->addWidget(boxResize);
 
   boxLabelsEditing = new QCheckBox();
   boxLabelsEditing->setChecked(!app->d_in_place_editing);
   optionsTabLayout->addWidget(boxLabelsEditing);
 
-  plotsTabWidget->addTab( plotOptions, QString() );
+  plotsTabWidget->addTab(plotOptions, QString());
 }
 
-void ConfigDialog::initAxesPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initAxesPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app)
     return;
 
   axesPage = new QWidget();
 
-  QGroupBox * axisOptions = new QGroupBox();
-  QGridLayout * axisOptionsLayout = new QGridLayout( axisOptions );
+  QGroupBox *axisOptions = new QGroupBox();
+  QGridLayout *axisOptionsLayout = new QGridLayout(axisOptions);
 
   boxBackbones = new QCheckBox();
   boxBackbones->setChecked(app->drawBackbones);
@@ -1629,7 +1627,7 @@ void ConfigDialog::initAxesPage()
 
   lblAxesLineWidth = new QLabel();
   axisOptionsLayout->addWidget(lblAxesLineWidth, 1, 0);
-  boxLineWidth= new QSpinBox();
+  boxLineWidth = new QSpinBox();
   boxLineWidth->setRange(0, 100);
   boxLineWidth->setValue(app->axesLineWidth);
   axisOptionsLayout->addWidget(boxLineWidth, 1, 1);
@@ -1650,7 +1648,7 @@ void ConfigDialog::initAxesPage()
   axisOptionsLayout->setRowStretch(4, 1);
 
   enabledAxesGroupBox = new QGroupBox();
-  enabledAxesGrid = new QGridLayout( enabledAxesGroupBox );
+  enabledAxesGrid = new QGridLayout(enabledAxesGroupBox);
 
   enableAxisLabel = new QLabel();
   enabledAxesGrid->addWidget(enableAxisLabel, 0, 2);
@@ -1660,30 +1658,30 @@ void ConfigDialog::initAxesPage()
   enabledAxesGrid->addWidget(scaleLabel, 0, 4);
 
   QLabel *pixLabel = new QLabel();
-  pixLabel->setPixmap (QPixmap (":/left_axis.png"));
+  pixLabel->setPixmap(QPixmap(":/left_axis.png"));
   enabledAxesGrid->addWidget(pixLabel, 1, 0);
   yLeftLabel = new QLabel();
   enabledAxesGrid->addWidget(yLeftLabel, 1, 1);
 
   pixLabel = new QLabel();
-  pixLabel->setPixmap (QPixmap (":/right_axis.png"));
+  pixLabel->setPixmap(QPixmap(":/right_axis.png"));
   enabledAxesGrid->addWidget(pixLabel, 2, 0);
   yRightLabel = new QLabel();
   enabledAxesGrid->addWidget(yRightLabel, 2, 1);
 
   pixLabel = new QLabel();
-  pixLabel->setPixmap (QPixmap (":/bottom_axis.png"));
+  pixLabel->setPixmap(QPixmap(":/bottom_axis.png"));
   enabledAxesGrid->addWidget(pixLabel, 3, 0);
   xBottomLabel = new QLabel();
   enabledAxesGrid->addWidget(xBottomLabel, 3, 1);
 
   pixLabel = new QLabel();
-  pixLabel->setPixmap (QPixmap (":/top_axis.png"));
+  pixLabel->setPixmap(QPixmap(":/top_axis.png"));
   enabledAxesGrid->addWidget(pixLabel, 4, 0);
   xTopLabel = new QLabel();
   enabledAxesGrid->addWidget(xTopLabel, 4, 1);
 
-  for (int i = 0; i < QwtPlot::axisCnt; i++){
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
     QCheckBox *box1 = new QCheckBox();
     int row = i + 1;
 
@@ -1702,82 +1700,82 @@ void ConfigDialog::initAxesPage()
     enabledAxesGrid->addWidget(box3, row, 4);
     box3->addItem(tr("linear"));
     box3->addItem("log");
-    if ( app->d_axes_scales[i] == "log" ) box3->setCurrentIndex(1);
+    if (app->d_axes_scales[i] == "log")
+      box3->setCurrentIndex(1);
   }
-  enabledAxesGrid->setColumnStretch (0, 0);
-  enabledAxesGrid->setColumnStretch (1, 1);
-  enabledAxesGrid->setColumnStretch (2, 1);
-  enabledAxesGrid->setColumnStretch (3, 1);
+  enabledAxesGrid->setColumnStretch(0, 0);
+  enabledAxesGrid->setColumnStretch(1, 1);
+  enabledAxesGrid->setColumnStretch(2, 1);
+  enabledAxesGrid->setColumnStretch(3, 1);
 
-  QVBoxLayout * axesPageLayout = new QVBoxLayout( axesPage );
+  QVBoxLayout *axesPageLayout = new QVBoxLayout(axesPage);
   axesPageLayout->addWidget(axisOptions);
   axesPageLayout->addWidget(enabledAxesGroupBox);
 }
 
-void ConfigDialog::initCurvesPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initCurvesPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   curves = new QWidget();
 
-  QGroupBox * curvesGroupBox = new QGroupBox();
-  QGridLayout * curvesBoxLayout = new QGridLayout( curvesGroupBox );
+  QGroupBox *curvesGroupBox = new QGroupBox();
+  QGridLayout *curvesBoxLayout = new QGridLayout(curvesGroupBox);
 
   lblCurveStyle = new QLabel();
-  curvesBoxLayout->addWidget( lblCurveStyle, 0, 0 );
+  curvesBoxLayout->addWidget(lblCurveStyle, 0, 0);
   boxCurveStyle = new QComboBox();
-  curvesBoxLayout->addWidget( boxCurveStyle, 0, 1 );
+  curvesBoxLayout->addWidget(boxCurveStyle, 0, 1);
 
   lblLineWidth = new QLabel();
-  curvesBoxLayout->addWidget( lblLineWidth, 1, 0 );
+  curvesBoxLayout->addWidget(lblLineWidth, 1, 0);
   boxCurveLineWidth = new DoubleSpinBox('f');
   boxCurveLineWidth->setLocale(app->locale());
   boxCurveLineWidth->setSingleStep(0.1);
   boxCurveLineWidth->setRange(0.1, 100);
   boxCurveLineWidth->setValue(app->defaultCurveLineWidth);
-  curvesBoxLayout->addWidget( boxCurveLineWidth, 1, 1 );
+  curvesBoxLayout->addWidget(boxCurveLineWidth, 1, 1);
 
   lblSymbSize = new QLabel();
-  curvesBoxLayout->addWidget( lblSymbSize, 2, 0 );
+  curvesBoxLayout->addWidget(lblSymbSize, 2, 0);
   boxSymbolSize = new QSpinBox();
-  boxSymbolSize->setRange(1,100);
-  boxSymbolSize->setValue(app->defaultSymbolSize/2);
-  curvesBoxLayout->addWidget( boxSymbolSize, 2, 1 );
+  boxSymbolSize->setRange(1, 100);
+  boxSymbolSize->setValue(app->defaultSymbolSize / 2);
+  curvesBoxLayout->addWidget(boxSymbolSize, 2, 1);
 
   cbApplyToMantid = new QCheckBox("Apply to Mantid");
-  if (app->applyCurveStyleToMantid)
-  {
+  if (app->applyCurveStyleToMantid) {
     cbApplyToMantid->setChecked(true);
-  }
-  else
-  {
+  } else {
     cbApplyToMantid->setChecked(false);
   }
   curvesBoxLayout->addWidget(cbApplyToMantid, 3, 1);
 
   cbDrawAllErrors = new QCheckBox("Draw all errors");
-  cbDrawAllErrors->setChecked( app->drawAllErrors );
+  cbDrawAllErrors->setChecked(app->drawAllErrors);
   curvesBoxLayout->addWidget(cbDrawAllErrors, 4, 1);
 
-  curvesBoxLayout->setRowStretch( 5, 1 );
+  curvesBoxLayout->setRowStretch(5, 1);
 
-  QHBoxLayout * curvesPageLayout = new QHBoxLayout( curves );
-  curvesPageLayout->addWidget( curvesGroupBox );
+  QHBoxLayout *curvesPageLayout = new QHBoxLayout(curves);
+  curvesPageLayout->addWidget(curvesGroupBox);
 }
 
-void ConfigDialog::initFittingPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initFittingPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
   fitPage = new QWidget();
 
   groupBoxFittingCurve = new QGroupBox();
-  QGridLayout * fittingCurveLayout = new QGridLayout(groupBoxFittingCurve);
+  QGridLayout *fittingCurveLayout = new QGridLayout(groupBoxFittingCurve);
   fittingCurveLayout->setSpacing(5);
 
   generatePointsBtn = new QRadioButton();
@@ -1806,7 +1804,7 @@ void ConfigDialog::initFittingPage()
   groupBoxMultiPeak->setCheckable(true);
   groupBoxMultiPeak->setChecked(app->generatePeakCurves);
 
-  QHBoxLayout * multiPeakLayout = new QHBoxLayout(groupBoxMultiPeak);
+  QHBoxLayout *multiPeakLayout = new QHBoxLayout(groupBoxMultiPeak);
 
   lblPeaksColor = new QLabel();
   multiPeakLayout->addWidget(lblPeaksColor);
@@ -1815,7 +1813,7 @@ void ConfigDialog::initFittingPage()
   multiPeakLayout->addWidget(boxPeaksColor);
 
   groupBoxFitParameters = new QGroupBox();
-  QGridLayout * fitParamsLayout = new QGridLayout(groupBoxFitParameters);
+  QGridLayout *fitParamsLayout = new QGridLayout(groupBoxFitParameters);
 
   lblPrecision = new QLabel();
   fitParamsLayout->addWidget(lblPrecision, 0, 0);
@@ -1838,55 +1836,58 @@ void ConfigDialog::initFittingPage()
   cbEnableQtiPlotFitting = new QCheckBox();
   cbEnableQtiPlotFitting->setChecked(app->m_enableQtiPlotFitting);
 
-  QVBoxLayout* fitPageLayout = new QVBoxLayout(fitPage);
+  QVBoxLayout *fitPageLayout = new QVBoxLayout(fitPage);
   fitPageLayout->addWidget(cbEnableQtiPlotFitting);
   fitPageLayout->addWidget(groupBoxFittingCurve);
   fitPageLayout->addWidget(groupBoxMultiPeak);
   fitPageLayout->addWidget(groupBoxFitParameters);
   fitPageLayout->addStretch();
 
-  connect(samePointsBtn, SIGNAL(toggled(bool)), this, SLOT(showPointsBox(bool)));
-  connect(generatePointsBtn, SIGNAL(toggled(bool)), this, SLOT(showPointsBox(bool)));
+  connect(samePointsBtn, SIGNAL(toggled(bool)), this,
+          SLOT(showPointsBox(bool)));
+  connect(generatePointsBtn, SIGNAL(toggled(bool)), this,
+          SLOT(showPointsBox(bool)));
 }
 
-void ConfigDialog::initConfirmationsPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initConfirmationsPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
   confirm = new QWidget();
 
   groupBoxConfirm = new QGroupBox();
-  QVBoxLayout * layout = new QVBoxLayout( groupBoxConfirm );
+  QVBoxLayout *layout = new QVBoxLayout(groupBoxConfirm);
 
   boxFolders = new QCheckBox();
   boxFolders->setChecked(app->confirmCloseFolder);
-  layout->addWidget( boxFolders );
+  layout->addWidget(boxFolders);
 
   boxTables = new QCheckBox();
   boxTables->setChecked(app->confirmCloseTable);
-  layout->addWidget( boxTables );
+  layout->addWidget(boxTables);
 
   boxMatrices = new QCheckBox();
   boxMatrices->setChecked(app->confirmCloseMatrix);
-  layout->addWidget( boxMatrices );
+  layout->addWidget(boxMatrices);
 
   boxPlots2D = new QCheckBox();
   boxPlots2D->setChecked(app->confirmClosePlot2D);
-  layout->addWidget( boxPlots2D );
+  layout->addWidget(boxPlots2D);
 
   boxPlots3D = new QCheckBox();
   boxPlots3D->setChecked(app->confirmClosePlot3D);
-  layout->addWidget( boxPlots3D );
+  layout->addWidget(boxPlots3D);
 
   boxNotes = new QCheckBox();
   boxNotes->setChecked(app->confirmCloseNotes);
-  layout->addWidget( boxNotes );
+  layout->addWidget(boxNotes);
 
-  boxInstrWindow=new QCheckBox();
+  boxInstrWindow = new QCheckBox();
   boxInstrWindow->setChecked(app->confirmCloseInstrWindow);
-  layout->addWidget( boxInstrWindow );
+  layout->addWidget(boxInstrWindow);
   layout->addStretch();
 
   boxPromptRenameTables = new QCheckBox();
@@ -1895,24 +1896,23 @@ void ConfigDialog::initConfirmationsPage()
   boxPromptDeleteWorkspace = new QCheckBox();
   boxPromptDeleteWorkspace->setChecked(app->d_inform_delete_workspace);
 
-
-  QVBoxLayout * confirmPageLayout = new QVBoxLayout( confirm );
+  QVBoxLayout *confirmPageLayout = new QVBoxLayout(confirm);
   confirmPageLayout->addWidget(groupBoxConfirm);
   confirmPageLayout->addWidget(boxPromptDeleteWorkspace);
   confirmPageLayout->addWidget(boxPromptRenameTables);
   confirmPageLayout->addStretch();
 }
 
-void ConfigDialog::initFileLocationsPage()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::initFileLocationsPage() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   fileLocationsPage = new QWidget();
 
   QGroupBox *gb = new QGroupBox();
   QGridLayout *gl = new QGridLayout(gb);
 
   lblTranslationsPath = new QLabel(tr("Translations"));
-  gl->addWidget(lblTranslationsPath , 0, 0);
+  gl->addWidget(lblTranslationsPath, 0, 0);
 
   translationsPathLine = new QLineEdit();
   translationsPathLine->setText(app->d_translations_folder);
@@ -1923,11 +1923,11 @@ void ConfigDialog::initFileLocationsPage()
   gl->addWidget(browseTranslationsBtn, 0, 2);
 
   lblHelpPath = new QLabel(tr("Help"));
-  gl->addWidget(lblHelpPath, 1, 0 );
+  gl->addWidget(lblHelpPath, 1, 0);
 
   QFileInfo hfi(app->helpFilePath);
   helpPathLine = new QLineEdit(hfi.dir().absolutePath());
-  gl->addWidget( helpPathLine, 1, 1);
+  gl->addWidget(helpPathLine, 1, 1);
 
   QPushButton *browseHelpBtn = new QPushButton();
   browseHelpBtn->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
@@ -1939,27 +1939,29 @@ void ConfigDialog::initFileLocationsPage()
 
   appTabWidget->addTab(fileLocationsPage, QString());
 
-  connect(browseTranslationsBtn, SIGNAL(clicked()), this, SLOT(chooseTranslationsFolder()));
+  connect(browseTranslationsBtn, SIGNAL(clicked()), this,
+          SLOT(chooseTranslationsFolder()));
   connect(browseHelpBtn, SIGNAL(clicked()), this, SLOT(chooseHelpFolder()));
 }
 
-void ConfigDialog::languageChange()
-{
-  setWindowTitle( tr( "MantidPlot - Choose default settings" ) ); //Mantid
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+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.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   // pages list
   itemsList->clear();
-  itemsList->addItem( tr( "General" ) );
-  itemsList->addItem( tr( "Mantid" ) );
-  itemsList->addItem( tr( "Tables" ) );
-  itemsList->addItem( tr( "2D Plots" ) );
-  itemsList->addItem( tr( "3D Plots" ) );
-  itemsList->addItem( tr( "Fitting" ) );
-  itemsList->addItem( tr( "MD Plotting" ) );
+  itemsList->addItem(tr("General"));
+  itemsList->addItem(tr("Mantid"));
+  itemsList->addItem(tr("Tables"));
+  itemsList->addItem(tr("2D Plots"));
+  itemsList->addItem(tr("3D Plots"));
+  itemsList->addItem(tr("Fitting"));
+  itemsList->addItem(tr("MD Plotting"));
   itemsList->setCurrentRow(0);
   itemsList->item(0)->setIcon(QIcon(getQPixmap("general_xpm")));
   itemsList->item(1)->setIcon(QIcon(":/MantidPlot_Icon_32offset.png"));
@@ -1968,20 +1970,21 @@ void ConfigDialog::languageChange()
   itemsList->item(4)->setIcon(QIcon(getQPixmap("logo_xpm")));
   itemsList->item(5)->setIcon(QIcon(getQPixmap("fit_xpm")));
   itemsList->item(6)->setIcon(QIcon(":/mdPlotting32x32.png"));
-  itemsList->setIconSize(QSize(32,32));
+  itemsList->setIconSize(QSize(32, 32));
   // calculate a sensible width for the items list
   // (default QListWidget size is 256 which looks too big)
   QFontMetrics fm(itemsList->font());
-  int width = 32,i;
-  for(i=0 ; i<itemsList->count() ; i++)
-    if( fm.width(itemsList->item(i)->text()) > width)
+  int width = 32, i;
+  for (i = 0; i < itemsList->count(); i++)
+    if (fm.width(itemsList->item(i)->text()) > width)
       width = fm.width(itemsList->item(i)->text());
-  itemsList->setMaximumWidth( itemsList->iconSize().width() + width + 50 );
+  itemsList->setMaximumWidth(itemsList->iconSize().width() + width + 50);
   // resize the list to the maximum width
-  itemsList->resize(itemsList->maximumWidth(),itemsList->height());
+  itemsList->resize(itemsList->maximumWidth(), itemsList->height());
 
-  //plots 2D page
-  plotsTabWidget->setTabText(plotsTabWidget->indexOf(plotOptions), tr("Options"));
+  // plots 2D page
+  plotsTabWidget->setTabText(plotsTabWidget->indexOf(plotOptions),
+                             tr("Options"));
   plotsTabWidget->setTabText(plotsTabWidget->indexOf(axesPage), tr("Axes"));
   plotsTabWidget->setTabText(plotsTabWidget->indexOf(curves), tr("Curves"));
   plotsTabWidget->setTabText(plotsTabWidget->indexOf(plotTicks), tr("Ticks"));
@@ -1991,20 +1994,21 @@ void ConfigDialog::languageChange()
   boxLabelsEditing->setText(tr("&Disable in-place editing"));
   lblMinTicksLength->setText(tr("Length"));
 
-  lblMajTicksLength->setText(tr("Length" ));
-  lblMajTicks->setText(tr("Major Ticks" ));
-  lblMinTicks->setText(tr("Minor Ticks" ));
+  lblMajTicksLength->setText(tr("Length"));
+  lblMajTicks->setText(tr("Major Ticks"));
+  lblMinTicks->setText(tr("Minor Ticks"));
 
-  lblMargin->setText(tr("Margin" ));
-  labelGraphAxesLabelsDist->setText(tr("Axes title space" ));
-  labelTickLabelsDist->setText(tr("Ticks - Labels space" ));
+  lblMargin->setText(tr("Margin"));
+  labelGraphAxesLabelsDist->setText(tr("Axes title space"));
+  labelTickLabelsDist->setText(tr("Ticks - Labels space"));
   boxAxesLabelsDist->setSuffix(" " + tr("pixels"));
   boxTickLabelsDist->setSuffix(" " + tr("pixels"));
-  labelFrameWidth->setText(tr("Frame width" ));
+  labelFrameWidth->setText(tr("Frame width"));
 
   boxFrame->setText(tr("Canvas Fra&me"));
   boxDistribution->setText(tr("Normalize histogram to bin width"));
-  boxDistribution->setToolTip(tr("If checked, plot all spectra graphs normalised to the bin widths"));
+  boxDistribution->setToolTip(
+      tr("If checked, plot all spectra graphs normalised to the bin widths"));
   boxTitle->setText(tr("Show &Title"));
   boxScaleFonts->setText(tr("Scale &Fonts"));
   boxAutoscaling->setText(tr("Auto&scaling"));
@@ -2014,16 +2018,16 @@ void ConfigDialog::languageChange()
   // axes page
   boxBackbones->setText(tr("Axes &backbones"));
   boxSynchronizeScales->setText(tr("Synchronize scale &divisions"));
-  lblAxesLineWidth->setText(tr("Axes linewidth" ));
+  lblAxesLineWidth->setText(tr("Axes linewidth"));
 
   yLeftLabel->setText(tr("Left"));
   yRightLabel->setText(tr("Right / color map"));
   xBottomLabel->setText(tr("Bottom"));
   xTopLabel->setText(tr("Top"));
 
-  enabledAxesGroupBox->setTitle(tr("Enabled axes" ));
-  enableAxisLabel->setText(tr( "Show" ));
-  showNumbersLabel->setText(tr( "Labels" ));
+  enabledAxesGroupBox->setTitle(tr("Enabled axes"));
+  enableAxisLabel->setText(tr("Show"));
+  showNumbersLabel->setText(tr("Labels"));
   scaleLabel->setText("Scale");
 
   boxMajTicks->clear();
@@ -2045,7 +2049,7 @@ void ConfigDialog::languageChange()
   boxPrintCropmarks->setText(tr("Print Crop&marks"));
   boxScaleLayersOnPrint->setText(tr("&Scale layers to paper size"));
 
-  //confirmations page
+  // confirmations page
   groupBoxConfirm->setTitle(tr("Prompt on closing"));
   boxFolders->setText(tr("Folders"));
   boxTables->setText(tr("Tables"));
@@ -2055,27 +2059,33 @@ void ConfigDialog::languageChange()
   boxNotes->setText(tr("&Notes"));
   boxInstrWindow->setText(tr("&Instrument Window"));
 
-  buttonOk->setText( tr( "&OK" ) );
-  buttonCancel->setText( tr( "&Cancel" ) );
-  buttonApply->setText( tr( "&Apply" ) );
-  buttonTextFont->setText( tr( "&Text Font" ) );
-  buttonHeaderFont->setText( tr( "&Labels Font" ) );
-  buttonAxesFont->setText( tr( "A&xes Labels" ) );
-  buttonNumbersFont->setText( tr( "Axes &Numbers" ) );
-  buttonLegendFont->setText( tr( "&Legend" ) );
-  buttonTitleFont->setText( tr( "T&itle" ) );
-  boxPromptDeleteWorkspace->setText( tr( "Prompt when deleting Workspaces" ) );
-  boxPromptRenameTables->setText( tr( "Prompt on &renaming tables when appending projects" ) );
-  //application page
-  appTabWidget->setTabText(appTabWidget->indexOf(application), tr("Application"));
+  buttonOk->setText(tr("&OK"));
+  buttonCancel->setText(tr("&Cancel"));
+  buttonApply->setText(tr("&Apply"));
+  buttonTextFont->setText(tr("&Text Font"));
+  buttonHeaderFont->setText(tr("&Labels Font"));
+  buttonAxesFont->setText(tr("A&xes Labels"));
+  buttonNumbersFont->setText(tr("Axes &Numbers"));
+  buttonLegendFont->setText(tr("&Legend"));
+  buttonTitleFont->setText(tr("T&itle"));
+  boxPromptDeleteWorkspace->setText(tr("Prompt when deleting Workspaces"));
+  boxPromptRenameTables->setText(
+      tr("Prompt on &renaming tables when appending projects"));
+  // application page
+  appTabWidget->setTabText(appTabWidget->indexOf(application),
+                           tr("Application"));
   appTabWidget->setTabText(appTabWidget->indexOf(confirm), tr("Confirmations"));
   appTabWidget->setTabText(appTabWidget->indexOf(appColors), tr("Colors"));
-  appTabWidget->setTabText(appTabWidget->indexOf(numericFormatPage), tr("Numeric Format"));
-  appTabWidget->setTabText(appTabWidget->indexOf(fileLocationsPage), tr("File Locations"));
-  appTabWidget->setTabText(appTabWidget->indexOf(floatingWindowsPage), tr("Floating windows"));
+  appTabWidget->setTabText(appTabWidget->indexOf(numericFormatPage),
+                           tr("Numeric Format"));
+  appTabWidget->setTabText(appTabWidget->indexOf(fileLocationsPage),
+                           tr("File Locations"));
+  appTabWidget->setTabText(appTabWidget->indexOf(floatingWindowsPage),
+                           tr("Floating windows"));
 
-  //Mantid Page
-  mtdTabWidget->setTabText(mtdTabWidget->indexOf(instrumentPage), tr("Instrument"));
+  // Mantid Page
+  mtdTabWidget->setTabText(mtdTabWidget->indexOf(instrumentPage),
+                           tr("Instrument"));
 
   lblLanguage->setText(tr("Language"));
   lblStyle->setText(tr("Style"));
@@ -2124,7 +2134,7 @@ void ConfigDialog::languageChange()
   // 	lblPythonConfigDir->setText(tr("Python Configuration Files"));
   // #endif
 
-  //tables page
+  // tables page
   boxUpdateTableValues->setText(tr("Automatically &Recalculate Column Values"));
   boxTableComments->setText(tr("&Display Comments in Header"));
   groupBoxTableCol->setTitle(tr("Colors"));
@@ -2140,27 +2150,28 @@ void ConfigDialog::languageChange()
   boxSeparator->addItem(",");
   setColumnSeparator(app->columnSeparator);
 
-  lblTableBackground->setText(tr( "Background" ));
-  lblTextColor->setText(tr( "Text" ));
+  lblTableBackground->setText(tr("Background"));
+  lblTextColor->setText(tr("Text"));
   lblHeaderColor->setText(tr("Labels"));
   groupBoxTableFonts->setTitle(tr("Fonts"));
 
-  //curves page
-  lblCurveStyle->setText(tr( "Default curve style" ));
-  lblLineWidth->setText(tr( "Line width" ));
-  lblSymbSize->setText(tr( "Symbol size" ));
+  // curves page
+  lblCurveStyle->setText(tr("Default curve style"));
+  lblLineWidth->setText(tr("Line width"));
+  lblSymbSize->setText(tr("Symbol size"));
 
   boxCurveStyle->clear();
-  boxCurveStyle->addItem( getQPixmap("lPlot_xpm"), tr( " Line" ) );
-  boxCurveStyle->addItem( getQPixmap("pPlot_xpm"), tr( " Scatter" ) );
-  boxCurveStyle->addItem( getQPixmap("lpPlot_xpm"), tr( " Line + Symbol" ) );
-  boxCurveStyle->addItem( getQPixmap("dropLines_xpm"), tr( " Vertical drop lines" ) );
-  boxCurveStyle->addItem( getQPixmap("spline_xpm"), tr( " Spline" ) );
-  boxCurveStyle->addItem( getQPixmap("hor_steps_xpm"), tr( " Horizontal steps" ) );
-  boxCurveStyle->addItem( getQPixmap("vert_steps_xpm"), tr( " Vertical steps" ) );
-  boxCurveStyle->addItem( getQPixmap("area_xpm"), tr( " Area" ) );
-  boxCurveStyle->addItem( getQPixmap("vertBars_xpm"), tr( " Vertical Bars" ) );
-  boxCurveStyle->addItem( getQPixmap("hBars_xpm"), tr( " Horizontal Bars" ) );
+  boxCurveStyle->addItem(getQPixmap("lPlot_xpm"), tr(" Line"));
+  boxCurveStyle->addItem(getQPixmap("pPlot_xpm"), tr(" Scatter"));
+  boxCurveStyle->addItem(getQPixmap("lpPlot_xpm"), tr(" Line + Symbol"));
+  boxCurveStyle->addItem(getQPixmap("dropLines_xpm"),
+                         tr(" Vertical drop lines"));
+  boxCurveStyle->addItem(getQPixmap("spline_xpm"), tr(" Spline"));
+  boxCurveStyle->addItem(getQPixmap("hor_steps_xpm"), tr(" Horizontal steps"));
+  boxCurveStyle->addItem(getQPixmap("vert_steps_xpm"), tr(" Vertical steps"));
+  boxCurveStyle->addItem(getQPixmap("area_xpm"), tr(" Area"));
+  boxCurveStyle->addItem(getQPixmap("vertBars_xpm"), tr(" Vertical Bars"));
+  boxCurveStyle->addItem(getQPixmap("hBars_xpm"), tr(" Horizontal Bars"));
 
   int style = app->defaultCurveStyle;
   if (style == Graph::Line)
@@ -2184,92 +2195,106 @@ void ConfigDialog::languageChange()
   else if (style == Graph::HorizontalBars)
     boxCurveStyle->setCurrentIndex(9);
 
-  //plots 3D
+  // plots 3D
   lblResolution->setText(tr("Resolution"));
-  boxResolution->setSpecialValueText( "1 " + tr("(all data shown)") );
-  boxShowLegend->setText(tr( "&Show Legend" ));
-  boxShowProjection->setText(tr( "Show &Projection" ));
-  btnFromColor->setText( tr( "&Data Max" ) );
-  boxSmoothMesh->setText(tr( "Smoot&h Line" ));
-  boxOrthogonal->setText(tr( "O&rthogonal" ));
-  btnLabels->setText( tr( "Lab&els" ) );
-  btnMesh->setText( tr( "Mesh &Line" ) );
-  btnGrid->setText( tr( "&Grid" ) );
-  btnToColor->setText( tr( "Data &Min" ) );
-  btnNumbers->setText( tr( "&Numbers" ) );
-  btnAxes->setText( tr( "A&xes" ) );
-  btnBackground3D->setText( tr( "&Background" ) );
-  groupBox3DCol->setTitle(tr("Colors" ));
-  groupBox3DFonts->setTitle(tr("Fonts" ));
-  btnTitleFnt->setText( tr( "&Title" ) );
-  btnLabelsFnt->setText( tr( "&Axes Labels" ) );
-  btnNumFnt->setText( tr( "&Numbers" ) );
-  boxAutoscale3DPlots->setText( tr( "Autosca&ling" ) );
-
-  //Fitting page
+  boxResolution->setSpecialValueText("1 " + tr("(all data shown)"));
+  boxShowLegend->setText(tr("&Show Legend"));
+  boxShowProjection->setText(tr("Show &Projection"));
+  btnFromColor->setText(tr("&Data Max"));
+  boxSmoothMesh->setText(tr("Smoot&h Line"));
+  boxOrthogonal->setText(tr("O&rthogonal"));
+  btnLabels->setText(tr("Lab&els"));
+  btnMesh->setText(tr("Mesh &Line"));
+  btnGrid->setText(tr("&Grid"));
+  btnToColor->setText(tr("Data &Min"));
+  btnNumbers->setText(tr("&Numbers"));
+  btnAxes->setText(tr("A&xes"));
+  btnBackground3D->setText(tr("&Background"));
+  groupBox3DCol->setTitle(tr("Colors"));
+  groupBox3DFonts->setTitle(tr("Fonts"));
+  btnTitleFnt->setText(tr("&Title"));
+  btnLabelsFnt->setText(tr("&Axes Labels"));
+  btnNumFnt->setText(tr("&Numbers"));
+  boxAutoscale3DPlots->setText(tr("Autosca&ling"));
+
+  // Fitting page
   cbEnableQtiPlotFitting->setText(tr("Enable QtiPlot fitting"));
-  cbEnableQtiPlotFitting->setToolTip(tr("Takes effect after reopening a plot window"));
+  cbEnableQtiPlotFitting->setToolTip(
+      tr("Takes effect after reopening a plot window"));
   groupBoxFittingCurve->setTitle(tr("Generated Fit Curve"));
   generatePointsBtn->setText(tr("Uniform X Function"));
-  lblPoints->setText( tr("Points") );
-  samePointsBtn->setText( tr( "Same X as Fitting Data" ) );
-  linearFit2PointsBox->setText( tr( "2 points for linear fits" ) );
+  lblPoints->setText(tr("Points"));
+  samePointsBtn->setText(tr("Same X as Fitting Data"));
+  linearFit2PointsBox->setText(tr("2 points for linear fits"));
   groupBoxMultiPeak->setTitle(tr("Display Peak Curves for Multi-peak Fits"));
   groupBoxFitParameters->setTitle(tr("Parameters Output"));
   lblPrecision->setText(tr("Significant Digits"));
   logBox->setText(tr("Write Parameters to Result Log"));
   plotLabelBox->setText(tr("Paste Parameters to Plot"));
-  plotLabelBox->setToolTip(tr("Adds a text box to the plot with details of fitting parameters"));
+  plotLabelBox->setToolTip(
+      tr("Adds a text box to the plot with details of fitting parameters"));
   scaleErrorsBox->setText(tr("Scale Errors with sqrt(Chi^2/doF)"));
   groupBoxMultiPeak->setTitle(tr("Display Peak Curves for Multi-peak Fits"));
   lblPeaksColor->setText(tr("Peaks Color"));
 
   // MDPlotting change
-  mdPlottingTabWidget->setTabText(mdPlottingTabWidget->indexOf(vsiPage), tr("VSI"));
-  mdPlottingTabWidget->setTabText(mdPlottingTabWidget->indexOf(mdPlottingGeneralPage), tr("General"));
+  mdPlottingTabWidget->setTabText(mdPlottingTabWidget->indexOf(vsiPage),
+                                  tr("VSI"));
+  mdPlottingTabWidget->setTabText(
+      mdPlottingTabWidget->indexOf(mdPlottingGeneralPage), tr("General"));
 
   // Vsi background color
-  QString vsiDefaultBackgroundToolTipText = "Sets the default background color when a new instance of the VSI is opened.";
+  QString vsiDefaultBackgroundToolTipText = "Sets the default background color "
+                                            "when a new instance of the VSI is "
+                                            "opened.";
   vsiDefaultBackground->setToolTip(vsiDefaultBackgroundToolTipText);
   lblVsiDefaultBackground->setToolTip(vsiDefaultBackgroundToolTipText);
   lblVsiDefaultBackground->setText(tr("Background color"));
 
   // Vsi initial view
-  QString vsiInitialViewToolTipText = "Sets the initial view when loading a new source into the VSI.";
+  QString vsiInitialViewToolTipText =
+      "Sets the initial view when loading a new source into the VSI.";
   lblVsiInitialView->setText(tr("Initial view"));
   vsiInitialView->setToolTip(vsiInitialViewToolTipText);
   lblVsiInitialView->setToolTip(vsiInitialViewToolTipText);
 
   // VSI master default
-  QString vsiMasterDefaultToolTipText = "User master defaults for the color map and the background color. If not checked the settings of the last session are used.";
-  mdPlottingVsiFrameBottom->setTitle(tr("Use defaults for color map and background color"));
+  QString vsiMasterDefaultToolTipText =
+      "User master defaults for the color map and the background color. If not "
+      "checked the settings of the last session are used.";
+  mdPlottingVsiFrameBottom->setTitle(
+      tr("Use defaults for color map and background color"));
   mdPlottingVsiFrameBottom->setToolTip(vsiMasterDefaultToolTipText);
 
   // Vsi default color map
-  QString vsiDefaultColorMapToolTipText = "Sets the default color map when a new instance of the VSI is opened.";
+  QString vsiDefaultColorMapToolTipText =
+      "Sets the default color map when a new instance of the VSI is opened.";
   vsiDefaultColorMap->setToolTip(vsiDefaultColorMapToolTipText);
   lblVsiDefaultColorMap->setToolTip(vsiDefaultColorMapToolTipText);
   lblVsiDefaultColorMap->setText(tr("Default color map"));
 
   // General plotting tab
-  QString vsiGeneralDefaultColorMapToolTipText = "Sets the default color map for both the Slice Viewer and the VSI.";
+  QString vsiGeneralDefaultColorMapToolTipText =
+      "Sets the default color map for both the Slice Viewer and the VSI.";
   mdPlottingGeneralColorMap->setToolTip(vsiGeneralDefaultColorMapToolTipText);
   lblGeneralDefaultColorMap->setToolTip(vsiGeneralDefaultColorMapToolTipText);
   lblGeneralDefaultColorMap->setText(tr("Default color map"));
 
-  mdPlottingGeneralFrame->setTitle("Use same default color map for Slice Viewer and VSI");
-  mdPlottingGeneralFrame->setToolTip("The specifed color map will be available for the Slice Viewer and the VSI when a new instance of either is started.");
+  mdPlottingGeneralFrame->setTitle(
+      "Use same default color map for Slice Viewer and VSI");
+  mdPlottingGeneralFrame->setToolTip("The specifed color map will be available "
+                                     "for the Slice Viewer and the VSI when a "
+                                     "new instance of either is started.");
 }
 
-void ConfigDialog::accept()
-{
+void ConfigDialog::accept() {
   apply();
   close();
 }
 
-void ConfigDialog::apply()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::apply() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app)
     return;
 
@@ -2280,23 +2305,25 @@ void ConfigDialog::apply()
   sep.replace(tr("SPACE"), " ");
   sep.replace("\\s", " ");
 
-  if (sep.contains(QRegExp("[0-9.eE+-]"))!=0){
+  if (sep.contains(QRegExp("[0-9.eE+-]")) != 0) {
     QMessageBox::warning(0, tr("MantidPlot - Import options error"),
-      tr("The separator must not contain the following characters: 0-9eE.+-"));
+                         tr("The separator must not contain the following "
+                            "characters: 0-9eE.+-"));
     return;
   }
 
   app->columnSeparator = sep;
   app->setAutoUpdateTableValues(boxUpdateTableValues->isChecked());
   app->customizeTables(buttonBackground->color(), buttonText->color(),
-    buttonHeader->color(), textFont, headerFont, boxTableComments->isChecked());
+                       buttonHeader->color(), textFont, headerFont,
+                       boxTableComments->isChecked());
   // 2D plots page: options tab
   app->d_in_place_editing = !boxLabelsEditing->isChecked();
-  app->titleOn=boxTitle->isChecked();
+  app->titleOn = boxTitle->isChecked();
   app->autoDistribution1D = boxDistribution->isChecked();
   // Sync with config service
-  ConfigService::Instance().setString("graph1d.autodistribution",
-                                      boxDistribution->isChecked() ? "On" : "Off");
+  ConfigService::Instance().setString(
+      "graph1d.autodistribution", boxDistribution->isChecked() ? "On" : "Off");
   if (boxFrame->isChecked())
     app->canvasFrameWidth = boxFrameWidth->value();
   else
@@ -2305,18 +2332,19 @@ void ConfigDialog::apply()
   app->defaultPlotMargin = boxMargin->value();
   app->d_graph_axes_labels_dist = boxAxesLabelsDist->value();
   app->d_graph_tick_labels_dist = boxTickLabelsDist->value();
-  app->setGraphDefaultSettings(boxAutoscaling->isChecked(),boxScaleFonts->isChecked(),
-    boxResize->isChecked(), boxAntialiasing->isChecked(), boxAspectRatio->isChecked());
+  app->setGraphDefaultSettings(
+      boxAutoscaling->isChecked(), boxScaleFonts->isChecked(),
+      boxResize->isChecked(), boxAntialiasing->isChecked(),
+      boxAspectRatio->isChecked());
 
   // 2D plots page: axes tab
   if (generalDialog->currentWidget() == plotsTabWidget &&
-        plotsTabWidget->currentWidget() == axesPage )
-  {
+      plotsTabWidget->currentWidget() == axesPage) {
     app->drawBackbones = boxBackbones->isChecked();
     app->axesLineWidth = boxLineWidth->value();
     app->d_synchronize_graph_scales = boxSynchronizeScales->isChecked();
 
-    for (int i = 0; i < QwtPlot::axisCnt; i++){
+    for (int i = 0; i < QwtPlot::axisCnt; i++) {
       int row = i + 1;
       QLayoutItem *item = enabledAxesGrid->itemAtPosition(row, 2);
       QCheckBox *box = qobject_cast<QCheckBox *>(item->widget());
@@ -2335,7 +2363,7 @@ void ConfigDialog::apply()
   // 2D plots page: curves tab
   app->defaultCurveStyle = curveStyle();
   app->defaultCurveLineWidth = boxCurveLineWidth->value();
-  app->defaultSymbolSize = 2*boxSymbolSize->value() + 1;
+  app->defaultSymbolSize = 2 * boxSymbolSize->value() + 1;
   app->applyCurveStyleToMantid = cbApplyToMantid->isChecked();
   app->drawAllErrors = cbDrawAllErrors->isChecked();
   // 2D plots page: ticks tab
@@ -2344,17 +2372,17 @@ void ConfigDialog::apply()
   app->majTicksStyle = boxMajTicks->currentIndex();
   app->minTicksStyle = boxMinTicks->currentIndex();
   // 2D plots page: fonts tab
-  app->plotAxesFont=axesFont;
-  app->plotNumbersFont=numbersFont;
-  app->plotLegendFont=legendFont;
-  app->plotTitleFont=titleFont;
+  app->plotAxesFont = axesFont;
+  app->plotNumbersFont = numbersFont;
+  app->plotLegendFont = legendFont;
+  app->plotTitleFont = titleFont;
   // 2D plots page: print tab
   app->d_print_cropmarks = boxPrintCropmarks->isChecked();
   app->d_scale_plots_on_print = boxScaleLayersOnPrint->isChecked();
-  QList<MdiSubWindow*> windows = app->windowsList();
-  foreach(MdiSubWindow *w, windows){
+  QList<MdiSubWindow *> windows = app->windowsList();
+  foreach (MdiSubWindow *w, windows) {
     if (std::string(w->metaObject()->className()) == "MultiLayer") {
-      MultiLayer* multiLayer = dynamic_cast<MultiLayer*>(w);
+      MultiLayer *multiLayer = dynamic_cast<MultiLayer *>(w);
       if (multiLayer) {
         multiLayer->setScaleLayersOnPrint(boxScaleLayersOnPrint->isChecked());
         multiLayer->printCropmarks(boxPrintCropmarks->isChecked());
@@ -2369,14 +2397,15 @@ void ConfigDialog::apply()
   app->setSaveSettings(boxSave->isChecked(), boxMinutes->value());
   app->d_backup_files = boxBackupProject->isChecked();
   app->defaultScriptingLang = boxScriptingLanguage->currentText();
-  app->d_init_window_type = (ApplicationWindow::WindowType)boxInitWindow->currentIndex();
+  app->d_init_window_type =
+      (ApplicationWindow::WindowType)boxInitWindow->currentIndex();
   app->setMatrixUndoStackSize(undoStackSizeBox->value());
   app->d_eol = (ApplicationWindow::EndLineChar)boxEndLine->currentIndex();
 
   // general page: numeric format tab
   app->d_decimal_digits = boxAppPrecision->value();
   QLocale locale;
-  switch (boxDecimalSeparator->currentIndex()){
+  switch (boxDecimalSeparator->currentIndex()) {
   case 0:
     locale = QLocale::system();
     break;
@@ -2397,43 +2426,56 @@ void ConfigDialog::apply()
   app->setLocale(locale);
 
   if (generalDialog->currentWidget() == appTabWidget &&
-    appTabWidget->currentWidget() == numericFormatPage &&
-    boxUpdateSeparators->isChecked()){
-      QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-      QList<MdiSubWindow *> windows = app->windowsList();
-      foreach(MdiSubWindow *w, windows){
-        w->setLocale(locale);
-        if(auto table = dynamic_cast<Table *>(w))
-          table->updateDecimalSeparators();
-        else if(auto matrix = dynamic_cast<Matrix *>(w))
-          matrix->resetView();
-      }
-      app->modifiedProject();
-      QApplication::restoreOverrideCursor();
+      appTabWidget->currentWidget() == numericFormatPage &&
+      boxUpdateSeparators->isChecked()) {
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    QList<MdiSubWindow *> windows = app->windowsList();
+    foreach (MdiSubWindow *w, windows) {
+      w->setLocale(locale);
+      if (auto table = dynamic_cast<Table *>(w))
+        table->updateDecimalSeparators();
+      else if (auto matrix = dynamic_cast<Matrix *>(w))
+        matrix->resetView();
+    }
+    app->modifiedProject();
+    QApplication::restoreOverrideCursor();
   }
   // general page: confirmations tab
   app->d_inform_delete_workspace = boxPromptDeleteWorkspace->isChecked();
   app->d_inform_rename_table = boxPromptRenameTables->isChecked();
   app->confirmCloseFolder = boxFolders->isChecked();
   app->updateConfirmOptions(boxTables->isChecked(), boxMatrices->isChecked(),
-    boxPlots2D->isChecked(), boxPlots3D->isChecked(),
-    boxNotes->isChecked(),boxInstrWindow->isChecked());
+                            boxPlots2D->isChecked(), boxPlots3D->isChecked(),
+                            boxNotes->isChecked(), boxInstrWindow->isChecked());
   // general page: colors tab
-  app->setAppColors(btnWorkspace->color(), btnPanels->color(), btnPanelsText->color());
+  app->setAppColors(btnWorkspace->color(), btnPanels->color(),
+                    btnPanelsText->color());
   // general page: floating windows tab
-  app->settings.setValue("/General/FloatingWindows/MultiLayer",boxFloatingGraph->isChecked());
-  app->settings.setValue("/General/FloatingWindows/Table",boxFloatingTable->isChecked());
-  app->settings.setValue("/General/FloatingWindows/MantidTable",boxFloatingTable->isChecked());
-  app->settings.setValue("/General/FloatingWindows/InstrumentWindow",boxFloatingInstrumentWindow->isChecked());
-  app->settings.setValue("/General/FloatingWindows/MantidMatrix",boxFloatingMantidMatrix->isChecked());
-  app->settings.setValue("/General/FloatingWindows/Note",boxFloatingNote->isChecked());
-  app->settings.setValue("/General/FloatingWindows/Matrix",boxFloatingMatrix->isChecked());
-  app->settings.setValue("/General/FloatingWindows/MdiSubWindow",boxFloatingCustomInterfaces->isChecked());
-  app->settings.setValue("/General/FloatingWindows/TiledWindow",boxFloatingTiledWindows->isChecked());
+  app->settings.setValue("/General/FloatingWindows/MultiLayer",
+                         boxFloatingGraph->isChecked());
+  app->settings.setValue("/General/FloatingWindows/Table",
+                         boxFloatingTable->isChecked());
+  app->settings.setValue("/General/FloatingWindows/MantidTable",
+                         boxFloatingTable->isChecked());
+  app->settings.setValue("/General/FloatingWindows/InstrumentWindow",
+                         boxFloatingInstrumentWindow->isChecked());
+  app->settings.setValue("/General/FloatingWindows/MantidMatrix",
+                         boxFloatingMantidMatrix->isChecked());
+  app->settings.setValue("/General/FloatingWindows/Note",
+                         boxFloatingNote->isChecked());
+  app->settings.setValue("/General/FloatingWindows/Matrix",
+                         boxFloatingMatrix->isChecked());
+  app->settings.setValue("/General/FloatingWindows/MdiSubWindow",
+                         boxFloatingCustomInterfaces->isChecked());
+  app->settings.setValue("/General/FloatingWindows/TiledWindow",
+                         boxFloatingTiledWindows->isChecked());
   // 3D plots page
-  QStringList plot3DColors = QStringList() << btnToColor->color().name() << btnLabels->color().name();
-  plot3DColors << btnMesh->color().name() << btnGrid->color().name() << btnFromColor->color().name();
-  plot3DColors << btnNumbers->color().name() << btnAxes->color().name() << btnBackground3D->color().name();
+  QStringList plot3DColors = QStringList() << btnToColor->color().name()
+                                           << btnLabels->color().name();
+  plot3DColors << btnMesh->color().name() << btnGrid->color().name()
+               << btnFromColor->color().name();
+  plot3DColors << btnNumbers->color().name() << btnAxes->color().name()
+               << btnBackground3D->color().name();
   app->plot3DColors = plot3DColors;
 
   app->showPlot3DLegend = boxShowLegend->isChecked();
@@ -2464,216 +2506,210 @@ void ConfigDialog::apply()
   // (default QListWidget size is 256 which looks too big)
   QFontMetrics fm(itemsList->font());
   int width = 32;
-  for(int i=0; i<itemsList->count(); i++)
-    if( fm.width(itemsList->item(i)->text()) > width)
+  for (int i = 0; i < itemsList->count(); i++)
+    if (fm.width(itemsList->item(i)->text()) > width)
       width = fm.width(itemsList->item(i)->text());
-  itemsList->setMaximumWidth( itemsList->iconSize().width() + width + 50 );
+  itemsList->setMaximumWidth(itemsList->iconSize().width() + width + 50);
   // resize the list to the maximum width
-  itemsList->resize(itemsList->maximumWidth(),itemsList->height());
-
-  //Mantid
-  Mantid::Kernel::ConfigServiceImpl&  cfgSvc = Mantid::Kernel::ConfigService::Instance();
-
-   cfgSvc.setString("default.facility", facility->currentText().toStdString());
-   cfgSvc.setString("default.instrument", defInstr->currentText().toStdString());
-   cfgSvc.setString("paraview.ignore", QString::number(ckIgnoreParaView->isChecked()).toStdString());
-   if (ckQconvention->isChecked())
-     cfgSvc.setString("Q.convention", "Crystallography");
-   else
-     cfgSvc.setString("Q.convention", "Inelastic");
-
+  itemsList->resize(itemsList->maximumWidth(), itemsList->height());
+
+  // Mantid
+  Mantid::Kernel::ConfigServiceImpl &cfgSvc =
+      Mantid::Kernel::ConfigService::Instance();
+
+  cfgSvc.setString("default.facility", facility->currentText().toStdString());
+  cfgSvc.setString("default.instrument", defInstr->currentText().toStdString());
+  cfgSvc.setString(
+      "paraview.ignore",
+      QString::number(ckIgnoreParaView->isChecked()).toStdString());
+  if (ckQconvention->isChecked())
+    cfgSvc.setString("Q.convention", "Crystallography");
+  else
+    cfgSvc.setString("Q.convention", "Inelastic");
 
   updateDirSearchSettings();
   updateCurveFitSettings();
   updateMantidOptionsTab();
   updateSendToTab();
 
-  try
-  {
-     cfgSvc.saveConfig( cfgSvc.getUserFilename());
-  }
-  catch(std::runtime_error&)
-  {
+  try {
+    cfgSvc.saveConfig(cfgSvc.getUserFilename());
+  } catch (std::runtime_error &) {
     QMessageBox::warning(this, "MantidPlot",
-      "Unable to update Mantid user properties file.\n"
-      "Configuration will not be saved.");
+                         "Unable to update Mantid user properties file.\n"
+                         "Configuration will not be saved.");
   }
 
   // MD Plotting
- updateMdPlottingSettings();
+  updateMdPlottingSettings();
 }
 
 /**
  * Update the MD Plotting settings
  */
-void ConfigDialog::updateMdPlottingSettings()
-{
+void ConfigDialog::updateMdPlottingSettings() {
   //////// GENERAL TAB
 
   // Read the common color map check box
-  if (mdPlottingGeneralFrame->isChecked())
-  {
+  if (mdPlottingGeneralFrame->isChecked()) {
     m_mdSettings.setUsageGeneralMdColorMap(true);
-  }
-  else
-  {
+  } else {
     m_mdSettings.setUsageGeneralMdColorMap(false);
   }
 
-  if (mdPlottingGeneralColorMap)
-  {
-    QString generalTabColorMapName  = mdPlottingGeneralColorMap->currentText();
-    QString generalTabColorMapFile = mdPlottingGeneralColorMap->itemData(mdPlottingGeneralColorMap->currentIndex()).toString();
+  if (mdPlottingGeneralColorMap) {
+    QString generalTabColorMapName = mdPlottingGeneralColorMap->currentText();
+    QString generalTabColorMapFile =
+        mdPlottingGeneralColorMap->itemData(mdPlottingGeneralColorMap
+                                                ->currentIndex()).toString();
 
-    m_mdSettings.setGeneralMdColorMap(generalTabColorMapName, generalTabColorMapFile);
+    m_mdSettings.setGeneralMdColorMap(generalTabColorMapName,
+                                      generalTabColorMapFile);
   }
 
   ///// VSI TAB
 
   // Read the Vsi color map
-  if (vsiDefaultColorMap)
-  {
+  if (vsiDefaultColorMap) {
     m_mdSettings.setUserSettingColorMap(vsiDefaultColorMap->currentText());
   }
 
-  // Read if the usage of the last color map and background color should be performed
-  if (mdPlottingVsiFrameBottom->isChecked())
-  {
+  // Read if the usage of the last color map and background color should be
+  // performed
+  if (mdPlottingVsiFrameBottom->isChecked()) {
     m_mdSettings.setUsageLastSession(false);
-  }
-  else
-  {
+  } else {
     m_mdSettings.setUsageLastSession(true);
   }
 
   // Read the background selection
-  if (vsiDefaultBackground)
-  {
+  if (vsiDefaultBackground) {
     m_mdSettings.setUserSettingBackgroundColor(vsiDefaultBackground->color());
   }
 
   // Read the initial view selection
-  if (vsiInitialView)
-  {
+  if (vsiInitialView) {
     m_mdSettings.setUserSettingIntialView(vsiInitialView->currentText());
   }
 }
 
-void ConfigDialog::updateDirSearchSettings()
-{
-  Mantid::Kernel::ConfigServiceImpl&  cfgSvc = Mantid::Kernel::ConfigService::Instance();
+void ConfigDialog::updateDirSearchSettings() {
+  Mantid::Kernel::ConfigServiceImpl &cfgSvc =
+      Mantid::Kernel::ConfigService::Instance();
 
   QString setting = lePythonScriptsDirs->text();
-  setting.replace('\\','/');
-   cfgSvc.setString("pythonscripts.directories",setting.toStdString());
+  setting.replace('\\', '/');
+  cfgSvc.setString("pythonscripts.directories", setting.toStdString());
 
   setting = lePythonPluginsDirs->text();
-  setting.replace('\\','/');
-   cfgSvc.setString("user.python.plugins.directories",setting.toStdString());
+  setting.replace('\\', '/');
+  cfgSvc.setString("user.python.plugins.directories", setting.toStdString());
 
   setting = leInstrumentDir->text();
-  setting.replace('\\','/');
-   cfgSvc.setString("instrumentDefinition.directory",setting.toStdString());
-
+  setting.replace('\\', '/');
+  cfgSvc.setString("instrumentDefinition.directory", setting.toStdString());
 }
 
-void ConfigDialog::updateCurveFitSettings()
-{
-  Mantid::Kernel::ConfigServiceImpl&  cfgSvc = Mantid::Kernel::ConfigService::Instance();
+void ConfigDialog::updateCurveFitSettings() {
+  Mantid::Kernel::ConfigServiceImpl &cfgSvc =
+      Mantid::Kernel::ConfigService::Instance();
 
   // Form setting string from function name and parameters
   QString fname = backgroundFunctions->currentText();
   std::string setting = fname.toStdString();
-  //Ignore parameters for none
-  if( fname != "None" )
-  {
+  // Ignore parameters for none
+  if (fname != "None") {
     QString args = functionArguments->text();
     setting += std::string(" ") + args.toStdString();
   }
 
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app) {
-    throw std::logic_error("Parent of ConfigDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
 
   // cfgSvc.setString("curvefitting.autoBackground", setting);
-  app->mantidUI->fitFunctionBrowser()->setAutoBackgroundName(QString::fromStdString(setting));
+  app->mantidUI->fitFunctionBrowser()->setAutoBackgroundName(
+      QString::fromStdString(setting));
 
   setting = defaultPeakShape->currentText().toStdString();
   // cfgSvc.setString("curvefitting.defaultPeak", setting);
   app->mantidUI->fitFunctionBrowser()->setDefaultPeakType(setting);
 
   setting = QString::number(findPeaksFWHM->value()).toStdString();
-   cfgSvc.setString("curvefitting.findPeaksFWHM", setting);
+  cfgSvc.setString("curvefitting.findPeaksFWHM", setting);
 
   setting = QString::number(findPeaksTolerance->value()).toStdString();
-   cfgSvc.setString("curvefitting.findPeaksTolerance", setting);
+  cfgSvc.setString("curvefitting.findPeaksTolerance", setting);
 
   setting = QString::number(peakRadius->value()).toStdString();
-   cfgSvc.setString("curvefitting.peakRadius", setting);
+  cfgSvc.setString("curvefitting.peakRadius", setting);
 
   app->mantidUI->fitFunctionBrowser()->setDecimals(decimals->value());
 }
 
-void ConfigDialog::updateMantidOptionsTab()
-{
-  auto& cfgSvc = ConfigService::Instance();
+void ConfigDialog::updateMantidOptionsTab() {
+  auto &cfgSvc = ConfigService::Instance();
 
   // re-use plot instances (spectra, slice, color-fill, etc.)
-  QString reusePlotInst = m_reusePlotInstances->isChecked()? "On" : "Off";
-   cfgSvc.setString("MantidOptions.ReusePlotInstances",reusePlotInst.toStdString());
+  QString reusePlotInst = m_reusePlotInstances->isChecked() ? "On" : "Off";
+  cfgSvc.setString("MantidOptions.ReusePlotInstances",
+                   reusePlotInst.toStdString());
 
-  //invisible workspaces options
-  QString showinvisible_ws = m_invisibleWorkspaces->isChecked()? "1" : "0";
-   cfgSvc.setString("MantidOptions.InvisibleWorkspaces",showinvisible_ws.toStdString());
+  // invisible workspaces options
+  QString showinvisible_ws = m_invisibleWorkspaces->isChecked() ? "1" : "0";
+  cfgSvc.setString("MantidOptions.InvisibleWorkspaces",
+                   showinvisible_ws.toStdString());
 
-  //OpenGL option
+  // OpenGL option
   QString setting = m_useOpenGL->isChecked() ? "On" : "Off";
-   cfgSvc.setString("MantidOptions.InstrumentView.UseOpenGL",setting.toStdString());
+  cfgSvc.setString("MantidOptions.InstrumentView.UseOpenGL",
+                   setting.toStdString());
 
-  //Hidden categories
+  // Hidden categories
   QString hiddenCategories = buildHiddenCategoryString().join(";");
 
-  //store it if it has changed
+  // store it if it has changed
   std::string hiddenCategoryString = hiddenCategories.toStdString();
-  if (hiddenCategoryString !=  cfgSvc.getString("algorithms.categories.hidden"))
-  {
-     cfgSvc.setString("algorithms.categories.hidden",hiddenCategoryString);
+  if (hiddenCategoryString !=
+      cfgSvc.getString("algorithms.categories.hidden")) {
+    cfgSvc.setString("algorithms.categories.hidden", hiddenCategoryString);
 
-    //update the algorithm tree
-    if (ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget())) {
+    // update the algorithm tree
+    if (ApplicationWindow *app =
+            dynamic_cast<ApplicationWindow *>(this->parentWidget())) {
       app->mantidUI->updateAlgorithms();
     }
   }
 }
 
-QStringList ConfigDialog::buildHiddenCategoryString(QTreeWidgetItem *parent)
-{
+QStringList ConfigDialog::buildHiddenCategoryString(QTreeWidgetItem *parent) {
   QStringList results;
-  //how many children at this level
-  int count = parent ? parent->childCount() : treeCategories->topLevelItemCount();
+  // how many children at this level
+  int count =
+      parent ? parent->childCount() : treeCategories->topLevelItemCount();
 
-  for (int i = 0; i < count; i++)
-  {
-    //get the child
-    QTreeWidgetItem *item = parent ? parent->child(i) : treeCategories->topLevelItem(i);
+  for (int i = 0; i < count; i++) {
+    // get the child
+    QTreeWidgetItem *item =
+        parent ? parent->child(i) : treeCategories->topLevelItem(i);
 
-    if (item->checkState(0) == Qt::Unchecked)
-    {
+    if (item->checkState(0) == Qt::Unchecked) {
       results.append(item->text(0));
     }
 
     QStringList childResults = buildHiddenCategoryString(item);
-    for (QStringList::ConstIterator it = childResults.begin();it!=childResults.end();++it)
-    {
+    for (QStringList::ConstIterator it = childResults.begin();
+         it != childResults.end(); ++it) {
       results.append(item->text(0) + "\\" + *it);
     }
   }
   return results;
 }
 
-int ConfigDialog::curveStyle()
-{
+int ConfigDialog::curveStyle() {
   int style = 0;
   switch (boxCurveStyle->currentIndex()) {
   case 0:
@@ -2710,156 +2746,145 @@ int ConfigDialog::curveStyle()
   return style;
 }
 
-void ConfigDialog::pickTextFont()
-{
+void ConfigDialog::pickTextFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,textFont,this);
-  if ( ok ) {
+  QFont font = QFontDialog::getFont(&ok, textFont, this);
+  if (ok) {
     textFont = font;
   } else {
     return;
   }
 }
 
-void ConfigDialog::pickHeaderFont()
-{
+void ConfigDialog::pickHeaderFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,headerFont,this);
-  if ( ok ) {
+  QFont font = QFontDialog::getFont(&ok, headerFont, this);
+  if (ok) {
     headerFont = font;
   } else {
     return;
   }
 }
 
-void ConfigDialog::pickLegendFont()
-{
+void ConfigDialog::pickLegendFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,legendFont,this);
-  if ( ok ) {
+  QFont font = QFontDialog::getFont(&ok, legendFont, this);
+  if (ok) {
     legendFont = font;
   } else {
     return;
   }
 }
 
-void ConfigDialog::pickAxesFont()
-{
+void ConfigDialog::pickAxesFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,axesFont,this);
-  if ( ok ) {
+  QFont font = QFontDialog::getFont(&ok, axesFont, this);
+  if (ok) {
     axesFont = font;
   } else {
     return;
   }
 }
 
-void ConfigDialog::pickNumbersFont()
-{
+void ConfigDialog::pickNumbersFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,numbersFont,this);
-  if ( ok ) {
+  QFont font = QFontDialog::getFont(&ok, numbersFont, this);
+  if (ok) {
     numbersFont = font;
   } else {
     return;
   }
 }
 
-void ConfigDialog::pickTitleFont()
-{
+void ConfigDialog::pickTitleFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,titleFont,this);
-  if ( ok )
+  QFont font = QFontDialog::getFont(&ok, titleFont, this);
+  if (ok)
     titleFont = font;
   else
     return;
 }
 
-void ConfigDialog::pickApplicationFont()
-{
+void ConfigDialog::pickApplicationFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok,appFont,this);
-  if ( ok )
+  QFont font = QFontDialog::getFont(&ok, appFont, this);
+  if (ok)
     appFont = font;
   else
     return;
   fontsBtn->setFont(appFont);
 }
 
-void ConfigDialog::pick3DTitleFont()
-{
+void ConfigDialog::pick3DTitleFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok, plot3DTitleFont,this);
-  if ( ok )
+  QFont font = QFontDialog::getFont(&ok, plot3DTitleFont, this);
+  if (ok)
     plot3DTitleFont = font;
   else
     return;
 }
 
-void ConfigDialog::pick3DNumbersFont()
-{
+void ConfigDialog::pick3DNumbersFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok, plot3DNumbersFont,this);
-  if ( ok )
+  QFont font = QFontDialog::getFont(&ok, plot3DNumbersFont, this);
+  if (ok)
     plot3DNumbersFont = font;
   else
     return;
 }
 
-void ConfigDialog::pick3DAxesFont()
-{
+void ConfigDialog::pick3DAxesFont() {
   bool ok;
-  QFont font = QFontDialog::getFont(&ok, plot3DAxesFont,this);
-  if ( ok )
+  QFont font = QFontDialog::getFont(&ok, plot3DAxesFont, this);
+  if (ok)
     plot3DAxesFont = font;
   else
     return;
 }
 
-void ConfigDialog::setColumnSeparator(const QString& sep)
-{
-  if (sep=="\t")
+void ConfigDialog::setColumnSeparator(const QString &sep) {
+  if (sep == "\t")
     boxSeparator->setCurrentIndex(0);
-  else if (sep==" ")
+  else if (sep == " ")
     boxSeparator->setCurrentIndex(1);
-  else if (sep==";\t")
+  else if (sep == ";\t")
     boxSeparator->setCurrentIndex(2);
-  else if (sep==",\t")
+  else if (sep == ",\t")
     boxSeparator->setCurrentIndex(3);
-  else if (sep=="; ")
+  else if (sep == "; ")
     boxSeparator->setCurrentIndex(4);
-  else if (sep==", ")
+  else if (sep == ", ")
     boxSeparator->setCurrentIndex(5);
-  else if (sep==";")
+  else if (sep == ";")
     boxSeparator->setCurrentIndex(6);
-  else if (sep==",")
+  else if (sep == ",")
     boxSeparator->setCurrentIndex(7);
-  else
-  {
+  else {
     QString separator = sep;
-    boxSeparator->setEditText(separator.replace(" ","\\s").replace("\t","\\t"));
+    boxSeparator->setEditText(
+        separator.replace(" ", "\\s").replace("\t", "\\t"));
   }
 }
-void ConfigDialog::gotoMantidDirectories()
-{
+void ConfigDialog::gotoMantidDirectories() {
   generalDialog->setCurrentWidget(mtdTabWidget);
   mtdTabWidget->setCurrentWidget(directoriesPage);
 }
 
-void ConfigDialog::switchToLanguage(int param)
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+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.");
+    throw std::logic_error(
+        "Parent of ConfigDialog is not ApplicationWindow as expected.");
   }
   app->switchToLanguage(param);
   languageChange();
 }
 
-void ConfigDialog::insertLanguagesList()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
-  if(!app)
+void ConfigDialog::insertLanguagesList() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
+  if (!app)
     return;
 
   boxLanguage->clear();
@@ -2868,14 +2893,12 @@ void ConfigDialog::insertLanguagesList()
   QStringList locales = app->locales;
   QStringList languages;
   int lang = 0;
-  for (int i=0; i < (int)locales.size(); i++)
-  {
+  for (int i = 0; i < (int)locales.size(); i++) {
     if (locales[i] == "en")
       languages.push_back("English");
-    else
-    {
+    else {
       QTranslator translator;
-      translator.load("qtiplot_"+locales[i], qmPath);
+      translator.load("qtiplot_" + locales[i], qmPath);
 
       QString language = translator.translate("ApplicationWindow", "English");
       if (!language.isEmpty())
@@ -2891,34 +2914,30 @@ void ConfigDialog::insertLanguagesList()
   boxLanguage->setCurrentIndex(lang);
 }
 
-
-void ConfigDialog::showPointsBox(bool)
-{
-  if (generatePointsBtn->isChecked())
-  {
+void ConfigDialog::showPointsBox(bool) {
+  if (generatePointsBtn->isChecked()) {
     lblPoints->show();
     generatePointsBox->show();
     linearFit2PointsBox->show();
-  }
-  else
-  {
+  } else {
     lblPoints->hide();
     generatePointsBox->hide();
     linearFit2PointsBox->hide();
   }
 }
 
-void ConfigDialog::chooseTranslationsFolder()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::chooseTranslationsFolder() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app)
     return;
 
   QFileInfo tfi(app->d_translations_folder);
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the location of the MantidPlot translations folder!"),
-    tfi.dir().absolutePath(), 0/**QFileDialog::ShowDirsOnly*/);
+  QString dir = QFileDialog::getExistingDirectory(
+      this, tr("Choose the location of the MantidPlot translations folder!"),
+      tfi.dir().absolutePath(), 0 /**QFileDialog::ShowDirsOnly*/);
 
-  if (!dir.isEmpty()){
+  if (!dir.isEmpty()) {
     app->d_translations_folder = dir;
     translationsPathLine->setText(dir);
     app->createLanguagesList();
@@ -2926,9 +2945,9 @@ void ConfigDialog::chooseTranslationsFolder()
   }
 }
 
-void ConfigDialog::chooseHelpFolder()
-{
-  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parentWidget());
+void ConfigDialog::chooseHelpFolder() {
+  ApplicationWindow *app =
+      dynamic_cast<ApplicationWindow *>(this->parentWidget());
   if (!app)
     return;
 
@@ -2938,15 +2957,13 @@ void ConfigDialog::chooseHelpFolder()
   helpPathLine->setText(hfi.dir().absolutePath());
 }
 
-void ConfigDialog::addPythonScriptsDirs()
-{
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Add a python scripts directory"),
-    "", 0/**QFileDialog::ShowDirsOnly*/);
-  if (!dir.isEmpty())
-  {
+void ConfigDialog::addPythonScriptsDirs() {
+  QString dir = QFileDialog::getExistingDirectory(
+      this, tr("Add a python scripts directory"), "",
+      0 /**QFileDialog::ShowDirsOnly*/);
+  if (!dir.isEmpty()) {
     QString dirs = lePythonScriptsDirs->text();
-    if (!dirs.isEmpty())
-    {
+    if (!dirs.isEmpty()) {
       dirs += ";";
     }
     dirs += dir;
@@ -2954,15 +2971,13 @@ void ConfigDialog::addPythonScriptsDirs()
   }
 }
 
-void ConfigDialog::addPythonPluginDirs()
-{
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Add a python extension directory"),
-    "", 0/**QFileDialog::ShowDirsOnly*/);
-  if (!dir.isEmpty())
-  {
+void ConfigDialog::addPythonPluginDirs() {
+  QString dir = QFileDialog::getExistingDirectory(
+      this, tr("Add a python extension directory"), "",
+      0 /**QFileDialog::ShowDirsOnly*/);
+  if (!dir.isEmpty()) {
     QString dirs = lePythonPluginsDirs->text();
-    if (!dirs.isEmpty())
-    {
+    if (!dirs.isEmpty()) {
       dirs += ";";
     }
     dirs += dir;
@@ -2970,12 +2985,10 @@ void ConfigDialog::addPythonPluginDirs()
   }
 }
 
-void ConfigDialog::addInstrumentDir()
-{
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Select new instrument definition directory"),
-    "", 0);
-  if (!dir.isEmpty())
-  {
+void ConfigDialog::addInstrumentDir() {
+  QString dir = QFileDialog::getExistingDirectory(
+      this, tr("Select new instrument definition directory"), "", 0);
+  if (!dir.isEmpty()) {
     leInstrumentDir->setText(dir);
   }
 }
diff --git a/MantidPlot/src/ConfigDialog.h b/MantidPlot/src/ConfigDialog.h
index aa87cf7e72947c17cb3ce19d27c4ba15f75f960b..a7fd6f79b9f4cd7b0beae356c7a8d857c896dadc 100644
--- a/MantidPlot/src/ConfigDialog.h
+++ b/MantidPlot/src/ConfigDialog.h
@@ -54,17 +54,14 @@ class QTreeWidget;
 class QTreeWidgetItem;
 class QStringList;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class InstrumentSelector;
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentSelector;
+}
 }
 
 //! Preferences dialog
-class ConfigDialog : public QDialog
-{
+class ConfigDialog : public QDialog {
   Q_OBJECT
 
 public:
@@ -73,59 +70,60 @@ public:
   * @param parent :: parent widget (must be the application window!=
   * @param fl :: window flags
   */
-  ConfigDialog( QWidget* parent, Qt::WFlags fl = 0 );
-  void setColumnSeparator(const QString& sep);
+  ConfigDialog(QWidget *parent, Qt::WFlags fl = 0);
+  void setColumnSeparator(const QString &sep);
   void gotoMantidDirectories();
 
-  private slots:
-    void languageChange() override;
-    void insertLanguagesList();
+private slots:
+  void languageChange() override;
+  void insertLanguagesList();
 
-    void accept() override;
-    void apply();
+  void accept() override;
+  void apply();
 
-    void setCurrentPage(int index);
+  void setCurrentPage(int index);
 
-    //table fonts
-    void pickTextFont();
-    void pickHeaderFont();
+  // table fonts
+  void pickTextFont();
+  void pickHeaderFont();
 
-    //graph fonts
-    void pickAxesFont();
-    void pickNumbersFont();
-    void pickLegendFont();
-    void pickTitleFont();
+  // graph fonts
+  void pickAxesFont();
+  void pickNumbersFont();
+  void pickLegendFont();
+  void pickTitleFont();
 
-    void enableScaleFonts();
-    void showFrameWidth(bool ok);
+  void enableScaleFonts();
+  void showFrameWidth(bool ok);
 
-    //application
-    void pickApplicationFont();
+  // application
+  void pickApplicationFont();
 
-    //2D curves
-    int curveStyle();
-    void pick3DTitleFont();
-    void pick3DNumbersFont();
-    void pick3DAxesFont();
+  // 2D curves
+  int curveStyle();
+  void pick3DTitleFont();
+  void pick3DNumbersFont();
+  void pick3DAxesFont();
 
-    //Fitting
-    void showPointsBox(bool);
+  // Fitting
+  void showPointsBox(bool);
 
-    void switchToLanguage(int param);
+  void switchToLanguage(int param);
 
-    void chooseTranslationsFolder();
-    void chooseHelpFolder();
+  void chooseTranslationsFolder();
+  void chooseHelpFolder();
 
-    //Mantid
-    void addPythonScriptsDirs();
-    void addPythonPluginDirs();
-    void addInstrumentDir();
-    void enableButtons();
-    void itemCheckedChanged(QTreeWidgetItem* item);
-    void updateChildren(std::map<std::string, std::string> &programKeysAndDetails, QTreeWidgetItem* program);
-    void addDialog();
-    void editDialog();
-    void deleteDialog();
+  // Mantid
+  void addPythonScriptsDirs();
+  void addPythonPluginDirs();
+  void addInstrumentDir();
+  void enableButtons();
+  void itemCheckedChanged(QTreeWidgetItem *item);
+  void updateChildren(std::map<std::string, std::string> &programKeysAndDetails,
+                      QTreeWidgetItem *program);
+  void addDialog();
+  void editDialog();
+  void deleteDialog();
 
 private:
   void initPlotsPage();
@@ -150,7 +148,7 @@ private:
   void updateMantidOptionsTab();
   void updateSendToTab();
 
-  void initMantidOptionsTab(); 
+  void initMantidOptionsTab();
   void initSendToProgramTab();
   void refreshTreeCategories();
   void populateProgramTree();
@@ -163,49 +161,53 @@ private:
   void updateMdPlottingSettings();
   void setupMdPlottingConnections();
 
-  QTreeWidgetItem* createCheckedTreeItem(QString name,bool checkBoxState);
+  QTreeWidgetItem *createCheckedTreeItem(QString name, bool checkBoxState);
   QStringList buildHiddenCategoryString(QTreeWidgetItem *parent = 0);
 
-  std::map<std::string,std::map<std::string,std::string> > m_sendToSettings;
+  std::map<std::string, std::map<std::string, std::string>> m_sendToSettings;
 
-  QFont textFont, headerFont, axesFont, numbersFont, legendFont, titleFont, appFont;
+  QFont textFont, headerFont, axesFont, numbersFont, legendFont, titleFont,
+      appFont;
   QFont plot3DTitleFont, plot3DNumbersFont, plot3DAxesFont;
 
-  QCheckBox *boxScaleLayersOnPrint, *boxPrintCropmarks, *boxUpdateSeparators, *linearFit2PointsBox;
+  QCheckBox *boxScaleLayersOnPrint, *boxPrintCropmarks, *boxUpdateSeparators,
+      *linearFit2PointsBox;
   QTabWidget *plotsTabWidget, *appTabWidget, *mtdTabWidget;
   ColorButton *btnBackground3D, *btnMesh, *btnAxes, *btnLabels, *btnNumbers;
   ColorButton *btnFromColor, *btnToColor, *btnGrid;
-  QPushButton	*btnTitleFnt, *btnLabelsFnt, *btnNumFnt;
+  QPushButton *btnTitleFnt, *btnLabelsFnt, *btnNumFnt;
   QPushButton *deleteButton, *editButton, *addButton;
   ColorButton *buttonBackground, *buttonText, *buttonHeader;
   QPushButton *buttonOk, *buttonCancel, *buttonApply;
-  QPushButton* buttonTextFont, *buttonHeaderFont;
-  QStackedWidget * generalDialog;
-  QWidget *appColors, *tables, *plotOptions, *plotTicks, *plotFonts, *confirm, *plotPrint;
-  QWidget *application, *curves, *axesPage, *plots3D, *fitPage, *numericFormatPage, *floatingWindowsPage;
-  //Mantid
+  QPushButton *buttonTextFont, *buttonHeaderFont;
+  QStackedWidget *generalDialog;
+  QWidget *appColors, *tables, *plotOptions, *plotTicks, *plotFonts, *confirm,
+      *plotPrint;
+  QWidget *application, *curves, *axesPage, *plots3D, *fitPage,
+      *numericFormatPage, *floatingWindowsPage;
+  // Mantid
   QWidget *instrumentPage;
   QComboBox *facility;
-  MantidQt::MantidWidgets::InstrumentSelector  *defInstr;
-  QCheckBox* ckIgnoreParaView;
-  QCheckBox* ckQconvention;
+  MantidQt::MantidWidgets::InstrumentSelector *defInstr;
+  QCheckBox *ckIgnoreParaView;
+  QCheckBox *ckQconvention;
 
   /// Mantid tab for setting directories
   QWidget *directoriesPage;
-  QLineEdit* lePythonScriptsDirs;///< pythonscripts.directories
-  QLineEdit* lePythonPluginsDirs;///< python plugins directories
-  QLineEdit* leInstrumentDir;///< instrumentDefinition.directory
+  QLineEdit *lePythonScriptsDirs; ///< pythonscripts.directories
+  QLineEdit *lePythonPluginsDirs; ///< python plugins directories
+  QLineEdit *leInstrumentDir;     ///< instrumentDefinition.directory
   // Mantid curve fitting page
   QWidget *curveFittingPage;
   QComboBox *backgroundFunctions;
   QLineEdit *functionArguments;
   QComboBox *defaultPeakShape;
-  QSpinBox  *findPeaksFWHM,*findPeaksTolerance;
-  QSpinBox  *peakRadius;
-  QSpinBox  *decimals;
+  QSpinBox *findPeaksFWHM, *findPeaksTolerance;
+  QSpinBox *peakRadius;
+  QSpinBox *decimals;
   /// mantid options page
-  QWidget*  mantidOptionsPage;
-  QWidget*  mantidSendToPage;
+  QWidget *mantidOptionsPage;
+  QWidget *mantidSendToPage;
   QCheckBox *m_invisibleWorkspaces;
   QCheckBox *m_reusePlotInstances;
   QCheckBox *m_useOpenGL;
@@ -213,72 +215,88 @@ private:
   QTreeWidget *treeCategories;
   QTreeWidget *treePrograms;
 
-  //MDPlotting
-  QTabWidget* mdPlottingTabWidget;
+  // MDPlotting
+  QTabWidget *mdPlottingTabWidget;
   QWidget *vsiPage, *mdPlottingGeneralPage;
   QComboBox *vsiDefaultColorMap, *vsiInitialView, *mdPlottingGeneralColorMap;
-  QLabel *lblVsiDefaultColorMap, *lblVsiDefaultBackground, *lblGeneralDefaultColorMap, *lblBoxGeneralDefaultColorMap, *lblVsiLastSession, *lblVsiInitialView;
+  QLabel *lblVsiDefaultColorMap, *lblVsiDefaultBackground,
+      *lblGeneralDefaultColorMap, *lblBoxGeneralDefaultColorMap,
+      *lblVsiLastSession, *lblVsiInitialView;
   ColorButton *vsiDefaultBackground;
-  QGroupBox* mdPlottingGeneralFrame, *mdPlottingVsiFrameBottom;
-  QCheckBox* vsiLastSession;
+  QGroupBox *mdPlottingGeneralFrame, *mdPlottingVsiFrameBottom;
+  QCheckBox *vsiLastSession;
   MantidQt::API::MdSettings m_mdSettings;
 
-  QPushButton* buttonAxesFont, *buttonNumbersFont, *buttonLegendFont, *buttonTitleFont, *fontsBtn;
-  QCheckBox *boxSearchUpdates, *boxOrthogonal, *logBox, *plotLabelBox, *scaleErrorsBox;
-  QCheckBox *boxTitle, *boxFrame, *boxDistribution, *boxPlots3D, *boxPlots2D, *boxTables, *boxNotes, *boxFolders,*boxInstrWindow;
+  QPushButton *buttonAxesFont, *buttonNumbersFont, *buttonLegendFont,
+      *buttonTitleFont, *fontsBtn;
+  QCheckBox *boxSearchUpdates, *boxOrthogonal, *logBox, *plotLabelBox,
+      *scaleErrorsBox;
+  QCheckBox *boxTitle, *boxFrame, *boxDistribution, *boxPlots3D, *boxPlots2D,
+      *boxTables, *boxNotes, *boxFolders, *boxInstrWindow;
   QCheckBox *boxSave, *boxBackbones, *boxShowLegend, *boxSmoothMesh;
-  QCheckBox *boxAutoscaling, *boxShowProjection, *boxMatrices, *boxScaleFonts, *boxResize, *boxAspectRatio;
-  QComboBox *boxMajTicks, *boxMinTicks, *boxStyle, *boxCurveStyle, *boxSeparator, *boxLanguage, *boxDecimalSeparator;
-  QCheckBox *boxFloatingGraph, *boxFloatingTable, *boxFloatingInstrumentWindow, *boxFloatingMantidMatrix, *boxFloatingNote, *boxFloatingMatrix;
-  QCheckBox *boxFloatingCustomInterfaces,*boxFloatingTiledWindows;
-  QSpinBox *boxMinutes, *boxLineWidth, *boxFrameWidth, *boxResolution, *boxMargin, *boxPrecision, *boxAppPrecision;
-  QSpinBox *boxSymbolSize, *boxMinTicksLength, *boxMajTicksLength, *generatePointsBox;
+  QCheckBox *boxAutoscaling, *boxShowProjection, *boxMatrices, *boxScaleFonts,
+      *boxResize, *boxAspectRatio;
+  QComboBox *boxMajTicks, *boxMinTicks, *boxStyle, *boxCurveStyle,
+      *boxSeparator, *boxLanguage, *boxDecimalSeparator;
+  QCheckBox *boxFloatingGraph, *boxFloatingTable, *boxFloatingInstrumentWindow,
+      *boxFloatingMantidMatrix, *boxFloatingNote, *boxFloatingMatrix;
+  QCheckBox *boxFloatingCustomInterfaces, *boxFloatingTiledWindows;
+  QSpinBox *boxMinutes, *boxLineWidth, *boxFrameWidth, *boxResolution,
+      *boxMargin, *boxPrecision, *boxAppPrecision;
+  QSpinBox *boxSymbolSize, *boxMinTicksLength, *boxMajTicksLength,
+      *generatePointsBox;
   DoubleSpinBox *boxCurveLineWidth;
   ColorButton *btnWorkspace, *btnPanels, *btnPanelsText;
-  QListWidget * itemsList;
-  QLabel *labelFrameWidth, *lblLanguage, *lblWorkspace, *lblPanels, *lblPageHeader;
-  QLabel *lblPanelsText, *lblFonts, *lblStyle, *lblDecimalSeparator, *lblAppPrecision;
+  QListWidget *itemsList;
+  QLabel *labelFrameWidth, *lblLanguage, *lblWorkspace, *lblPanels,
+      *lblPageHeader;
+  QLabel *lblPanelsText, *lblFonts, *lblStyle, *lblDecimalSeparator,
+      *lblAppPrecision;
   QGroupBox *groupBoxConfirm;
   QGroupBox *groupBoxTableFonts, *groupBoxTableCol;
   QLabel *lblSeparator, *lblTableBackground, *lblTextColor, *lblHeaderColor;
-  QLabel *lblSymbSize, *lblAxesLineWidth, *lblCurveStyle, *lblResolution, *lblPrecision;
+  QLabel *lblSymbSize, *lblAxesLineWidth, *lblCurveStyle, *lblResolution,
+      *lblPrecision;
   QGroupBox *groupBox3DFonts, *groupBox3DCol;
-  QLabel *lblMargin, *lblMajTicks, *lblMajTicksLength, *lblLineWidth, *lblMinTicks, *lblMinTicksLength, *lblPoints, *lblPeaksColor;
+  QLabel *lblMargin, *lblMajTicks, *lblMajTicksLength, *lblLineWidth,
+      *lblMinTicks, *lblMinTicksLength, *lblPoints, *lblPeaksColor;
   QGroupBox *groupBoxFittingCurve, *groupBoxFitParameters;
   QRadioButton *samePointsBtn, *generatePointsBtn;
   QGroupBox *groupBoxMultiPeak;
   ColorBox *boxPeaksColor;
   QLabel *lblScriptingLanguage, *lblInitWindow;
   QComboBox *boxScriptingLanguage, *boxInitWindow;
-  QCheckBox *boxAntialiasing, *boxAutoscale3DPlots, *boxTableComments, *boxThousandsSeparator;
-  QCheckBox *boxPromptRenameTables, *boxBackupProject, *boxLabelsEditing, *boxPromptDeleteWorkspace;
+  QCheckBox *boxAntialiasing, *boxAutoscale3DPlots, *boxTableComments,
+      *boxThousandsSeparator;
+  QCheckBox *boxPromptRenameTables, *boxBackupProject, *boxLabelsEditing,
+      *boxPromptDeleteWorkspace;
   QWidget *fileLocationsPage;
   QLabel *lblTranslationsPath, *lblHelpPath, *lblUndoStackSize, *lblEndOfLine;
   QLineEdit *translationsPathLine, *helpPathLine;
   QSpinBox *undoStackSizeBox;
   QComboBox *boxEndLine;
-  QCheckBox* cbApplyToMantid;
-  QCheckBox* cbDrawAllErrors;
-  QCheckBox* cbEnableQtiPlotFitting;
+  QCheckBox *cbApplyToMantid;
+  QCheckBox *cbDrawAllErrors;
+  QCheckBox *cbEnableQtiPlotFitting;
 
   QLabel *labelGraphAxesLabelsDist, *labelTickLabelsDist;
   QSpinBox *boxAxesLabelsDist, *boxTickLabelsDist;
-  QLabel *xBottomLabel, *xTopLabel, *yLeftLabel, *yRightLabel, *enableAxisLabel, *showNumbersLabel, *scaleLabel;
+  QLabel *xBottomLabel, *xTopLabel, *yLeftLabel, *yRightLabel, *enableAxisLabel,
+      *showNumbersLabel, *scaleLabel;
   QCheckBox *boxEnableAxis, *boxShowAxisLabels;
-  QGroupBox * enabledAxesGroupBox;
+  QGroupBox *enabledAxesGroupBox;
   QGridLayout *enabledAxesGrid;
   QCheckBox *boxSynchronizeScales;
 
-
 #ifdef SCRIPTING_PYTHON
   QLabel *lblPythonConfigDir;
   QLineEdit *pythonConfigDirLine;
 #endif
   QCheckBox *boxUpdateTableValues;
 
-  public slots:
-    void changeUsageGeneralMdColorMap();
-    void changeUsageLastSession();
+public slots:
+  void changeUsageGeneralMdColorMap();
+  void changeUsageLastSession();
 };
 
 #endif // CONFIGDIALOG_H
diff --git a/MantidPlot/src/ContourLinesEditor.cpp b/MantidPlot/src/ContourLinesEditor.cpp
index 19a0bfd048c0f3b5b62e3a7b02961e715bd4c797..82a67c2208868e8617899f211d144cb8b102d78c 100644
--- a/MantidPlot/src/ContourLinesEditor.cpp
+++ b/MantidPlot/src/ContourLinesEditor.cpp
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ContourLinesEditor.cpp
-	Project              : QtiPlot
+        File                 : ContourLinesEditor.cpp
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2009 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A Contour Lines Editor Widget
+        Copyright            : (C) 2009 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A Contour Lines Editor Widget
  ***************************************************************************/
 
 /***************************************************************************
@@ -45,69 +45,58 @@
 
 #include <stdexcept>
 
-ContourLinesEditor::ContourLinesEditor(const QLocale& locale, int precision, QWidget* parent)
-				: QWidget(parent),
-                                  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);
-	table->hideColumn(1);
-	table->setSelectionMode(QAbstractItemView::SingleSelection);
-	table->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
-	table->horizontalHeader()->setClickable( false );
-	table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
-	table->viewport()->setMouseTracking(true);
-	table->viewport()->installEventFilter(this);
-	table->setHorizontalHeaderLabels(QStringList() << tr("Level") << tr("Pen"));
-	table->setMinimumHeight(6*table->horizontalHeader()->height() + 2);
-	table->installEventFilter(this);
-
-	connect(table, SIGNAL(cellClicked (int, int)), this, SLOT(showPenDialog(int, int)));
-
-	insertBtn = new QPushButton(tr("&Insert"));
-	insertBtn->setEnabled(false);
-	connect(insertBtn, SIGNAL(clicked()), this, SLOT(insertLevel()));
-
-	deleteBtn = new QPushButton(tr("&Delete"));
-	deleteBtn->setEnabled(false);
-	connect(deleteBtn, SIGNAL(clicked()), this, SLOT(deleteLevel()));
-
-	QHBoxLayout* hb = new QHBoxLayout();
-	hb->addWidget(insertBtn);
-	hb->addWidget(deleteBtn);
-
-	QVBoxLayout* vl = new QVBoxLayout(this);
-	vl->setSpacing(0);
-	vl->addWidget(table);
-	vl->addLayout(hb);
-
-	setFocusProxy(table);
-	setMaximumWidth(200);
-
-	penDialog = NULL;
+ContourLinesEditor::ContourLinesEditor(const QLocale &locale, int precision,
+                                       QWidget *parent)
+    : QWidget(parent), 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);
+  table->hideColumn(1);
+  table->setSelectionMode(QAbstractItemView::SingleSelection);
+  table->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
+  table->horizontalHeader()->setClickable(false);
+  table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
+  table->viewport()->setMouseTracking(true);
+  table->viewport()->installEventFilter(this);
+  table->setHorizontalHeaderLabels(QStringList() << tr("Level") << tr("Pen"));
+  table->setMinimumHeight(6 * table->horizontalHeader()->height() + 2);
+  table->installEventFilter(this);
+
+  connect(table, SIGNAL(cellClicked(int, int)), this,
+          SLOT(showPenDialog(int, int)));
+
+  insertBtn = new QPushButton(tr("&Insert"));
+  insertBtn->setEnabled(false);
+  connect(insertBtn, SIGNAL(clicked()), this, SLOT(insertLevel()));
+
+  deleteBtn = new QPushButton(tr("&Delete"));
+  deleteBtn->setEnabled(false);
+  connect(deleteBtn, SIGNAL(clicked()), this, SLOT(deleteLevel()));
+
+  QHBoxLayout *hb = new QHBoxLayout();
+  hb->addWidget(insertBtn);
+  hb->addWidget(deleteBtn);
+
+  QVBoxLayout *vl = new QVBoxLayout(this);
+  vl->setSpacing(0);
+  vl->addWidget(table);
+  vl->addLayout(hb);
+
+  setFocusProxy(table);
+  setMaximumWidth(200);
+
+  penDialog = NULL;
 }
 
-void ContourLinesEditor::updateContourLevels()
-{
-	if (!d_spectrogram)
-		return;
+void ContourLinesEditor::updateContourLevels() {
+  if (!d_spectrogram)
+    return;
 
-	int rows = table->rowCount();
-	QwtValueList levels;
+  int rows = table->rowCount();
+  QwtValueList levels;
   for (int i = 0; i < rows; i++) {
     DoubleSpinBox *spinBox =
         dynamic_cast<DoubleSpinBox *>(table->cellWidget(i, 0));
@@ -118,318 +107,308 @@ void ContourLinesEditor::updateContourLevels()
   d_spectrogram->setContourLevels(levels);
 }
 
-void ContourLinesEditor::updateContourPens()
-{
-	if (!d_spectrogram)
-		return;
+void ContourLinesEditor::updateContourPens() {
+  if (!d_spectrogram)
+    return;
 
-	if (!table->isColumnHidden(1))
-		d_spectrogram->setContourPenList(d_pen_list);
+  if (!table->isColumnHidden(1))
+    d_spectrogram->setContourPenList(d_pen_list);
 }
 
-void ContourLinesEditor::setSpectrogram(Spectrogram *sp)
-{
-	if (!sp || d_spectrogram == sp)
-		return;
+void ContourLinesEditor::setSpectrogram(Spectrogram *sp) {
+  if (!sp || d_spectrogram == sp)
+    return;
 
-	d_spectrogram = sp;
-	updateContents();
+  d_spectrogram = sp;
+  updateContents();
 }
 
-void ContourLinesEditor::updateContents()
-{
-	if (!d_spectrogram)
-		return;
-
-	QwtValueList levels = d_spectrogram->contourLevels ();
-
-	int rows = (int)levels.size();
-	table->setRowCount(rows);
-	table->blockSignals(true);
-
-	QwtDoubleInterval range = d_spectrogram->data().range();
-	for (int i = 0; i < rows; i++){
-		DoubleSpinBox *sb = new DoubleSpinBox();
-		sb->setLocale(d_locale);
-		sb->setDecimals(d_precision);
-		sb->setValue(levels[i]);
-		sb->setRange(range.minValue (), range.maxValue ());
-		connect(sb, SIGNAL(activated(DoubleSpinBox *)), this, SLOT(spinBoxActivated(DoubleSpinBox *)));
-    	table->setCellWidget(i, 0, sb);
-
-		QPen pen = d_spectrogram->defaultContourPen();
-		if (pen.style() == Qt::NoPen)
-			pen = d_spectrogram->contourPen (levels[i]);
-
-		int width = 80;
-		int height = 20;
-    	QPixmap pix(width, height);
-    	pix.fill(Qt::white);
-    	QPainter paint(&pix);
-    	paint.setRenderHint(QPainter::Antialiasing);
-    	paint.setPen(pen);
-    	paint.drawLine(0, height/2, width, height/2);
-    	paint.end();
-
-    	QLabel *lbl = new QLabel();
-    	lbl->setPixmap(pix);
-
-    	table->setCellWidget(i, 1, lbl);
-
-    	d_pen_list << pen;
-	}
-	table->blockSignals(false);
+void ContourLinesEditor::updateContents() {
+  if (!d_spectrogram)
+    return;
+
+  QwtValueList levels = d_spectrogram->contourLevels();
+
+  int rows = (int)levels.size();
+  table->setRowCount(rows);
+  table->blockSignals(true);
+
+  QwtDoubleInterval range = d_spectrogram->data().range();
+  for (int i = 0; i < rows; i++) {
+    DoubleSpinBox *sb = new DoubleSpinBox();
+    sb->setLocale(d_locale);
+    sb->setDecimals(d_precision);
+    sb->setValue(levels[i]);
+    sb->setRange(range.minValue(), range.maxValue());
+    connect(sb, SIGNAL(activated(DoubleSpinBox *)), this,
+            SLOT(spinBoxActivated(DoubleSpinBox *)));
+    table->setCellWidget(i, 0, sb);
+
+    QPen pen = d_spectrogram->defaultContourPen();
+    if (pen.style() == Qt::NoPen)
+      pen = d_spectrogram->contourPen(levels[i]);
+
+    int width = 80;
+    int height = 20;
+    QPixmap pix(width, height);
+    pix.fill(Qt::white);
+    QPainter paint(&pix);
+    paint.setRenderHint(QPainter::Antialiasing);
+    paint.setPen(pen);
+    paint.drawLine(0, height / 2, width, height / 2);
+    paint.end();
+
+    QLabel *lbl = new QLabel();
+    lbl->setPixmap(pix);
+
+    table->setCellWidget(i, 1, lbl);
+
+    d_pen_list << pen;
+  }
+  table->blockSignals(false);
 }
 
-void ContourLinesEditor::insertLevel()
-{
-	if (!d_spectrogram)
-		return;
+void ContourLinesEditor::insertLevel() {
+  if (!d_spectrogram)
+    return;
 
-	int row = table->currentRow();
-	DoubleSpinBox *sb = table_cellWidget<DoubleSpinBox>(row, 0);
+  int row = table->currentRow();
+  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));
+  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();
 
-	double val = 0.5*(current_value + previous_value);
-
-	table->blockSignals(true);
-	table->insertRow(row);
-
-	sb = new DoubleSpinBox();
-	sb->setLocale(d_locale);
-	sb->setDecimals(d_precision);
-	sb->setValue(val);
-	sb->setRange(range.minValue (), range.maxValue ());
-	connect(sb, SIGNAL(activated(DoubleSpinBox *)), this, SLOT(spinBoxActivated(DoubleSpinBox *)));
-    table->setCellWidget(row, 0, sb);
-
-	QPen pen = d_spectrogram->defaultContourPen();
-	if (pen.style() == Qt::NoPen)
-		pen = d_spectrogram->contourPen (val);
-
-	int width = 80;
-	int height = 20;
-	QPixmap pix(width, height);
-	pix.fill(Qt::white);
-	QPainter paint(&pix);
-	paint.setRenderHint(QPainter::Antialiasing);
-	paint.setPen(pen);
-	paint.drawLine(0, height/2, width, height/2);
-	paint.end();
-
-	QLabel *lbl = new QLabel();
-	lbl->setPixmap(pix);
-
-	table->setCellWidget(row, 1, lbl);
-	table->blockSignals(false);
-
-	enableButtons(table->currentRow());
-	d_pen_list.insert(row, pen);
+  double val = 0.5 * (current_value + previous_value);
+
+  table->blockSignals(true);
+  table->insertRow(row);
+
+  sb = new DoubleSpinBox();
+  sb->setLocale(d_locale);
+  sb->setDecimals(d_precision);
+  sb->setValue(val);
+  sb->setRange(range.minValue(), range.maxValue());
+  connect(sb, SIGNAL(activated(DoubleSpinBox *)), this,
+          SLOT(spinBoxActivated(DoubleSpinBox *)));
+  table->setCellWidget(row, 0, sb);
+
+  QPen pen = d_spectrogram->defaultContourPen();
+  if (pen.style() == Qt::NoPen)
+    pen = d_spectrogram->contourPen(val);
+
+  int width = 80;
+  int height = 20;
+  QPixmap pix(width, height);
+  pix.fill(Qt::white);
+  QPainter paint(&pix);
+  paint.setRenderHint(QPainter::Antialiasing);
+  paint.setPen(pen);
+  paint.drawLine(0, height / 2, width, height / 2);
+  paint.end();
+
+  QLabel *lbl = new QLabel();
+  lbl->setPixmap(pix);
+
+  table->setCellWidget(row, 1, lbl);
+  table->blockSignals(false);
+
+  enableButtons(table->currentRow());
+  d_pen_list.insert(row, pen);
 }
 
-void ContourLinesEditor::deleteLevel()
-{
-	int index = table->currentRow();
-	table->removeRow (index);
+void ContourLinesEditor::deleteLevel() {
+  int index = table->currentRow();
+  table->removeRow(index);
 
-	if (index >=0 && index < d_pen_list.size())
-		d_pen_list.removeAt(index);
+  if (index >= 0 && index < d_pen_list.size())
+    d_pen_list.removeAt(index);
 }
 
-void ContourLinesEditor::showPenDialog(int row, int col)
-{
-	if (!d_spectrogram || col != 1)
-		return;
+void ContourLinesEditor::showPenDialog(int row, int col) {
+  if (!d_spectrogram || col != 1)
+    return;
 
-	enableButtons(row);
+  enableButtons(row);
 
-	QPen pen = d_pen_list[row];
+  QPen pen = d_pen_list[row];
 
-	if (!penDialog){
-		penDialog = new QDialog(this);
-		penDialog->setWindowTitle(tr("MantidPlot - Edit pen"));
+  if (!penDialog) {
+    penDialog = new QDialog(this);
+    penDialog->setWindowTitle(tr("MantidPlot - Edit pen"));
 
-		QGroupBox *gb1 = new QGroupBox();
-		QGridLayout *hl1 = new QGridLayout(gb1);
+    QGroupBox *gb1 = new QGroupBox();
+    QGridLayout *hl1 = new QGridLayout(gb1);
 
-		hl1->addWidget(new QLabel(tr("Color")), 0, 0);
-		penColorBox = new ColorButton();
-		penColorBox->setColor(pen.color());
-		hl1->addWidget(penColorBox, 0, 1);
+    hl1->addWidget(new QLabel(tr("Color")), 0, 0);
+    penColorBox = new ColorButton();
+    penColorBox->setColor(pen.color());
+    hl1->addWidget(penColorBox, 0, 1);
 
-		applyAllColorBox = new QCheckBox(tr("Apply to all"));
-		hl1->addWidget(applyAllColorBox, 0, 2);
+    applyAllColorBox = new QCheckBox(tr("Apply to all"));
+    hl1->addWidget(applyAllColorBox, 0, 2);
 
-		hl1->addWidget(new QLabel(tr("Style")), 1, 0);
-		penStyleBox = new PenStyleBox;
-		penStyleBox->setStyle(pen.style());
-		hl1->addWidget(penStyleBox, 1, 1);
+    hl1->addWidget(new QLabel(tr("Style")), 1, 0);
+    penStyleBox = new PenStyleBox;
+    penStyleBox->setStyle(pen.style());
+    hl1->addWidget(penStyleBox, 1, 1);
 
-		applyAllStyleBox = new QCheckBox(tr("Apply to all"));
-		hl1->addWidget(applyAllStyleBox, 1, 2);
+    applyAllStyleBox = new QCheckBox(tr("Apply to all"));
+    hl1->addWidget(applyAllStyleBox, 1, 2);
 
-		hl1->addWidget(new QLabel(tr("Width")), 2, 0);
-		penWidthBox = new DoubleSpinBox();
-		penWidthBox->setValue(pen.widthF());
-		hl1->addWidget(penWidthBox, 2, 1);
-		hl1->setRowStretch(3, 1);
+    hl1->addWidget(new QLabel(tr("Width")), 2, 0);
+    penWidthBox = new DoubleSpinBox();
+    penWidthBox->setValue(pen.widthF());
+    hl1->addWidget(penWidthBox, 2, 1);
+    hl1->setRowStretch(3, 1);
 
-		applyAllWidthBox = new QCheckBox(tr("Apply to all"));
-		hl1->addWidget(applyAllWidthBox, 2, 2);
+    applyAllWidthBox = new QCheckBox(tr("Apply to all"));
+    hl1->addWidget(applyAllWidthBox, 2, 2);
 
-		QPushButton *acceptPenBtn = new QPushButton(tr("&Ok"));
-		connect(acceptPenBtn, SIGNAL(clicked()), this, SLOT(updatePen()));
+    QPushButton *acceptPenBtn = new QPushButton(tr("&Ok"));
+    connect(acceptPenBtn, SIGNAL(clicked()), this, SLOT(updatePen()));
 
-		QPushButton *closeBtn = new QPushButton(tr("&Close"));
-		connect(closeBtn, SIGNAL(clicked()), penDialog, SLOT(reject()));
+    QPushButton *closeBtn = new QPushButton(tr("&Close"));
+    connect(closeBtn, SIGNAL(clicked()), penDialog, SLOT(reject()));
 
-		QHBoxLayout *hl2 = new QHBoxLayout();
-		hl2->addStretch();
-		hl2->addWidget(acceptPenBtn);
-		hl2->addWidget(closeBtn);
+    QHBoxLayout *hl2 = new QHBoxLayout();
+    hl2->addStretch();
+    hl2->addWidget(acceptPenBtn);
+    hl2->addWidget(closeBtn);
 
-		QVBoxLayout *vl = new QVBoxLayout(penDialog);
-		vl->addWidget(gb1);
-		vl->addLayout(hl2);
-	} else {
-		penColorBox->setColor(pen.color());
-		penStyleBox->setStyle(pen.style());
-		penWidthBox->setValue(pen.widthF());
-	}
+    QVBoxLayout *vl = new QVBoxLayout(penDialog);
+    vl->addWidget(gb1);
+    vl->addLayout(hl2);
+  } else {
+    penColorBox->setColor(pen.color());
+    penStyleBox->setStyle(pen.style());
+    penWidthBox->setValue(pen.widthF());
+  }
 
-	d_pen_index = row;
-	penDialog->exec();
+  d_pen_index = row;
+  penDialog->exec();
 }
 
-void ContourLinesEditor::updatePenColumn()
-{
-	table->blockSignals(true);
-	for (int i = 0; i < table->rowCount(); i++){
-		int width = 80;
-		int height = 20;
-    	QPixmap pix(width, height);
-    	pix.fill(Qt::white);
-    	QPainter paint(&pix);
-    	paint.setRenderHint(QPainter::Antialiasing);
-    	paint.setPen(d_pen_list[i]);
-    	paint.drawLine(0, height/2, width, height/2);
-    	paint.end();
-
-    	QLabel *lbl = new QLabel();
-    	lbl->setPixmap(pix);
-
-    	table->setCellWidget(i, 1, lbl);
-	}
-	table->blockSignals(false);
+void ContourLinesEditor::updatePenColumn() {
+  table->blockSignals(true);
+  for (int i = 0; i < table->rowCount(); i++) {
+    int width = 80;
+    int height = 20;
+    QPixmap pix(width, height);
+    pix.fill(Qt::white);
+    QPainter paint(&pix);
+    paint.setRenderHint(QPainter::Antialiasing);
+    paint.setPen(d_pen_list[i]);
+    paint.drawLine(0, height / 2, width, height / 2);
+    paint.end();
+
+    QLabel *lbl = new QLabel();
+    lbl->setPixmap(pix);
+
+    table->setCellWidget(i, 1, lbl);
+  }
+  table->blockSignals(false);
 }
 
-void ContourLinesEditor::updatePen()
-{
-	QPen pen = QPen(penColorBox->color(), penWidthBox->value(), penStyleBox->style());
-
-	d_pen_list[d_pen_index] = pen;
-
-	if (applyAllColorBox->isChecked()){
-		for (int i = 0; i < d_pen_list.size(); i++){
-			QPen p = d_pen_list[i];
-			p.setColor(penColorBox->color());
-			d_pen_list[i] = p;
-		}
-	}
-
-	if (applyAllStyleBox->isChecked()){
-		for (int i = 0; i < d_pen_list.size(); i++){
-			QPen p = d_pen_list[i];
-			p.setStyle(penStyleBox->style());
-			d_pen_list[i] = p;
-		}
-	}
-
-	if (applyAllWidthBox->isChecked()){
-		for (int i = 0; i < d_pen_list.size(); i++){
-			QPen p = d_pen_list[i];
-			p.setWidthF(penWidthBox->value());
-			d_pen_list[i] = p;
-		}
-	}
-
-	updatePenColumn();
-	penDialog->close();
+void ContourLinesEditor::updatePen() {
+  QPen pen =
+      QPen(penColorBox->color(), penWidthBox->value(), penStyleBox->style());
+
+  d_pen_list[d_pen_index] = pen;
+
+  if (applyAllColorBox->isChecked()) {
+    for (int i = 0; i < d_pen_list.size(); i++) {
+      QPen p = d_pen_list[i];
+      p.setColor(penColorBox->color());
+      d_pen_list[i] = p;
+    }
+  }
+
+  if (applyAllStyleBox->isChecked()) {
+    for (int i = 0; i < d_pen_list.size(); i++) {
+      QPen p = d_pen_list[i];
+      p.setStyle(penStyleBox->style());
+      d_pen_list[i] = p;
+    }
+  }
+
+  if (applyAllWidthBox->isChecked()) {
+    for (int i = 0; i < d_pen_list.size(); i++) {
+      QPen p = d_pen_list[i];
+      p.setWidthF(penWidthBox->value());
+      d_pen_list[i] = p;
+    }
+  }
+
+  updatePenColumn();
+  penDialog->close();
 }
 
-bool ContourLinesEditor::eventFilter(QObject *object, QEvent *e)
-{
-	if (e->type() == QEvent::MouseMove && object == table->viewport()){
-        const QMouseEvent *me = (const QMouseEvent *)e;
-        QPoint pos = table->viewport()->mapToParent(me->pos());
-        int row = table->rowAt(pos.y() - table->horizontalHeader()->height());
-        if (table->columnAt(pos.x()) == 1 && row >= 0 && row < table->rowCount())
-            setCursor(QCursor(Qt::PointingHandCursor));
-        else
-            setCursor(QCursor(Qt::ArrowCursor));
-        return true;
-	} else if (e->type() == QEvent::Leave && object == table->viewport()){
-		setCursor(QCursor(Qt::ArrowCursor));
-		return true;
-	} else if (e->type() == QEvent::KeyPress && object == table){
-		QKeyEvent *ke = (QKeyEvent *)e;
-		if (ke->key() == Qt::Key_Return && table->currentColumn() == 1){
-			showPenDialog(table->currentRow(), 1);
-			return true;
-		}
-	return false;
-	}
-	return QObject::eventFilter(object, e);
+bool ContourLinesEditor::eventFilter(QObject *object, QEvent *e) {
+  if (e->type() == QEvent::MouseMove && object == table->viewport()) {
+    const QMouseEvent *me = (const QMouseEvent *)e;
+    QPoint pos = table->viewport()->mapToParent(me->pos());
+    int row = table->rowAt(pos.y() - table->horizontalHeader()->height());
+    if (table->columnAt(pos.x()) == 1 && row >= 0 && row < table->rowCount())
+      setCursor(QCursor(Qt::PointingHandCursor));
+    else
+      setCursor(QCursor(Qt::ArrowCursor));
+    return true;
+  } else if (e->type() == QEvent::Leave && object == table->viewport()) {
+    setCursor(QCursor(Qt::ArrowCursor));
+    return true;
+  } else if (e->type() == QEvent::KeyPress && object == table) {
+    QKeyEvent *ke = (QKeyEvent *)e;
+    if (ke->key() == Qt::Key_Return && table->currentColumn() == 1) {
+      showPenDialog(table->currentRow(), 1);
+      return true;
+    }
+    return false;
+  }
+  return QObject::eventFilter(object, e);
 }
 
-void ContourLinesEditor::enableButtons(int row)
-{
-	if (row < 0)
-		return;
+void ContourLinesEditor::enableButtons(int row) {
+  if (row < 0)
+    return;
 
-	deleteBtn->setEnabled(true);
-	insertBtn->setEnabled(true);
+  deleteBtn->setEnabled(true);
+  insertBtn->setEnabled(true);
 }
 
-void ContourLinesEditor::spinBoxActivated(DoubleSpinBox *sb)
-{
-	if (!sb)
-		return;
-
-	int rows = table->rowCount();
-	for (int i = 0; i < rows; i++){
-		DoubleSpinBox *box = dynamic_cast<DoubleSpinBox*>(table->cellWidget(i, 0));
-		if (box && box == sb){
-			table->setCurrentCell(i, 0);
-			enableButtons(i);
-			return;
-		}
-	}
+void ContourLinesEditor::spinBoxActivated(DoubleSpinBox *sb) {
+  if (!sb)
+    return;
+
+  int rows = table->rowCount();
+  for (int i = 0; i < rows; i++) {
+    DoubleSpinBox *box = dynamic_cast<DoubleSpinBox *>(table->cellWidget(i, 0));
+    if (box && box == sb) {
+      table->setCurrentCell(i, 0);
+      enableButtons(i);
+      return;
+    }
+  }
 }
 
-void ContourLinesEditor::showPenColumn(bool on)
-{
-	if (on)
-		table->showColumn(1);
-	else
-		table->hideColumn(1);
+void ContourLinesEditor::showPenColumn(bool on) {
+  if (on)
+    table->showColumn(1);
+  else
+    table->hideColumn(1);
 }
 
-ContourLinesEditor::~ContourLinesEditor()
-{
-	if(penDialog)
-        delete penDialog;
+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));
+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.");
   }
diff --git a/MantidPlot/src/ContourLinesEditor.h b/MantidPlot/src/ContourLinesEditor.h
index a761e6c3e7ada2a2122cc3010f098715ed56735d..443d3ca67de1ee0f0f8cde7ce03f9d129051d227 100644
--- a/MantidPlot/src/ContourLinesEditor.h
+++ b/MantidPlot/src/ContourLinesEditor.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ContourLinesEditor.h
-	Project              : QtiPlot
+        File                 : ContourLinesEditor.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2009 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A Contour Lines Editor Widget
+        Copyright            : (C) 2009 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A Contour Lines Editor Widget
  ***************************************************************************/
 
 /***************************************************************************
@@ -41,64 +41,65 @@ class PenStyleBox;
 
 //! A complex widget allowing to customize contour line plots.
 /**
- * It uses a QTableWidget to display the values in one column and their corresponding pen in a second column.
+ * It uses a QTableWidget to display the values in one column and their
+ corresponding pen in a second column.
  * A click on a table color pops-up a dialog allowing to customize the pen.
 
-	\image html images/color_map_editor.png
+        \image html images/color_map_editor.png
  */
-class ContourLinesEditor: public QWidget
-{
-    Q_OBJECT
+class ContourLinesEditor : public QWidget {
+  Q_OBJECT
 
 public:
-	//! Constructor.
-	/**
-	* @param parent :: parent widget (only affects placement of the widget)
-	*/
-	ContourLinesEditor(const QLocale& locale = QLocale::system(), int precision = 6, QWidget* parent = 0);
-        ~ContourLinesEditor() override;
-        //! Use this function to initialize the values.
-	void setSpectrogram(Spectrogram *sp);
-	//! Updates levels in the target spectrogram and replots it.
-	void updateContourLevels();
-	void updateContourPens();
-	//! Updates cell items when spectrogram contour lines changed.
-	void updateContents();
-	void showPenColumn(bool on = true);
+  //! Constructor.
+  /**
+  * @param parent :: parent widget (only affects placement of the widget)
+  */
+  ContourLinesEditor(const QLocale &locale = QLocale::system(),
+                     int precision = 6, QWidget *parent = 0);
+  ~ContourLinesEditor() override;
+  //! Use this function to initialize the values.
+  void setSpectrogram(Spectrogram *sp);
+  //! Updates levels in the target spectrogram and replots it.
+  void updateContourLevels();
+  void updateContourPens();
+  //! Updates cell items when spectrogram contour lines changed.
+  void updateContents();
+  void showPenColumn(bool on = true);
 
 protected slots:
-	void enableButtons(int row);
-	void showPenDialog(int row, int col);
-	void insertLevel();
-	void deleteLevel();
-	void spinBoxActivated(DoubleSpinBox *);
-	void updatePen();
+  void enableButtons(int row);
+  void showPenDialog(int row, int col);
+  void insertLevel();
+  void deleteLevel();
+  void spinBoxActivated(DoubleSpinBox *);
+  void updatePen();
 
-        bool eventFilter(QObject *object, QEvent *e) override;
+  bool eventFilter(QObject *object, QEvent *e) override;
 
 private:
-	void updatePenColumn();
-  template<class Widget>
-  Widget* table_cellWidget(int i, int j) const;
+  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;
-	QPushButton *insertBtn, *deleteBtn;
-	Spectrogram *d_spectrogram;
+  //! Table displaying the values ranges in the first column and their
+  // corresponding pens in the second column
+  QTableWidget *table;
+  QPushButton *insertBtn, *deleteBtn;
+  Spectrogram *d_spectrogram;
 
-	//! Locale settings used to display level values
-	QLocale d_locale;
-	//! Precision used to display level values
-	int d_precision;
+  //! Locale settings used to display level values
+  QLocale d_locale;
+  //! Precision used to display level values
+  int d_precision;
 
-	QDialog *penDialog;
-	ColorButton *penColorBox;
-	PenStyleBox *penStyleBox;
-	DoubleSpinBox *penWidthBox;
-	QCheckBox *applyAllColorBox, *applyAllWidthBox, *applyAllStyleBox;
+  QDialog *penDialog;
+  ColorButton *penColorBox;
+  PenStyleBox *penStyleBox;
+  DoubleSpinBox *penWidthBox;
+  QCheckBox *applyAllColorBox, *applyAllWidthBox, *applyAllStyleBox;
 
-	int d_pen_index;
-	QList<QPen> d_pen_list;
+  int d_pen_index;
+  QList<QPen> d_pen_list;
 };
 
 #endif
diff --git a/MantidPlot/src/Convolution.cpp b/MantidPlot/src/Convolution.cpp
index fad8a7afa63fb54e44c1c3953e164f2c672a7bf2..d4ee2fdcd43f3ac81e7857577fef6f5dc0a8deef 100644
--- a/MantidPlot/src/Convolution.cpp
+++ b/MantidPlot/src/Convolution.cpp
@@ -36,208 +36,202 @@
 #include <QLocale>
 #include <gsl/gsl_fft_halfcomplex.h>
 
-Convolution::Convolution(ApplicationWindow *parent, Table *t, const QString& signalColName, const QString& responseColName)
-: Filter(parent, t), d_n_signal(0.0), d_n_response(0.0)
-{
-	setObjectName(tr("Convolution"));
-    setDataFromTable(t, signalColName, responseColName);
+Convolution::Convolution(ApplicationWindow *parent, Table *t,
+                         const QString &signalColName,
+                         const QString &responseColName)
+    : Filter(parent, t), d_n_signal(0.0), d_n_response(0.0) {
+  setObjectName(tr("Convolution"));
+  setDataFromTable(t, signalColName, responseColName);
 }
 
-bool Convolution::setDataFromTable(Table *t, const QString& signalColName, const QString& responseColName, int, int)
-{
-    if (t && d_table != t)
-        d_table = t;
-
-    int signal_col = d_table->colIndex(signalColName);
-	int response_col = d_table->colIndex(responseColName);
-
-	if (signal_col < 0)
-	{
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The signal data set %1 does not exist!").arg(signalColName));
-		d_init_err = true;
-		return false;
-	}
-	else if (response_col < 0)
-	{
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The response data set %1 does not exist!").arg(responseColName));
-		d_init_err = true;
-		return false;
-	}
-
-    if (d_n > 0)
-	{//delete previously allocated memory
-		delete[] d_x;
-		delete[] d_y;
-	}
-
-	d_n_response = 0;
-	int rows = d_table->numRows();
-	for (int i=0; i<rows; i++)
-	{
-		if (!d_table->text(i, response_col).isEmpty())
-			d_n_response++;
-	}
-	if (d_n_response >= rows/2)
-	{
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The response dataset '%1' must be less then half the size of the signal dataset '%2'!").arg(responseColName).arg(signalColName));
-		d_init_err = true;
-		return false;
-	}
-	else if (d_n_response%2 == 0)
-	{
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The response dataset '%1' must contain an odd number of points!").arg(responseColName));
-		d_init_err = true;
-		return false;
-	}
-
-	d_n = rows;
-
-	d_n_signal = 16;// tmp number of points
-	while (d_n_signal < d_n + d_n_response/2)
-		d_n_signal *= 2;
-
-    d_x = new double[d_n_signal]; //signal
-	d_y = new double[d_n_response]; //response
-
-    if(d_y && d_x)
-	{
-		memset( d_x, 0, d_n_signal * sizeof( double ) );// zero-pad signal data array
-		for(int i=0; i<d_n; i++)
-			d_x[i] = d_table->cell(i, signal_col);
-		for(int i=0; i<d_n_response; i++)
-			d_y[i] = d_table->cell(i, response_col);
-	}
-	else
-	{
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                        tr("Could not allocate memory, operation aborted!"));
-        d_init_err = true;
-		d_n = 0;
-		return false;
-	}
+bool Convolution::setDataFromTable(Table *t, const QString &signalColName,
+                                   const QString &responseColName, int, int) {
+  if (t && d_table != t)
+    d_table = t;
+
+  int signal_col = d_table->colIndex(signalColName);
+  int response_col = d_table->colIndex(responseColName);
+
+  if (signal_col < 0) {
+    QMessageBox::warning(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("The signal data set %1 does not exist!").arg(signalColName));
+    d_init_err = true;
+    return false;
+  } else if (response_col < 0) {
+    QMessageBox::warning(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("The response data set %1 does not exist!").arg(responseColName));
+    d_init_err = true;
+    return false;
+  }
+
+  if (d_n > 0) { // delete previously allocated memory
+    delete[] d_x;
+    delete[] d_y;
+  }
+
+  d_n_response = 0;
+  int rows = d_table->numRows();
+  for (int i = 0; i < rows; i++) {
+    if (!d_table->text(i, response_col).isEmpty())
+      d_n_response++;
+  }
+  if (d_n_response >= rows / 2) {
+    QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()),
+                         tr("MantidPlot") + " - " + tr("Error"),
+                         tr("The response dataset '%1' must be less then half "
+                            "the size of the signal dataset '%2'!")
+                             .arg(responseColName)
+                             .arg(signalColName));
+    d_init_err = true;
+    return false;
+  } else if (d_n_response % 2 == 0) {
+    QMessageBox::warning(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("The response dataset '%1' must contain an odd number of points!")
+            .arg(responseColName));
+    d_init_err = true;
+    return false;
+  }
+
+  d_n = rows;
+
+  d_n_signal = 16; // tmp number of points
+  while (d_n_signal < d_n + d_n_response / 2)
+    d_n_signal *= 2;
+
+  d_x = new double[d_n_signal];   // signal
+  d_y = new double[d_n_response]; // response
+
+  if (d_y && d_x) {
+    memset(d_x, 0, d_n_signal * sizeof(double)); // zero-pad signal data array
+    for (int i = 0; i < d_n; i++)
+      d_x[i] = d_table->cell(i, signal_col);
+    for (int i = 0; i < d_n_response; i++)
+      d_y[i] = d_table->cell(i, response_col);
+  } else {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Could not allocate memory, operation aborted!"));
+    d_init_err = true;
+    d_n = 0;
+    return false;
+  }
 
   return true;
 }
 
-void Convolution::output()
-{
-	convlv(d_x, d_n_signal, d_y, d_n_response, 1);
-	addResultCurve();
-    d_result_table = d_table;
+void Convolution::output() {
+  convlv(d_x, d_n_signal, d_y, d_n_response, 1);
+  addResultCurve();
+  d_result_table = d_table;
 }
 
-void Convolution::addResultCurve()
-{
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    if (!app)
-        return;
-
-	int cols = d_table->numCols();
-	int cols2 = cols+1;
-
-	d_table->addCol();
-	d_table->addCol();
-	QVarLengthArray<double> x_temp(d_n);//double x_temp[d_n];
-	QLocale locale = app->locale();
-	for (int i = 0; i<d_n; i++){
-		double x = i+1;
-		x_temp[i] = x;
-
-		d_table->setText(i, cols, QString::number(x));
-		d_table->setText(i, cols2, locale.toString(d_x[i], 'g', app->d_decimal_digits));
-	}
-
-	QStringList l = d_table->colNames().filter(tr("Index"));
-	QString id = QString::number((int)l.size()+1);
-	QString label = objectName() + id;
-
-	d_table->setColName(cols, tr("Index") + id);
-	d_table->setColName(cols2, label);
-	d_table->setColPlotDesignation(cols, Table::X);
-	d_table->setHeaderColType();
-
-	if (d_graphics_display){
-		if (!d_output_graph)
-			d_output_graph = createOutputGraph()->activeGraph();
-
-    	DataCurve *c = new DataCurve(d_table, d_table->colName(cols), d_table->colName(cols2));
-		c->setData(x_temp.data(), d_x, d_n);//c->setData(x_temp, d_x, d_n);
-    	c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
-		d_output_graph->insertPlotItem(c, Graph::Line);
-		d_output_graph->updatePlot();
-	}
+void Convolution::addResultCurve() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app)
+    return;
+
+  int cols = d_table->numCols();
+  int cols2 = cols + 1;
+
+  d_table->addCol();
+  d_table->addCol();
+  QVarLengthArray<double> x_temp(d_n); // double x_temp[d_n];
+  QLocale locale = app->locale();
+  for (int i = 0; i < d_n; i++) {
+    double x = i + 1;
+    x_temp[i] = x;
+
+    d_table->setText(i, cols, QString::number(x));
+    d_table->setText(i, cols2,
+                     locale.toString(d_x[i], 'g', app->d_decimal_digits));
+  }
+
+  QStringList l = d_table->colNames().filter(tr("Index"));
+  QString id = QString::number((int)l.size() + 1);
+  QString label = objectName() + id;
+
+  d_table->setColName(cols, tr("Index") + id);
+  d_table->setColName(cols2, label);
+  d_table->setColPlotDesignation(cols, Table::X);
+  d_table->setHeaderColType();
+
+  if (d_graphics_display) {
+    if (!d_output_graph)
+      d_output_graph = createOutputGraph()->activeGraph();
+
+    DataCurve *c =
+        new DataCurve(d_table, d_table->colName(cols), d_table->colName(cols2));
+    c->setData(x_temp.data(), d_x, d_n); // c->setData(x_temp, d_x, d_n);
+    c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
+    d_output_graph->insertPlotItem(c, Graph::Line);
+    d_output_graph->updatePlot();
+  }
 }
 
-void Convolution::convlv(double *sig, int n, double *dres, int m, int sign)
-{
-	double *res = new double[n];
-	memset(res,0,n*sizeof(double));
-	int i, m2 = m/2;
-	for (i=0;i<m2;i++)
-	{//store the response in wrap around order, see Numerical Recipes doc
-		res[i] = dres[m2+i];
-		res[n-m2+i] = dres[i];
-	}
-
-	if(m2%2==1)
-		res[m2]=dres[m-1];
-
-	// calculate ffts
-	gsl_fft_real_radix2_transform(res,1,n);
-	gsl_fft_real_radix2_transform(sig,1,n);
-
-	double re, im, size;
-	for (i=0;i<n/2;i++)
-	{// multiply/divide both ffts
-		if(i==0 || i==n/2-1)
-		{
-			if(sign == 1)
-				sig[i] = res[i]*sig[i];
-			else
-				sig[i] = sig[i]/res[i];
-		}
-		else
-		{
-			int ni = n-i;
-			if(sign == 1)
-			{
-				re = res[i]*sig[i]-res[ni]*sig[ni];
-				im = res[i]*sig[ni]+res[ni]*sig[i];
-			}
-			else
-			{
-				size = res[i]*res[i]+res[ni]*res[ni];
-				re = res[i]*sig[i]+res[ni]*sig[ni];
-				im = res[i]*sig[ni]-res[ni]*sig[i];
-				re /= size;
-				im /= size;
-			}
-
-			sig[i] = re;
-			sig[ni] = im;
-		}
-	}
-	delete[] res;
-	gsl_fft_halfcomplex_radix2_inverse(sig,1,n);// inverse fft
+void Convolution::convlv(double *sig, int n, double *dres, int m, int sign) {
+  double *res = new double[n];
+  memset(res, 0, n * sizeof(double));
+  int i, m2 = m / 2;
+  for (i = 0; i < m2; i++) { // store the response in wrap around order, see
+                             // Numerical Recipes doc
+    res[i] = dres[m2 + i];
+    res[n - m2 + i] = dres[i];
+  }
+
+  if (m2 % 2 == 1)
+    res[m2] = dres[m - 1];
+
+  // calculate ffts
+  gsl_fft_real_radix2_transform(res, 1, n);
+  gsl_fft_real_radix2_transform(sig, 1, n);
+
+  double re, im, size;
+  for (i = 0; i < n / 2; i++) { // multiply/divide both ffts
+    if (i == 0 || i == n / 2 - 1) {
+      if (sign == 1)
+        sig[i] = res[i] * sig[i];
+      else
+        sig[i] = sig[i] / res[i];
+    } else {
+      int ni = n - i;
+      if (sign == 1) {
+        re = res[i] * sig[i] - res[ni] * sig[ni];
+        im = res[i] * sig[ni] + res[ni] * sig[i];
+      } else {
+        size = res[i] * res[i] + res[ni] * res[ni];
+        re = res[i] * sig[i] + res[ni] * sig[ni];
+        im = res[i] * sig[ni] - res[ni] * sig[i];
+        re /= size;
+        im /= size;
+      }
+
+      sig[i] = re;
+      sig[ni] = im;
+    }
+  }
+  delete[] res;
+  gsl_fft_halfcomplex_radix2_inverse(sig, 1, n); // inverse fft
 }
- /**************************************************************************
- *             Class Deconvolution                                         *
- ***************************************************************************/
-
-Deconvolution::Deconvolution(ApplicationWindow *parent, Table *t, const QString& signalColName, const QString& responseColName)
-: Convolution(parent, t, signalColName, responseColName)
-{
-	setObjectName(tr("Deconvolution"));
-    setDataFromTable(t, signalColName, responseColName);
+/**************************************************************************
+*             Class Deconvolution                                         *
+***************************************************************************/
+
+Deconvolution::Deconvolution(ApplicationWindow *parent, Table *t,
+                             const QString &signalColName,
+                             const QString &responseColName)
+    : Convolution(parent, t, signalColName, responseColName) {
+  setObjectName(tr("Deconvolution"));
+  setDataFromTable(t, signalColName, responseColName);
 }
 
-void Deconvolution::output()
-{
-	convlv(d_x, signalDataSize(), d_y, responseDataSize(), -1);
-	addResultCurve();
-    d_result_table = d_table;
+void Deconvolution::output() {
+  convlv(d_x, signalDataSize(), d_y, responseDataSize(), -1);
+  addResultCurve();
+  d_result_table = d_table;
 }
diff --git a/MantidPlot/src/Convolution.h b/MantidPlot/src/Convolution.h
index f9136e13e403ce039e7312e7ed73cf984e00e22d..8bbd0a178a9057625edbdfda8270c7634776bed6 100644
--- a/MantidPlot/src/Convolution.h
+++ b/MantidPlot/src/Convolution.h
@@ -31,41 +31,42 @@
 
 #include "Filter.h"
 
-class Convolution : public Filter
-{
-Q_OBJECT
+class Convolution : public Filter {
+  Q_OBJECT
 
 public:
-    Convolution(ApplicationWindow *parent, Table *t, const QString& signalColName, const QString& responseColName);
+  Convolution(ApplicationWindow *parent, Table *t, const QString &signalColName,
+              const QString &responseColName);
 
-    bool setDataFromTable(Table *t, const QString &signalColName,
-                          const QString &responseColName, int = 1,
-                          int = -1) override;
-        //! Returns the size of the signal data set
-	int signalDataSize(){return d_n_signal;};
-	//! Returns the size of the response data set
-	int responseDataSize(){return d_n_response;};
+  bool setDataFromTable(Table *t, const QString &signalColName,
+                        const QString &responseColName, int = 1,
+                        int = -1) override;
+  //! Returns the size of the signal data set
+  int signalDataSize() { return d_n_signal; };
+  //! Returns the size of the response data set
+  int responseDataSize() { return d_n_response; };
 
 protected:
-	//! Handles the graphical output
-	void addResultCurve();
-	//! Performes the convolution of the two data sets and stores the result in the signal data set
-	void convlv(double *sig, int n, double *dres, int m, int sign);
+  //! Handles the graphical output
+  void addResultCurve();
+  //! Performes the convolution of the two data sets and stores the result in
+  // the signal data set
+  void convlv(double *sig, int n, double *dres, int m, int sign);
 
 private:
   void output() override;
-        //! Size of the signal data set
-	int d_n_signal;
-	//! Size of the response data set
-	int d_n_response;
+  //! Size of the signal data set
+  int d_n_signal;
+  //! Size of the response data set
+  int d_n_response;
 };
 
-class Deconvolution : public Convolution
-{
-Q_OBJECT
+class Deconvolution : public Convolution {
+  Q_OBJECT
 
 public:
-    Deconvolution(ApplicationWindow *parent, Table *t, const QString& realColName, const QString& imagColName = QString());
+  Deconvolution(ApplicationWindow *parent, Table *t, const QString &realColName,
+                const QString &imagColName = QString());
 
 private:
   void output() override;
diff --git a/MantidPlot/src/Correlation.cpp b/MantidPlot/src/Correlation.cpp
index 57d6e36cb3958daec473f1b5d7176f1241fe229b..5fa08a18a75602072040a38ee8450ccfb397674c 100644
--- a/MantidPlot/src/Correlation.cpp
+++ b/MantidPlot/src/Correlation.cpp
@@ -36,154 +36,162 @@
 
 #include <gsl/gsl_fft_halfcomplex.h>
 
-Correlation::Correlation(ApplicationWindow *parent, Table *t, const QString& colName1, const QString& colName2, int startRow, int endRow)
-: Filter(parent, t)
-{
-	setObjectName(tr("Correlation"));
-    setDataFromTable(t, colName1, colName2, startRow, endRow);
+Correlation::Correlation(ApplicationWindow *parent, Table *t,
+                         const QString &colName1, const QString &colName2,
+                         int startRow, int endRow)
+    : Filter(parent, t) {
+  setObjectName(tr("Correlation"));
+  setDataFromTable(t, colName1, colName2, startRow, endRow);
 }
 
-bool Correlation::setDataFromTable(Table *t, const QString& colName1, const QString& colName2, int startRow, int endRow)
-{
-    if (!t)
-        return false;
-
-    d_table = t;
-
-    int col1 = d_table->colIndex(colName1);
-	int col2 = d_table->colIndex(colName2);
-
-	if (col1 < 0){
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The data set %1 does not exist!").arg(colName1));
-		d_init_err = true;
-		return false;
-	} else if (col2 < 0){
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-		tr("The data set %1 does not exist!").arg(colName2));
-		d_init_err = true;
-		return false;
-	}
-
-    if (d_n > 0){//delete previousely allocated memory
-		delete[] d_x;
-		delete[] d_y;
-	}
-
-    startRow--; endRow--;
-	if (startRow < 0 || startRow >= t->numRows())
-		startRow = 0;
-	if (endRow < 0 || endRow >= t->numRows())
-		endRow = t->numRows() - 1;
-
-    int from = QMIN(startRow, endRow);
-    int to = QMAX(startRow, endRow);
-
-	int rows = abs(to - from) + 1;
-	d_n = 16; // tmp number of points
-	while (d_n < rows)
-		d_n *= 2;
-
-    d_x = new double[d_n];
-	d_y = new double[d_n];
-
-    if(d_y && d_x){
-		memset( d_x, 0, d_n * sizeof( double ) ); // zero-pad the two arrays...
-		memset( d_y, 0, d_n * sizeof( double ) );
-		for(int i = 0; i< d_n; i++){
-		    int j = i + from;
-			d_x[i] = d_table->cell(j, col1);
-			d_y[i] = d_table->cell(j, col2);
-		}
-	} else {
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                        tr("Could not allocate memory, operation aborted!"));
-        d_init_err = true;
-		d_n = 0;
-		return false;
-	}
-	return true;
+bool Correlation::setDataFromTable(Table *t, const QString &colName1,
+                                   const QString &colName2, int startRow,
+                                   int endRow) {
+  if (!t)
+    return false;
+
+  d_table = t;
+
+  int col1 = d_table->colIndex(colName1);
+  int col2 = d_table->colIndex(colName2);
+
+  if (col1 < 0) {
+    QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()),
+                         tr("MantidPlot") + " - " + tr("Error"),
+                         tr("The data set %1 does not exist!").arg(colName1));
+    d_init_err = true;
+    return false;
+  } else if (col2 < 0) {
+    QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()),
+                         tr("MantidPlot") + " - " + tr("Error"),
+                         tr("The data set %1 does not exist!").arg(colName2));
+    d_init_err = true;
+    return false;
+  }
+
+  if (d_n > 0) { // delete previousely allocated memory
+    delete[] d_x;
+    delete[] d_y;
+  }
+
+  startRow--;
+  endRow--;
+  if (startRow < 0 || startRow >= t->numRows())
+    startRow = 0;
+  if (endRow < 0 || endRow >= t->numRows())
+    endRow = t->numRows() - 1;
+
+  int from = QMIN(startRow, endRow);
+  int to = QMAX(startRow, endRow);
+
+  int rows = abs(to - from) + 1;
+  d_n = 16; // tmp number of points
+  while (d_n < rows)
+    d_n *= 2;
+
+  d_x = new double[d_n];
+  d_y = new double[d_n];
+
+  if (d_y && d_x) {
+    memset(d_x, 0, d_n * sizeof(double)); // zero-pad the two arrays...
+    memset(d_y, 0, d_n * sizeof(double));
+    for (int i = 0; i < d_n; i++) {
+      int j = i + from;
+      d_x[i] = d_table->cell(j, col1);
+      d_y[i] = d_table->cell(j, col2);
+    }
+  } else {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Could not allocate memory, operation aborted!"));
+    d_init_err = true;
+    d_n = 0;
+    return false;
+  }
+  return true;
 }
 
-void Correlation::output()
-{
-    // calculate the FFTs of the two functions
-	if( gsl_fft_real_radix2_transform( d_x, 1, d_n ) == 0 &&
-        gsl_fft_real_radix2_transform( d_y, 1, d_n ) == 0)
-	{
-		for(int i=0; i<d_n/2; i++ ){// multiply the FFT by its complex conjugate
-			if( i==0 || i==(d_n/2)-1 )
-				d_x[i] *= d_x[i];
-			else{
-				int ni = d_n-i;
-				double dReal = d_x[i] * d_y[i] + d_x[ni] * d_y[ni];
-				double dImag = d_x[i] * d_y[ni] - d_x[ni] * d_y[i];
-				d_x[i] = dReal;
-				d_x[ni] = dImag;
-			}
-		}
-	} else {
-		QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                             tr("Error in GSL forward FFT operation!"));
-		return;
-	}
-
-	gsl_fft_halfcomplex_radix2_inverse(d_x, 1, d_n );	//inverse FFT
-
-	addResultCurve();
-    d_result_table = d_table;
+void Correlation::output() {
+  // calculate the FFTs of the two functions
+  if (gsl_fft_real_radix2_transform(d_x, 1, d_n) == 0 &&
+      gsl_fft_real_radix2_transform(d_y, 1, d_n) == 0) {
+    for (int i = 0; i < d_n / 2;
+         i++) { // multiply the FFT by its complex conjugate
+      if (i == 0 || i == (d_n / 2) - 1)
+        d_x[i] *= d_x[i];
+      else {
+        int ni = d_n - i;
+        double dReal = d_x[i] * d_y[i] + d_x[ni] * d_y[ni];
+        double dImag = d_x[i] * d_y[ni] - d_x[ni] * d_y[i];
+        d_x[i] = dReal;
+        d_x[ni] = dImag;
+      }
+    }
+  } else {
+    QMessageBox::warning(dynamic_cast<ApplicationWindow *>(parent()),
+                         tr("MantidPlot") + " - " + tr("Error"),
+                         tr("Error in GSL forward FFT operation!"));
+    return;
+  }
+
+  gsl_fft_halfcomplex_radix2_inverse(d_x, 1, d_n); // inverse FFT
+
+  addResultCurve();
+  d_result_table = d_table;
 }
 
-void Correlation::addResultCurve()
-{
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    if (!app)
-        return;
-
-    QLocale locale = app->locale();
-
-    if (d_n > d_table->numRows())
-        d_table->setNumRows(d_n);
-
-	int cols = d_table->numCols();
-	int cols2 = cols+1;
-	d_table->addCol();
-	d_table->addCol();
-	int n = d_n/2;
-
-	QVarLengthArray<double> x_temp(d_n), y_temp(d_n);//double x_temp[d_n], y_temp[d_n];
-	for (int i = 0; i<d_n; i++){
-	    double x = i - n;
-        x_temp[i] = x;
-
-        double y;
-        if(i < n)
-			y = d_x[n + i];
-		else
-			y = d_x[i - n];
-        y_temp[i] = y;
-
-		d_table->setText(i, cols, QString::number(x));
-		d_table->setText(i, cols2, locale.toString(y, 'g', app->d_decimal_digits));
-	}
-
-	QStringList l = d_table->colNames().filter(tr("Lag"));
-	QString id = QString::number((int)l.size()+1);
-	QString label = objectName() + id;
-
-	d_table->setColName(cols, tr("Lag") + id);
-	d_table->setColName(cols2, label);
-	d_table->setColPlotDesignation(cols, Table::X);
-	d_table->setHeaderColType();
-
-	if (d_graphics_display){
-		if (!d_output_graph)
-			d_output_graph = createOutputGraph()->activeGraph();
-
-    	DataCurve *c = new DataCurve(d_table, d_table->colName(cols), d_table->colName(cols2));
-		c->setData(x_temp.data(), y_temp.data(), d_n);//c->setData(x_temp, y_temp, d_n);
-    	c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
-		d_output_graph->insertPlotItem(c, Graph::Line);
-		d_output_graph->updatePlot();
-	}
+void Correlation::addResultCurve() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app)
+    return;
+
+  QLocale locale = app->locale();
+
+  if (d_n > d_table->numRows())
+    d_table->setNumRows(d_n);
+
+  int cols = d_table->numCols();
+  int cols2 = cols + 1;
+  d_table->addCol();
+  d_table->addCol();
+  int n = d_n / 2;
+
+  QVarLengthArray<double> x_temp(d_n),
+      y_temp(d_n); // double x_temp[d_n], y_temp[d_n];
+  for (int i = 0; i < d_n; i++) {
+    double x = i - n;
+    x_temp[i] = x;
+
+    double y;
+    if (i < n)
+      y = d_x[n + i];
+    else
+      y = d_x[i - n];
+    y_temp[i] = y;
+
+    d_table->setText(i, cols, QString::number(x));
+    d_table->setText(i, cols2, locale.toString(y, 'g', app->d_decimal_digits));
+  }
+
+  QStringList l = d_table->colNames().filter(tr("Lag"));
+  QString id = QString::number((int)l.size() + 1);
+  QString label = objectName() + id;
+
+  d_table->setColName(cols, tr("Lag") + id);
+  d_table->setColName(cols2, label);
+  d_table->setColPlotDesignation(cols, Table::X);
+  d_table->setHeaderColType();
+
+  if (d_graphics_display) {
+    if (!d_output_graph)
+      d_output_graph = createOutputGraph()->activeGraph();
+
+    DataCurve *c =
+        new DataCurve(d_table, d_table->colName(cols), d_table->colName(cols2));
+    c->setData(x_temp.data(), y_temp.data(),
+               d_n); // c->setData(x_temp, y_temp, d_n);
+    c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
+    d_output_graph->insertPlotItem(c, Graph::Line);
+    d_output_graph->updatePlot();
+  }
 }
diff --git a/MantidPlot/src/Correlation.h b/MantidPlot/src/Correlation.h
index 85146bf7489dcd3842b66fe8c9a619bebeb60fda..8541047b8c7e516b156ec981a92986eb86c7ab3e 100644
--- a/MantidPlot/src/Correlation.h
+++ b/MantidPlot/src/Correlation.h
@@ -31,24 +31,23 @@
 
 #include "Filter.h"
 
-class Correlation : public Filter
-{
-Q_OBJECT
+class Correlation : public Filter {
+  Q_OBJECT
 
 public:
-    Correlation(ApplicationWindow *parent, Table *t, const QString& colName1, const QString& colName2, int startRow = 1, int endRow = -1);
+  Correlation(ApplicationWindow *parent, Table *t, const QString &colName1,
+              const QString &colName2, int startRow = 1, int endRow = -1);
 
-    bool setDataFromTable(Table *t, const QString &colName1,
-                          const QString &colName2, int startRow = 1,
-                          int endRow = -1) override;
+  bool setDataFromTable(Table *t, const QString &colName1,
+                        const QString &colName2, int startRow = 1,
+                        int endRow = -1) override;
 
 protected:
-	//! Handles the graphical output
-	void addResultCurve();
+  //! Handles the graphical output
+  void addResultCurve();
 
 private:
   void output() override;
 };
 
 #endif
-
diff --git a/MantidPlot/src/CurveRangeDialog.cpp b/MantidPlot/src/CurveRangeDialog.cpp
index c997714f0b6fa5e23998f1b8952169f2c3a3ace0..4a993e387eb5b844da4aff6a9b9d6c6197b3a140 100644
--- a/MantidPlot/src/CurveRangeDialog.cpp
+++ b/MantidPlot/src/CurveRangeDialog.cpp
@@ -38,78 +38,74 @@
 #include <QLabel>
 #include <QSpinBox>
 
-CurveRangeDialog::CurveRangeDialog(QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ), d_curve(NULL), d_graph(NULL)
-{
-    setWindowTitle(tr("MantidPlot - Plot range"));
-    setObjectName( "CurveRangeDialog" );
-
-    QGroupBox *gb1 = new QGroupBox();
-    QGridLayout *gl1 = new QGridLayout(gb1);
-    gl1->addWidget(new QLabel(tr("Data set: ")), 0, 0);
-
-    boxName = new QLabel();
-    gl1->addWidget(boxName, 0, 1);
-
-    gl1->addWidget(new QLabel(tr("From row number")), 1, 0);
-    boxStart = new QSpinBox();
-    boxStart->setMinimum(1);
-    gl1->addWidget(boxStart, 1, 1);
-
-    gl1->addWidget(new QLabel(tr("To row number")), 2, 0);
-    boxEnd = new QSpinBox();
-    boxEnd->setMinimum(1);
-    gl1->addWidget(boxEnd, 2, 1);
-    gl1->setRowStretch(3, 1);
-
-    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);
-
-    QVBoxLayout *vb = new QVBoxLayout(this);
-    vb->addWidget(gb1);
-    vb->addLayout(hl);
-
-    connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
-    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+CurveRangeDialog::CurveRangeDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), d_curve(NULL), d_graph(NULL) {
+  setWindowTitle(tr("MantidPlot - Plot range"));
+  setObjectName("CurveRangeDialog");
+
+  QGroupBox *gb1 = new QGroupBox();
+  QGridLayout *gl1 = new QGridLayout(gb1);
+  gl1->addWidget(new QLabel(tr("Data set: ")), 0, 0);
+
+  boxName = new QLabel();
+  gl1->addWidget(boxName, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("From row number")), 1, 0);
+  boxStart = new QSpinBox();
+  boxStart->setMinimum(1);
+  gl1->addWidget(boxStart, 1, 1);
+
+  gl1->addWidget(new QLabel(tr("To row number")), 2, 0);
+  boxEnd = new QSpinBox();
+  boxEnd->setMinimum(1);
+  gl1->addWidget(boxEnd, 2, 1);
+  gl1->setRowStretch(3, 1);
+
+  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);
+
+  QVBoxLayout *vb = new QVBoxLayout(this);
+  vb->addWidget(gb1);
+  vb->addLayout(hl);
+
+  connect(buttonOK, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void CurveRangeDialog::accept()
-{
-	if (!d_curve)
-		return;
-
-	int start = boxStart->value() - 1;
-	int end = boxEnd->value() - 1;
-	d_curve->setRowRange(QMIN(start, end), QMAX(start, end));
-	d_graph->updatePlot();
-	d_graph->notifyChanges();
-	close();
+void CurveRangeDialog::accept() {
+  if (!d_curve)
+    return;
+
+  int start = boxStart->value() - 1;
+  int end = boxEnd->value() - 1;
+  d_curve->setRowRange(QMIN(start, end), QMAX(start, end));
+  d_graph->updatePlot();
+  d_graph->notifyChanges();
+  close();
 }
 
-void CurveRangeDialog::setCurveToModify(Graph *g, int curve)
-{
-	if (!g)
-		return;
-
-	d_graph = g;
-    d_curve = dynamic_cast<DataCurve *>(d_graph->curve(curve));
-	if (!d_curve)
-		return;
-
-    Table *t = d_curve->table();
-	if (t)
-	{
-		boxStart->setMaximum(t->numRows());
-		boxEnd->setMaximum(t->numRows());
-	}
-
-	boxName->setText(d_curve->title().text());
-	boxStart->setValue(d_curve->startRow() + 1);
-	boxEnd->setValue(d_curve->endRow() + 1);
+void CurveRangeDialog::setCurveToModify(Graph *g, int curve) {
+  if (!g)
+    return;
+
+  d_graph = g;
+  d_curve = dynamic_cast<DataCurve *>(d_graph->curve(curve));
+  if (!d_curve)
+    return;
+
+  Table *t = d_curve->table();
+  if (t) {
+    boxStart->setMaximum(t->numRows());
+    boxEnd->setMaximum(t->numRows());
+  }
+
+  boxName->setText(d_curve->title().text());
+  boxStart->setValue(d_curve->startRow() + 1);
+  boxEnd->setValue(d_curve->endRow() + 1);
 }
diff --git a/MantidPlot/src/CurveRangeDialog.h b/MantidPlot/src/CurveRangeDialog.h
index e7ad448138c9eaac86d4ba5c52cf266613e22533..e3cb108f56709592d4307e82625fe113ea4983af 100644
--- a/MantidPlot/src/CurveRangeDialog.h
+++ b/MantidPlot/src/CurveRangeDialog.h
@@ -38,26 +38,25 @@ class Graph;
 class DataCurve;
 
 //! Curve range dialog
-class CurveRangeDialog : public QDialog
-{
-    Q_OBJECT
+class CurveRangeDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    CurveRangeDialog(QWidget* parent = 0, Qt::WFlags fl = 0 );
+  CurveRangeDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void setCurveToModify(Graph *g, int curve);
-        void accept() override;
+  void setCurveToModify(Graph *g, int curve);
+  void accept() override;
 
 private:
-	DataCurve *d_curve;
-	Graph *d_graph;
-
-    QPushButton* buttonOK;
-	QPushButton* buttonCancel;
-	QLabel* boxName;
-	QSpinBox* boxStart;
-	QSpinBox* boxEnd;
+  DataCurve *d_curve;
+  Graph *d_graph;
+
+  QPushButton *buttonOK;
+  QPushButton *buttonCancel;
+  QLabel *boxName;
+  QSpinBox *boxStart;
+  QSpinBox *boxEnd;
 };
 
 #endif
diff --git a/MantidPlot/src/CurvesDialog.cpp b/MantidPlot/src/CurvesDialog.cpp
index 3e6c042a6c536d1adb2b3d7c8281289502098421..12dda938ef6ce0f97318966ffcf8f5834b0e23bd 100644
--- a/MantidPlot/src/CurvesDialog.cpp
+++ b/MantidPlot/src/CurvesDialog.cpp
@@ -2,7 +2,8 @@
     File                 : CurvesDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Add/remove curves dialog
 
@@ -51,17 +52,14 @@
 
 #include <QMessageBox>
 
-
-CurvesDialog::CurvesDialog( ApplicationWindow* app, Graph* g, Qt::WFlags fl )
-  : QDialog( g, fl ),
-    d_app(app),
-    d_graph(g)
-{
+CurvesDialog::CurvesDialog(ApplicationWindow *app, Graph *g, Qt::WFlags fl)
+    : QDialog(g, fl), d_app(app), d_graph(g) {
   if (!app) {
-    throw std::logic_error("Null ApplicationWindow pointer is passed to CurvesDialog.");
+    throw std::logic_error(
+        "Null ApplicationWindow pointer is passed to CurvesDialog.");
   }
-  setObjectName( "CurvesDialog" );
-  setWindowTitle( tr( "MantidPlot - Add/Remove curves" ) );
+  setObjectName("CurvesDialog");
+  setWindowTitle(tr("MantidPlot - Add/Remove curves"));
   setSizeGripEnabled(true);
   setFocus();
 
@@ -69,103 +67,110 @@ CurvesDialog::CurvesDialog( ApplicationWindow* app, Graph* g, Qt::WFlags fl )
 
   hl->addWidget(new QLabel(tr("New curves style")));
   boxStyle = new QComboBox();
-  boxStyle->addItem( getQPixmap("lPlot_xpm"), tr( " Line" ) );
-  boxStyle->addItem( getQPixmap("pPlot_xpm"), tr( " Scatter" ) );
-  boxStyle->addItem( getQPixmap("lpPlot_xpm"), tr( " Line + Symbol" ) );
-  boxStyle->addItem( getQPixmap("dropLines_xpm"), tr( " Vertical drop lines" ) );
-  boxStyle->addItem( getQPixmap("spline_xpm"), tr( " Spline" ) );
-  boxStyle->addItem( getQPixmap("hor_steps_xpm"), tr( " Horizontal steps" ) );
-  boxStyle->addItem( getQPixmap("vert_steps_xpm"), tr( " Vertical steps" ) );
-  boxStyle->addItem( getQPixmap("area_xpm"), tr( " Area" ) );
-  boxStyle->addItem( getQPixmap("vertBars_xpm"), tr( " Vertical Bars" ) );
-  boxStyle->addItem( getQPixmap("hBars_xpm"), tr( " Horizontal Bars" ) );
+  boxStyle->addItem(getQPixmap("lPlot_xpm"), tr(" Line"));
+  boxStyle->addItem(getQPixmap("pPlot_xpm"), tr(" Scatter"));
+  boxStyle->addItem(getQPixmap("lpPlot_xpm"), tr(" Line + Symbol"));
+  boxStyle->addItem(getQPixmap("dropLines_xpm"), tr(" Vertical drop lines"));
+  boxStyle->addItem(getQPixmap("spline_xpm"), tr(" Spline"));
+  boxStyle->addItem(getQPixmap("hor_steps_xpm"), tr(" Horizontal steps"));
+  boxStyle->addItem(getQPixmap("vert_steps_xpm"), tr(" Vertical steps"));
+  boxStyle->addItem(getQPixmap("area_xpm"), tr(" Area"));
+  boxStyle->addItem(getQPixmap("vertBars_xpm"), tr(" Vertical Bars"));
+  boxStyle->addItem(getQPixmap("hBars_xpm"), tr(" Horizontal Bars"));
   hl->addWidget(boxStyle);
 
   boxMatrixStyle = new QComboBox();
-  boxMatrixStyle->addItem( getQPixmap("color_map_xpm"), tr("Contour - Color Fill"));
-  boxMatrixStyle->addItem( getQPixmap("contour_map_xpm"), tr("Contour Lines"));
-  boxMatrixStyle->addItem( getQPixmap("gray_map_xpm"), tr("Gray Scale Map"));
-  boxMatrixStyle->addItem( getQPixmap("histogram_xpm"), tr("Histogram"));
+  boxMatrixStyle->addItem(getQPixmap("color_map_xpm"),
+                          tr("Contour - Color Fill"));
+  boxMatrixStyle->addItem(getQPixmap("contour_map_xpm"), tr("Contour Lines"));
+  boxMatrixStyle->addItem(getQPixmap("gray_map_xpm"), tr("Gray Scale Map"));
+  boxMatrixStyle->addItem(getQPixmap("histogram_xpm"), tr("Histogram"));
   boxMatrixStyle->hide();
   hl->addWidget(boxMatrixStyle);
   hl->addStretch();
 
   QGridLayout *gl = new QGridLayout();
-  gl->addWidget(new QLabel( tr( "Available data" )), 0, 0);
-  gl->addWidget(new QLabel( tr( "Graph contents" )), 0, 2);
+  gl->addWidget(new QLabel(tr("Available data")), 0, 0);
+  gl->addWidget(new QLabel(tr("Graph contents")), 0, 2);
 
   available = new QListWidget();
-  available->setSelectionMode (QAbstractItemView::ExtendedSelection);
+  available->setSelectionMode(QAbstractItemView::ExtendedSelection);
   gl->addWidget(available, 1, 0);
 
-  //add button (move to graph contents)
-  QVBoxLayout* vl1 = new QVBoxLayout();
+  // add button (move to graph contents)
+  QVBoxLayout *vl1 = new QVBoxLayout();
   btnAdd = new QPushButton();
-  btnAdd->setIcon( getQPixmap("next_xpm") );
-  btnAdd->setFixedWidth (35);
-  btnAdd->setFixedHeight (30);
+  btnAdd->setIcon(getQPixmap("next_xpm"));
+  btnAdd->setFixedWidth(35);
+  btnAdd->setFixedHeight(30);
   vl1->addWidget(btnAdd);
 
-  //remove button (move to available data)
+  // remove button (move to available data)
   btnRemove = new QPushButton();
-  btnRemove->setIcon( getQPixmap("prev_xpm") );
-  btnRemove->setFixedWidth (35);
+  btnRemove->setIcon(getQPixmap("prev_xpm"));
+  btnRemove->setFixedWidth(35);
   btnRemove->setFixedHeight(30);
   vl1->addWidget(btnRemove);
   vl1->addStretch();
 
   gl->addLayout(vl1, 1, 1);
   contents = new QListWidget();
-  contents->setSelectionMode (QAbstractItemView::ExtendedSelection);
+  contents->setSelectionMode(QAbstractItemView::ExtendedSelection);
   gl->addWidget(contents, 1, 2);
 
-  QVBoxLayout* vl2 = new QVBoxLayout();
-  btnAssociations = new QPushButton(tr( "&Plot Associations..." ));
+  QVBoxLayout *vl2 = new QVBoxLayout();
+  btnAssociations = new QPushButton(tr("&Plot Associations..."));
   btnAssociations->setEnabled(false);
   vl2->addWidget(btnAssociations);
 
-  btnRange = new QPushButton(tr( "Edit &Range..." ));
+  btnRange = new QPushButton(tr("Edit &Range..."));
   btnRange->setEnabled(false);
   vl2->addWidget(btnRange);
 
-  btnEditFunction = new QPushButton(tr( "&Edit Function..." ));
+  btnEditFunction = new QPushButton(tr("&Edit Function..."));
   btnEditFunction->setEnabled(false);
   vl2->addWidget(btnEditFunction);
 
-  btnOK = new QPushButton(tr( "OK" ));
+  btnOK = new QPushButton(tr("OK"));
   vl2->addWidget(btnOK);
 
-  btnCancel = new QPushButton(tr( "Close" ));
+  btnCancel = new QPushButton(tr("Close"));
   vl2->addWidget(btnCancel);
 
-  boxShowRange = new QCheckBox(tr( "&Show Range" ));
+  boxShowRange = new QCheckBox(tr("&Show Range"));
   vl2->addWidget(boxShowRange);
 
   vl2->addStretch();
   gl->addLayout(vl2, 1, 3);
 
-  QVBoxLayout* vl3 = new QVBoxLayout(this);
+  QVBoxLayout *vl3 = new QVBoxLayout(this);
   vl3->addLayout(hl);
   vl3->addLayout(gl);
 
-  boxShowCurrentFolder = new QCheckBox(tr("Show current &folder only" ));
+  boxShowCurrentFolder = new QCheckBox(tr("Show current &folder only"));
   vl3->addWidget(boxShowCurrentFolder);
 
   init();
 
-  connect(boxShowCurrentFolder, SIGNAL(toggled(bool)), this, SLOT(showCurrentFolder(bool)));
-  connect(boxShowRange, SIGNAL(toggled(bool)), this, SLOT(showCurveRange(bool)));
-  connect(btnRange, SIGNAL(clicked()),this, SLOT(showCurveRangeDialog()));
-  connect(btnAssociations, SIGNAL(clicked()),this, SLOT(showPlotAssociations()));
-  connect(btnEditFunction, SIGNAL(clicked()),this, SLOT(showFunctionDialog()));
-  connect(btnAdd, SIGNAL(clicked()),this, SLOT(addCurves()));
-  connect(btnRemove, SIGNAL(clicked()),this, SLOT(removeCurves()));
-  connect(btnOK, SIGNAL(clicked()),this, SLOT(close())); 
-  connect(btnCancel, SIGNAL(clicked()),this, SLOT(close()));
+  connect(boxShowCurrentFolder, SIGNAL(toggled(bool)), this,
+          SLOT(showCurrentFolder(bool)));
+  connect(boxShowRange, SIGNAL(toggled(bool)), this,
+          SLOT(showCurveRange(bool)));
+  connect(btnRange, SIGNAL(clicked()), this, SLOT(showCurveRangeDialog()));
+  connect(btnAssociations, SIGNAL(clicked()), this,
+          SLOT(showPlotAssociations()));
+  connect(btnEditFunction, SIGNAL(clicked()), this, SLOT(showFunctionDialog()));
+  connect(btnAdd, SIGNAL(clicked()), this, SLOT(addCurves()));
+  connect(btnRemove, SIGNAL(clicked()), this, SLOT(removeCurves()));
+  connect(btnOK, SIGNAL(clicked()), this, SLOT(close()));
+  connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
   connect(contents, SIGNAL(itemSelectionChanged()), this, SLOT(enableBtnOK()));
-  connect(contents, SIGNAL(currentRowChanged(int)), this, SLOT(showCurveBtn(int)));
-  connect(contents, SIGNAL(itemSelectionChanged()), this, SLOT(enableRemoveBtn()));
-  connect(available, SIGNAL(itemSelectionChanged()), this, SLOT(enableAddBtn()));
+  connect(contents, SIGNAL(currentRowChanged(int)), this,
+          SLOT(showCurveBtn(int)));
+  connect(contents, SIGNAL(itemSelectionChanged()), this,
+          SLOT(enableRemoveBtn()));
+  connect(available, SIGNAL(itemSelectionChanged()), this,
+          SLOT(enableAddBtn()));
 
   QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), this);
   connect(shortcut, SIGNAL(activated()), this, SLOT(removeCurves()));
@@ -177,25 +182,21 @@ CurvesDialog::CurvesDialog( ApplicationWindow* app, Graph* g, Qt::WFlags fl )
   setGraph(g);
 }
 
-CurvesDialog::~CurvesDialog()
-{
+CurvesDialog::~CurvesDialog() {
   // Delete our local copies of the curves
-  QMap<QString,PlotCurve*>::iterator it;
-  for ( it = d_plotCurves.begin(); it != d_plotCurves.end() ; ++it)
-  {
+  QMap<QString, PlotCurve *>::iterator it;
+  for (it = d_plotCurves.begin(); it != d_plotCurves.end(); ++it) {
     delete it.value();
   }
 }
 
-void CurvesDialog::showCurveBtn(int)
-{
+void CurvesDialog::showCurveBtn(int) {
   QwtPlotItem *it = d_graph->plotItem(contents->currentRow());
   if (!it)
     return;
 
-  if ( it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram ||
-       it->rtti() == QwtPlotItem::Rtti_PlotUserItem )
-  {
+  if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram ||
+      it->rtti() == QwtPlotItem::Rtti_PlotUserItem) {
     btnEditFunction->setEnabled(false);
     btnAssociations->setEnabled(false);
     btnRange->setEnabled(false);
@@ -203,8 +204,7 @@ void CurvesDialog::showCurveBtn(int)
   }
 
   PlotCurve *c = dynamic_cast<PlotCurve *>(it);
-  if (c && c->type() == Graph::Function)
-  {
+  if (c && c->type() == Graph::Function) {
     btnEditFunction->setEnabled(true);
     btnAssociations->setEnabled(false);
     btnRange->setEnabled(false);
@@ -218,8 +218,7 @@ void CurvesDialog::showCurveBtn(int)
     btnRange->setEnabled(false);
 }
 
-void CurvesDialog::showCurveRangeDialog()
-{
+void CurvesDialog::showCurveRangeDialog() {
   int curve = contents->currentRow();
   if (curve < 0)
     curve = 0;
@@ -228,8 +227,7 @@ void CurvesDialog::showCurveRangeDialog()
   updateCurveRange();
 }
 
-void CurvesDialog::showPlotAssociations()
-{
+void CurvesDialog::showPlotAssociations() {
   int curve = contents->currentRow();
   if (curve < 0)
     curve = 0;
@@ -239,25 +237,19 @@ void CurvesDialog::showPlotAssociations()
   d_app->showPlotAssociations(curve);
 }
 
-void CurvesDialog::showFunctionDialog()
-{
+void CurvesDialog::showFunctionDialog() {
   int currentRow = contents->currentRow();
   close();
 
   d_app->showFunctionDialog(d_graph, currentRow);
 }
 
-QSize CurvesDialog::sizeHint() const
-{
-  return QSize(700, 400);
-}
+QSize CurvesDialog::sizeHint() const { return QSize(700, 400); }
 
-void CurvesDialog::contextMenuEvent(QContextMenuEvent *e)
-{
+void CurvesDialog::contextMenuEvent(QContextMenuEvent *e) {
   QPoint pos = available->viewport()->mapFromGlobal(QCursor::pos());
   QRect rect = available->visualItemRect(available->currentItem());
-  if (rect.contains(pos))
-  {
+  if (rect.contains(pos)) {
     QMenu contextMenu(this);
     QList<QListWidgetItem *> lst = available->selectedItems();
     if (lst.size() > 1)
@@ -269,13 +261,13 @@ void CurvesDialog::contextMenuEvent(QContextMenuEvent *e)
 
   pos = contents->viewport()->mapFromGlobal(QCursor::pos());
   rect = contents->visualItemRect(contents->currentItem());
-  if (rect.contains(pos))
-  {
+  if (rect.contains(pos)) {
     QMenu contextMenu(this);
     QList<QListWidgetItem *> lst = contents->selectedItems();
-    
-	if (lst.size() > 1)
-      contextMenu.addAction(tr("&Delete Selection"), this, SLOT(removeCurves()));
+
+    if (lst.size() > 1)
+      contextMenu.addAction(tr("&Delete Selection"), this,
+                            SLOT(removeCurves()));
     else if (lst.size() > 0)
       contextMenu.addAction(tr("&Delete Curve"), this, SLOT(removeCurves()));
     contextMenu.exec(QCursor::pos());
@@ -283,15 +275,13 @@ void CurvesDialog::contextMenuEvent(QContextMenuEvent *e)
   e->accept();
 }
 
-
-void CurvesDialog::init()
-{
+void CurvesDialog::init() {
   bool currentFolderOnly = d_app->d_show_current_folder;
   boxShowCurrentFolder->setChecked(currentFolderOnly);
   showCurrentFolder(currentFolderOnly);
 
   QStringList matrices = d_app->matrixNames();
-  if (!matrices.isEmpty ()){
+  if (!matrices.isEmpty()) {
     boxMatrixStyle->show();
     available->addItems(matrices);
   }
@@ -319,24 +309,21 @@ void CurvesDialog::init()
     boxStyle->setCurrentIndex(9);
 
   QList<MdiSubWindow *> wList = d_app->windowsList();
-  foreach(MdiSubWindow* w, wList)
-  {
-    MultiLayer* ml = dynamic_cast<MultiLayer*>(w);
-    if (ml)// layers are numbered starting from 1
+  foreach (MdiSubWindow *w, wList) {
+    MultiLayer *ml = dynamic_cast<MultiLayer *>(w);
+    if (ml) // layers are numbered starting from 1
     {
-      for(int i=1;i<=ml->layers();i++)
-      {
-        Graph* g = ml->layer(i);
-        if (g)
-        {
-          for(int j=0;j<g->curves();j++)
-          {
-            MantidMatrixCurve* c = dynamic_cast<MantidMatrixCurve*>(g->curve(j));
-            if (c)
-            {
+      for (int i = 1; i <= ml->layers(); i++) {
+        Graph *g = ml->layer(i);
+        if (g) {
+          for (int j = 0; j < g->curves(); j++) {
+            MantidMatrixCurve *c =
+                dynamic_cast<MantidMatrixCurve *>(g->curve(j));
+            if (c) {
               available->addItem(c->title().text());
               // Store copies of the curves
-              // Necessary because a curve is deleted when it's removed from a plot
+              // Necessary because a curve is deleted when it's removed from a
+              // plot
               d_plotCurves[c->title().text()] = c->clone(g);
               ml->setCloseOnEmpty(false);
             }
@@ -350,8 +337,7 @@ void CurvesDialog::init()
     btnAdd->setDisabled(true);
 }
 
-void CurvesDialog::setGraph(Graph *graph)
-{
+void CurvesDialog::setGraph(Graph *graph) {
   QList<QListWidgetItem *> lst = available->selectedItems();
   d_graph = graph;
   contents->addItems(d_graph->plotItemsList());
@@ -359,13 +345,12 @@ void CurvesDialog::setGraph(Graph *graph)
   enableAddBtn();
 }
 
-void CurvesDialog::addCurves()
-{
+void CurvesDialog::addCurves() {
   QStringList emptyColumns;
   QList<QListWidgetItem *> lst = available->selectedItems();
-  for (int i = 0; i < lst.size(); ++i){
+  for (int i = 0; i < lst.size(); ++i) {
     QString text = lst.at(i)->text();
-    if (contents->findItems(text, Qt::MatchExactly ).isEmpty ()){
+    if (contents->findItems(text, Qt::MatchExactly).isEmpty()) {
       if (!addCurve(text))
         emptyColumns << text;
     }
@@ -376,16 +361,14 @@ void CurvesDialog::addCurves()
   showCurveRange(boxShowRange->isChecked());
 }
 
-bool CurvesDialog::addCurve(const QString& name)
-{
+bool CurvesDialog::addCurve(const QString &name) {
   QStringList matrices = d_app->matrixNames();
-  if (matrices.contains(name)){
+  if (matrices.contains(name)) {
     Matrix *m = d_app->matrix(name);
     if (!m)
       return false;
 
-    switch (boxMatrixStyle->currentIndex())
-    {
+    switch (boxMatrixStyle->currentIndex()) {
     case 0:
       d_graph->plotSpectrogram(m, Graph::ColorMap);
       break;
@@ -405,8 +388,8 @@ bool CurvesDialog::addCurve(const QString& name)
   }
 
   int style = curveStyle();
-  Table* t = d_app->table(name);
-  if (t){
+  Table *t = d_app->table(name);
+  if (t) {
     PlotCurve *c = d_graph->insertCurve(t, name, style);
     CurveLayout cl = Graph::initCurveLayout();
     int color, symbol;
@@ -421,58 +404,54 @@ bool CurvesDialog::addCurve(const QString& name)
 
     if (style == Graph::Line)
       cl.sType = 0;
-    else if (style==Graph::VerticalBars || style==Graph::HorizontalBars ){
-      cl.filledArea=1;
-      cl.lCol=0;
-      cl.aCol=color;
+    else if (style == Graph::VerticalBars || style == Graph::HorizontalBars) {
+      cl.filledArea = 1;
+      cl.lCol = 0;
+      cl.aCol = color;
       cl.sType = 0;
-    } else if (style==Graph::Area ){
-      cl.filledArea=1;
-      cl.aCol=color;
+    } else if (style == Graph::Area) {
+      cl.filledArea = 1;
+      cl.aCol = color;
       cl.sType = 0;
     } else if (style == Graph::VerticalDropLines)
-      cl.connectType=2;
-    else if (style == Graph::VerticalSteps || style == Graph::HorizontalSteps){
-      cl.connectType=3;
+      cl.connectType = 2;
+    else if (style == Graph::VerticalSteps || style == Graph::HorizontalSteps) {
+      cl.connectType = 3;
       cl.sType = 0;
     } else if (style == Graph::Spline)
-      cl.connectType=5;
+      cl.connectType = 5;
 
     d_graph->updateCurveLayout(c, &cl);
     contents->addItem(name);
     return true;
   }
 
-  if (d_plotCurves.find(name) != d_plotCurves.end())
-  {
+  if (d_plotCurves.find(name) != d_plotCurves.end()) {
     d_graph->insertCurve(d_plotCurves[name]->clone(d_graph));
     return true;
   }
   return false;
 }
 
-
 /**Remove curves function
 *
 */
-void CurvesDialog::removeCurves()
-{
+void CurvesDialog::removeCurves() {
   int count = contents->count();
   QList<QListWidgetItem *> lst = contents->selectedItems();
-  
-  //disables user from deleting last graph from the graph
-  if(count == 1 || count == lst.size()) {
-  QMessageBox::warning( 
-    this, 
-    tr("Cannot Delete"), 
-    tr("There should be at least one graph plotted in the graph contents ") );
-	return; 
+
+  // disables user from deleting last graph from the graph
+  if (count == 1 || count == lst.size()) {
+    QMessageBox::warning(this, tr("Cannot Delete"),
+                         tr("There should be at least one graph plotted in the "
+                            "graph contents "));
+    return;
   }
-  
-  for (int i = 0; i < lst.size(); ++i){
+
+  for (int i = 0; i < lst.size(); ++i) {
     QListWidgetItem *it = lst.at(i);
     QString s = it->text();
-    if (boxShowRange->isChecked()){
+    if (boxShowRange->isChecked()) {
       QStringList lst = s.split("[");
       s = lst[0];
     }
@@ -483,138 +462,133 @@ void CurvesDialog::removeCurves()
   d_graph->updatePlot();
 }
 
-/** Enable Disable buttons function 
+/** Enable Disable buttons function
 *
 */
-void CurvesDialog::enableAddBtn()
-{
-  btnAdd->setEnabled (available->count()>0 && !available->selectedItems().isEmpty());
+void CurvesDialog::enableAddBtn() {
+  btnAdd->setEnabled(available->count() > 0 &&
+                     !available->selectedItems().isEmpty());
 }
 
-/** Enables or disables the button when appopriate number of graphs are in graph contents
+/** Enables or disables the button when appopriate number of graphs are in graph
+*contents
 *
 */
-void CurvesDialog::enableRemoveBtn()
-{ 
-  btnRemove->setEnabled (contents->count()>1 && !contents->selectedItems().isEmpty());
+void CurvesDialog::enableRemoveBtn() {
+  btnRemove->setEnabled(contents->count() > 1 &&
+                        !contents->selectedItems().isEmpty());
 }
 
 /** Enables btnOK when there is even one graph plotted in graph contents area
 *
 */
-void CurvesDialog::enableBtnOK(){
-  btnOK->setEnabled (contents->count()>0 && !contents->selectedItems().isEmpty());
+void CurvesDialog::enableBtnOK() {
+  btnOK->setEnabled(contents->count() > 0 &&
+                    !contents->selectedItems().isEmpty());
 }
 
-int CurvesDialog::curveStyle()
-{
+int CurvesDialog::curveStyle() {
   int style = 0;
-  switch (boxStyle->currentIndex())
-  {
- case 0:
+  switch (boxStyle->currentIndex()) {
+  case 0:
     style = Graph::Line;
     break;
- case 1:
+  case 1:
     style = Graph::Scatter;
     break;
- case 2:
+  case 2:
     style = Graph::LineSymbols;
     break;
- case 3:
+  case 3:
     style = Graph::VerticalDropLines;
     break;
- case 4:
+  case 4:
     style = Graph::Spline;
     break;
- case 5:
+  case 5:
     style = Graph::VerticalSteps;
     break;
- case 6:
+  case 6:
     style = Graph::HorizontalSteps;
     break;
- case 7:
+  case 7:
     style = Graph::Area;
     break;
- case 8:
+  case 8:
     style = Graph::VerticalBars;
     break;
- case 9:
+  case 9:
     style = Graph::HorizontalBars;
     break;
   }
   return style;
 }
 
-void CurvesDialog::showCurveRange(bool on)
-{
+void CurvesDialog::showCurveRange(bool on) {
   int row = contents->currentRow();
   contents->clear();
-  if (on){
+  if (on) {
     QStringList lst = QStringList();
-    for (int i=0; i<d_graph->curves(); i++){
+    for (int i = 0; i < d_graph->curves(); i++) {
       QwtPlotItem *it = d_graph->plotItem(i);
       if (!it)
         continue;
 
       auto plotCurve = dynamic_cast<PlotCurve *>(it);
-      if (plotCurve && plotCurve->type() != Graph::Function){
+      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) + "]";
+          lst << c->title().text() + "[" + QString::number(c->startRow() + 1) +
+                     ":" + QString::number(c->endRow() + 1) + "]";
         }
       } else
         lst << it->title().text();
     }
     contents->addItems(lst);
-  }
-  else
+  } else
     contents->addItems(d_graph->plotItemsList());
 
   contents->setCurrentRow(row);
   enableRemoveBtn();
 }
 
-void CurvesDialog::updateCurveRange()
-{
+void CurvesDialog::updateCurveRange() {
   showCurveRange(boxShowRange->isChecked());
 }
 
-void CurvesDialog::showCurrentFolder(bool currentFolder)
-{
+void CurvesDialog::showCurrentFolder(bool currentFolder) {
   d_app->d_show_current_folder = currentFolder;
   available->clear();
-  if (currentFolder){
+  if (currentFolder) {
     Folder *f = d_app->currentFolder();
-    if (f){
+    if (f) {
       QStringList columns;
-      foreach (QWidget *w, f->windowsList()){
+      foreach (QWidget *w, f->windowsList()) {
         if (!w->inherits("Table"))
           continue;
 
         if (Table *t = dynamic_cast<Table *>(w)) {
-          for (int i=0; i < t->numCols(); i++){
-            if(t->colPlotDesignation(i) == Table::Y)
+          for (int i = 0; i < t->numCols(); i++) {
+            if (t->colPlotDesignation(i) == Table::Y)
               columns << QString(t->objectName()) + "_" + t->colLabel(i);
           }
         }
       }
       available->addItems(columns);
     }
-  }
-  else
+  } else
     available->addItems(d_app->columnsList(Table::Y));
 }
 
-void CurvesDialog::closeEvent(QCloseEvent* e)
-{
+void CurvesDialog::closeEvent(QCloseEvent *e) {
   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);
+  foreach (MdiSubWindow *w, wList) {
+    MultiLayer *ml = dynamic_cast<MultiLayer *>(w);
+    if (ml)
+      ml->setCloseOnEmpty(true);
   }
   e->accept();
 }
diff --git a/MantidPlot/src/CurvesDialog.h b/MantidPlot/src/CurvesDialog.h
index 2bd2615db28a4410133adb946bbb1ce0debff4bf..1d6a924f91b3f536f15805cb68d3d045805504bb 100644
--- a/MantidPlot/src/CurvesDialog.h
+++ b/MantidPlot/src/CurvesDialog.h
@@ -2,7 +2,8 @@
     File                 : CurvesDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Add/remove curves dialog
 
@@ -41,12 +42,11 @@ class PlotCurve;
 class ApplicationWindow;
 
 //! Add/remove curves dialog
-class CurvesDialog : public QDialog
-{
+class CurvesDialog : public QDialog {
   Q_OBJECT
 
 public:
-  CurvesDialog( ApplicationWindow* app, Graph* g, Qt::WFlags fl = 0 );
+  CurvesDialog(ApplicationWindow *app, Graph *g, Qt::WFlags fl = 0);
   ~CurvesDialog() override;
 
 private slots:
@@ -64,33 +64,32 @@ private slots:
   void updateCurveRange();
   void showCurrentFolder(bool);
 
-
 private:
   void setGraph(Graph *graph);
   void closeEvent(QCloseEvent *) override;
 
-  void init();	
-  bool addCurve(const QString& name);
+  void init();
+  bool addCurve(const QString &name);
   QSize sizeHint() const override;
   void contextMenuEvent(QContextMenuEvent *) override;
 
-  ApplicationWindow* d_app;
+  ApplicationWindow *d_app;
   Graph *d_graph;
 
-  QPushButton* btnAdd;
-  QPushButton* btnRemove;
-  QPushButton* btnOK;
-  QPushButton* btnCancel;
-  QPushButton* btnAssociations;
-  QPushButton* btnEditFunction;
-  QPushButton* btnRange;
-  QListWidget* available;
-  QListWidget* contents;
-  QComboBox* boxStyle;
-  QComboBox* boxMatrixStyle;
-  QCheckBox* boxShowRange;
-  QCheckBox* boxShowCurrentFolder;
-  QMap<QString,PlotCurve*> d_plotCurves;
+  QPushButton *btnAdd;
+  QPushButton *btnRemove;
+  QPushButton *btnOK;
+  QPushButton *btnCancel;
+  QPushButton *btnAssociations;
+  QPushButton *btnEditFunction;
+  QPushButton *btnRange;
+  QListWidget *available;
+  QListWidget *contents;
+  QComboBox *boxStyle;
+  QComboBox *boxMatrixStyle;
+  QCheckBox *boxShowRange;
+  QCheckBox *boxShowCurrentFolder;
+  QMap<QString, PlotCurve *> d_plotCurves;
 };
 
 #endif // CurvesDialog_H
diff --git a/MantidPlot/src/CustomActionDialog.cpp b/MantidPlot/src/CustomActionDialog.cpp
index 51cedbdcd84edfce398f99427cff5bbce4e79681..9d916bb3b8cab8c16164f8f11412357cb493776b 100644
--- a/MantidPlot/src/CustomActionDialog.cpp
+++ b/MantidPlot/src/CustomActionDialog.cpp
@@ -47,515 +47,532 @@
 #include <QShortcut>
 #include <QMessageBox>
 
-CustomActionDialog::CustomActionDialog(QWidget* parent, Qt::WFlags fl)
-    : QDialog(parent, fl)
-{
-    setWindowTitle(tr("MantidPlot") + " - " + tr("Add Custom Action"));
-
-    itemsList = new QListWidget();
-    itemsList->setSelectionMode(QAbstractItemView::SingleSelection);
-	itemsList->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
-	itemsList->setSpacing(2);
-
-    QGroupBox *gb1 = new QGroupBox();
-	gb1->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
-
-	QGridLayout *gl1 = new QGridLayout(gb1);
-
-	gl1->addWidget(new QLabel(tr("Folder")), 0, 0);
-	folderBox = new QLineEdit();
-
-	gl1->addWidget(folderBox, 0, 1);
-	folderBtn = new QPushButton(tr("Choose &Folder"));
-	gl1->addWidget(folderBtn, 0, 2);
-
-	gl1->addWidget(new QLabel(tr("Script File")), 1, 0);
-	fileBox = new QLineEdit();
-
-	gl1->addWidget(fileBox, 1, 1);
-	fileBtn = new QPushButton(tr("Choose &Script"));
-	gl1->addWidget(fileBtn, 1, 2);
-
-	gl1->addWidget(new QLabel(tr("Icon")), 2, 0);
-	iconBox = new QLineEdit();
-	gl1->addWidget(iconBox, 2, 1);
-	iconBtn = new QPushButton(tr("Choose &Icon"));
-	gl1->addWidget(iconBtn, 2, 2);
-
-	gl1->addWidget(new QLabel(tr("Text")), 3, 0);
-	textBox = new QLineEdit();
-	gl1->addWidget(textBox, 3, 1);
-
-	gl1->addWidget(new QLabel(tr("Tool Tip Text")), 4, 0);
-	toolTipBox = new QLineEdit();
-	gl1->addWidget(toolTipBox, 4, 1);
-
-	gl1->addWidget(new QLabel(tr("Shortcut")), 5, 0);
-	shortcutBox = new QLineEdit();
-	gl1->addWidget(shortcutBox, 5, 1);
-
-    menuBtn = new QRadioButton(tr("&Menu"));
-    gl1->addWidget(menuBtn, 6, 0);
-    menuBox = new QComboBox();
-    gl1->addWidget(menuBox, 6, 1);
-
-    toolBarBtn = new QRadioButton(tr("&Tool Bar"));
-    toolBarBtn->setChecked(true);
-    gl1->addWidget(toolBarBtn, 7, 0);
-    toolBarBox = new QComboBox();
-    gl1->addWidget(toolBarBox, 7, 1);
-    gl1->setRowStretch(8, 1);
-	gl1->setColumnStretch(1, 10);
-
-	QHBoxLayout * bottomButtons = new QHBoxLayout();
-	bottomButtons->addStretch();
-	buttonSave = new QPushButton(tr("&Save"));
-	buttonSave->setAutoDefault( true );
-	bottomButtons->addWidget(buttonSave);
-	
-	buttonAdd = new QPushButton(tr("&Add"));
-	buttonAdd->setAutoDefault( true );
-	bottomButtons->addWidget(buttonAdd);
-
-	buttonRemove = new QPushButton(tr("&Remove"));
-	buttonRemove->setAutoDefault(true);
-	bottomButtons->addWidget(buttonRemove);
-
-	buttonCancel = new QPushButton(tr("&Close"));
-	buttonCancel->setAutoDefault( true );
-	bottomButtons->addWidget( buttonCancel );
-
-	QHBoxLayout *vl = new QHBoxLayout();
-	vl->addWidget(itemsList);
-	vl->addWidget(gb1);
-
-    QVBoxLayout *mainLayout = new QVBoxLayout(this);
-    mainLayout->addLayout(vl);
-	mainLayout->addLayout(bottomButtons);
-
-	init();
-
-	QShortcut *accelRemove = new QShortcut(QKeySequence(Qt::Key_Delete), this);
-	connect(accelRemove, SIGNAL(activated()), this, SLOT(removeAction()));
-
-	connect(buttonSave, SIGNAL(clicked()), this, SLOT(saveCurrentAction()));
-	connect(buttonAdd, SIGNAL(clicked()), this, SLOT(addAction()));
-	connect(buttonRemove, SIGNAL(clicked()), this, SLOT(removeAction()));
-	connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
-	connect(iconBtn, SIGNAL(clicked()), this, SLOT(chooseIcon()));
-	connect(fileBtn, SIGNAL(clicked()), this, SLOT(chooseFile()));
-	connect(folderBtn, SIGNAL(clicked()), this, SLOT(chooseFolder()));
-	connect(itemsList, SIGNAL(currentRowChanged(int)), this, SLOT(setCurrentAction(int)));
+CustomActionDialog::CustomActionDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setWindowTitle(tr("MantidPlot") + " - " + tr("Add Custom Action"));
+
+  itemsList = new QListWidget();
+  itemsList->setSelectionMode(QAbstractItemView::SingleSelection);
+  itemsList->setSizePolicy(
+      QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
+  itemsList->setSpacing(2);
+
+  QGroupBox *gb1 = new QGroupBox();
+  gb1->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
+
+  QGridLayout *gl1 = new QGridLayout(gb1);
+
+  gl1->addWidget(new QLabel(tr("Folder")), 0, 0);
+  folderBox = new QLineEdit();
+
+  gl1->addWidget(folderBox, 0, 1);
+  folderBtn = new QPushButton(tr("Choose &Folder"));
+  gl1->addWidget(folderBtn, 0, 2);
+
+  gl1->addWidget(new QLabel(tr("Script File")), 1, 0);
+  fileBox = new QLineEdit();
+
+  gl1->addWidget(fileBox, 1, 1);
+  fileBtn = new QPushButton(tr("Choose &Script"));
+  gl1->addWidget(fileBtn, 1, 2);
+
+  gl1->addWidget(new QLabel(tr("Icon")), 2, 0);
+  iconBox = new QLineEdit();
+  gl1->addWidget(iconBox, 2, 1);
+  iconBtn = new QPushButton(tr("Choose &Icon"));
+  gl1->addWidget(iconBtn, 2, 2);
+
+  gl1->addWidget(new QLabel(tr("Text")), 3, 0);
+  textBox = new QLineEdit();
+  gl1->addWidget(textBox, 3, 1);
+
+  gl1->addWidget(new QLabel(tr("Tool Tip Text")), 4, 0);
+  toolTipBox = new QLineEdit();
+  gl1->addWidget(toolTipBox, 4, 1);
+
+  gl1->addWidget(new QLabel(tr("Shortcut")), 5, 0);
+  shortcutBox = new QLineEdit();
+  gl1->addWidget(shortcutBox, 5, 1);
+
+  menuBtn = new QRadioButton(tr("&Menu"));
+  gl1->addWidget(menuBtn, 6, 0);
+  menuBox = new QComboBox();
+  gl1->addWidget(menuBox, 6, 1);
+
+  toolBarBtn = new QRadioButton(tr("&Tool Bar"));
+  toolBarBtn->setChecked(true);
+  gl1->addWidget(toolBarBtn, 7, 0);
+  toolBarBox = new QComboBox();
+  gl1->addWidget(toolBarBox, 7, 1);
+  gl1->setRowStretch(8, 1);
+  gl1->setColumnStretch(1, 10);
+
+  QHBoxLayout *bottomButtons = new QHBoxLayout();
+  bottomButtons->addStretch();
+  buttonSave = new QPushButton(tr("&Save"));
+  buttonSave->setAutoDefault(true);
+  bottomButtons->addWidget(buttonSave);
+
+  buttonAdd = new QPushButton(tr("&Add"));
+  buttonAdd->setAutoDefault(true);
+  bottomButtons->addWidget(buttonAdd);
+
+  buttonRemove = new QPushButton(tr("&Remove"));
+  buttonRemove->setAutoDefault(true);
+  bottomButtons->addWidget(buttonRemove);
+
+  buttonCancel = new QPushButton(tr("&Close"));
+  buttonCancel->setAutoDefault(true);
+  bottomButtons->addWidget(buttonCancel);
+
+  QHBoxLayout *vl = new QHBoxLayout();
+  vl->addWidget(itemsList);
+  vl->addWidget(gb1);
+
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  mainLayout->addLayout(vl);
+  mainLayout->addLayout(bottomButtons);
+
+  init();
+
+  QShortcut *accelRemove = new QShortcut(QKeySequence(Qt::Key_Delete), this);
+  connect(accelRemove, SIGNAL(activated()), this, SLOT(removeAction()));
+
+  connect(buttonSave, SIGNAL(clicked()), this, SLOT(saveCurrentAction()));
+  connect(buttonAdd, SIGNAL(clicked()), this, SLOT(addAction()));
+  connect(buttonRemove, SIGNAL(clicked()), this, SLOT(removeAction()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(iconBtn, SIGNAL(clicked()), this, SLOT(chooseIcon()));
+  connect(fileBtn, SIGNAL(clicked()), this, SLOT(chooseFile()));
+  connect(folderBtn, SIGNAL(clicked()), this, SLOT(chooseFolder()));
+  connect(itemsList, SIGNAL(currentRowChanged(int)), this,
+          SLOT(setCurrentAction(int)));
 }
 
-void CustomActionDialog::init()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-	folderBox->setText(app->customActionsDirPath);
+void CustomActionDialog::init() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  folderBox->setText(app->customActionsDirPath);
 
-	d_menus = app->customizableMenusList();
-	d_app_toolbars = app->toolBarsList();
-	QList<QMenu *> d_app_menus = app->menusList();
+  d_menus = app->customizableMenusList();
+  d_app_toolbars = app->toolBarsList();
+  QList<QMenu *> d_app_menus = app->menusList();
 
-	QStringList toolBars, menus;
-	foreach (QMenu *m, d_menus){
-		if (!m->title().isEmpty()){
-			menus << m->title().remove("&");
-	   }
+  QStringList toolBars, menus;
+  foreach (QMenu *m, d_menus) {
+    if (!m->title().isEmpty()) {
+      menus << m->title().remove("&");
     }
-	menus.sort();
-	menuBox->addItems(menus);
-
-	//Build the list of shortcut key sequences and keep it to memory to improve speed!
-	foreach (QMenu *m, d_app_menus){
-		QList<QAction *> actionsList = m->actions();
-		foreach (QAction *a, actionsList){
-			QString shortcut = a->shortcut().toString();
-	    	if (!shortcut.isEmpty() && !d_app_shortcut_keys.contains(shortcut))
-				d_app_shortcut_keys << shortcut;
-	   }
+  }
+  menus.sort();
+  menuBox->addItems(menus);
+
+  // Build the list of shortcut key sequences and keep it to memory to improve
+  // speed!
+  foreach (QMenu *m, d_app_menus) {
+    QList<QAction *> actionsList = m->actions();
+    foreach (QAction *a, actionsList) {
+      QString shortcut = a->shortcut().toString();
+      if (!shortcut.isEmpty() && !d_app_shortcut_keys.contains(shortcut))
+        d_app_shortcut_keys << shortcut;
     }
+  }
 
-	foreach (QToolBar *t, d_app_toolbars){
-		toolBars << t->windowTitle();
-		QList<QAction *> actionsList = t->actions();
-		foreach (QAction *a, actionsList){
-			QString shortcut = a->shortcut().toString();
-	    	if (!shortcut.isEmpty() && !d_app_shortcut_keys.contains(shortcut))
-				d_app_shortcut_keys << shortcut;
-		}
+  foreach (QToolBar *t, d_app_toolbars) {
+    toolBars << t->windowTitle();
+    QList<QAction *> actionsList = t->actions();
+    foreach (QAction *a, actionsList) {
+      QString shortcut = a->shortcut().toString();
+      if (!shortcut.isEmpty() && !d_app_shortcut_keys.contains(shortcut))
+        d_app_shortcut_keys << shortcut;
     }
-    toolBars.sort();
-	toolBarBox->addItems(toolBars);
+  }
+  toolBars.sort();
+  toolBarBox->addItems(toolBars);
 
-	updateDisplayList();
+  updateDisplayList();
 }
 
-void CustomActionDialog::updateDisplayList()
-{
-	itemsList->clear();
+void CustomActionDialog::updateDisplayList() {
+  itemsList->clear();
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
   if (!app) {
-    throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+    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();
-	    if (!shortcut.isEmpty())
-            text += " (" + shortcut + ")";
-
-        QListWidgetItem *it = new QListWidgetItem(text, itemsList);
-        if (!action->icon().isNull())
-            it->setIcon(action->icon());
-        itemsList->addItem(it);
-	}
-	itemsList->setCurrentRow(0);
-	setCurrentAction(0);
+  foreach (QAction *action,
+           actionsList) { // add existing actions to the list widget
+    QString text = action->text();
+    QString shortcut = action->shortcut().toString();
+    if (!shortcut.isEmpty())
+      text += " (" + shortcut + ")";
+
+    QListWidgetItem *it = new QListWidgetItem(text, itemsList);
+    if (!action->icon().isNull())
+      it->setIcon(action->icon());
+    itemsList->addItem(it);
+  }
+  itemsList->setCurrentRow(0);
+  setCurrentAction(0);
 }
 
-QAction* CustomActionDialog::addAction()
-{
-	QAction *action = NULL;
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parentWidget());
-    if (!app)
-        return action;
-
-	if (validUserInput()){
-    	action = new QAction(app);
-		customizeAction(action);
-
-        if (toolBarBtn->isChecked()){
-            foreach (QToolBar *t, d_app_toolbars){
-                if (t->windowTitle() == toolBarBox->currentText()){
-                    app->addCustomAction(action, t->objectName());
-                    break;
-                }
-            }
-        } else {
-            foreach (QMenu *m, d_menus){
-                if (m->title().remove("&") == menuBox->currentText()){
-                    action->setStatusTip(m->objectName());
-                    app->addCustomAction(action, m->objectName());
-                    break;
-                }
-            }
+QAction *CustomActionDialog::addAction() {
+  QAction *action = NULL;
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parentWidget());
+  if (!app)
+    return action;
+
+  if (validUserInput()) {
+    action = new QAction(app);
+    customizeAction(action);
+
+    if (toolBarBtn->isChecked()) {
+      foreach (QToolBar *t, d_app_toolbars) {
+        if (t->windowTitle() == toolBarBox->currentText()) {
+          app->addCustomAction(action, t->objectName());
+          break;
         }
+      }
+    } else {
+      foreach (QMenu *m, d_menus) {
+        if (m->title().remove("&") == menuBox->currentText()) {
+          action->setStatusTip(m->objectName());
+          app->addCustomAction(action, m->objectName());
+          break;
+        }
+      }
+    }
 
-		QString text = action->text();
-		QString shortcut = action->shortcut().toString();
-		if (!shortcut.isEmpty())
-			text += " (" + shortcut + ")";
+    QString text = action->text();
+    QString shortcut = action->shortcut().toString();
+    if (!shortcut.isEmpty())
+      text += " (" + shortcut + ")";
 
-    	QListWidgetItem *it = new QListWidgetItem(text, itemsList);
-    	if (!action->icon().isNull())
-        	it->setIcon(action->icon());
-    	itemsList->addItem(it);
-    	itemsList->setCurrentItem(it);
+    QListWidgetItem *it = new QListWidgetItem(text, itemsList);
+    if (!action->icon().isNull())
+      it->setIcon(action->icon());
+    itemsList->addItem(it);
+    itemsList->setCurrentItem(it);
 
-    	saveAction(action);
-	}
-    return action;
+    saveAction(action);
+  }
+  return action;
 }
 
-bool CustomActionDialog::validUserInput()
-{
-	QString folder = folderBox->text();
-    while (folder.isEmpty() || !QFileInfo(folder).exists() || !QFileInfo(folder).isReadable()){
-        chooseFolder();
-		folder = folderBox->text();
-	}
+bool CustomActionDialog::validUserInput() {
+  QString folder = folderBox->text();
+  while (folder.isEmpty() || !QFileInfo(folder).exists() ||
+         !QFileInfo(folder).isReadable()) {
+    chooseFolder();
+    folder = folderBox->text();
+  }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
   if (!app) {
-    throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of CustomActionDialog is not ApplicationWindow as expected.");
   }
-	QList<QAction *>actions = app->customActionsList();
+  QList<QAction *> actions = app->customActionsList();
 
-	if (textBox->text().isEmpty()){
-        QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
+  if (textBox->text().isEmpty()) {
+    QMessageBox::critical(
+        app, tr("MantidPlot") + " - " + tr("Error"),
         tr("Please provide a description for your custom action!"));
-        textBox->setFocus();
-        return false;
-    } else if (textBox->text().contains(".")){
-        QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
+    textBox->setFocus();
+    return false;
+  } else if (textBox->text().contains(".")) {
+    QMessageBox::critical(
+        app, tr("MantidPlot") + " - " + tr("Error"),
         tr("Dot characters are not allowed in the description text!"));
-        textBox->setFocus();
-        textBox->setText(textBox->text().remove(".").simplified());
-        return false;
-    }
+    textBox->setFocus();
+    textBox->setText(textBox->text().remove(".").simplified());
+    return false;
+  }
 
-    QString text = textBox->text().remove(".").simplified();
-    foreach(QAction *action, actions){
-        if(action->text() == text){
-            QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
-            tr("You have already defined an action having description: %1 <br>Please provide a different description text!").arg(textBox->text()));
-            textBox->setFocus();
-            return false;
-        }
+  QString text = textBox->text().remove(".").simplified();
+  foreach (QAction *action, actions) {
+    if (action->text() == text) {
+      QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
+                            tr("You have already defined an action having "
+                               "description: %1 <br>Please provide a different "
+                               "description text!").arg(textBox->text()));
+      textBox->setFocus();
+      return false;
     }
+  }
 
-    QString file = fileBox->text();
-    QFileInfo fi(file);
-    if (file.isEmpty() || !fi.exists()){
-        QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
-        tr("The file you have specified doesn't exist, please choose a valid script file!"));
-        fileBox->setFocus();
-        return false;
-    }
+  QString file = fileBox->text();
+  QFileInfo fi(file);
+  if (file.isEmpty() || !fi.exists()) {
+    QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
+                          tr("The file you have specified doesn't exist, "
+                             "please choose a valid script file!"));
+    fileBox->setFocus();
+    return false;
+  }
 
-    QString iconPath = iconBox->text();
-    QFileInfo iconInfo(iconPath);
-    if (!iconPath.isEmpty() && (!iconInfo.exists() || !iconInfo.isFile() || !iconInfo.isReadable())){
-        iconPath = QString();
-        QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
-        tr("The image file you have specified doesn't exist or can't be read, please choose another file!"));
-        iconBox->setFocus();
-        return false;
-    }
+  QString iconPath = iconBox->text();
+  QFileInfo iconInfo(iconPath);
+  if (!iconPath.isEmpty() &&
+      (!iconInfo.exists() || !iconInfo.isFile() || !iconInfo.isReadable())) {
+    iconPath = QString();
+    QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
+                          tr("The image file you have specified doesn't exist "
+                             "or can't be read, please choose another file!"));
+    iconBox->setFocus();
+    return false;
+  }
+
+  QStringList shortcuts = d_app_shortcut_keys;
+  foreach (QAction *a, actions) {
+    QString shortcut = a->shortcut().toString();
+    if (!shortcut.isEmpty() && !shortcuts.contains(shortcut))
+      shortcuts << shortcut;
+  }
+
+  shortcuts.sort();
+  QString s;
+  int i = 0, n = shortcuts.count();
+  while (i < n - 5) {
+    s += shortcuts[i] + "\t" + shortcuts[i + 1] + "\t" + shortcuts[i + 2];
+    s += "\t" + shortcuts[i + 3] + "\t" + shortcuts[i + 4] + "\n";
+    i += 5;
+  }
+
+  if (shortcuts.contains(shortcutBox->text().remove(QRegExp("\\s")))) {
+    QMessageBox::critical(
+        app, tr("MantidPlot") + " - " + tr("Error"),
+        tr("Please provide a different key sequence! The following shortcut "
+           "key sequences are already assigned:") +
+            "\n\n" + s);
+    shortcutBox->setFocus();
+    return false;
+  }
 
-	QStringList shortcuts = d_app_shortcut_keys;
-	foreach (QAction *a, actions){
-		QString shortcut = a->shortcut().toString();
-	    if (!shortcut.isEmpty() && !shortcuts.contains(shortcut))
-			shortcuts << shortcut;
-	}
-
-	shortcuts.sort();
-	QString s;
-	int i = 0, n = shortcuts.count();
-	while(i < n-5){
-		s += shortcuts[i] + "\t" + shortcuts[i+1] + "\t" + shortcuts[i+2];
-		s += "\t" + shortcuts[i+3] + "\t" + shortcuts[i+4] + "\n";
-		i += 5;
-	}
-
-	if (shortcuts.contains(shortcutBox->text().remove(QRegExp("\\s")))){
-		QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
-        tr("Please provide a different key sequence! The following shortcut key sequences are already assigned:") +
-		"\n\n" + s);
-       	shortcutBox->setFocus();
-        return false;
-	}
-
-	return true;
+  return true;
 }
 
-void CustomActionDialog::customizeAction(QAction *action)
-{
-	if (!action)
-		return;
-	
-	action->setText(textBox->text().remove(".").simplified());
-    action->setData(QFileInfo(fileBox->text()).absoluteFilePath());
-
-    QIcon icon = QIcon();
-	QString iconPath = iconBox->text();
-	QFileInfo iconInfo(iconPath);
-    if (!iconPath.isEmpty() && iconInfo.exists()){
-        icon = QIcon(iconPath);
-        action->setIcon(icon);
-        action->setIconText(iconInfo.absoluteFilePath());
-    }
+void CustomActionDialog::customizeAction(QAction *action) {
+  if (!action)
+    return;
 
-    if (!toolTipBox->text().isEmpty())
-        action->setToolTip(toolTipBox->text().simplified());
+  action->setText(textBox->text().remove(".").simplified());
+  action->setData(QFileInfo(fileBox->text()).absoluteFilePath());
 
-    if (!shortcutBox->text().isEmpty())
-        action->setShortcut(shortcutBox->text().remove(QRegExp("\\s")));
+  QIcon icon = QIcon();
+  QString iconPath = iconBox->text();
+  QFileInfo iconInfo(iconPath);
+  if (!iconPath.isEmpty() && iconInfo.exists()) {
+    icon = QIcon(iconPath);
+    action->setIcon(icon);
+    action->setIconText(iconInfo.absoluteFilePath());
+  }
+
+  if (!toolTipBox->text().isEmpty())
+    action->setToolTip(toolTipBox->text().simplified());
+
+  if (!shortcutBox->text().isEmpty())
+    action->setShortcut(shortcutBox->text().remove(QRegExp("\\s")));
 }
 
-void CustomActionDialog::removeAction()
-{
-	QString s = tr("Are you sure you want to remove this action?");
-    if (QMessageBox::Yes != QMessageBox::question(this, tr("MantidPlot") + " - " + tr("Remove Action"), s, QMessageBox::Yes, QMessageBox::Cancel))
-        return;
-
-	int row = itemsList->currentRow();
-    QAction *action = actionAt(row);
-	if (!action)
-		return;
-	
-    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();
-	
-	app->removeCustomAction(action);
-	
-    itemsList->takeItem(row);
-	if (itemsList->count())
-		setCurrentAction(0);
+void CustomActionDialog::removeAction() {
+  QString s = tr("Are you sure you want to remove this action?");
+  if (QMessageBox::Yes !=
+      QMessageBox::question(this,
+                            tr("MantidPlot") + " - " + tr("Remove Action"), s,
+                            QMessageBox::Yes, QMessageBox::Cancel))
+    return;
+
+  int row = itemsList->currentRow();
+  QAction *action = actionAt(row);
+  if (!action)
+    return;
+
+  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();
+
+  app->removeCustomAction(action);
+
+  itemsList->takeItem(row);
+  if (itemsList->count())
+    setCurrentAction(0);
 }
 
-void CustomActionDialog::saveCurrentAction()
-{
-	int row = itemsList->currentRow(); 
-	QAction *action = actionAt(row);
-	if (!action)
-		return;
-	
-	QList<QWidget *> list = action->associatedWidgets();
-    QWidget *w = list[0];
-   	QString parentName = w->objectName();
-	if ((toolBarBtn->isChecked() && w->objectName() != toolBarBox->currentText()) || 
-		(menuBtn->isChecked() && w->objectName() != menuBox->currentText())){
-		//relocate action: create a new one and delete the old
+void CustomActionDialog::saveCurrentAction() {
+  int row = itemsList->currentRow();
+  QAction *action = actionAt(row);
+  if (!action)
+    return;
+
+  QList<QWidget *> list = action->associatedWidgets();
+  QWidget *w = list[0];
+  QString parentName = w->objectName();
+  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());
     if (!app) {
-      throw std::logic_error("Parent of CustomActionDialog is not ApplicationWindow as expected.");
+      throw std::logic_error(
+          "Parent of CustomActionDialog is not ApplicationWindow as expected.");
     }
-		QAction *newAction = new QAction(app);
-		customizeAction(newAction);			
-		if (toolBarBtn->isChecked()){
-            foreach (QToolBar *t, d_app_toolbars){
-                if (t->windowTitle() == toolBarBox->currentText()){
-                    app->addCustomAction(newAction, t->objectName(), row);
-                    break;
-                }
-            }
-        } else {
-            foreach (QMenu *m, d_menus){
-                if (m->title().remove("&") == menuBox->currentText()){
-                    action->setStatusTip(m->objectName());
-                    app->addCustomAction(newAction, m->objectName(), row);
-                    break;
-                }
-            }
+    QAction *newAction = new QAction(app);
+    customizeAction(newAction);
+    if (toolBarBtn->isChecked()) {
+      foreach (QToolBar *t, d_app_toolbars) {
+        if (t->windowTitle() == toolBarBox->currentText()) {
+          app->addCustomAction(newAction, t->objectName(), row);
+          break;
         }
-		saveAction(newAction);
-		delete action;
-	} else {
-		customizeAction(action);
-		saveAction(action);
-	}
+      }
+    } else {
+      foreach (QMenu *m, d_menus) {
+        if (m->title().remove("&") == menuBox->currentText()) {
+          action->setStatusTip(m->objectName());
+          app->addCustomAction(newAction, m->objectName(), row);
+          break;
+        }
+      }
+    }
+    saveAction(newAction);
+    delete action;
+  } else {
+    customizeAction(action);
+    saveAction(action);
+  }
 }
 
-void CustomActionDialog::saveAction(QAction *action)
-{
-    if (!action)
-        return;
+void CustomActionDialog::saveAction(QAction *action) {
+  if (!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)){
-		QApplication::restoreOverrideCursor();
-		QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("File Save Error"),
-				tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that you have the right to write to this location!").arg(fileName));
-		return;
-	}
-
-    QTextStream out( &f );
-    out.setCodec("UTF-8");
-    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
-         << "<!DOCTYPE action>\n"
-         << "<action version=\"1.0\">\n";
-
-     out << "<text>" + action->text() + "</text>\n";
-     out << "<file>" + action->data().toString() + "</file>\n";
-     out << "<icon>" + action->iconText() + "</icon>\n";
-     out << "<tooltip>" + action->toolTip() + "</tooltip>\n";
-     out << "<shortcut>" + action->shortcut().toString() + "</shortcut>\n";
-
-     QList<QWidget *> list = action->associatedWidgets();
-     QWidget *w = list[0];
-     out << "<location>" + w->objectName() + "</location>\n";
-     out << "</action>\n";
+  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)) {
+    QApplication::restoreOverrideCursor();
+    QMessageBox::critical(
+        app, tr("MantidPlot") + " - " + tr("File Save Error"),
+        tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
+           "you have the right to write to this location!").arg(fileName));
+    return;
+  }
+
+  QTextStream out(&f);
+  out.setCodec("UTF-8");
+  out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+      << "<!DOCTYPE action>\n"
+      << "<action version=\"1.0\">\n";
+
+  out << "<text>" + action->text() + "</text>\n";
+  out << "<file>" + action->data().toString() + "</file>\n";
+  out << "<icon>" + action->iconText() + "</icon>\n";
+  out << "<tooltip>" + action->toolTip() + "</tooltip>\n";
+  out << "<shortcut>" + action->shortcut().toString() + "</shortcut>\n";
+
+  QList<QWidget *> list = action->associatedWidgets();
+  QWidget *w = list[0];
+  out << "<location>" + w->objectName() + "</location>\n";
+  out << "</action>\n";
 }
 
-void CustomActionDialog::chooseIcon()
-{
-    QList<QByteArray> list = QImageReader::supportedImageFormats();
-	QString filter = tr("images") + " (", aux1, aux2;
-	for (int i=0; i<(int)list.count(); i++){
-		aux1 = " *." + list[i] + " ";
-		aux2 += " *." + list[i] + ";;";
-		filter += aux1;
-	}
-	filter+=");;" + aux2;
-
-	QString fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Load icon from file"), iconBox->text(), filter);
-	if (!fn.isEmpty())
-		iconBox->setText(fn);
+void CustomActionDialog::chooseIcon() {
+  QList<QByteArray> list = QImageReader::supportedImageFormats();
+  QString filter = tr("images") + " (", aux1, aux2;
+  for (int i = 0; i < (int)list.count(); i++) {
+    aux1 = " *." + list[i] + " ";
+    aux2 += " *." + list[i] + ";;";
+    filter += aux1;
+  }
+  filter += ");;" + aux2;
+
+  QString fn = QFileDialog::getOpenFileName(
+      this, tr("MantidPlot - Load icon from file"), iconBox->text(), filter);
+  if (!fn.isEmpty())
+    iconBox->setText(fn);
 }
 
-void CustomActionDialog::chooseFile()
-{
-    QString fileName = QFileDialog::getOpenFileName(this, tr("Choose script file"), fileBox->text());
-    if (!fileName.isEmpty())
-        fileBox->setText(fileName);
+void CustomActionDialog::chooseFile() {
+  QString fileName = QFileDialog::getOpenFileName(
+      this, tr("Choose script file"), fileBox->text());
+  if (!fileName.isEmpty())
+    fileBox->setText(fileName);
 }
 
-void CustomActionDialog::chooseFolder()
-{
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parentWidget());
+void CustomActionDialog::chooseFolder() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parentWidget());
 
-    QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the custom actions folder"), app->customActionsDirPath);
-    if (!dir.isEmpty() && QFileInfo(dir).isReadable()){
-		QList<QAction *> actionsList = app->customActionsList();
-    	foreach (QAction *a, actionsList)
-            app->removeCustomAction(a);
+  QString dir = QFileDialog::getExistingDirectory(
+      this, tr("Choose the custom actions folder"), app->customActionsDirPath);
+  if (!dir.isEmpty() && QFileInfo(dir).isReadable()) {
+    QList<QAction *> actionsList = app->customActionsList();
+    foreach (QAction *a, actionsList)
+      app->removeCustomAction(a);
 
-        app->customActionsDirPath = dir;
-        app->loadCustomActions();
-		updateDisplayList();
-        folderBox->setText(dir);
-    }
+    app->customActionsDirPath = dir;
+    app->loadCustomActions();
+    updateDisplayList();
+    folderBox->setText(dir);
+  }
 }
 
-QAction * CustomActionDialog::actionAt(int row)
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+QAction *CustomActionDialog::actionAt(int row) {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
   if (!app)
     throw std::runtime_error(
         "The parent of this dialog was not the Application Window");
-  QList<QAction *>actions = app->customActionsList();
-	if (actions.isEmpty() || row < 0 || row >= actions.count())
-        return 0;
+  QList<QAction *> actions = app->customActionsList();
+  if (actions.isEmpty() || row < 0 || row >= actions.count())
+    return 0;
 
-    return actions.at(row);
+  return actions.at(row);
 }
 
-void CustomActionDialog::setCurrentAction(int row)
-{
-    QAction *action = actionAt(row);
-    if (!action)
-        return;
-
-    fileBox->setText(action->data().toString());
-    textBox->setText(action->text());
-    iconBox->setText(action->iconText());
-    toolTipBox->setText(action->toolTip());
-    shortcutBox->setText(action->shortcut().toString());
-
-    QList<QWidget *> list = action->associatedWidgets();
-    QWidget *w = NULL;
-    if (!list.isEmpty())
-        w = list[0];
-	if (!w)
-		return;
-
-	if (qstrcmp("QToolBar", w->metaObject()->className()) == 0){
-      int index = toolBarBox->findText((dynamic_cast<QToolBar*>(w))->windowTitle());
-    	if (index >= 0){
-        	toolBarBox->setCurrentIndex(index);
-        	toolBarBtn->setChecked(true);
-    	}
-	} else {
-        int index = menuBox->findText((dynamic_cast<QMenu*>(w))->title().remove("&"));
-        if (index >= 0){
-            menuBox->setCurrentIndex(index);
-            menuBtn->setChecked(true);
-        }
+void CustomActionDialog::setCurrentAction(int row) {
+  QAction *action = actionAt(row);
+  if (!action)
+    return;
+
+  fileBox->setText(action->data().toString());
+  textBox->setText(action->text());
+  iconBox->setText(action->iconText());
+  toolTipBox->setText(action->toolTip());
+  shortcutBox->setText(action->shortcut().toString());
+
+  QList<QWidget *> list = action->associatedWidgets();
+  QWidget *w = NULL;
+  if (!list.isEmpty())
+    w = list[0];
+  if (!w)
+    return;
+
+  if (qstrcmp("QToolBar", w->metaObject()->className()) == 0) {
+    int index =
+        toolBarBox->findText((dynamic_cast<QToolBar *>(w))->windowTitle());
+    if (index >= 0) {
+      toolBarBox->setCurrentIndex(index);
+      toolBarBtn->setChecked(true);
+    }
+  } else {
+    int index =
+        menuBox->findText((dynamic_cast<QMenu *>(w))->title().remove("&"));
+    if (index >= 0) {
+      menuBox->setCurrentIndex(index);
+      menuBtn->setChecked(true);
     }
+  }
 }
 
 /*****************************************************************************
@@ -565,54 +582,52 @@ void CustomActionDialog::setCurrentAction(int row)
  *****************************************************************************/
 
 CustomActionHandler::CustomActionHandler(QAction *action)
-     : metFitTag(true),filePath(QString()),d_widget_name(QString()),d_action(action)
- {
- }
+    : metFitTag(true), filePath(QString()), d_widget_name(QString()),
+      d_action(action) {}
 
 bool CustomActionHandler::startElement(const QString & /* namespaceURI */,
-                                const QString & /* localName */,
-                                const QString &qName,
-                                const QXmlAttributes &attributes)
-{
-     if (!metFitTag && qName != "action") {
-         errorStr = QObject::tr("The file is not a MantidPlot custom action file.");
-         return false;
-     }
-
-     if (qName == "action") {
-         QString version = attributes.value("version");
-         if (!version.isEmpty() && version != "1.0") {
-             errorStr = QObject::tr("The file is not an MantidPlot custom action version 1.0 file.");
-             return false;
-         }
-         metFitTag = true;
-     }
-
-     currentText.clear();
-     return true;
+                                       const QString & /* localName */,
+                                       const QString &qName,
+                                       const QXmlAttributes &attributes) {
+  if (!metFitTag && qName != "action") {
+    errorStr = QObject::tr("The file is not a MantidPlot custom action file.");
+    return false;
+  }
+
+  if (qName == "action") {
+    QString version = attributes.value("version");
+    if (!version.isEmpty() && version != "1.0") {
+      errorStr = QObject::tr(
+          "The file is not an MantidPlot custom action version 1.0 file.");
+      return false;
+    }
+    metFitTag = true;
+  }
+
+  currentText.clear();
+  return true;
 }
 
 bool CustomActionHandler::endElement(const QString & /* namespaceURI */,
-                              const QString & /* localName */,
-                              const QString &qName)
-{
-    if (qName == "text")
-        d_action->setText(currentText);
-    else if (qName == "file")
-        filePath = currentText;
-    else if (qName == "icon" && !currentText.isEmpty()){
-        d_action->setIcon(QIcon(currentText));
-        d_action->setIconText(currentText);
-    } else if (qName == "tooltip")
-        d_action->setToolTip(currentText);
-    else if (qName == "shortcut")
-        d_action->setShortcut(currentText);
-    else if (qName == "location"){
-		d_widget_name = currentText;
-		//use status tip to store the name of the destination menu (ugly hack!)
-        d_action->setStatusTip(currentText);
-    } else if (qName == "action")
-        d_action->setData(filePath);
-
-    return true;
+                                     const QString & /* localName */,
+                                     const QString &qName) {
+  if (qName == "text")
+    d_action->setText(currentText);
+  else if (qName == "file")
+    filePath = currentText;
+  else if (qName == "icon" && !currentText.isEmpty()) {
+    d_action->setIcon(QIcon(currentText));
+    d_action->setIconText(currentText);
+  } else if (qName == "tooltip")
+    d_action->setToolTip(currentText);
+  else if (qName == "shortcut")
+    d_action->setShortcut(currentText);
+  else if (qName == "location") {
+    d_widget_name = currentText;
+    // use status tip to store the name of the destination menu (ugly hack!)
+    d_action->setStatusTip(currentText);
+  } else if (qName == "action")
+    d_action->setData(filePath);
+
+  return true;
 }
diff --git a/MantidPlot/src/CustomActionDialog.h b/MantidPlot/src/CustomActionDialog.h
index 6181fde64b24ef2ba9432a29de812dc8aa9ff375..945b5dad7dd425a40d0af593396afb0cbe997731 100644
--- a/MantidPlot/src/CustomActionDialog.h
+++ b/MantidPlot/src/CustomActionDialog.h
@@ -41,49 +41,47 @@ class QLineEdit;
 class QMenu;
 class QToolBar;
 
-class CustomActionDialog : public QDialog
-{
-    Q_OBJECT
+class CustomActionDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	//! Constructor
-	/**
-	 * @param parent :: parent widget (must be the application window!=
-	 * @param fl :: window flags
-	 */
-    CustomActionDialog( QWidget* parent, Qt::WFlags fl = 0 );
+  //! Constructor
+  /**
+   * @param parent :: parent widget (must be the application window!=
+   * @param fl :: window flags
+   */
+  CustomActionDialog(QWidget *parent, Qt::WFlags fl = 0);
 
 private slots:
-	void chooseIcon();
-	void chooseFile();
-	void chooseFolder();
-	QAction* addAction();
-	void removeAction();
-	void setCurrentAction(int);
-	void saveCurrentAction();
+  void chooseIcon();
+  void chooseFile();
+  void chooseFolder();
+  QAction *addAction();
+  void removeAction();
+  void setCurrentAction(int);
+  void saveCurrentAction();
 
 private:
-	void init();
-	void updateDisplayList();
-	QAction* actionAt(int row);
-	void saveAction(QAction *action);
-	void customizeAction(QAction *action);
-	bool validUserInput();
-	QStringList d_app_shortcut_keys;
+  void init();
+  void updateDisplayList();
+  QAction *actionAt(int row);
+  void saveAction(QAction *action);
+  void customizeAction(QAction *action);
+  bool validUserInput();
+  QStringList d_app_shortcut_keys;
 
-	QList<QMenu *> d_menus;
-	QList<QToolBar *> d_app_toolbars;
+  QList<QMenu *> d_menus;
+  QList<QToolBar *> d_app_toolbars;
 
-    QListWidget *itemsList;
-    QPushButton *buttonCancel, *buttonAdd, *buttonRemove, *buttonSave;
-    QPushButton *folderBtn, *fileBtn, *iconBtn;
-    QLineEdit *folderBox, *fileBox, *iconBox, *textBox, *toolTipBox, *shortcutBox;
-    QRadioButton *menuBtn, *toolBarBtn;
-    QComboBox *menuBox, *toolBarBox;
+  QListWidget *itemsList;
+  QPushButton *buttonCancel, *buttonAdd, *buttonRemove, *buttonSave;
+  QPushButton *folderBtn, *fileBtn, *iconBtn;
+  QLineEdit *folderBox, *fileBox, *iconBox, *textBox, *toolTipBox, *shortcutBox;
+  QRadioButton *menuBtn, *toolBarBtn;
+  QComboBox *menuBox, *toolBarBox;
 };
 
-class CustomActionHandler : public QXmlDefaultHandler
-{
+class CustomActionHandler : public QXmlDefaultHandler {
 public:
   explicit CustomActionHandler(QAction *action);
 
@@ -98,14 +96,14 @@ public:
   };
   bool fatalError(const QXmlParseException &) override { return false; };
   QString errorString() const override { return errorStr; };
-        QString parentName(){return d_widget_name;};
+  QString parentName() { return d_widget_name; };
 
 private:
-    bool metFitTag;
-    QString currentText;
-    QString errorStr;
-    QString filePath;
-	QString d_widget_name;
-    QAction *d_action;
+  bool metFitTag;
+  QString currentText;
+  QString errorStr;
+  QString filePath;
+  QString d_widget_name;
+  QAction *d_action;
 };
 #endif
diff --git a/MantidPlot/src/DataPickerTool.cpp b/MantidPlot/src/DataPickerTool.cpp
index e2879f39c5c89b0c56d86eae35ab6d019afd8c64..96d63acde0a19f7aeb6e49a55748f7652a290b44 100644
--- a/MantidPlot/src/DataPickerTool.cpp
+++ b/MantidPlot/src/DataPickerTool.cpp
@@ -44,64 +44,64 @@
 #include <QApplication>
 #include <QTextStream>
 
-DataPickerTool::DataPickerTool(Graph *graph, ApplicationWindow *app, Mode mode, const QObject *status_target, const char *status_slot) :
-	QwtPlotPicker(graph->plotWidget()->canvas()),
-	PlotToolInterface(graph),
-	d_app(app),
-	d_mode(mode),
-	d_move_mode(Free)
-{
-	d_selected_curve = NULL;
-
-	d_selection_marker.setLineStyle(QwtPlotMarker::Cross);
-	d_selection_marker.setLinePen(QPen(Qt::red,1));
-
-	setTrackerMode(QwtPicker::AlwaysOn);
-	if (d_mode == Move) {
-		setSelectionFlags(QwtPicker::PointSelection | QwtPicker::DragSelection);
-		d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
-	} else {
-		setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
-		d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
-	}
-
-	if (status_target)
-		connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
-	switch(d_mode) {
-		case Display:
-			emit statusText(tr("Click on plot or move cursor to display coordinates!"));
-			break;
-		case Move:
-			emit statusText(tr("Please, click on plot and move cursor!"));
-			break;
-		case Remove:
-			emit statusText(tr("Select point and double click to remove it!"));
-			break;
-	}
-}
+DataPickerTool::DataPickerTool(Graph *graph, ApplicationWindow *app, Mode mode,
+                               const QObject *status_target,
+                               const char *status_slot)
+    : QwtPlotPicker(graph->plotWidget()->canvas()), PlotToolInterface(graph),
+      d_app(app), d_mode(mode), d_move_mode(Free) {
+  d_selected_curve = NULL;
+
+  d_selection_marker.setLineStyle(QwtPlotMarker::Cross);
+  d_selection_marker.setLinePen(QPen(Qt::red, 1));
+
+  setTrackerMode(QwtPicker::AlwaysOn);
+  if (d_mode == Move) {
+    setSelectionFlags(QwtPicker::PointSelection | QwtPicker::DragSelection);
+    d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
+  } else {
+    setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
+    d_graph->plotWidget()->canvas()->setCursor(
+        QCursor(getQPixmap("vizor_xpm"), -1, -1));
+  }
 
-DataPickerTool::~DataPickerTool()
-{
-	d_selection_marker.detach();
+  if (status_target)
+    connect(this, SIGNAL(statusText(const QString &)), status_target,
+            status_slot);
+  switch (d_mode) {
+  case Display:
+    emit statusText(tr("Click on plot or move cursor to display coordinates!"));
+    break;
+  case Move:
+    emit statusText(tr("Please, click on plot and move cursor!"));
+    break;
+  case Remove:
+    emit statusText(tr("Select point and double click to remove it!"));
+    break;
+  }
 }
 
-void DataPickerTool::append(const QPoint &pos)
-{
-	int dist, point_index;
-	const int curve = d_graph->plotWidget()->closestCurve(pos.x(), pos.y(), dist, point_index);
-	if (curve <= 0 || dist >= 5) { // 5 pixels tolerance
-		setSelection(NULL, 0);
-		return;
-	}
-	setSelection(dynamic_cast<QwtPlotCurve *>(d_graph->plotWidget()->curve(curve)), point_index);
-	if (!d_selected_curve) return;
-
-	QwtPlotPicker::append(transform(QwtDoublePoint(d_selected_curve->x(d_selected_point),
-					d_selected_curve->y(d_selected_point))));
+DataPickerTool::~DataPickerTool() { d_selection_marker.detach(); }
+
+void DataPickerTool::append(const QPoint &pos) {
+  int dist, point_index;
+  const int curve =
+      d_graph->plotWidget()->closestCurve(pos.x(), pos.y(), dist, point_index);
+  if (curve <= 0 || dist >= 5) { // 5 pixels tolerance
+    setSelection(NULL, 0);
+    return;
+  }
+  setSelection(
+      dynamic_cast<QwtPlotCurve *>(d_graph->plotWidget()->curve(curve)),
+      point_index);
+  if (!d_selected_curve)
+    return;
+
+  QwtPlotPicker::append(
+      transform(QwtDoublePoint(d_selected_curve->x(d_selected_point),
+                               d_selected_curve->y(d_selected_point))));
 }
 
-void DataPickerTool::setSelection(QwtPlotCurve *curve, int point_index)
-{
+void DataPickerTool::setSelection(QwtPlotCurve *curve, int point_index) {
   if (curve == d_selected_curve && point_index == d_selected_point)
     return;
 
@@ -116,22 +116,23 @@ 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);
+  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)));
+  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 (plotCurve && plotCurve->type() == Graph::Function) 
-  {
+  if (plotCurve && plotCurve->type() == Graph::Function) {
     QLocale locale = d_app->locale();
-    emit statusText(QString("%1[%2]: x=%3; y=%4")
-      .arg(d_selected_curve->title().text())
-      .arg(d_selected_point + 1)
-      .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 (dataCurve)
-  {
+    emit statusText(
+        QString("%1[%2]: x=%3; y=%4")
+            .arg(d_selected_curve->title().text())
+            .arg(d_selected_point + 1)
+            .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 (dataCurve) {
     int row = dataCurve->tableRow(d_selected_point);
 
     Table *t = dataCurve->table();
@@ -139,39 +140,36 @@ void DataPickerTool::setSelection(QwtPlotCurve *curve, int point_index)
     int yCol = t->colIndex(d_selected_curve->title().text());
 
     emit statusText(QString("%1[%2]: x=%3; y=%4")
-      .arg(d_selected_curve->title().text())
-      .arg(row + 1)
-      .arg(t->text(row, xCol))
-      .arg(t->text(row, yCol)));
+                        .arg(d_selected_curve->title().text())
+                        .arg(row + 1)
+                        .arg(t->text(row, xCol))
+                        .arg(t->text(row, yCol)));
   }
 
-  QwtDoublePoint selected_point_value(d_selected_curve->x(d_selected_point), d_selected_curve->y(d_selected_point));
+  QwtDoublePoint selected_point_value(d_selected_curve->x(d_selected_point),
+                                      d_selected_curve->y(d_selected_point));
   d_selection_marker.setValue(selected_point_value);
   if (d_selection_marker.plot() == NULL)
     d_selection_marker.attach(d_graph->plotWidget());
   d_graph->plotWidget()->replot();
 }
 
-bool DataPickerTool::eventFilter(QObject *obj, QEvent *event)
-{
-  if (!d_selected_curve)
-  {
+bool DataPickerTool::eventFilter(QObject *obj, QEvent *event) {
+  if (!d_selected_curve) {
     return QwtPlotPicker::eventFilter(obj, event);
   }
-  switch(event->type()) 
-  {
+  switch (event->type()) {
   case QEvent::MouseButtonDblClick:
     if (d_selected_curve)
       emit selected(d_selected_curve, d_selected_point);
     event->accept();
     return true;
 
-  case QEvent::MouseMove: 
-    if (auto mouseEvent = dynamic_cast<QMouseEvent *>(event))
-    {
-      if ( mouseEvent->modifiers() == Qt::ControlModifier )
+  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 )
+      else if (mouseEvent->modifiers() == Qt::AltModifier)
         d_move_mode = Horizontal;
       else
         d_move_mode = Free;
@@ -181,6 +179,5 @@ bool DataPickerTool::eventFilter(QObject *obj, QEvent *event)
   default:
     break;
   }
-	return QwtPlotPicker::eventFilter(obj, event);
+  return QwtPlotPicker::eventFilter(obj, event);
 }
-
diff --git a/MantidPlot/src/DataPickerTool.h b/MantidPlot/src/DataPickerTool.h
index cce274877d49935f0f49d641697dbb311df00a15..e44713ae28843b48fc109cb238ff0854d854f66d 100644
--- a/MantidPlot/src/DataPickerTool.h
+++ b/MantidPlot/src/DataPickerTool.h
@@ -40,43 +40,44 @@ class QwtPlotCurve;
 class QPoint;
 
 //! Plot tool for selecting, moving or removing individual points of a curve.
-class DataPickerTool : public QwtPlotPicker, public PlotToolInterface
-{
-	Q_OBJECT
-	public:
-		enum Mode { Display, Move, Remove };
-		enum MoveMode {Free, Vertical, Horizontal};
-		DataPickerTool(Graph *graph, ApplicationWindow *app, Mode mode, const QObject *status_target=NULL, const char *status_slot="");
-                ~DataPickerTool() override;
-    Mode getMode()const{return d_mode;}
-    bool eventFilter(QObject *obj, QEvent *event) override;
-                bool keyEventFilter(QKeyEvent *ke);
-		QwtPlotCurve *selectedCurve() const { return d_selected_curve; }
+class DataPickerTool : public QwtPlotPicker, public PlotToolInterface {
+  Q_OBJECT
+public:
+  enum Mode { Display, Move, Remove };
+  enum MoveMode { Free, Vertical, Horizontal };
+  DataPickerTool(Graph *graph, ApplicationWindow *app, Mode mode,
+                 const QObject *status_target = NULL,
+                 const char *status_slot = "");
+  ~DataPickerTool() override;
+  Mode getMode() const { return d_mode; }
+  bool eventFilter(QObject *obj, QEvent *event) override;
+  bool keyEventFilter(QKeyEvent *ke);
+  QwtPlotCurve *selectedCurve() const { return d_selected_curve; }
 
-                int rtti() const override {
-                  return PlotToolInterface::Rtti_DataPicker;
-                };
+  int rtti() const override { return PlotToolInterface::Rtti_DataPicker; };
 
-        signals:
-		/** Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
-		//! Emitted whenever a new data point has been selected.
-		void selected(QwtPlotCurve*, int);
-	protected:
-          void append(const QPoint &point) override;
-                void setSelection(QwtPlotCurve *curve, int point_index);
-	private:
-		ApplicationWindow *d_app;
-		QwtPlotMarker d_selection_marker;
-		Mode d_mode;
-		QwtPlotCurve *d_selected_curve;
-		int d_selected_point;
-		MoveMode d_move_mode;
-		QPoint d_restricted_move_pos;
+signals:
+  /** Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
+  //! Emitted whenever a new data point has been selected.
+  void selected(QwtPlotCurve *, int);
+
+protected:
+  void append(const QPoint &point) override;
+  void setSelection(QwtPlotCurve *curve, int point_index);
+
+private:
+  ApplicationWindow *d_app;
+  QwtPlotMarker d_selection_marker;
+  Mode d_mode;
+  QwtPlotCurve *d_selected_curve;
+  int d_selected_point;
+  MoveMode d_move_mode;
+  QPoint d_restricted_move_pos;
 };
 
 #endif // ifndef DATA_PICKER_TOOL_H
-
diff --git a/MantidPlot/src/DataSetDialog.cpp b/MantidPlot/src/DataSetDialog.cpp
index 1e5e20eebcb06228a31be114dc6435169054fa93..65498f2b29b4f0412e539ed297185b4a5c01e7b6 100644
--- a/MantidPlot/src/DataSetDialog.cpp
+++ b/MantidPlot/src/DataSetDialog.cpp
@@ -2,7 +2,8 @@
     File                 : DataSetDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Multi purpose dialog for choosing a data set
 
@@ -38,73 +39,67 @@
 #include <QVBoxLayout>
 #include <QHBoxLayout>
 
-DataSetDialog::DataSetDialog( const QString& text, ApplicationWindow* app, Graph* g,  Qt::WFlags fl )
-: QDialog( g, fl ),
-  d_app(app),
-  d_graph(g)
-{
-	setAttribute(Qt::WA_DeleteOnClose);
-	setWindowTitle(tr("MantidPlot - Select data set"));
+DataSetDialog::DataSetDialog(const QString &text, ApplicationWindow *app,
+                             Graph *g, Qt::WFlags fl)
+    : QDialog(g, fl), d_app(app), d_graph(g) {
+  setAttribute(Qt::WA_DeleteOnClose);
+  setWindowTitle(tr("MantidPlot - Select data set"));
 
-	d_operation = ApplicationWindow::NoAnalysis;
-	d_graph = 0;
+  d_operation = ApplicationWindow::NoAnalysis;
+  d_graph = 0;
 
-	QVBoxLayout * mainLayout = new QVBoxLayout( this );
-	QHBoxLayout * bottomLayout = new QHBoxLayout();
-	bottomLayout->addStretch();
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
+  bottomLayout->addStretch();
 
-	groupBox1 = new QGroupBox();
-	QHBoxLayout * topLayout = new QHBoxLayout( groupBox1 );
+  groupBox1 = new QGroupBox();
+  QHBoxLayout *topLayout = new QHBoxLayout(groupBox1);
 
-	topLayout->addWidget( new QLabel(text) );
-	boxName = new QComboBox();
-	topLayout->addWidget(boxName);
+  topLayout->addWidget(new QLabel(text));
+  boxName = new QComboBox();
+  topLayout->addWidget(boxName);
 
-	buttonOk = new QPushButton(tr( "&OK" ));
-	buttonOk->setAutoDefault( true );
-	buttonOk->setDefault( true );
-	bottomLayout->addWidget( buttonOk );
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
+  bottomLayout->addWidget(buttonOk);
 
-	buttonCancel = new QPushButton(tr( "&Cancel" ));
-	buttonCancel->setAutoDefault( true );
-	bottomLayout->addWidget( buttonCancel );
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  buttonCancel->setAutoDefault(true);
+  bottomLayout->addWidget(buttonCancel);
 
-	mainLayout->addWidget( groupBox1 );
-	mainLayout->addLayout( bottomLayout );
+  mainLayout->addWidget(groupBox1);
+  mainLayout->addLayout(bottomLayout);
 
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 
   setGraph(g);
 }
 
-void DataSetDialog::accept()
-{
-	if (d_operation == ApplicationWindow::NoAnalysis)
-		emit options(boxName->currentText());
-	else if (d_graph){
-      if (d_app)
-            d_app->analyzeCurve(d_graph, d_operation, boxName->currentText());
-	}
-	close();
+void DataSetDialog::accept() {
+  if (d_operation == ApplicationWindow::NoAnalysis)
+    emit options(boxName->currentText());
+  else if (d_graph) {
+    if (d_app)
+      d_app->analyzeCurve(d_graph, d_operation, boxName->currentText());
+  }
+  close();
 }
 
-void DataSetDialog::setCurveNames(const QStringList& names)
-{
-	boxName->addItems(names);
+void DataSetDialog::setCurveNames(const QStringList &names) {
+  boxName->addItems(names);
 }
 
-void DataSetDialog::setCurentDataSet(const QString& s)
-{
-	int row = boxName->findText(s);
-	boxName->setCurrentIndex(row);
+void DataSetDialog::setCurentDataSet(const QString &s) {
+  int row = boxName->findText(s);
+  boxName->setCurrentIndex(row);
 }
 
-void DataSetDialog::setGraph(Graph *g)
-{
-    if (!g)
-        return;
+void DataSetDialog::setGraph(Graph *g) {
+  if (!g)
+    return;
 
-   d_graph = g;
-   boxName->addItems(g->analysableCurvesList());
+  d_graph = g;
+  boxName->addItems(g->analysableCurvesList());
 }
diff --git a/MantidPlot/src/DataSetDialog.h b/MantidPlot/src/DataSetDialog.h
index 77014b64f1626daaf40bab27e126692bcb97c161..c4677d9395732af30f2db53de0ba4cafb3a29e8f 100644
--- a/MantidPlot/src/DataSetDialog.h
+++ b/MantidPlot/src/DataSetDialog.h
@@ -2,7 +2,8 @@
     File                 : DataSetDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Multi purpose dialog for choosing a data set
 
@@ -40,34 +41,36 @@ class QComboBox;
 class Graph;
 
 //! Multi purpose dialog for choosing a data set
-class DataSetDialog : public QDialog
-{
-    Q_OBJECT
+class DataSetDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    DataSetDialog( const QString& text, ApplicationWindow* app, Graph* g = NULL, Qt::WFlags fl = 0 );
+  DataSetDialog(const QString &text, ApplicationWindow *app, Graph *g = NULL,
+                Qt::WFlags fl = 0);
 
 public slots:
   void accept() override;
-        void setCurveNames(const QStringList& names);
-  void setOperationType(ApplicationWindow::Analysis operation){d_operation = operation;}
-	void setCurentDataSet(const QString& s);
+  void setCurveNames(const QStringList &names);
+  void setOperationType(ApplicationWindow::Analysis operation) {
+    d_operation = operation;
+  }
+  void setCurentDataSet(const QString &s);
 
 signals:
-	void options(const QString&);
+  void options(const QString &);
 
 private:
   void setGraph(Graph *g);
 
-  ApplicationWindow* d_app;
+  ApplicationWindow *d_app;
   Graph *d_graph;
   ApplicationWindow::Analysis d_operation;
   QString windowTitle;
 
-  QPushButton* buttonOk;
-  QPushButton* buttonCancel;
-  QGroupBox* groupBox1;
-  QComboBox* boxName;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QGroupBox *groupBox1;
+  QComboBox *boxName;
 };
 
 #endif
diff --git a/MantidPlot/src/Differentiation.cpp b/MantidPlot/src/Differentiation.cpp
index 09161f5cf24a1c4388b9a0969b03b3ab195d32c0..8bffe92a21d822dbab027bf9abab6c912ffdcdc0 100644
--- a/MantidPlot/src/Differentiation.cpp
+++ b/MantidPlot/src/Differentiation.cpp
@@ -33,36 +33,36 @@
 #include <QLocale>
 
 Differentiation::Differentiation(ApplicationWindow *parent, Graph *g)
-: Filter(parent, g)
-{
-	init();
+    : Filter(parent, g) {
+  init();
 }
 
-Differentiation::Differentiation(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Filter(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+Differentiation::Differentiation(ApplicationWindow *parent, Graph *g,
+                                 const QString &curveTitle)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-Differentiation::Differentiation(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Filter(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+Differentiation::Differentiation(ApplicationWindow *parent, Graph *g,
+                                 const QString &curveTitle, double start,
+                                 double end)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-Differentiation::Differentiation(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end)
-: Filter(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, start, end);
+Differentiation::Differentiation(ApplicationWindow *parent, Table *t,
+                                 const QString &xCol, const QString &yCol,
+                                 int start, int end)
+    : Filter(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, start, end);
 }
 
-void Differentiation::init()
-{
-	setObjectName(tr("Derivative"));
-    d_min_points = 4;
+void Differentiation::init() {
+  setObjectName(tr("Derivative"));
+  d_min_points = 4;
 }
 
 void Differentiation::output() {
diff --git a/MantidPlot/src/Differentiation.h b/MantidPlot/src/Differentiation.h
index 49d90debf0321953ddd55c0893426a8ec721804c..8386ea1c3ca5a17b6c022dc608b3e462c0d6fb81 100644
--- a/MantidPlot/src/Differentiation.h
+++ b/MantidPlot/src/Differentiation.h
@@ -31,18 +31,20 @@
 
 #include "Filter.h"
 
-class Differentiation : public Filter
-{
-Q_OBJECT
+class Differentiation : public Filter {
+  Q_OBJECT
 
 public:
-	Differentiation(ApplicationWindow *parent, Graph *g);
-	Differentiation(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-	Differentiation(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-	Differentiation(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start = 0, int end = -1);
+  Differentiation(ApplicationWindow *parent, Graph *g);
+  Differentiation(ApplicationWindow *parent, Graph *g,
+                  const QString &curveTitle);
+  Differentiation(ApplicationWindow *parent, Graph *g,
+                  const QString &curveTitle, double start, double end);
+  Differentiation(ApplicationWindow *parent, Table *t, const QString &xCol,
+                  const QString &yCol, int start = 0, int end = -1);
 
 private:
-    void init();
-    void output() override;
+  void init();
+  void output() override;
 };
 #endif
diff --git a/MantidPlot/src/DockedWindow.cpp b/MantidPlot/src/DockedWindow.cpp
index e512a3112540f768888d2592653691999013d0d9..0399a2e6aabb8f16718de9d89a203d5127ef8a99 100644
--- a/MantidPlot/src/DockedWindow.cpp
+++ b/MantidPlot/src/DockedWindow.cpp
@@ -7,13 +7,10 @@
 /**
  * Constructor.
  */
-DockedWindow::DockedWindow(ApplicationWindow* appWindow):
-  QMdiSubWindow(appWindow),
-  d_app(appWindow),
-  m_draggingToTiledWindow(false),
-  m_isInsideTiledWindow(false),
-  m_dragMouseDown(false)
-{
+DockedWindow::DockedWindow(ApplicationWindow *appWindow)
+    : QMdiSubWindow(appWindow), d_app(appWindow),
+      m_draggingToTiledWindow(false), m_isInsideTiledWindow(false),
+      m_dragMouseDown(false) {
   setFocusPolicy(Qt::StrongFocus);
   setAttribute(Qt::WA_DeleteOnClose);
 }
@@ -21,41 +18,37 @@ DockedWindow::DockedWindow(ApplicationWindow* appWindow):
 /**
   * Returns the inner MdiSubWindow.
   */
-MdiSubWindow* DockedWindow::mdiSubWindow() const
-{
-  return static_cast<MdiSubWindow*>(widget());
+MdiSubWindow *DockedWindow::mdiSubWindow() const {
+  return static_cast<MdiSubWindow *>(widget());
 }
 
 /**
  * Set the innner MdiSubWindow.
  * @param sw :: A subwindow to set.
  */
-void DockedWindow::setMdiSubWindow(MdiSubWindow* sw)
-{
+void DockedWindow::setMdiSubWindow(MdiSubWindow *sw) {
   setWidget(sw);
-  //setWindowIcon(sw->windowIcon());
-  connect(sw,SIGNAL(dragMousePress(QPoint)),this,SLOT(dragMousePress(QPoint)));
-  connect(sw,SIGNAL(dragMouseRelease(QPoint)),this,SLOT(dragMouseRelease(QPoint)));
-  connect(sw,SIGNAL(dragMouseMove(QPoint)),this,SLOT(dragMouseMove(QPoint)));
+  // setWindowIcon(sw->windowIcon());
+  connect(sw, SIGNAL(dragMousePress(QPoint)), this,
+          SLOT(dragMousePress(QPoint)));
+  connect(sw, SIGNAL(dragMouseRelease(QPoint)), this,
+          SLOT(dragMouseRelease(QPoint)));
+  connect(sw, SIGNAL(dragMouseMove(QPoint)), this, SLOT(dragMouseMove(QPoint)));
 }
 
 /**
  * Process state change events such as activation, minimizing or maximizing.
  */
-bool DockedWindow::event(QEvent * e)
-{
-  //std::cerr << "Docked event " << e->type() << std::endl;
-  if ( e->type() == QEvent::NonClientAreaMouseButtonPress )
-  {
+bool DockedWindow::event(QEvent *e) {
+  // std::cerr << "Docked event " << e->type() << std::endl;
+  if (e->type() == QEvent::NonClientAreaMouseButtonPress) {
     // User clicked the window title bar
     m_draggingToTiledWindow = true;
-  }
-  else if ( e->type() == QEvent::NonClientAreaMouseMove )
-  {
-    // For some reason this event is fired when the user releases the mouse over the title bar
-    if ( m_draggingToTiledWindow )
-    {
-      d_app->dropInTiledWindow( mdiSubWindow(), pos() - d_app->pos() );
+  } else if (e->type() == QEvent::NonClientAreaMouseMove) {
+    // For some reason this event is fired when the user releases the mouse over
+    // the title bar
+    if (m_draggingToTiledWindow) {
+      d_app->dropInTiledWindow(mdiSubWindow(), pos() - d_app->pos());
       return true;
     }
     m_draggingToTiledWindow = false;
@@ -64,42 +57,32 @@ bool DockedWindow::event(QEvent * e)
   return QMdiSubWindow::event(e);
 }
 
-void DockedWindow::moveEvent(QMoveEvent *ev)
-{
-  if ( m_draggingToTiledWindow )
-  {
+void DockedWindow::moveEvent(QMoveEvent *ev) {
+  if (m_draggingToTiledWindow) {
     // we are here if the window is being moved by the user
-    m_isInsideTiledWindow =  d_app->isInTiledWindow( ev->pos() - d_app->pos() );
-  }
-  else
-  {
+    m_isInsideTiledWindow = d_app->isInTiledWindow(ev->pos() - d_app->pos());
+  } else {
     m_isInsideTiledWindow = false;
   }
 }
 
-void DockedWindow::dragMousePress(QPoint pos)
-{
-  if ( d_app->hasTiledWindowOpen() )
-  {
+void DockedWindow::dragMousePress(QPoint pos) {
+  if (d_app->hasTiledWindowOpen()) {
     m_dragMouseDown = true;
     m_dragStartPos = pos;
   }
 }
 
-void DockedWindow::dragMouseRelease(QPoint)
-{
-  if ( m_dragMouseDown )
-  {
+void DockedWindow::dragMouseRelease(QPoint) {
+  if (m_dragMouseDown) {
     m_dragMouseDown = false;
   }
 }
 
-void DockedWindow::dragMouseMove(QPoint pos)
-{
-  if ( m_dragMouseDown )
-  {
-    if ((pos - m_dragStartPos).manhattanLength() < QApplication::startDragDistance())
-    {
+void DockedWindow::dragMouseMove(QPoint pos) {
+  if (m_dragMouseDown) {
+    if ((pos - m_dragStartPos).manhattanLength() <
+        QApplication::startDragDistance()) {
       return;
     }
 
@@ -107,11 +90,11 @@ void DockedWindow::dragMouseMove(QPoint pos)
     QMimeData *mimeData = new QMimeData;
 
     MdiSubWindow *ptr = mdiSubWindow();
-    auto d = QByteArray::fromRawData( (const char*)ptr, 1 );
-    mimeData->setData("TiledWindow",d);
+    auto d = QByteArray::fromRawData((const char *)ptr, 1);
+    mimeData->setData("TiledWindow", d);
 
     drag->setMimeData(mimeData);
     Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
-    (void) dropAction;
+    (void)dropAction;
   }
 }
diff --git a/MantidPlot/src/DockedWindow.h b/MantidPlot/src/DockedWindow.h
index 8b23d880152f3c8c536af80c6377e24e78521b72..195e470b548c572886d495ebae77a1f75d4bb9c0 100644
--- a/MantidPlot/src/DockedWindow.h
+++ b/MantidPlot/src/DockedWindow.h
@@ -11,13 +11,12 @@ class QSize;
 /**
  * Docked (MDI) wrapper window for a MdiSubWindow.
  */
-class DockedWindow: public QMdiSubWindow
-{
+class DockedWindow : public QMdiSubWindow {
   Q_OBJECT
 public:
   explicit DockedWindow(ApplicationWindow *appWindow);
-  MdiSubWindow* mdiSubWindow() const;
-  void setMdiSubWindow(MdiSubWindow* sw);
+  MdiSubWindow *mdiSubWindow() const;
+  void setMdiSubWindow(MdiSubWindow *sw);
 
 public slots:
   void dragMousePress(QPoint);
@@ -29,8 +28,7 @@ protected:
   void moveEvent(QMoveEvent *ev) override;
 
 private:
-
-  ApplicationWindow* d_app; ///< Pointer to the main window
+  ApplicationWindow *d_app; ///< Pointer to the main window
   bool m_draggingToTiledWindow;
   bool m_isInsideTiledWindow;
 
diff --git a/MantidPlot/src/ErrDialog.cpp b/MantidPlot/src/ErrDialog.cpp
index 191fc03960b69c65eb71b55c9f64bc23d5f27704..58fea0a7336c5f6cb15d505c005b3f2cf73acdbc 100644
--- a/MantidPlot/src/ErrDialog.cpp
+++ b/MantidPlot/src/ErrDialog.cpp
@@ -2,7 +2,8 @@
     File                 : ErrDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Add error bars dialog
 
@@ -45,15 +46,13 @@
 #include <QWidget>
 #include <QCheckBox>
 
-
-ErrDialog::ErrDialog( ApplicationWindow* parent, Qt::WFlags fl )
-  : QDialog( parent, fl )
-{
-  setFocusPolicy( Qt::StrongFocus );
-  setSizeGripEnabled( true );
+ErrDialog::ErrDialog(ApplicationWindow *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setFocusPolicy(Qt::StrongFocus);
+  setSizeGripEnabled(true);
 
   QVBoxLayout *vbox1 = new QVBoxLayout();
-  vbox1->setSpacing (5);
+  vbox1->setSpacing(5);
 
   QHBoxLayout *hbox1 = new QHBoxLayout();
   vbox1->addLayout(hbox1);
@@ -65,29 +64,30 @@ ErrDialog::ErrDialog( ApplicationWindow* parent, Qt::WFlags fl )
   hbox1->addWidget(nameLabel);
 
   groupBox1 = new QGroupBox(QString(tr("Source of errors")));
-  QGridLayout * gridLayout = new QGridLayout(groupBox1);
+  QGridLayout *gridLayout = new QGridLayout(groupBox1);
   vbox1->addWidget(groupBox1);
 
   buttonGroup1 = new QButtonGroup();
-  buttonGroup1->setExclusive( true );
+  buttonGroup1->setExclusive(true);
 
   // Add option to use Mantid workspace errors
   mantidBox = new QRadioButton();
-  // Since Mantid is only in English, just set this here instead of in languageChange()
+  // Since Mantid is only in English, just set this here instead of in
+  // languageChange()
   mantidBox->setText("Mantid Workspace");
-  mantidBox->setChecked( true );
+  mantidBox->setChecked(true);
   buttonGroup1->addButton(mantidBox);
   gridLayout->addWidget(mantidBox, 0, 0);
 
   drawAllErrors = new QCheckBox(this);
   drawAllErrors->setText("Draw all errors");
-  drawAllErrors->setChecked( parent->drawAllErrors );
+  drawAllErrors->setChecked(parent->drawAllErrors);
   gridLayout->addWidget(drawAllErrors, 0, 1);
 
   columnBox = new QRadioButton();
-  //columnBox->setChecked( true );  // Mantid button now takes this
+  // columnBox->setChecked( true );  // Mantid button now takes this
   buttonGroup1->addButton(columnBox);
-  gridLayout->addWidget(columnBox, 1, 0 );
+  gridLayout->addWidget(columnBox, 1, 0);
 
   colNamesBox = new QComboBox();
   tableNamesBox = new QComboBox();
@@ -95,7 +95,7 @@ ErrDialog::ErrDialog( ApplicationWindow* parent, Qt::WFlags fl )
   colNamesBox->setEnabled(false);
   tableNamesBox->setEnabled(false);
 
-  QHBoxLayout * comboBoxes = new QHBoxLayout();
+  QHBoxLayout *comboBoxes = new QHBoxLayout();
   comboBoxes->addWidget(tableNamesBox);
   comboBoxes->addWidget(colNamesBox);
 
@@ -103,39 +103,39 @@ ErrDialog::ErrDialog( ApplicationWindow* parent, Qt::WFlags fl )
 
   percentBox = new QRadioButton();
   buttonGroup1->addButton(percentBox);
-  gridLayout->addWidget(percentBox, 2, 0 );
+  gridLayout->addWidget(percentBox, 2, 0);
 
   valueBox = new QLineEdit();
   valueBox->setText("5");
-  valueBox->setAlignment( Qt::AlignHCenter );
+  valueBox->setAlignment(Qt::AlignHCenter);
   valueBox->setEnabled(false);
   gridLayout->addWidget(valueBox, 2, 1);
 
   standardBox = new QRadioButton();
   buttonGroup1->addButton(standardBox);
-  gridLayout->addWidget(standardBox, 3, 0 );
+  gridLayout->addWidget(standardBox, 3, 0);
 
   groupBox3 = new QGroupBox(QString());
   vbox1->addWidget(groupBox3);
-  QHBoxLayout * hbox2 = new QHBoxLayout(groupBox3);
+  QHBoxLayout *hbox2 = new QHBoxLayout(groupBox3);
 
   buttonGroup2 = new QButtonGroup();
-  buttonGroup2->setExclusive( true );
+  buttonGroup2->setExclusive(true);
 
   xErrBox = new QRadioButton();
   // Disable initially because Mantid button will be selected
   xErrBox->setEnabled(false);
   buttonGroup2->addButton(xErrBox);
-  hbox2->addWidget(xErrBox );
+  hbox2->addWidget(xErrBox);
 
   yErrBox = new QRadioButton();
   buttonGroup2->addButton(yErrBox);
-  hbox2->addWidget(yErrBox );
-  yErrBox->setChecked( true );
+  hbox2->addWidget(yErrBox);
+  yErrBox->setChecked(true);
 
-  QVBoxLayout * vbox2 = new QVBoxLayout();
+  QVBoxLayout *vbox2 = new QVBoxLayout();
   buttonAdd = new QPushButton();
-  buttonAdd->setDefault( true );
+  buttonAdd->setDefault(true);
   vbox2->addWidget(buttonAdd);
 
   buttonCancel = new QPushButton();
@@ -143,65 +143,67 @@ ErrDialog::ErrDialog( ApplicationWindow* parent, Qt::WFlags fl )
 
   vbox2->addStretch(1);
 
-  QHBoxLayout * hlayout1 = new QHBoxLayout(this);
+  QHBoxLayout *hlayout1 = new QHBoxLayout(this);
   hlayout1->addLayout(vbox1);
   hlayout1->addLayout(vbox2);
 
   languageChange();
 
   // signals and slots connections
-  connect( buttonAdd, SIGNAL( clicked() ), this, SLOT( add() ) );
-  connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-  connect( percentBox, SIGNAL( toggled(bool) ), valueBox, SLOT( setEnabled(bool) ) );
-  connect( columnBox, SIGNAL( toggled(bool) ), tableNamesBox, SLOT( setEnabled(bool) ) );
-  connect( columnBox, SIGNAL( toggled(bool) ), colNamesBox, SLOT( setEnabled(bool) ) );
-  connect( tableNamesBox, SIGNAL( activated(int) ), this, SLOT( selectSrcTable(int) ));
+  connect(buttonAdd, SIGNAL(clicked()), this, SLOT(add()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(percentBox, SIGNAL(toggled(bool)), valueBox, SLOT(setEnabled(bool)));
+  connect(columnBox, SIGNAL(toggled(bool)), tableNamesBox,
+          SLOT(setEnabled(bool)));
+  connect(columnBox, SIGNAL(toggled(bool)), colNamesBox,
+          SLOT(setEnabled(bool)));
+  connect(tableNamesBox, SIGNAL(activated(int)), this,
+          SLOT(selectSrcTable(int)));
   // Don't allow X errors to be asked for if choosing Mantid errors
-  connect( mantidBox, SIGNAL( toggled(bool) ), xErrBox, SLOT( setDisabled(bool) ) );
+  connect(mantidBox, SIGNAL(toggled(bool)), xErrBox, SLOT(setDisabled(bool)));
 }
 
-void ErrDialog::setCurveNames(const QStringList& names)
-{
+void ErrDialog::setCurveNames(const QStringList &names) {
   nameLabel->addItems(names);
 }
 
-void ErrDialog::setSrcTables(QList<MdiSubWindow *> tables)
-{
+void ErrDialog::setSrcTables(QList<MdiSubWindow *> tables) {
   if (tables.isEmpty())
     return;
 
   srcTables = tables;
   tableNamesBox->clear();
 
-  foreach(MdiSubWindow *w, tables)
+  foreach (MdiSubWindow *w, tables)
     tableNamesBox->addItem(w->objectName());
 
   if (!nameLabel->currentText().contains("="))
-    tableNamesBox->setCurrentIndex(tableNamesBox->findText(nameLabel->currentText().split("_", QString::SkipEmptyParts)[0]));
-  if (tableNamesBox->currentIndex() != -1) selectSrcTable(tableNamesBox->currentIndex());
+    tableNamesBox->setCurrentIndex(tableNamesBox->findText(
+        nameLabel->currentText().split("_", QString::SkipEmptyParts)[0]));
+  if (tableNamesBox->currentIndex() != -1)
+    selectSrcTable(tableNamesBox->currentIndex());
 }
 
-void ErrDialog::selectSrcTable(int tabnr)
-{
-  auto table = dynamic_cast<Table*>(srcTables.at(tabnr));
+void ErrDialog::selectSrcTable(int tabnr) {
+  auto table = dynamic_cast<Table *>(srcTables.at(tabnr));
   if (table) {
     colNamesBox->clear();
     colNamesBox->addItems(table->colNames());
   }
 }
 
-void ErrDialog::add()
-{
-  int direction=-1;
+void ErrDialog::add() {
+  int direction = -1;
   if (xErrBox->isChecked())
     direction = 0;
   else
     direction = 1;
 
   if (columnBox->isChecked())
-    emit options(nameLabel->currentText(), tableNamesBox->currentText()+"_"+colNamesBox->currentText(), direction);
-  else
-  {
+    emit options(nameLabel->currentText(), tableNamesBox->currentText() + "_" +
+                                               colNamesBox->currentText(),
+                 direction);
+  else {
     int type;
     if (percentBox->isChecked())
       type = 0;
@@ -210,23 +212,24 @@ void ErrDialog::add()
     else // Use this if the Mantid box is checked
       type = 2;
 
-    emit options(nameLabel->currentText(),type, valueBox->text(), direction,drawAllErrors->isChecked());
+    emit options(nameLabel->currentText(), type, valueBox->text(), direction,
+                 drawAllErrors->isChecked());
   }
 
   // If there's only one curve, close the dialog now
-  if ( nameLabel->count() == 1 ) reject();
+  if (nameLabel->count() == 1)
+    reject();
 }
 
-void ErrDialog::languageChange()
-{
-  setWindowTitle( tr( "MantidPlot - Error Bars" ) );
-  xErrBox->setText( tr( "&X Error Bars" ) );
-  buttonAdd->setText( tr( "&Add" ) );
-  textLabel1->setText( tr( "Add Error Bars to" ) );
-  groupBox1->setTitle( tr( "Source of errors" ) );
-  percentBox->setText( tr( "Percent of data (%)" ) );
-  standardBox->setText( tr( "Standard Deviation of Data" ) );
-  yErrBox->setText( tr( "&Y Error Bars" ) );
-  buttonCancel->setText( tr( "&Close" ) );
+void ErrDialog::languageChange() {
+  setWindowTitle(tr("MantidPlot - Error Bars"));
+  xErrBox->setText(tr("&X Error Bars"));
+  buttonAdd->setText(tr("&Add"));
+  textLabel1->setText(tr("Add Error Bars to"));
+  groupBox1->setTitle(tr("Source of errors"));
+  percentBox->setText(tr("Percent of data (%)"));
+  standardBox->setText(tr("Standard Deviation of Data"));
+  yErrBox->setText(tr("&Y Error Bars"));
+  buttonCancel->setText(tr("&Close"));
   columnBox->setText(tr("Existing column"));
 }
diff --git a/MantidPlot/src/ErrDialog.h b/MantidPlot/src/ErrDialog.h
index adb2f60441eeea58bffee08911593e2ac9f57380..b89d0791ebe211c0e06aec295725bb5fc1cc9c4b 100644
--- a/MantidPlot/src/ErrDialog.h
+++ b/MantidPlot/src/ErrDialog.h
@@ -2,7 +2,8 @@
     File                 : ErrDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Add error bars dialog
 
@@ -43,8 +44,7 @@ class MdiSubWindow;
 class ApplicationWindow;
 
 //! Add error bars dialog
-class ErrDialog : public QDialog
-{
+class ErrDialog : public QDialog {
   Q_OBJECT
 
 public:
@@ -53,25 +53,25 @@ public:
    * @param parent :: parent widget
    * @param fl :: window flags
    */
-  ErrDialog( ApplicationWindow* parent, Qt::WFlags fl = 0 );
+  ErrDialog(ApplicationWindow *parent, Qt::WFlags fl = 0);
 
 private:
-  QLabel* textLabel1;
-  QComboBox* nameLabel, *tableNamesBox, *colNamesBox;
+  QLabel *textLabel1;
+  QComboBox *nameLabel, *tableNamesBox, *colNamesBox;
   QGroupBox *groupBox2;
   QGroupBox *groupBox1, *groupBox3;
   QButtonGroup *buttonGroup1, *buttonGroup2;
-  QRadioButton* standardBox, *columnBox;
-  QRadioButton* percentBox;
-  QLineEdit* valueBox;
-  QRadioButton* xErrBox;
-  QRadioButton* yErrBox;
-  QPushButton* buttonAdd;
-  QPushButton* buttonCancel;
-  QList<MdiSubWindow*> srcTables;
+  QRadioButton *standardBox, *columnBox;
+  QRadioButton *percentBox;
+  QLineEdit *valueBox;
+  QRadioButton *xErrBox;
+  QRadioButton *yErrBox;
+  QPushButton *buttonAdd;
+  QPushButton *buttonCancel;
+  QList<MdiSubWindow *> srcTables;
 
-  QRadioButton* mantidBox;
-  QCheckBox* drawAllErrors;
+  QRadioButton *mantidBox;
+  QCheckBox *drawAllErrors;
 
 protected slots:
   //! Set all string in the current language
@@ -81,7 +81,7 @@ public slots:
   //! Add a plot definition
   void add();
   //! Supply the dialog with a curves list
-  void setCurveNames(const QStringList& names);
+  void setCurveNames(const QStringList &names);
   //! Supply the dialog with a tables list
   void setSrcTables(QList<MdiSubWindow *> tables);
   //! Select a table
@@ -89,9 +89,11 @@ public slots:
 
 signals:
   //! This is usually connected to the main window's defineErrorBars() slot
-  void options(const QString& curveName, int type, const QString& percent,int direction,bool all);
+  void options(const QString &curveName, int type, const QString &percent,
+               int direction, bool all);
   //! This is usually connected to the main window's defineErrorBars() slot
-  void options(const QString& curveName, const QString& errColumnName, int direction);
+  void options(const QString &curveName, const QString &errColumnName,
+               int direction);
 };
 
 #endif // ERRDIALOG_H
diff --git a/MantidPlot/src/ExpDecayDialog.cpp b/MantidPlot/src/ExpDecayDialog.cpp
index 2fdc7427aa8d7e7c76b0620c0a23c452e453b9b9..552c432c5332e4cad7fe84566a1b0834f334042a 100644
--- a/MantidPlot/src/ExpDecayDialog.cpp
+++ b/MantidPlot/src/ExpDecayDialog.cpp
@@ -2,7 +2,8 @@
     File                 : ExpDecayDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fit exponential decay dialog
 
@@ -41,238 +42,223 @@
 #include <QLineEdit>
 #include <QComboBox>
 
-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)
-{
-    setObjectName( "ExpDecayDialog" );
-
-	slopes = type;
-
-	setWindowTitle(tr("MantidPlot - Verify initial guesses"));
-
-	QGroupBox *gb1 = new QGroupBox();
-	QGridLayout *gl1 = new QGridLayout();
-	gl1->addWidget(new QLabel(tr("Exponential Fit of")), 0, 0);
-
-	boxName = new QComboBox();
-	connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT( activateCurve(const QString&) ) );
-	gl1->addWidget(boxName, 0, 1);
-
-	if (type < 0)
-		dampingLabel = new QLabel( tr("Growth time"));
-	else if (type == 1)
-		dampingLabel = new QLabel( tr("Decay time"));
-	else
-		dampingLabel = new QLabel( tr("First decay time (t1)"));
-	gl1->addWidget(dampingLabel, 1, 0);
-
-	boxFirst = new QLineEdit();
-	boxFirst->setText(tr("1"));
-	gl1->addWidget(boxFirst, 1, 1);
-
-	if (type > 1)
-	{
-		gl1->addWidget(new QLabel( tr("Second decay time (t2)")), 2, 0);
-
-		boxSecond = new QLineEdit();
-		boxSecond->setText(tr("1"));
-		gl1->addWidget(boxSecond, 2, 1);
-
-		thirdLabel = new QLabel( tr("Third decay time (t3)"));
-		gl1->addWidget(thirdLabel, 3, 0);
-
-		boxThird = new QLineEdit();
-		boxThird->setText(tr("1"));
-		gl1->addWidget(boxThird, 3, 1);
-
-		if (type < 3)
-		{
-			thirdLabel->hide();
-			boxThird->hide();
-		}
-	}
-
-	if (type <= 1)
-	{
-		gl1->addWidget(new QLabel(tr("Amplitude")), 2, 0);
-		boxAmplitude = new QLineEdit();
-		boxAmplitude->setText(tr("1"));
-		gl1->addWidget(boxAmplitude, 2, 1);
-	}
-
-	gl1->addWidget(new QLabel(tr("Y Offset")), 4, 0 );
-	boxYOffset = new QLineEdit();
-	boxYOffset->setText(tr("0"));
-	gl1->addWidget(boxYOffset, 4, 1);
-
-    gl1->addWidget(new QLabel(tr("Initial time")), 5, 0);
-
-	boxStart = new QLineEdit();
-	boxStart->setText(tr("0"));
-	gl1->addWidget(boxStart, 5, 1);
-
-	gl1->addWidget(new QLabel(tr("Color")), 6, 0 );
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
-	gl1->addWidget(boxColor, 6, 1);
-
-	gb1->setLayout(gl1);
-
-	buttonFit = new QPushButton(tr("&Fit"));
-	buttonFit->setDefault(true);
-
-	buttonCancel = new QPushButton(tr("&Close"));
-
-	QBoxLayout *bl1 = new QBoxLayout (QBoxLayout::TopToBottom);
-	bl1->addWidget(buttonFit);
-	bl1->addWidget(buttonCancel);
-	bl1->addStretch();
-
-	QHBoxLayout* hlayout = new QHBoxLayout();
-	hlayout->addWidget(gb1);
-	hlayout->addLayout(bl1);
-	setLayout(hlayout);
-
-	// signals and slots connections
-	connect( buttonFit, SIGNAL( clicked() ), this, SLOT(fit()));
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT(close()));
+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) {
+  setObjectName("ExpDecayDialog");
+
+  slopes = type;
+
+  setWindowTitle(tr("MantidPlot - Verify initial guesses"));
+
+  QGroupBox *gb1 = new QGroupBox();
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Exponential Fit of")), 0, 0);
+
+  boxName = new QComboBox();
+  connect(boxName, SIGNAL(activated(const QString &)), this,
+          SLOT(activateCurve(const QString &)));
+  gl1->addWidget(boxName, 0, 1);
+
+  if (type < 0)
+    dampingLabel = new QLabel(tr("Growth time"));
+  else if (type == 1)
+    dampingLabel = new QLabel(tr("Decay time"));
+  else
+    dampingLabel = new QLabel(tr("First decay time (t1)"));
+  gl1->addWidget(dampingLabel, 1, 0);
+
+  boxFirst = new QLineEdit();
+  boxFirst->setText(tr("1"));
+  gl1->addWidget(boxFirst, 1, 1);
+
+  if (type > 1) {
+    gl1->addWidget(new QLabel(tr("Second decay time (t2)")), 2, 0);
+
+    boxSecond = new QLineEdit();
+    boxSecond->setText(tr("1"));
+    gl1->addWidget(boxSecond, 2, 1);
+
+    thirdLabel = new QLabel(tr("Third decay time (t3)"));
+    gl1->addWidget(thirdLabel, 3, 0);
+
+    boxThird = new QLineEdit();
+    boxThird->setText(tr("1"));
+    gl1->addWidget(boxThird, 3, 1);
+
+    if (type < 3) {
+      thirdLabel->hide();
+      boxThird->hide();
+    }
+  }
+
+  if (type <= 1) {
+    gl1->addWidget(new QLabel(tr("Amplitude")), 2, 0);
+    boxAmplitude = new QLineEdit();
+    boxAmplitude->setText(tr("1"));
+    gl1->addWidget(boxAmplitude, 2, 1);
+  }
+
+  gl1->addWidget(new QLabel(tr("Y Offset")), 4, 0);
+  boxYOffset = new QLineEdit();
+  boxYOffset->setText(tr("0"));
+  gl1->addWidget(boxYOffset, 4, 1);
+
+  gl1->addWidget(new QLabel(tr("Initial time")), 5, 0);
+
+  boxStart = new QLineEdit();
+  boxStart->setText(tr("0"));
+  gl1->addWidget(boxStart, 5, 1);
+
+  gl1->addWidget(new QLabel(tr("Color")), 6, 0);
+  boxColor = new ColorBox();
+  boxColor->setColor(QColor(Qt::red));
+  gl1->addWidget(boxColor, 6, 1);
+
+  gb1->setLayout(gl1);
+
+  buttonFit = new QPushButton(tr("&Fit"));
+  buttonFit->setDefault(true);
+
+  buttonCancel = new QPushButton(tr("&Close"));
+
+  QBoxLayout *bl1 = new QBoxLayout(QBoxLayout::TopToBottom);
+  bl1->addWidget(buttonFit);
+  bl1->addWidget(buttonCancel);
+  bl1->addStretch();
+
+  QHBoxLayout *hlayout = new QHBoxLayout();
+  hlayout->addWidget(gb1);
+  hlayout->addLayout(bl1);
+  setLayout(hlayout);
+
+  // signals and slots connections
+  connect(buttonFit, SIGNAL(clicked()), this, SLOT(fit()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
 }
 
-void ExpDecayDialog::setGraph(Graph *g)
-{
-	if (!g)
-		return;
+void ExpDecayDialog::setGraph(Graph *g) {
+  if (!g)
+    return;
 
-    fitter = 0;
-	graph = g;
+  fitter = 0;
+  graph = g;
 
-	boxName->addItems(graph->analysableCurvesList());
+  boxName->addItems(graph->analysableCurvesList());
 
-    QString selectedCurve = g->selectedCurveTitle();
-	if (!selectedCurve.isEmpty())
-	{
-	    int index = boxName->findText (selectedCurve);
-		boxName->setCurrentIndex(index);
-	}
-    activateCurve(boxName->currentText());
+  QString selectedCurve = g->selectedCurveTitle();
+  if (!selectedCurve.isEmpty()) {
+    int index = boxName->findText(selectedCurve);
+    boxName->setCurrentIndex(index);
+  }
+  activateCurve(boxName->currentText());
 
-	connect (graph, SIGNAL(closedGraph()), this, SLOT(close()));
-    connect (graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
+  connect(graph, SIGNAL(closedGraph()), this, SLOT(close()));
+  connect(graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
 }
 
-void ExpDecayDialog::activateCurve(const QString& curveName)
-{
-	QwtPlotCurve *c = graph->curve(curveName);
-	if (!c)
-		return;
-
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (!app)
-        return;
-
-	int precision = app->fit_output_precision;
-	double start, end;
-	graph->range(graph->curveIndex(curveName), &start, &end);
-	boxStart->setText(QString::number(QMIN(start, end)));
-	boxYOffset->setText(QString::number(c->minYValue(), 'g', precision));
-	if (slopes < 2)
-        boxAmplitude->setText(QString::number(c->maxYValue() - c->minYValue(), 'g', precision));
-
+void ExpDecayDialog::activateCurve(const QString &curveName) {
+  QwtPlotCurve *c = graph->curve(curveName);
+  if (!c)
+    return;
+
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
+
+  int precision = app->fit_output_precision;
+  double start, end;
+  graph->range(graph->curveIndex(curveName), &start, &end);
+  boxStart->setText(QString::number(QMIN(start, end)));
+  boxYOffset->setText(QString::number(c->minYValue(), 'g', precision));
+  if (slopes < 2)
+    boxAmplitude->setText(
+        QString::number(c->maxYValue() - c->minYValue(), 'g', precision));
 }
 
-void ExpDecayDialog::changeDataRange()
-{
-double start = graph->selectedXStartValue();
-double end = graph->selectedXEndValue();
-boxStart->setText(QString::number(QMIN(start, end), 'g', 15));
+void ExpDecayDialog::changeDataRange() {
+  double start = graph->selectedXStartValue();
+  double end = graph->selectedXEndValue();
+  boxStart->setText(QString::number(QMIN(start, end), 'g', 15));
 }
 
-void ExpDecayDialog::fit()
-{
-	QString curve = boxName->currentText();
-	QwtPlotCurve *c = graph->curve(curve);
-	QStringList curvesList = graph->analysableCurvesList();
-	if (!c || !curvesList.contains(curve))
-	{
-		QMessageBox::critical(this,tr("MantidPlot - Warning"),
-				tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!").arg(curve));
-		boxName->clear();
-		boxName->addItems(curvesList);
-		return;
-	}
-
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (!app)
-        return;
-
-	int precision = app->fit_output_precision;
-
-	if (slopes == 3)
-	{
-		double x_init[7] = {1.0, boxFirst->text().toDouble(), 1.0, boxSecond->text().toDouble(),
-			1.0, boxThird->text().toDouble(), boxYOffset->text().toDouble()};
-		delete fitter;
-		fitter = new ThreeExpFit(app, graph);
-		fitter->setInitialGuesses(x_init);
-	}
-	else if (slopes == 2)
-	{
-		double x_init[5] = {1.0, boxFirst->text().toDouble(), 1.0, boxSecond->text().toDouble(),
-			boxYOffset->text().toDouble()};
-		delete fitter;
-		fitter = new TwoExpFit(app, graph);
-		fitter->setInitialGuesses(x_init);
-	}
-	else if (slopes == 1 || slopes == -1)
-	{
-		double x_init[3] = {boxAmplitude->text().toDouble(), slopes/boxFirst->text().toDouble(), boxYOffset->text().toDouble()};
-		delete fitter;
-		fitter = new ExponentialFit(app, graph, slopes == -1);
-		fitter->setInitialGuesses(x_init);
-	}
-
-  	if (fitter->setDataFromCurve(boxName->currentText(), boxStart->text().toDouble(), c->maxXValue()))
-	{
-		fitter->setColor(boxColor->currentIndex());
-		fitter->scaleErrors(app->fit_scale_errors);
-        fitter->setOutputPrecision(app->fit_output_precision);
-		fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
-		fitter->fit();
-
-		double *results = fitter->results();
-		boxFirst->setText(QString::number(results[1], 'g', precision));
-		if (slopes < 2)
-		{
-            boxAmplitude->setText(QString::number(results[0], 'g', precision));
-            boxYOffset->setText(QString::number(results[2], 'g', precision));
-        }
-        else if (slopes == 2)
-        {
-            boxSecond->setText(QString::number(results[3], 'g', precision));
-            boxYOffset->setText(QString::number(results[4], 'g', precision));
-        }
-        else if (slopes == 3)
-        {
-            boxSecond->setText(QString::number(results[3], 'g', precision));
-            boxThird->setText(QString::number(results[5], 'g', precision));
-            boxYOffset->setText(QString::number(results[6], 'g', precision));
-        }
-	}
+void ExpDecayDialog::fit() {
+  QString curve = boxName->currentText();
+  QwtPlotCurve *c = graph->curve(curve);
+  QStringList curvesList = graph->analysableCurvesList();
+  if (!c || !curvesList.contains(curve)) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Warning"),
+        tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!")
+            .arg(curve));
+    boxName->clear();
+    boxName->addItems(curvesList);
+    return;
+  }
+
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
+
+  int precision = app->fit_output_precision;
+
+  if (slopes == 3) {
+    double x_init[7] = {
+        1.0, boxFirst->text().toDouble(), 1.0, boxSecond->text().toDouble(),
+        1.0, boxThird->text().toDouble(), boxYOffset->text().toDouble()};
+    delete fitter;
+    fitter = new ThreeExpFit(app, graph);
+    fitter->setInitialGuesses(x_init);
+  } else if (slopes == 2) {
+    double x_init[5] = {1.0, boxFirst->text().toDouble(), 1.0,
+                        boxSecond->text().toDouble(),
+                        boxYOffset->text().toDouble()};
+    delete fitter;
+    fitter = new TwoExpFit(app, graph);
+    fitter->setInitialGuesses(x_init);
+  } else if (slopes == 1 || slopes == -1) {
+    double x_init[3] = {boxAmplitude->text().toDouble(),
+                        slopes / boxFirst->text().toDouble(),
+                        boxYOffset->text().toDouble()};
+    delete fitter;
+    fitter = new ExponentialFit(app, graph, slopes == -1);
+    fitter->setInitialGuesses(x_init);
+  }
+
+  if (fitter->setDataFromCurve(boxName->currentText(),
+                               boxStart->text().toDouble(), c->maxXValue())) {
+    fitter->setColor(boxColor->currentIndex());
+    fitter->scaleErrors(app->fit_scale_errors);
+    fitter->setOutputPrecision(app->fit_output_precision);
+    fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
+    fitter->fit();
+
+    double *results = fitter->results();
+    boxFirst->setText(QString::number(results[1], 'g', precision));
+    if (slopes < 2) {
+      boxAmplitude->setText(QString::number(results[0], 'g', precision));
+      boxYOffset->setText(QString::number(results[2], 'g', precision));
+    } else if (slopes == 2) {
+      boxSecond->setText(QString::number(results[3], 'g', precision));
+      boxYOffset->setText(QString::number(results[4], 'g', precision));
+    } else if (slopes == 3) {
+      boxSecond->setText(QString::number(results[3], 'g', precision));
+      boxThird->setText(QString::number(results[5], 'g', precision));
+      boxYOffset->setText(QString::number(results[6], 'g', precision));
+    }
+  }
 }
 
-void ExpDecayDialog::closeEvent (QCloseEvent * e )
-{
-	if(fitter)
-	{
-				ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-        if (app && app->pasteFitResultsToPlot)
-            fitter->showLegend();
+void ExpDecayDialog::closeEvent(QCloseEvent *e) {
+  if (fitter) {
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (app && app->pasteFitResultsToPlot)
+      fitter->showLegend();
 
-        delete fitter;
-	}
+    delete fitter;
+  }
 
-	e->accept();
+  e->accept();
 }
diff --git a/MantidPlot/src/ExpDecayDialog.h b/MantidPlot/src/ExpDecayDialog.h
index b41b67e93706380a2fa4d4206c2ec04a29e351ab..79887f8ad2795271909d4922d02a0fbe256817f3 100644
--- a/MantidPlot/src/ExpDecayDialog.h
+++ b/MantidPlot/src/ExpDecayDialog.h
@@ -2,7 +2,8 @@
     File                 : ExpDecayDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fit exponential decay dialog
 
@@ -40,46 +41,43 @@ class ColorBox;
 class Fit;
 
 //! Fit exponential decay dialog
-class ExpDecayDialog : public QDialog
-{
-    Q_OBJECT
+class ExpDecayDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    ExpDecayDialog( int type, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  ExpDecayDialog(int type, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void fit();
-	void setGraph(Graph *g);
+  void fit();
+  void setGraph(Graph *g);
 
 private slots:
-    void activateCurve(const QString& curveName);
-	void changeDataRange();
+  void activateCurve(const QString &curveName);
+  void changeDataRange();
 
 signals:
-	void options(const QString&,double,double,double,double,int);
-	void options(const QString&, double,double,double,int);
-	void options3(const QString&,double,double,double,double,double,int);
+  void options(const QString &, double, double, double, double, int);
+  void options(const QString &, double, double, double, int);
+  void options3(const QString &, double, double, double, double, double, int);
 
 private:
   void closeEvent(QCloseEvent *) override;
 
-    Fit *fitter;
-	Graph *graph;
-	int slopes;
+  Fit *fitter;
+  Graph *graph;
+  int slopes;
 
-	QPushButton* buttonFit;
-	QPushButton* buttonCancel;
-	QComboBox* boxName;
-	QLineEdit* boxAmplitude;
-	QLineEdit* boxFirst;
-	QLineEdit* boxSecond;
-	QLineEdit* boxThird;
-	QLineEdit* boxStart;
-	QLineEdit* boxYOffset;
-	QLabel* thirdLabel, *dampingLabel;
-	ColorBox* boxColor;
+  QPushButton *buttonFit;
+  QPushButton *buttonCancel;
+  QComboBox *boxName;
+  QLineEdit *boxAmplitude;
+  QLineEdit *boxFirst;
+  QLineEdit *boxSecond;
+  QLineEdit *boxThird;
+  QLineEdit *boxStart;
+  QLineEdit *boxYOffset;
+  QLabel *thirdLabel, *dampingLabel;
+  ColorBox *boxColor;
 };
 
 #endif
-
-
diff --git a/MantidPlot/src/ExponentialFit.cpp b/MantidPlot/src/ExponentialFit.cpp
index 15816c9637bfd24975ec694f75c1fb6922a57c27..c5cc56c7ec47cd2805c9946bd4dab1098f4e829d 100644
--- a/MantidPlot/src/ExponentialFit.cpp
+++ b/MantidPlot/src/ExponentialFit.cpp
@@ -2,7 +2,8 @@
     File                 : fitclasses.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Exponential fit classes
 
@@ -37,89 +38,86 @@
  *
  *****************************************************************************/
 
-ExponentialFit::ExponentialFit(ApplicationWindow *parent, Graph *g, bool expGrowth)
-: Fit(parent, g),
-	is_exp_growth(expGrowth)
-{
-	init();
+ExponentialFit::ExponentialFit(ApplicationWindow *parent, Graph *g,
+                               bool expGrowth)
+    : Fit(parent, g), is_exp_growth(expGrowth) {
+  init();
 }
 
-ExponentialFit::ExponentialFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, bool expGrowth)
-: Fit(parent, g),
-  is_exp_growth(expGrowth)
-{
-	init();
-	setDataFromCurve(curveTitle);
+ExponentialFit::ExponentialFit(ApplicationWindow *parent, Graph *g,
+                               const QString &curveTitle, bool expGrowth)
+    : Fit(parent, g), is_exp_growth(expGrowth) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
 ExponentialFit::ExponentialFit(ApplicationWindow *parent, Graph *g,
-		const QString& curveTitle, double start, double end, bool expGrowth)
-: Fit(parent, g),
-	is_exp_growth(expGrowth)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+                               const QString &curveTitle, double start,
+                               double end, bool expGrowth)
+    : Fit(parent, g), is_exp_growth(expGrowth) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-ExponentialFit::ExponentialFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow, bool expGrowth)
-: Fit(parent, t), is_exp_growth(expGrowth)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+ExponentialFit::ExponentialFit(ApplicationWindow *parent, Table *t,
+                               const QString &xCol, const QString &yCol,
+                               int startRow, int endRow, bool expGrowth)
+    : Fit(parent, t), is_exp_growth(expGrowth) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void ExponentialFit::init()
-{
-	d_f = exp_f;
-	d_df = exp_df;
-	d_fdf = exp_fdf;
-	d_fsimplex = exp_d;
-	d_p = 3;
-	initWorkspace(d_p);
+void ExponentialFit::init() {
+  d_f = exp_f;
+  d_df = exp_df;
+  d_fdf = exp_fdf;
+  d_fsimplex = exp_d;
+  d_p = 3;
+  initWorkspace(d_p);
 
-	d_param_names << "A" << "t" << "y0";
+  d_param_names << "A"
+                << "t"
+                << "y0";
 
-	if (is_exp_growth) {
-		setObjectName(tr("ExpGrowth"));
-		d_explanation = tr("Exponential growth");
-		d_formula = "y0+A*exp(x/t)";
-		d_param_explain << tr("amplitude") << tr("lifetime") << tr("offset");
-	} else {
-		setObjectName(tr("ExpDecay1"));
-		d_explanation = tr("Exponential decay");
-		d_formula = "y0+A*exp(-x/t)";
-		d_param_explain << tr("amplitude") << tr("e-folding time") << tr("offset");
-	}
+  if (is_exp_growth) {
+    setObjectName(tr("ExpGrowth"));
+    d_explanation = tr("Exponential growth");
+    d_formula = "y0+A*exp(x/t)";
+    d_param_explain << tr("amplitude") << tr("lifetime") << tr("offset");
+  } else {
+    setObjectName(tr("ExpDecay1"));
+    d_explanation = tr("Exponential decay");
+    d_formula = "y0+A*exp(-x/t)";
+    d_param_explain << tr("amplitude") << tr("e-folding time") << tr("offset");
+  }
 }
 
-void ExponentialFit::customizeFitResults()
-{
-	if (is_exp_growth)
-		d_results[1] = -1.0/d_results[1];
-	else
-		d_results[1] = 1.0/d_results[1];
+void ExponentialFit::customizeFitResults() {
+  if (is_exp_growth)
+    d_results[1] = -1.0 / d_results[1];
+  else
+    d_results[1] = 1.0 / d_results[1];
 }
 
-void ExponentialFit::calculateFitCurveData(double *X, double *Y)
-{
-	double a = d_results[0];
-	double l = -d_results[1];
-	double y0 = d_results[2];
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++) {
-		    double x = X0+i*step;
-			X[i] = x;
-			Y[i] = a*exp(l*x) + y0;
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i] = a*exp(l*x) + y0;
-		}
-	}
+void ExponentialFit::calculateFitCurveData(double *X, double *Y) {
+  double a = d_results[0];
+  double l = -d_results[1];
+  double y0 = d_results[2];
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = a * exp(l * x) + y0;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = a * exp(l * x) + y0;
+    }
+  }
 }
 
 /*****************************************************************************
@@ -128,77 +126,78 @@ void ExponentialFit::calculateFitCurveData(double *X, double *Y)
  *
  *****************************************************************************/
 
-TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g) : Fit(parent, g) {
+  init();
 }
 
-TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+TwoExpFit::TwoExpFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-TwoExpFit::TwoExpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+TwoExpFit::TwoExpFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                     const QString &yCol, int startRow, int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void TwoExpFit::init()
-{
-	setObjectName(tr("ExpDecay2"));
-	d_f = expd2_f;
-	d_df = expd2_df;
-	d_fdf = expd2_fdf;
-	d_fsimplex = expd2_d;
-	d_p = 5;
-    initWorkspace(d_p);
-	d_param_names << "A1" << "t1" << "A2" << "t2" << "y0";
-	d_explanation = tr("Exponential decay");
-	d_formula = "A1*exp(-x/t1)+A2*exp(-x/t2)+y0";
-	d_param_explain << tr("first amplitude") << tr("first lifetime") << tr("second amplitude") << tr("second lifetime") << tr("offset");
+void TwoExpFit::init() {
+  setObjectName(tr("ExpDecay2"));
+  d_f = expd2_f;
+  d_df = expd2_df;
+  d_fdf = expd2_fdf;
+  d_fsimplex = expd2_d;
+  d_p = 5;
+  initWorkspace(d_p);
+  d_param_names << "A1"
+                << "t1"
+                << "A2"
+                << "t2"
+                << "y0";
+  d_explanation = tr("Exponential decay");
+  d_formula = "A1*exp(-x/t1)+A2*exp(-x/t2)+y0";
+  d_param_explain << tr("first amplitude") << tr("first lifetime")
+                  << tr("second amplitude") << tr("second lifetime")
+                  << tr("offset");
 }
 
-void TwoExpFit::customizeFitResults()
-{
-    d_results[1] = 1.0/d_results[1];
-	d_results[3] = 1.0/d_results[3];
+void TwoExpFit::customizeFitResults() {
+  d_results[1] = 1.0 / d_results[1];
+  d_results[3] = 1.0 / d_results[3];
 }
 
-void TwoExpFit::calculateFitCurveData(double *X, double *Y)
-{
-	double a1 = d_results[0];
-	double l1 = -d_results[1];
-	double a2 = d_results[2];
-	double l2 = -d_results[3];
-	double y0 = d_results[4];
-	
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0 + i*step;
-			X[i] = x;
-			Y[i] = a1*exp(l1*x) + a2*exp(l2*x) + y0;
-		}
-	} else {
-		for (int i=0; i<d_points; i++){
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i] = a1*exp(l1*x) + a2*exp(l2*x) + y0;
-		}
-	}
+void TwoExpFit::calculateFitCurveData(double *X, double *Y) {
+  double a1 = d_results[0];
+  double l1 = -d_results[1];
+  double a2 = d_results[2];
+  double l2 = -d_results[3];
+  double y0 = d_results[4];
+
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = a1 * exp(l1 * x) + a2 * exp(l2 * x) + y0;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = a1 * exp(l1 * x) + a2 * exp(l2 * x) + y0;
+    }
+  }
 }
 
 /*****************************************************************************
@@ -207,78 +206,83 @@ void TwoExpFit::calculateFitCurveData(double *X, double *Y)
  *
  *****************************************************************************/
 
-ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g) : Fit(parent, g) {
+  init();
 }
 
-ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+ThreeExpFit::ThreeExpFit(ApplicationWindow *parent, Table *t,
+                         const QString &xCol, const QString &yCol, int startRow,
+                         int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void ThreeExpFit::init()
-{
-	setObjectName(tr("ExpDecay3"));
-	d_f = expd3_f;
-	d_df = expd3_df;
-	d_fdf = expd3_fdf;
-	d_fsimplex = expd3_d;
-	d_p = 7;
-    initWorkspace(d_p);
-	d_param_names << "A1" << "t1" << "A2" << "t2" << "A3" << "t3" << "y0";
-	d_explanation = tr("Exponential decay");
-	d_formula = "A1*exp(-x/t1)+A2*exp(-x/t2)+A3*exp(-x/t3)+y0";
-	d_param_explain << tr("first amplitude") << tr("first lifetime") << tr("second amplitude") << tr("second lifetime") << tr("third amplitude") << tr("third lifetime") << tr("offset");
+void ThreeExpFit::init() {
+  setObjectName(tr("ExpDecay3"));
+  d_f = expd3_f;
+  d_df = expd3_df;
+  d_fdf = expd3_fdf;
+  d_fsimplex = expd3_d;
+  d_p = 7;
+  initWorkspace(d_p);
+  d_param_names << "A1"
+                << "t1"
+                << "A2"
+                << "t2"
+                << "A3"
+                << "t3"
+                << "y0";
+  d_explanation = tr("Exponential decay");
+  d_formula = "A1*exp(-x/t1)+A2*exp(-x/t2)+A3*exp(-x/t3)+y0";
+  d_param_explain << tr("first amplitude") << tr("first lifetime")
+                  << tr("second amplitude") << tr("second lifetime")
+                  << tr("third amplitude") << tr("third lifetime")
+                  << tr("offset");
 }
 
-void ThreeExpFit::customizeFitResults()
-{
-	d_results[1]=1.0/d_results[1];
-	d_results[3]=1.0/d_results[3];
-	d_results[5]=1.0/d_results[5];
+void ThreeExpFit::customizeFitResults() {
+  d_results[1] = 1.0 / d_results[1];
+  d_results[3] = 1.0 / d_results[3];
+  d_results[5] = 1.0 / d_results[5];
 }
 
-void ThreeExpFit::calculateFitCurveData(double *X, double *Y)
-{
-	double a1 = d_results[0];
-	double l1 = -d_results[1];
-	double a2 = d_results[2];
-	double l2 = -d_results[3];
-	double a3 = d_results[4];
-	double l3 = -d_results[5];
-	double y0 = d_results[6];
-	
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0+i*step;
-			X[i] = x;
-			Y[i] = a1*exp(x*l1) + a2*exp(x*l2) + a3*exp(x*l3) + y0;
-		}
-	} else {
-		for (int i=0; i<d_points; i++){
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i] = a1*exp(x*l1) + a2*exp(x*l2) + a3*exp(x*l3) + y0;
-		}
-	}
+void ThreeExpFit::calculateFitCurveData(double *X, double *Y) {
+  double a1 = d_results[0];
+  double l1 = -d_results[1];
+  double a2 = d_results[2];
+  double l2 = -d_results[3];
+  double a3 = d_results[4];
+  double l3 = -d_results[5];
+  double y0 = d_results[6];
+
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = a1 * exp(x * l1) + a2 * exp(x * l2) + a3 * exp(x * l3) + y0;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = a1 * exp(x * l1) + a2 * exp(x * l2) + a3 * exp(x * l3) + y0;
+    }
+  }
 }
diff --git a/MantidPlot/src/ExponentialFit.h b/MantidPlot/src/ExponentialFit.h
index 1a521e139f5030391e1a646403e8122bf9d44c3a..d889b723e50a77f6cfb61182de098f7af3314c86 100644
--- a/MantidPlot/src/ExponentialFit.h
+++ b/MantidPlot/src/ExponentialFit.h
@@ -2,7 +2,8 @@
     File                 : fitclasses.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Exponential fit classes
 
@@ -31,68 +32,71 @@
 
 #include "Fit.h"
 
-class ExponentialFit : public Fit
-{
-	Q_OBJECT
-
-	public:
-		ExponentialFit(ApplicationWindow *parent, Graph *g,  bool expGrowth = false);
-		ExponentialFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, bool expGrowth = false);
-		ExponentialFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle,
-				double start, double end, bool expGrowth = false);
-		ExponentialFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1, bool expGrowth = false);
-
-                double eval(double *par, double x) override {
-                  return par[0] * exp(-par[1] * x) + par[2];
-                };
-
-        private:
-		void init();
-                void customizeFitResults() override;
-                void calculateFitCurveData(double *X, double *Y) override;
-
-                bool is_exp_growth;
+class ExponentialFit : public Fit {
+  Q_OBJECT
+
+public:
+  ExponentialFit(ApplicationWindow *parent, Graph *g, bool expGrowth = false);
+  ExponentialFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+                 bool expGrowth = false);
+  ExponentialFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+                 double start, double end, bool expGrowth = false);
+  ExponentialFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                 const QString &yCol, int startRow = 1, int endRow = -1,
+                 bool expGrowth = false);
+
+  double eval(double *par, double x) override {
+    return par[0] * exp(-par[1] * x) + par[2];
+  };
+
+private:
+  void init();
+  void customizeFitResults() override;
+  void calculateFitCurveData(double *X, double *Y) override;
+
+  bool is_exp_growth;
 };
 
-class TwoExpFit : public Fit
-{
-	Q_OBJECT
-
-	public:
-		TwoExpFit(ApplicationWindow *parent, Graph *g);
-		TwoExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		TwoExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		TwoExpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
-
-                double eval(double *par, double x) override {
-                  return par[0] * exp(-par[1] * x) + par[2] * exp(-par[3] * x) +
-                         par[4];
-                };
-
-        private:
-		void init();
-                void customizeFitResults() override;
-                void calculateFitCurveData(double *X, double *Y) override;
+class TwoExpFit : public Fit {
+  Q_OBJECT
+
+public:
+  TwoExpFit(ApplicationWindow *parent, Graph *g);
+  TwoExpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  TwoExpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+            double start, double end);
+  TwoExpFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+            const QString &yCol, int startRow = 1, int endRow = -1);
+
+  double eval(double *par, double x) override {
+    return par[0] * exp(-par[1] * x) + par[2] * exp(-par[3] * x) + par[4];
+  };
+
+private:
+  void init();
+  void customizeFitResults() override;
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 
-class ThreeExpFit : public Fit
-{
-	Q_OBJECT
-
-	public:
-		ThreeExpFit(ApplicationWindow *parent, Graph *g);
-		ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		ThreeExpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
-
-                double eval(double *par, double x) override {
-                  return par[0] * exp(-x * par[1]) + par[2] * exp(-x * par[3]) +
-                         par[4] * exp(-x * par[5]) + par[6];
-                };
-
-        private:
-		void init();
-                void customizeFitResults() override;
-                void calculateFitCurveData(double *X, double *Y) override;
+class ThreeExpFit : public Fit {
+  Q_OBJECT
+
+public:
+  ThreeExpFit(ApplicationWindow *parent, Graph *g);
+  ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  ThreeExpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+              double start, double end);
+  ThreeExpFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+              const QString &yCol, int startRow = 1, int endRow = -1);
+
+  double eval(double *par, double x) override {
+    return par[0] * exp(-x * par[1]) + par[2] * exp(-x * par[3]) +
+           par[4] * exp(-x * par[5]) + par[6];
+  };
+
+private:
+  void init();
+  void customizeFitResults() override;
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 #endif
diff --git a/MantidPlot/src/ExportDialog.cpp b/MantidPlot/src/ExportDialog.cpp
index 2baddf77b25be05b7399441bb56396d513328db1..1ac916925418e6f5599db30732ef46dc57f2bda0 100644
--- a/MantidPlot/src/ExportDialog.cpp
+++ b/MantidPlot/src/ExportDialog.cpp
@@ -2,7 +2,8 @@
     File                 : ExportDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Export ASCII dialog
 
@@ -36,32 +37,35 @@
 #include <QCheckBox>
 #include <QComboBox>
 
-ExportDialog::ExportDialog(const QString& tableName, QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
-	setWindowTitle( tr( "MantidPlot - Export ASCII" ) );
-	setSizeGripEnabled( true );
+ExportDialog::ExportDialog(const QString &tableName, QWidget *parent,
+                           Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setWindowTitle(tr("MantidPlot - Export ASCII"));
+  setSizeGripEnabled(true);
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent);
   if (!app) {
-    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of FFTDialog is not ApplicationWindow as expected.");
   }
 
-	QGridLayout *gl1 = new QGridLayout();
+  QGridLayout *gl1 = new QGridLayout();
   gl1->addWidget(new QLabel(tr("Export From")), 0, 0);
-	boxTable = new QComboBox();
-	QStringList tables = app->tableNames() + app->matrixNames() + app->mantidmatrixNames();
-	boxTable->addItems(tables);
-	boxTable->setCurrentIndex(0);
-
-  boxTable->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  boxTable = new QComboBox();
+  QStringList tables =
+      app->tableNames() + app->matrixNames() + app->mantidmatrixNames();
+  boxTable->addItems(tables);
+  boxTable->setCurrentIndex(0);
+
+  boxTable->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
   gl1->addWidget(boxTable, 0, 1);
 
-  boxAllTables = new QCheckBox(tr( "&All" ));
+  boxAllTables = new QCheckBox(tr("&All"));
   boxAllTables->setChecked(false);
   gl1->addWidget(boxAllTables, 0, 2);
 
-  sepText = new QLabel( tr( "Separator" ) );
+  sepText = new QLabel(tr("Separator"));
   gl1->addWidget(sepText, 1, 0);
 
   boxSeparator = new QComboBox();
@@ -73,159 +77,168 @@ ExportDialog::ExportDialog(const QString& tableName, QWidget* parent, Qt::WFlags
   boxSeparator->addItem("," + tr("SPACE"));
   boxSeparator->addItem(";");
   boxSeparator->addItem(",");
-  boxSeparator->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  boxSeparator->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
   boxSeparator->setEditable(true);
 
   gl1->addWidget(boxSeparator, 1, 1);
   setColumnSeparator(app->d_export_col_separator);
 
-	QString help = tr("The column separator can be customized. The following special codes can be used:\n\\t for a TAB character \n\\s for a SPACE");
-	help += "\n"+tr("The separator must not contain the following characters: 0-9eE.+-");
+  QString help =
+      tr("The column separator can be customized. The following special codes "
+         "can be used:\n\\t for a TAB character \n\\s for a SPACE");
+  help +=
+      "\n" +
+      tr("The separator must not contain the following characters: 0-9eE.+-");
 
-	boxSeparator->setWhatsThis(help);
+  boxSeparator->setWhatsThis(help);
   sepText->setWhatsThis(help);
   boxSeparator->setToolTip(help);
   sepText->setToolTip(help);
 
-  boxNames = new QCheckBox(tr( "Include Column &Names" ));
-  boxNames->setChecked( app->d_export_col_names );
+  boxNames = new QCheckBox(tr("Include Column &Names"));
+  boxNames->setChecked(app->d_export_col_names);
 
-  boxComments = new QCheckBox(tr( "Include Column Co&mments" ));
-  boxComments->setChecked( app->d_export_col_comment );
+  boxComments = new QCheckBox(tr("Include Column Co&mments"));
+  boxComments->setChecked(app->d_export_col_comment);
 
-  boxSelection = new QCheckBox(tr( "Export &Selection" ));
-  boxSelection->setChecked( app->d_export_table_selection );
+  boxSelection = new QCheckBox(tr("Export &Selection"));
+  boxSelection->setChecked(app->d_export_table_selection);
 
   QVBoxLayout *vl1 = new QVBoxLayout();
-  vl1->addLayout( gl1 );
-  vl1->addWidget( boxNames );
-  vl1->addWidget( boxComments );
-  vl1->addWidget( boxSelection );
+  vl1->addLayout(gl1);
+  vl1->addWidget(boxNames);
+  vl1->addWidget(boxComments);
+  vl1->addWidget(boxSelection);
 
   QHBoxLayout *hbox3 = new QHBoxLayout();
-  buttonOk = new QPushButton(tr( "&OK" ));
-  buttonOk->setDefault( true );
-  hbox3->addWidget( buttonOk );
-  buttonCancel = new QPushButton(tr( "&Cancel" ));
-  hbox3->addWidget( buttonCancel );
-  buttonHelp = new QPushButton(tr( "&Help" ));
-  hbox3->addWidget( buttonHelp );
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setDefault(true);
+  hbox3->addWidget(buttonOk);
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  hbox3->addWidget(buttonCancel);
+  buttonHelp = new QPushButton(tr("&Help"));
+  hbox3->addWidget(buttonHelp);
   hbox3->addStretch();
 
-  QVBoxLayout *vl = new QVBoxLayout( this );
+  QVBoxLayout *vl = new QVBoxLayout(this);
   vl->addLayout(vl1);
   vl->addStretch();
   vl->addLayout(hbox3);
 
   // signals and slots connections
-  connect( boxTable, SIGNAL(activated(const QString &)), this, SLOT(updateOptions(const QString &)));
-  connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-  connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( close() ) );
-  connect( buttonHelp, SIGNAL( clicked() ), this, SLOT( help() ) );
-  connect( boxAllTables, SIGNAL( toggled(bool) ), this, SLOT( enableTableName(bool) ) );
-
-  if (tables.contains(tableName)){
+  connect(boxTable, SIGNAL(activated(const QString &)), this,
+          SLOT(updateOptions(const QString &)));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
+  connect(buttonHelp, SIGNAL(clicked()), this, SLOT(help()));
+  connect(boxAllTables, SIGNAL(toggled(bool)), this,
+          SLOT(enableTableName(bool)));
+
+  if (tables.contains(tableName)) {
     boxTable->setCurrentIndex(boxTable->findText(tableName));
     updateOptions(tableName);
   }
 }
 
-void ExportDialog::help()
-{
-	QString s = tr("The column separator can be customized. The following special codes can be used:\n\\t for a TAB character \n\\s for a SPACE");
-	s += "\n"+tr("The separator must not contain the following characters: 0-9eE.+-");
-	QMessageBox::about(0, tr("MantidPlot - Help"),s);
+void ExportDialog::help() {
+  QString s =
+      tr("The column separator can be customized. The following special codes "
+         "can be used:\n\\t for a TAB character \n\\s for a SPACE");
+  s += "\n" +
+       tr("The separator must not contain the following characters: 0-9eE.+-");
+  QMessageBox::about(0, tr("MantidPlot - Help"), s);
 }
 
-void ExportDialog::enableTableName(bool ok)
-{
-	boxTable->setEnabled(!ok);
-}
+void ExportDialog::enableTableName(bool ok) { boxTable->setEnabled(!ok); }
 
-void ExportDialog::accept()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-	if (!app)
-		return;
-
-	QString sep = boxSeparator->currentText();
-	sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
-	sep.replace(tr("SPACE"), " ");
-	sep.replace("\\s", " ");
-	sep.replace("\\t", "\t");
-
-	if (sep.contains(QRegExp("[0-9.eE+-]"))){
-		QMessageBox::warning(0, tr("MantidPlot - Import options error"),
-				tr("The separator must not contain the following characters: 0-9eE.+-"));
-		return;
-	}
-
-	hide();
-	if (boxAllTables->isChecked())
-		app->exportAllTables(sep, boxNames->isChecked(), boxComments->isChecked(), boxSelection->isChecked());
-	else
-		app->exportASCII(boxTable->currentText(), sep, boxNames->isChecked(), boxComments->isChecked(), boxSelection->isChecked());
-	close();
-}
+void ExportDialog::accept() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  if (!app)
+    return;
 
-void ExportDialog::setColumnSeparator(const QString& sep)
-{
-	if (sep=="\t")
-		boxSeparator->setCurrentIndex(0);
-	else if (sep==" ")
-		boxSeparator->setCurrentIndex(1);
-	else if (sep==";\t")
-		boxSeparator->setCurrentIndex(2);
-	else if (sep==",\t")
-		boxSeparator->setCurrentIndex(3);
-	else if (sep=="; ")
-		boxSeparator->setCurrentIndex(4);
-	else if (sep==", ")
-		boxSeparator->setCurrentIndex(5);
-	else if (sep==";")
-		boxSeparator->setCurrentIndex(6);
-	else if (sep==",")
-		boxSeparator->setCurrentIndex(7);
-	else {
-		QString separator = sep;
-		boxSeparator->setEditText(separator.replace(" ","\\s").replace("\t","\\t"));
-	}
-}
+  QString sep = boxSeparator->currentText();
+  sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
+  sep.replace(tr("SPACE"), " ");
+  sep.replace("\\s", " ");
+  sep.replace("\\t", "\t");
 
-void ExportDialog::closeEvent(QCloseEvent* e)
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (app){
-		app->d_export_col_names = boxNames->isChecked();
-		app->d_export_table_selection = boxSelection->isChecked();
-		app->d_export_col_comment = boxComments->isChecked();
-
-		QString sep = boxSeparator->currentText();
-		sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
-		sep.replace(tr("SPACE"), " ");
-		sep.replace("\\s", " ");
-		sep.replace("\\t", "\t");
-		app->d_export_col_separator = sep;
-	}
-
-	e->accept();
+  if (sep.contains(QRegExp("[0-9.eE+-]"))) {
+    QMessageBox::warning(0, tr("MantidPlot - Import options error"),
+                         tr("The separator must not contain the following "
+                            "characters: 0-9eE.+-"));
+    return;
+  }
+
+  hide();
+  if (boxAllTables->isChecked())
+    app->exportAllTables(sep, boxNames->isChecked(), boxComments->isChecked(),
+                         boxSelection->isChecked());
+  else
+    app->exportASCII(boxTable->currentText(), sep, boxNames->isChecked(),
+                     boxComments->isChecked(), boxSelection->isChecked());
+  close();
 }
 
-void ExportDialog::updateOptions(const QString & name)
-{
-		ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (!app)
-        return;
+void ExportDialog::setColumnSeparator(const QString &sep) {
+  if (sep == "\t")
+    boxSeparator->setCurrentIndex(0);
+  else if (sep == " ")
+    boxSeparator->setCurrentIndex(1);
+  else if (sep == ";\t")
+    boxSeparator->setCurrentIndex(2);
+  else if (sep == ",\t")
+    boxSeparator->setCurrentIndex(3);
+  else if (sep == "; ")
+    boxSeparator->setCurrentIndex(4);
+  else if (sep == ", ")
+    boxSeparator->setCurrentIndex(5);
+  else if (sep == ";")
+    boxSeparator->setCurrentIndex(6);
+  else if (sep == ",")
+    boxSeparator->setCurrentIndex(7);
+  else {
+    QString separator = sep;
+    boxSeparator->setEditText(
+        separator.replace(" ", "\\s").replace("\t", "\\t"));
+  }
+}
 
-    MdiSubWindow* w = app->window(name);
-    if (!w)
-		return;
+void ExportDialog::closeEvent(QCloseEvent *e) {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (app) {
+    app->d_export_col_names = boxNames->isChecked();
+    app->d_export_table_selection = boxSelection->isChecked();
+    app->d_export_col_comment = boxComments->isChecked();
+
+    QString sep = boxSeparator->currentText();
+    sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
+    sep.replace(tr("SPACE"), " ");
+    sep.replace("\\s", " ");
+    sep.replace("\\t", "\t");
+    app->d_export_col_separator = sep;
+  }
 
-    boxComments->setEnabled(w->inherits("Table"));
-    boxNames->setEnabled(w->inherits("Table"));
-	boxSelection->setEnabled(qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
-	boxSeparator->setEnabled(qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
-	boxAllTables->setEnabled(qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
-	sepText->setEnabled(qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
+  e->accept();
+}
 
+void ExportDialog::updateOptions(const QString &name) {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
+
+  MdiSubWindow *w = app->window(name);
+  if (!w)
+    return;
+
+  boxComments->setEnabled(w->inherits("Table"));
+  boxNames->setEnabled(w->inherits("Table"));
+  boxSelection->setEnabled(
+      qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
+  boxSeparator->setEnabled(
+      qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
+  boxAllTables->setEnabled(
+      qstrcmp("MantidMatrix", w->metaObject()->className()) != 0);
+  sepText->setEnabled(qstrcmp("MantidMatrix", w->metaObject()->className()) !=
+                      0);
 }
diff --git a/MantidPlot/src/ExportDialog.h b/MantidPlot/src/ExportDialog.h
index 85d71d18c47ef81a3c589b9e3820cefd948cc6c6..bc1066bdd480f046ce48cdeddfd74334b8256f9c 100644
--- a/MantidPlot/src/ExportDialog.h
+++ b/MantidPlot/src/ExportDialog.h
@@ -2,7 +2,8 @@
     File                 : ExportDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Export ASCII dialog
 
@@ -36,53 +37,54 @@ class QComboBox;
 class QLabel;
 
 //! Export ASCII dialog
-class ExportDialog : public QDialog
-{
+class ExportDialog : public QDialog {
   Q_OBJECT
 
 public:
-	//! Constructor
-	/**
-	 * @param tableName :: active table name
-	 * @param parent :: parent widget
-	 * @param fl :: window flags
-	 */
-  ExportDialog(const QString& tableName, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  //! Constructor
+  /**
+   * @param tableName :: active table name
+   * @param parent :: parent widget
+   * @param fl :: window flags
+   */
+  ExportDialog(const QString &tableName, QWidget *parent = 0,
+               Qt::WFlags fl = 0);
 
 private:
   void closeEvent(QCloseEvent *) override;
 
-  QPushButton* buttonOk;
-  QPushButton* buttonCancel;
-  QPushButton* buttonHelp;
-  QCheckBox* boxNames;
-  QCheckBox* boxComments;
-  QCheckBox* boxSelection;
-  QCheckBox* boxAllTables;
-  QComboBox* boxSeparator;
-  QComboBox* boxTable;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonHelp;
+  QCheckBox *boxNames;
+  QCheckBox *boxComments;
+  QCheckBox *boxSelection;
+  QCheckBox *boxAllTables;
+  QComboBox *boxSeparator;
+  QComboBox *boxTable;
   QLabel *sepText;
 
 public slots:
-	//! Set the column delimiter
-	void setColumnSeparator(const QString& sep);
+  //! Set the column delimiter
+  void setColumnSeparator(const QString &sep);
 
 private slots:
-	//! Enable/disable the tables combox box
-	/**
-	 * The tables combo box is disabled when
-	 * the checkbox "all" is selected.
-	 */
-	void enableTableName(bool ok);
+  //! Enable/disable the tables combox box
+  /**
+   * The tables combo box is disabled when
+   * the checkbox "all" is selected.
+   */
+  void enableTableName(bool ok);
 
-	//! Enable/disable export options depending if the selected window is a Table or a Matrix.
-	void updateOptions(const QString & name);
+  //! Enable/disable export options depending if the selected window is a Table
+  // or a Matrix.
+  void updateOptions(const QString &name);
 
 protected slots:
-	//! Accept changes
+  //! Accept changes
   void accept() override;
-        //! Display help
-	void help();
+  //! Display help
+  void help();
 };
 
 #endif // ExportDialog_H
diff --git a/MantidPlot/src/FFT.cpp b/MantidPlot/src/FFT.cpp
index 369889b2b002078ccdda17e49de0496884c4a5f8..7cc91cd5eb2030f246674a6cc21018a1f8398f7c 100644
--- a/MantidPlot/src/FFT.cpp
+++ b/MantidPlot/src/FFT.cpp
@@ -37,318 +37,333 @@
 #include <gsl/gsl_fft_complex.h>
 #include <gsl/gsl_fft_halfcomplex.h>
 
-FFT::FFT(ApplicationWindow *parent, Table *t, const QString& realColName, const QString& imagColName, int from, int to)
-: Filter(parent, t)
-{
-	init();
-    setDataFromTable(t, realColName, imagColName, from, to);
+FFT::FFT(ApplicationWindow *parent, Table *t, const QString &realColName,
+         const QString &imagColName, int from, int to)
+    : Filter(parent, t) {
+  init();
+  setDataFromTable(t, realColName, imagColName, from, to);
 }
 
-FFT::FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Filter(parent, g)
-{
-	init();
-    setDataFromCurve(curveTitle);
+FFT::FFT(ApplicationWindow *parent, Graph *g, const QString &curveTitle)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-FFT::FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Filter(parent, g)
-{
-	init();
-    setDataFromCurve(curveTitle, start, end);
+FFT::FFT(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+         double start, double end)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-void FFT::init ()
-{
-    setObjectName(tr("FFT"));
-    d_inverse = false;
-    d_normalize = true;
-    d_shift_order = true;
-    d_real_col = -1;
-    d_imag_col = -1;
-	d_sampling = 1.0;
-	d_output_graph = 0;
+void FFT::init() {
+  setObjectName(tr("FFT"));
+  d_inverse = false;
+  d_normalize = true;
+  d_shift_order = true;
+  d_real_col = -1;
+  d_imag_col = -1;
+  d_sampling = 1.0;
+  d_output_graph = 0;
 }
 
-QString FFT::fftCurve()
-{
+QString FFT::fftCurve() {
   int i, i2;
-	int n2 = d_n/2;
-	std::vector<double> amp(d_n);
-	std::vector<double> result(2*d_n);
-
-	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;
-        return "";
-	}
-
-	double df = 1.0/(double)(d_n*d_sampling);//frequency sampling
-	double aMax = 0.0;//max amplitude
-	QString text;
-	if(!d_inverse){
-        d_explanation = tr("Forward") + " " + tr("FFT") + " " + tr("of") + " " + d_curve->title().text();
-		text = tr("Frequency");
-
-		gsl_fft_real_workspace *work=gsl_fft_real_workspace_alloc(d_n);
-		gsl_fft_real_wavetable *real=gsl_fft_real_wavetable_alloc(d_n);
-
-		if(!work || !real){
-			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                        tr("Could not allocate memory, operation aborted!"));
-            d_init_err = true;
-			return "";
-		}
-
-		gsl_fft_real_transform(d_y, 1, d_n, real,work);
-    gsl_fft_halfcomplex_unpack (d_y, result.data(), 1, d_n);
-
-		gsl_fft_real_wavetable_free(real);
-		gsl_fft_real_workspace_free(work);
-	} else {
-        d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " + d_curve->title().text();
-		text = tr("Time");
-
-    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);
-
-		if(!workspace || !wavetable){
-			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                        tr("Could not allocate memory, operation aborted!"));
-            d_init_err = true;
-			return "";
-		}
-
-		gsl_fft_complex_inverse (result.data(), 1, d_n, wavetable, workspace);
-		gsl_fft_complex_wavetable_free (wavetable);
-		gsl_fft_complex_workspace_free (workspace);
-	}
-
-	if (d_shift_order){
-		for(i=0; i<d_n; i++){
-			d_x[i] = (i-n2)*df;
-			int j = i + d_n;
-			double aux = result[i];
-			result[i] = result[j];
-			result[j] = aux;
-		}
-	} else {
-		for(i=0; i<d_n; i++)
-			d_x[i] = i*df;
-	}
-
-	for(i=0;i<d_n;i++) {
-		i2 = 2*i;
-		double real_part = result[i2];
-		double im_part = result[i2+1];
-		double a = sqrt(real_part*real_part + im_part*im_part);
-		amp[i]= a;
-		if (a > aMax)
-			aMax = a;
-	}
+  int n2 = d_n / 2;
+  std::vector<double> amp(d_n);
+  std::vector<double> result(2 * d_n);
+
+  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;
+    return "";
+  }
+
+  double df = 1.0 / (double)(d_n * d_sampling); // frequency sampling
+  double aMax = 0.0;                            // max amplitude
+  QString text;
+  if (!d_inverse) {
+    d_explanation = tr("Forward") + " " + tr("FFT") + " " + tr("of") + " " +
+                    d_curve->title().text();
+    text = tr("Frequency");
+
+    gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n);
+    gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n);
+
+    if (!work || !real) {
+      QMessageBox::critical(
+          dynamic_cast<ApplicationWindow *>(parent()),
+          tr("MantidPlot") + " - " + tr("Error"),
+          tr("Could not allocate memory, operation aborted!"));
+      d_init_err = true;
+      return "";
+    }
+
+    gsl_fft_real_transform(d_y, 1, d_n, real, work);
+    gsl_fft_halfcomplex_unpack(d_y, result.data(), 1, d_n);
+
+    gsl_fft_real_wavetable_free(real);
+    gsl_fft_real_workspace_free(work);
+  } else {
+    d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " +
+                    d_curve->title().text();
+    text = tr("Time");
+
+    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);
+
+    if (!workspace || !wavetable) {
+      QMessageBox::critical(
+          dynamic_cast<ApplicationWindow *>(parent()),
+          tr("MantidPlot") + " - " + tr("Error"),
+          tr("Could not allocate memory, operation aborted!"));
+      d_init_err = true;
+      return "";
+    }
+
+    gsl_fft_complex_inverse(result.data(), 1, d_n, wavetable, workspace);
+    gsl_fft_complex_wavetable_free(wavetable);
+    gsl_fft_complex_workspace_free(workspace);
+  }
+
+  if (d_shift_order) {
+    for (i = 0; i < d_n; i++) {
+      d_x[i] = (i - n2) * df;
+      int j = i + d_n;
+      double aux = result[i];
+      result[i] = result[j];
+      result[j] = aux;
+    }
+  } else {
+    for (i = 0; i < d_n; i++)
+      d_x[i] = i * df;
+  }
+
+  for (i = 0; i < d_n; i++) {
+    i2 = 2 * i;
+    double real_part = result[i2];
+    double im_part = result[i2 + 1];
+    double a = sqrt(real_part * real_part + im_part * im_part);
+    amp[i] = a;
+    if (a > aMax)
+      aMax = a;
+  }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
   if (!app) {
-    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of FFTDialog is not ApplicationWindow as expected.");
   }
 
-	QLocale locale = app->locale();
-	int prec = app->d_decimal_digits;
-
-	text += "\t"+tr("Real")+"\t"+tr("Imaginary")+"\t"+ tr("Amplitude")+"\t"+tr("Angle")+"\n";
-	for (i=0; i<d_n; i++){
-		i2 = 2*i;
-		text += locale.toString(d_x[i], 'g', prec)+"\t";
-		text += locale.toString(result[i2], 'g', prec)+"\t";
-		text += locale.toString(result[i2+1], 'g', prec)+"\t";
-		if (d_normalize)
-			text += locale.toString(amp[i]/aMax, 'g', prec)+"\t";
-		else
-			text += locale.toString(amp[i], 'g', prec)+"\t";
-		text += locale.toString(atan(result[i2+1]/result[i2]), 'g', prec)+"\n";
-	}
+  QLocale locale = app->locale();
+  int prec = app->d_decimal_digits;
+
+  text += "\t" + tr("Real") + "\t" + tr("Imaginary") + "\t" + tr("Amplitude") +
+          "\t" + tr("Angle") + "\n";
+  for (i = 0; i < d_n; i++) {
+    i2 = 2 * i;
+    text += locale.toString(d_x[i], 'g', prec) + "\t";
+    text += locale.toString(result[i2], 'g', prec) + "\t";
+    text += locale.toString(result[i2 + 1], 'g', prec) + "\t";
+    if (d_normalize)
+      text += locale.toString(amp[i] / aMax, 'g', prec) + "\t";
+    else
+      text += locale.toString(amp[i], 'g', prec) + "\t";
+    text +=
+        locale.toString(atan(result[i2 + 1] / result[i2]), 'g', prec) + "\n";
+  }
   return text;
 }
 
-QString FFT::fftTable()
-{
-    int i;
-	double *amp = new double[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);
-
-	if(!amp || !wavetable || !workspace)
-	{
-	  QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("Could not allocate memory, operation aborted!"));
-	  delete[] amp;
-	  if (wavetable) gsl_fft_complex_wavetable_free (wavetable);
-	  if (workspace) gsl_fft_complex_workspace_free (workspace);
-	  d_init_err = true;
-	  return "";
-	}
-
-	double df = 1.0/(double)(d_n*d_sampling);//frequency sampling
-	double aMax = 0.0;//max amplitude
-	QString text;
-	if(!d_inverse) {
-		d_explanation = tr("Forward") + " " + tr("FFT") + " " + tr("of") + " " + d_table->colName(d_real_col);
-		text = tr("Frequency");
-		gsl_fft_complex_forward (d_y, 1, d_n, wavetable, workspace);
-	} else {
-		d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " + d_table->colName(d_real_col);
-		text = tr("Time");
-		gsl_fft_complex_inverse (d_y, 1, d_n, wavetable, workspace);
-	}
-
-	gsl_fft_complex_wavetable_free (wavetable);
-	gsl_fft_complex_workspace_free (workspace);
-
-	if (d_shift_order) {
-		int n2 = d_n/2;
-		for(i=0; i<d_n; i++) {
-			d_x[i] = (i-n2)*df;
-			int j = i + d_n;
-			double aux = d_y[i];
-			d_y[i] = d_y[j];
-			d_y[j] = aux;
-		}
-	} else {
-		for(i=0; i<d_n; i++)
-			d_x[i] = i*df;
-	}
-
-	for(i=0; i<d_n; i++) {
-		int i2 = 2*i;
-		double a = sqrt(d_y[i2]*d_y[i2] + d_y[i2+1]*d_y[i2+1]);
-		amp[i]= a;
-		if (a > aMax)
-			aMax = a;
-	}
-
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    if (!app) {
-      throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+QString FFT::fftTable() {
+  int i;
+  double *amp = new double[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);
+
+  if (!amp || !wavetable || !workspace) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Could not allocate memory, operation aborted!"));
+    delete[] amp;
+    if (wavetable)
+      gsl_fft_complex_wavetable_free(wavetable);
+    if (workspace)
+      gsl_fft_complex_workspace_free(workspace);
+    d_init_err = true;
+    return "";
+  }
+
+  double df = 1.0 / (double)(d_n * d_sampling); // frequency sampling
+  double aMax = 0.0;                            // max amplitude
+  QString text;
+  if (!d_inverse) {
+    d_explanation = tr("Forward") + " " + tr("FFT") + " " + tr("of") + " " +
+                    d_table->colName(d_real_col);
+    text = tr("Frequency");
+    gsl_fft_complex_forward(d_y, 1, d_n, wavetable, workspace);
+  } else {
+    d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " +
+                    d_table->colName(d_real_col);
+    text = tr("Time");
+    gsl_fft_complex_inverse(d_y, 1, d_n, wavetable, workspace);
+  }
+
+  gsl_fft_complex_wavetable_free(wavetable);
+  gsl_fft_complex_workspace_free(workspace);
+
+  if (d_shift_order) {
+    int n2 = d_n / 2;
+    for (i = 0; i < d_n; i++) {
+      d_x[i] = (i - n2) * df;
+      int j = i + d_n;
+      double aux = d_y[i];
+      d_y[i] = d_y[j];
+      d_y[j] = aux;
     }
-    QLocale locale = app->locale();
-	int prec = app->d_decimal_digits;
-
-	text += "\t"+tr("Real")+"\t"+tr("Imaginary")+"\t"+tr("Amplitude")+"\t"+tr("Angle")+"\n";
-	for (i=0; i<d_n; i++) {
-		int i2 = 2*i;
-		text += locale.toString(d_x[i], 'g', prec)+"\t";
-		text += locale.toString(d_y[i2], 'g', prec)+"\t";
-		text += locale.toString(d_y[i2+1], 'g', prec)+"\t";
-		if (d_normalize)
-			text += locale.toString(amp[i]/aMax, 'g', prec)+"\t";
-		else
-			text += locale.toString(amp[i], 'g', prec)+"\t";
-		text += locale.toString(atan(d_y[i2+1]/d_y[i2]), 'g', prec)+"\n";
-	}
-	delete[] amp;
-    return text;
+  } else {
+    for (i = 0; i < d_n; i++)
+      d_x[i] = i * df;
+  }
+
+  for (i = 0; i < d_n; i++) {
+    int i2 = 2 * i;
+    double a = sqrt(d_y[i2] * d_y[i2] + d_y[i2 + 1] * d_y[i2 + 1]);
+    amp[i] = a;
+    if (a > aMax)
+      aMax = a;
+  }
+
+  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;
+
+  text += "\t" + tr("Real") + "\t" + tr("Imaginary") + "\t" + tr("Amplitude") +
+          "\t" + tr("Angle") + "\n";
+  for (i = 0; i < d_n; i++) {
+    int i2 = 2 * i;
+    text += locale.toString(d_x[i], 'g', prec) + "\t";
+    text += locale.toString(d_y[i2], 'g', prec) + "\t";
+    text += locale.toString(d_y[i2 + 1], 'g', prec) + "\t";
+    if (d_normalize)
+      text += locale.toString(amp[i] / aMax, 'g', prec) + "\t";
+    else
+      text += locale.toString(amp[i], 'g', prec) + "\t";
+    text += locale.toString(atan(d_y[i2 + 1] / d_y[i2]), 'g', prec) + "\n";
+  }
+  delete[] amp;
+  return text;
 }
 
-void FFT::output()
-{
-    QString text;
-    if (d_graph && d_curve)
-        text = fftCurve();
-    else if (d_table)
-        text = fftTable();
+void FFT::output() {
+  QString text;
+  if (d_graph && d_curve)
+    text = fftCurve();
+  else if (d_table)
+    text = fftTable();
 
-    if (!text.isEmpty())
-        output(text);
+  if (!text.isEmpty())
+    output(text);
 }
 
-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.");
+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);
+
+  if (d_graphics_display) {
+    MultiLayer *ml = 0;
+    if (!d_output_graph) {
+      ml = createOutputGraph();
+      d_output_graph = ml->activeGraph();
     }
-    QString tableName = app->generateUniqueName(QString(objectName()));
-    d_result_table = app->newHiddenTable(tableName, d_explanation, d_n, 5, text);
-
-	if (d_graphics_display){
-	    MultiLayer *ml = 0;
-	    if (!d_output_graph){
-            ml = createOutputGraph();
-            d_output_graph = ml->activeGraph();
-	    }
-
-		d_output_graph->setTitle(QString());
-		if (!d_inverse)
-			d_output_graph->setXAxisTitle(tr("Frequency") + " (" + tr("Hz") + ")");
-		else
-			d_output_graph->setXAxisTitle(tr("Time") + + " (" + tr("s") + ")");
-		d_output_graph->setYAxisTitle(tr("Amplitude"));
-
-        d_output_graph->insertCurve(d_result_table, 0, tableName + "_" + tr("Amplitude"), 0);
-		d_output_graph->setCurvePen(d_output_graph->curves() - 1, QPen(ColorBox::color(d_curveColorIndex), 1));
-        d_output_graph->replot();
-
-        if (ml)
-            ml->showMaximized();
-	}
+
+    d_output_graph->setTitle(QString());
+    if (!d_inverse)
+      d_output_graph->setXAxisTitle(tr("Frequency") + " (" + tr("Hz") + ")");
+    else
+      d_output_graph->setXAxisTitle(tr("Time") + +" (" + tr("s") + ")");
+    d_output_graph->setYAxisTitle(tr("Amplitude"));
+
+    d_output_graph->insertCurve(d_result_table, 0,
+                                tableName + "_" + tr("Amplitude"), 0);
+    d_output_graph->setCurvePen(d_output_graph->curves() - 1,
+                                QPen(ColorBox::color(d_curveColorIndex), 1));
+    d_output_graph->replot();
+
+    if (ml)
+      ml->showMaximized();
+  }
 }
 
-bool FFT::setDataFromTable(Table *t, const QString& realColName, const QString& imagColName, int from, int to)
-{
-	d_init_err = true;
-
-	if (!t)
-		return false;
-
-	d_real_col = d_table->colIndex(realColName);
-	if (d_real_col < 0 || t->columnType(d_real_col) != Table::Numeric)
-		return false;
-
-    if (!imagColName.isEmpty()){
-        d_imag_col = d_table->colIndex(imagColName);
-		if (d_imag_col < 0 || t->columnType(d_imag_col) != Table::Numeric)
-			return false;
-	}
-
-	from--; to--;
-	if (from < 0 || from >= t->numRows())
-		from = 0;
-	if (to < 0 || to >= t->numRows())
-		to = t->numRows() - 1;
-
-    if (t && d_table != t)
-        d_table = t;
-
-    if (d_n > 0) {//delete previousely allocated memory
-		delete[] d_x;
-		delete[] d_y;
-	}
-
-	d_graph = 0;
-	d_curve = 0;
-	d_init_err = false;
-
-    d_n = abs(to - from) + 1;
-    int n2 = 2*d_n;
-    d_y = new double[n2];
-    d_x = new double[d_n];
-
-    if(d_y && d_x) {// zero-pad data array
-		memset( d_y, 0, n2* sizeof( double ) );
-		for(int i=0; i<d_n; i++) {
-			int i2 = 2*i;
-			d_y[i2] = d_table->cell(i, d_real_col);
-			if (d_imag_col >= 0)
-				d_y[i2+1] = d_table->cell(i, d_imag_col);
-		}
-	} else {
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-                        tr("Could not allocate memory, operation aborted!"));
-        d_init_err = true;
-		return false;
-	}
-	return true;
+bool FFT::setDataFromTable(Table *t, const QString &realColName,
+                           const QString &imagColName, int from, int to) {
+  d_init_err = true;
+
+  if (!t)
+    return false;
+
+  d_real_col = d_table->colIndex(realColName);
+  if (d_real_col < 0 || t->columnType(d_real_col) != Table::Numeric)
+    return false;
+
+  if (!imagColName.isEmpty()) {
+    d_imag_col = d_table->colIndex(imagColName);
+    if (d_imag_col < 0 || t->columnType(d_imag_col) != Table::Numeric)
+      return false;
+  }
+
+  from--;
+  to--;
+  if (from < 0 || from >= t->numRows())
+    from = 0;
+  if (to < 0 || to >= t->numRows())
+    to = t->numRows() - 1;
+
+  if (t && d_table != t)
+    d_table = t;
+
+  if (d_n > 0) { // delete previousely allocated memory
+    delete[] d_x;
+    delete[] d_y;
+  }
+
+  d_graph = 0;
+  d_curve = 0;
+  d_init_err = false;
+
+  d_n = abs(to - from) + 1;
+  int n2 = 2 * d_n;
+  d_y = new double[n2];
+  d_x = new double[d_n];
+
+  if (d_y && d_x) { // zero-pad data array
+    memset(d_y, 0, n2 * sizeof(double));
+    for (int i = 0; i < d_n; i++) {
+      int i2 = 2 * i;
+      d_y[i2] = d_table->cell(i, d_real_col);
+      if (d_imag_col >= 0)
+        d_y[i2 + 1] = d_table->cell(i, d_imag_col);
+    }
+  } else {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Could not allocate memory, operation aborted!"));
+    d_init_err = true;
+    return false;
+  }
+  return true;
 }
diff --git a/MantidPlot/src/FFT.h b/MantidPlot/src/FFT.h
index 943d8bd9e538cb45ab0f489c321fe710fcd9d6e7..d1bc587011e9320cf2a80ded8aa65d086fb2eea2 100644
--- a/MantidPlot/src/FFT.h
+++ b/MantidPlot/src/FFT.h
@@ -31,41 +31,43 @@
 
 #include "Filter.h"
 
-class FFT : public Filter
-{
-Q_OBJECT
+class FFT : public Filter {
+  Q_OBJECT
 
 public:
-    FFT(ApplicationWindow *parent, Table *t, const QString& realColName, const QString& imagColName = QString(), int from = 1, int to = -1);
-	FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-    FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
+  FFT(ApplicationWindow *parent, Table *t, const QString &realColName,
+      const QString &imagColName = QString(), int from = 1, int to = -1);
+  FFT(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  FFT(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+      double start, double end);
 
-    void setInverseFFT(bool inverse = true){d_inverse = inverse;};
-    void setSampling(double sampling){d_sampling = sampling;};
-    void normalizeAmplitudes(bool norm = true){d_normalize = norm;};
-    void shiftFrequencies(bool shift = true){d_shift_order = shift;};
+  void setInverseFFT(bool inverse = true) { d_inverse = inverse; };
+  void setSampling(double sampling) { d_sampling = sampling; };
+  void normalizeAmplitudes(bool norm = true) { d_normalize = norm; };
+  void shiftFrequencies(bool shift = true) { d_shift_order = shift; };
 
 private:
-    void init();
-    void output() override;
-    void output(const QString &text);
+  void init();
+  void output() override;
+  void output(const QString &text);
 
-    QString fftCurve();
-    QString fftTable();
+  QString fftCurve();
+  QString fftTable();
 
-    bool setDataFromTable(Table *t, const QString &realColName,
-                          const QString &imagColName = QString(), int from = 0,
-                          int to = -1) override;
+  bool setDataFromTable(Table *t, const QString &realColName,
+                        const QString &imagColName = QString(), int from = 0,
+                        int to = -1) override;
 
-    double d_sampling;
-    //! Flag telling if an inverse FFT must be performed.
-    bool d_inverse;
-    //! Flag telling if the amplitudes in the output spectrum must be normalized.
-    bool d_normalize;
-    //! Flag telling if the output frequencies must be shifted in order to have a zero-centered spectrum.
-    bool d_shift_order;
+  double d_sampling;
+  //! Flag telling if an inverse FFT must be performed.
+  bool d_inverse;
+  //! Flag telling if the amplitudes in the output spectrum must be normalized.
+  bool d_normalize;
+  //! Flag telling if the output frequencies must be shifted in order to have a
+  // zero-centered spectrum.
+  bool d_shift_order;
 
-    int d_real_col, d_imag_col;
+  int d_real_col, d_imag_col;
 };
 
 #endif
diff --git a/MantidPlot/src/FFTDialog.cpp b/MantidPlot/src/FFTDialog.cpp
index dbf5567e3bbe88f8afdbf3def04a1aef8d61c4e8..18e112f0d4ea681c9bb229ed2617b6ffefefe071 100644
--- a/MantidPlot/src/FFTDialog.cpp
+++ b/MantidPlot/src/FFTDialog.cpp
@@ -2,7 +2,8 @@
     File                 : FFTDialog.cpp
     Project              : MantidPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fast Fourier transform options dialog
 
@@ -48,136 +49,136 @@
 #include <QLayout>
 #include <QApplication>
 
-FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags 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"));
-
-    d_matrix = 0;
-    d_table = 0;
-    graph = 0;
-    d_type = type;
-
-    forwardBtn = new QRadioButton(tr("&Forward"));
-    forwardBtn->setChecked( true );
-    backwardBtn = new QRadioButton(tr("&Inverse"));
-
-    QHBoxLayout *hbox1 = new QHBoxLayout();
-    hbox1->addWidget(forwardBtn);
-    hbox1->addWidget(backwardBtn);
-
-    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);
-
-    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);
-    }
+FFTDialog::FFTDialog(int type, QWidget *parent, Qt::WFlags 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"));
+
+  d_matrix = 0;
+  d_table = 0;
+  graph = 0;
+  d_type = type;
+
+  forwardBtn = new QRadioButton(tr("&Forward"));
+  forwardBtn->setChecked(true);
+  backwardBtn = new QRadioButton(tr("&Inverse"));
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->addWidget(forwardBtn);
+  hbox1->addWidget(backwardBtn);
+
+  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);
+
+  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);
+  }
 
-    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);
+  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);
+    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);
+    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);
+  }
 
-    QGroupBox *gb2 = new QGroupBox();
-    gb2->setLayout(gl1);
+  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);
-    }
+  if (d_type != onMatrix) {
+    boxOrder = new QCheckBox(tr("&Shift Results"));
+    boxOrder->setChecked(true);
+  }
 
-    QVBoxLayout *vbox1 = new QVBoxLayout();
-    vbox1->addWidget(gb1);
-    vbox1->addWidget(gb2);
-    vbox1->addWidget(boxNormalize);
-    if (d_type != onMatrix)
-      vbox1->addWidget(boxOrder);
-    vbox1->addStretch();
-
-    buttonOK = new QPushButton(tr("&OK"));
-    buttonOK->setDefault( true );
-    buttonCancel = new QPushButton(tr("&Close"));
-
-    QVBoxLayout *vbox2 = new QVBoxLayout();
-    vbox2->addWidget(buttonOK);
-    vbox2->addWidget(buttonCancel);
-    vbox2->addStretch();
-
-    QHBoxLayout *hbox2 = new QHBoxLayout(this);
-    hbox2->addLayout(vbox1);
-    hbox2->addLayout(vbox2);
-
-    // signals and slots connections
-    connect( buttonOK, SIGNAL( clicked() ), this, SLOT( accept() ) );
-    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+  QVBoxLayout *vbox1 = new QVBoxLayout();
+  vbox1->addWidget(gb1);
+  vbox1->addWidget(gb2);
+  vbox1->addWidget(boxNormalize);
+  if (d_type != onMatrix)
+    vbox1->addWidget(boxOrder);
+  vbox1->addStretch();
+
+  buttonOK = new QPushButton(tr("&OK"));
+  buttonOK->setDefault(true);
+  buttonCancel = new QPushButton(tr("&Close"));
+
+  QVBoxLayout *vbox2 = new QVBoxLayout();
+  vbox2->addWidget(buttonOK);
+  vbox2->addWidget(buttonCancel);
+  vbox2->addStretch();
+
+  QHBoxLayout *hbox2 = new QHBoxLayout(this);
+  hbox2->addLayout(vbox1);
+  hbox2->addLayout(vbox2);
+
+  // signals and slots connections
+  connect(buttonOK, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void FFTDialog::accept()
-{
-    if (d_type == onMatrix){
-        fftMatrix();
-        close();
-        return;
-    }
+void FFTDialog::accept() {
+  if (d_type == onMatrix) {
+    fftMatrix();
+    close();
+    return;
+  }
 
-	double sampling;
-	try
-	{
-		MyParser parser;
-		parser.SetExpr(boxSampling->text().toAscii().constData());
-		sampling=parser.Eval();
-	}
-	catch(mu::ParserError &e)
-	{
-		QMessageBox::critical(this, tr("MantidPlot - Sampling value error"), QString::fromStdString(e.GetMsg()));
-		boxSampling->setFocus();
-		return;
-	}
+  double sampling;
+  try {
+    MyParser parser;
+    parser.SetExpr(boxSampling->text().toAscii().constData());
+    sampling = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(this, tr("MantidPlot - Sampling value error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxSampling->setFocus();
+    return;
+  }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
   if (!app) {
-    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
+    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){
-		if (boxReal->currentText().isEmpty()){
-			QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please choose a column for the real part of the data!"));
-			boxReal->setFocus();
-			return;
-		}
-    fft = new FFT(app, d_table, boxReal->currentText(), boxImaginary->currentText());
-	}
+  if (graph)
+    fft = new FFT(app, graph, boxName->currentText());
+  else if (d_table) {
+    if (boxReal->currentText().isEmpty()) {
+      QMessageBox::critical(
+          this, tr("MantidPlot - Error"),
+          tr("Please choose a column for the real part of the data!"));
+      boxReal->setFocus();
+      return;
+    }
+    fft = new FFT(app, d_table, boxReal->currentText(),
+                  boxImaginary->currentText());
+  }
 
   if (fft) {
     fft->setInverseFFT(backwardBtn->isChecked());
@@ -187,198 +188,202 @@ void FFTDialog::accept()
     fft->run();
     delete fft;
   }
-	close();
+  close();
 }
 
-void FFTDialog::setGraph(Graph *g)
-{
-	graph = g;
-	boxName->insertItems (-1, g->analysableCurvesList());
-	activateCurve(boxName->currentText());
+void FFTDialog::setGraph(Graph *g) {
+  graph = g;
+  boxName->insertItems(-1, g->analysableCurvesList());
+  activateCurve(boxName->currentText());
 }
 
-void FFTDialog::activateCurve(const QString& curveName)
-{
-	if (graph){
-		QwtPlotCurve *c = graph->curve(curveName);
-		if (!c)
-			return;
-
-		boxSampling->setText(QString::number(c->x(1) - c->x(0)));
-	} else if (d_table) {
-	    int col = d_table->colIndex(curveName);
-		double x0 = d_table->text(0, col).toDouble();
-		double x1 = d_table->text(1, col).toDouble();
-		boxSampling->setText(QString::number(x1 - x0));
-	}
+void FFTDialog::activateCurve(const QString &curveName) {
+  if (graph) {
+    QwtPlotCurve *c = graph->curve(curveName);
+    if (!c)
+      return;
+
+    boxSampling->setText(QString::number(c->x(1) - c->x(0)));
+  } else if (d_table) {
+    int col = d_table->colIndex(curveName);
+    double x0 = d_table->text(0, col).toDouble();
+    double x1 = d_table->text(1, col).toDouble();
+    boxSampling->setText(QString::number(x1 - x0));
+  }
 }
 
-void FFTDialog::setTable(Table *t)
-{
-	d_table = t;
-	QStringList l = t->columnsList();
-	boxName->insertItems (-1, l);
-	boxReal->insertItems (-1, l);
-	boxImaginary->insertItems (-1, l);
-
-	int xcol = t->firstXCol();
-	if (xcol >= 0){
-		boxName->setCurrentIndex(xcol);
-
-		double x0 = t->text(0, xcol).toDouble();
-		double x1 = t->text(1, xcol).toDouble();
-		boxSampling->setText(QString::number(x1 - x0));
-	}
-
-	l = t->selectedColumns();
-	int selected = (int)l.size();
-	if (!selected){
-		boxReal->setItemText(boxReal->currentIndex(), QString());
-		boxImaginary->setItemText(boxImaginary->currentIndex(), QString());
-	} else if (selected == 1) {
-		boxReal->setCurrentIndex(t->colIndex(l[0]));
-		boxImaginary->setItemText(boxImaginary->currentIndex(), QString());
-	} else {
-		boxReal->setCurrentIndex(t->colIndex(l[0]));
-		boxImaginary->setCurrentIndex(t->colIndex(l[1]));
-	}
+void FFTDialog::setTable(Table *t) {
+  d_table = t;
+  QStringList l = t->columnsList();
+  boxName->insertItems(-1, l);
+  boxReal->insertItems(-1, l);
+  boxImaginary->insertItems(-1, l);
+
+  int xcol = t->firstXCol();
+  if (xcol >= 0) {
+    boxName->setCurrentIndex(xcol);
+
+    double x0 = t->text(0, xcol).toDouble();
+    double x1 = t->text(1, xcol).toDouble();
+    boxSampling->setText(QString::number(x1 - x0));
+  }
+
+  l = t->selectedColumns();
+  int selected = (int)l.size();
+  if (!selected) {
+    boxReal->setItemText(boxReal->currentIndex(), QString());
+    boxImaginary->setItemText(boxImaginary->currentIndex(), QString());
+  } else if (selected == 1) {
+    boxReal->setCurrentIndex(t->colIndex(l[0]));
+    boxImaginary->setItemText(boxImaginary->currentIndex(), QString());
+  } else {
+    boxReal->setCurrentIndex(t->colIndex(l[0]));
+    boxImaginary->setCurrentIndex(t->colIndex(l[1]));
+  }
 }
 
-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){
-        boxReal->setCurrentIndex(lst.indexOf(m->objectName()));
-        d_matrix = m;
-    }
-    boxImaginary->addItem (" ");
-    boxImaginary->addItems(lst);
+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) {
+    boxReal->setCurrentIndex(lst.indexOf(m->objectName()));
+    d_matrix = m;
+  }
+  boxImaginary->addItem(" ");
+  boxImaginary->addItems(lst);
 }
 
-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;
-
-    bool inverse = backwardBtn->isChecked();
-    int width = mReal->numCols();
-    int height = mReal->numRows();
-
-    bool errors = false;
-    Matrix *mIm = app->matrix(boxImaginary->currentText());
-    if (!mIm)
-        errors = true;
-    else if ((mIm->numCols() != width) || (mIm->numRows() != height))
-    {
-        errors = true;
-        QMessageBox::warning(app, tr("MantidPlot"),
-        tr("The two matrices have different dimensions, the imaginary part will be neglected!"));
-    }
+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;
+
+  bool inverse = backwardBtn->isChecked();
+  int width = mReal->numCols();
+  int height = mReal->numRows();
+
+  bool errors = false;
+  Matrix *mIm = app->matrix(boxImaginary->currentText());
+  if (!mIm)
+    errors = true;
+  else if ((mIm->numCols() != width) || (mIm->numRows() != height)) {
+    errors = true;
+    QMessageBox::warning(app, tr("MantidPlot"),
+                         tr("The two matrices have different dimensions, the "
+                            "imaginary part will be neglected!"));
+  }
+
+  double **x_int_re =
+      Matrix::allocateMatrixData(height, width); /* real coeff matrix */
+  if (!x_int_re)
+    return;
+  double **x_int_im =
+      Matrix::allocateMatrixData(height, width); /* imaginary coeff  matrix*/
+  if (!x_int_im) {
+    Matrix::freeMatrixData(x_int_re, height);
+    return;
+  }
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
-    double **x_int_re = Matrix::allocateMatrixData(height, width); /* real coeff matrix */
-    if (!x_int_re)
-		return;
-    double **x_int_im = Matrix::allocateMatrixData(height, width); /* imaginary coeff  matrix*/
-	if (!x_int_im){
-	    Matrix::freeMatrixData(x_int_re, height);
-		return;
-	}
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    for (int i = 0; i < height; i++){
-        for (int j = 0; j < width; j++){
-            x_int_re[i][j] = mReal->cell(i, j);
-            if (errors)
-                x_int_im[i][j] = 0.0;
-            else
-                x_int_im[i][j] = mIm->cell(i, j);
-        }
+  for (int i = 0; i < height; i++) {
+    for (int j = 0; j < width; j++) {
+      x_int_re[i][j] = mReal->cell(i, j);
+      if (errors)
+        x_int_im[i][j] = 0.0;
+      else
+        x_int_im[i][j] = mIm->cell(i, j);
     }
+  }
 
-    double **x_fin_re = NULL, **x_fin_im = NULL;
-    if (inverse){
-        x_fin_re = Matrix::allocateMatrixData(height, width); // coeff of the initial image
-        x_fin_im = Matrix::allocateMatrixData(height, width); // filled with 0 if everythng OK
-		if (!x_fin_re || !x_fin_im){
-		    Matrix::freeMatrixData(x_int_re, height);
-		    Matrix::freeMatrixData(x_int_im, height);
-			QApplication::restoreOverrideCursor();
-			return;
-		}
-
-        fft2d_inv(x_int_re, x_int_im, x_fin_re, x_fin_im, width, height);
-    } else
-        fft2d(x_int_re, x_int_im, width, height);
-
-    Matrix *realCoeffMatrix = app->newMatrix(height, width);
-    QString realCoeffMatrixName = app->generateUniqueName(tr("RealMatrixFFT"));
-    app->setWindowName(realCoeffMatrix, realCoeffMatrixName);
-    realCoeffMatrix->setWindowLabel(tr("Real part of the FFT transform of") + " " + mReal->objectName());
-
-    Matrix *imagCoeffMatrix = app->newMatrix(height, width);
-    QString imagCoeffMatrixName = app->generateUniqueName(tr("ImagMatrixFFT"));
-    app->setWindowName(imagCoeffMatrix, imagCoeffMatrixName);
-    imagCoeffMatrix->setWindowLabel(tr("Imaginary part of the FFT transform of") + " " + mReal->objectName());
-
-    Matrix *ampMatrix = app->newMatrix(height, width);
-    QString ampMatrixName = app->generateUniqueName(tr("AmplitudeMatrixFFT"));
-    app->setWindowName(ampMatrix, ampMatrixName);
-    ampMatrix->setWindowLabel(tr("Amplitudes of the FFT transform of") + " " + mReal->objectName());
-
-    if (inverse){
-        for (int i = 0; i < height; i++){
-            for (int j = 0; j < width; j++){
-                double re = x_fin_re[i][j];
-                double im = x_fin_im[i][j];
-                realCoeffMatrix->setCell(i, j, re);
-                imagCoeffMatrix->setCell(i, j, im);
-                ampMatrix->setCell(i, j, sqrt(re*re + im*im));
-            }
-        }
-        Matrix::freeMatrixData(x_fin_re, height);
-        Matrix::freeMatrixData(x_fin_im, height);
-    } else {
-        for (int i = 0; i < height; i++){
-            for (int j = 0; j < width; j++){
-                double re = x_int_re[i][j];
-                double im = x_int_im[i][j];
-                realCoeffMatrix->setCell(i, j, re);
-                imagCoeffMatrix->setCell(i, j, im);
-                ampMatrix->setCell(i, j, sqrt(re*re + im*im));
-            }
-        }
+  double **x_fin_re = NULL, **x_fin_im = NULL;
+  if (inverse) {
+    x_fin_re =
+        Matrix::allocateMatrixData(height, width); // coeff of the initial image
+    x_fin_im = Matrix::allocateMatrixData(
+        height, width); // filled with 0 if everythng OK
+    if (!x_fin_re || !x_fin_im) {
+      Matrix::freeMatrixData(x_int_re, height);
+      Matrix::freeMatrixData(x_int_im, height);
+      QApplication::restoreOverrideCursor();
+      return;
     }
 
-    if (boxNormalize->isChecked()){
-        double amp_min, amp_max;
-        ampMatrix->range(&amp_min, &amp_max);
-        for (int i = 0; i < height; i++){
-            for (int j = 0; j < width; j++){
-                double amp = ampMatrix->cell(i, j);
-                ampMatrix->setCell(i, j, amp/amp_max);
-            }
-        }
+    fft2d_inv(x_int_re, x_int_im, x_fin_re, x_fin_im, width, height);
+  } else
+    fft2d(x_int_re, x_int_im, width, height);
+
+  Matrix *realCoeffMatrix = app->newMatrix(height, width);
+  QString realCoeffMatrixName = app->generateUniqueName(tr("RealMatrixFFT"));
+  app->setWindowName(realCoeffMatrix, realCoeffMatrixName);
+  realCoeffMatrix->setWindowLabel(tr("Real part of the FFT transform of") +
+                                  " " + mReal->objectName());
+
+  Matrix *imagCoeffMatrix = app->newMatrix(height, width);
+  QString imagCoeffMatrixName = app->generateUniqueName(tr("ImagMatrixFFT"));
+  app->setWindowName(imagCoeffMatrix, imagCoeffMatrixName);
+  imagCoeffMatrix->setWindowLabel(tr("Imaginary part of the FFT transform of") +
+                                  " " + mReal->objectName());
+
+  Matrix *ampMatrix = app->newMatrix(height, width);
+  QString ampMatrixName = app->generateUniqueName(tr("AmplitudeMatrixFFT"));
+  app->setWindowName(ampMatrix, ampMatrixName);
+  ampMatrix->setWindowLabel(tr("Amplitudes of the FFT transform of") + " " +
+                            mReal->objectName());
+
+  if (inverse) {
+    for (int i = 0; i < height; i++) {
+      for (int j = 0; j < width; j++) {
+        double re = x_fin_re[i][j];
+        double im = x_fin_im[i][j];
+        realCoeffMatrix->setCell(i, j, re);
+        imagCoeffMatrix->setCell(i, j, im);
+        ampMatrix->setCell(i, j, sqrt(re * re + im * im));
+      }
     }
+    Matrix::freeMatrixData(x_fin_re, height);
+    Matrix::freeMatrixData(x_fin_im, height);
+  } else {
+    for (int i = 0; i < height; i++) {
+      for (int j = 0; j < width; j++) {
+        double re = x_int_re[i][j];
+        double im = x_int_im[i][j];
+        realCoeffMatrix->setCell(i, j, re);
+        imagCoeffMatrix->setCell(i, j, im);
+        ampMatrix->setCell(i, j, sqrt(re * re + im * im));
+      }
+    }
+  }
 
-    if (d_matrix){
-        realCoeffMatrix->resize(d_matrix->size());
-        imagCoeffMatrix->resize(d_matrix->size());
-        ampMatrix->resize(d_matrix->size());
+  if (boxNormalize->isChecked()) {
+    double amp_min, amp_max;
+    ampMatrix->range(&amp_min, &amp_max);
+    for (int i = 0; i < height; i++) {
+      for (int j = 0; j < width; j++) {
+        double amp = ampMatrix->cell(i, j);
+        ampMatrix->setCell(i, j, amp / amp_max);
+      }
     }
-    ampMatrix->setViewType(Matrix::ImageView);
+  }
 
-    Matrix::freeMatrixData(x_int_re, height);
-    Matrix::freeMatrixData(x_int_im, height);
-    QApplication::restoreOverrideCursor();
+  if (d_matrix) {
+    realCoeffMatrix->resize(d_matrix->size());
+    imagCoeffMatrix->resize(d_matrix->size());
+    ampMatrix->resize(d_matrix->size());
+  }
+  ampMatrix->setViewType(Matrix::ImageView);
+
+  Matrix::freeMatrixData(x_int_re, height);
+  Matrix::freeMatrixData(x_int_im, height);
+  QApplication::restoreOverrideCursor();
 }
diff --git a/MantidPlot/src/FFTDialog.h b/MantidPlot/src/FFTDialog.h
index 23c3a89ea70bbaf6c01ecda6edbd78e207b0c0df..d7673eb684e7193f77a29c11f69e8dcf3a93e1aa 100644
--- a/MantidPlot/src/FFTDialog.h
+++ b/MantidPlot/src/FFTDialog.h
@@ -2,7 +2,8 @@
     File                 : FFTDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fast Fourier transform options dialog
 
@@ -41,39 +42,35 @@ class Table;
 class Matrix;
 
 //! Fast Fourier transform options dialog
-class FFTDialog : public QDialog
-{
-    Q_OBJECT
+class FFTDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	enum DataType{onGraph = 0, onTable = 1, onMatrix = 2};
+  enum DataType { onGraph = 0, onTable = 1, onMatrix = 2 };
 
-    FFTDialog(int type, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  FFTDialog(int type, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void setGraph(Graph *g);
-	void setTable(Table *t);
-	void setMatrix(Matrix *m);
-	void activateCurve(const QString& curveName);
-        void accept() override;
+  void setGraph(Graph *g);
+  void setTable(Table *t);
+  void setMatrix(Matrix *m);
+  void activateCurve(const QString &curveName);
+  void accept() override;
 
 private:
-    void fftMatrix();
+  void fftMatrix();
 
-	Graph *graph;
-	Table *d_table;
-	Matrix *d_matrix;
-	int d_type;
+  Graph *graph;
+  Table *d_table;
+  Matrix *d_matrix;
+  int d_type;
 
-	QPushButton* buttonOK;
-	QPushButton* buttonCancel;
-	QRadioButton *forwardBtn, *backwardBtn;
-	QComboBox* boxName, *boxReal, *boxImaginary;
-	QLineEdit* boxSampling;
-	QCheckBox* boxNormalize, *boxOrder;
+  QPushButton *buttonOK;
+  QPushButton *buttonCancel;
+  QRadioButton *forwardBtn, *backwardBtn;
+  QComboBox *boxName, *boxReal, *boxImaginary;
+  QLineEdit *boxSampling;
+  QCheckBox *boxNormalize, *boxOrder;
 };
 
 #endif
-
-
-
diff --git a/MantidPlot/src/FFTFilter.cpp b/MantidPlot/src/FFTFilter.cpp
index fb0f98852f927b25f6121840c41e9d9d67123784..485521efca2bf18013d80425817b9899100afdc0 100644
--- a/MantidPlot/src/FFTFilter.cpp
+++ b/MantidPlot/src/FFTFilter.cpp
@@ -33,147 +33,139 @@
 
 #include <gsl/gsl_fft_halfcomplex.h>
 
-FFTFilter::FFTFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m)
-: Filter(parent, g)
-{
-	setDataFromCurve(curveTitle);
-	init(m);
+FFTFilter::FFTFilter(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle, int m)
+    : Filter(parent, g) {
+  setDataFromCurve(curveTitle);
+  init(m);
 }
 
-FFTFilter::FFTFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle,
-                             double start, double end, int m)
-: Filter(parent, g)
-{
-	setDataFromCurve(curveTitle, start, end);
-    init(m);
+FFTFilter::FFTFilter(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle, double start, double end, int m)
+    : Filter(parent, g) {
+  setDataFromCurve(curveTitle, start, end);
+  init(m);
 }
 
-FFTFilter::FFTFilter(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end, int m)
-: Filter(parent, t)
-{
-	setDataFromTable(t, xCol, yCol, start, end);
-	init(m);
+FFTFilter::FFTFilter(ApplicationWindow *parent, Table *t, const QString &xCol,
+                     const QString &yCol, int start, int end, int m)
+    : Filter(parent, t) {
+  setDataFromTable(t, xCol, yCol, start, end);
+  init(m);
 }
 
-void FFTFilter::init (int m)
-{
-    setObjectName(tr("FFT") + tr("Filtered"));
-    setFilterType(m);
-    d_points = d_n;
-    d_offset = true;
-    d_low_freq = 0;
-    d_high_freq = 0;
+void FFTFilter::init(int m) {
+  setObjectName(tr("FFT") + tr("Filtered"));
+  setFilterType(m);
+  d_points = d_n;
+  d_offset = true;
+  d_low_freq = 0;
+  d_high_freq = 0;
 }
 
-
-void FFTFilter::setFilterType(int type)
-{
-    if (type < 1 || type > 4)
-    {
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-        tr("Unknown filter type. Valid values are: 1 - Low pass, 2 - High Pass, 3 - Band Pass, 4 - Band block."));
-        d_init_err = true;
-        return;
-    }
-    d_filter_type = (FilterType)type;
+void FFTFilter::setFilterType(int type) {
+  if (type < 1 || type > 4) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("Unknown filter type. Valid values are: 1 - Low pass, 2 - High "
+           "Pass, 3 - Band Pass, 4 - Band block."));
+    d_init_err = true;
+    return;
+  }
+  d_filter_type = (FilterType)type;
 }
 
-void FFTFilter::setCutoff(double f)
-{
-    if (d_filter_type > 2 && d_low_freq == f)
-        return;
+void FFTFilter::setCutoff(double f) {
+  if (d_filter_type > 2 && d_low_freq == f)
+    return;
 
-    d_low_freq = f;
+  d_low_freq = f;
 }
 
-void FFTFilter::setBand(double lowFreq, double highFreq)
-{
-    if (d_filter_type < 3)
-        return;
-    else if (lowFreq == highFreq)
-    {
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
+void FFTFilter::setBand(double lowFreq, double highFreq) {
+  if (d_filter_type < 3)
+    return;
+  else if (lowFreq == highFreq) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
         tr("Please enter different values for the band limits."));
-        d_init_err = true;
-        return;
-    }
+    d_init_err = true;
+    return;
+  }
+
+  if (lowFreq > highFreq) {
+    d_low_freq = highFreq;
+    d_high_freq = lowFreq;
+  } else {
+    d_low_freq = lowFreq;
+    d_high_freq = highFreq;
+  }
+}
 
-    if (lowFreq > highFreq)
-    {
-        d_low_freq = highFreq;
-        d_high_freq = lowFreq;
-    }
-    else
-    {
-        d_low_freq = lowFreq;
-        d_high_freq = highFreq;
+void FFTFilter::calculateOutputData(double *x, double *y) {
+  for (int i = 0; i < d_points; i++) {
+    x[i] = d_x[i];
+    y[i] = d_y[i];
+  }
+
+  double df =
+      0.5 /
+      (double)(d_n *
+               (x[1] - x[0])); // half frequency sampling due to GSL storing
+
+  gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n);
+  gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n);
+
+  gsl_fft_real_transform(y, 1, d_n, real, work);
+  gsl_fft_real_wavetable_free(real);
+
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
+  QLocale locale = app->locale();
+
+  d_explanation = locale.toString(d_low_freq) + " ";
+  if (d_filter_type > 2)
+    d_explanation += tr("to") + " " + locale.toString(d_high_freq) + " ";
+  d_explanation += tr("Hz") + " ";
+
+  switch ((int)d_filter_type) {
+  case 1: // low pass
+    d_explanation += tr("Low Pass FFT Filter");
+    for (int i = 0; i < d_n; i++)
+      y[i] = i * df > d_low_freq ? 0 : y[i];
+    break;
+
+  case 2: // high pass
+    d_explanation += tr("High Pass FFT Filter");
+    for (int i = 0; i < d_n; i++)
+      y[i] = i * df < d_low_freq ? 0 : y[i];
+    break;
+
+  case 3: // band pass
+    d_explanation += tr("Band Pass FFT Filter");
+    if (d_offset) { // keep DC offset
+      for (int i = 1; i < d_n; i++)
+        y[i] = ((i * df > d_low_freq) && (i * df < d_high_freq)) ? y[i] : 0;
+    } else {
+      for (int i = 0; i < d_n; i++)
+        y[i] = ((i * df > d_low_freq) && (i * df < d_high_freq)) ? y[i] : 0;
     }
-}
+    break;
+
+  case 4: // band block
+    d_explanation += tr("Band Block FFT Filter");
+
+    if (!d_offset)
+      y[0] = 0; // substract DC offset
+
+    for (int i = 1; i < d_n; i++)
+      y[i] = ((i * df > d_low_freq) && (i * df < d_high_freq)) ? 0 : y[i];
+    break;
+  }
 
-void FFTFilter::calculateOutputData(double *x, double *y)
-{
-    for (int i = 0; i < d_points; i++){
-	   x[i] = d_x[i];
-	   y[i] = d_y[i];
-	}
-
-    double df = 0.5/(double)(d_n*(x[1]-x[0]));//half frequency sampling due to GSL storing
-
-	gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n);
-	gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n);
-
-	gsl_fft_real_transform (y, 1, d_n, real, work);
-	gsl_fft_real_wavetable_free (real);
-
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-    QLocale locale = app->locale();
-
-    d_explanation = locale.toString(d_low_freq) + " ";
-	if (d_filter_type > 2)
-	   d_explanation += tr("to") + " " + locale.toString(d_high_freq) + " ";
-	d_explanation += tr("Hz") + " ";
-
-	switch ((int)d_filter_type)
-	{
-		case 1://low pass
-			d_explanation += tr("Low Pass FFT Filter");
-			for (int i = 0; i < d_n; i++)
-				y[i] = i*df > d_low_freq ? 0 : y[i];
-			break;
-
-		case 2://high pass
-			d_explanation += tr("High Pass FFT Filter");
-			for (int i = 0; i < d_n; i++)
-				y[i] = i*df < d_low_freq ? 0 : y[i];
-			break;
-
-		case 3://band pass
-			d_explanation += tr("Band Pass FFT Filter");
-			if(d_offset)
-			{// keep DC offset
-				for (int i = 1; i < d_n; i++)
-					y[i] = ((i*df > d_low_freq ) && (i*df < d_high_freq )) ? y[i] : 0;
-			}
-			else
-			{
-				for (int i = 0; i < d_n; i++)
-					y[i] = ((i*df > d_low_freq ) && (i*df < d_high_freq )) ? y[i] : 0;
-			}
-			break;
-
-		case 4://band block
-			d_explanation += tr("Band Block FFT Filter");
-
-			if(!d_offset)
-				y[0] = 0;//substract DC offset
-
-			for (int i = 1; i < d_n; i++)
-				y[i] = ((i*df > d_low_freq ) && (i*df < d_high_freq )) ? 0 : y[i];
-			break;
-	}
-
-	gsl_fft_halfcomplex_wavetable *hc = gsl_fft_halfcomplex_wavetable_alloc (d_n);
-	gsl_fft_halfcomplex_inverse (y, 1, d_n, hc, work);
-	gsl_fft_halfcomplex_wavetable_free (hc);
-	gsl_fft_real_workspace_free (work);
+  gsl_fft_halfcomplex_wavetable *hc = gsl_fft_halfcomplex_wavetable_alloc(d_n);
+  gsl_fft_halfcomplex_inverse(y, 1, d_n, hc, work);
+  gsl_fft_halfcomplex_wavetable_free(hc);
+  gsl_fft_real_workspace_free(work);
 }
diff --git a/MantidPlot/src/FFTFilter.h b/MantidPlot/src/FFTFilter.h
index 2db38ee13093eab80fc7995cf28d03968da7bbfc..a1ef98b44798f4153058cddb0f8fa9d8b2e1f10b 100644
--- a/MantidPlot/src/FFTFilter.h
+++ b/MantidPlot/src/FFTFilter.h
@@ -31,43 +31,50 @@
 
 #include "Filter.h"
 
-class FFTFilter : public Filter
-{
-Q_OBJECT
+class FFTFilter : public Filter {
+  Q_OBJECT
 
 public:
-	FFTFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m = 1);
-	FFTFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end, int m = 1);
-	FFTFilter(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start = 0, int end = -1, int m = 1);
+  FFTFilter(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+            int m = 1);
+  FFTFilter(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+            double start, double end, int m = 1);
+  FFTFilter(ApplicationWindow *parent, Table *t, const QString &xCol,
+            const QString &yCol, int start = 0, int end = -1, int m = 1);
 
-    enum FilterType{LowPass = 1, HighPass = 2, BandPass = 3, BandBlock = 4};
+  enum FilterType { LowPass = 1, HighPass = 2, BandPass = 3, BandBlock = 4 };
 
-    void setFilterType(int type);
+  void setFilterType(int type);
 
-    //! Sets the cutoff frequency. To be used only for Low Pass and High Pass filters.
-    void setCutoff(double f);
+  //! Sets the cutoff frequency. To be used only for Low Pass and High Pass
+  // filters.
+  void setCutoff(double f);
 
-    //! Sets the cutoff frequencies. To be used only for the Band Pass and Band block filters.
-    void setBand(double lowFreq, double highFreq);
+  //! Sets the cutoff frequencies. To be used only for the Band Pass and Band
+  // block filters.
+  void setBand(double lowFreq, double highFreq);
 
-    //! Enables/Disables the DC offset when applying a Band Pass/Band block filter.
-    void enableOffset(bool offset = true){d_offset = offset;};
+  //! Enables/Disables the DC offset when applying a Band Pass/Band block
+  // filter.
+  void enableOffset(bool offset = true) { d_offset = offset; };
 
 private:
-    void init(int m);
-    void calculateOutputData(double *x, double *y) override;
+  void init(int m);
+  void calculateOutputData(double *x, double *y) override;
 
-    //! The filter type.
-    FilterType d_filter_type;
+  //! The filter type.
+  FilterType d_filter_type;
 
-    //! Cutoff frequency for Low Pass and High Pass filters. Lower edge of the band for Band Pass and Band block filters.
-    double d_low_freq;
+  //! Cutoff frequency for Low Pass and High Pass filters. Lower edge of the
+  // band for Band Pass and Band block filters.
+  double d_low_freq;
 
-    //! Upper edge of the band for Band Pass and Band block filters.
-    double d_high_freq;
+  //! Upper edge of the band for Band Pass and Band block filters.
+  double d_high_freq;
 
-    //! Flag telling if the DC offset must be added/substracted when applying a Band Pass/Band block filter respectively.
-    bool d_offset;
+  //! Flag telling if the DC offset must be added/substracted when applying a
+  // Band Pass/Band block filter respectively.
+  bool d_offset;
 };
 
 #endif
diff --git a/MantidPlot/src/Filter.cpp b/MantidPlot/src/Filter.cpp
index 02bf7f1a7dbba50d8a2865e3361ef35a1e7664ac..d7df474055b37d4506ba6a7ec13031ef12f95db7 100644
--- a/MantidPlot/src/Filter.cpp
+++ b/MantidPlot/src/Filter.cpp
@@ -40,438 +40,449 @@
 
 #include <gsl/gsl_sort.h>
 
-Filter::Filter( ApplicationWindow *parent, Graph *g, const QString& name)
-: QObject( parent)
-{
-	init();
-	setObjectName(name);
-	d_graph = g;
-	d_output_graph = g;
+Filter::Filter(ApplicationWindow *parent, Graph *g, const QString &name)
+    : QObject(parent) {
+  init();
+  setObjectName(name);
+  d_graph = g;
+  d_output_graph = g;
 }
 
-Filter::Filter( ApplicationWindow *parent, Table *t, const QString& name)
-: QObject( parent)
-{
-	init();
-	setObjectName(name);
-	d_table = t;
+Filter::Filter(ApplicationWindow *parent, Table *t, const QString &name)
+    : QObject(parent) {
+  init();
+  setObjectName(name);
+  d_table = t;
 }
 
-void Filter::init()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+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.");
+    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 = app->fit_output_precision;
-	d_init_err = false;
-    d_sort_data = true;
-    d_min_points = 2;
-    d_explanation = objectName();
-    d_graph = 0;
-    d_table = 0;
-    d_result_table = 0;
-	d_output_graph = 0;
-	d_graphics_display = true;
-	d_y_col_name = QString::null;
+  d_n = 0;
+  d_curveColorIndex = 1;
+  d_tolerance = 1e-4;
+  d_points = 100;
+  d_max_iterations = 1000;
+  d_curve = 0;
+  d_prec = app->fit_output_precision;
+  d_init_err = false;
+  d_sort_data = true;
+  d_min_points = 2;
+  d_explanation = objectName();
+  d_graph = 0;
+  d_table = 0;
+  d_result_table = 0;
+  d_output_graph = 0;
+  d_graphics_display = true;
+  d_y_col_name = QString::null;
 }
 
-void Filter::setInterval(double from, double to)
-{
-	if (!d_curve){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("Please assign a curve first!"));
-		return;
-	}
-	setDataFromCurve (d_curve->title().text(), from, to);
+void Filter::setInterval(double from, double to) {
+  if (!d_curve) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Please assign a curve first!"));
+    return;
+  }
+  setDataFromCurve(d_curve->title().text(), from, to);
 }
 
-void Filter::setDataCurve(int curve, double start, double end)
-{
-	if (d_n > 0)
-	{//delete previousely allocated memory
-		delete[] d_x;
-		delete[] d_y;
-	}
-
-	d_init_err = false;
-	d_curve = d_graph->curve(curve);
-    if (d_sort_data)
-        d_n = sortedCurveData(d_curve, start, end, &d_x, &d_y);
-    else
-    	d_n = curveData(d_curve, start, end, &d_x, &d_y);
-
-	if (d_n == -1){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("Several data points have the same x value causing divisions by zero, operation aborted!"));
-		d_init_err = true;
-        return;
-	}else if (d_n < d_min_points){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("You need at least %1 points in order to perform this operation!").arg(d_min_points));
-		d_init_err = true;
-        return;
-	}
-
-    d_from = start;
-    d_to = end;
+void Filter::setDataCurve(int curve, double start, double end) {
+  if (d_n > 0) { // delete previousely allocated memory
+    delete[] d_x;
+    delete[] d_y;
+  }
+
+  d_init_err = false;
+  d_curve = d_graph->curve(curve);
+  if (d_sort_data)
+    d_n = sortedCurveData(d_curve, start, end, &d_x, &d_y);
+  else
+    d_n = curveData(d_curve, start, end, &d_x, &d_y);
+
+  if (d_n == -1) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Several data points have the same x value "
+                             "causing divisions by zero, operation aborted!"));
+    d_init_err = true;
+    return;
+  } else if (d_n < d_min_points) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("You need at least %1 points in order to perform this operation!")
+            .arg(d_min_points));
+    d_init_err = true;
+    return;
+  }
+
+  d_from = start;
+  d_to = end;
 }
 
-int Filter::curveIndex(const QString& curveTitle, Graph *g)
-{
-	if (curveTitle.isEmpty()){
-		QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Filter Error"),
-				tr("Please enter a valid curve name!"));
-		d_init_err = true;
-		return -1;
-	}
-
-	if (g){
-		d_graph = g;
-		d_output_graph = g;
-	}
-
-	if (!d_graph){
-		d_init_err = true;
-		return -1;
-	}
-
-	return d_graph->curveIndex(curveTitle);
+int Filter::curveIndex(const QString &curveTitle, Graph *g) {
+  if (curveTitle.isEmpty()) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot - Filter Error"),
+                          tr("Please enter a valid curve name!"));
+    d_init_err = true;
+    return -1;
+  }
+
+  if (g) {
+    d_graph = g;
+    d_output_graph = g;
+  }
+
+  if (!d_graph) {
+    d_init_err = true;
+    return -1;
+  }
+
+  return d_graph->curveIndex(curveTitle);
 }
 
-bool Filter::setDataFromCurve(const QString& curveTitle, Graph *g)
-{
-	int index = curveIndex(curveTitle, g);
-	if (index < 0){
-		d_init_err = true;
-		return false;
-	}
-
-  	d_graph->range(index, &d_from, &d_to);
-    setDataCurve(index, d_from, d_to);
-	return true;
+bool Filter::setDataFromCurve(const QString &curveTitle, Graph *g) {
+  int index = curveIndex(curveTitle, g);
+  if (index < 0) {
+    d_init_err = true;
+    return false;
+  }
+
+  d_graph->range(index, &d_from, &d_to);
+  setDataCurve(index, d_from, d_to);
+  return true;
 }
 
-bool Filter::setDataFromCurve(const QString& curveTitle, double from, double to, Graph *g)
-{
-	int index = curveIndex(curveTitle, g);
-	if (index < 0){
-		d_init_err = true;
-		return false;
-	}
+bool Filter::setDataFromCurve(const QString &curveTitle, double from, double to,
+                              Graph *g) {
+  int index = curveIndex(curveTitle, g);
+  if (index < 0) {
+    d_init_err = true;
+    return false;
+  }
 
-	setDataCurve(index, from, to);
-	return true;
+  setDataCurve(index, from, to);
+  return true;
 }
 
-void Filter::setColor(const QString& colorName)
-{
-    QColor c = QColor(colorName);
-    if (colorName == "green")
-        c = QColor(Qt::green);
-    else if (colorName == "darkYellow")
-        c = QColor(Qt::darkYellow);
-    if (!ColorBox::isValidColor(c)){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Color Name Error"),
-				tr("The color name '%1' is not valid, a default color (red) will be used instead!").arg(colorName));
-        d_curveColorIndex = 1;
-        return;
-    }
+void Filter::setColor(const QString &colorName) {
+  QColor c = QColor(colorName);
+  if (colorName == "green")
+    c = QColor(Qt::green);
+  else if (colorName == "darkYellow")
+    c = QColor(Qt::darkYellow);
+  if (!ColorBox::isValidColor(c)) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Color Name Error"),
+        tr("The color name '%1' is not valid, a default color (red) will be "
+           "used instead!").arg(colorName));
+    d_curveColorIndex = 1;
+    return;
+  }
 
-	d_curveColorIndex = ColorBox::colorIndex(c);
+  d_curveColorIndex = ColorBox::colorIndex(c);
 }
 
-void Filter::showLegend()
-{
-	if (!d_output_graph)
-		return;
+void Filter::showLegend() {
+  if (!d_output_graph)
+    return;
 
-	LegendWidget* legend = d_output_graph->legend();
-	LegendWidget* l = d_output_graph->newLegend(legendInfo());
-	if (legend)
-		l->move(QPoint(legend->x(), legend->y() + legend->height() + 20));
+  LegendWidget *legend = d_output_graph->legend();
+  LegendWidget *l = d_output_graph->newLegend(legendInfo());
+  if (legend)
+    l->move(QPoint(legend->x(), legend->y() + legend->height() + 20));
 }
 
-bool Filter::run()
-{
-	if (d_init_err)
-		return false;
+bool Filter::run() {
+  if (d_init_err)
+    return false;
 
-	if (d_n < 0){
-	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (d_n < 0) {
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
     if (!app) {
-      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+      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;
-	}
+    QMessageBox::critical(
+        app, tr("MantidPlot") + " - " + tr("Error"),
+        tr("You didn't specify a valid data set for this operation!"));
+    return false;
+  }
 
-	QApplication::setOverrideCursor(Qt::WaitCursor);
+  QApplication::setOverrideCursor(Qt::WaitCursor);
 
-    output();//data analysis and output
-	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-    if (!app) {
-      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
-    }
-    app->updateLog(logInfo());
+  output(); // data analysis and output
+  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;
+  QApplication::restoreOverrideCursor();
+  return true;
 }
 
-void Filter::output()
-{
-    QVarLengthArray<double> X(d_points), Y(d_points);
-    calculateOutputData(X.data(), Y.data()); //does the data analysis
-	addResultCurve(X.data(), Y.data());
+void Filter::output() {
+  QVarLengthArray<double> X(d_points), Y(d_points);
+  calculateOutputData(X.data(), Y.data()); // does the data analysis
+  addResultCurve(X.data(), Y.data());
 }
 
-int Filter::sortedCurveData(QwtPlotCurve *c, double start, double end, double **x, double **y)
-{
-    if (!c)
-        return 0;
+int Filter::sortedCurveData(QwtPlotCurve *c, double start, double end,
+                            double **x, double **y) {
+  if (!c)
+    return 0;
 
-	int i_start = 0, i_end = 0;
-	int n = curveRange(c, start, end, &i_start, &i_end);
+  int i_start = 0, i_end = 0;
+  int n = curveRange(c, start, end, &i_start, &i_end);
 
-    (*x) = new double[n];
-    (*y) = new double[n];
-    double *xtemp = new double[n];
-    double *ytemp = new double[n];
+  (*x) = new double[n];
+  (*y) = new double[n];
+  double *xtemp = new double[n];
+  double *ytemp = new double[n];
 
-  	int j=0;
-    for (int i = i_start; i <= i_end; i++){
-        xtemp[j] = c->x(i);
-        ytemp[j++] = c->y(i);
-    }
-    size_t *p = new size_t[n];
-    gsl_sort_index(p, xtemp, 1, n);
-    for (int i=0; i<n; i++){
-        (*x)[i] = xtemp[p[i]];
-  	    (*y)[i] = ytemp[p[i]];
-    }
+  int j = 0;
+  for (int i = i_start; i <= i_end; i++) {
+    xtemp[j] = c->x(i);
+    ytemp[j++] = c->y(i);
+  }
+  size_t *p = new size_t[n];
+  gsl_sort_index(p, xtemp, 1, n);
+  for (int i = 0; i < n; i++) {
+    (*x)[i] = xtemp[p[i]];
+    (*y)[i] = ytemp[p[i]];
+  }
 
-    delete[] xtemp;
-    delete[] ytemp;
-    delete[] p;
-    return n;
+  delete[] xtemp;
+  delete[] ytemp;
+  delete[] p;
+  return n;
 }
 
-int Filter::curveData(QwtPlotCurve *c, double start, double end, double **x, double **y)
-{
-    if (!c)
-        return 0;
+int Filter::curveData(QwtPlotCurve *c, double start, double end, double **x,
+                      double **y) {
+  if (!c)
+    return 0;
+
+  int i_start = 0, i_end = 0;
+  int n = curveRange(c, start, end, &i_start, &i_end);
+
+  (*x) = new double[n];
+  (*y) = new double[n];
+
+  int j = 0;
+  for (int i = i_start; i <= i_end; i++) {
+    (*x)[j] = c->x(i);
+    (*y)[j++] = c->y(i);
+  }
+  return n;
+}
 
-   	int i_start = 0, i_end = 0;
-	int n = curveRange(c, start, end, &i_start, &i_end);
+int Filter::curveRange(QwtPlotCurve *c, double start, double end, int *iStart,
+                       int *iEnd) {
+  if (!c)
+    return 0;
 
-    (*x) = new double[n];
-    (*y) = new double[n];
+  int n = c->dataSize();
+  int i_start = 0, i_end = n;
 
-    int j=0;
-    for (int i = i_start; i <= i_end; i++){
-        (*x)[j] = c->x(i);
-        (*y)[j++] = c->y(i);
+  if (c->x(0) < c->x(n - 1)) {
+    for (int i = 0; i < n; i++) {
+      if (c->x(i) >= start) {
+        i_start = i;
+        break;
+      }
+    }
+    for (int i = n - 1; i >= 0; i--) {
+      if (c->x(i) <= end) {
+        i_end = i;
+        break;
+      }
+    }
+  } else {
+    for (int i = 0; i < n; i++) {
+      if (c->x(i) <= end) {
+        i_start = i;
+        break;
+      }
+    }
+    for (int i = n - 1; i >= 0; i--) {
+      if (c->x(i) >= start) {
+        i_end = i;
+        break;
+      }
     }
-    return n;
+  }
+
+  *iStart = QMIN(i_start, i_end);
+  *iEnd = QMAX(i_start, i_end);
+  n = abs(i_end - i_start) + 1;
+  return n;
 }
 
-int Filter::curveRange(QwtPlotCurve *c, double start, double end, int *iStart, int *iEnd)
-{
-    if (!c)
-        return 0;
-
-    int n = c->dataSize();
-    int i_start = 0, i_end = n;
-
-	if (c->x(0) < c->x(n-1)){
-    	for (int i = 0; i < n; i++){
-  	   	 if (c->x(i) >= start){
-  	    	  i_start = i;
-          	break;
-        	}
-		}
-    	for (int i = n-1; i >= 0; i--){
-  	    	if (c->x(i) <= end){
-  	      		i_end = i;
-          		break;
-        	}
-		}
-	} else {
-    	for (int i = 0; i < n; i++){
-  	   	 if (c->x(i) <= end){
-  	    	  i_start = i;
-          	break;
-        	}
-		}
-    	for (int i = n-1; i >= 0; i--){
-  	    	if (c->x(i) >= start){
-  	      		i_end = i;
-          		break;
-        	}
-		}
-	}
-
-	*iStart = QMIN(i_start, i_end);
-	*iEnd = QMAX(i_start, i_end);
-    n = abs(i_end - i_start) + 1;
-    return n;
+QwtPlotCurve *Filter::addResultCurve(double *x, double *y) {
+  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;
+  if (d_curve)
+    dataSet = d_curve->title().text();
+  else
+    dataSet = d_y_col_name;
+
+  d_result_table = app->newHiddenTable(
+      tableName, d_explanation + " " + tr("of") + " " + dataSet, d_points, 2);
+  for (int i = 0; i < d_points; i++) {
+    d_result_table->setText(i, 0,
+                            locale.toString(x[i], 'e', app->d_decimal_digits));
+    d_result_table->setText(i, 1,
+                            locale.toString(y[i], 'e', app->d_decimal_digits));
+  }
+
+  DataCurve *c = 0;
+  if (d_graphics_display) {
+    c = new DataCurve(d_result_table, tableName + "_1", tableName + "_2");
+    c->setData(x, y, d_points);
+    c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
+
+    if (!d_output_graph)
+      d_output_graph = createOutputGraph()->activeGraph();
+
+    d_output_graph->insertPlotItem(c, Graph::Line);
+    d_output_graph->updatePlot();
+  }
+  return dynamic_cast<QwtPlotCurve *>(c);
 }
 
-QwtPlotCurve* Filter::addResultCurve(double *x, double *y)
-{
-	  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;
-	if (d_curve)
-		dataSet = d_curve->title().text();
-	else
-		dataSet = d_y_col_name;
-
-    d_result_table = app->newHiddenTable(tableName, d_explanation + " " + tr("of") + " " + dataSet, d_points, 2);
-	for (int i=0; i<d_points; i++){
-		d_result_table->setText(i, 0, locale.toString(x[i], 'e', app->d_decimal_digits));
-		d_result_table->setText(i, 1, locale.toString(y[i], 'e', app->d_decimal_digits));
-	}
-
-	DataCurve *c = 0;
-	if (d_graphics_display){
-		c = new DataCurve(d_result_table, tableName + "_1", tableName + "_2");
-		c->setData(x, y, d_points);
-    	c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
-
-		if (!d_output_graph)
-			d_output_graph = createOutputGraph()->activeGraph();
-
-		d_output_graph->insertPlotItem(c, Graph::Line);
-    	d_output_graph->updatePlot();
-	}
-	return dynamic_cast<QwtPlotCurve*>(c);
+void Filter::enableGraphicsDisplay(bool on, Graph *g) {
+  d_graphics_display = on;
+  if (on) {
+    if (g)
+      d_output_graph = g;
+    else
+      d_output_graph = createOutputGraph()->activeGraph();
+  }
 }
 
-void Filter::enableGraphicsDisplay(bool on, Graph *g)
-{
-	d_graphics_display = on;
-	if (on){
-		if (g)
-			d_output_graph = g;
-		else
-			d_output_graph = createOutputGraph()->activeGraph();
-	}
+MultiLayer *Filter::createOutputGraph() {
+  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;
 }
 
-MultiLayer * Filter::createOutputGraph()
-{
-	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-    if (!app) {
-      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
+bool Filter::setDataFromTable(Table *t, const QString &xColName,
+                              const QString &yColName, int startRow,
+                              int endRow) {
+  d_init_err = true;
+
+  if (!t)
+    return false;
+
+  int xcol = t->colIndex(xColName);
+  int ycol = t->colIndex(yColName);
+  if (xcol < 0 || ycol < 0)
+    return false;
+
+  if (t->columnType(xcol) != Table::Numeric ||
+      t->columnType(ycol) != Table::Numeric)
+    return false;
+
+  startRow--;
+  endRow--;
+  if (startRow < 0 || startRow >= t->numRows())
+    startRow = 0;
+  if (endRow < 0 || endRow >= t->numRows())
+    endRow = t->numRows() - 1;
+
+  int from = QMIN(startRow, endRow);
+  int to = QMAX(startRow, endRow);
+
+  int r = abs(to - from) + 1;
+  QVector<double> X(r), Y(r);
+
+  int size = 0;
+  for (int i = from; i <= to; i++) {
+    QString xval = t->text(i, xcol);
+    QString yval = t->text(i, ycol);
+    if (!xval.isEmpty() && !yval.isEmpty()) {
+      bool valid_data = true;
+      X[size] = t->locale().toDouble(xval, &valid_data);
+      Y[size] = t->locale().toDouble(yval, &valid_data);
+      if (valid_data)
+        size++;
     }
-    MultiLayer *ml = app->newGraph(objectName() + tr("Plot"));
-   	d_output_graph = ml->activeGraph();
-	return ml;
-}
+  }
 
-bool Filter::setDataFromTable(Table *t, const QString& xColName, const QString& yColName, int startRow, int endRow)
-{
-	d_init_err = true;
-
-	if (!t)
-		return false;
-
-	int xcol = t->colIndex(xColName);
-	int ycol = t->colIndex(yColName);
-	if (xcol < 0 || ycol < 0)
-		return false;
-
-	if (t->columnType(xcol) != Table::Numeric || t->columnType(ycol) != Table::Numeric)
-		return false;
-
-    startRow--; endRow--;
-	if (startRow < 0 || startRow >= t->numRows())
-		startRow = 0;
-	if (endRow < 0 || endRow >= t->numRows())
-		endRow = t->numRows() - 1;
-
-    int from = QMIN(startRow, endRow);
-    int to = QMAX(startRow, endRow);
-
-	int r = abs(to - from) + 1;
-    QVector<double> X(r), Y(r);
-
-	int size = 0;
-	for (int i = from; i<=to; i++ ){
-		QString xval = t->text(i, xcol);
-		QString yval = t->text(i, ycol);
-		if (!xval.isEmpty() && !yval.isEmpty()){
-		    bool valid_data = true;
-            X[size] = t->locale().toDouble(xval, &valid_data);
-            Y[size] = t->locale().toDouble(yval, &valid_data);
-            if (valid_data)
-                size++;
-		}
-	}
-
-	if (size < d_min_points){
-	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (size < d_min_points) {
+    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;
-	}
-
-	if (d_n > 0){//delete previousely allocated memory
-		delete[] d_x;
-		delete[] d_y;
-	}
-
-	d_graph = 0;
-	d_curve = 0;
-	d_n = size;
-	d_init_err = false;
-	d_table = t;
-	d_y_col_name = t->colName(ycol);
-	X.resize(d_n);
-	Y.resize(d_n);
-	d_from = X[0];
-    d_to = X[d_n-1];
-
-	d_x = new double[d_n];
-    d_y = new double[d_n];
-
-    for (int i = 0; i < d_n; i++){
-        d_x[i] = X[i];
-        d_y[i] = Y[i];
+      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;
+  }
 
-	if (d_sort_data){
-    	size_t *p = new size_t[d_n];
-   		gsl_sort_index(p, X.data(), 1, d_n);
-    	for (int i=0; i<d_n; i++){
-        	d_x[i] = X[static_cast<int>(p[i])];
-  	    	d_y[i] = Y[static_cast<int>(p[i])];
-		}
-		delete[] p;
+  if (d_n > 0) { // delete previousely allocated memory
+    delete[] d_x;
+    delete[] d_y;
+  }
+
+  d_graph = 0;
+  d_curve = 0;
+  d_n = size;
+  d_init_err = false;
+  d_table = t;
+  d_y_col_name = t->colName(ycol);
+  X.resize(d_n);
+  Y.resize(d_n);
+  d_from = X[0];
+  d_to = X[d_n - 1];
+
+  d_x = new double[d_n];
+  d_y = new double[d_n];
+
+  for (int i = 0; i < d_n; i++) {
+    d_x[i] = X[i];
+    d_y[i] = Y[i];
+  }
+
+  if (d_sort_data) {
+    size_t *p = new size_t[d_n];
+    gsl_sort_index(p, X.data(), 1, d_n);
+    for (int i = 0; i < d_n; i++) {
+      d_x[i] = X[static_cast<int>(p[i])];
+      d_y[i] = Y[static_cast<int>(p[i])];
     }
-	return true;
+    delete[] p;
+  }
+  return true;
 }
 
-Filter::~Filter()
-{
-	if (d_n > 0){//delete the memory allocated for the data
-		if (d_x) delete[] d_x;
-		if (d_y) delete[] d_y;
-	}
+Filter::~Filter() {
+  if (d_n > 0) { // delete the memory allocated for the data
+    if (d_x)
+      delete[] d_x;
+    if (d_y)
+      delete[] d_y;
+  }
 }
diff --git a/MantidPlot/src/Filter.h b/MantidPlot/src/Filter.h
index 64e553b6b038537795dca35b9a96f61a6a9b0c04..64d7fc4ab639afba0fb15e6d09313e92e61678d7 100644
--- a/MantidPlot/src/Filter.h
+++ b/MantidPlot/src/Filter.h
@@ -38,150 +38,167 @@ class Graph;
 class Table;
 
 //! Abstract base class for data analysis operations
-class Filter : public QObject
-{
-	Q_OBJECT
+class Filter : public QObject {
+  Q_OBJECT
 
-	public:
-        Filter(ApplicationWindow *parent, Table *t = 0, const QString& name = QString());
-		Filter(ApplicationWindow *parent, Graph *g = 0, const QString& name = QString());
-                ~Filter() override;
+public:
+  Filter(ApplicationWindow *parent, Table *t = 0,
+         const QString &name = QString());
+  Filter(ApplicationWindow *parent, Graph *g = 0,
+         const QString &name = QString());
+  ~Filter() override;
 
-                //! Actually does the job. Should be reimplemented in derived classes.
-		virtual bool run();
+  //! Actually does the job. Should be reimplemented in derived classes.
+  virtual bool run();
 
-        virtual void setDataCurve(int curve, double start, double end);
-		bool setDataFromCurve(const QString& curveTitle, Graph *g = 0);
-		bool setDataFromCurve(const QString& curveTitle, double from, double to, Graph *g = 0);
+  virtual void setDataCurve(int curve, double start, double end);
+  bool setDataFromCurve(const QString &curveTitle, Graph *g = 0);
+  bool setDataFromCurve(const QString &curveTitle, double from, double to,
+                        Graph *g = 0);
 
-		virtual bool setDataFromTable(Table *, const QString&, const QString&, int = 1, int = -1);
+  virtual bool setDataFromTable(Table *, const QString &, const QString &,
+                                int = 1, int = -1);
 
-		//! Changes the data range if the source curve was already assigned. Provided for convenience.
-		void setInterval(double from, double to);
+  //! Changes the data range if the source curve was already assigned. Provided
+  // for convenience.
+  void setInterval(double from, double to);
 
-		//! Sets the tolerance used by the GSL routines
-		void setTolerance(double eps){d_tolerance = eps;};
+  //! Sets the tolerance used by the GSL routines
+  void setTolerance(double eps) { d_tolerance = eps; };
 
-		//! Sets the color of the output fit curve.
-		void setColor(int colorId){d_curveColorIndex = colorId;};
+  //! Sets the color of the output fit curve.
+  void setColor(int colorId) { d_curveColorIndex = colorId; };
 
-        //! Sets the color of the output fit curve. Provided for convenience. To be used in scripts only!
-        void setColor(const QString& colorName);
+  //! Sets the color of the output fit curve. Provided for convenience. To be
+  // used in scripts only!
+  void setColor(const QString &colorName);
 
-        //! Sets the number of points in the output curve
-        void setOutputPoints(int points){d_points = points;};
+  //! Sets the number of points in the output curve
+  void setOutputPoints(int points) { d_points = points; };
 
-        //! Sets the precision used for the output
-		void setOutputPrecision(int digits){d_prec = digits;};
+  //! Sets the precision used for the output
+  void setOutputPrecision(int digits) { d_prec = digits; };
 
-		//! Sets the maximum number of iterations to be performed during an iterative session
-		void setMaximumIterations(int iter){d_max_iterations = iter;};
+  //! Sets the maximum number of iterations to be performed during an iterative
+  // session
+  void setMaximumIterations(int iter) { d_max_iterations = iter; };
 
-		//! Adds a new legend to the plot. Calls virtual legendInfo()
-		virtual void showLegend();
+  //! Adds a new legend to the plot. Calls virtual legendInfo()
+  virtual void showLegend();
 
-        //! Output string added to the plot as a new legend
-		virtual QString legendInfo(){return QString();};
+  //! Output string added to the plot as a new legend
+  virtual QString legendInfo() { return QString(); };
 
-		//! Returns the size of the input data set
-		int dataSize(){return d_n;};
-        //! Returns the x values of the input data set
-		double* x(){return d_x;};
-		//! Returns the y values of the input data set
-		double* y(){return d_y;};
-		//! Returns a pointer to the table created to display the results
-        Table *resultTable(){return d_result_table;};
+  //! Returns the size of the input data set
+  int dataSize() { return d_n; };
+  //! Returns the x values of the input data set
+  double *x() { return d_x; };
+  //! Returns the y values of the input data set
+  double *y() { return d_y; };
+  //! Returns a pointer to the table created to display the results
+  Table *resultTable() { return d_result_table; };
 
-        bool error(){return d_init_err;};
+  bool error() { return d_init_err; };
 
-		virtual void enableGraphicsDisplay(bool on = true, Graph *g = 0);
+  virtual void enableGraphicsDisplay(bool on = true, Graph *g = 0);
 
-	protected:
-        void init();
+protected:
+  void init();
 
-        //! Sets x and y to the curve points between start and end. Memory will be allocated with new double[].
-  	    //! Returns the number of points within range == size of x and y arrays.
-  	    virtual int curveData(QwtPlotCurve *c, double start, double end, double **x, double **y);
-        //! Same as curveData, but sorts the points by their x value.
-        virtual int sortedCurveData(QwtPlotCurve *c, double start, double end, double **x, double **y);
+  //! Sets x and y to the curve points between start and end. Memory will be
+  // allocated with new double[].
+  //! Returns the number of points within range == size of x and y arrays.
+  virtual int curveData(QwtPlotCurve *c, double start, double end, double **x,
+                        double **y);
+  //! Same as curveData, but sorts the points by their x value.
+  virtual int sortedCurveData(QwtPlotCurve *c, double start, double end,
+                              double **x, double **y);
 
-		int curveRange(QwtPlotCurve *c, double start, double end, int *iStart, int *iEnd);
+  int curveRange(QwtPlotCurve *c, double start, double end, int *iStart,
+                 int *iEnd);
 
-        //! Adds the result curve to the target output plot window. Creates a hidden table and frees the input data from memory.
-        QwtPlotCurve* addResultCurve(double *x, double *y);
+  //! Adds the result curve to the target output plot window. Creates a hidden
+  // table and frees the input data from memory.
+  QwtPlotCurve *addResultCurve(double *x, double *y);
 
-        //! Performs checks and returns the index of the source data curve if OK, -1 otherwise
-        int curveIndex(const QString& curveTitle, Graph *g);
+  //! Performs checks and returns the index of the source data curve if OK, -1
+  // otherwise
+  int curveIndex(const QString &curveTitle, Graph *g);
 
-        //! Output string added to the log pannel of the application
-        virtual QString logInfo(){return QString();};
+  //! Output string added to the log pannel of the application
+  virtual QString logInfo() { return QString(); };
 
-		//! Performs the data analysis and takes care of the output
-		virtual void output();
+  //! Performs the data analysis and takes care of the output
+  virtual void output();
 
-		//! Calculates the data for the output curve and store it in the X an Y vectors
-		virtual void calculateOutputData(double *X, double *Y) { Q_UNUSED(X) Q_UNUSED(Y) };
+  //! Calculates the data for the output curve and store it in the X an Y
+  // vectors
+  virtual void calculateOutputData(double *X,
+                                   double *Y){Q_UNUSED(X) Q_UNUSED(Y)};
 
-		MultiLayer* createOutputGraph();
+  MultiLayer *createOutputGraph();
 
-		//! The source graph with the curve to be analyzed
-		Graph *d_graph;
+  //! The source graph with the curve to be analyzed
+  Graph *d_graph;
 
-		//! The graph where the result curve should be displayed
-		Graph *d_output_graph;
+  //! The graph where the result curve should be displayed
+  Graph *d_output_graph;
 
-        //! A table source of data
-		Table *d_table;
+  //! A table source of data
+  Table *d_table;
 
-        //! The table displaying the results of the filtering operation (not alvays valid!)
-        Table *d_result_table;
+  //! The table displaying the results of the filtering operation (not alvays
+  // valid!)
+  Table *d_result_table;
 
-		//! Size of the data arrays
-		int d_n;
+  //! Size of the data arrays
+  int d_n;
 
-		//! x data set to be analysed
-		double *d_x;
+  //! x data set to be analysed
+  double *d_x;
 
-		//! y data set to be analysed
-		double *d_y;
+  //! y data set to be analysed
+  double *d_y;
 
-		//! GSL Tolerance, if ever needed...
-		double d_tolerance;
+  //! GSL Tolerance, if ever needed...
+  double d_tolerance;
 
-		//! Number of result points to de calculated and displayed in the output curve
-		int d_points;
+  //! Number of result points to de calculated and displayed in the output curve
+  int d_points;
 
-		//! Color index of the result curve
-		int d_curveColorIndex;
+  //! Color index of the result curve
+  int d_curveColorIndex;
 
-		//! Maximum number of iterations per fit
-		int d_max_iterations;
+  //! Maximum number of iterations per fit
+  int d_max_iterations;
 
-		//! The curve to be analysed
-		QwtPlotCurve *d_curve;
+  //! The curve to be analysed
+  QwtPlotCurve *d_curve;
 
-		//! Precision (number of significant digits) used for the results output
-		int d_prec;
+  //! Precision (number of significant digits) used for the results output
+  int d_prec;
 
-		//! Error flag telling if something went wrong during the initialization phase.
-		bool d_init_err;
+  //! Error flag telling if something went wrong during the initialization
+  // phase.
+  bool d_init_err;
 
-        //! Data interval
-        double d_from, d_to;
+  //! Data interval
+  double d_from, d_to;
 
-        //! Specifies if the filter needs sorted data as input
-        bool d_sort_data;
+  //! Specifies if the filter needs sorted data as input
+  bool d_sort_data;
 
-        //! Minimum number of data points necessary to perform the operation
-        int d_min_points;
+  //! Minimum number of data points necessary to perform the operation
+  int d_min_points;
 
-        //! String explaining the operation in the comment of the result table and in the project explorer
-        QString d_explanation;
+  //! String explaining the operation in the comment of the result table and in
+  // the project explorer
+  QString d_explanation;
 
-		//! Specifies if the filter should display a result curve
-		bool d_graphics_display;
+  //! Specifies if the filter should display a result curve
+  bool d_graphics_display;
 
-		QString d_y_col_name;
+  QString d_y_col_name;
 };
 
 #endif
diff --git a/MantidPlot/src/FilterDialog.cpp b/MantidPlot/src/FilterDialog.cpp
index c5db27c063a5403a4eba0ef6dd3bc7ae3c3b26ae..fa1e0012c81a562b8e916ff03c9a6875784ec5ed 100644
--- a/MantidPlot/src/FilterDialog.cpp
+++ b/MantidPlot/src/FilterDialog.cpp
@@ -2,7 +2,8 @@
     File                 : FilterDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Filter options dialog
 
@@ -41,154 +42,139 @@
 #include <QLineEdit>
 #include <QComboBox>
 
-FilterDialog::FilterDialog(int type, QWidget* parent, Qt::WFlags 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"));
-    filter_type = type;
+FilterDialog::FilterDialog(int type, QWidget *parent, Qt::WFlags 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"));
+  filter_type = type;
 
-    setObjectName( "FilterDialog" );
+  setObjectName("FilterDialog");
 
-    QGroupBox *gb1 = new QGroupBox();
-    QGridLayout *gl1 = new QGridLayout(gb1);
-    gl1->addWidget(new QLabel(tr("Filter curve: ")), 0, 0);
+  QGroupBox *gb1 = new QGroupBox();
+  QGridLayout *gl1 = new QGridLayout(gb1);
+  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);
-
-    boxStart = new QLineEdit();
-    boxStart->setText(tr("0"));
-    gl1->addWidget(boxStart, 1, 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);
 
-    boxColor = new ColorBox();
-    boxColor->setColor(QColor(Qt::red));
-    if (type >= FFTFilter::BandPass)
-    {
-        gl1->addWidget(new QLabel(tr("High Frequency (Hz)")), 2, 0);
+  boxStart = new QLineEdit();
+  boxStart->setText(tr("0"));
+  gl1->addWidget(boxStart, 1, 1);
 
-        boxEnd = new QLineEdit();
-        boxEnd->setText(tr("0"));
-        gl1->addWidget(boxEnd, 2, 1);
+  boxColor = new ColorBox();
+  boxColor->setColor(QColor(Qt::red));
+  if (type >= FFTFilter::BandPass) {
+    gl1->addWidget(new QLabel(tr("High Frequency (Hz)")), 2, 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);
+    boxEnd = new QLineEdit();
+    boxEnd->setText(tr("0"));
+    gl1->addWidget(boxEnd, 2, 1);
 
-        boxOffset = new QCheckBox();
-        gl1->addWidget(boxOffset, 3, 1);
-
-        gl1->addWidget(new QLabel(tr("Color")), 4, 0);
-        gl1->addWidget(boxColor, 4, 1);
-        gl1->setRowStretch(5, 1);
-    }
+    if (type == FFTFilter::BandPass)
+      gl1->addWidget(new QLabel(tr("Add DC Offset")), 3, 0);
     else
-    {
-        gl1->addWidget(new QLabel(tr("Color")), 2, 0);
-        gl1->addWidget(boxColor, 2, 1);
-        gl1->setRowStretch(3, 1);
-    }
-
-    buttonFilter = new QPushButton(tr( "&Filter" ));
-    buttonFilter->setDefault( true );
-    buttonCancel = new QPushButton(tr( "&Close" ));
+      gl1->addWidget(new QLabel(tr("Substract DC Offset")), 3, 0);
+
+    boxOffset = new QCheckBox();
+    gl1->addWidget(boxOffset, 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("Color")), 2, 0);
+    gl1->addWidget(boxColor, 2, 1);
+    gl1->setRowStretch(3, 1);
+  }
+
+  buttonFilter = new QPushButton(tr("&Filter"));
+  buttonFilter->setDefault(true);
+  buttonCancel = new QPushButton(tr("&Close"));
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  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(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+}
 
-    QVBoxLayout *vl = new QVBoxLayout();
-    vl->addWidget(buttonFilter);
-    vl->addWidget(buttonCancel);
-    vl->addStretch();
+void FilterDialog::filter() {
+  double from = 0.0, to = 0.0;
+  try {
+    MyParser parser;
+    parser.SetExpr(boxStart->text().replace(",", ".").toAscii().constData());
+    from = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(this, tr("MantidPlot - Frequency input error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxStart->setFocus();
+    return;
+  }
+
+  if (from < 0) {
+    QMessageBox::critical(this, tr("MantidPlot - Frequency input error"),
+                          tr("Please enter positive frequency values!"));
+    boxStart->setFocus();
+    return;
+  }
+
+  if (filter_type >= FFTFilter::BandPass) {
+    try {
+      MyParser parser;
+      parser.SetExpr(boxEnd->text().replace(",", ".").toAscii().constData());
+      to = parser.Eval();
+    } catch (mu::ParserError &e) {
+      QMessageBox::critical(this, tr("MantidPlot - High Frequency input error"),
+                            QString::fromStdString(e.GetMsg()));
+      boxEnd->setFocus();
+      return;
+    }
 
-    QHBoxLayout *hb = new QHBoxLayout(this);
-    hb->addWidget(gb1);
-    hb->addLayout(vl);
+    if (to < 0) {
+      QMessageBox::critical(this, tr("MantidPlot - High Frequency input error"),
+                            tr("Please enter positive frequency values!"));
+      boxEnd->setFocus();
+      return;
+    }
 
-    connect( buttonFilter, SIGNAL( clicked() ), this, SLOT( filter() ) );
-    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-}
+    if (from >= to) {
+      QMessageBox::critical(
+          this, tr("MantidPlot - Frequency input error"),
+          tr("Please enter frequency limits that satisfy: Low < High !"));
+      boxEnd->setFocus();
+      return;
+    }
+  }
 
-void FilterDialog::filter()
-{
-double from = 0.0, to = 0.0;
-try
-	{
-	MyParser parser;
-	parser.SetExpr(boxStart->text().replace(",", ".").toAscii().constData());
-	from = parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(this, tr("MantidPlot - Frequency input error"), QString::fromStdString(e.GetMsg()));
-	boxStart->setFocus();
-	return;
-	}
-
-if (from < 0)
-		{
-		QMessageBox::critical(this, tr("MantidPlot - Frequency input error"),
-				tr("Please enter positive frequency values!"));
-		boxStart->setFocus();
-		return;
-		}
-
-if (filter_type >= FFTFilter::BandPass)
-	{
-	try
-		{
-		MyParser parser;
-		parser.SetExpr(boxEnd->text().replace(",", ".").toAscii().constData());
-		to=parser.Eval();
-		}
-	catch(mu::ParserError &e)
-		{
-		QMessageBox::critical(this, tr("MantidPlot - High Frequency input error"), QString::fromStdString(e.GetMsg()));
-		boxEnd->setFocus();
-		return;
-		}
-
-	if (to < 0)
-		{
-		QMessageBox::critical(this, tr("MantidPlot - High Frequency input error"),
-				tr("Please enter positive frequency values!"));
-		boxEnd->setFocus();
-		return;
-		}
-
-	if (from>=to)
-		{
-		QMessageBox::critical(this, tr("MantidPlot - Frequency input error"),
-				tr("Please enter frequency limits that satisfy: Low < High !"));
-		boxEnd->setFocus();
-		return;
-		}
-	}
-
-FFTFilter *f = new FFTFilter(dynamic_cast<ApplicationWindow *>(parent()), graph, boxName->currentText(), filter_type);
-if (filter_type == FFTFilter::BandPass)
-    {
+  FFTFilter *f = new FFTFilter(dynamic_cast<ApplicationWindow *>(parent()),
+                               graph, boxName->currentText(), filter_type);
+  if (filter_type == FFTFilter::BandPass) {
     f->setBand(from, to);
     f->enableOffset(boxOffset->isChecked());
-    }
-else if (filter_type == FFTFilter::BandBlock)
-    {
+  } else if (filter_type == FFTFilter::BandBlock) {
     f->setBand(from, to);
     f->enableOffset(!boxOffset->isChecked());
-    }
-else
+  } else
     f->setCutoff(from);
 
-f->setColor(boxColor->currentIndex());
-f->run();
-delete f;
+  f->setColor(boxColor->currentIndex());
+  f->run();
+  delete f;
 }
 
-void FilterDialog::setGraph(Graph *g)
-{
-graph = g;
-boxName->addItems (g->analysableCurvesList());
+void FilterDialog::setGraph(Graph *g) {
+  graph = g;
+  boxName->addItems(g->analysableCurvesList());
 }
diff --git a/MantidPlot/src/FilterDialog.h b/MantidPlot/src/FilterDialog.h
index a052988c7cb35d0be7dd2ec6c14acb6a4b1dc576..dda51142885b54f07eb5928d87ef76fcd9b1605e 100644
--- a/MantidPlot/src/FilterDialog.h
+++ b/MantidPlot/src/FilterDialog.h
@@ -2,7 +2,8 @@
     File                 : FilterDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Filter options dialog
 
@@ -39,31 +40,27 @@ class Graph;
 class ColorBox;
 
 //! Filter options dialog
-class FilterDialog : public QDialog
-{
-    Q_OBJECT
+class FilterDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    FilterDialog(int type, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  FilterDialog(int type, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void setGraph(Graph *g);
-	void filter();
+  void setGraph(Graph *g);
+  void filter();
 
 private:
-	Graph *graph;
-	int filter_type;
+  Graph *graph;
+  int filter_type;
 
-    QPushButton* buttonFilter;
-	QPushButton* buttonCancel;
-	QComboBox* boxName;
-	QCheckBox* boxOffset;
-	QLineEdit* boxStart;
-	QLineEdit* boxEnd;
-	ColorBox* boxColor;
+  QPushButton *buttonFilter;
+  QPushButton *buttonCancel;
+  QComboBox *boxName;
+  QCheckBox *boxOffset;
+  QLineEdit *boxStart;
+  QLineEdit *boxEnd;
+  ColorBox *boxColor;
 };
 
 #endif
-
-
-
diff --git a/MantidPlot/src/FindDialog.cpp b/MantidPlot/src/FindDialog.cpp
index 154f1cd14e6ecc88c266e9ec393add7d9a9761c2..7130fe5642a77d94f25d24b7da3f6a63a7a8217f 100644
--- a/MantidPlot/src/FindDialog.cpp
+++ b/MantidPlot/src/FindDialog.cpp
@@ -2,10 +2,11 @@
     File                 : FindDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Find dialog
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -40,113 +41,111 @@
 #include <QFrame>
 #include <QGroupBox>
 
-FindDialog::FindDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
-	setWindowTitle (tr("MantidPlot") + " - " + tr("Find"));
-	setSizeGripEnabled( true );
-
-	QGridLayout * topLayout = new QGridLayout();
-	QGridLayout * bottomLayout = new QGridLayout();
-	
-	topLayout->addWidget( new QLabel(tr( "Start From" )), 0, 0 );
-	labelStart = new QLabel();
-	labelStart->setFrameStyle(QFrame::Panel | QFrame::Sunken);
-	labelStart->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
-	topLayout->addWidget( labelStart, 0, 1, 1, 4 );
-
-	topLayout->addWidget( new QLabel(tr( "Find" )), 1, 0 );
-	boxFind = new QComboBox();
-	boxFind->setEditable(true);
-	boxFind->setDuplicatesEnabled(false);
-	boxFind->setInsertPolicy( QComboBox::InsertAtTop );
-	boxFind->setAutoCompletion(true);
-	boxFind->setMaxCount ( 10 );
-	boxFind->setMaxVisibleItems ( 10 );
-	boxFind->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
-	topLayout->addWidget( boxFind, 1, 1, 1, 4 );
-
-
-	QGroupBox * groupBox = new QGroupBox(tr("Search in"));
-	QVBoxLayout * groupBoxLayout = new QVBoxLayout( groupBox );
-
-	boxWindowNames = new QCheckBox(tr("&Window Names"));
-    boxWindowNames->setChecked(true);
-	groupBoxLayout->addWidget(boxWindowNames);
-	
-    boxWindowLabels = new QCheckBox(tr("Window &Labels"));
-    boxWindowLabels->setChecked( false );
-	groupBoxLayout->addWidget(boxWindowLabels);
-	
-    boxFolderNames = new QCheckBox(tr("Folder &Names"));
-    boxFolderNames->setChecked( false );
-	groupBoxLayout->addWidget(boxFolderNames);
-	
-	bottomLayout->addWidget( groupBox, 0, 0, 3, 1 );
-
-	boxCaseSensitive = new QCheckBox(tr("Case &Sensitive"));
-    boxCaseSensitive->setChecked(false);
-	bottomLayout->addWidget( boxCaseSensitive, 0, 1 );
-
-    boxPartialMatch = new QCheckBox(tr("&Partial Match Allowed"));
-    boxPartialMatch->setChecked(true);
-	bottomLayout->addWidget( boxPartialMatch, 1, 1 );
-	
-	boxSubfolders = new QCheckBox(tr("&Include Subfolders"));
-    boxSubfolders->setChecked(true);
-	bottomLayout->addWidget( boxSubfolders, 2, 1 );
-	
-	buttonFind = new QPushButton(tr("&Find"));
-    buttonFind->setDefault( true );
-	bottomLayout->addWidget( buttonFind, 0, 2 );
-   
-	buttonReset = new QPushButton(tr("&Update Start Path"));
-	bottomLayout->addWidget( buttonReset, 1, 2 );
-    buttonCancel = new QPushButton(tr("&Close"));
-	bottomLayout->addWidget( buttonCancel, 2, 2 );
-
-	QVBoxLayout* mainLayout = new QVBoxLayout(this);
-	mainLayout->addLayout(topLayout);
-	mainLayout->addLayout(bottomLayout);
-
-	setStartPath();
-   
-    // signals and slots connections
-    connect( buttonFind, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonReset, SIGNAL( clicked() ), this, SLOT( setStartPath() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+FindDialog::FindDialog(QWidget *parent, Qt::WFlags fl) : QDialog(parent, fl) {
+  setWindowTitle(tr("MantidPlot") + " - " + tr("Find"));
+  setSizeGripEnabled(true);
+
+  QGridLayout *topLayout = new QGridLayout();
+  QGridLayout *bottomLayout = new QGridLayout();
+
+  topLayout->addWidget(new QLabel(tr("Start From")), 0, 0);
+  labelStart = new QLabel();
+  labelStart->setFrameStyle(QFrame::Panel | QFrame::Sunken);
+  labelStart->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  topLayout->addWidget(labelStart, 0, 1, 1, 4);
+
+  topLayout->addWidget(new QLabel(tr("Find")), 1, 0);
+  boxFind = new QComboBox();
+  boxFind->setEditable(true);
+  boxFind->setDuplicatesEnabled(false);
+  boxFind->setInsertPolicy(QComboBox::InsertAtTop);
+  boxFind->setAutoCompletion(true);
+  boxFind->setMaxCount(10);
+  boxFind->setMaxVisibleItems(10);
+  boxFind->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  topLayout->addWidget(boxFind, 1, 1, 1, 4);
+
+  QGroupBox *groupBox = new QGroupBox(tr("Search in"));
+  QVBoxLayout *groupBoxLayout = new QVBoxLayout(groupBox);
+
+  boxWindowNames = new QCheckBox(tr("&Window Names"));
+  boxWindowNames->setChecked(true);
+  groupBoxLayout->addWidget(boxWindowNames);
+
+  boxWindowLabels = new QCheckBox(tr("Window &Labels"));
+  boxWindowLabels->setChecked(false);
+  groupBoxLayout->addWidget(boxWindowLabels);
+
+  boxFolderNames = new QCheckBox(tr("Folder &Names"));
+  boxFolderNames->setChecked(false);
+  groupBoxLayout->addWidget(boxFolderNames);
+
+  bottomLayout->addWidget(groupBox, 0, 0, 3, 1);
+
+  boxCaseSensitive = new QCheckBox(tr("Case &Sensitive"));
+  boxCaseSensitive->setChecked(false);
+  bottomLayout->addWidget(boxCaseSensitive, 0, 1);
+
+  boxPartialMatch = new QCheckBox(tr("&Partial Match Allowed"));
+  boxPartialMatch->setChecked(true);
+  bottomLayout->addWidget(boxPartialMatch, 1, 1);
+
+  boxSubfolders = new QCheckBox(tr("&Include Subfolders"));
+  boxSubfolders->setChecked(true);
+  bottomLayout->addWidget(boxSubfolders, 2, 1);
+
+  buttonFind = new QPushButton(tr("&Find"));
+  buttonFind->setDefault(true);
+  bottomLayout->addWidget(buttonFind, 0, 2);
+
+  buttonReset = new QPushButton(tr("&Update Start Path"));
+  bottomLayout->addWidget(buttonReset, 1, 2);
+  buttonCancel = new QPushButton(tr("&Close"));
+  bottomLayout->addWidget(buttonCancel, 2, 2);
+
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  mainLayout->addLayout(topLayout);
+  mainLayout->addLayout(bottomLayout);
+
+  setStartPath();
+
+  // signals and slots connections
+  connect(buttonFind, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonReset, SIGNAL(clicked()), this, SLOT(setStartPath()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void FindDialog::setStartPath()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+void FindDialog::setStartPath() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
   if (!app) {
-    throw std::logic_error("Parent of FindDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of FindDialog is not ApplicationWindow as expected.");
   }
-	labelStart->setText(app->currentFolder()->path());
+  labelStart->setText(app->currentFolder()->path());
 }
 
-void FindDialog::accept()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+void FindDialog::accept() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
   if (!app) {
-    throw std::logic_error("Parent of FindDialog is not ApplicationWindow as expected.");
+    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());
+  // add the combo box's current text to the list when the find button is
+  // pressed
+  QString text = boxFind->currentText();
+  if (!text.isEmpty()) {
+    if (boxFind->findText(text) == -1) // no duplicates
+    {
+      boxFind->insertItem(0, text);
+      boxFind->setCurrentIndex(0);
+    }
   }
-	app->find(boxFind->currentText(), boxWindowNames->isChecked(), boxWindowLabels->isChecked(),
-			boxFolderNames->isChecked(), boxCaseSensitive->isChecked(), boxPartialMatch->isChecked(),
-			boxSubfolders->isChecked());
-	// add the combo box's current text to the list when the find button is pressed
-	QString text = boxFind->currentText();
-	if(!text.isEmpty()) 
-	{
-		if(boxFind->findText(text) == -1) // no duplicates
-		{
-			boxFind->insertItem(0, text);
-			boxFind->setCurrentIndex(0);
-		}
-	}
 }
 
-FindDialog::~FindDialog()
-{
-}
+FindDialog::~FindDialog() {}
diff --git a/MantidPlot/src/FindDialog.h b/MantidPlot/src/FindDialog.h
index 973b0151eafed7905db327a84ee7cbe12a02a0eb..170a221d4f160d5ed1240cc5274bad2c76b7fd84 100644
--- a/MantidPlot/src/FindDialog.h
+++ b/MantidPlot/src/FindDialog.h
@@ -2,10 +2,11 @@
     File                 : FindDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Find dialog
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -38,34 +39,33 @@ class QComboBox;
 class QLabel;
 
 //! Find dialog
-class FindDialog : public QDialog
-{
-    Q_OBJECT
+class FindDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    FindDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
-    ~FindDialog() override;
+  FindDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
+  ~FindDialog() override;
 
 private:
-	QPushButton* buttonFind;
-	QPushButton* buttonCancel;
-	QPushButton* buttonReset;
+  QPushButton *buttonFind;
+  QPushButton *buttonCancel;
+  QPushButton *buttonReset;
 
-	QLabel *labelStart;
-	QComboBox* boxFind;
+  QLabel *labelStart;
+  QComboBox *boxFind;
 
-    QCheckBox* boxWindowNames;
-    QCheckBox* boxWindowLabels;
-	QCheckBox* boxFolderNames;
+  QCheckBox *boxWindowNames;
+  QCheckBox *boxWindowLabels;
+  QCheckBox *boxFolderNames;
 
-	QCheckBox* boxCaseSensitive;
-    QCheckBox* boxPartialMatch;
-	QCheckBox* boxSubfolders;
+  QCheckBox *boxCaseSensitive;
+  QCheckBox *boxPartialMatch;
+  QCheckBox *boxSubfolders;
 
 public slots:
 
-	//! Displays the project current folder path 
-	void setStartPath();
+  //! Displays the project current folder path
+  void setStartPath();
 
 protected slots:
 
diff --git a/MantidPlot/src/Fit.cpp b/MantidPlot/src/Fit.cpp
index 415a001110f3eb61bcfcfc748b5794d7a947b80a..c8ae5cbe8fbc510c57f4dc7f0b732b85fe8861cd 100644
--- a/MantidPlot/src/Fit.cpp
+++ b/MantidPlot/src/Fit.cpp
@@ -148,7 +148,7 @@ gsl_multifit_fdfsolver *Fit::fitGSL(gsl_multifit_function_fdf f,
   gsl_matrix *J = gsl_matrix_alloc(d_n, d_p);
   gsl_multifit_fdfsolver_jac(s, J);
   gsl_multifit_covar(J, 0.0, covar);
-  gsl_matrix_free (J);
+  gsl_matrix_free(J);
 #endif
   iterations = static_cast<int>(iter);
   return s;
@@ -475,7 +475,7 @@ bool Fit::setWeightingData(WeightingMethod w, const QString &colName) {
       d_w[i] = sqrt(d_y[i]);
   } break;
   case Dataset: // Dataset weighting
-  { // d_w are equal to the values of the arbitrary dataset
+  {             // d_w are equal to the values of the arbitrary dataset
     if (colName.isEmpty())
       return false;
 
@@ -484,10 +484,10 @@ bool Fit::setWeightingData(WeightingMethod w, const QString &colName) {
       return false;
 
     if (t->numRows() < d_n) {
-      QMessageBox::critical(app, tr("MantidPlot - Error"),
-                            tr("The column %1 has less points than the fitted "
-                               "data set. Please choose another column!.")
-                                .arg(colName));
+      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;
     }
 
@@ -619,8 +619,7 @@ void Fit::fit() {
   if (d_p > d_n) {
     QMessageBox::critical(app, tr("MantidPlot - Fit Error"),
                           tr("You need at least %1 data points for this fit "
-                             "operation. Operation aborted!")
-                              .arg(d_p));
+                             "operation. Operation aborted!").arg(d_p));
     return;
   }
   if (d_formula.isEmpty()) {
@@ -636,13 +635,8 @@ void Fit::fit() {
   QString names = d_param_names.join(",");
   const char *parNames = names.toAscii().constData();
 
-  struct FitData d_data = {static_cast<size_t>(d_n),
-                           static_cast<size_t>(d_p),
-                           d_x,
-                           d_y,
-                           d_w,
-                           function,
-                           parNames};
+  struct FitData d_data = {static_cast<size_t>(d_n), static_cast<size_t>(d_p),
+                           d_x, d_y, d_w, function, parNames};
 
   int status, iterations = d_max_iterations;
   if (d_solver == NelderMeadSimplex) {
@@ -740,8 +734,7 @@ bool Fit::save(const QString &fileName) {
     QMessageBox::critical(
         0, tr("MantidPlot") + " - " + tr("File Save Error"),
         tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
-           "you have the right to write to this location!")
-            .arg(fileName));
+           "you have the right to write to this location!").arg(fileName));
     return false;
   }
 
diff --git a/MantidPlot/src/Fit.h b/MantidPlot/src/Fit.h
index 57b7d624c6e5dbec5ba8aca723d1d444e1a5f843..23fa0ffa324a4b6d3aadfd7cf0c65a30cc4e95aa 100644
--- a/MantidPlot/src/Fit.h
+++ b/MantidPlot/src/Fit.h
@@ -41,202 +41,222 @@ class Table;
 class Matrix;
 
 //! Fit base class
-class Fit : public Filter
-{
-	Q_OBJECT
+class Fit : public Filter {
+  Q_OBJECT
 
-	public:
+public:
+  typedef double (*fit_function_simplex)(const gsl_vector *, void *);
+  typedef int (*fit_function)(const gsl_vector *, void *, gsl_vector *);
+  typedef int (*fit_function_df)(const gsl_vector *, void *, gsl_matrix *);
+  typedef int (*fit_function_fdf)(const gsl_vector *, void *, gsl_vector *,
+                                  gsl_matrix *);
 
-		typedef double (*fit_function_simplex)(const gsl_vector *, void *);
-		typedef int (*fit_function)(const gsl_vector *, void *, gsl_vector *);
-		typedef int (*fit_function_df)(const gsl_vector *, void *, gsl_matrix *);
-		typedef int (*fit_function_fdf)(const gsl_vector *, void *, gsl_vector *, gsl_matrix *);
+  enum Algorithm {
+    ScaledLevenbergMarquardt,
+    UnscaledLevenbergMarquardt,
+    NelderMeadSimplex
+  };
+  enum WeightingMethod { NoWeighting, Instrumental, Statistical, Dataset };
+  enum FitType { BuiltIn = 0, Plugin = 1, User = 2 };
 
-		enum Algorithm{ScaledLevenbergMarquardt, UnscaledLevenbergMarquardt, NelderMeadSimplex};
-		enum WeightingMethod{NoWeighting, Instrumental, Statistical, Dataset};
-        enum FitType{BuiltIn = 0, Plugin = 1, User = 2};
+  Fit(ApplicationWindow *parent, Graph *g = 0, const QString &name = QString());
+  Fit(ApplicationWindow *parent, Table *t, const QString &name = QString());
+  ~Fit() override;
 
-		Fit(ApplicationWindow *parent, Graph *g = 0, const QString& name = QString());
-		Fit(ApplicationWindow *parent, Table *t, const QString& name = QString());
-                ~Fit() override;
+  //! Actually does the fit. Should be reimplemented in derived classes.
+  virtual void fit();
+  bool run() override {
+    fit();
+    return true;
+  };
+
+  //! Sets the data set to be used for weighting
+  bool setWeightingData(WeightingMethod w,
+                        const QString &colName = QString::null);
+
+  void setDataCurve(int curve, double start, double end) override;
+  bool setDataFromTable(Table *t, const QString &xColName,
+                        const QString &yColName, int from = 1,
+                        int to = -1) override;
+
+  QString resultFormula() { return d_result_formula; };
+  QString formula() { return d_formula; };
+  virtual void setFormula(const QString &){};
+
+  int numParameters() { return d_p; };
+  QStringList parameterNames() { return d_param_names; };
+  virtual void setParametersList(const QStringList &){};
+  void setParameterExplanations(const QStringList &lst) {
+    d_param_explain = lst;
+  };
+
+  double initialGuess(int parIndex) {
+    return gsl_vector_get(d_param_init, parIndex);
+  };
+  void setInitialGuess(int parIndex, double val) {
+    gsl_vector_set(d_param_init, parIndex, val);
+  };
+  void setInitialGuesses(double *x_init);
+
+  virtual void guessInitialValues(){};
 
-                //! Actually does the fit. Should be reimplemented in derived classes.
-		virtual void fit();
-                bool run() override {
-                  fit();
-                  return true;
-                };
+  void setParameterRange(int parIndex, double left, double right);
+  void setAlgorithm(Algorithm s) { d_solver = s; };
 
-                //! Sets the data set to be used for weighting
-		bool setWeightingData(WeightingMethod w, const QString& colName = QString::null);
+  //! Specifies weather the result of the fit is a function curve
+  void generateFunction(bool yes, int points = 100);
 
-                void setDataCurve(int curve, double start, double end) override;
-                bool setDataFromTable(Table *t, const QString &xColName,
-                                      const QString &yColName, int from = 1,
-                                      int to = -1) override;
+  //! Output string added to the plot as a new legend
+  QString legendInfo() override;
+
+  //! Returns a vector with the fit results
+  double *results() { return d_results; };
 
-                QString resultFormula(){return d_result_formula;};
-		QString formula(){return d_formula;};
-		virtual void setFormula(const QString&){};
+  //! Returns a vector with the standard deviations of the results
+  double *errors();
 
-		int numParameters(){return d_p;};
-		QStringList parameterNames(){return d_param_names;};
-		virtual void setParametersList(const QStringList&){};
-        void setParameterExplanations(const QStringList& lst){d_param_explain = lst;};
+  //! Returns the sum of squares of the residuals from the best-fit line
+  double chiSquare() { return chi_2; };
 
-        double initialGuess(int parIndex){return gsl_vector_get(d_param_init, parIndex);};
-		void setInitialGuess(int parIndex, double val){gsl_vector_set(d_param_init, parIndex, val);};
-		void setInitialGuesses(double *x_init);
+  //! Returns R^2
+  double rSquare();
 
-		virtual void guessInitialValues(){};
+  //! Specifies wheather the errors must be scaled with sqrt(chi_2/dof)
+  void scaleErrors(bool yes = true) { d_scale_errors = yes; };
 
-		void setParameterRange(int parIndex, double left, double right);
-		void setAlgorithm(Algorithm s){d_solver = s;};
+  Table *parametersTable(const QString &tableName);
+  void writeParametersToTable(Table *t, bool append = false);
 
-		//! Specifies weather the result of the fit is a function curve
-		void generateFunction(bool yes, int points = 100);
+  Matrix *covarianceMatrix(const QString &matrixName);
 
-		//! Output string added to the plot as a new legend
-                QString legendInfo() override;
+  bool save(const QString &fileName);
+  bool load(const QString &fileName);
 
-                //! Returns a vector with the fit results
-		double* results(){return d_results;};
+  FitType type() { return d_fit_type; };
+  void setType(FitType t) { d_fit_type = t; };
 
-		//! Returns a vector with the standard deviations of the results
-		double* errors();
+  QString fileName() { return d_file_name; };
+  void setFileName(const QString &fn) { d_file_name = fn; };
 
-		//! Returns the sum of squares of the residuals from the best-fit line
-		double chiSquare() {return chi_2;};
+  //! Frees the memory allocated for the X and Y data sets
+  void freeMemory();
 
-		//! Returns R^2
-		double rSquare();
+  //! Calculates the data for the output fit curve
+  virtual double eval(double *, double) { return 0.0; };
 
-		//! Specifies wheather the errors must be scaled with sqrt(chi_2/dof)
-		void scaleErrors(bool yes = true){d_scale_errors = yes;};
+private:
+  void init();
 
-		Table* parametersTable(const QString& tableName);
-		void writeParametersToTable(Table *t, bool append = false);
+  //! Pointer to the GSL multifit minimizer (for simplex algorithm)
+  gsl_multimin_fminimizer *fitSimplex(gsl_multimin_function f, int &iterations,
+                                      int &status);
 
-		Matrix* covarianceMatrix(const QString& matrixName);
+  //! Pointer to the GSL multifit solver
+  gsl_multifit_fdfsolver *fitGSL(gsl_multifit_function_fdf f, int &iterations,
+                                 int &status);
 
-        bool save(const QString& fileName);
-        bool load(const QString& fileName);
+  //! Customs and stores the fit results according to the derived class
+  // specifications. Used by exponential fits.
+  virtual void customizeFitResults(){};
 
-        FitType type(){return d_fit_type;};
-        void setType(FitType t){d_fit_type = t;};
+protected:
+  //! Allocates the memory for the fit workspace
+  void initWorkspace(int par);
+  //! Frees the memory allocated for the fit workspace
+  void freeWorkspace();
+  //! Adds the result curve as a FunctionCurve to the plot, if d_gen_function =
+  // true
+  void insertFitFunctionCurve(const QString &name, double *x, double *y,
+                              int penWidth = 1);
 
-        QString fileName(){return d_file_name;};
-		void setFileName(const QString& fn){d_file_name = fn;};
+  //! Adds the result curve to the plot
+  virtual void generateFitCurve();
 
-        //! Frees the memory allocated for the X and Y data sets
-        void freeMemory();
+  //! Calculates the data for the output fit curve and store itin the X an Y
+  // vectors
+  virtual void calculateFitCurveData(double *X,
+                                     double *Y){Q_UNUSED(X) Q_UNUSED(Y)};
 
-        //! Calculates the data for the output fit curve
-        virtual double eval(double *, double){return 0.0;};
+  //! Output string added to the result log
+  virtual QString logFitInfo(int iterations, int status);
 
-	private:
-		void init();
+  fit_function d_f;
+  fit_function_df d_df;
+  fit_function_fdf d_fdf;
+  fit_function_simplex d_fsimplex;
 
-		//! Pointer to the GSL multifit minimizer (for simplex algorithm)
-		gsl_multimin_fminimizer * fitSimplex(gsl_multimin_function f, int &iterations, int &status);
+  //! Number of fit parameters
+  int d_p;
 
-		//! Pointer to the GSL multifit solver
-		gsl_multifit_fdfsolver * fitGSL(gsl_multifit_function_fdf f, int &iterations, int &status);
+  //! Initial guesses for the fit parameters
+  gsl_vector *d_param_init;
 
-		//! Customs and stores the fit results according to the derived class specifications. Used by exponential fits.
-		virtual void customizeFitResults(){};
+  /** \brief Tells whether the fitter uses non-linear/simplex fitting
+   * with an initial parameters set, that must be freed in the destructor.
+   */
+  bool is_non_linear;
 
-	protected:
-		//! Allocates the memory for the fit workspace
-		void initWorkspace(int par);
-		//! Frees the memory allocated for the fit workspace
-		void freeWorkspace();
-		//! Adds the result curve as a FunctionCurve to the plot, if d_gen_function = true
-		void insertFitFunctionCurve(const QString& name, double *x, double *y, int penWidth = 1);
+  //! weighting data set used for the fit
+  double *d_w;
 
-		//! Adds the result curve to the plot
-		virtual void generateFitCurve();
+  //! Names of the fit parameters
+  QStringList d_param_names;
 
-        //! Calculates the data for the output fit curve and store itin the X an Y vectors
-		virtual void calculateFitCurveData(double *X, double *Y) {Q_UNUSED(X) Q_UNUSED(Y)};
+  //! Stores a list of short explanations for the significance of the fit
+  // parameters
+  QStringList d_param_explain;
 
-		//! Output string added to the result log
-		virtual QString logFitInfo(int iterations, int status);
+  //! Specifies weather the result curve is a FunctionCurve or a normal curve
+  // with the same x values as the fit data
+  bool d_gen_function;
 
-		fit_function d_f;
-		fit_function_df d_df;
-		fit_function_fdf d_fdf;
-		fit_function_simplex d_fsimplex;
+  //! Algorithm type
+  Algorithm d_solver;
 
-		//! Number of fit parameters
-		int d_p;
+  //! The fit formula given on input
+  QString d_formula;
 
-		//! Initial guesses for the fit parameters
-		gsl_vector *d_param_init;
+  //! The result fit formula, where the fit parameters are replaced with the
+  // calculated values.
+  QString d_result_formula;
 
-		/** \brief Tells whether the fitter uses non-linear/simplex fitting
-		 * with an initial parameters set, that must be freed in the destructor.
-		 */
-		bool is_non_linear;
+  //! Covariance matrix
+  gsl_matrix *covar;
 
-		//! weighting data set used for the fit
-		double *d_w;
+  //! The kind of weighting to be performed on the data
+  WeightingMethod d_weighting;
 
-		//! Names of the fit parameters
-		QStringList d_param_names;
+  //! The name of the weighting dataset
+  QString weighting_dataset;
 
-		//! Stores a list of short explanations for the significance of the fit parameters
-		QStringList d_param_explain;
+  //! Stores the result parameters
+  double *d_results;
 
-		//! Specifies weather the result curve is a FunctionCurve or a normal curve with the same x values as the fit data
-		bool d_gen_function;
+  //! Stores standard deviations of the result parameters
+  double *d_errors;
 
-		//! Algorithm type
-		Algorithm d_solver;
+  //! The sum of squares of the residuals from the best-fit line
+  double chi_2;
 
-		//! The fit formula given on input
-		QString d_formula;
+  //! Specifies wheather the errors must be scaled with sqrt(chi_2/dof)
+  bool d_scale_errors;
 
-		//! The result fit formula, where the fit parameters are replaced with the calculated values.
-		QString d_result_formula;
+  //! Table window used for the output of fit parameters
+  Table *d_param_table;
 
-		//! Covariance matrix
-		gsl_matrix *covar;
+  //! Matrix window used for the output of covariance matrix
+  Matrix *d_cov_matrix;
 
-		//! The kind of weighting to be performed on the data
-		WeightingMethod d_weighting;
+  FitType d_fit_type;
 
-		//! The name of the weighting dataset
-		QString weighting_dataset;
+  //! Path of the XML file where the user stores the fit model
+  QString d_file_name;
 
-		//! Stores the result parameters
-		double *d_results;
+  //! Stores the left limits of the research interval for the result parameters
+  double *d_param_range_left;
 
-		//! Stores standard deviations of the result parameters
-		double *d_errors;
-
-		//! The sum of squares of the residuals from the best-fit line
-		double chi_2;
-
-		//! Specifies wheather the errors must be scaled with sqrt(chi_2/dof)
-		bool d_scale_errors;
-
-		//! Table window used for the output of fit parameters
-		Table *d_param_table;
-
-		//! Matrix window used for the output of covariance matrix
-		Matrix *d_cov_matrix;
-
-		FitType d_fit_type;
-
-		//! Path of the XML file where the user stores the fit model
-        QString d_file_name;
-
-		//! Stores the left limits of the research interval for the result parameters
-		double *d_param_range_left;
-
-		//! Stores the right limits of the research interval for the result parameters
-		double *d_param_range_right;
+  //! Stores the right limits of the research interval for the result parameters
+  double *d_param_range_right;
 };
 
 #endif
diff --git a/MantidPlot/src/FitDialog.cpp b/MantidPlot/src/FitDialog.cpp
index 8025227c5057e0ce518375d66c89aca7aa37041d..3df097393b93886801814ecf9663323cf6b5fbaa 100644
--- a/MantidPlot/src/FitDialog.cpp
+++ b/MantidPlot/src/FitDialog.cpp
@@ -66,412 +66,427 @@
 
 #include "MantidQtAPI/FileDialogHandler.h"
 
+FitDialog::FitDialog(Graph *g, QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setObjectName("FitDialog");
+  setWindowTitle(tr("MantidPlot - Fit Wizard"));
+  setSizeGripEnabled(true);
 
-FitDialog::FitDialog(Graph *g, QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
-{
-    setObjectName("FitDialog");
-	setWindowTitle(tr("MantidPlot - Fit Wizard"));
-	setSizeGripEnabled(true);
+  d_param_table = 0;
+  d_current_fit = 0;
+  d_preview_curve = 0;
 
-	d_param_table = 0;
-	d_current_fit = 0;
-	d_preview_curve = 0;
+  tw = new QStackedWidget();
 
-	tw = new QStackedWidget();
+  initEditPage();
+  initFitPage();
+  initAdvancedPage();
 
-	initEditPage();
-	initFitPage();
-	initAdvancedPage();
+  QVBoxLayout *vl = new QVBoxLayout();
+  vl->addWidget(tw);
+  setLayout(vl);
 
-	QVBoxLayout* vl = new QVBoxLayout();
-	vl->addWidget(tw);
-    setLayout(vl);
+  categoryBox->setCurrentRow(2);
+  funcBox->setCurrentRow(0);
 
-	categoryBox->setCurrentRow (2);
-	funcBox->setCurrentRow (0);
-
-	setGraph(g);
-	initBuiltInFunctions();
-    loadPlugins();
-    loadUserFunctions();
+  setGraph(g);
+  initBuiltInFunctions();
+  loadPlugins();
+  loadUserFunctions();
 }
 
-void FitDialog::initFitPage()
-{
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-    if (!app) {
-      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
-    }
+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);
-	boxCurve = new QComboBox();
-    gl1->addWidget(boxCurve, 0, 1);
-    gl1->addWidget(new QLabel(tr("Function")), 1, 0);
-	lblFunction = new QLabel();
-    gl1->addWidget(lblFunction, 1, 1);
-	boxFunction = new QTextEdit();
-	boxFunction->setReadOnly(true);
-    QPalette palette = boxFunction->palette();
-    palette.setColor(QPalette::Active, QPalette::Base, Qt::lightGray);
-    boxFunction->setPalette(palette);
-	boxFunction->setMaximumHeight(50);
-    gl1->addWidget(boxFunction, 2, 1);
-
-    QVBoxLayout *vb = new QVBoxLayout();
-    vb->addWidget(new QLabel(tr("Initial guesses")));
-    btnSaveGuesses = new QPushButton(tr( "&Save" ));
-    connect(btnSaveGuesses, SIGNAL(clicked()), this, SLOT(saveInitialGuesses()));
-    vb->addWidget(btnSaveGuesses);
-    btnParamRange = new QPushButton();
-    btnParamRange->setIcon(QIcon(getQPixmap("param_range_btn_xpm")));
-    btnParamRange->setCheckable(true);
-    connect(btnParamRange, SIGNAL(toggled(bool)), this, SLOT(showParameterRange(bool)));
-    vb->addWidget(btnParamRange);
-    previewBox = new QCheckBox(tr("&Preview"));
-    connect(previewBox, SIGNAL(stateChanged(int)), this, SLOT(updatePreview()));
-    vb->addWidget(previewBox);
-    vb->addStretch();
-	gl1->addLayout(vb, 3, 0);
-
-	boxParams = new QTableWidget();
-    boxParams->setColumnCount(5);
-    boxParams->horizontalHeader()->setClickable(false);
-    boxParams->horizontalHeader()->setResizeMode (0, QHeaderView::ResizeToContents);
-	boxParams->horizontalHeader()->setResizeMode (1, QHeaderView::Stretch);
-    boxParams->horizontalHeader()->setResizeMode (2, QHeaderView::Stretch);
-    boxParams->horizontalHeader()->setResizeMode (3, QHeaderView::Stretch);
-	boxParams->horizontalHeader()->setResizeMode (4, QHeaderView::ResizeToContents);
-    QStringList header = QStringList() << tr("Parameter") << tr("From") << tr("Value") << tr("To") << tr("Constant");
-    boxParams->setHorizontalHeaderLabels(header);
-    boxParams->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
-    boxParams->verticalHeader()->hide();
-    boxParams->hideColumn(1);
-    boxParams->hideColumn(3);
-    gl1->addWidget(boxParams, 3, 1);
-
-	gl1->addWidget(new QLabel( tr("Algorithm")), 4, 0 );
-	boxAlgorithm = new QComboBox();
-	boxAlgorithm->addItem(tr("Scaled Levenberg-Marquardt"));
-	boxAlgorithm->addItem(tr("Unscaled Levenberg-Marquardt"));
-	boxAlgorithm->addItem(tr("Nelder-Mead Simplex"));
-    gl1->addWidget(boxAlgorithm, 4, 1);
-
-	gl1->addWidget(new QLabel( tr("Color")), 5, 0);
-	boxColor = new ColorBox();
-	boxColor->setColor(QColor(Qt::red));
-    gl1->addWidget(boxColor, 5, 1);
-
-    QGroupBox *gb1 = new QGroupBox();
-    gb1->setLayout(gl1);
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel(tr("From x=")), 0, 0);
-
-	boxFrom = new DoubleSpinBox();
-//    boxFrom->setLocale(app->locale());
-    boxFrom->setDecimals(app->d_decimal_digits);
-    connect(boxFrom, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
-    gl2->addWidget(boxFrom, 0, 1);
-
-	gl2->addWidget(new QLabel( tr("To x=")), 1, 0);
-
-	boxTo = new DoubleSpinBox();
-//    boxTo->setLocale(app->locale());
-    boxTo->setDecimals(app->d_decimal_digits);
-    connect(boxTo, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
-    gl2->addWidget(boxTo, 1, 1);
-
-    QGroupBox *gb2 = new QGroupBox();
-    gb2->setLayout(gl2);
-
-    QGridLayout *gl3 = new QGridLayout();
-    gl3->addWidget(new QLabel(tr("Iterations")), 0, 0);
-	boxPoints = new QSpinBox();
-    boxPoints->setRange(10, 10000);
-	boxPoints->setSingleStep(50);
-	boxPoints->setValue(1000);
-    gl3->addWidget(boxPoints, 0, 1);
-	gl3->addWidget(new QLabel( tr("Tolerance")), 1, 0);
-
-	boxTolerance = new DoubleSpinBox();
-	boxTolerance->setRange(0.0, 1.0);
-	boxTolerance->setSingleStep(1e-4);
-//    boxTolerance->setLocale(app->locale());
-    boxTolerance->setDecimals(13);
-    boxTolerance->setValue(1e-4);
-	gl3->addWidget(boxTolerance, 1, 1);
-
-    QGroupBox *gb3 = new QGroupBox();
-    gb3->setLayout(gl3);
-
-    QHBoxLayout *hbox1 = new QHBoxLayout();
-    hbox1->addWidget(gb2);
-    hbox1->addWidget(gb3);
-
-    QHBoxLayout *hbox2 = new QHBoxLayout();
-	hbox2->addWidget(new QLabel(tr( "Weighting Method" )));
-	boxWeighting = new QComboBox();
-	boxWeighting->addItem(tr("No weighting"));
-	boxWeighting->addItem(tr("Instrumental"));
-	boxWeighting->addItem(tr("Statistical"));
-	boxWeighting->addItem(tr("Arbitrary Dataset"));
-    hbox2->addWidget(boxWeighting);
-    QGroupBox *gb4 = new QGroupBox();
-    gb4->setLayout(hbox2);
-
-	tableNamesBox = new QComboBox();
-	tableNamesBox->setEnabled(false);
-    hbox2->addWidget(tableNamesBox);
-	colNamesBox = new QComboBox();
-	colNamesBox->setEnabled(false);
-    hbox2->addWidget(colNamesBox);
-
-    QHBoxLayout *hbox3 = new QHBoxLayout();
-	buttonEdit = new QPushButton(tr( "<< &Edit function" ) );
-    hbox3->addWidget(buttonEdit);
-	btnDeleteFitCurves = new QPushButton(tr( "&Delete Fit Curves" ));
-    hbox3->addWidget(btnDeleteFitCurves);
-	buttonOk = new QPushButton(tr( "&Fit" ) );
-	buttonOk->setDefault( true );
-    hbox3->addWidget(buttonOk);
-	buttonCancel1 = new QPushButton(tr( "&Close" ));
-    hbox3->addWidget(buttonCancel1);
-	buttonAdvanced = new QPushButton(tr( "Custom &Output >>" ));
-    hbox3->addWidget(buttonAdvanced);
-    hbox3->addStretch();
-
-    QVBoxLayout *vbox1 = new QVBoxLayout();
-    vbox1->addWidget(gb1);
-    vbox1->addLayout(hbox1);
-    vbox1->addWidget(gb4);
-    vbox1->addLayout(hbox3);
-
-    fitPage = new QWidget();
-    fitPage->setLayout(vbox1);
-    tw->addWidget(fitPage);
-
-	connect( boxCurve, SIGNAL( activated(const QString&) ), this, SLOT( activateCurve(const QString&) ) );
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT(accept()));
-	connect( buttonCancel1, SIGNAL( clicked() ), this, SLOT(close()));
-	connect( buttonEdit, SIGNAL( clicked() ), this, SLOT(showEditPage()));
-	connect( btnDeleteFitCurves, SIGNAL( clicked() ), this, SLOT(deleteFitCurves()));
-	connect( boxWeighting, SIGNAL( activated(int) ), this, SLOT( enableWeightingParameters(int) ) );
-	connect( buttonAdvanced, SIGNAL(clicked()), this, SLOT(showAdvancedPage() ) );
-    connect( tableNamesBox, SIGNAL( activated(int) ), this, SLOT( selectSrcTable(int) ) );
-
-	setFocusProxy(boxFunction);
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
+  boxCurve = new QComboBox();
+  gl1->addWidget(boxCurve, 0, 1);
+  gl1->addWidget(new QLabel(tr("Function")), 1, 0);
+  lblFunction = new QLabel();
+  gl1->addWidget(lblFunction, 1, 1);
+  boxFunction = new QTextEdit();
+  boxFunction->setReadOnly(true);
+  QPalette palette = boxFunction->palette();
+  palette.setColor(QPalette::Active, QPalette::Base, Qt::lightGray);
+  boxFunction->setPalette(palette);
+  boxFunction->setMaximumHeight(50);
+  gl1->addWidget(boxFunction, 2, 1);
+
+  QVBoxLayout *vb = new QVBoxLayout();
+  vb->addWidget(new QLabel(tr("Initial guesses")));
+  btnSaveGuesses = new QPushButton(tr("&Save"));
+  connect(btnSaveGuesses, SIGNAL(clicked()), this, SLOT(saveInitialGuesses()));
+  vb->addWidget(btnSaveGuesses);
+  btnParamRange = new QPushButton();
+  btnParamRange->setIcon(QIcon(getQPixmap("param_range_btn_xpm")));
+  btnParamRange->setCheckable(true);
+  connect(btnParamRange, SIGNAL(toggled(bool)), this,
+          SLOT(showParameterRange(bool)));
+  vb->addWidget(btnParamRange);
+  previewBox = new QCheckBox(tr("&Preview"));
+  connect(previewBox, SIGNAL(stateChanged(int)), this, SLOT(updatePreview()));
+  vb->addWidget(previewBox);
+  vb->addStretch();
+  gl1->addLayout(vb, 3, 0);
+
+  boxParams = new QTableWidget();
+  boxParams->setColumnCount(5);
+  boxParams->horizontalHeader()->setClickable(false);
+  boxParams->horizontalHeader()->setResizeMode(0,
+                                               QHeaderView::ResizeToContents);
+  boxParams->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
+  boxParams->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);
+  boxParams->horizontalHeader()->setResizeMode(3, QHeaderView::Stretch);
+  boxParams->horizontalHeader()->setResizeMode(4,
+                                               QHeaderView::ResizeToContents);
+  QStringList header = QStringList() << tr("Parameter") << tr("From")
+                                     << tr("Value") << tr("To")
+                                     << tr("Constant");
+  boxParams->setHorizontalHeaderLabels(header);
+  boxParams->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
+  boxParams->verticalHeader()->hide();
+  boxParams->hideColumn(1);
+  boxParams->hideColumn(3);
+  gl1->addWidget(boxParams, 3, 1);
+
+  gl1->addWidget(new QLabel(tr("Algorithm")), 4, 0);
+  boxAlgorithm = new QComboBox();
+  boxAlgorithm->addItem(tr("Scaled Levenberg-Marquardt"));
+  boxAlgorithm->addItem(tr("Unscaled Levenberg-Marquardt"));
+  boxAlgorithm->addItem(tr("Nelder-Mead Simplex"));
+  gl1->addWidget(boxAlgorithm, 4, 1);
+
+  gl1->addWidget(new QLabel(tr("Color")), 5, 0);
+  boxColor = new ColorBox();
+  boxColor->setColor(QColor(Qt::red));
+  gl1->addWidget(boxColor, 5, 1);
+
+  QGroupBox *gb1 = new QGroupBox();
+  gb1->setLayout(gl1);
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("From x=")), 0, 0);
+
+  boxFrom = new DoubleSpinBox();
+  //    boxFrom->setLocale(app->locale());
+  boxFrom->setDecimals(app->d_decimal_digits);
+  connect(boxFrom, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
+  gl2->addWidget(boxFrom, 0, 1);
+
+  gl2->addWidget(new QLabel(tr("To x=")), 1, 0);
+
+  boxTo = new DoubleSpinBox();
+  //    boxTo->setLocale(app->locale());
+  boxTo->setDecimals(app->d_decimal_digits);
+  connect(boxTo, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
+  gl2->addWidget(boxTo, 1, 1);
+
+  QGroupBox *gb2 = new QGroupBox();
+  gb2->setLayout(gl2);
+
+  QGridLayout *gl3 = new QGridLayout();
+  gl3->addWidget(new QLabel(tr("Iterations")), 0, 0);
+  boxPoints = new QSpinBox();
+  boxPoints->setRange(10, 10000);
+  boxPoints->setSingleStep(50);
+  boxPoints->setValue(1000);
+  gl3->addWidget(boxPoints, 0, 1);
+  gl3->addWidget(new QLabel(tr("Tolerance")), 1, 0);
+
+  boxTolerance = new DoubleSpinBox();
+  boxTolerance->setRange(0.0, 1.0);
+  boxTolerance->setSingleStep(1e-4);
+  //    boxTolerance->setLocale(app->locale());
+  boxTolerance->setDecimals(13);
+  boxTolerance->setValue(1e-4);
+  gl3->addWidget(boxTolerance, 1, 1);
+
+  QGroupBox *gb3 = new QGroupBox();
+  gb3->setLayout(gl3);
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->addWidget(gb2);
+  hbox1->addWidget(gb3);
+
+  QHBoxLayout *hbox2 = new QHBoxLayout();
+  hbox2->addWidget(new QLabel(tr("Weighting Method")));
+  boxWeighting = new QComboBox();
+  boxWeighting->addItem(tr("No weighting"));
+  boxWeighting->addItem(tr("Instrumental"));
+  boxWeighting->addItem(tr("Statistical"));
+  boxWeighting->addItem(tr("Arbitrary Dataset"));
+  hbox2->addWidget(boxWeighting);
+  QGroupBox *gb4 = new QGroupBox();
+  gb4->setLayout(hbox2);
+
+  tableNamesBox = new QComboBox();
+  tableNamesBox->setEnabled(false);
+  hbox2->addWidget(tableNamesBox);
+  colNamesBox = new QComboBox();
+  colNamesBox->setEnabled(false);
+  hbox2->addWidget(colNamesBox);
+
+  QHBoxLayout *hbox3 = new QHBoxLayout();
+  buttonEdit = new QPushButton(tr("<< &Edit function"));
+  hbox3->addWidget(buttonEdit);
+  btnDeleteFitCurves = new QPushButton(tr("&Delete Fit Curves"));
+  hbox3->addWidget(btnDeleteFitCurves);
+  buttonOk = new QPushButton(tr("&Fit"));
+  buttonOk->setDefault(true);
+  hbox3->addWidget(buttonOk);
+  buttonCancel1 = new QPushButton(tr("&Close"));
+  hbox3->addWidget(buttonCancel1);
+  buttonAdvanced = new QPushButton(tr("Custom &Output >>"));
+  hbox3->addWidget(buttonAdvanced);
+  hbox3->addStretch();
+
+  QVBoxLayout *vbox1 = new QVBoxLayout();
+  vbox1->addWidget(gb1);
+  vbox1->addLayout(hbox1);
+  vbox1->addWidget(gb4);
+  vbox1->addLayout(hbox3);
+
+  fitPage = new QWidget();
+  fitPage->setLayout(vbox1);
+  tw->addWidget(fitPage);
+
+  connect(boxCurve, SIGNAL(activated(const QString &)), this,
+          SLOT(activateCurve(const QString &)));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel1, SIGNAL(clicked()), this, SLOT(close()));
+  connect(buttonEdit, SIGNAL(clicked()), this, SLOT(showEditPage()));
+  connect(btnDeleteFitCurves, SIGNAL(clicked()), this, SLOT(deleteFitCurves()));
+  connect(boxWeighting, SIGNAL(activated(int)), this,
+          SLOT(enableWeightingParameters(int)));
+  connect(buttonAdvanced, SIGNAL(clicked()), this, SLOT(showAdvancedPage()));
+  connect(tableNamesBox, SIGNAL(activated(int)), this,
+          SLOT(selectSrcTable(int)));
+
+  setFocusProxy(boxFunction);
 }
 
-void FitDialog::initEditPage()
-{
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel(tr("Category")), 0, 0);
-    gl1->addWidget(new QLabel(tr("Function")), 0, 1);
-    gl1->addWidget(new QLabel(tr("Expression")), 0, 2);
-
-	categoryBox = new QListWidget();
-	categoryBox->addItem(tr("User defined"));
-	categoryBox->addItem(tr("Built-in"));
-	categoryBox->addItem(tr("Basic"));
-	categoryBox->addItem(tr("Plugins"));
-
-    gl1->addWidget(categoryBox, 1, 0);
-	funcBox = new QListWidget();
-    gl1->addWidget(funcBox, 1, 1);
-	explainBox = new QTextEdit();
-	explainBox->setReadOnly(true);
-    gl1->addWidget(explainBox, 1, 2);
-
-	boxUseBuiltIn = new QCheckBox(tr("Fit with &built-in function"));
-	boxUseBuiltIn->hide();
-
-    QHBoxLayout *hbox1 = new QHBoxLayout();
-	hbox1->addWidget(boxUseBuiltIn);
-    hbox1->addStretch();
-
-	polynomOrderLabel = new QLabel( tr("Polynomial Order"));
-	polynomOrderLabel->hide();
-    hbox1->addWidget(polynomOrderLabel);
-
-	polynomOrderBox = new QSpinBox();
-    polynomOrderBox->setMinimum(1);
-	polynomOrderBox->setValue(1);
-	polynomOrderBox->hide();
-	connect(polynomOrderBox, SIGNAL(valueChanged(int)), this, SLOT(setNumPeaks(int)));
-    hbox1->addWidget(polynomOrderBox);
-
-	buttonPlugins = new QPushButton(tr( "Choose plug&ins folder..." ) );
-    hbox1->addWidget(buttonPlugins);
-	buttonPlugins->hide();
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel(tr("Name")), 0, 0);
-	boxName = new QLineEdit(tr("user1"));
-    gl2->addWidget(boxName, 0, 1);
-	btnAddFunc = new QPushButton(tr( "&Save" ));
-    gl2->addWidget(btnAddFunc, 0, 2);
-    gl2->addWidget(new QLabel(tr("Parameters")), 1, 0);
-	boxParam = new QLineEdit("a, b");
-    gl2->addWidget(boxParam, 1, 1);
-	btnDelFunc = new QPushButton( tr( "&Remove" ));
-    gl2->addWidget(btnDelFunc, 1, 2);
-
-    QGroupBox *gb = new QGroupBox();
-    gb->setLayout(gl2);
-
-	editBox = new QTextEdit();
-	//editBox->setTextFormat(Qt::PlainText);
-	editBox->setFocus();
-
-    QVBoxLayout *vbox1 = new QVBoxLayout();
-	btnAddTxt = new QPushButton(tr( "Add &expression" ) );
-    vbox1->addWidget(btnAddTxt);
-	btnAddName = new QPushButton(tr( "Add &name" ));
-    vbox1->addWidget(btnAddName);
-	buttonClear = new QPushButton(tr( "Rese&t" ));
-    vbox1->addWidget(buttonClear);
-	buttonCancel2 = new QPushButton(tr( "&Close" ));
-    vbox1->addWidget(buttonCancel2);
-    btnContinue = new QPushButton(tr( "&Fit >>" ));
-    vbox1->addWidget(btnContinue);
-    vbox1->addStretch();
-
-    QHBoxLayout *hbox2 = new QHBoxLayout();
-	hbox2->addWidget(editBox);
-    hbox2->addLayout(vbox1);
-
-    QVBoxLayout *vbox2 = new QVBoxLayout();
-    vbox2->addLayout(gl1);
-    vbox2->addLayout(hbox1);
-    vbox2->addWidget(gb);
-    vbox2->addLayout(hbox2);
-
-    editPage = new QWidget();
-    editPage->setLayout(vbox2);
-    tw->addWidget(editPage);
-
-	connect( buttonPlugins, SIGNAL(clicked()), this, SLOT(chooseFolder()));
-    connect( buttonClear, SIGNAL(clicked()), this, SLOT(resetFunction()));
-	connect( categoryBox, SIGNAL(currentRowChanged (int)), this, SLOT(showFunctionsList(int)));
-	connect( funcBox, SIGNAL(currentRowChanged(int)), this, SLOT(showExpression(int)));
-	connect( boxUseBuiltIn, SIGNAL(toggled(bool)), this, SLOT(setFunction(bool)));
-	connect( btnAddName, SIGNAL(clicked()), this, SLOT(addFunctionName()));
-	connect( btnAddTxt, SIGNAL(clicked()), this, SLOT(addFunction()));
-	connect( btnContinue, SIGNAL(clicked()), this, SLOT(showFitPage()));
-	connect( btnAddFunc, SIGNAL(clicked()), this, SLOT(saveUserFunction()));
-	connect( btnDelFunc, SIGNAL(clicked()), this, SLOT(removeUserFunction()));
-	connect( buttonCancel2, SIGNAL(clicked()), this, SLOT(close()));
+void FitDialog::initEditPage() {
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Category")), 0, 0);
+  gl1->addWidget(new QLabel(tr("Function")), 0, 1);
+  gl1->addWidget(new QLabel(tr("Expression")), 0, 2);
+
+  categoryBox = new QListWidget();
+  categoryBox->addItem(tr("User defined"));
+  categoryBox->addItem(tr("Built-in"));
+  categoryBox->addItem(tr("Basic"));
+  categoryBox->addItem(tr("Plugins"));
+
+  gl1->addWidget(categoryBox, 1, 0);
+  funcBox = new QListWidget();
+  gl1->addWidget(funcBox, 1, 1);
+  explainBox = new QTextEdit();
+  explainBox->setReadOnly(true);
+  gl1->addWidget(explainBox, 1, 2);
+
+  boxUseBuiltIn = new QCheckBox(tr("Fit with &built-in function"));
+  boxUseBuiltIn->hide();
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->addWidget(boxUseBuiltIn);
+  hbox1->addStretch();
+
+  polynomOrderLabel = new QLabel(tr("Polynomial Order"));
+  polynomOrderLabel->hide();
+  hbox1->addWidget(polynomOrderLabel);
+
+  polynomOrderBox = new QSpinBox();
+  polynomOrderBox->setMinimum(1);
+  polynomOrderBox->setValue(1);
+  polynomOrderBox->hide();
+  connect(polynomOrderBox, SIGNAL(valueChanged(int)), this,
+          SLOT(setNumPeaks(int)));
+  hbox1->addWidget(polynomOrderBox);
+
+  buttonPlugins = new QPushButton(tr("Choose plug&ins folder..."));
+  hbox1->addWidget(buttonPlugins);
+  buttonPlugins->hide();
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("Name")), 0, 0);
+  boxName = new QLineEdit(tr("user1"));
+  gl2->addWidget(boxName, 0, 1);
+  btnAddFunc = new QPushButton(tr("&Save"));
+  gl2->addWidget(btnAddFunc, 0, 2);
+  gl2->addWidget(new QLabel(tr("Parameters")), 1, 0);
+  boxParam = new QLineEdit("a, b");
+  gl2->addWidget(boxParam, 1, 1);
+  btnDelFunc = new QPushButton(tr("&Remove"));
+  gl2->addWidget(btnDelFunc, 1, 2);
+
+  QGroupBox *gb = new QGroupBox();
+  gb->setLayout(gl2);
+
+  editBox = new QTextEdit();
+  // editBox->setTextFormat(Qt::PlainText);
+  editBox->setFocus();
+
+  QVBoxLayout *vbox1 = new QVBoxLayout();
+  btnAddTxt = new QPushButton(tr("Add &expression"));
+  vbox1->addWidget(btnAddTxt);
+  btnAddName = new QPushButton(tr("Add &name"));
+  vbox1->addWidget(btnAddName);
+  buttonClear = new QPushButton(tr("Rese&t"));
+  vbox1->addWidget(buttonClear);
+  buttonCancel2 = new QPushButton(tr("&Close"));
+  vbox1->addWidget(buttonCancel2);
+  btnContinue = new QPushButton(tr("&Fit >>"));
+  vbox1->addWidget(btnContinue);
+  vbox1->addStretch();
+
+  QHBoxLayout *hbox2 = new QHBoxLayout();
+  hbox2->addWidget(editBox);
+  hbox2->addLayout(vbox1);
+
+  QVBoxLayout *vbox2 = new QVBoxLayout();
+  vbox2->addLayout(gl1);
+  vbox2->addLayout(hbox1);
+  vbox2->addWidget(gb);
+  vbox2->addLayout(hbox2);
+
+  editPage = new QWidget();
+  editPage->setLayout(vbox2);
+  tw->addWidget(editPage);
+
+  connect(buttonPlugins, SIGNAL(clicked()), this, SLOT(chooseFolder()));
+  connect(buttonClear, SIGNAL(clicked()), this, SLOT(resetFunction()));
+  connect(categoryBox, SIGNAL(currentRowChanged(int)), this,
+          SLOT(showFunctionsList(int)));
+  connect(funcBox, SIGNAL(currentRowChanged(int)), this,
+          SLOT(showExpression(int)));
+  connect(boxUseBuiltIn, SIGNAL(toggled(bool)), this, SLOT(setFunction(bool)));
+  connect(btnAddName, SIGNAL(clicked()), this, SLOT(addFunctionName()));
+  connect(btnAddTxt, SIGNAL(clicked()), this, SLOT(addFunction()));
+  connect(btnContinue, SIGNAL(clicked()), this, SLOT(showFitPage()));
+  connect(btnAddFunc, SIGNAL(clicked()), this, SLOT(saveUserFunction()));
+  connect(btnDelFunc, SIGNAL(clicked()), this, SLOT(removeUserFunction()));
+  connect(buttonCancel2, SIGNAL(clicked()), this, SLOT(close()));
 }
 
-
-void FitDialog::initAdvancedPage()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+void FitDialog::initAdvancedPage() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
   if (!app) {
-    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of FitDialog is not ApplicationWindow as expected.");
   }
 
-	generatePointsBtn = new QRadioButton (tr("&Uniform X Function"));
-	generatePointsBtn->setChecked(app->generateUniformFitPoints);
-	connect( generatePointsBtn, SIGNAL(clicked()), this, SLOT(enableApplyChanges()));
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(generatePointsBtn, 0, 0);
-
-	lblPoints = new QLabel( tr("Points"));
-
-	generatePointsBox = new QSpinBox ();
-    generatePointsBox->setRange(0, 1000000);
-	generatePointsBox->setSingleStep(10);
-	generatePointsBox->setValue(app->fitPoints);
-	connect( generatePointsBox, SIGNAL(valueChanged(int)), this, SLOT(enableApplyChanges(int)));
-    showPointsBox(!app->generateUniformFitPoints);
-
-    QHBoxLayout *hb = new QHBoxLayout();
-    hb->addStretch();
-    hb->addWidget(lblPoints);
-    hb->addWidget(generatePointsBox);
-	gl1->addLayout(hb, 0, 1);
-
-	samePointsBtn = new QRadioButton(tr( "Same X as Fitting &Data" ));
-    gl1->addWidget(samePointsBtn, 1, 0);
-	samePointsBtn->setChecked(!app->generateUniformFitPoints);
-	connect( samePointsBtn, SIGNAL(clicked()), this, SLOT(enableApplyChanges()));
-
-    QGroupBox *gb1 = new QGroupBox(tr("Generated Fit Curve"));
-    gb1->setLayout(gl1);
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel( tr("Significant Digits")), 0, 1);
-	boxPrecision = new QSpinBox ();
-    boxPrecision->setRange(0, 13);
-	boxPrecision->setValue (app->fit_output_precision);
-	connect( boxPrecision, SIGNAL(valueChanged (int)), this, SLOT(enableApplyChanges(int)));
-
-    gl2->addWidget(boxPrecision, 0, 2);
-	btnParamTable = new QPushButton(tr( "Parameters &Table" ));
-    gl2->addWidget(btnParamTable, 1, 0);
-	gl2->addWidget(new QLabel( tr("Name: ")), 1, 1);
-	paramTableName = new QLineEdit(tr( "Parameters" ));
-    gl2->addWidget(paramTableName, 1, 2);
-	globalParamTableBox = new QCheckBox (tr("&One table for all fits"));
-	gl2->addWidget(globalParamTableBox, 1, 3);
-	btnCovMatrix = new QPushButton(tr( "Covariance &Matrix" ));
-    gl2->addWidget(btnCovMatrix, 2, 0);
-    gl2->addWidget(new QLabel( tr("Name: ")), 2, 1);
-	covMatrixName = new QLineEdit( tr( "CovMatrix" ) );
-    gl2->addWidget(covMatrixName, 2, 2);
-
-	scaleErrorsBox = new QCheckBox(tr("Scale Errors with sqrt(Chi^2/doF)"));
-	scaleErrorsBox->setChecked(app->fit_scale_errors);
-	connect( scaleErrorsBox, SIGNAL(stateChanged (int)), this, SLOT(enableApplyChanges(int)));
-
-    QGroupBox *gb2 = new QGroupBox(tr("Parameters Output"));
-    gb2->setLayout(gl2);
-
-	logBox = new QCheckBox (tr("&Write Parameters to Result Log"));
-	logBox->setChecked(app->writeFitResultsToLog);
-	connect( logBox, SIGNAL(stateChanged(int)), this, SLOT(enableApplyChanges(int)));
-
-	plotLabelBox = new QCheckBox (tr("&Paste Parameters to Plot"));
-	plotLabelBox->setChecked(app->pasteFitResultsToPlot);
-	connect( plotLabelBox, SIGNAL(stateChanged (int)), this, SLOT(enableApplyChanges(int)));
-
-    QHBoxLayout *hbox1 = new QHBoxLayout();
-
-	btnBack = new QPushButton(tr( "<< &Fit" ));
-	connect( btnBack, SIGNAL(clicked()), this, SLOT(returnToFitPage()));
-    hbox1->addWidget(btnBack);
-
-	btnApply = new QPushButton(tr( "&Apply" ));
-	btnApply->setEnabled(false);
-	connect( btnApply, SIGNAL(clicked()), this, SLOT(applyChanges()));
-    hbox1->addWidget(btnApply);
-
-	buttonCancel3 = new QPushButton(tr( "&Close" ));
-    hbox1->addWidget(buttonCancel3);
-    hbox1->addStretch();
-
-    QVBoxLayout *vbox1 = new QVBoxLayout();
-    vbox1->addWidget(gb1);
-    vbox1->addWidget(gb2);
-	vbox1->addWidget(scaleErrorsBox);
-    vbox1->addWidget(logBox);
-    vbox1->addWidget(plotLabelBox);
-    vbox1->addStretch();
-    vbox1->addLayout(hbox1);
-
-    advancedPage = new QWidget();
-	advancedPage->setLayout(vbox1);
-    tw->addWidget(advancedPage);
-
-	connect(btnParamTable, SIGNAL(clicked()), this, SLOT(showParametersTable()));
-	connect(btnCovMatrix, SIGNAL(clicked()), this, SLOT(showCovarianceMatrix()));
-	connect(samePointsBtn, SIGNAL(toggled(bool)), this, SLOT(showPointsBox(bool)));
-	connect(generatePointsBtn, SIGNAL(toggled(bool)), this, SLOT(showPointsBox(bool)));
-	connect(buttonCancel3, SIGNAL(clicked()), this, SLOT(close()));
+  generatePointsBtn = new QRadioButton(tr("&Uniform X Function"));
+  generatePointsBtn->setChecked(app->generateUniformFitPoints);
+  connect(generatePointsBtn, SIGNAL(clicked()), this,
+          SLOT(enableApplyChanges()));
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(generatePointsBtn, 0, 0);
+
+  lblPoints = new QLabel(tr("Points"));
+
+  generatePointsBox = new QSpinBox();
+  generatePointsBox->setRange(0, 1000000);
+  generatePointsBox->setSingleStep(10);
+  generatePointsBox->setValue(app->fitPoints);
+  connect(generatePointsBox, SIGNAL(valueChanged(int)), this,
+          SLOT(enableApplyChanges(int)));
+  showPointsBox(!app->generateUniformFitPoints);
+
+  QHBoxLayout *hb = new QHBoxLayout();
+  hb->addStretch();
+  hb->addWidget(lblPoints);
+  hb->addWidget(generatePointsBox);
+  gl1->addLayout(hb, 0, 1);
+
+  samePointsBtn = new QRadioButton(tr("Same X as Fitting &Data"));
+  gl1->addWidget(samePointsBtn, 1, 0);
+  samePointsBtn->setChecked(!app->generateUniformFitPoints);
+  connect(samePointsBtn, SIGNAL(clicked()), this, SLOT(enableApplyChanges()));
+
+  QGroupBox *gb1 = new QGroupBox(tr("Generated Fit Curve"));
+  gb1->setLayout(gl1);
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("Significant Digits")), 0, 1);
+  boxPrecision = new QSpinBox();
+  boxPrecision->setRange(0, 13);
+  boxPrecision->setValue(app->fit_output_precision);
+  connect(boxPrecision, SIGNAL(valueChanged(int)), this,
+          SLOT(enableApplyChanges(int)));
+
+  gl2->addWidget(boxPrecision, 0, 2);
+  btnParamTable = new QPushButton(tr("Parameters &Table"));
+  gl2->addWidget(btnParamTable, 1, 0);
+  gl2->addWidget(new QLabel(tr("Name: ")), 1, 1);
+  paramTableName = new QLineEdit(tr("Parameters"));
+  gl2->addWidget(paramTableName, 1, 2);
+  globalParamTableBox = new QCheckBox(tr("&One table for all fits"));
+  gl2->addWidget(globalParamTableBox, 1, 3);
+  btnCovMatrix = new QPushButton(tr("Covariance &Matrix"));
+  gl2->addWidget(btnCovMatrix, 2, 0);
+  gl2->addWidget(new QLabel(tr("Name: ")), 2, 1);
+  covMatrixName = new QLineEdit(tr("CovMatrix"));
+  gl2->addWidget(covMatrixName, 2, 2);
+
+  scaleErrorsBox = new QCheckBox(tr("Scale Errors with sqrt(Chi^2/doF)"));
+  scaleErrorsBox->setChecked(app->fit_scale_errors);
+  connect(scaleErrorsBox, SIGNAL(stateChanged(int)), this,
+          SLOT(enableApplyChanges(int)));
+
+  QGroupBox *gb2 = new QGroupBox(tr("Parameters Output"));
+  gb2->setLayout(gl2);
+
+  logBox = new QCheckBox(tr("&Write Parameters to Result Log"));
+  logBox->setChecked(app->writeFitResultsToLog);
+  connect(logBox, SIGNAL(stateChanged(int)), this,
+          SLOT(enableApplyChanges(int)));
+
+  plotLabelBox = new QCheckBox(tr("&Paste Parameters to Plot"));
+  plotLabelBox->setChecked(app->pasteFitResultsToPlot);
+  connect(plotLabelBox, SIGNAL(stateChanged(int)), this,
+          SLOT(enableApplyChanges(int)));
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+
+  btnBack = new QPushButton(tr("<< &Fit"));
+  connect(btnBack, SIGNAL(clicked()), this, SLOT(returnToFitPage()));
+  hbox1->addWidget(btnBack);
+
+  btnApply = new QPushButton(tr("&Apply"));
+  btnApply->setEnabled(false);
+  connect(btnApply, SIGNAL(clicked()), this, SLOT(applyChanges()));
+  hbox1->addWidget(btnApply);
+
+  buttonCancel3 = new QPushButton(tr("&Close"));
+  hbox1->addWidget(buttonCancel3);
+  hbox1->addStretch();
+
+  QVBoxLayout *vbox1 = new QVBoxLayout();
+  vbox1->addWidget(gb1);
+  vbox1->addWidget(gb2);
+  vbox1->addWidget(scaleErrorsBox);
+  vbox1->addWidget(logBox);
+  vbox1->addWidget(plotLabelBox);
+  vbox1->addStretch();
+  vbox1->addLayout(hbox1);
+
+  advancedPage = new QWidget();
+  advancedPage->setLayout(vbox1);
+  tw->addWidget(advancedPage);
+
+  connect(btnParamTable, SIGNAL(clicked()), this, SLOT(showParametersTable()));
+  connect(btnCovMatrix, SIGNAL(clicked()), this, SLOT(showCovarianceMatrix()));
+  connect(samePointsBtn, SIGNAL(toggled(bool)), this,
+          SLOT(showPointsBox(bool)));
+  connect(generatePointsBtn, SIGNAL(toggled(bool)), this,
+          SLOT(showPointsBox(bool)));
+  connect(buttonCancel3, SIGNAL(clicked()), this, SLOT(close()));
 }
 
 void FitDialog::applyChanges() {
@@ -507,532 +522,534 @@ void FitDialog::applyChanges() {
   btnApply->setEnabled(false);
 }
 
-void FitDialog::showParametersTable()
-{
-	QString tableName = paramTableName->text();
-	if (tableName.isEmpty()){
-		QMessageBox::critical(this, tr("MantidPlot - Error"),
-				tr("Please enter a valid name for the parameters table."));
-		return;
-	}
-
-	if (!d_current_fit){
-		QMessageBox::critical(this, tr("MantidPlot - Error"),
-				tr("Please perform a fit first and try again."));
-		return;
-	}
-
-	d_param_table = d_current_fit->parametersTable(tableName);
+void FitDialog::showParametersTable() {
+  QString tableName = paramTableName->text();
+  if (tableName.isEmpty()) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Error"),
+        tr("Please enter a valid name for the parameters table."));
+    return;
+  }
+
+  if (!d_current_fit) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"),
+                          tr("Please perform a fit first and try again."));
+    return;
+  }
+
+  d_param_table = d_current_fit->parametersTable(tableName);
 }
 
-void FitDialog::showCovarianceMatrix()
-{
-	QString matrixName = covMatrixName->text();
-	if (matrixName.isEmpty()){
-		QMessageBox::critical(this, tr("MantidPlot - Error"),
-				tr("Please enter a valid name for the covariance matrix."));
-		return;
-	}
-
-	if (!d_current_fit){
-		QMessageBox::critical(this, tr("MantidPlot - Error"),
-				tr("Please perform a fit first and try again."));
-		return;
-	}
-
-	d_current_fit->covarianceMatrix(matrixName);
+void FitDialog::showCovarianceMatrix() {
+  QString matrixName = covMatrixName->text();
+  if (matrixName.isEmpty()) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Error"),
+        tr("Please enter a valid name for the covariance matrix."));
+    return;
+  }
+
+  if (!d_current_fit) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"),
+                          tr("Please perform a fit first and try again."));
+    return;
+  }
+
+  d_current_fit->covarianceMatrix(matrixName);
 }
 
-void FitDialog::showPointsBox(bool)
-{
-	if (generatePointsBtn->isChecked()){
-		lblPoints->show();
-		generatePointsBox->show();
-	} else {
-		lblPoints->hide();
-		generatePointsBox->hide();
-	}
+void FitDialog::showPointsBox(bool) {
+  if (generatePointsBtn->isChecked()) {
+    lblPoints->show();
+    generatePointsBox->show();
+  } else {
+    lblPoints->hide();
+    generatePointsBox->hide();
+  }
 }
 
-void FitDialog::setGraph(Graph *g)
-{
-	if (!g)
-		return;
+void FitDialog::setGraph(Graph *g) {
+  if (!g)
+    return;
 
-	d_graph = g;
-	boxCurve->clear();
-	boxCurve->addItems(d_graph->analysableCurvesList());
+  d_graph = g;
+  boxCurve->clear();
+  boxCurve->addItems(d_graph->analysableCurvesList());
 
-    QString selectedCurve = g->selectedCurveTitle();
-	if (!selectedCurve.isEmpty()){
-	    int index = boxCurve->findText (selectedCurve);
-		boxCurve->setCurrentIndex(index);
-	}
-    activateCurve(boxCurve->currentText());
+  QString selectedCurve = g->selectedCurveTitle();
+  if (!selectedCurve.isEmpty()) {
+    int index = boxCurve->findText(selectedCurve);
+    boxCurve->setCurrentIndex(index);
+  }
+  activateCurve(boxCurve->currentText());
 
-	connect (d_graph, SIGNAL(closedGraph()), this, SLOT(close()));
-	connect (d_graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
+  connect(d_graph, SIGNAL(closedGraph()), this, SLOT(close()));
+  connect(d_graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
 }
 
-void FitDialog::activateCurve(const QString& curveName)
-{
-	QwtPlotCurve *c = d_graph->curve(curveName);
-	if (!c)
-		return;
-
-	double start, end;
-    d_graph->range(d_graph->curveIndex(curveName), &start, &end);
-    boxFrom->setValue(QMIN(start, end));
-    boxTo->setValue(QMAX(start, end));
-	//Set the same color as the data curve chosen for fit (Feature Request #4031)
-	boxColor->setColor(c->pen().color());
+void FitDialog::activateCurve(const QString &curveName) {
+  QwtPlotCurve *c = d_graph->curve(curveName);
+  if (!c)
+    return;
+
+  double start, end;
+  d_graph->range(d_graph->curveIndex(curveName), &start, &end);
+  boxFrom->setValue(QMIN(start, end));
+  boxTo->setValue(QMAX(start, end));
+  // Set the same color as the data curve chosen for fit (Feature Request #4031)
+  boxColor->setColor(c->pen().color());
 }
 
-void FitDialog::saveUserFunction()
-{
-	if (editBox->toPlainText().isEmpty()){
-		QMessageBox::critical(this, tr("MantidPlot - Input function error"), tr("Please enter a valid function!"));
-		editBox->setFocus();
-		return;
-	} else if (boxName->text().isEmpty()) {
-		QMessageBox::critical(this, tr("MantidPlot - Input function error"),
-				tr("Please enter a function name!"));
-		boxName->setFocus();
-		return;
-	} else if (boxParam->text().remove(QRegExp("[,;\\s]")).isEmpty()){
-		QMessageBox::critical(this, tr("MantidPlot - Input function error"),
-				tr("Please enter at least one parameter name!"));
-		boxParam->setFocus();
-		return;
-	}
-
-	if (builtInFunctionNames().contains(boxName->text())){
-		QMessageBox::critical(this, tr("MantidPlot - Error: function name"),
-				"<p><b>" + boxName->text() + "</b>" + tr(" is a built-in function name"
-					"<p>You must choose another name for your function!"));
-		editBox->setFocus();
-		return;
-	}
-
-	if (editBox->toPlainText().contains(boxName->text())){
-		QMessageBox::critical(this, tr("MantidPlot - Input function error"),
-				tr("You can't define functions recursively!"));
-		editBox->setFocus();
-		return;
-	}
-
-	QString name = boxName->text();
-    QStringList lst = userFunctionNames();
-	QString formula = parseFormula(editBox->toPlainText().simplified());
-	if (lst.contains(name)){
-		int index = lst.indexOf(name);
+void FitDialog::saveUserFunction() {
+  if (editBox->toPlainText().isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input function error"),
+                          tr("Please enter a valid function!"));
+    editBox->setFocus();
+    return;
+  } else if (boxName->text().isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input function error"),
+                          tr("Please enter a function name!"));
+    boxName->setFocus();
+    return;
+  } else if (boxParam->text().remove(QRegExp("[,;\\s]")).isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input function error"),
+                          tr("Please enter at least one parameter name!"));
+    boxParam->setFocus();
+    return;
+  }
+
+  if (builtInFunctionNames().contains(boxName->text())) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Error: function name"),
+        "<p><b>" + boxName->text() + "</b>" +
+            tr(" is a built-in function name"
+               "<p>You must choose another name for your function!"));
+    editBox->setFocus();
+    return;
+  }
+
+  if (editBox->toPlainText().contains(boxName->text())) {
+    QMessageBox::critical(this, tr("MantidPlot - Input function error"),
+                          tr("You can't define functions recursively!"));
+    editBox->setFocus();
+    return;
+  }
+
+  QString name = boxName->text();
+  QStringList lst = userFunctionNames();
+  QString formula = parseFormula(editBox->toPlainText().simplified());
+  if (lst.contains(name)) {
+    int index = lst.indexOf(name);
     d_current_fit = dynamic_cast<NonLinearFit *>(d_user_functions[index]);
     if (d_current_fit) {
-		  d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
+      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());
+  } else {
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
     if (!app) {
-      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+      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"),
+        app->fitModelsPath + "/" + name, filter);
+    if (!fn.isEmpty()) {
+      QFileInfo fi(fn);
+      app->fitModelsPath = fi.dir().absolutePath();
+      QString baseName = fi.fileName();
+      if (!baseName.contains("."))
+        fn.append(".fit");
+
+      d_current_fit = new NonLinearFit(app, d_graph);
+      d_current_fit->setObjectName(name);
+      d_current_fit->setParametersList(boxParam->text().split(
+          QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
+      d_current_fit->setFormula(formula);
+      if (d_current_fit->save(fn)) {
+        QStringList lst = userFunctionNames();
+        lst << name;
+        lst.sort();
+        int index = int(lst.indexOf(name));
+        d_user_functions.insert(index, d_current_fit);
+
+        if (categoryBox->currentRow() == 0) {
+          funcBox->clear();
+          funcBox->addItems(lst);
+          funcBox->setCurrentRow(index);
+        }
+
+        if (d_user_functions.count() > 0 && !boxUseBuiltIn->isEnabled() &&
+            categoryBox->currentRow() == 0)
+          boxUseBuiltIn->setEnabled(true);
+      }
     }
-		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"),
-                                app->fitModelsPath + "/" + name, filter);
-		if (!fn.isEmpty()){
-            QFileInfo fi(fn);
-            app->fitModelsPath = fi.dir().absolutePath();
-            QString baseName = fi.fileName();
-            if (!baseName.contains("."))
-                fn.append(".fit");
-
-            d_current_fit = new NonLinearFit(app, d_graph);
-            d_current_fit->setObjectName(name);
-            d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
-            d_current_fit->setFormula(formula);
-            if (d_current_fit->save(fn)){
-                QStringList lst = userFunctionNames();
-                lst << name;
-                lst.sort();
-                int index = int(lst.indexOf(name));
-                d_user_functions.insert (index, d_current_fit);
-
-                if (categoryBox->currentRow() == 0){
-                    funcBox->clear();
-                    funcBox->addItems(lst);
-                    funcBox->setCurrentRow(index);
-                }
-
-                if (d_user_functions.count()>0 && !boxUseBuiltIn->isEnabled() && categoryBox->currentRow() == 0)
-                    boxUseBuiltIn->setEnabled(true);
-            }
-		}
-	}
+  }
 }
 
-void FitDialog::removeUserFunction()
-{
-    QStringList lst = userFunctionNames();
-    if (lst.isEmpty())
-        return;
-
-    QString s = tr("Are you sure you want to remove fit model file:\n %1 ?").arg(d_current_fit->fileName());
-    if (QMessageBox::Yes != QMessageBox::question (this, tr("MantidPlot") + " - " + tr("Remove Fit Model"), s, QMessageBox::Yes, QMessageBox::Cancel))
-        return;
-
-	QString name = funcBox->currentItem()->text();
-	if (lst.contains(name)){
-		explainBox->setText(QString());
-
-		int index = lst.indexOf(name);
-		if (0 <= index && index < d_user_functions.size()){
-            QFile f((d_user_functions[index])->fileName());
-            f.remove();
-            d_user_functions.removeAt(index);
-		}
-
-        lst.removeAll(name);
-		funcBox->clear();
-		funcBox->addItems(lst);
-		funcBox->setCurrentRow(0);
-
-		if (!lst.count())
-			boxUseBuiltIn->setEnabled(false);
-	}
+void FitDialog::removeUserFunction() {
+  QStringList lst = userFunctionNames();
+  if (lst.isEmpty())
+    return;
+
+  QString s = tr("Are you sure you want to remove fit model file:\n %1 ?")
+                  .arg(d_current_fit->fileName());
+  if (QMessageBox::Yes !=
+      QMessageBox::question(this,
+                            tr("MantidPlot") + " - " + tr("Remove Fit Model"),
+                            s, QMessageBox::Yes, QMessageBox::Cancel))
+    return;
+
+  QString name = funcBox->currentItem()->text();
+  if (lst.contains(name)) {
+    explainBox->setText(QString());
+
+    int index = lst.indexOf(name);
+    if (0 <= index && index < d_user_functions.size()) {
+      QFile f((d_user_functions[index])->fileName());
+      f.remove();
+      d_user_functions.removeAt(index);
+    }
+
+    lst.removeAll(name);
+    funcBox->clear();
+    funcBox->addItems(lst);
+    funcBox->setCurrentRow(0);
+
+    if (!lst.count())
+      boxUseBuiltIn->setEnabled(false);
+  }
 }
 
-void FitDialog::showFitPage()
-{
-	QString formula = editBox->toPlainText().simplified();
-	if (formula.isEmpty()){
-		QMessageBox::critical(this, tr("MantidPlot - Input function error"), tr("Please enter a valid function!"));
-		editBox->setFocus();
-		return;
-	}
+void FitDialog::showFitPage() {
+  QString formula = editBox->toPlainText().simplified();
+  if (formula.isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input function error"),
+                          tr("Please enter a valid function!"));
+    editBox->setFocus();
+    return;
+  }
 
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-    if (!boxUseBuiltIn->isChecked()){
-        d_current_fit = new NonLinearFit(app, d_graph);
-		d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
-		formula = parseFormula(formula);
-		d_current_fit->setFormula(formula);
+  if (!boxUseBuiltIn->isChecked()) {
+    d_current_fit = new NonLinearFit(app, d_graph);
+    d_current_fit->setParametersList(boxParam->text().split(
+        QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
+    formula = parseFormula(formula);
+    d_current_fit->setFormula(formula);
+  }
+
+  if (d_current_fit->error())
+    return;
+
+  if (d_current_fit->type() == Fit::BuiltIn &&
+      (isOfType(d_current_fit, "PolynomialFit") ||
+       isOfType(d_current_fit, "LinearFit") ||
+       isOfType(d_current_fit, "LinearSlopeFit"))) {
+    btnParamRange->setEnabled(false);
+    boxAlgorithm->setEnabled(false);
+    boxPoints->setEnabled(false);
+    boxTolerance->setEnabled(false);
+  } else {
+    btnParamRange->setEnabled(true);
+    boxAlgorithm->setEnabled(true);
+    boxPoints->setEnabled(true);
+    boxTolerance->setEnabled(true);
+  }
+
+  QStringList paramList = d_current_fit->parameterNames();
+  int parameters = d_current_fit->numParameters();
+  boxParams->clearContents();
+  boxParams->setRowCount(parameters);
+  boxParams->hideColumn(4);
+
+  int aux = parameters;
+  if (aux > 7)
+    aux = 7;
+  boxParams->setMinimumHeight(
+      4 + (aux + 1) * boxParams->horizontalHeader()->height());
+
+  // QLocale locale = app->locale();
+  int prec = boxPrecision->value();
+  for (int i = 0; i < parameters; i++) {
+    QTableWidgetItem *it = new QTableWidgetItem(paramList[i]);
+    it->setFlags(it->flags() & (~Qt::ItemIsEditable));
+    it->setBackground(QBrush(Qt::lightGray));
+    it->setForeground(QBrush(Qt::darkRed));
+    QFont font = it->font();
+    font.setBold(true);
+    it->setFont(font);
+    boxParams->setItem(i, 0, it);
+
+    if (d_current_fit->type() != Fit::BuiltIn) {
+      RangeLimitBox *rbl = new RangeLimitBox(RangeLimitBox::LeftLimit);
+      //			rbl->setLocale(locale);
+      rbl->setDecimals(prec);
+      boxParams->setCellWidget(i, 1, rbl);
+
+      RangeLimitBox *rbr = new RangeLimitBox(RangeLimitBox::RightLimit);
+      //			rbr->setLocale(locale);
+      rbr->setDecimals(prec);
+      boxParams->setCellWidget(i, 3, rbr);
     }
 
-	if (d_current_fit->error())
-		return;
-
-    if (d_current_fit->type() == Fit::BuiltIn && 
-	(isOfType(d_current_fit, "PolynomialFit") ||
-	 isOfType(d_current_fit, "LinearFit") ||
-	 isOfType(d_current_fit, "LinearSlopeFit"))){
-        btnParamRange->setEnabled(false);
-        boxAlgorithm->setEnabled(false);
-		boxPoints->setEnabled(false);
-		boxTolerance->setEnabled(false);
-    } else {
-        btnParamRange->setEnabled(true);
-        boxAlgorithm->setEnabled(true);
-		boxPoints->setEnabled(true);
-		boxTolerance->setEnabled(true);
+    DoubleSpinBox *sb = new DoubleSpinBox();
+    //		sb->setLocale(locale);
+    sb->setDecimals(prec);
+    sb->setValue(d_current_fit->initialGuess(i));
+    connect(sb, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
+    boxParams->setCellWidget(i, 2, sb);
+  }
+  for (int i = 0; i < parameters; i++)
+    boxParams->item(i, 0)->setText(paramList[i]);
+
+  if (d_current_fit->type() == Fit::User) {
+    boxParams->showColumn(4);
+    for (int i = 0; i < boxParams->rowCount(); i++) {
+      QTableWidgetItem *it = new QTableWidgetItem();
+      it->setFlags(it->flags() & (~Qt::ItemIsEditable));
+      it->setBackground(QBrush(Qt::lightGray));
+      boxParams->setItem(i, 4, it);
+
+      QCheckBox *cb = new QCheckBox();
+      boxParams->setCellWidget(i, 4, cb);
     }
+  }
 
-	QStringList paramList = d_current_fit->parameterNames();
-	int parameters = d_current_fit->numParameters();
-	boxParams->clearContents();
-	boxParams->setRowCount(parameters);
-    boxParams->hideColumn(4);
-
-    int aux = parameters;
-	if (aux > 7)
-		aux = 7;
-	boxParams->setMinimumHeight(4 + (aux + 1)*boxParams->horizontalHeader()->height());
-
-	//QLocale locale = app->locale();
-	int prec = boxPrecision->value();
-    for (int i = 0; i<parameters; i++){
-        QTableWidgetItem *it = new QTableWidgetItem(paramList[i]);
-        it->setFlags(it->flags() & (~Qt::ItemIsEditable));
-        it->setBackground(QBrush(Qt::lightGray));
-        it->setForeground(QBrush(Qt::darkRed));
-        QFont font = it->font();
-        font.setBold(true);
-        it->setFont(font);
-        boxParams->setItem(i, 0, it);
-
-		if (d_current_fit->type() != Fit::BuiltIn){
-			RangeLimitBox *rbl = new RangeLimitBox(RangeLimitBox::LeftLimit);
-//			rbl->setLocale(locale);
-			rbl->setDecimals(prec);
-			boxParams->setCellWidget(i, 1, rbl);
-			
-			RangeLimitBox *rbr = new RangeLimitBox(RangeLimitBox::RightLimit);
-//			rbr->setLocale(locale);
-			rbr->setDecimals(prec);
-			boxParams->setCellWidget(i, 3, rbr);
-		}
-
-		DoubleSpinBox *sb = new DoubleSpinBox();
-//		sb->setLocale(locale);
-		sb->setDecimals(prec);
-		sb->setValue(d_current_fit->initialGuess(i));
-        connect(sb, SIGNAL(valueChanged(double)), this, SLOT(updatePreview()));
-        boxParams->setCellWidget(i, 2, sb);
-	}
-    for (int i = 0; i<parameters; i++)
-        boxParams->item (i, 0)->setText(paramList[i]);
-
-	if (d_current_fit->type() == Fit::User){
-        boxParams->showColumn(4);
-		for (int i = 0; i<boxParams->rowCount(); i++ ){
-            QTableWidgetItem *it = new QTableWidgetItem();
-            it->setFlags(it->flags() & (~Qt::ItemIsEditable));
-            it->setBackground(QBrush(Qt::lightGray));
-            boxParams->setItem(i, 4, it);
-
-			QCheckBox *cb = new QCheckBox();
-            boxParams->setCellWidget(i, 4, cb);
-		}
-	}
-
-	boxFunction->setText(formula);
-	lblFunction->setText(boxName->text() +" (x, " + boxParam->text().simplified() + ")");
-
-	tw->setCurrentWidget (fitPage);
-	if (previewBox->isChecked())
-		updatePreview();
+  boxFunction->setText(formula);
+  lblFunction->setText(boxName->text() + " (x, " +
+                       boxParam->text().simplified() + ")");
+
+  tw->setCurrentWidget(fitPage);
+  if (previewBox->isChecked())
+    updatePreview();
 }
 
-void FitDialog::showEditPage()
-{
-    if (d_current_fit)
-        d_current_fit->freeMemory();
-	tw->setCurrentWidget(editPage);
+void FitDialog::showEditPage() {
+  if (d_current_fit)
+    d_current_fit->freeMemory();
+  tw->setCurrentWidget(editPage);
 }
 
-void FitDialog::showAdvancedPage()
-{
-	tw->setCurrentWidget (advancedPage);
-	if (d_current_fit && (isOfType(d_current_fit,"PolynomialFit") ||
-			      isOfType(d_current_fit, "LinearFit") ||
-			      isOfType(d_current_fit, "LinearSlopeFit"))){
-		scaleErrorsBox->setChecked(false);
-		scaleErrorsBox->setEnabled(false);
-	} else {
-		ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-		if (app)
-			scaleErrorsBox->setChecked(app->fit_scale_errors);
-		scaleErrorsBox->setEnabled(true);
-	}
+void FitDialog::showAdvancedPage() {
+  tw->setCurrentWidget(advancedPage);
+  if (d_current_fit && (isOfType(d_current_fit, "PolynomialFit") ||
+                        isOfType(d_current_fit, "LinearFit") ||
+                        isOfType(d_current_fit, "LinearSlopeFit"))) {
+    scaleErrorsBox->setChecked(false);
+    scaleErrorsBox->setEnabled(false);
+  } else {
+    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+    if (app)
+      scaleErrorsBox->setChecked(app->fit_scale_errors);
+    scaleErrorsBox->setEnabled(true);
+  }
 }
 
-void FitDialog::setFunction(bool ok)
-{
-	editBox->setEnabled(!ok);
-	boxParam->setEnabled(!ok);
-	boxName->setEnabled(!ok);
-	btnAddFunc->setEnabled(!ok);
-	btnAddName->setEnabled(!ok);
-	btnAddTxt->setEnabled(!ok);
-	buttonClear->setEnabled(!ok);
-
-	if (ok){
-		boxName->setText(funcBox->currentItem()->text());
-		editBox->setText(explainBox->toPlainText());
-		boxParam->setText(d_current_fit->parameterNames().join(", "));
-	}
+void FitDialog::setFunction(bool ok) {
+  editBox->setEnabled(!ok);
+  boxParam->setEnabled(!ok);
+  boxName->setEnabled(!ok);
+  btnAddFunc->setEnabled(!ok);
+  btnAddName->setEnabled(!ok);
+  btnAddTxt->setEnabled(!ok);
+  buttonClear->setEnabled(!ok);
+
+  if (ok) {
+    boxName->setText(funcBox->currentItem()->text());
+    editBox->setText(explainBox->toPlainText());
+    boxParam->setText(d_current_fit->parameterNames().join(", "));
+  }
 }
 
-void FitDialog::showFunctionsList(int category)
-{
-	boxUseBuiltIn->setChecked(false);
-	boxUseBuiltIn->setEnabled(false);
-	boxUseBuiltIn->hide();
-	buttonPlugins->hide();
-	btnDelFunc->setEnabled(false);
-    funcBox->blockSignals(true);
-	funcBox->clear();
-    explainBox->clear();
-	polynomOrderLabel->hide();
-	polynomOrderBox->hide();
-
-	switch (category)
-	{
-		case 0:
-			if (d_user_functions.count() > 0){
-				boxUseBuiltIn->setEnabled(true);
-
-                QStringList lst;
-                foreach(Fit *fit, d_user_functions)
-                    lst << fit->objectName();
-                funcBox->addItems(lst);
-			}
-            buttonPlugins->setText(tr("Choose &models folder..."));
-            buttonPlugins->show();
-			boxUseBuiltIn->setText(tr("Fit with selected &user function"));
-			boxUseBuiltIn->show();
-			btnDelFunc->setEnabled(true);
-        break;
-
-		case 1:
-			boxUseBuiltIn->setText(tr("Fit using &built-in function"));
-			boxUseBuiltIn->show();
-			boxUseBuiltIn->setEnabled(true);
-			funcBox->addItems(builtInFunctionNames());
-        break;
-
-		case 2:
-			showParseFunctions();
-        break;
-
-		case 3:
-            buttonPlugins->setText(tr("Choose plug&ins folder..."));
-            buttonPlugins->show();
-			boxUseBuiltIn->setText(tr("Fit using &plugin function"));
-			boxUseBuiltIn->show();
-            boxUseBuiltIn->setEnabled(d_plugins.size() > 0);
-            QStringList lst;
-            foreach(Fit *fit, d_plugins)
-                lst << fit->objectName();
-            funcBox->addItems(lst);
-        break;
-	}
-    funcBox->blockSignals(false);
-	funcBox->setCurrentRow (0);
+void FitDialog::showFunctionsList(int category) {
+  boxUseBuiltIn->setChecked(false);
+  boxUseBuiltIn->setEnabled(false);
+  boxUseBuiltIn->hide();
+  buttonPlugins->hide();
+  btnDelFunc->setEnabled(false);
+  funcBox->blockSignals(true);
+  funcBox->clear();
+  explainBox->clear();
+  polynomOrderLabel->hide();
+  polynomOrderBox->hide();
+
+  switch (category) {
+  case 0:
+    if (d_user_functions.count() > 0) {
+      boxUseBuiltIn->setEnabled(true);
+
+      QStringList lst;
+      foreach (Fit *fit, d_user_functions)
+        lst << fit->objectName();
+      funcBox->addItems(lst);
+    }
+    buttonPlugins->setText(tr("Choose &models folder..."));
+    buttonPlugins->show();
+    boxUseBuiltIn->setText(tr("Fit with selected &user function"));
+    boxUseBuiltIn->show();
+    btnDelFunc->setEnabled(true);
+    break;
+
+  case 1:
+    boxUseBuiltIn->setText(tr("Fit using &built-in function"));
+    boxUseBuiltIn->show();
+    boxUseBuiltIn->setEnabled(true);
+    funcBox->addItems(builtInFunctionNames());
+    break;
+
+  case 2:
+    showParseFunctions();
+    break;
+
+  case 3:
+    buttonPlugins->setText(tr("Choose plug&ins folder..."));
+    buttonPlugins->show();
+    boxUseBuiltIn->setText(tr("Fit using &plugin function"));
+    boxUseBuiltIn->show();
+    boxUseBuiltIn->setEnabled(d_plugins.size() > 0);
+    QStringList lst;
+    foreach (Fit *fit, d_plugins)
+      lst << fit->objectName();
+    funcBox->addItems(lst);
+    break;
+  }
+  funcBox->blockSignals(false);
+  funcBox->setCurrentRow(0);
 }
 
-void FitDialog::chooseFolder()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (categoryBox->currentRow() == 3){//plugins
-        QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the plugins folder"), app->fitPluginsPath);
-        if (!dir.isEmpty()){
-            funcBox->clear();
-            explainBox->clear();
-            app->fitPluginsPath = dir;
-            loadPlugins();
-        }
-	} else if (!categoryBox->currentRow()){//user-defined
-	    QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the fit models folder"), app->fitModelsPath);
-        if (!dir.isEmpty()){
-            funcBox->clear();
-            explainBox->clear();
-            app->fitModelsPath = dir;
-            loadUserFunctions();
-
-            QString path = app->fitModelsPath + "/";
-            foreach(Fit *fit, d_built_in_functions)
-                fit->setFileName(path + fit->objectName() + ".fit");
-        }
-	}
+void FitDialog::chooseFolder() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (categoryBox->currentRow() == 3) { // plugins
+    QString dir = QFileDialog::getExistingDirectory(
+        this, tr("Choose the plugins folder"), app->fitPluginsPath);
+    if (!dir.isEmpty()) {
+      funcBox->clear();
+      explainBox->clear();
+      app->fitPluginsPath = dir;
+      loadPlugins();
+    }
+  } else if (!categoryBox->currentRow()) { // user-defined
+    QString dir = QFileDialog::getExistingDirectory(
+        this, tr("Choose the fit models folder"), app->fitModelsPath);
+    if (!dir.isEmpty()) {
+      funcBox->clear();
+      explainBox->clear();
+      app->fitModelsPath = dir;
+      loadUserFunctions();
+
+      QString path = app->fitModelsPath + "/";
+      foreach (Fit *fit, d_built_in_functions)
+        fit->setFileName(path + fit->objectName() + ".fit");
+    }
+  }
 }
 
-void FitDialog::loadPlugins()
-{
-    d_plugins.clear();
-    //typedef char* (*fitFunc)();
+void FitDialog::loadPlugins() {
+  d_plugins.clear();
+  // typedef char* (*fitFunc)();
 
-	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.");
+    throw std::logic_error(
+        "Parent of FitDialog is not ApplicationWindow as expected.");
   }
-	QString path = app->fitPluginsPath + "/";
-	QString modelsDirPath = app->fitModelsPath + "/";
-	QDir dir(path);
-	QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
-    QStringList names;
-	for (int i=0; i<lst.count(); i++){
-	    QString file = lst[i];
-	    if (QLibrary::isLibrary (file)){
-            QLibrary lib(path + file);
-            PluginFit *fit = new PluginFit(app, d_graph);
-            fit->load(lib.fileName());
-            d_plugins << fit;
-            names << fit->objectName();
-            fit->setFileName(modelsDirPath + fit->objectName() + ".fit");
-	    }
-	}
-
-    if (d_plugins.size() > 0){
-        funcBox->addItems(names);
-        funcBox->setCurrentRow(0);
-        boxUseBuiltIn->setEnabled(true);
-    } else
-        boxUseBuiltIn->setEnabled(false);
+  QString path = app->fitPluginsPath + "/";
+  QString modelsDirPath = app->fitModelsPath + "/";
+  QDir dir(path);
+  QStringList lst = dir.entryList(QDir::Files | QDir::NoSymLinks, QDir::Name);
+  QStringList names;
+  for (int i = 0; i < lst.count(); i++) {
+    QString file = lst[i];
+    if (QLibrary::isLibrary(file)) {
+      QLibrary lib(path + file);
+      PluginFit *fit = new PluginFit(app, d_graph);
+      fit->load(lib.fileName());
+      d_plugins << fit;
+      names << fit->objectName();
+      fit->setFileName(modelsDirPath + fit->objectName() + ".fit");
+    }
+  }
+
+  if (d_plugins.size() > 0) {
+    funcBox->addItems(names);
+    funcBox->setCurrentRow(0);
+    boxUseBuiltIn->setEnabled(true);
+  } else
+    boxUseBuiltIn->setEnabled(false);
 }
 
-void FitDialog::showParseFunctions()
-{
-	funcBox->addItems(MyParser::functionsList());
+void FitDialog::showParseFunctions() {
+  funcBox->addItems(MyParser::functionsList());
 }
 
-void FitDialog::showExpression(int function)
-{
-    if (function < 0)
-        return;
-
-	if (categoryBox->currentRow() == 2)
-		explainBox->setText(MyParser::explainFunction(function));
-	else if (categoryBox->currentRow() == 1){
-		polynomOrderLabel->hide();
-		polynomOrderBox->hide();
-		if (funcBox->currentItem()->text() == tr("Gauss") ||
-			funcBox->currentItem()->text() == tr("Lorentz")){
-			polynomOrderLabel->setText(tr("Peaks"));
-			polynomOrderLabel->show();
-			polynomOrderBox->show();
-		} else if (funcBox->currentItem()->text() == tr("Polynomial")){
-			polynomOrderLabel->setText(tr("Polynomial Order"));
-			polynomOrderLabel->show();
-			polynomOrderBox->show();
-		}
-
-		d_current_fit = d_built_in_functions[function];
-		explainBox->setText(d_current_fit->formula());
-		setFunction(boxUseBuiltIn->isChecked());
-	} else if (categoryBox->currentRow() == 0){
-		if (d_user_functions.size() > function){
-			d_current_fit = d_user_functions[function];
-			explainBox->setText(d_current_fit->formula());
-		} else
-			explainBox->clear();
-		setFunction(boxUseBuiltIn->isChecked());
-	} else if (categoryBox->currentRow() == 3){
-		if (d_plugins.size() > 0){
-		    d_current_fit = d_plugins[function];
-			explainBox->setText(d_current_fit->formula());
-			setFunction(boxUseBuiltIn->isChecked());
-		} else
-			explainBox->clear();
-	}
+void FitDialog::showExpression(int function) {
+  if (function < 0)
+    return;
+
+  if (categoryBox->currentRow() == 2)
+    explainBox->setText(MyParser::explainFunction(function));
+  else if (categoryBox->currentRow() == 1) {
+    polynomOrderLabel->hide();
+    polynomOrderBox->hide();
+    if (funcBox->currentItem()->text() == tr("Gauss") ||
+        funcBox->currentItem()->text() == tr("Lorentz")) {
+      polynomOrderLabel->setText(tr("Peaks"));
+      polynomOrderLabel->show();
+      polynomOrderBox->show();
+    } else if (funcBox->currentItem()->text() == tr("Polynomial")) {
+      polynomOrderLabel->setText(tr("Polynomial Order"));
+      polynomOrderLabel->show();
+      polynomOrderBox->show();
+    }
+
+    d_current_fit = d_built_in_functions[function];
+    explainBox->setText(d_current_fit->formula());
+    setFunction(boxUseBuiltIn->isChecked());
+  } else if (categoryBox->currentRow() == 0) {
+    if (d_user_functions.size() > function) {
+      d_current_fit = d_user_functions[function];
+      explainBox->setText(d_current_fit->formula());
+    } else
+      explainBox->clear();
+    setFunction(boxUseBuiltIn->isChecked());
+  } else if (categoryBox->currentRow() == 3) {
+    if (d_plugins.size() > 0) {
+      d_current_fit = d_plugins[function];
+      explainBox->setText(d_current_fit->formula());
+      setFunction(boxUseBuiltIn->isChecked());
+    } else
+      explainBox->clear();
+  }
 }
 
-void FitDialog::addFunction()
-{
-	QString f = explainBox->toPlainText();
-	if (categoryBox->currentRow() == 2){//basic parser function
-		f = f.left(f.indexOf("(", 0)+1);
-		if (editBox->textCursor().hasSelection()){
-			QString markedText=editBox->textCursor().selectedText();
-			editBox->insertPlainText(f+markedText+")");
-		} else
-			editBox->insertPlainText(f+")");
-	}else
-		editBox->insertPlainText(f);
-
-	editBox->setFocus();
+void FitDialog::addFunction() {
+  QString f = explainBox->toPlainText();
+  if (categoryBox->currentRow() == 2) { // basic parser function
+    f = f.left(f.indexOf("(", 0) + 1);
+    if (editBox->textCursor().hasSelection()) {
+      QString markedText = editBox->textCursor().selectedText();
+      editBox->insertPlainText(f + markedText + ")");
+    } else
+      editBox->insertPlainText(f + ")");
+  } else
+    editBox->insertPlainText(f);
+
+  editBox->setFocus();
 }
 
-void FitDialog::addFunctionName()
-{
-	if (funcBox->count() > 0){
-		editBox->insertPlainText(funcBox->currentItem()->text());
-		editBox->setFocus();
-	}
+void FitDialog::addFunctionName() {
+  if (funcBox->count() > 0) {
+    editBox->insertPlainText(funcBox->currentItem()->text());
+    editBox->setFocus();
+  }
 }
 
 void FitDialog::accept() {
@@ -1181,145 +1198,134 @@ void FitDialog::accept() {
   }
 }
 
-void FitDialog::modifyGuesses(double* initVal)
-{
-	if (!d_current_fit)
-		return;
-
-	QString fitName = d_current_fit->objectName();
-	if (fitName == tr("ExpDecay1"))
-		initVal[1] = 1/initVal[1];
-	else if (fitName == tr("ExpGrowth"))
-		initVal[1] = -1/initVal[1];
-	else if (fitName == tr("ExpDecay2")){
-		initVal[1] = 1/initVal[1];
-		initVal[3] = 1/initVal[3];
-	} else if (fitName == tr("ExpDecay3")){
-		initVal[1] = 1/initVal[1];
-		initVal[3] = 1/initVal[3];
-		initVal[5] = 1/initVal[5];
-	}
+void FitDialog::modifyGuesses(double *initVal) {
+  if (!d_current_fit)
+    return;
+
+  QString fitName = d_current_fit->objectName();
+  if (fitName == tr("ExpDecay1"))
+    initVal[1] = 1 / initVal[1];
+  else if (fitName == tr("ExpGrowth"))
+    initVal[1] = -1 / initVal[1];
+  else if (fitName == tr("ExpDecay2")) {
+    initVal[1] = 1 / initVal[1];
+    initVal[3] = 1 / initVal[3];
+  } else if (fitName == tr("ExpDecay3")) {
+    initVal[1] = 1 / initVal[1];
+    initVal[3] = 1 / initVal[3];
+    initVal[5] = 1 / initVal[5];
+  }
 }
 
-void FitDialog::changeDataRange()
-{
-	double start = d_graph->selectedXStartValue();
-	double end = d_graph->selectedXEndValue();
-	boxFrom->setValue(QMIN(start, end));
-	boxTo->setValue(QMAX(start, end));
+void FitDialog::changeDataRange() {
+  double start = d_graph->selectedXStartValue();
+  double end = d_graph->selectedXEndValue();
+  boxFrom->setValue(QMIN(start, end));
+  boxTo->setValue(QMAX(start, end));
 }
 
-void FitDialog::setSrcTables(QList<MdiSubWindow*> tables)
-{
-	if (tables.isEmpty()){
-		tableNamesBox->addItem(tr("No data tables"));
-		colNamesBox->addItem(tr("No data tables"));
-		return;
-	}
-
-	srcTables = tables;
-	tableNamesBox->clear();
-	foreach(MdiSubWindow *w, srcTables)
-		tableNamesBox->addItem(w->objectName());
-
-	tableNamesBox->setCurrentIndex(tableNamesBox->findText(boxCurve->currentText().split("_", QString::SkipEmptyParts)[0]));
-	selectSrcTable(tableNamesBox->currentIndex());
+void FitDialog::setSrcTables(QList<MdiSubWindow *> tables) {
+  if (tables.isEmpty()) {
+    tableNamesBox->addItem(tr("No data tables"));
+    colNamesBox->addItem(tr("No data tables"));
+    return;
+  }
+
+  srcTables = tables;
+  tableNamesBox->clear();
+  foreach (MdiSubWindow *w, srcTables)
+    tableNamesBox->addItem(w->objectName());
+
+  tableNamesBox->setCurrentIndex(tableNamesBox->findText(
+      boxCurve->currentText().split("_", QString::SkipEmptyParts)[0]));
+  selectSrcTable(tableNamesBox->currentIndex());
 }
 
-void FitDialog::selectSrcTable(int tabnr)
-{
-	colNamesBox->clear();
+void FitDialog::selectSrcTable(int tabnr) {
+  colNamesBox->clear();
 
-	if (tabnr >= 0 && tabnr < srcTables.count()){
-    Table *t = dynamic_cast<Table*>(srcTables.at(tabnr));
-		if (t)
-			colNamesBox->addItems(t->colNames());
-	}
+  if (tabnr >= 0 && tabnr < srcTables.count()) {
+    Table *t = dynamic_cast<Table *>(srcTables.at(tabnr));
+    if (t)
+      colNamesBox->addItems(t->colNames());
+  }
 }
 
-void FitDialog::enableWeightingParameters(int index)
-{
-	if (index == Fit::Dataset){
-		tableNamesBox->setEnabled(true);
-		colNamesBox->setEnabled(true);
-	} else {
-		tableNamesBox->setEnabled(false);
-		colNamesBox->setEnabled(false);
-	}
+void FitDialog::enableWeightingParameters(int index) {
+  if (index == Fit::Dataset) {
+    tableNamesBox->setEnabled(true);
+    colNamesBox->setEnabled(true);
+  } else {
+    tableNamesBox->setEnabled(false);
+    colNamesBox->setEnabled(false);
+  }
 }
 
-void FitDialog::closeEvent (QCloseEvent * e)
-{							
-    if (d_preview_curve){
-        d_preview_curve->detach();
-        d_graph->replot();
-        delete d_preview_curve;
-    }
+void FitDialog::closeEvent(QCloseEvent *e) {
+  if (d_preview_curve) {
+    d_preview_curve->detach();
+    d_graph->replot();
+    delete d_preview_curve;
+  }
 
-	if(d_current_fit && plotLabelBox->isChecked())
-		d_current_fit->showLegend();
+  if (d_current_fit && plotLabelBox->isChecked())
+    d_current_fit->showLegend();
 
-	e->accept();
+  e->accept();
 }
 
-void FitDialog::enableApplyChanges(int)
-{
-	btnApply->setEnabled(true);
-}
+void FitDialog::enableApplyChanges(int) { btnApply->setEnabled(true); }
 
-void FitDialog::deleteFitCurves()
-{
-	d_graph->deleteFitCurves();
-	boxCurve->clear();
-	boxCurve->addItems(d_graph->curvesList());
+void FitDialog::deleteFitCurves() {
+  d_graph->deleteFitCurves();
+  boxCurve->clear();
+  boxCurve->addItems(d_graph->curvesList());
 }
 
-void FitDialog::resetFunction()
-{
-	boxName->clear();
-	boxParam->clear();
-	editBox->clear();
+void FitDialog::resetFunction() {
+  boxName->clear();
+  boxParam->clear();
+  editBox->clear();
 }
 
-void FitDialog::initBuiltInFunctions()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+void FitDialog::initBuiltInFunctions() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
   if (!app) {
-    throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+    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);
-	d_built_in_functions << new TwoExpFit(app, d_graph);
-	d_built_in_functions << new ThreeExpFit(app, d_graph);
-	d_built_in_functions << new ExponentialFit(app, d_graph, true);
+  d_built_in_functions << new SigmoidalFit(app, d_graph);
+  d_built_in_functions << new ExponentialFit(app, d_graph);
+  d_built_in_functions << new TwoExpFit(app, d_graph);
+  d_built_in_functions << new ThreeExpFit(app, d_graph);
+  d_built_in_functions << new ExponentialFit(app, d_graph, true);
 
-	MultiPeakFit *fit = new MultiPeakFit(app, d_graph, MultiPeakFit::Gauss);
-	fit->enablePeakCurves(app->generatePeakCurves);
-	fit->setPeakCurvesColor(app->peakCurvesColor);
-	d_built_in_functions << fit;
+  MultiPeakFit *fit = new MultiPeakFit(app, d_graph, MultiPeakFit::Gauss);
+  fit->enablePeakCurves(app->generatePeakCurves);
+  fit->setPeakCurvesColor(app->peakCurvesColor);
+  d_built_in_functions << fit;
 
-	d_built_in_functions << new GaussAmpFit(app, d_graph);
-	d_built_in_functions << new LinearFit(app, d_graph);
-	d_built_in_functions << new LinearSlopeFit(app, d_graph);
-	d_built_in_functions << new LogisticFit(app, d_graph);
+  d_built_in_functions << new GaussAmpFit(app, d_graph);
+  d_built_in_functions << new LinearFit(app, d_graph);
+  d_built_in_functions << new LinearSlopeFit(app, d_graph);
+  d_built_in_functions << new LogisticFit(app, d_graph);
 
-	fit = new MultiPeakFit(app, d_graph, MultiPeakFit::Lorentz);
-	fit->enablePeakCurves(app->generatePeakCurves);
-	fit->setPeakCurvesColor(app->peakCurvesColor);
-	d_built_in_functions << fit;
+  fit = new MultiPeakFit(app, d_graph, MultiPeakFit::Lorentz);
+  fit->enablePeakCurves(app->generatePeakCurves);
+  fit->setPeakCurvesColor(app->peakCurvesColor);
+  d_built_in_functions << fit;
 
-	d_built_in_functions << new PolynomialFit(app, d_graph, 1);
+  d_built_in_functions << new PolynomialFit(app, d_graph, 1);
 
-    QString path = app->fitModelsPath + "/";
-    foreach(Fit *fit, d_built_in_functions)
-        fit->setFileName(path + fit->objectName() + ".fit");
+  QString path = app->fitModelsPath + "/";
+  foreach (Fit *fit, d_built_in_functions)
+    fit->setFileName(path + fit->objectName() + ".fit");
 }
 
-void FitDialog::setNumPeaks(int peaks)
-{
-	if (d_current_fit->objectName() == tr("Gauss") ||
-		d_current_fit->objectName() == tr("Lorentz")) {
+void FitDialog::setNumPeaks(int peaks) {
+  if (d_current_fit->objectName() == tr("Gauss") ||
+      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")) {
@@ -1327,203 +1333,202 @@ void FitDialog::setNumPeaks(int peaks)
       fit->setOrder(peaks);
   }
 
-	int index = funcBox->currentRow();
-	d_built_in_functions[index] = d_current_fit;
-	showExpression(index);
+  int index = funcBox->currentRow();
+  d_built_in_functions[index] = d_current_fit;
+  showExpression(index);
 }
 
-QStringList FitDialog::builtInFunctionNames()
-{
-	QStringList lst;
-	foreach(Fit *fit, d_built_in_functions)
-		lst << fit->objectName();
-	return lst;
+QStringList FitDialog::builtInFunctionNames() {
+  QStringList lst;
+  foreach (Fit *fit, d_built_in_functions)
+    lst << fit->objectName();
+  return lst;
 }
 
-void FitDialog::loadUserFunctions()
-{
-    d_user_functions.clear();
+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.");
+    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);
-	QStringList names;
-	for (int i=0; i<lst.count(); i++){
-        NonLinearFit *fit = new NonLinearFit(app, d_graph);
-        if (fit->load(path + lst[i])){
-            if (fit->type() == Fit::User){
-                d_user_functions << fit;
-                names << fit->objectName();
-            } else if (fit->type() == Fit::BuiltIn){
-                QStringList lst = builtInFunctionNames();
-                int index = lst.indexOf(fit->objectName());
-                if (index >= 0 && index < d_built_in_functions.size()){
-                    Fit *f = d_built_in_functions[index];
-                    f->setFileName(fit->fileName());
-                    for (int i=0; i<f->numParameters(); i++)
-                        f->setInitialGuess(i, fit->initialGuess(i));
-                }
-            } else if (fit->type() == Fit::Plugin){
-                QStringList lst = plugInNames();
-                int index = lst.indexOf(fit->objectName());
-                if (index >= 0 && index < d_plugins.size()){
-                    Fit *f = d_plugins[index];
-                    f->setFileName(fit->fileName());
-                    for (int i=0; i<f->numParameters(); i++)
-                        f->setInitialGuess(i, fit->initialGuess(i));
-                }
-            }
+  QString path = app->fitModelsPath + "/";
+  QDir dir(path);
+  QStringList lst = dir.entryList(QDir::Files | QDir::NoSymLinks, QDir::Name);
+  QStringList names;
+  for (int i = 0; i < lst.count(); i++) {
+    NonLinearFit *fit = new NonLinearFit(app, d_graph);
+    if (fit->load(path + lst[i])) {
+      if (fit->type() == Fit::User) {
+        d_user_functions << fit;
+        names << fit->objectName();
+      } else if (fit->type() == Fit::BuiltIn) {
+        QStringList lst = builtInFunctionNames();
+        int index = lst.indexOf(fit->objectName());
+        if (index >= 0 && index < d_built_in_functions.size()) {
+          Fit *f = d_built_in_functions[index];
+          f->setFileName(fit->fileName());
+          for (int i = 0; i < f->numParameters(); i++)
+            f->setInitialGuess(i, fit->initialGuess(i));
         }
+      } else if (fit->type() == Fit::Plugin) {
+        QStringList lst = plugInNames();
+        int index = lst.indexOf(fit->objectName());
+        if (index >= 0 && index < d_plugins.size()) {
+          Fit *f = d_plugins[index];
+          f->setFileName(fit->fileName());
+          for (int i = 0; i < f->numParameters(); i++)
+            f->setInitialGuess(i, fit->initialGuess(i));
+        }
+      }
     }
+  }
 
-    if (d_user_functions.size() > 0){
-        funcBox->addItems(names);
-        funcBox->setCurrentRow(0);
-        boxUseBuiltIn->setEnabled(true);
-    } else
-        boxUseBuiltIn->setEnabled(false);
+  if (d_user_functions.size() > 0) {
+    funcBox->addItems(names);
+    funcBox->setCurrentRow(0);
+    boxUseBuiltIn->setEnabled(true);
+  } else
+    boxUseBuiltIn->setEnabled(false);
 }
 
-QStringList FitDialog::userFunctionNames()
-{
-	QStringList lst;
-	foreach(Fit *fit, d_user_functions)
-		lst << fit->objectName();
-	return lst;
+QStringList FitDialog::userFunctionNames() {
+  QStringList lst;
+  foreach (Fit *fit, d_user_functions)
+    lst << fit->objectName();
+  return lst;
 }
 
-void FitDialog::saveInitialGuesses()
-{
-    if (!d_current_fit)
-        return;
+void FitDialog::saveInitialGuesses() {
+  if (!d_current_fit)
+    return;
 
-	int rows = boxParams->rowCount();
-    for (int i=0; i<rows; i++)
-        d_current_fit->setInitialGuess(i, boxParams_cellWidget<DoubleSpinBox>(i, 2)->value());
+  int rows = boxParams->rowCount();
+  for (int i = 0; i < rows; i++)
+    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 {
+  QString fileName = d_current_fit->fileName();
+  if (!fileName.isEmpty())
+    d_current_fit->save(fileName);
+  else {
     ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
     if (!app) {
-      throw std::logic_error("Parent of FitDialog is not ApplicationWindow as expected.");
+      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"),
-                                app->fitModelsPath + "/" + d_current_fit->objectName(), filter);
-		if (!fn.isEmpty()){
-            QFileInfo fi(fn);
-            QString baseName = fi.fileName();
-            if (!baseName.contains("."))
-                fn.append(".fit");
-
-            if (d_current_fit->save(fn))
-                d_user_functions.append(d_current_fit);
-          }
+    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"),
+        app->fitModelsPath + "/" + d_current_fit->objectName(), filter);
+    if (!fn.isEmpty()) {
+      QFileInfo fi(fn);
+      QString baseName = fi.fileName();
+      if (!baseName.contains("."))
+        fn.append(".fit");
+
+      if (d_current_fit->save(fn))
+        d_user_functions.append(d_current_fit);
     }
+  }
 }
 
-QStringList FitDialog::plugInNames()
-{
-	QStringList lst;
-	foreach(Fit *fit, d_plugins)
-		lst << fit->objectName();
-	return lst;
+QStringList FitDialog::plugInNames() {
+  QStringList lst;
+  foreach (Fit *fit, d_plugins)
+    lst << fit->objectName();
+  return lst;
 }
 
-void FitDialog::returnToFitPage()
-{
-	applyChanges();
-	tw->setCurrentWidget(fitPage);
+void FitDialog::returnToFitPage() {
+  applyChanges();
+  tw->setCurrentWidget(fitPage);
 }
 
-void FitDialog::updatePreview()
-{
-    if (!previewBox->isChecked() && d_preview_curve){
-        d_preview_curve->detach();
-        d_graph->replot();
-        delete d_preview_curve;
-        d_preview_curve = 0;
-        return;
-    }
+void FitDialog::updatePreview() {
+  if (!previewBox->isChecked() && d_preview_curve) {
+    d_preview_curve->detach();
+    d_graph->replot();
+    delete d_preview_curve;
+    d_preview_curve = 0;
+    return;
+  }
 
-    if (!d_current_fit || !previewBox->isChecked())
-        return;
+  if (!d_current_fit || !previewBox->isChecked())
+    return;
 
-    int d_points = generatePointsBox->value();
-    QVarLengthArray<double> X(d_points), Y(d_points);//double X[d_points], Y[d_points];
-    int p = boxParams->rowCount();
-    QVarLengthArray<double> parameters(p);//double parameters[p];
-    for (int i=0; i<p; i++)
-        parameters[i] = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
-    if (d_current_fit->type() == Fit::BuiltIn)
-        modifyGuesses(parameters.data());//modifyGuesses(parameters);
-
-    double x0 = boxFrom->value();
-    double step = (boxTo->value() - x0)/(d_points - 1);
-    for (int i=0; i<d_points; i++){
-        double x = x0 + i*step;
-        X[i] = x;
-        Y[i] = d_current_fit->eval(parameters.data(), x);//Y[i] = d_current_fit->eval(parameters, x);
-    }
+  int d_points = generatePointsBox->value();
+  QVarLengthArray<double> X(d_points),
+      Y(d_points); // double X[d_points], Y[d_points];
+  int p = boxParams->rowCount();
+  QVarLengthArray<double> parameters(p); // double parameters[p];
+  for (int i = 0; i < p; i++)
+    parameters[i] = boxParams_cellWidget<DoubleSpinBox>(i, 2)->value();
+  if (d_current_fit->type() == Fit::BuiltIn)
+    modifyGuesses(parameters.data()); // modifyGuesses(parameters);
+
+  double x0 = boxFrom->value();
+  double step = (boxTo->value() - x0) / (d_points - 1);
+  for (int i = 0; i < d_points; i++) {
+    double x = x0 + i * step;
+    X[i] = x;
+    Y[i] = d_current_fit->eval(parameters.data(),
+                               x); // Y[i] = d_current_fit->eval(parameters, x);
+  }
 
-	if (!d_preview_curve){
-        d_preview_curve = new QwtPlotCurve();
-		d_preview_curve->setRenderHint(QwtPlotItem::RenderAntialiased, d_graph->antialiasing());
-        d_preview_curve->attach(d_graph->plotWidget());
-	}
+  if (!d_preview_curve) {
+    d_preview_curve = new QwtPlotCurve();
+    d_preview_curve->setRenderHint(QwtPlotItem::RenderAntialiased,
+                                   d_graph->antialiasing());
+    d_preview_curve->attach(d_graph->plotWidget());
+  }
 
-    d_preview_curve->setPen(QPen(ColorBox::color(boxColor->currentIndex()), 1));
-    d_preview_curve->setData(X.data(), Y.data(), d_points);//d_preview_curve->setData(X, Y, d_points);
-    d_graph->replot();
+  d_preview_curve->setPen(QPen(ColorBox::color(boxColor->currentIndex()), 1));
+  d_preview_curve->setData(
+      X.data(), Y.data(),
+      d_points); // d_preview_curve->setData(X, Y, d_points);
+  d_graph->replot();
 }
 
-void FitDialog::showParameterRange(bool on)
-{
-    if (on){
-        boxParams->showColumn(1);
-        boxParams->showColumn(3);
-    } else {
-        boxParams->hideColumn(1);
-        boxParams->hideColumn(3);
-    }
+void FitDialog::showParameterRange(bool on) {
+  if (on) {
+    boxParams->showColumn(1);
+    boxParams->showColumn(3);
+  } else {
+    boxParams->hideColumn(1);
+    boxParams->hideColumn(3);
+  }
 }
 
-QString FitDialog::parseFormula(const QString& s)
-{
-	QString formula = s;
-
-	QStringList lst = userFunctionNames();
-	for (int i=0; i<lst.count(); i++){
-		if (formula.contains(lst[i]))
-			formula.replace(lst[i], "(" + (d_user_functions[i])->formula() + ")");
-	}
-
-	QStringList builtInFunctions = builtInFunctionNames();
-	for (int i=0; i<(int)builtInFunctions.count(); i++){
-		if (formula.contains(builtInFunctions[i])){
-			Fit *fit = d_built_in_functions[i];
-			formula.replace(builtInFunctions[i], "(" + fit->formula() + ")");
-		}
-	}
-	return formula;
+QString FitDialog::parseFormula(const QString &s) {
+  QString formula = s;
+
+  QStringList lst = userFunctionNames();
+  for (int i = 0; i < lst.count(); i++) {
+    if (formula.contains(lst[i]))
+      formula.replace(lst[i], "(" + (d_user_functions[i])->formula() + ")");
+  }
+
+  QStringList builtInFunctions = builtInFunctionNames();
+  for (int i = 0; i < (int)builtInFunctions.count(); i++) {
+    if (formula.contains(builtInFunctions[i])) {
+      Fit *fit = d_built_in_functions[i];
+      formula.replace(builtInFunctions[i], "(" + fit->formula() + ")");
+    }
+  }
+  return formula;
 }
 
 bool FitDialog::isOfType(const QObject *obj, const char *toCompare) const {
   return strcmp(obj->metaObject()->className(), toCompare) == 0;
 }
 
-template<class Widget>
-Widget* FitDialog::boxParams_cellWidget(int i, int j) const {
-  Widget *w = dynamic_cast<Widget*>(boxParams->cellWidget(i, j));
+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/MantidPlot/src/FitDialog.h b/MantidPlot/src/FitDialog.h
index d4b845caea9dc695c08cfc3918a78e4cfc088bbe..b23d4c33a8f822b062f8b324537774cc03b890a5 100644
--- a/MantidPlot/src/FitDialog.h
+++ b/MantidPlot/src/FitDialog.h
@@ -52,111 +52,109 @@ class DoubleSpinBox;
 class QwtPlotCurve;
 
 //! Fit Wizard
-class FitDialog : public QDialog
-{
-    Q_OBJECT
+class FitDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    FitDialog(Graph *g, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  FitDialog(Graph *g, QWidget *parent = 0, Qt::WFlags fl = 0);
 
-    void setSrcTables(QList<MdiSubWindow*> tables);
+  void setSrcTables(QList<MdiSubWindow *> tables);
 
 protected:
   void closeEvent(QCloseEvent *e) override;
-    void initFitPage();
-	void initEditPage();
-	void initAdvancedPage();
+  void initFitPage();
+  void initEditPage();
+  void initAdvancedPage();
 
 private slots:
   void accept() override;
-    //! Clears the function editor, the parameter names and the function name
-    void resetFunction();
-	void showFitPage();
-	void showEditPage();
-	void showAdvancedPage();
-	void showFunctionsList(int category);
-	void showParseFunctions();
-	void showExpression(int function);
-	void addFunction();
-	void addFunctionName();
-	void setFunction(bool ok);
-	void saveUserFunction();
-	void removeUserFunction();
-	void setGraph(Graph *g);
-	void activateCurve(const QString& curveName);
-	void chooseFolder();
-	void changeDataRange();
-	void selectSrcTable(int tabnr);
-	void enableWeightingParameters(int index);
-	void showPointsBox(bool);
-	void showParametersTable();
-	void showCovarianceMatrix();
+  //! Clears the function editor, the parameter names and the function name
+  void resetFunction();
+  void showFitPage();
+  void showEditPage();
+  void showAdvancedPage();
+  void showFunctionsList(int category);
+  void showParseFunctions();
+  void showExpression(int function);
+  void addFunction();
+  void addFunctionName();
+  void setFunction(bool ok);
+  void saveUserFunction();
+  void removeUserFunction();
+  void setGraph(Graph *g);
+  void activateCurve(const QString &curveName);
+  void chooseFolder();
+  void changeDataRange();
+  void selectSrcTable(int tabnr);
+  void enableWeightingParameters(int index);
+  void showPointsBox(bool);
+  void showParametersTable();
+  void showCovarianceMatrix();
 
-	//! Applies the user changes to the numerical format of the output results
-	void applyChanges();
+  //! Applies the user changes to the numerical format of the output results
+  void applyChanges();
 
-	//! Deletes the result fit curves from the plot
-	void deleteFitCurves();
+  //! Deletes the result fit curves from the plot
+  void deleteFitCurves();
 
-    //! Enable the "Apply" button
-	void enableApplyChanges(int = 0);
-	void setNumPeaks(int peaks);
-	void saveInitialGuesses();
-	void returnToFitPage();
-	void updatePreview();
-	void showParameterRange(bool);
+  //! Enable the "Apply" button
+  void enableApplyChanges(int = 0);
+  void setNumPeaks(int peaks);
+  void saveInitialGuesses();
+  void returnToFitPage();
+  void updatePreview();
+  void showParameterRange(bool);
 
 private:
-	bool isOfType(const QObject *obj, const char *toCompare) const;
-	void loadPlugins();
-	void loadUserFunctions();
-	void initBuiltInFunctions();
-	void modifyGuesses(double* initVal);
-	QStringList builtInFunctionNames();
-	QStringList userFunctionNames();
-	QStringList plugInNames();
-	QString parseFormula(const QString& s);
-  template<class Widget>
-  Widget* boxParams_cellWidget(int i, int j) const ;
+  bool isOfType(const QObject *obj, const char *toCompare) const;
+  void loadPlugins();
+  void loadUserFunctions();
+  void initBuiltInFunctions();
+  void modifyGuesses(double *initVal);
+  QStringList builtInFunctionNames();
+  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;
-	Table *d_param_table;
-	QList <Fit*> d_user_functions, d_built_in_functions, d_plugins;
-	QList <MdiSubWindow*> srcTables;
-	QwtPlotCurve *d_preview_curve;
+  Fit *d_current_fit;
+  Graph *d_graph;
+  Table *d_param_table;
+  QList<Fit *> d_user_functions, d_built_in_functions, d_plugins;
+  QList<MdiSubWindow *> srcTables;
+  QwtPlotCurve *d_preview_curve;
 
-    QCheckBox* boxUseBuiltIn;
-	QStackedWidget* tw;
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel1;
-	QPushButton* buttonCancel2;
-	QPushButton* buttonCancel3;
-	QPushButton* buttonAdvanced;
-	QPushButton* buttonClear;
-	QPushButton* buttonPlugins;
-	QPushButton* btnBack;
-	QPushButton* btnSaveGuesses;
-	QComboBox* boxCurve;
-	QComboBox* boxAlgorithm;
-	QTableWidget* boxParams;
-	DoubleSpinBox* boxFrom;
-	DoubleSpinBox* boxTo;
-	DoubleSpinBox* boxTolerance;
-	QSpinBox* boxPoints, *generatePointsBox, *boxPrecision, *polynomOrderBox;
-	QWidget *fitPage, *editPage, *advancedPage;
-	QTextEdit *editBox, *explainBox, *boxFunction;
-	QListWidget *categoryBox, *funcBox;
-	QLineEdit *boxName, *boxParam;
-	QLabel *lblFunction, *lblPoints, *polynomOrderLabel;
-	QPushButton *btnAddFunc, *btnDelFunc, *btnContinue, *btnApply;
-	QPushButton *buttonEdit, *btnAddTxt, *btnAddName, *btnDeleteFitCurves;
-	ColorBox* boxColor;
-	QComboBox *boxWeighting, *tableNamesBox, *colNamesBox;
-	QRadioButton *generatePointsBtn, *samePointsBtn;
-	QPushButton *btnParamTable, *btnCovMatrix, *btnParamRange;
-	QLineEdit *covMatrixName, *paramTableName;
-	QCheckBox *plotLabelBox, *logBox, *scaleErrorsBox, *globalParamTableBox;
-	QCheckBox *previewBox;
+  QCheckBox *boxUseBuiltIn;
+  QStackedWidget *tw;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel1;
+  QPushButton *buttonCancel2;
+  QPushButton *buttonCancel3;
+  QPushButton *buttonAdvanced;
+  QPushButton *buttonClear;
+  QPushButton *buttonPlugins;
+  QPushButton *btnBack;
+  QPushButton *btnSaveGuesses;
+  QComboBox *boxCurve;
+  QComboBox *boxAlgorithm;
+  QTableWidget *boxParams;
+  DoubleSpinBox *boxFrom;
+  DoubleSpinBox *boxTo;
+  DoubleSpinBox *boxTolerance;
+  QSpinBox *boxPoints, *generatePointsBox, *boxPrecision, *polynomOrderBox;
+  QWidget *fitPage, *editPage, *advancedPage;
+  QTextEdit *editBox, *explainBox, *boxFunction;
+  QListWidget *categoryBox, *funcBox;
+  QLineEdit *boxName, *boxParam;
+  QLabel *lblFunction, *lblPoints, *polynomOrderLabel;
+  QPushButton *btnAddFunc, *btnDelFunc, *btnContinue, *btnApply;
+  QPushButton *buttonEdit, *btnAddTxt, *btnAddName, *btnDeleteFitCurves;
+  ColorBox *boxColor;
+  QComboBox *boxWeighting, *tableNamesBox, *colNamesBox;
+  QRadioButton *generatePointsBtn, *samePointsBtn;
+  QPushButton *btnParamTable, *btnCovMatrix, *btnParamRange;
+  QLineEdit *covMatrixName, *paramTableName;
+  QCheckBox *plotLabelBox, *logBox, *scaleErrorsBox, *globalParamTableBox;
+  QCheckBox *previewBox;
 };
 #endif // FITDIALOG_H
diff --git a/MantidPlot/src/FitModelHandler.cpp b/MantidPlot/src/FitModelHandler.cpp
index ae11ee02abfca4e84612e2feda14fd18c152de08..3b74687a147abd4a749fb6d78317318404a72104 100644
--- a/MantidPlot/src/FitModelHandler.cpp
+++ b/MantidPlot/src/FitModelHandler.cpp
@@ -31,67 +31,58 @@
 
 #include <QMessageBox>
 
-FitModelHandler::FitModelHandler(Fit *fit)
-     : d_fit(fit)
- {
-     metFitTag = false;
- }
+FitModelHandler::FitModelHandler(Fit *fit) : d_fit(fit) { metFitTag = false; }
 
- bool FitModelHandler::startElement(const QString & /* namespaceURI */,
-                                const QString & /* localName */,
-                                const QString &qName,
-                                const QXmlAttributes &attributes)
- {
-     if (!metFitTag && qName != "fit") {
-         errorStr = QObject::tr("The file is not an QtiPlot fit model file.");
-         return false;
-     }
+bool FitModelHandler::startElement(const QString & /* namespaceURI */,
+                                   const QString & /* localName */,
+                                   const QString &qName,
+                                   const QXmlAttributes &attributes) {
+  if (!metFitTag && qName != "fit") {
+    errorStr = QObject::tr("The file is not an QtiPlot fit model file.");
+    return false;
+  }
 
-     if (qName == "fit") {
-         QString version = attributes.value("version");
-         if (!version.isEmpty() && version != "1.0") {
-             errorStr = QObject::tr("The file is not an QtiPlot fit model version 1.0 file.");
-             return false;
-         }
-         metFitTag = true;
-     }
+  if (qName == "fit") {
+    QString version = attributes.value("version");
+    if (!version.isEmpty() && version != "1.0") {
+      errorStr =
+          QObject::tr("The file is not an QtiPlot fit model version 1.0 file.");
+      return false;
+    }
+    metFitTag = true;
+  }
 
-     currentText.clear();
-     return true;
- }
+  currentText.clear();
+  return true;
+}
 
 bool FitModelHandler::endElement(const QString & /* namespaceURI */,
-                              const QString & /* localName */,
-                              const QString &qName)
-{
-    if (qName == "model")
-        d_fit->setObjectName(currentText);
-    else if (qName == "type")
-        d_fit->setType((Fit::FitType)currentText.toInt());
-    else if (qName == "function")
-        d_formula = currentText.replace("&lt;", "<").replace("&gt;", ">");
-    else if (qName == "name" && !currentText.isEmpty())
-        d_parameters << currentText;
-    else if (qName == "explanation")
-        d_explanations << currentText;
-    else if (qName == "value")
-        d_values.append(currentText.toDouble());
-    else if (qName == "fit"){
-        d_fit->setParametersList(d_parameters);
-        d_fit->setFormula(d_formula);
-        d_fit->setInitialGuesses(d_values.data());
-        d_fit->setParameterExplanations(d_explanations);
-     }
-     return true;
- }
+                                 const QString & /* localName */,
+                                 const QString &qName) {
+  if (qName == "model")
+    d_fit->setObjectName(currentText);
+  else if (qName == "type")
+    d_fit->setType((Fit::FitType)currentText.toInt());
+  else if (qName == "function")
+    d_formula = currentText.replace("&lt;", "<").replace("&gt;", ">");
+  else if (qName == "name" && !currentText.isEmpty())
+    d_parameters << currentText;
+  else if (qName == "explanation")
+    d_explanations << currentText;
+  else if (qName == "value")
+    d_values.append(currentText.toDouble());
+  else if (qName == "fit") {
+    d_fit->setParametersList(d_parameters);
+    d_fit->setFormula(d_formula);
+    d_fit->setInitialGuesses(d_values.data());
+    d_fit->setParameterExplanations(d_explanations);
+  }
+  return true;
+}
 
- bool FitModelHandler::characters(const QString &str)
- {
-     currentText += str;
-     return true;
- }
+bool FitModelHandler::characters(const QString &str) {
+  currentText += str;
+  return true;
+}
 
- QString FitModelHandler::errorString() const
- {
-     return errorStr;
- }
+QString FitModelHandler::errorString() const { return errorStr; }
diff --git a/MantidPlot/src/FitModelHandler.h b/MantidPlot/src/FitModelHandler.h
index ab8227ff7b84088a3ad11fa1beeac8e3ffc58814..a10013f414e7ccd21954a614116ca02090332594 100644
--- a/MantidPlot/src/FitModelHandler.h
+++ b/MantidPlot/src/FitModelHandler.h
@@ -34,8 +34,7 @@
 
 class Fit;
 
-class FitModelHandler : public QXmlDefaultHandler
-{
+class FitModelHandler : public QXmlDefaultHandler {
 public:
   explicit FitModelHandler(Fit *fit);
 
@@ -49,14 +48,14 @@ public:
   QString errorString() const override;
 
 private:
-    Fit* d_fit;
-    bool metFitTag;
-    QString currentText;
-    QString errorStr;
-    QString d_formula;
-    QStringList d_parameters;
-    QStringList d_explanations;
-    QVarLengthArray<double> d_values;
+  Fit *d_fit;
+  bool metFitTag;
+  QString currentText;
+  QString errorStr;
+  QString d_formula;
+  QStringList d_parameters;
+  QStringList d_explanations;
+  QVarLengthArray<double> d_values;
 };
 
 #endif
diff --git a/MantidPlot/src/FloatingWindow.cpp b/MantidPlot/src/FloatingWindow.cpp
index 024b91340093affa43f343e6d54a0606fe6323e7..070b8d56704d63f1aedc8a7c3195849c5399b21d 100644
--- a/MantidPlot/src/FloatingWindow.cpp
+++ b/MantidPlot/src/FloatingWindow.cpp
@@ -18,20 +18,18 @@
 /**
  * Constructor.
  */
-FloatingWindow::FloatingWindow(ApplicationWindow* appWindow, Qt::WindowFlags f):
+FloatingWindow::FloatingWindow(ApplicationWindow *appWindow, Qt::WindowFlags f)
+    :
 #ifdef Q_OS_WIN
-QMainWindow(appWindow,f),
+      QMainWindow(appWindow, f),
 #else
-QMainWindow(NULL,f),
+      QMainWindow(NULL, f),
 #endif
-d_app(appWindow),
-m_draggingToTiledWindow(false),
-m_isInsideTiledWindow(false),
-m_dragMouseDown(false)
-{
+      d_app(appWindow), m_draggingToTiledWindow(false),
+      m_isInsideTiledWindow(false), m_dragMouseDown(false) {
   setFocusPolicy(Qt::StrongFocus);
   setWindowIcon(QIcon(":/MantidPlot_Icon_32offset.png"));
-  connect(appWindow,SIGNAL(shutting_down()),this,SLOT(close()));
+  connect(appWindow, SIGNAL(shutting_down()), this, SLOT(close()));
 #ifdef Q_OS_WIN
   // remember the flags
   m_flags = windowFlags();
@@ -43,74 +41,63 @@ m_dragMouseDown(false)
   setAttribute(Qt::WA_DeleteOnClose, false);
 }
 
-FloatingWindow::~FloatingWindow()
-{
-  //std::cerr << "Deleted FloatingWindow\n";
+FloatingWindow::~FloatingWindow() {
+  // std::cerr << "Deleted FloatingWindow\n";
 }
 
 /**
   * Returns the inner MdiSubWindow.
   */
-MdiSubWindow* FloatingWindow::mdiSubWindow() const
-{
-  return static_cast<MdiSubWindow*>(widget());
+MdiSubWindow *FloatingWindow::mdiSubWindow() const {
+  return static_cast<MdiSubWindow *>(widget());
 }
 
 /**
   * Returns the inner MdiSubWindow as a QWidget.(?)
   */
-QWidget* FloatingWindow::widget() const
-{
-  return static_cast<MdiSubWindowParent_t*>(centralWidget())->widget();
+QWidget *FloatingWindow::widget() const {
+  return static_cast<MdiSubWindowParent_t *>(centralWidget())->widget();
 }
 
 /**
  * Process state change events such as activation, minimizing or maximizing.
  */
-bool FloatingWindow::event(QEvent * e)
-{
-  if (e->type() == QEvent::WindowActivate)
-  {
+bool FloatingWindow::event(QEvent *e) {
+  if (e->type() == QEvent::WindowActivate) {
     // If FloatingWindow was activated by clicking on it we need to
     // let the application know about it
-    MdiSubWindow* w = dynamic_cast<MdiSubWindow*>(widget());
-    if (w && this != d_app->getActiveFloating())
-    {
-      // the second argument says that FloatingWindow must not be activated again
-      d_app->activateWindow(w,false);
+    MdiSubWindow *w = dynamic_cast<MdiSubWindow *>(widget());
+    if (w && this != d_app->getActiveFloating()) {
+      // the second argument says that FloatingWindow must not be activated
+      // again
+      d_app->activateWindow(w, false);
     }
-  }
-  else if (e->type() == QEvent::WindowStateChange)
-  {
-    if (this->isMinimized())
-    {
+  } else if (e->type() == QEvent::WindowStateChange) {
+    if (this->isMinimized()) {
 #ifdef Q_OS_WIN
-      // set parent to NULL wich makes it minimize nicely into a program bar icon
+      // set parent to NULL wich makes it minimize nicely into a program bar
+      // icon
       this->setParent(NULL);
       this->showMinimized();
 #endif
       mdiSubWindow()->setStatus(MdiSubWindow::Minimized);
       d_app->activateNewWindow();
-    }
-    else if ( !this->isMaximized() || !this->isMinimized() )
-    {
+    } else if (!this->isMaximized() || !this->isMinimized()) {
 #ifdef Q_OS_WIN
-      // re-parent to the main window making the floating window stay on top of it
-      if (this->parent() != d_app)
-      {
+      // re-parent to the main window making the floating window stay on top of
+      // it
+      if (this->parent() != d_app) {
         this->setParent(d_app);
         this->setWindowFlags(m_flags);
         this->showNormal();
       }
 #endif
       mdiSubWindow()->setStatus(MdiSubWindow::Normal);
-    }
-    else if (this->isMaximized())
-    {
+    } else if (this->isMaximized()) {
 #ifdef Q_OS_WIN
-      // re-parent to the main window making the floating window stay on top of it
-      if (this->parent() != d_app)
-      {
+      // re-parent to the main window making the floating window stay on top of
+      // it
+      if (this->parent() != d_app) {
         this->setParent(d_app);
         this->setWindowFlags(m_flags);
         this->showMaximized();
@@ -118,36 +105,27 @@ bool FloatingWindow::event(QEvent * e)
 #endif
       mdiSubWindow()->setStatus(MdiSubWindow::Maximized);
     }
-  }
-  else if (e->type() == QEvent::Close)
-  {
-    if (widget() && widget()->close())
-    {
+  } else if (e->type() == QEvent::Close) {
+    if (widget() && widget()->close()) {
       // forget about me and close
       d_app->removeFloatingWindow(this);
-    }
-    else
-    {
+    } else {
       // don't close
       e->ignore();
       return true;
     }
-  }
-  else if ( e->type() == QEvent::NonClientAreaMouseButtonPress )
-  {
+  } else if (e->type() == QEvent::NonClientAreaMouseButtonPress) {
     // User clicked the window title bar
     m_draggingToTiledWindow = true;
-    auto mu = static_cast<QMouseEvent*>(e);
+    auto mu = static_cast<QMouseEvent *>(e);
     m_dragStartPos = mu->pos();
-  }
-  else if ( e->type() == QEvent::NonClientAreaMouseMove )
-  {
-    // For some reason this event is fired when the user releases the mouse over the title bar
-    if ( m_draggingToTiledWindow && m_isInsideTiledWindow )
-    {
+  } else if (e->type() == QEvent::NonClientAreaMouseMove) {
+    // For some reason this event is fired when the user releases the mouse over
+    // the title bar
+    if (m_draggingToTiledWindow && m_isInsideTiledWindow) {
       m_draggingToTiledWindow = false;
       m_isInsideTiledWindow = false;
-      d_app->dropInTiledWindow( mdiSubWindow(), pos() + m_dragStartPos );
+      d_app->dropInTiledWindow(mdiSubWindow(), pos() + m_dragStartPos);
       return true;
     }
     m_draggingToTiledWindow = false;
@@ -156,15 +134,11 @@ bool FloatingWindow::event(QEvent * e)
   return QMainWindow::event(e);
 }
 
-void FloatingWindow::moveEvent(QMoveEvent *ev)
-{
-  if ( m_draggingToTiledWindow )
-  {
+void FloatingWindow::moveEvent(QMoveEvent *ev) {
+  if (m_draggingToTiledWindow) {
     // we are here if the window is being moved by the user
-    m_isInsideTiledWindow =  d_app->isInTiledWindow( ev->pos() + m_dragStartPos );
-  }
-  else
-  {
+    m_isInsideTiledWindow = d_app->isInTiledWindow(ev->pos() + m_dragStartPos);
+  } else {
     m_isInsideTiledWindow = false;
   }
 }
@@ -172,12 +146,10 @@ void FloatingWindow::moveEvent(QMoveEvent *ev)
 /**
   * Make this window stay on top
   */
-void FloatingWindow::setStaysOnTopFlag()
-{
+void FloatingWindow::setStaysOnTopFlag() {
   Qt::WindowFlags flags = windowFlags();
   Qt::WindowFlags new_flags = flags | Qt::WindowStaysOnTopHint;
-  if (new_flags != flags)
-  {
+  if (new_flags != flags) {
     setWindowFlags(new_flags);
     show();
   }
@@ -186,77 +158,64 @@ void FloatingWindow::setStaysOnTopFlag()
 /**
   * Make this window not stay on top
   */
-void FloatingWindow::removeStaysOnTopFlag()
-{
+void FloatingWindow::removeStaysOnTopFlag() {
   Qt::WindowFlags flags = windowFlags();
   Qt::WindowFlags new_flags = flags ^ Qt::WindowStaysOnTopHint;
-  if (new_flags != flags)
-  {
+  if (new_flags != flags) {
     setWindowFlags(new_flags);
     show();
   }
 }
 
 /** Sets the underlying MdiSubWindow */
-void FloatingWindow::setMdiSubWindow(MdiSubWindow* sw)
-{
+void FloatingWindow::setMdiSubWindow(MdiSubWindow *sw) {
   setWidget(sw);
   setWindowIcon(sw->windowIcon());
-  connect(sw,SIGNAL(dragMousePress(QPoint)),this,SLOT(dragMousePress(QPoint)));
-  connect(sw,SIGNAL(dragMouseRelease(QPoint)),this,SLOT(dragMouseRelease(QPoint)));
-  connect(sw,SIGNAL(dragMouseMove(QPoint)),this,SLOT(dragMouseMove(QPoint)));
+  connect(sw, SIGNAL(dragMousePress(QPoint)), this,
+          SLOT(dragMousePress(QPoint)));
+  connect(sw, SIGNAL(dragMouseRelease(QPoint)), this,
+          SLOT(dragMouseRelease(QPoint)));
+  connect(sw, SIGNAL(dragMouseMove(QPoint)), this, SLOT(dragMouseMove(QPoint)));
 }
 
-
 /** removes the underlying MdiSubWindow */
-void FloatingWindow::removeMdiSubWindow()
-{
-  MdiSubWindowParent_t* wrapper = dynamic_cast<MdiSubWindowParent_t*>(centralWidget());
-  if (wrapper)
-  {
+void FloatingWindow::removeMdiSubWindow() {
+  MdiSubWindowParent_t *wrapper =
+      dynamic_cast<MdiSubWindowParent_t *>(centralWidget());
+  if (wrapper) {
     wrapper->setWidget(NULL);
   }
 }
 
-QSize FloatingWindow::minimumSizeHint() const
-{
-  return QSize(200, 200);
-}
+QSize FloatingWindow::minimumSizeHint() const { return QSize(200, 200); }
 
 /** Sets the widget displayed in the FloatingWindow
  *
  * @param w :: MdiSubWindow being floated
  */
-void FloatingWindow::setWidget(QWidget* w)
-{
-  MdiSubWindowParent_t* wrapper = new MdiSubWindowParent_t(this);
+void FloatingWindow::setWidget(QWidget *w) {
+  MdiSubWindowParent_t *wrapper = new MdiSubWindowParent_t(this);
   wrapper->setWidget(w);
   setCentralWidget(wrapper);
 }
 
-void FloatingWindow::dragMousePress(QPoint pos)
-{
-  if ( d_app->hasTiledWindowOpen() )
-  {
+void FloatingWindow::dragMousePress(QPoint pos) {
+  if (d_app->hasTiledWindowOpen()) {
     m_dragMouseDown = true;
     m_dragStartPos = pos;
   }
 }
 
-void FloatingWindow::dragMouseRelease(QPoint)
-{
-  if ( m_dragMouseDown )
-  {
+void FloatingWindow::dragMouseRelease(QPoint) {
+  if (m_dragMouseDown) {
     m_dragMouseDown = false;
   }
 }
 
-void FloatingWindow::dragMouseMove(QPoint pos)
-{
-  if ( m_dragMouseDown )
-  {
-    if ((pos - m_dragStartPos).manhattanLength() < QApplication::startDragDistance())
-    {
+void FloatingWindow::dragMouseMove(QPoint pos) {
+  if (m_dragMouseDown) {
+    if ((pos - m_dragStartPos).manhattanLength() <
+        QApplication::startDragDistance()) {
       return;
     }
 
@@ -264,11 +223,11 @@ void FloatingWindow::dragMouseMove(QPoint pos)
     QMimeData *mimeData = new QMimeData;
 
     MdiSubWindow *ptr = mdiSubWindow();
-    auto d = QByteArray::fromRawData( (const char*)ptr, 1 );
-    mimeData->setData("TiledWindow",d);
+    auto d = QByteArray::fromRawData((const char *)ptr, 1);
+    mimeData->setData("TiledWindow", d);
 
     drag->setMimeData(mimeData);
     Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
-    (void) dropAction;
+    (void)dropAction;
   }
 }
diff --git a/MantidPlot/src/FloatingWindow.h b/MantidPlot/src/FloatingWindow.h
index 0204cb6f22d0a1d761d1c1a7d48848244962323e..cfaab47ea88f30eb289a5c83490a3ca8336898a2 100644
--- a/MantidPlot/src/FloatingWindow.h
+++ b/MantidPlot/src/FloatingWindow.h
@@ -11,16 +11,15 @@ class QSize;
 /**
  * Floating wrapper window for a MdiSubWindow.
  */
-class FloatingWindow: public QMainWindow
-{
+class FloatingWindow : public QMainWindow {
   Q_OBJECT
 public:
-  FloatingWindow(ApplicationWindow* appWindow, Qt::WindowFlags f = 0);
+  FloatingWindow(ApplicationWindow *appWindow, Qt::WindowFlags f = 0);
   ~FloatingWindow() override;
   void setStaysOnTopFlag();
   void removeStaysOnTopFlag();
-  MdiSubWindow* mdiSubWindow() const;
-  void setMdiSubWindow(MdiSubWindow* sw);
+  MdiSubWindow *mdiSubWindow() const;
+  void setMdiSubWindow(MdiSubWindow *sw);
   void removeMdiSubWindow();
   QSize minimumSizeHint() const override;
 
@@ -30,17 +29,16 @@ public slots:
   void dragMouseMove(QPoint);
 
 protected:
-
-  void setWidget(QWidget* w);
-  QWidget* widget() const;
+  void setWidget(QWidget *w);
+  QWidget *widget() const;
   bool event(QEvent *ev) override;
   void moveEvent(QMoveEvent *ev) override;
 
 private:
-
-  ApplicationWindow* d_app; ///< Pointer to the main window
+  ApplicationWindow *d_app; ///< Pointer to the main window
 #ifdef Q_OS_WIN
-  Qt::WindowFlags m_flags;  ///< Keeps a copy of window flags, used when re-parenting
+  Qt::WindowFlags
+      m_flags; ///< Keeps a copy of window flags, used when re-parenting
 #endif
   bool m_draggingToTiledWindow;
   bool m_isInsideTiledWindow;
diff --git a/MantidPlot/src/Folder.h b/MantidPlot/src/Folder.h
index 87ad2a4da2d0f3c5e33b9748d11782c4fbcf8d6a..a11ba91696eff3ae144e4b927403f5f95aa7f63d 100644
--- a/MantidPlot/src/Folder.h
+++ b/MantidPlot/src/Folder.h
@@ -2,7 +2,8 @@
     File                 : Folder.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Folder for the project explorer
 
@@ -42,93 +43,103 @@ class MultiLayer;
 class Note;
 
 //! Folder for the project explorer
-class Folder : public QObject
-{
-    Q_OBJECT
+class Folder : public QObject {
+  Q_OBJECT
 
 public:
-    Folder( Folder *parent, const QString &name );
+  Folder(Folder *parent, const QString &name);
 
-	QList<MdiSubWindow *> windowsList(){return lstWindows;};
+  QList<MdiSubWindow *> windowsList() { return lstWindows; };
 
-  void addWindow( MdiSubWindow *w );
+  void addWindow(MdiSubWindow *w);
   bool hasWindow(MdiSubWindow *w) const;
 
-	//! The list of subfolder names, including first generation children only
-	QStringList subfolders();
-
-	//! The list of subfolders
-	QList<Folder*> folders();
-
-	//! Pointer to the subfolder called s
-	Folder* findSubfolder(const QString& s, bool caseSensitive = true, bool partialMatch = false);
-
-	//! Pointer to the first window matching the search criteria
-	MdiSubWindow* findWindow(const QString& s, bool windowNames, bool labels,
-							 bool caseSensitive, bool partialMatch);
-
-	//! get a window by name
-	  /**
-	   * Returns the first window with given name that inherits class cls;
-	   * NULL on failure. If recursive is true, do a depth-first recursive
-	   * search.
-	   */
-	MdiSubWindow *window(const QString &name, const char *cls="MdiSubWindow", bool recursive=false);
-	//! Return table named name or NULL
-  Table *table(const QString &name, bool recursive=false) { return reinterpret_cast<Table*>(window(name, "Table", recursive)); }
-	//! Return matrix named name or NULL
-  Matrix *matrix(const QString &name, bool recursive=false) { return reinterpret_cast<Matrix*>(window(name, "Matrix", recursive)); }
-	//! Return graph named name or NULL
-  MultiLayer *graph(const QString &name, bool recursive=false) { return reinterpret_cast<MultiLayer*>(window(name, "MultiLayer", recursive)); }
-	//! Return note named name or NULL
-  Note *note(const QString &name, bool recursive=false) { return reinterpret_cast<Note*>(window(name, "Note", recursive)); }
-
-	//! The complete path of the folder in the project tree
-	QString path();
-	
-	//! The depth of the folder in the project tree
-	int depth();
-	
-	Folder *folderBelow();
-
-	//! The root of the hierarchy this folder belongs to.
-	Folder* rootFolder();
-
-	//! Size of the folder as a string
-	QString sizeToString();
-
-	QString birthDate(){return birthdate;};
-	void setBirthDate(const QString& s){birthdate = s;};
-
-	QString modificationDate(){return modifDate;};
-	void setModificationDate(const QString& s){modifDate = s;};
-
-	//! Pointer to the corresponding QListViewItem in the main application
-	FolderListItem * folderListItem(){return myFolderListItem;};
-	void setFolderListItem(FolderListItem *it){myFolderListItem = it;};
-
-    MdiSubWindow *activeWindow(){return d_active_window;};
-    void setActiveWindow(MdiSubWindow *w){d_active_window = w;};
-
-	QString logInfo(){return d_log_info;};
-	void clearLogInfo(){d_log_info = QString();};
+  //! The list of subfolder names, including first generation children only
+  QStringList subfolders();
+
+  //! The list of subfolders
+  QList<Folder *> folders();
+
+  //! Pointer to the subfolder called s
+  Folder *findSubfolder(const QString &s, bool caseSensitive = true,
+                        bool partialMatch = false);
+
+  //! Pointer to the first window matching the search criteria
+  MdiSubWindow *findWindow(const QString &s, bool windowNames, bool labels,
+                           bool caseSensitive, bool partialMatch);
+
+  //! get a window by name
+  /**
+   * Returns the first window with given name that inherits class cls;
+   * NULL on failure. If recursive is true, do a depth-first recursive
+   * search.
+   */
+  MdiSubWindow *window(const QString &name, const char *cls = "MdiSubWindow",
+                       bool recursive = false);
+  //! Return table named name or NULL
+  Table *table(const QString &name, bool recursive = false) {
+    return reinterpret_cast<Table *>(window(name, "Table", recursive));
+  }
+  //! Return matrix named name or NULL
+  Matrix *matrix(const QString &name, bool recursive = false) {
+    return reinterpret_cast<Matrix *>(window(name, "Matrix", recursive));
+  }
+  //! Return graph named name or NULL
+  MultiLayer *graph(const QString &name, bool recursive = false) {
+    return reinterpret_cast<MultiLayer *>(
+        window(name, "MultiLayer", recursive));
+  }
+  //! Return note named name or NULL
+  Note *note(const QString &name, bool recursive = false) {
+    return reinterpret_cast<Note *>(window(name, "Note", recursive));
+  }
+
+  //! The complete path of the folder in the project tree
+  QString path();
+
+  //! The depth of the folder in the project tree
+  int depth();
+
+  Folder *folderBelow();
+
+  //! The root of the hierarchy this folder belongs to.
+  Folder *rootFolder();
+
+  //! Size of the folder as a string
+  QString sizeToString();
+
+  QString birthDate() { return birthdate; };
+  void setBirthDate(const QString &s) { birthdate = s; };
+
+  QString modificationDate() { return modifDate; };
+  void setModificationDate(const QString &s) { modifDate = s; };
+
+  //! Pointer to the corresponding QListViewItem in the main application
+  FolderListItem *folderListItem() { return myFolderListItem; };
+  void setFolderListItem(FolderListItem *it) { myFolderListItem = it; };
+
+  MdiSubWindow *activeWindow() { return d_active_window; };
+  void setActiveWindow(MdiSubWindow *w) { d_active_window = w; };
+
+  QString logInfo() { return d_log_info; };
+  void clearLogInfo() { d_log_info = QString(); };
 
   bool isEmpty() const;
-	
-public slots:
-  ///Mantid: made this a slot for use with script messages when there is no script window
-  void appendLogInfo(const QString& text){d_log_info += text;};
-	void removeWindow( MdiSubWindow *w );
 
+public slots:
+  /// Mantid: made this a slot for use with script messages when there is no
+  /// script window
+  void appendLogInfo(const QString &text) { d_log_info += text; };
+  void removeWindow(MdiSubWindow *w);
 
 protected:
-    QString birthdate, modifDate;
-	QString d_log_info;
-    QList<MdiSubWindow *> lstWindows;
-	FolderListItem *myFolderListItem;
+  QString birthdate, modifDate;
+  QString d_log_info;
+  QList<MdiSubWindow *> lstWindows;
+  FolderListItem *myFolderListItem;
 
-	//! Pointer to the active window in the folder
-	MdiSubWindow *d_active_window;
+  //! Pointer to the active window in the folder
+  MdiSubWindow *d_active_window;
 };
 
 /*****************************************************************************
@@ -137,15 +148,14 @@ protected:
  *
  *****************************************************************************/
 //! Windows list item class
-class WindowListItem : public QTreeWidgetItem
-{
+class WindowListItem : public QTreeWidgetItem {
 public:
-    WindowListItem( QTreeWidget *parent, MdiSubWindow *w );
+  WindowListItem(QTreeWidget *parent, MdiSubWindow *w);
 
-    MdiSubWindow *window() { return myWindow; };
+  MdiSubWindow *window() { return myWindow; };
 
 protected:
-    MdiSubWindow *myWindow;
+  MdiSubWindow *myWindow;
 };
 
 /*****************************************************************************
@@ -154,28 +164,27 @@ protected:
  *
  *****************************************************************************/
 //! Folders list item class
-class FolderListItem : public QTreeWidgetItem
-{
+class FolderListItem : public QTreeWidgetItem {
 public:
-    FolderListItem( QTreeWidget *parent, Folder *f );
-    FolderListItem( FolderListItem *parent, Folder *f );
+  FolderListItem(QTreeWidget *parent, Folder *f);
+  FolderListItem(FolderListItem *parent, Folder *f);
 
-	enum {RTTI = 1001};
+  enum { RTTI = 1001 };
 
-	void setActive( bool o );
+  void setActive(bool o);
   void cancelRename(int) { return; };
   int rtti() const { return (int)RTTI; };
 
   Folder *folder() { return myFolder; };
 
-	//! Checks weather the folder item is a grandchild of the source folder
-	/**
-	 * @param src :: source folder item
-	 */
-	bool isChildOf(FolderListItem *src);
+  //! Checks weather the folder item is a grandchild of the source folder
+  /**
+   * @param src :: source folder item
+   */
+  bool isChildOf(FolderListItem *src);
 
 protected:
-    Folder *myFolder;
+  Folder *myFolder;
 };
 
 /*****************************************************************************
@@ -184,22 +193,21 @@ protected:
  *
  *****************************************************************************/
 //! Folder list view class
-class FolderListView : public QTreeWidget
-{
-    Q_OBJECT
+class FolderListView : public QTreeWidget {
+  Q_OBJECT
 
 public:
-    FolderListView( QWidget *parent = 0, const char *name = 0 );
-    QTreeWidgetItem* firstChild();
+  FolderListView(QWidget *parent = 0, const char *name = 0);
+  QTreeWidgetItem *firstChild();
 
 public slots:
-	void adjustColumns();
+  void adjustColumns();
 
 protected slots:
-	void expandedItem(const QModelIndex &index);
+  void expandedItem(const QModelIndex &index);
 
 signals:
-	void deleteSelection();
+  void deleteSelection();
 };
 
 #endif
diff --git a/MantidPlot/src/FunctionCurve.h b/MantidPlot/src/FunctionCurve.h
index 05c9a49be913ab4f5a827b517670a0d1e197be59..a413668b8edf9416cc7e55d20dc87575e009cd34 100644
--- a/MantidPlot/src/FunctionCurve.h
+++ b/MantidPlot/src/FunctionCurve.h
@@ -2,7 +2,8 @@
     File                 : FunctionCurve.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Function curve class
 
@@ -33,76 +34,77 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-  namespace API
-  {
-    class IFunction;
-    class MatrixWorkspace;
-  }
+namespace Mantid {
+namespace API {
+class IFunction;
+class MatrixWorkspace;
+}
 }
 
 // Function curve class
-class FunctionCurve: public PlotCurve
-{
+class FunctionCurve : public PlotCurve {
 public:
-	enum FunctionType{Normal = 0, Parametric = 1, Polar = 2};
+  enum FunctionType { Normal = 0, Parametric = 1, Polar = 2 };
+
+  FunctionCurve(const FunctionType &t, const QString &name = QString());
+  explicit FunctionCurve(const QString &name = QString());
+  FunctionCurve(const Mantid::API::IFunction *fun, const QString &wsName,
+                int wsIndex = 0, const QString &name = QString());
+  FunctionCurve(const FunctionCurve &c);
+  ~FunctionCurve() override;
 
-	FunctionCurve(const FunctionType& t, const QString& name = QString());
-        explicit FunctionCurve(const QString &name = QString());
-  FunctionCurve(const Mantid::API::IFunction* fun, 
-    const QString& wsName, int wsIndex = 0, const QString& name = QString());
-	FunctionCurve(const FunctionCurve& c);
-        ~FunctionCurve() override;
+  PlotCurve *clone(const Graph *) const override {
+    return new FunctionCurve(*this);
+  }
 
-        PlotCurve *clone(const Graph *) const override {
-          return new FunctionCurve(*this);
-        }
+  double startRange() { return d_from; };
+  double endRange() { return d_to; };
+  void setRange(double from, double to);
 
-        double startRange(){return d_from;};
-	double endRange(){return d_to;};
-	void setRange(double from, double to);
+  QStringList formulas() { return d_formulas; };
+  void setFormulas(const QStringList &lst) { d_formulas = lst; };
 
-	QStringList formulas(){return d_formulas;};
-	void setFormulas(const QStringList& lst){d_formulas = lst;};
+  //! Provided for convenience when dealing with normal functions
+  void setFormula(const QString &s) { d_formulas = QStringList() << s; };
 
-	//! Provided for convenience when dealing with normal functions
-	void setFormula(const QString& s){d_formulas = QStringList() << s;};
+  QString variable() { return d_variable; };
+  void setVariable(const QString &s) { d_variable = s; };
 
-	QString variable(){return d_variable;};
-	void setVariable(const QString& s){d_variable = s;};
+  FunctionType functionType() { return d_function_type; };
+  void setFunctionType(const FunctionType &t) { d_function_type = t; };
 
-	FunctionType functionType(){return d_function_type;};
-	void setFunctionType(const FunctionType& t){d_function_type = t;};
+  void copy(FunctionCurve *f);
 
-	void copy(FunctionCurve *f);
+  //! Returns a string used when saving to a project file
+  QString saveToString();
 
-	//! Returns a string used when saving to a project file
-	QString saveToString();
+  //! Returns a string that can be displayed in a plot legend
+  QString legend();
 
-	//! Returns a string that can be displayed in a plot legend
-	QString legend();
+  void loadData(int points = 0);
 
-	void loadData(int points = 0);
+  void loadMantidData(boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws,
+                      size_t wi);
 
-  void loadMantidData(boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws, size_t wi);
- 
   /// No error bars on this curve: Always return an empty list.
   QList<ErrorBarSettings *> errorBarSettingsList() const override {
     return QList<ErrorBarSettings *>();
   }
 
   /// returns identifier where this curve plots a IFunction
-  const Mantid::API::IFunction* getIFunctionIdentifier() const {return m_identifier;};
+  const Mantid::API::IFunction *getIFunctionIdentifier() const {
+    return m_identifier;
+  };
+
 private:
-	FunctionType d_function_type;
-	QString d_variable;
-	QStringList d_formulas;
-	double d_from, d_to;
-  
+  FunctionType d_function_type;
+  QString d_variable;
+  QStringList d_formulas;
+  double d_from, d_to;
+
   /// Used to identify which IFunction it is plotting
   /// Equal null where the curve is not plotting an IFunction
-  const Mantid::API::IFunction* m_identifier;
+  const Mantid::API::IFunction *m_identifier;
 };
 
 #endif
diff --git a/MantidPlot/src/FunctionDialog.h b/MantidPlot/src/FunctionDialog.h
index e453bf7f37399abf6ed8b509044e4ac885a5318d..d0abda7db6fe17841b2df481855ecbacd7c8a452 100644
--- a/MantidPlot/src/FunctionDialog.h
+++ b/MantidPlot/src/FunctionDialog.h
@@ -2,7 +2,8 @@
     File                 : FunctionDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Function dialog
 
@@ -42,60 +43,61 @@ class QTextEdit;
 class ApplicationWindow;
 
 //! Function dialog
-class FunctionDialog : public QDialog
-{
-    Q_OBJECT
+class FunctionDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    FunctionDialog( ApplicationWindow* app, Graph* g = NULL, Qt::WFlags fl = 0 );
+  FunctionDialog(ApplicationWindow *app, Graph *g = NULL, Qt::WFlags fl = 0);
 
 protected:
-	QComboBox* boxXFunction;
-    QComboBox* boxYFunction;
-    QComboBox* boxPolarRadius;
-    QComboBox* boxPolarTheta;
-    QComboBox* boxType;
-    QLineEdit* boxFrom;
-    QLineEdit* boxTo;
-	QLineEdit* boxParameter;
-    QLineEdit* boxParFrom;
-    QLineEdit* boxParTo;
-	QLineEdit* boxPolarParameter;
-    QLineEdit* boxPolarFrom;
-    QLineEdit* boxPolarTo;
-    QPushButton* buttonClear;
-    QPushButton* buttonCancel;
-    QPushButton* buttonOk;
-	QSpinBox* boxPoints;
-	QSpinBox* boxParPoints;
-	QSpinBox* boxPolarPoints;
-	QStackedWidget* optionStack;
-    QTextEdit* boxFunction;
-	QWidget* functionPage;
-	QWidget* polarPage;
-	QWidget* parametricPage;
+  QComboBox *boxXFunction;
+  QComboBox *boxYFunction;
+  QComboBox *boxPolarRadius;
+  QComboBox *boxPolarTheta;
+  QComboBox *boxType;
+  QLineEdit *boxFrom;
+  QLineEdit *boxTo;
+  QLineEdit *boxParameter;
+  QLineEdit *boxParFrom;
+  QLineEdit *boxParTo;
+  QLineEdit *boxPolarParameter;
+  QLineEdit *boxPolarFrom;
+  QLineEdit *boxPolarTo;
+  QPushButton *buttonClear;
+  QPushButton *buttonCancel;
+  QPushButton *buttonOk;
+  QSpinBox *boxPoints;
+  QSpinBox *boxParPoints;
+  QSpinBox *boxPolarPoints;
+  QStackedWidget *optionStack;
+  QTextEdit *boxFunction;
+  QWidget *functionPage;
+  QWidget *polarPage;
+  QWidget *parametricPage;
 
 protected slots:
-	void raiseWidget(int index);
+  void raiseWidget(int index);
 
 public slots:
   void accept() override;
-        void acceptFunction();
-	void acceptParametric();
-	void acceptPolar();
-	void setCurveToModify(Graph *g, int curve);
-	void insertParamFunctionsList(const QStringList& xList, const QStringList& yList);
-	void insertPolarFunctionsList(const QStringList& rList, const QStringList& thetaList);
-	void clearList();
+  void acceptFunction();
+  void acceptParametric();
+  void acceptPolar();
+  void setCurveToModify(Graph *g, int curve);
+  void insertParamFunctionsList(const QStringList &xList,
+                                const QStringList &yList);
+  void insertPolarFunctionsList(const QStringList &rList,
+                                const QStringList &thetaList);
+  void clearList();
 
 signals:
-	void clearParamFunctionsList();
-	void clearPolarFunctionsList();
+  void clearParamFunctionsList();
+  void clearPolarFunctionsList();
 
 private:
-  ApplicationWindow* d_app;
-	Graph *graph;
-	int curveID;
+  ApplicationWindow *d_app;
+  Graph *graph;
+  int curveID;
 };
 
 #endif // FUNCTIONDIALOG_H
diff --git a/MantidPlot/src/Graph.cpp b/MantidPlot/src/Graph.cpp
index 8e609d25283915d653a6cf86e896b0bf76d03b5f..525533b8f45387f6a33a143a0dfa8d57b8205cba 100644
--- a/MantidPlot/src/Graph.cpp
+++ b/MantidPlot/src/Graph.cpp
@@ -5667,27 +5667,24 @@ void Graph::loadFromProject(const std::string &lines, ApplicationWindow *app,
   }
 
   if (tsv.selectLine("AxesNumberColors")) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("AxesNumberColors").c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("AxesNumberColors")
+                                           .c_str()).split("\t");
     sl.pop_front();
     for (int i = 0; i < sl.count(); ++i)
       setAxisLabelsColor(i, QColor(sl[i]));
   }
 
   if (tsv.selectLine("AxesTitleColors")) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("AxesTitleColors").c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("AxesTitleColors")
+                                           .c_str()).split("\t");
     sl.pop_front();
     for (int i = 0; i < sl.count(); ++i)
       setAxisTitleColor(i, QColor(sl[i]));
   }
 
   if (tsv.selectLine("AxesTitleAlignment")) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("AxesTitleAlignment").c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("AxesTitleAlignment")
+                                           .c_str()).split("\t");
     sl.pop_front();
     for (int i = 0; i < sl.count(); ++i)
       setAxisTitleAlignment(i, sl[i].toInt());
@@ -5814,9 +5811,8 @@ void Graph::loadFromProject(const std::string &lines, ApplicationWindow *app,
   }
 
   if (tsv.selectLine("EnabledTickLabels")) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("EnabledTickLabels").c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("EnabledTickLabels")
+                                           .c_str()).split("\t");
     sl.pop_front();
     for (int i = 0; i < sl.count(); ++i)
       enableAxisLabels(i, sl[i].toInt());
@@ -5828,9 +5824,8 @@ void Graph::loadFromProject(const std::string &lines, ApplicationWindow *app,
   }
 
   for (int i = 0; tsv.selectLine("ImageMarker", i); ++i) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("ImageMarker", i).c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("ImageMarker", i)
+                                           .c_str()).split("\t");
     insertImageMarker(sl, fileVersion);
   }
 
@@ -5848,9 +5843,8 @@ void Graph::loadFromProject(const std::string &lines, ApplicationWindow *app,
   }
 
   if (tsv.selectLine("LabelsRotation")) {
-    QStringList sl =
-        QString::fromUtf8(tsv.lineAsString("LabelsRotation").c_str())
-            .split("\t");
+    QStringList sl = QString::fromUtf8(tsv.lineAsString("LabelsRotation")
+                                           .c_str()).split("\t");
     setAxisLabelRotation(QwtPlot::xBottom, sl[1].toInt());
     setAxisLabelRotation(QwtPlot::xTop, sl[2].toInt());
   }
diff --git a/MantidPlot/src/Graph3D.h b/MantidPlot/src/Graph3D.h
index 08ceeba4ccd5fb72542973df231da8bf098f430d..6fae8d7c3450ef78bb63fbff67f1b8240ce90d1b 100644
--- a/MantidPlot/src/Graph3D.h
+++ b/MantidPlot/src/Graph3D.h
@@ -47,388 +47,406 @@ using namespace Qwt3D;
 
 class UserFunction2D;
 class UserParametricSurface;
-class Function2D;//Mantid
+class Function2D; // Mantid
 
 /**\brief 3D graph widget.
  *
  * This provides 3D plotting using Qwt3D.
  *
  * \section future Future Plans
- * If MultiLayer is extended to accept any QWidget, Graph3D wouldn't have to inherit from MdiSubWindow any more.
- * It could also make sense to unify the interface with other plot types; see documentation of Graph.
- * Big problem here: export to vector formats. Qwt3D's export filters write directly to a file, so they
+ * If MultiLayer is extended to accept any QWidget, Graph3D wouldn't have to
+ *inherit from MdiSubWindow any more.
+ * It could also make sense to unify the interface with other plot types; see
+ *documentation of Graph.
+ * Big problem here: export to vector formats. Qwt3D's export filters write
+ *directly to a file, so they
  * can't be combined with output generated via QPrinter.
  */
-class Graph3D: public MdiSubWindow, public Mantid::IProjectSerialisable
-{
-	Q_OBJECT
+class Graph3D : public MdiSubWindow, public Mantid::IProjectSerialisable {
+  Q_OBJECT
 
 public:
-	Graph3D (const QString& label, QWidget* parent, const char* name=0, Qt::WFlags f=0);
-        ~Graph3D() override;
-
-        enum PlotType{Scatter = 0, Trajectory = 1, Bars = 2, Ribbon =  3};
-	enum PointStyle{None = 0, Dots = 1, VerticalBars = 2, HairCross = 3, Cones = 4};
+  Graph3D(const QString &label, QWidget *parent, const char *name = 0,
+          Qt::WFlags f = 0);
+  ~Graph3D() override;
+
+  enum PlotType { Scatter = 0, Trajectory = 1, Bars = 2, Ribbon = 3 };
+  enum PointStyle {
+    None = 0,
+    Dots = 1,
+    VerticalBars = 2,
+    HairCross = 3,
+    Cones = 4
+  };
 
 public slots:
-	void copy(Graph3D* g);
-	void initPlot();
-	void initCoord();
-    void addFunction(Function2D* hfun, double xl, double xr, double yl,
-                          double yr, double zl, double zr, size_t columns, size_t rows);
-    void addFunction(const QString& formula, double xl, double xr, double yl,
-                          double yr, double zl, double zr, size_t columns, size_t rows);
-    void addParametricSurface(const QString& xFormula, const QString& yFormula,
-						const QString& zFormula, double ul, double ur, double vl, double vr,
-						int columns, int rows, bool uPeriodic, bool vPeriodic);
-	void insertNewData(Table* table, const QString& colName);
-
-	Matrix * matrix(){return d_matrix;};
-	void addMatrixData(Matrix* m);//used to plot matrixes
-	void addMatrixData(Matrix* m,double xl,double xr,double yl,double yr,double zl,double zr);
-	void updateMatrixData(Matrix* m);
-
-	void addData(Table* table,const QString& xColName,const QString& yColName);
-	void addData(Table* table,const QString& xColName,const QString& yColName,
-                double xl, double xr, double yl, double yr, double zl, double zr);
-	void addData(Table* table, int xCol, int yCol, int zCol, int type = 0);
-	void loadData(Table* table, int xCol, int yCol, int zCol,
-                double xl=0.0, double xr=0.0, double yl=0.0, double yr=0.0, double zl=0.0, double zr=0.0);
-
-	void clearData();
-	bool hasData(){return sp->hasData();};
-
-	void updateData(Table* table);
-	void updateDataXY(Table* table, int xCol, int yCol);
-
-	void changeDataColumn(Table* table, const QString& colName, int type = 0);
-
-	//! \name User Functions
-	//@{
-	UserParametricSurface *parametricSurface(){return d_surface;};
-	//@}
-
-	//! \name User Functions
-	//@{
-    Function2D* userFunction(){ return d_func.data();  }
-    QString formula();
-	//@}
-
-	//! \name Event Handlers
-	//@{
-    bool eventFilter(QObject *object, QEvent *e) override;
-    void resizeEvent(QResizeEvent *) override;
-        void scaleFonts(double factor);
-	void setIgnoreFonts(bool ok){ignoreFonts = ok;};
-	//@}
-
-	//! \name Axes
-	//@{
-	void setFramed();
-	void setBoxed();
-	void setNoAxes();
-	bool isOrthogonal(){return sp->ortho();};
-	void setOrthogonal(bool on = true){sp->setOrtho(on);};
-
-	QStringList axesLabels(){return labels;};
-	void setAxesLabels(const QStringList& lst);
-	void resetAxesLabels();
-
-    void setXAxisLabel(const QString&);
-    void setYAxisLabel(const QString&);
-	void setZAxisLabel(const QString&);
-
-	QFont xAxisLabelFont();
-	QFont yAxisLabelFont();
-	QFont zAxisLabelFont();
-
-	void setXAxisLabelFont(const QFont& fnt);
-	void setYAxisLabelFont(const QFont& fnt);
-	void setZAxisLabelFont(const QFont& fnt);
-
-	void setXAxisLabelFont(const QStringList& lst);
-	void setYAxisLabelFont(const QStringList& lst);
-	void setZAxisLabelFont(const QStringList& lst);
-
-	QFont numbersFont();
-	void setNumbersFont(const QFont& font);
-	void setNumbersFont(const QStringList& lst);
-
-	double xStart();
-	double xStop();
-	double yStart();
-	double yStop();
-	double zStart();
-	double zStop();
-	QStringList scaleLimits();
-	void updateScale(int axis, const QStringList& options);
-	void setScales(double xl, double xr, double yl, double yr, double zl, double zr);
-	void updateScales(double xl, double xr, double yl, double yr,
-				  		double zl, double zr, int xcol, int ycol);
-	void updateScalesFromMatrix(double xl,double xr,double yl,double yr,double zl,double zr);
-
-	QStringList scaleTicks();
-	void setTicks(const QStringList& options);
-
-	void setXAxisTickLength(double majorLength, double minorLength);
-    void setYAxisTickLength(double majorLength, double minorLength);
-	void setZAxisTickLength(double majorLength, double minorLength);
-
-	void setAxisTickLength(int axis, double majorLength, double minorLength);
-	void setLabelsDistance(int val);
-	int labelsDistance(){return labelsDist;};
-
-	QStringList axisTickLengths();
-	void setTickLengths(const QStringList& lst);
-	//@}
-
-	//! \name Mesh
-	//@{
-	void setPolygonStyle();
-	void setHiddenLineStyle();
-	void setWireframeStyle();
-	void setFilledMeshStyle();
-	void setDotStyle();
-	void setBarStyle();
-	void setFloorData();
-	void setFloorIsolines();
-	void setEmptyFloor();
-
-	void setMeshLineWidth(double lw);
-	double meshLineWidth(){return sp->meshLineWidth();};
-	//@}
-
-	//! \name Grid
-	//@{
-	int grids();
-	void setGrid(Qwt3D::SIDE s, bool b);
-	void setGrid(int grids);
-
-	void setLeftGrid(bool b = true);
-	void setRightGrid(bool b = true);
-	void setCeilGrid(bool b = true);
-	void setFloorGrid(bool b = true);
-	void setFrontGrid(bool b = true);
-	void setBackGrid(bool b = true);
-	//@}
-
-	void setStyle(const QStringList& st);
-	void customPlotStyle(int style);
-	void resetNonEmptyStyle();
-
-	void setRotation(double  xVal,double  yVal,double  zVal);
-	void setScale(double  xVal,double  yVal,double  zVal);
-	void setShift(double  xVal,double  yVal,double  zVal);
-
-	double xRotation(){return sp->xRotation();};
-	double yRotation(){return sp->yRotation();};
-	double zRotation(){return sp->zRotation();};
-
-	double xScale(){return sp->xScale();};
-	double yScale(){return sp->yScale();};
-	double zScale(){return sp->zScale();};
-
-	double xShift(){return sp->xShift();};
-	double yShift(){return sp->yShift();};
-	double zShift(){return sp->zShift();};
-
-	double zoom(){return sp->zoom();};
-	void setZoom(double val);
-
-	Qwt3D::PLOTSTYLE plotStyle();
-	Qwt3D::FLOORSTYLE floorStyle();
-	Qwt3D::COORDSTYLE coordStyle();
-
-        void print() override;
-        void copyImage();
-	void exportImage(const QString& fileName, int quality = 100, bool transparent = false);
-        void exportPDF(const QString &fileName) override;
-    void exportVector(const QString& fileName);
-    void exportToFile(const QString& fileName);
-
-    void loadFromProject(const std::string &lines, ApplicationWindow *app,
-                         const int fileVersion) override;
-    std::string saveToProject(ApplicationWindow *app) override;
-
-        void zoomChanged(double);
-	void rotationChanged(double, double, double);
-	void scaleChanged(double, double, double);
-	void shiftChanged(double, double, double);
-
-	//! \name Colors
-	//@{
-	void setDataColors(const QColor& cMax, const QColor& cMin);
-
-	void changeTransparency(double t);
-	void setTransparency(double t);
-	double transparency(){return alpha;};
-
-	QColor minDataColor();
-	QColor maxDataColor();
-	QColor meshColor(){return meshCol;};
-	QColor axesColor(){return axesCol;};
-	QColor labelColor(){return labelsCol;};
-	QColor numColor(){return numCol;};
-	QColor bgColor(){return bgCol;};
-	QColor gridColor(){return gridCol;};
-
-	QString colorMap(){return color_map;};
-	void setDataColorMap(const QString& fileName);
-	bool openColorMap(ColorVector& cv, QString fname);
-
-	void setMeshColor(const QColor&);
-	void setAxesColor(const QColor&);
-	void setNumbersColor(const QColor&);
-	void setLabelsColor(const QColor&);
-	void setBackgroundColor(const QColor&);
-	void setGridColor(const QColor&);
-
-	void setColors(const QStringList& colors);
-	//@}
-
-	//! \name Title
-	//@{
-	QFont titleFont(){return titleFnt;};
-	void setTitleFont(const QFont& font);
-	QString plotTitle(){return title;};
-	QColor titleColor(){return titleCol;};
-	void setTitle(const QStringList& lst);
-	void setTitle(const QString& s, const QColor& color = QColor(Qt::black), const QFont& font = QFont());
-	//@}
-
-	//! \name Resolution
-	//@{
-	void setResolution(int r);
-	int resolution(){return sp->resolution();};
-	//@}
-
-	//! \name Legend
-	//@{
-	void showColorLegend(bool show = true);
-	bool isLegendOn(){return legendOn;};
-	//@}
-
-	void setOptions(bool legend, int r, int dist);
-	void setOptions(const QStringList& lst);
-	void update();
-
-	//! \name Bars
-	//@{
-	double barsRadius();
-	void setBarRadius(double rad);
-	//@}
-
-	//! \name Scatter Plots
-	//@{
-	double pointsSize(){return d_point_size;};
-	bool smoothPoints(){return d_smooth_points;};
-	void setDotOptions(double size, bool smooth);
-
-	bool smoothCrossHair(){return crossHairSmooth;};
-	bool boxedCrossHair(){return crossHairBoxed;};
-	double crossHairRadius(){return crossHairRad;};
-	double crossHairLinewidth(){return crossHairLineWidth;};
-	void setCrossOptions(double rad, double linewidth, bool smooth, bool boxed);
-	void setCrossStyle();
-
-	double coneRadius(){return conesRad;};
-	int coneQuality(){return conesQuality;};
-	void setConeOptions(double rad, int quality);
-	void setConeStyle();
-
-	PointStyle pointType(){return pointStyle;};
-	//@}
-
-	Table* table(){return d_table;};
-	void showWorksheet();
-	void setPlotAssociation(const QString& s){plotAssociation = s;};
-
-	void setAntialiasing(bool smooth = true);
-	bool antialiasing(){return sp->smoothDataMesh();};
-
-	//! Used for the animation: rotates the scene with 1/360 degrees
-	void rotate();
-	void animate(bool on = true);
-	bool isAnimated(){return d_timer->isActive();};
-
-    void findBestLayout();
-	bool autoscale(){return d_autoscale;};
-	//! Enables/Disables autoscaling using findBestLayout().
-	void setAutoscale(bool on = true){d_autoscale = on;};
+  void copy(Graph3D *g);
+  void initPlot();
+  void initCoord();
+  void addFunction(Function2D *hfun, double xl, double xr, double yl, double yr,
+                   double zl, double zr, size_t columns, size_t rows);
+  void addFunction(const QString &formula, double xl, double xr, double yl,
+                   double yr, double zl, double zr, size_t columns,
+                   size_t rows);
+  void addParametricSurface(const QString &xFormula, const QString &yFormula,
+                            const QString &zFormula, double ul, double ur,
+                            double vl, double vr, int columns, int rows,
+                            bool uPeriodic, bool vPeriodic);
+  void insertNewData(Table *table, const QString &colName);
+
+  Matrix *matrix() { return d_matrix; };
+  void addMatrixData(Matrix *m); // used to plot matrixes
+  void addMatrixData(Matrix *m, double xl, double xr, double yl, double yr,
+                     double zl, double zr);
+  void updateMatrixData(Matrix *m);
+
+  void addData(Table *table, const QString &xColName, const QString &yColName);
+  void addData(Table *table, const QString &xColName, const QString &yColName,
+               double xl, double xr, double yl, double yr, double zl,
+               double zr);
+  void addData(Table *table, int xCol, int yCol, int zCol, int type = 0);
+  void loadData(Table *table, int xCol, int yCol, int zCol, double xl = 0.0,
+                double xr = 0.0, double yl = 0.0, double yr = 0.0,
+                double zl = 0.0, double zr = 0.0);
+
+  void clearData();
+  bool hasData() { return sp->hasData(); };
+
+  void updateData(Table *table);
+  void updateDataXY(Table *table, int xCol, int yCol);
+
+  void changeDataColumn(Table *table, const QString &colName, int type = 0);
+
+  //! \name User Functions
+  //@{
+  UserParametricSurface *parametricSurface() { return d_surface; };
+  //@}
+
+  //! \name User Functions
+  //@{
+  Function2D *userFunction() { return d_func.data(); }
+  QString formula();
+  //@}
+
+  //! \name Event Handlers
+  //@{
+  bool eventFilter(QObject *object, QEvent *e) override;
+  void resizeEvent(QResizeEvent *) override;
+  void scaleFonts(double factor);
+  void setIgnoreFonts(bool ok) { ignoreFonts = ok; };
+  //@}
+
+  //! \name Axes
+  //@{
+  void setFramed();
+  void setBoxed();
+  void setNoAxes();
+  bool isOrthogonal() { return sp->ortho(); };
+  void setOrthogonal(bool on = true) { sp->setOrtho(on); };
+
+  QStringList axesLabels() { return labels; };
+  void setAxesLabels(const QStringList &lst);
+  void resetAxesLabels();
+
+  void setXAxisLabel(const QString &);
+  void setYAxisLabel(const QString &);
+  void setZAxisLabel(const QString &);
+
+  QFont xAxisLabelFont();
+  QFont yAxisLabelFont();
+  QFont zAxisLabelFont();
+
+  void setXAxisLabelFont(const QFont &fnt);
+  void setYAxisLabelFont(const QFont &fnt);
+  void setZAxisLabelFont(const QFont &fnt);
+
+  void setXAxisLabelFont(const QStringList &lst);
+  void setYAxisLabelFont(const QStringList &lst);
+  void setZAxisLabelFont(const QStringList &lst);
+
+  QFont numbersFont();
+  void setNumbersFont(const QFont &font);
+  void setNumbersFont(const QStringList &lst);
+
+  double xStart();
+  double xStop();
+  double yStart();
+  double yStop();
+  double zStart();
+  double zStop();
+  QStringList scaleLimits();
+  void updateScale(int axis, const QStringList &options);
+  void setScales(double xl, double xr, double yl, double yr, double zl,
+                 double zr);
+  void updateScales(double xl, double xr, double yl, double yr, double zl,
+                    double zr, int xcol, int ycol);
+  void updateScalesFromMatrix(double xl, double xr, double yl, double yr,
+                              double zl, double zr);
+
+  QStringList scaleTicks();
+  void setTicks(const QStringList &options);
+
+  void setXAxisTickLength(double majorLength, double minorLength);
+  void setYAxisTickLength(double majorLength, double minorLength);
+  void setZAxisTickLength(double majorLength, double minorLength);
+
+  void setAxisTickLength(int axis, double majorLength, double minorLength);
+  void setLabelsDistance(int val);
+  int labelsDistance() { return labelsDist; };
+
+  QStringList axisTickLengths();
+  void setTickLengths(const QStringList &lst);
+  //@}
+
+  //! \name Mesh
+  //@{
+  void setPolygonStyle();
+  void setHiddenLineStyle();
+  void setWireframeStyle();
+  void setFilledMeshStyle();
+  void setDotStyle();
+  void setBarStyle();
+  void setFloorData();
+  void setFloorIsolines();
+  void setEmptyFloor();
+
+  void setMeshLineWidth(double lw);
+  double meshLineWidth() { return sp->meshLineWidth(); };
+  //@}
+
+  //! \name Grid
+  //@{
+  int grids();
+  void setGrid(Qwt3D::SIDE s, bool b);
+  void setGrid(int grids);
+
+  void setLeftGrid(bool b = true);
+  void setRightGrid(bool b = true);
+  void setCeilGrid(bool b = true);
+  void setFloorGrid(bool b = true);
+  void setFrontGrid(bool b = true);
+  void setBackGrid(bool b = true);
+  //@}
+
+  void setStyle(const QStringList &st);
+  void customPlotStyle(int style);
+  void resetNonEmptyStyle();
+
+  void setRotation(double xVal, double yVal, double zVal);
+  void setScale(double xVal, double yVal, double zVal);
+  void setShift(double xVal, double yVal, double zVal);
+
+  double xRotation() { return sp->xRotation(); };
+  double yRotation() { return sp->yRotation(); };
+  double zRotation() { return sp->zRotation(); };
+
+  double xScale() { return sp->xScale(); };
+  double yScale() { return sp->yScale(); };
+  double zScale() { return sp->zScale(); };
+
+  double xShift() { return sp->xShift(); };
+  double yShift() { return sp->yShift(); };
+  double zShift() { return sp->zShift(); };
+
+  double zoom() { return sp->zoom(); };
+  void setZoom(double val);
+
+  Qwt3D::PLOTSTYLE plotStyle();
+  Qwt3D::FLOORSTYLE floorStyle();
+  Qwt3D::COORDSTYLE coordStyle();
+
+  void print() override;
+  void copyImage();
+  void exportImage(const QString &fileName, int quality = 100,
+                   bool transparent = false);
+  void exportPDF(const QString &fileName) override;
+  void exportVector(const QString &fileName);
+  void exportToFile(const QString &fileName);
+
+  void loadFromProject(const std::string &lines, ApplicationWindow *app,
+                       const int fileVersion) override;
+  std::string saveToProject(ApplicationWindow *app) override;
+
+  void zoomChanged(double);
+  void rotationChanged(double, double, double);
+  void scaleChanged(double, double, double);
+  void shiftChanged(double, double, double);
+
+  //! \name Colors
+  //@{
+  void setDataColors(const QColor &cMax, const QColor &cMin);
+
+  void changeTransparency(double t);
+  void setTransparency(double t);
+  double transparency() { return alpha; };
+
+  QColor minDataColor();
+  QColor maxDataColor();
+  QColor meshColor() { return meshCol; };
+  QColor axesColor() { return axesCol; };
+  QColor labelColor() { return labelsCol; };
+  QColor numColor() { return numCol; };
+  QColor bgColor() { return bgCol; };
+  QColor gridColor() { return gridCol; };
+
+  QString colorMap() { return color_map; };
+  void setDataColorMap(const QString &fileName);
+  bool openColorMap(ColorVector &cv, QString fname);
+
+  void setMeshColor(const QColor &);
+  void setAxesColor(const QColor &);
+  void setNumbersColor(const QColor &);
+  void setLabelsColor(const QColor &);
+  void setBackgroundColor(const QColor &);
+  void setGridColor(const QColor &);
+
+  void setColors(const QStringList &colors);
+  //@}
+
+  //! \name Title
+  //@{
+  QFont titleFont() { return titleFnt; };
+  void setTitleFont(const QFont &font);
+  QString plotTitle() { return title; };
+  QColor titleColor() { return titleCol; };
+  void setTitle(const QStringList &lst);
+  void setTitle(const QString &s, const QColor &color = QColor(Qt::black),
+                const QFont &font = QFont());
+  //@}
+
+  //! \name Resolution
+  //@{
+  void setResolution(int r);
+  int resolution() { return sp->resolution(); };
+  //@}
+
+  //! \name Legend
+  //@{
+  void showColorLegend(bool show = true);
+  bool isLegendOn() { return legendOn; };
+  //@}
+
+  void setOptions(bool legend, int r, int dist);
+  void setOptions(const QStringList &lst);
+  void update();
+
+  //! \name Bars
+  //@{
+  double barsRadius();
+  void setBarRadius(double rad);
+  //@}
+
+  //! \name Scatter Plots
+  //@{
+  double pointsSize() { return d_point_size; };
+  bool smoothPoints() { return d_smooth_points; };
+  void setDotOptions(double size, bool smooth);
+
+  bool smoothCrossHair() { return crossHairSmooth; };
+  bool boxedCrossHair() { return crossHairBoxed; };
+  double crossHairRadius() { return crossHairRad; };
+  double crossHairLinewidth() { return crossHairLineWidth; };
+  void setCrossOptions(double rad, double linewidth, bool smooth, bool boxed);
+  void setCrossStyle();
+
+  double coneRadius() { return conesRad; };
+  int coneQuality() { return conesQuality; };
+  void setConeOptions(double rad, int quality);
+  void setConeStyle();
+
+  PointStyle pointType() { return pointStyle; };
+  //@}
+
+  Table *table() { return d_table; };
+  void showWorksheet();
+  void setPlotAssociation(const QString &s) { plotAssociation = s; };
+
+  void setAntialiasing(bool smooth = true);
+  bool antialiasing() { return sp->smoothDataMesh(); };
+
+  //! Used for the animation: rotates the scene with 1/360 degrees
+  void rotate();
+  void animate(bool on = true);
+  bool isAnimated() { return d_timer->isActive(); };
+
+  void findBestLayout();
+  bool autoscale() { return d_autoscale; };
+  //! Enables/Disables autoscaling using findBestLayout().
+  void setAutoscale(bool on = true) { d_autoscale = on; };
 
 signals:
-	void showOptionsDialog();
-	void modified();
+  void showOptionsDialog();
+  void modified();
 
 private:
-	//! Wait this many msecs before redraw 3D plot (used for animations)
-  	int animation_redraw_wait;
-	//! File name of the color map used for the data (if any)
-  	QString color_map;
-
-	QTimer *d_timer;
-	QString title, plotAssociation;
-	QStringList labels;
-	QFont titleFnt;
-	bool legendOn, d_autoscale;
-	QVector<int> scaleType;
-	QColor axesCol,labelsCol,titleCol,meshCol,bgCol,numCol,gridCol;
-	//! Custom data colors.
-	QColor fromColor, toColor;
-	int labelsDist, legendMajorTicks;
-	bool ignoreFonts;
-	Qwt3D::StandardColor* col_;
-	double barsRad, alpha, d_point_size, crossHairRad, crossHairLineWidth, conesRad;
-	//! Draw 3D points with smoothed angles.
-	bool d_smooth_points;
-	bool crossHairSmooth, crossHairBoxed;
-	int conesQuality;
-	PointStyle pointStyle;
-	Table *d_table;
-	Matrix *d_matrix;
-    QPointer<Qwt3D::SurfacePlot> sp;
-    QScopedPointer<Function2D> d_func;
-	UserParametricSurface *d_surface;
-	Qwt3D::PLOTSTYLE style_;
-	
-	//scaling factor for zoom in the 3d graph
-	double m_zoomInScale;
-	//scaling factor for zoom out the 3d graph
-	double m_zoomOutScale;
-	int m_PreviousYpos;
+  //! Wait this many msecs before redraw 3D plot (used for animations)
+  int animation_redraw_wait;
+  //! File name of the color map used for the data (if any)
+  QString color_map;
+
+  QTimer *d_timer;
+  QString title, plotAssociation;
+  QStringList labels;
+  QFont titleFnt;
+  bool legendOn, d_autoscale;
+  QVector<int> scaleType;
+  QColor axesCol, labelsCol, titleCol, meshCol, bgCol, numCol, gridCol;
+  //! Custom data colors.
+  QColor fromColor, toColor;
+  int labelsDist, legendMajorTicks;
+  bool ignoreFonts;
+  Qwt3D::StandardColor *col_;
+  double barsRad, alpha, d_point_size, crossHairRad, crossHairLineWidth,
+      conesRad;
+  //! Draw 3D points with smoothed angles.
+  bool d_smooth_points;
+  bool crossHairSmooth, crossHairBoxed;
+  int conesQuality;
+  PointStyle pointStyle;
+  Table *d_table;
+  Matrix *d_matrix;
+  QPointer<Qwt3D::SurfacePlot> sp;
+  QScopedPointer<Function2D> d_func;
+  UserParametricSurface *d_surface;
+  Qwt3D::PLOTSTYLE style_;
+
+  // scaling factor for zoom in the 3d graph
+  double m_zoomInScale;
+  // scaling factor for zoom out the 3d graph
+  double m_zoomOutScale;
+  int m_PreviousYpos;
 };
 
 //! Class for user defined parametric surfaces
-class UserParametricSurface : public ParametricSurface
-{
+class UserParametricSurface : public ParametricSurface {
 public:
-    UserParametricSurface(const QString& xFormula, const QString& yFormula,
-						  const QString& zFormula, SurfacePlot& pw);
-    Triple operator()(double u, double v) override;
+  UserParametricSurface(const QString &xFormula, const QString &yFormula,
+                        const QString &zFormula, SurfacePlot &pw);
+  Triple operator()(double u, double v) override;
 
-        unsigned int rows(){return d_rows;};
-	unsigned int columns(){return d_columns;};
-	void setMesh (unsigned int columns, unsigned int rows);
+  unsigned int rows() { return d_rows; };
+  unsigned int columns() { return d_columns; };
+  void setMesh(unsigned int columns, unsigned int rows);
 
-	bool uPeriodic(){return d_u_periodic;};
-	bool vPeriodic(){return d_v_periodic;};
-	void setPeriodic (bool u, bool v);
+  bool uPeriodic() { return d_u_periodic; };
+  bool vPeriodic() { return d_v_periodic; };
+  void setPeriodic(bool u, bool v);
 
-	double uStart(){return d_ul;};
-	double uEnd(){return d_ur;};
-	double vStart(){return d_vl;};
-	double vEnd(){return d_vr;};
-	void setDomain(double ul, double ur, double vl, double vr);
+  double uStart() { return d_ul; };
+  double uEnd() { return d_ur; };
+  double vStart() { return d_vl; };
+  double vEnd() { return d_vr; };
+  void setDomain(double ul, double ur, double vl, double vr);
 
-	QString xFormula(){return d_x_formula;};
-	QString yFormula(){return d_y_formula;};
-	QString zFormula(){return d_z_formula;};
+  QString xFormula() { return d_x_formula; };
+  QString yFormula() { return d_y_formula; };
+  QString zFormula() { return d_z_formula; };
 
 private:
-	QString d_x_formula, d_y_formula, d_z_formula;
-	unsigned int d_rows, d_columns;
-	bool d_u_periodic, d_v_periodic;
-	double d_ul, d_ur, d_vl, d_vr;
+  QString d_x_formula, d_y_formula, d_z_formula;
+  unsigned int d_rows, d_columns;
+  bool d_u_periodic, d_v_periodic;
+  double d_ul, d_ur, d_vl, d_vr;
 };
 
 #endif // Plot3D_H
diff --git a/MantidPlot/src/Grid.cpp b/MantidPlot/src/Grid.cpp
index 95e7886c5eb37a07fd8c517b6696d86746b015b7..4d1ab028d36b978374211391888f3cd919f4f33f 100644
--- a/MantidPlot/src/Grid.cpp
+++ b/MantidPlot/src/Grid.cpp
@@ -38,17 +38,14 @@
 
 #include <QPainter>
 
-Grid::Grid() : QObject(), QwtPlotGrid(),
-d_maj_pen_y(QPen(Qt::blue, 0.5, Qt::SolidLine)),
-d_min_pen_y(QPen(Qt::gray, 0.4, Qt::DotLine)),
-mrkX(-1),
-mrkY(-1)
-{
-	setMajPen(QPen(Qt::blue, 0.5, Qt::SolidLine));
-	setMinPen(QPen(Qt::gray, 0.4, Qt::DotLine));
-	enableX(false);
-	enableY(false);
-    setRenderHint(QwtPlotItem::RenderAntialiased, false);
+Grid::Grid()
+    : QObject(), QwtPlotGrid(), d_maj_pen_y(QPen(Qt::blue, 0.5, Qt::SolidLine)),
+      d_min_pen_y(QPen(Qt::gray, 0.4, Qt::DotLine)), mrkX(-1), mrkY(-1) {
+  setMajPen(QPen(Qt::blue, 0.5, Qt::SolidLine));
+  setMinPen(QPen(Qt::gray, 0.4, Qt::DotLine));
+  enableX(false);
+  enableY(false);
+  setRenderHint(QwtPlotItem::RenderAntialiased, false);
 }
 
 /**
@@ -63,206 +60,207 @@ mrkY(-1)
   @param my :: Y axis
   @param r :: Contents rect of the plot canvas
   */
-void Grid::draw(QPainter *painter,
-		const QwtScaleMap &mx, const QwtScaleMap &my,
-		const QRect &r) const
-{
-	//  draw minor X gridlines
-	painter->setPen(minPen());
-
-	if (xMinEnabled()){
-		drawLines(painter, r, Qt::Vertical, mx,
-				xScaleDiv().ticks(QwtScaleDiv::MinorTick));
-		drawLines(painter, r, Qt::Vertical, mx,
-				xScaleDiv().ticks(QwtScaleDiv::MediumTick));
-	}
-
-	//  draw minor Y gridlines
-	painter->setPen(d_min_pen_y);
-
-	if (yMinEnabled()){
-		drawLines(painter, r, Qt::Horizontal, my,
-				yScaleDiv().ticks(QwtScaleDiv::MinorTick));
-		drawLines(painter, r, Qt::Horizontal, my,
-				yScaleDiv().ticks(QwtScaleDiv::MediumTick));
-	}
-
-	//  draw major X gridlines
-	painter->setPen(majPen());
-
-	if (xEnabled()){
-		drawLines(painter, r, Qt::Vertical, mx,
-				xScaleDiv().ticks (QwtScaleDiv::MajorTick));
-	}
-
-	//  draw major Y gridlines
-	painter->setPen(d_maj_pen_y);
-
-	if (yEnabled()){
-		drawLines(painter, r, Qt::Horizontal, my,
-				yScaleDiv().ticks (QwtScaleDiv::MajorTick));
-	}
+void Grid::draw(QPainter *painter, const QwtScaleMap &mx, const QwtScaleMap &my,
+                const QRect &r) const {
+  //  draw minor X gridlines
+  painter->setPen(minPen());
+
+  if (xMinEnabled()) {
+    drawLines(painter, r, Qt::Vertical, mx,
+              xScaleDiv().ticks(QwtScaleDiv::MinorTick));
+    drawLines(painter, r, Qt::Vertical, mx,
+              xScaleDiv().ticks(QwtScaleDiv::MediumTick));
+  }
+
+  //  draw minor Y gridlines
+  painter->setPen(d_min_pen_y);
+
+  if (yMinEnabled()) {
+    drawLines(painter, r, Qt::Horizontal, my,
+              yScaleDiv().ticks(QwtScaleDiv::MinorTick));
+    drawLines(painter, r, Qt::Horizontal, my,
+              yScaleDiv().ticks(QwtScaleDiv::MediumTick));
+  }
+
+  //  draw major X gridlines
+  painter->setPen(majPen());
+
+  if (xEnabled()) {
+    drawLines(painter, r, Qt::Vertical, mx,
+              xScaleDiv().ticks(QwtScaleDiv::MajorTick));
+  }
+
+  //  draw major Y gridlines
+  painter->setPen(d_maj_pen_y);
+
+  if (yEnabled()) {
+    drawLines(painter, r, Qt::Horizontal, my,
+              yScaleDiv().ticks(QwtScaleDiv::MajorTick));
+  }
 }
 
 void Grid::drawLines(QPainter *painter, const QRect &rect,
-		Qt::Orientation orientation, const QwtScaleMap &map,
-		const QwtValueList &values) const
-{
-	const int x1 = rect.left();
-	const int x2 = rect.right();
-	const int y1 = rect.top();
-	const int y2 = rect.bottom();
-
-	for (uint i = 0; i < (uint)values.count(); i++){
-		const int value = map.transform(values[i]);
-		if ( orientation == Qt::Horizontal ){
-			if ((value > y1) && (value < y2))
-				QwtPainter::drawLine(painter, x1, value, x2, value);
-		} else {
-			if ((value > x1) && (value < x2))
-				QwtPainter::drawLine(painter, value, y1, value, y2);
-		}
-	}
+                     Qt::Orientation orientation, const QwtScaleMap &map,
+                     const QwtValueList &values) const {
+  const int x1 = rect.left();
+  const int x2 = rect.right();
+  const int y1 = rect.top();
+  const int y2 = rect.bottom();
+
+  for (uint i = 0; i < (uint)values.count(); i++) {
+    const int value = map.transform(values[i]);
+    if (orientation == Qt::Horizontal) {
+      if ((value > y1) && (value < y2))
+        QwtPainter::drawLine(painter, x1, value, x2, value);
+    } else {
+      if ((value > x1) && (value < x2))
+        QwtPainter::drawLine(painter, value, y1, value, y2);
+    }
+  }
 }
 
-void Grid::load(const QStringList& grid)
-{
-    Plot *d_plot = dynamic_cast<Plot *>(plot());
-	if (!d_plot)
-		return;
-
-	bool majorOnX = grid[1].toInt();
-	bool minorOnX = grid[2].toInt();
-	bool majorOnY = grid[3].toInt();
-	bool minorOnY = grid[4].toInt();
-	bool xZeroOn = false;
-	bool yZeroOn = false;
-	int xAxis = QwtPlot::xBottom;
-	int yAxis = QwtPlot::yLeft;
-
-    QPen majPenX, minPenX, majPenY, minPenY;
-	if (grid.count() >= 21){ // since 0.9 final
-		majPenX = QPen(QColor(grid[5]), grid[7].toDouble(), Graph::getPenStyle(grid[6].toInt()));
-		minPenX = QPen(QColor(grid[8]), grid[10].toDouble(), Graph::getPenStyle(grid[9].toInt()));
-		majPenY = QPen(QColor(grid[11]), grid[13].toDouble(), Graph::getPenStyle(grid[12].toInt()));
-		minPenY = QPen(QColor(grid[14]), grid[16].toDouble(), Graph::getPenStyle(grid[15].toInt()));
-
-		xZeroOn = grid[17].toInt();
-		yZeroOn = grid[18].toInt();
-        xAxis = grid[19].toInt();
-        yAxis = grid[20].toInt();
-        if (grid.count() >= 22)
-            setRenderHint(QwtPlotItem::RenderAntialiased, grid[21].toInt());
-
-	} else { // older versions of QtiPlot (<= 0.9rc3)
-		majPenX = QPen(ColorBox::color(grid[5].toInt()), grid[7].toDouble(), Graph::getPenStyle(grid[6].toInt()));
-		minPenX = QPen(ColorBox::color(grid[8].toInt()), grid[10].toDouble(), Graph::getPenStyle(grid[9].toInt()));
-		majPenY = majPenX;
-		minPenY = minPenX;
-
-		xZeroOn = grid[11].toInt();
-		yZeroOn = grid[12].toInt();
-
-		if (grid.count() == 15){
-			xAxis = grid[13].toInt();
-			yAxis = grid[14].toInt();
-		}
-	}
-
-	setMajPenX(majPenX);
-	setMinPenX(minPenX);
-	setMajPenY(majPenY);
-	setMinPenY(minPenY);
-
-	enableX(majorOnX);
-	enableXMin(minorOnX);
-	enableY(majorOnY);
-	enableYMin(minorOnY);
-
-	setAxis(xAxis, yAxis);
-
-	enableZeroLineX(xZeroOn);
-	enableZeroLineY(yZeroOn);
+void Grid::load(const QStringList &grid) {
+  Plot *d_plot = dynamic_cast<Plot *>(plot());
+  if (!d_plot)
+    return;
+
+  bool majorOnX = grid[1].toInt();
+  bool minorOnX = grid[2].toInt();
+  bool majorOnY = grid[3].toInt();
+  bool minorOnY = grid[4].toInt();
+  bool xZeroOn = false;
+  bool yZeroOn = false;
+  int xAxis = QwtPlot::xBottom;
+  int yAxis = QwtPlot::yLeft;
+
+  QPen majPenX, minPenX, majPenY, minPenY;
+  if (grid.count() >= 21) { // since 0.9 final
+    majPenX = QPen(QColor(grid[5]), grid[7].toDouble(),
+                   Graph::getPenStyle(grid[6].toInt()));
+    minPenX = QPen(QColor(grid[8]), grid[10].toDouble(),
+                   Graph::getPenStyle(grid[9].toInt()));
+    majPenY = QPen(QColor(grid[11]), grid[13].toDouble(),
+                   Graph::getPenStyle(grid[12].toInt()));
+    minPenY = QPen(QColor(grid[14]), grid[16].toDouble(),
+                   Graph::getPenStyle(grid[15].toInt()));
+
+    xZeroOn = grid[17].toInt();
+    yZeroOn = grid[18].toInt();
+    xAxis = grid[19].toInt();
+    yAxis = grid[20].toInt();
+    if (grid.count() >= 22)
+      setRenderHint(QwtPlotItem::RenderAntialiased, grid[21].toInt());
+
+  } else { // older versions of QtiPlot (<= 0.9rc3)
+    majPenX = QPen(ColorBox::color(grid[5].toInt()), grid[7].toDouble(),
+                   Graph::getPenStyle(grid[6].toInt()));
+    minPenX = QPen(ColorBox::color(grid[8].toInt()), grid[10].toDouble(),
+                   Graph::getPenStyle(grid[9].toInt()));
+    majPenY = majPenX;
+    minPenY = minPenX;
+
+    xZeroOn = grid[11].toInt();
+    yZeroOn = grid[12].toInt();
+
+    if (grid.count() == 15) {
+      xAxis = grid[13].toInt();
+      yAxis = grid[14].toInt();
+    }
+  }
+
+  setMajPenX(majPenX);
+  setMinPenX(minPenX);
+  setMajPenY(majPenY);
+  setMinPenY(minPenY);
+
+  enableX(majorOnX);
+  enableXMin(minorOnX);
+  enableY(majorOnY);
+  enableYMin(minorOnY);
+
+  setAxis(xAxis, yAxis);
+
+  enableZeroLineX(xZeroOn);
+  enableZeroLineY(yZeroOn);
 }
 
-void Grid::enableZeroLineX(bool enable)
-{
+void Grid::enableZeroLineX(bool enable) {
   Plot *d_plot = dynamic_cast<Plot *>(plot());
-	if (!d_plot)
-		return;
-
-	if (mrkX<0 && enable){
-		QwtPlotMarker *m = new QwtPlotMarker();
-		mrkX = d_plot->insertMarker(m);
-		m->setRenderHint(QwtPlotItem::RenderAntialiased, false);
-		m->setAxis(xAxis(), yAxis());
-		m->setLineStyle(QwtPlotMarker::VLine);
-		m->setValue(0.0, 0.0);
-
-		double width = 1;
-		if (d_plot->canvas()->lineWidth())
-			width = d_plot->canvas()->lineWidth();
-		else if (d_plot->axisEnabled (QwtPlot::yLeft) || d_plot->axisEnabled (QwtPlot::yRight))
-			width =  d_plot->axesLinewidth();
-
-		m->setLinePen(QPen(Qt::black, width, Qt::SolidLine));
-	} else if (mrkX >= 0 && !enable) {
-		d_plot->removeMarker(mrkX);
-		mrkX=-1;
-	}
+  if (!d_plot)
+    return;
+
+  if (mrkX < 0 && enable) {
+    QwtPlotMarker *m = new QwtPlotMarker();
+    mrkX = d_plot->insertMarker(m);
+    m->setRenderHint(QwtPlotItem::RenderAntialiased, false);
+    m->setAxis(xAxis(), yAxis());
+    m->setLineStyle(QwtPlotMarker::VLine);
+    m->setValue(0.0, 0.0);
+
+    double width = 1;
+    if (d_plot->canvas()->lineWidth())
+      width = d_plot->canvas()->lineWidth();
+    else if (d_plot->axisEnabled(QwtPlot::yLeft) ||
+             d_plot->axisEnabled(QwtPlot::yRight))
+      width = d_plot->axesLinewidth();
+
+    m->setLinePen(QPen(Qt::black, width, Qt::SolidLine));
+  } else if (mrkX >= 0 && !enable) {
+    d_plot->removeMarker(mrkX);
+    mrkX = -1;
+  }
 }
 
-void Grid::enableZeroLineY(bool enable)
-{
+void Grid::enableZeroLineY(bool enable) {
   Plot *d_plot = dynamic_cast<Plot *>(plot());
-	if (!d_plot)
-		return;
-
-	if (mrkY<0 && enable) {
-		QwtPlotMarker *m = new QwtPlotMarker();
-		mrkY = d_plot->insertMarker(m);
-		m->setRenderHint(QwtPlotItem::RenderAntialiased, false);
-		m->setAxis(xAxis(), yAxis());
-		m->setLineStyle(QwtPlotMarker::HLine);
-		m->setValue(0.0, 0.0);
-
-		double width = 1;
-		if (d_plot->canvas()->lineWidth())
-			width = d_plot->canvas()->lineWidth();
-		else if (d_plot->axisEnabled (QwtPlot::xBottom) || d_plot->axisEnabled (QwtPlot::xTop))
-			width =  d_plot->axesLinewidth();
-
-		m->setLinePen(QPen(Qt::black, width, Qt::SolidLine));
-	} else if (mrkY>=0 && !enable){
-		d_plot->removeMarker(mrkY);
-		mrkY=-1;
-	}
+  if (!d_plot)
+    return;
+
+  if (mrkY < 0 && enable) {
+    QwtPlotMarker *m = new QwtPlotMarker();
+    mrkY = d_plot->insertMarker(m);
+    m->setRenderHint(QwtPlotItem::RenderAntialiased, false);
+    m->setAxis(xAxis(), yAxis());
+    m->setLineStyle(QwtPlotMarker::HLine);
+    m->setValue(0.0, 0.0);
+
+    double width = 1;
+    if (d_plot->canvas()->lineWidth())
+      width = d_plot->canvas()->lineWidth();
+    else if (d_plot->axisEnabled(QwtPlot::xBottom) ||
+             d_plot->axisEnabled(QwtPlot::xTop))
+      width = d_plot->axesLinewidth();
+
+    m->setLinePen(QPen(Qt::black, width, Qt::SolidLine));
+  } else if (mrkY >= 0 && !enable) {
+    d_plot->removeMarker(mrkY);
+    mrkY = -1;
+  }
 }
 
-void Grid::copy(Grid *grid)
-{
-	if (!grid)
-		return;
+void Grid::copy(Grid *grid) {
+  if (!grid)
+    return;
 
-	setMajPenX(grid->majPenX());
-	setMinPenX(grid->minPenX());
-	setMajPenY(grid->majPenY());
-	setMinPenY(grid->minPenY());
+  setMajPenX(grid->majPenX());
+  setMinPenX(grid->minPenX());
+  setMajPenY(grid->majPenY());
+  setMinPenY(grid->minPenY());
 
-	enableX(grid->xEnabled());
-	enableXMin(grid->xMinEnabled());
-	enableY(grid->yEnabled());
-	enableYMin(grid->yMinEnabled());
+  enableX(grid->xEnabled());
+  enableXMin(grid->xMinEnabled());
+  enableY(grid->yEnabled());
+  enableYMin(grid->yMinEnabled());
 
-	setAxis(grid->xAxis(), grid->yAxis());
+  setAxis(grid->xAxis(), grid->yAxis());
 
-	enableZeroLineX(grid->xZeroLineEnabled());
-	enableZeroLineY(grid->yZeroLineEnabled());
-	setRenderHint(QwtPlotItem::RenderAntialiased, grid->testRenderHint(QwtPlotItem::RenderAntialiased));
+  enableZeroLineX(grid->xZeroLineEnabled());
+  enableZeroLineY(grid->yZeroLineEnabled());
+  setRenderHint(QwtPlotItem::RenderAntialiased,
+                grid->testRenderHint(QwtPlotItem::RenderAntialiased));
 }
 
-std::string Grid::saveToString()
-{
+std::string Grid::saveToString() {
   TSVSerialiser tsv;
   tsv.writeLine("grid");
 
diff --git a/MantidPlot/src/Grid.h b/MantidPlot/src/Grid.h
index 9ad287ec3a694a34a94e62d3e4e8abe5a8cda8af..1c15ffc602c64b4e0516037b1d6ac1cc6e9fa7d9 100644
--- a/MantidPlot/src/Grid.h
+++ b/MantidPlot/src/Grid.h
@@ -33,43 +33,51 @@
 #include <qwt_plot_grid.h>
 #include <qwt_plot_marker.h>
 
-class Grid : public QObject, public QwtPlotGrid // Made a QObject just for our python proxies
-{
+class Grid : public QObject,
+             public QwtPlotGrid // Made a QObject just for our python proxies
+             {
   Q_OBJECT
 public:
-    Grid();
+  Grid();
 
-    bool xZeroLineEnabled(){return (mrkX >= 0)?true:false;};
-    void enableZeroLineX(bool enable = true);
-    bool yZeroLineEnabled(){return (mrkY >= 0)?true:false;};
-    void enableZeroLineY(bool enable = true);
+  bool xZeroLineEnabled() { return (mrkX >= 0) ? true : false; };
+  void enableZeroLineX(bool enable = true);
+  bool yZeroLineEnabled() { return (mrkY >= 0) ? true : false; };
+  void enableZeroLineY(bool enable = true);
 
-	void setMajPenX(const QPen &p){	setMajPen(p);};
-	const QPen& majPenX() const {return majPen();};
+  void setMajPenX(const QPen &p) { setMajPen(p); };
+  const QPen &majPenX() const { return majPen(); };
 
-	void setMinPenX(const QPen &p){	setMinPen(p);};
-	const QPen& minPenX() const {return minPen();};
+  void setMinPenX(const QPen &p) { setMinPen(p); };
+  const QPen &minPenX() const { return minPen(); };
 
-	void setMajPenY(const QPen &p){	if (d_maj_pen_y != p) d_maj_pen_y = p;};
-	const QPen& majPenY() const {return d_maj_pen_y;};
+  void setMajPenY(const QPen &p) {
+    if (d_maj_pen_y != p)
+      d_maj_pen_y = p;
+  };
+  const QPen &majPenY() const { return d_maj_pen_y; };
 
-	void setMinPenY(const QPen &p){	if (d_min_pen_y != p) d_min_pen_y = p;};
-	const QPen& minPenY() const {return d_min_pen_y;};
+  void setMinPenY(const QPen &p) {
+    if (d_min_pen_y != p)
+      d_min_pen_y = p;
+  };
+  const QPen &minPenY() const { return d_min_pen_y; };
 
-	void load(const QStringList& );
-	void copy(Grid *);
-	std::string saveToString();
+  void load(const QStringList &);
+  void copy(Grid *);
+  std::string saveToString();
 
 private:
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &rect) const override;
-        void drawLines(QPainter *painter, const QRect &rect, Qt::Orientation orientation, const QwtScaleMap &map,
-    	const QwtValueList &values) const;
+  void drawLines(QPainter *painter, const QRect &rect,
+                 Qt::Orientation orientation, const QwtScaleMap &map,
+                 const QwtValueList &values) const;
 
-	QPen d_maj_pen_y;
-	QPen d_min_pen_y;
+  QPen d_maj_pen_y;
+  QPen d_min_pen_y;
 
-	int mrkX, mrkY;//x=0 et y=0 line markers keys
+  int mrkX, mrkY; // x=0 et y=0 line markers keys
 };
 
 #endif
diff --git a/MantidPlot/src/GridDetails.h b/MantidPlot/src/GridDetails.h
index d05748d779045a25f66a7078f744500fa79e16c3..1176b87ad9943b988e78a2ae2e56b8581d344aea 100644
--- a/MantidPlot/src/GridDetails.h
+++ b/MantidPlot/src/GridDetails.h
@@ -1,10 +1,13 @@
 /**
-This class holds the widgets that hold the details for each axis so the contents are only filled once and switching axis only changes a pointer.
+This class holds the widgets that hold the details for each axis so the contents
+are only filled once and switching axis only changes a pointer.
 
-@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory from the University of Derby
+@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory
+from the University of Derby
 @date 24/09/2013
 
-Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -38,15 +41,15 @@ class ColorBox;
 class QComboBox;
 class DoubleSpinBox;
 class Grid;
-//The grid tab
-class GridDetails: public QWidget
-{
+// The grid tab
+class GridDetails : public QWidget {
   Q_OBJECT
 public:
-  GridDetails(ApplicationWindow* app, Graph* graph, int alignment, QWidget *parent = 0); // populate and fill in with existing data
+  GridDetails(ApplicationWindow *app, Graph *graph, int alignment,
+              QWidget *parent = 0); // populate and fill in with existing data
   ~GridDetails() override;
   void initWidgets();
-  bool modified(){return m_modified;}
+  bool modified() { return m_modified; }
   void apply(Grid *grid, bool antialias, bool multirun = false);
 public slots:
   void setModified();
@@ -62,8 +65,8 @@ private:
   QComboBox *m_cmbTypeMajor, *m_cmbTypeMinor, *m_cmbGridAxis;
   DoubleSpinBox *m_dspnWidthMajor, *m_dspnWidthMinor;
 
-  ApplicationWindow* m_app;
-  Graph* m_graph;
-  int m_alignment; //0 = horzontal, 1 = vertical, anything else sets this to 0;
+  ApplicationWindow *m_app;
+  Graph *m_graph;
+  int m_alignment; // 0 = horzontal, 1 = vertical, anything else sets this to 0;
 };
 #endif /* GRIDDETAILS_H_ */
\ No newline at end of file
diff --git a/MantidPlot/src/ImageDialog.h b/MantidPlot/src/ImageDialog.h
index 6456a864c411c007b79661f420b7840cb1ab0964..26276543bb58ad706cc2368f3a1554bebf2a6ea3 100644
--- a/MantidPlot/src/ImageDialog.h
+++ b/MantidPlot/src/ImageDialog.h
@@ -2,7 +2,8 @@
     File                 : ImageDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Image geometry dialog
 
@@ -35,35 +36,33 @@
 #include <QPushButton>
 
 //! Image geometry dialog
-class ImageDialog : public QDialog
-{
-    Q_OBJECT
+class ImageDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    ImageDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  ImageDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
-	void setOrigin(const QPoint& o);
-	void setSize(const QSize& size);
+  void setOrigin(const QPoint &o);
+  void setSize(const QSize &size);
 
 protected slots:
   void accept() override;
-        void update();
-	void adjustHeight(int width);
-	void adjustWidth(int height);
+  void update();
+  void adjustHeight(int width);
+  void adjustWidth(int height);
 
 signals:
-	void setGeometry(int, int, int, int);
+  void setGeometry(int, int, int, int);
 
 protected:
-	double aspect_ratio;
+  double aspect_ratio;
 
 private:
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel;
-	QPushButton* buttonApply;
-    QSpinBox* boxX, *boxY, *boxWidth, *boxHeight;
-	QCheckBox *keepRatioBox;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonApply;
+  QSpinBox *boxX, *boxY, *boxWidth, *boxHeight;
+  QCheckBox *keepRatioBox;
 };
 
-
 #endif // IMAGEDIALOG_H
diff --git a/MantidPlot/src/ImageExportDialog.cpp b/MantidPlot/src/ImageExportDialog.cpp
index e71589d83b10fdeddcd26c4b9dd211d5070c9b59..a2821826717913f1cf6416516d2f101029e83447 100644
--- a/MantidPlot/src/ImageExportDialog.cpp
+++ b/MantidPlot/src/ImageExportDialog.cpp
@@ -10,7 +10,6 @@
 
  ***************************************************************************/
 
-
 /***************************************************************************
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -41,270 +40,268 @@
 #include <QLabel>
 #include <QComboBox>
 
-ImageExportDialog::ImageExportDialog(QWidget * parent, bool vector_options, bool extended, Qt::WFlags flags)
-	: ExtensibleFileDialog( parent, extended, flags )
-{
-	setWindowTitle( tr( "MantidPlot - Choose a filename to save under" ) );
-	setAcceptMode(QFileDialog::AcceptSave);
+ImageExportDialog::ImageExportDialog(QWidget *parent, bool vector_options,
+                                     bool extended, Qt::WFlags flags)
+    : ExtensibleFileDialog(parent, extended, flags) {
+  setWindowTitle(tr("MantidPlot - Choose a filename to save under"));
+  setAcceptMode(QFileDialog::AcceptSave);
 
-	QList<QByteArray> list = QImageWriter::supportedImageFormats();
-	list<<"EPS";
-	list<<"PS";
-	list<<"PDF";
-	#if QT_VERSION >= 0x040300
-		list<<"SVG";
-	#endif
+  QList<QByteArray> list = QImageWriter::supportedImageFormats();
+  list << "EPS";
+  list << "PS";
+  list << "PDF";
+#if QT_VERSION >= 0x040300
+  list << "SVG";
+#endif
 
-    #if EMF_OUTPUT
-		list<<"EMF";
-	#endif
+#if EMF_OUTPUT
+  list << "EMF";
+#endif
 
-	QStringList filters;
-	for(int i=0 ; i<list.count() ; i++)
-		filters << "*."+list[i].toLower();
+  QStringList filters;
+  for (int i = 0; i < list.count(); i++)
+    filters << "*." + list[i].toLower();
 
-	filters.sort();
-	setFilters(filters);
-	setFileMode( QFileDialog::AnyFile );
+  filters.sort();
+  setFilters(filters);
+  setFileMode(QFileDialog::AnyFile);
 
-	initAdvancedOptions();
-	d_vector_options->setEnabled(vector_options);
-	setExtensionWidget(d_advanced_options);
+  initAdvancedOptions();
+  d_vector_options->setEnabled(vector_options);
+  setExtensionWidget(d_advanced_options);
 
 #if QT_VERSION >= 0x040300
-	connect(this, SIGNAL(filterSelected ( const QString & )),
-			this, SLOT(updateAdvancedOptions ( const QString & )));
+  connect(this, SIGNAL(filterSelected(const QString &)), this,
+          SLOT(updateAdvancedOptions(const QString &)));
 #else
-	QList<QComboBox*> combo_boxes = findChildren<QComboBox*>();
-	if (combo_boxes.size() >= 2)
-		connect(combo_boxes[1], SIGNAL(currentIndexChanged ( const QString & )),
-				this, SLOT(updateAdvancedOptions ( const QString & )));
+  QList<QComboBox *> combo_boxes = findChildren<QComboBox *>();
+  if (combo_boxes.size() >= 2)
+    connect(combo_boxes[1], SIGNAL(currentIndexChanged(const QString &)), this,
+            SLOT(updateAdvancedOptions(const QString &)));
 #endif
-	updateAdvancedOptions(selectedFilter());
+  updateAdvancedOptions(selectedFilter());
 }
 
-void ImageExportDialog::initAdvancedOptions()
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+void ImageExportDialog::initAdvancedOptions() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
   if (!app) {
-    throw std::logic_error("Parent of ImageExportDialog is not ApplicationWindow as expected.");
+    throw std::logic_error(
+        "Parent of ImageExportDialog is not ApplicationWindow as expected.");
   }
-	d_advanced_options = new QStackedWidget();
-
-	d_vector_options = new QGroupBox();
-	QGridLayout *vector_layout = new QGridLayout(d_vector_options);
-	d_advanced_options->addWidget(d_vector_options);
-
-    QLabel *resLabel = new QLabel(tr("Resolution (DPI)"));
-	vector_layout->addWidget(resLabel, 1, 0);
-	resLabel->hide();
-	d_resolution = new QSpinBox();
-	d_resolution->setRange(0, 1000);
-	//only printing with screen resolution works correctly for the moment
-	d_resolution->setValue(QPrinter().resolution());
-	vector_layout->addWidget(d_resolution, 1, 1);
-	d_resolution->hide();
-
-	d_color = new QCheckBox();
-	d_color->setText(tr("&Export in &color"));
-	d_color->setChecked(app->d_export_color);
-	vector_layout->addWidget(d_color, 2, 0, 1, 2);
-
-    d_standard_page = new QCheckBox();
-	d_standard_page->setText(tr("Custom &page size"));
-	vector_layout->addWidget(d_standard_page, 3, 0, 1, 2);
-
-	boxPageSize = new QComboBox();
-	boxPageSize->addItem("A0 - 841 x 1189 mm");
-	boxPageSize->addItem("A1 - 594 x 841 mm");
-	boxPageSize->addItem("A2 - 420 x 594 mm");
-	boxPageSize->addItem("A3 - 297 x 420 mm");
-	boxPageSize->addItem("A4 - 210 x 297 mm");
-	boxPageSize->addItem("A5 - 148 x 210 mm");
-	boxPageSize->addItem("A6 - 105 x 148 mm");
-	boxPageSize->addItem("A7 - 74 x 105 mm");
-	boxPageSize->addItem("A8 - 52 x 74 mm");
-	boxPageSize->addItem("A9 - 37 x 52 mm");
-	boxPageSize->addItem("B0 - 1030 x 1456 mm");
-	boxPageSize->addItem("B1 - 728 x 1030 mm");
-	boxPageSize->addItem("B2 - 515 x 728 mm");
-	boxPageSize->addItem("B3 - 364 x 515 mm");
-	boxPageSize->addItem("B4 - 257 x 364 mm");
-	boxPageSize->addItem("B5 - 182 x 257 mm");
-	boxPageSize->addItem("B6 - 128 x 182 mm");
-	boxPageSize->addItem("B7 - 91 x 128 mm");
-	boxPageSize->addItem("B8 - 64 x 91 mm");
-	boxPageSize->addItem("B9 - 45 x 64 mm");
-
-    setPageSize(app->d_export_vector_size);
-	d_standard_page->setChecked(app->d_export_vector_size != QPrinter::Custom);
-	boxPageSize->setEnabled(app->d_export_vector_size != QPrinter::Custom);
-	vector_layout->addWidget(boxPageSize, 3, 1, 1, 2);
-
-    connect(d_standard_page, SIGNAL(toggled(bool)), boxPageSize, SLOT(setEnabled(bool)));
-
-	d_keep_aspect = new QCheckBox();
-	d_keep_aspect->setText(tr("&Keep aspect ratio"));
-	d_keep_aspect->setChecked(app->d_keep_plot_aspect);
-	vector_layout->addWidget(d_keep_aspect, 4, 0, 1, 2);
-
-	d_raster_options = new QGroupBox();
-	QGridLayout *raster_layout = new QGridLayout(d_raster_options);
-	d_advanced_options->addWidget(d_raster_options);
-
-	raster_layout->addWidget(new QLabel(tr("Image quality")), 1, 0);
-	d_quality = new QSpinBox();
-	d_quality->setRange(1, 100);
-	d_quality->setValue(app->d_export_quality);
-	raster_layout->addWidget(d_quality, 1, 1);
-
-	d_transparency = new QCheckBox();
-	d_transparency->setText(tr("Save transparency"));
-	d_transparency->setChecked(app->d_export_transparency);
-	raster_layout->addWidget(d_transparency, 2, 0, 1, 2);
+  d_advanced_options = new QStackedWidget();
+
+  d_vector_options = new QGroupBox();
+  QGridLayout *vector_layout = new QGridLayout(d_vector_options);
+  d_advanced_options->addWidget(d_vector_options);
+
+  QLabel *resLabel = new QLabel(tr("Resolution (DPI)"));
+  vector_layout->addWidget(resLabel, 1, 0);
+  resLabel->hide();
+  d_resolution = new QSpinBox();
+  d_resolution->setRange(0, 1000);
+  // only printing with screen resolution works correctly for the moment
+  d_resolution->setValue(QPrinter().resolution());
+  vector_layout->addWidget(d_resolution, 1, 1);
+  d_resolution->hide();
+
+  d_color = new QCheckBox();
+  d_color->setText(tr("&Export in &color"));
+  d_color->setChecked(app->d_export_color);
+  vector_layout->addWidget(d_color, 2, 0, 1, 2);
+
+  d_standard_page = new QCheckBox();
+  d_standard_page->setText(tr("Custom &page size"));
+  vector_layout->addWidget(d_standard_page, 3, 0, 1, 2);
+
+  boxPageSize = new QComboBox();
+  boxPageSize->addItem("A0 - 841 x 1189 mm");
+  boxPageSize->addItem("A1 - 594 x 841 mm");
+  boxPageSize->addItem("A2 - 420 x 594 mm");
+  boxPageSize->addItem("A3 - 297 x 420 mm");
+  boxPageSize->addItem("A4 - 210 x 297 mm");
+  boxPageSize->addItem("A5 - 148 x 210 mm");
+  boxPageSize->addItem("A6 - 105 x 148 mm");
+  boxPageSize->addItem("A7 - 74 x 105 mm");
+  boxPageSize->addItem("A8 - 52 x 74 mm");
+  boxPageSize->addItem("A9 - 37 x 52 mm");
+  boxPageSize->addItem("B0 - 1030 x 1456 mm");
+  boxPageSize->addItem("B1 - 728 x 1030 mm");
+  boxPageSize->addItem("B2 - 515 x 728 mm");
+  boxPageSize->addItem("B3 - 364 x 515 mm");
+  boxPageSize->addItem("B4 - 257 x 364 mm");
+  boxPageSize->addItem("B5 - 182 x 257 mm");
+  boxPageSize->addItem("B6 - 128 x 182 mm");
+  boxPageSize->addItem("B7 - 91 x 128 mm");
+  boxPageSize->addItem("B8 - 64 x 91 mm");
+  boxPageSize->addItem("B9 - 45 x 64 mm");
+
+  setPageSize(app->d_export_vector_size);
+  d_standard_page->setChecked(app->d_export_vector_size != QPrinter::Custom);
+  boxPageSize->setEnabled(app->d_export_vector_size != QPrinter::Custom);
+  vector_layout->addWidget(boxPageSize, 3, 1, 1, 2);
+
+  connect(d_standard_page, SIGNAL(toggled(bool)), boxPageSize,
+          SLOT(setEnabled(bool)));
+
+  d_keep_aspect = new QCheckBox();
+  d_keep_aspect->setText(tr("&Keep aspect ratio"));
+  d_keep_aspect->setChecked(app->d_keep_plot_aspect);
+  vector_layout->addWidget(d_keep_aspect, 4, 0, 1, 2);
+
+  d_raster_options = new QGroupBox();
+  QGridLayout *raster_layout = new QGridLayout(d_raster_options);
+  d_advanced_options->addWidget(d_raster_options);
+
+  raster_layout->addWidget(new QLabel(tr("Image quality")), 1, 0);
+  d_quality = new QSpinBox();
+  d_quality->setRange(1, 100);
+  d_quality->setValue(app->d_export_quality);
+  raster_layout->addWidget(d_quality, 1, 1);
+
+  d_transparency = new QCheckBox();
+  d_transparency->setText(tr("Save transparency"));
+  d_transparency->setChecked(app->d_export_transparency);
+  raster_layout->addWidget(d_transparency, 2, 0, 1, 2);
 }
 
-void ImageExportDialog::updateAdvancedOptions (const QString & filter)
-{
-	if (filter.contains("*.svg") || filter.contains("*.emf")) {
-		d_extension_toggle->setChecked(false);
-		d_extension_toggle->setEnabled(false);
-		return;
-	}
-	d_extension_toggle->setEnabled(true);
-	if (filter.contains("*.eps") || filter.contains("*.ps") || filter.contains("*.pdf"))
-		d_advanced_options->setCurrentIndex(0);
-	else {
-		d_advanced_options->setCurrentIndex(1);
-		d_transparency->setEnabled(filter.contains("*.tif") || filter.contains("*.tiff") || filter.contains("*.png") || filter.contains("*.xpm"));
-	}
+void ImageExportDialog::updateAdvancedOptions(const QString &filter) {
+  if (filter.contains("*.svg") || filter.contains("*.emf")) {
+    d_extension_toggle->setChecked(false);
+    d_extension_toggle->setEnabled(false);
+    return;
+  }
+  d_extension_toggle->setEnabled(true);
+  if (filter.contains("*.eps") || filter.contains("*.ps") ||
+      filter.contains("*.pdf"))
+    d_advanced_options->setCurrentIndex(0);
+  else {
+    d_advanced_options->setCurrentIndex(1);
+    d_transparency->setEnabled(
+        filter.contains("*.tif") || filter.contains("*.tiff") ||
+        filter.contains("*.png") || filter.contains("*.xpm"));
+  }
 }
 
-void ImageExportDialog::closeEvent(QCloseEvent* e)
-{
-	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-	if (app){
-		app->d_extended_export_dialog = this->isExtended();
-		app->d_image_export_filter = this->selectedFilter();
-		app->d_export_transparency = d_transparency->isChecked();
-        app->d_export_quality = d_quality->value();
-
-        app->d_export_resolution = d_resolution->value();
-        app->d_export_color = d_color->isChecked();
-        app->d_export_vector_size = (int)pageSize();
-        app->d_keep_plot_aspect = d_keep_aspect->isChecked();
-	}
-
-	e->accept();
+void ImageExportDialog::closeEvent(QCloseEvent *e) {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (app) {
+    app->d_extended_export_dialog = this->isExtended();
+    app->d_image_export_filter = this->selectedFilter();
+    app->d_export_transparency = d_transparency->isChecked();
+    app->d_export_quality = d_quality->value();
+
+    app->d_export_resolution = d_resolution->value();
+    app->d_export_color = d_color->isChecked();
+    app->d_export_vector_size = (int)pageSize();
+    app->d_keep_plot_aspect = d_keep_aspect->isChecked();
+  }
+
+  e->accept();
 }
 
-QPrinter::PageSize ImageExportDialog::pageSize() const
-{
-if (!d_standard_page->isChecked())
+QPrinter::PageSize ImageExportDialog::pageSize() const {
+  if (!d_standard_page->isChecked())
     return QPrinter::Custom;
 
-QPrinter::PageSize size = QPrinter::A4;
-switch (boxPageSize->currentIndex())
-	{
-	case 0:
-		size = QPrinter::A0;
-	break;
-
-	case 1:
-		size = QPrinter::A1;
-	break;
-
-	case 2:
-		size = QPrinter::A2;
-	break;
-
-	case 3:
-		size = QPrinter::A3;
-	break;
-
-	case 4:
-		size = QPrinter::A4;
-	break;
-
-	case 5:
-		size = QPrinter::A5;
-	break;
-
-	case 6:
-		size = QPrinter::A6;
-	break;
-
-	case 7:
-		size = QPrinter::A7;
-	break;
-
-	case 8:
-		size = QPrinter::A8;
-	break;
-
-	case 9:
-		size = QPrinter::A9;
-	break;
-
-	case 10:
-		size = QPrinter::B0;
-	break;
-
-	case 11:
-		size = QPrinter::B1;
-	break;
-
-	case 12:
-		size = QPrinter::B2;
-	break;
-
-	case 13:
-		size = QPrinter::B3;
-	break;
-
-	case 14:
-		size = QPrinter::B4;
-	break;
-
-	case 15:
-		size = QPrinter::B5;
-	break;
-
-	case 16:
-		size = QPrinter::B6;
-	break;
-
-	case 17:
-		size = QPrinter::B7;
-	break;
-
-	case 18:
-		size = QPrinter::B8;
-	break;
-
-	case 19:
-		size = QPrinter::B9;
-	break;
-	}
-return size;
+  QPrinter::PageSize size = QPrinter::A4;
+  switch (boxPageSize->currentIndex()) {
+  case 0:
+    size = QPrinter::A0;
+    break;
+
+  case 1:
+    size = QPrinter::A1;
+    break;
+
+  case 2:
+    size = QPrinter::A2;
+    break;
+
+  case 3:
+    size = QPrinter::A3;
+    break;
+
+  case 4:
+    size = QPrinter::A4;
+    break;
+
+  case 5:
+    size = QPrinter::A5;
+    break;
+
+  case 6:
+    size = QPrinter::A6;
+    break;
+
+  case 7:
+    size = QPrinter::A7;
+    break;
+
+  case 8:
+    size = QPrinter::A8;
+    break;
+
+  case 9:
+    size = QPrinter::A9;
+    break;
+
+  case 10:
+    size = QPrinter::B0;
+    break;
+
+  case 11:
+    size = QPrinter::B1;
+    break;
+
+  case 12:
+    size = QPrinter::B2;
+    break;
+
+  case 13:
+    size = QPrinter::B3;
+    break;
+
+  case 14:
+    size = QPrinter::B4;
+    break;
+
+  case 15:
+    size = QPrinter::B5;
+    break;
+
+  case 16:
+    size = QPrinter::B6;
+    break;
+
+  case 17:
+    size = QPrinter::B7;
+    break;
+
+  case 18:
+    size = QPrinter::B8;
+    break;
+
+  case 19:
+    size = QPrinter::B9;
+    break;
+  }
+  return size;
 }
 
-void ImageExportDialog::setPageSize(int size)
-{
-if (size == QPrinter::Custom)
+void ImageExportDialog::setPageSize(int size) {
+  if (size == QPrinter::Custom)
     return;
-if (!size)
+  if (!size)
     boxPageSize->setCurrentIndex(4);
-else if (size == 1)
+  else if (size == 1)
     boxPageSize->setCurrentIndex(15);
-else if (size >= 5 && size <= 8)
+  else if (size >= 5 && size <= 8)
     boxPageSize->setCurrentIndex(size - 5);
-else if (size > 8 && size <= 23)
+  else if (size > 8 && size <= 23)
     boxPageSize->setCurrentIndex(size - 4);
 }
 
-void ImageExportDialog::selectFilter(const QString & filter)
-{
-	QFileDialog::selectFilter(filter);
-	updateAdvancedOptions(filter);
+void ImageExportDialog::selectFilter(const QString &filter) {
+  QFileDialog::selectFilter(filter);
+  updateAdvancedOptions(filter);
 }
diff --git a/MantidPlot/src/ImageExportDialog.h b/MantidPlot/src/ImageExportDialog.h
index c85f3e49d20d2be4844e231403f6469e50d8f1cd..3758b17196fb17f7ce43e05d2fe747e1ece85bb4 100644
--- a/MantidPlot/src/ImageExportDialog.h
+++ b/MantidPlot/src/ImageExportDialog.h
@@ -42,59 +42,65 @@ class QStackedWidget;
 class QGroupBox;
 
 //! QFileDialog extended with options for image export
-class ImageExportDialog: public ExtensibleFileDialog
-{
-	Q_OBJECT
+class ImageExportDialog : public ExtensibleFileDialog {
+  Q_OBJECT
 
 private:
-	//! Create #d_advanced_options and everything it contains.
-	void initAdvancedOptions();
+  //! Create #d_advanced_options and everything it contains.
+  void initAdvancedOptions();
 
-	//! Container widget for all advanced options.
-	QStackedWidget *d_advanced_options;
-	// vector format options
-	//! Container widget for all options available for vector formats.
-	QGroupBox *d_vector_options;
-	QSpinBox *d_resolution;
-	QCheckBox *d_color;
-	QCheckBox *d_keep_aspect;
-	QCheckBox *d_standard_page;
-	QComboBox *boxPageSize;
-	// raster format options
-	//! Container widget for all options available for raster formats.
-	QGroupBox *d_raster_options;
-	QSpinBox *d_quality;
-	QCheckBox *d_transparency;
+  //! Container widget for all advanced options.
+  QStackedWidget *d_advanced_options;
+  // vector format options
+  //! Container widget for all options available for vector formats.
+  QGroupBox *d_vector_options;
+  QSpinBox *d_resolution;
+  QCheckBox *d_color;
+  QCheckBox *d_keep_aspect;
+  QCheckBox *d_standard_page;
+  QComboBox *boxPageSize;
+  // raster format options
+  //! Container widget for all options available for raster formats.
+  QGroupBox *d_raster_options;
+  QSpinBox *d_quality;
+  QCheckBox *d_transparency;
 
 public:
-	//! Constructor
-	/**
-	 * @param parent :: parent widget
-	 * @param vector_options :: whether advanced options are to be provided for export to vector formats
-	 * @param extended :: flag: show/hide the advanced options on start-up
-	 * @param flags :: window flags
-	 */
-	ImageExportDialog(QWidget * parent = 0, bool vector_options = true, bool extended = true, Qt::WFlags flags = 0 );
-	//! For vector formats: returns the output resolution the user selected, defaulting to the screen resolution.
-	int resolution() const { return d_resolution->value(); }
-	//! For vector formats: returns whether colors should be enabled for ouput (default: true).
-	bool color() const { return d_color->isChecked(); }
-	//! For vector formats: returns whether the output should preserve aspect ratio of the plot (default: true).
-	bool keepAspect() const { return d_keep_aspect->isChecked(); }
-    //! For vector formats: returns a standard output page size (default: QPrinter::Custom).
-	QPrinter::PageSize pageSize() const;
-	void setPageSize(int size);
-	//! Return the quality (in percent) the user selected for export to raster formats.
-	int quality() const { return d_quality->value(); }
-	//! Return whether the output's background should be transparent.
-	bool transparency() const { return d_transparency->isChecked(); }
+  //! Constructor
+  /**
+   * @param parent :: parent widget
+   * @param vector_options :: whether advanced options are to be provided for
+   * export to vector formats
+   * @param extended :: flag: show/hide the advanced options on start-up
+   * @param flags :: window flags
+   */
+  ImageExportDialog(QWidget *parent = 0, bool vector_options = true,
+                    bool extended = true, Qt::WFlags flags = 0);
+  //! For vector formats: returns the output resolution the user selected,
+  // defaulting to the screen resolution.
+  int resolution() const { return d_resolution->value(); }
+  //! For vector formats: returns whether colors should be enabled for ouput
+  //(default: true).
+  bool color() const { return d_color->isChecked(); }
+  //! For vector formats: returns whether the output should preserve aspect
+  // ratio of the plot (default: true).
+  bool keepAspect() const { return d_keep_aspect->isChecked(); }
+  //! For vector formats: returns a standard output page size (default:
+  // QPrinter::Custom).
+  QPrinter::PageSize pageSize() const;
+  void setPageSize(int size);
+  //! Return the quality (in percent) the user selected for export to raster
+  // formats.
+  int quality() const { return d_quality->value(); }
+  //! Return whether the output's background should be transparent.
+  bool transparency() const { return d_transparency->isChecked(); }
+
+  void selectFilter(const QString &filter);
 
-	void selectFilter(const QString & filter);
-	
 protected slots:
   void closeEvent(QCloseEvent *) override;
-        //! Update which options are visible and enabled based on the output format.
-	void updateAdvancedOptions (const QString &filter);
+  //! Update which options are visible and enabled based on the output format.
+  void updateAdvancedOptions(const QString &filter);
 };
 
 #endif
diff --git a/MantidPlot/src/ImageMarker.cpp b/MantidPlot/src/ImageMarker.cpp
index aa750774ad73fe045eeb74659c99f83540a16a29..8446f13ab588db54a18a46ee66bbf0fc15d3bd01 100644
--- a/MantidPlot/src/ImageMarker.cpp
+++ b/MantidPlot/src/ImageMarker.cpp
@@ -31,109 +31,102 @@
 #include <QPainter>
 #include <QImageReader>
 
-ImageMarker::ImageMarker(const QString& fn):
-	d_pos(QPoint(0,0)),
-	d_x_right(0),
-    d_y_bottom(0)
-{
-	QList<QByteArray> lst = QImageReader::supportedImageFormats();
-	for (int i=0; i<(int)lst.count(); i++){
-		if (fn.contains("." + lst[i])){
-			d_pic.load(fn, lst[i], Qt::ImageConversionFlag::AutoColor);
-
-			d_size = d_pic.size();
-			d_file_name = fn;
-			break;
-		}
-	}
+ImageMarker::ImageMarker(const QString &fn)
+    : d_pos(QPoint(0, 0)), d_x_right(0), d_y_bottom(0) {
+  QList<QByteArray> lst = QImageReader::supportedImageFormats();
+  for (int i = 0; i < (int)lst.count(); i++) {
+    if (fn.contains("." + lst[i])) {
+      d_pic.load(fn, lst[i], Qt::ImageConversionFlag::AutoColor);
+
+      d_size = d_pic.size();
+      d_file_name = fn;
+      break;
+    }
+  }
 }
 
-void ImageMarker::draw (QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const
-{
-    const int x0 = xMap.transform(xValue());
-	const int y0 = yMap.transform(yValue());
-	const int x1 = xMap.transform(d_x_right);
-	const int y1 = yMap.transform(d_y_bottom);
+void ImageMarker::draw(QPainter *p, const QwtScaleMap &xMap,
+                       const QwtScaleMap &yMap, const QRect &) const {
+  const int x0 = xMap.transform(xValue());
+  const int y0 = yMap.transform(yValue());
+  const int x1 = xMap.transform(d_x_right);
+  const int y1 = yMap.transform(d_y_bottom);
 
-	p->drawPixmap(QRect(x0, y0, abs(x1 - x0), abs(y1 - y0)), d_pic);
+  p->drawPixmap(QRect(x0, y0, abs(x1 - x0), abs(y1 - y0)), d_pic);
 }
 
-void ImageMarker::setSize(const QSize& size)
-{
-    d_size = size;
-    updateBoundingRect();
+void ImageMarker::setSize(const QSize &size) {
+  d_size = size;
+  updateBoundingRect();
 }
 
-void ImageMarker::setOrigin(const QPoint& p)
-{
-    d_pos = p;
+void ImageMarker::setOrigin(const QPoint &p) {
+  d_pos = p;
 
-    if (!plot())
-        return;
+  if (!plot())
+    return;
 
-    setXValue(plot()->invTransform(xAxis(), p.x()));
-    setYValue(plot()->invTransform(yAxis(), p.y()));
+  setXValue(plot()->invTransform(xAxis(), p.x()));
+  setYValue(plot()->invTransform(yAxis(), p.y()));
 
-    d_size = size();
-    updateBoundingRect();
+  d_size = size();
+  updateBoundingRect();
 }
 
-void ImageMarker::setRect(int x, int y, int w, int h)
-{
-    if (d_pos == QPoint(x, y) && d_size == QSize(w, h))
-        return;
+void ImageMarker::setRect(int x, int y, int w, int h) {
+  if (d_pos == QPoint(x, y) && d_size == QSize(w, h))
+    return;
 
-    d_pos = QPoint(x, y);
-    d_size = QSize(w, h);
-    updateBoundingRect();
+  d_pos = QPoint(x, y);
+  d_size = QSize(w, h);
+  updateBoundingRect();
 }
 
-void ImageMarker::setBoundingRect(double left, double top, double right, double bottom)
-{
-    if (xValue() == left && yValue() == top && d_x_right == right && d_y_bottom == bottom)
-        return;
+void ImageMarker::setBoundingRect(double left, double top, double right,
+                                  double bottom) {
+  if (xValue() == left && yValue() == top && d_x_right == right &&
+      d_y_bottom == bottom)
+    return;
 
-    setXValue(left);
-    setYValue(top);
-    d_x_right = right;
-    d_y_bottom = bottom;
+  setXValue(left);
+  setYValue(top);
+  d_x_right = right;
+  d_y_bottom = bottom;
 
-    if (!plot())
-        return;
+  if (!plot())
+    return;
 
-    plot()->updateLayout();
+  plot()->updateLayout();
 
-    QRect r = this->rect();
-    d_pos = r.topLeft();
-    d_size = r.size();
+  QRect r = this->rect();
+  d_pos = r.topLeft();
+  d_size = r.size();
 }
 
-void ImageMarker::updateBoundingRect()
-{
-    if (!plot())
-        return;
+void ImageMarker::updateBoundingRect() {
+  if (!plot())
+    return;
 
-    setXValue(plot()->invTransform(xAxis(), d_pos.x()));
-    d_x_right = plot()->invTransform(xAxis(), d_pos.x() + d_size.width());
+  setXValue(plot()->invTransform(xAxis(), d_pos.x()));
+  d_x_right = plot()->invTransform(xAxis(), d_pos.x() + d_size.width());
 
-    setYValue(plot()->invTransform(yAxis(), d_pos.y()));
-    d_y_bottom = plot()->invTransform(yAxis(), d_pos.y() + d_size.height());
+  setYValue(plot()->invTransform(yAxis(), d_pos.y()));
+  d_y_bottom = plot()->invTransform(yAxis(), d_pos.y() + d_size.height());
 }
 
-QwtDoubleRect ImageMarker::boundingRect() const
-{
-    return QwtDoubleRect(xValue(), yValue(), qAbs(d_x_right - xValue()), qAbs(d_y_bottom - yValue()));
+QwtDoubleRect ImageMarker::boundingRect() const {
+  return QwtDoubleRect(xValue(), yValue(), qAbs(d_x_right - xValue()),
+                       qAbs(d_y_bottom - yValue()));
 }
 
-QRect ImageMarker::rect() const
-{
-    const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-    const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+QRect ImageMarker::rect() const {
+  const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+  const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
 
-    const int x0 = xMap.transform(xValue());
-    const int y0 = yMap.transform(yValue());
-    const int x1 = xMap.transform(d_x_right);
-    const int y1 = yMap.transform(d_y_bottom);
+  const int x0 = xMap.transform(xValue());
+  const int y0 = yMap.transform(yValue());
+  const int x1 = xMap.transform(d_x_right);
+  const int y1 = yMap.transform(d_y_bottom);
 
-    return QRect(x0, y0, abs(x1 - x0), abs(y1 - y0));
+  return QRect(x0, y0, abs(x1 - x0), abs(y1 - y0));
 }
diff --git a/MantidPlot/src/ImageMarker.h b/MantidPlot/src/ImageMarker.h
index e9146a86a280443bc9b5a3fc90dce4c6389212e2..fb04ba53518a034754764e642bb067b781d412bb 100644
--- a/MantidPlot/src/ImageMarker.h
+++ b/MantidPlot/src/ImageMarker.h
@@ -36,84 +36,96 @@
 /**\brief Draw images on a QwtPlot.
  *
  * ImageMarker draws #d_pic at the position specified by #d_pos,
- * scaled to #d_size. #d_file_name isn't used internally, but only provided to help
+ * scaled to #d_size. #d_file_name isn't used internally, but only provided to
+ *help
  * Graph manage save/restore.
  *
  * \section future Future Plans
- * Add a QwtPlotItem subclass (PlotEnrichment ?) and make ImageMarker, Legend and ArrowMarker
- * subclasses of that. These (usually) don't really mark a specific point in a plot and they don't
- * use the symbol/label functionality of QwtPlotMarker. Instead, it would make sense to provide a
- * unified move/resize (or even general affine transformations via QMatrix) interface and support for
- * positioning them either at fixed plot coordinates (like QwtPlotMarker) or at a fixed drawing
- * position within a QwtPlot (like a QWidget child); leaving the choice of positioning policy to the
+ * Add a QwtPlotItem subclass (PlotEnrichment ?) and make ImageMarker, Legend
+ *and ArrowMarker
+ * subclasses of that. These (usually) don't really mark a specific point in a
+ *plot and they don't
+ * use the symbol/label functionality of QwtPlotMarker. Instead, it would make
+ *sense to provide a
+ * unified move/resize (or even general affine transformations via QMatrix)
+ *interface and support for
+ * positioning them either at fixed plot coordinates (like QwtPlotMarker) or at
+ *a fixed drawing
+ * position within a QwtPlot (like a QWidget child); leaving the choice of
+ *positioning policy to the
  * user.
- * If PlotEnrichment (ideas for a better name?) inherits from both QWidget and QwtPlotItem (which
- * is luckily no QObject) and provides a unified drawing framework, its instances could be added
+ * If PlotEnrichment (ideas for a better name?) inherits from both QWidget and
+ *QwtPlotItem (which
+ * is luckily no QObject) and provides a unified drawing framework, its
+ *instances could be added
  * directly to MultiLayer without the need for a dummy Graph in between.
  * Could also help to avoid the hack in MultiLayer::updateMarkersBoundingRect().
  *
- * Following the above thoughts, it might help clarify the purpose of ImageMarker, Legend
+ * Following the above thoughts, it might help clarify the purpose of
+ *ImageMarker, Legend
  * and ArrowMarker if they are renamed according to the new superclasse's name
  * (e.g. ImageEnrichment, TextEnrichment and LineEnrichment).
  *
- * See the documentation of SelectionMoveResizer for other advantages of this approach.
+ * See the documentation of SelectionMoveResizer for other advantages of this
+ *approach.
  *
  * \sa Legend, ArrowMarker
  */
-class ImageMarker : public QwtPlotMarker
-{
+class ImageMarker : public QwtPlotMarker {
 public:
-	//! Construct an image marker from a file name.
+  //! Construct an image marker from a file name.
   explicit ImageMarker(const QString &fn);
 
-        //! Return bounding rectangle in paint coordinates.
-	QRect rect() const;
-	//! Set value (position) and #d_size, giving everything in paint coordinates.
-	void setRect(int x, int y, int w, int h);
+  //! Return bounding rectangle in paint coordinates.
+  QRect rect() const;
+  //! Set value (position) and #d_size, giving everything in paint coordinates.
+  void setRect(int x, int y, int w, int h);
 
-	//! Return bounding rectangle in plot coordinates.
-        QwtDoubleRect boundingRect() const override;
-        //! Set position (xValue() and yValue()), right and bottom values giving everything in plot coordinates.
-	void setBoundingRect(double left, double top, double right, double bottom);
+  //! Return bounding rectangle in plot coordinates.
+  QwtDoubleRect boundingRect() const override;
+  //! Set position (xValue() and yValue()), right and bottom values giving
+  // everything in plot coordinates.
+  void setBoundingRect(double left, double top, double right, double bottom);
 
-	double right(){return d_x_right;};
-	double bottom(){return d_y_bottom;};
+  double right() { return d_x_right; };
+  double bottom() { return d_y_bottom; };
 
-	//! Return #d_size.
-	QSize size() {return rect().size();};
-	//! Set #d_size.
-	void setSize(const QSize& size);
-	//! Set #d_size. Provided for convenience in scripts 
-	void setSize(int w, int h){setSize(QSize(w, h));};
+  //! Return #d_size.
+  QSize size() { return rect().size(); };
+  //! Set #d_size.
+  void setSize(const QSize &size);
+  //! Set #d_size. Provided for convenience in scripts
+  void setSize(int w, int h) { setSize(QSize(w, h)); };
 
-	//! Return position in paint coordinates.
-	QPoint origin() const { return rect().topLeft(); };
-	//! Set QwtPlotMarker::value() in paint coordinates.
-	void setOrigin(const QPoint &p);
-	//! Set QwtPlotMarker::value() in paint coordinates. Convenience function.
-	void setOrigin(int x, int y){setOrigin(QPoint(x, y));};
+  //! Return position in paint coordinates.
+  QPoint origin() const { return rect().topLeft(); };
+  //! Set QwtPlotMarker::value() in paint coordinates.
+  void setOrigin(const QPoint &p);
+  //! Set QwtPlotMarker::value() in paint coordinates. Convenience function.
+  void setOrigin(int x, int y) { setOrigin(QPoint(x, y)); };
 
-	//! Set #d_file_name.
-	void setFileName(const QString& fn) { d_file_name = fn; };
-	//! Return #d_file_name.
-	QString fileName(){return d_file_name;};
+  //! Set #d_file_name.
+  void setFileName(const QString &fn) { d_file_name = fn; };
+  //! Return #d_file_name.
+  QString fileName() { return d_file_name; };
 
-	//! Return the pixmap to be drawn, #d_pic.
-	QPixmap pixmap() const {return d_pic;};
+  //! Return the pixmap to be drawn, #d_pic.
+  QPixmap pixmap() const { return d_pic; };
 
-	void updateBoundingRect();
+  void updateBoundingRect();
 
 private:
-	//! Does the actual drawing; see QwtPlotItem::draw.
+  //! Does the actual drawing; see QwtPlotItem::draw.
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &r) const override;
 
-        QPoint d_pos;         //!< The position in paint coordinates.
-	QPixmap d_pic;        //!< The pixmap to be drawn.
-	QSize d_size;         //!< The size (in paint coordinates) to which #d_pic will be scaled in draw().
-	QString d_file_name;  //!< The file from which the image was loaded.
-	double d_x_right;     //!< The right side position in scale coordinates.
-  double d_y_bottom;    //!< The bottom side position in scale coordinates.
+  QPoint d_pos;  //!< The position in paint coordinates.
+  QPixmap d_pic; //!< The pixmap to be drawn.
+  QSize d_size;  //!< The size (in paint coordinates) to which #d_pic will be
+  // scaled in draw().
+  QString d_file_name; //!< The file from which the image was loaded.
+  double d_x_right;    //!< The right side position in scale coordinates.
+  double d_y_bottom;   //!< The bottom side position in scale coordinates.
 };
 
 #endif
diff --git a/MantidPlot/src/ImportASCIIDialog.h b/MantidPlot/src/ImportASCIIDialog.h
index 583b0236f8c5511bd2e6139396d896be595819cd..5c4ad1ce109dc8168db1df5cad8757da5ef3d966 100644
--- a/MantidPlot/src/ImportASCIIDialog.h
+++ b/MantidPlot/src/ImportASCIIDialog.h
@@ -45,151 +45,162 @@ class MatrixModel;
 
 #include <QTableWidget>
 
-class PreviewTable : public QTableWidget
-{
+class PreviewTable : public QTableWidget {
 public:
-    PreviewTable(int numRows, int numCols, QWidget * parent = 0, const char * name = 0);
+  PreviewTable(int numRows, int numCols, QWidget *parent = 0,
+               const char *name = 0);
 
-	void importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
-	bool stripSpaces, bool simplifySpaces, bool importComments, const QString& commentString,
-	int importMode, int endLine, int maxRows);
+  void importASCII(const QString &fname, const QString &sep, int ignoredLines,
+                   bool renameCols, bool stripSpaces, bool simplifySpaces,
+                   bool importComments, const QString &commentString,
+                   int importMode, int endLine, int maxRows);
   QString text(int row, int col) const;
-  void setText(int row, int col, const QString& txt);
+  void setText(int row, int col, const QString &txt);
   void insertColumns(int col, int count = 1);
 
-	void resetHeader();
-	void clear();
-	void updateDecimalSeparators(const QLocale& oldSeparators);
-	void setNumericPrecision(int prec) {d_numeric_precision = prec;};
+  void resetHeader();
+  void clear();
+  void updateDecimalSeparators(const QLocale &oldSeparators);
+  void setNumericPrecision(int prec) { d_numeric_precision = prec; };
 
 private:
-	void setHeader();
-	void addColumns(int c);
-  QTableWidgetItem* addNewItem(int row, int col);
+  void setHeader();
+  void addColumns(int c);
+  QTableWidgetItem *addNewItem(int row, int col);
   void makeItemPrototype();
-	QStringList comments, col_label;
-	int d_numeric_precision;
-  QTableWidgetItem* m_itemPrototype;
+  QStringList comments, col_label;
+  int d_numeric_precision;
+  QTableWidgetItem *m_itemPrototype;
 };
 
-class PreviewMatrix : public QTableView
-{
+class PreviewMatrix : public QTableView {
 public:
-    PreviewMatrix(QWidget *parent, Matrix * m = 0);
+  PreviewMatrix(QWidget *parent, Matrix *m = 0);
 
-	void importASCII(const QString &fname, const QString &sep, int ignoredLines,
-		bool stripSpaces, bool simplifySpaces, const QString& commentString,
-		int importAs, const QLocale& locale, int endLine, int maxRows);
+  void importASCII(const QString &fname, const QString &sep, int ignoredLines,
+                   bool stripSpaces, bool simplifySpaces,
+                   const QString &commentString, int importAs,
+                   const QLocale &locale, int endLine, int maxRows);
 
-	void clear();
+  void clear();
 
 private:
-	 MatrixModel *d_matrix_model;
+  MatrixModel *d_matrix_model;
 };
 
 //! Import ASCII file(s) dialog
-class ImportASCIIDialog: public ExtensibleFileDialog
-{
-	Q_OBJECT
+class ImportASCIIDialog : public ExtensibleFileDialog {
+  Q_OBJECT
 
 public:
-	//! Possible destinations for the imported data.
-	/**
-	 * Important: Keep this in sync with the initialization of #d_import_mode in initAdvancedOptions().
-	 */
-	enum ImportMode {
-		NewTables, //!< create a new table for each file (default)
-		NewMatrices, //!< create a new matrix for each file
-		NewWorkspace, //!< create a new workspace  for each file 
-		NewColumns, //!< add each file as new columns to the current table
-		NewRows, //!< add each file as new rows to the current table
-		Overwrite //!< replace content of current table with the selected file (like importing a single file in previous versions of QtiPlot)
-		
-	};
-
-	//! Constructor
-	/**
-	 * @param importModeEnabled :: flag: enable/disable import mode combo box
-	 * @param parent :: parent widget (only affects placement of the dialog)
-	 * @param extended :: flag: show/hide the advanced options on start-up
-	 * @param flags :: window flags
-	 */
-	ImportASCIIDialog(bool new_windows_only, QWidget * parent = 0, bool extended = true, Qt::WFlags flags = 0 );
-
-	//! Return the selected import mode
-	/**
-	 * \sa ImportMode
-	 */
-	ImportMode importMode() const { return (ImportMode) d_import_mode->currentIndex(); }
-	//! Return the selected column separator.
-	const QString columnSeparator() const;
-	//! Return the number of lines to be skipped at the start of each file.
-	int ignoredLines() const { return d_ignored_lines->value(); }
-	//! Whether to rename columns based on the first (non-skipped) line.
-	bool renameColumns() const { return d_rename_columns->isChecked(); }
-	//! Whether to replace sequences of whitespace charecters with a single space.
-	bool simplifySpaces() const { return d_simplify_spaces->isChecked(); }
-	//! Whether to remove whitespace from beginning and end of lines.
-	bool stripSpaces() const { return d_strip_spaces->isChecked(); }
-	//! Whether the user wants the import options to be saved.
-	bool readOnly() const {return d_read_only->isChecked(); }
-
-	//! Set the selected columns separator.
-	void setColumnSeparator(const QString &sep);
-
-	//! Returns a locale having the decimal separators set to user custom settings.
-	QLocale decimalSeparators();
-	//! Whether the user wants the decimal separators to be changed to application settings.
-	bool updateDecimalSeparators() const { return d_import_dec_separators->isChecked(); };
-
-    //! Returns a string used to comment lines when importing ASCII files
-	QString commentString(){return d_comment_string->text();};
-
-    //! Returns true if the second line of the ASCII file should be used to set comments in table
-    bool importComments(){return d_import_comments->isChecked();};
-	
-	//! Returns the convention used for the end line character!
-	inline int endLineChar(){return boxEndLine->currentIndex();};
-	///
-	QString getselectedColumnSeparator();
-		
+  //! Possible destinations for the imported data.
+  /**
+   * Important: Keep this in sync with the initialization of #d_import_mode in
+   * initAdvancedOptions().
+   */
+  enum ImportMode {
+    NewTables,    //!< create a new table for each file (default)
+    NewMatrices,  //!< create a new matrix for each file
+    NewWorkspace, //!< create a new workspace  for each file
+    NewColumns,   //!< add each file as new columns to the current table
+    NewRows,      //!< add each file as new rows to the current table
+    Overwrite //!< replace content of current table with the selected file (like
+    // importing a single file in previous versions of QtiPlot)
+
+  };
+
+  //! Constructor
+  /**
+   * @param importModeEnabled :: flag: enable/disable import mode combo box
+   * @param parent :: parent widget (only affects placement of the dialog)
+   * @param extended :: flag: show/hide the advanced options on start-up
+   * @param flags :: window flags
+   */
+  ImportASCIIDialog(bool new_windows_only, QWidget *parent = 0,
+                    bool extended = true, Qt::WFlags flags = 0);
+
+  //! Return the selected import mode
+  /**
+   * \sa ImportMode
+   */
+  ImportMode importMode() const {
+    return (ImportMode)d_import_mode->currentIndex();
+  }
+  //! Return the selected column separator.
+  const QString columnSeparator() const;
+  //! Return the number of lines to be skipped at the start of each file.
+  int ignoredLines() const { return d_ignored_lines->value(); }
+  //! Whether to rename columns based on the first (non-skipped) line.
+  bool renameColumns() const { return d_rename_columns->isChecked(); }
+  //! Whether to replace sequences of whitespace charecters with a single space.
+  bool simplifySpaces() const { return d_simplify_spaces->isChecked(); }
+  //! Whether to remove whitespace from beginning and end of lines.
+  bool stripSpaces() const { return d_strip_spaces->isChecked(); }
+  //! Whether the user wants the import options to be saved.
+  bool readOnly() const { return d_read_only->isChecked(); }
+
+  //! Set the selected columns separator.
+  void setColumnSeparator(const QString &sep);
+
+  //! Returns a locale having the decimal separators set to user custom
+  // settings.
+  QLocale decimalSeparators();
+  //! Whether the user wants the decimal separators to be changed to application
+  // settings.
+  bool updateDecimalSeparators() const {
+    return d_import_dec_separators->isChecked();
+  };
+
+  //! Returns a string used to comment lines when importing ASCII files
+  QString commentString() { return d_comment_string->text(); };
+
+  //! Returns true if the second line of the ASCII file should be used to set
+  // comments in table
+  bool importComments() { return d_import_comments->isChecked(); };
+
+  //! Returns the convention used for the end line character!
+  inline int endLineChar() { return boxEndLine->currentIndex(); };
+  ///
+  QString getselectedColumnSeparator();
+
 private slots:
-	//! Display help for advanced options.
-	void displayHelp();
-	//! For #Overwrite mode, allow only one file to be selected.
-	void updateImportMode(int mode);
-	void preview();
-	void changePreviewFile(const QString& path);
-	//! Enable/Disable options which are only available for tables.
-	void enableTableOptions(bool on);
+  //! Display help for advanced options.
+  void displayHelp();
+  //! For #Overwrite mode, allow only one file to be selected.
+  void updateImportMode(int mode);
+  void preview();
+  void changePreviewFile(const QString &path);
+  //! Enable/Disable options which are only available for tables.
+  void enableTableOptions(bool on);
 
 private:
-	void initPreview(int previewMode);
-	void previewTable();
-	void previewMatrix();
-
-        void closeEvent(QCloseEvent *) override;
-        //! Initialise #d_advanced_options and everything it contains.
-	void initAdvancedOptions();
-	void setNewWindowsOnly(bool on);
-	void addColumnSeparators();
-	void addColumnSeparatorsforLoadAscii();
-	
-
-	//! Container widget for all advanced options.
-	QGroupBox *d_advanced_options;
-	QCheckBox *d_read_only, *d_import_dec_separators;
-	QPushButton *d_help_button;
-	// the actual options
-	QComboBox *d_import_mode, *d_column_separator, *boxDecimalSeparator, *boxEndLine;
-	QSpinBox *d_ignored_lines, *d_preview_lines_box;
-	QCheckBox *d_rename_columns, *d_simplify_spaces, *d_strip_spaces, *d_import_comments;
-	QLineEdit *d_comment_string;
-	PreviewTable *d_preview_table;
-	PreviewMatrix *d_preview_matrix;
-	QCheckBox *d_preview_button;
-	QStackedWidget *d_preview_stack;
-	QString d_current_path;
+  void initPreview(int previewMode);
+  void previewTable();
+  void previewMatrix();
+
+  void closeEvent(QCloseEvent *) override;
+  //! Initialise #d_advanced_options and everything it contains.
+  void initAdvancedOptions();
+  void setNewWindowsOnly(bool on);
+  void addColumnSeparators();
+  void addColumnSeparatorsforLoadAscii();
+
+  //! Container widget for all advanced options.
+  QGroupBox *d_advanced_options;
+  QCheckBox *d_read_only, *d_import_dec_separators;
+  QPushButton *d_help_button;
+  // the actual options
+  QComboBox *d_import_mode, *d_column_separator, *boxDecimalSeparator,
+      *boxEndLine;
+  QSpinBox *d_ignored_lines, *d_preview_lines_box;
+  QCheckBox *d_rename_columns, *d_simplify_spaces, *d_strip_spaces,
+      *d_import_comments;
+  QLineEdit *d_comment_string;
+  PreviewTable *d_preview_table;
+  PreviewMatrix *d_preview_matrix;
+  QCheckBox *d_preview_button;
+  QStackedWidget *d_preview_stack;
+  QString d_current_path;
 };
 
 #endif
diff --git a/MantidPlot/src/IntDialog.h b/MantidPlot/src/IntDialog.h
index 3dfa31257374107d989a673e0e986422d7b6c1ee..d77192a6863ed32a082c55b27d21a0bda947f87f 100644
--- a/MantidPlot/src/IntDialog.h
+++ b/MantidPlot/src/IntDialog.h
@@ -40,29 +40,28 @@ class DoubleSpinBox;
 class Graph;
 
 //! Integration options dialog
-class IntDialog : public QDialog
-{
-    Q_OBJECT
+class IntDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    IntDialog(QWidget* parent = 0, Graph *g = 0, Qt::WFlags fl = 0 );
+  IntDialog(QWidget *parent = 0, Graph *g = 0, Qt::WFlags fl = 0);
 
 public slots:
   void accept() override;
 
 private:
-	Graph *d_graph;
+  Graph *d_graph;
 
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel;
-    QCheckBox* boxPlot;
-	QTextEdit* boxName;
-	QLineEdit* boxVariable;
-	QSpinBox* boxOrder;
-	QSpinBox* boxSteps;
-	DoubleSpinBox* boxStart;
-	DoubleSpinBox* boxEnd;
-	DoubleSpinBox* boxTol;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QCheckBox *boxPlot;
+  QTextEdit *boxName;
+  QLineEdit *boxVariable;
+  QSpinBox *boxOrder;
+  QSpinBox *boxSteps;
+  DoubleSpinBox *boxStart;
+  DoubleSpinBox *boxEnd;
+  DoubleSpinBox *boxTol;
 };
 
 #endif
diff --git a/MantidPlot/src/Integration.cpp b/MantidPlot/src/Integration.cpp
index c174f3fdc5e67bfe082be82324ab6cd622229d2c..a2585baaf09bda70286adf8252361c15b0d3de43 100644
--- a/MantidPlot/src/Integration.cpp
+++ b/MantidPlot/src/Integration.cpp
@@ -38,208 +38,211 @@
 
 #include <gsl/gsl_vector.h>
 
-Integration::Integration(const QString& formula, const QString& var, ApplicationWindow *parent, Graph *g, double start, double end)
-: Filter(parent, g),
-d_formula(formula),
-d_variable(var)
-{
-	d_init_err = false;
-	d_n = 0;
-	d_from = start;
-	d_to = end;
-	if (d_to == d_from)
-		d_init_err = true;
-
-	MyParser parser;
-	double x = 0.0;
-	parser.DefineVar(d_variable.toAscii().constData(), &x);
-	parser.SetExpr(d_formula.toAscii().constData());
-	try {
-		parser.Eval();
-	} catch(mu::ParserError &e) {
-		QMessageBox::critical(parent, tr("MantidPlot - Input error"), QString::fromStdString(e.GetMsg()));
-		d_init_err = true;
-	}
-
-	setObjectName(tr("Integration"));
-	d_integrand = AnalyticalFunction;
-	d_method = 1;
-    d_max_iterations = 20;
-    d_sort_data = false;
-    d_area = 0.0;
+Integration::Integration(const QString &formula, const QString &var,
+                         ApplicationWindow *parent, Graph *g, double start,
+                         double end)
+    : Filter(parent, g), d_formula(formula), d_variable(var) {
+  d_init_err = false;
+  d_n = 0;
+  d_from = start;
+  d_to = end;
+  if (d_to == d_from)
+    d_init_err = true;
+
+  MyParser parser;
+  double x = 0.0;
+  parser.DefineVar(d_variable.toAscii().constData(), &x);
+  parser.SetExpr(d_formula.toAscii().constData());
+  try {
+    parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(parent, tr("MantidPlot - Input error"),
+                          QString::fromStdString(e.GetMsg()));
+    d_init_err = true;
+  }
+
+  setObjectName(tr("Integration"));
+  d_integrand = AnalyticalFunction;
+  d_method = 1;
+  d_max_iterations = 20;
+  d_sort_data = false;
+  d_area = 0.0;
 }
 
 Integration::Integration(ApplicationWindow *parent, Graph *g)
-: Filter(parent, g)
-{
-	init();
+    : Filter(parent, g) {
+  init();
 }
 
-Integration::Integration(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Filter(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+Integration::Integration(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-Integration::Integration(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Filter(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+Integration::Integration(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle, double start, double end)
+    : Filter(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-Integration::Integration(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end)
-: Filter(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, start, end);
+Integration::Integration(ApplicationWindow *parent, Table *t,
+                         const QString &xCol, const QString &yCol, int start,
+                         int end)
+    : Filter(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, start, end);
 }
 
-void Integration::init()
-{
-	setObjectName(tr("Integration"));
-	d_integrand = DataSet;
-	d_method = 1;
-    d_max_iterations = 1;
-    d_sort_data = true;
-    d_area = 0.0;
+void Integration::init() {
+  setObjectName(tr("Integration"));
+  d_integrand = DataSet;
+  d_method = 1;
+  d_max_iterations = 1;
+  d_sort_data = true;
+  d_area = 0.0;
 }
 
-double Integration::trapez()
-{
-	double sum = 0.0;
-	int size = d_n - 1;
-	for(int i=0; i < size; i++){
-		int j = i + 1;
-		sum += 0.5*(d_y[j] + d_y[i])*(d_x[j] - d_x[i]);
-	}
-    return sum;
+double Integration::trapez() {
+  double sum = 0.0;
+  int size = d_n - 1;
+  for (int i = 0; i < size; i++) {
+    int j = i + 1;
+    sum += 0.5 * (d_y[j] + d_y[i]) * (d_x[j] - d_x[i]);
+  }
+  return sum;
 }
 
-double Integration::trapezf(int n)
-{
-    MyParser parser;
-	double x = d_from;
-	parser.DefineVar(d_variable.toAscii().constData(), &x);
-	parser.SetExpr(d_formula.toAscii().constData());
-
-    static double s;
-    if (n == 1){
-		double aux = parser.Eval();
-		x = d_to;
-        return (s = 0.5*(d_to - d_from)*(aux + parser.Eval()));
-    } else {
-        int it = 1;
-        for(int j=1; j < n-1; j++)
-            it<<=1;
-
-        double tnm = it;
-        double del = (d_to - d_from)/tnm;
-        x = d_from + 0.5*del;
-        double sum = 0.0;
-        for(int j=1; j <= it; j++, x += del)
-            sum += parser.Eval();
-
-        s = 0.5*(s + (d_to - d_from)*sum/tnm);
-        return s;
-    }
+double Integration::trapezf(int n) {
+  MyParser parser;
+  double x = d_from;
+  parser.DefineVar(d_variable.toAscii().constData(), &x);
+  parser.SetExpr(d_formula.toAscii().constData());
+
+  static double s;
+  if (n == 1) {
+    double aux = parser.Eval();
+    x = d_to;
+    return (s = 0.5 * (d_to - d_from) * (aux + parser.Eval()));
+  } else {
+    int it = 1;
+    for (int j = 1; j < n - 1; j++)
+      it <<= 1;
+
+    double tnm = it;
+    double del = (d_to - d_from) / tnm;
+    x = d_from + 0.5 * del;
+    double sum = 0.0;
+    for (int j = 1; j <= it; j++, x += del)
+      sum += parser.Eval();
+
+    s = 0.5 * (s + (d_to - d_from) * sum / tnm);
+    return s;
+  }
 }
 
 // Using Numerical Recipes. This is Romberg Integration method.
-int Integration::romberg()
-{
-    d_area = 0.0;
-	double *s = new double[d_max_iterations + 1];
-	double *h = new double[d_max_iterations + 2];
-	h[1] = 1.0;
-	int j;
-	for(j = 1; j <= d_max_iterations; j++){
-        s[j] = trapezf(j);
-		if(j > d_method){
-		    double ss, dss;
-			polint(&h[j-d_method], &s[j-d_method], d_method, 0.0, &ss, &dss);
-			if (fabs(dss) <= d_tolerance * fabs(ss)){
-                d_area = ss;
-                break;
-			}
-		}
-		h[j+1] = 0.25*h[j];
-	}
-    delete[] s;
-    delete[] h;
-    return j;
+int Integration::romberg() {
+  d_area = 0.0;
+  double *s = new double[d_max_iterations + 1];
+  double *h = new double[d_max_iterations + 2];
+  h[1] = 1.0;
+  int j;
+  for (j = 1; j <= d_max_iterations; j++) {
+    s[j] = trapezf(j);
+    if (j > d_method) {
+      double ss, dss;
+      polint(&h[j - d_method], &s[j - d_method], d_method, 0.0, &ss, &dss);
+      if (fabs(dss) <= d_tolerance * fabs(ss)) {
+        d_area = ss;
+        break;
+      }
+    }
+    h[j + 1] = 0.25 * h[j];
+  }
+  delete[] s;
+  delete[] h;
+  return j;
 }
 
-QString Integration::logInfo()
-{
+QString Integration::logInfo() {
   ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-  if (!app) return "";
-    QLocale locale = app->locale();
-    int prec = app->d_decimal_digits;
-
-	QString logInfo = "[" + QDateTime::currentDateTime().toString(Qt::LocalDate);
-	if (d_integrand == AnalyticalFunction){
-		logInfo += "\n" + tr("Numerical integration of") + " f(" + d_variable + ") = " + d_formula + " ";
-		logInfo += tr("using a %1 order method").arg(d_method) + "\n";
-		logInfo += tr("From") + " x = " + locale.toString(d_from, 'g', prec) + " ";
-		logInfo += tr("to") + " x = " + locale.toString(d_to, 'g', prec) + "\n";
-		logInfo += tr("Tolerance") + " = " + locale.toString(d_tolerance, 'g', prec) + "\n";
-		logInfo += tr("Iterations") + ": " + QString::number(romberg()) + "\n";
-	} else if (d_integrand == DataSet){
-		if (d_graph)
-			logInfo += tr("\tPlot")+ ": ''" + d_graph->multiLayer()->objectName() + "'']\n";
-		else
-			logInfo += "\n";
-		QString dataSet;
-		if (d_curve)
-			dataSet = d_curve->title().text();
-		else
-			dataSet = d_y_col_name;
-		logInfo += "\n" + tr("Numerical integration of") + ": " + dataSet + " ";
-		logInfo += tr("using the Trapezoidal Rule") + "\n";
-		logInfo += tr("Points") + ": " + QString::number(d_n) + " " + tr("from") + " x = " + locale.toString(d_from, 'g', prec) + " ";
-    	logInfo += tr("to") + " x = " + locale.toString(d_to, 'g', prec) + "\n";
-
-		// use GSL to find maximum value of data set
-		gsl_vector *aux = gsl_vector_alloc(d_n);
-		for(int i=0; i < d_n; i++)
-			gsl_vector_set (aux, i, fabs(d_y[i]));
-		int maxID = static_cast<int>(gsl_vector_max_index (aux));
-		gsl_vector_free(aux);
-
-    	logInfo += tr("Peak at") + " x = " + locale.toString(d_x[maxID], 'g', prec)+"\t";
-		logInfo += "y = " + locale.toString(d_y[maxID], 'g', prec)+"\n";
-		d_area = trapez();
-	}
-
-	logInfo += tr("Area") + "=" + locale.toString(d_area, 'g', prec);
-	logInfo += "\n-------------------------------------------------------------\n";
-    return logInfo;
+  if (!app)
+    return "";
+  QLocale locale = app->locale();
+  int prec = app->d_decimal_digits;
+
+  QString logInfo = "[" + QDateTime::currentDateTime().toString(Qt::LocalDate);
+  if (d_integrand == AnalyticalFunction) {
+    logInfo += "\n" + tr("Numerical integration of") + " f(" + d_variable +
+               ") = " + d_formula + " ";
+    logInfo += tr("using a %1 order method").arg(d_method) + "\n";
+    logInfo += tr("From") + " x = " + locale.toString(d_from, 'g', prec) + " ";
+    logInfo += tr("to") + " x = " + locale.toString(d_to, 'g', prec) + "\n";
+    logInfo += tr("Tolerance") + " = " +
+               locale.toString(d_tolerance, 'g', prec) + "\n";
+    logInfo += tr("Iterations") + ": " + QString::number(romberg()) + "\n";
+  } else if (d_integrand == DataSet) {
+    if (d_graph)
+      logInfo +=
+          tr("\tPlot") + ": ''" + d_graph->multiLayer()->objectName() + "'']\n";
+    else
+      logInfo += "\n";
+    QString dataSet;
+    if (d_curve)
+      dataSet = d_curve->title().text();
+    else
+      dataSet = d_y_col_name;
+    logInfo += "\n" + tr("Numerical integration of") + ": " + dataSet + " ";
+    logInfo += tr("using the Trapezoidal Rule") + "\n";
+    logInfo += tr("Points") + ": " + QString::number(d_n) + " " + tr("from") +
+               " x = " + locale.toString(d_from, 'g', prec) + " ";
+    logInfo += tr("to") + " x = " + locale.toString(d_to, 'g', prec) + "\n";
+
+    // use GSL to find maximum value of data set
+    gsl_vector *aux = gsl_vector_alloc(d_n);
+    for (int i = 0; i < d_n; i++)
+      gsl_vector_set(aux, i, fabs(d_y[i]));
+    int maxID = static_cast<int>(gsl_vector_max_index(aux));
+    gsl_vector_free(aux);
+
+    logInfo +=
+        tr("Peak at") + " x = " + locale.toString(d_x[maxID], 'g', prec) + "\t";
+    logInfo += "y = " + locale.toString(d_y[maxID], 'g', prec) + "\n";
+    d_area = trapez();
+  }
+
+  logInfo += tr("Area") + "=" + locale.toString(d_area, 'g', prec);
+  logInfo +=
+      "\n-------------------------------------------------------------\n";
+  return logInfo;
 }
 
-void Integration::setMethodOrder(int n)
-{
-    if (n < 1 || n > 5){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Error"),
-        tr("Unknown integration method. Valid values must be in the range: 1 (Trapezoidal Method) to 5."));
-        return;
-    }
-    d_method = n;
+void Integration::setMethodOrder(int n) {
+  if (n < 1 || n > 5) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()),
+                          tr("MantidPlot - Error"),
+                          tr("Unknown integration method. Valid values must be "
+                             "in the range: 1 (Trapezoidal Method) to 5."));
+    return;
+  }
+  d_method = n;
 }
 
-void Integration::output()
-{
-    if(d_integrand != AnalyticalFunction || d_init_err)
-        return;
+void Integration::output() {
+  if (d_integrand != AnalyticalFunction || d_init_err)
+    return;
 
-    if (!d_output_graph)
-        return;
+  if (!d_output_graph)
+    return;
 
-    FunctionCurve* c = d_output_graph->addFunction(QStringList(d_formula), d_from, d_to, d_points,
-                    d_variable, FunctionCurve::Normal);
-    if (c){
-        c->setBrush(QBrush(c->pen().color(), Qt::BDiagPattern));
-        d_output_graph->replot();
-    }
+  FunctionCurve *c =
+      d_output_graph->addFunction(QStringList(d_formula), d_from, d_to,
+                                  d_points, d_variable, FunctionCurve::Normal);
+  if (c) {
+    c->setBrush(QBrush(c->pen().color(), Qt::BDiagPattern));
+    d_output_graph->replot();
+  }
 }
diff --git a/MantidPlot/src/Integration.h b/MantidPlot/src/Integration.h
index ffe3ecd1f207d2a85636a3956c7dda80bd6ae321..3ba6142383ebbd93c12bcb5dc88c8ab7c4fc9751 100644
--- a/MantidPlot/src/Integration.h
+++ b/MantidPlot/src/Integration.h
@@ -31,48 +31,50 @@
 
 #include "Filter.h"
 
-class Integration : public Filter
-{
-Q_OBJECT
+class Integration : public Filter {
+  Q_OBJECT
 
 public:
-	enum Integrand{DataSet, AnalyticalFunction};
+  enum Integrand { DataSet, AnalyticalFunction };
 
-	Integration(ApplicationWindow *parent, Graph *g);
-	Integration(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-	Integration(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-	Integration(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end);
-	Integration(const QString& formula, const QString& var, ApplicationWindow *parent,
-                Graph *g, double start, double end);
+  Integration(ApplicationWindow *parent, Graph *g);
+  Integration(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  Integration(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+              double start, double end);
+  Integration(ApplicationWindow *parent, Table *t, const QString &xCol,
+              const QString &yCol, int start, int end);
+  Integration(const QString &formula, const QString &var,
+              ApplicationWindow *parent, Graph *g, double start, double end);
 
-    int method(){return d_method;};
-    void setMethodOrder(int n);
+  int method() { return d_method; };
+  void setMethodOrder(int n);
 
-    double area(){return d_area;};
+  double area() { return d_area; };
 
 private:
-    void init();
-    QString logInfo() override;
+  void init();
+  QString logInfo() override;
 
-    void output() override;
+  void output() override;
 
-        double trapez();
-	double trapezf(int n);
-    //! Returns the number of iterations used to calculate the area if d_integrand = AnalyticalFunction.
-    int romberg();
+  double trapez();
+  double trapezf(int n);
+  //! Returns the number of iterations used to calculate the area if d_integrand
+  //= AnalyticalFunction.
+  int romberg();
 
-    //! the integration method: 1 = trapezoidal, max = 5!
-    int d_method;
+  //! the integration method: 1 = trapezoidal, max = 5!
+  int d_method;
 
-    //! the value of the integral
-    double d_area;
+  //! the value of the integral
+  double d_area;
 
-	//! the type of the integrand
-	Integrand d_integrand;
-	//! Analytical function to be integrated
-	QString d_formula;
-	//! Variable name for the function to be integrated
-	QString d_variable;
+  //! the type of the integrand
+  Integrand d_integrand;
+  //! Analytical function to be integrated
+  QString d_formula;
+  //! Variable name for the function to be integrated
+  QString d_variable;
 };
 
 #endif
diff --git a/MantidPlot/src/Interpolation.cpp b/MantidPlot/src/Interpolation.cpp
index db4dfc68dfbd02f91be0790a80c05e93a0f7c014..af5858f0c22806807b06e9b9f54cac1f3f6a5c85 100644
--- a/MantidPlot/src/Interpolation.cpp
+++ b/MantidPlot/src/Interpolation.cpp
@@ -34,166 +34,167 @@
 #include <gsl/gsl_spline.h>
 #include <gsl/gsl_interp.h>
 
-Interpolation::Interpolation(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m)
-: Filter(parent, g)
-{
-	init(m);
-	setDataFromCurve(curveTitle);
+Interpolation::Interpolation(ApplicationWindow *parent, Graph *g,
+                             const QString &curveTitle, int m)
+    : Filter(parent, g) {
+  init(m);
+  setDataFromCurve(curveTitle);
 }
 
-Interpolation::Interpolation(ApplicationWindow *parent, Graph *g, const QString& curveTitle,
-                             double start, double end, int m)
-: Filter(parent, g)
-{
-	init(m);
-	setDataFromCurve(curveTitle, start, end);
+Interpolation::Interpolation(ApplicationWindow *parent, Graph *g,
+                             const QString &curveTitle, double start,
+                             double end, int m)
+    : Filter(parent, g) {
+  init(m);
+  setDataFromCurve(curveTitle, start, end);
 }
 
-Interpolation::Interpolation(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end, int m)
-: Filter(parent, t)
-{
-	init(m);
-	setDataFromTable(t, xCol, yCol, start, end);
+Interpolation::Interpolation(ApplicationWindow *parent, Table *t,
+                             const QString &xCol, const QString &yCol,
+                             int start, int end, int m)
+    : Filter(parent, t) {
+  init(m);
+  setDataFromTable(t, xCol, yCol, start, end);
 }
 
-void Interpolation::init(int m)
-{
-    if (m < 0 || m > 2){
-        QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot") + " - " + tr("Error"),
-        tr("Unknown interpolation method. Valid values are: 0 - Linear, 1 - Cubic, 2 - Akima."));
-        d_init_err = true;
-        return;
-    }
-    d_method = m;
-	switch(d_method)
-	{
-		case 0:
-			setObjectName(tr("Linear") + tr("Int"));
-			d_explanation = tr("Linear") + " " + tr("Interpolation");
-			break;
-		case 1:
-			setObjectName(tr("Cubic") + tr("Int"));
-			d_explanation = tr("Cubic") + " " + tr("Interpolation");
-			break;
-		case 2:
-			setObjectName(tr("Akima") + tr("Int"));
-			d_explanation = tr("Akima") + " " + tr("Interpolation");
-			break;
-	}
-    d_sort_data = true;
-    d_min_points = d_method + 3;
+void Interpolation::init(int m) {
+  if (m < 0 || m > 2) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Unknown interpolation method. Valid values are: "
+                             "0 - Linear, 1 - Cubic, 2 - Akima."));
+    d_init_err = true;
+    return;
+  }
+  d_method = m;
+  switch (d_method) {
+  case 0:
+    setObjectName(tr("Linear") + tr("Int"));
+    d_explanation = tr("Linear") + " " + tr("Interpolation");
+    break;
+  case 1:
+    setObjectName(tr("Cubic") + tr("Int"));
+    d_explanation = tr("Cubic") + " " + tr("Interpolation");
+    break;
+  case 2:
+    setObjectName(tr("Akima") + tr("Int"));
+    d_explanation = tr("Akima") + " " + tr("Interpolation");
+    break;
+  }
+  d_sort_data = true;
+  d_min_points = d_method + 3;
 }
 
-
-void Interpolation::setMethod(int m)
-{
-if (m < 0 || m > 2){
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot - Error"),
-    tr("Unknown interpolation method, valid values are: 0 - Linear, 1 - Cubic, 2 - Akima."));
+void Interpolation::setMethod(int m) {
+  if (m < 0 || m > 2) {
+    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()),
+                          tr("MantidPlot - Error"),
+                          tr("Unknown interpolation method, valid values are: "
+                             "0 - Linear, 1 - Cubic, 2 - Akima."));
     d_init_err = true;
     return;
-    }
-int min_points = m + 3;
-if (d_n < min_points){
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(this->parent()), tr("MantidPlot") + " - " + tr("Error"),
-    tr("You need at least %1 points in order to perform this operation!").arg(min_points));
+  }
+  int min_points = m + 3;
+  if (d_n < min_points) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(this->parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("You need at least %1 points in order to perform this operation!")
+            .arg(min_points));
     d_init_err = true;
     return;
-	}
-    d_method = m;
-    d_min_points = min_points;
-	switch(d_method)
-	{
-		case 0:
-			setObjectName(tr("Linear") + tr("Int"));
-			d_explanation = tr("Linear") + " " + tr("Interpolation");
-			break;
-		case 1:
-			setObjectName(tr("Cubic") + tr("Int"));
-			d_explanation = tr("Cubic") + " " + tr("Interpolation");
-			break;
-		case 2:
-			setObjectName(tr("Akima") + tr("Int"));
-			d_explanation = tr("Akima") + " " + tr("Interpolation");
-			break;
-	}
+  }
+  d_method = m;
+  d_min_points = min_points;
+  switch (d_method) {
+  case 0:
+    setObjectName(tr("Linear") + tr("Int"));
+    d_explanation = tr("Linear") + " " + tr("Interpolation");
+    break;
+  case 1:
+    setObjectName(tr("Cubic") + tr("Int"));
+    d_explanation = tr("Cubic") + " " + tr("Interpolation");
+    break;
+  case 2:
+    setObjectName(tr("Akima") + tr("Int"));
+    d_explanation = tr("Akima") + " " + tr("Interpolation");
+    break;
+  }
 }
 
-void Interpolation::calculateOutputData(double *x, double *y)
-{
-	gsl_interp_accel *acc = gsl_interp_accel_alloc ();
-	const gsl_interp_type *method = NULL;
-	switch(d_method)
-	{
-		case 0:
-			method = gsl_interp_linear;
-			break;
-		case 1:
-			method = gsl_interp_cspline;
-			break;
-		case 2:
-			method = gsl_interp_akima;
-			break;
-	}
-
-	gsl_spline *interp = gsl_spline_alloc (method, d_n);
-	gsl_spline_init (interp, d_x, d_y, d_n);
-
-    double step = (d_to - d_from)/(double)(d_points - 1);
-    for (int j = 0; j < d_points; j++)
-	{
-	   x[j] = d_from + j*step;
-	   y[j] = gsl_spline_eval (interp, x[j], acc);
-	}
-
-	gsl_spline_free (interp);
-	gsl_interp_accel_free (acc);
+void Interpolation::calculateOutputData(double *x, double *y) {
+  gsl_interp_accel *acc = gsl_interp_accel_alloc();
+  const gsl_interp_type *method = NULL;
+  switch (d_method) {
+  case 0:
+    method = gsl_interp_linear;
+    break;
+  case 1:
+    method = gsl_interp_cspline;
+    break;
+  case 2:
+    method = gsl_interp_akima;
+    break;
+  }
+
+  gsl_spline *interp = gsl_spline_alloc(method, d_n);
+  gsl_spline_init(interp, d_x, d_y, d_n);
+
+  double step = (d_to - d_from) / (double)(d_points - 1);
+  for (int j = 0; j < d_points; j++) {
+    x[j] = d_from + j * step;
+    y[j] = gsl_spline_eval(interp, x[j], acc);
+  }
+
+  gsl_spline_free(interp);
+  gsl_interp_accel_free(acc);
 }
 
-int Interpolation::sortedCurveData(QwtPlotCurve *c, double start, double end, double **x, double **y)
-{
-    if (!c || c->rtti() != QwtPlotItem::Rtti_PlotCurve)
-        return 0;
-
-    int i_start = 0, i_end = c->dataSize();
-    for (int i = 0; i < i_end; i++)
-  	    if (c->x(i) > start && i){
-  	      i_start = i - 1;
-          break;
-        }
-    for (int i = i_end-1; i >= 0; i--)
-  	    if (c->x(i) < end && i < c->dataSize()){
-  	      i_end = i + 1;
-          break;
-        }
-    int n = i_end - i_start + 1;
-    (*x) = new double[n];
-    (*y) = new double[n];
-    double *xtemp = new double[n];
-    double *ytemp = new double[n];
-
-	double pr_x = 0;
-  	int j=0;
-    for (int i = i_start; i <= i_end; i++){
-        xtemp[j] = c->x(i);
-        if (i > i_start && xtemp[j] == pr_x){
-            delete[] (*x);
-            delete[] (*y);
-            delete[] xtemp;
-            delete[] ytemp;
-            return -1;//this kind of data causes division by zero in GSL interpolation routines
-        }
-        pr_x = xtemp[j];
-        ytemp[j++] = c->y(i);
+int Interpolation::sortedCurveData(QwtPlotCurve *c, double start, double end,
+                                   double **x, double **y) {
+  if (!c || c->rtti() != QwtPlotItem::Rtti_PlotCurve)
+    return 0;
+
+  int i_start = 0, i_end = c->dataSize();
+  for (int i = 0; i < i_end; i++)
+    if (c->x(i) > start && i) {
+      i_start = i - 1;
+      break;
+    }
+  for (int i = i_end - 1; i >= 0; i--)
+    if (c->x(i) < end && i < c->dataSize()) {
+      i_end = i + 1;
+      break;
     }
-    size_t *p = new size_t[n];
-    gsl_sort_index(p, xtemp, 1, n);
-    for (int i=0; i<n; i++){
-        (*x)[i] = xtemp[p[i]];
-  	    (*y)[i] = ytemp[p[i]];
+  int n = i_end - i_start + 1;
+  (*x) = new double[n];
+  (*y) = new double[n];
+  double *xtemp = new double[n];
+  double *ytemp = new double[n];
+
+  double pr_x = 0;
+  int j = 0;
+  for (int i = i_start; i <= i_end; i++) {
+    xtemp[j] = c->x(i);
+    if (i > i_start && xtemp[j] == pr_x) {
+      delete[](*x);
+      delete[](*y);
+      delete[] xtemp;
+      delete[] ytemp;
+      return -1; // this kind of data causes division by zero in GSL
+                 // interpolation routines
     }
-    delete[] xtemp;
-    delete[] ytemp;
-    delete[] p;
-    return n;
+    pr_x = xtemp[j];
+    ytemp[j++] = c->y(i);
+  }
+  size_t *p = new size_t[n];
+  gsl_sort_index(p, xtemp, 1, n);
+  for (int i = 0; i < n; i++) {
+    (*x)[i] = xtemp[p[i]];
+    (*y)[i] = ytemp[p[i]];
+  }
+  delete[] xtemp;
+  delete[] ytemp;
+  delete[] p;
+  return n;
 }
diff --git a/MantidPlot/src/Interpolation.h b/MantidPlot/src/Interpolation.h
index f6c93fb1fb9bec0665f31ae78868f543018ad2d6..518113c80dddc4a3f73fe2b2e5306eda7a07dd9c 100644
--- a/MantidPlot/src/Interpolation.h
+++ b/MantidPlot/src/Interpolation.h
@@ -32,28 +32,30 @@
 #include "Filter.h"
 
 class QwtPlotCurve;
-class Interpolation : public Filter
-{
-Q_OBJECT
+class Interpolation : public Filter {
+  Q_OBJECT
 
 public:
-	enum InterpolationMethod{Linear, Cubic, Akima};
+  enum InterpolationMethod { Linear, Cubic, Akima };
 
-	Interpolation(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m = 0);
-	Interpolation(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end, int m = 0);
-	Interpolation(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start = 0, int end = -1, int m = 0);
+  Interpolation(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+                int m = 0);
+  Interpolation(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+                double start, double end, int m = 0);
+  Interpolation(ApplicationWindow *parent, Table *t, const QString &xCol,
+                const QString &yCol, int start = 0, int end = -1, int m = 0);
 
-    int method(){return d_method;};
-    void setMethod(int m);
+  int method() { return d_method; };
+  void setMethod(int m);
 
 private:
-    void init(int m);
-    void calculateOutputData(double *x, double *y) override;
-    int sortedCurveData(QwtPlotCurve *c, double start, double end, double **x,
-                        double **y) override;
+  void init(int m);
+  void calculateOutputData(double *x, double *y) override;
+  int sortedCurveData(QwtPlotCurve *c, double start, double end, double **x,
+                      double **y) override;
 
-    //! the interpolation method
-    int d_method;
+  //! the interpolation method
+  int d_method;
 };
 
 #endif
diff --git a/MantidPlot/src/InterpolationDialog.cpp b/MantidPlot/src/InterpolationDialog.cpp
index 8ca8ade901def8319d5d3be9568d263ab0bf2f28..b699537ca5cd12c738266efa745e34df95eb4040 100644
--- a/MantidPlot/src/InterpolationDialog.cpp
+++ b/MantidPlot/src/InterpolationDialog.cpp
@@ -2,7 +2,8 @@
     File                 : InterpolationDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Interpolation options dialog
 
@@ -41,120 +42,117 @@
 #include <QComboBox>
 #include <QLayout>
 
-InterpolationDialog::InterpolationDialog( QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ), graph(NULL)
-{
-    setObjectName( "InterpolationDialog" );
-    setWindowTitle(tr("MantidPlot - Interpolation Options"));
-
-    QGroupBox *gb1 = new QGroupBox();
-    QGridLayout *gl1 = new QGridLayout(gb1);
-    gl1->addWidget(new QLabel(tr("Make curve from")), 0, 0);
-
-    boxName = new QComboBox();
-    gl1->addWidget(boxName, 0, 1);
-
-    gl1->addWidget(new QLabel(tr("Spline")), 1, 0);
-    boxMethod = new QComboBox();
-    boxMethod->addItem(tr("Linear"));
-    boxMethod->addItem(tr("Cubic"));
-    boxMethod->addItem(tr("Non-rounded Akima"));
-    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("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("Color")), 5, 0);
-
-    boxColor = new ColorBox();
-    boxColor->setColor(QColor(Qt::red));
-    gl1->addWidget(boxColor, 5, 1);
-    gl1->setRowStretch(6, 1);
-
-    buttonFit = new QPushButton(tr( "&Make" ));
-    buttonFit->setDefault( true );
-    buttonCancel = new QPushButton(tr( "&Close" ));
-
-    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( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+InterpolationDialog::InterpolationDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), graph(NULL) {
+  setObjectName("InterpolationDialog");
+  setWindowTitle(tr("MantidPlot - Interpolation Options"));
+
+  QGroupBox *gb1 = new QGroupBox();
+  QGridLayout *gl1 = new QGridLayout(gb1);
+  gl1->addWidget(new QLabel(tr("Make curve from")), 0, 0);
+
+  boxName = new QComboBox();
+  gl1->addWidget(boxName, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("Spline")), 1, 0);
+  boxMethod = new QComboBox();
+  boxMethod->addItem(tr("Linear"));
+  boxMethod->addItem(tr("Cubic"));
+  boxMethod->addItem(tr("Non-rounded Akima"));
+  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("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("Color")), 5, 0);
+
+  boxColor = new ColorBox();
+  boxColor->setColor(QColor(Qt::red));
+  gl1->addWidget(boxColor, 5, 1);
+  gl1->setRowStretch(6, 1);
+
+  buttonFit = new QPushButton(tr("&Make"));
+  buttonFit->setDefault(true);
+  buttonCancel = new QPushButton(tr("&Close"));
+
+  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(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void InterpolationDialog::interpolate()
-{
-QString curve = boxName->currentText();
-QStringList curvesList = graph->analysableCurvesList();
-if (!curvesList.contains(curve))
-	{
-	QMessageBox::critical(this,tr("MantidPlot - Warning"),
-		tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!").arg(curve));
-	boxName->clear();
-	boxName->addItems(curvesList);
-	return;
-	}
-
-double from, to;
-try
-	{
-	MyParser parser;
-	parser.SetExpr(boxStart->text().replace(",", ".").toAscii().constData());
-	from = parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(this, tr("MantidPlot - Start limit error"), QString::fromStdString(e.GetMsg()));
-	boxStart->setFocus();
-	return;
-	}
-
-try
-	{
-	MyParser parser;
-	parser.SetExpr(boxEnd->text().replace(",", ".").toAscii().constData());
-	to = parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(this, tr("MantidPlot - End limit error"), QString::fromStdString(e.GetMsg()));
-	boxEnd->setFocus();
-	return;
-	}
-
-if (from >= to)
-	{
-	QMessageBox::critical(this, tr("MantidPlot - Input error"), tr("Please enter x limits that satisfy: from < to!"));
-	boxEnd->setFocus();
-	return;
-	}
-
-Interpolation *i = new Interpolation(dynamic_cast<ApplicationWindow *>(this->parent()), graph, curve,
-                                      from, to, boxMethod->currentIndex());
-i->setOutputPoints(boxPoints->value());
-i->setColor(boxColor->currentIndex());
-i->run();
-delete i;
+void InterpolationDialog::interpolate() {
+  QString curve = boxName->currentText();
+  QStringList curvesList = graph->analysableCurvesList();
+  if (!curvesList.contains(curve)) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Warning"),
+        tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!")
+            .arg(curve));
+    boxName->clear();
+    boxName->addItems(curvesList);
+    return;
+  }
+
+  double from, to;
+  try {
+    MyParser parser;
+    parser.SetExpr(boxStart->text().replace(",", ".").toAscii().constData());
+    from = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(this, tr("MantidPlot - Start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxStart->setFocus();
+    return;
+  }
+
+  try {
+    MyParser parser;
+    parser.SetExpr(boxEnd->text().replace(",", ".").toAscii().constData());
+    to = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(this, tr("MantidPlot - End limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxEnd->setFocus();
+    return;
+  }
+
+  if (from >= to) {
+    QMessageBox::critical(this, tr("MantidPlot - Input error"),
+                          tr("Please enter x limits that satisfy: from < to!"));
+    boxEnd->setFocus();
+    return;
+  }
+
+  Interpolation *i =
+      new Interpolation(dynamic_cast<ApplicationWindow *>(this->parent()),
+                        graph, curve, from, to, boxMethod->currentIndex());
+  i->setOutputPoints(boxPoints->value());
+  i->setColor(boxColor->currentIndex());
+  i->run();
+  delete i;
 }
 
 void InterpolationDialog::setGraph(Graph *g) {
@@ -173,30 +171,32 @@ void InterpolationDialog::setGraph(Graph *g) {
   connect(graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
 }
 
-void InterpolationDialog::activateCurve(const QString& curveName)
-{
-	QwtPlotCurve *c = graph->curve(curveName);
-	if (!c)
-		return;
+void InterpolationDialog::activateCurve(const QString &curveName) {
+  QwtPlotCurve *c = graph->curve(curveName);
+  if (!c)
+    return;
 
-    ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-    if(!app)
-        return;
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
 
-	double start, end;
-	graph->range(graph->curveIndex(curveName), &start, &end);
-	boxStart->setText(QString::number(QMIN(start, end), 'g', app->d_decimal_digits));
-	boxEnd->setText(QString::number(QMAX(start, end), 'g', app->d_decimal_digits));
+  double start, end;
+  graph->range(graph->curveIndex(curveName), &start, &end);
+  boxStart->setText(
+      QString::number(QMIN(start, end), 'g', app->d_decimal_digits));
+  boxEnd->setText(
+      QString::number(QMAX(start, end), 'g', app->d_decimal_digits));
 }
 
-void InterpolationDialog::changeDataRange()
-{
-ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
-if(!app)
+void InterpolationDialog::changeDataRange() {
+  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
+  if (!app)
     return;
 
-double start = graph->selectedXStartValue();
-double end = graph->selectedXEndValue();
-boxStart->setText(QString::number(QMIN(start, end), 'g', app->d_decimal_digits));
-boxEnd->setText(QString::number(QMAX(start, end), 'g', app->d_decimal_digits));
+  double start = graph->selectedXStartValue();
+  double end = graph->selectedXEndValue();
+  boxStart->setText(
+      QString::number(QMIN(start, end), 'g', app->d_decimal_digits));
+  boxEnd->setText(
+      QString::number(QMAX(start, end), 'g', app->d_decimal_digits));
 }
diff --git a/MantidPlot/src/InterpolationDialog.h b/MantidPlot/src/InterpolationDialog.h
index 1a6e4acbf49df40fdc24e8332dcb5dccf30610ac..b8f14c7e819a87c724a2daf04943ecb4f71339e0 100644
--- a/MantidPlot/src/InterpolationDialog.h
+++ b/MantidPlot/src/InterpolationDialog.h
@@ -2,7 +2,8 @@
     File                 : InterpolationDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Interpolation options dialog
 
@@ -39,32 +40,28 @@ class Graph;
 class ColorBox;
 
 //! Interpolation options dialog
-class InterpolationDialog : public QDialog
-{
-    Q_OBJECT
+class InterpolationDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    InterpolationDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  InterpolationDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void activateCurve(const QString& curveName);
-	void setGraph(Graph *g);
-	void interpolate();
-	void changeDataRange();
+  void activateCurve(const QString &curveName);
+  void setGraph(Graph *g);
+  void interpolate();
+  void changeDataRange();
 
 private:
-	Graph *graph;
-	QPushButton* buttonFit;
-	QPushButton* buttonCancel;
-	QComboBox* boxName;
-	QComboBox* boxMethod;
-	QSpinBox* boxPoints;
-	QLineEdit* boxStart;
-	QLineEdit* boxEnd;
-	ColorBox* boxColor;
+  Graph *graph;
+  QPushButton *buttonFit;
+  QPushButton *buttonCancel;
+  QComboBox *boxName;
+  QComboBox *boxMethod;
+  QSpinBox *boxPoints;
+  QLineEdit *boxStart;
+  QLineEdit *boxEnd;
+  ColorBox *boxColor;
 };
 
 #endif
-
-
-
diff --git a/MantidPlot/src/LabelTool.cpp b/MantidPlot/src/LabelTool.cpp
index 13daffb370a177525f7af16c4a2f9e9ba40c221d..0485ffaa5a5ba98335259495da4caa0b100d05a9 100644
--- a/MantidPlot/src/LabelTool.cpp
+++ b/MantidPlot/src/LabelTool.cpp
@@ -1,42 +1,48 @@
 #include "LabelTool.h"
 
 LabelTool::LabelTool(Graph *graph)
-  : QObject(graph->plotWidget()->canvas()),
-	PlotToolInterface(graph),
-
-    m_canvasPicker(new QwtPicker(graph->plotWidget()->canvas())),
-    m_xAxisPicker(new QwtPicker(graph->plotWidget()->axisWidget(Plot::xBottom))),   
-    m_yAxisPicker(new QwtPicker(graph->plotWidget()->axisWidget(Plot::yLeft))),
-    m_xPos(), m_yPos(), m_axisCoordsX(), m_axisCoordsY(), m_xPosSigFigs(), m_yPosSigFigs(), m_error(), m_dataCoords(), m_curveWsName()
-{
-    connect(m_xAxisPicker, SIGNAL(selected(const QwtPolygon &)), this, SLOT(xAxisClicked(const QwtPolygon &)));
-    connect(m_yAxisPicker, SIGNAL(selected(const QwtPolygon &)), this, SLOT(yAxisClicked(const QwtPolygon &)));
-    connect(m_canvasPicker, SIGNAL(selected(const QwtPolygon &)), this, SLOT(graphAreaClicked(const QwtPolygon &)));
-  
-    m_xAxisPicker->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
-    m_yAxisPicker->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
-    m_canvasPicker->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
+    : QObject(graph->plotWidget()->canvas()), PlotToolInterface(graph),
+
+      m_canvasPicker(new QwtPicker(graph->plotWidget()->canvas())),
+      m_xAxisPicker(
+          new QwtPicker(graph->plotWidget()->axisWidget(Plot::xBottom))),
+      m_yAxisPicker(
+          new QwtPicker(graph->plotWidget()->axisWidget(Plot::yLeft))),
+      m_xPos(), m_yPos(), m_axisCoordsX(), m_axisCoordsY(), m_xPosSigFigs(),
+      m_yPosSigFigs(), m_error(), m_dataCoords(), m_curveWsName() {
+  connect(m_xAxisPicker, SIGNAL(selected(const QwtPolygon &)), this,
+          SLOT(xAxisClicked(const QwtPolygon &)));
+  connect(m_yAxisPicker, SIGNAL(selected(const QwtPolygon &)), this,
+          SLOT(yAxisClicked(const QwtPolygon &)));
+  connect(m_canvasPicker, SIGNAL(selected(const QwtPolygon &)), this,
+          SLOT(graphAreaClicked(const QwtPolygon &)));
+
+  m_xAxisPicker->setSelectionFlags(QwtPicker::PointSelection |
+                                   QwtPicker::ClickSelection);
+  m_yAxisPicker->setSelectionFlags(QwtPicker::PointSelection |
+                                   QwtPicker::ClickSelection);
+  m_canvasPicker->setSelectionFlags(QwtPicker::PointSelection |
+                                    QwtPicker::ClickSelection);
 }
 
 /// Destructor for the tool.
-  LabelTool::~LabelTool()
-  {
-	  d_graph->plotWidget()->canvas()->unsetCursor();
-	  d_graph->plotWidget()->replot();
-  }
-  
+LabelTool::~LabelTool() {
+  d_graph->plotWidget()->canvas()->unsetCursor();
+  d_graph->plotWidget()->replot();
+}
+
 /**
- * When x-axis is clicked, the pixel coordinates are converted to graph coordinates, and displayed in a pop-up menu.
+ * When x-axis is clicked, the pixel coordinates are converted to graph
+ * coordinates, and displayed in a pop-up menu.
  * @param &x :: A reference to a click on the x-axis.
  */
-void LabelTool::xAxisClicked(const QwtPolygon &x)
-{
+void LabelTool::xAxisClicked(const QwtPolygon &x) {
   populateMantidCurves();
 
   // Obtains the x value of the pixel coordinate.
   QPoint xx = x.point(0);
   int xPosition = xx.x();
-  
+
   // Obtains the origins of the graph area and of the axis.
   QPoint canvasOrigin = d_graph->plotWidget()->canvas()->pos();
   int canvasOriginX = canvasOrigin.x();
@@ -45,17 +51,18 @@ void LabelTool::xAxisClicked(const QwtPolygon &x)
   int xAxisOriginXValue = xOrigin.x();
 
   /**
-   * The difference in the origins is calculated then taken into account when converting the pixel coordinates of the
+   * The difference in the origins is calculated then taken into account when
+   * converting the pixel coordinates of the
    * axis into graph coordinates.
    */
 
   int deltaOrigins = canvasOriginX - xAxisOriginXValue;
   int xPositionCorrected = xPosition - deltaOrigins;
- 
-  double xPos = d_graph->plotWidget()->invTransform(QwtPlot::xBottom, xPositionCorrected);
-  
-  if( xPos < 0)
-  {
+
+  double xPos =
+      d_graph->plotWidget()->invTransform(QwtPlot::xBottom, xPositionCorrected);
+
+  if (xPos < 0) {
     return;
   }
 
@@ -64,21 +71,21 @@ void LabelTool::xAxisClicked(const QwtPolygon &x)
   precisionValue << xPos;
   m_xPosSigFigs = precisionValue.str();
 
-  QMenu * clickMenu = new QMenu(d_graph);  
+  QMenu *clickMenu = new QMenu(d_graph);
 
-  QAction * addXAxisLabel = new QAction(tr(m_xPosSigFigs.c_str()), this);
+  QAction *addXAxisLabel = new QAction(tr(m_xPosSigFigs.c_str()), this);
   clickMenu->addAction(addXAxisLabel);
-  connect(addXAxisLabel,SIGNAL(triggered()), this, SLOT(insertXCoord()));
+  connect(addXAxisLabel, SIGNAL(triggered()), this, SLOT(insertXCoord()));
 
   clickMenu->exec(QCursor::pos());
 }
 
 /**
- * When y-axis is clicked, the pixel coordinates are converted to graph coordinates, and displayed in a pop-up menu.
+ * When y-axis is clicked, the pixel coordinates are converted to graph
+ * coordinates, and displayed in a pop-up menu.
  * @param &y :: A reference to a click on the y-axis.
  */
-void LabelTool::yAxisClicked(const QwtPolygon &y)
-{
+void LabelTool::yAxisClicked(const QwtPolygon &y) {
   populateMantidCurves();
 
   // Obtains the x value of the pixel coordinate.
@@ -91,19 +98,20 @@ void LabelTool::yAxisClicked(const QwtPolygon &y)
 
   QPoint yOrigin = d_graph->plotWidget()->axisWidget(QwtPlot::yLeft)->pos();
   int yAxisOriginYValue = yOrigin.y();
-  
-/**
- * The difference in the origins is calculated then taken into account when converting the pixel coordinates of the
- * axis into graph coordinates.
- */
+
+  /**
+   * The difference in the origins is calculated then taken into account when
+   * converting the pixel coordinates of the
+   * axis into graph coordinates.
+   */
 
   int deltaOrigins = canvasOriginY - yAxisOriginYValue;
   int yPositionCorrected = yPosition - deltaOrigins;
 
-  double yPos = d_graph->plotWidget()->invTransform(QwtPlot::yLeft, yPositionCorrected);
-    
-  if( yPos < 0)
-  {
+  double yPos =
+      d_graph->plotWidget()->invTransform(QwtPlot::yLeft, yPositionCorrected);
+
+  if (yPos < 0) {
     return;
   }
 
@@ -112,44 +120,44 @@ void LabelTool::yAxisClicked(const QwtPolygon &y)
   precisionValue << yPos;
   m_yPosSigFigs = precisionValue.str();
 
-  QMenu * clickMenu = new QMenu(d_graph);
-  
-  QAction * addYAxisLabel = new QAction(tr(m_yPosSigFigs.c_str()), this);
+  QMenu *clickMenu = new QMenu(d_graph);
+
+  QAction *addYAxisLabel = new QAction(tr(m_yPosSigFigs.c_str()), this);
   clickMenu->addAction(addYAxisLabel);
-  connect(addYAxisLabel,SIGNAL(triggered()), this, SLOT(insertYCoord()));
+  connect(addYAxisLabel, SIGNAL(triggered()), this, SLOT(insertYCoord()));
 
   clickMenu->exec(QCursor::pos());
 }
 
 /// Determines the number of curves present on the graph.
-void LabelTool::populateMantidCurves()
-{
-  int n_curves =  d_graph->curves();
+void LabelTool::populateMantidCurves() {
+  int n_curves = d_graph->curves();
 
-  // Determines whether any of the graphs are MantidMatrixCurves (MMCs) and returns their names into a list.
+  // Determines whether any of the graphs are MantidMatrixCurves (MMCs) and
+  // returns their names into a list.
   QList<MantidMatrixCurve *> mantidMatrixCurves;
   m_mantidMatrixCurves.clear();
-  for(int i=0; i<=n_curves; i++)
-  {
+  for (int i = 0; i <= n_curves; i++) {
     QwtPlotCurve *indexCurve = d_graph->curve(i);
-    MantidMatrixCurve *d = dynamic_cast<MantidMatrixCurve*>(indexCurve);
+    MantidMatrixCurve *d = dynamic_cast<MantidMatrixCurve *>(indexCurve);
 
-    if (d)
-    {
+    if (d) {
       m_mantidMatrixCurves.append(d);
     }
   }
 }
 
-/** 
- * When the graph area is clicked, pixel coordinates are found and used to determine graph coordinates.
+/**
+ * When the graph area is clicked, pixel coordinates are found and used to
+ * determine graph coordinates.
  * Determines the number of MMCs from the list in populateMantidCurves().
- * For each MMC, determines whether a click on the graph area is within close proximity to a data point.
+ * For each MMC, determines whether a click on the graph area is within close
+ * proximity to a data point.
  * If it is, the coordinates of the data point are stored for display.
- * @param &c :: A reference to a click on the graph area; it is bound by the x and y-axis.
+ * @param &c :: A reference to a click on the graph area; it is bound by the x
+ * and y-axis.
  */
-void LabelTool::graphAreaClicked(const QwtPolygon &c)
-{ 
+void LabelTool::graphAreaClicked(const QwtPolygon &c) {
   populateMantidCurves();
   m_dataCoords.clear();
 
@@ -157,17 +165,19 @@ void LabelTool::graphAreaClicked(const QwtPolygon &c)
   int xPosition = cc.x();
   int yPosition = cc.y();
 
-  // std::cout << "xPosition: " << xPosition << " " << "yPosition: " << yPosition << std::endl;
+  // std::cout << "xPosition: " << xPosition << " " << "yPosition: " <<
+  // yPosition << std::endl;
 
   m_xPos = d_graph->plotWidget()->invTransform(QwtPlot::xBottom, xPosition);
   m_yPos = d_graph->plotWidget()->invTransform(QwtPlot::yLeft, yPosition);
 
-  // Sets the tolerance value, in pixels, for the range in which to search for a data point.
+  // Sets the tolerance value, in pixels, for the range in which to search for a
+  // data point.
   int tolerance = 7;
-     
-  foreach(MantidMatrixCurve * mantidMatrixCurve, m_mantidMatrixCurves)
-  {
-    // Sets the upper and lower limits in pixel coordinates for the x and y-axes.
+
+  foreach (MantidMatrixCurve *mantidMatrixCurve, m_mantidMatrixCurves) {
+    // Sets the upper and lower limits in pixel coordinates for the x and
+    // y-axes.
     int upperLimitX = xPosition + tolerance;
     int lowerLimitX = xPosition - tolerance;
     int upperLimitY = yPosition + tolerance;
@@ -183,38 +193,41 @@ void LabelTool::graphAreaClicked(const QwtPolygon &c)
     size_t numberOfDataPoints = mwd->size();
 
     /**
-    * Gets the pixel value of the x-coordinate value of each data point within range.  
-    * Of the data points within range along x-axis, finds out if the pixel values of their y-coordinates are within range.
+    * Gets the pixel value of the x-coordinate value of each data point within
+    * range.
+    * Of the data points within range along x-axis, finds out if the pixel
+    * values of their y-coordinates are within range.
     * If they are, their position within the iteration - i - is stored in a set.
     */
 
     QSet<size_t> pointsWithinRange;
 
-    for(size_t i = 0; i < numberOfDataPoints; ++i)
-    {
+    for (size_t i = 0; i < numberOfDataPoints; ++i) {
       // The pixel values of the x and y coordinates of the data points.
-      int iPixelValueX = d_graph->plotWidget()->transform(QwtPlot::xBottom, mwd->x(i));
-      int iPixelvalueY = d_graph->plotWidget()->transform(QwtPlot::yLeft, mwd->y(i));
-
-      // Comparing the point of clicking with the positioning of the data points.
-      if(((iPixelValueX <= upperLimitX) && (iPixelValueX >= lowerLimitX)) && ((iPixelvalueY <= upperLimitY) && (iPixelvalueY >= lowerLimitY)))
-      {
+      int iPixelValueX =
+          d_graph->plotWidget()->transform(QwtPlot::xBottom, mwd->x(i));
+      int iPixelvalueY =
+          d_graph->plotWidget()->transform(QwtPlot::yLeft, mwd->y(i));
+
+      // Comparing the point of clicking with the positioning of the data
+      // points.
+      if (((iPixelValueX <= upperLimitX) && (iPixelValueX >= lowerLimitX)) &&
+          ((iPixelvalueY <= upperLimitY) && (iPixelvalueY >= lowerLimitY))) {
         pointsWithinRange.insert(i);
       }
     }
 
     // If there are points within the specified ranges.
-    if ( !pointsWithinRange.isEmpty() )
-    {
+    if (!pointsWithinRange.isEmpty()) {
       /**
-      * Uses Pythagoras' theorem to calculate the distance between the position of a click and 
-      * the surrounding data points that lie within both the x and y ranges. 
+      * Uses Pythagoras' theorem to calculate the distance between the position
+      * of a click and
+      * the surrounding data points that lie within both the x and y ranges.
       */
 
       QMap<double, size_t> map;
 
-      foreach(size_t i, pointsWithinRange)
-      {
+      foreach (size_t i, pointsWithinRange) {
         double deltaX = m_xPos - mwd->x(i);
         double deltaY = m_yPos - mwd->y(i);
         double deltaXSquared = deltaX * deltaX;
@@ -232,7 +245,8 @@ void LabelTool::graphAreaClicked(const QwtPolygon &c)
       double shortestDistance = distances[0];
       size_t nearestPointIndex = map[shortestDistance];
 
-      // Obtains the x and y coordinates of the closest data point, ready to be displayed.
+      // Obtains the x and y coordinates of the closest data point, ready to be
+      // displayed.
       double nearestPointXCoord = mwd->x(nearestPointIndex);
       double nearestPointYCoord = mwd->y(nearestPointIndex);
       double errorOfNearestPoint = mwd->e(nearestPointIndex);
@@ -255,314 +269,329 @@ void LabelTool::graphAreaClicked(const QwtPolygon &c)
       m_dataCoords = "(" + m_xPosSigFigs + ", " + m_yPosSigFigs + ")";
       m_error = m_yPosSigFigs + "+/-" + errorSigFigs;
 
-      // Gets the workspace name for which the curve with the datapoint belongs to.
+      // Gets the workspace name for which the curve with the datapoint belongs
+      // to.
       QString workspaceNameOfCurve = mantidMatrixCurve->workspaceName();
       m_curveWsName = workspaceNameOfCurve;
-    }    
+    }
   } // foreach
 
-  if ( !m_dataCoords.size() )
-  {
+  if (!m_dataCoords.size()) {
     // m_dataCoords has not been initialized
     // this means that there are no points near the clicked region
     blankRegionClicked();
-  }
-  else
-  {
+  } else {
     // at least one point was close enough to the clicked region
     dataPointClicked();
   }
 }
 
 /**
- * Pops up a menu when a click on the graph area is not within close proximity to a data point.
+ * Pops up a menu when a click on the graph area is not within close proximity
+ * to a data point.
  * Has option to add a label. Also displays info about the workspace.
  * One can also view the log values present.
  */
-void LabelTool::blankRegionClicked()
-{
-  QMenu * clickMenu = new QMenu(d_graph);
+void LabelTool::blankRegionClicked() {
+  QMenu *clickMenu = new QMenu(d_graph);
 
   // For adding labels onto workspace.
-  QAction * addLabel = new QAction(tr("Add a label"), this);
+  QAction *addLabel = new QAction(tr("Add a label"), this);
   clickMenu->addAction(addLabel);
-  connect(addLabel,SIGNAL(triggered()), this, SLOT(insertTextBox()));
-  
+  connect(addLabel, SIGNAL(triggered()), this, SLOT(insertTextBox()));
+
   // For workspace information.
-  QMenu * info = clickMenu->addMenu(tr("More info..."));
-  QMenu * workspaces = info->addMenu(tr("Workspaces"));
-
-  foreach(QString wsName, workspaceNames())
-  {
-		QAction * qa = new QAction(wsName,this);
-		workspaces->addAction(qa);
-		connect(qa,SIGNAL(triggered()),this,SLOT(insertLegend()));
+  QMenu *info = clickMenu->addMenu(tr("More info..."));
+  QMenu *workspaces = info->addMenu(tr("Workspaces"));
+
+  foreach (QString wsName, workspaceNames()) {
+    QAction *qa = new QAction(wsName, this);
+    workspaces->addAction(qa);
+    connect(qa, SIGNAL(triggered()), this, SLOT(insertLegend()));
   }
 
   // For viewing log values.
-  QMenu * logVals = info->addMenu(tr("Log values"));
+  QMenu *logVals = info->addMenu(tr("Log values"));
 
-  foreach(QString logProperty, logValues())
-  {
-		QAction * qa = new QAction(logProperty,this);
-		logVals->addAction(qa);
-		connect(qa,SIGNAL(triggered()),this,SLOT(insertLegend()));
+  foreach (QString logProperty, logValues()) {
+    QAction *qa = new QAction(logProperty, this);
+    logVals->addAction(qa);
+    connect(qa, SIGNAL(triggered()), this, SLOT(insertLegend()));
   }
 
   clickMenu->exec(QCursor::pos());
 }
 
-/// If the click is within close proximity of a data point, then a different menu is displayed.
-void LabelTool::dataPointClicked()
-{
-  QMenu * clickMenu = new QMenu(d_graph);
-  
+/// If the click is within close proximity of a data point, then a different
+/// menu is displayed.
+void LabelTool::dataPointClicked() {
+  QMenu *clickMenu = new QMenu(d_graph);
+
   // For displaying data coordinates.
 
-  QAction * addCoordinateLabel = new QAction(tr(m_dataCoords.c_str()), this);
+  QAction *addCoordinateLabel = new QAction(tr(m_dataCoords.c_str()), this);
   clickMenu->addAction(addCoordinateLabel);
-  connect(addCoordinateLabel,SIGNAL(triggered()), this, SLOT(insertDataCoord()));
+  connect(addCoordinateLabel, SIGNAL(triggered()), this,
+          SLOT(insertDataCoord()));
 
-  QAction * addErrorLabel = new QAction(tr(m_error.c_str()), this);
+  QAction *addErrorLabel = new QAction(tr(m_error.c_str()), this);
   clickMenu->addAction(addErrorLabel);
-  connect(addErrorLabel,SIGNAL(triggered()), this, SLOT(insertErrorValue()));
+  connect(addErrorLabel, SIGNAL(triggered()), this, SLOT(insertErrorValue()));
 
   // add a separator before addErrorLabel
   clickMenu->insertSeparator(addErrorLabel);
 
   // For adding labels onto workspace.
-  QAction * addLabel = new QAction(tr("Add a label"), this);
+  QAction *addLabel = new QAction(tr("Add a label"), this);
   clickMenu->addAction(addLabel);
-  connect(addLabel,SIGNAL(triggered()), this, SLOT(insertTextBox()));
+  connect(addLabel, SIGNAL(triggered()), this, SLOT(insertTextBox()));
 
   // add a separator before addLabel
   clickMenu->insertSeparator(addLabel);
 
   // For workspace information.
-  QMenu * info = clickMenu->addMenu(tr("More info..."));
-  QMenu * workspaces = info->addMenu(tr("Workspaces"));
-
-  foreach(QString wsName, workspaceNames())
-  {
-		QAction * qa = new QAction(tr(wsName),this);
-		workspaces->addAction(qa);
-		connect(qa,SIGNAL(triggered()),this,SLOT(insertLegend()));
+  QMenu *info = clickMenu->addMenu(tr("More info..."));
+  QMenu *workspaces = info->addMenu(tr("Workspaces"));
+
+  foreach (QString wsName, workspaceNames()) {
+    QAction *qa = new QAction(tr(wsName), this);
+    workspaces->addAction(qa);
+    connect(qa, SIGNAL(triggered()), this, SLOT(insertLegend()));
   }
 
-	// For viewing log values.
-	QMenu * logVals = info->addMenu(tr("Log values"));
+  // For viewing log values.
+  QMenu *logVals = info->addMenu(tr("Log values"));
 
-	foreach(QString logProperty, logValues())
-	{
-		QAction * qa = new QAction(tr(logProperty),this);
-		logVals->addAction(qa);
-		connect(qa,SIGNAL(triggered()),this,SLOT(insertLegend()));
-	}
+  foreach (QString logProperty, logValues()) {
+    QAction *qa = new QAction(tr(logProperty), this);
+    logVals->addAction(qa);
+    connect(qa, SIGNAL(triggered()), this, SLOT(insertLegend()));
+  }
 
   clickMenu->exec(QCursor::pos());
 }
 
 /// Creates a label with size equal to the axisFont size
-void LabelTool::insertLegend()
-{
-	QAction *action = qobject_cast<QAction *>(sender());
-	if (action)
-	{
-		LegendWidget *label = new LegendWidget(d_graph->plotWidget());
-		label->setOriginCoord(m_xPos,m_yPos);
-		label->setFont(d_graph->axisFont(0));
-		label->setText(action->text());
-	}
+void LabelTool::insertLegend() {
+  QAction *action = qobject_cast<QAction *>(sender());
+  if (action) {
+    LegendWidget *label = new LegendWidget(d_graph->plotWidget());
+    label->setOriginCoord(m_xPos, m_yPos);
+    label->setFont(d_graph->axisFont(0));
+    label->setText(action->text());
+  }
 }
 
-/// Displays a dialog box to input the contents of a label, then creates the label.
-void LabelTool::insertTextBox()
-{
+/// Displays a dialog box to input the contents of a label, then creates the
+/// label.
+void LabelTool::insertTextBox() {
   TextDialog *textDialog = new TextDialog(TextDialog::TextMarker);
   LegendWidget *label = new LegendWidget(d_graph->plotWidget());
-  
-  textDialog->setLegendWidget(label);  
-  label->setOriginCoord(m_xPos,m_yPos);
+
+  textDialog->setLegendWidget(label);
+  label->setOriginCoord(m_xPos, m_yPos);
 
   textDialog->exec();
 }
 
 /// Removes the active label on the instructions of the user.
-void LabelTool::removeTextBox()
-{
-  d_graph->removeMarker();
-}
+void LabelTool::removeTextBox() { d_graph->removeMarker(); }
 
 /**
- * Gets the names of the workspaces for display in the menu when a click is made whilst using the label tool.
+ * Gets the names of the workspaces for display in the menu when a click is made
+ * whilst using the label tool.
  * @return A set of the names of workspaces on the graph.
  */
-QSet<QString> LabelTool::workspaceNames()
-{
+QSet<QString> LabelTool::workspaceNames() {
   QSet<QString> workspaceNames;
-  
-  foreach(MantidMatrixCurve * mantidMatrixCurve, m_mantidMatrixCurves)
-  {
+
+  foreach (MantidMatrixCurve *mantidMatrixCurve, m_mantidMatrixCurves) {
     workspaceNames.insert(mantidMatrixCurve->workspaceName());
   }
-  
+
   return workspaceNames;
 }
 
-
 /**
- * Gets the log values for display in the menu when a click is made whilst using the label tool.
- * Accounts for the fact that for each workspace, the properties available may differ.
+ * Gets the log values for display in the menu when a click is made whilst using
+ * the label tool.
+ * Accounts for the fact that for each workspace, the properties available may
+ * differ.
  * @return A set of log properties for each workspace.
  */
-QSet<QString> LabelTool::logValues()
-{ 
+QSet<QString> LabelTool::logValues() {
   QSet<QString> logProperties;
 
-  foreach(QString workspaceName, workspaceNames())
-  {
-    Mantid::API::MatrixWorkspace_sptr matrixWs = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>(workspaceName.toStdString());
-    std::vector<Mantid::Kernel::Property *> properties = matrixWs->run().getProperties();
-
-    for(std::vector<Mantid::Kernel::Property *>::iterator prop = properties.begin(); prop != properties.end(); ++prop)
-    {
-      auto timeSeriesProp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double>*>(*prop);
-
-      if(timeSeriesProp)
-      {
+  foreach (QString workspaceName, workspaceNames()) {
+    Mantid::API::MatrixWorkspace_sptr matrixWs =
+        Mantid::API::AnalysisDataService::Instance()
+            .retrieveWS<Mantid::API::MatrixWorkspace>(
+                workspaceName.toStdString());
+    std::vector<Mantid::Kernel::Property *> properties =
+        matrixWs->run().getProperties();
+
+    for (std::vector<Mantid::Kernel::Property *>::iterator prop =
+             properties.begin();
+         prop != properties.end(); ++prop) {
+      auto timeSeriesProp =
+          dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(*prop);
+
+      if (timeSeriesProp) {
         double medianValue = timeSeriesProp->getStatistics().median;
-        std::string medianValue_str = boost::lexical_cast<std::string>(medianValue);
-        logProperties.insert(QString::fromStdString((*prop)->name() + " : " + medianValue_str));
+        std::string medianValue_str =
+            boost::lexical_cast<std::string>(medianValue);
+        logProperties.insert(
+            QString::fromStdString((*prop)->name() + " : " + medianValue_str));
       }
 
       else
-      
-        logProperties.insert(QString::fromStdString((*prop)->name() + " : " + (*prop)->value()));
+
+        logProperties.insert(
+            QString::fromStdString((*prop)->name() + " : " + (*prop)->value()));
     }
   }
   return logProperties;
 }
 
-/// Sets the coordinates for where the label showing the x-position value is to be located.
-void LabelTool::insertXCoord()
-{
+/// Sets the coordinates for where the label showing the x-position value is to
+/// be located.
+void LabelTool::insertXCoord() {
   LegendWidget *xCoordLabel = new LegendWidget(d_graph->plotWidget());
 
-  // Calculates the value, in pixel coordinates, where the y-axis intersects the x-axis.
-  int yAxisOriginInPixCoords = d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);
-    
-  double yAxisLabelPosition = d_graph->plotWidget()->invTransform(QwtPlot::yLeft, (yAxisOriginInPixCoords - 30));
+  // Calculates the value, in pixel coordinates, where the y-axis intersects the
+  // x-axis.
+  int yAxisOriginInPixCoords =
+      d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);
+
+  double yAxisLabelPosition = d_graph->plotWidget()->invTransform(
+      QwtPlot::yLeft, (yAxisOriginInPixCoords - 30));
   double xPosSigFigs = boost::lexical_cast<double>(m_xPosSigFigs);
-    
+
   xCoordLabel->setOriginCoord(xPosSigFigs, yAxisLabelPosition);
   xCoordLabel->setText(QString::fromStdString(m_xPosSigFigs));
-    
+
   /*
-      
+
   QwtText *xCoordLabel = new QwtText();
   xCoordLabel->draw();
     (d_graph->plotWidget());
   */
-
 }
 
-/// Sets the coordinates for where the label showing the y-position value is to be located.
-void LabelTool::insertYCoord()
-{
+/// Sets the coordinates for where the label showing the y-position value is to
+/// be located.
+void LabelTool::insertYCoord() {
   LegendWidget *yCoordLabel = new LegendWidget(d_graph->plotWidget());
 
-  // Calculates the value, in pixel coordinates, where the x-axis intersects the y-axis.
-  int xAxisOriginInPixCoords = d_graph->plotWidget()->transform(QwtPlot::xBottom, 0.0);
-    
-  double xAxisLabelPosition = d_graph->plotWidget()->invTransform(QwtPlot::xBottom, (xAxisOriginInPixCoords + 2));
+  // Calculates the value, in pixel coordinates, where the x-axis intersects the
+  // y-axis.
+  int xAxisOriginInPixCoords =
+      d_graph->plotWidget()->transform(QwtPlot::xBottom, 0.0);
+
+  double xAxisLabelPosition = d_graph->plotWidget()->invTransform(
+      QwtPlot::xBottom, (xAxisOriginInPixCoords + 2));
   double yPosSigFigs = boost::lexical_cast<double>(m_yPosSigFigs);
 
   yCoordLabel->setOriginCoord(xAxisLabelPosition, yPosSigFigs);
   yCoordLabel->setText(QString::fromStdString(m_yPosSigFigs));
 }
 
-/// Sets the coordinates for where the label showing the coordinates of the data point is to be located.
-void LabelTool::insertDataCoord()
-{
+/// Sets the coordinates for where the label showing the coordinates of the data
+/// point is to be located.
+void LabelTool::insertDataCoord() {
   LegendWidget *dataPointLabel = new LegendWidget(d_graph->plotWidget());
 
   // x and y pixel coordinates.
   double xGraphCoordOfDataPoint = boost::lexical_cast<double>(m_xPosSigFigs);
   double yGraphCoordOfDataPoint = boost::lexical_cast<double>(m_yPosSigFigs);
 
-  int xPixCoordOfDataPoint = d_graph->plotWidget()->transform(QwtPlot::xBottom, xGraphCoordOfDataPoint);
-  int yPixCoordOfDataPoint = d_graph->plotWidget()->transform(QwtPlot::yLeft, yGraphCoordOfDataPoint);
-    
-  // The value to shift the x-coordinate of the label by to avoid an overlap with its corresponding data point.
+  int xPixCoordOfDataPoint = d_graph->plotWidget()->transform(
+      QwtPlot::xBottom, xGraphCoordOfDataPoint);
+  int yPixCoordOfDataPoint =
+      d_graph->plotWidget()->transform(QwtPlot::yLeft, yGraphCoordOfDataPoint);
+
+  // The value to shift the x-coordinate of the label by to avoid an overlap
+  // with its corresponding data point.
   int shiftValueX = 10;
 
-  double labelCoordinateX = d_graph->plotWidget()->invTransform(QwtPlot::xBottom, (xPixCoordOfDataPoint + shiftValueX));
-  int xAxisOriginInPixCoords = d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);    
-  
+  double labelCoordinateX = d_graph->plotWidget()->invTransform(
+      QwtPlot::xBottom, (xPixCoordOfDataPoint + shiftValueX));
+  int xAxisOriginInPixCoords =
+      d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);
+
   double labelCoordinateY;
 
-  // Minimum pixel difference allowed between the y-coordinate of click and the x-axis.
-  int minDistFromAxis = 25; 
+  // Minimum pixel difference allowed between the y-coordinate of click and the
+  // x-axis.
+  int minDistFromAxis = 25;
 
-  if((xAxisOriginInPixCoords - yPixCoordOfDataPoint) < minDistFromAxis)
-  {
+  if ((xAxisOriginInPixCoords - yPixCoordOfDataPoint) < minDistFromAxis) {
     int deltaPositionFromAxis = xAxisOriginInPixCoords - yPixCoordOfDataPoint;
     int shiftValueY = minDistFromAxis - deltaPositionFromAxis;
 
-    // Remember, pixel values in the y direction increase downward from the top of the screen.
+    // Remember, pixel values in the y direction increase downward from the top
+    // of the screen.
     int labelYPixCoord = yPixCoordOfDataPoint - shiftValueY;
 
-    labelCoordinateY = d_graph->plotWidget()->invTransform(QwtPlot::yLeft,labelYPixCoord);
+    labelCoordinateY =
+        d_graph->plotWidget()->invTransform(QwtPlot::yLeft, labelYPixCoord);
   }
-    
-  else
-  {
-  labelCoordinateY = d_graph->plotWidget()->invTransform(QwtPlot::yLeft, (yPixCoordOfDataPoint));
+
+  else {
+    labelCoordinateY = d_graph->plotWidget()->invTransform(
+        QwtPlot::yLeft, (yPixCoordOfDataPoint));
   }
-    
-  dataPointLabel->setOriginCoord(labelCoordinateX,labelCoordinateY);
+
+  dataPointLabel->setOriginCoord(labelCoordinateX, labelCoordinateY);
   dataPointLabel->setText(QString::fromStdString(m_dataCoords));
 }
 
-/// Attaches a label close to a data point, showing the error associated with the y-value.
-void LabelTool::insertErrorValue()
-{  
+/// Attaches a label close to a data point, showing the error associated with
+/// the y-value.
+void LabelTool::insertErrorValue() {
   LegendWidget *errorPointLabel = new LegendWidget(d_graph->plotWidget());
 
   // x and y pixel coordinates.
   double xGraphCoordOfDataPoint = boost::lexical_cast<double>(m_xPosSigFigs);
   double yGraphCoordOfDataPoint = boost::lexical_cast<double>(m_yPosSigFigs);
 
-  int xPixCoordOfDataPoint = d_graph->plotWidget()->transform(QwtPlot::xBottom, xGraphCoordOfDataPoint);
-  int yPixCoordOfDataPoint = d_graph->plotWidget()->transform(QwtPlot::yLeft, yGraphCoordOfDataPoint);
-    
-  // The value to shift the x-coordinate of the label by to avoid an overlap with its corresponding data point.
+  int xPixCoordOfDataPoint = d_graph->plotWidget()->transform(
+      QwtPlot::xBottom, xGraphCoordOfDataPoint);
+  int yPixCoordOfDataPoint =
+      d_graph->plotWidget()->transform(QwtPlot::yLeft, yGraphCoordOfDataPoint);
+
+  // The value to shift the x-coordinate of the label by to avoid an overlap
+  // with its corresponding data point.
   int shiftValueX = 10;
 
-  double labelCoordinateX = d_graph->plotWidget()->invTransform(QwtPlot::xBottom, (xPixCoordOfDataPoint + shiftValueX));
-  int xAxisOriginInPixCoords = d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);    
-  
+  double labelCoordinateX = d_graph->plotWidget()->invTransform(
+      QwtPlot::xBottom, (xPixCoordOfDataPoint + shiftValueX));
+  int xAxisOriginInPixCoords =
+      d_graph->plotWidget()->transform(QwtPlot::yLeft, 0.0);
+
   double labelCoordinateY;
 
-  // Minimum pixel difference allowed between the y-coordinate of click and the x-axis.
-  int minDistFromAxis = 25; 
+  // Minimum pixel difference allowed between the y-coordinate of click and the
+  // x-axis.
+  int minDistFromAxis = 25;
 
-  if((xAxisOriginInPixCoords - yPixCoordOfDataPoint) < minDistFromAxis)
-  {
+  if ((xAxisOriginInPixCoords - yPixCoordOfDataPoint) < minDistFromAxis) {
     int deltaPositionFromAxis = xAxisOriginInPixCoords - yPixCoordOfDataPoint;
     int shiftValueY = minDistFromAxis - deltaPositionFromAxis;
 
-    // Remember, pixel values in the y direction increase downward from the top of the screen.
+    // Remember, pixel values in the y direction increase downward from the top
+    // of the screen.
     int labelYPixCoord = yPixCoordOfDataPoint - shiftValueY;
 
-    labelCoordinateY = d_graph->plotWidget()->invTransform(QwtPlot::yLeft,labelYPixCoord);
+    labelCoordinateY =
+        d_graph->plotWidget()->invTransform(QwtPlot::yLeft, labelYPixCoord);
   }
-    
-  else
-  {
-  labelCoordinateY = d_graph->plotWidget()->invTransform(QwtPlot::yLeft, (yPixCoordOfDataPoint));
+
+  else {
+    labelCoordinateY = d_graph->plotWidget()->invTransform(
+        QwtPlot::yLeft, (yPixCoordOfDataPoint));
   }
-    
-  errorPointLabel->setOriginCoord(labelCoordinateX,labelCoordinateY);
+
+  errorPointLabel->setOriginCoord(labelCoordinateX, labelCoordinateY);
   errorPointLabel->setText(QString::fromStdString(m_error));
 }
diff --git a/MantidPlot/src/LabelTool.h b/MantidPlot/src/LabelTool.h
index d1e518fe7f9352eb67c641cbf86ef40ea1c4559b..81f9969d6fb8236a798cdae32ac5004da30a664e 100644
--- a/MantidPlot/src/LabelTool.h
+++ b/MantidPlot/src/LabelTool.h
@@ -10,7 +10,7 @@
 #include "PlotCurve.h"
 #include "PlotToolInterface.h"
 
-#include "Mantid/MantidMatrixCurve.h" 
+#include "Mantid/MantidMatrixCurve.h"
 #include "MantidAPI/AnalysisDataService.h"
 #include "MantidQtAPI/MantidQwtWorkspaceData.h"
 #include "MantidKernel/TimeSeriesProperty.h"
@@ -42,32 +42,34 @@ class QwtPlot;
 class QAction;
 class QMenu;
 
-/// Labelling tool for graphs, which can also read points on a graph, as well as the axis.
-class LabelTool : public QObject, public QVector<QPoint>, public PlotToolInterface
-{
+/// Labelling tool for graphs, which can also read points on a graph, as well as
+/// the axis.
+class LabelTool : public QObject,
+                  public QVector<QPoint>,
+                  public PlotToolInterface {
   Q_OBJECT
 public:
   explicit LabelTool(Graph *graph);
   ~LabelTool() override;
   int rtti() const override { return PlotToolInterface::Rtti_LabelTool; };
 
- void removeTextBox();
+  void removeTextBox();
 
 protected:
-
 private:
   QwtPicker *m_canvasPicker;
   QwtPicker *m_xAxisPicker;
   QwtPicker *m_yAxisPicker;
-  
+
   QSet<QString> workspaceNames();
   // Future idea to display in the drop-down menu: QString workspaceTitle();
-  // Future idea to display in the drop-down menu: QString workspaceInstrument();
+  // Future idea to display in the drop-down menu: QString
+  // workspaceInstrument();
   QSet<QString> logValues();
-  
+
   void populateMantidCurves();
   void blankRegionClicked();
-  void dataPointClicked(); 
+  void dataPointClicked();
 
   /// Member variables relating to the point where the canvas is clicked.
   double m_xPos;
@@ -92,13 +94,12 @@ private slots:
   void xAxisClicked(const QwtPolygon &);
   void yAxisClicked(const QwtPolygon &);
 
-	void insertLegend();
-	void insertTextBox();
+  void insertLegend();
+  void insertTextBox();
   void insertXCoord();
   void insertYCoord();
   void insertDataCoord();
   void insertErrorValue();
 };
 
-
 #endif // ifndef LABEL_TOOL_H
diff --git a/MantidPlot/src/LayerDialog.cpp b/MantidPlot/src/LayerDialog.cpp
index b764ab2c62cdc708cae0283c026d67aadcdff2ce..c3b16136bb40502f9aae0cd3e1f84bc31c6dc4ba 100644
--- a/MantidPlot/src/LayerDialog.cpp
+++ b/MantidPlot/src/LayerDialog.cpp
@@ -249,8 +249,7 @@ void LayerDialog::update() {
   if (cols > graphs && !fitBox->isChecked()) {
     QMessageBox::about(this, tr("MantidPlot - Columns input error"),
                        tr("The number of columns you've entered is greater "
-                          "than the number of graphs (%1)!")
-                           .arg(graphs));
+                          "than the number of graphs (%1)!").arg(graphs));
     boxX->setFocus();
     return;
   }
@@ -258,8 +257,7 @@ void LayerDialog::update() {
   if (rows > graphs && !fitBox->isChecked()) {
     QMessageBox::about(this, tr("MantidPlot - Rows input error"),
                        tr("The number of rows you've entered is greater than "
-                          "the number of graphs (%1)!")
-                           .arg(graphs));
+                          "the number of graphs (%1)!").arg(graphs));
     boxY->setFocus();
     return;
   }
diff --git a/MantidPlot/src/LayerDialog.h b/MantidPlot/src/LayerDialog.h
index 0164e070853a85c8f25bc2850a25ee7369d10200..a97d481f70593bc06a4a85e50e90441ad39d3db6 100644
--- a/MantidPlot/src/LayerDialog.h
+++ b/MantidPlot/src/LayerDialog.h
@@ -38,34 +38,33 @@ class QCheckBox;
 class QComboBox;
 
 //! Arrange layers dialog
-class LayerDialog : public QDialog
-{
-    Q_OBJECT
+class LayerDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    LayerDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
-	void setMultiLayer(MultiLayer *g);
+  LayerDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
+  void setMultiLayer(MultiLayer *g);
 
 protected slots:
   void accept() override;
-        void update();
-	void enableLayoutOptions(bool ok);
-	void swapLayers();
+  void update();
+  void enableLayoutOptions(bool ok);
+  void swapLayers();
 
 private:
-	MultiLayer *multi_layer;
+  MultiLayer *multi_layer;
 
-	QPushButton* buttonOk;
-	QPushButton* buttonCancel;
-	QPushButton* buttonApply;
-	QPushButton* buttonSwapLayers;
-    QGroupBox *GroupCanvasSize, *GroupGrid;
-    QSpinBox *boxX, *boxY, *boxColsGap, *boxRowsGap;
-	QSpinBox *boxRightSpace, *boxLeftSpace, *boxTopSpace, *boxBottomSpace;
-	QSpinBox *boxCanvasWidth, *boxCanvasHeight, *layersBox;
-	QSpinBox *boxLayerDest, *boxLayerSrc;
-	QCheckBox *fitBox;
-	QComboBox *alignHorBox, *alignVertBox;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonApply;
+  QPushButton *buttonSwapLayers;
+  QGroupBox *GroupCanvasSize, *GroupGrid;
+  QSpinBox *boxX, *boxY, *boxColsGap, *boxRowsGap;
+  QSpinBox *boxRightSpace, *boxLeftSpace, *boxTopSpace, *boxBottomSpace;
+  QSpinBox *boxCanvasWidth, *boxCanvasHeight, *layersBox;
+  QSpinBox *boxLayerDest, *boxLayerSrc;
+  QCheckBox *fitBox;
+  QComboBox *alignHorBox, *alignVertBox;
 };
 
 #endif
diff --git a/MantidPlot/src/LegendWidget.cpp b/MantidPlot/src/LegendWidget.cpp
index b11a10f70fd5790cb42c0ce7bb97b793f9203562..21399eeffb01c3a98abc6ae80911c66bf8c3fb65 100644
--- a/MantidPlot/src/LegendWidget.cpp
+++ b/MantidPlot/src/LegendWidget.cpp
@@ -45,288 +45,280 @@
 #include <qwt_layout_metrics.h>
 #include <qwt_symbol.h>
 
-
-LegendWidget::LegendWidget(Plot *plot):QWidget(plot),
-	d_plot(plot),
-	d_frame (0),
-	d_angle(0),
-        d_x(0.), d_y(0.),
-        d_fixed_coordinates(false)
-{
-	setAttribute(Qt::WA_DeleteOnClose);
-
-	d_text = new QwtText(QString::null, QwtText::RichText);
-	d_text->setFont(QFont("Arial", 12, QFont::Normal, false));
-	d_text->setRenderFlags(Qt::AlignTop|Qt::AlignLeft);
-	d_text->setBackgroundBrush(QBrush(Qt::NoBrush));
-	d_text->setColor(Qt::black);
-	d_text->setBackgroundPen (QPen(Qt::NoPen));
-	d_text->setPaintAttribute(QwtText::PaintBackground);
-
-	h_space = 5;
-	left_margin = 10;
-	top_margin = 5;
-	line_length = 20;
-
-	QPoint pos = plot->canvas()->pos();
-	pos = QPoint(pos.x() + 10, pos.y() + 10);
-	move(pos);
-
-    d_selector = NULL;
-
-	connect (this, SIGNAL(showDialog()), plot->parent(), SIGNAL(viewTextDialog()));
-	connect (this, SIGNAL(showMenu()), plot->parent(), SIGNAL(showMarkerPopupMenu()));
-	connect (this, SIGNAL(enableEditor()), plot->parent(), SLOT(enableTextEditor()));
-
-	setMouseTracking(true);
-	show();
-	setFocus();
+LegendWidget::LegendWidget(Plot *plot)
+    : QWidget(plot), d_plot(plot), d_frame(0), d_angle(0), d_x(0.), d_y(0.),
+      d_fixed_coordinates(false) {
+  setAttribute(Qt::WA_DeleteOnClose);
+
+  d_text = new QwtText(QString::null, QwtText::RichText);
+  d_text->setFont(QFont("Arial", 12, QFont::Normal, false));
+  d_text->setRenderFlags(Qt::AlignTop | Qt::AlignLeft);
+  d_text->setBackgroundBrush(QBrush(Qt::NoBrush));
+  d_text->setColor(Qt::black);
+  d_text->setBackgroundPen(QPen(Qt::NoPen));
+  d_text->setPaintAttribute(QwtText::PaintBackground);
+
+  h_space = 5;
+  left_margin = 10;
+  top_margin = 5;
+  line_length = 20;
+
+  QPoint pos = plot->canvas()->pos();
+  pos = QPoint(pos.x() + 10, pos.y() + 10);
+  move(pos);
+
+  d_selector = NULL;
+
+  connect(this, SIGNAL(showDialog()), plot->parent(), SIGNAL(viewTextDialog()));
+  connect(this, SIGNAL(showMenu()), plot->parent(),
+          SIGNAL(showMarkerPopupMenu()));
+  connect(this, SIGNAL(enableEditor()), plot->parent(),
+          SLOT(enableTextEditor()));
+
+  setMouseTracking(true);
+  show();
+  setFocus();
 }
 
-void LegendWidget::paintEvent(QPaintEvent *e)
-{
-	if (d_fixed_coordinates){
-		setOriginCoord(d_x, d_y);
-		d_fixed_coordinates = false;
-	}
-
-	const int symbolLineLength = line_length + symbolsMaxWidth();
-	int width, height;
-	QwtArray<int> heights = itemsHeight(0, symbolLineLength, width, height);
-	if (d_frame == Shadow)
-		resize(width + 5, height + 5);
-	else
-    	resize(width, height);
-
-	QRect rect = QRect(0, 0, width - 1, height - 1);
-    QPainter p(this);
-	drawFrame(&p, rect);
-	drawText(&p, rect, heights, symbolLineLength);
-	e->accept();
+void LegendWidget::paintEvent(QPaintEvent *e) {
+  if (d_fixed_coordinates) {
+    setOriginCoord(d_x, d_y);
+    d_fixed_coordinates = false;
+  }
+
+  const int symbolLineLength = line_length + symbolsMaxWidth();
+  int width, height;
+  QwtArray<int> heights = itemsHeight(0, symbolLineLength, width, height);
+  if (d_frame == Shadow)
+    resize(width + 5, height + 5);
+  else
+    resize(width, height);
+
+  QRect rect = QRect(0, 0, width - 1, height - 1);
+  QPainter p(this);
+  drawFrame(&p, rect);
+  drawText(&p, rect, heights, symbolLineLength);
+  e->accept();
 }
 
-void LegendWidget::print(QPainter *painter, const QwtScaleMap map[QwtPlot::axisCnt])
-{
-	int x = map[QwtPlot::xBottom].transform(xValue());
-	int y = map[QwtPlot::yLeft].transform(yValue());
+void LegendWidget::print(QPainter *painter,
+                         const QwtScaleMap map[QwtPlot::axisCnt]) {
+  int x = map[QwtPlot::xBottom].transform(xValue());
+  int y = map[QwtPlot::yLeft].transform(yValue());
 
-    const int symbolLineLength = line_length + symbolsMaxWidth();
-	int width, height;
-	QwtArray<int> heights = itemsHeight(y, symbolLineLength, width, height);
+  const int symbolLineLength = line_length + symbolsMaxWidth();
+  int width, height;
+  QwtArray<int> heights = itemsHeight(y, symbolLineLength, width, height);
 
-	QRect rect = QRect(x, y, width, height);
-	drawFrame(painter, rect);
-	drawText(painter, rect, heights, symbolLineLength);
+  QRect rect = QRect(x, y, width, height);
+  drawFrame(painter, rect);
+  drawText(painter, rect, heights, symbolLineLength);
 }
 
-void LegendWidget::setText(const QString& s)
-{
-	d_text->setText(s);
-}
+void LegendWidget::setText(const QString &s) { d_text->setText(s); }
 
-void LegendWidget::setFrameStyle(int style)
-{
-	if (d_frame == style)
-		return;
+void LegendWidget::setFrameStyle(int style) {
+  if (d_frame == style)
+    return;
 
-	d_frame = style;
+  d_frame = style;
 }
 
-void LegendWidget::setBackgroundColor(const QColor& c)
-{
-	if (d_text->backgroundBrush().color() == c)
-		return;
+void LegendWidget::setBackgroundColor(const QColor &c) {
+  if (d_text->backgroundBrush().color() == c)
+    return;
 
-	d_text->setBackgroundBrush(QBrush(c));
+  d_text->setBackgroundBrush(QBrush(c));
 }
 
-void LegendWidget::setTextColor(const QColor& c)
-{
-	if ( c == d_text->color() )
-		return;
+void LegendWidget::setTextColor(const QColor &c) {
+  if (c == d_text->color())
+    return;
 
-	d_text->setColor(c);
+  d_text->setColor(c);
 }
 
-void LegendWidget::setOriginCoord(double x, double y)
-{
-	QPoint pos(d_plot->transform(QwtPlot::xBottom, x), d_plot->transform(QwtPlot::yLeft, y));
-	pos = d_plot->canvas()->mapToParent(pos);
-	move(pos);
+void LegendWidget::setOriginCoord(double x, double y) {
+  QPoint pos(d_plot->transform(QwtPlot::xBottom, x),
+             d_plot->transform(QwtPlot::yLeft, y));
+  pos = d_plot->canvas()->mapToParent(pos);
+  move(pos);
 }
 
-double LegendWidget::xValue()
-{
-	QPoint d_pos = d_plot->canvas()->mapFromParent(geometry().topLeft());
-	return d_plot->invTransform(QwtPlot::xBottom, d_pos.x());
+double LegendWidget::xValue() {
+  QPoint d_pos = d_plot->canvas()->mapFromParent(geometry().topLeft());
+  return d_plot->invTransform(QwtPlot::xBottom, d_pos.x());
 }
 
-double LegendWidget::yValue()
-{
-	QPoint d_pos = d_plot->canvas()->mapFromParent(geometry().topLeft());
-	return d_plot->invTransform(QwtPlot::yLeft, d_pos.y());
+double LegendWidget::yValue() {
+  QPoint d_pos = d_plot->canvas()->mapFromParent(geometry().topLeft());
+  return d_plot->invTransform(QwtPlot::yLeft, d_pos.y());
 }
 
-void LegendWidget::setFont(const QFont& font)
-{
-	if ( font == d_text->font() )
-		return;
+void LegendWidget::setFont(const QFont &font) {
+  if (font == d_text->font())
+    return;
 
-	d_text->setFont(font);
+  d_text->setFont(font);
 }
 
-void LegendWidget::drawFrame(QPainter *p, const QRect& rect)
-{
-	p->save();
-	p->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
-	if (d_frame == None)
-		p->fillRect (rect, d_text->backgroundBrush());
-
-	if (d_frame == Line){
-		p->setBrush(d_text->backgroundBrush());
-		QwtPainter::drawRect(p, rect);
-	} else if (d_frame == Shadow) {
-		QRect shadow_right = QRect(rect.right() + 1, rect.y() + 5, 5, rect.height());
-		QRect shadow_bottom = QRect(rect.x() + 5, rect.bottom() + 1, rect.width(), 5);
-		p->setBrush(QBrush(Qt::black));
-		p->drawRect(shadow_right);
-		p->drawRect(shadow_bottom);
-
-		p->setBrush(d_text->backgroundBrush());
-		QwtPainter::drawRect(p,rect);
-	}
-	p->restore();
+void LegendWidget::drawFrame(QPainter *p, const QRect &rect) {
+  p->save();
+  p->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
+  if (d_frame == None)
+    p->fillRect(rect, d_text->backgroundBrush());
+
+  if (d_frame == Line) {
+    p->setBrush(d_text->backgroundBrush());
+    QwtPainter::drawRect(p, rect);
+  } else if (d_frame == Shadow) {
+    QRect shadow_right =
+        QRect(rect.right() + 1, rect.y() + 5, 5, rect.height());
+    QRect shadow_bottom =
+        QRect(rect.x() + 5, rect.bottom() + 1, rect.width(), 5);
+    p->setBrush(QBrush(Qt::black));
+    p->drawRect(shadow_right);
+    p->drawRect(shadow_bottom);
+
+    p->setBrush(d_text->backgroundBrush());
+    QwtPainter::drawRect(p, rect);
+  }
+  p->restore();
 }
 
-void LegendWidget::drawVector(PlotCurve *c, QPainter *p, int x, int y, int l)
-{
-	if (!c)
-		return;
+void LegendWidget::drawVector(PlotCurve *c, QPainter *p, int x, int y, int l) {
+  if (!c)
+    return;
 
-  VectorCurve *v = dynamic_cast<VectorCurve*>(c);
-  if (!v) return;
+  VectorCurve *v = dynamic_cast<VectorCurve *>(c);
+  if (!v)
+    return;
 
-  Graph* g = dynamic_cast<Graph *>(d_plot->parent());
-  if (!g) return;
+  Graph *g = dynamic_cast<Graph *>(d_plot->parent());
+  if (!g)
+    return;
 
-	p->save();
+  p->save();
 
   if (g->antialiasing())
-		p->setRenderHints(QPainter::Antialiasing);
+    p->setRenderHints(QPainter::Antialiasing);
 
-	QPen pen(v->color(), v->width(), Qt::SolidLine);
-	p->setPen(pen);
-	p->drawLine(x, y, x + l, y);
+  QPen pen(v->color(), v->width(), Qt::SolidLine);
+  p->setPen(pen);
+  p->drawLine(x, y, x + l, y);
 
-	p->translate(x+l, y);
+  p->translate(x + l, y);
 
-	double pi=4*atan(-1.0);
-	int headLength = v->headLength();
-	int d=qRound(headLength*tan(pi*(double)v->headAngle()/180.0));
+  double pi = 4 * atan(-1.0);
+  int headLength = v->headLength();
+  int d = qRound(headLength * tan(pi * (double)v->headAngle() / 180.0));
 
-	QPolygon endArray(3);
-	endArray[0] = QPoint(0, 0);
-	endArray[1] = QPoint(-headLength, d);
-	endArray[2] = QPoint(-headLength, -d);
+  QPolygon endArray(3);
+  endArray[0] = QPoint(0, 0);
+  endArray[1] = QPoint(-headLength, d);
+  endArray[2] = QPoint(-headLength, -d);
 
-	if (v->filledArrowHead())
-		p->setBrush(QBrush(pen.color(), Qt::SolidPattern));
+  if (v->filledArrowHead())
+    p->setBrush(QBrush(pen.color(), Qt::SolidPattern));
 
-	p->drawPolygon(endArray);
-	p->restore();
+  p->drawPolygon(endArray);
+  p->restore();
 }
 
-void LegendWidget::drawSymbol(PlotCurve *c, int point, QPainter *p, int x, int y, int l)
-{
-    if (!c || c->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
-        return;
+void LegendWidget::drawSymbol(PlotCurve *c, int point, QPainter *p, int x,
+                              int y, int l) {
+  if (!c || c->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
+    return;
 
-    if (c->type() == Graph::VectXYXY || c->type() == Graph::VectXYAM){
-        drawVector(c, p, x, y, l);
-        return;
-    }
+  if (c->type() == Graph::VectXYXY || c->type() == Graph::VectXYAM) {
+    drawVector(c, p, x, y, l);
+    return;
+  }
 
-	if (c->type() == Graph::Pie){
+  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();
-		p->setPen (QPen(pen.color(), pen.widthF(), Qt::SolidLine));
-		QRect lr = QRect(x, y - 4, l, 10);
-		p->setBrush(br);
-		QwtPainter::drawRect(p, lr);
-		p->restore();
-		return;
-	}
-
-    QwtSymbol symb = c->symbol();
-    const QBrush br = c->brush();
-    QPen pen = c->pen();
+    if (!pie)
+      return;
+    const QBrush br = QBrush(pie->color(point), pie->pattern());
+    QPen pen = pie->pen();
     p->save();
-    if (c->style()!=0){
-        p->setPen (pen);
-        if (br.style() != Qt::NoBrush || c->type() == Graph::Box){
-            QRect lr = QRect(x, y-4, l, 10);
-            p->setBrush(br);
-            QwtPainter::drawRect(p, lr);
-        } else
-            QwtPainter::drawLine(p, x, y, x + l, y);
-    }
-    int symb_size = symb.size().width();
-    if (symb_size > 15)
-        symb_size = 15;
-    else if (symb_size < 3)
-        symb_size = 3;
-    symb.setSize(symb_size);
-    symb.draw(p, x + l/2, y);
+    p->setPen(QPen(pen.color(), pen.widthF(), Qt::SolidLine));
+    QRect lr = QRect(x, y - 4, l, 10);
+    p->setBrush(br);
+    QwtPainter::drawRect(p, lr);
     p->restore();
+    return;
+  }
+
+  QwtSymbol symb = c->symbol();
+  const QBrush br = c->brush();
+  QPen pen = c->pen();
+  p->save();
+  if (c->style() != 0) {
+    p->setPen(pen);
+    if (br.style() != Qt::NoBrush || c->type() == Graph::Box) {
+      QRect lr = QRect(x, y - 4, l, 10);
+      p->setBrush(br);
+      QwtPainter::drawRect(p, lr);
+    } else
+      QwtPainter::drawLine(p, x, y, x + l, y);
+  }
+  int symb_size = symb.size().width();
+  if (symb_size > 15)
+    symb_size = 15;
+  else if (symb_size < 3)
+    symb_size = 3;
+  symb.setSize(symb_size);
+  symb.draw(p, x + l / 2, y);
+  p->restore();
 }
 
-void LegendWidget::drawText(QPainter *p, const QRect& rect,
-		QwtArray<int> height, int symbolLineLength)
-{
+void LegendWidget::drawText(QPainter *p, const QRect &rect,
+                            QwtArray<int> height, int symbolLineLength) {
   p->save();
   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 
+  // RJT (22/09/09): For remainder of method, copied in code from current
   // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
   int l = symbolLineLength;
   QString text = d_text->text();
   QStringList titles = text.split("\n", QString::KeepEmptyParts);
 
-  for (int i=0; i<(int)titles.count(); i++){
-    int w = left_margin + rect.x(); // QtiPlot Rev 1373 has this as 2nd arg: d_frame_pen.width();
-    bool  curveSymbol = false;
+  for (int i = 0; i < (int)titles.count(); i++) {
+    int w =
+        left_margin +
+        rect.x(); // QtiPlot Rev 1373 has this as 2nd arg: d_frame_pen.width();
+    bool curveSymbol = false;
     QString s = titles[i];
-    while (s.contains("\\l(",Qt::CaseInsensitive) || s.contains("\\p{",Qt::CaseInsensitive)){
+    while (s.contains("\\l(", Qt::CaseInsensitive) ||
+           s.contains("\\p{", Qt::CaseInsensitive)) {
       curveSymbol = true;
-      int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
-      int pos2 = s.indexOf(",",pos); // two arguments in case if pie chart
-      int pos3 = s.indexOf(")",pos);
-      if (pos >= 0 && (pos2 == -1 || pos2 > pos3)){
-        QwtText aux(parse(s.left(pos))); //not a pie chart
+      int pos = s.indexOf("\\l(", 0, Qt::CaseInsensitive);
+      int pos2 = s.indexOf(",", pos); // two arguments in case if pie chart
+      int pos3 = s.indexOf(")", pos);
+      if (pos >= 0 && (pos2 == -1 || pos2 > pos3)) {
+        QwtText aux(parse(s.left(pos))); // not a pie chart
         aux.setFont(d_text->font());
         aux.setColor(d_text->color());
-        aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);
+        aux.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter);
 
         QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
-        QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
+        QRect tr = QRect(QPoint(w, height[i] - size.height() / 2), size);
         aux.draw(p, tr);
         w += size.width();
 
         int pos1 = s.indexOf("(", pos);
         int pos2 = s.indexOf(")", pos1);
-        if (pos2 == -1){
+        if (pos2 == -1) {
           s = s.right(s.length() - pos1 - 1);
           continue;
         }
         int point = -1;
-        PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point);
-        if (!curve){
+        PlotCurve *curve = getCurve(s.mid(pos1 + 1, pos2 - pos1 - 1), point);
+        if (!curve) {
           s = s.right(s.length() - pos2 - 1);
           continue;
         }
@@ -336,48 +328,51 @@ void LegendWidget::drawText(QPainter *p, const QRect& rect,
         s = s.right(s.length() - pos2 - 1);
       } else { // pie chart?
         pos = s.indexOf("\\p{", 0);
-        if (pos >= 0){  // old syntax
+        if (pos >= 0) { // old syntax
           QwtText aux(parse(s.left(pos)));
           aux.setFont(d_text->font());
           aux.setColor(d_text->color());
-          aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);
+          aux.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter);
 
           QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
-          QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
+          QRect tr = QRect(QPoint(w, height[i] - size.height() / 2), size);
           aux.draw(p, tr);
           w += size.width();
 
           int pos1 = s.indexOf("{", pos);
           int pos2 = s.indexOf("}", pos1);
-          if (pos2 == -1){
-          s = s.right(s.length() - pos1 - 1);
-          continue;
+          if (pos2 == -1) {
+            s = s.right(s.length() - pos1 - 1);
+            continue;
           }
           int point = s.mid(pos1 + 1, pos2 - pos1 - 1).toInt() - 1;
-          drawSymbol(dynamic_cast<PlotCurve*>(d_plot->curve(0)), point, p, w, height[i], l);
+          drawSymbol(dynamic_cast<PlotCurve *>(d_plot->curve(0)), point, p, w,
+                     height[i], l);
           w += l;
           s = s.right(s.length() - pos2 - 1);
         } else {
-          pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
-          if (pos >= 0 && pos2 != -1){ //new syntax
+          pos = s.indexOf("\\l(", 0, Qt::CaseInsensitive);
+          if (pos >= 0 && pos2 != -1) { // new syntax
             QwtText aux(parse(s.left(pos)));
             aux.setFont(d_text->font());
             aux.setColor(d_text->color());
-            aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);
+            aux.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter);
 
-            QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
-            QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
+            QSize size =
+                aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
+            QRect tr = QRect(QPoint(w, height[i] - size.height() / 2), size);
             aux.draw(p, tr);
             w += size.width();
 
             int pos1 = s.indexOf(",", pos);
             int pos3 = s.indexOf(")", pos1);
-            if (pos3 == -1){
+            if (pos3 == -1) {
               s = s.right(s.length() - pos1 - 1);
               continue;
             }
             int point = s.mid(pos1 + 1, pos3 - pos1 - 1).toInt() - 1;
-            drawSymbol(dynamic_cast<PlotCurve*>(d_plot->curve(0)), point, p, w, height[i], l);
+            drawSymbol(dynamic_cast<PlotCurve *>(d_plot->curve(0)), point, p, w,
+                       height[i], l);
             w += l;
             s = s.right(s.length() - pos3 - 1);
           }
@@ -385,25 +380,25 @@ void LegendWidget::drawText(QPainter *p, const QRect& rect,
       }
     }
 
-    if (!s.isEmpty()){
+    if (!s.isEmpty()) {
       if (curveSymbol)
         w += h_space;
       QwtText aux(parse(s));
       aux.setFont(d_text->font());
       aux.setColor(d_text->color());
-      aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);
+      aux.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter);
 
       QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
-      QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
+      QRect tr = QRect(QPoint(w, height[i] - size.height() / 2), size);
       aux.draw(p, tr);
     }
   }
   p->restore();
 }
 
-QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width, int &height)
-{
-  // RJT (22/09/09): For most of method, copied in code from current 
+QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width,
+                                        int &height) {
+  // RJT (22/09/09): For most of method, copied in code from current
   // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
   QString text = d_text->text();
   QStringList titles = text.split("\n", QString::KeepEmptyParts);
@@ -414,57 +409,61 @@ QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width,
   height = 0;
   int maxL = 0;
   int h = top_margin; // In QtiPlot rev 1373: + d_frame_pen.width();
-  for (int i=0; i<n; i++){
+  for (int i = 0; i < n; i++) {
     QString s = titles[i];
     int textL = 0;
-    //bool curveSymbol = false;
-    while (s.contains("\\l(",Qt::CaseInsensitive) || s.contains("\\p{",Qt::CaseInsensitive)){
-      int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
-      int pos2 = s.indexOf(",",pos); // two arguments in case if pie chart
-      int pos3 = s.indexOf(")",pos);
-      //curveSymbol = true;
-      if (pos >= 0 && (pos2==-1 || pos2>pos3)){
-        QwtText aux(parse(s.left(pos))); //not a pie chart
+    // bool curveSymbol = false;
+    while (s.contains("\\l(", Qt::CaseInsensitive) ||
+           s.contains("\\p{", Qt::CaseInsensitive)) {
+      int pos = s.indexOf("\\l(", 0, Qt::CaseInsensitive);
+      int pos2 = s.indexOf(",", pos); // two arguments in case if pie chart
+      int pos3 = s.indexOf(")", pos);
+      // curveSymbol = true;
+      if (pos >= 0 && (pos2 == -1 || pos2 > pos3)) {
+        QwtText aux(parse(s.left(pos))); // not a pie chart
         aux.setFont(d_text->font());
         QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
         textL += size.width();
 
         int pos1 = s.indexOf("(", pos);
         int pos2 = s.indexOf(")", pos1);
-        if (pos2 == -1){
+        if (pos2 == -1) {
           s = s.right(s.length() - pos1 - 1);
           continue;
         }
         int point = -1;
-        PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point);
-        if (!curve){
+        PlotCurve *curve = getCurve(s.mid(pos1 + 1, pos2 - pos1 - 1), point);
+        if (!curve) {
           s = s.right(s.length() - pos2 - 1);
           continue;
         }
 
         textL += symbolLineLength + h_space;
         s = s.right(s.length() - s.indexOf(")", pos) - 1);
-      } else { //Pie chart?
-        pos = s.indexOf("\\p{", 0,Qt::CaseInsensitive); //look for old syntax
-        if (pos >= 0){
+      } else {                                           // Pie chart?
+        pos = s.indexOf("\\p{", 0, Qt::CaseInsensitive); // look for old syntax
+        if (pos >= 0) {
           QwtText aux(parse(s.left(pos)));
           aux.setFont(d_text->font());
           QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
           textL += size.width();
           textL += symbolLineLength;
-          int pos2=s.indexOf("}", pos);
-          if (pos2==-1) pos2=pos+3;
+          int pos2 = s.indexOf("}", pos);
+          if (pos2 == -1)
+            pos2 = pos + 3;
           s = s.right(s.length() - pos2 - 1);
         } else {
-          pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive); // new syntax
-          if (pos >= 0){
+          pos = s.indexOf("\\l(", 0, Qt::CaseInsensitive); // new syntax
+          if (pos >= 0) {
             QwtText aux(parse(s.left(pos)));
             aux.setFont(d_text->font());
-            QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
+            QSize size =
+                aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
             textL += size.width();
             textL += symbolLineLength;
-            int pos2=s.indexOf(")", pos);
-            if (pos2==-1) pos2=pos+3;
+            int pos2 = s.indexOf(")", pos);
+            if (pos2 == -1)
+              pos2 = pos + 3;
             s = s.right(s.length() - pos2 - 1);
           }
         }
@@ -483,57 +482,55 @@ QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width,
     int textH = size.height();
     height += textH;
 
-    heights[i] = y + h + textH/2;
+    heights[i] = y + h + textH / 2;
     h += textH;
   }
 
-  height += 2*top_margin;
-  width = 2*left_margin + maxL + h_space;
+  height += 2 * top_margin;
+  width = 2 * left_margin + maxL + h_space;
 
   return heights;
 }
 
-int LegendWidget::symbolsMaxWidth()
-{
+int LegendWidget::symbolsMaxWidth() {
   QList<int> cvs = d_plot->curveKeys();
   int curves = cvs.count();
   if (!curves)
     return 0;
 
-  // RJT (22/09/09): For rest of method, copied in code from current 
+  // RJT (22/09/09): For rest of method, copied in code from current
   // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
   int maxL = 0;
   QString text = d_text->text();
   QStringList titles = text.split("\n", QString::KeepEmptyParts);
-  for (int i=0; i<(int)titles.count(); i++){
+  for (int i = 0; i < (int)titles.count(); i++) {
     QString s = titles[i];
-    while (s.contains("\\l(",Qt::CaseInsensitive)){
-      int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
+    while (s.contains("\\l(", Qt::CaseInsensitive)) {
+      int pos = s.indexOf("\\l(", 0, Qt::CaseInsensitive);
       int pos1 = s.indexOf("(", pos);
       int pos2 = s.indexOf(")", pos1);
-      int pos3 = s.indexOf(",",pos1);
-      if (pos3 != -1 && pos3 < pos2 ) pos2=pos3; // for pi charts get dataset number
-      if (pos2 == -1){
+      int pos3 = s.indexOf(",", pos1);
+      if (pos3 != -1 && pos3 < pos2)
+        pos2 = pos3; // for pi charts get dataset number
+      if (pos2 == -1) {
         s = s.right(s.length() - pos1 - 1);
         continue;
       }
 
       int point = 0;
-      PlotCurve* c = getCurve(s.mid(pos1 + 1, pos2 - pos1 - 1), point);
-      if (c && c->type() == Graph::Pie){
-        maxL = 2*d_text->font().pointSize();//10;
+      PlotCurve *c = getCurve(s.mid(pos1 + 1, pos2 - pos1 - 1), point);
+      if (c && c->type() == Graph::Pie) {
+        maxL = 2 * d_text->font().pointSize(); // 10;
         line_length = 0;
         s = s.right(s.length() - pos2 - 1);
         continue;
       }
 
       if (c && c->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) {
-        if (c->type() == Graph::Pie ||
-          c->type() == Graph::VerticalBars ||
-          c->type() == Graph::HorizontalBars ||
-          c->type() == Graph::Histogram ||
-          c->type() == Graph::Box){
-          maxL = 2*d_text->font().pointSize();//10;
+        if (c->type() == Graph::Pie || c->type() == Graph::VerticalBars ||
+            c->type() == Graph::HorizontalBars ||
+            c->type() == Graph::Histogram || c->type() == Graph::Box) {
+          maxL = 2 * d_text->font().pointSize(); // 10;
           line_length = 0;
         } else {
           int l = c->symbol().size().width();
@@ -541,184 +538,175 @@ int LegendWidget::symbolsMaxWidth()
             l = 3;
           else if (l > 15)
             l = 15;
-          if (l>maxL && c->symbol().style() != QwtSymbol::NoSymbol)
+          if (l > maxL && c->symbol().style() != QwtSymbol::NoSymbol)
             maxL = l;
         }
       }
       s = s.right(s.length() - pos2 - 1);
     }
 
-    if (titles[i].contains("\\p{")){ // old syntax for pie charts
-      maxL = 2*d_text->font().pointSize();//10;
+    if (titles[i].contains("\\p{")) {        // old syntax for pie charts
+      maxL = 2 * d_text->font().pointSize(); // 10;
       line_length = 0;
     }
   }
   return maxL;
 }
 
-QString LegendWidget::parse(const QString& str)
-{
-    QString s = str;
-    s.remove(QRegExp("\\l(*)", Qt::CaseSensitive, QRegExp::Wildcard));
-    s.remove(QRegExp("\\p{*}", Qt::CaseSensitive, QRegExp::Wildcard));
-
-	QString aux = str;
-    while (aux.contains(QRegExp("%(*)", Qt::CaseInsensitive, QRegExp::Wildcard))){//curve name specification
-		int pos = str.indexOf("%(", 0, Qt::CaseInsensitive);
-        int pos2 = str.indexOf(")", pos, Qt::CaseInsensitive);
-		QString spec = str.mid(pos + 2, pos2 - pos - 2);
-		QStringList lst = spec.split(",");
-		if (!lst.isEmpty()){
-        	int cv = lst[0].toInt() - 1;
+QString LegendWidget::parse(const QString &str) {
+  QString s = str;
+  s.remove(QRegExp("\\l(*)", Qt::CaseSensitive, QRegExp::Wildcard));
+  s.remove(QRegExp("\\p{*}", Qt::CaseSensitive, QRegExp::Wildcard));
+
+  QString aux = str;
+  while (aux.contains(QRegExp("%(*)", Qt::CaseInsensitive,
+                              QRegExp::Wildcard))) { // curve name specification
+    int pos = str.indexOf("%(", 0, Qt::CaseInsensitive);
+    int pos2 = str.indexOf(")", pos, Qt::CaseInsensitive);
+    QString spec = str.mid(pos + 2, pos2 - pos - 2);
+    QStringList lst = spec.split(",");
+    if (!lst.isEmpty()) {
+      int cv = lst[0].toInt() - 1;
       Graph *g = dynamic_cast<Graph *>(d_plot->parent());
-        	if (g && cv >= 0 && cv < g->curves()){
+      if (g && cv >= 0 && cv < g->curves()) {
         PlotCurve *c = dynamic_cast<PlotCurve *>(g->curve(cv));
-            	if (c){
-					if (lst.count() == 1)
-						s = s.replace(pos, pos2-pos+1, c->title().text());
-					else if (lst.count() == 3 && c->type() == Graph::Pie){
+        if (c) {
+          if (lst.count() == 1)
+            s = s.replace(pos, pos2 - pos + 1, c->title().text());
+          else if (lst.count() == 3 && c->type() == Graph::Pie) {
             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));
+              int col = t->colIndex(c->title().text());
+              int row = lst[2].toInt() - 1;
+              s = s.replace(pos, pos2 - pos + 1, t->text(row, col));
             }
-					}
-				}
-        	}
-			aux = aux.right(aux.length() - pos2 - 1);
-		}
+          }
+        }
+      }
+      aux = aux.right(aux.length() - pos2 - 1);
     }
-    return s;
+  }
+  return s;
 }
 
-PlotCurve* LegendWidget::getCurve(const QString& s, int &point)
-{
-	point = -1;
-	PlotCurve *curve = 0;
+PlotCurve *LegendWidget::getCurve(const QString &s, int &point) {
+  point = -1;
+  PlotCurve *curve = 0;
   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));
-		  }
-	  }
+    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;
+  return curve;
 }
 
-void LegendWidget::mousePressEvent (QMouseEvent * /*e*/)
-{
-  if (d_selector)
-  {
+void LegendWidget::mousePressEvent(QMouseEvent * /*e*/) {
+  if (d_selector) {
     delete d_selector;
     d_selector = NULL;
   }
 
-  Graph *g = (dynamic_cast<Graph*>(d_plot->parent()));
+  Graph *g = (dynamic_cast<Graph *>(d_plot->parent()));
   if (!g)
     return;
   g->activateGraph();
   g->deselectMarker();
 
-  // Make sure the target of the new SelectionMoveResizer is the actual object being clicked.
-  // 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): 
+  // Make sure the target of the new SelectionMoveResizer is the actual object
+  // being clicked.
+  // 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()))
-  if (LegendWidget *clickedWidget = dynamic_cast<LegendWidget*>(qApp->widgetAt(QCursor::pos()))) {
+  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)
-{
-  if (on)
-  {
-    if (d_selector)
-    {
+void LegendWidget::setSelected(bool on) {
+  if (on) {
+    if (d_selector) {
       return;
-    }
-    else
-    {
-      LegendWidget *clickedWidget = dynamic_cast<LegendWidget*>(qApp->widgetAt(QCursor::pos()));
+    } else {
+      LegendWidget *clickedWidget =
+          dynamic_cast<LegendWidget *>(qApp->widgetAt(QCursor::pos()));
       if (!clickedWidget)
-	return;
+        return;
       d_selector = new SelectionMoveResizer(clickedWidget);
-      Graph *g = (dynamic_cast<Graph*>(d_plot->parent()));
+      Graph *g = (dynamic_cast<Graph *>(d_plot->parent()));
       if (!g)
-	return;
+        return;
       connect(d_selector, SIGNAL(targetsChanged()), g, SIGNAL(modifiedGraph()));
       g->setSelectedText(this);
     }
-  }
-  else if (d_selector)
-  {
+  } else if (d_selector) {
     d_selector->close();
     d_selector = NULL;
-    Graph *g = (dynamic_cast<Graph*>(d_plot->parent()));
+    Graph *g = (dynamic_cast<Graph *>(d_plot->parent()));
     if (!g)
       return;
     g->setSelectedText(NULL);
   }
 }
 
-void LegendWidget::showTextEditor()
-{
-    Graph *g = (dynamic_cast<Graph*>(d_plot->parent()));
-    if (!g)
-      return;
+void LegendWidget::showTextEditor() {
+  Graph *g = (dynamic_cast<Graph *>(d_plot->parent()));
+  if (!g)
+    return;
 
-    ApplicationWindow *app = g->multiLayer()->applicationWindow();
-    if (!app)
-        return;
+  ApplicationWindow *app = g->multiLayer()->applicationWindow();
+  if (!app)
+    return;
 
-	if (app->d_in_place_editing)
-        enableEditor();
-    else
-        showDialog();
+  if (app->d_in_place_editing)
+    enableEditor();
+  else
+    showDialog();
 }
 
-void LegendWidget::clone(LegendWidget* t)
-{
-	d_frame = t->frameStyle();
-	d_angle = t->angle();
+void LegendWidget::clone(LegendWidget *t) {
+  d_frame = t->frameStyle();
+  d_angle = t->angle();
 
-	setTextColor(t->textColor());
-	setBackgroundColor(t->backgroundColor());
-	setFont(t->font());
-	setText(t->text());
-	move(t->pos());
+  setTextColor(t->textColor());
+  setBackgroundColor(t->backgroundColor());
+  setFont(t->font());
+  setText(t->text());
+  move(t->pos());
 }
 
-void LegendWidget::setFixedCoordinatesMode(bool on)
-{
-	if (d_fixed_coordinates == on)
-		return;
+void LegendWidget::setFixedCoordinatesMode(bool on) {
+  if (d_fixed_coordinates == on)
+    return;
 
-	d_fixed_coordinates = on;
+  d_fixed_coordinates = on;
 
-	if(on){
-		d_x = xValue();
-		d_y = yValue();
-	}
+  if (on) {
+    d_x = xValue();
+    d_y = yValue();
+  }
 }
 
-LegendWidget::~LegendWidget()
-{
-	delete d_text;
-	if (d_selector)
-        delete d_selector;
+LegendWidget::~LegendWidget() {
+  delete d_text;
+  if (d_selector)
+    delete d_selector;
 }
diff --git a/MantidPlot/src/LegendWidget.h b/MantidPlot/src/LegendWidget.h
index 9cc10cd327d66dfcc3fdcede63f684c649a0f5cc..1b0fcd8d33a3bb6c1c59c6a5f117a588884087b7 100644
--- a/MantidPlot/src/LegendWidget.h
+++ b/MantidPlot/src/LegendWidget.h
@@ -36,102 +36,100 @@
 #include "Graph.h"
 #include "Plot.h"
 
-class LegendWidget: public QWidget
-{
-	Q_OBJECT
+class LegendWidget : public QWidget {
+  Q_OBJECT
 
 public:
   explicit LegendWidget(Plot *);
   ~LegendWidget() override;
 
-        void clone(LegendWidget* t);
-	QwtPlot *plot(){return d_plot;};
+  void clone(LegendWidget *t);
+  QwtPlot *plot() { return d_plot; };
 
-	//! The kinds of frame a LegendWidget can draw around the Text.
-	enum FrameStyle{None = 0, Line = 1, Shadow = 2};
+  //! The kinds of frame a LegendWidget can draw around the Text.
+  enum FrameStyle { None = 0, Line = 1, Shadow = 2 };
 
-	QString text(){return d_text->text();};
-	void setText(const QString& s);
+  QString text() { return d_text->text(); };
+  void setText(const QString &s);
 
-	//! Sets the position of the top left corner in axis coordinates
-	void setOriginCoord(double x, double y);
-	//! Sets the position of the top left corner in paint coordinates
-	void setOrigin(int x, int y){move(x, y);};
+  //! Sets the position of the top left corner in axis coordinates
+  void setOriginCoord(double x, double y);
+  //! Sets the position of the top left corner in paint coordinates
+  void setOrigin(int x, int y) { move(x, y); };
 
-	QColor textColor(){return d_text->color();};
-	void setTextColor(const QColor& c);
+  QColor textColor() { return d_text->color(); };
+  void setTextColor(const QColor &c);
 
-	QColor backgroundColor(){return d_text->backgroundBrush().color();};
-	void setBackgroundColor(const QColor& c);
+  QColor backgroundColor() { return d_text->backgroundBrush().color(); };
+  void setBackgroundColor(const QColor &c);
 
-	int frameStyle(){return d_frame;};
-	void setFrameStyle(int style);
+  int frameStyle() { return d_frame; };
+  void setFrameStyle(int style);
 
-	QFont font(){return d_text->font();};
-	void setFont(const QFont& font);
+  QFont font() { return d_text->font(); };
+  void setFont(const QFont &font);
 
-	int angle(){return d_angle;};
-	void setAngle(int ang){d_angle = ang;};
+  int angle() { return d_angle; };
+  void setAngle(int ang) { d_angle = ang; };
 
-	double xValue();
-	double yValue();
+  double xValue();
+  double yValue();
 
-	void setSelected(bool on = true);
+  void setSelected(bool on = true);
 
-	void showTextEditor();
-	void showTextDialog(){emit showDialog();};
-	void showContextMenu(){emit showMenu();};
+  void showTextEditor();
+  void showTextDialog() { emit showDialog(); };
+  void showContextMenu() { emit showMenu(); };
 
   void print(QPainter *p, const QwtScaleMap map[QwtPlot::axisCnt]);
-	void setFixedCoordinatesMode(bool on = true);
-	
+  void setFixedCoordinatesMode(bool on = true);
+
 private:
-	PlotCurve* getCurve(const QString& s, int &point);
-	void drawFrame(QPainter *p, const QRect& rect);
-	void drawVector(PlotCurve *c, QPainter *p, int x, int y, int l);
-	void drawSymbol(PlotCurve *c, int point, QPainter *p, int x, int y, int l);
-	void drawText(QPainter *, const QRect&, QwtArray<int>, int);
+  PlotCurve *getCurve(const QString &s, int &point);
+  void drawFrame(QPainter *p, const QRect &rect);
+  void drawVector(PlotCurve *c, QPainter *p, int x, int y, int l);
+  void drawSymbol(PlotCurve *c, int point, QPainter *p, int x, int y, int l);
+  void drawText(QPainter *, const QRect &, QwtArray<int>, int);
+
+  QwtArray<int> itemsHeight(int y, int symbolLineLength, int &width,
+                            int &height);
+  int symbolsMaxWidth();
+  QString parse(const QString &str);
 
-	QwtArray<int> itemsHeight(int y, int symbolLineLength, int &width, int &height);
-	int symbolsMaxWidth();
-	QString parse(const QString& str);
+  void paintEvent(QPaintEvent *e) override;
+  void mousePressEvent(QMouseEvent *e) override;
+  void contextMenuEvent(QContextMenuEvent *) override { emit showMenu(); };
 
-        void paintEvent(QPaintEvent *e) override;
-        void mousePressEvent(QMouseEvent *e) override;
-        void contextMenuEvent(QContextMenuEvent *) override {
-          emit showMenu();
-        };
+  //! Parent plot
+  Plot *d_plot;
 
-        //! Parent plot
-	Plot *d_plot;
+  //! Frame type
+  int d_frame;
 
-	//! Frame type
-	int d_frame;
+  //! Rotation angle: not implemented yet
+  int d_angle;
 
-	//! Rotation angle: not implemented yet
-	int d_angle;
+  //! Pointer to the QwtText object
+  QwtText *d_text;
 
-	//! Pointer to the QwtText object
-	QwtText* d_text;
+  //! Distance between symbols and legend text
+  int h_space;
 
-	//! Distance between symbols and legend text
-	int h_space;
+  //! Distance between frame and content
+  int left_margin, top_margin;
 
-	//! Distance between frame and content
-	int left_margin, top_margin;
+  //! Length of the symbol line
+  int line_length;
 
-	//! Length of the symbol line
-	int line_length;
+  SelectionMoveResizer *d_selector;
 
-	SelectionMoveResizer *d_selector;
-	
-	double d_x, d_y;
-	bool d_fixed_coordinates;
+  double d_x, d_y;
+  bool d_fixed_coordinates;
 
 signals:
-	void showDialog();
-	void showMenu();
-	void enableEditor();
+  void showDialog();
+  void showMenu();
+  void enableEditor();
 };
 
 #endif
diff --git a/MantidPlot/src/LineDialog.h b/MantidPlot/src/LineDialog.h
index a46ef2a367b04ee342baec4488ce9f3d41d24d3d..9b2f3aee55667d6aa7d7a2c4560aaa0dd1391496 100644
--- a/MantidPlot/src/LineDialog.h
+++ b/MantidPlot/src/LineDialog.h
@@ -43,44 +43,43 @@ class ArrowMarker;
 class DoubleSpinBox;
 
 //! Line options dialog
-class LineDialog : public QDialog
-{
-    Q_OBJECT
+class LineDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    LineDialog(ArrowMarker *line, QWidget* parent = 0, Qt::WFlags fl = 0);
+  LineDialog(ArrowMarker *line, QWidget *parent = 0, Qt::WFlags fl = 0);
 
-    enum Unit{ScaleCoordinates, Pixels};
+  enum Unit { ScaleCoordinates, Pixels };
 
-	void initGeometryTab();
-	void enableHeadTab();
-	void setCoordinates(int unit);
+  void initGeometryTab();
+  void enableHeadTab();
+  void setCoordinates(int unit);
 
 public slots:
-	void enableButtonDefault(QWidget *w);
-	void setDefaultValues();
-	void displayCoordinates(int unit);
-	void setLineStyle(Qt::PenStyle style);
-        void accept() override;
-        void apply();
+  void enableButtonDefault(QWidget *w);
+  void setDefaultValues();
+  void displayCoordinates(int unit);
+  void setLineStyle(Qt::PenStyle style);
+  void accept() override;
+  void apply();
 
 private:
-	ArrowMarker *lm;
+  ArrowMarker *lm;
 
-    ColorButton* colorBox;
-    QComboBox* styleBox;
-    DoubleSpinBox* widthBox;
-	QComboBox* unitBox;
-    QPushButton* btnOk;
-    QPushButton* btnApply;
-	QPushButton* buttonDefault;
-    QCheckBox* endBox;
-    QCheckBox* startBox,  *filledBox;
-	QTabWidget* tw;
-	QWidget *options, *geometry, *head;
-	DoubleSpinBox *xStartBox, *yStartBox, *xEndBox, *yEndBox;
-	QSpinBox *xStartPixelBox, *yStartPixelBox, *xEndPixelBox, *yEndPixelBox;
-	QSpinBox *boxHeadAngle, *boxHeadLength;
+  ColorButton *colorBox;
+  QComboBox *styleBox;
+  DoubleSpinBox *widthBox;
+  QComboBox *unitBox;
+  QPushButton *btnOk;
+  QPushButton *btnApply;
+  QPushButton *buttonDefault;
+  QCheckBox *endBox;
+  QCheckBox *startBox, *filledBox;
+  QTabWidget *tw;
+  QWidget *options, *geometry, *head;
+  DoubleSpinBox *xStartBox, *yStartBox, *xEndBox, *yEndBox;
+  QSpinBox *xStartPixelBox, *yStartPixelBox, *xEndPixelBox, *yEndPixelBox;
+  QSpinBox *boxHeadAngle, *boxHeadLength;
 };
 
 #endif // LINEDIALOG_H
diff --git a/MantidPlot/src/LineProfileTool.h b/MantidPlot/src/LineProfileTool.h
index c7b83ca5d21277871f5a6961d36e27d9da0587ae..ee99e3e551b97e4962c4185943153a379abb7c0e 100644
--- a/MantidPlot/src/LineProfileTool.h
+++ b/MantidPlot/src/LineProfileTool.h
@@ -39,75 +39,87 @@ class QImage;
 class ImageMarker;
 class ApplicationWindow;
 
-/**\brief Plot tool for calculating intensity profiles of image markers along a line.
+/**\brief Plot tool for calculating intensity profiles of image markers along a
+ *line.
  *
- * It is assumed that on the parent Graph an ImageMarker is selected. During initialization,
- * a pointer to this marker is stored and the selection is removed. The LineProfileTool
- * adds itself as a full-sized child widget to the Graph's canvas, allowing for fast redraws
- * while selection of the line is in progress. Once the line is selected (mouse button is
- * released), the profile is calculate and displayed, a new LineMarker denoting the selected
- * profile line is added to the Graph and the LineProfileTool deletes itself by setting the
+ * It is assumed that on the parent Graph an ImageMarker is selected. During
+ *initialization,
+ * a pointer to this marker is stored and the selection is removed. The
+ *LineProfileTool
+ * adds itself as a full-sized child widget to the Graph's canvas, allowing for
+ *fast redraws
+ * while selection of the line is in progress. Once the line is selected (mouse
+ *button is
+ * released), the profile is calculate and displayed, a new LineMarker denoting
+ *the selected
+ * profile line is added to the Graph and the LineProfileTool deletes itself by
+ *setting the
  * Graph's active tool to NULL.
  *
  * \section future Future Plans
  * Actually, image analysis doesn't fit terribly well into the Graph framework.
- * A cleaner approach would be to add a new MyWidget subclass (Image?) that operates on a single
- * image, providing things like line profiles, intensity tables and measuring points on scanned graphs
- * (simple <a href="http://www.frantz.fi/software/g3data.php">g3data</a>-like functionality).
- * There could be facilities for making an Image from an ImageMarker and vice versa
+ * A cleaner approach would be to add a new MyWidget subclass (Image?) that
+ *operates on a single
+ * image, providing things like line profiles, intensity tables and measuring
+ *points on scanned graphs
+ * (simple <a href="http://www.frantz.fi/software/g3data.php">g3data</a>-like
+ *functionality).
+ * There could be facilities for making an Image from an ImageMarker and vice
+ *versa
  * (if that's really needed).
  * [ postponed until after the redesign of project handling ]
  */
-class LineProfileTool : public QWidget, public PlotToolInterface
-{
-	Q_OBJECT
+class LineProfileTool : public QWidget, public PlotToolInterface {
+  Q_OBJECT
 
-	public:
-		//! Standard constructor.
-		LineProfileTool(Graph *graph, ApplicationWindow *app, int average_pixels);
-		void calculateLineProfile(const QPoint &start, const QPoint &end);
+public:
+  //! Standard constructor.
+  LineProfileTool(Graph *graph, ApplicationWindow *app, int average_pixels);
+  void calculateLineProfile(const QPoint &start, const QPoint &end);
 
-                int rtti() const override {
-                  return PlotToolInterface::Rtti_LineProfileTool;
-                };
+  int rtti() const override { return PlotToolInterface::Rtti_LineProfileTool; };
 
-        signals:
-		/** Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
+signals:
+  /** Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
 
-	protected:
-		int averageImagePixel(const QImage &image, int px, int py, bool moreHorizontal);
-		void addLineMarker(const QPoint &start, const QPoint &end);
-		/**\brief Draw line during operation (replaced by a LineMarker at the end).
-		 */
-                void paintEvent(QPaintEvent *e) override;
-                /**\brief Pressing the left mouse button starts line selection.
-		 *
-		 * Clicks with anything else than the left button are propagated to the parent as usual.
-		 */
-                void mousePressEvent(QMouseEvent *e) override;
-                /**\brief Mouse movements need to be monitored for updating the line during operation.
-		 */
-                void mouseMoveEvent(QMouseEvent *e) override;
-                /**\brief Mouse releases end line selection and cause the profile to be displayed.
-		 */
-                void mouseReleaseEvent(QMouseEvent *e) override;
+protected:
+  int averageImagePixel(const QImage &image, int px, int py,
+                        bool moreHorizontal);
+  void addLineMarker(const QPoint &start, const QPoint &end);
+  /**\brief Draw line during operation (replaced by a LineMarker at the end).
+   */
+  void paintEvent(QPaintEvent *e) override;
+  /**\brief Pressing the left mouse button starts line selection.
+   *
+   * Clicks with anything else than the left button are propagated to the parent
+   *as usual.
+   */
+  void mousePressEvent(QMouseEvent *e) override;
+  /**\brief Mouse movements need to be monitored for updating the line during
+   * operation.
+   */
+  void mouseMoveEvent(QMouseEvent *e) override;
+  /**\brief Mouse releases end line selection and cause the profile to be
+   * displayed.
+   */
+  void mouseReleaseEvent(QMouseEvent *e) override;
 
-        private:
-        ApplicationWindow *d_app;
-		//! Number of image pixels over which to average.
-		int d_average_pixels;
-		//! The image marker to operate on.
-		ImageMarker *d_target;
-		/**\brief Mouse position where an operation started.
-		 */
-		QPoint d_op_start;
-		//! Difference between current and start position during operation.
-		QPoint d_op_dp;
+private:
+  ApplicationWindow *d_app;
+  //! Number of image pixels over which to average.
+  int d_average_pixels;
+  //! The image marker to operate on.
+  ImageMarker *d_target;
+  /**\brief Mouse position where an operation started.
+   */
+  QPoint d_op_start;
+  //! Difference between current and start position during operation.
+  QPoint d_op_dp;
 };
 
 #endif // ifndef LINE_PROFILE_TOOL_H
-
diff --git a/MantidPlot/src/LogisticFit.cpp b/MantidPlot/src/LogisticFit.cpp
index f5c1834ff32d543199ee5e3d224799e888c93b55..5e8c28685cb4dc7ddb3c404d87200e17964932ff 100644
--- a/MantidPlot/src/LogisticFit.cpp
+++ b/MantidPlot/src/LogisticFit.cpp
@@ -29,82 +29,82 @@
 #include "LogisticFit.h"
 #include "fit_gsl.h"
 
-LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g) : Fit(parent, g) {
+  init();
 }
 
-LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+LogisticFit::LogisticFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-LogisticFit::LogisticFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+LogisticFit::LogisticFit(ApplicationWindow *parent, Table *t,
+                         const QString &xCol, const QString &yCol, int startRow,
+                         int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void LogisticFit::init()
-{
-	setObjectName(tr("Logistic"));
-    d_f = logistic_f;
-    d_df = logistic_df;
-	d_fdf = logistic_fdf;
-	d_fsimplex = logistic_d;
-	d_param_explain << tr("init value") << tr("final value") << tr("center") << tr("power");
-	d_param_names << "A1" << "A2" << "x0" << "p";
-	d_explanation = tr("Logistic Fit");
-	d_formula = "A2+(A1-A2)/(1+(x/x0)^p))";
-	d_p = 4;    
-	initWorkspace(d_p);
+void LogisticFit::init() {
+  setObjectName(tr("Logistic"));
+  d_f = logistic_f;
+  d_df = logistic_df;
+  d_fdf = logistic_fdf;
+  d_fsimplex = logistic_d;
+  d_param_explain << tr("init value") << tr("final value") << tr("center")
+                  << tr("power");
+  d_param_names << "A1"
+                << "A2"
+                << "x0"
+                << "p";
+  d_explanation = tr("Logistic Fit");
+  d_formula = "A2+(A1-A2)/(1+(x/x0)^p))";
+  d_p = 4;
+  initWorkspace(d_p);
 }
 
-void LogisticFit::calculateFitCurveData(double *X, double *Y)
-{
-	double a1 = d_results[0];
-	double a2 = d_results[1];
-	double x0 = d_results[2];
-	double p = d_results[3];
+void LogisticFit::calculateFitCurveData(double *X, double *Y) {
+  double a1 = d_results[0];
+  double a2 = d_results[1];
+  double x0 = d_results[2];
+  double p = d_results[3];
 
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-        for (int i=0; i<d_points; i++){
-			double x = X0+i*step;
-        	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + pow(x/x0, p)) + a2;
-		} 
-	} else {
-      	for (int i=0; i<d_points; i++){
-			double x = d_x[i];
-        	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + pow(x/x0, p)) + a2;
-		}
-	}
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = (a1 - a2) / (1 + pow(x / x0, p)) + a2;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = (a1 - a2) / (1 + pow(x / x0, p)) + a2;
+    }
+  }
 }
 
-void LogisticFit::guessInitialValues()
-{
-	gsl_vector_view x = gsl_vector_view_array (d_x, d_n);
-	gsl_vector_view y = gsl_vector_view_array (d_y, d_n);
+void LogisticFit::guessInitialValues() {
+  gsl_vector_view x = gsl_vector_view_array(d_x, d_n);
+  gsl_vector_view y = gsl_vector_view_array(d_y, d_n);
 
-	double min_out, max_out;
-	gsl_vector_minmax (&y.vector, &min_out, &max_out);
+  double min_out, max_out;
+  gsl_vector_minmax(&y.vector, &min_out, &max_out);
 
-	gsl_vector_set(d_param_init, 0, min_out);
-	gsl_vector_set(d_param_init, 1, max_out);
-	gsl_vector_set(d_param_init, 2, gsl_vector_get (&x.vector, d_n/2));
-	gsl_vector_set(d_param_init, 3, 1.0);
+  gsl_vector_set(d_param_init, 0, min_out);
+  gsl_vector_set(d_param_init, 1, max_out);
+  gsl_vector_set(d_param_init, 2, gsl_vector_get(&x.vector, d_n / 2));
+  gsl_vector_set(d_param_init, 3, 1.0);
 }
diff --git a/MantidPlot/src/LogisticFit.h b/MantidPlot/src/LogisticFit.h
index c49cc8e95c38de62a31c7ada64cfdb7230f9ab09..b9bcfb2c938bfcd5cfa5f49b669bc2d542641485 100644
--- a/MantidPlot/src/LogisticFit.h
+++ b/MantidPlot/src/LogisticFit.h
@@ -31,25 +31,25 @@
 
 #include "Fit.h"
 
-class LogisticFit : public Fit
-{
-	Q_OBJECT
-
-	public:
-		LogisticFit(ApplicationWindow *parent, Graph *g);
-		LogisticFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		LogisticFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		LogisticFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
-
-                void guessInitialValues() override;
-                double eval(double *par, double x) override {
-                  return (par[0] - par[1]) / (1 + pow(x / par[2], par[3])) +
-                         par[1];
-                };
-
-        private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+class LogisticFit : public Fit {
+  Q_OBJECT
+
+public:
+  LogisticFit(ApplicationWindow *parent, Graph *g);
+  LogisticFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  LogisticFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+              double start, double end);
+  LogisticFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+              const QString &yCol, int startRow = 1, int endRow = -1);
+
+  void guessInitialValues() override;
+  double eval(double *par, double x) override {
+    return (par[0] - par[1]) / (1 + pow(x / par[2], par[3])) + par[1];
+  };
+
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 
 #endif
diff --git a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
index 52823f85ec466f9708a64bc3137e03dde7344b77..9a6e2d62294c260ec41c6e6fda73bcedecd2dfb0 100644
--- a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
+++ b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
@@ -25,195 +25,219 @@
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace
-{
-  /// static history window logger
-  Mantid::Kernel::Logger window_log("AlgorithmHistoryWindow");
-  /// static tree widget logger
-  Mantid::Kernel::Logger widget_log("AlgHistoryTreeWidget");
+namespace {
+/// static history window logger
+Mantid::Kernel::Logger window_log("AlgorithmHistoryWindow");
+/// static tree widget logger
+Mantid::Kernel::Logger widget_log("AlgHistoryTreeWidget");
 }
 
-AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QWidget *w) : QGroupBox(w),
-  m_execDurationlabel(NULL),m_execDurationEdit(NULL),
-  m_Datelabel(NULL),m_execDateTimeEdit(NULL), m_algexecDuration()
-{
-}
+AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QWidget *w)
+    : QGroupBox(w), m_execDurationlabel(NULL), m_execDurationEdit(NULL),
+      m_Datelabel(NULL), m_execDateTimeEdit(NULL), m_algexecDuration() {}
 
-AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QString title,QWidget*w)
-  : QGroupBox(title,w), m_execDurationlabel(NULL),m_execDurationEdit(NULL),
-    m_Datelabel(NULL),m_execDateTimeEdit(NULL), m_algexecDuration()
-{
+AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QString title, QWidget *w)
+    : QGroupBox(title, w), m_execDurationlabel(NULL), m_execDurationEdit(NULL),
+      m_Datelabel(NULL), m_execDateTimeEdit(NULL), m_algexecDuration() {
 
-  m_execDurationEdit=new QLineEdit("",this);
-  if(m_execDurationEdit)
+  m_execDurationEdit = new QLineEdit("", this);
+  if (m_execDurationEdit)
     m_execDurationEdit->setReadOnly(1);
   m_execDurationlabel = new QLabel("Duration:", this);
-  if(m_execDurationlabel)m_execDurationlabel->setBuddy(m_execDurationEdit);
+  if (m_execDurationlabel)
+    m_execDurationlabel->setBuddy(m_execDurationEdit);
 
-  QDateTime datetime(QDate(0,0,0), QTime(0,0,0),Qt::LocalTime );
-  m_execDateTimeEdit=new QLineEdit("",this);
-  if(m_execDateTimeEdit)
+  QDateTime datetime(QDate(0, 0, 0), QTime(0, 0, 0), Qt::LocalTime);
+  m_execDateTimeEdit = new QLineEdit("", this);
+  if (m_execDateTimeEdit)
     m_execDateTimeEdit->setReadOnly(1);
   m_Datelabel = new QLabel("Date:", this);
-  if(m_Datelabel)m_Datelabel->setBuddy(m_execDateTimeEdit);
-		
+  if (m_Datelabel)
+    m_Datelabel->setBuddy(m_execDateTimeEdit);
+
   QFormLayout *formLayout = new QFormLayout;
-  if(formLayout){
-    formLayout->addRow(m_execDurationlabel,m_execDurationEdit);
-    formLayout->addRow(m_Datelabel,m_execDateTimeEdit);
+  if (formLayout) {
+    formLayout->addRow(m_execDurationlabel, m_execDurationEdit);
+    formLayout->addRow(m_Datelabel, m_execDateTimeEdit);
     setLayout(formLayout);
   }
-  setGeometry (5,210,205,130);
-
+  setGeometry(5, 210, 205, 130);
 }
-AlgExecSummaryGrpBox::~AlgExecSummaryGrpBox()
-{
-  if(m_execDurationlabel){
+AlgExecSummaryGrpBox::~AlgExecSummaryGrpBox() {
+  if (m_execDurationlabel) {
     delete m_execDurationlabel;
-    m_execDurationlabel=NULL;
+    m_execDurationlabel = NULL;
   }
-  if(m_execDurationEdit){
+  if (m_execDurationEdit) {
     delete m_execDurationEdit;
-    m_execDurationEdit=NULL;
+    m_execDurationEdit = NULL;
   }
-  if(m_Datelabel){
+  if (m_Datelabel) {
     delete m_Datelabel;
-    m_Datelabel=NULL;
+    m_Datelabel = NULL;
   }
-  if(m_Datelabel){
+  if (m_Datelabel) {
     delete m_Datelabel;
-    m_Datelabel=NULL;
+    m_Datelabel = NULL;
   }
-  if(m_execDateTimeEdit){
+  if (m_execDateTimeEdit) {
     delete m_execDateTimeEdit;
-    m_execDateTimeEdit=NULL;
+    m_execDateTimeEdit = NULL;
   }
 }
-void AlgExecSummaryGrpBox::setData(const double execDuration,const Mantid::Kernel::DateAndTime execDate)
-{
+void AlgExecSummaryGrpBox::setData(const double execDuration,
+                                   const Mantid::Kernel::DateAndTime execDate) {
   QString dur("");
-  dur.setNum(execDuration,'g',6);
-  dur+=" seconds";
-  QLineEdit* execDurationEdit=getAlgExecDurationCtrl();
-  if(execDurationEdit)execDurationEdit->setText(dur);
-	
-  //Get the timeinfo structure, but converting from UTC to local time
-  std::tm t = execDate.to_localtime_tm() ;
-  QTime qt(t.tm_hour,t.tm_min,t.tm_sec);
-  QDate qd(t.tm_year+1900,t.tm_mon+1,t.tm_mday);
-  QDateTime datetime(qd,qt,Qt::LocalTime );
-	
+  dur.setNum(execDuration, 'g', 6);
+  dur += " seconds";
+  QLineEdit *execDurationEdit = getAlgExecDurationCtrl();
+  if (execDurationEdit)
+    execDurationEdit->setText(dur);
+
+  // Get the timeinfo structure, but converting from UTC to local time
+  std::tm t = execDate.to_localtime_tm();
+  QTime qt(t.tm_hour, t.tm_min, t.tm_sec);
+  QDate qd(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday);
+  QDateTime datetime(qd, qt, Qt::LocalTime);
+
   QString str("");
-  str=datetime.toString("dd/MM/yyyy hh:mm:ss");
-	
-  QLineEdit* datetimeEdit=getAlgExecDateCtrl();
-  if(datetimeEdit)datetimeEdit->setText(str);
+  str = datetime.toString("dd/MM/yyyy hh:mm:ss");
 
+  QLineEdit *datetimeEdit = getAlgExecDateCtrl();
+  if (datetimeEdit)
+    datetimeEdit->setText(str);
 }
 
-AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QWidget *w) : QGroupBox(w),
-  m_osNameLabel(NULL),m_osNameEdit(NULL),m_osVersionLabel(NULL),m_osVersionEdit(NULL),
-  m_frmworkVersionLabel(NULL),m_frmwkVersnEdit(NULL)
-{
-}
+AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QWidget *w)
+    : QGroupBox(w), m_osNameLabel(NULL), m_osNameEdit(NULL),
+      m_osVersionLabel(NULL), m_osVersionEdit(NULL),
+      m_frmworkVersionLabel(NULL), m_frmwkVersnEdit(NULL) {}
 
-AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QString title,QWidget*w):QGroupBox(title,w),
-								  m_osNameLabel(NULL),m_osNameEdit(NULL),m_osVersionLabel(NULL),m_osVersionEdit(NULL),
-								  m_frmworkVersionLabel(NULL),m_frmwkVersnEdit(NULL)
-{
-  //OS Name Label & Edit Box
-  m_osNameEdit=new QLineEdit("",this);
-  if(m_osNameEdit)
-  {
+AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QString title, QWidget *w)
+    : QGroupBox(title, w), m_osNameLabel(NULL), m_osNameEdit(NULL),
+      m_osVersionLabel(NULL), m_osVersionEdit(NULL),
+      m_frmworkVersionLabel(NULL), m_frmwkVersnEdit(NULL) {
+  // OS Name Label & Edit Box
+  m_osNameEdit = new QLineEdit("", this);
+  if (m_osNameEdit) {
     m_osNameEdit->setReadOnly(1);
   }
   m_osNameLabel = new QLabel("OS Name:", this);
-  if(m_osNameLabel)m_osNameLabel->setBuddy(m_osNameEdit);
+  if (m_osNameLabel)
+    m_osNameLabel->setBuddy(m_osNameEdit);
 
-  //OS Version Label & Edit Box
-  m_osVersionEdit=new QLineEdit("",this);
-  if(m_osVersionEdit)
-  {
+  // OS Version Label & Edit Box
+  m_osVersionEdit = new QLineEdit("", this);
+  if (m_osVersionEdit) {
     m_osVersionEdit->setReadOnly(1);
     m_osVersionLabel = new QLabel("OS Version:", this);
   }
-  if(m_osVersionLabel)
+  if (m_osVersionLabel)
     m_osVersionLabel->setBuddy(m_osVersionEdit);
 
-  //Mantid Framework Version Label & Edit Box
-  m_frmwkVersnEdit=new QLineEdit("",this);
-  if(m_frmwkVersnEdit)
+  // Mantid Framework Version Label & Edit Box
+  m_frmwkVersnEdit = new QLineEdit("", this);
+  if (m_frmwkVersnEdit)
     m_frmwkVersnEdit->setReadOnly(1);
   m_frmworkVersionLabel = new QLabel("Framework Version:", this);
-  if(m_frmworkVersionLabel)
+  if (m_frmworkVersionLabel)
     m_frmworkVersionLabel->setBuddy(m_frmwkVersnEdit);
-	
-  QFormLayout * formLayout=new QFormLayout();
-  if(formLayout)
-  {
-    formLayout->addRow(m_osNameLabel,m_osNameEdit);
-    formLayout->addRow(m_osVersionLabel,m_osVersionEdit);
-    formLayout->addRow(m_frmworkVersionLabel,m_frmwkVersnEdit);
+
+  QFormLayout *formLayout = new QFormLayout();
+  if (formLayout) {
+    formLayout->addRow(m_osNameLabel, m_osNameEdit);
+    formLayout->addRow(m_osVersionLabel, m_osVersionEdit);
+    formLayout->addRow(m_frmworkVersionLabel, m_frmwkVersnEdit);
     setLayout(formLayout);
   }
-  setGeometry (214,210,347,130);
+  setGeometry(214, 210, 347, 130);
 }
-AlgEnvHistoryGrpBox::~AlgEnvHistoryGrpBox()
-{
-  if(m_osNameLabel){delete m_osNameLabel;m_osNameLabel=NULL;}
-  if(m_osNameEdit){delete m_osNameEdit;m_osNameEdit=NULL;}
-  if(m_osNameEdit){delete m_osNameEdit;m_osNameEdit=NULL;}
-  if(m_osVersionLabel){delete m_osVersionLabel;m_osVersionLabel=NULL;}
-  if(m_osVersionEdit){delete m_osVersionEdit;m_osVersionEdit=NULL;}
-  if(m_frmworkVersionLabel){delete m_frmworkVersionLabel;m_frmworkVersionLabel=NULL;}
-  if(m_frmwkVersnEdit){ delete m_frmwkVersnEdit;m_frmwkVersnEdit=NULL;}
+AlgEnvHistoryGrpBox::~AlgEnvHistoryGrpBox() {
+  if (m_osNameLabel) {
+    delete m_osNameLabel;
+    m_osNameLabel = NULL;
+  }
+  if (m_osNameEdit) {
+    delete m_osNameEdit;
+    m_osNameEdit = NULL;
+  }
+  if (m_osNameEdit) {
+    delete m_osNameEdit;
+    m_osNameEdit = NULL;
+  }
+  if (m_osVersionLabel) {
+    delete m_osVersionLabel;
+    m_osVersionLabel = NULL;
+  }
+  if (m_osVersionEdit) {
+    delete m_osVersionEdit;
+    m_osVersionEdit = NULL;
+  }
+  if (m_frmworkVersionLabel) {
+    delete m_frmworkVersionLabel;
+    m_frmworkVersionLabel = NULL;
+  }
+  if (m_frmwkVersnEdit) {
+    delete m_frmwkVersnEdit;
+    m_frmwkVersnEdit = NULL;
+  }
 }
 
-
-AlgorithmHistoryWindow::AlgorithmHistoryWindow(QWidget *parent,const boost::shared_ptr<const Workspace> wsptr):
-MantidDialog(parent),m_algHist(wsptr->getHistory()),m_histPropWindow(NULL),m_execSumGrpBox(NULL),m_envHistGrpBox(NULL),
-m_wsName(wsptr->getName().c_str()), m_view(wsptr->getHistory().createView())
-{
+AlgorithmHistoryWindow::AlgorithmHistoryWindow(
+    QWidget *parent, const boost::shared_ptr<const Workspace> wsptr)
+    : MantidDialog(parent), m_algHist(wsptr->getHistory()),
+      m_histPropWindow(NULL), m_execSumGrpBox(NULL), m_envHistGrpBox(NULL),
+      m_wsName(wsptr->getName().c_str()),
+      m_view(wsptr->getHistory().createView()) {
   setWindowTitle(tr("Algorithm History"));
   setMinimumHeight(500);
   setMinimumWidth(750);
-  setGeometry(50,150,540,380); 
+  setGeometry(50, 150, 540, 380);
 
-  //Create a tree widget to display the algorithm names in the workspace history
+  // Create a tree widget to display the algorithm names in the workspace
+  // history
   m_Historytree = new AlgHistoryTreeWidget(this);
-  if(m_Historytree)
-  {
+  if (m_Historytree) {
     QStringList headers;
-    headers << "Algorithms" << "Unroll";
+    headers << "Algorithms"
+            << "Unroll";
 
     m_Historytree->setColumnCount(2);
     m_Historytree->setColumnWidth(0, 180);
     m_Historytree->setColumnWidth(1, 55);
     m_Historytree->setHeaderLabels(headers);
-    m_Historytree->setGeometry (5,5,205,200);
-    //Populate the History Tree widget
+    m_Historytree->setGeometry(5, 5, 205, 200);
+    // Populate the History Tree widget
     m_Historytree->populateAlgHistoryTreeWidget(m_algHist);
   }
 
-  //create a tree widget to display history properties
-  if(!m_histPropWindow)
-    m_histPropWindow=createAlgHistoryPropWindow();
+  // create a tree widget to display history properties
+  if (!m_histPropWindow)
+    m_histPropWindow = createAlgHistoryPropWindow();
 
-  //connect history tree with window
-  connect(m_Historytree, SIGNAL(updateAlgorithmHistoryWindow(Mantid::API::AlgorithmHistory_const_sptr)),this,
-    SLOT(updateAll(Mantid::API::AlgorithmHistory_const_sptr)));
-  connect(m_Historytree, SIGNAL(unrollAlgorithmHistory(const std::vector<int>&)), this, SLOT(doUnroll(const std::vector<int>&)));
-  connect(m_Historytree, SIGNAL(rollAlgorithmHistory(int)), this, SLOT(doRoll(int)));
+  // connect history tree with window
+  connect(m_Historytree, SIGNAL(updateAlgorithmHistoryWindow(
+                             Mantid::API::AlgorithmHistory_const_sptr)),
+          this, SLOT(updateAll(Mantid::API::AlgorithmHistory_const_sptr)));
+  connect(m_Historytree,
+          SIGNAL(unrollAlgorithmHistory(const std::vector<int> &)), this,
+          SLOT(doUnroll(const std::vector<int> &)));
+  connect(m_Historytree, SIGNAL(rollAlgorithmHistory(int)), this,
+          SLOT(doRoll(int)));
 
   // The tree and the history details layout
   QHBoxLayout *treeLayout = new QHBoxLayout;
-  treeLayout->addWidget(m_Historytree,3); // History stretches 1
-  treeLayout->addWidget(m_histPropWindow->m_histpropTree,5); // Properties gets more space
-
-  //Create a GroupBox to display exec date,duration
-  if(!m_execSumGrpBox)m_execSumGrpBox=createExecSummaryGrpBox();
-  //Create a Groupbox to display environment details
-  if(!m_envHistGrpBox)m_envHistGrpBox=createEnvHistGrpBox(wsptr->getHistory().getEnvironmentHistory());
+  treeLayout->addWidget(m_Historytree, 3); // History stretches 1
+  treeLayout->addWidget(m_histPropWindow->m_histpropTree,
+                        5); // Properties gets more space
+
+  // Create a GroupBox to display exec date,duration
+  if (!m_execSumGrpBox)
+    m_execSumGrpBox = createExecSummaryGrpBox();
+  // Create a Groupbox to display environment details
+  if (!m_envHistGrpBox)
+    m_envHistGrpBox =
+        createEnvHistGrpBox(wsptr->getHistory().getEnvironmentHistory());
 
   QHBoxLayout *environmentLayout = new QHBoxLayout;
   environmentLayout->addWidget(m_execSumGrpBox, 1);
@@ -222,16 +246,20 @@ m_wsName(wsptr->getName().c_str()), m_view(wsptr->getHistory().createView())
   // The buttons at the bottom
   m_scriptVersionLabel = new QLabel("Algorithm Versions:", this);
   m_scriptComboMode = new QComboBox(this);
-  // N.B. The combobox item strings below are used in AlgorithmHistoryWindow::getScriptVersionMode()
+  // N.B. The combobox item strings below are used in
+  // AlgorithmHistoryWindow::getScriptVersionMode()
   // If you change them here, you MUST change them there too.
   m_scriptComboMode->addItem("Only Specify Old Versions");
   m_scriptComboMode->addItem("Never Specify Versions");
   m_scriptComboMode->addItem("Always Specify Versions");
-  m_scriptComboMode->setToolTip("When to specify which version of an algorithm was used.");
-  m_scriptButtonFile = new QPushButton("Script to File",this);
-  m_scriptButtonClipboard = new QPushButton("Script to Clipboard",this);
-  connect(m_scriptButtonFile,SIGNAL(clicked()), this, SLOT(writeToScriptFile()));
-  connect(m_scriptButtonClipboard,SIGNAL(clicked()), this, SLOT(copytoClipboard()));
+  m_scriptComboMode->setToolTip(
+      "When to specify which version of an algorithm was used.");
+  m_scriptButtonFile = new QPushButton("Script to File", this);
+  m_scriptButtonClipboard = new QPushButton("Script to Clipboard", this);
+  connect(m_scriptButtonFile, SIGNAL(clicked()), this,
+          SLOT(writeToScriptFile()));
+  connect(m_scriptButtonClipboard, SIGNAL(clicked()), this,
+          SLOT(copytoClipboard()));
 
   QHBoxLayout *buttonLayout = new QHBoxLayout;
   buttonLayout->addStretch(1); // Align the button to the right
@@ -240,170 +268,178 @@ m_wsName(wsptr->getName().c_str()), m_view(wsptr->getHistory().createView())
   buttonLayout->addWidget(m_scriptButtonFile);
   buttonLayout->addWidget(m_scriptButtonClipboard);
 
-  //Main layout
+  // Main layout
   QVBoxLayout *mainLayout = new QVBoxLayout(this);
   mainLayout->addLayout(treeLayout);
   mainLayout->addLayout(environmentLayout);
   mainLayout->addLayout(buttonLayout);
 }
 
-AlgorithmHistoryWindow::~AlgorithmHistoryWindow()
-{	
-  if(m_Historytree){delete m_Historytree;m_Historytree=NULL;}
-  if(m_histPropWindow){ delete m_histPropWindow;m_histPropWindow=NULL;}
-  if(m_execSumGrpBox){delete m_execSumGrpBox;m_execSumGrpBox=NULL;}
-  if(m_envHistGrpBox){delete m_envHistGrpBox;m_envHistGrpBox=NULL;}
+AlgorithmHistoryWindow::~AlgorithmHistoryWindow() {
+  if (m_Historytree) {
+    delete m_Historytree;
+    m_Historytree = NULL;
+  }
+  if (m_histPropWindow) {
+    delete m_histPropWindow;
+    m_histPropWindow = NULL;
+  }
+  if (m_execSumGrpBox) {
+    delete m_execSumGrpBox;
+    m_execSumGrpBox = NULL;
+  }
+  if (m_envHistGrpBox) {
+    delete m_envHistGrpBox;
+    m_envHistGrpBox = NULL;
+  }
 }
 
-AlgExecSummaryGrpBox* AlgorithmHistoryWindow::createExecSummaryGrpBox()
-{	
-  AlgExecSummaryGrpBox *pgrpBox=new AlgExecSummaryGrpBox("Execution Summary",this);
-  if(pgrpBox)
-  {
-    //iterating through algorithm history to display exec duration,date
-    //last executed algorithm exec duration,date will be displayed in gruopbox
+AlgExecSummaryGrpBox *AlgorithmHistoryWindow::createExecSummaryGrpBox() {
+  AlgExecSummaryGrpBox *pgrpBox =
+      new AlgExecSummaryGrpBox("Execution Summary", this);
+  if (pgrpBox) {
+    // iterating through algorithm history to display exec duration,date
+    // last executed algorithm exec duration,date will be displayed in gruopbox
     const size_t noEntries = m_algHist.size();
-    for( size_t i = 0; i < noEntries; ++i)
-    {
+    for (size_t i = 0; i < noEntries; ++i) {
       const auto entry = m_algHist.getAlgorithmHistory(i);
-      double duration=0;
+      double duration = 0;
       duration = entry->executionDuration();
       Mantid::Kernel::DateAndTime date = entry->executionDate();
-      pgrpBox->setData(duration,date);
+      pgrpBox->setData(duration, date);
     }
     return pgrpBox;
-  }
-  else{
-    QMessageBox::critical(this,"Mantid","Invalid Pointer");
+  } else {
+    QMessageBox::critical(this, "Mantid", "Invalid Pointer");
     return 0;
   }
-	
 }
-AlgEnvHistoryGrpBox* AlgorithmHistoryWindow::createEnvHistGrpBox(const EnvironmentHistory& envHist)
-{	
-  AlgEnvHistoryGrpBox * pEnvGrpBox=new  AlgEnvHistoryGrpBox("Environment History",this);
-  if(pEnvGrpBox){
+AlgEnvHistoryGrpBox *
+AlgorithmHistoryWindow::createEnvHistGrpBox(const EnvironmentHistory &envHist) {
+  AlgEnvHistoryGrpBox *pEnvGrpBox =
+      new AlgEnvHistoryGrpBox("Environment History", this);
+  if (pEnvGrpBox) {
     pEnvGrpBox->fillEnvHistoryGroupBox(envHist);
     return pEnvGrpBox;
-  }
-  else{
-    QMessageBox::critical(this,"Mantid","Invalid Pointer");
+  } else {
+    QMessageBox::critical(this, "Mantid", "Invalid Pointer");
     return 0;
   }
-	
 }
-AlgHistoryProperties* AlgorithmHistoryWindow::createAlgHistoryPropWindow()
-{	
+AlgHistoryProperties *AlgorithmHistoryWindow::createAlgHistoryPropWindow() {
   std::vector<PropertyHistory_sptr> histProp;
-  const Mantid::API::AlgorithmHistories & entries = m_algHist.getAlgorithmHistories();
+  const Mantid::API::AlgorithmHistories &entries =
+      m_algHist.getAlgorithmHistories();
   auto rIter = entries.rbegin();
-  histProp=(*rIter)->getProperties();
+  histProp = (*rIter)->getProperties();
 
-  //AlgHistoryProperties * phistPropWindow=new AlgHistoryProperties(this,m_algHist);
-  if(histProp.empty()){
-    QMessageBox::critical(this,"Mantid","Properties not set");
+  // AlgHistoryProperties * phistPropWindow=new
+  // AlgHistoryProperties(this,m_algHist);
+  if (histProp.empty()) {
+    QMessageBox::critical(this, "Mantid", "Properties not set");
     return 0;
   }
-  AlgHistoryProperties * phistPropWindow=new AlgHistoryProperties(this,histProp);
-  if(phistPropWindow){
+  AlgHistoryProperties *phistPropWindow =
+      new AlgHistoryProperties(this, histProp);
+  if (phistPropWindow) {
     phistPropWindow->displayAlgHistoryProperties();
     return phistPropWindow;
-  }
-  else{QMessageBox::critical(this,"Mantid","Invalid Pointer");
+  } else {
+    QMessageBox::critical(this, "Mantid", "Invalid Pointer");
     return 0;
   }
 }
 
-//! Used by the save script to clipboard/file buttons to select which versioning mode to use.
-std::string AlgorithmHistoryWindow::getScriptVersionMode()
-{
+//! Used by the save script to clipboard/file buttons to select which versioning
+// mode to use.
+std::string AlgorithmHistoryWindow::getScriptVersionMode() {
   std::string curText = m_scriptComboMode->currentText().toStdString();
 
-  if(curText == "Only Specify Old Versions")
-  {
+  if (curText == "Only Specify Old Versions") {
     return "old";
-  }
-  else if(curText == "Always Specify Versions")
-  {
+  } else if (curText == "Always Specify Versions") {
     return "all";
-  }
-  else if(curText == "Never Specify Versions")
-  {
+  } else if (curText == "Never Specify Versions") {
     return "none";
   }
 
-  throw std::runtime_error("AlgorithmHistoryWindow::getScriptVersionMode received unhandled version mode string");
+  throw std::runtime_error("AlgorithmHistoryWindow::getScriptVersionMode "
+                           "received unhandled version mode string");
 }
 
-void AlgorithmHistoryWindow::writeToScriptFile()
-{
-  QString prevDir = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
+void AlgorithmHistoryWindow::writeToScriptFile() {
+  QString prevDir =
+      MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
   QString scriptDir("");
   // Default script directory
-  if(prevDir.isEmpty())
-  {
-    scriptDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directory"));
-  }
-  else
-  {
+  if (prevDir.isEmpty()) {
+    scriptDir = QString::fromStdString(
+        Mantid::Kernel::ConfigService::Instance().getString(
+            "pythonscripts.directory"));
+  } else {
     scriptDir = prevDir;
   }
-  QString filePath = MantidQt::API::FileDialogHandler::getSaveFileName(this,tr("Save Script As "),scriptDir,tr("Script files (*.py)"));
+  QString filePath = MantidQt::API::FileDialogHandler::getSaveFileName(
+      this, tr("Save Script As "), scriptDir, tr("Script files (*.py)"));
   // An empty string indicates they clicked cancel
-  if( filePath.isEmpty() ) return;
-  
+  if (filePath.isEmpty())
+    return;
+
   ScriptBuilder builder(m_view, getScriptVersionMode());
   std::ofstream file(filePath.toStdString().c_str(), std::ofstream::trunc);
   file << builder.build();
   file.flush();
   file.close();
 
-  MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filePath).absoluteDir().path());
+  MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(
+      QFileInfo(filePath).absoluteDir().path());
 }
 
-void AlgEnvHistoryGrpBox::fillEnvHistoryGroupBox(const EnvironmentHistory& envHistory)
-{
-  std::string osname=envHistory.osName();
-  std::string osversion=envHistory.osVersion();
-  std::string frwkversn=envHistory.frameworkVersion();
-	
-  QLineEdit* osNameEdit=getosNameEdit();
-  if(osNameEdit)osNameEdit->setText(osname.c_str());
-	
-  QLineEdit* osVersionEdit=getosVersionEdit();
-  if(osVersionEdit)osVersionEdit->setText(osversion.c_str());
+void AlgEnvHistoryGrpBox::fillEnvHistoryGroupBox(
+    const EnvironmentHistory &envHistory) {
+  std::string osname = envHistory.osName();
+  std::string osversion = envHistory.osVersion();
+  std::string frwkversn = envHistory.frameworkVersion();
 
-  QLineEdit* frmwkVersnEdit=getfrmworkVersionEdit();
-  if(frmwkVersnEdit)frmwkVersnEdit->setText(frwkversn.c_str());
+  QLineEdit *osNameEdit = getosNameEdit();
+  if (osNameEdit)
+    osNameEdit->setText(osname.c_str());
 
+  QLineEdit *osVersionEdit = getosVersionEdit();
+  if (osVersionEdit)
+    osVersionEdit->setText(osversion.c_str());
+
+  QLineEdit *frmwkVersnEdit = getfrmworkVersionEdit();
+  if (frmwkVersnEdit)
+    frmwkVersnEdit->setText(frwkversn.c_str());
 }
 
-void AlgorithmHistoryWindow::updateAll(Mantid::API::AlgorithmHistory_const_sptr algHistory)
-{	
+void AlgorithmHistoryWindow::updateAll(
+    Mantid::API::AlgorithmHistory_const_sptr algHistory) {
   updateAlgHistoryProperties(algHistory);
   updateExecSummaryGrpBox(algHistory);
 }
 
-void AlgorithmHistoryWindow::updateAlgHistoryProperties(AlgorithmHistory_const_sptr algHistory)
-{
+void AlgorithmHistoryWindow::updateAlgHistoryProperties(
+    AlgorithmHistory_const_sptr algHistory) {
   PropertyHistories histProp = algHistory->getProperties();
-  if(m_histPropWindow)
-  {  m_histPropWindow->setAlgProperties(histProp);
+  if (m_histPropWindow) {
+    m_histPropWindow->setAlgProperties(histProp);
     m_histPropWindow->clearData();
     m_histPropWindow->displayAlgHistoryProperties();
   }
 }
 
-void AlgorithmHistoryWindow::updateExecSummaryGrpBox(AlgorithmHistory_const_sptr algHistory)
-{
-  //getting the selcted algorithm at pos from History vector
-  double duration=algHistory->executionDuration();
-  Mantid::Kernel::DateAndTime date=algHistory->executionDate();
-  if(m_execSumGrpBox)m_execSumGrpBox->setData(duration,date);
+void AlgorithmHistoryWindow::updateExecSummaryGrpBox(
+    AlgorithmHistory_const_sptr algHistory) {
+  // getting the selcted algorithm at pos from History vector
+  double duration = algHistory->executionDuration();
+  Mantid::Kernel::DateAndTime date = algHistory->executionDate();
+  if (m_execSumGrpBox)
+    m_execSumGrpBox->setData(duration, date);
 }
 
-void AlgorithmHistoryWindow::copytoClipboard()
-{	
+void AlgorithmHistoryWindow::copytoClipboard() {
   ScriptBuilder builder(m_view, getScriptVersionMode());
   QString script;
   const std::string contents = builder.build();
@@ -411,25 +447,18 @@ void AlgorithmHistoryWindow::copytoClipboard()
 
   // Send to clipboard.
   QClipboard *clipboard = QApplication::clipboard();
-  if(NULL != clipboard)
-  {	
+  if (NULL != clipboard) {
     clipboard->setText(script);
   }
 }
 
-void AlgorithmHistoryWindow::doUnroll(const std::vector<int>& unrollIndicies )
-{
-  for(auto it=unrollIndicies.begin(); it!=unrollIndicies.end(); ++it)
-  {
+void AlgorithmHistoryWindow::doUnroll(const std::vector<int> &unrollIndicies) {
+  for (auto it = unrollIndicies.begin(); it != unrollIndicies.end(); ++it) {
     m_view->unroll(*it);
   }
 }
 
-void AlgorithmHistoryWindow::doRoll( int index )
-{
-  m_view->roll(index);
-}
-
+void AlgorithmHistoryWindow::doRoll(int index) { m_view->roll(index); }
 
 //--------------------------------------------------------------------------------------------------
 // AlgHistoryProperties Definitions
@@ -510,10 +539,10 @@ void AlgHistoryProperties::copySelectedItemText() {
 void AlgHistoryProperties::displayAlgHistoryProperties() {
   QStringList propList;
   std::string sProperty;
-  for ( std::vector<PropertyHistory_sptr>::const_iterator pIter = m_Histprop.begin();
-	pIter != m_Histprop.end(); ++pIter )
-  {
-    sProperty=(*pIter)->name();
+  for (std::vector<PropertyHistory_sptr>::const_iterator pIter =
+           m_Histprop.begin();
+       pIter != m_Histprop.end(); ++pIter) {
+    sProperty = (*pIter)->name();
     propList.append(sProperty.c_str());
 
     sProperty = (*pIter)->value();
@@ -525,22 +554,34 @@ void AlgHistoryProperties::displayAlgHistoryProperties() {
     }
     propList.append(sProperty.c_str());
 
-    bisDefault? (sProperty="Yes"):(sProperty="No");
+    bisDefault ? (sProperty = "Yes") : (sProperty = "No");
     propList.append(sProperty.c_str());
-    int nDirection=(*pIter)->direction();
-    switch(nDirection)
-    {
-    case 0:{sProperty="Input";break;}
-    case 1:{sProperty="Output";break;}
-    case 2:{sProperty="InOut";break;}
-    default:{sProperty="N/A";break;}
+    int nDirection = (*pIter)->direction();
+    switch (nDirection) {
+    case 0: {
+      sProperty = "Input";
+      break;
+    }
+    case 1: {
+      sProperty = "Output";
+      break;
+    }
+    case 2: {
+      sProperty = "InOut";
+      break;
+    }
+    default: {
+      sProperty = "N/A";
+      break;
+    }
     }
     propList.append(sProperty.c_str());
-    QTreeWidgetItem * item= new	QTreeWidgetItem(propList);
-    if(m_histpropTree)m_histpropTree->addTopLevelItem(item);
+    QTreeWidgetItem *item = new QTreeWidgetItem(propList);
+    if (m_histpropTree)
+      m_histpropTree->addTopLevelItem(item);
     propList.clear();
 
-  }// end of properties for loop
+  } // end of properties for loop
 
   // Fit some column widths to data
   m_histpropTree->resizeColumnToContents(0); // Property name
@@ -551,65 +592,58 @@ void AlgHistoryProperties::displayAlgHistoryProperties() {
 //--------------------------------------------------------------------------------------------------
 // AlgHistoryTreeWidget Definitions
 //--------------------------------------------------------------------------------------------------
-void AlgHistoryTreeWidget::onItemChanged(QTreeWidgetItem* item, int index)
-{
+void AlgHistoryTreeWidget::onItemChanged(QTreeWidgetItem *item, int index) {
   this->blockSignals(true);
-  if (index == UNROLL_COLUMN_INDEX && item->checkState(index) == Qt::Checked)
-  {
+  if (index == UNROLL_COLUMN_INDEX && item->checkState(index) == Qt::Checked) {
     itemChecked(item, index);
-  }
-  else if(index == UNROLL_COLUMN_INDEX && item->checkState(index) == Qt::Unchecked)
-  {
+  } else if (index == UNROLL_COLUMN_INDEX &&
+             item->checkState(index) == Qt::Unchecked) {
     itemUnchecked(item, index);
   }
   this->blockSignals(false);
 }
 
-void AlgHistoryTreeWidget::itemChecked(QTreeWidgetItem* item, int index)
-{
+void AlgHistoryTreeWidget::itemChecked(QTreeWidgetItem *item, int index) {
   std::vector<int> indicies;
   QModelIndex modelIndex;
 
-  do
-  {
+  do {
     modelIndex = indexFromItem(item, index);
-    indicies.push_back(modelIndex.row()+1);
-    
-    if(item->flags().testFlag(Qt::ItemIsUserCheckable))
-    {
+    indicies.push_back(modelIndex.row() + 1);
+
+    if (item->flags().testFlag(Qt::ItemIsUserCheckable)) {
       item->setCheckState(index, Qt::Checked);
     }
 
     item = item->parent();
-  } while(item);
+  } while (item);
 
-  indicies[indicies.size()-1] -= 1;
-  
-  //sum the indices to obtain the positions we must unroll 
+  indicies[indicies.size() - 1] -= 1;
+
+  // sum the indices to obtain the positions we must unroll
   std::vector<int> unrollIndicies;
   unrollIndicies.reserve(indicies.size());
-  std::partial_sum(indicies.rbegin(), indicies.rend(), std::back_inserter(unrollIndicies) );
+  std::partial_sum(indicies.rbegin(), indicies.rend(),
+                   std::back_inserter(unrollIndicies));
 
   this->blockSignals(false);
   emit unrollAlgorithmHistory(unrollIndicies);
   this->blockSignals(true);
 }
 
-void AlgHistoryTreeWidget::itemUnchecked(QTreeWidgetItem* item, int index)
-{
+void AlgHistoryTreeWidget::itemUnchecked(QTreeWidgetItem *item, int index) {
   int rollIndex = 0;
   QModelIndex modelIndex;
 
-  //disable any children
+  // disable any children
   uncheckAllChildren(item, index);
-  
-  //find where we are in the tree
-  do
-  {
+
+  // find where we are in the tree
+  do {
     modelIndex = indexFromItem(item, index);
-    rollIndex += modelIndex.row()+1;
+    rollIndex += modelIndex.row() + 1;
     item = item->parent();
-  } while(item);
+  } while (item);
 
   --rollIndex;
   this->blockSignals(false);
@@ -617,44 +651,43 @@ void AlgHistoryTreeWidget::itemUnchecked(QTreeWidgetItem* item, int index)
   this->blockSignals(true);
 }
 
-void AlgHistoryTreeWidget::uncheckAllChildren(QTreeWidgetItem* item, int index)
-{
-  if(item->childCount() > 0)
-  {  
+void AlgHistoryTreeWidget::uncheckAllChildren(QTreeWidgetItem *item,
+                                              int index) {
+  if (item->childCount() > 0) {
     item->setCheckState(index, Qt::Unchecked);
-    for(int i=0; i<item->childCount(); ++i)
-    {
+    for (int i = 0; i < item->childCount(); ++i) {
       uncheckAllChildren(item->child(i), index);
     }
   }
 }
 
-void AlgHistoryTreeWidget::treeSelectionChanged()
-{	
-  if (AlgHistoryItem* item = dynamic_cast<AlgHistoryItem*>(this->selectedItems()[0])) {
+void AlgHistoryTreeWidget::treeSelectionChanged() {
+  if (AlgHistoryItem *item =
+          dynamic_cast<AlgHistoryItem *>(this->selectedItems()[0])) {
     emit updateAlgorithmHistoryWindow(item->getAlgorithmHistory());
   }
 }
 
-void AlgHistoryTreeWidget::selectionChanged ( const QItemSelection & selected, const QItemSelection & deselected )
-{
+void AlgHistoryTreeWidget::selectionChanged(const QItemSelection &selected,
+                                            const QItemSelection &deselected) {
   QTreeView::selectionChanged(selected, deselected);
   treeSelectionChanged();
 }
 
-void AlgHistoryTreeWidget::populateAlgHistoryTreeWidget(const WorkspaceHistory& wsHist)
-{
+void AlgHistoryTreeWidget::populateAlgHistoryTreeWidget(
+    const WorkspaceHistory &wsHist) {
   this->blockSignals(true);
-  const Mantid::API::AlgorithmHistories & entries = wsHist.getAlgorithmHistories();
+  const Mantid::API::AlgorithmHistories &entries =
+      wsHist.getAlgorithmHistories();
   auto algHistIter = entries.begin();
 
   QString algName = "";
-  for (; algHistIter != entries.end(); ++algHistIter)
-  {
+  for (; algHistIter != entries.end(); ++algHistIter) {
     int nAlgVersion = (*algHistIter)->version();
-    algName = concatVersionwithName((*algHistIter)->name(),nAlgVersion);
+    algName = concatVersionwithName((*algHistIter)->name(), nAlgVersion);
 
-    AlgHistoryItem * item = new AlgHistoryItem(QStringList(algName), *algHistIter);
+    AlgHistoryItem *item =
+        new AlgHistoryItem(QStringList(algName), *algHistIter);
     this->addTopLevelItem(item);
     populateNestedHistory(item, *algHistIter);
   }
@@ -663,32 +696,33 @@ void AlgHistoryTreeWidget::populateAlgHistoryTreeWidget(const WorkspaceHistory&
   this->blockSignals(false);
 }
 
-void AlgHistoryTreeWidget::populateNestedHistory(AlgHistoryItem* parentWidget, Mantid::API::AlgorithmHistory_sptr history)
-{
+void AlgHistoryTreeWidget::populateNestedHistory(
+    AlgHistoryItem *parentWidget, Mantid::API::AlgorithmHistory_sptr history) {
   QString algName = "";
-  const Mantid::API::AlgorithmHistories & entries = history->getChildHistories();
-  if(history->childHistorySize() > 0)
-  {
-    parentWidget->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsEnabled );
+  const Mantid::API::AlgorithmHistories &entries = history->getChildHistories();
+  if (history->childHistorySize() > 0) {
+    parentWidget->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsSelectable |
+                           Qt::ItemIsEnabled);
     parentWidget->setCheckState(1, Qt::Unchecked);
   }
 
-  for (auto algHistIter = entries.begin(); algHistIter != entries.end(); ++algHistIter)
-  {
+  for (auto algHistIter = entries.begin(); algHistIter != entries.end();
+       ++algHistIter) {
     int nAlgVersion = (*algHistIter)->version();
-    algName = concatVersionwithName((*algHistIter)->name(),nAlgVersion);
+    algName = concatVersionwithName((*algHistIter)->name(), nAlgVersion);
 
-    AlgHistoryItem * item = new AlgHistoryItem(QStringList(algName), *algHistIter, parentWidget);
+    AlgHistoryItem *item =
+        new AlgHistoryItem(QStringList(algName), *algHistIter, parentWidget);
     parentWidget->addChild(item);
     populateNestedHistory(item, *algHistIter);
   }
 }
 
-QString AlgHistoryTreeWidget::concatVersionwithName(const std::string& name,const int version)
-{
+QString AlgHistoryTreeWidget::concatVersionwithName(const std::string &name,
+                                                    const int version) {
   QString algName = name.c_str();
-  algName =  algName + " v.";
-  QString algVersion=QString::number(version,10);
+  algName = algName + " v.";
+  QString algVersion = QString::number(version, 10);
   algName += algVersion;
   return algName;
 }
diff --git a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
index 6c6866493a8410fabc717b9cea360901dbb0cd6c..72adba7f9e677c5dc4a42c6f3e570bd75d61bc56 100644
--- a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
+++ b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
@@ -1,4 +1,4 @@
-#ifndef ALGORITHMHISTORYWINDOW_H 
+#ifndef ALGORITHMHISTORYWINDOW_H
 #define ALGORITHMHISTORYWINDOW_H
 
 #include "MantidAPI/HistoryItem.h"
@@ -29,95 +29,95 @@ class QFileDialog;
 // Mantid Forward declarations
 //------------------------------------------------------------------------------
 
-namespace Mantid 
-{
-  namespace API 
-  {
-    class Workspace;
-  }
+namespace Mantid {
+namespace API {
+class Workspace;
+}
 }
 
-
-class AlgHistoryItem : public QTreeWidgetItem, public Mantid::API::HistoryItem
-{
-  public:
-    AlgHistoryItem(const QStringList & names, Mantid::API::AlgorithmHistory_const_sptr algHistory, AlgHistoryItem* parent = 0)
-      : QTreeWidgetItem(parent, names, UserType), Mantid::API::HistoryItem(algHistory) {}
+class AlgHistoryItem : public QTreeWidgetItem, public Mantid::API::HistoryItem {
+public:
+  AlgHistoryItem(const QStringList &names,
+                 Mantid::API::AlgorithmHistory_const_sptr algHistory,
+                 AlgHistoryItem *parent = 0)
+      : QTreeWidgetItem(parent, names, UserType),
+        Mantid::API::HistoryItem(algHistory) {}
 };
 
-
-class AlgHistoryTreeWidget:public QTreeWidget
-{
+class AlgHistoryTreeWidget : public QTreeWidget {
   Q_OBJECT
 
 signals:
-  void updateAlgorithmHistoryWindow(Mantid::API::AlgorithmHistory_const_sptr algHistory);
-  void unrollAlgorithmHistory(const std::vector<int>& indicies);
+  void updateAlgorithmHistoryWindow(
+      Mantid::API::AlgorithmHistory_const_sptr algHistory);
+  void unrollAlgorithmHistory(const std::vector<int> &indicies);
   void rollAlgorithmHistory(int index);
 
 public:
   /// Constructor
   explicit AlgHistoryTreeWidget(QWidget *w)
       : QTreeWidget(w), m_algName(""), m_nVersion(0) {
-    connect(this, SIGNAL(itemChanged(QTreeWidgetItem*,int)),SLOT(onItemChanged(QTreeWidgetItem*,int)));
+    connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
+            SLOT(onItemChanged(QTreeWidgetItem *, int)));
   }
-  void populateAlgHistoryTreeWidget(const Mantid::API::WorkspaceHistory& wsHist);
+  void
+  populateAlgHistoryTreeWidget(const Mantid::API::WorkspaceHistory &wsHist);
 
 protected:
   void selectionChanged(const QItemSelection &selected,
                         const QItemSelection &deselected) override;
 
 private slots:
-  void onItemChanged(QTreeWidgetItem* item, int index);
+  void onItemChanged(QTreeWidgetItem *item, int index);
 
 private:
   void treeSelectionChanged();
-  void itemChecked(QTreeWidgetItem* item, int index);
-  void itemUnchecked(QTreeWidgetItem* item, int index);
-  void populateNestedHistory(AlgHistoryItem* parentWidget, Mantid::API::AlgorithmHistory_sptr history);
-  void uncheckAllChildren(QTreeWidgetItem* item, int index);
-  QString concatVersionwithName(const std::string& name,const int version);
-  
+  void itemChecked(QTreeWidgetItem *item, int index);
+  void itemUnchecked(QTreeWidgetItem *item, int index);
+  void populateNestedHistory(AlgHistoryItem *parentWidget,
+                             Mantid::API::AlgorithmHistory_sptr history);
+  void uncheckAllChildren(QTreeWidgetItem *item, int index);
+  QString concatVersionwithName(const std::string &name, const int version);
+
   const static int UNROLL_COLUMN_INDEX = 1;
   QString m_algName;
   int m_nVersion;
 };
 
-
-
-class AlgExecSummaryGrpBox: public QGroupBox
-{
+class AlgExecSummaryGrpBox : public QGroupBox {
   Q_OBJECT
-  public:
-    explicit AlgExecSummaryGrpBox(QWidget *w);
-  AlgExecSummaryGrpBox(QString,QWidget*w);
+public:
+  explicit AlgExecSummaryGrpBox(QWidget *w);
+  AlgExecSummaryGrpBox(QString, QWidget *w);
   ~AlgExecSummaryGrpBox() override;
-  void setData(const double execDuration,const Mantid::Kernel::DateAndTime execDate);
+  void setData(const double execDuration,
+               const Mantid::Kernel::DateAndTime execDate);
+
 private:
-  QLineEdit* getAlgExecDurationCtrl()const {return m_execDurationEdit;}
-  QLineEdit* getAlgExecDateCtrl() const{ return m_execDateTimeEdit;}
+  QLineEdit *getAlgExecDurationCtrl() const { return m_execDurationEdit; }
+  QLineEdit *getAlgExecDateCtrl() const { return m_execDateTimeEdit; }
+
 private:
   QLabel *m_execDurationlabel;
   QLineEdit *m_execDurationEdit;
   QLabel *m_Datelabel;
-  QLineEdit*m_execDateTimeEdit;
-  QString m_algexecDuration;  
+  QLineEdit *m_execDateTimeEdit;
+  QString m_algexecDuration;
 };
 
-
-
-class AlgEnvHistoryGrpBox: public QGroupBox
-{
+class AlgEnvHistoryGrpBox : public QGroupBox {
   Q_OBJECT
-  public:
-    explicit AlgEnvHistoryGrpBox(QWidget *w);
-  AlgEnvHistoryGrpBox(QString,QWidget*w);
+public:
+  explicit AlgEnvHistoryGrpBox(QWidget *w);
+  AlgEnvHistoryGrpBox(QString, QWidget *w);
   ~AlgEnvHistoryGrpBox() override;
 
-  QLineEdit* getosNameEdit()const {return m_osNameEdit;}
-  QLineEdit* getosVersionEdit()const {return m_osVersionEdit;}
-  QLineEdit* getfrmworkVersionEdit()const {return m_frmwkVersnEdit;}
-  void fillEnvHistoryGroupBox(const Mantid::Kernel::EnvironmentHistory& envHist);
+  QLineEdit *getosNameEdit() const { return m_osNameEdit; }
+  QLineEdit *getosVersionEdit() const { return m_osVersionEdit; }
+  QLineEdit *getfrmworkVersionEdit() const { return m_frmwkVersnEdit; }
+  void
+  fillEnvHistoryGroupBox(const Mantid::Kernel::EnvironmentHistory &envHist);
+
 private:
   QLabel *m_osNameLabel;
   QLineEdit *m_osNameEdit;
@@ -127,51 +127,52 @@ private:
   QLineEdit *m_frmwkVersnEdit;
 };
 
-
-
 class AlgHistoryProperties;
-class AlgorithmHistoryWindow: public MantidQt::API::MantidDialog
-{
+class AlgorithmHistoryWindow : public MantidQt::API::MantidDialog {
   Q_OBJECT
-  signals:
+signals:
   void updateAlgorithmHistoryWindow(QString algName);
 
 public:
-  AlgorithmHistoryWindow(QWidget *parent,const boost::shared_ptr<const Mantid::API::Workspace>);
+  AlgorithmHistoryWindow(QWidget *parent,
+                         const boost::shared_ptr<const Mantid::API::Workspace>);
   ~AlgorithmHistoryWindow() override;
 public slots:
   void updateAll(Mantid::API::AlgorithmHistory_const_sptr algHistmakeory);
-  void doUnroll(const std::vector<int>& unrollIndicies );
-  void doRoll( int index );
-  
+  void doUnroll(const std::vector<int> &unrollIndicies);
+  void doRoll(int index);
+
   void copytoClipboard();
   void writeToScriptFile();
+
 private:
-  AlgExecSummaryGrpBox* createExecSummaryGrpBox();
-  AlgEnvHistoryGrpBox* createEnvHistGrpBox(const Mantid::Kernel::EnvironmentHistory& envHistory);
-  AlgHistoryProperties * createAlgHistoryPropWindow();
+  AlgExecSummaryGrpBox *createExecSummaryGrpBox();
+  AlgEnvHistoryGrpBox *
+  createEnvHistGrpBox(const Mantid::Kernel::EnvironmentHistory &envHistory);
+  AlgHistoryProperties *createAlgHistoryPropWindow();
 
-  QFileDialog* createScriptDialog(const QString& algName);
-  void updateExecSummaryGrpBox(Mantid::API::AlgorithmHistory_const_sptr algHistory);
-  void updateAlgHistoryProperties(Mantid::API::AlgorithmHistory_const_sptr algHistory);
+  QFileDialog *createScriptDialog(const QString &algName);
+  void
+  updateExecSummaryGrpBox(Mantid::API::AlgorithmHistory_const_sptr algHistory);
+  void updateAlgHistoryProperties(
+      Mantid::API::AlgorithmHistory_const_sptr algHistory);
 
   std::string getScriptVersionMode();
 
 private:
-  const Mantid::API::WorkspaceHistory & m_algHist;
+  const Mantid::API::WorkspaceHistory &m_algHist;
   QLabel *m_scriptVersionLabel;
   QComboBox *m_scriptComboMode;
   QPushButton *m_scriptButtonFile;
   QPushButton *m_scriptButtonClipboard;
   AlgHistoryTreeWidget *m_Historytree;
-  AlgHistoryProperties * m_histPropWindow; 
-  AlgExecSummaryGrpBox *m_execSumGrpBox ;
-  AlgEnvHistoryGrpBox * m_envHistGrpBox;
+  AlgHistoryProperties *m_histPropWindow;
+  AlgExecSummaryGrpBox *m_execSumGrpBox;
+  AlgEnvHistoryGrpBox *m_envHistGrpBox;
   QString m_wsName;
   boost::shared_ptr<Mantid::API::HistoryView> m_view;
 };
 
-
 class AlgHistoryProperties : public QObject {
   Q_OBJECT
 
diff --git a/MantidPlot/src/Mantid/AlgorithmMonitor.cpp b/MantidPlot/src/Mantid/AlgorithmMonitor.cpp
index 5b4ffee3981e6414ebcc919bc80ebb93873f75e8..9e9dd1fe74ddd5102553009f39db2c658d974be9 100644
--- a/MantidPlot/src/Mantid/AlgorithmMonitor.cpp
+++ b/MantidPlot/src/Mantid/AlgorithmMonitor.cpp
@@ -17,24 +17,26 @@ QMutex AlgorithmMonitor::s_mutex;
 
 //-----------------------------------------------------------------------------
 /** Constructor */
-AlgorithmMonitor::AlgorithmMonitor(MantidUI *m) : 
-m_finishedObserver(*this, &AlgorithmMonitor::handleAlgorithmFinishedNotification),
-m_progressObserver(*this, &AlgorithmMonitor::handleAlgorithmProgressNotification),
-m_errorObserver(*this, &AlgorithmMonitor::handleAlgorithmErrorNotification),
-m_startingObserver(*this, &AlgorithmMonitor::handleAlgorithmStartingNotification),
-m_mantidUI(m), m_nRunning(0)
-{
-  AlgorithmManager::Instance().notificationCenter.addObserver(m_startingObserver);
+AlgorithmMonitor::AlgorithmMonitor(MantidUI *m)
+    : m_finishedObserver(
+          *this, &AlgorithmMonitor::handleAlgorithmFinishedNotification),
+      m_progressObserver(
+          *this, &AlgorithmMonitor::handleAlgorithmProgressNotification),
+      m_errorObserver(*this,
+                      &AlgorithmMonitor::handleAlgorithmErrorNotification),
+      m_startingObserver(
+          *this, &AlgorithmMonitor::handleAlgorithmStartingNotification),
+      m_mantidUI(m), m_nRunning(0) {
+  AlgorithmManager::Instance().notificationCenter.addObserver(
+      m_startingObserver);
   m_monitorDlg = new MonitorDlg(m_mantidUI->appWindow(), this);
   m_monitorDlg->setVisible(false);
 }
 
 //-----------------------------------------------------------------------------
 /** Destructor */
-AlgorithmMonitor::~AlgorithmMonitor()
-{
-  if( m_monitorDlg )
-  {
+AlgorithmMonitor::~AlgorithmMonitor() {
+  if (m_monitorDlg) {
     m_monitorDlg->close();
     delete m_monitorDlg;
   }
@@ -42,7 +44,8 @@ AlgorithmMonitor::~AlgorithmMonitor()
   wait(1000);
   exit();
   wait();
-  AlgorithmManager::Instance().notificationCenter.removeObserver(m_startingObserver);
+  AlgorithmManager::Instance().notificationCenter.removeObserver(
+      m_startingObserver);
 }
 
 //-----------------------------------------------------------------------------
@@ -50,8 +53,7 @@ AlgorithmMonitor::~AlgorithmMonitor()
  *
  * @param alg :: algorithm to monitor.
  */
-void AlgorithmMonitor::add(Mantid::API::IAlgorithm_sptr alg)
-{
+void AlgorithmMonitor::add(Mantid::API::IAlgorithm_sptr alg) {
   lock();
   alg->addObserver(m_finishedObserver);
   alg->addObserver(m_errorObserver);
@@ -69,38 +71,39 @@ void AlgorithmMonitor::add(Mantid::API::IAlgorithm_sptr alg)
  *
  * @param alg :: algorithm.
  */
-void AlgorithmMonitor::remove(const IAlgorithm* alg)
-{
+void AlgorithmMonitor::remove(const IAlgorithm *alg) {
   lock();
-  QVector<AlgorithmID>::iterator i = find(m_algorithms.begin(),m_algorithms.end(),alg->getAlgorithmID());
-  if (i != m_algorithms.end())
-  {
+  QVector<AlgorithmID>::iterator i =
+      find(m_algorithms.begin(), m_algorithms.end(), alg->getAlgorithmID());
+  if (i != m_algorithms.end()) {
     m_algorithms.erase(i);
     --m_nRunning;
   }
   emit algorithmFinished(alg->getAlgorithmID());
   emit countChanged();
-  if (m_algorithms.empty()) emit allAlgorithmsStopped();
+  if (m_algorithms.empty())
+    emit allAlgorithmsStopped();
   unlock();
 }
 
-void AlgorithmMonitor::update()
-{
-}
+void AlgorithmMonitor::update() {}
 
-void AlgorithmMonitor::handleAlgorithmFinishedNotification(const Poco::AutoPtr<Algorithm::FinishedNotification>& pNf)
-{
+void AlgorithmMonitor::handleAlgorithmFinishedNotification(
+    const Poco::AutoPtr<Algorithm::FinishedNotification> &pNf) {
   remove(pNf->algorithm());
 }
 
-void AlgorithmMonitor::handleAlgorithmProgressNotification(const Poco::AutoPtr<Algorithm::ProgressNotification>& pNf)
-{
-  emit needUpdateProgress(pNf->algorithm()->getAlgorithmID(),static_cast<double>(pNf->progress*100), QString::fromStdString(pNf->message),
-        double(pNf->estimatedTime), int(pNf->progressPrecision) );
+void AlgorithmMonitor::handleAlgorithmProgressNotification(
+    const Poco::AutoPtr<Algorithm::ProgressNotification> &pNf) {
+  emit needUpdateProgress(pNf->algorithm()->getAlgorithmID(),
+                          static_cast<double>(pNf->progress * 100),
+                          QString::fromStdString(pNf->message),
+                          double(pNf->estimatedTime),
+                          int(pNf->progressPrecision));
 }
 
-void AlgorithmMonitor::handleAlgorithmErrorNotification(const Poco::AutoPtr<Algorithm::ErrorNotification>& pNf)
-{
+void AlgorithmMonitor::handleAlgorithmErrorNotification(
+    const Poco::AutoPtr<Algorithm::ErrorNotification> &pNf) {
   remove(pNf->algorithm());
 }
 
@@ -111,17 +114,15 @@ void AlgorithmMonitor::handleAlgorithmErrorNotification(const Poco::AutoPtr<Algo
  *
  * @param pNf :: notification object
  */
-void AlgorithmMonitor::handleAlgorithmStartingNotification(const Poco::AutoPtr<Mantid::API::AlgorithmStartingNotification>& pNf)
-{
+void AlgorithmMonitor::handleAlgorithmStartingNotification(
+    const Poco::AutoPtr<Mantid::API::AlgorithmStartingNotification> &pNf) {
   add(pNf->getAlgorithm());
 }
 
 //-----------------------------------------------------------------------------
 /** Slot called to show the monitor dialog */
-void AlgorithmMonitor::showDialog()
-{
-  if( !m_monitorDlg->isVisible() )
-  {
+void AlgorithmMonitor::showDialog() {
+  if (!m_monitorDlg->isVisible()) {
     m_monitorDlg->setVisible(true);
     m_monitorDlg->update();
   }
@@ -129,39 +130,40 @@ void AlgorithmMonitor::showDialog()
 
 //-----------------------------------------------------------------------------
 /** Cancel the given algorithm's execution */
-void AlgorithmMonitor::cancel(Mantid::API::AlgorithmID id, QPushButton* cancelBtn = NULL)
-{
-  if ((cancelBtn) && (cancelBtn->text() == "Cancel"))
-  {
+void AlgorithmMonitor::cancel(Mantid::API::AlgorithmID id,
+                              QPushButton *cancelBtn = NULL) {
+  if ((cancelBtn) && (cancelBtn->text() == "Cancel")) {
     cancelBtn->setText("Cancelling");
     cancelBtn->setEnabled(false);
-    IAlgorithm_sptr a = Mantid::API::AlgorithmManager::Instance().getAlgorithm(id);
-    if (!a.get()) return;
+    IAlgorithm_sptr a =
+        Mantid::API::AlgorithmManager::Instance().getAlgorithm(id);
+    if (!a.get())
+      return;
     a->cancel();
   }
 }
 
 //-----------------------------------------------------------------------------
 /** Cancel all running algorithms */
-void AlgorithmMonitor::cancelAll()
-{
+void AlgorithmMonitor::cancelAll() {
   // Forward to the AlgorithmManager
   AlgorithmManager::Instance().cancelAll();
 }
 
- 
 //-----------------------------------------------------------------------------------------------//
-MonitorDlg::MonitorDlg(QWidget *parent,AlgorithmMonitor *algMonitor):QDialog(parent),m_algMonitor(algMonitor)
-{
+MonitorDlg::MonitorDlg(QWidget *parent, AlgorithmMonitor *algMonitor)
+    : QDialog(parent), m_algMonitor(algMonitor) {
   m_tree = 0;
   update();
-  connect(algMonitor,SIGNAL(countChanged()),this,SLOT(update()), Qt::QueuedConnection);
-  connect(algMonitor,SIGNAL(needUpdateProgress(void*, double, const QString&, double, int)),
-      SLOT(updateProgress(void*, double, const QString&, double, int)));
+  connect(algMonitor, SIGNAL(countChanged()), this, SLOT(update()),
+          Qt::QueuedConnection);
+  connect(algMonitor, SIGNAL(needUpdateProgress(void *, double, const QString &,
+                                                double, int)),
+          SLOT(updateProgress(void *, double, const QString &, double, int)));
 
   QHBoxLayout *buttonLayout = new QHBoxLayout;
   QPushButton *closeButton = new QPushButton("Close");
-  connect(closeButton,SIGNAL(clicked()),this,SLOT(close()));
+  connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
   buttonLayout->addStretch();
   buttonLayout->addWidget(closeButton);
 
@@ -171,84 +173,94 @@ MonitorDlg::MonitorDlg(QWidget *parent,AlgorithmMonitor *algMonitor):QDialog(par
   setLayout(layout);
   setWindowTitle("Mantid - Algorithm progress");
   setWindowIcon(QIcon(":/MantidPlot_Icon_32offset.png"));
-  resize(500,300);
+  resize(500, 300);
 }
 
-MonitorDlg::~MonitorDlg() 
-{
-}
+MonitorDlg::~MonitorDlg() {}
 
-void MonitorDlg::update()
-{
-  if (!m_tree)
-  {
+void MonitorDlg::update() {
+  if (!m_tree) {
     m_tree = new QTreeWidget(this);
     m_tree->setColumnCount(3);
     m_tree->setSelectionMode(QAbstractItemView::NoSelection);
     // Make the algorithm name column wider
     m_tree->setColumnWidth(0, 220);
     QStringList hList;
-    hList<<"Algorithm"<<"Progress"<<"";
+    hList << "Algorithm"
+          << "Progress"
+          << "";
     m_tree->setHeaderLabels(hList);
-    QHeaderView* hHeader = (QHeaderView*)m_tree->header();
-    hHeader->setResizeMode(1,QHeaderView::Stretch);
-    hHeader->setResizeMode(2,QHeaderView::Fixed);
+    QHeaderView *hHeader = (QHeaderView *)m_tree->header();
+    hHeader->setResizeMode(1, QHeaderView::Stretch);
+    hHeader->setResizeMode(2, QHeaderView::Fixed);
     hHeader->setStretchLastSection(false);
-  }
-  else
+  } else
     m_tree->clear();
 
-  if( !isVisible() ) return;
+  if (!isVisible())
+    return;
 
   m_algMonitor->lock();
-  QVector<Mantid::API::AlgorithmID>::const_iterator iend = m_algMonitor->algorithms().end();
-  for(QVector<Mantid::API::AlgorithmID>::const_iterator itr = m_algMonitor->algorithms().begin();
-      itr != iend; ++itr)
-  {
-    IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().getAlgorithm(*itr);
-    //m_algorithms << alg;
+  QVector<Mantid::API::AlgorithmID>::const_iterator iend =
+      m_algMonitor->algorithms().end();
+  for (QVector<Mantid::API::AlgorithmID>::const_iterator itr =
+           m_algMonitor->algorithms().begin();
+       itr != iend; ++itr) {
+    IAlgorithm_sptr alg =
+        Mantid::API::AlgorithmManager::Instance().getAlgorithm(*itr);
+    // m_algorithms << alg;
     QStringList iList;
-    iList<<QString::fromStdString(alg->name());
+    iList << QString::fromStdString(alg->name());
     QTreeWidgetItem *algItem = new QTreeWidgetItem(iList);
     m_tree->addTopLevelItem(algItem);
     QProgressBar *algProgress = new QProgressBar;
     algProgress->setAlignment(Qt::AlignHCenter);
     AlgButton *cancelButton = new AlgButton("Cancel", alg);
-    m_tree->setItemWidget(algItem,1,algProgress);
-    m_tree->setItemWidget(algItem,2,cancelButton);
-    const std::vector< Mantid::Kernel::Property* >& prop_list = alg->getProperties();
-    for(std::vector< Mantid::Kernel::Property* >::const_iterator prop=prop_list.begin();prop!=prop_list.end();++prop)
-    {
+    m_tree->setItemWidget(algItem, 1, algProgress);
+    m_tree->setItemWidget(algItem, 2, cancelButton);
+    const std::vector<Mantid::Kernel::Property *> &prop_list =
+        alg->getProperties();
+    for (std::vector<Mantid::Kernel::Property *>::const_iterator prop =
+             prop_list.begin();
+         prop != prop_list.end(); ++prop) {
       QStringList lstr;
-      Mantid::Kernel::MaskedProperty<std::string> * maskedProp = dynamic_cast<Mantid::Kernel::MaskedProperty<std::string> *>(*prop);
-      if(maskedProp)
-      {
-        lstr  << QString::fromStdString(maskedProp->name()) + ": " << QString::fromStdString(maskedProp->getMaskedValue());
+      Mantid::Kernel::MaskedProperty<std::string> *maskedProp =
+          dynamic_cast<Mantid::Kernel::MaskedProperty<std::string> *>(*prop);
+      if (maskedProp) {
+        lstr << QString::fromStdString(maskedProp->name()) + ": "
+             << QString::fromStdString(maskedProp->getMaskedValue());
+      } else {
+        lstr << QString::fromStdString((**prop).name()) + ": "
+             << QString::fromStdString((**prop).value());
       }
-      else
-      {
-        lstr  << QString::fromStdString((**prop).name()) + ": " << QString::fromStdString((**prop).value());
-      }
-      if ((**prop).isDefault()) lstr << " Default";
+      if ((**prop).isDefault())
+        lstr << " Default";
       algItem->addChild(new QTreeWidgetItem(lstr));
     }
 
-    connect(cancelButton,SIGNAL(clicked(Mantid::API::AlgorithmID, QPushButton*)),m_algMonitor,SLOT(cancel(Mantid::API::AlgorithmID, QPushButton*)));
+    connect(
+        cancelButton, SIGNAL(clicked(Mantid::API::AlgorithmID, QPushButton *)),
+        m_algMonitor, SLOT(cancel(Mantid::API::AlgorithmID, QPushButton *)));
   }
   m_algMonitor->unlock();
 }
 
-// The void* corresponds to Mantid::API::AlgorithmID, but Qt wasn't coping with the typedef
-void MonitorDlg::updateProgress(void* alg, const double p, const QString& msg, double /*estimatedTime*/, int /*progressPrecision*/)
-{
+// The void* corresponds to Mantid::API::AlgorithmID, but Qt wasn't coping with
+// the typedef
+void MonitorDlg::updateProgress(void *alg, const double p, const QString &msg,
+                                double /*estimatedTime*/,
+                                int /*progressPrecision*/) {
   m_algMonitor->lock();
   const int index = m_algMonitor->algorithms().indexOf(alg);
   m_algMonitor->unlock();
-  if ( index == -1 ) return;
+  if (index == -1)
+    return;
   QTreeWidgetItem *item = m_tree->topLevelItem(index);
-  if ( !item ) return;
- 
-  QProgressBar *algProgress = static_cast<QProgressBar*>( m_tree->itemWidget(item, 1) );
-  algProgress->setValue( int(p) );
+  if (!item)
+    return;
+
+  QProgressBar *algProgress =
+      static_cast<QProgressBar *>(m_tree->itemWidget(item, 1));
+  algProgress->setValue(int(p));
   algProgress->setFormat(msg + " %p%");
 }
diff --git a/MantidPlot/src/Mantid/AlgorithmMonitor.h b/MantidPlot/src/Mantid/AlgorithmMonitor.h
index ccf65ba4d3703175328b2bd2f35868c6a79dd6de..9a3d2a989e1d5d5ff6fb3887b76c4d7592a526ba 100644
--- a/MantidPlot/src/Mantid/AlgorithmMonitor.h
+++ b/MantidPlot/src/Mantid/AlgorithmMonitor.h
@@ -16,14 +16,12 @@ class QTreeWidget;
 class MantidUI;
 class MonitorDlg;
 
-
 //-----------------------------------------------------------------------------
 /** Monitor for reporting progress and canceling running algorithms
  *
  */
-class AlgorithmMonitor: public QThread
-{
-	Q_OBJECT
+class AlgorithmMonitor : public QThread {
+  Q_OBJECT
 
 public:
   /// Constructor
@@ -33,39 +31,50 @@ public:
   /// Add algorithm to monitor
   void add(Mantid::API::IAlgorithm_sptr alg);
   /// Removes stopped algorithm
-  void remove(const Mantid::API::IAlgorithm* alg);
+  void remove(const Mantid::API::IAlgorithm *alg);
 
   /// Returns number of running algorithms
-  int count(){return m_algorithms.size();}
+  int count() { return m_algorithms.size(); }
   /// Returns pointers to running algorithms
-  const QVector<Mantid::API::AlgorithmID>& algorithms(){return m_algorithms;}
-  void lock(){s_mutex.lock();}
-  void unlock(){s_mutex.unlock();}
+  const QVector<Mantid::API::AlgorithmID> &algorithms() { return m_algorithms; }
+  void lock() { s_mutex.lock(); }
+  void unlock() { s_mutex.unlock(); }
 signals:
-  void algorithmStarted(void* alg);
-  void algorithmFinished(void* alg);
-  void needUpdateProgress(void* alg,double p, const QString& msg, double estimatedTime, int progressPrecision);
+  void algorithmStarted(void *alg);
+  void algorithmFinished(void *alg);
+  void needUpdateProgress(void *alg, double p, const QString &msg,
+                          double estimatedTime, int progressPrecision);
   void countChanged();
   void allAlgorithmsStopped();
-protected:
 
+protected:
   /// Algorithm notification handlers
-  void handleAlgorithmFinishedNotification(const Poco::AutoPtr<Mantid::API::Algorithm::FinishedNotification>& pNf);
-  Poco::NObserver<AlgorithmMonitor, Mantid::API::Algorithm::FinishedNotification> m_finishedObserver;
-
-  void handleAlgorithmProgressNotification(const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification>& pNf);
-  Poco::NObserver<AlgorithmMonitor, Mantid::API::Algorithm::ProgressNotification> m_progressObserver;
-
-  void handleAlgorithmErrorNotification(const Poco::AutoPtr<Mantid::API::Algorithm::ErrorNotification>& pNf);
-  Poco::NObserver<AlgorithmMonitor, Mantid::API::Algorithm::ErrorNotification> m_errorObserver;
-
-  void handleAlgorithmStartingNotification(const Poco::AutoPtr<Mantid::API::AlgorithmStartingNotification>& pNf);
-  Poco::NObserver<AlgorithmMonitor, Mantid::API::AlgorithmStartingNotification> m_startingObserver;
+  void handleAlgorithmFinishedNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::FinishedNotification> &pNf);
+  Poco::NObserver<AlgorithmMonitor,
+                  Mantid::API::Algorithm::FinishedNotification>
+      m_finishedObserver;
+
+  void handleAlgorithmProgressNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification> &pNf);
+  Poco::NObserver<AlgorithmMonitor,
+                  Mantid::API::Algorithm::ProgressNotification>
+      m_progressObserver;
+
+  void handleAlgorithmErrorNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::ErrorNotification> &pNf);
+  Poco::NObserver<AlgorithmMonitor, Mantid::API::Algorithm::ErrorNotification>
+      m_errorObserver;
+
+  void handleAlgorithmStartingNotification(
+      const Poco::AutoPtr<Mantid::API::AlgorithmStartingNotification> &pNf);
+  Poco::NObserver<AlgorithmMonitor, Mantid::API::AlgorithmStartingNotification>
+      m_startingObserver;
 
 public slots:
   void update();
   void showDialog();
-  void cancel(Mantid::API::AlgorithmID, QPushButton*);
+  void cancel(Mantid::API::AlgorithmID, QPushButton *);
   void cancelAll();
 
 private:
@@ -74,43 +83,43 @@ private:
   int m_nRunning;
   /// IDs of running algorithms
   QVector<Mantid::API::AlgorithmID> m_algorithms;
-  MonitorDlg* m_monitorDlg;
+  MonitorDlg *m_monitorDlg;
   static QMutex s_mutex;
 };
 
-
 //-----------------------------------------------------------------------------
 /** Dialog that shows a list of algorithms running
  * and cancel buttons for them.
  */
-class MonitorDlg: public QDialog
-{
+class MonitorDlg : public QDialog {
   Q_OBJECT
 public:
-  MonitorDlg(QWidget *parent,AlgorithmMonitor *algMonitor);
+  MonitorDlg(QWidget *parent, AlgorithmMonitor *algMonitor);
   ~MonitorDlg() override;
 public slots:
   void update();
-  // The void* corresponds to Mantid::API::AlgorithmID, but Qt wasn't coping with the typedef
-  void updateProgress(void* alg, const double p, const QString& msg, double estimatedTime, int progressPrecision);
+  // The void* corresponds to Mantid::API::AlgorithmID, but Qt wasn't coping
+  // with the typedef
+  void updateProgress(void *alg, const double p, const QString &msg,
+                      double estimatedTime, int progressPrecision);
+
 private:
   AlgorithmMonitor *m_algMonitor;
   QTreeWidget *m_tree;
 };
 
-class AlgButton:public QPushButton
-{
+class AlgButton : public QPushButton {
   Q_OBJECT
 public:
-  AlgButton(const QString& text,Mantid::API::IAlgorithm_sptr alg):
-  QPushButton(text),m_alg(alg->getAlgorithmID())
-  {
-    connect(this,SIGNAL(clicked()),this,SLOT(sendClicked()));
+  AlgButton(const QString &text, Mantid::API::IAlgorithm_sptr alg)
+      : QPushButton(text), m_alg(alg->getAlgorithmID()) {
+    connect(this, SIGNAL(clicked()), this, SLOT(sendClicked()));
   }
 private slots:
-  void sendClicked(){emit clicked(m_alg, this);}
+  void sendClicked() { emit clicked(m_alg, this); }
 signals:
-  void clicked(Mantid::API::AlgorithmID, QPushButton*);
+  void clicked(Mantid::API::AlgorithmID, QPushButton *);
+
 private:
   Mantid::API::AlgorithmID m_alg;
 };
diff --git a/MantidPlot/src/Mantid/ErrorBarSettings.cpp b/MantidPlot/src/Mantid/ErrorBarSettings.cpp
index b19c4dba126aeecd4c9421131e28139495f88c19..fbd54d41c863f8f2cef69af629a04c401994c4e8 100644
--- a/MantidPlot/src/Mantid/ErrorBarSettings.cpp
+++ b/MantidPlot/src/Mantid/ErrorBarSettings.cpp
@@ -5,105 +5,70 @@
  *  Sets defaults of black lines having width 1.0 and caps of length 6,
  *  that show on both sides of the symbol but don't draw through it.
  */
-ErrorBarSettings::ErrorBarSettings(QObject * parent)
-  : QObject(parent), m_cap(6), m_plus(true), m_minus(true), 
-    m_through(false), m_width(1.0), m_color(Qt::black), m_defaultColor(true)
-{}
+ErrorBarSettings::ErrorBarSettings(QObject *parent)
+    : QObject(parent), m_cap(6), m_plus(true), m_minus(true), m_through(false),
+      m_width(1.0), m_color(Qt::black), m_defaultColor(true) {}
 
 /// Return the length of the cap decoration on the error bars
-int ErrorBarSettings::capLength() const
-{
-  return m_cap;
-}
+int ErrorBarSettings::capLength() const { return m_cap; }
 
 /// Set the length of the cap decoration on the error bars
-void ErrorBarSettings::setCapLength(int t)
-{
-  m_cap = t;
-}
+void ErrorBarSettings::setCapLength(int t) { m_cap = t; }
 
 /// Returns the width of the error bar lines. Overridden in QwtErrorPlotCurve.
-double ErrorBarSettings::width() const
-{
-  return m_width;
-}
+double ErrorBarSettings::width() const { return m_width; }
 
 /// Sets the width of the error bar lines. Overridden in QwtErrorPlotCurve.
-void ErrorBarSettings::setWidth(double w)
-{
-  m_width = w;
-}
+void ErrorBarSettings::setWidth(double w) { m_width = w; }
 
 /// Returns the color of the error bars. Overridden in QwtErrorPlotCurve.
-QColor ErrorBarSettings::color() const
-{
-  return m_color;
-}
+QColor ErrorBarSettings::color() const { return m_color; }
 
 /// Sets the color of the error bars. Overridden in QwtErrorPlotCurve.
-void ErrorBarSettings::setColor(const QColor& c)
-{
+void ErrorBarSettings::setColor(const QColor &c) {
   m_color = c;
   m_defaultColor = false;
 }
 
 /// Returns whether the error bar lines are drawn through any symbol
-bool ErrorBarSettings::throughSymbol() const
-{
-  return m_through;
-}
+bool ErrorBarSettings::throughSymbol() const { return m_through; }
 
 /// Sets whether to draw through any symbol
-void ErrorBarSettings::drawThroughSymbol(bool yes)
-{
-  m_through=yes;
-}
+void ErrorBarSettings::drawThroughSymbol(bool yes) { m_through = yes; }
 
 /// Returns whether these error bars will be drawn on the positive side
-bool ErrorBarSettings::plusSide() const
-{
-  return m_plus;
-}
+bool ErrorBarSettings::plusSide() const { return m_plus; }
 
 /// Set whether these error bars will be drawn on the positive side
-void ErrorBarSettings::drawPlusSide(bool yes)
-{
-  m_plus=yes;
-}
+void ErrorBarSettings::drawPlusSide(bool yes) { m_plus = yes; }
 
 /// Returns whether these error bars will be drawn on the negative side
-bool ErrorBarSettings::minusSide() const
-{
-  return m_minus;
-}
+bool ErrorBarSettings::minusSide() const { return m_minus; }
 
 /// Set whether these error bars will be drawn on the negative side
-void ErrorBarSettings::drawMinusSide(bool yes)
-{
-  m_minus=yes;
-}
+void ErrorBarSettings::drawMinusSide(bool yes) { m_minus = yes; }
 
 /// Write the settings to a tab-separated string. Used when saving a project.
-QString ErrorBarSettings::toString() const
-{
-  // Be sure to go through the (virtual) methods because some are overridden in a derived class
-  QString s = QString::number(this->width())+"\t";
-  s += QString::number(this->capLength())+"\t";
-  s += this->color().name()+"\t";
-  s += QString::number(this->throughSymbol())+"\t";
-  s += QString::number(this->plusSide())+"\t";
+QString ErrorBarSettings::toString() const {
+  // Be sure to go through the (virtual) methods because some are overridden in
+  // a derived class
+  QString s = QString::number(this->width()) + "\t";
+  s += QString::number(this->capLength()) + "\t";
+  s += this->color().name() + "\t";
+  s += QString::number(this->throughSymbol()) + "\t";
+  s += QString::number(this->plusSide()) + "\t";
   s += QString::number(this->minusSide());
 
   return s;
 }
 
 /// Set the attributes from a tab-separated string. Used when loading a project
-void ErrorBarSettings::fromString(const QString& settings)
-{
+void ErrorBarSettings::fromString(const QString &settings) {
   const QStringList settingslist = settings.split("\t");
   // Try to spot if something changes upstream
-  assert( settingslist.size() == 6 );
-  if ( settingslist.size() != 6 ) return;
+  assert(settingslist.size() == 6);
+  if (settingslist.size() != 6)
+    return;
 
   this->setWidth(settingslist[0].toDouble());
   this->setCapLength(settingslist[1].toInt());
@@ -112,5 +77,3 @@ void ErrorBarSettings::fromString(const QString& settings)
   this->drawPlusSide(settingslist[4].toInt());
   this->drawMinusSide(settingslist[5].toInt());
 }
-
-
diff --git a/MantidPlot/src/Mantid/ErrorBarSettings.h b/MantidPlot/src/Mantid/ErrorBarSettings.h
index 68e5af461b8634bca389f0deff8a434dcdddcf75..d22116b4285c0eaa4d3ab62d7dec326beb4b8657 100644
--- a/MantidPlot/src/Mantid/ErrorBarSettings.h
+++ b/MantidPlot/src/Mantid/ErrorBarSettings.h
@@ -5,9 +5,11 @@
 #include <QColor>
 
 /** Holds the settings for how a set of error bars are to be drawn.
-    The class is a QObject purely so that our python proxy objects will work with it.
+    The class is a QObject purely so that our python proxy objects will work
+   with it.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -24,8 +26,7 @@
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
-class ErrorBarSettings : public QObject
-{
+class ErrorBarSettings : public QObject {
   Q_OBJECT
 public:
   explicit ErrorBarSettings(QObject *parent = 0);
@@ -37,7 +38,7 @@ public:
   virtual void setWidth(double w);
 
   virtual QColor color() const;
-  virtual void setColor(const QColor& c);
+  virtual void setColor(const QColor &c);
 
   bool throughSymbol() const;
   void drawThroughSymbol(bool yes);
@@ -49,18 +50,19 @@ public:
   void drawMinusSide(bool yes);
 
   QString toString() const;
-  void fromString(const QString& settings);
+  void fromString(const QString &settings);
 
 private:
   int m_cap;      ///< Length of the bar cap decoration
   bool m_plus;    ///< Whether to draw these errors on the positive side
   bool m_minus;   ///< Whether to draw these errors on the negative side
   bool m_through; ///< Whether to draw through any symbol on the curve
-  
+
   double m_width; ///< Width of the error bars (only used for Mantid error bars)
-  QColor m_color;  ///< Color of the error bars (only used for Mantid error bars)
+  QColor m_color; ///< Color of the error bars (only used for Mantid error bars)
 
-  bool m_defaultColor; ///< Whether the color has been explicitly set via setColor();
+  bool m_defaultColor; ///< Whether the color has been explicitly set via
+  /// setColor();
 
   friend class MantidCurve;
   friend class MantidMatrixCurve;
diff --git a/MantidPlot/src/Mantid/FirstTimeSetup.cpp b/MantidPlot/src/Mantid/FirstTimeSetup.cpp
index ba4a3d96f6b41a4ccc0a62f1490d098732432b97..74aa9f638889cbcd8c5040b2e47555e25f970221 100644
--- a/MantidPlot/src/Mantid/FirstTimeSetup.cpp
+++ b/MantidPlot/src/Mantid/FirstTimeSetup.cpp
@@ -9,75 +9,82 @@
 #include <QSettings>
 #include <QUrl>
 
-FirstTimeSetup::FirstTimeSetup(QWidget *parent) : QDialog(parent)
-{
+FirstTimeSetup::FirstTimeSetup(QWidget *parent) : QDialog(parent) {
   m_uiForm.setupUi(this);
   initLayout();
 }
 
-FirstTimeSetup::~FirstTimeSetup()
-{
-}
+FirstTimeSetup::~FirstTimeSetup() {}
 
-void FirstTimeSetup::initLayout()
-{
+void FirstTimeSetup::initLayout() {
   this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
-  this->setWindowTitle(this->windowTitle() + " " + Mantid::Kernel::MantidVersion::version());
+  this->setWindowTitle(this->windowTitle() + " " +
+                       Mantid::Kernel::MantidVersion::version());
 
   setFixedSize(size());
-  m_uiForm.lblVersion->setText(m_uiForm.lblVersion->text() + Mantid::Kernel::MantidVersion::version());
+  m_uiForm.lblVersion->setText(m_uiForm.lblVersion->text() +
+                               Mantid::Kernel::MantidVersion::version());
 
   connect(m_uiForm.pbConfirm, SIGNAL(clicked()), this, SLOT(confirm()));
   connect(m_uiForm.pbCancel, SIGNAL(clicked()), this, SLOT(cancel()));
 
-  connect(m_uiForm.pbMUD, SIGNAL(clicked()), this, SLOT(openManageUserDirectories()));
-  connect(m_uiForm.clbReleaseNotes, SIGNAL(clicked()), this, SLOT(openReleaseNotes()));
-  connect(m_uiForm.clbSampleDatasets, SIGNAL(clicked()), this, SLOT(openSampleDatasets()));
-  connect(m_uiForm.clbMantidIntroduction, SIGNAL(clicked()), this, SLOT(openMantidIntroduction()));
-  connect(m_uiForm.clbPythonIntroduction, SIGNAL(clicked()), this, SLOT(openPythonIntroduction()));
-  connect(m_uiForm.clbPythonInMantid, SIGNAL(clicked()), this, SLOT(openPythonInMantid()));
-  connect(m_uiForm.clbExtendingMantid, SIGNAL(clicked()), this, SLOT(openExtendingMantid()));
-
-  //set first use
+  connect(m_uiForm.pbMUD, SIGNAL(clicked()), this,
+          SLOT(openManageUserDirectories()));
+  connect(m_uiForm.clbReleaseNotes, SIGNAL(clicked()), this,
+          SLOT(openReleaseNotes()));
+  connect(m_uiForm.clbSampleDatasets, SIGNAL(clicked()), this,
+          SLOT(openSampleDatasets()));
+  connect(m_uiForm.clbMantidIntroduction, SIGNAL(clicked()), this,
+          SLOT(openMantidIntroduction()));
+  connect(m_uiForm.clbPythonIntroduction, SIGNAL(clicked()), this,
+          SLOT(openPythonIntroduction()));
+  connect(m_uiForm.clbPythonInMantid, SIGNAL(clicked()), this,
+          SLOT(openPythonInMantid()));
+  connect(m_uiForm.clbExtendingMantid, SIGNAL(clicked()), this,
+          SLOT(openExtendingMantid()));
+
+  // set first use
   QSettings settings;
   settings.beginGroup("Mantid/FirstUse");
-  const bool doNotShowUntilNextRelease = settings.value("DoNotShowUntilNextRelease", 0).toInt();
+  const bool doNotShowUntilNextRelease =
+      settings.value("DoNotShowUntilNextRelease", 0).toInt();
   settings.endGroup();
   m_uiForm.chkDoNotShowUntilNextRelease->setChecked(doNotShowUntilNextRelease);
 
   // Populate list of facilities
   m_uiForm.cbFacility->clear();
   auto faclist = Mantid::Kernel::ConfigService::Instance().getFacilityNames();
-  for ( auto it = faclist.begin(); it != faclist.end(); ++it )
-  {
+  for (auto it = faclist.begin(); it != faclist.end(); ++it) {
     m_uiForm.cbFacility->addItem(QString::fromStdString(*it));
   }
 
-  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
+  Mantid::Kernel::ConfigServiceImpl &config =
+      Mantid::Kernel::ConfigService::Instance();
   std::string facility = config.getString("default.facility", true);
-  m_uiForm.cbFacility->setCurrentIndex(m_uiForm.cbFacility->findText(
-    QString::fromStdString(facility)));
+  m_uiForm.cbFacility->setCurrentIndex(
+      m_uiForm.cbFacility->findText(QString::fromStdString(facility)));
 
-  //set instrument
+  // set instrument
   std::string instrument = config.getString("default.instrument", true);
   m_uiForm.cbInstrument->updateInstrumentOnSelection(false);
-  m_uiForm.cbInstrument->setCurrentIndex(m_uiForm.cbInstrument->findText(
-    QString::fromStdString(instrument)));
-  connect(m_uiForm.cbFacility, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(facilitySelected(const QString &)));
-
-  //set chkAllowUsageData
-  std::string isUsageReportEnabled = config.getString("usagereports.enabled", true);
-  if (isUsageReportEnabled == "0")
-  {
+  m_uiForm.cbInstrument->setCurrentIndex(
+      m_uiForm.cbInstrument->findText(QString::fromStdString(instrument)));
+  connect(m_uiForm.cbFacility, SIGNAL(currentIndexChanged(const QString &)),
+          this, SLOT(facilitySelected(const QString &)));
+
+  // set chkAllowUsageData
+  std::string isUsageReportEnabled =
+      config.getString("usagereports.enabled", true);
+  if (isUsageReportEnabled == "0") {
     m_uiForm.chkAllowUsageData->setChecked(false);
   }
-  connect(m_uiForm.chkAllowUsageData, SIGNAL(stateChanged (int)), this, SLOT(allowUsageDataStateChanged(int)));
+  connect(m_uiForm.chkAllowUsageData, SIGNAL(stateChanged(int)), this,
+          SLOT(allowUsageDataStateChanged(int)));
 
   QString stlyeName = QApplication::style()->metaObject()->className();
-  if((stlyeName=="QMotifStyle") || (stlyeName=="QCDEStyle"))
-  {
-    //add stylesheet formatting for other environemnts
-    QString ss =  this->styleSheet();
+  if ((stlyeName == "QMotifStyle") || (stlyeName == "QCDEStyle")) {
+    // add stylesheet formatting for other environemnts
+    QString ss = this->styleSheet();
     ss += "\n"
           "QDialog#FirstTimeSetup QCommandLinkButton {"
           " background-color: rgba(255, 255, 255, 0);"
@@ -85,59 +92,65 @@ void FirstTimeSetup::initLayout()
           "}"
           "\n"
           "QDialog#FirstTimeSetup QCommandLinkButton:hover {"
-	        "  background-color: rgba(255, 255, 255, 128);"
+          "  background-color: rgba(255, 255, 255, 128);"
           "}";
     this->setStyleSheet(ss);
   }
 }
 
-
 void FirstTimeSetup::confirm() {
-  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
+  Mantid::Kernel::ConfigServiceImpl &config =
+      Mantid::Kernel::ConfigService::Instance();
   std::string filename = config.getUserFilename();
-  config.setString("default.facility", m_uiForm.cbFacility->currentText().toStdString());
-  config.setString("default.instrument", m_uiForm.cbInstrument->currentText().toStdString());
-  config.setString("usagereports.enabled", (m_uiForm.chkAllowUsageData->isChecked()? "1" : "0"));
+  config.setString("default.facility",
+                   m_uiForm.cbFacility->currentText().toStdString());
+  config.setString("default.instrument",
+                   m_uiForm.cbInstrument->currentText().toStdString());
+  config.setString("usagereports.enabled",
+                   (m_uiForm.chkAllowUsageData->isChecked() ? "1" : "0"));
   config.saveConfig(filename);
-   
+
   QSettings settings;
   settings.beginGroup("Mantid/FirstUse");
-  settings.setValue("DoNotShowUntilNextRelease", (m_uiForm.chkDoNotShowUntilNextRelease->isChecked()? 1 : 0));
-  settings.setValue("LastVersion", QString::fromStdString(Mantid::Kernel::MantidVersion::releaseNotes()));
+  settings.setValue(
+      "DoNotShowUntilNextRelease",
+      (m_uiForm.chkDoNotShowUntilNextRelease->isChecked() ? 1 : 0));
+  settings.setValue(
+      "LastVersion",
+      QString::fromStdString(Mantid::Kernel::MantidVersion::releaseNotes()));
   settings.endGroup();
 
   // Close the dialog
   this->close();
 }
 
-void FirstTimeSetup::cancel()
-{
+void FirstTimeSetup::cancel() {
   // Close the dialog without saving any changes
   this->close();
 }
 
-void FirstTimeSetup::allowUsageDataStateChanged(int checkedState)
-{
-  if (checkedState == Qt::Unchecked)
-  {
+void FirstTimeSetup::allowUsageDataStateChanged(int checkedState) {
+  if (checkedState == Qt::Unchecked) {
     QMessageBox msgBox(this);
     msgBox.setWindowTitle("Mantid: Report Usage Data ");
-    msgBox.setTextFormat(Qt::RichText);   //this is what makes the links clickable
-    msgBox.setText("Are you sure you want to disable reporting <a href='http://reports.mantidproject.org'>usage data</a>?");
-    msgBox.setInformativeText("All usage data is anonymous and untraceable.\n"
-      "We use the usage data to inform the future development of Mantid.\n"
-      "If you click \"Yes\" aspects you need risk being deprecated in "
-      "future versions if we think they are not used.\n\n"
-      "Are you sure you still want to disable reporting usage data?\n"
-      "Please click \"No\".");
+    msgBox.setTextFormat(Qt::RichText); // this is what makes the links
+                                        // clickable
+    msgBox.setText("Are you sure you want to disable reporting <a "
+                   "href='http://reports.mantidproject.org'>usage data</a>?");
+    msgBox.setInformativeText(
+        "All usage data is anonymous and untraceable.\n"
+        "We use the usage data to inform the future development of Mantid.\n"
+        "If you click \"Yes\" aspects you need risk being deprecated in "
+        "future versions if we think they are not used.\n\n"
+        "Are you sure you still want to disable reporting usage data?\n"
+        "Please click \"No\".");
     msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
     msgBox.setDefaultButton(QMessageBox::No);
     msgBox.setEscapeButton(QMessageBox::No);
     msgBox.setIcon(QMessageBox::Question);
-    
+
     int ret = msgBox.exec();
-    if ((ret == QMessageBox::No) || (ret == QMessageBox::NoButton))
-    {
+    if ((ret == QMessageBox::No) || (ret == QMessageBox::NoButton)) {
       // No was clicked, or no button was clicked
       // set the checkbox back to checked
       m_uiForm.chkAllowUsageData->setCheckState(Qt::Checked);
@@ -145,42 +158,40 @@ void FirstTimeSetup::allowUsageDataStateChanged(int checkedState)
   }
 }
 
-void FirstTimeSetup::facilitySelected(const QString & facility)
-{
+void FirstTimeSetup::facilitySelected(const QString &facility) {
   m_uiForm.cbInstrument->fillWithInstrumentsFromFacility(facility);
 }
 
-void FirstTimeSetup::openManageUserDirectories()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+void FirstTimeSetup::openManageUserDirectories() {
+  MantidQt::API::ManageUserDirectories *ad =
+      new MantidQt::API::ManageUserDirectories(this);
   ad->setAttribute(Qt::WA_DeleteOnClose);
   ad->show();
   ad->setFocus();
   // cppcheck-suppress memleak
 }
 
-void FirstTimeSetup::openReleaseNotes()
-{
-  QDesktopServices::openUrl(QUrl(QString::fromStdString(Mantid::Kernel::MantidVersion::releaseNotes())));
+void FirstTimeSetup::openReleaseNotes() {
+  QDesktopServices::openUrl(QUrl(
+      QString::fromStdString(Mantid::Kernel::MantidVersion::releaseNotes())));
 }
 
-void FirstTimeSetup::openSampleDatasets()
-{
+void FirstTimeSetup::openSampleDatasets() {
   QDesktopServices::openUrl(QUrl("http://download.mantidproject.org"));
 }
-void FirstTimeSetup::openMantidIntroduction()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Mantid_Basic_Course"));
+void FirstTimeSetup::openMantidIntroduction() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/Mantid_Basic_Course"));
 }
-void FirstTimeSetup::openPythonIntroduction()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Introduction_To_Python"));
+void FirstTimeSetup::openPythonIntroduction() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/Introduction_To_Python"));
 }
-void FirstTimeSetup::openPythonInMantid()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Python_In_Mantid"));
+void FirstTimeSetup::openPythonInMantid() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/Python_In_Mantid"));
 }
-void FirstTimeSetup::openExtendingMantid()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Extending_Mantid_With_Python"));
+void FirstTimeSetup::openExtendingMantid() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/Extending_Mantid_With_Python"));
 }
diff --git a/MantidPlot/src/Mantid/FirstTimeSetup.h b/MantidPlot/src/Mantid/FirstTimeSetup.h
index 8ff69d73e919b461ae35b7428aeb7f736eb77c21..638a23fc8cc38cfeecafd63793c66d741553df2a 100644
--- a/MantidPlot/src/Mantid/FirstTimeSetup.h
+++ b/MantidPlot/src/Mantid/FirstTimeSetup.h
@@ -9,8 +9,7 @@
 *
 */
 
-class FirstTimeSetup : public QDialog
-{
+class FirstTimeSetup : public QDialog {
   Q_OBJECT
 
 public:
@@ -32,10 +31,9 @@ private slots:
   void openPythonInMantid();
   void openExtendingMantid();
 
-  void facilitySelected(const QString& facility);
+  void facilitySelected(const QString &facility);
   void openManageUserDirectories();
 
-
 private:
   Ui::FirstTimeSetup m_uiForm;
 };
diff --git a/MantidPlot/src/Mantid/FitParameterTie.cpp b/MantidPlot/src/Mantid/FitParameterTie.cpp
index 28bdb2c7bc4fbed6c23d4ed7e02c32d6ef078c71..21d7d1059c7f77c32eb8c704868731034b78d38b 100644
--- a/MantidPlot/src/Mantid/FitParameterTie.cpp
+++ b/MantidPlot/src/Mantid/FitParameterTie.cpp
@@ -4,16 +4,14 @@
 #include <stdexcept>
 
 /// Constructor
-FitParameterTie::FitParameterTie(boost::shared_ptr<Mantid::API::CompositeFunction> cf)
-:m_compositeFunction(cf),m_prop(0)
-{}
+FitParameterTie::FitParameterTie(
+    boost::shared_ptr<Mantid::API::CompositeFunction> cf)
+    : m_compositeFunction(cf), m_prop(0) {}
 
 /// Destructor
-FitParameterTie::~FitParameterTie()
-{
-  if (m_prop)
-  {
-    //delete m_prop;
+FitParameterTie::~FitParameterTie() {
+  if (m_prop) {
+    // delete m_prop;
   }
 }
 
@@ -21,142 +19,122 @@ FitParameterTie::~FitParameterTie()
  * placeholders (#0,#1,#2) to make it easier to edit afterwards.
  * @param estr :: The tying expression , e.g. "f1.Sigma = 2*f0.Sigma + 1"
  */
-void FitParameterTie::set(const QString& estr)
-{
+void FitParameterTie::set(const QString &estr) {
   int ieq = estr.indexOf('=');
-  if (ieq < 0)
-  {
-    throw std::invalid_argument("The tie expression doesn't contain the tied parameter.\n"
-      "Syntax: <tied_name> = <tying_expression>");
+  if (ieq < 0) {
+    throw std::invalid_argument(
+        "The tie expression doesn't contain the tied parameter.\n"
+        "Syntax: <tied_name> = <tying_expression>");
   }
 
-  if (ieq == estr.size())
-  {
+  if (ieq == estr.size()) {
     throw std::invalid_argument("The tying expression is missing.\n"
-      "Syntax: <tied_name> = <tying_expression>");
+                                "Syntax: <tied_name> = <tying_expression>");
   }
 
-  if (estr.mid(ieq+1).trimmed().isEmpty())
-  {
+  if (estr.mid(ieq + 1).trimmed().isEmpty()) {
     throw std::invalid_argument("The tying expression is missing.\n"
-      "Syntax: <tied_name> = <tying_expression>");
+                                "Syntax: <tied_name> = <tying_expression>");
   }
 
   QString parName = estr.left(ieq).trimmed();
 
-  // rx matches function identifiers in the parameter names and captures the function index:
+  // rx matches function identifiers in the parameter names and captures the
+  // function index:
   // for f12.Sigma rx.cap(1).toInt() returns 12
   QRegExp rx("\\bf(\\d+)\\.");
 
-  if (rx.indexIn(parName) < 0)
-  {
-    throw std::invalid_argument("Parameter names must contain function identifiers:\n"
-      "e.g. f0.Sigma, f5.FWHM");
+  if (rx.indexIn(parName) < 0) {
+    throw std::invalid_argument(
+        "Parameter names must contain function identifiers:\n"
+        "e.g. f0.Sigma, f5.FWHM");
   }
 
   m_expr = estr;
-  for(int i=rx.indexIn(m_expr);i>=0;)
-  {
+  for (int i = rx.indexIn(m_expr); i >= 0;) {
     int iFun = rx.cap(1).toInt();
     int j = m_iFunctions.indexOf(iFun);
-    if (j < 0)
-    {
+    if (j < 0) {
       j = m_iFunctions.size();
       m_iFunctions.append(iFun);
     }
-    QString s = "#"+QString::number(j)+".";
-    m_expr.replace(rx.pos(),rx.cap().size(),s);
-    i=rx.indexIn(m_expr,i+rx.cap().size());
+    QString s = "#" + QString::number(j) + ".";
+    m_expr.replace(rx.pos(), rx.cap().size(), s);
+    i = rx.indexIn(m_expr, i + rx.cap().size());
   }
-
 }
 
 /// The tying expression
-QString FitParameterTie::expr(bool removePrefix)const
-{
+QString FitParameterTie::expr(bool removePrefix) const {
   QString str = m_expr;
-  for(int j=0;j<m_iFunctions.size();j++)
-  {
-    QString ph = "#"+QString::number(j);
+  for (int j = 0; j < m_iFunctions.size(); j++) {
+    QString ph = "#" + QString::number(j);
     QString fi;
-    if (removePrefix)
-    {
+    if (removePrefix) {
       ph += ".";
       fi = "";
+    } else {
+      fi = "f" + QString::number(m_iFunctions[j]);
     }
-    else
-    {
-      fi = "f"+QString::number(m_iFunctions[j]);
-    }
-    str.replace(ph,fi);
+    str.replace(ph, fi);
   }
   return str;
 }
 
 /// The parameter name
-QString FitParameterTie::parName()const
-{
+QString FitParameterTie::parName() const {
   QString str = m_expr.left(m_expr.indexOf('=')).trimmed();
-  for(int j=0;j<m_iFunctions.size();j++)
-  {
-    QString ph = "#"+QString::number(j);
-    QString fi = "f"+QString::number(m_iFunctions[j]);
-    str.replace(ph,fi);
+  for (int j = 0; j < m_iFunctions.size(); j++) {
+    QString ph = "#" + QString::number(j);
+    QString fi = "f" + QString::number(m_iFunctions[j]);
+    str.replace(ph, fi);
   }
   return str;
 }
 
 /// Returns the right-hand side of the expression
-QString FitParameterTie::exprRHS()const
-{
+QString FitParameterTie::exprRHS() const {
   QString ex = expr();
   int ieq = ex.indexOf('=');
-  if (ieq<0)
-  {
+  if (ieq < 0) {
     return ex;
   }
-  if (ieq==ex.size()-1)
-  {
+  if (ieq == ex.size() - 1) {
     return "";
   }
-  return ex.mid(ieq+1);
+  return ex.mid(ieq + 1);
 }
 
 /**
- * When a new function is added the function indeces in the tying expression must
+ * When a new function is added the function indeces in the tying expression
+ * must
  * be changed.
- * @param i :: The index at wich the function is inserted. All old indeces starting
+ * @param i :: The index at wich the function is inserted. All old indeces
+ * starting
  *   from i (inclusive) must be incremented.
  */
-void FitParameterTie::functionInserted(int i)
-{
-  for(int j=0;j<m_iFunctions.size();j++)
-  {
-    if (m_iFunctions[j] >= i)
-    {
+void FitParameterTie::functionInserted(int i) {
+  for (int j = 0; j < m_iFunctions.size(); j++) {
+    if (m_iFunctions[j] >= i) {
       m_iFunctions[j]++;
     }
   }
-
 }
 
 /**
  * When a function is deleted the function indeces in the tying expression must
- * be changed or the tie may become invalid if the deleted function is used in the tie.
+ * be changed or the tie may become invalid if the deleted function is used in
+ * the tie.
  * @param i :: The index of the deleted function. All old indeces starting
  *   from i+1 must be decremented.
  * @return true if the tie remains valid and false otherwise.
  */
-bool FitParameterTie::functionDeleted(int i)
-{
-  for(int j=0;j<m_iFunctions.size();j++)
-  {
-    if (m_iFunctions[j] == i)
-    {
+bool FitParameterTie::functionDeleted(int i) {
+  for (int j = 0; j < m_iFunctions.size(); j++) {
+    if (m_iFunctions[j] == i) {
       return false;
     }
-    if (m_iFunctions[j] > i)
-    {
+    if (m_iFunctions[j] > i) {
       m_iFunctions[j]--;
     }
   }
diff --git a/MantidPlot/src/Mantid/FitParameterTie.h b/MantidPlot/src/Mantid/FitParameterTie.h
index 8ad449c1a49de4ac12550cafe79d3e635a89d2fb..82635b10f715a0fc644b854ee4f43364e3fefe8f 100644
--- a/MantidPlot/src/Mantid/FitParameterTie.h
+++ b/MantidPlot/src/Mantid/FitParameterTie.h
@@ -5,12 +5,10 @@
 #include <QList>
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-  namespace API
-  {
-    class CompositeFunction;
-  }
+namespace Mantid {
+namespace API {
+class CompositeFunction;
+}
 }
 
 class QtProperty;
@@ -18,8 +16,7 @@ class QtProperty;
 /**
  * Class FitParameterTie is for editing parameter ties in Mantid functions.
  */
-class FitParameterTie
-{
+class FitParameterTie {
 public:
   /// Constructor
   explicit FitParameterTie(
@@ -27,23 +24,25 @@ public:
   /// Destructor
   ~FitParameterTie();
   /// Set the tying expression, e.g. "f1.Sigma = 2*f0.Sigma + 1"
-  void set(const QString& estr);
+  void set(const QString &estr);
   /// The tying expression
-  QString expr(bool removePrefix=false)const;
+  QString expr(bool removePrefix = false) const;
   /// The parameter name
-  QString parName()const;
+  QString parName() const;
   /// Returns the right-hand side of the expression
-  QString exprRHS()const;
-  /// Mofifies the function indeces in response to insertion of a new function into 
+  QString exprRHS() const;
+  /// Mofifies the function indeces in response to insertion of a new function
+  /// into
   /// the composite function
   void functionInserted(int i);
   /// Mofifies the function indeces in response to deletion of a function from
   /// the composite function
   bool functionDeleted(int i);
   /// Set property
-  void setProperty(QtProperty* prop){m_prop=prop;}
+  void setProperty(QtProperty *prop) { m_prop = prop; }
   /// Get property
-  QtProperty* getProperty()const{return m_prop;}
+  QtProperty *getProperty() const { return m_prop; }
+
 private:
   /// The tying expression
   QString m_expr;
@@ -52,7 +51,7 @@ private:
   /// A copy of the edited function
   boost::shared_ptr<Mantid::API::CompositeFunction> m_compositeFunction;
   /// The property
-  QtProperty* m_prop;
+  QtProperty *m_prop;
 };
 
 #endif /* FITPARAMETERTIE_H */
diff --git a/MantidPlot/src/Mantid/FlowLayout.cpp b/MantidPlot/src/Mantid/FlowLayout.cpp
index 789f61aebc0bad1a9b56ca556f458b413cdee338..e45d988c836642a8d3647312db757ecc1a422dd0 100644
--- a/MantidPlot/src/Mantid/FlowLayout.cpp
+++ b/MantidPlot/src/Mantid/FlowLayout.cpp
@@ -42,148 +42,121 @@
 
 #include "FlowLayout.h"
 FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing)
-    : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing)
-{
-    setContentsMargins(margin, margin, margin, margin);
+    : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) {
+  setContentsMargins(margin, margin, margin, margin);
 }
 
 FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing)
-    : m_hSpace(hSpacing), m_vSpace(vSpacing)
-{
-    setContentsMargins(margin, margin, margin, margin);
+    : m_hSpace(hSpacing), m_vSpace(vSpacing) {
+  setContentsMargins(margin, margin, margin, margin);
 }
 
-FlowLayout::~FlowLayout()
-{
-    QLayoutItem *item;
-    while ((item = takeAt(0)))
-        delete item;
+FlowLayout::~FlowLayout() {
+  QLayoutItem *item;
+  while ((item = takeAt(0)))
+    delete item;
 }
 
-void FlowLayout::addItem(QLayoutItem *item)
-{
-    itemList.append(item);
-}
+void FlowLayout::addItem(QLayoutItem *item) { itemList.append(item); }
 
-int FlowLayout::horizontalSpacing() const
-{
-    if (m_hSpace >= 0) {
-        return m_hSpace;
-    } else {
-        return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
-    }
+int FlowLayout::horizontalSpacing() const {
+  if (m_hSpace >= 0) {
+    return m_hSpace;
+  } else {
+    return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
+  }
 }
 
-int FlowLayout::verticalSpacing() const
-{
-    if (m_vSpace >= 0) {
-        return m_vSpace;
-    } else {
-        return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
-    }
+int FlowLayout::verticalSpacing() const {
+  if (m_vSpace >= 0) {
+    return m_vSpace;
+  } else {
+    return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
+  }
 }
 
-int FlowLayout::count() const
-{
-    return itemList.size();
-}
+int FlowLayout::count() const { return itemList.size(); }
 
-QLayoutItem *FlowLayout::itemAt(int index) const
-{
-    return itemList.value(index);
+QLayoutItem *FlowLayout::itemAt(int index) const {
+  return itemList.value(index);
 }
 
-QLayoutItem *FlowLayout::takeAt(int index)
-{
-    if (index >= 0 && index < itemList.size())
-        return itemList.takeAt(index);
-    else
-        return 0;
-}
-
-Qt::Orientations FlowLayout::expandingDirections() const
-{
+QLayoutItem *FlowLayout::takeAt(int index) {
+  if (index >= 0 && index < itemList.size())
+    return itemList.takeAt(index);
+  else
     return 0;
 }
 
-bool FlowLayout::hasHeightForWidth() const
-{
-    return true;
-}
+Qt::Orientations FlowLayout::expandingDirections() const { return 0; }
 
-int FlowLayout::heightForWidth(int width) const
-{
-    int height = doLayout(QRect(0, 0, width, 0), true);
-    return height;
-}
+bool FlowLayout::hasHeightForWidth() const { return true; }
 
-void FlowLayout::setGeometry(const QRect &rect)
-{
-    QLayout::setGeometry(rect);
-    doLayout(rect, false);
+int FlowLayout::heightForWidth(int width) const {
+  int height = doLayout(QRect(0, 0, width, 0), true);
+  return height;
 }
 
-QSize FlowLayout::sizeHint() const
-{
-    return minimumSize();
+void FlowLayout::setGeometry(const QRect &rect) {
+  QLayout::setGeometry(rect);
+  doLayout(rect, false);
 }
 
-QSize FlowLayout::minimumSize() const
-{
-    QSize size;
-    QLayoutItem *item;
-    foreach (item, itemList)
-        size = size.expandedTo(item->minimumSize());
+QSize FlowLayout::sizeHint() const { return minimumSize(); }
 
-    size += QSize(2*margin(), 2*margin());
-    return size;
-}
+QSize FlowLayout::minimumSize() const {
+  QSize size;
+  QLayoutItem *item;
+  foreach (item, itemList)
+    size = size.expandedTo(item->minimumSize());
 
-int FlowLayout::doLayout(const QRect &rect, bool testOnly) const
-{
-    int left, top, right, bottom;
-    getContentsMargins(&left, &top, &right, &bottom);
-    QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
-    int x = effectiveRect.x();
-    int y = effectiveRect.y();
-    int lineHeight = 0;
-
-    QLayoutItem *item;
-    foreach (item, itemList) {
-        QWidget *wid = item->widget();
-        int spaceX = horizontalSpacing();
-        if (spaceX == -1)
-            spaceX = wid->style()->layoutSpacing(
-                QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
-        int spaceY = verticalSpacing();
-        if (spaceY == -1)
-            spaceY = wid->style()->layoutSpacing(
-                QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
-        int nextX = x + item->sizeHint().width() + spaceX;
-        if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) {
-            x = effectiveRect.x();
-            y = y + lineHeight + spaceY;
-            nextX = x + item->sizeHint().width() + spaceX;
-            lineHeight = 0;
-        }
-
-        if (!testOnly)
-            item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
-
-        x = nextX;
-        lineHeight = qMax(lineHeight, item->sizeHint().height());
-    }
-    return y + lineHeight - rect.y() + bottom;
+  size += QSize(2 * margin(), 2 * margin());
+  return size;
 }
-int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const
-{
-    QObject *parent = this->parent();
-    if (!parent) {
-        return -1;
-    } else if (parent->isWidgetType()) {
-        QWidget *pw = static_cast<QWidget *>(parent);
-        return pw->style()->pixelMetric(pm, 0, pw);
-    } else {
-        return static_cast<QLayout *>(parent)->spacing();
+
+int FlowLayout::doLayout(const QRect &rect, bool testOnly) const {
+  int left, top, right, bottom;
+  getContentsMargins(&left, &top, &right, &bottom);
+  QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
+  int x = effectiveRect.x();
+  int y = effectiveRect.y();
+  int lineHeight = 0;
+
+  QLayoutItem *item;
+  foreach (item, itemList) {
+    QWidget *wid = item->widget();
+    int spaceX = horizontalSpacing();
+    if (spaceX == -1)
+      spaceX = wid->style()->layoutSpacing(
+          QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
+    int spaceY = verticalSpacing();
+    if (spaceY == -1)
+      spaceY = wid->style()->layoutSpacing(
+          QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
+    int nextX = x + item->sizeHint().width() + spaceX;
+    if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) {
+      x = effectiveRect.x();
+      y = y + lineHeight + spaceY;
+      nextX = x + item->sizeHint().width() + spaceX;
+      lineHeight = 0;
     }
+
+    if (!testOnly)
+      item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
+
+    x = nextX;
+    lineHeight = qMax(lineHeight, item->sizeHint().height());
+  }
+  return y + lineHeight - rect.y() + bottom;
+}
+int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const {
+  QObject *parent = this->parent();
+  if (!parent) {
+    return -1;
+  } else if (parent->isWidgetType()) {
+    QWidget *pw = static_cast<QWidget *>(parent);
+    return pw->style()->pixelMetric(pm, 0, pw);
+  } else {
+    return static_cast<QLayout *>(parent)->spacing();
+  }
 }
diff --git a/MantidPlot/src/Mantid/FlowLayout.h b/MantidPlot/src/Mantid/FlowLayout.h
index 53da4e86613ac225f799c9566ea9efde3be0f1a4..6dfd605e1e13929a3831c8791d8c7210e9b8047a 100644
--- a/MantidPlot/src/Mantid/FlowLayout.h
+++ b/MantidPlot/src/Mantid/FlowLayout.h
@@ -44,33 +44,33 @@
 #include <QLayout>
 #include <QRect>
 #include <QWidgetItem>
-class FlowLayout : public QLayout
-{
+class FlowLayout : public QLayout {
 public:
-    FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);
-    FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);
-    ~FlowLayout() override;
+  FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1,
+             int vSpacing = -1);
+  FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);
+  ~FlowLayout() override;
 
-    void addItem(QLayoutItem *item) override;
-    int horizontalSpacing() const;
-    int verticalSpacing() const;
-    Qt::Orientations expandingDirections() const override;
-    bool hasHeightForWidth() const override;
-    int heightForWidth(int) const override;
-    int count() const override;
-    QLayoutItem *itemAt(int index) const override;
-    QSize minimumSize() const override;
-    void setGeometry(const QRect &rect) override;
-    QSize sizeHint() const override;
-    QLayoutItem *takeAt(int index) override;
+  void addItem(QLayoutItem *item) override;
+  int horizontalSpacing() const;
+  int verticalSpacing() const;
+  Qt::Orientations expandingDirections() const override;
+  bool hasHeightForWidth() const override;
+  int heightForWidth(int) const override;
+  int count() const override;
+  QLayoutItem *itemAt(int index) const override;
+  QSize minimumSize() const override;
+  void setGeometry(const QRect &rect) override;
+  QSize sizeHint() const override;
+  QLayoutItem *takeAt(int index) override;
 
 private:
-    int doLayout(const QRect &rect, bool testOnly) const;
-    int smartSpacing(QStyle::PixelMetric pm) const;
+  int doLayout(const QRect &rect, bool testOnly) const;
+  int smartSpacing(QStyle::PixelMetric pm) const;
 
-    QList<QLayoutItem *> itemList;
-    int m_hSpace;
-    int m_vSpace;
+  QList<QLayoutItem *> itemList;
+  int m_hSpace;
+  int m_vSpace;
 };
 
 #endif
diff --git a/MantidPlot/src/Mantid/IFunctionWrapper.cpp b/MantidPlot/src/Mantid/IFunctionWrapper.cpp
index 443f2214bf479cad6c80d80d3d2d77973c25fee1..e14fe24105152d69cd41c8d6a10517777d7476a7 100644
--- a/MantidPlot/src/Mantid/IFunctionWrapper.cpp
+++ b/MantidPlot/src/Mantid/IFunctionWrapper.cpp
@@ -3,25 +3,27 @@
 #include "MantidAPI/CompositeFunction.h"
 #include "MantidAPI/IPeakFunction.h"
 
-void IFunctionWrapper::setFunction(const QString& name)
-{
-  try
-  {
-    m_function = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(Mantid::API::FunctionFactory::Instance().createFunction(name.toStdString()));
-    m_compositeFunction = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(m_function);
-    m_peakFunction = boost::dynamic_pointer_cast<Mantid::API::IPeakFunction>(m_function);
-  }
-  catch(...)
-  {
+void IFunctionWrapper::setFunction(const QString &name) {
+  try {
+    m_function = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(
+        Mantid::API::FunctionFactory::Instance().createFunction(
+            name.toStdString()));
+    m_compositeFunction =
+        boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(m_function);
+    m_peakFunction =
+        boost::dynamic_pointer_cast<Mantid::API::IPeakFunction>(m_function);
+  } catch (...) {
     m_function.reset();
     m_compositeFunction.reset();
     m_peakFunction.reset();
   }
 }
 
-void IFunctionWrapper::setFunction(boost::shared_ptr<Mantid::API::IFunction> function)
-{
+void IFunctionWrapper::setFunction(
+    boost::shared_ptr<Mantid::API::IFunction> function) {
   m_function = function;
-  m_compositeFunction = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(m_function);
-  m_peakFunction = boost::dynamic_pointer_cast<Mantid::API::IPeakFunction>(m_function);
+  m_compositeFunction =
+      boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(m_function);
+  m_peakFunction =
+      boost::dynamic_pointer_cast<Mantid::API::IPeakFunction>(m_function);
 }
diff --git a/MantidPlot/src/Mantid/IFunctionWrapper.h b/MantidPlot/src/Mantid/IFunctionWrapper.h
index eed0cb7facb222ac86105d96a5646b8baf171686..6d0bbf2197b285c243256ad876bbce4fbf505976 100644
--- a/MantidPlot/src/Mantid/IFunctionWrapper.h
+++ b/MantidPlot/src/Mantid/IFunctionWrapper.h
@@ -4,34 +4,34 @@
 #include <boost/shared_ptr.hpp>
 #include <QObject>
 
-namespace Mantid
-{
-  namespace API
-  {
-    class IFunction;
-    class CompositeFunction;
-    class IPeakFunction;
-  }
+namespace Mantid {
+namespace API {
+class IFunction;
+class CompositeFunction;
+class IPeakFunction;
+}
 }
 
 /**
  * IFunctionWrapper is a wrapper for IFunction pointer which is a QObject
  * and can send and recieve signals.
  */
-class IFunctionWrapper: public QObject
-{
+class IFunctionWrapper : public QObject {
   Q_OBJECT
 public:
-
-  IFunctionWrapper():m_function(),m_compositeFunction(),m_peakFunction(){}
+  IFunctionWrapper() : m_function(), m_compositeFunction(), m_peakFunction() {}
 
   /// IFunction pointer
-  boost::shared_ptr<Mantid::API::IFunction> function(){return m_function;}
-  boost::shared_ptr<Mantid::API::CompositeFunction> compositeFunction(){return m_compositeFunction;}
-  boost::shared_ptr<Mantid::API::IPeakFunction> peakFunction(){return m_peakFunction;}
+  boost::shared_ptr<Mantid::API::IFunction> function() { return m_function; }
+  boost::shared_ptr<Mantid::API::CompositeFunction> compositeFunction() {
+    return m_compositeFunction;
+  }
+  boost::shared_ptr<Mantid::API::IPeakFunction> peakFunction() {
+    return m_peakFunction;
+  }
 
   /// Set a new function from a string
-  void setFunction(const QString& name);
+  void setFunction(const QString &name);
   /// Set a new function from a pointer
   void setFunction(boost::shared_ptr<Mantid::API::IFunction> function);
 
diff --git a/MantidPlot/src/Mantid/IMantidMatrixExtensionHandler.h b/MantidPlot/src/Mantid/IMantidMatrixExtensionHandler.h
index ed1ba4152bef6fb11ba93417c4873866b5544bb8..4a247eb8fb82f65336916e5f4ce97b0eba1f84a9 100644
--- a/MantidPlot/src/Mantid/IMantidMatrixExtensionHandler.h
+++ b/MantidPlot/src/Mantid/IMantidMatrixExtensionHandler.h
@@ -5,18 +5,22 @@
 #include "MantidKernel/Chainable.h"
 #include "boost/shared_ptr.hpp"
 
-class IMantidMatrixExtensionHandler : public Mantid::Kernel::Chainable<IMantidMatrixExtensionHandler> {
+class IMantidMatrixExtensionHandler
+    : public Mantid::Kernel::Chainable<IMantidMatrixExtensionHandler> {
 public:
   ~IMantidMatrixExtensionHandler() override {}
-  virtual void setNumberFormat(MantidMatrixTabExtension& extension,
+  virtual void setNumberFormat(MantidMatrixTabExtension &extension,
                                const QChar &format, int precision) = 0;
-  virtual void recordFormat(MantidMatrixTabExtension& extension, const QChar &format, int precision) = 0;
-  virtual QChar getFormat(MantidMatrixTabExtension& extension) = 0;
-  virtual int getPrecision(MantidMatrixTabExtension& extension) = 0;
-  virtual void setColumnWidth(MantidMatrixTabExtension& extension, int width, int numberOfColumns) = 0;
-  virtual int getColumnWidth(MantidMatrixTabExtension& extension) = 0;
-  virtual QTableView* getTableView(MantidMatrixTabExtension& extension) = 0;
-  virtual void setColumnWidthPreference(MantidMatrixTabExtension& extension, int width)  = 0;
-  virtual int getColumnWidthPreference(MantidMatrixTabExtension& extension) = 0;
+  virtual void recordFormat(MantidMatrixTabExtension &extension,
+                            const QChar &format, int precision) = 0;
+  virtual QChar getFormat(MantidMatrixTabExtension &extension) = 0;
+  virtual int getPrecision(MantidMatrixTabExtension &extension) = 0;
+  virtual void setColumnWidth(MantidMatrixTabExtension &extension, int width,
+                              int numberOfColumns) = 0;
+  virtual int getColumnWidth(MantidMatrixTabExtension &extension) = 0;
+  virtual QTableView *getTableView(MantidMatrixTabExtension &extension) = 0;
+  virtual void setColumnWidthPreference(MantidMatrixTabExtension &extension,
+                                        int width) = 0;
+  virtual int getColumnWidthPreference(MantidMatrixTabExtension &extension) = 0;
 };
 #endif
diff --git a/MantidPlot/src/Mantid/IProjectSerialisable.h b/MantidPlot/src/Mantid/IProjectSerialisable.h
index 24fdc5ab586fd9d8ed9987ce0163b121c56cf03e..4ff258ab8815108390de5731ef85b540537a6897 100644
--- a/MantidPlot/src/Mantid/IProjectSerialisable.h
+++ b/MantidPlot/src/Mantid/IProjectSerialisable.h
@@ -5,46 +5,48 @@
 
 class ApplicationWindow;
 
-namespace Mantid
-{
-
-  /**
-  Defines an interface to a MantidPlot class that can be saved into or loaded from a project.
-
-  @author Harry Jeffery, ISIS, RAL
-  @date 31/07/2014
-
-  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-  This file is part of Mantid.
-
-  Mantid is free software; you can redistribute it and/or modify
-  it under the terms of the GNU General Public License as published by
-  the Free Software Foundation; either version 3 of the License, or
-  (at your option) any later version.
-
-  Mantid is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-  GNU General Public License for more details.
-
-  You should have received a copy of the GNU General Public License
-  along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-  File change history is stored at: <https://github.com/mantidproject/mantid>
-  Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class IProjectSerialisable
-  {
-  public:
-    /// Virtual destructor (required by linker on some versions of OS X/Intel compiler)
-    virtual ~IProjectSerialisable() {}
-    /// Loads the given lines from the project file and applies them.
-    virtual void loadFromProject(const std::string& lines, ApplicationWindow* app, const int fileVersion) = 0;
-    /// Serialises to a string that can be saved to a project file.
-    virtual std::string saveToProject(ApplicationWindow* app) = 0;
-  };
+namespace Mantid {
+
+/**
+Defines an interface to a MantidPlot class that can be saved into or loaded from
+a project.
+
+@author Harry Jeffery, ISIS, RAL
+@date 31/07/2014
+
+Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class IProjectSerialisable {
+public:
+  /// Virtual destructor (required by linker on some versions of OS X/Intel
+  /// compiler)
+  virtual ~IProjectSerialisable() {}
+  /// Loads the given lines from the project file and applies them.
+  virtual void loadFromProject(const std::string &lines, ApplicationWindow *app,
+                               const int fileVersion) = 0;
+  /// Serialises to a string that can be saved to a project file.
+  virtual std::string saveToProject(ApplicationWindow *app) = 0;
+};
 
 } // namespace Mantid
 
-#endif  /* MANTID_API_IPROJECTSERIALISABLE_H_ */
+#endif /* MANTID_API_IPROJECTSERIALISABLE_H_ */
diff --git a/MantidPlot/src/Mantid/ImportWorkspaceDlg.h b/MantidPlot/src/Mantid/ImportWorkspaceDlg.h
index e714ee552f922ce3192c8079ed8fb0acf51e6acd..37baef4cf5613a91a023a9246e28abb957df4975 100644
--- a/MantidPlot/src/Mantid/ImportWorkspaceDlg.h
+++ b/MantidPlot/src/Mantid/ImportWorkspaceDlg.h
@@ -10,8 +10,7 @@ class QPushButton;
 class QCheckBox;
 class QString;
 
-class ImportWorkspaceDlg : public QDialog
-{
+class ImportWorkspaceDlg : public QDialog {
   Q_OBJECT
 
 public:
@@ -20,12 +19,11 @@ public:
 
   int getLowerLimit() { return lowerLimit; }
   int getUpperLimit() { return upperLimit; }
-  bool isFiltered(){ return filtered; }
-  double getMinValue(){ return minValue; }
-  double getMaxValue(){ return maxValue; }
+  bool isFiltered() { return filtered; }
+  double getMinValue() { return minValue; }
+  double getMaxValue() { return maxValue; }
 
 protected:
-
 private slots:
   void okClicked();
   void enableFilter(int state);
@@ -46,13 +44,12 @@ private:
   QLineEdit *lineHigh;
 
   QCheckBox *checkFilter;
-  //QLabel *labelFilterMaximum;
+  // QLabel *labelFilterMaximum;
   QLineEdit *lineMinimum;
   QLineEdit *lineMaximum;
 
   QPushButton *okButton;
   QPushButton *cancelButton;
-
 };
 
 #endif /* IMPORTWORKSPACEDLG_H */
diff --git a/MantidPlot/src/Mantid/InputHistory.cpp b/MantidPlot/src/Mantid/InputHistory.cpp
index 9b62b9152565bd5fd90fb760f8bbf5f9644cc65c..e0080174126f0171261d16dd592febc366f37814 100644
--- a/MantidPlot/src/Mantid/InputHistory.cpp
+++ b/MantidPlot/src/Mantid/InputHistory.cpp
@@ -7,156 +7,151 @@
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
 
-extern bool Algorithm_descriptor_name_less(const Algorithm_descriptor& d1,const Algorithm_descriptor& d2);
+extern bool Algorithm_descriptor_name_less(const Algorithm_descriptor &d1,
+                                           const Algorithm_descriptor &d2);
 
 /// Constructor
-InputHistoryImpl::InputHistoryImpl()
-{
-    QSettings settings;
-    settings.beginGroup("Mantid/Algorithms");
+InputHistoryImpl::InputHistoryImpl() {
+  QSettings settings;
+  settings.beginGroup("Mantid/Algorithms");
 
-    QStringList keys = settings.allKeys();
-    QStringList algNames;
-    QString prevName = "";
-    for(int i=0;i<keys.size();i++)
-    {
-        if (keys[i] != prevName)
-        {
-            prevName = keys[i].split("/")[0];
-            algNames<<prevName;
-        }
+  QStringList keys = settings.allKeys();
+  QStringList algNames;
+  QString prevName = "";
+  for (int i = 0; i < keys.size(); i++) {
+    if (keys[i] != prevName) {
+      prevName = keys[i].split("/")[0];
+      algNames << prevName;
     }
-    for(int i=0;i<algNames.size();i++)
-    {
-        QString algName = algNames[i];
-        QList< PropertyData > prop_hist_list;
-        settings.beginGroup(algName);
-        QStringList keys = settings.allKeys();
-        for(int i=0;i<keys.size();i++)
-        {
-            QString value = settings.value(keys[i]).toString();
-            PropertyData prop_hist(keys[i],value);
-            prop_hist_list.push_back(prop_hist);
-        }
-        settings.endGroup();
-        m_history[algName] = prop_hist_list;
+  }
+  for (int i = 0; i < algNames.size(); i++) {
+    QString algName = algNames[i];
+    QList<PropertyData> prop_hist_list;
+    settings.beginGroup(algName);
+    QStringList keys = settings.allKeys();
+    for (int i = 0; i < keys.size(); i++) {
+      QString value = settings.value(keys[i]).toString();
+      PropertyData prop_hist(keys[i], value);
+      prop_hist_list.push_back(prop_hist);
     }
     settings.endGroup();
+    m_history[algName] = prop_hist_list;
+  }
+  settings.endGroup();
 }
 
-void InputHistoryImpl::save()
-{
-    QSettings settings;
-    settings.beginGroup("Mantid/Algorithms");
-    QMapIterator<QString,QList< PropertyData > > alg(m_history);
-    while(alg.hasNext())
-    {
-        alg.next();
-        const QList< PropertyData >& prop_hist = alg.value();
-        settings.beginGroup(alg.key());
-        for(QList< PropertyData >::const_iterator prop=prop_hist.begin();prop!=prop_hist.end();++prop)
-            settings.setValue(prop->name,prop->value);
-        settings.endGroup();
-    }
+void InputHistoryImpl::save() {
+  QSettings settings;
+  settings.beginGroup("Mantid/Algorithms");
+  QMapIterator<QString, QList<PropertyData>> alg(m_history);
+  while (alg.hasNext()) {
+    alg.next();
+    const QList<PropertyData> &prop_hist = alg.value();
+    settings.beginGroup(alg.key());
+    for (QList<PropertyData>::const_iterator prop = prop_hist.begin();
+         prop != prop_hist.end(); ++prop)
+      settings.setValue(prop->name, prop->value);
     settings.endGroup();
+  }
+  settings.endGroup();
 }
 /**
      Upadates the non-default algorithm properties in the history.
      @param alg :: Pointer to the algorthm
 */
-void InputHistoryImpl::updateAlgorithm(Mantid::API::IAlgorithm_sptr alg)
-{
-    const std::vector< Property* >& props = alg->getProperties();
-    QList< PropertyData > prop_hist_list;
-    for(std::vector< Property* >::const_iterator prop=props.begin();prop!=props.end();++prop)
-    if (!(*prop)->isDefault())
-    {
-        PropertyData prop_hist(QString::fromStdString((*prop)->name()),QString::fromStdString((*prop)->value()));
-        prop_hist_list.push_back(prop_hist);
+void InputHistoryImpl::updateAlgorithm(Mantid::API::IAlgorithm_sptr alg) {
+  const std::vector<Property *> &props = alg->getProperties();
+  QList<PropertyData> prop_hist_list;
+  for (std::vector<Property *>::const_iterator prop = props.begin();
+       prop != props.end(); ++prop)
+    if (!(*prop)->isDefault()) {
+      PropertyData prop_hist(QString::fromStdString((*prop)->name()),
+                             QString::fromStdString((*prop)->value()));
+      prop_hist_list.push_back(prop_hist);
+    } else {
+      PropertyData prop_hist(QString::fromStdString((*prop)->name()), "");
+      prop_hist_list.push_back(prop_hist);
     }
-    else
-    {
-        PropertyData prop_hist(QString::fromStdString((*prop)->name()),"");
-        prop_hist_list.push_back(prop_hist);
-    }
-    m_history[QString::fromStdString(alg->name())] = prop_hist_list;
+  m_history[QString::fromStdString(alg->name())] = prop_hist_list;
 }
 
-void InputHistoryImpl::printAll()
-{
-    QMapIterator<QString,QList< PropertyData > > alg(m_history);
-    while(alg.hasNext())
-    {
-        alg.next();
-        std::cerr<<alg.key().toStdString()<<'\n';
-        const QList< PropertyData >& prop_list = alg.value();
-        for(QList< PropertyData >::const_iterator prop=prop_list.begin();prop!=prop_list.end();++prop)
-            std::cerr<<prop->name.toStdString()<<": "<<prop->value.toStdString()<<'\n';
-    }
+void InputHistoryImpl::printAll() {
+  QMapIterator<QString, QList<PropertyData>> alg(m_history);
+  while (alg.hasNext()) {
+    alg.next();
+    std::cerr << alg.key().toStdString() << '\n';
+    const QList<PropertyData> &prop_list = alg.value();
+    for (QList<PropertyData>::const_iterator prop = prop_list.begin();
+         prop != prop_list.end(); ++prop)
+      std::cerr << prop->name.toStdString() << ": " << prop->value.toStdString()
+                << '\n';
+  }
 }
 
-/** 
+/**
     @param algName :: Algorithm name
 */
-QMap< QString,QString > InputHistoryImpl::algorithmProperties(const QString& algName)
-{
-    QMap< QString,QList< PropertyData > >::const_iterator a = m_history.find(algName);
-    if (a != m_history.end())
-    {
-        QMap< QString,QString > m;
-        const QList< PropertyData >& prop_list = a.value();
-        for(QList< PropertyData >::const_iterator prop=prop_list.begin();prop!=prop_list.end();++prop)
-            m[prop->name] = prop->value;
-        return m;
-    }
-    return QMap< QString,QString >();
+QMap<QString, QString>
+InputHistoryImpl::algorithmProperties(const QString &algName) {
+  QMap<QString, QList<PropertyData>>::const_iterator a =
+      m_history.find(algName);
+  if (a != m_history.end()) {
+    QMap<QString, QString> m;
+    const QList<PropertyData> &prop_list = a.value();
+    for (QList<PropertyData>::const_iterator prop = prop_list.begin();
+         prop != prop_list.end(); ++prop)
+      m[prop->name] = prop->value;
+    return m;
+  }
+  return QMap<QString, QString>();
 }
 
 /**  Returns the last entered value for property propName
      @param algName :: Name of the algorithm
      @param propName :: Property
-     @return The last entered value for the property or the empty string if the default value was used.
+     @return The last entered value for the property or the empty string if the
+   default value was used.
 */
 
-QString InputHistoryImpl::algorithmProperty(const QString& algName,const QString& propName)
-{
-    QMap< QString,QString > prop = algorithmProperties(algName);
-    return prop[propName];
+QString InputHistoryImpl::algorithmProperty(const QString &algName,
+                                            const QString &propName) {
+  QMap<QString, QString> prop = algorithmProperties(algName);
+  return prop[propName];
 }
 
-
-QString InputHistoryImpl::getDirectoryFromFilePath(const QString& filePath)
-{
-    QString s = filePath;
-	int i = s.lastIndexOf('\\');
-	if (i < 0) i = s.lastIndexOf('/');
-	if (i < 0) i = 0;
-	return s.remove(i,s.length()-i);
+QString InputHistoryImpl::getDirectoryFromFilePath(const QString &filePath) {
+  QString s = filePath;
+  int i = s.lastIndexOf('\\');
+  if (i < 0)
+    i = s.lastIndexOf('/');
+  if (i < 0)
+    i = 0;
+  return s.remove(i, s.length() - i);
 }
 
-QString InputHistoryImpl::getNameOnlyFromFilePath(const QString& filePath)
-{
-    QString s = filePath;
-	int i = s.lastIndexOf('\\');
-	if (i < 0) i = s.lastIndexOf('/');
-	if (i < 0) return s;
-	int j = s.lastIndexOf('.');
-	if (j < 0) j = s.length();
-	return s.mid(i+1,j - i - 1);
+QString InputHistoryImpl::getNameOnlyFromFilePath(const QString &filePath) {
+  QString s = filePath;
+  int i = s.lastIndexOf('\\');
+  if (i < 0)
+    i = s.lastIndexOf('/');
+  if (i < 0)
+    return s;
+  int j = s.lastIndexOf('.');
+  if (j < 0)
+    j = s.length();
+  return s.mid(i + 1, j - i - 1);
 }
 
-void InputHistoryImpl::updateAlgorithmProperty(const QString& algName,const QString& propName, const QString& propValue)
-{
-    QMap< QString,QList< PropertyData > >::iterator a = m_history.find(algName);
-    if (a == m_history.end())
-    {
-        QList< PropertyData > newList;
-        newList<<PropertyData(propName,propValue);
-        m_history[algName] = newList;
-    }
-    else
-    {
-        QList< PropertyData > &propList = a.value();
-        propList<<PropertyData(propName,propValue);
-    }
+void InputHistoryImpl::updateAlgorithmProperty(const QString &algName,
+                                               const QString &propName,
+                                               const QString &propValue) {
+  QMap<QString, QList<PropertyData>>::iterator a = m_history.find(algName);
+  if (a == m_history.end()) {
+    QList<PropertyData> newList;
+    newList << PropertyData(propName, propValue);
+    m_history[algName] = newList;
+  } else {
+    QList<PropertyData> &propList = a.value();
+    propList << PropertyData(propName, propValue);
+  }
 }
diff --git a/MantidPlot/src/Mantid/InputHistory.h b/MantidPlot/src/Mantid/InputHistory.h
index cc54cc6538e038222b57f1380f5d717c8f8b2066..23f085ff23e35aa76cb870e2a0f86d1e758410af 100644
--- a/MantidPlot/src/Mantid/InputHistory.h
+++ b/MantidPlot/src/Mantid/InputHistory.h
@@ -8,20 +8,17 @@
 #include <QMap>
 #include <QList>
 
-namespace Mantid
-{
-    namespace API
-    {
-        class IAlgorithm;
-        typedef boost::shared_ptr<IAlgorithm> IAlgorithm_sptr;
-    }
+namespace Mantid {
+namespace API {
+class IAlgorithm;
+typedef boost::shared_ptr<IAlgorithm> IAlgorithm_sptr;
+}
 }
 
-struct PropertyData
-{
-    PropertyData(const QString& nm,const QString& vl):name(nm),value(vl){}
-    QString name;
-    QString value;
+struct PropertyData {
+  PropertyData(const QString &nm, const QString &vl) : name(nm), value(vl) {}
+  QString name;
+  QString value;
 };
 
 /** @class InputHistory
@@ -31,7 +28,8 @@ struct PropertyData
  @author Roman Tolchenov, Tessella Support Services plc
  @date 15/10/2008
 
- Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -52,44 +50,44 @@ struct PropertyData
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class InputHistoryImpl
-{
+class InputHistoryImpl {
 public:
   InputHistoryImpl(const InputHistoryImpl &) = delete;
   InputHistoryImpl &operator=(const InputHistoryImpl &) = delete;
-    void updateAlgorithm(Mantid::API::IAlgorithm_sptr alg);
-    /// The name:value map of non-default properties with which algorithm algName was called last time.
-    QMap< QString, QString > algorithmProperties(const QString& algName);
-    /// Returns the value of property propNameif it has been recorded for algorithm algName.
-    QString algorithmProperty(const QString& algName,const QString& propName);
-    /// Replaces the value of a recorded property.
-    void updateAlgorithmProperty(const QString& algName,const QString& propName, const QString& propValue);
-    /// Saves the properties.
-    void save();
-
-    /// Returns the directory name from a full file path.
-    static QString getDirectoryFromFilePath(const QString& filePath);
-    /// Returns the short file name (without extension) from a full file path.
-    static QString getNameOnlyFromFilePath(const QString& filePath);
+  void updateAlgorithm(Mantid::API::IAlgorithm_sptr alg);
+  /// The name:value map of non-default properties with which algorithm algName
+  /// was called last time.
+  QMap<QString, QString> algorithmProperties(const QString &algName);
+  /// Returns the value of property propNameif it has been recorded for
+  /// algorithm algName.
+  QString algorithmProperty(const QString &algName, const QString &propName);
+  /// Replaces the value of a recorded property.
+  void updateAlgorithmProperty(const QString &algName, const QString &propName,
+                               const QString &propValue);
+  /// Saves the properties.
+  void save();
+
+  /// Returns the directory name from a full file path.
+  static QString getDirectoryFromFilePath(const QString &filePath);
+  /// Returns the short file name (without extension) from a full file path.
+  static QString getNameOnlyFromFilePath(const QString &filePath);
 
 private:
-	friend struct Mantid::Kernel::CreateUsingNew<InputHistoryImpl>;
+  friend struct Mantid::Kernel::CreateUsingNew<InputHistoryImpl>;
 
-	///Private Constructor
-	InputHistoryImpl();
-	///Private Destructor
-        virtual ~InputHistoryImpl() = default;
+  /// Private Constructor
+  InputHistoryImpl();
+  /// Private Destructor
+  virtual ~InputHistoryImpl() = default;
 
   /// For debugging
   // cppcheck-suppress unusedPrivateFunction
   void printAll();
 
   /// Keeps algorithm parameters.
-  QMap< QString,QList< PropertyData > > m_history;
-
+  QMap<QString, QList<PropertyData>> m_history;
 };
 
 typedef Mantid::Kernel::SingletonHolder<InputHistoryImpl> InputHistory;
 
-
 #endif /* INPUTHISTORY_H */
diff --git a/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp b/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
index ad77b07274e49c3f0a076ee686934ed1559fe42b..3c2ec6d9d1fd920e329b87deec21b2b2b9aba6b1 100644
--- a/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
+++ b/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
@@ -104,6 +104,6 @@ void InstrumentWindow::setViewType(const QString &type) {
 }
 
 void InstrumentWindow::closeSafely() {
-	confirmClose(false);
-	close();
+  confirmClose(false);
+  close();
 }
diff --git a/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.h b/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.h
index 9869af2a6b1ce29eaa05ee99bea50353cf25503f..af4ce5559e99204e3d30d3349280a21e18fa8d65 100644
--- a/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.h
+++ b/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.h
@@ -10,13 +10,11 @@
 #include <boost/shared_ptr.hpp>
 
 class ApplicationWindow;
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentWidget;
-		class InstrumentWidgetTab;
-	}
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentWidget;
+class InstrumentWidgetTab;
+}
 }
 
 using namespace Mantid;
@@ -34,12 +32,13 @@ public:
                        const int fileVersion) override;
   std::string saveToProject(ApplicationWindow *app) override;
   void selectTab(int tab);
-  MantidQt::MantidWidgets::InstrumentWidgetTab *getTab(const QString & title) const;
+  MantidQt::MantidWidgets::InstrumentWidgetTab *
+  getTab(const QString &title) const;
   MantidQt::MantidWidgets::InstrumentWidgetTab *getTab(int tab) const;
   void setBinRange(double min_value, double max_value);
   bool overlay(const QString &wsName);
   void changeColormap();
-  void changeColormap(const QString & file);
+  void changeColormap(const QString &file);
   void setColorMapMinValue(double);
   void setColorMapMaxValue(double);
   void setColorMapRange(double, double);
@@ -51,7 +50,7 @@ public slots:
   void closeSafely();
 
 private:
-	MantidQt::MantidWidgets::InstrumentWidget *m_instrumentWidget;
+  MantidQt::MantidWidgets::InstrumentWidget *m_instrumentWidget;
 };
 
 #endif // INSTRUMENTWINDOW_H
\ No newline at end of file
diff --git a/MantidPlot/src/Mantid/LoadDAEDlg.cpp b/MantidPlot/src/Mantid/LoadDAEDlg.cpp
index 9d265d29f85ee73ec4e36f1790aaaee12c9789cd..18e05d1da4b06980c797680ec528efda5bd67f98 100644
--- a/MantidPlot/src/Mantid/LoadDAEDlg.cpp
+++ b/MantidPlot/src/Mantid/LoadDAEDlg.cpp
@@ -6,143 +6,140 @@
 #include "LoadDAEDlg.h"
 #include "InputHistory.h"
 
-loadDAEDlg::loadDAEDlg(QWidget *parent) : QDialog(parent), m_hostName(""), m_workspaceName(""),m_spectrum_min(""),m_spectrum_max(""),m_spectrum_list(""),
-m_updateInterval(0)
-{
-	QGridLayout *paramsLayout = new QGridLayout;
-    QLabel *label = new QLabel(tr("DAE Name"));
-	lineHost = new QLineEdit;
-	label->setBuddy(lineHost);
-	paramsLayout->addWidget(label,0,0);
-	paramsLayout->addWidget(lineHost,0,1);
-    QString propValue = InputHistory::Instance().algorithmProperty("LoadDAE","DAEname");
-    if (!propValue.isEmpty())
-    {
-        lineHost->setText(propValue);
-    }
-	
-	label = new QLabel(tr("Workspace Name"));
-	lineName = new QLineEdit;
-	label->setBuddy(lineName);
-	paramsLayout->addWidget(label,1,0);
-	paramsLayout->addWidget(lineName,1,1);
-    propValue = InputHistory::Instance().algorithmProperty("LoadDAE","OutputWorkspace");
-    if (!propValue.isEmpty())
-    {
-        lineName->setText(propValue);
-    }
-	
-	QHBoxLayout *bottomRowLayout = new QHBoxLayout;
-	QPushButton *loadButton = new QPushButton(tr("Load"));
-	loadButton->setDefault(true);
-	QPushButton *cancelButton = new QPushButton(tr("Cancel"));
-	QPushButton *help = new QPushButton("?");
-	help->setMaximumWidth(25);
-	connect(help, SIGNAL(clicked()), this, SLOT(helpClicked()));
-	
-	bottomRowLayout->addWidget(help);
-	bottomRowLayout->addStretch();
-	bottomRowLayout->addWidget(cancelButton);
-	bottomRowLayout->addWidget(loadButton);
-
-	connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
-	connect(loadButton, SIGNAL(clicked()), this, SLOT(load()));
-	
-    QLabel *minSpLabel = new QLabel("Starting spectrum");
-    minSpLineEdit = new QLineEdit;
-    propValue = InputHistory::Instance().algorithmProperty("LoadRaw","spectrum_min");
-    if (!propValue.isEmpty())
-    {
-        minSpLineEdit->setText(propValue);
-    }
-    paramsLayout->addWidget(minSpLabel,2,0);
-    paramsLayout->addWidget(minSpLineEdit,2,1);
-    QLabel *maxSpLabel = new QLabel("Ending spectrum");
-    maxSpLineEdit = new QLineEdit;
-    propValue = InputHistory::Instance().algorithmProperty("LoadDAE","spectrum_max");
-    if (!propValue.isEmpty())
-    {
-        maxSpLineEdit->setText(propValue);
-    }
-    paramsLayout->addWidget(maxSpLabel,3,0);
-    paramsLayout->addWidget(maxSpLineEdit,3,1);
-    QLabel *listSpLabel = new QLabel("Spectrum List");
-    listSpLineEdit = new QLineEdit;
-    propValue = InputHistory::Instance().algorithmProperty("LoadDAE","spectrum_list");
-    if (!propValue.isEmpty())
-    {
-        listSpLineEdit->setText(propValue);
-    }
-    paramsLayout->addWidget(listSpLabel,4,0);
-    paramsLayout->addWidget(listSpLineEdit,4,1);
-
-	QHBoxLayout *updateLayout = new QHBoxLayout;
-    updateCheck = new QCheckBox("Update every");
-    updateLineEdit = new QLineEdit;
-    QIntValidator *ival = new QIntValidator(1,99999999,updateLineEdit);
-    updateLineEdit->setValidator(ival);
-    propValue = InputHistory::Instance().algorithmProperty("UpdateDAE","update_rate");
-    if (!propValue.isEmpty())
-    {
-        updateLineEdit->setText(propValue);
-        updateCheck->setCheckState(Qt::Checked);
-    }
-    label = new QLabel(" seconds");
-    paramsLayout->addWidget(updateCheck,5,0);
-    updateLayout->addWidget(updateLineEdit);
-    updateLayout->addWidget(label);
-    paramsLayout->addLayout(updateLayout,5,1);
-    connect(updateCheck,SIGNAL(stateChanged(int)),this,SLOT(changeUpdateState(int)));
-    connect(updateLineEdit,SIGNAL(textEdited(const QString & )),this,SLOT(updateIntervalEntered(const QString &)));
-
-
-    QVBoxLayout *mainLayout = new QVBoxLayout;
-	mainLayout->addLayout(paramsLayout);
-	mainLayout->addLayout(bottomRowLayout);
-	
-	setLayout(mainLayout);
-	setWindowTitle(tr("Load Workspace from DAE"));
-	setFixedHeight(sizeHint().height());
-}
+loadDAEDlg::loadDAEDlg(QWidget *parent)
+    : QDialog(parent), m_hostName(""), m_workspaceName(""), m_spectrum_min(""),
+      m_spectrum_max(""), m_spectrum_list(""), m_updateInterval(0) {
+  QGridLayout *paramsLayout = new QGridLayout;
+  QLabel *label = new QLabel(tr("DAE Name"));
+  lineHost = new QLineEdit;
+  label->setBuddy(lineHost);
+  paramsLayout->addWidget(label, 0, 0);
+  paramsLayout->addWidget(lineHost, 0, 1);
+  QString propValue =
+      InputHistory::Instance().algorithmProperty("LoadDAE", "DAEname");
+  if (!propValue.isEmpty()) {
+    lineHost->setText(propValue);
+  }
+
+  label = new QLabel(tr("Workspace Name"));
+  lineName = new QLineEdit;
+  label->setBuddy(lineName);
+  paramsLayout->addWidget(label, 1, 0);
+  paramsLayout->addWidget(lineName, 1, 1);
+  propValue =
+      InputHistory::Instance().algorithmProperty("LoadDAE", "OutputWorkspace");
+  if (!propValue.isEmpty()) {
+    lineName->setText(propValue);
+  }
 
-loadDAEDlg::~loadDAEDlg()
-{
-	
+  QHBoxLayout *bottomRowLayout = new QHBoxLayout;
+  QPushButton *loadButton = new QPushButton(tr("Load"));
+  loadButton->setDefault(true);
+  QPushButton *cancelButton = new QPushButton(tr("Cancel"));
+  QPushButton *help = new QPushButton("?");
+  help->setMaximumWidth(25);
+  connect(help, SIGNAL(clicked()), this, SLOT(helpClicked()));
+
+  bottomRowLayout->addWidget(help);
+  bottomRowLayout->addStretch();
+  bottomRowLayout->addWidget(cancelButton);
+  bottomRowLayout->addWidget(loadButton);
+
+  connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
+  connect(loadButton, SIGNAL(clicked()), this, SLOT(load()));
+
+  QLabel *minSpLabel = new QLabel("Starting spectrum");
+  minSpLineEdit = new QLineEdit;
+  propValue =
+      InputHistory::Instance().algorithmProperty("LoadRaw", "spectrum_min");
+  if (!propValue.isEmpty()) {
+    minSpLineEdit->setText(propValue);
+  }
+  paramsLayout->addWidget(minSpLabel, 2, 0);
+  paramsLayout->addWidget(minSpLineEdit, 2, 1);
+  QLabel *maxSpLabel = new QLabel("Ending spectrum");
+  maxSpLineEdit = new QLineEdit;
+  propValue =
+      InputHistory::Instance().algorithmProperty("LoadDAE", "spectrum_max");
+  if (!propValue.isEmpty()) {
+    maxSpLineEdit->setText(propValue);
+  }
+  paramsLayout->addWidget(maxSpLabel, 3, 0);
+  paramsLayout->addWidget(maxSpLineEdit, 3, 1);
+  QLabel *listSpLabel = new QLabel("Spectrum List");
+  listSpLineEdit = new QLineEdit;
+  propValue =
+      InputHistory::Instance().algorithmProperty("LoadDAE", "spectrum_list");
+  if (!propValue.isEmpty()) {
+    listSpLineEdit->setText(propValue);
+  }
+  paramsLayout->addWidget(listSpLabel, 4, 0);
+  paramsLayout->addWidget(listSpLineEdit, 4, 1);
+
+  QHBoxLayout *updateLayout = new QHBoxLayout;
+  updateCheck = new QCheckBox("Update every");
+  updateLineEdit = new QLineEdit;
+  QIntValidator *ival = new QIntValidator(1, 99999999, updateLineEdit);
+  updateLineEdit->setValidator(ival);
+  propValue =
+      InputHistory::Instance().algorithmProperty("UpdateDAE", "update_rate");
+  if (!propValue.isEmpty()) {
+    updateLineEdit->setText(propValue);
+    updateCheck->setCheckState(Qt::Checked);
+  }
+  label = new QLabel(" seconds");
+  paramsLayout->addWidget(updateCheck, 5, 0);
+  updateLayout->addWidget(updateLineEdit);
+  updateLayout->addWidget(label);
+  paramsLayout->addLayout(updateLayout, 5, 1);
+  connect(updateCheck, SIGNAL(stateChanged(int)), this,
+          SLOT(changeUpdateState(int)));
+  connect(updateLineEdit, SIGNAL(textEdited(const QString &)), this,
+          SLOT(updateIntervalEntered(const QString &)));
+
+  QVBoxLayout *mainLayout = new QVBoxLayout;
+  mainLayout->addLayout(paramsLayout);
+  mainLayout->addLayout(bottomRowLayout);
+
+  setLayout(mainLayout);
+  setWindowTitle(tr("Load Workspace from DAE"));
+  setFixedHeight(sizeHint().height());
 }
 
-void loadDAEDlg::load()
-{
-	if (!lineHost->text().isNull() && !lineHost->text().isEmpty() && !lineName->text().isNull() && !lineName->text().isEmpty())
-	{
-		m_hostName = lineHost->text();
-		m_workspaceName = lineName->text();
-        m_spectrum_min = minSpLineEdit->text();
-        m_spectrum_max = maxSpLineEdit->text();
-        m_spectrum_list = listSpLineEdit->text();
-        if (updateCheck->checkState() == Qt::Checked) m_updateInterval = updateLineEdit->text().toInt();
-        else
-        {
-            m_updateInterval = 0;
-            InputHistory::Instance().updateAlgorithmProperty("UpdateDAE","update_rate","");
-        }
-		close();
-	}
+loadDAEDlg::~loadDAEDlg() {}
+
+void loadDAEDlg::load() {
+  if (!lineHost->text().isNull() && !lineHost->text().isEmpty() &&
+      !lineName->text().isNull() && !lineName->text().isEmpty()) {
+    m_hostName = lineHost->text();
+    m_workspaceName = lineName->text();
+    m_spectrum_min = minSpLineEdit->text();
+    m_spectrum_max = maxSpLineEdit->text();
+    m_spectrum_list = listSpLineEdit->text();
+    if (updateCheck->checkState() == Qt::Checked)
+      m_updateInterval = updateLineEdit->text().toInt();
+    else {
+      m_updateInterval = 0;
+      InputHistory::Instance().updateAlgorithmProperty("UpdateDAE",
+                                                       "update_rate", "");
+    }
+    close();
+  }
 }
 
-void loadDAEDlg::changeUpdateState(int state)
-{
-    if (state == Qt::Checked && updateLineEdit->text().isEmpty()) updateLineEdit->setText("10");
+void loadDAEDlg::changeUpdateState(int state) {
+  if (state == Qt::Checked && updateLineEdit->text().isEmpty())
+    updateLineEdit->setText("10");
 }
 
-void loadDAEDlg::updateIntervalEntered(const QString & text )
-{
-    if (!text.isEmpty())
-        updateCheck->setCheckState(Qt::Checked);
-    else
-        updateCheck->setCheckState(Qt::Unchecked);
+void loadDAEDlg::updateIntervalEntered(const QString &text) {
+  if (!text.isEmpty())
+    updateCheck->setCheckState(Qt::Checked);
+  else
+    updateCheck->setCheckState(Qt::Unchecked);
 }
 
-void loadDAEDlg::helpClicked()
-{
-  QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/LoadDAE")));
+void loadDAEDlg::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl(QString("http://www.mantidproject.org/LoadDAE")));
 }
diff --git a/MantidPlot/src/Mantid/LoadDAEDlg.h b/MantidPlot/src/Mantid/LoadDAEDlg.h
index 282b9f7ddffa02a9b3428cf228e902176bdd9b8d..7e6167f1bd9a9f997a59ae7009c6b2b7b6fe41ec 100644
--- a/MantidPlot/src/Mantid/LoadDAEDlg.h
+++ b/MantidPlot/src/Mantid/LoadDAEDlg.h
@@ -11,45 +11,42 @@ class QString;
 class QVBoxLayout;
 class QCheckBox;
 
-class loadDAEDlg : public QDialog
-{
-	Q_OBJECT
-	
+class loadDAEDlg : public QDialog {
+  Q_OBJECT
+
 public:
   explicit loadDAEDlg(QWidget *parent = 0);
   ~loadDAEDlg() override;
 
-        const QString& getHostName() { return m_hostName; }
-	const QString& getWorkspaceName() { return m_workspaceName; }
-	const QString& getSpectrumMin() { return m_spectrum_min; }
-	const QString& getSpectrumMax() { return m_spectrum_max; }
-	const QString& getSpectrumList() { return m_spectrum_list; }
-  int updateInterval(){return m_updateInterval;}
+  const QString &getHostName() { return m_hostName; }
+  const QString &getWorkspaceName() { return m_workspaceName; }
+  const QString &getSpectrumMin() { return m_spectrum_min; }
+  const QString &getSpectrumMax() { return m_spectrum_max; }
+  const QString &getSpectrumList() { return m_spectrum_list; }
+  int updateInterval() { return m_updateInterval; }
 
 protected:
-	
 private slots:
-	void load();
-    void changeUpdateState(int);
-    void updateIntervalEntered(const QString & text );
+  void load();
+  void changeUpdateState(int);
+  void updateIntervalEntered(const QString &text);
   void helpClicked();
 
 private:
-	QString m_hostName;
-	QString m_workspaceName;
-    QString m_spectrum_min;
-    QString m_spectrum_max;
-    QString m_spectrum_list;
-    int m_updateInterval;
-
-	QLineEdit *lineHost;
-	QLineEdit *lineName;
-    QLineEdit *minSpLineEdit;
-    QLineEdit *maxSpLineEdit;
-    QLineEdit *listSpLineEdit;
-    QCheckBox *updateCheck;
-    QLineEdit *updateLineEdit;
-
+  QString m_hostName;
+  QString m_workspaceName;
+  QString m_spectrum_min;
+  QString m_spectrum_max;
+  QString m_spectrum_list;
+  int m_updateInterval;
+
+  QLineEdit *lineHost;
+  QLineEdit *lineName;
+  QLineEdit *minSpLineEdit;
+  QLineEdit *maxSpLineEdit;
+  QLineEdit *listSpLineEdit;
+  QCheckBox *updateCheck;
+  QLineEdit *updateLineEdit;
 };
 
 #endif /* LOADDAEDLG_H */
diff --git a/MantidPlot/src/Mantid/ManageCustomMenus.cpp b/MantidPlot/src/Mantid/ManageCustomMenus.cpp
index c506fcc2535fd68013de971590fbe6cfd1a7fb96..bb85d5de70ed9d83e89be44711d177a60b8bf625 100644
--- a/MantidPlot/src/Mantid/ManageCustomMenus.cpp
+++ b/MantidPlot/src/Mantid/ManageCustomMenus.cpp
@@ -6,230 +6,223 @@
 
 #include <QtGui>
 /**
-* Constructor for object. Performs initial setup and calls subsequent setup functions.
+* Constructor for object. Performs initial setup and calls subsequent setup
+* functions.
 * @param parent :: pointer to the main MantidPlot ApplicationWindow object
 */
-ManageCustomMenus::ManageCustomMenus(QWidget *parent) : QDialog(parent),
-m_scriptsTree(0), m_menusTree(0)
-{
-	m_uiForm.setupUi(this);
-    m_appWindow = static_cast<ApplicationWindow*>(parent);
-    initLayout();
+ManageCustomMenus::ManageCustomMenus(QWidget *parent)
+    : QDialog(parent), m_scriptsTree(0), m_menusTree(0) {
+  m_uiForm.setupUi(this);
+  m_appWindow = static_cast<ApplicationWindow *>(parent);
+  initLayout();
 }
 /**
-* Makes signal/slot connections and small changes to interface which QtDesigner does not give access to.
+* Makes signal/slot connections and small changes to interface which QtDesigner
+* does not give access to.
 */
-void ManageCustomMenus::initLayout()
-{
-    m_scriptsTree = m_uiForm.twScripts;
-    m_menusTree = m_uiForm.twMenus;
+void ManageCustomMenus::initLayout() {
+  m_scriptsTree = m_uiForm.twScripts;
+  m_menusTree = m_uiForm.twMenus;
 
-    m_scriptsTree->setHeaderLabel("Python Scripts");
-    m_menusTree->setHeaderLabel("Custom Menus");
+  m_scriptsTree->setHeaderLabel("Python Scripts");
+  m_menusTree->setHeaderLabel("Custom Menus");
 
-    // create qt connections
-    connect(m_uiForm.pbAddScript, SIGNAL(clicked()), this, SLOT(addScriptClicked()));
-    connect(m_uiForm.pbRemoveScript, SIGNAL(clicked()), this, SLOT(remScriptClicked()));
-    connect(m_uiForm.pbAddItem, SIGNAL(clicked()), this, SLOT(addItemClicked()));
-    connect(m_uiForm.pbRemoveItem, SIGNAL(clicked()), this, SLOT(remItemClicked()));
-    connect(m_uiForm.pbAddMenu, SIGNAL(clicked()), this, SLOT(addMenuClicked()));   
-    connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
-    connect(m_uiForm.pbConfirm, SIGNAL(clicked()), this, SLOT(close()));
-    // Perform subsequent setups
-    populateMenuTree();
+  // create qt connections
+  connect(m_uiForm.pbAddScript, SIGNAL(clicked()), this,
+          SLOT(addScriptClicked()));
+  connect(m_uiForm.pbRemoveScript, SIGNAL(clicked()), this,
+          SLOT(remScriptClicked()));
+  connect(m_uiForm.pbAddItem, SIGNAL(clicked()), this, SLOT(addItemClicked()));
+  connect(m_uiForm.pbRemoveItem, SIGNAL(clicked()), this,
+          SLOT(remItemClicked()));
+  connect(m_uiForm.pbAddMenu, SIGNAL(clicked()), this, SLOT(addMenuClicked()));
+  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  connect(m_uiForm.pbConfirm, SIGNAL(clicked()), this, SLOT(close()));
+  // Perform subsequent setups
+  populateMenuTree();
 }
 /**
 * Populates the m_menusTree to reflect the currently set custom menus.
 */
-void ManageCustomMenus::populateMenuTree()
-{
-    m_menusTree->clear();
-    m_widgetMap.clear();
+void ManageCustomMenus::populateMenuTree() {
+  m_menusTree->clear();
+  m_widgetMap.clear();
 
-    QListIterator<QMenu*> mItr(m_appWindow->getCustomMenus());
-    while( mItr.hasNext() )
-    {
-        QMenu *customMenu = mItr.next();
-        QTreeWidgetItem *menu = new QTreeWidgetItem(QStringList(customMenu->title()));
-        m_widgetMap.insert(menu, customMenu);
-        menu->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable );
-        QList<QAction*> scripts = customMenu->actions();
-        QListIterator<QAction*> kItr(scripts);
-        while( kItr.hasNext() )
-        {
-            QAction *action = kItr.next();
-            QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(action->text()));
-            m_widgetMap.insert(item, action);
-            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable );
-            item->setData(0, Qt::UserRole, action->data().toString());
-            item->setToolTip(0, action->data().toString());
-            menu->addChild(item);
-        }
-        m_menusTree->addTopLevelItem(menu);    
+  QListIterator<QMenu *> mItr(m_appWindow->getCustomMenus());
+  while (mItr.hasNext()) {
+    QMenu *customMenu = mItr.next();
+    QTreeWidgetItem *menu =
+        new QTreeWidgetItem(QStringList(customMenu->title()));
+    m_widgetMap.insert(menu, customMenu);
+    menu->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled |
+                   Qt::ItemIsEditable);
+    QList<QAction *> scripts = customMenu->actions();
+    QListIterator<QAction *> kItr(scripts);
+    while (kItr.hasNext()) {
+      QAction *action = kItr.next();
+      QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(action->text()));
+      m_widgetMap.insert(item, action);
+      item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled |
+                     Qt::ItemIsEditable);
+      item->setData(0, Qt::UserRole, action->data().toString());
+      item->setToolTip(0, action->data().toString());
+      menu->addChild(item);
     }
+    m_menusTree->addTopLevelItem(menu);
+  }
 }
 
 /**
-* Returns a list of pointers to the selected items in the Scripts and Custom Interfaces trees.
+* Returns a list of pointers to the selected items in the Scripts and Custom
+* Interfaces trees.
 * @return list of selected items
 */
-QList<QTreeWidgetItem*> ManageCustomMenus::getCurrentSelection()
-{
-    QList<QTreeWidgetItem*> result;
-    result = m_scriptsTree->selectedItems();
-    return result;
+QList<QTreeWidgetItem *> ManageCustomMenus::getCurrentSelection() {
+  QList<QTreeWidgetItem *> result;
+  result = m_scriptsTree->selectedItems();
+  return result;
 }
 /**
 * Returns pointer to currently selected menu item.
 * @return pointer to currently selected menu item
 */
-QTreeWidgetItem* ManageCustomMenus::getCurrentMenuSelection()
-{
-    QTreeWidgetItem* result = 0;
-    result = m_menusTree->currentItem();
-    return result;
+QTreeWidgetItem *ManageCustomMenus::getCurrentMenuSelection() {
+  QTreeWidgetItem *result = 0;
+  result = m_menusTree->currentItem();
+  return result;
 }
 /**
 * Handles adding a script to the scripts tree, through a FileDialog.
 */
-void ManageCustomMenus::addScriptClicked()
-{
-    QString scriptsDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directories"));
-    QStringList scriptFiles = QFileDialog::getOpenFileNames(this, "Select Python Files", scriptsDir, "Python (*.py)");
-    if ( !scriptFiles.isEmpty() )
-    {
-        // Add file items to m_scriptsTree
-        QStringList::const_iterator itEnd = scriptFiles.constEnd();
-        for( QStringList::const_iterator itr = scriptFiles.constBegin(); itr != itEnd; ++itr )
-        {
-            QString suggestedName = QFileInfo(*itr).baseName();
-            if( !m_scriptsTree->findItems(suggestedName, Qt::MatchFixedString | Qt::MatchCaseSensitive).isEmpty() ) continue;
+void ManageCustomMenus::addScriptClicked() {
+  QString scriptsDir = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "pythonscripts.directories"));
+  QStringList scriptFiles = QFileDialog::getOpenFileNames(
+      this, "Select Python Files", scriptsDir, "Python (*.py)");
+  if (!scriptFiles.isEmpty()) {
+    // Add file items to m_scriptsTree
+    QStringList::const_iterator itEnd = scriptFiles.constEnd();
+    for (QStringList::const_iterator itr = scriptFiles.constBegin();
+         itr != itEnd; ++itr) {
+      QString suggestedName = QFileInfo(*itr).baseName();
+      if (!m_scriptsTree->findItems(suggestedName, Qt::MatchFixedString |
+                                                       Qt::MatchCaseSensitive)
+               .isEmpty())
+        continue;
 
-            QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(suggestedName));
-            item->setData(0, Qt::UserRole, *itr);
-            item->setToolTip(0, *itr);
-            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable );
-            m_scriptsTree->insertTopLevelItem(0, item);
-        }
+      QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(suggestedName));
+      item->setData(0, Qt::UserRole, *itr);
+      item->setToolTip(0, *itr);
+      item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled |
+                     Qt::ItemIsEditable);
+      m_scriptsTree->insertTopLevelItem(0, item);
     }
+  }
 }
 /**
 * Handles removing selected scripts from the m_scriptsTree window.
 */
-void ManageCustomMenus::remScriptClicked()
-{
-    if ( m_scriptsTree->selectedItems().isEmpty() )
-    {
-        QMessageBox::information(this, "MantidPlot", "No item selected - please select a script from the left-hand list.");
-    }
-    else
-    {
-        QTreeWidgetItem* item;
-        foreach(item, m_scriptsTree->selectedItems())
-        {
-            delete item;
-        }
-    }
+void ManageCustomMenus::remScriptClicked() {
+  if (m_scriptsTree->selectedItems().isEmpty()) {
+    QMessageBox::information(
+        this, "MantidPlot",
+        "No item selected - please select a script from the left-hand list.");
+  } else {
+    QTreeWidgetItem *item;
+    foreach (item, m_scriptsTree->selectedItems()) { delete item; }
+  }
 }
 /**
-* Adds item (script or custom interface) to custom menu. Removes added scripts from the scripts tree.
+* Adds item (script or custom interface) to custom menu. Removes added scripts
+* from the scripts tree.
 */
-void ManageCustomMenus::addItemClicked()
-{
-    QList<QTreeWidgetItem*> selection = getCurrentSelection();
-    QTreeWidgetItem* menu = getCurrentMenuSelection();
-    if ( selection.isEmpty() )
-    {
-        QMessageBox::information(this, "MantidPlot", "No item selected - please select a script in the left-hand list of scripts.\n"
-                                                     "If none are listed, use the 'Add Script' button to add some files.");
+void ManageCustomMenus::addItemClicked() {
+  QList<QTreeWidgetItem *> selection = getCurrentSelection();
+  QTreeWidgetItem *menu = getCurrentMenuSelection();
+  if (selection.isEmpty()) {
+    QMessageBox::information(
+        this, "MantidPlot",
+        "No item selected - please select a script in the left-hand list of "
+        "scripts.\n"
+        "If none are listed, use the 'Add Script' button to add some files.");
+  } else if (menu == 0) {
+    QMessageBox::information(this, "MantidPlot",
+                             "No menu selected - please select a menu on the "
+                             "right-hand side to which to add this script.\n"
+                             "If no custom menus are present, use the 'Add "
+                             "Menu' button to create one.");
+  } else {
+    // Ensure using top-level menu.
+    if (menu->parent() != 0) {
+      menu = menu->parent();
     }
-    else if ( menu == 0 )
-    {
-        QMessageBox::information(this, "MantidPlot", "No menu selected - please select a menu on the right-hand side to which to add this script.\n"
-            "If no custom menus are present, use the 'Add Menu' button to create one.");
-    }
-    else
-    {
-        // Ensure using top-level menu.
-        if ( menu->parent() != 0 )
-        {
-            menu = menu->parent();
-        }
 
-        QTreeWidgetItem* item;
-        foreach(item, selection)
-        { // foreach is a Qt macro ( http://doc.qt.nokia.com/4.4/containers.html#the-foreach-keyword )
-            menu->addChild(item);
-            QString menuName = menu->text(0);
-            QString itemName = item->text(0);
-            QString item_data = item->data(0, Qt::UserRole).toString();
-            m_appWindow->addUserMenuAction( menuName, itemName, item_data);
-        }
-        // Refresh menu list
-        populateMenuTree();
+    QTreeWidgetItem *item;
+    foreach (item, selection) { // foreach is a Qt macro (
+      // http://doc.qt.nokia.com/4.4/containers.html#the-foreach-keyword
+      // )
+      menu->addChild(item);
+      QString menuName = menu->text(0);
+      QString itemName = item->text(0);
+      QString item_data = item->data(0, Qt::UserRole).toString();
+      m_appWindow->addUserMenuAction(menuName, itemName, item_data);
+    }
+    // Refresh menu list
+    populateMenuTree();
 
-        // Remove scripts elements that have been added to the menu.
-        if ( ! m_scriptsTree->selectedItems().isEmpty() )
-        {
-            remScriptClicked();
-        }
+    // Remove scripts elements that have been added to the menu.
+    if (!m_scriptsTree->selectedItems().isEmpty()) {
+      remScriptClicked();
     }
+  }
 }
 /**
 * Removes item from custom menu, or custom menu itself if selected.
 */
-void ManageCustomMenus::remItemClicked()
-{
-    QTreeWidgetItem* item = getCurrentMenuSelection();
-    if ( item == 0 )
-    {
-        QMessageBox::information(this, "MantidPlot", "No item selected - please select a script or menu in the right-hand list.");
-    }
-    else
-    {
-        if ( item->parent() != 0 )
-        {
-            // Delete menu sub-item
-            QTreeWidgetItem* menu = item->parent();
-            m_appWindow->removeUserMenuAction(menu->text(0), item->text(0));
-        }
-        else
-        {
-            // Delete menu
-            m_appWindow->removeUserMenu(item->text(0));
-        }
-        // Refresh menu list
-        populateMenuTree();
+void ManageCustomMenus::remItemClicked() {
+  QTreeWidgetItem *item = getCurrentMenuSelection();
+  if (item == 0) {
+    QMessageBox::information(this, "MantidPlot", "No item selected - please "
+                                                 "select a script or menu in "
+                                                 "the right-hand list.");
+  } else {
+    if (item->parent() != 0) {
+      // Delete menu sub-item
+      QTreeWidgetItem *menu = item->parent();
+      m_appWindow->removeUserMenuAction(menu->text(0), item->text(0));
+    } else {
+      // Delete menu
+      m_appWindow->removeUserMenu(item->text(0));
     }
+    // Refresh menu list
+    populateMenuTree();
+  }
 }
 /**
 * Adds new top-level menu to the interface.
 */
-void ManageCustomMenus::addMenuClicked()
-{
-    bool ok(false);
-    QString name = QInputDialog::getText(this, "Create a Menu", "Menu name:", QLineEdit::Normal, "", &ok);
-    if ( ok )
-    {
-        if( m_menusTree->findItems(name, Qt::MatchFixedString | Qt::MatchCaseSensitive ).isEmpty() )
-        {
-            if( !name.isEmpty() ) 
-            {
-                m_appWindow->addUserMenu(name);
-                populateMenuTree();
-            }
-        }
-        else
-        {
-            QMessageBox::information(this, "MantidPlot", "A menu with that name already exists.");
-        }
+void ManageCustomMenus::addMenuClicked() {
+  bool ok(false);
+  QString name = QInputDialog::getText(this, "Create a Menu", "Menu name:",
+                                       QLineEdit::Normal, "", &ok);
+  if (ok) {
+    if (m_menusTree->findItems(name, Qt::MatchFixedString |
+                                         Qt::MatchCaseSensitive).isEmpty()) {
+      if (!name.isEmpty()) {
+        m_appWindow->addUserMenu(name);
+        populateMenuTree();
+      }
+    } else {
+      QMessageBox::information(this, "MantidPlot",
+                               "A menu with that name already exists.");
     }
+  }
 }
 /**
 * Opens web browser to wiki page for this dialog.
 */
-void ManageCustomMenus::helpClicked()
-{
-    QUrl helpUrl("http://www.mantidproject.org/ManageCustomMenus");
-    QDesktopServices::openUrl(helpUrl);
+void ManageCustomMenus::helpClicked() {
+  QUrl helpUrl("http://www.mantidproject.org/ManageCustomMenus");
+  QDesktopServices::openUrl(helpUrl);
 }
diff --git a/MantidPlot/src/Mantid/ManageCustomMenus.h b/MantidPlot/src/Mantid/ManageCustomMenus.h
index 332bf1f111ffa2e922ee9203a3a5bc6178287091..78db7449cba9f7e60ee64ac17475fd5b0c296204 100644
--- a/MantidPlot/src/Mantid/ManageCustomMenus.h
+++ b/MantidPlot/src/Mantid/ManageCustomMenus.h
@@ -6,13 +6,15 @@
 
 class ApplicationWindow;
 
-/** 
-This class handles the "Manage Custom Menus" dialog for MantidPlot, in which users can
+/**
+This class handles the "Manage Custom Menus" dialog for MantidPlot, in which
+users can
 add custom scripts or custom Qt interfaces to a menu in MantidPlot.
 
 @author Michael Whitty, ISIS
 
-Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -30,34 +32,33 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class ManageCustomMenus : public QDialog
-{
-	Q_OBJECT
+class ManageCustomMenus : public QDialog {
+  Q_OBJECT
 public:
   explicit ManageCustomMenus(QWidget *parent = 0);
 
 private:
-    void initLayout();
-    void populateMenuTree();
-    QList<QTreeWidgetItem*> getCurrentSelection();
-    QTreeWidgetItem* getCurrentMenuSelection();
+  void initLayout();
+  void populateMenuTree();
+  QList<QTreeWidgetItem *> getCurrentSelection();
+  QTreeWidgetItem *getCurrentMenuSelection();
 private slots:
-    void addScriptClicked();
-    void remScriptClicked();
-    void addItemClicked();
-    void remItemClicked();
-    void addMenuClicked();
-    void helpClicked();
+  void addScriptClicked();
+  void remScriptClicked();
+  void addItemClicked();
+  void remItemClicked();
+  void addMenuClicked();
+  void helpClicked();
 
 private:
-    Ui::ManageCustomMenus m_uiForm;
-    QMap<QTreeWidgetItem*,QObject*> m_widgetMap;
-    QTreeWidget* m_scriptsTree;
-    QTreeWidget* m_customInterfacesTree;
-    QTreeWidget* m_menusTree;
-    ApplicationWindow* m_appWindow;
+  Ui::ManageCustomMenus m_uiForm;
+  QMap<QTreeWidgetItem *, QObject *> m_widgetMap;
+  QTreeWidget *m_scriptsTree;
+  QTreeWidget *m_customInterfacesTree;
+  QTreeWidget *m_menusTree;
+  ApplicationWindow *m_appWindow;
 };
 
 #endif /* MANTID_MANAGE_CUSTOM_MENUS_H */
\ No newline at end of file
diff --git a/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp b/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp
index e50ed7f95944413aec6f3b442af6a4bf0f37d41f..01b04baab20b8cf7c2e56e955b865229e6b45574 100644
--- a/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp
+++ b/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp
@@ -14,9 +14,9 @@
  *
  * @param allCategories :: the set of all categories to be used in the model.
  */
-InterfaceCategoryModel::InterfaceCategoryModel(const QSet<QString> & allCategories) : QAbstractListModel(),
-  m_allCategories(allCategories.toList())
-{
+InterfaceCategoryModel::InterfaceCategoryModel(
+    const QSet<QString> &allCategories)
+    : QAbstractListModel(), m_allCategories(allCategories.toList()) {
   qSort(m_allCategories);
   loadHiddenCategories();
 }
@@ -26,25 +26,28 @@ InterfaceCategoryModel::InterfaceCategoryModel(const QSet<QString> & allCategori
  *
  * @param parent :: unused.
  */
-int InterfaceCategoryModel::rowCount(const QModelIndex & parent) const
-{
+int InterfaceCategoryModel::rowCount(const QModelIndex &parent) const {
   UNUSED_ARG(parent);
 
   return m_allCategories.size();
 }
 
 /**
- * The data to be put in the given header item.  Overrides virtual method of parent class.
+ * The data to be put in the given header item.  Overrides virtual method of
+ *parent class.
  *
  * @param section :: unused
- * @param orientation :: either the top (horizontal) or left-hand (vertical) header.
- * @param role :: the "role" of the data, which can be one of several enum values.  See Qt docs for more info.
+ * @param orientation :: either the top (horizontal) or left-hand (vertical)
+ *header.
+ * @param role :: the "role" of the data, which can be one of several enum
+ *values.  See Qt docs for more info.
  */
-QVariant InterfaceCategoryModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
+QVariant InterfaceCategoryModel::headerData(int section,
+                                            Qt::Orientation orientation,
+                                            int role) const {
   UNUSED_ARG(section);
 
-  if( role == Qt::DisplayRole && orientation == Qt::Horizontal )
+  if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
     return QString("Show Interface Categories");
 
   return QVariant();
@@ -54,21 +57,20 @@ QVariant InterfaceCategoryModel::headerData(int section, Qt::Orientation orienta
  * The data assigned to a given item.  Overrides virtual method of parent class.
  *
  * @param index :: the index of the item.
- * @param role :: the "role" of the data, which can be one of several enum values.  See Qt docs for more info.
+ * @param role :: the "role" of the data, which can be one of several enum
+ *values.  See Qt docs for more info.
  */
-QVariant InterfaceCategoryModel::data(const QModelIndex & index, int role) const
-{
-  if( !index.isValid() )
+QVariant InterfaceCategoryModel::data(const QModelIndex &index,
+                                      int role) const {
+  if (!index.isValid())
     return QVariant();
-  
-  if( role == Qt::DisplayRole )
-  {
+
+  if (role == Qt::DisplayRole) {
     return m_allCategories[index.row()];
   }
-  if( role == Qt::CheckStateRole )
-  {
+  if (role == Qt::CheckStateRole) {
     QString category = m_allCategories[index.row()];
-    if( m_hiddenCategories.contains(category) )
+    if (m_hiddenCategories.contains(category))
       return Qt::Unchecked;
     else
       return Qt::Checked;
@@ -82,22 +84,22 @@ QVariant InterfaceCategoryModel::data(const QModelIndex & index, int role) const
  *
  * @param index :: the index of the item.
  * @param value :: the data to assign to the item.
- * @param role :: the "role" of the data, which can be one of several enum values.  See Qt docs for more info.
+ * @param role :: the "role" of the data, which can be one of several enum
+ *values.  See Qt docs for more info.
  */
-bool InterfaceCategoryModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
-  if( !index.isValid() )
+bool InterfaceCategoryModel::setData(const QModelIndex &index,
+                                     const QVariant &value, int role) {
+  if (!index.isValid())
     return false;
 
-  if (index.isValid() && role == Qt::CheckStateRole)
-  {
+  if (index.isValid() && role == Qt::CheckStateRole) {
     auto category = m_allCategories[index.row()];
 
-    if( value == Qt::Unchecked )
+    if (value == Qt::Unchecked)
       m_hiddenCategories.insert(category);
     else
       m_hiddenCategories.remove(category);
-    
+
     emit dataChanged(index, index);
     return true;
   }
@@ -108,19 +110,18 @@ bool InterfaceCategoryModel::setData(const QModelIndex &index, const QVariant &v
 /**
  * The total number of categories.  Overrides virtual method of parent class.
  */
-Qt::ItemFlags InterfaceCategoryModel::flags(const QModelIndex & index) const
-{
+Qt::ItemFlags InterfaceCategoryModel::flags(const QModelIndex &index) const {
   return Qt::ItemIsUserCheckable | QAbstractListModel::flags(index);
 }
 
 /**
  * Persist this model's data to the user preferences file.
  */
-void InterfaceCategoryModel::saveHiddenCategories()
-{
-  QString propValue = static_cast<QStringList>(m_hiddenCategories.toList()).join(";");
-  
-  auto & config = Mantid::Kernel::ConfigService::Instance();
+void InterfaceCategoryModel::saveHiddenCategories() {
+  QString propValue =
+      static_cast<QStringList>(m_hiddenCategories.toList()).join(";");
+
+  auto &config = Mantid::Kernel::ConfigService::Instance();
   config.setString("interfaces.categories.hidden", propValue.toStdString());
   config.saveConfig(config.getUserFilename());
 }
@@ -128,11 +129,10 @@ void InterfaceCategoryModel::saveHiddenCategories()
 /**
  * Load this model's data from the user preferences file.
  */
-void InterfaceCategoryModel::loadHiddenCategories()
-{
+void InterfaceCategoryModel::loadHiddenCategories() {
   const QString propValue = QString::fromStdString(
-    Mantid::Kernel::ConfigService::Instance().getString("interfaces.categories.hidden")
-  );
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "interfaces.categories.hidden"));
   m_hiddenCategories = propValue.split(";", QString::SkipEmptyParts).toSet();
 }
 
@@ -145,41 +145,35 @@ void InterfaceCategoryModel::loadHiddenCategories()
  *
  * @param parent :: the main MantidPlot ApplicationWindow object.
  */
-ManageInterfaceCategories::ManageInterfaceCategories(ApplicationWindow * parent) : QDialog(parent),
-  m_model(parent->allCategories())
-{
+ManageInterfaceCategories::ManageInterfaceCategories(ApplicationWindow *parent)
+    : QDialog(parent), m_model(parent->allCategories()) {
   initLayout();
 }
 
 /**
  * Set up the dialog.
  */
-void ManageInterfaceCategories::initLayout()
-{
+void ManageInterfaceCategories::initLayout() {
   m_uiForm.setupUi(this);
 
-  m_uiForm.categoryTreeView->setModel( &m_model );
+  m_uiForm.categoryTreeView->setModel(&m_model);
   m_uiForm.categoryTreeView->show();
 
   // OK button should save any changes and then exit.
-  connect(m_uiForm.okButton, SIGNAL(pressed()),
-          &m_model, SLOT(saveHiddenCategories()));
-  connect(m_uiForm.okButton, SIGNAL(pressed()),
-          this, SLOT(close()));
-  
+  connect(m_uiForm.okButton, SIGNAL(pressed()), &m_model,
+          SLOT(saveHiddenCategories()));
+  connect(m_uiForm.okButton, SIGNAL(pressed()), this, SLOT(close()));
+
   // Cancel should just exit.
-  connect(m_uiForm.cancelButton, SIGNAL(pressed()),
-          this, SLOT(close()));
+  connect(m_uiForm.cancelButton, SIGNAL(pressed()), this, SLOT(close()));
 
-  connect(m_uiForm.helpButton, SIGNAL(pressed()),
-          this, SLOT(helpClicked()));
+  connect(m_uiForm.helpButton, SIGNAL(pressed()), this, SLOT(helpClicked()));
 }
 
 /**
  * Opens a web browser showing the wiki page for this dialog.
  */
-void ManageInterfaceCategories::helpClicked()
-{
+void ManageInterfaceCategories::helpClicked() {
   QUrl helpUrl("http://www.mantidproject.org/ManageInterfaceCategories");
   QDesktopServices::openUrl(helpUrl);
 }
diff --git a/MantidPlot/src/Mantid/ManageInterfaceCategories.h b/MantidPlot/src/Mantid/ManageInterfaceCategories.h
index 522e04fa3f408e17daf4ee07329d12ef97d30407..25170b82eec7de05cd42f73438f74551ee03a157 100644
--- a/MantidPlot/src/Mantid/ManageInterfaceCategories.h
+++ b/MantidPlot/src/Mantid/ManageInterfaceCategories.h
@@ -11,25 +11,26 @@
 class ApplicationWindow;
 
 /**
- * Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
- * 
+ * Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ *National Laboratory & European Spallation Source
+ *
  * This file is part of Mantid.
- * 
+ *
  * Mantid is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
- * 
+ *
  * Mantid is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
- * 
+ *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- * 
+ *
  * File change history is stored at: <https://github.com/mantidproject/mantid>
- * Code Documentation is available at: <http://doxygen.mantidproject.org>    
+ * Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
 /**
@@ -37,13 +38,12 @@ class ApplicationWindow;
  * with the user's preferences about which categories to display.  It
  * interacts with the View in the ManageInterfaceCategories dialog, and
  * persists its data using the user preferences file via the ConfigService.
- 
+
  * See the Qt documentation for more information on how this class fits in to
  * their implementation of Model-View programming.
  */
-class InterfaceCategoryModel : public QAbstractListModel
-{
-	Q_OBJECT
+class InterfaceCategoryModel : public QAbstractListModel {
+  Q_OBJECT
 
 public:
   /// Constructor.
@@ -76,21 +76,21 @@ private:
 
   /// The set of all categories to be hidden.
   QSet<QString> m_hiddenCategories;
-  /// A list of all categories.  (Effectively a set, but implemented as a list so it can be sorted.
+  /// A list of all categories.  (Effectively a set, but implemented as a list
+  /// so it can be sorted.
   QList<QString> m_allCategories;
 };
 
 /**
- * This class handles the "Manage Interface Categories" dialog in MantidPlot, in 
+ * This class handles the "Manage Interface Categories" dialog in MantidPlot, in
  * which users can add or remove the various interface categories listed in the
  * "Interface" menu.
  */
-class ManageInterfaceCategories : public QDialog
-{
-	Q_OBJECT
+class ManageInterfaceCategories : public QDialog {
+  Q_OBJECT
 
 public:
-	/// Only constructor.  We insist on seeing the ApplicationWindow.
+  /// Only constructor.  We insist on seeing the ApplicationWindow.
   explicit ManageInterfaceCategories(ApplicationWindow *parent);
 
 private slots:
diff --git a/MantidPlot/src/Mantid/MantidAbout.cpp b/MantidPlot/src/Mantid/MantidAbout.cpp
index 1ffb537616a010c48e09f77124763d0205059f7c..d0175a7b7d3d1ed39e3c6c47eb25bca0c0127b41 100644
--- a/MantidPlot/src/Mantid/MantidAbout.cpp
+++ b/MantidPlot/src/Mantid/MantidAbout.cpp
@@ -1,31 +1,31 @@
 #include "MantidAbout.h"
 #include "MantidKernel/MantidVersion.h"
 
-extern const int maj_version ;
-extern const int min_version ;
-extern const int patch_version ;
+extern const int maj_version;
+extern const int min_version;
+extern const int patch_version;
 const int maj_version = 0;
 const int min_version = 9;
 const int patch_version = 5;
-extern const char * extra_version;
-extern const char * copyright_string;
-extern const char * release_date;
+extern const char *extra_version;
+extern const char *copyright_string;
+extern const char *release_date;
 
 /**
  * Constructor
  * @param parent :: The parent widget
  */
 
-MantidAbout::MantidAbout(QWidget *parent) : MantidQt::API::MantidDialog(parent)
-{
+MantidAbout::MantidAbout(QWidget *parent)
+    : MantidQt::API::MantidDialog(parent) {
   m_uiForm.setupUi(this);
 
-  QLabel* releasedate = m_uiForm.release_datevalue;
+  QLabel *releasedate = m_uiForm.release_datevalue;
   QString releaseDate(Mantid::Kernel::MantidVersion::releaseDate());
   releasedate->setText(releaseDate);
 
   QString version(Mantid::Kernel::MantidVersion::version());
-  QLabel* releaseversion = m_uiForm.release_versionvalue;
+  QLabel *releaseversion = m_uiForm.release_versionvalue;
   releaseversion->setText(version);
 
   QString release(Mantid::Kernel::MantidVersion::revision());
@@ -33,33 +33,34 @@ MantidAbout::MantidAbout(QWidget *parent) : MantidQt::API::MantidDialog(parent)
   release.append(" (<a href=\"http://github.com/mantidproject/mantid/commit/");
   release.append(Mantid::Kernel::MantidVersion::revisionFull());
   release.append("\">on github</a>)</p>");
-  QLabel* releaselabel = m_uiForm.revision_value;
+  QLabel *releaselabel = m_uiForm.revision_value;
   releaselabel->setText(release);
   releaselabel->setOpenExternalLinks(true);
 
-  QLabel* builtusing_labelvalue = m_uiForm.builtusing_labelvalue;
-  QString builtusing = "QtiPlot " + QString::number(maj_version) + "." + QString::number(min_version)
-      + "." + QString::number(patch_version) + extra_version + "  ";
+  QLabel *builtusing_labelvalue = m_uiForm.builtusing_labelvalue;
+  QString builtusing = "QtiPlot " + QString::number(maj_version) + "." +
+                       QString::number(min_version) + "." +
+                       QString::number(patch_version) + extra_version + "  ";
   builtusing += "Released: " + QString(release_date) + "<br>";
   builtusing += QString(copyright_string);
   builtusing_labelvalue->setText(builtusing);
 
-  QString mantidurl =
-      "<p><a href = http://www.mantidproject.org/Main_Page>http://www.mantidproject.org</a></p>";
-  QLabel* url = m_uiForm.mantidurl;
+  QString mantidurl = "<p><a href = "
+                      "http://www.mantidproject.org/Main_Page>http://"
+                      "www.mantidproject.org</a></p>";
+  QLabel *url = m_uiForm.mantidurl;
   url->setText(mantidurl);
   url->setOpenExternalLinks(true);
 
-  QString mantidDOI = QString::fromStdString("<p><a href = " +\
-                      Mantid::Kernel::MantidVersion::doi() + ">" +\
-                      Mantid::Kernel::MantidVersion::doi() + "</a></p>");
+  QString mantidDOI = QString::fromStdString(
+      "<p><a href = " + Mantid::Kernel::MantidVersion::doi() + ">" +
+      Mantid::Kernel::MantidVersion::doi() + "</a></p>");
   m_uiForm.mantiddoi->setText(mantidDOI);
   m_uiForm.mantiddoi->setOpenExternalLinks(true);
 
-  QString mantidCitation = QString::fromStdString("<p><a href = " +\
-                    Mantid::Kernel::MantidVersion::paperCitation() + ">" +\
-                    Mantid::Kernel::MantidVersion::paperCitation() + "</a></p>");
+  QString mantidCitation = QString::fromStdString(
+      "<p><a href = " + Mantid::Kernel::MantidVersion::paperCitation() + ">" +
+      Mantid::Kernel::MantidVersion::paperCitation() + "</a></p>");
   m_uiForm.mantidcitation->setText(mantidCitation);
   m_uiForm.mantidcitation->setOpenExternalLinks(true);
 }
-
diff --git a/MantidPlot/src/Mantid/MantidAbout.h b/MantidPlot/src/Mantid/MantidAbout.h
index 6aef3c239721424b179fd0c96f5157ed95baa220..cf9a22a038f8bf9cd28ff2a6ffcaa9e6d9c1627c 100644
--- a/MantidPlot/src/Mantid/MantidAbout.h
+++ b/MantidPlot/src/Mantid/MantidAbout.h
@@ -7,48 +7,47 @@
 #include "ui_MantidAbout.h"
 #include <MantidQtAPI/MantidDialog.h>
 
-	/** 
-    This class implements About MantidPlot dialog for mnatid help menu.
+/**
+This class implements About MantidPlot dialog for mnatid help menu.
 
-    @author Sofia Antony, ISIS, RAL
-    @date 13/01/2010
+@author Sofia Antony, ISIS, RAL
+@date 13/01/2010
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MantidAbout : public MantidQt::API::MantidDialog
-	{
+class MantidAbout : public MantidQt::API::MantidDialog {
 
-	Q_OBJECT
-	
-	public:
-		/// constructor
-          explicit MantidAbout(QWidget *parent = 0);
-                ///destructor
-          ~MantidAbout() override {}
+  Q_OBJECT
 
-        private:
-		/// form generated by QT Designer
-		Ui::MantidAbout m_uiForm;
-	};
+public:
+  /// constructor
+  explicit MantidAbout(QWidget *parent = 0);
+  /// destructor
+  ~MantidAbout() override {}
 
+private:
+  /// form generated by QT Designer
+  Ui::MantidAbout m_uiForm;
+};
 
 #endif /* MANTIDABOUT_H */
diff --git a/MantidPlot/src/Mantid/MantidApplication.cpp b/MantidPlot/src/Mantid/MantidApplication.cpp
index 34d5e56b70a15481b30ff010d5c052e5fdc743d2..2de9e735fcdfebbbdaf991fb10bef549b0cd9b4b 100644
--- a/MantidPlot/src/Mantid/MantidApplication.cpp
+++ b/MantidPlot/src/Mantid/MantidApplication.cpp
@@ -1,5 +1,5 @@
 //=============================
-//MantidApplciation definitions
+// MantidApplciation definitions
 //==============================
 #include "MantidApplication.h"
 #include "MantidQtAPI/MantidDialog.h"
@@ -12,74 +12,73 @@
 
 #include <iostream>
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("MantidApplication");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("MantidApplication");
 }
 
 /// Constructor
-MantidApplication::MantidApplication(int &argc, char ** argv ) : QApplication(argc, argv)
-{
-   try {
-     Mantid::Kernel::UsageService::Instance().setApplication("mantidplot");
-   } catch(std::runtime_error &rexc) {
-     g_log.error() << "Failed to initialize the Mantid usage service. This "
-       "is probably a sign that this Mantid is not fully or correctly set up. "
-       "Error details: " + std::string(rexc.what()) << std::endl;
-   }
+MantidApplication::MantidApplication(int &argc, char **argv)
+    : QApplication(argc, argv) {
+  try {
+    Mantid::Kernel::UsageService::Instance().setApplication("mantidplot");
+  } catch (std::runtime_error &rexc) {
+    g_log.error() << "Failed to initialize the Mantid usage service. This "
+                     "is probably a sign that this Mantid is not fully or "
+                     "correctly set up. "
+                     "Error details: " +
+                         std::string(rexc.what()) << std::endl;
+  }
 }
 
-bool MantidApplication::notify( QObject * receiver, QEvent * event )
-{
+bool MantidApplication::notify(QObject *receiver, QEvent *event) {
   bool res = false;
-  try
-  {
-    res = QApplication::notify(receiver,event);
-  }
-  catch(std::exception& e)
-  {
-    if (MantidQt::API::MantidDialog::handle(receiver,e))
+  try {
+    res = QApplication::notify(receiver, event);
+  } catch (std::exception &e) {
+    if (MantidQt::API::MantidDialog::handle(receiver, e))
       return true; // stops event propagation
 
     // Restore possible override cursor
-    while(QApplication::overrideCursor())
-    {
+    while (QApplication::overrideCursor()) {
       QApplication::restoreOverrideCursor();
     }
 
-    g_log.fatal()<<"Unexpected exception: "<<e.what()<<"\n";
+    g_log.fatal() << "Unexpected exception: " << e.what() << "\n";
     QMessageBox ask;
-    QAbstractButton *terminateButton = ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
+    QAbstractButton *terminateButton =
+        ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
     ask.addButton(tr("Continue"), QMessageBox::ActionRole);
-    ask.setText("Sorry, MantidPlot has caught an unexpected exception:\n\n"+QString::fromStdString(e.what())+
-		"\n\nWould you like to terminate MantidPlot or try to continue working?\nIf you choose to continue it is advisable to save your data and restart the application.");
+    ask.setText("Sorry, MantidPlot has caught an unexpected exception:\n\n" +
+                QString::fromStdString(e.what()) +
+                "\n\nWould you like to terminate MantidPlot or try to continue "
+                "working?\nIf you choose to continue it is advisable to save "
+                "your data and restart the application.");
     ask.setIcon(QMessageBox::Critical);
     ask.exec();
-    if (ask.clickedButton() == terminateButton)
-    {
-        g_log.fatal("Terminated by user.");
-        quit();
-    }else
-        g_log.fatal("Continue working.");
-  }
-  catch(...)
-  {
+    if (ask.clickedButton() == terminateButton) {
+      g_log.fatal("Terminated by user.");
+      quit();
+    } else
+      g_log.fatal("Continue working.");
+  } catch (...) {
 
-    g_log.fatal()<<"Unknown exception\n";
+    g_log.fatal() << "Unknown exception\n";
     QMessageBox ask;
-    QAbstractButton *terminateButton = ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
+    QAbstractButton *terminateButton =
+        ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
     ask.addButton(tr("Continue"), QMessageBox::ActionRole);
-    ask.setText("Sorry, MantidPlot has caught an unexpected exception"\
-		"\n\nWould you like to terminate MantidPlot or try to continue working?\nIf you choose to continue it is advisable to save your data and restart the application.");
+    ask.setText("Sorry, MantidPlot has caught an unexpected exception"
+                "\n\nWould you like to terminate MantidPlot or try to continue "
+                "working?\nIf you choose to continue it is advisable to save "
+                "your data and restart the application.");
     ask.setIcon(QMessageBox::Critical);
     ask.exec();
-    if (ask.clickedButton() == terminateButton)
-    {
-        g_log.fatal("Terminated by user.");
-        quit();
-    }else
-        g_log.fatal("Continue working.");
+    if (ask.clickedButton() == terminateButton) {
+      g_log.fatal("Terminated by user.");
+      quit();
+    } else
+      g_log.fatal("Continue working.");
   }
   return res;
 }
diff --git a/MantidPlot/src/Mantid/MantidApplication.h b/MantidPlot/src/Mantid/MantidApplication.h
index 81606e4c0609d5167f24eee746087e7f0b298725..87d57080ccaf7505f7ca950c9b59f1e73e8cb1e8 100644
--- a/MantidPlot/src/Mantid/MantidApplication.h
+++ b/MantidPlot/src/Mantid/MantidApplication.h
@@ -6,14 +6,12 @@
 //============================================================
 #include <QApplication>
 
-class MantidApplication:public QApplication
-{
+class MantidApplication : public QApplication {
   Q_OBJECT
 public:
-  MantidApplication(int & argc, char ** argv );
+  MantidApplication(int &argc, char **argv);
   /// Reimplement notify to catch exceptions from event handlers
   bool notify(QObject *receiver, QEvent *event) override;
 };
 
 #endif // MANTIDAPPLICATION_H_
-
diff --git a/MantidPlot/src/Mantid/MantidCurve.cpp b/MantidPlot/src/Mantid/MantidCurve.cpp
index 0b5b5ad1b369b1d4b215efa262b95f2f2fbf19ff..2cfc217bddd1edab54ebf56cb1d67cccb5cd3b66 100644
--- a/MantidPlot/src/Mantid/MantidCurve.cpp
+++ b/MantidPlot/src/Mantid/MantidCurve.cpp
@@ -20,21 +20,18 @@ Constructor
 @param err : flag indicating that all error bars should be used.
 @param allError : flag indicating that all error bars should be plotted.
 */
-MantidCurve::MantidCurve(const QString& wsName, bool err, bool allError)
- : PlotCurve(wsName), WorkspaceObserver(),
-   m_drawErrorBars(err), m_drawAllErrorBars(allError), m_errorSettings(new ErrorBarSettings(this))
-{
-}
+MantidCurve::MantidCurve(const QString &wsName, bool err, bool allError)
+    : PlotCurve(wsName), WorkspaceObserver(), m_drawErrorBars(err),
+      m_drawAllErrorBars(allError),
+      m_errorSettings(new ErrorBarSettings(this)) {}
 
 /**
-Constructor 
+Constructor
 @param err : flag indicating that errors should be used.
 */
 MantidCurve::MantidCurve(bool err)
- : PlotCurve(), WorkspaceObserver(), 
-   m_drawErrorBars(err), m_drawAllErrorBars(false), m_errorSettings(new ErrorBarSettings(this))
-{
-}
+    : PlotCurve(), WorkspaceObserver(), m_drawErrorBars(err),
+      m_drawAllErrorBars(false), m_errorSettings(new ErrorBarSettings(this)) {}
 
 /**
 Helper method to apply a chosen style.
@@ -42,71 +39,69 @@ Helper method to apply a chosen style.
 @param ml : pointer to multilayer object
 @param lineWidth: ref to linewidth, which may be internally adjusted
 */
-void MantidCurve::applyStyleChoice(Graph::CurveType style, MultiLayer* ml, int& lineWidth)
-{
+void MantidCurve::applyStyleChoice(Graph::CurveType style, MultiLayer *ml,
+                                   int &lineWidth) {
 
-  if ( style == Graph::Unspecified )
-    style = static_cast<Graph::CurveType>(ml->applicationWindow()->defaultCurveStyle);
+  if (style == Graph::Unspecified)
+    style = static_cast<Graph::CurveType>(
+        ml->applicationWindow()->defaultCurveStyle);
 
   QwtPlotCurve::CurveStyle qwtStyle;
   const int symbolSize = ml->applicationWindow()->defaultSymbolSize;
-  const QwtSymbol symbol(QwtSymbol::Ellipse, QBrush(Qt::black),QPen(),QSize(symbolSize,symbolSize));
-  switch(style)
-  {
-  case Graph::Line :
+  const QwtSymbol symbol(QwtSymbol::Ellipse, QBrush(Qt::black), QPen(),
+                         QSize(symbolSize, symbolSize));
+  switch (style) {
+  case Graph::Line:
     qwtStyle = QwtPlotCurve::Lines;
     break;
   case Graph::Scatter:
     qwtStyle = QwtPlotCurve::NoCurve;
     this->setSymbol(symbol);
     break;
-  case Graph::LineSymbols :
+  case Graph::LineSymbols:
     qwtStyle = QwtPlotCurve::Lines;
     this->setSymbol(symbol);
     break;
   case 15:
     qwtStyle = QwtPlotCurve::Steps;
-    break;  // should be Graph::HorizontalSteps but it doesn't work
+    break; // should be Graph::HorizontalSteps but it doesn't work
   default:
     qwtStyle = QwtPlotCurve::Lines;
     break;
   }
   setStyle(qwtStyle);
-  lineWidth = static_cast<int>(floor(ml->applicationWindow()->defaultCurveLineWidth));
+  lineWidth =
+      static_cast<int>(floor(ml->applicationWindow()->defaultCurveLineWidth));
 }
 
 /**
-Rebuild the bounding rectangle. Uses the mantidData (QwtMantidWorkspaceData) object to do so.
+Rebuild the bounding rectangle. Uses the mantidData (QwtMantidWorkspaceData)
+object to do so.
 */
-QwtDoubleRect MantidCurve::boundingRect() const
-{
-  if (m_boundingRect.isNull())
-  {
+QwtDoubleRect MantidCurve::boundingRect() const {
+  if (m_boundingRect.isNull()) {
     const auto data = mantidData();
-    if (data->size() == 0) return QwtDoubleRect(0,0,1,1);
+    if (data->size() == 0)
+      return QwtDoubleRect(0, 0, 1, 1);
     double y_min = data->getYMin();
     double y_max = data->getYMax();
     double x_min = data->x(0);
-    double x_max = data->x(data->size()-1);
-    m_boundingRect = QwtDoubleRect(x_min,y_min,x_max-x_min,y_max-y_min);
+    double x_max = data->x(data->size() - 1);
+    m_boundingRect = QwtDoubleRect(x_min, y_min, x_max - x_min, y_max - y_min);
   }
   return m_boundingRect;
 }
 
 /// Invalidates the bounding rect forcing it to be recalculated
-void MantidCurve::invalidateBoundingRect() {
-  m_boundingRect = QwtDoubleRect();
-}
+void MantidCurve::invalidateBoundingRect() { m_boundingRect = QwtDoubleRect(); }
 
 /**
 Slot for axis scale changed. Invalidate and rebuild the bounding rectangle.
 @param axis: axis index.
 @param toLog: true if switching to a log value
 */
-void MantidCurve::axisScaleChanged(int axis, bool toLog)
-{
-  if (axis == QwtPlot::yLeft || axis == QwtPlot::yRight)
-  {
+void MantidCurve::axisScaleChanged(int axis, bool toLog) {
+  if (axis == QwtPlot::yLeft || axis == QwtPlot::yRight) {
     mantidData()->setLogScaleY(toLog);
     // force boundingRect calculation at this moment
     invalidateBoundingRect();
@@ -115,20 +110,15 @@ void MantidCurve::axisScaleChanged(int axis, bool toLog)
 }
 
 /// Destructor
-MantidCurve::~MantidCurve()
-{
-}
+MantidCurve::~MantidCurve() {}
 
-
-void MantidCurve::itemChanged()
-{
-  //Forward request onwards
+void MantidCurve::itemChanged() {
+  // Forward request onwards
   PlotCurve::itemChanged();
 }
 
-QList<ErrorBarSettings*> MantidCurve::errorBarSettingsList() const
-{
-  QList<ErrorBarSettings*> retval;
+QList<ErrorBarSettings *> MantidCurve::errorBarSettingsList() const {
+  QList<ErrorBarSettings *> retval;
   retval.append(m_errorSettings);
   return retval;
 }
@@ -136,44 +126,41 @@ QList<ErrorBarSettings*> MantidCurve::errorBarSettingsList() const
 /** Create the name for a curve which is a copy of another curve.
  *  @param curveName :: The original curve name.
  */
-QString MantidCurve::createCopyName(const QString& curveName)
-{
+QString MantidCurve::createCopyName(const QString &curveName) {
   int i = curveName.lastIndexOf(" (copy");
-  if (i < 0) return curveName+" (copy)";
+  if (i < 0)
+    return curveName + " (copy)";
   int j = curveName.lastIndexOf(")");
-  if (j == i + 5) return curveName.mid(0,i)+" (copy2)";
-  int k = curveName.mid(i+5,j-i-5).toInt();
-  return curveName.mid(0,i)+" (copy"+QString::number(k+1)+")";
+  if (j == i + 5)
+    return curveName.mid(0, i) + " (copy2)";
+  int k = curveName.mid(i + 5, j - i - 5).toInt();
+  return curveName.mid(0, i) + " (copy" + QString::number(k + 1) + ")";
 }
 
-
-void MantidCurve::doDraw(QPainter *p, 
-          const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-          const QRect&, MantidQwtWorkspaceData const * const d) const
-{
+void MantidCurve::doDraw(QPainter *p, const QwtScaleMap &xMap,
+                         const QwtScaleMap &yMap, const QRect &,
+                         MantidQwtWorkspaceData const *const d) const {
   int sh = 0;
-  if (symbol().style() != QwtSymbol::NoSymbol)
-  {
+  if (symbol().style() != QwtSymbol::NoSymbol) {
     sh = symbol().size().height() / 2;
   }
 
   int xi0 = 0;
   QPen mypen(pen());
-  if ( ! m_errorSettings->m_defaultColor)
+  if (!m_errorSettings->m_defaultColor)
     mypen.setColor(m_errorSettings->color());
   mypen.setWidthF(m_errorSettings->width());
   p->setPen(mypen);
-  const int dx = m_errorSettings->capLength()/2;
-  const int dx2 = 2*dx;
+  const int dx = m_errorSettings->capLength() / 2;
+  const int dx2 = 2 * dx;
   const int x1 = static_cast<int>(floor(xMap.p1()));
   const int x2 = static_cast<int>(floor(xMap.p2()));
-  
+
   const int skipPoints = skipSymbolsCount();
-  for (int i = 0; i < static_cast<int>(d->esize()); i += skipPoints)
-  {
+  for (int i = 0; i < static_cast<int>(d->esize()); i += skipPoints) {
     const int xi = xMap.transform(d->ex(i));
-    if (m_drawAllErrorBars || (xi > x1 && xi < x2 && (i == 0 || abs(xi - xi0) > dx2)))
-    {
+    if (m_drawAllErrorBars ||
+        (xi > x1 && xi < x2 && (i == 0 || abs(xi - xi0) > dx2))) {
       const double Y = y(i);
       const double E = d->e(i);
       const int yi = yMap.transform(Y);
@@ -186,29 +173,25 @@ void MantidCurve::doDraw(QPainter *p,
       const int yhl = yi - sh;
       const int ylh = yi + sh;
 
-
-      if ( m_errorSettings->minusSide() )
-      {
+      if (m_errorSettings->minusSide()) {
         // This call can crash MantidPlot if the error is zero,
         //   so protect against this (line of zero length anyway)
         if (E != 0.0)
           p->drawLine(xi, ei1, xi, ylh);
-        p->drawLine(xi-dx,ei1,xi+dx,ei1);
+        p->drawLine(xi - dx, ei1, xi + dx, ei1);
       }
-      if ( m_errorSettings->plusSide() )
-      {
+      if (m_errorSettings->plusSide()) {
         // This call can crash MantidPlot if the error is zero,
         //   so protect against this (line of zero length anyway)
         if (E != 0.0)
           p->drawLine(xi, yhl, xi, ei2);
-        p->drawLine(xi-dx,ei2,xi+dx,ei2);
+        p->drawLine(xi - dx, ei2, xi + dx, ei2);
       }
-      if ( m_errorSettings->throughSymbol() )
-      {
+      if (m_errorSettings->throughSymbol()) {
         if (E != 0.0)
           p->drawLine(xi, yhl, xi, ylh);
       }
-      
+
       xi0 = xi;
     }
   }
diff --git a/MantidPlot/src/Mantid/MantidCurve.h b/MantidPlot/src/Mantid/MantidCurve.h
index 8c37ce8b9b1c897722aa74265fef4608812c4777..8f158965e8d63200d50723dd078c0066e0fb85ce 100644
--- a/MantidPlot/src/Mantid/MantidCurve.h
+++ b/MantidPlot/src/Mantid/MantidCurve.h
@@ -9,9 +9,10 @@
 class Graph;
 class ErrorBarSettings;
 
-/** Base class for MantidCurve types. 
+/** Base class for MantidCurve types.
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -30,34 +31,31 @@ class ErrorBarSettings;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MantidCurve :public PlotCurve, public MantidQt::API::WorkspaceObserver
-{
+class MantidCurve : public PlotCurve, public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 public:
   /// Constructor
-  MantidCurve(const QString& wsName, bool error, bool allerror = false);
+  MantidCurve(const QString &wsName, bool error, bool allerror = false);
   /// Default constructor
   explicit MantidCurve(bool err);
   /// Destructor
   ~MantidCurve() override;
   /// Clone
   MantidCurve *clone(const Graph *g) const override = 0;
-  /// Get mantid data 
-  virtual const MantidQwtWorkspaceData* mantidData() const = 0;
-  /// Get mantid data 
-  virtual MantidQwtWorkspaceData* mantidData() = 0;
+  /// Get mantid data
+  virtual const MantidQwtWorkspaceData *mantidData() const = 0;
+  /// Get mantid data
+  virtual MantidQwtWorkspaceData *mantidData() = 0;
   /// Overriden virtual method
   void itemChanged() override;
 
   /// Returns whether the curve has error bars
-  bool hasErrorBars() const
-  {
-    return m_drawErrorBars;
-  }
+  bool hasErrorBars() const { return m_drawErrorBars; }
 
-  /// Returns the error bar settings for this curve (a MantidCurve has only one set of error bars)
+  /// Returns the error bar settings for this curve (a MantidCurve has only one
+  /// set of error bars)
   QList<ErrorBarSettings *> errorBarSettingsList() const override;
 
   /// Invalidates the bounding rect forcing it to be recalculated
@@ -74,7 +72,7 @@ public:
   -------------------------------------------------------------------------------------*/
 
 protected slots:
-  
+
   void axisScaleChanged(int axis, bool toLog);
 
 protected:
@@ -83,32 +81,32 @@ protected:
   -------------------------------------------------------------------------------------*/
 
   /// Apply the style choice
-  void applyStyleChoice(Graph::CurveType style, MultiLayer* ml, int& lineWidth);
+  void applyStyleChoice(Graph::CurveType style, MultiLayer *ml, int &lineWidth);
 
   /// Make a name for a copied curve
-  static QString createCopyName(const QString& curveName);
+  static QString createCopyName(const QString &curveName);
 
   /// Draw the curve.
-  void doDraw(QPainter *p, 
-    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-    const QRect &rect, MantidQwtWorkspaceData const * const data) const;
+  void doDraw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+              const QRect &rect,
+              MantidQwtWorkspaceData const *const data) const;
 
   /*-------------------------------------------------------------------------------------
   End Protected Base/Common methods
   -------------------------------------------------------------------------------------*/
-   bool m_drawErrorBars; /// Flag indicating that error bars should be drawn.
-   bool m_drawAllErrorBars; ///< if true and m_drawErrorBars is true draw all error bars (no skipping)
+  bool m_drawErrorBars;    /// Flag indicating that error bars should be drawn.
+  bool m_drawAllErrorBars; ///< if true and m_drawErrorBars is true draw all
+  /// error bars (no skipping)
 
-   // The error bar settings for this curve. Owned by this class.
-   ErrorBarSettings * m_errorSettings;
+  // The error bar settings for this curve. Owned by this class.
+  ErrorBarSettings *m_errorSettings;
 
 private:
   /// The bounding rect used by qwt to set the axes
   mutable QwtDoubleRect m_boundingRect;
-  
-  //To ensure that all MantidCurves can work with Mantid Workspaces.
-  virtual void init(Graph* g, bool distr, Graph::CurveType style) = 0;
+
+  // To ensure that all MantidCurves can work with Mantid Workspaces.
+  virtual void init(Graph *g, bool distr, Graph::CurveType style) = 0;
 };
 
 #endif
-
diff --git a/MantidPlot/src/Mantid/MantidDock.h b/MantidPlot/src/Mantid/MantidDock.h
index cc57e272800a68941e91cc0d92794239f74cd4e2..ea1351e7c3c00e694ae29bd5573773f2fd94d5e3 100644
--- a/MantidPlot/src/Mantid/MantidDock.h
+++ b/MantidPlot/src/Mantid/MantidDock.h
@@ -43,13 +43,9 @@ class QHBoxLayout;
 class QSignalMapper;
 class QSortFilterProxyModel;
 
-enum MantidItemSortScheme
-{
-  ByName, ByLastModified
-};
+enum MantidItemSortScheme { ByName, ByLastModified };
 
-class MantidDockWidget: public QDockWidget
-{
+class MantidDockWidget : public QDockWidget {
   Q_OBJECT
 public:
   MantidDockWidget(MantidUI *mui, ApplicationWindow *parent);
@@ -59,12 +55,12 @@ public:
   void dropEvent(QDropEvent *de) override;
 
 public slots:
-  void clickedWorkspace(QTreeWidgetItem*, int);
+  void clickedWorkspace(QTreeWidgetItem *, int);
   void saveWorkspaceGroup();
   void deleteWorkspaces();
   void renameWorkspace();
-  void populateChildData(QTreeWidgetItem* item);
-  void saveToProgram(const QString & name);
+  void populateChildData(QTreeWidgetItem *item);
+  void saveToProgram(const QString &name);
   void sortAscending();
   void sortDescending();
   void chooseByName();
@@ -72,7 +68,7 @@ public slots:
   void saveWorkspacesToFolder(const QString &folder);
 
 protected slots:
-  void popupMenu(const QPoint & pos);
+  void popupMenu(const QPoint &pos);
   void workspaceSelected();
 
 private slots:
@@ -87,7 +83,7 @@ private slots:
   void convertMDHistoToMatrixWorkspace();
   void updateTree();
   void incrementUpdateCount();
-  void recordWorkspaceRename(QString,QString);
+  void recordWorkspaceRename(QString, QString);
   void clearUB();
   void filterWorkspaceTree(const QString &text);
   void plotSurface();
@@ -97,32 +93,42 @@ private:
   void addSaveMenuOption(QString algorithmString, QString menuEntryName = "");
   void setTreeUpdating(const bool state);
   inline bool isTreeUpdating() const { return m_treeUpdating; }
-  void populateTopLevel(const std::map<std::string,Mantid::API::Workspace_sptr> & topLevelItems, const QStringList & expanded);
-  MantidTreeWidgetItem * addTreeEntry(const std::pair<std::string,Mantid::API::Workspace_sptr> & item, QTreeWidgetItem* parent = NULL);
+  void populateTopLevel(
+      const std::map<std::string, Mantid::API::Workspace_sptr> &topLevelItems,
+      const QStringList &expanded);
+  MantidTreeWidgetItem *
+  addTreeEntry(const std::pair<std::string, Mantid::API::Workspace_sptr> &item,
+               QTreeWidgetItem *parent = NULL);
   bool shouldBeSelected(QString name) const;
   void createWorkspaceMenuActions();
   void createSortMenuActions();
-  void setItemIcon(QTreeWidgetItem *item,  const std::string & wsID);
-
-  void addMatrixWorkspaceMenuItems(QMenu *menu, const Mantid::API::MatrixWorkspace_const_sptr & matrixWS) const;
-  void addMDEventWorkspaceMenuItems(QMenu *menu, const Mantid::API::IMDEventWorkspace_const_sptr & mdeventWS) const;
-  void addMDHistoWorkspaceMenuItems(QMenu *menu, const Mantid::API::IMDWorkspace_const_sptr & WS) const;
-  void addPeaksWorkspaceMenuItems(QMenu *menu, const Mantid::API::IPeaksWorkspace_const_sptr & WS) const;
+  void setItemIcon(QTreeWidgetItem *item, const std::string &wsID);
+
+  void addMatrixWorkspaceMenuItems(
+      QMenu *menu,
+      const Mantid::API::MatrixWorkspace_const_sptr &matrixWS) const;
+  void addMDEventWorkspaceMenuItems(
+      QMenu *menu,
+      const Mantid::API::IMDEventWorkspace_const_sptr &mdeventWS) const;
+  void addMDHistoWorkspaceMenuItems(
+      QMenu *menu, const Mantid::API::IMDWorkspace_const_sptr &WS) const;
+  void addPeaksWorkspaceMenuItems(
+      QMenu *menu, const Mantid::API::IPeaksWorkspace_const_sptr &WS) const;
   void addWorkspaceGroupMenuItems(
       QMenu *menu, const Mantid::API::WorkspaceGroup_const_sptr &groupWS) const;
-  void addTableWorkspaceMenuItems(QMenu * menu) const;
-  void addClearMenuItems(QMenu* menu, const QString& wsName);
+  void addTableWorkspaceMenuItems(QMenu *menu) const;
+  void addClearMenuItems(QMenu *menu, const QString &wsName);
 
   void excludeItemFromSort(MantidTreeWidgetItem *item);
 
 protected:
-  MantidTreeWidget * m_tree;
+  MantidTreeWidget *m_tree;
   friend class MantidUI;
 
 private:
   QString selectedWsName;
-  
-  MantidUI * const m_mantidUI;
+
+  MantidUI *const m_mantidUI;
 
   QPushButton *m_loadButton;
   QPushButton *m_saveButton;
@@ -149,16 +155,15 @@ private:
 
   QAtomicInt m_updateCount;
   bool m_treeUpdating;
-  Mantid::API::AnalysisDataServiceImpl & m_ads;
+  Mantid::API::AnalysisDataServiceImpl &m_ads;
   /// Temporarily keeps names of selected workspaces during tree update
   /// in order to restore selection after update
   QStringList m_selectedNames;
   /// Keep a map of renamed workspaces between updates
-  QMap<QString,QString> m_renameMap;
+  QMap<QString, QString> m_renameMap;
 };
 
-class MantidTreeWidget:public QTreeWidget
-{
+class MantidTreeWidget : public QTreeWidget {
   Q_OBJECT
 
 public:
@@ -175,7 +180,7 @@ public:
   void setSortOrder(Qt::SortOrder);
   MantidItemSortScheme getSortScheme() const;
   Qt::SortOrder getSortOrder() const;
-  void logWarningMessage(const std::string&);
+  void logWarningMessage(const std::string &);
   void disableNodes(bool);
   void sort();
   void dropEvent(QDropEvent *de) override;
@@ -196,55 +201,53 @@ private:
   QPoint m_dragStartPosition;
   MantidDockWidget *m_dockWidget;
   MantidUI *m_mantidUI;
-  Mantid::API::AnalysisDataServiceImpl & m_ads;
+  Mantid::API::AnalysisDataServiceImpl &m_ads;
   MantidItemSortScheme m_sortScheme;
-  Qt::SortOrder m_sortOrder;  
+  Qt::SortOrder m_sortOrder;
 };
 
 /**A class derived from QTreeWidgetItem, to accomodate
  * sorting on the items in a MantidTreeWidget.
  */
-class MantidTreeWidgetItem : public QTreeWidgetItem
-{
+class MantidTreeWidgetItem : public QTreeWidgetItem {
 public:
   explicit MantidTreeWidgetItem(MantidTreeWidget *);
-  MantidTreeWidgetItem(QStringList, MantidTreeWidget*);
+  MantidTreeWidgetItem(QStringList, MantidTreeWidget *);
   void disableIfNode(bool);
-  void setSortPos(int o) {m_sortPos = o;}
-  int getSortPos() const {return m_sortPos;}
-
+  void setSortPos(int o) { m_sortPos = o; }
+  int getSortPos() const { return m_sortPos; }
 
 private:
   bool operator<(const QTreeWidgetItem &other) const override;
-  MantidTreeWidget* m_parent;
-  static Mantid::Kernel::DateAndTime getLastModified(const QTreeWidgetItem*);
+  MantidTreeWidget *m_parent;
+  static Mantid::Kernel::DateAndTime getLastModified(const QTreeWidgetItem *);
   int m_sortPos;
 };
 
-
-class AlgorithmDockWidget: public QDockWidget
-{
-    Q_OBJECT
+class AlgorithmDockWidget : public QDockWidget {
+  Q_OBJECT
 public:
-    AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w);
+  AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w);
 public slots:
-    void update();
-    void updateProgress(void* alg, const double p, const QString& msg, double estimatedTime, int progressPrecision);
-    void algorithmStarted(void* alg);
-    void algorithmFinished(void* alg);
+  void update();
+  void updateProgress(void *alg, const double p, const QString &msg,
+                      double estimatedTime, int progressPrecision);
+  void algorithmStarted(void *alg);
+  void algorithmFinished(void *alg);
+
 protected:
-    void showProgressBar();
-    void hideProgressBar();
-
-    MantidQt::MantidWidgets::AlgorithmSelectorWidget * m_selector;
-    QPushButton *m_runningButton;
-    QProgressBar* m_progressBar;
-    QHBoxLayout * m_runningLayout;
-    QList<void*> m_algID;
-    friend class MantidUI;
+  void showProgressBar();
+  void hideProgressBar();
+
+  MantidQt::MantidWidgets::AlgorithmSelectorWidget *m_selector;
+  QPushButton *m_runningButton;
+  QProgressBar *m_progressBar;
+  QHBoxLayout *m_runningLayout;
+  QList<void *> m_algID;
+  friend class MantidUI;
+
 private:
-    MantidUI *m_mantidUI;
+  MantidUI *m_mantidUI;
 };
 
-
 #endif
diff --git a/MantidPlot/src/Mantid/MantidGroupPlotGenerator.cpp b/MantidPlot/src/Mantid/MantidGroupPlotGenerator.cpp
index 943050f87a663b7b7a2cfed58050fb55195d8fcf..2fede3c1cd45fef86938730d5ddb66a27d7bfcf0 100644
--- a/MantidPlot/src/Mantid/MantidGroupPlotGenerator.cpp
+++ b/MantidPlot/src/Mantid/MantidGroupPlotGenerator.cpp
@@ -117,7 +117,6 @@ MantidGroupPlotGenerator::createWorkspaceForGroupPlot(
       xAxisLabel = firstWS->getXDimension()->getName();
       xAxisUnits = firstWS->getXDimension()->getUnits();
 
-
       // For each workspace in group, add data and log values
       std::vector<double> logValues;
       for (int i = 0; i < nWorkspaces; i++) {
diff --git a/MantidPlot/src/Mantid/MantidGroupPlotGenerator.h b/MantidPlot/src/Mantid/MantidGroupPlotGenerator.h
index 2aad97a17426f567dee95f1cbc1f2e2feb4b989b..ff864c2b69f85dfd34d0f02cbcdb58a36823f6c2 100644
--- a/MantidPlot/src/Mantid/MantidGroupPlotGenerator.h
+++ b/MantidPlot/src/Mantid/MantidGroupPlotGenerator.h
@@ -8,7 +8,7 @@
 
 /**
 * This utility class generates a surface or contour plot from a group of
-* workspaces. 
+* workspaces.
 */
 class MantidGroupPlotGenerator {
 public:
@@ -68,8 +68,7 @@ private:
   void convertXData(Mantid::API::MatrixWorkspace_sptr ws, Type graphType) const;
 
   /// Pointer to the Mantid UI
-  MantidUI * const m_mantidUI;
+  MantidUI *const m_mantidUI;
 };
 
-
 #endif
diff --git a/MantidPlot/src/Mantid/MantidMDCurve.cpp b/MantidPlot/src/Mantid/MantidMDCurve.cpp
index c796218815d9276b74a639629ee4ecc5690e25a0..7a199c3cf50f19bdce8c4b3321ff07988afb497d 100644
--- a/MantidPlot/src/Mantid/MantidMDCurve.cpp
+++ b/MantidPlot/src/Mantid/MantidMDCurve.cpp
@@ -9,14 +9,12 @@
 #include "../ApplicationWindow.h"
 #include "../MultiLayer.h"
 
-
 using namespace Mantid::API;
 using namespace MantidQt::API;
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("MantidMDCurve");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("MantidMDCurve");
 }
 
 /**
@@ -25,27 +23,27 @@ namespace
  *  @param err :: True if the errors are to be plotted
  *  @param distr :: True if this is a distribution
  *  @param style :: Graph style
- *  @throw std::invalid_argument if the index is out of range for the given workspace
+ *  @throw std::invalid_argument if the index is out of range for the given
+ * workspace
  */
-MantidMDCurve::MantidMDCurve(const QString& wsName,Graph* g,bool err,bool distr,Graph::CurveType style)
-  :MantidCurve(wsName, err),
-  m_wsName(wsName)
-{
-  if(!g)
-  {
-    throw std::invalid_argument("MantidMDCurve::MantidMDCurve() - NULL graph pointer not allowed");
+MantidMDCurve::MantidMDCurve(const QString &wsName, Graph *g, bool err,
+                             bool distr, Graph::CurveType style)
+    : MantidCurve(wsName, err), m_wsName(wsName) {
+  if (!g) {
+    throw std::invalid_argument(
+        "MantidMDCurve::MantidMDCurve() - NULL graph pointer not allowed");
   }
-  init(g,distr,style);
+  init(g, distr, style);
 }
 
-
-MantidMDCurve::MantidMDCurve(const MantidMDCurve& c)
-  :MantidCurve(createCopyName(c.title().text()), c.m_drawErrorBars, c.m_drawAllErrorBars),
-  m_wsName(c.m_wsName)
-{
+MantidMDCurve::MantidMDCurve(const MantidMDCurve &c)
+    : MantidCurve(createCopyName(c.title().text()), c.m_drawErrorBars,
+                  c.m_drawAllErrorBars),
+      m_wsName(c.m_wsName) {
   setData(c.data());
   observePostDelete();
-  connect( this, SIGNAL(resetData(const QString&)), this, SLOT(dataReset(const QString&)) );
+  connect(this, SIGNAL(resetData(const QString &)), this,
+          SLOT(dataReset(const QString &)));
   observeAfterReplace();
   observeADSClear();
 }
@@ -55,41 +53,37 @@ MantidMDCurve::MantidMDCurve(const MantidMDCurve& c)
  *  @param distr :: True if this is a distribution
  *  @param style :: The graph style to use
  */
-void MantidMDCurve::init(Graph* g, bool distr, Graph::CurveType style)
-{
+void MantidMDCurve::init(Graph *g, bool distr, Graph::CurveType style) {
   UNUSED_ARG(distr);
   IMDWorkspace_const_sptr ws = boost::dynamic_pointer_cast<IMDWorkspace>(
-              AnalysisDataService::Instance().retrieve(m_wsName.toStdString()) );
-  if(!ws)
-  {
-    std::string message = "Could not extract IMDWorkspace of name: " + m_wsName.toStdString();
+      AnalysisDataService::Instance().retrieve(m_wsName.toStdString()));
+  if (!ws) {
+    std::string message =
+        "Could not extract IMDWorkspace of name: " + m_wsName.toStdString();
     throw std::runtime_error(message);
   }
-  if(ws->getNonIntegratedDimensions().size() != 1)
-  {
-    std::string message = "This plot only applies to MD Workspaces with a single expanded dimension";
+  if (ws->getNonIntegratedDimensions().size() != 1) {
+    std::string message = "This plot only applies to MD Workspaces with a "
+                          "single expanded dimension";
     throw std::invalid_argument(message);
   }
 
   this->setTitle(m_wsName + "-signal");
 
   const bool log = g->isLog(QwtPlot::yLeft);
-  MantidQwtIMDWorkspaceData data(ws,log);
+  MantidQwtIMDWorkspaceData data(ws, log);
   setData(data);
 
   int lineWidth = 1;
-  MultiLayer* ml = dynamic_cast<MultiLayer*>(g->parent()->parent()->parent());
-  if (ml && (style == Graph::Unspecified || ml->applicationWindow()->applyCurveStyleToMantid) )
-  {
-    //FIXME: Style HorizontalSteps does NOT seem to be applied
+  MultiLayer *ml = dynamic_cast<MultiLayer *>(g->parent()->parent()->parent());
+  if (ml && (style == Graph::Unspecified ||
+             ml->applicationWindow()->applyCurveStyleToMantid)) {
+    // FIXME: Style HorizontalSteps does NOT seem to be applied
     applyStyleChoice(style, ml, lineWidth);
-  }
-  else
-  {
+  } else {
     setStyle(QwtPlotCurve::Lines);
   }
-  g->insertCurve(this,lineWidth);
-
+  g->insertCurve(this, lineWidth);
 
   // set the option to draw all error bars from the global settings
   if (hasErrorBars()) {
@@ -99,16 +93,16 @@ void MantidMDCurve::init(Graph* g, bool distr, Graph::CurveType style)
   m_errorSettings->m_color = pen().color();
   m_errorSettings->setWidth(pen().widthF());
 
-  connect(g,SIGNAL(axisScaleChanged(int,bool)),this,SLOT(axisScaleChanged(int,bool)));
+  connect(g, SIGNAL(axisScaleChanged(int, bool)), this,
+          SLOT(axisScaleChanged(int, bool)));
   observePostDelete();
-  connect( this, SIGNAL(resetData(const QString&)), this, SLOT(dataReset(const QString&)) );
+  connect(this, SIGNAL(resetData(const QString &)), this,
+          SLOT(dataReset(const QString &)));
   observeAfterReplace();
   observeADSClear();
 }
 
-
-MantidMDCurve::~MantidMDCurve()
-{
+MantidMDCurve::~MantidMDCurve() {
   observePostDelete(false);
   observeAfterReplace(false);
   observeADSClear(false);
@@ -117,112 +111,109 @@ MantidMDCurve::~MantidMDCurve()
 /**
  * Clone the curve for the use by a particular Graph
  */
-MantidMDCurve* MantidMDCurve::clone(const Graph*)const
-{
-  MantidMDCurve* mc = new MantidMDCurve(*this);/*
-  if (g)
-  {
-    mc->setDrawAsDistribution(g->isDistribution());
-  }*/
+MantidMDCurve *MantidMDCurve::clone(const Graph *) const {
+  MantidMDCurve *mc = new MantidMDCurve(*this); /*
+   if (g)
+   {
+     mc->setDrawAsDistribution(g->isDistribution());
+   }*/
   return mc;
 }
 
-
-void MantidMDCurve::setData(const QwtData &data)
-{
-  if (!dynamic_cast<const MantidQwtIMDWorkspaceData*>(&data)) 
-    throw std::runtime_error("Only MantidQwtIMDWorkspaceData can be set to a MantidMDCurve");
+void MantidMDCurve::setData(const QwtData &data) {
+  if (!dynamic_cast<const MantidQwtIMDWorkspaceData *>(&data))
+    throw std::runtime_error(
+        "Only MantidQwtIMDWorkspaceData can be set to a MantidMDCurve");
   PlotCurve::setData(data);
 }
 
-QwtDoubleRect MantidMDCurve::boundingRect() const
-{
+QwtDoubleRect MantidMDCurve::boundingRect() const {
   return MantidCurve::boundingRect();
 }
 
-void MantidMDCurve::draw(QPainter *p, 
-          const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-          const QRect &rect) const
-{
-  PlotCurve::draw(p,xMap,yMap,rect);
+void MantidMDCurve::draw(QPainter *p, const QwtScaleMap &xMap,
+                         const QwtScaleMap &yMap, const QRect &rect) const {
+  PlotCurve::draw(p, xMap, yMap, rect);
 
-  if (m_drawErrorBars)// drawing error bars
+  if (m_drawErrorBars) // drawing error bars
   {
-    const MantidQwtIMDWorkspaceData* d = dynamic_cast<const MantidQwtIMDWorkspaceData*>(&data());
-    if (!d)
-    {
-      throw std::runtime_error("Only MantidQwtIMDWorkspaceData can be set to a MantidMDCurve");
+    const MantidQwtIMDWorkspaceData *d =
+        dynamic_cast<const MantidQwtIMDWorkspaceData *>(&data());
+    if (!d) {
+      throw std::runtime_error(
+          "Only MantidQwtIMDWorkspaceData can be set to a MantidMDCurve");
     }
     doDraw(p, xMap, yMap, rect, d);
   }
 }
 
 /**  Resets the data if wsName is the name of this workspace
- *  @param wsName :: The name of a workspace which data has been changed in the data service.
+ *  @param wsName :: The name of a workspace which data has been changed in the
+ * data service.
  */
-void MantidMDCurve::dataReset(const QString& wsName)
-{
-  if (m_wsName != wsName) return;
+void MantidMDCurve::dataReset(const QString &wsName) {
+  if (m_wsName != wsName)
+    return;
   const std::string wsNameStd = wsName.toStdString();
   Mantid::API::IMDWorkspace_sptr mws;
-  try
-  {
-    Mantid::API::Workspace_sptr base =  Mantid::API::AnalysisDataService::Instance().retrieve(wsNameStd);
+  try {
+    Mantid::API::Workspace_sptr base =
+        Mantid::API::AnalysisDataService::Instance().retrieve(wsNameStd);
     mws = boost::dynamic_pointer_cast<Mantid::API::IMDWorkspace>(base);
-  }
-  catch(std::runtime_error&)
-  {
+  } catch (std::runtime_error &) {
     g_log.information() << "Workspace " << wsNameStd
-        << " could not be found - plotted curve(s) deleted\n";
+                        << " could not be found - plotted curve(s) deleted\n";
     mws = Mantid::API::IMDWorkspace_sptr();
   }
 
-  if (!mws) return;
-  const MantidQwtIMDWorkspaceData * new_mantidData(NULL);
+  if (!mws)
+    return;
+  const MantidQwtIMDWorkspaceData *new_mantidData(NULL);
   try {
     new_mantidData = mantidData()->copy(mws);
     setData(*new_mantidData);
     setStyle(QwtPlotCurve::Lines);
-    // Queue this plot to be updated once all MantidQwtIMDWorkspaceData objects for this workspace have been
+    // Queue this plot to be updated once all MantidQwtIMDWorkspaceData objects
+    // for this workspace have been
     emit dataUpdated();
-  } catch(std::range_error &) {
-    // Get here if the new workspace has fewer spectra and the plotted one no longer exists
-    g_log.information() << "Workspace " << wsNameStd
+  } catch (std::range_error &) {
+    // Get here if the new workspace has fewer spectra and the plotted one no
+    // longer exists
+    g_log.information()
+        << "Workspace " << wsNameStd
         << " now has fewer spectra - plotted curve(s) deleted\n";
     postDeleteHandle(wsNameStd);
   }
   delete new_mantidData;
 }
 
-
 /* This method saves the curve details to a string.
  * Useful for loading/saving mantid project.
 */
-QString MantidMDCurve::saveToString()
-{
-	QString s;
-	s="MantidMDCurve\t"+m_wsName+"\t"+QString::number(m_drawErrorBars)+"\n";
-	return s;
+QString MantidMDCurve::saveToString() {
+  QString s;
+  s = "MantidMDCurve\t" + m_wsName + "\t" + QString::number(m_drawErrorBars) +
+      "\n";
+  return s;
 }
 
-void MantidMDCurve::afterReplaceHandle(const std::string& wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-  (void) ws;
+void MantidMDCurve::afterReplaceHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
+  (void)ws;
 
   invalidateBoundingRect();
   emit resetData(QString::fromStdString(wsName));
 }
 
-
-MantidQwtIMDWorkspaceData* MantidMDCurve::mantidData() 
-{
-  MantidQwtIMDWorkspaceData* d = dynamic_cast<MantidQwtIMDWorkspaceData*>(&data());
+MantidQwtIMDWorkspaceData *MantidMDCurve::mantidData() {
+  MantidQwtIMDWorkspaceData *d =
+      dynamic_cast<MantidQwtIMDWorkspaceData *>(&data());
   return d;
 }
 
-const MantidQwtIMDWorkspaceData* MantidMDCurve::mantidData()const
-{
-  const MantidQwtIMDWorkspaceData* d = dynamic_cast<const MantidQwtIMDWorkspaceData*>(&data());
+const MantidQwtIMDWorkspaceData *MantidMDCurve::mantidData() const {
+  const MantidQwtIMDWorkspaceData *d =
+      dynamic_cast<const MantidQwtIMDWorkspaceData *>(&data());
   return d;
 }
-
diff --git a/MantidPlot/src/Mantid/MantidMDCurve.h b/MantidPlot/src/Mantid/MantidMDCurve.h
index 6d0c3e7d50ae5ec8e939b2a248a0663827484a51..d0a31faa0e4900b32985a7e342bc1a9e465040f9 100644
--- a/MantidPlot/src/Mantid/MantidMDCurve.h
+++ b/MantidPlot/src/Mantid/MantidMDCurve.h
@@ -9,12 +9,13 @@
 // Forward definitions
 class MantidUI;
 
-/** 
+/**
     This class is for plotting IMDWorkspaces
 
     @date 17/11/2011
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -32,20 +33,19 @@ class MantidUI;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MantidMDCurve : public MantidCurve
-{
+class MantidMDCurve : public MantidCurve {
   Q_OBJECT
 public:
-
   /// More complex constructor setting some defaults for the curve
-  MantidMDCurve(const QString& wsName,Graph* g,
-              bool err=false,bool distr = false, Graph::CurveType style = Graph::HorizontalSteps);
+  MantidMDCurve(const QString &wsName, Graph *g, bool err = false,
+                bool distr = false,
+                Graph::CurveType style = Graph::HorizontalSteps);
 
-  /// Copy constructor 
-  MantidMDCurve(const MantidMDCurve& c);
+  /// Copy constructor
+  MantidMDCurve(const MantidMDCurve &c);
 
   ~MantidMDCurve() override;
 
@@ -55,9 +55,10 @@ public:
   int rtti() const override { return Rtti_PlotUserItem; }
 
   /// Used for waterfall plots: updates the data curves with an offset
-  //void loadData();
+  // void loadData();
 
-  /// Overrides qwt_plot_curve::setData to make sure only data of QwtWorkspaceSpectrumData type can  be set
+  /// Overrides qwt_plot_curve::setData to make sure only data of
+  /// QwtWorkspaceSpectrumData type can  be set
   void setData(const QwtData &data);
 
   /// Overrides qwt_plot_curve::boundingRect
@@ -66,11 +67,15 @@ public:
   /// Return pointer to the data if it of the right type or 0 otherwise
   MantidQwtIMDWorkspaceData *mantidData() override;
 
-  /// Return pointer to the data if it of the right type or 0 otherwise, const version
+  /// Return pointer to the data if it of the right type or 0 otherwise, const
+  /// version
   const MantidQwtIMDWorkspaceData *mantidData() const override;
 
   /// Enables/disables drawing of error bars
-  void setErrorBars(bool yes=true,bool drawAll = false){m_drawErrorBars = yes;m_drawAllErrorBars = drawAll;}
+  void setErrorBars(bool yes = true, bool drawAll = false) {
+    m_drawErrorBars = yes;
+    m_drawAllErrorBars = drawAll;
+  }
 
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &) const override;
@@ -79,10 +84,9 @@ public:
   QString saveToString();
 
   /// The workspace name
-  QString workspaceName()const{return m_wsName;}
+  QString workspaceName() const { return m_wsName; }
 
 private:
-
   using PlotCurve::draw; // Avoid Intel compiler warning
 
   /// Init the curve
@@ -90,8 +94,7 @@ private:
 
   /// Handles delete notification
   void postDeleteHandle(const std::string &wsName) override {
-    if (wsName == m_wsName.toStdString())
-    {
+    if (wsName == m_wsName.toStdString()) {
       observePostDelete(false);
       emit removeMe(this);
     }
@@ -106,15 +109,15 @@ private:
 
 signals:
 
-  void resetData(const QString&);
+  void resetData(const QString &);
 
 private slots:
 
-  void dataReset(const QString&);
+  void dataReset(const QString &);
 
 private:
-
-  QString m_wsName;///< Workspace name. If empty the ws isn't in the data service
+  QString
+      m_wsName; ///< Workspace name. If empty the ws isn't in the data service
 };
 
 #endif // MANTID_CURVE_H
diff --git a/MantidPlot/src/Mantid/MantidMDCurveDialog.cpp b/MantidPlot/src/Mantid/MantidMDCurveDialog.cpp
index 53d742f1af0336d639a0df45cef269a4ba4abd58..a64398ab76022b90f13363c29f50e07bc99f5cb4 100644
--- a/MantidPlot/src/Mantid/MantidMDCurveDialog.cpp
+++ b/MantidPlot/src/Mantid/MantidMDCurveDialog.cpp
@@ -7,21 +7,20 @@ using Mantid::API::AnalysisDataService;
 using Mantid::API::IMDWorkspace;
 
 MantidMDCurveDialog::MantidMDCurveDialog(QWidget *parent, QString wsName)
-    : QDialog(parent),
-      m_wsName(wsName)
-{
-	ui.setupUi(this);
-	m_lineOptions = new LinePlotOptions(this);
-	ui.mainLayout->insertWidget(0, m_lineOptions);
+    : QDialog(parent), m_wsName(wsName) {
+  ui.setupUi(this);
+  m_lineOptions = new LinePlotOptions(this);
+  ui.mainLayout->insertWidget(0, m_lineOptions);
 
-	// To set the right dimension labels
+  // To set the right dimension labels
   IMDWorkspace_sptr ws = boost::dynamic_pointer_cast<IMDWorkspace>(
-    AnalysisDataService::Instance().retrieve( m_wsName.toStdString()) );
-  if (ws)
-  {
-    // Retrieve the original workspace. Prefer the "intermediate" one if available.
+      AnalysisDataService::Instance().retrieve(m_wsName.toStdString()));
+  if (ws) {
+    // Retrieve the original workspace. Prefer the "intermediate" one if
+    // available.
     if (ws->hasOriginalWorkspace())
-      ws = boost::dynamic_pointer_cast<IMDWorkspace>(ws->getOriginalWorkspace( ws->numOriginalWorkspaces()-1 ));
+      ws = boost::dynamic_pointer_cast<IMDWorkspace>(
+          ws->getOriginalWorkspace(ws->numOriginalWorkspaces() - 1));
     if (ws)
       m_lineOptions->setOriginalWorkspace(ws);
   }
@@ -31,24 +30,17 @@ MantidMDCurveDialog::MantidMDCurveDialog(QWidget *parent, QString wsName)
 }
 
 /// @return true if error bars are selected
-bool MantidMDCurveDialog::showErrorBars()
-{
+bool MantidMDCurveDialog::showErrorBars() {
   return ui.chkErrorBars->isChecked();
 }
 
-
-MantidMDCurveDialog::~MantidMDCurveDialog()
-{
-
-}
-void MantidMDCurveDialog::on_btnOK_clicked()
-{
+MantidMDCurveDialog::~MantidMDCurveDialog() {}
+void MantidMDCurveDialog::on_btnOK_clicked() {
   this->accept();
   this->close();
 }
 
-void MantidMDCurveDialog::on_btnCancel_clicked()
-{
+void MantidMDCurveDialog::on_btnCancel_clicked() {
   this->reject();
   this->close();
 }
diff --git a/MantidPlot/src/Mantid/MantidMDCurveDialog.h b/MantidPlot/src/Mantid/MantidMDCurveDialog.h
index c2b63e228bfe95988764bcf508e9dad7826ab82d..23453a6f80033a52bd37593ebf5d09c317e9a83c 100644
--- a/MantidPlot/src/Mantid/MantidMDCurveDialog.h
+++ b/MantidPlot/src/Mantid/MantidMDCurveDialog.h
@@ -8,31 +8,29 @@
 /** Dialog asking the user for some options on how to plot a MDWorkspace
  * before plotting
  */
-class MantidMDCurveDialog : public QDialog
-{
-    Q_OBJECT
+class MantidMDCurveDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    MantidMDCurveDialog(QWidget *parent = 0, QString wsName=QString());
-    ~MantidMDCurveDialog() override;
+  MantidMDCurveDialog(QWidget *parent = 0, QString wsName = QString());
+  ~MantidMDCurveDialog() override;
 
-    LinePlotOptions * getLineOptionsWidget()
-    {return m_lineOptions; }
+  LinePlotOptions *getLineOptionsWidget() { return m_lineOptions; }
 
-    bool showErrorBars();
+  bool showErrorBars();
 
 public slots:
-    void on_btnOK_clicked();
-    void on_btnCancel_clicked();
+  void on_btnOK_clicked();
+  void on_btnCancel_clicked();
 
 private:
-    Ui::MantidMDCurveDialogClass ui;
+  Ui::MantidMDCurveDialogClass ui;
 
-    /// Name of the workspace to plot
-    QString m_wsName;
+  /// Name of the workspace to plot
+  QString m_wsName;
 
-    /// Widget with MD plot options
-    LinePlotOptions * m_lineOptions;
+  /// Widget with MD plot options
+  LinePlotOptions *m_lineOptions;
 };
 
 #endif // MANTIDMDCURVEDIALOG_H
diff --git a/MantidPlot/src/Mantid/MantidMatrix.cpp b/MantidPlot/src/Mantid/MantidMatrix.cpp
index 69e956546526f1e968df020dba1c79f12e0dcbc6..1e658ad0dd5fc0351c6037759f418f39ec6ff710 100644
--- a/MantidPlot/src/Mantid/MantidMatrix.cpp
+++ b/MantidPlot/src/Mantid/MantidMatrix.cpp
@@ -637,17 +637,15 @@ QwtDoubleRect MantidMatrix::boundingRect() {
       } else {
         m_spectrogramCols = numCols() > 100 ? numCols() : 100;
       }
-      m_boundingRect =
-          QwtDoubleRect(QMIN(x_start, x_end) - 0.5 * dx,
-                        QMIN(y_start, y_end) - 0.5 * dy,
-                        fabs(x_end - x_start) + dx, fabs(y_end - y_start) + dy)
-              .normalized();
+      m_boundingRect = QwtDoubleRect(QMIN(x_start, x_end) - 0.5 * dx,
+                                     QMIN(y_start, y_end) - 0.5 * dy,
+                                     fabs(x_end - x_start) + dx,
+                                     fabs(y_end - y_start) + dy).normalized();
 
     } else {
       m_spectrogramCols = 0;
       m_boundingRect = QwtDoubleRect(0, QMIN(y_start, y_end) - 0.5 * dy, 1,
-                                     fabs(y_end - y_start) + dy)
-                           .normalized();
+                                     fabs(y_end - y_start) + dy).normalized();
     }
   } // Define the spectrogram bounding box
   return m_boundingRect;
diff --git a/MantidPlot/src/Mantid/MantidMatrix.h b/MantidPlot/src/Mantid/MantidMatrix.h
index 74ec91d513cef44b3fac7837621445e2018520a0..77bee5be71d0f5335c6c4d27cd64e9c34c9dc78b 100644
--- a/MantidPlot/src/Mantid/MantidMatrix.h
+++ b/MantidPlot/src/Mantid/MantidMatrix.h
@@ -45,8 +45,6 @@ class QTabWidget;
 class UpdateDAEThread;
 class ProjectData;
 
-
-
 /**
 * Find the minimum and maximum Y values in a matrix workspace.
 *
@@ -54,14 +52,17 @@ class ProjectData;
 * @param miny :: Variable to receive the minimum value.
 * @param maxy :: Variable to receive the maximum value.
 */
-void findYRange(Mantid::API::MatrixWorkspace_const_sptr ws, double &miny, double &maxy);
+void findYRange(Mantid::API::MatrixWorkspace_const_sptr ws, double &miny,
+                double &maxy);
 
-/** MantidMatrix is the class that represents a Qtiplot window for displaying workspaces.
+/** MantidMatrix is the class that represents a Qtiplot window for displaying
+workspaces.
 It has separate tabs for displaying spectrum values, bin boundaries, and errors.
 
 @author Roman Tolchenov, Tessella Support Services plc
 
-Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -82,61 +83,71 @@ File change history is stored at: <https://github.com/mantidproject/mantid>.
 Code Documentation is available at: <http://doxygen.mantidproject.org>
 
 */
-class MantidMatrix : public MdiSubWindow, MantidQt::API::WorkspaceObserver, public Mantid::IProjectSerialisable
-{
+class MantidMatrix : public MdiSubWindow,
+                     MantidQt::API::WorkspaceObserver,
+                     public Mantid::IProjectSerialisable {
   Q_OBJECT
 
 public:
-
-  MantidMatrix(Mantid::API::MatrixWorkspace_const_sptr ws, ApplicationWindow* parent, const QString& label, const QString& name = QString(), int start=-1, int end=-1);
-
-  void connectTableView(QTableView*,MantidMatrixModel*);
-  MantidMatrixModel * model(){return m_modelY;}
-  MantidMatrixModel * modelY(){return m_modelY;}
-  MantidMatrixModel * modelX(){return m_modelX;}
-  MantidMatrixModel * modelE(){return m_modelE;}
-  QItemSelectionModel * selectionModel(){return m_table_viewY->selectionModel();}
-  QItemSelectionModel * selectionModelY(){return m_table_viewY->selectionModel();}
-  QItemSelectionModel * selectionModelX(){return m_table_viewX->selectionModel();}
-  QItemSelectionModel * selectionModelE(){return m_table_viewE->selectionModel();}
-
-  int numRows()const{return m_rows;}
-  int numCols()const{return m_cols;}
+  MantidMatrix(Mantid::API::MatrixWorkspace_const_sptr ws,
+               ApplicationWindow *parent, const QString &label,
+               const QString &name = QString(), int start = -1, int end = -1);
+
+  void connectTableView(QTableView *, MantidMatrixModel *);
+  MantidMatrixModel *model() { return m_modelY; }
+  MantidMatrixModel *modelY() { return m_modelY; }
+  MantidMatrixModel *modelX() { return m_modelX; }
+  MantidMatrixModel *modelE() { return m_modelE; }
+  QItemSelectionModel *selectionModel() {
+    return m_table_viewY->selectionModel();
+  }
+  QItemSelectionModel *selectionModelY() {
+    return m_table_viewY->selectionModel();
+  }
+  QItemSelectionModel *selectionModelX() {
+    return m_table_viewX->selectionModel();
+  }
+  QItemSelectionModel *selectionModelE() {
+    return m_table_viewE->selectionModel();
+  }
+
+  int numRows() const { return m_rows; }
+  int numCols() const { return m_cols; }
   double dataX(int row, int col) const;
   double dataY(int row, int col) const;
   double dataE(int row, int col) const;
   double dataDx(int row, int col) const;
-  int indexX(int row,double s)const;
-  int indexY(double s)const;
+  int indexX(int row, double s) const;
+  int indexY(double s) const;
 
-  Mantid::API::MatrixWorkspace_const_sptr workspace(){return m_workspace;}
+  Mantid::API::MatrixWorkspace_const_sptr workspace() { return m_workspace; }
   QString workspaceName() const;
 
-  QPixmap matrixIcon(){return m_matrix_icon;}
-  //void copy(Matrix *m);
-  ApplicationWindow *appWindow(){return m_appWindow;}
+  QPixmap matrixIcon() { return m_matrix_icon; }
+  // void copy(Matrix *m);
+  ApplicationWindow *appWindow() { return m_appWindow; }
   Graph3D *plotGraph3D(int style);
 
   // Creates a MultiLayer graph and plots this MantidMatrix as a Spectrogram
-  MultiLayer* plotGraph2D(Graph::CurveType type);
+  MultiLayer *plotGraph2D(Graph::CurveType type);
 
-  void setBinGraph(MultiLayer* ml, Table* t=0);
+  void setBinGraph(MultiLayer *ml, Table *t = 0);
 
   bool setSelectedRows();
   bool setSelectedColumns();
-  const QList<int>& getSelectedRows() const;
-  const QList<int>& getSelectedColumns() const;
+  const QList<int> &getSelectedRows() const;
+  const QList<int> &getSelectedColumns() const;
 
-  int workspaceIndex(int row){return row + m_startRow;}
-  bool yShown(){return m_tabs->currentIndex() == 0;}
+  int workspaceIndex(int row) { return row + m_startRow; }
+  bool yShown() { return m_tabs->currentIndex() == 0; }
   QTableView *activeView();
   MantidMatrixModel *activeModel();
 
-  bool isHistogram(){return m_histogram;}
+  bool isHistogram() { return m_histogram; }
 
   // Set format and precision of displayed numbers.
-  void setNumberFormat(const QChar& f,int prec, bool all = false);
-  void setNumberFormat(int i,const QChar& f,int prec, bool all = false);
+  void setNumberFormat(const QChar &f, int prec, bool all = false);
+  void setNumberFormat(int i, const QChar &f, int prec, bool all = false);
 
   // Return number format of the active model
   QChar numberFormat();
@@ -150,12 +161,15 @@ public:
   std::string saveToProject(ApplicationWindow *app) override;
 
   /// returns the workspace name
-  const std::string & getWorkspaceName();
+  const std::string &getWorkspaceName();
 
-  Spectrogram* plotSpectrogram(Graph* plot, ApplicationWindow* app, Graph::CurveType type, bool project, const ProjectData * const prjdata);
-  /// Add a multilayer as a dependent mdi sub-window. This method is addeed to fix a crash (ticket #5732).
+  Spectrogram *plotSpectrogram(Graph *plot, ApplicationWindow *app,
+                               Graph::CurveType type, bool project,
+                               const ProjectData *const prjdata);
+  /// Add a multilayer as a dependent mdi sub-window. This method is addeed to
+  /// fix a crash (ticket #5732).
   /// A better solution is needed
-  void attachMultilayer(MultiLayer*);
+  void attachMultilayer(MultiLayer *);
 
   void afterReplaceHandle(
       const std::string &wsName,
@@ -170,80 +184,82 @@ signals:
   void needToClose();
   void needsUpdating();
 
-  public slots:
-
-    void changeWorkspace(Mantid::API::MatrixWorkspace_sptr ws);
-    void closeMatrix();
-
-    //! Return the width of all columns
-    int columnsWidth(int i=-1);
-    //! Set the width of all columns for all views (all==true) or the active view (all==false)
-    void setColumnsWidth(int width, bool all = true);
-    // Set the width of column in view i (0 - Y, 1 - X, 2 - E)
-    void setColumnsWidth(int i, int width);
-
-    //! Return the content of the cell as a string
-    QString text(int row, int col);
-    //! Return the value of the cell as a double
-    double cell(int row, int col);
-
-    //! Returns the X value corresponding to column 1
-    double xStart(){return x_start;}
-    //! Returns the X value corresponding to the last column
-    double xEnd(){return x_end;}
-    //! Returns the Y value corresponding to row 1
-    double yStart(){return y_start;}
-    //! Returns the Y value corresponding to the last row
-    double yEnd(){return y_end;}
-
-    //! Returns the step of the X axis
-    double dx(){return fabs(x_end - x_start)/(double)(numCols() - 1);}
-    //! Returns the step of the Y axis
-    double dy(){return fabs(y_end - y_start)/(double)(numRows() - 1);}
-
-    //! Returns the bounding rect of the matrix coordinates
-    QwtDoubleRect boundingRect();
-    /// Invalidates the bounding rect forcing it to be recalculated
-    void invalidateBoundingRect(){m_boundingRect = QwtDoubleRect();}
-
-    //! Min and max values in the matrix.
-    void range(double *min, double *max);
-    //! Set min and max values in the matrix.
-    void setRange(double min, double max);
-
-    // Scroll to row and column
-    void goTo(int row,int col);
-    //! Scroll to row (row starts with 1)
-    void goToRow(int row);
-    //! Scroll to column (column starts with 1)
-    void goToColumn(int col);
-    // Set the active tab by name
-    void goToTab(const QString & name);
-
-    void copySelection();
-
-    //! Allocate memory for a matrix buffer
-    static double** allocateMatrixData(int rows, int columns);
-    //! Free memory used for a matrix buffer
-    static void freeMatrixData(double **data, int rows);
-
-    int verticalHeaderWidth(){return m_table_viewY->verticalHeader()->width();}
-
-    void dependantClosed(MdiSubWindow* w);
-    void selfClosed(MdiSubWindow* w);
-    void repaintAll();
-    void closeDependants();
-    // for context menu filtering
-    bool eventFilter(QObject *object, QEvent *e) override;
-    //to synchronize the views
-    void viewChanged(int);
-
-    // Opens modified QtiPlot's MatrixDialog and sets column width and number format
-    void setMatrixProperties();
+public slots:
+
+  void changeWorkspace(Mantid::API::MatrixWorkspace_sptr ws);
+  void closeMatrix();
+
+  //! Return the width of all columns
+  int columnsWidth(int i = -1);
+  //! Set the width of all columns for all views (all==true) or the active view
+  //(all==false)
+  void setColumnsWidth(int width, bool all = true);
+  // Set the width of column in view i (0 - Y, 1 - X, 2 - E)
+  void setColumnsWidth(int i, int width);
+
+  //! Return the content of the cell as a string
+  QString text(int row, int col);
+  //! Return the value of the cell as a double
+  double cell(int row, int col);
+
+  //! Returns the X value corresponding to column 1
+  double xStart() { return x_start; }
+  //! Returns the X value corresponding to the last column
+  double xEnd() { return x_end; }
+  //! Returns the Y value corresponding to row 1
+  double yStart() { return y_start; }
+  //! Returns the Y value corresponding to the last row
+  double yEnd() { return y_end; }
+
+  //! Returns the step of the X axis
+  double dx() { return fabs(x_end - x_start) / (double)(numCols() - 1); }
+  //! Returns the step of the Y axis
+  double dy() { return fabs(y_end - y_start) / (double)(numRows() - 1); }
+
+  //! Returns the bounding rect of the matrix coordinates
+  QwtDoubleRect boundingRect();
+  /// Invalidates the bounding rect forcing it to be recalculated
+  void invalidateBoundingRect() { m_boundingRect = QwtDoubleRect(); }
+
+  //! Min and max values in the matrix.
+  void range(double *min, double *max);
+  //! Set min and max values in the matrix.
+  void setRange(double min, double max);
+
+  // Scroll to row and column
+  void goTo(int row, int col);
+  //! Scroll to row (row starts with 1)
+  void goToRow(int row);
+  //! Scroll to column (column starts with 1)
+  void goToColumn(int col);
+  // Set the active tab by name
+  void goToTab(const QString &name);
+
+  void copySelection();
+
+  //! Allocate memory for a matrix buffer
+  static double **allocateMatrixData(int rows, int columns);
+  //! Free memory used for a matrix buffer
+  static void freeMatrixData(double **data, int rows);
+
+  int verticalHeaderWidth() { return m_table_viewY->verticalHeader()->width(); }
+
+  void dependantClosed(MdiSubWindow *w);
+  void selfClosed(MdiSubWindow *w);
+  void repaintAll();
+  void closeDependants();
+  // for context menu filtering
+  bool eventFilter(QObject *object, QEvent *e) override;
+  // to synchronize the views
+  void viewChanged(int);
+
+  // Opens modified QtiPlot's MatrixDialog and sets column width and number
+  // format
+  void setMatrixProperties();
 
 protected:
-
-  void setup(Mantid::API::MatrixWorkspace_const_sptr ws, int start=-1, int end=-1);
+  void setup(Mantid::API::MatrixWorkspace_const_sptr ws, int start = -1,
+             int end = -1);
 
   ApplicationWindow *m_appWindow;
   Mantid::API::MatrixWorkspace_const_sptr m_workspace;
@@ -256,42 +272,46 @@ protected:
   QPointer<MantidMatrixModel> m_modelE;
   QColor m_bk_color;
   QPixmap m_matrix_icon;
-  double x_start,             //!< X value corresponding to column 1
-    x_end,                      //!< X value corresponding to the last column
-    y_start,                    //!< Y value corresponding to row 1
-    y_end;                      //!< Y value corresponding to the last row
-  int m_rows,m_cols;
+  double x_start, //!< X value corresponding to column 1
+      x_end,      //!< X value corresponding to the last column
+      y_start,    //!< Y value corresponding to row 1
+      y_end;      //!< Y value corresponding to the last row
+  int m_rows, m_cols;
   int m_startRow;
   int m_endRow;
   int m_workspaceTotalHist;
   bool m_histogram;
   double m_min;           // Saved minimum Y-value
   double m_max;           // Saved maximum Y-value
-  bool m_are_min_max_set; // If true ::range does not iterate over WS to find min and max but uses m_min and m_max instead
-  QwtDoubleRect m_boundingRect; // The bounding box in x and y coordinates used in spectrogram drawing
-  int m_spectrogramRows; // Number of rows in the spectrogram created from this matris
-  int m_spectrogramCols; // Number of columns in the spectrogram created from this matris
+  bool m_are_min_max_set; // If true ::range does not iterate over WS to find
+                          // min and max but uses m_min and m_max instead
+  QwtDoubleRect m_boundingRect; // The bounding box in x and y coordinates used
+                                // in spectrogram drawing
+  int m_spectrogramRows; // Number of rows in the spectrogram created from this
+                         // matris
+  int m_spectrogramCols; // Number of columns in the spectrogram created from
+                         // this matris
 
   // MDI windows created by this MantidMatrix
-  QVector<MultiLayer*> m_plots2D;
-  QMap< MultiLayer*,Table* > m_plots1D;
+  QVector<MultiLayer *> m_plots2D;
+  QMap<MultiLayer *, Table *> m_plots1D;
 
-  //MantidMatrixFunction m_funct;
+  // MantidMatrixFunction m_funct;
   int m_column_width;
 
   // MantidMatrixExtensionCollection
   MantidMatrixTabExtensionMap m_extensions;
 
 private:
-  //name of the underlying workspace
+  // name of the underlying workspace
   std::string m_strName;
 
   /// Storage for column and row selection
   QList<int> m_selectedRows, m_selectedCols;
 
-  //The tab labels
+  // The tab labels
   QString m_YTabLabel, m_XTabLabel, m_ETabLabel;
-  //index to identify the previous view on tab switch
+  // index to identify the previous view on tab switch
   int m_PrevIndex;
 
   QString m_colormapName;
@@ -312,33 +332,41 @@ private:
 /// Typedef for a shared pointer to a MantidMatrix
 typedef QSharedPointer<MantidMatrix> MantidMatrix_sptr;
 
-class ProjectData
-{
+class ProjectData {
 public:
-  ProjectData() : m_grayScale(0),m_intensityChanged(0),m_contourMode(0),m_contourLevels(0),
-    m_customPen(0),m_contourLabels(0),m_colormapPen(0),m_ContourLinesEditor(0)
-  {}
-  ~ProjectData(){}
-  bool getGrayScale() const {return m_grayScale;}
-  bool getIntensity() const {return m_intensityChanged;}
-  bool getContourMode() const {return m_contourMode;}
-  const QString& getColormapFile() const {return m_colormapFile;}
-  void  setGrayScale(bool grayscale) {m_grayScale=grayscale;}
-  void setIntensity(bool intensity)  {m_intensityChanged=intensity;}
-  void setColormapFile(const QString & fileName) {m_colormapFile=fileName;}
-  void setContourMode(bool contourmode) {m_contourMode=contourmode;}
-  void setContourLevels(int levels) {m_contourLevels=levels;}
-  int getContourLevels() const {return m_contourLevels;}
-  void setDefaultContourPen(const QPen& defaultpen) {m_defaultPen=defaultpen;}
-  QPen getDefaultContourPen() const {return  m_defaultPen;}
-  void setColorMapPen(bool colormappen) {m_colormapPen=colormappen;}
-  bool getColorMapPen() const {return m_colormapPen;}
-  void setCustomPen(bool custompen) {m_customPen=custompen;}
-  bool getcustomPen() const {return m_customPen;}
-  void setContourLineLabels(bool contourlabels) {m_contourLabels=contourlabels;}
-  bool getContourLineLabels() const {return m_contourLabels;}
-  void setCotntourLinesEditor(ContourLinesEditor *ceditor) {m_ContourLinesEditor=ceditor;}
-  ContourLinesEditor* getContourLinesEditor() const {return m_ContourLinesEditor;}
+  ProjectData()
+      : m_grayScale(0), m_intensityChanged(0), m_contourMode(0),
+        m_contourLevels(0), m_customPen(0), m_contourLabels(0),
+        m_colormapPen(0), m_ContourLinesEditor(0) {}
+  ~ProjectData() {}
+  bool getGrayScale() const { return m_grayScale; }
+  bool getIntensity() const { return m_intensityChanged; }
+  bool getContourMode() const { return m_contourMode; }
+  const QString &getColormapFile() const { return m_colormapFile; }
+  void setGrayScale(bool grayscale) { m_grayScale = grayscale; }
+  void setIntensity(bool intensity) { m_intensityChanged = intensity; }
+  void setColormapFile(const QString &fileName) { m_colormapFile = fileName; }
+  void setContourMode(bool contourmode) { m_contourMode = contourmode; }
+  void setContourLevels(int levels) { m_contourLevels = levels; }
+  int getContourLevels() const { return m_contourLevels; }
+  void setDefaultContourPen(const QPen &defaultpen) {
+    m_defaultPen = defaultpen;
+  }
+  QPen getDefaultContourPen() const { return m_defaultPen; }
+  void setColorMapPen(bool colormappen) { m_colormapPen = colormappen; }
+  bool getColorMapPen() const { return m_colormapPen; }
+  void setCustomPen(bool custompen) { m_customPen = custompen; }
+  bool getcustomPen() const { return m_customPen; }
+  void setContourLineLabels(bool contourlabels) {
+    m_contourLabels = contourlabels;
+  }
+  bool getContourLineLabels() const { return m_contourLabels; }
+  void setCotntourLinesEditor(ContourLinesEditor *ceditor) {
+    m_ContourLinesEditor = ceditor;
+  }
+  ContourLinesEditor *getContourLinesEditor() const {
+    return m_ContourLinesEditor;
+  }
 
 private:
   bool m_grayScale;
@@ -350,8 +378,7 @@ private:
   bool m_customPen;
   bool m_contourLabels;
   bool m_colormapPen;
-  ContourLinesEditor* m_ContourLinesEditor;
+  ContourLinesEditor *m_ContourLinesEditor;
 };
 
-
 #endif
diff --git a/MantidPlot/src/Mantid/MantidMatrixCurve.h b/MantidPlot/src/Mantid/MantidMatrixCurve.h
index 0e405548673df636ef70df4b1ec63e45b8afc5d9..18ad396dd762578e5d279dc9921171c1df69cfd9 100644
--- a/MantidPlot/src/Mantid/MantidMatrixCurve.h
+++ b/MantidPlot/src/Mantid/MantidMatrixCurve.h
@@ -9,14 +9,16 @@
 // Forward definitions
 class MantidUI;
 
-/** 
-    This class is for plotting spectra or bins from a Mantid MatrixWorkspace in a 
+/**
+    This class is for plotting spectra or bins from a Mantid MatrixWorkspace in
+   a
     QtiPlot's Graph widget.
-    
+
     @author Roman Tolchenov, Tessella plc
     @date 09/09/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -35,30 +37,31 @@ class MantidUI;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MantidMatrixCurve:public MantidCurve
-{
+class MantidMatrixCurve : public MantidCurve {
   Q_OBJECT
 public:
   /// Indicates whether the curve index is treated as a row or a column
-  enum IndexDir { Spectrum, // index is treated as a row
-                  Bin // index is treated as a column
-                };
+  enum IndexDir {
+    Spectrum, // index is treated as a row
+    Bin       // index is treated as a column
+  };
 
   /// More complex constructor setting some defaults for the curve
-  MantidMatrixCurve(const QString& name,const QString& wsName,Graph* g,
-                    int index, IndexDir indexType, bool err=false, bool distr = false,
+  MantidMatrixCurve(const QString &name, const QString &wsName, Graph *g,
+                    int index, IndexDir indexType, bool err = false,
+                    bool distr = false,
                     Graph::CurveType style = Graph::Unspecified);
 
   /// More complex constructor setting some defaults for the curve
-  MantidMatrixCurve(const QString& wsName,Graph* g,
-                    int index, IndexDir indexType, bool err=false, bool distr = false,
+  MantidMatrixCurve(const QString &wsName, Graph *g, int index,
+                    IndexDir indexType, bool err = false, bool distr = false,
                     Graph::CurveType style = Graph::Unspecified);
 
-  /// Copy constructor 
-  MantidMatrixCurve(const MantidMatrixCurve& c);
+  /// Copy constructor
+  MantidMatrixCurve(const MantidMatrixCurve &c);
 
   ~MantidMatrixCurve() override;
 
@@ -70,7 +73,8 @@ public:
   /// Used for waterfall plots: updates the data curves with an offset
   void loadData();
 
-  /// Overrides qwt_plot_curve::setData to make sure only data of QwtWorkspaceSpectrumData type can  be set
+  /// Overrides qwt_plot_curve::setData to make sure only data of
+  /// QwtWorkspaceSpectrumData type can  be set
   void setData(const QwtData &data);
 
   /// Overrides qwt_plot_curve::boundingRect
@@ -78,13 +82,18 @@ public:
 
   /// Return pointer to the data if it of the right type or 0 otherwise
   MantidQwtMatrixWorkspaceData *mantidData() override;
-  /// Return pointer to the data if it of the right type or 0 otherwise, const version
+  /// Return pointer to the data if it of the right type or 0 otherwise, const
+  /// version
   const MantidQwtMatrixWorkspaceData *mantidData() const override;
 
   /// Enables/disables drawing of error bars
-  void setErrorBars(bool yes=true,bool drawAll = false){m_drawErrorBars = yes;m_drawAllErrorBars = drawAll;}
+  void setErrorBars(bool yes = true, bool drawAll = false) {
+    m_drawErrorBars = yes;
+    m_drawAllErrorBars = drawAll;
+  }
 
-  /// Enables/disables drawing as distribution, ie dividing each y-value by the bin width.
+  /// Enables/disables drawing as distribution, ie dividing each y-value by the
+  /// bin width.
   bool setDrawAsDistribution(bool on = true);
 
   /// Returns whether the curve is plotted as a distribution
@@ -93,7 +102,8 @@ public:
   /// Returns true if the curve data comes for a histgoram workspace
   bool isHistogramData() const;
 
-  /// Returns whether the can be normalized, i.e whether the workspace data is already divided by the width
+  /// Returns whether the can be normalized, i.e whether the workspace data is
+  /// already divided by the width
   bool isNormalizable() const;
 
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
@@ -106,16 +116,16 @@ public:
   QString saveToString();
 
   /// The workspace name
-  QString workspaceName()const{return m_wsName;}
-  /// Returns the workspace index if a spectrum is plotted and -1 if it is a bin.
-  int workspaceIndex()const;
+  QString workspaceName() const { return m_wsName; }
+  /// Returns the workspace index if a spectrum is plotted and -1 if it is a
+  /// bin.
+  int workspaceIndex() const;
   /// Return the x units
-  Mantid::Kernel::Unit_sptr xUnits()const{return m_xUnits;}
+  Mantid::Kernel::Unit_sptr xUnits() const { return m_xUnits; }
   /// Return the y units
-  Mantid::Kernel::Unit_sptr yUnits()const{return m_yUnits;}
+  Mantid::Kernel::Unit_sptr yUnits() const { return m_yUnits; }
 
 private:
-
   using PlotCurve::draw; // Avoid Intel compiler warning
 
   /// Init the curve
@@ -123,8 +133,7 @@ private:
 
   /// Handles delete notification
   void postDeleteHandle(const std::string &wsName) override {
-    if (wsName == m_wsName.toStdString())
-    {
+    if (wsName == m_wsName.toStdString()) {
       observePostDelete(false);
       emit removeMe(this);
     }
@@ -139,20 +148,21 @@ private:
 
 signals:
 
-  void resetData(const QString&);
+  void resetData(const QString &);
 
 private slots:
 
-  void dataReset(const QString&);
+  void dataReset(const QString &);
 
 private:
-
   /// Make the curve name
-  QString createCurveName(const boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws);
+  QString createCurveName(
+      const boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws);
 
-  QString m_wsName;///< Workspace name. If empty the ws isn't in the data service
+  QString
+      m_wsName; ///< Workspace name. If empty the ws isn't in the data service
   /// index
-  int  m_index;
+  int m_index;
   /// Is the index a spectrum or bin index
   IndexDir m_indexType;
   /// x units
diff --git a/MantidPlot/src/Mantid/MantidMatrixDialog.cpp b/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
index 9ea52efc4279fd5d49c0bafe7cfde29104db639a..6dbaaf42d102b1e75798da31840d7a35cfe67101 100644
--- a/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
+++ b/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
@@ -9,63 +9,61 @@
 #include <QSpinBox>
 #include <QLineEdit>
 
-MantidMatrixDialog::MantidMatrixDialog( QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ),
-  d_matrix(0)
-{
-  setWindowTitle( tr( "MantidPlot - Matrix Properties" ) );
+MantidMatrixDialog::MantidMatrixDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), d_matrix(0) {
+  setWindowTitle(tr("MantidPlot - Matrix Properties"));
 
-  QGridLayout * topLayout = new QGridLayout();
-  QHBoxLayout * bottomLayout = new QHBoxLayout();
+  QGridLayout *topLayout = new QGridLayout();
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
 
-  topLayout->addWidget( new QLabel(tr( "Cell Width" )), 0, 0 );
+  topLayout->addWidget(new QLabel(tr("Cell Width")), 0, 0);
   boxColWidth = new QSpinBox();
-  boxColWidth->setRange(0,1000);
+  boxColWidth->setRange(0, 1000);
   boxColWidth->setSingleStep(10);
-  topLayout->addWidget( boxColWidth, 0, 1 );
+  topLayout->addWidget(boxColWidth, 0, 1);
 
-  topLayout->addWidget( new QLabel(tr( "Data Format" )), 1, 0 );
+  topLayout->addWidget(new QLabel(tr("Data Format")), 1, 0);
 
   boxFormat = new QComboBox();
-  boxFormat->addItem( tr( "Decimal: 1000" ), 'f' );
-  boxFormat->addItem( tr( "Scientific: 1E3" ), 'e' );
-  boxFormat->addItem( tr( "Shorter: 1E3 or 1000" ), 'g' );
-  topLayout->addWidget( boxFormat, 1, 1 );
+  boxFormat->addItem(tr("Decimal: 1000"), 'f');
+  boxFormat->addItem(tr("Scientific: 1E3"), 'e');
+  boxFormat->addItem(tr("Shorter: 1E3 or 1000"), 'g');
+  topLayout->addWidget(boxFormat, 1, 1);
 
-  topLayout->addWidget( new QLabel( tr( "Precision" )), 2, 0 );
+  topLayout->addWidget(new QLabel(tr("Precision")), 2, 0);
   boxPrecision = new QSpinBox();
   boxPrecision->setRange(0, 15);
-  topLayout->addWidget( boxPrecision, 2, 1 );
+  topLayout->addWidget(boxPrecision, 2, 1);
 
-  topLayout->addWidget( new QLabel( tr( "Set new range" )), 3, 0 );
+  topLayout->addWidget(new QLabel(tr("Set new range")), 3, 0);
   editRangeMin = new QLineEdit();
-  topLayout->addWidget(editRangeMin, 3, 1 );
+  topLayout->addWidget(editRangeMin, 3, 1);
   editRangeMax = new QLineEdit();
-  topLayout->addWidget(editRangeMax, 3, 2 );
+  topLayout->addWidget(editRangeMax, 3, 2);
 
-  buttonOk = new QPushButton(tr( "&OK" ));
-  buttonOk->setAutoDefault( true );
-  buttonOk->setDefault( true );
-  bottomLayout->addWidget( buttonOk );
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
+  bottomLayout->addWidget(buttonOk);
 
-  buttonCancel = new QPushButton(tr( "&Cancel" ));
-  buttonCancel->setAutoDefault( true );
-  bottomLayout->addWidget( buttonCancel );
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  buttonCancel->setAutoDefault(true);
+  bottomLayout->addWidget(buttonCancel);
 
-  QVBoxLayout * mainLayout = new QVBoxLayout(this);
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
   mainLayout->addLayout(topLayout);
   mainLayout->addLayout(bottomLayout);
 
   // signals and slots connections
   connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
-  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));;
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
+  ;
 }
 
-void MantidMatrixDialog::apply()
-{
+void MantidMatrixDialog::apply() {
   int width = boxColWidth->value();
-  if (d_matrix->columnsWidth() != width){
-    d_matrix->setColumnsWidth(width,false);
+  if (d_matrix->columnsWidth() != width) {
+    d_matrix->setColumnsWidth(width, false);
   }
 
   int prec = boxPrecision->value();
@@ -73,14 +71,13 @@ void MantidMatrixDialog::apply()
 
   d_matrix->setNumberFormat(format, prec);
 
-  double yMin,yMax;
+  double yMin, yMax;
   yMin = editRangeMin->text().toDouble();
   yMax = editRangeMax->text().toDouble();
-  d_matrix->setRange(yMin,yMax);
+  d_matrix->setRange(yMin, yMax);
 }
 
-void MantidMatrixDialog::setMatrix(MantidMatrix* m)
-{
+void MantidMatrixDialog::setMatrix(MantidMatrix *m) {
   if (!m)
     return;
 
@@ -88,27 +85,23 @@ void MantidMatrixDialog::setMatrix(MantidMatrix* m)
   boxColWidth->setValue(m->columnsWidth());
 
   int index = boxFormat->findData(m->numberFormat());
-  if (index > -1)
-  {
-    boxFormat->setCurrentIndex(index);  
-  }
-  else
-  {
+  if (index > -1) {
+    boxFormat->setCurrentIndex(index);
+  } else {
     boxFormat->setCurrentIndex(2);
   }
 
   boxPrecision->setValue(m->precision());
 
-  double yMin,yMax;
-  m->range(&yMin,&yMax);
+  double yMin, yMax;
+  m->range(&yMin, &yMax);
   editRangeMin->setText(QString::number(yMin));
   editRangeMax->setText(QString::number(yMax));
   editRangeMin->setValidator(new QDoubleValidator(this));
   editRangeMax->setValidator(new QDoubleValidator(this));
 }
 
-void MantidMatrixDialog::accept()
-{
+void MantidMatrixDialog::accept() {
   apply();
   close();
 }
diff --git a/MantidPlot/src/Mantid/MantidMatrixDialog.h b/MantidPlot/src/Mantid/MantidMatrixDialog.h
index f6da35737737efe367a3f55e983d88083652aaf6..37badc72bfe2d4dfea74937cdcf75ae6f135711d 100644
--- a/MantidPlot/src/Mantid/MantidMatrixDialog.h
+++ b/MantidPlot/src/Mantid/MantidMatrixDialog.h
@@ -11,8 +11,7 @@ class QComboBox;
 class QLineEdit;
 
 //! Matrix properties dialog
-class MantidMatrixDialog : public QDialog
-{
+class MantidMatrixDialog : public QDialog {
   Q_OBJECT
 
 public:
@@ -21,21 +20,21 @@ public:
   * @param parent :: parent widget
   * @param fl :: window flags
   */
-  MantidMatrixDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  MantidMatrixDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
   void setMatrix(MantidMatrix *m);
 
-  private slots:
-    //! Accept changes and quit
-    void accept() override;
-    //! Apply changes
-    void apply();
+private slots:
+  //! Accept changes and quit
+  void accept() override;
+  //! Apply changes
+  void apply();
 
 private:
-  MantidMatrix* d_matrix;
+  MantidMatrix *d_matrix;
 
-  QPushButton* buttonOk;
-  QPushButton* buttonCancel;
-  QSpinBox* boxColWidth, *boxPrecision;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QSpinBox *boxColWidth, *boxPrecision;
   QComboBox *boxFormat;
   QLineEdit *editRangeMin, *editRangeMax;
 };
diff --git a/MantidPlot/src/Mantid/MantidMatrixDxExtensionHandler.cpp b/MantidPlot/src/Mantid/MantidMatrixDxExtensionHandler.cpp
index 5ceed16c26d1298c1241036b1aa505ce794afd2a..b261b76f9566ce4f0a431897ff89a4394f41f23e 100644
--- a/MantidPlot/src/Mantid/MantidMatrixDxExtensionHandler.cpp
+++ b/MantidPlot/src/Mantid/MantidMatrixDxExtensionHandler.cpp
@@ -3,18 +3,19 @@
 #include <QTableView>
 #include <QHeaderView>
 
-MantidMatrixDxExtensionHandler::MantidMatrixDxExtensionHandler() : m_type(MantidMatrixModel::Type::DX) {}
+MantidMatrixDxExtensionHandler::MantidMatrixDxExtensionHandler()
+    : m_type(MantidMatrixModel::Type::DX) {}
 
 MantidMatrixDxExtensionHandler::~MantidMatrixDxExtensionHandler() {}
 
-
 /**
  * Sets the number format for DX values
  * @param extension: a MantidMatrix extension
  * @param format: the format
  * @param precision: the precision
  */
-void MantidMatrixDxExtensionHandler::setNumberFormat(MantidMatrixTabExtension& extension, const QChar& format,int precision) {
+void MantidMatrixDxExtensionHandler::setNumberFormat(
+    MantidMatrixTabExtension &extension, const QChar &format, int precision) {
   if (extension.type == m_type) {
     extension.model->setFormat(format, precision);
   } else {
@@ -22,13 +23,14 @@ void MantidMatrixDxExtensionHandler::setNumberFormat(MantidMatrixTabExtension& e
   }
 }
 
-/** 
+/**
  * Record the number format
  * @param extension: the extension to analyse
  * @param format: the format
  * @param precision: the precision
  */
-void MantidMatrixDxExtensionHandler::recordFormat(MantidMatrixTabExtension& extension, const QChar &format, int precision) {
+void MantidMatrixDxExtensionHandler::recordFormat(
+    MantidMatrixTabExtension &extension, const QChar &format, int precision) {
   if (extension.type == m_type) {
     MantidPreferences::MantidMatrixNumberFormatDx(format);
     MantidPreferences::MantidMatrixNumberPrecisionDx(precision);
@@ -42,7 +44,8 @@ void MantidMatrixDxExtensionHandler::recordFormat(MantidMatrixTabExtension& exte
  * @param extension: the extension
  * @returns a format character
  */
-QChar MantidMatrixDxExtensionHandler::getFormat(MantidMatrixTabExtension& extension) {
+QChar MantidMatrixDxExtensionHandler::getFormat(
+    MantidMatrixTabExtension &extension) {
   if (extension.type == m_type) {
     return MantidPreferences::MantidMatrixNumberFormatDx();
   } else {
@@ -55,7 +58,8 @@ QChar MantidMatrixDxExtensionHandler::getFormat(MantidMatrixTabExtension& extens
  * @param extension: the extension
  * @returns the precision
  */
-int MantidMatrixDxExtensionHandler::getPrecision(MantidMatrixTabExtension& extension) {
+int MantidMatrixDxExtensionHandler::getPrecision(
+    MantidMatrixTabExtension &extension) {
   if (extension.type == m_type) {
     return MantidPreferences::MantidMatrixNumberPrecisionDx();
   } else {
@@ -64,17 +68,17 @@ int MantidMatrixDxExtensionHandler::getPrecision(MantidMatrixTabExtension& exten
 }
 
 /**
- * Set the column width 
+ * Set the column width
  * @param extension: the extension
- * @param width: the width 
+ * @param width: the width
  * @param numberOfColumns: the number of columns
  */
-void MantidMatrixDxExtensionHandler::setColumnWidth(MantidMatrixTabExtension& extension, int width, int numberOfColumns) {
+void MantidMatrixDxExtensionHandler::setColumnWidth(
+    MantidMatrixTabExtension &extension, int width, int numberOfColumns) {
   if (extension.type == m_type) {
     auto table_view = extension.tableView;
     table_view->horizontalHeader()->setDefaultSectionSize(width);
-    for(int i=0; i<numberOfColumns; i++)
-    {
+    for (int i = 0; i < numberOfColumns; i++) {
       table_view->setColumnWidth(i, width);
     }
   } else {
@@ -83,11 +87,12 @@ void MantidMatrixDxExtensionHandler::setColumnWidth(MantidMatrixTabExtension& ex
 }
 
 /**
- * Get the column width 
+ * Get the column width
  * @param extension: the extension
  * @returns the column width
  */
-int MantidMatrixDxExtensionHandler::getColumnWidth(MantidMatrixTabExtension& extension) {
+int MantidMatrixDxExtensionHandler::getColumnWidth(
+    MantidMatrixTabExtension &extension) {
   if (extension.type == m_type) {
     auto table_view = extension.tableView;
     return table_view->columnWidth(0);
@@ -101,7 +106,8 @@ int MantidMatrixDxExtensionHandler::getColumnWidth(MantidMatrixTabExtension& ext
  * @param extension: the extension
  * @returns a pointer to the table view
  */
-QTableView* MantidMatrixDxExtensionHandler::getTableView(MantidMatrixTabExtension& extension) {
+QTableView *MantidMatrixDxExtensionHandler::getTableView(
+    MantidMatrixTabExtension &extension) {
   if (extension.type == m_type) {
     return extension.tableView;
   } else {
@@ -112,9 +118,10 @@ QTableView* MantidMatrixDxExtensionHandler::getTableView(MantidMatrixTabExtensio
 /**
  * Set the column width preference
  * @param extension: the extension
- * @param width: the width 
+ * @param width: the width
  */
-void MantidMatrixDxExtensionHandler::setColumnWidthPreference(MantidMatrixTabExtension& extension, int width) {
+void MantidMatrixDxExtensionHandler::setColumnWidthPreference(
+    MantidMatrixTabExtension &extension, int width) {
   if (extension.type == m_type) {
     MantidPreferences::MantidMatrixColumnWidthDx(width);
   } else {
@@ -125,7 +132,8 @@ void MantidMatrixDxExtensionHandler::setColumnWidthPreference(MantidMatrixTabExt
 /**
  * Get the column width preference
  */
-int MantidMatrixDxExtensionHandler:: getColumnWidthPreference(MantidMatrixTabExtension& extension) {
+int MantidMatrixDxExtensionHandler::getColumnWidthPreference(
+    MantidMatrixTabExtension &extension) {
   if (extension.type == m_type) {
     return MantidPreferences::MantidMatrixColumnWidthDx();
   } else {
diff --git a/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.cpp b/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.cpp
index e014f93f8780425e3b9ea5893b5802aa344569be..799d1abb246407e88ad85daed53e0e604193bbb7 100644
--- a/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.cpp
+++ b/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.cpp
@@ -6,7 +6,6 @@
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/make_unique.h"
 
-
 MantidMatrixExtensionRequest::MantidMatrixExtensionRequest()
     : m_extensionHandler(new MantidMatrixNullExtensionHandler()) {}
 
@@ -24,15 +23,15 @@ MantidMatrixExtensionRequest::createMantidMatrixTabExtension(
 
   switch (type) {
   case MantidMatrixModel::DX: {
-      extension.label = "X Errors";
-      extension.type = type;
-      // Extend the chain of responsibility
-      auto dxHandler =
-          Mantid::Kernel::make_unique<MantidMatrixDxExtensionHandler>();
-      dxHandler->setSuccessor(m_extensionHandler);
-      m_extensionHandler = std::move(dxHandler);
-      return extension;
-    }
+    extension.label = "X Errors";
+    extension.type = type;
+    // Extend the chain of responsibility
+    auto dxHandler =
+        Mantid::Kernel::make_unique<MantidMatrixDxExtensionHandler>();
+    dxHandler->setSuccessor(m_extensionHandler);
+    m_extensionHandler = std::move(dxHandler);
+    return extension;
+  }
   default:
     throw std::runtime_error(
         "The requested extension type has not been implemented yet");
@@ -50,24 +49,26 @@ void MantidMatrixExtensionRequest::setNumberFormat(
     MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
     const QChar &format, int precision) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     m_extensionHandler->setNumberFormat(extension, format, precision);
     m_extensionHandler->recordFormat(extension, format, precision);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
   }
 }
 
-
 /**
  * Set number format for all extensions
  * @param extensions: the extensions
  * @param format: the format
  * @param precision: the precision
  */
-void MantidMatrixExtensionRequest::setNumberFormatForAll(MantidMatrixTabExtensionMap& extensions, const QChar& format,int precision) {
+void MantidMatrixExtensionRequest::setNumberFormatForAll(
+    MantidMatrixTabExtensionMap &extensions, const QChar &format,
+    int precision) {
   for (auto it = extensions.begin(); it != extensions.end(); ++it) {
-    auto& extension = it->second;
+    auto &extension = it->second;
     m_extensionHandler->setNumberFormat(extension, format, precision);
   }
 }
@@ -79,12 +80,15 @@ void MantidMatrixExtensionRequest::setNumberFormatForAll(MantidMatrixTabExtensio
  * @param format: the format
   *@param precision: the precision
  */
-void MantidMatrixExtensionRequest::recordFormat(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, const QChar& format,int precision) {
+void MantidMatrixExtensionRequest::recordFormat(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    const QChar &format, int precision) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     m_extensionHandler->recordFormat(extension, format, precision);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
   }
 }
 
@@ -95,12 +99,15 @@ void MantidMatrixExtensionRequest::recordFormat(MantidMatrixModel::Type type, Ma
  * @param defaultValue: the default value
  * @returns the format character
  */
-QChar MantidMatrixExtensionRequest::getFormat(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, QChar defaultValue) {
+QChar MantidMatrixExtensionRequest::getFormat(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    QChar defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return m_extensionHandler->getFormat(extension);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
     return defaultValue;
   }
 }
@@ -112,26 +119,29 @@ QChar MantidMatrixExtensionRequest::getFormat(MantidMatrixModel::Type type, Mant
  * @param defaultValue: a defaut value
  * @returns the precision
  */
-int MantidMatrixExtensionRequest::getPrecision(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue) {
+int MantidMatrixExtensionRequest::getPrecision(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    int defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return m_extensionHandler->getPrecision(extension);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
     return defaultValue;
   }
 }
 
-
 /**
  * Set the column width
  * @param extensions: the extensions
  * @param width: the width
  * @param numberOfColumns: the number of columns
  */
-void MantidMatrixExtensionRequest::setColumnWidthForAll(MantidMatrixTabExtensionMap& extensions, int width, int numberOfColumns) {
+void MantidMatrixExtensionRequest::setColumnWidthForAll(
+    MantidMatrixTabExtensionMap &extensions, int width, int numberOfColumns) {
   for (auto it = extensions.begin(); it != extensions.end(); ++it) {
-    auto& extension = it->second;
+    auto &extension = it->second;
     m_extensionHandler->setColumnWidth(extension, width, numberOfColumns);
   }
 }
@@ -144,9 +154,11 @@ void MantidMatrixExtensionRequest::setColumnWidthForAll(MantidMatrixTabExtension
  * @param defaultValue: a default table view
  * @returns a table view object
  */
-QTableView* MantidMatrixExtensionRequest::getTableView(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int width, QTableView* defaultValue) {
+QTableView *MantidMatrixExtensionRequest::getTableView(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    int width, QTableView *defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     m_extensionHandler->setColumnWidthPreference(extension, width);
     return m_extensionHandler->getTableView(extension);
   } else {
@@ -154,7 +166,6 @@ QTableView* MantidMatrixExtensionRequest::getTableView(MantidMatrixModel::Type t
   }
 }
 
-
 /**
  * Get the table view for a specified type
  * @param type: the type
@@ -162,12 +173,15 @@ QTableView* MantidMatrixExtensionRequest::getTableView(MantidMatrixModel::Type t
  * @param width: the width to set
  * @returns a table view object
  */
-void MantidMatrixExtensionRequest::setColumnWidthPreference(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int width) {
+void MantidMatrixExtensionRequest::setColumnWidthPreference(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    int width) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     m_extensionHandler->setColumnWidthPreference(extension, width);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
   }
 }
 
@@ -178,12 +192,15 @@ void MantidMatrixExtensionRequest::setColumnWidthPreference(MantidMatrixModel::T
  * @param defaultValue: a default column width
  * @returns the precision
  */
-int MantidMatrixExtensionRequest::getColumnWidth(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue) {
+int MantidMatrixExtensionRequest::getColumnWidth(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    int defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return m_extensionHandler->getColumnWidth(extension);
   } else {
-    g_log.warning("MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
+    g_log.warning(
+        "MantidMatrixExtensionRequest: Trying to alter an unknown extension.");
     return defaultValue;
   }
 }
@@ -194,9 +211,10 @@ int MantidMatrixExtensionRequest::getColumnWidth(MantidMatrixModel::Type type, M
  * @param object: the object to compare to
  * @returns true if an extension matches the object else false
  */
-bool MantidMatrixExtensionRequest::tableViewMatchesObject(MantidMatrixTabExtensionMap& extensions, QObject *object) {
+bool MantidMatrixExtensionRequest::tableViewMatchesObject(
+    MantidMatrixTabExtensionMap &extensions, QObject *object) {
   for (auto it = extensions.begin(); it != extensions.end(); ++it) {
-    auto& extension = it->second;
+    auto &extension = it->second;
     if (extension.tableView == object) {
       return true;
     }
@@ -211,9 +229,11 @@ bool MantidMatrixExtensionRequest::tableViewMatchesObject(MantidMatrixTabExtensi
  * @param defaultValue: a default table view pointer
  * @returns the active table view
  */
-QTableView* MantidMatrixExtensionRequest::getActiveView(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, QTableView* defaultValue) {
+QTableView *MantidMatrixExtensionRequest::getActiveView(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    QTableView *defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return extension.tableView;
   } else {
     return defaultValue;
@@ -227,16 +247,17 @@ QTableView* MantidMatrixExtensionRequest::getActiveView(MantidMatrixModel::Type
  * @param defaultValue: a default active model
  * @returns the active model
  */
-MantidMatrixModel* MantidMatrixExtensionRequest::getActiveModel(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, MantidMatrixModel* defaultValue) {
+MantidMatrixModel *MantidMatrixExtensionRequest::getActiveModel(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    MantidMatrixModel *defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return extension.model;
   } else {
     return defaultValue;
   }
 }
 
-
 /**
  * Get the column width preference
  * @param type: the type
@@ -244,9 +265,11 @@ MantidMatrixModel* MantidMatrixExtensionRequest::getActiveModel(MantidMatrixMode
  * @param defaultValue: the default value
  * @returns the column width from the preferences
  */
-int MantidMatrixExtensionRequest::getColumnWidthPreference(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue) {
+int MantidMatrixExtensionRequest::getColumnWidthPreference(
+    MantidMatrixModel::Type type, MantidMatrixTabExtensionMap &extensions,
+    int defaultValue) {
   if (extensions.count(type) > 0) {
-    auto& extension = extensions[type];
+    auto &extension = extensions[type];
     return m_extensionHandler->getColumnWidthPreference(extension);
   } else {
     return defaultValue;
diff --git a/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.h b/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.h
index 9aa5f18218dda948ca68d9e328ccab4399a0ffe1..ea15c68825d430c145db7296753340b29d3368bc 100644
--- a/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.h
+++ b/MantidPlot/src/Mantid/MantidMatrixExtensionRequest.h
@@ -6,25 +6,45 @@
 #include "IMantidMatrixExtensionHandler.h"
 #include <memory>
 
-
 class MantidMatrixExtensionRequest {
 public:
   MantidMatrixExtensionRequest();
   ~MantidMatrixExtensionRequest();
-  MantidMatrixTabExtension createMantidMatrixTabExtension(MantidMatrixModel::Type type);
-  void setNumberFormat(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, const QChar& format,int precision);
-  void setNumberFormatForAll(MantidMatrixTabExtensionMap& extensions, const QChar& format,int precision);
-  void recordFormat(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, const QChar& format,int precision);
-  QChar getFormat(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, QChar defaultValue);
-  int getPrecision(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue);
-  int getColumnWidth(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue);
-  void setColumnWidthForAll(MantidMatrixTabExtensionMap& m_extensions, int width, int numberOfColumns);
-  QTableView* getTableView(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int width, QTableView* defaultValue);
-  void setColumnWidthPreference(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int width);
-  QTableView* getActiveView(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, QTableView* defaultValue);
-  MantidMatrixModel* getActiveModel(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, MantidMatrixModel* defaultValue);
-  bool tableViewMatchesObject(MantidMatrixTabExtensionMap& extensions, QObject *object);
-  int getColumnWidthPreference(MantidMatrixModel::Type type, MantidMatrixTabExtensionMap& extensions, int defaultValue);
+  MantidMatrixTabExtension
+  createMantidMatrixTabExtension(MantidMatrixModel::Type type);
+  void setNumberFormat(MantidMatrixModel::Type type,
+                       MantidMatrixTabExtensionMap &extensions,
+                       const QChar &format, int precision);
+  void setNumberFormatForAll(MantidMatrixTabExtensionMap &extensions,
+                             const QChar &format, int precision);
+  void recordFormat(MantidMatrixModel::Type type,
+                    MantidMatrixTabExtensionMap &extensions,
+                    const QChar &format, int precision);
+  QChar getFormat(MantidMatrixModel::Type type,
+                  MantidMatrixTabExtensionMap &extensions, QChar defaultValue);
+  int getPrecision(MantidMatrixModel::Type type,
+                   MantidMatrixTabExtensionMap &extensions, int defaultValue);
+  int getColumnWidth(MantidMatrixModel::Type type,
+                     MantidMatrixTabExtensionMap &extensions, int defaultValue);
+  void setColumnWidthForAll(MantidMatrixTabExtensionMap &m_extensions,
+                            int width, int numberOfColumns);
+  QTableView *getTableView(MantidMatrixModel::Type type,
+                           MantidMatrixTabExtensionMap &extensions, int width,
+                           QTableView *defaultValue);
+  void setColumnWidthPreference(MantidMatrixModel::Type type,
+                                MantidMatrixTabExtensionMap &extensions,
+                                int width);
+  QTableView *getActiveView(MantidMatrixModel::Type type,
+                            MantidMatrixTabExtensionMap &extensions,
+                            QTableView *defaultValue);
+  MantidMatrixModel *getActiveModel(MantidMatrixModel::Type type,
+                                    MantidMatrixTabExtensionMap &extensions,
+                                    MantidMatrixModel *defaultValue);
+  bool tableViewMatchesObject(MantidMatrixTabExtensionMap &extensions,
+                              QObject *object);
+  int getColumnWidthPreference(MantidMatrixModel::Type type,
+                               MantidMatrixTabExtensionMap &extensions,
+                               int defaultValue);
 
 private:
   std::unique_ptr<IMantidMatrixExtensionHandler> m_extensionHandler;
diff --git a/MantidPlot/src/Mantid/MantidMatrixFunction.cpp b/MantidPlot/src/Mantid/MantidMatrixFunction.cpp
index 62bf8c0e8f9bfae83c2dafa95ecd1808dd832eca..ba4ec08ecfab9c7775b615528184f31327c54b3a 100644
--- a/MantidPlot/src/Mantid/MantidMatrixFunction.cpp
+++ b/MantidPlot/src/Mantid/MantidMatrixFunction.cpp
@@ -3,14 +3,13 @@
 #include "MantidAPI/Axis.h"
 #include "MantidAPI/MatrixWorkspace.h"
 
-MantidMatrixFunction::MantidMatrixFunction(MantidMatrix &matrix):
-    m_outside(0)
-{
+MantidMatrixFunction::MantidMatrixFunction(MantidMatrix &matrix)
+    : m_outside(0) {
 
   init(matrix.workspace());
 
   double tmp;
-  matrix.range( &tmp, &m_outside );
+  matrix.range(&tmp, &m_outside);
   m_outside *= 1.1;
 
   m_observer = new MantidMatrixFunctionWorkspaceObserver(this);
@@ -19,8 +18,7 @@ MantidMatrixFunction::MantidMatrixFunction(MantidMatrix &matrix):
   m_observer->observeAfterReplace();
 }
 
-MantidMatrixFunction::~MantidMatrixFunction()
-{
+MantidMatrixFunction::~MantidMatrixFunction() {
   m_observer->observeADSClear(false);
   m_observer->observePreDelete(false);
   m_observer->observeAfterReplace(false);
@@ -31,17 +29,15 @@ MantidMatrixFunction::~MantidMatrixFunction()
  *
  * @param workspace :: New workspace to use.
  */
-void MantidMatrixFunction::init(const Mantid::API::MatrixWorkspace_const_sptr& workspace)
-{
-    m_workspace = workspace;
+void MantidMatrixFunction::init(
+    const Mantid::API::MatrixWorkspace_const_sptr &workspace) {
+  m_workspace = workspace;
 
-    if (!m_workspace->getAxis(1))
-    {
-      throw std::runtime_error("The y-axis is not set");
-    }
-
-    setMesh(m_workspace->blocksize(),m_workspace->getNumberHistograms());
+  if (!m_workspace->getAxis(1)) {
+    throw std::runtime_error("The y-axis is not set");
+  }
 
+  setMesh(m_workspace->blocksize(), m_workspace->getNumberHistograms());
 }
 
 /**
@@ -49,49 +45,43 @@ void MantidMatrixFunction::init(const Mantid::API::MatrixWorkspace_const_sptr& w
  *
  * @param workspace :: New workspace to use.
  */
-void MantidMatrixFunction::reset(const Mantid::API::MatrixWorkspace_const_sptr &workspace)
-{
-    init( workspace );
-    double minz, maxz;
-    findYRange( workspace, minz, maxz );
-    setMinZ( minz );
-    setMaxZ( maxz );
-    setMesh(workspace->blocksize(),workspace->getNumberHistograms());
-    double minx,maxx;
-    workspace->getXMinMax( minx, maxx );
-    const Mantid::API::Axis *axis = workspace->getAxis(1);
-    double miny = axis->getMin();
-    double maxy = axis->getMax();
-    setDomain(minx,maxx,miny,maxy);
-    create();
+void MantidMatrixFunction::reset(
+    const Mantid::API::MatrixWorkspace_const_sptr &workspace) {
+  init(workspace);
+  double minz, maxz;
+  findYRange(workspace, minz, maxz);
+  setMinZ(minz);
+  setMaxZ(maxz);
+  setMesh(workspace->blocksize(), workspace->getNumberHistograms());
+  double minx, maxx;
+  workspace->getXMinMax(minx, maxx);
+  const Mantid::API::Axis *axis = workspace->getAxis(1);
+  double miny = axis->getMin();
+  double maxy = axis->getMax();
+  setDomain(minx, maxx, miny, maxy);
+  create();
 }
 
-double MantidMatrixFunction::operator()(double x, double y)
-{
+double MantidMatrixFunction::operator()(double x, double y) {
   size_t i = indexY(y);
-  if ( i >= rows() )
-  {
+  if (i >= rows()) {
     return m_outside;
   }
 
-  size_t j = indexX(i,x);
+  size_t j = indexX(i, x);
 
-  if ( j < columns() )
-      return m_workspace->readY(i)[j];
+  if (j < columns())
+    return m_workspace->readY(i)[j];
   else
     return m_outside;
 }
 
-double MantidMatrixFunction::getMinPositiveValue()const
-{
+double MantidMatrixFunction::getMinPositiveValue() const {
   double zmin = DBL_MAX;
-  for(size_t i = 0; i < rows(); ++i)
-  {
-    for(size_t j = 0; j < columns(); ++j)
-    {
-      double tmp = value(i,j);
-      if (tmp > 0 && tmp < zmin)
-      {
+  for (size_t i = 0; i < rows(); ++i) {
+    for (size_t j = 0; j < columns(); ++j) {
+      double tmp = value(i, j);
+      if (tmp > 0 && tmp < zmin) {
         zmin = tmp;
       }
     }
@@ -99,147 +89,137 @@ double MantidMatrixFunction::getMinPositiveValue()const
   return zmin;
 }
 
-QString MantidMatrixFunction::saveToString() const
-{
-    return "mantidMatrix3D\t";
+QString MantidMatrixFunction::saveToString() const {
+  return "mantidMatrix3D\t";
 }
 
 /**
  * Connect to a viewer object to ask it to redraw when needed.
  *
- * @param viewer :: An object displaying this function. It must have slot update().
+ * @param viewer :: An object displaying this function. It must have slot
+ *update().
  */
-void MantidMatrixFunction::connectToViewer(QObject *viewer)
-{
-    m_observer->connect(m_observer,SIGNAL(requestRedraw()),viewer,SLOT(update()));
-    m_observer->connect(m_observer,SIGNAL(requestClose()),viewer,SLOT(close()));
+void MantidMatrixFunction::connectToViewer(QObject *viewer) {
+  m_observer->connect(m_observer, SIGNAL(requestRedraw()), viewer,
+                      SLOT(update()));
+  m_observer->connect(m_observer, SIGNAL(requestClose()), viewer,
+                      SLOT(close()));
 }
 
-double MantidMatrixFunction::value(size_t row,size_t col)const
-{
+double MantidMatrixFunction::value(size_t row, size_t col) const {
   return m_workspace->readY(row)[col];
 }
 
-void MantidMatrixFunction::getRowYRange(size_t row,double& ymin, double& ymax)const
-{
-  const Mantid::API::Axis& yAxis = *(m_workspace->getAxis(1));
-
+void MantidMatrixFunction::getRowYRange(size_t row, double &ymin,
+                                        double &ymax) const {
+  const Mantid::API::Axis &yAxis = *(m_workspace->getAxis(1));
 
   size_t i = row;
   double y = yAxis(i);
 
-  size_t imax = static_cast<int>(m_workspace->getNumberHistograms())-1;
-  if (yAxis.isNumeric())
-  {
-    if (i < imax)
-    {
-      ymax = (yAxis(i+1) + y)/2;
-      if (i > 0)
-      {
-        ymin = (yAxis(i-1) + y)/2;
+  size_t imax = static_cast<int>(m_workspace->getNumberHistograms()) - 1;
+  if (yAxis.isNumeric()) {
+    if (i < imax) {
+      ymax = (yAxis(i + 1) + y) / 2;
+      if (i > 0) {
+        ymin = (yAxis(i - 1) + y) / 2;
+      } else {
+        ymin = 2 * y - ymax;
       }
-      else
-      {
-        ymin = 2*y - ymax;
-      }
-    }
-    else
-    {
-      ymin = (yAxis(i-1) + y)/2;
-      ymax = 2*y - ymin;
+    } else {
+      ymin = (yAxis(i - 1) + y) / 2;
+      ymax = 2 * y - ymin;
     }
-  }
-  else // if spectra
+  } else // if spectra
   {
     ymin = y - 0.5;
     ymax = y + 0.5;
   }
-  
 }
 
-void MantidMatrixFunction::getRowXRange(int row,double& xmin, double& xmax)const
-{
-  const Mantid::MantidVec& X = m_workspace->readX(row);
+void MantidMatrixFunction::getRowXRange(int row, double &xmin,
+                                        double &xmax) const {
+  const Mantid::MantidVec &X = m_workspace->readX(row);
   xmin = X[0];
-  xmax = X[X.size()-1];
+  xmax = X[X.size() - 1];
 }
 
-const Mantid::MantidVec& MantidMatrixFunction::getMantidVec(int row)const
-{
-    return m_workspace->readX(row);
+const Mantid::MantidVec &MantidMatrixFunction::getMantidVec(int row) const {
+  return m_workspace->readX(row);
 }
 
-size_t MantidMatrixFunction::indexX(size_t row,double s)const
-{
+size_t MantidMatrixFunction::indexX(size_t row, double s) const {
   size_t n = m_workspace->blocksize();
 
-  const Mantid::MantidVec& X = m_workspace->readX(row);
-  if (n == 0 || s < X[0] || s > X[n-1]) return std::numeric_limits<size_t>::max();
+  const Mantid::MantidVec &X = m_workspace->readX(row);
+  if (n == 0 || s < X[0] || s > X[n - 1])
+    return std::numeric_limits<size_t>::max();
 
-  size_t i = 0, j = n-1, k = n/2;
-  for(size_t it = 0; it < n; it++)
-  {
+  size_t i = 0, j = n - 1, k = n / 2;
+  for (size_t it = 0; it < n; it++) {
     const double ss = X[k];
-    if (ss == s ) return k;
-    if (abs(static_cast<int>(i) - static_cast<int>(j)) <2)
-    {
-      double ds = fabs(ss-s);
-      if (fabs(X[j]-s) < ds) return j;
+    if (ss == s)
+      return k;
+    if (abs(static_cast<int>(i) - static_cast<int>(j)) < 2) {
+      double ds = fabs(ss - s);
+      if (fabs(X[j] - s) < ds)
+        return j;
       return i;
     }
-    if (s > ss) i = k;
+    if (s > ss)
+      i = k;
     else
       j = k;
-    k = i + (j - i)/2;
+    k = i + (j - i) / 2;
   }
 
   return i;
 }
 
-size_t MantidMatrixFunction::indexY(double s)const
-{
+size_t MantidMatrixFunction::indexY(double s) const {
   size_t n = rows();
 
-  const Mantid::API::Axis& yAxis = *m_workspace->getAxis(1);
+  const Mantid::API::Axis &yAxis = *m_workspace->getAxis(1);
 
   bool isNumeric = yAxis.isNumeric();
 
-  if (n == 0) return std::numeric_limits<size_t>::max();
+  if (n == 0)
+    return std::numeric_limits<size_t>::max();
 
   size_t i0 = 0;
 
-  if (s < yAxis(i0))
-  {
-    if (isNumeric || yAxis(i0) - s > 0.5) return std::numeric_limits<size_t>::max();
+  if (s < yAxis(i0)) {
+    if (isNumeric || yAxis(i0) - s > 0.5)
+      return std::numeric_limits<size_t>::max();
     return 0;
-  }
-  else if (s > yAxis(n-1))
-  {
-    if (isNumeric || s - yAxis(n-1) > 0.5) return std::numeric_limits<size_t>::max();
-    return n-1;
+  } else if (s > yAxis(n - 1)) {
+    if (isNumeric || s - yAxis(n - 1) > 0.5)
+      return std::numeric_limits<size_t>::max();
+    return n - 1;
   }
 
-  size_t i = i0, j = n-1, k = n/2;
-  for(size_t it = 0; it < n; it++)
-  {
+  size_t i = i0, j = n - 1, k = n / 2;
+  for (size_t it = 0; it < n; it++) {
     const double ss = yAxis(k);
-    if (ss == s ) return k;
-    if (abs(static_cast<int>(i) - static_cast<int>(j)) <2)
-    {
-      double ds = fabs(ss-s);
-      double ds1 = fabs(yAxis(j)-s);
-      if (ds1 < ds)
-      {
-        if (isNumeric || ds1 < 0.5) return j;
+    if (ss == s)
+      return k;
+    if (abs(static_cast<int>(i) - static_cast<int>(j)) < 2) {
+      double ds = fabs(ss - s);
+      double ds1 = fabs(yAxis(j) - s);
+      if (ds1 < ds) {
+        if (isNumeric || ds1 < 0.5)
+          return j;
         return std::numeric_limits<size_t>::max();
       }
-      if (isNumeric || ds < 0.5) return i;
+      if (isNumeric || ds < 0.5)
+        return i;
       return std::numeric_limits<size_t>::max();
     }
-    if (s > ss) i = k;
+    if (s > ss)
+      i = k;
     else
       j = k;
-    k = i + (j - i)/2;
+    k = i + (j - i) / 2;
   }
 
   return i;
@@ -247,37 +227,33 @@ size_t MantidMatrixFunction::indexY(double s)const
 
 /*--------------------------------------------------------------------------------------------*/
 
-MantidMatrixFunctionWorkspaceObserver::MantidMatrixFunctionWorkspaceObserver(MantidMatrixFunction *fun):
-    m_function(fun)
-{
-}
-
-void MantidMatrixFunctionWorkspaceObserver::afterReplaceHandle(const std::string &wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-    if ( m_function->m_workspace && wsName == m_function->m_workspace->name() )
-    {
-        auto mws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(ws);
-        if ( mws )
-        {
-            m_function->reset( mws );
-            emit requestRedraw();
-        }
-        else
-        {
-            emit requestClose();
-        }
+MantidMatrixFunctionWorkspaceObserver::MantidMatrixFunctionWorkspaceObserver(
+    MantidMatrixFunction *fun)
+    : m_function(fun) {}
+
+void MantidMatrixFunctionWorkspaceObserver::afterReplaceHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
+  if (m_function->m_workspace && wsName == m_function->m_workspace->name()) {
+    auto mws =
+        boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(ws);
+    if (mws) {
+      m_function->reset(mws);
+      emit requestRedraw();
+    } else {
+      emit requestClose();
     }
+  }
 }
 
-void MantidMatrixFunctionWorkspaceObserver::preDeleteHandle(const std::string &wsName, const boost::shared_ptr<Mantid::API::Workspace>)
-{
-    if ( m_function->m_workspace && wsName == m_function->m_workspace->name() )
-    {
-        emit requestClose();
-    }
+void MantidMatrixFunctionWorkspaceObserver::preDeleteHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace>) {
+  if (m_function->m_workspace && wsName == m_function->m_workspace->name()) {
+    emit requestClose();
+  }
 }
 
-void MantidMatrixFunctionWorkspaceObserver::clearADSHandle()
-{
-    emit requestClose();
+void MantidMatrixFunctionWorkspaceObserver::clearADSHandle() {
+  emit requestClose();
 }
diff --git a/MantidPlot/src/Mantid/MantidMatrixFunction.h b/MantidPlot/src/Mantid/MantidMatrixFunction.h
index 7037d46daf0b161905925191166dd72f941b443a..f7e4f8c5eb34d84a332fb03a929d96efa72076a0 100644
--- a/MantidPlot/src/Mantid/MantidMatrixFunction.h
+++ b/MantidPlot/src/Mantid/MantidMatrixFunction.h
@@ -14,22 +14,24 @@
 class MantidMatrixFunction;
 
 /**
- * A helper class listening to ADS notifications. Helps to avoid issues with multiple inheritance
+ * A helper class listening to ADS notifications. Helps to avoid issues with
+ *multiple inheritance
  * and QObject.
  *
  */
-class MantidMatrixFunctionWorkspaceObserver: public QObject, public MantidQt::API::WorkspaceObserver
-{
-    Q_OBJECT
+class MantidMatrixFunctionWorkspaceObserver
+    : public QObject,
+      public MantidQt::API::WorkspaceObserver {
+  Q_OBJECT
 public:
   explicit MantidMatrixFunctionWorkspaceObserver(MantidMatrixFunction *);
 
 signals:
-    void requestRedraw();
-    void requestClose();
+  void requestRedraw();
+  void requestClose();
 
 private:
-    /* Base class virtual methods */
+  /* Base class virtual methods */
 
   void afterReplaceHandle(
       const std::string &wsName,
@@ -39,14 +41,13 @@ private:
                   const boost::shared_ptr<Mantid::API::Workspace>) override;
   void clearADSHandle() override;
 
-    MantidMatrixFunction *m_function;
+  MantidMatrixFunction *m_function;
 };
 
 /**
  * This class helps displaying a MantidMatrix in a 2D or 3D graph.
  */
-class MantidMatrixFunction: public Function2D
-{
+class MantidMatrixFunction : public Function2D {
 public:
   explicit MantidMatrixFunction(MantidMatrix &matrix);
   ~MantidMatrixFunction() override;
@@ -61,12 +62,13 @@ public:
   /* Public methods */
 
   /// Value at a mesh node
-  double value(size_t row, size_t col)const;
+  double value(size_t row, size_t col) const;
   /// Return in ymin and ymax the inetrval the row takes on the y axis
-  void getRowYRange(size_t row, double& ymin, double& ymax)const;
+  void getRowYRange(size_t row, double &ymin, double &ymax) const;
   /// Return in xmin and xmax the inetrval the cell takes on the x axis
-  void getRowXRange(int row,double& xmin, double& xmax)const;
-  const Mantid::MantidVec& getMantidVec(int row)const;
+  void getRowXRange(int row, double &xmin, double &xmax) const;
+  const Mantid::MantidVec &getMantidVec(int row) const;
+
 private:
   /* Private methods */
 
diff --git a/MantidPlot/src/Mantid/MantidMatrixModel.h b/MantidPlot/src/Mantid/MantidMatrixModel.h
index 2b7ed05b4ca9e87de65dcad91474d044b0b54390..5ed4a35b932b809492af580fa3b533e0df080c25 100644
--- a/MantidPlot/src/Mantid/MantidMatrixModel.h
+++ b/MantidPlot/src/Mantid/MantidMatrixModel.h
@@ -9,39 +9,36 @@
 #include <QLocale>
 /**
 MantidMatrixModel is an implementation of QAbstractTableModel which is an
-interface between the data (workspace) and the widget displaying it (QTableView).
+interface between the data (workspace) and the widget displaying it
+(QTableView).
 It presents spectrum data (Type Y), bin boundaries (Type X), and errors (Type E)
 as a table.
 */
-class MantidMatrixModel:public QAbstractTableModel
-{
+class MantidMatrixModel : public QAbstractTableModel {
   Q_OBJECT
 public:
-  typedef enum {Y,X,E,DX} Type;
-  MantidMatrixModel(QObject *parent,
-    const Mantid::API::MatrixWorkspace* ws,
-    int rows,
-    int cols,
-    int start,
-    Type type);
+  typedef enum { Y, X, E, DX } Type;
+  MantidMatrixModel(QObject *parent, const Mantid::API::MatrixWorkspace *ws,
+                    int rows, int cols, int start, Type type);
 
   /// Call this function if the workspace has changed
-  void setup(const Mantid::API::MatrixWorkspace* ws,
-    int rows,
-    int cols,
-    int start);
+  void setup(const Mantid::API::MatrixWorkspace *ws, int rows, int cols,
+             int start);
 
-  /// Implementation of QAbstractTableModel::rowCount() -- number of rows (spectra) that can be shown
+  /// Implementation of QAbstractTableModel::rowCount() -- number of rows
+  /// (spectra) that can be shown
   int rowCount(const QModelIndex &parent = QModelIndex()) const override {
-    (void)parent; //To avoid compiler warning
+    (void)parent; // To avoid compiler warning
     return m_rows;
   }
 
-  /// Implementation of QAbstractTableModel::columnCount() -- number of columns. If type is X it is
-  /// the number of bin boundaries. If the type is DX it is the number of bin boundaries as well.
-  ///If type is Y or E it is the number of data values.
+  /// Implementation of QAbstractTableModel::columnCount() -- number of columns.
+  /// If type is X it is
+  /// the number of bin boundaries. If the type is DX it is the number of bin
+  /// boundaries as well.
+  /// If type is Y or E it is the number of data values.
   int columnCount(const QModelIndex &parent = QModelIndex()) const override {
-    (void)parent; //To avoid compiler warning
+    (void)parent; // To avoid compiler warning
     int columnCount = 0;
     if (m_type == X || m_type == DX) {
       columnCount = m_cols + m_colNumCorr;
@@ -53,7 +50,8 @@ public:
 
   double data(int row, int col) const;
 
-  /// Implementation of QAbstractTableModel::data(...). QTableView uses this function
+  /// Implementation of QAbstractTableModel::data(...). QTableView uses this
+  /// function
   /// to retrieve data for displaying.
   QVariant data(const QModelIndex &index, int role) const override;
   QVariant headerData(int section, Qt::Orientation orientation,
@@ -62,26 +60,30 @@ public:
   Qt::ItemFlags flags(const QModelIndex &index) const override;
 
   // Set format and precision of displayed numbers.
-  void setFormat(const QChar& f,int prec);
-  QChar format(){return m_format;}
-  int precision(){return m_prec;}
+  void setFormat(const QChar &f, int prec);
+  QChar format() { return m_format; }
+  int precision() { return m_prec; }
 public slots:
   /// Signals QTableView that the data have changed.
-  void resetData(){reset();}
+  void resetData() { reset(); }
+
 private:
-  bool checkMonitorCache(int row) const; //check the cache and add to it if neccessary
+  bool checkMonitorCache(
+      int row) const; // check the cache and add to it if neccessary
 
-  const Mantid::API::MatrixWorkspace* m_workspace;
-  int m_startRow; ///< starting workspace index to display
-  int m_endRow;   ///< ending workspace index to display
-  int m_rows,m_cols; ///< numbers of rows and columns
-  int m_colNumCorr;  ///< == 1 for histograms and == 0 for point data
+  const Mantid::API::MatrixWorkspace *m_workspace;
+  int m_startRow;     ///< starting workspace index to display
+  int m_endRow;       ///< ending workspace index to display
+  int m_rows, m_cols; ///< numbers of rows and columns
+  int m_colNumCorr;   ///< == 1 for histograms and == 0 for point data
   QLocale m_locale;
-  Type m_type;///< The type: X for bin boundaries, Y for the spectrum data, E for errors, DX for x errors
-  char m_format;   //  Format of numbers returned by data(): 'f' - fixed, 'e' - scientific.
-  int m_prec;       //  Number precision
-  QColor m_mon_color; // Monitor Specific background color
-  mutable QHash<int, bool> m_monCache; //monitor flag cache
+  Type m_type; ///< The type: X for bin boundaries, Y for the spectrum data, E
+  /// for errors, DX for x errors
+  char m_format; //  Format of numbers returned by data(): 'f' - fixed, 'e' -
+                 //  scientific.
+  int m_prec;    //  Number precision
+  QColor m_mon_color;                  // Monitor Specific background color
+  mutable QHash<int, bool> m_monCache; // monitor flag cache
 };
 
 #endif
diff --git a/MantidPlot/src/Mantid/MantidMatrixNullExtensionHandler.h b/MantidPlot/src/Mantid/MantidMatrixNullExtensionHandler.h
index 835e694fee14643936df189bda4374e4c06d7775..146730f25f1a22e4646b7ec7055e7265c8a2c269 100644
--- a/MantidPlot/src/Mantid/MantidMatrixNullExtensionHandler.h
+++ b/MantidPlot/src/Mantid/MantidMatrixNullExtensionHandler.h
@@ -16,48 +16,57 @@ public:
 
   void setNumberFormat(MantidMatrixTabExtension &, const QChar &,
                        int) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   void recordFormat(MantidMatrixTabExtension &, const QChar &, int) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   QChar getFormat(MantidMatrixTabExtension &) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   int getPrecision(MantidMatrixTabExtension &) override {
-    throw  std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   void setColumnWidth(MantidMatrixTabExtension &, int, int) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   int getColumnWidth(MantidMatrixTabExtension &) override {
-    throw  std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   QTableView *getTableView(MantidMatrixTabExtension &) override {
-    throw  std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   void setColumnWidthPreference(MantidMatrixTabExtension &, int) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 
   int getColumnWidthPreference(MantidMatrixTabExtension &) override {
-    throw std::runtime_error("You have seemed to attached an invalid extension to the "
-                "Mantid Matrix.");
+    throw std::runtime_error(
+        "You have seemed to attached an invalid extension to the "
+        "Mantid Matrix.");
   }
 };
 #endif
\ No newline at end of file
diff --git a/MantidPlot/src/Mantid/MantidMatrixTabExtension.h b/MantidPlot/src/Mantid/MantidMatrixTabExtension.h
index 4cdf729678c4d3ee6ae7fe2ddfee40345d019c27..bc91ba0bf59c5a263817d2e3abd0e7d5bcfc07e8 100644
--- a/MantidPlot/src/Mantid/MantidMatrixTabExtension.h
+++ b/MantidPlot/src/Mantid/MantidMatrixTabExtension.h
@@ -10,20 +10,20 @@
  * Holds the information for a new tab.
  */
 struct MantidMatrixTabExtension {
-  MantidMatrixTabExtension(QString label, QTableView * tableView, MantidMatrixModel *model, MantidMatrixModel::Type type) : label(label),
-                                                                                              tableView(tableView),
-                                                                                              model(model),
-                                                                                              type(type) {}
-  MantidMatrixTabExtension(): label(""),
-                              tableView(NULL),
-                              model(NULL),
-                              type(MantidMatrixModel::Type::DX){}
+  MantidMatrixTabExtension(QString label, QTableView *tableView,
+                           MantidMatrixModel *model,
+                           MantidMatrixModel::Type type)
+      : label(label), tableView(tableView), model(model), type(type) {}
+  MantidMatrixTabExtension()
+      : label(""), tableView(NULL), model(NULL),
+        type(MantidMatrixModel::Type::DX) {}
   QString label;
   QTableView *tableView;
   QPointer<MantidMatrixModel> model;
   MantidMatrixModel::Type type;
 };
 
-typedef std::map<MantidMatrixModel::Type, MantidMatrixTabExtension> MantidMatrixTabExtensionMap;
+typedef std::map<MantidMatrixModel::Type, MantidMatrixTabExtension>
+    MantidMatrixTabExtensionMap;
 
 #endif
diff --git a/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp b/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
index 40fe9eed3382180336fa11eac7f920177a3465bd..8847724b5ecbcd353882d5f55ef4a8cbcef5b668 100644
--- a/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
+++ b/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
@@ -344,8 +344,7 @@ void MantidSampleLogDialog::init() {
                          Strings::toString(m_experimentInfoIndex) +
                          ") is not available. There are " +
                          Strings::toString(mei->getNumExperimentInfo()) +
-                         " in the workspace"
-                  << std::endl;
+                         " in the workspace" << std::endl;
         // Make a blank experiment info object
         m_ei = ExperimentInfo_const_sptr(new ExperimentInfo());
       } else
@@ -448,8 +447,9 @@ void MantidSampleLogDialog::init() {
                dynamic_cast<
                    Mantid::Kernel::PropertyWithValue<std::vector<double>> *>(
                    *pItr) ||
-               dynamic_cast<Mantid::Kernel::PropertyWithValue<std::vector<int>>
-                                *>(*pItr)) {
+               dynamic_cast<
+                   Mantid::Kernel::PropertyWithValue<std::vector<int>> *>(
+                   *pItr)) {
       treeItem->setText(1, "numeric array");
       treeItem->setData(
           1, Qt::UserRole,
diff --git a/MantidPlot/src/Mantid/MantidSampleLogDialog.h b/MantidPlot/src/Mantid/MantidSampleLogDialog.h
index ab314fe9be2017b4b0b4e013d434bcdea26a990f..cb957d0f249e76cdc4d471691cfc64f5e9ae9295 100644
--- a/MantidPlot/src/Mantid/MantidSampleLogDialog.h
+++ b/MantidPlot/src/Mantid/MantidSampleLogDialog.h
@@ -21,14 +21,15 @@ class QPushButton;
 class QRadioButton;
 class MantidUI;
 
-/** 
+/**
 This class displays a list of log files for a selected workspace. It
 allows the user to plot selected log files.
 
 @author Martyn Gigg, Tessella Support Services plc
 @date 05/11/2009
 
-Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -46,40 +47,40 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MantidSampleLogDialog : public QDialog
-{
+class MantidSampleLogDialog : public QDialog {
   Q_OBJECT
 
 public:
-  ///Constructor
-  MantidSampleLogDialog(const QString & wsname, MantidUI* mui, Qt::WFlags flags = 0, size_t experimentInfoIndex = 0);
+  /// Constructor
+  MantidSampleLogDialog(const QString &wsname, MantidUI *mui,
+                        Qt::WFlags flags = 0, size_t experimentInfoIndex = 0);
 
-  private slots:
-    ///Plot logs
-    void importSelectedLogs();
+private slots:
+  /// Plot logs
+  void importSelectedLogs();
 
-    /// Show the stats of the selected log
-    void showLogStatistics();
-    void showLogStatisticsOfItem(QTreeWidgetItem * item);
+  /// Show the stats of the selected log
+  void showLogStatistics();
+  void showLogStatisticsOfItem(QTreeWidgetItem *item);
 
-    ///Context menu popup
-    void popupMenu(const QPoint & pos);
+  /// Context menu popup
+  void popupMenu(const QPoint &pos);
 
-    ///Import a single item
-    void importItem(QTreeWidgetItem *item);
+  /// Import a single item
+  void importItem(QTreeWidgetItem *item);
 
-    void selectExpInfoNumber(int num);
+  void selectExpInfoNumber(int num);
 
 private:
-  ///Initialize the layout
+  /// Initialize the layout
   void init();
 
-  ///A tree widget
+  /// A tree widget
   QTreeWidget *m_tree;
 
-  ///The workspace name
+  /// The workspace name
   std::string m_wsname;
 
   /// Index into the ExperimentInfo list.
@@ -88,7 +89,7 @@ private:
   /// The actual experiment info being looked at.
   Mantid::API::ExperimentInfo_const_sptr m_ei;
 
-  ///Buttons to do things
+  /// Buttons to do things
   QPushButton *buttonPlot, *buttonClose;
 
   /// Filter radio buttons
@@ -98,25 +99,28 @@ private:
   static const std::size_t NUM_STATS = 7;
 
   /// Stats labels
-  QLabel* statLabels[NUM_STATS]; //minLabel, maxLabel, meanLabel, timeAverageLabel, medianLabel, stddevLabel, durationLabel;
+  QLabel *statLabels[NUM_STATS]; // minLabel, maxLabel, meanLabel,
+                                 // timeAverageLabel, medianLabel, stddevLabel,
+                                 // durationLabel;
 
   /// Testboxes with stats data
-  QLineEdit  * statValues[NUM_STATS];
+  QLineEdit *statValues[NUM_STATS];
 
   /// Widget to select the # of the experiment info to look at.
-  QSpinBox * m_spinNumber;
-
-  ///A pointer to the MantidUI object
-  MantidUI* m_mantidUI;
-  /// these values are used to specify the format of the log file, all of which are stored as strings
-  enum logType
-  {
-    string,                           ///< indicates the log is a string, no other known formating
-    numTSeries,                       ///< for time series properties that contain numbers
-    stringTSeries,                    ///< for logs that are string time series properties
-    numeric,                          ///< for logs that are single numeric values (int or double)
-    numericArray                      ///< for logs that are an array of numeric values (int or double)
+  QSpinBox *m_spinNumber;
+
+  /// A pointer to the MantidUI object
+  MantidUI *m_mantidUI;
+  /// these values are used to specify the format of the log file, all of which
+  /// are stored as strings
+  enum logType {
+    string,        ///< indicates the log is a string, no other known formating
+    numTSeries,    ///< for time series properties that contain numbers
+    stringTSeries, ///< for logs that are string time series properties
+    numeric,       ///< for logs that are single numeric values (int or double)
+    numericArray   ///< for logs that are an array of numeric values (int or
+    /// double)
   };
 };
 
-#endif //MANTIDSAMPLELOGDIALOG_H_
+#endif // MANTIDSAMPLELOGDIALOG_H_
diff --git a/MantidPlot/src/Mantid/MantidSampleMaterialDialog.cpp b/MantidPlot/src/Mantid/MantidSampleMaterialDialog.cpp
index 80e54518b632b77e4b361362c709000513c37429..a063a38ef3e4f1752600d23915ee7eef377e4e04 100644
--- a/MantidPlot/src/Mantid/MantidSampleMaterialDialog.cpp
+++ b/MantidPlot/src/Mantid/MantidSampleMaterialDialog.cpp
@@ -22,26 +22,29 @@ using namespace Mantid::Kernel;
  * @param mtdUI Pointer to the MantidUI object
  * @param flags Window flags
  */
-MantidSampleMaterialDialog::MantidSampleMaterialDialog(const QString & wsName, MantidUI* mtdUI, Qt::WFlags flags):
-  QDialog(mtdUI->appWindow(), flags),
-  m_wsName(wsName),
-  m_mantidUI(mtdUI)
-{
+MantidSampleMaterialDialog::MantidSampleMaterialDialog(const QString &wsName,
+                                                       MantidUI *mtdUI,
+                                                       Qt::WFlags flags)
+    : QDialog(mtdUI->appWindow(), flags), m_wsName(wsName), m_mantidUI(mtdUI) {
   m_uiForm.setupUi(this);
 
   connect(m_uiForm.pbClose, SIGNAL(clicked()), this, SLOT(close()));
 
-  connect(m_uiForm.pbSetMaterial, SIGNAL(clicked()), this, SLOT(handleSetMaterial()));
-  connect(m_uiForm.pbCopyMaterial, SIGNAL(clicked()), this, SLOT(handleCopyMaterial()));
+  connect(m_uiForm.pbSetMaterial, SIGNAL(clicked()), this,
+          SLOT(handleSetMaterial()));
+  connect(m_uiForm.pbCopyMaterial, SIGNAL(clicked()), this,
+          SLOT(handleCopyMaterial()));
 }
 
 /**
- * Gets the sample material for a workspace and displays its properties in the tree.
+ * Gets the sample material for a workspace and displays its properties in the
+ * tree.
  */
-void MantidSampleMaterialDialog::updateMaterial()
-{
-  MatrixWorkspace_sptr ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_wsName.toStdString());
-  if(!ws)
+void MantidSampleMaterialDialog::updateMaterial() {
+  MatrixWorkspace_sptr ws =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          m_wsName.toStdString());
+  if (!ws)
     return;
 
   const Material material = ws->sample().getMaterial();
@@ -108,10 +111,10 @@ void MantidSampleMaterialDialog::updateMaterial()
 }
 
 /**
- * Creates a SetSampleMaterial dialog to set the sample material of the workspace.
+ * Creates a SetSampleMaterial dialog to set the sample material of the
+ * workspace.
  */
-void MantidSampleMaterialDialog::handleSetMaterial()
-{
+void MantidSampleMaterialDialog::handleSetMaterial() {
   QHash<QString, QString> presets;
   presets["InputWorkspace"] = m_wsName;
 
@@ -119,10 +122,10 @@ void MantidSampleMaterialDialog::handleSetMaterial()
 }
 
 /**
- * Creates a CopySample dialog with pre filled input to copy the sample material.
+ * Creates a CopySample dialog with pre filled input to copy the sample
+ * material.
  */
-void MantidSampleMaterialDialog::handleCopyMaterial()
-{
+void MantidSampleMaterialDialog::handleCopyMaterial() {
   QHash<QString, QString> presets;
   presets["InputWorkspace"] = m_wsName;
   presets["CopyName"] = "0";
@@ -136,12 +139,12 @@ void MantidSampleMaterialDialog::handleCopyMaterial()
 }
 
 /**
- * Reloads the material information when an algorithm started from the dialog finishes.
+ * Reloads the material information when an algorithm started from the dialog
+ *finishes.
  *
  * @param alg Completed algorithm (unused)
  */
-void MantidSampleMaterialDialog::finishHandle(const IAlgorithm *alg)
-{
+void MantidSampleMaterialDialog::finishHandle(const IAlgorithm *alg) {
   UNUSED_ARG(alg);
   updateMaterial();
 }
diff --git a/MantidPlot/src/Mantid/MantidSampleMaterialDialog.h b/MantidPlot/src/Mantid/MantidSampleMaterialDialog.h
index 650debcf72b8d3db9f58d4bc40ce545549e73f8d..5fa74272a504746d3ad83404f9e19e7d0e030f84 100644
--- a/MantidPlot/src/Mantid/MantidSampleMaterialDialog.h
+++ b/MantidPlot/src/Mantid/MantidSampleMaterialDialog.h
@@ -22,7 +22,8 @@ and allows it to be modified.
 @author Dan Nixon
 @date 22/10/2014
 
-Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -43,12 +44,13 @@ File change history is stored at: <https://github.com/mantidproject/mantid>
 Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MantidSampleMaterialDialog : public QDialog, Mantid::API::AlgorithmObserver
-{
+class MantidSampleMaterialDialog : public QDialog,
+                                   Mantid::API::AlgorithmObserver {
   Q_OBJECT
 
 public:
-  MantidSampleMaterialDialog(const QString & wsName, MantidUI* mtdUI, Qt::WFlags flags = 0);
+  MantidSampleMaterialDialog(const QString &wsName, MantidUI *mtdUI,
+                             Qt::WFlags flags = 0);
 
 public slots:
   void updateMaterial();
@@ -63,10 +65,9 @@ private:
   QString m_wsName;
 
   /// A pointer to the MantidUI object
-  MantidUI* m_mantidUI;
+  MantidUI *m_mantidUI;
 
   Ui::MantidSampleMaterialDialog m_uiForm;
-
 };
 
-#endif //MANTIDSAMPLEMATERIALDIALOG_H_
+#endif // MANTIDSAMPLEMATERIALDIALOG_H_
diff --git a/MantidPlot/src/Mantid/MantidTable.h b/MantidPlot/src/Mantid/MantidTable.h
index d7075481f2537316130b9d9e3aa7977cedd115c2..4f79f410741ca33d19d95609d7fe0d55b4016ca4 100644
--- a/MantidPlot/src/Mantid/MantidTable.h
+++ b/MantidPlot/src/Mantid/MantidTable.h
@@ -5,20 +5,19 @@
 #include "MantidQtAPI/WorkspaceObserver.h"
 #include "MantidAPI/ITableWorkspace_fwd.h"
 
-
 /** A MantidTable appears to be a MantidPlot "Table" object
  * that shows the data from an ITableWorkspace.
  *
  */
-class MantidTable: public Table, public MantidQt::API::WorkspaceObserver
-{
+class MantidTable : public Table, public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 public:
-  MantidTable(ScriptingEnv *env, Mantid::API::ITableWorkspace_sptr ws, const QString &label, 
-    ApplicationWindow* parent, bool transpose = false);
+  MantidTable(ScriptingEnv *env, Mantid::API::ITableWorkspace_sptr ws,
+              const QString &label, ApplicationWindow *parent,
+              bool transpose = false);
 
   /// returns the workspace name
-  const std::string & getWorkspaceName() {return m_wsName; }
+  const std::string &getWorkspaceName() { return m_wsName; }
 
   //! is this table editable
   bool isEditable() override;
@@ -64,7 +63,6 @@ private:
   const std::string m_wsName;
   /// Show the table workspace transposed
   bool m_transposed;
-
 };
 
 #endif /* MANTIDTABLE_H */
diff --git a/MantidPlot/src/Mantid/MantidUI.cpp b/MantidPlot/src/Mantid/MantidUI.cpp
index e65207b60a7eb65ddd51976b687131bc3daa77ee..732b2f299bacefb6a5d3ccb64eccfb36ea6d75ce 100644
--- a/MantidPlot/src/Mantid/MantidUI.cpp
+++ b/MantidPlot/src/Mantid/MantidUI.cpp
@@ -97,7 +97,7 @@ size_t DET_TABLE_NDETS_GROUP = 10;
 // Initialize logger
 Mantid::Kernel::Logger g_log("MantidUI");
 
-bool isOfType(const QObject* obj, const char* toCompare) {
+bool isOfType(const QObject *obj, const char *toCompare) {
   return strcmp(obj->metaObject()->className(), toCompare) == 0;
 }
 }
@@ -433,13 +433,15 @@ MantidUI::getWorkspace(const QString &workspaceName) {
 bool MantidUI::menuAboutToShow(MdiSubWindow *w) {
 
   if (w && isOfType(w, "MantidMatrix")) {
-    auto plotMenuAction = appWindow()->myMenuBar()->addMenu(appWindow()->plot3DMenu);
+    auto plotMenuAction =
+        appWindow()->myMenuBar()->addMenu(appWindow()->plot3DMenu);
     plotMenuAction->setText(tr("3D &Plot"));
     appWindow()->actionCopySelection->setEnabled(true);
     appWindow()->actionPasteSelection->setEnabled(false);
     appWindow()->actionClearSelection->setEnabled(false);
 
-    auto menuMantidMatrixAction = appWindow()->myMenuBar()->addMenu(menuMantidMatrix);
+    auto menuMantidMatrixAction =
+        appWindow()->myMenuBar()->addMenu(menuMantidMatrix);
     menuMantidMatrixAction->setText(tr("&Workspace"));
     return true;
   }
@@ -1276,10 +1278,10 @@ Table *MantidUI::createDetectorTable(
         colValues << QVariant(dataY0) << QVariant(dataE0); // data
       }
       colValues << QVariant("0") << QVariant("0") // rt
-                << QVariant("0")    // efixed
-                << QVariant("0")    // rtp
-                << QVariant("n/a"); // monitor
-    }                               // End catch for no spectrum
+                << QVariant("0")                  // efixed
+                << QVariant("0")                  // rtp
+                << QVariant("n/a");               // monitor
+    }                                             // End catch for no spectrum
   }
 
   // This modifies widgets, so it needs to run in the Qt GUI thread: no openmp
@@ -1717,8 +1719,9 @@ void MantidUI::groupWorkspaces() {
   } catch (std::invalid_argument &) {
     QMessageBox::critical(appWindow(), "MantidPlot - Algorithm error",
                           " Error in GroupWorkspaces algorithm");
-  } catch (Mantid::Kernel::Exception::NotFoundError
-               &) // if not a valid object in analysis data service
+  } catch (Mantid::Kernel::Exception::NotFoundError &) // if not a valid object
+                                                       // in analysis data
+                                                       // service
   {
     QMessageBox::critical(appWindow(), "MantidPlot - Algorithm error",
                           " Error in GroupWorkspaces algorithm");
@@ -2144,7 +2147,7 @@ void MantidUI::menuMantidMatrixAboutToShow() {
   menuMantidMatrix->addAction(actionCopyDetectorsToTable);
   menuMantidMatrix->addSeparator();
   menuMantidMatrix->addAction(tr("Set &Properties..."), w,
-                               SLOT(setMatrixProperties()));
+                              SLOT(setMatrixProperties()));
 
   ///
   menuMantidMatrix->addSeparator();
diff --git a/MantidPlot/src/Mantid/MantidUI.h b/MantidPlot/src/Mantid/MantidUI.h
index 154ca93e5f64ce6690b8624b0b3dcd72a2cfeb4d..e874804be6446837dbb37b09a5e5d7d84a252480 100644
--- a/MantidPlot/src/Mantid/MantidUI.h
+++ b/MantidPlot/src/Mantid/MantidUI.h
@@ -604,8 +604,8 @@ private:
   ApplicationWindow *m_appWindow;    // QtiPlot main ApplicationWindow
   MantidDockWidget *m_exploreMantid; // Dock window for manipulating workspaces
   AlgorithmDockWidget *m_exploreAlgorithms; // Dock window for using algorithms
-  RemoteClusterDockWidget
-      *m_exploreRemoteTasks; // Dock window for using remote tasks
+  RemoteClusterDockWidget *
+      m_exploreRemoteTasks; // Dock window for using remote tasks
   /// Current fit property browser being used
   MantidQt::MantidWidgets::FitPropertyBrowser *m_fitFunction;
   /// Default fit property browser (the one docked on the left)
@@ -646,8 +646,8 @@ private:
   // Stores dependent mdi windows. If the 'key' window closes, all 'value' ones
   // must be closed as well.
   std::unordered_multimap<MdiSubWindow *, MdiSubWindow *> m_mdiDependency;
-  QMdiSubWindow
-      *m_vatesSubWindow; ///< Holder for the Vates interface sub-window
+  QMdiSubWindow *
+      m_vatesSubWindow; ///< Holder for the Vates interface sub-window
 
   // prevents some repeated code realtating to log names
   void formatLogName(QString &label, const QString &wsName);
diff --git a/MantidPlot/src/Mantid/MantidWSIndexDialog.h b/MantidPlot/src/Mantid/MantidWSIndexDialog.h
index a323e336f33f9331a9a85d6a89744694614260e5..6a9aa8c6b7b9ce6f27ecb82dabc507fc5e10cc2f 100644
--- a/MantidPlot/src/Mantid/MantidWSIndexDialog.h
+++ b/MantidPlot/src/Mantid/MantidWSIndexDialog.h
@@ -23,31 +23,34 @@
 //----------------------------------
 class IntervalList;
 
-/** 
-    The MantidWSIndexDialog class presents users with a dialog so that they may 
+/**
+    The MantidWSIndexDialog class presents users with a dialog so that they may
     specify which workspace indices / spectra IDs are to be plotted by Mantid.
 
     They are prompted with the available range(s) of indices/IDs they can plot.
     They must enter a range(s) that is(are) enclosed within those ranges.
 
     "Ranges" are of a format you've probably seen when inputting page numbers to
-    print into a word processing program or similar, i.e. "2, 4-6" to print out 
-    pages 2, 4, 5 and 6. 
-    
+    print into a word processing program or similar, i.e. "2, 4-6" to print out
+    pages 2, 4, 5 and 6.
+
     Ranges are defined by the "Interval" and "IntervalList" classes.
 
     The IntervalListValidator class overrides QValidator, and allows Mantid
     to assertain whether a user has attempted to input a valid range or not.
-    Altering this class will affect the behaviour of what is allowed to be typed,
+    Altering this class will affect the behaviour of what is allowed to be
+   typed,
     and what inputs allow the "OK" button to be pressed.
 
-    TODO - perhaps the interval objects are useful elsewhere, in which case those
+    TODO - perhaps the interval objects are useful elsewhere, in which case
+   those
            three classes are best in thier own header and source.
 
     @author Peter G Parker, ISIS, RAL
     @date 2011/10/06
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -65,11 +68,10 @@ class IntervalList;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class Interval
-{
+class Interval {
 public:
   /// Constructor - starting and ending at single.
   explicit Interval(int single);
@@ -78,12 +80,13 @@ public:
   /// Constructor - attempts to parse given string to find start and end.
   explicit Interval(QString);
   /// Copy constructor
-  Interval(const Interval&);
+  Interval(const Interval &);
 
   /// Attempts to merge the given Interval with this Interval
-  bool merge(const Interval&);
-  /// Returns true if it is possible to merge the given Interval with this Interval, else false.
-  bool canMerge(const Interval&) const;
+  bool merge(const Interval &);
+  /// Returns true if it is possible to merge the given Interval with this
+  /// Interval, else false.
+  bool canMerge(const Interval &) const;
   /// Returns the int marking the start of this Interval
   int start() const;
   /// Returns the int marking the end of this Interval
@@ -94,8 +97,9 @@ public:
   /// Returns a set of ints that represents the interval.
   std::set<int> getIntSet() const;
 
-  /// Returns true if this interval completely contains the interval passed to it, else false.
-  bool contains(const Interval&) const;
+  /// Returns true if this interval completely contains the interval passed to
+  /// it, else false.
+  bool contains(const Interval &) const;
 
   /// Returns a string which represents the start and end of this Interval
   std::string toStdString() const;
@@ -110,8 +114,7 @@ private:
   int m_start, m_end;
 };
 
-class IntervalList
-{
+class IntervalList {
 public:
   /// Constructor - with empty list.
   IntervalList(void);
@@ -120,17 +123,18 @@ public:
   /// Constructor - with a list containing a single Interval
   explicit IntervalList(Interval);
   /// Copy Constructor
-  IntervalList(const IntervalList&);
+  IntervalList(const IntervalList &);
 
   /// Returns a reference to the list of Intervals.
-  const QList<Interval>& getList() const;
+  const QList<Interval> &getList() const;
   /// Returns the combined length of all Intervals in the list.
   int totalIntervalLength() const;
 
   /// Returns a string that represents the IntervalList, of the form
   /// "0, 2-5, 8, 10-12".  String is cut short by default to 6 intervals.
   std::string toStdString(int numOfIntervals = 6) const;
-  /// Convenience function that returns the contents of toStdString as a QString object.
+  /// Convenience function that returns the contents of toStdString as a QString
+  /// object.
   QString toQString(int numOfIntervals = 6) const;
 
   /// Add an interval starting and ending at single.
@@ -142,42 +146,48 @@ public:
   /// Attempts to parse the given string into a IntervalList to add.
   void addIntervals(QString);
   /// Adds an IntervalList to this IntervalList.
-  void addIntervalList(const IntervalList&);
-  /// Replaces the current list with the list belonging to given IntervalList object.
-  void setIntervalList(const IntervalList&);
+  void addIntervalList(const IntervalList &);
+  /// Replaces the current list with the list belonging to given IntervalList
+  /// object.
+  void setIntervalList(const IntervalList &);
 
   /// Returns a set of ints that represents the interval.
   std::set<int> getIntSet() const;
 
-  /// Returns true if this interval list completely contains the interval passed to it, else false.
-  bool contains(const Interval&) const;
-  /// Returns true if this interval list completely contains the interval list passed to it, else false.
-  bool contains(const IntervalList&) const;
-
-  /// Returns true if the QString can be parsed into an IntervalList, else false.
-  static bool isParsable(const QString&);
-  /// Returns true if the QString can be parsed into an IntervalList which can then be contained
+  /// Returns true if this interval list completely contains the interval passed
+  /// to it, else false.
+  bool contains(const Interval &) const;
+  /// Returns true if this interval list completely contains the interval list
+  /// passed to it, else false.
+  bool contains(const IntervalList &) const;
+
+  /// Returns true if the QString can be parsed into an IntervalList, else
+  /// false.
+  static bool isParsable(const QString &);
+  /// Returns true if the QString can be parsed into an IntervalList which can
+  /// then be contained
   /// in the IntervalList given, else false.
-  static bool isParsable(const QString&, const IntervalList&);
+  static bool isParsable(const QString &, const IntervalList &);
 
-  /// Returns an IntervalList which is the intersection of the given IntervalList and Interval
-  static IntervalList intersect(const IntervalList&, const Interval&);
-  /// Returns an IntervalList which is the intersection of the given IntervalLists
-  static IntervalList intersect(const IntervalList&, const IntervalList&);
+  /// Returns an IntervalList which is the intersection of the given
+  /// IntervalList and Interval
+  static IntervalList intersect(const IntervalList &, const Interval &);
+  /// Returns an IntervalList which is the intersection of the given
+  /// IntervalLists
+  static IntervalList intersect(const IntervalList &, const IntervalList &);
 
 private:
   /// A list of all the Intervals in this IntervalList
   QList<Interval> m_list;
 };
 
-class IntervalListValidator : public QValidator
-{
+class IntervalListValidator : public QValidator {
   Q_OBJECT
 
 public:
   /// Constructor - This object must know its parent QObject, as well as the
   /// IntervalList it is validating against.
-  IntervalListValidator(QObject* parent, const IntervalList& intervals);
+  IntervalListValidator(QObject *parent, const IntervalList &intervals);
 
   /// Overriden method to validate a given QString, at a particular position
   State validate(QString &, int &) const override;
@@ -331,5 +341,4 @@ private:
   QVBoxLayout *m_outer;
 };
 
-#endif //MANTIDWSINDEXDIALOG_H_
-
+#endif // MANTIDWSINDEXDIALOG_H_
diff --git a/MantidPlot/src/Mantid/PeakPickerTool.cpp b/MantidPlot/src/Mantid/PeakPickerTool.cpp
index bfd93296c20fe69fc15bd5a6df448f804af72829..64737a260548e14ce1cd8a0386fbfe4dfef620b4 100644
--- a/MantidPlot/src/Mantid/PeakPickerTool.cpp
+++ b/MantidPlot/src/Mantid/PeakPickerTool.cpp
@@ -6,7 +6,6 @@
 #include "../FunctionCurve.h"
 #include "MantidQtMantidWidgets/PropertyHandler.h"
 
-
 #include "MantidAPI/CompositeFunction.h"
 #include "MantidAPI/IPeakFunction.h"
 #include "MantidAPI/FunctionFactory.h"
@@ -22,24 +21,21 @@
 #include <QInputDialog>
 #include <QMessageBox>
 
-
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("PeakPickerTool");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("PeakPickerTool");
 }
 
-PeakPickerTool::PeakPickerTool(Graph *graph, MantidQt::MantidWidgets::FitPropertyBrowser *fitPropertyBrowser, MantidUI *mantidUI, bool showFitPropertyBrowser) :
-QwtPlotPicker(graph->plotWidget()->canvas()),
-PlotToolInterface(graph),
-m_fitPropertyBrowser(fitPropertyBrowser),
-m_mantidUI(mantidUI),
-m_wsName(),m_spec(),m_init(false),
-m_width_set(true), m_width(0), m_addingPeak(false), m_resetting(false),
-m_xMin(0.), m_xMax(0.),
-m_changingXMin(false), m_changingXMax(false),
-m_shouldBeNormalised(false)
-{
+PeakPickerTool::PeakPickerTool(
+    Graph *graph,
+    MantidQt::MantidWidgets::FitPropertyBrowser *fitPropertyBrowser,
+    MantidUI *mantidUI, bool showFitPropertyBrowser)
+    : QwtPlotPicker(graph->plotWidget()->canvas()), PlotToolInterface(graph),
+      m_fitPropertyBrowser(fitPropertyBrowser), m_mantidUI(mantidUI),
+      m_wsName(), m_spec(), m_init(false), m_width_set(true), m_width(0),
+      m_addingPeak(false), m_resetting(false), m_xMin(0.), m_xMax(0.),
+      m_changingXMin(false), m_changingXMax(false),
+      m_shouldBeNormalised(false) {
   d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
 
   addExistingFitsAndGuess(d_graph->curvesList());
@@ -61,42 +57,58 @@ m_shouldBeNormalised(false)
   m_fitPropertyBrowser->getHandler()->removeAllPlots();
   m_fitPropertyBrowser->setWorkspaceName(m_wsName);
   m_fitPropertyBrowser->setWorkspaceIndex(m_spec);
-  connect(m_fitPropertyBrowser,SIGNAL(currentChanged()),this,SLOT(currentChanged()));
-  connect(m_fitPropertyBrowser,SIGNAL(workspaceIndexChanged(int)),this,SLOT(workspaceIndexChanged(int)));
-  connect(m_fitPropertyBrowser,SIGNAL(workspaceNameChanged(const QString&)),
-                  this,SLOT(workspaceNameChanged(const QString&)));
-  connect(m_fitPropertyBrowser,SIGNAL(functionRemoved()),this,SLOT(functionRemoved()));
-  connect(m_fitPropertyBrowser,SIGNAL(functionCleared()),this,SLOT(functionCleared()));
-  connect(m_fitPropertyBrowser,SIGNAL(algorithmFinished(const QString&)),
-                  this,SLOT(algorithmFinished(const QString&)));
-  connect(m_fitPropertyBrowser,SIGNAL(startXChanged(double)),this,SLOT(startXChanged(double)));
-  connect(m_fitPropertyBrowser,SIGNAL(endXChanged(double)),this,SLOT(endXChanged(double)));
-  connect(m_fitPropertyBrowser,SIGNAL(parameterChanged(const Mantid::API::IFunction*)),
-                  this,SLOT(parameterChanged(const Mantid::API::IFunction*)));
-  connect(m_fitPropertyBrowser,SIGNAL(plotGuess()),this,SLOT(plotGuess()));
-  connect(m_fitPropertyBrowser,SIGNAL(plotCurrentGuess()),this,SLOT(plotCurrentGuess()));
-  connect(m_fitPropertyBrowser,SIGNAL(removeGuess()),this,SLOT(removeGuess()));
-  connect(m_fitPropertyBrowser,SIGNAL(removeCurrentGuess()),this,SLOT(removeCurrentGuess()));
-  connect(m_fitPropertyBrowser,SIGNAL(removePlotSignal(MantidQt::MantidWidgets::PropertyHandler*)),
-          this,SLOT(removePlot(MantidQt::MantidWidgets::PropertyHandler*)));
-  connect(m_fitPropertyBrowser,SIGNAL(removeFitCurves()),this,SLOT(removeFitCurves()));
+  connect(m_fitPropertyBrowser, SIGNAL(currentChanged()), this,
+          SLOT(currentChanged()));
+  connect(m_fitPropertyBrowser, SIGNAL(workspaceIndexChanged(int)), this,
+          SLOT(workspaceIndexChanged(int)));
+  connect(m_fitPropertyBrowser, SIGNAL(workspaceNameChanged(const QString &)),
+          this, SLOT(workspaceNameChanged(const QString &)));
+  connect(m_fitPropertyBrowser, SIGNAL(functionRemoved()), this,
+          SLOT(functionRemoved()));
+  connect(m_fitPropertyBrowser, SIGNAL(functionCleared()), this,
+          SLOT(functionCleared()));
+  connect(m_fitPropertyBrowser, SIGNAL(algorithmFinished(const QString &)),
+          this, SLOT(algorithmFinished(const QString &)));
+  connect(m_fitPropertyBrowser, SIGNAL(startXChanged(double)), this,
+          SLOT(startXChanged(double)));
+  connect(m_fitPropertyBrowser, SIGNAL(endXChanged(double)), this,
+          SLOT(endXChanged(double)));
+  connect(m_fitPropertyBrowser,
+          SIGNAL(parameterChanged(const Mantid::API::IFunction *)), this,
+          SLOT(parameterChanged(const Mantid::API::IFunction *)));
+  connect(m_fitPropertyBrowser, SIGNAL(plotGuess()), this, SLOT(plotGuess()));
+  connect(m_fitPropertyBrowser, SIGNAL(plotCurrentGuess()), this,
+          SLOT(plotCurrentGuess()));
+  connect(m_fitPropertyBrowser, SIGNAL(removeGuess()), this,
+          SLOT(removeGuess()));
+  connect(m_fitPropertyBrowser, SIGNAL(removeCurrentGuess()), this,
+          SLOT(removeCurrentGuess()));
+  connect(m_fitPropertyBrowser,
+          SIGNAL(removePlotSignal(MantidQt::MantidWidgets::PropertyHandler *)),
+          this, SLOT(removePlot(MantidQt::MantidWidgets::PropertyHandler *)));
+  connect(m_fitPropertyBrowser, SIGNAL(removeFitCurves()), this,
+          SLOT(removeFitCurves()));
 
   // When fit browser destroyed, disable oneself in the parent graph
-  connect(m_fitPropertyBrowser, SIGNAL(destroyed()), graph, SLOT(disableTools()));
-
-  //Show the fitPropertyBrowser if it isn't already.
-  if (showFitPropertyBrowser) m_fitPropertyBrowser->show();
-  connect(this,SIGNAL(isOn(bool)),m_fitPropertyBrowser,SLOT(setPeakToolOn(bool)));
+  connect(m_fitPropertyBrowser, SIGNAL(destroyed()), graph,
+          SLOT(disableTools()));
+
+  // Show the fitPropertyBrowser if it isn't already.
+  if (showFitPropertyBrowser)
+    m_fitPropertyBrowser->show();
+  connect(this, SIGNAL(isOn(bool)), m_fitPropertyBrowser,
+          SLOT(setPeakToolOn(bool)));
   emit isOn(true);
 
   auto cf = m_fitPropertyBrowser->compositeFunction();
-  if (m_fitPropertyBrowser->count() == 0 || (m_fitPropertyBrowser->count() == 1 && m_fitPropertyBrowser->isAutoBack()))
-  {
+  if (m_fitPropertyBrowser->count() == 0 ||
+      (m_fitPropertyBrowser->count() == 1 &&
+       m_fitPropertyBrowser->isAutoBack())) {
     m_init = true;
 
     QwtScaleMap xMap = d_graph->plotWidget()->canvasMap(QwtPlot::xBottom);
     double s1 = xMap.s1(), s2 = xMap.s2();
-    double ds = fabs(s2-s1)*0.05; 
+    double ds = fabs(s2 - s1) * 0.05;
     xMin(s1 + ds);
     xMax(s2 - ds);
 
@@ -104,52 +116,43 @@ m_shouldBeNormalised(false)
     m_changingXMax = false;
     m_fitPropertyBrowser->setStartX(xMin());
     m_fitPropertyBrowser->setEndX(xMax());
-    if (m_fitPropertyBrowser->isAutoBack())
-    {
+    if (m_fitPropertyBrowser->isAutoBack()) {
       m_fitPropertyBrowser->addAutoBackground();
     }
-  }
-  else
-  {
+  } else {
     m_init = true;
     xMin(m_fitPropertyBrowser->startX());
     xMax(m_fitPropertyBrowser->endX());
     m_changingXMin = false;
     m_changingXMax = false;
-    for(size_t i=0;i<cf->nFunctions();i++)
-    {
-      auto pf = dynamic_cast<Mantid::API::IPeakFunction*>(cf->getFunction(i).get());
-      if (pf)
-      {
+    for (size_t i = 0; i < cf->nFunctions(); i++) {
+      auto pf =
+          dynamic_cast<Mantid::API::IPeakFunction *>(cf->getFunction(i).get());
+      if (pf) {
         m_width = pf->fwhm();
-        if (m_width != 0.) break;
+        if (m_width != 0.)
+          break;
       }
     }
   }
   attach(d_graph->plotWidget());
   d_graph->plotWidget()->replot();
 
-  connect(d_graph,SIGNAL(curveRemoved()),this,SLOT(curveRemoved()));
-  connect(d_graph,SIGNAL(modifiedGraph()),this,SLOT(modifiedGraph()));
+  connect(d_graph, SIGNAL(curveRemoved()), this, SLOT(curveRemoved()));
+  connect(d_graph, SIGNAL(modifiedGraph()), this, SLOT(modifiedGraph()));
 
-  try
-  {// if it's a MatrixWorkspace in the ADS
+  try { // if it's a MatrixWorkspace in the ADS
     m_ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(
-        m_wsName.toStdString()
-      ));
-  }
-  catch(...)
-  {// or it can be a TableWorkspace
+        Mantid::API::AnalysisDataService::Instance().retrieve(
+            m_wsName.toStdString()));
+  } catch (...) { // or it can be a TableWorkspace
     m_ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-      m_fitPropertyBrowser->createMatrixFromTableWorkspace()
-    );
+        m_fitPropertyBrowser->createMatrixFromTableWorkspace());
   }
 }
 
-PeakPickerTool::~PeakPickerTool()
-{
-  disconnect(d_graph,SIGNAL(curveRemoved()),this,SLOT(curveRemoved()));
+PeakPickerTool::~PeakPickerTool() {
+  disconnect(d_graph, SIGNAL(curveRemoved()), this, SLOT(curveRemoved()));
   detach();
   d_graph->plotWidget()->canvas()->unsetCursor();
   d_graph->plotWidget()->replot();
@@ -157,320 +160,287 @@ PeakPickerTool::~PeakPickerTool()
 }
 
 /**
-Event filter. Returning true means event processed, false let it go 
+Event filter. Returning true means event processed, false let it go
 down the processing chain.
 */
-bool PeakPickerTool::eventFilter(QObject *obj, QEvent *event)
-{
-  //std::cerr<<"event "<<event->type()<<'\n';
-  switch(event->type()) {
-    case QEvent::MouseButtonDblClick:  
-      {
-        QPoint p = ((QMouseEvent*)event)->pos();
-        double x = d_graph->plotWidget()->invTransform(2,p.x());
-        double x1 = d_graph->plotWidget()->invTransform(2,p.x()+3);
-        double dx = fabs(x-x1);
-        if (clickedOnXMin(x,dx) || clickedOnXMax(x,dx))
-        {
-          xMin(x-dx);
-          xMax(x+dx);
-          d_graph->plotWidget()->replot();
-        }
-        return true;
+bool PeakPickerTool::eventFilter(QObject *obj, QEvent *event) {
+  // std::cerr<<"event "<<event->type()<<'\n';
+  switch (event->type()) {
+  case QEvent::MouseButtonDblClick: {
+    QPoint p = ((QMouseEvent *)event)->pos();
+    double x = d_graph->plotWidget()->invTransform(2, p.x());
+    double x1 = d_graph->plotWidget()->invTransform(2, p.x() + 3);
+    double dx = fabs(x - x1);
+    if (clickedOnXMin(x, dx) || clickedOnXMax(x, dx)) {
+      xMin(x - dx);
+      xMax(x + dx);
+      d_graph->plotWidget()->replot();
+    }
+    return true;
+  }
+
+  case QEvent::MouseMove: {
+    QPoint pnt = ((QMouseEvent *)event)->pos();
+    if (!isWidthSet()) {
+      double c = centre();
+      double w = d_graph->plotWidget()->invTransform(2, pnt.x()) - c;
+      setWidth(2 * fabs(w));
+      m_fitPropertyBrowser->updateParameters();
+      emit peakChanged();
+    } else if (resetting()) {
+      double c = d_graph->plotWidget()->invTransform(2, pnt.x());
+      int yAxis = QwtPlot::yLeft;
+      double h = d_graph->plotWidget()->invTransform(yAxis, pnt.y());
+      setPeak(c, h);
+      m_fitPropertyBrowser->updateParameters();
+      emit peakChanged();
+    } else if (changingXMin() &&
+               changingXMax()) { // modify xMin and xMax at the same time
+      setToolTip("");
+      double x = d_graph->plotWidget()->invTransform(2, pnt.x());
+      double x0 = (xMin() + xMax()) / 2;
+      double xmin, xmax;
+      if (x >= x0) {
+        xmax = x;
+        xmin = x0 * 2 - x;
+      } else {
+        xmax = x0 * 2 - x;
+        xmin = x;
       }
+      xMin(xmin);
+      xMax(xmax);
+      m_fitPropertyBrowser->setStartX(xMin());
+      m_fitPropertyBrowser->setEndX(xMax());
+    } else if (changingXMin()) {
+      double x = d_graph->plotWidget()->invTransform(2, pnt.x());
+      xMin(x);
+      m_fitPropertyBrowser->setStartX(xMin());
+    } else if (changingXMax()) {
+      double x = d_graph->plotWidget()->invTransform(2, pnt.x());
+      xMax(x);
+      m_fitPropertyBrowser->setEndX(xMax());
+    }
+    d_graph->plotWidget()->replot();
+    //}
+    break;
+  }
 
-    case QEvent::MouseMove:
+  case QEvent::MouseButtonPress: {
+    Qt::KeyboardModifiers mod = ((QMouseEvent *)event)->modifiers();
+    QPoint p = ((QMouseEvent *)event)->pos();
+    if (((QMouseEvent *)event)->button() == Qt::LeftButton) {
+      if (!m_init) { // Create the marker
+        m_init = true;
+        attach(d_graph->plotWidget());
+        double x = d_graph->plotWidget()->invTransform(2, p.x());
+        // when PeakRangeMarker is created chngingxMin() and changingXMax are
+        // both true
+        xMin(x);
+        xMax(x);
+        m_fitPropertyBrowser->setStartX(xMin());
+        m_fitPropertyBrowser->setEndX(xMax());
+        d_graph->plotWidget()->replot();
+      } else if (m_addingPeak) {
+        addPeakAt(p.x(), p.y());
+        m_addingPeak = false;
+        d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
+        setToolTip("");
+      } else if (mod.testFlag(Qt::ShiftModifier)) // Shift button was pressed
       {
-        QPoint pnt = ((QMouseEvent*)event)->pos();
-        if (!isWidthSet())
-        {
-          double c = centre();
-          double w = d_graph->plotWidget()->invTransform(2,pnt.x()) - c;
-          setWidth(2*fabs(w));
-          m_fitPropertyBrowser->updateParameters();
-          emit peakChanged();
-        }
-        else if (resetting())
-        {
-          double c = d_graph->plotWidget()->invTransform(2,pnt.x());
-          int yAxis = QwtPlot::yLeft;
-          double h = d_graph->plotWidget()->invTransform(yAxis,pnt.y());
-          setPeak(c,h);
-          m_fitPropertyBrowser->updateParameters();
-          emit peakChanged();
-        }
-        else if (changingXMin() && changingXMax())
-        {// modify xMin and xMax at the same time 
-          setToolTip("");
-          double x = d_graph->plotWidget()->invTransform(2,pnt.x());
-          double x0 = (xMin() + xMax())/2;
-          double xmin,xmax;
-          if (x >= x0)
-          {
-            xmax = x;
-            xmin = x0*2-x;
-          }
-          else
-          {
-            xmax = x0*2-x;
-            xmin = x;
-          }
-          xMin(xmin);
-          xMax(xmax);
-          m_fitPropertyBrowser->setStartX(xMin());
-          m_fitPropertyBrowser->setEndX(xMax());
-        }
-        else if (changingXMin())
-        {
-          double x = d_graph->plotWidget()->invTransform(2,pnt.x());
-          xMin(x);
+        // Add a new peak
+        addPeakAt(p.x(), p.y());
+      } else // No shift button
+      {
+        widthIsSet();
+        double x = d_graph->plotWidget()->invTransform(2, p.x());
+        double x1 = d_graph->plotWidget()->invTransform(2, p.x() + 3);
+        MantidQt::MantidWidgets::PropertyHandler *handler =
+            clickedOnCentreMarker(x, fabs(x1 - x));
+        if (clickedOnXMax(x, fabs(x1 - x))) { // begin changing xMax
+          changingXMax(true);
+          d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
+          d_graph->plotWidget()->replot();
           m_fitPropertyBrowser->setStartX(xMin());
         }
-        else if (changingXMax())
-        {
-          double x = d_graph->plotWidget()->invTransform(2,pnt.x());
-          xMax(x);
+        if (clickedOnXMin(x, fabs(x1 - x))) { // begin changing xMin
+          changingXMin(true);
+          d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
+          d_graph->plotWidget()->replot();
           m_fitPropertyBrowser->setEndX(xMax());
         }
-        d_graph->plotWidget()->replot();
-        //}
-        break;
-      }
-
-    case QEvent::MouseButtonPress:
-      {
-        Qt::KeyboardModifiers mod = ((QMouseEvent*)event)->modifiers();
-        QPoint p = ((QMouseEvent*)event)->pos();
-        if (((QMouseEvent*)event)->button() == Qt::LeftButton )
-        {
-          if ( ! m_init )
-          {// Create the marker
-            m_init = true;
-            attach(d_graph->plotWidget());
-            double x = d_graph->plotWidget()->invTransform(2,p.x());
-            // when PeakRangeMarker is created chngingxMin() and changingXMax are both true
-            xMin(x);
-            xMax(x);
-            m_fitPropertyBrowser->setStartX(xMin());
-            m_fitPropertyBrowser->setEndX(xMax());
-            d_graph->plotWidget()->replot();
-          }
-          else if (m_addingPeak)
-          {
-            addPeakAt(p.x(),p.y());
-            m_addingPeak = false;
-            d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
-            setToolTip("");
-          }
-          else if ( mod.testFlag(Qt::ShiftModifier) )// Shift button was pressed
-          {
-            // Add a new peak
-            addPeakAt(p.x(),p.y());
-          }
-          else // No shift button
-          {
-            widthIsSet();
-            double x = d_graph->plotWidget()->invTransform(2,p.x());
-            double x1 = d_graph->plotWidget()->invTransform(2,p.x()+3);
-            MantidQt::MantidWidgets::PropertyHandler* handler = clickedOnCentreMarker(x,fabs(x1-x));
-            if (clickedOnXMax(x,fabs(x1-x)))
-            {// begin changing xMax
-              changingXMax(true);
-              d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
-              d_graph->plotWidget()->replot();
-              m_fitPropertyBrowser->setStartX(xMin());
-            }
-            if (clickedOnXMin(x,fabs(x1-x)))
-            {// begin changing xMin
-              changingXMin(true);
-              d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
-              d_graph->plotWidget()->replot();
-              m_fitPropertyBrowser->setEndX(xMax());
-            }
-            if (clickedOnWidthMarker(x,fabs(x1-x)))
-            {// begin changing width
-              widthIsSet(false);
-              d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
-              d_graph->plotWidget()->replot();
-              emit peakChanged();
-            }
-            else if (handler)
-            {// select current, begin changing centre and height
-              m_fitPropertyBrowser->setCurrentFunction(handler);
-              d_graph->plotWidget()->replot();
-              resetting(true);
-              emit peakChanged();
-            }
-          }
+        if (clickedOnWidthMarker(x, fabs(x1 - x))) { // begin changing width
+          widthIsSet(false);
+          d_graph->plotWidget()->canvas()->setCursor(Qt::SizeHorCursor);
+          d_graph->plotWidget()->replot();
+          emit peakChanged();
+        } else if (handler) { // select current, begin changing centre and
+                              // height
+          m_fitPropertyBrowser->setCurrentFunction(handler);
+          d_graph->plotWidget()->replot();
+          resetting(true);
+          emit peakChanged();
         }
-        return true;
       }
+    }
+    return true;
+  }
 
-      // Mouse button up - stop all changes
-    case QEvent::MouseButtonRelease:
-      d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
-      widthIsSet();
-      if ((m_changingXMin || m_changingXMax) && m_fitPropertyBrowser->isAutoBack())
-      {
-        m_fitPropertyBrowser->refitAutoBackground();
-      }
-      resetting(false);
-      changingXMin(false);
-      changingXMax(false);
-      m_addingPeak = false;
-      m_fitPropertyBrowser->setStartX(xMin());
-      m_fitPropertyBrowser->setEndX(xMax());
-      //if (current() >= 0 && m_width == 0.)
-      //{
-      //  setToolTip("Click and drag the red line to set the peak width");
-      //}
-      break;
-
-    case QEvent::KeyPress:
-      break;
-    case QEvent::KeyRelease:
-      break;
-    default:
-      break;
+  // Mouse button up - stop all changes
+  case QEvent::MouseButtonRelease:
+    d_graph->plotWidget()->canvas()->setCursor(Qt::pointingHandCursor);
+    widthIsSet();
+    if ((m_changingXMin || m_changingXMax) &&
+        m_fitPropertyBrowser->isAutoBack()) {
+      m_fitPropertyBrowser->refitAutoBackground();
+    }
+    resetting(false);
+    changingXMin(false);
+    changingXMax(false);
+    m_addingPeak = false;
+    m_fitPropertyBrowser->setStartX(xMin());
+    m_fitPropertyBrowser->setEndX(xMax());
+    // if (current() >= 0 && m_width == 0.)
+    //{
+    //  setToolTip("Click and drag the red line to set the peak width");
+    //}
+    break;
+
+  case QEvent::KeyPress:
+    break;
+  case QEvent::KeyRelease:
+    break;
+  default:
+    break;
   }
   return QwtPlotPicker::eventFilter(obj, event);
 }
 
-void PeakPickerTool::windowStateChanged( Qt::WindowStates, Qt::WindowStates newState )
-{
-  (void) newState;
-}
-
-void PeakPickerTool::functionCleared()
-{
-  d_graph->plotWidget()->replot();
+void PeakPickerTool::windowStateChanged(Qt::WindowStates,
+                                        Qt::WindowStates newState) {
+  (void)newState;
 }
 
-void PeakPickerTool::draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const
-{
-  try
-  {
-    MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->getHandler();
-    if ( !h ) return;
-    QList<MantidQt::MantidWidgets::PropertyHandler*> peaks = h->getPeakList();
-    foreach(MantidQt::MantidWidgets::PropertyHandler* peak,peaks)
-    {
+void PeakPickerTool::functionCleared() { d_graph->plotWidget()->replot(); }
+
+void PeakPickerTool::draw(QPainter *p, const QwtScaleMap &xMap,
+                          const QwtScaleMap &yMap, const QRect &) const {
+  try {
+    MantidQt::MantidWidgets::PropertyHandler *h =
+        m_fitPropertyBrowser->getHandler();
+    if (!h)
+      return;
+    QList<MantidQt::MantidWidgets::PropertyHandler *> peaks = h->getPeakList();
+    foreach (MantidQt::MantidWidgets::PropertyHandler *peak, peaks) {
       double c = peak->centre();
-      if (c >= xMap.s1() && c <= xMap.s2())
-      {
+      if (c >= xMap.s1() && c <= xMap.s2()) {
         int ic = xMap.transform(c);
-        if (peak == m_fitPropertyBrowser->currentHandler())
-        {// draw current peak
+        if (peak ==
+            m_fitPropertyBrowser->currentHandler()) { // draw current peak
           double width = peak->fwhm();
           QPen pen;
-          pen.setColor(QColor(255,0,0));
+          pen.setColor(QColor(255, 0, 0));
           pen.setStyle(Qt::DashLine);
           p->setPen(pen);
-          int x1 = xMap.transform(c - width/2);
-          int x2 = xMap.transform(c + width/2);
-          QwtPainter::drawLine(p, x1, int(yMap.p1()), x1,int(yMap.p2()));
-          QwtPainter::drawLine(p, x2, int(yMap.p1()), x2,int(yMap.p2()));
+          int x1 = xMap.transform(c - width / 2);
+          int x2 = xMap.transform(c + width / 2);
+          QwtPainter::drawLine(p, x1, int(yMap.p1()), x1, int(yMap.p2()));
+          QwtPainter::drawLine(p, x2, int(yMap.p1()), x2, int(yMap.p2()));
 
           pen.setStyle(Qt::SolidLine);
           p->setPen(pen);
-          int ih = yMap.transform(peak->height()+peak->base());
+          int ih = yMap.transform(peak->height() + peak->base());
           int ib = yMap.transform(peak->base());
           QwtPainter::drawLine(p, ic, ib, ic, ih);
           QwtPainter::drawLine(p, x1, ib, x2, ib);
-        }
-        else
-        {
-          p->setPen(QPen(QColor(200,200,200)));
+        } else {
+          p->setPen(QPen(QColor(200, 200, 200)));
           QwtPainter::drawLine(p, ic, int(yMap.p1()), ic, int(yMap.p2()));
         }
       }
     }
-  }
-  catch(...)
-  {
+  } catch (...) {
     // Do nothing
   }
   QPen pen;
-  pen.setColor(QColor(0,0,255));
+  pen.setColor(QColor(0, 0, 255));
   pen.setStyle(Qt::DashLine);
   p->setPen(pen);
   int x1 = xMap.transform(xMin());
   int x2 = xMap.transform(xMax());
-  QwtPainter::drawLine(p, x1, int(yMap.p1()), x1,int(yMap.p2()));
-  QwtPainter::drawLine(p, x2, int(yMap.p1()), x2,int(yMap.p2()));
+  QwtPainter::drawLine(p, x1, int(yMap.p1()), x1, int(yMap.p2()));
+  QwtPainter::drawLine(p, x2, int(yMap.p1()), x2, int(yMap.p2()));
 
-  pen.setColor(QColor(0,0,255));
+  pen.setColor(QColor(0, 0, 255));
   pen.setStyle(Qt::SolidLine);
   p->setPen(pen);
-  QwtPainter::drawLine(p, x1, int(yMap.p1()), x1+3,int(yMap.p1()));
-  QwtPainter::drawLine(p, x1, int(yMap.p2()), x1+3,int(yMap.p2()));
-
-  QwtPainter::drawLine(p, x2, int(yMap.p1()), x2-3,int(yMap.p1()));
-  QwtPainter::drawLine(p, x2, int(yMap.p2()), x2-3,int(yMap.p2()));
+  QwtPainter::drawLine(p, x1, int(yMap.p1()), x1 + 3, int(yMap.p1()));
+  QwtPainter::drawLine(p, x1, int(yMap.p2()), x1 + 3, int(yMap.p2()));
 
+  QwtPainter::drawLine(p, x2, int(yMap.p1()), x2 - 3, int(yMap.p1()));
+  QwtPainter::drawLine(p, x2, int(yMap.p2()), x2 - 3, int(yMap.p2()));
 }
 
-// Add a new peak with centre c and height h. 
-void PeakPickerTool::addPeak(double c,double h)
-{
+// Add a new peak with centre c and height h.
+void PeakPickerTool::addPeak(double c, double h) {
   std::string fnName = m_fitPropertyBrowser->defaultPeakType();
-  MantidQt::MantidWidgets::PropertyHandler* handler = m_fitPropertyBrowser->addFunction(fnName);
-  if (!handler || !handler->pfun()) return;
+  MantidQt::MantidWidgets::PropertyHandler *handler =
+      m_fitPropertyBrowser->addFunction(fnName);
+  if (!handler || !handler->pfun())
+    return;
   handler->setCentre(c);
-  //if previous width was set use that
-  if (handler->fwhm() == 0 && m_width != 0.0)
-  {
+  // if previous width was set use that
+  if (handler->fwhm() == 0 && m_width != 0.0) {
     handler->setFwhm(m_width);
   }
   handler->calcBase();
   // if no width still try to estimate
-  if (handler->fwhm() == 0.)
-  {
+  if (handler->fwhm() == 0.) {
     double w = handler->EstimateFwhm();
     if (w > 0) {
       handler->setFwhm(w);
     }
   }
   handler->setHeight(h);
-
 }
 
 // Give new centre and height to the current peak
-void PeakPickerTool::setPeak(double c,double h)
-{
-  MantidQt::MantidWidgets::PropertyHandler* handler = m_fitPropertyBrowser->currentHandler();
-  if ( ! handler ) return;
+void PeakPickerTool::setPeak(double c, double h) {
+  MantidQt::MantidWidgets::PropertyHandler *handler =
+      m_fitPropertyBrowser->currentHandler();
+  if (!handler)
+    return;
   handler->setCentre(c);
   handler->calcBase();
   handler->setHeight(h);
 }
 
 // Return the centre of the currently selected peak
-double PeakPickerTool::centre()const
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  return h? h->centre(): 0;
+double PeakPickerTool::centre() const {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  return h ? h->centre() : 0;
 }
 
 // Return the width of the currently selected peak
-double PeakPickerTool::width()const
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  return h? h->fwhm(): 0;
+double PeakPickerTool::width() const {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  return h ? h->fwhm() : 0;
 }
 
 // Return the height of the currently selected peak
-double PeakPickerTool::height()const
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  return h? h->fwhm(): 0;
+double PeakPickerTool::height() const {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  return h ? h->fwhm() : 0;
 }
 
 // Change the width of the currently selected peak
-void PeakPickerTool::setWidth(double x)
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  if (!h || !h->pfun()) return;
+void PeakPickerTool::setWidth(double x) {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  if (!h || !h->pfun())
+    return;
   m_width = x;
   h->setFwhm(x);
   double height = h->height() + h->base();
@@ -480,37 +450,36 @@ void PeakPickerTool::setWidth(double x)
 }
 
 // Check if x is near the xMin marker (+-dx)
-bool PeakPickerTool::clickedOnXMin(double x,double dx)
-{
+bool PeakPickerTool::clickedOnXMin(double x, double dx) {
   double c = xMin();
   return (fabs(x - c) <= dx);
 }
 
 // Check if x is near the xMax marker (+-dx)
-bool PeakPickerTool::clickedOnXMax(double x,double dx)
-{
+bool PeakPickerTool::clickedOnXMax(double x, double dx) {
   double c = xMax();
   return (fabs(x - c) <= dx);
 }
 
 // Check if x is near a width marker (+-dx)
-bool PeakPickerTool::clickedOnWidthMarker(double x,double dx)
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  if (!h) return false;
+bool PeakPickerTool::clickedOnWidthMarker(double x, double dx) {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  if (!h)
+    return false;
   double c = h->centre();
-  double w = h->fwhm()/2;
+  double w = h->fwhm() / 2;
   return (fabs(x - c - w) <= dx) || (fabs(x - c + w) <= dx);
 }
 
-// Check if x is near a peak centre marker (+-dx). If true returns the peak's address or 0 otherwise.
-MantidQt::MantidWidgets::PropertyHandler* PeakPickerTool::clickedOnCentreMarker(double x,double dx)const
-{
-  QList<MantidQt::MantidWidgets::PropertyHandler*> peaks = m_fitPropertyBrowser->getHandler()->getPeakList();
-  foreach(MantidQt::MantidWidgets::PropertyHandler* peak,peaks)
-  {
-    if (fabs(x - peak->centre()) <= dx)
-    {
+// Check if x is near a peak centre marker (+-dx). If true returns the peak's
+// address or 0 otherwise.
+MantidQt::MantidWidgets::PropertyHandler *
+PeakPickerTool::clickedOnCentreMarker(double x, double dx) const {
+  QList<MantidQt::MantidWidgets::PropertyHandler *> peaks =
+      m_fitPropertyBrowser->getHandler()->getPeakList();
+  foreach (MantidQt::MantidWidgets::PropertyHandler *peak, peaks) {
+    if (fabs(x - peak->centre()) <= dx) {
       return peak;
     }
   }
@@ -518,21 +487,17 @@ MantidQt::MantidWidgets::PropertyHandler* PeakPickerTool::clickedOnCentreMarker(
 }
 
 // Lower fit boundary
-void PeakPickerTool::xMin(double x)
-{
+void PeakPickerTool::xMin(double x) {
   m_xMin = x;
-  if (x > m_xMax) 
-  {
+  if (x > m_xMax) {
     m_xMax = x;
   }
 }
 
 // Upper fit boundary
-void PeakPickerTool::xMax(double x) 
-{
+void PeakPickerTool::xMax(double x) {
   m_xMax = x;
-  if (x < m_xMin)
-  {
+  if (x < m_xMin) {
     m_xMin = x;
   }
 }
@@ -540,58 +505,56 @@ void PeakPickerTool::xMax(double x)
 /**
  * Slot. Reacts on the index change in the Fit Browser.
  */
-void PeakPickerTool::currentChanged()
-{
-  d_graph->plotWidget()->replot();
-}
+void PeakPickerTool::currentChanged() { d_graph->plotWidget()->replot(); }
 
 /**
  * Slot. Reacts on the function deletion in the Fit Browser.
  */
-void PeakPickerTool::functionRemoved()
-{
-  d_graph->plotWidget()->replot();
-}
+void PeakPickerTool::functionRemoved() { d_graph->plotWidget()->replot(); }
 
 /**
- * Slot. Called when the Fit algorithm finishes. 
+ * Slot. Called when the Fit algorithm finishes.
  * @param out :: The name of the output workspace with the results of the fit.
  */
-void PeakPickerTool::algorithmFinished(const QString& out)
-{
+void PeakPickerTool::algorithmFinished(const QString &out) {
   // Remove old curves first, unless this is muon data
   // (muon scientists want to keep old fits until cleared manually)
   if (!isMuonData()) {
     removeFitCurves();
   }
 
-  // If style needs to be changed from default, signal pair second will be true and change to line.
-  auto * curve = new MantidMatrixCurve("",out,graph(),1,MantidMatrixCurve::Spectrum, false, m_shouldBeNormalised, Graph::Line);
+  // If style needs to be changed from default, signal pair second will be true
+  // and change to line.
+  auto *curve =
+      new MantidMatrixCurve("", out, graph(), 1, MantidMatrixCurve::Spectrum,
+                            false, m_shouldBeNormalised, Graph::Line);
   m_curveNames.append(curve->title().text());
-  if (m_fitPropertyBrowser->plotDiff())
-  {
-    curve = new MantidMatrixCurve("",out,graph(),2,MantidMatrixCurve::Spectrum,false,m_shouldBeNormalised);
+  if (m_fitPropertyBrowser->plotDiff()) {
+    curve =
+        new MantidMatrixCurve("", out, graph(), 2, MantidMatrixCurve::Spectrum,
+                              false, m_shouldBeNormalised);
     m_curveNames.append(curve->title().text());
   }
-  if(m_fitPropertyBrowser->plotCompositeMembers())
-  {
+  if (m_fitPropertyBrowser->plotCompositeMembers()) {
     using namespace Mantid::API;
-    try
-    {
-      auto wkspace = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(out.toStdString());
+    try {
+      auto wkspace =
+          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+              out.toStdString());
       const size_t nhist = wkspace->getNumberHistograms();
-      for(size_t i = 3; i < nhist; ++i) // first 3 are data,sum,diff
+      for (size_t i = 3; i < nhist; ++i) // first 3 are data,sum,diff
       {
-        curve = new MantidMatrixCurve("",out,graph(),static_cast<int>(i),MantidMatrixCurve::Spectrum,false,m_shouldBeNormalised);
+        curve = new MantidMatrixCurve("", out, graph(), static_cast<int>(i),
+                                      MantidMatrixCurve::Spectrum, false,
+                                      m_shouldBeNormalised);
         m_curveNames.append(curve->title().text());
       }
-    }
-    catch(Mantid::Kernel::Exception::NotFoundError&)
-    {
-      g_log.warning() << "PeakPicker cannot find output workspace '" + out.toStdString() + "'" << std::endl;
+    } catch (Mantid::Kernel::Exception::NotFoundError &) {
+      g_log.warning() << "PeakPicker cannot find output workspace '" +
+                             out.toStdString() + "'" << std::endl;
     }
   }
-  
+
   graph()->replot();
 }
 
@@ -599,10 +562,8 @@ void PeakPickerTool::algorithmFinished(const QString& out)
  * Slot. Called when the workspace index is changed in the FitBrowser
  * @param i :: The new workspace index.
  */
-void PeakPickerTool::workspaceIndexChanged(int i)
-{
-  if (i != m_spec)
-  {
+void PeakPickerTool::workspaceIndexChanged(int i) {
+  if (i != m_spec) {
     m_fitPropertyBrowser->setWorkspaceIndex(m_spec);
   }
 }
@@ -613,16 +574,14 @@ void PeakPickerTool::workspaceIndexChanged(int i)
   * the workspace group containing m_wsName
   * @param wsName :: The new workspace name.
   */
-void PeakPickerTool::workspaceNameChanged(const QString& wsName)
-{
-  if (wsName != m_wsName)
-  {
+void PeakPickerTool::workspaceNameChanged(const QString &wsName) {
+  if (wsName != m_wsName) {
     Mantid::API::Workspace_sptr ws;
- 
-    if (Mantid::API::AnalysisDataService::Instance().doesExist(wsName.toStdString()))
-    {
-       m_wsName = wsName;
-       m_fitPropertyBrowser->setWorkspaceName(m_wsName);
+
+    if (Mantid::API::AnalysisDataService::Instance().doesExist(
+            wsName.toStdString())) {
+      m_wsName = wsName;
+      m_fitPropertyBrowser->setWorkspaceName(m_wsName);
     }
   }
 }
@@ -631,8 +590,7 @@ void PeakPickerTool::workspaceNameChanged(const QString& wsName)
  * Slot. Called when the startX changed in the FitBrowser
  * @param sX :: The new startX
  */
-void PeakPickerTool::startXChanged(double sX)
-{
+void PeakPickerTool::startXChanged(double sX) {
   xMin(sX);
   graph()->replot();
 }
@@ -641,8 +599,7 @@ void PeakPickerTool::startXChanged(double sX)
  * Slot. Called when the endX changed in the FitBrowser
  * @param eX :: The new endX
  */
-void PeakPickerTool::endXChanged(double eX)
-{
+void PeakPickerTool::endXChanged(double eX) {
   xMax(eX);
   graph()->replot();
 }
@@ -651,117 +608,102 @@ void PeakPickerTool::endXChanged(double eX)
  * Slot. Called in response to parameterChanged signal from FitBrowser
  * @param f :: The pointer to the function with the changed parameter
  */
-void PeakPickerTool::parameterChanged(const Mantid::API::IFunction* f)
-{
-  MantidQt::MantidWidgets::PropertyHandler* theHandler = m_fitPropertyBrowser->getHandler();
-  MantidQt::MantidWidgets::PropertyHandler* h = theHandler->findHandler(f);
-  if (!h) return;
+void PeakPickerTool::parameterChanged(const Mantid::API::IFunction *f) {
+  MantidQt::MantidWidgets::PropertyHandler *theHandler =
+      m_fitPropertyBrowser->getHandler();
+  MantidQt::MantidWidgets::PropertyHandler *h = theHandler->findHandler(f);
+  if (!h)
+    return;
   replot(h);
-  if (h != theHandler && theHandler->hasPlot())
-  {
+  if (h != theHandler && theHandler->hasPlot()) {
     replot(theHandler);
   }
   graph()->replot();
 }
 
-void PeakPickerTool::replot(MantidQt::MantidWidgets::PropertyHandler* h) const
-{
-  if (h->hasPlot())
-  {
-    FunctionCurve* fc = 0;
+void PeakPickerTool::replot(MantidQt::MantidWidgets::PropertyHandler *h) const {
+  if (h->hasPlot()) {
+    FunctionCurve *fc = 0;
     int indexForFC = -1;
-    for (int i = 0; i < d_graph->curves(); i++)
-    {
-      fc = dynamic_cast<FunctionCurve*>(d_graph->curve(i));
-      if (fc)
-      {
-        if (fc->getIFunctionIdentifier() == h->ifun().get())
-        {
+    for (int i = 0; i < d_graph->curves(); i++) {
+      fc = dynamic_cast<FunctionCurve *>(d_graph->curve(i));
+      if (fc) {
+        if (fc->getIFunctionIdentifier() == h->ifun().get()) {
           indexForFC = i;
           break;
         }
       }
     }
 
-    if (indexForFC >= 0)
-    {
+    if (indexForFC >= 0) {
       QStringList formulas = fc->formulas();
       formulas[1] = QString::fromStdString(h->ifun()->asString());
       fc->setFormulas(formulas);
-      //fc->loadData();
-      auto ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(m_fitPropertyBrowser->getWorkspace());
-      fc->loadMantidData(ws,m_fitPropertyBrowser->workspaceIndex());
+      // fc->loadData();
+      auto ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(
+          m_fitPropertyBrowser->getWorkspace());
+      fc->loadMantidData(ws, m_fitPropertyBrowser->workspaceIndex());
     }
   }
 }
 
-
 /**
  * Adds commands specific to the tool to a context menu
  * @param menu :: A reference to the context menu
  */
-void PeakPickerTool::prepareContextMenu(QMenu& menu)
-{
-  QAction *action = new QAction("Add peak...",this);
-  connect(action,SIGNAL(triggered()),this,SLOT(addPeak()));
+void PeakPickerTool::prepareContextMenu(QMenu &menu) {
+  QAction *action = new QAction("Add peak...", this);
+  connect(action, SIGNAL(triggered()), this, SLOT(addPeak()));
   menu.addAction(action);
 
-  action = new QAction("Add background...",this);
-  connect(action,SIGNAL(triggered()),this,SLOT(addBackground()));
+  action = new QAction("Add background...", this);
+  connect(action, SIGNAL(triggered()), this, SLOT(addBackground()));
   menu.addAction(action);
 
-  action = new QAction("Add other function...",this);
-  connect(action,SIGNAL(triggered()),this,SLOT(addOther()));
+  action = new QAction("Add other function...", this);
+  connect(action, SIGNAL(triggered()), this, SLOT(addOther()));
   menu.addAction(action);
 
   menu.addSeparator();
 
-  if (m_fitPropertyBrowser->count()>0)
-  {
-    if (m_fitPropertyBrowser->getHandler()->hasPlot())
-    {
-      action = new QAction("Remove guess",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(removeGuess()));
+  if (m_fitPropertyBrowser->count() > 0) {
+    if (m_fitPropertyBrowser->getHandler()->hasPlot()) {
+      action = new QAction("Remove guess", this);
+      connect(action, SIGNAL(triggered()), this, SLOT(removeGuess()));
       menu.addAction(action);
-    }
-    else
-    {
-      action = new QAction("Plot guess",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(plotGuess()));
+    } else {
+      action = new QAction("Plot guess", this);
+      connect(action, SIGNAL(triggered()), this, SLOT(plotGuess()));
       menu.addAction(action);
     }
 
-    MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-    if (h && h->pfun())
-    {
-      if (h->hasPlot())
-      {
-        action = new QAction("Remove guess for this peak",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(removeCurrentGuess()));
+    MantidQt::MantidWidgets::PropertyHandler *h =
+        m_fitPropertyBrowser->currentHandler();
+    if (h && h->pfun()) {
+      if (h->hasPlot()) {
+        action = new QAction("Remove guess for this peak", this);
+        connect(action, SIGNAL(triggered()), this, SLOT(removeCurrentGuess()));
         menu.addAction(action);
-      }
-      else
-      {
-        action = new QAction("Plot guess for this peak",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(plotCurrentGuess()));
+      } else {
+        action = new QAction("Plot guess for this peak", this);
+        connect(action, SIGNAL(triggered()), this, SLOT(plotCurrentGuess()));
         menu.addAction(action);
       }
 
       menu.addSeparator();
 
-      action = new QAction("Remove peak",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(deletePeak()));
+      action = new QAction("Remove peak", this);
+      connect(action, SIGNAL(triggered()), this, SLOT(deletePeak()));
       menu.addAction(action);
-
     }
   }
 
-  action = new QAction("Reset range",this);
-  connect(action,SIGNAL(triggered()),this,SLOT(resetRange()));
+  action = new QAction("Reset range", this);
+  connect(action, SIGNAL(triggered()), this, SLOT(resetRange()));
   menu.addAction(action);
 
-  action = new QAction("Clear all",this);
-  connect(action,SIGNAL(triggered()),this,SLOT(clear()));
+  action = new QAction("Clear all", this);
+  connect(action, SIGNAL(triggered()), this, SLOT(clear()));
   menu.addAction(action);
 
   menu.addSeparator();
@@ -769,36 +711,33 @@ void PeakPickerTool::prepareContextMenu(QMenu& menu)
   action = new QAction("Get Parameters", this);
   connect(action, SIGNAL(triggered()), this, SLOT(getParameters()));
   menu.addAction(action);
-  
+
   menu.addSeparator();
 
-  if (m_fitPropertyBrowser->isFitEnabled())
-  {
-    action = new QAction("Fit",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(fit()));
+  if (m_fitPropertyBrowser->isFitEnabled()) {
+    action = new QAction("Fit", this);
+    connect(action, SIGNAL(triggered()), this, SLOT(fit()));
     menu.addAction(action);
   }
 
-  if (m_fitPropertyBrowser->isUndoEnabled())
-  {
-    action = new QAction("Undo fit",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(undoFit()));
+  if (m_fitPropertyBrowser->isUndoEnabled()) {
+    action = new QAction("Undo fit", this);
+    connect(action, SIGNAL(triggered()), this, SLOT(undoFit()));
     menu.addAction(action);
   }
-
 }
 
 /**
  * Slot. Adds a peak
  */
-void PeakPickerTool::addPeak()
-{
-  int i = m_fitPropertyBrowser->registeredPeaks().indexOf(QString::fromStdString(m_fitPropertyBrowser->defaultPeakType()));
+void PeakPickerTool::addPeak() {
+  int i = m_fitPropertyBrowser->registeredPeaks().indexOf(
+      QString::fromStdString(m_fitPropertyBrowser->defaultPeakType()));
   bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(d_graph, "MantidPlot - Fit", "Select peak type", m_fitPropertyBrowser->registeredPeaks(),i,false,&ok);
-  if (ok)
-  {
+  QString fnName = QInputDialog::getItem(
+      d_graph, "MantidPlot - Fit", "Select peak type",
+      m_fitPropertyBrowser->registeredPeaks(), i, false, &ok);
+  if (ok) {
     m_fitPropertyBrowser->setDefaultPeakType(fnName.toStdString());
     m_addingPeak = true;
     d_graph->plotWidget()->canvas()->setCursor(Qt::CrossCursor);
@@ -807,14 +746,13 @@ void PeakPickerTool::addPeak()
 }
 
 /**
- * 
+ *
  */
-void PeakPickerTool::addPeakAt(int x,int y)
-{
+void PeakPickerTool::addPeakAt(int x, int y) {
   // x - axis is #2, y - is #0
-  double c = d_graph->plotWidget()->invTransform(2,x);
-  double h = d_graph->plotWidget()->invTransform(0,y);
-  addPeak(c,h);
+  double c = d_graph->plotWidget()->invTransform(2, x);
+  double h = d_graph->plotWidget()->invTransform(0, y);
+  addPeak(c, h);
   emit peakChanged();
   d_graph->plotWidget()->replot();
   m_fitPropertyBrowser->updateParameters();
@@ -823,10 +761,11 @@ void PeakPickerTool::addPeakAt(int x,int y)
 /**
  * Slot. Deletes the current peak
  */
-void PeakPickerTool::deletePeak()
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  if (!h) return;
+void PeakPickerTool::deletePeak() {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  if (!h)
+    return;
   h->removeFunction();
   functionRemoved();
 }
@@ -834,32 +773,23 @@ void PeakPickerTool::deletePeak()
 /**
  * Slot. Start the fit
  */
-void PeakPickerTool::fit()
-{
-  m_fitPropertyBrowser->fit();
-}
+void PeakPickerTool::fit() { m_fitPropertyBrowser->fit(); }
 
 /**
  * Slot. Add a background function
  */
-void PeakPickerTool::addBackground()
-{
+void PeakPickerTool::addBackground() {
   bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(d_graph, 
-         "MantidPlot - Fit", "Select background type", 
-         m_fitPropertyBrowser->registeredBackgrounds(),
-         m_fitPropertyBrowser->registeredBackgrounds().indexOf("LinearBackground"),
-         false,&ok);
-  if (ok)
-  {
-    if (fnName == "LinearBackground")
-    {
+  QString fnName = QInputDialog::getItem(
+      d_graph, "MantidPlot - Fit", "Select background type",
+      m_fitPropertyBrowser->registeredBackgrounds(),
+      m_fitPropertyBrowser->registeredBackgrounds().indexOf("LinearBackground"),
+      false, &ok);
+  if (ok) {
+    if (fnName == "LinearBackground") {
       m_fitPropertyBrowser->setAutoBackgroundName(fnName);
       m_fitPropertyBrowser->addAutoBackground();
-    }
-    else
-    {
+    } else {
       m_fitPropertyBrowser->addFunction(fnName.toStdString());
     }
   }
@@ -868,16 +798,12 @@ void PeakPickerTool::addBackground()
 /**
  * Slot. Add a function that is neither peak nor background
  */
-void PeakPickerTool::addOther()
-{
+void PeakPickerTool::addOther() {
   bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(d_graph, 
-         "MantidPlot - Fit", "Select function type", 
-         m_fitPropertyBrowser->registeredOthers(),0,
-         false,&ok);
-  if (ok)
-  {
+  QString fnName = QInputDialog::getItem(
+      d_graph, "MantidPlot - Fit", "Select function type",
+      m_fitPropertyBrowser->registeredOthers(), 0, false, &ok);
+  if (ok) {
     m_fitPropertyBrowser->addFunction(fnName.toStdString());
   }
 }
@@ -885,24 +811,17 @@ void PeakPickerTool::addOther()
 /**
  * Slot. Undo the fit
  */
-void PeakPickerTool::undoFit()
-{
-  m_fitPropertyBrowser->undoFit();
-}
+void PeakPickerTool::undoFit() { m_fitPropertyBrowser->undoFit(); }
 
 /**
  * Slot. Clear all functions
  */
-void PeakPickerTool::clear()
-{
-  m_fitPropertyBrowser->clear();
-}
+void PeakPickerTool::clear() { m_fitPropertyBrowser->clear(); }
 
 /** Set the tool tip text
  * @param txt :: The tip text
  */
-void PeakPickerTool::setToolTip(const QString& txt)
-{
+void PeakPickerTool::setToolTip(const QString &txt) {
   d_graph->setToolTip(txt);
   m_fitPropertyBrowser->setTip(txt);
 }
@@ -910,17 +829,17 @@ void PeakPickerTool::setToolTip(const QString& txt)
 /**
  * Slot. Plot the initial guess for the function
  */
-void PeakPickerTool::plotGuess()
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->getHandler();
+void PeakPickerTool::plotGuess() {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->getHandler();
   plotFitFunction(h);
   h->hasPlot() = true;
   d_graph->replot();
 }
 
-void PeakPickerTool::plotCurrentGuess()
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
+void PeakPickerTool::plotCurrentGuess() {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
   plotFitFunction(h);
   h->hasPlot() = true;
   d_graph->replot();
@@ -929,81 +848,72 @@ void PeakPickerTool::plotCurrentGuess()
 /**
  * Plot function
  */
-void PeakPickerTool::plotFitFunction(MantidQt::MantidWidgets::PropertyHandler* h)
-{
-  if (h)
-  {
+void PeakPickerTool::plotFitFunction(
+    MantidQt::MantidWidgets::PropertyHandler *h) {
+  if (h) {
     // check to see if function is already plotted?
     bool alreadyPlotted = false;
-    FunctionCurve* fc;
-    for (int i = 0; i < d_graph->curves(); i++)
-    {
-      fc = dynamic_cast<FunctionCurve*>(d_graph->curve(i));
+    FunctionCurve *fc;
+    for (int i = 0; i < d_graph->curves(); i++) {
+      fc = dynamic_cast<FunctionCurve *>(d_graph->curve(i));
       if (fc)
-        if (fc->getIFunctionIdentifier() == h->ifun().get())
-        {
+        if (fc->getIFunctionIdentifier() == h->ifun().get()) {
           alreadyPlotted = true;
           break;
         }
     }
-  
+
     // plot current function guess
-    if (!alreadyPlotted)
-    {
+    if (!alreadyPlotted) {
       fc = new FunctionCurve(
-        h->ifun().get(), QString::fromStdString(m_fitPropertyBrowser->workspaceName()),
-        //QString::fromStdString(m_fitPropertyBrowser->groupMember()),//m_browser->workspaceName()),
-        m_fitPropertyBrowser->workspaceIndex(),
-        h->functionName());
-      fc->setRange(m_fitPropertyBrowser->startX(),m_fitPropertyBrowser->endX());
-      auto ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(m_fitPropertyBrowser->getWorkspace());
-      fc->loadMantidData(ws,m_fitPropertyBrowser->workspaceIndex());
-      // Graph now owns m_curve. Use m_curve->removeMe() to remove (and delete) from Graph
+          h->ifun().get(),
+          QString::fromStdString(m_fitPropertyBrowser->workspaceName()),
+          // QString::fromStdString(m_fitPropertyBrowser->groupMember()),//m_browser->workspaceName()),
+          m_fitPropertyBrowser->workspaceIndex(), h->functionName());
+      fc->setRange(m_fitPropertyBrowser->startX(),
+                   m_fitPropertyBrowser->endX());
+      auto ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(
+          m_fitPropertyBrowser->getWorkspace());
+      fc->loadMantidData(ws, m_fitPropertyBrowser->workspaceIndex());
+      // Graph now owns m_curve. Use m_curve->removeMe() to remove (and delete)
+      // from Graph
       d_graph->insertCurve(fc);
-      connect(fc,SIGNAL(forgetMe()),h,SLOT(plotRemoved()));
-      if (h == m_fitPropertyBrowser->getHandler())
-      {
+      connect(fc, SIGNAL(forgetMe()), h, SLOT(plotRemoved()));
+      if (h == m_fitPropertyBrowser->getHandler()) {
         m_fitPropertyBrowser->setTextPlotGuess("Remove guess");
       }
     }
   }
 }
 
-
 /**
  * Slot. Remove the plot of the i-th function
  */
-void PeakPickerTool::removeGuess()
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->getHandler();
+void PeakPickerTool::removeGuess() {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->getHandler();
   removePlot(h);
   h->hasPlot() = false;
   d_graph->replot();
 }
 
-void PeakPickerTool::removePlot(MantidQt::MantidWidgets::PropertyHandler* h)
-{
+void PeakPickerTool::removePlot(MantidQt::MantidWidgets::PropertyHandler *h) {
   // check to see if function is already plotted?
-  FunctionCurve* fc = 0;
+  FunctionCurve *fc = 0;
   int indexForFC = -1;
-  for (int i = 0; i < d_graph->curves(); i++)
-  {
-    fc = dynamic_cast<FunctionCurve*>(d_graph->curve(i));
-    if (fc)
-    {
-      if (fc->getIFunctionIdentifier() == h->ifun().get())
-      {
+  for (int i = 0; i < d_graph->curves(); i++) {
+    fc = dynamic_cast<FunctionCurve *>(d_graph->curve(i));
+    if (fc) {
+      if (fc->getIFunctionIdentifier() == h->ifun().get()) {
         indexForFC = i;
         break;
       }
     }
   }
 
-  if (indexForFC >= 0)
-  {
+  if (indexForFC >= 0) {
     fc->removeMe();
-    if (h == m_fitPropertyBrowser->getHandler())
-    {
+    if (h == m_fitPropertyBrowser->getHandler()) {
       m_fitPropertyBrowser->setTextPlotGuess("Plot guess");
     }
   }
@@ -1012,65 +922,53 @@ void PeakPickerTool::removePlot(MantidQt::MantidWidgets::PropertyHandler* h)
 /**
  * Slot. Remove the plot of the i-th function
  */
-void PeakPickerTool::removeCurrentGuess()
-{
-  MantidQt::MantidWidgets::PropertyHandler* h = m_fitPropertyBrowser->currentHandler();
-  if (h)
-  {
+void PeakPickerTool::removeCurrentGuess() {
+  MantidQt::MantidWidgets::PropertyHandler *h =
+      m_fitPropertyBrowser->currentHandler();
+  if (h) {
     removePlot(h);
     h->hasPlot() = false;
     d_graph->replot();
   }
 }
 
-void PeakPickerTool::curveRemoved()
-{
-  d_graph->replot();
-}
+void PeakPickerTool::curveRemoved() { d_graph->replot(); }
 
-void PeakPickerTool::resetRange()
-{
+void PeakPickerTool::resetRange() {
   QwtScaleMap xMap = d_graph->plotWidget()->canvasMap(QwtPlot::xBottom);
   double s1 = xMap.s1(), s2 = xMap.s2();
-  double ds = fabs(s2-s1)*0.05;
+  double ds = fabs(s2 - s1) * 0.05;
   xMin(s1 + ds);
   xMax(s2 - ds);
   m_fitPropertyBrowser->setStartX(xMin());
   m_fitPropertyBrowser->setEndX(xMax());
-  if (m_fitPropertyBrowser->isAutoBack())
-  {
+  if (m_fitPropertyBrowser->isAutoBack()) {
     m_fitPropertyBrowser->addAutoBackground();
   }
   d_graph->replot();
 }
 
-
 /**
-* Checks whether there is a parameters file attached to the plot. 
+* Checks whether there is a parameters file attached to the plot.
 * If so, it opens up that parameters table.
 */
-void PeakPickerTool::getParameters()
-{
+void PeakPickerTool::getParameters() {
   QString parameterWs = m_wsName + "_Parameters";
-  if (Mantid::API::AnalysisDataService::Instance().doesExist(parameterWs.toStdString() ) )
-  {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(
+          parameterWs.toStdString())) {
     m_mantidUI->importWorkspace(parameterWs);
-  }
-  else
-  {
-    QMessageBox::information(m_fitPropertyBrowser, "Mantid - Warning", "No parameter file with the name \"" + parameterWs + "\" found.");
+  } else {
+    QMessageBox::information(m_fitPropertyBrowser, "Mantid - Warning",
+                             "No parameter file with the name \"" +
+                                 parameterWs + "\" found.");
   }
 }
 
-void PeakPickerTool::modifiedGraph()
-{
-}
+void PeakPickerTool::modifiedGraph() {}
 
-void PeakPickerTool::removeFitCurves()
-{
+void PeakPickerTool::removeFitCurves() {
   QStringListIterator itr(m_curveNames);
-  while(itr.hasNext())
-  {
+  while (itr.hasNext()) {
     graph()->removeCurve(itr.next());
   }
   m_curveNames.clear();
diff --git a/MantidPlot/src/Mantid/PeakPickerTool.h b/MantidPlot/src/Mantid/PeakPickerTool.h
index 8f1f9ca19d0579a916c578c3beb1801d0b44ddcd..1802d3dafba5122bbdc7a381f0fb55d474178ab9 100644
--- a/MantidPlot/src/Mantid/PeakPickerTool.h
+++ b/MantidPlot/src/Mantid/PeakPickerTool.h
@@ -18,7 +18,6 @@
 // Forward declarations
 //---------------------------
 
-
 class MantidUI;
 class QwtPlotCurve;
 class QPoint;
@@ -26,33 +25,31 @@ class QToolBar;
 class PeakRangeMarker;
 class FunctionCurve;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 class FitPropertyBrowser;
 class PropertyHandler;
-}}
-
-namespace Mantid
-{
-  namespace API
-  {
-    class IFunction;
-    class CompositeFunction;
-    class MatrixWorkspace;
-  }
+}
 }
 
-/** 
+namespace Mantid {
+namespace API {
+class IFunction;
+class CompositeFunction;
+class MatrixWorkspace;
+}
+}
+
+/**
     This class is for selecting peaks on a graph for subsequent fitting.
-    As a QwtPlotPicker it uses its eventFilter method to intercept mouse 
+    As a QwtPlotPicker it uses its eventFilter method to intercept mouse
     and keyboard input.
 
     @author Roman Tolchenov, Tessella plc
     @date 10/08/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -70,14 +67,18 @@ namespace Mantid
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class PeakPickerTool : public QwtPlotPicker, public PlotToolInterface, public QwtPlotItem
-{
+class PeakPickerTool : public QwtPlotPicker,
+                       public PlotToolInterface,
+                       public QwtPlotItem {
   Q_OBJECT
 public:
   /// Constructor
-  PeakPickerTool(Graph *graph, MantidQt::MantidWidgets::FitPropertyBrowser *fitPropertyBrowser, MantidUI *mantidUI, bool showFitPropertyBrowser=true);
+  PeakPickerTool(
+      Graph *graph,
+      MantidQt::MantidWidgets::FitPropertyBrowser *fitPropertyBrowser,
+      MantidUI *mantidUI, bool showFitPropertyBrowser = true);
   /// Destructor
   ~PeakPickerTool() override;
   /// Runtime type identifier
@@ -85,18 +86,18 @@ public:
   /// Receives and processes mouse and keyboard events
   bool eventFilter(QObject *obj, QEvent *event) override;
   /// Workspace name
-  const QString& workspaceName()const{return m_wsName;}
+  const QString &workspaceName() const { return m_wsName; }
   /// workspace index
-  int spec()const{return m_spec;}
+  int spec() const { return m_spec; }
   /// The parent graph
-  Graph* graph()const{return d_graph;}
+  Graph *graph() const { return d_graph; }
   /// Prepare a context menu
-  void prepareContextMenu(QMenu& menu); 
+  void prepareContextMenu(QMenu &menu);
   /// Was the tool created successfuly?
-  bool isInitialized() const {return m_init;}
+  bool isInitialized() const { return m_init; }
 
 public slots:
-  void windowStateChanged( Qt::WindowStates oldState, Qt::WindowStates newState );
+  void windowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState);
 
 signals:
   void peakChanged();
@@ -106,10 +107,10 @@ private slots:
   void functionCleared();
   void currentChanged();
   void functionRemoved();
-  void algorithmFinished(const QString&);
+  void algorithmFinished(const QString &);
   void workspaceIndexChanged(int i);
-  void workspaceNameChanged(const QString&);
-  void parameterChanged(const Mantid::API::IFunction*);
+  void workspaceNameChanged(const QString &);
+  void parameterChanged(const Mantid::API::IFunction *);
   void startXChanged(double);
   void endXChanged(double);
 
@@ -125,7 +126,7 @@ private slots:
   void removeGuess();
   void plotCurrentGuess();
   void removeCurrentGuess();
-  void removePlot(MantidQt::MantidWidgets::PropertyHandler* h);
+  void removePlot(MantidQt::MantidWidgets::PropertyHandler *h);
   void removeFitCurves();
 
   void curveRemoved();
@@ -136,56 +137,58 @@ private slots:
   void getParameters();
 
 private:
-  void plotFitFunction(MantidQt::MantidWidgets::PropertyHandler* h);
-  void replot(MantidQt::MantidWidgets::PropertyHandler* h) const;
+  void plotFitFunction(MantidQt::MantidWidgets::PropertyHandler *h);
+  void replot(MantidQt::MantidWidgets::PropertyHandler *h) const;
 
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &) const override;
-  // Add a new peak with centre c and height h. 
-  void addPeak(double c,double h);
-  void addPeakAt(int x,int y);
+  // Add a new peak with centre c and height h.
+  void addPeak(double c, double h);
+  void addPeakAt(int x, int y);
 
   // Return the centre of the currently selected peak
-  double centre()const;
+  double centre() const;
   // Return the width of the currently selected peak
-  double width()const;
+  double width() const;
   // Return the height of the currently selected peak
-  double height()const;
+  double height() const;
   // Check if the width is been set
-  bool isWidthSet()const{return m_width_set;}
+  bool isWidthSet() const { return m_width_set; }
   // Set the width set flag
-  void widthIsSet(bool yes=true) {m_width_set = yes;}
+  void widthIsSet(bool yes = true) { m_width_set = yes; }
   // Change the width of the currently selected peak
   void setWidth(double x);
 
   // Check if x is near the xMin marker (+-dx)
-  bool clickedOnXMin(double x,double dx);
+  bool clickedOnXMin(double x, double dx);
   // Check if x is near the xMax marker (+-dx)
-  bool clickedOnXMax(double x,double dx);
+  bool clickedOnXMax(double x, double dx);
   // Check if x is near a width marker (+-dx)
-  bool clickedOnWidthMarker(double x,double dx);
+  bool clickedOnWidthMarker(double x, double dx);
   // Return valid handler if x is within +- dx around peak's centre
-  MantidQt::MantidWidgets::PropertyHandler* clickedOnCentreMarker(double x,double dx)const;
+  MantidQt::MantidWidgets::PropertyHandler *
+  clickedOnCentreMarker(double x, double dx) const;
 
   // Give new centre and height to the current peak
-  void setPeak(double c,double h);
-  // Indicates that the marker (and peak tool) is in a process of resetting a peak (changing centre and height)
-  bool resetting()const{return m_resetting;}
+  void setPeak(double c, double h);
+  // Indicates that the marker (and peak tool) is in a process of resetting a
+  // peak (changing centre and height)
+  bool resetting() const { return m_resetting; }
   // Switch on/off the resetting flag
-  void resetting(bool ok){m_resetting = ok;}
+  void resetting(bool ok) { m_resetting = ok; }
   // Lower fit boundary
-  double xMin()const{return m_xMin;}
+  double xMin() const { return m_xMin; }
   void xMin(double x);
-  bool changingXMin()const{return m_changingXMin;}
-  void changingXMin(bool ok){m_changingXMin = ok;}
+  bool changingXMin() const { return m_changingXMin; }
+  void changingXMin(bool ok) { m_changingXMin = ok; }
   // Upper fit boundary
-  double xMax()const  {return m_xMax;}
-  void xMax(double x) ;
-  bool changingXMax()const{return m_changingXMax;}
-  void changingXMax(bool ok){m_changingXMax = ok;}
+  double xMax() const { return m_xMax; }
+  void xMax(double x);
+  bool changingXMax() const { return m_changingXMax; }
+  void changingXMax(bool ok) { m_changingXMax = ok; }
 
   // Set the tool tip text
-  void setToolTip(const QString& txt);
+  void setToolTip(const QString &txt);
 
   // Set up member variables from curve
   bool initializeFromCurve(PlotCurve *curve);
@@ -195,7 +198,7 @@ private:
   bool isMuonData() const;
 
   /// Creates a pointer to fitPropertyBrowser
-  MantidQt::MantidWidgets::FitPropertyBrowser* m_fitPropertyBrowser;
+  MantidQt::MantidWidgets::FitPropertyBrowser *m_fitPropertyBrowser;
 
   MantidUI *m_mantidUI;
 
@@ -206,20 +209,18 @@ private:
   /// Pointer to the workspace
   boost::shared_ptr<Mantid::API::MatrixWorkspace> m_ws;
 
-  bool m_init;      // Is the tool initialized?
-  bool m_width_set; // The width set flag
-  double m_width;   // The default width
-  bool m_addingPeak;// The adding peak state flag
-  bool m_resetting; // The resetting state flag
-  double m_xMin;    // Lower fit boundary
-  double m_xMax;    // Upper fit boundary
+  bool m_init;         // Is the tool initialized?
+  bool m_width_set;    // The width set flag
+  double m_width;      // The default width
+  bool m_addingPeak;   // The adding peak state flag
+  bool m_resetting;    // The resetting state flag
+  double m_xMin;       // Lower fit boundary
+  double m_xMax;       // Upper fit boundary
   bool m_changingXMin; // Flag indicating that changing of xMin is in progress
   bool m_changingXMax; // Flag indicating that changing of xMax is in progress
   bool m_shouldBeNormalised; // Should the data be normalised before fitting?
 
   QStringList m_curveNames; // Names of all curves added to graph()
-
 };
 
-
 #endif /* PEAK_PICKER_TOOL_H */
diff --git a/MantidPlot/src/Mantid/Preferences.cpp b/MantidPlot/src/Mantid/Preferences.cpp
index e6d14803246cd451569a2d0ebdc8df80eba6240e..fe533739fa25b80f26760206b95420692708615b 100644
--- a/MantidPlot/src/Mantid/Preferences.cpp
+++ b/MantidPlot/src/Mantid/Preferences.cpp
@@ -5,178 +5,155 @@
 //           MantidMatrix settings
 //------------------------------------------//
 
-int MantidPreferences::MantidMatrixColumnWidthY()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthY",100).toInt();
+int MantidPreferences::MantidMatrixColumnWidthY() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthY", 100)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixColumnWidthX()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthX",100).toInt();
+int MantidPreferences::MantidMatrixColumnWidthX() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthX", 100)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixColumnWidthE()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthE",100).toInt();
+int MantidPreferences::MantidMatrixColumnWidthE() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthE", 100)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixColumnWidthDx()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthDx",100).toInt();
+int MantidPreferences::MantidMatrixColumnWidthDx() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/ColumnWidthDx", 100)
+      .toInt();
 }
 
-
-void MantidPreferences::MantidMatrixColumnWidthY(int width)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthY",width);
+void MantidPreferences::MantidMatrixColumnWidthY(int width) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthY", width);
 }
 
-void MantidPreferences::MantidMatrixColumnWidthX(int width)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthX",width);
+void MantidPreferences::MantidMatrixColumnWidthX(int width) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthX", width);
 }
 
-void MantidPreferences::MantidMatrixColumnWidthE(int width)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthE",width);
+void MantidPreferences::MantidMatrixColumnWidthE(int width) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthE", width);
 }
 
-void MantidPreferences::MantidMatrixColumnWidthDx(int width)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthDx",width);
+void MantidPreferences::MantidMatrixColumnWidthDx(int width) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthDx", width);
 }
 
-void MantidPreferences::MantidMatrixColumnWidth(int width)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthY",width);
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthX",width);
-    settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthE",width);
+void MantidPreferences::MantidMatrixColumnWidth(int width) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthY", width);
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthX", width);
+  settings.setValue("Mantid/Preferences/MantidMatrix/ColumnWidthE", width);
 }
 
-
-QChar MantidPreferences::MantidMatrixNumberFormatY()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatY",'g').toChar();
+QChar MantidPreferences::MantidMatrixNumberFormatY() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatY", 'g')
+      .toChar();
 }
 
-QChar MantidPreferences::MantidMatrixNumberFormatX()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatX",'g').toChar();
+QChar MantidPreferences::MantidMatrixNumberFormatX() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatX", 'g')
+      .toChar();
 }
 
-QChar MantidPreferences::MantidMatrixNumberFormatE()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatE",'g').toChar();
+QChar MantidPreferences::MantidMatrixNumberFormatE() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatE", 'g')
+      .toChar();
 }
 
-QChar MantidPreferences::MantidMatrixNumberFormatDx()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatDx",'g').toChar();
+QChar MantidPreferences::MantidMatrixNumberFormatDx() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberFormatDx", 'g')
+      .toChar();
 }
 
-
-void MantidPreferences::MantidMatrixNumberFormatY(const QChar& f)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatY",f);
+void MantidPreferences::MantidMatrixNumberFormatY(const QChar &f) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatY", f);
 }
 
-void MantidPreferences::MantidMatrixNumberFormatX(const QChar& f)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatX",f);
+void MantidPreferences::MantidMatrixNumberFormatX(const QChar &f) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatX", f);
 }
 
-void MantidPreferences::MantidMatrixNumberFormatE(const QChar& f)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatE",f);
+void MantidPreferences::MantidMatrixNumberFormatE(const QChar &f) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatE", f);
 }
 
-void MantidPreferences::MantidMatrixNumberFormatDx(const QChar& f)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatDx",f);
+void MantidPreferences::MantidMatrixNumberFormatDx(const QChar &f) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatDx", f);
 }
 
-void MantidPreferences::MantidMatrixNumberFormat(const QChar& f)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatY",f);
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatX",f);
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatE",f);
+void MantidPreferences::MantidMatrixNumberFormat(const QChar &f) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatY", f);
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatX", f);
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberFormatE", f);
 }
 
-
-int MantidPreferences::MantidMatrixNumberPrecisionY()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionY",6).toInt();
+int MantidPreferences::MantidMatrixNumberPrecisionY() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionY", 6)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixNumberPrecisionX()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionX",6).toInt();
+int MantidPreferences::MantidMatrixNumberPrecisionX() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionX", 6)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixNumberPrecisionE()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionE",6).toInt();
+int MantidPreferences::MantidMatrixNumberPrecisionE() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionE", 6)
+      .toInt();
 }
 
-int MantidPreferences::MantidMatrixNumberPrecisionDx()
-{
-    QSettings settings;
-    return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionDx",6).toInt();
+int MantidPreferences::MantidMatrixNumberPrecisionDx() {
+  QSettings settings;
+  return settings.value("Mantid/Preferences/MantidMatrix/NumberPrecisionDx", 6)
+      .toInt();
 }
 
-
-
-void MantidPreferences::MantidMatrixNumberPrecisionY(int p)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionY",p);
+void MantidPreferences::MantidMatrixNumberPrecisionY(int p) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionY", p);
 }
 
-void MantidPreferences::MantidMatrixNumberPrecisionX(int p)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionX",p);
+void MantidPreferences::MantidMatrixNumberPrecisionX(int p) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionX", p);
 }
 
-void MantidPreferences::MantidMatrixNumberPrecisionE(int p)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionE",p);
+void MantidPreferences::MantidMatrixNumberPrecisionE(int p) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionE", p);
 }
 
-void MantidPreferences::MantidMatrixNumberPrecisionDx(int p)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionDx",p);
+void MantidPreferences::MantidMatrixNumberPrecisionDx(int p) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionDx", p);
 }
 
-void MantidPreferences::MantidMatrixNumberPrecision(int p)
-{
-    QSettings settings;
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionY",p);
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionX",p);
-    settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionE",p);
+void MantidPreferences::MantidMatrixNumberPrecision(int p) {
+  QSettings settings;
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionY", p);
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionX", p);
+  settings.setValue("Mantid/Preferences/MantidMatrix/NumberPrecisionE", p);
 }
-
-
diff --git a/MantidPlot/src/Mantid/Preferences.h b/MantidPlot/src/Mantid/Preferences.h
index 583c7b4718e7af1aa8d636950cce6cff96c8c471..84eabce69c6837786002c5e1c4b8e31870b9b683 100644
--- a/MantidPlot/src/Mantid/Preferences.h
+++ b/MantidPlot/src/Mantid/Preferences.h
@@ -12,7 +12,8 @@
  @author Roman Tolchenov, Tessella Support Services plc
  @date 13/02/2009
 
- Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -33,47 +34,44 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class MantidPreferences
-{
+class MantidPreferences {
 public:
-    // ---  MantidMatrixSettings --- //
-
-    static int MantidMatrixColumnWidthY();
-    static int MantidMatrixColumnWidthX();
-    static int MantidMatrixColumnWidthE();
-    static int MantidMatrixColumnWidthDx();
-    static void MantidMatrixColumnWidthY(int width);
-    static void MantidMatrixColumnWidthX(int width);
-    static void MantidMatrixColumnWidthE(int width);
-    static void MantidMatrixColumnWidthDx(int width);
-    static void MantidMatrixColumnWidth(int width);
-
-    static QChar MantidMatrixNumberFormatY();
-    static QChar MantidMatrixNumberFormatX();
-    static QChar MantidMatrixNumberFormatE();
-    static QChar MantidMatrixNumberFormatDx();
-    static void MantidMatrixNumberFormatY(const QChar& f);
-    static void MantidMatrixNumberFormatX(const QChar& f);
-    static void MantidMatrixNumberFormatE(const QChar& f);
-    static void MantidMatrixNumberFormatDx(const QChar& f);
-    static void MantidMatrixNumberFormat(const QChar& f);
-
-    static int MantidMatrixNumberPrecisionY();
-    static int MantidMatrixNumberPrecisionX();
-    static int MantidMatrixNumberPrecisionE();
-    static int MantidMatrixNumberPrecisionDx();
-    static void MantidMatrixNumberPrecisionY(int p);
-    static void MantidMatrixNumberPrecisionX(int p);
-    static void MantidMatrixNumberPrecisionE(int p);
-    static void MantidMatrixNumberPrecisionDx(int p);
-    static void MantidMatrixNumberPrecision(int p);
-
+  // ---  MantidMatrixSettings --- //
+
+  static int MantidMatrixColumnWidthY();
+  static int MantidMatrixColumnWidthX();
+  static int MantidMatrixColumnWidthE();
+  static int MantidMatrixColumnWidthDx();
+  static void MantidMatrixColumnWidthY(int width);
+  static void MantidMatrixColumnWidthX(int width);
+  static void MantidMatrixColumnWidthE(int width);
+  static void MantidMatrixColumnWidthDx(int width);
+  static void MantidMatrixColumnWidth(int width);
+
+  static QChar MantidMatrixNumberFormatY();
+  static QChar MantidMatrixNumberFormatX();
+  static QChar MantidMatrixNumberFormatE();
+  static QChar MantidMatrixNumberFormatDx();
+  static void MantidMatrixNumberFormatY(const QChar &f);
+  static void MantidMatrixNumberFormatX(const QChar &f);
+  static void MantidMatrixNumberFormatE(const QChar &f);
+  static void MantidMatrixNumberFormatDx(const QChar &f);
+  static void MantidMatrixNumberFormat(const QChar &f);
+
+  static int MantidMatrixNumberPrecisionY();
+  static int MantidMatrixNumberPrecisionX();
+  static int MantidMatrixNumberPrecisionE();
+  static int MantidMatrixNumberPrecisionDx();
+  static void MantidMatrixNumberPrecisionY(int p);
+  static void MantidMatrixNumberPrecisionX(int p);
+  static void MantidMatrixNumberPrecisionE(int p);
+  static void MantidMatrixNumberPrecisionDx(int p);
+  static void MantidMatrixNumberPrecision(int p);
 
 private:
-    /// Creation of non-static instances is not allowed.
-    MantidPreferences();
-    MantidPreferences(const MantidPreferences&);
+  /// Creation of non-static instances is not allowed.
+  MantidPreferences();
+  MantidPreferences(const MantidPreferences &);
 };
 
-
 #endif /* MANTIDPREFERENCES_H */
diff --git a/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp b/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
index 4d8bdb6454fdbcd96cb4aee7c44e148bda533db4..bbe057b73b6a641d8d2983ec1d0d1098ff11301a 100644
--- a/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
+++ b/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
@@ -1,25 +1,18 @@
 #include "RemoveErrorsDialog.h"
 #include "ui_RemoveErrorsDialog.h"
 
-RemoveErrorsDialog::RemoveErrorsDialog(QWidget *parent) :
-    QDialog(parent),
-    ui(new Ui::RemoveErrorsDialog)
-{
-    ui->setupUi(this);
-    connect( ui->buttonBox, SIGNAL( accepted() ), this, SLOT( remove() ) );
+RemoveErrorsDialog::RemoveErrorsDialog(QWidget *parent)
+    : QDialog(parent), ui(new Ui::RemoveErrorsDialog) {
+  ui->setupUi(this);
+  connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(remove()));
 }
 
-RemoveErrorsDialog::~RemoveErrorsDialog()
-{
-    delete ui;
-}
+RemoveErrorsDialog::~RemoveErrorsDialog() { delete ui; }
 
-void RemoveErrorsDialog::setCurveNames(const QStringList& names)
-{
+void RemoveErrorsDialog::setCurveNames(const QStringList &names) {
   ui->nameLabel->addItems(names);
 }
 
-void RemoveErrorsDialog::remove()
-{
+void RemoveErrorsDialog::remove() {
   emit curveName(ui->nameLabel->currentText());
 }
\ No newline at end of file
diff --git a/MantidPlot/src/Mantid/RemoveErrorsDialog.h b/MantidPlot/src/Mantid/RemoveErrorsDialog.h
index 067c6326fd1ef3708c90520a4969827b3efd6594..f984d9065f21b04cc1cc48caea4293341d60c50a 100644
--- a/MantidPlot/src/Mantid/RemoveErrorsDialog.h
+++ b/MantidPlot/src/Mantid/RemoveErrorsDialog.h
@@ -4,11 +4,11 @@
 #include <QDialog>
 
 namespace Ui {
-    class RemoveErrorsDialog;
+class RemoveErrorsDialog;
 }
 
 class RemoveErrorsDialog : public QDialog {
-    Q_OBJECT
+  Q_OBJECT
 public:
   explicit RemoveErrorsDialog(QWidget *parent = 0);
   ~RemoveErrorsDialog() override;
@@ -18,14 +18,14 @@ public:
 
 signals:
 
-    void curveName(const QString&);
+  void curveName(const QString &);
 
 protected slots:
 
   void remove();
 
 private:
-    Ui::RemoveErrorsDialog *ui;
+  Ui::RemoveErrorsDialog *ui;
 };
 
 #endif // REMOVEERRORSDIALOG_H
diff --git a/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp b/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
index 0814da59551452e138cd5f902fd2f43905eb3a33..9f66b169cedca3e35e0eeebc9e864895172fb556 100644
--- a/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
+++ b/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
@@ -13,77 +13,67 @@
 //---------------------------------------
 
 /// Constructor
-UserFitFunctionDialog::UserFitFunctionDialog(QWidget* parent) :
-  QDialog(parent)
-{
+UserFitFunctionDialog::UserFitFunctionDialog(QWidget *parent)
+    : QDialog(parent) {
   ui.setupUi(this);
 
   ui.btnAdd->setEnabled(false);
 
-  connect(ui.btnAdd,SIGNAL(clicked()),this,SLOT(addFunction()));
-  connect(ui.btnMultiply,SIGNAL(clicked()),this,SLOT(multiplyFunction()));
-  connect(ui.btnInsert,SIGNAL(clicked()),this,SLOT(insertFunction()));
-  connect(ui.treeFunctions,SIGNAL(itemSelectionChanged()),this,SLOT(functionSelectionChanged()));
-
+  connect(ui.btnAdd, SIGNAL(clicked()), this, SLOT(addFunction()));
+  connect(ui.btnMultiply, SIGNAL(clicked()), this, SLOT(multiplyFunction()));
+  connect(ui.btnInsert, SIGNAL(clicked()), this, SLOT(insertFunction()));
+  connect(ui.treeFunctions, SIGNAL(itemSelectionChanged()), this,
+          SLOT(functionSelectionChanged()));
 }
 
-void UserFitFunctionDialog::addFunction()
-{
-  addFunction("+",false);
-}
+void UserFitFunctionDialog::addFunction() { addFunction("+", false); }
 
-void UserFitFunctionDialog::multiplyFunction()
-{
-  addFunction("*",true);
-}
+void UserFitFunctionDialog::multiplyFunction() { addFunction("*", true); }
 
-void UserFitFunctionDialog::insertFunction()
-{
-  addFunction("",false);
-}
+void UserFitFunctionDialog::insertFunction() { addFunction("", false); }
 
-void UserFitFunctionDialog::addFunction(const QString& op,bool brackets)
-{
+void UserFitFunctionDialog::addFunction(const QString &op, bool brackets) {
   ui.teExpression->setFocus();
 
-  QList<QTreeWidgetItem*> selection = ui.treeFunctions->selectedItems();
-  if (selection.size() == 0) return;
+  QList<QTreeWidgetItem *> selection = ui.treeFunctions->selectedItems();
+  if (selection.size() == 0)
+    return;
 
-  QTreeWidgetItem* item = selection.first();
-  QTreeWidgetItem* parentItem = item->parent();
+  QTreeWidgetItem *item = selection.first();
+  QTreeWidgetItem *parentItem = item->parent();
 
-  if (parentItem == NULL) return; // this sould never happen, just in case
+  if (parentItem == NULL)
+    return; // this sould never happen, just in case
 
-  if (parentItem->parent() != NULL) item = parentItem;
+  if (parentItem->parent() != NULL)
+    item = parentItem;
 
-  //QTextCursor cursor = ui.teExpression->textCursor();
-  //cursor.insertText( item->text(1) );
+  // QTextCursor cursor = ui.teExpression->textCursor();
+  // cursor.insertText( item->text(1) );
 
   QString oper = ui.teExpression->toPlainText().isEmpty() ? "" : op;
   QString expr = item->text(1);
-  if (brackets) expr = QString("(") + expr + ")";
+  if (brackets)
+    expr = QString("(") + expr + ")";
   expr = oper + expr;
-  ui.teExpression->insertPlainText( expr );
-
-  if (item->childCount() == 0 || !ui.lePeakParams->text().isEmpty()) return;
+  ui.teExpression->insertPlainText(expr);
 
-  ui.lePeakParams->setText( item->child(0)->text(1) );
-  ui.leWidthFormula->setText( item->child(1)->text(1) );
+  if (item->childCount() == 0 || !ui.lePeakParams->text().isEmpty())
+    return;
 
+  ui.lePeakParams->setText(item->child(0)->text(1));
+  ui.leWidthFormula->setText(item->child(1)->text(1));
 }
 
-void UserFitFunctionDialog::functionSelectionChanged()
-{
-  QItemSelectionModel* selection = ui.treeFunctions->selectionModel();
-  if (!selection->hasSelection())
-  {
+void UserFitFunctionDialog::functionSelectionChanged() {
+  QItemSelectionModel *selection = ui.treeFunctions->selectionModel();
+  if (!selection->hasSelection()) {
     ui.btnAdd->setEnabled(false);
     return;
   }
   QModelIndexList indexList = selection->selectedIndexes();
   QModelIndex index = indexList.first();
-  if (index.parent()== QModelIndex())
-  {
+  if (index.parent() == QModelIndex()) {
     ui.btnAdd->setEnabled(false);
     return;
   }
diff --git a/MantidPlot/src/Mantid/UserFitFunctionDialog.h b/MantidPlot/src/Mantid/UserFitFunctionDialog.h
index e14934000b6b45573e9162a6b38a31d0b6c43c48..3b7c429c0e3f47d51bc5fd62fb9cd68c0d1fa124 100644
--- a/MantidPlot/src/Mantid/UserFitFunctionDialog.h
+++ b/MantidPlot/src/Mantid/UserFitFunctionDialog.h
@@ -17,13 +17,14 @@
 
 class MantidUI;
 
-/** 
+/**
     This is a dialog for constructing fitting functions.
 
     @author Roman Tolchenov, Tessella plc
     @date 23/09/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -41,25 +42,23 @@ class MantidUI;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class UserFitFunctionDialog : public QDialog
-{
+class UserFitFunctionDialog : public QDialog {
   Q_OBJECT
 
 public:
-  
   /// Default constructor
   explicit UserFitFunctionDialog(QWidget *parent);
 
   /// The constructed expression
-  QString expression()const{return ui.teExpression->toPlainText();}
+  QString expression() const { return ui.teExpression->toPlainText(); }
 
   /// Peak parameters. Empty if the function is not a peak
-  QString peakParams()const{return ui.lePeakParams->text();}
+  QString peakParams() const { return ui.lePeakParams->text(); }
 
-  /// Width formula - 
-  QString widthFormula()const{return ui.leWidthFormula->text();}
+  /// Width formula -
+  QString widthFormula() const { return ui.leWidthFormula->text(); }
 
 private slots:
 
@@ -72,19 +71,16 @@ private slots:
   /// Add the selected function(s) from ui.treeFunctions to the edit window
   void insertFunction();
 
-  /// React on the change of selection in ui.treeFunctions (e.g. enable or disable ui.btnAdd)
+  /// React on the change of selection in ui.treeFunctions (e.g. enable or
+  /// disable ui.btnAdd)
   void functionSelectionChanged();
 
 private:
-
   /// Add the selected function(s) from ui.treeFunctions to the edit window
-  void addFunction(const QString& op,bool brackets);
+  void addFunction(const QString &op, bool brackets);
 
   // The form generated with Qt Designer
   Ui::UserFitFunctionDialog ui;
-
 };
 
-
-
 #endif /* USERFITFUNCTIONDIALOG_H */
\ No newline at end of file
diff --git a/MantidPlot/src/Mantid/WorkspaceIcons.cpp b/MantidPlot/src/Mantid/WorkspaceIcons.cpp
index 757413ba0891295daca4d174d7ec7e1ad69e4cf4..114d7e46590f75a40ade7bb2a9d9393e4a13f3f7 100644
--- a/MantidPlot/src/Mantid/WorkspaceIcons.cpp
+++ b/MantidPlot/src/Mantid/WorkspaceIcons.cpp
@@ -10,20 +10,16 @@
 /**
  * Default constructor
  */
-WorkspaceIcons::WorkspaceIcons() : m_idToPixmapName()
-{
-  initInternalLookup();
-}
+WorkspaceIcons::WorkspaceIcons() : m_idToPixmapName() { initInternalLookup(); }
 
 /**
  * @param workspaceID A string giving the ID for a workspace
  * @throws std::runtime_error if no icon can be found
  */
-QPixmap WorkspaceIcons::getIcon(const std::string & workspaceID) const
-{
+QPixmap WorkspaceIcons::getIcon(const std::string &workspaceID) const {
   // All mappings are simple bar the MDEventWorkspace as each of its templates
   // has different ID.
-  if(workspaceID.compare(0, 16, "MDEventWorkspace") == 0)
+  if (workspaceID.compare(0, 16, "MDEventWorkspace") == 0)
     return getQPixmap(m_idToPixmapName.value("MDEventWorkspace"));
   else
     return getQPixmap(m_idToPixmapName.value(workspaceID));
@@ -34,8 +30,7 @@ QPixmap WorkspaceIcons::getIcon(const std::string & workspaceID) const
 //-----------------------------------------------------------------------------
 /**
  */
-void WorkspaceIcons::initInternalLookup()
-{
+void WorkspaceIcons::initInternalLookup() {
   m_idToPixmapName.clear();
   // MatrixWorkspace types
   m_idToPixmapName["EventWorkspace"] = "mantid_matrix_xpm";
diff --git a/MantidPlot/src/Mantid/WorkspaceIcons.h b/MantidPlot/src/Mantid/WorkspaceIcons.h
index c29f6261f18748fb3c417b093443498e8c8de283..68d75f8cced7ea178101ad2508e72d0dc8b02df7 100644
--- a/MantidPlot/src/Mantid/WorkspaceIcons.h
+++ b/MantidPlot/src/Mantid/WorkspaceIcons.h
@@ -8,13 +8,12 @@
  * Defines a mapping between a workspace ID and a pixmap
  * to use for an icon.
  */
-class WorkspaceIcons
-{
+class WorkspaceIcons {
 public:
   WorkspaceIcons();
 
   /// Returns an icon for the given ID
-  QPixmap getIcon(const std::string & workspaceID) const;
+  QPixmap getIcon(const std::string &workspaceID) const;
 
 private:
   /// Defines the mapping between ID & pixmap name
diff --git a/MantidPlot/src/Matrix.cpp b/MantidPlot/src/Matrix.cpp
index 1139acbc4d907cd583adbe3ada1883df3715bdbb..cb1e9c503a2139b335926879ee14e6cca0a747c4 100644
--- a/MantidPlot/src/Matrix.cpp
+++ b/MantidPlot/src/Matrix.cpp
@@ -69,55 +69,48 @@
 #include <gsl/gsl_math.h>
 #include <gsl/gsl_linalg.h>
 
-Matrix::Matrix(ScriptingEnv *env, const QString& label, ApplicationWindow* parent, const QString& name, Qt::WFlags f)
-  : MdiSubWindow(parent, label, name, f), Scripted(env), 
-  d_matrix_model(NULL),m_bk_color(),d_stack(NULL),
-  d_table_view(NULL),imageLabel(NULL),formula_str(),
-  txt_format(),num_precision(0),x_start(0.0),
-  x_end(0.0),y_start(0.0),y_end(0.0),
-  d_view_type(ViewType::TableView),d_header_view_type(HeaderViewType::ColumnRow),
-  d_color_map(),d_color_map_type(ColorMapType::Rainbow),
-  d_column_width(0),d_select_all_shortcut(NULL),
-  d_undo_stack(NULL),d_workspace(NULL)
-{
+Matrix::Matrix(ScriptingEnv *env, const QString &label,
+               ApplicationWindow *parent, const QString &name, Qt::WFlags f)
+    : MdiSubWindow(parent, label, name, f), Scripted(env), d_matrix_model(NULL),
+      m_bk_color(), d_stack(NULL), d_table_view(NULL), imageLabel(NULL),
+      formula_str(), txt_format(), num_precision(0), x_start(0.0), x_end(0.0),
+      y_start(0.0), y_end(0.0), d_view_type(ViewType::TableView),
+      d_header_view_type(HeaderViewType::ColumnRow), d_color_map(),
+      d_color_map_type(ColorMapType::Rainbow), d_column_width(0),
+      d_select_all_shortcut(NULL), d_undo_stack(NULL), d_workspace(NULL) {
   m_bk_color = QColor(255, 255, 128);
   m_matrix_icon = getQPixmap("matrix_xpm");
 }
 
-Matrix::Matrix(ScriptingEnv *env, int r, int c, const QString& label, ApplicationWindow* parent, const QString& name, Qt::WFlags f)
-  : MdiSubWindow(parent, label, name, f), Scripted(env),
-  d_matrix_model(NULL),m_bk_color(),d_stack(NULL),
-  d_table_view(NULL),imageLabel(NULL),formula_str(),
-  txt_format(),num_precision(0),x_start(0.0),
-  x_end(0.0),y_start(0.0),y_end(0.0),
-  d_view_type(ViewType::TableView),d_header_view_type(HeaderViewType::ColumnRow),
-  d_color_map(),d_color_map_type(ColorMapType::Rainbow),
-  d_column_width(0),d_select_all_shortcut(NULL),
-  d_undo_stack(NULL),d_workspace(NULL)
-{
+Matrix::Matrix(ScriptingEnv *env, int r, int c, const QString &label,
+               ApplicationWindow *parent, const QString &name, Qt::WFlags f)
+    : MdiSubWindow(parent, label, name, f), Scripted(env), d_matrix_model(NULL),
+      m_bk_color(), d_stack(NULL), d_table_view(NULL), imageLabel(NULL),
+      formula_str(), txt_format(), num_precision(0), x_start(0.0), x_end(0.0),
+      y_start(0.0), y_end(0.0), d_view_type(ViewType::TableView),
+      d_header_view_type(HeaderViewType::ColumnRow), d_color_map(),
+      d_color_map_type(ColorMapType::Rainbow), d_column_width(0),
+      d_select_all_shortcut(NULL), d_undo_stack(NULL), d_workspace(NULL) {
   m_bk_color = QColor(255, 255, 128);
   m_matrix_icon = getQPixmap("matrix_xpm");
   initTable(r, c);
 }
 
-Matrix::Matrix(ScriptingEnv *env, const QImage& image, const QString& label, ApplicationWindow* parent, const QString& name, Qt::WFlags f)
-  : MdiSubWindow(parent, label, name, f), Scripted(env),
-  d_matrix_model(NULL),m_bk_color(),d_stack(NULL),
-  d_table_view(NULL),imageLabel(NULL),formula_str(),
-  txt_format(QChar()),num_precision(0),x_start(0.0),
-  x_end(0.0),y_start(0.0),y_end(0.0),
-  d_view_type(ViewType::TableView),d_header_view_type(HeaderViewType::ColumnRow),
-  d_color_map(),d_color_map_type(ColorMapType::Rainbow),
-  d_column_width(0),d_select_all_shortcut(NULL),
-  d_undo_stack(NULL),d_workspace(NULL)
-{
+Matrix::Matrix(ScriptingEnv *env, const QImage &image, const QString &label,
+               ApplicationWindow *parent, const QString &name, Qt::WFlags f)
+    : MdiSubWindow(parent, label, name, f), Scripted(env), d_matrix_model(NULL),
+      m_bk_color(), d_stack(NULL), d_table_view(NULL), imageLabel(NULL),
+      formula_str(), txt_format(QChar()), num_precision(0), x_start(0.0),
+      x_end(0.0), y_start(0.0), y_end(0.0), d_view_type(ViewType::TableView),
+      d_header_view_type(HeaderViewType::ColumnRow), d_color_map(),
+      d_color_map_type(ColorMapType::Rainbow), d_column_width(0),
+      d_select_all_shortcut(NULL), d_undo_stack(NULL), d_workspace(NULL) {
   m_bk_color = QColor(255, 255, 128);
   m_matrix_icon = getQPixmap("matrix_xpm");
   initImage(image);
 }
 
-void Matrix::initGlobals()
-{
+void Matrix::initGlobals() {
   d_workspace = NULL;
   d_table_view = NULL;
   imageLabel = NULL;
@@ -143,8 +136,7 @@ void Matrix::initGlobals()
   d_undo_stack->setUndoLimit(applicationWindow()->matrixUndoStackSize());
 }
 
-void Matrix::initTable(int rows, int cols)
-{
+void Matrix::initTable(int rows, int cols) {
   initGlobals();
   d_view_type = TableView;
 
@@ -152,12 +144,14 @@ void Matrix::initTable(int rows, int cols)
   initTableView();
 
   // resize the table
-  setGeometry(50, 50, QMIN(_Matrix_initial_columns_, cols)*d_table_view->horizontalHeader()->sectionSize(0) + 55,
-      (QMIN(_Matrix_initial_rows_,rows)+1)*d_table_view->verticalHeader()->sectionSize(0));
+  setGeometry(50, 50, QMIN(_Matrix_initial_columns_, cols) *
+                              d_table_view->horizontalHeader()->sectionSize(0) +
+                          55,
+              (QMIN(_Matrix_initial_rows_, rows) + 1) *
+                  d_table_view->verticalHeader()->sectionSize(0));
 }
 
-void Matrix::initImage(const QImage& image)
-{
+void Matrix::initImage(const QImage &image) {
   initGlobals();
   d_view_type = ImageView;
 
@@ -166,7 +160,7 @@ void Matrix::initImage(const QImage& image)
 
   int w = image.width();
   int h = image.height();
-  if (w <= 500 && h <= 400){
+  if (w <= 500 && h <= 400) {
     int size = QMAX(w, h);
     imageLabel->resize(size, size);
   } else
@@ -175,29 +169,22 @@ void Matrix::initImage(const QImage& image)
   displayImage(image);
 }
 
-double Matrix::cell(int row, int col)
-{
-  return d_matrix_model->cell(row, col);
-}
+double Matrix::cell(int row, int col) { return d_matrix_model->cell(row, col); }
 
-void Matrix::setCell(int row, int col, double value)
-{
+void Matrix::setCell(int row, int col, double value) {
   d_matrix_model->setCell(row, col, value);
 }
 
-QString Matrix::text(int row, int col)
-{
+QString Matrix::text(int row, int col) {
   return d_matrix_model->text(row, col);
 }
 
-void Matrix::setText (int row, int col, const QString & new_text )
-{
+void Matrix::setText(int row, int col, const QString &new_text) {
   d_matrix_model->setText(row, col, new_text);
 }
 
-void Matrix::setCoordinates(double xs, double xe, double ys, double ye)
-{
-  if (x_start == xs && x_end == xe &&	y_start == ys && y_end == ye)
+void Matrix::setCoordinates(double xs, double xe, double ys, double ye) {
+  if (x_start == xs && x_end == xe && y_start == ys && y_end == ye)
     return;
 
   x_start = xs;
@@ -208,8 +195,7 @@ void Matrix::setCoordinates(double xs, double xe, double ys, double ye)
   emit modifiedWindow(this);
 }
 
-void Matrix::restore(const QStringList &lst)
-{
+void Matrix::restore(const QStringList &lst) {
   QStringList l;
   QStringList::const_iterator i = lst.begin();
 
@@ -219,10 +205,10 @@ void Matrix::restore(const QStringList &lst)
   l = (*i++).split("\t");
   if (l[0] == "Formula")
     formula_str = l[1];
-  else if (l[0] == "<formula>"){
-    for(formula_str=""; i != lst.end() && *i != "</formula>"; ++i)
+  else if (l[0] == "<formula>") {
+    for (formula_str = ""; i != lst.end() && *i != "</formula>"; ++i)
       formula_str += *i + "\n";
-    formula_str.truncate(formula_str.length()-1);
+    formula_str.truncate(formula_str.length() - 1);
     ++i;
   }
 
@@ -245,16 +231,16 @@ void Matrix::restore(const QStringList &lst)
   l = (*i++).split("\t");
   d_color_map_type = (Matrix::ColorMapType)l[1].toInt();
 
-  if (lst.contains ("<ColorMap>")){
+  if (lst.contains("<ColorMap>")) {
     QStringList aux;
-    while (*i != "</ColorMap>"){
+    while (*i != "</ColorMap>") {
       aux << *i;
       ++i;
     }
     setColorMap(aux);
   }
 
-  if (d_view_type == ImageView){
+  if (d_view_type == ImageView) {
     if (d_table_view)
       delete d_table_view;
     if (d_select_all_shortcut)
@@ -267,8 +253,7 @@ void Matrix::restore(const QStringList &lst)
   resetView();
 }
 
-void Matrix::setNumericFormat(const QChar& f, int prec)
-{
+void Matrix::setNumericFormat(const QChar &f, int prec) {
   if (txt_format == f && num_precision == prec)
     return;
 
@@ -280,83 +265,87 @@ void Matrix::setNumericFormat(const QChar& f, int prec)
   QApplication::restoreOverrideCursor();
 }
 
-void Matrix::setTextFormat(const QChar &format, int precision)
-{
+void Matrix::setTextFormat(const QChar &format, int precision) {
   txt_format = format;
   num_precision = precision;
 }
 
-void Matrix::setColumnsWidth(int width)
-{
+void Matrix::setColumnsWidth(int width) {
   if (d_column_width == width)
     return;
 
   d_column_width = width;
   d_table_view->horizontalHeader()->setDefaultSectionSize(d_column_width);
 
-  if (d_view_type == TableView){
+  if (d_view_type == TableView) {
     int cols = numCols();
-    for(int i=0; i<cols; i++)
+    for (int i = 0; i < cols; i++)
       d_table_view->setColumnWidth(i, width);
   }
 
   emit modifiedWindow(this);
 }
 
-void Matrix::setDimensions(int rows, int cols)
-{
+void Matrix::setDimensions(int rows, int cols) {
   int r = numRows();
   int c = numCols();
   if (r == rows && c == cols)
     return;
 
-  if (rows <= 0 || cols <= 0 || INT_MAX/rows < cols) //avoid integer overflow
+  if (rows <= 0 || cols <= 0 || INT_MAX / rows < cols) // avoid integer overflow
   {
     QApplication::restoreOverrideCursor();
-    QMessageBox::critical(d_matrix_model->matrix(), tr("MantidPlot") + " - " + tr("Input Size Error"),
-      tr("The dimensions you have specified are not acceptable!") + "\n" +
-      tr("Please enter positive values for which the product rows*columns does not exceed the maximum integer value available (") +
-      tr(QString::number(INT_MAX).toAscii().constData()) + tr(")!"));
+    QMessageBox::critical(
+        d_matrix_model->matrix(),
+        tr("MantidPlot") + " - " + tr("Input Size Error"),
+        tr("The dimensions you have specified are not acceptable!") + "\n" +
+            tr("Please enter positive values for which the product "
+               "rows*columns does not exceed the maximum integer value "
+               "available (") +
+            tr(QString::number(INT_MAX).toAscii().constData()) + tr(")!"));
     return;
   }
 
-  if(rows*cols > r*c && !d_matrix_model->canResize(rows, cols))
+  if (rows * cols > r * c && !d_matrix_model->canResize(rows, cols))
     return;
 
   double *buffer = d_matrix_model->dataCopy();
   if (buffer)
-    d_undo_stack->push(new MatrixSetSizeCommand(d_matrix_model, QSize(r, c), QSize(rows, cols), buffer,
-        tr("Set Dimensions") + " " + QString::number(rows) + "x" + QString::number(cols)));
-  else if(ignoreUndo()){
+    d_undo_stack->push(new MatrixSetSizeCommand(
+        d_matrix_model, QSize(r, c), QSize(rows, cols), buffer,
+        tr("Set Dimensions") + " " + QString::number(rows) + "x" +
+            QString::number(cols)));
+  else if (ignoreUndo()) {
     d_matrix_model->setDimensions(rows, cols);
     resetView();
   }
   emit modifiedWindow(this);
 }
 
-double Matrix::integrate()
-{
+double Matrix::integrate() {
   int rows = numRows() - 1;
   int cols = numCols() - 1;
   double sum = 0.0;
-  for(int i=0; i<rows; i++){
+  for (int i = 0; i < rows; i++) {
     int i1 = i + 1;
-    for(int j=0; j<cols; j++){
+    for (int j = 0; j < cols; j++) {
       int j1 = j + 1;
-      sum += 0.25*(d_matrix_model->cell(i, j) + d_matrix_model->cell(i, j1) +
-          d_matrix_model->cell(i1, j) + d_matrix_model->cell(i1, j1));
+      sum +=
+          0.25 * (d_matrix_model->cell(i, j) + d_matrix_model->cell(i, j1) +
+                  d_matrix_model->cell(i1, j) + d_matrix_model->cell(i1, j1));
     }
   }
-  return sum*dx()*dy();
+  return sum * dx() * dy();
 }
 
-double Matrix::determinant()
-{
+double Matrix::determinant() {
   int rows = numRows();
   int cols = numCols();
 
-  if (rows != cols){
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(applicationWindow()), tr("MantidPlot - Error"),
+  if (rows != cols) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(applicationWindow()),
+        tr("MantidPlot - Error"),
         tr("Calculation failed, the matrix is not square!"));
     return GSL_POSINF;
   }
@@ -364,10 +353,11 @@ double Matrix::determinant()
   gsl_set_error_handler_off();
 
   gsl_matrix *A = gsl_matrix_alloc(rows, cols);
-  gsl_permutation * p = gsl_permutation_alloc(rows);
-  if (!A || !p){
+  gsl_permutation *p = gsl_permutation_alloc(rows);
+  if (!A || !p) {
     QApplication::restoreOverrideCursor();
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(applicationWindow()),
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(applicationWindow()),
         tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
         tr("Not enough memory, operation aborted!"));
     return 0.0;
@@ -377,11 +367,10 @@ double Matrix::determinant()
 
   double *data = d_matrix_model->dataVector();
   int i, cell = 0;
-  for(i=0; i<rows; i++)
-    for(int j=0; j<cols; j++)
+  for (i = 0; i < rows; i++)
+    for (int j = 0; j < cols; j++)
       gsl_matrix_set(A, i, j, data[cell++]);
 
-
   gsl_linalg_LU_decomp(A, p, &i);
   double det = gsl_linalg_LU_det(A, i);
 
@@ -392,64 +381,69 @@ double Matrix::determinant()
   return det;
 }
 
-void Matrix::invert()
-{
-  if (numRows() != numCols()){
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(applicationWindow()), tr("MantidPlot - Error"),
+void Matrix::invert() {
+  if (numRows() != numCols()) {
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(applicationWindow()),
+        tr("MantidPlot - Error"),
         tr("Inversion failed, the matrix is not square!"));
     return;
   }
-  if(d_matrix_model->initWorkspace())
-    d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, Invert, tr("Invert")));
+  if (d_matrix_model->initWorkspace())
+    d_undo_stack->push(
+        new MatrixSymmetryOperation(d_matrix_model, Invert, tr("Invert")));
 }
 
-void Matrix::transpose()
-{
-  initWorkspace(numRows()*numCols());
+void Matrix::transpose() {
+  initWorkspace(numRows() * numCols());
   if (!d_workspace)
     return;
 
-  d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, Transpose, tr("Transpose")));
+  d_undo_stack->push(
+      new MatrixSymmetryOperation(d_matrix_model, Transpose, tr("Transpose")));
 }
 
-void Matrix::flipVertically()
-{
-  initWorkspace(numRows()*numCols());
+void Matrix::flipVertically() {
+  initWorkspace(numRows() * numCols());
   if (!d_workspace)
     return;
 
-  d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, FlipVertically, tr("Flip Vertically")));
+  d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, FlipVertically,
+                                                 tr("Flip Vertically")));
 }
 
-void Matrix::flipHorizontally()
-{
-  initWorkspace(numRows()*numCols());
+void Matrix::flipHorizontally() {
+  initWorkspace(numRows() * numCols());
   if (!d_workspace)
     return;
 
-  d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, FlipHorizontally, tr("Flip Horizontally")));
+  d_undo_stack->push(new MatrixSymmetryOperation(
+      d_matrix_model, FlipHorizontally, tr("Flip Horizontally")));
 }
 
-void Matrix::rotate90(bool clockwise)
-{
-  initWorkspace(numRows()*numCols());
+void Matrix::rotate90(bool clockwise) {
+  initWorkspace(numRows() * numCols());
   if (!d_workspace)
     return;
 
   if (clockwise)
-    d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, RotateClockwise, tr("Rotate 90�")));
+    d_undo_stack->push(new MatrixSymmetryOperation(
+        d_matrix_model, RotateClockwise, tr("Rotate 90�")));
   else
-    d_undo_stack->push(new MatrixSymmetryOperation(d_matrix_model, RotateCounterClockwise, tr("Rotate -90�")));
+    d_undo_stack->push(new MatrixSymmetryOperation(
+        d_matrix_model, RotateCounterClockwise, tr("Rotate -90�")));
 }
 
-bool Matrix::canCalculate(bool useMuParser)
-{
+bool Matrix::canCalculate(bool useMuParser) {
   if (formula_str.isEmpty())
     return false;
 
-  if (useMuParser){
-    muParserScript *mup = new muParserScript(scriptingEnv(),QString("<%1>").arg(objectName()), this, false);
-    connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptingEnv(), SIGNAL(error(const QString&, const QString&,int)));
+  if (useMuParser) {
+    muParserScript *mup = new muParserScript(
+        scriptingEnv(), QString("<%1>").arg(objectName()), this, false);
+    connect(mup, SIGNAL(error(const QString &, const QString &, int)),
+            scriptingEnv(),
+            SIGNAL(error(const QString &, const QString &, int)));
 
     double *ri = mup->defineVariable("i");
     double *rr = mup->defineVariable("row");
@@ -462,20 +456,29 @@ bool Matrix::canCalculate(bool useMuParser)
       return false;
 
     double r = 1.0;
-    *ri = r; *rr = r; *y = r;
-    double c = 1.0; *cj = c; *cc = c; *x = c;
+    *ri = r;
+    *rr = r;
+    *y = r;
+    double c = 1.0;
+    *cj = c;
+    *cc = c;
+    *x = c;
     int codeLines = mup->codeLines();
     if (codeLines == 1 && gsl_isnan(mup->evalSingleLine()))
       return false;
-    else if (codeLines > 1){
+    else if (codeLines > 1) {
       QVariant res = mup->evaluate(ScriptCode(formula_str));
       if (!res.canConvert(QVariant::Double))
         return false;
     }
   } else {
-    Script *script = scriptingEnv()->newScript(QString("<%1>").arg(objectName()),this, Script::NonInteractive);
-    connect(script, SIGNAL(error(const QString&,const QString&,int)), scriptingEnv(), SIGNAL(error(const QString&,const QString&,int)));
-    connect(script, SIGNAL(print(const QString&)), scriptingEnv(), SIGNAL(print(const QString&)));
+    Script *script = scriptingEnv()->newScript(
+        QString("<%1>").arg(objectName()), this, Script::NonInteractive);
+    connect(script, SIGNAL(error(const QString &, const QString &, int)),
+            scriptingEnv(),
+            SIGNAL(error(const QString &, const QString &, int)));
+    connect(script, SIGNAL(print(const QString &)), scriptingEnv(),
+            SIGNAL(print(const QString &)));
 
     double r = 1.0;
     script->setDouble(r, "i");
@@ -495,16 +498,17 @@ bool Matrix::canCalculate(bool useMuParser)
   return true;
 }
 
-bool Matrix::muParserCalculate(int startRow, int endRow, int startCol, int endCol)
-{
+bool Matrix::muParserCalculate(int startRow, int endRow, int startCol,
+                               int endCol) {
   double *buffer = d_matrix_model->dataCopy(startRow, endRow, startCol, endCol);
 
-  if (buffer){
-    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, MuParserCalculate, startRow, endRow,
-        startCol, endCol, buffer, tr("Calculate Values")));
+  if (buffer) {
+    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, MuParserCalculate,
+                                             startRow, endRow, startCol, endCol,
+                                             buffer, tr("Calculate Values")));
     emit modifiedWindow(this);
     return true;
-  } else if(ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->muParserCalculate(startRow, endRow, startCol, endCol);
     emit modifiedWindow(this);
     return true;
@@ -512,18 +516,19 @@ bool Matrix::muParserCalculate(int startRow, int endRow, int startCol, int endCo
   return false;
 }
 
-bool Matrix::calculate(int startRow, int endRow, int startCol, int endCol, bool forceMuParser)
-{
+bool Matrix::calculate(int startRow, int endRow, int startCol, int endCol,
+                       bool forceMuParser) {
   if (QString(scriptingEnv()->objectName()) == "muParser" || forceMuParser)
     return muParserCalculate(startRow, endRow, startCol, endCol);
 
   double *buffer = d_matrix_model->dataCopy(startRow, endRow, startCol, endCol);
-  if (buffer){
-    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, Calculate, startRow, endRow,
-        startCol, endCol, buffer, tr("Calculate Values")));
+  if (buffer) {
+    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, Calculate,
+                                             startRow, endRow, startCol, endCol,
+                                             buffer, tr("Calculate Values")));
     emit modifiedWindow(this);
     return true;
-  } else if(ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->calculate(startRow, endRow, startCol, endCol);
     emit modifiedWindow(this);
     return true;
@@ -531,8 +536,7 @@ bool Matrix::calculate(int startRow, int endRow, int startCol, int endCol, bool
   return false;
 }
 
-void Matrix::clearSelection()
-{
+void Matrix::clearSelection() {
   if (d_view_type == ImageView)
     return;
 
@@ -546,30 +550,31 @@ void Matrix::clearSelection()
   int startCol = sel.left();
   int endCol = sel.right();
   double *buffer = d_matrix_model->dataCopy(startRow, endRow, startCol, endCol);
-  if (buffer){
-    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, Clear, startRow, endRow, startCol, endCol, buffer, tr("Clear Selection")));
+  if (buffer) {
+    d_undo_stack->push(new MatrixUndoCommand(d_matrix_model, Clear, startRow,
+                                             endRow, startCol, endCol, buffer,
+                                             tr("Clear Selection")));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->clear(startRow, endRow, startCol, endCol);
     emit modifiedWindow(this);
   }
 }
 
-void Matrix::copySelection()
-{
+void Matrix::copySelection() {
   if (d_view_type == ImageView)
     return;
 
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   QString s = "";
   QString eol = applicationWindow()->endOfLine();
-  if (!selModel->hasSelection()){
+  if (!selModel->hasSelection()) {
     QModelIndex index = selModel->currentIndex();
     s = text(index.row(), index.column());
   } else {
     QItemSelection sel = selModel->selection();
     QListIterator<QItemSelectionRange> it(sel);
-    if(!it.hasNext())
+    if (!it.hasNext())
       return;
 
     QItemSelectionRange cur = it.next();
@@ -577,18 +582,17 @@ void Matrix::copySelection()
     int bottom = cur.bottom();
     int left = cur.left();
     int right = cur.right();
-    for(int i=top; i<=bottom; i++){
-      for(int j=left; j<right; j++)
+    for (int i = top; i <= bottom; i++) {
+      for (int j = left; j < right; j++)
         s += d_matrix_model->text(i, j) + "\t";
-      s += d_matrix_model->text(i,right) + eol;
+      s += d_matrix_model->text(i, right) + eol;
     }
   }
   // Copy text into the clipboard
   QApplication::clipboard()->setText(s.trimmed());
 }
 
-void Matrix::pasteSelection()
-{
+void Matrix::pasteSelection() {
   if (d_view_type == ImageView)
     return;
 
@@ -598,13 +602,14 @@ void Matrix::pasteSelection()
 
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
-  QStringList linesList = text.split(applicationWindow()->endOfLine(), QString::SkipEmptyParts);
+  QStringList linesList =
+      text.split(applicationWindow()->endOfLine(), QString::SkipEmptyParts);
   int rows = linesList.size();
   if (!rows)
     return;
 
   int cols = linesList[0].split("\t").count();
-  for (int i = 1; i < rows; i++){
+  for (int i = 1; i < rows; i++) {
     int aux = linesList[i].split("\t").count();
     if (aux > cols)
       cols = aux;
@@ -612,7 +617,7 @@ void Matrix::pasteSelection()
 
   int topRow = 0, leftCol = 0;
   QItemSelectionModel *selModel = d_table_view->selectionModel();
-  if (selModel->hasSelection()){
+  if (selModel->hasSelection()) {
     QItemSelectionRange sel = selModel->selection()[0];
     topRow = sel.top();
     leftCol = sel.left();
@@ -628,21 +633,22 @@ void Matrix::pasteSelection()
   if (rightCol > oldCols - 1)
     rightCol = oldCols - 1;
 
-  double *clipboardBuffer = (double *)malloc(rows*cols*sizeof(double));
-  if (!clipboardBuffer){
-    QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-        tr("Not enough memory, operation aborted!"));
+  double *clipboardBuffer = (double *)malloc(rows * cols * sizeof(double));
+  if (!clipboardBuffer) {
+    QMessageBox::critical(this, tr("MantidPlot") + " - " +
+                                    tr("Memory Allocation Error"),
+                          tr("Not enough memory, operation aborted!"));
     QApplication::restoreOverrideCursor();
     return;
   }
 
-  QLocale locale = this->locale(); //Better use QLocale::system() ??
+  QLocale locale = this->locale(); // Better use QLocale::system() ??
   int cell = 0;
-  for(int i = 0; i < rows; i++){
+  for (int i = 0; i < rows; i++) {
     QStringList cells = linesList[i].split("\t");
     int size = cells.count();
-    for(int j = 0; j<cols; j++){
-      if (j >= size){
+    for (int j = 0; j < cols; j++) {
+      if (j >= size) {
         clipboardBuffer[cell++] = GSL_NAN;
         continue;
       }
@@ -657,13 +663,14 @@ void Matrix::pasteSelection()
 
   QApplication::restoreOverrideCursor();
 
-  double *backupBuffer = d_matrix_model->dataCopy(topRow, bottomRow, leftCol, rightCol);
-  if (backupBuffer){
-    d_undo_stack->push(new MatrixPasteCommand(d_matrix_model, topRow, bottomRow,
-        leftCol, rightCol, clipboardBuffer, rows, cols, backupBuffer, oldRows,
-        oldCols, tr("Paste")));
+  double *backupBuffer =
+      d_matrix_model->dataCopy(topRow, bottomRow, leftCol, rightCol);
+  if (backupBuffer) {
+    d_undo_stack->push(new MatrixPasteCommand(
+        d_matrix_model, topRow, bottomRow, leftCol, rightCol, clipboardBuffer,
+        rows, cols, backupBuffer, oldRows, oldCols, tr("Paste")));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->pasteData(clipboardBuffer, topRow, leftCol, rows, cols);
     emit modifiedWindow(this);
   }
@@ -671,14 +678,12 @@ void Matrix::pasteSelection()
   free(clipboardBuffer);
 }
 
-void Matrix::cutSelection()
-{
+void Matrix::cutSelection() {
   copySelection();
   clearSelection();
 }
 
-void Matrix::deleteSelectedRows()
-{
+void Matrix::deleteSelectedRows() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return;
@@ -686,8 +691,8 @@ void Matrix::deleteSelectedRows()
   int startRow = -1;
   int count = 0;
   int rows = numRows();
-  for (int i=0; i<rows; i++){
-    if (selModel->isRowSelected (i, QModelIndex())){
+  for (int i = 0; i < rows; i++) {
+    if (selModel->isRowSelected(i, QModelIndex())) {
       if (startRow < 0)
         startRow = i;
       ++count;
@@ -696,20 +701,22 @@ void Matrix::deleteSelectedRows()
   if (startRow < 0 || !count)
     return;
 
-  double *buffer = d_matrix_model->dataCopy(startRow, startRow + count - 1, 0, numCols() - 1);
-  if (buffer){
-    d_undo_stack->push(new MatrixDeleteRowsCommand(d_matrix_model, startRow, count, buffer, tr("Delete Rows") + " " +
-        QString::number(startRow + 1) + " - " + QString::number(startRow + count)));
+  double *buffer = d_matrix_model->dataCopy(startRow, startRow + count - 1, 0,
+                                            numCols() - 1);
+  if (buffer) {
+    d_undo_stack->push(new MatrixDeleteRowsCommand(
+        d_matrix_model, startRow, count, buffer,
+        tr("Delete Rows") + " " + QString::number(startRow + 1) + " - " +
+            QString::number(startRow + count)));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->removeRows(startRow, count);
     d_table_view->reset();
     emit modifiedWindow(this);
   }
 }
 
-void Matrix::deleteSelectedColumns()
-{
+void Matrix::deleteSelectedColumns() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return;
@@ -717,8 +724,8 @@ void Matrix::deleteSelectedColumns()
   int startCol = -1;
   int count = 0;
   int cols = numCols();
-  for (int i=0; i<cols; i++){
-    if (selModel->isColumnSelected(i, QModelIndex())){
+  for (int i = 0; i < cols; i++) {
+    if (selModel->isColumnSelected(i, QModelIndex())) {
       if (startCol < 0)
         startCol = i;
       ++count;
@@ -727,50 +734,50 @@ void Matrix::deleteSelectedColumns()
   if (startCol < 0 || !count)
     return;
 
-  double *buffer = d_matrix_model->dataCopy(0, numRows() - 1, startCol, startCol + count - 1);
-  if (buffer){
-    d_undo_stack->push(new MatrixDeleteColsCommand(d_matrix_model, startCol, count, buffer, tr("Delete Columns") + " " +
-        QString::number(startCol + 1) + " - " + QString::number(startCol + count)));
+  double *buffer = d_matrix_model->dataCopy(0, numRows() - 1, startCol,
+                                            startCol + count - 1);
+  if (buffer) {
+    d_undo_stack->push(new MatrixDeleteColsCommand(
+        d_matrix_model, startCol, count, buffer,
+        tr("Delete Columns") + " " + QString::number(startCol + 1) + " - " +
+            QString::number(startCol + count)));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->removeColumns(startCol, count);
     d_table_view->reset();
     emit modifiedWindow(this);
   }
 }
 
-int Matrix::numSelectedRows()
-{
+int Matrix::numSelectedRows() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return 0;
 
   int rows = numRows();
   int count = 0;
-  for (int i = 0; i<rows; i++){
-    if (selModel->isRowSelected (i, QModelIndex()))
+  for (int i = 0; i < rows; i++) {
+    if (selModel->isRowSelected(i, QModelIndex()))
       count++;
   }
   return count;
 }
 
-int Matrix::numSelectedColumns()
-{
+int Matrix::numSelectedColumns() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return 0;
 
   int cols = numCols();
   int count = 0;
-  for (int i = 0; i<cols; i++){
-    if (selModel->isColumnSelected (i, QModelIndex()))
+  for (int i = 0; i < cols; i++) {
+    if (selModel->isColumnSelected(i, QModelIndex()))
       count++;
   }
   return count;
 }
 
-void Matrix::insertRow()
-{
+void Matrix::insertRow() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return;
@@ -782,14 +789,14 @@ void Matrix::insertRow()
   if (!d_matrix_model->canResize(numRows() + 1, numCols()))
     return;
 
-  d_undo_stack->push(new MatrixInsertRowCommand(d_matrix_model, index.row(), tr("Insert Row") + " " +
-      QString::number(index.row() + 1)));
+  d_undo_stack->push(new MatrixInsertRowCommand(
+      d_matrix_model, index.row(),
+      tr("Insert Row") + " " + QString::number(index.row() + 1)));
   d_table_view->reset();
   emit modifiedWindow(this);
 }
 
-void Matrix::insertColumn()
-{
+void Matrix::insertColumn() {
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
     return;
@@ -801,53 +808,53 @@ void Matrix::insertColumn()
   if (!d_matrix_model->canResize(numRows(), numCols() + 1))
     return;
 
-  d_undo_stack->push(new MatrixInsertColCommand(d_matrix_model, index.column(), tr("Insert Column") + " " +
-      QString::number(index.column() + 1)));
+  d_undo_stack->push(new MatrixInsertColCommand(
+      d_matrix_model, index.column(),
+      tr("Insert Column") + " " + QString::number(index.column() + 1)));
   d_table_view->reset();
   emit modifiedWindow(this);
 }
 
-void Matrix::customEvent(QEvent *e)
-{
-  if (e->type() == SCRIPTING_CHANGE_EVENT){
-    if (auto sce = dynamic_cast<ScriptingChangeEvent*>(e)) {
+void Matrix::customEvent(QEvent *e) {
+  if (e->type() == SCRIPTING_CHANGE_EVENT) {
+    if (auto sce = dynamic_cast<ScriptingChangeEvent *>(e)) {
       scriptingChangeEvent(sce);
     }
   }
 }
 
-void Matrix::exportRasterImage(const QString& fileName, int quality)
-{
+void Matrix::exportRasterImage(const QString &fileName, int quality) {
   d_matrix_model->renderImage().save(fileName, 0, quality);
 }
 
-void Matrix::exportToFile(const QString& fileName)
-{
-  if ( fileName.isEmpty() ){
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please provide a valid file name!"));
+void Matrix::exportToFile(const QString &fileName) {
+  if (fileName.isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"),
+                          tr("Please provide a valid file name!"));
     return;
   }
 
-  if (fileName.contains(".eps") || fileName.contains(".pdf") || fileName.contains(".ps")){
+  if (fileName.contains(".eps") || fileName.contains(".pdf") ||
+      fileName.contains(".ps")) {
     exportVector(fileName);
     return;
-  } else if(fileName.contains(".svg")){
+  } else if (fileName.contains(".svg")) {
     exportSVG(fileName);
     return;
   } else {
     QList<QByteArray> list = QImageWriter::supportedImageFormats();
-    for(int i=0 ; i<list.count() ; i++){
-      if (fileName.contains( "." + list[i].toLower())){
+    for (int i = 0; i < list.count(); i++) {
+      if (fileName.contains("." + list[i].toLower())) {
         d_matrix_model->renderImage().save(fileName, list[i], 100);
         return;
       }
     }
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("File format not handled, operation aborted!"));
+    QMessageBox::critical(this, tr("MantidPlot - Error"),
+                          tr("File format not handled, operation aborted!"));
   }
 }
 
-void Matrix::exportSVG(const QString& fileName)
-{
+void Matrix::exportSVG(const QString &fileName) {
 #if QT_VERSION >= 0x040300
   if (d_view_type != ImageView)
     return;
@@ -860,27 +867,20 @@ void Matrix::exportSVG(const QString& fileName)
   svg.setSize(QSize(width, height));
 
   QPainter p(&svg);
-  p.drawImage (QRect(0, 0, width, height), d_matrix_model->renderImage());
+  p.drawImage(QRect(0, 0, width, height), d_matrix_model->renderImage());
   p.end();
 #endif
 }
 
-void Matrix::exportPDF(const QString& fileName)
-{
-  print(fileName);
-}
+void Matrix::exportPDF(const QString &fileName) { print(fileName); }
 
-void Matrix::print()
-{
-  print(QString());
-}
+void Matrix::print() { print(QString()); }
 
-void Matrix::print(const QString& fileName)
-{
+void Matrix::print(const QString &fileName) {
   QPrinter printer;
-  printer.setColorMode (QPrinter::GrayScale);
+  printer.setColorMode(QPrinter::GrayScale);
 
-  if (!fileName.isEmpty()){
+  if (!fileName.isEmpty()) {
     printer.setCreator("MantidPlot");
     printer.setOutputFormat(QPrinter::PdfFormat);
     printer.setOutputFileName(fileName);
@@ -889,15 +889,15 @@ void Matrix::print(const QString& fileName)
     if (printDialog.exec() != QDialog::Accepted)
       return;
   }
-  printer.setFullPage( true );
+  printer.setFullPage(true);
   QPainter p;
-  if ( !p.begin(&printer ) )
+  if (!p.begin(&printer))
     return; // paint on printer
   int dpiy = printer.logicalDpiY();
-  const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins
+  const int margin = (int)((1 / 2.54) * dpiy); // 1 cm margins
 
-  if (d_view_type == ImageView){
-    p.drawImage (printer.pageRect(), d_matrix_model->renderImage());
+  if (d_view_type == ImageView) {
+    p.drawImage(printer.pageRect(), d_matrix_model->renderImage());
     return;
   }
 
@@ -911,62 +911,65 @@ void Matrix::print(const QString& fileName)
 
   // print header
   p.setFont(QFont());
-  QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString();
+  QString header_label =
+      d_matrix_model->headerData(0, Qt::Horizontal).toString();
   QRect br;
   br = p.boundingRect(br, Qt::AlignCenter, header_label);
-  p.drawLine(right, height, right, height+br.height());
+  p.drawLine(right, height, right, height + br.height());
   QRect tr(br);
 
-  for(i=0; i<cols; i++){
+  for (i = 0; i < cols; i++) {
     int w = d_table_view->columnWidth(i);
-    tr.setTopLeft(QPoint(right,height));
+    tr.setTopLeft(QPoint(right, height));
     tr.setWidth(w);
     tr.setHeight(br.height());
     header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString();
     p.drawText(tr, Qt::AlignCenter, header_label.left(-1));
     right += w;
-    p.drawLine(right, height, right, height+tr.height());
+    p.drawLine(right, height, right, height + tr.height());
 
-    if (right >= printer.width()-2*margin )
+    if (right >= printer.width() - 2 * margin)
       break;
   }
 
-  p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line
+  p.drawLine(margin + vertHeaderWidth, height, right - 1,
+             height); // first horizontal line
   height += tr.height();
-  p.drawLine(margin, height, right-1, height);
+  p.drawLine(margin, height, right - 1, height);
 
   // print table values
-  for(i=0;i<rows;i++){
+  for (i = 0; i < rows; i++) {
     right = margin;
-    QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t";
+    QString cell_text =
+        d_matrix_model->headerData(i, Qt::Horizontal).toString() + "\t";
     tr = p.boundingRect(tr, Qt::AlignCenter, cell_text);
-    p.drawLine(right, height, right, height+tr.height());
+    p.drawLine(right, height, right, height + tr.height());
 
-    br.setTopLeft(QPoint(right,height));
+    br.setTopLeft(QPoint(right, height));
     br.setWidth(vertHeaderWidth);
     br.setHeight(tr.height());
     p.drawText(br, Qt::AlignCenter, cell_text.left(-1));
     right += vertHeaderWidth;
-    p.drawLine(right, height, right, height+tr.height());
+    p.drawLine(right, height, right, height + tr.height());
 
-    for(int j=0; j<cols; j++){
-      int w = d_table_view->columnWidth (j);
-      cell_text = text(i,j)+"\t";
-      tr = p.boundingRect(tr,Qt::AlignCenter,cell_text);
-      br.setTopLeft(QPoint(right,height));
+    for (int j = 0; j < cols; j++) {
+      int w = d_table_view->columnWidth(j);
+      cell_text = text(i, j) + "\t";
+      tr = p.boundingRect(tr, Qt::AlignCenter, cell_text);
+      br.setTopLeft(QPoint(right, height));
       br.setWidth(w);
       br.setHeight(tr.height());
       p.drawText(br, Qt::AlignCenter, cell_text.left(-1));
       right += w;
-      p.drawLine(right, height, right, height+tr.height());
+      p.drawLine(right, height, right, height + tr.height());
 
-      if (right >= printer.width()-2*margin )
+      if (right >= printer.width() - 2 * margin)
         break;
     }
     height += br.height();
-    p.drawLine(margin, height, right-1, height);
+    p.drawLine(margin, height, right - 1, height);
 
-    if (height >= printer.height()-margin ){
+    if (height >= printer.height() - margin) {
       printer.newPage();
       height = margin;
       p.drawLine(margin, height, right, height);
@@ -974,13 +977,14 @@ void Matrix::print(const QString& fileName)
   }
 }
 
-void Matrix::exportVector(const QString& fileName, int res, bool color, bool keepAspect, QPrinter::PageSize pageSize)
-{
+void Matrix::exportVector(const QString &fileName, int res, bool color,
+                          bool keepAspect, QPrinter::PageSize pageSize) {
   if (d_view_type != ImageView)
     return;
 
-  if ( fileName.isEmpty() ){
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please provide a valid file name!"));
+  if (fileName.isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"),
+                          tr("Please provide a valid file name!"));
     return;
   }
 
@@ -1007,32 +1011,32 @@ void Matrix::exportVector(const QString& fileName, int res, bool color, bool kee
   else
     printer.setPageSize(pageSize);
 
-  double aspect = (double)cols/(double)rows;
+  double aspect = (double)cols / (double)rows;
   if (aspect < 1)
     printer.setOrientation(QPrinter::Portrait);
   else
     printer.setOrientation(QPrinter::Landscape);
 
-  if (keepAspect){// export should preserve aspect ratio
-    double page_aspect = double(printer.width())/double(printer.height());
-    if (page_aspect > aspect){
-      int margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins
-      int height = printer.height() - 2*margin;
-      int width = static_cast<int>(height*aspect);
-      int x = (printer.width()- width)/2;
+  if (keepAspect) { // export should preserve aspect ratio
+    double page_aspect = double(printer.width()) / double(printer.height());
+    if (page_aspect > aspect) {
+      int margin = (int)((0.1 / 2.54) * printer.logicalDpiY()); // 1 mm margins
+      int height = printer.height() - 2 * margin;
+      int width = static_cast<int>(height * aspect);
+      int x = (printer.width() - width) / 2;
       rect = QRect(x, margin, width, height);
     } else {
-      int margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins
-      int width = printer.width() - 2*margin;
-      int height = static_cast<int>(width/aspect);
-      int y = (printer.height()- height)/2;
+      int margin = (int)((0.1 / 2.54) * printer.logicalDpiX()); // 1 mm margins
+      int width = printer.width() - 2 * margin;
+      int height = static_cast<int>(width / aspect);
+      int y = (printer.height() - height) / 2;
       rect = QRect(margin, y, width, height);
     }
   } else {
-    int x_margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins
-    int y_margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins
-    int width = printer.width() - 2*x_margin;
-    int height = printer.height() - 2*y_margin;
+    int x_margin = (int)((0.1 / 2.54) * printer.logicalDpiX()); // 1 mm margins
+    int y_margin = (int)((0.1 / 2.54) * printer.logicalDpiY()); // 1 mm margins
+    int width = printer.width() - 2 * x_margin;
+    int height = printer.height() - 2 * y_margin;
     rect = QRect(x_margin, y_margin, width, height);
   }
 
@@ -1041,15 +1045,14 @@ void Matrix::exportVector(const QString& fileName, int res, bool color, bool kee
   paint.end();
 }
 
-void Matrix::range(double *min, double *max)
-{
+void Matrix::range(double *min, double *max) {
   double d_min = cell(0, 0);
   double d_max = d_min;
   int rows = numRows();
   int cols = numCols();
 
-  for(int i=0; i<rows; i++){
-    for(int j=0; j<cols; j++){
+  for (int i = 0; i < rows; i++) {
+    for (int j = 0; j < cols; j++) {
       double aux = cell(i, j);
       if (aux <= d_min)
         d_min = aux;
@@ -1063,70 +1066,71 @@ void Matrix::range(double *min, double *max)
   *max = d_max;
 }
 
-double** Matrix::allocateMatrixData(int rows, int columns)
-{
-  double** data = (double **)malloc(rows * sizeof (double*));
-  if(!data){
-    QMessageBox::critical(0, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-        tr("Not enough memory, operation aborted!"));
+double **Matrix::allocateMatrixData(int rows, int columns) {
+  double **data = (double **)malloc(rows * sizeof(double *));
+  if (!data) {
+    QMessageBox::critical(0, tr("MantidPlot") + " - " +
+                                 tr("Memory Allocation Error"),
+                          tr("Not enough memory, operation aborted!"));
     return NULL;
   }
 
-  for ( int i = 0; i < rows; ++i){
-    data[i] = (double *)malloc(columns * sizeof (double));
-    if(!data[i]){
-      for ( int j = 0; j < i; j++)
+  for (int i = 0; i < rows; ++i) {
+    data[i] = (double *)malloc(columns * sizeof(double));
+    if (!data[i]) {
+      for (int j = 0; j < i; j++)
         free(data[j]);
       free(data);
 
-      QMessageBox::critical(0, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-          tr("Not enough memory, operation aborted!"));
+      QMessageBox::critical(0, tr("MantidPlot") + " - " +
+                                   tr("Memory Allocation Error"),
+                            tr("Not enough memory, operation aborted!"));
       return NULL;
     }
   }
   return data;
 }
 
-void Matrix::freeMatrixData(double **data, int rows)
-{
-  for ( int i = 0; i < rows; i++)
+void Matrix::freeMatrixData(double **data, int rows) {
+  for (int i = 0; i < rows; i++)
     free(data[i]);
 
   free(data);
 }
 
-void Matrix::goToRow(int row)
-{
-  if(row < 1 || row > numRows())
+void Matrix::goToRow(int row) {
+  if (row < 1 || row > numRows())
     return;
 
   if (d_view_type == ImageView)
-    d_undo_stack->push(new MatrixSetViewCommand(this, d_view_type, TableView, tr("Set Data Mode")));
+    d_undo_stack->push(new MatrixSetViewCommand(this, d_view_type, TableView,
+                                                tr("Set Data Mode")));
   d_table_view->selectRow(row - 1);
-  d_table_view->scrollTo(d_matrix_model->index(row - 1, 0), QAbstractItemView::PositionAtTop);
+  d_table_view->scrollTo(d_matrix_model->index(row - 1, 0),
+                         QAbstractItemView::PositionAtTop);
 }
 
-void Matrix::goToColumn(int col)
-{
-  if(col < 1 || col > numCols())
+void Matrix::goToColumn(int col) {
+  if (col < 1 || col > numCols())
     return;
 
   if (d_view_type == ImageView)
-    d_undo_stack->push(new MatrixSetViewCommand(this, d_view_type, TableView, tr("Set Data Mode")));
+    d_undo_stack->push(new MatrixSetViewCommand(this, d_view_type, TableView,
+                                                tr("Set Data Mode")));
   d_table_view->selectColumn(col - 1);
-  d_table_view->scrollTo(d_matrix_model->index(0, col - 1), QAbstractItemView::PositionAtCenter);
+  d_table_view->scrollTo(d_matrix_model->index(0, col - 1),
+                         QAbstractItemView::PositionAtCenter);
 }
 
-void Matrix::moveCell(const QModelIndex& index)
-{
+void Matrix::moveCell(const QModelIndex &index) {
   if (!index.isValid())
     return;
 
-  d_table_view->setCurrentIndex(d_matrix_model->index(index.row() + 1, index.column()));
+  d_table_view->setCurrentIndex(
+      d_matrix_model->index(index.row() + 1, index.column()));
 }
 
-void Matrix::copy(Matrix *m)
-{
+void Matrix::copy(Matrix *m) {
   if (!m)
     return;
 
@@ -1147,8 +1151,8 @@ void Matrix::copy(Matrix *m)
 
   double *data = d_matrix_model->dataVector();
   double *m_data = mModel->dataVector();
-  int size = rows*cols;
-  for (int i=0; i<size; i++)
+  int size = rows * cols;
+  for (int i = 0; i < size; i++)
     data[i] = m_data[i];
 
   d_header_view_type = m->headerViewType();
@@ -1158,7 +1162,7 @@ void Matrix::copy(Matrix *m)
   d_color_map_type = m->colorMapType();
   d_color_map = m->colorMap();
 
-  if (d_view_type == ImageView){
+  if (d_view_type == ImageView) {
     if (d_table_view)
       delete d_table_view;
     if (d_select_all_shortcut)
@@ -1169,34 +1173,33 @@ void Matrix::copy(Matrix *m)
   resetView();
 }
 
-void Matrix::displayImage(const QImage& image)
-{
+void Matrix::displayImage(const QImage &image) {
   if (!imageLabel)
     return;
 
   QImage im(imageLabel->size(), QImage::Format_RGB32);
   im.fill(0);
   QPainter p(&im);
-  p.drawImage(0, 0, image.scaled(imageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
+  p.drawImage(0, 0, image.scaled(imageLabel->size(), Qt::KeepAspectRatio,
+                                 Qt::SmoothTransformation));
   p.end();
   imageLabel->setPixmap(QPixmap::fromImage(im));
 }
 
-void Matrix::setViewType(ViewType type, bool renderImage)
-{
+void Matrix::setViewType(ViewType type, bool renderImage) {
   if (d_view_type == type)
     return;
 
   d_view_type = type;
 
-  if (d_view_type == ImageView){
+  if (d_view_type == ImageView) {
     delete d_table_view;
     delete d_select_all_shortcut;
     initImageView();
     if (renderImage)
       displayImage(d_matrix_model->renderImage());
     d_stack->setCurrentWidget(imageLabel);
-  } else if (d_view_type == TableView){
+  } else if (d_view_type == TableView) {
     delete imageLabel;
     initTableView();
     d_stack->setCurrentWidget(d_table_view);
@@ -1204,8 +1207,7 @@ void Matrix::setViewType(ViewType type, bool renderImage)
   emit modifiedWindow(this);
 }
 
-void Matrix::initImageView()
-{
+void Matrix::initImageView() {
   imageLabel = new QLabel();
   imageLabel->setBackgroundRole(QPalette::Base);
   imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
@@ -1213,11 +1215,13 @@ void Matrix::initImageView()
   d_stack->addWidget(imageLabel);
 }
 
-void Matrix::initTableView()
-{
+void Matrix::initTableView() {
   d_table_view = new QTableView();
-  d_table_view->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
-  d_table_view->setSelectionMode(QAbstractItemView::ContiguousSelection);// only one contiguous selection supported
+  d_table_view->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+  d_table_view->setSelectionMode(
+      QAbstractItemView::ContiguousSelection); // only one contiguous selection
+                                               // supported
   d_table_view->setModel(d_matrix_model);
   d_table_view->setEditTriggers(QAbstractItemView::DoubleClicked);
   d_table_view->setFocusPolicy(Qt::StrongFocus);
@@ -1228,44 +1232,43 @@ void Matrix::initTableView()
   d_table_view->setPalette(pal);
 
   // set header properties
-  QHeaderView* hHeader = (QHeaderView*)d_table_view->horizontalHeader();
+  QHeaderView *hHeader = (QHeaderView *)d_table_view->horizontalHeader();
   hHeader->setMovable(false);
   hHeader->setResizeMode(QHeaderView::Fixed);
   hHeader->setDefaultSectionSize(d_column_width);
 
   int cols = numCols();
-  for(int i=0; i<cols; i++)
+  for (int i = 0; i < cols; i++)
     d_table_view->setColumnWidth(i, d_column_width);
 
-  QHeaderView* vHeader = (QHeaderView*)d_table_view->verticalHeader();
+  QHeaderView *vHeader = (QHeaderView *)d_table_view->verticalHeader();
   vHeader->setMovable(false);
   vHeader->setResizeMode(QHeaderView::ResizeToContents);
 
   d_stack->addWidget(d_table_view);
 
   // recreate keyboard shortcut
-  d_select_all_shortcut = new QShortcut(QKeySequence(tr("Ctrl+A", "Matrix: select all")), this);
-  connect(d_select_all_shortcut, SIGNAL(activated()), d_table_view, SLOT(selectAll()));
+  d_select_all_shortcut =
+      new QShortcut(QKeySequence(tr("Ctrl+A", "Matrix: select all")), this);
+  connect(d_select_all_shortcut, SIGNAL(activated()), d_table_view,
+          SLOT(selectAll()));
 }
 
-QImage Matrix::image()
-{
-  return d_matrix_model->renderImage();
-}
+QImage Matrix::image() { return d_matrix_model->renderImage(); }
 
-void Matrix::importImage(const QString& fn)
-{
+void Matrix::importImage(const QString &fn) {
   QImage image(fn);
   if (image.isNull())
     return;
 
   double *buffer = d_matrix_model->dataCopy();
-  if (buffer){
-    d_undo_stack->push(new MatrixSetImageCommand(d_matrix_model, image, d_view_type, 0,
-        numRows() - 1, 0, numCols() - 1, buffer, tr("Import Image") + " \"" + fn + "\""));
+  if (buffer) {
+    d_undo_stack->push(new MatrixSetImageCommand(
+        d_matrix_model, image, d_view_type, 0, numRows() - 1, 0, numCols() - 1,
+        buffer, tr("Import Image") + " \"" + fn + "\""));
     setWindowLabel(fn);
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->setImage(image);
     setViewType(ImageView, false);
     displayImage(image);
@@ -1274,8 +1277,7 @@ void Matrix::importImage(const QString& fn)
   }
 }
 
-void Matrix::setGrayScale()
-{
+void Matrix::setGrayScale() {
   d_color_map_type = GrayScale;
   d_color_map = QwtLinearColorMap(Qt::black, Qt::white);
   if (d_view_type == ImageView)
@@ -1283,8 +1285,7 @@ void Matrix::setGrayScale()
   emit modifiedWindow(this);
 }
 
-void Matrix::setRainbowColorMap()
-{
+void Matrix::setRainbowColorMap() {
   d_color_map_type = Rainbow;
 
   d_color_map = QwtLinearColorMap(Qt::blue, Qt::red);
@@ -1297,8 +1298,7 @@ void Matrix::setRainbowColorMap()
   emit modifiedWindow(this);
 }
 
-void Matrix::setColorMap(const QwtLinearColorMap& map)
-{
+void Matrix::setColorMap(const QwtLinearColorMap &map) {
   d_color_map_type = Custom;
   d_color_map = map;
   if (d_view_type == ImageView)
@@ -1307,8 +1307,7 @@ void Matrix::setColorMap(const QwtLinearColorMap& map)
   emit modifiedWindow(this);
 }
 
-void Matrix::setColorMap(const QStringList& lst)
-{
+void Matrix::setColorMap(const QStringList &lst) {
   d_color_map_type = Custom;
 
   QStringList::const_iterator line = lst.begin();
@@ -1316,16 +1315,19 @@ void Matrix::setColorMap(const QStringList& lst)
 
   int mode = s.remove("<Mode>").remove("</Mode>").trimmed().toInt();
   s = *(++line);
-  QColor color1 = QColor(s.remove("<MinColor>").remove("</MinColor>").trimmed());
+  QColor color1 =
+      QColor(s.remove("<MinColor>").remove("</MinColor>").trimmed());
   s = *(++line);
-  QColor color2 = QColor(s.remove("<MaxColor>").remove("</MaxColor>").trimmed());
+  QColor color2 =
+      QColor(s.remove("<MaxColor>").remove("</MaxColor>").trimmed());
 
   d_color_map = QwtLinearColorMap(color1, color2);
   d_color_map.setMode((QwtLinearColorMap::Mode)mode);
 
   s = *(++line);
-  int stops = s.remove("<ColorStops>").remove("</ColorStops>").trimmed().toInt();
-  for (int i = 0; i < stops; i++){
+  int stops =
+      s.remove("<ColorStops>").remove("</ColorStops>").trimmed().toInt();
+  for (int i = 0; i < stops; i++) {
     s = (*(++line)).trimmed();
     s.remove("<Stop>").remove("</Stop>");
     auto l = s.split("\t");
@@ -1333,8 +1335,7 @@ void Matrix::setColorMap(const QStringList& lst)
   }
 }
 
-void Matrix::setColorMapType(ColorMapType mapType)
-{
+void Matrix::setColorMapType(ColorMapType mapType) {
   d_color_map_type = mapType;
 
   if (d_color_map_type == GrayScale)
@@ -1343,11 +1344,10 @@ void Matrix::setColorMapType(ColorMapType mapType)
     setRainbowColorMap();
 }
 
-void Matrix::resetView()
-{
+void Matrix::resetView() {
   if (d_view_type == ImageView)
     displayImage(d_matrix_model->renderImage());
-  else if (d_view_type == TableView){
+  else if (d_view_type == TableView) {
     d_table_view->horizontalHeader()->setDefaultSectionSize(d_column_width);
     d_table_view->horizontalHeader()->reset();
     d_table_view->verticalHeader()->reset();
@@ -1358,8 +1358,7 @@ void Matrix::resetView()
   }
 }
 
-void Matrix::setHeaderViewType(HeaderViewType type)
-{
+void Matrix::setHeaderViewType(HeaderViewType type) {
   if (d_header_view_type == type)
     return;
 
@@ -1370,52 +1369,56 @@ void Matrix::setHeaderViewType(HeaderViewType type)
   emit modifiedWindow(this);
 }
 
-QwtDoubleRect Matrix::boundingRect()
-{
+QwtDoubleRect Matrix::boundingRect() {
   int rows = numRows();
   int cols = numCols();
-  double dx = fabs(x_end - x_start)/(double)(cols - 1);
-  double dy = fabs(y_end - y_start)/(double)(rows - 1);
+  double dx = fabs(x_end - x_start) / (double)(cols - 1);
+  double dy = fabs(y_end - y_start) / (double)(rows - 1);
 
-  return QwtDoubleRect(QMIN(x_start, x_end) - 0.5*dx, QMIN(y_start, y_end) - 0.5*dy,
-      fabs(x_end - x_start) + dx, fabs(y_end - y_start) + dy).normalized();
+  return QwtDoubleRect(QMIN(x_start, x_end) - 0.5 * dx,
+                       QMIN(y_start, y_end) - 0.5 * dy,
+                       fabs(x_end - x_start) + dx,
+                       fabs(y_end - y_start) + dy).normalized();
 }
 
-void Matrix::fft(bool inverse)
-{
+void Matrix::fft(bool inverse) {
   double *buffer = d_matrix_model->dataCopy();
-  if (buffer){
+  if (buffer) {
     QString commandText = inverse ? tr("Inverse FFT") : tr("Forward FFT");
-    d_undo_stack->push(new MatrixFftCommand(inverse, d_matrix_model, 0, numRows() - 1,
-        0, numCols() - 1, buffer, commandText));
+    d_undo_stack->push(new MatrixFftCommand(inverse, d_matrix_model, 0,
+                                            numRows() - 1, 0, numCols() - 1,
+                                            buffer, commandText));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
+  } else if (ignoreUndo()) {
     d_matrix_model->fft(inverse);
     emit modifiedWindow(this);
   }
 }
 
-bool Matrix::exportASCII(const QString& fname, const QString& separator, bool exportSelection)
-{
+bool Matrix::exportASCII(const QString &fname, const QString &separator,
+                         bool exportSelection) {
   QFile f(fname);
-  if ( !f.open( QIODevice::WriteOnly ) ){
+  if (!f.open(QIODevice::WriteOnly)) {
     QApplication::restoreOverrideCursor();
-    QMessageBox::critical(this, tr("MantidPlot - ASCII Export Error"),
-        tr("Could not write to file: <br><h4>%1</h4><p>Please verify that you have the right to write to this location!").arg(fname));
+    QMessageBox::critical(
+        this, tr("MantidPlot - ASCII Export Error"),
+        tr("Could not write to file: <br><h4>%1</h4><p>Please verify that you "
+           "have the right to write to this location!").arg(fname));
     return false;
   }
 
   int rows = numRows();
   int cols = numCols();
-  QTextStream t( &f );
+  QTextStream t(&f);
   QString eol = applicationWindow()->endOfLine();
-  if (exportSelection && d_view_type == TableView){
-    QModelIndexList selectedIndexes = d_table_view->selectionModel()->selectedIndexes();
+  if (exportSelection && d_view_type == TableView) {
+    QModelIndexList selectedIndexes =
+        d_table_view->selectionModel()->selectedIndexes();
     int topRow = selectedIndexes[0].row();
     int bottomRow = topRow;
     int leftCol = selectedIndexes[0].column();
     int rightCol = leftCol;
-    foreach(QModelIndex index, selectedIndexes){
+    foreach (QModelIndex index, selectedIndexes) {
       int row = index.row();
       if (row < topRow)
         topRow = row;
@@ -1429,8 +1432,8 @@ bool Matrix::exportASCII(const QString& fname, const QString& separator, bool ex
         rightCol = col;
     }
 
-    for (int i = topRow; i <= bottomRow; i++){
-      for (int j = leftCol; j < rightCol; j++){
+    for (int i = topRow; i <= bottomRow; i++) {
+      for (int j = leftCol; j < rightCol; j++) {
         t << d_matrix_model->text(i, j);
         t << separator;
       }
@@ -1438,12 +1441,12 @@ bool Matrix::exportASCII(const QString& fname, const QString& separator, bool ex
       t << eol;
     }
   } else {
-    for (int i=0; i<rows; i++) {
-      for (int j=0; j<cols-1; j++){
-        t << d_matrix_model->text(i,j);
+    for (int i = 0; i < rows; i++) {
+      for (int j = 0; j < cols - 1; j++) {
+        t << d_matrix_model->text(i, j);
         t << separator;
       }
-      t << d_matrix_model->text(i, cols-1);
+      t << d_matrix_model->text(i, cols - 1);
       t << eol;
     }
   }
@@ -1451,81 +1454,83 @@ bool Matrix::exportASCII(const QString& fname, const QString& separator, bool ex
   return true;
 }
 
-void Matrix::importASCII(const QString &fname, const QString &sep, int ignoredLines,
-    bool stripSpaces, bool simplifySpaces, const QString& commentString,
-    ImportMode importAs, const QLocale& locale, int endLineChar, int maxRows)
-{
+void Matrix::importASCII(const QString &fname, const QString &sep,
+                         int ignoredLines, bool stripSpaces,
+                         bool simplifySpaces, const QString &commentString,
+                         ImportMode importAs, const QLocale &locale,
+                         int endLineChar, int maxRows) {
   double *buffer = d_matrix_model->dataCopy();
-  if (buffer){
-    d_undo_stack->push(new MatrixImportAsciiCommand(fname, sep, ignoredLines, stripSpaces,
-        simplifySpaces, commentString, importAs, locale, endLineChar, maxRows,
-        d_matrix_model, 0, numRows() - 1, 0, numCols() - 1, buffer,
+  if (buffer) {
+    d_undo_stack->push(new MatrixImportAsciiCommand(
+        fname, sep, ignoredLines, stripSpaces, simplifySpaces, commentString,
+        importAs, locale, endLineChar, maxRows, d_matrix_model, 0,
+        numRows() - 1, 0, numCols() - 1, buffer,
         tr("Import ASCII File") + " \"" + fname + "\""));
     emit modifiedWindow(this);
-  } else if (ignoreUndo()){
-    d_matrix_model->importASCII(fname, sep, ignoredLines, stripSpaces, simplifySpaces,
-        commentString, importAs, locale, endLineChar, maxRows);
+  } else if (ignoreUndo()) {
+    d_matrix_model->importASCII(fname, sep, ignoredLines, stripSpaces,
+                                simplifySpaces, commentString, importAs, locale,
+                                endLineChar, maxRows);
     emit modifiedWindow(this);
   }
 }
 
-bool Matrix::ignoreUndo()
-{
-  QString msg = tr("Due to memory limitations it will not be possible to undo this change. Do you want to continue anyways?");
-  return (QMessageBox::Yes == QMessageBox::warning(dynamic_cast<ApplicationWindow *>(applicationWindow()),
-      tr("MantidPlot") + " - " + tr("Warning"), msg, QMessageBox::Yes, QMessageBox::Cancel));
+bool Matrix::ignoreUndo() {
+  QString msg = tr("Due to memory limitations it will not be possible to undo "
+                   "this change. Do you want to continue anyways?");
+  return (QMessageBox::Yes ==
+          QMessageBox::warning(
+              dynamic_cast<ApplicationWindow *>(applicationWindow()),
+              tr("MantidPlot") + " - " + tr("Warning"), msg, QMessageBox::Yes,
+              QMessageBox::Cancel));
 }
 
-double* Matrix::initWorkspace(int size)
-{
+double *Matrix::initWorkspace(int size) {
   if (!d_workspace)
-    d_workspace = (double *)malloc(size * sizeof (double));
+    d_workspace = (double *)malloc(size * sizeof(double));
 
   if (!d_workspace)
-    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(applicationWindow()), tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
+    QMessageBox::critical(
+        dynamic_cast<ApplicationWindow *>(applicationWindow()),
+        tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
         tr("Not enough memory, operation aborted!"));
 
   return d_workspace;
 }
 
-Matrix::~Matrix()
-{
+Matrix::~Matrix() {
   delete d_undo_stack;
   delete d_matrix_model;
 }
 
-void Matrix::loadFromProject(const std::string& lines, ApplicationWindow* app, const int fileVersion)
-{
+void Matrix::loadFromProject(const std::string &lines, ApplicationWindow *app,
+                             const int fileVersion) {
   Q_UNUSED(app);
   Q_UNUSED(fileVersion);
 
   TSVSerialiser tsv(lines);
 
-  if(tsv.selectLine("ColWidth"))
-  {
+  if (tsv.selectLine("ColWidth")) {
     setColumnsWidth(tsv.asInt(1));
   }
 
-  if(tsv.selectSection("formula"))
-  {
+  if (tsv.selectSection("formula")) {
     QString formula;
     tsv >> formula;
     setFormula(formula);
   }
 
-  if(tsv.selectLine("TextFormat"))
-  {
+  if (tsv.selectLine("TextFormat")) {
     std::string format;
     int value;
     tsv >> format >> value;
-    if(format == "f")
+    if (format == "f")
       setTextFormat('f', value);
     else
       setTextFormat('e', value);
   }
 
-  if(tsv.selectLine("WindowLabel"))
-  {
+  if (tsv.selectLine("WindowLabel")) {
     QString label;
     int captionPolicy;
     tsv >> label >> captionPolicy;
@@ -1533,57 +1538,50 @@ void Matrix::loadFromProject(const std::string& lines, ApplicationWindow* app, c
     setCaptionPolicy((MdiSubWindow::CaptionPolicy)captionPolicy);
   }
 
-  if(tsv.selectLine("Coordinates"))
-  {
-    setCoordinates(tsv.asDouble(1), tsv.asDouble(2), tsv.asDouble(3), tsv.asDouble(4));
+  if (tsv.selectLine("Coordinates")) {
+    setCoordinates(tsv.asDouble(1), tsv.asDouble(2), tsv.asDouble(3),
+                   tsv.asDouble(4));
   }
 
-  if(tsv.selectLine("ViewType"))
-  {
+  if (tsv.selectLine("ViewType")) {
     setViewType((Matrix::ViewType)tsv.asInt(1));
   }
 
-  if(tsv.selectLine("HeaderViewType"))
-  {
+  if (tsv.selectLine("HeaderViewType")) {
     setHeaderViewType((Matrix::HeaderViewType)tsv.asInt(1));
   }
 
-  if(tsv.selectLine("ColorPolicy"))
-  {
+  if (tsv.selectLine("ColorPolicy")) {
     setColorMapType((Matrix::ColorMapType)tsv.asInt(1));
   }
 
-  if(tsv.selectSection("ColorMap"))
-  {
+  if (tsv.selectSection("ColorMap")) {
     QString colorMap;
     tsv >> colorMap;
     setColorMap(colorMap.split("\n"));
   }
 
-  if(tsv.selectSection("data"))
-  {
+  if (tsv.selectSection("data")) {
     std::string dataLines;
     tsv >> dataLines;
     std::vector<std::string> dataVec, valVec;
 
-    if(!dataLines.empty())
+    if (!dataLines.empty())
       boost::split(dataVec, dataLines, boost::is_any_of("\n"));
 
-    for(auto lineIt = dataVec.begin(); lineIt != dataVec.end(); ++lineIt)
-    {
+    for (auto lineIt = dataVec.begin(); lineIt != dataVec.end(); ++lineIt) {
       boost::split(valVec, *lineIt, boost::is_any_of("\t"));
 
-      //Take the row number from the front
+      // Take the row number from the front
       int row = 0;
       Mantid::Kernel::Strings::convert<int>(valVec.front(), row);
 
-      //Remove the row number, so we're just left with the values
+      // Remove the row number, so we're just left with the values
       valVec.erase(valVec.begin());
 
-      for(int col = 0; col < numCols(); ++col)
-      {
+      for (int col = 0; col < numCols(); ++col) {
         const std::string cellStr = valVec[col];
-        if(cellStr.empty())
+        if (cellStr.empty())
           continue;
 
         std::stringstream cellSS(cellStr);
@@ -1593,26 +1591,26 @@ void Matrix::loadFromProject(const std::string& lines, ApplicationWindow* app, c
         setCell(row, col, cell);
       }
 
-      //Clear out the value vector for the next iteration
+      // Clear out the value vector for the next iteration
       valVec.clear();
     }
     resetView();
   }
 }
 
-std::string Matrix::saveToProject(ApplicationWindow* app)
-{
+std::string Matrix::saveToProject(ApplicationWindow *app) {
   TSVSerialiser tsv;
 
   tsv.writeRaw("<matrix>");
-  tsv.writeLine(objectName().toStdString()) << numRows() << numCols() << birthDate();
+  tsv.writeLine(objectName().toStdString()) << numRows() << numCols()
+                                            << birthDate();
   tsv.writeRaw(app->windowGeometryInfo(this));
 
   tsv.writeLine("ColWidth") << d_column_width;
 
   tsv.writeSection("formula", formula_str.toUtf8().constData());
 
-  //Converting QChar into something useful is not fun.
+  // Converting QChar into something useful is not fun.
   std::string tf(" ");
   tf[0] = txt_format.toAscii();
   tsv.writeLine("TextFormat") << tf << num_precision;
@@ -1621,33 +1619,35 @@ std::string Matrix::saveToProject(ApplicationWindow* app)
 
   tsv.writeLine("Coordinates");
   tsv << QString::number(x_start, 'g', 15);
-  tsv << QString::number(x_end,   'g', 15);
+  tsv << QString::number(x_end, 'g', 15);
   tsv << QString::number(y_start, 'g', 15);
-  tsv << QString::number(y_end,   'g', 15);
+  tsv << QString::number(y_end, 'g', 15);
 
   tsv.writeLine("ViewType") << d_view_type;
   tsv.writeLine("HeaderViewType") << d_header_view_type;
 
-  if(d_color_map_type != Custom)
-  {
+  if (d_color_map_type != Custom) {
     tsv.writeLine("ColorPolicy") << d_color_map_type;
-  }
-  else
-  {
+  } else {
     tsv.writeRaw("<ColorMap>");
-    tsv.writeInlineSection("Mode", Mantid::Kernel::Strings::toString<int>(d_color_map.mode()));
-    tsv.writeInlineSection("MinColor", d_color_map.color1().name().toStdString());
-    tsv.writeInlineSection("MaxColor", d_color_map.color2().name().toStdString());
+    tsv.writeInlineSection(
+        "Mode", Mantid::Kernel::Strings::toString<int>(d_color_map.mode()));
+    tsv.writeInlineSection("MinColor",
+                           d_color_map.color1().name().toStdString());
+    tsv.writeInlineSection("MaxColor",
+                           d_color_map.color2().name().toStdString());
 
     QwtArray<double> colors = d_color_map.colorStops();
     size_t stops = colors.size();
-    tsv.writeInlineSection("ColorStops", Mantid::Kernel::Strings::toString<size_t>(stops - 2));
-    for(int i = 1; i < (int)stops - 1; ++i)
-    {
+    tsv.writeInlineSection(
+        "ColorStops", Mantid::Kernel::Strings::toString<size_t>(stops - 2));
+    for (int i = 1; i < (int)stops - 1; ++i) {
       std::stringstream stopLine;
       stopLine << Mantid::Kernel::Strings::toString<double>(colors[i]);
       stopLine << "\t";
-      stopLine << QColor(d_color_map.rgb(QwtDoubleInterval(0,1), colors[i])).name().toStdString();
+      stopLine << QColor(d_color_map.rgb(QwtDoubleInterval(0, 1), colors[i]))
+                      .name()
+                      .toStdString();
       tsv.writeInlineSection("Stop", stopLine.str());
     }
 
diff --git a/MantidPlot/src/Matrix.h b/MantidPlot/src/Matrix.h
index 3734fec2a24a025526ee9b00eab723828d3b51d0..37599e75edfe1adf578c0fd70c250fcc9142a002 100644
--- a/MantidPlot/src/Matrix.h
+++ b/MantidPlot/src/Matrix.h
@@ -61,15 +61,16 @@ class QShortcut;
 class QUndoStack;
 
 //! Matrix worksheet class
-class Matrix: public MdiSubWindow, public Scripted, public Mantid::IProjectSerialisable
-{
+class Matrix : public MdiSubWindow,
+               public Scripted,
+               public Mantid::IProjectSerialisable {
   Q_OBJECT
 
 protected:
-  Matrix(ScriptingEnv *env, const QString& label, ApplicationWindow* parent, const QString& name = QString(), Qt::WFlags f=0);
+  Matrix(ScriptingEnv *env, const QString &label, ApplicationWindow *parent,
+         const QString &name = QString(), Qt::WFlags f = 0);
 
 public:
-
   /**
    * \brief Constructor
    *
@@ -82,49 +83,69 @@ public:
 ::    * @param name :: window name
    * @param f :: window flags
    */
-  Matrix(ScriptingEnv *env, int r, int c, const QString& label, ApplicationWindow* parent, const QString& name = QString(), Qt::WFlags f=0);
-  Matrix(ScriptingEnv *env, const QImage& image, const QString& label, ApplicationWindow* parent, const QString& name = QString(), Qt::WFlags f=0);
+  Matrix(ScriptingEnv *env, int r, int c, const QString &label,
+         ApplicationWindow *parent, const QString &name = QString(),
+         Qt::WFlags f = 0);
+  Matrix(ScriptingEnv *env, const QImage &image, const QString &label,
+         ApplicationWindow *parent, const QString &name = QString(),
+         Qt::WFlags f = 0);
   ~Matrix() override;
 
-  enum Operation{Transpose, Invert, FlipHorizontally, FlipVertically, RotateClockwise,
-    RotateCounterClockwise, FFT, Clear, Calculate, MuParserCalculate, SetImage, ImportAscii};
-  enum HeaderViewType{ColumnRow, XY};
-  enum ViewType{TableView, ImageView};
-  enum ColorMapType{GrayScale, Rainbow, Custom};
+  enum Operation {
+    Transpose,
+    Invert,
+    FlipHorizontally,
+    FlipVertically,
+    RotateClockwise,
+    RotateCounterClockwise,
+    FFT,
+    Clear,
+    Calculate,
+    MuParserCalculate,
+    SetImage,
+    ImportAscii
+  };
+  enum HeaderViewType { ColumnRow, XY };
+  enum ViewType { TableView, ImageView };
+  enum ColorMapType { GrayScale, Rainbow, Custom };
   enum ImportMode {
     NewColumns, //!< add file as new columns to the current matrix
-    NewRows, //!< add file as new rows to the current matrix
-    Overwrite //!< replace content of current matrix with the imported file
+    NewRows,    //!< add file as new rows to the current matrix
+    Overwrite   //!< replace content of current matrix with the imported file
   };
 
   void setViewType(ViewType, bool renderImage = true);
-  ViewType viewType(){return d_view_type;};
+  ViewType viewType() { return d_view_type; };
 
-  HeaderViewType headerViewType(){return d_header_view_type;};
+  HeaderViewType headerViewType() { return d_header_view_type; };
   void setHeaderViewType(HeaderViewType type);
 
   QImage image();
-  void displayImage(const QImage& image);
-  void importImage(const QString& fn);
-  void exportRasterImage(const QString& fileName, int quality = 100);
-  void exportSVG(const QString& fileName);
-  void exportToFile(const QString& fileName);
-  void exportVector(const QString& fileName, int res = 0, bool color = true, bool keepAspect = true, QPrinter::PageSize pageSize = QPrinter::Custom);
-
-  MatrixModel * matrixModel(){return d_matrix_model;};
-  QUndoStack *undoStack(){return d_undo_stack;};
-
-  QItemSelectionModel * selectionModel(){return d_table_view->selectionModel();};
+  void displayImage(const QImage &image);
+  void importImage(const QString &fn);
+  void exportRasterImage(const QString &fileName, int quality = 100);
+  void exportSVG(const QString &fileName);
+  void exportToFile(const QString &fileName);
+  void exportVector(const QString &fileName, int res = 0, bool color = true,
+                    bool keepAspect = true,
+                    QPrinter::PageSize pageSize = QPrinter::Custom);
+
+  MatrixModel *matrixModel() { return d_matrix_model; };
+  QUndoStack *undoStack() { return d_undo_stack; };
+
+  QItemSelectionModel *selectionModel() {
+    return d_table_view->selectionModel();
+  };
 
   //! Return the number of rows
-  int numRows(){return d_matrix_model->rowCount();};
-  void setNumRows(int rows){d_matrix_model->setRowCount(rows);};
+  int numRows() { return d_matrix_model->rowCount(); };
+  void setNumRows(int rows) { d_matrix_model->setRowCount(rows); };
 
   //! Return the number of columns
-  int numCols(){return d_matrix_model->columnCount();};
-  void setNumCols(int cols){d_matrix_model->setColumnCount(cols);};
+  int numCols() { return d_matrix_model->columnCount(); };
+  void setNumCols(int cols) { d_matrix_model->setColumnCount(cols); };
 
-  //event handlers
+  // event handlers
   //! Custom event handler
   /**
    * Currently handles SCRIPTING_CHANGE_EVENT only.
@@ -132,20 +153,20 @@ public:
   void customEvent(QEvent *e) override;
 
   void resetView();
-  void moveCell(const QModelIndex& index);
+  void moveCell(const QModelIndex &index);
 
   virtual void flipVertically();
   virtual void flipHorizontally();
   void rotate90(bool clockwise = true);
   void fft(bool inverse = false);
 
-  ColorMapType colorMapType(){return d_color_map_type;};
+  ColorMapType colorMapType() { return d_color_map_type; };
   void setColorMapType(ColorMapType mapType);
 
-  QwtLinearColorMap colorMap(){return d_color_map;};
-  void setColorMap(const QwtLinearColorMap& map);
+  QwtLinearColorMap colorMap() { return d_color_map; };
+  void setColorMap(const QwtLinearColorMap &map);
   //! Used when restoring from project files
-  void setColorMap(const QStringList& lst);
+  void setColorMap(const QStringList &lst);
 
   void setGrayScale();
   void setRainbowColorMap();
@@ -159,26 +180,33 @@ public:
   void invert();
 
   //! Calculate matrix values using the #formula_str.
-  bool calculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1, bool forceMuParser = true);
-  //! Calculate matrix values using the #formula_str (optimization for muParser).
-  bool muParserCalculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1);
-
-  bool exportASCII(const QString& fname, const QString& separator, bool exportSelection);
-  void importASCII(const QString &fname, const QString &sep, int ignoredLines, bool stripSpaces,
-      bool simplifySpaces, const QString& commentString, ImportMode importAs = Overwrite,
-      const QLocale& l = QLocale(), int endLineChar = 0, int maxRows = -1);
-
-  QPixmap matrixIcon(){return m_matrix_icon;}
+  bool calculate(int startRow = 0, int endRow = -1, int startCol = 0,
+                 int endCol = -1, bool forceMuParser = true);
+  //! Calculate matrix values using the #formula_str (optimization for
+  // muParser).
+  bool muParserCalculate(int startRow = 0, int endRow = -1, int startCol = 0,
+                         int endCol = -1);
+
+  bool exportASCII(const QString &fname, const QString &separator,
+                   bool exportSelection);
+  void importASCII(const QString &fname, const QString &sep, int ignoredLines,
+                   bool stripSpaces, bool simplifySpaces,
+                   const QString &commentString,
+                   ImportMode importAs = Overwrite,
+                   const QLocale &l = QLocale(), int endLineChar = 0,
+                   int maxRows = -1);
+
+  QPixmap matrixIcon() { return m_matrix_icon; }
 
 public slots:
   void exportPDF(const QString &fileName) override;
   //! Print the Matrix
   void print() override;
   //! Print the Matrix to fileName
-  void print(const QString& fileName);
+  void print(const QString &fileName);
 
   //! Return the width of all columns
-  int columnsWidth(){return d_column_width;};
+  int columnsWidth() { return d_column_width; };
   //! Set the width of all columns
   void setColumnsWidth(int width);
 
@@ -188,31 +216,31 @@ public slots:
   //! Return the content of the cell as a string
   QString text(int row, int col);
   //! Set the content of the cell as a string
-  void setText(int row, int col, const QString & new_text );
+  void setText(int row, int col, const QString &new_text);
   //! Return the value of the cell as a double
   double cell(int row, int col);
   //! Set the value of the cell
-  void setCell(int row, int col, double value );
+  void setCell(int row, int col, double value);
 
   /**
    * \brief Return the text format code ('e', 'f', ...)
    *
    * \sa setNumerFormat(), setTextFormat()
    */
-  QChar textFormat(){return txt_format;};
+  QChar textFormat() { return txt_format; };
   /**
    * \brief Return the number precision digits
    *
    * See arguments of setNumericFormat().
    * \sa setNumericFormat(), setTextFormat()
    */
-  int precision(){return num_precision;};
+  int precision() { return num_precision; };
   /**
    * \brief Set the number of significant digits
    *
    * \sa precision(), setNumericFormat(), setTextFormat()
    */
-  void setNumericPrecision(int prec){num_precision = prec;};
+  void setNumericPrecision(int prec) { num_precision = prec; };
 
   /**
    * \brief Set the number format for the cells
@@ -223,12 +251,12 @@ public slots:
    * \sa setTextFormat()
    */
   void setTextFormat(const QChar &format, int precision);
-  void setNumericFormat(const QChar & f, int prec);
+  void setNumericFormat(const QChar &f, int prec);
 
   //! Return the matrix formula
-  QString formula(){return formula_str;};
+  QString formula() { return formula_str; };
   //! Set the matrix forumla
-  void setFormula(const QString &s){formula_str = s;};
+  void setFormula(const QString &s) { formula_str = s; };
 
   //! Load the matrix from a string list (i.e. lines from a project file)
   void restore(const QStringList &l) override;
@@ -263,18 +291,18 @@ public slots:
   int numSelectedColumns();
 
   //! Returns the X value corresponding to column 1
-  double xStart(){return x_start;};
+  double xStart() { return x_start; };
   //! Returns the X value corresponding to the last column
-  double xEnd(){return x_end;};
+  double xEnd() { return x_end; };
   //! Returns the Y value corresponding to row 1
-  double yStart(){return y_start;};
+  double yStart() { return y_start; };
   //! Returns the Y value corresponding to the last row
-  double yEnd(){return y_end;};
+  double yEnd() { return y_end; };
 
   //! Returns the step of the X axis
-  double dx(){return fabs(x_end - x_start)/(double)(numCols() - 1);};
+  double dx() { return fabs(x_end - x_start) / (double)(numCols() - 1); };
   //! Returns the step of the Y axis
-  double dy(){return fabs(y_end - y_start)/(double)(numRows() - 1);};
+  double dy() { return fabs(y_end - y_start) / (double)(numRows() - 1); };
 
   //! Returns the bounding rect of the matrix coordinates
   QwtDoubleRect boundingRect();
@@ -290,33 +318,37 @@ public slots:
   void goToColumn(int col);
 
   //! Allocate memory for a matrix buffer
-  static double** allocateMatrixData(int rows, int columns);
+  static double **allocateMatrixData(int rows, int columns);
   //! Free memory used for a matrix buffer
   static void freeMatrixData(double **data, int rows);
 
-  int verticalHeaderWidth(){return d_table_view->verticalHeader()->width();}
+  int verticalHeaderWidth() { return d_table_view->verticalHeader()->width(); }
 
   void copy(Matrix *m);
-  //! Tries to allocate memory for the workspace. Returns a NULL pointer if failure.
+  //! Tries to allocate memory for the workspace. Returns a NULL pointer if
+  // failure.
   double *initWorkspace(int size);
-  void freeWorkspace(){free(d_workspace); d_workspace = NULL;};
+  void freeWorkspace() {
+    free(d_workspace);
+    d_workspace = NULL;
+  };
 
   bool canCalculate(bool useMuParser = true);
 
-  protected:
+protected:
   MatrixModel *d_matrix_model;
   QColor m_bk_color;
 
   //! Initialize the matrix
   void initTable(int rows, int cols);
-  void initImage(const QImage& image);
+  void initImage(const QImage &image);
   void initImageView();
   void initTableView();
   void initGlobals();
   bool ignoreUndo();
   QPixmap m_matrix_icon;
 
-  //private:
+  // private:
   QStackedWidget *d_stack;
   //! Pointer to the table view
   QTableView *d_table_view;
@@ -329,9 +361,9 @@ public slots:
   //! Number of significant digits
   int num_precision;
   double x_start, //!< X value corresponding to column 1
-  x_end,  //!< X value corresponding to the last column
-  y_start,  //!< Y value corresponding to row 1
-  y_end;  //!< Y value corresponding to the last row
+      x_end,      //!< X value corresponding to the last column
+      y_start,    //!< Y value corresponding to row 1
+      y_end;      //!< Y value corresponding to the last row
 
   //! Keeps track of the view type;
   ViewType d_view_type;
diff --git a/MantidPlot/src/MatrixCommand.cpp b/MantidPlot/src/MatrixCommand.cpp
index ad603f5f3801df7da4966f39f2b9c451f4bb9f07..830cc0de119e9f0844613f3673371edebc5996c6 100644
--- a/MantidPlot/src/MatrixCommand.cpp
+++ b/MantidPlot/src/MatrixCommand.cpp
@@ -34,742 +34,669 @@
 /*************************************************************************/
 /*           Class MatrixEditCellCommand                                 */
 /*************************************************************************/
-MatrixEditCellCommand::MatrixEditCellCommand(MatrixModel *model, const QModelIndex & index,
-                        double valBefore, double valAfter, const QString & text):
-QUndoCommand(text),
-d_model(model),
-d_index(index),
-d_val_before(valBefore),
-d_val_after(valAfter)
-{
-    setText(model->matrix()->objectName() + ": " + text);
-}
-
-void MatrixEditCellCommand::redo()
-{
-    if (!d_model)
-        return;
-
-    Matrix *m = d_model->matrix();
-    if (m){
-        d_model->setCell(d_index.row(), d_index.column(), d_val_after);
-        m->resetView();
-        m->notifyChanges();
-    }
+MatrixEditCellCommand::MatrixEditCellCommand(MatrixModel *model,
+                                             const QModelIndex &index,
+                                             double valBefore, double valAfter,
+                                             const QString &text)
+    : QUndoCommand(text), d_model(model), d_index(index),
+      d_val_before(valBefore), d_val_after(valAfter) {
+  setText(model->matrix()->objectName() + ": " + text);
 }
 
-void MatrixEditCellCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixEditCellCommand::redo() {
+  if (!d_model)
+    return;
 
-    Matrix *m = d_model->matrix();
-    if (m){
-        d_model->setCell(d_index.row(), d_index.column(), d_val_before);
-        m->resetView();
-        m->notifyChanges();
-    }
+  Matrix *m = d_model->matrix();
+  if (m) {
+    d_model->setCell(d_index.row(), d_index.column(), d_val_after);
+    m->resetView();
+    m->notifyChanges();
+  }
+}
+
+void MatrixEditCellCommand::undo() {
+  if (!d_model)
+    return;
+
+  Matrix *m = d_model->matrix();
+  if (m) {
+    d_model->setCell(d_index.row(), d_index.column(), d_val_before);
+    m->resetView();
+    m->notifyChanges();
+  }
 }
 
 /*************************************************************************/
 /*           Class MatrixSetFormulaCommand                               */
 /*************************************************************************/
-MatrixSetFormulaCommand::MatrixSetFormulaCommand(Matrix *m, const QString& oldFormula,
-                        const QString& newFormula, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_formula(oldFormula),
-d_new_formula(newFormula)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetFormulaCommand::MatrixSetFormulaCommand(Matrix *m,
+                                                 const QString &oldFormula,
+                                                 const QString &newFormula,
+                                                 const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_formula(oldFormula),
+      d_new_formula(newFormula) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetFormulaCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetFormulaCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setFormula(d_new_formula);
+  d_matrix->setFormula(d_new_formula);
 }
 
-void MatrixSetFormulaCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetFormulaCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setFormula(d_old_formula);
+  d_matrix->setFormula(d_old_formula);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetViewCommand                                  */
 /*************************************************************************/
 MatrixSetViewCommand::MatrixSetViewCommand(Matrix *m, Matrix::ViewType oldView,
-                    Matrix::ViewType newView, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_view(oldView),
-d_new_view(newView)
-{
-    setText(m->objectName() + ": " + text);
+                                           Matrix::ViewType newView,
+                                           const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_view(oldView),
+      d_new_view(newView) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetViewCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetViewCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setViewType(d_new_view);
+  d_matrix->setViewType(d_new_view);
 }
 
-void MatrixSetViewCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetViewCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setViewType(d_old_view);
+  d_matrix->setViewType(d_old_view);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetHeaderViewCommand                            */
 /*************************************************************************/
-MatrixSetHeaderViewCommand::MatrixSetHeaderViewCommand(Matrix *m, Matrix::HeaderViewType oldView,
-                    Matrix::HeaderViewType newView, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_view(oldView),
-d_new_view(newView)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetHeaderViewCommand::MatrixSetHeaderViewCommand(
+    Matrix *m, Matrix::HeaderViewType oldView, Matrix::HeaderViewType newView,
+    const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_view(oldView),
+      d_new_view(newView) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetHeaderViewCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetHeaderViewCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setHeaderViewType(d_new_view);
+  d_matrix->setHeaderViewType(d_new_view);
 }
 
-void MatrixSetHeaderViewCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetHeaderViewCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setHeaderViewType(d_old_view);
+  d_matrix->setHeaderViewType(d_old_view);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetColWidthCommand                              */
 /*************************************************************************/
-MatrixSetColWidthCommand::MatrixSetColWidthCommand(Matrix *m, int oldWidth, int newWidth, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_width(oldWidth),
-d_new_width(newWidth)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetColWidthCommand::MatrixSetColWidthCommand(Matrix *m, int oldWidth,
+                                                   int newWidth,
+                                                   const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_width(oldWidth),
+      d_new_width(newWidth) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetColWidthCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetColWidthCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setColumnsWidth(d_new_width);
+  d_matrix->setColumnsWidth(d_new_width);
 }
 
-void MatrixSetColWidthCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetColWidthCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setColumnsWidth(d_old_width);
+  d_matrix->setColumnsWidth(d_old_width);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetPrecisionCommand                             */
 /*************************************************************************/
-MatrixSetPrecisionCommand::MatrixSetPrecisionCommand(Matrix *m, const QChar& oldFormat,
-                const QChar& newFormat, int oldPrec, int newPrec, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_format(oldFormat),
-d_new_format(newFormat),
-d_old_prec(oldPrec),
-d_new_prec(newPrec)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetPrecisionCommand::MatrixSetPrecisionCommand(Matrix *m,
+                                                     const QChar &oldFormat,
+                                                     const QChar &newFormat,
+                                                     int oldPrec, int newPrec,
+                                                     const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_format(oldFormat),
+      d_new_format(newFormat), d_old_prec(oldPrec), d_new_prec(newPrec) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetPrecisionCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetPrecisionCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setNumericFormat(d_new_format, d_new_prec);
+  d_matrix->setNumericFormat(d_new_format, d_new_prec);
 }
 
-void MatrixSetPrecisionCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetPrecisionCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setNumericFormat(d_old_format, d_old_prec);
+  d_matrix->setNumericFormat(d_old_format, d_old_prec);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetCoordinatesCommand                           */
 /*************************************************************************/
-MatrixSetCoordinatesCommand::MatrixSetCoordinatesCommand(Matrix *m, double oxs, double oxe,
-    double oys, double oye, double nxs, double nxe, double nys, double nye, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_old_xs(oxs),
-d_old_xe(oxe),
-d_old_ys(oys),
-d_old_ye(oye),
-d_new_xs(nxs),
-d_new_xe(nxe),
-d_new_ys(nys),
-d_new_ye(nye)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetCoordinatesCommand::MatrixSetCoordinatesCommand(
+    Matrix *m, double oxs, double oxe, double oys, double oye, double nxs,
+    double nxe, double nys, double nye, const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_old_xs(oxs), d_old_xe(oxe),
+      d_old_ys(oys), d_old_ye(oye), d_new_xs(nxs), d_new_xe(nxe), d_new_ys(nys),
+      d_new_ye(nye) {
+  setText(m->objectName() + ": " + text);
 }
 
-void MatrixSetCoordinatesCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetCoordinatesCommand::redo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setCoordinates(d_new_xs, d_new_xe, d_new_ys, d_new_ye);
+  d_matrix->setCoordinates(d_new_xs, d_new_xe, d_new_ys, d_new_ye);
 }
 
-void MatrixSetCoordinatesCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetCoordinatesCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    d_matrix->setCoordinates(d_old_xs, d_old_xe, d_old_ys, d_old_ye);
+  d_matrix->setCoordinates(d_old_xs, d_old_xe, d_old_ys, d_old_ye);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetColorMapCommand                              */
 /*************************************************************************/
-MatrixSetColorMapCommand::MatrixSetColorMapCommand(Matrix *m, Matrix::ColorMapType type_before,
-							const QwtLinearColorMap& map_before, Matrix::ColorMapType type_after,
-							const QwtLinearColorMap& map_after, const QString & text):
-QUndoCommand(text),
-d_matrix(m),
-d_map_type_before(type_before),
-d_map_type_after(type_after)
-{
-    setText(m->objectName() + ": " + text);
+MatrixSetColorMapCommand::MatrixSetColorMapCommand(
+    Matrix *m, Matrix::ColorMapType type_before,
+    const QwtLinearColorMap &map_before, Matrix::ColorMapType type_after,
+    const QwtLinearColorMap &map_after, const QString &text)
+    : QUndoCommand(text), d_matrix(m), d_map_type_before(type_before),
+      d_map_type_after(type_after) {
+  setText(m->objectName() + ": " + text);
 
-	d_map_before = QwtLinearColorMap(map_before);
-	d_map_after = QwtLinearColorMap(map_after);
+  d_map_before = QwtLinearColorMap(map_before);
+  d_map_after = QwtLinearColorMap(map_after);
 }
 
-void MatrixSetColorMapCommand::redo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetColorMapCommand::redo() {
+  if (!d_matrix)
+    return;
 
-	switch(d_map_type_after){
-		case Matrix::GrayScale:
-			d_matrix->setGrayScale();
-		break;
+  switch (d_map_type_after) {
+  case Matrix::GrayScale:
+    d_matrix->setGrayScale();
+    break;
 
-		case Matrix::Rainbow:
-			d_matrix->setRainbowColorMap();
-		break;
+  case Matrix::Rainbow:
+    d_matrix->setRainbowColorMap();
+    break;
 
-		case Matrix::Custom:
-			d_matrix->setColorMap(d_map_after);
-		break;
-	}
+  case Matrix::Custom:
+    d_matrix->setColorMap(d_map_after);
+    break;
+  }
 }
 
-void MatrixSetColorMapCommand::undo()
-{
-    if (!d_matrix)
-        return;
+void MatrixSetColorMapCommand::undo() {
+  if (!d_matrix)
+    return;
 
-    	switch(d_map_type_before){
-		case Matrix::GrayScale:
-			d_matrix->setGrayScale();
-		break;
+  switch (d_map_type_before) {
+  case Matrix::GrayScale:
+    d_matrix->setGrayScale();
+    break;
 
-		case Matrix::Rainbow:
-			d_matrix->setRainbowColorMap();
-		break;
+  case Matrix::Rainbow:
+    d_matrix->setRainbowColorMap();
+    break;
 
-		case Matrix::Custom:
-			d_matrix->setColorMap(d_map_before);
-		break;
-	}
+  case Matrix::Custom:
+    d_matrix->setColorMap(d_map_before);
+    break;
+  }
 }
 
 /*************************************************************************/
 /*           Class MatrixDeleteRowsCommand                               */
 /*************************************************************************/
-MatrixDeleteRowsCommand::MatrixDeleteRowsCommand(MatrixModel *model, int startRow, int count, double* data, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_start_row(startRow),
-d_count(count),
-d_data(data)
-{
-    setText(model->matrix()->objectName() + ": " + text);
+MatrixDeleteRowsCommand::MatrixDeleteRowsCommand(MatrixModel *model,
+                                                 int startRow, int count,
+                                                 double *data,
+                                                 const QString &text)
+    : QUndoCommand(text), d_model(model), d_start_row(startRow), d_count(count),
+      d_data(data) {
+  setText(model->matrix()->objectName() + ": " + text);
 }
 
-void MatrixDeleteRowsCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixDeleteRowsCommand::redo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeRows(d_start_row, d_count);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->removeRows(d_start_row, d_count);
+  QApplication::restoreOverrideCursor();
 }
 
-void MatrixDeleteRowsCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixDeleteRowsCommand::undo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
-    d_model->insertRows(d_start_row, d_count);
-	double *data = d_model->dataVector();
-	int cols = d_model->columnCount();
-	int size = cols * d_count;
-	int cell = d_start_row*cols;
-	for (int i = 0; i<size; i++)
-		data[cell++] = d_data[i];
+  d_model->insertRows(d_start_row, d_count);
+  double *data = d_model->dataVector();
+  int cols = d_model->columnCount();
+  int size = cols * d_count;
+  int cell = d_start_row * cols;
+  for (int i = 0; i < size; i++)
+    data[cell++] = d_data[i];
 
-	QApplication::restoreOverrideCursor();
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixInsertRowCommand                                */
 /*************************************************************************/
-MatrixInsertRowCommand::MatrixInsertRowCommand(MatrixModel *model, int startRow, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_start_row(startRow)
-{
-    setText(model->matrix()->objectName() + ": " + text);
+MatrixInsertRowCommand::MatrixInsertRowCommand(MatrixModel *model, int startRow,
+                                               const QString &text)
+    : QUndoCommand(text), d_model(model), d_start_row(startRow) {
+  setText(model->matrix()->objectName() + ": " + text);
 }
 
-void MatrixInsertRowCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixInsertRowCommand::redo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->insertRows(d_start_row, 1);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->insertRows(d_start_row, 1);
+  QApplication::restoreOverrideCursor();
 }
 
-void MatrixInsertRowCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixInsertRowCommand::undo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeRows(d_start_row, 1);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->removeRows(d_start_row, 1);
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixDeleteColsCommand                               */
 /*************************************************************************/
-MatrixDeleteColsCommand::MatrixDeleteColsCommand(MatrixModel *model, int startCol, int count, double* data, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_start_col(startCol),
-d_count(count),
-d_data(data)
-{
-    setText(model->matrix()->objectName() + ": " + text);
+MatrixDeleteColsCommand::MatrixDeleteColsCommand(MatrixModel *model,
+                                                 int startCol, int count,
+                                                 double *data,
+                                                 const QString &text)
+    : QUndoCommand(text), d_model(model), d_start_col(startCol), d_count(count),
+      d_data(data) {
+  setText(model->matrix()->objectName() + ": " + text);
 }
 
-void MatrixDeleteColsCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixDeleteColsCommand::redo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeColumns(d_start_col, d_count);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->removeColumns(d_start_col, d_count);
+  QApplication::restoreOverrideCursor();
 }
 
-void MatrixDeleteColsCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixDeleteColsCommand::undo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
-    d_model->insertColumns(d_start_col, d_count);
-	double *data = d_model->dataVector();
-	int rows = d_model->rowCount();
-	int cols = d_model->columnCount();
-	for (int i = 0; i<rows; i++){
-		int aux = i*cols + d_start_col;
-		int aux2 = i*d_count;
-		for (int j = 0; j<d_count; j++)
-			data[aux++] = d_data[aux2++];
-	}
-	QApplication::restoreOverrideCursor();
+  d_model->insertColumns(d_start_col, d_count);
+  double *data = d_model->dataVector();
+  int rows = d_model->rowCount();
+  int cols = d_model->columnCount();
+  for (int i = 0; i < rows; i++) {
+    int aux = i * cols + d_start_col;
+    int aux2 = i * d_count;
+    for (int j = 0; j < d_count; j++)
+      data[aux++] = d_data[aux2++];
+  }
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixInsertColCommand                                */
 /*************************************************************************/
-MatrixInsertColCommand::MatrixInsertColCommand(MatrixModel *model, int startCol, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_start_col(startCol)
-{
-    setText(model->matrix()->objectName() + ": " + text);
+MatrixInsertColCommand::MatrixInsertColCommand(MatrixModel *model, int startCol,
+                                               const QString &text)
+    : QUndoCommand(text), d_model(model), d_start_col(startCol) {
+  setText(model->matrix()->objectName() + ": " + text);
 }
 
-void MatrixInsertColCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixInsertColCommand::redo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->insertColumns(d_start_col, 1);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->insertColumns(d_start_col, 1);
+  QApplication::restoreOverrideCursor();
 }
 
-void MatrixInsertColCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixInsertColCommand::undo() {
+  if (!d_model)
+    return;
 
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeColumns(d_start_col, 1);
-	QApplication::restoreOverrideCursor();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->removeColumns(d_start_col, 1);
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixSetSizeCommand                                */
 /*************************************************************************/
-MatrixSetSizeCommand::MatrixSetSizeCommand(MatrixModel *model, const QSize& oldSize, const QSize& newSize, double *data, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_old_size(oldSize),
-d_new_size(newSize),
-d_backup(data)
-{
-    setText(model->matrix()->objectName() + ": " + text);
-}
-
-void MatrixSetSizeCommand::redo()
-{
-    if (!d_model)
-        return;
-
-    d_model->setDimensions(d_new_size.width(), d_new_size.height());
-	d_model->matrix()->resetView();
-}
-
-void MatrixSetSizeCommand::undo()
-{
-    if (!d_model)
-        return;
-	
-	int rows = d_old_size.width();
-	int cols = d_old_size.height();
-    d_model->setDimensions(rows, cols);
-	
-	double *data = d_model->dataVector();
-    if (!data)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	int cell = 0;
-    for (int i = 0; i < rows; i++){
-        for (int j = 0; j < cols; j++){
-            data[cell] = d_backup[cell];
-			cell++;
-		}
+MatrixSetSizeCommand::MatrixSetSizeCommand(MatrixModel *model,
+                                           const QSize &oldSize,
+                                           const QSize &newSize, double *data,
+                                           const QString &text)
+    : QUndoCommand(text), d_model(model), d_old_size(oldSize),
+      d_new_size(newSize), d_backup(data) {
+  setText(model->matrix()->objectName() + ": " + text);
+}
+
+void MatrixSetSizeCommand::redo() {
+  if (!d_model)
+    return;
+
+  d_model->setDimensions(d_new_size.width(), d_new_size.height());
+  d_model->matrix()->resetView();
+}
+
+void MatrixSetSizeCommand::undo() {
+  if (!d_model)
+    return;
+
+  int rows = d_old_size.width();
+  int cols = d_old_size.height();
+  d_model->setDimensions(rows, cols);
+
+  double *data = d_model->dataVector();
+  if (!data)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  int cell = 0;
+  for (int i = 0; i < rows; i++) {
+    for (int j = 0; j < cols; j++) {
+      data[cell] = d_backup[cell];
+      cell++;
     }
-	d_model->matrix()->resetView();
-	QApplication::restoreOverrideCursor();
+  }
+  d_model->matrix()->resetView();
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixUndoCommand                           */
 /*************************************************************************/
-MatrixUndoCommand::MatrixUndoCommand(MatrixModel *model, Matrix::Operation op, int startRow, int endRow, int startCol, int endCol,
-									double *data, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_operation(op),
-d_start_row(startRow),
-d_end_row(endRow),
-d_start_col(startCol),
-d_end_col(endCol),
-d_data(data)
-{
-    setText(model->matrix()->objectName() + ": " + text);
-}
-
-void MatrixUndoCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	switch(d_operation){
-		case Matrix::Clear:
-			d_model->clear(d_start_row, d_end_row, d_start_col, d_end_col);
-		break;
-		case Matrix::Calculate:
-			d_model->calculate(d_start_row, d_end_row, d_start_col, d_end_col);
-		break;
-		case Matrix::MuParserCalculate:
-			d_model->muParserCalculate(d_start_row, d_end_row, d_start_col, d_end_col);
-		break;
-		default:
-		break;
-	}
-    d_model->matrix()->resetView();
-}
-
-void MatrixUndoCommand::undo()
-{
-    if (!d_model)
-        return;
-
-    double *data = d_model->dataVector();
-    if (!data)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    int cols = d_model->columnCount();
-	int aux = 0;
-    for (int i = d_start_row; i <= d_end_row; i++){
-        int row = i*cols + d_start_col;
-        for (int j = d_start_col; j <= d_end_col; j++)
-            data[row++] = d_data[aux++];
-    }
-    d_model->matrix()->resetView();
-	QApplication::restoreOverrideCursor();
+MatrixUndoCommand::MatrixUndoCommand(MatrixModel *model, Matrix::Operation op,
+                                     int startRow, int endRow, int startCol,
+                                     int endCol, double *data,
+                                     const QString &text)
+    : QUndoCommand(text), d_model(model), d_operation(op),
+      d_start_row(startRow), d_end_row(endRow), d_start_col(startCol),
+      d_end_col(endCol), d_data(data) {
+  setText(model->matrix()->objectName() + ": " + text);
+}
+
+void MatrixUndoCommand::redo() {
+  if (!d_model)
+    return;
+
+  switch (d_operation) {
+  case Matrix::Clear:
+    d_model->clear(d_start_row, d_end_row, d_start_col, d_end_col);
+    break;
+  case Matrix::Calculate:
+    d_model->calculate(d_start_row, d_end_row, d_start_col, d_end_col);
+    break;
+  case Matrix::MuParserCalculate:
+    d_model->muParserCalculate(d_start_row, d_end_row, d_start_col, d_end_col);
+    break;
+  default:
+    break;
+  }
+  d_model->matrix()->resetView();
+}
+
+void MatrixUndoCommand::undo() {
+  if (!d_model)
+    return;
+
+  double *data = d_model->dataVector();
+  if (!data)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  int cols = d_model->columnCount();
+  int aux = 0;
+  for (int i = d_start_row; i <= d_end_row; i++) {
+    int row = i * cols + d_start_col;
+    for (int j = d_start_col; j <= d_end_col; j++)
+      data[row++] = d_data[aux++];
+  }
+  d_model->matrix()->resetView();
+  QApplication::restoreOverrideCursor();
 }
 
 /*************************************************************************/
 /*           Class MatrixFftCommand                                      */
 /*************************************************************************/
-MatrixFftCommand::MatrixFftCommand(bool inverse, MatrixModel *model, int startRow, int endRow,
-									int startCol, int endCol, double *data, const QString& text):
-MatrixUndoCommand(model, Matrix::FFT, startRow, endRow, startCol, endCol, data, text),
-d_inverse(inverse)
-{
-}
+MatrixFftCommand::MatrixFftCommand(bool inverse, MatrixModel *model,
+                                   int startRow, int endRow, int startCol,
+                                   int endCol, double *data,
+                                   const QString &text)
+    : MatrixUndoCommand(model, Matrix::FFT, startRow, endRow, startCol, endCol,
+                        data, text),
+      d_inverse(inverse) {}
 
-void MatrixFftCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixFftCommand::redo() {
+  if (!d_model)
+    return;
 
-    d_model->fft(d_inverse);
+  d_model->fft(d_inverse);
 }
 
 /*************************************************************************/
 /*           Class MatrixSetImageCommand                           */
 /*************************************************************************/
-MatrixSetImageCommand::MatrixSetImageCommand(MatrixModel *model, const QImage& image, Matrix::ViewType oldView,
-						int startRow, int endRow, int startCol, int endCol, double *data, const QString& text):
-MatrixUndoCommand(model, Matrix::SetImage, startRow, endRow, startCol, endCol, data, text),
-d_image(image),
-d_old_view(oldView)
-{
-}
+MatrixSetImageCommand::MatrixSetImageCommand(MatrixModel *model,
+                                             const QImage &image,
+                                             Matrix::ViewType oldView,
+                                             int startRow, int endRow,
+                                             int startCol, int endCol,
+                                             double *data, const QString &text)
+    : MatrixUndoCommand(model, Matrix::SetImage, startRow, endRow, startCol,
+                        endCol, data, text),
+      d_image(image), d_old_view(oldView) {}
 
-void MatrixSetImageCommand::undo()
-{
-    if (!d_model)
-        return;
+void MatrixSetImageCommand::undo() {
+  if (!d_model)
+    return;
 
-    d_model->setDimensions(d_end_row - d_start_row + 1, d_end_col - d_start_col + 1);
-	d_model->matrix()->setViewType(d_old_view);
-	MatrixUndoCommand::undo();
+  d_model->setDimensions(d_end_row - d_start_row + 1,
+                         d_end_col - d_start_col + 1);
+  d_model->matrix()->setViewType(d_old_view);
+  MatrixUndoCommand::undo();
 }
 
-void MatrixSetImageCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixSetImageCommand::redo() {
+  if (!d_model)
+    return;
 
-    d_model->setImage(d_image);
-    Matrix *m = d_model->matrix();
-	m->setViewType(Matrix::ImageView, false);
-	m->displayImage(d_image);
+  d_model->setImage(d_image);
+  Matrix *m = d_model->matrix();
+  m->setViewType(Matrix::ImageView, false);
+  m->displayImage(d_image);
 }
 
 /*************************************************************************/
 /*           Class MatrixImportAsciiCommand                              */
 /*************************************************************************/
-MatrixImportAsciiCommand::MatrixImportAsciiCommand(const QString &fname, const QString &sep,
-						int ignoredLines, bool stripSpaces, bool simplifySpaces,
-						const QString& commentString, Matrix::ImportMode importAs, const QLocale& locale,
-						int endLineChar, int maxRows, MatrixModel *model, int startRow, int endRow,
-						int startCol, int endCol, double *data, const QString& text):
-MatrixUndoCommand(model, Matrix::ImportAscii, startRow, endRow, startCol, endCol, data, text),
-d_path(fname),
-d_sep(sep),
-d_comment(commentString),
-d_ignore_lines(ignoredLines),
-d_end_line(endLineChar),
-d_max_rows(maxRows),
-d_strip_spaces(stripSpaces),
-d_simplify_spaces(simplifySpaces),
-d_mode(importAs),
-d_locale(locale)
-{
-}
+MatrixImportAsciiCommand::MatrixImportAsciiCommand(
+    const QString &fname, const QString &sep, int ignoredLines,
+    bool stripSpaces, bool simplifySpaces, const QString &commentString,
+    Matrix::ImportMode importAs, const QLocale &locale, int endLineChar,
+    int maxRows, MatrixModel *model, int startRow, int endRow, int startCol,
+    int endCol, double *data, const QString &text)
+    : MatrixUndoCommand(model, Matrix::ImportAscii, startRow, endRow, startCol,
+                        endCol, data, text),
+      d_path(fname), d_sep(sep), d_comment(commentString),
+      d_ignore_lines(ignoredLines), d_end_line(endLineChar),
+      d_max_rows(maxRows), d_strip_spaces(stripSpaces),
+      d_simplify_spaces(simplifySpaces), d_mode(importAs), d_locale(locale) {}
 
-void MatrixImportAsciiCommand::redo()
-{
-    if (!d_model)
-        return;
+void MatrixImportAsciiCommand::redo() {
+  if (!d_model)
+    return;
 
-	d_model->importASCII(d_path, d_sep, d_ignore_lines, d_strip_spaces, d_simplify_spaces,
-						d_comment, d_mode, d_locale, d_end_line, d_max_rows);
+  d_model->importASCII(d_path, d_sep, d_ignore_lines, d_strip_spaces,
+                       d_simplify_spaces, d_comment, d_mode, d_locale,
+                       d_end_line, d_max_rows);
 }
 
 /*************************************************************************/
 /*           Class MatrixSymmetryOperation                                */
 /*************************************************************************/
-MatrixSymmetryOperation::MatrixSymmetryOperation(MatrixModel *model, Matrix::Operation op, const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_operation(op)
-{
-    setText(model->matrix()->objectName() + ": " + text);
-}
-
-void MatrixSymmetryOperation::redo()
-{
-    if (!d_model)
-        return;
-
-    switch(d_operation){
-		case Matrix::Transpose:
-			d_model->transpose();
-		break;
-		case Matrix::Invert:
-			d_model->invert();
-		break;
-		case Matrix::FlipVertically:
-			d_model->flipVertically();
-		break;
-		case Matrix::FlipHorizontally:
-			d_model->flipHorizontally();
-		break;
-		case Matrix::RotateClockwise:
-			d_model->rotate90(true);
-		break;
-		case Matrix::RotateCounterClockwise:
-			d_model->rotate90(false);
-		break;
-		default:
-		break;
-	}
-	d_model->matrix()->resetView();
-}
-
-void MatrixSymmetryOperation::undo()
-{
-    if (!d_model)
-        return;
-
-    switch(d_operation){
-		case Matrix::Transpose:
-			d_model->transpose();
-		break;
-		case Matrix::Invert:
-			d_model->invert();
-		break;
-		case Matrix::FlipVertically:
-			d_model->flipVertically();
-		break;
-		case Matrix::FlipHorizontally:
-			d_model->flipHorizontally();
-		break;
-		case Matrix::RotateClockwise:
-			d_model->rotate90(false);
-		break;
-		case Matrix::RotateCounterClockwise:
-			d_model->rotate90(true);
-		break;
-		default:
-		break;
-	}
-	d_model->matrix()->resetView();
+MatrixSymmetryOperation::MatrixSymmetryOperation(MatrixModel *model,
+                                                 Matrix::Operation op,
+                                                 const QString &text)
+    : QUndoCommand(text), d_model(model), d_operation(op) {
+  setText(model->matrix()->objectName() + ": " + text);
+}
+
+void MatrixSymmetryOperation::redo() {
+  if (!d_model)
+    return;
+
+  switch (d_operation) {
+  case Matrix::Transpose:
+    d_model->transpose();
+    break;
+  case Matrix::Invert:
+    d_model->invert();
+    break;
+  case Matrix::FlipVertically:
+    d_model->flipVertically();
+    break;
+  case Matrix::FlipHorizontally:
+    d_model->flipHorizontally();
+    break;
+  case Matrix::RotateClockwise:
+    d_model->rotate90(true);
+    break;
+  case Matrix::RotateCounterClockwise:
+    d_model->rotate90(false);
+    break;
+  default:
+    break;
+  }
+  d_model->matrix()->resetView();
+}
+
+void MatrixSymmetryOperation::undo() {
+  if (!d_model)
+    return;
+
+  switch (d_operation) {
+  case Matrix::Transpose:
+    d_model->transpose();
+    break;
+  case Matrix::Invert:
+    d_model->invert();
+    break;
+  case Matrix::FlipVertically:
+    d_model->flipVertically();
+    break;
+  case Matrix::FlipHorizontally:
+    d_model->flipHorizontally();
+    break;
+  case Matrix::RotateClockwise:
+    d_model->rotate90(false);
+    break;
+  case Matrix::RotateCounterClockwise:
+    d_model->rotate90(true);
+    break;
+  default:
+    break;
+  }
+  d_model->matrix()->resetView();
 }
 
 /*************************************************************************/
 /*           Class MatrixPasteCommand                               	 */
 /*************************************************************************/
-MatrixPasteCommand::MatrixPasteCommand(MatrixModel *model, int startRow, int endRow, int startCol, int endCol,
-					double *clipboardData, int rows, int cols, double *backupData, int oldRows, int oldCols,
-					const QString& text):
-QUndoCommand(text),
-d_model(model),
-d_start_row(startRow),
-d_end_row(endRow),
-d_start_col(startCol),
-d_end_col(endCol),
-d_rows(rows),
-d_cols(cols),
-d_old_rows(oldRows),
-d_old_cols(oldCols),
-d_clipboard_data(clipboardData),
-d_backup_data(backupData)
-{
-    setText(model->matrix()->objectName() + ": " + text);
-}
-
-void MatrixPasteCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));	
-    d_model->pasteData(d_clipboard_data, d_start_row, d_start_col, d_rows, d_cols);
-	d_model->matrix()->resetView();
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixPasteCommand::undo()
-{
-	if (!d_model)
-        return;
-
- 	double *data = d_model->dataVector();
-    if (!data)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	if (d_old_rows != d_model->rowCount())
-		d_model->setRowCount(d_old_rows);
-	if (d_old_cols != d_model->columnCount())
-		d_model->setColumnCount(d_old_cols);
-
-    int cols = d_model->columnCount();
-	int aux = 0;
-    for (int i = d_start_row; i <= d_end_row; i++){
-        int row = i*cols + d_start_col;
-        for (int j = d_start_col; j <= d_end_col; j++)
-            data[row++] = d_backup_data[aux++];
-    }
-    d_model->matrix()->resetView();
-	QApplication::restoreOverrideCursor();
+MatrixPasteCommand::MatrixPasteCommand(MatrixModel *model, int startRow,
+                                       int endRow, int startCol, int endCol,
+                                       double *clipboardData, int rows,
+                                       int cols, double *backupData,
+                                       int oldRows, int oldCols,
+                                       const QString &text)
+    : QUndoCommand(text), d_model(model), d_start_row(startRow),
+      d_end_row(endRow), d_start_col(startCol), d_end_col(endCol), d_rows(rows),
+      d_cols(cols), d_old_rows(oldRows), d_old_cols(oldCols),
+      d_clipboard_data(clipboardData), d_backup_data(backupData) {
+  setText(model->matrix()->objectName() + ": " + text);
+}
+
+void MatrixPasteCommand::redo() {
+  if (!d_model)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_model->pasteData(d_clipboard_data, d_start_row, d_start_col, d_rows,
+                     d_cols);
+  d_model->matrix()->resetView();
+  QApplication::restoreOverrideCursor();
+}
+
+void MatrixPasteCommand::undo() {
+  if (!d_model)
+    return;
+
+  double *data = d_model->dataVector();
+  if (!data)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  if (d_old_rows != d_model->rowCount())
+    d_model->setRowCount(d_old_rows);
+  if (d_old_cols != d_model->columnCount())
+    d_model->setColumnCount(d_old_cols);
+
+  int cols = d_model->columnCount();
+  int aux = 0;
+  for (int i = d_start_row; i <= d_end_row; i++) {
+    int row = i * cols + d_start_col;
+    for (int j = d_start_col; j <= d_end_col; j++)
+      data[row++] = d_backup_data[aux++];
+  }
+  d_model->matrix()->resetView();
+  QApplication::restoreOverrideCursor();
 }
diff --git a/MantidPlot/src/MatrixCommand.h b/MantidPlot/src/MatrixCommand.h
index a281ce02d2bd4750d7cd541958f8a2ece5ab8a41..b2de5464fc2d3cc0b9c07e47a603ea53f16be0dc 100644
--- a/MantidPlot/src/MatrixCommand.h
+++ b/MantidPlot/src/MatrixCommand.h
@@ -34,271 +34,270 @@
 #include <QUndoCommand>
 
 //! Matrix commands used by the undo/redo framework
-class MatrixEditCellCommand: public QUndoCommand
-{
+class MatrixEditCellCommand : public QUndoCommand {
 public:
-    MatrixEditCellCommand(MatrixModel *model, const QModelIndex & index, double valBefore,
-                            double valAfter, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixEditCellCommand(MatrixModel *model, const QModelIndex &index,
+                        double valBefore, double valAfter, const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    QModelIndex d_index;
-    double d_val_before;
-    double d_val_after;
+  MatrixModel *d_model;
+  QModelIndex d_index;
+  double d_val_before;
+  double d_val_after;
 };
 
-class MatrixSetFormulaCommand: public QUndoCommand
-{
+class MatrixSetFormulaCommand : public QUndoCommand {
 public:
-    MatrixSetFormulaCommand(Matrix *m, const QString& oldFormula, const QString& newFormula, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixSetFormulaCommand(Matrix *m, const QString &oldFormula,
+                          const QString &newFormula, const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    QString d_old_formula;
-    QString d_new_formula;
+  Matrix *d_matrix;
+  QString d_old_formula;
+  QString d_new_formula;
 };
 
-class MatrixSetViewCommand: public QUndoCommand
-{
+class MatrixSetViewCommand : public QUndoCommand {
 public:
-    MatrixSetViewCommand(Matrix *m, Matrix::ViewType oldView, Matrix::ViewType newView, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixSetViewCommand(Matrix *m, Matrix::ViewType oldView,
+                       Matrix::ViewType newView, const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    Matrix::ViewType d_old_view;
-    Matrix::ViewType d_new_view;
+  Matrix *d_matrix;
+  Matrix::ViewType d_old_view;
+  Matrix::ViewType d_new_view;
 };
 
-class MatrixSetHeaderViewCommand: public QUndoCommand
-{
+class MatrixSetHeaderViewCommand : public QUndoCommand {
 public:
-    MatrixSetHeaderViewCommand(Matrix *m, Matrix::HeaderViewType oldView,
-                            Matrix::HeaderViewType newView, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixSetHeaderViewCommand(Matrix *m, Matrix::HeaderViewType oldView,
+                             Matrix::HeaderViewType newView,
+                             const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    Matrix::HeaderViewType d_old_view;
-    Matrix::HeaderViewType d_new_view;
+  Matrix *d_matrix;
+  Matrix::HeaderViewType d_old_view;
+  Matrix::HeaderViewType d_new_view;
 };
 
-class MatrixSetColWidthCommand: public QUndoCommand
-{
+class MatrixSetColWidthCommand : public QUndoCommand {
 public:
-    MatrixSetColWidthCommand(Matrix *m, int oldWidth, int newWidth, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixSetColWidthCommand(Matrix *m, int oldWidth, int newWidth,
+                           const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    int d_old_width;
-    int d_new_width;
+  Matrix *d_matrix;
+  int d_old_width;
+  int d_new_width;
 };
 
-class MatrixSetPrecisionCommand: public QUndoCommand
-{
+class MatrixSetPrecisionCommand : public QUndoCommand {
 public:
-    MatrixSetPrecisionCommand(Matrix *m, const QChar& oldFormat, const QChar& newFormat,
-                    int oldPrec, int newPrec, const QString & text);
-    void redo() override;
-    void undo() override;
+  MatrixSetPrecisionCommand(Matrix *m, const QChar &oldFormat,
+                            const QChar &newFormat, int oldPrec, int newPrec,
+                            const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    QChar d_old_format;
-    QChar d_new_format;
-    int d_old_prec;
-    int d_new_prec;
+  Matrix *d_matrix;
+  QChar d_old_format;
+  QChar d_new_format;
+  int d_old_prec;
+  int d_new_prec;
 };
 
-class MatrixSetCoordinatesCommand: public QUndoCommand
-{
+class MatrixSetCoordinatesCommand : public QUndoCommand {
 public:
-    MatrixSetCoordinatesCommand(Matrix *, double, double, double, double,
-                    double, double, double, double, const QString &);
-    void redo() override;
-    void undo() override;
+  MatrixSetCoordinatesCommand(Matrix *, double, double, double, double, double,
+                              double, double, double, const QString &);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    double d_old_xs, d_old_xe, d_old_ys, d_old_ye;
-    double d_new_xs, d_new_xe, d_new_ys, d_new_ye;
+  Matrix *d_matrix;
+  double d_old_xs, d_old_xe, d_old_ys, d_old_ye;
+  double d_new_xs, d_new_xe, d_new_ys, d_new_ye;
 };
 
-class MatrixSetColorMapCommand: public QUndoCommand
-{
+class MatrixSetColorMapCommand : public QUndoCommand {
 public:
-    MatrixSetColorMapCommand(Matrix *m, Matrix::ColorMapType d_map_type_before,
-					const QwtLinearColorMap& d_map_before, Matrix::ColorMapType d_map_type_after,
-					const QwtLinearColorMap& d_map_after, const QString& text);
-    void redo() override;
-    void undo() override;
+  MatrixSetColorMapCommand(Matrix *m, Matrix::ColorMapType d_map_type_before,
+                           const QwtLinearColorMap &d_map_before,
+                           Matrix::ColorMapType d_map_type_after,
+                           const QwtLinearColorMap &d_map_after,
+                           const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    Matrix *d_matrix;
-    Matrix::ColorMapType d_map_type_before, d_map_type_after;
-    QwtLinearColorMap d_map_before, d_map_after;
+  Matrix *d_matrix;
+  Matrix::ColorMapType d_map_type_before, d_map_type_after;
+  QwtLinearColorMap d_map_before, d_map_after;
 };
 
-class MatrixDeleteRowsCommand: public QUndoCommand
-{
+class MatrixDeleteRowsCommand : public QUndoCommand {
 public:
-    MatrixDeleteRowsCommand(MatrixModel *model, int startRow, int count, double* data, const QString& text);
-    ~MatrixDeleteRowsCommand() override { free(d_data); };
-    void redo() override;
-    void undo() override;
+  MatrixDeleteRowsCommand(MatrixModel *model, int startRow, int count,
+                          double *data, const QString &text);
+  ~MatrixDeleteRowsCommand() override { free(d_data); };
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    int d_start_row, d_count;
-	double* d_data;
+  MatrixModel *d_model;
+  int d_start_row, d_count;
+  double *d_data;
 };
 
-class MatrixInsertRowCommand: public QUndoCommand
-{
+class MatrixInsertRowCommand : public QUndoCommand {
 public:
-    MatrixInsertRowCommand(MatrixModel *model, int startRow, const QString& text);
-    void redo() override;
-    void undo() override;
+  MatrixInsertRowCommand(MatrixModel *model, int startRow, const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    int d_start_row;
+  MatrixModel *d_model;
+  int d_start_row;
 };
 
-class MatrixDeleteColsCommand: public QUndoCommand
-{
+class MatrixDeleteColsCommand : public QUndoCommand {
 public:
-    MatrixDeleteColsCommand(MatrixModel *model, int startCol, int count, double* data, const QString& text);
-    ~MatrixDeleteColsCommand() override { free(d_data); };
-    void redo() override;
-    void undo() override;
+  MatrixDeleteColsCommand(MatrixModel *model, int startCol, int count,
+                          double *data, const QString &text);
+  ~MatrixDeleteColsCommand() override { free(d_data); };
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    int d_start_col, d_count;
-	double* d_data;
+  MatrixModel *d_model;
+  int d_start_col, d_count;
+  double *d_data;
 };
 
-class MatrixInsertColCommand: public QUndoCommand
-{
+class MatrixInsertColCommand : public QUndoCommand {
 public:
-    MatrixInsertColCommand(MatrixModel *model, int startCol, const QString& text);
-    void redo() override;
-    void undo() override;
+  MatrixInsertColCommand(MatrixModel *model, int startCol, const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    int d_start_col;
+  MatrixModel *d_model;
+  int d_start_col;
 };
 
-class MatrixSetSizeCommand: public QUndoCommand
-{
+class MatrixSetSizeCommand : public QUndoCommand {
 public:
-    MatrixSetSizeCommand(MatrixModel *model, const QSize& oldSize, const QSize& newSize, double *data, const QString& text);
-    ~MatrixSetSizeCommand() override { free(d_backup); };
-    void redo() override;
-    void undo() override;
+  MatrixSetSizeCommand(MatrixModel *model, const QSize &oldSize,
+                       const QSize &newSize, double *data, const QString &text);
+  ~MatrixSetSizeCommand() override { free(d_backup); };
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    QSize d_old_size, d_new_size;
-	double *d_backup;
+  MatrixModel *d_model;
+  QSize d_old_size, d_new_size;
+  double *d_backup;
 };
 
-class MatrixUndoCommand: public QUndoCommand
-{
+class MatrixUndoCommand : public QUndoCommand {
 public:
-    MatrixUndoCommand(MatrixModel *model, Matrix::Operation op, int startRow, int endRow, int startCol, int endCol,
-						double *data, const QString& text);
-    ~MatrixUndoCommand() override { free(d_data); };
-    void redo() override;
-    void undo() override;
+  MatrixUndoCommand(MatrixModel *model, Matrix::Operation op, int startRow,
+                    int endRow, int startCol, int endCol, double *data,
+                    const QString &text);
+  ~MatrixUndoCommand() override { free(d_data); };
+  void redo() override;
+  void undo() override;
 
 protected:
-	MatrixModel *d_model;
-	Matrix::Operation d_operation;
-    int d_start_row, d_end_row, d_start_col, d_end_col;
-    double* d_data;
+  MatrixModel *d_model;
+  Matrix::Operation d_operation;
+  int d_start_row, d_end_row, d_start_col, d_end_col;
+  double *d_data;
 };
 
-class MatrixFftCommand: public MatrixUndoCommand
-{
+class MatrixFftCommand : public MatrixUndoCommand {
 public:
-    MatrixFftCommand(bool inverse, MatrixModel *model, int startRow, int endRow,
-					int startCol, int endCol, double *data, const QString& text);
-    void redo() override;
+  MatrixFftCommand(bool inverse, MatrixModel *model, int startRow, int endRow,
+                   int startCol, int endCol, double *data, const QString &text);
+  void redo() override;
 
 private:
-    bool d_inverse;
+  bool d_inverse;
 };
 
-class MatrixSetImageCommand: public MatrixUndoCommand
-{
+class MatrixSetImageCommand : public MatrixUndoCommand {
 public:
-    MatrixSetImageCommand(MatrixModel *model, const QImage& image, Matrix::ViewType oldView,
-						int startRow, int endRow, int startCol, int endCol, double *data, const QString& text);
-    void redo() override;
-    void undo() override;
+  MatrixSetImageCommand(MatrixModel *model, const QImage &image,
+                        Matrix::ViewType oldView, int startRow, int endRow,
+                        int startCol, int endCol, double *data,
+                        const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    QImage d_image;
-	Matrix::ViewType d_old_view;
+  QImage d_image;
+  Matrix::ViewType d_old_view;
 };
 
-class MatrixImportAsciiCommand: public MatrixUndoCommand
-{
+class MatrixImportAsciiCommand : public MatrixUndoCommand {
 public:
-    MatrixImportAsciiCommand(const QString &fname, const QString &sep,
-						int ignoredLines, bool stripSpaces, bool simplifySpaces,
-						const QString& commentString, Matrix::ImportMode importAs, const QLocale& locale,
-						int endLineChar, int maxRows, MatrixModel *model, int startRow, int endRow,
-						int startCol, int endCol, double *data, const QString& text);
-    void redo() override;
+  MatrixImportAsciiCommand(const QString &fname, const QString &sep,
+                           int ignoredLines, bool stripSpaces,
+                           bool simplifySpaces, const QString &commentString,
+                           Matrix::ImportMode importAs, const QLocale &locale,
+                           int endLineChar, int maxRows, MatrixModel *model,
+                           int startRow, int endRow, int startCol, int endCol,
+                           double *data, const QString &text);
+  void redo() override;
 
 private:
-	QString d_path, d_sep, d_comment;
-	int d_ignore_lines, d_end_line, d_max_rows;
-	bool d_strip_spaces, d_simplify_spaces;
-	Matrix::ImportMode d_mode;
-	QLocale d_locale;
+  QString d_path, d_sep, d_comment;
+  int d_ignore_lines, d_end_line, d_max_rows;
+  bool d_strip_spaces, d_simplify_spaces;
+  Matrix::ImportMode d_mode;
+  QLocale d_locale;
 };
 
-class MatrixSymmetryOperation: public QUndoCommand
-{
+class MatrixSymmetryOperation : public QUndoCommand {
 public:
-    MatrixSymmetryOperation(MatrixModel *model, Matrix::Operation op, const QString& text);
-    void redo() override;
-    void undo() override;
+  MatrixSymmetryOperation(MatrixModel *model, Matrix::Operation op,
+                          const QString &text);
+  void redo() override;
+  void undo() override;
 
 private:
-    MatrixModel *d_model;
-    Matrix::Operation d_operation;
+  MatrixModel *d_model;
+  Matrix::Operation d_operation;
 };
 
-class MatrixPasteCommand: public QUndoCommand
-{
+class MatrixPasteCommand : public QUndoCommand {
 public:
-    MatrixPasteCommand(MatrixModel *model, int startRow, int endRow, int startCol, int endCol,
-					double *clipboardData, int rows, int cols, double *backupData,
-					int oldRows, int oldCols, const QString& text);
-    ~MatrixPasteCommand() override {
-      free(d_clipboard_data);
-      free(d_backup_data);
-    };
-    void redo() override;
-    void undo() override;
+  MatrixPasteCommand(MatrixModel *model, int startRow, int endRow, int startCol,
+                     int endCol, double *clipboardData, int rows, int cols,
+                     double *backupData, int oldRows, int oldCols,
+                     const QString &text);
+  ~MatrixPasteCommand() override {
+    free(d_clipboard_data);
+    free(d_backup_data);
+  };
+  void redo() override;
+  void undo() override;
 
 private:
-	MatrixModel *d_model;
-    int d_start_row, d_end_row, d_start_col, d_end_col, d_rows, d_cols, d_old_rows, d_old_cols;
-	double *d_clipboard_data, *d_backup_data;
+  MatrixModel *d_model;
+  int d_start_row, d_end_row, d_start_col, d_end_col, d_rows, d_cols,
+      d_old_rows, d_old_cols;
+  double *d_clipboard_data, *d_backup_data;
 };
 #endif
diff --git a/MantidPlot/src/MatrixDialog.cpp b/MantidPlot/src/MatrixDialog.cpp
index 8454d697496aa46c7ed282eac6f5728abc8c3ea5..bf3329c81d8a66f317ee925a66cc63a93155d91f 100644
--- a/MantidPlot/src/MatrixDialog.cpp
+++ b/MantidPlot/src/MatrixDialog.cpp
@@ -37,122 +37,119 @@
 #include <QGroupBox>
 #include <QSpinBox>
 
-MatrixDialog::MatrixDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl ),
-    d_matrix(0)
-{
-    setWindowTitle( tr( "MantidPlot - Matrix Properties" ) );
-
-	QGridLayout * topLayout = new QGridLayout();
-	QHBoxLayout * bottomLayout = new QHBoxLayout();
-
-	topLayout->addWidget( new QLabel(tr( "Cell Width" )), 0, 0 );
-	boxColWidth = new QSpinBox();
-	boxColWidth->setRange(0,1000);
-	boxColWidth->setSingleStep(10);
-	topLayout->addWidget( boxColWidth, 0, 1 );
-
-	topLayout->addWidget( new QLabel(tr( "Data Format" )), 1, 0 );
-	boxFormat = new QComboBox();
-    boxFormat->addItem( tr( "Decimal: 1000" ) );
-	boxFormat->addItem( tr( "Scientific: 1E3" ) );
-
-	topLayout->addWidget( boxFormat, 1, 1 );
-
-	topLayout->addWidget( new QLabel( tr( "Numeric Display" )), 2, 0 );
-	boxNumericDisplay = new QComboBox();
-    boxNumericDisplay->addItem( tr( "Default Decimal Digits" ) );
-	boxNumericDisplay->addItem( tr( "Significant Digits=" ) );
-
-	topLayout->addWidget( boxNumericDisplay, 2, 1 );
-	boxPrecision = new QSpinBox();
-	boxPrecision->setRange(0, 13);
-	boxPrecision->setEnabled( false );
-	topLayout->addWidget( boxPrecision, 2, 2 );
-
-	buttonApply = new QPushButton(tr( "&Apply" ));
-	buttonApply->setAutoDefault( true );
-	bottomLayout->addWidget( buttonApply );
-
-	buttonOk = new QPushButton(tr( "&OK" ));
-	buttonOk->setAutoDefault( true );
-	buttonOk->setDefault( true );
-	bottomLayout->addWidget( buttonOk );
-
-	buttonCancel = new QPushButton(tr( "&Cancel" ));
-	buttonCancel->setAutoDefault( true );
-	bottomLayout->addWidget( buttonCancel );
-
-	QVBoxLayout * mainLayout = new QVBoxLayout(this);
-	mainLayout->addLayout(topLayout);
-	mainLayout->addLayout(bottomLayout);
-
-	// signals and slots connections
-	connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
-	connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
-	connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
-	connect(boxNumericDisplay, SIGNAL(activated(int)), this, SLOT(showPrecisionBox(int)));
+MatrixDialog::MatrixDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), d_matrix(0) {
+  setWindowTitle(tr("MantidPlot - Matrix Properties"));
+
+  QGridLayout *topLayout = new QGridLayout();
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
+
+  topLayout->addWidget(new QLabel(tr("Cell Width")), 0, 0);
+  boxColWidth = new QSpinBox();
+  boxColWidth->setRange(0, 1000);
+  boxColWidth->setSingleStep(10);
+  topLayout->addWidget(boxColWidth, 0, 1);
+
+  topLayout->addWidget(new QLabel(tr("Data Format")), 1, 0);
+  boxFormat = new QComboBox();
+  boxFormat->addItem(tr("Decimal: 1000"));
+  boxFormat->addItem(tr("Scientific: 1E3"));
+
+  topLayout->addWidget(boxFormat, 1, 1);
+
+  topLayout->addWidget(new QLabel(tr("Numeric Display")), 2, 0);
+  boxNumericDisplay = new QComboBox();
+  boxNumericDisplay->addItem(tr("Default Decimal Digits"));
+  boxNumericDisplay->addItem(tr("Significant Digits="));
+
+  topLayout->addWidget(boxNumericDisplay, 2, 1);
+  boxPrecision = new QSpinBox();
+  boxPrecision->setRange(0, 13);
+  boxPrecision->setEnabled(false);
+  topLayout->addWidget(boxPrecision, 2, 2);
+
+  buttonApply = new QPushButton(tr("&Apply"));
+  buttonApply->setAutoDefault(true);
+  bottomLayout->addWidget(buttonApply);
+
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
+  bottomLayout->addWidget(buttonOk);
+
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  buttonCancel->setAutoDefault(true);
+  bottomLayout->addWidget(buttonCancel);
+
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  mainLayout->addLayout(topLayout);
+  mainLayout->addLayout(bottomLayout);
+
+  // signals and slots connections
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
+  connect(boxNumericDisplay, SIGNAL(activated(int)), this,
+          SLOT(showPrecisionBox(int)));
 }
 
-void MatrixDialog::showPrecisionBox(int item)
-{
-	if (item)
-		boxPrecision->setEnabled(true);
-	else {
-		boxPrecision->setValue(6);
-		boxPrecision->setEnabled(false);
-	}
+void MatrixDialog::showPrecisionBox(int item) {
+  if (item)
+    boxPrecision->setEnabled(true);
+  else {
+    boxPrecision->setValue(6);
+    boxPrecision->setEnabled(false);
+  }
 }
 
-void MatrixDialog::apply()
-{
-    int width = boxColWidth->value();
-    if (d_matrix->columnsWidth() != width){
-        d_matrix->undoStack()->push(new MatrixSetColWidthCommand(d_matrix, d_matrix->columnsWidth(),
-                        width, tr("Set Columns Width") + " " + QString::number(width)));
-        d_matrix->setColumnsWidth(width);
-    }
-
-    int prec = boxPrecision->value();
-    QChar format = 'f';
-    QString fmtName = tr("Decimal");
-    if (boxFormat->currentIndex()){
-        format = 'e';
-        fmtName = tr("Scientific");
-    }
-
-    QChar oldFormat = d_matrix->textFormat();
-    int oldPrec = d_matrix->precision();
-    if (oldFormat != format || oldPrec != prec){
-        d_matrix->undoStack()->push(new MatrixSetPrecisionCommand(d_matrix, oldFormat, format,
-                        oldPrec, prec, tr("Set Data Format %1").arg(fmtName) + " - " +
-                        tr("Precision %1 digits").arg(prec)));
-        d_matrix->setNumericFormat(format, prec);
-    }
+void MatrixDialog::apply() {
+  int width = boxColWidth->value();
+  if (d_matrix->columnsWidth() != width) {
+    d_matrix->undoStack()->push(new MatrixSetColWidthCommand(
+        d_matrix, d_matrix->columnsWidth(), width,
+        tr("Set Columns Width") + " " + QString::number(width)));
+    d_matrix->setColumnsWidth(width);
+  }
+
+  int prec = boxPrecision->value();
+  QChar format = 'f';
+  QString fmtName = tr("Decimal");
+  if (boxFormat->currentIndex()) {
+    format = 'e';
+    fmtName = tr("Scientific");
+  }
+
+  QChar oldFormat = d_matrix->textFormat();
+  int oldPrec = d_matrix->precision();
+  if (oldFormat != format || oldPrec != prec) {
+    d_matrix->undoStack()->push(new MatrixSetPrecisionCommand(
+        d_matrix, oldFormat, format, oldPrec, prec,
+        tr("Set Data Format %1").arg(fmtName) + " - " +
+            tr("Precision %1 digits").arg(prec)));
+    d_matrix->setNumericFormat(format, prec);
+  }
 }
 
-void MatrixDialog::setMatrix(Matrix *m)
-{
-    if (!m)
-        return;
+void MatrixDialog::setMatrix(Matrix *m) {
+  if (!m)
+    return;
 
-    d_matrix = m;
-    boxColWidth->setValue(m->columnsWidth());
+  d_matrix = m;
+  boxColWidth->setValue(m->columnsWidth());
 
-    if (QString(m->textFormat()) == "f")
-		boxFormat->setCurrentIndex(0);
-	else
-		boxFormat->setCurrentIndex(1);
+  if (QString(m->textFormat()) == "f")
+    boxFormat->setCurrentIndex(0);
+  else
+    boxFormat->setCurrentIndex(1);
 
-	boxPrecision->setValue(m->precision());
-	if (m->precision() != 6){
-		boxPrecision->setEnabled( true );
-		boxNumericDisplay->setCurrentIndex(1);
-	}
+  boxPrecision->setValue(m->precision());
+  if (m->precision() != 6) {
+    boxPrecision->setEnabled(true);
+    boxNumericDisplay->setCurrentIndex(1);
+  }
 }
 
-void MatrixDialog::accept()
-{
-	apply();
-	close();
+void MatrixDialog::accept() {
+  apply();
+  close();
 }
diff --git a/MantidPlot/src/MatrixDialog.h b/MantidPlot/src/MatrixDialog.h
index 58621c9d69269846d7c3867f7872d8946bac3b13..870c511608edb6951ea2329462cb08c87dc4b1ac 100644
--- a/MantidPlot/src/MatrixDialog.h
+++ b/MantidPlot/src/MatrixDialog.h
@@ -37,34 +37,33 @@ class QSpinBox;
 class QComboBox;
 
 //! Matrix properties dialog
-class MatrixDialog : public QDialog
-{
-    Q_OBJECT
+class MatrixDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	//! Constructor
-	/**
-	 * @param parent :: parent widget
-	 * @param fl :: window flags
-	 */
-    MatrixDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
-    void setMatrix(Matrix *m);
+  //! Constructor
+  /**
+   * @param parent :: parent widget
+   * @param fl :: window flags
+   */
+  MatrixDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
+  void setMatrix(Matrix *m);
 
 private slots:
-	//! Accept changes and quit
+  //! Accept changes and quit
   void accept() override;
-        //! Apply changes
-	void apply();
-	//! Activate the numeric precision choice box
-	void showPrecisionBox(int item);
+  //! Apply changes
+  void apply();
+  //! Activate the numeric precision choice box
+  void showPrecisionBox(int item);
 
 private:
-    Matrix *d_matrix;
+  Matrix *d_matrix;
 
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel, *buttonApply;
-	QSpinBox* boxColWidth, *boxPrecision;
-	QComboBox *boxFormat, *boxNumericDisplay;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel, *buttonApply;
+  QSpinBox *boxColWidth, *boxPrecision;
+  QComboBox *boxFormat, *boxNumericDisplay;
 };
 
 #endif // MATRIXDIALOG_H
diff --git a/MantidPlot/src/MatrixModel.cpp b/MantidPlot/src/MatrixModel.cpp
index 70b5030e22f321a034e6815cb35f1ddd5b6a47c6..7f59a0ecb5e4232475b07765cf22284b27c64dbf 100644
--- a/MantidPlot/src/MatrixModel.cpp
+++ b/MantidPlot/src/MatrixModel.cpp
@@ -818,13 +818,13 @@ bool MatrixModel::muParserCalculate(int startRow, int endRow, int startCol,
       double r = row + 1.0;
       *ri = r;
       *rr = r;
-      *y = y_start + row * dy;
+      *y = y_start + row *dy;
       int aux = row * d_cols + startCol;
       for (int col = startCol; col <= endCol; col++) {
         double c = col + 1.0;
         *cj = c;
         *cc = c;
-        *x = x_start + col * dx;
+        *x = x_start + col *dx;
         d_data[aux++] = mup->evalSingleLine();
       }
     }
@@ -834,13 +834,13 @@ bool MatrixModel::muParserCalculate(int startRow, int endRow, int startCol,
       double r = row + 1.0;
       *ri = r;
       *rr = r;
-      *y = y_start + row * dy;
+      *y = y_start + row *dy;
       int aux = row * d_cols + startCol;
       for (int col = startCol; col <= endCol; col++) {
         double c = col + 1.0;
         *cj = c;
         *cc = c;
-        *x = x_start + col * dx;
+        *x = x_start + col *dx;
         res = mup->evaluate(ScriptCode(d_matrix->formula()));
         if (res.canConvert(QVariant::Double))
           d_data[aux++] = res.toDouble();
diff --git a/MantidPlot/src/MatrixModel.h b/MantidPlot/src/MatrixModel.h
index e502394a8f7bc0e7248ccbe6dd600effc60c8d1d..25cdcdfc51453a3009d3eb53d87766518f1da1a1 100644
--- a/MantidPlot/src/MatrixModel.h
+++ b/MantidPlot/src/MatrixModel.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : MatrixModel.h
-	Project              : QtiPlot
+        File                 : MatrixModel.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2007 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : QtiPlot's matrix model
+        Copyright            : (C) 2007 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : QtiPlot's matrix model
 
  ***************************************************************************/
 
@@ -41,106 +41,110 @@
 
 class Matrix;
 
-class MatrixModel : public QAbstractTableModel
-{
-    Q_OBJECT
+class MatrixModel : public QAbstractTableModel {
+  Q_OBJECT
 
 protected:
   explicit MatrixModel(QObject *parent);
 
 public:
-    MatrixModel(int rows = 32, int cols = 32, QObject *parent = 0);
-    MatrixModel(const QImage& image, QObject *parent);
-    ~MatrixModel() override;
+  MatrixModel(int rows = 32, int cols = 32, QObject *parent = 0);
+  MatrixModel(const QImage &image, QObject *parent);
+  ~MatrixModel() override;
 
-    Matrix *matrix(){return d_matrix;};
+  Matrix *matrix() { return d_matrix; };
 
-    Qt::ItemFlags flags(const QModelIndex &index) const override;
+  Qt::ItemFlags flags(const QModelIndex &index) const override;
 
-    virtual bool canResize(int rows, int cols);
-	virtual void setDimensions(int rows, int cols);
+  virtual bool canResize(int rows, int cols);
+  virtual void setDimensions(int rows, int cols);
 
-        int rowCount(const QModelIndex &parent = QModelIndex()) const override;
-        virtual void setRowCount(int rows);
+  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
+  virtual void setRowCount(int rows);
 
-        int
-        columnCount(const QModelIndex &parent = QModelIndex()) const override;
-        virtual void setColumnCount(int cols);
+  int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+  virtual void setColumnCount(int cols);
 
-        bool removeRows(int row, int count,
-                        const QModelIndex &parent = QModelIndex()) override;
-        bool insertRows(int row, int count,
-                        const QModelIndex &parent = QModelIndex()) override;
+  bool removeRows(int row, int count,
+                  const QModelIndex &parent = QModelIndex()) override;
+  bool insertRows(int row, int count,
+                  const QModelIndex &parent = QModelIndex()) override;
 
-        bool removeColumns(int column, int count,
-                           const QModelIndex &parent = QModelIndex()) override;
-        bool insertColumns(int column, int count,
-                           const QModelIndex &parent = QModelIndex()) override;
+  bool removeColumns(int column, int count,
+                     const QModelIndex &parent = QModelIndex()) override;
+  bool insertColumns(int column, int count,
+                     const QModelIndex &parent = QModelIndex()) override;
 
-        virtual double x(int col) const;
-	virtual double y(int row) const;
+  virtual double x(int col) const;
+  virtual double y(int row) const;
 
-	virtual double cell(int row, int col) const;
-	virtual void setCell(int row, int col, double val);
+  virtual double cell(int row, int col) const;
+  virtual void setCell(int row, int col, double val);
 
-	virtual QString text(int row, int col);
-	virtual void setText(int row, int col, const QString&);
+  virtual QString text(int row, int col);
+  virtual void setText(int row, int col, const QString &);
 
-	std::string saveToProject();
-	virtual QImage renderImage();
+  std::string saveToProject();
+  virtual QImage renderImage();
 
-	virtual double data(int row, int col) const;
-        QVariant data(const QModelIndex &index,
+  virtual double data(int row, int col) const;
+  QVariant data(const QModelIndex &index,
+                int role = Qt::DisplayRole) const override;
+  bool setData(const QModelIndex &index, const QVariant &value,
+               int role) override;
+
+  virtual double *dataVector() { return d_data; };
+  QVariant headerData(int section, Qt::Orientation orientation,
                       int role = Qt::DisplayRole) const override;
-        bool setData(const QModelIndex &index, const QVariant &value,
-                     int role) override;
-
-    virtual double* dataVector(){return d_data;};
-    QVariant headerData(int section, Qt::Orientation orientation,
-                        int role = Qt::DisplayRole) const override;
-
-        virtual void setImage(const QImage& image);
-
-	virtual 
-    bool importASCII(const QString &fname, const QString &sep, int ignoredLines, bool stripSpaces,
-					bool simplifySpaces, const QString& commentString, int importAs,
-					const QLocale& locale, int endLineChar = 0, int maxRows = -1);
-
-	void setLocale(const QLocale& locale){d_locale = locale;};
-	void setNumericFormat(char f, int prec);
-
-	virtual bool initWorkspace();
-	virtual void invert();
-	virtual void transpose();
-	virtual void flipVertically();
-	virtual void flipHorizontally();
-	virtual void rotate90(bool clockwise);
-	virtual void fft(bool inverse);
-	virtual void clear(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1);
-	virtual bool calculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1);
-	virtual bool muParserCalculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1);
-	virtual double* dataCopy(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1);
-	virtual void pasteData(double *clipboardBuffer, int topRow, int leftCol, int rows, int cols);
+
+  virtual void setImage(const QImage &image);
+
+  virtual bool importASCII(const QString &fname, const QString &sep,
+                           int ignoredLines, bool stripSpaces,
+                           bool simplifySpaces, const QString &commentString,
+                           int importAs, const QLocale &locale,
+                           int endLineChar = 0, int maxRows = -1);
+
+  void setLocale(const QLocale &locale) { d_locale = locale; };
+  void setNumericFormat(char f, int prec);
+
+  virtual bool initWorkspace();
+  virtual void invert();
+  virtual void transpose();
+  virtual void flipVertically();
+  virtual void flipHorizontally();
+  virtual void rotate90(bool clockwise);
+  virtual void fft(bool inverse);
+  virtual void clear(int startRow = 0, int endRow = -1, int startCol = 0,
+                     int endCol = -1);
+  virtual bool calculate(int startRow = 0, int endRow = -1, int startCol = 0,
+                         int endCol = -1);
+  virtual bool muParserCalculate(int startRow = 0, int endRow = -1,
+                                 int startCol = 0, int endCol = -1);
+  virtual double *dataCopy(int startRow = 0, int endRow = -1, int startCol = 0,
+                           int endCol = -1);
+  virtual void pasteData(double *clipboardBuffer, int topRow, int leftCol,
+                         int rows, int cols);
 
 protected:
-	Matrix *d_matrix;
-    int d_rows, d_cols;
-
-//private:
-	void init();
-    double *d_data;
-	//! Format code for displaying numbers
-	char d_txt_format;
-	//! Number of significant digits
-	int d_num_precision;
-	//! Locale used to display data
-	QLocale d_locale;
-
-	//! Pointers to GSL matrices used during inversion operations
-	gsl_matrix *d_direct_matrix, *d_inv_matrix;
-	//! Pointer to a GSL permutation used during inversion operations
-	gsl_permutation *d_inv_perm;
-	QSize d_data_block_size;
+  Matrix *d_matrix;
+  int d_rows, d_cols;
+
+  // private:
+  void init();
+  double *d_data;
+  //! Format code for displaying numbers
+  char d_txt_format;
+  //! Number of significant digits
+  int d_num_precision;
+  //! Locale used to display data
+  QLocale d_locale;
+
+  //! Pointers to GSL matrices used during inversion operations
+  gsl_matrix *d_direct_matrix, *d_inv_matrix;
+  //! Pointer to a GSL permutation used during inversion operations
+  gsl_permutation *d_inv_perm;
+  QSize d_data_block_size;
 };
 
 #endif
diff --git a/MantidPlot/src/MatrixSizeDialog.cpp b/MantidPlot/src/MatrixSizeDialog.cpp
index 1fcecc8c48a652fce28080615ac18f41fc948501..b6bb21bba505d8f6a86308b154215a43e7ae38a3 100644
--- a/MantidPlot/src/MatrixSizeDialog.cpp
+++ b/MantidPlot/src/MatrixSizeDialog.cpp
@@ -37,99 +37,99 @@
 #include <QMessageBox>
 #include <QLayout>
 
-MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl ),
-    d_matrix(m)
-{
-    setWindowTitle(tr("MantidPlot - Matrix Dimensions"));
-
-	groupBox1 = new QGroupBox(tr("Dimensions"));
-	QHBoxLayout *topLayout = new QHBoxLayout(groupBox1);
-	topLayout->addWidget( new QLabel(tr( "Rows" )) );
-    boxRows = new QSpinBox();
-    boxRows->setRange(1, 1000000);
-	topLayout->addWidget(boxRows);
-	topLayout->addStretch();
-	topLayout->addWidget( new QLabel(tr( "Columns" )) );
-    boxCols = new QSpinBox();
-	boxCols->setRange(1, 1000000);
-	topLayout->addWidget(boxCols);
-
-    groupBox2 = new QGroupBox(tr("Coordinates"));
-    QGridLayout *centerLayout = new QGridLayout(groupBox2);
-	centerLayout->addWidget( new QLabel(tr( "X (Columns)" )), 0, 1 );
-	centerLayout->addWidget( new QLabel(tr( "Y (Rows)" )), 0, 2 );
-
-	centerLayout->addWidget( new QLabel(tr( "First" )), 1, 0 );
-
-	QLocale locale = m->locale();
-    boxXStart = new DoubleSpinBox();
-    boxXStart->setLocale(locale);
-    centerLayout->addWidget( boxXStart, 1, 1 );
-
-    boxYStart = new DoubleSpinBox();
-    boxYStart->setLocale(locale);
-	centerLayout->addWidget( boxYStart, 1, 2 );
-
-	centerLayout->addWidget( new QLabel(tr( "Last" )), 2, 0 );
-    boxXEnd = new DoubleSpinBox();
-    boxXEnd->setLocale(locale);
-    centerLayout->addWidget( boxXEnd, 2, 1 );
-
-    boxYEnd = new DoubleSpinBox();
-    boxYEnd->setLocale(locale);
-	centerLayout->addWidget( boxYEnd, 2, 2 );
-	centerLayout->setRowStretch(3, 1);
-
-    QHBoxLayout *bottomLayout = new QHBoxLayout();
-    bottomLayout->addStretch();
-	buttonApply = new QPushButton(tr("&Apply"));
-	buttonApply->setDefault( true );
-	bottomLayout->addWidget(buttonApply);
-	buttonOk = new QPushButton(tr("&OK"));
-	bottomLayout->addWidget( buttonOk );
-    buttonCancel = new QPushButton(tr("&Cancel"));
-	bottomLayout->addWidget( buttonCancel );
-
-	QVBoxLayout * mainLayout = new QVBoxLayout( this );
-    mainLayout->addWidget(groupBox1);
-	mainLayout->addWidget(groupBox2);
-	mainLayout->addLayout(bottomLayout);
-
-    boxRows->setValue(m->numRows());
-    boxCols->setValue(m->numCols());
-
-    boxXStart->setValue(m->xStart());
-	boxYStart->setValue(m->yStart());
-	boxXEnd->setValue(m->xEnd());
-	boxYEnd->setValue(m->yEnd());
-
-	connect( buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
-    connect( buttonOk, SIGNAL(clicked()), this, SLOT(accept() ));
-    connect( buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+MatrixSizeDialog::MatrixSizeDialog(Matrix *m, QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), d_matrix(m) {
+  setWindowTitle(tr("MantidPlot - Matrix Dimensions"));
+
+  groupBox1 = new QGroupBox(tr("Dimensions"));
+  QHBoxLayout *topLayout = new QHBoxLayout(groupBox1);
+  topLayout->addWidget(new QLabel(tr("Rows")));
+  boxRows = new QSpinBox();
+  boxRows->setRange(1, 1000000);
+  topLayout->addWidget(boxRows);
+  topLayout->addStretch();
+  topLayout->addWidget(new QLabel(tr("Columns")));
+  boxCols = new QSpinBox();
+  boxCols->setRange(1, 1000000);
+  topLayout->addWidget(boxCols);
+
+  groupBox2 = new QGroupBox(tr("Coordinates"));
+  QGridLayout *centerLayout = new QGridLayout(groupBox2);
+  centerLayout->addWidget(new QLabel(tr("X (Columns)")), 0, 1);
+  centerLayout->addWidget(new QLabel(tr("Y (Rows)")), 0, 2);
+
+  centerLayout->addWidget(new QLabel(tr("First")), 1, 0);
+
+  QLocale locale = m->locale();
+  boxXStart = new DoubleSpinBox();
+  boxXStart->setLocale(locale);
+  centerLayout->addWidget(boxXStart, 1, 1);
+
+  boxYStart = new DoubleSpinBox();
+  boxYStart->setLocale(locale);
+  centerLayout->addWidget(boxYStart, 1, 2);
+
+  centerLayout->addWidget(new QLabel(tr("Last")), 2, 0);
+  boxXEnd = new DoubleSpinBox();
+  boxXEnd->setLocale(locale);
+  centerLayout->addWidget(boxXEnd, 2, 1);
+
+  boxYEnd = new DoubleSpinBox();
+  boxYEnd->setLocale(locale);
+  centerLayout->addWidget(boxYEnd, 2, 2);
+  centerLayout->setRowStretch(3, 1);
+
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
+  bottomLayout->addStretch();
+  buttonApply = new QPushButton(tr("&Apply"));
+  buttonApply->setDefault(true);
+  bottomLayout->addWidget(buttonApply);
+  buttonOk = new QPushButton(tr("&OK"));
+  bottomLayout->addWidget(buttonOk);
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  bottomLayout->addWidget(buttonCancel);
+
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  mainLayout->addWidget(groupBox1);
+  mainLayout->addWidget(groupBox2);
+  mainLayout->addLayout(bottomLayout);
+
+  boxRows->setValue(m->numRows());
+  boxCols->setValue(m->numCols());
+
+  boxXStart->setValue(m->xStart());
+  boxYStart->setValue(m->yStart());
+  boxXEnd->setValue(m->xEnd());
+  boxYEnd->setValue(m->yEnd());
+
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void MatrixSizeDialog::apply()
-{
-	double fromX = boxXStart->value();
-	double toX = boxXEnd->value();
-	double fromY = boxYStart->value();
-	double toY = boxYEnd->value();
-    double oxs = d_matrix->xStart();
-    double oxe = d_matrix->xEnd();
-    double oys = d_matrix->yStart();
-    double oye = d_matrix->yEnd();
-    if(oxs != fromX || oxe != toX || oys != fromY || oye != toY){
-        d_matrix->undoStack()->push(new MatrixSetCoordinatesCommand(d_matrix,
-                        oxs, oxe, oys, oye, fromX, toX, fromY, toY,
-                        tr("Set Coordinates x[%1 : %2], y[%3 : %4]").arg(fromX).arg(toX).arg(fromY).arg(toY)));
-        d_matrix->setCoordinates(fromX, toX, fromY, toY);
-    }
-	d_matrix->setDimensions(boxRows->value(), boxCols->value());
+void MatrixSizeDialog::apply() {
+  double fromX = boxXStart->value();
+  double toX = boxXEnd->value();
+  double fromY = boxYStart->value();
+  double toY = boxYEnd->value();
+  double oxs = d_matrix->xStart();
+  double oxe = d_matrix->xEnd();
+  double oys = d_matrix->yStart();
+  double oye = d_matrix->yEnd();
+  if (oxs != fromX || oxe != toX || oys != fromY || oye != toY) {
+    d_matrix->undoStack()->push(new MatrixSetCoordinatesCommand(
+        d_matrix, oxs, oxe, oys, oye, fromX, toX, fromY, toY,
+        tr("Set Coordinates x[%1 : %2], y[%3 : %4]")
+            .arg(fromX)
+            .arg(toX)
+            .arg(fromY)
+            .arg(toY)));
+    d_matrix->setCoordinates(fromX, toX, fromY, toY);
+  }
+  d_matrix->setDimensions(boxRows->value(), boxCols->value());
 }
 
-void MatrixSizeDialog::accept()
-{
-	apply();
-	close();
+void MatrixSizeDialog::accept() {
+  apply();
+  close();
 }
diff --git a/MantidPlot/src/MatrixSizeDialog.h b/MantidPlot/src/MatrixSizeDialog.h
index 9d60b566f23a73b35b04b542b63f3158a62ee12c..a038597a92ba5a68ffe87eaed3f1b1b35bc4cd72 100644
--- a/MantidPlot/src/MatrixSizeDialog.h
+++ b/MantidPlot/src/MatrixSizeDialog.h
@@ -38,31 +38,30 @@ class QSpinBox;
 class DoubleSpinBox;
 
 //! Matrix dimensions dialog
-class MatrixSizeDialog : public QDialog
-{
-    Q_OBJECT
+class MatrixSizeDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	//! Constructor
-	/**
-	 * @param parent :: parent widget
-	 * @param fl :: window flags
-	 */
-    MatrixSizeDialog(Matrix *m, QWidget* parent = 0, Qt::WFlags fl = 0);
+  //! Constructor
+  /**
+   * @param parent :: parent widget
+   * @param fl :: window flags
+   */
+  MatrixSizeDialog(Matrix *m, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 private slots:
-	//! Accept changes and quit
+  //! Accept changes and quit
   void accept() override;
-        //! Apply changes
-	void apply();
+  //! Apply changes
+  void apply();
 
 private:
-    QPushButton* buttonOk, *buttonApply;
-	QPushButton* buttonCancel;
-    QGroupBox* groupBox1, *groupBox2;
-	QSpinBox *boxCols, *boxRows;
-	DoubleSpinBox *boxXStart, *boxYStart, *boxXEnd, *boxYEnd;
-	Matrix *d_matrix;
+  QPushButton *buttonOk, *buttonApply;
+  QPushButton *buttonCancel;
+  QGroupBox *groupBox1, *groupBox2;
+  QSpinBox *boxCols, *boxRows;
+  DoubleSpinBox *boxXStart, *boxYStart, *boxXEnd, *boxYEnd;
+  Matrix *d_matrix;
 };
 
 #endif // MATRIXSIZEDIALOG_H
diff --git a/MantidPlot/src/MatrixValuesDialog.cpp b/MantidPlot/src/MatrixValuesDialog.cpp
index eca30a80e17f175d5a9f3e552f749b96b58194fb..de197d557d77d554373ce8ceb08cbb51b9aaaf21 100644
--- a/MantidPlot/src/MatrixValuesDialog.cpp
+++ b/MantidPlot/src/MatrixValuesDialog.cpp
@@ -46,121 +46,114 @@
 #include <QCheckBox>
 #endif
 
-MatrixValuesDialog::MatrixValuesDialog( ScriptingEnv *env, QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ), Scripted(env), matrix(NULL)
-{
-    setObjectName("MatrixValuesDialog");
-    setWindowTitle( tr( "MantidPlot - Set Matrix Values" ) );
-    setSizeGripEnabled(true);
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel(tr("For row (i)")), 0, 0);
-    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();
-    vbox1->addLayout(gl1);
-    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);
-
-    QVBoxLayout *vbox2 = new QVBoxLayout();
-    btnApply = new QPushButton(tr( "&Apply" ));
-    vbox2->addWidget(btnApply);
-    btnCancel = new QPushButton(tr( "&Close" ));
-    vbox2->addWidget(btnCancel);
-    vbox2->addStretch();
-
-    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);
-
-    connect(btnApply, SIGNAL(clicked()), this, SLOT(apply()));
-    connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
+MatrixValuesDialog::MatrixValuesDialog(ScriptingEnv *env, QWidget *parent,
+                                       Qt::WFlags fl)
+    : QDialog(parent, fl), Scripted(env), matrix(NULL) {
+  setObjectName("MatrixValuesDialog");
+  setWindowTitle(tr("MantidPlot - Set Matrix Values"));
+  setSizeGripEnabled(true);
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("For row (i)")), 0, 0);
+  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();
+  vbox1->addLayout(gl1);
+  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);
+
+  QVBoxLayout *vbox2 = new QVBoxLayout();
+  btnApply = new QPushButton(tr("&Apply"));
+  vbox2->addWidget(btnApply);
+  btnCancel = new QPushButton(tr("&Close"));
+  vbox2->addWidget(btnCancel);
+  vbox2->addStretch();
+
+  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);
+
+  connect(btnApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
 }
 
-QSize MatrixValuesDialog::sizeHint() const
-{
-    return QSize( 400, 190 );
-}
+QSize MatrixValuesDialog::sizeHint() const { return QSize(400, 190); }
 
-void MatrixValuesDialog::customEvent(QEvent *e)
-{
-	if (e->type() == SCRIPTING_CHANGE_EVENT) {
-    if (auto sce = dynamic_cast<ScriptingChangeEvent*>(e)) {
+void MatrixValuesDialog::customEvent(QEvent *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();
-
-    matrix->setFormula(formula);
-	
-    bool useMuParser = true;
-	
-    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;
-	}
-    matrix->setFormula(oldFormula);
-    return false;
-}
+bool MatrixValuesDialog::apply() {
+  QString formula = commands->text();
+  QString oldFormula = matrix->formula();
 
-void MatrixValuesDialog::setMatrix(Matrix* m)
-{
-    if (!m)
-        return;
-
-    matrix = m;
-    commands->setText(m->formula());
-
-    endCol->setValue(m->numCols());
-    endRow->setValue(m->numRows());
-
-    if (m->viewType() == Matrix::TableView){
-        QItemSelectionModel *selModel = m->selectionModel();
-        if (selModel->hasSelection()){
-            QItemSelectionRange selection = selModel->selection().first();
-            if (selection.width() > 1 || selection.height() > 1){
-                startCol->setValue(selection.left()+1);
-                startRow->setValue(selection.top()+1);
-                endCol->setValue(selection.right()+1);
-                endRow->setValue(selection.bottom()+1);
-            }
-        }
-    }
-}
+  matrix->setFormula(formula);
+
+  bool useMuParser = true;
 
+  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;
+  }
+  matrix->setFormula(oldFormula);
+  return false;
+}
 
+void MatrixValuesDialog::setMatrix(Matrix *m) {
+  if (!m)
+    return;
+
+  matrix = m;
+  commands->setText(m->formula());
+
+  endCol->setValue(m->numCols());
+  endRow->setValue(m->numRows());
+
+  if (m->viewType() == Matrix::TableView) {
+    QItemSelectionModel *selModel = m->selectionModel();
+    if (selModel->hasSelection()) {
+      QItemSelectionRange selection = selModel->selection().first();
+      if (selection.width() > 1 || selection.height() > 1) {
+        startCol->setValue(selection.left() + 1);
+        startRow->setValue(selection.top() + 1);
+        endCol->setValue(selection.right() + 1);
+        endRow->setValue(selection.bottom() + 1);
+      }
+    }
+  }
+}
diff --git a/MantidPlot/src/MatrixValuesDialog.h b/MantidPlot/src/MatrixValuesDialog.h
index 267251b30cd60f7698a7e494d86ee92ce2016931..cd462b2c6facbda9ac6ef243c4aee141b776729d 100644
--- a/MantidPlot/src/MatrixValuesDialog.h
+++ b/MantidPlot/src/MatrixValuesDialog.h
@@ -46,27 +46,26 @@ class ScriptEditor;
 class Matrix;
 
 //! Set matrix values dialog
-class MatrixValuesDialog : public QDialog, public Scripted
-{
-    Q_OBJECT
+class MatrixValuesDialog : public QDialog, public Scripted {
+  Q_OBJECT
 
 public:
-    MatrixValuesDialog( ScriptingEnv *env, QWidget* parent = 0, Qt::WFlags fl = 0 );
-	void setMatrix(Matrix *m);
+  MatrixValuesDialog(ScriptingEnv *env, QWidget *parent = 0, Qt::WFlags fl = 0);
+  void setMatrix(Matrix *m);
 
 private slots:
-	bool apply();
+  bool apply();
 
 private:
-	Matrix *matrix;
+  Matrix *matrix;
 
-        QSize sizeHint() const override;
-        void customEvent(QEvent *e) override;
+  QSize sizeHint() const override;
+  void customEvent(QEvent *e) override;
 
-        ScriptEditor* commands;
-    QPushButton* btnCancel;
-	QSpinBox *startRow, *endRow, *startCol, *endCol;
-	QPushButton *btnApply;
+  ScriptEditor *commands;
+  QPushButton *btnCancel;
+  QSpinBox *startRow, *endRow, *startCol, *endCol;
+  QPushButton *btnApply;
 };
 
 #endif //
diff --git a/MantidPlot/src/MdiSubWindow.cpp b/MantidPlot/src/MdiSubWindow.cpp
index aaf964bf4d5181dcaefa5df1d588dc716b5f26d7..a05407594567fd9a1090a29703e2f1a3db15782d 100644
--- a/MantidPlot/src/MdiSubWindow.cpp
+++ b/MantidPlot/src/MdiSubWindow.cpp
@@ -47,71 +47,65 @@
 using std::ifstream;
 using std::string;
 
-MdiSubWindow::MdiSubWindow(QWidget *parent, const QString& label, const QString& name, Qt::WFlags f):
-  MdiSubWindowParent_t (parent, f),
-  d_app( static_cast<ApplicationWindow*>(parent) ),
-  d_label(label),
-  d_status(Normal),
-  d_caption_policy(Both),
-  d_confirm_close(true),
-  d_birthdate(QDateTime::currentDateTime ().toString(Qt::LocalDate)),
-  d_min_restore_size(QSize())
-{
+MdiSubWindow::MdiSubWindow(QWidget *parent, const QString &label,
+                           const QString &name, Qt::WFlags f)
+    : MdiSubWindowParent_t(parent, f),
+      d_app(static_cast<ApplicationWindow *>(parent)), d_label(label),
+      d_status(Normal), d_caption_policy(Both), d_confirm_close(true),
+      d_birthdate(QDateTime::currentDateTime().toString(Qt::LocalDate)),
+      d_min_restore_size(QSize()) {
   setObjectName(name);
   setName(name);
   setAttribute(Qt::WA_DeleteOnClose);
   setLocale(parent->locale());
   confirmClose(false);
-  if(parent->metaObject()->indexOfSlot(QMetaObject::normalizedSignature("changeToDocked(MdiSubWindow*)")))
-  {
-    connect(this, SIGNAL(dockToMDIArea(MdiSubWindow*)), parent, SLOT(changeToDocked(MdiSubWindow*)));
-    connect(this, SIGNAL(undockFromMDIArea(MdiSubWindow*)), parent, SLOT(changeToFloating(MdiSubWindow*)));
+  if (parent->metaObject()->indexOfSlot(
+          QMetaObject::normalizedSignature("changeToDocked(MdiSubWindow*)"))) {
+    connect(this, SIGNAL(dockToMDIArea(MdiSubWindow *)), parent,
+            SLOT(changeToDocked(MdiSubWindow *)));
+    connect(this, SIGNAL(undockFromMDIArea(MdiSubWindow *)), parent,
+            SLOT(changeToFloating(MdiSubWindow *)));
   }
 }
 
-void MdiSubWindow::updateCaption()
-{
-  switch (d_caption_policy)
-  {
-    case Name:
+void MdiSubWindow::updateCaption() {
+  switch (d_caption_policy) {
+  case Name:
+    setWindowTitle(objectName());
+    break;
+
+  case Label:
+    if (!d_label.isEmpty())
+      setWindowTitle(d_label);
+    else
+      setWindowTitle(objectName());
+    break;
+
+  case Both:
+    if (!d_label.isEmpty())
+      setWindowTitle(objectName() + " - " + d_label);
+    else
       setWindowTitle(objectName());
-      break;
-
-    case Label:
-      if (!d_label.isEmpty())
-        setWindowTitle(d_label);
-      else
-        setWindowTitle(objectName());
-      break;
-
-    case Both:
-      if (!d_label.isEmpty())
-        setWindowTitle(objectName() + " - " + d_label);
-      else
-        setWindowTitle(objectName());
-      break;
+    break;
   }
 
-  QWidget* wrapper = this->getWrapperWindow();
-  if (wrapper)
-  {
+  QWidget *wrapper = this->getWrapperWindow();
+  if (wrapper) {
     wrapper->setWindowTitle(windowTitle());
   }
   emit captionChanged(objectName(), d_label);
 }
 
-void MdiSubWindow::resizeEvent( QResizeEvent* e )
-{
+void MdiSubWindow::resizeEvent(QResizeEvent *e) {
   emit resizedWindow(this);
-  MdiSubWindowParent_t::resizeEvent( e );
+  MdiSubWindowParent_t::resizeEvent(e);
 }
 
 /**
  * Set whether a dialog should be raised when closing the
  * window. If not sets the delete on close flag
  */
-void MdiSubWindow::confirmClose(bool ask)
-{
+void MdiSubWindow::confirmClose(bool ask) {
   d_confirm_close = ask;
   setAttribute(Qt::WA_DeleteOnClose, !ask);
 }
@@ -119,36 +113,24 @@ void MdiSubWindow::confirmClose(bool ask)
 /**
  * Override the QWidget's show() slot to show the wrapper window instead.
  */
-void MdiSubWindow::show()
-{
-  setNormal();
-}
+void MdiSubWindow::show() { setNormal(); }
 
 /**
  * Focus on the window
  */
-void MdiSubWindow::setFocus()
-{
-  QWidget::setFocus(Qt::OtherFocusReason);
-}
-
+void MdiSubWindow::setFocus() { QWidget::setFocus(Qt::OtherFocusReason); }
 
 /**
  * Override the QWidget's hide() slot to hide the wrapper window instead.
  */
-void MdiSubWindow::hide()
-{
-  setHidden();
-}
+void MdiSubWindow::hide() { setHidden(); }
 
 /**
  * Override the QWidget's close() slot to close the wrapper window as well.
  */
-bool MdiSubWindow::close()
-{
-  QWidget* pw = getWrapperWindow();
-  if (!pw)
-  {
+bool MdiSubWindow::close() {
+  QWidget *pw = getWrapperWindow();
+  if (!pw) {
     return MdiSubWindowParent_t::close();
   }
   return pw->close();
@@ -157,179 +139,159 @@ bool MdiSubWindow::close()
 /**
  * Override the QWidget's move(x,y) method to move the wrapper window instead.
  */
-void MdiSubWindow::move(int x, int y)
-{
-  QWidget* pw = getWrapperWindow();
-  if (pw)
-  {
-    QPoint pos = mapTo(pw, QPoint(x,y));
-    pw->move( pos );
+void MdiSubWindow::move(int x, int y) {
+  QWidget *pw = getWrapperWindow();
+  if (pw) {
+    QPoint pos = mapTo(pw, QPoint(x, y));
+    pw->move(pos);
   }
 }
 
 /**
  * Override the QWidget's move(pos) method to move the wrapper window instead.
  */
-void MdiSubWindow::move(const QPoint& pos)
-{
-  QWidget* pw = getWrapperWindow();
-  if (pw)
-  {
+void MdiSubWindow::move(const QPoint &pos) {
+  QWidget *pw = getWrapperWindow();
+  if (pw) {
     QPoint pos1 = mapTo(pw, pos);
-    pw->move( pos1 );
+    pw->move(pos1);
   }
 }
 
 /**
  * Resize the window to it's default size
  */
-void MdiSubWindow::resizeToDefault()
-{
-  resize( 500, 400 );
-}
+void MdiSubWindow::resizeToDefault() { resize(500, 400); }
 
 /**
  */
-void MdiSubWindow::undock()
-{
-  if( !isFloating() ) emit undockFromMDIArea(this);
+void MdiSubWindow::undock() {
+  if (!isFloating())
+    emit undockFromMDIArea(this);
 }
 
 /**
  * @return True if the subwindow is undocked
  */
-bool MdiSubWindow::isFloating() const
-{
+bool MdiSubWindow::isFloating() const {
   return (this->getFloatingWindow() != NULL);
 }
 
 /**
  */
-void MdiSubWindow::dock()
-{
-  if( !isDocked() ) emit dockToMDIArea(this);
+void MdiSubWindow::dock() {
+  if (!isDocked())
+    emit dockToMDIArea(this);
 }
 
 /**
  * @return True if the subwindow is docked to the MDI area
  */
-bool MdiSubWindow::isDocked() const
-{
+bool MdiSubWindow::isDocked() const {
   return (this->getDockedWindow() != NULL);
 }
 
 /**
  */
-void MdiSubWindow::detach()
-{
-  emit detachFromParent(this);
-}
+void MdiSubWindow::detach() { emit detachFromParent(this); }
 
 /**
  * Handle the close event.
  * @param e :: A QCloseEvent event.
  */
-void MdiSubWindow::closeEvent( QCloseEvent *e )
-{
+void MdiSubWindow::closeEvent(QCloseEvent *e) {
   // Default result = do close.
   int result = 0;
 
   // If you need to confirm the close, ask the user
-  if (d_confirm_close)
-  {
-    result = QMessageBox::information(this, tr("MantidPlot"),
-                                      tr("Do you want to hide or delete") + "<p><b>'" + objectName() + "'</b> ?",
-                                      tr("Delete"), tr("Hide"), tr("Cancel"), 0, 2);
+  if (d_confirm_close) {
+    result = QMessageBox::information(
+        this, tr("MantidPlot"), tr("Do you want to hide or delete") +
+                                    "<p><b>'" + objectName() + "'</b> ?",
+        tr("Delete"), tr("Hide"), tr("Cancel"), 0, 2);
   }
 
-  switch(result)
-  {
-    case 0: // close
-      if (!widget() || widget()->close())
-      {
-        e->accept();
-        emit closedWindow(this);
-        // Continue; the mdi window should close (?)
-      }
-      else
-      {
-        QMessageBox::critical(parentWidget(),"MantidPlot - Error", "Window cannot be closed");
-        e->ignore();
-      }
-      break;
-
-    case 1: // hide
+  switch (result) {
+  case 0: // close
+    if (!widget() || widget()->close()) {
+      e->accept();
+      emit closedWindow(this);
+      // Continue; the mdi window should close (?)
+    } else {
+      QMessageBox::critical(parentWidget(), "MantidPlot - Error",
+                            "Window cannot be closed");
       e->ignore();
-      emit hiddenWindow(this);
-      break;
+    }
+    break;
 
-    case 2: // cancel
-      e->ignore();
-      break;
-  }
+  case 1: // hide
+    e->ignore();
+    emit hiddenWindow(this);
+    break;
 
+  case 2: // cancel
+    e->ignore();
+    break;
+  }
 }
 
-QString MdiSubWindow::aspect()
-{
+QString MdiSubWindow::aspect() {
   QString s = tr("Normal");
-  switch (d_status)
-  {
-    case Normal:
-      break;
-
-    case Minimized:
-      return tr("Minimized");
-      break;
-
-    case Maximized:
-      return tr("Maximized");
-      break;
-
-    case Hidden:
-      return tr("Hidden");
-      break;
+  switch (d_status) {
+  case Normal:
+    break;
+
+  case Minimized:
+    return tr("Minimized");
+    break;
+
+  case Maximized:
+    return tr("Maximized");
+    break;
+
+  case Hidden:
+    return tr("Hidden");
+    break;
   }
   return s;
 }
 
-QString MdiSubWindow::sizeToString()
-{
-  return QString::number(8.*static_cast<float>(sizeof(this))/1024.0, 'f', 1) + " " + tr("kB");
+QString MdiSubWindow::sizeToString() {
+  return QString::number(8. * static_cast<float>(sizeof(this)) / 1024.0, 'f',
+                         1) +
+         " " + tr("kB");
 }
 
-void MdiSubWindow::changeEvent(QEvent *event)
-{
-  if (!isHidden() && event->type() == QEvent::WindowStateChange){
+void MdiSubWindow::changeEvent(QEvent *event) {
+  if (!isHidden() && event->type() == QEvent::WindowStateChange) {
     Status oldStatus = d_status;
     Status newStatus = Normal;
-    if( windowState() & Qt::WindowMinimized ){
+    if (windowState() & Qt::WindowMinimized) {
       if (oldStatus != Minimized)
         d_min_restore_size = frameSize();
       newStatus = Minimized;
-    } else if ( windowState() & Qt::WindowMaximized )
+    } else if (windowState() & Qt::WindowMaximized)
       newStatus = Maximized;
 
-    if (newStatus != oldStatus){
+    if (newStatus != oldStatus) {
       d_status = newStatus;
-      emit statusChanged (this);
+      emit statusChanged(this);
     }
   }
   MdiSubWindowParent_t::changeEvent(event);
 }
 
-bool MdiSubWindow::eventFilter(QObject *object, QEvent *e)
-{
-  if (e->type() == QEvent::ContextMenu && object == widget()){
-        emit showContextMenu();
-        return true;
+bool MdiSubWindow::eventFilter(QObject *object, QEvent *e) {
+  if (e->type() == QEvent::ContextMenu && object == widget()) {
+    emit showContextMenu();
+    return true;
   }
 
-  //if (e->type() == QEvent::Move && object == widget()){
+  // if (e->type() == QEvent::Move && object == widget()){
   //  QObjectList lst = children();
   //  foreach(QObject *o, lst){
   //    if (o->isA("QMenu") && d_app){
- //         d_app->customWindowTitleBarMenu(this, dynamic_cast<QMenu *>(o));
+  //         d_app->customWindowTitleBarMenu(this, dynamic_cast<QMenu *>(o));
   //      break;
   //    }
   //  }
@@ -337,82 +299,68 @@ bool MdiSubWindow::eventFilter(QObject *object, QEvent *e)
   return MdiSubWindowParent_t::eventFilter(object, e);
 }
 
-void MdiSubWindow::setStatus(Status s)
-{
+void MdiSubWindow::setStatus(Status s) {
   if (d_status == s)
     return;
 
   d_status = s;
-  emit statusChanged (this);
+  emit statusChanged(this);
 }
 
-void MdiSubWindow::setHidden()
-{
-  QWidget* pw = getWrapperWindow();
-  if (!pw)
-  {
+void MdiSubWindow::setHidden() {
+  QWidget *pw = getWrapperWindow();
+  if (!pw) {
     MdiSubWindowParent_t::hide();
-  }
-  else
-  {
+  } else {
     pw->hide();
   }
   setStatus(Hidden);
 }
 
-void MdiSubWindow::setNormal()
-{
-  QWidget* wrapper = getWrapperWindow();
-  if (wrapper)
-  {
+void MdiSubWindow::setNormal() {
+  QWidget *wrapper = getWrapperWindow();
+  if (wrapper) {
     wrapper->showNormal();
-  }
-  else
-  {
+  } else {
     showNormal();
   }
   setStatus(Normal);
 }
 
-void MdiSubWindow::setMinimized()
-{
+void MdiSubWindow::setMinimized() {
   setStatus(Minimized);
-  QWidget* wrapper = getWrapperWindow();
-  if (wrapper)
-  {
+  QWidget *wrapper = getWrapperWindow();
+  if (wrapper) {
     wrapper->showMinimized();
-    //d_app->activateNewWindow();
-  }
-  else
-  {
+    // d_app->activateNewWindow();
+  } else {
     showMinimized();
   }
 }
 
-void MdiSubWindow::setMaximized()
-{
-  QWidget* wrapper = getWrapperWindow();
-  if (wrapper)
-  {
+void MdiSubWindow::setMaximized() {
+  QWidget *wrapper = getWrapperWindow();
+  if (wrapper) {
     wrapper->showMaximized();
-  }
-  else
-  {
+  } else {
     showMaximized();
   }
   setStatus(Maximized);
 }
 
-QString MdiSubWindow::parseAsciiFile(const QString& fname, const QString &commentString,
-                                     int endLine, int ignoreFirstLines, int maxRows, int& rows)
-{
+QString MdiSubWindow::parseAsciiFile(const QString &fname,
+                                     const QString &commentString, int endLine,
+                                     int ignoreFirstLines, int maxRows,
+                                     int &rows) {
   if (endLine == 2)
-    return parseMacAsciiFile(fname, commentString, ignoreFirstLines, maxRows, rows);
+    return parseMacAsciiFile(fname, commentString, ignoreFirstLines, maxRows,
+                             rows);
 
-  //QTextStream replaces '\r\n' with '\n', therefore we don't need a special treatement in this case!
+  // QTextStream replaces '\r\n' with '\n', therefore we don't need a special
+  // treatement in this case!
 
   QFile f(fname);
-  if(!f.open(QIODevice::ReadOnly))
+  if (!f.open(QIODevice::ReadOnly))
     return QString::null;
 
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
@@ -422,13 +370,14 @@ QString MdiSubWindow::parseAsciiFile(const QString& fname, const QString &commen
   tempFile.open();
   QTextStream temp(&tempFile);
 
-  for (int i = 0; i < ignoreFirstLines; i++)//skip first 'ignoreFirstLines' lines
+  for (int i = 0; i < ignoreFirstLines;
+       i++) // skip first 'ignoreFirstLines' lines
     t.readLine();
 
   bool validCommentString = !commentString.isEmpty();
   rows = 0;
-  if (maxRows <= 0){//read all valid lines
-    while(!t.atEnd()){//count the number of valid rows
+  if (maxRows <= 0) {    // read all valid lines
+    while (!t.atEnd()) { // count the number of valid rows
       QString s = t.readLine();
       if (validCommentString && s.startsWith(commentString))
         continue;
@@ -437,8 +386,8 @@ QString MdiSubWindow::parseAsciiFile(const QString& fname, const QString &commen
       temp << s + "\n";
       qApp->processEvents(QEventLoop::ExcludeUserInput);
     }
-  } else {//we write only 'maxRows' valid rows to the temp file
-    while(!t.atEnd() && rows < maxRows){
+  } else { // we write only 'maxRows' valid rows to the temp file
+    while (!t.atEnd() && rows < maxRows) {
       QString s = t.readLine();
       if (validCommentString && s.startsWith(commentString))
         continue;
@@ -458,12 +407,13 @@ QString MdiSubWindow::parseAsciiFile(const QString& fname, const QString &commen
   return path;
 }
 
-QString MdiSubWindow::parseMacAsciiFile(const QString& fname, const QString &commentString,
-                                        int ignoreFirstLines, int maxRows, int& rows)
-{
+QString MdiSubWindow::parseMacAsciiFile(const QString &fname,
+                                        const QString &commentString,
+                                        int ignoreFirstLines, int maxRows,
+                                        int &rows) {
   ifstream f;
   f.open(fname.toAscii());
-  if(!f)
+  if (!f)
     return QString::null;
 
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
@@ -472,7 +422,8 @@ QString MdiSubWindow::parseMacAsciiFile(const QString& fname, const QString &com
   tempFile.open();
   QTextStream temp(&tempFile);
 
-  for (int i = 0; i < ignoreFirstLines; i++){//skip first 'ignoreFirstLines' lines
+  for (int i = 0; i < ignoreFirstLines;
+       i++) { // skip first 'ignoreFirstLines' lines
     string s;
     getline(f, s, '\r');
   }
@@ -481,8 +432,8 @@ QString MdiSubWindow::parseMacAsciiFile(const QString& fname, const QString &com
   string comment = commentString.toAscii().constData();
   int commentLength = static_cast<int>(comment.size());
   rows = 0;
-  if (maxRows <= 0){//read all valid lines
-    while(f.good() && !f.eof()){//count the number of valid rows
+  if (maxRows <= 0) {              // read all valid lines
+    while (f.good() && !f.eof()) { // count the number of valid rows
       string s;
       getline(f, s, '\r');
       if (validCommentString && s.compare(0, commentLength, comment) == 0)
@@ -492,8 +443,8 @@ QString MdiSubWindow::parseMacAsciiFile(const QString& fname, const QString &com
       temp << QString(s.c_str()) + "\n";
       qApp->processEvents(QEventLoop::ExcludeUserInput);
     }
-  } else {//we write only 'maxRows' valid rows to the temp file
-    while(f.good() && !f.eof() && rows < maxRows){
+  } else { // we write only 'maxRows' valid rows to the temp file
+    while (f.good() && !f.eof() && rows < maxRows) {
       string s;
       getline(f, s, '\r');
       if (validCommentString && s.compare(0, commentLength, comment) == 0)
@@ -515,31 +466,31 @@ QString MdiSubWindow::parseMacAsciiFile(const QString& fname, const QString &com
 }
 
 /**
- * Return a pointer to the wrapper window if it is a FloatingWindow or NULL otherwise.
+ * Return a pointer to the wrapper window if it is a FloatingWindow or NULL
+ * otherwise.
  */
-FloatingWindow* MdiSubWindow::getFloatingWindow() const
-{
-  if (!parent() || !parent()->parent()) return NULL;
-  return dynamic_cast<FloatingWindow*>(parent()->parent());
+FloatingWindow *MdiSubWindow::getFloatingWindow() const {
+  if (!parent() || !parent()->parent())
+    return NULL;
+  return dynamic_cast<FloatingWindow *>(parent()->parent());
 }
 
 /**
- * Return a pointer to the wrapper window if it is a QMdiSubWindow or NULL otherwise.
+ * Return a pointer to the wrapper window if it is a QMdiSubWindow or NULL
+ * otherwise.
  */
-QMdiSubWindow* MdiSubWindow::getDockedWindow() const
-{
-  if (!parent()) return NULL;
-  return dynamic_cast<QMdiSubWindow*>(parent());
+QMdiSubWindow *MdiSubWindow::getDockedWindow() const {
+  if (!parent())
+    return NULL;
+  return dynamic_cast<QMdiSubWindow *>(parent());
 }
 
 /**
  * Return a pointer to the wrapper window.
  */
-QWidget* MdiSubWindow::getWrapperWindow() const
-{
-  QWidget* wrapper = getDockedWindow();
-  if (!wrapper)
-  {
+QWidget *MdiSubWindow::getWrapperWindow() const {
+  QWidget *wrapper = getDockedWindow();
+  if (!wrapper) {
     wrapper = getFloatingWindow();
   }
   return wrapper;
@@ -548,38 +499,27 @@ QWidget* MdiSubWindow::getWrapperWindow() const
 /**
  * Wrapper for the resize method.
  */
-void MdiSubWindow::resize(int w, int h)
-{
-  QWidget* pw = getWrapperWindow();
-  if(pw)
-  {
+void MdiSubWindow::resize(int w, int h) {
+  QWidget *pw = getWrapperWindow();
+  if (pw) {
     setGeometry(x(), y(), w, h);
     pw->adjustSize();
-  }
-  else
-  {
-    QFrame::resize(w,h);
+  } else {
+    QFrame::resize(w, h);
   }
 }
 
 /**
  * Wrapper for the resize method.
  */
-void MdiSubWindow::resize(const QSize& size)
-{
-  QWidget* pw = getWrapperWindow();
-  if(pw)
-  {
+void MdiSubWindow::resize(const QSize &size) {
+  QWidget *pw = getWrapperWindow();
+  if (pw) {
     setGeometry(pw->x(), pw->y(), size.width(), size.height());
     pw->adjustSize();
-  }
-  else
-  {
+  } else {
     QFrame::resize(size);
   }
 }
 
-QSize MdiSubWindow::sizeHint() const
-{
-  return size();
-}
+QSize MdiSubWindow::sizeHint() const { return size(); }
diff --git a/MantidPlot/src/MdiSubWindow.h b/MantidPlot/src/MdiSubWindow.h
index 5688746b0c660c99b8d165f1efddad456c82dff0..d80a24428cec119faaf926b62cd2dffa776fe916 100644
--- a/MantidPlot/src/MdiSubWindow.h
+++ b/MantidPlot/src/MdiSubWindow.h
@@ -43,78 +43,74 @@ class QString;
 class FloatingWindow;
 class ApplicationWindow;
 
-class MdiSubWindowParent_t: public QFrame
-{
+class MdiSubWindowParent_t : public QFrame {
   Q_OBJECT
 public:
-  MdiSubWindowParent_t(QWidget* parent, Qt::WFlags f = 0):
-    QFrame(parent,f),
-    m_widget(NULL)
-  {}
-  void setWidget(QWidget* w)
-  {
-    if (w == NULL)
-      {// removing widget
-        if (m_widget)
-        {
-          layout()->takeAt(0);
-        }
-        m_widget = NULL;
-        return;
+  MdiSubWindowParent_t(QWidget *parent, Qt::WFlags f = 0)
+      : QFrame(parent, f), m_widget(NULL) {}
+  void setWidget(QWidget *w) {
+    if (w == NULL) { // removing widget
+      if (m_widget) {
+        layout()->takeAt(0);
       }
+      m_widget = NULL;
+      return;
+    }
 
     // widget cannot be replaced
-    if (m_widget)
-    {
+    if (m_widget) {
       throw std::runtime_error("Widget already set");
     }
 
     // setting the internal widget
-    if ( this->layout() == NULL )
-    {
-      QVBoxLayout* layout = new QVBoxLayout(this);
-      layout->setContentsMargins(0,0,0,0);
+    if (this->layout() == NULL) {
+      QVBoxLayout *layout = new QVBoxLayout(this);
+      layout->setContentsMargins(0, 0, 0, 0);
       layout->addWidget(w);
-    }
-    else
-    {
+    } else {
       layout()->addWidget(w);
     }
     m_widget = w;
     m_widget->setParent(this); // I am not sure about this
   }
   ~MdiSubWindowParent_t() override {
-    //std::cerr << "MdiSubWindowParent_t deleted\n";
+    // std::cerr << "MdiSubWindowParent_t deleted\n";
   }
-  QWidget* widget() {return m_widget;}
-  const QWidget* widget() const {return m_widget;}
+  QWidget *widget() { return m_widget; }
+  const QWidget *widget() const { return m_widget; }
+
 protected:
-  QWidget* m_widget;
+  QWidget *m_widget;
 };
 
 /**
  * \brief Base class of all MDI client windows.
  *
  * These are the main objects of every Qtiplot project.
- * All content (apart from the directory structure) is managed by subclasses of MdiSubWindow.
+ * All content (apart from the directory structure) is managed by subclasses of
+ *MdiSubWindow.
  *
- * With introduction of floating windows this class is no longer a sub-window (with window title and system menu)
- * but rather the internal widget of a QMdiSubWindow or a FloatingWindow. The outer window can be changed between
- * FloatingWindow and QMdiSubWindow at runtime using ApplicationWindow::changeToFloating(...) and
- * ApplicationWindow::changeToDocked(...) methods. MdiSubWindow overrides show(), hide(), and close() methods so that the
+ * With introduction of floating windows this class is no longer a sub-window
+ *(with window title and system menu)
+ * but rather the internal widget of a QMdiSubWindow or a FloatingWindow. The
+ *outer window can be changed between
+ * FloatingWindow and QMdiSubWindow at runtime using
+ *ApplicationWindow::changeToFloating(...) and
+ * ApplicationWindow::changeToDocked(...) methods. MdiSubWindow overrides
+ *show(), hide(), and close() methods so that the
  * corresponding events are passed to the outer window.
  *
- * MdiSubWindow can serve as a wrapper for another widget. Use MdiSubWindow::setWidget(...) to set its internal widget.
- * In this case if close event needs to be processed override closeEvent(...) of the internal widget.
+ * MdiSubWindow can serve as a wrapper for another widget. Use
+ *MdiSubWindow::setWidget(...) to set its internal widget.
+ * In this case if close event needs to be processed override closeEvent(...) of
+ *the internal widget.
  *
  * \sa Folder, ApplicationWindow
  */
-class MdiSubWindow: public MdiSubWindowParent_t
-{
+class MdiSubWindow : public MdiSubWindowParent_t {
   Q_OBJECT
 
 public:
-
   //! Constructor
   /**
    * @param parent :: parent window
@@ -123,55 +119,67 @@ public:
    * @param f :: window flags
    * \sa setCaptionPolicy(), captionPolicy()
    */
-  MdiSubWindow(QWidget *parent, const QString& label = QString(), const QString& name = QString(), Qt::WFlags f = 0);
+  MdiSubWindow(QWidget *parent, const QString &label = QString(),
+               const QString &name = QString(), Qt::WFlags f = 0);
 
   //! Possible window captions.
-  enum CaptionPolicy{
-    Name = 0, //!< caption determined by the window name
+  enum CaptionPolicy {
+    Name = 0,  //!< caption determined by the window name
     Label = 1, //!< caption detemined by the window label
-    Both = 2 //!< caption = "name - label"
+    Both = 2   //!< caption = "name - label"
   };
-  enum Status{Hidden = -1, Normal = 0, Minimized = 1, Maximized = 2};
+  enum Status { Hidden = -1, Normal = 0, Minimized = 1, Maximized = 2 };
 
   /// Get the pointer to ApplicationWindow
-  ApplicationWindow *applicationWindow() {return d_app;}
+  ApplicationWindow *applicationWindow() { return d_app; }
 
 public slots:
 
   //! Return the window label
-  QString windowLabel(){return QString(d_label);}
+  QString windowLabel() { return QString(d_label); }
   //! Set the window label
-  void setWindowLabel(const QString& s) { d_label = s; updateCaption();}
+  void setWindowLabel(const QString &s) {
+    d_label = s;
+    updateCaption();
+  }
 
   //! Return the window name
-  QString name(){return objectName();}
+  QString name() { return objectName(); }
   //! Set the window name
-  void setName(const QString& s){setObjectName(s); updateCaption();}
+  void setName(const QString &s) {
+    setObjectName(s);
+    updateCaption();
+  }
 
   //! Return the caption policy
-  CaptionPolicy captionPolicy(){return d_caption_policy;}
+  CaptionPolicy captionPolicy() { return d_caption_policy; }
   //! Set the caption policy
-  void setCaptionPolicy(CaptionPolicy policy) { d_caption_policy = policy; updateCaption(); }
+  void setCaptionPolicy(CaptionPolicy policy) {
+    d_caption_policy = policy;
+    updateCaption();
+  }
 
   //! Return the creation date
-  QString birthDate(){return d_birthdate;}
+  QString birthDate() { return d_birthdate; }
   //! Set the creation date
-  void setBirthDate(const QString& s){d_birthdate = s;}
+  void setBirthDate(const QString &s) { d_birthdate = s; }
 
   //! Return the window status as a string
   QString aspect();
   //! Return the window status flag (hidden, normal, minimized or maximized)
-    Status status(){return d_status;}
+  Status status() { return d_status; }
   //! Set the window status flag (hidden, normal, minimized or maximized)
   void setStatus(Status s);
 
   // TODO:
   //! Not implemented yet
-  virtual void restore(const QStringList& ){}
+  virtual void restore(const QStringList &) {}
 
-  virtual void exportPDF(const QString&){}
+  virtual void exportPDF(const QString &) {}
 
-  virtual QString saveToString(const QString &, bool = false){return QString();}
+  virtual QString saveToString(const QString &, bool = false) {
+    return QString();
+  }
 
   // TODO: make this return something useful
   //! Size of the widget as a string
@@ -180,7 +188,7 @@ public slots:
   //!Notifies that a window was hidden by a direct user action
   virtual void setHidden();
 
-  //event handlers
+  // event handlers
   //! Close event handler
   /**
    * Ask the user "delete, hide, or cancel?" if the
@@ -195,48 +203,52 @@ public slots:
   //! Filters other object's events (customizes title bar's context menu)
   bool eventFilter(QObject *object, QEvent *e) override;
 
-  FloatingWindow* getFloatingWindow() const;
-  QMdiSubWindow* getDockedWindow() const;
-  QWidget* getWrapperWindow() const;
+  FloatingWindow *getFloatingWindow() const;
+  QMdiSubWindow *getDockedWindow() const;
+  QWidget *getWrapperWindow() const;
 
   void setNormal();
   void setMinimized();
   void setMaximized();
 
   //! Returns the size the window had before a change state event to minimized.
-  QSize minRestoreSize(){return d_min_restore_size;}
+  QSize minRestoreSize() { return d_min_restore_size; }
 
-  //! Static function used as a workaround for ASCII files having end line char != '\n'.
+  //! Static function used as a workaround for ASCII files having end line char
+  //!= '\n'.
   /*
-   * It counts the number of valid rows to be imported and the number of first lines to be ignored.
-   * It creates a temporary file with '\n' terminated lines which can be correctly read by QTextStream
+   * It counts the number of valid rows to be imported and the number of first
+   * lines to be ignored.
+   * It creates a temporary file with '\n' terminated lines which can be
+   * correctly read by QTextStream
    * and returnes a path to this file.
    */
-  static QString parseAsciiFile(const QString& fname, const QString &commentString, int endLine,
-                                int ignoreFirstLines, int maxRows, int& rows);
+  static QString parseAsciiFile(const QString &fname,
+                                const QString &commentString, int endLine,
+                                int ignoreFirstLines, int maxRows, int &rows);
 
-  void setconfirmcloseFlag(bool closeflag){d_confirm_close=closeflag;}
+  void setconfirmcloseFlag(bool closeflag) { d_confirm_close = closeflag; }
 
   //! Notifies the main application that the window has been modified
-  void notifyChanges(){emit modifiedWindow(this);}
-  virtual void print(){}
+  void notifyChanges() { emit modifiedWindow(this); }
+  virtual void print() {}
 
   bool close();
   void hide();
   void show();
   void resize(int w, int h);
-  void resize(const QSize& size);
+  void resize(const QSize &size);
   QSize sizeHint() const override;
 
   /// Focus on the window
   void setFocus();
 
   void move(int x, int y);
-  void move(const QPoint& pos);
+  void move(const QPoint &pos);
   /// Resize the window to it's default size
   void resizeToDefault();
 
-public: //non-slot methods
+public: // non-slot methods
   /**@name Floating/Docking */
   ///@{
   /// If docked, undock the window out of the MDI area
@@ -249,7 +261,7 @@ public: //non-slot methods
   bool isDocked() const;
   /// Detach this window from any parent window
   void detach();
-  ///@}
+///@}
 
 signals:
   //! Emitted when the window was closed
@@ -274,15 +286,17 @@ signals:
   void dragMousePress(QPoint);
   void dragMouseRelease(QPoint);
   void dragMouseMove(QPoint);
-  
+
 protected:
   //! Catches status changes
   void changeEvent(QEvent *event) override;
 
 private:
   //! Used to parse ASCII files with carriage return ('\r') endline.
-  static QString parseMacAsciiFile(const QString& fname, const QString &commentString,
-                           int ignoreFirstLines, int maxRows, int& rows);
+  static QString parseMacAsciiFile(const QString &fname,
+                                   const QString &commentString,
+                                   int ignoreFirstLines, int maxRows,
+                                   int &rows);
   //! Set caption according to current CaptionPolicy, name and label
   void updateCaption();
   /// Store the pointer to the ApplicationWindow
@@ -309,6 +323,6 @@ private:
   friend class FloatingWindow;
 };
 
-typedef QList<MdiSubWindow*> MDIWindowList;
+typedef QList<MdiSubWindow *> MDIWindowList;
 
 #endif
diff --git a/MantidPlot/src/MultiLayer.cpp b/MantidPlot/src/MultiLayer.cpp
index be23f27bb59e8d128a2871904d2bd9cb8166a902..62a1a7038035574c40ff501513bf81db1cb1e2e0 100644
--- a/MantidPlot/src/MultiLayer.cpp
+++ b/MantidPlot/src/MultiLayer.cpp
@@ -1116,21 +1116,24 @@ void MultiLayer::wheelEvent(QWheelEvent *e) {
       }
     }
   }
-  if (resize &&
-      (e->modifiers() & Qt::AltModifier || e->modifiers() & Qt::ControlModifier ||
-       e->modifiers() & Qt::ShiftModifier)) {
+  if (resize && (e->modifiers() & Qt::AltModifier ||
+                 e->modifiers() & Qt::ControlModifier ||
+                 e->modifiers() & Qt::ShiftModifier)) {
     intSize = resize_graph->plotWidget()->size();
-    if (e->modifiers() & Qt::AltModifier) { // If alt is pressed then change the width
+    if (e->modifiers() &
+        Qt::AltModifier) { // If alt is pressed then change the width
       if (e->delta() > 0)
         intSize.rwidth() += 5;
       else if (e->delta() < 0)
         intSize.rwidth() -= 5;
-    } else if (e->modifiers() & Qt::ControlModifier) { // If crt is pressed then changed the height
+    } else if (e->modifiers() & Qt::ControlModifier) { // If crt is pressed then
+                                                       // changed the height
       if (e->delta() > 0)
         intSize.rheight() += 5;
       else if (e->delta() < 0)
         intSize.rheight() -= 5;
-    } else if (e->modifiers() & Qt::ShiftModifier) { // If shift is pressed then resize
+    } else if (e->modifiers() &
+               Qt::ShiftModifier) { // If shift is pressed then resize
       if (e->delta() > 0) {
         intSize.rwidth() += 5;
         intSize.rheight() += 5;
@@ -1744,22 +1747,19 @@ void MultiLayer::loadFromProject(const std::string &lines,
     setMargins(left, right, top, bottom);
   }
 
-  if(tsv.selectLine("Spacing"))
-  {
+  if (tsv.selectLine("Spacing")) {
     int rowSpace = 0, colSpace = 0;
     tsv >> rowSpace >> colSpace;
     setSpacing(rowSpace, colSpace);
   }
 
-  if(tsv.selectLine("LayerCanvasSize"))
-  {
+  if (tsv.selectLine("LayerCanvasSize")) {
     int width = 0, height = 0;
     tsv >> width >> height;
     setLayerCanvasSize(width, height);
   }
 
-  if(tsv.selectLine("Alignement"))
-  {
+  if (tsv.selectLine("Alignement")) {
     int hor = 0, vert = 0;
     tsv >> hor >> vert;
     setAlignement(hor, vert);
@@ -1781,8 +1781,7 @@ void MultiLayer::loadFromProject(const std::string &lines,
 
       TSVSerialiser gtsv(graphLines);
 
-      if(gtsv.selectLine("ggeometry"))
-      {
+      if (gtsv.selectLine("ggeometry")) {
         int x = 0, y = 0, w = 0, h = 0;
         gtsv >> x >> y >> w >> h;
 
diff --git a/MantidPlot/src/MultiLayer.h b/MantidPlot/src/MultiLayer.h
index e35be84c02b1fdb8a88bc5484b4668ab81f1be5f..2cc414e8cb0adba8112fc82d211ab71f517515cf 100644
--- a/MantidPlot/src/MultiLayer.h
+++ b/MantidPlot/src/MultiLayer.h
@@ -52,49 +52,56 @@ class WaterfallFillDialog;
 /**
  * \brief An MDI window (MdiSubWindow) managing one or more Graph objects.
  *
- * %Note that several parts of the code, as well as the user interface, refer to MultiLayer as "graph" or "plot",
+ * %Note that several parts of the code, as well as the user interface, refer to
+ *MultiLayer as "graph" or "plot",
  * practically guaranteeing confusion with the classes Graph and Plot.
  *
  * \section future Future Plans
  * Manage any QWidget instead of only Graph.
- * This would allow 3D graphs to be added as well, so you could produce mixed 2D/3D arrangements.
- * It would also allow text labels to be added directly instead of having to complicate things by wrapping them
- * up in a Graph (see documentation of ImageMarker for details) (see documentation of ImageMarker for details).
+ * This would allow 3D graphs to be added as well, so you could produce mixed
+ *2D/3D arrangements.
+ * It would also allow text labels to be added directly instead of having to
+ *complicate things by wrapping them
+ * up in a Graph (see documentation of ImageMarker for details) (see
+ *documentation of ImageMarker for details).
  *
- * The main problem to be figured out for this is how Graph would interface with the rest of the project.
+ * The main problem to be figured out for this is how Graph would interface with
+ *the rest of the project.
  * A possible solution is outlined in the documentation of ApplicationWindow:
- * If MultiLayer exposes its parent Project to the widgets it manages, they could handle things like creating
+ * If MultiLayer exposes its parent Project to the widgets it manages, they
+ *could handle things like creating
  * tables by calling methods of Project instead of sending signals.
  */
-class MultiLayer: public MdiSubWindow, public Mantid::IProjectSerialisable
-{
-	Q_OBJECT
+class MultiLayer : public MdiSubWindow, public Mantid::IProjectSerialisable {
+  Q_OBJECT
 
 public:
-  MultiLayer (ApplicationWindow* parent = 0, int layers = 1, int rows = 1, int cols = 1, const QString& label = "", const char* name=0, Qt::WFlags f=0);
+  MultiLayer(ApplicationWindow *parent = 0, int layers = 1, int rows = 1,
+             int cols = 1, const QString &label = "", const char *name = 0,
+             Qt::WFlags f = 0);
   ~MultiLayer() override;
 
   QSize minimumSizeHint() const override;
 
-  QList<Graph *> layersList(){return graphsList;};
-	Graph *layer(int num);
-	LayerButton* addLayerButton();
-	void copy(MultiLayer* ml);
+  QList<Graph *> layersList() { return graphsList; };
+  Graph *layer(int num);
+  LayerButton *addLayerButton();
+  void copy(MultiLayer *ml);
 
-	enum HorAlignement{HCenter, Left, Right};
-	enum VertAlignement{VCenter, Top, Bottom};
+  enum HorAlignement { HCenter, Left, Right };
+  enum VertAlignement { VCenter, Top, Bottom };
 
-	bool scaleLayersOnPrint(){return d_scale_on_print;};
-	void setScaleLayersOnPrint(bool on){d_scale_on_print = on;};
+  bool scaleLayersOnPrint() { return d_scale_on_print; };
+  void setScaleLayersOnPrint(bool on) { d_scale_on_print = on; };
 
-	bool printCropmarksEnabled(){return d_print_cropmarks;};
-	void printCropmarks(bool on){d_print_cropmarks = on;};
+  bool printCropmarksEnabled() { return d_print_cropmarks; };
+  void printCropmarks(bool on) { d_print_cropmarks = on; };
 
-  //Mantid
-  void insertCurve(MultiLayer* ml, int i);
+  // Mantid
+  void insertCurve(MultiLayer *ml, int i);
 
   /// Set whether the MultiLayer should close itself when it becomes empty
-  void setCloseOnEmpty(bool yes=true){d_close_on_empty = yes;}
+  void setCloseOnEmpty(bool yes = true) { d_close_on_empty = yes; }
 
   void setWaterfallLayout(bool on = true);
 
@@ -103,71 +110,73 @@ public:
   std::string saveToProject(ApplicationWindow *app) override;
 
 public slots:
-	Graph* addLayer(int x = 0, int y = 0, int width = 0, int height = 0);
-	void setLayersNumber(int n);
+  Graph *addLayer(int x = 0, int y = 0, int width = 0, int height = 0);
+  void setLayersNumber(int n);
 
-	bool isEmpty();
-    void removeLayer();
-	void confirmRemoveLayer();
+  bool isEmpty();
+  void removeLayer();
+  void confirmRemoveLayer();
 
-	Graph* activeGraph(){return active_graph;};
-	void setActiveGraph(Graph* g);
-	void activateGraph(LayerButton* button);
+  Graph *activeGraph() { return active_graph; };
+  void setActiveGraph(Graph *g);
+  void activateGraph(LayerButton *button);
 
-	void setGraphGeometry(int x, int y, int w, int h);
+  void setGraphGeometry(int x, int y, int w, int h);
 
-	void findBestLayout(int &rows, int &cols);
+  void findBestLayout(int &rows, int &cols);
 
-	QSize arrangeLayers(bool userSize);
-	void arrangeLayers(bool fit, bool userSize);
-	bool swapLayers(int src, int dest);
-    void adjustSize();
+  QSize arrangeLayers(bool userSize);
+  void arrangeLayers(bool fit, bool userSize);
+  bool swapLayers(int src, int dest);
+  void adjustSize();
 
-	int getRows(){return d_rows;};
-	void setRows(int r);
+  int getRows() { return d_rows; };
+  void setRows(int r);
 
-	int getCols(){return d_cols;};
-	void setCols(int c);
+  int getCols() { return d_cols; };
+  void setCols(int c);
 
-	int colsSpacing(){return colsSpace;};
-	int rowsSpacing(){return rowsSpace;};
-	void setSpacing (int rgap, int cgap);
+  int colsSpacing() { return colsSpace; };
+  int rowsSpacing() { return rowsSpace; };
+  void setSpacing(int rgap, int cgap);
 
-	int leftMargin(){return left_margin;};
-	int rightMargin(){return right_margin;};
-	int topMargin(){return top_margin;};
-	int bottomMargin(){return bottom_margin;};
-	void setMargins (int lm, int rm, int tm, int bm);
+  int leftMargin() { return left_margin; };
+  int rightMargin() { return right_margin; };
+  int topMargin() { return top_margin; };
+  int bottomMargin() { return bottom_margin; };
+  void setMargins(int lm, int rm, int tm, int bm);
 
-	QSize layerCanvasSize(){return QSize(l_canvas_width, l_canvas_height);};
-	void setLayerCanvasSize (int w, int h);
+  QSize layerCanvasSize() { return QSize(l_canvas_width, l_canvas_height); };
+  void setLayerCanvasSize(int w, int h);
 
-	int horizontalAlignement(){return hor_align;};
-	int verticalAlignement(){return vert_align;};
-	void setAlignement (int ha, int va);
+  int horizontalAlignement() { return hor_align; };
+  int verticalAlignement() { return vert_align; };
+  void setAlignement(int ha, int va);
 
-	int layers(){return graphsList.size();};
+  int layers() { return graphsList.size(); };
 
-	//! \name Print and Export
-	//@{
-	QPixmap canvasPixmap();
-	void exportToFile(const QString& fileName);
-	void exportImage(const QString& fileName, int quality = 100, bool transparent = false);
-	void exportSVG(const QString& fname);
-        void exportPDF(const QString &fname) override;
-        void exportVector(const QString& fileName, int res = 0, bool color = true,
-                    bool keepAspect = true, QPrinter::PageSize pageSize = QPrinter::Custom);
-
-	void copyAllLayers();
-        void print() override;
-        void printAllLayers(QPainter *painter);
-	void printActiveLayer();
-	//@}
+  //! \name Print and Export
+  //@{
+  QPixmap canvasPixmap();
+  void exportToFile(const QString &fileName);
+  void exportImage(const QString &fileName, int quality = 100,
+                   bool transparent = false);
+  void exportSVG(const QString &fname);
+  void exportPDF(const QString &fname) override;
+  void exportVector(const QString &fileName, int res = 0, bool color = true,
+                    bool keepAspect = true,
+                    QPrinter::PageSize pageSize = QPrinter::Custom);
+
+  void copyAllLayers();
+  void print() override;
+  void printAllLayers(QPainter *painter);
+  void printActiveLayer();
+  //@}
 
-	void setFonts(const QFont& titleFnt, const QFont& scaleFnt,
-							const QFont& numbersFnt, const QFont& legendFnt);
+  void setFonts(const QFont &titleFnt, const QFont &scaleFnt,
+                const QFont &numbersFnt, const QFont &legendFnt);
 
-	void connectLayer(Graph *g);
+  void connectLayer(Graph *g);
 
   void maybeNeedToClose();
 
@@ -180,117 +189,115 @@ public slots:
   void reverseWaterfallOrder();
   void showWaterfallFillDialog();
   void updateWaterfalls();
-  bool isWaterfallPlot(){return d_is_waterfall_plot;}
-  QColor waterfallFillColor(){return d_waterfall_fill_color;}
-  void setWaterfallFillColor(const QColor& c);
-  //@}
+  bool isWaterfallPlot() { return d_is_waterfall_plot; }
+  QColor waterfallFillColor() { return d_waterfall_fill_color; }
+  void setWaterfallFillColor(const QColor &c);
+//@}
 
 signals:
-	void showTextDialog();
-	void showPlotDialog(int);
-	void showAxisDialog(int);
-	void showScaleDialog(int);
-	void showGraphContextMenu();
-	void showCurveContextMenu(int);
-	void showCurvesDialog();
-	void drawTextOff();
-	void drawLineEnded(bool);
-	void showAxisTitleDialog();
-	void showMarkerPopupMenu();
-	void modifiedPlot();
-	void cursorInfo(const QString&);
-	void showImageDialog();
-	void showLineDialog();
-	void viewTitleDialog();
-	void createTable(const QString&,int,int,const QString&);
-	void pasteMarker();
-	void setPointerCursor();
-	void currentFontChanged(const QFont&);
-    void enableTextEditor(Graph *);
+  void showTextDialog();
+  void showPlotDialog(int);
+  void showAxisDialog(int);
+  void showScaleDialog(int);
+  void showGraphContextMenu();
+  void showCurveContextMenu(int);
+  void showCurvesDialog();
+  void drawTextOff();
+  void drawLineEnded(bool);
+  void showAxisTitleDialog();
+  void showMarkerPopupMenu();
+  void modifiedPlot();
+  void cursorInfo(const QString &);
+  void showImageDialog();
+  void showLineDialog();
+  void viewTitleDialog();
+  void createTable(const QString &, int, int, const QString &);
+  void pasteMarker();
+  void setPointerCursor();
+  void currentFontChanged(const QFont &);
+  void enableTextEditor(Graph *);
 
 private:
-
   /// Handle dropping of additional curves onto a MantidMDCurve.
-  void dropOntoMDCurve(Graph *g, MantidMDCurve* originalCurve, MantidTreeWidget * tree);
+  void dropOntoMDCurve(Graph *g, MantidMDCurve *originalCurve,
+                       MantidTreeWidget *tree);
   /// Handle dropping of additional curves onto a MantidMatrixCurve
-  void dropOntoMatrixCurve(Graph *g, MantidMatrixCurve* originalCurve, MantidTreeWidget * tree);
+  void dropOntoMatrixCurve(Graph *g, MantidMatrixCurve *originalCurve,
+                           MantidTreeWidget *tree);
 
-	//! \name Event Handlers
-	//@{
+  //! \name Event Handlers
+  //@{
   void closeEvent(QCloseEvent *) override;
   void wheelEvent(QWheelEvent *) override;
   void keyPressEvent(QKeyEvent *) override;
   bool eventFilter(QObject *object, QEvent *) override;
-        void releaseLayer();
-	void resizeLayers(QResizeEvent *re);
-        bool focusNextPrevChild(bool next) override;
-        void dragEnterEvent(QDragEnterEvent *event) override;
-        void dropEvent(QDropEvent *event) override;
-        //@}
+  void releaseLayer();
+  void resizeLayers(QResizeEvent *re);
+  bool focusNextPrevChild(bool next) override;
+  void dragEnterEvent(QDragEnterEvent *event) override;
+  void dropEvent(QDropEvent *event) override;
+  //@}
 
   void removeLayerSelectionFrame();
 
   void createWaterfallBox();
   void removeWaterfallBox();
 
-	Graph* active_graph;
-	//! Used for resizing of layers.
-	int d_cols, d_rows, graph_width, graph_height, colsSpace, rowsSpace;
-	int left_margin, right_margin, top_margin, bottom_margin;
-	int l_canvas_width, l_canvas_height, hor_align, vert_align;
-	bool d_scale_on_print, d_print_cropmarks;
+  Graph *active_graph;
+  //! Used for resizing of layers.
+  int d_cols, d_rows, graph_width, graph_height, colsSpace, rowsSpace;
+  int left_margin, right_margin, top_margin, bottom_margin;
+  int l_canvas_width, l_canvas_height, hor_align, vert_align;
+  bool d_scale_on_print, d_print_cropmarks;
 
-    QList<LayerButton *> buttonsList;
-    QList<Graph *> graphsList;
+  QList<LayerButton *> buttonsList;
+  QList<Graph *> graphsList;
   QHBoxLayout *layerButtonsBox, *waterfallBox;
   QHBoxLayout *buttonsLine;
-    QWidget *canvas;
+  QWidget *canvas;
 
-	QPointer<SelectionMoveResizer> d_layers_selector;
-  bool d_close_on_empty;/// true makes Multilayer close itself if it becomes empty
+  QPointer<SelectionMoveResizer> d_layers_selector;
+  bool d_close_on_empty; /// true makes Multilayer close itself if it becomes
+                         /// empty
 
   bool d_is_waterfall_plot;
   QColor d_waterfall_fill_color;
 };
 
 //! Button with layer number
-class LayerButton: public QPushButton
-{
-	Q_OBJECT
+class LayerButton : public QPushButton {
+  Q_OBJECT
 
 public:
-    LayerButton (const QString& text = QString::null, QWidget* parent = 0);
-	static int btnSize(){return 20;};
+  LayerButton(const QString &text = QString::null, QWidget *parent = 0);
+  static int btnSize() { return 20; };
 
 protected:
   void mousePressEvent(QMouseEvent *) override;
   void mouseDoubleClickEvent(QMouseEvent *) override;
 
 signals:
-	void showCurvesDialog();
-	void clicked(LayerButton*);
+  void showCurvesDialog();
+  void clicked(LayerButton *);
 };
 
-Q_DECLARE_METATYPE(MultiLayer*)
+Q_DECLARE_METATYPE(MultiLayer *)
 
-
-class WaterfallFillDialog : QDialog
-{
-    Q_OBJECT
+class WaterfallFillDialog : QDialog {
+  Q_OBJECT
 
 public:
-    WaterfallFillDialog(MultiLayer *parent, Graph *active_graph);
+  WaterfallFillDialog(MultiLayer *parent, Graph *active_graph);
 
 public slots:
   void setFillMode();
   void enableFill(bool b);
 
 private:
-    Graph *m_active_graph;
-    QRadioButton *m_solidRadioButton;
-    QRadioButton *m_lineRadioButton;
-    ColorButton *m_colourBox;
+  Graph *m_active_graph;
+  QRadioButton *m_solidRadioButton;
+  QRadioButton *m_lineRadioButton;
+  ColorButton *m_colourBox;
 };
 
-
 #endif
diff --git a/MantidPlot/src/MultiPeakFit.cpp b/MantidPlot/src/MultiPeakFit.cpp
index 19e82aa0b9a2ebaada92fdc7c60ada970e69b62c..b540790e890f2a60ab73b18b63de3fd27e326976 100644
--- a/MantidPlot/src/MultiPeakFit.cpp
+++ b/MantidPlot/src/MultiPeakFit.cpp
@@ -2,9 +2,11 @@
     File                 : fitclasses.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
-    Description          : MultiPeakFit module with Lorentz and Gauss peak shapes
+    Description          : MultiPeakFit module with Lorentz and Gauss peak
+ shapes
 
  ***************************************************************************/
 
@@ -38,382 +40,397 @@
 #include <QLocale>
 #include <QMessageBox>
 
-MultiPeakFit::MultiPeakFit(ApplicationWindow *parent, Graph *g, PeakProfile profile, int peaks)
-: Fit(parent, g), d_profile(profile)
-{
-init(peaks);
-}
-
-MultiPeakFit::MultiPeakFit(ApplicationWindow *parent, Table *t, const QString&, const QString&,
-		  				  int, int, PeakProfile profile, int peaks)
-: Fit(parent, t), d_profile(profile)
-{
-init(peaks);
-}
-
-void MultiPeakFit::init(int peaks)
-{
-	if (d_profile == Gauss){
-		setObjectName(tr("Gauss"));
-		d_f = gauss_multi_peak_f;
-		d_df = gauss_multi_peak_df;
-		d_fdf = gauss_multi_peak_fdf;
-		d_fsimplex = gauss_multi_peak_d;
-	} else {
-		setObjectName(tr("Lorentz"));
-		d_f = lorentz_multi_peak_f;
-		d_df = lorentz_multi_peak_df;
-		d_fdf = lorentz_multi_peak_fdf;
-		d_fsimplex = lorentz_multi_peak_d;
-	}
-
-	d_param_init = NULL;
-	covar = NULL;
-	d_results = NULL;
-
-	setNumPeaks(peaks);
-
-	generate_peak_curves = true;
-	d_peaks_color = 2;//green
-}
-
-void MultiPeakFit::setNumPeaks(int n)
-{
-	d_peaks = n;
-	if (d_profile == Gauss)
-		d_explanation = tr("Gauss Fit");
-	else
-		d_explanation = tr("Lorentz Fit");
-	if (d_peaks > 1)
-		d_explanation += "(" + QString::number(d_peaks) +") " + tr("multi-peak");
-
-	freeWorkspace();
-	d_p = 3*d_peaks + 1;
-	initWorkspace(d_p);
-
-	d_param_names = generateParameterList(d_peaks);
-	d_param_explain = generateExplanationList(d_peaks);
-	d_formula = generateFormula(d_peaks, d_profile);
-}
-
-QStringList MultiPeakFit::generateParameterList(int peaks)
-{
-	if (peaks == 1)
-		return QStringList() << "A" << "xc" << "w" << "y0";
-
-	QStringList lst;
-	for (int i = 0; i<peaks; i++){
-		QString index = QString::number(i+1);
-		lst << "A" + index;
-		lst << "xc" + index;
-		lst << "w" + index;
-	}
-	lst << "y0";
-	return lst;
-}
-
-QStringList MultiPeakFit::generateExplanationList(int peaks)
-{
-	if (peaks == 1)
-		return QStringList() << tr("area") << tr("center") <<  tr("width") << tr("offset");
-
-	QStringList lst;
-	for (int i = 0; i<peaks; i++){
-		QString index = QString::number(i+1);
-		lst << tr("area") + " " + index;
-		lst << tr("center") + " " + index;
-		lst << tr("width") + " " + index;
-	}
-	lst << tr("offset");
-	return lst;
-}
-
-QString MultiPeakFit::generateFormula(int peaks, PeakProfile profile)
-{
-	if (peaks == 1){
-		switch (profile){
-			case Gauss:
-				return "y0+A*sqrt(2/PI)/w*exp(-2*((x-xc)/w)^2)";
-				break;
-
-			case Lorentz:
-				return "y0+2*A/PI*w/(4*(x-xc)^2+w^2)";
-				break;
-		}
-	}
-
-	QString formula = "y0+";
-	for (int i = 0; i<peaks; i++){
-		formula += peakFormula(i+1, profile);
-		if (i < peaks - 1)
-			formula += "+";
-	}
-	return formula;
-}
-
-QString MultiPeakFit::peakFormula(int peakIndex, PeakProfile profile)
-{
-	QString formula;
-	QString index = QString::number(peakIndex);
-	switch (profile)
-	{
-		case Gauss:
-			formula += "sqrt(2/PI)*A" + index + "/w" + index;
-			formula += "*exp(-2*(x-xc" + index + ")^2/w" + index + "^2)";
-			break;
-		case Lorentz:
-			formula += "2*A"+index+"/PI*w"+index+"/(4*(x-xc"+index+")^2+w"+index+"^2)";
-			break;
-	}
-	return formula;
-}
-
-void MultiPeakFit::guessInitialValues()
-{
-	if (!d_n || d_peaks > 1)
-		return;
-
-	size_t imin, imax;
-	gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);
-
-	double min_out = d_y[imin];
-	double max_out = d_y[imax];
-
-	QVarLengthArray<double> temp(d_n);//double temp[d_n];
-	for (int i = 0; i < d_n; i++)
-		temp[i] = fabs(d_y[i]);
-	size_t imax_temp = gsl_stats_max_index(temp.data(), 1, d_n);//size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);
-
-	double offset, area;
-	if (imax_temp == imax)
-		offset = min_out;
-	else //reversed bell
-		offset = max_out;
-
-	double xc = d_x[imax_temp];
-	double width = 2*gsl_stats_sd(d_x, 1, d_n);
-
-	if (d_profile == Lorentz)
-		area = M_PI_2*width*fabs(max_out - min_out);
-	else
-		area = sqrt(M_PI_2)*width*fabs(max_out - min_out);
-
-	gsl_vector_set(d_param_init, 0, area);
-	gsl_vector_set(d_param_init, 1, xc);
-	gsl_vector_set(d_param_init, 2, width);
-	gsl_vector_set(d_param_init, 3, offset);
-}
-
-void MultiPeakFit::customizeFitResults()
-{
-	for (int j=0; j<d_peaks; j++){
-	    d_results[3*j] = fabs(d_results[3*j]);
-        d_results[3*j + 2] = fabs(d_results[3*j + 2]);
-	}
-}
-
-void MultiPeakFit::insertPeakFunctionCurve(double *x, double *y, int peak)
-{
-	QStringList curves = d_output_graph->curvesList();
-	int index = 0;
-	for (int i = 0; i<(int)curves.count(); i++ ){
-		if (curves[i].startsWith(tr("Peak")))
-			index++;
-	}
-	QString title = tr("Peak") + QString::number(++index);
-
-	FunctionCurve *c = new FunctionCurve(FunctionCurve::Normal, title);
-	c->setPen(QPen(ColorBox::color(d_peaks_color), 1));
-	c->setData(x, y, d_points);
-	c->setRange(d_x[0], d_x[d_n-1]);
-
-	QString formula = "y0+"+peakFormula(peak + 1, d_profile);
-	QString parameter = QString::number(d_results[d_p-1], 'e', d_prec);
-	formula.replace(d_param_names[d_p-1], parameter);
-	for (int j=0; j<3; j++){
-		int p = 3*peak + j;
-		parameter = QString::number(d_results[p], 'e', d_prec);
-		formula.replace(d_param_names[p], parameter);
-	}
-	c->setFormula(formula.replace("--", "+").replace("-+", "-").replace("+-", "-"));
-	d_output_graph->insertPlotItem(c, Graph::Line);
-	d_output_graph->addFitCurve(c);
-}
-
-void MultiPeakFit::generateFitCurve()
-{
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
-	if (!d_gen_function)
-		d_points = d_n;
-
-	gsl_matrix * m = gsl_matrix_alloc (d_points, d_peaks);
-	if (!m){
-		QMessageBox::warning(app, tr("MantidPlot - Fit Error"), tr("Could not allocate enough memory for the fit curves!"));
-		return;
-	}
-
-	QVarLengthArray<double> X(d_points), Y(d_points);//double X[d_points], Y[d_points];
-	int i, j;
-	int peaks_aux = d_peaks;
-	if (d_peaks == 1)
-		peaks_aux--;
-
-	if (d_gen_function){
-		double step = (d_x[d_n-1] - d_x[0])/(d_points-1);
-		for (i = 0; i<d_points; i++){
-		    double x = d_x[0] + i*step;
-			X[i] = x;
-			double yi = 0;
-			for (j=0; j<d_peaks; j++){
-                double y = evalPeak(d_results, x, j);
-				gsl_matrix_set(m, i, j, y + d_results[d_p - 1]);
-				yi += y;
-			}
-            Y[i] = yi + d_results[d_p - 1];//add offset
-		}
-
-        customizeFitResults();
-
-		if (d_graphics_display){
-			if (!d_output_graph)
-				d_output_graph = createOutputGraph()->activeGraph();
-
-			if (d_peaks > 1)
-				insertFitFunctionCurve(QString(objectName()) + tr("Fit"), X.data(), Y.data(), 2);//insertFitFunctionCurve(QString(objectName()) + tr("Fit"), X, Y, 2);
-			else
-				insertFitFunctionCurve(QString(objectName()) + tr("Fit"), X.data(), Y.data());//insertFitFunctionCurve(QString(objectName()) + tr("Fit"), X, Y);
-
-			if (generate_peak_curves){
-				for (i=0; i<peaks_aux; i++){//add the peak curves
-					for (j=0; j<d_points; j++)
-						Y[j] = gsl_matrix_get (m, j, i);
-
-				insertPeakFunctionCurve(X.data(), Y.data(), i);//insertPeakFunctionCurve(X, Y, i);
-				}
-			}
-			d_output_graph->replot();
-		}
-	} else {
-		QString tableName = app->generateUniqueName(tr("Fit"));
-		QString dataSet;
-		if (d_curve)
-			dataSet = d_curve->title().text();
-		else
-			dataSet = d_y_col_name;
-		QString label = d_explanation + " " + tr("fit of") + " " + dataSet;
-
-		d_result_table = app->newHiddenTable(tableName, label, d_points, peaks_aux + 2);
-		QStringList header = QStringList() << "1";
-		for (i = 0; i<peaks_aux; i++)
-			header << tr("peak") + QString::number(i+1);
-		header << "2";
-		d_result_table->setHeader(header);
-
-        QLocale locale = app->locale();
-		for (i = 0; i<d_points; i++){
-			X[i] = d_x[i];
-			d_result_table->setText(i, 0, locale.toString(X[i], 'e', d_prec));
-
-			double yi=0;
-			for (j=0; j<d_peaks; j++){
-				double diff = X[i] - d_results[3*j + 1];
-				double w = d_results[3*j + 2];
-				double y_aux = 0;
-				if (d_profile == Gauss)
-					y_aux += sqrt(M_2_PI)*d_results[3*j]/w*exp(-2*diff*diff/(w*w));
-				else
-					y_aux += M_2_PI*d_results[3*j]*w/(4*diff*diff+w*w);
-
-				yi += y_aux;
-				y_aux += d_results[d_p - 1];
-				d_result_table->setText(i, j+1, locale.toString(y_aux, 'e', d_prec));
-				gsl_matrix_set(m, i, j, y_aux);
-			}
-			Y[i] = yi + d_results[d_p - 1];//add offset
-			if (d_peaks > 1)
-				d_result_table->setText(i, d_peaks+1, locale.toString(Y[i], 'e', d_prec));
-		}
-
-		customizeFitResults();
-
-		if (d_graphics_display){
-			if (!d_output_graph)
-				d_output_graph = createOutputGraph()->activeGraph();
-
-			label = tableName + "_2";
-			DataCurve *c = new DataCurve(d_result_table, tableName + "_1", label);
-			if (d_peaks > 1)
-				c->setPen(QPen(ColorBox::color(d_curveColorIndex), 2));
-			else
-				c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
-			c->setData(X.data(), Y.data(), d_points);//c->setData(X, Y, d_points);
-			d_output_graph->insertPlotItem(c, Graph::Line);
-			d_output_graph->addFitCurve(c);
-
-			if (generate_peak_curves){
-				for (i=0; i<peaks_aux; i++){//add the peak curves
-					for (j=0; j<d_points; j++)
-						Y[j] = gsl_matrix_get (m, j, i);
-
-					label = tableName + "_" + tr("peak") + QString::number(i+1);
-					c = new DataCurve(d_result_table, tableName + "_1", label);
-					c->setPen(QPen(ColorBox::color(d_peaks_color), 1));
-					c->setData(X.data(), Y.data(), d_points);//c->setData(X, Y, d_points);
-					d_output_graph->insertPlotItem(c, Graph::Line);
-					d_output_graph->addFitCurve(c);
-				}
-			}
-			d_output_graph->replot();
-		}
-	}
-	gsl_matrix_free(m);
-}
-
-double MultiPeakFit::eval(double *par, double x)
-{
-	double y = 0;
-	for (int i=0; i<d_peaks; i++)
-		y += evalPeak(par, x, i);
-
-	return y + par[d_p - 1];//add offset
-}
-
-double MultiPeakFit::evalPeak(double *par, double x, int peak)
-{
-	int aux = 3*peak;
-    double diff = x - par[aux + 1];
-    double w = par[aux + 2];
-    if (d_profile == Gauss)
-        return sqrt(M_2_PI)*par[aux]/w*exp(-2*diff*diff/(w*w));
+MultiPeakFit::MultiPeakFit(ApplicationWindow *parent, Graph *g,
+                           PeakProfile profile, int peaks)
+    : Fit(parent, g), d_profile(profile) {
+  init(peaks);
+}
+
+MultiPeakFit::MultiPeakFit(ApplicationWindow *parent, Table *t, const QString &,
+                           const QString &, int, int, PeakProfile profile,
+                           int peaks)
+    : Fit(parent, t), d_profile(profile) {
+  init(peaks);
+}
+
+void MultiPeakFit::init(int peaks) {
+  if (d_profile == Gauss) {
+    setObjectName(tr("Gauss"));
+    d_f = gauss_multi_peak_f;
+    d_df = gauss_multi_peak_df;
+    d_fdf = gauss_multi_peak_fdf;
+    d_fsimplex = gauss_multi_peak_d;
+  } else {
+    setObjectName(tr("Lorentz"));
+    d_f = lorentz_multi_peak_f;
+    d_df = lorentz_multi_peak_df;
+    d_fdf = lorentz_multi_peak_fdf;
+    d_fsimplex = lorentz_multi_peak_d;
+  }
+
+  d_param_init = NULL;
+  covar = NULL;
+  d_results = NULL;
+
+  setNumPeaks(peaks);
+
+  generate_peak_curves = true;
+  d_peaks_color = 2; // green
+}
+
+void MultiPeakFit::setNumPeaks(int n) {
+  d_peaks = n;
+  if (d_profile == Gauss)
+    d_explanation = tr("Gauss Fit");
+  else
+    d_explanation = tr("Lorentz Fit");
+  if (d_peaks > 1)
+    d_explanation += "(" + QString::number(d_peaks) + ") " + tr("multi-peak");
+
+  freeWorkspace();
+  d_p = 3 * d_peaks + 1;
+  initWorkspace(d_p);
+
+  d_param_names = generateParameterList(d_peaks);
+  d_param_explain = generateExplanationList(d_peaks);
+  d_formula = generateFormula(d_peaks, d_profile);
+}
+
+QStringList MultiPeakFit::generateParameterList(int peaks) {
+  if (peaks == 1)
+    return QStringList() << "A"
+                         << "xc"
+                         << "w"
+                         << "y0";
+
+  QStringList lst;
+  for (int i = 0; i < peaks; i++) {
+    QString index = QString::number(i + 1);
+    lst << "A" + index;
+    lst << "xc" + index;
+    lst << "w" + index;
+  }
+  lst << "y0";
+  return lst;
+}
+
+QStringList MultiPeakFit::generateExplanationList(int peaks) {
+  if (peaks == 1)
+    return QStringList() << tr("area") << tr("center") << tr("width")
+                         << tr("offset");
+
+  QStringList lst;
+  for (int i = 0; i < peaks; i++) {
+    QString index = QString::number(i + 1);
+    lst << tr("area") + " " + index;
+    lst << tr("center") + " " + index;
+    lst << tr("width") + " " + index;
+  }
+  lst << tr("offset");
+  return lst;
+}
+
+QString MultiPeakFit::generateFormula(int peaks, PeakProfile profile) {
+  if (peaks == 1) {
+    switch (profile) {
+    case Gauss:
+      return "y0+A*sqrt(2/PI)/w*exp(-2*((x-xc)/w)^2)";
+      break;
+
+    case Lorentz:
+      return "y0+2*A/PI*w/(4*(x-xc)^2+w^2)";
+      break;
+    }
+  }
+
+  QString formula = "y0+";
+  for (int i = 0; i < peaks; i++) {
+    formula += peakFormula(i + 1, profile);
+    if (i < peaks - 1)
+      formula += "+";
+  }
+  return formula;
+}
+
+QString MultiPeakFit::peakFormula(int peakIndex, PeakProfile profile) {
+  QString formula;
+  QString index = QString::number(peakIndex);
+  switch (profile) {
+  case Gauss:
+    formula += "sqrt(2/PI)*A" + index + "/w" + index;
+    formula += "*exp(-2*(x-xc" + index + ")^2/w" + index + "^2)";
+    break;
+  case Lorentz:
+    formula += "2*A" + index + "/PI*w" + index + "/(4*(x-xc" + index + ")^2+w" +
+               index + "^2)";
+    break;
+  }
+  return formula;
+}
+
+void MultiPeakFit::guessInitialValues() {
+  if (!d_n || d_peaks > 1)
+    return;
+
+  size_t imin, imax;
+  gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);
+
+  double min_out = d_y[imin];
+  double max_out = d_y[imax];
+
+  QVarLengthArray<double> temp(d_n); // double temp[d_n];
+  for (int i = 0; i < d_n; i++)
+    temp[i] = fabs(d_y[i]);
+  size_t imax_temp = gsl_stats_max_index(
+      temp.data(), 1,
+      d_n); // size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);
+
+  double offset, area;
+  if (imax_temp == imax)
+    offset = min_out;
+  else // reversed bell
+    offset = max_out;
+
+  double xc = d_x[imax_temp];
+  double width = 2 * gsl_stats_sd(d_x, 1, d_n);
+
+  if (d_profile == Lorentz)
+    area = M_PI_2 * width * fabs(max_out - min_out);
+  else
+    area = sqrt(M_PI_2) * width * fabs(max_out - min_out);
+
+  gsl_vector_set(d_param_init, 0, area);
+  gsl_vector_set(d_param_init, 1, xc);
+  gsl_vector_set(d_param_init, 2, width);
+  gsl_vector_set(d_param_init, 3, offset);
+}
+
+void MultiPeakFit::customizeFitResults() {
+  for (int j = 0; j < d_peaks; j++) {
+    d_results[3 * j] = fabs(d_results[3 * j]);
+    d_results[3 * j + 2] = fabs(d_results[3 * j + 2]);
+  }
+}
+
+void MultiPeakFit::insertPeakFunctionCurve(double *x, double *y, int peak) {
+  QStringList curves = d_output_graph->curvesList();
+  int index = 0;
+  for (int i = 0; i < (int)curves.count(); i++) {
+    if (curves[i].startsWith(tr("Peak")))
+      index++;
+  }
+  QString title = tr("Peak") + QString::number(++index);
+
+  FunctionCurve *c = new FunctionCurve(FunctionCurve::Normal, title);
+  c->setPen(QPen(ColorBox::color(d_peaks_color), 1));
+  c->setData(x, y, d_points);
+  c->setRange(d_x[0], d_x[d_n - 1]);
+
+  QString formula = "y0+" + peakFormula(peak + 1, d_profile);
+  QString parameter = QString::number(d_results[d_p - 1], 'e', d_prec);
+  formula.replace(d_param_names[d_p - 1], parameter);
+  for (int j = 0; j < 3; j++) {
+    int p = 3 * peak + j;
+    parameter = QString::number(d_results[p], 'e', d_prec);
+    formula.replace(d_param_names[p], parameter);
+  }
+  c->setFormula(
+      formula.replace("--", "+").replace("-+", "-").replace("+-", "-"));
+  d_output_graph->insertPlotItem(c, Graph::Line);
+  d_output_graph->addFitCurve(c);
+}
+
+void MultiPeakFit::generateFitCurve() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  if (!d_gen_function)
+    d_points = d_n;
+
+  gsl_matrix *m = gsl_matrix_alloc(d_points, d_peaks);
+  if (!m) {
+    QMessageBox::warning(
+        app, tr("MantidPlot - Fit Error"),
+        tr("Could not allocate enough memory for the fit curves!"));
+    return;
+  }
+
+  QVarLengthArray<double> X(d_points),
+      Y(d_points); // double X[d_points], Y[d_points];
+  int i, j;
+  int peaks_aux = d_peaks;
+  if (d_peaks == 1)
+    peaks_aux--;
+
+  if (d_gen_function) {
+    double step = (d_x[d_n - 1] - d_x[0]) / (d_points - 1);
+    for (i = 0; i < d_points; i++) {
+      double x = d_x[0] + i * step;
+      X[i] = x;
+      double yi = 0;
+      for (j = 0; j < d_peaks; j++) {
+        double y = evalPeak(d_results, x, j);
+        gsl_matrix_set(m, i, j, y + d_results[d_p - 1]);
+        yi += y;
+      }
+      Y[i] = yi + d_results[d_p - 1]; // add offset
+    }
+
+    customizeFitResults();
+
+    if (d_graphics_display) {
+      if (!d_output_graph)
+        d_output_graph = createOutputGraph()->activeGraph();
+
+      if (d_peaks > 1)
+        insertFitFunctionCurve(
+            QString(objectName()) + tr("Fit"), X.data(), Y.data(),
+            2); // insertFitFunctionCurve(QString(objectName()) + tr("Fit"), X,
+                // Y, 2);
+      else
+        insertFitFunctionCurve(
+            QString(objectName()) + tr("Fit"), X.data(),
+            Y.data()); // insertFitFunctionCurve(QString(objectName()) +
+                       // tr("Fit"), X, Y);
+
+      if (generate_peak_curves) {
+        for (i = 0; i < peaks_aux; i++) { // add the peak curves
+          for (j = 0; j < d_points; j++)
+            Y[j] = gsl_matrix_get(m, j, i);
+
+          insertPeakFunctionCurve(X.data(), Y.data(),
+                                  i); // insertPeakFunctionCurve(X, Y, i);
+        }
+      }
+      d_output_graph->replot();
+    }
+  } else {
+    QString tableName = app->generateUniqueName(tr("Fit"));
+    QString dataSet;
+    if (d_curve)
+      dataSet = d_curve->title().text();
     else
-        return M_2_PI*par[aux]*w/(4*diff*diff+w*w);
-}
+      dataSet = d_y_col_name;
+    QString label = d_explanation + " " + tr("fit of") + " " + dataSet;
 
-QString MultiPeakFit::logFitInfo(int iterations, int status)
-{
-	QString info = Fit::logFitInfo(iterations, status);
-	if (d_peaks == 1)
-		return info;
+    d_result_table =
+        app->newHiddenTable(tableName, label, d_points, peaks_aux + 2);
+    QStringList header = QStringList() << "1";
+    for (i = 0; i < peaks_aux; i++)
+      header << tr("peak") + QString::number(i + 1);
+    header << "2";
+    d_result_table->setHeader(header);
 
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
     QLocale locale = app->locale();
-
-	info += tr("Peak") + "\t" + tr("Area") + "\t";
-	info += tr("Center") + "\t" + tr("Width") + "\t" + tr("Height") + "\n";
-	info += "---------------------------------------------------------------------------------------\n";
-	for (int j=0; j<d_peaks; j++){
-		info += QString::number(j+1) + "\t";
-		info += locale.toString(d_results[3*j], 'e', d_prec) + "\t";
-		info += locale.toString(d_results[3*j+1], 'e', d_prec) + "\t";
-		info += locale.toString(d_results[3*j+2], 'e', d_prec) + "\t";
-
-		if (d_profile == Lorentz)
-			info += locale.toString(M_2_PI*d_results[3*j]/d_results[3*j+2], 'e', d_prec) + "\n";
-		else
-			info += locale.toString(sqrt(M_2_PI)*d_results[3*j]/d_results[3*j+2], 'e', d_prec) + "\n";
-	}
-	info += "---------------------------------------------------------------------------------------\n";
-	return info;
+    for (i = 0; i < d_points; i++) {
+      X[i] = d_x[i];
+      d_result_table->setText(i, 0, locale.toString(X[i], 'e', d_prec));
+
+      double yi = 0;
+      for (j = 0; j < d_peaks; j++) {
+        double diff = X[i] - d_results[3 * j + 1];
+        double w = d_results[3 * j + 2];
+        double y_aux = 0;
+        if (d_profile == Gauss)
+          y_aux += sqrt(M_2_PI) * d_results[3 * j] / w *
+                   exp(-2 * diff * diff / (w * w));
+        else
+          y_aux += M_2_PI * d_results[3 * j] * w / (4 * diff * diff + w * w);
+
+        yi += y_aux;
+        y_aux += d_results[d_p - 1];
+        d_result_table->setText(i, j + 1, locale.toString(y_aux, 'e', d_prec));
+        gsl_matrix_set(m, i, j, y_aux);
+      }
+      Y[i] = yi + d_results[d_p - 1]; // add offset
+      if (d_peaks > 1)
+        d_result_table->setText(i, d_peaks + 1,
+                                locale.toString(Y[i], 'e', d_prec));
+    }
+
+    customizeFitResults();
+
+    if (d_graphics_display) {
+      if (!d_output_graph)
+        d_output_graph = createOutputGraph()->activeGraph();
+
+      label = tableName + "_2";
+      DataCurve *c = new DataCurve(d_result_table, tableName + "_1", label);
+      if (d_peaks > 1)
+        c->setPen(QPen(ColorBox::color(d_curveColorIndex), 2));
+      else
+        c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
+      c->setData(X.data(), Y.data(), d_points); // c->setData(X, Y, d_points);
+      d_output_graph->insertPlotItem(c, Graph::Line);
+      d_output_graph->addFitCurve(c);
+
+      if (generate_peak_curves) {
+        for (i = 0; i < peaks_aux; i++) { // add the peak curves
+          for (j = 0; j < d_points; j++)
+            Y[j] = gsl_matrix_get(m, j, i);
+
+          label = tableName + "_" + tr("peak") + QString::number(i + 1);
+          c = new DataCurve(d_result_table, tableName + "_1", label);
+          c->setPen(QPen(ColorBox::color(d_peaks_color), 1));
+          c->setData(X.data(), Y.data(),
+                     d_points); // c->setData(X, Y, d_points);
+          d_output_graph->insertPlotItem(c, Graph::Line);
+          d_output_graph->addFitCurve(c);
+        }
+      }
+      d_output_graph->replot();
+    }
+  }
+  gsl_matrix_free(m);
+}
+
+double MultiPeakFit::eval(double *par, double x) {
+  double y = 0;
+  for (int i = 0; i < d_peaks; i++)
+    y += evalPeak(par, x, i);
+
+  return y + par[d_p - 1]; // add offset
+}
+
+double MultiPeakFit::evalPeak(double *par, double x, int peak) {
+  int aux = 3 * peak;
+  double diff = x - par[aux + 1];
+  double w = par[aux + 2];
+  if (d_profile == Gauss)
+    return sqrt(M_2_PI) * par[aux] / w * exp(-2 * diff * diff / (w * w));
+  else
+    return M_2_PI * par[aux] * w / (4 * diff * diff + w * w);
+}
+
+QString MultiPeakFit::logFitInfo(int iterations, int status) {
+  QString info = Fit::logFitInfo(iterations, status);
+  if (d_peaks == 1)
+    return info;
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  QLocale locale = app->locale();
+
+  info += tr("Peak") + "\t" + tr("Area") + "\t";
+  info += tr("Center") + "\t" + tr("Width") + "\t" + tr("Height") + "\n";
+  info += "--------------------------------------------------------------------"
+          "-------------------\n";
+  for (int j = 0; j < d_peaks; j++) {
+    info += QString::number(j + 1) + "\t";
+    info += locale.toString(d_results[3 * j], 'e', d_prec) + "\t";
+    info += locale.toString(d_results[3 * j + 1], 'e', d_prec) + "\t";
+    info += locale.toString(d_results[3 * j + 2], 'e', d_prec) + "\t";
+
+    if (d_profile == Lorentz)
+      info += locale.toString(M_2_PI * d_results[3 * j] / d_results[3 * j + 2],
+                              'e', d_prec) +
+              "\n";
+    else
+      info += locale.toString(sqrt(M_2_PI) * d_results[3 * j] /
+                                  d_results[3 * j + 2],
+                              'e', d_prec) +
+              "\n";
+  }
+  info += "--------------------------------------------------------------------"
+          "-------------------\n";
+  return info;
 }
 
 /*****************************************************************************
@@ -423,37 +440,36 @@ QString MultiPeakFit::logFitInfo(int iterations, int status)
  *****************************************************************************/
 
 LorentzFit::LorentzFit(ApplicationWindow *parent, Graph *g)
-: MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1)
-{
-	init();
+    : MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1) {
+  init();
 }
 
-LorentzFit::LorentzFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1)
-{
-	init();
-	setDataFromCurve(curveTitle);
+LorentzFit::LorentzFit(ApplicationWindow *parent, Graph *g,
+                       const QString &curveTitle)
+    : MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-LorentzFit::LorentzFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+LorentzFit::LorentzFit(ApplicationWindow *parent, Graph *g,
+                       const QString &curveTitle, double start, double end)
+    : MultiPeakFit(parent, g, MultiPeakFit::Lorentz, 1) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-LorentzFit::LorentzFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: MultiPeakFit(parent, t, xCol, yCol, startRow, endRow, MultiPeakFit::Lorentz, 1)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+LorentzFit::LorentzFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                       const QString &yCol, int startRow, int endRow)
+    : MultiPeakFit(parent, t, xCol, yCol, startRow, endRow,
+                   MultiPeakFit::Lorentz, 1) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void LorentzFit::init()
-{
-	setObjectName(tr("Lorentz"));
-	d_explanation = tr("Lorentz Fit");
-	d_param_explain << tr("area") << tr("center") << tr("width") << tr("offset");
+void LorentzFit::init() {
+  setObjectName(tr("Lorentz"));
+  d_explanation = tr("Lorentz Fit");
+  d_param_explain << tr("area") << tr("center") << tr("width") << tr("offset");
 }
 
 /*****************************************************************************
@@ -463,37 +479,36 @@ void LorentzFit::init()
  *****************************************************************************/
 
 GaussFit::GaussFit(ApplicationWindow *parent, Graph *g)
-: MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1)
-{
-	init();
+    : MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1) {
+  init();
 }
 
-GaussFit::GaussFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1)
-{
-	init();
-	setDataFromCurve(curveTitle);
+GaussFit::GaussFit(ApplicationWindow *parent, Graph *g,
+                   const QString &curveTitle)
+    : MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-GaussFit::GaussFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+GaussFit::GaussFit(ApplicationWindow *parent, Graph *g,
+                   const QString &curveTitle, double start, double end)
+    : MultiPeakFit(parent, g, MultiPeakFit::Gauss, 1) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-GaussFit::GaussFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: MultiPeakFit(parent, t, xCol, yCol, startRow, endRow, MultiPeakFit::Gauss, 1)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+GaussFit::GaussFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                   const QString &yCol, int startRow, int endRow)
+    : MultiPeakFit(parent, t, xCol, yCol, startRow, endRow, MultiPeakFit::Gauss,
+                   1) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void GaussFit::init()
-{
-	setObjectName(tr("Gauss"));
-	d_explanation = tr("Gauss Fit");
-	d_param_explain << tr("area") << tr("center") << tr("width") << tr("offset");
+void GaussFit::init() {
+  setObjectName(tr("Gauss"));
+  d_explanation = tr("Gauss Fit");
+  d_param_explain << tr("area") << tr("center") << tr("width") << tr("offset");
 }
 
 /*****************************************************************************
@@ -502,99 +517,100 @@ void GaussFit::init()
  *
  *****************************************************************************/
 
-GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
-}
-
-GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
-}
-
-GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
-}
-
-GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
-}
-
-void GaussAmpFit::init()
-{
-	setObjectName(tr("GaussAmp"));
-	d_f = gauss_f;
-	d_df = gauss_df;
-	d_fdf = gauss_fdf;
-	d_fsimplex = gauss_d;
-	d_p = 4;
-    initWorkspace(d_p);
-	d_param_explain << tr("offset") << tr("amplitude") << tr("center") << tr("width");
-	d_param_names << "y0" << "A" << "xc" << "w";
-	d_explanation = tr("GaussAmp Fit");
-	d_formula = "y0+A*exp(-(x-xc)^2/(2*w^2))";
-}
-
-void GaussAmpFit::calculateFitCurveData(double *X, double *Y)
-{
-	double y0 = d_results[0];
-	double a = d_results[1];
-	double xc = d_results[2];
-	double w2 = d_results[3]*d_results[3];
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1] - X0)/(d_points - 1);
-		for (int i=0; i<d_points; i++){
-            double x = X0 + i*step;
-			X[i] = x;
-			double diff = x - xc;
-			Y[i] = a*exp(-0.5*diff*diff/w2) + y0;
-		}
-	}else{
-		for (int i=0; i<d_points; i++){
-		    double x = d_x[i];
-			X[i] = x;
-			double diff = x - xc;
-			Y[i] = a*exp(-0.5*diff*diff/w2) + y0;
-		}
-	}
-}
-
-double GaussAmpFit::eval(double *par, double x)
-{
-    double diff = x - par[2];
-    return par[1]*exp(-0.5*diff*diff/(par[3]*par[3])) + par[0];
-}
-
-void GaussAmpFit::guessInitialValues()
-{
-	size_t imin, imax;
-	gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);
-
-	double min_out = d_y[imin];
-	double max_out = d_y[imax];
-
-	gsl_vector_set(d_param_init, 1, fabs(max_out - min_out));
-
-	QVarLengthArray<double> temp(d_n);//double temp[d_n];
-	for (int i = 0; i < d_n; i++)
-		temp[i] = fabs(d_y[i]);
-	size_t imax_temp = gsl_stats_max_index(temp.data(), 1, d_n);//size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);
-
-	gsl_vector_set(d_param_init, 2, d_x[imax_temp]);
-	gsl_vector_set(d_param_init, 3, gsl_stats_sd(d_x, 1, d_n));
-
-	if (imax_temp == imax)
-		gsl_vector_set(d_param_init, 0, min_out);
-	else //reversed bell
-		gsl_vector_set(d_param_init, 0, max_out);
+GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g) : Fit(parent, g) {
+  init();
+}
+
+GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
+}
+
+GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Graph *g,
+                         const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
+}
+
+GaussAmpFit::GaussAmpFit(ApplicationWindow *parent, Table *t,
+                         const QString &xCol, const QString &yCol, int startRow,
+                         int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
+}
+
+void GaussAmpFit::init() {
+  setObjectName(tr("GaussAmp"));
+  d_f = gauss_f;
+  d_df = gauss_df;
+  d_fdf = gauss_fdf;
+  d_fsimplex = gauss_d;
+  d_p = 4;
+  initWorkspace(d_p);
+  d_param_explain << tr("offset") << tr("amplitude") << tr("center")
+                  << tr("width");
+  d_param_names << "y0"
+                << "A"
+                << "xc"
+                << "w";
+  d_explanation = tr("GaussAmp Fit");
+  d_formula = "y0+A*exp(-(x-xc)^2/(2*w^2))";
+}
+
+void GaussAmpFit::calculateFitCurveData(double *X, double *Y) {
+  double y0 = d_results[0];
+  double a = d_results[1];
+  double xc = d_results[2];
+  double w2 = d_results[3] * d_results[3];
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      double diff = x - xc;
+      Y[i] = a * exp(-0.5 * diff * diff / w2) + y0;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      double diff = x - xc;
+      Y[i] = a * exp(-0.5 * diff * diff / w2) + y0;
+    }
+  }
+}
+
+double GaussAmpFit::eval(double *par, double x) {
+  double diff = x - par[2];
+  return par[1] * exp(-0.5 * diff * diff / (par[3] * par[3])) + par[0];
+}
+
+void GaussAmpFit::guessInitialValues() {
+  size_t imin, imax;
+  gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);
+
+  double min_out = d_y[imin];
+  double max_out = d_y[imax];
+
+  gsl_vector_set(d_param_init, 1, fabs(max_out - min_out));
+
+  QVarLengthArray<double> temp(d_n); // double temp[d_n];
+  for (int i = 0; i < d_n; i++)
+    temp[i] = fabs(d_y[i]);
+  size_t imax_temp = gsl_stats_max_index(
+      temp.data(), 1,
+      d_n); // size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);
+
+  gsl_vector_set(d_param_init, 2, d_x[imax_temp]);
+  gsl_vector_set(d_param_init, 3, gsl_stats_sd(d_x, 1, d_n));
+
+  if (imax_temp == imax)
+    gsl_vector_set(d_param_init, 0, min_out);
+  else // reversed bell
+    gsl_vector_set(d_param_init, 0, max_out);
 }
diff --git a/MantidPlot/src/MultiPeakFit.h b/MantidPlot/src/MultiPeakFit.h
index 59f8ca64f2bbddf9af53689df3f1d5f90acda9e2..70542e1713f0e9b1b4e6ce5b953574ecea33c80c 100644
--- a/MantidPlot/src/MultiPeakFit.h
+++ b/MantidPlot/src/MultiPeakFit.h
@@ -2,9 +2,11 @@
     File                 : MultiPeakFit.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
-    Description          : MultiPeakFit module with Lorentz and Gauss peak shapes
+    Description          : MultiPeakFit module with Lorentz and Gauss peak
+ shapes
 
  ***************************************************************************/
 
@@ -31,98 +33,104 @@
 
 #include "Fit.h"
 
-class MultiPeakFit : public Fit
-{
-	Q_OBJECT
+class MultiPeakFit : public Fit {
+  Q_OBJECT
 
-	public:
-		enum PeakProfile{Gauss, Lorentz};
-		MultiPeakFit(ApplicationWindow *parent, Graph *g = 0, PeakProfile profile = Gauss, int peaks = 1);
-		MultiPeakFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol,
-		  			 int startRow = 0, int endRow = -1, PeakProfile profile = Gauss, int peaks = 1);
+public:
+  enum PeakProfile { Gauss, Lorentz };
+  MultiPeakFit(ApplicationWindow *parent, Graph *g = 0,
+               PeakProfile profile = Gauss, int peaks = 1);
+  MultiPeakFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+               const QString &yCol, int startRow = 0, int endRow = -1,
+               PeakProfile profile = Gauss, int peaks = 1);
 
-		int peaks(){return d_peaks;};
-		void setNumPeaks(int n);
+  int peaks() { return d_peaks; };
+  void setNumPeaks(int n);
 
-		void enablePeakCurves(bool on){generate_peak_curves = on;};
-		void setPeakCurvesColor(int colorIndex){d_peaks_color = colorIndex;};
+  void enablePeakCurves(bool on) { generate_peak_curves = on; };
+  void setPeakCurvesColor(int colorIndex) { d_peaks_color = colorIndex; };
 
-		static QString generateFormula(int order, PeakProfile profile);
-		static QStringList generateParameterList(int order);
-		static QStringList generateExplanationList(int order);
+  static QString generateFormula(int order, PeakProfile profile);
+  static QStringList generateParameterList(int order);
+  static QStringList generateExplanationList(int order);
 
-		//! Used by the GaussFit and LorentzFit derived classes to calculate initial values for the parameters
-                void guessInitialValues() override;
+  //! Used by the GaussFit and LorentzFit derived classes to calculate initial
+  // values for the parameters
+  void guessInitialValues() override;
 
-                double eval(double *par, double x) override;
-                double evalPeak(double *par, double x, int peak);
+  double eval(double *par, double x) override;
+  double evalPeak(double *par, double x, int peak);
 
-	private:
-		void init(int);
+private:
+  void init(int);
 
-                QString logFitInfo(int iterations, int status) override;
-                void generateFitCurve() override;
-                static QString peakFormula(int peakIndex, PeakProfile profile);
-		//! Inserts a peak function curve into the plot
-		void insertPeakFunctionCurve(double *x, double *y, int peak);
-                void customizeFitResults() override;
+  QString logFitInfo(int iterations, int status) override;
+  void generateFitCurve() override;
+  static QString peakFormula(int peakIndex, PeakProfile profile);
+  //! Inserts a peak function curve into the plot
+  void insertPeakFunctionCurve(double *x, double *y, int peak);
+  void customizeFitResults() override;
 
-                //! Number of peaks
-		int d_peaks;
+  //! Number of peaks
+  int d_peaks;
 
-		//! Tells weather the peak curves should be displayed together with the best line fit.
-		bool generate_peak_curves;
+  //! Tells weather the peak curves should be displayed together with the best
+  // line fit.
+  bool generate_peak_curves;
 
-		//! Color index for the peak curves
-		int d_peaks_color;
+  //! Color index for the peak curves
+  int d_peaks_color;
 
-		//! The peak profile
-		PeakProfile d_profile;
+  //! The peak profile
+  PeakProfile d_profile;
 };
 
-class LorentzFit : public MultiPeakFit
-{
-	Q_OBJECT
+class LorentzFit : public MultiPeakFit {
+  Q_OBJECT
 
-	public:
-		LorentzFit(ApplicationWindow *parent, Graph *g);
-		LorentzFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		LorentzFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		LorentzFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 0, int endRow = -1);
+public:
+  LorentzFit(ApplicationWindow *parent, Graph *g);
+  LorentzFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  LorentzFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+             double start, double end);
+  LorentzFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+             const QString &yCol, int startRow = 0, int endRow = -1);
 
-	private:
-		void init();
+private:
+  void init();
 };
 
-class GaussFit : public MultiPeakFit
-{
-	Q_OBJECT
+class GaussFit : public MultiPeakFit {
+  Q_OBJECT
 
-	public:
-		GaussFit(ApplicationWindow *parent, Graph *g);
-		GaussFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		GaussFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		GaussFit( ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 0, int endRow = -1);
+public:
+  GaussFit(ApplicationWindow *parent, Graph *g);
+  GaussFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  GaussFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+           double start, double end);
+  GaussFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+           const QString &yCol, int startRow = 0, int endRow = -1);
 
-	private:
-		void init();
+private:
+  void init();
 };
 
-class GaussAmpFit : public Fit
-{
-	Q_OBJECT
+class GaussAmpFit : public Fit {
+  Q_OBJECT
 
-	public:
-		GaussAmpFit(ApplicationWindow *parent, Graph *g);
-		GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		GaussAmpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 0, int endRow = -1);
+public:
+  GaussAmpFit(ApplicationWindow *parent, Graph *g);
+  GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  GaussAmpFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+              double start, double end);
+  GaussAmpFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+              const QString &yCol, int startRow = 0, int endRow = -1);
 
-                void guessInitialValues() override;
-                double eval(double *par, double x) override;
+  void guessInitialValues() override;
+  double eval(double *par, double x) override;
 
-        private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 #endif
diff --git a/MantidPlot/src/MultiPeakFitTool.cpp b/MantidPlot/src/MultiPeakFitTool.cpp
index 5acce04c1aab22c672e92aa372095707eb145f05..c79cb713aba4cac88bbae1f72e78ce2bf188491d 100644
--- a/MantidPlot/src/MultiPeakFitTool.cpp
+++ b/MantidPlot/src/MultiPeakFitTool.cpp
@@ -40,114 +40,122 @@
 
 #include <gsl/gsl_statistics.h>
 
-MultiPeakFitTool::MultiPeakFitTool(Graph *graph, ApplicationWindow *app, MultiPeakFit::PeakProfile profile, int num_peaks, const QObject *status_target, const char *status_slot)
-	: PlotToolInterface(graph),
-	d_profile(profile),
-	d_num_peaks(num_peaks)
-{
-	d_selected_peaks = 0;
-	d_curve = 0;
-
-	d_fit = new MultiPeakFit(app, d_graph, d_profile, d_num_peaks);
-	d_fit->enablePeakCurves(app->generatePeakCurves);
-	d_fit->setPeakCurvesColor(app->peakCurvesColor);
-	d_fit->generateFunction(app->generateUniformFitPoints, app->fitPoints);
-
-	if (status_target)
-		connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
-	d_picker_tool = new DataPickerTool(d_graph, app, DataPickerTool::Display, this, SIGNAL(statusText(const QString&)));
-    d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("cursor_xpm"), -1, -1));
-
-	connect(d_picker_tool, SIGNAL(selected(QwtPlotCurve*,int)), this, SLOT(selectPeak(QwtPlotCurve*,int)));
-	d_graph->plotWidget()->canvas()->grabMouse();
-
-	emit statusText(tr("Move cursor and click to select a point and double-click/press 'Enter' to set the position of a peak!"));
+MultiPeakFitTool::MultiPeakFitTool(Graph *graph, ApplicationWindow *app,
+                                   MultiPeakFit::PeakProfile profile,
+                                   int num_peaks, const QObject *status_target,
+                                   const char *status_slot)
+    : PlotToolInterface(graph), d_profile(profile), d_num_peaks(num_peaks) {
+  d_selected_peaks = 0;
+  d_curve = 0;
+
+  d_fit = new MultiPeakFit(app, d_graph, d_profile, d_num_peaks);
+  d_fit->enablePeakCurves(app->generatePeakCurves);
+  d_fit->setPeakCurvesColor(app->peakCurvesColor);
+  d_fit->generateFunction(app->generateUniformFitPoints, app->fitPoints);
+
+  if (status_target)
+    connect(this, SIGNAL(statusText(const QString &)), status_target,
+            status_slot);
+  d_picker_tool = new DataPickerTool(d_graph, app, DataPickerTool::Display,
+                                     this, SIGNAL(statusText(const QString &)));
+  d_graph->plotWidget()->canvas()->setCursor(
+      QCursor(getQPixmap("cursor_xpm"), -1, -1));
+
+  connect(d_picker_tool, SIGNAL(selected(QwtPlotCurve *, int)), this,
+          SLOT(selectPeak(QwtPlotCurve *, int)));
+  d_graph->plotWidget()->canvas()->grabMouse();
+
+  emit statusText(
+      tr("Move cursor and click to select a point and double-click/press "
+         "'Enter' to set the position of a peak!"));
 }
 
-MultiPeakFitTool::~MultiPeakFitTool()
-{
-	if (d_picker_tool)
-		delete d_picker_tool;
-	if (d_fit)
-		delete d_fit;
+MultiPeakFitTool::~MultiPeakFitTool() {
+  if (d_picker_tool)
+    delete d_picker_tool;
+  if (d_fit)
+    delete d_fit;
 }
 
-void MultiPeakFitTool::selectPeak(QwtPlotCurve *curve, int point_index)
-{
-	// TODO: warn user
-	if (!curve || (d_curve && d_curve != curve))
-		return;
-	d_curve = curve;
-
-	d_fit->setInitialGuess(3*d_selected_peaks, curve->y(point_index));
-	d_fit->setInitialGuess(3*d_selected_peaks+1, curve->x(point_index));
-
-	QwtPlotMarker *m = new QwtPlotMarker();
-	m->setLineStyle(QwtPlotMarker::VLine);
-	m->setLinePen(QPen(Qt::green, 2, Qt::DashLine));
-	m->setXValue(curve->x(point_index));
-	d_graph->plotWidget()->insertMarker(m);
-	d_graph->plotWidget()->replot();
-
-	d_selected_peaks++;
-	if (d_selected_peaks == d_num_peaks)
-		finalize();
-	else
-		emit statusText(
-				tr("Peak %1 selected! Click to select a point and double-click/press 'Enter' to set the position of the next peak!")
-				.arg(QString::number(d_selected_peaks)));
+void MultiPeakFitTool::selectPeak(QwtPlotCurve *curve, int point_index) {
+  // TODO: warn user
+  if (!curve || (d_curve && d_curve != curve))
+    return;
+  d_curve = curve;
+
+  d_fit->setInitialGuess(3 * d_selected_peaks, curve->y(point_index));
+  d_fit->setInitialGuess(3 * d_selected_peaks + 1, curve->x(point_index));
+
+  QwtPlotMarker *m = new QwtPlotMarker();
+  m->setLineStyle(QwtPlotMarker::VLine);
+  m->setLinePen(QPen(Qt::green, 2, Qt::DashLine));
+  m->setXValue(curve->x(point_index));
+  d_graph->plotWidget()->insertMarker(m);
+  d_graph->plotWidget()->replot();
+
+  d_selected_peaks++;
+  if (d_selected_peaks == d_num_peaks)
+    finalize();
+  else
+    emit statusText(tr("Peak %1 selected! Click to select a point and "
+                       "double-click/press 'Enter' to set the position of the "
+                       "next peak!").arg(QString::number(d_selected_peaks)));
 }
 
-void MultiPeakFitTool::finalize()
-{
-	delete d_picker_tool; d_picker_tool = NULL;
-	d_graph->plotWidget()->canvas()->releaseMouse();
-
-	if (d_fit->setDataFromCurve(d_curve->title().text())){
-		QApplication::setOverrideCursor(Qt::WaitCursor);
-
-		double *y = d_fit->y();
-		int n = d_fit->dataSize();
-
-		size_t imin, imax;
-		gsl_stats_minmax_index(&imin, &imax, y, 1, n);
-		QVarLengthArray<double> temp(n);//double temp[n];
-		for (int i = 0; i < n; i++)
-			temp[i] = fabs(y[i]);
-		size_t imax_temp = gsl_stats_max_index(temp.data(), 1, n);//size_t imax_temp = gsl_stats_max_index(temp, 1, n);
-        double offset = 0.0;
-		if (imax_temp == imax)
-			offset = y[imin];
-		else
-            offset = y[imax];
-        d_fit->setInitialGuess(3*d_selected_peaks, offset);
-
-		double w = 2*gsl_stats_sd(d_fit->x(), 1, n)/(double)d_selected_peaks;
-		for (int i = 0; i < d_selected_peaks; i++){
-		    int aux = 3*i;
-			d_fit->setInitialGuess(aux + 2, w);
-			double yc = d_fit->initialGuess(aux);
-			if (d_profile == MultiPeakFit::Lorentz)
-                d_fit->setInitialGuess(aux, (yc - offset)*M_PI_2*w);
-            else
-                d_fit->setInitialGuess(aux, (yc - offset)*sqrt(M_PI_2)*w);
-		}
-
-		d_fit->fit();
-		delete d_fit; d_fit = NULL;
-		QApplication::restoreOverrideCursor();
-	}
-
-	//remove peak line markers
-	QList<int>mrks = d_graph->plotWidget()->markerKeys();
-	int n=(int)mrks.count();
-	for (int i=0; i<d_num_peaks; i++)
-		d_graph->plotWidget()->removeMarker(mrks[n-i-1]);
-
-	d_graph->plotWidget()->replot();
-    if (d_graph->activeTool() && d_graph->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector){
-        (static_cast<RangeSelectorTool *>(d_graph->activeTool()))->setEnabled();
-    } else
-        d_graph->plotWidget()->canvas()->unsetCursor();
-    delete this;
+void MultiPeakFitTool::finalize() {
+  delete d_picker_tool;
+  d_picker_tool = NULL;
+  d_graph->plotWidget()->canvas()->releaseMouse();
+
+  if (d_fit->setDataFromCurve(d_curve->title().text())) {
+    QApplication::setOverrideCursor(Qt::WaitCursor);
+
+    double *y = d_fit->y();
+    int n = d_fit->dataSize();
+
+    size_t imin, imax;
+    gsl_stats_minmax_index(&imin, &imax, y, 1, n);
+    QVarLengthArray<double> temp(n); // double temp[n];
+    for (int i = 0; i < n; i++)
+      temp[i] = fabs(y[i]);
+    size_t imax_temp = gsl_stats_max_index(
+        temp.data(), 1,
+        n); // size_t imax_temp = gsl_stats_max_index(temp, 1, n);
+    double offset = 0.0;
+    if (imax_temp == imax)
+      offset = y[imin];
+    else
+      offset = y[imax];
+    d_fit->setInitialGuess(3 * d_selected_peaks, offset);
+
+    double w = 2 * gsl_stats_sd(d_fit->x(), 1, n) / (double)d_selected_peaks;
+    for (int i = 0; i < d_selected_peaks; i++) {
+      int aux = 3 * i;
+      d_fit->setInitialGuess(aux + 2, w);
+      double yc = d_fit->initialGuess(aux);
+      if (d_profile == MultiPeakFit::Lorentz)
+        d_fit->setInitialGuess(aux, (yc - offset) * M_PI_2 * w);
+      else
+        d_fit->setInitialGuess(aux, (yc - offset) * sqrt(M_PI_2) * w);
+    }
+
+    d_fit->fit();
+    delete d_fit;
+    d_fit = NULL;
+    QApplication::restoreOverrideCursor();
+  }
+
+  // remove peak line markers
+  QList<int> mrks = d_graph->plotWidget()->markerKeys();
+  int n = (int)mrks.count();
+  for (int i = 0; i < d_num_peaks; i++)
+    d_graph->plotWidget()->removeMarker(mrks[n - i - 1]);
+
+  d_graph->plotWidget()->replot();
+  if (d_graph->activeTool() &&
+      d_graph->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector) {
+    (static_cast<RangeSelectorTool *>(d_graph->activeTool()))->setEnabled();
+  } else
+    d_graph->plotWidget()->canvas()->unsetCursor();
+  delete this;
 }
diff --git a/MantidPlot/src/MultiPeakFitTool.h b/MantidPlot/src/MultiPeakFitTool.h
index 300acc75a40e8cc7540fd7f17eddb7f502dda09f..62241d98ffc0d3b572892c05c40f9170663bdf1a 100644
--- a/MantidPlot/src/MultiPeakFitTool.h
+++ b/MantidPlot/src/MultiPeakFitTool.h
@@ -39,38 +39,42 @@ class QwtPlotCurve;
 
 /** Plot tool for doing multi-peak fitting.
  *
- * This class can be seen as a user-interface wrapper around MultiPeakFit, providing functionality for visually
+ * This class can be seen as a user-interface wrapper around MultiPeakFit,
+ *providing functionality for visually
  * selecting estimated peak positions and finally executing the fit.
  *
- * Maybe some other parts of the multi-peak fitting process (namely, specifying the number of peaks and optionally
+ * Maybe some other parts of the multi-peak fitting process (namely, specifying
+ *the number of peaks and optionally
  * the peak profile) could be moved here as well.
  */
-class MultiPeakFitTool : public QObject, public PlotToolInterface
-{
-	Q_OBJECT
-	public:
-		MultiPeakFitTool(Graph *graph, ApplicationWindow *app, MultiPeakFit::PeakProfile profile, int num_peaks, const QObject *status_target, const char *status_slot);
-                ~MultiPeakFitTool() override;
+class MultiPeakFitTool : public QObject, public PlotToolInterface {
+  Q_OBJECT
+public:
+  MultiPeakFitTool(Graph *graph, ApplicationWindow *app,
+                   MultiPeakFit::PeakProfile profile, int num_peaks,
+                   const QObject *status_target, const char *status_slot);
+  ~MultiPeakFitTool() override;
 
-                int rtti() const override {
-                  return PlotToolInterface::Rtti_MultiPeakFitTool;
-                };
-        signals:
-		/** Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
-	protected slots:
-		void selectPeak(QwtPlotCurve *curve, int point_index);
-	private:
-		void finalize();
-		MultiPeakFit::PeakProfile d_profile;
-		int d_num_peaks, d_selected_peaks;
-		DataPickerTool *d_picker_tool;
-		MultiPeakFit *d_fit;
-		QwtPlotCurve *d_curve;
+  int rtti() const override {
+    return PlotToolInterface::Rtti_MultiPeakFitTool;
+  };
+signals:
+  /** Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
+protected slots:
+  void selectPeak(QwtPlotCurve *curve, int point_index);
+
+private:
+  void finalize();
+  MultiPeakFit::PeakProfile d_profile;
+  int d_num_peaks, d_selected_peaks;
+  DataPickerTool *d_picker_tool;
+  MultiPeakFit *d_fit;
+  QwtPlotCurve *d_curve;
 };
 
 #endif // ifndef MULTI_PEAK_FIT_TOOL
-
diff --git a/MantidPlot/src/MultiTabScriptInterpreter.cpp b/MantidPlot/src/MultiTabScriptInterpreter.cpp
index 7ff51f12fffc3f07e3b756e05f7560c1088af86a..f994bc7e4d437e5e335f2b378d2fb59d040115c1 100644
--- a/MantidPlot/src/MultiTabScriptInterpreter.cpp
+++ b/MantidPlot/src/MultiTabScriptInterpreter.cpp
@@ -487,7 +487,7 @@ void MultiTabScriptInterpreter::spacesToTabs() { m_current->spacesToTabs(); }
 void MultiTabScriptInterpreter::showSelectFont() {
   // Would prefer to use QFontDialog but only interested in font family
 
-  QDialog *selectFont =new QDialog(this, Qt::Dialog);
+  QDialog *selectFont = new QDialog(this, Qt::Dialog);
   selectFont->setModal(false);
   selectFont->setWindowTitle("Configure Tab Whitespace");
 
diff --git a/MantidPlot/src/MyParser.cpp b/MantidPlot/src/MyParser.cpp
index cbccf8be57789d34a489109c1541557d2571b2eb..0aff7228a68c4abe7f7186e1333fa3c9b0fb6289 100644
--- a/MantidPlot/src/MyParser.cpp
+++ b/MantidPlot/src/MyParser.cpp
@@ -2,10 +2,11 @@
     File                 : MyParser.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Parser class based on muParser
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -27,170 +28,208 @@
  *                                                                         *
  ***************************************************************************/
 #ifdef _WIN32
-#pragma warning(disable: 4251)
+#pragma warning(disable : 4251)
 #endif
 
 #include "MyParser.h"
 
-MyParser::MyParser()
-:Parser()
-{
-DefineConst("pi", M_PI);
-DefineConst("Pi", M_PI);
-DefineConst("PI", M_PI);
+MyParser::MyParser() : Parser() {
+  DefineConst("pi", M_PI);
+  DefineConst("Pi", M_PI);
+  DefineConst("PI", M_PI);
 
-DefineFun("bessel_j0", bessel_J0);
-DefineFun("bessel_j1", bessel_J1);
-DefineFun("bessel_jn", bessel_Jn);
-DefineFun("bessel_y0", bessel_Y0);
-DefineFun("bessel_y1", bessel_Y1);
-DefineFun("bessel_yn", bessel_Yn);
-DefineFun("beta", beta);
-DefineFun("erf", erf);
-DefineFun("erfc", erfc);
-DefineFun("erfz", erfz);
-DefineFun("erfq", erfq);
-DefineFun("gamma", gamma);
-DefineFun("gammaln", gammaln);
-DefineFun("hazard", hazard);
+  DefineFun("bessel_j0", bessel_J0);
+  DefineFun("bessel_j1", bessel_J1);
+  DefineFun("bessel_jn", bessel_Jn);
+  DefineFun("bessel_y0", bessel_Y0);
+  DefineFun("bessel_y1", bessel_Y1);
+  DefineFun("bessel_yn", bessel_Yn);
+  DefineFun("beta", beta);
+  DefineFun("erf", erf);
+  DefineFun("erfc", erfc);
+  DefineFun("erfz", erfz);
+  DefineFun("erfq", erfq);
+  DefineFun("gamma", gamma);
+  DefineFun("gammaln", gammaln);
+  DefineFun("hazard", hazard);
 }
 
-QStringList MyParser::functionsList()
-{
-QStringList l;
-l << "abs()" << "acos()" << "acosh()" << "asin()" << "asinh()" << "atan()";
-l << "atanh()" << "avg(,)" << "bessel_j0()" << "bessel_j1()" << "bessel_jn(,)";
-l << "bessel_y0()" << "bessel_y1()" << "bessel_yn(,)" << "beta(,)";
-l << "cos()" << "cosh()" << "erf()" << "erfc()" << "erfz()" << "erfq()";
-l << "exp()" << "gamma()" << "gammaln()" << "hazard()";
-l << "if( , , )" << "ln()" << "log()" << "log2()" << "min()" << "max()";
-l << "rint()" << "sign()" << "sin()" << "sinh()" << "sqrt()" << "tan()" << "tanh()";
-return l;
+QStringList MyParser::functionsList() {
+  QStringList l;
+  l << "abs()"
+    << "acos()"
+    << "acosh()"
+    << "asin()"
+    << "asinh()"
+    << "atan()";
+  l << "atanh()"
+    << "avg(,)"
+    << "bessel_j0()"
+    << "bessel_j1()"
+    << "bessel_jn(,)";
+  l << "bessel_y0()"
+    << "bessel_y1()"
+    << "bessel_yn(,)"
+    << "beta(,)";
+  l << "cos()"
+    << "cosh()"
+    << "erf()"
+    << "erfc()"
+    << "erfz()"
+    << "erfq()";
+  l << "exp()"
+    << "gamma()"
+    << "gammaln()"
+    << "hazard()";
+  l << "if( , , )"
+    << "ln()"
+    << "log()"
+    << "log2()"
+    << "min()"
+    << "max()";
+  l << "rint()"
+    << "sign()"
+    << "sin()"
+    << "sinh()"
+    << "sqrt()"
+    << "tan()"
+    << "tanh()";
+  return l;
 }
 
-QString MyParser::explainFunction(int index)
-{
-QString blabla;
-switch (index)
-	{
-case 0:
-	blabla="abs(x):\n Absolute value of x.";
-break;
+QString MyParser::explainFunction(int index) {
+  QString blabla;
+  switch (index) {
+  case 0:
+    blabla = "abs(x):\n Absolute value of x.";
+    break;
 
-case 1:
-	blabla="acos(x):\n Inverse cos function.";
-break;
+  case 1:
+    blabla = "acos(x):\n Inverse cos function.";
+    break;
 
-case 2:
-	blabla="acosh(x):\n Hyperbolic inverse cos function.";
-break;
+  case 2:
+    blabla = "acosh(x):\n Hyperbolic inverse cos function.";
+    break;
 
-case 3:
-	blabla="asin(x):\n Inverse sin function.";
-break;
+  case 3:
+    blabla = "asin(x):\n Inverse sin function.";
+    break;
 
-case 4:
-	blabla="asinh(x):\n Hyperbolic inverse sin function.";
-break;
-case 5:
-	blabla="atan(x):\n Inverse tan function.";
-break;
-case 6:
-	blabla="atanh(x):\n  Hyperbolic inverse tan function.";
-break;
-case 7:
-	blabla="avg(x,y,...):\n  Mean value of all arguments.";
-break;
-case 8:
-	blabla="bessel_j0(x):\n  Regular cylindrical Bessel function of zeroth order, J_0(x).";
-break;
-case 9:
-	blabla="bessel_j1(x):\n  Regular cylindrical Bessel function of first order, J_1(x).";
-break;
-case 10:
-	blabla="bessel_j1(double x, int n):\n Regular cylindrical Bessel function of order n, J_n(x).";
-break;
-case 11:
-	blabla="bessel_y0(x):\n Irregular cylindrical Bessel function of zeroth order, Y_0(x), for x>0.";
-break;
-case 12:
-	blabla="bessel_y1(x):\n Irregular cylindrical Bessel function of first order, Y_1(x), for x>0.";
-break;
-case 13:
-	blabla="bessel_yn(double x, int n):\n Irregular cylindrical Bessel function of order n, Y_n(x), for x>0.";
-break;
-case 14:
-	blabla="beta (a,b):\n Computes the Beta Function, B(a,b) = Gamma(a)*Gamma(b)/Gamma(a+b) for a > 0, b > 0.";
-break;
-case 15:
-	blabla="cos (x):\n Calculate cosine.";
-break;
-case 16:
-	blabla="cosh(x):\n Hyperbolic cos function.";
-break;
-case 17:
-	blabla="erf(x):\n  The error function.";
-break;
-case 18:
-	blabla="erfc(x):\n Complementary error function erfc(x) = 1 - erf(x).";
-break;
-case 19:
-	blabla="erfz(x):\n The Gaussian probability density function Z(x).";
-break;
-case 20:
-	blabla="erfq(x):\n The upper tail of the Gaussian probability function Q(x).";
-break;
-case 21:
-	blabla="exp(x):\n Exponential function: e raised to the power of x.";
-break;
-case 22:
-	blabla="gamma(x):\n Computes the Gamma function, subject to x not being a negative integer.";
-break;
-case 23:
-	blabla="gammaln(x):\n Computes the logarithm of the Gamma function, subject to x not a being negative integer. For x<0, log(|Gamma(x)|) is returned.";
-break;
-case 24:
-	blabla="hazard(x):\n Computes the hazard function for the normal distribution h(x) = erfz(x)/erfq(x).";
-break;
-case 25:
-	blabla="if(e1, e2, e3):	if e1 then e2 else e3.";
-break;
-case 26:
-	blabla="ln(x):\n Calculate natural logarithm.";
-break;
-case 27:
-	blabla="log(x):\n Calculate decimal logarithm.";
-break;
-case 28:
-	blabla="log2(x):\n Calculate 	logarithm to the base 2.";
-break;
-case 29:
-	blabla="min(x,y,...):\n Calculate minimum of all arguments.";
-break;
-case 30:
-	blabla="max(x,y,...):\n Calculate maximum of all arguments.";
-break;
-case 31:
-	blabla="rint(x):\n Round to nearest integer.";
-break;
-case 32:
-	blabla="sign(x):\n Sign function: -1 if x<0; 1 if x>0.";
-break;
-case 33:
-	blabla="sin(x):\n Calculate sine.";
-break;
-case 34:
-	blabla="sinh(x):\n Hyperbolic sin function.";
-break;
-case 35:
-	blabla="sqrt(x):\n Square root function.";
-break;
-case 36:
-	blabla="tan(x):\n Calculate tangent function.";
-break;
-case 37:
-	blabla="tanh(x):\n Hyperbolic tan function.";
-break;
-	}
-return blabla;
+  case 4:
+    blabla = "asinh(x):\n Hyperbolic inverse sin function.";
+    break;
+  case 5:
+    blabla = "atan(x):\n Inverse tan function.";
+    break;
+  case 6:
+    blabla = "atanh(x):\n  Hyperbolic inverse tan function.";
+    break;
+  case 7:
+    blabla = "avg(x,y,...):\n  Mean value of all arguments.";
+    break;
+  case 8:
+    blabla = "bessel_j0(x):\n  Regular cylindrical Bessel function of zeroth "
+             "order, J_0(x).";
+    break;
+  case 9:
+    blabla = "bessel_j1(x):\n  Regular cylindrical Bessel function of first "
+             "order, J_1(x).";
+    break;
+  case 10:
+    blabla = "bessel_j1(double x, int n):\n Regular cylindrical Bessel "
+             "function of order n, J_n(x).";
+    break;
+  case 11:
+    blabla = "bessel_y0(x):\n Irregular cylindrical Bessel function of zeroth "
+             "order, Y_0(x), for x>0.";
+    break;
+  case 12:
+    blabla = "bessel_y1(x):\n Irregular cylindrical Bessel function of first "
+             "order, Y_1(x), for x>0.";
+    break;
+  case 13:
+    blabla = "bessel_yn(double x, int n):\n Irregular cylindrical Bessel "
+             "function of order n, Y_n(x), for x>0.";
+    break;
+  case 14:
+    blabla = "beta (a,b):\n Computes the Beta Function, B(a,b) = "
+             "Gamma(a)*Gamma(b)/Gamma(a+b) for a > 0, b > 0.";
+    break;
+  case 15:
+    blabla = "cos (x):\n Calculate cosine.";
+    break;
+  case 16:
+    blabla = "cosh(x):\n Hyperbolic cos function.";
+    break;
+  case 17:
+    blabla = "erf(x):\n  The error function.";
+    break;
+  case 18:
+    blabla = "erfc(x):\n Complementary error function erfc(x) = 1 - erf(x).";
+    break;
+  case 19:
+    blabla = "erfz(x):\n The Gaussian probability density function Z(x).";
+    break;
+  case 20:
+    blabla =
+        "erfq(x):\n The upper tail of the Gaussian probability function Q(x).";
+    break;
+  case 21:
+    blabla = "exp(x):\n Exponential function: e raised to the power of x.";
+    break;
+  case 22:
+    blabla = "gamma(x):\n Computes the Gamma function, subject to x not being "
+             "a negative integer.";
+    break;
+  case 23:
+    blabla = "gammaln(x):\n Computes the logarithm of the Gamma function, "
+             "subject to x not a being negative integer. For x<0, "
+             "log(|Gamma(x)|) is returned.";
+    break;
+  case 24:
+    blabla = "hazard(x):\n Computes the hazard function for the normal "
+             "distribution h(x) = erfz(x)/erfq(x).";
+    break;
+  case 25:
+    blabla = "if(e1, e2, e3):	if e1 then e2 else e3.";
+    break;
+  case 26:
+    blabla = "ln(x):\n Calculate natural logarithm.";
+    break;
+  case 27:
+    blabla = "log(x):\n Calculate decimal logarithm.";
+    break;
+  case 28:
+    blabla = "log2(x):\n Calculate 	logarithm to the base 2.";
+    break;
+  case 29:
+    blabla = "min(x,y,...):\n Calculate minimum of all arguments.";
+    break;
+  case 30:
+    blabla = "max(x,y,...):\n Calculate maximum of all arguments.";
+    break;
+  case 31:
+    blabla = "rint(x):\n Round to nearest integer.";
+    break;
+  case 32:
+    blabla = "sign(x):\n Sign function: -1 if x<0; 1 if x>0.";
+    break;
+  case 33:
+    blabla = "sin(x):\n Calculate sine.";
+    break;
+  case 34:
+    blabla = "sinh(x):\n Hyperbolic sin function.";
+    break;
+  case 35:
+    blabla = "sqrt(x):\n Square root function.";
+    break;
+  case 36:
+    blabla = "tan(x):\n Calculate tangent function.";
+    break;
+  case 37:
+    blabla = "tanh(x):\n Hyperbolic tan function.";
+    break;
+  }
+  return blabla;
 }
diff --git a/MantidPlot/src/MyParser.h b/MantidPlot/src/MyParser.h
index b874d7514afc4db904a1782b8254f72d8265dc9a..c31bbf803c9b6904ad6daa834f2515bb56c3be4e 100644
--- a/MantidPlot/src/MyParser.h
+++ b/MantidPlot/src/MyParser.h
@@ -41,78 +41,42 @@ using namespace mu;
  *
  * \section future Future Plans
  * Eliminate in favour of Script/ScriptingEnv.
- * This will allow you to use e.g. Python's global variables and functions everywhere.
- * Before this happens, a cleaner and more generic solution for accessing the current ScriptingEnv
- * should be implemented (maybe by making it a property of Project; see ApplicationWindow).
+ * This will allow you to use e.g. Python's global variables and functions
+ *everywhere.
+ * Before this happens, a cleaner and more generic solution for accessing the
+ *current ScriptingEnv
+ * should be implemented (maybe by making it a property of Project; see
+ *ApplicationWindow).
  */
-class MyParser : public Parser
-{
+class MyParser : public Parser {
 public:
-	MyParser();
+  MyParser();
 
-	static QStringList functionsList();
-	static QString explainFunction(int index);
+  static QStringList functionsList();
+  static QString explainFunction(int index);
 
-	static double bessel_J0(double x)
-		{
-		return gsl_sf_bessel_J0 (x);
-		}
+  static double bessel_J0(double x) { return gsl_sf_bessel_J0(x); }
 
-	static double bessel_J1(double x)
-		{
-		return gsl_sf_bessel_J1 (x);
-		}
+  static double bessel_J1(double x) { return gsl_sf_bessel_J1(x); }
 
-	static double bessel_Jn(double x, double n)
-		{
-		return gsl_sf_bessel_Jn ((int)n, x);
-		}
+  static double bessel_Jn(double x, double n) {
+    return gsl_sf_bessel_Jn((int)n, x);
+  }
 
-	static double bessel_Y0(double x)
-		{
-		return gsl_sf_bessel_Y0 (x);
-		}
+  static double bessel_Y0(double x) { return gsl_sf_bessel_Y0(x); }
 
-	static double bessel_Y1(double x)
-		{
-		return gsl_sf_bessel_Y1 (x);
-		}
-	static double bessel_Yn(double x, double n)
-		{
-		return gsl_sf_bessel_Yn ((int)n, x);
-		}
-	static double beta(double a, double b)
-		{
-		return gsl_sf_beta (a, b);
-		}
-	static double erf(double x)
-		{
-		return gsl_sf_erf (x);
-		}
-	static double erfc(double x)
-		{
-		return gsl_sf_erfc (x);
-		}
-	static double erfz(double x)
-		{
-		return gsl_sf_erf_Z (x);
-		}
-	static double erfq(double x)
-		{
-		return gsl_sf_erf_Q (x);
-		}
-	static double gamma(double x)
-		{
-		return gsl_sf_gamma (x);
-		}
-	static double gammaln(double x)
-		{
-		return gsl_sf_lngamma (x);
-		}
-	static double hazard(double x)
-		{
-		return gsl_sf_hazard (x);
-		}
+  static double bessel_Y1(double x) { return gsl_sf_bessel_Y1(x); }
+  static double bessel_Yn(double x, double n) {
+    return gsl_sf_bessel_Yn((int)n, x);
+  }
+  static double beta(double a, double b) { return gsl_sf_beta(a, b); }
+  static double erf(double x) { return gsl_sf_erf(x); }
+  static double erfc(double x) { return gsl_sf_erfc(x); }
+  static double erfz(double x) { return gsl_sf_erf_Z(x); }
+  static double erfq(double x) { return gsl_sf_erf_Q(x); }
+  static double gamma(double x) { return gsl_sf_gamma(x); }
+  static double gammaln(double x) { return gsl_sf_lngamma(x); }
+  static double hazard(double x) { return gsl_sf_hazard(x); }
 };
 
 #endif
diff --git a/MantidPlot/src/NonLinearFit.cpp b/MantidPlot/src/NonLinearFit.cpp
index 80095a6bef5603d357bdea6669d0e135079eefe9..163c867ba1a207f49675725ccaf60d146ffc6b66 100644
--- a/MantidPlot/src/NonLinearFit.cpp
+++ b/MantidPlot/src/NonLinearFit.cpp
@@ -33,143 +33,145 @@
 #include <QMessageBox>
 
 NonLinearFit::NonLinearFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+    : Fit(parent, g) {
+  init();
 }
 
-NonLinearFit::NonLinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+NonLinearFit::NonLinearFit(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-NonLinearFit::NonLinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+NonLinearFit::NonLinearFit(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-NonLinearFit::NonLinearFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+NonLinearFit::NonLinearFit(ApplicationWindow *parent, Table *t,
+                           const QString &xCol, const QString &yCol,
+                           int startRow, int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void NonLinearFit::init()
-{
-    if (objectName().isEmpty())
-        setObjectName(tr("NonLinear"));
-	d_formula = QString::null;
-	d_f = user_f;
-	d_df = user_df;
-	d_fdf = user_fdf; 
-	d_fsimplex = user_d;
-	d_explanation = tr("Non-linear Fit");
-    d_fit_type = User;
+void NonLinearFit::init() {
+  if (objectName().isEmpty())
+    setObjectName(tr("NonLinear"));
+  d_formula = QString::null;
+  d_f = user_f;
+  d_df = user_df;
+  d_fdf = user_fdf;
+  d_fsimplex = user_d;
+  d_explanation = tr("Non-linear Fit");
+  d_fit_type = User;
 }
 
-void NonLinearFit::setFormula(const QString& s)
-{
-	if (s.isEmpty()){
-		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),  tr("MantidPlot - Input function error"),
-				tr("Please enter a valid non-empty expression! Operation aborted!"));
-		d_init_err = true;
-		return;
-	}
-
-	if (!d_p){
-		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Fit Error"),
-				tr("There are no parameters specified for this fit operation. Please define a list of parameters first!"));
-		d_init_err = true;
-		return;
-	}
-
-	if (d_formula == s)
-		return;
-
-	try
-	{
-		double *param = new double[d_p];
-		MyParser parser;
-		double xvar;
-		parser.DefineVar("x", &xvar);
-		for (int k=0; k<(int)d_p; k++){
-			param[k]=gsl_vector_get(d_param_init, k);
-			parser.DefineVar(d_param_names[k].toAscii().constData(), &param[k]);
-		}
-		parser.SetExpr(s.toAscii().constData());
-		parser.Eval() ;
-		delete[] param;
-	}
-	catch(mu::ParserError &e)
-	{
-		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),  tr("MantidPlot - Input function error"), QString::fromStdString(e.GetMsg()));
-		d_init_err = true;
-		return;
-	}
-
-	d_init_err = false;
-	d_formula = s;
+void NonLinearFit::setFormula(const QString &s) {
+  if (s.isEmpty()) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Input function error"),
+        tr("Please enter a valid non-empty expression! Operation aborted!"));
+    d_init_err = true;
+    return;
+  }
+
+  if (!d_p) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Fit Error"),
+        tr("There are no parameters specified for this fit operation. Please "
+           "define a list of parameters first!"));
+    d_init_err = true;
+    return;
+  }
+
+  if (d_formula == s)
+    return;
+
+  try {
+    double *param = new double[d_p];
+    MyParser parser;
+    double xvar;
+    parser.DefineVar("x", &xvar);
+    for (int k = 0; k < (int)d_p; k++) {
+      param[k] = gsl_vector_get(d_param_init, k);
+      parser.DefineVar(d_param_names[k].toAscii().constData(), &param[k]);
+    }
+    parser.SetExpr(s.toAscii().constData());
+    parser.Eval();
+    delete[] param;
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot - Input function error"),
+                          QString::fromStdString(e.GetMsg()));
+    d_init_err = true;
+    return;
+  }
+
+  d_init_err = false;
+  d_formula = s;
 }
 
-void NonLinearFit::setParametersList(const QStringList& lst)
-{
-	if (lst.count() < 1){
-		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Fit Error"),
-				tr("You must provide a list containing at least one parameter for this type of fit. Operation aborted!"));
-		d_init_err = true;
-		return;
-	}
-
-	d_init_err = false;
-	d_param_names = lst;
-
-	if (d_p > 0)
-		freeWorkspace();
-	d_p = (int)lst.count();
-	initWorkspace(d_p);
-
-	for (int i=0; i<d_p; i++)
-		d_param_explain << "";
+void NonLinearFit::setParametersList(const QStringList &lst) {
+  if (lst.count() < 1) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Fit Error"),
+        tr("You must provide a list containing at least one parameter for this "
+           "type of fit. Operation aborted!"));
+    d_init_err = true;
+    return;
+  }
+
+  d_init_err = false;
+  d_param_names = lst;
+
+  if (d_p > 0)
+    freeWorkspace();
+  d_p = (int)lst.count();
+  initWorkspace(d_p);
+
+  for (int i = 0; i < d_p; i++)
+    d_param_explain << "";
 }
 
-void NonLinearFit::calculateFitCurveData(double *X, double *Y)
-{
-	MyParser parser;
-	for (int i=0; i<d_p; i++)
-		parser.DefineVar(d_param_names[i].toAscii().constData(), &d_results[i]);
-
-	double x;
-	parser.DefineVar("x", &x);
-	parser.SetExpr(d_formula.toAscii().constData());
-
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    x = X0 + i*step;
-			X[i] = x;
-			Y[i] = parser.Eval();
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    x = d_x[i];
-			X[i] = x;
-			Y[i] = parser.Eval();
-		}
-	}
+void NonLinearFit::calculateFitCurveData(double *X, double *Y) {
+  MyParser parser;
+  for (int i = 0; i < d_p; i++)
+    parser.DefineVar(d_param_names[i].toAscii().constData(), &d_results[i]);
+
+  double x;
+  parser.DefineVar("x", &x);
+  parser.SetExpr(d_formula.toAscii().constData());
+
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      x = X0 + i * step;
+      X[i] = x;
+      Y[i] = parser.Eval();
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      x = d_x[i];
+      X[i] = x;
+      Y[i] = parser.Eval();
+    }
+  }
 }
 
-double NonLinearFit::eval(double *par, double x)
-{
-	MyParser parser;
-	for (int i=0; i<d_p; i++)
-		parser.DefineVar(d_param_names[i].toAscii().constData(), &par[i]);
-	parser.DefineVar("x", &x);
-	parser.SetExpr(d_formula.toAscii().constData());
-    return parser.Eval();
+double NonLinearFit::eval(double *par, double x) {
+  MyParser parser;
+  for (int i = 0; i < d_p; i++)
+    parser.DefineVar(d_param_names[i].toAscii().constData(), &par[i]);
+  parser.DefineVar("x", &x);
+  parser.SetExpr(d_formula.toAscii().constData());
+  return parser.Eval();
 }
diff --git a/MantidPlot/src/NonLinearFit.h b/MantidPlot/src/NonLinearFit.h
index 5f56a182ccd709e1c200c4c75151aa7eb40fb87b..848aa75b19cb4304faad75aac7ea20536c9b9c04 100644
--- a/MantidPlot/src/NonLinearFit.h
+++ b/MantidPlot/src/NonLinearFit.h
@@ -2,7 +2,8 @@
     File                 : NonLinearFit.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : NonLinearFit class
 
@@ -31,23 +32,24 @@
 
 #include "Fit.h"
 
-class NonLinearFit : public Fit
-{
-	Q_OBJECT
+class NonLinearFit : public Fit {
+  Q_OBJECT
 
-	public:
-		NonLinearFit(ApplicationWindow *parent, Graph *g);
-		NonLinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		NonLinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		NonLinearFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
+public:
+  NonLinearFit(ApplicationWindow *parent, Graph *g);
+  NonLinearFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  NonLinearFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+               double start, double end);
+  NonLinearFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+               const QString &yCol, int startRow = 1, int endRow = -1);
 
-                double eval(double *par, double x) override;
+  double eval(double *par, double x) override;
 
-                void setParametersList(const QStringList &lst) override;
-                void setFormula(const QString &s) override;
+  void setParametersList(const QStringList &lst) override;
+  void setFormula(const QString &s) override;
 
-        private:
-          void calculateFitCurveData(double *X, double *Y) override;
-                void init();
+private:
+  void calculateFitCurveData(double *X, double *Y) override;
+  void init();
 };
 #endif
diff --git a/MantidPlot/src/Note.cpp b/MantidPlot/src/Note.cpp
index 0a3763432c8fb69693a23a0815e6aa18ff903a83..8fdd66c5517f0ddedff7a27c77b429914dfd0d64 100644
--- a/MantidPlot/src/Note.cpp
+++ b/MantidPlot/src/Note.cpp
@@ -4,7 +4,7 @@
     --------------------------------------------------------------------
     Copyright            : (C) 2006 by Ion Vasilief,
                            Tilman Hoener zu Siederdissen,
-					  Knut Franke
+                                          Knut Franke
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net,
                            knut.franke*gmx.de
     Description          : Notes window class
@@ -44,14 +44,13 @@
 #include "MantidKernel/ConfigService.h"
 #include "MantidQtAPI/FileDialogHandler.h"
 
-Note::Note(const QString& label, QWidget* parent, const QString& name, Qt::WFlags f)
-  : MdiSubWindow(parent, label, name, f)
-{
+Note::Note(const QString &label, QWidget *parent, const QString &name,
+           Qt::WFlags f)
+    : MdiSubWindow(parent, label, name, f) {
   init();
 }
 
-void Note::init()
-{
+void Note::init() {
   te = new QTextEdit(this);
   te->setObjectName(name());
   setWidget(te);
@@ -60,32 +59,25 @@ void Note::init()
   connect(te, SIGNAL(textChanged()), this, SLOT(modifiedNote()));
 }
 
-void Note::setName(const QString& name)
-{
+void Note::setName(const QString &name) {
   te->setObjectName(name);
   MdiSubWindow::setName(name);
 }
 
-void Note::modifiedNote()
-{
-  emit modifiedWindow(this);
-}
+void Note::modifiedNote() { emit modifiedWindow(this); }
 
-void Note::print()
-{
+void Note::print() {
   QsciPrinter printer(QPrinter::HighResolution);
   printer.setColorMode(QPrinter::GrayScale);
   printer.setOutputFormat(QPrinter::PostScriptFormat);
   QPrintDialog printDialog(&printer);
   printDialog.setWindowTitle("MantidPlot - Print Note");
-  if (printDialog.exec() == QDialog::Accepted)
-  {
+  if (printDialog.exec() == QDialog::Accepted) {
     te->document()->print(&printer);
   }
 }
 
-void Note::exportPDF(const QString& fileName)
-{
+void Note::exportPDF(const QString &fileName) {
   QPrinter printer;
   printer.setColorMode(QPrinter::GrayScale);
   printer.setCreator("MantidPlot");
@@ -94,27 +86,27 @@ void Note::exportPDF(const QString& fileName)
   te->document()->print(&printer);
 }
 
-QString Note::exportASCII(const QString &filename)
-{
+QString Note::exportASCII(const QString &filename) {
   QString filter;
   filter += tr("Text") + " (*.txt *.TXT);;";
-  filter += tr("All Files")+" (*)";
+  filter += tr("All Files") + " (*)";
 
   QString selectedFilter;
   QString fn;
-  if (filename.isEmpty())
-  {
-    QString dir(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory").c_str());
-    fn = MantidQt::API::FileDialogHandler::getSaveFileName(this, tr("Save Text to File"),dir,filter, &selectedFilter);
-  }
-  else
+  if (filename.isEmpty()) {
+    QString dir(Mantid::Kernel::ConfigService::Instance()
+                    .getString("defaultsave.directory")
+                    .c_str());
+    fn = MantidQt::API::FileDialogHandler::getSaveFileName(
+        this, tr("Save Text to File"), dir, filter, &selectedFilter);
+  } else
     fn = filename;
 
-  if ( !fn.isEmpty() ){
+  if (!fn.isEmpty()) {
     QFileInfo fi(fn);
 
     QString baseName = fi.fileName();
-    if (!baseName.contains(".")){
+    if (!baseName.contains(".")) {
       if (selectedFilter.contains(".txt"))
         fn.append(".txt");
       else if (selectedFilter.contains(".py"))
@@ -122,13 +114,15 @@ QString Note::exportASCII(const QString &filename)
     }
 
     QFile f(fn);
-    if (!f.open(IO_WriteOnly)){
-      QMessageBox::critical(0, tr("MantidPlot - File Save Error"),
-            tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that you have the right to write to this location!").arg(fn));
+    if (!f.open(IO_WriteOnly)) {
+      QMessageBox::critical(
+          0, tr("MantidPlot - File Save Error"),
+          tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that "
+             "you have the right to write to this location!").arg(fn));
       return QString::null;
     }
 
-    QTextStream t( &f );
+    QTextStream t(&f);
     t.setCodec(QTextCodec::codecForName("UTF-8"));
     t << text();
     f.close();
@@ -136,19 +130,19 @@ QString Note::exportASCII(const QString &filename)
   return fn;
 }
 
-void Note::loadFromProject(const std::string& lines, ApplicationWindow* app, const int fileVersion)
-{
+void Note::loadFromProject(const std::string &lines, ApplicationWindow *app,
+                           const int fileVersion) {
   Q_UNUSED(fileVersion);
 
   std::vector<std::string> lineVec;
   boost::split(lineVec, lines, boost::is_any_of("\n"));
 
-  if(lineVec.size() < 1)
+  if (lineVec.size() < 1)
     return;
 
   std::vector<std::string> firstLineVec;
   boost::split(firstLineVec, lineVec[0], boost::is_any_of("\t"));
-  if(firstLineVec.size() < 2)
+  if (firstLineVec.size() < 2)
     return;
 
   const QString name = QString::fromUtf8(firstLineVec[0].c_str());
@@ -160,27 +154,24 @@ void Note::loadFromProject(const std::string& lines, ApplicationWindow* app, con
 
   TSVSerialiser tsv(lines);
 
-  if(tsv.hasLine("geometry"))
-  {
-    const QString geometry = QString::fromUtf8(tsv.lineAsString("geometry").c_str());
+  if (tsv.hasLine("geometry")) {
+    const QString geometry =
+        QString::fromUtf8(tsv.lineAsString("geometry").c_str());
     app->restoreWindowGeometry(app, this, geometry);
   }
 
-  if(tsv.selectLine("WindowLabel"))
-  {
+  if (tsv.selectLine("WindowLabel")) {
     setWindowLabel(QString::fromUtf8(tsv.asString(1).c_str()));
     setCaptionPolicy((MdiSubWindow::CaptionPolicy)tsv.asInt(2));
   }
 
-  if(tsv.hasSection("content"))
-  {
+  if (tsv.hasSection("content")) {
     const std::string content = tsv.sections("content").front();
     te->setText(QString::fromUtf8(content.c_str()));
   }
 }
 
-std::string Note::saveToProject(ApplicationWindow* app)
-{
+std::string Note::saveToProject(ApplicationWindow *app) {
   TSVSerialiser tsv;
   tsv.writeRaw("<note>");
   tsv.writeLine(name().toStdString()) << birthDate();
diff --git a/MantidPlot/src/Note.h b/MantidPlot/src/Note.h
index f40e1b9856592048b6a9b8b5bfae5010aaf59099..0c476ca05a97d0149926126fd9b448598868adcf 100644
--- a/MantidPlot/src/Note.h
+++ b/MantidPlot/src/Note.h
@@ -2,7 +2,8 @@
     File                 : Note.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Notes window class
 
@@ -40,22 +41,22 @@ class ApplicationWindow;
  * \section future Future Plans
  * - Search and replace
  */
-class Note: public MdiSubWindow, public Mantid::IProjectSerialisable
-{
+class Note : public MdiSubWindow, public Mantid::IProjectSerialisable {
   Q_OBJECT
 
 public:
-  Note(const QString& label, QWidget* parent, const QString& name = QString(), Qt::WFlags f=0);
+  Note(const QString &label, QWidget *parent, const QString &name = QString(),
+       Qt::WFlags f = 0);
   ~Note() override{};
 
   void loadFromProject(const std::string &lines, ApplicationWindow *app,
                        const int fileVersion) override;
   std::string saveToProject(ApplicationWindow *app) override;
 
-  void setName(const QString& name);
+  void setName(const QString &name);
 
 public slots:
-  QTextEdit* editor(){return te;};
+  QTextEdit *editor() { return te; };
   void modifiedNote();
 
   // QTextEdit methods
@@ -64,7 +65,7 @@ public slots:
 
   void print() override;
   void exportPDF(const QString &fileName) override;
-  QString exportASCII(const QString &filename=QString::null);
+  QString exportASCII(const QString &filename = QString::null);
 
 private:
   void init();
diff --git a/MantidPlot/src/OpenProjectDialog.cpp b/MantidPlot/src/OpenProjectDialog.cpp
index deef7d8bf3e0a06d3d31ebdf2522afdf7a9faeb6..3b0ac10fc427e83617ba257db08f95b0c650fedc 100644
--- a/MantidPlot/src/OpenProjectDialog.cpp
+++ b/MantidPlot/src/OpenProjectDialog.cpp
@@ -34,66 +34,64 @@
 #include <QLabel>
 #include <QPushButton>
 
-OpenProjectDialog::OpenProjectDialog(QWidget *parent, bool extended, Qt::WFlags flags)
-	: ExtensibleFileDialog(parent, extended, flags)
-{
-	//setCaption(tr("QtiPlot - Open Project"));
-	setWindowTitle(tr("MantidPlot - Open Project"));
-	setFileMode(ExistingFile);
-	QStringList filters;
-	//filters << tr("QtiPlot project") + " (*.qti)"
-		//<< tr("Compressed QtiPlot project") + " (*.qti.gz)"
-	filters << tr("MantidPlot project") + " (*.mantid)"
-		<< tr("Compressed MantidPlot project") + " (*.mantid.gz)"
-		<< tr("Origin project") + " (*.opj *.OPJ)"
-		<< tr("Origin matrix") + " (*.ogm *.OGM)"
-		<< tr("Origin worksheet") + " (*.ogw *.OGW)"
-		<< tr("Origin graph") + " (*.ogg *.OGG)"
-		<< tr("Backup files") + " (*.mantid~)"
-		//<< tr("Python Source") + " (*.py *.PY)"
-		<< tr("All files") + " (*)";
-	setFilters(filters);
+OpenProjectDialog::OpenProjectDialog(QWidget *parent, bool extended,
+                                     Qt::WFlags flags)
+    : ExtensibleFileDialog(parent, extended, flags) {
+  // setCaption(tr("QtiPlot - Open Project"));
+  setWindowTitle(tr("MantidPlot - Open Project"));
+  setFileMode(ExistingFile);
+  QStringList filters;
+  // filters << tr("QtiPlot project") + " (*.qti)"
+  //<< tr("Compressed QtiPlot project") + " (*.qti.gz)"
+  filters << tr("MantidPlot project") + " (*.mantid)"
+          << tr("Compressed MantidPlot project") + " (*.mantid.gz)"
+          << tr("Origin project") + " (*.opj *.OPJ)"
+          << tr("Origin matrix") + " (*.ogm *.OGM)"
+          << tr("Origin worksheet") + " (*.ogw *.OGW)"
+          << tr("Origin graph") + " (*.ogg *.OGG)"
+          << tr("Backup files") + " (*.mantid~)"
+          //<< tr("Python Source") + " (*.py *.PY)"
+          << tr("All files") + " (*)";
+  setFilters(filters);
 
-	QWidget *advanced_options = new QWidget();
-	QHBoxLayout *advanced_layout = new QHBoxLayout();
-	advanced_options->setLayout(advanced_layout);
-	advanced_layout->addWidget(new QLabel(tr("Open As")));
-	d_open_mode = new QComboBox();
-	// Important: Keep this is sync with enum OpenMode.
-	d_open_mode->addItem(tr("New Project Window"));
-	d_open_mode->addItem(tr("New Folder"));
-	advanced_layout->addWidget(d_open_mode);
-	setExtensionWidget(advanced_options);
+  QWidget *advanced_options = new QWidget();
+  QHBoxLayout *advanced_layout = new QHBoxLayout();
+  advanced_options->setLayout(advanced_layout);
+  advanced_layout->addWidget(new QLabel(tr("Open As")));
+  d_open_mode = new QComboBox();
+  // Important: Keep this is sync with enum OpenMode.
+  d_open_mode->addItem(tr("New Project Window"));
+  d_open_mode->addItem(tr("New Folder"));
+  advanced_layout->addWidget(d_open_mode);
+  setExtensionWidget(advanced_options);
 
 #if QT_VERSION >= 0x040300
-	connect(this, SIGNAL(filterSelected ( const QString & )),
-			this, SLOT(updateAdvancedOptions ( const QString & )));
+  connect(this, SIGNAL(filterSelected(const QString &)), this,
+          SLOT(updateAdvancedOptions(const QString &)));
 #else
-	QList<QComboBox*> combo_boxes = findChildren<QComboBox*>();
-	if (combo_boxes.size() >= 2)
-		connect(combo_boxes[1], SIGNAL(currentIndexChanged ( const QString & )),
-				this, SLOT(updateAdvancedOptions ( const QString & )));
+  QList<QComboBox *> combo_boxes = findChildren<QComboBox *>();
+  if (combo_boxes.size() >= 2)
+    connect(combo_boxes[1], SIGNAL(currentIndexChanged(const QString &)), this,
+            SLOT(updateAdvancedOptions(const QString &)));
 #endif
-	updateAdvancedOptions(selectedFilter());
+  updateAdvancedOptions(selectedFilter());
 }
 
-void OpenProjectDialog::updateAdvancedOptions (const QString & filter)
-{
-	if (filter.contains("*.ogm") || filter.contains("*.ogw")) {
-		d_extension_toggle->setChecked(false);
-		d_extension_toggle->setEnabled(false);
-		return;
-	}
-	d_extension_toggle->setEnabled(true);
+void OpenProjectDialog::updateAdvancedOptions(const QString &filter) {
+  if (filter.contains("*.ogm") || filter.contains("*.ogw")) {
+    d_extension_toggle->setChecked(false);
+    d_extension_toggle->setEnabled(false);
+    return;
+  }
+  d_extension_toggle->setEnabled(true);
 }
 
-void OpenProjectDialog::closeEvent(QCloseEvent* e)
-{
-	if (isExtendable()){
-		ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-		if (app)
-			app->d_extended_open_dialog = this->isExtended();
-	}
+void OpenProjectDialog::closeEvent(QCloseEvent *e) {
+  if (isExtendable()) {
+    ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+    if (app)
+      app->d_extended_open_dialog = this->isExtended();
+  }
 
-	e->accept();
+  e->accept();
 }
diff --git a/MantidPlot/src/OpenProjectDialog.h b/MantidPlot/src/OpenProjectDialog.h
index d43c2f43e83f42d3da463f482552476c5c4b9b03..3b1f03f926ce0fb2818bd87aab38bc196247333a 100644
--- a/MantidPlot/src/OpenProjectDialog.h
+++ b/MantidPlot/src/OpenProjectDialog.h
@@ -33,21 +33,21 @@
 
 #include <QComboBox>
 
-class OpenProjectDialog : public ExtensibleFileDialog
-{
-	Q_OBJECT
-	public:
-		enum OpenMode { NewProject, NewFolder };
-		OpenProjectDialog(QWidget *parent=0, bool extended = true, Qt::WFlags flags=0);
-		OpenMode openMode() const { return (OpenMode) d_open_mode->currentIndex(); }
-
-	private:
-		QComboBox *d_open_mode;
-
-    protected slots:
-      void closeEvent(QCloseEvent *) override;
-        //! Update which options are visible and enabled based on the output format.
-        void updateAdvancedOptions (const QString &filter);
+class OpenProjectDialog : public ExtensibleFileDialog {
+  Q_OBJECT
+public:
+  enum OpenMode { NewProject, NewFolder };
+  OpenProjectDialog(QWidget *parent = 0, bool extended = true,
+                    Qt::WFlags flags = 0);
+  OpenMode openMode() const { return (OpenMode)d_open_mode->currentIndex(); }
+
+private:
+  QComboBox *d_open_mode;
+
+protected slots:
+  void closeEvent(QCloseEvent *) override;
+  //! Update which options are visible and enabled based on the output format.
+  void updateAdvancedOptions(const QString &filter);
 };
 
 #endif // ifndef OPEN_PROJECT_DIALOG_H
diff --git a/MantidPlot/src/Plot.cpp b/MantidPlot/src/Plot.cpp
index d58e6205359e06264c42cb99d25564866bf6cfa1..899bc4f393caace9133851e4040526d272dad6b6 100644
--- a/MantidPlot/src/Plot.cpp
+++ b/MantidPlot/src/Plot.cpp
@@ -2,7 +2,8 @@
     File                 : Plot.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plot window class
 
@@ -49,440 +50,431 @@
 
 #include <limits>
 
-Detacher::Detacher(QwtPlotItem *plotItem) : m_plotItem(plotItem)
-{
-}
+Detacher::Detacher(QwtPlotItem *plotItem) : m_plotItem(plotItem) {}
 
-Detacher::~Detacher()
-{
-  delete m_plotItem;
-}
+Detacher::~Detacher() { delete m_plotItem; }
 
 Plot::Plot(int width, int height, QWidget *parent, const char *)
-: QwtPlot(parent)
-{
-	setAutoReplot (false);
-
-	marker_key = 0;
-	curve_key = 0;
-
-	minTickLength = 5;
-	majTickLength = 9;
-
-	setGeometry(QRect(0, 0, width, height));
-	setAxisTitle(QwtPlot::yLeft, tr("Y Axis Title"));
-	setAxisTitle(QwtPlot::xBottom, tr("X Axis Title"));
-	//due to the plot layout updates, we must always have a non empty title
-	setAxisTitle(QwtPlot::yRight, tr(" "));
-	setAxisTitle(QwtPlot::xTop, tr(" "));
-
-	// grid
-	d_grid = new Grid();
-	d_grid->attach(this);
-
-	//custom scale
-	for (int i= 0; i<QwtPlot::axisCnt; i++) {
-		QwtScaleWidget *scale = (QwtScaleWidget *) axisWidget(i);
-		if (scale) {
-			scale->setMargin(0);
-
-			//the axis title color must be initialized...
-			QwtText title = scale->title();
-			title.setColor(Qt::black);
-			scale->setTitle(title);
-
-            //...same for axis color
-            QPalette pal = scale->palette();
-            pal.setColor(QPalette::Foreground, QColor(Qt::black));
-            scale->setPalette(pal);
-
-			ScaleDraw *sd = new ScaleDraw(this);
-			sd->setTickLength(QwtScaleDiv::MinorTick, minTickLength);
-			sd->setTickLength(QwtScaleDiv::MediumTick, minTickLength);
-			sd->setTickLength(QwtScaleDiv::MajorTick, majTickLength);
-
-			setAxisScaleDraw (i, sd);
-			setAxisScaleEngine (i, new ScaleEngine());
-		}
-	}
-
-	QwtPlotLayout *pLayout = plotLayout();
-	pLayout->setCanvasMargin(0);
-	pLayout->setAlignCanvasToScales (true);
-
-	QwtPlotCanvas* plCanvas = canvas();
-	plCanvas->setFocusPolicy(Qt::StrongFocus);
-	plCanvas->setFocusIndicator(QwtPlotCanvas::ItemFocusIndicator);
-	//plCanvas->setFocus();
-	plCanvas->setFrameShadow(QwtPlot::Plain);
-	plCanvas->setCursor(Qt::arrowCursor);
-	plCanvas->setLineWidth(1);
-	plCanvas->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
-	plCanvas->setPaintAttribute(QwtPlotCanvas::PaintPacked, true);
+    : QwtPlot(parent) {
+  setAutoReplot(false);
+
+  marker_key = 0;
+  curve_key = 0;
+
+  minTickLength = 5;
+  majTickLength = 9;
+
+  setGeometry(QRect(0, 0, width, height));
+  setAxisTitle(QwtPlot::yLeft, tr("Y Axis Title"));
+  setAxisTitle(QwtPlot::xBottom, tr("X Axis Title"));
+  // due to the plot layout updates, we must always have a non empty title
+  setAxisTitle(QwtPlot::yRight, tr(" "));
+  setAxisTitle(QwtPlot::xTop, tr(" "));
+
+  // grid
+  d_grid = new Grid();
+  d_grid->attach(this);
+
+  // custom scale
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    QwtScaleWidget *scale = (QwtScaleWidget *)axisWidget(i);
+    if (scale) {
+      scale->setMargin(0);
+
+      // the axis title color must be initialized...
+      QwtText title = scale->title();
+      title.setColor(Qt::black);
+      scale->setTitle(title);
+
+      //...same for axis color
+      QPalette pal = scale->palette();
+      pal.setColor(QPalette::Foreground, QColor(Qt::black));
+      scale->setPalette(pal);
+
+      ScaleDraw *sd = new ScaleDraw(this);
+      sd->setTickLength(QwtScaleDiv::MinorTick, minTickLength);
+      sd->setTickLength(QwtScaleDiv::MediumTick, minTickLength);
+      sd->setTickLength(QwtScaleDiv::MajorTick, majTickLength);
+
+      setAxisScaleDraw(i, sd);
+      setAxisScaleEngine(i, new ScaleEngine());
+    }
+  }
+
+  QwtPlotLayout *pLayout = plotLayout();
+  pLayout->setCanvasMargin(0);
+  pLayout->setAlignCanvasToScales(true);
+
+  QwtPlotCanvas *plCanvas = canvas();
+  plCanvas->setFocusPolicy(Qt::StrongFocus);
+  plCanvas->setFocusIndicator(QwtPlotCanvas::ItemFocusIndicator);
+  // plCanvas->setFocus();
+  plCanvas->setFrameShadow(QwtPlot::Plain);
+  plCanvas->setCursor(Qt::arrowCursor);
+  plCanvas->setLineWidth(1);
+  plCanvas->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
+  plCanvas->setPaintAttribute(QwtPlotCanvas::PaintPacked, true);
   plCanvas->installEventFilter(this);
 
-    QColor background = QColor(Qt::white);
-    background.setAlpha(255);
+  QColor background = QColor(Qt::white);
+  background.setAlpha(255);
 
-	QPalette palette;
-    palette.setColor(QPalette::Window, background);
-    setPalette(palette);
+  QPalette palette;
+  palette.setColor(QPalette::Window, background);
+  setPalette(palette);
 
-	setCanvasBackground (background);
-	setFocusPolicy(Qt::StrongFocus);
-	//setFocusProxy(plCanvas);
-	setFrameShape(QFrame::Box);
-	setLineWidth(0);
+  setCanvasBackground(background);
+  setFocusPolicy(Qt::StrongFocus);
+  // setFocusProxy(plCanvas);
+  setFrameShape(QFrame::Box);
+  setLineWidth(0);
 }
 
-QColor Plot::frameColor()
-{
-	return palette().color(QPalette::Active, QPalette::Foreground);
+QColor Plot::frameColor() {
+  return palette().color(QPalette::Active, QPalette::Foreground);
 }
 
-void Plot::printFrame(QPainter *painter, const QRect &rect) const
-{
-	painter->save();
+void Plot::printFrame(QPainter *painter, const QRect &rect) const {
+  painter->save();
 
-	int lw = lineWidth();
-	if (lw){
-		QColor color = palette().color(QPalette::Active, QPalette::Foreground);
-		painter->setPen (QPen(color, lw, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
-	} else
-		painter->setPen(QPen(Qt::NoPen));
+  int lw = lineWidth();
+  if (lw) {
+    QColor color = palette().color(QPalette::Active, QPalette::Foreground);
+    painter->setPen(
+        QPen(color, lw, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
+  } else
+    painter->setPen(QPen(Qt::NoPen));
 
-    painter->setBrush(paletteBackgroundColor());
-    QwtPainter::drawRect(painter, rect);
-	painter->restore();
+  painter->setBrush(paletteBackgroundColor());
+  QwtPainter::drawRect(painter, rect);
+  painter->restore();
 }
 
-void Plot::printCanvas(QPainter *painter, const QRect&, const QRect &canvasRect,
-   			 const QwtScaleMap map[axisCnt], const QwtPlotPrintFilter &pfilter) const
-{
-	painter->save();
-
-	const QwtPlotCanvas* plotCanvas = canvas();	
-	//commented it was clipping the top part of the graph
-	//QRect rect = canvasRect.adjusted(1, 1, -2, -2);
-	
-	QRect rect = canvasRect.adjusted(1, -1, -2, -1);
-	
-
-    QwtPainter::fillRect(painter, rect, canvasBackground());
-	painter->setClipping(true);
-	QwtPainter::setClipRect(painter, rect);
-
-    drawItems(painter, canvasRect, map, pfilter);
-    painter->restore();
-
-    painter->save();
-	int lw = plotCanvas->lineWidth();
-	if(lw > 0){
-		QColor color = plotCanvas->palette().color(QPalette::Active, QColorGroup::Foreground);
-		painter->setPen (QPen(color, lw, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
-		QwtPainter::drawRect(painter, canvasRect.adjusted(0, 0, -1, -1));
-	}
-    painter->restore();
-
-	// print texts
-	QObjectList lst = children();
-	foreach(QObject *o, lst){
-		if (o->inherits("LegendWidget") && !(static_cast<QWidget *>(o))->isHidden())
-        	(static_cast<LegendWidget *>(o))->print(painter, map);
-	}
+void Plot::printCanvas(QPainter *painter, const QRect &,
+                       const QRect &canvasRect, const QwtScaleMap map[axisCnt],
+                       const QwtPlotPrintFilter &pfilter) const {
+  painter->save();
+
+  const QwtPlotCanvas *plotCanvas = canvas();
+  // commented it was clipping the top part of the graph
+  // QRect rect = canvasRect.adjusted(1, 1, -2, -2);
+
+  QRect rect = canvasRect.adjusted(1, -1, -2, -1);
+
+  QwtPainter::fillRect(painter, rect, canvasBackground());
+  painter->setClipping(true);
+  QwtPainter::setClipRect(painter, rect);
+
+  drawItems(painter, canvasRect, map, pfilter);
+  painter->restore();
+
+  painter->save();
+  int lw = plotCanvas->lineWidth();
+  if (lw > 0) {
+    QColor color =
+        plotCanvas->palette().color(QPalette::Active, QColorGroup::Foreground);
+    painter->setPen(
+        QPen(color, lw, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
+    QwtPainter::drawRect(painter, canvasRect.adjusted(0, 0, -1, -1));
+  }
+  painter->restore();
+
+  // print texts
+  QObjectList lst = children();
+  foreach (QObject *o, lst) {
+    if (o->inherits("LegendWidget") && !(static_cast<QWidget *>(o))->isHidden())
+      (static_cast<LegendWidget *>(o))->print(painter, map);
+  }
 }
 
-void Plot::drawItems (QPainter *painter, const QRect &rect,
-			const QwtScaleMap map[axisCnt], const QwtPlotPrintFilter &pfilter) const
-{
-    painter->save();
-    painter->setRenderHint(QPainter::Antialiasing);
-    for (int i=0; i<QwtPlot::axisCnt; i++){
-		if (!axisEnabled(i))
-			continue;
-        drawBreak(painter, rect, map[i], i);
+void Plot::drawItems(QPainter *painter, const QRect &rect,
+                     const QwtScaleMap map[axisCnt],
+                     const QwtPlotPrintFilter &pfilter) const {
+  painter->save();
+  painter->setRenderHint(QPainter::Antialiasing);
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    if (!axisEnabled(i))
+      continue;
+    drawBreak(painter, rect, map[i], i);
+  }
+  painter->restore();
+
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    if (!axisEnabled(i))
+      continue;
+
+    const ScaleEngine *sc_engine =
+        static_cast<const ScaleEngine *>(axisScaleEngine(i));
+    /*const QwtScaleEngine *qwtsc_engine=axisScaleEngine(i);
+    const ScaleEngine *sc_engine =dynamic_cast<const
+    ScaleEngine*>(qwtsc_engine);
+    if(sc_engine!=NULL)
+    {	*/
+    if (!sc_engine->hasBreak())
+      continue;
+
+    QwtScaleMap m = map[i];
+    int lb = m.transform(sc_engine->axisBreakLeft());
+    int rb = m.transform(sc_engine->axisBreakRight());
+    int start = lb, end = rb;
+    if (sc_engine->testAttribute(QwtScaleEngine::Inverted)) {
+      end = lb;
+      start = rb;
     }
-    painter->restore();
-
-    for (int i=0; i<QwtPlot::axisCnt; i++){
-		if (!axisEnabled(i))
-			continue;
-
-		const ScaleEngine *sc_engine = static_cast<const ScaleEngine *>(axisScaleEngine(i));
-		/*const QwtScaleEngine *qwtsc_engine=axisScaleEngine(i);
-		const ScaleEngine *sc_engine =dynamic_cast<const ScaleEngine*>(qwtsc_engine);
-		if(sc_engine!=NULL)
-		{	*/
-		if (!sc_engine->hasBreak())
-			continue;
-	
-		QwtScaleMap m = map[i];
-		int lb = m.transform(sc_engine->axisBreakLeft());
-		int rb = m.transform(sc_engine->axisBreakRight());
-		int start = lb, end = rb;
-		if (sc_engine->testAttribute(QwtScaleEngine::Inverted)){
-			end = lb;
-			start = rb;
-		}
-		QRegion cr(rect);
-		if (i == QwtPlot::xBottom || i == QwtPlot::xTop)
-			painter->setClipRegion(cr.subtracted(QRegion(start, rect.y(), abs(end - start), rect.height())), Qt::IntersectClip);
-		else if (i == QwtPlot::yLeft || i == QwtPlot::yRight)
-			painter->setClipRegion(cr.subtracted(QRegion(rect.x(), end, rect.width(), abs(end - start))), Qt::IntersectClip);
-		//}
-	}
-
-	QwtPlot::drawItems(painter, rect, map, pfilter);
-
-	for (int i=0; i<QwtPlot::axisCnt; i++){
-		if (!axisEnabled(i))
-			continue;
-
-		const ScaleDraw *sd = static_cast<const ScaleDraw *>(axisScaleDraw (i));
-		int majorTicksType = sd->majorTicksStyle();
-		int minorTicksType = sd->minorTicksStyle();
-
-		bool min = (minorTicksType == ScaleDraw::In || minorTicksType == ScaleDraw::Both);
-		bool maj = (majorTicksType == ScaleDraw::In || majorTicksType == ScaleDraw::Both);
-
-		if (min || maj)
-			drawInwardTicks(painter, rect, map[i], i, min, maj);
-	}
+    QRegion cr(rect);
+    if (i == QwtPlot::xBottom || i == QwtPlot::xTop)
+      painter->setClipRegion(
+          cr.subtracted(
+              QRegion(start, rect.y(), abs(end - start), rect.height())),
+          Qt::IntersectClip);
+    else if (i == QwtPlot::yLeft || i == QwtPlot::yRight)
+      painter->setClipRegion(
+          cr.subtracted(QRegion(rect.x(), end, rect.width(), abs(end - start))),
+          Qt::IntersectClip);
+    //}
+  }
+
+  QwtPlot::drawItems(painter, rect, map, pfilter);
+
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    if (!axisEnabled(i))
+      continue;
+
+    const ScaleDraw *sd = static_cast<const ScaleDraw *>(axisScaleDraw(i));
+    int majorTicksType = sd->majorTicksStyle();
+    int minorTicksType = sd->minorTicksStyle();
+
+    bool min =
+        (minorTicksType == ScaleDraw::In || minorTicksType == ScaleDraw::Both);
+    bool maj =
+        (majorTicksType == ScaleDraw::In || majorTicksType == ScaleDraw::Both);
+
+    if (min || maj)
+      drawInwardTicks(painter, rect, map[i], i, min, maj);
+  }
 }
 
 void Plot::drawInwardTicks(QPainter *painter, const QRect &rect,
-		const QwtScaleMap &map, int axis, bool min, bool maj) const
-{
-	int x1=rect.left();
-	int x2=rect.right();
-	int y1=rect.top();
-	int y2=rect.bottom();
-
-	QPalette pal=axisWidget(axis)->palette();
-	QColor color=pal.color(QPalette::Active, QColorGroup::Foreground);
-
-	painter->save();
-	painter->setPen(QPen(color, axesLinewidth(), Qt::SolidLine));
-
-	const QwtScaleDiv *scDiv=(const QwtScaleDiv *)axisScaleDiv(axis);
-	const QwtValueList minTickList = scDiv->ticks(QwtScaleDiv::MinorTick);
-	int minTicks = (int)minTickList.count();
-
-	const QwtValueList medTickList = scDiv->ticks(QwtScaleDiv::MediumTick);
-	int medTicks = (int)medTickList.count();
-
-	const QwtValueList majTickList = scDiv->ticks(QwtScaleDiv::MajorTick);
-	int majTicks = (int)majTickList.count();
-
-	int j, x, y, low,high;
-	switch (axis)
-	{
-		case QwtPlot::yLeft:
-			x=x1;
-			low=y1+majTickLength;
-			high=y2-majTickLength;
-			if (min){
-				for (j = 0; j < minTicks; j++){
-					y = map.transform(minTickList[j]);
-					if (y>low && y< high)
-						QwtPainter::drawLine(painter, x, y, x+minTickLength, y);
-				}
-				for (j = 0; j < medTicks; j++){
-					y = map.transform(medTickList[j]);
-					if (y>low && y< high)
-						QwtPainter::drawLine(painter, x, y, x+minTickLength, y);
-				}
-			}
-
-			if (maj){
-				for (j = 0; j < majTicks; j++){
-					y = map.transform(majTickList[j]);
-					if (y>low && y< high)
-						QwtPainter::drawLine(painter, x, y, x+majTickLength, y);
-				}
-			}
-			break;
-
-		case QwtPlot::yRight:
-			{
-				x=x2;
-				low=y1+majTickLength;
-				high=y2-majTickLength;
-				if (min){
-					for (j = 0; j < minTicks; j++){
-						y = map.transform(minTickList[j]);
-						if (y>low && y< high)
-							QwtPainter::drawLine(painter, x+1, y, x-minTickLength, y);
-					}
-					for (j = 0; j < medTicks; j++){
-						y = map.transform(medTickList[j]);
-						if (y>low && y< high)
-							QwtPainter::drawLine(painter, x+1, y, x-minTickLength, y);
-					}
-				}
-
-				if (maj){
-					for (j = 0; j <majTicks; j++){
-						y = map.transform(majTickList[j]);
-						if (y>low && y< high)
-							QwtPainter::drawLine(painter, x+1, y, x-majTickLength, y);
-					}
-				}
-			}
-			break;
-
-		case QwtPlot::xBottom:
-			y=y2;
-			low=x1+majTickLength;
-			high=x2-majTickLength;
-			if (min){
-				for (j = 0; j < minTicks; j++){
-					x = map.transform(minTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y+1, x, y-minTickLength);
-				}
-				for (j = 0; j < medTicks; j++){
-					x = map.transform(medTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y+1, x, y-minTickLength);
-				}
-			}
-
-			if (maj){
-				for (j = 0; j < majTicks; j++){
-					x = map.transform(majTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y+1, x, y-majTickLength);
-				}
-			}
-			break;
-
-		case QwtPlot::xTop:
-			y=y1;
-			low=x1+majTickLength;
-			high=x2-majTickLength;
-
-			if (min){
-				for (j = 0; j < minTicks; j++){
-					x = map.transform(minTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y, x, y + minTickLength);
-				}
-				for (j = 0; j < medTicks; j++){
-					x = map.transform(medTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y, x, y + minTickLength);
-				}
-			}
-
-			if (maj){
-				for (j = 0; j <majTicks; j++){
-					x = map.transform(majTickList[j]);
-					if (x>low && x<high)
-						QwtPainter::drawLine(painter, x, y, x, y + majTickLength);
-				}
-			}
-			break;
-	}
-	painter->restore();
-}
+                           const QwtScaleMap &map, int axis, bool min,
+                           bool maj) const {
+  int x1 = rect.left();
+  int x2 = rect.right();
+  int y1 = rect.top();
+  int y2 = rect.bottom();
+
+  QPalette pal = axisWidget(axis)->palette();
+  QColor color = pal.color(QPalette::Active, QColorGroup::Foreground);
+
+  painter->save();
+  painter->setPen(QPen(color, axesLinewidth(), Qt::SolidLine));
+
+  const QwtScaleDiv *scDiv = (const QwtScaleDiv *)axisScaleDiv(axis);
+  const QwtValueList minTickList = scDiv->ticks(QwtScaleDiv::MinorTick);
+  int minTicks = (int)minTickList.count();
+
+  const QwtValueList medTickList = scDiv->ticks(QwtScaleDiv::MediumTick);
+  int medTicks = (int)medTickList.count();
+
+  const QwtValueList majTickList = scDiv->ticks(QwtScaleDiv::MajorTick);
+  int majTicks = (int)majTickList.count();
+
+  int j, x, y, low, high;
+  switch (axis) {
+  case QwtPlot::yLeft:
+    x = x1;
+    low = y1 + majTickLength;
+    high = y2 - majTickLength;
+    if (min) {
+      for (j = 0; j < minTicks; j++) {
+        y = map.transform(minTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x, y, x + minTickLength, y);
+      }
+      for (j = 0; j < medTicks; j++) {
+        y = map.transform(medTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x, y, x + minTickLength, y);
+      }
+    }
 
-void Plot::drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map, int axis) const
-{	
-    const ScaleEngine *sc_engine = static_cast<const ScaleEngine *>(axisScaleEngine(axis));
-	/*const QwtScaleEngine *qwtsc_engine=axisScaleEngine(axis);
-	const ScaleEngine *sc_engine =dynamic_cast<const ScaleEngine*>(qwtsc_engine);
-	if(sc_engine!=NULL)
-	{*/	
-		if (!sc_engine->hasBreak() || !sc_engine->hasBreakDecoration())
-			return;
-
-		painter->save();
-
-		QColor color = axisWidget(axis)->palette().color(QPalette::Active, QColorGroup::Foreground);
-		painter->setPen(QPen(color, axesLinewidth(), Qt::SolidLine));
-
-		int left = map.transform(sc_engine->axisBreakLeft());
-		int right = map.transform(sc_engine->axisBreakRight());
-		int x, y;
-		int len = majTickLength;
-		switch (axis){
-		case QwtPlot::yLeft:
-			x = rect.left() - 1;
-			QwtPainter::drawLine(painter, x, left, x + len, left - len);
-			QwtPainter::drawLine(painter, x, right, x + len, right - len);
-			break;
-
-		case QwtPlot::yRight:
-			x = rect.right() + 1;
-			QwtPainter::drawLine(painter, x - len, left + len, x, left);
-			QwtPainter::drawLine(painter, x - len, right + len, x, right);
-			break;
-
-		case QwtPlot::xBottom:
-			y = rect.bottom() + 1;
-			QwtPainter::drawLine(painter, left, y, left + len, y - len);
-			QwtPainter::drawLine(painter, right, y, right + len, y - len);
-			break;
-
-		case QwtPlot::xTop:
-			y = rect.top() - 1;
-			QwtPainter::drawLine(painter, left - len, y + len, left, y);
-			QwtPainter::drawLine(painter, right - len, y + len, right, y);
-			break;
-		}
-		painter->restore();
-	//}
-}
+    if (maj) {
+      for (j = 0; j < majTicks; j++) {
+        y = map.transform(majTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x, y, x + majTickLength, y);
+      }
+    }
+    break;
+
+  case QwtPlot::yRight: {
+    x = x2;
+    low = y1 + majTickLength;
+    high = y2 - majTickLength;
+    if (min) {
+      for (j = 0; j < minTicks; j++) {
+        y = map.transform(minTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x + 1, y, x - minTickLength, y);
+      }
+      for (j = 0; j < medTicks; j++) {
+        y = map.transform(medTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x + 1, y, x - minTickLength, y);
+      }
+    }
 
-void Plot::setAxesLinewidth(int width)
-{
-	for (int i=0; i<QwtPlot::axisCnt; i++){
-		QwtScaleWidget *scale=(QwtScaleWidget*) this->axisWidget(i);
-		if (scale) {
-			scale->setPenWidth(width);
-			scale->repaint();
-		}
-	}
-}
+    if (maj) {
+      for (j = 0; j < majTicks; j++) {
+        y = map.transform(majTickList[j]);
+        if (y > low && y < high)
+          QwtPainter::drawLine(painter, x + 1, y, x - majTickLength, y);
+      }
+    }
+  } break;
+
+  case QwtPlot::xBottom:
+    y = y2;
+    low = x1 + majTickLength;
+    high = x2 - majTickLength;
+    if (min) {
+      for (j = 0; j < minTicks; j++) {
+        x = map.transform(minTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y + 1, x, y - minTickLength);
+      }
+      for (j = 0; j < medTicks; j++) {
+        x = map.transform(medTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y + 1, x, y - minTickLength);
+      }
+    }
 
-int Plot::axesLinewidth() const
-{
-	for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ ) {
-		const QwtScaleWidget *scale = this->axisWidget(axis);
-		if (scale)
-			return scale->penWidth();
-	}
-	return 0;
+    if (maj) {
+      for (j = 0; j < majTicks; j++) {
+        x = map.transform(majTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y + 1, x, y - majTickLength);
+      }
+    }
+    break;
+
+  case QwtPlot::xTop:
+    y = y1;
+    low = x1 + majTickLength;
+    high = x2 - majTickLength;
+
+    if (min) {
+      for (j = 0; j < minTicks; j++) {
+        x = map.transform(minTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y, x, y + minTickLength);
+      }
+      for (j = 0; j < medTicks; j++) {
+        x = map.transform(medTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y, x, y + minTickLength);
+      }
+    }
+
+    if (maj) {
+      for (j = 0; j < majTicks; j++) {
+        x = map.transform(majTickList[j]);
+        if (x > low && x < high)
+          QwtPainter::drawLine(painter, x, y, x, y + majTickLength);
+      }
+    }
+    break;
+  }
+  painter->restore();
+}
+
+void Plot::drawBreak(QPainter *painter, const QRect &rect,
+                     const QwtScaleMap &map, int axis) const {
+  const ScaleEngine *sc_engine =
+      static_cast<const ScaleEngine *>(axisScaleEngine(axis));
+  /*const QwtScaleEngine *qwtsc_engine=axisScaleEngine(axis);
+  const ScaleEngine *sc_engine =dynamic_cast<const ScaleEngine*>(qwtsc_engine);
+  if(sc_engine!=NULL)
+  {*/
+  if (!sc_engine->hasBreak() || !sc_engine->hasBreakDecoration())
+    return;
+
+  painter->save();
+
+  QColor color = axisWidget(axis)->palette().color(QPalette::Active,
+                                                   QColorGroup::Foreground);
+  painter->setPen(QPen(color, axesLinewidth(), Qt::SolidLine));
+
+  int left = map.transform(sc_engine->axisBreakLeft());
+  int right = map.transform(sc_engine->axisBreakRight());
+  int x, y;
+  int len = majTickLength;
+  switch (axis) {
+  case QwtPlot::yLeft:
+    x = rect.left() - 1;
+    QwtPainter::drawLine(painter, x, left, x + len, left - len);
+    QwtPainter::drawLine(painter, x, right, x + len, right - len);
+    break;
+
+  case QwtPlot::yRight:
+    x = rect.right() + 1;
+    QwtPainter::drawLine(painter, x - len, left + len, x, left);
+    QwtPainter::drawLine(painter, x - len, right + len, x, right);
+    break;
+
+  case QwtPlot::xBottom:
+    y = rect.bottom() + 1;
+    QwtPainter::drawLine(painter, left, y, left + len, y - len);
+    QwtPainter::drawLine(painter, right, y, right + len, y - len);
+    break;
+
+  case QwtPlot::xTop:
+    y = rect.top() - 1;
+    QwtPainter::drawLine(painter, left - len, y + len, left, y);
+    QwtPainter::drawLine(painter, right - len, y + len, right, y);
+    break;
+  }
+  painter->restore();
+  //}
 }
 
-int Plot::minorTickLength() const
-{
-	return minTickLength;
+void Plot::setAxesLinewidth(int width) {
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    QwtScaleWidget *scale = (QwtScaleWidget *)this->axisWidget(i);
+    if (scale) {
+      scale->setPenWidth(width);
+      scale->repaint();
+    }
+  }
 }
 
-int Plot::majorTickLength() const
-{
-	return majTickLength;
+int Plot::axesLinewidth() const {
+  for (int axis = 0; axis < QwtPlot::axisCnt; axis++) {
+    const QwtScaleWidget *scale = this->axisWidget(axis);
+    if (scale)
+      return scale->penWidth();
+  }
+  return 0;
 }
 
-void Plot::setTickLength (int minLength, int majLength)
-{
-	if (majTickLength == majLength &&
-			minTickLength == minLength)
-		return;
+int Plot::minorTickLength() const { return minTickLength; }
+
+int Plot::majorTickLength() const { return majTickLength; }
 
-	majTickLength = majLength;
-	minTickLength = minLength;
+void Plot::setTickLength(int minLength, int majLength) {
+  if (majTickLength == majLength && minTickLength == minLength)
+    return;
+
+  majTickLength = majLength;
+  minTickLength = minLength;
 }
 
-QwtPlotCurve* Plot::curve(int index)
-{
-    QwtPlotItem *it = d_curves.value(index);
-    if (it && it->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-        return static_cast<QwtPlotCurve*>(it);
-    else
-        return 0;
+QwtPlotCurve *Plot::curve(int index) {
+  QwtPlotItem *it = d_curves.value(index);
+  if (it && it->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
+    return static_cast<QwtPlotCurve *>(it);
+  else
+    return 0;
 }
 
 /**
@@ -491,43 +483,39 @@ QwtPlotCurve* Plot::curve(int index)
  * @param xpos :: x coordinate of a point on the canvas in pixels.
  * @param ypos :: y coordinate of a point on the canvas in pixels.
  * @param dist :: ?
- * @param point :: Output index of the nearest data point to the point with coordinates (xpos,ypos)
+ * @param point :: Output index of the nearest data point to the point with
+ * coordinates (xpos,ypos)
  */
-int Plot::closestCurve(int xpos, int ypos, int &dist, int &point)
-{
-	QwtScaleMap map[QwtPlot::axisCnt];
-	for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
-		map[axis] = canvasMap(axis);
+int Plot::closestCurve(int xpos, int ypos, int &dist, int &point) {
+  QwtScaleMap map[QwtPlot::axisCnt];
+  for (int axis = 0; axis < QwtPlot::axisCnt; axis++)
+    map[axis] = canvasMap(axis);
 
   double dmin = std::numeric_limits<double>::max();
-	int key = -1;
-	for (QMap<int, QwtPlotItem *>::iterator iter = d_curves.begin(); iter != d_curves.end(); ++iter )
-	{
-		QwtPlotItem *item = (QwtPlotItem *)iter.value();
-		if (!item)
-			continue;
-
-    if(item->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-    {
+  int key = -1;
+  for (QMap<int, QwtPlotItem *>::iterator iter = d_curves.begin();
+       iter != d_curves.end(); ++iter) {
+    QwtPlotItem *item = (QwtPlotItem *)iter.value();
+    if (!item)
+      continue;
+
+    if (item->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) {
       PlotCurve *c = static_cast<PlotCurve *>(item);
       DataCurve *dc = dynamic_cast<DataCurve *>(item);
-      if (dc)
-      {
+      if (dc) {
         if (c->type() != Graph::Function && dc->hasLabels() &&
-          dc->selectedLabels(QPoint(xpos, ypos))){
-            dist = 0;
-            return iter.key();
+            dc->selectedLabels(QPoint(xpos, ypos))) {
+          dist = 0;
+          return iter.key();
         } else
           dc->setLabelsSelected(false);
       }
 
-      for (int i=0; i<c->dataSize(); i++)
-      {
+      for (int i = 0; i < c->dataSize(); i++) {
         double cx = map[c->xAxis()].xTransform(c->x(i)) - double(xpos);
         double cy = map[c->yAxis()].xTransform(c->y(i)) - double(ypos);
         double f = qwtSqr(cx) + qwtSqr(cy);
-        if (f < dmin && c->type() != Graph::ErrorBars)
-        {
+        if (f < dmin && c->type() != Graph::ErrorBars) {
           dmin = f;
           key = iter.key();
           point = i;
@@ -535,133 +523,118 @@ int Plot::closestCurve(int xpos, int ypos, int &dist, int &point)
       }
     }
   }
-	dist = static_cast<int>(sqrt(dmin));
-	return key;
+  dist = static_cast<int>(sqrt(dmin));
+  return key;
 }
 
-void Plot::removeMarker(int index)
-{
-	QwtPlotMarker *m = d_markers[index];
-	if(!m)
-		return;
-	m->detach();
-	d_markers.remove (index);
+void Plot::removeMarker(int index) {
+  QwtPlotMarker *m = d_markers[index];
+  if (!m)
+    return;
+  m->detach();
+  d_markers.remove(index);
 }
 
-int Plot::insertMarker(QwtPlotMarker *m)
-{
-	marker_key++;
-	if (!d_markers.contains(marker_key))
-		d_markers.insert (marker_key, m);
-	m->setRenderHint(QwtPlotItem::RenderAntialiased, (static_cast<Graph *>(parent()))->antialiasing());
-	m->attach(((QwtPlot *)this));
-	return marker_key;
+int Plot::insertMarker(QwtPlotMarker *m) {
+  marker_key++;
+  if (!d_markers.contains(marker_key))
+    d_markers.insert(marker_key, m);
+  m->setRenderHint(QwtPlotItem::RenderAntialiased,
+                   (static_cast<Graph *>(parent()))->antialiasing());
+  m->attach(((QwtPlot *)this));
+  return marker_key;
 }
 
-int Plot::insertCurve(QwtPlotItem *c)
-{
-	curve_key++;
-	if (!d_curves.contains(curve_key))
-		d_curves.insert (curve_key, c);
-	if (c->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-		(static_cast<QwtPlotCurve *>(c))->setPaintAttribute(QwtPlotCurve::PaintFiltered);
-
-	c->setRenderHint(QwtPlotItem::RenderAntialiased, (static_cast<Graph *>(parent()))->antialiasing());
-	c->attach(this);
-	return curve_key;
-}
+int Plot::insertCurve(QwtPlotItem *c) {
+  curve_key++;
+  if (!d_curves.contains(curve_key))
+    d_curves.insert(curve_key, c);
+  if (c->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
+    (static_cast<QwtPlotCurve *>(c))
+        ->setPaintAttribute(QwtPlotCurve::PaintFiltered);
 
-void Plot::removeCurve(int index)
-{
-	QwtPlotItem *c = d_curves[index];
-  	if (!c)
-  		return;
-
-  	if (c->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
-  	{
-  		Spectrogram *sp = static_cast<Spectrogram *>(c);
-  	    QwtScaleWidget *colorAxis = axisWidget(sp->colorScaleAxis());
-  	    if (colorAxis)
-  	    	colorAxis->setColorBarEnabled(false);
-  	}
-
-	c->detach();
-	QwtPlotItem* p = d_curves.take (index);
-  // RNT: Making curve_key unique prevents clashes elsewhere
-	//--curve_key;
-	// MG: This is a rather crude but effective way of delaying the
-	// deletion of the curve objects. This is necessary because in
-	// a tight loop a curve may not have been completely removed 
-	// but the object has been deleted.
-	Detacher *detacher = new Detacher(p);
-	detacher->deleteLater();
+  c->setRenderHint(QwtPlotItem::RenderAntialiased,
+                   (static_cast<Graph *>(parent()))->antialiasing());
+  c->attach(this);
+  return curve_key;
 }
 
-QList<int> Plot::getMajorTicksType()
-{
-	QList<int> majorTicksType;
-	for (int axis=0; axis<QwtPlot::axisCnt; axis++)
-	{
-		if (axisEnabled(axis))
-		{
-			ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw (axis));
-			majorTicksType << sd->majorTicksStyle();
-		}
-		else
-			majorTicksType << ScaleDraw::Out;
-	}
-	return majorTicksType;
+void Plot::removeCurve(int index) {
+  QwtPlotItem *c = d_curves[index];
+  if (!c)
+    return;
+
+  if (c->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) {
+    Spectrogram *sp = static_cast<Spectrogram *>(c);
+    QwtScaleWidget *colorAxis = axisWidget(sp->colorScaleAxis());
+    if (colorAxis)
+      colorAxis->setColorBarEnabled(false);
+  }
+
+  c->detach();
+  QwtPlotItem *p = d_curves.take(index);
+  // RNT: Making curve_key unique prevents clashes elsewhere
+  //--curve_key;
+  // MG: This is a rather crude but effective way of delaying the
+  // deletion of the curve objects. This is necessary because in
+  // a tight loop a curve may not have been completely removed
+  // but the object has been deleted.
+  Detacher *detacher = new Detacher(p);
+  detacher->deleteLater();
+}
+
+QList<int> Plot::getMajorTicksType() {
+  QList<int> majorTicksType;
+  for (int axis = 0; axis < QwtPlot::axisCnt; axis++) {
+    if (axisEnabled(axis)) {
+      ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+      majorTicksType << sd->majorTicksStyle();
+    } else
+      majorTicksType << ScaleDraw::Out;
+  }
+  return majorTicksType;
 }
 
-void Plot::setMajorTicksType(int axis, int type)
-{
-	ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw (axis));
-	if (sd)
-		sd->setMajorTicksStyle ((ScaleDraw::TicksStyle)type);
+void Plot::setMajorTicksType(int axis, int type) {
+  ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+  if (sd)
+    sd->setMajorTicksStyle((ScaleDraw::TicksStyle)type);
 }
 
-QList<int> Plot::getMinorTicksType()
-{
-	QList<int> minorTicksType;
-	for (int axis=0; axis<QwtPlot::axisCnt; axis++)
-	{
-		if (axisEnabled(axis))
-		{
-			ScaleDraw *sd = static_cast<ScaleDraw *>( axisScaleDraw (axis));
-			minorTicksType << sd->minorTicksStyle();
-		}
-		else
-			minorTicksType << ScaleDraw::Out;
-	}
-	return minorTicksType;
+QList<int> Plot::getMinorTicksType() {
+  QList<int> minorTicksType;
+  for (int axis = 0; axis < QwtPlot::axisCnt; axis++) {
+    if (axisEnabled(axis)) {
+      ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+      minorTicksType << sd->minorTicksStyle();
+    } else
+      minorTicksType << ScaleDraw::Out;
+  }
+  return minorTicksType;
 }
 
-void Plot::setMinorTicksType(int axis, int type)
-{
-	ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw (axis));
-	if (sd)
-		sd->setMinorTicksStyle((ScaleDraw::TicksStyle)type);
+void Plot::setMinorTicksType(int axis, int type) {
+  ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+  if (sd)
+    sd->setMinorTicksStyle((ScaleDraw::TicksStyle)type);
 }
 
-int Plot::axisLabelFormat(int axis)
-{
-	if (axisValid(axis)){
-		ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw (axis));
-		return sd->labelNumericFormat();
-	}
-	return 0;
+int Plot::axisLabelFormat(int axis) {
+  if (axisValid(axis)) {
+    ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+    return sd->labelNumericFormat();
+  }
+  return 0;
 }
 
-int Plot::axisLabelPrecision(int axis)
-{
-	if (axisValid(axis))
-	{
-		ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw (axis));
-		return sd->labelNumericPrecision();
-	}
+int Plot::axisLabelPrecision(int axis) {
+  if (axisValid(axis)) {
+    ScaleDraw *sd = static_cast<ScaleDraw *>(axisScaleDraw(axis));
+    return sd->labelNumericPrecision();
+  }
 
-	//for a bad call we return the default values
-	return 4;
+  // for a bad call we return the default values
+  return 4;
 }
 
 /**
@@ -670,91 +643,86 @@ int Plot::axisLabelPrecision(int axis)
   @retval f format character
   @retval prec precision
   */
-void Plot::axisLabelFormat(int axis, char &f, int &prec) const
-{
-	if (axisValid(axis)){
-		const ScaleDraw *sd = static_cast<const ScaleDraw *>(axisScaleDraw (axis));
-		sd->labelFormat(f, prec);
-	} else {//for a bad call we return the default values
-		f = 'g';
-		prec = 4;
-	}
+void Plot::axisLabelFormat(int axis, char &f, int &prec) const {
+  if (axisValid(axis)) {
+    const ScaleDraw *sd = static_cast<const ScaleDraw *>(axisScaleDraw(axis));
+    sd->labelFormat(f, prec);
+  } else { // for a bad call we return the default values
+    f = 'g';
+    prec = 4;
+  }
 }
 
 /**
   \brief Adjust plot content to its current size.
-  Must be reimplemented because the base implementation adds a mask causing an ugly drawing artefact.
+  Must be reimplemented because the base implementation adds a mask causing an
+  ugly drawing artefact.
 */
-void Plot::updateLayout()
-{
-    plotLayout()->activate(this, contentsRect());
-
-    // resize and show the visible widgets
-
-    if (!titleLabel()->text().isEmpty()){
-        titleLabel()->setGeometry(plotLayout()->titleRect());
-        if (!titleLabel()->isVisible())
-            titleLabel()->show();
+void Plot::updateLayout() {
+  plotLayout()->activate(this, contentsRect());
+
+  // resize and show the visible widgets
+
+  if (!titleLabel()->text().isEmpty()) {
+    titleLabel()->setGeometry(plotLayout()->titleRect());
+    if (!titleLabel()->isVisible())
+      titleLabel()->show();
+  } else
+    titleLabel()->hide();
+
+  for (int axisId = 0; axisId < axisCnt; axisId++) {
+    if (axisEnabled(axisId)) {
+      axisWidget(axisId)->setGeometry(plotLayout()->scaleRect(axisId));
+      if (!axisWidget(axisId)->isVisible())
+        axisWidget(axisId)->show();
     } else
-		titleLabel()->hide();
-
-    for (int axisId = 0; axisId < axisCnt; axisId++ ){
-        if (axisEnabled(axisId) ){
-            axisWidget(axisId)->setGeometry(plotLayout()->scaleRect(axisId));
-            if (!axisWidget(axisId)->isVisible())
-                axisWidget(axisId)->show();
-        } else
-            axisWidget(axisId)->hide();
-    }
+      axisWidget(axisId)->hide();
+  }
 
-    canvas()->setGeometry(plotLayout()->canvasRect());
+  canvas()->setGeometry(plotLayout()->canvasRect());
 }
 
-
-const QColor & Plot::paletteBackgroundColor() const
-{
-	return	palette().color(QPalette::Window);
+const QColor &Plot::paletteBackgroundColor() const {
+  return palette().color(QPalette::Window);
 }
 
-void Plot::updateCurveLabels()
-{
-    QList<QwtPlotItem *> curves = curvesList();
-    foreach(QwtPlotItem *i, curves){
-      DataCurve * dc = dynamic_cast<DataCurve *>(i);
-      if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram &&
-        dc->type() != Graph::Function &&
-        dc->hasLabels())
-        dc->updateLabelsPosition();
-    }
+void Plot::updateCurveLabels() {
+  QList<QwtPlotItem *> curves = curvesList();
+  foreach (QwtPlotItem *i, curves) {
+    DataCurve *dc = dynamic_cast<DataCurve *>(i);
+    if (dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram &&
+        dc->type() != Graph::Function && dc->hasLabels())
+      dc->updateLabelsPosition();
+  }
 }
 
 // Created for waterfall plots.
-// Contains the functionality that's in Graph.cpp of today's qtiplot (where Plot & Graph have been merged)
-void Plot::reverseCurveOrder()
-{
+// Contains the functionality that's in Graph.cpp of today's qtiplot (where Plot
+// & Graph have been merged)
+void Plot::reverseCurveOrder() {
   if (d_curves.isEmpty())
     return;
 
-  QMap<int,QwtPlotItem *> lst;
+  QMap<int, QwtPlotItem *> lst;
   QList<int> keys = curveKeys();
   int n = d_curves.size();
   for (int i = 0; i < n; i++)
-    lst.insert(keys[i],d_curves[keys[n - i - 1]]);
-//  Qtiplot code: lst << d_curves[n - i - 1];
+    lst.insert(keys[i], d_curves[keys[n - i - 1]]);
+  //  Qtiplot code: lst << d_curves[n - i - 1];
 
   d_curves = lst;
-//  Qtiplot code: setCurvesList(lst);
+  //  Qtiplot code: setCurvesList(lst);
 }
 
-void Plot::showEvent (QShowEvent * event)
-{
-    event->accept();
-    updateCurveLabels();
+void Plot::showEvent(QShowEvent *event) {
+  event->accept();
+  updateCurveLabels();
 }
 
 /**
   \brief Paint the plot into a given rectangle.
-  Paint the contents of a QwtPlot instance into a given rectangle (Qwt modified code).
+  Paint the contents of a QwtPlot instance into a given rectangle (Qwt modified
+  code).
 
   Note that this method is const so that it properly overrides
   QwtPlot::print (coverity issue 1076125). This however requires
@@ -766,202 +734,195 @@ void Plot::showEvent (QShowEvent * event)
   @param pfilter :: Print filter
 */
 void Plot::print(QPainter *painter, const QRect &plotRect,
-        const QwtPlotPrintFilter &pfilter) const
-{
-    int axisId;
+                 const QwtPlotPrintFilter &pfilter) const {
+  int axisId;
 
-    if ( painter == 0 || !painter->isActive() ||
-            !plotRect.isValid() || size().isNull() )
-       return;
+  if (painter == 0 || !painter->isActive() || !plotRect.isValid() ||
+      size().isNull())
+    return;
 
-    QwtText t = title();
-	printFrame(painter, plotRect);
+  QwtText t = title();
+  printFrame(painter, plotRect);
 
-    painter->save();
+  painter->save();
 
-    // All paint operations need to be scaled according to
-    // the paint device metrics.
+  // All paint operations need to be scaled according to
+  // the paint device metrics.
 
-    QwtPainter::setMetricsMap(this, painter->device());
-    const QwtMetricsMap &metricsMap = QwtPainter::metricsMap();
+  QwtPainter::setMetricsMap(this, painter->device());
+  const QwtMetricsMap &metricsMap = QwtPainter::metricsMap();
 
-    // It is almost impossible to integrate into the Qt layout
-    // framework, when using different fonts for printing
-    // and screen. To avoid writing different and Qt unconform
-    // layout engines we change the widget attributes, print and
-    // reset the widget attributes again. This way we produce a lot of
-    // useless layout events ...
+  // It is almost impossible to integrate into the Qt layout
+  // framework, when using different fonts for printing
+  // and screen. To avoid writing different and Qt unconform
+  // layout engines we change the widget attributes, print and
+  // reset the widget attributes again. This way we produce a lot of
+  // useless layout events ...
 
-    pfilter.apply((QwtPlot *)const_cast<Plot*>(this));
+  pfilter.apply((QwtPlot *)const_cast<Plot *>(this));
 
-    int baseLineDists[QwtPlot::axisCnt];
-    if ( !(pfilter.options() & 16) ){
-        // In case of no background we set the backbone of
-        // the scale on the frame of the canvas.
+  int baseLineDists[QwtPlot::axisCnt];
+  if (!(pfilter.options() & 16)) {
+    // In case of no background we set the backbone of
+    // the scale on the frame of the canvas.
 
-        for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
-            QwtScaleWidget *scaleWidget = const_cast<QwtScaleWidget*>(axisWidget(axisId));
-            if ( scaleWidget ){
-                baseLineDists[axisId] = scaleWidget->margin();
-                scaleWidget->setMargin(0);
-            }
-        }
-    }
-    // Calculate the layout for the print.
-
-    int layoutOptions = QwtPlotLayout::IgnoreScrollbars
-        | QwtPlotLayout::IgnoreFrames;
-    if ( !(pfilter.options() & QwtPlotPrintFilter::PrintMargin) )
-        layoutOptions |= QwtPlotLayout::IgnoreMargin;
-    if ( !(pfilter.options() & QwtPlotPrintFilter::PrintLegend) )
-        layoutOptions |= QwtPlotLayout::IgnoreLegend;
-
-    ((QwtPlot *)const_cast<Plot*>(this))->plotLayout()->activate(this,
-        QwtPainter::metricsMap().deviceToLayout(plotRect),
-        layoutOptions);
-
-    if ((pfilter.options() & QwtPlotPrintFilter::PrintTitle)
-        && (!titleLabel()->text().isEmpty())){
-        printTitle(painter, plotLayout()->titleRect());
+    for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++) {
+      QwtScaleWidget *scaleWidget =
+          const_cast<QwtScaleWidget *>(axisWidget(axisId));
+      if (scaleWidget) {
+        baseLineDists[axisId] = scaleWidget->margin();
+        scaleWidget->setMargin(0);
+      }
     }
+  }
+  // Calculate the layout for the print.
+
+  int layoutOptions =
+      QwtPlotLayout::IgnoreScrollbars | QwtPlotLayout::IgnoreFrames;
+  if (!(pfilter.options() & QwtPlotPrintFilter::PrintMargin))
+    layoutOptions |= QwtPlotLayout::IgnoreMargin;
+  if (!(pfilter.options() & QwtPlotPrintFilter::PrintLegend))
+    layoutOptions |= QwtPlotLayout::IgnoreLegend;
+
+  ((QwtPlot *)const_cast<Plot *>(this))
+      ->plotLayout()
+      ->activate(this, QwtPainter::metricsMap().deviceToLayout(plotRect),
+                 layoutOptions);
+
+  if ((pfilter.options() & QwtPlotPrintFilter::PrintTitle) &&
+      (!titleLabel()->text().isEmpty())) {
+    printTitle(painter, plotLayout()->titleRect());
+  }
 
-	QRect canvasRect = plotLayout()->canvasRect();;
-	canvasRect = metricsMap.layoutToDevice(canvasRect);
-
- 
-    // When using QwtPainter all sizes where computed in pixel
-    // coordinates and scaled by QwtPainter later. This limits
-    // the precision to screen resolution. A much better solution
-    // is to scale the maps and print in unlimited resolution.
-
-    QwtScaleMap map[axisCnt];
-    for (axisId = 0; axisId < axisCnt; axisId++){
-        map[axisId].setTransformation(axisScaleEngine(axisId)->transformation());
-
-        const QwtScaleDiv &scaleDiv = *axisScaleDiv(axisId);
-        map[axisId].setScaleInterval(scaleDiv.lBound(), scaleDiv.hBound());
-
-        double from, to;
-        if ( axisEnabled(axisId) ){
-            const int sDist = axisWidget(axisId)->startBorderDist();
-            const int eDist = axisWidget(axisId)->endBorderDist();
-            const QRect &scaleRect = plotLayout()->scaleRect(axisId);
-
-            if ( axisId == xTop || axisId == xBottom ){
-                from = metricsMap.layoutToDeviceX(scaleRect.left() + sDist);
-                to = metricsMap.layoutToDeviceX(scaleRect.right() + 1 - eDist);
-            } else {
-                from = metricsMap.layoutToDeviceY(scaleRect.bottom() + 1 - eDist );
-                to = metricsMap.layoutToDeviceY(scaleRect.top() + sDist);
-            }
-        } else {
-            const int margin = plotLayout()->canvasMargin(axisId);
-            if ( axisId == yLeft || axisId == yRight ){
-                from = metricsMap.layoutToDeviceX(canvasRect.bottom() - margin);
-                to = metricsMap.layoutToDeviceX(canvasRect.top() + margin);
-            } else {
-                from = metricsMap.layoutToDeviceY(canvasRect.left() + margin);
-                to = metricsMap.layoutToDeviceY(canvasRect.right() - margin);
-            }
-        }
-        map[axisId].setPaintXInterval(from, to);
+  QRect canvasRect = plotLayout()->canvasRect();
+  ;
+  canvasRect = metricsMap.layoutToDevice(canvasRect);
+
+  // When using QwtPainter all sizes where computed in pixel
+  // coordinates and scaled by QwtPainter later. This limits
+  // the precision to screen resolution. A much better solution
+  // is to scale the maps and print in unlimited resolution.
+
+  QwtScaleMap map[axisCnt];
+  for (axisId = 0; axisId < axisCnt; axisId++) {
+    map[axisId].setTransformation(axisScaleEngine(axisId)->transformation());
+
+    const QwtScaleDiv &scaleDiv = *axisScaleDiv(axisId);
+    map[axisId].setScaleInterval(scaleDiv.lBound(), scaleDiv.hBound());
+
+    double from, to;
+    if (axisEnabled(axisId)) {
+      const int sDist = axisWidget(axisId)->startBorderDist();
+      const int eDist = axisWidget(axisId)->endBorderDist();
+      const QRect &scaleRect = plotLayout()->scaleRect(axisId);
+
+      if (axisId == xTop || axisId == xBottom) {
+        from = metricsMap.layoutToDeviceX(scaleRect.left() + sDist);
+        to = metricsMap.layoutToDeviceX(scaleRect.right() + 1 - eDist);
+      } else {
+        from = metricsMap.layoutToDeviceY(scaleRect.bottom() + 1 - eDist);
+        to = metricsMap.layoutToDeviceY(scaleRect.top() + sDist);
+      }
+    } else {
+      const int margin = plotLayout()->canvasMargin(axisId);
+      if (axisId == yLeft || axisId == yRight) {
+        from = metricsMap.layoutToDeviceX(canvasRect.bottom() - margin);
+        to = metricsMap.layoutToDeviceX(canvasRect.top() + margin);
+      } else {
+        from = metricsMap.layoutToDeviceY(canvasRect.left() + margin);
+        to = metricsMap.layoutToDeviceY(canvasRect.right() - margin);
+      }
     }
+    map[axisId].setPaintXInterval(from, to);
+  }
 
-   // The canvas maps are already scaled.
-    QwtPainter::setMetricsMap(painter->device(), painter->device());
-    // 'Dummy' QRect argument inserted into printCanvas method to avoid Intel
-    // compiler warning (about printCanvas signature not matching that in base class)
-    printCanvas(painter, QRect(), canvasRect, map, pfilter);
-    QwtPainter::resetMetricsMap();
-
-
-  
-   canvasRect = plotLayout()->canvasRect();
-
-
-    for ( axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
-        QwtScaleWidget *scaleWidget = const_cast<QwtScaleWidget*>(axisWidget(axisId));
-        if (scaleWidget){
-            int baseDist = scaleWidget->margin();
-
-            int startDist, endDist;
-            scaleWidget->getBorderDistHint(startDist, endDist);
-
-            QRect scaleRect = plotLayout()->scaleRect(axisId);
-            if (!scaleWidget->margin()){
-                switch(axisId){
-                    case xBottom:
-                        scaleRect.translate(0, canvasRect.bottom() - scaleRect.top());
-                    break;
-                    case xTop:
-                        scaleRect.translate(0, canvasRect.top() - scaleRect.bottom());
-                    break;
-                    case yLeft:
-                        scaleRect.translate(canvasRect.left() - scaleRect.right(), 0);
-                    break;
-                    case yRight:
-                        scaleRect.translate(canvasRect.right() - scaleRect.left(), 0);
-                    break;
-                }
-            }
-            printScale(painter, axisId, startDist, endDist, baseDist, scaleRect);
+  // The canvas maps are already scaled.
+  QwtPainter::setMetricsMap(painter->device(), painter->device());
+  // 'Dummy' QRect argument inserted into printCanvas method to avoid Intel
+  // compiler warning (about printCanvas signature not matching that in base
+  // class)
+  printCanvas(painter, QRect(), canvasRect, map, pfilter);
+  QwtPainter::resetMetricsMap();
+
+  canvasRect = plotLayout()->canvasRect();
+
+  for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++) {
+    QwtScaleWidget *scaleWidget =
+        const_cast<QwtScaleWidget *>(axisWidget(axisId));
+    if (scaleWidget) {
+      int baseDist = scaleWidget->margin();
+
+      int startDist, endDist;
+      scaleWidget->getBorderDistHint(startDist, endDist);
+
+      QRect scaleRect = plotLayout()->scaleRect(axisId);
+      if (!scaleWidget->margin()) {
+        switch (axisId) {
+        case xBottom:
+          scaleRect.translate(0, canvasRect.bottom() - scaleRect.top());
+          break;
+        case xTop:
+          scaleRect.translate(0, canvasRect.top() - scaleRect.bottom());
+          break;
+        case yLeft:
+          scaleRect.translate(canvasRect.left() - scaleRect.right(), 0);
+          break;
+        case yRight:
+          scaleRect.translate(canvasRect.right() - scaleRect.left(), 0);
+          break;
         }
+      }
+      printScale(painter, axisId, startDist, endDist, baseDist, scaleRect);
     }
+  }
 
-    if ( !(pfilter.options() & 16) )
-    {
-        QRect boundingRect(
-            canvasRect.left() - 1, canvasRect.top() - 1,
-            canvasRect.width() + 2, canvasRect.height() + 2);
-        boundingRect = metricsMap.layoutToDevice(boundingRect);
-        boundingRect.setWidth(boundingRect.width() - 1);
-        boundingRect.setHeight(boundingRect.height() - 1);
-
-        painter->setPen(QPen(Qt::black));
-        painter->setBrush(QBrush(Qt::NoBrush));
-        painter->drawRect(boundingRect);
-    }
+  if (!(pfilter.options() & 16)) {
+    QRect boundingRect(canvasRect.left() - 1, canvasRect.top() - 1,
+                       canvasRect.width() + 2, canvasRect.height() + 2);
+    boundingRect = metricsMap.layoutToDevice(boundingRect);
+    boundingRect.setWidth(boundingRect.width() - 1);
+    boundingRect.setHeight(boundingRect.height() - 1);
 
-    
+    painter->setPen(QPen(Qt::black));
+    painter->setBrush(QBrush(Qt::NoBrush));
+    painter->drawRect(boundingRect);
+  }
 
-    ((QwtPlot *)const_cast<Plot*>(this))->plotLayout()->invalidate();
+  ((QwtPlot *)const_cast<Plot *>(this))->plotLayout()->invalidate();
 
-    // reset all widgets with their original attributes.
-    if ( !(pfilter.options() & 16) ){
-        // restore the previous base line dists
-        for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
-            QwtScaleWidget *scaleWidget =
-              const_cast<QwtScaleWidget*>(axisWidget(axisId));
-            if ( scaleWidget  )
-                scaleWidget->setMargin(baseLineDists[axisId]);
-        }
+  // reset all widgets with their original attributes.
+  if (!(pfilter.options() & 16)) {
+    // restore the previous base line dists
+    for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++) {
+      QwtScaleWidget *scaleWidget =
+          const_cast<QwtScaleWidget *>(axisWidget(axisId));
+      if (scaleWidget)
+        scaleWidget->setMargin(baseLineDists[axisId]);
     }
+  }
 
-    pfilter.reset((QwtPlot *)const_cast<Plot*>(this));
-    painter->restore();
-    const_cast<Plot*>(this)->setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten
+  pfilter.reset((QwtPlot *)const_cast<Plot *>(this));
+  painter->restore();
+  const_cast<Plot *>(this)->setTitle(t); // hack used to avoid bug in
+                                         // Qwt::printTitle(): the title
+                                         // attributes are overwritten
 }
 
-
-bool Plot::eventFilter(QObject *obj, QEvent *ev)
-{
+bool Plot::eventFilter(QObject *obj, QEvent *ev) {
   QEvent::Type eventType = ev->type();
-  QWidget *canvas = qobject_cast<QWidget*>(obj);
-  if ( canvas )
-  {
-    if ( eventType == QEvent::MouseButtonPress )
-    {    
-      emit dragMousePress( canvas->mapToGlobal( static_cast<QMouseEvent*>(ev)->pos()) );
-    }
-    else if ( eventType == QEvent::MouseButtonRelease )
-    {
-      emit dragMouseRelease( canvas->mapToGlobal( static_cast<QMouseEvent*>(ev)->pos()) );
-    }
-    else if ( eventType == QEvent::MouseMove )
-    {
-      emit dragMouseMove( canvas->mapToGlobal( static_cast<QMouseEvent*>(ev)->pos()) );
+  QWidget *canvas = qobject_cast<QWidget *>(obj);
+  if (canvas) {
+    if (eventType == QEvent::MouseButtonPress) {
+      emit dragMousePress(
+          canvas->mapToGlobal(static_cast<QMouseEvent *>(ev)->pos()));
+    } else if (eventType == QEvent::MouseButtonRelease) {
+      emit dragMouseRelease(
+          canvas->mapToGlobal(static_cast<QMouseEvent *>(ev)->pos()));
+    } else if (eventType == QEvent::MouseMove) {
+      emit dragMouseMove(
+          canvas->mapToGlobal(static_cast<QMouseEvent *>(ev)->pos()));
     }
   }
 
-  return QwtPlot::eventFilter(obj,ev);
+  return QwtPlot::eventFilter(obj, ev);
 }
diff --git a/MantidPlot/src/Plot.h b/MantidPlot/src/Plot.h
index bf78cc80f466daa98c0b1b5363b921d9e2b2bad8..dde62dd940e3491743231dd84e7a4b8d42567610 100644
--- a/MantidPlot/src/Plot.h
+++ b/MantidPlot/src/Plot.h
@@ -2,7 +2,8 @@
     File                 : Plot.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plot window class
 
@@ -41,8 +42,7 @@
 class Grid;
 
 /// Helper class to delay deletion of curves
-struct Detacher : public QObject
-{
+struct Detacher : public QObject {
   explicit Detacher(QwtPlotItem *plotItem);
   ~Detacher() override;
 
@@ -52,62 +52,62 @@ private:
 };
 
 //! Plot window class
-class Plot: public QwtPlot
-{
-    Q_OBJECT
+class Plot : public QwtPlot {
+  Q_OBJECT
 
 public:
-	Plot(int width = 500, int height = 400, QWidget *parent = 0, const char *name = 0);
+  Plot(int width = 500, int height = 400, QWidget *parent = 0,
+       const char *name = 0);
 
-	Grid *grid(){return static_cast<Grid *>(d_grid);};
-	QList<int> curveKeys(){return d_curves.keys();};
-	QList<QwtPlotItem *> curvesList(){return d_curves.values();};
+  Grid *grid() { return static_cast<Grid *>(d_grid); };
+  QList<int> curveKeys() { return d_curves.keys(); };
+  QList<QwtPlotItem *> curvesList() { return d_curves.values(); };
 
-	int insertCurve(QwtPlotItem *c);
-	void removeCurve(int index);
+  int insertCurve(QwtPlotItem *c);
+  void removeCurve(int index);
 
-	int closestCurve(int xpos, int ypos, int &dist, int &point);
-	QwtPlotCurve* curve(int index);
-	QwtPlotItem* plotItem(int index){return d_curves.value(index);};
-	QMap<int, QwtPlotItem*> curves(){return d_curves;};
+  int closestCurve(int xpos, int ypos, int &dist, int &point);
+  QwtPlotCurve *curve(int index);
+  QwtPlotItem *plotItem(int index) { return d_curves.value(index); };
+  QMap<int, QwtPlotItem *> curves() { return d_curves; };
 
-	QwtPlotMarker* marker(int index){return d_markers.value(index);};
-	QList<int> markerKeys(){return d_markers.keys();};
-	int insertMarker(QwtPlotMarker *m);
-	void removeMarker(int index);
+  QwtPlotMarker *marker(int index) { return d_markers.value(index); };
+  QList<int> markerKeys() { return d_markers.keys(); };
+  int insertMarker(QwtPlotMarker *m);
+  void removeMarker(int index);
 
-	QList<int> getMajorTicksType();
-	void setMajorTicksType(int axis, int type);
+  QList<int> getMajorTicksType();
+  void setMajorTicksType(int axis, int type);
 
-	QList<int> getMinorTicksType();
-	void setMinorTicksType(int axis, int type);
+  QList<int> getMinorTicksType();
+  void setMinorTicksType(int axis, int type);
 
-	int minorTickLength() const;
-	int majorTickLength() const;
-	void setTickLength (int minLength, int majLength);
+  int minorTickLength() const;
+  int majorTickLength() const;
+  void setTickLength(int minLength, int majLength);
 
-	int axesLinewidth() const;
-	void setAxesLinewidth(int width);
+  int axesLinewidth() const;
+  void setAxesLinewidth(int width);
 
-    void axisLabelFormat(int axis, char &f, int &prec) const;
+  void axisLabelFormat(int axis, char &f, int &prec) const;
 
-    int axisLabelFormat(int axis);
-    int axisLabelPrecision(int axis);
+  int axisLabelFormat(int axis);
+  int axisLabelPrecision(int axis);
 
-    QColor frameColor();
-    const QColor & paletteBackgroundColor() const;
+  QColor frameColor();
+  const QColor &paletteBackgroundColor() const;
 
-    using QwtPlot::print; // Avoid Intel compiler warning
-    void
-    print(QPainter *, const QRect &rect,
-          const QwtPlotPrintFilter & = QwtPlotPrintFilter()) const override;
-    void updateLayout() override;
+  using QwtPlot::print; // Avoid Intel compiler warning
+  void print(QPainter *, const QRect &rect,
+             const QwtPlotPrintFilter & = QwtPlotPrintFilter()) const override;
+  void updateLayout() override;
 
-    void updateCurveLabels();
-    // pass through method that is public on the base class in later qwt versions
-    void updateAxes() { QwtPlot::updateAxes(); }
+  void updateCurveLabels();
+  // pass through method that is public on the base class in later qwt versions
+  void updateAxes() { QwtPlot::updateAxes(); }
 
-    void reverseCurveOrder(); // Created in connection with waterfall plots. Called from Graph method of same name.
+  void reverseCurveOrder(); // Created in connection with waterfall plots.
+                            // Called from Graph method of same name.
 
 signals:
   void dragMousePress(QPoint);
@@ -116,29 +116,31 @@ signals:
 
 protected:
   void showEvent(QShowEvent *event) override;
-    void printFrame(QPainter *painter, const QRect &rect) const;
-    // 'Dummy' QRect argument inserted into printCanvas method to avoid Intel
-    // compiler warning (about printCanvas signature not matching that in base class)
-    void printCanvas(QPainter *painter, const QRect &, const QRect &canvasRect,
-                     const QwtScaleMap map[axisCnt],
-                     const QwtPlotPrintFilter &pfilter) const override;
-    void drawItems(QPainter *painter, const QRect &rect,
+  void printFrame(QPainter *painter, const QRect &rect) const;
+  // 'Dummy' QRect argument inserted into printCanvas method to avoid Intel
+  // compiler warning (about printCanvas signature not matching that in base
+  // class)
+  void printCanvas(QPainter *painter, const QRect &, const QRect &canvasRect,
                    const QwtScaleMap map[axisCnt],
                    const QwtPlotPrintFilter &pfilter) const override;
+  void drawItems(QPainter *painter, const QRect &rect,
+                 const QwtScaleMap map[axisCnt],
+                 const QwtPlotPrintFilter &pfilter) const override;
 
-        void drawInwardTicks(QPainter *painter, const QRect &rect,
-							const QwtScaleMap&map, int axis, bool min, bool maj) const;
-    void drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map, int axis) const;
+  void drawInwardTicks(QPainter *painter, const QRect &rect,
+                       const QwtScaleMap &map, int axis, bool min,
+                       bool maj) const;
+  void drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map,
+                 int axis) const;
 
-    bool eventFilter(QObject *obj, QEvent *ev) override;
+  bool eventFilter(QObject *obj, QEvent *ev) override;
 
-        Grid *d_grid;
-	QMap<int, QwtPlotItem*> d_curves;
-	QMap<int, QwtPlotMarker*> d_markers;
-
-	int minTickLength, majTickLength;
-	int marker_key;
-	int curve_key;
+  Grid *d_grid;
+  QMap<int, QwtPlotItem *> d_curves;
+  QMap<int, QwtPlotMarker *> d_markers;
 
+  int minTickLength, majTickLength;
+  int marker_key;
+  int curve_key;
 };
 #endif
diff --git a/MantidPlot/src/Plot3DDialog.cpp b/MantidPlot/src/Plot3DDialog.cpp
index e65e6cd3646f2307ab97b5d4c11c89444522ad05..95f6eefff0a752f107a4cb3387d830d3796c5d96 100644
--- a/MantidPlot/src/Plot3DDialog.cpp
+++ b/MantidPlot/src/Plot3DDialog.cpp
@@ -58,859 +58,847 @@
 
 using Mantid::Kernel::ConfigService;
 
-Plot3DDialog::Plot3DDialog( QWidget* parent,  Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
-    setObjectName( "Plot3DDialog" );
-	setWindowTitle( tr( "MantidPlot - Surface Plot Options" ) );
-
-	bars=0; points=0;
-
-    QHBoxLayout *hbox = new QHBoxLayout();
-    hbox->addStretch();
-	btnTable = new QPushButton();
-    hbox->addWidget(btnTable);
-	buttonApply = new QPushButton(tr( "&Apply" ));
-    hbox->addWidget(buttonApply);
-	buttonOk = new QPushButton(tr( "&OK" ));
-	buttonOk->setDefault( true );
-    hbox->addWidget(buttonOk);
-	buttonCancel = new QPushButton(tr( "&Cancel" ));
-    hbox->addWidget(buttonCancel);
-
-    generalDialog = new QTabWidget();
-
-    initScalesPage();
-	initAxesPage();
-	initTitlePage();
-	initColorsPage();
-	initGeneralPage();
-
-	QVBoxLayout* vl = new QVBoxLayout(this);
-	vl->addWidget(generalDialog);
-	vl->addLayout(hbox);
-
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-	connect( buttonApply, SIGNAL( clicked() ), this, SLOT(updatePlot() ) );
-	connect( btnTable, SIGNAL( clicked() ), this, SLOT(worksheet() ) );
+Plot3DDialog::Plot3DDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setObjectName("Plot3DDialog");
+  setWindowTitle(tr("MantidPlot - Surface Plot Options"));
+
+  bars = 0;
+  points = 0;
+
+  QHBoxLayout *hbox = new QHBoxLayout();
+  hbox->addStretch();
+  btnTable = new QPushButton();
+  hbox->addWidget(btnTable);
+  buttonApply = new QPushButton(tr("&Apply"));
+  hbox->addWidget(buttonApply);
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setDefault(true);
+  hbox->addWidget(buttonOk);
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  hbox->addWidget(buttonCancel);
+
+  generalDialog = new QTabWidget();
+
+  initScalesPage();
+  initAxesPage();
+  initTitlePage();
+  initColorsPage();
+  initGeneralPage();
+
+  QVBoxLayout *vl = new QVBoxLayout(this);
+  vl->addWidget(generalDialog);
+  vl->addLayout(hbox);
+
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(updatePlot()));
+  connect(btnTable, SIGNAL(clicked()), this, SLOT(worksheet()));
 }
 
-void Plot3DDialog::initScalesPage()
-{
-	axesList = new QListWidget();
-	axesList->addItem(tr( "X" ) );
-	axesList->addItem(tr( "Y" ) );
-	axesList->addItem(tr( "Z" ) );
-	axesList->setFixedWidth(50);
-	axesList->setCurrentRow(0);
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel(tr("From")), 0, 0);
-	boxFrom = new QLineEdit();
-	boxFrom->setMaximumWidth(150);
-    gl1->addWidget(boxFrom, 0, 1);
-    gl1->addWidget(new QLabel(tr("To")), 1, 0);
-	boxTo = new QLineEdit();
-	boxTo->setMaximumWidth(150);
-    gl1->addWidget(boxTo, 1, 1);
-    gl1->addWidget(new QLabel(tr("Type")), 2, 0);
-	boxType=new QComboBox();
-	boxType->addItem(tr("linear"));
-	boxType->addItem(tr("logarithmic"));
-	boxType->setMaximumWidth(150);
-    gl1->addWidget(boxType, 2, 1);
-    gl1->setRowStretch(3, 1);
-
-    QGroupBox *gb1 = new QGroupBox();
-    gb1->setLayout(gl1);
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel(tr("Major Ticks")), 0, 0);
-	boxMajors = new QSpinBox();
-    gl2->addWidget(boxMajors, 0, 1);
-    gl2->addWidget(new QLabel(tr("Minor Ticks")), 1, 0);
-	boxMinors = new QSpinBox();
-    gl2->addWidget(boxMinors, 1, 1);
-    gl2->setRowStretch(2, 1);
-
-    TicksGroupBox = new QGroupBox();
-    TicksGroupBox->setLayout(gl2);
-
-	QHBoxLayout* hb = new QHBoxLayout();
-	hb->addWidget(axesList);
-	hb->addWidget(gb1);
-    hb->addWidget(TicksGroupBox);
-
-    scale = new QWidget();
-    scale->setLayout(hb);
-	generalDialog->insertTab(-1, scale, tr( "&Scale" ) );
+void Plot3DDialog::initScalesPage() {
+  axesList = new QListWidget();
+  axesList->addItem(tr("X"));
+  axesList->addItem(tr("Y"));
+  axesList->addItem(tr("Z"));
+  axesList->setFixedWidth(50);
+  axesList->setCurrentRow(0);
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("From")), 0, 0);
+  boxFrom = new QLineEdit();
+  boxFrom->setMaximumWidth(150);
+  gl1->addWidget(boxFrom, 0, 1);
+  gl1->addWidget(new QLabel(tr("To")), 1, 0);
+  boxTo = new QLineEdit();
+  boxTo->setMaximumWidth(150);
+  gl1->addWidget(boxTo, 1, 1);
+  gl1->addWidget(new QLabel(tr("Type")), 2, 0);
+  boxType = new QComboBox();
+  boxType->addItem(tr("linear"));
+  boxType->addItem(tr("logarithmic"));
+  boxType->setMaximumWidth(150);
+  gl1->addWidget(boxType, 2, 1);
+  gl1->setRowStretch(3, 1);
+
+  QGroupBox *gb1 = new QGroupBox();
+  gb1->setLayout(gl1);
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("Major Ticks")), 0, 0);
+  boxMajors = new QSpinBox();
+  gl2->addWidget(boxMajors, 0, 1);
+  gl2->addWidget(new QLabel(tr("Minor Ticks")), 1, 0);
+  boxMinors = new QSpinBox();
+  gl2->addWidget(boxMinors, 1, 1);
+  gl2->setRowStretch(2, 1);
+
+  TicksGroupBox = new QGroupBox();
+  TicksGroupBox->setLayout(gl2);
+
+  QHBoxLayout *hb = new QHBoxLayout();
+  hb->addWidget(axesList);
+  hb->addWidget(gb1);
+  hb->addWidget(TicksGroupBox);
+
+  scale = new QWidget();
+  scale->setLayout(hb);
+  generalDialog->insertTab(-1, scale, tr("&Scale"));
 }
 
-void Plot3DDialog::initAxesPage()
-{
-	axesList2 = new QListWidget();
-	axesList2->addItem(tr( "X" ) );
-	axesList2->addItem(tr( "Y" ) );
-	axesList2->addItem(tr( "Z" ) );
-	axesList2->setFixedWidth(50);
-	axesList2->setCurrentRow(0);
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel(tr("Title")), 0, 0);
-	boxLabel = new QTextEdit();
-	boxLabel->setMaximumHeight(60);
-    gl1->addWidget(boxLabel, 0, 1);
-    gl1->addWidget(new QLabel(tr("Axis Font")), 1, 0);
-
-    QHBoxLayout* hb1 = new QHBoxLayout();
-	btnLabelFont = new QPushButton(tr( "&Choose font" ));
-    hb1->addWidget(btnLabelFont);
-	
-	axisTitleFormatButtons = new TextFormatButtons(boxLabel);
-	hb1->addWidget(axisTitleFormatButtons);
-
-    hb1->addStretch();
-    gl1->addLayout(hb1, 1, 1);
-
-    gl1->addWidget(new QLabel(tr("Major Ticks Length")), 2, 0);
-	boxMajorLength = new QLineEdit();
-    gl1->addWidget(boxMajorLength, 2, 1);
-    gl1->addWidget(new QLabel(tr("Minor Ticks Length")), 3, 0);
-	boxMinorLength = new QLineEdit();
-    gl1->addWidget(boxMinorLength, 3, 1);
-    gl1->setRowStretch(4, 1);
-
-    QGroupBox *gb1 = new QGroupBox();
-    gb1->setLayout(gl1);
-
-	QHBoxLayout* hb2 = new QHBoxLayout();
-	hb2->addWidget(axesList2);
-	hb2->addWidget(gb1);
-
-    axes = new QWidget();
-    axes->setLayout(hb2);
-	generalDialog->insertTab(-1, axes, tr( "&Axis" ) );
-
-	connect( axesList2, SIGNAL(currentRowChanged(int)), this, SLOT(viewAxisOptions(int)));
-	connect( axesList, SIGNAL(currentRowChanged(int)), this, SLOT(viewScaleLimits(int)));
-	connect( btnLabelFont, SIGNAL(clicked()), this, SLOT(pickAxisLabelFont()));
+void Plot3DDialog::initAxesPage() {
+  axesList2 = new QListWidget();
+  axesList2->addItem(tr("X"));
+  axesList2->addItem(tr("Y"));
+  axesList2->addItem(tr("Z"));
+  axesList2->setFixedWidth(50);
+  axesList2->setCurrentRow(0);
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Title")), 0, 0);
+  boxLabel = new QTextEdit();
+  boxLabel->setMaximumHeight(60);
+  gl1->addWidget(boxLabel, 0, 1);
+  gl1->addWidget(new QLabel(tr("Axis Font")), 1, 0);
+
+  QHBoxLayout *hb1 = new QHBoxLayout();
+  btnLabelFont = new QPushButton(tr("&Choose font"));
+  hb1->addWidget(btnLabelFont);
+
+  axisTitleFormatButtons = new TextFormatButtons(boxLabel);
+  hb1->addWidget(axisTitleFormatButtons);
+
+  hb1->addStretch();
+  gl1->addLayout(hb1, 1, 1);
+
+  gl1->addWidget(new QLabel(tr("Major Ticks Length")), 2, 0);
+  boxMajorLength = new QLineEdit();
+  gl1->addWidget(boxMajorLength, 2, 1);
+  gl1->addWidget(new QLabel(tr("Minor Ticks Length")), 3, 0);
+  boxMinorLength = new QLineEdit();
+  gl1->addWidget(boxMinorLength, 3, 1);
+  gl1->setRowStretch(4, 1);
+
+  QGroupBox *gb1 = new QGroupBox();
+  gb1->setLayout(gl1);
+
+  QHBoxLayout *hb2 = new QHBoxLayout();
+  hb2->addWidget(axesList2);
+  hb2->addWidget(gb1);
+
+  axes = new QWidget();
+  axes->setLayout(hb2);
+  generalDialog->insertTab(-1, axes, tr("&Axis"));
+
+  connect(axesList2, SIGNAL(currentRowChanged(int)), this,
+          SLOT(viewAxisOptions(int)));
+  connect(axesList, SIGNAL(currentRowChanged(int)), this,
+          SLOT(viewScaleLimits(int)));
+  connect(btnLabelFont, SIGNAL(clicked()), this, SLOT(pickAxisLabelFont()));
 }
 
-void Plot3DDialog::initTitlePage()
-{
-    QHBoxLayout* hb1 = new QHBoxLayout();
-    hb1->addStretch();
-    QLabel *colorLabel = new QLabel(tr( "Co&lor" ));
-    hb1->addWidget(colorLabel);
-    btnTitleColor = new ColorButton();
-    hb1->addWidget(btnTitleColor);
-    colorLabel->setBuddy(btnTitleColor);
-
-    btnTitleFont = new QPushButton(tr( "&Font" ));
-    hb1->addWidget(btnTitleFont);
-	
-	QVBoxLayout* vl = new QVBoxLayout();
-	boxTitle = new QTextEdit();
-	boxTitle->setMaximumHeight(80);
-	vl->addWidget(boxTitle);
-	
-	titleFormatButtons = new TextFormatButtons(boxTitle);
-	hb1->addWidget(titleFormatButtons);
-    hb1->addStretch();
-
-    vl->addLayout(hb1);
-    vl->addStretch();
-
-    title = new QWidget();
-    title->setLayout(vl);
-	generalDialog->insertTab(-1, title, tr( "&Title" ) );
-
-	connect( btnTitleFont, SIGNAL(clicked()), this, SLOT(pickTitleFont() ) );
+void Plot3DDialog::initTitlePage() {
+  QHBoxLayout *hb1 = new QHBoxLayout();
+  hb1->addStretch();
+  QLabel *colorLabel = new QLabel(tr("Co&lor"));
+  hb1->addWidget(colorLabel);
+  btnTitleColor = new ColorButton();
+  hb1->addWidget(btnTitleColor);
+  colorLabel->setBuddy(btnTitleColor);
+
+  btnTitleFont = new QPushButton(tr("&Font"));
+  hb1->addWidget(btnTitleFont);
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  boxTitle = new QTextEdit();
+  boxTitle->setMaximumHeight(80);
+  vl->addWidget(boxTitle);
+
+  titleFormatButtons = new TextFormatButtons(boxTitle);
+  hb1->addWidget(titleFormatButtons);
+  hb1->addStretch();
+
+  vl->addLayout(hb1);
+  vl->addStretch();
+
+  title = new QWidget();
+  title->setLayout(vl);
+  generalDialog->insertTab(-1, title, tr("&Title"));
+
+  connect(btnTitleFont, SIGNAL(clicked()), this, SLOT(pickTitleFont()));
 }
 
-void Plot3DDialog::initColorsPage()
-{
-    QGridLayout* vl1 = new QGridLayout();
-    btnFromColor = new ColorButton();
-    QLabel *maxLabel = new QLabel(tr( "&Max" ));
-    maxLabel->setBuddy(btnFromColor);
-    vl1->addWidget(maxLabel, 0, 0);
-    vl1->addWidget(btnFromColor, 0, 1);
-
-	btnToColor = new ColorButton();
-	QLabel *minLabel = new QLabel(tr( "M&in" ));
-	minLabel->setBuddy(btnToColor);
-    vl1->addWidget(minLabel, 1, 0);
-    vl1->addWidget(btnToColor, 1, 1);
-
-	btnColorMap = new QPushButton(tr( "Color Ma&p" ));
-    vl1->addWidget(btnColorMap, 2, 1);
-    vl1->setRowStretch(3, 1);
-
-    QGroupBox *gb1 = new QGroupBox(tr( "Data" ));
-    gb1->setLayout(vl1);
-
-    QGridLayout* vl2 = new QGridLayout();
-    btnMesh = new ColorButton();
-    QLabel *meshLabel = new QLabel(tr( "&Line" ));
-    meshLabel->setBuddy(btnMesh);
-    vl2->addWidget(meshLabel, 0, 0);
-    vl2->addWidget(btnMesh, 0, 1);
-
-    btnBackground = new ColorButton();
-    QLabel *backgroundLabel = new QLabel(tr( "&Background" ));
-    backgroundLabel->setBuddy(btnBackground);
-    vl2->addWidget(backgroundLabel, 1, 0);
-    vl2->addWidget(btnBackground, 1, 1);
-    vl2->setRowStretch(2, 1);
-
-    QGroupBox *gb2 = new QGroupBox(tr( "General" ));
-    gb2->setLayout(vl2);
-
-    QGridLayout *gl1 = new QGridLayout();
-    btnAxes = new ColorButton();
-    QLabel *axesLabel = new QLabel(tr( "A&xes" ));
-    axesLabel->setBuddy(btnAxes);
-    gl1->addWidget(axesLabel, 0, 0);
-    gl1->addWidget(btnAxes, 0, 1);
-
-    btnLabels = new ColorButton();
-    QLabel *labLabels = new QLabel(tr( "Lab&els" ));
-    labLabels->setBuddy(btnLabels);
-    gl1->addWidget(labLabels, 1, 0);
-    gl1->addWidget(btnLabels, 1, 1);
-
-	btnNumbers = new ColorButton();
-	QLabel *numbersLabel = new QLabel(tr( "&Numbers" ));
-    numbersLabel->setBuddy(btnNumbers);
-	gl1->addWidget(numbersLabel, 2, 0);
-    gl1->addWidget(btnNumbers, 2, 1);
-
-	btnGrid = new ColorButton();
-	QLabel *gridLabel = new QLabel(tr( "&Grid" ));
-	gridLabel->setBuddy(btnGrid);
-	gl1->addWidget(gridLabel, 3, 0);
-    gl1->addWidget(btnGrid, 3, 1);
-    gl1->setRowStretch(4, 1);
-
-    AxesColorGroupBox = new QGroupBox(tr( "Coordinate System" ));
-    AxesColorGroupBox->setLayout(gl1);
-
-    QHBoxLayout* hb1 = new QHBoxLayout();
-	hb1->addWidget(gb1);
-    hb1->addWidget(gb2);
-    hb1->addWidget(AxesColorGroupBox);
-
-    QHBoxLayout* hb2 = new QHBoxLayout();
-    hb2->addStretch();
-	hb2->addWidget(new QLabel( tr( "Opacity" )));
-	boxTransparency = new QSpinBox();
-    boxTransparency->setRange(0, 100);
-    boxTransparency->setSingleStep(5);
-    hb2->addWidget(boxTransparency);
-
-	QVBoxLayout* vl = new QVBoxLayout();
-	vl->addLayout(hb2);
-	vl->addLayout(hb1);
-
-    colors = new QWidget();
-    colors->setLayout(vl);
-	generalDialog->insertTab(-1, colors, tr( "&Colors" ) );
-
-	connect( btnColorMap, SIGNAL( clicked() ), this, SLOT(pickDataColorMap() ) );
-	connect( boxTransparency, SIGNAL( valueChanged(int) ), this, SLOT(changeTransparency(int) ) );
+void Plot3DDialog::initColorsPage() {
+  QGridLayout *vl1 = new QGridLayout();
+  btnFromColor = new ColorButton();
+  QLabel *maxLabel = new QLabel(tr("&Max"));
+  maxLabel->setBuddy(btnFromColor);
+  vl1->addWidget(maxLabel, 0, 0);
+  vl1->addWidget(btnFromColor, 0, 1);
+
+  btnToColor = new ColorButton();
+  QLabel *minLabel = new QLabel(tr("M&in"));
+  minLabel->setBuddy(btnToColor);
+  vl1->addWidget(minLabel, 1, 0);
+  vl1->addWidget(btnToColor, 1, 1);
+
+  btnColorMap = new QPushButton(tr("Color Ma&p"));
+  vl1->addWidget(btnColorMap, 2, 1);
+  vl1->setRowStretch(3, 1);
+
+  QGroupBox *gb1 = new QGroupBox(tr("Data"));
+  gb1->setLayout(vl1);
+
+  QGridLayout *vl2 = new QGridLayout();
+  btnMesh = new ColorButton();
+  QLabel *meshLabel = new QLabel(tr("&Line"));
+  meshLabel->setBuddy(btnMesh);
+  vl2->addWidget(meshLabel, 0, 0);
+  vl2->addWidget(btnMesh, 0, 1);
+
+  btnBackground = new ColorButton();
+  QLabel *backgroundLabel = new QLabel(tr("&Background"));
+  backgroundLabel->setBuddy(btnBackground);
+  vl2->addWidget(backgroundLabel, 1, 0);
+  vl2->addWidget(btnBackground, 1, 1);
+  vl2->setRowStretch(2, 1);
+
+  QGroupBox *gb2 = new QGroupBox(tr("General"));
+  gb2->setLayout(vl2);
+
+  QGridLayout *gl1 = new QGridLayout();
+  btnAxes = new ColorButton();
+  QLabel *axesLabel = new QLabel(tr("A&xes"));
+  axesLabel->setBuddy(btnAxes);
+  gl1->addWidget(axesLabel, 0, 0);
+  gl1->addWidget(btnAxes, 0, 1);
+
+  btnLabels = new ColorButton();
+  QLabel *labLabels = new QLabel(tr("Lab&els"));
+  labLabels->setBuddy(btnLabels);
+  gl1->addWidget(labLabels, 1, 0);
+  gl1->addWidget(btnLabels, 1, 1);
+
+  btnNumbers = new ColorButton();
+  QLabel *numbersLabel = new QLabel(tr("&Numbers"));
+  numbersLabel->setBuddy(btnNumbers);
+  gl1->addWidget(numbersLabel, 2, 0);
+  gl1->addWidget(btnNumbers, 2, 1);
+
+  btnGrid = new ColorButton();
+  QLabel *gridLabel = new QLabel(tr("&Grid"));
+  gridLabel->setBuddy(btnGrid);
+  gl1->addWidget(gridLabel, 3, 0);
+  gl1->addWidget(btnGrid, 3, 1);
+  gl1->setRowStretch(4, 1);
+
+  AxesColorGroupBox = new QGroupBox(tr("Coordinate System"));
+  AxesColorGroupBox->setLayout(gl1);
+
+  QHBoxLayout *hb1 = new QHBoxLayout();
+  hb1->addWidget(gb1);
+  hb1->addWidget(gb2);
+  hb1->addWidget(AxesColorGroupBox);
+
+  QHBoxLayout *hb2 = new QHBoxLayout();
+  hb2->addStretch();
+  hb2->addWidget(new QLabel(tr("Opacity")));
+  boxTransparency = new QSpinBox();
+  boxTransparency->setRange(0, 100);
+  boxTransparency->setSingleStep(5);
+  hb2->addWidget(boxTransparency);
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  vl->addLayout(hb2);
+  vl->addLayout(hb1);
+
+  colors = new QWidget();
+  colors->setLayout(vl);
+  generalDialog->insertTab(-1, colors, tr("&Colors"));
+
+  connect(btnColorMap, SIGNAL(clicked()), this, SLOT(pickDataColorMap()));
+  connect(boxTransparency, SIGNAL(valueChanged(int)), this,
+          SLOT(changeTransparency(int)));
 }
 
-void Plot3DDialog::initGeneralPage()
-{
-    QGridLayout *gl1 = new QGridLayout();
-	boxLegend = new QCheckBox(tr("Show Legend"));
-    gl1->addWidget(boxLegend, 0, 0);
-	boxOrthogonal = new QCheckBox(tr("Orthogonal"));
-    gl1->addWidget(boxOrthogonal, 0, 1);
-
-    gl1->addWidget(new QLabel(tr( "Line Width" )), 1, 0);
-	boxMeshLineWidth = new QDoubleSpinBox();
-	boxMeshLineWidth->setDecimals(1);
-	boxMeshLineWidth->setSingleStep(0.1);
-    boxMeshLineWidth->setRange(1, 100);
-    gl1->addWidget(boxMeshLineWidth, 1, 1);
-
-    gl1->addWidget(new QLabel( tr( "Resolution" )), 2, 0);
-	boxResolution = new QSpinBox();
-    boxResolution->setRange(1, 100);
-	boxResolution->setSpecialValueText( "1 (all data)" );
-    gl1->addWidget(boxResolution, 2, 1);
-
-    gl1->addWidget(new QLabel( tr( "Numbers Font" )), 3, 0);
-	btnNumbersFont=new QPushButton(tr( "&Choose Font" ));
-    gl1->addWidget(btnNumbersFont, 3, 1);
-
-    gl1->addWidget(new QLabel( tr( "Distance labels - axis" )), 4, 0);
-	boxDistance = new QSpinBox();
-    boxDistance->setRange(0, 1000);
-    boxDistance->setSingleStep(5);
-    gl1->addWidget(boxDistance, 4, 1);
-    gl1->setRowStretch(5, 1);
-
-    QGroupBox *gb1 = new QGroupBox();
-    gb1->setLayout(gl1);
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel(tr( "Zoom (%)" )), 0, 0);
-	boxZoom = new QSpinBox();
-    boxZoom->setRange(1, 10000);
-    boxZoom->setSingleStep(10);
-
-    gl2->addWidget(boxZoom, 0, 1);
-    gl2->addWidget(new QLabel(tr( "X Zoom (%)" )), 1, 0);
-	boxXScale = new QSpinBox();
-    boxXScale->setRange(1, 10000);
-    boxXScale->setSingleStep(10);
-    gl2->addWidget(boxXScale, 1, 1);
-
-    gl2->addWidget(new QLabel(tr( "Y Zoom (%)" )), 2, 0);
-	boxYScale = new QSpinBox();
-    boxYScale->setRange(1, 10000);
-    boxYScale->setSingleStep(10);
-    gl2->addWidget(boxYScale, 2, 1);
-
-    gl2->addWidget(new QLabel(tr( "Z Zoom (%)" )), 3, 0);
-	boxZScale = new QSpinBox();
-    boxZScale->setRange(1, 10000);
-    boxZScale->setSingleStep(10);
-    gl2->addWidget(boxZScale, 3, 1);
-    gl2->setRowStretch(4, 1);
-
-    QGroupBox *gb2 = new QGroupBox();
-    gb2->setLayout(gl2);
-
-	QHBoxLayout* hl = new QHBoxLayout();
-	hl->addWidget(gb1);
-	hl->addWidget(gb2);
-
-    general = new QWidget();
-    general->setLayout(hl);
-	generalDialog->insertTab(-1, general, tr("&General"));
-
-	connect( boxZoom, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
-	connect( boxXScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
-	connect( boxYScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
-	connect( boxZScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
-	connect( btnNumbersFont, SIGNAL(clicked()), this, SLOT(pickNumbersFont()));
+void Plot3DDialog::initGeneralPage() {
+  QGridLayout *gl1 = new QGridLayout();
+  boxLegend = new QCheckBox(tr("Show Legend"));
+  gl1->addWidget(boxLegend, 0, 0);
+  boxOrthogonal = new QCheckBox(tr("Orthogonal"));
+  gl1->addWidget(boxOrthogonal, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("Line Width")), 1, 0);
+  boxMeshLineWidth = new QDoubleSpinBox();
+  boxMeshLineWidth->setDecimals(1);
+  boxMeshLineWidth->setSingleStep(0.1);
+  boxMeshLineWidth->setRange(1, 100);
+  gl1->addWidget(boxMeshLineWidth, 1, 1);
+
+  gl1->addWidget(new QLabel(tr("Resolution")), 2, 0);
+  boxResolution = new QSpinBox();
+  boxResolution->setRange(1, 100);
+  boxResolution->setSpecialValueText("1 (all data)");
+  gl1->addWidget(boxResolution, 2, 1);
+
+  gl1->addWidget(new QLabel(tr("Numbers Font")), 3, 0);
+  btnNumbersFont = new QPushButton(tr("&Choose Font"));
+  gl1->addWidget(btnNumbersFont, 3, 1);
+
+  gl1->addWidget(new QLabel(tr("Distance labels - axis")), 4, 0);
+  boxDistance = new QSpinBox();
+  boxDistance->setRange(0, 1000);
+  boxDistance->setSingleStep(5);
+  gl1->addWidget(boxDistance, 4, 1);
+  gl1->setRowStretch(5, 1);
+
+  QGroupBox *gb1 = new QGroupBox();
+  gb1->setLayout(gl1);
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("Zoom (%)")), 0, 0);
+  boxZoom = new QSpinBox();
+  boxZoom->setRange(1, 10000);
+  boxZoom->setSingleStep(10);
+
+  gl2->addWidget(boxZoom, 0, 1);
+  gl2->addWidget(new QLabel(tr("X Zoom (%)")), 1, 0);
+  boxXScale = new QSpinBox();
+  boxXScale->setRange(1, 10000);
+  boxXScale->setSingleStep(10);
+  gl2->addWidget(boxXScale, 1, 1);
+
+  gl2->addWidget(new QLabel(tr("Y Zoom (%)")), 2, 0);
+  boxYScale = new QSpinBox();
+  boxYScale->setRange(1, 10000);
+  boxYScale->setSingleStep(10);
+  gl2->addWidget(boxYScale, 2, 1);
+
+  gl2->addWidget(new QLabel(tr("Z Zoom (%)")), 3, 0);
+  boxZScale = new QSpinBox();
+  boxZScale->setRange(1, 10000);
+  boxZScale->setSingleStep(10);
+  gl2->addWidget(boxZScale, 3, 1);
+  gl2->setRowStretch(4, 1);
+
+  QGroupBox *gb2 = new QGroupBox();
+  gb2->setLayout(gl2);
+
+  QHBoxLayout *hl = new QHBoxLayout();
+  hl->addWidget(gb1);
+  hl->addWidget(gb2);
+
+  general = new QWidget();
+  general->setLayout(hl);
+  generalDialog->insertTab(-1, general, tr("&General"));
+
+  connect(boxZoom, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
+  connect(boxXScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
+  connect(boxYScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
+  connect(boxZScale, SIGNAL(valueChanged(int)), this, SLOT(changeZoom(int)));
+  connect(btnNumbersFont, SIGNAL(clicked()), this, SLOT(pickNumbersFont()));
 }
 
-void Plot3DDialog::initPointsOptionsStack()
-{
-    QHBoxLayout* hl1 = new QHBoxLayout();
-    hl1->addStretch();
-	hl1->addWidget(new QLabel( tr( "Style" )));
-	boxPointStyle = new QComboBox();
-	boxPointStyle->addItem(tr("Dot"));
-	boxPointStyle->addItem(tr("Cross Hair"));
-	boxPointStyle->addItem(tr("Cone"));
-    hl1->addWidget(boxPointStyle);
-
-	optionStack = new QStackedWidget();
-	optionStack->setFrameShape( QFrame::StyledPanel );
-	optionStack->setFrameShadow( QStackedWidget::Plain );
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel( tr( "Width" )), 0, 0);
-	boxSize = new QLineEdit("5");
-    gl1->addWidget(boxSize, 0, 1);
-
-	gl1->addWidget(new QLabel( tr( "Smooth angles" )), 1, 0);
-	boxSmooth = new QCheckBox();
-	boxSmooth->setChecked(false);
-    gl1->addWidget(boxSmooth, 1, 1);
-
-    dotsPage = new QWidget();
-    dotsPage->setLayout(gl1);
-	optionStack->addWidget(dotsPage);
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel( tr( "Radius" )), 0, 0);
-	boxCrossRad = new QLineEdit("0.01");
-    gl2->addWidget(boxCrossRad, 0, 1);
-	gl2->addWidget(new QLabel(tr( "Line Width")), 1, 0);
-	boxCrossLinewidth = new QLineEdit("1");
-    gl2->addWidget(boxCrossLinewidth, 1, 1);
-	gl2->addWidget(new QLabel(tr( "Smooth line" )), 2, 0);
-	boxCrossSmooth = new QCheckBox();
-    boxCrossSmooth->setChecked(true);
-    gl2->addWidget(boxCrossSmooth, 2, 1);
-	gl2->addWidget(new QLabel(tr( "Boxed" )), 3, 0);
-	boxBoxed = new QCheckBox();
-	boxBoxed->setChecked(false);
-    gl2->addWidget(boxBoxed, 3, 1);
-
-	crossPage = new QWidget();
-    crossPage->setLayout(gl2);
-	optionStack->addWidget(crossPage);
-
-    QGridLayout *gl3 = new QGridLayout();
-    gl3->addWidget(new QLabel( tr( "Width" )), 0, 0);
-	boxConesRad = new QLineEdit("0.5");
-    gl3->addWidget(boxConesRad, 0, 1);
-    gl3->addWidget(new QLabel( tr( "Quality" )), 1, 0);
-	boxQuality = new QSpinBox();
-    boxQuality->setRange(0, 40);
-	boxQuality->setValue(32);
-    gl3->addWidget(boxQuality, 1, 1);
-
-    conesPage = new QWidget();
-    conesPage->setLayout(gl3);
-	optionStack->addWidget(conesPage);
-
-	QVBoxLayout* vl = new QVBoxLayout();
-    vl->addLayout(hl1);
-    vl->addWidget(optionStack);
-
-    points = new QWidget();
-    points->setLayout(vl);
-
-	generalDialog->insertTab(4, points, tr( "Points" ));
-	connect( boxPointStyle, SIGNAL( activated(int) ), optionStack, SLOT( setCurrentIndex(int) ) );
+void Plot3DDialog::initPointsOptionsStack() {
+  QHBoxLayout *hl1 = new QHBoxLayout();
+  hl1->addStretch();
+  hl1->addWidget(new QLabel(tr("Style")));
+  boxPointStyle = new QComboBox();
+  boxPointStyle->addItem(tr("Dot"));
+  boxPointStyle->addItem(tr("Cross Hair"));
+  boxPointStyle->addItem(tr("Cone"));
+  hl1->addWidget(boxPointStyle);
+
+  optionStack = new QStackedWidget();
+  optionStack->setFrameShape(QFrame::StyledPanel);
+  optionStack->setFrameShadow(QStackedWidget::Plain);
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Width")), 0, 0);
+  boxSize = new QLineEdit("5");
+  gl1->addWidget(boxSize, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("Smooth angles")), 1, 0);
+  boxSmooth = new QCheckBox();
+  boxSmooth->setChecked(false);
+  gl1->addWidget(boxSmooth, 1, 1);
+
+  dotsPage = new QWidget();
+  dotsPage->setLayout(gl1);
+  optionStack->addWidget(dotsPage);
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("Radius")), 0, 0);
+  boxCrossRad = new QLineEdit("0.01");
+  gl2->addWidget(boxCrossRad, 0, 1);
+  gl2->addWidget(new QLabel(tr("Line Width")), 1, 0);
+  boxCrossLinewidth = new QLineEdit("1");
+  gl2->addWidget(boxCrossLinewidth, 1, 1);
+  gl2->addWidget(new QLabel(tr("Smooth line")), 2, 0);
+  boxCrossSmooth = new QCheckBox();
+  boxCrossSmooth->setChecked(true);
+  gl2->addWidget(boxCrossSmooth, 2, 1);
+  gl2->addWidget(new QLabel(tr("Boxed")), 3, 0);
+  boxBoxed = new QCheckBox();
+  boxBoxed->setChecked(false);
+  gl2->addWidget(boxBoxed, 3, 1);
+
+  crossPage = new QWidget();
+  crossPage->setLayout(gl2);
+  optionStack->addWidget(crossPage);
+
+  QGridLayout *gl3 = new QGridLayout();
+  gl3->addWidget(new QLabel(tr("Width")), 0, 0);
+  boxConesRad = new QLineEdit("0.5");
+  gl3->addWidget(boxConesRad, 0, 1);
+  gl3->addWidget(new QLabel(tr("Quality")), 1, 0);
+  boxQuality = new QSpinBox();
+  boxQuality->setRange(0, 40);
+  boxQuality->setValue(32);
+  gl3->addWidget(boxQuality, 1, 1);
+
+  conesPage = new QWidget();
+  conesPage->setLayout(gl3);
+  optionStack->addWidget(conesPage);
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  vl->addLayout(hl1);
+  vl->addWidget(optionStack);
+
+  points = new QWidget();
+  points->setLayout(vl);
+
+  generalDialog->insertTab(4, points, tr("Points"));
+  connect(boxPointStyle, SIGNAL(activated(int)), optionStack,
+          SLOT(setCurrentIndex(int)));
 }
 
-void Plot3DDialog::setPlot(Graph3D *g)
-{
-	if (!g)
-		return;
-
-	d_plot = g;
-
-	btnFromColor->setColor(g->minDataColor());
-	btnToColor->setColor(g->maxDataColor());
-	btnTitleColor->setColor(g->titleColor());
-	btnMesh->setColor(g->meshColor());
-	btnAxes->setColor(g->axesColor());
-	btnNumbers->setColor(g->numColor());
-	btnLabels->setColor(g->labelColor());
-	btnBackground->setColor(g->bgColor());
-	btnGrid->setColor(g->gridColor());
-
-	boxMeshLineWidth->setValue(g->meshLineWidth());
-	boxTransparency->setValue(static_cast<int>(100*g->transparency()));
-
-	boxTitle->setText(g->plotTitle());
-	titleFont = g->titleFont();
-
-    xScale = d_plot->xScale();
-    yScale = d_plot->yScale();
-    zScale = d_plot->zScale();
-    zoom   = d_plot->zoom();
-
-	boxZoom->setValue(100);
-	boxXScale->setValue(100);
-	boxYScale->setValue(100);
-	boxZScale->setValue(100);
-
-	boxResolution->setValue(g->resolution());
-	boxLegend->setChecked(g->isLegendOn());
-	boxOrthogonal->setChecked(g->isOrthogonal());
-
-	labels = g->axesLabels();
-	boxLabel->setText(labels[0]);
-
-	tickLengths = g->axisTickLengths();
-	boxMajorLength->setText(tickLengths[0]);
-	boxMinorLength->setText(tickLengths[1]);
-
-	xAxisFont = g->xAxisLabelFont();
-	yAxisFont = g->yAxisLabelFont();
-	zAxisFont = g->zAxisLabelFont();
-
-	scales = g->scaleLimits();
-	boxFrom->setText(scales[0]);
-	boxTo->setText(scales[1]);
-	boxMajors->setValue(scales[2].toInt());
-	boxMinors->setValue(scales[3].toInt());
-	boxType->setCurrentIndex(scales[4].toInt());
-
-	boxDistance->setValue(g->labelsDistance());
-	numbersFont = g->numbersFont();
-
-	if (g->coordStyle() == Qwt3D::NOCOORD){
-		TicksGroupBox->setDisabled(true);
-		generalDialog->setTabEnabled(generalDialog->indexOf(axes), false);
-		AxesColorGroupBox->setDisabled(true);
-		boxDistance->setDisabled(true);
-		btnNumbersFont->setDisabled(true);
-	}
-
-	Qwt3D::PLOTSTYLE style = g->plotStyle();
-	Graph3D::PointStyle pt = g->pointType();
-
-	if ( style == Qwt3D::USER ){
-			switch (pt)
-			{
-				case Graph3D::None :
-					break;
-
-				case Graph3D::Dots :
-					disableMeshOptions();
-					initPointsOptionsStack();
-					showPointsTab (g->pointsSize(), g->smoothPoints());
-					break;
-
-				case Graph3D::VerticalBars :
-					showBarsTab(g->barsRadius());
-					break;
-
-				case Graph3D::HairCross :
-					disableMeshOptions();
-					initPointsOptionsStack();
-					showCrossHairTab (g->crossHairRadius(), g->crossHairLinewidth(),
-							g->smoothCrossHair(), g->boxedCrossHair());
-					break;
-
-				case Graph3D::Cones :
-					disableMeshOptions();
-					initPointsOptionsStack();
-					showConesTab(g->coneRadius(), g->coneQuality());
-					break;
-			}
-		}
-		else if ( style == Qwt3D::FILLED )
-			disableMeshOptions();
-		else if (style == Qwt3D::HIDDENLINE || style == Qwt3D::WIREFRAME)
-			boxLegend->setDisabled(true);
-
-		if (g->grids() == 0)
-			btnGrid->setDisabled(true);
-
-		if (g->userFunction() || g->parametricSurface())
-			btnTable->hide();
-		else if (g->table())
-            btnTable->setText(tr("&Worksheet"));
-		else if (g->matrix())
-			btnTable->setText(tr("&Matrix"));
-
-	connect( boxMeshLineWidth, SIGNAL(valueChanged(double)), d_plot, SLOT(setMeshLineWidth(double)));
-	connect( boxOrthogonal, SIGNAL(toggled(bool)), d_plot, SLOT(setOrthogonal(bool)));
-	connect( boxLegend, SIGNAL(toggled(bool)), d_plot, SLOT(showColorLegend(bool)));
-    connect( boxResolution, SIGNAL(valueChanged(int)), d_plot, SLOT(setResolution(int)));
-	connect( boxDistance, SIGNAL(valueChanged(int)), d_plot, SLOT(setLabelsDistance(int)));
+void Plot3DDialog::setPlot(Graph3D *g) {
+  if (!g)
+    return;
+
+  d_plot = g;
+
+  btnFromColor->setColor(g->minDataColor());
+  btnToColor->setColor(g->maxDataColor());
+  btnTitleColor->setColor(g->titleColor());
+  btnMesh->setColor(g->meshColor());
+  btnAxes->setColor(g->axesColor());
+  btnNumbers->setColor(g->numColor());
+  btnLabels->setColor(g->labelColor());
+  btnBackground->setColor(g->bgColor());
+  btnGrid->setColor(g->gridColor());
+
+  boxMeshLineWidth->setValue(g->meshLineWidth());
+  boxTransparency->setValue(static_cast<int>(100 * g->transparency()));
+
+  boxTitle->setText(g->plotTitle());
+  titleFont = g->titleFont();
+
+  xScale = d_plot->xScale();
+  yScale = d_plot->yScale();
+  zScale = d_plot->zScale();
+  zoom = d_plot->zoom();
+
+  boxZoom->setValue(100);
+  boxXScale->setValue(100);
+  boxYScale->setValue(100);
+  boxZScale->setValue(100);
+
+  boxResolution->setValue(g->resolution());
+  boxLegend->setChecked(g->isLegendOn());
+  boxOrthogonal->setChecked(g->isOrthogonal());
+
+  labels = g->axesLabels();
+  boxLabel->setText(labels[0]);
+
+  tickLengths = g->axisTickLengths();
+  boxMajorLength->setText(tickLengths[0]);
+  boxMinorLength->setText(tickLengths[1]);
+
+  xAxisFont = g->xAxisLabelFont();
+  yAxisFont = g->yAxisLabelFont();
+  zAxisFont = g->zAxisLabelFont();
+
+  scales = g->scaleLimits();
+  boxFrom->setText(scales[0]);
+  boxTo->setText(scales[1]);
+  boxMajors->setValue(scales[2].toInt());
+  boxMinors->setValue(scales[3].toInt());
+  boxType->setCurrentIndex(scales[4].toInt());
+
+  boxDistance->setValue(g->labelsDistance());
+  numbersFont = g->numbersFont();
+
+  if (g->coordStyle() == Qwt3D::NOCOORD) {
+    TicksGroupBox->setDisabled(true);
+    generalDialog->setTabEnabled(generalDialog->indexOf(axes), false);
+    AxesColorGroupBox->setDisabled(true);
+    boxDistance->setDisabled(true);
+    btnNumbersFont->setDisabled(true);
+  }
+
+  Qwt3D::PLOTSTYLE style = g->plotStyle();
+  Graph3D::PointStyle pt = g->pointType();
+
+  if (style == Qwt3D::USER) {
+    switch (pt) {
+    case Graph3D::None:
+      break;
+
+    case Graph3D::Dots:
+      disableMeshOptions();
+      initPointsOptionsStack();
+      showPointsTab(g->pointsSize(), g->smoothPoints());
+      break;
+
+    case Graph3D::VerticalBars:
+      showBarsTab(g->barsRadius());
+      break;
+
+    case Graph3D::HairCross:
+      disableMeshOptions();
+      initPointsOptionsStack();
+      showCrossHairTab(g->crossHairRadius(), g->crossHairLinewidth(),
+                       g->smoothCrossHair(), g->boxedCrossHair());
+      break;
+
+    case Graph3D::Cones:
+      disableMeshOptions();
+      initPointsOptionsStack();
+      showConesTab(g->coneRadius(), g->coneQuality());
+      break;
+    }
+  } else if (style == Qwt3D::FILLED)
+    disableMeshOptions();
+  else if (style == Qwt3D::HIDDENLINE || style == Qwt3D::WIREFRAME)
+    boxLegend->setDisabled(true);
+
+  if (g->grids() == 0)
+    btnGrid->setDisabled(true);
+
+  if (g->userFunction() || g->parametricSurface())
+    btnTable->hide();
+  else if (g->table())
+    btnTable->setText(tr("&Worksheet"));
+  else if (g->matrix())
+    btnTable->setText(tr("&Matrix"));
+
+  connect(boxMeshLineWidth, SIGNAL(valueChanged(double)), d_plot,
+          SLOT(setMeshLineWidth(double)));
+  connect(boxOrthogonal, SIGNAL(toggled(bool)), d_plot,
+          SLOT(setOrthogonal(bool)));
+  connect(boxLegend, SIGNAL(toggled(bool)), d_plot,
+          SLOT(showColorLegend(bool)));
+  connect(boxResolution, SIGNAL(valueChanged(int)), d_plot,
+          SLOT(setResolution(int)));
+  connect(boxDistance, SIGNAL(valueChanged(int)), d_plot,
+          SLOT(setLabelsDistance(int)));
 }
 
-void Plot3DDialog::worksheet()
-{
-	d_plot->showWorksheet();
-	close();
+void Plot3DDialog::worksheet() {
+  d_plot->showWorksheet();
+  close();
 }
 
-void Plot3DDialog::showBarsTab(double rad)
-{
-	bars = new QWidget( generalDialog );
+void Plot3DDialog::showBarsTab(double rad) {
+  bars = new QWidget(generalDialog);
 
-	QHBoxLayout* hb = new QHBoxLayout(bars);
-	hb->addWidget(new QLabel( tr( "Width" )));
+  QHBoxLayout *hb = new QHBoxLayout(bars);
+  hb->addWidget(new QLabel(tr("Width")));
 
-	boxBarsRad = new QLineEdit();
-	boxBarsRad->setText(QString::number(rad));
-	hb->addWidget(boxBarsRad);
+  boxBarsRad = new QLineEdit();
+  boxBarsRad->setText(QString::number(rad));
+  hb->addWidget(boxBarsRad);
 
-	generalDialog->insertTab(4, bars, tr( "Bars" ));
+  generalDialog->insertTab(4, bars, tr("Bars"));
 }
 
-void Plot3DDialog::showPointsTab(double rad, bool smooth)
-{
-	boxPointStyle->setCurrentIndex(0);
-	boxSize->setText(QString::number(rad));
-	boxSmooth->setChecked(smooth);
-	optionStack->setCurrentIndex(0);
+void Plot3DDialog::showPointsTab(double rad, bool smooth) {
+  boxPointStyle->setCurrentIndex(0);
+  boxSize->setText(QString::number(rad));
+  boxSmooth->setChecked(smooth);
+  optionStack->setCurrentIndex(0);
 }
 
-void Plot3DDialog::showConesTab(double rad, int quality)
-{
-	boxPointStyle->setCurrentIndex(2);
-	boxConesRad->setText(QString::number(rad));
-	boxQuality->setValue(quality);
-	optionStack->setCurrentIndex (2);
+void Plot3DDialog::showConesTab(double rad, int quality) {
+  boxPointStyle->setCurrentIndex(2);
+  boxConesRad->setText(QString::number(rad));
+  boxQuality->setValue(quality);
+  optionStack->setCurrentIndex(2);
 }
 
-void Plot3DDialog::showCrossHairTab(double rad, double linewidth, bool smooth, bool boxed)
-{
-	boxPointStyle->setCurrentIndex(1);
-	boxCrossRad->setText(QString::number(rad));
-	boxCrossLinewidth->setText(QString::number(linewidth));
-	boxCrossSmooth->setChecked(smooth);
-	boxBoxed->setChecked(boxed);
-	optionStack->setCurrentIndex(1);
+void Plot3DDialog::showCrossHairTab(double rad, double linewidth, bool smooth,
+                                    bool boxed) {
+  boxPointStyle->setCurrentIndex(1);
+  boxCrossRad->setText(QString::number(rad));
+  boxCrossLinewidth->setText(QString::number(linewidth));
+  boxCrossSmooth->setChecked(smooth);
+  boxBoxed->setChecked(boxed);
+  optionStack->setCurrentIndex(1);
 }
 
-void Plot3DDialog::disableMeshOptions()
-{
-	btnMesh->setDisabled(true);
-	boxMeshLineWidth->setDisabled(true);
+void Plot3DDialog::disableMeshOptions() {
+  btnMesh->setDisabled(true);
+  boxMeshLineWidth->setDisabled(true);
 }
 
-void Plot3DDialog::pickDataColorMap()
-{
+void Plot3DDialog::pickDataColorMap() {
   QString fileselection = MantidColorMap::loadMapDialog("", this);
   if (!fileselection.isEmpty())
     d_plot->setDataColorMap(fileselection);
 }
 
-void Plot3DDialog::pickTitleFont()
-{
-	bool ok;
-	QFont font = QFontDialog::getFont(&ok,titleFont,this);
-	if ( ok ) {
-		titleFont = font;
-	} else {
-		return;
-	}
+void Plot3DDialog::pickTitleFont() {
+  bool ok;
+  QFont font = QFontDialog::getFont(&ok, titleFont, this);
+  if (ok) {
+    titleFont = font;
+  } else {
+    return;
+  }
 }
 
-void Plot3DDialog::pickNumbersFont()
-{
-	bool ok;
-	QFont font = QFontDialog::getFont(&ok,numbersFont,this);
-	if ( ok ) {
-		numbersFont = font;
-	} else {
-		return;
-	}
+void Plot3DDialog::pickNumbersFont() {
+  bool ok;
+  QFont font = QFontDialog::getFont(&ok, numbersFont, this);
+  if (ok) {
+    numbersFont = font;
+  } else {
+    return;
+  }
 }
 
-void Plot3DDialog::viewAxisOptions(int axis)
-{
-	boxLabel->setText(labels[axis]);
+void Plot3DDialog::viewAxisOptions(int axis) {
+  boxLabel->setText(labels[axis]);
 
-	boxMajorLength->setText(tickLengths[2*axis+0]);
-	boxMinorLength->setText(tickLengths[2*axis+1]);
+  boxMajorLength->setText(tickLengths[2 * axis + 0]);
+  boxMinorLength->setText(tickLengths[2 * axis + 1]);
 }
 
-void Plot3DDialog::viewScaleLimits(int axis)
-{
-	boxFrom->setText(scales[5*axis+0]);
-	boxTo->setText(scales[5*axis+1]);
-	boxMajors->setValue(scales[5*axis+2].toInt());
-	boxMinors->setValue(scales[5*axis+3].toInt());
-	boxType->setCurrentIndex(scales[5*axis+4].toInt());
+void Plot3DDialog::viewScaleLimits(int axis) {
+  boxFrom->setText(scales[5 * axis + 0]);
+  boxTo->setText(scales[5 * axis + 1]);
+  boxMajors->setValue(scales[5 * axis + 2].toInt());
+  boxMinors->setValue(scales[5 * axis + 3].toInt());
+  boxType->setCurrentIndex(scales[5 * axis + 4].toInt());
 }
 
-void Plot3DDialog::accept()
-{
-	if (updatePlot())
-		close();
+void Plot3DDialog::accept() {
+  if (updatePlot())
+    close();
 }
 
-void Plot3DDialog::changeZoom(int)
-{
-	if (generalDialog->currentWidget() != static_cast<QWidget*>(general))
-		return;
-
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	d_plot->setZoom(zoom*boxZoom->value()*0.01);
-    d_plot->setScale(xScale*boxXScale->value()*0.01, yScale*boxYScale->value()*0.01, zScale*boxZScale->value()*0.01);
-    d_plot->update();
-    QApplication::restoreOverrideCursor();
+void Plot3DDialog::changeZoom(int) {
+  if (generalDialog->currentWidget() != static_cast<QWidget *>(general))
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  d_plot->setZoom(zoom * boxZoom->value() * 0.01);
+  d_plot->setScale(xScale * boxXScale->value() * 0.01,
+                   yScale * boxYScale->value() * 0.01,
+                   zScale * boxZScale->value() * 0.01);
+  d_plot->update();
+  QApplication::restoreOverrideCursor();
 }
 
-void Plot3DDialog::changeTransparency(int val)
-{
-	if (generalDialog->currentWidget() != static_cast<QWidget*>(colors))
-		return;
+void Plot3DDialog::changeTransparency(int val) {
+  if (generalDialog->currentWidget() != static_cast<QWidget *>(colors))
+    return;
 
-	d_plot->changeTransparency(val*0.01);
-	d_plot->update();
+  d_plot->changeTransparency(val * 0.01);
+  d_plot->update();
 }
 
-bool Plot3DDialog::updatePlot()
-{
-	if (!d_plot)
-		return false;
-
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-    if (!app)
-        return false;
-
-	if (generalDialog->currentWidget()==static_cast<QWidget*>(bars)){
-		d_plot->setBarRadius(boxBarsRad->text().toDouble());
-		d_plot->setBarStyle();
-	} else if (generalDialog->currentWidget() == static_cast<QWidget*>(points)){
-		if (boxPointStyle->currentIndex() == 0) {
-			d_plot->setDotOptions(boxSize->text().toDouble(), boxSmooth->isChecked());
-			d_plot->setDotStyle();
-		} else if (boxPointStyle->currentIndex() == 1){
-			d_plot->setCrossOptions(boxCrossRad->text().toDouble(), boxCrossLinewidth->text().toDouble(),
-					boxCrossSmooth->isChecked(), boxBoxed->isChecked());
-            d_plot->setCrossStyle();
-        } else if (boxPointStyle->currentIndex() == 2) {
-			d_plot->setConeOptions(boxConesRad->text().toDouble(), boxQuality->value());
-			d_plot->setConeStyle();
-        }
-
-        app->custom3DActions(d_plot);
-	} else if (generalDialog->currentWidget()==static_cast<QWidget*>(title)){
-		d_plot->setTitle(boxTitle->toPlainText().remove("\n"), btnTitleColor->color(), titleFont);
-	} else if (generalDialog->currentWidget()==static_cast<QWidget*>(colors)){
-		d_plot->changeTransparency(boxTransparency->value()*0.01);
-		d_plot->setDataColors(btnFromColor->color(), btnToColor->color());
-		d_plot->setMeshColor(btnMesh->color());
-		d_plot->setAxesColor(btnAxes->color());
-		d_plot->setNumbersColor(btnNumbers->color());
-		d_plot->setLabelsColor(btnLabels->color());
-		d_plot->setBackgroundColor(btnBackground->color());
-		d_plot->setGridColor(btnGrid->color());
-	} else if (generalDialog->currentWidget()==static_cast<QWidget*>(general)){
-		d_plot->showColorLegend(boxLegend->isChecked());
-		d_plot->setResolution(boxResolution->value());
-		d_plot->setMeshLineWidth(boxMeshLineWidth->value());
-		d_plot->setLabelsDistance(boxDistance->value());
-		d_plot->setNumbersFont(numbersFont);
-		d_plot->setZoom(zoom*boxZoom->value()*0.01);
-		d_plot->setScale(xScale*boxXScale->value()*0.01, yScale*boxYScale->value()*0.01, zScale*boxZScale->value()*0.01);
-	} else if (generalDialog->currentWidget()==static_cast<QWidget*>(scale)){
-		int axis = axesList->currentRow();
-		QString from=boxFrom->text().toLower();
-		QString to=boxTo->text().toLower();
-		double start, end;
-		try {
-			MyParser parser;
-			parser.SetExpr(from.toAscii().constData());
-			start = parser.Eval();
-		} catch(mu::ParserError &e){
-			QMessageBox::critical(0,tr("MantidPlot - Start limit error"),  QString::fromStdString(e.GetMsg()));
-			boxFrom->setFocus();
-			return false;
-		}
-
-		try {
-			MyParser parser;
-			parser.SetExpr(to.toAscii().constData());
-			end = parser.Eval();
-		} catch(mu::ParserError &e){
-			QMessageBox::critical(0,tr("MantidPlot - End limit error"), QString::fromStdString(e.GetMsg()));
-			boxTo->setFocus();
-			return false;
-		}
-
-        /*double xsc = d_plot->xScale();
-        double ysc = d_plot->yScale();
-        double zsc = d_plot->zScale();
-        if (axis == 2)
-        {
-            double start0 = scales[0].toDouble();
-            double end0 = scales[1].toDouble();
-            zsc *= (end0 - start0)/(end - start);
-            QMessageBox::information(this,"OK","OK");
-        }*/
-
-        d_plot->updateScale(axis, scaleOptions(axis, start, end, boxMajors->text(), boxMinors->text()));
-        //d_plot->setScale(xsc,ysc,zsc*0.1);
-	} else if (generalDialog->currentWidget()==static_cast<QWidget*>(axes)){
-		int axis = axesList2->currentRow();
-		labels[axis] = boxLabel->toPlainText();
-
-		switch(axis)
-		{
-		case 0:
-			d_plot->setXAxisLabel(boxLabel->toPlainText().remove("\n"));
-			d_plot->setXAxisLabelFont(axisFont(axis));
-			d_plot->setXAxisTickLength(boxMajorLength->text().toDouble(), boxMinorLength->text().toDouble());
-		break;
-		case 1:
-			d_plot->setYAxisLabel(boxLabel->toPlainText().remove("\n"));
-			d_plot->setYAxisLabelFont(axisFont(axis));
-			d_plot->setYAxisTickLength(boxMajorLength->text().toDouble(), boxMinorLength->text().toDouble());
-		break;
-		case 2:
-			d_plot->setZAxisLabel(boxLabel->toPlainText().remove("\n"));
-			d_plot->setZAxisLabelFont(axisFont(axis));
-			d_plot->setZAxisTickLength(boxMajorLength->text().toDouble(), boxMinorLength->text().toDouble());
-		break;
-		}
-	}
-
-    d_plot->update();
-    app->modifiedProject(d_plot);
-	return true;
+bool Plot3DDialog::updatePlot() {
+  if (!d_plot)
+    return false;
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return false;
+
+  if (generalDialog->currentWidget() == static_cast<QWidget *>(bars)) {
+    d_plot->setBarRadius(boxBarsRad->text().toDouble());
+    d_plot->setBarStyle();
+  } else if (generalDialog->currentWidget() == static_cast<QWidget *>(points)) {
+    if (boxPointStyle->currentIndex() == 0) {
+      d_plot->setDotOptions(boxSize->text().toDouble(), boxSmooth->isChecked());
+      d_plot->setDotStyle();
+    } else if (boxPointStyle->currentIndex() == 1) {
+      d_plot->setCrossOptions(
+          boxCrossRad->text().toDouble(), boxCrossLinewidth->text().toDouble(),
+          boxCrossSmooth->isChecked(), boxBoxed->isChecked());
+      d_plot->setCrossStyle();
+    } else if (boxPointStyle->currentIndex() == 2) {
+      d_plot->setConeOptions(boxConesRad->text().toDouble(),
+                             boxQuality->value());
+      d_plot->setConeStyle();
+    }
+
+    app->custom3DActions(d_plot);
+  } else if (generalDialog->currentWidget() == static_cast<QWidget *>(title)) {
+    d_plot->setTitle(boxTitle->toPlainText().remove("\n"),
+                     btnTitleColor->color(), titleFont);
+  } else if (generalDialog->currentWidget() == static_cast<QWidget *>(colors)) {
+    d_plot->changeTransparency(boxTransparency->value() * 0.01);
+    d_plot->setDataColors(btnFromColor->color(), btnToColor->color());
+    d_plot->setMeshColor(btnMesh->color());
+    d_plot->setAxesColor(btnAxes->color());
+    d_plot->setNumbersColor(btnNumbers->color());
+    d_plot->setLabelsColor(btnLabels->color());
+    d_plot->setBackgroundColor(btnBackground->color());
+    d_plot->setGridColor(btnGrid->color());
+  } else if (generalDialog->currentWidget() ==
+             static_cast<QWidget *>(general)) {
+    d_plot->showColorLegend(boxLegend->isChecked());
+    d_plot->setResolution(boxResolution->value());
+    d_plot->setMeshLineWidth(boxMeshLineWidth->value());
+    d_plot->setLabelsDistance(boxDistance->value());
+    d_plot->setNumbersFont(numbersFont);
+    d_plot->setZoom(zoom * boxZoom->value() * 0.01);
+    d_plot->setScale(xScale * boxXScale->value() * 0.01,
+                     yScale * boxYScale->value() * 0.01,
+                     zScale * boxZScale->value() * 0.01);
+  } else if (generalDialog->currentWidget() == static_cast<QWidget *>(scale)) {
+    int axis = axesList->currentRow();
+    QString from = boxFrom->text().toLower();
+    QString to = boxTo->text().toLower();
+    double start, end;
+    try {
+      MyParser parser;
+      parser.SetExpr(from.toAscii().constData());
+      start = parser.Eval();
+    } catch (mu::ParserError &e) {
+      QMessageBox::critical(0, tr("MantidPlot - Start limit error"),
+                            QString::fromStdString(e.GetMsg()));
+      boxFrom->setFocus();
+      return false;
+    }
+
+    try {
+      MyParser parser;
+      parser.SetExpr(to.toAscii().constData());
+      end = parser.Eval();
+    } catch (mu::ParserError &e) {
+      QMessageBox::critical(0, tr("MantidPlot - End limit error"),
+                            QString::fromStdString(e.GetMsg()));
+      boxTo->setFocus();
+      return false;
+    }
+
+    /*double xsc = d_plot->xScale();
+    double ysc = d_plot->yScale();
+    double zsc = d_plot->zScale();
+    if (axis == 2)
+    {
+        double start0 = scales[0].toDouble();
+        double end0 = scales[1].toDouble();
+        zsc *= (end0 - start0)/(end - start);
+        QMessageBox::information(this,"OK","OK");
+    }*/
+
+    d_plot->updateScale(axis, scaleOptions(axis, start, end, boxMajors->text(),
+                                           boxMinors->text()));
+    // d_plot->setScale(xsc,ysc,zsc*0.1);
+  } else if (generalDialog->currentWidget() == static_cast<QWidget *>(axes)) {
+    int axis = axesList2->currentRow();
+    labels[axis] = boxLabel->toPlainText();
+
+    switch (axis) {
+    case 0:
+      d_plot->setXAxisLabel(boxLabel->toPlainText().remove("\n"));
+      d_plot->setXAxisLabelFont(axisFont(axis));
+      d_plot->setXAxisTickLength(boxMajorLength->text().toDouble(),
+                                 boxMinorLength->text().toDouble());
+      break;
+    case 1:
+      d_plot->setYAxisLabel(boxLabel->toPlainText().remove("\n"));
+      d_plot->setYAxisLabelFont(axisFont(axis));
+      d_plot->setYAxisTickLength(boxMajorLength->text().toDouble(),
+                                 boxMinorLength->text().toDouble());
+      break;
+    case 2:
+      d_plot->setZAxisLabel(boxLabel->toPlainText().remove("\n"));
+      d_plot->setZAxisLabelFont(axisFont(axis));
+      d_plot->setZAxisTickLength(boxMajorLength->text().toDouble(),
+                                 boxMinorLength->text().toDouble());
+      break;
+    }
+  }
+
+  d_plot->update();
+  app->modifiedProject(d_plot);
+  return true;
 }
 
 QStringList Plot3DDialog::scaleOptions(int axis, double start, double end,
-		const QString& majors, const QString& minors)
-{
-	QStringList l;
-	l<<QString::number(start);
-	l<<QString::number(end);
-	l<<majors;
-	l<<minors;
-	l<<QString::number(boxType->currentIndex());
-
-	for (int i=0;i<5;i++)
-		scales[5*axis+i]=l[i];
-	return l;
+                                       const QString &majors,
+                                       const QString &minors) {
+  QStringList l;
+  l << QString::number(start);
+  l << QString::number(end);
+  l << majors;
+  l << minors;
+  l << QString::number(boxType->currentIndex());
+
+  for (int i = 0; i < 5; i++)
+    scales[5 * axis + i] = l[i];
+  return l;
 }
 
-void Plot3DDialog::pickAxisLabelFont()
-{
-	bool ok;
-	QFont font;
-	switch(axesList2->currentRow())
-	{
-		case 0:
-			font= QFontDialog::getFont(&ok,xAxisFont,this);
-			if ( ok )
-				xAxisFont=font;
-			else
-				return;
-			break;
-
-		case 1:
-			font= QFontDialog::getFont(&ok,yAxisFont,this);
-			if ( ok )
-				yAxisFont=font;
-			else
-				return;
-			break;
-
-		case 2:
-			font= QFontDialog::getFont(&ok,zAxisFont,this);
-			if ( ok )
-				zAxisFont=font;
-			else
-				return;
-			break;
-	}
+void Plot3DDialog::pickAxisLabelFont() {
+  bool ok;
+  QFont font;
+  switch (axesList2->currentRow()) {
+  case 0:
+    font = QFontDialog::getFont(&ok, xAxisFont, this);
+    if (ok)
+      xAxisFont = font;
+    else
+      return;
+    break;
+
+  case 1:
+    font = QFontDialog::getFont(&ok, yAxisFont, this);
+    if (ok)
+      yAxisFont = font;
+    else
+      return;
+    break;
+
+  case 2:
+    font = QFontDialog::getFont(&ok, zAxisFont, this);
+    if (ok)
+      zAxisFont = font;
+    else
+      return;
+    break;
+  }
 }
 
-QFont Plot3DDialog::axisFont(int axis)
-{
-	QFont f;
-	switch(axis)
-	{
-		case 0:
-			f=xAxisFont;
-			break;
-
-		case 1:
-			f=yAxisFont;
-			break;
-
-		case 2:
-			f=zAxisFont;
-			break;
-	}
-	return f;
+QFont Plot3DDialog::axisFont(int axis) {
+  QFont f;
+  switch (axis) {
+  case 0:
+    f = xAxisFont;
+    break;
+
+  case 1:
+    f = yAxisFont;
+    break;
+
+  case 2:
+    f = zAxisFont;
+    break;
+  }
+  return f;
 }
 
-void Plot3DDialog::showGeneralTab()
-{
-	generalDialog->setCurrentWidget (general);
+void Plot3DDialog::showGeneralTab() {
+  generalDialog->setCurrentWidget(general);
 }
 
-void Plot3DDialog::showTitleTab()
-{
-	generalDialog->setCurrentWidget (title);
-}
+void Plot3DDialog::showTitleTab() { generalDialog->setCurrentWidget(title); }
 
-void Plot3DDialog::showAxisTab()
-{
-	generalDialog->setCurrentWidget (axes);
-}
+void Plot3DDialog::showAxisTab() { generalDialog->setCurrentWidget(axes); }
diff --git a/MantidPlot/src/Plot3DDialog.h b/MantidPlot/src/Plot3DDialog.h
index e6b420cd08ea2617054a470148335cd739b9e1b9..52484c0f2499c8bc113190cf3662b4c3d1cce5c4 100644
--- a/MantidPlot/src/Plot3DDialog.h
+++ b/MantidPlot/src/Plot3DDialog.h
@@ -51,83 +51,81 @@ class TextFormatButtons;
 using namespace Qwt3D;
 
 //! Surface plot options dialog
-class Plot3DDialog : public QDialog
-{
-    Q_OBJECT
+class Plot3DDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    Plot3DDialog( QWidget* parent, Qt::WFlags fl = 0 );
-	void setPlot(Graph3D *);
+  Plot3DDialog(QWidget *parent, Qt::WFlags fl = 0);
+  void setPlot(Graph3D *);
 
-	void showTitleTab();
-	void showAxisTab();
-	void showGeneralTab();
+  void showTitleTab();
+  void showAxisTab();
+  void showGeneralTab();
 
 private slots:
   void accept() override;
-        bool updatePlot();
-
-	void pickTitleFont();
-	void viewAxisOptions(int axis);
-	QFont axisFont(int axis);
-	void pickAxisLabelFont();
-	void pickNumbersFont();
-
-	QStringList scaleOptions(int axis, double start, double end,
-							const QString& majors, const QString& minors);
-	void viewScaleLimits(int axis);
-	void disableMeshOptions();
-	void showBarsTab(double rad);
-	void showPointsTab(double rad, bool smooth);
-	void showConesTab(double rad, int quality);
-	void showCrossHairTab(double rad, double linewidth, bool smooth, bool boxed);
-
-	void worksheet();
-
-	void initPointsOptionsStack();
-	void changeZoom(int);
-	void changeTransparency(int val);
-    void pickDataColorMap();
+  bool updatePlot();
+
+  void pickTitleFont();
+  void viewAxisOptions(int axis);
+  QFont axisFont(int axis);
+  void pickAxisLabelFont();
+  void pickNumbersFont();
+
+  QStringList scaleOptions(int axis, double start, double end,
+                           const QString &majors, const QString &minors);
+  void viewScaleLimits(int axis);
+  void disableMeshOptions();
+  void showBarsTab(double rad);
+  void showPointsTab(double rad, bool smooth);
+  void showConesTab(double rad, int quality);
+  void showCrossHairTab(double rad, double linewidth, bool smooth, bool boxed);
+
+  void worksheet();
+
+  void initPointsOptionsStack();
+  void changeZoom(int);
+  void changeTransparency(int val);
+  void pickDataColorMap();
 
 private:
-    void initScalesPage();
-	void initAxesPage();
-	void initTitlePage();
-	void initColorsPage();
-	void initGeneralPage();
-
-    Graph3D *d_plot;
-	QFont titleFont, xAxisFont,yAxisFont,zAxisFont, numbersFont;
-	QStringList labels, scales, tickLengths;
-    QDoubleSpinBox *boxMeshLineWidth;
-    QPushButton* buttonApply;
-    QPushButton* buttonOk;
-    QPushButton* buttonCancel;
-	QPushButton *btnTitleFont, *btnLabelFont;
-    QPushButton *btnNumbersFont, *btnTable, *btnColorMap;
-	ColorButton *btnBackground, *btnMesh, *btnAxes, *btnTitleColor, *btnLabels;
-	ColorButton *btnFromColor, *btnToColor, *btnNumbers, *btnGrid;
-    QTabWidget* generalDialog;
-	QWidget *scale, *colors, *general, *axes, *title, *bars, *points;
-	QLineEdit *boxFrom, *boxTo;
-	QTextEdit *boxTitle, *boxLabel;
-	QSpinBox *boxMajors, *boxMinors;
-	QGroupBox *TicksGroupBox, *AxesColorGroupBox;
-	QSpinBox *boxResolution, *boxDistance, *boxTransparency;
-	QCheckBox *boxLegend, *boxSmooth, *boxBoxed, *boxCrossSmooth, *boxOrthogonal;
-	QListWidget *axesList, *axesList2;
-	QComboBox *boxType, *boxPointStyle;
-	QLineEdit *boxMajorLength, *boxMinorLength, *boxConesRad;
-	QSpinBox *boxZoom, *boxXScale, *boxYScale, *boxZScale, *boxQuality;
-	QLineEdit *boxSize, *boxBarsRad, *boxCrossRad, *boxCrossLinewidth;
-	QStackedWidget *optionStack;
-	QWidget *dotsPage, *conesPage, *crossPage;
-	TextFormatButtons *titleFormatButtons, *axisTitleFormatButtons;
-    double xScale;
-    double yScale;
-    double zScale;
-    double zoom;
-
+  void initScalesPage();
+  void initAxesPage();
+  void initTitlePage();
+  void initColorsPage();
+  void initGeneralPage();
+
+  Graph3D *d_plot;
+  QFont titleFont, xAxisFont, yAxisFont, zAxisFont, numbersFont;
+  QStringList labels, scales, tickLengths;
+  QDoubleSpinBox *boxMeshLineWidth;
+  QPushButton *buttonApply;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *btnTitleFont, *btnLabelFont;
+  QPushButton *btnNumbersFont, *btnTable, *btnColorMap;
+  ColorButton *btnBackground, *btnMesh, *btnAxes, *btnTitleColor, *btnLabels;
+  ColorButton *btnFromColor, *btnToColor, *btnNumbers, *btnGrid;
+  QTabWidget *generalDialog;
+  QWidget *scale, *colors, *general, *axes, *title, *bars, *points;
+  QLineEdit *boxFrom, *boxTo;
+  QTextEdit *boxTitle, *boxLabel;
+  QSpinBox *boxMajors, *boxMinors;
+  QGroupBox *TicksGroupBox, *AxesColorGroupBox;
+  QSpinBox *boxResolution, *boxDistance, *boxTransparency;
+  QCheckBox *boxLegend, *boxSmooth, *boxBoxed, *boxCrossSmooth, *boxOrthogonal;
+  QListWidget *axesList, *axesList2;
+  QComboBox *boxType, *boxPointStyle;
+  QLineEdit *boxMajorLength, *boxMinorLength, *boxConesRad;
+  QSpinBox *boxZoom, *boxXScale, *boxYScale, *boxZScale, *boxQuality;
+  QLineEdit *boxSize, *boxBarsRad, *boxCrossRad, *boxCrossLinewidth;
+  QStackedWidget *optionStack;
+  QWidget *dotsPage, *conesPage, *crossPage;
+  TextFormatButtons *titleFormatButtons, *axisTitleFormatButtons;
+  double xScale;
+  double yScale;
+  double zScale;
+  double zoom;
 };
 
 #endif
diff --git a/MantidPlot/src/PlotCurve.cpp b/MantidPlot/src/PlotCurve.cpp
index c5f353d83e6c39fb4b91899a177b5aa6a47be4c6..e6ba1773f1ebbc72175b034274770482e08e5683 100644
--- a/MantidPlot/src/PlotCurve.cpp
+++ b/MantidPlot/src/PlotCurve.cpp
@@ -50,8 +50,7 @@ using namespace Mantid::API;
 
 PlotCurve::PlotCurve(const QString &name)
     : QwtPlotCurve(name), d_type(0), d_x_offset(0.0), d_y_offset(0.0),
-      d_side_lines(false),
-      d_skip_symbols(1), m_isDistribution(false) {}
+      d_side_lines(false), d_skip_symbols(1), m_isDistribution(false) {}
 
 PlotCurve::PlotCurve(const PlotCurve &c)
     : QObject(), QwtPlotCurve(c.title().text()), d_type(c.d_type),
@@ -308,10 +307,10 @@ void PlotCurve::computeWaterfallOffsets(double &xDataOffset,
       double yRange = plot->axisScaleDiv(Plot::yLeft)->range();
 
       // First compute offsets in a linear scale
-      xDataOffset = index * g->waterfallXOffset() * 0.01 *
-                    xRange / (double)(curves - 1);
-      yDataOffset = index * g->waterfallYOffset() * 0.01 *
-                    yRange / (double)(curves - 1);
+      xDataOffset =
+          index * g->waterfallXOffset() * 0.01 * xRange / (double)(curves - 1);
+      yDataOffset =
+          index * g->waterfallYOffset() * 0.01 * yRange / (double)(curves - 1);
 
       // Corresponding offset on the screen in pixels
       d_x_offset = plot->canvas()->width() * xDataOffset / xRange;
diff --git a/MantidPlot/src/PlotDialog.cpp b/MantidPlot/src/PlotDialog.cpp
index 1991a69d06eccb8b46f0f5ee8c2df31e2c2d83c1..e65d3d3a71621a9ac45a7202afcec65fac8984d7 100644
--- a/MantidPlot/src/PlotDialog.cpp
+++ b/MantidPlot/src/PlotDialog.cpp
@@ -73,9 +73,9 @@
 
 using Mantid::Kernel::ConfigService;
 
-PlotDialog::PlotDialog(bool showExtended, ApplicationWindow* app, MultiLayer *ml, Qt::WFlags fl) :
-    QDialog(ml, fl), d_app(app), d_ml(0)
-{
+PlotDialog::PlotDialog(bool showExtended, ApplicationWindow *app,
+                       MultiLayer *ml, Qt::WFlags fl)
+    : QDialog(ml, fl), d_app(app), d_ml(0) {
   setObjectName("PlotDialog");
   setWindowTitle(tr("MantidPlot - Plot details"));
   setModal(true);
@@ -121,7 +121,7 @@ PlotDialog::PlotDialog(bool showExtended, ApplicationWindow* app, MultiLayer *ml
 
   clearTabWidget();
 
-  QHBoxLayout* hb2 = new QHBoxLayout();
+  QHBoxLayout *hb2 = new QHBoxLayout();
   btnMore = new QPushButton("&<<");
   btnMore->setFixedWidth(30);
   btnMore->setCheckable(true);
@@ -146,18 +146,20 @@ PlotDialog::PlotDialog(bool showExtended, ApplicationWindow* app, MultiLayer *ml
 
   connect(buttonOk, SIGNAL(clicked()), this, SLOT(quit()));
   connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
-  connect(buttonApply, SIGNAL(clicked() ), this, SLOT(acceptParams()));
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(acceptParams()));
   connect(btnWorksheet, SIGNAL(clicked()), this, SLOT(showWorksheet()));
   connect(btnEditCurve, SIGNAL(clicked()), this, SLOT(editCurve()));
-  connect(listBox, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int)), this,
-  SLOT(showPlotAssociations( QTreeWidgetItem *, int)));
-  connect(listBox, SIGNAL(currentItemChanged (QTreeWidgetItem *, QTreeWidgetItem *)), this,
-  SLOT(updateTabWindow(QTreeWidgetItem *, QTreeWidgetItem *)));
+  connect(listBox, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this,
+          SLOT(showPlotAssociations(QTreeWidgetItem *, int)));
+  connect(listBox,
+          SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
+          this, SLOT(updateTabWindow(QTreeWidgetItem *, QTreeWidgetItem *)));
   connect(listBox, SIGNAL(itemCollapsed(QTreeWidgetItem *)), this,
-  SLOT(updateTreeWidgetItem(QTreeWidgetItem *)));
+          SLOT(updateTreeWidgetItem(QTreeWidgetItem *)));
   connect(listBox, SIGNAL(itemExpanded(QTreeWidgetItem *)), this,
-  SLOT(updateTreeWidgetItem(QTreeWidgetItem *)));
-  connect(boxPlotType, SIGNAL(currentIndexChanged(int)), this, SLOT(changePlotType(int)));
+          SLOT(updateTreeWidgetItem(QTreeWidgetItem *)));
+  connect(boxPlotType, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(changePlotType(int)));
 
   QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), this);
   connect(shortcut, SIGNAL(activated()), this, SLOT(removeSelectedCurve()));
@@ -165,10 +167,8 @@ PlotDialog::PlotDialog(bool showExtended, ApplicationWindow* app, MultiLayer *ml
   setMultiLayer(ml);
 }
 
-void PlotDialog::showAll(bool all)
-{
-  if (all)
-  {
+void PlotDialog::showAll(bool all) {
+  if (all) {
     listBox->show();
     listBox->setFocus();
 
@@ -177,16 +177,13 @@ void PlotDialog::showAll(bool all)
       curvePlotTypeBox->show();
 
     btnMore->setText("&>>");
-  }
-  else
-  {
+  } else {
     listBox->hide();
     curvePlotTypeBox->hide();
     btnMore->setText("&<<");
   }
 }
-void PlotDialog::initContourLinesPage()
-{
+void PlotDialog::initContourLinesPage() {
   QLocale locale = d_app->locale();
 
   contourLinesPage = new QWidget();
@@ -216,7 +213,8 @@ void PlotDialog::initContourLinesPage()
   hl1->addWidget(contourLinesDistanceBox, 2, 1);
 
   btnSetEquidistantLevels = new QPushButton(tr("Set &Levels"));
-  connect(btnSetEquidistantLevels, SIGNAL(clicked()), this, SLOT(setEquidistantLevels()));
+  connect(btnSetEquidistantLevels, SIGNAL(clicked()), this,
+          SLOT(setEquidistantLevels()));
   hl1->addWidget(btnSetEquidistantLevels, 3, 1);
 
   hl1->setColumnStretch(1, 10);
@@ -231,15 +229,18 @@ void PlotDialog::initContourLinesPage()
 
   QVBoxLayout *vl1 = new QVBoxLayout;
   autoContourBox = new QRadioButton(tr("Use &Color Map"));
-  connect(autoContourBox, SIGNAL(toggled(bool)), this, SLOT(showDefaultContourLinesBox(bool)));
+  connect(autoContourBox, SIGNAL(toggled(bool)), this,
+          SLOT(showDefaultContourLinesBox(bool)));
   vl1->addWidget(autoContourBox);
 
   defaultContourBox = new QRadioButton(tr("Use Default &Pen"));
-  connect(defaultContourBox, SIGNAL(toggled(bool)), this, SLOT(showDefaultContourLinesBox(bool)));
+  connect(defaultContourBox, SIGNAL(toggled(bool)), this,
+          SLOT(showDefaultContourLinesBox(bool)));
   vl1->addWidget(defaultContourBox);
 
   customPenBtn = new QRadioButton(tr("Use &Table Custom Pen"));
-  connect(customPenBtn, SIGNAL(toggled(bool)), this, SLOT(showCustomPenColumn(bool)));
+  connect(customPenBtn, SIGNAL(toggled(bool)), this,
+          SLOT(showCustomPenColumn(bool)));
   vl1->addWidget(customPenBtn);
 
   hl2->addLayout(vl1);
@@ -259,9 +260,9 @@ void PlotDialog::initContourLinesPage()
   gl1->addWidget(contourWidthBox, 1, 1);
 
   gl1->addWidget(new QLabel(tr("Style")), 2, 0);
-  //penContourStyle = new PenStyleBox();
+  // penContourStyle = new PenStyleBox();
   boxContourStyle = new PenStyleBox();
-  //gl1->addWidget((QWidget*)penContourStyle, 2, 1);
+  // gl1->addWidget((QWidget*)penContourStyle, 2, 1);
   gl1->addWidget(boxContourStyle, 2, 1);
   hl2->addWidget(defaultPenBox);
 
@@ -270,19 +271,18 @@ void PlotDialog::initContourLinesPage()
   vl0->addWidget(penGroupBox);
   vl0->addStretch();
 
-  QVBoxLayout* vl2 = new QVBoxLayout(contourLinesPage);
+  QVBoxLayout *vl2 = new QVBoxLayout(contourLinesPage);
   vl2->addWidget(levelsGroupBox);
 
   privateTabWidget->insertTab(-1, contourLinesPage, tr("Contour Lines"));
-  //privateTabWidget->addTab(layerGeometryPage, tr("Contour Lines"));
+  // privateTabWidget->addTab(layerGeometryPage, tr("Contour Lines"));
 }
-void PlotDialog::setEquidistantLevels()
-{
+void PlotDialog::setEquidistantLevels() {
   QTreeWidgetItem *it = listBox->currentItem();
   if (!it)
     return;
 
-  CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(it);
+  CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(it);
   if (!item)
     return;
 
@@ -290,7 +290,7 @@ void PlotDialog::setEquidistantLevels()
   if (!plotItem)
     return;
 
-  Spectrogram *sp = dynamic_cast<Spectrogram*>(plotItem);
+  Spectrogram *sp = dynamic_cast<Spectrogram *>(plotItem);
   if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
     return;
 
@@ -302,15 +302,13 @@ void PlotDialog::setEquidistantLevels()
   sp->plot()->replot();
   contourLinesEditor->updateContents();
 }
-void PlotDialog::showCustomPenColumn(bool on)
-{
+void PlotDialog::showCustomPenColumn(bool on) {
   contourLinesEditor->showPenColumn(on);
   if (on)
     defaultPenBox->hide();
 }
 
-void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int)
-{
+void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) {
   if (!item)
     return;
 
@@ -320,16 +318,15 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int)
   if (item->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
-  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem*>(item);
+  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(item);
   if (!ctit)
     return;
   QwtPlotItem *it = dynamic_cast<QwtPlotItem *>(ctit->plotItem());
   if (!it)
     return;
 
-  if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
-  {
-    Spectrogram *sp = dynamic_cast<Spectrogram*>(it);
+  if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) {
+    Spectrogram *sp = dynamic_cast<Spectrogram *>(it);
     if (sp && sp->matrix())
       sp->matrix()->showMaximized();
     return;
@@ -339,25 +336,21 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int)
   PlotCurve *pc = dynamic_cast<PlotCurve *>(it);
   if (!pc)
     return;
-  if (pc->type() == Graph::Function)
-  {
-    FunctionDialog *fd = d_app->showFunctionDialog(ctit->graph(),
-                                                   ctit->plotItemIndex());
+  if (pc->type() == Graph::Function) {
+    FunctionDialog *fd =
+        d_app->showFunctionDialog(ctit->graph(), ctit->plotItemIndex());
 
     if (fd)
-      connect((QObject *) fd, SIGNAL(destroyed()), this, SLOT(show()));
-  }
-  else
-  {
-    AssociationsDialog* ad = d_app->showPlotAssociations(ctit->plotItemIndex());
+      connect((QObject *)fd, SIGNAL(destroyed()), this, SLOT(show()));
+  } else {
+    AssociationsDialog *ad = d_app->showPlotAssociations(ctit->plotItemIndex());
 
     if (ad)
-      connect((QObject *) ad, SIGNAL(destroyed()), this, SLOT(show()));
+      connect((QObject *)ad, SIGNAL(destroyed()), this, SLOT(show()));
   }
 }
 
-void PlotDialog::editCurve()
-{
+void PlotDialog::editCurve() {
 
   CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(listBox->currentItem());
   if (!item)
@@ -366,32 +359,29 @@ void PlotDialog::editCurve()
     return;
 
   int index = item->plotItemIndex();
-  PlotCurve* pc = dynamic_cast<PlotCurve *>(item->plotItem());
+  PlotCurve *pc = dynamic_cast<PlotCurve *>(item->plotItem());
   if (!pc)
     return;
   int curveType = pc->type();
 
   hide();
 
-  if (d_app)
-  {
-    if (curveType == Graph::Function)
-    {
+  if (d_app) {
+    if (curveType == Graph::Function) {
       FunctionDialog *fd = d_app->showFunctionDialog(item->graph(), index);
       if (fd)
-        connect(reinterpret_cast<QObject *>(fd), SIGNAL(destroyed()), this, SLOT(show()));
-    }
-    else
-    {
-      AssociationsDialog* ad = d_app->showPlotAssociations(index);
+        connect(reinterpret_cast<QObject *>(fd), SIGNAL(destroyed()), this,
+                SLOT(show()));
+    } else {
+      AssociationsDialog *ad = d_app->showPlotAssociations(index);
       if (ad)
-        connect(reinterpret_cast<QObject *>(ad), SIGNAL(destroyed()), this, SLOT(show()));
+        connect(reinterpret_cast<QObject *>(ad), SIGNAL(destroyed()), this,
+                SLOT(show()));
     }
   }
 }
 
-void PlotDialog::changePlotType(int plotType)
-{
+void PlotDialog::changePlotType(int plotType) {
   if (boxPlotType->count() == 1)
     return;
 
@@ -405,40 +395,36 @@ void PlotDialog::changePlotType(int plotType)
     return;
 
   int curveType = item->plotItemType();
-  if (curveType == Graph::ColorMap || curveType == Graph::Contour || curveType == Graph::GrayScale)
+  if (curveType == Graph::ColorMap || curveType == Graph::Contour ||
+      curveType == Graph::GrayScale)
     clearTabWidget();
-  else if (curveType == Graph::VectXYAM || curveType == Graph::VectXYXY)
-  {
-    if ((plotType && curveType == Graph::VectXYAM) || (!plotType && curveType == Graph::VectXYXY))
+  else if (curveType == Graph::VectXYAM || curveType == Graph::VectXYXY) {
+    if ((plotType && curveType == Graph::VectXYAM) ||
+        (!plotType && curveType == Graph::VectXYXY))
       return;
 
     clearTabWidget();
     insertTabs(curveType);
 
-    VectorCurve *v = dynamic_cast<VectorCurve*>(item->plotItem());
+    VectorCurve *v = dynamic_cast<VectorCurve *>(item->plotItem());
     if (!v)
       return;
 
-    if (plotType)
-    {
+    if (plotType) {
       graph->setCurveType(item->plotItemIndex(), Graph::VectXYAM);
       v->setVectorStyle(VectorCurve::XYAM);
-    }
-    else
-    {
+    } else {
       graph->setCurveType(item->plotItemIndex(), Graph::VectXYXY);
       v->setVectorStyle(VectorCurve::XYXY);
     }
     customVectorsPage(plotType);
-  }
-  else
-  {
+  } else {
     clearTabWidget();
     insertTabs(plotType);
 
     graph->setCurveType(item->plotItemIndex(), plotType);
 
-    boxConnect->setCurrentIndex(1); //show line for Line and LineSymbol plots
+    boxConnect->setCurrentIndex(1); // show line for Line and LineSymbol plots
 
     QwtSymbol s = QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(9, 9));
     if (plotType == Graph::Line)
@@ -450,8 +436,7 @@ void PlotDialog::changePlotType(int plotType)
 
     graph->setCurveSymbol(item->plotItemIndex(), s);
 
-    if (plotType)
-    {
+    if (plotType) {
       boxSymbolStyle->setCurrentIndex(1);
       boxFillSymbol->setChecked(false);
       boxFillColor->setEnabled(false);
@@ -463,13 +448,13 @@ void PlotDialog::changePlotType(int plotType)
 /**
  * Changes the graph's plot stlye from somewhere other than the plot dialog.
  *
- * @params plotType :: This is the plot style number. i.e line is 0 and scatter is 1.
+ * @params plotType :: This is the plot style number. i.e line is 0 and scatter
+ *is 1.
  * @params color :: The color the user specified for the plot.
  */
-void PlotDialog::setPlotType(int plotType, int curveNum, const QString & color)
-{
+void PlotDialog::setPlotType(int plotType, int curveNum, const QString &color) {
   selectCurve(curveNum);
-  CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(listBox->currentItem());
+  CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(listBox->currentItem());
   if (!item)
     return;
   if (item->type() != CurveTreeItem::PlotCurveTreeItem)
@@ -492,8 +477,7 @@ void PlotDialog::setPlotType(int plotType, int curveNum, const QString & color)
   graph->setCurveSymbol(item->plotItemIndex(), s);
 }
 
-void PlotDialog::initFontsPage()
-{
+void PlotDialog::initFontsPage() {
   QGroupBox *boxFonts = new QGroupBox();
   QGridLayout *fl = new QGridLayout(boxFonts);
 
@@ -514,18 +498,17 @@ void PlotDialog::initFontsPage()
   hl->addWidget(boxFonts);
   privateTabWidget->addTab(fontsPage, tr("Fonts"));
 
-  connect(btnTitle, SIGNAL( clicked() ), this, SLOT( setTitlesFont() ));
-  connect(btnAxesLabels, SIGNAL( clicked() ), this, SLOT( setAxesLabelsFont() ));
-  connect(btnAxesNumbers, SIGNAL( clicked() ), this, SLOT( setAxesNumbersFont() ));
-  connect(btnLegend, SIGNAL( clicked() ), this, SLOT( setLegendsFont() ));
+  connect(btnTitle, SIGNAL(clicked()), this, SLOT(setTitlesFont()));
+  connect(btnAxesLabels, SIGNAL(clicked()), this, SLOT(setAxesLabelsFont()));
+  connect(btnAxesNumbers, SIGNAL(clicked()), this, SLOT(setAxesNumbersFont()));
+  connect(btnLegend, SIGNAL(clicked()), this, SLOT(setLegendsFont()));
 }
 
-void PlotDialog::initLayerPage()
-{
+void PlotDialog::initLayerPage() {
   layerPage = new QWidget();
 
-  QGroupBox * boxBkg = new QGroupBox();
-  QGridLayout * boxBkgLayout = new QGridLayout(boxBkg);
+  QGroupBox *boxBkg = new QGroupBox();
+  QGridLayout *boxBkgLayout = new QGridLayout(boxBkg);
 
   boxBkgLayout->addWidget(new QLabel(tr("Background Color")), 0, 0);
   boxBackgroundColor = new ColorButton();
@@ -565,8 +548,8 @@ void PlotDialog::initLayerPage()
   boxBkgLayout->addWidget(boxCanvasFrameWidth, 3, 3);
   boxBkgLayout->setRowStretch(4, 1);
 
-  QGroupBox * box4 = new QGroupBox(QString());
-  QGridLayout * box4Layout = new QGridLayout(box4);
+  QGroupBox *box4 = new QGroupBox(QString());
+  QGridLayout *box4Layout = new QGridLayout(box4);
 
   box4Layout->addWidget(new QLabel(tr("Margin")), 0, 0);
   boxMargin = new QSpinBox();
@@ -581,15 +564,14 @@ void PlotDialog::initLayerPage()
   box4Layout->addWidget(boxAll, 2, 1);
   box4Layout->setRowStretch(3, 1);
 
-  QHBoxLayout * hl = new QHBoxLayout(layerPage);
+  QHBoxLayout *hl = new QHBoxLayout(layerPage);
   hl->addWidget(boxBkg);
   hl->addWidget(box4);
 
   privateTabWidget->addTab(layerPage, tr("Layer"));
 }
 
-void PlotDialog::initLayerGeometryPage()
-{
+void PlotDialog::initLayerGeometryPage() {
   layerGeometryPage = new QWidget();
 
   QGroupBox *gb1 = new QGroupBox(tr("Origin"));
@@ -634,22 +616,24 @@ void PlotDialog::initLayerGeometryPage()
   bl1->addWidget(gb1);
   bl1->addWidget(gb2);
 
-  keepRatioOnResizeBox = new QCheckBox(tr("Keep aspect ratio on window resize"));
+  keepRatioOnResizeBox =
+      new QCheckBox(tr("Keep aspect ratio on window resize"));
   QBoxLayout *bl2 = new QBoxLayout(QBoxLayout::LeftToRight);
   bl2->addWidget(keepRatioOnResizeBox);
 
-  QVBoxLayout * vl = new QVBoxLayout(layerGeometryPage);
+  QVBoxLayout *vl = new QVBoxLayout(layerGeometryPage);
   vl->addLayout(bl1);
   vl->addLayout(bl2);
 
   privateTabWidget->addTab(layerGeometryPage, tr("Geometry"));
 
-  connect(boxLayerWidth, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerHeight(int) ));
-  connect(boxLayerHeight, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerWidth(int) ));
+  connect(boxLayerWidth, SIGNAL(valueChanged(int)), this,
+          SLOT(adjustLayerHeight(int)));
+  connect(boxLayerHeight, SIGNAL(valueChanged(int)), this,
+          SLOT(adjustLayerWidth(int)));
 }
 
-void PlotDialog::initPiePage()
-{
+void PlotDialog::initPiePage() {
   piePage = new QWidget();
 
   QGridLayout *gl1 = new QGridLayout();
@@ -692,7 +676,7 @@ void PlotDialog::initPiePage()
   QGroupBox *gb2 = new QGroupBox(tr("Fill"));
   gb2->setLayout(gl2);
 
-  QHBoxLayout* hl = new QHBoxLayout();
+  QHBoxLayout *hl = new QHBoxLayout();
   hl->addWidget(gb1);
   hl->addWidget(gb2);
   piePage->setLayout(hl);
@@ -700,8 +684,7 @@ void PlotDialog::initPiePage()
   privateTabWidget->addTab(piePage, tr("Pattern"));
 }
 
-void PlotDialog::initPieGeometryPage()
-{
+void PlotDialog::initPieGeometryPage() {
   pieGeometryPage = new QWidget();
 
   QLocale locale = d_app->locale();
@@ -749,7 +732,7 @@ void PlotDialog::initPieGeometryPage()
   gl2->addWidget(boxPieOffset, 1, 1);
   gl2->setRowStretch(2, 1);
 
-  QVBoxLayout* vl = new QVBoxLayout(pieGeometryPage);
+  QVBoxLayout *vl = new QVBoxLayout(pieGeometryPage);
   vl->addWidget(gb3);
   vl->addWidget(gb1);
   vl->addWidget(gb2);
@@ -757,8 +740,7 @@ void PlotDialog::initPieGeometryPage()
   privateTabWidget->addTab(pieGeometryPage, tr("Pie Geometry"));
 }
 
-void PlotDialog::initPieLabelsPage()
-{
+void PlotDialog::initPieLabelsPage() {
   pieLabelsPage = new QWidget();
 
   pieAutoLabelsBox = new QGroupBox(tr("Automatic &Format"));
@@ -787,15 +769,14 @@ void PlotDialog::initPieLabelsPage()
   gl2->addWidget(boxPieEdgeDist, 0, 1);
   gl2->setRowStretch(1, 1);
 
-  QVBoxLayout* vl = new QVBoxLayout(pieLabelsPage);
+  QVBoxLayout *vl = new QVBoxLayout(pieLabelsPage);
   vl->addWidget(pieAutoLabelsBox);
   vl->addWidget(boxPieWedge);
 
   privateTabWidget->addTab(pieLabelsPage, tr("Labels"));
 }
 
-void PlotDialog::initPrintPage()
-{
+void PlotDialog::initPrintPage() {
   QGroupBox *gb = new QGroupBox();
   QVBoxLayout *vl = new QVBoxLayout(gb);
   boxScaleLayers = new QCheckBox(tr("&Scale layers to paper size"));
@@ -805,13 +786,12 @@ void PlotDialog::initPrintPage()
   vl->addStretch();
 
   printPage = new QWidget();
-  QHBoxLayout* hlayout = new QHBoxLayout(printPage);
+  QHBoxLayout *hlayout = new QHBoxLayout(printPage);
   hlayout->addWidget(gb);
   privateTabWidget->addTab(printPage, tr("Print"));
 }
 
-void PlotDialog::initLabelsPage()
-{
+void PlotDialog::initLabelsPage() {
   labelsGroupBox = new QGroupBox(tr("&Show"));
   labelsGroupBox->setCheckable(true);
 
@@ -857,13 +837,12 @@ void PlotDialog::initLabelsPage()
   gl->setColumnStretch(3, 1);
 
   labelsPage = new QWidget();
-  QHBoxLayout* hlayout = new QHBoxLayout(labelsPage);
+  QHBoxLayout *hlayout = new QHBoxLayout(labelsPage);
   hlayout->addWidget(labelsGroupBox);
   privateTabWidget->addTab(labelsPage, tr("Labels"));
 }
 
-void PlotDialog::initAxesPage()
-{
+void PlotDialog::initAxesPage() {
   QGroupBox *gb = new QGroupBox(tr("Attach curve to: "));
   QGridLayout *gl = new QGridLayout(gb);
   gl->addWidget(new QLabel(tr("x Axis")), 0, 0);
@@ -881,13 +860,12 @@ void PlotDialog::initAxesPage()
   gl->setRowStretch(2, 1);
 
   axesPage = new QWidget();
-  QHBoxLayout* hlayout = new QHBoxLayout(axesPage);
+  QHBoxLayout *hlayout = new QHBoxLayout(axesPage);
   hlayout->addWidget(gb);
   privateTabWidget->addTab(axesPage, tr("Axes"));
 }
 
-void PlotDialog::initLinePage()
-{
+void PlotDialog::initLinePage() {
   QGroupBox *gb = new QGroupBox();
   QGridLayout *gl1 = new QGridLayout(gb);
   gl1->addWidget(new QLabel(tr("Connect")), 0, 0);
@@ -938,7 +916,7 @@ void PlotDialog::initLinePage()
   gl2->setRowStretch(2, 1);
 
   linePage = new QWidget();
-  QHBoxLayout* hlayout = new QHBoxLayout(linePage);
+  QHBoxLayout *hlayout = new QHBoxLayout(linePage);
   hlayout->addWidget(gb);
   hlayout->addWidget(fillGroupBox);
   privateTabWidget->addTab(linePage, tr("Line"));
@@ -946,8 +924,7 @@ void PlotDialog::initLinePage()
   connect(fillGroupBox, SIGNAL(toggled(bool)), this, SLOT(showAreaColor(bool)));
 }
 
-void PlotDialog::initSymbolsPage()
-{
+void PlotDialog::initSymbolsPage() {
   QGroupBox *gb = new QGroupBox();
   QGridLayout *gl = new QGridLayout(gb);
   gl->addWidget(new QLabel(tr("Style")), 0, 0);
@@ -975,16 +952,16 @@ void PlotDialog::initSymbolsPage()
   gl->setRowStretch(5, 1);
 
   symbolPage = new QWidget();
-  QHBoxLayout* hl = new QHBoxLayout(symbolPage);
+  QHBoxLayout *hl = new QHBoxLayout(symbolPage);
   hl->addWidget(gb);
 
   privateTabWidget->insertTab(-1, symbolPage, tr("Symbol"));
 
-  connect(boxFillSymbol, SIGNAL(toggled(bool)), this, SLOT(showBoxSymbols(bool)));
+  connect(boxFillSymbol, SIGNAL(toggled(bool)), this,
+          SLOT(showBoxSymbols(bool)));
 }
 
-void PlotDialog::initBoxPage()
-{
+void PlotDialog::initBoxPage() {
   QGroupBox *gb1 = new QGroupBox(tr("Box"));
   QGridLayout *gl1 = new QGridLayout(gb1);
   gl1->addWidget(new QLabel(tr("Type")), 0, 0);
@@ -1075,18 +1052,18 @@ void PlotDialog::initBoxPage()
   vl2->addStretch();
 
   boxPage = new QWidget();
-  QHBoxLayout* hl = new QHBoxLayout(boxPage);
+  QHBoxLayout *hl = new QHBoxLayout(boxPage);
   hl->addLayout(vl1);
   hl->addLayout(vl2);
   privateTabWidget->insertTab(-1, boxPage, tr("Box/Whiskers"));
 
   connect(boxType, SIGNAL(activated(int)), this, SLOT(setBoxType(int)));
   connect(boxRange, SIGNAL(activated(int)), this, SLOT(setBoxRangeType(int)));
-  connect(boxWhiskersRange, SIGNAL(activated(int)), this, SLOT(setWhiskersRange(int)));
+  connect(boxWhiskersRange, SIGNAL(activated(int)), this,
+          SLOT(setWhiskersRange(int)));
 }
 
-void PlotDialog::initPercentilePage()
-{
+void PlotDialog::initPercentilePage() {
   QGroupBox *gb1 = new QGroupBox(tr("Type"));
   QGridLayout *gl1 = new QGridLayout(gb1);
   gl1->addWidget(new QLabel(tr("Max")), 0, 0);
@@ -1138,34 +1115,31 @@ void PlotDialog::initPercentilePage()
   gl2->setRowStretch(4, 1);
 
   percentilePage = new QWidget();
-  QHBoxLayout* hl = new QHBoxLayout(percentilePage);
+  QHBoxLayout *hl = new QHBoxLayout(percentilePage);
   hl->addWidget(gb1);
   hl->addWidget(gb2);
   privateTabWidget->insertTab(-1, percentilePage, tr("Percentile"));
 
-  connect(boxFillSymbols, SIGNAL(toggled(bool)), this, SLOT(showBoxSymbols(bool)));
+  connect(boxFillSymbols, SIGNAL(toggled(bool)), this,
+          SLOT(showBoxSymbols(bool)));
 }
 
 /*
- * Hides the "Custom color map" button when the user has not selected that specific button.
+ * Hides the "Custom color map" button when the user has not selected that
+ * specific button.
  */
-void PlotDialog::showColorMapEditor(bool)
-{
-  if (grayScaleBox->isChecked() || defaultScaleBox->isChecked())
-  {
+void PlotDialog::showColorMapEditor(bool) {
+  if (grayScaleBox->isChecked() || defaultScaleBox->isChecked()) {
     mSelectColormap->hide();
     boxSetCMapAsDefault->hide();
-  }
-  else
-  {
+  } else {
     boxSetCMapAsDefault->show();
     mSelectColormap->show();
   }
   setColorMapName();
 }
 
-void PlotDialog::initSpectrogramPage()
-{
+void PlotDialog::initSpectrogramPage() {
   spectrogramPage = new QWidget();
 
   imageGroupBox = new QGroupBox(tr("Image"));
@@ -1174,15 +1148,18 @@ void PlotDialog::initSpectrogramPage()
   QVBoxLayout *vl = new QVBoxLayout();
 
   grayScaleBox = new QRadioButton(tr("&Gray Scale"));
-  connect(grayScaleBox, SIGNAL(toggled(bool)), this, SLOT(showColorMapEditor(bool)));
+  connect(grayScaleBox, SIGNAL(toggled(bool)), this,
+          SLOT(showColorMapEditor(bool)));
   vl->addWidget(grayScaleBox);
 
   defaultScaleBox = new QRadioButton(tr("&Default Color Map"));
-  connect(defaultScaleBox, SIGNAL(toggled(bool)), this, SLOT(showColorMapEditor(bool)));
+  connect(defaultScaleBox, SIGNAL(toggled(bool)), this,
+          SLOT(showColorMapEditor(bool)));
   vl->addWidget(defaultScaleBox);
 
   customScaleBox = new QRadioButton(tr("&Custom Color Map"));
-  connect(customScaleBox, SIGNAL(toggled(bool)), this, SLOT(showColorMapEditor(bool)));
+  connect(customScaleBox, SIGNAL(toggled(bool)), this,
+          SLOT(showColorMapEditor(bool)));
   vl->addWidget(customScaleBox);
 
   QVBoxLayout *vlCM = new QVBoxLayout();
@@ -1219,43 +1196,40 @@ void PlotDialog::initSpectrogramPage()
   colorScaleWidthBox->setRange(2, 10000);
   gl2->addWidget(colorScaleWidthBox, 1, 1);
 
-  QVBoxLayout* vl2 = new QVBoxLayout(spectrogramPage);
+  QVBoxLayout *vl2 = new QVBoxLayout(spectrogramPage);
   vl2->addWidget(imageGroupBox);
   vl2->addWidget(axisScaleBox);
   vl2->addStretch();
 
   setColorMapName();
 
-  privateTabWidget->insertTab(-1, spectrogramPage, tr("Contour") + " / " + tr("Image"));
+  privateTabWidget->insertTab(-1, spectrogramPage,
+                              tr("Contour") + " / " + tr("Image"));
 }
 
-void PlotDialog::setColorMapName()
-{
+void PlotDialog::setColorMapName() {
   if (grayScaleBox->isChecked()) {
     mLabelCurrentColormap->setText("Map: Greyscale");
-  } 
-  else {
+  } else {
     Spectrogram *sp = NULL;
     QTreeWidgetItem *it = listBox->currentItem();
     if (it) {
-      CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(it);
+      CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(it);
       if (item) {
         QwtPlotItem *plotItem = dynamic_cast<QwtPlotItem *>(item->plotItem());
         if (plotItem) {
-          sp = dynamic_cast<Spectrogram*>(plotItem);
+          sp = dynamic_cast<Spectrogram *>(plotItem);
         }
       }
     }
     if (sp) {
       if (defaultScaleBox->isChecked()) {
-        mLabelCurrentColormap->setText("Map: " + sp->getDefaultColorMap().getName());
-      } 
-      else if (mCurrentColorMap.isEmpty()) {
+        mLabelCurrentColormap->setText("Map: " +
+                                       sp->getDefaultColorMap().getName());
+      } else if (mCurrentColorMap.isEmpty()) {
         mLabelCurrentColormap->setText("Map: " + sp->getColorMap().getName());
-      } 
-      else
-      {
-          //set the name of the color map to the filename
+      } else {
+        // set the name of the color map to the filename
         QFileInfo fileinfo(mCurrentColorMap);
         mLabelCurrentColormap->setText("Map: " + fileinfo.baseName());
       }
@@ -1263,17 +1237,15 @@ void PlotDialog::setColorMapName()
   }
 }
 
-void PlotDialog::showBoxSymbols(bool show)
-{
+void PlotDialog::showBoxSymbols(bool show) {
   boxPercFillColor->setEnabled(show);
   boxFillColor->setEnabled(show);
 }
 
-void PlotDialog::initErrorsPage()
-{
+void PlotDialog::initErrorsPage() {
   QGroupBox *gb1 = new QGroupBox(tr("Direction"));
 
-  QVBoxLayout* vl = new QVBoxLayout(gb1);
+  QVBoxLayout *vl = new QVBoxLayout(gb1);
   plusBox = new QCheckBox(tr("Plus"));
   vl->addWidget(plusBox);
   minusBox = new QCheckBox(tr("Minus"));
@@ -1312,15 +1284,14 @@ void PlotDialog::initErrorsPage()
   gl->setRowStretch(4, 1);
 
   errorsPage = new QWidget();
-  QHBoxLayout* hl = new QHBoxLayout(errorsPage);
+  QHBoxLayout *hl = new QHBoxLayout(errorsPage);
   hl->addWidget(gb1);
   hl->addWidget(gb2);
   privateTabWidget->insertTab(-1, errorsPage, tr("Error Bars"));
 }
 
-void PlotDialog::initHistogramPage()
-{
-  QHBoxLayout* hl = new QHBoxLayout();
+void PlotDialog::initHistogramPage() {
+  QHBoxLayout *hl = new QHBoxLayout();
   automaticBox = new QCheckBox(tr("Automatic Binning"));
   hl->addWidget(automaticBox);
   hl->addStretch();
@@ -1340,7 +1311,7 @@ void PlotDialog::initHistogramPage()
   gl->addWidget(histogramEndBox, 2, 1);
 
   histogramPage = new QWidget();
-  QVBoxLayout* vl = new QVBoxLayout(histogramPage);
+  QVBoxLayout *vl = new QVBoxLayout(histogramPage);
   vl->addLayout(hl);
   vl->addWidget(GroupBoxH);
   vl->addStretch();
@@ -1348,11 +1319,10 @@ void PlotDialog::initHistogramPage()
   privateTabWidget->insertTab(-1, histogramPage, tr("Histogram Data"));
 
   connect(automaticBox, SIGNAL(clicked()), this, SLOT(setAutomaticBinning()));
-  connect(buttonStatistics, SIGNAL(clicked()), this, SLOT(showStatistics() ));
+  connect(buttonStatistics, SIGNAL(clicked()), this, SLOT(showStatistics()));
 }
 
-void PlotDialog::initSpacingPage()
-{
+void PlotDialog::initSpacingPage() {
   spacingPage = new QWidget();
 
   QGridLayout *gl = new QGridLayout(spacingPage);
@@ -1371,8 +1341,7 @@ void PlotDialog::initSpacingPage()
   privateTabWidget->insertTab(-1, spacingPage, tr("Spacing"));
 }
 
-void PlotDialog::initVectPage()
-{
+void PlotDialog::initVectPage() {
   QGroupBox *gb1 = new QGroupBox();
   QGridLayout *gl1 = new QGridLayout(gb1);
   gl1->addWidget(new QLabel(tr("Color")), 0, 0);
@@ -1434,8 +1403,7 @@ void PlotDialog::initVectPage()
   privateTabWidget->insertTab(-1, vectPage, tr("Vector"));
 }
 
-void PlotDialog::setMultiLayer(MultiLayer *ml)
-{
+void PlotDialog::setMultiLayer(MultiLayer *ml) {
   if (!ml)
     return;
 
@@ -1443,7 +1411,8 @@ void PlotDialog::setMultiLayer(MultiLayer *ml)
   boxScaleLayers->setChecked(d_ml->scaleLayersOnPrint());
   boxPrintCrops->setChecked(d_ml->printCropmarksEnabled());
 
-  // the plot (dataset) name will be displayed in the tree entry (leftmost/topmost tree level)
+  // the plot (dataset) name will be displayed in the tree entry
+  // (leftmost/topmost tree level)
   QTreeWidgetItem *item = new QTreeWidgetItem(listBox, QStringList(ml->name()));
   item->setIcon(0, QIcon(getQPixmap("folder_open")));
   listBox->addTopLevelItem(item);
@@ -1451,36 +1420,36 @@ void PlotDialog::setMultiLayer(MultiLayer *ml)
 
   QList<Graph *> layers = ml->layersList();
   int i = 0;
-  foreach(Graph *g, layers)
-  {
-    // builds the names/labels of layers (Layer1, Layer2, etc.) visible in the tree
-    LayerItem *layer = new LayerItem(g, item, tr("Layer ") + QString::number(++i));
+  foreach (Graph *g, layers) {
+    // builds the names/labels of layers (Layer1, Layer2, etc.) visible in the
+    // tree
+    LayerItem *layer =
+        new LayerItem(g, item, tr("Layer ") + QString::number(++i));
     item->addChild(layer);
 
-    if (g == ml->activeGraph())
-    {
+    if (g == ml->activeGraph()) {
       layer->setExpanded(true);
       layer->setActive(true);
       listBox->setCurrentItem(layer);
 
       keepRatioOnResizeBox->setChecked(g->isFixedAspectRatioEnabled());
-      if (g->isSpectrogram()) keepRatioOnResizeBox->show();
-      else keepRatioOnResizeBox->hide();
+      if (g->isSpectrogram())
+        keepRatioOnResizeBox->show();
+      else
+        keepRatioOnResizeBox->hide();
     }
   }
 }
 
-void PlotDialog::selectCurve(int index)
-{
-  LayerItem *layerItem = dynamic_cast<LayerItem*>(listBox->currentItem());
+void PlotDialog::selectCurve(int index) {
+  LayerItem *layerItem = dynamic_cast<LayerItem *>(listBox->currentItem());
   if (!layerItem)
     return;
   if (layerItem->type() != LayerItem::LayerTreeItem)
     return;
   QTreeWidgetItem *item = layerItem->child(index);
-  if (item)
-  {
-    CurveTreeItem *ctit = dynamic_cast<CurveTreeItem*>(item);
+  if (item) {
+    CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(item);
     if (!ctit)
       return;
     ctit->setActive(true);
@@ -1488,8 +1457,7 @@ void PlotDialog::selectCurve(int index)
   }
 }
 
-void PlotDialog::showStatistics()
-{
+void PlotDialog::showStatistics() {
   if (!d_app)
     return;
 
@@ -1499,7 +1467,7 @@ void PlotDialog::showStatistics()
   if (it->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
-  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem*>(it);
+  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(it);
   if (!ctit)
     return;
 
@@ -1507,43 +1475,44 @@ void PlotDialog::showStatistics()
   if (!plotItem)
     return;
 
-  QwtHistogram *h = dynamic_cast<QwtHistogram*>(plotItem);
+  QwtHistogram *h = dynamic_cast<QwtHistogram *>(plotItem);
   if (!h)
     return;
 
   QString tableName = d_app->generateUniqueName(tr("Bins"));
   Table *t = d_app->newTable(h->dataSize(), 4, tableName,
-      tr("Histogram and Probabilities for") + " " + h->title().text());
-  if (t)
-  {
+                             tr("Histogram and Probabilities for") + " " +
+                                 h->title().text());
+  if (t) {
     double h_sum = 0.0;
     for (int i = 0; i < h->dataSize(); i++)
       h_sum += h->y(i);
 
     double sum = 0.0;
-    for (int i = 0; i < h->dataSize(); i++)
-    {
+    for (int i = 0; i < h->dataSize(); i++) {
       sum += h->y(i);
       t->setText(i, 0, QString::number(h->x(i)));
       t->setText(i, 1, QString::number(h->y(i)));
       t->setText(i, 2, QString::number(sum));
       t->setText(i, 3, QString::number(sum / h_sum * 100));
     }
-    t->setHeader(QStringList() << tr("Bins") << tr("Quantity") << tr("Sum") << tr("Percent"));
+    t->setHeader(QStringList() << tr("Bins") << tr("Quantity") << tr("Sum")
+                               << tr("Percent"));
     t->showMaximized();
   }
 
   QDateTime dt = QDateTime::currentDateTime();
-  QString info = dt.toString(Qt::LocalDate) + "\t" + tr("Histogram and Probabilities for") + " "
-      + h->title().text() + "\n";
+  QString info = dt.toString(Qt::LocalDate) + "\t" +
+                 tr("Histogram and Probabilities for") + " " +
+                 h->title().text() + "\n";
   info += tr("Mean") + " = " + QString::number(h->mean()) + "\t";
-  info += tr("Standard Deviation") + " = " + QString::number(h->standardDeviation()) + "\n";
+  info += tr("Standard Deviation") + " = " +
+          QString::number(h->standardDeviation()) + "\n";
   info += tr("Minimum") + " = " + QString::number(h->minimum()) + "\t";
   info += tr("Maximum") + " = " + QString::number(h->maximum()) + "\t";
   info += tr("Bins") + " = " + QString::number(h->dataSize()) + "\n";
   info += "-------------------------------------------------------------\n";
-  if (!info.isEmpty())
-  {
+  if (!info.isEmpty()) {
     d_app->currentFolder()->appendLogInfo(info);
     d_app->showResults(true);
   }
@@ -1551,15 +1520,14 @@ void PlotDialog::showStatistics()
   close();
 }
 
-void PlotDialog::contextMenuEvent(QContextMenuEvent *e)
-{
+void PlotDialog::contextMenuEvent(QContextMenuEvent *e) {
   QTreeWidgetItem *item = listBox->currentItem();
   if (!item)
     return;
   if (item->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
-  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem*>(item);
+  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(item);
   if (!ctit)
     return;
 
@@ -1569,37 +1537,34 @@ void PlotDialog::contextMenuEvent(QContextMenuEvent *e)
 
   QPoint pos = listBox->viewport()->mapFromGlobal(QCursor::pos());
   QRect rect = listBox->visualItemRect(listBox->currentItem());
-  if (rect.contains(pos))
-  {
+  if (rect.contains(pos)) {
     QMenu contextMenu(this);
     contextMenu.addAction(tr("&Delete"), this, SLOT(removeSelectedCurve()));
 
-    if (it->rtti() == QwtPlotItem::Rtti_PlotCurve)
-    {
+    if (it->rtti() == QwtPlotItem::Rtti_PlotCurve) {
       PlotCurve *pc = dynamic_cast<PlotCurve *>(it);
       if (!pc)
         return;
       if (pc->type() == Graph::Function)
         contextMenu.addAction(tr("&Edit..."), this, SLOT(editCurve()));
       else
-        contextMenu.addAction(tr("&Plot Associations..."), this, SLOT(editCurve()));
+        contextMenu.addAction(tr("&Plot Associations..."), this,
+                              SLOT(editCurve()));
     }
     contextMenu.exec(QCursor::pos());
   }
   e->accept();
 }
 
-void PlotDialog::removeSelectedCurve()
-{
-  CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(listBox->currentItem());
+void PlotDialog::removeSelectedCurve() {
+  CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(listBox->currentItem());
   if (!item)
     return;
   if (item->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
   Graph *graph = item->graph();
-  if (graph)
-  {
+  if (graph) {
     graph->removeCurve(item->plotItemIndex());
     graph->updatePlot();
 
@@ -1610,20 +1575,18 @@ void PlotDialog::removeSelectedCurve()
   }
 }
 
-void PlotDialog::showAreaColor(bool show)
-{
+void PlotDialog::showAreaColor(bool show) {
   boxAreaColor->setEnabled(show);
   boxPattern->setEnabled(show);
 }
 
-void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *previousItem)
-{
+void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem,
+                                 QTreeWidgetItem *previousItem) {
   if (!currentItem)
     return;
 
   bool forceClearTabs = false;
-  if (!previousItem || previousItem == currentItem)
-  {
+  if (!previousItem || previousItem == currentItem) {
     previousItem = currentItem;
     forceClearTabs = true;
   }
@@ -1642,8 +1605,7 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *
 
   boxPlotType->blockSignals(true);
 
-  if (currentItem->type() == CurveTreeItem::PlotCurveTreeItem)
-  {
+  if (currentItem->type() == CurveTreeItem::PlotCurveTreeItem) {
     CurveTreeItem *curveItem = dynamic_cast<CurveTreeItem *>(currentItem);
     if (!curveItem) {
       boxPlotType->blockSignals(false);
@@ -1651,37 +1613,29 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *
     }
 
     CurveTreeItem *pi = dynamic_cast<CurveTreeItem *>(previousItem);
-    if (previousItem->type() != CurveTreeItem::PlotCurveTreeItem
-        || (pi && pi->plotItemType() != curveItem->plotItemType())
-        || forceClearTabs)
-    {
+    if (previousItem->type() != CurveTreeItem::PlotCurveTreeItem ||
+        (pi && pi->plotItemType() != curveItem->plotItemType()) ||
+        forceClearTabs) {
       clearTabWidget();
       int plot_type = setPlotType(curveItem);
-      if (plot_type >= 0)
-      {
+      if (plot_type >= 0) {
         insertTabs(plot_type);
       }
-      if (!curvePlotTypeBox->isVisible())
-      {
+      if (!curvePlotTypeBox->isVisible()) {
         curvePlotTypeBox->show();
       }
     }
     setActiveCurve(curveItem);
-  }
-  else if (currentItem->type() == LayerItem::LayerTreeItem)
-  {
-    if (previousItem->type() != LayerItem::LayerTreeItem)
-    {
+  } else if (currentItem->type() == LayerItem::LayerTreeItem) {
+    if (previousItem->type() != LayerItem::LayerTreeItem) {
       clearTabWidget();
       privateTabWidget->addTab(layerPage, tr("Layer"));
       privateTabWidget->addTab(layerGeometryPage, tr("Geometry"));
       const int index = privateTabWidget->indexOf(layerPage);
       privateTabWidget->setCurrentIndex(index);
     }
-    setActiveLayer(dynamic_cast<LayerItem*>(currentItem));
-  }
-  else
-  {
+    setActiveLayer(dynamic_cast<LayerItem *>(currentItem));
+  } else {
     clearTabWidget();
     privateTabWidget->addTab(printPage, tr("Print"));
     privateTabWidget->addTab(fontsPage, tr("Fonts"));
@@ -1695,10 +1649,8 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *
   boxPlotType->blockSignals(false);
 }
 
-void PlotDialog::insertTabs(int plot_type)
-{
-  if (plot_type == Graph::Pie)
-  {
+void PlotDialog::insertTabs(int plot_type) {
+  if (plot_type == Graph::Pie) {
     privateTabWidget->addTab(piePage, tr("Pattern"));
     privateTabWidget->addTab(pieGeometryPage, tr("Pie Geometry"));
     privateTabWidget->addTab(pieLabelsPage, tr("Labels"));
@@ -1708,63 +1660,49 @@ void PlotDialog::insertTabs(int plot_type)
   }
 
   privateTabWidget->addTab(axesPage, tr("Axes"));
-  if (plot_type == Graph::Line)
-  {
+  if (plot_type == Graph::Line) {
     boxConnect->setEnabled(true);
     privateTabWidget->addTab(linePage, tr("Line"));
     const int index = privateTabWidget->indexOf(linePage);
     privateTabWidget->setCurrentIndex(index);
-  }
-  else if (plot_type == Graph::Scatter)
-  {
+  } else if (plot_type == Graph::Scatter) {
     boxConnect->setEnabled(true);
     privateTabWidget->addTab(symbolPage, tr("Symbol"));
     const int index = privateTabWidget->indexOf(symbolPage);
     privateTabWidget->setCurrentIndex(index);
-  }
-  else if (plot_type == Graph::LineSymbols)
-  {
+  } else if (plot_type == Graph::LineSymbols) {
     boxConnect->setEnabled(true);
     privateTabWidget->addTab(linePage, tr("Line"));
     privateTabWidget->addTab(symbolPage, tr("Symbol"));
     const int index = privateTabWidget->indexOf(symbolPage);
     privateTabWidget->setCurrentIndex(index);
-  }
-  else if (plot_type == Graph::VerticalBars || plot_type == Graph::HorizontalBars
-      || plot_type == Graph::Histogram)
-  {
+  } else if (plot_type == Graph::VerticalBars ||
+             plot_type == Graph::HorizontalBars ||
+             plot_type == Graph::Histogram) {
     boxConnect->setEnabled(false);
     privateTabWidget->addTab(linePage, tr("Pattern"));
     privateTabWidget->addTab(spacingPage, tr("Spacing"));
 
-    if (plot_type == Graph::Histogram)
-    {
+    if (plot_type == Graph::Histogram) {
       privateTabWidget->addTab(histogramPage, tr("Histogram Data"));
       const int index = privateTabWidget->indexOf(histogramPage);
       privateTabWidget->setCurrentIndex(index);
-    }
-    else {
+    } else {
       const int index = privateTabWidget->indexOf(linePage);
       privateTabWidget->setCurrentIndex(index);
     }
-  }
-  else if (plot_type == Graph::VectXYXY || plot_type == Graph::VectXYAM)
-  {
+  } else if (plot_type == Graph::VectXYXY || plot_type == Graph::VectXYAM) {
     boxConnect->setEnabled(true);
     privateTabWidget->addTab(linePage, tr("Line"));
     privateTabWidget->addTab(vectPage, tr("Vector"));
     customVectorsPage(plot_type == Graph::VectXYAM);
     const int index = privateTabWidget->indexOf(vectPage);
     privateTabWidget->setCurrentIndex(index);
-  }
-  else if (plot_type == Graph::ErrorBars)
-  {
+  } else if (plot_type == Graph::ErrorBars) {
     privateTabWidget->addTab(errorsPage, tr("Error Bars"));
     const int index = privateTabWidget->indexOf(errorsPage);
     privateTabWidget->setCurrentIndex(index);
-  }
-  else if (plot_type == Graph::Box)
-  {
+  } else if (plot_type == Graph::Box) {
     boxConnect->setEnabled(false);
     privateTabWidget->addTab(linePage, tr("Pattern"));
     privateTabWidget->addTab(boxPage, tr("Box/Whiskers"));
@@ -1772,10 +1710,9 @@ void PlotDialog::insertTabs(int plot_type)
     const int index = privateTabWidget->indexOf(linePage);
     privateTabWidget->setCurrentIndex(index);
     return;
-  }
-  else if (plot_type == Graph::ColorMap || plot_type == Graph::GrayScale || plot_type == Graph::Contour
-      || plot_type == Graph::ColorMapContour)
-  {
+  } else if (plot_type == Graph::ColorMap || plot_type == Graph::GrayScale ||
+             plot_type == Graph::Contour ||
+             plot_type == Graph::ColorMapContour) {
     privateTabWidget->addTab(spectrogramPage, tr("Colors"));
     setColorMapName();
     privateTabWidget->addTab(contourLinesPage, tr("Contour Lines"));
@@ -1789,15 +1726,14 @@ void PlotDialog::insertTabs(int plot_type)
   if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
-  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem*>(item);
+  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(item);
   if (!ctit)
     return;
 
   const DataCurve *c = dynamic_cast<const DataCurve *>(ctit->plotItem());
   if (!c)
     return;
-  if (c && c->type() != Graph::Function)
-  {
+  if (c && c->type() != Graph::Function) {
     privateTabWidget->addTab(labelsPage, tr("Labels"));
     if (c->hasSelectedLabels()) {
       const int index = privateTabWidget->indexOf(labelsPage);
@@ -1806,8 +1742,7 @@ void PlotDialog::insertTabs(int plot_type)
   }
 }
 
-void PlotDialog::clearTabWidget()
-{
+void PlotDialog::clearTabWidget() {
   privateTabWidget->removeTab(privateTabWidget->indexOf(labelsPage));
   privateTabWidget->removeTab(privateTabWidget->indexOf(axesPage));
   privateTabWidget->removeTab(privateTabWidget->indexOf(linePage));
@@ -1829,18 +1764,16 @@ void PlotDialog::clearTabWidget()
   privateTabWidget->removeTab(privateTabWidget->indexOf(contourLinesPage));
 }
 
-void PlotDialog::quit()
-{
+void PlotDialog::quit() {
   if (acceptParams())
     close();
 }
 
-void PlotDialog::showWorksheet()
-{
+void PlotDialog::showWorksheet() {
   if (!d_app)
     return;
 
-  CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(listBox->currentItem());
+  CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(listBox->currentItem());
   if (!item)
     return;
   if (item->type() != CurveTreeItem::PlotCurveTreeItem)
@@ -1850,11 +1783,9 @@ void PlotDialog::showWorksheet()
   close();
 }
 
-int PlotDialog::setPlotType(CurveTreeItem *item)
-{
+int PlotDialog::setPlotType(CurveTreeItem *item) {
   int curveType = item->plotItemType();
-  if (curveType >= 0)
-  {
+  if (curveType >= 0) {
     boxPlotType->clear();
 
     if (curveType == Graph::ErrorBars)
@@ -1867,41 +1798,33 @@ int PlotDialog::setPlotType(CurveTreeItem *item)
       boxPlotType->addItem(tr("Horizontal Bars"));
     else if (curveType == Graph::Histogram)
       boxPlotType->addItem(tr("Histogram"));
-    else if (curveType == Graph::VectXYXY || curveType == Graph::VectXYAM)
-    {
+    else if (curveType == Graph::VectXYXY || curveType == Graph::VectXYAM) {
       boxPlotType->addItem(tr("Vector XYXY"));
       boxPlotType->addItem(tr("Vector XYAM"));
       if (curveType == Graph::VectXYAM)
         boxPlotType->setCurrentIndex(1);
-    }
-    else if (curveType == Graph::Box)
+    } else if (curveType == Graph::Box)
       boxPlotType->addItem(tr("Box"));
-    else if (curveType == Graph::ColorMap || curveType == Graph::GrayScale || curveType == Graph::Contour
-        || curveType == Graph::ColorMapContour)
+    else if (curveType == Graph::ColorMap || curveType == Graph::GrayScale ||
+             curveType == Graph::Contour || curveType == Graph::ColorMapContour)
       boxPlotType->insertItem(-1, tr("Contour") + " / " + tr("Image"));
-    else
-    {
+    else {
       boxPlotType->addItem(tr("Line"));
       boxPlotType->addItem(tr("Scatter"));
       boxPlotType->addItem(tr("Line + Symbol"));
 
-      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve*>(item->plotItem());
+      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve *>(item->plotItem());
       if (!c)
         return -1;
 
       QwtSymbol s = c->symbol();
-      if (s.style() == QwtSymbol::NoSymbol)
-      {
+      if (s.style() == QwtSymbol::NoSymbol) {
         boxPlotType->setCurrentIndex(0);
         return Graph::Line;
-      }
-      else if (c->style() == QwtPlotCurve::NoCurve)
-      {
+      } else if (c->style() == QwtPlotCurve::NoCurve) {
         boxPlotType->setCurrentIndex(1);
         return Graph::Scatter;
-      }
-      else
-      {
+      } else {
         boxPlotType->setCurrentIndex(2);
         return Graph::LineSymbols;
       }
@@ -1910,8 +1833,7 @@ int PlotDialog::setPlotType(CurveTreeItem *item)
   return curveType;
 }
 
-void PlotDialog::setActiveLayer(LayerItem *item)
-{
+void PlotDialog::setActiveLayer(LayerItem *item) {
   if (!item)
     return;
   item->setActive(true);
@@ -1965,10 +1887,9 @@ void PlotDialog::setActiveLayer(LayerItem *item)
   boxLayerHeight->setValue(p->size().height());
   boxLayerHeight->blockSignals(false);
 
-  aspect_ratio = (double) p->size().width() / (double) p->size().height();
+  aspect_ratio = (double)p->size().width() / (double)p->size().height();
 }
-void PlotDialog::updateContourLevelsDisplay(Spectrogram *sp)
-{
+void PlotDialog::updateContourLevelsDisplay(Spectrogram *sp) {
   QwtValueList levels = sp->contourLevels();
   levelsBox->setValue(levels.size());
   if (levels.size() >= 1)
@@ -1976,8 +1897,7 @@ void PlotDialog::updateContourLevelsDisplay(Spectrogram *sp)
   if (levels.size() >= 2)
     contourLinesDistanceBox->setValue(fabs(levels[1] - levels[0]));
 }
-void PlotDialog::setActiveCurve(CurveTreeItem *item)
-{
+void PlotDialog::setActiveCurve(CurveTreeItem *item) {
   if (!item)
     return;
 
@@ -1989,35 +1909,40 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   btnWorksheet->show();
   btnEditCurve->show();
 
-  //axes page
+  // axes page
   boxXAxis->setCurrentIndex(i->xAxis() - 2);
   boxYAxis->setCurrentIndex(i->yAxis());
 
-  if (i->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
-  {
+  if (i->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) {
 
     btnEditCurve->hide();
     Spectrogram *sp = dynamic_cast<Spectrogram *>(i);
     if (!sp)
       return;
 
-    imageGroupBox->setChecked(sp->testDisplayMode(QwtPlotSpectrogram::ImageMode));
+    imageGroupBox->setChecked(
+        sp->testDisplayMode(QwtPlotSpectrogram::ImageMode));
     grayScaleBox->setChecked(sp->colorMapPolicy() == Spectrogram::GrayScale);
     defaultScaleBox->setChecked(sp->colorMapPolicy() == Spectrogram::Default);
     customScaleBox->setChecked(sp->colorMapPolicy() == Spectrogram::Custom);
 
-    //colorMapEditor->setRange(sp->data().range().minValue(), sp->data().range().maxValue());
-    //colorMapEditor->setColorMap((const QwtLinearColorMap &)sp->colorMap());
+    // colorMapEditor->setRange(sp->data().range().minValue(),
+    // sp->data().range().maxValue());
+    // colorMapEditor->setColorMap((const QwtLinearColorMap &)sp->colorMap());
 
-    levelsGroupBox->setChecked(sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
+    levelsGroupBox->setChecked(
+        sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
     levelsBox->setValue(sp->levels());
 
-    //autoContourBox->setChecked(sp->defaultContourPen().style() == Qt::NoPen);
-    autoContourBox->setChecked(sp->useColorMapPen() && sp->defaultContourPen().style() == Qt::NoPen);
-    //customPenBtn->setChecked(sp->defaultContourPen().style() == Qt::NoPen);
-    customPenBtn->setChecked(!sp->useColorMapPen() && sp->defaultContourPen().style() == Qt::NoPen);
+    // autoContourBox->setChecked(sp->defaultContourPen().style() == Qt::NoPen);
+    autoContourBox->setChecked(sp->useColorMapPen() &&
+                               sp->defaultContourPen().style() == Qt::NoPen);
+    // customPenBtn->setChecked(sp->defaultContourPen().style() == Qt::NoPen);
+    customPenBtn->setChecked(!sp->useColorMapPen() &&
+                             sp->defaultContourPen().style() == Qt::NoPen);
     defaultContourBox->setChecked(
-        (sp->defaultContourPen().style() != Qt::NoPen) && !(sp->useColorMapPen()));
+        (sp->defaultContourPen().style() != Qt::NoPen) &&
+        !(sp->useColorMapPen()));
 
     levelsColorBox->setColor(sp->defaultContourPen().color());
     contourWidthBox->setValue(sp->defaultContourPen().widthF());
@@ -2030,16 +1955,19 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     updateContourLevelsDisplay(sp);
 
     axisScaleBox->setChecked(sp->hasColorScale());
-    colorScaleBox->setCurrentIndex((int) sp->colorScaleAxis());
+    colorScaleBox->setCurrentIndex((int)sp->colorScaleAxis());
     colorScaleWidthBox->setValue(sp->colorBarWidth());
 
-    //labels page
+    // labels page
 
     showAllLabelControls(false);
 
     labelsGroupBox->blockSignals(true);
-    labelsGroupBox->setEnabled(sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
-    labelsGroupBox->setChecked(sp->hasLabels() && sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
+    labelsGroupBox->setEnabled(
+        sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
+    labelsGroupBox->setChecked(
+        sp->hasLabels() &&
+        sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
     boxLabelsColor->setColor(sp->labelsColor());
     boxLabelsAngle->setValue(sp->labelsRotation());
 
@@ -2060,7 +1988,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     return;
   }
 
-  PlotCurve *c = dynamic_cast<PlotCurve*>(i);
+  PlotCurve *c = dynamic_cast<PlotCurve *>(i);
   if (!c)
     return;
 
@@ -2070,9 +1998,8 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     btnEditCurve->setText(tr("&Plot Associations..."));
 
   int curveType = item->plotItemType();
-  if (curveType == Graph::Pie)
-  {
-    QwtPieCurve *pie = dynamic_cast<QwtPieCurve*>(i);
+  if (curveType == Graph::Pie) {
+    QwtPieCurve *pie = dynamic_cast<QwtPieCurve *>(i);
     if (!pie)
       return;
     boxPiePattern->setPattern(pie->pattern());
@@ -2097,7 +2024,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     boxRadius->setValue(pie->radius());
     boxRadius->blockSignals(false);
     boxPieOffset->blockSignals(true);
-    boxPieOffset->setValue((int) pie->horizontalOffset());
+    boxPieOffset->setValue((int)pie->horizontalOffset());
     boxPieOffset->blockSignals(false);
 
     pieAutoLabelsBox->setChecked(pie->labelsAutoFormat());
@@ -2110,7 +2037,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     boxPieWedge->setChecked(pie->fixedLabelsPosition());
     return;
   }
-  //line page
+  // line page
   int style = c->style();
   if (curveType == Graph::Spline)
     style = 5;
@@ -2127,7 +2054,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   fillGroupBox->blockSignals(false);
   boxAreaColor->setColor(c->brush().color());
 
-  //symbol page
+  // symbol page
   const QwtSymbol s = c->symbol();
   boxSymbolSize->setValue(s.size().width() / 2);
   boxSymbolStyle->setStyle(s.style());
@@ -2140,22 +2067,18 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   if (c->type() == Graph::Function)
     return;
 
-  if (curveType == Graph::VerticalBars || curveType == Graph::HorizontalBars
-      || curveType == Graph::Histogram)
-  {        //spacing page
-    QwtBarCurve *b = dynamic_cast<QwtBarCurve*>(i);
-    if (b)
-    {
+  if (curveType == Graph::VerticalBars || curveType == Graph::HorizontalBars ||
+      curveType == Graph::Histogram) { // spacing page
+    QwtBarCurve *b = dynamic_cast<QwtBarCurve *>(i);
+    if (b) {
       gapBox->setValue(b->gap());
       offsetBox->setValue(b->offset());
     }
   }
 
-  if (curveType == Graph::Histogram)
-  {        //Histogram page
-    QwtHistogram *h = dynamic_cast<QwtHistogram*>(i);
-    if (h)
-    {
+  if (curveType == Graph::Histogram) { // Histogram page
+    QwtHistogram *h = dynamic_cast<QwtHistogram *>(i);
+    if (h) {
       automaticBox->setChecked(h->autoBinning());
       binSizeBox->setText(QString::number(h->binSize()));
       histogramBeginBox->setText(QString::number(h->begin()));
@@ -2164,11 +2087,10 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     }
   }
 
-  if (curveType == Graph::VectXYXY || curveType == Graph::VectXYAM)
-  {        //Vector page
-    VectorCurve *v = dynamic_cast<VectorCurve*>(i);
-    if (v)
-    {
+  if (curveType == Graph::VectXYXY ||
+      curveType == Graph::VectXYAM) { // Vector page
+    VectorCurve *v = dynamic_cast<VectorCurve *>(i);
+    if (v) {
       vectColorBox->setColor(v->color());
       vectWidthBox->setValue(v->width());
       headLengthBox->setValue(v->headLength());
@@ -2179,11 +2101,9 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     }
   }
 
-  if (curveType == Graph::ErrorBars)
-  {
-    QwtErrorPlotCurve *err = dynamic_cast<QwtErrorPlotCurve*>(i);
-    if (err)
-    {
+  if (curveType == Graph::ErrorBars) {
+    QwtErrorPlotCurve *err = dynamic_cast<QwtErrorPlotCurve *>(i);
+    if (err) {
       widthBox->blockSignals(true);
       widthBox->setValue(err->width());
       widthBox->blockSignals(false);
@@ -2209,11 +2129,9 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     return;
   }
 
-  if (curveType == Graph::Box)
-  {
-    BoxCurve *b = dynamic_cast<BoxCurve*>(i);
-    if (b)
-    {
+  if (curveType == Graph::Box) {
+    BoxCurve *b = dynamic_cast<BoxCurve *>(i);
+    if (b) {
       boxMaxStyle->setStyle(b->maxStyle());
       boxMinStyle->setStyle(b->minStyle());
       boxMeanStyle->setStyle(b->meanStyle());
@@ -2232,17 +2150,19 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
       boxWidth->setValue(b->boxWidth());
       setBoxRangeType(boxRange->currentIndex());
       setBoxType(boxType->currentIndex());
-      if (b->boxRangeType() == BoxCurve::SD || b->boxRangeType() == BoxCurve::SE)
+      if (b->boxRangeType() == BoxCurve::SD ||
+          b->boxRangeType() == BoxCurve::SE)
         boxCnt->setValue(b->boxRange());
       else
-        boxCoef->setValue((int) b->boxRange());
+        boxCoef->setValue((int)b->boxRange());
 
       boxWhiskersRange->setCurrentIndex(b->whiskersRangeType());
       setWhiskersRange(boxWhiskersRange->currentIndex());
-      if (b->whiskersRangeType() == BoxCurve::SD || b->whiskersRangeType() == BoxCurve::SE)
+      if (b->whiskersRangeType() == BoxCurve::SD ||
+          b->whiskersRangeType() == BoxCurve::SE)
         whiskerCnt->setValue(b->whiskersRange());
       else
-        boxWhiskersCoef->setValue((int) b->whiskersRange());
+        boxWhiskersCoef->setValue((int)b->whiskersRange());
     }
     return;
   }
@@ -2250,8 +2170,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   const DataCurve *dc = dynamic_cast<const DataCurve *>(i);
   if (!dc)
     return;
-  if (!dc->table())
-  {
+  if (!dc->table()) {
     privateTabWidget->removeTab(privateTabWidget->indexOf(labelsPage));
     return;
   }
@@ -2272,8 +2191,7 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   boxLabelsXOffset->setValue(dc->labelsXOffset());
   boxLabelsYOffset->setValue(dc->labelsYOffset());
   boxLabelsWhiteOut->setChecked(dc->labelsWhiteOut());
-  switch (dc->labelsAlignment())
-  {
+  switch (dc->labelsAlignment()) {
   case Qt::AlignHCenter:
     boxLabelsAlign->setCurrentIndex(0);
     break;
@@ -2286,31 +2204,25 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
   }
   labelsGroupBox->blockSignals(false);
 }
-void PlotDialog::showAllLabelControls(bool show)
-{
-  if (show)
-  {
+void PlotDialog::showAllLabelControls(bool show) {
+  if (show) {
     boxLabelsColumn->show();
     boxLabelsAlign->show();
     justifyLabelsLbl->show();
     labelsColumnLbl->show();
-  }
-  else
-  {
+  } else {
     boxLabelsColumn->hide();
     boxLabelsAlign->hide();
     justifyLabelsLbl->hide();
     labelsColumnLbl->hide();
   }
 }
-void PlotDialog::updateEndPointColumns(const QString& text)
-{
+void PlotDialog::updateEndPointColumns(const QString &text) {
   QStringList cols = text.split(",", QString::SkipEmptyParts);
   QStringList aux = cols[0].split(":", QString::SkipEmptyParts);
   QString table = aux[0];
   QStringList list;
-  for (int i = 0; i < (int) columnNames.count(); i++)
-  {
+  for (int i = 0; i < (int)columnNames.count(); i++) {
     QString s = columnNames[i];
     if (s.contains(table))
       list << s;
@@ -2327,26 +2239,18 @@ void PlotDialog::updateEndPointColumns(const QString& text)
                        table + "_" + cols[3].remove("(Y)").remove("(M)"));
 }
 
-bool PlotDialog::acceptParams()
-{
-  if (privateTabWidget->currentWidget() == fontsPage)
-  {
+bool PlotDialog::acceptParams() {
+  if (privateTabWidget->currentWidget() == fontsPage) {
     d_ml->setFonts(titleFont, axesFont, numbersFont, legendFont);
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == printPage)
-  {
+  } else if (privateTabWidget->currentWidget() == printPage) {
     d_ml->setScaleLayersOnPrint(boxScaleLayers->isChecked());
     d_ml->printCropmarks(boxPrintCrops->isChecked());
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == layerPage)
-  {
-    if (boxAll->isChecked())
-    {
+  } else if (privateTabWidget->currentWidget() == layerPage) {
+    if (boxAll->isChecked()) {
       QList<Graph *> layers = d_ml->layersList();
-      foreach(Graph *g, layers)
-      {
+      foreach (Graph *g, layers) {
         g->setFrame(boxBorderWidth->value(), boxBorderColor->color());
         g->setMargin(boxMargin->value());
 
@@ -2360,44 +2264,39 @@ bool PlotDialog::acceptParams()
 
         g->setAntialiasing(boxAntialiasing->isChecked());
 
-        //Canvas frame
-        g->setCanvasFrame(boxCanvasFrameWidth->value(), boxCanvasFrameColor->color());
+        // Canvas frame
+        g->setCanvasFrame(boxCanvasFrameWidth->value(),
+                          boxCanvasFrameColor->color());
       }
-    }
-    else
-    {
-      LayerItem *item = dynamic_cast<LayerItem*>(listBox->currentItem());
-      if (!item)
-      {
+    } else {
+      LayerItem *item = dynamic_cast<LayerItem *>(listBox->currentItem());
+      if (!item) {
         return (true);
-      }
-      else
-      {
+      } else {
         Graph *g = item->graph();
         QColor c = boxBackgroundColor->color();
 
-        //background opacity & color
+        // background opacity & color
         c.setAlpha(boxBackgroundTransparency->value());
         g->setBackgroundColor(c);
-        //Canvas color & opacity
+        // Canvas color & opacity
         c = boxCanvasColor->color();
         c.setAlpha(boxCanvasTransparency->value());
         g->setCanvasBackground(c);
-        //Border color & width
+        // Border color & width
         g->setFrame(boxBorderWidth->value(), boxBorderColor->color());
-        //Anti-aliasing
+        // Anti-aliasing
         g->setAntialiasing(boxAntialiasing->isChecked());
-        //Margin
+        // Margin
         g->setMargin(boxMargin->value());
-        //Canvas frame
-        g->setCanvasFrame(boxCanvasFrameWidth->value(), boxCanvasFrameColor->color());
+        // Canvas frame
+        g->setCanvasFrame(boxCanvasFrameWidth->value(),
+                          boxCanvasFrameColor->color());
       }
     }
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == layerGeometryPage)
-  {
-    LayerItem *item = dynamic_cast<LayerItem*>(listBox->currentItem());
+  } else if (privateTabWidget->currentWidget() == layerGeometryPage) {
+    LayerItem *item = dynamic_cast<LayerItem *>(listBox->currentItem());
     if (!item)
       return false;
     Graph *g = item->graph();
@@ -2422,7 +2321,7 @@ bool PlotDialog::acceptParams()
   if (!it)
     return false;
 
-  CurveTreeItem *item = dynamic_cast<CurveTreeItem*>(it);
+  CurveTreeItem *item = dynamic_cast<CurveTreeItem *>(it);
   if (!item)
     return false;
 
@@ -2434,81 +2333,68 @@ bool PlotDialog::acceptParams()
   if (!graph)
     return false;
 
-  if (privateTabWidget->currentWidget() == axesPage)
-  {
+  if (privateTabWidget->currentWidget() == axesPage) {
     plotItem->setAxis(boxXAxis->currentIndex() + 2, boxYAxis->currentIndex());
     graph->setAutoScale();
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == spectrogramPage)
-  {
-    Spectrogram *sp = dynamic_cast<Spectrogram*>(plotItem);
+  } else if (privateTabWidget->currentWidget() == spectrogramPage) {
+    Spectrogram *sp = dynamic_cast<Spectrogram *>(plotItem);
 
-    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-    {
+    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) {
       return false;
     }
 
-    if (grayScaleBox->isChecked())
-    {
+    if (grayScaleBox->isChecked()) {
       sp->setGrayScale();
-    }
-    else if (defaultScaleBox->isChecked())
-    {
+    } else if (defaultScaleBox->isChecked()) {
       sp->setDefaultColorMap();
     }
-    //if customScaleBox radiobutton is selected it loads the colormap file and
-    //updates the spectrogram,colormap widget with the loaded file
-    else if (customScaleBox->isChecked())
-    {
+    // if customScaleBox radiobutton is selected it loads the colormap file and
+    // updates the spectrogram,colormap widget with the loaded file
+    else if (customScaleBox->isChecked()) {
       sp->mutableColorMap().loadMap(mCurrentColorMap);
       // sp->setDefaultColorMap();
       sp->setCustomColorMap(sp->mutableColorMap());
-      //sets the selected colormapfile name to spectrogram
+      // sets the selected colormapfile name to spectrogram
       sp->setColorMapFileName(mCurrentColorMap);
       if (boxSetCMapAsDefault->isChecked()) {
-        //saves the settings as default
+        // saves the settings as default
         sp->saveSettings();
       }
     }
 
-    sp->showColorScale((QwtPlot::Axis) colorScaleBox->currentIndex(), axisScaleBox->isChecked());
+    sp->showColorScale((QwtPlot::Axis)colorScaleBox->currentIndex(),
+                       axisScaleBox->isChecked());
     sp->setColorBarWidth(colorScaleWidthBox->value());
 
-    //Update axes page
+    // Update axes page
     boxXAxis->setCurrentIndex(sp->xAxis() - 2);
     boxYAxis->setCurrentIndex(sp->yAxis());
-  }
-  else if (privateTabWidget->currentPage() == contourLinesPage)
-  {
-    Spectrogram *sp = dynamic_cast<Spectrogram*>(plotItem);
+  } else if (privateTabWidget->currentPage() == contourLinesPage) {
+    Spectrogram *sp = dynamic_cast<Spectrogram *>(plotItem);
 
-    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-    {
+    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) {
       return false;
     }
 
-    if (defaultContourBox->isChecked())
-    {
+    if (defaultContourBox->isChecked()) {
       QPen pen = QPen(levelsColorBox->color(), contourWidthBox->value(),
-          Graph::getPenStyle(boxContourStyle->currentIndex()));
+                      Graph::getPenStyle(boxContourStyle->currentIndex()));
       pen.setCosmetic(true);
       sp->setDefaultContourPen(pen);
       sp->setColorMapPen(false);
-    }
-    else if (customPenBtn->isChecked())
+    } else if (customPenBtn->isChecked())
       contourLinesEditor->updateContourPens();
     else
       sp->setColorMapPen();
 
     contourLinesEditor->updateContourLevels();
-    sp->setDisplayMode(QwtPlotSpectrogram::ContourMode, levelsGroupBox->isChecked());
+    sp->setDisplayMode(QwtPlotSpectrogram::ContourMode,
+                       levelsGroupBox->isChecked());
     labelsGroupBox->setChecked(levelsGroupBox->isChecked());
     labelsGroupBox->setEnabled(levelsGroupBox->isChecked());
     sp->showContourLineLabels(levelsGroupBox->isChecked());
-  }
-  else if (privateTabWidget->currentWidget() == linePage)
-  {
+  } else if (privateTabWidget->currentWidget() == linePage) {
     int index = item->plotItemIndex();
     graph->setCurveStyle(index, boxConnect->currentIndex());
     QBrush br = QBrush(boxAreaColor->color(), boxPattern->getSelectedPattern());
@@ -2517,38 +2403,37 @@ bool PlotDialog::acceptParams()
     graph->setCurveBrush(index, br);
 
     QPen pen = QPen(boxLineColor->color(), boxLineWidth->value(),
-        Graph::getPenStyle(boxLineStyle->currentIndex()));
+                    Graph::getPenStyle(boxLineStyle->currentIndex()));
     QwtPlotCurve *curve = dynamic_cast<QwtPlotCurve *>(plotItem);
     curve->setPen(pen);
-  }
-  else if (privateTabWidget->currentWidget() == symbolPage)
-  {
+  } else if (privateTabWidget->currentWidget() == symbolPage) {
     int size = 2 * boxSymbolSize->value() + 1;
     QBrush br = QBrush(boxFillColor->color(), Qt::SolidPattern);
 
     if (!boxFillSymbol->isChecked())
       br = QBrush();
 
-    QPen pen = QPen(boxSymbolColor->color(), boxPenWidth->value(), Qt::SolidLine);
-    QwtSymbol s = QwtSymbol(boxSymbolStyle->selectedSymbol(), br, pen, QSize(size, size));
-    QwtPlotCurve *curve = dynamic_cast<QwtPlotCurve*>(plotItem);
+    QPen pen =
+        QPen(boxSymbolColor->color(), boxPenWidth->value(), Qt::SolidLine);
+    QwtSymbol s =
+        QwtSymbol(boxSymbolStyle->selectedSymbol(), br, pen, QSize(size, size));
+    QwtPlotCurve *curve = dynamic_cast<QwtPlotCurve *>(plotItem);
     curve->setSymbol(s);
-  }
-  else if (privateTabWidget->currentWidget() == histogramPage)
-  {
-    QwtHistogram *h = dynamic_cast<QwtHistogram*>(plotItem);
+  } else if (privateTabWidget->currentWidget() == histogramPage) {
+    QwtHistogram *h = dynamic_cast<QwtHistogram *>(plotItem);
     if (!h)
       return false;
 
-    if (validInput())
-    {
-      if (h->autoBinning() == automaticBox->isChecked() && h->binSize() == binSizeBox->text().toDouble()
-          && h->begin() == histogramBeginBox->text().toDouble()
-          && h->end() == histogramEndBox->text().toDouble())
+    if (validInput()) {
+      if (h->autoBinning() == automaticBox->isChecked() &&
+          h->binSize() == binSizeBox->text().toDouble() &&
+          h->begin() == histogramBeginBox->text().toDouble() &&
+          h->end() == histogramEndBox->text().toDouble())
         return true;
 
       h->setBinning(automaticBox->isChecked(), binSizeBox->text().toDouble(),
-          histogramBeginBox->text().toDouble(), histogramEndBox->text().toDouble());
+                    histogramBeginBox->text().toDouble(),
+                    histogramEndBox->text().toDouble());
       h->loadData();
 
       graph->updateScale();
@@ -2556,71 +2441,62 @@ bool PlotDialog::acceptParams()
 
       return true;
     }
-  }
-  else if (privateTabWidget->currentWidget() == spacingPage)
-    graph->setBarsGap(item->plotItemIndex(), gapBox->value(), offsetBox->value());
-  else if (privateTabWidget->currentWidget() == vectPage)
-  {
+  } else if (privateTabWidget->currentWidget() == spacingPage)
+    graph->setBarsGap(item->plotItemIndex(), gapBox->value(),
+                      offsetBox->value());
+  else if (privateTabWidget->currentWidget() == vectPage) {
     int index = item->plotItemIndex();
     if (!d_app)
       return false;
 
     QString xEndCol = xEndBox->currentText();
     QString yEndCol = yEndBox->currentText();
-    Table* w = d_app->table(xEndCol);
+    Table *w = d_app->table(xEndCol);
     if (!w)
       return false;
 
-    graph->updateVectorsLayout(index, vectColorBox->color(), vectWidthBox->value(),
-        headLengthBox->value(), headAngleBox->value(), filledHeadBox->isChecked(),
-        vectPosBox->currentIndex(), xEndCol, yEndCol);
+    graph->updateVectorsLayout(index, vectColorBox->color(),
+                               vectWidthBox->value(), headLengthBox->value(),
+                               headAngleBox->value(),
+                               filledHeadBox->isChecked(),
+                               vectPosBox->currentIndex(), xEndCol, yEndCol);
 
     QString text = item->text(0);
     QStringList t = text.split(": ", QString::SkipEmptyParts);
     QString table = t[0];
 
     QStringList cols = t[1].split(",", QString::SkipEmptyParts);
-    if (graph->curveType(index) == Graph::VectXYXY)
-    {
+    if (graph->curveType(index) == Graph::VectXYXY) {
       xEndCol = xEndCol.remove(table + "_") + "(X)";
       yEndCol = yEndCol.remove(table + "_") + "(Y)";
-    }
-    else
-    {
+    } else {
       xEndCol = xEndCol.remove(table + "_") + "(A)";
       yEndCol = yEndCol.remove(table + "_") + "(M)";
     }
 
-    if (cols[2] != xEndCol || cols[3] != yEndCol)
-    {
+    if (cols[2] != xEndCol || cols[3] != yEndCol) {
       cols[2] = xEndCol;
       cols[3] = yEndCol;
       item->setText(0, table + ": " + cols.join(","));
     }
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == errorsPage)
-  {
-    graph->updateErrorBars(dynamic_cast<QwtErrorPlotCurve*>(item->plotItem()), xBox->isChecked(),
-        widthBox->value(), capBox->currentText().toInt(), colorBox->color(), plusBox->isChecked(),
-        minusBox->isChecked(), throughBox->isChecked());
+  } else if (privateTabWidget->currentWidget() == errorsPage) {
+    graph->updateErrorBars(
+        dynamic_cast<QwtErrorPlotCurve *>(item->plotItem()), xBox->isChecked(),
+        widthBox->value(), capBox->currentText().toInt(), colorBox->color(),
+        plusBox->isChecked(), minusBox->isChecked(), throughBox->isChecked());
     return true;
-  }
-  else if (privateTabWidget->currentWidget() == piePage)
-  {
-    QwtPieCurve *pie = dynamic_cast<QwtPieCurve*>(plotItem);
+  } else if (privateTabWidget->currentWidget() == piePage) {
+    QwtPieCurve *pie = dynamic_cast<QwtPieCurve *>(plotItem);
     if (!pie)
       return false;
 
-    pie->setPen(
-        QPen(boxPieLineColor->color(), boxPieLineWidth->value(),
-            Graph::getPenStyle(boxPieLineStyle->currentIndex())));
+    pie->setPen(QPen(boxPieLineColor->color(), boxPieLineWidth->value(),
+                     Graph::getPenStyle(boxPieLineStyle->currentIndex())));
     pie->setBrushStyle(boxPiePattern->getSelectedPattern());
     pie->setFirstColor(boxFirstColor->currentIndex());
-  }
-  else if (privateTabWidget->currentWidget() == pieGeometryPage)
-  {
-    QwtPieCurve *pie = dynamic_cast<QwtPieCurve*>(plotItem);
+  } else if (privateTabWidget->currentWidget() == pieGeometryPage) {
+    QwtPieCurve *pie = dynamic_cast<QwtPieCurve *>(plotItem);
     if (!pie)
       return false;
 
@@ -2630,10 +2506,8 @@ bool PlotDialog::acceptParams()
     pie->setHorizontalOffset(boxPieOffset->value());
     pie->setStartAzimuth(boxPieStartAzimuth->value());
     pie->setCounterClockwise(boxPieConterClockwise->isChecked());
-  }
-  else if (privateTabWidget->currentWidget() == pieLabelsPage)
-  {
-    QwtPieCurve *pie = dynamic_cast<QwtPieCurve*>(plotItem);
+  } else if (privateTabWidget->currentWidget() == pieLabelsPage) {
+    QwtPieCurve *pie = dynamic_cast<QwtPieCurve *>(plotItem);
     if (!pie)
       return false;
 
@@ -2644,12 +2518,9 @@ bool PlotDialog::acceptParams()
     pie->setFixedLabelsPosition(boxPieWedge->isChecked());
     pie->setLabelsEdgeDistance(boxPieEdgeDist->value());
     graph->replot();
-  }
-  else if (privateTabWidget->currentWidget() == percentilePage)
-  {
-    BoxCurve *b = dynamic_cast<BoxCurve*>(plotItem);
-    if (b)
-    {
+  } else if (privateTabWidget->currentWidget() == percentilePage) {
+    BoxCurve *b = dynamic_cast<BoxCurve *>(plotItem);
+    if (b) {
       b->setMaxStyle(boxMaxStyle->selectedSymbol());
       b->setP99Style(box99Style->selectedSymbol());
       b->setMeanStyle(boxMeanStyle->selectedSymbol());
@@ -2660,44 +2531,41 @@ bool PlotDialog::acceptParams()
       QBrush br = QBrush(boxPercFillColor->color(), Qt::SolidPattern);
       if (!boxFillSymbols->isChecked())
         br = QBrush();
-      QwtSymbol s = QwtSymbol(QwtSymbol::NoSymbol, br,
-          QPen(boxEdgeColor->color(), boxEdgeWidth->value(), Qt::SolidLine), QSize(size, size));
+      QwtSymbol s = QwtSymbol(
+          QwtSymbol::NoSymbol, br,
+          QPen(boxEdgeColor->color(), boxEdgeWidth->value(), Qt::SolidLine),
+          QSize(size, size));
       b->setSymbol(s);
     }
-  }
-  else if (privateTabWidget->currentWidget() == boxPage)
-  {
-    BoxCurve *b = dynamic_cast<BoxCurve*>(plotItem);
-    if (b)
-    {
+  } else if (privateTabWidget->currentWidget() == boxPage) {
+    BoxCurve *b = dynamic_cast<BoxCurve *>(plotItem);
+    if (b) {
       b->setBoxWidth(boxWidth->value());
       b->setBoxStyle(boxType->currentIndex());
       if (boxCnt->isVisible())
         b->setBoxRange(boxRange->currentIndex() + 1, boxCnt->value());
       else
-        b->setBoxRange(boxRange->currentIndex() + 1, (double) boxCoef->value());
+        b->setBoxRange(boxRange->currentIndex() + 1, (double)boxCoef->value());
 
       if (whiskerCnt->isVisible())
-        b->setWhiskersRange(boxWhiskersRange->currentIndex(), whiskerCnt->value());
+        b->setWhiskersRange(boxWhiskersRange->currentIndex(),
+                            whiskerCnt->value());
       else
-        b->setWhiskersRange(boxWhiskersRange->currentIndex(), (double) boxWhiskersCoef->value());
+        b->setWhiskersRange(boxWhiskersRange->currentIndex(),
+                            (double)boxWhiskersCoef->value());
     }
-  }
-  else if (privateTabWidget->currentWidget() == labelsPage)
-  {
+  } else if (privateTabWidget->currentWidget() == labelsPage) {
 
-    Spectrogram *sp = dynamic_cast<Spectrogram*>(plotItem);
-    if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram)
-    {
+    Spectrogram *sp = dynamic_cast<Spectrogram *>(plotItem);
+    if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) {
       sp->setLabelsRotation(boxLabelsAngle->value());
       sp->setLabelsColor(boxLabelsColor->color());
       sp->showContourLineLabels(labelsGroupBox->isChecked());
       sp->setLabelsWhiteOut(boxLabelsWhiteOut->isChecked());
-      sp->setLabelsOffset((double) boxLabelsXOffset->value(), (double) boxLabelsYOffset->value());
+      sp->setLabelsOffset((double)boxLabelsXOffset->value(),
+                          (double)boxLabelsYOffset->value());
 
-    }
-    else
-    {
+    } else {
       DataCurve *c = dynamic_cast<DataCurve *>(plotItem);
       if (!c)
         return false;
@@ -2707,20 +2575,17 @@ bool PlotDialog::acceptParams()
       QString table = t[0];
       QStringList cols = t[1].split(",", QString::SkipEmptyParts);
 
-      if (labelsGroupBox->isChecked())
-      {
+      if (labelsGroupBox->isChecked()) {
         c->setLabelsColumnName(boxLabelsColumn->currentText());
 
         if (cols.count() == 3)
           cols[2] = boxLabelsColumn->currentText().remove(table + "_") + "(L)";
-        else if (cols.count() == 5)     //vector curves
+        else if (cols.count() == 5) // vector curves
           cols[4] = boxLabelsColumn->currentText().remove(table + "_") + "(L)";
         else
           cols << boxLabelsColumn->currentText().remove(table + "_") + "(L)";
         item->setText(0, table + ": " + cols.join(","));
-      }
-      else
-      {
+      } else {
         c->setLabelsColumnName(QString());
         cols.pop_back();
         item->setText(0, table + ": " + cols.join(","));
@@ -2739,36 +2604,33 @@ bool PlotDialog::acceptParams()
   return true;
 }
 
-void PlotDialog::setAutomaticBinning()
-{
+void PlotDialog::setAutomaticBinning() {
   GroupBoxH->setEnabled(!automaticBox->isChecked());
 }
 
-bool PlotDialog::validInput()
-{
+bool PlotDialog::validInput() {
   QString from = histogramBeginBox->text();
   QString to = histogramEndBox->text();
   QString step = binSizeBox->text();
   QRegExp nonDigit("\\D");
 
-  if (histogramBeginBox->text().isEmpty())
-  {
-    QMessageBox::critical(this, tr("MantidPlot - Input error"), tr("Please enter a valid start limit!"));
+  if (histogramBeginBox->text().isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input error"),
+                          tr("Please enter a valid start limit!"));
     histogramBeginBox->setFocus();
     return false;
   }
 
-  if (histogramEndBox->text().isEmpty())
-  {
-    QMessageBox::critical(this, tr("MantidPlot - Input error"), tr("Please enter a valid end limit!"));
+  if (histogramEndBox->text().isEmpty()) {
+    QMessageBox::critical(this, tr("MantidPlot - Input error"),
+                          tr("Please enter a valid end limit!"));
     histogramEndBox->setFocus();
     return false;
   }
 
-  if (binSizeBox->text().isEmpty())
-  {
+  if (binSizeBox->text().isEmpty()) {
     QMessageBox::critical(this, tr("MantidPlot - Input error"),
-        tr("Please enter a valid bin size value!"));
+                          tr("Please enter a valid bin size value!"));
     binSizeBox->setFocus();
     return false;
   }
@@ -2786,80 +2648,65 @@ bool PlotDialog::validInput()
     to = to.replace(pos, 1, "");
 
   double start, end, stp;
-  if (from.contains(nonDigit))
-  {
-    try
-    {
+  if (from.contains(nonDigit)) {
+    try {
       MyParser parser;
       parser.SetExpr(histogramBeginBox->text().toAscii().constData());
       start = parser.Eval();
-    } catch (mu::ParserError &e)
-    {
+    } catch (mu::ParserError &e) {
       QMessageBox::critical(this, tr("MantidPlot - Start limit error"),
-          QString::fromStdString(e.GetMsg()));
+                            QString::fromStdString(e.GetMsg()));
       histogramBeginBox->setFocus();
       return false;
     }
-  }
-  else
+  } else
     start = histogramBeginBox->text().toDouble();
 
-  if (to.contains(nonDigit))
-  {
-    try
-    {
+  if (to.contains(nonDigit)) {
+    try {
       MyParser parser;
       parser.SetExpr(histogramEndBox->text().toAscii().constData());
       end = parser.Eval();
-    } catch (mu::ParserError &e)
-    {
+    } catch (mu::ParserError &e) {
       QMessageBox::critical(this, tr("MantidPlot - End limit error"),
-          QString::fromStdString(e.GetMsg()));
+                            QString::fromStdString(e.GetMsg()));
       histogramEndBox->setFocus();
       return false;
     }
-  }
-  else
+  } else
     end = histogramEndBox->text().toDouble();
 
-  if (start >= end)
-  {
+  if (start >= end) {
     QMessageBox::critical(this, tr("MantidPlot - Input error"),
-        tr("Please enter limits that satisfy: begin < end!"));
+                          tr("Please enter limits that satisfy: begin < end!"));
     histogramEndBox->setFocus();
     return false;
   }
 
-  if (step.contains(nonDigit))
-  {
-    try
-    {
+  if (step.contains(nonDigit)) {
+    try {
       MyParser parser;
       parser.SetExpr((binSizeBox->text()).toAscii().constData());
       stp = parser.Eval();
-    } catch (mu::ParserError &e)
-    {
+    } catch (mu::ParserError &e) {
       QMessageBox::critical(this, tr("MantidPlot - Bin size input error"),
-          QString::fromStdString(e.GetMsg()));
+                            QString::fromStdString(e.GetMsg()));
       binSizeBox->setFocus();
       return false;
     }
-  }
-  else
+  } else
     stp = binSizeBox->text().toDouble();
 
-  if (stp <= 0)
-  {
+  if (stp <= 0) {
     QMessageBox::critical(this, tr("MantidPlot - Bin size input error"),
-        tr("Please enter a positive bin size value!"));
+                          tr("Please enter a positive bin size value!"));
     binSizeBox->setFocus();
     return false;
   }
 
   return true;
 }
-void PlotDialog::setPiePenStyle(const Qt::PenStyle& style)
-{
+void PlotDialog::setPiePenStyle(const Qt::PenStyle &style) {
   if (style == Qt::SolidLine)
     boxPieLineStyle->setCurrentIndex(0);
   if (style == Qt::DashLine)
@@ -2872,10 +2719,8 @@ void PlotDialog::setPiePenStyle(const Qt::PenStyle& style)
     boxPieLineStyle->setCurrentIndex(4);
 }
 
-void PlotDialog::setPenStyle(Qt::PenStyle style)
-{
-  switch (style)
-  {
+void PlotDialog::setPenStyle(Qt::PenStyle style) {
+  switch (style) {
   case Qt::SolidLine:
     boxLineStyle->setCurrentIndex(0);
     break;
@@ -2897,8 +2742,7 @@ void PlotDialog::setPenStyle(Qt::PenStyle style)
   }
 }
 
-void PlotDialog::setBoxType(int index)
-{
+void PlotDialog::setBoxType(int index) {
   boxCoeffLabel->hide();
   boxRangeLabel->hide();
   boxRange->hide();
@@ -2906,75 +2750,59 @@ void PlotDialog::setBoxType(int index)
   boxCntLabel->hide();
   boxCnt->hide();
 
-  if (index != BoxCurve::NoBox && index != BoxCurve::WindBox)
-  {
+  if (index != BoxCurve::NoBox && index != BoxCurve::WindBox) {
     boxRange->show();
     boxRangeLabel->show();
     int id = boxRange->currentIndex() + 1;
-    if (id == BoxCurve::UserDef)
-    {
+    if (id == BoxCurve::UserDef) {
       boxCoef->show();
       boxCoeffLabel->show();
-    }
-    else if (id == BoxCurve::SD || id == BoxCurve::SE)
-    {
+    } else if (id == BoxCurve::SD || id == BoxCurve::SE) {
       boxCntLabel->show();
       boxCnt->show();
     }
   }
 }
 
-void PlotDialog::setBoxRangeType(int index)
-{
+void PlotDialog::setBoxRangeType(int index) {
   boxCoeffLabel->hide();
   boxCoef->hide();
   boxCntLabel->hide();
   boxCnt->hide();
 
   index++;
-  if (index == BoxCurve::UserDef)
-  {
+  if (index == BoxCurve::UserDef) {
     boxCoeffLabel->show();
     boxCoef->show();
-  }
-  else if (index == BoxCurve::SD || index == BoxCurve::SE)
-  {
+  } else if (index == BoxCurve::SD || index == BoxCurve::SE) {
     boxCntLabel->show();
     boxCnt->show();
   }
 }
 
-void PlotDialog::setWhiskersRange(int index)
-{
+void PlotDialog::setWhiskersRange(int index) {
   whiskerCoeffLabel->hide();
   boxWhiskersCoef->hide();
   whiskerCntLabel->hide();
   whiskerCnt->hide();
 
-  if (index == BoxCurve::UserDef)
-  {
+  if (index == BoxCurve::UserDef) {
     whiskerCoeffLabel->show();
     boxWhiskersCoef->show();
-  }
-  else if (index == BoxCurve::SD || index == BoxCurve::SE)
-  {
+  } else if (index == BoxCurve::SD || index == BoxCurve::SE) {
     whiskerCntLabel->show();
     whiskerCnt->show();
   }
 }
 
-void PlotDialog::customVectorsPage(bool angleMag)
-{
-  if (angleMag)
-  {
+void PlotDialog::customVectorsPage(bool angleMag) {
+  if (angleMag) {
     GroupBoxVectEnd->setTitle(tr("Vector Data"));
     labelXEnd->setText(tr("Angle"));
     labelYEnd->setText(tr("Magnitude"));
     labelPosition->show();
     vectPosBox->show();
-  }
-  else
-  {
+  } else {
     GroupBoxVectEnd->setTitle(tr("End Point"));
     labelXEnd->setText(tr("X End"));
     labelYEnd->setText(tr("Y End"));
@@ -2986,28 +2814,24 @@ void PlotDialog::customVectorsPage(bool angleMag)
 /**
  This slot gets called on clicking slect colormap button
  */
-void PlotDialog::changeColormap(const QString &filename)
-{
-  //loads the settings to get the colormap file name.
-  //as theres is no spectrgram valid pointer here i'm directly using Qsetting
+void PlotDialog::changeColormap(const QString &filename) {
+  // loads the settings to get the colormap file name.
+  // as theres is no spectrgram valid pointer here i'm directly using Qsetting
   // instead of Spectrogram::loadSettings()
-  //mCurrentColorMap gives the last selected colormap file name
+  // mCurrentColorMap gives the last selected colormap file name
   QSettings settings;
   settings.beginGroup("Mantid/2DPlotSpectrogram");
-  //Load Colormap. If the file is invalid the default stored colour map is used
+  // Load Colormap. If the file is invalid the default stored colour map is used
   mCurrentColorMap = settings.value("ColormapFile", "").toString();
   settings.endGroup();
 
   QString fileselection;
-  //Use a file dialog if no parameter is passed
-  if (filename.isEmpty())
-  {
+  // Use a file dialog if no parameter is passed
+  if (filename.isEmpty()) {
     fileselection = MantidColorMap::loadMapDialog(mCurrentColorMap, this);
     if (fileselection.isEmpty())
       return;
-  }
-  else
-  {
+  } else {
     fileselection = QFileInfo(filename).absoluteFilePath();
     if (!QFileInfo(fileselection).exists())
       return;
@@ -3020,16 +2844,14 @@ void PlotDialog::changeColormap(const QString &filename)
   setColorMapName();
 }
 
-void PlotDialog::showDefaultContourLinesBox(bool)
-{
+void PlotDialog::showDefaultContourLinesBox(bool) {
   if (autoContourBox->isChecked())
     defaultPenBox->hide();
   else
     defaultPenBox->show();
 }
 
-void PlotDialog::updateTreeWidgetItem(QTreeWidgetItem *item)
-{
+void PlotDialog::updateTreeWidgetItem(QTreeWidgetItem *item) {
   if (item->type() != QTreeWidgetItem::Type)
     return;
 
@@ -3039,110 +2861,89 @@ void PlotDialog::updateTreeWidgetItem(QTreeWidgetItem *item)
     item->setIcon(0, QIcon(getQPixmap("folder_closed")));
 }
 
-void PlotDialog::setTitlesFont()
-{
+void PlotDialog::setTitlesFont() {
   bool ok;
   QFont font = QFontDialog::getFont(&ok, titleFont, this);
-  if (ok)
-  {
+  if (ok) {
     titleFont = font;
-  }
-  else
-  {
+  } else {
     return;
   }
 }
 
-void PlotDialog::setAxesLabelsFont()
-{
+void PlotDialog::setAxesLabelsFont() {
   bool ok;
   QFont font = QFontDialog::getFont(&ok, axesFont, this);
-  if (ok)
-  {
+  if (ok) {
     axesFont = font;
-  }
-  else
-  {
+  } else {
     return;
   }
 }
 
-void PlotDialog::setAxesNumbersFont()
-{
+void PlotDialog::setAxesNumbersFont() {
   bool ok;
   QFont font = QFontDialog::getFont(&ok, numbersFont, this);
-  if (ok)
-  {
+  if (ok) {
     numbersFont = font;
-  }
-  else
-  {
+  } else {
     return;
   }
 }
 
-void PlotDialog::setLegendsFont()
-{
+void PlotDialog::setLegendsFont() {
   bool ok;
   QFont font = QFontDialog::getFont(&ok, legendFont, this);
-  if (ok)
-  {
+  if (ok) {
     legendFont = font;
-  }
-  else
-  {
+  } else {
     return;
   }
 }
 
-void PlotDialog::initFonts(const QFont& titlefont, const QFont& axesfont, const QFont& numbersfont,
-    const QFont& legendfont)
-{
+void PlotDialog::initFonts(const QFont &titlefont, const QFont &axesfont,
+                           const QFont &numbersfont, const QFont &legendfont) {
   axesFont = axesfont;
   titleFont = titlefont;
   numbersFont = numbersfont;
   legendFont = legendfont;
 }
 
-void PlotDialog::adjustLayerHeight(int width)
-{
-  if (keepRatioBox->isChecked())
-  {
-    disconnect(boxLayerHeight, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerWidth(int) ));
+void PlotDialog::adjustLayerHeight(int width) {
+  if (keepRatioBox->isChecked()) {
+    disconnect(boxLayerHeight, SIGNAL(valueChanged(int)), this,
+               SLOT(adjustLayerWidth(int)));
     boxLayerHeight->setValue(static_cast<int>(width / aspect_ratio));
-    connect(boxLayerHeight, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerWidth(int) ));
-  }
-  else
-    aspect_ratio = (double) width / double(boxLayerHeight->value());
+    connect(boxLayerHeight, SIGNAL(valueChanged(int)), this,
+            SLOT(adjustLayerWidth(int)));
+  } else
+    aspect_ratio = (double)width / double(boxLayerHeight->value());
 }
 
-void PlotDialog::adjustLayerWidth(int height)
-{
-  if (keepRatioBox->isChecked())
-  {
-    disconnect(boxLayerWidth, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerHeight(int) ));
+void PlotDialog::adjustLayerWidth(int height) {
+  if (keepRatioBox->isChecked()) {
+    disconnect(boxLayerWidth, SIGNAL(valueChanged(int)), this,
+               SLOT(adjustLayerHeight(int)));
     boxLayerWidth->setValue(static_cast<int>(height * aspect_ratio));
-    connect(boxLayerWidth, SIGNAL( valueChanged ( int ) ), this, SLOT( adjustLayerHeight(int) ));
-  }
-  else
-    aspect_ratio = double(boxLayerWidth->value()) / (double) height;
+    connect(boxLayerWidth, SIGNAL(valueChanged(int)), this,
+            SLOT(adjustLayerHeight(int)));
+  } else
+    aspect_ratio = double(boxLayerWidth->value()) / (double)height;
 }
 
-void PlotDialog::closeEvent(QCloseEvent* e)
-{
+void PlotDialog::closeEvent(QCloseEvent *e) {
   if (d_app)
     d_app->d_extended_plot_dialog = btnMore->isChecked();
 
   e->accept();
 }
 
-void PlotDialog::chooseLabelsFont()
-{
+void PlotDialog::chooseLabelsFont() {
   QTreeWidgetItem *item = listBox->currentItem();
   if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
     return;
 
-  CurveTreeItem* ctit = dynamic_cast<CurveTreeItem*>(item);
+  CurveTreeItem *ctit = dynamic_cast<CurveTreeItem *>(item);
   if (!ctit)
     return;
 
@@ -3156,19 +2957,16 @@ void PlotDialog::chooseLabelsFont()
     return;
   bool okF;
   QFont fnt = QFontDialog::getFont(&okF, c->labelsFont(), this);
-  if (okF && fnt != c->labelsFont())
-  {
+  if (okF && fnt != c->labelsFont()) {
     c->setLabelsFont(fnt);
     graph->replot();
     graph->notifyChanges();
   }
 }
 
-int PlotDialog::labelsAlignment()
-{
+int PlotDialog::labelsAlignment() {
   int align = -1;
-  switch (boxLabelsAlign->currentIndex())
-  {
+  switch (boxLabelsAlign->currentIndex()) {
   case 0:
     align = Qt::AlignHCenter;
     break;
@@ -3190,47 +2988,39 @@ int PlotDialog::labelsAlignment()
  *
  *****************************************************************************/
 
-LayerItem::LayerItem(Graph *g, QTreeWidgetItem *parent, const QString& s) :
-    QTreeWidgetItem(parent, QStringList(s), LayerTreeItem), d_graph(g)
-{
+LayerItem::LayerItem(Graph *g, QTreeWidgetItem *parent, const QString &s)
+    : QTreeWidgetItem(parent, QStringList(s), LayerTreeItem), d_graph(g) {
   setIcon(0, getQPixmap("layer_disabled_xpm"));
   if (g)
     insertCurvesList();
 }
 
-void LayerItem::setActive(bool on)
-{
+void LayerItem::setActive(bool on) {
   if (on)
     setIcon(0, getQPixmap("layer_enabled_xpm"));
   else
     setIcon(0, getQPixmap("layer_disabled_xpm"));
 }
 
-void LayerItem::insertCurvesList()
-{
-  for (int i = 0; i < d_graph->curves(); i++)
-  {
+void LayerItem::insertCurvesList() {
+  for (int i = 0; i < d_graph->curves(); i++) {
     QString plotAssociation = QString();
     QwtPlotItem *it = dynamic_cast<QwtPlotItem *>(d_graph->plotItem(i));
     if (!it)
       continue;
 
-    if (it->rtti() == QwtPlotItem::Rtti_PlotCurve)
-    {
+    if (it->rtti() == QwtPlotItem::Rtti_PlotCurve) {
       PlotCurve *c = dynamic_cast<PlotCurve *>(it);
-      DataCurve* dc = dynamic_cast<DataCurve *>(it);
-      if (c && dc && c->type() != Graph::Function && dc->table())
-      {
+      DataCurve *dc = dynamic_cast<DataCurve *>(it);
+      if (c && dc && c->type() != Graph::Function && dc->table()) {
         QString s = dc->plotAssociation();
         QString table = dc->table()->name();
         plotAssociation = table + ": " + s.remove(table + "_");
-      }
-      else
-      {
+      } else {
         plotAssociation = it->title().text();
       }
-    }
-    else  // builds the names/labels of special (non-) curves within layers displayed in tree entries
+    } else // builds the names/labels of special (non-) curves within layers
+           // displayed in tree entries
     {
       if (d_graph->isSpectrogram() || it->title().isEmpty())
         plotAssociation = it->title().text() + " Layer details (editable)";
@@ -3248,14 +3038,14 @@ void LayerItem::insertCurvesList()
  *
  *****************************************************************************/
 
-CurveTreeItem::CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QString& s) :
-    QTreeWidgetItem(parent, QStringList(s), PlotCurveTreeItem), d_curve(curve)
-{
+CurveTreeItem::CurveTreeItem(QwtPlotItem *curve, LayerItem *parent,
+                             const QString &s)
+    : QTreeWidgetItem(parent, QStringList(s), PlotCurveTreeItem),
+      d_curve(curve) {
   setIcon(0, getQPixmap("graph_disabled_xpm"));
 }
 
-Graph* CurveTreeItem::graph()
-{
+Graph *CurveTreeItem::graph() {
   LayerItem *l = dynamic_cast<LayerItem *>(parent());
   if (l) {
     return l->graph();
@@ -3264,16 +3054,14 @@ Graph* CurveTreeItem::graph()
   }
 }
 
-void CurveTreeItem::setActive(bool on)
-{
+void CurveTreeItem::setActive(bool on) {
   if (on)
     setIcon(0, getQPixmap("graph_xpm"));
   else
     setIcon(0, getQPixmap("graph_disabled_xpm"));
 }
 
-int CurveTreeItem::plotItemIndex()
-{
+int CurveTreeItem::plotItemIndex() {
   Graph *g = graph();
   if (!g)
     return -1;
@@ -3281,8 +3069,7 @@ int CurveTreeItem::plotItemIndex()
   return g->plotItemIndex(dynamic_cast<QwtPlotItem *>(d_curve));
 }
 
-int CurveTreeItem::plotItemType()
-{
+int CurveTreeItem::plotItemType() {
   Graph *g = graph();
   if (!g)
     return -1;
diff --git a/MantidPlot/src/PlotDialog.h b/MantidPlot/src/PlotDialog.h
index 61056ec0b87933ce7668eff3f352fc57d2f1927b..5994d8b9f08e670e79cd5d874dd9d2bfa4585dfa 100644
--- a/MantidPlot/src/PlotDialog.h
+++ b/MantidPlot/src/PlotDialog.h
@@ -2,7 +2,8 @@
     File                 : PlotDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Custom curves dialog
 
@@ -34,8 +35,6 @@
 #include "MultiLayer.h"
 //#include "MantidKernel/Logger.h"
 
-
-
 class QCheckBox;
 class QComboBox;
 class QLabel;
@@ -66,16 +65,18 @@ class ContourLinesEditor;
 class ApplicationWindow;
 
 //! Custom plot/curves dialog
-class PlotDialog : public QDialog
-{
+class PlotDialog : public QDialog {
   Q_OBJECT
 
 public:
-  PlotDialog(bool showExtended, ApplicationWindow* app, MultiLayer *ml, Qt::WFlags fl = 0 );
-  void initFonts(const QFont& titlefont, const QFont& axesfont, const QFont& numbersfont, const QFont& legendfont);
-  void insertColumnsList(const QStringList& names){columnNames = names;};
+  PlotDialog(bool showExtended, ApplicationWindow *app, MultiLayer *ml,
+             Qt::WFlags fl = 0);
+  void initFonts(const QFont &titlefont, const QFont &axesfont,
+                 const QFont &numbersfont, const QFont &legendfont);
+  void insertColumnsList(const QStringList &names) { columnNames = names; };
 
-  void setPlotType(int plotType, int curveNum, const QString & color = "Default");
+  void setPlotType(int plotType, int curveNum,
+                   const QString &color = "Default");
 
 public slots:
   void showAll(bool all);
@@ -84,7 +85,7 @@ public slots:
 private slots:
   void showStatistics();
   void customVectorsPage(bool angleMag);
-  void updateEndPointColumns(const QString& text);
+  void updateEndPointColumns(const QString &text);
 
   void showBoxSymbols(bool show);
   bool acceptParams();
@@ -97,7 +98,8 @@ private slots:
   void setActiveCurve(CurveTreeItem *item);
 
   void insertTabs(int plot_type);
-  void updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *previousItem);
+  void updateTabWindow(QTreeWidgetItem *currentItem,
+                       QTreeWidgetItem *previousItem);
   void showAreaColor(bool show);
 
   void removeSelectedCurve();
@@ -107,21 +109,21 @@ private slots:
   void showPlotAssociations(QTreeWidgetItem *item, int);
 
   void setPenStyle(Qt::PenStyle style);
-  void setPiePenStyle(const Qt::PenStyle& style);
+  void setPiePenStyle(const Qt::PenStyle &style);
 
-  //box plots
+  // box plots
   void setBoxType(int index);
   void setBoxRangeType(int index);
   void setWhiskersRange(int index);
 
-  //spectrograms
+  // spectrograms
   void showDefaultContourLinesBox(bool show);
   void showColorMapEditor(bool show);
 
-  //layer geometry
+  // layer geometry
   void adjustLayerHeight(int width);
   void adjustLayerWidth(int height);
-  void changeColormap(const QString & filename = "");
+  void changeColormap(const QString &filename = "");
   void setEquidistantLevels();
 
 protected slots:
@@ -175,76 +177,84 @@ private:
   MultiLayer *d_ml;
   QStringList columnNames;
 
-  QSpinBox* boxX, *boxY, *boxLayerWidth, *boxLayerHeight;
+  QSpinBox *boxX, *boxY, *boxLayerWidth, *boxLayerHeight;
   QCheckBox *keepRatioBox;
   QCheckBox *keepRatioOnResizeBox;
 
   QPushButton *btnTitle, *btnAxesLabels, *btnAxesNumbers, *btnLegend;
   ColorMapEditor *colorMapEditor;
   QLabel *mLabelCurrentColormap;
-  QPushButton* mSelectColormap;
+  QPushButton *mSelectColormap;
   QString mCurrentColorMap;
-  QWidget *curvePlotTypeBox, *layerPage, *layerGeometryPage, *piePage, *fontsPage, *printPage, *contourLinesPage;
-  QTreeWidget* listBox;
-  QCheckBox *boxAntialiasing, *boxAll, *boxScaleLayers, *boxPrintCrops, *boxSetCMapAsDefault;
-  ColorButton *boxBorderColor, *boxBackgroundColor, *boxCanvasColor, *boxCanvasFrameColor;
-  QSpinBox *boxBackgroundTransparency, *boxCanvasTransparency, *boxBorderWidth, *boxMargin, *boxCanvasFrameWidth;
+  QWidget *curvePlotTypeBox, *layerPage, *layerGeometryPage, *piePage,
+      *fontsPage, *printPage, *contourLinesPage;
+  QTreeWidget *listBox;
+  QCheckBox *boxAntialiasing, *boxAll, *boxScaleLayers, *boxPrintCrops,
+      *boxSetCMapAsDefault;
+  ColorButton *boxBorderColor, *boxBackgroundColor, *boxCanvasColor,
+      *boxCanvasFrameColor;
+  QSpinBox *boxBackgroundTransparency, *boxCanvasTransparency, *boxBorderWidth,
+      *boxMargin, *boxCanvasFrameWidth;
   QSpinBox *boxRadius;
   DoubleSpinBox *boxPieLineWidth;
   ColorBox *boxFirstColor, *boxPieLineColor;
   PatternBox *boxPiePattern;
-  QComboBox* boxPieLineStyle;
-
-  QPushButton* buttonApply, *btnWorksheet;
-  QPushButton* buttonOk, *btnMore;
-  QPushButton* buttonCancel;
-  QComboBox* boxPlotType;
-  QWidget* linePage;
-  QComboBox* boxConnect;
-  QComboBox* boxLineStyle;
+  QComboBox *boxPieLineStyle;
+
+  QPushButton *buttonApply, *btnWorksheet;
+  QPushButton *buttonOk, *btnMore;
+  QPushButton *buttonCancel;
+  QComboBox *boxPlotType;
+  QWidget *linePage;
+  QComboBox *boxConnect;
+  QComboBox *boxLineStyle;
   DoubleSpinBox *boxLineWidth, *boxPenWidth;
-  ColorBox* boxLineColor, *boxAreaColor;
-  QWidget* symbolPage;
-  QSpinBox* boxSymbolSize;
-  ColorBox* boxSymbolColor,*boxFillColor;
-  SymbolBox* boxSymbolStyle;
+  ColorBox *boxLineColor, *boxAreaColor;
+  QWidget *symbolPage;
+  QSpinBox *boxSymbolSize;
+  ColorBox *boxSymbolColor, *boxFillColor;
+  SymbolBox *boxSymbolStyle;
   PatternBox *boxPattern;
-  QTabWidget* privateTabWidget;
+  QTabWidget *privateTabWidget;
   QWidget *errorsPage, *spectrogramPage;
-  QGroupBox* fillGroupBox;
-  QCheckBox* plusBox;
-  QCheckBox* minusBox;
-  QCheckBox* xBox;
+  QGroupBox *fillGroupBox;
+  QCheckBox *plusBox;
+  QCheckBox *minusBox;
+  QCheckBox *xBox;
   ColorButton *colorBox, *levelsColorBox;
-  ColorBox* vectColorBox;
-  DoubleSpinBox* widthBox;
-  QComboBox* capBox;
-  QCheckBox* throughBox;
-  QLabel *labelPosition, *labelXEnd, *labelYEnd,*justifyLabelsLbl,*labelsColumnLbl;
-  QGroupBox* GroupBoxH;
+  ColorBox *vectColorBox;
+  DoubleSpinBox *widthBox;
+  QComboBox *capBox;
+  QCheckBox *throughBox;
+  QLabel *labelPosition, *labelXEnd, *labelYEnd, *justifyLabelsLbl,
+      *labelsColumnLbl;
+  QGroupBox *GroupBoxH;
   QWidget *histogramPage, *spacingPage;
   QLineEdit *binSizeBox, *histogramBeginBox, *histogramEndBox;
   QCheckBox *automaticBox;
-  QPushButton* buttonStatistics, *btnEditCurve;
-  QSpinBox* gapBox, *offsetBox, *boxWidth;
+  QPushButton *buttonStatistics, *btnEditCurve;
+  QSpinBox *gapBox, *offsetBox, *boxWidth;
   QWidget *vectPage, *boxPage, *percentilePage, *axesPage;
-  QComboBox *xEndBox, *yEndBox, *boxType, *boxWhiskersType, *boxWhiskersRange, *boxRange;
-  QSpinBox* headAngleBox, *headLengthBox, *boxPercSize;
+  QComboBox *xEndBox, *yEndBox, *boxType, *boxWhiskersType, *boxWhiskersRange,
+      *boxRange;
+  QSpinBox *headAngleBox, *headLengthBox, *boxPercSize;
   DoubleSpinBox *vectWidthBox, *boxEdgeWidth;
   QCheckBox *filledHeadBox;
   QSpinBox *boxCoef, *boxWhiskersCoef;
   QCheckBox *boxFillSymbols, *boxFillSymbol;
   ColorBox *boxPercFillColor, *boxEdgeColor;
-  QLabel 	*whiskerCoeffLabel, *whiskerRangeLabel, *boxCoeffLabel;
+  QLabel *whiskerCoeffLabel, *whiskerRangeLabel, *boxCoeffLabel;
   QLabel *boxRangeLabel, *whiskerCntLabel, *boxCntLabel;
   QGroupBox *GroupBoxVectEnd;
-  QComboBox *vectPosBox, *boxXAxis, *boxYAxis, *colorScaleBox;//, *boxContourStyle;
-  PenStyleBox	*penContourStyle,*boxContourStyle;
+  QComboBox *vectPosBox, *boxXAxis, *boxYAxis,
+      *colorScaleBox; //, *boxContourStyle;
+  PenStyleBox *penContourStyle, *boxContourStyle;
   QSpinBox *levelsBox, *colorScaleWidthBox;
   DoubleSpinBox *contourWidthBox;
   QGroupBox *levelsGroupBox, *axisScaleBox, *imageGroupBox;
   QGroupBox *defaultPenBox;
-  QRadioButton *defaultScaleBox, *grayScaleBox, *customScaleBox, *defaultContourBox, *autoContourBox;
+  QRadioButton *defaultScaleBox, *grayScaleBox, *customScaleBox,
+      *defaultContourBox, *autoContourBox;
 
   SymbolBox *boxMaxStyle, *boxMinStyle, *boxMeanStyle, *box99Style, *box1Style;
   QDoubleSpinBox *whiskerCnt, *boxCnt;
@@ -253,20 +263,22 @@ private:
   DoubleSpinBox *boxLabelsAngle;
   QSpinBox *boxLabelsXOffset, *boxLabelsYOffset;
   QCheckBox *boxLabelsWhiteOut;
-  QPushButton *btnLabelsFont,*btnSetEquidistantLevels;
+  QPushButton *btnLabelsFont, *btnSetEquidistantLevels;
   QComboBox *boxLabelsAlign, *boxLabelsColumn;
-  ColorBox* boxLabelsColor;
+  ColorBox *boxLabelsColor;
   QWidget *labelsPage;
 
   QGroupBox *pieAutoLabelsBox, *boxPieWedge;
-  DoubleSpinBox *boxPieStartAzimuth, *boxPieEdgeDist, *boxPieViewAngle, *boxPieThickness,*firstContourLineBox,*contourLinesDistanceBox;
-  QCheckBox *boxPieConterClockwise, *boxPieValues, *boxPiePercentages, *boxPieCategories;
+  DoubleSpinBox *boxPieStartAzimuth, *boxPieEdgeDist, *boxPieViewAngle,
+      *boxPieThickness, *firstContourLineBox, *contourLinesDistanceBox;
+  QCheckBox *boxPieConterClockwise, *boxPieValues, *boxPiePercentages,
+      *boxPieCategories;
   QWidget *pieLabelsPage;
   QSpinBox *boxPieOffset;
   QWidget *pieGeometryPage;
   ContourLinesEditor *contourLinesEditor;
   QRadioButton *customPenBtn;
-  //static Mantid::Kernel::Logger &g_log;
+  // static Mantid::Kernel::Logger &g_log;
 };
 
 /*****************************************************************************
@@ -275,11 +287,10 @@ private:
  *
  *****************************************************************************/
 //! LayerItem tree widget item class
-class LayerItem : public QTreeWidgetItem
-{
+class LayerItem : public QTreeWidgetItem {
 public:
-  enum {LayerTreeItem = 1001};
-  LayerItem(Graph *g, QTreeWidgetItem *parent, const QString& s);
+  enum { LayerTreeItem = 1001 };
+  LayerItem(Graph *g, QTreeWidgetItem *parent, const QString &s);
 
   Graph *graph() { return d_graph; };
   void setActive(bool select);
@@ -295,16 +306,15 @@ protected:
  *
  *****************************************************************************/
 //! CurveTreeItem tree widget item class
-class CurveTreeItem : public QTreeWidgetItem
-{
+class CurveTreeItem : public QTreeWidgetItem {
 public:
-  enum {PlotCurveTreeItem = 1002};
-  CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QString& s);
+  enum { PlotCurveTreeItem = 1002 };
+  CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QString &s);
 
-  Graph* graph();
+  Graph *graph();
   void setActive(bool on);
 
-  QwtPlotItem *plotItem() const{ return d_curve; };
+  QwtPlotItem *plotItem() const { return d_curve; };
   int plotItemType();
   int plotItemIndex();
 
diff --git a/MantidPlot/src/PlotToolInterface.h b/MantidPlot/src/PlotToolInterface.h
index 5497175a4fb8748478930e7f32d37795a6b1d3d0..70918cb24a87c46626dfd4e284a4e485e064ffe3 100644
--- a/MantidPlot/src/PlotToolInterface.h
+++ b/MantidPlot/src/PlotToolInterface.h
@@ -33,56 +33,65 @@ class Graph;
 
 /** Interface for tools operating on a Graph.
  *
- * The basic idea is to have one PlotToolInterface subclass per user-visible tool operating on a Graph,
+ * The basic idea is to have one PlotToolInterface subclass per user-visible
+ *tool operating on a Graph,
  * although there may be cases where exceptions to this rule are appropriate.
- * %Note that tools can be presented to the user via icons (like DataPickerTool) or via menu entries
+ * %Note that tools can be presented to the user via icons (like DataPickerTool)
+ *or via menu entries
  * (like TranslateCurveTool); the basic concept is quite similar.
- * The main point in managing plot tools as subclasses of this class (as opposed to using void pointers)
+ * The main point in managing plot tools as subclasses of this class (as opposed
+ *to using void pointers)
  * is the virtual destructor that allows tools to clean up after themselves.
  * Additionally, a pointer to the parent Graph (#d_graph) is managed.
  * In the future, this class may provide other generic tool functionality.
  *
- * %Note that zooming and range selection are somewhat special in that they can be active in addition
- * to other tools. These are handled as special cases, while all other tools are rendered mutually exclusive
- * by having Graph manage a pointer to the currently active tool (Graph::d_active_tool).
+ * %Note that zooming and range selection are somewhat special in that they can
+ *be active in addition
+ * to other tools. These are handled as special cases, while all other tools are
+ *rendered mutually exclusive
+ * by having Graph manage a pointer to the currently active tool
+ *(Graph::d_active_tool).
  *
- * It would be nice for some of the plot tools (like TranslateCurveTool or MultiPeakFitTool) to send a signal
- * when they are finished and to generalize the statusText signal provided by most tools, but having
+ * It would be nice for some of the plot tools (like TranslateCurveTool or
+ *MultiPeakFitTool) to send a signal
+ * when they are finished and to generalize the statusText signal provided by
+ *most tools, but having
  * PlotToolInterface inherit from QObject would make it impossible for
- * plot tools to also inherit from other QObject decendants (such as QwtPlotPicker).
- * As a workaround, plot tools can call Graph::setActiveTool(), carefully noting that they are deleted
+ * plot tools to also inherit from other QObject decendants (such as
+ *QwtPlotPicker).
+ * As a workaround, plot tools can call Graph::setActiveTool(), carefully noting
+ *that they are deleted
  * during this call.
  *
- * Currently, plot tools are instantiated by ApplicationWindow and handed to the Graph in question;
- * this scheme will have to be revised for dynamically adding new tools via plugins.
+ * Currently, plot tools are instantiated by ApplicationWindow and handed to the
+ *Graph in question;
+ * this scheme will have to be revised for dynamically adding new tools via
+ *plugins.
  */
-class PlotToolInterface
-{
-	public:
+class PlotToolInterface {
+public:
+  enum RttiValues {
+    Rtti_PlotTool = 0,
 
-    enum RttiValues
-    {
-        Rtti_PlotTool = 0,
+    Rtti_RangeSelector,
+    Rtti_DataPicker,
+    Rtti_TranslateCurveTool,
+    Rtti_MultiPeakFitTool,
+    Rtti_LineProfileTool,
+    Rtti_SelectPeakTool,
+    Rtti_LabelTool,
 
-        Rtti_RangeSelector,
-        Rtti_DataPicker,
-        Rtti_TranslateCurveTool,
-        Rtti_MultiPeakFitTool,
-        Rtti_LineProfileTool,
-        Rtti_SelectPeakTool,
-        Rtti_LabelTool,
+    Rtti_PlotUserTool = 1000
+  };
 
-        Rtti_PlotUserTool = 1000
-    };
+  explicit PlotToolInterface(Graph *graph) { d_graph = graph; }
+  virtual ~PlotToolInterface(){};
 
-    explicit PlotToolInterface(Graph *graph) { d_graph = graph; }
-                virtual ~PlotToolInterface() {};
+  virtual int rtti() const { return Rtti_PlotTool; };
+  Graph *graph() const { return d_graph; }
 
-    virtual int rtti() const { return Rtti_PlotTool;};
-    Graph* graph()const{return d_graph;}
-
-	protected:
-		Graph *d_graph;
+protected:
+  Graph *d_graph;
 };
 
 #endif // ifndef PLOT_TOOL_INTERFACE_H
diff --git a/MantidPlot/src/PlotWizard.cpp b/MantidPlot/src/PlotWizard.cpp
index 55b30581f94a373d886e59feb3efd0ae4be2d149..522817d2228546d4f291a044d052d81f4302a1fa 100644
--- a/MantidPlot/src/PlotWizard.cpp
+++ b/MantidPlot/src/PlotWizard.cpp
@@ -2,7 +2,8 @@
     File                 : PlotWizard.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : A wizard type dialog to create new plots
 
@@ -36,357 +37,343 @@
 #include <QListWidget>
 #include <QComboBox>
 
-PlotWizard::PlotWizard( QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl )
-{
-	setWindowTitle( tr("MantidPlot - Select Columns to Plot") );
-
-	setSizeGripEnabled( true );
-
-	// top part starts here
-	groupBox1 = new QGroupBox();
-
-    QGridLayout *gl1 = new QGridLayout();
-	buttonX = new QPushButton("<->" + tr("&X"));
-	buttonX->setAutoDefault( false );
-	gl1->addWidget( buttonX, 0, 0);
-
-	buttonXErr = new QPushButton("<->" + tr("x&Err"));
-	buttonXErr->setAutoDefault( false );
-	gl1->addWidget( buttonXErr, 0, 1);
-
-	buttonY = new QPushButton("<->" + tr("&Y"));
-	buttonY->setAutoDefault( false );
-	gl1->addWidget( buttonY, 1, 0);
-
-	buttonYErr = new QPushButton("<->" + tr("yE&rr"));
-	buttonYErr->setAutoDefault( false );
-	gl1->addWidget( buttonYErr, 1, 1);
-
-	buttonZ = new QPushButton("<->" + tr("&Z"));
-	buttonZ->setAutoDefault( false );
-	gl1->addWidget( buttonZ, 2, 0);
-    gl1->setRowStretch(3,1);
-
-    QHBoxLayout *hl2 = new QHBoxLayout();
-    buttonNew = new QPushButton(tr("&New curve"));
-    buttonNew->setDefault( true );
-    buttonNew->setAutoDefault( true );
-	hl2->addWidget(buttonNew);
-
-	buttonDelete = new QPushButton(tr("&Delete curve"));
-    buttonDelete->setAutoDefault( false );
-	hl2->addWidget(buttonDelete);
-
-    QVBoxLayout *vl = new QVBoxLayout();
-    vl->addLayout(gl1);
-    vl->addStretch();
-    vl->addLayout(hl2);
-
-    QGridLayout *gl2 = new QGridLayout(groupBox1);
-    gl2->addWidget(new QLabel(tr( "Worksheet" )), 0, 0);
-    boxTables = new QComboBox();
-    gl2->addWidget(boxTables, 0, 1);
-    columnsList = new QListWidget();
-    gl2->addWidget(columnsList, 1, 0);
-    gl2->addLayout(vl, 1, 1);
-
-	// middle part is only one widget
-	plotAssociations = new QListWidget();
-
-	// bottom part starts here
-	QHBoxLayout * bottomLayout = new QHBoxLayout();
-    bottomLayout->addStretch();
-
-	buttonOk = new QPushButton(tr("&Plot"));
-    buttonOk->setAutoDefault( false );
-	bottomLayout->addWidget( buttonOk );
-
-	buttonCancel = new QPushButton(tr("&Close"));
-    buttonCancel->setAutoDefault( false );
-	bottomLayout->addWidget( buttonCancel );
-
-	QVBoxLayout* vlayout = new QVBoxLayout( this );
-	vlayout->addWidget( groupBox1 );
-	vlayout->addWidget( plotAssociations );
-	vlayout->addLayout( bottomLayout );
-
-	// signals and slots connections
-	connect( boxTables, SIGNAL(activated(const QString &)),this, SLOT(changeColumnsList(const QString &)));
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-	connect( buttonNew, SIGNAL( clicked() ), this, SLOT( addCurve() ) );
-	connect( buttonDelete, SIGNAL( clicked() ), this, SLOT( removeCurve() ) );
-	connect( buttonX, SIGNAL( clicked() ), this, SLOT(addXCol()));
-	connect( buttonY, SIGNAL( clicked() ), this, SLOT(addYCol()));
-	connect( buttonXErr, SIGNAL( clicked() ), this, SLOT(addXErrCol()));
-	connect( buttonYErr, SIGNAL( clicked() ), this, SLOT(addYErrCol()));
-	connect( buttonZ, SIGNAL( clicked() ), this, SLOT(addZCol()));
+PlotWizard::PlotWizard(QWidget *parent, Qt::WFlags fl) : QDialog(parent, fl) {
+  setWindowTitle(tr("MantidPlot - Select Columns to Plot"));
+
+  setSizeGripEnabled(true);
+
+  // top part starts here
+  groupBox1 = new QGroupBox();
+
+  QGridLayout *gl1 = new QGridLayout();
+  buttonX = new QPushButton("<->" + tr("&X"));
+  buttonX->setAutoDefault(false);
+  gl1->addWidget(buttonX, 0, 0);
+
+  buttonXErr = new QPushButton("<->" + tr("x&Err"));
+  buttonXErr->setAutoDefault(false);
+  gl1->addWidget(buttonXErr, 0, 1);
+
+  buttonY = new QPushButton("<->" + tr("&Y"));
+  buttonY->setAutoDefault(false);
+  gl1->addWidget(buttonY, 1, 0);
+
+  buttonYErr = new QPushButton("<->" + tr("yE&rr"));
+  buttonYErr->setAutoDefault(false);
+  gl1->addWidget(buttonYErr, 1, 1);
+
+  buttonZ = new QPushButton("<->" + tr("&Z"));
+  buttonZ->setAutoDefault(false);
+  gl1->addWidget(buttonZ, 2, 0);
+  gl1->setRowStretch(3, 1);
+
+  QHBoxLayout *hl2 = new QHBoxLayout();
+  buttonNew = new QPushButton(tr("&New curve"));
+  buttonNew->setDefault(true);
+  buttonNew->setAutoDefault(true);
+  hl2->addWidget(buttonNew);
+
+  buttonDelete = new QPushButton(tr("&Delete curve"));
+  buttonDelete->setAutoDefault(false);
+  hl2->addWidget(buttonDelete);
+
+  QVBoxLayout *vl = new QVBoxLayout();
+  vl->addLayout(gl1);
+  vl->addStretch();
+  vl->addLayout(hl2);
+
+  QGridLayout *gl2 = new QGridLayout(groupBox1);
+  gl2->addWidget(new QLabel(tr("Worksheet")), 0, 0);
+  boxTables = new QComboBox();
+  gl2->addWidget(boxTables, 0, 1);
+  columnsList = new QListWidget();
+  gl2->addWidget(columnsList, 1, 0);
+  gl2->addLayout(vl, 1, 1);
+
+  // middle part is only one widget
+  plotAssociations = new QListWidget();
+
+  // bottom part starts here
+  QHBoxLayout *bottomLayout = new QHBoxLayout();
+  bottomLayout->addStretch();
+
+  buttonOk = new QPushButton(tr("&Plot"));
+  buttonOk->setAutoDefault(false);
+  bottomLayout->addWidget(buttonOk);
+
+  buttonCancel = new QPushButton(tr("&Close"));
+  buttonCancel->setAutoDefault(false);
+  bottomLayout->addWidget(buttonCancel);
+
+  QVBoxLayout *vlayout = new QVBoxLayout(this);
+  vlayout->addWidget(groupBox1);
+  vlayout->addWidget(plotAssociations);
+  vlayout->addLayout(bottomLayout);
+
+  // signals and slots connections
+  connect(boxTables, SIGNAL(activated(const QString &)), this,
+          SLOT(changeColumnsList(const QString &)));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(buttonNew, SIGNAL(clicked()), this, SLOT(addCurve()));
+  connect(buttonDelete, SIGNAL(clicked()), this, SLOT(removeCurve()));
+  connect(buttonX, SIGNAL(clicked()), this, SLOT(addXCol()));
+  connect(buttonY, SIGNAL(clicked()), this, SLOT(addYCol()));
+  connect(buttonXErr, SIGNAL(clicked()), this, SLOT(addXErrCol()));
+  connect(buttonYErr, SIGNAL(clicked()), this, SLOT(addYErrCol()));
+  connect(buttonZ, SIGNAL(clicked()), this, SLOT(addZCol()));
 }
 
-QSize PlotWizard::sizeHint() const
-{
-	return QSize(350, 400);
-}
+QSize PlotWizard::sizeHint() const { return QSize(350, 400); }
+
+void PlotWizard::accept() {
+  QStringList curves, curves3D, ribbons;
+  for (int i = 0; i < plotAssociations->count(); i++) {
+    QString text = plotAssociations->item(i)->text();
+    if (text.endsWith("(X)")) {
+      QMessageBox::critical(
+          this, tr("MantidPlot - Error"),
+          tr("Please define a Y column for the following curve") + ":\n\n" +
+              text);
+      return;
+    }
 
-void PlotWizard::accept()
-{
-	QStringList curves, curves3D, ribbons;
-	for (int i=0; i < plotAssociations->count(); i++)
-	{
-		QString text = plotAssociations->item(i)->text();
-        if (text.endsWith("(X)"))
-        {
-            QMessageBox::critical(this, tr("MantidPlot - Error"),
-            tr("Please define a Y column for the following curve") + ":\n\n" + text);
-            return;
-        }
-
-		if ( text.contains("(Z)") )
-		{
-			if ( text.contains("(Y)") && !curves3D.contains(text) )
-				curves3D << text;
-			else if ( !text.contains("(Y)") && !ribbons.contains(text) )
-				ribbons << text;
-		}
-		else if ( text.contains("(xErr)") || text.contains("(yErr)"))
-		{
-			QStringList lst = text.split(",", QString::SkipEmptyParts);
-			lst.pop_back();
-			QString master_curve = lst.join(",");
-
-			if (!curves.contains(master_curve))
-				curves.prepend(master_curve);
-
-			if (!curves.contains(text))
-				curves << text; //add error bars at the end of the list.
-		}
-		else if (!curves.contains(text))
-			curves.prepend(text);
-	}
-
-	if (curves.count()>0)
-        emit plot(curves);
-
-	 if (curves3D.count()>0)
-		plot3D(curves3D);
-
-    if (ribbons.count()>0)
-        plot3DRibbon(ribbons);
-
-	if(!noCurves())
-		close();
-}
+    if (text.contains("(Z)")) {
+      if (text.contains("(Y)") && !curves3D.contains(text))
+        curves3D << text;
+      else if (!text.contains("(Y)") && !ribbons.contains(text))
+        ribbons << text;
+    } else if (text.contains("(xErr)") || text.contains("(yErr)")) {
+      QStringList lst = text.split(",", QString::SkipEmptyParts);
+      lst.pop_back();
+      QString master_curve = lst.join(",");
+
+      if (!curves.contains(master_curve))
+        curves.prepend(master_curve);
+
+      if (!curves.contains(text))
+        curves << text; // add error bars at the end of the list.
+    } else if (!curves.contains(text))
+      curves.prepend(text);
+  }
 
-void PlotWizard::changeColumnsList(const QString &table)
-{
-	QStringList newList;
-
-	for( int i=0 ; i<columns.count() ; i++)
-	{
-		QString s = columns[i];
-		if ( s.contains(table) )
-			newList << s.remove(table+"_");
-	}
-	setColumnsListBoxContents(newList);
+  if (curves.count() > 0)
+    emit plot(curves);
+
+  if (curves3D.count() > 0)
+    plot3D(curves3D);
+
+  if (ribbons.count() > 0)
+    plot3DRibbon(ribbons);
+
+  if (!noCurves())
+    close();
 }
 
-void PlotWizard::addXCol()
-{
-	if (noCurves())
-		return;
-
-	QString text = plotAssociations->currentItem()->text();
-	if ( text.contains("(X)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You have already defined a X column!"));
-	else
-	{
-		plotAssociations->currentItem()->setText(text+columnsList->currentItem()->text()+"(X)");
-	}
+void PlotWizard::changeColumnsList(const QString &table) {
+  QStringList newList;
+
+  for (int i = 0; i < columns.count(); i++) {
+    QString s = columns[i];
+    if (s.contains(table))
+      newList << s.remove(table + "_");
+  }
+  setColumnsListBoxContents(newList);
 }
 
-void PlotWizard::addYCol()
-{
-	if (noCurves())
-		return;
-
-	QString text = plotAssociations->currentItem()->text();
-	if ( !text.contains("(X)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"),tr("You must define a X column first!"));
-	else if ( text.contains("(Y)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You have already defined a Y column!"));
-	else
-	{
-		plotAssociations->currentItem()->setText(text+", "+columnsList->currentItem()->text()+"(Y)");
-	}
+void PlotWizard::addXCol() {
+  if (noCurves())
+    return;
+
+  QString text = plotAssociations->currentItem()->text();
+  if (text.contains("(X)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You have already defined a X column!"));
+  else {
+    plotAssociations->currentItem()->setText(
+        text + columnsList->currentItem()->text() + "(X)");
+  }
 }
 
-void PlotWizard::addZCol()
-{
-	if (noCurves())
-		return;
-
-	QString text = plotAssociations->currentItem()->text();
-	if ( text.contains("(xErr)") || text.contains("(yErr)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("This kind of curve is not handled by MantidPlot!"));
-	else if ( !text.contains("(X)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You must define a X column first!"));
-	else if ( text.contains("(Z)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You have already defined a Z column!"));
-	else
-	{
-		plotAssociations->currentItem()->setText(text+", "+columnsList->currentItem()->text()+"(Z)");
-	}
+void PlotWizard::addYCol() {
+  if (noCurves())
+    return;
+
+  QString text = plotAssociations->currentItem()->text();
+  if (!text.contains("(X)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a X column first!"));
+  else if (text.contains("(Y)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You have already defined a Y column!"));
+  else {
+    plotAssociations->currentItem()->setText(
+        text + ", " + columnsList->currentItem()->text() + "(Y)");
+  }
 }
 
-void PlotWizard::addXErrCol()
-{
-	if (noCurves())
-		return;
-
-	QString text = plotAssociations->currentItem()->text();
-	if ( text.contains("(Z)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("This kind of curve is not handled by MantidPlot!"));
-	else if ( !text.contains("(X)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You must define a X column first!"));
-	else if ( !text.contains("(Y)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You must define a Y column first!"));
-	else if ( text.contains("(xErr)") || text.contains("(yErr)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You have already defined an error-bars column!"));
-	else
-	{
-		plotAssociations->currentItem()->setText(text+", "+columnsList->currentItem()->text()+"(xErr)");
-	}
+void PlotWizard::addZCol() {
+  if (noCurves())
+    return;
+
+  QString text = plotAssociations->currentItem()->text();
+  if (text.contains("(xErr)") || text.contains("(yErr)"))
+    QMessageBox::warning(
+        this, tr("MantidPlot - Error"),
+        tr("This kind of curve is not handled by MantidPlot!"));
+  else if (!text.contains("(X)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a X column first!"));
+  else if (text.contains("(Z)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You have already defined a Z column!"));
+  else {
+    plotAssociations->currentItem()->setText(
+        text + ", " + columnsList->currentItem()->text() + "(Z)");
+  }
 }
 
-void PlotWizard::addYErrCol()
-{
-	if (noCurves())
-		return;
-
-	QString text = plotAssociations->currentItem()->text();
-	if ( text.contains("(Z)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("This kind of curve is not handled by MantidPlot!"));
-	else if ( !text.contains("(X)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You must define a X column first!"));
-	else if ( !text.contains("(Y)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You must define a Y column first!"));
-	else if ( text.contains("(xErr)") || text.contains("(yErr)") )
-		QMessageBox::warning(this, tr("MantidPlot - Error"), tr("You have already defined an error-bars column!"));
-	else
-	{
-		plotAssociations->currentItem()->setText(text+", "+columnsList->currentItem()->text()+"(yErr)");
-	}
+void PlotWizard::addXErrCol() {
+  if (noCurves())
+    return;
+
+  QString text = plotAssociations->currentItem()->text();
+  if (text.contains("(Z)"))
+    QMessageBox::warning(
+        this, tr("MantidPlot - Error"),
+        tr("This kind of curve is not handled by MantidPlot!"));
+  else if (!text.contains("(X)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a X column first!"));
+  else if (!text.contains("(Y)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a Y column first!"));
+  else if (text.contains("(xErr)") || text.contains("(yErr)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You have already defined an error-bars column!"));
+  else {
+    plotAssociations->currentItem()->setText(
+        text + ", " + columnsList->currentItem()->text() + "(xErr)");
+  }
 }
 
-void PlotWizard::addCurve()
-{
-	plotAssociations->addItem( boxTables->currentText() + ": " );
-	plotAssociations->setCurrentRow( plotAssociations->count()-1 );
+void PlotWizard::addYErrCol() {
+  if (noCurves())
+    return;
+
+  QString text = plotAssociations->currentItem()->text();
+  if (text.contains("(Z)"))
+    QMessageBox::warning(
+        this, tr("MantidPlot - Error"),
+        tr("This kind of curve is not handled by MantidPlot!"));
+  else if (!text.contains("(X)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a X column first!"));
+  else if (!text.contains("(Y)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You must define a Y column first!"));
+  else if (text.contains("(xErr)") || text.contains("(yErr)"))
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+                         tr("You have already defined an error-bars column!"));
+  else {
+    plotAssociations->currentItem()->setText(
+        text + ", " + columnsList->currentItem()->text() + "(yErr)");
+  }
 }
 
-void PlotWizard::removeCurve()
-{
-	plotAssociations->takeItem( plotAssociations->currentRow() );
+void PlotWizard::addCurve() {
+  plotAssociations->addItem(boxTables->currentText() + ": ");
+  plotAssociations->setCurrentRow(plotAssociations->count() - 1);
 }
 
-void PlotWizard::insertTablesList(const QStringList& tables)
-{
-	boxTables->addItems(tables);
+void PlotWizard::removeCurve() {
+  plotAssociations->takeItem(plotAssociations->currentRow());
 }
 
-void PlotWizard::setColumnsListBoxContents(const QStringList& cols)
-{
-	columnsList->clear();
-	columnsList->insertItems(0, cols);
-	columnsList->setCurrentRow(0);
+void PlotWizard::insertTablesList(const QStringList &tables) {
+  boxTables->addItems(tables);
 }
 
-void PlotWizard::setColumnsList(const QStringList& cols)
-{
-	columns = cols;
+void PlotWizard::setColumnsListBoxContents(const QStringList &cols) {
+  columnsList->clear();
+  columnsList->insertItems(0, cols);
+  columnsList->setCurrentRow(0);
 }
 
-bool PlotWizard::noCurves()
-{
-	if ( plotAssociations->count() == 0 )
-	{
-		QMessageBox::warning(0, tr("MantidPlot - Error"), tr("You must add a new curve first!"));
-		return true;
-	}
-	else
-		return false;
+void PlotWizard::setColumnsList(const QStringList &cols) { columns = cols; }
+
+bool PlotWizard::noCurves() {
+  if (plotAssociations->count() == 0) {
+    QMessageBox::warning(0, tr("MantidPlot - Error"),
+                         tr("You must add a new curve first!"));
+    return true;
+  } else
+    return false;
 }
 
-void PlotWizard::plot3DRibbon(const QStringList& lst)
-{
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-    if (!app)
-        return;
-
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    for (int i=0; i< lst.count(); i++)
-    {
-        QString s = lst[i];
-        int pos = s.indexOf(":", 0);
-        QString table_name = s.left(pos) + "_";
-        Table *t = app->table(table_name);
-        if (t)
-        {
-            int posX = s.indexOf("(", pos);
-            QString xColName = table_name + s.mid(pos+2, posX-pos-2);
-
-            posX = s.indexOf(",", posX);
-            int posY = s.indexOf("(", posX);
-            QString yColName = table_name + s.mid(posX+2, posY-posX-2);
-
-            Graph3D *g = app->newPlot3D();
-            if (g) {
-                g->addData(t, xColName, yColName);
-                g->update();
-            }
-        }
+void PlotWizard::plot3DRibbon(const QStringList &lst) {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  for (int i = 0; i < lst.count(); i++) {
+    QString s = lst[i];
+    int pos = s.indexOf(":", 0);
+    QString table_name = s.left(pos) + "_";
+    Table *t = app->table(table_name);
+    if (t) {
+      int posX = s.indexOf("(", pos);
+      QString xColName = table_name + s.mid(pos + 2, posX - pos - 2);
+
+      posX = s.indexOf(",", posX);
+      int posY = s.indexOf("(", posX);
+      QString yColName = table_name + s.mid(posX + 2, posY - posX - 2);
+
+      Graph3D *g = app->newPlot3D();
+      if (g) {
+        g->addData(t, xColName, yColName);
+        g->update();
+      }
     }
-    QApplication::restoreOverrideCursor();
+  }
+  QApplication::restoreOverrideCursor();
 }
 
-void PlotWizard::plot3D(const QStringList& lst)
-{
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-    if (!app)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    for (int i=0; i< lst.count(); i++)
-    {
-        QString s = lst[i];
-        int pos = s.indexOf(":", 0);
-        QString table_name = s.left(pos) + "_";
-        Table *t = app->table(table_name);
-        if (t)
-        {
-            int posX = s.indexOf("(", pos);
-            QString xColName = table_name + s.mid(pos+2, posX-pos-2);
-
-            posX = s.indexOf(",", posX);
-            int posY = s.indexOf("(", posX);
-            QString yColName = table_name + s.mid(posX+2, posY-posX-2);
-
-            posY = s.indexOf(",", posY);
-            int posZ = s.indexOf("(", posY);
-            QString zColName = table_name + s.mid(posY+2, posZ-posY-2);
-
-            int xCol = t->colIndex(xColName);
-            int yCol = t->colIndex(yColName);
-            int zCol = t->colIndex(zColName);
-            if (xCol >= 0 && yCol >= 0 && zCol >= 0) {
-                Graph3D *g = app->newPlot3D();
-                if (g)
-                    g->addData(t, xCol, yCol, zCol, 1);
-            }
-        }
+void PlotWizard::plot3D(const QStringList &lst) {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  for (int i = 0; i < lst.count(); i++) {
+    QString s = lst[i];
+    int pos = s.indexOf(":", 0);
+    QString table_name = s.left(pos) + "_";
+    Table *t = app->table(table_name);
+    if (t) {
+      int posX = s.indexOf("(", pos);
+      QString xColName = table_name + s.mid(pos + 2, posX - pos - 2);
+
+      posX = s.indexOf(",", posX);
+      int posY = s.indexOf("(", posX);
+      QString yColName = table_name + s.mid(posX + 2, posY - posX - 2);
+
+      posY = s.indexOf(",", posY);
+      int posZ = s.indexOf("(", posY);
+      QString zColName = table_name + s.mid(posY + 2, posZ - posY - 2);
+
+      int xCol = t->colIndex(xColName);
+      int yCol = t->colIndex(yColName);
+      int zCol = t->colIndex(zColName);
+      if (xCol >= 0 && yCol >= 0 && zCol >= 0) {
+        Graph3D *g = app->newPlot3D();
+        if (g)
+          g->addData(t, xCol, yCol, zCol, 1);
+      }
     }
-	QApplication::restoreOverrideCursor();
+  }
+  QApplication::restoreOverrideCursor();
 }
diff --git a/MantidPlot/src/PlotWizard.h b/MantidPlot/src/PlotWizard.h
index 038263ba45d761f6bf0bbac726d6a84599cd2ceb..e7cd828a0a3c0f935a38a7a18046a6e799e3a547 100644
--- a/MantidPlot/src/PlotWizard.h
+++ b/MantidPlot/src/PlotWizard.h
@@ -2,7 +2,8 @@
     File                 : PlotWizard.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : A wizard type dialog to create new plots
 
@@ -27,7 +28,6 @@
  *                                                                         *
  ***************************************************************************/
 
-
 #ifndef PLOTWIZARD_H
 #define PLOTWIZARD_H
 
@@ -38,85 +38,85 @@ class QListWidget;
 class QComboBox;
 
 //! A wizard type dialog class to create new plots
-class PlotWizard : public QDialog
-{
-    Q_OBJECT
+class PlotWizard : public QDialog {
+  Q_OBJECT
 
 public:
-	//! Constructor
-	/**
-	 * @param parent :: parent widget
-	 * @param fl :: Qt window flags
-	 */
-    PlotWizard( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  //! Constructor
+  /**
+   * @param parent :: parent widget
+   * @param fl :: Qt window flags
+   */
+  PlotWizard(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 private:
-				//! Button "Plot"
-    QPushButton* buttonOk,
-				//! Button "<->xErr"
-				*buttonXErr,
-				//! Button "<->yErr"
-				*buttonYErr,
-				//! Button "Delete curve"
-				*buttonDelete;
-				//! Button "cancel"
-	QPushButton* buttonCancel,
-				//! Button "<->X"
-				*buttonX,
-				//! Button "<->Y"
-				*buttonY,
-				//! Button "New curve"
-				*buttonNew,
-				//! Button "<->Z"
-				*buttonZ;
-				//! Button group defining the layout
-    QGroupBox*  groupBox1;
-				//! Combo box to select the table
-    QComboBox* boxTables;
-				//! List of the columns in the selected table
-	QListWidget *columnsList,
-				//! List of the plots to generate
-			 *plotAssociations;
+  //! Button "Plot"
+  QPushButton *buttonOk,
+      //! Button "<->xErr"
+      *buttonXErr,
+      //! Button "<->yErr"
+      *buttonYErr,
+      //! Button "Delete curve"
+      *buttonDelete;
+  //! Button "cancel"
+  QPushButton *buttonCancel,
+      //! Button "<->X"
+      *buttonX,
+      //! Button "<->Y"
+      *buttonY,
+      //! Button "New curve"
+      *buttonNew,
+      //! Button "<->Z"
+      *buttonZ;
+  //! Button group defining the layout
+  QGroupBox *groupBox1;
+  //! Combo box to select the table
+  QComboBox *boxTables;
+  //! List of the columns in the selected table
+  QListWidget *columnsList,
+      //! List of the plots to generate
+      *plotAssociations;
 
-	//! Internal list of columns (contains all columns in all tables)
-	QStringList columns;
+  //! Internal list of columns (contains all columns in all tables)
+  QStringList columns;
 
 public slots:
-	//! Update the columns list box to contain the columns of 'table'
-	void changeColumnsList(const QString &table);
-	//! Insert a list of tables into the tables combo box
-	void insertTablesList(const QStringList& tables);
-	//! Set the contents of the columns list box to the strings in 'cols'
-	void setColumnsListBoxContents(const QStringList& cols);
-	//! Set the internal columns list to 'cols'
-	void setColumnsList(const QStringList& cols);
-	//! Add new curve
-	void addCurve();
-	//! Delete selected curve
-	void removeCurve();
-	//! Add column as X
-	void addXCol();
-	//! Add column as Y
-	void addYCol();
-	//! Add column as X error
-	void addXErrCol();
-	//! Add column as Y error
-	void addYErrCol();
-	//! Accept settings, close the dialog
-        void accept() override;
-        //! Add column as Z
-	void addZCol();
+  //! Update the columns list box to contain the columns of 'table'
+  void changeColumnsList(const QString &table);
+  //! Insert a list of tables into the tables combo box
+  void insertTablesList(const QStringList &tables);
+  //! Set the contents of the columns list box to the strings in 'cols'
+  void setColumnsListBoxContents(const QStringList &cols);
+  //! Set the internal columns list to 'cols'
+  void setColumnsList(const QStringList &cols);
+  //! Add new curve
+  void addCurve();
+  //! Delete selected curve
+  void removeCurve();
+  //! Add column as X
+  void addXCol();
+  //! Add column as Y
+  void addYCol();
+  //! Add column as X error
+  void addXErrCol();
+  //! Add column as Y error
+  void addYErrCol();
+  //! Accept settings, close the dialog
+  void accept() override;
+  //! Add column as Z
+  void addZCol();
 
 private:
-    void plot3D(const QStringList& lst);
-    void plot3DRibbon(const QStringList& lst);
-	//! Display a warning that a new curve must be added first before the selection of the columns
-	bool noCurves();
-        QSize sizeHint() const override;
+  void plot3D(const QStringList &lst);
+  void plot3DRibbon(const QStringList &lst);
+  //! Display a warning that a new curve must be added first before the
+  // selection of the columns
+  bool noCurves();
+  QSize sizeHint() const override;
 
 signals:
-	//! Emitted when new plots need to be created
-	void plot (const QStringList&);
+  //! Emitted when new plots need to be created
+  void plot(const QStringList &);
 };
 
 #endif //  PLOTWIZARD_H
diff --git a/MantidPlot/src/PluginFit.cpp b/MantidPlot/src/PluginFit.cpp
index b01e5ad7c79b07e3f3d5e2990e3f2b92eebadf71..ee4468cbe124c80c455ece6226f0fb5f053c2a96 100644
--- a/MantidPlot/src/PluginFit.cpp
+++ b/MantidPlot/src/PluginFit.cpp
@@ -2,7 +2,8 @@
     File                 : PluginFit.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plugin Fit class
 
@@ -32,173 +33,183 @@
 #include <QMessageBox>
 
 PluginFit::PluginFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g), f_eval(NULL)
-{
-	init();
+    : Fit(parent, g), f_eval(NULL) {
+  init();
 }
 
-PluginFit::PluginFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g), f_eval(NULL)
-{
-	init();
-	setDataFromCurve(curveTitle);
+PluginFit::PluginFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle)
+    : Fit(parent, g), f_eval(NULL) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-PluginFit::PluginFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g), f_eval(NULL)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+PluginFit::PluginFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle, double start, double end)
+    : Fit(parent, g), f_eval(NULL) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-PluginFit::PluginFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t), f_eval(NULL)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+PluginFit::PluginFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                     const QString &yCol, int startRow, int endRow)
+    : Fit(parent, t), f_eval(NULL) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void PluginFit::init()
-{
-	d_explanation = tr("Plugin Fit");
-    d_fit_type = Plugin;
+void PluginFit::init() {
+  d_explanation = tr("Plugin Fit");
+  d_fit_type = Plugin;
 }
 
-
-namespace{
+namespace {
 typedef union {
   double (*func)(const gsl_vector *, void *);
-  void* ptr;
+  void *ptr;
 } simplex_union;
 
 typedef union {
   int (*func)(const gsl_vector *, void *, gsl_vector *);
-  void* ptr;
+  void *ptr;
 } f_union;
 
 typedef union {
-  int (*func)(const gsl_vector *, void *,gsl_matrix *);
-  void* ptr;
+  int (*func)(const gsl_vector *, void *, gsl_matrix *);
+  void *ptr;
 } df_union;
 
 typedef union {
   int (*func)(const gsl_vector *, void *, gsl_vector *, gsl_matrix *);
-  void* ptr;
+  void *ptr;
 } fdf_union;
 
 typedef union {
   double (*func)(double, double *);
-  void* ptr;
+  void *ptr;
 } ffe_union;
 
 typedef union {
-  char* (*func)();
-  void* ptr;
+  char *(*func)();
+  void *ptr;
 } ff_union;
 }
 
-bool PluginFit::load(const QString& pluginName)
-{
-	if (!QFile::exists (pluginName)){
-		QMessageBox::critical(static_cast<ApplicationWindow*>(parent()), tr("MantidPlot - File not found"),
-				tr("Plugin file: <p><b> %1 </b> <p>not found. Operation aborted!").arg(pluginName));
-		return false;
-	}
-
-	QLibrary lib(pluginName);
-
-	simplex_union simplex;
-        simplex.ptr = lib.resolve( "function_d" );
-        d_fsimplex = simplex.func;
-	if (!d_fsimplex){
-		QMessageBox::critical(static_cast<ApplicationWindow*>(parent()), tr("MantidPlot - Plugin Error"),
-				tr("The plugin does not implement a %1 method necessary for simplex fitting.").arg("function_d"));
-		return false;
-	}
-
-        f_union f;
-        f.ptr = lib.resolve( "function_f" );
-        d_f = f.func;
-	if (!d_f){
-		QMessageBox::critical(static_cast<ApplicationWindow*>(parent()), tr("MantidPlot - Plugin Error"),
-				tr("The plugin does not implement a %1 method necessary for Levenberg-Marquardt fitting.").arg("function_f"));
-		return false;
-	}
-
-        df_union df;
-        df.ptr = lib.resolve( "function_df" );
-	d_df = df.func;
-	if (!(df.ptr)){
-		QMessageBox::critical(static_cast<ApplicationWindow*>(parent()), tr("MantidPlot - Plugin Error"),
-				tr("The plugin does not implement a %1 method necessary for Levenberg-Marquardt fitting.").arg("function_df"));
-		return false;
-	}
-
-        fdf_union fdf;
-        fdf.ptr = lib.resolve( "function_fdf" );
-	d_fdf = fdf.func;
-	if (!d_fdf){
-		QMessageBox::critical(static_cast<ApplicationWindow*>(parent()), tr("MantidPlot - Plugin Error"),
-				tr("The plugin does not implement a %1 method necessary for Levenberg-Marquardt fitting.").arg("function_fdf"));
-		return false;
-	}
-
-        ffe_union ffe;
-        ffe.ptr = lib.resolve("function_eval");
-	f_eval = ffe.func;
-	if (!f_eval)
-		return false;
-
-	typedef char* (*fitFunc)();
-        ff_union ff;
-        ff.ptr = lib.resolve("parameters");
-	fitFunc fitFunction = ff.func;
-	if (fitFunction){
-		d_param_names = QString(fitFunction()).split(",", QString::SkipEmptyParts);
-		d_p = (int)d_param_names.count();
-        initWorkspace(d_p);
-	} else
-		return false;
-
-        ff.ptr = lib.resolve("explanations");
-	fitFunc fitExplain = ff.func;
-	if (fitExplain)
-		d_param_explain = QString(fitExplain()).split(",", QString::SkipEmptyParts);
-	else
-		for (int i=0; i<d_p; i++)
-			d_param_explain << "";
-
-        ff.ptr = lib.resolve("name");
-	fitFunction = ff.func;
-	setObjectName(QString(fitFunction()));
-
-        ff.ptr = lib.resolve("function");
-	fitFunction = ff.func;
-	if (fitFunction)
-		d_formula = QString(fitFunction());
-	else
-		return false;
-
-	return true;
+bool PluginFit::load(const QString &pluginName) {
+  if (!QFile::exists(pluginName)) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - File not found"),
+        tr("Plugin file: <p><b> %1 </b> <p>not found. Operation aborted!")
+            .arg(pluginName));
+    return false;
+  }
+
+  QLibrary lib(pluginName);
+
+  simplex_union simplex;
+  simplex.ptr = lib.resolve("function_d");
+  d_fsimplex = simplex.func;
+  if (!d_fsimplex) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Plugin Error"),
+        tr("The plugin does not implement a %1 method necessary for simplex "
+           "fitting.").arg("function_d"));
+    return false;
+  }
+
+  f_union f;
+  f.ptr = lib.resolve("function_f");
+  d_f = f.func;
+  if (!d_f) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Plugin Error"),
+        tr("The plugin does not implement a %1 method necessary for "
+           "Levenberg-Marquardt fitting.").arg("function_f"));
+    return false;
+  }
+
+  df_union df;
+  df.ptr = lib.resolve("function_df");
+  d_df = df.func;
+  if (!(df.ptr)) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Plugin Error"),
+        tr("The plugin does not implement a %1 method necessary for "
+           "Levenberg-Marquardt fitting.").arg("function_df"));
+    return false;
+  }
+
+  fdf_union fdf;
+  fdf.ptr = lib.resolve("function_fdf");
+  d_fdf = fdf.func;
+  if (!d_fdf) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot - Plugin Error"),
+        tr("The plugin does not implement a %1 method necessary for "
+           "Levenberg-Marquardt fitting.").arg("function_fdf"));
+    return false;
+  }
+
+  ffe_union ffe;
+  ffe.ptr = lib.resolve("function_eval");
+  f_eval = ffe.func;
+  if (!f_eval)
+    return false;
+
+  typedef char *(*fitFunc)();
+  ff_union ff;
+  ff.ptr = lib.resolve("parameters");
+  fitFunc fitFunction = ff.func;
+  if (fitFunction) {
+    d_param_names = QString(fitFunction()).split(",", QString::SkipEmptyParts);
+    d_p = (int)d_param_names.count();
+    initWorkspace(d_p);
+  } else
+    return false;
+
+  ff.ptr = lib.resolve("explanations");
+  fitFunc fitExplain = ff.func;
+  if (fitExplain)
+    d_param_explain = QString(fitExplain()).split(",", QString::SkipEmptyParts);
+  else
+    for (int i = 0; i < d_p; i++)
+      d_param_explain << "";
+
+  ff.ptr = lib.resolve("name");
+  fitFunction = ff.func;
+  setObjectName(QString(fitFunction()));
+
+  ff.ptr = lib.resolve("function");
+  fitFunction = ff.func;
+  if (fitFunction)
+    d_formula = QString(fitFunction());
+  else
+    return false;
+
+  return true;
 }
 
-void PluginFit::calculateFitCurveData(double *X, double *Y)
-{
-  if (!f_eval) return;
-	if (d_gen_function)
-	{
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0+i*step;
-			X[i] = x;
-			Y[i]= f_eval(x, d_results);
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i]= f_eval(x, d_results);
-		}
-	}
+void PluginFit::calculateFitCurveData(double *X, double *Y) {
+  if (!f_eval)
+    return;
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = f_eval(x, d_results);
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = f_eval(x, d_results);
+    }
+  }
 }
diff --git a/MantidPlot/src/PluginFit.h b/MantidPlot/src/PluginFit.h
index 84474d75f41665522232d8a04ede690d3556b0df..0253cb40b2e5a6b6a7d20f6261fce7e98ceb0765 100644
--- a/MantidPlot/src/PluginFit.h
+++ b/MantidPlot/src/PluginFit.h
@@ -2,7 +2,8 @@
     File                 : PluginFit.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Plugin Fit class
 
@@ -31,25 +32,24 @@
 
 #include "Fit.h"
 
-class PluginFit : public Fit
-{
-	Q_OBJECT
+class PluginFit : public Fit {
+  Q_OBJECT
 
-	public:
-		PluginFit(ApplicationWindow *parent, Graph *g);
-		PluginFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		PluginFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		PluginFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
+public:
+  PluginFit(ApplicationWindow *parent, Graph *g);
+  PluginFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  PluginFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+            double start, double end);
+  PluginFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+            const QString &yCol, int startRow = 1, int endRow = -1);
 
-		bool load(const QString& pluginName);
-                double eval(double *par, double x) override {
-                  return f_eval(x, par);
-                };
+  bool load(const QString &pluginName);
+  double eval(double *par, double x) override { return f_eval(x, par); };
 
-        private:
-		void init();
-		typedef double (*fitFunctionEval)(double, double *);
-                void calculateFitCurveData(double *X, double *Y) override;
-                fitFunctionEval f_eval;
+private:
+  void init();
+  typedef double (*fitFunctionEval)(double, double *);
+  void calculateFitCurveData(double *X, double *Y) override;
+  fitFunctionEval f_eval;
 };
 #endif
diff --git a/MantidPlot/src/PolynomFitDialog.cpp b/MantidPlot/src/PolynomFitDialog.cpp
index 8c8a83438fd728a7761878123aec9476437724a7..1a7f10fbcdde3a58cec987e0dac5271da9ca1496 100644
--- a/MantidPlot/src/PolynomFitDialog.cpp
+++ b/MantidPlot/src/PolynomFitDialog.cpp
@@ -2,7 +2,8 @@
     File                 : PolynomFitDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fit polynomial dialog
 
@@ -37,126 +38,123 @@
 #include <QGroupBox>
 #include <QLineEdit>
 
-PolynomFitDialog::PolynomFitDialog( QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ), graph(NULL)
-{
-    setObjectName( "PolynomFitDialog" );
-    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);
-
-    boxName = new QComboBox();
-    gl1->addWidget(boxName, 0, 1);
-
-    gl1->addWidget(new QLabel( tr("Order (1 - 9, 1 = linear)")), 1, 0);
-    boxOrder = new QSpinBox();
-    boxOrder->setRange(1, 9);
-    boxOrder->setValue(2);
-    gl1->addWidget(boxOrder, 1, 1);
-
-    gl1->addWidget(new QLabel( tr("Fit curve # pts")), 2, 0);
-    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"));
-    gl1->addWidget(boxStart, 3, 1);
-
-    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));
-    gl1->addWidget(boxColor, 5, 1);
-
-    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 );
-
-    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);
-
-    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&)));
+PolynomFitDialog::PolynomFitDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), graph(NULL) {
+  setObjectName("PolynomFitDialog");
+  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);
+
+  boxName = new QComboBox();
+  gl1->addWidget(boxName, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("Order (1 - 9, 1 = linear)")), 1, 0);
+  boxOrder = new QSpinBox();
+  boxOrder->setRange(1, 9);
+  boxOrder->setValue(2);
+  gl1->addWidget(boxOrder, 1, 1);
+
+  gl1->addWidget(new QLabel(tr("Fit curve # pts")), 2, 0);
+  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"));
+  gl1->addWidget(boxStart, 3, 1);
+
+  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));
+  gl1->addWidget(boxColor, 5, 1);
+
+  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);
+
+  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);
+
+  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()
-{
-	QString curveName = boxName->currentText();
-	QStringList curvesList = graph->analysableCurvesList();
-	if (!curvesList.contains(curveName))
-	{
-		QMessageBox::critical(this, tr("MantidPlot - Warning"),
-				tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!").arg(curveName));
-		boxName->clear();
-		boxName->addItems(curvesList);
-		return;
-	}
-
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-    PolynomialFit *fitter = new PolynomialFit(app, graph, boxOrder->value(), boxShowFormula->isChecked());
-    if (fitter->setDataFromCurve(curveName, boxStart->text().toDouble(), boxEnd->text().toDouble()))
-    {
-        fitter->setColor(boxColor->currentIndex());
-        fitter->setOutputPrecision(app->fit_output_precision);
-	fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
-        fitter->fit();
-        delete fitter;
-	}
+void PolynomFitDialog::fit() {
+  QString curveName = boxName->currentText();
+  QStringList curvesList = graph->analysableCurvesList();
+  if (!curvesList.contains(curveName)) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Warning"),
+        tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!")
+            .arg(curveName));
+    boxName->clear();
+    boxName->addItems(curvesList);
+    return;
+  }
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+  PolynomialFit *fitter = new PolynomialFit(app, graph, boxOrder->value(),
+                                            boxShowFormula->isChecked());
+  if (fitter->setDataFromCurve(curveName, boxStart->text().toDouble(),
+                               boxEnd->text().toDouble())) {
+    fitter->setColor(boxColor->currentIndex());
+    fitter->setOutputPrecision(app->fit_output_precision);
+    fitter->generateFunction(app->generateUniformFitPoints, app->fitPoints);
+    fitter->fit();
+    delete fitter;
+  }
 }
 
-void PolynomFitDialog::setGraph(Graph *g)
-{
-	graph = g;
-	boxName->addItems (g->analysableCurvesList());
-
-	QString selectedCurve = g->selectedCurveTitle();
-	if (!selectedCurve.isEmpty())
-	{
-	    int index = boxName->findText (selectedCurve);
-		boxName->setCurrentIndex(index);
-	}
-    activateCurve(boxName->currentText());
-
-	connect (graph, SIGNAL(closedGraph()), this, SLOT(close()));
-	connect (graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
+void PolynomFitDialog::setGraph(Graph *g) {
+  graph = g;
+  boxName->addItems(g->analysableCurvesList());
+
+  QString selectedCurve = g->selectedCurveTitle();
+  if (!selectedCurve.isEmpty()) {
+    int index = boxName->findText(selectedCurve);
+    boxName->setCurrentIndex(index);
+  }
+  activateCurve(boxName->currentText());
+
+  connect(graph, SIGNAL(closedGraph()), this, SLOT(close()));
+  connect(graph, SIGNAL(dataRangeChanged()), this, SLOT(changeDataRange()));
 }
 
-void PolynomFitDialog::activateCurve(const QString& curveName)
-{
-	double start, end;
-	int n_points = graph->range(graph->curveIndex(curveName), &start, &end);
+void PolynomFitDialog::activateCurve(const QString &curveName) {
+  double start, end;
+  int n_points = graph->range(graph->curveIndex(curveName), &start, &end);
 
-	boxStart->setText(QString::number(start, 'g', 15));
-	boxEnd->setText(QString::number(end, 'g', 15));
-	boxPoints->setValue(QMAX(n_points, 100));
+  boxStart->setText(QString::number(start, 'g', 15));
+  boxEnd->setText(QString::number(end, 'g', 15));
+  boxPoints->setValue(QMAX(n_points, 100));
 }
 
-void PolynomFitDialog::changeDataRange()
-{
-	double start = graph->selectedXStartValue();
-	double end = graph->selectedXEndValue();
-	boxStart->setText(QString::number(QMIN(start, end), 'g', 15));
-	boxEnd->setText(QString::number(QMAX(start, end), 'g', 15));
+void PolynomFitDialog::changeDataRange() {
+  double start = graph->selectedXStartValue();
+  double end = graph->selectedXEndValue();
+  boxStart->setText(QString::number(QMIN(start, end), 'g', 15));
+  boxEnd->setText(QString::number(QMAX(start, end), 'g', 15));
 }
diff --git a/MantidPlot/src/PolynomFitDialog.h b/MantidPlot/src/PolynomFitDialog.h
index 88b45a90e7b934a3107662524c04f2d934110f6a..b332f0727796f0822e457a1a7de7d1b7a8f5436f 100644
--- a/MantidPlot/src/PolynomFitDialog.h
+++ b/MantidPlot/src/PolynomFitDialog.h
@@ -2,7 +2,8 @@
     File                 : PolynomFitDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Fit polynomial dialog
 
@@ -40,32 +41,30 @@ class Graph;
 class ColorBox;
 
 //! Fit polynomial dialog
-class PolynomFitDialog : public QDialog
-{
-    Q_OBJECT
+class PolynomFitDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    PolynomFitDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  PolynomFitDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void fit();
-	void setGraph(Graph *g);
-	void activateCurve(const QString& curveName);
-	void changeDataRange();
+  void fit();
+  void setGraph(Graph *g);
+  void activateCurve(const QString &curveName);
+  void changeDataRange();
 
 private:
-	Graph *graph;
+  Graph *graph;
 
-    QPushButton* buttonFit;
-	QPushButton* buttonCancel;
-    QCheckBox* boxShowFormula;
-	QComboBox* boxName;
-	QSpinBox* boxOrder;
-	QSpinBox* boxPoints;
-	QLineEdit* boxStart;
-	QLineEdit* boxEnd;
-	ColorBox* boxColor;
+  QPushButton *buttonFit;
+  QPushButton *buttonCancel;
+  QCheckBox *boxShowFormula;
+  QComboBox *boxName;
+  QSpinBox *boxOrder;
+  QSpinBox *boxPoints;
+  QLineEdit *boxStart;
+  QLineEdit *boxEnd;
+  ColorBox *boxColor;
 };
 
 #endif
-
diff --git a/MantidPlot/src/PolynomialFit.cpp b/MantidPlot/src/PolynomialFit.cpp
index c21ca1f75162f571ca6d91308cc348039f4a812e..0ede56eac072d4a8553108c9ee6b2223daeec455 100644
--- a/MantidPlot/src/PolynomialFit.cpp
+++ b/MantidPlot/src/PolynomialFit.cpp
@@ -34,178 +34,175 @@
 #include <gsl/gsl_multifit.h>
 #include <gsl/gsl_fit.h>
 
-PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g, int order, bool legend)
-: Fit(parent, g), d_order(order), show_legend(legend)
-{
-	init();
+PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g, int order,
+                             bool legend)
+    : Fit(parent, g), d_order(order), show_legend(legend) {
+  init();
 }
 
-PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g, QString& curveTitle, int order, bool legend)
-: Fit(parent, g), d_order(order), show_legend(legend)
-{
-	init();
-	setDataFromCurve(curveTitle);
+PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g,
+                             QString &curveTitle, int order, bool legend)
+    : Fit(parent, g), d_order(order), show_legend(legend) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g, QString& curveTitle, double start, double end, int order, bool legend)
-: Fit(parent, g), d_order(order), show_legend(legend)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+PolynomialFit::PolynomialFit(ApplicationWindow *parent, Graph *g,
+                             QString &curveTitle, double start, double end,
+                             int order, bool legend)
+    : Fit(parent, g), d_order(order), show_legend(legend) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-PolynomialFit::PolynomialFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow, int order, bool legend)
-: Fit(parent, t), d_order(order), show_legend(legend)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+PolynomialFit::PolynomialFit(ApplicationWindow *parent, Table *t,
+                             const QString &xCol, const QString &yCol,
+                             int startRow, int endRow, int order, bool legend)
+    : Fit(parent, t), d_order(order), show_legend(legend) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void PolynomialFit::init()
-{
-	setObjectName(tr("Polynomial"));
-	is_non_linear = false;
-	d_explanation = tr("Polynomial Fit");
-	setOrder(d_order);
-	d_scale_errors = false;
+void PolynomialFit::init() {
+  setObjectName(tr("Polynomial"));
+  is_non_linear = false;
+  d_explanation = tr("Polynomial Fit");
+  setOrder(d_order);
+  d_scale_errors = false;
 }
 
-void PolynomialFit::setOrder(int order)
-{
-	d_order = order;
-	d_p = d_order + 1;
+void PolynomialFit::setOrder(int order) {
+  d_order = order;
+  d_p = d_order + 1;
 
-	freeWorkspace();
-	initWorkspace(d_p);
+  freeWorkspace();
+  initWorkspace(d_p);
 
-	d_formula = generateFormula(d_order);
-	d_param_names = generateParameterList(d_order);
+  d_formula = generateFormula(d_order);
+  d_param_names = generateParameterList(d_order);
 
-	d_param_explain.clear();
-	for (int i=0; i<d_p; i++)
-		d_param_explain << "";
+  d_param_explain.clear();
+  for (int i = 0; i < d_p; i++)
+    d_param_explain << "";
 }
 
-QString PolynomialFit::generateFormula(int order)
-{
-	QString formula = QString::null;
-	for (int i = 0; i < order+1; i++){
-		QString par = "a" + QString::number(i);
-		formula += par;
-		if (i>0)
-			formula +="*x";
-		if (i>1)
-			formula += "^"+QString::number(i);
-		if (i != order)
-			formula += "+";
-	}
-	return formula;
+QString PolynomialFit::generateFormula(int order) {
+  QString formula = QString::null;
+  for (int i = 0; i < order + 1; i++) {
+    QString par = "a" + QString::number(i);
+    formula += par;
+    if (i > 0)
+      formula += "*x";
+    if (i > 1)
+      formula += "^" + QString::number(i);
+    if (i != order)
+      formula += "+";
+  }
+  return formula;
 }
 
-QStringList PolynomialFit::generateParameterList(int order)
-{
-	QStringList lst;
-	for (int i = 0; i < order+1; i++)
-		lst << "a" + QString::number(i);
-	return lst;
+QStringList PolynomialFit::generateParameterList(int order) {
+  QStringList lst;
+  for (int i = 0; i < order + 1; i++)
+    lst << "a" + QString::number(i);
+  return lst;
 }
 
-void PolynomialFit::calculateFitCurveData(double *X, double *Y)
-{
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0+i*step;
-			X[i] = x;
-			double 	yi = 0.0;
-			for (int j=0; j<d_p;j++)
-				yi += d_results[j]*pow(x, j);
-			Y[i] = yi;
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    double x = d_x[i];
-			X[i] = x;
-			double 	yi = 0.0;
-			for (int j=0; j<d_p; j++)
-				yi += d_results[j]*pow(x, j);
-			Y[i] = yi;
-		}
-	}
+void PolynomialFit::calculateFitCurveData(double *X, double *Y) {
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      double yi = 0.0;
+      for (int j = 0; j < d_p; j++)
+        yi += d_results[j] * pow(x, j);
+      Y[i] = yi;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      double yi = 0.0;
+      for (int j = 0; j < d_p; j++)
+        yi += d_results[j] * pow(x, j);
+      Y[i] = yi;
+    }
+  }
 }
 
-double PolynomialFit::eval(double *par, double x)
-{
-	double 	y = 0.0;
-	for (int j=0; j<d_p; j++)
-		y += par[j]*pow(x, j);
-	return y;
+double PolynomialFit::eval(double *par, double x) {
+  double y = 0.0;
+  for (int j = 0; j < d_p; j++)
+    y += par[j] * pow(x, j);
+  return y;
 }
 
-void PolynomialFit::fit()
-{
-    if (d_init_err)
-        return;
+void PolynomialFit::fit() {
+  if (d_init_err)
+    return;
 
-	if (d_p > d_n){
-  		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Fit Error"),
-  	    tr("You need at least %1 data points for this fit operation. Operation aborted!").arg(d_p));
-  		return;
-  	}
+  if (d_p > d_n) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot - Fit Error"),
+                          tr("You need at least %1 data points for this fit "
+                             "operation. Operation aborted!").arg(d_p));
+    return;
+  }
 
-	gsl_matrix *X = gsl_matrix_alloc (d_n, d_p);
+  gsl_matrix *X = gsl_matrix_alloc(d_n, d_p);
 
-	for (int i = 0; i <d_n; i++){
-		for (int j= 0; j < d_p; j++)
-			gsl_matrix_set (X, i, j, pow(d_x[i],j));
-	}
+  for (int i = 0; i < d_n; i++) {
+    for (int j = 0; j < d_p; j++)
+      gsl_matrix_set(X, i, j, pow(d_x[i], j));
+  }
 
-	gsl_vector_view y = gsl_vector_view_array (d_y, d_n);
-	gsl_vector_view w = gsl_vector_view_array (d_w, d_n);
-	gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (d_n, d_p);
+  gsl_vector_view y = gsl_vector_view_array(d_y, d_n);
+  gsl_vector_view w = gsl_vector_view_array(d_w, d_n);
+  gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(d_n, d_p);
 
-	if (d_weighting == NoWeighting)
-		gsl_multifit_linear (X, &y.vector, d_param_init, covar, &chi_2, work);
-	else
-		gsl_multifit_wlinear (X, &w.vector, &y.vector, d_param_init, covar, &chi_2, work);
+  if (d_weighting == NoWeighting)
+    gsl_multifit_linear(X, &y.vector, d_param_init, covar, &chi_2, work);
+  else
+    gsl_multifit_wlinear(X, &w.vector, &y.vector, d_param_init, covar, &chi_2,
+                         work);
 
-	for (int i = 0; i < d_p; i++)
-		d_results[i] = gsl_vector_get(d_param_init, i);
+  for (int i = 0; i < d_p; i++)
+    d_results[i] = gsl_vector_get(d_param_init, i);
 
-	gsl_multifit_linear_free (work);
-	gsl_matrix_free (X);
+  gsl_multifit_linear_free(work);
+  gsl_matrix_free(X);
 
-	generateFitCurve();
+  generateFitCurve();
 
-	if (show_legend)
-		showLegend();
+  if (show_legend)
+    showLegend();
 
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
-	if (app->writeFitResultsToLog)
-		app->updateLog(logFitInfo(0, 0));
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  if (app->writeFitResultsToLog)
+    app->updateLog(logFitInfo(0, 0));
 }
 
-QString PolynomialFit::legendInfo()
-{
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
-    QLocale locale = app->locale();
-	QString legend = "Y=" + locale.toString(d_results[0], 'g', d_prec);
-	for (int j = 1; j < d_p; j++){
-		double cj = d_results[j];
-		if (cj>0 && !legend.isEmpty())
-			legend += "+";
-
-		QString s;
-		s.sprintf("%.5f",cj);
-		if (s != "1.00000")
-			legend += locale.toString(cj, 'g', d_prec);
-
-		legend += "X";
-		if (j>1)
-			legend += "<sup>" + QString::number(j) + "</sup>";
-	}
-	return legend;
+QString PolynomialFit::legendInfo() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  QLocale locale = app->locale();
+  QString legend = "Y=" + locale.toString(d_results[0], 'g', d_prec);
+  for (int j = 1; j < d_p; j++) {
+    double cj = d_results[j];
+    if (cj > 0 && !legend.isEmpty())
+      legend += "+";
+
+    QString s;
+    s.sprintf("%.5f", cj);
+    if (s != "1.00000")
+      legend += locale.toString(cj, 'g', d_prec);
+
+    legend += "X";
+    if (j > 1)
+      legend += "<sup>" + QString::number(j) + "</sup>";
+  }
+  return legend;
 }
 
 /*****************************************************************************
@@ -214,105 +211,105 @@ QString PolynomialFit::legendInfo()
  *
  *****************************************************************************/
 
-LinearFit::LinearFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+LinearFit::LinearFit(ApplicationWindow *parent, Graph *g) : Fit(parent, g) {
+  init();
 }
 
-LinearFit::LinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+LinearFit::LinearFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-LinearFit::LinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+LinearFit::LinearFit(ApplicationWindow *parent, Graph *g,
+                     const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-LinearFit::LinearFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+LinearFit::LinearFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                     const QString &yCol, int startRow, int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void LinearFit::init()
-{
-	d_scale_errors = false;
-	
-	d_p = 2;
-    d_min_points = d_p;
-
-	covar = gsl_matrix_alloc (d_p, d_p);
-	d_results = new double[d_p];
-
-    d_param_init = gsl_vector_alloc(d_p);
-	gsl_vector_set_all (d_param_init, 1.0);
-
-	is_non_linear = false;
-	d_formula = "A*x+B";
-	d_param_names << "B" << "A";
-	d_param_explain << "y-intercept" << "slope";
-	d_explanation = tr("Linear Regression");
-	setObjectName(tr("Linear"));
-}
-
-void LinearFit::fit()
-{
-    if (d_init_err)
-        return;
-
-	if (d_p > d_n){
-  		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Fit Error"),
-  	    tr("You need at least %1 data points for this fit operation. Operation aborted!").arg(d_p));
-  		return;
-  	}
+void LinearFit::init() {
+  d_scale_errors = false;
 
-	double c0, c1, cov00, cov01, cov11;
-	if (d_weighting == NoWeighting)
-		gsl_fit_linear(d_x, 1, d_y, 1, d_n, &c0, &c1, &cov00, &cov01, &cov11, &chi_2);
-	else
-		gsl_fit_wlinear(d_x, 1, d_w, 1, d_y, 1, d_n, &c0, &c1, &cov00, &cov01, &cov11, &chi_2);
+  d_p = 2;
+  d_min_points = d_p;
 
-	d_results[0] = c0;
-	d_results[1] = c1;
+  covar = gsl_matrix_alloc(d_p, d_p);
+  d_results = new double[d_p];
 
-	gsl_matrix_set(covar, 0, 0, cov00);
-	gsl_matrix_set(covar, 0, 1, cov01);
-	gsl_matrix_set(covar, 1, 1, cov11);
-	gsl_matrix_set(covar, 1, 0, cov01);
+  d_param_init = gsl_vector_alloc(d_p);
+  gsl_vector_set_all(d_param_init, 1.0);
 
-	generateFitCurve();
-
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
-	if (app->writeFitResultsToLog)
-		app->updateLog(logFitInfo(0, 0));
+  is_non_linear = false;
+  d_formula = "A*x+B";
+  d_param_names << "B"
+                << "A";
+  d_param_explain << "y-intercept"
+                  << "slope";
+  d_explanation = tr("Linear Regression");
+  setObjectName(tr("Linear"));
 }
 
-void LinearFit::calculateFitCurveData(double *X, double *Y)
-{
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0+i*step;
-			X[i] = x;
-			Y[i] = d_results[0] + d_results[1]*x;
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i] = d_results[0] + d_results[1]*x;
-		}
-	}
+void LinearFit::fit() {
+  if (d_init_err)
+    return;
+
+  if (d_p > d_n) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot - Fit Error"),
+                          tr("You need at least %1 data points for this fit "
+                             "operation. Operation aborted!").arg(d_p));
+    return;
+  }
+
+  double c0, c1, cov00, cov01, cov11;
+  if (d_weighting == NoWeighting)
+    gsl_fit_linear(d_x, 1, d_y, 1, d_n, &c0, &c1, &cov00, &cov01, &cov11,
+                   &chi_2);
+  else
+    gsl_fit_wlinear(d_x, 1, d_w, 1, d_y, 1, d_n, &c0, &c1, &cov00, &cov01,
+                    &cov11, &chi_2);
+
+  d_results[0] = c0;
+  d_results[1] = c1;
+
+  gsl_matrix_set(covar, 0, 0, cov00);
+  gsl_matrix_set(covar, 0, 1, cov01);
+  gsl_matrix_set(covar, 1, 1, cov11);
+  gsl_matrix_set(covar, 1, 0, cov01);
+
+  generateFitCurve();
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  if (app->writeFitResultsToLog)
+    app->updateLog(logFitInfo(0, 0));
 }
 
+void LinearFit::calculateFitCurveData(double *X, double *Y) {
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = d_results[0] + d_results[1] * x;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = d_results[0] + d_results[1] * x;
+    }
+  }
+}
 
 /*****************************************************************************
  *
@@ -321,95 +318,95 @@ void LinearFit::calculateFitCurveData(double *X, double *Y)
  *****************************************************************************/
 
 LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+    : Fit(parent, g) {
+  init();
 }
 
-LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Graph *g,
+                               const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Graph *g,
+                               const QString &curveTitle, double start,
+                               double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+LinearSlopeFit::LinearSlopeFit(ApplicationWindow *parent, Table *t,
+                               const QString &xCol, const QString &yCol,
+                               int startRow, int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void LinearSlopeFit::init()
-{
-	d_scale_errors = false;
-	
-	d_p = 1;
-    d_min_points = d_p;
-
-	covar = gsl_matrix_alloc (d_p, d_p);
-	d_results = new double[d_p];
-
-    d_param_init = gsl_vector_alloc(d_p);
-	gsl_vector_set_all (d_param_init, 1.0);
-
-	is_non_linear = false;
-	d_formula = "A*x";
-	d_param_names << "A";
-	d_param_explain << "slope";
-	d_explanation = tr("Linear Regression");
-	setObjectName(tr("LinearSlope"));
+void LinearSlopeFit::init() {
+  d_scale_errors = false;
+
+  d_p = 1;
+  d_min_points = d_p;
+
+  covar = gsl_matrix_alloc(d_p, d_p);
+  d_results = new double[d_p];
+
+  d_param_init = gsl_vector_alloc(d_p);
+  gsl_vector_set_all(d_param_init, 1.0);
+
+  is_non_linear = false;
+  d_formula = "A*x";
+  d_param_names << "A";
+  d_param_explain << "slope";
+  d_explanation = tr("Linear Regression");
+  setObjectName(tr("LinearSlope"));
 }
 
-void LinearSlopeFit::fit()
-{
-    if (d_init_err)
-        return;
+void LinearSlopeFit::fit() {
+  if (d_init_err)
+    return;
 
-	if (d_p > d_n){
-  		QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot - Fit Error"),
-  	    tr("You need at least %1 data points for this fit operation. Operation aborted!").arg(d_p));
-  		return;
-  	}
+  if (d_p > d_n) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot - Fit Error"),
+                          tr("You need at least %1 data points for this fit "
+                             "operation. Operation aborted!").arg(d_p));
+    return;
+  }
 
-	double c1, cov11;
-	if (d_weighting == NoWeighting)
-		gsl_fit_mul(d_x, 1, d_y, 1, d_n, &c1, &cov11, &chi_2);
-	else
-		gsl_fit_wmul(d_x, 1, d_w, 1, d_y, 1, d_n, &c1, &cov11, &chi_2);
+  double c1, cov11;
+  if (d_weighting == NoWeighting)
+    gsl_fit_mul(d_x, 1, d_y, 1, d_n, &c1, &cov11, &chi_2);
+  else
+    gsl_fit_wmul(d_x, 1, d_w, 1, d_y, 1, d_n, &c1, &cov11, &chi_2);
 
-	d_results[0] = c1;
+  d_results[0] = c1;
 
-	gsl_matrix_set(covar, 0, 0, cov11);
-	generateFitCurve();
+  gsl_matrix_set(covar, 0, 0, cov11);
+  generateFitCurve();
 
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
-	if (app->writeFitResultsToLog)
-		app->updateLog(logFitInfo(0, 0));
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
+  if (app->writeFitResultsToLog)
+    app->updateLog(logFitInfo(0, 0));
 }
 
-void LinearSlopeFit::calculateFitCurveData(double *X, double *Y)
-{
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1] - X0)/(d_points - 1);
-		for (int i=0; i<d_points; i++){
-		    double x = X0 + i*step;
-			X[i] = x;
-			Y[i] = d_results[0]*x;
-		}
-	} else {
-		for (int i=0; i<d_points; i++) {
-		    double x = d_x[i];
-			X[i] = x;
-			Y[i] = d_results[0]*x;
-		}
-	}
+void LinearSlopeFit::calculateFitCurveData(double *X, double *Y) {
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = d_results[0] * x;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = d_results[0] * x;
+    }
+  }
 }
diff --git a/MantidPlot/src/PolynomialFit.h b/MantidPlot/src/PolynomialFit.h
index 7271339bab38dcb2d221428e1dfa41f65f202fb1..0b13c6293bcab4c9c38c2102b103337c648e477c 100644
--- a/MantidPlot/src/PolynomialFit.h
+++ b/MantidPlot/src/PolynomialFit.h
@@ -31,72 +31,75 @@
 
 #include "Fit.h"
 
-class PolynomialFit : public Fit
-{
-	Q_OBJECT
+class PolynomialFit : public Fit {
+  Q_OBJECT
 
-	public:
-		PolynomialFit(ApplicationWindow *parent, Graph *g, int order = 2, bool legend = false);
-		PolynomialFit(ApplicationWindow *parent, Graph *g, QString& curveTitle, int order = 2, bool legend = false);
-		PolynomialFit(ApplicationWindow *parent, Graph *g, QString& curveTitle, double start, double end, int order = 2, bool legend = false);
-		PolynomialFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1, int order = 2, bool legend = false);
+public:
+  PolynomialFit(ApplicationWindow *parent, Graph *g, int order = 2,
+                bool legend = false);
+  PolynomialFit(ApplicationWindow *parent, Graph *g, QString &curveTitle,
+                int order = 2, bool legend = false);
+  PolynomialFit(ApplicationWindow *parent, Graph *g, QString &curveTitle,
+                double start, double end, int order = 2, bool legend = false);
+  PolynomialFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                const QString &yCol, int startRow = 1, int endRow = -1,
+                int order = 2, bool legend = false);
 
-                QString legendInfo() override;
-                void fit() override;
+  QString legendInfo() override;
+  void fit() override;
 
-                int order(){return d_order;};
-		void setOrder(int order);
+  int order() { return d_order; };
+  void setOrder(int order);
 
-		static QString generateFormula(int order);
-		static QStringList generateParameterList(int order);
+  static QString generateFormula(int order);
+  static QStringList generateParameterList(int order);
 
-                double eval(double *par, double x) override;
+  double eval(double *par, double x) override;
 
-        private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 
-                int d_order;
-		bool show_legend;
+  int d_order;
+  bool show_legend;
 };
 
-class LinearFit : public Fit
-{
-	Q_OBJECT
+class LinearFit : public Fit {
+  Q_OBJECT
 
-	public:
-		LinearFit(ApplicationWindow *parent, Graph *g);
-		LinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		LinearFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		LinearFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
+public:
+  LinearFit(ApplicationWindow *parent, Graph *g);
+  LinearFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  LinearFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+            double start, double end);
+  LinearFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+            const QString &yCol, int startRow = 1, int endRow = -1);
 
-                void fit() override;
-                double eval(double *par, double x) override {
-                  return par[0] + par[1] * x;
-                };
+  void fit() override;
+  double eval(double *par, double x) override { return par[0] + par[1] * x; };
 
-        private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 
-class LinearSlopeFit : public Fit
-{
-	Q_OBJECT
+class LinearSlopeFit : public Fit {
+  Q_OBJECT
 
-	public:
-		LinearSlopeFit(ApplicationWindow *parent, Graph *g);
-		LinearSlopeFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		LinearSlopeFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		LinearSlopeFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
+public:
+  LinearSlopeFit(ApplicationWindow *parent, Graph *g);
+  LinearSlopeFit(ApplicationWindow *parent, Graph *g,
+                 const QString &curveTitle);
+  LinearSlopeFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+                 double start, double end);
+  LinearSlopeFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+                 const QString &yCol, int startRow = 1, int endRow = -1);
 
-                void fit() override;
-                double eval(double *par, double x) override {
-                  return par[0] * x;
-                };
+  void fit() override;
+  double eval(double *par, double x) override { return par[0] * x; };
 
-        private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 };
 #endif
diff --git a/MantidPlot/src/PrecompiledHeader.h b/MantidPlot/src/PrecompiledHeader.h
index 0dbf2bd8bdbe5366bbe67b193afda65342f6b073..61650fb002ccf40040845cfe7a11b7e9382e8e07 100644
--- a/MantidPlot/src/PrecompiledHeader.h
+++ b/MantidPlot/src/PrecompiledHeader.h
@@ -1,20 +1,18 @@
 #ifndef MANTIDPLOT_PRECOMPILEDHEADER_H_
 #define MANTIDPLOT_PRECOMPILEDHEADER_H_
 
-//Mantid
+// Mantid
 #include "MantidKernel/Exception.h"
 #include "MantidAPI/IAlgorithm.h"
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 #include "MantidAPI/ITableWorkspace_fwd.h"
 #include "MantidAPI/AnalysisDataService.h"
 
-//STL 
+// STL
 #include <istream>
 #include <set>
 #include <vector>
 #include <string>
 #include <cmath>
 
-
-
-#endif //MANTIDPLOT_PRECOMPILEDHEADER_H_
\ No newline at end of file
+#endif // MANTIDPLOT_PRECOMPILEDHEADER_H_
\ No newline at end of file
diff --git a/MantidPlot/src/PythonScript.h b/MantidPlot/src/PythonScript.h
index 2df4848167251e0ab3ee2d6680d9a284db0cee86..988057823bab924f9a4662755a654e379efcd623 100644
--- a/MantidPlot/src/PythonScript.h
+++ b/MantidPlot/src/PythonScript.h
@@ -39,7 +39,6 @@
 #include <QFileInfo>
 #include <QDir>
 
-
 class ScriptingEnv;
 class PythonScripting;
 struct _sipWrapperType;
@@ -47,21 +46,21 @@ struct _sipWrapperType;
 /**
  * This class holds, compiles and executes the Python code.
  */
-class PythonScript : public Script, MantidQt::API::WorkspaceObserver
-{
+class PythonScript : public Script, MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 public:
   /// Constructor
-  PythonScript(PythonScripting *env, const QString &name, const InteractionType interact,
-               QObject * context);
+  PythonScript(PythonScripting *env, const QString &name,
+               const InteractionType interact, QObject *context);
   /// Destructor
   ~PythonScript() override;
 
-  /// Set the identifier of the script. If empty, set a default so that the code object behaves correctly
+  /// Set the identifier of the script. If empty, set a default so that the code
+  /// object behaves correctly
   void setIdentifier(const QString &name) override;
 
   /// Create a PyObject that wraps this C++ instance
-  PyObject * createSipInstanceFromMe();
+  PyObject *createSipInstanceFromMe();
 
   // -------------------------- Print/error message handling ------------------
   /// Connects the python stdout to a Qt signal
@@ -69,14 +68,14 @@ public:
   /// Simulate file-like object (required for IPython)
   inline void flush() {}
   /// Simulate file-like object (required for colorama)
-  inline bool closed() { return false;  }
+  inline bool closed() { return false; }
   /// Is the given code complete
   bool compilesToCompleteStatement(const QString &code) const override;
 
   // -------------------------- Line number tracing ---------------------------
   /// Emits a signal from this object indicating the current line number of the
   /// code. This includes any offset.
-  void lineNumberChanged(PyObject * codeObject, int lineNo);
+  void lineNumberChanged(PyObject *codeObject, int lineNo);
   /// Emit the line change signal
   void sendLineChangeSignal(int lineNo, bool error);
 
@@ -86,8 +85,8 @@ public:
   /// Special handle for syntax errors as they have no traceback
   QString constructSyntaxErrorStr(PyObject *syntaxError);
   /// Convert a traceback to a string
-  void tracebackToMsg(QTextStream &msgStream, PyTracebackObject* traceback,
-                      bool root=true);
+  void tracebackToMsg(QTextStream &msgStream, PyTracebackObject *traceback,
+                      bool root = true);
 
   /// Set the name of the passed object so that Python can refer to it
   bool setQObject(QObject *val, const char *name) override;
@@ -102,61 +101,53 @@ public:
 
 private:
   /// Helper class to ensure the sys.path variable is updated correctly
-  struct PythonPathHolder
-  {
+  struct PythonPathHolder {
     /// Update the path with the given entry
     explicit PythonPathHolder(const QString &entry) : m_path(entry) {
       const QFileInfo filePath(m_path);
-      if( filePath.exists() )
-      {
+      if (filePath.exists()) {
         QDir directory = filePath.absoluteDir();
         // Check it is not a package
-        if( !QFileInfo(directory, "__init__.py").exists() )
-        {
+        if (!QFileInfo(directory, "__init__.py").exists()) {
           m_path = directory.absolutePath();
           appendPath(m_path);
-        }
-        else
-        {
+        } else {
           m_path = "";
         }
       }
     }
     /// Remove the entry from the path
-    ~PythonPathHolder()
-    {
-      if(!m_path.isEmpty()) removePath(m_path);
+    ~PythonPathHolder() {
+      if (!m_path.isEmpty())
+        removePath(m_path);
     }
 
-    void appendPath(const QString & path)
-    {
+    void appendPath(const QString &path) {
       ScopedPythonGIL pythonLock;
-      QString code =
-        "if r'%1' not in sys.path:\n"
-        "    sys.path.append(r'%1')";
+      QString code = "if r'%1' not in sys.path:\n"
+                     "    sys.path.append(r'%1')";
       code = code.arg(path);
       PyRun_SimpleString(code);
     }
-    void removePath(const QString & path)
-    {
+    void removePath(const QString &path) {
       ScopedPythonGIL pythonLock;
-      QString code =
-        "if r'%1' in sys.path:\n"
-        "    sys.path.remove(r'%1')";
+      QString code = "if r'%1' in sys.path:\n"
+                     "    sys.path.remove(r'%1')";
       code = code.arg(path);
       PyRun_SimpleString(code.toAscii());
     }
+
   private:
     QString m_path;
   };
 
-
-  inline PythonScripting * pythonEnv() const { return m_pythonEnv; }
-  void initialize(const QString & name, QObject *context);
+  inline PythonScripting *pythonEnv() const { return m_pythonEnv; }
+  void initialize(const QString &name, QObject *context);
   void beginStdoutRedirect();
   void endStdoutRedirect();
 
-  // --------------------------- Script compilation/execution  -----------------------------------
+  // --------------------------- Script compilation/execution
+  // -----------------------------------
   /// Compile the code, returning true if it was successful, false otherwise
   bool compileImpl() override;
   /// Evaluate the current code and return a result as a QVariant
@@ -171,14 +162,14 @@ private:
   /// Performs the call to Python from a string
   bool executeString();
   /// Executes the code object and returns the result, may be null
-  PyObject* executeCompiledCode(PyObject *compiledCode);
+  PyObject *executeCompiledCode(PyObject *compiledCode);
   /// Check an object for a result.
   bool checkResult(PyObject *result);
   /// Compile to bytecode
-  PyObject * compileToByteCode(bool for_eval=true);
-
+  PyObject *compileToByteCode(bool for_eval = true);
 
-  // ---------------------------- Variable reference ---------------------------------------------
+  // ---------------------------- Variable reference
+  // ---------------------------------------------
   /// Listen to add notifications from the ADS
   void addHandle(const std::string &wsName,
                  const Mantid::API::Workspace_sptr ws) override;
@@ -190,19 +181,20 @@ private:
   /// Listen to ADS clear notifications
   void clearADSHandle() override;
   /// Add/update a Python reference to the given workspace
-  void addPythonReference(const std::string& wsName,const Mantid::API::Workspace_sptr ws);
+  void addPythonReference(const std::string &wsName,
+                          const Mantid::API::Workspace_sptr ws);
   /// Delete a Python reference to the given workspace name
-  void deletePythonReference(const std::string& wsName);
+  void deletePythonReference(const std::string &wsName);
 
   /// Send out an error and clear it from python.
   void emit_error();
 
-  PythonScripting * m_pythonEnv;
+  PythonScripting *m_pythonEnv;
   PyObject *localDict, *stdoutSave, *stderrSave;
   PyObject *m_codeFileObject;
   long m_threadID; ///< Python thread id
   /// A reference to the IAlgorithm._algorithmInThread static method
-  PyObject * m_algorithmInThread;
+  PyObject *m_algorithmInThread;
   bool isFunction;
   QString fileName;
   bool m_isInitialized;
diff --git a/MantidPlot/src/PythonScripting.h b/MantidPlot/src/PythonScripting.h
index 3ab487a58ee09e7ea4cf87b58840e1e2e564dc79..6a0e53dfd7b33881f91aa20da93126c179b74ed9 100644
--- a/MantidPlot/src/PythonScripting.h
+++ b/MantidPlot/src/PythonScripting.h
@@ -40,8 +40,7 @@ class QString;
 /**
  * A scripting environment for executing Python code.
  */
-class PythonScripting: public ScriptingEnv
-{
+class PythonScripting : public ScriptingEnv {
 
   Q_OBJECT
 
@@ -57,7 +56,7 @@ public:
   /// Simulate file-like object (required for colorama)
   inline bool closed() { return false; }
   /// 'Fake' method needed for IPython import
-  void set_parent(PyObject*) {}
+  void set_parent(PyObject *) {}
 
   /// Set the argv attribute on the sys module
   void setSysArgs(const QStringList &args) override;
@@ -80,27 +79,28 @@ public:
   /// Convert a Python list object to a Qt QStringList
   QStringList toStringList(PyObject *py_seq);
   /// Convert a QtringList to a Python List
-  PyObject * toPyList(const QStringList & items);
-  /// Returns an integer representation of the object. No check is performed to see if it is an integer
+  PyObject *toPyList(const QStringList &items);
+  /// Returns an integer representation of the object. No check is performed to
+  /// see if it is an integer
   long toLong(PyObject *object, bool decref = false);
   /// Raise an asynchronous exception in the given thread
   void raiseAsyncException(long id, PyObject *exc);
 
-  ///Return a list of file extensions for Python
+  /// Return a list of file extensions for Python
   const QStringList fileExtensions() const override;
 
   /// Set a reference to a QObject in the given dictionary
-  bool setQObject(QObject*, const char*, PyObject *dict);
+  bool setQObject(QObject *, const char *, PyObject *dict);
   /// Set a reference to a QObject in the global dictionary
   bool setQObject(QObject *val, const char *name) override {
     return setQObject(val, name, NULL);
   }
   /// Set a reference to an int in the global dictionary
   bool setInt(int, const char *) override;
-  bool setInt(int, const char*, PyObject *dict);
+  bool setInt(int, const char *, PyObject *dict);
   /// Set a reference to a double in the global dictionary
   bool setDouble(double, const char *) override;
-  bool setDouble(double, const char*, PyObject *dict);
+  bool setDouble(double, const char *, PyObject *dict);
 
   /// Return a list of mathematical functions define by qtiplot
   const QStringList mathFunctions() const override;
diff --git a/MantidPlot/src/QwtBarCurve.cpp b/MantidPlot/src/QwtBarCurve.cpp
index 09ad3277a69918ade3ce4bd7cf23b5df80a2c5a6..f708849dce9dd18400c2c7eb630915467d6ed0f3 100644
--- a/MantidPlot/src/QwtBarCurve.cpp
+++ b/MantidPlot/src/QwtBarCurve.cpp
@@ -2,7 +2,8 @@
     File                 : QwtBarCurve.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Bar curve
 
@@ -29,174 +30,150 @@
 #include "QwtBarCurve.h"
 #include <QPainter>
 
-QwtBarCurve::QwtBarCurve(BarStyle style, Table *t, const QString& xColName, const QString& name, int startRow, int endRow):
-    DataCurve(t, xColName, name, startRow, endRow)
-{
-bar_offset=0;
-bar_gap=0;
-bar_style=style;
-
-setPen(QPen(Qt::black, 1, Qt::SolidLine));
-setBrush(QBrush(Qt::red));
-setStyle(QwtPlotCurve::UserCurve);
-
-if (bar_style == Vertical)
-	setType(Graph::VerticalBars);
-else
-	setType(Graph::HorizontalBars);
+QwtBarCurve::QwtBarCurve(BarStyle style, Table *t, const QString &xColName,
+                         const QString &name, int startRow, int endRow)
+    : DataCurve(t, xColName, name, startRow, endRow) {
+  bar_offset = 0;
+  bar_gap = 0;
+  bar_style = style;
+
+  setPen(QPen(Qt::black, 1, Qt::SolidLine));
+  setBrush(QBrush(Qt::red));
+  setStyle(QwtPlotCurve::UserCurve);
+
+  if (bar_style == Vertical)
+    setType(Graph::VerticalBars);
+  else
+    setType(Graph::HorizontalBars);
 }
 
-void QwtBarCurve::copy(const QwtBarCurve *b)
-{
-bar_gap = b->bar_gap;
-bar_offset = b->bar_offset;
-bar_style = b->bar_style;
+void QwtBarCurve::copy(const QwtBarCurve *b) {
+  bar_gap = b->bar_gap;
+  bar_offset = b->bar_offset;
+  bar_style = b->bar_style;
 }
 
-void QwtBarCurve::draw(QPainter *painter,
-    const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
-   if ( !painter || dataSize() <= 0 )
-        return;
-
-    if (to < 0)
-        to = dataSize() - 1;
-
-    painter->save();
-    painter->setPen(QwtPlotCurve::pen());
-    painter->setBrush(QwtPlotCurve::brush());
-
-    int ref;
-	double bar_width = 0;
-
-    if (bar_style == Vertical)
-       ref= yMap.transform(1e-100); //smalest positive value for log scales
-    else
-       ref= xMap.transform(1e-100);
-
-	if (bar_style == Vertical)
-	{
-		int dx = abs(xMap.transform(x(from+1))-xMap.transform(x(from)));
-		for (int i=from+2; i<to; i++)
-		{
-			int min = abs(xMap.transform(x(i+1))-xMap.transform(x(i)));
-			if (min <= dx)
-				dx=min;
-		}
-		bar_width = dx*(1-bar_gap*0.01);
-	}
-	else
-	{
-		int dy = abs(yMap.transform(y(from+1))-yMap.transform(y(from)));
-		for (int i=from+2; i<to; i++)
-		{
-			int min = abs(yMap.transform(y(i+1))-yMap.transform(y(i)));
-			if (min <= dy)
-				dy=min;
-		}
-		bar_width = dy*(1-bar_gap*0.01);
-	}
-
-	const int half_width = static_cast<int>((0.5-bar_offset*0.01)*bar_width);
-	int bw1 = static_cast<int>(bar_width) + 1;
-	for (int i=from; i<=to; i++)
-	{
-		const int px = xMap.transform(x(i));
-        const int py = yMap.transform(y(i));
-
-		if (bar_style == Vertical)
-		{
-			if (y(i) < 0)
-				painter->drawRect(px-half_width, ref, bw1, (py-ref));
-			else
-				painter->drawRect(px-half_width, py, bw1, (ref-py+1));
-		}
-		else
-		{
-			if (x(i) < 0)
-				painter->drawRect(px, py-half_width, (ref-px), bw1);
-			else
-				painter->drawRect(ref, py-half_width, (px-ref), bw1);
-		}
-	}
-	painter->restore();
+void QwtBarCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                       const QwtScaleMap &yMap, int from, int to) const {
+  if (!painter || dataSize() <= 0)
+    return;
+
+  if (to < 0)
+    to = dataSize() - 1;
+
+  painter->save();
+  painter->setPen(QwtPlotCurve::pen());
+  painter->setBrush(QwtPlotCurve::brush());
+
+  int ref;
+  double bar_width = 0;
+
+  if (bar_style == Vertical)
+    ref = yMap.transform(1e-100); // smalest positive value for log scales
+  else
+    ref = xMap.transform(1e-100);
+
+  if (bar_style == Vertical) {
+    int dx = abs(xMap.transform(x(from + 1)) - xMap.transform(x(from)));
+    for (int i = from + 2; i < to; i++) {
+      int min = abs(xMap.transform(x(i + 1)) - xMap.transform(x(i)));
+      if (min <= dx)
+        dx = min;
+    }
+    bar_width = dx * (1 - bar_gap * 0.01);
+  } else {
+    int dy = abs(yMap.transform(y(from + 1)) - yMap.transform(y(from)));
+    for (int i = from + 2; i < to; i++) {
+      int min = abs(yMap.transform(y(i + 1)) - yMap.transform(y(i)));
+      if (min <= dy)
+        dy = min;
+    }
+    bar_width = dy * (1 - bar_gap * 0.01);
+  }
+
+  const int half_width =
+      static_cast<int>((0.5 - bar_offset * 0.01) * bar_width);
+  int bw1 = static_cast<int>(bar_width) + 1;
+  for (int i = from; i <= to; i++) {
+    const int px = xMap.transform(x(i));
+    const int py = yMap.transform(y(i));
+
+    if (bar_style == Vertical) {
+      if (y(i) < 0)
+        painter->drawRect(px - half_width, ref, bw1, (py - ref));
+      else
+        painter->drawRect(px - half_width, py, bw1, (ref - py + 1));
+    } else {
+      if (x(i) < 0)
+        painter->drawRect(px, py - half_width, (ref - px), bw1);
+      else
+        painter->drawRect(ref, py - half_width, (px - ref), bw1);
+    }
+  }
+  painter->restore();
 }
 
-QwtDoubleRect QwtBarCurve::boundingRect() const
-{
-QwtDoubleRect rect = QwtPlotCurve::boundingRect();
-double n= (double)dataSize();
-
-if (bar_style == Vertical)
-	{
-	double dx=(rect.right()-rect.left())/n;
-	rect.setLeft(rect.left()-dx);
-	rect.setRight(rect.right()+dx);
-	}
-else
-	{
-	double dy=(rect.bottom()-rect.top())/n;
-	rect.setTop(rect.top()-dy);
-	rect.setBottom(rect.bottom()+dy);
-	}
-
-return rect;
+QwtDoubleRect QwtBarCurve::boundingRect() const {
+  QwtDoubleRect rect = QwtPlotCurve::boundingRect();
+  double n = (double)dataSize();
+
+  if (bar_style == Vertical) {
+    double dx = (rect.right() - rect.left()) / n;
+    rect.setLeft(rect.left() - dx);
+    rect.setRight(rect.right() + dx);
+  } else {
+    double dy = (rect.bottom() - rect.top()) / n;
+    rect.setTop(rect.top() - dy);
+    rect.setBottom(rect.bottom() + dy);
+  }
+
+  return rect;
 }
 
-void QwtBarCurve::setGap (int gap)
-{
-if (bar_gap == gap)
-	return;
+void QwtBarCurve::setGap(int gap) {
+  if (bar_gap == gap)
+    return;
 
-bar_gap =gap;
+  bar_gap = gap;
 }
 
-void QwtBarCurve::setOffset(int offset)
-{
-if (bar_offset == offset)
-	return;
+void QwtBarCurve::setOffset(int offset) {
+  if (bar_offset == offset)
+    return;
 
-bar_offset = offset;
+  bar_offset = offset;
 }
 
-double QwtBarCurve::dataOffset()
-{
-	if (bar_style == Vertical)
-	{
-		const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
-		int dx = abs(xMap.transform(x(1))-xMap.transform(x(0)));
-		double bar_width = dx*(1-bar_gap*0.01);
-		if (plot()->isVisible())
-		{
-			for (int i = 2; i<dataSize(); i++)
-			{
-				int min = abs(xMap.transform(x(i+1))-xMap.transform(x(i)));
-				if (min <= dx)
-					dx=min;
-			}
-			int x1 = xMap.transform(minXValue()) + static_cast<int>(bar_offset*0.01*bar_width);
-			return xMap.invTransform(x1) - minXValue();
-		}
-		else
-			return 0.5*bar_offset*0.01*bar_width;
-	}
-	else
-	{
-		const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
-		int dy = abs(yMap.transform(y(1))-yMap.transform(y(0)));
-		double bar_width = dy*(1-bar_gap*0.01);
-		if (plot()->isVisible())
-		{
-			for (int i=2; i<dataSize(); i++)
-			{
-				int min = abs(yMap.transform(y(i+1))-yMap.transform(y(i)));
-				if (min <= dy)
-					dy=min;
-			}
-			int y1 = yMap.transform(minYValue()) + static_cast<int>(bar_offset*0.01*bar_width);
-			return yMap.invTransform(y1) - minYValue();
-		}
-		else
-			return 0.5*bar_offset*0.01*bar_width;
-	}
+double QwtBarCurve::dataOffset() {
+  if (bar_style == Vertical) {
+    const QwtScaleMap &xMap = plot()->canvasMap(xAxis());
+    int dx = abs(xMap.transform(x(1)) - xMap.transform(x(0)));
+    double bar_width = dx * (1 - bar_gap * 0.01);
+    if (plot()->isVisible()) {
+      for (int i = 2; i < dataSize(); i++) {
+        int min = abs(xMap.transform(x(i + 1)) - xMap.transform(x(i)));
+        if (min <= dx)
+          dx = min;
+      }
+      int x1 = xMap.transform(minXValue()) +
+               static_cast<int>(bar_offset * 0.01 * bar_width);
+      return xMap.invTransform(x1) - minXValue();
+    } else
+      return 0.5 * bar_offset * 0.01 * bar_width;
+  } else {
+    const QwtScaleMap &yMap = plot()->canvasMap(yAxis());
+    int dy = abs(yMap.transform(y(1)) - yMap.transform(y(0)));
+    double bar_width = dy * (1 - bar_gap * 0.01);
+    if (plot()->isVisible()) {
+      for (int i = 2; i < dataSize(); i++) {
+        int min = abs(yMap.transform(y(i + 1)) - yMap.transform(y(i)));
+        if (min <= dy)
+          dy = min;
+      }
+      int y1 = yMap.transform(minYValue()) +
+               static_cast<int>(bar_offset * 0.01 * bar_width);
+      return yMap.invTransform(y1) - minYValue();
+    } else
+      return 0.5 * bar_offset * 0.01 * bar_width;
+  }
 }
diff --git a/MantidPlot/src/QwtBarCurve.h b/MantidPlot/src/QwtBarCurve.h
index e61dc04ba8764cac51577f1aa2781fd7dafa3a7a..892fdb536907e728766273f49df0d3da39d68fda 100644
--- a/MantidPlot/src/QwtBarCurve.h
+++ b/MantidPlot/src/QwtBarCurve.h
@@ -2,7 +2,8 @@
     File                 : QwtBarCurve.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Bar curve
 
@@ -33,33 +34,34 @@
 #include <qwt_plot.h>
 
 //! Bar curve
-class QwtBarCurve: public DataCurve
-{
+class QwtBarCurve : public DataCurve {
 public:
-	enum BarStyle{Vertical = 0, Horizontal = 1};
-	QwtBarCurve(BarStyle style, Table *t, const QString& xColName, const QString& name, int startRow, int endRow);
+  enum BarStyle { Vertical = 0, Horizontal = 1 };
+  QwtBarCurve(BarStyle style, Table *t, const QString &xColName,
+              const QString &name, int startRow, int endRow);
 
-	void copy(const QwtBarCurve *b);
+  void copy(const QwtBarCurve *b);
 
-        QwtDoubleRect boundingRect() const override;
+  QwtDoubleRect boundingRect() const override;
 
-        BarStyle orientation(){return bar_style;};
+  BarStyle orientation() { return bar_style; };
 
-	void setGap (int gap);
-	int gap() const {return bar_gap;};
+  void setGap(int gap);
+  int gap() const { return bar_gap; };
 
-	void setOffset(int offset);
-	int offset() const {return bar_offset;};
+  void setOffset(int offset);
+  int offset() const { return bar_offset; };
 
-	double dataOffset();
+  double dataOffset();
 
 private:
-	using DataCurve::draw; // Unhide base class method (avoids Intel compiler warning)
-        void draw(QPainter *painter, const QwtScaleMap &xMap,
-                  const QwtScaleMap &yMap, int from, int to) const override;
+  using DataCurve::draw; // Unhide base class method (avoids Intel compiler
+                         // warning)
+  void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+            int from, int to) const override;
 
-        int bar_gap, bar_offset;
-	BarStyle bar_style;
+  int bar_gap, bar_offset;
+  BarStyle bar_style;
 };
 
 #endif
diff --git a/MantidPlot/src/QwtErrorPlotCurve.cpp b/MantidPlot/src/QwtErrorPlotCurve.cpp
index fa46d3457e5768ff2e719d47584abafca03df380..f7848d338452bf3c513cd2138dea9c15c9b9553d 100644
--- a/MantidPlot/src/QwtErrorPlotCurve.cpp
+++ b/MantidPlot/src/QwtErrorPlotCurve.cpp
@@ -34,24 +34,22 @@
 
 #include <QPainter>
 
-QwtErrorPlotCurve::QwtErrorPlotCurve(int orientation, Table *t, const QString& name) :
-    DataCurve(t, QString(), name), ErrorBarSettings(), d_master_curve(NULL)
-{
+QwtErrorPlotCurve::QwtErrorPlotCurve(int orientation, Table *t,
+                                     const QString &name)
+    : DataCurve(t, QString(), name), ErrorBarSettings(), d_master_curve(NULL) {
   type = orientation;
   setType(Graph::ErrorBars);
   setStyle(QwtPlotCurve::UserCurve);
 }
 
-QwtErrorPlotCurve::QwtErrorPlotCurve(Table *t, const QString& name) :
-    DataCurve(t, QString(), name), ErrorBarSettings(), d_master_curve(NULL)
-{
+QwtErrorPlotCurve::QwtErrorPlotCurve(Table *t, const QString &name)
+    : DataCurve(t, QString(), name), ErrorBarSettings(), d_master_curve(NULL) {
   type = Vertical;
   setType(Graph::ErrorBars);
   setStyle(QwtPlotCurve::UserCurve);
 }
 
-void QwtErrorPlotCurve::copy(const QwtErrorPlotCurve *e)
-{
+void QwtErrorPlotCurve::copy(const QwtErrorPlotCurve *e) {
   setCapLength(e->capLength());
   type = e->type;
   drawPlusSide(e->plusSide());
@@ -61,9 +59,8 @@ void QwtErrorPlotCurve::copy(const QwtErrorPlotCurve *e)
   err = e->err;
 }
 
-void QwtErrorPlotCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-    int from, int to) const
-{
+void QwtErrorPlotCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                             const QwtScaleMap &yMap, int from, int to) const {
   if (!painter || dataSize() <= 0)
     return;
 
@@ -76,13 +73,13 @@ void QwtErrorPlotCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const Q
   painter->restore();
 }
 
-void QwtErrorPlotCurve::drawErrorBars(QPainter *painter, const QwtScaleMap &xMap,
-    const QwtScaleMap &yMap, int from, int to) const
-{
+void QwtErrorPlotCurve::drawErrorBars(QPainter *painter,
+                                      const QwtScaleMap &xMap,
+                                      const QwtScaleMap &yMap, int from,
+                                      int to) const {
   int sh = 0, sw = 0;
   const QwtSymbol symbol = d_master_curve->symbol();
-  if (symbol.style() != QwtSymbol::NoSymbol)
-  {
+  if (symbol.style() != QwtSymbol::NoSymbol) {
     sh = symbol.size().height();
     sw = symbol.size().width();
   }
@@ -96,47 +93,43 @@ void QwtErrorPlotCurve::drawErrorBars(QPainter *painter, const QwtScaleMap &xMap
 
   int skipPoints = d_master_curve->skipSymbolsCount();
 
-  for (int i = from; i <= to; i += skipPoints)
-  {
+  for (int i = from; i <= to; i += skipPoints) {
     const int xi = xMap.transform(x(i) + d_xOffset);
     const int yi = yMap.transform(y(i) + d_yOffset);
 
-    if (type == Vertical)
-    {
+    if (type == Vertical) {
       const int yh = yMap.transform(y(i) + err[i]);
       const int yl = yMap.transform(y(i) - err[i]);
       const int yhl = yi - sh / 2;
       const int ylh = yi + sh / 2;
 
-      if (plusSide())
-      {
+      if (plusSide()) {
         QwtPainter::drawLine(painter, xi, yhl, xi, yh);
-        QwtPainter::drawLine(painter, xi - capLength() / 2, yh, xi + capLength() / 2, yh);
+        QwtPainter::drawLine(painter, xi - capLength() / 2, yh,
+                             xi + capLength() / 2, yh);
       }
-      if (minusSide())
-      {
+      if (minusSide()) {
         QwtPainter::drawLine(painter, xi, ylh, xi, yl);
-        QwtPainter::drawLine(painter, xi - capLength() / 2, yl, xi + capLength() / 2, yl);
+        QwtPainter::drawLine(painter, xi - capLength() / 2, yl,
+                             xi + capLength() / 2, yl);
       }
       if (throughSymbol())
         QwtPainter::drawLine(painter, xi, yhl, xi, ylh);
-    }
-    else if (type == Horizontal)
-    {
+    } else if (type == Horizontal) {
       const int xp = xMap.transform(x(i) + err[i]);
       const int xm = xMap.transform(x(i) - err[i]);
       const int xpm = xi + sw / 2;
       const int xmp = xi - sw / 2;
 
-      if (plusSide())
-      {
+      if (plusSide()) {
         QwtPainter::drawLine(painter, xp, yi, xpm, yi);
-        QwtPainter::drawLine(painter, xp, yi - capLength() / 2, xp, yi + capLength() / 2);
+        QwtPainter::drawLine(painter, xp, yi - capLength() / 2, xp,
+                             yi + capLength() / 2);
       }
-      if (minusSide())
-      {
+      if (minusSide()) {
         QwtPainter::drawLine(painter, xm, yi, xmp, yi);
-        QwtPainter::drawLine(painter, xm, yi - capLength() / 2, xm, yi + capLength() / 2);
+        QwtPainter::drawLine(painter, xm, yi - capLength() / 2, xm,
+                             yi + capLength() / 2);
       }
       if (throughSymbol())
         QwtPainter::drawLine(painter, xmp, yi, xpm, yi);
@@ -144,16 +137,14 @@ void QwtErrorPlotCurve::drawErrorBars(QPainter *painter, const QwtScaleMap &xMap
   }
 }
 
-double QwtErrorPlotCurve::errorValue(int i)
-{
+double QwtErrorPlotCurve::errorValue(int i) {
   if (i >= 0 && i < dataSize())
     return err[i];
   else
     return 0.0;
 }
 
-bool QwtErrorPlotCurve::xErrors()
-{
+bool QwtErrorPlotCurve::xErrors() {
   bool x = false;
   if (type == Horizontal)
     x = true;
@@ -161,59 +152,48 @@ bool QwtErrorPlotCurve::xErrors()
   return x;
 }
 
-void QwtErrorPlotCurve::setXErrors(bool yes)
-{
+void QwtErrorPlotCurve::setXErrors(bool yes) {
   if (yes)
     type = Horizontal;
   else
     type = Vertical;
 }
 
-void QwtErrorPlotCurve::setWidth(double w)
-{
+void QwtErrorPlotCurve::setWidth(double w) {
   QPen p = pen();
   p.setWidthF(w);
   setPen(p);
 }
 
-void QwtErrorPlotCurve::setColor(const QColor& c)
-{
+void QwtErrorPlotCurve::setColor(const QColor &c) {
   QPen p = pen();
   p.setColor(c);
   setPen(p);
 }
 
-QwtDoubleRect QwtErrorPlotCurve::boundingRect() const
-{
+QwtDoubleRect QwtErrorPlotCurve::boundingRect() const {
   QwtDoubleRect rect = QwtPlotCurve::boundingRect();
 
   int size = dataSize();
 
   QwtArray<double> X(size), Y(size), min(size), max(size);
-  for (int i = 0; i < size; i++)
-  {
+  for (int i = 0; i < size; i++) {
     X[i] = x(i);
     Y[i] = y(i);
-    if (type == Vertical)
-    {
+    if (type == Vertical) {
       min[i] = y(i) - err[i];
       max[i] = y(i) + err[i];
-    }
-    else
-    {
+    } else {
       min[i] = x(i) - err[i];
       max[i] = x(i) + err[i];
     }
   }
 
   QwtArrayData *erMin, *erMax;
-  if (type == Vertical)
-  {
+  if (type == Vertical) {
     erMin = new QwtArrayData(X, min);
     erMax = new QwtArrayData(X, max);
-  }
-  else
-  {
+  } else {
     erMin = new QwtArrayData(min, Y);
     erMax = new QwtArrayData(max, Y);
   }
@@ -232,8 +212,7 @@ QwtDoubleRect QwtErrorPlotCurve::boundingRect() const
   return rect;
 }
 
-void QwtErrorPlotCurve::setMasterCurve(DataCurve *c)
-{
+void QwtErrorPlotCurve::setMasterCurve(DataCurve *c) {
   if (!c || d_master_curve == c)
     return;
 
@@ -246,8 +225,7 @@ void QwtErrorPlotCurve::setMasterCurve(DataCurve *c)
   loadData();
 }
 
-void QwtErrorPlotCurve::loadData()
-{
+void QwtErrorPlotCurve::loadData() {
   if (!d_master_curve)
     return;
 
@@ -273,21 +251,19 @@ void QwtErrorPlotCurve::loadData()
   QVector<double> X(r), Y(r), err(r);
   int data_size = 0;
   QLocale locale = (static_cast<Plot *>(plot()))->locale();
-  for (int i = d_start_row; i <= d_end_row; i++)
-  {
+  for (int i = d_start_row; i <= d_end_row; i++) {
     QString xval = mt->text(i, xcol);
     QString yval = mt->text(i, ycol);
     QString errval = d_table->text(i, errcol);
-    if (!xval.isEmpty() && !yval.isEmpty() && !errval.isEmpty())
-    {
+    if (!xval.isEmpty() && !yval.isEmpty() && !errval.isEmpty()) {
       bool ok = true;
       if (xColType == Table::Text)
-        X[data_size] = (double) (data_size + 1);
+        X[data_size] = (double)(data_size + 1);
       else
         X[data_size] = locale.toDouble(xval, &ok);
 
       if (yColType == Table::Text)
-        Y[data_size] = (double) (data_size + 1);
+        Y[data_size] = (double)(data_size + 1);
       else
         Y[data_size] = locale.toDouble(yval, &ok);
 
@@ -311,21 +287,19 @@ void QwtErrorPlotCurve::loadData()
   setErrors(err);
 }
 
-QString QwtErrorPlotCurve::plotAssociation() const
-{
+QString QwtErrorPlotCurve::plotAssociation() const {
   if (!d_master_curve)
     return QString();
 
-  QString base = d_master_curve->xColumnName() + "(X)," + d_master_curve->title().text() + "(Y),"
-      + title().text();
+  QString base = d_master_curve->xColumnName() + "(X)," +
+                 d_master_curve->title().text() + "(Y)," + title().text();
   if (type == Horizontal)
     return base + "(xErr)";
   else
     return base + "(yErr)";
 }
 
-bool QwtErrorPlotCurve::updateData(Table *t, const QString& colName)
-{
+bool QwtErrorPlotCurve::updateData(Table *t, const QString &colName) {
   if (d_table != t || colName != title().text())
     return false;
 
diff --git a/MantidPlot/src/QwtErrorPlotCurve.h b/MantidPlot/src/QwtErrorPlotCurve.h
index cfce6b52dc694d7a06bcc0d4e8eb3f6ef7c8a73b..04f2597f47f8cc7e31466b3416326266f23f2db7 100644
--- a/MantidPlot/src/QwtErrorPlotCurve.h
+++ b/MantidPlot/src/QwtErrorPlotCurve.h
@@ -2,7 +2,8 @@
     File                 : QwtErrorPlotCurve.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Error bars curve
 
@@ -34,21 +35,20 @@
 #include <qwt_plot.h>
 
 //! Error bars curve
-class QwtErrorPlotCurve: public DataCurve, public ErrorBarSettings
-{
+class QwtErrorPlotCurve : public DataCurve, public ErrorBarSettings {
 public:
-  enum Orientation{Horizontal = 0, Vertical = 1};
+  enum Orientation { Horizontal = 0, Vertical = 1 };
 
-  QwtErrorPlotCurve(int orientation, Table *t, const QString& name);
-  QwtErrorPlotCurve(Table *t, const QString& name);
+  QwtErrorPlotCurve(int orientation, Table *t, const QString &name);
+  QwtErrorPlotCurve(Table *t, const QString &name);
 
   void copy(const QwtErrorPlotCurve *e);
 
   QwtDoubleRect boundingRect() const override;
 
   double errorValue(int i);
-  QwtArray<double> errors(){return err;};
-  void setErrors(const QwtArray<double>&data){err=data;};
+  QwtArray<double> errors() { return err; };
+  void setErrors(const QwtArray<double> &data) { err = data; };
 
   double width() const override { return pen().widthF(); };
   void setWidth(double w) override;
@@ -56,18 +56,19 @@ public:
   QColor color() const override { return pen().color(); };
   void setColor(const QColor &c) override;
 
-  int direction(){return type;};
-  void setDirection(int o){type = o;};
+  int direction() { return type; };
+  void setDirection(int o) { type = o; };
 
   bool xErrors();
   void setXErrors(bool yes);
 
   //! Returns the master curve to which this error bars curve is attached.
-  DataCurve* masterCurve(){return d_master_curve;};
+  DataCurve *masterCurve() { return d_master_curve; };
   void setMasterCurve(DataCurve *c);
 
-  //! Causes the master curve to delete this curve from its managed error bars list.
-  void detachFromMasterCurve(){d_master_curve->removeErrorBars(this);};
+  //! Causes the master curve to delete this curve from its managed error bars
+  // list.
+  void detachFromMasterCurve() { d_master_curve->removeErrorBars(this); };
 
   QString plotAssociation() const override;
 
@@ -75,7 +76,8 @@ public:
   void loadData() override;
 
 private:
-  using DataCurve::draw; // Unhide base class method (avoids Intel compiler warning)
+  using DataCurve::draw; // Unhide base class method (avoids Intel compiler
+                         // warning)
   void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             int from, int to) const override;
 
diff --git a/MantidPlot/src/QwtHistogram.cpp b/MantidPlot/src/QwtHistogram.cpp
index f3e7373d1c5b501eb558df1d22acbb8649be46be..f5ab340d37a037424b6a8b8fb7504dccef8135df 100644
--- a/MantidPlot/src/QwtHistogram.cpp
+++ b/MantidPlot/src/QwtHistogram.cpp
@@ -2,7 +2,8 @@
     File                 : QwtHistogram.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Histogram class
 
@@ -33,286 +34,282 @@
 #include <gsl/gsl_vector.h>
 #include <gsl/gsl_histogram.h>
 
-QwtHistogram::QwtHistogram(Table *t, const QString& xColName, const QString& name, int startRow, int endRow)
-  : QwtBarCurve(QwtBarCurve::Vertical, t, xColName, name, startRow, endRow),
-    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)
-{
-    d_matrix = 0;
-    setType(Graph::Histogram);
-    setStyle(QwtPlotCurve::UserCurve);
+QwtHistogram::QwtHistogram(Table *t, const QString &xColName,
+                           const QString &name, int startRow, int endRow)
+    : QwtBarCurve(QwtBarCurve::Vertical, t, xColName, name, startRow, endRow),
+      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) {
+  d_matrix = 0;
+  setType(Graph::Histogram);
+  setStyle(QwtPlotCurve::UserCurve);
 }
 
 QwtHistogram::QwtHistogram(Matrix *m)
-  : QwtBarCurve(QwtBarCurve::Vertical, NULL, "matrix", (m != NULL ? m->objectName() : QString() ), 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){
-        d_autoBin = true;
-        d_matrix = m;
-        setType(Graph::Histogram);
-        setStyle(QwtPlotCurve::UserCurve);
-    }
+    : QwtBarCurve(QwtBarCurve::Vertical, NULL, "matrix",
+                  (m != NULL ? m->objectName() : QString()), 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) {
+    d_autoBin = true;
+    d_matrix = m;
+    setType(Graph::Histogram);
+    setStyle(QwtPlotCurve::UserCurve);
+  }
 }
 
-void QwtHistogram::copy(const QwtHistogram *h)
-{
-	QwtBarCurve::copy(h);
+void QwtHistogram::copy(const QwtHistogram *h) {
+  QwtBarCurve::copy(h);
 
-	d_autoBin = h->d_autoBin;
-	d_bin_size = h->d_bin_size;
-	d_begin = h->d_begin;
-	d_end = h->d_end;
+  d_autoBin = h->d_autoBin;
+  d_bin_size = h->d_bin_size;
+  d_begin = h->d_begin;
+  d_end = h->d_end;
 }
 
-void QwtHistogram::draw(QPainter *painter,
-		const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
-	if ( !painter || dataSize() <= 0 )
-		return;
+void QwtHistogram::draw(QPainter *painter, const QwtScaleMap &xMap,
+                        const QwtScaleMap &yMap, int from, int to) const {
+  if (!painter || dataSize() <= 0)
+    return;
 
-	if (to < 0)
-		to = dataSize() - 1;
+  if (to < 0)
+    to = dataSize() - 1;
 
-	painter->save();
-	painter->setPen(QwtPlotCurve::pen());
-	painter->setBrush(QwtPlotCurve::brush());
+  painter->save();
+  painter->setPen(QwtPlotCurve::pen());
+  painter->setBrush(QwtPlotCurve::brush());
 
-	const int ref= yMap.transform(baseline());
-	const int dx=abs(xMap.transform(x(from+1)) - xMap.transform(x(from)));
-	const int bar_width=static_cast<int>(dx*(1-gap()*0.01));
-	const int half_width = static_cast<int>(0.5*(dx-bar_width));
-	const int xOffset = static_cast<int>(0.01*offset()*bar_width);
+  const int ref = yMap.transform(baseline());
+  const int dx = abs(xMap.transform(x(from + 1)) - xMap.transform(x(from)));
+  const int bar_width = static_cast<int>(dx * (1 - gap() * 0.01));
+  const int half_width = static_cast<int>(0.5 * (dx - bar_width));
+  const int xOffset = static_cast<int>(0.01 * offset() * bar_width);
 
-	for (int i=from; i<=to; i++){
-		const int px1 = xMap.transform(x(i));
-		const int py1 = yMap.transform(y(i));
-		painter->drawRect(px1+half_width+xOffset,py1,bar_width+1,(ref-py1+1));
-	}
+  for (int i = from; i <= to; i++) {
+    const int px1 = xMap.transform(x(i));
+    const int py1 = yMap.transform(y(i));
+    painter->drawRect(px1 + half_width + xOffset, py1, bar_width + 1,
+                      (ref - py1 + 1));
+  }
 
-	painter->restore();
+  painter->restore();
 }
 
-QwtDoubleRect QwtHistogram::boundingRect() const
-{
-	QwtDoubleRect rect = QwtPlotCurve::boundingRect();
-	rect.setLeft(rect.left()-x(1));
-	rect.setRight(rect.right()+x(dataSize()-1));
-	rect.setTop(0);
-	rect.setBottom(1.2*rect.bottom());
-	return rect;
+QwtDoubleRect QwtHistogram::boundingRect() const {
+  QwtDoubleRect rect = QwtPlotCurve::boundingRect();
+  rect.setLeft(rect.left() - x(1));
+  rect.setRight(rect.right() + x(dataSize() - 1));
+  rect.setTop(0);
+  rect.setBottom(1.2 * rect.bottom());
+  return rect;
 }
 
-void QwtHistogram::setBinning(bool autoBin, double size, double begin, double end)
-{
-	d_autoBin = autoBin;
-	d_bin_size = size;
-	d_begin = begin;
-	d_end = end;
+void QwtHistogram::setBinning(bool autoBin, double size, double begin,
+                              double end) {
+  d_autoBin = autoBin;
+  d_bin_size = size;
+  d_begin = begin;
+  d_end = end;
 }
 
-void QwtHistogram::loadData()
-{
-    if (d_matrix){
-        loadDataFromMatrix();
-        return;
+void QwtHistogram::loadData() {
+  if (d_matrix) {
+    loadDataFromMatrix();
+    return;
+  }
+
+  int r = abs(d_end_row - d_start_row) + 1;
+  QVarLengthArray<double> Y(r);
+
+  int ycol = d_table->colIndex(title().text());
+  int size = 0;
+  for (int i = 0; i < r; i++) {
+    QString yval = d_table->text(i, ycol);
+    if (!yval.isEmpty()) {
+      bool valid_data = true;
+      Y[size] = plot()->locale().toDouble(yval, &valid_data);
+      if (valid_data)
+        size++;
     }
-
-    int r = abs(d_end_row - d_start_row) + 1;
-	QVarLengthArray<double> Y(r);
-
-    int ycol = d_table->colIndex(title().text());
-	int size = 0;
-	for (int i = 0; i<r; i++ ){
-		QString yval = d_table->text(i, ycol);
-		if (!yval.isEmpty()){
-		    bool valid_data = true;
-            Y[size] = plot()->locale().toDouble(yval, &valid_data);
-            if (valid_data)
-                size++;
-		}
-	}
-	if(size < 2 || (size==2 && Y[0] == Y[1])){//non valid histogram
-		double X[2];
-		Y.resize(2);
-		for (int i = 0; i<2; i++ ){
-			Y[i] = 0;
-			X[i] = 0;
-		}
-		setData(X, Y.data(), 2);
-		return;
-	}
-
-	int n;
-	gsl_histogram *h;
-	if (d_autoBin){
-		n = 10;
-		h = gsl_histogram_alloc (n);
-		if (!h)
-			return;
-
-		gsl_vector *v = gsl_vector_alloc (size);
-		for (int i = 0; i<size; i++ )
-			gsl_vector_set (v, i, Y[i]);
-
-		double min, max;
-		gsl_vector_minmax (v, &min, &max);
-		gsl_vector_free (v);
-
-		d_begin = floor(min);
-		d_end = ceil(max);
-		d_bin_size = (d_end - d_begin)/(double)n;
-
-		gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max));
-	} else {
-		n = static_cast<int>((d_end - d_begin)/d_bin_size + 1);
-		h = gsl_histogram_alloc (n);
-		if (!h)
-			return;
-
-		double *range = new double[n+2];
-		for (int i = 0; i<= n+1; i++ )
-			range[i] = d_begin + i*d_bin_size;
-
-		gsl_histogram_set_ranges (h, range, n+1);
-		delete[] range;
-	}
-
-	for (int i = 0; i<size; i++ )
-		gsl_histogram_increment (h, Y[i]);
-
-	QVarLengthArray<double> X(n); //stores ranges (x) and bins (y)
-	Y.resize(n);
-	for (int i = 0; i<n; i++ ){
-		Y[i] = gsl_histogram_get (h, i);
-		double lower, upper;
-		gsl_histogram_get_range (h, i, &lower, &upper);
-		X[i] = lower;
-	}
-	setData(X.data(), Y.data(), n);
-
-	d_mean = gsl_histogram_mean(h);
-	d_standard_deviation = gsl_histogram_sigma(h);
-	d_min = gsl_histogram_min_val(h);
-	d_max = gsl_histogram_max_val(h);
-
-	gsl_histogram_free (h);
+  }
+  if (size < 2 || (size == 2 && Y[0] == Y[1])) { // non valid histogram
+    double X[2];
+    Y.resize(2);
+    for (int i = 0; i < 2; i++) {
+      Y[i] = 0;
+      X[i] = 0;
+    }
+    setData(X, Y.data(), 2);
+    return;
+  }
+
+  int n;
+  gsl_histogram *h;
+  if (d_autoBin) {
+    n = 10;
+    h = gsl_histogram_alloc(n);
+    if (!h)
+      return;
+
+    gsl_vector *v = gsl_vector_alloc(size);
+    for (int i = 0; i < size; i++)
+      gsl_vector_set(v, i, Y[i]);
+
+    double min, max;
+    gsl_vector_minmax(v, &min, &max);
+    gsl_vector_free(v);
+
+    d_begin = floor(min);
+    d_end = ceil(max);
+    d_bin_size = (d_end - d_begin) / (double)n;
+
+    gsl_histogram_set_ranges_uniform(h, floor(min), ceil(max));
+  } else {
+    n = static_cast<int>((d_end - d_begin) / d_bin_size + 1);
+    h = gsl_histogram_alloc(n);
+    if (!h)
+      return;
+
+    double *range = new double[n + 2];
+    for (int i = 0; i <= n + 1; i++)
+      range[i] = d_begin + i * d_bin_size;
+
+    gsl_histogram_set_ranges(h, range, n + 1);
+    delete[] range;
+  }
+
+  for (int i = 0; i < size; i++)
+    gsl_histogram_increment(h, Y[i]);
+
+  QVarLengthArray<double> X(n); // stores ranges (x) and bins (y)
+  Y.resize(n);
+  for (int i = 0; i < n; i++) {
+    Y[i] = gsl_histogram_get(h, i);
+    double lower, upper;
+    gsl_histogram_get_range(h, i, &lower, &upper);
+    X[i] = lower;
+  }
+  setData(X.data(), Y.data(), n);
+
+  d_mean = gsl_histogram_mean(h);
+  d_standard_deviation = gsl_histogram_sigma(h);
+  d_min = gsl_histogram_min_val(h);
+  d_max = gsl_histogram_max_val(h);
+
+  gsl_histogram_free(h);
 }
 
-void QwtHistogram::loadDataFromMatrix()
-{
-    if (!d_matrix)
-        return;
-
-   int size = d_matrix->numRows()*d_matrix->numCols();
-   const double *data = d_matrix->matrixModel()->dataVector();
-
-	int n;
-	gsl_histogram *h;
-	if (d_autoBin){
-		double min, max;
-		d_matrix->range(&min, &max);
-		d_begin = floor(min);
-		d_end = ceil(max);
-		d_bin_size = 1.0;
-
-		n = static_cast<int>(floor((d_end - d_begin)/d_bin_size));
-		if (!n)
-            return;
-
-		h = gsl_histogram_alloc (n);
-		if (!h)
-			return;
-		gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max));
-	} else {
-		n = static_cast<int>((d_end - d_begin)/d_bin_size + 1);
-		if (!n)
-            return;
-
-		h = gsl_histogram_alloc (n);
-		if (!h)
-			return;
-
-		double *range = new double[n+2];
-		for (int i = 0; i<= n+1; i++ )
-			range[i] = d_begin + i*d_bin_size;
-
-		gsl_histogram_set_ranges (h, range, n+1);
-		delete[] range;
-	}
-
-	for (int i = 0; i<size; i++ )
-		gsl_histogram_increment (h, data[i]);
-
-	QVarLengthArray<double> X(n), Y(n); //stores ranges (x) and bins (y)
-	for (int i = 0; i<n; i++ ){
-		Y[i] = gsl_histogram_get (h, i);
-		double lower, upper;
-		gsl_histogram_get_range (h, i, &lower, &upper);
-		X[i] = lower;
-	}
-	setData(X.data(), Y.data(), n);
-
-	d_mean = gsl_histogram_mean(h);
-	d_standard_deviation = gsl_histogram_sigma(h);
-	d_min = gsl_histogram_min_val(h);
-	d_max = gsl_histogram_max_val(h);
-
-	gsl_histogram_free (h);
+void QwtHistogram::loadDataFromMatrix() {
+  if (!d_matrix)
+    return;
+
+  int size = d_matrix->numRows() * d_matrix->numCols();
+  const double *data = d_matrix->matrixModel()->dataVector();
+
+  int n;
+  gsl_histogram *h;
+  if (d_autoBin) {
+    double min, max;
+    d_matrix->range(&min, &max);
+    d_begin = floor(min);
+    d_end = ceil(max);
+    d_bin_size = 1.0;
+
+    n = static_cast<int>(floor((d_end - d_begin) / d_bin_size));
+    if (!n)
+      return;
+
+    h = gsl_histogram_alloc(n);
+    if (!h)
+      return;
+    gsl_histogram_set_ranges_uniform(h, floor(min), ceil(max));
+  } else {
+    n = static_cast<int>((d_end - d_begin) / d_bin_size + 1);
+    if (!n)
+      return;
+
+    h = gsl_histogram_alloc(n);
+    if (!h)
+      return;
+
+    double *range = new double[n + 2];
+    for (int i = 0; i <= n + 1; i++)
+      range[i] = d_begin + i * d_bin_size;
+
+    gsl_histogram_set_ranges(h, range, n + 1);
+    delete[] range;
+  }
+
+  for (int i = 0; i < size; i++)
+    gsl_histogram_increment(h, data[i]);
+
+  QVarLengthArray<double> X(n), Y(n); // stores ranges (x) and bins (y)
+  for (int i = 0; i < n; i++) {
+    Y[i] = gsl_histogram_get(h, i);
+    double lower, upper;
+    gsl_histogram_get_range(h, i, &lower, &upper);
+    X[i] = lower;
+  }
+  setData(X.data(), Y.data(), n);
+
+  d_mean = gsl_histogram_mean(h);
+  d_standard_deviation = gsl_histogram_sigma(h);
+  d_min = gsl_histogram_min_val(h);
+  d_max = gsl_histogram_max_val(h);
+
+  gsl_histogram_free(h);
 }
 
-void QwtHistogram::initData(double *Y, int size)
-{
-	if(size<2 || (size == 2 && Y[0] == Y[1]))
-	{//non valid histogram data
-		double x[2], y[2];
-		for (int i = 0; i<2; i++ ){
-			y[i] = 0;
-			x[i] = 0;
-		}
-		setData(x, y, 2);
-		return;
-	}
-
-	int n = 10;//default value
-	QVarLengthArray<double> x(n), y(n);//double x[n], y[n]; //store ranges (x) and bins (y)
-	gsl_histogram * h = gsl_histogram_alloc (n);
-	if (!h)
-		return;
-
-	gsl_vector *v;
-	v = gsl_vector_alloc (size);
-	for (int i = 0; i<size; i++ )
-		gsl_vector_set (v, i, Y[i]);
-
-	double min, max;
-	gsl_vector_minmax (v, &min, &max);
-	gsl_vector_free (v);
-
-	d_begin = floor(min);
-	d_end = ceil(max);
-
-	gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max));
-
-	for (int i = 0; i<size; i++ )
-		gsl_histogram_increment (h, Y[i]);
-
-	for (int i = 0; i<n; i++ ){
-		y[i] = gsl_histogram_get (h, i);
-		double lower, upper;
-		gsl_histogram_get_range (h, i, &lower, &upper);
-		x[i] = lower;
-	}
-
-	setData(x.data(), y.data(), n);//setData(x, y, n);
-
-	d_bin_size = (d_end - d_begin)/(double)n;
-	d_autoBin = true;
-    d_mean = gsl_histogram_mean(h);
-	d_standard_deviation = gsl_histogram_sigma(h);
-	d_min = gsl_histogram_min_val(h);
-	d_max = gsl_histogram_max_val(h);
-
-	gsl_histogram_free (h);
+void QwtHistogram::initData(double *Y, int size) {
+  if (size < 2 || (size == 2 && Y[0] == Y[1])) { // non valid histogram data
+    double x[2], y[2];
+    for (int i = 0; i < 2; i++) {
+      y[i] = 0;
+      x[i] = 0;
+    }
+    setData(x, y, 2);
+    return;
+  }
+
+  int n = 10; // default value
+  QVarLengthArray<double> x(n),
+      y(n); // double x[n], y[n]; //store ranges (x) and bins (y)
+  gsl_histogram *h = gsl_histogram_alloc(n);
+  if (!h)
+    return;
+
+  gsl_vector *v;
+  v = gsl_vector_alloc(size);
+  for (int i = 0; i < size; i++)
+    gsl_vector_set(v, i, Y[i]);
+
+  double min, max;
+  gsl_vector_minmax(v, &min, &max);
+  gsl_vector_free(v);
+
+  d_begin = floor(min);
+  d_end = ceil(max);
+
+  gsl_histogram_set_ranges_uniform(h, floor(min), ceil(max));
+
+  for (int i = 0; i < size; i++)
+    gsl_histogram_increment(h, Y[i]);
+
+  for (int i = 0; i < n; i++) {
+    y[i] = gsl_histogram_get(h, i);
+    double lower, upper;
+    gsl_histogram_get_range(h, i, &lower, &upper);
+    x[i] = lower;
+  }
+
+  setData(x.data(), y.data(), n); // setData(x, y, n);
+
+  d_bin_size = (d_end - d_begin) / (double)n;
+  d_autoBin = true;
+  d_mean = gsl_histogram_mean(h);
+  d_standard_deviation = gsl_histogram_sigma(h);
+  d_min = gsl_histogram_min_val(h);
+  d_max = gsl_histogram_max_val(h);
+
+  gsl_histogram_free(h);
 }
diff --git a/MantidPlot/src/QwtHistogram.h b/MantidPlot/src/QwtHistogram.h
index 2558bed08f487d76184fabf01abf5cc9a3760e2c..89f9220d7ee7a69996606285d25210f12bb36e7c 100644
--- a/MantidPlot/src/QwtHistogram.h
+++ b/MantidPlot/src/QwtHistogram.h
@@ -2,7 +2,8 @@
     File                 : QwtHistogram.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Histogram class
 
@@ -31,48 +32,49 @@
 class Matrix;
 
 //! Histogram class
-class QwtHistogram: public QwtBarCurve
-{
+class QwtHistogram : public QwtBarCurve {
 public:
-	QwtHistogram(Table *t, const QString& xColName, const QString& name, int startRow, int endRow);
-        explicit QwtHistogram(Matrix *m);
+  QwtHistogram(Table *t, const QString &xColName, const QString &name,
+               int startRow, int endRow);
+  explicit QwtHistogram(Matrix *m);
 
-        void copy(const QwtHistogram *h);
+  void copy(const QwtHistogram *h);
 
-        QwtDoubleRect boundingRect() const override;
+  QwtDoubleRect boundingRect() const override;
 
-        void setBinning(bool autoBin, double size, double begin, double end);
-	bool autoBinning(){return d_autoBin;};
-	double begin(){return d_begin;};
-	double end(){return d_end;};
-	double binSize(){return d_bin_size;};
+  void setBinning(bool autoBin, double size, double begin, double end);
+  bool autoBinning() { return d_autoBin; };
+  double begin() { return d_begin; };
+  double end() { return d_end; };
+  double binSize() { return d_bin_size; };
 
-        void loadData() override;
-    void initData(double* Y, int size);
+  void loadData() override;
+  void initData(double *Y, int size);
 
-    double mean(){return d_mean;};
-    double standardDeviation(){return d_standard_deviation;};
-    double minimum(){return d_min;};
-    double maximum(){return d_max;};
+  double mean() { return d_mean; };
+  double standardDeviation() { return d_standard_deviation; };
+  double minimum() { return d_min; };
+  double maximum() { return d_max; };
 
-	Matrix* matrix(){return d_matrix;};
+  Matrix *matrix() { return d_matrix; };
 
 private:
   void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             int from, int to) const override;
-        // Implement overloaded virtual method to just pass up to the base class to avoid
-	// an Intel compiler warning
+  // Implement overloaded virtual method to just pass up to the base class to
+  // avoid
+  // an Intel compiler warning
   void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &rect) const override {
-          DataCurve::draw(p,xMap,yMap,rect);
-	}
+    DataCurve::draw(p, xMap, yMap, rect);
+  }
 
-    void loadDataFromMatrix();
-    Matrix *d_matrix;
+  void loadDataFromMatrix();
+  Matrix *d_matrix;
 
-	bool d_autoBin;
-	double d_bin_size, d_begin, d_end;
+  bool d_autoBin;
+  double d_bin_size, d_begin, d_end;
 
-    //! Variables storing statistical information
-	double d_mean, d_standard_deviation, d_min, d_max;
+  //! Variables storing statistical information
+  double d_mean, d_standard_deviation, d_min, d_max;
 };
diff --git a/MantidPlot/src/QwtPieCurve.cpp b/MantidPlot/src/QwtPieCurve.cpp
index 8d9d826642c327fcbd3a7f91d89d147e57f389d8..994395a8cd4144715da74262af07c7e353f423d6 100644
--- a/MantidPlot/src/QwtPieCurve.cpp
+++ b/MantidPlot/src/QwtPieCurve.cpp
@@ -34,22 +34,13 @@
 #include <QMessageBox>
 #include <QApplication>
 
-QwtPieCurve::QwtPieCurve(Table *t, const QString& name, int startRow, int endRow):
-DataCurve(t, QString(), name, startRow, endRow),
-d_pie_ray(50),
-d_first_color(0),
-d_start_azimuth(270),
-d_view_angle(33),
-d_thickness(33),
-d_horizontal_offset(0),
-d_edge_dist(25),
-d_counter_clockwise(false),
-d_auto_labeling(true),
-d_values(false),
-d_percentages(true),
-d_categories(false),
-d_fixed_labels_pos(true)
-{
+QwtPieCurve::QwtPieCurve(Table *t, const QString &name, int startRow,
+                         int endRow)
+    : DataCurve(t, QString(), name, startRow, endRow), d_pie_ray(50),
+      d_first_color(0), d_start_azimuth(270), d_view_angle(33), d_thickness(33),
+      d_horizontal_offset(0), d_edge_dist(25), d_counter_clockwise(false),
+      d_auto_labeling(true), d_values(false), d_percentages(true),
+      d_categories(false), d_fixed_labels_pos(true) {
   setPen(QPen(QColor(Qt::black), 1, Qt::SolidLine));
   setBrush(QBrush(Qt::SolidPattern));
   setStyle(QwtPlotCurve::UserCurve);
@@ -57,8 +48,7 @@ d_fixed_labels_pos(true)
   d_table_rows = QVarLengthArray<int>(0);
 }
 
-void QwtPieCurve::clone(QwtPieCurve* c)
-{
+void QwtPieCurve::clone(QwtPieCurve *c) {
   if (!c)
     return;
 
@@ -79,10 +69,10 @@ void QwtPieCurve::clone(QwtPieCurve* c)
   d_table_rows = c->d_table_rows;
 }
 
-void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
+void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                       const QwtScaleMap &yMap, int from, int to) const {
   int size = dataSize();
-  if ( !painter ||  size <= 0 )
+  if (!painter || size <= 0)
     return;
 
   if (to < 0)
@@ -94,21 +84,23 @@ void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScal
     drawDisk(painter, xMap, yMap);
 }
 
-void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const
-{
+void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap,
+                           const QwtScaleMap &yMap) const {
   const double x_width = fabs(xMap.p1() - xMap.p2());
-  const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width;
-  const double y_center = (yMap.p1() + yMap.p2())*0.5;
-  const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2()));
-  const double view_angle_rad = d_view_angle*M_PI/180.0;
-  const double ray_y = ray_x*sin(view_angle_rad);
-  const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad);
+  const double x_center =
+      (xMap.p1() + xMap.p2()) * 0.5 + d_horizontal_offset * 0.01 * x_width;
+  const double y_center = (yMap.p1() + yMap.p2()) * 0.5;
+  const double ray_x =
+      d_pie_ray * 0.005 * qMin(x_width, fabs(yMap.p1() - yMap.p2()));
+  const double view_angle_rad = d_view_angle * M_PI / 180.0;
+  const double ray_y = ray_x * sin(view_angle_rad);
+  const double thick = 0.01 * d_thickness * ray_x * cos(view_angle_rad);
 
   QRectF pieRect;
   pieRect.setX(x_center - ray_x);
   pieRect.setY(y_center - ray_y);
-  pieRect.setWidth(2*ray_x);
-  pieRect.setHeight(2*ray_y);
+  pieRect.setWidth(2 * ray_x);
+  pieRect.setHeight(2 * ray_y);
 
   QRectF pieRect2 = pieRect;
   pieRect2.translate(0, thick);
@@ -129,16 +121,17 @@ void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const Qwt
 
   painter->drawEllipse(pieRect);
 
-  if (d_texts_list.size() > 0){
-    PieLabel* l = d_texts_list[0];
-    if (l){
+  if (d_texts_list.size() > 0) {
+    PieLabel *l = d_texts_list[0];
+    if (l) {
       QString s;
-      if (d_auto_labeling){
+      if (d_auto_labeling) {
         if (d_categories)
           s += QString::number(d_table_rows[0]) + "\n";
 
         if (d_values && d_percentages)
-          s += (static_cast<Plot *>(plot()))->locale().toString(y(0), 'g', 4) + " (100%)";
+          s += (static_cast<Plot *>(plot()))->locale().toString(y(0), 'g', 4) +
+               " (100%)";
         else if (d_values)
           s += (static_cast<Plot *>(plot()))->locale().toString(y(0), 'g', 4);
         else if (d_percentages)
@@ -149,20 +142,20 @@ void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const Qwt
       } else
         l->setText(l->customText());
 
-      if (d_fixed_labels_pos){
+      if (d_fixed_labels_pos) {
         double a_deg = d_start_azimuth + 180.0;
         if (a_deg > 360)
           a_deg -= 360;
-        double a_rad = a_deg*M_PI/180.0;
-        double rx = ray_x*(1 + 0.01*d_edge_dist);
-        const double x = x_center + rx*cos(a_rad);
-        double ry = ray_y*(1 + 0.01*d_edge_dist);
-        double y = y_center + ry*sin(a_rad);
+        double a_rad = a_deg * M_PI / 180.0;
+        double rx = ray_x * (1 + 0.01 * d_edge_dist);
+        const double x = x_center + rx * cos(a_rad);
+        double ry = ray_y * (1 + 0.01 * d_edge_dist);
+        double y = y_center + ry * sin(a_rad);
         if (a_deg > 0 && a_deg < 180)
           y += thick;
 
-        double dx = xMap.invTransform(x - l->width()/2);
-        double dy = yMap.invTransform(y - l->height()/2);
+        double dx = xMap.invTransform(x - l->width() / 2);
+        double dy = yMap.invTransform(y - l->height() / 2);
         l->setOriginCoord(dx, dy);
       }
     }
@@ -170,21 +163,23 @@ void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const Qwt
   painter->restore();
 }
 
-void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
+void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap,
+                             const QwtScaleMap &yMap, int from, int to) const {
   const double x_width = fabs(xMap.p1() - xMap.p2());
-  const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width;
-  const double y_center = (yMap.p1() + yMap.p2())*0.5;
-  const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2()));
-  const double view_angle_rad = d_view_angle*M_PI/180.0;
-  const double ray_y = ray_x*sin(view_angle_rad);
-  const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad);
+  const double x_center =
+      (xMap.p1() + xMap.p2()) * 0.5 + d_horizontal_offset * 0.01 * x_width;
+  const double y_center = (yMap.p1() + yMap.p2()) * 0.5;
+  const double ray_x =
+      d_pie_ray * 0.005 * qMin(x_width, fabs(yMap.p1() - yMap.p2()));
+  const double view_angle_rad = d_view_angle * M_PI / 180.0;
+  const double ray_y = ray_x * sin(view_angle_rad);
+  const double thick = 0.01 * d_thickness * ray_x * cos(view_angle_rad);
 
   QRectF pieRect;
   pieRect.setX(x_center - ray_x);
   pieRect.setY(y_center - ray_y);
-  pieRect.setWidth(2*ray_x);
-  pieRect.setHeight(2*ray_y);
+  pieRect.setWidth(2 * ray_x);
+  pieRect.setHeight(2 * ray_y);
 
   QRectF pieRect2 = pieRect;
   pieRect2.translate(0, thick);
@@ -199,8 +194,8 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
   double *start_angle = new double[size];
   double *end_angle = new double[size];
   double aux_angle = d_start_azimuth;
-  for (int i = from; i <= to; i++){
-    double a = -sign*y(i)/sum*360.0;
+  for (int i = from; i <= to; i++) {
+    double a = -sign * y(i) / sum * 360.0;
     start_angle[i] = aux_angle;
 
     double end = aux_angle + a;
@@ -213,52 +208,54 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
     aux_angle = end;
   }
 
-  int angle = (int)(5760 * d_start_azimuth/360.0);
+  int angle = (int)(5760 * d_start_azimuth / 360.0);
   if (d_counter_clockwise)
-    angle = (int)(5760 * (1 - d_start_azimuth/360.0));
+    angle = (int)(5760 * (1 - d_start_azimuth / 360.0));
 
   painter->save();
 
   QLocale locale = (static_cast<Plot *>(plot()))->locale();
-  for (int i = from; i <= to; i++){
+  for (int i = from; i <= to; i++) {
     const double yi = y(i);
-    const double q = yi/sum;
-    const int value = (int)(q*5760);
+    const double q = yi / sum;
+    const int value = (int)(q * 5760);
 
     painter->setPen(QwtPlotCurve::pen());
     painter->setBrush(QBrush(color(i), QwtPlotCurve::brush().style()));
 
-    double deg = q*360;
+    double deg = q * 360;
     double start_3D_view_angle = start_angle[i];
     double end_3D_view_angle = end_angle[i];
-    if (d_counter_clockwise){
+    if (d_counter_clockwise) {
       start_3D_view_angle = end_angle[i];
       end_3D_view_angle = start_angle[i];
     }
 
     bool draw3D = false;
-    if (deg <= 180 && start_3D_view_angle >= 0 && start_3D_view_angle < 180){
-      if ((end_3D_view_angle > 180 && end_3D_view_angle > start_3D_view_angle)){
+    if (deg <= 180 && start_3D_view_angle >= 0 && start_3D_view_angle < 180) {
+      if ((end_3D_view_angle > 180 &&
+           end_3D_view_angle > start_3D_view_angle)) {
         deg = 180 - start_3D_view_angle;
         end_3D_view_angle = 180.0;
       }
       draw3D = true;
-    } else if (start_3D_view_angle >= 180 && end_3D_view_angle < start_3D_view_angle){
+    } else if (start_3D_view_angle >= 180 &&
+               end_3D_view_angle < start_3D_view_angle) {
       if (end_3D_view_angle > 180)
         end_3D_view_angle = 180;
       deg = end_3D_view_angle;
       start_3D_view_angle = 0;
       draw3D = true;
-    } else if (deg > 180 && start_3D_view_angle >= 180){
+    } else if (deg > 180 && start_3D_view_angle >= 180) {
       deg = 180;
       end_3D_view_angle = 180;
       start_3D_view_angle = 0;
       draw3D = true;
     }
 
-    if (draw3D){
-      double rad = start_3D_view_angle/180.0*M_PI;
-      QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad));
+    if (draw3D) {
+      double rad = start_3D_view_angle / 180.0 * M_PI;
+      QPointF start(x_center + ray_x * cos(rad), y_center + ray_y * sin(rad));
       QPainterPath path(start);
       path.lineTo(start.x(), start.y() + thick);
       path.arcTo(pieRect2, -start_3D_view_angle, -deg);
@@ -267,12 +264,12 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
       path.arcTo(pieRect, -end_3D_view_angle, deg);
       painter->drawPath(path);
     } else {
-      if (start_3D_view_angle >= 0 && start_3D_view_angle < 180){
+      if (start_3D_view_angle >= 0 && start_3D_view_angle < 180) {
         if (end_3D_view_angle > 180)
           end_3D_view_angle = 0;
 
-        double rad = start_3D_view_angle/180.0*M_PI;
-        QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad));
+        double rad = start_3D_view_angle / 180.0 * M_PI;
+        QPointF start(x_center + ray_x * cos(rad), y_center + ray_y * sin(rad));
         QPainterPath path(start);
         path.lineTo(start.x(), start.y() + thick);
 
@@ -294,62 +291,61 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
       }
     }
 
-    painter->drawPie(pieRect, sign*angle, sign*value);
+    painter->drawPie(pieRect, sign * angle, sign * value);
     angle += value;
 
     if (i >= d_texts_list.size())
       continue;
 
-    PieLabel* l = d_texts_list[i];
-    if (l){
+    PieLabel *l = d_texts_list[i];
+    if (l) {
       QString s;
-      if (d_auto_labeling){
+      if (d_auto_labeling) {
         if (d_categories)
           s += QString::number(d_table_rows[i]) + "\n";
         if (d_values && d_percentages)
-          s += locale.toString(yi, 'g', 4) + " (" + locale.toString(q*100, 'g', 4) + "%)";
+          s += locale.toString(yi, 'g', 4) + " (" +
+               locale.toString(q * 100, 'g', 4) + "%)";
         else if (d_values)
           s += locale.toString(yi, 'g', 4);
         else if (d_percentages)
-          s += locale.toString(q*100, 'g', 4) + "%";
+          s += locale.toString(q * 100, 'g', 4) + "%";
         l->setText(s);
         if (l->isHidden())
           l->show();
       } else
         l->setText(l->customText());
 
-      if (d_fixed_labels_pos){
-        double a_deg = start_angle[i] - sign*q*180.0;
+      if (d_fixed_labels_pos) {
+        double a_deg = start_angle[i] - sign * q * 180.0;
         if (a_deg > 360)
           a_deg -= 360.0;
-        double a_rad = a_deg*M_PI/180.0;
+        double a_rad = a_deg * M_PI / 180.0;
 
-        double rx = ray_x*(1 + 0.01*d_edge_dist);
-        const double x = x_center + rx*cos(a_rad);
+        double rx = ray_x * (1 + 0.01 * d_edge_dist);
+        const double x = x_center + rx * cos(a_rad);
 
-        double ry = ray_y*(1 + 0.01*d_edge_dist);
-        double y = y_center + ry*sin(a_rad);
+        double ry = ray_y * (1 + 0.01 * d_edge_dist);
+        double y = y_center + ry * sin(a_rad);
         if (a_deg > 0 && a_deg < 180)
           y += thick;
 
-        double dx = xMap.invTransform(x - l->width()/2);
-        double dy = yMap.invTransform(y - l->height()/2);
+        double dx = xMap.invTransform(x - l->width() / 2);
+        double dy = yMap.invTransform(y - l->height() / 2);
         l->setOriginCoord(dx, dy);
       }
     }
   }
   painter->restore();
-  delete [] start_angle;
-  delete [] end_angle;
+  delete[] start_angle;
+  delete[] end_angle;
 }
 
-QColor QwtPieCurve::color(int i) const
-{
+QColor QwtPieCurve::color(int i) const {
   return ColorBox::color((d_first_color + i) % ColorBox::numPredefinedColors());
 }
 
-void QwtPieCurve::setBrushStyle(const Qt::BrushStyle& style)
-{
+void QwtPieCurve::setBrushStyle(const Qt::BrushStyle &style) {
   QBrush br = QwtPlotCurve::brush();
   if (br.style() == style)
     return;
@@ -358,15 +354,15 @@ void QwtPieCurve::setBrushStyle(const Qt::BrushStyle& style)
   setBrush(br);
 }
 
-void QwtPieCurve::loadData()
-{
-  // Limit number of slices to 1000 - seems plenty and avoids potential crash (#4470)
-  if ( abs(d_end_row-d_start_row) > 1000 )
-  {
+void QwtPieCurve::loadData() {
+  // Limit number of slices to 1000 - seems plenty and avoids potential crash
+  // (#4470)
+  if (abs(d_end_row - d_start_row) > 1000) {
     QString mess = QString("Pie charts are limited to 1000 segments!\n") +
-                   QString("You asked for ") + QString::number(abs(d_end_row-d_start_row)) +
+                   QString("You asked for ") +
+                   QString::number(abs(d_end_row - d_start_row)) +
                    QString(" - plotting only the first 1000.");
-    QMessageBox::warning(qApp->topLevelWidgets()[0],"Pie chart",mess);
+    QMessageBox::warning(qApp->topLevelWidgets()[0], "Pie chart", mess);
     d_end_row = d_start_row + 1000;
   }
 
@@ -377,12 +373,12 @@ void QwtPieCurve::loadData()
 
   int size = 0;
   int ycol = d_table->colIndex(title().text());
-  for (int i = d_start_row; i <= d_end_row; i++ ){
+  for (int i = d_start_row; i <= d_end_row; i++) {
     QString xval = d_table->text(i, ycol);
     bool valid_data = true;
-    if (!xval.isEmpty()){
+    if (!xval.isEmpty()) {
       X[size] = locale.toDouble(xval, &valid_data);
-      if (valid_data){
+      if (valid_data) {
         d_table_rows[size] = i + 1;
         size++;
       }
@@ -393,24 +389,24 @@ void QwtPieCurve::loadData()
   setData(X.data(), X.data(), size);
 
   int labels = d_texts_list.size();
-  //If there are no labels (initLabels() wasn't called yet) or if we have enough labels: do nothing!
-  if(d_texts_list.isEmpty() || labels == size)
+  // If there are no labels (initLabels() wasn't called yet) or if we have
+  // enough labels: do nothing!
+  if (d_texts_list.isEmpty() || labels == size)
     return;
 
-  //Else add new pie labels.
-  for (int i = labels; i < size; i++ ){
-    PieLabel* l = new PieLabel(d_plot, this);
+  // Else add new pie labels.
+  for (int i = labels; i < size; i++) {
+    PieLabel *l = new PieLabel(d_plot, this);
     d_texts_list << l;
     l->hide();
   }
 }
 
-void QwtPieCurve::addLabel(PieLabel *l, bool clone)
-{
+void QwtPieCurve::addLabel(PieLabel *l, bool clone) {
   if (!l)
     return;
 
-  if (clone){
+  if (clone) {
     PieLabel *newLabel = new PieLabel(static_cast<Plot *>(plot()), this);
     newLabel->clone(l);
     newLabel->setCustomText(l->customText());
@@ -421,8 +417,7 @@ void QwtPieCurve::addLabel(PieLabel *l, bool clone)
   }
 }
 
-void QwtPieCurve::removeLabel(PieLabel *l)
-{
+void QwtPieCurve::removeLabel(PieLabel *l) {
   if (!l)
     return;
 
@@ -439,8 +434,7 @@ void QwtPieCurve::removeLabel(PieLabel *l)
   d_texts_list.insert(index, newLabel);
 }
 
-void QwtPieCurve::initLabels()
-{
+void QwtPieCurve::initLabels() {
   int size = abs(d_end_row - d_start_row) + 1;
   int dataPoints = dataSize();
   double sum = 0.0;
@@ -449,35 +443,31 @@ void QwtPieCurve::initLabels()
 
   Plot *d_plot = static_cast<Plot *>(plot());
   QLocale locale = d_plot->locale();
-  for (int i = 0; i <size; i++ ){
-    PieLabel* l = new PieLabel(d_plot, this);
+  for (int i = 0; i < size; i++) {
+    PieLabel *l = new PieLabel(d_plot, this);
     d_texts_list << l;
     if (i < dataPoints)
-      l->setText(locale.toString(y(i)/sum*100, 'g', 4) + "%");
+      l->setText(locale.toString(y(i) / sum * 100, 'g', 4) + "%");
     else
       l->hide();
   }
 }
 
-PieLabel::PieLabel(Plot *plot, QwtPieCurve *pie):LegendWidget(plot),
-    d_pie_curve(pie),
-    d_custom_text(QString::null)
-{
+PieLabel::PieLabel(Plot *plot, QwtPieCurve *pie)
+    : LegendWidget(plot), d_pie_curve(pie), d_custom_text(QString::null) {
   setBackgroundColor(QColor(255, 255, 255, 0));
   setFrameStyle(0);
 }
 
-QString PieLabel::customText()
-{
+QString PieLabel::customText() {
   if (d_custom_text.isEmpty())
     return text();
 
   return d_custom_text;
 }
 
-void PieLabel::closeEvent(QCloseEvent* e)
-{
-  if(d_pie_curve)
+void PieLabel::closeEvent(QCloseEvent *e) {
+  if (d_pie_curve)
     d_pie_curve->removeLabel(this);
   e->accept();
 }
diff --git a/MantidPlot/src/QwtPieCurve.h b/MantidPlot/src/QwtPieCurve.h
index cebe86193a5780e1ff3ea0ba5f978a3f3d1657d1..bd6293962045a67bb12806624514ba2626d99b89 100644
--- a/MantidPlot/src/QwtPieCurve.h
+++ b/MantidPlot/src/QwtPieCurve.h
@@ -33,57 +33,57 @@
 class PieLabel;
 
 //! Pie plot class
-class QwtPieCurve: public DataCurve
-{
+class QwtPieCurve : public DataCurve {
 public:
-  QwtPieCurve(Table *t, const QString& name, int startRow, int endRow);
+  QwtPieCurve(Table *t, const QString &name, int startRow, int endRow);
 
-  using DataCurve::clone; // Unhide base class method (avoids Intel compiler warning)
-  void clone(QwtPieCurve* c);
+  using DataCurve::clone; // Unhide base class method (avoids Intel compiler
+                          // warning)
+  void clone(QwtPieCurve *c);
 
-  double viewAngle(){return d_view_angle;};
-  void setViewAngle(double a){d_view_angle = a;};
+  double viewAngle() { return d_view_angle; };
+  void setViewAngle(double a) { d_view_angle = a; };
 
-  double thickness(){return d_thickness;};
-  void setThickness(double t){d_thickness = t;};
+  double thickness() { return d_thickness; };
+  void setThickness(double t) { d_thickness = t; };
 
-  double horizontalOffset(){return d_horizontal_offset;};
-  void setHorizontalOffset(double d){d_horizontal_offset = d;};
+  double horizontalOffset() { return d_horizontal_offset; };
+  void setHorizontalOffset(double d) { d_horizontal_offset = d; };
 
-  bool counterClockwise(){return d_counter_clockwise;};
-  void setCounterClockwise(bool on){d_counter_clockwise = on;};
+  bool counterClockwise() { return d_counter_clockwise; };
+  void setCounterClockwise(bool on) { d_counter_clockwise = on; };
 
-  double startAzimuth(){return d_start_azimuth;};
-  void setStartAzimuth(double angle){d_start_azimuth = angle;};
+  double startAzimuth() { return d_start_azimuth; };
+  void setStartAzimuth(double angle) { d_start_azimuth = angle; };
 
-  double labelsEdgeDistance(){return d_edge_dist;};
-  void setLabelsEdgeDistance(double d){d_edge_dist = d;};
+  double labelsEdgeDistance() { return d_edge_dist; };
+  void setLabelsEdgeDistance(double d) { d_edge_dist = d; };
 
-  bool labelsAutoFormat(){return d_auto_labeling;};
-  void setLabelsAutoFormat(bool on){d_auto_labeling = on;};
+  bool labelsAutoFormat() { return d_auto_labeling; };
+  void setLabelsAutoFormat(bool on) { d_auto_labeling = on; };
 
-  bool labelsValuesFormat(){return d_values;};
-  void setLabelValuesFormat(bool on){d_values = on;};
+  bool labelsValuesFormat() { return d_values; };
+  void setLabelValuesFormat(bool on) { d_values = on; };
 
-  bool labelsPercentagesFormat(){return d_percentages;};
-  void setLabelPercentagesFormat(bool on){d_percentages = on;};
+  bool labelsPercentagesFormat() { return d_percentages; };
+  void setLabelPercentagesFormat(bool on) { d_percentages = on; };
 
-  bool labelCategories(){return d_categories;};
-  void setLabelCategories(bool on){d_categories = on;};
+  bool labelCategories() { return d_categories; };
+  void setLabelCategories(bool on) { d_categories = on; };
 
-  bool fixedLabelsPosition(){return d_fixed_labels_pos;};
-  void setFixedLabelsPosition(bool on){d_fixed_labels_pos = on;};
+  bool fixedLabelsPosition() { return d_fixed_labels_pos; };
+  void setFixedLabelsPosition(bool on) { d_fixed_labels_pos = on; };
 
   QColor color(int i) const;
 
-  int radius(){return d_pie_ray;};
-  void setRadius(int size){d_pie_ray = size;};
+  int radius() { return d_pie_ray; };
+  void setRadius(int size) { d_pie_ray = size; };
 
-  Qt::BrushStyle pattern(){return QwtPlotCurve::brush().style();};
-  void setBrushStyle(const Qt::BrushStyle& style);
+  Qt::BrushStyle pattern() { return QwtPlotCurve::brush().style(); };
+  void setBrushStyle(const Qt::BrushStyle &style);
 
-  void setFirstColor(int index){d_first_color = index;};
-  int firstColor(){return d_first_color;};
+  void setFirstColor(int index) { d_first_color = index; };
+  int firstColor() { return d_first_color; };
 
   void loadData() override;
   void initLabels();
@@ -91,15 +91,17 @@ public:
   void addLabel(PieLabel *l, bool clone = false);
   void removeLabel(PieLabel *l);
 
-  QList <PieLabel *> labelsList(){return d_texts_list;};
+  QList<PieLabel *> labelsList() { return d_texts_list; };
 
 private:
-  using DataCurve::draw; // Unhide base class method (avoids Intel compiler warning)
+  using DataCurve::draw; // Unhide base class method (avoids Intel compiler
+                         // warning)
   void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             int from, int to) const override;
   void drawSlices(QPainter *painter, const QwtScaleMap &xMap,
-      const QwtScaleMap &yMap, int from, int to) const;
-  void drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const;
+                  const QwtScaleMap &yMap, int from, int to) const;
+  void drawDisk(QPainter *painter, const QwtScaleMap &xMap,
+                const QwtScaleMap &yMap) const;
 
   int d_pie_ray;
   int d_first_color;
@@ -114,22 +116,22 @@ private:
   bool d_percentages;
   bool d_categories;
   bool d_fixed_labels_pos;
-  QList <PieLabel *> d_texts_list;
-  //! Stores table row indices to be displayed in PieLabels if d_categories is true.
+  QList<PieLabel *> d_texts_list;
+  //! Stores table row indices to be displayed in PieLabels if d_categories is
+  // true.
   QVarLengthArray<int> d_table_rows;
 };
 
-class PieLabel: public LegendWidget
-{
+class PieLabel : public LegendWidget {
   Q_OBJECT
 
 public:
   PieLabel(Plot *, QwtPieCurve *pie = 0);
 
   QString customText();
-  void setCustomText(const QString& s){d_custom_text = s;};
+  void setCustomText(const QString &s) { d_custom_text = s; };
 
-  void setPieCurve(QwtPieCurve *pie){d_pie_curve = pie;};
+  void setPieCurve(QwtPieCurve *pie) { d_pie_curve = pie; };
 
 private:
   void closeEvent(QCloseEvent *e) override;
diff --git a/MantidPlot/src/RangeSelectorTool.h b/MantidPlot/src/RangeSelectorTool.h
index ac4e0d823960434cc83f2bd72b41790786f36a2a..da7e879bebef1601ce99d84580754ab5fcfbacba 100644
--- a/MantidPlot/src/RangeSelectorTool.h
+++ b/MantidPlot/src/RangeSelectorTool.h
@@ -42,64 +42,72 @@ class QEvent;
  *
  * As detailed in the documentation of PlotToolInterface, this one is different
  * from most other plot tools in that other tools depend on it.
- * Thus, either RangeSelectorTool should cease to inherit from PlotToolInterface and be renamed to
- * RangeSelector, drawing a clear destinction to the other tools, or the notion of multiple tools being
- * active in parallel and possibly depending on each other should be generalized somehow.
+ * Thus, either RangeSelectorTool should cease to inherit from PlotToolInterface
+ *and be renamed to
+ * RangeSelector, drawing a clear destinction to the other tools, or the notion
+ *of multiple tools being
+ * active in parallel and possibly depending on each other should be generalized
+ *somehow.
  *
- * In any case, gathering the code specific to range selection in a seperate class makes Graph/CanvasPicker
+ * In any case, gathering the code specific to range selection in a seperate
+ *class makes Graph/CanvasPicker
  * more manageable; maybe something similar can be done for zooming.
  */
-class RangeSelectorTool : public QwtPlotPicker, public PlotToolInterface
-{
-	Q_OBJECT
-	public:
-		RangeSelectorTool(Graph *graph, const QObject *status_target=NULL, const char *status_slot="");
-                ~RangeSelectorTool() override;
-                double minXValue() const { return QMIN(d_active_marker.xValue(), d_inactive_marker.xValue()); }
-		double maxXValue() const { return QMAX(d_active_marker.xValue(), d_inactive_marker.xValue()); }
-		int dataSize() const { return qAbs(d_active_point - d_inactive_point); }
-                bool eventFilter(QObject *obj, QEvent *event) override;
-                bool keyEventFilter(QKeyEvent *ke);
+class RangeSelectorTool : public QwtPlotPicker, public PlotToolInterface {
+  Q_OBJECT
+public:
+  RangeSelectorTool(Graph *graph, const QObject *status_target = NULL,
+                    const char *status_slot = "");
+  ~RangeSelectorTool() override;
+  double minXValue() const {
+    return QMIN(d_active_marker.xValue(), d_inactive_marker.xValue());
+  }
+  double maxXValue() const {
+    return QMAX(d_active_marker.xValue(), d_inactive_marker.xValue());
+  }
+  int dataSize() const { return qAbs(d_active_point - d_inactive_point); }
+  bool eventFilter(QObject *obj, QEvent *event) override;
+  bool keyEventFilter(QKeyEvent *ke);
 
-		QwtPlotCurve *selectedCurve() const { return d_selected_curve; }
-		//! Caller is responsible for replot.
-		void setSelectedCurve(QwtPlotCurve *curve);
+  QwtPlotCurve *selectedCurve() const { return d_selected_curve; }
+  //! Caller is responsible for replot.
+  void setSelectedCurve(QwtPlotCurve *curve);
 
-        void copySelection();
-        void cutSelection();
-        void clearSelection();
-        void pasteSelection();
-        int rtti() const override {
-          return PlotToolInterface::Rtti_RangeSelector;
-        };
-                bool isVisible(){return d_visible;};
+  void copySelection();
+  void cutSelection();
+  void clearSelection();
+  void pasteSelection();
+  int rtti() const override { return PlotToolInterface::Rtti_RangeSelector; };
+  bool isVisible() { return d_visible; };
 
-	public slots:
-		virtual void pointSelected(const QPoint &point);
-        void setCurveRange();
-        void setEnabled(bool on = true) override;
+public slots:
+  virtual void pointSelected(const QPoint &point);
+  void setCurveRange();
+  void setEnabled(bool on = true) override;
 
-        signals:
-		/** Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
-		//! Emitted whenever the selected curve and/or range have changed.
-		void changed();
-	protected:
-          void append(const QPoint &point) override { pointSelected(point); }
-                void emitStatusText();
-		void switchActiveMarker();
-		//! Caller is responsible for replot.
-		void setActivePoint(int index);
-	private:
-		QwtPlotMarker d_active_marker, d_inactive_marker;
-		int d_active_point, d_inactive_point;
-		QwtPlotCurve *d_selected_curve;
-		bool d_enabled;
-		bool d_visible;
+signals:
+  /** Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
+  //! Emitted whenever the selected curve and/or range have changed.
+  void changed();
+
+protected:
+  void append(const QPoint &point) override { pointSelected(point); }
+  void emitStatusText();
+  void switchActiveMarker();
+  //! Caller is responsible for replot.
+  void setActivePoint(int index);
+
+private:
+  QwtPlotMarker d_active_marker, d_inactive_marker;
+  int d_active_point, d_inactive_point;
+  QwtPlotCurve *d_selected_curve;
+  bool d_enabled;
+  bool d_visible;
 };
 
 #endif // ifndef RANGE_SELECTOR_TOOL_H
-
diff --git a/MantidPlot/src/RenameWindowDialog.cpp b/MantidPlot/src/RenameWindowDialog.cpp
index 1ed0f2d08a3f54fd3c29b7c9db5bbd45b9cd0f18..0debb83e4b8a318e2aaa605e90367de8fa2551d2 100644
--- a/MantidPlot/src/RenameWindowDialog.cpp
+++ b/MantidPlot/src/RenameWindowDialog.cpp
@@ -2,7 +2,8 @@
     File                 : RenameWindowDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Rename window dialog
 
@@ -36,13 +37,12 @@
 #include <QMessageBox>
 #include <QButtonGroup>
 
-RenameWindowDialog::RenameWindowDialog(QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
+RenameWindowDialog::RenameWindowDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
   setWindowTitle(tr("MantidPlot - Rename Window"));
 
-  QGridLayout * leftLayout = new QGridLayout();
-  QVBoxLayout * rightLayout = new QVBoxLayout();
+  QGridLayout *leftLayout = new QGridLayout();
+  QVBoxLayout *rightLayout = new QVBoxLayout();
 
   groupBox1 = new QGroupBox(tr("Window Title"));
   groupBox1->setLayout(leftLayout);
@@ -68,85 +68,84 @@ RenameWindowDialog::RenameWindowDialog(QWidget* parent, Qt::WFlags fl )
   buttons->addButton(boxLabel);
   buttons->addButton(boxBoth);
 
-  buttonOk = new QPushButton(tr( "&OK" ));
-  buttonOk->setAutoDefault( true );
-  buttonOk->setDefault( true );
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
   rightLayout->addWidget(buttonOk);
 
-  buttonCancel = new QPushButton(tr( "&Cancel" ));
-  buttonCancel->setAutoDefault( true );
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  buttonCancel->setAutoDefault(true);
   rightLayout->addWidget(buttonCancel);
   rightLayout->addStretch();
 
-  QHBoxLayout * mainLayout = new QHBoxLayout(this);
+  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() ) );
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void RenameWindowDialog::setWidget(MdiSubWindow *w)
-{
-	window = w;
-	boxNameLine->setText(w->objectName());
-	boxLabelEdit->setText(w->windowLabel());
-	switch (w->captionPolicy())
-	{
-		case MdiSubWindow::Name:
-			boxName->setChecked(true);
-			break;
-
-		case MdiSubWindow::Label:
-			boxLabel->setChecked(true);
-			break;
-
-		case MdiSubWindow::Both:
-			boxBoth->setChecked(true);
-			break;
-	}
+void RenameWindowDialog::setWidget(MdiSubWindow *w) {
+  window = w;
+  boxNameLine->setText(w->objectName());
+  boxLabelEdit->setText(w->windowLabel());
+  switch (w->captionPolicy()) {
+  case MdiSubWindow::Name:
+    boxName->setChecked(true);
+    break;
+
+  case MdiSubWindow::Label:
+    boxLabel->setChecked(true);
+    break;
+
+  case MdiSubWindow::Both:
+    boxBoth->setChecked(true);
+    break;
+  }
 }
 
-MdiSubWindow::CaptionPolicy RenameWindowDialog::getCaptionPolicy()
-{
-	MdiSubWindow::CaptionPolicy policy = MdiSubWindow::Name;
-	if (boxLabel->isChecked())
-		policy = MdiSubWindow::Label;
-	else if (boxBoth->isChecked())
-		policy = MdiSubWindow::Both;
+MdiSubWindow::CaptionPolicy RenameWindowDialog::getCaptionPolicy() {
+  MdiSubWindow::CaptionPolicy policy = MdiSubWindow::Name;
+  if (boxLabel->isChecked())
+    policy = MdiSubWindow::Label;
+  else if (boxBoth->isChecked())
+    policy = MdiSubWindow::Both;
 
-	return policy;
+  return policy;
 }
 
-void RenameWindowDialog::accept()
-{
-	QString name = window->name();
-	QString text = boxNameLine->text().remove("=").remove(QRegExp("\\s"));
-	QString label = boxLabelEdit->toPlainText();
-
-	MdiSubWindow::CaptionPolicy policy = getCaptionPolicy();
-	if (text == name && label == window->windowLabel() && window->captionPolicy() == policy)
-		close();
-
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(parentWidget());
-	if (!app)
-		return;
-
-	if (text.contains("_")){
-  		QMessageBox::warning(this, tr("MantidPlot - Warning"),
-  	    tr("For internal consistency reasons the underscore character is replaced with a minus sign."));}
-
-  	if (text.replace("_", "-") != name){
-		if(!app->setWindowName(window, text))
-			return;
-	}
-
-	label.replace("\n"," ").replace("\t"," ");
-	window->setWindowLabel(label);
-	window->setCaptionPolicy(policy);
-	app->modifiedProject(window);
-	close();
+void RenameWindowDialog::accept() {
+  QString name = window->name();
+  QString text = boxNameLine->text().remove("=").remove(QRegExp("\\s"));
+  QString label = boxLabelEdit->toPlainText();
+
+  MdiSubWindow::CaptionPolicy policy = getCaptionPolicy();
+  if (text == name && label == window->windowLabel() &&
+      window->captionPolicy() == policy)
+    close();
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parentWidget());
+  if (!app)
+    return;
+
+  if (text.contains("_")) {
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),
+                         tr("For internal consistency reasons the underscore "
+                            "character is replaced with a minus sign."));
+  }
+
+  if (text.replace("_", "-") != name) {
+    if (!app->setWindowName(window, text))
+      return;
+  }
+
+  label.replace("\n", " ").replace("\t", " ");
+  window->setWindowLabel(label);
+  window->setCaptionPolicy(policy);
+  app->modifiedProject(window);
+  close();
 }
diff --git a/MantidPlot/src/RenameWindowDialog.h b/MantidPlot/src/RenameWindowDialog.h
index 4036ac89d3edc607389a2fafb8efff1aa1bf1905..5806f60b9abbfd3ded0a916aa63432247ed0b9e1 100644
--- a/MantidPlot/src/RenameWindowDialog.h
+++ b/MantidPlot/src/RenameWindowDialog.h
@@ -2,10 +2,11 @@
     File                 : RenameWindowDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Rename window dialog
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -43,33 +44,32 @@ class MdiSubWindow;
 class QButtonGroup;
 
 //! Rename window dialog
-class RenameWindowDialog : public QDialog
-{
-    Q_OBJECT
+class RenameWindowDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    RenameWindowDialog(QWidget* parent = 0, Qt::WFlags fl = 0 );
+  RenameWindowDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 private:
-    QPushButton * buttonOk;
-	QPushButton * buttonCancel;
-    QGroupBox * groupBox1;
-	QButtonGroup * buttons;
-	QRadioButton * boxName;
-	QRadioButton * boxLabel;
-	QRadioButton * boxBoth;
-	QLineEdit * boxNameLine;
-	QTextEdit * boxLabelEdit;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QGroupBox *groupBox1;
+  QButtonGroup *buttons;
+  QRadioButton *boxName;
+  QRadioButton *boxLabel;
+  QRadioButton *boxBoth;
+  QLineEdit *boxNameLine;
+  QTextEdit *boxLabelEdit;
 
 public slots:
-	void setWidget(MdiSubWindow *w);
-	MdiSubWindow::CaptionPolicy getCaptionPolicy();
-        void accept() override;
+  void setWidget(MdiSubWindow *w);
+  MdiSubWindow::CaptionPolicy getCaptionPolicy();
+  void accept() override;
 
 signals:
 
 private:
-	MdiSubWindow *window;
+  MdiSubWindow *window;
 };
 
 #endif // EXPORTDIALOG_H
diff --git a/MantidPlot/src/ScaleDetails.h b/MantidPlot/src/ScaleDetails.h
index fd56ece1c85c0b6d717acf940e14e41ced3a9f72..3aca6215ab635ccfa12cb94c21e390a440dffc24 100644
--- a/MantidPlot/src/ScaleDetails.h
+++ b/MantidPlot/src/ScaleDetails.h
@@ -1,10 +1,13 @@
 /**
-This class holds the widgets that hold the details for each axis so the contents are only filled once and switching axis only changes a pointer.
+This class holds the widgets that hold the details for each axis so the contents
+are only filled once and switching axis only changes a pointer.
 
-@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory from the University of Derby
+@author Keith Brown, Placement Student at ISIS Rutherford Appleton Laboratory
+from the University of Derby
 @date 15/09/2013
 
-Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -48,15 +51,15 @@ class Graph;
 class TextFormatButtons;
 class ColorButton;
 
-class ScaleDetails: public QWidget
-{
+class ScaleDetails : public QWidget {
   Q_OBJECT
-    //details for each axis in the Scale Tab
+  // details for each axis in the Scale Tab
 public:
-  ScaleDetails(ApplicationWindow* app, Graph* graph, int mappedaxis, QWidget *parent = 0); // populate and fill in with existing data
+  ScaleDetails(ApplicationWindow *app, Graph *graph, int mappedaxis,
+               QWidget *parent = 0); // populate and fill in with existing data
   ~ScaleDetails() override;
   void initWidgets();
-  bool modified(){return m_modified;}
+  bool modified() { return m_modified; }
   void apply();
   bool valid();
 
@@ -72,16 +75,19 @@ private slots:
 private:
   bool m_modified, m_initialised;
   int m_mappedaxis;
-  ApplicationWindow* m_app;
-  Graph* m_graph;
+  ApplicationWindow *m_app;
+  Graph *m_graph;
 
-  DoubleSpinBox *m_dspnEnd, *m_dspnStart, *m_dspnStep, *m_dspnBreakStart, *m_dspnBreakEnd, *m_dspnStepBeforeBreak, *m_dspnStepAfterBreak, *m_dspnN;
+  DoubleSpinBox *m_dspnEnd, *m_dspnStart, *m_dspnStep, *m_dspnBreakStart,
+      *m_dspnBreakEnd, *m_dspnStepBeforeBreak, *m_dspnStepAfterBreak, *m_dspnN;
   QCheckBox *m_chkInvert, *m_chkLog10AfterBreak, *m_chkBreakDecoration;
   QRadioButton *m_radStep, *m_radMajor;
   QSpinBox *m_spnMajorValue, *m_spnBreakPosition, *m_spnBreakWidth;
   QGroupBox *m_grpAxesBreaks;
-  QComboBox *m_cmbMinorTicksBeforeBreak, *m_cmbMinorTicksAfterBreak, *m_cmbScaleType, *m_cmbMinorValue, *m_cmbUnit;
-  QLabel *m_lblScaleTypeLabel, *m_lblMinorBox, *m_lblStart, *m_lblEnd, *m_lblN, *m_lblWarn;
+  QComboBox *m_cmbMinorTicksBeforeBreak, *m_cmbMinorTicksAfterBreak,
+      *m_cmbScaleType, *m_cmbMinorValue, *m_cmbUnit;
+  QLabel *m_lblScaleTypeLabel, *m_lblMinorBox, *m_lblStart, *m_lblEnd, *m_lblN,
+      *m_lblWarn;
   QDateTimeEdit *m_dteStartDateTime, *m_dteEndDateTime;
   QTimeEdit *m_timStartTime, *m_timEndTime;
 
diff --git a/MantidPlot/src/ScaleDraw.h b/MantidPlot/src/ScaleDraw.h
index 0fe6722c8570a2b8cfaba31d088fafdc22e4290c..8288e716a31b33afabb3f78b836aeb21f5d6eec7 100644
--- a/MantidPlot/src/ScaleDraw.h
+++ b/MantidPlot/src/ScaleDraw.h
@@ -37,97 +37,107 @@
 #include <qwt_scale_draw.h>
 
 //! Extension to QwtScaleDraw
-class ScaleDraw: public QwtScaleDraw
-{
+class ScaleDraw : public QwtScaleDraw {
 public:
-	enum TicksStyle{None = 0, Out = 1, Both = 2, In = 3};
-	enum ScaleType{Numeric = 0, Text = 1, Day = 2, Month = 3, Time = 4, Date = 5, ColHeader = 6};
-	enum NumericFormat{Automatic, Decimal, Scientific, Superscripts};
-	enum NameFormat{ShortName, LongName, Initial};
+  enum TicksStyle { None = 0, Out = 1, Both = 2, In = 3 };
+  enum ScaleType {
+    Numeric = 0,
+    Text = 1,
+    Day = 2,
+    Month = 3,
+    Time = 4,
+    Date = 5,
+    ColHeader = 6
+  };
+  enum NumericFormat { Automatic, Decimal, Scientific, Superscripts };
+  enum NameFormat { ShortName, LongName, Initial };
 
   //! Constructs a new scale draw which is a clone of sd.
   ScaleDraw(Plot *plot, ScaleDraw *sd);
-	ScaleDraw(Plot *plot, const QString& formula = QString::null);
-	ScaleDraw(Plot *plot, const QStringList& labels, const QString& format, ScaleType type = Text);
+  ScaleDraw(Plot *plot, const QString &formula = QString::null);
+  ScaleDraw(Plot *plot, const QStringList &labels, const QString &format,
+            ScaleType type = Text);
 
   QString formatString();
-  QString format(){return d_format_info;};
+  QString format() { return d_format_info; };
 
-	QString formula() {return d_formula;};
-	void setFormula(const QString& formula) {d_formula = formula;};
+  QString formula() { return d_formula; };
+  void setFormula(const QString &formula) { d_formula = formula; };
 
-	double transformValue(double value) const;
-        QwtText label(double value) const override;
+  double transformValue(double value) const;
+  QwtText label(double value) const override;
 
-        int labelNumericPrecision(){return d_prec;};
-	void setNumericPrecision(int prec){d_prec = prec;};
+  int labelNumericPrecision() { return d_prec; };
+  void setNumericPrecision(int prec) { d_prec = prec; };
 
-	int majorTicksStyle()const{return d_majTicks;};
-	void setMajorTicksStyle(TicksStyle type){d_majTicks = type;};
+  int majorTicksStyle() const { return d_majTicks; };
+  void setMajorTicksStyle(TicksStyle type) { d_majTicks = type; };
 
-	int minorTicksStyle()const{return d_minTicks;};
-	void setMinorTicksStyle(TicksStyle type){d_minTicks = type;};
+  int minorTicksStyle() const { return d_minTicks; };
+  void setMinorTicksStyle(TicksStyle type) { d_minTicks = type; };
 
-	void setSelected(bool select = true){d_selected = select;};
+  void setSelected(bool select = true) { d_selected = select; };
 
-	int axis() const;
+  int axis() const;
 
-	ScaleType scaleType(){return d_type;};
-	void setScaleType(ScaleType type){d_type = type;};
+  ScaleType scaleType() { return d_type; };
+  void setScaleType(ScaleType type) { d_type = type; };
 
-	void labelFormat(char &f, int &prec) const;
+  void labelFormat(char &f, int &prec) const;
 
-	NumericFormat labelNumericFormat(){return d_numeric_format;};
-	void setNumericFormat(NumericFormat format);
+  NumericFormat labelNumericFormat() { return d_numeric_format; };
+  void setNumericFormat(NumericFormat format);
 
-	void setDayFormat(NameFormat format);
-	void setMonthFormat(NameFormat format);
-	void setTimeFormat(const QTime& t, const QString& format);
-	void setDateFormat(const QDateTime& d, const QString& format);
+  void setDayFormat(NameFormat format);
+  void setMonthFormat(NameFormat format);
+  void setTimeFormat(const QTime &t, const QString &format);
+  void setDateFormat(const QDateTime &d, const QString &format);
 
-	QDateTime dateTimeOrigin(){return d_date_time_origin;};
-    void setDateTimeOrigin(const QDateTime& d){d_date_time_origin = d;};
+  QDateTime dateTimeOrigin() { return d_date_time_origin; };
+  void setDateTimeOrigin(const QDateTime &d) { d_date_time_origin = d; };
 
-	QStringList labelsList(){return d_text_labels;};
+  QStringList labelsList() { return d_text_labels; };
 
-	NameFormat nameFormat(){return d_name_format;};
+  NameFormat nameFormat() { return d_name_format; };
 
 protected:
   void draw(QPainter *, const QPalette &) const override;
   void drawLabel(QPainter *painter, double value) const override;
   void drawTick(QPainter *p, double value, int len) const override;
   void drawBackbone(QPainter *painter) const override;
-        void drawBreak(QPainter *) const;
+  void drawBreak(QPainter *) const;
 
 private:
-	//! Pointer to the parent plot
-	Plot *d_plot;
-	//! Stores the scale type (numeric, text, etc...). See: enum NumericFormat
-	ScaleType d_type;
-	//! Stores the scale numeric format: Automatic, Decimal, Scientific, Superscripts
-	NumericFormat d_numeric_format;
-	//! Numerical format specification
-	char d_fmt;
-	//! Numerical precision
-    int d_prec;
-	//! A mathematical expression used to calculate the label values
-	QString d_formula;
-    //! Max ticks style
-	int d_majTicks;
-    //! Min ticks style
-	int d_minTicks;
-	//! Flag telling if the scale labels are selected (a blue frame is drawn around each labels if true)
-	bool d_selected;
-	//! Stores the scale name format for Day and Month scales
-	NameFormat d_name_format;
-	//! Stores the date-time origin used to calculate labels for Date/Time scales
-	QDateTime d_date_time_origin;
-	//! Stores extra format information:
-	/* - the date/time format used to calculate labels for Date/Time scales
-	 * - the Column/Table name in the case of Text/ColHeader scales
-	 */
-	QString d_format_info;
-	//! Stores the labels for Txt scales
-	QStringList d_text_labels;
+  //! Pointer to the parent plot
+  Plot *d_plot;
+  //! Stores the scale type (numeric, text, etc...). See: enum NumericFormat
+  ScaleType d_type;
+  //! Stores the scale numeric format: Automatic, Decimal, Scientific,
+  // Superscripts
+  NumericFormat d_numeric_format;
+  //! Numerical format specification
+  char d_fmt;
+  //! Numerical precision
+  int d_prec;
+  //! A mathematical expression used to calculate the label values
+  QString d_formula;
+  //! Max ticks style
+  int d_majTicks;
+  //! Min ticks style
+  int d_minTicks;
+  //! Flag telling if the scale labels are selected (a blue frame is drawn
+  // around each labels if true)
+  bool d_selected;
+  //! Stores the scale name format for Day and Month scales
+  NameFormat d_name_format;
+  //! Stores the date-time origin used to calculate labels for Date/Time scales
+  QDateTime d_date_time_origin;
+  //! Stores extra format information:
+  /* - the date/time format used to calculate labels for Date/Time scales
+   * - the Column/Table name in the case of Text/ColHeader scales
+   */
+  QString d_format_info;
+  //! Stores the labels for Txt scales
+  QStringList d_text_labels;
 };
 #endif
diff --git a/MantidPlot/src/ScalePicker.cpp b/MantidPlot/src/ScalePicker.cpp
index 6018ff00bc34f6e22c2aa6c3bab0124f88f8d66f..fbd7c67436e30cdd457e9cc2505ca12c4ada32c2 100644
--- a/MantidPlot/src/ScalePicker.cpp
+++ b/MantidPlot/src/ScalePicker.cpp
@@ -37,239 +37,216 @@
 #include <QMouseEvent>
 #include <QPen>
 
-ScalePicker::ScalePicker(QwtPlot *plot):
-    QObject(plot),
-	d_title_selected(false),
-	d_labels_selected(false),
-    d_selected_axis(NULL),
-	d_current_axis(NULL)
-{
-	refresh();
+ScalePicker::ScalePicker(QwtPlot *plot)
+    : QObject(plot), d_title_selected(false), d_labels_selected(false),
+      d_selected_axis(NULL), d_current_axis(NULL) {
+  refresh();
 }
 
-bool ScalePicker::eventFilter(QObject *object, QEvent *e)
-{
-	if (!object->inherits("QwtScaleWidget"))
-		return QObject::eventFilter(object, e);
-
-	QwtScaleWidget *scale = static_cast<QwtScaleWidget *>(object);
-	d_current_axis = scale;
-
-	if ( e->type() == QEvent::MouseButtonDblClick ){
-		mouseDblClicked(scale, ((QMouseEvent *)e)->pos());
-        return true;
-    }
-
-	if ( e->type() == QEvent::MouseButtonPress){
-		const QMouseEvent *me = (const QMouseEvent *)e;
-		QPoint pos = me->pos();
-		if (me->button() == Qt::LeftButton){
-			scale->setFocus();
-			emit clicked();
-
-            deselect();
-
-			if (titleRect(scale).contains(pos))
-                selectTitle(scale);
-            else if (!scaleTicksRect(scale).contains(pos))
-				selectLabels(scale);
-
-			return !(me->modifiers() & Qt::ShiftModifier) && !scaleTicksRect(scale).contains(pos);
-        } else if (me->button() == Qt::RightButton){
-			mouseRightClicked(scale, pos);
-			return true;
-        }
+bool ScalePicker::eventFilter(QObject *object, QEvent *e) {
+  if (!object->inherits("QwtScaleWidget"))
+    return QObject::eventFilter(object, e);
+
+  QwtScaleWidget *scale = static_cast<QwtScaleWidget *>(object);
+  d_current_axis = scale;
+
+  if (e->type() == QEvent::MouseButtonDblClick) {
+    mouseDblClicked(scale, ((QMouseEvent *)e)->pos());
+    return true;
+  }
+
+  if (e->type() == QEvent::MouseButtonPress) {
+    const QMouseEvent *me = (const QMouseEvent *)e;
+    QPoint pos = me->pos();
+    if (me->button() == Qt::LeftButton) {
+      scale->setFocus();
+      emit clicked();
+
+      deselect();
+
+      if (titleRect(scale).contains(pos))
+        selectTitle(scale);
+      else if (!scaleTicksRect(scale).contains(pos))
+        selectLabels(scale);
+
+      return !(me->modifiers() & Qt::ShiftModifier) &&
+             !scaleTicksRect(scale).contains(pos);
+    } else if (me->button() == Qt::RightButton) {
+      mouseRightClicked(scale, pos);
+      return true;
     }
-	return QObject::eventFilter(object, e);
+  }
+  return QObject::eventFilter(object, e);
 }
 
-void ScalePicker::mouseDblClicked(const QwtScaleWidget *scale, const QPoint &pos)
-{
-	if (titleRect(scale).contains(pos))
-		emit axisTitleDblClicked();
-	else if (scaleRect(scale).contains(pos))
-        emit axisDblClicked(scale->alignment());
+void ScalePicker::mouseDblClicked(const QwtScaleWidget *scale,
+                                  const QPoint &pos) {
+  if (titleRect(scale).contains(pos))
+    emit axisTitleDblClicked();
+  else if (scaleRect(scale).contains(pos))
+    emit axisDblClicked(scale->alignment());
 }
 
-void ScalePicker::mouseRightClicked(const QwtScaleWidget *scale, const QPoint &pos)
-{
-if (scaleRect(scale).contains(pos))
-	emit axisRightClicked(scale->alignment());
-else
-	emit axisTitleRightClicked();
+void ScalePicker::mouseRightClicked(const QwtScaleWidget *scale,
+                                    const QPoint &pos) {
+  if (scaleRect(scale).contains(pos))
+    emit axisRightClicked(scale->alignment());
+  else
+    emit axisTitleRightClicked();
 }
 
 // The rect of a scale without the title
-QRect ScalePicker::scaleRect(const QwtScaleWidget *scale) const
-{
-int margin = 1; // pixels tolerance
-QRect rect = scale->rect();
-rect.setRect(rect.x() - margin, rect.y() - margin, rect.width() + 2 * margin, rect.height() +  2 * margin);
-
-if (scale->title().text().isEmpty())
-	return rect;
-
-int dh = scale->title().textSize().height();
-switch(scale->alignment())
-    {
-    case QwtScaleDraw::LeftScale:
-        {
-		rect.setLeft(rect.left() + dh);
-        break;
-        }
-    case QwtScaleDraw::RightScale:
-        {
-		rect.setRight(rect.right() - dh);
-        break;
-        }
-    case QwtScaleDraw::BottomScale:
-        {
-		rect.setBottom(rect.bottom() - dh);
-	    break;
-        }
-    case QwtScaleDraw::TopScale:
-        {
-		rect.setTop(rect.top() + dh);
-        break;
-        }
-    }
-return rect;
+QRect ScalePicker::scaleRect(const QwtScaleWidget *scale) const {
+  int margin = 1; // pixels tolerance
+  QRect rect = scale->rect();
+  rect.setRect(rect.x() - margin, rect.y() - margin, rect.width() + 2 * margin,
+               rect.height() + 2 * margin);
+
+  if (scale->title().text().isEmpty())
+    return rect;
+
+  int dh = scale->title().textSize().height();
+  switch (scale->alignment()) {
+  case QwtScaleDraw::LeftScale: {
+    rect.setLeft(rect.left() + dh);
+    break;
+  }
+  case QwtScaleDraw::RightScale: {
+    rect.setRight(rect.right() - dh);
+    break;
+  }
+  case QwtScaleDraw::BottomScale: {
+    rect.setBottom(rect.bottom() - dh);
+    break;
+  }
+  case QwtScaleDraw::TopScale: {
+    rect.setTop(rect.top() + dh);
+    break;
+  }
+  }
+  return rect;
 }
 
-void ScalePicker::refresh()
-{
-    for ( uint i = 0; i < QwtPlot::axisCnt; i++ ){
-        QwtScaleWidget *scale = static_cast<QwtScaleWidget *>(plot()->axisWidget(i));
-        if ( scale )
-            scale->installEventFilter(this);
-    }
+void ScalePicker::refresh() {
+  for (uint i = 0; i < QwtPlot::axisCnt; i++) {
+    QwtScaleWidget *scale =
+        static_cast<QwtScaleWidget *>(plot()->axisWidget(i));
+    if (scale)
+      scale->installEventFilter(this);
+  }
 }
 
-QwtPlot *ScalePicker::plot()
-{
-  return dynamic_cast<QwtPlot *>(parent());
+QwtPlot *ScalePicker::plot() { return dynamic_cast<QwtPlot *>(parent()); }
+
+QRect ScalePicker::scaleTicksRect(const QwtScaleWidget *scale) const {
+  int majTickLength = scale->scaleDraw()->majTickLength();
+  QRect rect = scale->rect();
+  switch (scale->alignment()) {
+  case QwtScaleDraw::LeftScale:
+    rect.setLeft(rect.right() - majTickLength);
+    break;
+  case QwtScaleDraw::RightScale:
+    rect.setRight(rect.left() + majTickLength);
+    break;
+  case QwtScaleDraw::TopScale:
+    rect.setTop(rect.bottom() - majTickLength);
+    break;
+  case QwtScaleDraw::BottomScale:
+    rect.setBottom(rect.top() + majTickLength);
+    break;
+  }
+  return rect;
 }
 
-QRect ScalePicker::scaleTicksRect(const QwtScaleWidget *scale) const
-{
-	int majTickLength = scale->scaleDraw()->majTickLength();
-	QRect rect = scale->rect();
-	switch(scale->alignment())
-	{
-	case QwtScaleDraw::LeftScale:
-		rect.setLeft(rect.right() - majTickLength);
-	break;
-	case QwtScaleDraw::RightScale:
-		rect.setRight(rect.left() + majTickLength);
-	break;
-	case QwtScaleDraw::TopScale:
-		rect.setTop(rect.bottom() - majTickLength);
-	break;
-	case QwtScaleDraw::BottomScale:
-		rect.setBottom(rect.top() + majTickLength);
-	break;
-	}
-	return rect;
+QRect ScalePicker::titleRect(const QwtScaleWidget *scale) const {
+  if (scale->title().text().isEmpty())
+    return QRect();
+
+  QRect rect = scale->rect();
+  int margin = scale->margin();
+  rect = rect.adjusted(margin, margin, -margin, -margin);
+
+  int dh = scale->title().textSize().height();
+  switch (scale->alignment()) {
+  case QwtScaleDraw::LeftScale: {
+    rect.setRight(rect.left() + dh);
+    break;
+  }
+  case QwtScaleDraw::RightScale: {
+    rect.setLeft(rect.right() - dh);
+    break;
+  }
+  case QwtScaleDraw::BottomScale: {
+    rect.setTop(rect.bottom() - dh);
+    break;
+  }
+  case QwtScaleDraw::TopScale: {
+    rect.setBottom(rect.top() + dh);
+    break;
+  }
+  }
+  return rect;
 }
 
-QRect ScalePicker::titleRect(const QwtScaleWidget *scale) const
-{
-	if (scale->title().text().isEmpty())
-		return QRect();
-
-	QRect rect = scale->rect();
-	int margin = scale->margin();
-	rect = rect.adjusted (margin, margin, -margin, -margin);
-
-	int dh = scale->title().textSize().height();
-	switch(scale->alignment())
-    {
-    	case QwtScaleDraw::LeftScale:
-        {
-			rect.setRight(rect.left() + dh);
-        	break;
-        }
-    	case QwtScaleDraw::RightScale:
-        {
-			rect.setLeft(rect.right() - dh);
-        	break;
-        }
-    	case QwtScaleDraw::BottomScale:
-        {
-			rect.setTop(rect.bottom() - dh);
-	    	break;
-        }
-    	case QwtScaleDraw::TopScale:
-        {
-			rect.setBottom(rect.top() + dh);
-        	break;
-        }
-    }
-	return rect;
-}
-
-void ScalePicker::selectTitle(QwtScaleWidget *scale, bool select)
-{
-    if (!scale)
-        return;
+void ScalePicker::selectTitle(QwtScaleWidget *scale, bool select) {
+  if (!scale)
+    return;
 
-    if (d_title_selected == select && d_selected_axis == scale)
-        return;
+  if (d_title_selected == select && d_selected_axis == scale)
+    return;
 
-    Graph *g = static_cast<Graph *>(plot()->parent());
-    g->deselect();
+  Graph *g = static_cast<Graph *>(plot()->parent());
+  g->deselect();
 
-    d_title_selected = select;
-    d_selected_axis = scale;
-	d_labels_selected = false;
+  d_title_selected = select;
+  d_selected_axis = scale;
+  d_labels_selected = false;
 
-    QwtText title = scale->title();
-    if (select){
-        title.setBackgroundPen(QPen(Qt::blue));
-		g->notifyFontChange(title.font());
-    } else
-        title.setBackgroundPen(QPen(Qt::NoPen));
+  QwtText title = scale->title();
+  if (select) {
+    title.setBackgroundPen(QPen(Qt::blue));
+    g->notifyFontChange(title.font());
+  } else
+    title.setBackgroundPen(QPen(Qt::NoPen));
 
-    scale->setTitle(title);
+  scale->setTitle(title);
 }
 
-void ScalePicker::selectLabels(QwtScaleWidget *scale, bool select)
-{
-	if (!scale)
-        return;
+void ScalePicker::selectLabels(QwtScaleWidget *scale, bool select) {
+  if (!scale)
+    return;
 
-    if (d_labels_selected == select && d_selected_axis == scale)
-        return;
+  if (d_labels_selected == select && d_selected_axis == scale)
+    return;
 
-	Graph *g = static_cast<Graph *>(plot()->parent());
-    g->deselect();
+  Graph *g = static_cast<Graph *>(plot()->parent());
+  g->deselect();
 
-	d_labels_selected = select;
-	d_selected_axis = scale;
-	d_title_selected = false;
+  d_labels_selected = select;
+  d_selected_axis = scale;
+  d_title_selected = false;
 
-	g->notifyFontChange(scale->font());
+  g->notifyFontChange(scale->font());
 
-	ScaleDraw *sc_draw = static_cast<ScaleDraw *>(scale->scaleDraw());
-	sc_draw->setSelected(select);
-	scale->repaint();
+  ScaleDraw *sc_draw = static_cast<ScaleDraw *>(scale->scaleDraw());
+  sc_draw->setSelected(select);
+  scale->repaint();
 }
 
-void ScalePicker::deselect()
-{
-	if (!d_selected_axis)
-		return;
+void ScalePicker::deselect() {
+  if (!d_selected_axis)
+    return;
 
-	d_title_selected = false;
-	d_labels_selected = false;
+  d_title_selected = false;
+  d_labels_selected = false;
 
-	QwtText title = d_selected_axis->title();
-    title.setBackgroundPen(QPen(Qt::NoPen));
-    d_selected_axis->setTitle(title);
+  QwtText title = d_selected_axis->title();
+  title.setBackgroundPen(QPen(Qt::NoPen));
+  d_selected_axis->setTitle(title);
 
-	ScaleDraw *sc_draw = static_cast<ScaleDraw *>(d_selected_axis->scaleDraw());
-	sc_draw->setSelected(false);
+  ScaleDraw *sc_draw = static_cast<ScaleDraw *>(d_selected_axis->scaleDraw());
+  sc_draw->setSelected(false);
 
-    d_selected_axis->repaint();
-	d_selected_axis = NULL;
+  d_selected_axis->repaint();
+  d_selected_axis = NULL;
 }
diff --git a/MantidPlot/src/ScalePicker.h b/MantidPlot/src/ScalePicker.h
index dd705b2117a5c80564ae7e800edcb09560bd7e76..369b01d18a24557dfc9f3b3ad933f7f31513d62f 100644
--- a/MantidPlot/src/ScalePicker.h
+++ b/MantidPlot/src/ScalePicker.h
@@ -36,75 +36,77 @@ class QwtScaleWidget;
 /**\brief Handles user interaction with a QwtScaleWidget.
  *
  * This class is used by Graph to catch events for the scales on its Plot.
- * ScalePicker doesn't take any actions beyond emitting signals, which are then processed by Graph.
+ * ScalePicker doesn't take any actions beyond emitting signals, which are then
+ *processed by Graph.
  */
-class ScalePicker: public QObject
-{
-    Q_OBJECT
+class ScalePicker : public QObject {
+  Q_OBJECT
 public:
   explicit ScalePicker(QwtPlot *plot);
 
-        //! Returns the bounding rectangle of a scale without the title.
-	QRect scaleRect(const QwtScaleWidget *) const;
-
-	//! Returns the bounding rectangle of a scale excluding the title and the tick labels.
-	QRect scaleTicksRect(const QwtScaleWidget *scale) const;
-	
-	//! Returns the bounding rectangle of a scale's title.
-	QRect titleRect(const QwtScaleWidget *scale) const;
-
-	/** Install myself as event filter for all axes of my parent.
-	 * For every axis of plot(), add myself to the corresponding QwtScaleWidget.
-	 * \sa QwtPlot::axisWidget()
-	 */
-	void refresh();
-
-	//! Return my parent casted to QwtPlot.
-	QwtPlot *plot();
-
-	void deselect();
-	
-	bool titleSelected(){return d_title_selected;};
-    void selectTitle(QwtScaleWidget *scale, bool select = true);
-	
-	bool labelsSelected(){return d_labels_selected;};
-	void selectLabels(QwtScaleWidget *scale, bool select = true);
-	
-	/** Returns a pointer to the selected axis in the plot layer. 
-	 * The selected axis has selected title or selected tick labels (blue frame around texts).
-	 */
-	QwtScaleWidget* selectedAxis(){return d_selected_axis;};
-	//! Returns a pointer to the active axis in the plot layer.
-	QwtScaleWidget* currentAxis(){return d_current_axis;};
+  //! Returns the bounding rectangle of a scale without the title.
+  QRect scaleRect(const QwtScaleWidget *) const;
+
+  //! Returns the bounding rectangle of a scale excluding the title and the tick
+  // labels.
+  QRect scaleTicksRect(const QwtScaleWidget *scale) const;
+
+  //! Returns the bounding rectangle of a scale's title.
+  QRect titleRect(const QwtScaleWidget *scale) const;
+
+  /** Install myself as event filter for all axes of my parent.
+   * For every axis of plot(), add myself to the corresponding QwtScaleWidget.
+   * \sa QwtPlot::axisWidget()
+   */
+  void refresh();
+
+  //! Return my parent casted to QwtPlot.
+  QwtPlot *plot();
+
+  void deselect();
+
+  bool titleSelected() { return d_title_selected; };
+  void selectTitle(QwtScaleWidget *scale, bool select = true);
+
+  bool labelsSelected() { return d_labels_selected; };
+  void selectLabels(QwtScaleWidget *scale, bool select = true);
+
+  /** Returns a pointer to the selected axis in the plot layer.
+   * The selected axis has selected title or selected tick labels (blue frame
+   * around texts).
+   */
+  QwtScaleWidget *selectedAxis() { return d_selected_axis; };
+  //! Returns a pointer to the active axis in the plot layer.
+  QwtScaleWidget *currentAxis() { return d_current_axis; };
 
 signals:
-	//! Emitted when the user clicks on one of the monitored axes.
-	void clicked();
-
-	/** Emitted when the user right-clicks on an axis (but not its title).
-	 * The argument specifies the axis' QwtScaleDraw::Alignment.
-	 */
-	void axisRightClicked(int);
-	//! Emitted when the user right-clicks on the title of an axis.
-	void axisTitleRightClicked();
-
-	/** Emitted when the user double-clicks on an axis (but not its title).
-	 * The argument specifies the axis' QwtScaleDraw::Alignment.
-	 */
-	void axisDblClicked(int);
-
-	/** Emitted when the user double-clicks on an the axis title.
-	 */
-	void axisTitleDblClicked();
-	
+  //! Emitted when the user clicks on one of the monitored axes.
+  void clicked();
+
+  /** Emitted when the user right-clicks on an axis (but not its title).
+   * The argument specifies the axis' QwtScaleDraw::Alignment.
+   */
+  void axisRightClicked(int);
+  //! Emitted when the user right-clicks on the title of an axis.
+  void axisTitleRightClicked();
+
+  /** Emitted when the user double-clicks on an axis (but not its title).
+   * The argument specifies the axis' QwtScaleDraw::Alignment.
+   */
+  void axisDblClicked(int);
+
+  /** Emitted when the user double-clicks on an the axis title.
+   */
+  void axisTitleDblClicked();
+
 private:
   bool eventFilter(QObject *, QEvent *) override;
 
-        void mouseDblClicked(const QwtScaleWidget *, const QPoint &);
-	void mouseClicked(const QwtScaleWidget *scale, const QPoint &pos) ;
-	void mouseRightClicked(const QwtScaleWidget *scale, const QPoint &pos);
+  void mouseDblClicked(const QwtScaleWidget *, const QPoint &);
+  void mouseClicked(const QwtScaleWidget *scale, const QPoint &pos);
+  void mouseRightClicked(const QwtScaleWidget *scale, const QPoint &pos);
 
-	bool d_title_selected;
-	bool d_labels_selected;
-	QwtScaleWidget *d_selected_axis, *d_current_axis;
+  bool d_title_selected;
+  bool d_labels_selected;
+  QwtScaleWidget *d_selected_axis, *d_current_axis;
 };
diff --git a/MantidPlot/src/ScreenPickerTool.cpp b/MantidPlot/src/ScreenPickerTool.cpp
index 1b9bb27b0fc11d9fdda2b48e50ab3d88d1985dc5..4210725c4afd123a1eb3aea36d55c23f3268b4f1 100644
--- a/MantidPlot/src/ScreenPickerTool.cpp
+++ b/MantidPlot/src/ScreenPickerTool.cpp
@@ -36,72 +36,69 @@
 #include "pixmaps.h"
 #include <qwt_symbol.h>
 
-ScreenPickerTool::ScreenPickerTool(Graph *graph, const QObject *status_target, const char *status_slot)
-	: QwtPlotPicker(graph->plotWidget()->canvas()),
-	PlotToolInterface(graph)
-{
-	d_selection_marker.setLineStyle(QwtPlotMarker::Cross);
-	d_selection_marker.setLinePen(QPen(Qt::red,1));
-	setTrackerMode(QwtPicker::AlwaysOn);
-	setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
-	d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("cursor_xpm"), -1, -1));
-
-	if (status_target)
-		connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
-	emit statusText(tr("Click on plot or move cursor to display coordinates!"));
+ScreenPickerTool::ScreenPickerTool(Graph *graph, const QObject *status_target,
+                                   const char *status_slot)
+    : QwtPlotPicker(graph->plotWidget()->canvas()), PlotToolInterface(graph) {
+  d_selection_marker.setLineStyle(QwtPlotMarker::Cross);
+  d_selection_marker.setLinePen(QPen(Qt::red, 1));
+  setTrackerMode(QwtPicker::AlwaysOn);
+  setSelectionFlags(QwtPicker::PointSelection | QwtPicker::ClickSelection);
+  d_graph->plotWidget()->canvas()->setCursor(
+      QCursor(getQPixmap("cursor_xpm"), -1, -1));
+
+  if (status_target)
+    connect(this, SIGNAL(statusText(const QString &)), status_target,
+            status_slot);
+  emit statusText(tr("Click on plot or move cursor to display coordinates!"));
 }
 
-ScreenPickerTool::~ScreenPickerTool()
-{
-	d_selection_marker.detach();
-	d_graph->plotWidget()->canvas()->unsetCursor();
-	d_graph->plotWidget()->replot();
+ScreenPickerTool::~ScreenPickerTool() {
+  d_selection_marker.detach();
+  d_graph->plotWidget()->canvas()->unsetCursor();
+  d_graph->plotWidget()->replot();
 }
 
-void ScreenPickerTool::append(const QPoint &point)
-{
-	QwtDoublePoint pos = invTransform(point);
-	QString info;
-	info.sprintf("x=%g; y=%g", pos.x(), pos.y());
-	emit statusText(info);
-
-	d_selection_marker.setValue(pos);
-	if (d_selection_marker.plot() == NULL)
-		d_selection_marker.attach(d_graph->plotWidget());
-	d_graph->plotWidget()->replot();
+void ScreenPickerTool::append(const QPoint &point) {
+  QwtDoublePoint pos = invTransform(point);
+  QString info;
+  info.sprintf("x=%g; y=%g", pos.x(), pos.y());
+  emit statusText(info);
+
+  d_selection_marker.setValue(pos);
+  if (d_selection_marker.plot() == NULL)
+    d_selection_marker.attach(d_graph->plotWidget());
+  d_graph->plotWidget()->replot();
 }
 
-bool ScreenPickerTool::eventFilter(QObject *obj, QEvent *event)
-{
-	switch(event->type()) {
-		case QEvent::MouseButtonDblClick:
-			emit selected(d_selection_marker.value());
-			return true;
-		case QEvent::KeyPress:
-			{
-				QKeyEvent *ke = (QKeyEvent*) event;
-				switch(ke->key()) {
-					case Qt::Key_Enter:
-					case Qt::Key_Return:
-					{
-                        QwtDoublePoint pos = invTransform(canvas()->mapFromGlobal(QCursor::pos()));
-                        d_selection_marker.setValue(pos);
-                        if (d_selection_marker.plot() == NULL)
-                            d_selection_marker.attach(d_graph->plotWidget());
-                        d_graph->plotWidget()->replot();
-						emit selected(d_selection_marker.value());
-						QString info;
-                        emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
-						return true;
-					}
-					default:
-						break;
-				}
-			}
-		default:
-			break;
-	}
-	return QwtPlotPicker::eventFilter(obj, event);
+bool ScreenPickerTool::eventFilter(QObject *obj, QEvent *event) {
+  switch (event->type()) {
+  case QEvent::MouseButtonDblClick:
+    emit selected(d_selection_marker.value());
+    return true;
+  case QEvent::KeyPress: {
+    QKeyEvent *ke = (QKeyEvent *)event;
+    switch (ke->key()) {
+    case Qt::Key_Enter:
+    case Qt::Key_Return: {
+      QwtDoublePoint pos =
+          invTransform(canvas()->mapFromGlobal(QCursor::pos()));
+      d_selection_marker.setValue(pos);
+      if (d_selection_marker.plot() == NULL)
+        d_selection_marker.attach(d_graph->plotWidget());
+      d_graph->plotWidget()->replot();
+      emit selected(d_selection_marker.value());
+      QString info;
+      emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
+      return true;
+    }
+    default:
+      break;
+    }
+  }
+  default:
+    break;
+  }
+  return QwtPlotPicker::eventFilter(obj, event);
 }
 /**
  *  This overrides the base class trackerText() function so that we can
@@ -109,9 +106,8 @@ bool ScreenPickerTool::eventFilter(QObject *obj, QEvent *event)
  *
  *  @param pos  The current mouse location.
  */
-QwtText ScreenPickerTool::trackerText( const QPoint & pos ) const
-{	
-	return QwtPlotPicker::trackerText(pos);
+QwtText ScreenPickerTool::trackerText(const QPoint &pos) const {
+  return QwtPlotPicker::trackerText(pos);
 }
 
 /**
@@ -120,87 +116,85 @@ QwtText ScreenPickerTool::trackerText( const QPoint & pos ) const
  *
  *  @param pos  The current mouse location.
  */
-QwtText ScreenPickerTool::trackerText( const QwtDoublePoint & pos ) const
-{	
-	QString info;
-    info.sprintf("%g; %g", pos.x(), pos.y());
-	return QwtText(info);
+QwtText ScreenPickerTool::trackerText(const QwtDoublePoint &pos) const {
+  QString info;
+  info.sprintf("%g; %g", pos.x(), pos.y());
+  return QwtText(info);
 }
 
-DrawPointTool::DrawPointTool(ApplicationWindow *app, Graph *graph, const QObject *status_target, const char *status_slot)
-	: ScreenPickerTool(graph, status_target, status_slot),
-	d_app(app)
-{
-	d_curve = NULL;
-	d_table = NULL;
+DrawPointTool::DrawPointTool(ApplicationWindow *app, Graph *graph,
+                             const QObject *status_target,
+                             const char *status_slot)
+    : ScreenPickerTool(graph, status_target, status_slot), d_app(app) {
+  d_curve = NULL;
+  d_table = NULL;
 }
 
-void DrawPointTool::appendPoint(const QwtDoublePoint &pos)
-{
-	if (!d_app)
-		return;
-
-    QString info;
-	emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
-
-	if (!d_table){
-		d_table = d_app->newHiddenTable(d_app->generateUniqueName(tr("Draw")), "", 30, 2, "");
-		d_app->modifiedProject();
-	}
-
-	int rows = 0;
-	if (d_curve)
-		rows = d_curve->dataSize();
-
-	if (d_table->numRows() <= rows)
-		d_table->setNumRows(rows + 10);
-
-	d_table->setCell(rows, 0, pos.x());
-	d_table->setCell(rows, 1, pos.y());
-
-	if (!d_curve){
-		d_curve = new DataCurve(d_table, d_table->colName(0), d_table->colName(1));
-		d_curve->setAxis(QwtPlot::xBottom, QwtPlot::yLeft);
-		d_curve->setPen(QPen(Qt::black, d_app->defaultCurveLineWidth));
-		d_curve->setSymbol(QwtSymbol(QwtSymbol::Ellipse, QBrush(Qt::black),
-						  QPen(Qt::black, d_app->defaultCurveLineWidth),
-						  QSize(d_app->defaultSymbolSize, d_app->defaultSymbolSize)));
-		d_graph->insertPlotItem(d_curve, Graph::LineSymbols);
-	}
-
-	d_curve->setFullRange();
-	d_graph->updatePlot();
+void DrawPointTool::appendPoint(const QwtDoublePoint &pos) {
+  if (!d_app)
+    return;
+
+  QString info;
+  emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
+
+  if (!d_table) {
+    d_table = d_app->newHiddenTable(d_app->generateUniqueName(tr("Draw")), "",
+                                    30, 2, "");
+    d_app->modifiedProject();
+  }
+
+  int rows = 0;
+  if (d_curve)
+    rows = d_curve->dataSize();
+
+  if (d_table->numRows() <= rows)
+    d_table->setNumRows(rows + 10);
+
+  d_table->setCell(rows, 0, pos.x());
+  d_table->setCell(rows, 1, pos.y());
+
+  if (!d_curve) {
+    d_curve = new DataCurve(d_table, d_table->colName(0), d_table->colName(1));
+    d_curve->setAxis(QwtPlot::xBottom, QwtPlot::yLeft);
+    d_curve->setPen(QPen(Qt::black, d_app->defaultCurveLineWidth));
+    d_curve->setSymbol(
+        QwtSymbol(QwtSymbol::Ellipse, QBrush(Qt::black),
+                  QPen(Qt::black, d_app->defaultCurveLineWidth),
+                  QSize(d_app->defaultSymbolSize, d_app->defaultSymbolSize)));
+    d_graph->insertPlotItem(d_curve, Graph::LineSymbols);
+  }
+
+  d_curve->setFullRange();
+  d_graph->updatePlot();
 }
 
-bool DrawPointTool::eventFilter(QObject *obj, QEvent *event)
-{
-	switch(event->type()) {
-		case QEvent::MouseButtonDblClick:
-			appendPoint(d_selection_marker.value());
-			return true;
-		case QEvent::KeyPress:
-			{
-				QKeyEvent *ke = (QKeyEvent*) event;
-				switch(ke->key()) {
-					case Qt::Key_Enter:
-					case Qt::Key_Return:
-					{
-                        QwtDoublePoint pos = invTransform(canvas()->mapFromGlobal(QCursor::pos()));
-                        d_selection_marker.setValue(pos);
-                        if (d_selection_marker.plot() == NULL)
-                            d_selection_marker.attach(d_graph->plotWidget());
-                        d_graph->plotWidget()->replot();
-						emit selected(d_selection_marker.value());
-
-						appendPoint(pos);
-						return true;
-					}
-					default:
-						break;
-				}
-			}
-		default:
-			break;
-	}
-	return QwtPlotPicker::eventFilter(obj, event);
+bool DrawPointTool::eventFilter(QObject *obj, QEvent *event) {
+  switch (event->type()) {
+  case QEvent::MouseButtonDblClick:
+    appendPoint(d_selection_marker.value());
+    return true;
+  case QEvent::KeyPress: {
+    QKeyEvent *ke = (QKeyEvent *)event;
+    switch (ke->key()) {
+    case Qt::Key_Enter:
+    case Qt::Key_Return: {
+      QwtDoublePoint pos =
+          invTransform(canvas()->mapFromGlobal(QCursor::pos()));
+      d_selection_marker.setValue(pos);
+      if (d_selection_marker.plot() == NULL)
+        d_selection_marker.attach(d_graph->plotWidget());
+      d_graph->plotWidget()->replot();
+      emit selected(d_selection_marker.value());
+
+      appendPoint(pos);
+      return true;
+    }
+    default:
+      break;
+    }
+  }
+  default:
+    break;
+  }
+  return QwtPlotPicker::eventFilter(obj, event);
 }
diff --git a/MantidPlot/src/ScreenPickerTool.h b/MantidPlot/src/ScreenPickerTool.h
index f286dc09c541097385d60ae9380ea26599656926..781dc63ea92f4b8b59e5f98298018d224390d8b0 100644
--- a/MantidPlot/src/ScreenPickerTool.h
+++ b/MantidPlot/src/ScreenPickerTool.h
@@ -42,45 +42,49 @@ class DataCurve;
 
 /**Plot tool for selecting arbitrary points.
  *
- * This is a rather thin wrapper around QwtPlotPicker, providing selection of points
+ * This is a rather thin wrapper around QwtPlotPicker, providing selection of
+ *points
  * on a Graph/Plot and displaying coordinates.
  */
-class ScreenPickerTool : public QwtPlotPicker, public PlotToolInterface
-{
-	Q_OBJECT
-	public:
-		ScreenPickerTool(Graph *graph, const QObject *status_target=NULL, const char *status_slot="");
-                ~ScreenPickerTool() override;
+class ScreenPickerTool : public QwtPlotPicker, public PlotToolInterface {
+  Q_OBJECT
+public:
+  ScreenPickerTool(Graph *graph, const QObject *status_target = NULL,
+                   const char *status_slot = "");
+  ~ScreenPickerTool() override;
 
-        signals:
-		/** Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
-	protected:
-          bool eventFilter(QObject *obj, QEvent *event) override;
-          void append(const QPoint &point) override;
-          QwtText trackerText(const QPoint &) const override;
-          QwtText trackerText(const QwtDoublePoint &) const override;
-                QwtPlotMarker d_selection_marker;
+signals:
+  /** Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
+
+protected:
+  bool eventFilter(QObject *obj, QEvent *event) override;
+  void append(const QPoint &point) override;
+  QwtText trackerText(const QPoint &) const override;
+  QwtText trackerText(const QwtDoublePoint &) const override;
+  QwtPlotMarker d_selection_marker;
 };
 
 /**Plot tool for drawing arbitrary points.
  *
  */
-class DrawPointTool : public ScreenPickerTool
-{
-	Q_OBJECT
-	public:
-		DrawPointTool(ApplicationWindow *app, Graph *graph, const QObject *status_target=NULL, const char *status_slot="");
+class DrawPointTool : public ScreenPickerTool {
+  Q_OBJECT
+public:
+  DrawPointTool(ApplicationWindow *app, Graph *graph,
+                const QObject *status_target = NULL,
+                const char *status_slot = "");
 
-	protected:
-          bool eventFilter(QObject *obj, QEvent *event) override;
-                void appendPoint(const QwtDoublePoint &point);
-		DataCurve *d_curve;
-		Table *d_table;
-		ApplicationWindow *d_app;
+protected:
+  bool eventFilter(QObject *obj, QEvent *event) override;
+  void appendPoint(const QwtDoublePoint &point);
+  DataCurve *d_curve;
+  Table *d_table;
+  ApplicationWindow *d_app;
 };
 
 #endif // ifndef SCREEN_PICKER_TOOL_H
diff --git a/MantidPlot/src/Script.cpp b/MantidPlot/src/Script.cpp
index 2c06a8226d8ed3108efa2c0d2b37ed5f7f376705..d82f2d5383b026602e8956a7a4a4fbafa53e97ec 100644
--- a/MantidPlot/src/Script.cpp
+++ b/MantidPlot/src/Script.cpp
@@ -38,15 +38,12 @@
 /**
  * Constructor taking a script reference
  */
-Script::ScriptTask::ScriptTask(Script & script)
-  : QFutureInterface<bool>(), QRunnable(), m_script(script)
-{
-}
+Script::ScriptTask::ScriptTask(Script &script)
+    : QFutureInterface<bool>(), QRunnable(), m_script(script) {}
 
 /// Starts a thread/or uses the current thread
 /// by using the script thread pool to start this job
-QFuture<bool> Script::ScriptTask::start()
-{
+QFuture<bool> Script::ScriptTask::start() {
   this->setRunnable(this);
   this->reportStarted();
   QFuture<bool> future = this->future();
@@ -55,8 +52,7 @@ QFuture<bool> Script::ScriptTask::start()
 }
 
 /// Runs the task in the thread
-void Script::ScriptTask::run()
-{
+void Script::ScriptTask::run() {
   const bool result = m_script.execute(m_script.scriptCode());
 
   this->reportResult(result);
@@ -69,8 +65,7 @@ void Script::ScriptTask::run()
 /**
  * Constructor. Allows only a single thread that does not expire
  */
-Script::ScriptThreadPool::ScriptThreadPool() : QThreadPool()
-{
+Script::ScriptThreadPool::ScriptThreadPool() : QThreadPool() {
   this->setMaxThreadCount(1);
   this->setExpiryTimeout(-1);
 }
@@ -81,13 +76,11 @@ Script::ScriptThreadPool::ScriptThreadPool() : QThreadPool()
 
 #include <QtConcurrentRun>
 
-
 Script::Script(ScriptingEnv *env, const QString &name,
-               const InteractionType interact, QObject * context)
-  : QObject(), m_env(env), m_name(name.toStdString()) , m_context(context),
-    m_redirectOutput(true), m_reportProgress(false), m_interactMode(interact),
-    m_execMode(NotExecuting), m_thread(new ScriptThreadPool)
-{
+               const InteractionType interact, QObject *context)
+    : QObject(), m_env(env), m_name(name.toStdString()), m_context(context),
+      m_redirectOutput(true), m_reportProgress(false), m_interactMode(interact),
+      m_execMode(NotExecuting), m_thread(new ScriptThreadPool) {
   m_env->incref();
 
   connect(this, SIGNAL(started(const QString &)), this, SLOT(setIsRunning()));
@@ -99,12 +92,13 @@ Script::Script(ScriptingEnv *env, const QString &name,
    * This can be very confusing to users so force a call to release
    * the memory.
    */
-  connect(this, SIGNAL(finished(const QString &)), this, SLOT(setNotExecuting()));
-  connect(this, SIGNAL(error(const QString &, const QString &, int)), this, SLOT(setNotExecuting()));
+  connect(this, SIGNAL(finished(const QString &)), this,
+          SLOT(setNotExecuting()));
+  connect(this, SIGNAL(error(const QString &, const QString &, int)), this,
+          SLOT(setNotExecuting()));
 }
 
-Script::~Script()
-{
+Script::~Script() {
   delete m_thread;
   m_env->decref();
 }
@@ -112,18 +106,14 @@ Script::~Script()
 /**
  * Sets a new name for the script
  */
-void Script::setIdentifier(const QString & name)
-{
-  m_name = name.toStdString();
-}
+void Script::setIdentifier(const QString &name) { m_name = name.toStdString(); }
 
 /**
  * Compile the code, returning true/false depending on the status
  * @param code Code to compile
  * @return True/false depending on success
  */
-bool Script::compile(const ScriptCode & code)
-{
+bool Script::compile(const ScriptCode &code) {
   setupCode(code);
   return this->compileImpl();
 }
@@ -133,59 +123,48 @@ bool Script::compile(const ScriptCode & code)
  * @param code Code to evaluate
  * @return The result as a QVariant
  */
-QVariant Script::evaluate(const ScriptCode & code)
-{
+QVariant Script::evaluate(const ScriptCode &code) {
   setupCode(code);
   return this->evaluateImpl();
 }
 
 /// Execute the Code, returning false on an error / exception.
-bool Script::execute(const ScriptCode & code)
-{
+bool Script::execute(const ScriptCode &code) {
   setupCode(code);
   return this->executeImpl();
 }
 
-/// Execute the code asynchronously, returning immediately after the execution has started
-QFuture<bool> Script::executeAsync(const ScriptCode & code)
-{
+/// Execute the code asynchronously, returning immediately after the execution
+/// has started
+QFuture<bool> Script::executeAsync(const ScriptCode &code) {
   setupCode(code);
   ScriptTask *asyncScript = new ScriptTask(*this);
   return asyncScript->start();
 }
 
 /// Request that this script be aborted
-void Script::abort()
-{
-  if(isExecuting()) this->abortImpl();
+void Script::abort() {
+  if (isExecuting())
+    this->abortImpl();
 }
 
 /// Sets the execution mode to NotExecuting
-void Script::setNotExecuting()
-{
-  m_execMode = NotExecuting;
-}
+void Script::setNotExecuting() { m_execMode = NotExecuting; }
 
 /// Sets the execution mode to Running to indicate something is running
-void Script::setIsRunning()
-{
-  m_execMode = Running;
-}
+void Script::setIsRunning() { m_execMode = Running; }
 
 /**
  * Sets the offset & code string
  */
-void Script::setupCode(const ScriptCode & code)
-{
-  m_code = code;
-}
+void Script::setupCode(const ScriptCode &code) { m_code = code; }
 
 /**
- * Ensure that any line endings are converted to single '\n' so that the Python C API is happy
+ * Ensure that any line endings are converted to single '\n' so that the Python
+ * C API is happy
  * @param text :: The text to check and convert
  */
-QString Script::normaliseLineEndings(QString text) const
-{
+QString Script::normaliseLineEndings(QString text) const {
   text = text.replace(QRegExp("\\r\\n"), QString("\n"));
   text = text.replace(QRegExp("\\r"), QString("\n"));
   return text;
diff --git a/MantidPlot/src/Script.h b/MantidPlot/src/Script.h
index d13ddbe0c7f0f38f2bdf40e68e0a5cea67b48a58..d6404b3af2ee2e5a048e8ddcfda5ef002f14104c 100644
--- a/MantidPlot/src/Script.h
+++ b/MantidPlot/src/Script.h
@@ -51,29 +51,28 @@ class Script;
  * variables. The code may be changed and executed multiple times during the
  * lifetime of an object.
  */
-class Script : public QObject
-{
+class Script : public QObject {
   Q_OBJECT
 
-  public:
+public:
   /// Interaction type
-  enum InteractionType {Interactive, NonInteractive};
+  enum InteractionType { Interactive, NonInteractive };
   /// Execution mode
-  enum ExecutionMode {Serialised, Asynchronous, Running, NotExecuting};
+  enum ExecutionMode { Serialised, Asynchronous, Running, NotExecuting };
 
   /// Constructor
   Script(ScriptingEnv *env, const QString &name, const InteractionType interact,
-         QObject * context = NULL);
+         QObject *context = NULL);
   /// Destructor
   ~Script() override;
   /// Returns the envirnoment this script is tied to
   inline ScriptingEnv *environment() { return m_env; }
   /// Returns the identifier for the script.
-  inline const std::string & identifier() const { return m_name; }
+  inline const std::string &identifier() const { return m_name; }
   /// Update the identifier for the object.
   virtual void setIdentifier(const QString &name);
   /// Return the current context
-  const QObject * context() const { return m_context; }
+  const QObject *context() const { return m_context; }
   /// Set the context in which the code is to be executed.
   virtual void setContext(QObject *context) { m_context = context; }
 
@@ -94,18 +93,20 @@ class Script : public QObject
 
   /// Create a list of keywords for the code completion API
   virtual void generateAutoCompleteList() {}
-  // Does the code compile to a complete statement, i.e no more input is required
-  virtual bool compilesToCompleteStatement(const QString & code) const = 0;
+  // Does the code compile to a complete statement, i.e no more input is
+  // required
+  virtual bool compilesToCompleteStatement(const QString &code) const = 0;
 
 public slots:
   /// Compile the code, returning true/false depending on the status
-  bool compile(const ScriptCode & code);
+  bool compile(const ScriptCode &code);
   /// Evaluate the Code, returning QVariant() on an error / exception.
-  QVariant evaluate(const ScriptCode & code);
+  QVariant evaluate(const ScriptCode &code);
   /// Execute the Code, returning false on an error / exception.
-  bool execute(const ScriptCode & code);
-  /// Execute the code asynchronously, returning immediately after the execution has started
-  QFuture<bool> executeAsync(const ScriptCode & code);
+  bool execute(const ScriptCode &code);
+  /// Execute the code asynchronously, returning immediately after the execution
+  /// has started
+  QFuture<bool> executeAsync(const ScriptCode &code);
   /// Request that execution of this script be aborted
   void abort();
 
@@ -115,32 +116,34 @@ public slots:
   void setIsRunning();
 
   // local variables
-  virtual bool setQObject(QObject*, const char*) { return false; }
-  virtual bool setInt(int, const char*) { return false; }
-  virtual bool setDouble(double, const char*) { return false; }
+  virtual bool setQObject(QObject *, const char *) { return false; }
+  virtual bool setInt(int, const char *) { return false; }
+  virtual bool setDouble(double, const char *) { return false; }
   virtual void clearLocals() {}
 
 signals:
   /// A signal defining when this script has started executing
-  void started(const QString & message);
+  void started(const QString &message);
   /// A signal defining when this script has completed successfully
-  void finished(const QString & message);
+  void finished(const QString &message);
   /// signal an error condition / exception
-  void error(const QString & message, const QString & scriptName, int lineNumber);
+  void error(const QString &message, const QString &scriptName, int lineNumber);
   /// output generated by the code
-  void print(const QString & output);
+  void print(const QString &output);
   /// Line number changed
   void currentLineChanged(int lineno, bool error);
   // Signal that new keywords are available
-  void autoCompleteListGenerated(const QStringList & keywords);
+  void autoCompleteListGenerated(const QStringList &keywords);
 
 protected:
   /// Return the true line number by adding the offset
-  inline int getRealLineNo(const int codeLine) const { return codeLine + m_code.offset(); }
+  inline int getRealLineNo(const int codeLine) const {
+    return codeLine + m_code.offset();
+  }
   /// Return the code string
-  inline const std::string & codeString() const { return m_code.codeString(); }
+  inline const std::string &codeString() const { return m_code.codeString(); }
   /// Return the script code object
-  inline const ScriptCode & scriptCode() const { return m_code; }
+  inline const ScriptCode &scriptCode() const { return m_code; }
   /// Compile the code, returning true/false depending on the status
   virtual bool compileImpl() = 0;
   /// Evaluate the Code, returning QVariant() on an error / exception.
@@ -154,8 +157,7 @@ private:
   /**
    * Worker task for the asynchronous exec calls
    */
-  class ScriptTask : public QFutureInterface<bool>, public QRunnable
-  {
+  class ScriptTask : public QFutureInterface<bool>, public QRunnable {
   public:
     explicit ScriptTask(Script &script);
     QFuture<bool> start();
@@ -163,24 +165,24 @@ private:
 
   private:
     ScriptTask();
-    Script & m_script;
+    Script &m_script;
   };
   /**
    * ThreadPool that allows only a single thread
    */
-  class ScriptThreadPool : public QThreadPool
-  {
+  class ScriptThreadPool : public QThreadPool {
   public:
     ScriptThreadPool();
   };
 
   /// Setup the code from a script code object
-  void setupCode(const ScriptCode & code);
-  /// Normalise line endings for the given code. The Python C/API does not seem to like CRLF endings so normalise to just LF
+  void setupCode(const ScriptCode &code);
+  /// Normalise line endings for the given code. The Python C/API does not seem
+  /// to like CRLF endings so normalise to just LF
   QString normaliseLineEndings(QString text) const;
 
   ScriptingEnv *m_env;
-  std::string m_name; //Easier to convert to C string
+  std::string m_name; // Easier to convert to C string
   ScriptCode m_code;
   QObject *m_context;
   bool m_redirectOutput;
@@ -192,5 +194,4 @@ private:
   ScriptThreadPool *m_thread;
 };
 
-
 #endif
diff --git a/MantidPlot/src/ScriptCode.cpp b/MantidPlot/src/ScriptCode.cpp
index 2ca98df92784935224bb75ee3c739dbacffb17f0..53642055b25192d5e43c3cd53715ed84683b1e07 100644
--- a/MantidPlot/src/ScriptCode.cpp
+++ b/MantidPlot/src/ScriptCode.cpp
@@ -2,16 +2,13 @@
 #include <boost/regex.hpp>
 
 /// Empty code
-ScriptCode::ScriptCode() : m_code(), m_offset()
-{
-}
+ScriptCode::ScriptCode() : m_code(), m_offset() {}
 
 /**
  * Code from a c-style string, setting the offset to zero
  * @param codeStr A string of code
  */
-ScriptCode::ScriptCode(const char * codeStr) : m_code(codeStr), m_offset(0)
-{
+ScriptCode::ScriptCode(const char *codeStr) : m_code(codeStr), m_offset(0) {
   convertLineEndingsToUnix();
 }
 
@@ -20,23 +17,20 @@ ScriptCode::ScriptCode(const char * codeStr) : m_code(codeStr), m_offset(0)
  * @param codeStr A string of code
  * @param offset An offset for the first line in a larger block of code
  */
-ScriptCode::ScriptCode(const char * codeStr, const int offset)
-  : m_code(codeStr), m_offset(offset)
-{
+ScriptCode::ScriptCode(const char *codeStr, const int offset)
+    : m_code(codeStr), m_offset(offset) {
   convertLineEndingsToUnix();
 }
 
 /// Code from a QString with zero offset
-ScriptCode::ScriptCode(const QString & codeStr)
-  : m_code(codeStr.toStdString()), m_offset(0)
-{
+ScriptCode::ScriptCode(const QString &codeStr)
+    : m_code(codeStr.toStdString()), m_offset(0) {
   convertLineEndingsToUnix();
 }
 
 /// Code from a QString with a defined offset
-ScriptCode::ScriptCode(const QString & codeStr, const int offset)
-  : m_code(codeStr.toStdString()), m_offset(offset)
-{
+ScriptCode::ScriptCode(const QString &codeStr, const int offset)
+    : m_code(codeStr.toStdString()), m_offset(offset) {
   convertLineEndingsToUnix();
 }
 
@@ -44,9 +38,9 @@ ScriptCode::ScriptCode(const QString & codeStr, const int offset)
  * Ensures that the code string only has Unix style line-endings
  * Some interpreters will not accept code with other line ending types
  */
-void ScriptCode::convertLineEndingsToUnix()
-{
+void ScriptCode::convertLineEndingsToUnix() {
   // Unify line endings
-  static boost::regex eol("\\R"); // \R is Perl syntax for matching any EOL sequence
+  static boost::regex eol(
+      "\\R"); // \R is Perl syntax for matching any EOL sequence
   m_code = boost::regex_replace(m_code, eol, "\n"); // converts all to LF
 }
diff --git a/MantidPlot/src/ScriptCode.h b/MantidPlot/src/ScriptCode.h
index b8f31707970c1881d43312c3cb46c97e685241cb..67f0795946d2f3a47b59b2f8580bd438ae3caa02 100644
--- a/MantidPlot/src/ScriptCode.h
+++ b/MantidPlot/src/ScriptCode.h
@@ -9,22 +9,21 @@
  * chunk of code. They can be created directly from strings
  * and are also implicitly convertible to strings
  */
-class ScriptCode
-{
+class ScriptCode {
 public:
   /// Empty code
   ScriptCode();
   /// Code from a C-string with zero offset
   explicit ScriptCode(const char *codeStr);
   /// Code from a C-string with a defined offset
-  ScriptCode(const char * codeStr, const int offset);
+  ScriptCode(const char *codeStr, const int offset);
   /// Code from a QString with zero offset
   explicit ScriptCode(const QString &codeStr);
   /// Code from a QString with a defined offset
-  ScriptCode(const QString & codeStr, const int offset);
+  ScriptCode(const QString &codeStr, const int offset);
 
   /// Code string
-  inline const std::string & codeString() const { return m_code; }
+  inline const std::string &codeString() const { return m_code; }
   /// Return the offset
   inline int offset() const { return m_offset; }
   /// Is the string empty
diff --git a/MantidPlot/src/ScriptFileInterpreter.cpp b/MantidPlot/src/ScriptFileInterpreter.cpp
index f9d83545f4bbc524ef15b524489f24016d55056d..842498a1337f8df1eb3a882400ad14f89008459e 100644
--- a/MantidPlot/src/ScriptFileInterpreter.cpp
+++ b/MantidPlot/src/ScriptFileInterpreter.cpp
@@ -223,9 +223,9 @@ inline void
 ScriptFileInterpreter::replaceSelectedText(const ScriptEditor *editor,
                                            const QString &text) {
   int UTF8_CodePage = 65001;
-  const char *b =
-      ((editor->SCI_GETCODEPAGE == UTF8_CodePage) ? text.toUtf8().constData()
-                                                  : text.toLatin1().constData());
+  const char *b = ((editor->SCI_GETCODEPAGE == UTF8_CodePage)
+                       ? text.toUtf8().constData()
+                       : text.toLatin1().constData());
   editor->SendScintilla(editor->SCI_REPLACESEL, b);
 }
 
diff --git a/MantidPlot/src/ScriptOutputDisplay.h b/MantidPlot/src/ScriptOutputDisplay.h
index e3fda016cef65727f8ebb6d68f57e932a9c9239a..9bc5acdb7768edc5f9551fe1120cc4bca2b9f6b0 100644
--- a/MantidPlot/src/ScriptOutputDisplay.h
+++ b/MantidPlot/src/ScriptOutputDisplay.h
@@ -7,8 +7,7 @@
  * Defines a "read-only" text area that can be used
  * to output messages
  */
-class ScriptOutputDisplay : public QTextEdit
-{
+class ScriptOutputDisplay : public QTextEdit {
   Q_OBJECT
 
 public:
@@ -20,35 +19,37 @@ public:
 
   /// Add actions applicable to an edit menu
   void populateEditMenu(QMenu &editMenu);
-  ///Capture key presses
+  /// Capture key presses
   void keyPressEvent(QKeyEvent *event) override;
-  //squash dragging ability
+  // squash dragging ability
   void mouseMoveEvent(QMouseEvent *e) override;
-  //prevent middle mouse clicks from pasting
+  // prevent middle mouse clicks from pasting
   void mouseReleaseEvent(QMouseEvent *e) override;
   /// capture ctrl_up or down to zoom
   void wheelEvent(QWheelEvent *e) override;
-  //sets the zoom to a specific level
+  // sets the zoom to a specific level
   void setZoom(int value);
   /// zooms the text size
-  void zoom(int range=1);
+  void zoom(int range = 1);
   /// returns the current zoom level
   int zoomLevel();
 public slots:
-  //zooms in, not called ZoomIn to avoid clashing with the base ZoomIn that does not work
-  void zoomUp();  
-  //zooms in, not called ZoomIn to avoid clashing with the base ZoomIn that does not work
+  // zooms in, not called ZoomIn to avoid clashing with the base ZoomIn that
+  // does not work
+  void zoomUp();
+  // zooms in, not called ZoomIn to avoid clashing with the base ZoomIn that
+  // does not work
   void zoomDown();
   /// Print the text within the window
   void print();
   /// Save the output to a file
-  void saveToFile(const QString & filename = "");
+  void saveToFile(const QString &filename = "");
   /// Display an output message that is not an error
-  void displayMessage(const QString & msg);
+  void displayMessage(const QString &msg);
   /// Display an output message with a timestamp & border
-  void displayMessageWithTimestamp(const QString & msg);
+  void displayMessageWithTimestamp(const QString &msg);
   /// Display an error message
-  void displayError(const QString & msg);
+  void displayError(const QString &msg);
 
 signals:
   /// Emitted when a zoom in is requested
@@ -58,7 +59,7 @@ signals:
 
 private slots:
   /// Context menu slot
-  void showContextMenu(const QPoint & pos);
+  void showContextMenu(const QPoint &pos);
 
 private:
   enum MessageType { Standard, Error };
@@ -67,7 +68,7 @@ private:
   /// Add the timestamp formatting
   QString addTimestamp(const QString &);
   /// Append new text
-  void appendText(const QString & txt);
+  void appendText(const QString &txt);
   /// Create the action pointers
   void initActions();
   /// Reset the default font
@@ -80,9 +81,9 @@ private:
   QAction *m_clear;
   /// Save action
   QAction *m_save;
-  ///original default font size
+  /// original default font size
   int m_origFontSize;
-  ///current zoom level
+  /// current zoom level
   int m_zoomLevel;
 };
 
diff --git a/MantidPlot/src/Scripted.cpp b/MantidPlot/src/Scripted.cpp
index f1068bb48f7bc1a75e53cd21650547a0ea8226e9..1e095b29b955d8aad17a622798861007311cd257 100644
--- a/MantidPlot/src/Scripted.cpp
+++ b/MantidPlot/src/Scripted.cpp
@@ -8,25 +8,20 @@
  * Constructor
  * @param env :: A pointer to a scripting environment
  */
-Scripted::Scripted(ScriptingEnv *env) :  m_scriptEnv(env)
-{
+Scripted::Scripted(ScriptingEnv *env) : m_scriptEnv(env) {
   m_scriptEnv->incref();
 }
 
 /**
  * Desuctor
  */
-Scripted::~Scripted()
-{
-  m_scriptEnv->decref();
-}
+Scripted::~Scripted() { m_scriptEnv->decref(); }
 
 /**
  * Called when the scripting environment changes
  * @param sce :: Scripting change event
  */
-void Scripted::scriptingChangeEvent(ScriptingChangeEvent *sce)
-{
+void Scripted::scriptingChangeEvent(ScriptingChangeEvent *sce) {
   m_scriptEnv->decref();
   sce->scriptingEnv()->incref();
   m_scriptEnv = sce->scriptingEnv();
diff --git a/MantidPlot/src/Scripted.h b/MantidPlot/src/Scripted.h
index 0a559847492653666afef403cf4aa99f4101620f..b068747f19fb516e8aae79cdfec4cabff9cb86ae 100644
--- a/MantidPlot/src/Scripted.h
+++ b/MantidPlot/src/Scripted.h
@@ -13,15 +13,16 @@
 class ScriptingEnv;
 
 /**
- * A custom event to notify an object that it should update its scripting environment
+ * A custom event to notify an object that it should update its scripting
+ * environment
  */
-class ScriptingChangeEvent : public QEvent
-{
+class ScriptingChangeEvent : public QEvent {
 public:
   explicit ScriptingChangeEvent(ScriptingEnv *e)
       : QEvent(SCRIPTING_CHANGE_EVENT), env(e) {}
   ScriptingEnv *scriptingEnv() const { return env; }
   Type type() const { return SCRIPTING_CHANGE_EVENT; }
+
 private:
   ScriptingEnv *env;
 };
@@ -33,19 +34,18 @@ private:
  * implement slot customEvent(QEvent*) such that it forwards any
  * ScriptingChangeEvents to Scripted::scriptingChangeEvent.
  */
-class Scripted
-{
-  public:
+class Scripted {
+public:
   /// Constructor
-  explicit Scripted(ScriptingEnv* env);
+  explicit Scripted(ScriptingEnv *env);
   /// Destructor
   ~Scripted();
   /// Called when the scripting environment changes
-  void scriptingChangeEvent(ScriptingChangeEvent*);
+  void scriptingChangeEvent(ScriptingChangeEvent *);
   /// Access the current environment
-  ScriptingEnv *scriptingEnv(){return m_scriptEnv;}
-  
-  private:
+  ScriptingEnv *scriptingEnv() { return m_scriptEnv; }
+
+private:
   Scripted();
   /// A pointer to the current environment
   ScriptingEnv *m_scriptEnv;
diff --git a/MantidPlot/src/ScriptingEnv.h b/MantidPlot/src/ScriptingEnv.h
index 217d9858d78c099f15078aad5375be721399f0fe..59e384f2a0a3b87ef6edef191c744508b1a8204b 100644
--- a/MantidPlot/src/ScriptingEnv.h
+++ b/MantidPlot/src/ScriptingEnv.h
@@ -47,66 +47,76 @@ class QsciLexer;
  * A ScriptingEnv object represents a running interpreter. It can create
  * script objects that execute arbitrary strings of code.
  */
-class ScriptingEnv : public QObject
-{
+class ScriptingEnv : public QObject {
   Q_OBJECT
 
-  public:
-  ///Constructor
-  ScriptingEnv(ApplicationWindow *parent, const QString & langName);
+public:
+  /// Constructor
+  ScriptingEnv(ApplicationWindow *parent, const QString &langName);
   /// Destructor
   ~ScriptingEnv() override;
   /// Start the environment
   bool initialize();
-  /// Shutdown the environment in a more controlled manner than the destructor allows
+  /// Shutdown the environment in a more controlled manner than the destructor
+  /// allows
   void finalize();
 
   /// Is the environment initialized
   bool isInitialized() const { return d_initialized; }
 
   /// If the environment supports it, set the system arguments
-  virtual void setSysArgs(const QStringList & args) = 0;
+  virtual void setSysArgs(const QStringList &args) = 0;
 
   /// Create a script object that is responsible for executing actual code
-  virtual Script *newScript(const QString &name, QObject * context, const Script::InteractionType interact) const = 0;
+  virtual Script *newScript(const QString &name, QObject *context,
+                            const Script::InteractionType interact) const = 0;
 
   //! If an exception / error occured, return a nicely formated stack backtrace.
   virtual QString stackTraceString() { return QString::null; }
-  /// Return a list of supported mathematical functions. These should be imported into the global namespace.
+  /// Return a list of supported mathematical functions. These should be
+  /// imported into the global namespace.
   virtual const QStringList mathFunctions() const { return QStringList(); }
   /// Return a documentation string for the given mathematical function.
-  virtual const QString mathFunctionDoc(const QString&) const { return QString::null; }
+  virtual const QString mathFunctionDoc(const QString &) const {
+    return QString::null;
+  }
   /// Return a list of file extensions commonly used for this language.
   virtual const QStringList fileExtensions() const { return QStringList(); }
-  /// Construct a filter expression from fileExtension(), suitable for QFileDialog.
+  /// Construct a filter expression from fileExtension(), suitable for
+  /// QFileDialog.
   const QString fileFilter() const;
   /// Return the name of the scripting language supported by this environment
   const QString languageName() const;
-  /// If the environment supports evaluation as well as execution then override and return true
+  /// If the environment supports evaluation as well as execution then override
+  /// and return true
   virtual bool supportsEvaluation() { return false; }
   ///  Is progress reporting supported
   virtual bool supportsProgressReporting() const { return false; }
   /// Does this support abort requests?
   virtual bool supportsAbortRequests() const { return false; }
-  /// Create a code lexer for this environment, can be NULL. Ownership of a created object
+  /// Create a code lexer for this environment, can be NULL. Ownership of a
+  /// created object
   /// is transferred to the caller.
-  virtual QsciLexer * createCodeLexer() const { return NULL; }
+  virtual QsciLexer *createCodeLexer() const { return NULL; }
 
   virtual void redirectStdOut(bool) {}
 
 public slots:
   /// Set a reference to a QObject in the global scope
-  virtual bool setQObject(QObject*, const char*) { return false; }
+  virtual bool setQObject(QObject *, const char *) { return false; }
   /// Set a reference to an integer in the global scope
-  virtual bool setInt(int, const char*) { return false; }
+  virtual bool setInt(int, const char *) { return false; }
   /// Set a reference to a double  in the global scope
-  virtual bool setDouble(double, const char*) { return false; }
+  virtual bool setDouble(double, const char *) { return false; }
 
-  /// Clear the global environment. What exactly happens depends on the implementation.
+  /// Clear the global environment. What exactly happens depends on the
+  /// implementation.
   virtual void clear() {}
-  /// Increase the reference count. This should only be called by Scripted and Script to avoid memory leaks.
+  /// Increase the reference count. This should only be called by Scripted and
+  /// Script to avoid memory leaks.
   void incref();
-  /// Decrease the reference count. This should only be called by Scripted and Script to avoid segfaults.
+  /// Decrease the reference count. This should only be called by Scripted and
+  /// Script to avoid segfaults.
   void decref();
 
 signals:
@@ -115,9 +125,9 @@ signals:
   /// Stopping
   void shuttingDown();
   /// signal an error condition / exception
-  void error(const QString & message, const QString & scriptName, int lineNumber);
+  void error(const QString &message, const QString &scriptName, int lineNumber);
   /// output that is not handled by a Script
-  void print(const QString & output);
+  void print(const QString &output);
 
 protected:
   /// Override to perform some initialisation code
@@ -125,8 +135,7 @@ protected:
   /// Override to perform shutdown code
   virtual void shutdown() {}
   /// Set that a script is being executed
-   void setIsRunning(bool running) { m_is_running = running; }
-
+  void setIsRunning(bool running) { m_is_running = running; }
 
   /// whether the interpreter has been successfully initialized
   bool d_initialized;
@@ -147,12 +156,12 @@ private:
 /**
  * Keeps a static list of available interpreters and instantiates them on demand
  */
-class ScriptingLangManager
-{
+class ScriptingLangManager {
 public:
   /// Return an instance of the first implementation we can find.
   static ScriptingEnv *newEnv(ApplicationWindow *parent);
-  /// Return an instance of the implementation specified by name, NULL on failure.
+  /// Return an instance of the implementation specified by name, NULL on
+  /// failure.
   static ScriptingEnv *newEnv(const QString &name, ApplicationWindow *parent);
   /// Return the names of available implementations.
   static QStringList languages();
@@ -160,7 +169,7 @@ public:
   static int numLanguages();
 
 private:
-  typedef ScriptingEnv*(*ScriptingEnvConstructor)(ApplicationWindow*);
+  typedef ScriptingEnv *(*ScriptingEnvConstructor)(ApplicationWindow *);
   typedef struct {
     const char *name;
     ScriptingEnvConstructor constructor;
diff --git a/MantidPlot/src/ScriptingLangDialog.cpp b/MantidPlot/src/ScriptingLangDialog.cpp
index 90e965dd787cbfb8a175a4426ce7803f5def92c9..d24ac5159291b9ebe1719b1e280128e7e2db4833 100644
--- a/MantidPlot/src/ScriptingLangDialog.cpp
+++ b/MantidPlot/src/ScriptingLangDialog.cpp
@@ -1,11 +1,11 @@
 /***************************************************************************
-	File                 : ScriptingLangDialog.cpp
-	Project              : QtiPlot
+        File                 : ScriptingLangDialog.cpp
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Knut Franke, Ion Vasilief
-	Email (use @ for *)  : knut.franke*gmx.de, ion_vasilief*yahoo.fr
-	Description          : Dialog for changing the current scripting
-	                       language
+        Copyright            : (C) 2006 by Knut Franke, Ion Vasilief
+        Email (use @ for *)  : knut.franke*gmx.de, ion_vasilief*yahoo.fr
+        Description          : Dialog for changing the current scripting
+                               language
 
 ***************************************************************************/
 
@@ -35,10 +35,11 @@
 #include <QLayout>
 #include <QMessageBox>
 
-ScriptingLangDialog::ScriptingLangDialog(ScriptingEnv *env, ApplicationWindow *parent, Qt::WFlags fl )
-  : QDialog(parent, fl), Scripted(env)
-{
-        setWindowTitle(tr("MantidPlot - Select scripting language"));
+ScriptingLangDialog::ScriptingLangDialog(ScriptingEnv *env,
+                                         ApplicationWindow *parent,
+                                         Qt::WFlags fl)
+    : QDialog(parent, fl), Scripted(env) {
+  setWindowTitle(tr("MantidPlot - Select scripting language"));
 
   langList = new QListWidget(this);
 
@@ -56,24 +57,23 @@ ScriptingLangDialog::ScriptingLangDialog(ScriptingEnv *env, ApplicationWindow *p
 
   connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
   connect(btnCancel, SIGNAL(clicked()), this, SLOT(close()));
-  connect(langList, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(accept()));
+  connect(langList, SIGNAL(itemActivated(QListWidgetItem *)), this,
+          SLOT(accept()));
 
   updateLangList();
 }
 
-void ScriptingLangDialog::updateLangList()
-{
+void ScriptingLangDialog::updateLangList() {
   langList->clear();
   langList->insertItems(0, ScriptingLangManager::languages());
-  QListWidgetItem *current = langList->findItems(scriptingEnv()->objectName(), Qt::MatchExactly).first();
+  QListWidgetItem *current = langList->findItems(scriptingEnv()->objectName(),
+                                                 Qt::MatchExactly).first();
   if (current)
     langList->setCurrentItem(current);
 }
 
-void ScriptingLangDialog::accept()
-{
-  ApplicationWindow *app = static_cast<ApplicationWindow*>(parent());
+void ScriptingLangDialog::accept() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent());
   if (app->setScriptingLanguage(langList->currentItem()->text()))
-	close();
+    close();
 }
-
diff --git a/MantidPlot/src/ScriptingLangDialog.h b/MantidPlot/src/ScriptingLangDialog.h
index 15b9c947d64fe46e4b80a68b626f87a943e65927..f6902cd6c810a3d8a25b86d71785a2054509f9f0 100644
--- a/MantidPlot/src/ScriptingLangDialog.h
+++ b/MantidPlot/src/ScriptingLangDialog.h
@@ -1,11 +1,11 @@
 /***************************************************************************
-	File                 : ScriptingLangDialog.h
-	Project              : QtiPlot
+        File                 : ScriptingLangDialog.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Knut Franke, Ion Vasilief
-	Email (use @ for *)  : knut.franke*gmx.de, ion_vasilief*yahoo.fr
-	Description          : Dialog for changing the current scripting
-	                       language
+        Copyright            : (C) 2006 by Knut Franke, Ion Vasilief
+        Email (use @ for *)  : knut.franke*gmx.de, ion_vasilief*yahoo.fr
+        Description          : Dialog for changing the current scripting
+                               language
 
  ***************************************************************************/
 
@@ -39,13 +39,13 @@ class ApplicationWindow;
 class QListWidget;
 class QPushButton;
 
-class ScriptingLangDialog: public QDialog, public Scripted
-{
+class ScriptingLangDialog : public QDialog, public Scripted {
   Q_OBJECT
-  
-  public:
-  ScriptingLangDialog(ScriptingEnv *env, ApplicationWindow *parent, Qt::WFlags fl = 0);
-										      
+
+public:
+  ScriptingLangDialog(ScriptingEnv *env, ApplicationWindow *parent,
+                      Qt::WFlags fl = 0);
+
 public slots:
   void updateLangList();
   void accept() override;
@@ -56,4 +56,3 @@ private:
 };
 
 #endif
-
diff --git a/MantidPlot/src/ScriptingWindow.h b/MantidPlot/src/ScriptingWindow.h
index 98fa26fc26c651a72ef7378d350ada046c5d8896..c4575a1810f5fe9816a0ad9de55d05937e9422f1 100644
--- a/MantidPlot/src/ScriptingWindow.h
+++ b/MantidPlot/src/ScriptingWindow.h
@@ -172,8 +172,8 @@ private:
   QMenu *m_windowMenu;
   /// Window actions
   QAction *m_alwaysOnTop, *m_hide, *m_zoomIn, *m_zoomOut, *m_resetZoom,
-      *m_toggleProgress, *m_toggleFolding, *m_toggleWrapping, *m_toggleWhitespace,
-      *m_openConfigTabs, *m_selectFont;
+      *m_toggleProgress, *m_toggleFolding, *m_toggleWrapping,
+      *m_toggleWhitespace, *m_openConfigTabs, *m_selectFont;
   /// Help menu
   QMenu *m_helpMenu;
   /// Help actions
diff --git a/MantidPlot/src/SelectionMoveResizer.cpp b/MantidPlot/src/SelectionMoveResizer.cpp
index a86ca49030f5aa3bb5ccdddbfe9ad9129c118b87..a13608f17b92629b40245a554b174a03e1095ed5 100644
--- a/MantidPlot/src/SelectionMoveResizer.cpp
+++ b/MantidPlot/src/SelectionMoveResizer.cpp
@@ -41,478 +41,473 @@
 #include "ImageMarker.h"
 
 SelectionMoveResizer::SelectionMoveResizer(LegendWidget *target)
-	: QWidget(target->parentWidget())
-{
-	init();
-	add(target);
+    : QWidget(target->parentWidget()) {
+  init();
+  add(target);
 }
 SelectionMoveResizer::SelectionMoveResizer(ArrowMarker *target)
-	: QWidget(target->plot()->canvas())
-{
-	init();
-	add(target);
+    : QWidget(target->plot()->canvas()) {
+  init();
+  add(target);
 }
 SelectionMoveResizer::SelectionMoveResizer(ImageMarker *target)
-	: QWidget(target->plot()->canvas())
-{
-	init();
-	add(target);
+    : QWidget(target->plot()->canvas()) {
+  init();
+  add(target);
 }
 
 SelectionMoveResizer::SelectionMoveResizer(QWidget *target)
-	: QWidget(target->parentWidget())
-{
-	init();
-	add(target);
+    : QWidget(target->parentWidget()) {
+  init();
+  add(target);
 }
 
-void SelectionMoveResizer::init()
-{
-	d_bounding_rect = QRect(0,0,-1,-1);
-	d_op = None;
-	d_op_start = QPoint(0,0);
-	d_op_dp = QPoint(0,0);
-
-    setAttribute(Qt::WA_DeleteOnClose);
-	setGeometry(0, 0, parentWidget()->width(), parentWidget()->height());
-	setMouseTracking(true);
-	parentWidget()->installEventFilter(this);
-	show();
-	setFocus();
+void SelectionMoveResizer::init() {
+  d_bounding_rect = QRect(0, 0, -1, -1);
+  d_op = None;
+  d_op_start = QPoint(0, 0);
+  d_op_dp = QPoint(0, 0);
+
+  setAttribute(Qt::WA_DeleteOnClose);
+  setGeometry(0, 0, parentWidget()->width(), parentWidget()->height());
+  setMouseTracking(true);
+  parentWidget()->installEventFilter(this);
+  show();
+  setFocus();
 }
 
-SelectionMoveResizer::~SelectionMoveResizer()
-{
-	parentWidget()->removeEventFilter(this);
+SelectionMoveResizer::~SelectionMoveResizer() {
+  parentWidget()->removeEventFilter(this);
 }
 
-void SelectionMoveResizer::add(LegendWidget *target)
-{
-	if (target->parentWidget() != parent())
-		return;
-	d_legend_markers << target;
-	target->installEventFilter(this);
-	connect(target, SIGNAL(destroyed(QObject*)), this, SLOT(removeLegend(QObject*)));
+void SelectionMoveResizer::add(LegendWidget *target) {
+  if (target->parentWidget() != parent())
+    return;
+  d_legend_markers << target;
+  target->installEventFilter(this);
+  connect(target, SIGNAL(destroyed(QObject *)), this,
+          SLOT(removeLegend(QObject *)));
 
-	if (d_bounding_rect.isValid())
-		d_bounding_rect |= target->geometry();
-	else
-		d_bounding_rect = target->geometry();
+  if (d_bounding_rect.isValid())
+    d_bounding_rect |= target->geometry();
+  else
+    d_bounding_rect = target->geometry();
 
-	update();
+  update();
 }
 
-void SelectionMoveResizer::add(ArrowMarker *target)
-{
-	if (target->plot()->canvas() != parent())
-		return;
-	d_line_markers << target;
+void SelectionMoveResizer::add(ArrowMarker *target) {
+  if (target->plot()->canvas() != parent())
+    return;
+  d_line_markers << target;
 
-	if (d_bounding_rect.isValid())
-		d_bounding_rect |= target->rect();
-	else
-		d_bounding_rect = target->rect();
+  if (d_bounding_rect.isValid())
+    d_bounding_rect |= target->rect();
+  else
+    d_bounding_rect = target->rect();
 
-	update();
+  update();
 }
-void SelectionMoveResizer::add(ImageMarker *target)
-{
-	if (target->plot()->canvas() != parent())
-		return;
-	d_image_markers << target;
-
-	if (d_bounding_rect.isValid())
-		d_bounding_rect |= target->rect();
-	else
-		d_bounding_rect = target->rect();
-
-	update();
+void SelectionMoveResizer::add(ImageMarker *target) {
+  if (target->plot()->canvas() != parent())
+    return;
+  d_image_markers << target;
+
+  if (d_bounding_rect.isValid())
+    d_bounding_rect |= target->rect();
+  else
+    d_bounding_rect = target->rect();
+
+  update();
 }
 
-void SelectionMoveResizer::add(QWidget *target)
-{
-	if (target->parentWidget() != parent())
-		return;
-	d_widgets << target;
-	target->installEventFilter(this);
-	connect(target, SIGNAL(destroyed(QObject*)), this, SLOT(removeWidget(QObject*)));
+void SelectionMoveResizer::add(QWidget *target) {
+  if (target->parentWidget() != parent())
+    return;
+  d_widgets << target;
+  target->installEventFilter(this);
+  connect(target, SIGNAL(destroyed(QObject *)), this,
+          SLOT(removeWidget(QObject *)));
 
-	if (d_bounding_rect.isValid())
-		d_bounding_rect |= target->frameGeometry();
-	else
-		d_bounding_rect = target->frameGeometry();
+  if (d_bounding_rect.isValid())
+    d_bounding_rect |= target->frameGeometry();
+  else
+    d_bounding_rect = target->frameGeometry();
 
-	update();
+  update();
 }
 
-int SelectionMoveResizer::removeAll(LegendWidget *target)
-{
-	int result = d_legend_markers.removeAll(target);
-	if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() && d_image_markers.isEmpty() && d_widgets.isEmpty())
-		delete this;
-	else
-		recalcBoundingRect();
-	return result;
+int SelectionMoveResizer::removeAll(LegendWidget *target) {
+  int result = d_legend_markers.removeAll(target);
+  if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() &&
+      d_image_markers.isEmpty() && d_widgets.isEmpty())
+    delete this;
+  else
+    recalcBoundingRect();
+  return result;
 }
-int SelectionMoveResizer::removeAll(ArrowMarker *target)
-{
-	int result = d_line_markers.removeAll(target);
-	if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() && d_image_markers.isEmpty() && d_widgets.isEmpty())
-		delete this;
-	else
-		recalcBoundingRect();
-	return result;
+int SelectionMoveResizer::removeAll(ArrowMarker *target) {
+  int result = d_line_markers.removeAll(target);
+  if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() &&
+      d_image_markers.isEmpty() && d_widgets.isEmpty())
+    delete this;
+  else
+    recalcBoundingRect();
+  return result;
 }
-int SelectionMoveResizer::removeAll(ImageMarker *target)
-{
-	int result = d_image_markers.removeAll(target);
-	if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() && d_image_markers.isEmpty() && d_widgets.isEmpty())
-		delete this;
-	else
-		recalcBoundingRect();
-	return result;
+int SelectionMoveResizer::removeAll(ImageMarker *target) {
+  int result = d_image_markers.removeAll(target);
+  if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() &&
+      d_image_markers.isEmpty() && d_widgets.isEmpty())
+    delete this;
+  else
+    recalcBoundingRect();
+  return result;
 }
 
-int SelectionMoveResizer::removeAll(QWidget *target)
-{
-	int result = d_widgets.removeAll(target);
-	if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() && d_image_markers.isEmpty() && d_widgets.isEmpty())
-		delete this;
-	else
-		recalcBoundingRect();
-	return result;
+int SelectionMoveResizer::removeAll(QWidget *target) {
+  int result = d_widgets.removeAll(target);
+  if (d_legend_markers.isEmpty() && d_line_markers.isEmpty() &&
+      d_image_markers.isEmpty() && d_widgets.isEmpty())
+    delete this;
+  else
+    recalcBoundingRect();
+  return result;
 }
 
-void SelectionMoveResizer::recalcBoundingRect()
-{
-	d_bounding_rect = QRect(0, 0, -1, -1);
-
-	foreach(LegendWidget *i, d_legend_markers) {
-		if(d_bounding_rect.isValid())
-			d_bounding_rect |= i->geometry();
-		else
-			d_bounding_rect = i->geometry();
-	}
-	foreach(ArrowMarker *i, d_line_markers) {
-		if(d_bounding_rect.isValid())
-			d_bounding_rect |= i->rect();
-		else
-			d_bounding_rect = i->rect();
-	}
-	foreach(ImageMarker *i, d_image_markers) {
-		if(d_bounding_rect.isValid())
-			d_bounding_rect |= i->rect();
-		else
-			d_bounding_rect = i->rect();
-	}
-	foreach(QWidget *i, d_widgets) {
-		if(d_bounding_rect.isValid())
-			d_bounding_rect |= i->frameGeometry();
-		else
-			d_bounding_rect = i->frameGeometry();
-	}
-
-	update();
+void SelectionMoveResizer::recalcBoundingRect() {
+  d_bounding_rect = QRect(0, 0, -1, -1);
+
+  foreach (LegendWidget *i, d_legend_markers) {
+    if (d_bounding_rect.isValid())
+      d_bounding_rect |= i->geometry();
+    else
+      d_bounding_rect = i->geometry();
+  }
+  foreach (ArrowMarker *i, d_line_markers) {
+    if (d_bounding_rect.isValid())
+      d_bounding_rect |= i->rect();
+    else
+      d_bounding_rect = i->rect();
+  }
+  foreach (ImageMarker *i, d_image_markers) {
+    if (d_bounding_rect.isValid())
+      d_bounding_rect |= i->rect();
+    else
+      d_bounding_rect = i->rect();
+  }
+  foreach (QWidget *i, d_widgets) {
+    if (d_bounding_rect.isValid())
+      d_bounding_rect |= i->frameGeometry();
+    else
+      d_bounding_rect = i->frameGeometry();
+  }
+
+  update();
 }
 
-const QRect SelectionMoveResizer::handlerRect(QRect rect, Operation op)
-{
-	switch(op) {
-		case Resize_N:
-			return QRect( QPoint(rect.center().x()-handler_size/2, rect.top()),
-					QSize(handler_size,handler_size));
-		case Resize_NE:
-			return QRect( QPoint(rect.right()-handler_size+1, rect.top()),
-				QSize(handler_size,handler_size));
-		case Resize_E:
-			return QRect( QPoint(rect.right()-handler_size+1, rect.center().y()-handler_size/2),
-					QSize(handler_size,handler_size));
-		case Resize_SE:
-			return QRect( QPoint(rect.right()-handler_size+1, rect.bottom()-handler_size+1),
-					QSize(handler_size,handler_size));
-		case Resize_S:
-			return QRect( QPoint(rect.center().x()-handler_size/2, rect.bottom()-handler_size+1),
-					QSize(handler_size,handler_size));
-		case Resize_SW:
-			return QRect( QPoint(rect.left(),rect.bottom()-handler_size+1),
-					QSize(handler_size,handler_size));
-		case Resize_W:
-			return QRect( QPoint(rect.left(), rect.center().y()-handler_size/2),
-					QSize(handler_size,handler_size));
-		case Resize_NW:
-			return QRect( rect.topLeft(),
-					QSize(handler_size,handler_size));
-		default:
-			return QRect( rect.topLeft(), QSize(0,0));
-	}
+const QRect SelectionMoveResizer::handlerRect(QRect rect, Operation op) {
+  switch (op) {
+  case Resize_N:
+    return QRect(QPoint(rect.center().x() - handler_size / 2, rect.top()),
+                 QSize(handler_size, handler_size));
+  case Resize_NE:
+    return QRect(QPoint(rect.right() - handler_size + 1, rect.top()),
+                 QSize(handler_size, handler_size));
+  case Resize_E:
+    return QRect(QPoint(rect.right() - handler_size + 1,
+                        rect.center().y() - handler_size / 2),
+                 QSize(handler_size, handler_size));
+  case Resize_SE:
+    return QRect(QPoint(rect.right() - handler_size + 1,
+                        rect.bottom() - handler_size + 1),
+                 QSize(handler_size, handler_size));
+  case Resize_S:
+    return QRect(QPoint(rect.center().x() - handler_size / 2,
+                        rect.bottom() - handler_size + 1),
+                 QSize(handler_size, handler_size));
+  case Resize_SW:
+    return QRect(QPoint(rect.left(), rect.bottom() - handler_size + 1),
+                 QSize(handler_size, handler_size));
+  case Resize_W:
+    return QRect(QPoint(rect.left(), rect.center().y() - handler_size / 2),
+                 QSize(handler_size, handler_size));
+  case Resize_NW:
+    return QRect(rect.topLeft(), QSize(handler_size, handler_size));
+  default:
+    return QRect(rect.topLeft(), QSize(0, 0));
+  }
 }
 
-QRect SelectionMoveResizer::operateOn(const QRect &in)
-{
-	QRect boundary_out = d_bounding_rect;
-	switch (d_op) {
-		case Move:
-			boundary_out.translate(d_op_dp);
-			break;
-		case Resize_N:
-			boundary_out.setTop(boundary_out.top()+d_op_dp.y());
-			break;
-		case Resize_E:
-			boundary_out.setRight(boundary_out.right()+d_op_dp.x());
-			break;
-		case Resize_S:
-			boundary_out.setBottom(boundary_out.bottom()+d_op_dp.y());
-			break;
-		case Resize_W:
-			boundary_out.setLeft(boundary_out.left()+d_op_dp.x());
-			break;
-		case Resize_NE:
-			boundary_out.setTop(boundary_out.top()+d_op_dp.y());
-			boundary_out.setRight(boundary_out.right()+d_op_dp.x());
-			break;
-		case Resize_SE:
-			boundary_out.setBottom(boundary_out.bottom()+d_op_dp.y());
-			boundary_out.setRight(boundary_out.right()+d_op_dp.x());
-			break;
-		case Resize_SW:
-			boundary_out.setBottom(boundary_out.bottom()+d_op_dp.y());
-			boundary_out.setLeft(boundary_out.left()+d_op_dp.x());
-			break;
-		case Resize_NW:
-			boundary_out.setTop(boundary_out.top()+d_op_dp.y());
-			boundary_out.setLeft(boundary_out.left()+d_op_dp.x());
-			break;
-		default:
-			return in;
-	}
-	boundary_out = boundary_out.normalized();
-	if (in == d_bounding_rect)
-		return boundary_out;
-	double scale_x = ((double)boundary_out.width())/d_bounding_rect.width();
-	double scale_y = ((double)boundary_out.height())/d_bounding_rect.height();
-	int offset_x = qRound(boundary_out.left()-d_bounding_rect.left()*scale_x);
-	int offset_y = qRound(boundary_out.top()-d_bounding_rect.top()*scale_y);
-	return QRect(QPoint(qRound(in.left()*scale_x)+offset_x, qRound(in.top()*scale_y)+offset_y),
-			QSize(qRound(in.width()*scale_x), qRound(in.height()*scale_y)));
+QRect SelectionMoveResizer::operateOn(const QRect &in) {
+  QRect boundary_out = d_bounding_rect;
+  switch (d_op) {
+  case Move:
+    boundary_out.translate(d_op_dp);
+    break;
+  case Resize_N:
+    boundary_out.setTop(boundary_out.top() + d_op_dp.y());
+    break;
+  case Resize_E:
+    boundary_out.setRight(boundary_out.right() + d_op_dp.x());
+    break;
+  case Resize_S:
+    boundary_out.setBottom(boundary_out.bottom() + d_op_dp.y());
+    break;
+  case Resize_W:
+    boundary_out.setLeft(boundary_out.left() + d_op_dp.x());
+    break;
+  case Resize_NE:
+    boundary_out.setTop(boundary_out.top() + d_op_dp.y());
+    boundary_out.setRight(boundary_out.right() + d_op_dp.x());
+    break;
+  case Resize_SE:
+    boundary_out.setBottom(boundary_out.bottom() + d_op_dp.y());
+    boundary_out.setRight(boundary_out.right() + d_op_dp.x());
+    break;
+  case Resize_SW:
+    boundary_out.setBottom(boundary_out.bottom() + d_op_dp.y());
+    boundary_out.setLeft(boundary_out.left() + d_op_dp.x());
+    break;
+  case Resize_NW:
+    boundary_out.setTop(boundary_out.top() + d_op_dp.y());
+    boundary_out.setLeft(boundary_out.left() + d_op_dp.x());
+    break;
+  default:
+    return in;
+  }
+  boundary_out = boundary_out.normalized();
+  if (in == d_bounding_rect)
+    return boundary_out;
+  double scale_x = ((double)boundary_out.width()) / d_bounding_rect.width();
+  double scale_y = ((double)boundary_out.height()) / d_bounding_rect.height();
+  int offset_x = qRound(boundary_out.left() - d_bounding_rect.left() * scale_x);
+  int offset_y = qRound(boundary_out.top() - d_bounding_rect.top() * scale_y);
+  return QRect(
+      QPoint(qRound(in.left() * scale_x) + offset_x,
+             qRound(in.top() * scale_y) + offset_y),
+      QSize(qRound(in.width() * scale_x), qRound(in.height() * scale_y)));
 }
 
-void SelectionMoveResizer::operateOnTargets()
-{
-	foreach(LegendWidget *i, d_legend_markers) {
-		QRect new_rect = operateOn(i->geometry());
-		i->setFixedCoordinatesMode(false);//make sure that we could move the legend by hand
-		i->move(new_rect.topLeft());
-		if (!i->text().isEmpty()){
-            QFont f = i->font();
-            f.setPointSize(f.pointSize() * new_rect.width() * new_rect.height()/(i->rect().width() * i->rect().height()));
-            i->setFont(f);
-            i->repaint();
-            (static_cast<Graph *>(i->parent()->parent()))->notifyFontChange(f);
-		}
-	}
-
-	foreach(ArrowMarker *i, d_line_markers) {
-		QPoint p1 = i->startPoint();
-		QPoint p2 = i->endPoint();
-		QRect new_rect = operateOn(i->rect());
-		i->setStartPoint(QPoint(
-					p1.x()<p2.x() ? new_rect.left() : new_rect.right(),
-					p1.y()<p2.y() ? new_rect.top() : new_rect.bottom() ));
-		i->setEndPoint(QPoint(
-					p2.x()<p1.x() ? new_rect.left() : new_rect.right(),
-					p2.y()<p1.y() ? new_rect.top() : new_rect.bottom() ));
-	}
-
-	foreach(ImageMarker *i, d_image_markers) {
-		QRect new_rect = operateOn(i->rect());
-		i->setOrigin(new_rect.topLeft());
-		i->setSize(new_rect.size());
-	}
-
-	foreach(QWidget *i, d_widgets)
-		i->setGeometry(operateOn(i->geometry()));
-
-	recalcBoundingRect();
-
-	d_op_start = d_op_dp = QPoint(0,0);
-
-	update();
-	emit targetsChanged();
+void SelectionMoveResizer::operateOnTargets() {
+  foreach (LegendWidget *i, d_legend_markers) {
+    QRect new_rect = operateOn(i->geometry());
+    i->setFixedCoordinatesMode(
+        false); // make sure that we could move the legend by hand
+    i->move(new_rect.topLeft());
+    if (!i->text().isEmpty()) {
+      QFont f = i->font();
+      f.setPointSize(f.pointSize() * new_rect.width() * new_rect.height() /
+                     (i->rect().width() * i->rect().height()));
+      i->setFont(f);
+      i->repaint();
+      (static_cast<Graph *>(i->parent()->parent()))->notifyFontChange(f);
+    }
+  }
+
+  foreach (ArrowMarker *i, d_line_markers) {
+    QPoint p1 = i->startPoint();
+    QPoint p2 = i->endPoint();
+    QRect new_rect = operateOn(i->rect());
+    i->setStartPoint(
+        QPoint(p1.x() < p2.x() ? new_rect.left() : new_rect.right(),
+               p1.y() < p2.y() ? new_rect.top() : new_rect.bottom()));
+    i->setEndPoint(
+        QPoint(p2.x() < p1.x() ? new_rect.left() : new_rect.right(),
+               p2.y() < p1.y() ? new_rect.top() : new_rect.bottom()));
+  }
+
+  foreach (ImageMarker *i, d_image_markers) {
+    QRect new_rect = operateOn(i->rect());
+    i->setOrigin(new_rect.topLeft());
+    i->setSize(new_rect.size());
+  }
+
+  foreach (QWidget *i, d_widgets)
+    i->setGeometry(operateOn(i->geometry()));
+
+  recalcBoundingRect();
+
+  d_op_start = d_op_dp = QPoint(0, 0);
+
+  update();
+  emit targetsChanged();
 }
 
-void SelectionMoveResizer::paintEvent(QPaintEvent *e)
-{
-	QPainter p(this);
-	QRect drawn_rect = operateOn(d_bounding_rect);
-
-	QPen white_pen(Qt::white, 3, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
-	p.setPen(white_pen);
-	p.drawRect(QRect(QPoint(drawn_rect.left(), drawn_rect.top()), drawn_rect.size()));
-	white_pen.setWidth(2); p.setPen(white_pen);
-	for (int i=0; i<8; i++)
-		p.drawRect(handlerRect(drawn_rect, (Operation)i));
-	p.setPen(QPen(Qt::black,1,Qt::SolidLine));
-	p.drawRect(QRect(QPoint(drawn_rect.left(), drawn_rect.top()), drawn_rect.size()));
-	for (int i=0; i<8; i++)
-		p.fillRect(handlerRect(drawn_rect, (Operation)i), QBrush(Qt::black));
-
-	e->accept();
+void SelectionMoveResizer::paintEvent(QPaintEvent *e) {
+  QPainter p(this);
+  QRect drawn_rect = operateOn(d_bounding_rect);
+
+  QPen white_pen(Qt::white, 3, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
+  p.setPen(white_pen);
+  p.drawRect(
+      QRect(QPoint(drawn_rect.left(), drawn_rect.top()), drawn_rect.size()));
+  white_pen.setWidth(2);
+  p.setPen(white_pen);
+  for (int i = 0; i < 8; i++)
+    p.drawRect(handlerRect(drawn_rect, (Operation)i));
+  p.setPen(QPen(Qt::black, 1, Qt::SolidLine));
+  p.drawRect(
+      QRect(QPoint(drawn_rect.left(), drawn_rect.top()), drawn_rect.size()));
+  for (int i = 0; i < 8; i++)
+    p.fillRect(handlerRect(drawn_rect, (Operation)i), QBrush(Qt::black));
+
+  e->accept();
 }
 
-void SelectionMoveResizer::mousePressEvent(QMouseEvent *me)
-{
-	if (me->button() == Qt::RightButton) {
-		// If one of the parents' event handlers deletes me, Qt crashes while trying to send the QContextMenuEvent.
-		foreach(LegendWidget *l, d_legend_markers){
-			if(l->geometry().contains(me->pos()))
-				return l->showContextMenu();
-		}
-		me->accept();
-		return;
-	}
-	if (me->button() != Qt::LeftButton || !d_bounding_rect.contains(me->pos())) {
-		me->ignore();
-		return;
-	}
-	d_op_start = me->pos();
-	d_op = Move;
-	for (int i=0; i<8; i++)
-		if (handlerRect(d_bounding_rect, (Operation)i).contains(d_op_start)) {
-			d_op = (Operation)i;
-			break;
-		}
-
-	me->accept();
+void SelectionMoveResizer::mousePressEvent(QMouseEvent *me) {
+  if (me->button() == Qt::RightButton) {
+    // If one of the parents' event handlers deletes me, Qt crashes while trying
+    // to send the QContextMenuEvent.
+    foreach (LegendWidget *l, d_legend_markers) {
+      if (l->geometry().contains(me->pos()))
+        return l->showContextMenu();
+    }
+    me->accept();
+    return;
+  }
+  if (me->button() != Qt::LeftButton || !d_bounding_rect.contains(me->pos())) {
+    me->ignore();
+    return;
+  }
+  d_op_start = me->pos();
+  d_op = Move;
+  for (int i = 0; i < 8; i++)
+    if (handlerRect(d_bounding_rect, (Operation)i).contains(d_op_start)) {
+      d_op = (Operation)i;
+      break;
+    }
+
+  me->accept();
 }
 
-void SelectionMoveResizer::mouseMoveEvent(QMouseEvent *me)
-{
-	if (d_op == None && d_bounding_rect.contains(me->pos()) && me->button() == Qt::LeftButton) {
-		d_op = Move;
-		d_op_start = me->pos();
-	}
-	if (d_op == None || d_op_start == QPoint(-1,-1)) {
-		if (d_bounding_rect.contains(me->pos())) {
-			setCursor(Qt::SizeAllCursor);
-			if (handlerRect(d_bounding_rect, Resize_N).contains(me->pos()) || handlerRect(d_bounding_rect, Resize_S).contains(me->pos()))
-				setCursor(Qt::SizeVerCursor);
-			else if (handlerRect(d_bounding_rect, Resize_E).contains(me->pos()) || handlerRect(d_bounding_rect, Resize_W).contains(me->pos()))
-				setCursor(Qt::SizeHorCursor);
-			else if (handlerRect(d_bounding_rect, Resize_NE).contains(me->pos()) || handlerRect(d_bounding_rect, Resize_SW).contains(me->pos()))
-				setCursor(Qt::SizeBDiagCursor);
-			else if (handlerRect(d_bounding_rect, Resize_NW).contains(me->pos()) || handlerRect(d_bounding_rect, Resize_SE).contains(me->pos()))
-				setCursor(Qt::SizeFDiagCursor);
-		} else
-			unsetCursor();
-		return QWidget::mouseMoveEvent(me);
-	}
-	d_op_dp = me->pos() - d_op_start;
-	repaint();
-	me->accept();
+void SelectionMoveResizer::mouseMoveEvent(QMouseEvent *me) {
+  if (d_op == None && d_bounding_rect.contains(me->pos()) &&
+      me->button() == Qt::LeftButton) {
+    d_op = Move;
+    d_op_start = me->pos();
+  }
+  if (d_op == None || d_op_start == QPoint(-1, -1)) {
+    if (d_bounding_rect.contains(me->pos())) {
+      setCursor(Qt::SizeAllCursor);
+      if (handlerRect(d_bounding_rect, Resize_N).contains(me->pos()) ||
+          handlerRect(d_bounding_rect, Resize_S).contains(me->pos()))
+        setCursor(Qt::SizeVerCursor);
+      else if (handlerRect(d_bounding_rect, Resize_E).contains(me->pos()) ||
+               handlerRect(d_bounding_rect, Resize_W).contains(me->pos()))
+        setCursor(Qt::SizeHorCursor);
+      else if (handlerRect(d_bounding_rect, Resize_NE).contains(me->pos()) ||
+               handlerRect(d_bounding_rect, Resize_SW).contains(me->pos()))
+        setCursor(Qt::SizeBDiagCursor);
+      else if (handlerRect(d_bounding_rect, Resize_NW).contains(me->pos()) ||
+               handlerRect(d_bounding_rect, Resize_SE).contains(me->pos()))
+        setCursor(Qt::SizeFDiagCursor);
+    } else
+      unsetCursor();
+    return QWidget::mouseMoveEvent(me);
+  }
+  d_op_dp = me->pos() - d_op_start;
+  repaint();
+  me->accept();
 }
 
-void SelectionMoveResizer::mouseDoubleClickEvent(QMouseEvent *e)
-{
-	foreach(LegendWidget *l, d_legend_markers) {
-		if(l->geometry().contains(e->pos()))
-			return l->showTextEditor();
-	}
+void SelectionMoveResizer::mouseDoubleClickEvent(QMouseEvent *e) {
+  foreach (LegendWidget *l, d_legend_markers) {
+    if (l->geometry().contains(e->pos()))
+      return l->showTextEditor();
+  }
 
-	e->ignore();
+  e->ignore();
 }
 
-void SelectionMoveResizer::mouseReleaseEvent(QMouseEvent *me)
-{
-	if (me->button() != Qt::LeftButton || d_op == None || d_op_start == QPoint(-1,-1))
-		return QWidget::mouseReleaseEvent(me);
+void SelectionMoveResizer::mouseReleaseEvent(QMouseEvent *me) {
+  if (me->button() != Qt::LeftButton || d_op == None ||
+      d_op_start == QPoint(-1, -1))
+    return QWidget::mouseReleaseEvent(me);
 
-	d_op_dp = me->pos() - d_op_start;
-	operateOnTargets();
-	d_op = None;
-	me->accept();
+  d_op_dp = me->pos() - d_op_start;
+  operateOnTargets();
+  d_op = None;
+  me->accept();
 }
 
-void SelectionMoveResizer::keyPressEvent(QKeyEvent *ke)
-{
-	switch(ke->key()) {
-		case Qt::Key_Enter:
-		case Qt::Key_Return:
-			if (d_op == None) {
-				ke->ignore();
-				break;
-			}
-			operateOnTargets();
-			d_op = None;
-			ke->accept();
-			break;
-		case Qt::Key_Escape:
-			delete this;
-			ke->accept();
-			return;
-		case Qt::Key_Left:
-			if (d_op == None) {
-				d_op = Move;
-				d_op_start = QPoint(-1,-1);
-			}
-			d_op_dp += QPoint(-1,0);
-			repaint();
-			ke->accept();
-			break;
-		case Qt::Key_Right:
-			if (d_op == None) {
-				d_op = Move;
-				d_op_start = QPoint(-1,-1);
-			}
-			d_op_dp += QPoint(1,0);
-			repaint();
-			ke->accept();
-			break;
-		case Qt::Key_Up:
-			if (d_op == None) {
-				d_op = Move;
-				d_op_start = QPoint(-1,-1);
-			}
-			d_op_dp += QPoint(0,-1);
-			repaint();
-			ke->accept();
-			break;
-		case Qt::Key_Down:
-			if (d_op == None) {
-				d_op = Move;
-				d_op_start = QPoint(-1,-1);
-			}
-			d_op_dp += QPoint(0,1);
-			repaint();
-			ke->accept();
-			break;
-		default:
-			ke->ignore();
-	}
+void SelectionMoveResizer::keyPressEvent(QKeyEvent *ke) {
+  switch (ke->key()) {
+  case Qt::Key_Enter:
+  case Qt::Key_Return:
+    if (d_op == None) {
+      ke->ignore();
+      break;
+    }
+    operateOnTargets();
+    d_op = None;
+    ke->accept();
+    break;
+  case Qt::Key_Escape:
+    delete this;
+    ke->accept();
+    return;
+  case Qt::Key_Left:
+    if (d_op == None) {
+      d_op = Move;
+      d_op_start = QPoint(-1, -1);
+    }
+    d_op_dp += QPoint(-1, 0);
+    repaint();
+    ke->accept();
+    break;
+  case Qt::Key_Right:
+    if (d_op == None) {
+      d_op = Move;
+      d_op_start = QPoint(-1, -1);
+    }
+    d_op_dp += QPoint(1, 0);
+    repaint();
+    ke->accept();
+    break;
+  case Qt::Key_Up:
+    if (d_op == None) {
+      d_op = Move;
+      d_op_start = QPoint(-1, -1);
+    }
+    d_op_dp += QPoint(0, -1);
+    repaint();
+    ke->accept();
+    break;
+  case Qt::Key_Down:
+    if (d_op == None) {
+      d_op = Move;
+      d_op_start = QPoint(-1, -1);
+    }
+    d_op_dp += QPoint(0, 1);
+    repaint();
+    ke->accept();
+    break;
+  default:
+    ke->ignore();
+  }
 }
 
-bool SelectionMoveResizer::eventFilter(QObject *o, QEvent *e)
-{
-	switch (e->type()) {
-		case QEvent::Resize:
-			if(static_cast<QWidget*>(o) == parentWidget())
-				setGeometry(0, 0, parentWidget()->width(), parentWidget()->height());
-			recalcBoundingRect();
-			return false;
-		case QEvent::Move:
-			if(static_cast<QWidget*>(o) != parentWidget())
-				recalcBoundingRect();
-			return false;
-		default:
-			return false;
-	}
+bool SelectionMoveResizer::eventFilter(QObject *o, QEvent *e) {
+  switch (e->type()) {
+  case QEvent::Resize:
+    if (static_cast<QWidget *>(o) == parentWidget())
+      setGeometry(0, 0, parentWidget()->width(), parentWidget()->height());
+    recalcBoundingRect();
+    return false;
+  case QEvent::Move:
+    if (static_cast<QWidget *>(o) != parentWidget())
+      recalcBoundingRect();
+    return false;
+  default:
+    return false;
+  }
 }
 
-void SelectionMoveResizer::removeWidget(QObject* w)
-{
-	removeAll(static_cast<QWidget*>(w));
+void SelectionMoveResizer::removeWidget(QObject *w) {
+  removeAll(static_cast<QWidget *>(w));
 }
 
-void SelectionMoveResizer::removeLegend(QObject* w)
-{
-	removeAll(static_cast<LegendWidget*>(w));
+void SelectionMoveResizer::removeLegend(QObject *w) {
+  removeAll(static_cast<LegendWidget *>(w));
 }
diff --git a/MantidPlot/src/SelectionMoveResizer.h b/MantidPlot/src/SelectionMoveResizer.h
index 62730190689f8eb3a64ba59dd9b0585265d8099d..0aa01e18f277562f3b4e4e35addec42d496dfa04 100644
--- a/MantidPlot/src/SelectionMoveResizer.h
+++ b/MantidPlot/src/SelectionMoveResizer.h
@@ -40,171 +40,215 @@ class LegendWidget;
 class ArrowMarker;
 class ImageMarker;
 
-/**\brief Handler for modifying one or more QWidget and/or QwtPlotMarker with mouse or keyboard.
+/**\brief Handler for modifying one or more QWidget and/or QwtPlotMarker with
+ *mouse or keyboard.
  *
- * During initialization, the SelectionMoveResizer adds itself as a new child widget to
- * the target's parentWidget() or QwtPlotCanvas. Because Qt 4.1 and beyond propagate a widget's
- * background by default, frame and resize handlers can then simply be drawn on top of
+ * During initialization, the SelectionMoveResizer adds itself as a new child
+ *widget to
+ * the target's parentWidget() or QwtPlotCanvas. Because Qt 4.1 and beyond
+ *propagate a widget's
+ * background by default, frame and resize handlers can then simply be drawn on
+ *top of
  * the usual content of the parent.
- * Also, the SelectionMoveResizer gets to see mouse and key events first without the need to filter
+ * Also, the SelectionMoveResizer gets to see mouse and key events first without
+ *the need to filter
  * events for its parent.
- * %Note however that the latter must still be done in order to catch geometry changes and
+ * %Note however that the latter must still be done in order to catch geometry
+ *changes and
  * stay the same size as the parent.
  *
  * At every point in time, the list of managed targets must be non-empty,
  * so that the SelectionMoveResizer has a well-defined bounding rectangle.
- * When there are no more selected targets, it deletes itself, so references to a SelectionMoveResizer
+ * When there are no more selected targets, it deletes itself, so references to
+ *a SelectionMoveResizer
  * should be maintained by QPointer and checked for validity before use.
  *
- * QWidget targets are automatically removed when they are deleted (possibly also deleting the
- * SelectionMoveResizer), using the QObject::destroyed() signal. With QwtPlotMarker, this is not
- * possible since it's not a QObject. Thus, care has to be taken to remove them before or shortly after deletion,
+ * QWidget targets are automatically removed when they are deleted (possibly
+ *also deleting the
+ * SelectionMoveResizer), using the QObject::destroyed() signal. With
+ *QwtPlotMarker, this is not
+ * possible since it's not a QObject. Thus, care has to be taken to remove them
+ *before or shortly after deletion,
  * lest the wrath of Segmentation Fault shall come upon you.
  *
  * \section design Design Ideas
- *   - Keep as much of the select/move/resize code as possible in one class to ease maintanance.
- *   - Use the same class for layer and marker handling to avoid duplicating code.
+ *   - Keep as much of the select/move/resize code as possible in one class to
+ *ease maintanance.
+ *   - Use the same class for layer and marker handling to avoid duplicating
+ *code.
  *     Good for bugfixing and for maintaining a consistent user interface.
  *   - Keep this class generic so that it can later be used for other parents
  *     (than MultiLayer's canvas QWidget and Plot's QwtPlotCanvas)
- *     and/or targets (e.g. new QwtPlotMarker subclasses) with little to no modifications.
- *   - Differentiate between move/resize, which are generic operations, and editing (like moving the
- *     endpoints of a ArrowMarker), which requires detailed knowledge about the target.
- *     This way, new types of markers or MultiLayer children support moving/resizing without further
- *     work. Editing can then be implemented in the targets themselves, as shown in ArrowMarker.
+ *     and/or targets (e.g. new QwtPlotMarker subclasses) with little to no
+ *modifications.
+ *   - Differentiate between move/resize, which are generic operations, and
+ *editing (like moving the
+ *     endpoints of a ArrowMarker), which requires detailed knowledge about the
+ *target.
+ *     This way, new types of markers or MultiLayer children support
+ *moving/resizing without further
+ *     work. Editing can then be implemented in the targets themselves, as shown
+ *in ArrowMarker.
  *   .
  *
  * \section future Future Plans
- * See the documentation of ImageMarker for ideas about replacing QwtPlotMarker with a new QwtPlotItem subclass.
- * For SelectionMoveResizer this would mean supporting new enrichments without modifications and being able
- * to automatically remove them upon deletion (if the new class inherits QObject).
- * Not to mention that the implementation would be a lot cleaner if we would only have to handle two target classes
+ * See the documentation of ImageMarker for ideas about replacing QwtPlotMarker
+ *with a new QwtPlotItem subclass.
+ * For SelectionMoveResizer this would mean supporting new enrichments without
+ *modifications and being able
+ * to automatically remove them upon deletion (if the new class inherits
+ *QObject).
+ * Not to mention that the implementation would be a lot cleaner if we would
+ *only have to handle two target classes
  * instead of four.
  *
- * Think about turning SelectionMoveResizer into an input method for general affine transformations.
+ * Think about turning SelectionMoveResizer into an input method for general
+ *affine transformations.
  * Particularly, this would add rotation, flipping and shearing.
  * Markers could implement this using QPainter's coordinate transformations.
  * Definitely not a priority, though.
  */
-class SelectionMoveResizer : public QWidget
-{
-	Q_OBJECT
+class SelectionMoveResizer : public QWidget {
+  Q_OBJECT
 
-	public:
-		//! Construct a new MoveResizer with the given marker as the only target.
-          explicit SelectionMoveResizer(LegendWidget *target);
-                //! Construct a new MoveResizer with the given marker as the only target.
-          explicit SelectionMoveResizer(ArrowMarker *target);
-                //! Construct a new MoveResizer with the given marker as the only target.
-          explicit SelectionMoveResizer(ImageMarker *target);
-                //! Construct a new MoveResizer with the given widget as the only target.
-          explicit SelectionMoveResizer(QWidget *target);
-                //! Clean up after myself.
-          ~SelectionMoveResizer() override;
-                /**\brief React on geometry changes of parent and targets.
-		 */
-          bool eventFilter(QObject *o, QEvent *e) override;
-                //! Returns true if w is one of targets, false else.
-		bool contains(QWidget *w) const { return d_widgets.contains(w); };
-		//! Returns true if m is one of targets, false else.
-		bool contains(LegendWidget *m) const { return d_legend_markers.contains(m); };
-		//! Returns true if m is one of targets, false else.
-		bool contains(ArrowMarker *m) const { return d_line_markers.contains(m); };
-		//! Returns true if m is one of targets, false else.
-		bool contains(ImageMarker *m) const { return d_image_markers.contains(m); };
+public:
+  //! Construct a new MoveResizer with the given marker as the only target.
+  explicit SelectionMoveResizer(LegendWidget *target);
+  //! Construct a new MoveResizer with the given marker as the only target.
+  explicit SelectionMoveResizer(ArrowMarker *target);
+  //! Construct a new MoveResizer with the given marker as the only target.
+  explicit SelectionMoveResizer(ImageMarker *target);
+  //! Construct a new MoveResizer with the given widget as the only target.
+  explicit SelectionMoveResizer(QWidget *target);
+  //! Clean up after myself.
+  ~SelectionMoveResizer() override;
+  /**\brief React on geometry changes of parent and targets.
+   */
+  bool eventFilter(QObject *o, QEvent *e) override;
+  //! Returns true if w is one of targets, false else.
+  bool contains(QWidget *w) const { return d_widgets.contains(w); };
+  //! Returns true if m is one of targets, false else.
+  bool contains(LegendWidget *m) const { return d_legend_markers.contains(m); };
+  //! Returns true if m is one of targets, false else.
+  bool contains(ArrowMarker *m) const { return d_line_markers.contains(m); };
+  //! Returns true if m is one of targets, false else.
+  bool contains(ImageMarker *m) const { return d_image_markers.contains(m); };
 
-	public slots:
-		//! Add target to the list of items to be moved/resized together.
-		void add(LegendWidget *target);
-		//! Add target to the list of items to be moved/resized together.
-		void add(ArrowMarker *target);
-		//! Add target to the list of items to be moved/resized together.
-		void add(ImageMarker *target);
-		//! Add target to the list of items to be moved/resized together.
-		void add(QWidget *target);
-		//! Remove target from the list of items to be moved/resized together and returns the number of occurences removed.
-		int removeAll(LegendWidget *target);
-		//! Remove target from the list of items to be moved/resized together and returns the number of occurences removed.
-		int removeAll(ArrowMarker *target);
-		//! Remove target from the list of items to be moved/resized together and returns the number of occurences removed.
-		int removeAll(ImageMarker *target);
-		//! Remove target from the list of items to be moved/resized together and returns the number of occurences removed.
-		int removeAll(QWidget *target);
-		//! Calculate #d_bounding_rect based on the bounding rectangles of all targets.
-		void recalcBoundingRect();
+public slots:
+  //! Add target to the list of items to be moved/resized together.
+  void add(LegendWidget *target);
+  //! Add target to the list of items to be moved/resized together.
+  void add(ArrowMarker *target);
+  //! Add target to the list of items to be moved/resized together.
+  void add(ImageMarker *target);
+  //! Add target to the list of items to be moved/resized together.
+  void add(QWidget *target);
+  //! Remove target from the list of items to be moved/resized together and
+  // returns the number of occurences removed.
+  int removeAll(LegendWidget *target);
+  //! Remove target from the list of items to be moved/resized together and
+  // returns the number of occurences removed.
+  int removeAll(ArrowMarker *target);
+  //! Remove target from the list of items to be moved/resized together and
+  // returns the number of occurences removed.
+  int removeAll(ImageMarker *target);
+  //! Remove target from the list of items to be moved/resized together and
+  // returns the number of occurences removed.
+  int removeAll(QWidget *target);
+  //! Calculate #d_bounding_rect based on the bounding rectangles of all
+  // targets.
+  void recalcBoundingRect();
 
-	signals:
-		//! Emitted when the targets are modified (moved or resized).
-		void targetsChanged();
+signals:
+  //! Emitted when the targets are modified (moved or resized).
+  void targetsChanged();
 
-	protected:
-		//! Available modes of operation.
-		enum Operation { None=-2, Move, Resize_N, Resize_NE, Resize_E, Resize_SE, Resize_S, Resize_SW, Resize_W, Resize_NW };
+protected:
+  //! Available modes of operation.
+  enum Operation {
+    None = -2,
+    Move,
+    Resize_N,
+    Resize_NE,
+    Resize_E,
+    Resize_SE,
+    Resize_S,
+    Resize_SW,
+    Resize_W,
+    Resize_NW
+  };
 
-		/**\brief Draw frame and resize handlers.
-		 *
-		 * Besides managing resize operations, this also provides a visual feedback
-		 * on the selection state.
-		 */
-                void paintEvent(QPaintEvent *e) override;
-                /**\brief Mouse button presses start move/resize operations.
-		 *
-		 * Clicks outside of #d_bounding_rect or with anything else than the left button
-		 * are propagated to the parent as usual.
-		 */
-                void mousePressEvent(QMouseEvent *e) override;
-                /**\brief Mouse movements need to be monitored for updating the frame during operation.
-		 *
-		 * When no operation is in progress, the mouse cursor is updated based on its position
-		 * before the event is passed on to the parent.
-		 */
-                void mouseMoveEvent(QMouseEvent *e) override;
-                /**\brief Mouse releases end the current operation and apply it to the targets.
-		 *
-		 * When there is no operation in progress, the event is passed on to the parent.
-		 */
-                void mouseReleaseEvent(QMouseEvent *e) override;
-                /**\brief Allow keyboard-based moving of the selection.
-		 *
-		 * Unused keys are passed on to the parent.
-		 */
-                void keyPressEvent(QKeyEvent *e) override;
-                //! Ignore double-clicks so that they can be used by my parent.
-                void mouseDoubleClickEvent(QMouseEvent *e) override;
+  /**\brief Draw frame and resize handlers.
+   *
+   * Besides managing resize operations, this also provides a visual feedback
+   * on the selection state.
+   */
+  void paintEvent(QPaintEvent *e) override;
+  /**\brief Mouse button presses start move/resize operations.
+   *
+   * Clicks outside of #d_bounding_rect or with anything else than the left
+   *button
+   * are propagated to the parent as usual.
+   */
+  void mousePressEvent(QMouseEvent *e) override;
+  /**\brief Mouse movements need to be monitored for updating the frame during
+   *operation.
+   *
+   * When no operation is in progress, the mouse cursor is updated based on its
+   *position
+   * before the event is passed on to the parent.
+   */
+  void mouseMoveEvent(QMouseEvent *e) override;
+  /**\brief Mouse releases end the current operation and apply it to the
+   *targets.
+   *
+   * When there is no operation in progress, the event is passed on to the
+   *parent.
+   */
+  void mouseReleaseEvent(QMouseEvent *e) override;
+  /**\brief Allow keyboard-based moving of the selection.
+   *
+   * Unused keys are passed on to the parent.
+   */
+  void keyPressEvent(QKeyEvent *e) override;
+  //! Ignore double-clicks so that they can be used by my parent.
+  void mouseDoubleClickEvent(QMouseEvent *e) override;
 
-        private:
-		//! Size of resize handle in pixels.
-		static const int handler_size = 10;
-		//! Return one of the rectangles to be filled for starting resize operations.
-		static const QRect handlerRect(QRect rect, Operation op);
-		//! Apply operation specified by #d_op and #d_op_dp to in.
-		QRect operateOn(const QRect& in);
-		//! Apply operation specified by #d_op and #d_op_dp to all targets.
-		void operateOnTargets();
-		//! The initialization part common to all constructors.
-		void init();
+private:
+  //! Size of resize handle in pixels.
+  static const int handler_size = 10;
+  //! Return one of the rectangles to be filled for starting resize operations.
+  static const QRect handlerRect(QRect rect, Operation op);
+  //! Apply operation specified by #d_op and #d_op_dp to in.
+  QRect operateOn(const QRect &in);
+  //! Apply operation specified by #d_op and #d_op_dp to all targets.
+  void operateOnTargets();
+  //! The initialization part common to all constructors.
+  void init();
 
-		//! Target markers I'm handling.
-		QList <LegendWidget *> d_legend_markers;
-		//! Target markers I'm handling.
-		QList <ArrowMarker *> d_line_markers;
-		//! Target markers I'm handling.
-		QList <ImageMarker *> d_image_markers;
-		//! Target widgets I'm handling.
-		QList <QWidget *> d_widgets;
-		//! Bounding rectangle of all targets taken together, in drawing coordinates.
-		QRect d_bounding_rect;
-		//! The type of operation currently in progress.
-		Operation d_op;
-		//! Mouse position where an operation started; (-1,-1) means started by keyboard.
-		QPoint d_op_start;
-		//! Difference between current and start position during operation.
-		QPoint d_op_dp;
+  //! Target markers I'm handling.
+  QList<LegendWidget *> d_legend_markers;
+  //! Target markers I'm handling.
+  QList<ArrowMarker *> d_line_markers;
+  //! Target markers I'm handling.
+  QList<ImageMarker *> d_image_markers;
+  //! Target widgets I'm handling.
+  QList<QWidget *> d_widgets;
+  //! Bounding rectangle of all targets taken together, in drawing coordinates.
+  QRect d_bounding_rect;
+  //! The type of operation currently in progress.
+  Operation d_op;
+  //! Mouse position where an operation started; (-1,-1) means started by
+  // keyboard.
+  QPoint d_op_start;
+  //! Difference between current and start position during operation.
+  QPoint d_op_dp;
 
-	private slots:
-		//! A non-typesafe version of remvoveAll(QWidget*) needed for QObject::destroyed().
-		void removeWidget(QObject* w);
-		void removeLegend(QObject* w);
+private slots:
+  //! A non-typesafe version of remvoveAll(QWidget*) needed for
+  // QObject::destroyed().
+  void removeWidget(QObject *w);
+  void removeLegend(QObject *w);
 };
 
 #endif // ifndef SELECTION_MOVE_RESIZER_H
diff --git a/MantidPlot/src/SendToProgramDialog.cpp b/MantidPlot/src/SendToProgramDialog.cpp
index 5efed49e3724cc3b6e65add46f4788900d542ca3..eccb97c096e37211a3096d90ef73fa46774ff0e7 100644
--- a/MantidPlot/src/SendToProgramDialog.cpp
+++ b/MantidPlot/src/SendToProgramDialog.cpp
@@ -20,173 +20,174 @@
 
 #include <map>
 
-
 /**
 * Constructor when adding a new program to the send to list
 */
-SendToProgramDialog::SendToProgramDialog(QWidget* parent, Qt::WFlags fl)
-    : QDialog( parent, fl ), validName(false), validTarget(false), validSaveUsing(false)
-{
+SendToProgramDialog::SendToProgramDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), validName(false), validTarget(false),
+      validSaveUsing(false) {
   m_uiform.setupUi(this);
 
-  //Adding new information is disabled until selected fields have been validated and passed
+  // Adding new information is disabled until selected fields have been
+  // validated and passed
   m_uiform.buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
 
-  //Icon image for the browse button
+  // Icon image for the browse button
   m_uiform.browseButton->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 
-  //Setup save and browse button, cancel does nothing but closes the current dialog (does this by default)
+  // Setup save and browse button, cancel does nothing but closes the current
+  // dialog (does this by default)
   connect(m_uiform.browseButton, SIGNAL(clicked()), this, SLOT(browse()));
   connect(m_uiform.buttonBox, SIGNAL(accepted()), this, SLOT(save()));
 
-  //Setup Validation for the mandatory information
-  connect(m_uiform.nameText, SIGNAL(textChanged(const QString&)), this, SLOT(validateName()));
-  connect(m_uiform.targetText, SIGNAL(textChanged(const QString&)), this, SLOT(validateTarget()));
-  connect(m_uiform.saveUsingText, SIGNAL(textChanged(const QString&)), this, SLOT(validateSaveUsing()));
+  // Setup Validation for the mandatory information
+  connect(m_uiform.nameText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateName()));
+  connect(m_uiform.targetText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateTarget()));
+  connect(m_uiform.saveUsingText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateSaveUsing()));
 }
 
-
 /**
 * Constructor when editing a program settings
 */
-SendToProgramDialog::SendToProgramDialog(QWidget* parent, QString programName, std::map<std::string, std::string> programKeysAndDetails, Qt::WFlags fl)
-    : QDialog(parent, fl), validName(true), validTarget(true), validSaveUsing(true)
-{
+SendToProgramDialog::SendToProgramDialog(
+    QWidget *parent, QString programName,
+    std::map<std::string, std::string> programKeysAndDetails, Qt::WFlags fl)
+    : QDialog(parent, fl), validName(true), validTarget(true),
+      validSaveUsing(true) {
   m_uiform.setupUi(this);
 
-  //Set the name of the program you wish to edit and make it so that the user can't change it
+  // Set the name of the program you wish to edit and make it so that the user
+  // can't change it
   m_uiform.nameText->setText(programName);
   QPalette palette;
-  palette.setColor(m_uiform.nameText->backgroundRole(), QColor(230,230,230));
+  palette.setColor(m_uiform.nameText->backgroundRole(), QColor(230, 230, 230));
   m_uiform.nameText->setPalette(palette);
   m_uiform.nameText->setReadOnly(true);
 
-  //Assign the collected data on the program to the form boxes
+  // Assign the collected data on the program to the form boxes
   if (programKeysAndDetails.count("target") != 0)
-    m_uiform.targetText->setText(QString::fromStdString(programKeysAndDetails.find("target")->second));
+    m_uiform.targetText->setText(
+        QString::fromStdString(programKeysAndDetails.find("target")->second));
   if (programKeysAndDetails.count("arguments") != 0)
-    m_uiform.argumentsText->setText(QString::fromStdString(programKeysAndDetails.find("arguments")->second));
+    m_uiform.argumentsText->setText(QString::fromStdString(
+        programKeysAndDetails.find("arguments")->second));
   if (programKeysAndDetails.count("saveparameters") != 0)
-    m_uiform.saveParametersText->setText(QString::fromStdString(programKeysAndDetails.find("saveparameters")->second));
+    m_uiform.saveParametersText->setText(QString::fromStdString(
+        programKeysAndDetails.find("saveparameters")->second));
 
   if (programKeysAndDetails.count("saveusing") != 0)
 
-    m_uiform.saveUsingText->setText(QString::fromStdString(programKeysAndDetails.find("saveusing")->second));
+    m_uiform.saveUsingText->setText(QString::fromStdString(
+        programKeysAndDetails.find("saveusing")->second));
 
-  //Validation correct on startup
+  // Validation correct on startup
   validateName();
   validateTarget();
   validateSaveUsing();
 
-  //Icon image for the browse button
+  // Icon image for the browse button
   m_uiform.browseButton->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 
-  //Setup save and browse button, cancel does nothing but closes the current dialog (does this by default)
+  // Setup save and browse button, cancel does nothing but closes the current
+  // dialog (does this by default)
   connect(m_uiform.browseButton, SIGNAL(clicked()), this, SLOT(browse()));
   connect(m_uiform.buttonBox, SIGNAL(accepted()), this, SLOT(save()));
-  
-  //Setup Validation for the mandatory information
-  connect(m_uiform.nameText, SIGNAL(textChanged(const QString&)), this, SLOT(validateName()));
-  connect(m_uiform.targetText, SIGNAL(textChanged(const QString&)), this, SLOT(validateTarget()));
-  connect(m_uiform.saveUsingText, SIGNAL(textChanged(const QString&)), this, SLOT(validateSaveUsing()));
+
+  // Setup Validation for the mandatory information
+  connect(m_uiform.nameText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateName()));
+  connect(m_uiform.targetText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateTarget()));
+  connect(m_uiform.saveUsingText, SIGNAL(textChanged(const QString &)), this,
+          SLOT(validateSaveUsing()));
 }
 
 /**
 * Open up a new file browsing window
 */
-void SendToProgramDialog::browse()
-{
+void SendToProgramDialog::browse() {
   // (*) Will let all files be selected
   QFileDialog *dialog = new QFileDialog;
-  QString fileName = dialog->getOpenFileName(this, tr("Select Program Location"), "C:/", tr("All Files (*)"));
-  
-  //Sets the file target that the user selected to be the file path for the program
+  QString fileName = dialog->getOpenFileName(
+      this, tr("Select Program Location"), "C:/", tr("All Files (*)"));
+
+  // Sets the file target that the user selected to be the file path for the
+  // program
   m_uiform.targetText->setText(fileName);
 }
 
-
 /**
 * See whether anything has been entered as a program name.
 */
-void SendToProgramDialog::validateName()
-{
-  if (m_uiform.nameText->text() == "")
-  {
-    m_uiform.validateName->setVisible(true); 
+void SendToProgramDialog::validateName() {
+  if (m_uiform.nameText->text() == "") {
+    m_uiform.validateName->setVisible(true);
     validName = false;
-  }
-  else
-  {
-    m_uiform.validateName->setVisible(false); 
+  } else {
+    m_uiform.validateName->setVisible(false);
     validName = true;
   }
   validateAll();
 }
 
-
 /**
 * Make sure the user specified target program is executable.
 */
-void SendToProgramDialog::validateTarget()
-{
+void SendToProgramDialog::validateTarget() {
   QString filePath = m_uiform.targetText->text();
   filePath.replace(QString("\\"), QString("/"));
-    
-  if (filePath != ""){
-    if (Mantid::Kernel::ConfigService::Instance().isExecutable(filePath.toStdString()))  
-    {
-      m_uiform.validateTarget->setVisible(false); 
+
+  if (filePath != "") {
+    if (Mantid::Kernel::ConfigService::Instance().isExecutable(
+            filePath.toStdString())) {
+      m_uiform.validateTarget->setVisible(false);
       validTarget = true;
-    }
-    else
-    {
-      m_uiform.validateTarget->setVisible(true); 
+    } else {
+      m_uiform.validateTarget->setVisible(true);
       validTarget = false;
     }
-  }
-  else
-  {
-    m_uiform.validateTarget->setVisible(true); 
+  } else {
+    m_uiform.validateTarget->setVisible(true);
     validTarget = false;
   }
   validateAll();
-
 }
 
-
 /**
 * Make sure the user specified save algorithm exists.
 */
-void SendToProgramDialog::validateSaveUsing()
-{
-  validSaveUsing = Mantid::API::AlgorithmFactory::Instance().exists( m_uiform.saveUsingText->text().toStdString() );
-  m_uiform.validateSaveUsing->setVisible( ! validSaveUsing );
+void SendToProgramDialog::validateSaveUsing() {
+  validSaveUsing = Mantid::API::AlgorithmFactory::Instance().exists(
+      m_uiform.saveUsingText->text().toStdString());
+  m_uiform.validateSaveUsing->setVisible(!validSaveUsing);
 
   validateAll();
 }
 
-
 /**
-* If a validation passes or fails then a validation of the entire 
+* If a validation passes or fails then a validation of the entire
 * dialog needs to be done to enable or disable the save button.
 */
-void SendToProgramDialog::validateAll()
-{
-  //If validation passes on name, target and the save algorithm the save button becomes available for the user to press.
-  if(validName == true && validTarget == true && validSaveUsing == true)
+void SendToProgramDialog::validateAll() {
+  // If validation passes on name, target and the save algorithm the save button
+  // becomes available for the user to press.
+  if (validName == true && validTarget == true && validSaveUsing == true)
     m_uiform.buttonBox->button(QDialogButtonBox::Save)->setEnabled(true);
   else
     m_uiform.buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
 }
 
-
 /**
 * Save the new program or changes to a program
 */
-void SendToProgramDialog::save()
-{ 
-  //Collect mandatory information and then check to see if it has been collected (visible will always be true or false and is therefore not collected yet)
-  std::map<std::string,std::string> programKeysAndDetails;
+void SendToProgramDialog::save() {
+  // Collect mandatory information and then check to see if it has been
+  // collected (visible will always be true or false and is therefore not
+  // collected yet)
+  std::map<std::string, std::string> programKeysAndDetails;
 
   std::string name = m_uiform.nameText->text().toStdString();
 
@@ -194,30 +195,35 @@ void SendToProgramDialog::save()
   filePath.replace(QString("\\"), QString("/"));
 
   programKeysAndDetails["target"] = filePath.toStdString();
-  
-  programKeysAndDetails["saveusing"] = m_uiform.saveUsingText->text().toStdString(); 
 
-  //No need to check that mandatory data is here due to validation that has been implemented above
-  //Collect the rest of the information if there is any (visible will always be true or false)
-  if(m_uiform.argumentsText->text() != "")
-    programKeysAndDetails["arguments"] = m_uiform.argumentsText->text().toStdString();
-  if(m_uiform.saveParametersText->text() != "")
-    programKeysAndDetails["saveparameters"] = m_uiform.saveParametersText->text().toStdString();
-
-  //when a program is saved be it an edit or a new program, visible defaults to "Yes"
+  programKeysAndDetails["saveusing"] =
+      m_uiform.saveUsingText->text().toStdString();
+
+  // No need to check that mandatory data is here due to validation that has
+  // been implemented above
+  // Collect the rest of the information if there is any (visible will always be
+  // true or false)
+  if (m_uiform.argumentsText->text() != "")
+    programKeysAndDetails["arguments"] =
+        m_uiform.argumentsText->text().toStdString();
+  if (m_uiform.saveParametersText->text() != "")
+    programKeysAndDetails["saveparameters"] =
+        m_uiform.saveParametersText->text().toStdString();
+
+  // when a program is saved be it an edit or a new program, visible defaults to
+  // "Yes"
   programKeysAndDetails["visible"] = "Yes";
 
-  m_settings.first = name; 
+  m_settings.first = name;
   m_settings.second = programKeysAndDetails;
 }
 
-
 /**
-* Get the settings 
+* Get the settings
 *
 * @return m_settings :: Key and detail of what is to go in the config service
 */
-std::pair<std::string, std::map<std::string, std::string> > SendToProgramDialog::getSettings() const
-{
+std::pair<std::string, std::map<std::string, std::string>>
+SendToProgramDialog::getSettings() const {
   return m_settings;
 }
diff --git a/MantidPlot/src/SendToProgramDialog.h b/MantidPlot/src/SendToProgramDialog.h
index 6453ac3e800dadc425e41474d5f95b9b479c0f61..6741bd4a4a3ab07e53acd9a0ff8fe5852816ecb1 100644
--- a/MantidPlot/src/SendToProgramDialog.h
+++ b/MantidPlot/src/SendToProgramDialog.h
@@ -15,16 +15,18 @@ class QListWidget;
 class QMouseEvent;
 class QStringList;
 
-//SendToProgramDialog
+// SendToProgramDialog
 
-class SendToProgramDialog : public QDialog
-{
+class SendToProgramDialog : public QDialog {
   Q_OBJECT
-  
+
 public:
-  SendToProgramDialog(QWidget* parent, Qt::WFlags fl = 0 );
-  SendToProgramDialog(QWidget* parent, QString programName, std::map<std::string, std::string> programKeysAndDetails, Qt::WFlags fl = 0 );
-  std::pair<std::string,std::map<std::string,std::string> > getSettings() const;
+  SendToProgramDialog(QWidget *parent, Qt::WFlags fl = 0);
+  SendToProgramDialog(QWidget *parent, QString programName,
+                      std::map<std::string, std::string> programKeysAndDetails,
+                      Qt::WFlags fl = 0);
+  std::pair<std::string, std::map<std::string, std::string>>
+  getSettings() const;
 
 private slots:
   /// Open up a new file browsing window.
@@ -38,7 +40,7 @@ private slots:
 
   /// Validate user specified target.
   void validateTarget();
-  
+
   /// Validate user specified save algorithm.
   void validateSaveUsing();
 
@@ -48,8 +50,7 @@ private slots:
 private:
   bool validName, validTarget, validSaveUsing;
   Ui::SendToProgramDialog m_uiform;
-  std::pair<std::string,std::map<std::string,std::string> > m_settings;
+  std::pair<std::string, std::map<std::string, std::string>> m_settings;
 };
 
-
 #endif // SendToProgram_H
diff --git a/MantidPlot/src/SetColValuesDialog.h b/MantidPlot/src/SetColValuesDialog.h
index 0849407a7b1b32329a706f251dba937d8b784b76..80153591a86bc1e1a01f17ff98c8d9bca30e6943 100644
--- a/MantidPlot/src/SetColValuesDialog.h
+++ b/MantidPlot/src/SetColValuesDialog.h
@@ -48,41 +48,39 @@ class Table;
 class ScriptingEnv;
 class ScriptEditor;
 
-
 //! Set column values dialog
-class SetColValuesDialog : public QDialog, public Scripted
-{
-    Q_OBJECT
+class SetColValuesDialog : public QDialog, public Scripted {
+  Q_OBJECT
 
 public:
-    SetColValuesDialog( ScriptingEnv *env, Table* t, Qt::WFlags fl = 0 );
+  SetColValuesDialog(ScriptingEnv *env, Table *t, Qt::WFlags fl = 0);
 
 private slots:
-	bool apply();
-	void prevColumn();
-	void nextColumn();
-	void insertCol();
-	void insertCell();
-	void updateColumn(int sc);
+  bool apply();
+  void prevColumn();
+  void nextColumn();
+  void insertCol();
+  void insertCell();
+  void updateColumn(int sc);
 
 private:
-	Table* table;
-	
-	void setTable(Table* w);
-        QSize sizeHint() const override;
-        void customEvent(QEvent *e) override;
+  Table *table;
+
+  void setTable(Table *w);
+  QSize sizeHint() const override;
+  void customEvent(QEvent *e) override;
 
-    QComboBox* boxColumn;
-    QPushButton* btnAddCol;
-    QPushButton* btnCancel;
-    QPushButton *buttonPrev;
-    QPushButton *buttonNext;
-    QPushButton *addCellButton;
-    QPushButton *btnApply;
-    ScriptEditor* commands;
-    QTextEdit* explain;
-	QSpinBox* start, *end;
-	QLabel *colNameLabel;
+  QComboBox *boxColumn;
+  QPushButton *btnAddCol;
+  QPushButton *btnCancel;
+  QPushButton *buttonPrev;
+  QPushButton *buttonNext;
+  QPushButton *addCellButton;
+  QPushButton *btnApply;
+  ScriptEditor *commands;
+  QTextEdit *explain;
+  QSpinBox *start, *end;
+  QLabel *colNameLabel;
 };
 
 #endif //
diff --git a/MantidPlot/src/SigmoidalFit.cpp b/MantidPlot/src/SigmoidalFit.cpp
index 76432ce82281f1f0606752eacc9086eaf61852ca..96ff6ecb25d5b9d68bfe1c91fb1408cf62d9d9a9 100644
--- a/MantidPlot/src/SigmoidalFit.cpp
+++ b/MantidPlot/src/SigmoidalFit.cpp
@@ -30,81 +30,82 @@
 #include "fit_gsl.h"
 
 SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Graph *g)
-: Fit(parent, g)
-{
-	init();
+    : Fit(parent, g) {
+  init();
 }
 
-SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle);
+SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle);
 }
 
-SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end)
-: Fit(parent, g)
-{
-	init();
-	setDataFromCurve(curveTitle, start, end);
+SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle, double start, double end)
+    : Fit(parent, g) {
+  init();
+  setDataFromCurve(curveTitle, start, end);
 }
 
-SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow, int endRow)
-: Fit(parent, t)
-{
-	init();
-	setDataFromTable(t, xCol, yCol, startRow, endRow);
+SigmoidalFit::SigmoidalFit(ApplicationWindow *parent, Table *t,
+                           const QString &xCol, const QString &yCol,
+                           int startRow, int endRow)
+    : Fit(parent, t) {
+  init();
+  setDataFromTable(t, xCol, yCol, startRow, endRow);
 }
 
-void SigmoidalFit::init()
-{
-	setObjectName(tr("Boltzmann"));
-	d_f = boltzmann_f;
-	d_df = boltzmann_df;
-	d_fdf = boltzmann_fdf;
-	d_fsimplex = boltzmann_d;
-	d_param_explain << tr("init value") << tr("final value") << tr("center") << tr("time constant");
-	d_param_names << "A1" << "A2" << "x0" << "dx";
-	d_explanation = tr("Boltzmann (Sigmoidal) Fit");
-	d_formula = "A2+(A1-A2)/(1+exp((x-x0)/dx))";
-	d_p = 4;
-    initWorkspace(d_p);
+void SigmoidalFit::init() {
+  setObjectName(tr("Boltzmann"));
+  d_f = boltzmann_f;
+  d_df = boltzmann_df;
+  d_fdf = boltzmann_fdf;
+  d_fsimplex = boltzmann_d;
+  d_param_explain << tr("init value") << tr("final value") << tr("center")
+                  << tr("time constant");
+  d_param_names << "A1"
+                << "A2"
+                << "x0"
+                << "dx";
+  d_explanation = tr("Boltzmann (Sigmoidal) Fit");
+  d_formula = "A2+(A1-A2)/(1+exp((x-x0)/dx))";
+  d_p = 4;
+  initWorkspace(d_p);
 }
 
-void SigmoidalFit::calculateFitCurveData(double *X, double *Y)
-{
-	double a1 = d_results[0];
-	double a2 = d_results[1];
-	double x0 = d_results[2];
-	double p = d_results[3];
-	
-	if (d_gen_function){
-		double X0 = d_x[0];
-		double step = (d_x[d_n-1]-X0)/(d_points-1);
-        for (int i=0; i<d_points; i++){
-			double x = X0+i*step;
-        	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
-		}
-	} else {
-        for (int i=0; i<d_points; i++){
-			double x = d_x[i];
-        	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
-		}
-	}
+void SigmoidalFit::calculateFitCurveData(double *X, double *Y) {
+  double a1 = d_results[0];
+  double a2 = d_results[1];
+  double x0 = d_results[2];
+  double p = d_results[3];
+
+  if (d_gen_function) {
+    double X0 = d_x[0];
+    double step = (d_x[d_n - 1] - X0) / (d_points - 1);
+    for (int i = 0; i < d_points; i++) {
+      double x = X0 + i * step;
+      X[i] = x;
+      Y[i] = (a1 - a2) / (1 + exp((x - x0) / p)) + a2;
+    }
+  } else {
+    for (int i = 0; i < d_points; i++) {
+      double x = d_x[i];
+      X[i] = x;
+      Y[i] = (a1 - a2) / (1 + exp((x - x0) / p)) + a2;
+    }
+  }
 }
 
-void SigmoidalFit::guessInitialValues()
-{
-	gsl_vector_view x = gsl_vector_view_array (d_x, d_n);
-	gsl_vector_view y = gsl_vector_view_array (d_y, d_n);
+void SigmoidalFit::guessInitialValues() {
+  gsl_vector_view x = gsl_vector_view_array(d_x, d_n);
+  gsl_vector_view y = gsl_vector_view_array(d_y, d_n);
 
-	double min_out, max_out;
-	gsl_vector_minmax (&y.vector, &min_out, &max_out);
+  double min_out, max_out;
+  gsl_vector_minmax(&y.vector, &min_out, &max_out);
 
-	gsl_vector_set(d_param_init, 0, min_out);
-	gsl_vector_set(d_param_init, 1, max_out);
-	gsl_vector_set(d_param_init, 2, gsl_vector_get (&x.vector, d_n/2));
-	gsl_vector_set(d_param_init, 3, 1.0);
+  gsl_vector_set(d_param_init, 0, min_out);
+  gsl_vector_set(d_param_init, 1, max_out);
+  gsl_vector_set(d_param_init, 2, gsl_vector_get(&x.vector, d_n / 2));
+  gsl_vector_set(d_param_init, 3, 1.0);
 }
diff --git a/MantidPlot/src/SigmoidalFit.h b/MantidPlot/src/SigmoidalFit.h
index c42841992534526c13b22bebf53a26fe7b31ba52..97b1e6b49bca2ea9c7e7ac04a24d3c09b720665b 100644
--- a/MantidPlot/src/SigmoidalFit.h
+++ b/MantidPlot/src/SigmoidalFit.h
@@ -31,29 +31,29 @@
 
 #include "Fit.h"
 
-class SigmoidalFit : public Fit
-{
-	Q_OBJECT
+class SigmoidalFit : public Fit {
+  Q_OBJECT
 
-	public:
-		SigmoidalFit(ApplicationWindow *parent, Graph *g);
-		SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle);
-		SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
-		SigmoidalFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 1, int endRow = -1);
+public:
+  SigmoidalFit(ApplicationWindow *parent, Graph *g);
+  SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle);
+  SigmoidalFit(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+               double start, double end);
+  SigmoidalFit(ApplicationWindow *parent, Table *t, const QString &xCol,
+               const QString &yCol, int startRow = 1, int endRow = -1);
 
-                double eval(double *par, double x) override {
-                  return (par[0] - par[1]) / (1 + exp((x - par[2]) / par[3])) +
-                         par[1];
-                };
+  double eval(double *par, double x) override {
+    return (par[0] - par[1]) / (1 + exp((x - par[2]) / par[3])) + par[1];
+  };
 
-                void guessInitialValues() override;
-                void setLogistic(bool on = true);
+  void guessInitialValues() override;
+  void setLogistic(bool on = true);
 
-	private:
-		void init();
-                void calculateFitCurveData(double *X, double *Y) override;
+private:
+  void init();
+  void calculateFitCurveData(double *X, double *Y) override;
 
-                bool d_logistic;
+  bool d_logistic;
 };
 
 #endif
diff --git a/MantidPlot/src/SmoothCurveDialog.cpp b/MantidPlot/src/SmoothCurveDialog.cpp
index 0d27abfc8b1d60b01bbf11569ef99637bd9feeeb..989bf19ff1b295f53db02e92ad650502ed776c86 100644
--- a/MantidPlot/src/SmoothCurveDialog.cpp
+++ b/MantidPlot/src/SmoothCurveDialog.cpp
@@ -2,7 +2,8 @@
     File                 : SmoothCurveDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Smoothing options dialog
 
@@ -41,13 +42,12 @@
 #include <QComboBox>
 #include <QLayout>
 
-SmoothCurveDialog::SmoothCurveDialog(int method, QWidget* parent, Qt::WFlags fl )
-  : QDialog( parent, fl ), graph(NULL), boxPointsLeft(NULL), boxPointsRight(NULL),
-    boxOrder(NULL)
-{
+SmoothCurveDialog::SmoothCurveDialog(int method, QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl), graph(NULL), boxPointsLeft(NULL),
+      boxPointsRight(NULL), boxOrder(NULL) {
   smooth_method = method;
 
-  setObjectName( "SmoothCurveDialog" );
+  setObjectName("SmoothCurveDialog");
   setWindowTitle(tr("MantidPlot - Smoothing Options"));
 
   QGroupBox *gb1 = new QGroupBox();
@@ -60,48 +60,45 @@ SmoothCurveDialog::SmoothCurveDialog(int method, QWidget* parent, Qt::WFlags fl
   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);
+  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->setColumnStretch(2, 1);
 
-  btnSmooth = new QPushButton(tr( "&Smooth" ));
+  btnSmooth = new QPushButton(tr("&Smooth"));
   btnSmooth->setDefault(true);
-  buttonCancel = new QPushButton(tr( "&Close" ));
+  buttonCancel = new QPushButton(tr("&Close"));
 
   QVBoxLayout *vl = new QVBoxLayout();
   vl->addWidget(btnSmooth);
@@ -112,43 +109,39 @@ SmoothCurveDialog::SmoothCurveDialog(int method, QWidget* parent, Qt::WFlags fl
   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&)));
+  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()
-{
-    SmoothFilter *sf = new SmoothFilter(static_cast<ApplicationWindow *>(this->parent()), graph,
-                                        boxName->currentText(), smooth_method);
-    if (smooth_method == SmoothFilter::SavitzkyGolay)
-    {
-        sf->setSmoothPoints(boxPointsLeft->value(), boxPointsRight->value());
-        sf->setPolynomOrder(boxOrder->value());
-    }
-    else
-        sf->setSmoothPoints(boxPointsLeft->value());
-
-    sf->setColor(boxColor->currentIndex());
-    sf->run();
-    delete sf;
+void SmoothCurveDialog::smooth() {
+  SmoothFilter *sf =
+      new SmoothFilter(static_cast<ApplicationWindow *>(this->parent()), graph,
+                       boxName->currentText(), smooth_method);
+  if (smooth_method == SmoothFilter::SavitzkyGolay) {
+    sf->setSmoothPoints(boxPointsLeft->value(), boxPointsRight->value());
+    sf->setPolynomOrder(boxOrder->value());
+  } else
+    sf->setSmoothPoints(boxPointsLeft->value());
+
+  sf->setColor(boxColor->currentIndex());
+  sf->run();
+  delete sf;
 }
 
-void SmoothCurveDialog::setGraph(Graph *g)
-{
-    graph = g;
-    boxName->addItems (g->analysableCurvesList());
-    activateCurve(boxName->currentText());
+void SmoothCurveDialog::setGraph(Graph *g) {
+  graph = g;
+  boxName->addItems(g->analysableCurvesList());
+  activateCurve(boxName->currentText());
 }
 
-void SmoothCurveDialog::activateCurve(const QString& curveName)
-{
-    if (smooth_method == SmoothFilter::Average)
-	{
-	QwtPlotCurve *c = graph->curve(curveName);
-	if (!c || c->rtti() != QwtPlotItem::Rtti_PlotCurve)
-		return;
+void SmoothCurveDialog::activateCurve(const QString &curveName) {
+  if (smooth_method == SmoothFilter::Average) {
+    QwtPlotCurve *c = graph->curve(curveName);
+    if (!c || c->rtti() != QwtPlotItem::Rtti_PlotCurve)
+      return;
 
-	boxPointsLeft->setMaximum(c->dataSize()/2);
-	}
+    boxPointsLeft->setMaximum(c->dataSize() / 2);
+  }
 }
diff --git a/MantidPlot/src/SmoothCurveDialog.h b/MantidPlot/src/SmoothCurveDialog.h
index 0a2eeef7ac433d02d62dcdf20eaa356fe3dcdc3a..856aeef6ddb3b3201adf2c4092fe7f564995b991 100644
--- a/MantidPlot/src/SmoothCurveDialog.h
+++ b/MantidPlot/src/SmoothCurveDialog.h
@@ -2,7 +2,8 @@
     File                 : SmoothCurveDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Smoothing options dialog
 
@@ -38,29 +39,25 @@ class Graph;
 class ColorBox;
 
 //! Smoothing options dialog
-class SmoothCurveDialog : public QDialog
-{
-    Q_OBJECT
+class SmoothCurveDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    SmoothCurveDialog(int method, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  SmoothCurveDialog(int method, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
-	void setGraph(Graph *g);
-	void smooth();
-	void activateCurve(const QString& curveName);
+  void setGraph(Graph *g);
+  void smooth();
+  void activateCurve(const QString &curveName);
 
 private:
-	Graph *graph;
-	int smooth_method;
-    QPushButton* btnSmooth;
-	QPushButton* buttonCancel;
-	QComboBox* boxName;
-	QSpinBox *boxPointsLeft, *boxPointsRight, *boxOrder;
-	ColorBox* boxColor;
+  Graph *graph;
+  int smooth_method;
+  QPushButton *btnSmooth;
+  QPushButton *buttonCancel;
+  QComboBox *boxName;
+  QSpinBox *boxPointsLeft, *boxPointsRight, *boxOrder;
+  ColorBox *boxColor;
 };
 
 #endif
-
-
-
diff --git a/MantidPlot/src/SmoothFilter.cpp b/MantidPlot/src/SmoothFilter.cpp
index 77129df0497dc4b52b5f18b4132ea2cf30e5aacf..850e1039eff9101f7c5cb97782088c062f944402 100644
--- a/MantidPlot/src/SmoothFilter.cpp
+++ b/MantidPlot/src/SmoothFilter.cpp
@@ -34,213 +34,214 @@
 
 #include <gsl/gsl_fft_halfcomplex.h>
 
-SmoothFilter::SmoothFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m)
-: Filter(parent, g)
-{
-	setDataFromCurve(curveTitle);
-	init(m);
+SmoothFilter::SmoothFilter(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle, int m)
+    : Filter(parent, g) {
+  setDataFromCurve(curveTitle);
+  init(m);
 }
 
-SmoothFilter::SmoothFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle,
-                             double start, double end, int m)
-: Filter(parent, g)
-{
-	setDataFromCurve(curveTitle, start, end);
-    init(m);
+SmoothFilter::SmoothFilter(ApplicationWindow *parent, Graph *g,
+                           const QString &curveTitle, double start, double end,
+                           int m)
+    : Filter(parent, g) {
+  setDataFromCurve(curveTitle, start, end);
+  init(m);
 }
 
-SmoothFilter::SmoothFilter(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start, int end, int m)
-: Filter(parent, t)
-{
-	setDataFromTable(t, xCol, yCol, start, end);
-	init(m);
+SmoothFilter::SmoothFilter(ApplicationWindow *parent, Table *t,
+                           const QString &xCol, const QString &yCol, int start,
+                           int end, int m)
+    : Filter(parent, t) {
+  setDataFromTable(t, xCol, yCol, start, end);
+  init(m);
 }
 
-void SmoothFilter::init (int m)
-{
-    setObjectName(tr("Smoothed"));
-    setMethod(m);
-    d_points = d_n;
-    d_smooth_points = 2;
-    d_sav_gol_points = 2;
-    d_polynom_order = 2;
+void SmoothFilter::init(int m) {
+  setObjectName(tr("Smoothed"));
+  setMethod(m);
+  d_points = d_n;
+  d_smooth_points = 2;
+  d_sav_gol_points = 2;
+  d_polynom_order = 2;
 }
 
-
-void SmoothFilter::setMethod(int m)
-{
-if (m < 1 || m > 3){
-    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-    tr("Unknown smooth filter. Valid values are: 1 - Savitky-Golay, 2 - FFT, 3 - Moving Window Average."));
+void SmoothFilter::setMethod(int m) {
+  if (m < 1 || m > 3) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("Unknown smooth filter. Valid values are: 1 - Savitky-Golay, 2 - "
+           "FFT, 3 - Moving Window Average."));
     d_init_err = true;
     return;
-    }
-d_method = (SmoothMethod)m;
+  }
+  d_method = (SmoothMethod)m;
 }
 
-void SmoothFilter::calculateOutputData(double *x, double *y)
-{
-    for (int i = 0; i < d_points; i++){
-	   x[i] = d_x[i];
-	   y[i] = d_y[i];//filtering frequencies
-	}
-
-	switch((int)d_method)
-	{
-		case 1:
-            d_explanation = QString::number(d_smooth_points) + " " + tr("points") + " " + tr("Savitzky-Golay smoothing");
-            smoothSavGol(x, y);
-			break;
-		case 2:
-            d_explanation = QString::number(d_smooth_points) + " " + tr("points") + " " + tr("FFT smoothing");
-    		smoothFFT(x, y);
-			break;
-		case 3:
-            d_explanation = QString::number(d_smooth_points) + " " + tr("points") + " " + tr("average smoothing");
-    		smoothAverage(x, y);
-			break;
-	}
+void SmoothFilter::calculateOutputData(double *x, double *y) {
+  for (int i = 0; i < d_points; i++) {
+    x[i] = d_x[i];
+    y[i] = d_y[i]; // filtering frequencies
+  }
+
+  switch ((int)d_method) {
+  case 1:
+    d_explanation = QString::number(d_smooth_points) + " " + tr("points") +
+                    " " + tr("Savitzky-Golay smoothing");
+    smoothSavGol(x, y);
+    break;
+  case 2:
+    d_explanation = QString::number(d_smooth_points) + " " + tr("points") +
+                    " " + tr("FFT smoothing");
+    smoothFFT(x, y);
+    break;
+  case 3:
+    d_explanation = QString::number(d_smooth_points) + " " + tr("points") +
+                    " " + tr("average smoothing");
+    smoothAverage(x, y);
+    break;
+  }
 }
 
-void SmoothFilter::smoothFFT(double *x, double *y)
-{
-	gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n);
-	gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n);
-	gsl_fft_real_transform (y, 1, d_n, real, work);//FFT forward
-	gsl_fft_real_wavetable_free (real);
-
-	double df = 1.0/(double)(x[1] - x[0]);
-	double lf = df/(double)d_smooth_points;//frequency cutoff
-	df = 0.5*df/(double)d_n;
-
-    for (int i = 0; i < d_n; i++){
-	   x[i] = d_x[i];
-	   y[i] = i*df > lf ? 0 : y[i];//filtering frequencies
-	}
-
-	gsl_fft_halfcomplex_wavetable *hc = gsl_fft_halfcomplex_wavetable_alloc (d_n);
-	gsl_fft_halfcomplex_inverse (y, 1, d_n, hc, work);//FFT inverse
-	gsl_fft_halfcomplex_wavetable_free (hc);
-	gsl_fft_real_workspace_free (work);
+void SmoothFilter::smoothFFT(double *x, double *y) {
+  gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n);
+  gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n);
+  gsl_fft_real_transform(y, 1, d_n, real, work); // FFT forward
+  gsl_fft_real_wavetable_free(real);
+
+  double df = 1.0 / (double)(x[1] - x[0]);
+  double lf = df / (double)d_smooth_points; // frequency cutoff
+  df = 0.5 * df / (double)d_n;
+
+  for (int i = 0; i < d_n; i++) {
+    x[i] = d_x[i];
+    y[i] = i * df > lf ? 0 : y[i]; // filtering frequencies
+  }
+
+  gsl_fft_halfcomplex_wavetable *hc = gsl_fft_halfcomplex_wavetable_alloc(d_n);
+  gsl_fft_halfcomplex_inverse(y, 1, d_n, hc, work); // FFT inverse
+  gsl_fft_halfcomplex_wavetable_free(hc);
+  gsl_fft_real_workspace_free(work);
 }
 
-void SmoothFilter::smoothAverage(double *, double *y)
-{
-	int p2 = d_smooth_points/2;
-	double m = double(2*p2+1);
-	double aux = 0.0;
-    double *s = new double[d_n];
-
-	s[0] = y[0];
-	for (int i=1; i<p2; i++){
-		aux = 0.0;
-		for (int j=-i; j<=i; j++)
-			aux += y[i+j];
-
-		s[i] = aux/(double)(2*i+1);
-	}
-	for (int i=p2; i<d_n-p2; i++){
-		aux = 0.0;
-		for (int j=-p2; j<=p2; j++)
-			aux += y[i+j];
-
-		s[i] = aux/m;
-	}
-	for (int i=d_n-p2; i<d_n-1; i++){
-		aux = 0.0;
-		for (int j=d_n-i-1; j>=i-d_n+1; j--)
-			aux += y[i+j];
-
-		s[i] = aux/(double)(2*(d_n-i-1)+1);
-	}
-	s[d_n-1] = y[d_n-1];
-
-    for (int i = 0; i<d_n; i++)
-        y[i] = s[i];
-
-    delete[] s;
+void SmoothFilter::smoothAverage(double *, double *y) {
+  int p2 = d_smooth_points / 2;
+  double m = double(2 * p2 + 1);
+  double aux = 0.0;
+  double *s = new double[d_n];
+
+  s[0] = y[0];
+  for (int i = 1; i < p2; i++) {
+    aux = 0.0;
+    for (int j = -i; j <= i; j++)
+      aux += y[i + j];
+
+    s[i] = aux / (double)(2 * i + 1);
+  }
+  for (int i = p2; i < d_n - p2; i++) {
+    aux = 0.0;
+    for (int j = -p2; j <= p2; j++)
+      aux += y[i + j];
+
+    s[i] = aux / m;
+  }
+  for (int i = d_n - p2; i < d_n - 1; i++) {
+    aux = 0.0;
+    for (int j = d_n - i - 1; j >= i - d_n + 1; j--)
+      aux += y[i + j];
+
+    s[i] = aux / (double)(2 * (d_n - i - 1) + 1);
+  }
+  s[d_n - 1] = y[d_n - 1];
+
+  for (int i = 0; i < d_n; i++)
+    y[i] = s[i];
+
+  delete[] s;
 }
 
-void SmoothFilter::smoothSavGol(double *, double *y)
-{
-	double *s = new double[d_n];
-    int nl = d_smooth_points;
-    int nr = d_sav_gol_points;
-	int np = nl+nr+1;
-	double *c = vector(1, np);
-
-	//seek shift index for given case nl, nr, m (see savgol).
-	int *index = intvector(1, np);
-	index[1]=0;
-	int i, j=3;
-	for (i=2; i<=nl+1; i++)
-	{// index(2)=-1; index(3)=-2; index(4)=-3; index(5)=-4; index(6)=-5
-		index[i]=i-j;
-		j += 2;
-	}
-	j=2;
-	for (i=nl+2; i<=np; i++)
-	{// index(7)= 5; index(8)= 4; index(9)= 3; index(10)=2; index(11)=1
-		index[i]=i-j;
-		j += 2;
-	}
-
-	//calculate Savitzky-Golay filter coefficients.
-	savgol(c, np, nl, nr, 0, d_polynom_order);
-
-	for (i=0; i<d_n; i++){// Apply filter to input data.
-		s[i]=0.0;
-		for (j=1; j<=np; j++){
-			int it = i+index[j];
-			if (it >=0 && it < d_n)//skip left points that do not exist.
-				s[i] += c[j]*y[i+index[j]];
-		}
-	}
-
-    for (i = 0; i<d_n; i++)
-        y[i] = s[i];
-
-	delete[] s;
-	free_vector(c, 1, np);
-	free_intvector(index, 1, np);
-}
-
-void SmoothFilter::setSmoothPoints(int points, int left_points)
-{
-    if (points < 0 || left_points < 0)
-    {
-        QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("The number of points must be positive!"));
-		d_init_err = true;
-		return;
-    }
-    else if (d_polynom_order > points + left_points)
-    {
-        QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("The polynomial order must be lower than the number of left points plus the number of right points!"));
-		d_init_err = true;
-		return;
+void SmoothFilter::smoothSavGol(double *, double *y) {
+  double *s = new double[d_n];
+  int nl = d_smooth_points;
+  int nr = d_sav_gol_points;
+  int np = nl + nr + 1;
+  double *c = vector(1, np);
+
+  // seek shift index for given case nl, nr, m (see savgol).
+  int *index = intvector(1, np);
+  index[1] = 0;
+  int i, j = 3;
+  for (i = 2; i <= nl + 1;
+       i++) { // index(2)=-1; index(3)=-2; index(4)=-3; index(5)=-4; index(6)=-5
+    index[i] = i - j;
+    j += 2;
+  }
+  j = 2;
+  for (i = nl + 2; i <= np;
+       i++) { // index(7)= 5; index(8)= 4; index(9)= 3; index(10)=2; index(11)=1
+    index[i] = i - j;
+    j += 2;
+  }
+
+  // calculate Savitzky-Golay filter coefficients.
+  savgol(c, np, nl, nr, 0, d_polynom_order);
+
+  for (i = 0; i < d_n; i++) { // Apply filter to input data.
+    s[i] = 0.0;
+    for (j = 1; j <= np; j++) {
+      int it = i + index[j];
+      if (it >= 0 && it < d_n) // skip left points that do not exist.
+        s[i] += c[j] * y[i + index[j]];
     }
+  }
 
-    d_smooth_points = points;
-    d_sav_gol_points = left_points;
+  for (i = 0; i < d_n; i++)
+    y[i] = s[i];
+
+  delete[] s;
+  free_vector(c, 1, np);
+  free_intvector(index, 1, np);
 }
 
-void SmoothFilter::setPolynomOrder(int order)
-{
-	if (d_method != SavitzkyGolay)
-    {
-        QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("Setting polynomial order is only available for Savitzky-Golay smooth filters! Ignored option!"));
-		return;
-    }
+void SmoothFilter::setSmoothPoints(int points, int left_points) {
+  if (points < 0 || left_points < 0) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("The number of points must be positive!"));
+    d_init_err = true;
+    return;
+  } else if (d_polynom_order > points + left_points) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("The polynomial order must be lower than the number of left points "
+           "plus the number of right points!"));
+    d_init_err = true;
+    return;
+  }
 
-    if (order > d_smooth_points + d_sav_gol_points)
-    {
-        QMessageBox::critical(static_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
-				tr("The polynomial order must be lower than the number of left points plus the number of right points!"));
-		d_init_err = true;
-		return;
-    }
-    d_polynom_order = order;
+  d_smooth_points = points;
+  d_sav_gol_points = left_points;
+}
+
+void SmoothFilter::setPolynomOrder(int order) {
+  if (d_method != SavitzkyGolay) {
+    QMessageBox::critical(static_cast<ApplicationWindow *>(parent()),
+                          tr("MantidPlot") + " - " + tr("Error"),
+                          tr("Setting polynomial order is only available for "
+                             "Savitzky-Golay smooth filters! Ignored option!"));
+    return;
+  }
+
+  if (order > d_smooth_points + d_sav_gol_points) {
+    QMessageBox::critical(
+        static_cast<ApplicationWindow *>(parent()),
+        tr("MantidPlot") + " - " + tr("Error"),
+        tr("The polynomial order must be lower than the number of left points "
+           "plus the number of right points!"));
+    d_init_err = true;
+    return;
+  }
+  d_polynom_order = order;
 }
diff --git a/MantidPlot/src/SmoothFilter.h b/MantidPlot/src/SmoothFilter.h
index 78f26e36d2c97de83372a1f67161da482f15bdeb..f2dd068042f96b84606e9171e4a8df01911653e5 100644
--- a/MantidPlot/src/SmoothFilter.h
+++ b/MantidPlot/src/SmoothFilter.h
@@ -31,42 +31,45 @@
 
 #include "Filter.h"
 
-class SmoothFilter : public Filter
-{
-Q_OBJECT
+class SmoothFilter : public Filter {
+  Q_OBJECT
 
 public:
-	SmoothFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, int m = 3);
-	SmoothFilter(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end, int m = 3);
-	SmoothFilter(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int start = 0, int end = -1, int m = 3);
+  SmoothFilter(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+               int m = 3);
+  SmoothFilter(ApplicationWindow *parent, Graph *g, const QString &curveTitle,
+               double start, double end, int m = 3);
+  SmoothFilter(ApplicationWindow *parent, Table *t, const QString &xCol,
+               const QString &yCol, int start = 0, int end = -1, int m = 3);
 
-    enum SmoothMethod{SavitzkyGolay = 1, FFT = 2, Average = 3};
+  enum SmoothMethod { SavitzkyGolay = 1, FFT = 2, Average = 3 };
 
-    int method(){return (int)d_method;};
-    void setMethod(int m);
+  int method() { return (int)d_method; };
+  void setMethod(int m);
 
-    void setSmoothPoints(int points, int left_points = 0);
-    //! Sets the polynomial order in the Savitky-Golay algorithm.
-    void setPolynomOrder(int order);
+  void setSmoothPoints(int points, int left_points = 0);
+  //! Sets the polynomial order in the Savitky-Golay algorithm.
+  void setPolynomOrder(int order);
 
 private:
-    void init(int m);
-    void calculateOutputData(double *x, double *y) override;
-    void smoothFFT(double *x, double *y);
-    void smoothAverage(double *x, double *y);
-    void smoothSavGol(double *x, double *y);
+  void init(int m);
+  void calculateOutputData(double *x, double *y) override;
+  void smoothFFT(double *x, double *y);
+  void smoothAverage(double *x, double *y);
+  void smoothSavGol(double *x, double *y);
 
-    //! The smooth method.
-    SmoothMethod d_method;
+  //! The smooth method.
+  SmoothMethod d_method;
 
-    //! The number of adjacents points used to smooth the data set.
-    int d_smooth_points;
+  //! The number of adjacents points used to smooth the data set.
+  int d_smooth_points;
 
-    //! The number of left adjacents points used by the Savitky-Golay algorithm.
-    int d_sav_gol_points;
+  //! The number of left adjacents points used by the Savitky-Golay algorithm.
+  int d_sav_gol_points;
 
-    //! Polynomial order in the Savitky-Golay algorithm (see Numerical Receipes in C for details).
-    int d_polynom_order;
+  //! Polynomial order in the Savitky-Golay algorithm (see Numerical Receipes in
+  // C for details).
+  int d_polynom_order;
 };
 
 #endif
diff --git a/MantidPlot/src/SortDialog.cpp b/MantidPlot/src/SortDialog.cpp
index ecf84f290b3bcb979f06f9dbdda0b4780f9460b8..675fc7d84e4f43959477dcc31525fb5d869793cf 100644
--- a/MantidPlot/src/SortDialog.cpp
+++ b/MantidPlot/src/SortDialog.cpp
@@ -2,7 +2,8 @@
     File                 : SortDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Sorting options dialog
 
@@ -35,68 +36,64 @@
 #include <QLayout>
 #include <QApplication>
 
-SortDialog::SortDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
-	setWindowTitle(tr("MantidPlot - Sorting Options"));
-	setSizeGripEnabled(true);
-
-	QGroupBox *groupBox1 = new QGroupBox();
-	QGridLayout * topLayout = new QGridLayout(groupBox1);
-	QHBoxLayout * hl = new QHBoxLayout();
-	hl->addStretch();
-
-	topLayout->addWidget( new QLabel(tr("Sort columns")), 0, 0 );
-	boxType = new QComboBox();
-	boxType->addItem(tr("Separately"));
-	boxType->addItem(tr("Together"));
-	topLayout->addWidget(boxType, 0, 1 );
-
-	topLayout->addWidget( new QLabel( tr("Order")), 1, 0 );
-	boxOrder = new QComboBox();
-	boxOrder->addItem(tr("Ascending"));
-	boxOrder->addItem(tr("Descending"));
-	topLayout->addWidget(boxOrder, 1, 1 );
-
-	topLayout->addWidget( new QLabel(tr("Leading column")), 2, 0 );
-	columnsList = new QComboBox();
-	topLayout->addWidget(columnsList, 2, 1);
-	topLayout->setRowStretch(3, 1);
-
-	buttonOk = new QPushButton(tr("&Sort"));
-	buttonOk->setDefault( true );
-	hl->addWidget(buttonOk);
-
-	buttonCancel = new QPushButton(tr("&Close"));
-	hl->addWidget(buttonCancel);
-
-	QVBoxLayout * mainlayout = new QVBoxLayout(this);
-	mainlayout->addWidget(groupBox1);
-	mainlayout->addLayout(hl);
-
-	connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-	connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-	connect( boxType, SIGNAL( activated(int) ), this, SLOT(changeType(int)));
+SortDialog::SortDialog(QWidget *parent, Qt::WFlags fl) : QDialog(parent, fl) {
+  setWindowTitle(tr("MantidPlot - Sorting Options"));
+  setSizeGripEnabled(true);
+
+  QGroupBox *groupBox1 = new QGroupBox();
+  QGridLayout *topLayout = new QGridLayout(groupBox1);
+  QHBoxLayout *hl = new QHBoxLayout();
+  hl->addStretch();
+
+  topLayout->addWidget(new QLabel(tr("Sort columns")), 0, 0);
+  boxType = new QComboBox();
+  boxType->addItem(tr("Separately"));
+  boxType->addItem(tr("Together"));
+  topLayout->addWidget(boxType, 0, 1);
+
+  topLayout->addWidget(new QLabel(tr("Order")), 1, 0);
+  boxOrder = new QComboBox();
+  boxOrder->addItem(tr("Ascending"));
+  boxOrder->addItem(tr("Descending"));
+  topLayout->addWidget(boxOrder, 1, 1);
+
+  topLayout->addWidget(new QLabel(tr("Leading column")), 2, 0);
+  columnsList = new QComboBox();
+  topLayout->addWidget(columnsList, 2, 1);
+  topLayout->setRowStretch(3, 1);
+
+  buttonOk = new QPushButton(tr("&Sort"));
+  buttonOk->setDefault(true);
+  hl->addWidget(buttonOk);
+
+  buttonCancel = new QPushButton(tr("&Close"));
+  hl->addWidget(buttonCancel);
+
+  QVBoxLayout *mainlayout = new QVBoxLayout(this);
+  mainlayout->addWidget(groupBox1);
+  mainlayout->addLayout(hl);
+
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(boxType, SIGNAL(activated(int)), this, SLOT(changeType(int)));
 }
 
-void SortDialog::accept()
-{
-	emit sort(boxType->currentIndex(),boxOrder->currentIndex(),columnsList->currentText());
+void SortDialog::accept() {
+  emit sort(boxType->currentIndex(), boxOrder->currentIndex(),
+            columnsList->currentText());
 }
 
-void SortDialog::insertColumnsList(const QStringList& cols)
-{
-	columnsList->addItems(cols);
-	columnsList->setCurrentIndex(0);
+void SortDialog::insertColumnsList(const QStringList &cols) {
+  columnsList->addItems(cols);
+  columnsList->setCurrentIndex(0);
 
-	boxType->setCurrentIndex(1);
+  boxType->setCurrentIndex(1);
 }
 
-void SortDialog::changeType(int Type)
-{
-	boxType->setCurrentIndex(Type);
-	if(Type==1)
-		columnsList->setEnabled(true);
-	else
-		columnsList->setEnabled(false);
+void SortDialog::changeType(int Type) {
+  boxType->setCurrentIndex(Type);
+  if (Type == 1)
+    columnsList->setEnabled(true);
+  else
+    columnsList->setEnabled(false);
 }
diff --git a/MantidPlot/src/SortDialog.h b/MantidPlot/src/SortDialog.h
index f4e2f37f2eb790bf9ab92875d0fac625864ad448..c0cec16a227581033bba4a771b4a836a1afebadd 100644
--- a/MantidPlot/src/SortDialog.h
+++ b/MantidPlot/src/SortDialog.h
@@ -2,7 +2,8 @@
     File                 : SortDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Sort table dialog
 
@@ -35,26 +36,25 @@ class QPushButton;
 class QComboBox;
 
 //! Sorting options dialog
-class SortDialog : public QDialog
-{
+class SortDialog : public QDialog {
   Q_OBJECT
 
 public:
-  SortDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
-  void insertColumnsList(const QStringList& cols);
+  SortDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
+  void insertColumnsList(const QStringList &cols);
 
 private slots:
   void accept() override;
   void changeType(int index);
 
 signals:
-  void sort(int, int, const QString&);
+  void sort(int, int, const QString &);
 
 private:
-  QPushButton* buttonOk;
-  QPushButton* buttonCancel;
-  QComboBox* boxType;
-  QComboBox* boxOrder;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QComboBox *boxType;
+  QComboBox *boxOrder;
   QComboBox *columnsList;
 };
 
diff --git a/MantidPlot/src/Spectrogram.cpp b/MantidPlot/src/Spectrogram.cpp
index 77d6964abeba292092f16be5624b21ab6b9b56f7..5a2461c76353334a87882039b38769eabba4be3d 100644
--- a/MantidPlot/src/Spectrogram.cpp
+++ b/MantidPlot/src/Spectrogram.cpp
@@ -799,7 +799,7 @@ void Spectrogram::drawContourLines(
 void Spectrogram::updateLabels(
     QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
     const QwtRasterData::ContourLines &contourLines) const {
-  (void)p; // Avoid compiler warning
+  (void)p;    // Avoid compiler warning
   (void)xMap; // Avoid compiler warning
   (void)yMap; // Avoid compiler warning
 
diff --git a/MantidPlot/src/Spectrogram.h b/MantidPlot/src/Spectrogram.h
index 57950adbae461a4a7e66c8f1525d03cf874f8add..d30a5ec7cb70e8d27faaa31aa9f311085d4896e8 100644
--- a/MantidPlot/src/Spectrogram.h
+++ b/MantidPlot/src/Spectrogram.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : Spectrogram.h
-	Project              : QtiPlot
+        File                 : Spectrogram.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : QtiPlot's Spectrogram Class
+        Copyright            : (C) 2006 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : QtiPlot's Spectrogram Class
  ***************************************************************************/
 
 /***************************************************************************
@@ -53,27 +53,29 @@
 class MatrixData;
 class PlotMarker;
 
-namespace MantidQt
-{
-  namespace API
-  {
-    class QwtRasterDataMD;
-  }
+namespace MantidQt {
+namespace API {
+class QwtRasterDataMD;
+}
 }
 
-class Spectrogram: public QObject, public QwtPlotSpectrogram, public MantidQt::API::WorkspaceObserver
-{
+class Spectrogram : public QObject,
+                    public QwtPlotSpectrogram,
+                    public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 
 public:
   Spectrogram();
   explicit Spectrogram(Matrix *m);
-  Spectrogram(const QString &wsName, const Mantid::API::IMDWorkspace_const_sptr & workspace);
-  Spectrogram(Function2D *f,int nrows, int ncols,double left, double top, double width, double height,double minz,double maxz);//Mantid
-  Spectrogram(Function2D *f,int nrows, int ncols,QwtDoubleRect bRect,double minz,double maxz);//Mantid
+  Spectrogram(const QString &wsName,
+              const Mantid::API::IMDWorkspace_const_sptr &workspace);
+  Spectrogram(Function2D *f, int nrows, int ncols, double left, double top,
+              double width, double height, double minz, double maxz); // Mantid
+  Spectrogram(Function2D *f, int nrows, int ncols, QwtDoubleRect bRect,
+              double minz, double maxz); // Mantid
   ~Spectrogram() override;
 
-  void loadFromProject(const std::string& lines);
+  void loadFromProject(const std::string &lines);
   std::string saveToProject();
 
   /// Handles delete notification
@@ -85,20 +87,20 @@ public:
   /// Handle an ADS clear notificiation
   void clearADSHandle() override;
 
-  enum ColorMapPolicy{GrayScale, Default, Custom};
+  enum ColorMapPolicy { GrayScale, Default, Custom };
 
   QImage renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                      const QwtDoubleRect &rect) const override;
 
-  Spectrogram* copy();
-  Matrix * matrix(){return d_matrix;};
-  Function2D *funct(){return d_funct;}
+  Spectrogram *copy();
+  Matrix *matrix() { return d_matrix; };
+  Function2D *funct() { return d_funct; }
 
-  int levels()const{return (int)contourLevels().size() + 1;};
+  int levels() const { return (int)contourLevels().size() + 1; };
   void setLevelsNumber(int levels);
 
   bool hasColorScale();
-  int colorScaleAxis(){return color_axis;};
+  int colorScaleAxis() { return color_axis; };
   void showColorScale(int axis, bool on = true);
 
   int colorBarWidth();
@@ -109,11 +111,11 @@ public:
   MantidColorMap getDefaultColorMap();
   static QwtLinearColorMap defaultColorMap();
 
-  void loadColorMap(const QString& file);
-  void setCustomColorMap(const QwtLinearColorMap& map);
+  void loadColorMap(const QString &file);
+  void setCustomColorMap(const QwtLinearColorMap &map);
   void setMantidColorMap(const MantidColorMap &map);
   void updateData(Matrix *m);
-  void updateData(const Mantid::API::IMDWorkspace_const_sptr & workspace);
+  void updateData(const Mantid::API::IMDWorkspace_const_sptr &workspace);
   MantidQt::API::QwtRasterDataMD *
   dataFromWorkspace(const Mantid::API::IMDWorkspace_const_sptr &workspace,
                     const QwtDoubleInterval *range = nullptr);
@@ -123,36 +125,37 @@ public:
     d_color_map_autoscale = autoscale;
   }
 
-  ColorMapPolicy colorMapPolicy()const{return color_map_policy;};
+  ColorMapPolicy colorMapPolicy() const { return color_map_policy; };
 
   QwtDoubleRect boundingRect() const override;
-  double getMinPositiveValue()const;
+  double getMinPositiveValue() const;
   void setContourPenList(QList<QPen> lst);
   void setContourLinePen(int index, const QPen &pen);
-  QList<QPen> contourPenList(){return d_pen_list;};
-  //! Flag telling if we use the color map to calculate the pen (QwtPlotSpectrogram::contourPen()).
+  QList<QPen> contourPenList() { return d_pen_list; };
+  //! Flag telling if we use the color map to calculate the pen
+  //(QwtPlotSpectrogram::contourPen()).
   bool d_color_map_pen;
-  bool useColorMapPen()const{return d_color_map_pen;};
+  bool useColorMapPen() const { return d_color_map_pen; };
   void setColorMapPen(bool on = true);
   void showContourLineLabels(bool show = true);
-  bool hasLabels(){return d_show_labels;};
-  QFont labelsFont(){return d_labels_font;};
-  void setLabelsFont(const QFont& font);
+  bool hasLabels() { return d_show_labels; };
+  QFont labelsFont() { return d_labels_font; };
+  void setLabelsFont(const QFont &font);
 
-  QList <PlotMarker *> labelsList(){return d_labels_list;};
-  const MantidColorMap & getColorMap() const;
-  MantidColorMap & mutableColorMap();
+  QList<PlotMarker *> labelsList() { return d_labels_list; };
+  const MantidColorMap &getColorMap() const;
+  MantidColorMap &mutableColorMap();
   void saveSettings();
   void loadSettings();
   void setColorMapFileName(QString colormapName);
-  double labelsRotation(){return d_labels_angle;};
+  double labelsRotation() { return d_labels_angle; };
   void setLabelsRotation(double angle);
-  bool labelsWhiteOut(){return d_white_out_labels;};
+  bool labelsWhiteOut() { return d_white_out_labels; };
   void setLabelsWhiteOut(bool whiteOut);
   void setLabelsOffset(double x, double y);
   void setLabelOffset(int index, double x, double y);
-  QColor labelsColor(){return d_labels_color;};
-  void setLabelsColor(const QColor& c);
+  QColor labelsColor() { return d_labels_color; };
+  void setLabelsColor(const QColor &c);
   //	void setLabelOffset(int index, double x, double y);
 
   void updateForNewMaxData(const double new_max);
@@ -160,28 +163,30 @@ public:
   void recount();
   void setCustomColorMap(const QwtColorMap &map);
 
-  void setContourLevels (const QwtValueList & levels);
+  void setContourLevels(const QwtValueList &levels);
   bool hasSelectedLabels();
-  bool selectedLabels(const QPoint& pos);
-  double labelsXOffset(){return d_labels_x_offset;};
-  double labelsYOffset(){return d_labels_y_offset;};
+  bool selectedLabels(const QPoint &pos);
+  double labelsXOffset() { return d_labels_x_offset; };
+  double labelsYOffset() { return d_labels_y_offset; };
   void selectLabel(bool on);
   /// change intensity of the colors
-  void changeIntensity( double start,double end);
-  ///sets a boolan flag for intensity changes
+  void changeIntensity(double start, double end);
+  /// sets a boolan flag for intensity changes
   void setIntensityChange(bool on);
   /// returns boolan flag intensity change
   bool isIntensityChanged();
 
 signals:
-  void removeMe(Spectrogram*);
+  void removeMe(Spectrogram *);
 
 protected:
   void
   drawContourLines(QPainter *p, const QwtScaleMap &xMap,
                    const QwtScaleMap &yMap,
                    const QwtRasterData::ContourLines &lines) const override;
-  void updateLabels(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtRasterData::ContourLines &lines) const;
+  void updateLabels(QPainter *p, const QwtScaleMap &xMap,
+                    const QwtScaleMap &yMap,
+                    const QwtRasterData::ContourLines &lines) const;
   void createLabels();
 
   //! Pointer to the source data matrix
@@ -207,11 +212,13 @@ protected:
   bool d_white_out_labels;
   double d_labels_angle;
   //! List of the text labels associated to this spectrogram.
-  QList <PlotMarker *> d_labels_list;
-  //! Keeps track of the plot marker on which the user clicked when selecting the labels.
+  QList<PlotMarker *> d_labels_list;
+  //! Keeps track of the plot marker on which the user clicked when selecting
+  // the labels.
   PlotMarker *d_selected_label;
 
-  //! Keep track of the coordinates of the point where the user clicked when selecting the labels.
+  //! Keep track of the coordinates of the point where the user clicked when
+  // selecting the labels.
   double d_click_pos_x, d_click_pos_y;
   //! Labels color
   QColor d_labels_color;
@@ -233,25 +240,22 @@ protected:
   bool d_color_map_autoscale;
 };
 
-class SpectrogramData: public QwtRasterData
-{
+class SpectrogramData : public QwtRasterData {
 public:
   explicit SpectrogramData(const QwtDoubleRect &rect) : QwtRasterData(rect) {}
-  virtual double getMinPositiveValue()const = 0;
+  virtual double getMinPositiveValue() const = 0;
 };
 
-
-class MatrixData: public SpectrogramData
-{
+class MatrixData : public SpectrogramData {
 public:
   explicit MatrixData(Matrix *m)
       : SpectrogramData(m->boundingRect()), d_matrix(m) {
     n_rows = d_matrix->numRows();
     n_cols = d_matrix->numCols();
 
-    d_m = new double* [n_rows];
-    for ( int l = 0; l < n_rows; ++l)
-      d_m[l] = new double [n_cols];
+    d_m = new double *[n_rows];
+    for (int l = 0; l < n_rows; ++l)
+      d_m[l] = new double[n_cols];
 
     for (int i = 0; i < n_rows; i++)
       for (int j = 0; j < n_cols; j++)
@@ -267,9 +271,9 @@ public:
 
   ~MatrixData() override {
     for (int i = 0; i < n_rows; i++)
-      delete [] d_m[i];
+      delete[] d_m[i];
 
-    delete [] d_m;
+    delete[] d_m;
   };
 
   QwtRasterData *copy() const override { return new MatrixData(d_matrix); }
@@ -291,7 +295,7 @@ private:
   Matrix *d_matrix;
 
   //! Vector used to store in memory the data from the source matrix window
-  double** d_m;
+  double **d_m;
 
   //! Data size
   int n_rows, n_cols;
@@ -307,28 +311,25 @@ private:
 
   //! Y axis bottom value in the data matrix
   double y_start;
-
 };
 
-class FunctionData: public SpectrogramData
-{
+class FunctionData : public SpectrogramData {
 public:
-  FunctionData(Function2D *f,int nrows, int ncols,double left, double top, double width, double height,double minz,double maxz):
-    SpectrogramData(QwtDoubleRect(left, top, width, height)),
-    d_funct(f),n_rows(nrows),n_cols(ncols),min_z(minz),max_z(maxz)
-  {
-  }
+  FunctionData(Function2D *f, int nrows, int ncols, double left, double top,
+               double width, double height, double minz, double maxz)
+      : SpectrogramData(QwtDoubleRect(left, top, width, height)), d_funct(f),
+        n_rows(nrows), n_cols(ncols), min_z(minz), max_z(maxz) {}
 
-  FunctionData(Function2D *f,int nrows, int ncols,QwtDoubleRect bRect,double minz,double maxz):
-    SpectrogramData(bRect),
-    d_funct(f),n_rows(nrows),n_cols(ncols),min_z(minz),max_z(maxz)
-  {
-  }
+  FunctionData(Function2D *f, int nrows, int ncols, QwtDoubleRect bRect,
+               double minz, double maxz)
+      : SpectrogramData(bRect), d_funct(f), n_rows(nrows), n_cols(ncols),
+        min_z(minz), max_z(maxz) {}
 
   ~FunctionData() override{};
 
   QwtRasterData *copy() const override {
-    return new FunctionData(d_funct, n_rows, n_cols,boundingRect(),min_z,max_z);
+    return new FunctionData(d_funct, n_rows, n_cols, boundingRect(), min_z,
+                            max_z);
   }
 
   QwtDoubleInterval range() const override {
@@ -340,9 +341,9 @@ public:
   }
 
   double value(double x, double y) const override {
-    //static std::ofstream f("funct.txt");
-    //f<<x<<' '<<y<<' '<<d_funct->operator()(x,y)<<'\n';
-    return d_funct->operator()(x,y);
+    // static std::ofstream f("funct.txt");
+    // f<<x<<' '<<y<<' '<<d_funct->operator()(x,y)<<'\n';
+    return d_funct->operator()(x, y);
   }
 
   double getMinPositiveValue() const override {
diff --git a/MantidPlot/src/SurfaceDialog.cpp b/MantidPlot/src/SurfaceDialog.cpp
index 8d646494be80c526c19d42c8a8243ec4e051f834..90a4a081546843f74aed347b8b2dc6d0cc2a1172 100644
--- a/MantidPlot/src/SurfaceDialog.cpp
+++ b/MantidPlot/src/SurfaceDialog.cpp
@@ -45,537 +45,518 @@
 #include <QCompleter>
 #include <QApplication>
 
-SurfaceDialog::SurfaceDialog( QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl )
-{
-	setObjectName( "SurfaceDialog" );
-	setWindowTitle(tr("MantidPlot - Define surface plot"));
-    setSizeGripEnabled( true );
-
-	QHBoxLayout *hbox1 = new QHBoxLayout();
-	hbox1->addWidget(new QLabel(tr( "Surface type" )));
-	boxType = new QComboBox();
-	boxType->addItem( tr( "Function" ) );
-	boxType->addItem( tr( "Parametric" ) );
-	hbox1->addWidget(boxType);
-	hbox1->addStretch();
-
-	optionStack = new QStackedWidget();
-
-	initFunctionPage();
-	initParametricSurfacePage();
-
-	buttonClear = new QPushButton(tr("Clear &list"));
-	buttonOk = new QPushButton(tr("&OK"));
-    buttonOk->setDefault(true);
-    buttonCancel = new QPushButton(tr("&Close"));
-
-    QBoxLayout *bl2 = new QBoxLayout ( QBoxLayout::LeftToRight);
-    bl2->addStretch();
-	bl2->addWidget(buttonClear);
-	bl2->addWidget(buttonOk);
-	bl2->addWidget(buttonCancel);
-
-	QVBoxLayout* vl = new QVBoxLayout(this);
-    vl->addLayout(hbox1);
-	vl->addWidget(optionStack);
-	vl->addLayout(bl2);
-
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(parent);
-	if (app){
-		boxFunction->insertItems(0, app->surfaceFunc);
-		boxX->setCompleter (new QCompleter(app->d_param_surface_func));
-		boxY->setCompleter (new QCompleter(app->d_param_surface_func));
-		boxZ->setCompleter (new QCompleter(app->d_param_surface_func));
-	}
-
-	d_graph = 0;
-    setFocusProxy(boxFunction);
-
-	connect( boxType, SIGNAL(activated(int)), optionStack, SLOT(setCurrentIndex(int)));
-	connect( buttonClear, SIGNAL(clicked()), this, SLOT(clearList()));
-    connect( buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
-    connect( buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+SurfaceDialog::SurfaceDialog(QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
+  setObjectName("SurfaceDialog");
+  setWindowTitle(tr("MantidPlot - Define surface plot"));
+  setSizeGripEnabled(true);
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->addWidget(new QLabel(tr("Surface type")));
+  boxType = new QComboBox();
+  boxType->addItem(tr("Function"));
+  boxType->addItem(tr("Parametric"));
+  hbox1->addWidget(boxType);
+  hbox1->addStretch();
+
+  optionStack = new QStackedWidget();
+
+  initFunctionPage();
+  initParametricSurfacePage();
+
+  buttonClear = new QPushButton(tr("Clear &list"));
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setDefault(true);
+  buttonCancel = new QPushButton(tr("&Close"));
+
+  QBoxLayout *bl2 = new QBoxLayout(QBoxLayout::LeftToRight);
+  bl2->addStretch();
+  bl2->addWidget(buttonClear);
+  bl2->addWidget(buttonOk);
+  bl2->addWidget(buttonCancel);
+
+  QVBoxLayout *vl = new QVBoxLayout(this);
+  vl->addLayout(hbox1);
+  vl->addWidget(optionStack);
+  vl->addLayout(bl2);
+
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(parent);
+  if (app) {
+    boxFunction->insertItems(0, app->surfaceFunc);
+    boxX->setCompleter(new QCompleter(app->d_param_surface_func));
+    boxY->setCompleter(new QCompleter(app->d_param_surface_func));
+    boxZ->setCompleter(new QCompleter(app->d_param_surface_func));
+  }
+
+  d_graph = 0;
+  setFocusProxy(boxFunction);
+
+  connect(boxType, SIGNAL(activated(int)), optionStack,
+          SLOT(setCurrentIndex(int)));
+  connect(buttonClear, SIGNAL(clicked()), this, SLOT(clearList()));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
 }
 
-void SurfaceDialog::initFunctionPage()
-{
-	boxFunction = new QComboBox();
-	boxFunction->setEditable(true);
-
-	QBoxLayout *bl1 = new QBoxLayout (QBoxLayout::LeftToRight);
-	bl1->addWidget(new QLabel( tr("f(x,y)=")), 1);
-	bl1->addWidget(boxFunction, 10);
-
-    QGroupBox *gb1 = new QGroupBox(tr("X - axis"));
-
-	boxXFrom = new QLineEdit();
-	boxXFrom->setText(tr("-1"));
-
-	boxXTo = new QLineEdit();
-	boxXTo->setText(tr("1"));
-
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel( tr("From")), 0, 0);
-    gl1->addWidget(boxXFrom, 0, 1);
-    gl1->addWidget(new QLabel(tr("To")), 1, 0);
-    gl1->addWidget(boxXTo, 1, 1);
-    gl1->setRowStretch(2, 1);
-    gb1->setLayout(gl1);
-
-    QGroupBox *gb2 = new QGroupBox(tr("Y - axis"));
-	boxYFrom = new QLineEdit();
-	boxYFrom->setText(tr("-1"));
-
-	boxYTo = new QLineEdit();
-	boxYTo->setText(tr("1"));
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel( tr("From")), 0, 0);
-    gl2->addWidget(boxYFrom, 0, 1);
-    gl2->addWidget(new QLabel(tr("To")), 1, 0);
-    gl2->addWidget(boxYTo, 1, 1);
-    gl2->setRowStretch(2, 1);
-    gb2->setLayout(gl2);
-
-    QGroupBox *gb3 = new QGroupBox(tr("Z - axis"));
-	boxZFrom = new QLineEdit();
-	boxZFrom->setText(tr("-1"));
-
-	boxZTo = new QLineEdit();
-	boxZTo->setText(tr("1"));
-
-    QGridLayout *gl3 = new QGridLayout();
-    gl3->addWidget(new QLabel( tr("From")), 0, 0);
-    gl3->addWidget(boxZFrom, 0, 1);
-    gl3->addWidget(new QLabel(tr("To")), 1, 0);
-    gl3->addWidget(boxZTo, 1, 1);
-    gl3->setRowStretch(2, 1);
-    gb3->setLayout(gl3);
-
-	QBoxLayout *bl2 = new QBoxLayout (QBoxLayout::LeftToRight);
-	bl2->addWidget(gb1);
-	bl2->addWidget(gb2);
-	bl2->addWidget(gb3);
-
-	QGroupBox *gb4 = new QGroupBox(tr("Mesh"));
-	boxFuncColumns = new QSpinBox();
-	boxFuncColumns->setRange(1, 1000);
-	boxFuncColumns->setValue(40);
-
-	boxFuncRows = new QSpinBox();
-	boxFuncRows->setRange(1, 1000);
-	boxFuncRows->setValue(40);
-
-	QGridLayout *hb4 = new QGridLayout(gb4);
-    hb4->addWidget(new QLabel( tr("Columns")), 0, 0);
-    hb4->addWidget(boxFuncColumns, 0, 1);
-    hb4->addWidget(new QLabel(tr("Rows")), 1, 0);
-    hb4->addWidget(boxFuncRows, 1, 1);
-
-	functionPage = new QWidget();
-
-	QVBoxLayout* vl = new QVBoxLayout(functionPage);
-    vl->addLayout(bl1);
-	vl->addLayout(bl2);
-	vl->addWidget(gb4);
-
-	optionStack->addWidget(functionPage);
+void SurfaceDialog::initFunctionPage() {
+  boxFunction = new QComboBox();
+  boxFunction->setEditable(true);
+
+  QBoxLayout *bl1 = new QBoxLayout(QBoxLayout::LeftToRight);
+  bl1->addWidget(new QLabel(tr("f(x,y)=")), 1);
+  bl1->addWidget(boxFunction, 10);
+
+  QGroupBox *gb1 = new QGroupBox(tr("X - axis"));
+
+  boxXFrom = new QLineEdit();
+  boxXFrom->setText(tr("-1"));
+
+  boxXTo = new QLineEdit();
+  boxXTo->setText(tr("1"));
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("From")), 0, 0);
+  gl1->addWidget(boxXFrom, 0, 1);
+  gl1->addWidget(new QLabel(tr("To")), 1, 0);
+  gl1->addWidget(boxXTo, 1, 1);
+  gl1->setRowStretch(2, 1);
+  gb1->setLayout(gl1);
+
+  QGroupBox *gb2 = new QGroupBox(tr("Y - axis"));
+  boxYFrom = new QLineEdit();
+  boxYFrom->setText(tr("-1"));
+
+  boxYTo = new QLineEdit();
+  boxYTo->setText(tr("1"));
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("From")), 0, 0);
+  gl2->addWidget(boxYFrom, 0, 1);
+  gl2->addWidget(new QLabel(tr("To")), 1, 0);
+  gl2->addWidget(boxYTo, 1, 1);
+  gl2->setRowStretch(2, 1);
+  gb2->setLayout(gl2);
+
+  QGroupBox *gb3 = new QGroupBox(tr("Z - axis"));
+  boxZFrom = new QLineEdit();
+  boxZFrom->setText(tr("-1"));
+
+  boxZTo = new QLineEdit();
+  boxZTo->setText(tr("1"));
+
+  QGridLayout *gl3 = new QGridLayout();
+  gl3->addWidget(new QLabel(tr("From")), 0, 0);
+  gl3->addWidget(boxZFrom, 0, 1);
+  gl3->addWidget(new QLabel(tr("To")), 1, 0);
+  gl3->addWidget(boxZTo, 1, 1);
+  gl3->setRowStretch(2, 1);
+  gb3->setLayout(gl3);
+
+  QBoxLayout *bl2 = new QBoxLayout(QBoxLayout::LeftToRight);
+  bl2->addWidget(gb1);
+  bl2->addWidget(gb2);
+  bl2->addWidget(gb3);
+
+  QGroupBox *gb4 = new QGroupBox(tr("Mesh"));
+  boxFuncColumns = new QSpinBox();
+  boxFuncColumns->setRange(1, 1000);
+  boxFuncColumns->setValue(40);
+
+  boxFuncRows = new QSpinBox();
+  boxFuncRows->setRange(1, 1000);
+  boxFuncRows->setValue(40);
+
+  QGridLayout *hb4 = new QGridLayout(gb4);
+  hb4->addWidget(new QLabel(tr("Columns")), 0, 0);
+  hb4->addWidget(boxFuncColumns, 0, 1);
+  hb4->addWidget(new QLabel(tr("Rows")), 1, 0);
+  hb4->addWidget(boxFuncRows, 1, 1);
+
+  functionPage = new QWidget();
+
+  QVBoxLayout *vl = new QVBoxLayout(functionPage);
+  vl->addLayout(bl1);
+  vl->addLayout(bl2);
+  vl->addWidget(gb4);
+
+  optionStack->addWidget(functionPage);
 }
 
-void SurfaceDialog::initParametricSurfacePage()
-{
-	boxX = new QLineEdit();
-	boxY = new QLineEdit();
-	boxZ = new QLineEdit();
-
-	QGroupBox *gb = new QGroupBox(tr("Equations"));
-	QGridLayout *gl = new QGridLayout(gb);
-    gl->addWidget(new QLabel( tr("X(u,v)=")), 0, 0);
-    gl->addWidget(boxX, 0, 1);
-    gl->addWidget(new QLabel(tr("Y(u,v)=")), 1, 0);
-    gl->addWidget(boxY, 1, 1);
-	gl->addWidget(new QLabel(tr("Z(u,v)=")), 2, 0);
-    gl->addWidget(boxZ, 2, 1);
-    gl->setRowStretch(3, 1);
-
-    QGroupBox *gb1 = new QGroupBox(tr("u"));
-	boxUFrom = new QLineEdit();
-	boxUFrom->setText("0");
-	boxUTo = new QLineEdit();
-	boxUTo->setText("pi");
-    QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel( tr("From")), 0, 0);
-    gl1->addWidget(boxUFrom, 0, 1);
-    gl1->addWidget(new QLabel(tr("To")), 1, 0);
-    gl1->addWidget(boxUTo, 1, 1);
-	boxUPeriodic = new QCheckBox(tr("Periodic"));
-	gl1->addWidget(boxUPeriodic, 2, 1);
-    gl1->setRowStretch(3, 1);
-    gb1->setLayout(gl1);
-
-    QGroupBox *gb2 = new QGroupBox(tr("v"));
-	boxVFrom = new QLineEdit();
-	boxVFrom->setText("0");
-
-	boxVTo = new QLineEdit();
-	boxVTo->setText("pi");
-
-    QGridLayout *gl2 = new QGridLayout();
-    gl2->addWidget(new QLabel( tr("From")), 0, 0);
-    gl2->addWidget(boxVFrom, 0, 1);
-    gl2->addWidget(new QLabel(tr("To")), 1, 0);
-    gl2->addWidget(boxVTo, 1, 1);
-	boxVPeriodic = new QCheckBox(tr("Periodic"));
-	gl2->addWidget(boxVPeriodic, 2, 1);
-    gl2->setRowStretch(3, 1);
-    gb2->setLayout(gl2);
-
-	QGroupBox *gb3 = new QGroupBox(tr("Mesh"));
-	boxColumns = new QSpinBox();
-	boxColumns->setRange(1, 1000);
-	boxColumns->setValue(40);
-
-	boxRows = new QSpinBox();
-	boxRows->setRange(1, 1000);
-	boxRows->setValue(40);
-
-    QGridLayout *gl3 = new QGridLayout();
-    gl3->addWidget(new QLabel( tr("Columns")), 0, 0);
-    gl3->addWidget(boxColumns, 0, 1);
-    gl3->addWidget(new QLabel(tr("Rows")), 1, 0);
-    gl3->addWidget(boxRows, 1, 1);
-    gl3->setRowStretch(2, 1);
-    gb3->setLayout(gl3);
-
-	QBoxLayout *bl2 = new QBoxLayout (QBoxLayout::LeftToRight);
-	bl2->addWidget(gb1);
-	bl2->addWidget(gb2);
-	bl2->addWidget(gb3);
-
-	parametricPage = new QWidget();
-
-	QVBoxLayout* vl = new QVBoxLayout(parametricPage);
-    vl->addWidget(gb);
-	vl->addLayout(bl2);
-
-	optionStack->addWidget(parametricPage);
+void SurfaceDialog::initParametricSurfacePage() {
+  boxX = new QLineEdit();
+  boxY = new QLineEdit();
+  boxZ = new QLineEdit();
+
+  QGroupBox *gb = new QGroupBox(tr("Equations"));
+  QGridLayout *gl = new QGridLayout(gb);
+  gl->addWidget(new QLabel(tr("X(u,v)=")), 0, 0);
+  gl->addWidget(boxX, 0, 1);
+  gl->addWidget(new QLabel(tr("Y(u,v)=")), 1, 0);
+  gl->addWidget(boxY, 1, 1);
+  gl->addWidget(new QLabel(tr("Z(u,v)=")), 2, 0);
+  gl->addWidget(boxZ, 2, 1);
+  gl->setRowStretch(3, 1);
+
+  QGroupBox *gb1 = new QGroupBox(tr("u"));
+  boxUFrom = new QLineEdit();
+  boxUFrom->setText("0");
+  boxUTo = new QLineEdit();
+  boxUTo->setText("pi");
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("From")), 0, 0);
+  gl1->addWidget(boxUFrom, 0, 1);
+  gl1->addWidget(new QLabel(tr("To")), 1, 0);
+  gl1->addWidget(boxUTo, 1, 1);
+  boxUPeriodic = new QCheckBox(tr("Periodic"));
+  gl1->addWidget(boxUPeriodic, 2, 1);
+  gl1->setRowStretch(3, 1);
+  gb1->setLayout(gl1);
+
+  QGroupBox *gb2 = new QGroupBox(tr("v"));
+  boxVFrom = new QLineEdit();
+  boxVFrom->setText("0");
+
+  boxVTo = new QLineEdit();
+  boxVTo->setText("pi");
+
+  QGridLayout *gl2 = new QGridLayout();
+  gl2->addWidget(new QLabel(tr("From")), 0, 0);
+  gl2->addWidget(boxVFrom, 0, 1);
+  gl2->addWidget(new QLabel(tr("To")), 1, 0);
+  gl2->addWidget(boxVTo, 1, 1);
+  boxVPeriodic = new QCheckBox(tr("Periodic"));
+  gl2->addWidget(boxVPeriodic, 2, 1);
+  gl2->setRowStretch(3, 1);
+  gb2->setLayout(gl2);
+
+  QGroupBox *gb3 = new QGroupBox(tr("Mesh"));
+  boxColumns = new QSpinBox();
+  boxColumns->setRange(1, 1000);
+  boxColumns->setValue(40);
+
+  boxRows = new QSpinBox();
+  boxRows->setRange(1, 1000);
+  boxRows->setValue(40);
+
+  QGridLayout *gl3 = new QGridLayout();
+  gl3->addWidget(new QLabel(tr("Columns")), 0, 0);
+  gl3->addWidget(boxColumns, 0, 1);
+  gl3->addWidget(new QLabel(tr("Rows")), 1, 0);
+  gl3->addWidget(boxRows, 1, 1);
+  gl3->setRowStretch(2, 1);
+  gb3->setLayout(gl3);
+
+  QBoxLayout *bl2 = new QBoxLayout(QBoxLayout::LeftToRight);
+  bl2->addWidget(gb1);
+  bl2->addWidget(gb2);
+  bl2->addWidget(gb3);
+
+  parametricPage = new QWidget();
+
+  QVBoxLayout *vl = new QVBoxLayout(parametricPage);
+  vl->addWidget(gb);
+  vl->addLayout(bl2);
+
+  optionStack->addWidget(parametricPage);
 }
 
-void SurfaceDialog::clearList()
-{
-    ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-
-    if (app && boxType->currentIndex()){
-        app->d_param_surface_func.clear();
-    }else{
-        boxFunction->clear();
-        if (app)
-            app->clearSurfaceFunctionsList();
-    }
-}
+void SurfaceDialog::clearList() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
 
-void SurfaceDialog::setFunction(Graph3D *g)
-{
-	if (!g)
-		return;
-
-	d_graph = g;
-    UserFunction2D *f = dynamic_cast<UserFunction2D*>( d_graph->userFunction() );
-	if (!f)
-		return;
-
-    boxFunction->setItemText(boxFunction->currentIndex(), f->formula());
-    boxFuncColumns->setValue(static_cast<int>(f->columns()));
-    boxFuncRows->setValue(static_cast<int>(f->rows()));
-
-	boxXFrom->setText(QString::number(g->xStart()));
-	boxXTo->setText(QString::number(g->xStop()));
-	boxYFrom->setText(QString::number(g->yStart()));
-	boxYTo->setText(QString::number(g->yStop()));
-	boxZFrom->setText(QString::number(g->zStart()));
-	boxZTo->setText(QString::number(g->zStop()));
+  if (app && boxType->currentIndex()) {
+    app->d_param_surface_func.clear();
+  } else {
+    boxFunction->clear();
+    if (app)
+      app->clearSurfaceFunctionsList();
+  }
 }
 
-void SurfaceDialog::accept()
-{
-	if (boxType->currentIndex())
-		acceptParametricSurface();
-	else
-		acceptFunction();
+void SurfaceDialog::setFunction(Graph3D *g) {
+  if (!g)
+    return;
+
+  d_graph = g;
+  UserFunction2D *f = dynamic_cast<UserFunction2D *>(d_graph->userFunction());
+  if (!f)
+    return;
+
+  boxFunction->setItemText(boxFunction->currentIndex(), f->formula());
+  boxFuncColumns->setValue(static_cast<int>(f->columns()));
+  boxFuncRows->setValue(static_cast<int>(f->rows()));
+
+  boxXFrom->setText(QString::number(g->xStart()));
+  boxXTo->setText(QString::number(g->xStop()));
+  boxYFrom->setText(QString::number(g->yStart()));
+  boxYTo->setText(QString::number(g->yStop()));
+  boxZFrom->setText(QString::number(g->zStart()));
+  boxZTo->setText(QString::number(g->zStop()));
 }
 
-void SurfaceDialog::acceptParametricSurface()
-{
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-
-	MyParser parser;
-	double u = 1.0, v = 1.0;
-	parser.DefineVar("u", &u);
-	parser.DefineVar("v", &v);
-
-    int list_size = 15;
-    QString x_formula = boxX->text();
-	try {
-		parser.SetExpr(x_formula.toAscii().constData());
-		parser.Eval();
-	} catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - X Formula Error"), QString::fromStdString(e.GetMsg()));
-		boxX->setFocus();
-		return;
-	}
-
-    app->d_param_surface_func.removeAll(x_formula);
-	app->d_param_surface_func.push_front(x_formula);
-	while ((int)app->d_param_surface_func.size() > list_size)
-		app->d_param_surface_func.pop_back();
-
-    QString y_formula = boxY->text();
-	try {
-		parser.SetExpr(y_formula.toAscii().constData());
-		parser.Eval();
-	} catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - Y Formula Error"), QString::fromStdString(e.GetMsg()));
-		boxY->setFocus();
-		return;
-	}
-
-    app->d_param_surface_func.removeAll(y_formula);
-	app->d_param_surface_func.push_front(y_formula);
-	while ((int)app->d_param_surface_func.size() > list_size)
-		app->d_param_surface_func.pop_back();
-
-    QString z_formula = boxZ->text();
-	try {
-		parser.SetExpr(z_formula.toAscii().constData());
-		parser.Eval();
-	} catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - Z Formula Error"), QString::fromStdString(e.GetMsg()));
-		boxZ->setFocus();
-		return;
-	}
-
-    app->d_param_surface_func.removeAll(z_formula);
-	app->d_param_surface_func.push_front(z_formula);
-	while ((int)app->d_param_surface_func.size() > list_size)
-		app->d_param_surface_func.pop_back();
-
-	QString ufrom = boxUFrom->text().toLower();
-	QString uto = boxUTo->text().toLower();
-	QString vfrom = boxVFrom->text().toLower();
-	QString vto = boxVTo->text().toLower();
-	double ul, ur, vl, vr;
-	try{
-		parser.SetExpr(ufrom.toAscii().constData());
-		ul = parser.Eval();
-	}
-	catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - u start limit error"), QString::fromStdString(e.GetMsg()));
-		boxUFrom->setFocus();
-		return;
-	}
-
-	try{
-		parser.SetExpr(uto.toAscii().constData());
-		ur = parser.Eval();
-	}
-	catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - u end limit error"), QString::fromStdString(e.GetMsg()));
-		boxUTo->setFocus();
-		return;
-	}
-
-	try{
-		parser.SetExpr(vfrom.toAscii().constData());
-		vl = parser.Eval();
-	}
-	catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - v start limit error"), QString::fromStdString(e.GetMsg()));
-		boxVFrom->setFocus();
-		return;
-	}
-
-	try{
-		parser.SetExpr(vto.toAscii().constData());
-		vr = parser.Eval();
-	}
-	catch(mu::ParserError &e){
-		QMessageBox::critical(app, tr("MantidPlot - u end limit error"), QString::fromStdString(e.GetMsg()));
-		boxVTo->setFocus();
-		return;
-	}
+void SurfaceDialog::accept() {
+  if (boxType->currentIndex())
+    acceptParametricSurface();
+  else
+    acceptFunction();
+}
 
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	if (!d_graph)
-		app->plotParametricSurface(x_formula, y_formula, z_formula,
-							   ul, ur, vl, vr, boxColumns->value(), boxRows->value(),
-							   boxUPeriodic->isChecked(), boxVPeriodic->isChecked());
-	else
-		d_graph->addParametricSurface(x_formula, y_formula, z_formula,
-							   ul, ur, vl, vr, boxColumns->value(), boxRows->value(),
-							   boxUPeriodic->isChecked(), boxVPeriodic->isChecked());
-    QApplication::restoreOverrideCursor();
-	close();
+void SurfaceDialog::acceptParametricSurface() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+
+  MyParser parser;
+  double u = 1.0, v = 1.0;
+  parser.DefineVar("u", &u);
+  parser.DefineVar("v", &v);
+
+  int list_size = 15;
+  QString x_formula = boxX->text();
+  try {
+    parser.SetExpr(x_formula.toAscii().constData());
+    parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - X Formula Error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxX->setFocus();
+    return;
+  }
+
+  app->d_param_surface_func.removeAll(x_formula);
+  app->d_param_surface_func.push_front(x_formula);
+  while ((int)app->d_param_surface_func.size() > list_size)
+    app->d_param_surface_func.pop_back();
+
+  QString y_formula = boxY->text();
+  try {
+    parser.SetExpr(y_formula.toAscii().constData());
+    parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Y Formula Error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxY->setFocus();
+    return;
+  }
+
+  app->d_param_surface_func.removeAll(y_formula);
+  app->d_param_surface_func.push_front(y_formula);
+  while ((int)app->d_param_surface_func.size() > list_size)
+    app->d_param_surface_func.pop_back();
+
+  QString z_formula = boxZ->text();
+  try {
+    parser.SetExpr(z_formula.toAscii().constData());
+    parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Z Formula Error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxZ->setFocus();
+    return;
+  }
+
+  app->d_param_surface_func.removeAll(z_formula);
+  app->d_param_surface_func.push_front(z_formula);
+  while ((int)app->d_param_surface_func.size() > list_size)
+    app->d_param_surface_func.pop_back();
+
+  QString ufrom = boxUFrom->text().toLower();
+  QString uto = boxUTo->text().toLower();
+  QString vfrom = boxVFrom->text().toLower();
+  QString vto = boxVTo->text().toLower();
+  double ul, ur, vl, vr;
+  try {
+    parser.SetExpr(ufrom.toAscii().constData());
+    ul = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - u start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxUFrom->setFocus();
+    return;
+  }
+
+  try {
+    parser.SetExpr(uto.toAscii().constData());
+    ur = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - u end limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxUTo->setFocus();
+    return;
+  }
+
+  try {
+    parser.SetExpr(vfrom.toAscii().constData());
+    vl = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - v start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxVFrom->setFocus();
+    return;
+  }
+
+  try {
+    parser.SetExpr(vto.toAscii().constData());
+    vr = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - u end limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxVTo->setFocus();
+    return;
+  }
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  if (!d_graph)
+    app->plotParametricSurface(
+        x_formula, y_formula, z_formula, ul, ur, vl, vr, boxColumns->value(),
+        boxRows->value(), boxUPeriodic->isChecked(), boxVPeriodic->isChecked());
+  else
+    d_graph->addParametricSurface(
+        x_formula, y_formula, z_formula, ul, ur, vl, vr, boxColumns->value(),
+        boxRows->value(), boxUPeriodic->isChecked(), boxVPeriodic->isChecked());
+  QApplication::restoreOverrideCursor();
+  close();
 }
 
-void SurfaceDialog::acceptFunction()
-{
-ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-
-QString Xfrom=boxXFrom->text().toLower();
-QString Xto=boxXTo->text().toLower();
-QString Yfrom=boxYFrom->text().toLower();
-QString Yto=boxYTo->text().toLower();
-QString Zfrom=boxZFrom->text().toLower();
-QString Zto=boxZTo->text().toLower();
-
-double fromX, toX, fromY,toY, fromZ,toZ;
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Xfrom.toAscii().constData());
-	fromX=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - X Start limit error"), QString::fromStdString(e.GetMsg()));
-	boxXFrom->setFocus();
-	return;
-	}
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Xto.toAscii().constData());
-	toX=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - X End limit error"), QString::fromStdString(e.GetMsg()));
-	boxXTo->setFocus();
-	return;
-	}
-
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Yfrom.toAscii().constData());
-	fromY=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - Y Start limit error"), QString::fromStdString(e.GetMsg()));
-	boxYFrom->setFocus();
-	return;
-	}
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Yto.toAscii().constData());
-	toY=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - Y End limit error"), QString::fromStdString(e.GetMsg()));
-	boxYTo->setFocus();
-	return;
-	}
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Zfrom.toAscii().constData());
-	fromZ=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - Z Start limit error"), QString::fromStdString(e.GetMsg()));
-	boxZFrom->setFocus();
-	return;
-	}
-try
-	{
-	MyParser parser;
-	parser.SetExpr(Zto.toAscii().constData());
-	toZ=parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - Z End limit error"), QString::fromStdString(e.GetMsg()));
-	boxZTo->setFocus();
-	return;
-	}
-
-if (fromX >= toX || fromY >= toY || fromZ >= toZ)
-	{
-	QMessageBox::critical(app, tr("MantidPlot - Input error"),
-				tr("Please enter limits that satisfy: from < end!"));
-	boxXTo->setFocus();
-	return;
-	}
-
-QString formula=boxFunction->currentText();
-bool error=false;
-try
-	{
-	MyParser parser;
-	double x=fromX;
-	double y=fromY;
-	parser.DefineVar("x", &x);
-	parser.DefineVar("y", &y);
-	parser.SetExpr(formula.toAscii().constData());
-
-	
-	parser.Eval();
-  // cppcheck-suppress unreadVariable
-	x=toX; 
-  // cppcheck-suppress unreadVariable
-	y=toY;
-	parser.Eval();
-	}
-catch(mu::ParserError &e)
-	{
-	QMessageBox::critical(0, tr("MantidPlot - Input function error"), QString::fromStdString(e.GetMsg()));
-	boxFunction->setFocus();
-	error=true;
-	}
-
-if (!error){
+void SurfaceDialog::acceptFunction() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+
+  QString Xfrom = boxXFrom->text().toLower();
+  QString Xto = boxXTo->text().toLower();
+  QString Yfrom = boxYFrom->text().toLower();
+  QString Yto = boxYTo->text().toLower();
+  QString Zfrom = boxZFrom->text().toLower();
+  QString Zto = boxZTo->text().toLower();
+
+  double fromX, toX, fromY, toY, fromZ, toZ;
+  try {
+    MyParser parser;
+    parser.SetExpr(Xfrom.toAscii().constData());
+    fromX = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - X Start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxXFrom->setFocus();
+    return;
+  }
+  try {
+    MyParser parser;
+    parser.SetExpr(Xto.toAscii().constData());
+    toX = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - X End limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxXTo->setFocus();
+    return;
+  }
+
+  try {
+    MyParser parser;
+    parser.SetExpr(Yfrom.toAscii().constData());
+    fromY = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Y Start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxYFrom->setFocus();
+    return;
+  }
+  try {
+    MyParser parser;
+    parser.SetExpr(Yto.toAscii().constData());
+    toY = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Y End limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxYTo->setFocus();
+    return;
+  }
+  try {
+    MyParser parser;
+    parser.SetExpr(Zfrom.toAscii().constData());
+    fromZ = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Z Start limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxZFrom->setFocus();
+    return;
+  }
+  try {
+    MyParser parser;
+    parser.SetExpr(Zto.toAscii().constData());
+    toZ = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(app, tr("MantidPlot - Z End limit error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxZTo->setFocus();
+    return;
+  }
+
+  if (fromX >= toX || fromY >= toY || fromZ >= toZ) {
+    QMessageBox::critical(app, tr("MantidPlot - Input error"),
+                          tr("Please enter limits that satisfy: from < end!"));
+    boxXTo->setFocus();
+    return;
+  }
+
+  QString formula = boxFunction->currentText();
+  bool error = false;
+  try {
+    MyParser parser;
+    double x = fromX;
+    double y = fromY;
+    parser.DefineVar("x", &x);
+    parser.DefineVar("y", &y);
+    parser.SetExpr(formula.toAscii().constData());
+
+    parser.Eval();
+    // cppcheck-suppress unreadVariable
+    x = toX;
+    // cppcheck-suppress unreadVariable
+    y = toY;
+    parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(0, tr("MantidPlot - Input function error"),
+                          QString::fromStdString(e.GetMsg()));
+    boxFunction->setFocus();
+    error = true;
+  }
+
+  if (!error) {
     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	if (!d_graph){
-		app->plotSurface(boxFunction->currentText(),fromX, toX, fromY, toY, fromZ, toZ,
-					 boxFuncColumns->value(), boxFuncRows->value());
-	} else
-		d_graph->addFunction(boxFunction->currentText(),fromX, toX, fromY, toY, fromZ, toZ,
-					 boxFuncColumns->value(), boxFuncRows->value());
-
-	app->updateSurfaceFuncList(boxFunction->currentText());
+    if (!d_graph) {
+      app->plotSurface(boxFunction->currentText(), fromX, toX, fromY, toY,
+                       fromZ, toZ, boxFuncColumns->value(),
+                       boxFuncRows->value());
+    } else
+      d_graph->addFunction(boxFunction->currentText(), fromX, toX, fromY, toY,
+                           fromZ, toZ, boxFuncColumns->value(),
+                           boxFuncRows->value());
+
+    app->updateSurfaceFuncList(boxFunction->currentText());
     QApplication::restoreOverrideCursor();
-	close();
-	}
+    close();
+  }
 }
 
-void SurfaceDialog::setParametricSurface(Graph3D *g)
-{
-	if (!g)
-		return;
+void SurfaceDialog::setParametricSurface(Graph3D *g) {
+  if (!g)
+    return;
 
-	d_graph = g;
-	UserParametricSurface *s = d_graph->parametricSurface();
+  d_graph = g;
+  UserParametricSurface *s = d_graph->parametricSurface();
 
-	boxType->setCurrentIndex(1);
-	optionStack->setCurrentIndex(1);
+  boxType->setCurrentIndex(1);
+  optionStack->setCurrentIndex(1);
 
-	boxX->setText(s->xFormula());
-	boxY->setText(s->yFormula());
-	boxZ->setText(s->zFormula());
+  boxX->setText(s->xFormula());
+  boxY->setText(s->yFormula());
+  boxZ->setText(s->zFormula());
 
-	boxUFrom->setText(QString::number(s->uStart()));
-	boxUTo->setText(QString::number(s->uEnd()));
-	boxVFrom->setText(QString::number(s->vStart()));
-	boxVTo->setText(QString::number(s->vEnd()));
+  boxUFrom->setText(QString::number(s->uStart()));
+  boxUTo->setText(QString::number(s->uEnd()));
+  boxVFrom->setText(QString::number(s->vStart()));
+  boxVTo->setText(QString::number(s->vEnd()));
 
-	boxColumns->setValue(s->columns());
-	boxRows->setValue(s->rows());
+  boxColumns->setValue(s->columns());
+  boxRows->setValue(s->rows());
 
-	boxUPeriodic->setChecked(s->uPeriodic());
-	boxVPeriodic->setChecked(s->vPeriodic());
+  boxUPeriodic->setChecked(s->uPeriodic());
+  boxVPeriodic->setChecked(s->vPeriodic());
 }
diff --git a/MantidPlot/src/SurfaceDialog.h b/MantidPlot/src/SurfaceDialog.h
index 3ac04cb8dace6ecba471094440b817842fb25c22..ee94641dde746b4b09beedd1a0a86dac56c63fd9 100644
--- a/MantidPlot/src/SurfaceDialog.h
+++ b/MantidPlot/src/SurfaceDialog.h
@@ -40,55 +40,54 @@ class QSpinBox;
 class Graph3D;
 
 //! Define surface plot dialog
-class SurfaceDialog : public QDialog
-{
-    Q_OBJECT
+class SurfaceDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    SurfaceDialog( QWidget* parent = 0, Qt::WFlags fl = 0 );
+  SurfaceDialog(QWidget *parent = 0, Qt::WFlags fl = 0);
 
 public slots:
   void accept() override;
-        void setFunction(Graph3D *);
-	void setParametricSurface(Graph3D *);
+  void setFunction(Graph3D *);
+  void setParametricSurface(Graph3D *);
 
 private slots:
-	void clearList();
+  void clearList();
 
 private:
-	Graph3D *d_graph;
+  Graph3D *d_graph;
 
-	void acceptParametricSurface();
-	void acceptFunction();
-	void initFunctionPage();
-	void initParametricSurfacePage();
+  void acceptParametricSurface();
+  void acceptFunction();
+  void initFunctionPage();
+  void initParametricSurfacePage();
 
-	QWidget* functionPage;
-	QWidget* parametricPage;
-	QStackedWidget* optionStack;
-    QPushButton* buttonOk;
-	QPushButton* buttonCancel;
-	QPushButton* buttonClear;
-	QComboBox* boxType;
-	QComboBox* boxFunction;
-	QLineEdit* boxXFrom;
-	QLineEdit* boxXTo;
-	QLineEdit* boxYFrom;
-	QLineEdit* boxYTo;
-	QLineEdit* boxZFrom;
-	QLineEdit* boxZTo;
+  QWidget *functionPage;
+  QWidget *parametricPage;
+  QStackedWidget *optionStack;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonClear;
+  QComboBox *boxType;
+  QComboBox *boxFunction;
+  QLineEdit *boxXFrom;
+  QLineEdit *boxXTo;
+  QLineEdit *boxYFrom;
+  QLineEdit *boxYTo;
+  QLineEdit *boxZFrom;
+  QLineEdit *boxZTo;
 
-	QLineEdit* boxX;
-	QLineEdit* boxY;
-	QLineEdit* boxZ;
+  QLineEdit *boxX;
+  QLineEdit *boxY;
+  QLineEdit *boxZ;
 
-	QLineEdit* boxUFrom;
-	QLineEdit* boxUTo;
-	QLineEdit* boxVFrom;
-	QLineEdit* boxVTo;
+  QLineEdit *boxUFrom;
+  QLineEdit *boxUTo;
+  QLineEdit *boxVFrom;
+  QLineEdit *boxVTo;
 
-	QCheckBox *boxUPeriodic, *boxVPeriodic;
-	QSpinBox *boxColumns, *boxRows, *boxFuncColumns, *boxFuncRows;
+  QCheckBox *boxUPeriodic, *boxVPeriodic;
+  QSpinBox *boxColumns, *boxRows, *boxFuncColumns, *boxFuncRows;
 };
 
 #endif
diff --git a/MantidPlot/src/TSVSerialiser.cpp b/MantidPlot/src/TSVSerialiser.cpp
index 28ffab41d4afb5914738d24595f21ffe70fc7948..0c644a57b77c0507383538215b63112175473e9b 100644
--- a/MantidPlot/src/TSVSerialiser.cpp
+++ b/MantidPlot/src/TSVSerialiser.cpp
@@ -6,26 +6,22 @@
 #include <boost/regex.hpp>
 #include <sstream>
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("TSVSerialiser");
+namespace {
+Mantid::Kernel::Logger g_log("TSVSerialiser");
 }
 
-TSVSerialiser::TSVSerialiser() : m_curIndex(0), m_midLine(false)
-{
-}
+TSVSerialiser::TSVSerialiser() : m_curIndex(0), m_midLine(false) {}
 
-TSVSerialiser::TSVSerialiser(const std::string& lines) : m_curIndex(0), m_midLine(false)
-{
+TSVSerialiser::TSVSerialiser(const std::string &lines)
+    : m_curIndex(0), m_midLine(false) {
   parseLines(lines);
 }
 
-void TSVSerialiser::parseLines(const std::string& lines)
-{
+void TSVSerialiser::parseLines(const std::string &lines) {
   std::vector<std::string> lineVec;
   boost::split(lineVec, lines, boost::is_any_of("\n"));
 
-  //Clear out any old data.
+  // Clear out any old data.
   m_lines.clear();
   m_sections.clear();
 
@@ -33,104 +29,100 @@ void TSVSerialiser::parseLines(const std::string& lines)
   boost::regex closedSectionRegex("\\s*<([a-zA-Z0-9]+)>(.*)</\\1>");
   boost::regex openSectionRegex("\\s*<([a-zA-Z0-9]+)( [0-9]+)?>(.*)");
 
-  for(auto lineIt = lineVec.begin(); lineIt != lineVec.end(); ++lineIt)
-  {
+  for (auto lineIt = lineVec.begin(); lineIt != lineVec.end(); ++lineIt) {
     const std::string line = *lineIt;
 
-    if(line.length() == 0)
+    if (line.length() == 0)
       continue;
 
-    //Stores matched sections of a regex
+    // Stores matched sections of a regex
     boost::smatch matches;
 
-    //Check if this is a value line
-    if(boost::regex_match(line, matches, valueLineRegex))
-    {
+    // Check if this is a value line
+    if (boost::regex_match(line, matches, valueLineRegex)) {
       std::string name = matches[1].str();
       m_lines[name].push_back(line);
     }
-    //Look for lines which open and close a section in one line: <section>data</section>
-    else if(boost::regex_match(line, matches, closedSectionRegex))
-    {
+    // Look for lines which open and close a section in one line:
+    // <section>data</section>
+    else if (boost::regex_match(line, matches, closedSectionRegex)) {
       std::string name = matches[1].str();
       std::string contents = matches[2].str();
 
       m_sections[name].push_back(contents);
     }
-    //Check if this is the start of a multiline section, if so, consume the whole section.
-    else if(boost::regex_match(line, matches, openSectionRegex))
-    {
+    // Check if this is the start of a multiline section, if so, consume the
+    // whole section.
+    else if (boost::regex_match(line, matches, openSectionRegex)) {
       std::stringstream sectionSS;
 
       std::string name = matches[1].str();
       std::string firstLine = matches[2].str();
       std::string num;
-      if(matches.size() == 4)
-      {
+      if (matches.size() == 4) {
         num = matches[2].str();
         firstLine = matches[3].str();
       }
 
-      //firstLine exists because of a legacy edgecase: the <folder> section keeps values on the same line as
-      //the opening tag, so we have to be able to read that.
-      if(firstLine.length() > 0)
+      // firstLine exists because of a legacy edgecase: the <folder> section
+      // keeps values on the same line as
+      // the opening tag, so we have to be able to read that.
+      if (firstLine.length() > 0)
         sectionSS << firstLine << "\n";
 
-      boost::regex  openRegex("\\s*<"  + name + num + ">.*");
+      boost::regex openRegex("\\s*<" + name + num + ">.*");
       boost::regex closeRegex("\\s*</" + name + ">");
 
-      //Lets iterate over the contents of the section
+      // Lets iterate over the contents of the section
       auto secIt = lineIt + 1;
 
-      //Search for opening and closing tags, counting depth and building the section string.
-      for(int depth = 1; depth > 0 && secIt != lineVec.end(); ++secIt)
-      {
+      // Search for opening and closing tags, counting depth and building the
+      // section string.
+      for (int depth = 1; depth > 0 && secIt != lineVec.end(); ++secIt) {
         std::string secLine = *secIt;
-        //Are we going down?
-        if(boost::regex_match(secLine, openRegex))
+        // Are we going down?
+        if (boost::regex_match(secLine, openRegex))
           depth++;
-        else if(boost::regex_match(secLine, closeRegex))
+        else if (boost::regex_match(secLine, closeRegex))
           depth--;
 
-        if(depth > 0)
+        if (depth > 0)
           sectionSS << secLine << "\n";
       }
 
-      //We've now advanced beyond the end of the section so go back one
+      // We've now advanced beyond the end of the section so go back one
       secIt--;
 
       std::string sectionStr = sectionSS.str();
 
-      //We drop the last character because it's a spare newline
-      if(sectionStr.size() > 0)
+      // We drop the last character because it's a spare newline
+      if (sectionStr.size() > 0)
         sectionStr.resize(sectionStr.size() - 1);
 
       m_sections[name + num].push_back(sectionStr);
 
-      //Skip parsing to the end of the section
+      // Skip parsing to the end of the section
       lineIt = secIt;
-    }
-    else
-    {
-      //If we've made it here then we don't know what kind of line this is.
-      g_log.warning() << "Unable to identify line in TSVSerialiser::parseLines(): '" << line << "'" << std::endl;
+    } else {
+      // If we've made it here then we don't know what kind of line this is.
+      g_log.warning()
+          << "Unable to identify line in TSVSerialiser::parseLines(): '" << line
+          << "'" << std::endl;
     }
   }
 }
 
-bool TSVSerialiser::hasLine(const std::string& name) const
-{
-  return ( m_lines.find(name) != m_lines.end() );
+bool TSVSerialiser::hasLine(const std::string &name) const {
+  return (m_lines.find(name) != m_lines.end());
 }
 
-bool TSVSerialiser::hasSection(const std::string& name) const
-{
-  return ( m_sections.find(name) != m_sections.end() );
+bool TSVSerialiser::hasSection(const std::string &name) const {
+  return (m_sections.find(name) != m_sections.end());
 }
 
-std::vector<std::string> TSVSerialiser::values(const std::string& name, size_t i) const
-{
-  //Select correct line with lineAsString, parse it, then return values
+std::vector<std::string> TSVSerialiser::values(const std::string &name,
+                                               size_t i) const {
+  // Select correct line with lineAsString, parse it, then return values
   std::vector<std::string> ret;
 
   std::string line = lineAsString(name, i);
@@ -139,17 +131,17 @@ std::vector<std::string> TSVSerialiser::values(const std::string& name, size_t i
   return ret;
 }
 
-std::vector<std::string> TSVSerialiser::sections(const std::string& name) const
-{
-  if(!hasSection(name))
+std::vector<std::string>
+TSVSerialiser::sections(const std::string &name) const {
+  if (!hasSection(name))
     return std::vector<std::string>();
 
   return m_sections.at(name);
 }
 
-std::string TSVSerialiser::lineAsString(const std::string& name, const size_t i) const
-{
-  if(!hasLine(name))
+std::string TSVSerialiser::lineAsString(const std::string &name,
+                                        const size_t i) const {
+  if (!hasLine(name))
     return "";
 
   auto lines = m_lines.at(name);
@@ -157,37 +149,34 @@ std::string TSVSerialiser::lineAsString(const std::string& name, const size_t i)
   return lines[i];
 }
 
-bool TSVSerialiser::selectLine(const std::string& name, const size_t i)
-{
-  if(!hasLine(name))
+bool TSVSerialiser::selectLine(const std::string &name, const size_t i) {
+  if (!hasLine(name))
     return false;
 
-  if(i >= m_lines[name].size())
+  if (i >= m_lines[name].size())
     return false;
 
   m_curValues = values(name, i);
-  m_curIndex = 1; //1 because we want to start on the values, not the name
+  m_curIndex = 1; // 1 because we want to start on the values, not the name
   return true;
 }
 
-bool TSVSerialiser::selectSection(const std::string& name, const size_t i)
-{
-  if(!hasSection(name))
+bool TSVSerialiser::selectSection(const std::string &name, const size_t i) {
+  if (!hasSection(name))
     return false;
 
-  if(i >= m_sections[name].size())
+  if (i >= m_sections[name].size())
     return false;
 
   m_curValues.clear();
   m_curValues.push_back(name);
   m_curValues.push_back(m_sections[name][i]);
-  m_curIndex = 1; //1 because we want to start on the values, not the name
+  m_curIndex = 1; // 1 because we want to start on the values, not the name
   return true;
 }
 
-int TSVSerialiser::asInt(const size_t i) const
-{
-  if(i >= m_curValues.size())
+int TSVSerialiser::asInt(const size_t i) const {
+  if (i >= m_curValues.size())
     return 0;
 
   std::string valStr = m_curValues.at(i);
@@ -199,9 +188,8 @@ int TSVSerialiser::asInt(const size_t i) const
   return ret;
 }
 
-double TSVSerialiser::asDouble(const size_t i) const
-{
-  if(i >= m_curValues.size())
+double TSVSerialiser::asDouble(const size_t i) const {
+  if (i >= m_curValues.size())
     return 0.00;
 
   std::string valStr = m_curValues.at(i);
@@ -213,9 +201,8 @@ double TSVSerialiser::asDouble(const size_t i) const
   return ret;
 }
 
-float TSVSerialiser::asFloat(const size_t i) const
-{
-  if(i >= m_curValues.size())
+float TSVSerialiser::asFloat(const size_t i) const {
+  if (i >= m_curValues.size())
     return 0.00;
 
   std::string valStr = m_curValues.at(i);
@@ -227,49 +214,41 @@ float TSVSerialiser::asFloat(const size_t i) const
   return ret;
 }
 
-std::string TSVSerialiser::asString(const size_t i) const
-{
-  if(i >= m_curValues.size())
+std::string TSVSerialiser::asString(const size_t i) const {
+  if (i >= m_curValues.size())
     return "";
 
   return m_curValues.at(i);
 }
 
-TSVSerialiser& TSVSerialiser::operator>>(int& val)
-{
+TSVSerialiser &TSVSerialiser::operator>>(int &val) {
   val = asInt(m_curIndex++);
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator>>(double& val)
-{
+TSVSerialiser &TSVSerialiser::operator>>(double &val) {
   val = asDouble(m_curIndex++);
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator>>(float& val)
-{
+TSVSerialiser &TSVSerialiser::operator>>(float &val) {
   val = asFloat(m_curIndex++);
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator>>(std::string& val)
-{
+TSVSerialiser &TSVSerialiser::operator>>(std::string &val) {
   val = asString(m_curIndex++);
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator>>(QString& val)
-{
+TSVSerialiser &TSVSerialiser::operator>>(QString &val) {
   val = QString::fromUtf8(asString(m_curIndex++).c_str());
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::writeLine(const std::string& name)
-{
-  //If we're not on a new line, make one
-  if(m_midLine)
-  {
+TSVSerialiser &TSVSerialiser::writeLine(const std::string &name) {
+  // If we're not on a new line, make one
+  if (m_midLine) {
     m_output << "\n";
   }
 
@@ -279,86 +258,79 @@ TSVSerialiser& TSVSerialiser::writeLine(const std::string& name)
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator<<(const std::string& val)
-{
+TSVSerialiser &TSVSerialiser::operator<<(const std::string &val) {
   m_output << "\t" << val;
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator<<(const char* val)
-{
+TSVSerialiser &TSVSerialiser::operator<<(const char *val) {
   m_output << "\t" << std::string(val);
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator<<(const QString& val)
-{
+TSVSerialiser &TSVSerialiser::operator<<(const QString &val) {
   const std::string str = val.toUtf8().constData();
   m_output << "\t" << str;
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator<<(const double& val)
-{
+TSVSerialiser &TSVSerialiser::operator<<(const double &val) {
   m_output << "\t" << val;
   return *this;
 }
 
-TSVSerialiser& TSVSerialiser::operator<<(const int& val)
-{
+TSVSerialiser &TSVSerialiser::operator<<(const int &val) {
   m_output << "\t" << val;
   return *this;
 }
 
-void TSVSerialiser::writeRaw(const std::string& raw)
-{
-  if(m_midLine)
-  {
+void TSVSerialiser::writeRaw(const std::string &raw) {
+  if (m_midLine) {
     m_output << "\n";
     m_midLine = false;
   }
 
   m_output << raw;
 
-  //If raw didn't end in a newline, make a note of it.
+  // If raw didn't end in a newline, make a note of it.
   m_midLine = (raw.length() > 0 && raw[raw.length() - 1] != '\n');
 }
 
-void TSVSerialiser::writeSection(const std::string& name, const std::string& body)
-{
-  //If we're not on a new line, make one
-  if(m_midLine)
-  {
+void TSVSerialiser::writeSection(const std::string &name,
+                                 const std::string &body) {
+  // If we're not on a new line, make one
+  if (m_midLine) {
     m_output << "\n";
     m_midLine = false;
   }
 
-  m_output << "<" << name << ">" << "\n";
+  m_output << "<" << name << ">"
+           << "\n";
   m_output << body;
 
-  //If body isn't blank and didn't end with a new line, add one.
-  if(body.length() > 0 && body[body.length() - 1] != '\n')
+  // If body isn't blank and didn't end with a new line, add one.
+  if (body.length() > 0 && body[body.length() - 1] != '\n')
     m_output << "\n";
 
-  m_output << "</" << name << ">" << "\n";
+  m_output << "</" << name << ">"
+           << "\n";
 }
 
-void TSVSerialiser::writeInlineSection(const std::string& name, const std::string& body)
-{
-  //If we're not on a new line, make one
-  if(m_midLine)
-  {
+void TSVSerialiser::writeInlineSection(const std::string &name,
+                                       const std::string &body) {
+  // If we're not on a new line, make one
+  if (m_midLine) {
     m_output << "\n";
     m_midLine = false;
   }
 
   m_output << "<" << name << ">";
   m_output << body;
-  m_output << "</" << name << ">" << "\n";
+  m_output << "</" << name << ">"
+           << "\n";
 }
 
-std::string TSVSerialiser::outputLines() const
-{
+std::string TSVSerialiser::outputLines() const {
   std::string output = m_output.str();
   if (m_midLine)
     output += "\n";
@@ -366,8 +338,7 @@ std::string TSVSerialiser::outputLines() const
   return output;
 }
 
-void TSVSerialiser::clear()
-{
+void TSVSerialiser::clear() {
   m_sections.clear();
   m_lines.clear();
   m_curValues.clear();
diff --git a/MantidPlot/src/TSVSerialiser.h b/MantidPlot/src/TSVSerialiser.h
index d1122150130a210f410ccc5b7c5c79b1fc9c0f3d..309a22f6e1728a4feb5240d5bbca99913fcbebcf 100644
--- a/MantidPlot/src/TSVSerialiser.h
+++ b/MantidPlot/src/TSVSerialiser.h
@@ -13,7 +13,8 @@
   @author Harry Jeffery, ISIS, RAL
   @date 23/07/2014
 
-  Copyright &copy; 2007-2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007-2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -32,55 +33,54 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-class TSVSerialiser
-{
+class TSVSerialiser {
 public:
-
   TSVSerialiser();
 
   explicit TSVSerialiser(const std::string &lines);
 
-  void parseLines(const std::string& lines);
+  void parseLines(const std::string &lines);
   std::string outputLines() const;
   void clear();
 
-  bool hasLine(const std::string& name) const;
-  bool hasSection(const std::string& name) const;
+  bool hasLine(const std::string &name) const;
+  bool hasSection(const std::string &name) const;
 
-  std::vector<std::string> values(const std::string& name, const size_t i = 0) const;
-  std::vector<std::string> sections(const std::string& name) const;
+  std::vector<std::string> values(const std::string &name,
+                                  const size_t i = 0) const;
+  std::vector<std::string> sections(const std::string &name) const;
 
-  std::string lineAsString(const std::string& name, const size_t i = 0) const;
+  std::string lineAsString(const std::string &name, const size_t i = 0) const;
 
-  bool selectLine(const std::string& name, const size_t i = 0);
-  bool selectSection(const std::string& name, const size_t i = 0);
+  bool selectLine(const std::string &name, const size_t i = 0);
+  bool selectSection(const std::string &name, const size_t i = 0);
 
-  int         asInt(const size_t i) const;
-  double      asDouble(const size_t i) const;
-  float       asFloat(const size_t i) const;
+  int asInt(const size_t i) const;
+  double asDouble(const size_t i) const;
+  float asFloat(const size_t i) const;
   std::string asString(const size_t i) const;
 
-  TSVSerialiser& operator>>(int& val);
-  TSVSerialiser& operator>>(double& val);
-  TSVSerialiser& operator>>(float& val);
-  TSVSerialiser& operator>>(std::string& val);
-  TSVSerialiser& operator>>(QString& val);
+  TSVSerialiser &operator>>(int &val);
+  TSVSerialiser &operator>>(double &val);
+  TSVSerialiser &operator>>(float &val);
+  TSVSerialiser &operator>>(std::string &val);
+  TSVSerialiser &operator>>(QString &val);
 
-  TSVSerialiser& writeLine(const std::string& name);
+  TSVSerialiser &writeLine(const std::string &name);
 
-  TSVSerialiser& operator<<(const std::string& val);
-  TSVSerialiser& operator<<(const char* val);
-  TSVSerialiser& operator<<(const QString& val);
-  TSVSerialiser& operator<<(const double& val);
-  TSVSerialiser& operator<<(const int& val);
+  TSVSerialiser &operator<<(const std::string &val);
+  TSVSerialiser &operator<<(const char *val);
+  TSVSerialiser &operator<<(const QString &val);
+  TSVSerialiser &operator<<(const double &val);
+  TSVSerialiser &operator<<(const int &val);
 
-  void writeRaw(const std::string& raw);
-  void writeSection(const std::string& name, const std::string& body);
-  void writeInlineSection(const std::string& name, const std::string& body);
+  void writeRaw(const std::string &raw);
+  void writeSection(const std::string &name, const std::string &body);
+  void writeInlineSection(const std::string &name, const std::string &body);
 
 private:
-  std::map<std::string,std::vector<std::string> > m_sections;
-  std::map<std::string,std::vector<std::string> > m_lines;
+  std::map<std::string, std::vector<std::string>> m_sections;
+  std::map<std::string, std::vector<std::string>> m_lines;
 
   std::vector<std::string> m_curValues;
   int m_curIndex;
diff --git a/MantidPlot/src/Table.cpp b/MantidPlot/src/Table.cpp
index 02370994a98e6ed31f0ea9d15e9f414ef76afc44..ff3aba3d524d905e1d40904820d60ca87045b067 100644
--- a/MantidPlot/src/Table.cpp
+++ b/MantidPlot/src/Table.cpp
@@ -472,9 +472,9 @@ void Table::setCommands(const QString &com) {
 
 bool Table::calculate() {
   bool success = true;
-  for (int col=leftSelectedColumn(); col<=rightSelectedColumn(); col++)
-   if (!calculate(col, topSelectedRow(), bottomSelectedRow()))
-     success = false;
+  for (int col = leftSelectedColumn(); col <= rightSelectedColumn(); col++)
+    if (!calculate(col, topSelectedRow(), bottomSelectedRow()))
+      success = false;
   return success;
 }
 
@@ -753,9 +753,9 @@ void Table::setColName(int col, const QString &text, bool enumerateRight) {
       newLabel += QString::number(n);
 
     if (col_label.contains(newLabel) > 0) {
-      auto msg = "There is already a column called : <b>" +
-        newLabel + "</b> in table <b>" + caption +
-        "</b>!<p>Please choose another name!";
+      auto msg = "There is already a column called : <b>" + newLabel +
+                 "</b> in table <b>" + caption +
+                 "</b>!<p>Please choose another name!";
       QMessageBox::critical(0, tr("MantidPlot - Error"),
                             tr(msg.toAscii().constData()));
       return;
@@ -1603,8 +1603,7 @@ void Table::setText(int row, int col, const QString &text) {
   d_table->setText(row, col, text);
 }
 
-void Table::saveToMemory()
-{
+void Table::saveToMemory() {
   // clear d_saved_cells, if any
   freeMemory();
   d_saved_cells = new double *[d_table->columnCount()];
@@ -2233,7 +2232,7 @@ void Table::importASCII(const QString &fname, const QString &sep,
       }
 
       if (importComments) { // import comments
-        s = t.readLine(); // read 2nd line
+        s = t.readLine();   // read 2nd line
         if (simplifySpaces)
           s = s.simplified();
         else if (stripSpaces)
@@ -2320,8 +2319,8 @@ bool Table::exportASCII(const QString &fname, const QString &separator,
   if (!f.open(QIODevice::WriteOnly)) {
     QApplication::restoreOverrideCursor();
     auto msg = "Could not write to file: <br><h4>" + fname +
-      "</h4><p>Please verify that you have the right to "
-      "write to this location!";
+               "</h4><p>Please verify that you have the right to "
+               "write to this location!";
     QMessageBox::critical(0, tr("MantidPlot - ASCII Export Error"),
                           tr(msg.toAscii().constData()).arg(fname));
     return false;
@@ -2499,7 +2498,7 @@ void Table::restore(QString &spec) {
       d_table->setText(i, j, "");
   }
 
-  t.readLine(); // table geometry useless info when restoring
+  t.readLine();     // table geometry useless info when restoring
   s = t.readLine(); // header line
 
   list = s.split("\t");
diff --git a/MantidPlot/src/Table.h b/MantidPlot/src/Table.h
index b986b1595894fc1b806d12f7c224942d97b7d8f8..eb3cb41f84abda87dcd3aab4d3b967841b439e3a 100644
--- a/MantidPlot/src/Table.h
+++ b/MantidPlot/src/Table.h
@@ -292,7 +292,7 @@ public slots:
   virtual void deleteRows(int startRow, int endRow);
   void insertRow();
   void insertRow(int row); // Mantid
-  void addRows(int num); // Mantid
+  void addRows(int num);   // Mantid
   virtual void insertRows(int atRow, int num);
   //@}
 
diff --git a/MantidPlot/src/TableDialog.cpp b/MantidPlot/src/TableDialog.cpp
index db09294b00a03e935402f30b1b201473e22f58e6..32c15c69e27bbea030071c9e3c2459f7e443110b 100644
--- a/MantidPlot/src/TableDialog.cpp
+++ b/MantidPlot/src/TableDialog.cpp
@@ -2,7 +2,8 @@
     File                 : TableDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Column options dialog
 
@@ -43,544 +44,528 @@
 #include <QRegExp>
 #include <QDate>
 
-TableDialog::TableDialog(Table *t, Qt::WFlags fl )
-    : QDialog( t, fl),
-    d_table(t)
-{
-    setObjectName( "TableDialog" );
-    setWindowTitle( tr( "MantidPlot - Column options" ) );
-    setSizeGripEnabled(true);
-
-	QHBoxLayout *hboxa = new QHBoxLayout();
-	hboxa->addWidget(new QLabel(tr( "Column Name:" )));
-    colName = new QLineEdit();
-    hboxa->addWidget(colName);
-
-	enumerateAllBox = new QCheckBox(tr("Enumerate all to the right" ));
-
-	buttonPrev = new QPushButton("&<<");
-	buttonPrev->setAutoDefault(false);
-	buttonPrev->setMaximumWidth(40);
-
-	buttonNext = new QPushButton("&>>");
-	buttonNext->setAutoDefault(false);
-	buttonNext->setMaximumWidth(40);
-
-	QHBoxLayout *hboxb = new QHBoxLayout();
-    hboxb->addWidget(buttonPrev);
-    hboxb->addWidget(buttonNext);
-    hboxb->addStretch();
-
-    QVBoxLayout *vbox1 = new QVBoxLayout();
-    vbox1->addLayout(hboxa);
-    vbox1->addWidget(enumerateAllBox);
-    vbox1->addLayout(hboxb);
-
-	buttonOk = new QPushButton(tr( "&OK" ));
-    buttonOk->setDefault(true);
-
-	buttonApply = new QPushButton(tr("&Apply"));
-	buttonApply->setAutoDefault(false);
-
-	buttonCancel = new QPushButton(tr( "&Cancel" ));
-	buttonCancel->setAutoDefault(false);
-
-	QVBoxLayout  *vbox2 = new QVBoxLayout();
-	vbox2->setSpacing(5);
-	vbox2->setMargin(5);
-	vbox2->addWidget(buttonOk);
-	vbox2->addWidget(buttonApply);
-	vbox2->addWidget(buttonCancel);
-
-    QHBoxLayout  *hbox1 = new QHBoxLayout();
-	hbox1->setSpacing(5);
-	hbox1->addLayout(vbox1);
-	hbox1->addLayout(vbox2);
-
-	QGridLayout *gl1 = new QGridLayout();
-    gl1->addWidget(new QLabel( tr("Plot Designation:")), 0, 0);
-
-   	columnsBox = new QComboBox();
-	columnsBox->addItem(tr("None"));
-	columnsBox->addItem(tr("X (abscissae)"));
-	columnsBox->addItem(tr("Y (ordinates)"));
-	columnsBox->addItem(tr("Z (height)"));
-	columnsBox->addItem(tr("X Error"));
-	columnsBox->addItem(tr("Y Error"));
-	columnsBox->addItem(tr("Label"));
-    gl1->addWidget(columnsBox, 0, 1);
-
-    gl1->addWidget(new QLabel(tr("Display")), 1, 0);
-
-   	displayBox = new QComboBox();
-	displayBox->addItem(tr("Numeric"));
-	displayBox->addItem(tr("Text"));
-	displayBox->addItem(tr("Date"));
-	displayBox->addItem(tr("Time"));
-	displayBox->addItem(tr("Month"));
-	displayBox->addItem(tr("Day of Week"));
-    gl1->addWidget(displayBox, 1, 1);
-
-    labelFormat = new QLabel(tr( "Format:" ));
- 	gl1->addWidget(labelFormat, 2, 0);
-
-    formatBox = new QComboBox();
-    gl1->addWidget(formatBox, 2, 1);
-
-	labelNumeric = new QLabel(tr( "Precision:" ));
-	gl1->addWidget(labelNumeric, 3, 0);
-
-    precisionBox = new QSpinBox();
-    precisionBox->setRange(0, 13);
-    gl1->addWidget(precisionBox, 3, 1);
-
-    boxReadOnly = new QCheckBox(tr("&Read-only" ));
-    gl1->addWidget(boxReadOnly, 4, 0);
-
-	boxHideColumn = new QCheckBox(tr("&Hidden" ));
-    gl1->addWidget(boxHideColumn, 4, 1);
-	
-	applyToRightCols = new QCheckBox(tr( "Apply to all columns to the right" ));
-
-    QVBoxLayout *vbox3 = new QVBoxLayout();
-    vbox3->addLayout(gl1);
-    vbox3->addWidget(applyToRightCols);
-
-    QGroupBox *gb = new QGroupBox(tr("Options"));
-    gb->setLayout(vbox3);
-
-    QHBoxLayout  *hbox2 = new QHBoxLayout();
-    hbox2->addWidget(new QLabel(tr( "Column Width:" )));
-
-	colWidth = new QSpinBox();
-    colWidth->setRange(0, 1000);
-	colWidth->setSingleStep(10);
-
-	hbox2->addWidget(colWidth);
-
-    applyToAllBox = new QCheckBox(tr( "Apply to all" ));
-	hbox2->addWidget(applyToAllBox);
-
-	comments = new QTextEdit();
-	boxShowTableComments = new QCheckBox(tr("&Display Comments in Header"));
-	boxShowTableComments->setChecked(d_table->commentsEnabled());
-
-	QVBoxLayout* vbox4 = new QVBoxLayout();
-    vbox4->addLayout(hbox1);
-	vbox4->addWidget(gb);
-	vbox4->addLayout(hbox2);
-	vbox4->addWidget(new QLabel(tr( "Comment:" )));
-	vbox4->addWidget(comments);
-	vbox4->addWidget(boxShowTableComments);
-
-    setLayout(vbox4);
-    setFocusProxy (colName);
-
-    updateColumn(d_table->selectedColumn());
-
-   // signals and slots connections
-	connect(colWidth, SIGNAL(valueChanged(int)), this, SLOT(setColumnWidth(int)));
-	connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
-    connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
-    connect(buttonCancel, SIGNAL( clicked() ), this, SLOT( close() ) );
-	connect(columnsBox, SIGNAL(activated(int)), this, SLOT(setPlotDesignation(int)) );
-	connect(displayBox, SIGNAL(activated(int)), this, SLOT(updateDisplay(int)));
-	connect(buttonPrev, SIGNAL(clicked()), this, SLOT(prevColumn()));
-	connect(buttonNext, SIGNAL(clicked()), this, SLOT(nextColumn()));
-	connect(formatBox, SIGNAL(activated(int)), this, SLOT(enablePrecision(int)) );
-	connect(precisionBox, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
-	connect(boxShowTableComments, SIGNAL(toggled(bool)), d_table, SLOT(showComments(bool)));
-}
+TableDialog::TableDialog(Table *t, Qt::WFlags fl) : QDialog(t, fl), d_table(t) {
+  setObjectName("TableDialog");
+  setWindowTitle(tr("MantidPlot - Column options"));
+  setSizeGripEnabled(true);
 
-void TableDialog::enablePrecision(int f)
-{
-if(displayBox->currentIndex())
-	return;//the col type != "Numeric"
+  QHBoxLayout *hboxa = new QHBoxLayout();
+  hboxa->addWidget(new QLabel(tr("Column Name:")));
+  colName = new QLineEdit();
+  hboxa->addWidget(colName);
 
-precisionBox->setEnabled(f > 0);
-}
+  enumerateAllBox = new QCheckBox(tr("Enumerate all to the right"));
 
-void TableDialog::accept()
-{
-apply();
-close();
-}
+  buttonPrev = new QPushButton("&<<");
+  buttonPrev->setAutoDefault(false);
+  buttonPrev->setMaximumWidth(40);
+
+  buttonNext = new QPushButton("&>>");
+  buttonNext->setAutoDefault(false);
+  buttonNext->setMaximumWidth(40);
+
+  QHBoxLayout *hboxb = new QHBoxLayout();
+  hboxb->addWidget(buttonPrev);
+  hboxb->addWidget(buttonNext);
+  hboxb->addStretch();
+
+  QVBoxLayout *vbox1 = new QVBoxLayout();
+  vbox1->addLayout(hboxa);
+  vbox1->addWidget(enumerateAllBox);
+  vbox1->addLayout(hboxb);
+
+  buttonOk = new QPushButton(tr("&OK"));
+  buttonOk->setDefault(true);
 
-void TableDialog::prevColumn()
-{
-int sc = d_table->selectedColumn();
-apply();
-updateColumn(--sc);
+  buttonApply = new QPushButton(tr("&Apply"));
+  buttonApply->setAutoDefault(false);
+
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  buttonCancel->setAutoDefault(false);
+
+  QVBoxLayout *vbox2 = new QVBoxLayout();
+  vbox2->setSpacing(5);
+  vbox2->setMargin(5);
+  vbox2->addWidget(buttonOk);
+  vbox2->addWidget(buttonApply);
+  vbox2->addWidget(buttonCancel);
+
+  QHBoxLayout *hbox1 = new QHBoxLayout();
+  hbox1->setSpacing(5);
+  hbox1->addLayout(vbox1);
+  hbox1->addLayout(vbox2);
+
+  QGridLayout *gl1 = new QGridLayout();
+  gl1->addWidget(new QLabel(tr("Plot Designation:")), 0, 0);
+
+  columnsBox = new QComboBox();
+  columnsBox->addItem(tr("None"));
+  columnsBox->addItem(tr("X (abscissae)"));
+  columnsBox->addItem(tr("Y (ordinates)"));
+  columnsBox->addItem(tr("Z (height)"));
+  columnsBox->addItem(tr("X Error"));
+  columnsBox->addItem(tr("Y Error"));
+  columnsBox->addItem(tr("Label"));
+  gl1->addWidget(columnsBox, 0, 1);
+
+  gl1->addWidget(new QLabel(tr("Display")), 1, 0);
+
+  displayBox = new QComboBox();
+  displayBox->addItem(tr("Numeric"));
+  displayBox->addItem(tr("Text"));
+  displayBox->addItem(tr("Date"));
+  displayBox->addItem(tr("Time"));
+  displayBox->addItem(tr("Month"));
+  displayBox->addItem(tr("Day of Week"));
+  gl1->addWidget(displayBox, 1, 1);
+
+  labelFormat = new QLabel(tr("Format:"));
+  gl1->addWidget(labelFormat, 2, 0);
+
+  formatBox = new QComboBox();
+  gl1->addWidget(formatBox, 2, 1);
+
+  labelNumeric = new QLabel(tr("Precision:"));
+  gl1->addWidget(labelNumeric, 3, 0);
+
+  precisionBox = new QSpinBox();
+  precisionBox->setRange(0, 13);
+  gl1->addWidget(precisionBox, 3, 1);
+
+  boxReadOnly = new QCheckBox(tr("&Read-only"));
+  gl1->addWidget(boxReadOnly, 4, 0);
+
+  boxHideColumn = new QCheckBox(tr("&Hidden"));
+  gl1->addWidget(boxHideColumn, 4, 1);
+
+  applyToRightCols = new QCheckBox(tr("Apply to all columns to the right"));
+
+  QVBoxLayout *vbox3 = new QVBoxLayout();
+  vbox3->addLayout(gl1);
+  vbox3->addWidget(applyToRightCols);
+
+  QGroupBox *gb = new QGroupBox(tr("Options"));
+  gb->setLayout(vbox3);
+
+  QHBoxLayout *hbox2 = new QHBoxLayout();
+  hbox2->addWidget(new QLabel(tr("Column Width:")));
+
+  colWidth = new QSpinBox();
+  colWidth->setRange(0, 1000);
+  colWidth->setSingleStep(10);
+
+  hbox2->addWidget(colWidth);
+
+  applyToAllBox = new QCheckBox(tr("Apply to all"));
+  hbox2->addWidget(applyToAllBox);
+
+  comments = new QTextEdit();
+  boxShowTableComments = new QCheckBox(tr("&Display Comments in Header"));
+  boxShowTableComments->setChecked(d_table->commentsEnabled());
+
+  QVBoxLayout *vbox4 = new QVBoxLayout();
+  vbox4->addLayout(hbox1);
+  vbox4->addWidget(gb);
+  vbox4->addLayout(hbox2);
+  vbox4->addWidget(new QLabel(tr("Comment:")));
+  vbox4->addWidget(comments);
+  vbox4->addWidget(boxShowTableComments);
+
+  setLayout(vbox4);
+  setFocusProxy(colName);
+
+  updateColumn(d_table->selectedColumn());
+
+  // signals and slots connections
+  connect(colWidth, SIGNAL(valueChanged(int)), this, SLOT(setColumnWidth(int)));
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
+  connect(columnsBox, SIGNAL(activated(int)), this,
+          SLOT(setPlotDesignation(int)));
+  connect(displayBox, SIGNAL(activated(int)), this, SLOT(updateDisplay(int)));
+  connect(buttonPrev, SIGNAL(clicked()), this, SLOT(prevColumn()));
+  connect(buttonNext, SIGNAL(clicked()), this, SLOT(nextColumn()));
+  connect(formatBox, SIGNAL(activated(int)), this, SLOT(enablePrecision(int)));
+  connect(precisionBox, SIGNAL(valueChanged(int)), this,
+          SLOT(updatePrecision(int)));
+  connect(boxShowTableComments, SIGNAL(toggled(bool)), d_table,
+          SLOT(showComments(bool)));
 }
 
-void TableDialog::nextColumn()
-{
-int sc = d_table->selectedColumn();
-apply();
-updateColumn(++sc);
+void TableDialog::enablePrecision(int f) {
+  if (displayBox->currentIndex())
+    return; // the col type != "Numeric"
+
+  precisionBox->setEnabled(f > 0);
 }
 
-void TableDialog::updateColumn(int sc)
-{
-    int colType = d_table->columnType(sc);
-    if (!sc)
-        buttonPrev->setEnabled(false);
-    else
-        buttonPrev->setEnabled(true);
-
-    if (sc >= d_table->numCols() - 1)
-        buttonNext->setEnabled(false);
-    else
-        buttonNext->setEnabled(true);
-
-    d_table->setSelectedCol(sc);
-    d_table->table()->clearSelection();
-    d_table->table()->selectColumn(sc);
-    int pd = d_table->colPlotDesignation(sc);
-    columnsBox->setCurrentIndex(pd);
-    displayBox->setEnabled(pd != Table::Label);
-
-    QString colLabel = d_table->colLabel(sc);
-    colName->setText(colLabel);
-    colName->setFocus();
-    colName->selectAll();
-
-    comments->setText(d_table->colComment(sc));
-    displayBox->setCurrentIndex(colType);
-    updateDisplay(colType);
-
-    boxReadOnly->setChecked(d_table->isReadOnlyColumn(sc));
-	bool hidden = d_table->isColumnHidden(sc);
-	boxHideColumn->setChecked(hidden);
-	if (hidden)
-		colWidth->setValue(100);
-	else
-		colWidth->setValue(d_table->columnWidth(sc));
-
-    d_table->saveToMemory();
-
-    if (colType == Table::Numeric){
-        int f, prec;
-        d_table->columnNumericFormat(sc, &f, &prec);
-
-        formatBox->setCurrentIndex(f);
-        precisionBox->setValue(prec);
-        enablePrecision(f);
-	} else if (colType == Table::Time || colType == Table::Date){
-        QString format = d_table->columnFormat(sc);
-        if (formatBox->findText(format) < 0)
-            formatBox->insertItem(0, format);
-
-        formatBox->setItemText(0, format);
-    } else if (colType == Table::Day){
-        QString format = d_table->columnFormat(sc);
-        if (format == "ddd")
-            formatBox->setCurrentIndex(0);
-        else if (format == "dddd")
-            formatBox->setCurrentIndex(1);
-        else if (format == "d")
-            formatBox->setCurrentIndex(2);
-    } else if (colType == Table::Month){
-        QString format = d_table->columnFormat(sc);
-        if (format == "MMM")
-            formatBox->setCurrentIndex(0);
-        else if (format == "MMMM")
-            formatBox->setCurrentIndex(1);
-        else if (format == "M")
-            formatBox->setCurrentIndex(2);
-    }
+void TableDialog::accept() {
+  apply();
+  close();
 }
 
-void TableDialog::setColumnWidth(int width)
-{
-d_table->setColumnWidth(width, applyToAllBox->isChecked());
-d_table->setHeaderColType();
+void TableDialog::prevColumn() {
+  int sc = d_table->selectedColumn();
+  apply();
+  updateColumn(--sc);
 }
 
-void TableDialog::apply()
-{
-    if (colName->text().contains("_")){
-        QMessageBox::warning(this, tr("MantidPlot - Warning"),
-        tr("For internal consistency reasons the underscore character is replaced with a minus sign."));}
-
-    QString name=colName->text().replace("-", "_");
-    if (name.contains(QRegExp("\\W"))){
-        QMessageBox::warning(this,tr("MantidPlot - Error"), tr("The column names must only contain letters and digits!"));
-        name.remove(QRegExp("\\W"));
-	}
-
-    int sc = d_table->selectedColumn();
-    d_table->setColumnWidth(colWidth->value(), applyToAllBox->isChecked());
-    d_table->setColComment(sc, comments->toPlainText().replace("\n", " ").replace("\t", " "));
-    d_table->setColName(sc, name.replace("_", "-"), enumerateAllBox->isChecked());
-
-    bool rightColumns = applyToRightCols->isChecked();
-    if (rightColumns){
-        bool readOnly = boxReadOnly->isChecked();
-		for (int i = sc; i<d_table->numCols(); i++){
-            d_table->setReadOnlyColumn(i, readOnly);
-			d_table->hideColumn(i, boxHideColumn->isChecked());
-		}
-    } else {
-        d_table->setReadOnlyColumn(sc, boxReadOnly->isChecked());
-		d_table->hideColumn(sc, boxHideColumn->isChecked());
-	}
-
-    int format = formatBox->currentIndex();
-    int colType = displayBox->currentIndex();
-    switch(colType)
-	{
-	case 0:
-		setNumericFormat(formatBox->currentIndex(), precisionBox->value(), rightColumns);
-	break;
-
-	case 1:
-		setTextFormat(rightColumns);
-	break;
-
-	case 2:
-		 setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
-	break;
-
-	case 3:
-		setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
-	break;
-
-	case 4:
-        if(format == 0)
-            setMonthFormat("MMM", rightColumns);
-        else if(format == 1)
-            setMonthFormat("MMMM", rightColumns);
-        else if(format == 2)
-            setMonthFormat("M", rightColumns);
-	break;
-
-	case 5:
-        if(format == 0)
-            setDayFormat("ddd", rightColumns);
-        else if(format == 1)
-            setDayFormat("dddd", rightColumns);
-        else if(format == 2)
-            setDayFormat("d", rightColumns);
-	break;
-	}
+void TableDialog::nextColumn() {
+  int sc = d_table->selectedColumn();
+  apply();
+  updateColumn(++sc);
 }
 
-void TableDialog::closeEvent( QCloseEvent* ce )
-{
-d_table->freeMemory();
-ce->accept();
+void TableDialog::updateColumn(int sc) {
+  int colType = d_table->columnType(sc);
+  if (!sc)
+    buttonPrev->setEnabled(false);
+  else
+    buttonPrev->setEnabled(true);
+
+  if (sc >= d_table->numCols() - 1)
+    buttonNext->setEnabled(false);
+  else
+    buttonNext->setEnabled(true);
+
+  d_table->setSelectedCol(sc);
+  d_table->table()->clearSelection();
+  d_table->table()->selectColumn(sc);
+  int pd = d_table->colPlotDesignation(sc);
+  columnsBox->setCurrentIndex(pd);
+  displayBox->setEnabled(pd != Table::Label);
+
+  QString colLabel = d_table->colLabel(sc);
+  colName->setText(colLabel);
+  colName->setFocus();
+  colName->selectAll();
+
+  comments->setText(d_table->colComment(sc));
+  displayBox->setCurrentIndex(colType);
+  updateDisplay(colType);
+
+  boxReadOnly->setChecked(d_table->isReadOnlyColumn(sc));
+  bool hidden = d_table->isColumnHidden(sc);
+  boxHideColumn->setChecked(hidden);
+  if (hidden)
+    colWidth->setValue(100);
+  else
+    colWidth->setValue(d_table->columnWidth(sc));
+
+  d_table->saveToMemory();
+
+  if (colType == Table::Numeric) {
+    int f, prec;
+    d_table->columnNumericFormat(sc, &f, &prec);
+
+    formatBox->setCurrentIndex(f);
+    precisionBox->setValue(prec);
+    enablePrecision(f);
+  } else if (colType == Table::Time || colType == Table::Date) {
+    QString format = d_table->columnFormat(sc);
+    if (formatBox->findText(format) < 0)
+      formatBox->insertItem(0, format);
+
+    formatBox->setItemText(0, format);
+  } else if (colType == Table::Day) {
+    QString format = d_table->columnFormat(sc);
+    if (format == "ddd")
+      formatBox->setCurrentIndex(0);
+    else if (format == "dddd")
+      formatBox->setCurrentIndex(1);
+    else if (format == "d")
+      formatBox->setCurrentIndex(2);
+  } else if (colType == Table::Month) {
+    QString format = d_table->columnFormat(sc);
+    if (format == "MMM")
+      formatBox->setCurrentIndex(0);
+    else if (format == "MMMM")
+      formatBox->setCurrentIndex(1);
+    else if (format == "M")
+      formatBox->setCurrentIndex(2);
+  }
 }
 
-void TableDialog::setPlotDesignation(int i)
-{
-    d_table->setPlotDesignation((Table::PlotDesignation)i, applyToRightCols->isChecked());
-    if (i == Table::Label){
-        displayBox->setCurrentIndex(1);
-		updateDisplay(1);
-		displayBox->setEnabled(false);
-    } else
-        displayBox->setEnabled(true);
+void TableDialog::setColumnWidth(int width) {
+  d_table->setColumnWidth(width, applyToAllBox->isChecked());
+  d_table->setHeaderColType();
 }
 
-void TableDialog::showPrecisionBox(int item)
-{
-    switch(item)
-    {
-        case 0:
-        {
-            precisionBox->hide();
-            break;
-        }
-        case 1:
-        {
-            precisionBox->show();
-            break;
-        }
-        case 2:
-        {
-            precisionBox->show();
-            break;
-        }
+void TableDialog::apply() {
+  if (colName->text().contains("_")) {
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),
+                         tr("For internal consistency reasons the underscore "
+                            "character is replaced with a minus sign."));
+  }
+
+  QString name = colName->text().replace("-", "_");
+  if (name.contains(QRegExp("\\W"))) {
+    QMessageBox::warning(
+        this, tr("MantidPlot - Error"),
+        tr("The column names must only contain letters and digits!"));
+    name.remove(QRegExp("\\W"));
+  }
+
+  int sc = d_table->selectedColumn();
+  d_table->setColumnWidth(colWidth->value(), applyToAllBox->isChecked());
+  d_table->setColComment(
+      sc, comments->toPlainText().replace("\n", " ").replace("\t", " "));
+  d_table->setColName(sc, name.replace("_", "-"), enumerateAllBox->isChecked());
+
+  bool rightColumns = applyToRightCols->isChecked();
+  if (rightColumns) {
+    bool readOnly = boxReadOnly->isChecked();
+    for (int i = sc; i < d_table->numCols(); i++) {
+      d_table->setReadOnlyColumn(i, readOnly);
+      d_table->hideColumn(i, boxHideColumn->isChecked());
     }
+  } else {
+    d_table->setReadOnlyColumn(sc, boxReadOnly->isChecked());
+    d_table->hideColumn(sc, boxHideColumn->isChecked());
+  }
+
+  int format = formatBox->currentIndex();
+  int colType = displayBox->currentIndex();
+  switch (colType) {
+  case 0:
+    setNumericFormat(formatBox->currentIndex(), precisionBox->value(),
+                     rightColumns);
+    break;
+
+  case 1:
+    setTextFormat(rightColumns);
+    break;
+
+  case 2:
+    setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
+    break;
+
+  case 3:
+    setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
+    break;
+
+  case 4:
+    if (format == 0)
+      setMonthFormat("MMM", rightColumns);
+    else if (format == 1)
+      setMonthFormat("MMMM", rightColumns);
+    else if (format == 2)
+      setMonthFormat("M", rightColumns);
+    break;
+
+  case 5:
+    if (format == 0)
+      setDayFormat("ddd", rightColumns);
+    else if (format == 1)
+      setDayFormat("dddd", rightColumns);
+    else if (format == 2)
+      setDayFormat("d", rightColumns);
+    break;
+  }
 }
 
-void TableDialog::updatePrecision(int prec)
-{
-    setNumericFormat(formatBox->currentIndex(), prec, applyToRightCols->isChecked());
+void TableDialog::closeEvent(QCloseEvent *ce) {
+  d_table->freeMemory();
+  ce->accept();
 }
 
-void TableDialog::updateDisplay(int item)
-{
-    labelFormat->show();
-    formatBox->show();
-    formatBox->clear();
-    formatBox->setEditable(false);
-    labelNumeric->hide();
+void TableDialog::setPlotDesignation(int i) {
+  d_table->setPlotDesignation((Table::PlotDesignation)i,
+                              applyToRightCols->isChecked());
+  if (i == Table::Label) {
+    displayBox->setCurrentIndex(1);
+    updateDisplay(1);
+    displayBox->setEnabled(false);
+  } else
+    displayBox->setEnabled(true);
+}
+
+void TableDialog::showPrecisionBox(int item) {
+  switch (item) {
+  case 0: {
     precisionBox->hide();
+    break;
+  }
+  case 1: {
+    precisionBox->show();
+    break;
+  }
+  case 2: {
+    precisionBox->show();
+    break;
+  }
+  }
+}
 
-    if (item == 0){
-        formatBox->addItem( tr( "Default" ) );
-        formatBox->addItem( tr( "Decimal: 1000" ) );
-        formatBox->addItem( tr( "Scientific: 1E3" ) );
-
-        labelNumeric->show();
-        precisionBox->show();
-	} else {
-        switch (item)
-		{
-		case 1:
-			labelFormat->hide();
-			formatBox->hide();
-		break;
-
-		case 2:
-            formatBox->setEditable(true);
-			formatBox->addItem(tr("dd/MM/yyyy"));
-			formatBox->addItem(tr("dd/MM/yyyy HH:mm"));
-			formatBox->addItem(tr("dd/MM/yyyy HH:mm:ss"));
-
-			formatBox->addItem(tr("dd.MM.yyyy"));
-			formatBox->addItem(tr("dd.MM.yyyy HH:mm"));
-			formatBox->addItem(tr("dd.MM.yyyy HH:mm:ss"));
-
-			formatBox->addItem(tr("dd MM yyyy"));
-			formatBox->addItem(tr("dd MM yyyy HH:mm"));
-			formatBox->addItem(tr("dd MM yyyy HH:mm:ss"));
-
-			formatBox->addItem(tr("yyyy-MM-dd"));
-			formatBox->addItem(tr("yyyy-MM-dd HH:mm"));
-			formatBox->addItem(tr("yyyy-MM-dd HH:mm:ss"));
-
-			formatBox->addItem(tr("yyyyMMdd"));
-			formatBox->addItem(tr("yyyyMMdd HH:mm"));
-			formatBox->addItem(tr("yyyyMMdd HH:mm:ss"));
-		break;
-
-		case 3:
-			{
-			formatBox->setEditable ( true );
-
-			formatBox->addItem(tr("h") );
-			formatBox->addItem(tr("h ap") );
-			formatBox->addItem(tr("h AP") );
-			formatBox->addItem(tr("h:mm"));
-			formatBox->addItem(tr("h:mm ap") );
-			formatBox->addItem(tr("hh:mm"));
-			formatBox->addItem(tr("h:mm:ss") );
-			formatBox->addItem(tr("h:mm:ss.zzz") );
-			formatBox->addItem(tr("mm:ss") );
-			formatBox->addItem(tr("mm:ss.zzz") );
-			formatBox->addItem(tr("hmm") );
-			formatBox->addItem(tr("hmmss") );
-			formatBox->addItem(tr("hhmmss") );
-			}
-		break;
-
-		case 4:
-		{
-			QDate date=QDate::currentDate();
-			formatBox->addItem(QDate::shortMonthName(date.month()));
-			formatBox->addItem(QDate::longMonthName(date.month()));
-			formatBox->addItem(QDate::shortMonthName(date.month()).left(1));
-		}
-		break;
-
-		case 5:
-		{
-			QDate date=QDate::currentDate();
-			formatBox->addItem(QDate::shortDayName(date.dayOfWeek()));
-			formatBox->addItem(QDate::longDayName(date.dayOfWeek()));
-			formatBox->addItem(QDate::shortDayName(date.dayOfWeek()).left(1));
-		}
-		break;
-		}
-	}
+void TableDialog::updatePrecision(int prec) {
+  setNumericFormat(formatBox->currentIndex(), prec,
+                   applyToRightCols->isChecked());
 }
 
-void TableDialog::setDateTimeFormat(int type, const QString& format, bool allRightColumns)
-{
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    bool ok = false;
-	int sc = d_table->selectedColumn();
-	if (allRightColumns){
-		for (int i = sc; i<d_table->numCols(); i++){
-		    if (type == Table::Date)
-                ok = d_table->setDateFormat(format, i);
-            else if (type == Table::Time)
-                ok = d_table->setTimeFormat(format, i);
-			if (!ok)
-                break;
-		}
-	}
-	else if (type == Table::Date)
-		ok = d_table->setDateFormat(format, sc);
-    else if (type == Table::Time)
-		ok = d_table->setTimeFormat(format, sc);
-
-	QApplication::restoreOverrideCursor();
-
-    if (!ok){
-        QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Couldn't guess the source data format, please specify it using the 'Format' box!")+"\n\n"+
-                             tr("For more information about the supported date/time formats please read the Qt documentation for the QDateTime class!"));
-        return;
+void TableDialog::updateDisplay(int item) {
+  labelFormat->show();
+  formatBox->show();
+  formatBox->clear();
+  formatBox->setEditable(false);
+  labelNumeric->hide();
+  precisionBox->hide();
+
+  if (item == 0) {
+    formatBox->addItem(tr("Default"));
+    formatBox->addItem(tr("Decimal: 1000"));
+    formatBox->addItem(tr("Scientific: 1E3"));
+
+    labelNumeric->show();
+    precisionBox->show();
+  } else {
+    switch (item) {
+    case 1:
+      labelFormat->hide();
+      formatBox->hide();
+      break;
+
+    case 2:
+      formatBox->setEditable(true);
+      formatBox->addItem(tr("dd/MM/yyyy"));
+      formatBox->addItem(tr("dd/MM/yyyy HH:mm"));
+      formatBox->addItem(tr("dd/MM/yyyy HH:mm:ss"));
+
+      formatBox->addItem(tr("dd.MM.yyyy"));
+      formatBox->addItem(tr("dd.MM.yyyy HH:mm"));
+      formatBox->addItem(tr("dd.MM.yyyy HH:mm:ss"));
+
+      formatBox->addItem(tr("dd MM yyyy"));
+      formatBox->addItem(tr("dd MM yyyy HH:mm"));
+      formatBox->addItem(tr("dd MM yyyy HH:mm:ss"));
+
+      formatBox->addItem(tr("yyyy-MM-dd"));
+      formatBox->addItem(tr("yyyy-MM-dd HH:mm"));
+      formatBox->addItem(tr("yyyy-MM-dd HH:mm:ss"));
+
+      formatBox->addItem(tr("yyyyMMdd"));
+      formatBox->addItem(tr("yyyyMMdd HH:mm"));
+      formatBox->addItem(tr("yyyyMMdd HH:mm:ss"));
+      break;
+
+    case 3: {
+      formatBox->setEditable(true);
+
+      formatBox->addItem(tr("h"));
+      formatBox->addItem(tr("h ap"));
+      formatBox->addItem(tr("h AP"));
+      formatBox->addItem(tr("h:mm"));
+      formatBox->addItem(tr("h:mm ap"));
+      formatBox->addItem(tr("hh:mm"));
+      formatBox->addItem(tr("h:mm:ss"));
+      formatBox->addItem(tr("h:mm:ss.zzz"));
+      formatBox->addItem(tr("mm:ss"));
+      formatBox->addItem(tr("mm:ss.zzz"));
+      formatBox->addItem(tr("hmm"));
+      formatBox->addItem(tr("hmmss"));
+      formatBox->addItem(tr("hhmmss"));
+    } break;
+
+    case 4: {
+      QDate date = QDate::currentDate();
+      formatBox->addItem(QDate::shortMonthName(date.month()));
+      formatBox->addItem(QDate::longMonthName(date.month()));
+      formatBox->addItem(QDate::shortMonthName(date.month()).left(1));
+    } break;
+
+    case 5: {
+      QDate date = QDate::currentDate();
+      formatBox->addItem(QDate::shortDayName(date.dayOfWeek()));
+      formatBox->addItem(QDate::longDayName(date.dayOfWeek()));
+      formatBox->addItem(QDate::shortDayName(date.dayOfWeek()).left(1));
+    } break;
     }
+  }
+}
 
-    if (formatBox->findText(format) < 0){
-        formatBox->insertItem(0, format);
-        formatBox->setItemText(0, format);
+void TableDialog::setDateTimeFormat(int type, const QString &format,
+                                    bool allRightColumns) {
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  bool ok = false;
+  int sc = d_table->selectedColumn();
+  if (allRightColumns) {
+    for (int i = sc; i < d_table->numCols(); i++) {
+      if (type == Table::Date)
+        ok = d_table->setDateFormat(format, i);
+      else if (type == Table::Time)
+        ok = d_table->setTimeFormat(format, i);
+      if (!ok)
+        break;
     }
-    d_table->notifyChanges();
+  } else if (type == Table::Date)
+    ok = d_table->setDateFormat(format, sc);
+  else if (type == Table::Time)
+    ok = d_table->setTimeFormat(format, sc);
+
+  QApplication::restoreOverrideCursor();
+
+  if (!ok) {
+    QMessageBox::critical(
+        this, tr("MantidPlot - Error"),
+        tr("Couldn't guess the source data format, please specify it using the "
+           "'Format' box!") +
+            "\n\n" +
+            tr("For more information about the supported date/time formats "
+               "please read the Qt documentation for the QDateTime class!"));
+    return;
+  }
+
+  if (formatBox->findText(format) < 0) {
+    formatBox->insertItem(0, format);
+    formatBox->setItemText(0, format);
+  }
+  d_table->notifyChanges();
 }
 
-void TableDialog::setNumericFormat(int type, int prec, bool allRightColumns)
-{
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	int sc = d_table->selectedColumn();
-	if (allRightColumns){
-		for (int i = sc; i<d_table->numCols(); i++)
-			d_table->setColNumericFormat(type, prec, i);
-	} else
-		d_table->setColNumericFormat(type, prec, sc);
-
-	d_table->notifyChanges();
-	QApplication::restoreOverrideCursor();
+void TableDialog::setNumericFormat(int type, int prec, bool allRightColumns) {
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  int sc = d_table->selectedColumn();
+  if (allRightColumns) {
+    for (int i = sc; i < d_table->numCols(); i++)
+      d_table->setColNumericFormat(type, prec, i);
+  } else
+    d_table->setColNumericFormat(type, prec, sc);
+
+  d_table->notifyChanges();
+  QApplication::restoreOverrideCursor();
 }
 
-void TableDialog::setTextFormat(bool allRightColumns)
-{
-	int sc = d_table->selectedColumn();
-	if (allRightColumns){
-		for (int i = sc; i<d_table->numCols(); i++)
-			d_table->setTextFormat(i);
-	} else
-		d_table->setTextFormat(sc);
+void TableDialog::setTextFormat(bool allRightColumns) {
+  int sc = d_table->selectedColumn();
+  if (allRightColumns) {
+    for (int i = sc; i < d_table->numCols(); i++)
+      d_table->setTextFormat(i);
+  } else
+    d_table->setTextFormat(sc);
 }
 
-void TableDialog::setDayFormat(const QString& format, bool allRightColumns)
-{
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	int sc = d_table->selectedColumn();
-	if (allRightColumns){
-		for (int i = sc; i<d_table->numCols(); i++)
-            d_table->setDayFormat(format, i);
-	} else
-        d_table->setDayFormat(format, sc);
-
-	QApplication::restoreOverrideCursor();
-    d_table->notifyChanges();
+void TableDialog::setDayFormat(const QString &format, bool allRightColumns) {
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  int sc = d_table->selectedColumn();
+  if (allRightColumns) {
+    for (int i = sc; i < d_table->numCols(); i++)
+      d_table->setDayFormat(format, i);
+  } else
+    d_table->setDayFormat(format, sc);
+
+  QApplication::restoreOverrideCursor();
+  d_table->notifyChanges();
 }
 
-void TableDialog::setMonthFormat(const QString& format, bool allRightColumns)
-{
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	int sc = d_table->selectedColumn();
-	if (allRightColumns){
-		for (int i = sc; i<d_table->numCols(); i++)
-            d_table->setMonthFormat(format, i);
-	} else
-        d_table->setMonthFormat(format, sc);
-
-	QApplication::restoreOverrideCursor();
-    d_table->notifyChanges();
+void TableDialog::setMonthFormat(const QString &format, bool allRightColumns) {
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  int sc = d_table->selectedColumn();
+  if (allRightColumns) {
+    for (int i = sc; i < d_table->numCols(); i++)
+      d_table->setMonthFormat(format, i);
+  } else
+    d_table->setMonthFormat(format, sc);
+
+  QApplication::restoreOverrideCursor();
+  d_table->notifyChanges();
 }
diff --git a/MantidPlot/src/TableDialog.h b/MantidPlot/src/TableDialog.h
index 14c3625ed410a4782187aa04fd2c635edd6e07ba..5c7d71b087c3407a1bff8cfc16b01078ef3b27bd 100644
--- a/MantidPlot/src/TableDialog.h
+++ b/MantidPlot/src/TableDialog.h
@@ -2,7 +2,8 @@
     File                 : TableDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Column options dialog
 
@@ -40,57 +41,56 @@ class QTextEdit;
 class QSpinBox;
 
 //! Column options dialog
-class TableDialog : public QDialog
-{
-    Q_OBJECT
+class TableDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    TableDialog(Table *t, Qt::WFlags fl = 0 );
+  TableDialog(Table *t, Qt::WFlags fl = 0);
 
 private slots:
-	void prevColumn();
-	void nextColumn();
-	void updateColumn(int);
-	void setColumnWidth(int width);
-	void showPrecisionBox(int item);
-	void updatePrecision(int prec);
-	void setPlotDesignation(int i);
-        void accept() override;
-        void apply();
-	void updateDisplay(int item);
-	void enablePrecision(int f);
-	void setNumericFormat(int type, int prec, bool allRightColumns);
-	void setDayFormat(const QString& format, bool allRightColumns);
-	void setMonthFormat(const QString& format, bool allRightColumns);
+  void prevColumn();
+  void nextColumn();
+  void updateColumn(int);
+  void setColumnWidth(int width);
+  void showPrecisionBox(int item);
+  void updatePrecision(int prec);
+  void setPlotDesignation(int i);
+  void accept() override;
+  void apply();
+  void updateDisplay(int item);
+  void enablePrecision(int f);
+  void setNumericFormat(int type, int prec, bool allRightColumns);
+  void setDayFormat(const QString &format, bool allRightColumns);
+  void setMonthFormat(const QString &format, bool allRightColumns);
 
 signals:
-	void nameChanged(const QString&);
-	void enumRightCols(bool);
-	void changeWidth(const QString&, bool);
+  void nameChanged(const QString &);
+  void enumRightCols(bool);
+  void changeWidth(const QString &, bool);
 
 private:
-    void setDateTimeFormat(int type, const QString& format, bool allRightColumns);
-	void setTextFormat(bool allRightColumns);
-        void closeEvent(QCloseEvent *) override;
+  void setDateTimeFormat(int type, const QString &format, bool allRightColumns);
+  void setTextFormat(bool allRightColumns);
+  void closeEvent(QCloseEvent *) override;
 
-    Table * d_table;
+  Table *d_table;
 
-    QPushButton* buttonOk;
-    QPushButton* buttonCancel;
-	QPushButton* buttonApply;
-	QPushButton* buttonPrev;
-	QPushButton* buttonNext;
-    QLineEdit* colName;
-    QCheckBox* enumerateAllBox;
-    QCheckBox* applyToRightCols;
-    QCheckBox* applyToAllBox;
-    QComboBox* formatBox;
-	QComboBox* displayBox;
-    QComboBox* columnsBox;
-    QSpinBox* colWidth, *precisionBox;
-	QLabel *labelNumeric, *labelFormat;
-	QTextEdit *comments;
-	QCheckBox *boxShowTableComments, *boxReadOnly, *boxHideColumn;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonApply;
+  QPushButton *buttonPrev;
+  QPushButton *buttonNext;
+  QLineEdit *colName;
+  QCheckBox *enumerateAllBox;
+  QCheckBox *applyToRightCols;
+  QCheckBox *applyToAllBox;
+  QComboBox *formatBox;
+  QComboBox *displayBox;
+  QComboBox *columnsBox;
+  QSpinBox *colWidth, *precisionBox;
+  QLabel *labelNumeric, *labelFormat;
+  QTextEdit *comments;
+  QCheckBox *boxShowTableComments, *boxReadOnly, *boxHideColumn;
 };
 
 #endif // TABLEDIALOG_H
diff --git a/MantidPlot/src/TableStatistics.h b/MantidPlot/src/TableStatistics.h
index 3fcd6fb721706013743e64b17371cf488a41711d..b875471e62430142cc91f771c4d98ca2eea2db55 100644
--- a/MantidPlot/src/TableStatistics.h
+++ b/MantidPlot/src/TableStatistics.h
@@ -1,11 +1,11 @@
 /***************************************************************************
-	File                 : TableStatistics.h
-	Project              : QtiPlot
+        File                 : TableStatistics.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Knut Franke
-	Email (use @ for *)  : knut.franke*gmx.de
-	Description          : Table subclass that displays statistics on
-	                       columns or rows of another table
+        Copyright            : (C) 2006 by Knut Franke
+        Email (use @ for *)  : knut.franke*gmx.de
+        Description          : Table subclass that displays statistics on
+                               columns or rows of another table
 
  ***************************************************************************/
 
@@ -37,39 +37,40 @@
  * \section future Future Plans
  * Make it possible to add new columns/rows to be monitored.
  */
-class TableStatistics : public Table
-{
-	Q_OBJECT
+class TableStatistics : public Table {
+  Q_OBJECT
 
-	public:
-		//! supported statistics types
-		enum Type { row, column };
-		TableStatistics(ScriptingEnv *env, ApplicationWindow *parent, Table *base, Type, QList<int> targets);
-		//! return the type of statistics
-		Type type() const { return d_type; }
-		//! return the base table of which statistics are displayed
-		Table *base() const { return d_base; }
+public:
+  //! supported statistics types
+  enum Type { row, column };
+  TableStatistics(ScriptingEnv *env, ApplicationWindow *parent, Table *base,
+                  Type, QList<int> targets);
+  //! return the type of statistics
+  Type type() const { return d_type; }
+  //! return the base table of which statistics are displayed
+  Table *base() const { return d_base; }
 
-                void loadFromProject(const std::string &lines,
-                                     ApplicationWindow *app,
-                                     const int fileVersion) override;
-                std::string saveToProject(ApplicationWindow *app) override;
+  void loadFromProject(const std::string &lines, ApplicationWindow *app,
+                       const int fileVersion) override;
+  std::string saveToProject(ApplicationWindow *app) override;
 
-    public slots:
-        //! update statistics after a column has changed (to be connected with Table::modifiedData)
-        void update(Table*, const QString& colName);
-		//! handle renaming of columns (to be connected with Table::changedColHeader)
-		void renameCol(const QString&, const QString&);
-		//! remove statistics of removed columns (to be connected with Table::removedCol)
-		void removeCol(const QString&);
+public slots:
+  //! update statistics after a column has changed (to be connected with
+  // Table::modifiedData)
+  void update(Table *, const QString &colName);
+  //! handle renaming of columns (to be connected with Table::changedColHeader)
+  void renameCol(const QString &, const QString &);
+  //! remove statistics of removed columns (to be connected with
+  // Table::removedCol)
+  void removeCol(const QString &);
 
-	private slots:
-		void closedBase();
-	
-	private:
-		Table *d_base;
-		Type d_type;
-		QList<int> d_targets;
+private slots:
+  void closedBase();
+
+private:
+  Table *d_base;
+  Type d_type;
+  QList<int> d_targets;
 };
 
 #endif
diff --git a/MantidPlot/src/TextDialog.cpp b/MantidPlot/src/TextDialog.cpp
index 393be4ad81fa2276caa00dc58bee03db18320ae4..7c2ee6c72f73aefda82c92940f12df52573823b1 100644
--- a/MantidPlot/src/TextDialog.cpp
+++ b/MantidPlot/src/TextDialog.cpp
@@ -47,12 +47,11 @@
 
 #include <qwt_scale_widget.h>
 
-TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
-  : QDialog( parent, fl)
-{
+TextDialog::TextDialog(TextType type, QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
   setAttribute(Qt::WA_DeleteOnClose);
-  setWindowTitle( tr( "MantidPlot - Text options" ) );
-  setSizeGripEnabled( true );
+  setWindowTitle(tr("MantidPlot - Text options"));
+  setSizeGripEnabled(true);
 
   d_graph = NULL;
   d_scale = NULL;
@@ -62,56 +61,56 @@ TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
 
   // top groupbox
   groupBox1 = new QGroupBox(QString());
-  QGridLayout * topLayout = new QGridLayout(groupBox1);
+  QGridLayout *topLayout = new QGridLayout(groupBox1);
   topLayout->addWidget(new QLabel(tr("Text Color")), 0, 0);
 
   colorBtn = new ColorButton();
   topLayout->addWidget(colorBtn, 0, 1);
 
   buttonOk = new QPushButton(tr("&OK"));
-  buttonOk->setAutoDefault( true );
-  buttonOk->setDefault( true );
+  buttonOk->setAutoDefault(true);
+  buttonOk->setDefault(true);
 
   topLayout->addWidget(buttonOk, 0, 3);
   topLayout->addWidget(new QLabel(tr("Font")), 1, 0);
 
-  buttonFont = new QPushButton(tr( "&Font" ));
+  buttonFont = new QPushButton(tr("&Font"));
   topLayout->addWidget(buttonFont, 1, 1);
 
-  buttonApply = new QPushButton(tr( "&Apply" ));
-  buttonApply->setDefault( true );
-  topLayout->addWidget( buttonApply, 1, 3 );
+  buttonApply = new QPushButton(tr("&Apply"));
+  buttonApply->setDefault(true);
+  topLayout->addWidget(buttonApply, 1, 3);
 
   alignmentBox = NULL;
   backgroundBox = NULL;
-  if (textType != TextDialog::TextMarker){
+  if (textType != TextDialog::TextMarker) {
     topLayout->addWidget(new QLabel(tr("Alignment")), 2, 0);
     alignmentBox = new QComboBox();
-    alignmentBox->addItem( tr( "Center" ) );
-    alignmentBox->addItem( tr( "Left" ) );
-    alignmentBox->addItem( tr( "Right" ) );
+    alignmentBox->addItem(tr("Center"));
+    alignmentBox->addItem(tr("Left"));
+    alignmentBox->addItem(tr("Right"));
     topLayout->addWidget(alignmentBox, 2, 1);
 
     boxApplyToAll = new QCheckBox(tr("Apply format to all &labels in layer"));
-    topLayout->addWidget(boxApplyToAll, 3, 0 );
+    topLayout->addWidget(boxApplyToAll, 3, 0);
   } else {
     topLayout->addWidget(new QLabel(tr("Frame")), 2, 0);
     backgroundBox = new QComboBox();
-    backgroundBox->addItem( tr( "None" ) );
-    backgroundBox->addItem( tr( "Rectangle" ) );
-    backgroundBox->addItem( tr( "Shadow" ) );
+    backgroundBox->addItem(tr("None"));
+    backgroundBox->addItem(tr("Rectangle"));
+    backgroundBox->addItem(tr("Shadow"));
     topLayout->addWidget(backgroundBox, 2, 1);
   }
 
-  buttonCancel = new QPushButton( tr( "&Cancel" ) );
-  topLayout->addWidget( buttonCancel, 2, 3 );
+  buttonCancel = new QPushButton(tr("&Cancel"));
+  topLayout->addWidget(buttonCancel, 2, 3);
 
   backgroundBtn = NULL;
 
   buttonDefault = NULL;
   boxBackgroundTransparency = NULL;
-  if (textType == TextMarker)
-  { //TODO: Sometime background features for axes lables should be implemented
+  if (textType == TextMarker) { // TODO: Sometime background features for axes
+                                // lables should be implemented
     topLayout->addWidget(new QLabel(tr("Opacity")), 3, 0);
     boxBackgroundTransparency = new QSpinBox();
     boxBackgroundTransparency->setRange(0, 255);
@@ -119,21 +118,21 @@ TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
     boxBackgroundTransparency->setWrapping(true);
     boxBackgroundTransparency->setSpecialValueText(tr("Transparent"));
 
-    topLayout->addWidget( boxBackgroundTransparency, 3, 1 );
+    topLayout->addWidget(boxBackgroundTransparency, 3, 1);
     topLayout->addWidget(new QLabel(tr("Background color")), 4, 0);
     backgroundBtn = new ColorButton(groupBox1);
     backgroundBtn->setEnabled(false);
-    topLayout->addWidget( backgroundBtn, 4, 1 );
+    topLayout->addWidget(backgroundBtn, 4, 1);
 
-    connect(boxBackgroundTransparency, SIGNAL(valueChanged(int)),
-				this, SLOT(updateTransparency(int)));
+    connect(boxBackgroundTransparency, SIGNAL(valueChanged(int)), this,
+            SLOT(updateTransparency(int)));
 
     boxApplyToAll = new QCheckBox(tr("Apply format to all &labels in layer"));
-    topLayout->addWidget(boxApplyToAll, 5, 0 );
+    topLayout->addWidget(boxApplyToAll, 5, 0);
 
-    buttonDefault = new QPushButton( tr( "Set As &Default" ) );
-    topLayout->addWidget( buttonDefault, 3, 3 );
-    connect( buttonDefault, SIGNAL(clicked()), this, SLOT(setDefaultValues()));
+    buttonDefault = new QPushButton(tr("Set As &Default"));
+    topLayout->addWidget(buttonDefault, 3, 3);
+    connect(buttonDefault, SIGNAL(clicked()), this, SLOT(setDefaultValues()));
   }
 
   // align the OK, Apply, and Cancel buttons to the right
@@ -162,264 +161,253 @@ TextDialog::TextDialog(TextType type, QWidget* parent, Qt::WFlags fl)
   textEditBox->setAcceptRichText(false);
   textEditBox->setFont(QFont());
 
-  formatButtons =  new TextFormatButtons(textEditBox, TextFormatButtons::AxisLabel);
+  formatButtons =
+      new TextFormatButtons(textEditBox, TextFormatButtons::AxisLabel);
 
   setFocusPolicy(Qt::StrongFocus);
   setFocusProxy(textEditBox);
 
-  QVBoxLayout* mainLayout = new QVBoxLayout();
+  QVBoxLayout *mainLayout = new QVBoxLayout();
   mainLayout->addWidget(groupBox1);
   mainLayout->addWidget(formatButtons);
   mainLayout->addWidget(textEditBox);
-  setLayout( mainLayout );
+  setLayout(mainLayout);
 
   // signals and slots connections
-  connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
-  connect( buttonApply, SIGNAL( clicked() ), this, SLOT( apply() ) );
-  connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-  connect( buttonFont, SIGNAL( clicked() ), this, SLOT(customFont() ) );
+  connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(buttonFont, SIGNAL(clicked()), this, SLOT(customFont()));
 }
 
-void TextDialog::setGraph(Graph *g)
-{
-	if (!g)
-		return;
-
-	d_graph = g;
-	QwtText l;
-	if (textType == LayerTitle)
-		l = d_graph->plotWidget()->title();
-	else if (textType == AxisTitle){
-		d_scale = g->currentScale();
-		if (!d_scale)
-			return;
-
-		l =	d_scale->title();
-		switch(d_scale->alignment()){
-			case QwtScaleDraw::BottomScale:
-				setWindowTitle(tr("MantidPlot") + " - " + tr("X Axis Title"));
-			break;
-			case QwtScaleDraw::LeftScale:
-				setWindowTitle(tr("MantidPlot") + " - " + tr("Y Axis Title"));
-			break;
-			case QwtScaleDraw::TopScale:
-				setWindowTitle(tr("MantidPlot") + " - " + tr("Top Axis Title"));
-			break;
-			case QwtScaleDraw::RightScale:
-				setWindowTitle(tr("MantidPlot") + " - " + tr("Right Axis Title"));
-			break;
-		}
-	}
-
-	setAlignment(l.renderFlags());
-	setText(l.text());
-	selectedFont = l.font();
-	colorBtn->setColor(l.color());
+void TextDialog::setGraph(Graph *g) {
+  if (!g)
+    return;
+
+  d_graph = g;
+  QwtText l;
+  if (textType == LayerTitle)
+    l = d_graph->plotWidget()->title();
+  else if (textType == AxisTitle) {
+    d_scale = g->currentScale();
+    if (!d_scale)
+      return;
+
+    l = d_scale->title();
+    switch (d_scale->alignment()) {
+    case QwtScaleDraw::BottomScale:
+      setWindowTitle(tr("MantidPlot") + " - " + tr("X Axis Title"));
+      break;
+    case QwtScaleDraw::LeftScale:
+      setWindowTitle(tr("MantidPlot") + " - " + tr("Y Axis Title"));
+      break;
+    case QwtScaleDraw::TopScale:
+      setWindowTitle(tr("MantidPlot") + " - " + tr("Top Axis Title"));
+      break;
+    case QwtScaleDraw::RightScale:
+      setWindowTitle(tr("MantidPlot") + " - " + tr("Right Axis Title"));
+      break;
+    }
+  }
+
+  setAlignment(l.renderFlags());
+  setText(l.text());
+  selectedFont = l.font();
+  colorBtn->setColor(l.color());
 }
 
-void TextDialog::setLegendWidget(LegendWidget *l)
-{
-	if (!l)
-		return;
+void TextDialog::setLegendWidget(LegendWidget *l) {
+  if (!l)
+    return;
 
-	d_graph = static_cast<Graph *>((l->plot()->parent()));
-	d_legend = l;
+  d_graph = static_cast<Graph *>((l->plot()->parent()));
+  d_legend = l;
 
-	setText(l->text());
-	selectedFont = l->font();
-	colorBtn->setColor(l->textColor());
+  setText(l->text());
+  selectedFont = l->font();
+  colorBtn->setColor(l->textColor());
 
-	QColor bc = l->backgroundColor();
-	boxBackgroundTransparency->setValue(bc.alpha());
-	backgroundBtn->setEnabled(bc.alpha());
-	backgroundBtn->setColor(bc);
+  QColor bc = l->backgroundColor();
+  boxBackgroundTransparency->setValue(bc.alpha());
+  backgroundBtn->setEnabled(bc.alpha());
+  backgroundBtn->setColor(bc);
 
-	backgroundBox->setCurrentIndex(l->frameStyle());
+  backgroundBox->setCurrentIndex(l->frameStyle());
 
-	d_legend->setSelected(false);
+  d_legend->setSelected(false);
 }
 
-void TextDialog::apply()
-{
-	if (textType == AxisTitle){
-		if (!d_graph || !d_scale)
-			return;
-
-		QwtText t =	d_scale->title();
-		t.setRenderFlags(alignment());
-		t.setText(textEditBox->toPlainText());
-		d_scale->setTitle(t);
-
-		if (boxApplyToAll->isChecked())
-			formatAllLabels();
-		else {
-			t.setFont(selectedFont);
-			t.setColor(colorBtn->color());
-			d_scale->setTitle(t);
-			d_graph->replot();
-		}
-	} else if (textType == TextMarker && d_legend){
-		//QColor tc = colorBtn->color();
-		QColor c = backgroundBtn->color();
-		c.setAlpha(boxBackgroundTransparency->value());
-
-		d_legend->setText(textEditBox->toPlainText());
-		if (boxApplyToAll->isChecked())
-			formatAllLabels();
-		else {
-			d_legend->setBackgroundColor(c);
-			d_legend->setTextColor(colorBtn->color());
-			d_legend->setFrameStyle(backgroundBox->currentIndex());
-			d_legend->setFont(selectedFont);
-			d_legend->repaint();
-		}
-	} else if (textType == LayerTitle){
-		if (!d_graph)
-			return;
-
-		Plot *plot = d_graph->plotWidget();
-		QwtText t =	plot->title();
-		t.setRenderFlags(alignment());
-		t.setText(textEditBox->toPlainText());
-		plot->setTitle(t);
-
-		if (boxApplyToAll->isChecked())
-			formatAllLabels();
-		else {
-			t.setFont(selectedFont);
-			t.setColor(colorBtn->color());
-			plot->setTitle(t);
-			plot->replot();
-		}
-	}
-
-	if (d_graph)
-		d_graph->notifyChanges();
+void TextDialog::apply() {
+  if (textType == AxisTitle) {
+    if (!d_graph || !d_scale)
+      return;
+
+    QwtText t = d_scale->title();
+    t.setRenderFlags(alignment());
+    t.setText(textEditBox->toPlainText());
+    d_scale->setTitle(t);
+
+    if (boxApplyToAll->isChecked())
+      formatAllLabels();
+    else {
+      t.setFont(selectedFont);
+      t.setColor(colorBtn->color());
+      d_scale->setTitle(t);
+      d_graph->replot();
+    }
+  } else if (textType == TextMarker && d_legend) {
+    // QColor tc = colorBtn->color();
+    QColor c = backgroundBtn->color();
+    c.setAlpha(boxBackgroundTransparency->value());
+
+    d_legend->setText(textEditBox->toPlainText());
+    if (boxApplyToAll->isChecked())
+      formatAllLabels();
+    else {
+      d_legend->setBackgroundColor(c);
+      d_legend->setTextColor(colorBtn->color());
+      d_legend->setFrameStyle(backgroundBox->currentIndex());
+      d_legend->setFont(selectedFont);
+      d_legend->repaint();
+    }
+  } else if (textType == LayerTitle) {
+    if (!d_graph)
+      return;
+
+    Plot *plot = d_graph->plotWidget();
+    QwtText t = plot->title();
+    t.setRenderFlags(alignment());
+    t.setText(textEditBox->toPlainText());
+    plot->setTitle(t);
+
+    if (boxApplyToAll->isChecked())
+      formatAllLabels();
+    else {
+      t.setFont(selectedFont);
+      t.setColor(colorBtn->color());
+      plot->setTitle(t);
+      plot->replot();
+    }
+  }
+
+  if (d_graph)
+    d_graph->notifyChanges();
 }
 
-void TextDialog::formatAllLabels()
-{
-	if (!d_graph)
-		return;
-
-	Plot *plot = d_graph->plotWidget();
-	if (!plot)
-		return;
-
-	QColor tc = colorBtn->color();
-	QObjectList lst = plot->children();
-	foreach(QObject *o, lst){
-		if (o->inherits("LegendWidget")){
-			LegendWidget *l = static_cast<LegendWidget *>(o);
-        	l->setTextColor(tc);
-			l->setFont(selectedFont);
-			if(textType == TextMarker){
-				QColor c = backgroundBtn->color();
-				c.setAlpha(boxBackgroundTransparency->value());
-				l->setBackgroundColor(c);
-				l->setFrameStyle(backgroundBox->currentIndex());
-			}
-		}
-	}
-
-	for (int i=0; i < QwtPlot::axisCnt; i++){
-		QwtScaleWidget *scale = plot->axisWidget(i);
-		if (scale){
-			QwtText t = scale->title();
-			t.setColor(tc);
-			t.setFont(selectedFont);
-			scale->setTitle(t);
-		}
-	}
-
-	QwtText t = plot->title();
-	t.setColor(tc);
-	t.setFont(selectedFont);
-	plot->setTitle (t);
-	plot->replot();
+void TextDialog::formatAllLabels() {
+  if (!d_graph)
+    return;
+
+  Plot *plot = d_graph->plotWidget();
+  if (!plot)
+    return;
+
+  QColor tc = colorBtn->color();
+  QObjectList lst = plot->children();
+  foreach (QObject *o, lst) {
+    if (o->inherits("LegendWidget")) {
+      LegendWidget *l = static_cast<LegendWidget *>(o);
+      l->setTextColor(tc);
+      l->setFont(selectedFont);
+      if (textType == TextMarker) {
+        QColor c = backgroundBtn->color();
+        c.setAlpha(boxBackgroundTransparency->value());
+        l->setBackgroundColor(c);
+        l->setFrameStyle(backgroundBox->currentIndex());
+      }
+    }
+  }
+
+  for (int i = 0; i < QwtPlot::axisCnt; i++) {
+    QwtScaleWidget *scale = plot->axisWidget(i);
+    if (scale) {
+      QwtText t = scale->title();
+      t.setColor(tc);
+      t.setFont(selectedFont);
+      scale->setTitle(t);
+    }
+  }
+
+  QwtText t = plot->title();
+  t.setColor(tc);
+  t.setFont(selectedFont);
+  plot->setTitle(t);
+  plot->replot();
 }
 
-void TextDialog::setDefaultValues()
-{
-	ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
-	if (!app)
-		return;
+void TextDialog::setDefaultValues() {
+  ApplicationWindow *app = static_cast<ApplicationWindow *>(this->parent());
+  if (!app)
+    return;
 
-	QColor c = backgroundBtn->color();
-	c.setAlpha(boxBackgroundTransparency->value());
-	app->setLegendDefaultSettings(backgroundBox->currentIndex(), selectedFont, colorBtn->color(), c);
+  QColor c = backgroundBtn->color();
+  c.setAlpha(boxBackgroundTransparency->value());
+  app->setLegendDefaultSettings(backgroundBox->currentIndex(), selectedFont,
+                                colorBtn->color(), c);
 }
 
-void TextDialog::accept()
-{
-	apply();
-	close();
+void TextDialog::accept() {
+  apply();
+  close();
 }
 
-int TextDialog::alignment()
-{
-	int align=-1;
-	switch (alignmentBox->currentIndex())
-	{
-		case 0:
-			align = Qt::AlignHCenter;
-			break;
-
-		case 1:
-			align = Qt::AlignLeft;
-			break;
-
-		case 2:
-			align = Qt::AlignRight;
-			break;
-	}
-	return align;
+int TextDialog::alignment() {
+  int align = -1;
+  switch (alignmentBox->currentIndex()) {
+  case 0:
+    align = Qt::AlignHCenter;
+    break;
+
+  case 1:
+    align = Qt::AlignLeft;
+    break;
+
+  case 2:
+    align = Qt::AlignRight;
+    break;
+  }
+  return align;
 }
 
-void TextDialog::setAlignment(int align)
-{
-	switch(align)
-	{
-		case Qt::AlignHCenter:
-			alignmentBox->setCurrentIndex(0);
-			break;
-		case Qt::AlignLeft:
-			alignmentBox->setCurrentIndex(1);
-			break;
-		case Qt::AlignRight:
-			alignmentBox->setCurrentIndex(2);
-			break;
-	}
+void TextDialog::setAlignment(int align) {
+  switch (align) {
+  case Qt::AlignHCenter:
+    alignmentBox->setCurrentIndex(0);
+    break;
+  case Qt::AlignLeft:
+    alignmentBox->setCurrentIndex(1);
+    break;
+  case Qt::AlignRight:
+    alignmentBox->setCurrentIndex(2);
+    break;
+  }
 }
 
-void TextDialog::customFont()
-{
-	bool okF;
-	QFont fnt = QFontDialog::getFont( &okF, selectedFont, this);
-	if (okF && fnt != selectedFont)
-		selectedFont = fnt;
+void TextDialog::customFont() {
+  bool okF;
+  QFont fnt = QFontDialog::getFont(&okF, selectedFont, this);
+  if (okF && fnt != selectedFont)
+    selectedFont = fnt;
 }
 
-void TextDialog::setText(const QString & t)
-{
-	QTextCursor cursor = textEditBox->textCursor();
-	// select the whole (old) text
-	cursor.movePosition(QTextCursor::Start);
-	cursor.movePosition(QTextCursor::End,QTextCursor::KeepAnchor);
-	// replace old text
-	cursor.insertText(t);
-	// select the whole (new) text
-	cursor.movePosition(QTextCursor::Start);
-	cursor.movePosition(QTextCursor::End,QTextCursor::KeepAnchor);
-	// this line makes the selection visible to the user
-	// (the 2 lines above only change the selection in the
-	// underlying QTextDocument)
-	textEditBox->setTextCursor(cursor);
-	// give focus back to text edit
-	textEditBox->setFocus();
+void TextDialog::setText(const QString &t) {
+  QTextCursor cursor = textEditBox->textCursor();
+  // select the whole (old) text
+  cursor.movePosition(QTextCursor::Start);
+  cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
+  // replace old text
+  cursor.insertText(t);
+  // select the whole (new) text
+  cursor.movePosition(QTextCursor::Start);
+  cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
+  // this line makes the selection visible to the user
+  // (the 2 lines above only change the selection in the
+  // underlying QTextDocument)
+  textEditBox->setTextCursor(cursor);
+  // give focus back to text edit
+  textEditBox->setFocus();
 }
 
-void TextDialog::updateTransparency(int alpha)
-{
-backgroundBtn->setEnabled(alpha);
+void TextDialog::updateTransparency(int alpha) {
+  backgroundBtn->setEnabled(alpha);
 }
diff --git a/MantidPlot/src/TextDialog.h b/MantidPlot/src/TextDialog.h
index b25cfe1a934c53494bff8b32c58de4975e3aafd9..55e892b544b8e02e254742b83823dc7991bb690f 100644
--- a/MantidPlot/src/TextDialog.h
+++ b/MantidPlot/src/TextDialog.h
@@ -46,79 +46,78 @@ class QwtScaleWidget;
 #include "TextFormatButtons.h"
 
 //! Options dialog for text labels/axes labels
-class TextDialog : public QDialog
-{
-	Q_OBJECT
+class TextDialog : public QDialog {
+  Q_OBJECT
 
 public:
-	//! Label types
-	enum TextType{
-		TextMarker, /**< normal text label */
-		AxisTitle,   /**< axis label */
-		LayerTitle
-	};
-
-	//! Constructor
-	/**
-	 * @param type :: text type (TextMarker | AxisTitle)
-	 * @param parent :: parent widget
-	 * @param fl :: window flags
-	 */
-	TextDialog(TextType type, QWidget* parent = 0, Qt::WFlags fl = 0 );
-
-	//! Return axis label alignment
-	/**
-	 * \sa setAlignment()
-	 */
-	int alignment();
+  //! Label types
+  enum TextType {
+    TextMarker, /**< normal text label */
+    AxisTitle,  /**< axis label */
+    LayerTitle
+  };
+
+  //! Constructor
+  /**
+   * @param type :: text type (TextMarker | AxisTitle)
+   * @param parent :: parent widget
+   * @param fl :: window flags
+   */
+  TextDialog(TextType type, QWidget *parent = 0, Qt::WFlags fl = 0);
+
+  //! Return axis label alignment
+  /**
+   * \sa setAlignment()
+   */
+  int alignment();
 
 public slots:
-	//! Set the contents of the text editor box
-	void setText(const QString & t);
-	//! Set axis label alignment
-	/**
-	 * @param align :: alignment (can be -1 for invalid,
-	 *  Qt::AlignHCenter, Qt::AlignLeft, or Qt::AlignRight)
-	 */
-	void setAlignment(int align);
-	void setGraph(Graph *g);
-	void setLegendWidget(LegendWidget *);
+  //! Set the contents of the text editor box
+  void setText(const QString &t);
+  //! Set axis label alignment
+  /**
+   * @param align :: alignment (can be -1 for invalid,
+   *  Qt::AlignHCenter, Qt::AlignLeft, or Qt::AlignRight)
+   */
+  void setAlignment(int align);
+  void setGraph(Graph *g);
+  void setLegendWidget(LegendWidget *);
 
 private slots:
-	//! Let the user select another font
-	void customFont();
-	//! Accept changes and close dialog
-        void accept() override;
-        //! Apply changes
-	void apply();
-	void setDefaultValues();
+  //! Let the user select another font
+  void customFont();
+  //! Accept changes and close dialog
+  void accept() override;
+  //! Apply changes
+  void apply();
+  void setDefaultValues();
 
-	void updateTransparency(int alpha);
+  void updateTransparency(int alpha);
 
 protected:
-	void formatAllLabels();
-
-	//! current font
-	QFont selectedFont;
-	TextType textType;
-
-	ColorButton *colorBtn, *backgroundBtn;
-	QPushButton *buttonFont;
-	QComboBox *backgroundBox;
-	QPushButton *buttonOk;
-	QPushButton *buttonCancel;
-	QPushButton *buttonApply;
-	QPushButton *buttonDefault;
-	QTextEdit *textEditBox;
-	QGroupBox *groupBox1;
-	QComboBox *alignmentBox;
-	TextFormatButtons *formatButtons;
-	QSpinBox *boxBackgroundTransparency;
-	QCheckBox *boxApplyToAll;
-
-	LegendWidget *d_legend;
-	Graph *d_graph;
-	QwtScaleWidget *d_scale;
+  void formatAllLabels();
+
+  //! current font
+  QFont selectedFont;
+  TextType textType;
+
+  ColorButton *colorBtn, *backgroundBtn;
+  QPushButton *buttonFont;
+  QComboBox *backgroundBox;
+  QPushButton *buttonOk;
+  QPushButton *buttonCancel;
+  QPushButton *buttonApply;
+  QPushButton *buttonDefault;
+  QTextEdit *textEditBox;
+  QGroupBox *groupBox1;
+  QComboBox *alignmentBox;
+  TextFormatButtons *formatButtons;
+  QSpinBox *boxBackgroundTransparency;
+  QCheckBox *boxApplyToAll;
+
+  LegendWidget *d_legend;
+  Graph *d_graph;
+  QwtScaleWidget *d_scale;
 };
 
 #endif // TEXTDLG_H
diff --git a/MantidPlot/src/TextEditor.cpp b/MantidPlot/src/TextEditor.cpp
index ce710933ac60cc162da999bed0fa7626d3d9f19e..eb041848909ffe670fd79f309a8994ab20c70d83 100644
--- a/MantidPlot/src/TextEditor.cpp
+++ b/MantidPlot/src/TextEditor.cpp
@@ -36,99 +36,97 @@
 #include <qwt_text_label.h>
 #include <qwt_scale_widget.h>
 
-TextEditor::TextEditor(Graph *g): QTextEdit(g), d_target(NULL)
-{
-	setAttribute(Qt::WA_DeleteOnClose);
-	setFrameShadow(QFrame::Plain);
-	setFrameShape(QFrame::Box);
-	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-	setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-
-	QPalette palette = this->palette();
-	palette.setColor(QPalette::Active, QPalette::WindowText, Qt::blue);
-	palette.setColor(QPalette::Active, QPalette::Base, Qt::white);
-	setPalette(palette);
-
-	QString text;
-	if (g->selectedText()){
-		d_target = g->selectedText();
-		setGeometry(d_target->geometry());
-    auto legend = dynamic_cast<LegendWidget*>(d_target);
-		text = legend ? legend->text() : "";
-		d_target->hide();
-	} else if (g->titleSelected()){
-		d_target = g->plotWidget()->titleLabel();
-		QwtText t = g->plotWidget()->title();
-		text = t.text();
-		setAlignment((Qt::Alignment)t.renderFlags());
-		setGeometry(d_target->geometry());
-	} else if (g->selectedScale()){
-		d_target = g->selectedScale();
-		QwtScaleWidget *scale = (QwtScaleWidget*)d_target;
-		QwtText t = scale->title();
-		text = t.text();
-		setAlignment((Qt::Alignment)t.renderFlags());
-
-		QRect rect = g->axisTitleRect(scale);
-		if (scale->alignment() == QwtScaleDraw::BottomScale ||
-			scale->alignment() == QwtScaleDraw::TopScale){
-			resize(rect.size());
-			move(QPoint(d_target->x() + rect.x(), d_target->y() + rect.y()));
-		} else {
-			resize(QSize(rect.height(), rect.width()));
-			if (scale->alignment() == QwtScaleDraw::LeftScale)
-                move(QPoint(d_target->x() + rect.x(), d_target->y() + rect.y() + rect.height()/2));
-            else if (scale->alignment() == QwtScaleDraw::RightScale)
-                move(QPoint(d_target->x() - rect.height(), d_target->y() + rect.y() + rect.height()/2));
-
-			t.setText(" ");
-			t.setBackgroundPen(QPen(Qt::NoPen));
-			scale->setTitle(t);
-		}
-	}
-
-	QTextCursor cursor = textCursor();
-	cursor.insertText(text);
-	d_initial_text = text;
-
-	show();
-	setFocus();
-}
+TextEditor::TextEditor(Graph *g) : QTextEdit(g), d_target(NULL) {
+  setAttribute(Qt::WA_DeleteOnClose);
+  setFrameShadow(QFrame::Plain);
+  setFrameShape(QFrame::Box);
+  setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+  setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+
+  QPalette palette = this->palette();
+  palette.setColor(QPalette::Active, QPalette::WindowText, Qt::blue);
+  palette.setColor(QPalette::Active, QPalette::Base, Qt::white);
+  setPalette(palette);
+
+  QString text;
+  if (g->selectedText()) {
+    d_target = g->selectedText();
+    setGeometry(d_target->geometry());
+    auto legend = dynamic_cast<LegendWidget *>(d_target);
+    text = legend ? legend->text() : "";
+    d_target->hide();
+  } else if (g->titleSelected()) {
+    d_target = g->plotWidget()->titleLabel();
+    QwtText t = g->plotWidget()->title();
+    text = t.text();
+    setAlignment((Qt::Alignment)t.renderFlags());
+    setGeometry(d_target->geometry());
+  } else if (g->selectedScale()) {
+    d_target = g->selectedScale();
+    QwtScaleWidget *scale = (QwtScaleWidget *)d_target;
+    QwtText t = scale->title();
+    text = t.text();
+    setAlignment((Qt::Alignment)t.renderFlags());
+
+    QRect rect = g->axisTitleRect(scale);
+    if (scale->alignment() == QwtScaleDraw::BottomScale ||
+        scale->alignment() == QwtScaleDraw::TopScale) {
+      resize(rect.size());
+      move(QPoint(d_target->x() + rect.x(), d_target->y() + rect.y()));
+    } else {
+      resize(QSize(rect.height(), rect.width()));
+      if (scale->alignment() == QwtScaleDraw::LeftScale)
+        move(QPoint(d_target->x() + rect.x(),
+                    d_target->y() + rect.y() + rect.height() / 2));
+      else if (scale->alignment() == QwtScaleDraw::RightScale)
+        move(QPoint(d_target->x() - rect.height(),
+                    d_target->y() + rect.y() + rect.height() / 2));
+
+      t.setText(" ");
+      t.setBackgroundPen(QPen(Qt::NoPen));
+      scale->setTitle(t);
+    }
+  }
+
+  QTextCursor cursor = textCursor();
+  cursor.insertText(text);
+  d_initial_text = text;
 
-TextEditor::~TextEditor()
-{
-  emit textEditorDeleted();
+  show();
+  setFocus();
 }
 
-void TextEditor::closeEvent(QCloseEvent *e)
-{
-  if(d_target != NULL)
-  {
+TextEditor::~TextEditor() { emit textEditorDeleted(); }
+
+void TextEditor::closeEvent(QCloseEvent *e) {
+  if (d_target != NULL) {
     Graph *g = dynamic_cast<Graph *>(parent());
     if (g) {
       QString s = QString();
-      if (auto legend = dynamic_cast<LegendWidget*>(d_target)){
+      if (auto legend = dynamic_cast<LegendWidget *>(d_target)) {
         s = toPlainText();
         legend->setText(s);
         d_target->show();
         g->setSelectedText(NULL);
-      } else if (auto pieLabel = dynamic_cast<PieLabel*>(d_target)){
+      } else if (auto pieLabel = dynamic_cast<PieLabel *>(d_target)) {
         s = toPlainText();
         pieLabel->setCustomText(s);
         d_target->show();
         g->setSelectedText(NULL);
-      } else if (QString(d_target->metaObject()->className()) == "QwtTextLabel"){
+      } else if (QString(d_target->metaObject()->className()) ==
+                 "QwtTextLabel") {
         QwtText title = g->plotWidget()->title();
         s = toPlainText();
-        if(s.isEmpty())
+        if (s.isEmpty())
           s = " ";
-        title.setText(s);			
+        title.setText(s);
         g->plotWidget()->setTitle(title);
-      } else if (QString(d_target->metaObject()->className()) == "QwtScaleWidget"){
-        QwtScaleWidget *scale = (QwtScaleWidget*)d_target;
+      } else if (QString(d_target->metaObject()->className()) ==
+                 "QwtScaleWidget") {
+        QwtScaleWidget *scale = (QwtScaleWidget *)d_target;
         QwtText title = scale->title();
         s = toPlainText();
-        if(s.isEmpty())
+        if (s.isEmpty())
           s = " ";
         title.setText(s);
         scale->setTitle(title);
@@ -143,19 +141,18 @@ void TextEditor::closeEvent(QCloseEvent *e)
   e->accept();
 }
 
-void TextEditor::formatText(const QString& prefix, const QString& postfix)
-{
-	QTextCursor cursor = textCursor();
-	QString markedText = cursor.selectedText();
-	cursor.insertText(prefix + markedText + postfix);
-	if(markedText.isEmpty()){
-		cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, postfix.size());
-		setTextCursor(cursor);
-	}
-	setFocus();
+void TextEditor::formatText(const QString &prefix, const QString &postfix) {
+  QTextCursor cursor = textCursor();
+  QString markedText = cursor.selectedText();
+  cursor.insertText(prefix + markedText + postfix);
+  if (markedText.isEmpty()) {
+    cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor,
+                        postfix.size());
+    setTextCursor(cursor);
+  }
+  setFocus();
 }
 
-void TextEditor::addSymbol(const QString& letter)
-{
-	textCursor().insertText(letter);
+void TextEditor::addSymbol(const QString &letter) {
+  textCursor().insertText(letter);
 }
diff --git a/MantidPlot/src/TextEditor.h b/MantidPlot/src/TextEditor.h
index 6e34ea641e37554d206d1904f969e70729f07733..88e284a0876bef80b919a8e0f9f401ba1acbe3f3 100644
--- a/MantidPlot/src/TextEditor.h
+++ b/MantidPlot/src/TextEditor.h
@@ -34,24 +34,23 @@
 
 class Graph;
 
-class TextEditor: public QTextEdit
-{
-	Q_OBJECT
+class TextEditor : public QTextEdit {
+  Q_OBJECT
 
 public:
   explicit TextEditor(Graph *g);
   ~TextEditor() override;
-    void formatText(const QString & prefix, const QString & postfix);
+  void formatText(const QString &prefix, const QString &postfix);
 
 signals:
-    void textEditorDeleted();
+  void textEditorDeleted();
 public slots:
-    void addSymbol(const QString & letter);
+  void addSymbol(const QString &letter);
 
 private:
   void closeEvent(QCloseEvent *e) override;
-        QString d_initial_text;
-	QWidget *d_target;
+  QString d_initial_text;
+  QWidget *d_target;
 };
 
 #endif
diff --git a/MantidPlot/src/TextFileIO.cpp b/MantidPlot/src/TextFileIO.cpp
index c1f6c4094bc9d69df623e23a955b38af4663ff94..48a221a59613aebbe038c35294e3d52a6742659f 100644
--- a/MantidPlot/src/TextFileIO.cpp
+++ b/MantidPlot/src/TextFileIO.cpp
@@ -12,29 +12,25 @@
 /**
  * Construct an object with a list of file filters
  */
-TextFileIO::TextFileIO(QStringList fileFilters) : m_filters(fileFilters)
-{
-
-}
+TextFileIO::TextFileIO(QStringList fileFilters) : m_filters(fileFilters) {}
 
 /**
  * Save to a file
  * @param filename An optional filename
  * @return True if the save was successful, false otherwise
  */
-bool TextFileIO::save(const QString & txt, const QString & filename) const
-{
+bool TextFileIO::save(const QString &txt, const QString &filename) const {
   QString saved = filename;
-  if(saved.isEmpty())
-  {
+  if (saved.isEmpty()) {
     saved = askWhereToSave();
   }
-  if(saved.isEmpty()) return true; //cancelled
+  if (saved.isEmpty())
+    return true; // cancelled
 
   QFile file(saved);
-  if( !file.open(QIODevice::WriteOnly) )
-  {
-    QMessageBox::critical(NULL, "MantidPlot - File error",
+  if (!file.open(QIODevice::WriteOnly)) {
+    QMessageBox::critical(
+        NULL, "MantidPlot - File error",
         QString("Could not open file \"%1\" for writing.").arg(saved));
     return false;
   }
@@ -48,18 +44,18 @@ bool TextFileIO::save(const QString & txt, const QString & filename) const
 }
 
 /// Open a save dialog
-QString TextFileIO::askWhereToSave() const
-{
+QString TextFileIO::askWhereToSave() const {
   QString selectedFilter;
   QString filter = m_filters.join(";;");
-  QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(NULL, "MantidPlot - Save", "",filter, &selectedFilter);
-  if( filename.isEmpty() ) return QString();
-  if( QFileInfo(filename).suffix().isEmpty() )
-  {
-    QString ext = selectedFilter.section('(',1).section(' ', 0, 0);
-    ext.remove(0,1);
-    if( ext != ")" ) filename += ext;
+  QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(
+      NULL, "MantidPlot - Save", "", filter, &selectedFilter);
+  if (filename.isEmpty())
+    return QString();
+  if (QFileInfo(filename).suffix().isEmpty()) {
+    QString ext = selectedFilter.section('(', 1).section(' ', 0, 0);
+    ext.remove(0, 1);
+    if (ext != ")")
+      filename += ext;
   }
   return filename;
-
 }
diff --git a/MantidPlot/src/TextFileIO.h b/MantidPlot/src/TextFileIO.h
index 6cd7b77e793d6f9e147783f9d5c7b9aea04d2295..b9702e1eafe94001abecdf159858dc156f6823fb 100644
--- a/MantidPlot/src/TextFileIO.h
+++ b/MantidPlot/src/TextFileIO.h
@@ -8,14 +8,13 @@
  * Defines a static class for simple text file
  * I/O.
  */
-class TextFileIO
-{
+class TextFileIO {
 public:
   /// Construct the object with a list of file filters
   explicit TextFileIO(QStringList fileFilters = QStringList());
 
   /// Save to a file
-  bool save(const QString & txt, const QString & filename) const;
+  bool save(const QString &txt, const QString &filename) const;
 
 private:
   /// Open a save dialog
@@ -24,5 +23,4 @@ private:
   const QStringList m_filters;
 };
 
-
 #endif /* TEXTFILEIO_H_ */
diff --git a/MantidPlot/src/TiledWindow.cpp b/MantidPlot/src/TiledWindow.cpp
index 1890ef4e02f4dbd7abcc05a111e39f677bdd9af0..7f1732c09d975afcea326b47148f3072a7360af0 100644
--- a/MantidPlot/src/TiledWindow.cpp
+++ b/MantidPlot/src/TiledWindow.cpp
@@ -28,40 +28,32 @@ const int acceptDropWidth(5);
 /**
  * Constructor.
  */
-Tile::Tile(QWidget *parent):
-  QFrame(parent),
-  m_tiledWindow(parent),
-  m_widget(NULL),
-  m_selected(false),
-  m_acceptDrop(false)
-{
+Tile::Tile(QWidget *parent)
+    : QFrame(parent), m_tiledWindow(parent), m_widget(NULL), m_selected(false),
+      m_acceptDrop(false) {
   m_layout = new QVBoxLayout(this);
-  m_layout->setContentsMargins(5,5,5,5);
+  m_layout->setContentsMargins(5, 5, 5, 5);
 }
 
 /**
  * Destructor.
  */
-Tile::~Tile()
-{
-  //std::cerr << "Tile deleted." << std::endl;
+Tile::~Tile() {
+  // std::cerr << "Tile deleted." << std::endl;
 }
 
 /**
  * Set a widget to this tile.
  * @param w :: A widget to set.
  */
-void Tile::setWidget(MdiSubWindow *w)
-{
-  if (w == NULL)
-  {
+void Tile::setWidget(MdiSubWindow *w) {
+  if (w == NULL) {
     removeWidget();
     return;
   }
 
   // widget cannot be replaced
-  if (m_widget)
-  {
+  if (m_widget) {
     throw std::runtime_error("Widget already set");
   }
 
@@ -72,37 +64,31 @@ void Tile::setWidget(MdiSubWindow *w)
 /**
  * Remove attached widget.
  */
-void Tile::removeWidget()
-{
+void Tile::removeWidget() {
   m_layout->takeAt(0);
   // m_widget needs it's parent set or bad things happen
-  m_widget->setParent( m_tiledWindow );
+  m_widget->setParent(m_tiledWindow);
   m_widget = NULL;
 }
 
 /**
  */
-void Tile::paintEvent(QPaintEvent *ev)
-{
+void Tile::paintEvent(QPaintEvent *ev) {
   QPainter painter(this);
-  QRect bkGround = this->rect().adjusted(0,0,-1,-1);
-  if ( widget() == NULL )
-  {
+  QRect bkGround = this->rect().adjusted(0, 0, -1, -1);
+  if (widget() == NULL) {
     painter.fillRect(bkGround, QColor("lightGray"));
   }
-  if ( m_acceptDrop )
-  {
+  if (m_acceptDrop) {
     QPen pen(acceptDropColor);
     pen.setWidth(acceptDropWidth);
     painter.setPen(pen);
-    painter.drawRect( bkGround );
-  }
-  else if ( m_selected )
-  {
+    painter.drawRect(bkGround);
+  } else if (m_selected) {
     QPen pen(selectedColor);
     pen.setWidth(selectedWidth);
     painter.setPen(pen);
-    painter.drawRect( bkGround );
+    painter.drawRect(bkGround);
   }
   QFrame::paintEvent(ev);
 }
@@ -110,8 +96,7 @@ void Tile::paintEvent(QPaintEvent *ev)
 /**
  * Make this tile look selected or deselected: change the border colour.
  */
-void Tile::makeSelected(bool yes)
-{
+void Tile::makeSelected(bool yes) {
   m_selected = yes;
   update();
 }
@@ -120,107 +105,102 @@ void Tile::makeSelected(bool yes)
  * Make this tile show that it accepts widget drops or not by changing
  * border width and colour.
  */
-void Tile::makeAcceptDrop(bool yes)
-{
+void Tile::makeAcceptDrop(bool yes) {
   m_acceptDrop = yes;
   update();
 }
 
 namespace {
 
-  /// Marker position relative to the tile.
-  enum Position {Left = 0, Right = 1};
+/// Marker position relative to the tile.
+enum Position { Left = 0, Right = 1 };
+
+/**
+ * The inner widget of the QScrollArea. The subclass is needed to draw
+ * the insertion markers.
+ */
+class InnerWidget : public QWidget {
+public:
+  /// Constructor
+  explicit InnerWidget(QWidget *parent) : QWidget(parent), m_draw(false) {}
 
   /**
-   * The inner widget of the QScrollArea. The subclass is needed to draw
-   * the insertion markers.
+   * Work out where to put the marker.
+   * @param tile :: A tile near which to draw the marker.
+   * @param pos :: Cursor position in tile's coordinates.
    */
-  class InnerWidget: public QWidget
-  {
-  public:
-    /// Constructor
-    explicit InnerWidget(QWidget *parent) : QWidget(parent), m_draw(false) {}
-
-    /**
-     * Work out where to put the marker.
-     * @param tile :: A tile near which to draw the marker.
-     * @param pos :: Cursor position in tile's coordinates.
-     */
-    Position getMarkerPosition(QWidget *tile, const QPoint& pos) 
-    {
-      int left = pos.x();
-      int right = tile->width() - left;
-      int dist[2] = {left, right};
-      auto minit = std::min_element( dist, dist + 2 );
-      size_t i = static_cast<size_t>( std::distance( dist, minit ) );
-      return static_cast<Position>(i);
-    }
-
-    /**
-     * Update the InnerWidget to show a marker.
-     * @param tile :: A tile near which to draw the marker.
-     * @param pos :: Cursor position in tile's coordinates.
-     */
-    void showInsertMarker(QWidget *tile, const QPoint& pos) 
-    {
-
-      Position markPosition = getMarkerPosition( tile, pos );
-      QPoint dp = tile->mapTo( this, QPoint() );
-      QRect trect = tile->rect().translated( dp );
-        
-      QPoint x0, x1;
-      switch (markPosition) {
-      case(Left):
-        x0 = trect.bottomLeft();
-        x1 = trect.topLeft();
-        break;
-      case(Right):
-      default:
-        x0 = trect.bottomRight();
-        x1 = trect.topRight();
-        break;
-      }
-      m_x0 = x0; m_x1 = x1;
-      m_draw = true;
-      update();
-    }
+  Position getMarkerPosition(QWidget *tile, const QPoint &pos) {
+    int left = pos.x();
+    int right = tile->width() - left;
+    int dist[2] = {left, right};
+    auto minit = std::min_element(dist, dist + 2);
+    size_t i = static_cast<size_t>(std::distance(dist, minit));
+    return static_cast<Position>(i);
+  }
 
-    /// Clear the marker.
-    void clearMarker() 
-    {
-      m_draw = false;
-      update();
+  /**
+   * Update the InnerWidget to show a marker.
+   * @param tile :: A tile near which to draw the marker.
+   * @param pos :: Cursor position in tile's coordinates.
+   */
+  void showInsertMarker(QWidget *tile, const QPoint &pos) {
+
+    Position markPosition = getMarkerPosition(tile, pos);
+    QPoint dp = tile->mapTo(this, QPoint());
+    QRect trect = tile->rect().translated(dp);
+
+    QPoint x0, x1;
+    switch (markPosition) {
+    case (Left):
+      x0 = trect.bottomLeft();
+      x1 = trect.topLeft();
+      break;
+    case (Right):
+    default:
+      x0 = trect.bottomRight();
+      x1 = trect.topRight();
+      break;
     }
-  protected:
-
-    /// Paint event handler
-    void paintEvent(QPaintEvent *) override {
-      QPainter painter(this);
-      painter.fillRect( this->rect().adjusted(0,0,-1,-1), QColor("white") );
-      if ( m_draw )
-      {
-        QPen pen( acceptDropColor );
-        pen.setWidth( acceptDropWidth );
-        painter.setPen( pen );
-        painter.drawLine( m_x0, m_x1 );
-      }
+    m_x0 = x0;
+    m_x1 = x1;
+    m_draw = true;
+    update();
+  }
+
+  /// Clear the marker.
+  void clearMarker() {
+    m_draw = false;
+    update();
+  }
+
+protected:
+  /// Paint event handler
+  void paintEvent(QPaintEvent *) override {
+    QPainter painter(this);
+    painter.fillRect(this->rect().adjusted(0, 0, -1, -1), QColor("white"));
+    if (m_draw) {
+      QPen pen(acceptDropColor);
+      pen.setWidth(acceptDropWidth);
+      painter.setPen(pen);
+      painter.drawLine(m_x0, m_x1);
     }
-  private:
-    /// Define position of the marker
-    QPoint m_x0, m_x1;
-    /// Drawing flag.
-    bool m_draw;
-  };
-
-  /// Cast a widget to InnerWidget
-  InnerWidget *getInnerWidget( QWidget *w )
-  {
-      InnerWidget *innerWidget = dynamic_cast<InnerWidget*>( w );
-      if ( !innerWidget )
-        throw std::logic_error("Inner widget of TiledWindow is supposed to be an InnerWidget");
-      return innerWidget;
   }
 
+private:
+  /// Define position of the marker
+  QPoint m_x0, m_x1;
+  /// Drawing flag.
+  bool m_draw;
+};
+
+/// Cast a widget to InnerWidget
+InnerWidget *getInnerWidget(QWidget *w) {
+  InnerWidget *innerWidget = dynamic_cast<InnerWidget *>(w);
+  if (!innerWidget)
+    throw std::logic_error(
+        "Inner widget of TiledWindow is supposed to be an InnerWidget");
+  return innerWidget;
+}
 }
 
 /**
@@ -230,18 +210,17 @@ namespace {
  * @param name :: The name of the window.
  * @param f :: Window flags.
  */
-TiledWindow::TiledWindow(QWidget* parent, 
-                         const QString& label, 
-                         const QString& name, 
-                         int nrows,
-                         int ncols, 
+TiledWindow::TiledWindow(QWidget *parent, const QString &label,
+                         const QString &name, int nrows, int ncols,
                          Qt::WFlags f)
-  : MdiSubWindow(parent, label, name, f),m_scrollArea(NULL),m_layout(NULL),m_buttonPressed(false)
-{
-  connect(this,SIGNAL(dropAtPositionQueued(MdiSubWindow*,QPoint,bool)),this,SLOT(dropAtPosition(MdiSubWindow*,QPoint,bool)),Qt::QueuedConnection);
-  init(nrows,ncols);
-  setGeometry(0,0,500,400);
-  setAcceptDrops( true );
+    : MdiSubWindow(parent, label, name, f), m_scrollArea(NULL), m_layout(NULL),
+      m_buttonPressed(false) {
+  connect(this, SIGNAL(dropAtPositionQueued(MdiSubWindow *, QPoint, bool)),
+          this, SLOT(dropAtPosition(MdiSubWindow *, QPoint, bool)),
+          Qt::QueuedConnection);
+  init(nrows, ncols);
+  setGeometry(0, 0, 500, 400);
+  setAcceptDrops(true);
 }
 
 /**
@@ -249,19 +228,17 @@ TiledWindow::TiledWindow(QWidget* parent,
  * @param nrows :: Number of rows to create.
  * @param ncols :: Number of columns to create.
  */
-void TiledWindow::init(int nrows, int ncols)
-{
-  if ( nrows < 1 )
-  {
-    throw std::invalid_argument("Number of rows in TiledWindow cannot be less then 1.");
+void TiledWindow::init(int nrows, int ncols) {
+  if (nrows < 1) {
+    throw std::invalid_argument(
+        "Number of rows in TiledWindow cannot be less then 1.");
   }
-  if ( ncols < 1 )
-  {
-    throw std::invalid_argument("Number of columns in TiledWindow cannot be less then 1.");
+  if (ncols < 1) {
+    throw std::invalid_argument(
+        "Number of columns in TiledWindow cannot be less then 1.");
   }
-  
-  if ( m_scrollArea )
-  {
+
+  if (m_scrollArea) {
     m_scrollArea->close();
     m_scrollArea->deleteLater();
   }
@@ -272,19 +249,18 @@ void TiledWindow::init(int nrows, int ncols)
   QWidget *innerWidget = new InnerWidget(m_scrollArea);
   m_layout = new QGridLayout(innerWidget);
   m_layout->setMargin(6);
-  m_layout->setColumnMinimumWidth(0,minimumTileWidth);
-  m_layout->setRowMinimumHeight(0,minimumTileHeight);
+  m_layout->setColumnMinimumWidth(0, minimumTileWidth);
+  m_layout->setRowMinimumHeight(0, minimumTileHeight);
   m_layout->addWidget(new Tile(this), nrows - 1, ncols - 1);
-  m_layout->setColumnMinimumWidth(0,minimumTileWidth);
-  m_layout->setRowMinimumHeight(0,minimumTileHeight);
-  for(int col = 0; col < ncols; ++col)
-  {
-    m_layout->setColumnStretch( col, 1 );
+  m_layout->setColumnMinimumWidth(0, minimumTileWidth);
+  m_layout->setRowMinimumHeight(0, minimumTileHeight);
+  for (int col = 0; col < ncols; ++col) {
+    m_layout->setColumnStretch(col, 1);
   }
 
   m_scrollArea->setWidget(innerWidget);
-  this->setWidget( NULL );
-  this->setWidget( m_scrollArea );
+  this->setWidget(NULL);
+  this->setWidget(m_scrollArea);
 
   tileEmptyCells();
 }
@@ -293,11 +269,10 @@ void TiledWindow::init(int nrows, int ncols)
  * Save the window info to a string.
  * TODO: not implemented.
  */
-QString TiledWindow::saveToString(const QString &info, bool)
-{
+QString TiledWindow::saveToString(const QString &info, bool) {
   UNUSED_ARG(info);
-  QString s= "<tiled_widget>\n";
-  s+="</tiled_widget>\n";
+  QString s = "<tiled_widget>\n";
+  s += "</tiled_widget>\n";
   return s;
 }
 
@@ -305,52 +280,37 @@ QString TiledWindow::saveToString(const QString &info, bool)
  * Restore the window from a string saved by saveToSring method.
  * TODO: not implemented.
  */
-void TiledWindow::restore(const QStringList& data)
-{
-  UNUSED_ARG(data);
-}
+void TiledWindow::restore(const QStringList &data) { UNUSED_ARG(data); }
 
 /**
  * Print the window.
  * TODO: not implemented.
  */
-void TiledWindow::print()
-{
-}
+void TiledWindow::print() {}
 
 /**
  * Get number of rows
  */
-int TiledWindow::rowCount() const
-{
-  return m_layout->rowCount();
-}
+int TiledWindow::rowCount() const { return m_layout->rowCount(); }
 
 /**
  * Get number of columns
  */
-int TiledWindow::columnCount() const
-{
-  return m_layout->columnCount();
-}
+int TiledWindow::columnCount() const { return m_layout->columnCount(); }
 
 /**
  * Remove all widgets.
  */
-void TiledWindow::clear()
-{
+void TiledWindow::clear() {
   clearSelection();
   // remove and close all widgets
   int nrows = rowCount();
   int ncols = columnCount();
-  for(int row = 0; row < nrows; ++row)
-  {
-    for(int col = 0; col < ncols; ++col)
-    {
-      Tile *tile = getTile(row,col);
+  for (int row = 0; row < nrows; ++row) {
+    for (int col = 0; col < ncols; ++col) {
+      Tile *tile = getTile(row, col);
       MdiSubWindow *widget = tile->widget();
-      if ( widget != NULL )
-      {
+      if (widget != NULL) {
         tile->removeWidget();
         widget->close();
         widget->deleteLater();
@@ -358,18 +318,17 @@ void TiledWindow::clear()
     }
   }
   // re-init the window with a single tile
-  init(1,1);
+  init(1, 1);
 }
 
 /**
  * Re-arrange the tiles according to a new layout shape.
  * @param newColumnCount :: A new number of columns in the layout.
  */
-void TiledWindow::reshape(int newColumnCount)
-{
-  if ( newColumnCount < 1 )
-  {
-    throw std::invalid_argument("Number of columns in a TiledWindow cannot be less than 1.");
+void TiledWindow::reshape(int newColumnCount) {
+  if (newColumnCount < 1) {
+    throw std::invalid_argument(
+        "Number of columns in a TiledWindow cannot be less than 1.");
   }
 
   clearSelection();
@@ -378,47 +337,43 @@ void TiledWindow::reshape(int newColumnCount)
   int ncols = columnCount();
 
   // remove all widgets and store their pointers
-  QList<MdiSubWindow*> widgets;
-  for(int row = 0; row < nrows; ++row)
-  {
-    for(int col = 0; col < ncols; ++col)
-    {
-      Tile *tile = getTile(row,col);
+  QList<MdiSubWindow *> widgets;
+  for (int row = 0; row < nrows; ++row) {
+    for (int col = 0; col < ncols; ++col) {
+      Tile *tile = getTile(row, col);
       MdiSubWindow *widget = tile->widget();
-      if ( widget != NULL )
-      {
+      if (widget != NULL) {
         tile->removeWidget();
-        widgets.append( widget );
+        widgets.append(widget);
       }
     }
   }
 
   int nWidgets = widgets.size();
-  if ( nWidgets < newColumnCount )
-  {
+  if (nWidgets < newColumnCount) {
     newColumnCount = nWidgets;
   }
 
-  if ( newColumnCount == 0 ) return;
+  if (newColumnCount == 0)
+    return;
 
   // clear the layout
-  init(1,1);
+  init(1, 1);
   // make sure new dimensions will fit all widgets
   int newRowCount = nWidgets / newColumnCount;
-  if ( newRowCount * newColumnCount != nWidgets ) 
-  {
+  if (newRowCount * newColumnCount != nWidgets) {
     newRowCount += 1;
   }
   // set up the new layout by putting in an empty tile at the top-right corner
-  // m_layout now knows its rowCount and columnCount and calcTilePosition can be used
+  // m_layout now knows its rowCount and columnCount and calcTilePosition can be
+  // used
   Tile *tile = getOrAddTile(newRowCount - 1, newColumnCount - 1);
-  (void) tile;
+  (void)tile;
   // re-insert the widgets
-  for(int i = 0; i < nWidgets; ++i)
-  {
+  for (int i = 0; i < nWidgets; ++i) {
     int row(0), col(0);
-    calcTilePosition( i, row, col );
-    addWidget( widgets[i], row, col );
+    calcTilePosition(i, row, col);
+    addWidget(widgets[i], row, col);
   }
 }
 
@@ -427,40 +382,38 @@ void TiledWindow::reshape(int newColumnCount)
  * @param row :: The row of the cell.
  * @param col :: The column of the cell.
  */
-Tile *TiledWindow::getOrAddTile(int row, int col)
-{
-  auto item = m_layout->itemAtPosition( row, col );
-  if ( item == NULL )
-  {
-    m_layout->addWidget( new Tile(this), row, col );
+Tile *TiledWindow::getOrAddTile(int row, int col) {
+  auto item = m_layout->itemAtPosition(row, col);
+  if (item == NULL) {
+    m_layout->addWidget(new Tile(this), row, col);
     tileEmptyCells();
-    item = m_layout->itemAtPosition( row, col );
-    if ( item == NULL )
-    {
+    item = m_layout->itemAtPosition(row, col);
+    if (item == NULL) {
       throw std::logic_error("TiledWindow cannot be properly initialized.");
     }
   }
-  Tile *widget = dynamic_cast<Tile*>(item->widget());
-  if ( widget != NULL ) return widget;
+  Tile *widget = dynamic_cast<Tile *>(item->widget());
+  if (widget != NULL)
+    return widget;
 
   throw std::logic_error("TiledWindow wasn't properly initialized.");
 }
 
 /**
- * If a cell contains an Tile return it. If the cell contains a widget of another type
+ * If a cell contains an Tile return it. If the cell contains a widget of
+ * another type
  * throw an exception. If it's empty return fill it with a Tile and return it.
  * @param row :: The row of the cell.
  * @param col :: The column of the cell.
  */
-Tile *TiledWindow::getTile(int row, int col) const
-{
-  auto item = m_layout->itemAtPosition( row, col );
-  if ( item == NULL )
-  {
+Tile *TiledWindow::getTile(int row, int col) const {
+  auto item = m_layout->itemAtPosition(row, col);
+  if (item == NULL) {
     throw std::runtime_error("Tile indices are out of range.");
   }
-  Tile *widget = dynamic_cast<Tile*>(item->widget());
-  if ( widget != NULL ) return widget;
+  Tile *widget = dynamic_cast<Tile *>(item->widget());
+  if (widget != NULL)
+    return widget;
 
   throw std::logic_error("TiledWindow wasn't properly initialized.");
 }
@@ -470,27 +423,22 @@ Tile *TiledWindow::getTile(int row, int col) const
  * @param row :: The row to check.
  * @param col :: The column to check.
  */
-bool TiledWindow::hasWidget(int row, int col) const
-{
-  Tile *tile = getTile(row,col);
+bool TiledWindow::hasWidget(int row, int col) const {
+  Tile *tile = getTile(row, col);
   return tile->widget() != NULL;
 }
 
 /**
  * Tile empty cells with Tiles.
  */
-void TiledWindow::tileEmptyCells()
-{
+void TiledWindow::tileEmptyCells() {
   int nrows = rowCount();
   int ncols = columnCount();
-  for(int row = 0; row < nrows; ++row)
-  {
-    for(int col = 0; col < ncols; ++col)
-    {
-      QLayoutItem *item = m_layout->itemAtPosition( row, col );
-      if ( item == NULL )
-      {
-        m_layout->addWidget( new Tile(this), row, col );
+  for (int row = 0; row < nrows; ++row) {
+    for (int col = 0; col < ncols; ++col) {
+      QLayoutItem *item = m_layout->itemAtPosition(row, col);
+      if (item == NULL) {
+        m_layout->addWidget(new Tile(this), row, col);
       }
     }
   }
@@ -498,38 +446,38 @@ void TiledWindow::tileEmptyCells()
 
 /**
  * Add a new sub-window at a given position in the layout.
- * The row and column indices do not have to be within the current shape - 
+ * The row and column indices do not have to be within the current shape -
  * it will change accordingly.
  * @param widget :: An MdiSubWindow to add.
  * @param row :: A row index at which to place the new tile.
  * @param col :: A column index at which to place the new tile.
  */
-void TiledWindow::addWidget(MdiSubWindow *widget, int row, int col)
-{
-  try
-  {
-    Tile *tile = getOrAddTile( row, col );
+void TiledWindow::addWidget(MdiSubWindow *widget, int row, int col) {
+  try {
+    Tile *tile = getOrAddTile(row, col);
     // prepare the cell
-    m_layout->setColumnMinimumWidth(col,minimumTileWidth);
-    m_layout->setRowMinimumHeight(row,minimumTileHeight);
-    m_layout->setColumnStretch(col,1);
+    m_layout->setColumnMinimumWidth(col, minimumTileWidth);
+    m_layout->setRowMinimumHeight(row, minimumTileHeight);
+    m_layout->setColumnStretch(col, 1);
     // detach the widget from ApplicationWindow
     widget->detach();
     // widget must have it's parent
     widget->setParent(this);
     // disable mouse events
-    widget->setAttribute(Qt::WA_TransparentForMouseEvents,true);
+    widget->setAttribute(Qt::WA_TransparentForMouseEvents, true);
     // attach it to this window
     tile->setWidget(widget);
-    connect( widget, SIGNAL(detachFromParent(MdiSubWindow*)), this, SLOT(removeWidget(MdiSubWindow*)));
-    connect( widget, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(removeWidget(MdiSubWindow*)));
+    connect(widget, SIGNAL(detachFromParent(MdiSubWindow *)), this,
+            SLOT(removeWidget(MdiSubWindow *)));
+    connect(widget, SIGNAL(closedWindow(MdiSubWindow *)), this,
+            SLOT(removeWidget(MdiSubWindow *)));
     // fill possible empty spaces with Tiles
     tileEmptyCells();
-  }
-  catch(std::invalid_argument& ex)
-  {
-    QMessageBox::critical(this,"MantidPlot- Error","Cannot add a widget to a TiledWindow:\n\n" + QString::fromStdString(ex.what()));
-    sendWidgetTo( widget, Default );
+  } catch (std::invalid_argument &ex) {
+    QMessageBox::critical(this, "MantidPlot- Error",
+                          "Cannot add a widget to a TiledWindow:\n\n" +
+                              QString::fromStdString(ex.what()));
+    sendWidgetTo(widget, Default);
   }
 }
 
@@ -539,68 +487,64 @@ void TiledWindow::addWidget(MdiSubWindow *widget, int row, int col)
  * @param row :: A row index at which to place the new tile.
  * @param col :: A column index at which to place the new tile.
  */
-void TiledWindow::insertWidget(MdiSubWindow *widget, int row, int col)
-{
-  int index = calcFlatIndex( row, col );
+void TiledWindow::insertWidget(MdiSubWindow *widget, int row, int col) {
+  int index = calcFlatIndex(row, col);
   int lastRow = rowCount() - 1;
   int lastCol = columnCount() - 1;
   // if the last tile has a widget append a row
-  if ( getWidget( lastRow, lastCol ) != NULL )
-  {
+  if (getWidget(lastRow, lastCol) != NULL) {
     ++lastRow;
-    Tile *tile = getOrAddTile( lastRow, lastCol );
-    (void) tile;
+    Tile *tile = getOrAddTile(lastRow, lastCol);
+    (void)tile;
   }
 
   // shift widgets towards the bottom
-  int lastIndex = calcFlatIndex( lastRow, lastCol );
+  int lastIndex = calcFlatIndex(lastRow, lastCol);
   int rowTo(0), colTo(0), rowFrom(0), colFrom(0);
-  for(int i = lastIndex; i > index; --i)
-  {
-    calcTilePosition( i, rowTo, colTo );
-    calcTilePosition( i - 1, rowFrom, colFrom );
-    if ( hasWidget( rowFrom, colFrom ) )
-    {
-      MdiSubWindow *w = removeTile( rowFrom, colFrom );
-      addWidget( w, rowTo, colTo );
+  for (int i = lastIndex; i > index; --i) {
+    calcTilePosition(i, rowTo, colTo);
+    calcTilePosition(i - 1, rowFrom, colFrom);
+    if (hasWidget(rowFrom, colFrom)) {
+      MdiSubWindow *w = removeTile(rowFrom, colFrom);
+      addWidget(w, rowTo, colTo);
     }
   }
-  addWidget( widget, row, col );
+  addWidget(widget, row, col);
 }
 
-
 /**
  * Get a widget at a position in the layout.
  * @param row :: The row of the tile
  * @param col :: The column of the tile
- * @return :: A pointer to the MdiSubWindow at this position or NULL if the tile is empty.
+ * @return :: A pointer to the MdiSubWindow at this position or NULL if the tile
+ * is empty.
  */
-MdiSubWindow *TiledWindow::getWidget(int row, int col) 
-{
-  Tile *tile = getTile(row,col);
+MdiSubWindow *TiledWindow::getWidget(int row, int col) {
+  Tile *tile = getTile(row, col);
   return tile->widget();
 }
 
 /**
  * Make a widget floating or docked.
- * @param w :: A MdiSubWindow. It must be already detached from the tile and ready to become floating or docked.
+ * @param w :: A MdiSubWindow. It must be already detached from the tile and
+ * ready to become floating or docked.
  * @param to :: A wrapper window option: Floating, Docked or Default.
  */
-void TiledWindow::sendWidgetTo(MdiSubWindow *w, TiledWindow::RemoveDestination to)
-{
+void TiledWindow::sendWidgetTo(MdiSubWindow *w,
+                               TiledWindow::RemoveDestination to) {
   w->resizeToDefault();
-  switch (to)
-  {
-  case( Floating ): w->undock(); break;
-  case( Docked ):   w->dock(); break;
-  case( Default ):  
+  switch (to) {
+  case (Floating):
+    w->undock();
+    break;
+  case (Docked):
+    w->dock();
+    break;
+  case (Default):
   default:
-    if ( applicationWindow()->isDefaultFloating( w ) )
-    {
+    if (applicationWindow()->isDefaultFloating(w)) {
       w->undock();
-    }
-    else
-    {
+    } else {
       w->dock();
     }
   }
@@ -611,17 +555,16 @@ void TiledWindow::sendWidgetTo(MdiSubWindow *w, TiledWindow::RemoveDestination t
  * @param row :: The tile's row index.
  * @param col :: The tile's column index.
  */
-void TiledWindow::removeWidgetTo(int row, int col, TiledWindow::RemoveDestination to)
-{
-  try
-  {
-    deselectWidget( row, col );
-    MdiSubWindow *widget = removeTile( row, col );
-    sendWidgetTo( widget, to );
-  }
-  catch(std::runtime_error& ex)
-  {
-    QMessageBox::critical(this,"MantidPlot- Error","Cannot remove a widget from a TiledWindow:\n\n" + QString::fromStdString(ex.what()));
+void TiledWindow::removeWidgetTo(int row, int col,
+                                 TiledWindow::RemoveDestination to) {
+  try {
+    deselectWidget(row, col);
+    MdiSubWindow *widget = removeTile(row, col);
+    sendWidgetTo(widget, to);
+  } catch (std::runtime_error &ex) {
+    QMessageBox::critical(this, "MantidPlot- Error",
+                          "Cannot remove a widget from a TiledWindow:\n\n" +
+                              QString::fromStdString(ex.what()));
   }
 }
 
@@ -630,9 +573,8 @@ void TiledWindow::removeWidgetTo(int row, int col, TiledWindow::RemoveDestinatio
  * @param row :: The tile's row index.
  * @param col :: The tile's column index.
  */
-void TiledWindow::removeWidgetToDocked(int row, int col)
-{
-  removeWidgetTo( row, col, Docked );
+void TiledWindow::removeWidgetToDocked(int row, int col) {
+  removeWidgetTo(row, col, Docked);
 }
 
 /**
@@ -640,9 +582,8 @@ void TiledWindow::removeWidgetToDocked(int row, int col)
  * @param row :: The tile's row index.
  * @param col :: The tile's column index.
  */
-void TiledWindow::removeWidgetToFloating(int row, int col)
-{
-  removeWidgetTo( row, col, Floating );
+void TiledWindow::removeWidgetToFloating(int row, int col) {
+  removeWidgetTo(row, col, Floating);
 }
 
 /**
@@ -651,12 +592,10 @@ void TiledWindow::removeWidgetToFloating(int row, int col)
  * @param col :: The column of a tile to remove.
  * @return :: A pointer to the removed subwindow.
  */
-MdiSubWindow *TiledWindow::removeTile(int row, int col)
-{
-  Tile *tile = getTile( row, col );
-  MdiSubWindow *widget = removeTile( tile );
-  if ( widget == NULL )
-  {
+MdiSubWindow *TiledWindow::removeTile(int row, int col) {
+  Tile *tile = getTile(row, col);
+  MdiSubWindow *widget = removeTile(tile);
+  if (widget == NULL) {
     QString msg = QString("Cell (%1,%2) is empty.").arg(row).arg(col);
     throw std::runtime_error(msg.toStdString());
   }
@@ -668,13 +607,11 @@ MdiSubWindow *TiledWindow::removeTile(int row, int col)
  * @param tile :: A tile to remove.
  * @return :: A pointer to the removed subwindow.
  */
-MdiSubWindow *TiledWindow::removeTile(Tile *tile)
-{
+MdiSubWindow *TiledWindow::removeTile(Tile *tile) {
   MdiSubWindow *widget = tile->widget();
-  if ( widget != NULL )
-  {
+  if (widget != NULL) {
     tile->removeWidget();
-    widget->setAttribute(Qt::WA_TransparentForMouseEvents,false);
+    widget->setAttribute(Qt::WA_TransparentForMouseEvents, false);
     widget->disconnect(this);
   }
   deselectTile(tile);
@@ -685,15 +622,11 @@ MdiSubWindow *TiledWindow::removeTile(Tile *tile)
  * Remove (but don't delete) a widget.
  * @param w :: A widget to remove.
  */
-void TiledWindow::removeWidget(MdiSubWindow *w)
-{
-  for( int row = 0; row < rowCount(); ++row)
-  {
-    for(int col = 0; col < columnCount(); ++col)
-    {
-      if ( getWidget( row, col ) == w )
-      {
-        removeTile(row,col);
+void TiledWindow::removeWidget(MdiSubWindow *w) {
+  for (int row = 0; row < rowCount(); ++row) {
+    for (int col = 0; col < columnCount(); ++col) {
+      if (getWidget(row, col) == w) {
+        removeTile(row, col);
         return;
       }
     }
@@ -705,27 +638,24 @@ void TiledWindow::removeWidget(MdiSubWindow *w)
  * @param pos :: Position of the mouse as returned by QMouseEvent
  * @return :: A pointer to the tile or NULL if clicked on an empty space.
  */
-Tile *TiledWindow::getTileAtMousePos( const QPoint& pos ) 
-{
-  QWidget * w = childAt( pos );
-  auto *tile = dynamic_cast<Tile*>(w);
-  if ( tile ) return tile;
+Tile *TiledWindow::getTileAtMousePos(const QPoint &pos) {
+  QWidget *w = childAt(pos);
+  auto *tile = dynamic_cast<Tile *>(w);
+  if (tile)
+    return tile;
   return NULL;
 }
 
 /**
  * Get a list of all tiles.
  */
-QList<Tile*> TiledWindow::getAllTiles()
-{
-  QList<Tile*> tiles;
+QList<Tile *> TiledWindow::getAllTiles() {
+  QList<Tile *> tiles;
   int nrows = rowCount();
   int ncols = columnCount();
-  for(int row = 0; row < nrows; ++row)
-  {
-    for(int col = 0; col < ncols; ++col)
-    {
-      tiles.append( getTile(row, col) );
+  for (int row = 0; row < nrows; ++row) {
+    for (int col = 0; col < ncols; ++col) {
+      tiles.append(getTile(row, col));
     }
   }
   return tiles;
@@ -734,22 +664,17 @@ QList<Tile*> TiledWindow::getAllTiles()
 /**
  * Mouse press event handler.
  */
-void TiledWindow::mousePressEvent(QMouseEvent *ev)
-{
+void TiledWindow::mousePressEvent(QMouseEvent *ev) {
   clearDrops();
-  auto tile = getTileAtMousePos( ev->pos() );
-  if ( tile == NULL ) return;
-  if ( (ev->modifiers() & Qt::ShiftModifier) != 0 )
-  {
-    addRangeToSelection( tile );
-  }
-  else if ( (ev->modifiers() & Qt::ControlModifier) != 0 )
-  {
-    addToSelection( tile, true );
-  }
-  else if ( !tile->isSelected() )
-  {
-    addToSelection( tile, false );
+  auto tile = getTileAtMousePos(ev->pos());
+  if (tile == NULL)
+    return;
+  if ((ev->modifiers() & Qt::ShiftModifier) != 0) {
+    addRangeToSelection(tile);
+  } else if ((ev->modifiers() & Qt::ControlModifier) != 0) {
+    addToSelection(tile, true);
+  } else if (!tile->isSelected()) {
+    addToSelection(tile, false);
   }
   m_buttonPressed = true;
 }
@@ -757,18 +682,15 @@ void TiledWindow::mousePressEvent(QMouseEvent *ev)
 /**
  * Mouse release event handler.
  */
-void TiledWindow::mouseReleaseEvent(QMouseEvent*)
-{
-  m_buttonPressed = false;
-}
+void TiledWindow::mouseReleaseEvent(QMouseEvent *) { m_buttonPressed = false; }
 
 /**
  * Mouse move event handler.
  */
-void TiledWindow::mouseMoveEvent(QMouseEvent *ev)
-{
-  if ( !m_buttonPressed || !hasSelection() || (ev->pos() - m_dragStartPos).manhattanLength() < QApplication::startDragDistance())
-  {
+void TiledWindow::mouseMoveEvent(QMouseEvent *ev) {
+  if (!m_buttonPressed || !hasSelection() ||
+      (ev->pos() - m_dragStartPos).manhattanLength() <
+          QApplication::startDragDistance()) {
     return;
   }
 
@@ -776,107 +698,97 @@ void TiledWindow::mouseMoveEvent(QMouseEvent *ev)
   QMimeData *mimeData = new QMimeData;
 
   mimeData->setObjectName("TiledWindow");
-  mimeData->setText( name() );
+  mimeData->setText(name());
 
   drag->setMimeData(mimeData);
   Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
-  (void) dropAction;
+  (void)dropAction;
 }
 
 /**
  * Add a tile to the selection.
  * @param tile :: A tile to add.
- * @param append :: If true the tile will be appended to the existing selection. If false 
+ * @param append :: If true the tile will be appended to the existing selection.
+ * If false
  *   any previous selection will be deselected and replaced with tile.
  */
-void TiledWindow::addToSelection(Tile *tile, bool append)
-{
-  if ( tile == NULL ) return;
-  if ( tile->widget() == NULL ) return;
-  if ( append )
-  {
-    if ( deselectTile( tile ) )
-    {
+void TiledWindow::addToSelection(Tile *tile, bool append) {
+  if (tile == NULL)
+    return;
+  if (tile->widget() == NULL)
+    return;
+  if (append) {
+    if (deselectTile(tile)) {
       return;
     }
-  }
-  else
-  {
+  } else {
     clearSelection();
   }
-  m_selection.append( tile );
+  m_selection.append(tile);
   tile->makeSelected(true);
 }
 
 /**
  * Add a range of tiles to the selection. One of the ends of tha range
- * is given by an already selected tile with the lowest flat index (see calcFlatIndex).
+ * is given by an already selected tile with the lowest flat index (see
+ * calcFlatIndex).
  * The other end is the tile in the argument.
  * @param tile :: A new end tile of the range.
  */
-void TiledWindow::addRangeToSelection(Tile *tile)
-{
-  if ( m_selection.isEmpty() )
-  {
-    addToSelection( tile, false );
+void TiledWindow::addRangeToSelection(Tile *tile) {
+  if (m_selection.isEmpty()) {
+    addToSelection(tile, false);
     return;
   }
 
   int ifirst = rowCount() * columnCount();
   int ilast = 0;
-  foreach(Tile *selected, m_selection)
-  {
-    int index = calcFlatIndex( selected );
-    if ( index < ifirst ) ifirst = index;
-    if ( index > ilast ) ilast = index;
+  foreach (Tile *selected, m_selection) {
+    int index = calcFlatIndex(selected);
+    if (index < ifirst)
+      ifirst = index;
+    if (index > ilast)
+      ilast = index;
   }
 
-  int index = calcFlatIndex( tile );
-  if ( index == ilast ) return;
+  int index = calcFlatIndex(tile);
+  if (index == ilast)
+    return;
 
-  if ( index < ifirst )
-  {
+  if (index < ifirst) {
     ilast = ifirst;
     ifirst = index;
-  }
-  else
-  {
+  } else {
     ilast = index;
   }
 
   clearSelection();
-  for(int i = ifirst; i <= ilast; ++i)
-  {
+  for (int i = ifirst; i <= ilast; ++i) {
     int row(0), col(0);
-    calcTilePosition( i, row, col );
-    Tile *tile = getTile( row, col );
-    addToSelection( tile, true );
+    calcTilePosition(i, row, col);
+    Tile *tile = getTile(row, col);
+    addToSelection(tile, true);
   }
 }
 
 /**
  * Clear the selection.
  */
-void TiledWindow::clearSelection()
-{
-  foreach(Tile *tile, m_selection)
-  {
-    tile->makeSelected(false);
-  }
+void TiledWindow::clearSelection() {
+  foreach (Tile *tile, m_selection) { tile->makeSelected(false); }
   m_selection.clear();
 }
 
 /**
- * Deselect a tile. If the tile isn't selected do nothing. 
+ * Deselect a tile. If the tile isn't selected do nothing.
  * @param tile :: A tile to deselect.
- * @return true if the tile was deselected and false if it was not selected before the call.
+ * @return true if the tile was deselected and false if it was not selected
+ * before the call.
  */
-bool TiledWindow::deselectTile(Tile *tile)
-{
-  int index = m_selection.indexOf( tile );
-  if ( index >= 0 )
-  {
-    m_selection.removeAt( index );
+bool TiledWindow::deselectTile(Tile *tile) {
+  int index = m_selection.indexOf(tile);
+  if (index >= 0) {
+    m_selection.removeAt(index);
     tile->makeSelected(false);
     return true;
   }
@@ -886,57 +798,50 @@ bool TiledWindow::deselectTile(Tile *tile)
 /**
  * Check if there are any selected tiles
  */
-bool TiledWindow::hasSelection() const
-{
-  return ! m_selection.isEmpty();
-}
+bool TiledWindow::hasSelection() const { return !m_selection.isEmpty(); }
 
 /**
- * Calculate an index of a tile as if they were in a 1d list of concatenated rows.
+ * Calculate an index of a tile as if they were in a 1d list of concatenated
+ * rows.
  * QLayout::indexOf doesn't work here.
  * @param tile :: A tile to get the index for.
  */
-int TiledWindow::calcFlatIndex(Tile *tile) const
-{
-  int indexInLayout = m_layout->indexOf( tile );
+int TiledWindow::calcFlatIndex(Tile *tile) const {
+  int indexInLayout = m_layout->indexOf(tile);
   int row(0), col(0), rowSpan(1), colSpan(1);
-  m_layout->getItemPosition( indexInLayout, &row, &col, &rowSpan, &colSpan );
-  return calcFlatIndex( row, col );
+  m_layout->getItemPosition(indexInLayout, &row, &col, &rowSpan, &colSpan);
+  return calcFlatIndex(row, col);
 }
 
 /**
- * Calculate an index of a tile as if they were in a 1d list of concatenated rows.
+ * Calculate an index of a tile as if they were in a 1d list of concatenated
+ * rows.
  * QLayout::indexOf doesn't work here.
  * @param row :: The row number of a tile.
  * @param col :: The column number of a tile.
  */
-int TiledWindow::calcFlatIndex(int row, int col) const
-{
+int TiledWindow::calcFlatIndex(int row, int col) const {
   return row * columnCount() + col;
 }
 
 /**
- * Calculate tile's row and column indices given it's flat index as returned 
+ * Calculate tile's row and column indices given it's flat index as returned
  * by calcFlatIndex(...).
  * @param index :: The flat index of a tile.
  * @param row :: A reference to a variable to accept the row index value.
  * @param col :: A reference to a variable to accept the column index value.
  */
-void TiledWindow::calcTilePosition( int index, int &row, int &col ) const
-{
-  if ( index < 0 )
-  {
+void TiledWindow::calcTilePosition(int index, int &row, int &col) const {
+  if (index < 0) {
     throw std::runtime_error("Flat index in TiledWindow is outside range.");
   }
   int ncols = columnCount();
   row = index / ncols;
-  if ( row >= rowCount() )
-  {
+  if (row >= rowCount()) {
     throw std::runtime_error("Flat index in TiledWindow is outside range.");
   }
   col = index - row * ncols;
-  if ( col >= ncols )
-  {
+  if (col >= ncols) {
     throw std::runtime_error("Flat index in TiledWindow is outside range.");
   }
 }
@@ -946,15 +851,13 @@ void TiledWindow::calcTilePosition( int index, int &row, int &col ) const
  * @param row :: A row.
  * @param col :: A column.
  */
-void TiledWindow::selectWidget(int row, int col)
-{
-  try
-  {
-    addToSelection( getTile(row,col), false );
-  }
-  catch(std::runtime_error& ex)
-  {
-    QMessageBox::critical(this,"MantidPlot- Error","Cannot select a widget in TiledWindow:\n\n" + QString::fromStdString(ex.what()));
+void TiledWindow::selectWidget(int row, int col) {
+  try {
+    addToSelection(getTile(row, col), false);
+  } catch (std::runtime_error &ex) {
+    QMessageBox::critical(this, "MantidPlot- Error",
+                          "Cannot select a widget in TiledWindow:\n\n" +
+                              QString::fromStdString(ex.what()));
   }
 }
 
@@ -963,14 +866,11 @@ void TiledWindow::selectWidget(int row, int col)
  * @param row :: A row.
  * @param col :: A column.
  */
-void TiledWindow::deselectWidget(int row, int col)
-{
-  try
-  {
-    deselectTile( getTile(row,col) );
+void TiledWindow::deselectWidget(int row, int col) {
+  try {
+    deselectTile(getTile(row, col));
+  } catch (std::runtime_error &) {
   }
-  catch(std::runtime_error&)
-  {}
 }
 
 /**
@@ -978,15 +878,12 @@ void TiledWindow::deselectWidget(int row, int col)
  * @param row :: A row.
  * @param col :: A column.
  */
-bool TiledWindow::isSelected(int row, int col)
-{
-  try
-  {
-    Tile *tile = getTile(row,col);
+bool TiledWindow::isSelected(int row, int col) {
+  try {
+    Tile *tile = getTile(row, col);
     return m_selection.contains(tile);
+  } catch (std::runtime_error &) {
   }
-  catch(std::runtime_error&)
-  {}
   return false;
 }
 
@@ -997,16 +894,14 @@ bool TiledWindow::isSelected(int row, int col)
  * @param row2 :: Row index of the end of the range.
  * @param col2 :: Column index of the end of the range.
  */
-void TiledWindow::selectRange(int row1, int col1, int row2, int col2)
-{
-  try
-  {
-    addToSelection( getTile(row1,col1), false );
-    addRangeToSelection( getTile(row2,col2) );
-  }
-  catch(std::runtime_error& ex)
-  {
-    QMessageBox::critical(this,"MantidPlot- Error","Cannot select widgets in TiledWindow:\n\n" + QString::fromStdString(ex.what()));
+void TiledWindow::selectRange(int row1, int col1, int row2, int col2) {
+  try {
+    addToSelection(getTile(row1, col1), false);
+    addRangeToSelection(getTile(row2, col2));
+  } catch (std::runtime_error &ex) {
+    QMessageBox::critical(this, "MantidPlot- Error",
+                          "Cannot select widgets in TiledWindow:\n\n" +
+                              QString::fromStdString(ex.what()));
   }
 }
 
@@ -1014,16 +909,13 @@ void TiledWindow::selectRange(int row1, int col1, int row2, int col2)
  * Remove the selection and make its widgets floating or docked
  * @param to :: A wrapper window option: Floating, Docked or Default.
  */
-void TiledWindow::removeSelectionTo(TiledWindow::RemoveDestination to)
-{
-  foreach(Tile *tile, m_selection)
-  {
-    MdiSubWindow *widget = removeTile( tile );
-    if ( widget == NULL )
-    {
+void TiledWindow::removeSelectionTo(TiledWindow::RemoveDestination to) {
+  foreach (Tile *tile, m_selection) {
+    MdiSubWindow *widget = removeTile(tile);
+    if (widget == NULL) {
       throw std::logic_error("TiledWindow: Empty tile is found in slection.");
     }
-    sendWidgetTo( widget, to );
+    sendWidgetTo(widget, to);
   }
   clearSelection();
 }
@@ -1031,76 +923,68 @@ void TiledWindow::removeSelectionTo(TiledWindow::RemoveDestination to)
 /**
  * Remove the selection and make all windows docked.
  */
-void TiledWindow::removeSelectionToDocked()
-{
-  removeSelectionTo( Docked );
-}
+void TiledWindow::removeSelectionToDocked() { removeSelectionTo(Docked); }
 
 /**
  * Remove the selection and make all windows floating.
  */
-void TiledWindow::removeSelectionToFloating()
-{
-  removeSelectionTo( Floating );
-}
+void TiledWindow::removeSelectionToFloating() { removeSelectionTo(Floating); }
 
 /**
  * Remove the selection and put them into separate windows. Each window
  * will be either floating or docked depending on the default setting for
  * a particular MdiSubwindow type.
  */
-void TiledWindow::removeSelectionToDefaultWindowType()
-{
-  removeSelectionTo( Default );
+void TiledWindow::removeSelectionToDefaultWindowType() {
+  removeSelectionTo(Default);
 }
 
 /**
  * Populate a menu with actions.
  * @param menu :: A menu to populate.
  */
-void TiledWindow::populateMenu(QMenu *menu)
-{  
-  QAction *actionToDocked = new QAction("Selection to Docked",menu);
-  connect(actionToDocked,SIGNAL(triggered()),this,SLOT(removeSelectionToDocked()));
-  menu->addAction( actionToDocked );
+void TiledWindow::populateMenu(QMenu *menu) {
+  QAction *actionToDocked = new QAction("Selection to Docked", menu);
+  connect(actionToDocked, SIGNAL(triggered()), this,
+          SLOT(removeSelectionToDocked()));
+  menu->addAction(actionToDocked);
 
-  QAction *actionToFloating = new QAction("Selection to Floating",menu);
-  connect(actionToFloating,SIGNAL(triggered()),this,SLOT(removeSelectionToFloating()));
-  menu->addAction( actionToFloating );
+  QAction *actionToFloating = new QAction("Selection to Floating", menu);
+  connect(actionToFloating, SIGNAL(triggered()), this,
+          SLOT(removeSelectionToFloating()));
+  menu->addAction(actionToFloating);
 
   // reshape actions
   {
     QSignalMapper *reshapeMapper = new QSignalMapper(this);
-    connect(reshapeMapper,SIGNAL(mapped(int)),this,SLOT(reshape(int)));
+    connect(reshapeMapper, SIGNAL(mapped(int)), this, SLOT(reshape(int)));
 
     QActionGroup *reshapeActionGroup = new QActionGroup(this);
     const int nShapes = 9;
-    for( int i = 1; i < nShapes; ++i )
-    {
-      QAction *action = new QAction(QString("%1").arg(i),menu);
+    for (int i = 1; i < nShapes; ++i) {
+      QAction *action = new QAction(QString("%1").arg(i), menu);
       action->setCheckable(true);
-      connect(action,SIGNAL(triggered()),reshapeMapper,SLOT(map()));
-      reshapeMapper->setMapping(action,i);
+      connect(action, SIGNAL(triggered()), reshapeMapper, SLOT(map()));
+      reshapeMapper->setMapping(action, i);
       reshapeActionGroup->addAction(action);
     }
     QMenu *submenu = new QMenu("Reshape");
     submenu->addActions(reshapeActionGroup->actions());
-    menu->addMenu( submenu );
+    menu->addMenu(submenu);
   }
 
   menu->addSeparator();
 
-  QAction *actionClear = new QAction("Clear",menu);
-  connect(actionClear,SIGNAL(triggered()),this,SLOT(clear()));
-  menu->addAction( actionClear );
+  QAction *actionClear = new QAction("Clear", menu);
+  connect(actionClear, SIGNAL(triggered()), this, SLOT(clear()));
+  menu->addAction(actionClear);
 }
 
 /**
  * Check if a Tile can accept drops.
  * @param tile :: A tile to check.
  */
-bool TiledWindow::canAcceptDrops(Tile *tile) const
-{
+bool TiledWindow::canAcceptDrops(Tile *tile) const {
   return tile->widget() == NULL;
 }
 
@@ -1109,33 +993,25 @@ bool TiledWindow::canAcceptDrops(Tile *tile) const
  * given approximate coords.
  *
  * @param pos :: Approx position in pixels where a widget will be dropped.
- * @param global :: Selector of the origin for pos. If true pos is relative to 
- *   the top-left corner of the screen. If false it's in the TiledWindow's coordinates.
+ * @param global :: Selector of the origin for pos. If true pos is relative to
+ *   the top-left corner of the screen. If false it's in the TiledWindow's
+ *coordinates.
  */
-void TiledWindow::showInsertPosition( QPoint pos, bool global )
-{
+void TiledWindow::showInsertPosition(QPoint pos, bool global) {
   clearDrops();
-  if ( global )
-  {
-    pos = mapFromGlobal( pos );
-  }
-  Tile *tile = getTileAtMousePos( pos );
-  if ( tile )
-  {
-    if ( canAcceptDrops(tile) )
-    {
-      tile->makeAcceptDrop( true );
-    }
-    else
-    {
-      InnerWidget *innerWidget = getInnerWidget( m_scrollArea->widget() );
-      pos = tile->mapFrom( this, pos );
-      if ( tile->rect().contains(pos) )
-      {
-        innerWidget->showInsertMarker( tile, pos );
-      }
-      else
-      {
+  if (global) {
+    pos = mapFromGlobal(pos);
+  }
+  Tile *tile = getTileAtMousePos(pos);
+  if (tile) {
+    if (canAcceptDrops(tile)) {
+      tile->makeAcceptDrop(true);
+    } else {
+      InnerWidget *innerWidget = getInnerWidget(m_scrollArea->widget());
+      pos = tile->mapFrom(this, pos);
+      if (tile->rect().contains(pos)) {
+        innerWidget->showInsertMarker(tile, pos);
+      } else {
         innerWidget->clearMarker();
       }
     }
@@ -1143,62 +1019,51 @@ void TiledWindow::showInsertPosition( QPoint pos, bool global )
 }
 
 /// Tell all tiles to not show that they accept widget drops.
-void TiledWindow::clearDrops()
-{
+void TiledWindow::clearDrops() {
   auto tiles = getAllTiles();
-  foreach(Tile* tile, tiles)
-  {
-    tile->makeAcceptDrop(false);
-  }
-  InnerWidget *innerWidget = getInnerWidget( m_scrollArea->widget() );
+  foreach (Tile *tile, tiles) { tile->makeAcceptDrop(false); }
+  InnerWidget *innerWidget = getInnerWidget(m_scrollArea->widget());
   innerWidget->clearMarker();
 }
 
 /**
  * Try to drop a widget at a mouse position. Return true if succeeded.
- * 
+ *
  * @param w :: A widget to drop.
  * @param pos :: Approx position in pixels where a widget will be dropped.
- * @param global :: Selector of the origin for pos. If true pos is relative to 
- *   the top-left corner of the screen. If false it's in the TiledWindow's coordinates.
+ * @param global :: Selector of the origin for pos. If true pos is relative to
+ *   the top-left corner of the screen. If false it's in the TiledWindow's
+ *coordinates.
  */
-bool TiledWindow::dropAtPosition( MdiSubWindow *w, QPoint pos, bool global )
-{
+bool TiledWindow::dropAtPosition(MdiSubWindow *w, QPoint pos, bool global) {
   clearDrops();
-  if ( global )
-  {
-    pos = mapFromGlobal( pos );
+  if (global) {
+    pos = mapFromGlobal(pos);
   }
-  Tile *tile = getTileAtMousePos( pos );
-  if ( !tile )
-  {
+  Tile *tile = getTileAtMousePos(pos);
+  if (!tile) {
     return false;
   }
 
-  int index = calcFlatIndex( tile );
+  int index = calcFlatIndex(tile);
   int row = -1, col = -1;
-  calcTilePosition( index, row, col );
+  calcTilePosition(index, row, col);
 
-  if ( canAcceptDrops(tile) )
-  {
-    addWidget( w, row, col );
+  if (canAcceptDrops(tile)) {
+    addWidget(w, row, col);
     return true;
-  }
-  else
-  {
-    pos = tile->mapFrom( this, pos );
-    InnerWidget *innerWidget = getInnerWidget( m_scrollArea->widget() );
-    Position position = innerWidget->getMarkerPosition( tile, pos );
-    if ( position == Right ) 
-    {
+  } else {
+    pos = tile->mapFrom(this, pos);
+    InnerWidget *innerWidget = getInnerWidget(m_scrollArea->widget());
+    Position position = innerWidget->getMarkerPosition(tile, pos);
+    if (position == Right) {
       col += 1;
-      if ( col >= columnCount() )
-      {
+      if (col >= columnCount()) {
         col = 0;
         row += 1;
       }
     }
-    insertWidget( w, row, col );
+    insertWidget(w, row, col);
     return true;
   }
   return false;
@@ -1208,20 +1073,15 @@ bool TiledWindow::dropAtPosition( MdiSubWindow *w, QPoint pos, bool global )
  * The drag enter event handler.
  * @param ev :: The event.
  */
-void TiledWindow::dragEnterEvent(QDragEnterEvent* ev)
-{
+void TiledWindow::dragEnterEvent(QDragEnterEvent *ev) {
   auto mimeData = ev->mimeData();
   auto frmts = mimeData->formats();
-  if ( mimeData->hasFormat("TiledWindow") )
-  {
+  if (mimeData->hasFormat("TiledWindow")) {
     ev->accept();
-  }
-  else if( mimeData->objectName() == "TiledWindow" && ev->source() == static_cast<QWidget*>(this) )
-  {
+  } else if (mimeData->objectName() == "TiledWindow" &&
+             ev->source() == static_cast<QWidget *>(this)) {
     ev->accept();
-  }
-  else
-  {
+  } else {
     ev->ignore();
   }
 }
@@ -1229,61 +1089,53 @@ void TiledWindow::dragEnterEvent(QDragEnterEvent* ev)
 /**
  * The drag leave event handler.
  */
-void TiledWindow::dragLeaveEvent(QDragLeaveEvent *)
-{
-  clearDrops();
-}
+void TiledWindow::dragLeaveEvent(QDragLeaveEvent *) { clearDrops(); }
 
 /**
  * The drag move event handler.
  * @param ev :: The event.
  */
-void TiledWindow::dragMoveEvent(QDragMoveEvent* ev)
-{
-  showInsertPosition( ev->pos(), false );
+void TiledWindow::dragMoveEvent(QDragMoveEvent *ev) {
+  showInsertPosition(ev->pos(), false);
 }
 
 /**
  * The drop event handler.
  * @param ev :: The event.
  */
-void TiledWindow::dropEvent(QDropEvent* ev)
-{
+void TiledWindow::dropEvent(QDropEvent *ev) {
   auto mimeData = ev->mimeData();
-  if ( mimeData->hasFormat("TiledWindow") )
-  {
+  if (mimeData->hasFormat("TiledWindow")) {
     // Drop a widget from outside
-    if ( ev->source() == static_cast<QWidget*>(this) ) return;
+    if (ev->source() == static_cast<QWidget *>(this))
+      return;
     const char *ptr = mimeData->data("TiledWindow").constData();
-    MdiSubWindow *w = reinterpret_cast<MdiSubWindow*>( const_cast<char*>(ptr) );
+    MdiSubWindow *w = reinterpret_cast<MdiSubWindow *>(const_cast<char *>(ptr));
     // Indirect call to dropAtPosition(). Direct call may cause a crash.
-    emit dropAtPositionQueued( w, ev->pos(), false );
-  }
-  else if( mimeData->objectName() == "TiledWindow" && ev->source() == static_cast<QWidget*>(this) )
-  {
+    emit dropAtPositionQueued(w, ev->pos(), false);
+  } else if (mimeData->objectName() == "TiledWindow" &&
+             ev->source() == static_cast<QWidget *>(this)) {
     // re-arranging widgets within this window
-    if ( isFloating() || rect().contains(ev->pos()) )
-    {
-      // this is how it should normally work, but it only works for floating windows
-      if ( m_selection.size() == 1 )
-      {
-          if ( !getTileAtMousePos(ev->pos()) ) return;
+    if (isFloating() || rect().contains(ev->pos())) {
+      // this is how it should normally work, but it only works for floating
+      // windows
+      if (m_selection.size() == 1) {
+        if (!getTileAtMousePos(ev->pos()))
+          return;
         // TODO: make it work for multiple selection
-        auto w = removeTile( m_selection[0] );
+        auto w = removeTile(m_selection[0]);
         clearSelection();
-        emit dropAtPositionQueued( w, ev->pos(), false );
-      }
-      else
-      {
+        emit dropAtPositionQueued(w, ev->pos(), false);
+      } else {
         // ignore drop of multiple selections
         clearDrops();
         clearSelection();
       }
-    }
-    else
-    {
-      // For some reason Qt doesn't send QDropLeaveEvent when mouse leaves QMdiSubWindow
-      // and enters QMdiArea. This prevents the code that works for floating windows
+    } else {
+      // For some reason Qt doesn't send QDropLeaveEvent when mouse leaves
+      // QMdiSubWindow
+      // and enters QMdiArea. This prevents the code that works for floating
+      // windows
       // working for docked ones. What follows is a workaround.
       applicationWindow()->mantidUI->drop(ev);
     }
diff --git a/MantidPlot/src/TiledWindow.h b/MantidPlot/src/TiledWindow.h
index 19be37814e35dc0d46735b575b0355ddcb87b945..4500974367a1d75196006d4283e31306b934762c 100644
--- a/MantidPlot/src/TiledWindow.h
+++ b/MantidPlot/src/TiledWindow.h
@@ -14,23 +14,20 @@ class Tile;
 
 /**
  *
- *  A mdi sub-window that contains other sub-windows arranged in rows and columns.
+ *  A mdi sub-window that contains other sub-windows arranged in rows and
+ *columns.
  *  The child sub-windows can be selected, moved, deleted, dragged and dropped.
  *
  */
-class TiledWindow: public MdiSubWindow
-{
+class TiledWindow : public MdiSubWindow {
   Q_OBJECT
 
 public:
-  TiledWindow(QWidget* parent, 
-    const QString& label, 
-    const QString& name = QString(), 
-    int nrows = 1,
-    int ncols = 1,
-    Qt::WFlags f=0);
-
-  /// Populate a menu with actions 
+  TiledWindow(QWidget *parent, const QString &label,
+              const QString &name = QString(), int nrows = 1, int ncols = 1,
+              Qt::WFlags f = 0);
+
+  /// Populate a menu with actions
   void populateMenu(QMenu *menu);
 
 public slots:
@@ -73,9 +70,9 @@ public slots:
   /// Remove the selection and put them into separate windows
   void removeSelectionToDefaultWindowType();
   /// Sow a position where tile can be inserted.
-  void showInsertPosition( QPoint pos, bool global = true );
+  void showInsertPosition(QPoint pos, bool global = true);
   /// Do the widget drop operation
-  bool dropAtPosition( MdiSubWindow *w, QPoint pos, bool global = true );
+  bool dropAtPosition(MdiSubWindow *w, QPoint pos, bool global = true);
 
   /// Save
   QString saveToString(const QString &info, bool = false) override;
@@ -94,7 +91,6 @@ protected:
   void dropEvent(QDropEvent *ev) override;
 
 private:
-
   /// Ways a widget can be removed from this window
   enum RemoveDestination { Default, Docked, Floating };
 
@@ -113,9 +109,9 @@ private:
   /// Remove (but don't delete) a widget.
   MdiSubWindow *removeTile(Tile *tile);
   /// Get a tile at a mouse position (in pixels).
-  Tile *getTileAtMousePos( const QPoint& pos );
+  Tile *getTileAtMousePos(const QPoint &pos);
   /// Get a list of all tiles.
-  QList<Tile*> getAllTiles();
+  QList<Tile *> getAllTiles();
   /// Add a tile to the selection.
   void addToSelection(Tile *tile, bool append);
   /// Add a range of tiles to the selection.
@@ -125,7 +121,7 @@ private:
   /// Calculate a linear index from row and column numbers.
   int calcFlatIndex(int row, int col) const;
   /// Calculate tile's position in the layout.
-  void calcTilePosition( int index, int &row, int &col ) const;
+  void calcTilePosition(int index, int &row, int &col) const;
   /// Deselect a tile
   bool deselectTile(Tile *tile);
   /// Tell all tiles to not show that they accept widget drops.
@@ -151,13 +147,12 @@ signals:
   void dropAtPositionQueued(MdiSubWindow *w, QPoint pos, bool global);
 
 private:
-
   /// The inner widget providing scrolling functionality.
   QScrollArea *m_scrollArea;
   /// The layout arranging the tiles into a grid.
   mutable QGridLayout *m_layout;
   /// Tile selection
-  QList<Tile*> m_selection;
+  QList<Tile *> m_selection;
   /// mouse cursor position where dragging started
   QPoint m_dragStartPos;
   /// mouse left button is pressed
@@ -165,11 +160,11 @@ private:
 };
 
 /**
- * The widget holder. It displays the held MdiSubWindow, helps to implement selection, 
+ * The widget holder. It displays the held MdiSubWindow, helps to implement
+ * selection,
  * drag and drop operations.
  */
-class Tile: public QFrame
-{
+class Tile : public QFrame {
 public:
   /// Constructor
   explicit Tile(QWidget *parent);
@@ -180,13 +175,14 @@ public:
   /// Remove the held widget without deleting it.
   void removeWidget();
   /// Get the held widget
-  MdiSubWindow *widget() {return m_widget;}
+  MdiSubWindow *widget() { return m_widget; }
   /// Display the tile as selected
   void makeSelected(bool yes);
   /// Display the tile ready to accept a drop of a widget
   void makeAcceptDrop(bool yes);
   /// Check if the tile is selected
-  bool isSelected() const {return m_selected;}
+  bool isSelected() const { return m_selected; }
+
 protected:
   void paintEvent(QPaintEvent *ev) override;
 
@@ -194,14 +190,13 @@ private:
   /// The TiledWindow which has this Tile
   QWidget *m_tiledWindow;
   /// The layout
-  QVBoxLayout * m_layout;
+  QVBoxLayout *m_layout;
   /// A pointer to the displayed widget
-  MdiSubWindow* m_widget;
+  MdiSubWindow *m_widget;
   /// Selected flag
   bool m_selected;
   /// Accepts drops flag
   bool m_acceptDrop;
-
 };
 
 #endif // TiledWindow_H
diff --git a/MantidPlot/src/TitlePicker.cpp b/MantidPlot/src/TitlePicker.cpp
index 1828e4a7ae9c78739f4820afc550777845ef9429..dbaf8eb1cb35134f2feabc3ee94fdcb3dcbc13d7 100644
--- a/MantidPlot/src/TitlePicker.cpp
+++ b/MantidPlot/src/TitlePicker.cpp
@@ -34,65 +34,61 @@
 #include <QMouseEvent>
 #include <QPen>
 
-TitlePicker::TitlePicker(QwtPlot *plot):
-	QObject(plot)
-{
-    d_selected = false;
-	title = plot->titleLabel();
-	title->setFocusPolicy(Qt::StrongFocus);
-	if (title)
-		title->installEventFilter(this);
+TitlePicker::TitlePicker(QwtPlot *plot) : QObject(plot) {
+  d_selected = false;
+  title = plot->titleLabel();
+  title->setFocusPolicy(Qt::StrongFocus);
+  if (title)
+    title->installEventFilter(this);
 }
 
-bool TitlePicker::eventFilter(QObject *object, QEvent *e)
-{
-	if (object != (QObject *)title)
-		return FALSE;
+bool TitlePicker::eventFilter(QObject *object, QEvent *e) {
+  if (object != (QObject *)title)
+    return FALSE;
 
-    if ( object->inherits("QwtTextLabel") && e->type() == QEvent::MouseButtonDblClick){
-        emit doubleClicked();
-		d_selected = true;
-        return TRUE;
-    }
+  if (object->inherits("QwtTextLabel") &&
+      e->type() == QEvent::MouseButtonDblClick) {
+    emit doubleClicked();
+    d_selected = true;
+    return TRUE;
+  }
+
+  if (object->inherits("QwtTextLabel") &&
+      e->type() == QEvent::MouseButtonPress) {
+    const QMouseEvent *me = (const QMouseEvent *)e;
 
-	 if ( object->inherits("QwtTextLabel") &&  e->type() == QEvent::MouseButtonPress ){
-		 const QMouseEvent *me = (const QMouseEvent *)e;
+    emit clicked();
 
-		 emit clicked();
+    if (me->button() == Qt::RightButton)
+      emit showTitleMenu();
+    else if (me->button() == Qt::LeftButton)
+      setSelected();
 
-		 if (me->button() == Qt::RightButton)
-			emit showTitleMenu();
-         else if (me->button() == Qt::LeftButton)
-		 	setSelected();
+    return !(me->modifiers() & Qt::ShiftModifier);
+  }
 
-		 return !(me->modifiers() & Qt::ShiftModifier);
+  if (object->inherits("QwtTextLabel") && e->type() == QEvent::KeyPress) {
+    switch (((const QKeyEvent *)e)->key()) {
+    case Qt::Key_Delete:
+      emit removeTitle();
+      return TRUE;
     }
+  }
 
-	if ( object->inherits("QwtTextLabel") &&
-        e->type() == QEvent::KeyPress){
-		switch (((const QKeyEvent *)e)->key())
-			{
-			case Qt::Key_Delete:
-			emit removeTitle();
-            return TRUE;
-			}
-		}
-
-    return QObject::eventFilter(object, e);
+  return QObject::eventFilter(object, e);
 }
 
-void TitlePicker::setSelected(bool select)
-{
-    if (!title || d_selected == select)
-        return;
+void TitlePicker::setSelected(bool select) {
+  if (!title || d_selected == select)
+    return;
 
-    d_selected = select;
+  d_selected = select;
 
-    QwtText text = title->text();
-    if (select)
-        text.setBackgroundPen(QPen(Qt::blue));
-    else
-        text.setBackgroundPen(QPen(Qt::NoPen));
+  QwtText text = title->text();
+  if (select)
+    text.setBackgroundPen(QPen(Qt::blue));
+  else
+    text.setBackgroundPen(QPen(Qt::NoPen));
 
-    (static_cast<QwtPlot *>(parent()))->setTitle(text);
+  (static_cast<QwtPlot *>(parent()))->setTitle(text);
 }
diff --git a/MantidPlot/src/TitlePicker.h b/MantidPlot/src/TitlePicker.h
index 1c328c9e05dbba8db88048d92b42228c655f7f18..ff7f2c3bd8fb0e33c9f99d10ee2125bec946a5a3 100644
--- a/MantidPlot/src/TitlePicker.h
+++ b/MantidPlot/src/TitlePicker.h
@@ -31,23 +31,22 @@
 class QwtPlot;
 class QwtTextLabel;
 
-class TitlePicker: public QObject
-{
-    Q_OBJECT
+class TitlePicker : public QObject {
+  Q_OBJECT
 
 public:
   explicit TitlePicker(QwtPlot *plot);
-    void setSelected(bool select = true);
-	bool selected(){return d_selected;};
+  void setSelected(bool select = true);
+  bool selected() { return d_selected; };
 
 signals:
-	void clicked();
-	void doubleClicked();
-	void removeTitle();
-	void showTitleMenu();
+  void clicked();
+  void doubleClicked();
+  void removeTitle();
+  void showTitleMenu();
 
 private:
   bool eventFilter(QObject *, QEvent *) override;
-        QwtTextLabel *title;
-	bool d_selected;
+  QwtTextLabel *title;
+  bool d_selected;
 };
diff --git a/MantidPlot/src/TranslateCurveTool.cpp b/MantidPlot/src/TranslateCurveTool.cpp
index c9607a648dfabb87983a65583aad273c93c73a6e..964a727df99a32b676832432f4e90ad4550e6fdc 100644
--- a/MantidPlot/src/TranslateCurveTool.cpp
+++ b/MantidPlot/src/TranslateCurveTool.cpp
@@ -41,33 +41,35 @@
 #include <QLocale>
 #include <qwt_plot_curve.h>
 
-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)
-		connect(this, SIGNAL(statusText(const QString&)), status_target, status_slot);
-	//d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
-	//emit statusText(tr("Double-click on plot to select a data point!"));
+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)
+    connect(this, SIGNAL(statusText(const QString &)), status_target,
+            status_slot);
+  // d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"),
+  // -1, -1));
+  // emit statusText(tr("Double-click on plot to select a data point!"));
 
-	// Phase 1: select curve point
-	d_sub_tool = new DataPickerTool(d_graph, app, DataPickerTool::Display, this, SIGNAL(statusText(const QString&)));
-	connect(dynamic_cast<DataPickerTool*>(d_sub_tool), SIGNAL(selected(QwtPlotCurve*,int)),
-			this, SLOT(selectCurvePoint(QwtPlotCurve*,int)));
-  //d_sub_tool = NULL;
+  // Phase 1: select curve point
+  d_sub_tool = new DataPickerTool(d_graph, app, DataPickerTool::Display, this,
+                                  SIGNAL(statusText(const QString &)));
+  connect(dynamic_cast<DataPickerTool *>(d_sub_tool),
+          SIGNAL(selected(QwtPlotCurve *, int)), this,
+          SLOT(selectCurvePoint(QwtPlotCurve *, int)));
+  // d_sub_tool = NULL;
 }
 
-void TranslateCurveTool::selectCurvePoint(QwtPlotCurve *curve, int point_index)
-{
+void TranslateCurveTool::selectCurvePoint(QwtPlotCurve *curve,
+                                          int point_index) {
   if (!d_sub_tool)
     return;
   DataCurve *c = dynamic_cast<DataCurve *>(curve);
   if (c && c->type() != Graph::Function) {
-    
+
     Table *t = c->table();
     if (!t)
       return;
@@ -94,87 +96,98 @@ void TranslateCurveTool::selectCurvePoint(QwtPlotCurve *curve, int point_index)
   }
 
   d_selected_curve = curve;
-	d_curve_point = QwtDoublePoint(curve->x(point_index), curve->y(point_index));
-	delete d_sub_tool;
+  d_curve_point = QwtDoublePoint(curve->x(point_index), curve->y(point_index));
+  delete d_sub_tool;
 
-	// Phase 2: select destination
-	d_sub_tool = new ScreenPickerTool(d_graph, this, SIGNAL(statusText(const QString&)));
-	connect(dynamic_cast<ScreenPickerTool*>(d_sub_tool), SIGNAL(selected(const QwtDoublePoint&)), this, SLOT(selectDestination(const QwtDoublePoint&)));
-	emit statusText(tr("Curve selected! Move cursor and click to choose a point and double-click/press 'Enter' to finish!"));
+  // Phase 2: select destination
+  d_sub_tool =
+      new ScreenPickerTool(d_graph, this, SIGNAL(statusText(const QString &)));
+  connect(dynamic_cast<ScreenPickerTool *>(d_sub_tool),
+          SIGNAL(selected(const QwtDoublePoint &)), this,
+          SLOT(selectDestination(const QwtDoublePoint &)));
+  emit statusText(tr("Curve selected! Move cursor and click to choose a point "
+                     "and double-click/press 'Enter' to finish!"));
 }
 
-void TranslateCurveTool::selectDestination(const QwtDoublePoint &point)
-{
-  if (!d_sub_tool) return;
-	delete d_sub_tool;
-	if (!d_selected_curve)
-		return;
+void TranslateCurveTool::selectDestination(const QwtDoublePoint &point) {
+  if (!d_sub_tool)
+    return;
+  delete d_sub_tool;
+  if (!d_selected_curve)
+    return;
 
-	// Phase 3: execute the translation
+  // Phase 3: execute the translation
 
-	if(auto c = dynamic_cast<PlotCurve *>(d_selected_curve)){
+  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"),
+      if (d_dir == Horizontal) {
+        QMessageBox::warning(
+            d_app, tr("MantidPlot - Warning"),
             tr("This operation cannot be performed on function curves."));
-        } 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();
-                if (d > 0)
-                    func->setFormula(formula + "+" + QString::number(d, 'g', 15));
-                else
-                    func->setFormula(formula + QString::number(d, 'g', 15));
-                func->loadData();
-            }
+      } 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();
+          if (d > 0)
+            func->setFormula(formula + "+" + QString::number(d, 'g', 15));
+          else
+            func->setFormula(formula + QString::number(d, 'g', 15));
+          func->loadData();
         }
-	    d_graph->setActiveTool(NULL);
-	    return;
+      }
+      d_graph->setActiveTool(NULL);
+      return;
     }
   } else if (DataCurve *c = dynamic_cast<DataCurve *>(d_selected_curve)) {
     double d;
-		QString col_name;
-		switch(d_dir) {
-			case Vertical:
-			{
-				col_name = c->title().text();
-				d = point.y() - d_curve_point.y();
-				break;
-			}
-			case Horizontal:
-			{
-				col_name = c->xColumnName();
-				d = point.x() - d_curve_point.x();
-				break;
-			}
-            default: // this should never happen
-            {
-                d = std::numeric_limits<float>::quiet_NaN();
-            }
-	}
-	Table *tab = d_app->table(col_name);
-	if (!tab) return;
-	int col = tab->colIndex(col_name);
-	if (tab->columnType(col) != Table::Numeric) {
-		QMessageBox::warning(d_app, tr("MantidPlot - Warning"),
-				tr("This operation cannot be performed on curves plotted from columns having a non-numerical format."));
-		return;
-	}
+    QString col_name;
+    switch (d_dir) {
+    case Vertical: {
+      col_name = c->title().text();
+      d = point.y() - d_curve_point.y();
+      break;
+    }
+    case Horizontal: {
+      col_name = c->xColumnName();
+      d = point.x() - d_curve_point.x();
+      break;
+    }
+    default: // this should never happen
+    {
+      d = std::numeric_limits<float>::quiet_NaN();
+    }
+    }
+    Table *tab = d_app->table(col_name);
+    if (!tab)
+      return;
+    int col = tab->colIndex(col_name);
+    if (tab->columnType(col) != Table::Numeric) {
+      QMessageBox::warning(
+          d_app, tr("MantidPlot - Warning"),
+          tr("This operation cannot be performed on curves plotted from "
+             "columns having a non-numerical format."));
+      return;
+    }
 
-	int prec; char f;
-	tab->columnNumericFormat(col, &f, &prec);
-	int row_start = c->tableRow(0);
+    int prec;
+    char f;
+    tab->columnNumericFormat(col, &f, &prec);
+    int row_start = c->tableRow(0);
     int row_end = row_start + c->dataSize();
 
     QLocale locale = d_app->locale();
-	for (int i=row_start; i<row_end; i++){
-		if (!tab->text(i, col).isEmpty())
-			tab->setText(i, col, locale.toString(
-					(d_dir==Horizontal ? d_selected_curve->x(i) : d_selected_curve->y(i)) + d, f, prec));
-	}
-	d_app->updateCurves(tab, col_name);
-	d_app->modifiedProject();
-	d_graph->setActiveTool(NULL);
-	// attention: I'm now deleted. Maybe there is a cleaner solution...*/
+    for (int i = row_start; i < row_end; i++) {
+      if (!tab->text(i, col).isEmpty())
+        tab->setText(i, col, locale.toString((d_dir == Horizontal
+                                                  ? d_selected_curve->x(i)
+                                                  : d_selected_curve->y(i)) +
+                                                 d,
+                                             f, prec));
     }
+    d_app->updateCurves(tab, col_name);
+    d_app->modifiedProject();
+    d_graph->setActiveTool(NULL);
+    // attention: I'm now deleted. Maybe there is a cleaner solution...*/
+  }
 }
diff --git a/MantidPlot/src/TranslateCurveTool.h b/MantidPlot/src/TranslateCurveTool.h
index 54e6bb3f3b6b05d8f85642ad9c77f7176ec46111..2bd087a24b3c2e6aa781debadddb471b6d0a7857 100644
--- a/MantidPlot/src/TranslateCurveTool.h
+++ b/MantidPlot/src/TranslateCurveTool.h
@@ -39,43 +39,50 @@ class ApplicationWindow;
 class QwtPlotCurve;
 
 //! Plot tool for translating curves.
-class TranslateCurveTool : public QObject, public PlotToolInterface
-{
-	Q_OBJECT
-	public:
-		enum Direction { Vertical, Horizontal };
-		/**\brief Standard constructor.
-		 * @param graph :: the Graph to operate on (or rather, on whose image markers to operate on)
-		 * @param app :: parent window of graph
-		 * @param dir :: the direction in which to translate curves
-		 * @param status_target :: target to which the statusText(const QString&) signal will be connected
-		 * @param status_slot :: slot on status_target to which the statusText(const QString&) signal will be connected
-		 * The status_target/status_slot arguments are provided, because statusText(const QString&) is emitted
-		 * during initialization, before there's any other chance of connecting to it.
-		 */
-		TranslateCurveTool(Graph *graph, ApplicationWindow *app, Direction dir, const QObject *status_target=NULL, const char *status_slot="");
+class TranslateCurveTool : public QObject, public PlotToolInterface {
+  Q_OBJECT
+public:
+  enum Direction { Vertical, Horizontal };
+  /**\brief Standard constructor.
+   * @param graph :: the Graph to operate on (or rather, on whose image markers
+   * to operate on)
+   * @param app :: parent window of graph
+   * @param dir :: the direction in which to translate curves
+   * @param status_target :: target to which the statusText(const QString&)
+   * signal will be connected
+   * @param status_slot :: slot on status_target to which the statusText(const
+   * QString&) signal will be connected
+   * The status_target/status_slot arguments are provided, because
+   * statusText(const QString&) is emitted
+   * during initialization, before there's any other chance of connecting to it.
+   */
+  TranslateCurveTool(Graph *graph, ApplicationWindow *app, Direction dir,
+                     const QObject *status_target = NULL,
+                     const char *status_slot = "");
 
-                int rtti() const override {
-                  return PlotToolInterface::Rtti_TranslateCurveTool;
-                };
-        signals:
-		/**\brief Emitted whenever a new message should be presented to the user.
-		 *
-		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
-		 */
-		void statusText(const QString&);
-	public slots:
-		//! Select curve to translate, using the specified point as base point.
-		void selectCurvePoint(QwtPlotCurve *curve, int point_index);
-		//! Select the coordinates where the base point should end up (modulo projection on #d_dir direction).
-		void selectDestination(const QwtDoublePoint &point);
-	private:
-		Direction d_dir;
-		PlotToolInterface *d_sub_tool;
-		QwtPlotCurve *d_selected_curve;
-		QwtDoublePoint d_curve_point;
-		ApplicationWindow *d_app;
+  int rtti() const override {
+    return PlotToolInterface::Rtti_TranslateCurveTool;
+  };
+signals:
+  /**\brief Emitted whenever a new message should be presented to the user.
+   *
+   * You don't have to connect to this signal if you alreay specified a reciever
+   *during initialization.
+   */
+  void statusText(const QString &);
+public slots:
+  //! Select curve to translate, using the specified point as base point.
+  void selectCurvePoint(QwtPlotCurve *curve, int point_index);
+  //! Select the coordinates where the base point should end up (modulo
+  // projection on #d_dir direction).
+  void selectDestination(const QwtDoublePoint &point);
+
+private:
+  Direction d_dir;
+  PlotToolInterface *d_sub_tool;
+  QwtPlotCurve *d_selected_curve;
+  QwtDoublePoint d_curve_point;
+  ApplicationWindow *d_app;
 };
 
 #endif // TRANSLATE_CURVE_TOOL_H
-
diff --git a/MantidPlot/src/UserFunction.cpp b/MantidPlot/src/UserFunction.cpp
index 85ee35a43819af50d139e52fc97714393360404e..88ff11a2f4c270ab25fd7a31eeb8457088cc9f3a 100644
--- a/MantidPlot/src/UserFunction.cpp
+++ b/MantidPlot/src/UserFunction.cpp
@@ -1,64 +1,52 @@
 #ifdef _WIN32
-#pragma warning(disable: 4251)
+#pragma warning(disable : 4251)
 #endif
 
 #include "MyParser.h"
 #include "UserFunction.h"
 #include <QMessageBox>
 
-Function2D::Function2D():
-    Qwt3D::Function(), d_rows(0), d_columns(0)
-{
-}
+Function2D::Function2D() : Qwt3D::Function(), d_rows(0), d_columns(0) {}
 
-void Function2D::setMesh (size_t columns, size_t rows)
-{
-    Function::setMesh (static_cast<unsigned int>(columns), static_cast<unsigned int>(rows));
-    d_columns = columns;
-    d_rows = rows;
+void Function2D::setMesh(size_t columns, size_t rows) {
+  Function::setMesh(static_cast<unsigned int>(columns),
+                    static_cast<unsigned int>(rows));
+  d_columns = columns;
+  d_rows = rows;
 }
 
-UserFunction2D::UserFunction2D(const QString& s)
-: Function2D(), d_formula(s)
-{}
-
-double UserFunction2D::operator()(double x, double y)
-{
-    if (d_formula.isEmpty())
-		return 0.0;
-
-	MyParser parser;
-	double result=0.0;
-	try
-	{
-		parser.DefineVar("x", &x);
-		parser.DefineVar("y", &y);
-
-                parser.SetExpr((const std::string)d_formula.toAscii().constData());
-		result=parser.Eval();
-	}
-	catch(mu::ParserError &e)
-	{
-		QMessageBox::critical(0,"MantidPlot - Input function error",QString::fromStdString(e.GetMsg()));
-	}
-    return result;
+UserFunction2D::UserFunction2D(const QString &s) : Function2D(), d_formula(s) {}
+
+double UserFunction2D::operator()(double x, double y) {
+  if (d_formula.isEmpty())
+    return 0.0;
+
+  MyParser parser;
+  double result = 0.0;
+  try {
+    parser.DefineVar("x", &x);
+    parser.DefineVar("y", &y);
+
+    parser.SetExpr((const std::string)d_formula.toAscii().constData());
+    result = parser.Eval();
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(0, "MantidPlot - Input function error",
+                          QString::fromStdString(e.GetMsg()));
+  }
+  return result;
 }
 
 /**
  * @return The smallest positive value this function ever to return.
  */
-double UserFunction2D::getMinPositiveValue() const
-{
-    return 0.0001;
-}
+double UserFunction2D::getMinPositiveValue() const { return 0.0001; }
 
 /**
  * @brief UserFunction2D::saveToString
  *
  * @return :: Initialization string.
  */
-QString UserFunction2D::saveToString() const
-{
-    return formula() + ";" + QString::number(columns()) + ";" + QString::number(rows());
+QString UserFunction2D::saveToString() const {
+  return formula() + ";" + QString::number(columns()) + ";" +
+         QString::number(rows());
 }
-
diff --git a/MantidPlot/src/UserFunction.h b/MantidPlot/src/UserFunction.h
index b5a31a470e2ac31cc262609885319845f641dba9..4a3de27b1e88ed54caff552a4f4bec310a967e62 100644
--- a/MantidPlot/src/UserFunction.h
+++ b/MantidPlot/src/UserFunction.h
@@ -28,25 +28,24 @@
  *    void connectToViewer(QObject* viewer);
  *          to connect to a viewer object (eg Graph3D)
  */
-class Function2D : public Qwt3D::Function
-{
+class Function2D : public Qwt3D::Function {
 public:
-    Function2D();
-    /// Get minimum positive value. It is needed for logarithmic scales.
-    virtual double getMinPositiveValue()const = 0;
-    /// Save function parameters to a string.
-    virtual QString saveToString() const = 0;
-    /// Connect to a viewer object
-    virtual void connectToViewer(QObject*) {}
+  Function2D();
+  /// Get minimum positive value. It is needed for logarithmic scales.
+  virtual double getMinPositiveValue() const = 0;
+  /// Save function parameters to a string.
+  virtual QString saveToString() const = 0;
+  /// Connect to a viewer object
+  virtual void connectToViewer(QObject *) {}
+
+  size_t rows() const { return d_rows; }
+  size_t columns() const { return d_columns; }
+  void setMesh(size_t columns, size_t rows);
 
-    size_t rows() const {return d_rows;}
-    size_t columns() const {return d_columns;}
-    void setMesh (size_t columns, size_t rows);
 private:
-      size_t d_rows, d_columns;
+  size_t d_rows, d_columns;
 };
 
-
 /**
  * @brief The UserFunction2D class implements a user defined 2D function.
  *
@@ -54,21 +53,20 @@ private:
  * x and y for the function arguments.
  *
  */
-class UserFunction2D : public Function2D
-{
+class UserFunction2D : public Function2D {
 public:
   explicit UserFunction2D(const QString &s);
-    /// Get function value
+  /// Get function value
   double operator()(double x, double y) override;
-    /// Get minimum positive value.
+  /// Get minimum positive value.
   double getMinPositiveValue() const override;
-    /// Save function parameters to a string.
+  /// Save function parameters to a string.
   QString saveToString() const override;
 
-    QString formula() const {return d_formula;}
+  QString formula() const { return d_formula; }
 
 private:
-      QString d_formula;
+  QString d_formula;
 };
 
 #endif
diff --git a/MantidPlot/src/VectorCurve.cpp b/MantidPlot/src/VectorCurve.cpp
index 3d2d5b9424b8612b8688501e74cb8942d39202b6..760381a91de6ab1a647f6ff434a1a775bd06a1ea 100644
--- a/MantidPlot/src/VectorCurve.cpp
+++ b/MantidPlot/src/VectorCurve.cpp
@@ -2,7 +2,8 @@
     File                 : VectorCurve.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Vector curve class
 
@@ -32,352 +33,325 @@
 #include <qwt_double_rect.h>
 #include <QPainter>
 
-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),
-    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);
-	else if (style == XYAM)
-		setType(Graph::VectXYAM);
+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), 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);
+  else if (style == XYAM)
+    setType(Graph::VectXYAM);
 }
 
-void VectorCurve::copy(const VectorCurve *vc)
-{
-d_style = vc->d_style;
-filledArrow = vc->filledArrow;
-d_headLength = vc->d_headLength;
-d_headAngle = vc->d_headAngle;
-d_position = vc->d_position;
-pen = vc->pen;
-vectorEnd = (QwtArrayData *)vc->vectorEnd->copy();
+void VectorCurve::copy(const VectorCurve *vc) {
+  d_style = vc->d_style;
+  filledArrow = vc->filledArrow;
+  d_headLength = vc->d_headLength;
+  d_headAngle = vc->d_headAngle;
+  d_position = vc->d_position;
+  pen = vc->pen;
+  vectorEnd = (QwtArrayData *)vc->vectorEnd->copy();
 }
 
-void VectorCurve::draw(QPainter *painter,
-    const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
-    if ( !painter || dataSize() <= 0 )
-        return;
+void VectorCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                       const QwtScaleMap &yMap, int from, int to) const {
+  if (!painter || dataSize() <= 0)
+    return;
 
-    if (to < 0)
-        to = dataSize() - 1;
+  if (to < 0)
+    to = dataSize() - 1;
 
-	QwtPlotCurve::draw(painter, xMap, yMap, from, to);
+  QwtPlotCurve::draw(painter, xMap, yMap, from, to);
 
-    painter->save();
-    painter->setPen(pen);
-    drawVector(painter, xMap, yMap, from, to);
-    painter->restore();
+  painter->save();
+  painter->setPen(pen);
+  drawVector(painter, xMap, yMap, from, to);
+  painter->restore();
 }
 
-void VectorCurve::drawVector(QPainter *painter,
-    const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
-if (d_style == XYAM)
-{
- for (int i = from; i <= to; i++)
-	{
-	const double x0 = x(i);
-	const double y0 = y(i);
-	const double angle = vectorEnd->x(i);
-	const double mag = vectorEnd->y(i);
-
-	int xs = 0, ys = 0, xe = 0, ye = 0;
-	switch(d_position)
-		{
-		case Tail:
-			xs = xMap.transform(x0);
-			ys = yMap.transform(y0);
-			xe = xMap.transform(x0 + mag*cos(angle));
-			ye = yMap.transform(y0 + mag*sin(angle));
-		break;
-
-		case Middle:
-			{
-			double dxh = 0.5*mag*cos(angle);
-			double dyh = 0.5*mag*sin(angle);
-			xs = xMap.transform(x0 - dxh);
-			ys = yMap.transform(y0 - dyh);
-			xe = xMap.transform(x0 + dxh);
-			ye = yMap.transform(y0 + dyh);
-			}
-		break;
-
-		case Head:
-			xs = xMap.transform(x0 - mag*cos(angle));
-			ys = yMap.transform(y0 - mag*sin(angle));
-			xe = xMap.transform(x0);
-			ye = yMap.transform(y0);
-		break;
-		}
-	QwtPainter::drawLine(painter, xs, ys, xe, ye);
-	drawArrowHead(painter, xs, ys, xe, ye);
-	}
-}
-else
-	{
-	for (int i = from; i <= to; i++)
-		{
-		const int xs = xMap.transform(x(i));
-		const int ys = yMap.transform(y(i));
-		const int xe = xMap.transform(vectorEnd->x(i));
-		const int ye = yMap.transform(vectorEnd->y(i));
-		QwtPainter::drawLine(painter, xs, ys, xe, ye);
-		drawArrowHead(painter, xs, ys, xe, ye);
-		}
-	}
+void VectorCurve::drawVector(QPainter *painter, const QwtScaleMap &xMap,
+                             const QwtScaleMap &yMap, int from, int to) const {
+  if (d_style == XYAM) {
+    for (int i = from; i <= to; i++) {
+      const double x0 = x(i);
+      const double y0 = y(i);
+      const double angle = vectorEnd->x(i);
+      const double mag = vectorEnd->y(i);
+
+      int xs = 0, ys = 0, xe = 0, ye = 0;
+      switch (d_position) {
+      case Tail:
+        xs = xMap.transform(x0);
+        ys = yMap.transform(y0);
+        xe = xMap.transform(x0 + mag * cos(angle));
+        ye = yMap.transform(y0 + mag * sin(angle));
+        break;
+
+      case Middle: {
+        double dxh = 0.5 * mag * cos(angle);
+        double dyh = 0.5 * mag * sin(angle);
+        xs = xMap.transform(x0 - dxh);
+        ys = yMap.transform(y0 - dyh);
+        xe = xMap.transform(x0 + dxh);
+        ye = yMap.transform(y0 + dyh);
+      } break;
+
+      case Head:
+        xs = xMap.transform(x0 - mag * cos(angle));
+        ys = yMap.transform(y0 - mag * sin(angle));
+        xe = xMap.transform(x0);
+        ye = yMap.transform(y0);
+        break;
+      }
+      QwtPainter::drawLine(painter, xs, ys, xe, ye);
+      drawArrowHead(painter, xs, ys, xe, ye);
+    }
+  } else {
+    for (int i = from; i <= to; i++) {
+      const int xs = xMap.transform(x(i));
+      const int ys = yMap.transform(y(i));
+      const int xe = xMap.transform(vectorEnd->x(i));
+      const int ye = yMap.transform(vectorEnd->y(i));
+      QwtPainter::drawLine(painter, xs, ys, xe, ye);
+      drawArrowHead(painter, xs, ys, xe, ye);
+    }
+  }
 }
 
-void VectorCurve::drawArrowHead(QPainter *p, int xs, int ys, int xe, int ye) const
-{
-p->save();
-p->translate(xe, ye);
-double t=theta(xs, ys, xe, ye);
-p->rotate(-t);
+void VectorCurve::drawArrowHead(QPainter *p, int xs, int ys, int xe,
+                                int ye) const {
+  p->save();
+  p->translate(xe, ye);
+  double t = theta(xs, ys, xe, ye);
+  p->rotate(-t);
 
-double pi=4*atan(-1.0);
-int d=qRound(d_headLength*tan(pi*(double)d_headAngle/180.0));
+  double pi = 4 * atan(-1.0);
+  int d = qRound(d_headLength * tan(pi * (double)d_headAngle / 180.0));
 
-QPolygon endArray(3);
-endArray[0] = QPoint(0, 0);
-endArray[1] = QPoint(-d_headLength, d);
-endArray[2] = QPoint(-d_headLength, -d);
+  QPolygon endArray(3);
+  endArray[0] = QPoint(0, 0);
+  endArray[1] = QPoint(-d_headLength, d);
+  endArray[2] = QPoint(-d_headLength, -d);
 
-if (filledArrow)
-	p->setBrush(QBrush(pen.color(), Qt::SolidPattern));
+  if (filledArrow)
+    p->setBrush(QBrush(pen.color(), Qt::SolidPattern));
 
-QwtPainter::drawPolygon(p,endArray);
-p->restore();
+  QwtPainter::drawPolygon(p, endArray);
+  p->restore();
 }
 
-double VectorCurve::theta(int x0, int y0, int x1, int y1) const
-{
-double t,pi=4*atan(-1.0);
-if (x1==x0)
-	{
-	if (y0>y1)
-		t=90;
-	else
-		t=270;
-	}
-else
-	{
-	t=atan2((y1-y0)*1.0,(x1-x0)*1.0)*180/pi;
-	if (t<0)
-		t=360+t;
-	}
-return t;
+double VectorCurve::theta(int x0, int y0, int x1, int y1) const {
+  double t, pi = 4 * atan(-1.0);
+  if (x1 == x0) {
+    if (y0 > y1)
+      t = 90;
+    else
+      t = 270;
+  } else {
+    t = atan2((y1 - y0) * 1.0, (x1 - x0) * 1.0) * 180 / pi;
+    if (t < 0)
+      t = 360 + t;
+  }
+  return t;
 }
 
-void VectorCurve::setVectorEnd(const QString& xColName, const QString& yColName)
-{
-if (d_end_x_a == xColName && d_end_y_m == yColName)
-	return;
+void VectorCurve::setVectorEnd(const QString &xColName,
+                               const QString &yColName) {
+  if (d_end_x_a == xColName && d_end_y_m == yColName)
+    return;
 
-d_end_x_a = xColName;
-d_end_y_m = yColName;
+  d_end_x_a = xColName;
+  d_end_y_m = yColName;
 
-loadData();
+  loadData();
 }
 
-void VectorCurve::setVectorEnd(const QwtArray<double>&x, const QwtArray<double>&y)
-{
-    vectorEnd=new QwtArrayData(x, y);
+void VectorCurve::setVectorEnd(const QwtArray<double> &x,
+                               const QwtArray<double> &y) {
+  vectorEnd = new QwtArrayData(x, y);
 }
 
-double VectorCurve::width()
-{
-return pen.widthF();
-}
+double VectorCurve::width() { return pen.widthF(); }
 
-void VectorCurve::setWidth(double w)
-{
-pen.setWidthF(w);
-}
+void VectorCurve::setWidth(double w) { pen.setWidthF(w); }
 
-QColor VectorCurve::color()
-{
-return pen.color();
-}
+QColor VectorCurve::color() { return pen.color(); }
 
-void VectorCurve::setColor(const QColor& c)
-{
-if (pen.color() != c)
-	pen.setColor(c);
+void VectorCurve::setColor(const QColor &c) {
+  if (pen.color() != c)
+    pen.setColor(c);
 }
 
-void VectorCurve::setHeadLength(int l)
-{
-if (d_headLength != l)
-	d_headLength = l;
+void VectorCurve::setHeadLength(int l) {
+  if (d_headLength != l)
+    d_headLength = l;
 }
 
-void VectorCurve::setHeadAngle(int a)
-{
-if (d_headAngle != a)
-	d_headAngle = a;
+void VectorCurve::setHeadAngle(int a) {
+  if (d_headAngle != a)
+    d_headAngle = a;
 }
 
-void VectorCurve::fillArrowHead(bool fill)
-{
-if (filledArrow != fill)
-	filledArrow = fill;
+void VectorCurve::fillArrowHead(bool fill) {
+  if (filledArrow != fill)
+    filledArrow = fill;
 }
 
-QwtDoubleRect VectorCurve::boundingRect() const
-{
-QwtDoubleRect rect = QwtPlotCurve::boundingRect();
-QwtDoubleRect vrect = vectorEnd->boundingRect();
-
-if (d_style == XYXY){
-	rect.setTop(QMIN((double)rect.top(), (double)vrect.top()));
-	rect.setBottom(QMAX((double)rect.bottom(), (double)vrect.bottom()));
-	rect.setLeft(QMIN((double)rect.left(), (double)vrect.left()));
-	rect.setRight(QMAX((double)rect.right(), (double)vrect.right()));
-} else {
-	const double angle = vectorEnd->x(0);
-	double mag = vectorEnd->y(0);
-	switch(d_position)
-		{
-		case Tail:
-			rect.setTop(QMIN((double)rect.top(), (double)(rect.top()+mag*sin(angle))));
-			rect.setBottom(QMAX((double)rect.bottom(), (double)(rect.bottom()+mag*sin(angle))));
-			rect.setLeft(QMIN((double)rect.left(), (double)(rect.left()+mag*cos(angle))));
-			rect.setRight(QMAX((double)rect.right(), (double)(rect.right()+mag*cos(angle))));
-		break;
-
-		case Middle:
-			{
-			mag *= 0.5;
-			rect.setTop(QMIN((double)rect.top(), (double)(rect.top() - fabs(mag*sin(angle)))));
-			rect.setBottom(QMAX((double)rect.bottom(), (double)(rect.bottom() + fabs(mag*sin(angle)))));
-			rect.setLeft(QMIN((double)rect.left(), (double)(rect.left() - fabs(mag*cos(angle)))));
-			rect.setRight(QMAX((double)rect.right(), (double)(rect.right() + fabs(mag*cos(angle)))));
-			}
-		break;
-
-		case Head:
-			rect.setTop(QMIN((double)rect.top(), (double)(rect.top() - mag*sin(angle))));
-			rect.setBottom(QMAX((double)rect.bottom(), (double)(rect.bottom() - mag*sin(angle))));
-			rect.setLeft(QMIN((double)rect.left(), (double)(rect.left() - mag*cos(angle))));
-			rect.setRight(QMAX((double)rect.right(), (double)(rect.right() - mag*cos(angle))));
-		break;
-		}
-	}
-return rect;
+QwtDoubleRect VectorCurve::boundingRect() const {
+  QwtDoubleRect rect = QwtPlotCurve::boundingRect();
+  QwtDoubleRect vrect = vectorEnd->boundingRect();
+
+  if (d_style == XYXY) {
+    rect.setTop(QMIN((double)rect.top(), (double)vrect.top()));
+    rect.setBottom(QMAX((double)rect.bottom(), (double)vrect.bottom()));
+    rect.setLeft(QMIN((double)rect.left(), (double)vrect.left()));
+    rect.setRight(QMAX((double)rect.right(), (double)vrect.right()));
+  } else {
+    const double angle = vectorEnd->x(0);
+    double mag = vectorEnd->y(0);
+    switch (d_position) {
+    case Tail:
+      rect.setTop(
+          QMIN((double)rect.top(), (double)(rect.top() + mag * sin(angle))));
+      rect.setBottom(QMAX((double)rect.bottom(),
+                          (double)(rect.bottom() + mag * sin(angle))));
+      rect.setLeft(
+          QMIN((double)rect.left(), (double)(rect.left() + mag * cos(angle))));
+      rect.setRight(QMAX((double)rect.right(),
+                         (double)(rect.right() + mag * cos(angle))));
+      break;
+
+    case Middle: {
+      mag *= 0.5;
+      rect.setTop(QMIN((double)rect.top(),
+                       (double)(rect.top() - fabs(mag * sin(angle)))));
+      rect.setBottom(QMAX((double)rect.bottom(),
+                          (double)(rect.bottom() + fabs(mag * sin(angle)))));
+      rect.setLeft(QMIN((double)rect.left(),
+                        (double)(rect.left() - fabs(mag * cos(angle)))));
+      rect.setRight(QMAX((double)rect.right(),
+                         (double)(rect.right() + fabs(mag * cos(angle)))));
+    } break;
+
+    case Head:
+      rect.setTop(
+          QMIN((double)rect.top(), (double)(rect.top() - mag * sin(angle))));
+      rect.setBottom(QMAX((double)rect.bottom(),
+                          (double)(rect.bottom() - mag * sin(angle))));
+      rect.setLeft(
+          QMIN((double)rect.left(), (double)(rect.left() - mag * cos(angle))));
+      rect.setRight(QMAX((double)rect.right(),
+                         (double)(rect.right() - mag * cos(angle))));
+      break;
+    }
+  }
+  return rect;
 }
 
-void VectorCurve::updateColumnNames(const QString& oldName, const QString& newName, bool updateTableName)
-{
-    if (updateTableName){
-        QString s = title().text();
-        QStringList lst = s.split("_", QString::SkipEmptyParts);
-        if (lst[0] == oldName)
-            setTitle(newName + "_" + lst[1]);
-
-        lst = d_x_column.split("_", QString::SkipEmptyParts);
-        if (lst[0] == oldName)
-            d_x_column = newName + "_" + lst[1];
-
-		lst = d_end_x_a.split("_", QString::SkipEmptyParts);
-        if (lst[0] == oldName)
-            d_end_x_a = newName + "_" + lst[1];
-
-		lst = d_end_y_m.split("_", QString::SkipEmptyParts);
-        if (lst[0] == oldName)
-            d_end_y_m = newName + "_" + lst[1];
-    } else {
-        if (title().text() == oldName)
-            setTitle(newName);
-        if (d_x_column == oldName)
-            d_x_column = newName;
-		if (d_end_x_a == oldName)
-            d_end_x_a = newName;
-		if (d_end_y_m == oldName)
-            d_end_y_m = newName;
-    }
+void VectorCurve::updateColumnNames(const QString &oldName,
+                                    const QString &newName,
+                                    bool updateTableName) {
+  if (updateTableName) {
+    QString s = title().text();
+    QStringList lst = s.split("_", QString::SkipEmptyParts);
+    if (lst[0] == oldName)
+      setTitle(newName + "_" + lst[1]);
+
+    lst = d_x_column.split("_", QString::SkipEmptyParts);
+    if (lst[0] == oldName)
+      d_x_column = newName + "_" + lst[1];
+
+    lst = d_end_x_a.split("_", QString::SkipEmptyParts);
+    if (lst[0] == oldName)
+      d_end_x_a = newName + "_" + lst[1];
+
+    lst = d_end_y_m.split("_", QString::SkipEmptyParts);
+    if (lst[0] == oldName)
+      d_end_y_m = newName + "_" + lst[1];
+  } else {
+    if (title().text() == oldName)
+      setTitle(newName);
+    if (d_x_column == oldName)
+      d_x_column = newName;
+    if (d_end_x_a == oldName)
+      d_end_x_a = newName;
+    if (d_end_y_m == oldName)
+      d_end_y_m = newName;
+  }
 }
 
-QString VectorCurve::plotAssociation() const
-{
-    QString base = d_x_column + "(X)," + title().text() + "(Y)," + d_end_x_a;
-    if (d_style == XYAM)
-        base += "(A)," + d_end_y_m + "(M)";
-    else
-        base += "(X)," + d_end_y_m + "(Y)";
+QString VectorCurve::plotAssociation() const {
+  QString base = d_x_column + "(X)," + title().text() + "(Y)," + d_end_x_a;
+  if (d_style == XYAM)
+    base += "(A)," + d_end_y_m + "(M)";
+  else
+    base += "(X)," + d_end_y_m + "(Y)";
 
-    if (!d_labels_column.isEmpty())
-        base += "," + d_labels_column + "(L)";
+  if (!d_labels_column.isEmpty())
+    base += "," + d_labels_column + "(L)";
 
-	return base;
+  return base;
 }
 
-bool VectorCurve::updateData(Table *t, const QString& colName)
-{
-	if (d_table != t ||
-	   (colName != title().text() && d_x_column != colName && d_end_x_a != colName && d_end_y_m != colName))
-		return false;
+bool VectorCurve::updateData(Table *t, const QString &colName) {
+  if (d_table != t || (colName != title().text() && d_x_column != colName &&
+                       d_end_x_a != colName && d_end_y_m != colName))
+    return false;
 
-	loadData();
-	return true;
+  loadData();
+  return true;
 }
 
-void VectorCurve::loadData()
-{
-    if (!plot())
-        return;
-
-	int xcol = d_table->colIndex(d_x_column);
-	int ycol = d_table->colIndex(title().text());
-	int endXCol = d_table->colIndex(d_end_x_a);
-	int endYCol = d_table->colIndex(d_end_y_m);
-
-	int rows = abs(d_end_row - d_start_row) + 1;
-    QVector<double> X(rows), Y(rows), X2(rows), Y2(rows);
-    int size = 0;
-    QLocale locale = plot()->locale();
-	for (int i = d_start_row; i <= d_end_row; i++){
-		QString xval = d_table->text(i, xcol);
-		QString yval = d_table->text(i, ycol);
-		QString xend = d_table->text(i, endXCol);
-		QString yend = d_table->text(i, endYCol);
-		if (!xval.isEmpty() && !yval.isEmpty() && !xend.isEmpty() && !yend.isEmpty()){
-		    bool valid_data = true;
-			X[size] = locale.toDouble(xval, &valid_data);
-			if (!valid_data)
-                continue;
-            Y[size] = locale.toDouble(yval, &valid_data);
-            if (!valid_data)
-                continue;
-			X2[size] = locale.toDouble(xend, &valid_data);
-			if (!valid_data)
-                continue;
-            Y2[size] = locale.toDouble(yend, &valid_data);
-			if (valid_data)
-                size++;
-		}
-	}
-
-	if (!size)
-		return;
-
-    X.resize(size); Y.resize(size); X2.resize(size); Y2.resize(size);
-	setData(X.data(), Y.data(), size);
-	foreach(DataCurve *c, d_error_bars)
-        c->setData(X.data(), Y.data(), size);
-	setVectorEnd(X2, Y2);
+void VectorCurve::loadData() {
+  if (!plot())
+    return;
+
+  int xcol = d_table->colIndex(d_x_column);
+  int ycol = d_table->colIndex(title().text());
+  int endXCol = d_table->colIndex(d_end_x_a);
+  int endYCol = d_table->colIndex(d_end_y_m);
+
+  int rows = abs(d_end_row - d_start_row) + 1;
+  QVector<double> X(rows), Y(rows), X2(rows), Y2(rows);
+  int size = 0;
+  QLocale locale = plot()->locale();
+  for (int i = d_start_row; i <= d_end_row; i++) {
+    QString xval = d_table->text(i, xcol);
+    QString yval = d_table->text(i, ycol);
+    QString xend = d_table->text(i, endXCol);
+    QString yend = d_table->text(i, endYCol);
+    if (!xval.isEmpty() && !yval.isEmpty() && !xend.isEmpty() &&
+        !yend.isEmpty()) {
+      bool valid_data = true;
+      X[size] = locale.toDouble(xval, &valid_data);
+      if (!valid_data)
+        continue;
+      Y[size] = locale.toDouble(yval, &valid_data);
+      if (!valid_data)
+        continue;
+      X2[size] = locale.toDouble(xend, &valid_data);
+      if (!valid_data)
+        continue;
+      Y2[size] = locale.toDouble(yend, &valid_data);
+      if (valid_data)
+        size++;
+    }
+  }
+
+  if (!size)
+    return;
+
+  X.resize(size);
+  Y.resize(size);
+  X2.resize(size);
+  Y2.resize(size);
+  setData(X.data(), Y.data(), size);
+  foreach (DataCurve *c, d_error_bars)
+    c->setData(X.data(), Y.data(), size);
+  setVectorEnd(X2, Y2);
 }
 
-VectorCurve::~VectorCurve()
-{
-delete vectorEnd;
-}
+VectorCurve::~VectorCurve() { delete vectorEnd; }
diff --git a/MantidPlot/src/VectorCurve.h b/MantidPlot/src/VectorCurve.h
index 657262b375de29c540825111c16271ec69581dce..2541c8c39755ffd82a2080fcefe799eba36da6af 100644
--- a/MantidPlot/src/VectorCurve.h
+++ b/MantidPlot/src/VectorCurve.h
@@ -2,7 +2,8 @@
     File                 : VectorCurve.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Vector curve class
 
@@ -35,72 +36,73 @@
 class QwtPlot;
 
 //! Vector curve class
-class VectorCurve: public DataCurve
-{
+class VectorCurve : public DataCurve {
 public:
-	enum VectorStyle{XYXY, XYAM};
+  enum VectorStyle { XYXY, XYAM };
 
-	VectorCurve(VectorStyle style, Table *t, const QString& xColName, const char *name,
-				const QString& endCol1, const QString& endCol2, int startRow, int endRow);
-        ~VectorCurve() override;
+  VectorCurve(VectorStyle style, Table *t, const QString &xColName,
+              const char *name, const QString &endCol1, const QString &endCol2,
+              int startRow, int endRow);
+  ~VectorCurve() override;
 
-        enum Position{Tail, Middle, Head};
+  enum Position { Tail, Middle, Head };
 
-	void copy(const VectorCurve *vc);
+  void copy(const VectorCurve *vc);
 
-        QwtDoubleRect boundingRect() const override;
+  QwtDoubleRect boundingRect() const override;
 
-        using DataCurve::draw; // Unhide base class method (avoids Intel compiler warning)
-        void draw(QPainter *painter, const QwtScaleMap &xMap,
-                  const QwtScaleMap &yMap, int from, int to) const override;
+  using DataCurve::draw; // Unhide base class method (avoids Intel compiler
+                         // warning)
+  void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+            int from, int to) const override;
 
-        void drawVector(QPainter *painter, const QwtScaleMap &xMap,
-		const QwtScaleMap &yMap, int from, int to) const;
+  void drawVector(QPainter *painter, const QwtScaleMap &xMap,
+                  const QwtScaleMap &yMap, int from, int to) const;
 
-	void drawArrowHead(QPainter *p, int xs, int ys, int xe, int ye) const;
-	double theta(int x0, int y0, int x1, int y1) const;
+  void drawArrowHead(QPainter *p, int xs, int ys, int xe, int ye) const;
+  double theta(int x0, int y0, int x1, int y1) const;
 
-	QString vectorEndXAColName(){return d_end_x_a;};
-	QString vectorEndYMColName(){return d_end_y_m;};
-	void setVectorEnd(const QString& xColName, const QString& yColName);
-	void setVectorEnd(const QwtArray<double>&x, const QwtArray<double>&y);
+  QString vectorEndXAColName() { return d_end_x_a; };
+  QString vectorEndYMColName() { return d_end_y_m; };
+  void setVectorEnd(const QString &xColName, const QString &yColName);
+  void setVectorEnd(const QwtArray<double> &x, const QwtArray<double> &y);
 
-	double width();
-	void setWidth(double w);
+  double width();
+  void setWidth(double w);
 
-	QColor color();
-	void setColor(const QColor& c);
+  QColor color();
+  void setColor(const QColor &c);
 
-	int headLength(){return d_headLength;};
-	void setHeadLength(int l);
+  int headLength() { return d_headLength; };
+  void setHeadLength(int l);
 
-	int headAngle(){return d_headAngle;};
-	void setHeadAngle(int a);
+  int headAngle() { return d_headAngle; };
+  void setHeadAngle(int a);
 
-	bool filledArrowHead(){return filledArrow;};
-	void fillArrowHead(bool fill);
+  bool filledArrowHead() { return filledArrow; };
+  void fillArrowHead(bool fill);
 
-	int position(){return d_position;};
-	void setPosition(int pos){d_position = pos;};
+  int position() { return d_position; };
+  void setPosition(int pos) { d_position = pos; };
 
-	int vectorStyle(){return d_style;};
-	void setVectorStyle(int style){d_style = style;};
+  int vectorStyle() { return d_style; };
+  void setVectorStyle(int style) { d_style = style; };
 
-        bool updateData(Table *t, const QString &colName) override;
-        void loadData() override;
+  bool updateData(Table *t, const QString &colName) override;
+  void loadData() override;
 
-        QString plotAssociation() const override;
-        void updateColumnNames(const QString &oldName, const QString &newName,
-                               bool updateTableName) override;
+  QString plotAssociation() const override;
+  void updateColumnNames(const QString &oldName, const QString &newName,
+                         bool updateTableName) override;
 
 protected:
-	QwtArrayData *vectorEnd;
-	QPen pen;
-	bool filledArrow;
-	int d_style, d_headLength, d_headAngle, d_position;
+  QwtArrayData *vectorEnd;
+  QPen pen;
+  bool filledArrow;
+  int d_style, d_headLength, d_headAngle, d_position;
 
-	QString d_end_x_a;
-	QString d_end_y_m;
+  QString d_end_x_a;
+  QString d_end_y_m;
 };
 
 #endif
diff --git a/MantidPlot/src/analysis/fft2D.cpp b/MantidPlot/src/analysis/fft2D.cpp
index 751bd7c339f0ffac320d754c0d73f096dc168a36..eff9fbd6a74df76033bb113e397e63120f68065f 100644
--- a/MantidPlot/src/analysis/fft2D.cpp
+++ b/MantidPlot/src/analysis/fft2D.cpp
@@ -31,144 +31,165 @@
 //#define _USE_MATH_DEFINES
 #include <math.h>
 #include <QVarLengthArray>
-void fft(double* x_int_re, double* x_int_im, int taille)
-{
-    int size_2=taille>>1;
-    double base = 2*M_PI/taille;
-    const double SQ_2 = M_SQRT2;
-    QVarLengthArray<double> pair_re(size_2), pair_im(size_2), impair_re(size_2), impair_im(size_2);//double pair_re[size_2], pair_im[size_2], impair_re[size_2], impair_im[size_2];
-    for(int i=0; i<size_2; i++){
-        int tmp1=(i<<1);
-        pair_re[i]=x_int_re[tmp1];
-        pair_im[i]=x_int_im[tmp1];
-        impair_re[i]=x_int_re[tmp1+1];
-        impair_im[i]=x_int_im[tmp1+1];
-    }
+void fft(double *x_int_re, double *x_int_im, int taille) {
+  int size_2 = taille >> 1;
+  double base = 2 * M_PI / taille;
+  const double SQ_2 = M_SQRT2;
+  QVarLengthArray<double> pair_re(size_2), pair_im(size_2), impair_re(size_2),
+      impair_im(size_2); // double pair_re[size_2], pair_im[size_2],
+                         // impair_re[size_2], impair_im[size_2];
+  for (int i = 0; i < size_2; i++) {
+    int tmp1 = (i << 1);
+    pair_re[i] = x_int_re[tmp1];
+    pair_im[i] = x_int_im[tmp1];
+    impair_re[i] = x_int_re[tmp1 + 1];
+    impair_im[i] = x_int_im[tmp1 + 1];
+  }
 
-    if(taille>2){
-        fft(pair_re.data(),pair_im.data(),size_2);
-        fft(impair_re.data(),impair_im.data(),size_2);
-    }
+  if (taille > 2) {
+    fft(pair_re.data(), pair_im.data(), size_2);
+    fft(impair_re.data(), impair_im.data(), size_2);
+  }
 
-    for(int i=0; i<size_2; i++){
-        double tmp=base*i;
-        double tmpcos=cos(tmp);
-        double tmpsin=sin(tmp);
-        x_int_re[i]=(pair_re[i]+impair_re[i]*tmpcos+impair_im[i]*tmpsin)/SQ_2;
-        x_int_im[i]=(pair_im[i]+impair_im[i]*tmpcos-impair_re[i]*tmpsin)/SQ_2;
-        x_int_re[i+size_2]=(pair_re[i]-impair_re[i]*tmpcos-impair_im[i]*tmpsin)/SQ_2;
-        x_int_im[i+size_2]=(pair_im[i]-impair_im[i]*tmpcos+impair_re[i]*tmpsin)/SQ_2;
-    }
+  for (int i = 0; i < size_2; i++) {
+    double tmp = base * i;
+    double tmpcos = cos(tmp);
+    double tmpsin = sin(tmp);
+    x_int_re[i] =
+        (pair_re[i] + impair_re[i] * tmpcos + impair_im[i] * tmpsin) / SQ_2;
+    x_int_im[i] =
+        (pair_im[i] + impair_im[i] * tmpcos - impair_re[i] * tmpsin) / SQ_2;
+    x_int_re[i + size_2] =
+        (pair_re[i] - impair_re[i] * tmpcos - impair_im[i] * tmpsin) / SQ_2;
+    x_int_im[i + size_2] =
+        (pair_im[i] - impair_im[i] * tmpcos + impair_re[i] * tmpsin) / SQ_2;
+  }
 }
 
-void fft_inv(double* x_int_re, double* x_int_im, int taille)
-{
-    int size_2=taille>>1;
-    double base=2*M_PI/taille;
-    const double SQ_2 = M_SQRT2; // const double SQ_2=sqrt(2);
-    QVarLengthArray<double> pair_re(size_2), pair_im(size_2), impair_re(size_2), impair_im(size_2);//double pair_re[size_2], pair_im[size_2], impair_re[size_2], impair_im[size_2];
-    for(int i=0; i<size_2; i++){
-        int tmp1=i<<1;
-        pair_re[i]=x_int_re[tmp1];
-        pair_im[i]=x_int_im[tmp1];
-        impair_re[i]=x_int_re[tmp1+1];
-        impair_im[i]=x_int_im[tmp1+1];
-    }
+void fft_inv(double *x_int_re, double *x_int_im, int taille) {
+  int size_2 = taille >> 1;
+  double base = 2 * M_PI / taille;
+  const double SQ_2 = M_SQRT2; // const double SQ_2=sqrt(2);
+  QVarLengthArray<double> pair_re(size_2), pair_im(size_2), impair_re(size_2),
+      impair_im(size_2); // double pair_re[size_2], pair_im[size_2],
+                         // impair_re[size_2], impair_im[size_2];
+  for (int i = 0; i < size_2; i++) {
+    int tmp1 = i << 1;
+    pair_re[i] = x_int_re[tmp1];
+    pair_im[i] = x_int_im[tmp1];
+    impair_re[i] = x_int_re[tmp1 + 1];
+    impair_im[i] = x_int_im[tmp1 + 1];
+  }
 
-    if(taille>2){
-        fft_inv(pair_re.data(), pair_im.data(),size_2);//fft_inv(pair_re, pair_im,size_2);
-        fft_inv(impair_re.data(), impair_im.data(),size_2);//fft_inv(impair_re, impair_im,size_2);
-    }
+  if (taille > 2) {
+    fft_inv(pair_re.data(), pair_im.data(),
+            size_2); // fft_inv(pair_re, pair_im,size_2);
+    fft_inv(impair_re.data(), impair_im.data(),
+            size_2); // fft_inv(impair_re, impair_im,size_2);
+  }
 
-    for(int i=0; i<size_2; i++){
-        double tmp=base*i;
-        double tmpcos=cos(tmp);
-        double tmpsin=sin(tmp);
-        x_int_re[i]=(pair_re[i]+impair_re[i]*tmpcos-impair_im[i]*tmpsin)/SQ_2;
-        x_int_im[i]=(pair_im[i]+impair_im[i]*tmpcos+impair_re[i]*tmpsin)/SQ_2;
-        x_int_re[i+size_2]=(pair_re[i]-impair_re[i]*tmpcos+impair_im[i]*tmpsin)/SQ_2;
-        x_int_im[i+size_2]=(pair_im[i]-impair_im[i]*tmpcos-impair_re[i]*tmpsin)/SQ_2;
-    }
+  for (int i = 0; i < size_2; i++) {
+    double tmp = base * i;
+    double tmpcos = cos(tmp);
+    double tmpsin = sin(tmp);
+    x_int_re[i] =
+        (pair_re[i] + impair_re[i] * tmpcos - impair_im[i] * tmpsin) / SQ_2;
+    x_int_im[i] =
+        (pair_im[i] + impair_im[i] * tmpcos + impair_re[i] * tmpsin) / SQ_2;
+    x_int_re[i + size_2] =
+        (pair_re[i] - impair_re[i] * tmpcos + impair_im[i] * tmpsin) / SQ_2;
+    x_int_im[i + size_2] =
+        (pair_im[i] - impair_im[i] * tmpcos - impair_re[i] * tmpsin) / SQ_2;
+  }
 }
 
-void fft2d(double **xtre, double **xtim, int width, int height)
-{
-    double **xint_re = Matrix::allocateMatrixData(height, width);
-    if (!xint_re)
-        return;
-    double **xint_im = Matrix::allocateMatrixData(height, width);
-    if (!xint_im){
-        Matrix::freeMatrixData(xint_re, height);
-        return;
-    }
+void fft2d(double **xtre, double **xtim, int width, int height) {
+  double **xint_re = Matrix::allocateMatrixData(height, width);
+  if (!xint_re)
+    return;
+  double **xint_im = Matrix::allocateMatrixData(height, width);
+  if (!xint_im) {
+    Matrix::freeMatrixData(xint_re, height);
+    return;
+  }
 
-    QVarLengthArray<double> x_int_l(width), x_int2_l(width), x_int_c(height), x_int2_c(height);//double x_int_l[width], x_int2_l[width], x_int_c[height], x_int2_c[height];
-    for(int k=0; k<height; k++){
-        for(int j=0; j<width; j++){
-            //x_int_l[j] = x[k][j];
-            //x_int2_l[j] = 0.0;
+  QVarLengthArray<double> x_int_l(width), x_int2_l(width), x_int_c(height),
+      x_int2_c(height); // double x_int_l[width], x_int2_l[width],
+                        // x_int_c[height], x_int2_c[height];
+  for (int k = 0; k < height; k++) {
+    for (int j = 0; j < width; j++) {
+      // x_int_l[j] = x[k][j];
+      // x_int2_l[j] = 0.0;
 
-            x_int_l[j] = xtre[k][j];
-            x_int2_l[j] = xtim[k][j];
-        }
-        fft(x_int_l.data(), x_int2_l.data(), width);//fft(x_int_l, x_int2_l, width);
-        for(int j=0; j<width; j++){
-            xint_re[k][j]=x_int_l[j];
-            xint_im[k][j]=x_int2_l[j];
-        }
+      x_int_l[j] = xtre[k][j];
+      x_int2_l[j] = xtim[k][j];
     }
+    fft(x_int_l.data(), x_int2_l.data(),
+        width); // fft(x_int_l, x_int2_l, width);
+    for (int j = 0; j < width; j++) {
+      xint_re[k][j] = x_int_l[j];
+      xint_im[k][j] = x_int2_l[j];
+    }
+  }
 
-    for(int k=0; k<width; k++){
-        for(int i=0; i<height; i++){
-            x_int_c[i]=xint_re[i][k];
-            x_int2_c[i]=xint_im[i][k];
-        }
-        fft(x_int_c.data(),x_int2_c.data(), height) ;//fft(x_int_c,x_int2_c, height) ;
-        for(int i=0; i<height; i++){
-            xtre[(i+(height>>1))%height][(k+(width>>1))%width]=x_int_c[i];
-            xtim[(i+(height>>1))%height][(k+(width>>1))%width]=x_int2_c[i];
-        }
+  for (int k = 0; k < width; k++) {
+    for (int i = 0; i < height; i++) {
+      x_int_c[i] = xint_re[i][k];
+      x_int2_c[i] = xint_im[i][k];
     }
-    Matrix::freeMatrixData(xint_re, height);
-    Matrix::freeMatrixData(xint_im, height);
+    fft(x_int_c.data(), x_int2_c.data(),
+        height); // fft(x_int_c,x_int2_c, height) ;
+    for (int i = 0; i < height; i++) {
+      xtre[(i + (height >> 1)) % height][(k + (width >> 1)) % width] =
+          x_int_c[i];
+      xtim[(i + (height >> 1)) % height][(k + (width >> 1)) % width] =
+          x_int2_c[i];
+    }
+  }
+  Matrix::freeMatrixData(xint_re, height);
+  Matrix::freeMatrixData(xint_im, height);
 }
 
-void fft2d_inv(double **xtre, double **xtim, double **xrec_re, double **xrec_im, int width, int height)
-{
-    double **xint_re = Matrix::allocateMatrixData(height, width);
-    if (!xint_re)
-        return;
-    double **xint_im = Matrix::allocateMatrixData(height, width);
-    if (!xint_im){
-        Matrix::freeMatrixData(xint_re, height);
-        return;
-    }
+void fft2d_inv(double **xtre, double **xtim, double **xrec_re, double **xrec_im,
+               int width, int height) {
+  double **xint_re = Matrix::allocateMatrixData(height, width);
+  if (!xint_re)
+    return;
+  double **xint_im = Matrix::allocateMatrixData(height, width);
+  if (!xint_im) {
+    Matrix::freeMatrixData(xint_re, height);
+    return;
+  }
 
-    QVarLengthArray<double> x_int_l(width), x_int2_l(width), x_int_c(height), x_int2_c(height);//double x_int_l[width], x_int2_l[width], x_int_c[height], x_int2_c[height];
-    for(int k=0; k<height; k++){
-        for(int j=0; j<width; j++){
-            int idx_h = (k+(height>>1))%height;
-            int idx_w = (j+(width>>1))%width;
-            x_int_l[j] = xtre[idx_h][idx_w];
-            x_int2_l[j] = xtim[idx_h][idx_w];
-        }
-        fft_inv(x_int_l.data(), x_int2_l.data(), width) ;//fft_inv(x_int_l, x_int2_l, width) ;
-        for(int j=0; j<width; j++){
-            xint_re[k][j] = x_int_l[j];
-            xint_im[k][j] = x_int2_l[j];
-        }
+  QVarLengthArray<double> x_int_l(width), x_int2_l(width), x_int_c(height),
+      x_int2_c(height); // double x_int_l[width], x_int2_l[width],
+                        // x_int_c[height], x_int2_c[height];
+  for (int k = 0; k < height; k++) {
+    for (int j = 0; j < width; j++) {
+      int idx_h = (k + (height >> 1)) % height;
+      int idx_w = (j + (width >> 1)) % width;
+      x_int_l[j] = xtre[idx_h][idx_w];
+      x_int2_l[j] = xtim[idx_h][idx_w];
     }
-    for(int k=0; k<width; k++){
-        for(int i=0; i<height; i++){
-            x_int_c[i] = xint_re[i][k];
-            x_int2_c[i] = xint_im[i][k];
-        }
-        fft_inv(x_int_c.data(),x_int2_c.data(), height) ;//fft_inv(x_int_c,x_int2_c, height) ;
-        for(int i=0; i<height; i++){
-            xrec_re[i][k] = x_int_c[i];
-            xrec_im[i][k] = x_int2_c[i];
-        }
+    fft_inv(x_int_l.data(), x_int2_l.data(),
+            width); // fft_inv(x_int_l, x_int2_l, width) ;
+    for (int j = 0; j < width; j++) {
+      xint_re[k][j] = x_int_l[j];
+      xint_im[k][j] = x_int2_l[j];
     }
-    Matrix::freeMatrixData(xint_re, height);
-    Matrix::freeMatrixData(xint_im, height);
+  }
+  for (int k = 0; k < width; k++) {
+    for (int i = 0; i < height; i++) {
+      x_int_c[i] = xint_re[i][k];
+      x_int2_c[i] = xint_im[i][k];
+    }
+    fft_inv(x_int_c.data(), x_int2_c.data(),
+            height); // fft_inv(x_int_c,x_int2_c, height) ;
+    for (int i = 0; i < height; i++) {
+      xrec_re[i][k] = x_int_c[i];
+      xrec_im[i][k] = x_int2_c[i];
+    }
+  }
+  Matrix::freeMatrixData(xint_re, height);
+  Matrix::freeMatrixData(xint_im, height);
 }
diff --git a/MantidPlot/src/analysis/fft2D.h b/MantidPlot/src/analysis/fft2D.h
index ba01593482fde9cf3ef311de84a121c74506ac99..8e81a0c9f1ebd17a9fa4398d7535d480769e6099 100644
--- a/MantidPlot/src/analysis/fft2D.h
+++ b/MantidPlot/src/analysis/fft2D.h
@@ -31,6 +31,7 @@
 #define FOURIER_H
 
 void fft2d(double **xtre, double **xtim, int width, int height);
-void fft2d_inv(double **xtre, double **xtim, double **xrec_re, double **xrec_im, int width, int height);
+void fft2d_inv(double **xtre, double **xtim, double **xrec_re, double **xrec_im,
+               int width, int height);
 
 #endif
diff --git a/MantidPlot/src/cursors.h b/MantidPlot/src/cursors.h
index 9089c4ff4fc13d2777430b3569cc1953cf8655d5..6bcacc896e2d574b38cf652317bdb55679995f67 100644
--- a/MantidPlot/src/cursors.h
+++ b/MantidPlot/src/cursors.h
@@ -4,7 +4,7 @@
     --------------------------------------------------------------------
     This file has been superceded by pixmaps.h, which holds ALL xpm
     char arrays.
-                           
+
  ***************************************************************************/
 
 #include "pixmaps.h"
diff --git a/MantidPlot/src/customevents.h b/MantidPlot/src/customevents.h
index ef8a744fb276fd1b920b7aa74b4a77a26fef6ac3..a47975cf655b02cfcd4e44b51dd1cb60cf28dad4 100644
--- a/MantidPlot/src/customevents.h
+++ b/MantidPlot/src/customevents.h
@@ -2,7 +2,7 @@
     File                 : customevents.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, 
+    Copyright            : (C) 2006 by Ion Vasilief,
                            Tilman Hoener zu Siederdissen,
                            Knut Franke
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net,
@@ -12,7 +12,7 @@
     Please use only event types defined here in order to avoid clashes.
     The lowest event ID not used by Qt is QEvent::User. See documentation
     of QEvent for details.
-                           
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -40,4 +40,3 @@
 #define SCRIPTING_CHANGE_EVENT QEvent::User
 
 #endif
-
diff --git a/MantidPlot/src/fit_gsl.cpp b/MantidPlot/src/fit_gsl.cpp
index b35212e5bb9658e3998cb7d090d1c85a369733fc..9366aef7b0ac886daf64dcc88fb156c7ec070aad 100644
--- a/MantidPlot/src/fit_gsl.cpp
+++ b/MantidPlot/src/fit_gsl.cpp
@@ -7,707 +7,718 @@
 #include <gsl/gsl_math.h>
 #include "fit_gsl.h"
 #include "MyParser.h"
-int expd3_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double t1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double t2=gsl_vector_get(x,3);
-    double A3=gsl_vector_get(x,4);
-    double t3=gsl_vector_get(x,5);
-    double y0=gsl_vector_get(x,6);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double Yi = A1 * exp (-X[i]*t1) + A2 * exp (-X[i]*t2) + A3 * exp (-X[i]*t3) +y0;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
-    return GSL_SUCCESS;
-}
-double expd3_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double t1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double t2=gsl_vector_get(x,3);
-    double A3=gsl_vector_get(x,4);
-    double t3=gsl_vector_get(x,5);
-    double y0=gsl_vector_get(x,6);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double dYi = ((A1 * exp (-X[i]*t1) + A2 * exp (-X[i]*t2) + A3 * exp (-X[i]*t3) +y0)-Y[i])/sigma[i];
-        val+=dYi * dYi;
-    }
-    return val;
-}
-int expd3_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double l1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double l2=gsl_vector_get(x,3);
-    double A3=gsl_vector_get(x,4);
-    double l3=gsl_vector_get(x,5);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj, */
-        /* where fi = (Yi - yi)/sigma[i],      */
-        /*       Yi = A1 * exp(-xi*l1) + A2 * exp(-xi*l2) +y0  */
-        /* and the xj are the parameters (A1,l1,A2,l2,y0) */
-        double t = X[i];
-        double s = sigma[i];
-        double e1 = exp(-t*l1)/s;
-        double e2 = exp(-t*l2)/s;
-        double e3 = exp(-t*l3)/s;
-        gsl_matrix_set (J, i, 0, e1);
-        gsl_matrix_set (J, i, 1, -t * A1 * e1);
-        gsl_matrix_set (J, i, 2, e2);
-        gsl_matrix_set (J, i, 3, -t * A2 * e2);
-        gsl_matrix_set (J, i, 4, e3);
-        gsl_matrix_set (J, i, 5, -t * A3 * e3);
-        gsl_matrix_set (J, i, 6, 1/s);
-    }
-    return GSL_SUCCESS;
-}
-int expd3_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    expd3_f (x, params, f);
-    expd3_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int expd2_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double t1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double t2=gsl_vector_get(x,3);
-    double y0=gsl_vector_get(x,4);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double Yi = A1 * exp (-X[i]*t1) + A2 * exp (-X[i]*t2) + y0;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
-    return GSL_SUCCESS;
-}
-double expd2_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double t1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double t2=gsl_vector_get(x,3);
-    double y0=gsl_vector_get(x,4);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double dYi = ((A1 * exp (-X[i]*t1) + A2 * exp (-X[i]*t2) + y0)-Y[i])/sigma[i];
-        val+=dYi * dYi;
-    }
-    return val;
-}
-int expd2_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1=gsl_vector_get(x,0);
-    double l1=gsl_vector_get(x,1);
-    double A2=gsl_vector_get(x,2);
-    double l2=gsl_vector_get(x,3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj, */
-        /* where fi = (Yi - yi)/sigma[i],      */
-        /*       Yi = A1 * exp(-xi*l1) + A2 * exp(-xi*l2) +y0  */
-        /* and the xj are the parameters (A1,l1,A2,l2,y0) */
-        double s = sigma[i];
-        double t = X[i];
-        double e1 = exp(-t*l1)/s;
-        double e2 = exp(-t*l2)/s;
-        gsl_matrix_set (J, i, 0, e1);
-        gsl_matrix_set (J, i, 1, -t * A1 * e1);
-        gsl_matrix_set (J, i, 2, e2);
-        gsl_matrix_set (J, i, 3, -t * A2 * e2);
-        gsl_matrix_set (J, i, 4, 1/s);
-    }
-    return GSL_SUCCESS;
-}
-int expd2_fdf (const gsl_vector * x, void *params,
-               gsl_vector * f, gsl_matrix * J) {
-    expd2_f (x, params, f);
-    expd2_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int exp_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A = gsl_vector_get (x, 0);
-    double lambda = gsl_vector_get (x, 1);
-    double b = gsl_vector_get (x, 2);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double Yi = A * exp (-lambda * X[i]) + b;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
-    return GSL_SUCCESS;
-}
-double exp_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A = gsl_vector_get (x, 0);
-    double lambda = gsl_vector_get (x, 1);
-    double b = gsl_vector_get (x, 2);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double dYi = ((A * exp (-lambda * X[i]) + b)-Y[i])/sigma[i];
-        val+=dYi * dYi;
-    }
-    return val;
-}
-int exp_df (const gsl_vector * x, void *params,
-            gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A = gsl_vector_get (x, 0);
-    double lambda = gsl_vector_get (x, 1);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj, */
-        /* where fi = (Yi - yi)/sigma[i],      */
-        /*       Yi = A * exp(-lambda * i) + b  */
-        /* and the xj are the parameters (A,lambda,b) */
-        double t = X[i];
-        double s = sigma[i];
-        double e = exp(-lambda * t);
-        gsl_matrix_set (J, i, 0, e/s);
-        gsl_matrix_set (J, i, 1, -t * A * e/s);
-        gsl_matrix_set (J, i, 2, 1/s);
-    }
-    return GSL_SUCCESS;
-}
-int exp_fdf (const gsl_vector * x, void *params,
-             gsl_vector * f, gsl_matrix * J) {
-    exp_f (x, params, f);
-    exp_df (x, params, J);
-    return GSL_SUCCESS;
+int expd3_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double t1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double t2 = gsl_vector_get(x, 3);
+  double A3 = gsl_vector_get(x, 4);
+  double t3 = gsl_vector_get(x, 5);
+  double y0 = gsl_vector_get(x, 6);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double Yi =
+        A1 * exp(-X[i] * t1) + A2 * exp(-X[i] * t2) + A3 * exp(-X[i] * t3) + y0;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
+  return GSL_SUCCESS;
+}
+double expd3_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double t1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double t2 = gsl_vector_get(x, 3);
+  double A3 = gsl_vector_get(x, 4);
+  double t3 = gsl_vector_get(x, 5);
+  double y0 = gsl_vector_get(x, 6);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double dYi = ((A1 * exp(-X[i] * t1) + A2 * exp(-X[i] * t2) +
+                   A3 * exp(-X[i] * t3) + y0) -
+                  Y[i]) /
+                 sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
+}
+int expd3_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double l1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double l2 = gsl_vector_get(x, 3);
+  double A3 = gsl_vector_get(x, 4);
+  double l3 = gsl_vector_get(x, 5);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj, */
+    /* where fi = (Yi - yi)/sigma[i],      */
+    /*       Yi = A1 * exp(-xi*l1) + A2 * exp(-xi*l2) +y0  */
+    /* and the xj are the parameters (A1,l1,A2,l2,y0) */
+    double t = X[i];
+    double s = sigma[i];
+    double e1 = exp(-t * l1) / s;
+    double e2 = exp(-t * l2) / s;
+    double e3 = exp(-t * l3) / s;
+    gsl_matrix_set(J, i, 0, e1);
+    gsl_matrix_set(J, i, 1, -t * A1 * e1);
+    gsl_matrix_set(J, i, 2, e2);
+    gsl_matrix_set(J, i, 3, -t * A2 * e2);
+    gsl_matrix_set(J, i, 4, e3);
+    gsl_matrix_set(J, i, 5, -t * A3 * e3);
+    gsl_matrix_set(J, i, 6, 1 / s);
+  }
+  return GSL_SUCCESS;
+}
+int expd3_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) {
+  expd3_f(x, params, f);
+  expd3_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int expd2_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double t1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double t2 = gsl_vector_get(x, 3);
+  double y0 = gsl_vector_get(x, 4);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double Yi = A1 * exp(-X[i] * t1) + A2 * exp(-X[i] * t2) + y0;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
+  return GSL_SUCCESS;
+}
+double expd2_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double t1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double t2 = gsl_vector_get(x, 3);
+  double y0 = gsl_vector_get(x, 4);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double dYi =
+        ((A1 * exp(-X[i] * t1) + A2 * exp(-X[i] * t2) + y0) - Y[i]) / sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
+}
+int expd2_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double l1 = gsl_vector_get(x, 1);
+  double A2 = gsl_vector_get(x, 2);
+  double l2 = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj, */
+    /* where fi = (Yi - yi)/sigma[i],      */
+    /*       Yi = A1 * exp(-xi*l1) + A2 * exp(-xi*l2) +y0  */
+    /* and the xj are the parameters (A1,l1,A2,l2,y0) */
+    double s = sigma[i];
+    double t = X[i];
+    double e1 = exp(-t * l1) / s;
+    double e2 = exp(-t * l2) / s;
+    gsl_matrix_set(J, i, 0, e1);
+    gsl_matrix_set(J, i, 1, -t * A1 * e1);
+    gsl_matrix_set(J, i, 2, e2);
+    gsl_matrix_set(J, i, 3, -t * A2 * e2);
+    gsl_matrix_set(J, i, 4, 1 / s);
+  }
+  return GSL_SUCCESS;
+}
+int expd2_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) {
+  expd2_f(x, params, f);
+  expd2_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int exp_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A = gsl_vector_get(x, 0);
+  double lambda = gsl_vector_get(x, 1);
+  double b = gsl_vector_get(x, 2);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double Yi = A * exp(-lambda * X[i]) + b;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
+  return GSL_SUCCESS;
+}
+double exp_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A = gsl_vector_get(x, 0);
+  double lambda = gsl_vector_get(x, 1);
+  double b = gsl_vector_get(x, 2);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double dYi = ((A * exp(-lambda * X[i]) + b) - Y[i]) / sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
+}
+int exp_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A = gsl_vector_get(x, 0);
+  double lambda = gsl_vector_get(x, 1);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj, */
+    /* where fi = (Yi - yi)/sigma[i],      */
+    /*       Yi = A * exp(-lambda * i) + b  */
+    /* and the xj are the parameters (A,lambda,b) */
+    double t = X[i];
+    double s = sigma[i];
+    double e = exp(-lambda * t);
+    gsl_matrix_set(J, i, 0, e / s);
+    gsl_matrix_set(J, i, 1, -t * A * e / s);
+    gsl_matrix_set(J, i, 2, 1 / s);
+  }
+  return GSL_SUCCESS;
+}
+int exp_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) {
+  exp_f(x, params, f);
+  exp_df(x, params, J);
+  return GSL_SUCCESS;
 }
 
-int gauss_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double Y0 = gsl_vector_get (x, 0);
-    double A = gsl_vector_get (x, 1);
-    double C = gsl_vector_get (x, 2);
-    double w = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double diff=X[i]-C;
-        double Yi = A*exp(-0.5*diff*diff/(w*w))+Y0;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
-    return GSL_SUCCESS;
-}
-double gauss_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double Y0 = gsl_vector_get (x, 0);
-    double A = gsl_vector_get (x, 1);
-    double C = gsl_vector_get (x, 2);
-    double w = gsl_vector_get (x, 3);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double diff=X[i]-C;
-        double dYi = ((A*exp(-0.5*diff*diff/(w*w))+Y0)-Y[i])/sigma[i];
-        val+=dYi * dYi;
-    }
-    return val;
-}
-int gauss_df (const gsl_vector * x, void *params,
-              gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A = gsl_vector_get (x, 1);
-    double C = gsl_vector_get (x, 2);
-    double w = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj,	 */
-        /* where fi = Yi - yi,					*/
-        /* Yi = y=A*exp[-(Xi-xc)^2/(2*w*w)]+B		*/
-        /* and the xj are the parameters (B,A,C,w) */
-        double s = sigma[i];
-        double diff = X[i]-C;
-        double e = exp(-0.5*diff*diff/(w*w))/s;
-        gsl_matrix_set (J, i, 0, 1/s);
-        gsl_matrix_set (J, i, 1, e);
-        gsl_matrix_set (J, i, 2, diff*A*e/(w*w));
-        gsl_matrix_set (J, i, 3, diff*diff*A*e/(w*w*w));
-    }
-    return GSL_SUCCESS;
-}
-int gauss_fdf (const gsl_vector * x, void *params,
-               gsl_vector * f, gsl_matrix * J) {
-    gauss_f (x, params, f);
-    gauss_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int gauss_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w2 = new double[peaks];
-    double offset = gsl_vector_get (x, p-1);
-    size_t i,j;
-    for (i = 0; i < peaks; i++) {
-        xc[i] = gsl_vector_get(x, 3*i+1);
-        double wi = gsl_vector_get(x, 3*i+2);
-        a[i] = sqrt(M_2_PI)*gsl_vector_get(x, 3*i)/wi;
-        w2[i] = wi*wi;
-    }
-    for (i = 0; i < n; i++) {
-        double res = 0;
-        for (j = 0; j < peaks; j++) {
-            double diff=X[i]-xc[j];
-            res += a[j]*exp(-2*diff*diff/w2[j]);
-        }
-        gsl_vector_set(f, i, (res + offset - Y[i])/sigma[i]);
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w2;
-    return GSL_SUCCESS;
-}
-double gauss_multi_peak_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w2 = new double[peaks];
-    double offset = gsl_vector_get (x, p-1);
-    size_t i,j;
-    double val=0;
-    for (i = 0; i < peaks; i++) {
-        xc[i] = gsl_vector_get(x, 3*i+1);
-        double wi = gsl_vector_get(x, 3*i+2);
-        a[i] = sqrt(M_2_PI)*gsl_vector_get(x, 3*i)/wi;
-        w2[i] = wi*wi;
-    }
+int gauss_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double Y0 = gsl_vector_get(x, 0);
+  double A = gsl_vector_get(x, 1);
+  double C = gsl_vector_get(x, 2);
+  double w = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double diff = X[i] - C;
+    double Yi = A * exp(-0.5 * diff * diff / (w * w)) + Y0;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
+  return GSL_SUCCESS;
+}
+double gauss_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double Y0 = gsl_vector_get(x, 0);
+  double A = gsl_vector_get(x, 1);
+  double C = gsl_vector_get(x, 2);
+  double w = gsl_vector_get(x, 3);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double diff = X[i] - C;
+    double dYi =
+        ((A * exp(-0.5 * diff * diff / (w * w)) + Y0) - Y[i]) / sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
+}
+int gauss_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A = gsl_vector_get(x, 1);
+  double C = gsl_vector_get(x, 2);
+  double w = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj,	 */
+    /* where fi = Yi - yi,					*/
+    /* Yi = y=A*exp[-(Xi-xc)^2/(2*w*w)]+B		*/
+    /* and the xj are the parameters (B,A,C,w) */
+    double s = sigma[i];
+    double diff = X[i] - C;
+    double e = exp(-0.5 * diff * diff / (w * w)) / s;
+    gsl_matrix_set(J, i, 0, 1 / s);
+    gsl_matrix_set(J, i, 1, e);
+    gsl_matrix_set(J, i, 2, diff * A * e / (w * w));
+    gsl_matrix_set(J, i, 3, diff * diff * A * e / (w * w * w));
+  }
+  return GSL_SUCCESS;
+}
+int gauss_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) {
+  gauss_f(x, params, f);
+  gauss_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int gauss_multi_peak_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w2 = new double[peaks];
+  double offset = gsl_vector_get(x, p - 1);
+  size_t i, j;
+  for (i = 0; i < peaks; i++) {
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    double wi = gsl_vector_get(x, 3 * i + 2);
+    a[i] = sqrt(M_2_PI) * gsl_vector_get(x, 3 * i) / wi;
+    w2[i] = wi * wi;
+  }
+  for (i = 0; i < n; i++) {
+    double res = 0;
+    for (j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      res += a[j] * exp(-2 * diff * diff / w2[j]);
+    }
+    gsl_vector_set(f, i, (res + offset - Y[i]) / sigma[i]);
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w2;
+  return GSL_SUCCESS;
+}
+double gauss_multi_peak_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w2 = new double[peaks];
+  double offset = gsl_vector_get(x, p - 1);
+  size_t i, j;
+  double val = 0;
+  for (i = 0; i < peaks; i++) {
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    double wi = gsl_vector_get(x, 3 * i + 2);
+    a[i] = sqrt(M_2_PI) * gsl_vector_get(x, 3 * i) / wi;
+    w2[i] = wi * wi;
+  }
 
-    for (i = 0; i < n; i++) {
-        double res = 0;
-        for (j = 0; j < peaks; j++) {
-            double diff=X[i]-xc[j];
-            res+= a[j]*exp(-2*diff*diff/w2[j]);
-        }
-        double t = (res+offset-Y[i])/sigma[i];
-        val += t*t;
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w2;
-    return val;
-}
-int gauss_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w = new double[peaks];
-    size_t i,j;
-    for (i = 0; i<peaks; i++) {
-        a[i] = gsl_vector_get (x, 3*i);
-        xc[i] = gsl_vector_get (x, 3*i+1);
-        w[i] = gsl_vector_get (x, 3*i+2);
-    }
-    for (i = 0; i<n; i++) {
-        double s = sigma[i];
-        for (j = 0; j<peaks; j++) {
-            double diff = X[i]-xc[j];
-            double w2 = w[j]*w[j];
-            double e = sqrt(M_2_PI)/s*exp(-2*diff*diff/w2);
-            gsl_matrix_set (J, i, 3*j, e/w[j]);
-            gsl_matrix_set (J, i, 3*j+1, 4*diff*a[j]*e/(w2*w[j]));
-            gsl_matrix_set (J, i, 3*j+2, a[j]/w2*e*(4*diff*diff/w2 - 1));
-        }
-        gsl_matrix_set (J, i, p-1, 1.0/s);
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w;
-    return GSL_SUCCESS;
-}
-int gauss_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    gauss_multi_peak_f (x, params, f);
-    gauss_multi_peak_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int lorentz_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w = new double[peaks];
-    double offset = gsl_vector_get (x, p-1);
-    size_t i,j;
-    for (i = 0; i < peaks; i++) {
-        a[i] = gsl_vector_get(x, 3*i);
-        xc[i] = gsl_vector_get(x, 3*i+1);
-        w[i] = gsl_vector_get(x, 3*i+2);
-    }
-    for (i = 0; i < n; i++) {
-        double res = 0;
-        for (j = 0; j < peaks; j++) {
-            double diff=X[i]-xc[j];
-            res += a[j]*w[j]/(4*diff*diff+w[j]*w[j]);
-        }
-        gsl_vector_set(f, i, (M_2_PI*res + offset - Y[i])/sigma[i]);
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w;
-    return GSL_SUCCESS;
-}
-double lorentz_multi_peak_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w = new double[peaks];
-    double offset = gsl_vector_get (x, p-1);
-    double val=0;
-    for (size_t i = 0; i < peaks; i++) {
-        a[i] = gsl_vector_get(x, 3*i);
-        xc[i] = gsl_vector_get(x, 3*i+1);
-        w[i] = gsl_vector_get(x, 3*i+2);
-    }
-    for (size_t i = 0; i < n; i++) {
-        double res = 0;
-        for (size_t j = 0; j < peaks; j++) {
-            double diff = X[i]-xc[j];
-            res += a[j]*w[j]/(4*diff*diff+w[j]*w[j]);
-        }
-        double t = (M_2_PI*res + offset - Y[i])/sigma[i];
-        val += t*t;
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w;
-    return val;
-}
-int lorentz_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    size_t peaks = (p-1)/3;
-    double *a = new double[peaks];
-    double *xc = new double[peaks];
-    double *w = new double[peaks];
-    size_t i,j;
-    for (i = 0; i<peaks; i++) {
-        a[i] = gsl_vector_get (x, 3*i);
-        xc[i] = gsl_vector_get (x, 3*i+1);
-        w[i] = gsl_vector_get (x, 3*i+2);
-    }
-    for (i = 0; i<n; i++) {
-        double s = sigma[i];
-        for (j = 0; j<peaks; j++) {
-            double diff = X[i]-xc[j];
-            double diff2 = diff*diff;
-            double w2 = w[j]*w[j];
-            double num = 1.0/(4*diff2+w2);
-            double num2 = num*num;
-            double den = 4*diff2-w2;
-            gsl_matrix_set (J, i, 3*j, M_2_PI*w[j]*num/s);
-            gsl_matrix_set (J, i, 3*j+1, M_2_PI*8*diff*a[j]*w[j]*num2/s);
-            gsl_matrix_set (J, i, 3*j+2, M_2_PI*den*a[j]*num2/s);
-        }
-        gsl_matrix_set (J, i, p-1, 1.0/s);
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w;
-    return GSL_SUCCESS;
-}
-int lorentz_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    lorentz_multi_peak_f (x, params, f);
-    lorentz_multi_peak_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int user_f(const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    const char *function = ((struct FitData *) params)->function;
-    QString names = (QString)((struct FitData *) params)->names;
-    QStringList parNames= names.split(",", QString::SkipEmptyParts);
-    MyParser parser;
-    try {
-        double *parameters = new double[p];
-        double xvar;
-        parser.DefineVar("x", &xvar);
-        for (int i=0; i<(int)p; i++) {
-            parameters[i]=gsl_vector_get(x,i);
-            parser.DefineVar(parNames[i].toAscii().constData(), &parameters[i]);
-        }
-        parser.SetExpr(function);
-        for (int j = 0; j < (int)n; j++) {
-            // cppcheck-suppress unreadVariable
-            xvar=X[j];
-            gsl_vector_set (f, j, (parser.Eval() - Y[j])/sigma[j]);
-        }
-        delete[] parameters;
-    } catch (mu::ParserError &e) {
-        QMessageBox::critical(0,"MantidPlot - Input function error",QString::fromStdString(e.GetMsg()));
-        return GSL_EINVAL;
-    }
-    return GSL_SUCCESS;
-}
-double user_d(const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    const char *function = ((struct FitData *) params)->function;
-    QString names = (QString)((struct FitData *) params)->names;
-    QStringList parNames= names.split(",", QString::SkipEmptyParts);
-    double val=0;
-    MyParser parser;
-    try {
-        double *parameters = new double[p];
-        double xvar;
-        parser.DefineVar("x", &xvar);
-        for (int i=0; i<(int)p; i++) {
-            parameters[i]=gsl_vector_get(x,i);
-            parser.DefineVar(parNames[i].toAscii().constData(), &parameters[i]);
-        }
-        parser.SetExpr(function);
-        for (int j = 0; j < (int)n; j++) {
-            // cppcheck-suppress unreadVariable
-            xvar=X[j];
-            double t=(parser.Eval() - Y[j])/sigma[j];
-            val+=t*t;
-        }
-        delete[] parameters;
-    } catch (mu::ParserError &e) {
-        QMessageBox::critical(0,"MantidPlot - Input function error",QString::fromStdString(e.GetMsg()));
-        return GSL_EINVAL;
-    }
-    return val;
+  for (i = 0; i < n; i++) {
+    double res = 0;
+    for (j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      res += a[j] * exp(-2 * diff * diff / w2[j]);
+    }
+    double t = (res + offset - Y[i]) / sigma[i];
+    val += t * t;
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w2;
+  return val;
+}
+int gauss_multi_peak_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w = new double[peaks];
+  size_t i, j;
+  for (i = 0; i < peaks; i++) {
+    a[i] = gsl_vector_get(x, 3 * i);
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    w[i] = gsl_vector_get(x, 3 * i + 2);
+  }
+  for (i = 0; i < n; i++) {
+    double s = sigma[i];
+    for (j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      double w2 = w[j] * w[j];
+      double e = sqrt(M_2_PI) / s * exp(-2 * diff * diff / w2);
+      gsl_matrix_set(J, i, 3 * j, e / w[j]);
+      gsl_matrix_set(J, i, 3 * j + 1, 4 * diff * a[j] * e / (w2 * w[j]));
+      gsl_matrix_set(J, i, 3 * j + 2,
+                     a[j] / w2 * e * (4 * diff * diff / w2 - 1));
+    }
+    gsl_matrix_set(J, i, p - 1, 1.0 / s);
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w;
+  return GSL_SUCCESS;
+}
+int gauss_multi_peak_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                         gsl_matrix *J) {
+  gauss_multi_peak_f(x, params, f);
+  gauss_multi_peak_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int lorentz_multi_peak_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w = new double[peaks];
+  double offset = gsl_vector_get(x, p - 1);
+  size_t i, j;
+  for (i = 0; i < peaks; i++) {
+    a[i] = gsl_vector_get(x, 3 * i);
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    w[i] = gsl_vector_get(x, 3 * i + 2);
+  }
+  for (i = 0; i < n; i++) {
+    double res = 0;
+    for (j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      res += a[j] * w[j] / (4 * diff * diff + w[j] * w[j]);
+    }
+    gsl_vector_set(f, i, (M_2_PI * res + offset - Y[i]) / sigma[i]);
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w;
+  return GSL_SUCCESS;
+}
+double lorentz_multi_peak_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w = new double[peaks];
+  double offset = gsl_vector_get(x, p - 1);
+  double val = 0;
+  for (size_t i = 0; i < peaks; i++) {
+    a[i] = gsl_vector_get(x, 3 * i);
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    w[i] = gsl_vector_get(x, 3 * i + 2);
+  }
+  for (size_t i = 0; i < n; i++) {
+    double res = 0;
+    for (size_t j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      res += a[j] * w[j] / (4 * diff * diff + w[j] * w[j]);
+    }
+    double t = (M_2_PI * res + offset - Y[i]) / sigma[i];
+    val += t * t;
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w;
+  return val;
+}
+int lorentz_multi_peak_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  size_t peaks = (p - 1) / 3;
+  double *a = new double[peaks];
+  double *xc = new double[peaks];
+  double *w = new double[peaks];
+  size_t i, j;
+  for (i = 0; i < peaks; i++) {
+    a[i] = gsl_vector_get(x, 3 * i);
+    xc[i] = gsl_vector_get(x, 3 * i + 1);
+    w[i] = gsl_vector_get(x, 3 * i + 2);
+  }
+  for (i = 0; i < n; i++) {
+    double s = sigma[i];
+    for (j = 0; j < peaks; j++) {
+      double diff = X[i] - xc[j];
+      double diff2 = diff * diff;
+      double w2 = w[j] * w[j];
+      double num = 1.0 / (4 * diff2 + w2);
+      double num2 = num * num;
+      double den = 4 * diff2 - w2;
+      gsl_matrix_set(J, i, 3 * j, M_2_PI * w[j] * num / s);
+      gsl_matrix_set(J, i, 3 * j + 1,
+                     M_2_PI * 8 * diff * a[j] * w[j] * num2 / s);
+      gsl_matrix_set(J, i, 3 * j + 2, M_2_PI * den * a[j] * num2 / s);
+    }
+    gsl_matrix_set(J, i, p - 1, 1.0 / s);
+  }
+  delete[] a;
+  delete[] xc;
+  delete[] w;
+  return GSL_SUCCESS;
+}
+int lorentz_multi_peak_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                           gsl_matrix *J) {
+  lorentz_multi_peak_f(x, params, f);
+  lorentz_multi_peak_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int user_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  const char *function = ((struct FitData *)params)->function;
+  QString names = (QString)((struct FitData *)params)->names;
+  QStringList parNames = names.split(",", QString::SkipEmptyParts);
+  MyParser parser;
+  try {
+    double *parameters = new double[p];
+    double xvar;
+    parser.DefineVar("x", &xvar);
+    for (int i = 0; i < (int)p; i++) {
+      parameters[i] = gsl_vector_get(x, i);
+      parser.DefineVar(parNames[i].toAscii().constData(), &parameters[i]);
+    }
+    parser.SetExpr(function);
+    for (int j = 0; j < (int)n; j++) {
+      // cppcheck-suppress unreadVariable
+      xvar = X[j];
+      gsl_vector_set(f, j, (parser.Eval() - Y[j]) / sigma[j]);
+    }
+    delete[] parameters;
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(0, "MantidPlot - Input function error",
+                          QString::fromStdString(e.GetMsg()));
+    return GSL_EINVAL;
+  }
+  return GSL_SUCCESS;
+}
+double user_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  const char *function = ((struct FitData *)params)->function;
+  QString names = (QString)((struct FitData *)params)->names;
+  QStringList parNames = names.split(",", QString::SkipEmptyParts);
+  double val = 0;
+  MyParser parser;
+  try {
+    double *parameters = new double[p];
+    double xvar;
+    parser.DefineVar("x", &xvar);
+    for (int i = 0; i < (int)p; i++) {
+      parameters[i] = gsl_vector_get(x, i);
+      parser.DefineVar(parNames[i].toAscii().constData(), &parameters[i]);
+    }
+    parser.SetExpr(function);
+    for (int j = 0; j < (int)n; j++) {
+      // cppcheck-suppress unreadVariable
+      xvar = X[j];
+      double t = (parser.Eval() - Y[j]) / sigma[j];
+      val += t * t;
+    }
+    delete[] parameters;
+  } catch (mu::ParserError &e) {
+    QMessageBox::critical(0, "MantidPlot - Input function error",
+                          QString::fromStdString(e.GetMsg()));
+    return GSL_EINVAL;
+  }
+  return val;
 }
 int user_df(const gsl_vector *x, void *params, gsl_matrix *J) {
-    size_t n = ((struct FitData *)params)->n;
-    size_t p = ((struct FitData *)params)->p;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    const char *function = ((struct FitData *) params)->function;
-    QString names = (QString)((struct FitData *) params)->names;
-    QStringList parNames= names.split(",", QString::SkipEmptyParts);
-    try {
-        double *param = new double[p];
-        MyParser parser;
-        double xvar;
-        parser.DefineVar("x", &xvar);
-        for (int k=0; k<(int)p; k++) {
-            param[k]=gsl_vector_get(x,k);
-            parser.DefineVar(parNames[k].toAscii().constData(), &param[k]);
-        }
-        parser.SetExpr(function);
-        for (int i = 0; i<(int)n; i++) {
-            // cppcheck-suppress unreadVariable
-            xvar = X[i];
-            for (int j=0; j<(int)p; j++)
-                gsl_matrix_set (J, i, j, 1/sigma[i]*parser.Diff(&param[j], param[j]));
-        }
-        delete[] param;
-    } catch (mu::ParserError &) {
-        return GSL_EINVAL;
-    }
-    return GSL_SUCCESS;
-}
-int user_fdf(const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    user_f (x, params, f);
-    user_df (x, params, J);
-    return GSL_SUCCESS;
-}
-int boltzmann_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double dx = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double Yi = (A1-A2)/(1+exp((X[i]-x0)/dx))+A2;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
-    return GSL_SUCCESS;
-}
-double boltzmann_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double dx = gsl_vector_get (x, 3);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double dYi = ((A1-A2)/(1+exp((X[i]-x0)/dx)) + A2 - Y[i])/sigma[i];
-        val+=dYi * dYi;
-    }
-    return val;
-}
-int boltzmann_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double dx = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj,		*/
-        /* where fi = Yi - yi,						*/
-        /* Yi = (A1-A2)/(1+exp((X[i]-x0)/dx)) + A2	*/
-        /* and the xj are the parameters (A1,A2,x0,dx)*/
-        double s = sigma[i];
-        double diff = X[i]-x0;
-        double e = exp(diff/dx);
-        double r = 1/(1+e);
-        double aux = (A1 - A2)*e*r*r/(dx*s);
-        gsl_matrix_set (J, i, 0, r/s);
-        gsl_matrix_set (J, i, 1, (1-r)/s);
-        gsl_matrix_set (J, i, 2, aux);
-        gsl_matrix_set (J, i, 3, aux*diff/dx);
-    }
-    return GSL_SUCCESS;
-}
-int boltzmann_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    boltzmann_f (x, params, f);
-    boltzmann_df (x, params, J);
-    return GSL_SUCCESS;
+  size_t n = ((struct FitData *)params)->n;
+  size_t p = ((struct FitData *)params)->p;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  const char *function = ((struct FitData *)params)->function;
+  QString names = (QString)((struct FitData *)params)->names;
+  QStringList parNames = names.split(",", QString::SkipEmptyParts);
+  try {
+    double *param = new double[p];
+    MyParser parser;
+    double xvar;
+    parser.DefineVar("x", &xvar);
+    for (int k = 0; k < (int)p; k++) {
+      param[k] = gsl_vector_get(x, k);
+      parser.DefineVar(parNames[k].toAscii().constData(), &param[k]);
+    }
+    parser.SetExpr(function);
+    for (int i = 0; i < (int)n; i++) {
+      // cppcheck-suppress unreadVariable
+      xvar = X[i];
+      for (int j = 0; j < (int)p; j++)
+        gsl_matrix_set(J, i, j,
+                       1 / sigma[i] * parser.Diff(&param[j], param[j]));
+    }
+    delete[] param;
+  } catch (mu::ParserError &) {
+    return GSL_EINVAL;
+  }
+  return GSL_SUCCESS;
+}
+int user_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) {
+  user_f(x, params, f);
+  user_df(x, params, J);
+  return GSL_SUCCESS;
+}
+int boltzmann_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double dx = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double Yi = (A1 - A2) / (1 + exp((X[i] - x0) / dx)) + A2;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
+  return GSL_SUCCESS;
+}
+double boltzmann_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double dx = gsl_vector_get(x, 3);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double dYi =
+        ((A1 - A2) / (1 + exp((X[i] - x0) / dx)) + A2 - Y[i]) / sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
+}
+int boltzmann_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double dx = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj,		*/
+    /* where fi = Yi - yi,						*/
+    /* Yi = (A1-A2)/(1+exp((X[i]-x0)/dx)) + A2	*/
+    /* and the xj are the parameters (A1,A2,x0,dx)*/
+    double s = sigma[i];
+    double diff = X[i] - x0;
+    double e = exp(diff / dx);
+    double r = 1 / (1 + e);
+    double aux = (A1 - A2) * e * r * r / (dx * s);
+    gsl_matrix_set(J, i, 0, r / s);
+    gsl_matrix_set(J, i, 1, (1 - r) / s);
+    gsl_matrix_set(J, i, 2, aux);
+    gsl_matrix_set(J, i, 3, aux * diff / dx);
+  }
+  return GSL_SUCCESS;
+}
+int boltzmann_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                  gsl_matrix *J) {
+  boltzmann_f(x, params, f);
+  boltzmann_df(x, params, J);
+  return GSL_SUCCESS;
 }
 
-int logistic_f (const gsl_vector * x, void *params, gsl_vector * f) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
+int logistic_f(const gsl_vector *x, void *params, gsl_vector *f) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
 
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double p = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        double Yi = (A1-A2)/(1+pow(X[i]/x0, p))+A2;
-        gsl_vector_set (f, i, (Yi - Y[i])/sigma[i]);
-    }
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double p = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    double Yi = (A1 - A2) / (1 + pow(X[i] / x0, p)) + A2;
+    gsl_vector_set(f, i, (Yi - Y[i]) / sigma[i]);
+  }
 
-    return GSL_SUCCESS;
+  return GSL_SUCCESS;
 }
 
-double logistic_d (const gsl_vector * x, void *params) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *Y = ((struct FitData *)params)->Y;
-    double *sigma = ((struct FitData *)params)->sigma;
+double logistic_d(const gsl_vector *x, void *params) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *Y = ((struct FitData *)params)->Y;
+  double *sigma = ((struct FitData *)params)->sigma;
 
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double p = gsl_vector_get (x, 3);
-    size_t i;
-    double val=0;
-    for (i = 0; i < n; i++) {
-        double dYi = ((A1-A2)/(1+pow(X[i]/x0, p)) + A2 - Y[i])/sigma[i];
-        val += dYi * dYi;
-    }
-    return val;
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double p = gsl_vector_get(x, 3);
+  size_t i;
+  double val = 0;
+  for (i = 0; i < n; i++) {
+    double dYi = ((A1 - A2) / (1 + pow(X[i] / x0, p)) + A2 - Y[i]) / sigma[i];
+    val += dYi * dYi;
+  }
+  return val;
 }
 
-int logistic_df (const gsl_vector * x, void *params, gsl_matrix * J) {
-    size_t n = ((struct FitData *)params)->n;
-    double *X = ((struct FitData *)params)->X;
-    double *sigma = ((struct FitData *)params)->sigma;
+int logistic_df(const gsl_vector *x, void *params, gsl_matrix *J) {
+  size_t n = ((struct FitData *)params)->n;
+  double *X = ((struct FitData *)params)->X;
+  double *sigma = ((struct FitData *)params)->sigma;
 
-    double A1 = gsl_vector_get (x, 0);
-    double A2 = gsl_vector_get (x, 1);
-    double x0 = gsl_vector_get (x, 2);
-    double p = gsl_vector_get (x, 3);
-    size_t i;
-    for (i = 0; i < n; i++) {
-        /* Jacobian matrix J(i,j) = dfi / dxj,		*/
-        /* where fi = Yi - yi,						*/
-        /* Yi = (A1-A2)/(1+(X[i]/x0)^p)) + A2	*/
-        /* and the xj are the parameters (A1,A2,x0,p)*/
-        double s = sigma[i];
-        double rap = X[i]/x0;
-        double r = 1/(1 + pow(rap, p));
-        double aux = (A1-A2)*r*r*pow(rap, p);
-        gsl_matrix_set (J, i, 0, r/s);
-        gsl_matrix_set (J, i, 1, (1-r)/s);
-        gsl_matrix_set (J, i, 2, aux*p/(x0*s));
-        gsl_matrix_set (J, i, 3, -aux*log(rap)/s);
-    }
-    return GSL_SUCCESS;
+  double A1 = gsl_vector_get(x, 0);
+  double A2 = gsl_vector_get(x, 1);
+  double x0 = gsl_vector_get(x, 2);
+  double p = gsl_vector_get(x, 3);
+  size_t i;
+  for (i = 0; i < n; i++) {
+    /* Jacobian matrix J(i,j) = dfi / dxj,		*/
+    /* where fi = Yi - yi,						*/
+    /* Yi = (A1-A2)/(1+(X[i]/x0)^p)) + A2	*/
+    /* and the xj are the parameters (A1,A2,x0,p)*/
+    double s = sigma[i];
+    double rap = X[i] / x0;
+    double r = 1 / (1 + pow(rap, p));
+    double aux = (A1 - A2) * r * r * pow(rap, p);
+    gsl_matrix_set(J, i, 0, r / s);
+    gsl_matrix_set(J, i, 1, (1 - r) / s);
+    gsl_matrix_set(J, i, 2, aux * p / (x0 * s));
+    gsl_matrix_set(J, i, 3, -aux * log(rap) / s);
+  }
+  return GSL_SUCCESS;
 }
 
-int logistic_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J) {
-    logistic_f (x, params, f);
-    logistic_df (x, params, J);
-    return GSL_SUCCESS;
+int logistic_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                 gsl_matrix *J) {
+  logistic_f(x, params, f);
+  logistic_df(x, params, J);
+  return GSL_SUCCESS;
 }
diff --git a/MantidPlot/src/fit_gsl.h b/MantidPlot/src/fit_gsl.h
index 9dda60de976fb63281fb3df71b1ea0fbd0455a1c..b2444037387deacf52524711587f2e723ea97775 100644
--- a/MantidPlot/src/fit_gsl.h
+++ b/MantidPlot/src/fit_gsl.h
@@ -5,58 +5,63 @@
 
 //! Structure for fitting data
 struct FitData {
-  size_t n;// number of points to be fitted (size of X, Y and sigma arrays)
-  size_t p;// number of fit parameters
-  double * X;// the data to be fitted (abscissae) 
-  double * Y; // the data to be fitted (ordinates)
-  double * sigma; // the weighting data
+  size_t n;  // number of points to be fitted (size of X, Y and sigma arrays)
+  size_t p;  // number of fit parameters
+  double *X; // the data to be fitted (abscissae)
+  double *Y; // the data to be fitted (ordinates)
+  double *sigma;        // the weighting data
   const char *function; // fit model (used only by the NonLinearFit class)
-  const char *names; // names of the fit parameters separated by "," (used only by the NonLinearFit class)
+  const char *names; // names of the fit parameters separated by "," (used only
+                     // by the NonLinearFit class)
 };
 
-int expd3_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int expd3_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int expd3_f (const gsl_vector * x, void *params, gsl_vector * f);
-double expd3_d (const gsl_vector * x, void *params);
-
-int expd2_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int expd2_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int expd2_f (const gsl_vector * x, void *params, gsl_vector * f);
-double expd2_d (const gsl_vector * x, void *params);
-
-int exp_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int exp_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int exp_f (const gsl_vector * x, void *params, gsl_vector * f);
-double exp_d (const gsl_vector * x, void *params);
-
-int boltzmann_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int boltzmann_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int boltzmann_f (const gsl_vector * x, void *params, gsl_vector * f);
-double boltzmann_d (const gsl_vector * x, void *params);
-
-int logistic_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int logistic_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int logistic_f (const gsl_vector * x, void *params, gsl_vector * f);
-double logistic_d (const gsl_vector * x, void *params);
-
-int gauss_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-int gauss_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int gauss_f (const gsl_vector * x, void *params,gsl_vector * f);
-double gauss_d (const gsl_vector * x, void *params);
-
-int gauss_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);
-double gauss_multi_peak_d (const gsl_vector * x, void *params);
-int gauss_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int gauss_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-
-int lorentz_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);
-double lorentz_multi_peak_d (const gsl_vector * x, void *params);
-int lorentz_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);
-int lorentz_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
-
-int user_f(const gsl_vector * x, void *params, gsl_vector * f);
-double user_d(const gsl_vector * x, void *params);
-int user_df(const gsl_vector * x, void *params,gsl_matrix * J);
-int user_fdf(const gsl_vector * x, void *params,gsl_vector * f, gsl_matrix * J);
+int expd3_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
+int expd3_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int expd3_f(const gsl_vector *x, void *params, gsl_vector *f);
+double expd3_d(const gsl_vector *x, void *params);
+
+int expd2_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
+int expd2_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int expd2_f(const gsl_vector *x, void *params, gsl_vector *f);
+double expd2_d(const gsl_vector *x, void *params);
+
+int exp_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
+int exp_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int exp_f(const gsl_vector *x, void *params, gsl_vector *f);
+double exp_d(const gsl_vector *x, void *params);
+
+int boltzmann_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                  gsl_matrix *J);
+int boltzmann_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int boltzmann_f(const gsl_vector *x, void *params, gsl_vector *f);
+double boltzmann_d(const gsl_vector *x, void *params);
+
+int logistic_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                 gsl_matrix *J);
+int logistic_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int logistic_f(const gsl_vector *x, void *params, gsl_vector *f);
+double logistic_d(const gsl_vector *x, void *params);
+
+int gauss_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
+int gauss_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int gauss_f(const gsl_vector *x, void *params, gsl_vector *f);
+double gauss_d(const gsl_vector *x, void *params);
+
+int gauss_multi_peak_f(const gsl_vector *x, void *params, gsl_vector *f);
+double gauss_multi_peak_d(const gsl_vector *x, void *params);
+int gauss_multi_peak_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int gauss_multi_peak_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                         gsl_matrix *J);
+
+int lorentz_multi_peak_f(const gsl_vector *x, void *params, gsl_vector *f);
+double lorentz_multi_peak_d(const gsl_vector *x, void *params);
+int lorentz_multi_peak_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int lorentz_multi_peak_fdf(const gsl_vector *x, void *params, gsl_vector *f,
+                           gsl_matrix *J);
+
+int user_f(const gsl_vector *x, void *params, gsl_vector *f);
+double user_d(const gsl_vector *x, void *params);
+int user_df(const gsl_vector *x, void *params, gsl_matrix *J);
+int user_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
 
 #endif
diff --git a/MantidPlot/src/globals.h b/MantidPlot/src/globals.h
index bdc1c8e847f9766e43cd994f35c8765adebccd4f..151737eade5333bc24ba6752b454d2fb7c09f96b 100644
--- a/MantidPlot/src/globals.h
+++ b/MantidPlot/src/globals.h
@@ -2,7 +2,8 @@
     File                 : globals.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Definition of global constants
 
@@ -35,8 +36,8 @@ const int min_version = 9;
 //! Patch version number (0..9)
 const int patch_version = 5;
 //! Extra version information string (like "alpha", "-2", etc...)
-const char * extra_version = "";
+const char *extra_version = "";
 //! Copyright string containing the author names
-const char * copyright_string = "Copyright (C) 2004-2008 Ion Vasilief";
+const char *copyright_string = "Copyright (C) 2004-2008 Ion Vasilief";
 //! Release date as a string
-const char * release_date = "10 Apr 2008";
+const char *release_date = "10 Apr 2008";
diff --git a/MantidPlot/src/importOPJ.cpp b/MantidPlot/src/importOPJ.cpp
index 5d9593c3ade455d2de158dd9cbe1933f36ca6895..39637a82acb803b4d9fa16539ff6d79812eb53e9 100644
--- a/MantidPlot/src/importOPJ.cpp
+++ b/MantidPlot/src/importOPJ.cpp
@@ -2,8 +2,10 @@
     File                 : importOPJ.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006-2007 by Ion Vasilief, Alex Kargovsky, Tilman Hoener zu Siederdissen
-    Email (use @ for *)  : ion_vasilief*yahoo.fr, kargovsky*yumr.phys.msu.su, thzs*gmx.net
+    Copyright            : (C) 2006-2007 by Ion Vasilief, Alex Kargovsky, Tilman
+ Hoener zu Siederdissen
+    Email (use @ for *)  : ion_vasilief*yahoo.fr, kargovsky*yumr.phys.msu.su,
+ thzs*gmx.net
     Description          : Origin project import class
 
  ***************************************************************************/
@@ -63,1405 +65,1393 @@ using std::vector;
 
 #define OBJECTXOFFSET 200
 
-QString strreverse(const QString &str) //QString reversing
+QString strreverse(const QString &str) // QString reversing
 {
-	QString out="";
-	for(int i=str.length()-1; i>=0; --i)
-	{
-		out+=str[i];
-	}
-	return out;
+  QString out = "";
+  for (int i = str.length() - 1; i >= 0; --i) {
+    out += str[i];
+  }
+  return out;
 }
 
-QString JulianDateTime2String(double jdt)
-{
-	QTime time(0,0,0,0);
-	time = time.addSecs(int(jdt-(int)jdt)*86400);
-	QDateTime dt(QDate::fromJulianDay(int(jdt) + 1), time);
-	return dt.toString("dd.MM.yyyy hh:mm:ss");
+QString JulianDateTime2String(double jdt) {
+  QTime time(0, 0, 0, 0);
+  time = time.addSecs(int(jdt - (int)jdt) * 86400);
+  QDateTime dt(QDate::fromJulianDay(int(jdt) + 1), time);
+  return dt.toString("dd.MM.yyyy hh:mm:ss");
 }
 
-ImportOPJ::ImportOPJ(ApplicationWindow *app, const QString& filename) :
-		mw(app)
-{
-	xoffset=0;
-	OPJFile opj((const char *)filename.toAscii().constData());
-	parse_error = opj.Parse();
-	importTables(opj);
-	importGraphs(opj);
-	importNotes(opj);
-	if(filename.endsWith(".opj", Qt::CaseInsensitive))
-		createProjectTree(opj);
-	mw->showResults(opj.resultsLogString(), mw->logWindow->isVisible());
+ImportOPJ::ImportOPJ(ApplicationWindow *app, const QString &filename)
+    : mw(app) {
+  xoffset = 0;
+  OPJFile opj((const char *)filename.toAscii().constData());
+  parse_error = opj.Parse();
+  importTables(opj);
+  importGraphs(opj);
+  importNotes(opj);
+  if (filename.endsWith(".opj", Qt::CaseInsensitive))
+    createProjectTree(opj);
+  mw->showResults(opj.resultsLogString(), mw->logWindow->isVisible());
 }
 
-inline uint qHash(const tree<projectNode>::iterator &key)
-{
-	return qHash(key->name.c_str());
+inline uint qHash(const tree<projectNode>::iterator &key) {
+  return qHash(key->name.c_str());
 }
 
-bool ImportOPJ::createProjectTree(const OPJFile& opj)
-{
-	const tree<projectNode>* projectTree = opj.project();
-	tree<projectNode>::iterator root = projectTree->begin(projectTree->begin());
-	if(!root.node)
-		return false;
-	FolderListItem* item = static_cast<FolderListItem*>(mw->folders->firstChild());
-	item->setText(0, root->name.c_str());
-	item->folder()->setObjectName(root->name.c_str());
-	Folder* projectFolder = mw->projectFolder();
-	QHash< tree<projectNode>::iterator, Folder*> parent;
-	parent[root] = projectFolder;
-	for(tree<projectNode>::iterator sib = projectTree->begin(root); sib != projectTree->end(root); ++sib)
-	{
-		if(sib->type == 1)
-		{
-			parent[sib] = mw->addFolder(sib->name.c_str(), parent.value(projectTree->parent(sib)));
-			parent[sib]->setBirthDate(JulianDateTime2String(sib->creation_date));
-			parent[sib]->setModificationDate(JulianDateTime2String(sib->modification_date));
-		}
-		else
-		{
-			MdiSubWindow* w = projectFolder->window(sib->name.c_str());
-			if(w)
-			{
-				parent.value(projectTree->parent(sib))->addWindow(w);
-				projectFolder->removeWindow(w);
-			}
-		}
-	}
-	mw->changeFolder(projectFolder, true);
-	return true;
+bool ImportOPJ::createProjectTree(const OPJFile &opj) {
+  const tree<projectNode> *projectTree = opj.project();
+  tree<projectNode>::iterator root = projectTree->begin(projectTree->begin());
+  if (!root.node)
+    return false;
+  FolderListItem *item =
+      static_cast<FolderListItem *>(mw->folders->firstChild());
+  item->setText(0, root->name.c_str());
+  item->folder()->setObjectName(root->name.c_str());
+  Folder *projectFolder = mw->projectFolder();
+  QHash<tree<projectNode>::iterator, Folder *> parent;
+  parent[root] = projectFolder;
+  for (tree<projectNode>::iterator sib = projectTree->begin(root);
+       sib != projectTree->end(root); ++sib) {
+    if (sib->type == 1) {
+      parent[sib] = mw->addFolder(sib->name.c_str(),
+                                  parent.value(projectTree->parent(sib)));
+      parent[sib]->setBirthDate(JulianDateTime2String(sib->creation_date));
+      parent[sib]->setModificationDate(
+          JulianDateTime2String(sib->modification_date));
+    } else {
+      MdiSubWindow *w = projectFolder->window(sib->name.c_str());
+      if (w) {
+        parent.value(projectTree->parent(sib))->addWindow(w);
+        projectFolder->removeWindow(w);
+      }
+    }
+  }
+  mw->changeFolder(projectFolder, true);
+  return true;
 }
 
 int ImportOPJ::translateOrigin2QtiplotLineStyle(int linestyle) {
-	int qtiplotstyle=0;
-	switch (linestyle)
-	{
-		case OPJFile::Solid:
-			qtiplotstyle=0;
-			break;
-		case OPJFile::Dash:
-		case OPJFile::ShortDash:
-			qtiplotstyle=1;
-			break;
-		case OPJFile::Dot:
-		case OPJFile::ShortDot:
-			qtiplotstyle=2;
-			break;
-		case OPJFile::DashDot:
-		case OPJFile::ShortDashDot:
-			qtiplotstyle=3;
-			break;
-		case OPJFile::DashDotDot:
-			qtiplotstyle=4;
-			break;
-	}
-	return qtiplotstyle;
+  int qtiplotstyle = 0;
+  switch (linestyle) {
+  case OPJFile::Solid:
+    qtiplotstyle = 0;
+    break;
+  case OPJFile::Dash:
+  case OPJFile::ShortDash:
+    qtiplotstyle = 1;
+    break;
+  case OPJFile::Dot:
+  case OPJFile::ShortDot:
+    qtiplotstyle = 2;
+    break;
+  case OPJFile::DashDot:
+  case OPJFile::ShortDashDot:
+    qtiplotstyle = 3;
+    break;
+  case OPJFile::DashDotDot:
+    qtiplotstyle = 4;
+    break;
+  }
+  return qtiplotstyle;
 }
 
-bool ImportOPJ::importTables(const OPJFile& opj)
-{
-	int visible_count=0;
-	int QtiPlot_scaling_factor=10; //in Origin width is measured in characters while in QtiPlot - pixels --- need to be accurate
-	for (int s=0; s<opj.numSpreads(); s++)
-	{
-		int nr_cols = opj.numCols(s);
-		int maxrows = opj.maxRows(s);
-		if(!nr_cols) //remove tables without cols
-			continue;
-
-		Table *table = (opj.spreadHidden(s)||opj.spreadLoose(s))&&opj.Version()==7.5 ? mw->newHiddenTable(opj.spreadName(s), opj.spreadLabel(s), maxrows, nr_cols)
-										: mw->newTable(opj.spreadName(s), maxrows, nr_cols);
-		if (!table)
-			return false;
-
-		rect windowRect;
-		if(opj.Version() == 7.5)
-		{
-			windowRect = opj.spreadWindowRect(s);
-			table->resize(windowRect.width() - (table->frameGeometry().width() - table->width()),
-				windowRect.height() - (table->frameGeometry().height() - table->height()));
-		}
-
-		table->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.spreadTitle(s));
-		table->setBirthDate(JulianDateTime2String(opj.spreadCreationDate(s)));
-
-        QLocale locale = mw->locale();
-		table->setWindowLabel(opj.spreadLabel(s));
-		for (int j=0; j<nr_cols; j++)
-		{
-			QString name(opj.colName(s,j));
-			table->setColName(j, name.replace(QRegExp(".*_"),""));
-			table->setCommand(j, QString(opj.colCommand(s,j)));
-			table->setColComment(j, QString(opj.colComment(s,j)));
-			table->setColumnWidth(j, opj.colWidth(s,j)*QtiPlot_scaling_factor);
-
-			switch(opj.colType(s,j))
-			{
-			case X:
-				table->setColPlotDesignation(j, Table::X);
-				break;
-			case Y:
-				table->setColPlotDesignation(j, Table::Y);
-				break;
-			case Z:
-				table->setColPlotDesignation(j, Table::Z);
-				break;
-			case XErr:
-				table->setColPlotDesignation(j, Table::xErr);
-				break;
-			case YErr:
-				table->setColPlotDesignation(j, Table::yErr);
-				break;
-			case Label:
-				table->setColPlotDesignation(j, Table::Label);
-				break;
-			default:
-				table->setColPlotDesignation(j, Table::None);
-			}
-
-            table->setHeaderColType();//update header
-
-            double **d_cells = new double* [nr_cols];
-            for ( int i = 0; i < nr_cols; ++i)
-                d_cells[i] = new double [table->numRows()];
-
-			for (int i=0; i<opj.numRows(s,j); i++){
-				if(opj.colType(s,j)!=Label && opj.colValueType(s,j)!=1){// number
-					double* val = (double*)opj.oData(s,j,i,true);
-					if(fabs(*val)>0 && fabs(*val)<2.0e-300)// empty entry
-						continue;
-
-                    table->setText(i, j, locale.toString(*val, 'g', 16));
-                    d_cells[j][i] = *val;
-				}
-				else// label? doesn't seem to work
-					table->setText(i, j, QString((char*)opj.oData(s,j,i)));
-			}
-            table->saveToMemory(d_cells);
-
-			QString format;
-  		int f = 0;
-			switch(opj.colValueType(s,j))
-			{
-			case 0: //Numeric
-			case 6: //Text&Numeric
-				if(opj.colNumDisplayType(s,j)==0)
-					f=0;
-				else
-					switch(opj.colValueTypeSpec(s,j))
-					{
-					case 0: //Decimal 1000
-						f=1;
-						break;
-					case 1: //Scientific
-						f=2;
-						break;
-					case 2: //Engeneering
-					case 3: //Decimal 1,000
-						f=0;
-						break;
-					}
-				table->setColNumericFormat(f, opj.colDecPlaces(s,j), j);
-				break;
-			case 1: //Text
-				table->setTextFormat(j);
-				break;
-			case 2: // Date
-				switch(opj.colValueTypeSpec(s,j))
-				{
-                case -128:
-                    format="dd/MM/yyyy";
-					break;
-                case -119:
-                    format="dd/MM/yyyy HH:mm";
-					break;
-                case -118:
-                    format="dd/MM/yyyy HH:mm:ss";
-					break;
-				case 0:
-				case 9:
-				case 10:
-					format="dd.MM.yyyy";
-					break;
-				case 2:
-					format="MMM d";
-					break;
-				case 3:
-					format="M/d";
-					break;
-				case 4:
-					format="d";
-					break;
-				case 5:
-				case 6:
-					format="ddd";
-					break;
-				case 7:
-					format="yyyy";
-					break;
-				case 8:
-					format="yy";
-					break;
-				case 11:
-				case 12:
-				case 13:
-				case 14:
-				case 15:
-					format="yyMMdd";
-					break;
-				case 16:
-				case 17:
-					format="MMM";
-					break;
-				case 19:
-					format="M-d-yyyy";
-					break;
-				default:
-					format="dd.MM.yyyy";
-				}
-				table->setDateFormat(format, j);
-				break;
-			case 3: // Time
-				switch(opj.colValueTypeSpec(s,j)+128)
-				{
-				case 0:
-					format="hh:mm";
-					break;
-				case 1:
-					format="hh";
-					break;
-				case 2:
-					format="hh:mm:ss";
-					break;
-				case 3:
-					format="hh:mm:ss.zzz";
-					break;
-				case 4:
-					format="hh ap";
-					break;
-				case 5:
-					format="hh:mm ap";
-					break;
-				case 6:
-					format="mm:ss";
-					break;
-				case 7:
-					format="mm:ss.zzz";
-					break;
-				case 8:
-					format="hhmm";
-					break;
-				case 9:
-					format="hhmmss";
-					break;
-				case 10:
-					format="hh:mm:ss.zzz";
-					break;
-				}
-				table->setTimeFormat(format, j);
-				break;
-			case 4: // Month
-				switch(opj.colValueTypeSpec(s,j)){
-                    case 0:
-                        format = "MMM";
-					break;
-                    case 1:
-                        format = "MMMM";
-					break;
-                    case 2:
-                        format = "M";
-					break;
-				}
-				table->setMonthFormat(format, j);
-				break;
-			case 5: // Day
-				switch(opj.colValueTypeSpec(s,j)){
-                    case 0:
-                        format = "ddd";
-					break;
-                    case 1:
-                        format = "dddd";
-					break;
-                    case 2:
-                        format = "d";
-					break;
-				}
-				table->setDayFormat(format, j);
-				break;
-			}
-            table->freeMemory();
-		}
-
-
-		if(!(opj.spreadHidden(s)||opj.spreadLoose(s))||opj.Version()!=7.5)
-		{
-			switch(opj.spreadState(s))
-			{
-			case originWindow::Minimized:
-				mw->minimizeWindow(table);
-				break;
-			case originWindow::Maximized:
-				mw->maximizeWindow(table);
-				break;
-			default:
-				table->showNormal();
-			}
-
-			//cascade the tables
-			if(opj.Version() == 7.5)
-			{
-				table->move(QPoint(windowRect.left, windowRect.top));
-			}
-			else
-			{
-				int dx=table->verticalHeaderWidth();
-				int dy=table->frameGeometry().height() - table->height();
-				table->move(QPoint(visible_count*dx+xoffset*OBJECTXOFFSET,visible_count*dy));
-				visible_count++;
-			}
-		}
-	}
-
-//Import matrices
-	for (int s=0; s<opj.numMatrices(); s++)
-	{
-		int nr_cols = opj.numMatrixCols(s);
-		int nr_rows = opj.numMatrixRows(s);
-
-		Matrix* matrix = mw->newMatrix(opj.matrixName(s), nr_rows, nr_cols);
-		if (!matrix)
-			return false;
-
-		rect windowRect;
-		if(opj.Version() == 7.5){
-			windowRect = opj.matrixWindowRect(s);
-			matrix->resize(windowRect.width() - (matrix->frameGeometry().width() - matrix->width()),
-				windowRect.height() - (matrix->frameGeometry().height() - matrix->height()));
-		}
-
-		matrix->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.matrixTitle(s));
-		matrix->setBirthDate(JulianDateTime2String(opj.matrixCreationDate(s)));
-
-		matrix->setWindowLabel(opj.matrixLabel(s));
-		matrix->setFormula(opj.matrixFormula(s));
-		matrix->setColumnsWidth(opj.matrixWidth(s)*QtiPlot_scaling_factor);
-		if(opj.matrixViewType(s) == matrix::ImageView)
-			matrix->setViewType(Matrix::ImageView);
-		if(opj.matrixHeaderViewType(s) == matrix::XY)
-			matrix->setHeaderViewType(Matrix::XY);
-		vector<double> data = opj.matrixData(s);
-		double *matrix_data = matrix->matrixModel()->dataVector();
-		int size = matrix->numRows()*matrix->numCols();
-		int cell = 0;
-		for(int i=0; i<size; i++){
-			double val = data[cell];
-			if (val < 2.0e-300)
-				val = GSL_NAN;
-			matrix_data[cell] = val;
-            cell++;
-		}
-
-		QChar format;
-		switch(opj.matrixValueTypeSpec(s))
-		{
-		case 0: //Decimal 1000
-			format='f';
-			break;
-		case 1: //Scientific
-			format='e';
-			break;
-		case 2: //Engeneering
-		case 3: //Decimal 1,000
-			format='g';
-			break;
-		}
-		matrix->setNumericFormat(format, opj.matrixSignificantDigits(s));
-
-		if(!opj.matrixHidden(s)||opj.Version()!=7.5)
-		{
-			switch(opj.matrixState(s))
-			{
-			case originWindow::Minimized:
-				mw->minimizeWindow(matrix);
-				break;
-			case originWindow::Maximized:
-				mw->maximizeWindow(matrix);
-				break;
-			default:
-				matrix->showNormal();
-			}
-
-			//cascade the matrices
-			if(opj.Version() == 7.5)
-				matrix->move(QPoint(windowRect.left, windowRect.top));
-			else {
-				int dx=matrix->verticalHeaderWidth();
-				int dy=matrix->frameGeometry().height() - matrix->height();
-				matrix->move(QPoint(visible_count*dx+xoffset*OBJECTXOFFSET,visible_count*dy));
-				visible_count++;
-			}
-		}
-	}
-
-	if(visible_count>0)
-		xoffset++;
-	return true;
+bool ImportOPJ::importTables(const OPJFile &opj) {
+  int visible_count = 0;
+  int QtiPlot_scaling_factor = 10; // in Origin width is measured in characters
+                                   // while in QtiPlot - pixels --- need to be
+                                   // accurate
+  for (int s = 0; s < opj.numSpreads(); s++) {
+    int nr_cols = opj.numCols(s);
+    int maxrows = opj.maxRows(s);
+    if (!nr_cols) // remove tables without cols
+      continue;
+
+    Table *table =
+        (opj.spreadHidden(s) || opj.spreadLoose(s)) && opj.Version() == 7.5
+            ? mw->newHiddenTable(opj.spreadName(s), opj.spreadLabel(s), maxrows,
+                                 nr_cols)
+            : mw->newTable(opj.spreadName(s), maxrows, nr_cols);
+    if (!table)
+      return false;
+
+    rect windowRect;
+    if (opj.Version() == 7.5) {
+      windowRect = opj.spreadWindowRect(s);
+      table->resize(windowRect.width() -
+                        (table->frameGeometry().width() - table->width()),
+                    windowRect.height() -
+                        (table->frameGeometry().height() - table->height()));
+    }
+
+    table->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.spreadTitle(s));
+    table->setBirthDate(JulianDateTime2String(opj.spreadCreationDate(s)));
+
+    QLocale locale = mw->locale();
+    table->setWindowLabel(opj.spreadLabel(s));
+    for (int j = 0; j < nr_cols; j++) {
+      QString name(opj.colName(s, j));
+      table->setColName(j, name.replace(QRegExp(".*_"), ""));
+      table->setCommand(j, QString(opj.colCommand(s, j)));
+      table->setColComment(j, QString(opj.colComment(s, j)));
+      table->setColumnWidth(j, opj.colWidth(s, j) * QtiPlot_scaling_factor);
+
+      switch (opj.colType(s, j)) {
+      case X:
+        table->setColPlotDesignation(j, Table::X);
+        break;
+      case Y:
+        table->setColPlotDesignation(j, Table::Y);
+        break;
+      case Z:
+        table->setColPlotDesignation(j, Table::Z);
+        break;
+      case XErr:
+        table->setColPlotDesignation(j, Table::xErr);
+        break;
+      case YErr:
+        table->setColPlotDesignation(j, Table::yErr);
+        break;
+      case Label:
+        table->setColPlotDesignation(j, Table::Label);
+        break;
+      default:
+        table->setColPlotDesignation(j, Table::None);
+      }
+
+      table->setHeaderColType(); // update header
+
+      double **d_cells = new double *[nr_cols];
+      for (int i = 0; i < nr_cols; ++i)
+        d_cells[i] = new double[table->numRows()];
+
+      for (int i = 0; i < opj.numRows(s, j); i++) {
+        if (opj.colType(s, j) != Label &&
+            opj.colValueType(s, j) != 1) { // number
+          double *val = (double *)opj.oData(s, j, i, true);
+          if (fabs(*val) > 0 && fabs(*val) < 2.0e-300) // empty entry
+            continue;
+
+          table->setText(i, j, locale.toString(*val, 'g', 16));
+          d_cells[j][i] = *val;
+        } else // label? doesn't seem to work
+          table->setText(i, j, QString((char *)opj.oData(s, j, i)));
+      }
+      table->saveToMemory(d_cells);
+
+      QString format;
+      int f = 0;
+      switch (opj.colValueType(s, j)) {
+      case 0: // Numeric
+      case 6: // Text&Numeric
+        if (opj.colNumDisplayType(s, j) == 0)
+          f = 0;
+        else
+          switch (opj.colValueTypeSpec(s, j)) {
+          case 0: // Decimal 1000
+            f = 1;
+            break;
+          case 1: // Scientific
+            f = 2;
+            break;
+          case 2: // Engeneering
+          case 3: // Decimal 1,000
+            f = 0;
+            break;
+          }
+        table->setColNumericFormat(f, opj.colDecPlaces(s, j), j);
+        break;
+      case 1: // Text
+        table->setTextFormat(j);
+        break;
+      case 2: // Date
+        switch (opj.colValueTypeSpec(s, j)) {
+        case -128:
+          format = "dd/MM/yyyy";
+          break;
+        case -119:
+          format = "dd/MM/yyyy HH:mm";
+          break;
+        case -118:
+          format = "dd/MM/yyyy HH:mm:ss";
+          break;
+        case 0:
+        case 9:
+        case 10:
+          format = "dd.MM.yyyy";
+          break;
+        case 2:
+          format = "MMM d";
+          break;
+        case 3:
+          format = "M/d";
+          break;
+        case 4:
+          format = "d";
+          break;
+        case 5:
+        case 6:
+          format = "ddd";
+          break;
+        case 7:
+          format = "yyyy";
+          break;
+        case 8:
+          format = "yy";
+          break;
+        case 11:
+        case 12:
+        case 13:
+        case 14:
+        case 15:
+          format = "yyMMdd";
+          break;
+        case 16:
+        case 17:
+          format = "MMM";
+          break;
+        case 19:
+          format = "M-d-yyyy";
+          break;
+        default:
+          format = "dd.MM.yyyy";
+        }
+        table->setDateFormat(format, j);
+        break;
+      case 3: // Time
+        switch (opj.colValueTypeSpec(s, j) + 128) {
+        case 0:
+          format = "hh:mm";
+          break;
+        case 1:
+          format = "hh";
+          break;
+        case 2:
+          format = "hh:mm:ss";
+          break;
+        case 3:
+          format = "hh:mm:ss.zzz";
+          break;
+        case 4:
+          format = "hh ap";
+          break;
+        case 5:
+          format = "hh:mm ap";
+          break;
+        case 6:
+          format = "mm:ss";
+          break;
+        case 7:
+          format = "mm:ss.zzz";
+          break;
+        case 8:
+          format = "hhmm";
+          break;
+        case 9:
+          format = "hhmmss";
+          break;
+        case 10:
+          format = "hh:mm:ss.zzz";
+          break;
+        }
+        table->setTimeFormat(format, j);
+        break;
+      case 4: // Month
+        switch (opj.colValueTypeSpec(s, j)) {
+        case 0:
+          format = "MMM";
+          break;
+        case 1:
+          format = "MMMM";
+          break;
+        case 2:
+          format = "M";
+          break;
+        }
+        table->setMonthFormat(format, j);
+        break;
+      case 5: // Day
+        switch (opj.colValueTypeSpec(s, j)) {
+        case 0:
+          format = "ddd";
+          break;
+        case 1:
+          format = "dddd";
+          break;
+        case 2:
+          format = "d";
+          break;
+        }
+        table->setDayFormat(format, j);
+        break;
+      }
+      table->freeMemory();
+    }
+
+    if (!(opj.spreadHidden(s) || opj.spreadLoose(s)) || opj.Version() != 7.5) {
+      switch (opj.spreadState(s)) {
+      case originWindow::Minimized:
+        mw->minimizeWindow(table);
+        break;
+      case originWindow::Maximized:
+        mw->maximizeWindow(table);
+        break;
+      default:
+        table->showNormal();
+      }
+
+      // cascade the tables
+      if (opj.Version() == 7.5) {
+        table->move(QPoint(windowRect.left, windowRect.top));
+      } else {
+        int dx = table->verticalHeaderWidth();
+        int dy = table->frameGeometry().height() - table->height();
+        table->move(QPoint(visible_count * dx + xoffset * OBJECTXOFFSET,
+                           visible_count * dy));
+        visible_count++;
+      }
+    }
+  }
+
+  // Import matrices
+  for (int s = 0; s < opj.numMatrices(); s++) {
+    int nr_cols = opj.numMatrixCols(s);
+    int nr_rows = opj.numMatrixRows(s);
+
+    Matrix *matrix = mw->newMatrix(opj.matrixName(s), nr_rows, nr_cols);
+    if (!matrix)
+      return false;
+
+    rect windowRect;
+    if (opj.Version() == 7.5) {
+      windowRect = opj.matrixWindowRect(s);
+      matrix->resize(windowRect.width() -
+                         (matrix->frameGeometry().width() - matrix->width()),
+                     windowRect.height() -
+                         (matrix->frameGeometry().height() - matrix->height()));
+    }
+
+    matrix->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.matrixTitle(s));
+    matrix->setBirthDate(JulianDateTime2String(opj.matrixCreationDate(s)));
+
+    matrix->setWindowLabel(opj.matrixLabel(s));
+    matrix->setFormula(opj.matrixFormula(s));
+    matrix->setColumnsWidth(opj.matrixWidth(s) * QtiPlot_scaling_factor);
+    if (opj.matrixViewType(s) == matrix::ImageView)
+      matrix->setViewType(Matrix::ImageView);
+    if (opj.matrixHeaderViewType(s) == matrix::XY)
+      matrix->setHeaderViewType(Matrix::XY);
+    vector<double> data = opj.matrixData(s);
+    double *matrix_data = matrix->matrixModel()->dataVector();
+    int size = matrix->numRows() * matrix->numCols();
+    int cell = 0;
+    for (int i = 0; i < size; i++) {
+      double val = data[cell];
+      if (val < 2.0e-300)
+        val = GSL_NAN;
+      matrix_data[cell] = val;
+      cell++;
+    }
+
+    QChar format;
+    switch (opj.matrixValueTypeSpec(s)) {
+    case 0: // Decimal 1000
+      format = 'f';
+      break;
+    case 1: // Scientific
+      format = 'e';
+      break;
+    case 2: // Engeneering
+    case 3: // Decimal 1,000
+      format = 'g';
+      break;
+    }
+    matrix->setNumericFormat(format, opj.matrixSignificantDigits(s));
+
+    if (!opj.matrixHidden(s) || opj.Version() != 7.5) {
+      switch (opj.matrixState(s)) {
+      case originWindow::Minimized:
+        mw->minimizeWindow(matrix);
+        break;
+      case originWindow::Maximized:
+        mw->maximizeWindow(matrix);
+        break;
+      default:
+        matrix->showNormal();
+      }
+
+      // cascade the matrices
+      if (opj.Version() == 7.5)
+        matrix->move(QPoint(windowRect.left, windowRect.top));
+      else {
+        int dx = matrix->verticalHeaderWidth();
+        int dy = matrix->frameGeometry().height() - matrix->height();
+        matrix->move(QPoint(visible_count * dx + xoffset * OBJECTXOFFSET,
+                            visible_count * dy));
+        visible_count++;
+      }
+    }
+  }
+
+  if (visible_count > 0)
+    xoffset++;
+  return true;
 }
 
-bool ImportOPJ::importNotes(const OPJFile& opj)
-{
-	int visible_count=0;
-	for (int n=0; n<opj.numNotes(); n++)
-	{
-		QString name=opj.noteName(n);
-		QRegExp rx("^@\\((\\S+)\\)$");
-		if(rx.indexIn(name)==0)
-			name=rx.cap(1);
-
-		Note *note = mw->newNote(name);
-		if(!note)
-			return false;
-		note->setWindowLabel(opj.noteLabel(n));
-		note->setText(opj.noteText(n));
-		note->setBirthDate(JulianDateTime2String(opj.noteCreationDate(n)));
-
-		//cascade the notes
-		int dx=20;
-		int dy=note->frameGeometry().height() - note->height();
-		note->move(QPoint(visible_count*dx+xoffset*OBJECTXOFFSET,visible_count*dy));
-		visible_count++;
-	}
-	if(visible_count>0)
-		xoffset++;
-	return true;
+bool ImportOPJ::importNotes(const OPJFile &opj) {
+  int visible_count = 0;
+  for (int n = 0; n < opj.numNotes(); n++) {
+    QString name = opj.noteName(n);
+    QRegExp rx("^@\\((\\S+)\\)$");
+    if (rx.indexIn(name) == 0)
+      name = rx.cap(1);
+
+    Note *note = mw->newNote(name);
+    if (!note)
+      return false;
+    note->setWindowLabel(opj.noteLabel(n));
+    note->setText(opj.noteText(n));
+    note->setBirthDate(JulianDateTime2String(opj.noteCreationDate(n)));
+
+    // cascade the notes
+    int dx = 20;
+    int dy = note->frameGeometry().height() - note->height();
+    note->move(QPoint(visible_count * dx + xoffset * OBJECTXOFFSET,
+                      visible_count * dy));
+    visible_count++;
+  }
+  if (visible_count > 0)
+    xoffset++;
+  return true;
 }
 
-bool ImportOPJ::importGraphs(const OPJFile& opj)
-{
-	int visible_count=0;
-	int tickTypeMap[]={0,3,1,2};
-	for (int g=0; g<opj.numGraphs(); ++g)
-	{
-		MultiLayer *ml = mw->multilayerPlot(opj.graphName(g), 0, 0, 0);
-		if (!ml)
-			return false;
-
-		ml->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.graphTitle(g));
-		ml->setBirthDate(JulianDateTime2String(opj.graphCreationDate(g)));
-		ml->hide();//!hack used in order to avoid resize and repaint events
-		ml->setWindowLabel(opj.graphLabel(g));
-
-		rect graphRect = opj.graphRect(g);
-		rect graphWindowRect = opj.graphWindowRect(g);
-		ml->resize(graphWindowRect.width() - (ml->frameGeometry().width() - ml->width()),
-                    graphWindowRect.height() - (ml->frameGeometry().height() - ml->height()));
-
-		double fXScale = (double)ml->width()/(double)graphRect.width();
-		double fYScale = (double)ml->height()/(double)graphRect.height();
-		fXScale = fYScale = QMIN(fXScale, fYScale);
-
-		double fWindowFactor =  QMIN((double)graphWindowRect.width()/500.0, (double)graphWindowRect.height()/350.0);
-		double fFontScaleFactor = 0.37*fWindowFactor;
-		double fVectorArrowScaleFactor = 0.08*fWindowFactor;
-
-		for(int l=0; l<opj.numLayers(g); ++l)
-		{
-			Graph *graph=ml->addLayer();
-			if(!graph)
-				return false;
-
-			rect layerRect=opj.layerRect(g,l);
-
-			graph->setXAxisTitle(parseOriginText(QString::fromLocal8Bit(opj.layerXAxisTitle(g,l).txt.c_str())));
-			graph->setYAxisTitle(parseOriginText(QString::fromLocal8Bit(opj.layerYAxisTitle(g,l).txt.c_str())));
-			LegendWidget* legend = 0;
-			if(!opj.layerLegend(g,l).txt.empty())
-			{
-				legend = graph->newLegend(parseOriginText(QString::fromLocal8Bit(opj.layerLegend(g,l).txt.c_str())));
-			}
-			int auto_color=0;
-			//int auto_color1=0;
-			int style=0;
-			for(int c=0; c<opj.numCurves(g,l); c++)
-			{
-				try{
-				QString data(opj.curveDataName(g,l,c));
-				int color=0;
-				switch(opj.curveType(g,l,c))
-				{
-				case OPJFile::Line:
-					style=Graph::Line;
-					break;
-				case OPJFile::Scatter:
-					style=Graph::Scatter;
-					break;
-				case OPJFile::LineSymbol:
-					style=Graph::LineSymbols;
-					break;
-				case OPJFile::ErrorBar:
-				case OPJFile::XErrorBar:
-					style=Graph::ErrorBars;
-					break;
-				case OPJFile::Column:
-					style=Graph::VerticalBars;
-					break;
-				case OPJFile::Bar:
-					style=Graph::HorizontalBars;
-					break;
-				case OPJFile::Histogram:
-					style=Graph::Histogram;
-					break;
-				case OPJFile::Pie:
-					style=Graph::Pie;
-					break;
-				case OPJFile::Box:
-					style=Graph::Box;
-					break;
-				case OPJFile::FlowVector:
-					style=Graph::VectXYXY;
-					break;
-				case OPJFile::Vector:
-					style=Graph::VectXYAM;
-					break;
-				case OPJFile::Area:
-				case OPJFile::AreaStack:
-					style=Graph::Area;
-					break;
-				case OPJFile::TextPlot:
-					style=OPJFile::TextPlot;
-					break;
-				default:
-					continue;
-				}
-				QString tableName;
-				QStringList formulas;
-				double start, end;
-				int s;
-				PlotCurve *curve = NULL;
-				switch(data[0].toAscii())
-				{
-				case 'T':
-					tableName = data.right(data.length()-2);
-					if(style==Graph::ErrorBars)
-					{
-						int flags=opj.curveSymbolType(g,l,c);
-						curve = graph->addErrorBars(tableName + "_" + opj.curveXColName(g,l,c), mw->table(tableName), tableName + "_" + opj.curveYColName(g,l,c),
-							((flags&0x10)==0x10?0:1), int(ceil(opj.curveLineWidth(g,l,c))), int(ceil(opj.curveSymbolSize(g,l,c))), QColor(Qt::black),
-							(flags&0x40)==0x40, (flags&2)==2, (flags&1)==1);
-					}
-					else if(style==Graph::Histogram)
-						curve = graph->insertCurve(mw->table(tableName), tableName + "_" + opj.curveYColName(g,l,c), style);
-					else if(style==Graph::Pie || style==Graph::Box)
-					{
-						QStringList names;
-						names << (tableName + "_" + opj.curveYColName(g,l,c));
-						graph->addCurves(mw->table(tableName), names, style);
-					}
-					else if(style==Graph::VectXYXY)
-					{
-						QStringList names;
-						vectorProperties vector = opj.curveVectorProperties(g,l,c);
-						names << (tableName + "_" + opj.curveXColName(g,l,c))
-							<< (tableName + "_" + opj.curveYColName(g,l,c))
-							<< (tableName + "_" + QString(vector.endXColName.c_str()))
-							<< (tableName + "_" + QString(vector.endYColName.c_str()));
-
-						graph->addCurves(mw->table(tableName), names, style);
-					}
-					else if(style==Graph::VectXYAM)
-					{
-						QStringList names;
-						vectorProperties vector = opj.curveVectorProperties(g,l,c);
-						names << (tableName + "_" + opj.curveXColName(g,l,c))
-							<< (tableName + "_" + opj.curveYColName(g,l,c))
-							<< (tableName + "_" + QString(vector.angleColName.c_str()))
-							<< (tableName + "_" + QString(vector.magnitudeColName.c_str()));
-
-						graph->addCurves(mw->table(tableName), names, style);
-					}
-					else if(style == OPJFile::TextPlot)
-					{
-						Table* table = mw->table(tableName);
-						QString labelsCol = opj.curveYColName(g,l,c);
-						int xcol = table->colX(table->colIndex(labelsCol));
-						int ycol = table->colY(table->colIndex(labelsCol));
-						if (xcol < 0 || ycol < 0)
-							return false;
-
-						DataCurve* mc = graph->masterCurve(table->colName(xcol), table->colName(ycol));
-						if(mc)
-						{
-							graph->replot();
-							mc->setLabelsColumnName(labelsCol);
-						}
-					}
-					else
-						curve = graph->insertCurve(mw->table(tableName), tableName + "_" + opj.curveXColName(g,l,c), tableName + "_" + opj.curveYColName(g,l,c), style);
-					break;
-				case 'F':
-					s=opj.functionIndex(data.right(data.length()-2).toStdString().c_str());
-                                        if (s<0)
-                                          break;
-					int type;
-					if(opj.functionType(s)==1)//Polar
-					{
-						type=2;
-						formulas << opj.functionFormula(s) << "x";
-						start = M_PI/180*opj.functionBegin(s) ;
-						end = M_PI/180*opj.functionEnd(s);
-					}
-					else
-					{
-						type=0;
-						formulas << opj.functionFormula(s);
-						start = opj.functionBegin(s);
-						end = opj.functionEnd(s);
-					}
-					curve = graph->addFunction(formulas, start, end, opj.functionPoints(s), "x", type, opj.functionName(s));
-
-					mw->updateFunctionLists(type, formulas);
-					break;
-				default:
-					continue;
-				}
-
-				//strange behaviour of insert curve - legend added - need to rollback legend text
-				if(legend)
-				{
-					legend->setText(parseOriginText(QString::fromLocal8Bit(opj.layerLegend(g,l).txt.c_str())));
-				}
-
-				CurveLayout cl = graph->initCurveLayout(style, opj.numCurves(g,l));
-				cl.sSize = int(ceil(opj.curveSymbolSize(g,l,c)));
-				cl.penWidth=float(opj.curveSymbolThickness(g,l,c));
-				color=opj.curveSymbolColor(g,l,c);
-				if((style==Graph::Scatter || style==Graph::LineSymbols || style==Graph::Area)&&color==0xF7)//0xF7 -Automatic color
-					color=auto_color++;
-				cl.symCol=color;
-				switch(opj.curveSymbolType(g,l,c)&0xFF)
-				{
-				case 0: //NoSymbol
-					cl.sType=0;
-					break;
-				case 1: //Rect
-					cl.sType=2;
-					break;
-				case 2: //Ellipse
-				case 20://Sphere
-					cl.sType=1;
-					break;
-				case 3: //UTriangle
-					cl.sType=6;
-					break;
-				case 4: //DTriangle
-					cl.sType=5;
-					break;
-				case 5: //Diamond
-					cl.sType=3;
-					break;
-				case 6: //Cross +
-					cl.sType=9;
-					break;
-				case 7: //Cross x
-					cl.sType=10;
-					break;
-				case 8: //Snow
-					cl.sType=13;
-					break;
-				case 9: //Horizontal -
-					cl.sType=11;
-					break;
-				case 10: //Vertical |
-					cl.sType=12;
-					break;
-				case 15: //LTriangle
-					cl.sType=7;
-					break;
-				case 16: //RTriangle
-					cl.sType=8;
-					break;
-				case 17: //Hexagon
-				case 19: //Pentagon
-					cl.sType=15;
-					break;
-				case 18: //Star
-					cl.sType=14;
-					break;
-				default:
-					cl.sType=0;
-				}
-
-				switch(opj.curveSymbolType(g,l,c)>>8)
-				{
-				case 0:
-					cl.fillCol=color;
-					break;
-				case 1:
-				case 2:
-				case 8:
-				case 9:
-				case 10:
-				case 11:
-					color=opj.curveSymbolFillColor(g,l,c);
-					if((style==Graph::Scatter || style==Graph::LineSymbols || style==Graph::Area)&&color==0xF7)//0xF7 -Automatic color
-						color=17;// depend on Origin settings - not stored in file
-					cl.fillCol=color;
-					break;
-				default:
-					cl.fillCol=-1;
-				}
-
-				cl.lWidth = float(ceil(opj.curveLineWidth(g,l,c)));
-				color=opj.curveLineColor(g,l,c);
-				cl.lCol=(color==0xF7?0:color); //0xF7 -Automatic color
-				int linestyle=opj.curveLineStyle(g,l,c);
-				cl.filledArea=(opj.curveIsFilledArea(g,l,c)||style==Graph::VerticalBars||style==Graph::HorizontalBars||style==Graph::Histogram||style == Graph::Pie)?1:0;
-				if(cl.filledArea)
-				{
-					switch(opj.curveFillPattern(g,l,c))
-					{
-					case 0:
-						cl.aStyle=0;
-						break;
-					case 1:
-					case 2:
-					case 3:
-						cl.aStyle=4;
-						break;
-					case 4:
-					case 5:
-					case 6:
-						cl.aStyle=5;
-						break;
-					case 7:
-					case 8:
-					case 9:
-						cl.aStyle=6;
-						break;
-					case 10:
-					case 11:
-					case 12:
-						cl.aStyle=1;
-						break;
-					case 13:
-					case 14:
-					case 15:
-						cl.aStyle=2;
-						break;
-					case 16:
-					case 17:
-					case 18:
-						cl.aStyle=3;
-						break;
-					}
-					color=(cl.aStyle==0 ? opj.curveFillAreaColor(g,l,c) : opj.curveFillPatternColor(g,l,c));
-					cl.aCol=(color==0xF7?0:color); //0xF7 -Automatic color
-					if (style == Graph::VerticalBars || style == Graph::HorizontalBars || style == Graph::Histogram || style == Graph::Pie)
-					{
-						color=opj.curveFillPatternBorderColor(g,l,c);
-						cl.lCol = (color==0xF7?0:color); //0xF7 -Automatic color
-						color=(cl.aStyle==0 ? opj.curveFillAreaColor(g,l,c) : opj.curveFillPatternColor(g,l,c));
-						cl.aCol=(color==0xF7?cl.lCol:color); //0xF7 -Automatic color
-						cl.lWidth = float(ceil(opj.curveFillPatternBorderWidth(g,l,c)));
-						linestyle=opj.curveFillPatternBorderStyle(g,l,c);
-					}
-				}
-				switch (linestyle)
-				{
-					case OPJFile::Solid:
-						cl.lStyle=0;
-						break;
-					case OPJFile::Dash:
-					case OPJFile::ShortDash:
-						cl.lStyle=1;
-						break;
-					case OPJFile::Dot:
-					case OPJFile::ShortDot:
-						cl.lStyle=2;
-						break;
-					case OPJFile::DashDot:
-					case OPJFile::ShortDashDot:
-						cl.lStyle=3;
-						break;
-					case OPJFile::DashDotDot:
-						cl.lStyle=4;
-						break;
-				}
-
-				graph->updateCurveLayout(curve, &cl);
-				if (style == Graph::VerticalBars || style == Graph::HorizontalBars)
-				{
-					QwtBarCurve *b = static_cast<QwtBarCurve*>(graph->curve(c));
-					if (b)
-						b->setGap(qRound(100-opj.curveSymbolSize(g,l,c)*10));
-				}
-				else if(style == Graph::Histogram)
-				{
-					QwtHistogram *h = static_cast<QwtHistogram*>(graph->curve(c));
-					if (h)
-					{
-						vector<double> bin=opj.layerHistogram(g,l);
-						if(bin.size()==3)
-							h->setBinning(false, bin[0], bin[1], bin[2]);
-						h->loadData();
-					}
-				}
-				else if(style == Graph::Pie)
-				{
-					QwtPieCurve *p = static_cast<QwtPieCurve*>(graph->curve(c));
-					switch (linestyle)
-					{
-					case OPJFile::Solid:
-						cl.lStyle=Qt::SolidLine;
-						break;
-					case OPJFile::Dash:
-					case OPJFile::ShortDash:
-						cl.lStyle=Qt::DashLine;
-						break;
-					case OPJFile::Dot:
-					case OPJFile::ShortDot:
-						cl.lStyle=Qt::DotLine;
-						break;
-					case OPJFile::DashDot:
-					case OPJFile::ShortDashDot:
-						cl.lStyle=Qt::DashDotLine;
-						break;
-					case OPJFile::DashDotDot:
-						cl.lStyle=Qt::DashDotDotLine;
-						break;
-					}
-					p->setPen(QPen(ColorBox::color(cl.lCol), cl.lWidth, (Qt::PenStyle)cl.lStyle));
-					p->setFirstColor(opj.curveFillAreaFirstColor(g,l,c));
-					//geometry
-                    p->setRadius(opj.curvePieProperties(g,l,c).radius);
-                    p->setThickness(opj.curvePieProperties(g,l,c).thickness);
-					p->setViewAngle(opj.curvePieProperties(g,l,c).view_angle);
-					p->setStartAzimuth(opj.curvePieProperties(g,l,c).rotation);
-					p->setCounterClockwise(opj.curvePieProperties(g,l,c).clockwise_rotation);
-                    p->setHorizontalOffset(opj.curvePieProperties(g,l,c).horizontal_offset);
-					//labels
-					p->setLabelsEdgeDistance(opj.curvePieProperties(g,l,c).distance);
-					p->setLabelsAutoFormat(opj.curvePieProperties(g,l,c).format_automatic);
-					p->setLabelPercentagesFormat(opj.curvePieProperties(g,l,c).format_percentages);
-                    p->setLabelValuesFormat(opj.curvePieProperties(g,l,c).format_values);
-                    p->setLabelCategories(opj.curvePieProperties(g,l,c).format_categories);
-                    p->setFixedLabelsPosition(opj.curvePieProperties(g,l,c).position_associate);
-				}
-				else if(style == Graph::VectXYXY || style == Graph::VectXYAM)
-				{
-					vectorProperties vector = opj.curveVectorProperties(g,l,c);
-					graph->updateVectorsLayout(c, ColorBox::color(cl.symCol), ceil(vector.width),
-						int(floor(vector.arrow_lenght*fVectorArrowScaleFactor + 0.5)), vector.arrow_angle, vector.arrow_closed, vector.position);
-				}
-				switch(opj.curveLineConnect(g,l,c))
-				{
-				case OPJFile::NoLine:
-					graph->setCurveStyle(c, QwtPlotCurve::NoCurve);
-					break;
-				case OPJFile::Straight:
-					graph->setCurveStyle(c, QwtPlotCurve::Lines);
-					break;
-				case OPJFile::BSpline:
-				case OPJFile::Bezier:
-				case OPJFile::Spline:
-					graph->setCurveStyle(c, 5);
-					break;
-				case OPJFile::StepHorizontal:
-				case OPJFile::StepHCenter:
-					graph->setCurveStyle(c, QwtPlotCurve::Steps);
-					break;
-				case OPJFile::StepVertical:
-				case OPJFile::StepVCenter:
-					graph->setCurveStyle(c, 6);
-					break;
-				}
-
-				}
-				catch(...)
-				{
-				}
-			}
-			graphLayerRange rangeX=opj.layerXRange(g,l);
-			vector<int>    ticksX=opj.layerXTicks(g,l);
-			graphLayerRange rangeY=opj.layerYRange(g,l);
-			vector<int>	   ticksY=opj.layerYTicks(g,l);
-			if(style == Graph::HorizontalBars)
-			{
-				graph->setScale(0,rangeX.min,rangeX.max,rangeX.step,ticksX[0],ticksX[1],opj.layerXScale(g,l));
-				graph->setScale(2,rangeY.min,rangeY.max,rangeY.step,ticksY[0],ticksY[1],opj.layerYScale(g,l));
-			}
-			else if(style != Graph::Box)
-			{
-
-				graphAxisBreak breakX = opj.layerXBreak(g,l);
-				graphAxisBreak breakY = opj.layerYBreak(g,l);
-				if(breakX.show)
-					graph->setScale(2,rangeX.min,rangeX.max,rangeX.step,ticksX[0],ticksX[1],opj.layerXScale(g,l),
-									false,
-									breakX.from, breakX.to,
-									breakX.position,
-									breakX.scale_increment_before, breakX.scale_increment_after,
-									breakX.minor_ticks_before, breakX.minor_ticks_after, breakX.log10);
-				else
-					graph->setScale(2,rangeX.min,rangeX.max,rangeX.step,ticksX[0],ticksX[1],opj.layerXScale(g,l));
-
-				if(breakY.show)
-					graph->setScale(0,rangeY.min,rangeY.max,rangeY.step,ticksY[0],ticksY[1],opj.layerYScale(g,l),
-					false,
-					breakY.from, breakY.to,
-					breakY.position,
-					breakY.scale_increment_before, breakY.scale_increment_after,
-					breakY.minor_ticks_before, breakY.minor_ticks_after, breakY.log10);
-				else
-					graph->setScale(0,rangeY.min,rangeY.max,rangeY.step,ticksY[0],ticksY[1],opj.layerYScale(g,l));
-			}
-
-			//grid
-			vector<graphGrid> grids = opj.layerGrid(g,l);
-			Grid *grid = graph->grid();
-			grid->enableX(!grids[0].hidden);
-			grid->enableXMin(!grids[1].hidden);
-			grid->enableY(!grids[2].hidden);
-			grid->enableYMin(!grids[3].hidden);
-
-			grid->setMajPenX(QPen(ColorBox::color(grids[0].color), ceil(grids[0].width),
-							Graph::getPenStyle(translateOrigin2QtiplotLineStyle(grids[0].style))));
-			grid->setMinPenX(QPen(ColorBox::color(grids[1].color), ceil(grids[1].width),
-							Graph::getPenStyle(translateOrigin2QtiplotLineStyle(grids[1].style))));
-			grid->setMajPenY(QPen(ColorBox::color(grids[2].color), ceil(grids[2].width),
-							Graph::getPenStyle(translateOrigin2QtiplotLineStyle(grids[2].style))));
-			grid->setMinPenY(QPen(ColorBox::color(grids[3].color), ceil(grids[3].width),
-							Graph::getPenStyle(translateOrigin2QtiplotLineStyle(grids[3].style))));
-
-			grid->setAxis(2, 0);
-			grid->enableZeroLineX(0);
-			grid->enableZeroLineY(0);
-
-			vector<graphAxisFormat> formats=opj.layerAxisFormat(g,l);
-			vector<graphAxisTick> ticks=opj.layerAxisTickLabels(g,l);
-			for(int i=0; i<4; ++i)
-			{
-				QString data(ticks[i].dataName.c_str());
-				QString tableName=data.right(data.length()-2) + "_" + ticks[i].colName.c_str();
-
-				QString formatInfo;
-				int format = 0;
-				int type;
-				int prec=ticks[i].decimal_places;
-				switch(ticks[i].value_type)
-				{
-				case OPJFile::Numeric:
-					type = ScaleDraw::Numeric;
-					switch(ticks[i].value_type_specification)
-					{
-					case 0: //Decimal 1000
-						if(prec != -1)
-							format = 1;
-						else
-							format = 0;
-
-						break;
-					case 1: //Scientific
-						format=2;
-						break;
-					case 2: //Engeneering
-					case 3: //Decimal 1,000
-						format=0;
-						break;
-					}
-					if(prec == -1)
-						prec = 2;
-					break;
-				case OPJFile::Text: //Text
-					type=ScaleDraw::Text;
-					break;
-				case 2: // Date
-					type=ScaleDraw::Date;
-					break;
-				case 3: // Time
-					type=ScaleDraw::Time;
-					break;
-				case OPJFile::Month: // Month
-					type=ScaleDraw::Month;
-					format=ticks[i].value_type_specification;
-					break;
-				case OPJFile::Day: // Day
-					type=ScaleDraw::Day;
-					format=ticks[i].value_type_specification;
-					break;
-				case OPJFile::ColumnHeading:
-					type=ScaleDraw::ColHeader;
-					switch(ticks[i].value_type_specification)
-					{
-					case 0: //Decimal 1000
-						format=1;
-						break;
-					case 1: //Scientific
-						format=2;
-						break;
-					case 2: //Engeneering
-					case 3: //Decimal 1,000
-						format=0;
-						break;
-					}
-					prec=2;
-					break;
-				default:
-					type=ScaleDraw::Numeric;
-					format=0;
-					prec=2;
-				}
-
-				graph->showAxis(i, type, tableName, mw->table(tableName), !(formats[i].hidden),
-					tickTypeMap[formats[i].majorTicksType], tickTypeMap[formats[i].minorTicksType],
-					!(ticks[i].hidden),	ColorBox::color(formats[i].color), format, prec,
-					ticks[i].rotation, 0, "", (ticks[i].color==0xF7 ? ColorBox::color(formats[i].color) : ColorBox::color(ticks[i].color)));
-
-				QFont fnt = graph->axisTitleFont(i);
-				int fontsize;
-				switch(i)
-				{
-				case 0:
-				case 1:
-					fontsize = opj.layerYAxisTitle(g,l).fontsize;
-					break;
-				case 2:
-				case 3:
-					fontsize = opj.layerXAxisTitle(g,l).fontsize;
-					break;
-				}
-				fnt.setPointSize(int(floor(fontsize*fFontScaleFactor + 0.5)));
-				fnt.setBold(false);
-				graph->setAxisTitleFont(i, fnt);
-
-				fnt = graph->axisFont(i);
-				fnt.setPointSize(int(floor(ticks[i].fontsize*fFontScaleFactor + 0.5)));
-				graph->setAxisFont(i, fnt);
-			}
-
-			graph->setAutoscaleFonts(true);
-        	graph->setIgnoreResizeEvents(!mw->autoResizeLayers);
-
-			int nXDelta = graph->plotWidget()->width() - graph->plotWidget()->canvas()->width();
-			int nYDelta = graph->plotWidget()->height() - graph->plotWidget()->canvas()->height();
-			QPoint posCanvas =  graph->plotWidget()->canvas()->pos();
-
-			graph->resize(int(layerRect.width()*fXScale) + nXDelta,
-				int(layerRect.height()*fYScale) + nYDelta);
-
-			int newXGraphPos = int(layerRect.left*fXScale) - posCanvas.x() - ml->x();
-			int newYGraphPos = int(layerRect.top*fYScale) - posCanvas.y() - ml->y();
-			graph->move((newXGraphPos > 0 ? newXGraphPos : 0), (newYGraphPos > 0 ? newYGraphPos : 0));
-
-			graph->plotWidget()->resize(int(layerRect.width()*fXScale) + nXDelta,
-				int(layerRect.height()*fYScale) + nYDelta);
-
-			//add texts
-			vector<text> texts=opj.layerTexts(g, l);
-			if(style != Graph::Pie)
-			{
-				for(size_t i=0; i<texts.size(); ++i)
-				{
-					addText(texts[i], graph, 0, layerRect, fFontScaleFactor, fXScale, fYScale);
-				}
-			}
-
-			if(legend)
-				addText(opj.layerLegend(g,l), graph, legend, layerRect, fFontScaleFactor, fXScale, fYScale);
-
-			vector<line> lines = opj.layerLines(g, l);
-			for(size_t i=0; i<lines.size(); ++i)
-			{
-				ArrowMarker mrk;
-				mrk.setStartPoint(lines[i].begin.x, lines[i].begin.y);
-				mrk.setEndPoint(lines[i].end.x, lines[i].end.y);
-				mrk.drawStartArrow(lines[i].begin.shape_type > 0);
-				mrk.drawEndArrow(lines[i].end.shape_type > 0);
-				mrk.setHeadLength(int(lines[i].end.shape_length));
-                mrk.setHeadAngle(arrowAngle(lines[i].end.shape_length, lines[i].end.shape_width));
-				mrk.setColor(ColorBox::color(lines[i].color));
-				mrk.setWidth((int)lines[i].width);
-				Qt::PenStyle s;
-
-				switch(lines[i].line_style)
-				{
-				case OPJFile::Solid:
-					s=Qt::SolidLine;
-					break;
-				case OPJFile::Dash:
-				case OPJFile::ShortDash:
-					s=Qt::DashLine;
-					break;
-				case OPJFile::Dot:
-				case OPJFile::ShortDot:
-					s=Qt::DotLine;
-					break;
-				case OPJFile::DashDot:
-				case OPJFile::ShortDashDot:
-					s=Qt::DashDotLine;
-					break;
-				case OPJFile::DashDotDot:
-					s=Qt::DashDotDotLine;
-					break;
-				default:
-					s=Qt::SolidLine;
-				}
-				mrk.setStyle(s);
-				graph->addArrow(&mrk);
-			}
-
-			vector<bitmap> bitmaps=opj.layerBitmaps(g, l);
-			for(size_t i=0; i<bitmaps.size(); ++i)
-			{
-				QPixmap bmp;
-				bmp.loadFromData(bitmaps[i].data, uint(bitmaps[i].size), "BMP");
-				QTemporaryFile file;
-				file.setFileTemplate(QDir::tempPath() + "/XXXXXX.bmp");
-				if (file.open())
-				{
-					bmp.save(file.fileName(), "BMP");
-					ImageMarker *mrk = graph->addImage(file.fileName());
-					double left, top, right, bottom;
-					left = top = right = bottom = 0.0;
-					switch(bitmaps[i].attach)
-					{
-					case OPJFile::Scale:
-						left = bitmaps[i].left;
-						top = bitmaps[i].top;
-						right = left + bitmaps[i].width;
-						bottom = top - bitmaps[i].height;
-						break;
-					case OPJFile::Frame:
-						if(bitmaps[i].width > 0)
-						{
-							left = (rangeX.max-rangeX.min)*bitmaps[i].left + rangeX.min;
-							right = left + bitmaps[i].width;
-						}
-						else
-						{
-							right = (rangeX.max-rangeX.min)*bitmaps[i].left + rangeX.min;
-							left = right + bitmaps[i].width;
-						}
-
-						if(bitmaps[i].height > 0)
-						{
-							top = rangeY.max - (rangeY.max-rangeY.min)*bitmaps[i].top;
-							bottom = top - bitmaps[i].height;
-						}
-						else
-						{
-							bottom = rangeY.max - (rangeY.max-rangeY.min)*bitmaps[i].top;
-							top = bottom - bitmaps[i].height;
-						}
-						break;
-						case OPJFile::Page:
-							//rect graphRect = opj.graphRect(g);
-							left = (rangeX.max-rangeX.min)*(bitmaps[i].left - (double)layerRect.left/(double)graphRect.width())/((double)layerRect.width()/(double)graphRect.width()) + rangeX.min;
-							top = rangeY.max - (rangeY.max-rangeY.min)*(bitmaps[i].top - (double)layerRect.top/(double)graphRect.height())/((double)layerRect.height()/(double)graphRect.height());
-							right = left + bitmaps[i].width;
-							bottom = top - bitmaps[i].height;
-							break;
-					}
-
-					mrk->setBoundingRect(left, top, right, bottom);
-				}
-			}
-		}
-		//cascade the graphs
-		if(!opj.graphHidden(g))
-		{
-			ml->move(QPoint(graphWindowRect.left, graphWindowRect.top));
-
-			switch(opj.graphState(g))
-			{
-			case originWindow::Minimized:
-				mw->minimizeWindow(ml);
-				break;
-			case originWindow::Maximized:
-				ml->show(); // to correct scaling with maximize
-				mw->maximizeWindow(ml);
-				break;
-			default:
-				ml->show();
-			}
-		}
-		else
-		{
-			ml->show();
-			//ml->arrangeLayers(true,true);
-			mw->hideWindow(ml);
-		}
-	}
-	if(visible_count>0)
-		xoffset++;
-	return true;
+bool ImportOPJ::importGraphs(const OPJFile &opj) {
+  int visible_count = 0;
+  int tickTypeMap[] = {0, 3, 1, 2};
+  for (int g = 0; g < opj.numGraphs(); ++g) {
+    MultiLayer *ml = mw->multilayerPlot(opj.graphName(g), 0, 0, 0);
+    if (!ml)
+      return false;
+
+    ml->setCaptionPolicy((MdiSubWindow::CaptionPolicy)opj.graphTitle(g));
+    ml->setBirthDate(JulianDateTime2String(opj.graphCreationDate(g)));
+    ml->hide(); //!hack used in order to avoid resize and repaint events
+    ml->setWindowLabel(opj.graphLabel(g));
+
+    rect graphRect = opj.graphRect(g);
+    rect graphWindowRect = opj.graphWindowRect(g);
+    ml->resize(graphWindowRect.width() -
+                   (ml->frameGeometry().width() - ml->width()),
+               graphWindowRect.height() -
+                   (ml->frameGeometry().height() - ml->height()));
+
+    double fXScale = (double)ml->width() / (double)graphRect.width();
+    double fYScale = (double)ml->height() / (double)graphRect.height();
+    fXScale = fYScale = QMIN(fXScale, fYScale);
+
+    double fWindowFactor = QMIN((double)graphWindowRect.width() / 500.0,
+                                (double)graphWindowRect.height() / 350.0);
+    double fFontScaleFactor = 0.37 * fWindowFactor;
+    double fVectorArrowScaleFactor = 0.08 * fWindowFactor;
+
+    for (int l = 0; l < opj.numLayers(g); ++l) {
+      Graph *graph = ml->addLayer();
+      if (!graph)
+        return false;
+
+      rect layerRect = opj.layerRect(g, l);
+
+      graph->setXAxisTitle(parseOriginText(
+          QString::fromLocal8Bit(opj.layerXAxisTitle(g, l).txt.c_str())));
+      graph->setYAxisTitle(parseOriginText(
+          QString::fromLocal8Bit(opj.layerYAxisTitle(g, l).txt.c_str())));
+      LegendWidget *legend = 0;
+      if (!opj.layerLegend(g, l).txt.empty()) {
+        legend = graph->newLegend(parseOriginText(
+            QString::fromLocal8Bit(opj.layerLegend(g, l).txt.c_str())));
+      }
+      int auto_color = 0;
+      // int auto_color1=0;
+      int style = 0;
+      for (int c = 0; c < opj.numCurves(g, l); c++) {
+        try {
+          QString data(opj.curveDataName(g, l, c));
+          int color = 0;
+          switch (opj.curveType(g, l, c)) {
+          case OPJFile::Line:
+            style = Graph::Line;
+            break;
+          case OPJFile::Scatter:
+            style = Graph::Scatter;
+            break;
+          case OPJFile::LineSymbol:
+            style = Graph::LineSymbols;
+            break;
+          case OPJFile::ErrorBar:
+          case OPJFile::XErrorBar:
+            style = Graph::ErrorBars;
+            break;
+          case OPJFile::Column:
+            style = Graph::VerticalBars;
+            break;
+          case OPJFile::Bar:
+            style = Graph::HorizontalBars;
+            break;
+          case OPJFile::Histogram:
+            style = Graph::Histogram;
+            break;
+          case OPJFile::Pie:
+            style = Graph::Pie;
+            break;
+          case OPJFile::Box:
+            style = Graph::Box;
+            break;
+          case OPJFile::FlowVector:
+            style = Graph::VectXYXY;
+            break;
+          case OPJFile::Vector:
+            style = Graph::VectXYAM;
+            break;
+          case OPJFile::Area:
+          case OPJFile::AreaStack:
+            style = Graph::Area;
+            break;
+          case OPJFile::TextPlot:
+            style = OPJFile::TextPlot;
+            break;
+          default:
+            continue;
+          }
+          QString tableName;
+          QStringList formulas;
+          double start, end;
+          int s;
+          PlotCurve *curve = NULL;
+          switch (data[0].toAscii()) {
+          case 'T':
+            tableName = data.right(data.length() - 2);
+            if (style == Graph::ErrorBars) {
+              int flags = opj.curveSymbolType(g, l, c);
+              curve = graph->addErrorBars(
+                  tableName + "_" + opj.curveXColName(g, l, c),
+                  mw->table(tableName),
+                  tableName + "_" + opj.curveYColName(g, l, c),
+                  ((flags & 0x10) == 0x10 ? 0 : 1),
+                  int(ceil(opj.curveLineWidth(g, l, c))),
+                  int(ceil(opj.curveSymbolSize(g, l, c))), QColor(Qt::black),
+                  (flags & 0x40) == 0x40, (flags & 2) == 2, (flags & 1) == 1);
+            } else if (style == Graph::Histogram)
+              curve = graph->insertCurve(
+                  mw->table(tableName),
+                  tableName + "_" + opj.curveYColName(g, l, c), style);
+            else if (style == Graph::Pie || style == Graph::Box) {
+              QStringList names;
+              names << (tableName + "_" + opj.curveYColName(g, l, c));
+              graph->addCurves(mw->table(tableName), names, style);
+            } else if (style == Graph::VectXYXY) {
+              QStringList names;
+              vectorProperties vector = opj.curveVectorProperties(g, l, c);
+              names << (tableName + "_" + opj.curveXColName(g, l, c))
+                    << (tableName + "_" + opj.curveYColName(g, l, c))
+                    << (tableName + "_" + QString(vector.endXColName.c_str()))
+                    << (tableName + "_" + QString(vector.endYColName.c_str()));
+
+              graph->addCurves(mw->table(tableName), names, style);
+            } else if (style == Graph::VectXYAM) {
+              QStringList names;
+              vectorProperties vector = opj.curveVectorProperties(g, l, c);
+              names << (tableName + "_" + opj.curveXColName(g, l, c))
+                    << (tableName + "_" + opj.curveYColName(g, l, c))
+                    << (tableName + "_" + QString(vector.angleColName.c_str()))
+                    << (tableName + "_" +
+                        QString(vector.magnitudeColName.c_str()));
+
+              graph->addCurves(mw->table(tableName), names, style);
+            } else if (style == OPJFile::TextPlot) {
+              Table *table = mw->table(tableName);
+              QString labelsCol = opj.curveYColName(g, l, c);
+              int xcol = table->colX(table->colIndex(labelsCol));
+              int ycol = table->colY(table->colIndex(labelsCol));
+              if (xcol < 0 || ycol < 0)
+                return false;
+
+              DataCurve *mc = graph->masterCurve(table->colName(xcol),
+                                                 table->colName(ycol));
+              if (mc) {
+                graph->replot();
+                mc->setLabelsColumnName(labelsCol);
+              }
+            } else
+              curve = graph->insertCurve(
+                  mw->table(tableName),
+                  tableName + "_" + opj.curveXColName(g, l, c),
+                  tableName + "_" + opj.curveYColName(g, l, c), style);
+            break;
+          case 'F':
+            s = opj.functionIndex(
+                data.right(data.length() - 2).toStdString().c_str());
+            if (s < 0)
+              break;
+            int type;
+            if (opj.functionType(s) == 1) // Polar
+            {
+              type = 2;
+              formulas << opj.functionFormula(s) << "x";
+              start = M_PI / 180 * opj.functionBegin(s);
+              end = M_PI / 180 * opj.functionEnd(s);
+            } else {
+              type = 0;
+              formulas << opj.functionFormula(s);
+              start = opj.functionBegin(s);
+              end = opj.functionEnd(s);
+            }
+            curve =
+                graph->addFunction(formulas, start, end, opj.functionPoints(s),
+                                   "x", type, opj.functionName(s));
+
+            mw->updateFunctionLists(type, formulas);
+            break;
+          default:
+            continue;
+          }
+
+          // strange behaviour of insert curve - legend added - need to rollback
+          // legend text
+          if (legend) {
+            legend->setText(parseOriginText(
+                QString::fromLocal8Bit(opj.layerLegend(g, l).txt.c_str())));
+          }
+
+          CurveLayout cl = graph->initCurveLayout(style, opj.numCurves(g, l));
+          cl.sSize = int(ceil(opj.curveSymbolSize(g, l, c)));
+          cl.penWidth = float(opj.curveSymbolThickness(g, l, c));
+          color = opj.curveSymbolColor(g, l, c);
+          if ((style == Graph::Scatter || style == Graph::LineSymbols ||
+               style == Graph::Area) &&
+              color == 0xF7) // 0xF7 -Automatic color
+            color = auto_color++;
+          cl.symCol = color;
+          switch (opj.curveSymbolType(g, l, c) & 0xFF) {
+          case 0: // NoSymbol
+            cl.sType = 0;
+            break;
+          case 1: // Rect
+            cl.sType = 2;
+            break;
+          case 2:  // Ellipse
+          case 20: // Sphere
+            cl.sType = 1;
+            break;
+          case 3: // UTriangle
+            cl.sType = 6;
+            break;
+          case 4: // DTriangle
+            cl.sType = 5;
+            break;
+          case 5: // Diamond
+            cl.sType = 3;
+            break;
+          case 6: // Cross +
+            cl.sType = 9;
+            break;
+          case 7: // Cross x
+            cl.sType = 10;
+            break;
+          case 8: // Snow
+            cl.sType = 13;
+            break;
+          case 9: // Horizontal -
+            cl.sType = 11;
+            break;
+          case 10: // Vertical |
+            cl.sType = 12;
+            break;
+          case 15: // LTriangle
+            cl.sType = 7;
+            break;
+          case 16: // RTriangle
+            cl.sType = 8;
+            break;
+          case 17: // Hexagon
+          case 19: // Pentagon
+            cl.sType = 15;
+            break;
+          case 18: // Star
+            cl.sType = 14;
+            break;
+          default:
+            cl.sType = 0;
+          }
+
+          switch (opj.curveSymbolType(g, l, c) >> 8) {
+          case 0:
+            cl.fillCol = color;
+            break;
+          case 1:
+          case 2:
+          case 8:
+          case 9:
+          case 10:
+          case 11:
+            color = opj.curveSymbolFillColor(g, l, c);
+            if ((style == Graph::Scatter || style == Graph::LineSymbols ||
+                 style == Graph::Area) &&
+                color == 0xF7) // 0xF7 -Automatic color
+              color = 17;      // depend on Origin settings - not stored in file
+            cl.fillCol = color;
+            break;
+          default:
+            cl.fillCol = -1;
+          }
+
+          cl.lWidth = float(ceil(opj.curveLineWidth(g, l, c)));
+          color = opj.curveLineColor(g, l, c);
+          cl.lCol = (color == 0xF7 ? 0 : color); // 0xF7 -Automatic color
+          int linestyle = opj.curveLineStyle(g, l, c);
+          cl.filledArea =
+              (opj.curveIsFilledArea(g, l, c) || style == Graph::VerticalBars ||
+               style == Graph::HorizontalBars || style == Graph::Histogram ||
+               style == Graph::Pie)
+                  ? 1
+                  : 0;
+          if (cl.filledArea) {
+            switch (opj.curveFillPattern(g, l, c)) {
+            case 0:
+              cl.aStyle = 0;
+              break;
+            case 1:
+            case 2:
+            case 3:
+              cl.aStyle = 4;
+              break;
+            case 4:
+            case 5:
+            case 6:
+              cl.aStyle = 5;
+              break;
+            case 7:
+            case 8:
+            case 9:
+              cl.aStyle = 6;
+              break;
+            case 10:
+            case 11:
+            case 12:
+              cl.aStyle = 1;
+              break;
+            case 13:
+            case 14:
+            case 15:
+              cl.aStyle = 2;
+              break;
+            case 16:
+            case 17:
+            case 18:
+              cl.aStyle = 3;
+              break;
+            }
+            color = (cl.aStyle == 0 ? opj.curveFillAreaColor(g, l, c)
+                                    : opj.curveFillPatternColor(g, l, c));
+            cl.aCol = (color == 0xF7 ? 0 : color); // 0xF7 -Automatic color
+            if (style == Graph::VerticalBars ||
+                style == Graph::HorizontalBars || style == Graph::Histogram ||
+                style == Graph::Pie) {
+              color = opj.curveFillPatternBorderColor(g, l, c);
+              cl.lCol = (color == 0xF7 ? 0 : color); // 0xF7 -Automatic color
+              color = (cl.aStyle == 0 ? opj.curveFillAreaColor(g, l, c)
+                                      : opj.curveFillPatternColor(g, l, c));
+              cl.aCol =
+                  (color == 0xF7 ? cl.lCol : color); // 0xF7 -Automatic color
+              cl.lWidth = float(ceil(opj.curveFillPatternBorderWidth(g, l, c)));
+              linestyle = opj.curveFillPatternBorderStyle(g, l, c);
+            }
+          }
+          switch (linestyle) {
+          case OPJFile::Solid:
+            cl.lStyle = 0;
+            break;
+          case OPJFile::Dash:
+          case OPJFile::ShortDash:
+            cl.lStyle = 1;
+            break;
+          case OPJFile::Dot:
+          case OPJFile::ShortDot:
+            cl.lStyle = 2;
+            break;
+          case OPJFile::DashDot:
+          case OPJFile::ShortDashDot:
+            cl.lStyle = 3;
+            break;
+          case OPJFile::DashDotDot:
+            cl.lStyle = 4;
+            break;
+          }
+
+          graph->updateCurveLayout(curve, &cl);
+          if (style == Graph::VerticalBars || style == Graph::HorizontalBars) {
+            QwtBarCurve *b = static_cast<QwtBarCurve *>(graph->curve(c));
+            if (b)
+              b->setGap(qRound(100 - opj.curveSymbolSize(g, l, c) * 10));
+          } else if (style == Graph::Histogram) {
+            QwtHistogram *h = static_cast<QwtHistogram *>(graph->curve(c));
+            if (h) {
+              vector<double> bin = opj.layerHistogram(g, l);
+              if (bin.size() == 3)
+                h->setBinning(false, bin[0], bin[1], bin[2]);
+              h->loadData();
+            }
+          } else if (style == Graph::Pie) {
+            QwtPieCurve *p = static_cast<QwtPieCurve *>(graph->curve(c));
+            switch (linestyle) {
+            case OPJFile::Solid:
+              cl.lStyle = Qt::SolidLine;
+              break;
+            case OPJFile::Dash:
+            case OPJFile::ShortDash:
+              cl.lStyle = Qt::DashLine;
+              break;
+            case OPJFile::Dot:
+            case OPJFile::ShortDot:
+              cl.lStyle = Qt::DotLine;
+              break;
+            case OPJFile::DashDot:
+            case OPJFile::ShortDashDot:
+              cl.lStyle = Qt::DashDotLine;
+              break;
+            case OPJFile::DashDotDot:
+              cl.lStyle = Qt::DashDotDotLine;
+              break;
+            }
+            p->setPen(QPen(ColorBox::color(cl.lCol), cl.lWidth,
+                           (Qt::PenStyle)cl.lStyle));
+            p->setFirstColor(opj.curveFillAreaFirstColor(g, l, c));
+            // geometry
+            p->setRadius(opj.curvePieProperties(g, l, c).radius);
+            p->setThickness(opj.curvePieProperties(g, l, c).thickness);
+            p->setViewAngle(opj.curvePieProperties(g, l, c).view_angle);
+            p->setStartAzimuth(opj.curvePieProperties(g, l, c).rotation);
+            p->setCounterClockwise(
+                opj.curvePieProperties(g, l, c).clockwise_rotation);
+            p->setHorizontalOffset(
+                opj.curvePieProperties(g, l, c).horizontal_offset);
+            // labels
+            p->setLabelsEdgeDistance(opj.curvePieProperties(g, l, c).distance);
+            p->setLabelsAutoFormat(
+                opj.curvePieProperties(g, l, c).format_automatic);
+            p->setLabelPercentagesFormat(
+                opj.curvePieProperties(g, l, c).format_percentages);
+            p->setLabelValuesFormat(
+                opj.curvePieProperties(g, l, c).format_values);
+            p->setLabelCategories(
+                opj.curvePieProperties(g, l, c).format_categories);
+            p->setFixedLabelsPosition(
+                opj.curvePieProperties(g, l, c).position_associate);
+          } else if (style == Graph::VectXYXY || style == Graph::VectXYAM) {
+            vectorProperties vector = opj.curveVectorProperties(g, l, c);
+            graph->updateVectorsLayout(
+                c, ColorBox::color(cl.symCol), ceil(vector.width),
+                int(floor(vector.arrow_lenght * fVectorArrowScaleFactor + 0.5)),
+                vector.arrow_angle, vector.arrow_closed, vector.position);
+          }
+          switch (opj.curveLineConnect(g, l, c)) {
+          case OPJFile::NoLine:
+            graph->setCurveStyle(c, QwtPlotCurve::NoCurve);
+            break;
+          case OPJFile::Straight:
+            graph->setCurveStyle(c, QwtPlotCurve::Lines);
+            break;
+          case OPJFile::BSpline:
+          case OPJFile::Bezier:
+          case OPJFile::Spline:
+            graph->setCurveStyle(c, 5);
+            break;
+          case OPJFile::StepHorizontal:
+          case OPJFile::StepHCenter:
+            graph->setCurveStyle(c, QwtPlotCurve::Steps);
+            break;
+          case OPJFile::StepVertical:
+          case OPJFile::StepVCenter:
+            graph->setCurveStyle(c, 6);
+            break;
+          }
+
+        } catch (...) {
+        }
+      }
+      graphLayerRange rangeX = opj.layerXRange(g, l);
+      vector<int> ticksX = opj.layerXTicks(g, l);
+      graphLayerRange rangeY = opj.layerYRange(g, l);
+      vector<int> ticksY = opj.layerYTicks(g, l);
+      if (style == Graph::HorizontalBars) {
+        graph->setScale(0, rangeX.min, rangeX.max, rangeX.step, ticksX[0],
+                        ticksX[1], opj.layerXScale(g, l));
+        graph->setScale(2, rangeY.min, rangeY.max, rangeY.step, ticksY[0],
+                        ticksY[1], opj.layerYScale(g, l));
+      } else if (style != Graph::Box) {
+
+        graphAxisBreak breakX = opj.layerXBreak(g, l);
+        graphAxisBreak breakY = opj.layerYBreak(g, l);
+        if (breakX.show)
+          graph->setScale(
+              2, rangeX.min, rangeX.max, rangeX.step, ticksX[0], ticksX[1],
+              opj.layerXScale(g, l), false, breakX.from, breakX.to,
+              breakX.position, breakX.scale_increment_before,
+              breakX.scale_increment_after, breakX.minor_ticks_before,
+              breakX.minor_ticks_after, breakX.log10);
+        else
+          graph->setScale(2, rangeX.min, rangeX.max, rangeX.step, ticksX[0],
+                          ticksX[1], opj.layerXScale(g, l));
+
+        if (breakY.show)
+          graph->setScale(
+              0, rangeY.min, rangeY.max, rangeY.step, ticksY[0], ticksY[1],
+              opj.layerYScale(g, l), false, breakY.from, breakY.to,
+              breakY.position, breakY.scale_increment_before,
+              breakY.scale_increment_after, breakY.minor_ticks_before,
+              breakY.minor_ticks_after, breakY.log10);
+        else
+          graph->setScale(0, rangeY.min, rangeY.max, rangeY.step, ticksY[0],
+                          ticksY[1], opj.layerYScale(g, l));
+      }
+
+      // grid
+      vector<graphGrid> grids = opj.layerGrid(g, l);
+      Grid *grid = graph->grid();
+      grid->enableX(!grids[0].hidden);
+      grid->enableXMin(!grids[1].hidden);
+      grid->enableY(!grids[2].hidden);
+      grid->enableYMin(!grids[3].hidden);
+
+      grid->setMajPenX(
+          QPen(ColorBox::color(grids[0].color), ceil(grids[0].width),
+               Graph::getPenStyle(
+                   translateOrigin2QtiplotLineStyle(grids[0].style))));
+      grid->setMinPenX(
+          QPen(ColorBox::color(grids[1].color), ceil(grids[1].width),
+               Graph::getPenStyle(
+                   translateOrigin2QtiplotLineStyle(grids[1].style))));
+      grid->setMajPenY(
+          QPen(ColorBox::color(grids[2].color), ceil(grids[2].width),
+               Graph::getPenStyle(
+                   translateOrigin2QtiplotLineStyle(grids[2].style))));
+      grid->setMinPenY(
+          QPen(ColorBox::color(grids[3].color), ceil(grids[3].width),
+               Graph::getPenStyle(
+                   translateOrigin2QtiplotLineStyle(grids[3].style))));
+
+      grid->setAxis(2, 0);
+      grid->enableZeroLineX(0);
+      grid->enableZeroLineY(0);
+
+      vector<graphAxisFormat> formats = opj.layerAxisFormat(g, l);
+      vector<graphAxisTick> ticks = opj.layerAxisTickLabels(g, l);
+      for (int i = 0; i < 4; ++i) {
+        QString data(ticks[i].dataName.c_str());
+        QString tableName =
+            data.right(data.length() - 2) + "_" + ticks[i].colName.c_str();
+
+        QString formatInfo;
+        int format = 0;
+        int type;
+        int prec = ticks[i].decimal_places;
+        switch (ticks[i].value_type) {
+        case OPJFile::Numeric:
+          type = ScaleDraw::Numeric;
+          switch (ticks[i].value_type_specification) {
+          case 0: // Decimal 1000
+            if (prec != -1)
+              format = 1;
+            else
+              format = 0;
+
+            break;
+          case 1: // Scientific
+            format = 2;
+            break;
+          case 2: // Engeneering
+          case 3: // Decimal 1,000
+            format = 0;
+            break;
+          }
+          if (prec == -1)
+            prec = 2;
+          break;
+        case OPJFile::Text: // Text
+          type = ScaleDraw::Text;
+          break;
+        case 2: // Date
+          type = ScaleDraw::Date;
+          break;
+        case 3: // Time
+          type = ScaleDraw::Time;
+          break;
+        case OPJFile::Month: // Month
+          type = ScaleDraw::Month;
+          format = ticks[i].value_type_specification;
+          break;
+        case OPJFile::Day: // Day
+          type = ScaleDraw::Day;
+          format = ticks[i].value_type_specification;
+          break;
+        case OPJFile::ColumnHeading:
+          type = ScaleDraw::ColHeader;
+          switch (ticks[i].value_type_specification) {
+          case 0: // Decimal 1000
+            format = 1;
+            break;
+          case 1: // Scientific
+            format = 2;
+            break;
+          case 2: // Engeneering
+          case 3: // Decimal 1,000
+            format = 0;
+            break;
+          }
+          prec = 2;
+          break;
+        default:
+          type = ScaleDraw::Numeric;
+          format = 0;
+          prec = 2;
+        }
+
+        graph->showAxis(
+            i, type, tableName, mw->table(tableName), !(formats[i].hidden),
+            tickTypeMap[formats[i].majorTicksType],
+            tickTypeMap[formats[i].minorTicksType], !(ticks[i].hidden),
+            ColorBox::color(formats[i].color), format, prec, ticks[i].rotation,
+            0, "", (ticks[i].color == 0xF7 ? ColorBox::color(formats[i].color)
+                                           : ColorBox::color(ticks[i].color)));
+
+        QFont fnt = graph->axisTitleFont(i);
+        int fontsize;
+        switch (i) {
+        case 0:
+        case 1:
+          fontsize = opj.layerYAxisTitle(g, l).fontsize;
+          break;
+        case 2:
+        case 3:
+          fontsize = opj.layerXAxisTitle(g, l).fontsize;
+          break;
+        }
+        fnt.setPointSize(int(floor(fontsize * fFontScaleFactor + 0.5)));
+        fnt.setBold(false);
+        graph->setAxisTitleFont(i, fnt);
+
+        fnt = graph->axisFont(i);
+        fnt.setPointSize(
+            int(floor(ticks[i].fontsize * fFontScaleFactor + 0.5)));
+        graph->setAxisFont(i, fnt);
+      }
+
+      graph->setAutoscaleFonts(true);
+      graph->setIgnoreResizeEvents(!mw->autoResizeLayers);
+
+      int nXDelta =
+          graph->plotWidget()->width() - graph->plotWidget()->canvas()->width();
+      int nYDelta = graph->plotWidget()->height() -
+                    graph->plotWidget()->canvas()->height();
+      QPoint posCanvas = graph->plotWidget()->canvas()->pos();
+
+      graph->resize(int(layerRect.width() * fXScale) + nXDelta,
+                    int(layerRect.height() * fYScale) + nYDelta);
+
+      int newXGraphPos =
+          int(layerRect.left * fXScale) - posCanvas.x() - ml->x();
+      int newYGraphPos = int(layerRect.top * fYScale) - posCanvas.y() - ml->y();
+      graph->move((newXGraphPos > 0 ? newXGraphPos : 0),
+                  (newYGraphPos > 0 ? newYGraphPos : 0));
+
+      graph->plotWidget()->resize(int(layerRect.width() * fXScale) + nXDelta,
+                                  int(layerRect.height() * fYScale) + nYDelta);
+
+      // add texts
+      vector<text> texts = opj.layerTexts(g, l);
+      if (style != Graph::Pie) {
+        for (size_t i = 0; i < texts.size(); ++i) {
+          addText(texts[i], graph, 0, layerRect, fFontScaleFactor, fXScale,
+                  fYScale);
+        }
+      }
+
+      if (legend)
+        addText(opj.layerLegend(g, l), graph, legend, layerRect,
+                fFontScaleFactor, fXScale, fYScale);
+
+      vector<line> lines = opj.layerLines(g, l);
+      for (size_t i = 0; i < lines.size(); ++i) {
+        ArrowMarker mrk;
+        mrk.setStartPoint(lines[i].begin.x, lines[i].begin.y);
+        mrk.setEndPoint(lines[i].end.x, lines[i].end.y);
+        mrk.drawStartArrow(lines[i].begin.shape_type > 0);
+        mrk.drawEndArrow(lines[i].end.shape_type > 0);
+        mrk.setHeadLength(int(lines[i].end.shape_length));
+        mrk.setHeadAngle(
+            arrowAngle(lines[i].end.shape_length, lines[i].end.shape_width));
+        mrk.setColor(ColorBox::color(lines[i].color));
+        mrk.setWidth((int)lines[i].width);
+        Qt::PenStyle s;
+
+        switch (lines[i].line_style) {
+        case OPJFile::Solid:
+          s = Qt::SolidLine;
+          break;
+        case OPJFile::Dash:
+        case OPJFile::ShortDash:
+          s = Qt::DashLine;
+          break;
+        case OPJFile::Dot:
+        case OPJFile::ShortDot:
+          s = Qt::DotLine;
+          break;
+        case OPJFile::DashDot:
+        case OPJFile::ShortDashDot:
+          s = Qt::DashDotLine;
+          break;
+        case OPJFile::DashDotDot:
+          s = Qt::DashDotDotLine;
+          break;
+        default:
+          s = Qt::SolidLine;
+        }
+        mrk.setStyle(s);
+        graph->addArrow(&mrk);
+      }
+
+      vector<bitmap> bitmaps = opj.layerBitmaps(g, l);
+      for (size_t i = 0; i < bitmaps.size(); ++i) {
+        QPixmap bmp;
+        bmp.loadFromData(bitmaps[i].data, uint(bitmaps[i].size), "BMP");
+        QTemporaryFile file;
+        file.setFileTemplate(QDir::tempPath() + "/XXXXXX.bmp");
+        if (file.open()) {
+          bmp.save(file.fileName(), "BMP");
+          ImageMarker *mrk = graph->addImage(file.fileName());
+          double left, top, right, bottom;
+          left = top = right = bottom = 0.0;
+          switch (bitmaps[i].attach) {
+          case OPJFile::Scale:
+            left = bitmaps[i].left;
+            top = bitmaps[i].top;
+            right = left + bitmaps[i].width;
+            bottom = top - bitmaps[i].height;
+            break;
+          case OPJFile::Frame:
+            if (bitmaps[i].width > 0) {
+              left = (rangeX.max - rangeX.min) * bitmaps[i].left + rangeX.min;
+              right = left + bitmaps[i].width;
+            } else {
+              right = (rangeX.max - rangeX.min) * bitmaps[i].left + rangeX.min;
+              left = right + bitmaps[i].width;
+            }
+
+            if (bitmaps[i].height > 0) {
+              top = rangeY.max - (rangeY.max - rangeY.min) * bitmaps[i].top;
+              bottom = top - bitmaps[i].height;
+            } else {
+              bottom = rangeY.max - (rangeY.max - rangeY.min) * bitmaps[i].top;
+              top = bottom - bitmaps[i].height;
+            }
+            break;
+          case OPJFile::Page:
+            // rect graphRect = opj.graphRect(g);
+            left = (rangeX.max - rangeX.min) *
+                       (bitmaps[i].left -
+                        (double)layerRect.left / (double)graphRect.width()) /
+                       ((double)layerRect.width() / (double)graphRect.width()) +
+                   rangeX.min;
+            top = rangeY.max -
+                  (rangeY.max - rangeY.min) *
+                      (bitmaps[i].top -
+                       (double)layerRect.top / (double)graphRect.height()) /
+                      ((double)layerRect.height() / (double)graphRect.height());
+            right = left + bitmaps[i].width;
+            bottom = top - bitmaps[i].height;
+            break;
+          }
+
+          mrk->setBoundingRect(left, top, right, bottom);
+        }
+      }
+    }
+    // cascade the graphs
+    if (!opj.graphHidden(g)) {
+      ml->move(QPoint(graphWindowRect.left, graphWindowRect.top));
+
+      switch (opj.graphState(g)) {
+      case originWindow::Minimized:
+        mw->minimizeWindow(ml);
+        break;
+      case originWindow::Maximized:
+        ml->show(); // to correct scaling with maximize
+        mw->maximizeWindow(ml);
+        break;
+      default:
+        ml->show();
+      }
+    } else {
+      ml->show();
+      // ml->arrangeLayers(true,true);
+      mw->hideWindow(ml);
+    }
+  }
+  if (visible_count > 0)
+    xoffset++;
+  return true;
 }
 
-void ImportOPJ::addText(const text& _text, Graph* graph, LegendWidget* txt, const rect& layerRect, double fFontScaleFactor, double fXScale, double fYScale)
-{
-	int bkg;
-	switch(_text.border_type)
-	{
-	case OPJFile::BlackLine:
-		bkg=1;
-		break;
-	case OPJFile::Shadow:
-	case OPJFile::DarkMarble:
-		bkg=2;
-		break;
-	default:
-		bkg=0;
-		break;
-	}
-
-	if(!txt)
-		txt=graph->newLegend(parseOriginText(QString::fromLocal8Bit(_text.txt.c_str())));
-
-	QFont font(mw->plotLegendFont);
-	font.setPointSize(int(floor(_text.fontsize*fFontScaleFactor + 0.5)));
-	txt->setAngle(_text.rotation);
-	txt->setTextColor(ColorBox::color(_text.color));
-	txt->setFont(font);
-	txt->setFrameStyle(bkg);
-
-	rect txtRect=_text.clientRect;
-	int x=(txtRect.left>layerRect.left ? txtRect.left-layerRect.left : 0);
-	int y=(txtRect.top>layerRect.top ? txtRect.top-layerRect.top : 0);
-	txt->move(QPoint(int(x*fXScale), int(y*fYScale)));
-
-	/*QRect qtiRect=graph->plotWidget()->canvas()->geometry();
-	txt->setOrigin(QPoint(x*qtiRect.width()/layerRect.width(),
-		y*qtiRect.height()/layerRect.height()));*/
+void ImportOPJ::addText(const text &_text, Graph *graph, LegendWidget *txt,
+                        const rect &layerRect, double fFontScaleFactor,
+                        double fXScale, double fYScale) {
+  int bkg;
+  switch (_text.border_type) {
+  case OPJFile::BlackLine:
+    bkg = 1;
+    break;
+  case OPJFile::Shadow:
+  case OPJFile::DarkMarble:
+    bkg = 2;
+    break;
+  default:
+    bkg = 0;
+    break;
+  }
+
+  if (!txt)
+    txt = graph->newLegend(
+        parseOriginText(QString::fromLocal8Bit(_text.txt.c_str())));
+
+  QFont font(mw->plotLegendFont);
+  font.setPointSize(int(floor(_text.fontsize * fFontScaleFactor + 0.5)));
+  txt->setAngle(_text.rotation);
+  txt->setTextColor(ColorBox::color(_text.color));
+  txt->setFont(font);
+  txt->setFrameStyle(bkg);
+
+  rect txtRect = _text.clientRect;
+  int x = (txtRect.left > layerRect.left ? txtRect.left - layerRect.left : 0);
+  int y = (txtRect.top > layerRect.top ? txtRect.top - layerRect.top : 0);
+  txt->move(QPoint(int(x * fXScale), int(y * fYScale)));
+
+  /*QRect qtiRect=graph->plotWidget()->canvas()->geometry();
+  txt->setOrigin(QPoint(x*qtiRect.width()/layerRect.width(),
+          y*qtiRect.height()/layerRect.height()));*/
 }
 
-QString ImportOPJ::parseOriginText(const QString &str)
-{
-	QStringList lines=str.split("\n");
-	QString text="";
-	for(int i=0; i<lines.size(); ++i)
-	{
-		if(i>0)
-			text.append("\n");
-		text.append(parseOriginTags(lines[i]));
-	}
-	return text;
+QString ImportOPJ::parseOriginText(const QString &str) {
+  QStringList lines = str.split("\n");
+  QString text = "";
+  for (int i = 0; i < lines.size(); ++i) {
+    if (i > 0)
+      text.append("\n");
+    text.append(parseOriginTags(lines[i]));
+  }
+  return text;
 }
 
-QString ImportOPJ::parseOriginTags(const QString &str)
-{
-	QString line=str;
-	//Lookbehind conditions are not supported - so need to reverse string
-	QRegExp rx("\\)[^\\)\\(]*\\((?!\\s*[buig\\+\\-]\\s*\\\\)");
-	QRegExp rxfont("\\)[^\\)\\(]*\\((?![^\\:]*\\:f\\s*\\\\)");
-	QString linerev = strreverse(line);
-	QString lBracket=strreverse("&lbracket;");
-	QString rBracket=strreverse("&rbracket;");
-	QString ltagBracket=strreverse("&ltagbracket;");
-	QString rtagBracket=strreverse("&rtagbracket;");
-	int pos1=rx.indexIn(linerev);
-	int pos2=rxfont.indexIn(linerev);
-
-	while (pos1>-1 || pos2>-1) {
-		if(pos1==pos2)
-		{
-			QString value = rx.cap(0);
-			int len=value.length();
-			value=rBracket+value.mid(1,len-2)+lBracket;
-			linerev.replace(pos1, len, value);
-		}
-		else if ((pos1>pos2&&pos2!=-1)||pos1==-1)
-		{
-			QString value = rxfont.cap(0);
-			int len=value.length();
-			value=rtagBracket+value.mid(1,len-2)+ltagBracket;
-			linerev.replace(pos2, len, value);
-		}
-		else if ((pos2>pos1&&pos1!=-1)||pos2==-1)
-		{
-			QString value = rx.cap(0);
-			int len=value.length();
-			value=rtagBracket+value.mid(1,len-2)+ltagBracket;
-			linerev.replace(pos1, len, value);
-		}
-
-		pos1=rx.indexIn(linerev);
-		pos2=rxfont.indexIn(linerev);
-	}
-	linerev.replace(ltagBracket, "(");
-	linerev.replace(rtagBracket, ")");
-
-	line = strreverse(linerev);
-
-	//replace \b(...), \i(...), \u(...), \g(...), \+(...), \-(...), \f:font(...) tags
-	QString rxstr[]={
-		"\\\\\\s*b\\s*\\(",
-		"\\\\\\s*i\\s*\\(",
-		"\\\\\\s*u\\s*\\(",
-		"\\\\\\s*g\\s*\\(",
-		"\\\\\\s*\\+\\s*\\(",
-		"\\\\\\s*\\-\\s*\\(",
-		"\\\\\\s*f\\:[^\\(]*\\("};
-	int postag[]={0,0,0,0,0,0,0};
-	QString ltag[]={"<b>","<i>","<u>","<font face=Symbol>","<sup>","<sub>","<font face=%1>"};
-	QString rtag[]={"</b>","</i>","</u>","</font>","</sup>","</sub>","</font>"};
-	QRegExp rxtags[7];
-	for(int i=0; i<7; ++i)
-		rxtags[i].setPattern(rxstr[i]+"[^\\(\\)]*\\)");
-
-	bool flag=true;
-	while(flag) {
-		for(int i=0; i<7; ++i)
-		{
-			postag[i] = rxtags[i].indexIn(line);
-			while (postag[i] > -1) {
-				QString value = rxtags[i].cap(0);
-				int len=value.length();
-				int pos2=value.indexOf("(");
-				if(i<6)
-					value=ltag[i]+value.mid(pos2+1,len-pos2-2)+rtag[i];
-				else
-				{
-					int posfont=value.indexOf("f:");
-					value=ltag[i].arg(value.mid(posfont+2,pos2-posfont-2))+value.mid(pos2+1,len-pos2-2)+rtag[i];
-				}
-				line.replace(postag[i], len, value);
-				postag[i] = rxtags[i].indexIn(line);
-			}
-		}
-		flag=false;
-		for(int i=0; i<7; ++i)
-		{
-			if(rxtags[i].indexIn(line)>-1)
-			{
-				flag=true;
-				break;
-			}
-		}
-	}
-
-	//replace unclosed tags
-	for(int i=0; i<6; ++i)
-		line.replace(QRegExp(rxstr[i]), ltag[i]);
-	rxfont.setPattern(rxstr[6]);
-	int pos = rxfont.indexIn(line);
-	while (pos > -1) {
-		QString value = rxfont.cap(0);
-		int len=value.length();
-		int posfont=value.indexOf("f:");
-		value=ltag[6].arg(value.mid(posfont+2,len-posfont-3));
-		line.replace(pos, len, value);
-		pos = rxfont.indexIn(line);
-	}
-
-	line.replace("&lbracket;", "(");
-	line.replace("&rbracket;", ")");
-
-	return line;
+QString ImportOPJ::parseOriginTags(const QString &str) {
+  QString line = str;
+  // Lookbehind conditions are not supported - so need to reverse string
+  QRegExp rx("\\)[^\\)\\(]*\\((?!\\s*[buig\\+\\-]\\s*\\\\)");
+  QRegExp rxfont("\\)[^\\)\\(]*\\((?![^\\:]*\\:f\\s*\\\\)");
+  QString linerev = strreverse(line);
+  QString lBracket = strreverse("&lbracket;");
+  QString rBracket = strreverse("&rbracket;");
+  QString ltagBracket = strreverse("&ltagbracket;");
+  QString rtagBracket = strreverse("&rtagbracket;");
+  int pos1 = rx.indexIn(linerev);
+  int pos2 = rxfont.indexIn(linerev);
+
+  while (pos1 > -1 || pos2 > -1) {
+    if (pos1 == pos2) {
+      QString value = rx.cap(0);
+      int len = value.length();
+      value = rBracket + value.mid(1, len - 2) + lBracket;
+      linerev.replace(pos1, len, value);
+    } else if ((pos1 > pos2 && pos2 != -1) || pos1 == -1) {
+      QString value = rxfont.cap(0);
+      int len = value.length();
+      value = rtagBracket + value.mid(1, len - 2) + ltagBracket;
+      linerev.replace(pos2, len, value);
+    } else if ((pos2 > pos1 && pos1 != -1) || pos2 == -1) {
+      QString value = rx.cap(0);
+      int len = value.length();
+      value = rtagBracket + value.mid(1, len - 2) + ltagBracket;
+      linerev.replace(pos1, len, value);
+    }
+
+    pos1 = rx.indexIn(linerev);
+    pos2 = rxfont.indexIn(linerev);
+  }
+  linerev.replace(ltagBracket, "(");
+  linerev.replace(rtagBracket, ")");
+
+  line = strreverse(linerev);
+
+  // replace \b(...), \i(...), \u(...), \g(...), \+(...), \-(...), \f:font(...)
+  // tags
+  QString rxstr[] = {"\\\\\\s*b\\s*\\(",      "\\\\\\s*i\\s*\\(",
+                     "\\\\\\s*u\\s*\\(",      "\\\\\\s*g\\s*\\(",
+                     "\\\\\\s*\\+\\s*\\(",    "\\\\\\s*\\-\\s*\\(",
+                     "\\\\\\s*f\\:[^\\(]*\\("};
+  int postag[] = {0, 0, 0, 0, 0, 0, 0};
+  QString ltag[] = {"<b>", "<i>", "<u>", "<font face=Symbol>", "<sup>", "<sub>",
+                    "<font face=%1>"};
+  QString rtag[] = {"</b>",   "</i>",   "</u>",   "</font>",
+                    "</sup>", "</sub>", "</font>"};
+  QRegExp rxtags[7];
+  for (int i = 0; i < 7; ++i)
+    rxtags[i].setPattern(rxstr[i] + "[^\\(\\)]*\\)");
+
+  bool flag = true;
+  while (flag) {
+    for (int i = 0; i < 7; ++i) {
+      postag[i] = rxtags[i].indexIn(line);
+      while (postag[i] > -1) {
+        QString value = rxtags[i].cap(0);
+        int len = value.length();
+        int pos2 = value.indexOf("(");
+        if (i < 6)
+          value = ltag[i] + value.mid(pos2 + 1, len - pos2 - 2) + rtag[i];
+        else {
+          int posfont = value.indexOf("f:");
+          value = ltag[i].arg(value.mid(posfont + 2, pos2 - posfont - 2)) +
+                  value.mid(pos2 + 1, len - pos2 - 2) + rtag[i];
+        }
+        line.replace(postag[i], len, value);
+        postag[i] = rxtags[i].indexIn(line);
+      }
+    }
+    flag = false;
+    for (int i = 0; i < 7; ++i) {
+      if (rxtags[i].indexIn(line) > -1) {
+        flag = true;
+        break;
+      }
+    }
+  }
+
+  // replace unclosed tags
+  for (int i = 0; i < 6; ++i)
+    line.replace(QRegExp(rxstr[i]), ltag[i]);
+  rxfont.setPattern(rxstr[6]);
+  int pos = rxfont.indexIn(line);
+  while (pos > -1) {
+    QString value = rxfont.cap(0);
+    int len = value.length();
+    int posfont = value.indexOf("f:");
+    value = ltag[6].arg(value.mid(posfont + 2, len - posfont - 3));
+    line.replace(pos, len, value);
+    pos = rxfont.indexIn(line);
+  }
+
+  line.replace("&lbracket;", "(");
+  line.replace("&rbracket;", ")");
+
+  return line;
 }
 
-//TODO: bug in grid dialog
+// TODO: bug in grid dialog
 //		scale/minor ticks checkbox
 //		histogram: autobin export
 //		if prec not setted - automac+4digits
diff --git a/MantidPlot/src/importOPJ.h b/MantidPlot/src/importOPJ.h
index 53e6c396c611e5d8781704c732f2b1fccc5c69e0..56cd77e1d0f7cd45ca5e303fc2b8124e4911f1ba 100644
--- a/MantidPlot/src/importOPJ.h
+++ b/MantidPlot/src/importOPJ.h
@@ -33,26 +33,29 @@
 #include "origin/OPJFile.h"
 
 //! Origin project import class
-class ImportOPJ
-{
+class ImportOPJ {
 public:
-	ImportOPJ(ApplicationWindow *app, const QString& filename);
+  ImportOPJ(ApplicationWindow *app, const QString &filename);
 
-	bool createProjectTree(const OPJFile& opj);
-	bool importTables(const OPJFile& opj);
-	bool importGraphs(const OPJFile& opj);
-	bool importNotes(const OPJFile& opj);
-	int error(){return parse_error;};
+  bool createProjectTree(const OPJFile &opj);
+  bool importTables(const OPJFile &opj);
+  bool importGraphs(const OPJFile &opj);
+  bool importNotes(const OPJFile &opj);
+  int error() { return parse_error; };
 
 private:
-    int arrowAngle(double length, double width){return int(ceil(45*atan(0.5*width/length)/atan(1.0)));};
-	int translateOrigin2QtiplotLineStyle(int linestyle);
-	QString parseOriginText(const QString &str);
-	QString parseOriginTags(const QString &str);
-	void addText(const text& _text, Graph* graph, LegendWidget* txt, const rect& layerRect, double fFontScaleFactor, double fXScale, double fYScale);
-	int parse_error;
-	int xoffset;
-	ApplicationWindow *mw;
+  int arrowAngle(double length, double width) {
+    return int(ceil(45 * atan(0.5 * width / length) / atan(1.0)));
+  };
+  int translateOrigin2QtiplotLineStyle(int linestyle);
+  QString parseOriginText(const QString &str);
+  QString parseOriginTags(const QString &str);
+  void addText(const text &_text, Graph *graph, LegendWidget *txt,
+               const rect &layerRect, double fFontScaleFactor, double fXScale,
+               double fYScale);
+  int parse_error;
+  int xoffset;
+  ApplicationWindow *mw;
 };
 
-#endif //IMPORTOPJ_H
+#endif // IMPORTOPJ_H
diff --git a/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp b/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
index 08ada319fc49dbf3f985f9e383bb9dbb724e65ef..7a0ef642f9bc0a5bad626595b971123ced055e44 100644
--- a/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
+++ b/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.cpp
@@ -1,17 +1,17 @@
 /****************************************************************************
 **
 ** This file is part of a Qt Solutions component.
-** 
+**
 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** 
+**
 ** Contact:  Qt Software Information (qt-info@nokia.com)
-** 
-** Commercial Usage  
+**
+** Commercial Usage
 ** Licensees holding valid Qt Commercial licenses may use this file in
 ** accordance with the Qt Solutions Commercial License Agreement provided
 ** with the Software or, alternatively, in accordance with the terms
 ** contained in a written agreement between you and Nokia.
-** 
+**
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 2.1 as published by the Free Software
@@ -19,29 +19,29 @@
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU Lesser General Public License version 2.1 requirements
 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-** 
+**
 ** In addition, as a special exception, Nokia gives you certain
 ** additional rights. These rights are described in the Nokia Qt LGPL
 ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
 ** package.
-** 
-** GNU General Public License Usage 
+**
+** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 3.0 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU General Public License version 3.0 requirements will be
 ** met: http://www.gnu.org/copyleft/gpl.html.
-** 
+**
 ** Please note Third Party Software included with Qt Solutions may impose
 ** additional restrictions and it is the user's responsibility to ensure
 ** that they have met the licensing requirements of the GPL, LGPL, or Qt
 ** Solutions Commercial license and the relevant license of the Third
 ** Party Software they are using.
-** 
+**
 ** If you are unsure which license is appropriate for your use, please
 ** contact the sales department at qt-sales@nokia.com.
-** 
+**
 ****************************************************************************/
 
 #include <QtGui/QApplication>
@@ -108,7 +108,8 @@
         picker->insertColor(QColor(0, 0, 255), "Blue"));
         picker->insertColor(white);
 
-        connect(colors, SIGNAL(colorChanged(const QColor &)), SLOT(setCurrentColor(const QColor &)));
+        connect(colors, SIGNAL(colorChanged(const QColor &)),
+   SLOT(setCurrentColor(const QColor &)));
     }
     \endcode
 
@@ -139,15 +140,14 @@
     mouseRelease, even if the mouse button was  not pressed inside the
     widget.
 */
-class ColorPickerButton : public QFrame
-{
-    Q_OBJECT
+class ColorPickerButton : public QFrame {
+  Q_OBJECT
 
 public:
   explicit ColorPickerButton(QWidget *parent);
 
 signals:
-    void clicked();
+  void clicked();
 
 protected:
   void mousePressEvent(QMouseEvent *e) override;
@@ -163,26 +163,25 @@ protected:
 /*
     This class represents each "color" or item in the color grid.
 */
-class ColorPickerItem : public QFrame
-{
-    Q_OBJECT
+class ColorPickerItem : public QFrame {
+  Q_OBJECT
 
 public:
-    ColorPickerItem(const QColor &color = Qt::white, const QString &text = QString::null,
-		      QWidget *parent = 0);
-    ~ColorPickerItem();
+  ColorPickerItem(const QColor &color = Qt::white,
+                  const QString &text = QString::null, QWidget *parent = 0);
+  ~ColorPickerItem();
 
-    QColor color() const;
-    QString text() const;
+  QColor color() const;
+  QString text() const;
 
-    void setSelected(bool);
-    bool isSelected() const;
+  void setSelected(bool);
+  bool isSelected() const;
 signals:
-    void clicked();
-    void selected();
+  void clicked();
+  void selected();
 
 public slots:
-    void setColor(const QColor &color, const QString &text = QString());
+  void setColor(const QColor &color, const QString &text = QString());
 
 protected:
   void mousePressEvent(QMouseEvent *e) override;
@@ -191,42 +190,40 @@ protected:
   void paintEvent(QPaintEvent *e) override;
 
 private:
-    QColor c;
-    QString t;
-    bool sel;
+  QColor c;
+  QString t;
+  bool sel;
 };
 
 /*
 
 */
-class ColorPickerPopup : public QFrame
-{
-    Q_OBJECT
+class ColorPickerPopup : public QFrame {
+  Q_OBJECT
 
 public:
-    ColorPickerPopup(int width, bool withColorDialog,
-		       QWidget *parent = 0);
-    ~ColorPickerPopup();
+  ColorPickerPopup(int width, bool withColorDialog, QWidget *parent = 0);
+  ~ColorPickerPopup();
 
-    void insertColor(const QColor &col, const QString &text, int index);
-    void exec();
+  void insertColor(const QColor &col, const QString &text, int index);
+  void exec();
 
-    void setExecFlag();
+  void setExecFlag();
 
-    QColor lastSelected() const;
+  QColor lastSelected() const;
 
-    ColorPickerItem *find(const QColor &col) const;
-    QColor color(int index) const;
+  ColorPickerItem *find(const QColor &col) const;
+  QColor color(int index) const;
 
 signals:
-    void selected(const QColor &);
-    void hid();
+  void selected(const QColor &);
+  void hid();
 
 public slots:
-    void getColorFromDialog();
+  void getColorFromDialog();
 
 protected slots:
-    void updateSelected();
+  void updateSelected();
 
 protected:
   void keyPressEvent(QKeyEvent *e) override;
@@ -237,15 +234,15 @@ protected:
   void regenerateGrid();
 
 private:
-    QMap<int, QMap<int, QWidget *> > widgetAt;
-    QList<ColorPickerItem *> items;
-    QGridLayout *grid;
-    ColorPickerButton *moreButton;
-    QEventLoop *eventLoop;
-
-    int lastPos;
-    int cols;
-    QColor lastSel;
+  QMap<int, QMap<int, QWidget *>> widgetAt;
+  QList<ColorPickerItem *> items;
+  QGridLayout *grid;
+  ColorPickerButton *moreButton;
+  QEventLoop *eventLoop;
+
+  int lastPos;
+  int cols;
+  QColor lastSel;
 };
 
 /*!
@@ -265,113 +262,106 @@ private:
 
     \sa QFrame
 */
-QtColorPicker::QtColorPicker(QWidget *parent,
-			     int cols, bool enableColorDialog)
-    : QPushButton(parent), popup(0), withColorDialog(enableColorDialog)
-{
-    setFocusPolicy(Qt::StrongFocus);
-    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
-    setAutoDefault(false);
-    setAutoFillBackground(true);
-    setCheckable(true);
-
-    // Set text
-    setText(tr("Black"));
-    firstInserted = false;
-
-    // Create and set icon
-    col = Qt::black;
-    dirty = true;
-
-    // Create color grid popup and connect to it.
-    popup = new ColorPickerPopup(cols, withColorDialog, this);
-    connect(popup, SIGNAL(selected(const QColor &)),
-	    SLOT(setCurrentColor(const QColor &)));
-    connect(popup, SIGNAL(hid()), SLOT(popupClosed()));
-
-    // Connect this push button's pressed() signal.
-    connect(this, SIGNAL(toggled(bool)), SLOT(buttonPressed(bool)));
+QtColorPicker::QtColorPicker(QWidget *parent, int cols, bool enableColorDialog)
+    : QPushButton(parent), popup(0), withColorDialog(enableColorDialog) {
+  setFocusPolicy(Qt::StrongFocus);
+  setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
+  setAutoDefault(false);
+  setAutoFillBackground(true);
+  setCheckable(true);
+
+  // Set text
+  setText(tr("Black"));
+  firstInserted = false;
+
+  // Create and set icon
+  col = Qt::black;
+  dirty = true;
+
+  // Create color grid popup and connect to it.
+  popup = new ColorPickerPopup(cols, withColorDialog, this);
+  connect(popup, SIGNAL(selected(const QColor &)),
+          SLOT(setCurrentColor(const QColor &)));
+  connect(popup, SIGNAL(hid()), SLOT(popupClosed()));
+
+  // Connect this push button's pressed() signal.
+  connect(this, SIGNAL(toggled(bool)), SLOT(buttonPressed(bool)));
 }
 
 /*!
     Destructs the QtColorPicker.
 */
-QtColorPicker::~QtColorPicker()
-{
-}
+QtColorPicker::~QtColorPicker() {}
 
 /*! \internal
 
     Pops up the color grid, and makes sure the status of
     QtColorPicker's button is right.
 */
-void QtColorPicker::buttonPressed(bool toggled)
-{
-    if (!toggled)
-        return;
-
-    const QRect desktop = QApplication::desktop()->geometry();
-    // Make sure the popup is inside the desktop.
-    QPoint pos = mapToGlobal(rect().bottomLeft());
-    if (pos.x() < desktop.left())
-       pos.setX(desktop.left());
-    if (pos.y() < desktop.top())
-       pos.setY(desktop.top());
-
-    if ((pos.x() + popup->sizeHint().width()) > desktop.width())
-       pos.setX(desktop.width() - popup->sizeHint().width());
-    if ((pos.y() + popup->sizeHint().height()) > desktop.bottom())
-       pos.setY(desktop.bottom() - popup->sizeHint().height());
-    popup->move(pos);
-
-    if (ColorPickerItem *item = popup->find(col))
-        item->setSelected(true);
-
-    // Remove focus from this widget, preventing the focus rect
-    // from showing when the popup is shown. Order an update to
-    // make sure the focus rect is cleared.
-    clearFocus();
-    update();
-
-    // Allow keyboard navigation as soon as the popup shows.
-    popup->setFocus();
-
-    // Execute the popup. The popup will enter the event loop.
-    popup->show();
+void QtColorPicker::buttonPressed(bool toggled) {
+  if (!toggled)
+    return;
+
+  const QRect desktop = QApplication::desktop()->geometry();
+  // Make sure the popup is inside the desktop.
+  QPoint pos = mapToGlobal(rect().bottomLeft());
+  if (pos.x() < desktop.left())
+    pos.setX(desktop.left());
+  if (pos.y() < desktop.top())
+    pos.setY(desktop.top());
+
+  if ((pos.x() + popup->sizeHint().width()) > desktop.width())
+    pos.setX(desktop.width() - popup->sizeHint().width());
+  if ((pos.y() + popup->sizeHint().height()) > desktop.bottom())
+    pos.setY(desktop.bottom() - popup->sizeHint().height());
+  popup->move(pos);
+
+  if (ColorPickerItem *item = popup->find(col))
+    item->setSelected(true);
+
+  // Remove focus from this widget, preventing the focus rect
+  // from showing when the popup is shown. Order an update to
+  // make sure the focus rect is cleared.
+  clearFocus();
+  update();
+
+  // Allow keyboard navigation as soon as the popup shows.
+  popup->setFocus();
+
+  // Execute the popup. The popup will enter the event loop.
+  popup->show();
 }
 
 /*!
     \internal
 */
-void QtColorPicker::paintEvent(QPaintEvent *e)
-{
-    if (dirty) {
-        int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize);
-        QPixmap pix(iconSize, iconSize);
-        pix.fill(palette().button().color());
-
-        QPainter p(&pix);
-
-        int w = pix.width();			// width of cell in pixels
-        int h = pix.height();			// height of cell in pixels
-        p.setPen(QPen(Qt::gray));
-        p.setBrush(col);
-        p.drawRect(2, 2, w - 5, h - 5);
-        setIcon(QIcon(pix));
-
-        dirty = false;
-    }
-    QPushButton::paintEvent(e);
+void QtColorPicker::paintEvent(QPaintEvent *e) {
+  if (dirty) {
+    int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize);
+    QPixmap pix(iconSize, iconSize);
+    pix.fill(palette().button().color());
+
+    QPainter p(&pix);
+
+    int w = pix.width();  // width of cell in pixels
+    int h = pix.height(); // height of cell in pixels
+    p.setPen(QPen(Qt::gray));
+    p.setBrush(col);
+    p.drawRect(2, 2, w - 5, h - 5);
+    setIcon(QIcon(pix));
+
+    dirty = false;
+  }
+  QPushButton::paintEvent(e);
 }
 
 /*! \internal
 
     Makes sure the button isn't pressed when the popup hides.
 */
-void QtColorPicker::popupClosed()
-{
-    setChecked(false);
-    setFocus();
+void QtColorPicker::popupClosed() {
+  setChecked(false);
+  setFocus();
 }
 
 /*!
@@ -379,18 +369,12 @@ void QtColorPicker::popupClosed()
 
     \sa text()
 */
-QColor QtColorPicker::currentColor() const
-{
-    return col;
-}
+QColor QtColorPicker::currentColor() const { return col; }
 
 /*!
     Returns the color at position \a index.
 */
-QColor QtColorPicker::color(int index) const
-{
-    return popup->color(index);
-}
+QColor QtColorPicker::color(int index) const { return popup->color(index); }
 
 /*!
     Adds the 17 predefined colors from the Qt namespace.
@@ -400,28 +384,26 @@ QColor QtColorPicker::color(int index) const
 
     \sa insertColor()
 */
-void QtColorPicker::setStandardColors()
-{
-    insertColor(Qt::black, tr("Black"));
-    insertColor(Qt::white, tr("White"));
-    insertColor(Qt::red, tr("Red"));
-    insertColor(Qt::darkRed, tr("Dark red"));
-    insertColor(Qt::green, tr("Green"));
-    insertColor(Qt::darkGreen, tr("Dark green"));
-    insertColor(Qt::blue, tr("Blue"));
-    insertColor(Qt::darkBlue, tr("Dark blue"));
-    insertColor(Qt::cyan, tr("Cyan"));
-    insertColor(Qt::darkCyan, tr("Dark cyan"));
-    insertColor(Qt::magenta, tr("Magenta"));
-    insertColor(Qt::darkMagenta, tr("Dark magenta"));
-    insertColor(Qt::yellow, tr("Yellow"));
-    insertColor(Qt::darkYellow, tr("Dark yellow"));
-    insertColor(Qt::gray, tr("Gray"));
-    insertColor(Qt::darkGray, tr("Dark gray"));
-    insertColor(Qt::lightGray, tr("Light gray"));
+void QtColorPicker::setStandardColors() {
+  insertColor(Qt::black, tr("Black"));
+  insertColor(Qt::white, tr("White"));
+  insertColor(Qt::red, tr("Red"));
+  insertColor(Qt::darkRed, tr("Dark red"));
+  insertColor(Qt::green, tr("Green"));
+  insertColor(Qt::darkGreen, tr("Dark green"));
+  insertColor(Qt::blue, tr("Blue"));
+  insertColor(Qt::darkBlue, tr("Dark blue"));
+  insertColor(Qt::cyan, tr("Cyan"));
+  insertColor(Qt::darkCyan, tr("Dark cyan"));
+  insertColor(Qt::magenta, tr("Magenta"));
+  insertColor(Qt::darkMagenta, tr("Dark magenta"));
+  insertColor(Qt::yellow, tr("Yellow"));
+  insertColor(Qt::darkYellow, tr("Dark yellow"));
+  insertColor(Qt::gray, tr("Gray"));
+  insertColor(Qt::darkGray, tr("Dark gray"));
+  insertColor(Qt::lightGray, tr("Light gray"));
 }
 
-
 /*!
     Makes \a color current. If \a color is not already in the color grid, it
     is inserted with the text "Custom".
@@ -429,29 +411,28 @@ void QtColorPicker::setStandardColors()
     This function emits the colorChanged() signal if the new color is
     valid, and different from the old one.
 */
-void QtColorPicker::setCurrentColor(const QColor &color)
-{
-    if (col == color || !color.isValid())
-	return;
-
-    ColorPickerItem *item = popup->find(color);
-    if (!item) {
-      insertColor(color, tr("Custom"));
-      item = popup->find(color);
-    }
+void QtColorPicker::setCurrentColor(const QColor &color) {
+  if (col == color || !color.isValid())
+    return;
+
+  ColorPickerItem *item = popup->find(color);
+  if (!item) {
+    insertColor(color, tr("Custom"));
+    item = popup->find(color);
+  }
 
-    if (item) {
-      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);
+  }
 }
 
 /*!
@@ -460,14 +441,14 @@ void QtColorPicker::setCurrentColor(const QColor &color)
     automatically assigned a position, starting from left to right,
     top to bottom.
 */
-void QtColorPicker::insertColor(const QColor &color, const QString &text, int index)
-{
-    popup->insertColor(color, text, index);
-    if (!firstInserted) {
-	col = color;
-	setText(text);
-	firstInserted = true;
-    }
+void QtColorPicker::insertColor(const QColor &color, const QString &text,
+                                int index) {
+  popup->insertColor(color, text, index);
+  if (!firstInserted) {
+    col = color;
+    setText(text);
+    firstInserted = true;
+  }
 }
 
 /*! \property QtColorPicker::colorDialog
@@ -478,14 +459,10 @@ void QtColorPicker::insertColor(const QColor &color, const QString &text, int in
     QColorDialog when clicked. The user will then be able to select
     any custom color they like.
 */
-void QtColorPicker::setColorDialogEnabled(bool enabled)
-{
-    withColorDialog = enabled;
-}
-bool QtColorPicker::colorDialogEnabled() const
-{
-    return withColorDialog;
+void QtColorPicker::setColorDialogEnabled(bool enabled) {
+  withColorDialog = enabled;
 }
+bool QtColorPicker::colorDialogEnabled() const { return withColorDialog; }
 
 /*!
     Pops up a color grid with Qt default colors at \a point, using
@@ -497,37 +474,36 @@ bool QtColorPicker::colorDialogEnabled() const
     \code
         void Drawer::mouseReleaseEvent(QMouseEvent *e)
         {
-	    if (e->button() & RightButton) {
+            if (e->button() & RightButton) {
                 QColor color = QtColorPicker::getColor(mapToGlobal(e->pos()));
             }
         }
     \endcode
 */
-QColor QtColorPicker::getColor(const QPoint &point, bool allowCustomColors)
-{
-    ColorPickerPopup popup(-1, allowCustomColors);
-
-    popup.insertColor(Qt::black, tr("Black"), 0);
-    popup.insertColor(Qt::white, tr("White"), 1);
-    popup.insertColor(Qt::red, tr("Red"), 2);
-    popup.insertColor(Qt::darkRed, tr("Dark red"), 3);
-    popup.insertColor(Qt::green, tr("Green"), 4);
-    popup.insertColor(Qt::darkGreen, tr("Dark green"), 5);
-    popup.insertColor(Qt::blue, tr("Blue"), 6);
-    popup.insertColor(Qt::darkBlue, tr("Dark blue"), 7);
-    popup.insertColor(Qt::cyan, tr("Cyan"), 8);
-    popup.insertColor(Qt::darkCyan, tr("Dark cyan"), 9);
-    popup.insertColor(Qt::magenta, tr("Magenta"), 10);
-    popup.insertColor(Qt::darkMagenta, tr("Dark magenta"), 11);
-    popup.insertColor(Qt::yellow, tr("Yellow"), 12);
-    popup.insertColor(Qt::darkYellow, tr("Dark yellow"), 13);
-    popup.insertColor(Qt::gray, tr("Gray"), 14);
-    popup.insertColor(Qt::darkGray, tr("Dark gray"), 15);
-    popup.insertColor(Qt::lightGray, tr("Light gray"), 16);
-
-    popup.move(point);
-    popup.exec();
-    return popup.lastSelected();
+QColor QtColorPicker::getColor(const QPoint &point, bool allowCustomColors) {
+  ColorPickerPopup popup(-1, allowCustomColors);
+
+  popup.insertColor(Qt::black, tr("Black"), 0);
+  popup.insertColor(Qt::white, tr("White"), 1);
+  popup.insertColor(Qt::red, tr("Red"), 2);
+  popup.insertColor(Qt::darkRed, tr("Dark red"), 3);
+  popup.insertColor(Qt::green, tr("Green"), 4);
+  popup.insertColor(Qt::darkGreen, tr("Dark green"), 5);
+  popup.insertColor(Qt::blue, tr("Blue"), 6);
+  popup.insertColor(Qt::darkBlue, tr("Dark blue"), 7);
+  popup.insertColor(Qt::cyan, tr("Cyan"), 8);
+  popup.insertColor(Qt::darkCyan, tr("Dark cyan"), 9);
+  popup.insertColor(Qt::magenta, tr("Magenta"), 10);
+  popup.insertColor(Qt::darkMagenta, tr("Dark magenta"), 11);
+  popup.insertColor(Qt::yellow, tr("Yellow"), 12);
+  popup.insertColor(Qt::darkYellow, tr("Dark yellow"), 13);
+  popup.insertColor(Qt::gray, tr("Gray"), 14);
+  popup.insertColor(Qt::darkGray, tr("Dark gray"), 15);
+  popup.insertColor(Qt::lightGray, tr("Light gray"), 16);
+
+  popup.move(point);
+  popup.exec();
+  return popup.lastSelected();
 }
 
 /*! \internal
@@ -535,40 +511,37 @@ QColor QtColorPicker::getColor(const QPoint &point, bool allowCustomColors)
     Constructs the popup widget.
 */
 ColorPickerPopup::ColorPickerPopup(int width, bool withColorDialog,
-				       QWidget *parent)
-    : QFrame(parent, Qt::Popup)
-{
-    setFrameStyle(QFrame::StyledPanel);
-    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
-
-    setFocusPolicy(Qt::StrongFocus);
-    setMouseTracking(true);
-    cols = width;
-
-    if (withColorDialog) {
-	moreButton = new ColorPickerButton(this);
-	moreButton->setFixedWidth(24);
-	moreButton->setFixedHeight(21);
-	moreButton->setFrameRect(QRect(2, 2, 20, 17));
-	connect(moreButton, SIGNAL(clicked()), SLOT(getColorFromDialog()));
-    } else {
-	moreButton = 0;
-    }
+                                   QWidget *parent)
+    : QFrame(parent, Qt::Popup) {
+  setFrameStyle(QFrame::StyledPanel);
+  setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
+
+  setFocusPolicy(Qt::StrongFocus);
+  setMouseTracking(true);
+  cols = width;
+
+  if (withColorDialog) {
+    moreButton = new ColorPickerButton(this);
+    moreButton->setFixedWidth(24);
+    moreButton->setFixedHeight(21);
+    moreButton->setFrameRect(QRect(2, 2, 20, 17));
+    connect(moreButton, SIGNAL(clicked()), SLOT(getColorFromDialog()));
+  } else {
+    moreButton = 0;
+  }
 
-    eventLoop = 0;
-    grid = 0;
-    regenerateGrid();
+  eventLoop = 0;
+  grid = 0;
+  regenerateGrid();
 }
 
-
 /*! \internal
 
     Destructs the popup widget.
 */
-ColorPickerPopup::~ColorPickerPopup()
-{
-    if (eventLoop)
-        eventLoop->exit();
+ColorPickerPopup::~ColorPickerPopup() {
+  if (eventLoop)
+    eventLoop->exit();
 }
 
 /*! \internal
@@ -576,14 +549,13 @@ ColorPickerPopup::~ColorPickerPopup()
     If there is an item whole color is equal to \a col, returns a
     pointer to this item; otherwise returns 0.
 */
-ColorPickerItem *ColorPickerPopup::find(const QColor &col) const
-{
-    for (int i = 0; i < items.size(); ++i) {
-	if (items.at(i) && items.at(i)->color() == col)
-	    return items.at(i);
-    }
+ColorPickerItem *ColorPickerPopup::find(const QColor &col) const {
+  for (int i = 0; i < items.size(); ++i) {
+    if (items.at(i) && items.at(i)->color() == col)
+      return items.at(i);
+  }
 
-    return 0;
+  return 0;
 }
 
 /*! \internal
@@ -591,79 +563,76 @@ ColorPickerItem *ColorPickerPopup::find(const QColor &col) const
     Adds \a item to the grid. The items are added from top-left to
     bottom-right.
 */
-void ColorPickerPopup::insertColor(const QColor &col, const QString &text, int index)
-{
-    // Don't add colors that we have already.
-    ColorPickerItem *existingItem = find(col);
-    ColorPickerItem *lastSelectedItem = find(lastSelected());
-
-    if (existingItem) {
-        if (lastSelectedItem && existingItem != lastSelectedItem)
-            lastSelectedItem->setSelected(false);
-        existingItem->setFocus();
-        existingItem->setSelected(true);
-        return;
-    }
+void ColorPickerPopup::insertColor(const QColor &col, const QString &text,
+                                   int index) {
+  // Don't add colors that we have already.
+  ColorPickerItem *existingItem = find(col);
+  ColorPickerItem *lastSelectedItem = find(lastSelected());
+
+  if (existingItem) {
+    if (lastSelectedItem && existingItem != lastSelectedItem)
+      lastSelectedItem->setSelected(false);
+    existingItem->setFocus();
+    existingItem->setSelected(true);
+    return;
+  }
 
-    ColorPickerItem *item = new ColorPickerItem(col, text, this);
+  ColorPickerItem *item = new ColorPickerItem(col, text, this);
 
-    if (lastSelectedItem) {
-        lastSelectedItem->setSelected(false);
-    }
-    else {
-        item->setSelected(true);
-        lastSel = col;
-    }
-    item->setFocus();
+  if (lastSelectedItem) {
+    lastSelectedItem->setSelected(false);
+  } else {
+    item->setSelected(true);
+    lastSel = col;
+  }
+  item->setFocus();
 
-    connect(item, SIGNAL(selected()), SLOT(updateSelected()));
+  connect(item, SIGNAL(selected()), SLOT(updateSelected()));
 
-    if (index == -1)
-	index = items.count();
+  if (index == -1)
+    index = items.count();
 
-    items.insert((unsigned int)index, item);
-    regenerateGrid();
+  items.insert((unsigned int)index, item);
+  regenerateGrid();
 
-    update();
+  update();
 }
 
 /*! \internal
 
 */
-QColor ColorPickerPopup::color(int index) const
-{
-    if (index < 0 || index > (int) items.count() - 1)
-        return QColor();
-
-    // cppcheck-suppress cstyleCast
-    ColorPickerPopup *that = (ColorPickerPopup *)this;
-    return that->items.at(index)->color();
+QColor ColorPickerPopup::color(int index) const {
+  if (index < 0 || index > (int)items.count() - 1)
+    return QColor();
+
+  // cppcheck-suppress cstyleCast
+  ColorPickerPopup *that = (ColorPickerPopup *)this;
+  return that->items.at(index)->color();
 }
 
 /*! \internal
 
 */
-void ColorPickerPopup::exec()
-{
-    show();
-
-    QEventLoop e;
-    eventLoop = &e;
-    (void) e.exec();
-    eventLoop = 0;
+void ColorPickerPopup::exec() {
+  show();
+
+  QEventLoop e;
+  eventLoop = &e;
+  (void)e.exec();
+  eventLoop = 0;
 }
 
 /*! \internal
 
 */
-void ColorPickerPopup::updateSelected()
-{
+void ColorPickerPopup::updateSelected() {
   QLayoutItem *layoutItem;
   int i = 0;
   while ((layoutItem = grid->itemAt(i)) != 0) {
     QWidget *w = layoutItem->widget();
     if (w && w->inherits("ColorPickerItem")) {
-      ColorPickerItem *litem = reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
+      ColorPickerItem *litem =
+          reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
       if (litem != sender())
         litem->setSelected(false);
     }
@@ -684,148 +653,151 @@ void ColorPickerPopup::updateSelected()
 /*! \internal
 
 */
-void ColorPickerPopup::mouseReleaseEvent(QMouseEvent *e)
-{
-    if (!rect().contains(e->pos()))
-	hide();
+void ColorPickerPopup::mouseReleaseEvent(QMouseEvent *e) {
+  if (!rect().contains(e->pos()))
+    hide();
 }
 
 /*! \internal
 
     Controls keyboard navigation and selection on the color grid.
 */
-void ColorPickerPopup::keyPressEvent(QKeyEvent *e)
-{
-    int curRow = 0;
-    int curCol = 0;
-
-    bool foundFocus = false;
-    for (int j = 0; !foundFocus && j < grid->rowCount(); ++j) {
-	for (int i = 0; !foundFocus && i < grid->columnCount(); ++i) {
-	    if (widgetAt[j][i] && widgetAt[j][i]->hasFocus()) {
-		curRow = j;
-		curCol = i;
-		foundFocus = true;
-		break;
-	    }
-	}
+void ColorPickerPopup::keyPressEvent(QKeyEvent *e) {
+  int curRow = 0;
+  int curCol = 0;
+
+  bool foundFocus = false;
+  for (int j = 0; !foundFocus && j < grid->rowCount(); ++j) {
+    for (int i = 0; !foundFocus && i < grid->columnCount(); ++i) {
+      if (widgetAt[j][i] && widgetAt[j][i]->hasFocus()) {
+        curRow = j;
+        curCol = i;
+        foundFocus = true;
+        break;
+      }
     }
+  }
 
-    switch (e->key()) {
-	case Qt::Key_Left:
-	    if (curCol > 0) --curCol;
-	    else if (curRow > 0) { --curRow; curCol = grid->columnCount() - 1; }
-	    break;
-	case Qt::Key_Right:
-	    if (curCol < grid->columnCount() - 1 && widgetAt[curRow][curCol + 1]) ++curCol;
-	    else if (curRow < grid->rowCount() - 1) { ++curRow; curCol = 0; }
-	    break;
-	case Qt::Key_Up:
-	    if (curRow > 0) --curRow;
-	    else curCol = 0;
-	    break;
-	case Qt::Key_Down:
-	    if (curRow < grid->rowCount() - 1) {
-		QWidget *w = widgetAt[curRow + 1][curCol];
-		if (w) {
-		    ++curRow;
-		} else for (int i = 1; i < grid->columnCount(); ++i) {
-		    if (!widgetAt[curRow + 1][i]) {
-			curCol = i - 1;
-			++curRow;
-			break;
-		    }
-		}
-	    }
-	    break;
-	case Qt::Key_Space:
-	case Qt::Key_Return:
-	case Qt::Key_Enter: {
-	    QWidget *w = widgetAt[curRow][curCol];
-	    if (w && w->inherits("ColorPickerItem")) {
-		ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
-		wi->setSelected(true);
-
-		QLayoutItem *layoutItem;
-                int i = 0;
-		while ((layoutItem = grid->itemAt(i)) != 0) {
-		    QWidget *w = layoutItem->widget();
-		    if (w && w->inherits("ColorPickerItem")) {
-			ColorPickerItem *litem
-			    = reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
-			if (litem != wi)
-			    litem->setSelected(false);
-		    }
-		    ++i;
-		}
-
-		lastSel = wi->color();
-		emit selected(wi->color());
-		hide();
-	    } else if (w && w->inherits("QPushButton")) {
-		ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
-		wi->setSelected(true);
-
-		QLayoutItem *layoutItem;
-                int i = 0;
-		while ((layoutItem = grid->itemAt(i)) != 0) {
-		    QWidget *w = layoutItem->widget();
-		    if (w && w->inherits("ColorPickerItem")) {
-			ColorPickerItem *litem
-			    = reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
-			if (litem != wi)
-			    litem->setSelected(false);
-		    }
-		    ++i;
-		}
-
-		lastSel = wi->color();
-		emit selected(wi->color());
-		hide();
-	    }
-	}
-	break;
-        case Qt::Key_Escape:
-            hide();
-        break;
-	default:
-	    e->ignore();
-	    break;
+  switch (e->key()) {
+  case Qt::Key_Left:
+    if (curCol > 0)
+      --curCol;
+    else if (curRow > 0) {
+      --curRow;
+      curCol = grid->columnCount() - 1;
+    }
+    break;
+  case Qt::Key_Right:
+    if (curCol < grid->columnCount() - 1 && widgetAt[curRow][curCol + 1])
+      ++curCol;
+    else if (curRow < grid->rowCount() - 1) {
+      ++curRow;
+      curCol = 0;
+    }
+    break;
+  case Qt::Key_Up:
+    if (curRow > 0)
+      --curRow;
+    else
+      curCol = 0;
+    break;
+  case Qt::Key_Down:
+    if (curRow < grid->rowCount() - 1) {
+      QWidget *w = widgetAt[curRow + 1][curCol];
+      if (w) {
+        ++curRow;
+      } else
+        for (int i = 1; i < grid->columnCount(); ++i) {
+          if (!widgetAt[curRow + 1][i]) {
+            curCol = i - 1;
+            ++curRow;
+            break;
+          }
+        }
     }
+    break;
+  case Qt::Key_Space:
+  case Qt::Key_Return:
+  case Qt::Key_Enter: {
+    QWidget *w = widgetAt[curRow][curCol];
+    if (w && w->inherits("ColorPickerItem")) {
+      ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
+      wi->setSelected(true);
+
+      QLayoutItem *layoutItem;
+      int i = 0;
+      while ((layoutItem = grid->itemAt(i)) != 0) {
+        QWidget *w = layoutItem->widget();
+        if (w && w->inherits("ColorPickerItem")) {
+          ColorPickerItem *litem =
+              reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
+          if (litem != wi)
+            litem->setSelected(false);
+        }
+        ++i;
+      }
+
+      lastSel = wi->color();
+      emit selected(wi->color());
+      hide();
+    } else if (w && w->inherits("QPushButton")) {
+      ColorPickerItem *wi = reinterpret_cast<ColorPickerItem *>(w);
+      wi->setSelected(true);
+
+      QLayoutItem *layoutItem;
+      int i = 0;
+      while ((layoutItem = grid->itemAt(i)) != 0) {
+        QWidget *w = layoutItem->widget();
+        if (w && w->inherits("ColorPickerItem")) {
+          ColorPickerItem *litem =
+              reinterpret_cast<ColorPickerItem *>(layoutItem->widget());
+          if (litem != wi)
+            litem->setSelected(false);
+        }
+        ++i;
+      }
 
-    widgetAt[curRow][curCol]->setFocus();
+      lastSel = wi->color();
+      emit selected(wi->color());
+      hide();
+    }
+  } break;
+  case Qt::Key_Escape:
+    hide();
+    break;
+  default:
+    e->ignore();
+    break;
+  }
+
+  widgetAt[curRow][curCol]->setFocus();
 }
 
 /*! \internal
 
 */
-void ColorPickerPopup::hideEvent(QHideEvent *e)
-{
-    if (eventLoop) {
-	eventLoop->exit();
-    }
+void ColorPickerPopup::hideEvent(QHideEvent *e) {
+  if (eventLoop) {
+    eventLoop->exit();
+  }
 
-    setFocus();
+  setFocus();
 
-    emit hid();
-    QFrame::hideEvent(e);
+  emit hid();
+  QFrame::hideEvent(e);
 }
 
 /*! \internal
 
 */
-QColor ColorPickerPopup::lastSelected() const
-{
-    return lastSel;
-}
+QColor ColorPickerPopup::lastSelected() const { return lastSel; }
 
 /*! \internal
 
     Sets focus on the popup to enable keyboard navigation. Draws
     focusRect and selection rect.
 */
-void ColorPickerPopup::showEvent(QShowEvent *)
-{
+void ColorPickerPopup::showEvent(QShowEvent *) {
   bool foundSelected = false;
   for (int i = 0; i < grid->columnCount(); ++i) {
     for (int j = 0; j < grid->rowCount(); ++j) {
@@ -851,39 +823,39 @@ void ColorPickerPopup::showEvent(QShowEvent *)
 /*!
 
 */
-void ColorPickerPopup::regenerateGrid()
-{
-    widgetAt.clear();
-
-    int columns = cols;
-    if (columns == -1)
-	columns = (int) ceil(sqrt((float) items.count()));
-
-    // When the number of columns grows, the number of rows will
-    // fall. There's no way to shrink a grid, so we create a new
-    // one.
-    if (grid) delete grid;
-    grid = new QGridLayout(this);
-    grid->setMargin(1);
-    grid->setSpacing(0);
-
-    int ccol = 0, crow = 0;
-    for (int i = 0; i < items.size(); ++i) {
-        if (items.at(i)) {
-            widgetAt[crow][ccol] = items.at(i);
-            grid->addWidget(items.at(i), crow, ccol++);
-            if (ccol == columns) {
-                ++crow;
-                ccol = 0;
-            }
-        }
+void ColorPickerPopup::regenerateGrid() {
+  widgetAt.clear();
+
+  int columns = cols;
+  if (columns == -1)
+    columns = (int)ceil(sqrt((float)items.count()));
+
+  // When the number of columns grows, the number of rows will
+  // fall. There's no way to shrink a grid, so we create a new
+  // one.
+  if (grid)
+    delete grid;
+  grid = new QGridLayout(this);
+  grid->setMargin(1);
+  grid->setSpacing(0);
+
+  int ccol = 0, crow = 0;
+  for (int i = 0; i < items.size(); ++i) {
+    if (items.at(i)) {
+      widgetAt[crow][ccol] = items.at(i);
+      grid->addWidget(items.at(i), crow, ccol++);
+      if (ccol == columns) {
+        ++crow;
+        ccol = 0;
+      }
     }
+  }
 
-    if (moreButton) {
-	grid->addWidget(moreButton, crow, ccol);
-	widgetAt[crow][ccol] = moreButton;
-    }
-    updateGeometry();
+  if (moreButton) {
+    grid->addWidget(moreButton, crow, ccol);
+    widgetAt[crow][ccol] = moreButton;
+  }
+  updateGeometry();
 }
 
 /*! \internal
@@ -891,17 +863,16 @@ void ColorPickerPopup::regenerateGrid()
     Copies the color dialog's currently selected item and emits
     itemSelected().
 */
-void ColorPickerPopup::getColorFromDialog()
-{
-    bool ok;
-    QRgb rgb = QColorDialog::getRgba(lastSel.rgba(), &ok, parentWidget());
-    if (!ok)
-	return;
-
-    QColor col = QColor::fromRgba(rgb);
-    insertColor(col, tr("Custom"), -1);
-    lastSel = col;
-    emit selected(col);
+void ColorPickerPopup::getColorFromDialog() {
+  bool ok;
+  QRgb rgb = QColorDialog::getRgba(lastSel.rgba(), &ok, parentWidget());
+  if (!ok)
+    return;
+
+  QColor col = QColor::fromRgba(rgb);
+  insertColor(col, tr("Custom"), -1);
+  lastSel = col;
+  emit selected(col);
 }
 
 /*!
@@ -909,241 +880,208 @@ void ColorPickerPopup::getColorFromDialog()
     whose name is set to \a text.
 */
 ColorPickerItem::ColorPickerItem(const QColor &color, const QString &text,
-				     QWidget *parent)
-    : QFrame(parent), c(color), t(text), sel(false)
-{
-    setToolTip(t);
-    setFixedWidth(24);
-    setFixedHeight(21);
+                                 QWidget *parent)
+    : QFrame(parent), c(color), t(text), sel(false) {
+  setToolTip(t);
+  setFixedWidth(24);
+  setFixedHeight(21);
 }
 
 /*!
     Destructs a ColorPickerItem.
  */
-ColorPickerItem::~ColorPickerItem()
-{
-}
+ColorPickerItem::~ColorPickerItem() {}
 
 /*!
     Returns the item's color.
 
     \sa text()
 */
-QColor ColorPickerItem::color() const
-{
-    return c;
-}
+QColor ColorPickerItem::color() const { return c; }
 
 /*!
     Returns the item's text.
 
     \sa color()
 */
-QString ColorPickerItem::text() const
-{
-    return t;
-}
+QString ColorPickerItem::text() const { return t; }
 
 /*!
 
 */
-bool ColorPickerItem::isSelected() const
-{
-    return sel;
-}
+bool ColorPickerItem::isSelected() const { return sel; }
 
 /*!
 
 */
-void ColorPickerItem::setSelected(bool selected)
-{
-    sel = selected;
-    update();
+void ColorPickerItem::setSelected(bool selected) {
+  sel = selected;
+  update();
 }
 
 /*!
     Sets the item's color to \a color, and its name to \a text.
 */
-void ColorPickerItem::setColor(const QColor &color, const QString &text)
-{
-    c = color;
-    t = text;
-    setToolTip(t);
-    update();
+void ColorPickerItem::setColor(const QColor &color, const QString &text) {
+  c = color;
+  t = text;
+  setToolTip(t);
+  update();
 }
 
 /*!
 
 */
-void ColorPickerItem::mouseMoveEvent(QMouseEvent *)
-{
-    setFocus();
-    update();
+void ColorPickerItem::mouseMoveEvent(QMouseEvent *) {
+  setFocus();
+  update();
 }
 
 /*!
 
 */
-void ColorPickerItem::mouseReleaseEvent(QMouseEvent *)
-{
-    sel = true;
-    emit selected();
+void ColorPickerItem::mouseReleaseEvent(QMouseEvent *) {
+  sel = true;
+  emit selected();
 }
 
 /*!
 
 */
-void ColorPickerItem::mousePressEvent(QMouseEvent *)
-{
-    setFocus();
-    update();
+void ColorPickerItem::mousePressEvent(QMouseEvent *) {
+  setFocus();
+  update();
 }
 
 /*!
 
 */
-void ColorPickerItem::paintEvent(QPaintEvent *)
-{
-    QPainter p(this);
-    int w = width();			// width of cell in pixels
-    int h = height();			// height of cell in pixels
+void ColorPickerItem::paintEvent(QPaintEvent *) {
+  QPainter p(this);
+  int w = width();  // width of cell in pixels
+  int h = height(); // height of cell in pixels
 
-    p.setPen( QPen( Qt::gray, 0, Qt::SolidLine ) );
+  p.setPen(QPen(Qt::gray, 0, Qt::SolidLine));
 
-    if (sel)
-	p.drawRect(1, 1, w - 3, h - 3);
+  if (sel)
+    p.drawRect(1, 1, w - 3, h - 3);
 
-    p.setPen( QPen( Qt::black, 0, Qt::SolidLine ) );
-    p.drawRect(3, 3, w - 7, h - 7);
-    p.fillRect(QRect(4, 4, w - 8, h - 8), QBrush(c));
+  p.setPen(QPen(Qt::black, 0, Qt::SolidLine));
+  p.drawRect(3, 3, w - 7, h - 7);
+  p.fillRect(QRect(4, 4, w - 8, h - 8), QBrush(c));
 
-    if (hasFocus())
-	p.drawRect(0, 0, w - 1, h - 1);
+  if (hasFocus())
+    p.drawRect(0, 0, w - 1, h - 1);
 }
 
 /*!
 
 */
-ColorPickerButton::ColorPickerButton(QWidget *parent)
-    : QFrame(parent)
-{
-    setFrameStyle(StyledPanel);
+ColorPickerButton::ColorPickerButton(QWidget *parent) : QFrame(parent) {
+  setFrameStyle(StyledPanel);
 }
 
 /*!
 
 */
-void ColorPickerButton::mousePressEvent(QMouseEvent *)
-{
-    setFrameShadow(Sunken);
-    update();
+void ColorPickerButton::mousePressEvent(QMouseEvent *) {
+  setFrameShadow(Sunken);
+  update();
 }
 
 /*!
 
 */
-void ColorPickerButton::mouseMoveEvent(QMouseEvent *)
-{
-    setFocus();
-    update();
+void ColorPickerButton::mouseMoveEvent(QMouseEvent *) {
+  setFocus();
+  update();
 }
 
 /*!
 
 */
-void ColorPickerButton::mouseReleaseEvent(QMouseEvent *)
-{
-    setFrameShadow(Raised);
-    repaint();
-    emit clicked();
+void ColorPickerButton::mouseReleaseEvent(QMouseEvent *) {
+  setFrameShadow(Raised);
+  repaint();
+  emit clicked();
 }
 
 /*!
 
 */
-void ColorPickerButton::keyPressEvent(QKeyEvent *e)
-{
-    if (e->key() == Qt::Key_Up
-	|| e->key() == Qt::Key_Down
-	|| e->key() == Qt::Key_Left
-	|| e->key() == Qt::Key_Right) {
-	qApp->sendEvent(parent(), e);
-    } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Space || e->key() == Qt::Key_Return) {
-	setFrameShadow(Sunken);
-	update();
-    } else {
-	QFrame::keyPressEvent(e);
-    }
+void ColorPickerButton::keyPressEvent(QKeyEvent *e) {
+  if (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down ||
+      e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) {
+    qApp->sendEvent(parent(), e);
+  } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Space ||
+             e->key() == Qt::Key_Return) {
+    setFrameShadow(Sunken);
+    update();
+  } else {
+    QFrame::keyPressEvent(e);
+  }
 }
 
 /*!
 
 */
-void ColorPickerButton::keyReleaseEvent(QKeyEvent *e)
-{
-    if (e->key() == Qt::Key_Up
-	|| e->key() == Qt::Key_Down
-	|| e->key() == Qt::Key_Left
-	|| e->key() == Qt::Key_Right) {
-	qApp->sendEvent(parent(), e);
-    } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Space || e->key() == Qt::Key_Return) {
-	setFrameShadow(Raised);
-	repaint();
-	emit clicked();
-    } else {
-	QFrame::keyReleaseEvent(e);
-    }
-
+void ColorPickerButton::keyReleaseEvent(QKeyEvent *e) {
+  if (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down ||
+      e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) {
+    qApp->sendEvent(parent(), e);
+  } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Space ||
+             e->key() == Qt::Key_Return) {
+    setFrameShadow(Raised);
+    repaint();
+    emit clicked();
+  } else {
+    QFrame::keyReleaseEvent(e);
+  }
 }
 
 /*!
 
 */
-void ColorPickerButton::focusInEvent(QFocusEvent *e)
-{
-    setFrameShadow(Raised);
-    update();
-    QFrame::focusOutEvent(e);
+void ColorPickerButton::focusInEvent(QFocusEvent *e) {
+  setFrameShadow(Raised);
+  update();
+  QFrame::focusOutEvent(e);
 }
 
 /*!
 
 */
-void ColorPickerButton::focusOutEvent(QFocusEvent *e)
-{
-    setFrameShadow(Raised);
-    update();
-    QFrame::focusOutEvent(e);
+void ColorPickerButton::focusOutEvent(QFocusEvent *e) {
+  setFrameShadow(Raised);
+  update();
+  QFrame::focusOutEvent(e);
 }
 
 /*!
 
 */
-void ColorPickerButton::paintEvent(QPaintEvent *e)
-{
-    QFrame::paintEvent(e);
-
-    QPainter p(this);
-    p.fillRect(contentsRect(), palette().button());
+void ColorPickerButton::paintEvent(QPaintEvent *e) {
+  QFrame::paintEvent(e);
 
-    QRect r = rect();
+  QPainter p(this);
+  p.fillRect(contentsRect(), palette().button());
 
-    int offset = frameShadow() == Sunken ? 1 : 0;
+  QRect r = rect();
 
-    QPen pen(palette().buttonText(), 1);
-    p.setPen(pen);
+  int offset = frameShadow() == Sunken ? 1 : 0;
 
-    p.drawRect(r.center().x() + offset - 4, r.center().y() + offset, 1, 1);
-    p.drawRect(r.center().x() + offset    , r.center().y() + offset, 1, 1);
-    p.drawRect(r.center().x() + offset + 4, r.center().y() + offset, 1, 1);
-    if (hasFocus()) {
-	p.setPen( QPen( Qt::black, 0, Qt::SolidLine ) );
-	p.drawRect(0, 0, width() - 1, height() - 1);
-    }
+  QPen pen(palette().buttonText(), 1);
+  p.setPen(pen);
 
-    p.end();
+  p.drawRect(r.center().x() + offset - 4, r.center().y() + offset, 1, 1);
+  p.drawRect(r.center().x() + offset, r.center().y() + offset, 1, 1);
+  p.drawRect(r.center().x() + offset + 4, r.center().y() + offset, 1, 1);
+  if (hasFocus()) {
+    p.setPen(QPen(Qt::black, 0, Qt::SolidLine));
+    p.drawRect(0, 0, width() - 1, height() - 1);
+  }
 
+  p.end();
 }
 
 #include "qtcolorpicker.moc"
-
diff --git a/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.h b/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.h
index 87a43b5189448d7618529ecb1c3c0c621faba309..345957b8169a51d6d3bcb7178a413ebfc990341d 100644
--- a/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.h
+++ b/MantidPlot/src/lib/3rdparty/qtcolorpicker/src/qtcolorpicker.h
@@ -1,17 +1,17 @@
 /****************************************************************************
 **
 ** This file is part of a Qt Solutions component.
-** 
+**
 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** 
+**
 ** Contact:  Qt Software Information (qt-info@nokia.com)
-** 
-** Commercial Usage  
+**
+** Commercial Usage
 ** Licensees holding valid Qt Commercial licenses may use this file in
 ** accordance with the Qt Solutions Commercial License Agreement provided
 ** with the Software or, alternatively, in accordance with the terms
 ** contained in a written agreement between you and Nokia.
-** 
+**
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 2.1 as published by the Free Software
@@ -19,29 +19,29 @@
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU Lesser General Public License version 2.1 requirements
 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-** 
+**
 ** In addition, as a special exception, Nokia gives you certain
 ** additional rights. These rights are described in the Nokia Qt LGPL
 ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
 ** package.
-** 
-** GNU General Public License Usage 
+**
+** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 3.0 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU General Public License version 3.0 requirements will be
 ** met: http://www.gnu.org/copyleft/gpl.html.
-** 
+**
 ** Please note Third Party Software included with Qt Solutions may impose
 ** additional restrictions and it is the user's responsibility to ensure
 ** that they have met the licensing requirements of the GPL, LGPL, or Qt
 ** Solutions Commercial license and the relevant license of the Third
 ** Party Software they are using.
-** 
+**
 ** If you are unsure which license is appropriate for your use, please
 ** contact the sales department at qt-sales@nokia.com.
-** 
+**
 ****************************************************************************/
 
 #ifndef QTCOLORPICKER_H
@@ -55,67 +55,68 @@
 #include <QtGui/QFocusEvent>
 
 #if defined(Q_WS_WIN)
-#  if !defined(QT_QTCOLORPICKER_EXPORT) && !defined(QT_QTCOLORPICKER_IMPORT)
-#    define QT_QTCOLORPICKER_EXPORT
-#  elif defined(QT_QTCOLORPICKER_IMPORT)
-#    if defined(QT_QTCOLORPICKER_EXPORT)
-#      undef QT_QTCOLORPICKER_EXPORT
-#    endif
-#    define QT_QTCOLORPICKER_EXPORT __declspec(dllimport)
-#  elif defined(QT_QTCOLORPICKER_EXPORT)
-#    undef QT_QTCOLORPICKER_EXPORT
-#    define QT_QTCOLORPICKER_EXPORT __declspec(dllexport)
-#  endif
+#if !defined(QT_QTCOLORPICKER_EXPORT) && !defined(QT_QTCOLORPICKER_IMPORT)
+#define QT_QTCOLORPICKER_EXPORT
+#elif defined(QT_QTCOLORPICKER_IMPORT)
+#if defined(QT_QTCOLORPICKER_EXPORT)
+#undef QT_QTCOLORPICKER_EXPORT
+#endif
+#define QT_QTCOLORPICKER_EXPORT __declspec(dllimport)
+#elif defined(QT_QTCOLORPICKER_EXPORT)
+#undef QT_QTCOLORPICKER_EXPORT
+#define QT_QTCOLORPICKER_EXPORT __declspec(dllexport)
+#endif
 #else
-#  define QT_QTCOLORPICKER_EXPORT
+#define QT_QTCOLORPICKER_EXPORT
 #endif
 
 class ColorPickerPopup;
 
-class QT_QTCOLORPICKER_EXPORT QtColorPicker : public QPushButton
-{
-    Q_OBJECT
+class QT_QTCOLORPICKER_EXPORT QtColorPicker : public QPushButton {
+  Q_OBJECT
 
-    Q_PROPERTY(bool colorDialog READ colorDialogEnabled WRITE setColorDialogEnabled)
+  Q_PROPERTY(bool colorDialog READ colorDialogEnabled WRITE
+                 setColorDialogEnabled)
 
 public:
-    QtColorPicker(QWidget *parent = 0,
-                  int columns = -1, bool enableColorDialog = true);
+  QtColorPicker(QWidget *parent = 0, int columns = -1,
+                bool enableColorDialog = true);
 
-    ~QtColorPicker() override;
+  ~QtColorPicker() override;
 
-    void insertColor(const QColor &color, const QString &text = QString::null, int index = -1);
+  void insertColor(const QColor &color, const QString &text = QString::null,
+                   int index = -1);
 
-    QColor currentColor() const;
+  QColor currentColor() const;
 
-    QColor color(int index) const;
+  QColor color(int index) const;
 
-    void setColorDialogEnabled(bool enabled);
-    bool colorDialogEnabled() const;
+  void setColorDialogEnabled(bool enabled);
+  bool colorDialogEnabled() const;
 
-    void setStandardColors();
+  void setStandardColors();
 
-    static QColor getColor(const QPoint &pos, bool allowCustomColors = true);
+  static QColor getColor(const QPoint &pos, bool allowCustomColors = true);
 
 public Q_SLOTS:
-    void setCurrentColor(const QColor &col);
+  void setCurrentColor(const QColor &col);
 
 Q_SIGNALS:
-    void colorChanged(const QColor &);
+  void colorChanged(const QColor &);
 
 protected:
   void paintEvent(QPaintEvent *e) override;
 
 private Q_SLOTS:
-    void buttonPressed(bool toggled);
-    void popupClosed();
+  void buttonPressed(bool toggled);
+  void popupClosed();
 
 private:
-    ColorPickerPopup *popup;
-    QColor col;
-    bool withColorDialog;
-    bool dirty;
-    bool firstInserted;
+  ColorPickerPopup *popup;
+  QColor col;
+  bool withColorDialog;
+  bool dirty;
+  bool firstInserted;
 };
 
 #endif
diff --git a/MantidPlot/src/lib/include/CollapsiveGroupBox.h b/MantidPlot/src/lib/include/CollapsiveGroupBox.h
index 27d633fb9fe56b0e2fd93fa9d94ebf4aa3b43e87..ebd4ab77439d7e63a605e819bd4d50b71ece78df 100644
--- a/MantidPlot/src/lib/include/CollapsiveGroupBox.h
+++ b/MantidPlot/src/lib/include/CollapsiveGroupBox.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : CollapsiveGroupBox.h
+        File                 : CollapsiveGroupBox.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2010 by Ion Vasilief
+        Copyright            : (C) 2010 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A collapsive QGroupBox
+        Description          : A collapsive QGroupBox
 
  ***************************************************************************/
 
@@ -36,8 +36,7 @@
 /**
  *
  */
-class CollapsiveGroupBox : public QGroupBox
-{
+class CollapsiveGroupBox : public QGroupBox {
   Q_OBJECT
 
 public:
@@ -45,11 +44,11 @@ public:
   /**
    * \param parent parent widget (only affects placement of the widget)
    */
-  CollapsiveGroupBox(const QString & title = QString(), QWidget * parent = 0);
+  CollapsiveGroupBox(const QString &title = QString(), QWidget *parent = 0);
 
 public slots:
-  void setCollapsed (bool collapsed = true);
-  void setExpanded (bool expanded = true);
+  void setCollapsed(bool collapsed = true);
+  void setExpanded(bool expanded = true);
 };
 
 #endif
diff --git a/MantidPlot/src/lib/include/ColorBox.h b/MantidPlot/src/lib/include/ColorBox.h
index 94833512ffe7242c3b9630e25a0ad53707dba4de..667e844c9c6bd59d6c1d4c2bc81654e256216c4e 100644
--- a/MantidPlot/src/lib/include/ColorBox.h
+++ b/MantidPlot/src/lib/include/ColorBox.h
@@ -35,8 +35,7 @@
 /**
  * It contains a list of 24 predefined colors.
  */
-class ColorBox : public QComboBox
-{
+class ColorBox : public QComboBox {
   Q_OBJECT
 
 public:
@@ -46,7 +45,7 @@ public:
    */
   ColorBox(QWidget *parent = 0);
   //! Set the current color
-  void setColor(const QColor& c);
+  void setColor(const QColor &c);
   //! Return the current color
   QColor color() const;
   //! Return the list of colors
@@ -54,13 +53,14 @@ public:
   //! Returns the color names
   static QStringList colorNames();
   //! Return the index for a given color
-  static int colorIndex(const QColor& c);
+  static int colorIndex(const QColor &c);
   //! Return the color at index 'colorIndex'
   static QColor color(int colorIndex);
   //! Return the default color at index 'colorIndex'
   static QColor defaultColor(int colorIndex);
-  //! Returns TRUE if the color is included in the color box, otherwise returns FALSE.
-  static bool isValidColor(const QColor& color);
+  //! Returns TRUE if the color is included in the color box, otherwise returns
+  // FALSE.
+  static bool isValidColor(const QColor &color);
   //! Returns the number of predefined colors
   static int numPredefinedColors();
   //! Returns the color name for the predefined colors
diff --git a/MantidPlot/src/lib/include/ColorButton.h b/MantidPlot/src/lib/include/ColorButton.h
index 1763d5725e71c6e4b1cbff1b642819a560a56dc5..2e6d196dbad8a20cc2c6af08c08820076b6ef4ce 100644
--- a/MantidPlot/src/lib/include/ColorButton.h
+++ b/MantidPlot/src/lib/include/ColorButton.h
@@ -36,8 +36,7 @@
 /**
  *
  */
-class ColorButton : public QtColorPicker
-{
+class ColorButton : public QtColorPicker {
   Q_OBJECT
 
 public:
@@ -47,9 +46,9 @@ public:
    */
   ColorButton(QWidget *parent = 0);
   //! Set the current color to be displayed
-  void setColor(const QColor& c){setCurrentColor (c);};
+  void setColor(const QColor &c) { setCurrentColor(c); };
   //! Get the current color
-  QColor color(){return currentColor();};
+  QColor color() { return currentColor(); };
 
 signals:
   void colorChanged();
diff --git a/MantidPlot/src/lib/include/ColorMapEditor.h b/MantidPlot/src/lib/include/ColorMapEditor.h
index 02aa313c4b158ee6238fc812958e1871cf3c3718..94c662bca715784b424ff87a6a05100b21cf5fbb 100644
--- a/MantidPlot/src/lib/include/ColorMapEditor.h
+++ b/MantidPlot/src/lib/include/ColorMapEditor.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ColorMapEditor.h
-	Project              : QtiPlot
+        File                 : ColorMapEditor.h
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtLinearColorMap Editor Widget
+        Copyright            : (C) 2006 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A QwtLinearColorMap Editor Widget
  ***************************************************************************/
 
 /***************************************************************************
@@ -39,13 +39,13 @@ class DoubleSpinBox;
 
 //! A complex widget allowing to customize a QwtLinearColorMap.
 /**
- * It uses a QTableWidget to display the values in one column and their corresponding colors in a second column.
+ * It uses a QTableWidget to display the values in one column and their
+ corresponding colors in a second column.
  * A click on a table color pops-up a QColorDialog allowing to customize it.
 
-	\image html images/color_map_editor.png
+        \image html images/color_map_editor.png
  */
-class ColorMapEditor: public QWidget
-{
+class ColorMapEditor : public QWidget {
   Q_OBJECT
 
 public:
@@ -53,17 +53,18 @@ public:
   /**
    * \param parent parent widget (only affects placement of the widget)
    */
-  ColorMapEditor(const QLocale& locale = QLocale::system(), int precision = 6, QWidget* parent = 0);
+  ColorMapEditor(const QLocale &locale = QLocale::system(), int precision = 6,
+                 QWidget *parent = 0);
   //! Returns the customized color map.
-  QwtLinearColorMap colorMap(){return color_map;};
+  QwtLinearColorMap colorMap() { return color_map; };
   //! Use this function to initialize the color map to be edited.
-  void setColorMap(const QwtLinearColorMap& map);
+  void setColorMap(const QwtLinearColorMap &map);
   //! Use this function to initialize the values range.
   void setRange(double min, double max);
   //! Exports the map to a pseudo-XML string
-  static QString saveToXmlString(const QwtLinearColorMap& color_map);
+  static QString saveToXmlString(const QwtLinearColorMap &color_map);
 
-  signals:
+signals:
   void scalingChanged();
 
 protected slots:
@@ -78,7 +79,8 @@ protected slots:
   bool eventFilter(QObject *object, QEvent *e) override;
 
 private:
-  //! Table displaying the values ranges in the first column and their corresponding colors in the second column
+  //! Table displaying the values ranges in the first column and their
+  // corresponding colors in the second column
   QTableWidget *table;
   QPushButton *insertBtn, *deleteBtn;
   QCheckBox *scaleColorsBox;
diff --git a/MantidPlot/src/lib/include/ExtensibleFileDialog.h b/MantidPlot/src/lib/include/ExtensibleFileDialog.h
index c1b9a926f0999a3013e243bc87470e9b84283bec..b345e88ad3bd237b07512103c4f6124f14e4cde5 100644
--- a/MantidPlot/src/lib/include/ExtensibleFileDialog.h
+++ b/MantidPlot/src/lib/include/ExtensibleFileDialog.h
@@ -34,15 +34,18 @@
 
 //! QFileDialog plus generic extension support.
 /**
- * This is a simple hack on top of QFileDialog that allows a custom extension widget to be added to
- * the bottom of the dialog. A button is provided for toggling display of this widget on/off.
+ * This is a simple hack on top of QFileDialog that allows a custom extension
+ *widget to be added to
+ * the bottom of the dialog. A button is provided for toggling display of this
+ *widget on/off.
  *
- * For the placement of button and extension widget, it is assumed that QFileDialog uses a
- * QGridLayout as its top-level layout. Other layouts will probably lead to a strange outlook,
+ * For the placement of button and extension widget, it is assumed that
+ *QFileDialog uses a
+ * QGridLayout as its top-level layout. Other layouts will probably lead to a
+ *strange outlook,
  * although the functionality should stay intact.
  */
-class ExtensibleFileDialog : public QFileDialog
-{
+class ExtensibleFileDialog : public QFileDialog {
   Q_OBJECT
 
 public:
@@ -52,17 +55,21 @@ public:
    * \param extended flag: show/hide the advanced options on start-up
    * \param flags window flags
    */
-  ExtensibleFileDialog(QWidget *parent=0, bool extended = true, Qt::WFlags flags=0);
-  //! Set the extension widget to be displayed when the user presses the toggle button.
+  ExtensibleFileDialog(QWidget *parent = 0, bool extended = true,
+                       Qt::WFlags flags = 0);
+  //! Set the extension widget to be displayed when the user presses the toggle
+  // button.
   void setExtensionWidget(QWidget *extension);
 
   //! Tells weather the dialog has a valid extension widget
-  bool isExtendable(){return d_extension != NULL;};
-  bool isExtended(){return d_extension_toggle->isChecked();};
+  bool isExtendable() { return d_extension != NULL; };
+  bool isExtended() { return d_extension_toggle->isChecked(); };
   //! Toggle extension widget on/off
   void setExtended(bool extended);
   //! Sets the text to be displayed in the toggle button
-  void setExtentionToggleButtonText(const QString& text){d_extension_toggle->setText(text);};
+  void setExtentionToggleButtonText(const QString &text) {
+    d_extension_toggle->setText(text);
+  };
   //! Enables/Disables editing of the file type filter
   void setEditableFilter(bool on = true);
 
diff --git a/MantidPlot/src/lib/include/LineNumberDisplay.h b/MantidPlot/src/lib/include/LineNumberDisplay.h
index d9698952333b70f903a2d62d3fdf5e0070ce7b7f..e3c45d895a9dfdea8fb7a3ef367d42a460d03069 100644
--- a/MantidPlot/src/lib/include/LineNumberDisplay.h
+++ b/MantidPlot/src/lib/include/LineNumberDisplay.h
@@ -35,14 +35,14 @@
 /**
  * It must be used in connection with another "source" QTextEdit.
  */
-class LineNumberDisplay: public QTextEdit
-{
+class LineNumberDisplay : public QTextEdit {
   Q_OBJECT
 
 public:
   //! Constructor
   /**
-   * \param te the "source" QTextEdit for which we want to display the line numbers
+   * \param te the "source" QTextEdit for which we want to display the line
+   * numbers
    * \param parent parent widget (only affects placement of the dialog)
    */
   LineNumberDisplay(QTextEdit *te, QWidget *parent = 0);
@@ -52,7 +52,7 @@ public slots:
   void updateDocumentSelection();
 
 private slots:
-  void changeCharFormat (const QTextCharFormat &);
+  void changeCharFormat(const QTextCharFormat &);
 
 private:
   void showEvent(QShowEvent *) override;
diff --git a/MantidPlot/src/lib/include/PatternBox.h b/MantidPlot/src/lib/include/PatternBox.h
index 522e5fdb952854b4430a82bc555bf3d5223672ea..791cc9dbb7fe4534469d7bdaeb608efdd38b0e67 100644
--- a/MantidPlot/src/lib/include/PatternBox.h
+++ b/MantidPlot/src/lib/include/PatternBox.h
@@ -35,8 +35,7 @@
 /**
  * This is a simple hack on top of the QComboBox class.
  */
-class PatternBox : public QComboBox
-{
+class PatternBox : public QComboBox {
   Q_OBJECT
 
 public:
@@ -45,10 +44,10 @@ public:
    * \param parent parent widget (only affects placement of the widget)
    */
   PatternBox(QWidget *parent = 0);
-  void setPattern(const Qt::BrushStyle& c);
+  void setPattern(const Qt::BrushStyle &c);
   Qt::BrushStyle getSelectedPattern() const;
 
-  static int patternIndex(const Qt::BrushStyle& style);
+  static int patternIndex(const Qt::BrushStyle &style);
   static Qt::BrushStyle brushStyle(int index);
 
 protected:
diff --git a/MantidPlot/src/lib/include/PenStyleBox.h b/MantidPlot/src/lib/include/PenStyleBox.h
index e199edae8619e4db64418e8343197056fc8b5aa6..a867799ada706dde287b6e93f2e1bb3960b60821 100644
--- a/MantidPlot/src/lib/include/PenStyleBox.h
+++ b/MantidPlot/src/lib/include/PenStyleBox.h
@@ -35,8 +35,7 @@
 /**
  * This is a simple hack on top of the QComboBox class.
  */
-class PenStyleBox : public QComboBox
-{
+class PenStyleBox : public QComboBox {
   Q_OBJECT
 
 public:
@@ -45,10 +44,10 @@ public:
    * \param parent parent widget (only affects placement of the widget)
    */
   PenStyleBox(QWidget *parent = 0);
-  void setStyle(const Qt::PenStyle& style);
+  void setStyle(const Qt::PenStyle &style);
   Qt::PenStyle style() const;
 
-  static int styleIndex(const Qt::PenStyle& style);
+  static int styleIndex(const Qt::PenStyle &style);
   static Qt::PenStyle penStyle(int index);
 
 private:
diff --git a/MantidPlot/src/lib/include/SymbolBox.h b/MantidPlot/src/lib/include/SymbolBox.h
index f26f1b8f3738cacea97b1096fcc325893ec445b1..f855f0e2b7e843f92429f5c0970f42f3aef42a69 100644
--- a/MantidPlot/src/lib/include/SymbolBox.h
+++ b/MantidPlot/src/lib/include/SymbolBox.h
@@ -37,8 +37,7 @@
  * This is a simple hack on top of the QComboBox class.
  \image html images/symbol_box.png
  */
-class SymbolBox : public QComboBox
-{
+class SymbolBox : public QComboBox {
   Q_OBJECT
 public:
   //! Constructor.
@@ -47,11 +46,11 @@ public:
    */
   SymbolBox(bool showNoSymbol = true, QWidget *parent = 0);
 
-  void setStyle(const QwtSymbol::Style& c);
+  void setStyle(const QwtSymbol::Style &c);
   QwtSymbol::Style selectedSymbol() const;
 
   static QwtSymbol::Style style(int index);
-  static int symbolIndex(const QwtSymbol::Style& style);
+  static int symbolIndex(const QwtSymbol::Style &style);
   static QList<int> defaultSymbols();
 
 signals:
diff --git a/MantidPlot/src/lib/include/SymbolDialog.h b/MantidPlot/src/lib/include/SymbolDialog.h
index 33a1685c03f007c0776dc925748bad513b7aa75e..fe7cd9c6922ca28203b5cb3d18797a7d888d77e5 100644
--- a/MantidPlot/src/lib/include/SymbolDialog.h
+++ b/MantidPlot/src/lib/include/SymbolDialog.h
@@ -2,7 +2,8 @@
     File                 : SymbolDialog.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Tool window to select special text characters
 
@@ -40,20 +41,19 @@ class QGridLayout;
 class QButtonGroup;
 
 //! Tools window to select special text characters
-class SymbolDialog : public QDialog
-{
+class SymbolDialog : public QDialog {
   Q_OBJECT
 
 public:
   //! Character set
-  enum CharSet{
-    lowerGreek = 0, /*!< lower case Greek letters */
-    upperGreek = 1,  /*!< upper case Greek letters */
-    mathSymbols = 2, /*!< mathematical symbols */
-    arrowSymbols = 3, /*!< arrow symbols */
-    numberSymbols = 4, /*!< number symbols (e.g. 1/2, vi)*/
+  enum CharSet {
+    lowerGreek = 0,        /*!< lower case Greek letters */
+    upperGreek = 1,        /*!< upper case Greek letters */
+    mathSymbols = 2,       /*!< mathematical symbols */
+    arrowSymbols = 3,      /*!< arrow symbols */
+    numberSymbols = 4,     /*!< number symbols (e.g. 1/2, vi)*/
     latexArrowSymbols = 5, /*!< default LaTeX arrow symbols */
-    latexMathSymbols = 6 /*!< default LaTeX math symbols */
+    latexMathSymbols = 6   /*!< default LaTeX math symbols */
   };
 
   //! Constructor
@@ -62,7 +62,7 @@ public:
    * \param parent parent widget
    * \param fl window flags
    */
-  SymbolDialog(CharSet charSet, QWidget* parent = 0, Qt::WFlags fl = 0 );
+  SymbolDialog(CharSet charSet, QWidget *parent = 0, Qt::WFlags fl = 0);
 
 private:
   //! Show lowercase Greek characters
@@ -80,14 +80,15 @@ private:
   //! Show default LaTeX math symbols
   void initLatexMathSymbols();
 
-  QButtonGroup * buttons;
-  QPushButton * closeButton;
+  QButtonGroup *buttons;
+  QPushButton *closeButton;
   int numButtons;
-  QVBoxLayout * mainLayout;
-  QGridLayout * gridLayout;
+  QVBoxLayout *mainLayout;
+  QGridLayout *gridLayout;
 
 protected:
-  //! Event handler: When the dialog gets the focus the first button is set to react on [return]
+  //! Event handler: When the dialog gets the focus the first button is set to
+  // react on [return]
   void focusInEvent(QFocusEvent *event) override;
 
 public slots:
@@ -100,7 +101,7 @@ public slots:
 
 signals:
   //! Emitted when a letter is to be added
-  void addLetter(const QString&);
+  void addLetter(const QString &);
 };
 
 #endif // exportDialog_H
diff --git a/MantidPlot/src/lib/include/TextFormatButtons.h b/MantidPlot/src/lib/include/TextFormatButtons.h
index 9f1cf70d86caea5c96fd513f832fcbffec83674f..55494ce09761d9192f5b1bcadf116a70caf1ca60 100644
--- a/MantidPlot/src/lib/include/TextFormatButtons.h
+++ b/MantidPlot/src/lib/include/TextFormatButtons.h
@@ -2,9 +2,11 @@
     File                 : TextFormatButtons.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
-    Description          : Widget with text format buttons (connected to a QTextEdit)
+    Description          : Widget with text format buttons (connected to a
+ QTextEdit)
 
  ***************************************************************************/
 
@@ -35,29 +37,29 @@ class QTextEdit;
 class QPushButton;
 
 //! Widget with text format buttons (connected to a QTextEdit)
-class TextFormatButtons : public QWidget
-{
+class TextFormatButtons : public QWidget {
   Q_OBJECT
 
 signals:
   void formattingModified();
 
 public:
-  enum Buttons{Plot3D, AxisLabel, Legend, Equation, TexLegend};
+  enum Buttons { Plot3D, AxisLabel, Legend, Equation, TexLegend };
 
   //! Constructor
   /**
    * \param textEdit the QTextEdit that the buttons shall affect
    * \param parent parent widget
    */
-  TextFormatButtons(QTextEdit * textEdit, Buttons buttons = Plot3D, QWidget * parent=0);
+  TextFormatButtons(QTextEdit *textEdit, Buttons buttons = Plot3D,
+                    QWidget *parent = 0);
   void setButtons(Buttons btns);
 
 private:
   QTextEdit *connectedTextEdit;
   Buttons d_buttons;
   //! Internal function: format selected text with prefix and postfix
-  void formatText(const QString & prefix, const QString & postfix);
+  void formatText(const QString &prefix, const QString &postfix);
   void init(Buttons btns);
 
 private slots:
@@ -87,7 +89,7 @@ private slots:
   //! Let the user insert arrow symbols
   void showArrowSymbols();
   //! Insert 'letter' into the text
-  void addSymbol(const QString& letter);
+  void addSymbol(const QString &letter);
 };
 
 #endif // TEXTFORMATBUTTONS_H
diff --git a/MantidPlot/src/lib/src/CollapsiveGroupBox.cpp b/MantidPlot/src/lib/src/CollapsiveGroupBox.cpp
index 10175826241a4fc2898c4318ee7727bf2560c312..ae83513b65003f64bdb9048a212b8434b21d153c 100644
--- a/MantidPlot/src/lib/src/CollapsiveGroupBox.cpp
+++ b/MantidPlot/src/lib/src/CollapsiveGroupBox.cpp
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : CollapsiveGroupBox.cpp
+        File                 : CollapsiveGroupBox.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2010 by Ion Vasilief
+        Copyright            : (C) 2010 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A collapsive QGroupBox
+        Description          : A collapsive QGroupBox
 
  ***************************************************************************/
 
@@ -28,15 +28,14 @@
  ***************************************************************************/
 #include "CollapsiveGroupBox.h"
 
-CollapsiveGroupBox::CollapsiveGroupBox(const QString & title, QWidget *parent) : QGroupBox(title, parent)
-{
+CollapsiveGroupBox::CollapsiveGroupBox(const QString &title, QWidget *parent)
+    : QGroupBox(title, parent) {
   setCheckable(true);
   connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));
 }
 
-void CollapsiveGroupBox::setCollapsed(bool collapsed)
-{
-  foreach (QObject *o, children()){
+void CollapsiveGroupBox::setCollapsed(bool collapsed) {
+  foreach (QObject *o, children()) {
     if (o->isWidgetType())
       ((QWidget *)o)->setVisible(collapsed);
   }
@@ -44,9 +43,8 @@ void CollapsiveGroupBox::setCollapsed(bool collapsed)
   setFlat(collapsed);
 }
 
-void CollapsiveGroupBox::setExpanded(bool expanded)
-{
-  foreach (QObject *o, children()){
+void CollapsiveGroupBox::setExpanded(bool expanded) {
+  foreach (QObject *o, children()) {
     if (o->isWidgetType())
       ((QWidget *)o)->setVisible(expanded);
   }
diff --git a/MantidPlot/src/lib/src/ColorBox.cpp b/MantidPlot/src/lib/src/ColorBox.cpp
index ce5ee091b17a1b496b0c41fed421028c94aed495..37d81d835a8932b85bdb32f98065d47eac694137 100644
--- a/MantidPlot/src/lib/src/ColorBox.cpp
+++ b/MantidPlot/src/lib/src/ColorBox.cpp
@@ -2,7 +2,7 @@
     File                 : ColorBox.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2006-2010 by Ion Vasilief, Alex Kargovsky
+        Copyright            : (C) 2006-2010 by Ion Vasilief, Alex Kargovsky
     Email (use @ for *)  : ion_vasilief*yahoo.fr, kargovsky*yumr.phys.msu.su
     Description          : A combo box to select a standard color
 
@@ -38,40 +38,38 @@
  * defaultColorNames() method below!!
  */
 const QColor ColorBox::colors[] = {
-    QColor(Qt::black), //black
-    QColor(Qt::red), //red
-    QColor(Qt::green), //green
-    QColor(Qt::blue), //blue
-    QColor(Qt::cyan), //cyan
-    QColor(Qt::magenta), //magenta
-    QColor("#FF8000"), //orange
-    QColor(Qt::darkMagenta), //purple
-    QColor(Qt::darkGreen), //olive
-    QColor(Qt::darkBlue), //navy
-    QColor(Qt::darkRed), // wine
-    QColor(Qt::darkCyan), //dark cyan
-    QColor("#0000A0"), //royal
-    QColor("#8000FF"), //violet
-    QColor("#FF0080"), //pink
-    QColor(Qt::white), //white
-    QColor(Qt::lightGray), //light gray
-    QColor(Qt::gray), //gray
-    QColor("#FFFF80"), //light yellow
-    QColor("#80FFFF"), // light cyan
-    QColor("#FF80FF"), // light magenta
-    QColor(Qt::darkGray), //dark gray
-    QColor(Qt::yellow), //yellow
-    QColor(Qt::darkYellow), //dark yellow
+    QColor(Qt::black),       // black
+    QColor(Qt::red),         // red
+    QColor(Qt::green),       // green
+    QColor(Qt::blue),        // blue
+    QColor(Qt::cyan),        // cyan
+    QColor(Qt::magenta),     // magenta
+    QColor("#FF8000"),       // orange
+    QColor(Qt::darkMagenta), // purple
+    QColor(Qt::darkGreen),   // olive
+    QColor(Qt::darkBlue),    // navy
+    QColor(Qt::darkRed),     // wine
+    QColor(Qt::darkCyan),    // dark cyan
+    QColor("#0000A0"),       // royal
+    QColor("#8000FF"),       // violet
+    QColor("#FF0080"),       // pink
+    QColor(Qt::white),       // white
+    QColor(Qt::lightGray),   // light gray
+    QColor(Qt::gray),        // gray
+    QColor("#FFFF80"),       // light yellow
+    QColor("#80FFFF"),       // light cyan
+    QColor("#FF80FF"),       // light magenta
+    QColor(Qt::darkGray),    // dark gray
+    QColor(Qt::yellow),      // yellow
+    QColor(Qt::darkYellow),  // dark yellow
 };
 
-ColorBox::ColorBox(QWidget *parent) : QComboBox(parent)
-{
+ColorBox::ColorBox(QWidget *parent) : QComboBox(parent) {
   setEditable(false);
   init();
 }
 
-void ColorBox::init()
-{
+void ColorBox::init() {
   QList<QColor> indexedColors = colorList();
   QStringList color_names = colorNames();
 
@@ -81,7 +79,7 @@ void ColorBox::init()
   QPainter p;
   p.begin(&icon);
 
-  for (int i = 0; i < indexedColors.size(); i++){
+  for (int i = 0; i < indexedColors.size(); i++) {
     p.setBrush(QBrush(indexedColors[i]));
     p.drawRect(r);
     this->addItem(icon, color_names[i]);
@@ -89,26 +87,18 @@ void ColorBox::init()
   p.end();
 }
 
-void ColorBox::setColor(const QColor& c)
-{
-  setCurrentIndex(colorIndex(c));
-}
+void ColorBox::setColor(const QColor &c) { setCurrentIndex(colorIndex(c)); }
 
-QColor ColorBox::color() const
-{
-  return color(this->currentIndex());
-}
+QColor ColorBox::color() const { return color(this->currentIndex()); }
 
-int ColorBox::colorIndex(const QColor& c)
-{
+int ColorBox::colorIndex(const QColor &c) {
   if (!isValidColor(c))
     return 0;
 
   return colorList().indexOf(c);
 }
 
-QColor ColorBox::color(int colorIndex)
-{
+QColor ColorBox::color(int colorIndex) {
   QList<QColor> colorsList = colorList();
   if (colorIndex >= 0 && colorIndex < colorsList.size())
     return colorsList[colorIndex];
@@ -116,100 +106,99 @@ QColor ColorBox::color(int colorIndex)
   return Qt::black; // default color is black.
 }
 
-QList<QColor> ColorBox::colorList()
-{
-  // RJT: I don't see why we particularly need the ability to change the list of colours
-  // and it was causing problems even after I changed the organization and application
-  // names. So I'm just going to disable it and stick with the hard-coded defaults.
-
-//#ifdef Q_OS_MAC
-//  QSettings settings(QSettings::IniFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
-//#else
-//  QSettings settings(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
-//#endif
-//  settings.beginGroup("/General");
+QList<QColor> ColorBox::colorList() {
+  // RJT: I don't see why we particularly need the ability to change the list of
+  // colours
+  // and it was causing problems even after I changed the organization and
+  // application
+  // names. So I'm just going to disable it and stick with the hard-coded
+  // defaults.
+
+  //#ifdef Q_OS_MAC
+  //  QSettings settings(QSettings::IniFormat,QSettings::UserScope,
+  //  "ProIndependent", "QtiPlot");
+  //#else
+  //  QSettings settings(QSettings::NativeFormat,QSettings::UserScope,
+  //  "ProIndependent", "QtiPlot");
+  //#endif
+  //  settings.beginGroup("/General");
 
   QList<QColor> indexedColors;
-//  QStringList lst = settings.value("/IndexedColors").toStringList();
-//  if (!lst.isEmpty()){
-//    for (int i = 0; i < lst.size(); i++)
-//      indexedColors << QColor(lst[i]);
-//  } else {
-    for (int i = 0; i < colors_count; i++)
-      indexedColors << colors[i];
-//  }
-//  settings.endGroup();
+  //  QStringList lst = settings.value("/IndexedColors").toStringList();
+  //  if (!lst.isEmpty()){
+  //    for (int i = 0; i < lst.size(); i++)
+  //      indexedColors << QColor(lst[i]);
+  //  } else {
+  for (int i = 0; i < colors_count; i++)
+    indexedColors << colors[i];
+  //  }
+  //  settings.endGroup();
 
   return indexedColors;
 }
 
-QStringList ColorBox::colorNames()
-{
+QStringList ColorBox::colorNames() {
   // RJT: See comment at top of previous method
 
-//#ifdef Q_OS_MAC
-//  QSettings settings(QSettings::IniFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
-//#else
-//  QSettings settings(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
-//#endif
-//  settings.beginGroup("/General");
-//  QStringList color_names = settings.value("/IndexedColorNames", defaultColorNames()).toStringList();
-//  settings.endGroup();
-//  return color_names;
+  //#ifdef Q_OS_MAC
+  //  QSettings settings(QSettings::IniFormat,QSettings::UserScope,
+  //  "ProIndependent", "QtiPlot");
+  //#else
+  //  QSettings settings(QSettings::NativeFormat,QSettings::UserScope,
+  //  "ProIndependent", "QtiPlot");
+  //#endif
+  //  settings.beginGroup("/General");
+  //  QStringList color_names = settings.value("/IndexedColorNames",
+  //  defaultColorNames()).toStringList();
+  //  settings.endGroup();
+  //  return color_names;
   return defaultColorNames();
 }
 
-QColor ColorBox::defaultColor(int colorIndex)
-{
+QColor ColorBox::defaultColor(int colorIndex) {
   if (colorIndex >= 0 && colorIndex < colors_count)
     return colors[colorIndex];
 
   return Qt::black; // default color is black.
 }
 
-bool ColorBox::isValidColor(const QColor& color)
-{
+bool ColorBox::isValidColor(const QColor &color) {
   return colorList().contains(color);
 }
 
-int ColorBox::numPredefinedColors()
-{
-  return colors_count;
-}
+int ColorBox::numPredefinedColors() { return colors_count; }
 
-QStringList ColorBox::defaultColorNames()
-{
+QStringList ColorBox::defaultColorNames() {
   QStringList color_names = QStringList();
-  color_names << tr( "black" );
-  color_names << tr( "red" );
-  color_names << tr( "green" );
-  color_names << tr( "blue" );
-  color_names << tr( "cyan" );
-  color_names << tr( "magenta" );
-  color_names << tr( "orange" );
-  color_names << tr( "purple" );
-  color_names << tr( "olive" );
-  color_names << tr( "navy" );
-  color_names << tr( "wine" );
-  color_names << tr( "dark cyan" );
-  color_names << tr( "royal" );
-  color_names << tr( "violet" );
-  color_names << tr( "pink" );
-  color_names << tr( "white" );
-  color_names << tr( "light gray" );
-  color_names << tr( "gray" );
-  color_names << tr( "light yellow" );
-  color_names << tr( "light cyan" );
-  color_names << tr( "light magenta" );
-  color_names << tr( "dark gray" );
-  color_names << tr( "yellow" );
-  color_names << tr( "dark yellow" );
+  color_names << tr("black");
+  color_names << tr("red");
+  color_names << tr("green");
+  color_names << tr("blue");
+  color_names << tr("cyan");
+  color_names << tr("magenta");
+  color_names << tr("orange");
+  color_names << tr("purple");
+  color_names << tr("olive");
+  color_names << tr("navy");
+  color_names << tr("wine");
+  color_names << tr("dark cyan");
+  color_names << tr("royal");
+  color_names << tr("violet");
+  color_names << tr("pink");
+  color_names << tr("white");
+  color_names << tr("light gray");
+  color_names << tr("gray");
+  color_names << tr("light yellow");
+  color_names << tr("light cyan");
+  color_names << tr("light magenta");
+  color_names << tr("dark gray");
+  color_names << tr("yellow");
+  color_names << tr("dark yellow");
 
   return color_names;
 }
 
-QList<QColor> ColorBox::defaultColors()
-{
+QList<QColor> ColorBox::defaultColors() {
   QList<QColor> lst;
   for (int i = 0; i < colors_count; i++)
     lst << colors[i];
diff --git a/MantidPlot/src/lib/src/ColorButton.cpp b/MantidPlot/src/lib/src/ColorButton.cpp
index 65f47ef92bdb849c116396f4ccd1703ce35222e9..289d337f61ba22ccbe4f5a2820b3e8b894813ca2 100644
--- a/MantidPlot/src/lib/src/ColorButton.cpp
+++ b/MantidPlot/src/lib/src/ColorButton.cpp
@@ -2,7 +2,7 @@
     File                 : ColorButton.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2009 - 2010 by Ion Vasilief
+        Copyright            : (C) 2009 - 2010 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
     Description          : A wrapper around QtColorPicker from QtSolutions
 
@@ -30,8 +30,7 @@
 #include "ColorBox.h"
 #include <QColorDialog>
 
-ColorButton::ColorButton(QWidget *parent) : QtColorPicker(parent)
-{
+ColorButton::ColorButton(QWidget *parent) : QtColorPicker(parent) {
   QStringList color_names = ColorBox::defaultColorNames();
   QList<QColor> defaultColors = ColorBox::defaultColors();
   for (int i = 0; i < ColorBox::numPredefinedColors(); i++)
@@ -39,11 +38,12 @@ ColorButton::ColorButton(QWidget *parent) : QtColorPicker(parent)
 
   QList<QColor> colors = ColorBox::colorList();
   color_names = ColorBox::colorNames();
-  for (int i = 0; i < colors.count(); i++){
+  for (int i = 0; i < colors.count(); i++) {
     QColor c = colors[i];
     if (!defaultColors.contains(c))
       insertColor(c, color_names[i]);
   }
 
-  connect(this, SIGNAL(colorChanged(const QColor & )), this, SIGNAL(colorChanged()));
+  connect(this, SIGNAL(colorChanged(const QColor &)), this,
+          SIGNAL(colorChanged()));
 }
diff --git a/MantidPlot/src/lib/src/ColorMapEditor.cpp b/MantidPlot/src/lib/src/ColorMapEditor.cpp
index 355642b50f0f7025abafd34f5c48c0ddf0a7ebe6..9047f4c2bae3df9d4ed7a98e059261dc9a417ac5 100644
--- a/MantidPlot/src/lib/src/ColorMapEditor.cpp
+++ b/MantidPlot/src/lib/src/ColorMapEditor.cpp
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ColorMapEditor.cpp
-	Project              : QtiPlot
+        File                 : ColorMapEditor.cpp
+        Project              : QtiPlot
 --------------------------------------------------------------------
-	Copyright            : (C) 2006 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtLinearColorMap Editor Widget
+        Copyright            : (C) 2006 by Ion Vasilief
+        Email (use @ for *)  : ion_vasilief*yahoo.fr
+        Description          : A QwtLinearColorMap Editor Widget
  ***************************************************************************/
 
 /***************************************************************************
@@ -38,30 +38,27 @@
 #include <QMouseEvent>
 #include <QMessageBox>
 
-ColorMapEditor::ColorMapEditor(const QLocale& locale, int precision, QWidget* parent)
-: QWidget(parent),
-  color_map(QwtLinearColorMap()),
-  min_val(0),
-  max_val(1),
-  d_locale(locale),
-  d_precision(precision)
-{
+ColorMapEditor::ColorMapEditor(const QLocale &locale, int precision,
+                               QWidget *parent)
+    : QWidget(parent), color_map(QwtLinearColorMap()), min_val(0), max_val(1),
+      d_locale(locale), d_precision(precision) {
   table = new QTableWidget();
   table->setColumnCount(2);
   table->setSelectionMode(QAbstractItemView::SingleSelection);
   table->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
   table->verticalHeader()->hide();
-  table->horizontalHeader()->setClickable( false );
+  table->horizontalHeader()->setClickable(false);
   table->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive);
   table->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
   table->horizontalHeader()->setStretchLastSection(true);
   table->viewport()->setMouseTracking(true);
   table->viewport()->installEventFilter(this);
   table->setHorizontalHeaderLabels(QStringList() << tr("Level") << tr("Color"));
-  table->setMinimumHeight(6*table->horizontalHeader()->height() + 2);
+  table->setMinimumHeight(6 * table->horizontalHeader()->height() + 2);
   table->installEventFilter(this);
 
-  connect(table, SIGNAL(cellClicked (int, int)), this, SLOT(showColorDialog(int, int)));
+  connect(table, SIGNAL(cellClicked(int, int)), this,
+          SLOT(showColorDialog(int, int)));
 
   insertBtn = new QPushButton(tr("&Insert"));
   insertBtn->setEnabled(false);
@@ -71,15 +68,16 @@ ColorMapEditor::ColorMapEditor(const QLocale& locale, int precision, QWidget* pa
   deleteBtn->setEnabled(false);
   connect(deleteBtn, SIGNAL(clicked()), this, SLOT(deleteLevel()));
 
-  QHBoxLayout* hb = new QHBoxLayout();
+  QHBoxLayout *hb = new QHBoxLayout();
   hb->addWidget(insertBtn);
   hb->addWidget(deleteBtn);
 
   scaleColorsBox = new QCheckBox(tr("&Scale Colors"));
   scaleColorsBox->setChecked(true);
-  connect(scaleColorsBox, SIGNAL(toggled(bool)), this, SLOT(setScaledColors(bool)));
+  connect(scaleColorsBox, SIGNAL(toggled(bool)), this,
+          SLOT(setScaledColors(bool)));
 
-  QVBoxLayout* vl = new QVBoxLayout(this);
+  QVBoxLayout *vl = new QVBoxLayout(this);
   vl->setSpacing(0);
   vl->addWidget(table);
   vl->addLayout(hb);
@@ -89,33 +87,33 @@ ColorMapEditor::ColorMapEditor(const QLocale& locale, int precision, QWidget* pa
   setMaximumWidth(200);
 }
 
-void ColorMapEditor::updateColorMap()
-{
+void ColorMapEditor::updateColorMap() {
   int rows = table->rowCount();
   QColor c_min = QColor(table->item(0, 1)->text());
   QColor c_max = QColor(table->item(rows - 1, 1)->text());
   QwtLinearColorMap map(c_min, c_max);
-  for (int i = 1; i < rows-1; i++){
+  for (int i = 1; i < rows - 1; i++) {
     QwtDoubleInterval range = QwtDoubleInterval(min_val, max_val);
-    double val = (((DoubleSpinBox*)table->cellWidget(i, 0))->value() - min_val)/range.width();
-    map.addColorStop (val, QColor(table->item(i, 1)->text()));
+    double val =
+        (((DoubleSpinBox *)table->cellWidget(i, 0))->value() - min_val) /
+        range.width();
+    map.addColorStop(val, QColor(table->item(i, 1)->text()));
   }
 
   color_map = map;
   setScaledColors(scaleColorsBox->isChecked());
 }
 
-void ColorMapEditor::setColorMap(const QwtLinearColorMap& map)
-{
+void ColorMapEditor::setColorMap(const QwtLinearColorMap &map) {
   scaleColorsBox->setChecked(map.mode() == QwtLinearColorMap::ScaledColors);
 
-  QwtArray <double> colors = map.colorStops();
+  QwtArray<double> colors = map.colorStops();
   int rows = (int)colors.size();
   table->setRowCount(rows);
   table->blockSignals(true);
 
   QwtDoubleInterval range = QwtDoubleInterval(min_val, max_val);
-  for (int i = 0; i < rows; i++){
+  for (int i = 0; i < rows; i++) {
     DoubleSpinBox *sb = new DoubleSpinBox();
     sb->setLocale(d_locale);
     sb->setDecimals(d_precision);
@@ -123,23 +121,24 @@ void ColorMapEditor::setColorMap(const QwtLinearColorMap& map)
 
     if (i == 0)
       sb->setRange(min_val, min_val);
-    else if (i == rows -1)
+    else if (i == rows - 1)
       sb->setRange(max_val, max_val);
     else
       sb->setRange(min_val, max_val);
 
     connect(sb, SIGNAL(valueChanged(double)), this, SLOT(updateColorMap()));
-    connect(sb, SIGNAL(activated(DoubleSpinBox *)), this, SLOT(spinBoxActivated(DoubleSpinBox *)));
+    connect(sb, SIGNAL(activated(DoubleSpinBox *)), this,
+            SLOT(spinBoxActivated(DoubleSpinBox *)));
     table->setCellWidget(i, 0, sb);
 
     QColor c = QColor(map.rgb(QwtDoubleInterval(0, 1), colors[i]));
     QTableWidgetItem *it = new QTableWidgetItem(c.name());
-// Avoid compiler warning
-//#ifdef Q_CC_MSVC
+    // Avoid compiler warning
+    //#ifdef Q_CC_MSVC
     it->setFlags(it->flags() & (~Qt::ItemIsEditable));
-//#else
-//    it->setFlags(!Qt::ItemIsEditable);
-//#endif
+    //#else
+    //    it->setFlags(!Qt::ItemIsEditable);
+    //#endif
     it->setBackground(QBrush(c));
     it->setForeground(QBrush(c));
     table->setItem(i, 1, it);
@@ -149,28 +148,26 @@ void ColorMapEditor::setColorMap(const QwtLinearColorMap& map)
   color_map = map;
 }
 
-void ColorMapEditor::setRange(double min, double max)
-{
+void ColorMapEditor::setRange(double min, double max) {
   min_val = QMIN(min, max);
   max_val = QMAX(min, max);
 }
 
-void ColorMapEditor::insertLevel()
-{
+void ColorMapEditor::insertLevel() {
   int row = table->currentRow();
-  DoubleSpinBox *sb = (DoubleSpinBox*)table->cellWidget(row, 0);
+  DoubleSpinBox *sb = (DoubleSpinBox *)table->cellWidget(row, 0);
   if (!sb)
     return;
 
   double current_value = sb->value();
   double previous_value = min_val;
-  sb = (DoubleSpinBox*)table->cellWidget(row - 1, 0);
+  sb = (DoubleSpinBox *)table->cellWidget(row - 1, 0);
   if (sb)
     previous_value = sb->value();
 
-  double val = 0.5*(current_value + previous_value);
+  double val = 0.5 * (current_value + previous_value);
   QwtDoubleInterval range = QwtDoubleInterval(min_val, max_val);
-  double mapped_val = (val - min_val)/range.width();
+  double mapped_val = (val - min_val) / range.width();
 
   QColor c = QColor(color_map.rgb(QwtDoubleInterval(0, 1), mapped_val));
 
@@ -183,16 +180,17 @@ void ColorMapEditor::insertLevel()
   sb->setValue(val);
   sb->setRange(min_val, max_val);
   connect(sb, SIGNAL(valueChanged(double)), this, SLOT(updateColorMap()));
-  connect(sb, SIGNAL(activated(DoubleSpinBox *)), this, SLOT(spinBoxActivated(DoubleSpinBox *)));
+  connect(sb, SIGNAL(activated(DoubleSpinBox *)), this,
+          SLOT(spinBoxActivated(DoubleSpinBox *)));
   table->setCellWidget(row, 0, sb);
 
   QTableWidgetItem *it = new QTableWidgetItem(c.name());
-// Avoid compiler warning
-//#ifdef Q_CC_MSVC
+  // Avoid compiler warning
+  //#ifdef Q_CC_MSVC
   it->setFlags(it->flags() & (~Qt::ItemIsEditable));
-//#else
-//  it->setFlags(!Qt::ItemIsEditable);
-//#endif
+  //#else
+  //  it->setFlags(!Qt::ItemIsEditable);
+  //#endif
   it->setBackground(QBrush(c));
   it->setForeground(QBrush(c));
   table->setItem(row, 1, it);
@@ -202,15 +200,13 @@ void ColorMapEditor::insertLevel()
   updateColorMap();
 }
 
-void ColorMapEditor::deleteLevel()
-{
-  table->removeRow (table->currentRow());
+void ColorMapEditor::deleteLevel() {
+  table->removeRow(table->currentRow());
   enableButtons(table->currentRow());
   updateColorMap();
 }
 
-void ColorMapEditor::showColorDialog(int row, int col)
-{
+void ColorMapEditor::showColorDialog(int row, int col) {
   if (col != 1)
     return;
 
@@ -228,9 +224,8 @@ void ColorMapEditor::showColorDialog(int row, int col)
   updateColorMap();
 }
 
-bool ColorMapEditor::eventFilter(QObject *object, QEvent *e)
-{
-  if (e->type() == QEvent::MouseMove && object == table->viewport()){
+bool ColorMapEditor::eventFilter(QObject *object, QEvent *e) {
+  if (e->type() == QEvent::MouseMove && object == table->viewport()) {
     const QMouseEvent *me = (const QMouseEvent *)e;
     QPoint pos = table->viewport()->mapToParent(me->pos());
     int row = table->rowAt(pos.y() - table->horizontalHeader()->height());
@@ -239,12 +234,12 @@ bool ColorMapEditor::eventFilter(QObject *object, QEvent *e)
     else
       setCursor(QCursor(Qt::ArrowCursor));
     return true;
-  } else if (e->type() == QEvent::Leave && object == table->viewport()){
+  } else if (e->type() == QEvent::Leave && object == table->viewport()) {
     setCursor(QCursor(Qt::ArrowCursor));
     return true;
-  } else if (e->type() == QEvent::KeyPress && object == table){
+  } else if (e->type() == QEvent::KeyPress && object == table) {
     QKeyEvent *ke = (QKeyEvent *)e;
-    if (ke->key() == Qt::Key_Return && table->currentColumn() == 1){
+    if (ke->key() == Qt::Key_Return && table->currentColumn() == 1) {
       showColorDialog(table->currentRow(), 1);
       return true;
     }
@@ -253,12 +248,11 @@ bool ColorMapEditor::eventFilter(QObject *object, QEvent *e)
   return QObject::eventFilter(object, e);
 }
 
-void ColorMapEditor::enableButtons(int row)
-{
+void ColorMapEditor::enableButtons(int row) {
   if (row < 0)
     return;
 
-  if (row == 0 || row == table->rowCount()-1)
+  if (row == 0 || row == table->rowCount() - 1)
     deleteBtn->setEnabled(false);
   else
     deleteBtn->setEnabled(true);
@@ -269,8 +263,7 @@ void ColorMapEditor::enableButtons(int row)
     insertBtn->setEnabled(true);
 }
 
-void ColorMapEditor::setScaledColors(bool scale)
-{
+void ColorMapEditor::setScaledColors(bool scale) {
   if (scale)
     color_map.setMode(QwtLinearColorMap::ScaledColors);
   else
@@ -279,33 +272,30 @@ void ColorMapEditor::setScaledColors(bool scale)
   scalingChanged();
 }
 
-QString ColorMapEditor::saveToXmlString(const QwtLinearColorMap& color_map)
-{
+QString ColorMapEditor::saveToXmlString(const QwtLinearColorMap &color_map) {
   QString s = "<ColorMap>\n";
   s += "\t<Mode>" + QString::number(color_map.mode()) + "</Mode>\n";
   s += "\t<MinColor>" + color_map.color1().name() + "</MinColor>\n";
   s += "\t<MaxColor>" + color_map.color2().name() + "</MaxColor>\n";
-  QwtArray <double> colors = color_map.colorStops();
+  QwtArray<double> colors = color_map.colorStops();
   int stops = (int)colors.size();
   s += "\t<ColorStops>" + QString::number(stops - 2) + "</ColorStops>\n";
-  for (int i = 1; i < stops - 1; i++)
-  {
+  for (int i = 1; i < stops - 1; i++) {
     s += "\t<Stop>" + QString::number(colors[i]) + "\t";
-    s += QColor(color_map.rgb(QwtDoubleInterval(0,1), colors[i])).name();
+    s += QColor(color_map.rgb(QwtDoubleInterval(0, 1), colors[i])).name();
     s += "</Stop>\n";
   }
   return s += "</ColorMap>\n";
 }
 
-void ColorMapEditor::spinBoxActivated(DoubleSpinBox *sb)
-{
+void ColorMapEditor::spinBoxActivated(DoubleSpinBox *sb) {
   if (!sb)
     return;
 
   int rows = table->rowCount();
-  for (int i = 0; i < rows; i++){
-    DoubleSpinBox *box = (DoubleSpinBox*)table->cellWidget(i, 0);
-    if (box && box == sb){
+  for (int i = 0; i < rows; i++) {
+    DoubleSpinBox *box = (DoubleSpinBox *)table->cellWidget(i, 0);
+    if (box && box == sb) {
       table->setCurrentCell(i, 0);
       enableButtons(i);
       return;
diff --git a/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp b/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
index ddd056c17655921a2c3d93ab4d21cb0cccf47a0b..e24ae0bbc84160bbad12563e279da25f9dcbf0cc 100644
--- a/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
+++ b/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp
@@ -2,8 +2,9 @@
     File                 : ExtensibleFileDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2007 by Knut Franke
-						   (C) 2007 - 2010 by Ion Vasilief
+        Copyright            : (C) 2007 by Knut Franke
+                                                   (C) 2007 - 2010 by Ion
+ Vasilief
     Email (use @ for *)  : knut.franke*gmx.de, ion_vasilief*yahoo.fr
     Description          : QFileDialog plus generic extension support
 
@@ -34,9 +35,9 @@
 #include <QUrl>
 #include <QComboBox>
 
-ExtensibleFileDialog::ExtensibleFileDialog(QWidget *parent, bool extended, Qt::WFlags flags)
-  : QFileDialog(parent, flags)
-{
+ExtensibleFileDialog::ExtensibleFileDialog(QWidget *parent, bool extended,
+                                           Qt::WFlags flags)
+    : QFileDialog(parent, flags) {
   d_extension = 0;
   d_extension_row = 0;
 
@@ -45,15 +46,18 @@ ExtensibleFileDialog::ExtensibleFileDialog(QWidget *parent, bool extended, Qt::W
   d_extension_toggle->hide(); // show only for d_extension != 0
   setExtended(extended);
 
-  QGridLayout *main_layout = qobject_cast<QGridLayout*>(layout());
+  QGridLayout *main_layout = qobject_cast<QGridLayout *>(layout());
   if (main_layout) {
     d_extension_row = main_layout->rowCount();
-    main_layout->addWidget(d_extension_toggle, d_extension_row, main_layout->columnCount()-1);
+    main_layout->addWidget(d_extension_toggle, d_extension_row,
+                           main_layout->columnCount() - 1);
     main_layout->setRowStretch(d_extension_row, 0);
-    main_layout->setRowStretch(d_extension_row+1, 0);
+    main_layout->setRowStretch(d_extension_row + 1, 0);
   } else {
-    // fallback in case QFileDialog uses a different layout in the future (=> main_layout==0)
-    // would probably look a mess, but at least all functions would be accessible
+    // fallback in case QFileDialog uses a different layout in the future (=>
+    // main_layout==0)
+    // would probably look a mess, but at least all functions would be
+    // accessible
     layout()->addWidget(d_extension_toggle);
   }
 
@@ -61,8 +65,7 @@ ExtensibleFileDialog::ExtensibleFileDialog(QWidget *parent, bool extended, Qt::W
   connect(this, SIGNAL(rejected()), this, SLOT(close()));
 }
 
-void ExtensibleFileDialog::setExtensionWidget(QWidget *extension)
-{
+void ExtensibleFileDialog::setExtensionWidget(QWidget *extension) {
   if (d_extension == extension)
     return;
   if (d_extension) {
@@ -76,39 +79,40 @@ void ExtensibleFileDialog::setExtensionWidget(QWidget *extension)
   }
   d_extension_toggle->show();
 
-  QGridLayout *main_layout = qobject_cast<QGridLayout*>(layout());
+  QGridLayout *main_layout = qobject_cast<QGridLayout *>(layout());
   if (main_layout)
-    main_layout->addWidget(d_extension, d_extension_row, 0, 2, main_layout->columnCount()-1);
+    main_layout->addWidget(d_extension, d_extension_row, 0, 2,
+                           main_layout->columnCount() - 1);
   else
     layout()->addWidget(d_extension);
 
   d_extension->setVisible(d_extension_toggle->isChecked());
-  connect(d_extension_toggle, SIGNAL(toggled(bool)), d_extension, SLOT(setVisible(bool)));
-  connect(d_extension_toggle, SIGNAL(toggled(bool)), this, SLOT(updateToggleButtonText(bool)));
+  connect(d_extension_toggle, SIGNAL(toggled(bool)), d_extension,
+          SLOT(setVisible(bool)));
+  connect(d_extension_toggle, SIGNAL(toggled(bool)), this,
+          SLOT(updateToggleButtonText(bool)));
 }
 
-void ExtensibleFileDialog::setEditableFilter(bool on)
-{
+void ExtensibleFileDialog::setEditableFilter(bool on) {
   QLayout *main_layout = layout();
   if (!main_layout)
     return;
 
-  for (int i = 0; i < main_layout->count(); i++){
+  for (int i = 0; i < main_layout->count(); i++) {
     QLayoutItem *item = main_layout->itemAt(i);
     if (!item)
       continue;
-    QComboBox *filterBox = qobject_cast<QComboBox*>(item->widget());
-    if (filterBox){
+    QComboBox *filterBox = qobject_cast<QComboBox *>(item->widget());
+    if (filterBox) {
       filterBox->setEditable(on);
-      connect(filterBox, SIGNAL(editTextChanged(const QString &)),
-          this, SIGNAL(filterSelected(const QString &)));
+      connect(filterBox, SIGNAL(editTextChanged(const QString &)), this,
+              SIGNAL(filterSelected(const QString &)));
       return;
     }
   }
 }
 
-void ExtensibleFileDialog::updateToggleButtonText(bool toggled)
-{
+void ExtensibleFileDialog::updateToggleButtonText(bool toggled) {
   QString s = tr("&Advanced");
   if (toggled)
     s += " >>";
@@ -117,8 +121,7 @@ void ExtensibleFileDialog::updateToggleButtonText(bool toggled)
   d_extension_toggle->setText(s);
 }
 
-void ExtensibleFileDialog::setExtended(bool extended)
-{
+void ExtensibleFileDialog::setExtended(bool extended) {
   updateToggleButtonText(extended);
   if (extended)
     d_extension_toggle->toggle();
diff --git a/MantidPlot/src/lib/src/LineNumberDisplay.cpp b/MantidPlot/src/lib/src/LineNumberDisplay.cpp
index 73ad3f0b50d70574e00dbd93bf241e472cf33c9e..f6583c2a025ce7c35b0e5e702c74460f521aba46 100644
--- a/MantidPlot/src/lib/src/LineNumberDisplay.cpp
+++ b/MantidPlot/src/lib/src/LineNumberDisplay.cpp
@@ -32,8 +32,7 @@
 #include <QPainter>
 
 LineNumberDisplay::LineNumberDisplay(QTextEdit *te, QWidget *parent)
-  : QTextEdit(parent), d_text_edit(te)
-{
+    : QTextEdit(parent), d_text_edit(te) {
   setReadOnly(true);
   setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
   setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@@ -48,25 +47,27 @@ LineNumberDisplay::LineNumberDisplay(QTextEdit *te, QWidget *parent)
   palette.setColor(QPalette::Highlight, palette.color(QPalette::Base));
   setPalette(palette);
 
-  if (te){
-    connect(this, SIGNAL(selectionChanged()), this, SLOT(updateDocumentSelection()));
+  if (te) {
+    connect(this, SIGNAL(selectionChanged()), this,
+            SLOT(updateDocumentSelection()));
 
-    connect(te->document(), SIGNAL(contentsChanged()), this, SLOT(updateLineNumbers()));
+    connect(te->document(), SIGNAL(contentsChanged()), this,
+            SLOT(updateLineNumbers()));
     connect((QObject *)te->verticalScrollBar(), SIGNAL(valueChanged(int)),
-        (QObject *)verticalScrollBar(), SLOT(setValue(int)));
-    connect(te, SIGNAL(currentCharFormatChanged (const QTextCharFormat &)),
-        this, SLOT(changeCharFormat (const QTextCharFormat &)));
+            (QObject *)verticalScrollBar(), SLOT(setValue(int)));
+    connect(te, SIGNAL(currentCharFormatChanged(const QTextCharFormat &)), this,
+            SLOT(changeCharFormat(const QTextCharFormat &)));
   }
 }
 
-void LineNumberDisplay::updateDocumentSelection()
-{
+void LineNumberDisplay::updateDocumentSelection() {
   if (!isVisible() || !d_text_edit)
     return;
 
   QTextCursor c = textCursor();
 #if QT_VERSION >= 0x040500
-  int selectionStart = document()->findBlock(c.selectionStart()).firstLineNumber();
+  int selectionStart =
+      document()->findBlock(c.selectionStart()).firstLineNumber();
   int selectionEnd = document()->findBlock(c.selectionEnd()).firstLineNumber();
 #else
   int selectionStart = document()->findBlock(c.selectionStart()).blockNumber();
@@ -90,8 +91,7 @@ void LineNumberDisplay::updateDocumentSelection()
   d_text_edit->setTextCursor(cursor);
 }
 
-void LineNumberDisplay::updateLineNumbers(bool force)
-{
+void LineNumberDisplay::updateLineNumbers(bool force) {
   if (!isVisible() || !d_text_edit)
     return;
 
@@ -100,24 +100,22 @@ void LineNumberDisplay::updateLineNumbers(bool force)
     return;
 
   QString aux;
-  for(int i = 0; i < lines; i++)
+  for (int i = 0; i < lines; i++)
     aux += QString::number(i + 1) + "\n";
 
   setPlainText(aux);
 
   QFontMetrics fm(d_text_edit->currentFont(), this);
-  setMaximumWidth(2*fm.boundingRect(QString::number(lines)).width());
+  setMaximumWidth(2 * fm.boundingRect(QString::number(lines)).width());
   verticalScrollBar()->setValue(d_text_edit->verticalScrollBar()->value());
 }
 
-void LineNumberDisplay::showEvent(QShowEvent *e)
-{
+void LineNumberDisplay::showEvent(QShowEvent *e) {
   e->accept();
   if (isVisible())
     updateLineNumbers();
 }
 
-void LineNumberDisplay::changeCharFormat (const QTextCharFormat &f)
-{
+void LineNumberDisplay::changeCharFormat(const QTextCharFormat &f) {
   setCurrentFont(f.font());
 }
diff --git a/MantidPlot/src/lib/src/PatternBox.cpp b/MantidPlot/src/lib/src/PatternBox.cpp
index 388c29fa77855a397dcad9de71b788f918ae6be2..b284e15b82e127ea2376cff8d365138dd8cd57e6 100644
--- a/MantidPlot/src/lib/src/PatternBox.cpp
+++ b/MantidPlot/src/lib/src/PatternBox.cpp
@@ -33,127 +33,111 @@
 #include <qpainter.h>
 
 const Qt::BrushStyle PatternBox::patterns[] = {
-    Qt::SolidPattern,
-    Qt::HorPattern,
-    Qt::VerPattern,
-    Qt::CrossPattern,
-    Qt::BDiagPattern,
-    Qt::FDiagPattern,
-    Qt::DiagCrossPattern,
-    Qt::Dense1Pattern,
-    Qt::Dense2Pattern,
-    Qt::Dense3Pattern,
-    Qt::Dense4Pattern,
-    Qt::Dense5Pattern,
-    Qt::Dense6Pattern,
-    Qt::Dense7Pattern
-};
-
-PatternBox::PatternBox(QWidget *parent) : QComboBox(parent)
-{
-  init();
-}
+    Qt::SolidPattern,     Qt::HorPattern,    Qt::VerPattern,
+    Qt::CrossPattern,     Qt::BDiagPattern,  Qt::FDiagPattern,
+    Qt::DiagCrossPattern, Qt::Dense1Pattern, Qt::Dense2Pattern,
+    Qt::Dense3Pattern,    Qt::Dense4Pattern, Qt::Dense5Pattern,
+    Qt::Dense6Pattern,    Qt::Dense7Pattern};
+
+PatternBox::PatternBox(QWidget *parent) : QComboBox(parent) { init(); }
 
-void PatternBox::init()
-{
+void PatternBox::init() {
 
   QPixmap icon = QPixmap(28, 14);
-  icon.fill ( QColor (Qt::white) );
+  icon.fill(QColor(Qt::white));
   const QRect r = QRect(0, 0, 27, 13);
   QPainter p(&icon);
   QBrush br = QBrush(QColor(Qt::darkGray), Qt::SolidPattern);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Solid" ) );
+  this->addItem(icon, tr("Solid"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::HorPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Horizontal" ) );
+  this->addItem(icon, tr("Horizontal"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::VerPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Vertical" ) );
+  this->addItem(icon, tr("Vertical"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::CrossPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Cross" ) );
+  this->addItem(icon, tr("Cross"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::BDiagPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "BDiagonal" ) );
+  this->addItem(icon, tr("BDiagonal"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::FDiagPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "FDiagonal" ) );
+  this->addItem(icon, tr("FDiagonal"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::DiagCrossPattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "DiagCross" ) );
+  this->addItem(icon, tr("DiagCross"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense1Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense1" ) );
+  this->addItem(icon, tr("Dense1"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense2Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense2" ) );
+  this->addItem(icon, tr("Dense2"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense3Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense3" ) );
+  this->addItem(icon, tr("Dense3"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense4Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense4" ) );
+  this->addItem(icon, tr("Dense4"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense5Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense5" ) );
+  this->addItem(icon, tr("Dense5"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense6Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense6" ) );
+  this->addItem(icon, tr("Dense6"));
 
   br = QBrush(QColor(Qt::darkGray), Qt::Dense7Pattern);
   p.eraseRect(r);
   p.fillRect(r, br);
   p.drawRect(r);
-  this->addItem(icon, tr( "Dense7" ) );
+  this->addItem(icon, tr("Dense7"));
   p.end();
 }
 
-void PatternBox::setPattern(const Qt::BrushStyle& style)
-{
-  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out of range
+void PatternBox::setPattern(const Qt::BrushStyle &style) {
+  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out
+  // of range
   size_t n = numberOfPatterns();
-  for(size_t i = 0; i < n; ++i)
-  {
-    if (patterns[i] == style)
-    {
+  for (size_t i = 0; i < n; ++i) {
+    if (patterns[i] == style) {
       setCurrentIndex(int(i));
       return;
     }
@@ -161,16 +145,14 @@ void PatternBox::setPattern(const Qt::BrushStyle& style)
   setCurrentIndex(0); // default pattern is solid.
 }
 
-Qt::BrushStyle PatternBox::brushStyle(int index)
-{
+Qt::BrushStyle PatternBox::brushStyle(int index) {
   if (index < (int)numberOfPatterns())
     return patterns[index];
   else
     return Qt::SolidPattern; // default patterns is solid.
 }
 
-Qt::BrushStyle PatternBox::getSelectedPattern() const
-{
+Qt::BrushStyle PatternBox::getSelectedPattern() const {
   size_t i = this->currentIndex();
   if (i < numberOfPatterns())
     return patterns[i];
@@ -178,21 +160,18 @@ Qt::BrushStyle PatternBox::getSelectedPattern() const
     return Qt::SolidPattern; // default patterns is solid.
 }
 
-int PatternBox::patternIndex(const Qt::BrushStyle& style)
-{
-  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out of range
+int PatternBox::patternIndex(const Qt::BrushStyle &style) {
+  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out
+  // of range
   size_t n = numberOfPatterns();
-  for(size_t i = 0; i < n; ++i)
-  {
-    if (patterns[i] == style)
-    {
+  for (size_t i = 0; i < n; ++i) {
+    if (patterns[i] == style) {
       return int(i);
     }
   }
   return 0; // default pattern is solid.
 }
 
-size_t PatternBox::numberOfPatterns()
-{
+size_t PatternBox::numberOfPatterns() {
   return sizeof(patterns) / sizeof(Qt::BrushStyle);
 }
diff --git a/MantidPlot/src/lib/src/PenStyleBox.cpp b/MantidPlot/src/lib/src/PenStyleBox.cpp
index 179541eebf96af77a5dca3652e3ad984569cee05..daf8f668ef5235f05f366e6c83d49a93a866ac70 100644
--- a/MantidPlot/src/lib/src/PenStyleBox.cpp
+++ b/MantidPlot/src/lib/src/PenStyleBox.cpp
@@ -30,16 +30,11 @@
 
 #include <algorithm>
 
-const Qt::PenStyle PenStyleBox::patterns[] = {
-    Qt::SolidLine,
-    Qt::DashLine,
-    Qt::DotLine,
-    Qt::DashDotLine,
-    Qt::DashDotDotLine
-};
+const Qt::PenStyle PenStyleBox::patterns[] = {Qt::SolidLine, Qt::DashLine,
+                                              Qt::DotLine, Qt::DashDotLine,
+                                              Qt::DashDotDotLine};
 
-PenStyleBox::PenStyleBox(QWidget *parent) : QComboBox(parent)
-{
+PenStyleBox::PenStyleBox(QWidget *parent) : QComboBox(parent) {
   setEditable(false);
   addItem("_____");
   addItem("_ _ _");
@@ -48,60 +43,57 @@ PenStyleBox::PenStyleBox(QWidget *parent) : QComboBox(parent)
   addItem("_.._..");
 }
 
-void PenStyleBox::setStyle(const Qt::PenStyle& style)
-{
-  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out of range
+void PenStyleBox::setStyle(const Qt::PenStyle &style) {
+  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out
+  // of range
   size_t n = numberOfPatterns();
-  for(size_t i = 0; i < n ; ++i)
-  {
-    if (patterns[i] == style)
-    {
+  for (size_t i = 0; i < n; ++i) {
+    if (patterns[i] == style) {
       setCurrentIndex(int(i));
       return;
     }
   }
   setCurrentIndex(0); // default style is solid.
-//  const Qt::PenStyle*ite = std::find(patterns, patterns + sizeof(patterns), style);
-//  if (ite == patterns + sizeof(patterns))
-//    this->setCurrentIndex(0); // default style is solid.
-//  else
-//    this->setCurrentIndex(int(ite - patterns));
+  //  const Qt::PenStyle*ite = std::find(patterns, patterns + sizeof(patterns),
+  //  style);
+  //  if (ite == patterns + sizeof(patterns))
+  //    this->setCurrentIndex(0); // default style is solid.
+  //  else
+  //    this->setCurrentIndex(int(ite - patterns));
 }
 
-Qt::PenStyle PenStyleBox::penStyle(int index)
-{
+Qt::PenStyle PenStyleBox::penStyle(int index) {
   if (index < (int)numberOfPatterns())
     return patterns[index];
   else
-    return Qt::SolidLine; // default style is solid. 
+    return Qt::SolidLine; // default style is solid.
 }
 
-Qt::PenStyle PenStyleBox::style() const
-{
+Qt::PenStyle PenStyleBox::style() const {
   size_t i = this->currentIndex();
   if (i < numberOfPatterns())
     return patterns[i];
   else
-    return Qt::SolidLine; // default style is solid. 
+    return Qt::SolidLine; // default style is solid.
 }
 
-int PenStyleBox::styleIndex(const Qt::PenStyle& style)
-{
-  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out of range
+int PenStyleBox::styleIndex(const Qt::PenStyle &style) {
+  // Avoid compiler warnings relating to patterns + sizeof(patterns) being out
+  // of range
   size_t n = numberOfPatterns();
-  for(size_t i = 0; i < n ; ++i)
-  {
-    if (patterns[i] == style) return int(i);
+  for (size_t i = 0; i < n; ++i) {
+    if (patterns[i] == style)
+      return int(i);
   }
   return 0; // default style is solid.
-//  const Qt::PenStyle*ite = std::find(patterns, patterns + sizeof(patterns), style);
-//  if (ite == patterns + sizeof(patterns))
-//    return 0; // default style is solid.
-//  else
-//    return (int(ite - patterns));
+  //  const Qt::PenStyle*ite = std::find(patterns, patterns + sizeof(patterns),
+  //  style);
+  //  if (ite == patterns + sizeof(patterns))
+  //    return 0; // default style is solid.
+  //  else
+  //    return (int(ite - patterns));
 }
 
-size_t PenStyleBox::numberOfPatterns()
-{
+size_t PenStyleBox::numberOfPatterns() {
   return sizeof(patterns) / sizeof(Qt::PenStyle);
 }
\ No newline at end of file
diff --git a/MantidPlot/src/lib/src/SymbolBox.cpp b/MantidPlot/src/lib/src/SymbolBox.cpp
index c1c04b449874b1ba2db90e36dc3fe11ffe1380dc..5f7e31330a3ebe07ee0b21162e6b2fccb74d5391 100644
--- a/MantidPlot/src/lib/src/SymbolBox.cpp
+++ b/MantidPlot/src/lib/src/SymbolBox.cpp
@@ -33,33 +33,20 @@
 #include <qpainter.h>
 
 const QwtSymbol::Style SymbolBox::symbols[] = {
-    QwtSymbol::NoSymbol,
-    QwtSymbol::Ellipse,
-    QwtSymbol::Rect,
-    QwtSymbol::Diamond,
-    QwtSymbol::Triangle,
-    QwtSymbol::DTriangle,
-    QwtSymbol::UTriangle,
-    QwtSymbol::LTriangle,
-    QwtSymbol::RTriangle,
-    QwtSymbol::Cross,
-    QwtSymbol::XCross,
-    QwtSymbol::HLine,
-    QwtSymbol::VLine,
-    QwtSymbol::Star1,
-    QwtSymbol::Star2,
-    QwtSymbol::Hexagon
-};
-
-SymbolBox::SymbolBox(bool showNoSymbol, QWidget *parent) : QComboBox(parent)
-{
+    QwtSymbol::NoSymbol,  QwtSymbol::Ellipse,   QwtSymbol::Rect,
+    QwtSymbol::Diamond,   QwtSymbol::Triangle,  QwtSymbol::DTriangle,
+    QwtSymbol::UTriangle, QwtSymbol::LTriangle, QwtSymbol::RTriangle,
+    QwtSymbol::Cross,     QwtSymbol::XCross,    QwtSymbol::HLine,
+    QwtSymbol::VLine,     QwtSymbol::Star1,     QwtSymbol::Star2,
+    QwtSymbol::Hexagon};
+
+SymbolBox::SymbolBox(bool showNoSymbol, QWidget *parent) : QComboBox(parent) {
   init(showNoSymbol);
 }
 
-void SymbolBox::init(bool showNoSymbol)
-{
+void SymbolBox::init(bool showNoSymbol) {
   QPixmap icon = QPixmap(15, 15);
-  QColor c = QColor (Qt::gray);
+  QColor c = QColor(Qt::gray);
   icon.fill(c);
   const QRect r = QRect(1, 1, 14, 14);
   QPainter p(&icon);
@@ -68,107 +55,105 @@ void SymbolBox::init(bool showNoSymbol)
   p.setBrush(QBrush(QColor(Qt::white)));
 
   if (showNoSymbol)
-    this->addItem(tr("No Symbol" ));
+    this->addItem(tr("No Symbol"));
 
-  symb.setStyle (QwtSymbol::Ellipse);
+  symb.setStyle(QwtSymbol::Ellipse);
   symb.draw(&p, r);
-  this->addItem(icon, tr("Ellipse" ));
+  this->addItem(icon, tr("Ellipse"));
 
-  symb.setStyle (QwtSymbol::Rect);
+  symb.setStyle(QwtSymbol::Rect);
   icon.fill(c);
   symb.draw(&p, r.adjusted(0, 0, -1, -1));
-  this->addItem(icon,tr("Rectangle"));
+  this->addItem(icon, tr("Rectangle"));
 
-  symb.setStyle (QwtSymbol::Diamond);
+  symb.setStyle(QwtSymbol::Diamond);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Diamond"));
+  this->addItem(icon, tr("Diamond"));
 
-  symb.setStyle (QwtSymbol::Triangle);
+  symb.setStyle(QwtSymbol::Triangle);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Triangle"));
+  this->addItem(icon, tr("Triangle"));
 
-  symb.setStyle (QwtSymbol::DTriangle);
+  symb.setStyle(QwtSymbol::DTriangle);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Down Triangle"));
+  this->addItem(icon, tr("Down Triangle"));
 
-  symb.setStyle (QwtSymbol::UTriangle);
+  symb.setStyle(QwtSymbol::UTriangle);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Up Triangle"));
+  this->addItem(icon, tr("Up Triangle"));
 
-  symb.setStyle (QwtSymbol::LTriangle);
+  symb.setStyle(QwtSymbol::LTriangle);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Left Triangle"));
+  this->addItem(icon, tr("Left Triangle"));
 
-  symb.setStyle (QwtSymbol::RTriangle);
+  symb.setStyle(QwtSymbol::RTriangle);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Right Triangle"));
+  this->addItem(icon, tr("Right Triangle"));
 
-  symb.setStyle (QwtSymbol::Cross);
+  symb.setStyle(QwtSymbol::Cross);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Cross"));
+  this->addItem(icon, tr("Cross"));
 
-  symb.setStyle (QwtSymbol::XCross);
+  symb.setStyle(QwtSymbol::XCross);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Diagonal Cross"));
+  this->addItem(icon, tr("Diagonal Cross"));
 
-  symb.setStyle (QwtSymbol::HLine);
+  symb.setStyle(QwtSymbol::HLine);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Horizontal Line"));
+  this->addItem(icon, tr("Horizontal Line"));
 
-  symb.setStyle (QwtSymbol::VLine);
-  p.eraseRect ( r );
+  symb.setStyle(QwtSymbol::VLine);
+  p.eraseRect(r);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Vertical Line"));
+  this->addItem(icon, tr("Vertical Line"));
 
-  symb.setStyle (QwtSymbol::Star1);
+  symb.setStyle(QwtSymbol::Star1);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Star 1"));
+  this->addItem(icon, tr("Star 1"));
 
-  symb.setStyle (QwtSymbol::Star2);
+  symb.setStyle(QwtSymbol::Star2);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Star 2"));
+  this->addItem(icon, tr("Star 2"));
 
-  symb.setStyle (QwtSymbol::Hexagon);
+  symb.setStyle(QwtSymbol::Hexagon);
   icon.fill(c);
   symb.draw(&p, r);
-  this->addItem(icon,tr("Hexagon"));
+  this->addItem(icon, tr("Hexagon"));
 
   p.end();
 }
 
-void SymbolBox::setStyle(const QwtSymbol::Style& style)
-{
-  // Avoid compiler warnings relating to symbols + sizeof(symbols) being out of range
+void SymbolBox::setStyle(const QwtSymbol::Style &style) {
+  // Avoid compiler warnings relating to symbols + sizeof(symbols) being out of
+  // range
   size_t n = numberOfSymbols();
-  for(size_t i = 0; i < n; ++i)
-  {
-    if (symbols[i] == style)
-    {
+  for (size_t i = 0; i < n; ++i) {
+    if (symbols[i] == style) {
       setCurrentIndex(int(i));
       return;
     }
   }
   setCurrentIndex(0);
-//  const QwtSymbol::Style*ite = std::find(symbols, symbols + sizeof(symbols), style);
-//  if (ite == symbols + sizeof(symbols))
-//    this->setCurrentIndex(0);
-//  else
-//    this->setCurrentIndex(int(ite - symbols));
+  //  const QwtSymbol::Style*ite = std::find(symbols, symbols + sizeof(symbols),
+  //  style);
+  //  if (ite == symbols + sizeof(symbols))
+  //    this->setCurrentIndex(0);
+  //  else
+  //    this->setCurrentIndex(int(ite - symbols));
 }
 
-QwtSymbol::Style SymbolBox::selectedSymbol() const
-{
+QwtSymbol::Style SymbolBox::selectedSymbol() const {
   size_t i = this->currentIndex();
   if (i < sizeof(symbols))
     return symbols[this->currentIndex()];
@@ -176,35 +161,32 @@ QwtSymbol::Style SymbolBox::selectedSymbol() const
   return QwtSymbol::NoSymbol;
 }
 
-int SymbolBox::symbolIndex(const QwtSymbol::Style& style)
-{
-  // Avoid compiler warnings relating to symbols + sizeof(symbols) being out of range
+int SymbolBox::symbolIndex(const QwtSymbol::Style &style) {
+  // Avoid compiler warnings relating to symbols + sizeof(symbols) being out of
+  // range
   size_t n = numberOfSymbols();
-  for(size_t i = 0; i < n; ++i)
-  {
-    if (symbols[i] == style)
-    {
+  for (size_t i = 0; i < n; ++i) {
+    if (symbols[i] == style) {
       return int(i);
     }
   }
   return 0;
-//  const QwtSymbol::Style*ite = std::find(symbols, symbols + sizeof(symbols), style);
-//  if (ite == symbols + sizeof(symbols))
-//    return 0;
-//
-//  return (int(ite - symbols));
+  //  const QwtSymbol::Style*ite = std::find(symbols, symbols + sizeof(symbols),
+  //  style);
+  //  if (ite == symbols + sizeof(symbols))
+  //    return 0;
+  //
+  //  return (int(ite - symbols));
 }
 
-QwtSymbol::Style SymbolBox::style(int index)
-{
+QwtSymbol::Style SymbolBox::style(int index) {
   if (index >= 0 && index < (int)numberOfSymbols())
     return symbols[index];
 
   return QwtSymbol::NoSymbol;
 }
 
-QList<int> SymbolBox::defaultSymbols()
-{
+QList<int> SymbolBox::defaultSymbols() {
   QList<int> lst;
   for (int i = 0; i < QwtSymbol::StyleCnt; i++)
     lst << i;
@@ -212,13 +194,11 @@ QList<int> SymbolBox::defaultSymbols()
   return lst;
 }
 
-void SymbolBox::focusInEvent(QFocusEvent * e)
-{
+void SymbolBox::focusInEvent(QFocusEvent *e) {
   emit activated(this);
   return QComboBox::focusInEvent(e);
 }
 
-size_t SymbolBox::numberOfSymbols()
-{
+size_t SymbolBox::numberOfSymbols() {
   return sizeof(symbols) / sizeof(QwtSymbol::Style);
 }
diff --git a/MantidPlot/src/lib/src/SymbolDialog.cpp b/MantidPlot/src/lib/src/SymbolDialog.cpp
index b1416ef019559e6664d239f8ff807e0cbcd3b506..e36dc440e9caae1db1f943fd0a1de5e14991a9a7 100644
--- a/MantidPlot/src/lib/src/SymbolDialog.cpp
+++ b/MantidPlot/src/lib/src/SymbolDialog.cpp
@@ -2,8 +2,9 @@
     File                 : SymbolDialog.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2004 - 2010 by Ion Vasilief,
-						   (C) 2006 - June 2007 by Tilman Hoener zu Siederdissen
+        Copyright            : (C) 2004 - 2010 by Ion Vasilief,
+                                                   (C) 2006 - June 2007 by
+ Tilman Hoener zu Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Tool window to select special text characters
 
@@ -37,18 +38,17 @@
 #include <QTextCodec>
 #include <QFontDatabase>
 
-SymbolDialog::SymbolDialog(CharSet charSet, QWidget* parent, Qt::WFlags fl )
-: QDialog( parent, fl )
-{
+SymbolDialog::SymbolDialog(CharSet charSet, QWidget *parent, Qt::WFlags fl)
+    : QDialog(parent, fl) {
   setAttribute(Qt::WA_DeleteOnClose);
-  setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
-  setSizeGripEnabled( false );
+  setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+  setSizeGripEnabled(false);
 
   buttons = new QButtonGroup(this);
   mainLayout = new QVBoxLayout(this);
   gridLayout = new QGridLayout();
 
-  switch(charSet){
+  switch (charSet) {
   case lowerGreek:
     initLowerGreekChars();
     break;
@@ -74,455 +74,424 @@ SymbolDialog::SymbolDialog(CharSet charSet, QWidget* parent, Qt::WFlags fl )
 
   closeButton = new QPushButton(tr("&Close"), this);
 
-  mainLayout->addLayout( gridLayout );
+  mainLayout->addLayout(gridLayout);
   mainLayout->addStretch();
-  mainLayout->addWidget( closeButton );
+  mainLayout->addWidget(closeButton);
 
   languageChange();
 
   connect(buttons, SIGNAL(buttonClicked(int)), this, SLOT(getChar(int)));
   connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
   QShortcut *shortcut = new QShortcut(Qt::Key_Return, this);
-  connect( shortcut , SIGNAL(activated()), this, SLOT(addCurrentChar()) );
+  connect(shortcut, SIGNAL(activated()), this, SLOT(addCurrentChar()));
 }
 
-void SymbolDialog::initLowerGreekChars()
-{
+void SymbolDialog::initLowerGreekChars() {
   int counter = 0;
-  for (int i=0 ; i <= (0x3C9-0x3B1) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x3B1)));
+  for (int i = 0; i <= (0x3C9 - 0x3B1); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x3B1)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/5,counter%5);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 5, counter % 5);
   }
 }
 
-void SymbolDialog::initUpperGreekChars()
-{
+void SymbolDialog::initUpperGreekChars() {
   int i, counter = 0;
-  for ( i=0; i <= (0x394-0x393); i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x393)));
+  for (i = 0; i <= (0x394 - 0x393); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x393)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
     buttons->addButton(btn, counter + 1);
-    gridLayout->addWidget(btn, counter/5,counter%5);
+    gridLayout->addWidget(btn, counter / 5, counter % 5);
   }
 
-  for ( i=0; i <= (0x3A0-0x398); i+=3,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x398)));
+  for (i = 0; i <= (0x3A0 - 0x398); i += 3, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x398)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
     buttons->addButton(btn, counter + 1);
-    gridLayout->addWidget(btn, counter/5,counter%5);
+    gridLayout->addWidget(btn, counter / 5, counter % 5);
   }
 
-  for ( i=0; i <= (0x3A6-0x3A0); i+=3,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x3A0)));
+  for (i = 0; i <= (0x3A6 - 0x3A0); i += 3, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x3A0)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
     buttons->addButton(btn, counter + 1);
-    gridLayout->addWidget(btn, counter/5,counter%5);
+    gridLayout->addWidget(btn, counter / 5, counter % 5);
   }
 
-
-  for ( i=0 ; i <= (0x3A9-0x3A8) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x3A8)));
+  for (i = 0; i <= (0x3A9 - 0x3A8); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x3A8)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/5,counter%5);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 5, counter % 5);
   }
 
   numButtons = counter;
 }
 
-void SymbolDialog::initNumberSymbols()
-{
+void SymbolDialog::initNumberSymbols() {
   int i, counter = 0;
-  for ( i=0 ; i <= (0x216B-0x2153) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2153)));
+  for (i = 0; i <= (0x216B - 0x2153); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2153)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x217B-0x2170) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2170)));
+  for (i = 0; i <= (0x217B - 0x2170); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2170)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
   numButtons = counter;
 }
 
-void SymbolDialog::initMathSymbols()
-{
+void SymbolDialog::initMathSymbols() {
   int i, counter = 0;
-  for ( i=0 ; i <= (0x220D-0x2200) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2200)));
+  for (i = 0; i <= (0x220D - 0x2200); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2200)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2211-0x220F) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x220F)));
+  for (i = 0; i <= (0x2211 - 0x220F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x220F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x00B1-0x00B1) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x00B1)));
+  for (i = 0; i <= (0x00B1 - 0x00B1); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x00B1)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2213-0x2213) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2213)));
+  for (i = 0; i <= (0x2213 - 0x2213); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2213)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
   // MULTIPLICATION SIGN
-  for ( i=0; i <= (0x00D7-0x00D7) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x00D7)));
+  for (i = 0; i <= (0x00D7 - 0x00D7); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x00D7)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x221E - 0x2217) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2217)));
+  for (i = 0; i <= (0x221E - 0x2217); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2217)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2222-0x2222) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2222)));
+  for (i = 0; i <= (0x2222 - 0x2222); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2222)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2230-0x2227) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2227)));
+  for (i = 0; i <= (0x2230 - 0x2227); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2227)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x223F-0x223F) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x223F)));
+  for (i = 0; i <= (0x223F - 0x223F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x223F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x2245-0x2245) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2245)));
+  for (i = 0; i <= (0x2245 - 0x2245); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2245)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2248-0x2248) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2248)));
+  for (i = 0; i <= (0x2248 - 0x2248); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2248)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
-  for ( i=0 ; i <= (0x2259-0x2259) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2259)));
+  for (i = 0; i <= (0x2259 - 0x2259); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2259)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x2255-0x2254) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2254)));
+  for (i = 0; i <= (0x2255 - 0x2254); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2254)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x2267-0x225F) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x225F)));
+  for (i = 0; i <= (0x2267 - 0x225F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x225F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
   // < SIGN
-  for ( i=0; i < 1 ; i++,counter++ ){
+  for (i = 0; i < 1; i++, counter++) {
     QPushButton *btn = new QPushButton(QString("<"));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x226B-0x226A) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x226A)));
+  for (i = 0; i <= (0x226B - 0x226A); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x226A)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
-  for ( i=0 ; i <= (0x2289-0x2282) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2282)));
+  for (i = 0; i <= (0x2289 - 0x2282); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2282)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
   // h bar
-  for ( i=0 ; i <= (0x210F-0x210F) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x210F)));
+  for (i = 0; i <= (0x210F - 0x210F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x210F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
 
   // angstrom
-  for ( i=0 ; i <= (0x212B-0x212B) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x212B)));
+  for (i = 0; i <= (0x212B - 0x212B); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x212B)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
   // per mille and per ten thousand (thanks to Knut Franke)
-  for ( i=0; i <= (0x2031-0x2030) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2030)));
+  for (i = 0; i <= (0x2031 - 0x2030); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2030)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/8,counter%8);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 8, counter % 8);
   }
   numButtons = counter;
 }
 
-void SymbolDialog::initLatexMathSymbols()
-{
+void SymbolDialog::initLatexMathSymbols() {
   int i, counter = 0;
-  for ( i=0 ; i <= (0x2200-0x2200) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2200)));
+  for (i = 0; i <= (0x2200 - 0x2200); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2200)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2209-0x2202) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2202)));
+  for (i = 0; i <= (0x2209 - 0x2202); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2202)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x220C-0x220B) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x220B)));
+  for (i = 0; i <= (0x220C - 0x220B); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x220B)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2211-0x220F) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x220F)));
+  for (i = 0; i <= (0x2211 - 0x220F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x220F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x00B1-0x00B1) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x00B1)));
+  for (i = 0; i <= (0x00B1 - 0x00B1); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x00B1)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2213-0x2213) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2213)));
+  for (i = 0; i <= (0x2213 - 0x2213); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2213)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
   // MULTIPLICATION SIGN
-  for ( i=0; i <= (0x00D7-0x00D7) ; i++,counter++ ){
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x00D7)));
+  for (i = 0; i <= (0x00D7 - 0x00D7); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x00D7)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
 
-  for ( i=0 ; i <= (0x221E - 0x2217) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2217)));
+  for (i = 0; i <= (0x221E - 0x2217); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2217)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i < (0x222F-0x2227) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2227)));
+  for (i = 0; i < (0x222F - 0x2227); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2227)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x223F-0x223F) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x223F)));
+  for (i = 0; i <= (0x223F - 0x223F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x223F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2245-0x2245) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2245)));
+  for (i = 0; i <= (0x2245 - 0x2245); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2245)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2248-0x2248) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2248)));
+  for (i = 0; i <= (0x2248 - 0x2248); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2248)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2265-0x2260) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2260)));
+  for (i = 0; i <= (0x2265 - 0x2260); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2260)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x226B-0x226A) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x226A)));
+  for (i = 0; i <= (0x226B - 0x226A); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x226A)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
-  for ( i=0 ; i <= (0x2289-0x2282) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2282)));
+  for (i = 0; i <= (0x2289 - 0x2282); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2282)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
 
   // h bar
-  for ( i=0 ; i <= (0x210F-0x210F) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x210F)));
+  for (i = 0; i <= (0x210F - 0x210F); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x210F)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
 
   // angstrom
-  for ( i=0 ; i <= (0x212B-0x212B) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x212B)));
+  for (i = 0; i <= (0x212B - 0x212B); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x212B)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/7,counter%7);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 7, counter % 7);
   }
   numButtons = counter;
 
   QFont font = this->font();
   QStringList families = QFontDatabase().families();
-  foreach(QString f, families){
-    if (f.contains("Unicode")){
+  foreach (QString f, families) {
+    if (f.contains("Unicode")) {
       font.setFamily(f);
 
-      for(int i = 0; i < numButtons; i++){
+      for (int i = 0; i < numButtons; i++) {
         QWidget *w = gridLayout->itemAt(i)->widget();
         if (w)
           w->setFont(font);
@@ -532,163 +501,145 @@ void SymbolDialog::initLatexMathSymbols()
   }
 }
 
-void SymbolDialog::initArrowSymbols()
-{
+void SymbolDialog::initArrowSymbols() {
   int i, counter = 0;
-  for ( i=0 ; i <= (0x219B-0x2190) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2190)));
-    btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
-  }
-  for ( i=0 ; i <= (0x21A7-0x21A4) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21A4)));
-    btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
-  }
-  for ( i=0 ; i <= (0x21D5-0x21CD) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21CD)));
-    btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
-  }
-  for ( i=0 ; i <= (0x21E9-0x21E6) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21E6)));
-    btn->setMaximumWidth(40);
-    btn->setFlat ( true );
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+  for (i = 0; i <= (0x219B - 0x2190); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2190)));
+    btn->setMaximumWidth(40);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
+  }
+  for (i = 0; i <= (0x21A7 - 0x21A4); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21A4)));
+    btn->setMaximumWidth(40);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
+  }
+  for (i = 0; i <= (0x21D5 - 0x21CD); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21CD)));
+    btn->setMaximumWidth(40);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
+  }
+  for (i = 0; i <= (0x21E9 - 0x21E6); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21E6)));
+    btn->setMaximumWidth(40);
+    btn->setFlat(true);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
   numButtons = counter;
 }
 
-void SymbolDialog::initLatexArrowSymbols()
-{
+void SymbolDialog::initLatexArrowSymbols() {
   QFont font = this->font();
   QStringList families = QFontDatabase().families();
-  foreach(QString f, families){
-    if (f.contains("Unicode")){
+  foreach (QString f, families) {
+    if (f.contains("Unicode")) {
       font.setFamily(f);
       break;
     }
   }
 
   int i, counter = 0;
-  for ( i=0 ; i <= (0x2199-0x2190) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x2190)));
+  for (i = 0; i <= (0x2199 - 0x2190); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x2190)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
+    btn->setFlat(true);
     btn->setFont(font);
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
 
-  for ( i=0 ; i <= (0x21AA-0x21A9) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21A9)));
+  for (i = 0; i <= (0x21AA - 0x21A9); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21A9)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
+    btn->setFlat(true);
     btn->setFont(font);
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
 
-  for ( i=0 ; i <= (0x21D5-0x21D0) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21D0)));
+  for (i = 0; i <= (0x21D5 - 0x21D0); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21D0)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
+    btn->setFlat(true);
     btn->setFont(font);
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
 
-  for ( i=0 ; i <= (0x21BD-0x21BC) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21BC)));
+  for (i = 0; i <= (0x21BD - 0x21BC); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21BC)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
+    btn->setFlat(true);
     btn->setFont(font);
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
 
-  for ( i=0 ; i <= (0x21C1-0x21C0) ; i++,counter++ )
-  {
-    QPushButton *btn = new QPushButton(QString(QChar(i+0x21C0)));
+  for (i = 0; i <= (0x21C1 - 0x21C0); i++, counter++) {
+    QPushButton *btn = new QPushButton(QString(QChar(i + 0x21C0)));
     btn->setMaximumWidth(40);
-    btn->setFlat ( true );
+    btn->setFlat(true);
     btn->setFont(font);
-    btn->setAutoDefault (false);
-    buttons->addButton(btn,counter+1);
-    gridLayout->addWidget(btn,counter/6,counter%6);
+    btn->setAutoDefault(false);
+    buttons->addButton(btn, counter + 1);
+    gridLayout->addWidget(btn, counter / 6, counter % 6);
   }
 
   QPushButton *btn = new QPushButton(QString(QChar(0x21CC)));
   btn->setMaximumWidth(40);
-  btn->setFlat ( true );
+  btn->setFlat(true);
   btn->setFont(font);
-  btn->setAutoDefault (false);
-  buttons->addButton(btn,counter+1);
-  gridLayout->addWidget(btn,counter/6,counter%6);
+  btn->setAutoDefault(false);
+  buttons->addButton(btn, counter + 1);
+  gridLayout->addWidget(btn, counter / 6, counter % 6);
 
   counter++;
 
   btn = new QPushButton(QString(QChar(0x21A6)));
   btn->setMaximumWidth(40);
-  btn->setFlat ( true );
+  btn->setFlat(true);
   btn->setFont(font);
-  btn->setAutoDefault (false);
-  buttons->addButton(btn,counter+1);
-  gridLayout->addWidget(btn,counter/6,counter%6);
+  btn->setAutoDefault(false);
+  buttons->addButton(btn, counter + 1);
+  gridLayout->addWidget(btn, counter / 6, counter % 6);
 
   numButtons = counter;
 }
 
-void SymbolDialog::addCurrentChar()
-{
-  for (int i=1; i < numButtons; i++)
-  {
-    QPushButton *btn = (QPushButton *) buttons->button(i);
+void SymbolDialog::addCurrentChar() {
+  for (int i = 1; i < numButtons; i++) {
+    QPushButton *btn = (QPushButton *)buttons->button(i);
     if (btn && btn->hasFocus())
       emit addLetter(btn->text());
   }
 }
 
-void SymbolDialog::getChar(int btnIndex)
-{
-  QPushButton * btn = (QPushButton *)buttons->button( btnIndex );
-  if(btn)
+void SymbolDialog::getChar(int btnIndex) {
+  QPushButton *btn = (QPushButton *)buttons->button(btnIndex);
+  if (btn)
     emit addLetter(btn->text().replace("<", "&lt;"));
 }
 
-
-void SymbolDialog::languageChange()
-{
-  setWindowTitle( tr( "MantidPlot - Choose Symbol" ) );
+void SymbolDialog::languageChange() {
+  setWindowTitle(tr("MantidPlot - Choose Symbol"));
 }
 
-
-void SymbolDialog::focusInEvent( QFocusEvent * event )
-{
+void SymbolDialog::focusInEvent(QFocusEvent *event) {
   Q_UNUSED(event)
-	    // select the first button as default (in case [return] is pressed)
-	    ((QPushButton *)buttons->button(1))->setFocus(Qt::TabFocusReason);
+  // select the first button as default (in case [return] is pressed)
+  ((QPushButton *)buttons->button(1))->setFocus(Qt::TabFocusReason);
 }
diff --git a/MantidPlot/src/lib/src/TextFormatButtons.cpp b/MantidPlot/src/lib/src/TextFormatButtons.cpp
index 5a9147fbe0dde24b196b927467316b19ebcb14a0..7d30de050c668fc5785654345b63d82cf41bd837 100644
--- a/MantidPlot/src/lib/src/TextFormatButtons.cpp
+++ b/MantidPlot/src/lib/src/TextFormatButtons.cpp
@@ -2,9 +2,11 @@
     File                 : TextFormatButtons.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
-    Description          : Widget with text format buttons (connected to a QTextEdit)
+    Description          : Widget with text format buttons (connected to a
+ QTextEdit)
 
  ***************************************************************************/
 
@@ -34,23 +36,20 @@
 #include <QHBoxLayout>
 #include <QString>
 
-TextFormatButtons::TextFormatButtons(QTextEdit * textEdit, Buttons buttons, QWidget * parent)
-: QWidget(parent),
-  connectedTextEdit(textEdit),
-  d_buttons(buttons)
-{
-  QHBoxLayout * layout = new QHBoxLayout(this);
+TextFormatButtons::TextFormatButtons(QTextEdit *textEdit, Buttons buttons,
+                                     QWidget *parent)
+    : QWidget(parent), connectedTextEdit(textEdit), d_buttons(buttons) {
+  QHBoxLayout *layout = new QHBoxLayout(this);
   layout->setMargin(0);
   layout->setSpacing(0);
 
   init(buttons);
 }
 
-void TextFormatButtons::init(Buttons buttons)
-{
-  QHBoxLayout *layout = (QHBoxLayout*)this->layout();
+void TextFormatButtons::init(Buttons buttons) {
+  QHBoxLayout *layout = (QHBoxLayout *)this->layout();
   QLayoutItem *child;
-  while ((child = layout->takeAt(0)) != 0){
+  while ((child = layout->takeAt(0)) != 0) {
     if (child->widget())
       delete child->widget();
   }
@@ -61,48 +60,57 @@ void TextFormatButtons::init(Buttons buttons)
 #else
   int btnSize = 32;
 #endif
-  if (buttons == Legend || buttons == TexLegend){
-    QPushButton *buttonCurve = new QPushButton( QPixmap(":/lineSymbol.png"), QString());
+  if (buttons == Legend || buttons == TexLegend) {
+    QPushButton *buttonCurve =
+        new QPushButton(QPixmap(":/lineSymbol.png"), QString());
     buttonCurve->setFixedWidth(btnSize);
     buttonCurve->setFixedHeight(btnSize);
     buttonCurve->setFont(font);
     layout->addWidget(buttonCurve);
-    connect( buttonCurve, SIGNAL(clicked()), this, SLOT(addCurve()) );
-    connect( buttonCurve, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonCurve, SIGNAL(clicked()), this, SLOT(addCurve()));
+    connect(buttonCurve, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
   }
 
-  QPushButton *buttonSubscript = new QPushButton(QPixmap(":/index.png"), QString());
+  QPushButton *buttonSubscript =
+      new QPushButton(QPixmap(":/index.png"), QString());
   buttonSubscript->setFixedWidth(btnSize);
   buttonSubscript->setFixedHeight(btnSize);
   buttonSubscript->setFont(font);
   layout->addWidget(buttonSubscript);
-  connect( buttonSubscript, SIGNAL(clicked()), this, SLOT(addSubscript()) );
-  connect( buttonSubscript, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonSubscript, SIGNAL(clicked()), this, SLOT(addSubscript()));
+  connect(buttonSubscript, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
-  QPushButton *buttonSuperscript = new QPushButton(QPixmap(":/exp.png"), QString());
+  QPushButton *buttonSuperscript =
+      new QPushButton(QPixmap(":/exp.png"), QString());
   buttonSuperscript->setFixedWidth(btnSize);
   buttonSuperscript->setFixedHeight(btnSize);
   buttonSuperscript->setFont(font);
   layout->addWidget(buttonSuperscript);
-  connect( buttonSuperscript, SIGNAL(clicked()), this, SLOT(addSuperscript()));
-  connect( buttonSuperscript, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonSuperscript, SIGNAL(clicked()), this, SLOT(addSuperscript()));
+  connect(buttonSuperscript, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
-  if (buttons == Equation || buttons == TexLegend){
-    QPushButton *buttonFraction = new QPushButton(QPixmap(":/fraction.png"), QString());
+  if (buttons == Equation || buttons == TexLegend) {
+    QPushButton *buttonFraction =
+        new QPushButton(QPixmap(":/fraction.png"), QString());
     buttonFraction->setFixedWidth(btnSize);
     buttonFraction->setFixedHeight(btnSize);
     buttonFraction->setFont(font);
     layout->addWidget(buttonFraction);
     connect(buttonFraction, SIGNAL(clicked()), this, SLOT(addFraction()));
-    connect(buttonFraction, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonFraction, SIGNAL(clicked()), this,
+            SIGNAL(formattingModified()));
 
-    QPushButton *buttonSquareRoot = new QPushButton(QPixmap(":/square_root.png"), QString());
+    QPushButton *buttonSquareRoot =
+        new QPushButton(QPixmap(":/square_root.png"), QString());
     buttonSquareRoot->setFixedWidth(btnSize);
     buttonSquareRoot->setFixedHeight(btnSize);
     buttonSquareRoot->setFont(font);
     layout->addWidget(buttonSquareRoot);
     connect(buttonSquareRoot, SIGNAL(clicked()), this, SLOT(addSquareRoot()));
-    connect(buttonSquareRoot, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonSquareRoot, SIGNAL(clicked()), this,
+            SIGNAL(formattingModified()));
   }
 
   QPushButton *buttonLowerGreek = new QPushButton(QString(QChar(0x3B1)));
@@ -110,135 +118,149 @@ void TextFormatButtons::init(Buttons buttons)
   buttonLowerGreek->setFixedWidth(btnSize);
   buttonLowerGreek->setFixedHeight(btnSize);
   layout->addWidget(buttonLowerGreek);
-  connect( buttonLowerGreek, SIGNAL(clicked()), this, SLOT(showLowerGreek()));
-  connect( buttonLowerGreek, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonLowerGreek, SIGNAL(clicked()), this, SLOT(showLowerGreek()));
+  connect(buttonLowerGreek, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
   QPushButton *buttonUpperGreek = new QPushButton(QString(QChar(0x393)));
   buttonUpperGreek->setFont(font);
   buttonUpperGreek->setFixedWidth(btnSize);
   buttonUpperGreek->setFixedHeight(btnSize);
   layout->addWidget(buttonUpperGreek);
-  connect( buttonUpperGreek, SIGNAL(clicked()), this, SLOT(showUpperGreek()));
-  connect( buttonUpperGreek, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonUpperGreek, SIGNAL(clicked()), this, SLOT(showUpperGreek()));
+  connect(buttonUpperGreek, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
   QPushButton *buttonArrowSymbols = new QPushButton(QString(QChar(0x2192)));
   buttonArrowSymbols->setFont(font);
   buttonArrowSymbols->setFixedWidth(btnSize);
   buttonArrowSymbols->setFixedHeight(btnSize);
   layout->addWidget(buttonArrowSymbols);
-  connect( buttonArrowSymbols, SIGNAL(clicked()), this, SLOT(showArrowSymbols()));
-  connect( buttonArrowSymbols, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonArrowSymbols, SIGNAL(clicked()), this,
+          SLOT(showArrowSymbols()));
+  connect(buttonArrowSymbols, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
   QPushButton *buttonMathSymbols = new QPushButton(QString(QChar(0x222B)));
   buttonMathSymbols->setFont(font);
   buttonMathSymbols->setFixedWidth(btnSize);
   buttonMathSymbols->setFixedHeight(btnSize);
   layout->addWidget(buttonMathSymbols);
-  connect( buttonMathSymbols, SIGNAL(clicked()), this, SLOT(showMathSymbols()));
-  connect( buttonMathSymbols, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+  connect(buttonMathSymbols, SIGNAL(clicked()), this, SLOT(showMathSymbols()));
+  connect(buttonMathSymbols, SIGNAL(clicked()), this,
+          SIGNAL(formattingModified()));
 
-  if (buttons != Plot3D && buttons != Equation && buttons != TexLegend){
+  if (buttons != Plot3D && buttons != Equation && buttons != TexLegend) {
     font = this->font();
     font.setBold(true);
 
-    QPushButton *buttonBold = new QPushButton(tr("B","Button bold"));
+    QPushButton *buttonBold = new QPushButton(tr("B", "Button bold"));
     buttonBold->setFont(font);
     buttonBold->setFixedWidth(btnSize);
     buttonBold->setFixedHeight(btnSize);
     layout->addWidget(buttonBold);
-    connect( buttonBold, SIGNAL(clicked()), this, SLOT(addBold()));
-    connect( buttonBold, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonBold, SIGNAL(clicked()), this, SLOT(addBold()));
+    connect(buttonBold, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
 
     font = this->font();
     font.setItalic(true);
 
-    QPushButton *buttonItalics = new QPushButton(tr("It","Button italics"));
+    QPushButton *buttonItalics = new QPushButton(tr("It", "Button italics"));
     buttonItalics->setFont(font);
     buttonItalics->setFixedWidth(btnSize);
     buttonItalics->setFixedHeight(btnSize);
     layout->addWidget(buttonItalics);
-    connect( buttonItalics, SIGNAL(clicked()), this, SLOT(addItalics()));
-    connect( buttonItalics, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonItalics, SIGNAL(clicked()), this, SLOT(addItalics()));
+    connect(buttonItalics, SIGNAL(clicked()), this,
+            SIGNAL(formattingModified()));
 
     font = this->font();
     font.setUnderline(true);
 
-    QPushButton *buttonUnderline = new QPushButton(tr("U","Button underline"));
+    QPushButton *buttonUnderline = new QPushButton(tr("U", "Button underline"));
     buttonUnderline->setFont(font);
     buttonUnderline->setFixedWidth(btnSize);
     buttonUnderline->setFixedHeight(btnSize);
     layout->addWidget(buttonUnderline);
     layout->addStretch();
-    connect( buttonUnderline, SIGNAL(clicked()), this, SLOT(addUnderline()));
-    connect( buttonUnderline, SIGNAL(clicked()), this, SIGNAL(formattingModified()));
+    connect(buttonUnderline, SIGNAL(clicked()), this, SLOT(addUnderline()));
+    connect(buttonUnderline, SIGNAL(clicked()), this,
+            SIGNAL(formattingModified()));
   } else
     layout->addStretch();
 }
 
-void TextFormatButtons::showLowerGreek()
-{
-  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::lowerGreek, this, Qt::Tool|Qt::WindowStaysOnTopHint);
+void TextFormatButtons::showLowerGreek() {
+  SymbolDialog *greekLetters = new SymbolDialog(
+      SymbolDialog::lowerGreek, this, Qt::Tool | Qt::WindowStaysOnTopHint);
   greekLetters->setAttribute(Qt::WA_DeleteOnClose);
   QFont f = connectedTextEdit->font();
   f.setPointSize(12);
   greekLetters->setFont(f);
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), this, SLOT(addSymbol(const QString&)));
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), this, SIGNAL(formattingModified()));
+  connect(greekLetters, SIGNAL(addLetter(const QString &)), this,
+          SLOT(addSymbol(const QString &)));
+  connect(greekLetters, SIGNAL(addLetter(const QString &)), this,
+          SIGNAL(formattingModified()));
   greekLetters->show();
   greekLetters->setFocus();
 }
 
-void TextFormatButtons::showUpperGreek()
-{
-  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::upperGreek, this, Qt::Tool|Qt::WindowStaysOnTopHint);
+void TextFormatButtons::showUpperGreek() {
+  SymbolDialog *greekLetters = new SymbolDialog(
+      SymbolDialog::upperGreek, this, Qt::Tool | Qt::WindowStaysOnTopHint);
   greekLetters->setAttribute(Qt::WA_DeleteOnClose);
   QFont f = connectedTextEdit->font();
   f.setPointSize(12);
   greekLetters->setFont(f);
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), this, SLOT(addSymbol(const QString&)));
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), this, SIGNAL(formattingModified()));
+  connect(greekLetters, SIGNAL(addLetter(const QString &)), this,
+          SLOT(addSymbol(const QString &)));
+  connect(greekLetters, SIGNAL(addLetter(const QString &)), this,
+          SIGNAL(formattingModified()));
   greekLetters->show();
   greekLetters->setFocus();
 }
 
-void TextFormatButtons::showMathSymbols()
-{
+void TextFormatButtons::showMathSymbols() {
   SymbolDialog::CharSet charSet = SymbolDialog::mathSymbols;
   if (d_buttons == Equation || d_buttons == TexLegend)
     charSet = SymbolDialog::latexMathSymbols;
 
-  SymbolDialog *mathSymbols = new SymbolDialog(charSet, this, Qt::Tool|Qt::WindowStaysOnTopHint);
+  SymbolDialog *mathSymbols =
+      new SymbolDialog(charSet, this, Qt::Tool | Qt::WindowStaysOnTopHint);
   mathSymbols->setAttribute(Qt::WA_DeleteOnClose);
   QFont f = connectedTextEdit->font();
   f.setPointSize(12);
   mathSymbols->setFont(f);
-  connect(mathSymbols, SIGNAL(addLetter(const QString&)), this, SLOT(addSymbol(const QString&)));
-  connect(mathSymbols, SIGNAL(addLetter(const QString&)), this, SIGNAL(formattingModified()));
+  connect(mathSymbols, SIGNAL(addLetter(const QString &)), this,
+          SLOT(addSymbol(const QString &)));
+  connect(mathSymbols, SIGNAL(addLetter(const QString &)), this,
+          SIGNAL(formattingModified()));
   mathSymbols->show();
   mathSymbols->setFocus();
 }
 
-void TextFormatButtons::showArrowSymbols()
-{
+void TextFormatButtons::showArrowSymbols() {
   SymbolDialog::CharSet charSet = SymbolDialog::arrowSymbols;
   if (d_buttons == Equation || d_buttons == TexLegend)
     charSet = SymbolDialog::latexArrowSymbols;
 
-  SymbolDialog *arrowSymbols = new SymbolDialog(charSet, this, Qt::Tool|Qt::WindowStaysOnTopHint);
+  SymbolDialog *arrowSymbols =
+      new SymbolDialog(charSet, this, Qt::Tool | Qt::WindowStaysOnTopHint);
   arrowSymbols->setAttribute(Qt::WA_DeleteOnClose);
   arrowSymbols->setFont(connectedTextEdit->font());
   QFont f = connectedTextEdit->font();
   f.setPointSize(12);
   arrowSymbols->setFont(f);
-  connect(arrowSymbols, SIGNAL(addLetter(const QString&)), this, SLOT(addSymbol(const QString&)));
-  connect(arrowSymbols, SIGNAL(addLetter(const QString&)), this, SIGNAL(formattingModified()));
+  connect(arrowSymbols, SIGNAL(addLetter(const QString &)), this,
+          SLOT(addSymbol(const QString &)));
+  connect(arrowSymbols, SIGNAL(addLetter(const QString &)), this,
+          SIGNAL(formattingModified()));
   arrowSymbols->show();
   arrowSymbols->setFocus();
 }
 
-void TextFormatButtons::addSymbol(const QString & letter)
-{
-  if (d_buttons == Equation || d_buttons == TexLegend){
+void TextFormatButtons::addSymbol(const QString &letter) {
+  if (d_buttons == Equation || d_buttons == TexLegend) {
     int s = 0x3B1;
     if (letter == QString(QChar(s)))
       connectedTextEdit->textCursor().insertText("\\alpha");
@@ -437,7 +459,8 @@ void TextFormatButtons::addSymbol(const QString & letter)
     else if (letter == QString(QChar(5 + s)))
       connectedTextEdit->textCursor().insertText("\\int \\!\\!\\! \\int");
     else if (letter == QString(QChar(6 + s)))
-      connectedTextEdit->textCursor().insertText("\\int \\!\\!\\! \\int \\!\\!\\! \\int");
+      connectedTextEdit->textCursor().insertText(
+          "\\int \\!\\!\\! \\int \\!\\!\\! \\int");
     else if (letter == QString(QChar(7 + s)))
       connectedTextEdit->textCursor().insertText("\\oint");
 
@@ -494,64 +517,48 @@ void TextFormatButtons::addSymbol(const QString & letter)
     connectedTextEdit->textCursor().insertText(letter);
 }
 
-void TextFormatButtons::addCurve()
-{
-  formatText("\\l(",")");
-}
+void TextFormatButtons::addCurve() { formatText("\\l(", ")"); }
 
-void TextFormatButtons::addUnderline()
-{
-  formatText("<u>","</u>");
-}
+void TextFormatButtons::addUnderline() { formatText("<u>", "</u>"); }
 
-void TextFormatButtons::addItalics()
-{
-  formatText("<i>","</i>");
-}
+void TextFormatButtons::addItalics() { formatText("<i>", "</i>"); }
 
-void TextFormatButtons::addBold()
-{
-  formatText("<b>","</b>");
-}
+void TextFormatButtons::addBold() { formatText("<b>", "</b>"); }
 
-void TextFormatButtons::addSubscript()
-{
+void TextFormatButtons::addSubscript() {
   if (d_buttons == TexLegend || d_buttons == Equation || d_buttons == Plot3D)
-    formatText("_{","}");
+    formatText("_{", "}");
   else
-    formatText("<sub>","</sub>");
+    formatText("<sub>", "</sub>");
 }
 
-void TextFormatButtons::addSuperscript()
-{
-  if (d_buttons == TexLegend || d_buttons == Equation  || d_buttons == Plot3D)
-    formatText("^{","}");
+void TextFormatButtons::addSuperscript() {
+  if (d_buttons == TexLegend || d_buttons == Equation || d_buttons == Plot3D)
+    formatText("^{", "}");
   else
-    formatText("<sup>","</sup>");
+    formatText("<sup>", "</sup>");
 }
 
-void TextFormatButtons::addFraction()
-{
+void TextFormatButtons::addFraction() {
   if (d_buttons == TexLegend || d_buttons == Equation)
-    formatText("\\frac{","}{}");
+    formatText("\\frac{", "}{}");
 }
 
-void TextFormatButtons::addSquareRoot()
-{
+void TextFormatButtons::addSquareRoot() {
   if (d_buttons == TexLegend || d_buttons == Equation)
-    formatText("\\sqrt{","}");
+    formatText("\\sqrt{", "}");
 }
 
-void TextFormatButtons::formatText(const QString & prefix, const QString & postfix)
-{
+void TextFormatButtons::formatText(const QString &prefix,
+                                   const QString &postfix) {
   QTextCursor cursor = connectedTextEdit->textCursor();
   QString markedText = cursor.selectedText();
-  cursor.insertText(prefix+markedText+postfix);
-  if(markedText.isEmpty())
-  {
+  cursor.insertText(prefix + markedText + postfix);
+  if (markedText.isEmpty()) {
     // if no text is marked, place cursor inside the <..></..> statement
     // instead of after it
-    cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::MoveAnchor,postfix.size());
+    cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor,
+                        postfix.size());
     // the next line makes the selection visible to the user
     // (the line above only changes the selection in the
     // underlying QTextDocument)
@@ -561,8 +568,7 @@ void TextFormatButtons::formatText(const QString & prefix, const QString & postf
   connectedTextEdit->setFocus();
 }
 
-void TextFormatButtons::setButtons(Buttons btns)
-{
+void TextFormatButtons::setButtons(Buttons btns) {
   if (btns == d_buttons)
     return;
 
diff --git a/MantidPlot/src/main.cpp b/MantidPlot/src/main.cpp
index b6da397d3e924194f1d8e75b17e458e51e3928ac..47c9c3cff6b7a6556899738ac7fc5e6ec028c440 100644
--- a/MantidPlot/src/main.cpp
+++ b/MantidPlot/src/main.cpp
@@ -2,7 +2,8 @@
     File                 : main.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : QtiPlot main function
 
@@ -43,7 +44,8 @@
 #include "Mantid/MantidApplication.h"
 
 // The following stuff is for the doxygen title page
-/**  \mainpage QtiPlot - Data analysis and scientific plotting - API documentation
+/**  \mainpage QtiPlot - Data analysis and scientific plotting - API
+documentation
 
   \section description Program description:
 Scientists often need to use data analysis and plotting software.
@@ -52,13 +54,17 @@ called <a href="http://www.originlab.com">Origin</a>, which is not
 free, of course. The purpose of this project is to develop
 a free (open source), platform independent alternative to
 Origin. QtiPlot is still far from this goal, but
-there's a <a class="el" href="http://soft.proindependent.com/wishtolist.html">"wish to"</a> list we are constantly working on.
+there's a <a class="el"
+href="http://soft.proindependent.com/wishtolist.html">"wish to"</a> list we are
+constantly working on.
 All suggestions and contributions are most welcome!
-If you want to contribute code, please read the notes on \ref style "coding style" first.
+If you want to contribute code, please read the notes on \ref style "coding
+style" first.
 <br>
 
  The QtiPlot web page can be found at<br>
- <a href="http://soft.proindependent.com/qtiplot.html">http://soft.proindependent.com/qtiplot.html</a><br>
+ <a
+href="http://soft.proindependent.com/qtiplot.html">http://soft.proindependent.com/qtiplot.html</a><br>
 
   \section libs QtiPlot uses the following libraries:
   <a href="http://www.trolltech.com/products/qt/index.html">Qt</a>,
@@ -77,8 +83,10 @@ If you want to contribute code, please read the notes on \ref style "coding styl
     types without modifying existing classes (think of plug-ins here).
   - Unify naming of some methods and variables with class names.
   - Add generic plug-in support, support for implementing extensions in
-    Python, a full-featured multi-level undo/redo framework (-&gt; visitor pattern).
-	 [ undo/redo assigned to thzs; plug-in/Python extension support assigned to knut ]
+    Python, a full-featured multi-level undo/redo framework (-&gt; visitor
+pattern).
+         [ undo/redo assigned to thzs; plug-in/Python extension support assigned
+to knut ]
   - Revise some internal APIs that use undocumented protocols for the
     strings that get passed around. Wherever possible, consistency should be
     checked at compile-time. This would also probably eliminate the need to
@@ -86,8 +94,9 @@ If you want to contribute code, please read the notes on \ref style "coding styl
   - Switch file format to a completely XML-based one so we can write a
     more robust parser based on Qt's XML support. Legacy support for the old
     format could be a plug-in.
-	 See whether we can make use of the XML save/restore interface planned for Qwt.
-	 Wait for the new XML reader in Qt 4.3 or use SAX?
+         See whether we can make use of the XML save/restore interface planned
+for Qwt.
+         Wait for the new XML reader in Qt 4.3 or use SAX?
   - Document as much as possible using doxygen and write simple demo
     plug-ins.
   - Modularize the build process so that Python support could use SIP's
@@ -95,143 +104,165 @@ If you want to contribute code, please read the notes on \ref style "coding styl
     liborigin and zlib could also be split out into plug-ins on the basis
     that you shouldn't have to install libraries you don't use. Also reduces
     compile times during bugfixing.
-	 [ assigned to knut ]
-  - Change some internal APIs that depend on the notion of a selected/current item.
-    This will lead to a cleaner and simpler interface for plug-ins and Python scripts.
+         [ assigned to knut ]
+  - Change some internal APIs that depend on the notion of a selected/current
+item.
+    This will lead to a cleaner and simpler interface for plug-ins and Python
+scripts.
   .
 
   %Note about modularization: this is mainly about internal reorganizations.
-  Most of the current features should remain part of the main executable, but use interfaces similar or
-  identical to those used by plug-ins. This should ease maintanance and make adding new features
+  Most of the current features should remain part of the main executable, but
+use interfaces similar or
+  identical to those used by plug-ins. This should ease maintanance and make
+adding new features
   to the core application a no-brainer once they're available as plug-ins.
-  Support for Python, liborigin and zlib could be real, external plug-ins since many people probably
-  don't need them, but this can be decided shortly before distribution and ideally by
+  Support for Python, liborigin and zlib could be real, external plug-ins since
+many people probably
+  don't need them, but this can be decided shortly before distribution and
+ideally by
   modifying just a few lines in a build script.
 
   \section features Features
   - Waterfall plots
   - Polar charts
   - Ternary plots
-  - Improved data analysis: base-line detection tool, more built-in fit functions...
+  - Improved data analysis: base-line detection tool, more built-in fit
+functions...
   - Improved import of Origin project files
   - More import/export filters including Open Document spreadsheets (plugin)
 
-  \sa ApplicationWindow, MultiLayer, Graph, Graph3D, ImageMarker, Legend, MyWidget, SelectionMoveResizer, MyParser, Note, ScriptEdit, Table
+  \sa ApplicationWindow, MultiLayer, Graph, Graph3D, ImageMarker, Legend,
+MyWidget, SelectionMoveResizer, MyParser, Note, ScriptEdit, Table
 
   \page style Coding Style
-  The following rules are not used everywhere (yet), but are intended as guidelines for new code and eventually
+  The following rules are not used everywhere (yet), but are intended as
+guidelines for new code and eventually
   old code should be adapted as well.
 
   - Files use Unix-style line endings ("\n").
-  - Class names start with a capital letter, object/variable names with a lower case letter.
-  - Methods and functions are named likeThis(), variables like_this and instance variables are prefixed with "d_".
+  - Class names start with a capital letter, object/variable names with a lower
+case letter.
+  - Methods and functions are named likeThis(), variables like_this and instance
+variables are prefixed with "d_".
   - Property access methods use Qt style: property() and setProperty().
-  - Every file should be named exactly like the class inside and there should be only one class per file, with the exception of
+  - Every file should be named exactly like the class inside and there should be
+only one class per file, with the exception of
     really short classes like LayerButton.
-  - For indentations, tabs are preferred because they allow everyone to choose the indentation depth for him/herself.
+  - For indentations, tabs are preferred because they allow everyone to choose
+the indentation depth for him/herself.
 */
 
 #if defined(_MSC_VER)
-// MantidPlot embeds a Python interpreter which depends on MSVCRT90.dll. Extension modules
-// can also depend on the same runtime but it exists in the SxS system folder. Even though
-// Python27.dll loads the runtime correctly there is an issue that extension modules
-// using ctypes.cdll.LoadLibrary don't consult the SxS registry and fail to load the correct
+// MantidPlot embeds a Python interpreter which depends on MSVCRT90.dll.
+// Extension modules
+// can also depend on the same runtime but it exists in the SxS system folder.
+// Even though
+// Python27.dll loads the runtime correctly there is an issue that extension
+// modules
+// using ctypes.cdll.LoadLibrary don't consult the SxS registry and fail to load
+// the correct
 // runtime library. See for example zmq.
 // For more information see https://bugs.python.org/issue24429
-#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='amd64' publicKeyToken='1fc8b3b9a1e18e3b'\"")
+#pragma comment(                                                               \
+    linker,                                                                    \
+    "\"/manifestdependency:type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='amd64' publicKeyToken='1fc8b3b9a1e18e3b'\"")
 #endif
 
-
-int main( int argc, char ** argv )
-{
-  // First, look for command-line arguments that we want to deal with before launching anything
-   if ( argc == 2 )
-  {
+int main(int argc, char **argv) {
+  // First, look for command-line arguments that we want to deal with before
+  // launching anything
+  if (argc == 2) {
     QString str(argv[1]);
-    if ( str == "-v" || str == "--version" )
-    {
-      std::cout << Mantid::Kernel::MantidVersion::version() << " (" << 
-                   Mantid::Kernel::MantidVersion::releaseDate() << ")" << std::endl;
+    if (str == "-v" || str == "--version") {
+      std::cout << Mantid::Kernel::MantidVersion::version() << " ("
+                << Mantid::Kernel::MantidVersion::releaseDate() << ")"
+                << std::endl;
       exit(0);
-    }
-    else if ( str == "-r" || str == "--revision") // Print abbreviated git SHA-1
+    } else if (str == "-r" ||
+               str == "--revision") // Print abbreviated git SHA-1
     {
       QString revision(Mantid::Kernel::MantidVersion::revision());
       std::cout << revision.toStdString() << std::endl;
       exit(0);
-    }
-    else if ( str == "-a" || str == "--about" ) 
-    {
-      MantidApplication app( argc, argv );  // Needed to avoid an error
+    } else if (str == "-a" || str == "--about") {
+      MantidApplication app(argc, argv); // Needed to avoid an error
       ApplicationWindow::about();
       exit(0);
-    }
-    else if ( str == "-h" || str == "--help")
-    {
+    } else if (str == "-h" || str == "--help") {
       QString s = "\nUsage: ";
       s += "MantidPlot [options] [filename]\n\n";
       s += "Valid options are:\n";
       s += "-a or --about: show about dialog and exit\n";
-      s += "-d or --default-settings: start MantidPlot with the default settings\n";
+      s += "-d or --default-settings: start MantidPlot with the default "
+           "settings\n";
       s += "-h or --help: show command line options\n";
       s += "-v or --version: print MantidPlot version and release date\n";
       s += "-r or --revision: print MantidPlot version and release date\n";
       s += "-s or --silent: start mantidplot without any setup dialogs\n";
       s += "-x or --execute: execute the script file given as argument\n";
-      s += "-xq or --executeandquit: execute the script file given as argument and then exit MantidPlot\n\n";
-      s += "'filename' can be any of .qti, qti.gz, .opj, .ogm, .ogw, .ogg, .py or ASCII file\n\n";
+      s += "-xq or --executeandquit: execute the script file given as argument "
+           "and then exit MantidPlot\n\n";
+      s += "'filename' can be any of .qti, qti.gz, .opj, .ogm, .ogw, .ogg, .py "
+           "or ASCII file\n\n";
       std::wcout << s.toStdWString();
 
       exit(0);
     }
-
   }
 
-  MantidApplication app( argc, argv );
+  MantidApplication app(argc, argv);
 
   QStringList args = app.arguments();
   args.removeFirst(); // remove application name
 
-  try
-  {
+  try {
     // Splash
     QPixmap pixmap;
-    if (!pixmap.load(":/MantidSplashScreen.png")) std::cerr << "Couldn't load splashscreen\n";
+    if (!pixmap.load(":/MantidSplashScreen.png"))
+      std::cerr << "Couldn't load splashscreen\n";
     QSplashScreen splash(pixmap);
     const QString releaseDateTime(Mantid::Kernel::MantidVersion::releaseDate());
     const QString versionInfo(Mantid::Kernel::MantidVersion::version());
-    splash.showMessage("Release: " + releaseDateTime + " (Version " + versionInfo + ")", Qt::AlignLeft | Qt::AlignBottom);
+    splash.showMessage("Release: " + releaseDateTime + " (Version " +
+                           versionInfo + ")",
+                       Qt::AlignLeft | Qt::AlignBottom);
     splash.setMask(pixmap.createMaskFromColor(QColor(Qt::transparent)));
     splash.show();
-    // If we take too long to get to the event loop then box starts out gray so ensure
-    // it is painted before doing any heavy lifting like the ApplicationWindow init
+    // If we take too long to get to the event loop then box starts out gray so
+    // ensure
+    // it is painted before doing any heavy lifting like the ApplicationWindow
+    // init
     splash.repaint();
     app.processEvents();
 
-    const bool factorySettings = (args.contains("-d") || args.contains("--default-settings"));
+    const bool factorySettings =
+        (args.contains("-d") || args.contains("--default-settings"));
     ApplicationWindow *mw = new ApplicationWindow(factorySettings, args);
     mw->restoreApplicationGeometry();
     mw->parseCommandLineArguments(args);
     app.processEvents();
 
-    //register a couple of fonts
-    QFontDatabase::addApplicationFont(":/fonts/MontserratAlternates-Regular.ttf");
+    // register a couple of fonts
+    QFontDatabase::addApplicationFont(
+        ":/fonts/MontserratAlternates-Regular.ttf");
     QFontDatabase::addApplicationFont(":/fonts/OpenSans-Regular.ttf");
 
     splash.finish(mw);
 
-    app.connect( &app, SIGNAL(lastWindowClosed()), mw, SLOT(exitWithPresetCode()) );
+    app.connect(&app, SIGNAL(lastWindowClosed()), mw,
+                SLOT(exitWithPresetCode()));
     QTimer::singleShot(0, mw, SLOT(about2Start()));
     return app.exec();
-  }
-  catch(std::exception& e)
-  {
-    QMessageBox::critical(0,"Mantid - Error",
-      QString("An unhandled exception has been caught. MantidPlot will have to close. Details:\n\n")+e.what());
-  }
-  catch(...)
-  {
-    QMessageBox::critical(0,"Mantid - Error",
-      "An unhandled exception has been caught. MantidPlot will have to close.");
+  } catch (std::exception &e) {
+    QMessageBox::critical(
+        0, "Mantid - Error",
+        QString("An unhandled exception has been caught. MantidPlot will have "
+                "to close. Details:\n\n") +
+            e.what());
+  } catch (...) {
+    QMessageBox::critical(0, "Mantid - Error", "An unhandled exception has "
+                                               "been caught. MantidPlot will "
+                                               "have to close.");
   }
 }
diff --git a/MantidPlot/src/muParserScript.cpp b/MantidPlot/src/muParserScript.cpp
index fadfce2fac55c15a268825ed082c1dc122aec6c9..df4f916c61b27512e943bdc9931a47c48a9a9767 100644
--- a/MantidPlot/src/muParserScript.cpp
+++ b/MantidPlot/src/muParserScript.cpp
@@ -41,23 +41,25 @@
 
 using namespace mu;
 
-// same as defined in MantidUI.cpp - could be harmonized and shared in all MantidPlot files
-bool isOfType(const QObject* obj, const char* toCompare) {
+// same as defined in MantidUI.cpp - could be harmonized and shared in all
+// MantidPlot files
+bool isOfType(const QObject *obj, const char *toCompare) {
   return strcmp(obj->metaObject()->className(), toCompare) == 0;
 }
 
-muParserScript::muParserScript(ScriptingEnv *env,  const QString &name, QObject *context,
-    bool checkMultilineCode)
-: Script(env,name, Script::NonInteractive, context),
-  d_warn_multiline_code(checkMultilineCode)
-{
+muParserScript::muParserScript(ScriptingEnv *env, const QString &name,
+                               QObject *context, bool checkMultilineCode)
+    : Script(env, name, Script::NonInteractive, context),
+      d_warn_multiline_code(checkMultilineCode) {
   parser.DefineConst("pi", M_PI);
   parser.DefineConst("Pi", M_PI);
   parser.DefineConst("PI", M_PI);
   parser.DefineConst("e", M_E);
   parser.DefineConst("E", M_E);
 
-  for (const muParserScripting::mathFunction *i=muParserScripting::math_functions; i->name; i++)
+  for (const muParserScripting::mathFunction *i =
+           muParserScripting::math_functions;
+       i->name; i++)
     if (i->numargs == 1 && i->fun1 != NULL)
       parser.DefineFun(i->name, i->fun1);
     else if (i->numargs == 2 && i->fun2 != NULL)
@@ -75,7 +77,6 @@ muParserScript::muParserScript(ScriptingEnv *env,  const QString &name, QObject
   rparser = parser;
   parser.SetVarFactory(mu_addVariable);
   rparser.SetVarFactory(mu_addVariableR);
-
 }
 
 muParserScript::~muParserScript() {
@@ -83,14 +84,14 @@ muParserScript::~muParserScript() {
   clearVariables(rvariables);
 }
 
-double muParserScript::col(const QString &arg)
-{
+double muParserScript::col(const QString &arg) {
   if (!isOfType(context(), "Table"))
-    throw Parser::exception_type(tr("col() works only on tables!").toAscii().constData());
+    throw Parser::exception_type(
+        tr("col() works only on tables!").toAscii().constData());
   QStringList items;
   QString item = "";
 
-  for (int i=0; i < arg.size(); i++) {
+  for (int i = 0; i < arg.size(); i++) {
     if (arg[i] == '"') {
       item += "\"";
       for (i++; i < arg.size() && arg[i] != '"'; i++)
@@ -108,51 +109,59 @@ double muParserScript::col(const QString &arg)
   }
   items << item;
 
-  Table *table = static_cast<Table*>(const_cast<QObject*>(context()));
+  Table *table = static_cast<Table *>(const_cast<QObject *>(context()));
   int col, row;
   Parser local_parser(rparser);
   if (items[0].startsWith("\"") && items[0].endsWith("\"")) {
-    col = table->colNames().indexOf(items[0].mid(1,items[0].length()-2));
-    if (col<0)
-      throw Parser::exception_type(tr("There's no column named %1 in table %2!").
-          arg(items[0]).arg(context()->objectName()).toAscii().constData());
-  } else {// for backwards compatibility
+    col = table->colNames().indexOf(items[0].mid(1, items[0].length() - 2));
+    if (col < 0)
+      throw Parser::exception_type(tr("There's no column named %1 in table %2!")
+                                       .arg(items[0])
+                                       .arg(context()->objectName())
+                                       .toAscii()
+                                       .constData());
+  } else { // for backwards compatibility
     col = table->colNames().indexOf(items[0]);
-    if (col<0) {
+    if (col < 0) {
       local_parser.SetExpr(items[0].toAscii().constData());
       col = qRound(local_parser.Eval()) - 1;
     }
   }
 
-  if (items.count() == 2)
-  {
+  if (items.count() == 2) {
     local_parser.SetExpr(items[1].toAscii().constData());
     row = qRound(local_parser.Eval()) - 1;
   } else if (variables["i"])
-    row = (int) *(variables["i"]) - 1;
+    row = (int)*(variables["i"]) - 1;
   else
     return 0;
   clearVariables(rvariables);
   if (row < 0 || row >= table->numRows())
-    throw Parser::exception_type(tr("There's no row %1 in table %2!").
-        arg(row+1).arg(context()->objectName()).toAscii().constData());
+    throw Parser::exception_type(tr("There's no row %1 in table %2!")
+                                     .arg(row + 1)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
   if (col < 0 || col >= table->numCols())
-    throw Parser::exception_type(tr("There's no column %1 in table %2!").
-        arg(col+1).arg(context()->objectName()).toAscii().constData());
+    throw Parser::exception_type(tr("There's no column %1 in table %2!")
+                                     .arg(col + 1)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
   if (table->text(row, col).isEmpty())
     throw new EmptySourceError();
   else {
-    return table->cell(row,col);
+    return table->cell(row, col);
   }
 }
 
-double muParserScript::tablecol(const QString &arg)
-{
+double muParserScript::tablecol(const QString &arg) {
   if (!isOfType(context(), "Table"))
-    throw Parser::exception_type(tr("tablecol() works only on tables!").toAscii().constData());
+    throw Parser::exception_type(
+        tr("tablecol() works only on tables!").toAscii().constData());
   QStringList items;
   QString item = "";
-  for (int i=0; i < arg.size(); i++) {
+  for (int i = 0; i < arg.size(); i++) {
     if (arg[i] == '"') {
       item += "\"";
       for (i++; i < arg.size() && arg[i] != '"'; i++)
@@ -170,81 +179,110 @@ double muParserScript::tablecol(const QString &arg)
   }
   items << item;
 
-  Table *this_table = static_cast<Table*>( const_cast<QObject*>(context()));
+  Table *this_table = static_cast<Table *>(const_cast<QObject *>(context()));
   int col, row;
   Parser local_parser(rparser);
   if (items.count() != 2)
-    throw Parser::exception_type(tr("tablecol: wrong number of arguments (need 2, got %1)").
-                                 arg(items.count()).toAscii().constData());
+    throw Parser::exception_type(
+        tr("tablecol: wrong number of arguments (need 2, got %1)")
+            .arg(items.count())
+            .toAscii()
+            .constData());
   if (!items[0].startsWith("\"") || !items[0].endsWith("\""))
-    throw Parser::exception_type(tr("tablecol: first argument must be a string (table name)").
-                                 toAscii().constData());
-  Table *target_table = this_table->folder()->rootFolder()->table(items[0].mid(1,items[0].length()-2));
+    throw Parser::exception_type(
+        tr("tablecol: first argument must be a string (table name)")
+            .toAscii()
+            .constData());
+  Table *target_table = this_table->folder()->rootFolder()->table(
+      items[0].mid(1, items[0].length() - 2));
   if (!target_table)
-    throw Parser::exception_type(tr("Couldn't find a table named %1.").
-                                 arg(items[0]).toAscii().constData());
+    throw Parser::exception_type(tr("Couldn't find a table named %1.")
+                                     .arg(items[0])
+                                     .toAscii()
+                                     .constData());
   if (items[1].startsWith("\"") && items[1].endsWith("\"")) {
-    col = target_table->colNames().indexOf(items[1].mid(1,items[1].length()-2));
-    if (col<0)
-      throw Parser::exception_type(tr("There's no column named %1 in table %2!").
-          arg(items[1]).arg(target_table->name()).toAscii().constData());
+    col = target_table->colNames().indexOf(
+        items[1].mid(1, items[1].length() - 2));
+    if (col < 0)
+      throw Parser::exception_type(tr("There's no column named %1 in table %2!")
+                                       .arg(items[1])
+                                       .arg(target_table->name())
+                                       .toAscii()
+                                       .constData());
   } else {
     local_parser.SetExpr(items[1].toAscii().constData());
     col = qRound(local_parser.Eval()) - 1;
   }
   if (variables["i"])
-    row = (int) *(variables["i"]) - 1;
+    row = (int)*(variables["i"]) - 1;
   else
     row = -1;
   clearVariables(rvariables);
   if (row < 0 || row >= target_table->numRows())
-    throw Parser::exception_type(tr("There's no row %1 in table %2!").
-        arg(row+1).arg(target_table->name()).toAscii().constData());
+    throw Parser::exception_type(tr("There's no row %1 in table %2!")
+                                     .arg(row + 1)
+                                     .arg(target_table->name())
+                                     .toAscii()
+                                     .constData());
   if (col < 0 || col >= target_table->numCols())
-    throw Parser::exception_type(tr("There's no column %1 in table %2!").
-        arg(col+1).arg(target_table->name()).toAscii().constData());
-  if (target_table->text(row,col).isEmpty())
+    throw Parser::exception_type(tr("There's no column %1 in table %2!")
+                                     .arg(col + 1)
+                                     .arg(target_table->name())
+                                     .toAscii()
+                                     .constData());
+  if (target_table->text(row, col).isEmpty())
     throw new EmptySourceError();
   else
-    return target_table->cell(row,col);
+    return target_table->cell(row, col);
 }
 
-double muParserScript::cell(int row, int col)
-{
+double muParserScript::cell(int row, int col) {
   if (!isOfType(context(), "Matrix"))
-    throw Parser::exception_type(tr("cell() works only on tables and matrices!").toAscii().constData());
-  Matrix *matrix = static_cast<Matrix*>( const_cast<QObject*>(context()));
+    throw Parser::exception_type(
+        tr("cell() works only on tables and matrices!").toAscii().constData());
+  Matrix *matrix = static_cast<Matrix *>(const_cast<QObject *>(context()));
   if (row < 1 || row > matrix->numRows())
-    throw Parser::exception_type(tr("There's no row %1 in matrix %2!").
-        arg(row).arg(context()->objectName()).toAscii().constData());
+    throw Parser::exception_type(tr("There's no row %1 in matrix %2!")
+                                     .arg(row)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
   if (col < 1 || col > matrix->numCols())
-    throw Parser::exception_type(tr("There's no column %1 in matrix %2!").
-        arg(col).arg(context()->objectName()).toAscii().constData());
-  if (matrix->text(row-1,col-1).isEmpty())
+    throw Parser::exception_type(tr("There's no column %1 in matrix %2!")
+                                     .arg(col)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
+  if (matrix->text(row - 1, col - 1).isEmpty())
     throw new EmptySourceError();
   else
-    return matrix->cell(row-1,col-1);
+    return matrix->cell(row - 1, col - 1);
 }
 
-double muParserScript::tableCell(int col, int row)
-{
+double muParserScript::tableCell(int col, int row) {
   if (!isOfType(context(), "Table"))
-    throw Parser::exception_type(tr("cell() works only on tables and matrices!").toAscii().constData());
-  Table *table = static_cast<Table*>(const_cast<QObject*>(context()));
+    throw Parser::exception_type(
+        tr("cell() works only on tables and matrices!").toAscii().constData());
+  Table *table = static_cast<Table *>(const_cast<QObject *>(context()));
   if (row < 1 || row > table->numRows())
-    throw Parser::exception_type(tr("There's no row %1 in table %2!").
-        arg(row).arg(context()->objectName()).toAscii().constData());
+    throw Parser::exception_type(tr("There's no row %1 in table %2!")
+                                     .arg(row)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
   if (col < 1 || col > table->numCols())
-    throw Parser::exception_type(tr("There's no column %1 in table %2!").
-        arg(col).arg(context()->objectName()).toAscii().constData());
-  if (table->text(row-1,col-1).isEmpty())
+    throw Parser::exception_type(tr("There's no column %1 in table %2!")
+                                     .arg(col)
+                                     .arg(context()->objectName())
+                                     .toAscii()
+                                     .constData());
+  if (table->text(row - 1, col - 1).isEmpty())
     throw new EmptySourceError();
   else
-    return table->cell(row-1,col-1);
+    return table->cell(row - 1, col - 1);
 }
 
-double *muParserScript::addVariable(const char *name)
-{
+double *muParserScript::addVariable(const char *name) {
   double *valptr = new double;
   if (!valptr)
     throw Parser::exception_type(tr("Out of memory").toAscii().constData());
@@ -254,8 +292,7 @@ double *muParserScript::addVariable(const char *name)
   return valptr;
 }
 
-double *muParserScript::addVariableR(const char *name)
-{
+double *muParserScript::addVariableR(const char *name) {
   double *valptr = new double;
   if (!valptr)
     throw Parser::exception_type(tr("Out of memory").toAscii().constData());
@@ -264,14 +301,11 @@ double *muParserScript::addVariableR(const char *name)
   return valptr;
 }
 
-double* muParserScript::defineVariable(const char *name, double val)
-{
+double *muParserScript::defineVariable(const char *name, double val) {
   double *valptr = variables[name];
-  if (!valptr)
-  {
+  if (!valptr) {
     valptr = new double;
-    if (!valptr)
-    {
+    if (!valptr) {
       emit error(tr("Out of memory"), "", 0);
       return 0;
     }
@@ -289,14 +323,11 @@ double* muParserScript::defineVariable(const char *name, double val)
   return valptr;
 }
 
-bool muParserScript::setDouble(double val, const char *name)
-{
+bool muParserScript::setDouble(double val, const char *name) {
   double *valptr = variables[name];
-  if (!valptr)
-  {
+  if (!valptr) {
     valptr = new double;
-    if (!valptr)
-    {
+    if (!valptr) {
       emit error(tr("Out of memory"), "", 0);
       return false;
     }
@@ -311,31 +342,26 @@ bool muParserScript::setDouble(double val, const char *name)
     }
   }
   *valptr = val;
-  return  true;
+  return true;
 }
 
-bool muParserScript::setInt(int val, const char *name)
-{
-  return setDouble((double) val, name);
+bool muParserScript::setInt(int val, const char *name) {
+  return setDouble((double)val, name);
 }
 
-bool muParserScript::setQObject(QObject*, const char*)
-{
-  return false;
-}
+bool muParserScript::setQObject(QObject *, const char *) { return false; }
 
-QString muParserScript::compileColArg(const QString &in)
-{
+QString muParserScript::compileColArg(const QString &in) {
   QString out = "\"";
-  for (int i=0; i < in.size(); i++)
-    if (in[i] == 'c' && in.mid(i,4)=="col(") {
+  for (int i = 0; i < in.size(); i++)
+    if (in[i] == 'c' && in.mid(i, 4) == "col(") {
       out += "col(";
       QString arg = "";
       int paren = 1;
-      for (i+=4; i < in.size() && paren > 0; i++)
+      for (i += 4; i < in.size() && paren > 0; i++)
         if (in[i] == '"') {
           arg += "\"";
-          for (i++; i < in.size() && in[i] != '"'; i++)
+          for (i++; i < in.size() && in [i] != '"'; i++)
             if (in[i] == '\\') {
               arg += "\\";
               arg += in[++i];
@@ -347,15 +373,14 @@ QString muParserScript::compileColArg(const QString &in)
           arg += "(";
         } else if (in[i] == ')') {
           paren--;
-          if(paren>0) arg += ")";
-        }
-        else
+          if (paren > 0)
+            arg += ")";
+        } else
           arg += in[i];
-      out += compileColArg(arg).replace('"',"\\\"");
+      out += compileColArg(arg).replace('"', "\\\"");
       out += ")";
       i--;
-    }
-    else if (in[i] == '\\')
+    } else if (in[i] == '\\')
       out += "\\\\";
     else if (in[i] == '"')
       out += "\\\"";
@@ -364,13 +389,12 @@ QString muParserScript::compileColArg(const QString &in)
   return out + "\"";
 }
 
-
-QString muParserScript::evalSingleLineToString(const QLocale& locale, char f, int prec)
-{
+QString muParserScript::evalSingleLineToString(const QLocale &locale, char f,
+                                               int prec) {
   double val = 0.0;
   try {
     val = parser.Eval();
-  } catch (EmptySourceError*) {
+  } catch (EmptySourceError *) {
     return "";
   } catch (ParserError &) {
     return "";
@@ -378,8 +402,7 @@ QString muParserScript::evalSingleLineToString(const QLocale& locale, char f, in
   return locale.toString(val, f, prec);
 }
 
-double muParserScript::evalSingleLine()
-{
+double muParserScript::evalSingleLine() {
   double val = 0.0;
   try {
     val = parser.Eval();
@@ -393,17 +416,16 @@ double muParserScript::evalSingleLine()
 
 muParserScript *muParserScript::current = NULL;
 
-bool muParserScript::compileImpl()
-{
+bool muParserScript::compileImpl() {
   const QString code = QString::fromStdString(codeString());
   muCode.clear();
   QString muCodeLine = "";
-  for (int i=0; i < code.size(); i++)
-    if (code[i] == 'c' && code.mid(i,4)=="col(") {
+  for (int i = 0; i < code.size(); i++)
+    if (code[i] == 'c' && code.mid(i, 4) == "col(") {
       muCodeLine += "col(";
       QString arg = "";
       int paren = 1;
-      for (i+=4; i < code.size() && paren > 0; ++i)
+      for (i += 4; i < code.size() && paren > 0; ++i)
         if (code[i] == '"') {
           arg += "\"";
           for (++i; i < code.size() && code[i] != '"'; ++i)
@@ -418,15 +440,17 @@ bool muParserScript::compileImpl()
           arg += "(";
         } else if (code[i] == ')') {
           paren--;
-          if(paren>0) arg += ")";
-        }
-        else
+          if (paren > 0)
+            arg += ")";
+        } else
           arg += code[i];
       muCodeLine += compileColArg(arg);
       muCodeLine += ")";
       i--;
     } else if (code[i] == '#')
-      for (++i; i < code.size() && code[i] != '\n'; ++i){;}
+      for (++i; i < code.size() && code[i] != '\n'; ++i) {
+        ;
+      }
     else if (code[i] == '\n') {
       muCodeLine = muCodeLine.trimmed();
       if (!muCodeLine.isEmpty())
@@ -438,16 +462,16 @@ bool muParserScript::compileImpl()
   if (!muCodeLine.isEmpty())
     muCode += muCodeLine;
 
-  if (muCode.size() == 1){
+  if (muCode.size() == 1) {
     current = this;
     parser.SetExpr(muCode[0].toAscii().constData());
     try {
       parser.Eval();
-    } catch (EmptySourceError*) {
+    } catch (EmptySourceError *) {
       QApplication::restoreOverrideCursor();
       return false;
     } catch (mu::ParserError &e) {
-      if (e.GetCode() != ecVAL_EXPECTED){
+      if (e.GetCode() != ecVAL_EXPECTED) {
         QApplication::restoreOverrideCursor();
         emit error(e.GetMsg().c_str(), "", 0);
         return false;
@@ -457,15 +481,14 @@ bool muParserScript::compileImpl()
   return true;
 }
 
-QVariant muParserScript::evaluateImpl()
-{
+QVariant muParserScript::evaluateImpl() {
   if (!compile(scriptCode())) {
     return QVariant();
   }
   double val = 0.0;
   try {
     current = this;
-    for (QStringList::iterator i=muCode.begin(); i != muCode.end(); ++i) {
+    for (QStringList::iterator i = muCode.begin(); i != muCode.end(); ++i) {
       parser.SetExpr(i->toAscii().constData());
       val = parser.Eval();
     }
@@ -478,13 +501,12 @@ QVariant muParserScript::evaluateImpl()
   return QVariant(val);
 }
 
-bool muParserScript::executeImpl()
-{
+bool muParserScript::executeImpl() {
   if (!compile(scriptCode()))
     return false;
   try {
     current = this;
-    for (QStringList::iterator i=muCode.begin(); i != muCode.end(); ++i) {
+    for (QStringList::iterator i = muCode.begin(); i != muCode.end(); ++i) {
       parser.SetExpr(i->toAscii().constData());
       parser.Eval();
     }
@@ -497,13 +519,12 @@ bool muParserScript::executeImpl()
   return true;
 }
 
-void muParserScript::abortImpl()
-{
+void muParserScript::abortImpl() {
   // does nothing
 }
 
-void muParserScript::clearVariables(QMap<QString, double*> &vars) {
-  for(auto varPtr : vars){
+void muParserScript::clearVariables(QMap<QString, double *> &vars) {
+  for (auto varPtr : vars) {
     delete varPtr;
   }
   vars.clear();
diff --git a/MantidPlot/src/muParserScript.h b/MantidPlot/src/muParserScript.h
index b6e9650c23d5a0d9cbea10518f726fdc6af47940..babc12a81809211e4ee1ac1137b60f0db47a373e 100644
--- a/MantidPlot/src/muParserScript.h
+++ b/MantidPlot/src/muParserScript.h
@@ -39,57 +39,66 @@
 
 class ScriptingEnv;
 
-class muParserScript: public Script
-{
+class muParserScript : public Script {
   Q_OBJECT
 
-  public:
-    muParserScript(ScriptingEnv *env, const QString &name,
-                   QObject *context, bool checkMultilineCode = true);
-    ~muParserScript();
+public:
+  muParserScript(ScriptingEnv *env, const QString &name, QObject *context,
+                 bool checkMultilineCode = true);
+  ~muParserScript();
 
-    bool compilesToCompleteStatement(const QString &) const override {
-      return true;
-    };
+  bool compilesToCompleteStatement(const QString &) const override {
+    return true;
+  };
 
-  public slots:
-    QVariant evaluateImpl() override;
-    double evalSingleLine();
-    QString evalSingleLineToString(const QLocale& locale, char f, int prec);
-    bool compileImpl() override;
-    bool executeImpl() override;
-    void abortImpl() override;
-    bool setQObject(QObject *val, const char *name) override;
-    bool setInt(int val, const char *name) override;
-    bool setDouble(double val, const char *name) override;
-    double* defineVariable(const char *name, double val = 0.0);
-    int codeLines(){return muCode.size();};
+public slots:
+  QVariant evaluateImpl() override;
+  double evalSingleLine();
+  QString evalSingleLineToString(const QLocale &locale, char f, int prec);
+  bool compileImpl() override;
+  bool executeImpl() override;
+  void abortImpl() override;
+  bool setQObject(QObject *val, const char *name) override;
+  bool setInt(int val, const char *name) override;
+  bool setDouble(double val, const char *name) override;
+  double *defineVariable(const char *name, double val = 0.0);
+  int codeLines() { return muCode.size(); };
 
-  private:
-    double col(const QString &arg);
-    double tablecol(const QString &arg);
-    double cell(int row, int col);
-    double tableCell(int col, int row);
-    double *addVariable(const char *name);
-    double *addVariableR(const char *name);
-    static double *mu_addVariableR(const char *name) { return current->addVariableR(name); }
-    static double mu_col(const char *arg) { return current->col(arg); }
-    static double mu_cell(double row, double col) { return current->cell(qRound(row), qRound(col)); }
-    static double mu_tableCell(double col, double row) { return current->tableCell(qRound(col), qRound(row)); }
-    static double mu_tablecol(const char *arg) { return current->tablecol(arg); }
-    static double *mu_addVariable(const char *name, void *){ return current->addVariable(name); }
-    static double *mu_addVariableR(const char *name, void *) { return current->addVariableR(name); }
-    static QString compileColArg(const QString& in);
-    static void clearVariables(QMap<QString, double*> &vars);
+private:
+  double col(const QString &arg);
+  double tablecol(const QString &arg);
+  double cell(int row, int col);
+  double tableCell(int col, int row);
+  double *addVariable(const char *name);
+  double *addVariableR(const char *name);
+  static double *mu_addVariableR(const char *name) {
+    return current->addVariableR(name);
+  }
+  static double mu_col(const char *arg) { return current->col(arg); }
+  static double mu_cell(double row, double col) {
+    return current->cell(qRound(row), qRound(col));
+  }
+  static double mu_tableCell(double col, double row) {
+    return current->tableCell(qRound(col), qRound(row));
+  }
+  static double mu_tablecol(const char *arg) { return current->tablecol(arg); }
+  static double *mu_addVariable(const char *name, void *) {
+    return current->addVariable(name);
+  }
+  static double *mu_addVariableR(const char *name, void *) {
+    return current->addVariableR(name);
+  }
+  static QString compileColArg(const QString &in);
+  static void clearVariables(QMap<QString, double *> &vars);
 
-    mu::Parser parser, rparser;
-    QMap<QString, double*> variables, rvariables;
-    QStringList muCode;
-    //! Flag telling is the parser should warn users on multiline code input
-    bool d_warn_multiline_code;
+  mu::Parser parser, rparser;
+  QMap<QString, double *> variables, rvariables;
+  QStringList muCode;
+  //! Flag telling is the parser should warn users on multiline code input
+  bool d_warn_multiline_code;
 
-  public:
-    static muParserScript *current;
+public:
+  static muParserScript *current;
 };
 
 #endif
diff --git a/MantidPlot/src/muParserScripting.cpp b/MantidPlot/src/muParserScripting.cpp
index fcf2b9e60e0e059b78a12968b7bbcafc85699209..00860dc586107021e1631d797f627a344b9a4934 100644
--- a/MantidPlot/src/muParserScripting.cpp
+++ b/MantidPlot/src/muParserScripting.cpp
@@ -27,7 +27,7 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "muParserScript.h" 
+#include "muParserScript.h"
 #include "muParserScripting.h"
 #include "Table.h"
 #include "Matrix.h"
@@ -36,76 +36,124 @@
 
 using namespace mu;
 
-const char* muParserScripting::langName = "muParser";
+const char *muParserScripting::langName = "muParser";
 
 const muParserScripting::mathFunction muParserScripting::math_functions[] = {
-  { "abs", 1, NULL,NULL,NULL, "abs(x):\n Absolute value of x." },
-  { "acos", 1, NULL,NULL,NULL, "acos(x):\n Inverse cos function." },
-  { "acosh", 1, NULL,NULL,NULL, "acosh(x):\n Hyperbolic inverse cos function." },
-  { "asin", 1, NULL,NULL,NULL, "asin(x):\n Inverse sin function." },
-  { "asinh", 1, NULL,NULL,NULL, "asinh(x):\n Hyperbolic inverse sin function." },
-  { "atan", 1, NULL,NULL,NULL, "atan(x):\n Inverse tan function." },
-  { "atanh", 1, NULL,NULL,NULL, "atanh(x):\n  Hyperbolic inverse tan function." },
-  { "avg", -1, NULL,NULL,NULL, "avg(x,y,...):\n  Mean value of all arguments." },
-  { "bessel_j0", 1, bessel_J0,NULL,NULL, "bessel_j0(x):\n  Regular cylindrical Bessel function of zeroth order, J_0(x)." },
-  { "bessel_j1", 1, bessel_J1,NULL,NULL, "bessel_j1(x):\n  Regular cylindrical Bessel function of first order, J_1(x)." },
-  { "bessel_jn", 2, NULL,bessel_Jn,NULL, "bessel_jn(double x, int n):\n Regular cylindrical Bessel function of order n, J_n(x)." },
-  { "bessel_jn_zero", 2, NULL,bessel_Jn_zero,NULL, "bessel_jn_zero(double n, unsigned int s):\n s-th positive zero x_s of regular cylindrical Bessel function of order n, J_n(x_s)=0" },
-  { "bessel_y0", 1, bessel_Y0, NULL,NULL, "bessel_y0(x):\n Irregular cylindrical Bessel function of zeroth order, Y_0(x), for x>0." },
-  { "bessel_y1", 1, bessel_Y1, NULL,NULL, "bessel_y1(x):\n Irregular cylindrical Bessel function of first order, Y_1(x), for x>0." },
-  { "bessel_yn", 2, NULL,bessel_Yn,NULL, "bessel_yn(double x, int n):\n Irregular cylindrical Bessel function of order n, Y_n(x), for x>0." },
-  { "beta", 2, NULL,beta,NULL, "beta(a,b):\n Computes the Beta Function, B(a,b) = Gamma(a)*Gamma(b)/Gamma(a+b) for a > 0, b > 0." },
-  { "ceil", 1, ceil,NULL,NULL, "ceil(x):\n Round to the next larger integer,\n smallest integer larger or equal to x." },
-  { "cos", 1, NULL,NULL,NULL, "cos(x):\n Calculate cosine." },
-  { "cosh", 1, NULL,NULL,NULL, "cosh(x):\n Hyperbolic cos function." },
-  { "erf", 1, erf, NULL,NULL, "erf(x):\n  The error function." },
-  { "erfc", 1, erfc, NULL,NULL, "erfc(x):\n Complementary error function erfc(x) = 1 - erf(x)." },
-  { "erfz", 1, erf_Z, NULL,NULL, "erfz(x):\n The Gaussian probability density function Z(x)." },
-  { "erfq", 1, erf_Q, NULL,NULL, "erfq(x):\n The upper tail of the Gaussian probability function Q(x)." },
-  { "exp", 1, NULL,NULL,NULL, "exp(x):\n Exponential function: e raised to the power of x." },
-  { "floor", 1, floor,NULL,NULL, "floor(x):\n Round to the next smaller integer,\n largest integer smaller or equal to x." },
-  { "gamma", 1, gamma, NULL,NULL, "gamma(x):\n Computes the Gamma function, subject to x not being a negative integer." },
-  { "gammaln", 1, lngamma,NULL,NULL, "gammaln(x):\n Computes the logarithm of the Gamma function, subject to x not a being negative integer. For x<0, log(|Gamma(x)|) is returned." },
-  { "hazard", 1, hazard,NULL,NULL, "hazard(x):\n Computes the hazard function for the normal distribution h(x) = erfz(x)/erfq(x)." },
-  { "if", 3, NULL,NULL,NULL, "if(e1, e2, e3):\n if e1 then e2 else e3." },
-  { "ln", 1, NULL,NULL,NULL, "ln(x):\n Calculate natural logarithm log_e." },
-  { "log", 1, NULL,NULL,NULL, "log(x):\n Calculate decimal logarithm log_10." },
-  { "log10", 1, NULL,NULL,NULL, "log10(x):\n Calculate decimal logarithm log_10." },
-  { "log2", 1, NULL,NULL,NULL, "log2(x):\n Calculate binary logarithm log_2." },
-  { "min", -1, NULL,NULL,NULL, "min(x,y,...):\n Calculate minimum of all arguments." },
-  { "max", -1, NULL,NULL,NULL, "max(x,y,...):\n Calculate maximum of all arguments." },
-  { "mod", 2, NULL,mod,NULL, "mod(x,y):\n Calculate rest of integer division x/y,\n x modulo y." },
-  { "pow", 2, NULL,mypow,NULL, "pow(x,y):\n Raise x to the power of y, x^y." },
-  { "rint", 1, NULL,NULL,NULL, "rint(x):\n Round to nearest integer." },
-  { "sign", 1, NULL,NULL,NULL, "sign(x):\n Sign function: -1 if x<0; 1 if x>0." },
-  { "sin", 1, NULL,NULL,NULL, "sin(x):\n Calculate sine." },
-  { "sinh", 1, NULL,NULL,NULL, "sinh(x):\n Hyperbolic sin function." },
-  { "sqrt", 1, NULL,NULL,NULL, "sqrt(x):\n Square root function." },
-  { "sum", -1, NULL,NULL,NULL, "sum(x,y,...):\n Calculate sum of all arguments." },
-  { "tan", 1, NULL,NULL,NULL, "tan(x):\n Calculate tangent function." },
-  { "tanh", 1, NULL,NULL,NULL, "tanh(x):\n Hyperbolic tan function." },
-  { "w0", 1, lambert_W0, NULL, NULL, "w0(x):\n Compute the principal branch of Lambert's W function, W_0(x).\n W is defined as a solution to the equation W(x)*exp(W(x))=x.\n For x<0, there are two real-valued branches; this function computes the one where W>-1 for x<0 (also see wm1(x))." },
-  { "wm1", 1, lambert_Wm1, NULL, NULL, "wm1(x):\n Compute the secondary branch of Lambert's W function, W_{-1}(x).\n W is defined as a solution to the equation W(x)*exp(W(x))=x.\n For x<0, there are two real-valued branches; this function computes the one where W<-1 for x<0. (also see w0(x))." },
-  {0,0,NULL,NULL,NULL,0}
-};
+    {"abs", 1, NULL, NULL, NULL, "abs(x):\n Absolute value of x."},
+    {"acos", 1, NULL, NULL, NULL, "acos(x):\n Inverse cos function."},
+    {"acosh", 1, NULL, NULL, NULL,
+     "acosh(x):\n Hyperbolic inverse cos function."},
+    {"asin", 1, NULL, NULL, NULL, "asin(x):\n Inverse sin function."},
+    {"asinh", 1, NULL, NULL, NULL,
+     "asinh(x):\n Hyperbolic inverse sin function."},
+    {"atan", 1, NULL, NULL, NULL, "atan(x):\n Inverse tan function."},
+    {"atanh", 1, NULL, NULL, NULL,
+     "atanh(x):\n  Hyperbolic inverse tan function."},
+    {"avg", -1, NULL, NULL, NULL,
+     "avg(x,y,...):\n  Mean value of all arguments."},
+    {"bessel_j0", 1, bessel_J0, NULL, NULL, "bessel_j0(x):\n  Regular "
+                                            "cylindrical Bessel function of "
+                                            "zeroth order, J_0(x)."},
+    {"bessel_j1", 1, bessel_J1, NULL, NULL, "bessel_j1(x):\n  Regular "
+                                            "cylindrical Bessel function of "
+                                            "first order, J_1(x)."},
+    {"bessel_jn", 2, NULL, bessel_Jn, NULL, "bessel_jn(double x, int n):\n "
+                                            "Regular cylindrical Bessel "
+                                            "function of order n, J_n(x)."},
+    {"bessel_jn_zero", 2, NULL, bessel_Jn_zero, NULL,
+     "bessel_jn_zero(double n, unsigned int s):\n s-th positive zero x_s of "
+     "regular cylindrical Bessel function of order n, J_n(x_s)=0"},
+    {"bessel_y0", 1, bessel_Y0, NULL, NULL, "bessel_y0(x):\n Irregular "
+                                            "cylindrical Bessel function of "
+                                            "zeroth order, Y_0(x), for x>0."},
+    {"bessel_y1", 1, bessel_Y1, NULL, NULL, "bessel_y1(x):\n Irregular "
+                                            "cylindrical Bessel function of "
+                                            "first order, Y_1(x), for x>0."},
+    {"bessel_yn", 2, NULL, bessel_Yn, NULL,
+     "bessel_yn(double x, int n):\n Irregular cylindrical Bessel function of "
+     "order n, Y_n(x), for x>0."},
+    {"beta", 2, NULL, beta, NULL, "beta(a,b):\n Computes the Beta Function, "
+                                  "B(a,b) = Gamma(a)*Gamma(b)/Gamma(a+b) for a "
+                                  "> 0, b > 0."},
+    {"ceil", 1, ceil, NULL, NULL, "ceil(x):\n Round to the next larger "
+                                  "integer,\n smallest integer larger or equal "
+                                  "to x."},
+    {"cos", 1, NULL, NULL, NULL, "cos(x):\n Calculate cosine."},
+    {"cosh", 1, NULL, NULL, NULL, "cosh(x):\n Hyperbolic cos function."},
+    {"erf", 1, erf, NULL, NULL, "erf(x):\n  The error function."},
+    {"erfc", 1, erfc, NULL, NULL,
+     "erfc(x):\n Complementary error function erfc(x) = 1 - erf(x)."},
+    {"erfz", 1, erf_Z, NULL, NULL,
+     "erfz(x):\n The Gaussian probability density function Z(x)."},
+    {"erfq", 1, erf_Q, NULL, NULL,
+     "erfq(x):\n The upper tail of the Gaussian probability function Q(x)."},
+    {"exp", 1, NULL, NULL, NULL,
+     "exp(x):\n Exponential function: e raised to the power of x."},
+    {"floor", 1, floor, NULL, NULL, "floor(x):\n Round to the next smaller "
+                                    "integer,\n largest integer smaller or "
+                                    "equal to x."},
+    {"gamma", 1, gamma, NULL, NULL, "gamma(x):\n Computes the Gamma function, "
+                                    "subject to x not being a negative "
+                                    "integer."},
+    {"gammaln", 1, lngamma, NULL, NULL,
+     "gammaln(x):\n Computes the logarithm of the Gamma function, subject to x "
+     "not a being negative integer. For x<0, log(|Gamma(x)|) is returned."},
+    {"hazard", 1, hazard, NULL, NULL, "hazard(x):\n Computes the hazard "
+                                      "function for the normal distribution "
+                                      "h(x) = erfz(x)/erfq(x)."},
+    {"if", 3, NULL, NULL, NULL, "if(e1, e2, e3):\n if e1 then e2 else e3."},
+    {"ln", 1, NULL, NULL, NULL, "ln(x):\n Calculate natural logarithm log_e."},
+    {"log", 1, NULL, NULL, NULL,
+     "log(x):\n Calculate decimal logarithm log_10."},
+    {"log10", 1, NULL, NULL, NULL,
+     "log10(x):\n Calculate decimal logarithm log_10."},
+    {"log2", 1, NULL, NULL, NULL,
+     "log2(x):\n Calculate binary logarithm log_2."},
+    {"min", -1, NULL, NULL, NULL,
+     "min(x,y,...):\n Calculate minimum of all arguments."},
+    {"max", -1, NULL, NULL, NULL,
+     "max(x,y,...):\n Calculate maximum of all arguments."},
+    {"mod", 2, NULL, mod, NULL,
+     "mod(x,y):\n Calculate rest of integer division x/y,\n x modulo y."},
+    {"pow", 2, NULL, mypow, NULL,
+     "pow(x,y):\n Raise x to the power of y, x^y."},
+    {"rint", 1, NULL, NULL, NULL, "rint(x):\n Round to nearest integer."},
+    {"sign", 1, NULL, NULL, NULL,
+     "sign(x):\n Sign function: -1 if x<0; 1 if x>0."},
+    {"sin", 1, NULL, NULL, NULL, "sin(x):\n Calculate sine."},
+    {"sinh", 1, NULL, NULL, NULL, "sinh(x):\n Hyperbolic sin function."},
+    {"sqrt", 1, NULL, NULL, NULL, "sqrt(x):\n Square root function."},
+    {"sum", -1, NULL, NULL, NULL,
+     "sum(x,y,...):\n Calculate sum of all arguments."},
+    {"tan", 1, NULL, NULL, NULL, "tan(x):\n Calculate tangent function."},
+    {"tanh", 1, NULL, NULL, NULL, "tanh(x):\n Hyperbolic tan function."},
+    {"w0", 1, lambert_W0, NULL, NULL,
+     "w0(x):\n Compute the principal branch of Lambert's W function, W_0(x).\n "
+     "W is defined as a solution to the equation W(x)*exp(W(x))=x.\n For x<0, "
+     "there are two real-valued branches; this function computes the one where "
+     "W>-1 for x<0 (also see wm1(x))."},
+    {"wm1", 1, lambert_Wm1, NULL, NULL,
+     "wm1(x):\n Compute the secondary branch of Lambert's W function, "
+     "W_{-1}(x).\n W is defined as a solution to the equation "
+     "W(x)*exp(W(x))=x.\n For x<0, there are two real-valued branches; this "
+     "function computes the one where W<-1 for x<0. (also see w0(x))."},
+    {0, 0, NULL, NULL, NULL, 0}};
 
-void muParserScripting::setSysArgs(const QStringList &)
-{
-  throw std::runtime_error("muParserScripting does not support command line arguments");
+void muParserScripting::setSysArgs(const QStringList &) {
+  throw std::runtime_error(
+      "muParserScripting does not support command line arguments");
 }
 
-const QStringList muParserScripting::mathFunctions() const
-{
+const QStringList muParserScripting::mathFunctions() const {
   QStringList l;
-  for (const mathFunction *i=math_functions; i->name; i++)
+  for (const mathFunction *i = math_functions; i->name; i++)
     l << i->name;
   return l;
 }
 
-const QString muParserScripting::mathFunctionDoc (const QString &name) const
-{
-  for (const mathFunction *i=math_functions; i->name; i++)
-    if (name==i->name)
+const QString muParserScripting::mathFunctionDoc(const QString &name) const {
+  for (const mathFunction *i = math_functions; i->name; i++)
+    if (name == i->name)
       return i->description;
   return QString::null;
 }
diff --git a/MantidPlot/src/muParserScripting.h b/MantidPlot/src/muParserScripting.h
index 05eecab694be6aebb47e5da1adcc911525020488..6d6f1569c0a0861717fb04a080f84bce90409557 100644
--- a/MantidPlot/src/muParserScripting.h
+++ b/MantidPlot/src/muParserScripting.h
@@ -38,96 +38,83 @@
 #include "math.h"
 #include <gsl/gsl_sf.h>
 
-//Mantid - follows changes to ScriptingEnv
+// Mantid - follows changes to ScriptingEnv
 class QsciLexer;
 
 //! TODO
-class muParserScripting: public ScriptingEnv
-{
+class muParserScripting : public ScriptingEnv {
   Q_OBJECT
 
-  public:
-    static const char *langName;
-    explicit muParserScripting(ApplicationWindow *parent)
-        : ScriptingEnv(parent, langName) {
-      d_initialized = true;
-    }
-    static ScriptingEnv *constructor(ApplicationWindow *parent) { return new muParserScripting(parent); }
-
-    /// Set the system arguments. Throws an exception as it is not supported
-    void setSysArgs(const QStringList &args) override;
-
-    Script *newScript(const QString &name, QObject *context,
-                      const Script::InteractionType) const override {
-      return new muParserScript(const_cast<muParserScripting*>(this), name, context);
-    }
-
-    bool supportsEvaluation() override { return true; }
-
-    // we do not support global variables
-    bool setQObject(QObject *, const char *) override { return false; }
-    bool setInt(int, const char *) override { return false; }
-    bool setDouble(double, const char *) override { return false; }
-
-    const QStringList mathFunctions() const override;
-    const QString mathFunctionDoc(const QString &name) const override;
-
-    struct mathFunction
-    {
-      const char *name;
-      int numargs;
-      double (*fun1)(double);
-      double (*fun2)(double,double);
-      double (*fun3)(double,double,double);
-      const char *description;
-    };
-    static const mathFunction math_functions[];
-
-  private:
-    static double mod(double x, double y)
-      { return fmod(x,y); }
-    static double mypow(double x, double y)
-      { return pow(x,y); }
-    static double bessel_J0(double x)
-      { return gsl_sf_bessel_J0 (x); }
-    static double bessel_J1(double x)
-      { return gsl_sf_bessel_J1 (x); }
-    static double bessel_Jn(double x, double n)
-      { return gsl_sf_bessel_Jn ((int)n, x); }
-    static double bessel_Yn(double x, double n)
-      { return gsl_sf_bessel_Yn ((int)n, x); }
-    static double bessel_Jn_zero(double n, double s)
-      { return gsl_sf_bessel_zero_Jnu(n, (unsigned int) s); }
-    static double bessel_Y0(double x)
-      { return gsl_sf_bessel_Y0 (x); }
-    static double bessel_Y1(double x)
-      { return gsl_sf_bessel_Y1 (x); }
-    static double beta(double a, double b)
-      { return gsl_sf_beta (a,b); }
-    static double erf(double x)
-      { return gsl_sf_erf (x); }
-    static double erfc(double x)
-      { return gsl_sf_erfc (x); }
-    static double erf_Z(double x)
-      { return gsl_sf_erf_Z (x); }
-    static double erf_Q(double x)
-      { return gsl_sf_erf_Q (x); }
-    static double gamma(double x)
-      { return gsl_sf_gamma (x); }
-    static double lngamma(double x)
-      { return gsl_sf_lngamma (x); }
-    static double hazard(double x)
-      { return gsl_sf_hazard (x); }
-	 static double lambert_W0(double x)
-	   { return gsl_sf_lambert_W0(x); }
-	 static double lambert_Wm1(double x)
-	   { return gsl_sf_lambert_Wm1(x); }
+public:
+  static const char *langName;
+  explicit muParserScripting(ApplicationWindow *parent)
+      : ScriptingEnv(parent, langName) {
+    d_initialized = true;
+  }
+  static ScriptingEnv *constructor(ApplicationWindow *parent) {
+    return new muParserScripting(parent);
+  }
+
+  /// Set the system arguments. Throws an exception as it is not supported
+  void setSysArgs(const QStringList &args) override;
+
+  Script *newScript(const QString &name, QObject *context,
+                    const Script::InteractionType) const override {
+    return new muParserScript(const_cast<muParserScripting *>(this), name,
+                              context);
+  }
+
+  bool supportsEvaluation() override { return true; }
+
+  // we do not support global variables
+  bool setQObject(QObject *, const char *) override { return false; }
+  bool setInt(int, const char *) override { return false; }
+  bool setDouble(double, const char *) override { return false; }
+
+  const QStringList mathFunctions() const override;
+  const QString mathFunctionDoc(const QString &name) const override;
+
+  struct mathFunction {
+    const char *name;
+    int numargs;
+    double (*fun1)(double);
+    double (*fun2)(double, double);
+    double (*fun3)(double, double, double);
+    const char *description;
+  };
+  static const mathFunction math_functions[];
+
+private:
+  static double mod(double x, double y) { return fmod(x, y); }
+  static double mypow(double x, double y) { return pow(x, y); }
+  static double bessel_J0(double x) { return gsl_sf_bessel_J0(x); }
+  static double bessel_J1(double x) { return gsl_sf_bessel_J1(x); }
+  static double bessel_Jn(double x, double n) {
+    return gsl_sf_bessel_Jn((int)n, x);
+  }
+  static double bessel_Yn(double x, double n) {
+    return gsl_sf_bessel_Yn((int)n, x);
+  }
+  static double bessel_Jn_zero(double n, double s) {
+    return gsl_sf_bessel_zero_Jnu(n, (unsigned int)s);
+  }
+  static double bessel_Y0(double x) { return gsl_sf_bessel_Y0(x); }
+  static double bessel_Y1(double x) { return gsl_sf_bessel_Y1(x); }
+  static double beta(double a, double b) { return gsl_sf_beta(a, b); }
+  static double erf(double x) { return gsl_sf_erf(x); }
+  static double erfc(double x) { return gsl_sf_erfc(x); }
+  static double erf_Z(double x) { return gsl_sf_erf_Z(x); }
+  static double erf_Q(double x) { return gsl_sf_erf_Q(x); }
+  static double gamma(double x) { return gsl_sf_gamma(x); }
+  static double lngamma(double x) { return gsl_sf_lngamma(x); }
+  static double hazard(double x) { return gsl_sf_hazard(x); }
+  static double lambert_W0(double x) { return gsl_sf_lambert_W0(x); }
+  static double lambert_Wm1(double x) { return gsl_sf_lambert_Wm1(x); }
 };
 
-class EmptySourceError : public mu::ParserError
-{
-	public:
-		EmptySourceError() {}
+class EmptySourceError : public mu::ParserError {
+public:
+  EmptySourceError() {}
 };
 
 #endif
diff --git a/MantidPlot/src/nrutil.cpp b/MantidPlot/src/nrutil.cpp
index 2581b2b425edff0c3b7be17cf8b97b1bdcd620a4..e18d9d543077406715f050e37c3a4b9ed7705182 100644
--- a/MantidPlot/src/nrutil.cpp
+++ b/MantidPlot/src/nrutil.cpp
@@ -5,152 +5,158 @@
 
 #include "nrutil.h"
 
-int IMIN(int ia, int ib)
-	{
-	if (ia<=ib)
-		return ia;
-	else
-		return ib;
-	}
-
-void nrerror(const char * error_text)
-{//Numerical Recipes standard error handler
-fprintf(stderr,"Numerical Recipes run-time error...\n");
-fprintf(stderr,"%s\n",error_text);
-fprintf(stderr,"...now exiting to system...\n");
-exit(1);
+int IMIN(int ia, int ib) {
+  if (ia <= ib)
+    return ia;
+  else
+    return ib;
 }
 
-double **matrix(long nrl, long nrh, long ncl, long nch)
-{// allocate a double matrix with subscript range m[nrl..nrh][ncl..nch]
-long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
-double **m;
-
-//allocate pointers to rows
-m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
-if (!m) nrerror("allocation failure 1 in matrix()");
-m += NR_END;
-m -= nrl;
-
-// allocate rows and set pointers to them
-m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
-if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
-m[nrl] += NR_END;
-m[nrl] -= ncl;
-for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
-
-// return pointer to array of pointers to rows
-return m;
+void nrerror(
+    const char *error_text) { // Numerical Recipes standard error handler
+  fprintf(stderr, "Numerical Recipes run-time error...\n");
+  fprintf(stderr, "%s\n", error_text);
+  fprintf(stderr, "...now exiting to system...\n");
+  exit(1);
 }
 
-void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
-{
-(void)nrh;
-(void)nch;
-//free a double matrix allocated by matrix()
-free((FREE_ARG) (m[nrl]+ncl-NR_END));
-free((FREE_ARG) (m+nrl-NR_END));
+double **matrix(long nrl, long nrh, long ncl,
+                long nch) { // allocate a double matrix with subscript range
+                            // m[nrl..nrh][ncl..nch]
+  long i, nrow = nrh - nrl + 1, ncol = nch - ncl + 1;
+  double **m;
+
+  // allocate pointers to rows
+  m = (double **)malloc((size_t)((nrow + NR_END) * sizeof(double *)));
+  if (!m)
+    nrerror("allocation failure 1 in matrix()");
+  m += NR_END;
+  m -= nrl;
+
+  // allocate rows and set pointers to them
+  m[nrl] = (double *)malloc((size_t)((nrow * ncol + NR_END) * sizeof(double)));
+  if (!m[nrl])
+    nrerror("allocation failure 2 in matrix()");
+  m[nrl] += NR_END;
+  m[nrl] -= ncl;
+  for (i = nrl + 1; i <= nrh; i++)
+    m[i] = m[i - 1] + ncol;
+
+  // return pointer to array of pointers to rows
+  return m;
 }
 
+void free_matrix(double **m, long nrl, long nrh, long ncl, long nch) {
+  (void)nrh;
+  (void)nch;
+  // free a double matrix allocated by matrix()
+  free((FREE_ARG)(m[nrl] + ncl - NR_END));
+  free((FREE_ARG)(m + nrl - NR_END));
+}
 
-double *vector(long nl, long nh)
-{//allocate a double vector with subscript range v[nl..nh]
-double *v;
-v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double)));
-if (!v)
-	nrerror("allocation failure in double vector()");
-return v-nl+NR_END;
+double *
+vector(long nl,
+       long nh) { // allocate a double vector with subscript range v[nl..nh]
+  double *v;
+  v = (double *)malloc((size_t)((nh - nl + 1 + NR_END) * sizeof(double)));
+  if (!v)
+    nrerror("allocation failure in double vector()");
+  return v - nl + NR_END;
 }
 
-void free_vector(double *v, long nl, long)
-{// free a double vector allocated with vector()
-free((FREE_ARG) (v+nl-NR_END));
+void free_vector(double *v, long nl,
+                 long) { // free a double vector allocated with vector()
+  free((FREE_ARG)(v + nl - NR_END));
 }
 
-size_t *ivector(long nl, long nh)
-{
-size_t *v;
-v=(size_t *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(size_t)));
-if (!v) nrerror("allocation failure in ivector()");
-return v-nl+NR_END;
+size_t *ivector(long nl, long nh) {
+  size_t *v;
+  v = (size_t *)malloc((size_t)((nh - nl + 1 + NR_END) * sizeof(size_t)));
+  if (!v)
+    nrerror("allocation failure in ivector()");
+  return v - nl + NR_END;
 }
 
-void free_ivector(size_t *v, long nl, long)
-{
-free((FREE_ARG) (v+nl-NR_END));
+void free_ivector(size_t *v, long nl, long) {
+  free((FREE_ARG)(v + nl - NR_END));
 }
 
-int *intvector(long nl, long nh)
-{
-int *v;
-v=(int *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(int)));
-if (!v) nrerror("allocation failure in intvector()");
-return v-nl+NR_END;
+int *intvector(long nl, long nh) {
+  int *v;
+  v = (int *)malloc((size_t)((nh - nl + 1 + NR_END) * sizeof(int)));
+  if (!v)
+    nrerror("allocation failure in intvector()");
+  return v - nl + NR_END;
 }
 
-void free_intvector(int*v, long nl, long)
-{
-free((FREE_ARG) (v+nl-NR_END));
+void free_intvector(int *v, long nl, long) {
+  free((FREE_ARG)(v + nl - NR_END));
 }
 
- void savgol(double *c, int np, int nl, int nr, int ld, int m)  {
-/*-------------------------------------------------------------------------------------------
- USES lubksb,ludcmp given below.
- Returns in c(np), in wrap-around order (see reference) consistent with the argument respns
- in routine convlv, a set of Savitzky-Golay filter coefficients. nl is the number of leftward
- (past) data points used, while nr is the number of rightward (future) data points, making
- the total number of data points used nl+nr+1. ld is the order of the derivative desired
- (e.g., ld = 0 for smoothed function). m is the order of the smoothing polynomial, also
- equal to the highest conserved moment; usual values are m = 2 or m = 4.
--------------------------------------------------------------------------------------------*/
-int imj,ipj,j,k,kk,mm;
-double d,fac,sum,**a,*b;
-
-if (np < nl+nr+1 || nl < 0 || nr < 0 || ld > m || nl+nr < m)
-	nrerror("bad args in savgol");
-
-int *indx= intvector(1,m+1);
-a=matrix(1,m+1,1,m+1);
-b=vector(1,m+1);
-for (ipj=0;ipj<=(m << 1);ipj++)
-	{//Set up the normal equations of the desired least-squares fit
-	sum=(ipj ? 0.0 : 1.0);
-	for (k=1;k<=nr;k++)
-		sum += pow((double)k,(double)ipj);
-	for (k=1;k<=nl;k++)
-		sum += pow((double)-k,(double)ipj);
-	mm=IMIN(ipj,2*m-ipj);
-	for (imj = -mm;imj<=mm;imj+=2)
-		a[1+(ipj+imj)/2][1+(ipj-imj)/2]=sum;
-	}
-
-ludcmp(a, m+1, indx, &d); //Solve them: LU decomposition.
-
-for (j=1;j<=m+1;j++)
-	b[j]=0.0;
-
-b[ld+1]=1.0; //Right-hand side vector is unit vector, depending on which derivative we want.
-
-lubksb(a,m+1,indx,b); //Get one row of the inverse matrix.
-
-for (kk=1;kk<=np;kk++)
-	c[kk]=0.0; //Zero the output array (it may be bigger than number of coefficients).
-
-for (k = -nl;k<=nr;k++)
-	{
-	sum=b[1];   //Each Savitzky-Golay coefficient is the dot product
-				//of powers of an integer with the inverse matrix row.
-	fac=1.0;
-	for (mm=1;mm<=m;mm++)
-		sum += b[mm+1]*(fac *= k);
-
-	kk=((np-k) % np)+1; //Store in wrap-around order.
-	c[kk]=sum;
-	}
-
-free_vector(b,1,m+1);
-free_matrix(a,1,m+1,1,m+1);
-free_intvector(indx,1,m+1);
+void savgol(double *c, int np, int nl, int nr, int ld, int m) {
+  /*-------------------------------------------------------------------------------------------
+   USES lubksb,ludcmp given below.
+   Returns in c(np), in wrap-around order (see reference) consistent with the
+  argument respns
+   in routine convlv, a set of Savitzky-Golay filter coefficients. nl is the
+  number of leftward
+   (past) data points used, while nr is the number of rightward (future) data
+  points, making
+   the total number of data points used nl+nr+1. ld is the order of the
+  derivative desired
+   (e.g., ld = 0 for smoothed function). m is the order of the smoothing
+  polynomial, also
+   equal to the highest conserved moment; usual values are m = 2 or m = 4.
+  -------------------------------------------------------------------------------------------*/
+  int imj, ipj, j, k, kk, mm;
+  double d, fac, sum, **a, *b;
+
+  if (np < nl + nr + 1 || nl < 0 || nr < 0 || ld > m || nl + nr < m)
+    nrerror("bad args in savgol");
+
+  int *indx = intvector(1, m + 1);
+  a = matrix(1, m + 1, 1, m + 1);
+  b = vector(1, m + 1);
+  for (ipj = 0; ipj <= (m << 1);
+       ipj++) { // Set up the normal equations of the desired least-squares fit
+    sum = (ipj ? 0.0 : 1.0);
+    for (k = 1; k <= nr; k++)
+      sum += pow((double)k, (double)ipj);
+    for (k = 1; k <= nl; k++)
+      sum += pow((double)-k, (double)ipj);
+    mm = IMIN(ipj, 2 * m - ipj);
+    for (imj = -mm; imj <= mm; imj += 2)
+      a[1 + (ipj + imj) / 2][1 + (ipj - imj) / 2] = sum;
+  }
+
+  ludcmp(a, m + 1, indx, &d); // Solve them: LU decomposition.
+
+  for (j = 1; j <= m + 1; j++)
+    b[j] = 0.0;
+
+  b[ld + 1] = 1.0; // Right-hand side vector is unit vector, depending on which
+                   // derivative we want.
+
+  lubksb(a, m + 1, indx, b); // Get one row of the inverse matrix.
+
+  for (kk = 1; kk <= np; kk++)
+    c[kk] = 0.0; // Zero the output array (it may be bigger than number of
+                 // coefficients).
+
+  for (k = -nl; k <= nr; k++) {
+    sum = b[1]; // Each Savitzky-Golay coefficient is the dot product
+    // of powers of an integer with the inverse matrix row.
+    fac = 1.0;
+    for (mm = 1; mm <= m; mm++)
+      sum += b[mm + 1] *(fac *= k);
+
+    kk = ((np - k) % np) + 1; // Store in wrap-around order.
+    c[kk] = sum;
+  }
+
+  free_vector(b, 1, m + 1);
+  free_matrix(a, 1, m + 1, 1, m + 1);
+  free_intvector(indx, 1, m + 1);
 }
 
 /**************************************************************
@@ -163,67 +169,58 @@ free_intvector(indx,1,m+1);
 * in combination with LUBKSB to solve linear equations or to  *
 * invert a matrix. Return code is 1, if matrix is singular.   *
 **************************************************************/
-void ludcmp(double **a, int n, int *indx, double *d)
-{
-int i(0),imax(0),j(0),k(0);
-double big,dum,sum,temp;
-double *vv=vector(1,n);
-*d=1.0;
-for (i=1;i<=n;i++)
-	{
-	big=0.0;
-	for (j=1;j<=n;j++)
-		if ((temp=fabs(a[i][j])) > big)
-			big=temp;
-	if (big == 0.0)
-			nrerror("allocation failure 1 in matrix()");
-	vv[i]=1.0/big;
-	}
-for (j=1;j<=n;j++)
-	{
-	for (i=1;i<j;i++)
-		{
-		sum=a[i][j];
-		for (k=1;k<i;k++)
-			sum -= a[i][k]*a[k][j];
-		a[i][j]=sum;
-		}
-	big=0.0;
-	for (i=j;i<=n;i++)
-		{
-		sum=a[i][j];
-		for (k=1;k<j;k++)
-			sum -= a[i][k]*a[k][j];
-		a[i][j]=sum;
-		if ( (dum=vv[i]*fabs(sum)) >= big)
-			{
-			big=dum;
-			imax=i;
-			}
-		}
-	if (j != imax)
-		{
-		for (k=1;k<=n;k++)
-			{
-			dum=a[imax][k];
-			a[imax][k]=a[j][k];
-			a[j][k]=dum;
-			}
-		*d = -(*d);
-		vv[imax]=vv[j];
-		}
-	indx[j]=imax;
-	if (a[j][j] == 0.0)
-		a[j][j]=TINY;
-
-	if (j != n)
-		{
-		dum=1.0/(a[j][j]);
-		for (i=j+1;i<=n;i++)
-			a[i][j] *= dum;
-		}
-	}
-free_vector(vv,1,n);
+void ludcmp(double **a, int n, int *indx, double *d) {
+  int i(0), imax(0), j(0), k(0);
+  double big, dum, sum, temp;
+  double *vv = vector(1, n);
+  *d = 1.0;
+  for (i = 1; i <= n; i++) {
+    big = 0.0;
+    for (j = 1; j <= n; j++)
+      if ((temp = fabs(a[i][j])) > big)
+        big = temp;
+    if (big == 0.0)
+      nrerror("allocation failure 1 in matrix()");
+    vv[i] = 1.0 / big;
+  }
+  for (j = 1; j <= n; j++) {
+    for (i = 1; i < j; i++) {
+      sum = a[i][j];
+      for (k = 1; k < i; k++)
+        sum -= a[i][k] * a[k][j];
+      a[i][j] = sum;
+    }
+    big = 0.0;
+    for (i = j; i <= n; i++) {
+      sum = a[i][j];
+      for (k = 1; k < j; k++)
+        sum -= a[i][k] * a[k][j];
+      a[i][j] = sum;
+      if ((dum = vv[i] * fabs(sum)) >= big) {
+        big = dum;
+        imax = i;
+      }
+    }
+    if (j != imax) {
+      for (k = 1; k <= n; k++) {
+        dum = a[imax][k];
+        a[imax][k] = a[j][k];
+        a[j][k] = dum;
+      }
+      *d = -(*d);
+      vv[imax] = vv[j];
+    }
+    indx[j] = imax;
+    if (a[j][j] == 0.0)
+      a[j][j] = TINY;
+
+    if (j != n) {
+      dum = 1.0 / (a[j][j]);
+      for (i = j + 1; i <= n; i++)
+        a[i][j] *= dum;
+    }
+  }
+  free_vector(vv, 1, n);
 }
 
 /*****************************************************************
@@ -236,67 +233,59 @@ free_vector(vv,1,n);
 * cessive calls with different right-hand sides. This routine is *
 * also efficient for plain matrix inversion.                     *
 *****************************************************************/
-void lubksb(double **a, int n, int *indx, double b[])
-{
-int i,ii=0,ip,j;
-double sum;
-
-for (i=1;i<=n;i++)
-	{
-	ip=indx[i];
-	sum=b[ip];
-	b[ip]=b[i];
-	if (ii)
-		for (j=ii;j<=i-1;j++)
-			sum -= a[i][j]*b[j];
-        else if (sum != 0.0)
-          ii = i;
-
-        b[i]=sum;
-	}
-for (i=n;i>=1;i--)
-	{
-	sum=b[i];
-	for (j=i+1;j<=n;j++)
-		sum -= a[i][j]*b[j];
-
-	b[i]=sum/a[i][i];
-	}
+void lubksb(double **a, int n, int *indx, double b[]) {
+  int i, ii = 0, ip, j;
+  double sum;
+
+  for (i = 1; i <= n; i++) {
+    ip = indx[i];
+    sum = b[ip];
+    b[ip] = b[i];
+    if (ii)
+      for (j = ii; j <= i - 1; j++)
+        sum -= a[i][j] * b[j];
+    else if (sum != 0.0)
+      ii = i;
+
+    b[i] = sum;
+  }
+  for (i = n; i >= 1; i--) {
+    sum = b[i];
+    for (j = i + 1; j <= n; j++)
+      sum -= a[i][j] * b[j];
+
+    b[i] = sum / a[i][i];
+  }
 }
 
-void polint(double xa[], double ya[], int n, double x, double *y, double *dy)
-{
-int i,m,ns=1;
-double den,dif,dift,ho,hp,w;
-double *c, *d;
-dif=fabs(x-xa[1]);
-c=vector(1,n);
-d=vector(1,n);
-for(i=1;i<=n;i++)
-	{
-	if ((dift=fabs(x-xa[i]))<dif)
-		{
-		ns=i;
-		dif=dift;
-		}
-	c[i]=ya[i];
-	d[i]=ya[i];
-	}
-*y=ya[ns--];
-for(m=1;m<n;m++)
-	{
-	for(i=1;i<=n-m;i++)
-		{
-		ho=xa[i]-x;
-		hp=xa[i+m]-x;
-		w=c[i+1]-d[i];
-		den=ho-hp;
-		den=w/den;
-		d[i]=hp*den;
-		c[i]=ho*den;
-		}
-	*y+=(*dy=(2*ns<(n-m)?c[ns+1]:d[ns--]));
-	}
-free_vector(d,1,n);
-free_vector(c,1,n);
+void polint(double xa[], double ya[], int n, double x, double *y, double *dy) {
+  int i, m, ns = 1;
+  double den, dif, dift, ho, hp, w;
+  double *c, *d;
+  dif = fabs(x - xa[1]);
+  c = vector(1, n);
+  d = vector(1, n);
+  for (i = 1; i <= n; i++) {
+    if ((dift = fabs(x - xa[i])) < dif) {
+      ns = i;
+      dif = dift;
+    }
+    c[i] = ya[i];
+    d[i] = ya[i];
+  }
+  *y = ya[ns--];
+  for (m = 1; m < n; m++) {
+    for (i = 1; i <= n - m; i++) {
+      ho = xa[i] - x;
+      hp = xa[i + m] - x;
+      w = c[i + 1] - d[i];
+      den = ho - hp;
+      den = w / den;
+      d[i] = hp * den;
+      c[i] = ho * den;
+    }
+    *y += (*dy = (2 * ns < (n - m) ? c[ns + 1] : d[ns--]));
+  }
+  free_vector(d, 1, n);
+  free_vector(c, 1, n);
 }
diff --git a/MantidPlot/src/nrutil.h b/MantidPlot/src/nrutil.h
index 85c1f7dad5309d8b26222798802cfb0446f2dad9..b0093966365cbceb0f5d2a7202d855ce7d06ff88 100644
--- a/MantidPlot/src/nrutil.h
+++ b/MantidPlot/src/nrutil.h
@@ -2,7 +2,7 @@
 #define NRUTIL_H
 
 #define NR_END 1
-#define FREE_ARG char*
+#define FREE_ARG char *
 #define TINY 1.0e-20
 
 void nrerror(char error_text[]);
@@ -13,9 +13,9 @@ void free_vector(double *v, long nl, long nh);
 size_t *ivector(long nl, long nh);
 void free_ivector(size_t *v, long nl, long nh);
 int *intvector(long nl, long nh);
-void free_intvector(int*v, long nl, long nh);
+void free_intvector(int *v, long nl, long nh);
 
-//used for smoothing
+// used for smoothing
 void lubksb(double **a, int n, int *indx, double b[]);
 void ludcmp(double **a, int n, int *indx, double *d);
 void savgol(double *c, int np, int nl, int nr, int ld, int m);
@@ -23,4 +23,3 @@ void savgol(double *c, int np, int nl, int nr, int ld, int m);
 void polint(double xa[], double ya[], int n, double x, double *y, double *dy);
 
 #endif // NRUTIL_H
-
diff --git a/MantidPlot/src/pixmaps.cpp b/MantidPlot/src/pixmaps.cpp
index 75faddbc7aebf93d8e47a4779b26f8ffe73fb07c..0d2a02e4a2f65786d942e88023fff67b39ee72fb 100644
--- a/MantidPlot/src/pixmaps.cpp
+++ b/MantidPlot/src/pixmaps.cpp
@@ -1,3 +1,4 @@
+// clang-format off
 /*
  * pixmaps.cpp : file containing the definitions of pixelmaps in pixmaps.h
  *
diff --git a/MantidPlot/src/pixmaps.h b/MantidPlot/src/pixmaps.h
index ac46ddf0523af53a3b3c26c6d5a3629fa4c77e00..d0083c720570da2f00bbde1acbc1ca0b751737b0 100644
--- a/MantidPlot/src/pixmaps.h
+++ b/MantidPlot/src/pixmaps.h
@@ -2,7 +2,8 @@
     File                 : pixmaps.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu Siederdissen
+    Copyright            : (C) 2006 by Ion Vasilief, Tilman Hoener zu
+ Siederdissen
     Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net
     Description          : Various pixmaps
 
diff --git a/MantidPlot/src/plot2D/ImageSymbol.cpp b/MantidPlot/src/plot2D/ImageSymbol.cpp
index 1e7585ba192e044a54c30a4a86058a89308bbd72..2545679e4b80c7a5e33f49d9d2a56d18cb308bcb 100644
--- a/MantidPlot/src/plot2D/ImageSymbol.cpp
+++ b/MantidPlot/src/plot2D/ImageSymbol.cpp
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ImageSymbol.cpp
+        File                 : ImageSymbol.cpp
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2010 by Ion Vasilief
+        Copyright            : (C) 2010 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtSymbol displaying a custom images
+        Description          : A QwtSymbol displaying a custom images
 
  ***************************************************************************/
 
@@ -30,24 +30,21 @@
 #include <QPainter>
 #include <qwt_painter.h>
 
-ImageSymbol::ImageSymbol(const QString& fileName):
-        QwtSymbol(QwtSymbol::StyleCnt, QBrush(), QPen(Qt::NoPen), QSize()),
-        d_image_path(fileName)
-{
+ImageSymbol::ImageSymbol(const QString &fileName)
+    : QwtSymbol(QwtSymbol::StyleCnt, QBrush(), QPen(Qt::NoPen), QSize()),
+      d_image_path(fileName) {
   d_pixmap.load(fileName);
   setSize(d_pixmap.size());
 }
 
-ImageSymbol::ImageSymbol(const QPixmap& pixmap, const QString& fileName):
-        QwtSymbol(QwtSymbol::StyleCnt, QBrush(), QPen(Qt::NoPen), QSize()),
-        d_image_path(fileName)
-{
+ImageSymbol::ImageSymbol(const QPixmap &pixmap, const QString &fileName)
+    : QwtSymbol(QwtSymbol::StyleCnt, QBrush(), QPen(Qt::NoPen), QSize()),
+      d_image_path(fileName) {
   d_pixmap = QPixmap(pixmap);
   setSize(d_pixmap.size());
 }
 
-ImageSymbol *ImageSymbol::clone() const
-{
+ImageSymbol *ImageSymbol::clone() const {
   ImageSymbol *other = new ImageSymbol(d_image_path);
   *other = *this;
 
@@ -59,7 +56,6 @@ ImageSymbol *ImageSymbol::clone() const
   \param painter Painter
   \param r Bounding rectangle
 */
-void ImageSymbol::draw(QPainter *p, const QRect& r) const
-{
+void ImageSymbol::draw(QPainter *p, const QRect &r) const {
   p->drawPixmap(r, d_pixmap);
 }
diff --git a/MantidPlot/src/plot2D/ImageSymbol.h b/MantidPlot/src/plot2D/ImageSymbol.h
index 9b743f2c4cb3accb5552f44ccab645e9144a8284..6ee29b99cd967c9b768bb9e7e68795d1aa1b7c57 100644
--- a/MantidPlot/src/plot2D/ImageSymbol.h
+++ b/MantidPlot/src/plot2D/ImageSymbol.h
@@ -1,10 +1,10 @@
 /***************************************************************************
-	File                 : ImageSymbol.h
+        File                 : ImageSymbol.h
     Project              : QtiPlot
     --------------------------------------------------------------------
-	Copyright            : (C) 2010 by Ion Vasilief
+        Copyright            : (C) 2010 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : A QwtSymbol displaying a custom image
+        Description          : A QwtSymbol displaying a custom image
 
  ***************************************************************************/
 
@@ -29,17 +29,16 @@
 #include <qwt_symbol.h>
 
 //! A QwtSymbol displaying a custom image
-class ImageSymbol: public QwtSymbol
-{
+class ImageSymbol : public QwtSymbol {
 public:
   explicit ImageSymbol(const QString &fileName);
-  ImageSymbol(const QPixmap& pixmap, const QString& fileName = QString());
+  ImageSymbol(const QPixmap &pixmap, const QString &fileName = QString());
 
   ImageSymbol *clone() const override;
   void draw(QPainter *p, const QRect &r) const override;
 
-  QPixmap pixmap(){return d_pixmap;};
-  QString imagePath(){return d_image_path;};
+  QPixmap pixmap() { return d_pixmap; };
+  QString imagePath() { return d_image_path; };
 
 private:
   QString d_image_path;
diff --git a/MantidPlot/src/resource.h b/MantidPlot/src/resource.h
index bda06aeaeba4d00f0759eb34235d126e07b62963..da1cc4ab096f011cbda0489577c84a1ed340953b 100644
--- a/MantidPlot/src/resource.h
+++ b/MantidPlot/src/resource.h
@@ -4,12 +4,12 @@
 //
 
 // Next default values for new objects
-// 
+//
 #ifdef APSTUDIO_INVOKED
 #ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NEXT_RESOURCE_VALUE        102
-#define _APS_NEXT_COMMAND_VALUE         40001
-#define _APS_NEXT_CONTROL_VALUE         1000
-#define _APS_NEXT_SYMED_VALUE           101
+#define _APS_NEXT_RESOURCE_VALUE 102
+#define _APS_NEXT_COMMAND_VALUE 40001
+#define _APS_NEXT_CONTROL_VALUE 1000
+#define _APS_NEXT_SYMED_VALUE 101
 #endif
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/AlgorithmDialog.h b/MantidQt/API/inc/MantidQtAPI/AlgorithmDialog.h
index 0a0a982e5a07887ba2f564f3c95640d73f2593c7..3d9fb4cf438654a3762ce4e03c5111bb42c65982 100644
--- a/MantidQt/API/inc/MantidQtAPI/AlgorithmDialog.h
+++ b/MantidQt/API/inc/MantidQtAPI/AlgorithmDialog.h
@@ -7,11 +7,12 @@
 * subscribe method.
 */
 
-#define DECLARE_DIALOG(classname) \
-  namespace { \
-    Mantid::Kernel::RegistrationHelper \
-    register_dialog_##classname \
-    (((MantidQt::API::AlgorithmDialogFactory::Instance().subscribe<classname>(#classname)), 0)); \
+#define DECLARE_DIALOG(classname)                                              \
+  namespace {                                                                  \
+  Mantid::Kernel::RegistrationHelper register_dialog_##classname((             \
+      (MantidQt::API::AlgorithmDialogFactory::Instance().subscribe<classname>( \
+          #classname)),                                                        \
+      0));                                                                     \
   }
 
 //----------------------------------
@@ -46,33 +47,30 @@ class QLayout;
 //----------------------------------
 // Mantid Forward declarations
 //----------------------------------
-namespace Mantid
-{
-  namespace Kernel
-  {
-    class Property;
-  }
+namespace Mantid {
+namespace Kernel {
+class Property;
+}
 }
 
-//Top-level namespace for this library
-namespace MantidQt
-{
+// Top-level namespace for this library
+namespace MantidQt {
 
-namespace API 
-{
+namespace API {
 
 //----------------------------------
 // Forward declarations
 //----------------------------------
 class InterfaceManager;
 
-/** 
+/**
     This class should be the basis for all customised algorithm dialogs.
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 24/02/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -90,17 +88,16 @@ class InterfaceManager;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_API AlgorithmDialog : public QDialog, Mantid::API::AlgorithmObserver
-{
-  
+class EXPORT_OPT_MANTIDQT_API AlgorithmDialog : public QDialog,
+                                                Mantid::API::AlgorithmObserver {
+
   Q_OBJECT
 
 public:
-
   /// DefaultConstructor
-  AlgorithmDialog(QWidget* parent = 0);
+  AlgorithmDialog(QWidget *parent = 0);
   /// Destructor
   ~AlgorithmDialog() override;
 
@@ -117,14 +114,15 @@ public:
   bool isInitialized() const;
 
 protected:
-
   /** @name Virtual functions */
   //@{
   /// This does the work and must be overridden in each deriving class
   virtual void initLayout() = 0;
 
-  /// Parse out the values entered into the dialog boxes. Use storePropertyValue()
-  /// to store the <name, value> pair in the base class so that they can be retrieved later
+  /// Parse out the values entered into the dialog boxes. Use
+  /// storePropertyValue()
+  /// to store the <name, value> pair in the base class so that they can be
+  /// retrieved later
   virtual void parseInput();
 
   /// Save the input history of an accepted dialog
@@ -132,31 +130,32 @@ protected:
   //@}
 
   /** @name Algorithm information */
-  // InterfaceManager needs to be able to reset the algorithm as I can't pass it in use a 
+  // InterfaceManager needs to be able to reset the algorithm as I can't pass it
+  // in use a
   // constructor
   friend class InterfaceManager;
-  
+
   /// Get the algorithm pointer
   Mantid::API::IAlgorithm_sptr getAlgorithm() const;
 
-  /// Get a pointer to the named property 
-  Mantid::Kernel::Property* getAlgorithmProperty(const QString & propName) const;
+  /// Get a pointer to the named property
+  Mantid::Kernel::Property *getAlgorithmProperty(const QString &propName) const;
   /// Return a true if the given property requires user input
-  bool requiresUserInput(const QString & propName) const;
+  bool requiresUserInput(const QString &propName) const;
 
   /// Get an input value from the form, dealing with blank inputs etc
-  QString getInputValue(const QString& propName) const;
+  QString getInputValue(const QString &propName) const;
   /// Get a property validator label
-  QLabel* getValidatorMarker(const QString & propname);
-  
+  QLabel *getValidatorMarker(const QString &propname);
+
   /// Adds a property (name,value) pair to the stored map
-  void storePropertyValue(const QString & name, const QString & value);
+  void storePropertyValue(const QString &name, const QString &value);
 
   /// Removes a property (name, value) pair from the stored map
-  void removePropertyValue(const QString& name);
+  void removePropertyValue(const QString &name);
 
   /// Set properties on this algorithm by pulling values from the tied widgets
-  bool setPropertyValues(const QStringList & skipList = QStringList());
+  bool setPropertyValues(const QStringList &skipList = QStringList());
   bool setPropertyValue(const QString pName, bool validateOthers);
 
   void showValidators();
@@ -165,51 +164,51 @@ protected:
   /** @name Dialog information */
   //@{
   /// Get the message string
-  const QString & getOptionalMessage() const;
+  const QString &getOptionalMessage() const;
 
   /// Add the optional message to the given layout.
   void addOptionalMessage(QVBoxLayout *mainLay);
 
   /// Get the usage boolean value
   bool isForScript() const;
- 
+
   /// Is there a message string available
   bool isMessageAvailable() const;
 
   /// Check is a given property should have its control enabled or not
-  bool isWidgetEnabled(const QString & propName) const;
+  bool isWidgetEnabled(const QString &propName) const;
   //@}
 
   /** @name Helper functions */
   //@{
-  ///Tie a widget to a property
-  QWidget* tie(QWidget* widget, const QString & property, QLayout* parent_layout=NULL,
-      bool readHistory = true);
+  /// Tie a widget to a property
+  QWidget *tie(QWidget *widget, const QString &property,
+               QLayout *parent_layout = NULL, bool readHistory = true);
 
-  ///Untie a widget to a property
-  void untie(const QString & property);
+  /// Untie a widget to a property
+  void untie(const QString &property);
 
-  
   /// Open a file dialog to select a file.
-  QString openFileDialog(const QString & propName);
+  QString openFileDialog(const QString &propName);
 
   /// Open a file dialog to select many file.
-  QStringList openMultipleFileDialog(const QString & propName);
+  QStringList openMultipleFileDialog(const QString &propName);
 
   /// Fill a combo box for the named algorithm's allowed values
-  void fillAndSetComboBox(const QString & propName, QComboBox* optionsBox) const;
+  void fillAndSetComboBox(const QString &propName, QComboBox *optionsBox) const;
 
-  /// Fill in the necessary input for a text field 
-  void fillLineEdit(const QString & propName, QLineEdit* field);
+  /// Fill in the necessary input for a text field
+  void fillLineEdit(const QString &propName, QLineEdit *field);
 
   /// Create a row layout of buttons with specified text
-  QLayout *createDefaultButtonLayout(const QString & helpText = QString("?"),
-                     const QString & loadText = QString("Run"), 
-                     const QString & cancelText = QString("Close"), 
-                     const QString & keepOpenText = QString("Keep Open"));
+  QLayout *
+  createDefaultButtonLayout(const QString &helpText = QString("?"),
+                            const QString &loadText = QString("Run"),
+                            const QString &cancelText = QString("Close"),
+                            const QString &keepOpenText = QString("Keep Open"));
 
   /// Create a help button for this algorithm
-  QPushButton* createHelpButton(const QString & helpText = QString("?")) const;
+  QPushButton *createHelpButton(const QString &helpText = QString("?")) const;
 
   /// Flag an input workspace combobox with its property name
   void flagInputWS(QWidget *inputWidget);
@@ -223,7 +222,7 @@ signals:
   void algCompletedSignal();
 
 protected slots:
-  
+
   /// A default slot that can be used for an OK button.
   void accept() override;
 
@@ -233,7 +232,6 @@ protected slots:
   /// Keep open checkbox clicked;
   virtual void keepOpenChanged(int state);
 
-  
   /// Keep the running algorithm has completed
   virtual void algorithmCompleted();
 
@@ -245,17 +243,17 @@ protected slots:
   void enableExitButton();
 
 protected:
-
   /// Parse out the input from the dialog
   void parse();
   /// Test if the given name's widget has been explicity asked to be enabled
-  bool requestedToKeepEnabled(const QString& propName) const;
-  /// Get the property value from either the previous input store or from Python argument
+  bool requestedToKeepEnabled(const QString &propName) const;
+  /// Get the property value from either the previous input store or from Python
+  /// argument
   /// @param propName :: Name of the property
   /// @return Previous value. If there is no value, empty string is returned
-  QString getPreviousValue(const QString& propName);
+  QString getPreviousValue(const QString &propName);
   /// Set a value based on any old input that we have
-  void setPreviousValue(QWidget *widget, const QString & property);
+  void setPreviousValue(QWidget *widget, const QString &property);
   /// Handle completion of algorithm started while staying open
   void finishHandle(const Mantid::API::IAlgorithm *alg) override;
   /// Handle completion of algorithm started while staying open
@@ -263,31 +261,32 @@ protected:
                    const std::string &what) override;
   void closeEvent(QCloseEvent *evt) override;
 
-/// The following methods were made public for testing in GenericDialogDemo.cpp
+  /// The following methods were made public for testing in
+  /// GenericDialogDemo.cpp
 public:
   /// Set the algorithm associated with this dialog
   void setAlgorithm(Mantid::API::IAlgorithm_sptr);
-  /// Set a list of suggested values  
-  void setPresetValues(const QHash<QString,QString> & presetValues);
+  /// Set a list of suggested values
+  void setPresetValues(const QHash<QString, QString> &presetValues);
   /// Set whether this is intended for use from a script or not
   void isForScript(bool forScript);
   /// If true then execute the algorithm on acceptance
   void executeOnAccept(bool on);
   /// Set an optional message to be displayed at the top of the dialog
-  void setOptionalMessage(const QString & message);
+  void setOptionalMessage(const QString &message);
   /// Set comma-separated-list of enabled parameter names
-  void addEnabledAndDisableLists(const QStringList & enabled, const QStringList & disabled);
+  void addEnabledAndDisableLists(const QStringList &enabled,
+                                 const QStringList &disabled);
   /// Add an AlgorithmObserver to the algorithm
   void addAlgorithmObserver(Mantid::API::AlgorithmObserver *observer);
 
 protected:
-
   /** @name Member variables. */
   //@{
   /// The algorithm associated with this dialog
   Mantid::API::IAlgorithm_sptr m_algorithm;
 
-  ///The name of the algorithm
+  /// The name of the algorithm
   QString m_algName;
   /// The properties associated with this dialog
   QStringList m_algProperties;
@@ -296,7 +295,7 @@ protected:
   QHash<QString, QString> m_propertyValueMap;
 
   /// A list pointers to the widget for each property
-  QHash<QString, QWidget*> m_tied_properties;
+  QHash<QString, QWidget *> m_tied_properties;
 
   /// A boolean indicating whether this is for a script or not
   bool m_forScript;
@@ -304,10 +303,11 @@ protected:
   QStringList m_python_arguments;
   /// A list of property names that should have their widgets enabled
   QStringList m_enabled;
-  /// A list of property names that the user has requested to be disabled (overrides those in enabled)
+  /// A list of property names that the user has requested to be disabled
+  /// (overrides those in enabled)
   QStringList m_disabled;
   /// The message string to be displayed at the top of the widget; if it exists.
-  QString m_strMessage;  
+  QString m_strMessage;
   /// Whether to keep the dialog box open after alg execution
   bool m_keepOpen;
   /// Is the message string empty or not
@@ -319,27 +319,28 @@ protected:
   bool m_autoParseOnInit;
 
   /// A list of labels to use as validation markers
-  QHash<QString, QLabel*> m_validators;
+  QHash<QString, QLabel *> m_validators;
 
-  /// A map where key = property name; value = the error for this property (i.e. it is not valid).
+  /// A map where key = property name; value = the error for this property (i.e.
+  /// it is not valid).
   QHash<QString, QString> m_errors;
 
   /// A list of property names whose widgets handle their own validation
   QStringList m_noValidation;
 
   /// Store a list of the names of input workspace boxes
-  QVector<QWidget*> m_inputws_opts;
+  QVector<QWidget *> m_inputws_opts;
 
   /// Store a list of output workspace text edits
-  QVector<QLineEdit*> m_outputws_fields;
+  QVector<QLineEdit *> m_outputws_fields;
 
   /// A map to keep track of replace workspace button presses
-  QHash<QPushButton*, int> m_wsbtn_tracker;
+  QHash<QPushButton *, int> m_wsbtn_tracker;
 
-  //the keep open checkbox control
-  QCheckBox* m_keepOpenCheckBox;
+  // the keep open checkbox control
+  QCheckBox *m_keepOpenCheckBox;
 
-  QPushButton* m_okButton, *m_exitButton;
+  QPushButton *m_okButton, *m_exitButton;
 
   /// A list of AlgorithmObservers to add to the algorithm prior to execution
   std::vector<Mantid::API::AlgorithmObserver *> m_observers;
@@ -350,7 +351,6 @@ protected:
   bool m_statusTracked;
   //@}
 };
-
 }
 }
-#endif //MANTIDQT_API_ALGORITHMDIALOG_H_
+#endif // MANTIDQT_API_ALGORITHMDIALOG_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/AlgorithmInputHistory.h b/MantidQt/API/inc/MantidQtAPI/AlgorithmInputHistory.h
index 6add232669d66186d01aae3a4d6b9d79e8de0380..d44602964f2dfb94389f27591942a5bc0ecbad02 100644
--- a/MantidQt/API/inc/MantidQtAPI/AlgorithmInputHistory.h
+++ b/MantidQt/API/inc/MantidQtAPI/AlgorithmInputHistory.h
@@ -9,15 +9,14 @@
 #include <QHash>
 #include <QString>
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
 /** This abstract class deals with the loading and saving of previous algorithm
     property values to/from MantidPlot's QSettings.
 
-    Copyright &copy; 2009-2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009-2012 ISIS Rutherford Appleton Laboratory, NScD Oak
+   Ridge National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -34,8 +33,7 @@ namespace API
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
-class EXPORT_OPT_MANTIDQT_API AbstractAlgorithmInputHistory
-{
+class EXPORT_OPT_MANTIDQT_API AbstractAlgorithmInputHistory {
 public:
   AbstractAlgorithmInputHistory(const AbstractAlgorithmInputHistory &) = delete;
   AbstractAlgorithmInputHistory &
@@ -45,23 +43,26 @@ public:
 
   /// Update the old values that are stored here. Only valid
   /// values are stored here
-  void storeNewValue(const QString & algName, const QPair<QString, QString> & property);
-  
+  void storeNewValue(const QString &algName,
+                     const QPair<QString, QString> &property);
+
   /// Clear values for a particular algorithm
-  void clearAlgorithmInput(const QString & algName);
+  void clearAlgorithmInput(const QString &algName);
+
+  /// Retrieve an old parameter value
+  QString previousInput(const QString &algName, const QString &propName) const;
+
+  /// Set the directory that was accessed when the previous open file dialog was
+  /// used
+  void setPreviousDirectory(const QString &lastdir);
 
-  /// Retrieve an old parameter value 
-  QString previousInput(const QString & algName, const QString & propName) const;
-  
-  /// Set the directory that was accessed when the previous open file dialog was used
-  void setPreviousDirectory(const QString & lastdir);
-  
-  /// Get the directory that was accessed when the previous open file dialog was used
-  const QString & getPreviousDirectory() const;
+  /// Get the directory that was accessed when the previous open file dialog was
+  /// used
+  const QString &getPreviousDirectory() const;
 
   /// Save the values stored here to persistent storage
   void save() const;
-  
+
 protected:
   /// Constructor
   AbstractAlgorithmInputHistory(QString settingsGroup);
@@ -69,24 +70,26 @@ protected:
 private:
   /// Load any values that are available from persistent storage
   void load();
-  
+
   /// A map indexing the algorithm name and a list of property name:value pairs
-  QHash<QString, QHash<QString, QString> > m_lastInput;
-  
+  QHash<QString, QHash<QString, QString>> m_lastInput;
+
   /// The directory that last used by an open file dialog
   QString m_previousDirectory;
-  
-  /// The string denoting the group (in the QSettings) where the algorithm properties are stored
+
+  /// The string denoting the group (in the QSettings) where the algorithm
+  /// properties are stored
   QString m_algorithmsGroup;
-  
+
   /// The string denoting the key for the previous dir storage
   QString m_dirKey;
 };
 
-class EXPORT_OPT_MANTIDQT_API AlgorithmInputHistoryImpl : public AbstractAlgorithmInputHistory
-{
+class EXPORT_OPT_MANTIDQT_API AlgorithmInputHistoryImpl
+    : public AbstractAlgorithmInputHistory {
 private:
-  AlgorithmInputHistoryImpl() : AbstractAlgorithmInputHistory("Mantid/Algorithms") {}
+  AlgorithmInputHistoryImpl()
+      : AbstractAlgorithmInputHistory("Mantid/Algorithms") {}
   ~AlgorithmInputHistoryImpl() override {}
 
 private:
@@ -95,12 +98,13 @@ private:
 
 #ifdef _WIN32
 // this breaks new namespace declaraion rules; need to find a better fix
-  template class EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<AlgorithmInputHistoryImpl>;
+template class EXPORT_OPT_MANTIDQT_API
+    Mantid::Kernel::SingletonHolder<AlgorithmInputHistoryImpl>;
 #endif /* _WIN32 */
-  /// The specific instantiation of the templated type
-  typedef EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<AlgorithmInputHistoryImpl> AlgorithmInputHistory;
-
+/// The specific instantiation of the templated type
+typedef EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<
+    AlgorithmInputHistoryImpl> AlgorithmInputHistory;
 }
 }
 
-#endif //ALGORITHMINPUTHISTORY_H_
+#endif // ALGORITHMINPUTHISTORY_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/AlgorithmPropertiesWidget.h b/MantidQt/API/inc/MantidQtAPI/AlgorithmPropertiesWidget.h
index 92bfaa743d7cd547e9a173e79b96187ffd576e14..50eaaf3e569308ca6d6b259aaf01496d11839207 100644
--- a/MantidQt/API/inc/MantidQtAPI/AlgorithmPropertiesWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/AlgorithmPropertiesWidget.h
@@ -13,116 +13,113 @@
 #include <QtGui/qwidget.h>
 #include <QtGui>
 
+namespace MantidQt {
+namespace API {
 
-namespace MantidQt
-{
-namespace API
-{
+/** Widget that contains dynamically generated
+ * PropertyWidget's for each property of an algorithm,
+ * contained in a scroll area.
 
+  @date 2012-03-09
 
-  /** Widget that contains dynamically generated
-   * PropertyWidget's for each property of an algorithm,
-   * contained in a scroll area.
-    
-    @date 2012-03-09
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  This file is part of Mantid.
 
-    This file is part of Mantid.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API AlgorithmPropertiesWidget : public QWidget {
+  Q_OBJECT
+  Q_PROPERTY(QString algorithmName READ getAlgorithmName WRITE setAlgorithmName)
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_API AlgorithmPropertiesWidget : public QWidget
-  {
-    Q_OBJECT
-    Q_PROPERTY( QString algorithmName READ getAlgorithmName WRITE setAlgorithmName )
+public:
+  AlgorithmPropertiesWidget(QWidget *parent = NULL);
+  ~AlgorithmPropertiesWidget() override;
 
-  public:
-    AlgorithmPropertiesWidget(QWidget * parent = NULL);
-    ~AlgorithmPropertiesWidget() override;
+  void
+  setInputHistory(MantidQt::API::AbstractAlgorithmInputHistory *inputHistory);
 
-    void setInputHistory(MantidQt::API::AbstractAlgorithmInputHistory * inputHistory);
+  void initLayout();
 
-    void initLayout();
+  Mantid::API::IAlgorithm_sptr getAlgorithm();
+  void setAlgorithm(Mantid::API::IAlgorithm_sptr algo);
 
-    Mantid::API::IAlgorithm_sptr  getAlgorithm();
-    void setAlgorithm(Mantid::API::IAlgorithm_sptr algo);
+  QString getAlgorithmName() const;
+  void setAlgorithmName(QString name);
 
-    QString getAlgorithmName() const;
-    void setAlgorithmName(QString name);
+  void addEnabledAndDisableLists(const QStringList &enabled,
+                                 const QStringList &disabled);
 
-    void addEnabledAndDisableLists(const QStringList & enabled, const QStringList & disabled);
+  void hideOrDisableProperties();
 
-    void hideOrDisableProperties();
+  void saveInput();
 
-    void saveInput();
+  /// Each dynamically created PropertyWidget
+  QHash<QString, PropertyWidget *> m_propWidgets;
 
-    /// Each dynamically created PropertyWidget
-    QHash<QString, PropertyWidget*> m_propWidgets;
+  /// Mapping between group and it's dynamically created widget
+  QHash<QString, QGroupBox *> m_groupWidgets;
 
-    /// Mapping between group and it's dynamically created widget
-    QHash<QString, QGroupBox*> m_groupWidgets;
+  /// Viewport containing the grid of property widgets
+  QWidget *m_viewport;
 
-    /// Viewport containing the grid of property widgets
-    QWidget * m_viewport;
+  /// Scroll area containing the viewport
+  QScrollArea *m_scroll;
 
-    /// Scroll area containing the viewport
-    QScrollArea * m_scroll;
+public slots:
+  /// Any property changed
+  void propertyChanged(const QString &pName);
 
-  public slots:
-    /// Any property changed
-    void propertyChanged(const QString & pName);
+  /// Replace WS button was clicked
+  void replaceWSClicked(const QString &propName);
 
-    /// Replace WS button was clicked
-    void replaceWSClicked(const QString & propName);
+private:
+  bool isWidgetEnabled(Mantid::Kernel::Property *property,
+                       const QString &propName) const;
 
-  private:
+  /// Chosen algorithm name
+  QString m_algoName;
 
-    bool isWidgetEnabled(Mantid::Kernel::Property * property, const QString & propName) const;
+  /// Pointer to the algorithm to view
+  Mantid::API::IAlgorithm_sptr m_algo;
 
-    /// Chosen algorithm name
-    QString m_algoName;
+  /// The grid widget containing the input boxes
+  QGridLayout *m_inputGrid;
 
-    /// Pointer to the algorithm to view
-    Mantid::API::IAlgorithm_sptr m_algo;
+  /// The current grid widget for sub-boxes
+  QGridLayout *m_currentGrid;
 
-    /// The grid widget containing the input boxes
-    QGridLayout *m_inputGrid;
+  /// A map where key = property name; value = the error for this property (i.e.
+  /// it is not valid).
+  QHash<QString, QString> m_errors;
 
-    /// The current grid widget for sub-boxes
-    QGridLayout *m_currentGrid;
+  /// A list of property names that are FORCED to stay enabled.
+  QStringList m_enabled;
 
-    /// A map where key = property name; value = the error for this property (i.e. it is not valid).
-    QHash<QString, QString> m_errors;
-
-    /// A list of property names that are FORCED to stay enabled.
-    QStringList m_enabled;
-
-    /// A list of property names that are FORCED to stay disabled.
-    /// e.g. when callid AlgorithmNameDialog()
-    QStringList m_disabled;
-
-    /// History of inputs to the algorithm
-    MantidQt::API::AbstractAlgorithmInputHistory * m_inputHistory;
-
-  };
+  /// A list of property names that are FORCED to stay disabled.
+  /// e.g. when callid AlgorithmNameDialog()
+  QStringList m_disabled;
 
+  /// History of inputs to the algorithm
+  MantidQt::API::AbstractAlgorithmInputHistory *m_inputHistory;
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_ALGORITHMPROPERTIESWIDGET_H_ */
+#endif /* MANTID_API_ALGORITHMPROPERTIESWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/AlgorithmRunner.h b/MantidQt/API/inc/MantidQtAPI/AlgorithmRunner.h
index a1ebe05a85c9f460bb832822a21a156ebdff6f11..fdbe9a4f7d5323ea978abc215392aeeb3cf37841 100644
--- a/MantidQt/API/inc/MantidQtAPI/AlgorithmRunner.h
+++ b/MantidQt/API/inc/MantidQtAPI/AlgorithmRunner.h
@@ -7,87 +7,90 @@
 #include <QObject>
 #include <Poco/NObserver.h>
 
-namespace MantidQt
-{
-namespace API
-{
-  /** The AlgorithmRunner is a QObject that encapsulates
-   * methods for running an algorithm asynchronously (in the background)
-   * and feeds-back to a GUI widget.
-   *
-   * The QObject keeps track of a running algorithm.
-   * Any already-running algorithm is cancelled if it gets started again.
-   * Signals are emitted when the algorithm progresses or finishes.
-   *
-   * TO USE:
-   *  - Create the AlgorithmRunner object.
-   *  - Connect the desired signal(s) to slots on your GUI.
-   *  - Call startAlgorithm() to start.
-    
-    @date 2012-04-23
-
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_API AlgorithmRunner : public QObject
-  {
-    Q_OBJECT
-
-  public:
-    explicit AlgorithmRunner(QObject * parent = 0);
-    ~AlgorithmRunner() override;
-
-    void cancelRunningAlgorithm();
-
-    void startAlgorithm(Mantid::API::IAlgorithm_sptr alg);
-    Mantid::API::IAlgorithm_sptr getAlgorithm() const;
-
-  signals:
-    /// Signal emitted when the algorithm has completed execution/encountered an error
-    void algorithmComplete(bool error);
-
-    /// Signal emitted when the algorithm reports progress
-    void algorithmProgress(double p, const std::string& msg);
-
-  protected:
-
-    /// Algorithm notification handlers
-    void handleAlgorithmFinishedNotification(const Poco::AutoPtr<Mantid::API::Algorithm::FinishedNotification>& pNf);
-    Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::FinishedNotification> m_finishedObserver;
-
-    void handleAlgorithmProgressNotification(const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification>& pNf);
-    Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::ProgressNotification> m_progressObserver;
-
-    void handleAlgorithmErrorNotification(const Poco::AutoPtr<Mantid::API::Algorithm::ErrorNotification>& pNf);
-    Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::ErrorNotification> m_errorObserver;
-
-    /// For the asynchronous call in dynamic rebinning. Holds the result of asyncExecute() algorithm call
-    Poco::ActiveResult<bool> * m_asyncResult;
-
-    /// Reference to the algorithm executing asynchronously.
-    Mantid::API::IAlgorithm_sptr m_asyncAlg;
-
-  };
-
+namespace MantidQt {
+namespace API {
+/** The AlgorithmRunner is a QObject that encapsulates
+ * methods for running an algorithm asynchronously (in the background)
+ * and feeds-back to a GUI widget.
+ *
+ * The QObject keeps track of a running algorithm.
+ * Any already-running algorithm is cancelled if it gets started again.
+ * Signals are emitted when the algorithm progresses or finishes.
+ *
+ * TO USE:
+ *  - Create the AlgorithmRunner object.
+ *  - Connect the desired signal(s) to slots on your GUI.
+ *  - Call startAlgorithm() to start.
+
+  @date 2012-04-23
+
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API AlgorithmRunner : public QObject {
+  Q_OBJECT
+
+public:
+  explicit AlgorithmRunner(QObject *parent = 0);
+  ~AlgorithmRunner() override;
+
+  void cancelRunningAlgorithm();
+
+  void startAlgorithm(Mantid::API::IAlgorithm_sptr alg);
+  Mantid::API::IAlgorithm_sptr getAlgorithm() const;
+
+signals:
+  /// Signal emitted when the algorithm has completed execution/encountered an
+  /// error
+  void algorithmComplete(bool error);
+
+  /// Signal emitted when the algorithm reports progress
+  void algorithmProgress(double p, const std::string &msg);
+
+protected:
+  /// Algorithm notification handlers
+  void handleAlgorithmFinishedNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::FinishedNotification> &pNf);
+  Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::FinishedNotification>
+      m_finishedObserver;
+
+  void handleAlgorithmProgressNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification> &pNf);
+  Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::ProgressNotification>
+      m_progressObserver;
+
+  void handleAlgorithmErrorNotification(
+      const Poco::AutoPtr<Mantid::API::Algorithm::ErrorNotification> &pNf);
+  Poco::NObserver<AlgorithmRunner, Mantid::API::Algorithm::ErrorNotification>
+      m_errorObserver;
+
+  /// For the asynchronous call in dynamic rebinning. Holds the result of
+  /// asyncExecute() algorithm call
+  Poco::ActiveResult<bool> *m_asyncResult;
+
+  /// Reference to the algorithm executing asynchronously.
+  Mantid::API::IAlgorithm_sptr m_asyncAlg;
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_ALGORITHMRUNNER_H_ */
+#endif /* MANTID_API_ALGORITHMRUNNER_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/BatchAlgorithmRunner.h b/MantidQt/API/inc/MantidQtAPI/BatchAlgorithmRunner.h
index f3249a5b985c5012ac718f8f95569f9684fce89c..0e0ac3bd7249b3b946c162c27b9c428ff0b98e43 100644
--- a/MantidQt/API/inc/MantidQtAPI/BatchAlgorithmRunner.h
+++ b/MantidQt/API/inc/MantidQtAPI/BatchAlgorithmRunner.h
@@ -11,111 +11,111 @@
 #include <Poco/NObserver.h>
 #include <Poco/Void.h>
 
-namespace MantidQt
-{
-namespace API
-{
-  /**
-   * Algorithm runner for execution of a queue of algorithms
-
-    @date 2014-08-10
-
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-
-  class BatchNotification : public Poco::Notification
-  {
-  public:
-    BatchNotification(bool inProgress, bool error) : Poco::Notification(),
-      m_inProgress(inProgress), m_error(error) {}
-
-    bool isInProgress() const { return m_inProgress; }
-    bool hasError() const { return m_error; }
-
-  private:
-    bool m_inProgress;
-    bool m_error;
-  };
-
-  class EXPORT_OPT_MANTIDQT_API BatchAlgorithmRunner : public QObject
-  {
-    Q_OBJECT
-
-  public:
-    typedef std::map<std::string, std::string> AlgorithmRuntimeProps;
-    typedef std::pair<Mantid::API::IAlgorithm_sptr, AlgorithmRuntimeProps> ConfiguredAlgorithm;
-
-    explicit BatchAlgorithmRunner(QObject * parent = 0);
-    ~BatchAlgorithmRunner() override;
-
-    /// Adds an algorithm to the execution queue
-    void addAlgorithm(Mantid::API::IAlgorithm_sptr algo, AlgorithmRuntimeProps props = AlgorithmRuntimeProps());
-    /// Clears all algorithms from queue
-    void clearQueue();
-    /// Gets size of queue
-    size_t queueLength();
-
-    /// Executes the batch, waits for the result and returns it
-    bool executeBatch();
-    /// Starts the batch executing and returns immediately
-    void executeBatchAsync();
-
-    /// Sets if the execuion should be stopped if an error is detected
-    void stopOnFailure(bool stopOnFailure);
-
-  signals:
-    /// Emitted when a batch has finished executing
-    void batchComplete(bool error);
-
-  private:
-    /// Implementation of algorithm runner
-    bool executeBatchAsyncImpl(const Poco::Void&);
-    /// Sets up and executes an algorithm
-    bool executeAlgo(ConfiguredAlgorithm algorithm);
-
-    /// Handler for batch completion
-    void handleNotification(const Poco::AutoPtr<BatchNotification>& pNf);
-
-    /// The queue of algorithms to be executed
-    std::deque<ConfiguredAlgorithm> m_algorithms;
-
-    /// The current algorithm being executed
-    Mantid::API::IAlgorithm_sptr m_currentAlgorithm;
-
-    /// If execution should be stopped on algorithm failure
-    bool m_stopOnFailure;
-
-    /// Notification center used to handle notifications from active method
-    mutable Poco::NotificationCenter m_notificationCenter;
-    /// Observer for notifications
-    Poco::NObserver<BatchAlgorithmRunner, BatchNotification> m_notificationObserver;
-
-    /// Active method to run batch runner on separate thread
-    Poco::ActiveMethod<bool, Poco::Void, BatchAlgorithmRunner, Poco::ActiveStarter<BatchAlgorithmRunner>> m_executeAsync;
-    /// Holds result of async execution
-    Poco::ActiveResult<bool> executeAsync();
-
-  };
+namespace MantidQt {
+namespace API {
+/**
+ * Algorithm runner for execution of a queue of algorithms
+
+  @date 2014-08-10
+
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class BatchNotification : public Poco::Notification {
+public:
+  BatchNotification(bool inProgress, bool error)
+      : Poco::Notification(), m_inProgress(inProgress), m_error(error) {}
+
+  bool isInProgress() const { return m_inProgress; }
+  bool hasError() const { return m_error; }
+
+private:
+  bool m_inProgress;
+  bool m_error;
+};
+
+class EXPORT_OPT_MANTIDQT_API BatchAlgorithmRunner : public QObject {
+  Q_OBJECT
+
+public:
+  typedef std::map<std::string, std::string> AlgorithmRuntimeProps;
+  typedef std::pair<Mantid::API::IAlgorithm_sptr, AlgorithmRuntimeProps>
+      ConfiguredAlgorithm;
+
+  explicit BatchAlgorithmRunner(QObject *parent = 0);
+  ~BatchAlgorithmRunner() override;
+
+  /// Adds an algorithm to the execution queue
+  void addAlgorithm(Mantid::API::IAlgorithm_sptr algo,
+                    AlgorithmRuntimeProps props = AlgorithmRuntimeProps());
+  /// Clears all algorithms from queue
+  void clearQueue();
+  /// Gets size of queue
+  size_t queueLength();
+
+  /// Executes the batch, waits for the result and returns it
+  bool executeBatch();
+  /// Starts the batch executing and returns immediately
+  void executeBatchAsync();
+
+  /// Sets if the execuion should be stopped if an error is detected
+  void stopOnFailure(bool stopOnFailure);
+
+signals:
+  /// Emitted when a batch has finished executing
+  void batchComplete(bool error);
+
+private:
+  /// Implementation of algorithm runner
+  bool executeBatchAsyncImpl(const Poco::Void &);
+  /// Sets up and executes an algorithm
+  bool executeAlgo(ConfiguredAlgorithm algorithm);
+
+  /// Handler for batch completion
+  void handleNotification(const Poco::AutoPtr<BatchNotification> &pNf);
+
+  /// The queue of algorithms to be executed
+  std::deque<ConfiguredAlgorithm> m_algorithms;
+
+  /// The current algorithm being executed
+  Mantid::API::IAlgorithm_sptr m_currentAlgorithm;
+
+  /// If execution should be stopped on algorithm failure
+  bool m_stopOnFailure;
+
+  /// Notification center used to handle notifications from active method
+  mutable Poco::NotificationCenter m_notificationCenter;
+  /// Observer for notifications
+  Poco::NObserver<BatchAlgorithmRunner, BatchNotification>
+      m_notificationObserver;
+
+  /// Active method to run batch runner on separate thread
+  Poco::ActiveMethod<bool, Poco::Void, BatchAlgorithmRunner,
+                     Poco::ActiveStarter<BatchAlgorithmRunner>> m_executeAsync;
+  /// Holds result of async execution
+  Poco::ActiveResult<bool> executeAsync();
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_BATCHALGORITHMRUNNER_H_ */
+#endif /* MANTID_API_BATCHALGORITHMRUNNER_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/BoolPropertyWidget.h b/MantidQt/API/inc/MantidQtAPI/BoolPropertyWidget.h
index bee428c8638f93830a8774606366ca40acaff4b5..c2740c228dc5bc69224afd3c310bf996842e7c25 100644
--- a/MantidQt/API/inc/MantidQtAPI/BoolPropertyWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/BoolPropertyWidget.h
@@ -6,57 +6,55 @@
 #include "MantidQtAPI/PropertyWidget.h"
 #include <qcheckbox.h>
 
+namespace MantidQt {
+namespace API {
 
-namespace MantidQt
-{
-namespace API
-{
+/** Set of widgets representing a PropertyWithValue<bool>.
+ *
 
-  /** Set of widgets representing a PropertyWithValue<bool>.
-   *
-    
-    @date 2012-02-16
+  @date 2012-02-16
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport BoolPropertyWidget : public PropertyWidget
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport BoolPropertyWidget : public PropertyWidget {
+  Q_OBJECT
 
-  public:
-    BoolPropertyWidget(Mantid::Kernel::PropertyWithValue<bool> * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
-    ~BoolPropertyWidget() override;
-    QString getValue() const override;
-    void setValueImpl(const QString &value) override;
+public:
+  BoolPropertyWidget(Mantid::Kernel::PropertyWithValue<bool> *prop,
+                     QWidget *parent = NULL, QGridLayout *layout = NULL,
+                     int row = -1);
+  ~BoolPropertyWidget() override;
+  QString getValue() const override;
+  void setValueImpl(const QString &value) override;
 
-    ///@return the main widget of this combo of widgets
-    QWidget *getMainWidget() override { return m_checkBox; }
-
-  protected:
-    /// Checkbox widget
-    QCheckBox * m_checkBox;
-  };
+  ///@return the main widget of this combo of widgets
+  QWidget *getMainWidget() override { return m_checkBox; }
 
+protected:
+  /// Checkbox widget
+  QCheckBox *m_checkBox;
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTID_API_BOOLPROPERTYWIDGET_H_ */
+#endif /* MANTID_API_BOOLPROPERTYWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/DistributionOptions.h b/MantidQt/API/inc/MantidQtAPI/DistributionOptions.h
index 6c6530ec756324f7b826315fdf80c4c037587156..bb53d2802b7e561832779c590a5743181166fce0 100644
--- a/MantidQt/API/inc/MantidQtAPI/DistributionOptions.h
+++ b/MantidQt/API/inc/MantidQtAPI/DistributionOptions.h
@@ -2,17 +2,17 @@
 #define DISTRIBUTIONOPTIONS_H_
 
 /**
-* This file contains declarations of options which control 
+* This file contains declarations of options which control
 * normalization of mantid curves.
 */
 namespace MantidQt {
 
-	// Enumerate how to handle distributions
-	enum DistributionFlag {
-		DistributionDefault = 0, // Use preferences value
-		DistributionTrue,        // Force distribution plotting
-		DistributionFalse        // Disable distribution plotting
-	};
+// Enumerate how to handle distributions
+enum DistributionFlag {
+  DistributionDefault = 0, // Use preferences value
+  DistributionTrue,        // Force distribution plotting
+  DistributionFalse        // Disable distribution plotting
+};
 }
 
-#endif //DISTRIBUTIONOPTIONS_H_
\ No newline at end of file
+#endif // DISTRIBUTIONOPTIONS_H_
\ No newline at end of file
diff --git a/MantidQt/API/inc/MantidQtAPI/DllOption.h b/MantidQt/API/inc/MantidQtAPI/DllOption.h
index c6ffb39d8b688d95b1129c13e43d5e4ef4340052..2d64b43438a4ed64aa4242c227e15d059f4139a0 100644
--- a/MantidQt/API/inc/MantidQtAPI/DllOption.h
+++ b/MantidQt/API/inc/MantidQtAPI/DllOption.h
@@ -4,9 +4,9 @@
 #include "MantidKernel/System.h"
 
 #ifdef IN_MANTIDQT_API
-#define EXPORT_OPT_MANTIDQT_API DLLExport 
+#define EXPORT_OPT_MANTIDQT_API DLLExport
 #else
 #define EXPORT_OPT_MANTIDQT_API DLLImport
 #endif /* IN_MANTIDQT_API */
 
-#endif //MANTIDQT_API_DLLOPTION_H_
+#endif // MANTIDQT_API_DLLOPTION_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h b/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
index f564fc77a94a35caaff12b817e42649339e40e2b..d11d77e47399815c75d8e5029f964ab416411ba8 100644
--- a/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
+++ b/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
@@ -3,20 +3,18 @@
 
 #include <QFileDialog>
 #ifdef Q_OS_DARWIN
-  #include <errno.h>
-  #include <sys/sysctl.h>
+#include <errno.h>
+#include <sys/sysctl.h>
 #endif
 
-
-namespace MantidQt
-{
-namespace API 
-{
-/** 
+namespace MantidQt {
+namespace API {
+/**
     Contains modifications to Qt functions where problems have been found
     on certain operating systems
 
-    Copyright &copy; 2009-2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009-2010 ISIS Rutherford Appleton Laboratory, NScD Oak
+   Ridge National Laboratory & European Spallation Source
     @date 17/09/2010
 
     This file is part of Mantid.
@@ -35,29 +33,36 @@ namespace API
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-struct FileDialogHandler
-{
-  /** The MacOS's native save dialog crashes when running a 10.6 package on 10.8 so this function, which takes
-  *  the same arguments as the Qt function, ensures a nonnative object is used on the Mac when necessary.
+struct FileDialogHandler {
+  /** The MacOS's native save dialog crashes when running a 10.6 package on 10.8
+  * so this function, which takes
+  *  the same arguments as the Qt function, ensures a nonnative object is used
+  * on the Mac when necessary.
   *  If compiled on 10.8 the native will be used
   *  @param parent :: the dialog will be shown centered over this parent widget
-  *  @param caption :: The dialog's caption 
-  *  @param dir :: The file dialog's working directory will be set to dir. If dir includes a file name, the file will be selected
+  *  @param caption :: The dialog's caption
+  *  @param dir :: The file dialog's working directory will be set to dir. If
+  * dir includes a file name, the file will be selected
   *  @param filter :: extensions of files to look for
-  *  @param selectedFilter :: pass a pointer an existing string that will be filled with the extension the user selected
-  *  @param options :: The options argument holds various options about how to run the dialog
+  *  @param selectedFilter :: pass a pointer an existing string that will be
+  * filled with the extension the user selected
+  *  @param options :: The options argument holds various options about how to
+  * run the dialog
   */
-  static QString getSaveFileName(QWidget * parent = 0, const QString & caption = QString(), const QString & dir = QString(), const QString & filter = QString(), QString * selectedFilter = 0, QFileDialog::Options options = 0)
-  {
+  static QString getSaveFileName(QWidget *parent = 0,
+                                 const QString &caption = QString(),
+                                 const QString &dir = QString(),
+                                 const QString &filter = QString(),
+                                 QString *selectedFilter = 0,
+                                 QFileDialog::Options options = 0) {
     options = options | QFileDialog::DontUseNativeDialog;
-    return QFileDialog::getSaveFileName(parent, caption, dir, filter, selectedFilter, options);
+    return QFileDialog::getSaveFileName(parent, caption, dir, filter,
+                                        selectedFilter, options);
   }
-
 };
-
 }
 }
 
-#endif          //MANTIDQT_API_FILEDIALOGHANDLER_H_
+#endif // MANTIDQT_API_FILEDIALOGHANDLER_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/FilePropertyWidget.h b/MantidQt/API/inc/MantidQtAPI/FilePropertyWidget.h
index b4635b309526566f80151373bd9a52645d78651a..11e67b214a0ad4db64fe0d98ff2721825e9da4fe 100644
--- a/MantidQt/API/inc/MantidQtAPI/FilePropertyWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/FilePropertyWidget.h
@@ -9,64 +9,60 @@
 #include "MantidAPI/FileProperty.h"
 #include <qpushbutton.h>
 
+namespace MantidQt {
+namespace API {
 
-namespace MantidQt
-{
-namespace API
-{
+/** Widget for FileProperty, which has a "Browse" button.
 
-  /** Widget for FileProperty, which has a "Browse" button.
-    
-    @date 2012-02-17
+  @date 2012-02-17
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport FilePropertyWidget : public TextPropertyWidget
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport FilePropertyWidget : public TextPropertyWidget {
+  Q_OBJECT
 
-  public:
-    FilePropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
-    ~FilePropertyWidget() override;
+public:
+  FilePropertyWidget(Mantid::Kernel::Property *prop, QWidget *parent = NULL,
+                     QGridLayout *layout = NULL, int row = -1);
+  ~FilePropertyWidget() override;
 
-    static QString openFileDialog(Mantid::Kernel::Property * baseProp);
-    static QStringList openMultipleFileDialog(Mantid::Kernel::Property * baseProp);
+  static QString openFileDialog(Mantid::Kernel::Property *baseProp);
+  static QStringList openMultipleFileDialog(Mantid::Kernel::Property *baseProp);
 
-  public slots:
-    void browseClicked();
+public slots:
+  void browseClicked();
 
-  protected:
-    /// "Browse" button
-    QPushButton * m_browseButton;
+protected:
+  /// "Browse" button
+  QPushButton *m_browseButton;
 
-    /// Is a file property
-    Mantid::API::FileProperty* m_fileProp;
-
-    /// Is a multiple file property
-    Mantid::API::MultipleFileProperty* m_multipleFileProp;
-
-  };
+  /// Is a file property
+  Mantid::API::FileProperty *m_fileProp;
 
+  /// Is a multiple file property
+  Mantid::API::MultipleFileProperty *m_multipleFileProp;
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTID_API_FILEPROPERTYWIDGET_H_ */
+#endif /* MANTID_API_FILEPROPERTYWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/GenericDialog.h b/MantidQt/API/inc/MantidQtAPI/GenericDialog.h
index 78f5f3885cf78f6760edb9893a0765c12dd7b5e5..c335fa97a9eac8b16831aaf59ff93839109bdda5 100644
--- a/MantidQt/API/inc/MantidQtAPI/GenericDialog.h
+++ b/MantidQt/API/inc/MantidQtAPI/GenericDialog.h
@@ -19,19 +19,18 @@ class QSignalMapper;
 class QGridLayout;
 class QLineEdit;
 
-namespace MantidQt
-{
+namespace MantidQt {
 
-namespace API
-{
+namespace API {
 
-/** 
-    This class gives a basic dialog that is not tailored to a particular 
+/**
+    This class gives a basic dialog that is not tailored to a particular
     algorithm.
 
     @date 24/02/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -49,17 +48,15 @@ namespace API
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class GenericDialog : public AlgorithmDialog
-{
-  
+class GenericDialog : public AlgorithmDialog {
+
   Q_OBJECT
 
 public:
-
   // Constructor
-  GenericDialog(QWidget* parent = 0);
+  GenericDialog(QWidget *parent = 0);
   // Destructor
   ~GenericDialog() override;
 
@@ -72,11 +69,9 @@ private:
   void parseInput() override;
 
   /// Widget containing all the PropertyWidgets
-  AlgorithmPropertiesWidget * m_algoPropertiesWidget;
-
+  AlgorithmPropertiesWidget *m_algoPropertiesWidget;
 };
-
 }
 }
 
-#endif //MANTIDQT_API_GENERICDIALOG_H_
+#endif // MANTIDQT_API_GENERICDIALOG_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/GraphOptions.h b/MantidQt/API/inc/MantidQtAPI/GraphOptions.h
index 4640ff0f6f68af51f4c4ff7e904a6b068a5139f0..53e952bde26867e54a3424dcecd25b34577db395 100644
--- a/MantidQt/API/inc/MantidQtAPI/GraphOptions.h
+++ b/MantidQt/API/inc/MantidQtAPI/GraphOptions.h
@@ -5,18 +5,17 @@
  * This file contains declarations of options such as scale types that are
  * shared between the colormaps and instrument window
  */
-namespace GraphOptions
-{
+namespace GraphOptions {
 
 /**
  * Scale type enumeration
  */
-  enum ScaleType { Linear = 0, Log10, Power };
+enum ScaleType { Linear = 0, Log10, Power };
 
-  /**
-   * Axis choice
-   */
-  enum Axis { Left, Right, Bottom, Top };
+/**
+ * Axis choice
+ */
+enum Axis { Left, Right, Bottom, Top };
 }
 
-#endif //MANTIDSCALETYPE_H_
+#endif // MANTIDSCALETYPE_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/HelpWindow.h b/MantidQt/API/inc/MantidQtAPI/HelpWindow.h
index c969645bf22226ae3d9052f80fd65ec24e9aff84..99641c09f2c09b3593aaa77383c79a73da0cf964 100644
--- a/MantidQt/API/inc/MantidQtAPI/HelpWindow.h
+++ b/MantidQt/API/inc/MantidQtAPI/HelpWindow.h
@@ -9,13 +9,12 @@ class QString;
 class QUrl;
 class QWidget;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
 /**
-  Copyright &copy; 2013-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2013-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -35,19 +34,24 @@ namespace API
   File change history is stored at: <https://github.com/mantidproject/mantid>.
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDQT_API HelpWindow
-{
+class EXPORT_OPT_MANTIDQT_API HelpWindow {
 public:
-  static void showPage(QWidget *parent, const std::string & url=std::string());
-  static void showPage(QWidget *parent, const QString & url);
-  static void showPage(QWidget *parent, const QUrl & url);
-  static void showAlgorithm(QWidget *parent, const std::string &name=std::string(), const int version=-1);
-  static void showAlgorithm(QWidget *parent, const QString &name, const int version=-1);
-  static void showConcept(QWidget *parent, const std::string &name=std::string());
+  static void showPage(QWidget *parent, const std::string &url = std::string());
+  static void showPage(QWidget *parent, const QString &url);
+  static void showPage(QWidget *parent, const QUrl &url);
+  static void showAlgorithm(QWidget *parent,
+                            const std::string &name = std::string(),
+                            const int version = -1);
+  static void showAlgorithm(QWidget *parent, const QString &name,
+                            const int version = -1);
+  static void showConcept(QWidget *parent,
+                          const std::string &name = std::string());
   static void showConcept(QWidget *parent, const QString &name);
-  static void showFitFunction(QWidget *parent, const std::string &name=std::string());
+  static void showFitFunction(QWidget *parent,
+                              const std::string &name = std::string());
   static void showCustomInterface(QWidget *parent, const QString &name);
-  static void showCustomInterface(QWidget *parent, const std::string &name=std::string());
+  static void showCustomInterface(QWidget *parent,
+                                  const std::string &name = std::string());
 };
 } // namespace API
 } // namespace MantidQt
diff --git a/MantidQt/API/inc/MantidQtAPI/InterfaceFactory.h b/MantidQt/API/inc/MantidQtAPI/InterfaceFactory.h
index 7fce6d1c919424feff3994a28bb8a4cbe8cf98dd..f57fbe104c34af08aff6e43307ebcb14b7d85666 100644
--- a/MantidQt/API/inc/MantidQtAPI/InterfaceFactory.h
+++ b/MantidQt/API/inc/MantidQtAPI/InterfaceFactory.h
@@ -65,7 +65,7 @@ private:
   /// Private Constructor for singleton class
   AlgorithmDialogFactoryImpl() = default;
 
-  ///Private Destructor
+  /// Private Destructor
   ~AlgorithmDialogFactoryImpl() override = default;
 };
 
@@ -141,7 +141,7 @@ private:
 
   /// Private Constructor for singleton class
   UserSubWindowFactoryImpl();
-  ///Private Destructor
+  /// Private Destructor
   ~UserSubWindowFactoryImpl() override = default;
   /// Try to create a sub window from the list of aliases for an interface
   UserSubWindow *createFromAlias(const std::string &name) const;
diff --git a/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h b/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
index b86e753ec4f83b4bae4526373638601f4416e2af..8e17e76c44122685bc4be38ad1e3f6fae49fea17 100644
--- a/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
+++ b/MantidQt/API/inc/MantidQtAPI/InterfaceManager.h
@@ -20,21 +20,16 @@ class QWidget;
 //----------------------------------
 // Mantid forward declarations
 //----------------------------------
-namespace Mantid 
-{
-namespace API
-{
-  class IAlgorithm;
+namespace Mantid {
+namespace API {
+class IAlgorithm;
 }
-
 }
 
 // Top level namespace for this library
-namespace MantidQt
-{
+namespace MantidQt {
 
-namespace API
-{
+namespace API {
 
 //----------------------------------
 // Forward declarations
@@ -44,14 +39,17 @@ class UserSubWindow;
 class VatesViewerInterface;
 class MantidHelpInterface;
 
-/** 
-    This class is responsible for creating the correct dialog for an algorithm. If 
-    no specialized version is registered for that algorithm then the default is created
-    
+/**
+    This class is responsible for creating the correct dialog for an algorithm.
+   If
+    no specialized version is registered for that algorithm then the default is
+   created
+
     @author Martyn Gigg, Tessella Support Services plc
     @date 24/02/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -70,28 +68,32 @@ class MantidHelpInterface;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_API InterfaceManager
-{
+class EXPORT_OPT_MANTIDQT_API InterfaceManager {
 
 public:
-  
   /// Create a new instance of the correct type of AlgorithmDialog
-  AlgorithmDialog* createDialog(boost::shared_ptr<Mantid::API::IAlgorithm> alg, QWidget* parent = 0,
-        bool forScript = false, const QHash<QString,QString> & presetValues = (QHash<QString,QString>()),
-        const QString & optional_msg = QString(), const QStringList & enabled = QStringList(),
-        const QStringList & disabled = QStringList());
+  AlgorithmDialog *createDialog(
+      boost::shared_ptr<Mantid::API::IAlgorithm> alg, QWidget *parent = 0,
+      bool forScript = false,
+      const QHash<QString, QString> &presetValues = (QHash<QString, QString>()),
+      const QString &optional_msg = QString(),
+      const QStringList &enabled = QStringList(),
+      const QStringList &disabled = QStringList());
 
   /// Create an algorithm dialog for a given name and version
-  AlgorithmDialog* createDialogFromName(const QString& algorithmName, const int version = -1,
-                                        QWidget* parent = 0, bool forScript = false,
-                                        const QHash<QString,QString> & presetValues = (QHash<QString,QString>()),
-                                        const QString & optionalMsg = QString(), const QStringList & enabled = QStringList(),
-                                        const QStringList & disabled = QStringList());
+  AlgorithmDialog *createDialogFromName(
+      const QString &algorithmName, const int version = -1, QWidget *parent = 0,
+      bool forScript = false,
+      const QHash<QString, QString> &presetValues = (QHash<QString, QString>()),
+      const QString &optionalMsg = QString(),
+      const QStringList &enabled = QStringList(),
+      const QStringList &disabled = QStringList());
 
   /// Create a new instance of the correct type of UserSubWindow
-  UserSubWindow* createSubWindow(const QString & interface_name, QWidget* parent = 0);
+  UserSubWindow *createSubWindow(const QString &interface_name,
+                                 QWidget *parent = 0);
 
   /**
    * Function that instantiates the Vates simple user interface.
@@ -102,7 +104,8 @@ public:
    * Registration function for the Vates simple interface factory.
    * @param factory the factory instance
    */
-  static void registerVatesGuiFactory(Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *factory);
+  static void registerVatesGuiFactory(
+      Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *factory);
 
   /**
    * Function that instantiates the help window.
@@ -133,7 +136,8 @@ public:
    * Registration function for the help window factory.
    * @param factory the factory instance
    */
-  static void registerHelpWindowFactory(Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *factory);
+  static void registerHelpWindowFactory(
+      Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *factory);
 
   /// The keys associated with UserSubWindow classes
   QStringList getUserSubWindowKeys() const;
@@ -141,38 +145,39 @@ public:
   /// Getter for vates libraries availablity
   static bool hasVatesLibraries();
 
-  ///Constructor
+  /// Constructor
   InterfaceManager();
-  ///Destructor
+  /// Destructor
   virtual ~InterfaceManager();
 
 private:
   /// Handle to the Vates simple user interface factory
-  static Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *m_vatesGuiFactory;
+  static Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *
+      m_vatesGuiFactory;
   /// Handle to the help window factory
-  static Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *m_helpViewer;
+  static Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *
+      m_helpViewer;
 };
-
 }
 }
 
 /*
  * Used to register Vates GUI
  */
-#define REGISTER_VATESGUI(TYPE) \
-  namespace { \
-  Mantid::Kernel::RegistrationHelper \
-  register_vatesgui \
-  (((MantidQt::API::InterfaceManager::registerVatesGuiFactory \
-  (new Mantid::Kernel::Instantiator<TYPE, VatesViewerInterface>())), 0)); \
-}
+#define REGISTER_VATESGUI(TYPE)                                                \
+  namespace {                                                                  \
+  Mantid::Kernel::RegistrationHelper register_vatesgui(                        \
+      ((MantidQt::API::InterfaceManager::registerVatesGuiFactory(              \
+           new Mantid::Kernel::Instantiator<TYPE, VatesViewerInterface>())),   \
+       0));                                                                    \
+  }
 
 /// Used to register help window
-#define REGISTER_HELPWINDOW(TYPE) \
-  namespace { \
-  Mantid::Kernel::RegistrationHelper \
-  register_helpviewer \
-  (((MantidQt::API::InterfaceManager::registerHelpWindowFactory \
-  (new Mantid::Kernel::Instantiator<TYPE, MantidHelpInterface>())), 0)); \
-}
-#endif //MANTIDQT_API_DIALOGMANAGER
+#define REGISTER_HELPWINDOW(TYPE)                                              \
+  namespace {                                                                  \
+  Mantid::Kernel::RegistrationHelper register_helpviewer(                      \
+      ((MantidQt::API::InterfaceManager::registerHelpWindowFactory(            \
+           new Mantid::Kernel::Instantiator<TYPE, MantidHelpInterface>())),    \
+       0));                                                                    \
+  }
+#endif // MANTIDQT_API_DIALOGMANAGER
diff --git a/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h b/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
index 527fbc5afd8f4e978d16a4f9c7dde2c8b33917d6..74b61d4a1489d4e193545907c4d949b6fccbbd06 100644
--- a/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
+++ b/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
@@ -5,25 +5,22 @@
 #include "ui_ManageUserDirectories.h"
 #include "DllOption.h"
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
-class EXPORT_OPT_MANTIDQT_API ManageUserDirectories : public QDialog
-{
+class EXPORT_OPT_MANTIDQT_API ManageUserDirectories : public QDialog {
   Q_OBJECT
 
 public:
   ManageUserDirectories(QWidget *parent = 0);
   ~ManageUserDirectories() override;
-  static void openUserDirsDialog(QWidget * parent);
+  static void openUserDirsDialog(QWidget *parent);
 
 private:
   virtual void initLayout();
   void loadProperties();
   void saveProperties();
-  QListWidget* listWidget();
+  QListWidget *listWidget();
 
 private slots:
   void helpClicked();
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidAlgorithmMetatype.h b/MantidQt/API/inc/MantidQtAPI/MantidAlgorithmMetatype.h
index 05700958ae4c56dfc749ad90af2ef743af1cab99..33f9da36610eccb189efd1e085eaede38eaaa984 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidAlgorithmMetatype.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidAlgorithmMetatype.h
@@ -6,11 +6,11 @@
 
 /**
 
- Declare Qt metatype for IAlgorithm_sptr to allow its direct use with signals and slots.
+ Declare Qt metatype for IAlgorithm_sptr to allow its direct use with signals
+ and slots.
 
  */
 
 Q_DECLARE_METATYPE(Mantid::API::IAlgorithm_sptr)
 
-
 #endif /* MANTIDALGORITHMMETATYPE_H */
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h b/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
index 6e3396f7c8a0f44459cde4d4702ac1888739ef64..ad110600301e4da2a9e78a221db1ea91238657a1 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidColorMap.h
@@ -10,48 +10,49 @@
 #include "MantidQtAPI/GraphOptions.h"
 #include "DllOption.h"
 
-
 /**
-   The class inherits from QwtColorMap and implements reading a color color map from a file. 
-   There is also a mode which indicates the scale type. 
+   The class inherits from QwtColorMap and implements reading a color color map
+   from a file.
+   There is also a mode which indicates the scale type.
+
+   Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
-   Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-   
    This file is part of Mantid.
-   
+
    Mantid is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    Mantid is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-   
+
    File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-class EXPORT_OPT_MANTIDQT_API MantidColorMap : public QwtColorMap
-{
+class EXPORT_OPT_MANTIDQT_API MantidColorMap : public QwtColorMap {
 
 public:
   MantidColorMap();
-  explicit MantidColorMap(const QString & filename, GraphOptions::ScaleType type);
+  explicit MantidColorMap(const QString &filename,
+                          GraphOptions::ScaleType type);
   ~MantidColorMap() override;
   QwtColorMap *copy() const override;
 
   void changeScaleType(GraphOptions::ScaleType type);
 
-  void setNthPower(double nth_power){m_nth_power = nth_power;};
+  void setNthPower(double nth_power) { m_nth_power = nth_power; };
+
+  double getNthPower() const { return m_nth_power; };
 
-  double getNthPower() const {return m_nth_power;};
+  bool loadMap(const QString &filename);
 
-  bool loadMap(const QString & filename);
-  
-  static QString loadMapDialog(QString previousFile, QWidget * parent);
+  static QString loadMapDialog(QString previousFile, QWidget *parent);
 
   void setNanColor(int r, int g, int b);
 
@@ -70,52 +71,42 @@ public:
    * Retrieve the scale type
    * @returns the current scale type
    */
-  GraphOptions::ScaleType getScaleType() const
-  {
-    return m_scale_type;
-  }
+  GraphOptions::ScaleType getScaleType() const { return m_scale_type; }
 
-   /**
-   * Retrieve the map name
-   * @returns the map name
-   */
-  QString getName() const
-  {
-    return m_name;
-  }
+  /**
+  * Retrieve the map name
+  * @returns the map name
+  */
+  QString getName() const { return m_name; }
 
   /**
    * Retrieve the map name
    * @returns the map name
    */
-  QString getFilePath() const
-  {
-    return m_path;
-  }
+  QString getFilePath() const { return m_path; }
 
   /**
    * Get the number of colors in this map
    */
-  inline unsigned char getTopCIndex() const
-  {
+  inline unsigned char getTopCIndex() const {
     return static_cast<unsigned char>(m_num_colors - 1);
   }
-  
-  /** 
+
+  /**
    * The maximum number of colors that any color map is allowed to use
    */
-  static unsigned char getLargestAllowedCIndex()
-  {
+  static unsigned char getLargestAllowedCIndex() {
     return static_cast<unsigned char>(255);
   }
 
 private:
-
   /// The scale choice
   mutable GraphOptions::ScaleType m_scale_type;
 
-  /// An array of shared pointers to objects that define how the color should be painted on
-  /// an OpenGL surface. QVector objects are implicitly shared so offer better performance than
+  /// An array of shared pointers to objects that define how the color should be
+  /// painted on
+  /// an OpenGL surface. QVector objects are implicitly shared so offer better
+  /// performance than
   /// standard vectors
   QVector<QRgb> m_colors;
 
@@ -128,16 +119,13 @@ private:
   /// Cached NAN value
   double m_nan;
 
-  ///the name of the color map
+  /// the name of the color map
   QString m_name;
 
-  ///the path to the map file
+  /// the path to the map file
   QString m_path;
 
   double m_nth_power;
-
 };
 
-
-
-#endif //MANTIDCOLORMAP_H_
+#endif // MANTIDCOLORMAP_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidDialog.h b/MantidQt/API/inc/MantidQtAPI/MantidDialog.h
index 1b3de01a8f561a950f1de0ebb55ffb45d77db5fd..7263467b1e9309928e51529147d5cd50bc79d56c 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidDialog.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidDialog.h
@@ -13,16 +13,15 @@
 // Qt Forward declarations
 //----------------------------------
 
-//Top-level namespace for this library
-namespace MantidQt
-{
+// Top-level namespace for this library
+namespace MantidQt {
 
-namespace API 
-{
+namespace API {
 
-/** 
-    Dialog derived from this class can capture and handle exceptions raised in 
-    its event handlers. To be able to do this override QAplication::notify method:
+/**
+    Dialog derived from this class can capture and handle exceptions raised in
+    its event handlers. To be able to do this override QAplication::notify
+   method:
 
         bool MyApplication::notify( QObject * receiver, QEvent * event )
         {
@@ -36,7 +35,7 @@ namespace API
                 if (MantidQt::API::MantidDialog::handle(receiver,e))
                     return true; // stops event propagation
                 else
-                   // do somethig else ... 
+                   // do somethig else ...
             }
 
             return res;
@@ -47,7 +46,8 @@ namespace API
     @author Roman Tolchenov, Tessella plc
     @date 24/04/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -65,40 +65,38 @@ namespace API
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_API MantidDialog : public QDialog
-{
-  
+class EXPORT_OPT_MANTIDQT_API MantidDialog : public QDialog {
+
   Q_OBJECT
 
 public:
-
   /// DefaultConstructor
-  MantidDialog(QWidget* parent = 0);
+  MantidDialog(QWidget *parent = 0);
   /// Destructor
   ~MantidDialog() override;
 
   /// Handles the exception caught in an event handler.
-  static bool handle( QObject* receiver, const std::exception& e );
-
+  static bool handle(QObject *receiver, const std::exception &e);
 
 signals:
-  void runAsPythonScript(const QString& code, bool);
+  void runAsPythonScript(const QString &code, bool);
 
 protected:
-  /// Run python code that is passed to it and, optionally, return anything it wrote to standard output as a string
-  QString runPythonCode(const QString & code, bool no_output = false);
+  /// Run python code that is passed to it and, optionally, return anything it
+  /// wrote to standard output as a string
+  QString runPythonCode(const QString &code, bool no_output = false);
 
   /// Override this method to handle an exception in a derived class.
-  virtual void handleException( const std::exception& e );
+  virtual void handleException(const std::exception &e);
 
 private:
-  /// This object implements the runPythonCode() function, by emitting the code as a runAsPythonScript signal
+  /// This object implements the runPythonCode() function, by emitting the code
+  /// as a runAsPythonScript signal
   PythonRunner m_pyRunner;
 };
-
 }
 }
 
-#endif //MANTIDQT_API_MANTIDDIALOG_H_
+#endif // MANTIDQT_API_MANTIDDIALOG_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h b/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
index 6256b3444067581968a15cb826a9de1fa5403a06..9b5d06783d340a65a59aea4feeeeccc1c368ea60 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidHelpInterface.h
@@ -8,17 +8,17 @@
 class QString;
 class QUrl;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
 /**
  *
-  This class is an interface for the central widget for handling VATES visualization
+  This class is an interface for the central widget for handling VATES
+ visualization
   operations. Its main use is for the plugin mode operation of the viewer.
 
-  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -38,8 +38,7 @@ namespace API
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDQT_API MantidHelpInterface : public QWidget
-{
+class EXPORT_OPT_MANTIDQT_API MantidHelpInterface : public QWidget {
   Q_OBJECT
 public:
   /// Default constructor
@@ -47,16 +46,17 @@ public:
   /// Default destructor.
   ~MantidHelpInterface() override;
 
-  virtual void showPage(const std::string & url=std::string());
-  virtual void showPage(const QString & url);
-  virtual void showPage(const QUrl & url);
-  virtual void showWikiPage(const std::string &page=std::string());
+  virtual void showPage(const std::string &url = std::string());
+  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 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 std::string &name = std::string());
   virtual void showFitFunction(const QString &name);
   virtual void showCustomInterface(const std::string &name);
   virtual void showCustomInterface(const QString &name);
@@ -65,7 +65,6 @@ public slots:
   /// Perform any clean up on main window shutdown
   virtual void shutdown();
 };
-
 }
 }
 
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidQwtIMDWorkspaceData.h b/MantidQt/API/inc/MantidQtAPI/MantidQwtIMDWorkspaceData.h
index cf4add27d5f27ae2bde1566c955e3a240aee555f..10731f750d655f101f45b04184b6346dd2b3f37a 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidQwtIMDWorkspaceData.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidQwtIMDWorkspaceData.h
@@ -13,26 +13,28 @@
  * It implements the QwtData interface.
  *
  */
-class EXPORT_OPT_MANTIDQT_API MantidQwtIMDWorkspaceData : public MantidQwtWorkspaceData
-{
+class EXPORT_OPT_MANTIDQT_API MantidQwtIMDWorkspaceData
+    : public MantidQwtWorkspaceData {
 public:
-
   /// For PlotAxisChoice, auto-determine it
   static const int PlotAuto = -2;
   /// For PlotAxisChoice, distance from start of line
   static const int PlotDistance = -1;
 
-  MantidQwtIMDWorkspaceData(Mantid::API::IMDWorkspace_const_sptr workspace, const bool logScale,
-      Mantid::Kernel::VMD start = Mantid::Kernel::VMD(), Mantid::Kernel::VMD end = Mantid::Kernel::VMD(),
+  MantidQwtIMDWorkspaceData(
+      Mantid::API::IMDWorkspace_const_sptr workspace, const bool logScale,
+      Mantid::Kernel::VMD start = Mantid::Kernel::VMD(),
+      Mantid::Kernel::VMD end = Mantid::Kernel::VMD(),
       Mantid::API::MDNormalization normalize = Mantid::API::NoNormalization,
       bool isDistribution = false);
 
-  MantidQwtIMDWorkspaceData(const MantidQwtIMDWorkspaceData& data);
-  MantidQwtIMDWorkspaceData &operator=(const MantidQwtIMDWorkspaceData &) ;
+  MantidQwtIMDWorkspaceData(const MantidQwtIMDWorkspaceData &data);
+  MantidQwtIMDWorkspaceData &operator=(const MantidQwtIMDWorkspaceData &);
   ~MantidQwtIMDWorkspaceData() override;
 
   QwtData *copy() const override;
-  virtual MantidQwtIMDWorkspaceData* copy(Mantid::API::IMDWorkspace_sptr workspace) const;
+  virtual MantidQwtIMDWorkspaceData *
+  copy(Mantid::API::IMDWorkspace_sptr workspace) const;
 
   size_t size() const override;
   size_t esize() const override;
@@ -54,7 +56,6 @@ protected:
   double getEX(size_t i) const override;
 
 private:
-
   void cacheLinePlot();
   void calculateMinMax();
   void choosePlotAxis();
@@ -94,8 +95,9 @@ private:
   /// Original workspace (for purposes of showing alternative coordinates)
   boost::weak_ptr<const Mantid::API::IMDWorkspace> m_originalWorkspace;
 
-  /// Optional coordinate transformation to go from distance on line to another coordinate
-  Mantid::API::CoordTransform * m_transform;
+  /// Optional coordinate transformation to go from distance on line to another
+  /// coordinate
+  Mantid::API::CoordTransform *m_transform;
 
   /// Choice of which X axis to plot.
   int m_plotAxis;
@@ -104,6 +106,5 @@ private:
   /// This will correspond to -1 (distance)
   /// or the index into the original workspace dimensions
   int m_currentPlotAxis;
-
 };
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidQwtWorkspaceData.h b/MantidQt/API/inc/MantidQtAPI/MantidQwtWorkspaceData.h
index a7f85ddfe72a6733791e719380337ac4dcda9c93..e6bf6801417f5c9f6c15a986d3d620ea57fd6feb 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidQwtWorkspaceData.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidQwtWorkspaceData.h
@@ -42,7 +42,7 @@ class MatrixWorkspace;
 class EXPORT_OPT_MANTIDQT_API MantidQwtWorkspaceData : public QwtData {
 public:
   MantidQwtWorkspaceData(bool logScaleY);
-  MantidQwtWorkspaceData(const MantidQwtWorkspaceData& data);
+  MantidQwtWorkspaceData(const MantidQwtWorkspaceData &data);
   MantidQwtWorkspaceData &operator=(const MantidQwtWorkspaceData &);
 
   virtual QString getXAxisLabel() const = 0;
@@ -63,11 +63,11 @@ public:
   virtual void setYOffset(const double y);
   virtual void setWaterfallPlot(bool on);
   virtual bool isWaterfallPlot() const;
-  double offsetY() const {return m_offsetY;}
+  double offsetY() const { return m_offsetY; }
 
   void calculateYMinAndMax(/*const std::vector<double> &yvalues*/) const;
-protected:
 
+protected:
   virtual double getX(size_t i) const = 0;
   virtual double getY(size_t i) const = 0;
   virtual double getE(size_t i) const = 0;
diff --git a/MantidQt/API/inc/MantidQtAPI/MantidWidget.h b/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
index 13122f3b229598744b04b2a61cbc7ffbbe1e2a17..cf61ee531ce1f442e8c6b7eb3ba9ad3415f1ec23 100644
--- a/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
@@ -6,70 +6,70 @@
 #include <QWidget>
 #include <QVariant>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /** 
-    This is the base class all customised widgets that do not wish to be tied
-    to a specific Mantid algorithm but rather customised for user's requirements.
-    
-    The virtual function getUserInput() must be implemented to return what the widget considers
-    as user input.
+namespace MantidQt {
+namespace API {
+/**
+This is the base class all customised widgets that do not wish to be tied
+to a specific Mantid algorithm but rather customised for user's requirements.
 
-    @author Martyn Gigg, Tessella Support Services plc
-    @date 18/03/2009
+The virtual function getUserInput() must be implemented to return what the
+widget considers
+as user input.
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+@author Martyn Gigg, Tessella Support Services plc
+@date 18/03/2009
 
-    This file is part of Mantid.
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_API MantidWidget : public QWidget
-    {
-    Q_OBJECT
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    public:
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API MantidWidget : public QWidget {
+  Q_OBJECT
 
-    /// Returns a QVariant containing what the widget classes as user input so that
-    /// input can be returned through a common interface.
-    virtual QVariant getUserInput() const { return QVariant(); }
-    /**
-     * Sets a value on a mantid widget through a common interface
-     * @param value :: The value as a QVariant
-     */
-    virtual void setUserInput(const QVariant & value)  { Q_UNUSED(value); }
+public:
+  /// Returns a QVariant containing what the widget classes as user input so
+  /// that
+  /// input can be returned through a common interface.
+  virtual QVariant getUserInput() const { return QVariant(); }
+  /**
+   * Sets a value on a mantid widget through a common interface
+   * @param value :: The value as a QVariant
+   */
+  virtual void setUserInput(const QVariant &value) { Q_UNUSED(value); }
 
-    signals:
-      void runAsPythonScript(const QString& code, bool);
+signals:
+  void runAsPythonScript(const QString &code, bool);
 
-    protected:
-      /// Default constructor
-      MantidWidget(QWidget *parent = NULL);
-      /// Run python code that is passed to it and, optionally, return 
-      /// anything it wrote to standard output as a string
-      QString runPythonCode(const QString & code, bool no_output = false);
+protected:
+  /// Default constructor
+  MantidWidget(QWidget *parent = NULL);
+  /// Run python code that is passed to it and, optionally, return
+  /// anything it wrote to standard output as a string
+  QString runPythonCode(const QString &code, bool no_output = false);
 
-    private:
-      /// This object implements the runPythonCode() function, by emitting the code as a runAsPythonScript signal
-      PythonRunner m_pyRunner;
-    };
-  }
+private:
+  /// This object implements the runPythonCode() function, by emitting the code
+  /// as a runAsPythonScript signal
+  PythonRunner m_pyRunner;
+};
+}
 }
 
-#endif //MANTIDQTAPI_MANTIDWIDGET_H_
+#endif // MANTIDQTAPI_MANTIDWIDGET_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/MdConstants.h b/MantidQt/API/inc/MantidQtAPI/MdConstants.h
index 942967368fd8d81972f1a895b64be2a70aa54e29..deab55060218b5ded48af6a33cd428d4d4589f59 100644
--- a/MantidQt/API/inc/MantidQtAPI/MdConstants.h
+++ b/MantidQt/API/inc/MantidQtAPI/MdConstants.h
@@ -6,103 +6,100 @@
 #include <QColor>
 #include <QStringList>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /**
-      *
-      This class is a collection of constants and keys used for the VSI.
+namespace MantidQt {
+namespace API {
+/**
+  *
+  This class is a collection of constants and keys used for the VSI.
 
-      @date 6/1/2015
+  @date 6/1/2015
 
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-      This file is part of Mantid.
+  This file is part of Mantid.
 
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-      */
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
 
-    class EXPORT_OPT_MANTIDQT_API MdConstants
-    {
-      public:
+class EXPORT_OPT_MANTIDQT_API MdConstants {
+public:
+  // MD ParaView plugin names
+  static const QString MantidParaViewSplatterPlot;
+  static const QString MantidParaViewSpecialCoordinates;
+  static const QString MDPeaksFilter;
+  static const QString MantidParaViewPeaksFilter;
+  static const QString PeakDimensions;
+  static const QString PeaksWorkspace;
+  static const QString Delimiter;
+  static const QString WorkspaceName;
+  static const QString ProbePoint;
+  static const QString Threshold;
 
-        // MD ParaView plugin names
-        static const QString MantidParaViewSplatterPlot;
-        static const QString MantidParaViewSpecialCoordinates;
-        static const QString MDPeaksFilter;
-        static const QString MantidParaViewPeaksFilter;
-        static const QString PeakDimensions;
-        static const QString PeaksWorkspace;
-        static const QString Delimiter;
-        static const QString WorkspaceName;
-        static const QString ProbePoint;
-        static const QString Threshold;
+  MdConstants();
 
-        MdConstants();
+  ~MdConstants();
 
-        ~MdConstants();
+  /**
+   * Initialize constants which are required to store and persist MD settings.
+   */
+  void initializeSettingsConstants();
 
-        /**
-         * Initialize constants which are required to store and persist MD settings.
-         */
-        void initializeSettingsConstants();
+  /**
+   * Initialize constants which are required for the view
+   */
+  void initializeViewConstants();
 
-        /**
-         * Initialize constants which are required for the view
-         */
-        void initializeViewConstants();
+  QString getGeneralMdColorMap() const;
 
-        QString getGeneralMdColorMap() const;
+  QColor getDefaultBackgroundColor() const;
 
-        QColor getDefaultBackgroundColor() const;
+  QStringList getVsiColorMaps() const;
 
-        QStringList getVsiColorMaps() const;
+  QString getStandardView() const;
 
-        QString getStandardView() const;
+  QString getMultiSliceView() const;
 
-        QString getMultiSliceView() const;
+  QString getThreeSliceView() const;
 
-        QString getThreeSliceView() const;
+  QString getSplatterPlotView() const;
 
-        QString getSplatterPlotView() const;
+  QString getTechniqueDependence() const;
 
-        QString getTechniqueDependence() const;
-        
-        double getColorScaleStandardMax();
+  double getColorScaleStandardMax();
 
-        QStringList getAllInitialViews() const;
-        
-        double getLogScaleDefaultValue();
+  QStringList getAllInitialViews() const;
 
-      private:
-        QString m_generalMdColorMap;
-        QColor m_defaultBackgroundColor;
-        QStringList m_vsiColorMaps;
-        QString m_standardView;
-        QString m_multiSliceView;
-        QString m_threeSliceView;
-        QString m_splatterPlotView;
-        QString m_techniqueDependence;
+  double getLogScaleDefaultValue();
 
-        const double m_colorScaleStandardMax;
-        const double m_logScaleDefaultValue;
-    };
-  }
+private:
+  QString m_generalMdColorMap;
+  QColor m_defaultBackgroundColor;
+  QStringList m_vsiColorMaps;
+  QString m_standardView;
+  QString m_multiSliceView;
+  QString m_threeSliceView;
+  QString m_splatterPlotView;
+  QString m_techniqueDependence;
+
+  const double m_colorScaleStandardMax;
+  const double m_logScaleDefaultValue;
+};
+}
 }
 
-#endif 
+#endif
diff --git a/MantidQt/API/inc/MantidQtAPI/MdPlottingCmapsProvider.h b/MantidQt/API/inc/MantidQtAPI/MdPlottingCmapsProvider.h
index f22febfc8caba14796ae67b91c28325e49dd621a..fb4cc4e23a660ca5eec5bf5a9c6c07299f29d8a7 100644
--- a/MantidQt/API/inc/MantidQtAPI/MdPlottingCmapsProvider.h
+++ b/MantidQt/API/inc/MantidQtAPI/MdPlottingCmapsProvider.h
@@ -7,77 +7,86 @@
 
 class QStringList;
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /**
-      *
-      This helper class allows for reading and processing the names of the available MD color map files
-
-      @date 7/1/2015
-
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-      */
-
-    class EXPORT_OPT_MANTIDQT_API MdPlottingCmapsProvider
-    {
-      public:
-        MdPlottingCmapsProvider();
-
-        ~MdPlottingCmapsProvider();
-
-        /**
-         * Get the name of all available color maps for general MD plotting.
-         * @param colorMapNames Reference to a list with the names of the color maps.
-         * @param colorMapFiles Reference to a corresponding list with the file paths for the color maps.
-         */
-        void getColorMapsForMdPlotting(QStringList& colorMapNames, QStringList& colorMapFiles);
-
-        /**
-         * Get the name of all available color maps for the VSI (at least the ones stored in files).
-         * @param colorMapNames Reference to a list with the names of the color maps.
-         */
-        void getColorMapsForVSI(QStringList& colorMapNames);
-
-      private:
-        /** 
-         * Gets all files from directory of a given file type.
-         * @param colorMapNames Reference to a list of color map names.
-         * @param colorMapFiles Reference to a list of file paths for the corresponding color maps.
-         * @param colorMapDirectory Directory where the color maps are stored.
-         * @param fileType suffix of the desired files.
-         */
-        void appendAllFileNamesForFileType(QStringList& colorMapNames, QStringList& colorMapFiles, QString colorMapDirectory, QString fileType);
-
-        /**
-         * Compare the colormap names of the Slice Viewer and the VSI and extract all indicees of the list of Slice Viewer color maps
-         * which also exist in the list of the VSI color maps.
-         * @param colorMapNamesSliceViewer A list of color maps of the Slice Viewer.
-         * @param colorMapNamesVsi A list of color maps for the VSI.
-         * @returns A vector of indices for the slice viewer list.
-         */
-        std::vector<int> getSliceViewerIndicesForCommonColorMaps(QStringList colorMapNamesSliceViewer,QStringList colorMapNamesVsi);
-    };
-  }
+namespace MantidQt {
+namespace API {
+/**
+  *
+  This helper class allows for reading and processing the names of the available
+  MD color map files
+
+  @date 7/1/2015
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
+
+class EXPORT_OPT_MANTIDQT_API MdPlottingCmapsProvider {
+public:
+  MdPlottingCmapsProvider();
+
+  ~MdPlottingCmapsProvider();
+
+  /**
+   * Get the name of all available color maps for general MD plotting.
+   * @param colorMapNames Reference to a list with the names of the color maps.
+   * @param colorMapFiles Reference to a corresponding list with the file paths
+   * for the color maps.
+   */
+  void getColorMapsForMdPlotting(QStringList &colorMapNames,
+                                 QStringList &colorMapFiles);
+
+  /**
+   * Get the name of all available color maps for the VSI (at least the ones
+   * stored in files).
+   * @param colorMapNames Reference to a list with the names of the color maps.
+   */
+  void getColorMapsForVSI(QStringList &colorMapNames);
+
+private:
+  /**
+   * Gets all files from directory of a given file type.
+   * @param colorMapNames Reference to a list of color map names.
+   * @param colorMapFiles Reference to a list of file paths for the
+   * corresponding color maps.
+   * @param colorMapDirectory Directory where the color maps are stored.
+   * @param fileType suffix of the desired files.
+   */
+  void appendAllFileNamesForFileType(QStringList &colorMapNames,
+                                     QStringList &colorMapFiles,
+                                     QString colorMapDirectory,
+                                     QString fileType);
+
+  /**
+   * Compare the colormap names of the Slice Viewer and the VSI and extract all
+   * indicees of the list of Slice Viewer color maps
+   * which also exist in the list of the VSI color maps.
+   * @param colorMapNamesSliceViewer A list of color maps of the Slice Viewer.
+   * @param colorMapNamesVsi A list of color maps for the VSI.
+   * @returns A vector of indices for the slice viewer list.
+   */
+  std::vector<int>
+  getSliceViewerIndicesForCommonColorMaps(QStringList colorMapNamesSliceViewer,
+                                          QStringList colorMapNamesVsi);
+};
+}
 }
 
-#endif 
+#endif
diff --git a/MantidQt/API/inc/MantidQtAPI/MdSettings.h b/MantidQt/API/inc/MantidQtAPI/MdSettings.h
index a8a8e87cab0dc97a605399f6d61cd6ec5faa5ec8..dd362ccf2e40eeec36d7d5c392933ecd6988c25e 100644
--- a/MantidQt/API/inc/MantidQtAPI/MdSettings.h
+++ b/MantidQt/API/inc/MantidQtAPI/MdSettings.h
@@ -7,188 +7,187 @@
 #include <QString>
 #include <QStringList>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /**
-      *
-      This class is for reading and persisting MD properties.
-
-      @date 19/12/2014
-
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-      */
-
-    class EXPORT_OPT_MANTIDQT_API MdSettings
-    {
-      public:
-
-        MdSettings();
-
-        ~MdSettings();
-
-        /**
-         * Set the UserSetting color map for the vsi.
-         *@param colorMap UserSetting colormap for the vsi
-         */
-        void setUserSettingColorMap(QString colorMap);
-
-        /**
-          * Get the UserSetting color map for the vsi.
-          * @returns The UserSetting color map for the vsi.
-          */
-        QString getUserSettingColorMap();
-
-        /**
-          * Get the LastSession color map
-          */
-        QString getLastSessionColorMap();
-
-        /** 
-          * Set the LastSession color map
-          * @param colorMap The colormap for the VSI.
-          */
-        void setLastSessionColorMap(QString colorMap);
-
-        /**
-          * Get the background color for the user setting.
-          * @returns The background color.
-          */
-        QColor getUserSettingBackgroundColor();
-
-        /**
-         * Get the default background color.
-         * @returns The default background color.
-         */
-        QColor getDefaultBackgroundColor();
-
-        /**
-          * Set the background color for the user setting.
-          * @param backgroundColor The background color.
-          */
-        void setUserSettingBackgroundColor(QColor backgroundColor);
-
-        /**
-          * Get the background color for the last session.
-          * @returns The background color.
-          */
-        QColor getLastSessionBackgroundColor();
-
-        /**
-          * Set the background color for the user setting.
-          * @param backgroundColor The background color.
-          */
-        void setLastSessionBackgroundColor(QColor backgroundColor);
-
-        /** 
-          * Set the general MD color map
-          * @param colorMapName The name of the general color map.
-          * @param colorMapFile The file name of the general color map.
-          */
-        void setGeneralMdColorMap(QString colorMapName, QString colorMapFile);
-
-        /**
-          * Get the general MD color map file
-          * @returns The file path to the general md color map .map file.
-          */
-        QString getGeneralMdColorMapFile();
-
-        /**
-         * Get the general MD color map name
-         * @returns The name of the general Md color map.
-         */
-        QString getGeneralMdColorMapName();
-
-        /**
-          *  Set the flag if general color map is desired or not.
-          * @param flag If a general color map is desired or not.
-          */
-        void setUsageGeneralMdColorMap(bool flag);
-
-        /**
-          * Get the flag if the general color map is desired or not.
-          * @returns Is a general color map desired?
-          */
-        bool getUsageGeneralMdColorMap();
-
-        /**
-          * Set the flag which indicates if the last active color map is supposed to be used.
-          * @param flag If the last active color map is supposed to be used or not.
-          */
-        void setUsageLastSession(bool flag);
-
-        /**
-          * Get the flag which indicates if the last active color map is supposed to be used.
-          * @returns Is the last active color map to be used?
-          */
-        bool getUsageLastSession();
-
-        /**
-         * Get user setting for the initial view.
-         * @returns The initial view
-         */
-        QString getUserSettingInitialView();
-        
-       /**
-        * Sets if the color scale was log in the last session
-        * @param logScale The state of the log scale.
-        */
-        void setLastSessionLogScale(bool logScale);
-
-        /**
-         * Set the user setting for the initial view.
-         * @param initialView The selected initial view.
-         */
-        void setUserSettingIntialView(QString initialView);
-        
-        /**
-         * Retrieves the state of the last session's log scale.
-         * @returns Was a log scale state?
-         */
-         bool getLastSessionLogScale();
-         
-      private:
-        MdConstants m_mdConstants;
-
-        QString m_vsiGroup;
-        QString m_generalMdGroup;
-        QString m_sliceViewerGroup;
-
-        QString m_lblUserSettingColorMap;
-        QString m_lblLastSessionColorMap;
-        QString m_lblGeneralMdColorMap;
-        QString m_lblGeneralMdColorMapName;
-        QString m_lblUseGeneralMdColorMap;
-        QString m_lblUseLastSessionColorMap;
-
-        QString m_lblUserSettingBackgroundColor;
-        QString m_lblLastSessionBackgroundColor;
-
-        QString m_lblSliceViewerColorMap;
-
-        QString m_lblUserSettingInitialView;
-        QString m_lblLastSessionLogScale;
-    };
-  }
+namespace MantidQt {
+namespace API {
+/**
+  *
+  This class is for reading and persisting MD properties.
+
+  @date 19/12/2014
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
+
+class EXPORT_OPT_MANTIDQT_API MdSettings {
+public:
+  MdSettings();
+
+  ~MdSettings();
+
+  /**
+   * Set the UserSetting color map for the vsi.
+   *@param colorMap UserSetting colormap for the vsi
+   */
+  void setUserSettingColorMap(QString colorMap);
+
+  /**
+    * Get the UserSetting color map for the vsi.
+    * @returns The UserSetting color map for the vsi.
+    */
+  QString getUserSettingColorMap();
+
+  /**
+    * Get the LastSession color map
+    */
+  QString getLastSessionColorMap();
+
+  /**
+    * Set the LastSession color map
+    * @param colorMap The colormap for the VSI.
+    */
+  void setLastSessionColorMap(QString colorMap);
+
+  /**
+    * Get the background color for the user setting.
+    * @returns The background color.
+    */
+  QColor getUserSettingBackgroundColor();
+
+  /**
+   * Get the default background color.
+   * @returns The default background color.
+   */
+  QColor getDefaultBackgroundColor();
+
+  /**
+    * Set the background color for the user setting.
+    * @param backgroundColor The background color.
+    */
+  void setUserSettingBackgroundColor(QColor backgroundColor);
+
+  /**
+    * Get the background color for the last session.
+    * @returns The background color.
+    */
+  QColor getLastSessionBackgroundColor();
+
+  /**
+    * Set the background color for the user setting.
+    * @param backgroundColor The background color.
+    */
+  void setLastSessionBackgroundColor(QColor backgroundColor);
+
+  /**
+    * Set the general MD color map
+    * @param colorMapName The name of the general color map.
+    * @param colorMapFile The file name of the general color map.
+    */
+  void setGeneralMdColorMap(QString colorMapName, QString colorMapFile);
+
+  /**
+    * Get the general MD color map file
+    * @returns The file path to the general md color map .map file.
+    */
+  QString getGeneralMdColorMapFile();
+
+  /**
+   * Get the general MD color map name
+   * @returns The name of the general Md color map.
+   */
+  QString getGeneralMdColorMapName();
+
+  /**
+    *  Set the flag if general color map is desired or not.
+    * @param flag If a general color map is desired or not.
+    */
+  void setUsageGeneralMdColorMap(bool flag);
+
+  /**
+    * Get the flag if the general color map is desired or not.
+    * @returns Is a general color map desired?
+    */
+  bool getUsageGeneralMdColorMap();
+
+  /**
+    * Set the flag which indicates if the last active color map is supposed to
+   * be used.
+    * @param flag If the last active color map is supposed to be used or not.
+    */
+  void setUsageLastSession(bool flag);
+
+  /**
+    * Get the flag which indicates if the last active color map is supposed to
+   * be used.
+    * @returns Is the last active color map to be used?
+    */
+  bool getUsageLastSession();
+
+  /**
+   * Get user setting for the initial view.
+   * @returns The initial view
+   */
+  QString getUserSettingInitialView();
+
+  /**
+   * Sets if the color scale was log in the last session
+   * @param logScale The state of the log scale.
+   */
+  void setLastSessionLogScale(bool logScale);
+
+  /**
+   * Set the user setting for the initial view.
+   * @param initialView The selected initial view.
+   */
+  void setUserSettingIntialView(QString initialView);
+
+  /**
+   * Retrieves the state of the last session's log scale.
+   * @returns Was a log scale state?
+   */
+  bool getLastSessionLogScale();
+
+private:
+  MdConstants m_mdConstants;
+
+  QString m_vsiGroup;
+  QString m_generalMdGroup;
+  QString m_sliceViewerGroup;
+
+  QString m_lblUserSettingColorMap;
+  QString m_lblLastSessionColorMap;
+  QString m_lblGeneralMdColorMap;
+  QString m_lblGeneralMdColorMapName;
+  QString m_lblUseGeneralMdColorMap;
+  QString m_lblUseLastSessionColorMap;
+
+  QString m_lblUserSettingBackgroundColor;
+  QString m_lblLastSessionBackgroundColor;
+
+  QString m_lblSliceViewerColorMap;
+
+  QString m_lblUserSettingInitialView;
+  QString m_lblLastSessionLogScale;
+};
+}
 }
 
-#endif 
+#endif
diff --git a/MantidQt/API/inc/MantidQtAPI/Message.h b/MantidQt/API/inc/MantidQtAPI/Message.h
index 6ce90fd89149090e3aed2b73247b6cba9d538d10..f450732a2900438292cc078533adff20d459532c 100644
--- a/MantidQt/API/inc/MantidQtAPI/Message.h
+++ b/MantidQt/API/inc/MantidQtAPI/Message.h
@@ -16,46 +16,45 @@
 // Forward declarations
 //----------------------------------------------------------
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /** @class Message
-     * Provides a simple binding of a text message with a priority
-     */
-    class EXPORT_OPT_MANTIDQT_API Message : public QObject
-    {
-      // No Q_Object macro by design
-
-    public:
-      /// Priority matches Mantid Logger priority
-      typedef Mantid::Kernel::Logger::Priority Priority;
-
-      /// Default constuctor required by Qt meta-type system
-      Message();
-      /// Construct a message from a QString with a given priority (default=notice)
-      Message(const QString & text, Priority priority=Priority::PRIO_NOTICE);
-      /// Construct a message from a std::string with a given priority (default=notice)
-      Message(const std::string & text, Priority priority=Priority::PRIO_NOTICE);
-      /// Construct a message from a c-style string and a given priority (default=notice)
-      Message(const char * text, Priority priority=Priority::PRIO_NOTICE);
-      /// Copy constructor
-      Message(const Message & msg);
-
-    public:
-      /// @returns The message text
-      inline QString text() const {return m_text;}
-      /// @returns The message priority
-      inline Priority priority() const {return m_priority;}
-
-    private:
-      QString m_text;
-      Priority m_priority;
-    };
-  }
+namespace MantidQt {
+namespace API {
+/** @class Message
+ * Provides a simple binding of a text message with a priority
+ */
+class EXPORT_OPT_MANTIDQT_API Message : public QObject {
+  // No Q_Object macro by design
+
+public:
+  /// Priority matches Mantid Logger priority
+  typedef Mantid::Kernel::Logger::Priority Priority;
+
+  /// Default constuctor required by Qt meta-type system
+  Message();
+  /// Construct a message from a QString with a given priority (default=notice)
+  Message(const QString &text, Priority priority = Priority::PRIO_NOTICE);
+  /// Construct a message from a std::string with a given priority
+  /// (default=notice)
+  Message(const std::string &text, Priority priority = Priority::PRIO_NOTICE);
+  /// Construct a message from a c-style string and a given priority
+  /// (default=notice)
+  Message(const char *text, Priority priority = Priority::PRIO_NOTICE);
+  /// Copy constructor
+  Message(const Message &msg);
+
+public:
+  /// @returns The message text
+  inline QString text() const { return m_text; }
+  /// @returns The message priority
+  inline Priority priority() const { return m_priority; }
+
+private:
+  QString m_text;
+  Priority m_priority;
+};
+}
 }
 
 /// Required to operate in signals/slots
 Q_DECLARE_METATYPE(MantidQt::API::Message)
 
-#endif //MESSAGE_H_
+#endif // MESSAGE_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/OptionsPropertyWidget.h b/MantidQt/API/inc/MantidQtAPI/OptionsPropertyWidget.h
index 0cb5b19972cb7c0a31ef790a9a2b6ea31589d097..9057eaceb24c10fa4283bed990eb3db915afaff1 100644
--- a/MantidQt/API/inc/MantidQtAPI/OptionsPropertyWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/OptionsPropertyWidget.h
@@ -7,61 +7,57 @@
 #include <qcombobox.h>
 #include <QLabel>
 
+namespace MantidQt {
+namespace API {
 
-namespace MantidQt
-{
-namespace API
-{
+/** Widget for displaying a Property that has a set of allowed values.
+ * The display is then a drop-down box instead of a Text box.
 
-  /** Widget for displaying a Property that has a set of allowed values.
-   * The display is then a drop-down box instead of a Text box.
-    
-    @date 2012-02-17
+  @date 2012-02-17
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport OptionsPropertyWidget : public PropertyWidget
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport OptionsPropertyWidget : public PropertyWidget {
+  Q_OBJECT
 
-  public:
-    OptionsPropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
-    ~OptionsPropertyWidget() override;
-    QString getValue() const override;
-    void setValueImpl(const QString &value) override;
+public:
+  OptionsPropertyWidget(Mantid::Kernel::Property *prop, QWidget *parent = NULL,
+                        QGridLayout *layout = NULL, int row = -1);
+  ~OptionsPropertyWidget() override;
+  QString getValue() const override;
+  void setValueImpl(const QString &value) override;
 
-    ///@return the main widget of this combo of widgets
-    QWidget *getMainWidget() override { return m_combo; }
+  ///@return the main widget of this combo of widgets
+  QWidget *getMainWidget() override { return m_combo; }
 
-  protected:
-    /// Label (name of the property)
-    QLabel * m_label;
-
-    /// Combo box with the allowed options
-    QComboBox * m_combo;
-
-  };
+protected:
+  /// Label (name of the property)
+  QLabel *m_label;
 
+  /// Combo box with the allowed options
+  QComboBox *m_combo;
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTID_API_OPTIONSPROPERTYWIDGET_H_ */
+#endif /* MANTID_API_OPTIONSPROPERTYWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/PlotAxis.h b/MantidQt/API/inc/MantidQtAPI/PlotAxis.h
index 4046030a1e5e63dafa3ba0c497da541de0ccbf0a..18ba06dfb08d0cdc4ca83855d351779070dea7a5 100644
--- a/MantidQt/API/inc/MantidQtAPI/PlotAxis.h
+++ b/MantidQt/API/inc/MantidQtAPI/PlotAxis.h
@@ -10,66 +10,65 @@
 #include <QString>
 #include <string>
 
-namespace MantidQt
-{
-  namespace API
-  {
-
-    /**
-      Deals with formatting a label for a plot axis for a given type of workspace
-
-      Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-     */
-    class EXPORT_OPT_MANTIDQT_API PlotAxis
-    {
-    public:
-      /// Constructor with workspace & axis index
-      PlotAxis(const Mantid::API::IMDWorkspace & workspace,
-               const size_t index);
-      /// Constructor with an IMDDimension
-      PlotAxis(const Mantid::Geometry::IMDDimension & dim);
-      /// Constructor with just a workspace (reverse order to above so compiler doesn't convert a
-      /// a bool to an size_t and call the wrong thing
-      PlotAxis(const bool plottingDistribution, const Mantid::API::MatrixWorkspace & workspace);
-
-      /// Create a new axis title
-      QString title() const;
-
-    private:
-      DISABLE_DEFAULT_CONSTRUCT(PlotAxis)
-
-      /// Creates a title suitable for an axis attached to the given index
-      void titleFromIndex(const Mantid::API::IMDWorkspace & workspace,
-                          const size_t index);
-      /// Creates a title suitable for an axis attached to the given dimension
-      void titleFromDimension(const Mantid::Geometry::IMDDimension & dim);
-      /// Creates a title suitable for the Y data values
-      void titleFromYData(const Mantid::API::MatrixWorkspace & workspace,
-                          const bool plottingDistribution);
-
-      /// Title
-      QString m_title;
-    };
-
-  } // namespace API
+namespace MantidQt {
+namespace API {
+
+/**
+  Deals with formatting a label for a plot axis for a given type of workspace
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class EXPORT_OPT_MANTIDQT_API PlotAxis {
+public:
+  /// Constructor with workspace & axis index
+  PlotAxis(const Mantid::API::IMDWorkspace &workspace, const size_t index);
+  /// Constructor with an IMDDimension
+  PlotAxis(const Mantid::Geometry::IMDDimension &dim);
+  /// Constructor with just a workspace (reverse order to above so compiler
+  /// doesn't convert a
+  /// a bool to an size_t and call the wrong thing
+  PlotAxis(const bool plottingDistribution,
+           const Mantid::API::MatrixWorkspace &workspace);
+
+  /// Create a new axis title
+  QString title() const;
+
+private:
+  DISABLE_DEFAULT_CONSTRUCT(PlotAxis)
+
+  /// Creates a title suitable for an axis attached to the given index
+  void titleFromIndex(const Mantid::API::IMDWorkspace &workspace,
+                      const size_t index);
+  /// Creates a title suitable for an axis attached to the given dimension
+  void titleFromDimension(const Mantid::Geometry::IMDDimension &dim);
+  /// Creates a title suitable for the Y data values
+  void titleFromYData(const Mantid::API::MatrixWorkspace &workspace,
+                      const bool plottingDistribution);
+
+  /// Title
+  QString m_title;
+};
+
+} // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_API_PLOTAXISLABEL_H_ */
+#endif /* MANTIDQT_API_PLOTAXISLABEL_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/PowerScaleEngine.h b/MantidQt/API/inc/MantidQtAPI/PowerScaleEngine.h
index 4ccc7a4122643e638f8326599fe42765efbfe1ac..26dadaee095cce3aa924b64bfbae9d4e9ffe1488 100644
--- a/MantidQt/API/inc/MantidQtAPI/PowerScaleEngine.h
+++ b/MantidQt/API/inc/MantidQtAPI/PowerScaleEngine.h
@@ -35,16 +35,16 @@
 #include "ScaleEngine.h"
 #include "MantidQtAPI/DllOption.h"
 
-class EXPORT_OPT_MANTIDQT_API PowerScaleTransformation: public ScaleTransformation
-{
+class EXPORT_OPT_MANTIDQT_API PowerScaleTransformation
+    : public ScaleTransformation {
 public:
-	PowerScaleTransformation(const ScaleEngine *engine):ScaleTransformation(engine), nth_power(engine->nthPower()){};
-        double xForm(double x, double, double, double p1,
-                     double p2) const override;
-        double invXForm(double x, double s1, double s2, double p1,
-                        double p2) const override;
-        QwtScaleTransformation *copy() const override;
-        ~PowerScaleTransformation() override;
+  PowerScaleTransformation(const ScaleEngine *engine)
+      : ScaleTransformation(engine), nth_power(engine->nthPower()){};
+  double xForm(double x, double, double, double p1, double p2) const override;
+  double invXForm(double x, double s1, double s2, double p1,
+                  double p2) const override;
+  QwtScaleTransformation *copy() const override;
+  ~PowerScaleTransformation() override;
 
 private:
   double nth_power;
@@ -54,8 +54,7 @@ private:
   \brief A scale engine for power (X^n) scales
 */
 
-class EXPORT_OPT_MANTIDQT_API PowerScaleEngine: public QwtScaleEngine
-{
+class EXPORT_OPT_MANTIDQT_API PowerScaleEngine : public QwtScaleEngine {
 public:
   void autoScale(int maxSteps, double &x1, double &x2,
                  double &stepSize) const override;
@@ -69,21 +68,17 @@ public:
   ~PowerScaleEngine() override;
 
 protected:
-    QwtDoubleInterval align(const QwtDoubleInterval&,
-        double stepSize) const;
+  QwtDoubleInterval align(const QwtDoubleInterval &, double stepSize) const;
 
 private:
-    void buildTicks(
-        const QwtDoubleInterval &, double stepSize, int maxMinSteps,
-        QwtValueList ticks[QwtScaleDiv::NTickTypes]) const;
+  void buildTicks(const QwtDoubleInterval &, double stepSize, int maxMinSteps,
+                  QwtValueList ticks[QwtScaleDiv::NTickTypes]) const;
 
-    void buildMinorTicks(
-        const QwtValueList& majorTicks,
-        int maxMinMark, double step,
-        QwtValueList &, QwtValueList &) const;
+  void buildMinorTicks(const QwtValueList &majorTicks, int maxMinMark,
+                       double step, QwtValueList &, QwtValueList &) const;
 
-    QwtValueList buildMajorTicks(
-        const QwtDoubleInterval &interval, double stepSize) const;
+  QwtValueList buildMajorTicks(const QwtDoubleInterval &interval,
+                               double stepSize) const;
 };
 
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/PrecompiledHeader.h b/MantidQt/API/inc/MantidQtAPI/PrecompiledHeader.h
index 4047a4595f12a1bc23fd894328a9d251a14f516e..0ca739d5c5febafc0644e059063ec32bcb2d3899 100644
--- a/MantidQt/API/inc/MantidQtAPI/PrecompiledHeader.h
+++ b/MantidQt/API/inc/MantidQtAPI/PrecompiledHeader.h
@@ -6,11 +6,10 @@
 #include "MantidAPI/Algorithm.h"
 #include "MantidAPI/AnalysisDataService.h"
 
-//STL
+// STL
 #include <vector>
 #include <map>
 #include <set>
 #include <string>
 
-
 #endif // MANTIDQT_API_PRECOMPILEDHEADER_H_
\ No newline at end of file
diff --git a/MantidQt/API/inc/MantidQtAPI/PropertyWidget.h b/MantidQt/API/inc/MantidQtAPI/PropertyWidget.h
index 5d25dc8205a9a9aed10b27620ed3bfe3b4dd24c5..34f9612496238b480edaf64655c54c313907da4f 100644
--- a/MantidQt/API/inc/MantidQtAPI/PropertyWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/PropertyWidget.h
@@ -15,177 +15,176 @@
 
 class QLineEdit;
 
-namespace MantidQt
-{
-namespace API
-{
-  /**
-   * A small extension to QLabel, so that it emits a signal when clicked.
-   * Used for the information "icons" in PropertyWidget.
-   */
-  class ClickableLabel : public QLabel
-  {
-    Q_OBJECT
-
-  public:
-    /// Constructor
-    ClickableLabel(QWidget * parent);
-    /// Destructor
-    ~ClickableLabel() override;
+namespace MantidQt {
+namespace API {
+/**
+ * A small extension to QLabel, so that it emits a signal when clicked.
+ * Used for the information "icons" in PropertyWidget.
+ */
+class ClickableLabel : public QLabel {
+  Q_OBJECT
+
+public:
+  /// Constructor
+  ClickableLabel(QWidget *parent);
+  /// Destructor
+  ~ClickableLabel() override;
 
 signals:
-    /// Signal emitted when a user clicks the label.
-    void clicked();
- 
-  protected:
-    /// Catches the mouse press event and emits the signal.
-    void mousePressEvent(QMouseEvent *event) override;
-  };
+  /// Signal emitted when a user clicks the label.
+  void clicked();
 
-  /** Base class for widgets that will set
-   * Mantid::Kernel::Property* types
-    
-    @date 2012-02-16
+protected:
+  /// Catches the mouse press event and emits the signal.
+  void mousePressEvent(QMouseEvent *event) override;
+};
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** Base class for widgets that will set
+ * Mantid::Kernel::Property* types
 
-    This file is part of Mantid.
+  @date 2012-02-16
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  This file is part of Mantid.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_API PropertyWidget : public QWidget
-  {
-    Q_OBJECT
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-  public:
-    enum Info { INVALID, REPLACE, RESTORE };
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    PropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
-    ~PropertyWidget() override;
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API PropertyWidget : public QWidget {
+  Q_OBJECT
 
-    bool inGrid() const;
+public:
+  enum Info { INVALID, REPLACE, RESTORE };
 
-    /// Return the value of the property given the GUI state.
-    virtual QString getValue() const = 0;
+  PropertyWidget(Mantid::Kernel::Property *prop, QWidget *parent = NULL,
+                 QGridLayout *layout = NULL, int row = -1);
+  ~PropertyWidget() override;
 
-    /// Set the value of the property given into the GUI state.
-    void setValue(const QString & value);
-    /// Set this widget's previously-entered value.
-    void setPreviousValue(const QString & previousValue);
+  bool inGrid() const;
 
-    virtual QWidget * getMainWidget() = 0;
+  /// Return the value of the property given the GUI state.
+  virtual QString getValue() const = 0;
 
-    void setEnabled(bool val);
-    void setVisible(bool val) override;
+  /// Set the value of the property given into the GUI state.
+  void setValue(const QString &value);
+  /// Set this widget's previously-entered value.
+  void setPreviousValue(const QString &previousValue);
 
-    /// @return the Layout object that these widget(s) are in.
-    QGridLayout * getGridLayout()
-    {return m_gridLayout; }
+  virtual QWidget *getMainWidget() = 0;
 
-    /// @return the row of the widgets in the Layout
-    int getGridRow()
-    {return m_row; }
+  void setEnabled(bool val);
+  void setVisible(bool val) override;
 
-    void addReplaceWSButton();
+  /// @return the Layout object that these widget(s) are in.
+  QGridLayout *getGridLayout() { return m_gridLayout; }
 
-    /// @return the property in the widget
-    Mantid::Kernel::Property * getProperty()
-    { return m_prop; }
+  /// @return the row of the widgets in the Layout
+  int getGridRow() { return m_row; }
 
-    void setError(const QString & error);
+  void addReplaceWSButton();
 
-  private:
-    virtual void setValueImpl(const QString & value) = 0;
+  /// @return the property in the widget
+  Mantid::Kernel::Property *getProperty() { return m_prop; }
 
-  public slots:
-    /// Update which icons should be shown.
-    void updateIconVisibility(const QString & error = "");
-    /// Deal with the "replace workspace" button being clicked.
-    void replaceWSButtonClicked();
-    /// Emits a signal that the value of the property was changed.
-    void valueChangedSlot();
-    /// To be called when a user edits a property, as opposed to one being set programmatically.
-    void userEditedProperty();
-    /// Toggle whether or not to use the previously-entered value.
-    void toggleUseHistory();
+  void setError(const QString &error);
 
-  private:
-    /// Sets the history on/off icons.
-    void setUseHistoryIcon(bool useHistory);
+private:
+  virtual void setValueImpl(const QString &value) = 0;
 
-  signals:
-    /// Signal is emitted whenever the value (as entered by the user) in the GUI changes.
-    void valueChanged(const QString & propName);
+public slots:
+  /// Update which icons should be shown.
+  void updateIconVisibility(const QString &error = "");
+  /// Deal with the "replace workspace" button being clicked.
+  void replaceWSButtonClicked();
+  /// Emits a signal that the value of the property was changed.
+  void valueChangedSlot();
+  /// To be called when a user edits a property, as opposed to one being set
+  /// programmatically.
+  void userEditedProperty();
+  /// Toggle whether or not to use the previously-entered value.
+  void toggleUseHistory();
 
-    /// Signal is emitted whenever someone clicks the replace WS button.
-    void replaceWorkspaceName(const QString & propName);
+private:
+  /// Sets the history on/off icons.
+  void setUseHistoryIcon(bool useHistory);
 
-    void userChangedProperty();
+signals:
+  /// Signal is emitted whenever the value (as entered by the user) in the GUI
+  /// changes.
+  void valueChanged(const QString &propName);
+
+  /// Signal is emitted whenever someone clicks the replace WS button.
+  void replaceWorkspaceName(const QString &propName);
 
-  protected:
-    /// Set the font of the given label based on the optional/required status of the given property.
-    static void setLabelFont(Mantid::Kernel::Property * prop, QWidget * label);
+  void userChangedProperty();
 
-    /// Set the placeholder text of the given field based on the default value of the given property.
-    static void setFieldPlaceholderText(Mantid::Kernel::Property * prop, QLineEdit * field);
+protected:
+  /// Set the font of the given label based on the optional/required status of
+  /// the given property.
+  static void setLabelFont(Mantid::Kernel::Property *prop, QWidget *label);
 
-    /// Property being looked at. This is NOT owned by the widget
-    Mantid::Kernel::Property * m_prop;
+  /// Set the placeholder text of the given field based on the default value of
+  /// the given property.
+  static void setFieldPlaceholderText(Mantid::Kernel::Property *prop,
+                                      QLineEdit *field);
 
-    /// Grid layout of the dialog to which we are adding widgets
-    QGridLayout * m_gridLayout;
+  /// Property being looked at. This is NOT owned by the widget
+  Mantid::Kernel::Property *m_prop;
 
-    /// Parent widget to add sub-widgets to.
-    QWidget * m_parent;
+  /// Grid layout of the dialog to which we are adding widgets
+  QGridLayout *m_gridLayout;
 
-    /// If using the GridLayout, this is the row where the widget was inserted.
-    int m_row;
+  /// Parent widget to add sub-widgets to.
+  QWidget *m_parent;
 
-    /// Documentation string (tooltip)
-    QString m_doc;
+  /// If using the GridLayout, this is the row where the widget was inserted.
+  int m_row;
 
-    /// Button to "replace input workspace"
-    QPushButton * m_replaceWSButton;
+  /// Documentation string (tooltip)
+  QString m_doc;
 
-    /// All contained widgets
-    QVector<QWidget*> m_widgets;
+  /// Button to "replace input workspace"
+  QPushButton *m_replaceWSButton;
 
-    /// Error message received when trying to set the value
-    QString m_error;
+  /// All contained widgets
+  QVector<QWidget *> m_widgets;
 
-    /// Whether or not the property is an output workspace.
-    bool m_isOutputWsProp;
+  /// Error message received when trying to set the value
+  QString m_error;
 
-    /// Stores the previously entered value when this dialog was last open.
-    QString m_previousValue;
+  /// Whether or not the property is an output workspace.
+  bool m_isOutputWsProp;
 
-    /// Stored the last non-previously-entered value entered entered by the user.
-    QString m_enteredValue;
+  /// Stores the previously entered value when this dialog was last open.
+  QString m_previousValue;
 
-    /// Allow icon access by Info enum.
-    QMap<Info, ClickableLabel *> m_icons;
+  /// Stored the last non-previously-entered value entered entered by the user.
+  QString m_enteredValue;
 
-    /// History on/off flag.  Note this is different from whether or not
-    /// the property has a previously-entered value to actually use.
-    bool m_useHistory;
-  };
+  /// Allow icon access by Info enum.
+  QMap<Info, ClickableLabel *> m_icons;
 
+  /// History on/off flag.  Note this is different from whether or not
+  /// the property has a previously-entered value to actually use.
+  bool m_useHistory;
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTID_API_PROPERTYWIDGET_H_ */
+#endif /* MANTID_API_PROPERTYWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/PropertyWidgetFactory.h b/MantidQt/API/inc/MantidQtAPI/PropertyWidgetFactory.h
index 1dc96809becad1db9b57366c95ce0dfff4142c99..a0adfe331afb82dd64e8fb9a29df509c42f37054 100644
--- a/MantidQt/API/inc/MantidQtAPI/PropertyWidgetFactory.h
+++ b/MantidQt/API/inc/MantidQtAPI/PropertyWidgetFactory.h
@@ -7,47 +7,45 @@
 #include <qgridlayout.h>
 #include "MantidQtAPI/PropertyWidget.h"
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
-  /** PropertyWidgetFactory : TODO: DESCRIPTION
-    
-    @date 2012-02-17
+/** PropertyWidgetFactory : TODO: DESCRIPTION
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  @date 2012-02-17
 
-    This file is part of Mantid.
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport PropertyWidgetFactory 
-  {
-  public:
-    PropertyWidgetFactory();
-    virtual ~PropertyWidgetFactory();
-    
-    static PropertyWidget * createWidget(Mantid::Kernel::Property * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  };
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport PropertyWidgetFactory {
+public:
+  PropertyWidgetFactory();
+  virtual ~PropertyWidgetFactory();
 
+  static PropertyWidget *createWidget(Mantid::Kernel::Property *prop,
+                                      QWidget *parent = NULL,
+                                      QGridLayout *layout = NULL, int row = -1);
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTID_API_PROPERTYWIDGETFACTORY_H_ */
+#endif /* MANTID_API_PROPERTYWIDGETFACTORY_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/PythonRunner.h b/MantidQt/API/inc/MantidQtAPI/PythonRunner.h
index a25d5d3b95ae6bd16ba6d83a9dd7a2533b3563d6..74488bd21aab5ad94e09d6b42ee5abc9159c501e 100644
--- a/MantidQt/API/inc/MantidQtAPI/PythonRunner.h
+++ b/MantidQt/API/inc/MantidQtAPI/PythonRunner.h
@@ -8,53 +8,52 @@
 /** The ase class from which mantid custom widgets are derived it contains
 *  some useful functions
 */
-namespace MantidQt
-{
-  namespace API
-  {
-    /** 
-    This is the base class all customised user interfaces that do not wish to be tied
-    to a specific Mantid algorithm but rather customised for user's requirements
-
-    @author Steve Williams, Rutherford Appleton Laboratory
-    @date 10/11/2010
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_API PythonRunner : public QObject
-    {
-    Q_OBJECT
-
-    public:
-      /// Default constructor
-      PythonRunner() : QObject(){}
-
-      /// Run python code
-      QString runPythonCode(const QString & code, bool no_output = false);
-      /// Converts a list of strings into a string recognised by Python as a tuple
-      static const QString stringList2Tuple(const QStringList & list);
-    signals:
-      void runAsPythonScript(const QString& code, bool);
-    };
-  }
+namespace MantidQt {
+namespace API {
+/**
+This is the base class all customised user interfaces that do not wish to be
+tied
+to a specific Mantid algorithm but rather customised for user's requirements
+
+@author Steve Williams, Rutherford Appleton Laboratory
+@date 10/11/2010
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API PythonRunner : public QObject {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  PythonRunner() : QObject() {}
+
+  /// Run python code
+  QString runPythonCode(const QString &code, bool no_output = false);
+  /// Converts a list of strings into a string recognised by Python as a tuple
+  static const QString stringList2Tuple(const QStringList &list);
+signals:
+  void runAsPythonScript(const QString &code, bool);
+};
+}
 }
 
-#endif //MANTIDQTAPI_PYTHONRUNNER_H_
+#endif // MANTIDQTAPI_PYTHONRUNNER_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/PythonSystemHeader.h b/MantidQt/API/inc/MantidQtAPI/PythonSystemHeader.h
index 76ff6ea0973d844700c21ee2999061804d56f6e6..e02eea6c1686d42010bd29274632d28c3dc59e7e 100644
--- a/MantidQt/API/inc/MantidQtAPI/PythonSystemHeader.h
+++ b/MantidQt/API/inc/MantidQtAPI/PythonSystemHeader.h
@@ -13,4 +13,4 @@
 #include <traceback.h>
 #include <frameobject.h>
 
-#endif //PYTHONSYSTEMHEADER_H_
+#endif // PYTHONSYSTEMHEADER_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/QtSignalChannel.h b/MantidQt/API/inc/MantidQtAPI/QtSignalChannel.h
index f9773c978cd5de412040a1b8ed70a8ecefc0ab39..53d4f5eb2060946c6679667bbde9bb75bfbca6fc 100644
--- a/MantidQt/API/inc/MantidQtAPI/QtSignalChannel.h
+++ b/MantidQt/API/inc/MantidQtAPI/QtSignalChannel.h
@@ -6,72 +6,71 @@
 #include <QObject>
 #include <Poco/Channel.h>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    //---------------------------------------------------------------------
-    //
-    //---------------------------------------------------------------------
-    class Message;
-
-    /** 
-    Provides a translation layer that takes a Poco::Message and converts it
-    to a Qt signal.
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_API QtSignalChannel : public QObject, public Poco::Channel
-    {
-    Q_OBJECT
-
-    public:
-      /// Default constructor
-      QtSignalChannel(const QString & source = "");
-      /// Destructor
-      ~QtSignalChannel() override;
-
-      /// If set, only Mantid log messages from this source are emitted
-      void setSource(const QString & source);
-      /// Get the current source are emitted
-      inline const QString & source() const { return m_source; }
-
-      /// Converts the Poco::Message to a Qt signal
-      void log(const Poco::Message &msg) override;
-
-    public slots:
-      /// Set the log level for all loggers
-      void setGlobalLogLevel(int level);
-
-    signals:
-      // Emitted when a Poco log message is received in this channel
-      void messageReceived(const Message & msg);
-
-    private:
-      Q_DISABLE_COPY(QtSignalChannel)
-
-      /// Optional source (use std::string to avoid conversion in comparison)
-      QString m_source;
-   };
-  }
+namespace MantidQt {
+namespace API {
+//---------------------------------------------------------------------
+//
+//---------------------------------------------------------------------
+class Message;
+
+/**
+Provides a translation layer that takes a Poco::Message and converts it
+to a Qt signal.
+
+Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API QtSignalChannel : public QObject,
+                                                public Poco::Channel {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  QtSignalChannel(const QString &source = "");
+  /// Destructor
+  ~QtSignalChannel() override;
+
+  /// If set, only Mantid log messages from this source are emitted
+  void setSource(const QString &source);
+  /// Get the current source are emitted
+  inline const QString &source() const { return m_source; }
+
+  /// Converts the Poco::Message to a Qt signal
+  void log(const Poco::Message &msg) override;
+
+public slots:
+  /// Set the log level for all loggers
+  void setGlobalLogLevel(int level);
+
+signals:
+  // Emitted when a Poco log message is received in this channel
+  void messageReceived(const Message &msg);
+
+private:
+  Q_DISABLE_COPY(QtSignalChannel)
+
+  /// Optional source (use std::string to avoid conversion in comparison)
+  QString m_source;
+};
+}
 }
 
-#endif //MANTIDQTAPI_MANTIDWIDGET_H_
+#endif // MANTIDQTAPI_MANTIDWIDGET_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceBinData.h b/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceBinData.h
index 7e87c987497d0868c43f812b7c486996c3df6aab..5b921712f5364fc890900fcca6593d86da591c1e 100644
--- a/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceBinData.h
+++ b/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceBinData.h
@@ -37,7 +37,7 @@ public:
 
 protected:
   // Assignment operator.
-  QwtWorkspaceBinData & operator=(const QwtWorkspaceBinData &);
+  QwtWorkspaceBinData &operator=(const QwtWorkspaceBinData &);
   /**
   Return the x value of data point i
   @param i :: Index
@@ -73,6 +73,5 @@ private:
   QString m_xTitle;
   /// A title for the Y axis
   QString m_yTitle;
-
 };
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceSpectrumData.h b/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceSpectrumData.h
index e39c13c51e4530e005cc8060231564e4aad1cfef..9bd9e55162297634c93ba61e80c935cfc13b7ca3 100644
--- a/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceSpectrumData.h
+++ b/MantidQt/API/inc/MantidQtAPI/QwtWorkspaceSpectrumData.h
@@ -51,8 +51,8 @@ public:
   /// Number of error bars to plot
   size_t esize() const override;
 
-  //double getYMin() const override;
-  //double getYMax() const override;
+  // double getYMin() const override;
+  // double getYMax() const override;
   /// Return the label to use for the X axis
   QString getXAxisLabel() const override;
   /// Return the label to use for the Y axis
@@ -62,15 +62,15 @@ public:
   bool dataIsNormalized() const { return m_dataIsNormalized; }
 
   ///// Inform the data that it is to be plotted on a log y scale
-  //void setLogScale(bool on) override;
-  //bool logScaleY() const override { return m_logScaleY; }
-  //void saveLowestPositiveValue(const double v) override;
+  // void setLogScale(bool on) override;
+  // bool logScaleY() const override { return m_logScaleY; }
+  // void saveLowestPositiveValue(const double v) override;
   bool setAsDistribution(bool on = true);
 
   //// Sets offsets for and enables waterfall plots
-  //void setXOffset(const double x) override;
-  //void setYOffset(const double y) override;
-  //void setWaterfallPlot(bool on) override;
+  // void setXOffset(const double x) override;
+  // void setYOffset(const double y) override;
+  // void setWaterfallPlot(bool on) override;
 
 protected:
   // Assignment operator (virtualized). MSVC not happy with compiler generated
@@ -102,23 +102,23 @@ private:
   /// returns (X[i]+X[i+1])/2
   bool m_binCentres;
   ///// Indicates that the data is plotted on a log y scale
-  //bool m_logScaleY;
+  // bool m_logScaleY;
   ///// lowest y value
-  //double m_minY;
+  // double m_minY;
   ///// lowest positive y value
-  //double m_minPositive;
+  // double m_minPositive;
   ///// higest y value
-  //double m_maxY;
+  // double m_maxY;
   /// Is plotting as distribution
   bool m_isDistribution;
 
   ///// Indicates whether or not waterfall plots are enabled
-  //bool m_isWaterfall;
+  // bool m_isWaterfall;
 
   ///// x-axis offset for waterfall plots
-  //double m_offsetX;
+  // double m_offsetX;
 
   ///// y-axis offset for waterfall plots
-  //double m_offsetY;
+  // double m_offsetY;
 };
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/RepoModel.h b/MantidQt/API/inc/MantidQtAPI/RepoModel.h
index dc6795432da263f5ef7fa436d83f7b58841488cd..657e0f529523857c7b55cbe9cb74d5549d36fad4 100644
--- a/MantidQt/API/inc/MantidQtAPI/RepoModel.h
+++ b/MantidQt/API/inc/MantidQtAPI/RepoModel.h
@@ -13,251 +13,261 @@
 #include <QFutureWatcher>
 #include <QMessageBox>
 
-class QLineEdit; 
-class QCheckBox; 
+class QLineEdit;
+class QCheckBox;
 class QTextEdit;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
-const QString REMOTEONLY = "REMOTE_ONLY"; 
+const QString REMOTEONLY = "REMOTE_ONLY";
 const QString LOCALONLY = "LOCAL_ONLY";
 const QString LOCALCHANGED = "LOCAL_CHANGED";
 const QString REMOTECHANGED = "REMOTE_CHANGED";
 const QString BOTHUNCHANGED = "UPDATED";
-const QString BOTHCHANGED = "CHANGED"; 
+const QString BOTHCHANGED = "CHANGED";
 const QString UPLOADST = "UPLOADING";
 const QString DOWNLOADST = "DOWNLOADING";
 const QString PROTECTEDENTRY = "protected";
-const QString DELETABLEENTRY = "deletable"; 
-
-
-  /** RepoModel : Wrapper for ScriptRepository to fit the Model View Qt Framework. 
-      
-      The ScriptRepository has an hierarchical access to the folders and files, as so, 
-      it was necessary to extend the QAbstractItemModel in order to provide access to the 
-      entries on ScriptRepository.
-
-      The RepoModel will be given to a QTreeView and as so, it will allow the user to interact 
-      with the ScriptRepository through the Qt ModelView Framework. 
-
-      The requirements for a class to fit this framework is to reimplement the following methods: 
-        - RepoModel::data - giving access to the data
-        - RepoModel::flags - indication of the allowed interaction 
-        - RepoModel::headerData 
-        - RepoModel::index
-        - RepoModel::parent
-        - RepoModel::rowCount
-        - RepoModel::columnCount
-        - RepoModel::setData
-
-     Through these methods, the RepoModel will be able to provide access to the ScriptRepository 
-     service. Allowing the users to upload and download files and folders.
-
-     Some extra services are provided, to allow the classes to show the description of the files 
-     as well as open the files to be inspected by the users: 
-      - entrySelected
-      - fileSelected
-
-     This class should be constructed just once, and as so, the copy constructor and the assignment 
-     will be make private to ensure this. 
-    
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class RepoModel : public QAbstractItemModel
-{
-    Q_OBJECT
+const QString DELETABLEENTRY = "deletable";
+
+/** RepoModel : Wrapper for ScriptRepository to fit the Model View Qt Framework.
+
+    The ScriptRepository has an hierarchical access to the folders and files, as
+  so,
+    it was necessary to extend the QAbstractItemModel in order to provide access
+  to the
+    entries on ScriptRepository.
+
+    The RepoModel will be given to a QTreeView and as so, it will allow the user
+  to interact
+    with the ScriptRepository through the Qt ModelView Framework.
+
+    The requirements for a class to fit this framework is to reimplement the
+  following methods:
+      - RepoModel::data - giving access to the data
+      - RepoModel::flags - indication of the allowed interaction
+      - RepoModel::headerData
+      - RepoModel::index
+      - RepoModel::parent
+      - RepoModel::rowCount
+      - RepoModel::columnCount
+      - RepoModel::setData
+
+   Through these methods, the RepoModel will be able to provide access to the
+  ScriptRepository
+   service. Allowing the users to upload and download files and folders.
+
+   Some extra services are provided, to allow the classes to show the
+  description of the files
+   as well as open the files to be inspected by the users:
+    - entrySelected
+    - fileSelected
+
+   This class should be constructed just once, and as so, the copy constructor
+  and the assignment
+   will be make private to ensure this.
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
 
-  /** A nested class to help RepoModel to implement the QAbstractItemModel. 
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class RepoModel : public QAbstractItemModel {
+  Q_OBJECT
+
+  /** A nested class to help RepoModel to implement the QAbstractItemModel.
       This class in indended to keep track of the path inside the Repository
-      of the entries, in such a way the repomodel will be able to get from the 
+      of the entries, in such a way the repomodel will be able to get from the
       index the path.
-      The RepoModel::appendChild allows the RepoModel to reconstruct the tree of the directories,
-      while the RepoModel::child and RepoModel::parent methods allow to iterate over the tree.      
+      The RepoModel::appendChild allows the RepoModel to reconstruct the tree of
+     the directories,
+      while the RepoModel::child and RepoModel::parent methods allow to iterate
+     over the tree.
   */
-  class RepoItem
-  {
-public:
+  class RepoItem {
+  public:
     // construct the RepoItem passing the script repository path
-    RepoItem(const QString & label, 
-             const QString & path = "/",
-             RepoItem * parent = 0);
+    RepoItem(const QString &label, const QString &path = "/",
+             RepoItem *parent = 0);
 
     ~RepoItem();
     // append child to build the directory tree
-    void appendChild(RepoItem * child);
+    void appendChild(RepoItem *child);
     // access to the row_th file/folder child of this entry
-    RepoItem * child(int row) const;
+    RepoItem *child(int row) const;
     /// To which row this repoItem belongs?
     int row() const;
     // return the number of files/folders that are children of this entry
     int childCount() const;
     /// access to the script repository path
     /// @return : script repository path
-    const QString & path() const{return keypath;}; 
+    const QString &path() const { return keypath; };
     /// access to the label provided at construction
     /// @return : label for this entry
-    const QString & label()const{return m_label;}; 
+    const QString &label() const { return m_label; };
     /// access to the parent of this entry
     /// @return : this entry parent's
-    RepoItem * parent() const{return parentItem;};
+    RepoItem *parent() const { return parentItem; };
     /// allow to remove a child, which allows erasing rows from the view.
     bool removeChild(int row);
-private:
+
+  private:
     /// track the list of children for this entry
-    QList<RepoItem * >childItems;
+    QList<RepoItem *> childItems;
     /// the label of this entry
-    QString m_label; 
+    QString m_label;
     /// the path of the script repository
-    QString keypath; 
+    QString keypath;
     /// the parent of this entry
-    RepoItem* parentItem;
-private:
-    RepoItem( const RepoItem& );
-    const RepoItem& operator=( const RepoItem& );
-};
+    RepoItem *parentItem;
 
-    class UploadForm: public QDialog{
-    public:
-      UploadForm(const QString & file2upload, QWidget * parent = 0);
-      ~UploadForm() override;
-      QString email(); 
-      QString author(); 
-      QString comment();
-      bool saveInfo();
-      void setEmail(const QString& ); 
-      void setAuthor(const QString&);
-      void lastSaveOption(bool option);
-
-    protected: 
-      QLineEdit * author_le; 
-      QLineEdit * email_le; 
-      QCheckBox * save_ck;
-      QTextEdit * comment_te;
-    };
-
-    /** Auxiliary Dialog to get the option from the user about removing the entries 
-     *  from the local folder or the central repository. When removing from central 
-     *  repository, it will allow also to provide the justification.
-     */
-    class DeleteQueryBox : public QMessageBox{
-    public: 
-      DeleteQueryBox(const QString & path, QWidget* parent = 0);
-      ~DeleteQueryBox() override;
-      QString comment();
-    private: 
-      QTextEdit * comment_te; 
-    };
+  private:
+    RepoItem(const RepoItem &);
+    const RepoItem &operator=(const RepoItem &);
+  };
+
+  class UploadForm : public QDialog {
+  public:
+    UploadForm(const QString &file2upload, QWidget *parent = 0);
+    ~UploadForm() override;
+    QString email();
+    QString author();
+    QString comment();
+    bool saveInfo();
+    void setEmail(const QString &);
+    void setAuthor(const QString &);
+    void lastSaveOption(bool option);
+
+  protected:
+    QLineEdit *author_le;
+    QLineEdit *email_le;
+    QCheckBox *save_ck;
+    QTextEdit *comment_te;
+  };
+
+  /** Auxiliary Dialog to get the option from the user about removing the
+   * entries
+   *  from the local folder or the central repository. When removing from
+   * central
+   *  repository, it will allow also to provide the justification.
+   */
+  class DeleteQueryBox : public QMessageBox {
+  public:
+    DeleteQueryBox(const QString &path, QWidget *parent = 0);
+    ~DeleteQueryBox() override;
+    QString comment();
+
+  private:
+    QTextEdit *comment_te;
+  };
 
 public:
-    /// constructor
-    RepoModel(QObject *parent = 0);
-    /// destructor
-    ~RepoModel() override;
-    /// access to the ScriptRepository data
-    QVariant data(const QModelIndex &index, int role) const override;
-    /// information on the available interaction
-    Qt::ItemFlags flags(const QModelIndex &index) const override;
-    /// header strings
-    QVariant headerData(int section, Qt::Orientation orientation,
-                        int role = Qt::DisplayRole) const override;
-    /// access to the index
-    QModelIndex index(int row, int column,
-                      const QModelIndex &parent = QModelIndex()) const override;
-    /// access to parent
-    QModelIndex parent(const QModelIndex &index) const override;
-    //// provide the number of the rows
-    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
-    /// provide the nubmer of the coluns
-    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
-    /// change data
-    bool setData(const QModelIndex &index, const QVariant &value,
-                 int role = Qt::EditRole) override;
-
-    static const QString & localOnlySt(); 
-    static const QString & remoteOnlySt(); 
-    static const QString & localChangedSt(); 
-    static const QString & remoteChangedSt(); 
-    static const QString & updatedSt(); 
-    static const QString & bothChangedSt(); 
-    static const QString & downloadSt();
-    static const QString & uploadSt();
-
-    QString fileDescription(const QModelIndex & index); 
-    QString filePath(const QModelIndex & index);
-    QString author(const QModelIndex& index);
-
- signals:
-    void executingThread(bool);
+  /// constructor
+  RepoModel(QObject *parent = 0);
+  /// destructor
+  ~RepoModel() override;
+  /// access to the ScriptRepository data
+  QVariant data(const QModelIndex &index, int role) const override;
+  /// information on the available interaction
+  Qt::ItemFlags flags(const QModelIndex &index) const override;
+  /// header strings
+  QVariant headerData(int section, Qt::Orientation orientation,
+                      int role = Qt::DisplayRole) const override;
+  /// access to the index
+  QModelIndex index(int row, int column,
+                    const QModelIndex &parent = QModelIndex()) const override;
+  /// access to parent
+  QModelIndex parent(const QModelIndex &index) const override;
+  //// provide the number of the rows
+  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
+  /// provide the nubmer of the coluns
+  int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+  /// change data
+  bool setData(const QModelIndex &index, const QVariant &value,
+               int role = Qt::EditRole) override;
+
+  static const QString &localOnlySt();
+  static const QString &remoteOnlySt();
+  static const QString &localChangedSt();
+  static const QString &remoteChangedSt();
+  static const QString &updatedSt();
+  static const QString &bothChangedSt();
+  static const QString &downloadSt();
+  static const QString &uploadSt();
+
+  QString fileDescription(const QModelIndex &index);
+  QString filePath(const QModelIndex &index);
+  QString author(const QModelIndex &index);
+
+signals:
+  void executingThread(bool);
+
 private:
-    /// auxiliary method to populate the model
-    void setupModelData(RepoItem *parent);
-    /// auxiliary method to match the ScriptStatus to string
-    const QString & fromStatus(Mantid::API::SCRIPTSTATUS status)const; 
-    /// pointer to the RepoItem root
-    RepoItem *rootItem;
-    /// pointer to the ScriptRepository
-    Mantid::API::ScriptRepository_sptr repo_ptr;
-    /// ScriptLocalRepository path, to be able to retrieve the absolute path
-    QString repo_path;
-    /// auxiliary method to help populating the model
-    RepoItem * getParent(const QString & folder, QList<RepoItem*>&parents);
-
-    Q_DISABLE_COPY(RepoModel)
-    
-    /// auxiliary method to deal with exceptions
-    void handleExceptions(const Mantid::API::ScriptRepoException & ex, 
-                          const QString & title, 
-                          bool showWarning=true)const;
-
-    //handle download in thread
-    QFuture<QString> download_threads;
-    QFutureWatcher<QString> download_watcher;
-    QModelIndex download_index;
-    QString downloading_path;
-    bool isDownloading(const QModelIndex & index)const ; 
-    private slots:
-    void downloadFinished();
- private:
-    //handle connection to the uploader server in thread
-    // this connection are used to upload or deleting files.
-    
-    // QFuture variable, used to check if the thread is running, alive, etc... 
-    QFuture<QString> upload_threads;
-    // The mechanism to have a call back function executed after finishing the thread
-    QFutureWatcher<QString> upload_watcher;
-    // keep track of the file being used to the connection with uploader
-    QString uploading_path;
-    QModelIndex upload_index;
-    // check if the file pointed by the index is inside a connection with uploader
-    bool isUploading(const QModelIndex & index)const ; 
-    private slots:
-    // call back method executed after finishing the thread
-    void uploadFinished();
+  /// auxiliary method to populate the model
+  void setupModelData(RepoItem *parent);
+  /// auxiliary method to match the ScriptStatus to string
+  const QString &fromStatus(Mantid::API::SCRIPTSTATUS status) const;
+  /// pointer to the RepoItem root
+  RepoItem *rootItem;
+  /// pointer to the ScriptRepository
+  Mantid::API::ScriptRepository_sptr repo_ptr;
+  /// ScriptLocalRepository path, to be able to retrieve the absolute path
+  QString repo_path;
+  /// auxiliary method to help populating the model
+  RepoItem *getParent(const QString &folder, QList<RepoItem *> &parents);
 
-  };
+  Q_DISABLE_COPY(RepoModel)
+
+  /// auxiliary method to deal with exceptions
+  void handleExceptions(const Mantid::API::ScriptRepoException &ex,
+                        const QString &title, bool showWarning = true) const;
+
+  // handle download in thread
+  QFuture<QString> download_threads;
+  QFutureWatcher<QString> download_watcher;
+  QModelIndex download_index;
+  QString downloading_path;
+  bool isDownloading(const QModelIndex &index) const;
+private slots:
+  void downloadFinished();
+
+private:
+  // handle connection to the uploader server in thread
+  // this connection are used to upload or deleting files.
+
+  // QFuture variable, used to check if the thread is running, alive, etc...
+  QFuture<QString> upload_threads;
+  // The mechanism to have a call back function executed after finishing the
+  // thread
+  QFutureWatcher<QString> upload_watcher;
+  // keep track of the file being used to the connection with uploader
+  QString uploading_path;
+  QModelIndex upload_index;
+  // check if the file pointed by the index is inside a connection with uploader
+  bool isUploading(const QModelIndex &index) const;
+private slots:
+  // call back method executed after finishing the thread
+  void uploadFinished();
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_SCRIPTREPOSITORYVIEW_H_ */
+#endif /* MANTID_API_SCRIPTREPOSITORYVIEW_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/RepoTreeView.h b/MantidQt/API/inc/MantidQtAPI/RepoTreeView.h
index 26b206f89b75f5545f3d551b5608ecedd6ebdf0d..e5fd757a712a0c144f71e47f70bc0d5632807861 100644
--- a/MantidQt/API/inc/MantidQtAPI/RepoTreeView.h
+++ b/MantidQt/API/inc/MantidQtAPI/RepoTreeView.h
@@ -4,58 +4,57 @@
 #include "DllOption.h"
 #include <QTreeView>
 
-namespace MantidQt
-{
-namespace API
-{
-  /** RepoTreeView : A specialization of QTreeView class that emits signal every time
-      the selection change. It extends the currentChanged method in order to add the 
-      emition of the signal currentCell.
-    
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class  EXPORT_OPT_MANTIDQT_API RepoTreeView : public QTreeView
-  {
-    Q_OBJECT
-
-   public:
-    // constuctor 
-    RepoTreeView(QWidget * parent=0):QTreeView(parent){};
-    // destructor - not virtual, because this is not intended to be base
-    ~RepoTreeView() override{};
-
-  signals:
-    void currentCell(const QModelIndex& ); 
-  
-  protected slots:
-
-    void currentChanged(const QModelIndex &current,
-                        const QModelIndex &previous) override {
-      QTreeView::currentChanged(current,previous); 
-      emit currentCell(current);
-    };
+namespace MantidQt {
+namespace API {
+/** RepoTreeView : A specialization of QTreeView class that emits signal every
+  time
+    the selection change. It extends the currentChanged method in order to add
+  the
+    emition of the signal currentCell.
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API RepoTreeView : public QTreeView {
+  Q_OBJECT
+
+public:
+  // constuctor
+  RepoTreeView(QWidget *parent = 0) : QTreeView(parent){};
+  // destructor - not virtual, because this is not intended to be base
+  ~RepoTreeView() override{};
+
+signals:
+  void currentCell(const QModelIndex &);
+
+protected slots:
+
+  void currentChanged(const QModelIndex &current,
+                      const QModelIndex &previous) override {
+    QTreeView::currentChanged(current, previous);
+    emit currentCell(current);
   };
-
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_REPOTREEVIEW_H_ */
+#endif /* MANTID_API_REPOTREEVIEW_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/ScaleEngine.h b/MantidQt/API/inc/MantidQtAPI/ScaleEngine.h
index 91f1a6295a782eb1c93b270f0652b3cbb139f8cf..66b4a746169969ce25e608e47a5dd865b2085b47 100644
--- a/MantidQt/API/inc/MantidQtAPI/ScaleEngine.h
+++ b/MantidQt/API/inc/MantidQtAPI/ScaleEngine.h
@@ -4,7 +4,8 @@
     --------------------------------------------------------------------
     Copyright            : (C) 2007 by Ion Vasilief
     Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : Extensions to QwtScaleEngine and QwtScaleTransformation
+    Description          : Extensions to QwtScaleEngine and
+ QwtScaleTransformation
 
  ***************************************************************************/
 
@@ -36,95 +37,96 @@
 
 class ScaleEngine;
 
-class EXPORT_OPT_MANTIDQT_API ScaleTransformation: public QwtScaleTransformation
-{
+class EXPORT_OPT_MANTIDQT_API ScaleTransformation
+    : public QwtScaleTransformation {
 public:
-	enum Type{Linear, Log10, Power};
+  enum Type { Linear, Log10, Power };
 
-	ScaleTransformation(const ScaleEngine *engine):QwtScaleTransformation(Other), d_engine(engine){};
-        double xForm(double x, double, double, double p1,
-                     double p2) const override;
-        double invXForm(double x, double s1, double s2, double p1,
-                        double p2) const override;
-        QwtScaleTransformation *copy() const override;
-        ~ScaleTransformation() override;
+  ScaleTransformation(const ScaleEngine *engine)
+      : QwtScaleTransformation(Other), d_engine(engine){};
+  double xForm(double x, double, double, double p1, double p2) const override;
+  double invXForm(double x, double s1, double s2, double p1,
+                  double p2) const override;
+  QwtScaleTransformation *copy() const override;
+  ~ScaleTransformation() override;
 
 protected:
-	QwtScaleTransformation* newScaleTransformation() const;
-    //! The scale engine that generates the transformation
-	const ScaleEngine* d_engine;
+  QwtScaleTransformation *newScaleTransformation() const;
+  //! The scale engine that generates the transformation
+  const ScaleEngine *d_engine;
 };
 
-class EXPORT_OPT_MANTIDQT_API ScaleEngine: public QwtScaleEngine
-{
+class EXPORT_OPT_MANTIDQT_API ScaleEngine : public QwtScaleEngine {
 public:
-	ScaleEngine(ScaleTransformation::Type type = ScaleTransformation::Linear,
-				double left_break = -DBL_MAX, double right_break = DBL_MAX);
+  ScaleEngine(ScaleTransformation::Type type = ScaleTransformation::Linear,
+              double left_break = -DBL_MAX, double right_break = DBL_MAX);
 
-        ~ScaleEngine() override;
+  ~ScaleEngine() override;
 
-        QwtScaleTransformation *transformation() const override;
-        QwtScaleDiv divideScale(double x1, double x2, int maxMajSteps,
-                                int maxMinSteps,
-                                double stepSize = 0.0) const override;
-        void autoScale(int maxNumSteps, double &x1, double &x2,
-                       double &stepSize) const override;
+  QwtScaleTransformation *transformation() const override;
+  QwtScaleDiv divideScale(double x1, double x2, int maxMajSteps,
+                          int maxMinSteps,
+                          double stepSize = 0.0) const override;
+  void autoScale(int maxNumSteps, double &x1, double &x2,
+                 double &stepSize) const override;
 
-    double axisBreakLeft() const;
-    double axisBreakRight() const;
-	void setBreakRegion(double from, double to){d_break_left = from; d_break_right = to;};
+  double axisBreakLeft() const;
+  double axisBreakRight() const;
+  void setBreakRegion(double from, double to) {
+    d_break_left = from;
+    d_break_right = to;
+  };
 
-	int breakWidth() const;
-	void setBreakWidth(int width){d_break_width = width;};
+  int breakWidth() const;
+  void setBreakWidth(int width) { d_break_width = width; };
 
-	int breakPosition() const;
-	void setBreakPosition(int pos){d_break_pos = pos;};
+  int breakPosition() const;
+  void setBreakPosition(int pos) { d_break_pos = pos; };
 
-    double stepBeforeBreak() const;
-    void setStepBeforeBreak(double step){d_step_before = step;};
+  double stepBeforeBreak() const;
+  void setStepBeforeBreak(double step) { d_step_before = step; };
 
-    double stepAfterBreak() const;
-    void setStepAfterBreak(double step){d_step_after = step;};
+  double stepAfterBreak() const;
+  void setStepAfterBreak(double step) { d_step_after = step; };
 
-    int minTicksBeforeBreak() const;
-    void setMinTicksBeforeBreak(int ticks){d_minor_ticks_before = ticks;};
+  int minTicksBeforeBreak() const;
+  void setMinTicksBeforeBreak(int ticks) { d_minor_ticks_before = ticks; };
 
-    int minTicksAfterBreak() const;
-    void setMinTicksAfterBreak(int ticks){d_minor_ticks_after = ticks;};
+  int minTicksAfterBreak() const;
+  void setMinTicksAfterBreak(int ticks) { d_minor_ticks_after = ticks; };
 
-    bool log10ScaleAfterBreak() const;
-    void setLog10ScaleAfterBreak(bool on){d_log10_scale_after = on;};
+  bool log10ScaleAfterBreak() const;
+  void setLog10ScaleAfterBreak(bool on) { d_log10_scale_after = on; };
 
-    double nthPower() const;
-    void setNthPower(double nth_power){d_nth_power = nth_power;};
+  double nthPower() const;
+  void setNthPower(double nth_power) { d_nth_power = nth_power; };
 
-	ScaleTransformation::Type type() const;
-	void setType(ScaleTransformation::Type type){d_type = type;};
+  ScaleTransformation::Type type() const;
+  void setType(ScaleTransformation::Type type) { d_type = type; };
 
-	bool hasBreak() const;
-	void clone(const ScaleEngine *engine);
+  bool hasBreak() const;
+  void clone(const ScaleEngine *engine);
 
-	bool hasBreakDecoration() const;
-	void drawBreakDecoration(bool draw){d_break_decoration = draw;};
+  bool hasBreakDecoration() const;
+  void drawBreakDecoration(bool draw) { d_break_decoration = draw; };
 
 private:
-
-	QwtScaleEngine *newScaleEngine() const;
-
-	ScaleTransformation::Type d_type;
-	double d_break_left, d_break_right;
-	//! Position of axis break (% of axis length)
-	int d_break_pos;
-	//! Scale increment before and after break
-	double d_step_before, d_step_after;
-	//! Minor ticks before and after break
-	int d_minor_ticks_before, d_minor_ticks_after;
-	//! Log10 scale after break
-	bool d_log10_scale_after;
-	//! Width of the axis break in pixels
-	int d_break_width;
-	//! If true draw the break decoration
-	bool d_break_decoration;
+  QwtScaleEngine *newScaleEngine() const;
+
+  ScaleTransformation::Type d_type;
+  double d_break_left, d_break_right;
+  //! Position of axis break (% of axis length)
+  int d_break_pos;
+  //! Scale increment before and after break
+  double d_step_before, d_step_after;
+  //! Minor ticks before and after break
+  int d_minor_ticks_before, d_minor_ticks_after;
+  //! Log10 scale after break
+  bool d_log10_scale_after;
+  //! Width of the axis break in pixels
+  int d_break_width;
+  //! If true draw the break decoration
+  bool d_break_decoration;
   //! Nth Power for a power scale
   double d_nth_power;
 };
diff --git a/MantidQt/API/inc/MantidQtAPI/ScriptRepositoryView.h b/MantidQt/API/inc/MantidQtAPI/ScriptRepositoryView.h
index 782ab37933fd49b2d77404219412819d7401b0e8..32e94f38ed1944653ef35bca8e2a2ded64bbe16d 100644
--- a/MantidQt/API/inc/MantidQtAPI/ScriptRepositoryView.h
+++ b/MantidQt/API/inc/MantidQtAPI/ScriptRepositoryView.h
@@ -6,104 +6,104 @@
 #include "ui_ScriptRepositoryView.h"
 #include "DllOption.h"
 
-namespace MantidQt
-{
-namespace API
-{
-  class RepoModel;
-  /** ScriptRepositoryView : Provide the User Interface to the ScriptRepository. It does so 
-      through the Mantid Model View Framework. It is composed by a specialized QTreeView 
-      (RepoTreeView) and a TextBrowser. The TreeView is populated with the RepoModel, wich wrappers
-      the ScriptRepository. Inside this class, there are two nested classes that will implement 
-      delegates to the columns of Status and AutoUpdate in order to improve the User Experience. 
-    
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class  EXPORT_OPT_MANTIDQT_API ScriptRepositoryView : public QDialog
-  {
-    Q_OBJECT
-
-      /// Delegate to show the icons Download and Upload
-    class RepoDelegate : public QStyledItemDelegate
-    {
-    public:
-      RepoDelegate(QObject *parent = 0);
-
-      void paint(QPainter *painter, const QStyleOptionViewItem &option,
-                 const QModelIndex &index) const override;
-      bool editorEvent(QEvent *event, QAbstractItemModel *model,
-                       const QStyleOptionViewItem &option,
-                       const QModelIndex &index) override;
-      QSize sizeHint(const QStyleOptionViewItem &option,
-                     const QModelIndex &index) const override;
-    };
-    /// Delegate to show the checkbox for configuring the auto update
-    class CheckBoxDelegate : public QStyledItemDelegate
-    {
-    public:
-      CheckBoxDelegate(QObject * parent = 0);
-      void paint(QPainter *painter, const QStyleOptionViewItem &option,
-                 const QModelIndex &index) const override;
-      bool editorEvent(QEvent *event, QAbstractItemModel *model,
-                       const QStyleOptionViewItem &option,
-                       const QModelIndex &index) override;
-    };
-    /// Delegate to show the icon to remove the entry from the local and central repository
-    class RemoveEntryDelegate : public QStyledItemDelegate
-    {
-    public:
-      RemoveEntryDelegate(QObject * parent = 0);
-      void paint(QPainter *painter, const QStyleOptionViewItem &option,
-                 const QModelIndex &index) const override;
-      bool editorEvent(QEvent *event, QAbstractItemModel *model,
-                       const QStyleOptionViewItem &option,
-                       const QModelIndex &index) override;
-    };
-
-   public:
-    // constuctor 
-    ScriptRepositoryView(QWidget * parent=0);
-    // destructor - not virtual, because this is not intended to be base
-    ~ScriptRepositoryView() override;
-
-  signals:
-    // allow Mantid Plot to open a python file to be seen 
-    void loadScript(const QString);
-    
-  protected slots:
-    // allow to interact with the cells, in order to update the description of the files
-    void cell_activated(const QModelIndex & ); 
-    void updateModel();
-    void currentChanged ( const QModelIndex & current );
-    void helpClicked();
-    void openFolderLink(QString);
-
-
-  private:
-    Ui::ScriptRepositoryView * ui; 
-    RepoModel * model;
+namespace MantidQt {
+namespace API {
+class RepoModel;
+/** ScriptRepositoryView : Provide the User Interface to the ScriptRepository.
+  It does so
+    through the Mantid Model View Framework. It is composed by a specialized
+  QTreeView
+    (RepoTreeView) and a TextBrowser. The TreeView is populated with the
+  RepoModel, wich wrappers
+    the ScriptRepository. Inside this class, there are two nested classes that
+  will implement
+    delegates to the columns of Status and AutoUpdate in order to improve the
+  User Experience.
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API ScriptRepositoryView : public QDialog {
+  Q_OBJECT
+
+  /// Delegate to show the icons Download and Upload
+  class RepoDelegate : public QStyledItemDelegate {
+  public:
+    RepoDelegate(QObject *parent = 0);
+
+    void paint(QPainter *painter, const QStyleOptionViewItem &option,
+               const QModelIndex &index) const override;
+    bool editorEvent(QEvent *event, QAbstractItemModel *model,
+                     const QStyleOptionViewItem &option,
+                     const QModelIndex &index) override;
+    QSize sizeHint(const QStyleOptionViewItem &option,
+                   const QModelIndex &index) const override;
+  };
+  /// Delegate to show the checkbox for configuring the auto update
+  class CheckBoxDelegate : public QStyledItemDelegate {
+  public:
+    CheckBoxDelegate(QObject *parent = 0);
+    void paint(QPainter *painter, const QStyleOptionViewItem &option,
+               const QModelIndex &index) const override;
+    bool editorEvent(QEvent *event, QAbstractItemModel *model,
+                     const QStyleOptionViewItem &option,
+                     const QModelIndex &index) override;
+  };
+  /// Delegate to show the icon to remove the entry from the local and central
+  /// repository
+  class RemoveEntryDelegate : public QStyledItemDelegate {
+  public:
+    RemoveEntryDelegate(QObject *parent = 0);
+    void paint(QPainter *painter, const QStyleOptionViewItem &option,
+               const QModelIndex &index) const override;
+    bool editorEvent(QEvent *event, QAbstractItemModel *model,
+                     const QStyleOptionViewItem &option,
+                     const QModelIndex &index) override;
   };
 
+public:
+  // constuctor
+  ScriptRepositoryView(QWidget *parent = 0);
+  // destructor - not virtual, because this is not intended to be base
+  ~ScriptRepositoryView() override;
+
+signals:
+  // allow Mantid Plot to open a python file to be seen
+  void loadScript(const QString);
+
+protected slots:
+  // allow to interact with the cells, in order to update the description of the
+  // files
+  void cell_activated(const QModelIndex &);
+  void updateModel();
+  void currentChanged(const QModelIndex &current);
+  void helpClicked();
+  void openFolderLink(QString);
+
+private:
+  Ui::ScriptRepositoryView *ui;
+  RepoModel *model;
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_SCRIPTREPOSITORYVIEW_H_ */
+#endif /* MANTID_API_SCRIPTREPOSITORYVIEW_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/SelectionNotificationService.h b/MantidQt/API/inc/MantidQtAPI/SelectionNotificationService.h
index be793d990e5f3f18cf0e8333420a894bfc74e1de..f0d06640beb0f3c0eceff558a2b3c6be7cd7d9dd 100644
--- a/MantidQt/API/inc/MantidQtAPI/SelectionNotificationService.h
+++ b/MantidQt/API/inc/MantidQtAPI/SelectionNotificationService.h
@@ -5,74 +5,75 @@
 #include "DllOption.h"
 #include "MantidKernel/SingletonHolder.h"
 
-namespace MantidQt
-{
-  namespace API
-  {
-    //---------------------------------------------------------------------
-    //
-    //---------------------------------------------------------------------
-
-    /** 
-    Provides a simple loosely coupled mechanism for passing information 
-    about a selected point from several possible sources to several 
-    possible destinations.  Neither the sources, or the destinations 
-    need exist or have references to each other.  Currently the only
-    "message" supported is a QPointSelection message.  To send the message,
-    an object just needs to call the sendQPointSelection() method on the
-    single Instance() of this class. 
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_API SelectionNotificationServiceImpl : public QObject
-    {
-    Q_OBJECT
-
-    public:
-
-      /// Emit the QPointSelection_signal, callable from any thread
-      void sendQPointSelection( bool lab_coords, double qx, double qy, double qz );
-
-    signals:
-      void QPointSelection_signal( bool, double, double, double );
-
-    private:
-      /// private constructor, since SelectionNotificationService is a singleton
-      SelectionNotificationServiceImpl();
-
-      /// private constructor, since SelectionNotificationService is a singleton
-      ~SelectionNotificationServiceImpl() override;
-
-      friend struct Mantid::Kernel::CreateUsingNew<SelectionNotificationServiceImpl>;      
-   };
-
-   /// Forward declaration of a specialisation of SingletonHolder for SelectionNotificationServiceImpl
-   /// (needed for dllexport/dllimport) and a typedef for it.
+namespace MantidQt {
+namespace API {
+//---------------------------------------------------------------------
+//
+//---------------------------------------------------------------------
+
+/**
+Provides a simple loosely coupled mechanism for passing information
+about a selected point from several possible sources to several
+possible destinations.  Neither the sources, or the destinations
+need exist or have references to each other.  Currently the only
+"message" supported is a QPointSelection message.  To send the message,
+an object just needs to call the sendQPointSelection() method on the
+single Instance() of this class.
+
+Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API SelectionNotificationServiceImpl
+    : public QObject {
+  Q_OBJECT
+
+public:
+  /// Emit the QPointSelection_signal, callable from any thread
+  void sendQPointSelection(bool lab_coords, double qx, double qy, double qz);
+
+signals:
+  void QPointSelection_signal(bool, double, double, double);
+
+private:
+  /// private constructor, since SelectionNotificationService is a singleton
+  SelectionNotificationServiceImpl();
+
+  /// private constructor, since SelectionNotificationService is a singleton
+  ~SelectionNotificationServiceImpl() override;
+
+  friend struct Mantid::Kernel::CreateUsingNew<
+      SelectionNotificationServiceImpl>;
+};
+
+/// Forward declaration of a specialisation of SingletonHolder for
+/// SelectionNotificationServiceImpl
+/// (needed for dllexport/dllimport) and a typedef for it.
 #ifdef _WIN32
-  template class EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<SelectionNotificationServiceImpl>;
+template class EXPORT_OPT_MANTIDQT_API
+    Mantid::Kernel::SingletonHolder<SelectionNotificationServiceImpl>;
 #endif /* _WIN32 */
 
-  typedef EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<SelectionNotificationServiceImpl> SelectionNotificationService;
-
-  }
+typedef EXPORT_OPT_MANTIDQT_API Mantid::Kernel::SingletonHolder<
+    SelectionNotificationServiceImpl> SelectionNotificationService;
+}
 }
 
 #endif // MANTIDQTAPI_SELECTION_NOTIFICATION_SERVICE_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/SignalBlocker.h b/MantidQt/API/inc/MantidQtAPI/SignalBlocker.h
index be7478473a859a071b99029e996b6bcde59fda9c..2600a877f8517041e06cde87a8966f1ae6c4f3bc 100644
--- a/MantidQt/API/inc/MantidQtAPI/SignalBlocker.h
+++ b/MantidQt/API/inc/MantidQtAPI/SignalBlocker.h
@@ -30,19 +30,19 @@ namespace API {
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-template <typename Type>
-class EXPORT_OPT_MANTIDQT_API SignalBlocker {
+template <typename Type> class EXPORT_OPT_MANTIDQT_API SignalBlocker {
 
 private:
   /// Object to manage blocking
   Type *m_obj;
+
 public:
   /// Constructor
   SignalBlocker(Type *obj);
   /// Destructor
   ~SignalBlocker();
   /// Overriden function like behavior.
-  Type* operator->();
+  Type *operator->();
   /// Release management
   void release();
 };
diff --git a/MantidQt/API/inc/MantidQtAPI/SignalRange.h b/MantidQt/API/inc/MantidQtAPI/SignalRange.h
index 99a9ebba7ea66fca3ab2bd18a755ab9630b984ae..9bc0dfebcd2e2ee0ffb8f6de608b4afd38ce306d 100644
--- a/MantidQt/API/inc/MantidQtAPI/SignalRange.h
+++ b/MantidQt/API/inc/MantidQtAPI/SignalRange.h
@@ -7,63 +7,64 @@
 
 #include <qwt_double_interval.h>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    /**
-     Calculates the signal range from a given workspace and optional MDFunction
+namespace MantidQt {
+namespace API {
+/**
+ Calculates the signal range from a given workspace and optional MDFunction
 
-     Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-     This file is part of Mantid.
+ This file is part of Mantid.
 
-     Mantid is free software; you can redistribute it and/or modify
-     it under the terms of the GNU General Public License as published by
-     the Free Software Foundation; either version 3 of the License, or
-     (at your option) any later version.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-     Mantid is distributed in the hope that it will be useful,
-     but WITHOUT ANY WARRANTY; without even the implied warranty of
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-     GNU General Public License for more details.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-     You should have received a copy of the GNU General Public License
-     along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-     File change history is stored at: <https://github.com/mantidproject/mantid>.
-     Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class EXPORT_OPT_MANTIDQT_API SignalRange
-    {
-    public:
-      SignalRange(const Mantid::API::IMDWorkspace & workspace,
-                  const Mantid::API::MDNormalization normalization = Mantid::API::NoNormalization);
-      SignalRange(const Mantid::API::IMDWorkspace & workspace,
-                  Mantid::Geometry::MDImplicitFunction &function,
-                  const Mantid::API::MDNormalization normalization = Mantid::API::NoNormalization);
+ File change history is stored at: <https://github.com/mantidproject/mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API SignalRange {
+public:
+  SignalRange(const Mantid::API::IMDWorkspace &workspace,
+              const Mantid::API::MDNormalization normalization =
+                  Mantid::API::NoNormalization);
+  SignalRange(const Mantid::API::IMDWorkspace &workspace,
+              Mantid::Geometry::MDImplicitFunction &function,
+              const Mantid::API::MDNormalization normalization =
+                  Mantid::API::NoNormalization);
 
-      /// Returns the range of the workspace signal values
-      QwtDoubleInterval interval() const;
+  /// Returns the range of the workspace signal values
+  QwtDoubleInterval interval() const;
 
-    private:
-      DISABLE_DEFAULT_CONSTRUCT(SignalRange)
+private:
+  DISABLE_DEFAULT_CONSTRUCT(SignalRange)
 
-      /// Find the min/max signal values in the entire workspace
-      void findFullRange(const Mantid::API::IMDWorkspace & workspace,
-                         Mantid::Geometry::MDImplicitFunction *function);
-      /// Get the range of signal, in parallel, given an iterator
-      QwtDoubleInterval getRange(const std::vector<Mantid::API::IMDIterator *> & iterators);
-      ///Get the range of signal given an iterator
-      QwtDoubleInterval getRange(Mantid::API::IMDIterator * it);
+  /// Find the min/max signal values in the entire workspace
+  void findFullRange(const Mantid::API::IMDWorkspace &workspace,
+                     Mantid::Geometry::MDImplicitFunction *function);
+  /// Get the range of signal, in parallel, given an iterator
+  QwtDoubleInterval
+  getRange(const std::vector<Mantid::API::IMDIterator *> &iterators);
+  /// Get the range of signal given an iterator
+  QwtDoubleInterval getRange(Mantid::API::IMDIterator *it);
 
-      /// The range of the signal data
-      QwtDoubleInterval m_interval;
-      /// The normalization used for the signals
-      Mantid::API::MDNormalization m_normalization;
-    };
+  /// The range of the signal data
+  QwtDoubleInterval m_interval;
+  /// The normalization used for the signals
+  Mantid::API::MDNormalization m_normalization;
+};
 
-  } // namespace API
+} // namespace API
 } // namespace MantidQt
 
 #endif /* MANTIDQT_API_SIGNALRANGE_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/SyncedCheckboxes.h b/MantidQt/API/inc/MantidQtAPI/SyncedCheckboxes.h
index eb89341dde1da2fdb2c473eaf24a63fbea38bdbf..5e49c1730fb07f5df075a4782781bf267bf4e10c 100644
--- a/MantidQt/API/inc/MantidQtAPI/SyncedCheckboxes.h
+++ b/MantidQt/API/inc/MantidQtAPI/SyncedCheckboxes.h
@@ -7,67 +7,65 @@
 #include <qpushbutton.h>
 #include <QtGui/qaction.h>
 
-namespace MantidQt
-{
-namespace API
-{
-
-  /** QObject that links:
-
-    - a checkable QAction (menu item)
-    - and a checkable QAbstractButton (like a toolbar button)
-
-    so that their checked status is consistent.
-    Emits a single "toggled" signal if either one is toggled.
-    
-    @date 2011-12-06
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_API SyncedCheckboxes : public QObject
-  {
-    Q_OBJECT
-
-  public:
-    SyncedCheckboxes(QAction * menu, QAbstractButton * button, bool checked = false);
-    ~SyncedCheckboxes() override;
-    void toggle(bool val);
-    void setEnabled(bool val);
-    void setVisible(bool val);
-    
-  signals:
-    /// Signal emitted when the check box is toggled
-    void toggled(bool);
-
-  public slots:
-    void on_menu_toggled(bool);
-    void on_button_toggled(bool);
-
-  private:
-    QAction * m_menu;
-    QAbstractButton * m_button;
-  };
+namespace MantidQt {
+namespace API {
 
+/** QObject that links:
+
+  - a checkable QAction (menu item)
+  - and a checkable QAbstractButton (like a toolbar button)
+
+  so that their checked status is consistent.
+  Emits a single "toggled" signal if either one is toggled.
+
+  @date 2011-12-06
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API SyncedCheckboxes : public QObject {
+  Q_OBJECT
+
+public:
+  SyncedCheckboxes(QAction *menu, QAbstractButton *button,
+                   bool checked = false);
+  ~SyncedCheckboxes() override;
+  void toggle(bool val);
+  void setEnabled(bool val);
+  void setVisible(bool val);
+
+signals:
+  /// Signal emitted when the check box is toggled
+  void toggled(bool);
+
+public slots:
+  void on_menu_toggled(bool);
+  void on_button_toggled(bool);
+
+private:
+  QAction *m_menu;
+  QAbstractButton *m_button;
+};
 
 } // namespace API
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_API_SYNCEDCHECKBOXES_H_ */
+#endif /* MANTIDQT_API_SYNCEDCHECKBOXES_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/TextPropertyWidget.h b/MantidQt/API/inc/MantidQtAPI/TextPropertyWidget.h
index ff5750190930dbce1685d8274b56e0129c3f1172..16bab8a7d580c1aa990fa67ce204ccc8cf17767e 100644
--- a/MantidQt/API/inc/MantidQtAPI/TextPropertyWidget.h
+++ b/MantidQt/API/inc/MantidQtAPI/TextPropertyWidget.h
@@ -6,61 +6,57 @@
 #include <qlineedit.h>
 #include <QLabel>
 
+namespace MantidQt {
+namespace API {
 
-namespace MantidQt
-{
-namespace API
-{
+/** The most generic widgets for Property's that are only
+ * a simple string.
 
-  /** The most generic widgets for Property's that are only
-   * a simple string.
-    
-    @date 2012-02-16
+  @date 2012-02-16
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport TextPropertyWidget : public PropertyWidget
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport TextPropertyWidget : public PropertyWidget {
+  Q_OBJECT
 
-  public:
-    TextPropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent = NULL, QGridLayout * layout = NULL, int row=-1);
-    ~TextPropertyWidget() override;
-    QString getValue() const override;
-    void setValueImpl(const QString &value) override;
+public:
+  TextPropertyWidget(Mantid::Kernel::Property *prop, QWidget *parent = NULL,
+                     QGridLayout *layout = NULL, int row = -1);
+  ~TextPropertyWidget() override;
+  QString getValue() const override;
+  void setValueImpl(const QString &value) override;
 
-    ///@return the main widget of this combo of widgets
-    QWidget *getMainWidget() override { return m_textbox; }
+  ///@return the main widget of this combo of widgets
+  QWidget *getMainWidget() override { return m_textbox; }
 
-  protected:
-    /// Label (name of the property)
-    QLabel * m_label;
-
-    /// The text box to edit
-    QLineEdit * m_textbox;
-
-  };
+protected:
+  /// Label (name of the property)
+  QLabel *m_label;
 
+  /// The text box to edit
+  QLineEdit *m_textbox;
+};
 
 } // namespace API
 } // namespace Mantid
 
-#endif  /* MANTID_API_TEXTPROPERTYWIDGET_H_ */
+#endif /* MANTID_API_TEXTPROPERTYWIDGET_H_ */
diff --git a/MantidQt/API/inc/MantidQtAPI/UserSubWindow.h b/MantidQt/API/inc/MantidQtAPI/UserSubWindow.h
index 5d191cf619e98a036b79fa5180dfbedd1e3cb73c..633193b0834ccd2b7be573d9ebe6b67f11c59837 100644
--- a/MantidQt/API/inc/MantidQtAPI/UserSubWindow.h
+++ b/MantidQt/API/inc/MantidQtAPI/UserSubWindow.h
@@ -1,17 +1,17 @@
 #ifndef MANTIDQT_API_USERSUBWINDOW_H_
 #define MANTIDQT_API_USERSUBWINDOW_H_
 
-
 /* Used to register classes into the factory. Creates a global object in an
 * anonymous namespace. The object itself does nothing, but the comma operator
 * is used in the call to its constructor to effect a call to the factory's
 * subscribe method.
 */
-#define DECLARE_SUBWINDOW(classname) \
-  namespace { \
-    Mantid::Kernel::RegistrationHelper \
-    register_subwindow_##classname \
-    (((MantidQt::API::UserSubWindowFactory::Instance().subscribe<classname>()), 0)); \
+#define DECLARE_SUBWINDOW(classname)                                           \
+  namespace {                                                                  \
+  Mantid::Kernel::RegistrationHelper register_subwindow_##classname(           \
+      ((MantidQt::API::UserSubWindowFactory::Instance()                        \
+            .subscribe<classname>()),                                          \
+       0));                                                                    \
   }
 
 //----------------------------------
@@ -35,32 +35,29 @@
 // Mantid Forward declarations
 //----------------------------------
 
-//Top-level namespace for this library
-namespace MantidQt
-{
-  namespace MantidWidgets 
-  {
-  class FitPropertyBrowser;
-  }
+// Top-level namespace for this library
+namespace MantidQt {
+namespace MantidWidgets {
+class FitPropertyBrowser;
+}
 
-namespace API 
-{
+namespace API {
 
 //----------------------------------
 // Forward declarations
 //----------------------------------
 class InterfaceManager;
 
-
-
-/** 
-    This is the base class all customised user interfaces that do not wish to be tied
+/**
+    This is the base class all customised user interfaces that do not wish to be
+   tied
     to a specific Mantid algorithm but rather customised for user's requirements
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 18/03/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -78,26 +75,28 @@ class InterfaceManager;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_API UserSubWindow : public QMainWindow
-{
+class EXPORT_OPT_MANTIDQT_API UserSubWindow : public QMainWindow {
   Q_OBJECT
 
 public:
   /// Name of the interface
-  static std::string name() { return "UserSubWindow::name() default Reimplement static name() method."; }
+  static std::string name() {
+    return "UserSubWindow::name() default Reimplement static name() method.";
+  }
   /// A list of aliases
   static std::set<std::string> aliases() { return std::set<std::string>(); }
 
 public:
   /// DefaultConstructor
-  UserSubWindow(QWidget* parent = 0);
+  UserSubWindow(QWidget *parent = 0);
   /// Destructor
   ~UserSubWindow() override;
   /// Create the layout of the widget. Can only be called once.
   void initializeLayout();
-  /// Run local Python init code. Calls overridable function in specialized interface
+  /// Run local Python init code. Calls overridable function in specialized
+  /// interface
   void initializeLocalPython();
   /// Is this dialog initialized
   bool isInitialized() const;
@@ -106,11 +105,12 @@ public:
 
 signals:
   /// Emitted to start a (generally small) script running
-  void runAsPythonScript(const QString& code, bool);
+  void runAsPythonScript(const QString &code, bool);
 
   /// Thrown when used fit property browser should be changed to given one
-  void setFitPropertyBrowser(MantidQt::MantidWidgets::FitPropertyBrowser* browser);
-  
+  void
+  setFitPropertyBrowser(MantidQt::MantidWidgets::FitPropertyBrowser *browser);
+
 protected:
   /**@name Virtual Functions */
   //@{
@@ -119,14 +119,15 @@ protected:
   /// Run local Python setup code
   virtual void initLocalPython() {}
   //@}
-  
+
   /// Raise a dialog box giving some information
-  void showInformationBox(const QString & message) const;
-  
-  /// Run a piece of python code and return any output that was written to stdout
-  QString runPythonCode(const QString & code, bool no_output = false);
+  void showInformationBox(const QString &message) const;
+
+  /// Run a piece of python code and return any output that was written to
+  /// stdout
+  QString runPythonCode(const QString &code, bool no_output = false);
   QString openFileDialog(const bool save, const QStringList &exts);
-  QLabel* newValidator(QWidget *parent);
+  QLabel *newValidator(QWidget *parent);
 
 private:
   // This is so that it can set the name
@@ -135,7 +136,7 @@ private:
   friend class InterfaceManager;
 
   /// Set the interface name
-  void setInterfaceName(const QString & iface_name);
+  void setInterfaceName(const QString &iface_name);
   /// Has this already been initialized
   bool m_bIsInitialized;
   /// Has the python initialization been run
@@ -146,8 +147,7 @@ private:
   /// Python executor
   PythonRunner m_pythonRunner;
 };
-
 }
 }
 
-#endif //MANTIDQT_API_USERSUBWINDOW_H_
+#endif // MANTIDQT_API_USERSUBWINDOW_H_
diff --git a/MantidQt/API/inc/MantidQtAPI/VatesViewerInterface.h b/MantidQt/API/inc/MantidQtAPI/VatesViewerInterface.h
index 14829fda8e43799d8a4924ca6a8d1b5766821bbd..cf1be78c837280efade1c28632f9fa4b14b98d94 100644
--- a/MantidQt/API/inc/MantidQtAPI/VatesViewerInterface.h
+++ b/MantidQt/API/inc/MantidQtAPI/VatesViewerInterface.h
@@ -9,20 +9,20 @@
 
 class QString;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
 /**
  *
-  This class is an interface for the central widget for handling VATES visualization
+  This class is an interface for the central widget for handling VATES
+ visualization
   operations. Its main use is for the plugin mode operation of the viewer.
 
   @author Michael Reuter
   @date 08/09/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -42,8 +42,7 @@ namespace API
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDQT_API VatesViewerInterface : public QWidget
-{
+class EXPORT_OPT_MANTIDQT_API VatesViewerInterface : public QWidget {
   Q_OBJECT
 public:
   /// Default constructor for plugin mode.
@@ -61,7 +60,8 @@ public:
    * @param workspaceType the type of workspace being visualized
    * @param instrumentName The Name of the instrument.
    */
-  virtual void renderWorkspace(QString workspaceName, int workspaceType, std::string instrumentName);
+  virtual void renderWorkspace(QString workspaceName, int workspaceType,
+                               std::string instrumentName);
 
   /**
    * Special function of correct widget invocation for plugin mode.
@@ -79,7 +79,6 @@ public slots:
   /// Perform any clean up on main window shutdown
   virtual void shutdown();
 };
-
 }
 }
 
diff --git a/MantidQt/API/inc/MantidQtAPI/WorkspaceObserver.h b/MantidQt/API/inc/MantidQtAPI/WorkspaceObserver.h
index 909c98bf06b8aa8fa5bad81ebf34c5d65218d11b..a637c021cb8fa812833dcb6039bb06e2673f98c0 100644
--- a/MantidQt/API/inc/MantidQtAPI/WorkspaceObserver.h
+++ b/MantidQt/API/inc/MantidQtAPI/WorkspaceObserver.h
@@ -8,7 +8,6 @@
 #include "DllOption.h"
 #include <QMetaType>
 
-
 Q_DECLARE_METATYPE(std::string)
 Q_DECLARE_METATYPE(Mantid::API::Workspace_sptr)
 
@@ -16,244 +15,250 @@ Q_DECLARE_METATYPE(Mantid::API::Workspace_sptr)
 // Mantid Forward declaration
 //------------------------------------------------
 
-namespace MantidQt
-{
-  namespace API
-  {
-    //------------------------------------------------
-    // Forward declaration
-    //------------------------------------------------
-    class WorkspaceObserver;
-
-    /**
-    * A simple callback class so that we avoid multiple inheritance issues with QObject.
-    * 
-    * This adds an extra level of indirection to the call between a Poco notification handler and the call to the correct WorkspaceObserver handler.
-    * It is necessary to do this rather than just call the function directly so that the function call gets executed in the object's thread rather than
-    * in the thread that the notification was received in.
-    *
-    * Multiple inheritance is not used in WorkspaceObserver as their seems to be some problem using it and QObject
-    * 
-    */
-    class EXPORT_OPT_MANTIDQT_API ObserverCallback : public QObject
-    {
-      Q_OBJECT
-
-    public:
-      ObserverCallback(WorkspaceObserver *observer) : QObject(NULL), m_observer(observer)
-      {
-      }
-
-    signals:
-      /// Delete signal handler
-      void preDeleteRequested(const std::string &name, Mantid::API::Workspace_sptr workspace);
-      void postDeleteRequested(const std::string &name);
-      void addRequested(const std::string &name, Mantid::API::Workspace_sptr workspace);
-      void afterReplaced(const std::string &name, Mantid::API::Workspace_sptr workspace);
-      void renamed(const std::string &oldName, const std::string &newName);
-      void adsCleared();
-
-    private slots:
-      /// Pre Delete slot
-      void handlePreDelete(const std::string &name, Mantid::API::Workspace_sptr workspace);
-      /// Post Delete slot
-      void handlePostDelete(const std::string &name);
-      /// Add slot
-      void handleAdd(const std::string &name,  Mantid::API::Workspace_sptr workspace);
-      /// Replace slot
-      void handleAfterReplace(const std::string &name,  Mantid::API::Workspace_sptr workspace);
-      /// Rename slot
-      void handleRename(const std::string &oldName, const std::string &newName);
-      ///Clear slot
-      void handleClearADS();
-
-    private:
-      friend class WorkspaceObserver;
-      /// Default constructor
-      ObserverCallback();
-      /// Object to call back to
-      WorkspaceObserver *m_observer;
-    };
-
-    /** @class WorkspaceObserver 
-
-    Observes AnalysisDataService notifications: add,replace,delete.
-    Hides Poco::Notification API from the user. 
-
-    @author Roman Tolchenov, Tessella plc
-    @date 18/09/2009
-
-    Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class EXPORT_OPT_MANTIDQT_API WorkspaceObserver
-    {
-
-    public:
-      /// Default constructor
-      WorkspaceObserver();
-      /// Destructor
-      virtual ~WorkspaceObserver();
-      /// Observe workspace deletes
-      void observePreDelete(bool on = true);
-      /// Observe workspace deletes
-      void observePostDelete(bool on = true);
-      /// Observe replacements
-      void observeAfterReplace(bool on = true);
-      /// Observe renaming
-      void observeRename(bool on = true);
-      /// Observe additions
-      void observeAdd(bool on = true);
-      /// Observe clearances
-      void observeADSClear(bool on = true);
-
-    protected:
-      /** Handler of the delete notifications. Could be overriden in inherited classes.
-      The default handler is provided (doing nothing).
-      @param wsName :: The name of the deleted workspace.
-      @param ws :: Pointer to the workspace to be deleted.
-      */
-      virtual void preDeleteHandle(const std::string& wsName, const Mantid::API::Workspace_sptr ws)
-      {
-        Q_UNUSED(wsName);
-        Q_UNUSED(ws);
-      }
-
-      /** Handler of the delete notifications. Could be overriden in inherited classes.
-      The default handler is provided (doing nothing).
-      @param wsName :: The name of the deleted workspace.
-      */
-      virtual void postDeleteHandle(const std::string& wsName)
-      {
-        Q_UNUSED(wsName);
-      }
-      /** Handler of the add notifications. Could be overriden in inherited classes.
-      The default handler is provided (doing nothing).
-      @param wsName :: The name of the added workspace.
-      @param ws :: The shared pointer to the workspace to be added.
-      */
-      virtual void addHandle(const std::string& wsName,
-        const Mantid::API::Workspace_sptr ws)
-      {
-        Q_UNUSED(wsName);
-        Q_UNUSED(ws);
-      }
-      /** Handler of the AfterReplace notifications. Could be overriden in inherited classes.
-      The default handler is provided (doing nothing).
-      @param wsName :: The name of the deleted workspace.
-      @param ws :: The shared pointer to the workspace to be deleted.
-      */
-      virtual void afterReplaceHandle(const std::string& wsName,
-        const Mantid::API::Workspace_sptr ws)
-      {
-        Q_UNUSED(wsName);
-        Q_UNUSED(ws);
-      }
-
-      /** Handler of the Rename notifications. Could be overriden in inherited classes.
-      The default handler is provided (doing nothing).
-      @param oldName :: The old name of a workspace
-      @param newName :: The new name of a workspace
-      */
-      virtual void renameHandle(const std::string& oldName,
-        const std::string& newName)
-      {
-        Q_UNUSED(oldName);
-        Q_UNUSED(newName);
-      }
-
-      /** Handle an ADS clear notification
-      * 
-      */
-      virtual void clearADSHandle()
-      {
-      }
-
-    protected:
-      /** Poco notification handler for DataService::PostDeleteNotification.
-      @param pNf :: The pointer to the notification.
-      */
-      void _preDeleteHandle(Mantid::API::WorkspacePreDeleteNotification_ptr pNf)
-      {
-        m_proxy->preDeleteRequested(pNf->objectName(), pNf->object());
-      }
-      /// Poco::NObserver for DataServise::DeleteNotification.
-      Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspacePreDeleteNotification> m_preDeleteObserver;
-
-      /** Poco notification handler for DataService::PostDeleteNotification.
-      @param pNf :: The pointer to the notification.
-      */
-      void _postDeleteHandle(Mantid::API::WorkspacePostDeleteNotification_ptr pNf)
-      {
-        m_proxy->postDeleteRequested(pNf->objectName());
-      }
-      /// Poco::NObserver for DataServise::DeleteNotification.
-      Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspacePostDeleteNotification> m_postDeleteObserver;
-
-      /** Poco notification handler for DataService::DeleteNotification.
-      @param pNf :: The pointer to the notification.
-      */
-      void _addHandle(Mantid::API::WorkspaceAddNotification_ptr pNf)
-      {
-        m_proxy->addRequested(pNf->objectName(), pNf->object());
-      }
-      /// Poco::NObserver for DataServise::AddNotification.
-      Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspaceAddNotification> m_addObserver;
-
-      /** Poco notification handler for DataService::AfterReplaceNotification.
-      @param pNf :: The pointer to the notification.
-      */
-      void _afterReplaceHandle(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf)
-      {
-        m_proxy->afterReplaced(pNf->objectName(), pNf->object());
-      }
-      /// Poco::NObserver for DataServise::AfterReplaceNotification.
-      Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspaceAfterReplaceNotification> m_afterReplaceObserver;
-
-      /** Poco notification handler for DataService::RenameNotification.
-      @param pNf :: The pointer to the notification.
-      */
-      void _renameHandle(Mantid::API::WorkspaceRenameNotification_ptr pNf)
-      {
-        m_proxy->renamed(pNf->objectName(), pNf->newObjectName());
-      }
-      /// Poco::NObserver for DataServise::RenameNotification.
-      Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspaceRenameNotification> m_renameObserver;
-
-      ///Clear notification observer
-      Poco::NObserver<WorkspaceObserver, Mantid::API::ClearADSNotification> m_clearADSObserver;
-      /// ADS clear notification
-      void _clearADSHandle(Mantid::API::ClearADSNotification_ptr)
-      {
-        m_proxy->adsCleared();
-      }
-
-    private:
-      friend class ObserverCallback;
-      ObserverCallback *m_proxy;
-
-      bool m_predel_observed, m_postdel_observed, m_add_observed, m_repl_observed, m_rename_observed, m_clr_observed;
-    };
-
-
-  } // MantidQt
+namespace MantidQt {
+namespace API {
+//------------------------------------------------
+// Forward declaration
+//------------------------------------------------
+class WorkspaceObserver;
+
+/**
+* A simple callback class so that we avoid multiple inheritance issues with
+*QObject.
+*
+* This adds an extra level of indirection to the call between a Poco
+*notification handler and the call to the correct WorkspaceObserver handler.
+* It is necessary to do this rather than just call the function directly so that
+*the function call gets executed in the object's thread rather than
+* in the thread that the notification was received in.
+*
+* Multiple inheritance is not used in WorkspaceObserver as their seems to be
+*some problem using it and QObject
+*
+*/
+class EXPORT_OPT_MANTIDQT_API ObserverCallback : public QObject {
+  Q_OBJECT
+
+public:
+  ObserverCallback(WorkspaceObserver *observer)
+      : QObject(NULL), m_observer(observer) {}
+
+signals:
+  /// Delete signal handler
+  void preDeleteRequested(const std::string &name,
+                          Mantid::API::Workspace_sptr workspace);
+  void postDeleteRequested(const std::string &name);
+  void addRequested(const std::string &name,
+                    Mantid::API::Workspace_sptr workspace);
+  void afterReplaced(const std::string &name,
+                     Mantid::API::Workspace_sptr workspace);
+  void renamed(const std::string &oldName, const std::string &newName);
+  void adsCleared();
+
+private slots:
+  /// Pre Delete slot
+  void handlePreDelete(const std::string &name,
+                       Mantid::API::Workspace_sptr workspace);
+  /// Post Delete slot
+  void handlePostDelete(const std::string &name);
+  /// Add slot
+  void handleAdd(const std::string &name,
+                 Mantid::API::Workspace_sptr workspace);
+  /// Replace slot
+  void handleAfterReplace(const std::string &name,
+                          Mantid::API::Workspace_sptr workspace);
+  /// Rename slot
+  void handleRename(const std::string &oldName, const std::string &newName);
+  /// Clear slot
+  void handleClearADS();
+
+private:
+  friend class WorkspaceObserver;
+  /// Default constructor
+  ObserverCallback();
+  /// Object to call back to
+  WorkspaceObserver *m_observer;
+};
+
+/** @class WorkspaceObserver
+
+Observes AnalysisDataService notifications: add,replace,delete.
+Hides Poco::Notification API from the user.
+
+@author Roman Tolchenov, Tessella plc
+@date 18/09/2009
+
+Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_API WorkspaceObserver {
+
+public:
+  /// Default constructor
+  WorkspaceObserver();
+  /// Destructor
+  virtual ~WorkspaceObserver();
+  /// Observe workspace deletes
+  void observePreDelete(bool on = true);
+  /// Observe workspace deletes
+  void observePostDelete(bool on = true);
+  /// Observe replacements
+  void observeAfterReplace(bool on = true);
+  /// Observe renaming
+  void observeRename(bool on = true);
+  /// Observe additions
+  void observeAdd(bool on = true);
+  /// Observe clearances
+  void observeADSClear(bool on = true);
+
+protected:
+  /** Handler of the delete notifications. Could be overriden in inherited
+  classes.
+  The default handler is provided (doing nothing).
+  @param wsName :: The name of the deleted workspace.
+  @param ws :: Pointer to the workspace to be deleted.
+  */
+  virtual void preDeleteHandle(const std::string &wsName,
+                               const Mantid::API::Workspace_sptr ws) {
+    Q_UNUSED(wsName);
+    Q_UNUSED(ws);
+  }
+
+  /** Handler of the delete notifications. Could be overriden in inherited
+  classes.
+  The default handler is provided (doing nothing).
+  @param wsName :: The name of the deleted workspace.
+  */
+  virtual void postDeleteHandle(const std::string &wsName) { Q_UNUSED(wsName); }
+  /** Handler of the add notifications. Could be overriden in inherited classes.
+  The default handler is provided (doing nothing).
+  @param wsName :: The name of the added workspace.
+  @param ws :: The shared pointer to the workspace to be added.
+  */
+  virtual void addHandle(const std::string &wsName,
+                         const Mantid::API::Workspace_sptr ws) {
+    Q_UNUSED(wsName);
+    Q_UNUSED(ws);
+  }
+  /** Handler of the AfterReplace notifications. Could be overriden in inherited
+  classes.
+  The default handler is provided (doing nothing).
+  @param wsName :: The name of the deleted workspace.
+  @param ws :: The shared pointer to the workspace to be deleted.
+  */
+  virtual void afterReplaceHandle(const std::string &wsName,
+                                  const Mantid::API::Workspace_sptr ws) {
+    Q_UNUSED(wsName);
+    Q_UNUSED(ws);
+  }
+
+  /** Handler of the Rename notifications. Could be overriden in inherited
+  classes.
+  The default handler is provided (doing nothing).
+  @param oldName :: The old name of a workspace
+  @param newName :: The new name of a workspace
+  */
+  virtual void renameHandle(const std::string &oldName,
+                            const std::string &newName) {
+    Q_UNUSED(oldName);
+    Q_UNUSED(newName);
+  }
+
+  /** Handle an ADS clear notification
+  *
+  */
+  virtual void clearADSHandle() {}
+
+protected:
+  /** Poco notification handler for DataService::PostDeleteNotification.
+  @param pNf :: The pointer to the notification.
+  */
+  void _preDeleteHandle(Mantid::API::WorkspacePreDeleteNotification_ptr pNf) {
+    m_proxy->preDeleteRequested(pNf->objectName(), pNf->object());
+  }
+  /// Poco::NObserver for DataServise::DeleteNotification.
+  Poco::NObserver<WorkspaceObserver,
+                  Mantid::API::WorkspacePreDeleteNotification>
+      m_preDeleteObserver;
+
+  /** Poco notification handler for DataService::PostDeleteNotification.
+  @param pNf :: The pointer to the notification.
+  */
+  void _postDeleteHandle(Mantid::API::WorkspacePostDeleteNotification_ptr pNf) {
+    m_proxy->postDeleteRequested(pNf->objectName());
+  }
+  /// Poco::NObserver for DataServise::DeleteNotification.
+  Poco::NObserver<WorkspaceObserver,
+                  Mantid::API::WorkspacePostDeleteNotification>
+      m_postDeleteObserver;
+
+  /** Poco notification handler for DataService::DeleteNotification.
+  @param pNf :: The pointer to the notification.
+  */
+  void _addHandle(Mantid::API::WorkspaceAddNotification_ptr pNf) {
+    m_proxy->addRequested(pNf->objectName(), pNf->object());
+  }
+  /// Poco::NObserver for DataServise::AddNotification.
+  Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspaceAddNotification>
+      m_addObserver;
+
+  /** Poco notification handler for DataService::AfterReplaceNotification.
+  @param pNf :: The pointer to the notification.
+  */
+  void
+  _afterReplaceHandle(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf) {
+    m_proxy->afterReplaced(pNf->objectName(), pNf->object());
+  }
+  /// Poco::NObserver for DataServise::AfterReplaceNotification.
+  Poco::NObserver<WorkspaceObserver,
+                  Mantid::API::WorkspaceAfterReplaceNotification>
+      m_afterReplaceObserver;
+
+  /** Poco notification handler for DataService::RenameNotification.
+  @param pNf :: The pointer to the notification.
+  */
+  void _renameHandle(Mantid::API::WorkspaceRenameNotification_ptr pNf) {
+    m_proxy->renamed(pNf->objectName(), pNf->newObjectName());
+  }
+  /// Poco::NObserver for DataServise::RenameNotification.
+  Poco::NObserver<WorkspaceObserver, Mantid::API::WorkspaceRenameNotification>
+      m_renameObserver;
+
+  /// Clear notification observer
+  Poco::NObserver<WorkspaceObserver, Mantid::API::ClearADSNotification>
+      m_clearADSObserver;
+  /// ADS clear notification
+  void _clearADSHandle(Mantid::API::ClearADSNotification_ptr) {
+    m_proxy->adsCleared();
+  }
+
+private:
+  friend class ObserverCallback;
+  ObserverCallback *m_proxy;
+
+  bool m_predel_observed, m_postdel_observed, m_add_observed, m_repl_observed,
+      m_rename_observed, m_clr_observed;
+};
+
+} // MantidQt
 } // API
 
 #endif
diff --git a/MantidQt/API/inc/MantidQtAPI/qwt_compat.h b/MantidQt/API/inc/MantidQtAPI/qwt_compat.h
index f6d05c7c30c5ef607df7646cff77d5a39664e64f..a81ac0569599ca507661a674bfba5b00b526191a 100644
--- a/MantidQt/API/inc/MantidQtAPI/qwt_compat.h
+++ b/MantidQt/API/inc/MantidQtAPI/qwt_compat.h
@@ -5,17 +5,17 @@
 
 #if QWT_VERSION >= 0x050200
 // FAA 11/04/2010: QWT 5.2.0 changed some member functions
-// QwtScaleEngine 
+// QwtScaleEngine
 //   loMargin/hiMargin renamed to lowerMargin/upperMargin
-// QwtScaleDiv 
+// QwtScaleDiv
 //   lBound/hBound renamed to lowerBound/upperBound
-#   define lBound() lowerBound()
-#   define hBound() upperBound()
-#   define loMargin() lowerMargin()
-#   define hiMargin() upperMargin()
+#define lBound() lowerBound()
+#define hBound() upperBound()
+#define loMargin() lowerMargin()
+#define hiMargin() upperMargin()
 #else
-#   define lowerMargin()  loMargin()
-#   define upperMargin()  hiMargin()
+#define lowerMargin() loMargin()
+#define upperMargin() hiMargin()
 #endif /* QWT_VERSION >= 0x050200 */
 
 #endif /* MANTID_QWT_COMPAT */
diff --git a/MantidQt/API/src/AlgorithmInputHistory.cpp b/MantidQt/API/src/AlgorithmInputHistory.cpp
index ae0cc53a0c1fcea39964dcc2cd16b962f261f7f9..8e1802d16917194116432b3b84aae42b03659343 100644
--- a/MantidQt/API/src/AlgorithmInputHistory.cpp
+++ b/MantidQt/API/src/AlgorithmInputHistory.cpp
@@ -16,22 +16,21 @@ using namespace MantidQt::API;
 /**
  * Constructor
  */
-AbstractAlgorithmInputHistory::AbstractAlgorithmInputHistory(QString settingsGroup)
-: m_lastInput(), m_previousDirectory(""),
-  m_algorithmsGroup(settingsGroup), m_dirKey("LastDirectory")
-{
-  //Fill the stored map from the QSettings information
+AbstractAlgorithmInputHistory::AbstractAlgorithmInputHistory(
+    QString settingsGroup)
+    : m_lastInput(), m_previousDirectory(""), m_algorithmsGroup(settingsGroup),
+      m_dirKey("LastDirectory") {
+  // Fill the stored map from the QSettings information
   load();
 }
 
-
 /**
  * Destructor
  */
-AbstractAlgorithmInputHistory::~AbstractAlgorithmInputHistory()
-{
-  //Can't write the history out here since, in Linux, the singletons are destroyed after
-  //the QApplication object and then we get a crash
+AbstractAlgorithmInputHistory::~AbstractAlgorithmInputHistory() {
+  // Can't write the history out here since, in Linux, the singletons are
+  // destroyed after
+  // the QApplication object and then we get a crash
 }
 
 /**
@@ -41,111 +40,114 @@ AbstractAlgorithmInputHistory::~AbstractAlgorithmInputHistory()
  * @param algName :: The name of the algorithm
  * @param property :: A pair containing <name,value> of a property
  */
-void AbstractAlgorithmInputHistory::storeNewValue(const QString & algName,
-					      const QPair<QString, QString> & property)
-{
+void AbstractAlgorithmInputHistory::storeNewValue(
+    const QString &algName, const QPair<QString, QString> &property) {
   m_lastInput[algName][property.first] = property.second;
 }
 
 /**
   * Clear all stored values associated with a particular algorithm
   */
-void AbstractAlgorithmInputHistory::clearAlgorithmInput(const QString & algName)
-{
-  if( m_lastInput.contains(algName) ) m_lastInput[algName].clear();
+void AbstractAlgorithmInputHistory::clearAlgorithmInput(
+    const QString &algName) {
+  if (m_lastInput.contains(algName))
+    m_lastInput[algName].clear();
 }
 
 /**
- * Retrieve an old parameter value 
+ * Retrieve an old parameter value
  * @param algName :: The name of the algorithm
  * @param propName :: The name of the property
  */
-QString AbstractAlgorithmInputHistory::previousInput(const QString & algName, const QString & propName) const
-{
-  if( !m_lastInput.contains(algName) ) return "";
-  
-  if( m_lastInput.value(algName).contains(propName) ) return m_lastInput.value(algName).value(propName);
-  else return "";
+QString
+AbstractAlgorithmInputHistory::previousInput(const QString &algName,
+                                             const QString &propName) const {
+  if (!m_lastInput.contains(algName))
+    return "";
+
+  if (m_lastInput.value(algName).contains(propName))
+    return m_lastInput.value(algName).value(propName);
+  else
+    return "";
 }
 
 /**
-  * Set the directory that was accessed when the previous open file dialog was used
-  * @param lastdir :: A QString giving the path of the directory that was last accessed with a file dialog
+  * Set the directory that was accessed when the previous open file dialog was
+ * used
+  * @param lastdir :: A QString giving the path of the directory that was last
+ * accessed with a file dialog
   */
-void AbstractAlgorithmInputHistory::setPreviousDirectory(const QString & lastdir)
-{
+void AbstractAlgorithmInputHistory::setPreviousDirectory(
+    const QString &lastdir) {
   m_previousDirectory = lastdir;
 }
-  
-/// Get the directory that was accessed when the previous open file dialog was used
-const QString & AbstractAlgorithmInputHistory::getPreviousDirectory() const
-{
+
+/// Get the directory that was accessed when the previous open file dialog was
+/// used
+const QString &AbstractAlgorithmInputHistory::getPreviousDirectory() const {
   return m_previousDirectory;
 }
 
 /**
   * Save the stored information to persistent storage
   */
-void AbstractAlgorithmInputHistory::save() const
-{    
+void AbstractAlgorithmInputHistory::save() const {
   QSettings settings;
   settings.beginGroup(m_algorithmsGroup);
-  QHashIterator<QString,QHash<QString, QString> > inputHistory(m_lastInput);
-  while( inputHistory.hasNext() )
-  {
+  QHashIterator<QString, QHash<QString, QString>> inputHistory(m_lastInput);
+  while (inputHistory.hasNext()) {
     inputHistory.next();
     settings.beginGroup(inputHistory.key());
-    //Remove all keys for this group that exist at the moment
+    // Remove all keys for this group that exist at the moment
     settings.remove("");
     QHash<QString, QString>::const_iterator iend = inputHistory.value().end();
-    for( QHash<QString, QString>::const_iterator itr = inputHistory.value().begin(); itr != iend; ++itr )
-    {
+    for (QHash<QString, QString>::const_iterator itr =
+             inputHistory.value().begin();
+         itr != iend; ++itr) {
       settings.setValue(itr.key(), itr.value());
     }
     settings.endGroup();
   }
-  
-  //Store the previous directory
+
+  // Store the previous directory
   settings.setValue(m_dirKey, m_previousDirectory);
-  
+
   settings.endGroup();
 }
 
-
 //----------------------------------
 // Private member functions
 //----------------------------------
 
 /**
-  * Load any values that are available from persistent storage. Note: this clears all currently values stored
+  * Load any values that are available from persistent storage. Note: this
+ * clears all currently values stored
   */
-void AbstractAlgorithmInputHistory::load()
-{
+void AbstractAlgorithmInputHistory::load() {
   m_lastInput.clear();
   QSettings settings;
   settings.beginGroup(m_algorithmsGroup);
-//  QStringList algorithms = settings.childGroups();
-  QListIterator<QString> algNames( settings.childGroups() );
-  
-  //Each property is a key of the algorithm group
-  while( algNames.hasNext() )
-  {
+  //  QStringList algorithms = settings.childGroups();
+  QListIterator<QString> algNames(settings.childGroups());
+
+  // Each property is a key of the algorithm group
+  while (algNames.hasNext()) {
     QHash<QString, QString> algorithmProperties;
     QString group = algNames.next();
     settings.beginGroup(group);
     QListIterator<QString> properties(settings.childKeys());
-    while( properties.hasNext() )
-    {
+    while (properties.hasNext()) {
       QString propName = properties.next();
       QString value = settings.value(propName).toString();
-      if( !value.isEmpty() ) algorithmProperties.insert(propName, value);
+      if (!value.isEmpty())
+        algorithmProperties.insert(propName, value);
     }
     m_lastInput.insert(group, algorithmProperties);
     settings.endGroup();
   }
-  
-  //The previous dir
+
+  // The previous dir
   m_previousDirectory = settings.value(m_dirKey).toString();
-  
+
   settings.endGroup();
 }
diff --git a/MantidQt/API/src/AlgorithmPropertiesWidget.cpp b/MantidQt/API/src/AlgorithmPropertiesWidget.cpp
index 7754caa5760a82b36338f9725ada5821ca78eb5f..9ad793f078832ccd64e222a860d922d051f81590 100644
--- a/MantidQt/API/src/AlgorithmPropertiesWidget.cpp
+++ b/MantidQt/API/src/AlgorithmPropertiesWidget.cpp
@@ -20,468 +20,435 @@ using Mantid::API::FrameworkManager;
 using Mantid::API::Algorithm_sptr;
 using Mantid::API::AlgorithmProxy;
 
-namespace MantidQt
-{
-namespace API
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  AlgorithmPropertiesWidget::AlgorithmPropertiesWidget(QWidget * parent)
-  : QWidget(parent),
-    m_algoName(""),
-    m_algo(),
-    m_inputHistory(NULL)
-  {
-    // Create the grid layout that will have all the widgets
-    m_inputGrid = new QGridLayout;
-
-    // Create the viewport that holds only the grid layout
-    m_viewport = new QWidget(this);
-
-    // Put everything in a vertical box and put it inside the m_scroll area
-    QVBoxLayout *mainLay = new QVBoxLayout();
-    m_viewport->setLayout(mainLay);
-    //The property boxes
-    mainLay->addLayout(m_inputGrid);
-    // Add a stretchy item to allow the properties grid to be top-aligned
-    mainLay->addStretch(1);
-
-
-    // Create a m_scroll area for the (rare) occasion when an algorithm has
-    // so many properties it won't fit on the screen
-    m_scroll = new QScrollArea(this);
-    m_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-    m_scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
-    m_scroll->setWidget(m_viewport);
-    m_scroll->setWidgetResizable(true);
-    m_scroll->setAlignment(Qt::Alignment(Qt::AlignLeft & Qt::AlignTop));
-
-
-    // Add a layout for the whole widget, containing just the m_scroll area
-    QVBoxLayout *dialog_layout = new QVBoxLayout();
-    dialog_layout->addWidget(m_scroll);
-    setLayout(dialog_layout);
-
-    this->initLayout();
+namespace MantidQt {
+namespace API {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+AlgorithmPropertiesWidget::AlgorithmPropertiesWidget(QWidget *parent)
+    : QWidget(parent), m_algoName(""), m_algo(), m_inputHistory(NULL) {
+  // Create the grid layout that will have all the widgets
+  m_inputGrid = new QGridLayout;
+
+  // Create the viewport that holds only the grid layout
+  m_viewport = new QWidget(this);
+
+  // Put everything in a vertical box and put it inside the m_scroll area
+  QVBoxLayout *mainLay = new QVBoxLayout();
+  m_viewport->setLayout(mainLay);
+  // The property boxes
+  mainLay->addLayout(m_inputGrid);
+  // Add a stretchy item to allow the properties grid to be top-aligned
+  mainLay->addStretch(1);
+
+  // Create a m_scroll area for the (rare) occasion when an algorithm has
+  // so many properties it won't fit on the screen
+  m_scroll = new QScrollArea(this);
+  m_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+  m_scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+  m_scroll->setWidget(m_viewport);
+  m_scroll->setWidgetResizable(true);
+  m_scroll->setAlignment(Qt::Alignment(Qt::AlignLeft & Qt::AlignTop));
+
+  // Add a layout for the whole widget, containing just the m_scroll area
+  QVBoxLayout *dialog_layout = new QVBoxLayout();
+  dialog_layout->addWidget(m_scroll);
+  setLayout(dialog_layout);
+
+  this->initLayout();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+AlgorithmPropertiesWidget::~AlgorithmPropertiesWidget() {}
+
+//----------------------------------------------------------------------------------------------
+/** Sets the AlgorithmInputHistoryImpl object holding all histories.
+ * This object does NOT take ownership
+ *
+ * @param inputHistory :: AlgorithmInputHistoryImpl ptr
+ */
+void AlgorithmPropertiesWidget::setInputHistory(
+    MantidQt::API::AbstractAlgorithmInputHistory *inputHistory) {
+  m_inputHistory = inputHistory;
+}
+
+//----------------------------------------------------------------------------------------------
+///@return the algorithm being viewed
+Mantid::API::IAlgorithm_sptr AlgorithmPropertiesWidget::getAlgorithm() {
+  return m_algo;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Directly set the algorithm to view. Sets the name to match
+ *
+ * @param algo :: IAlgorithm bare ptr */
+void AlgorithmPropertiesWidget::setAlgorithm(
+    Mantid::API::IAlgorithm_sptr algo) {
+  if (!algo)
+    return;
+  saveInput();
+  m_algo = algo;
+  m_algoName = QString::fromStdString(m_algo->name());
+  this->initLayout();
+}
+
+//----------------------------------------------------------------------------------------------
+///@return the name of the algorithm being displayed
+QString AlgorithmPropertiesWidget::getAlgorithmName() const {
+  return m_algoName;
+}
+
+/** Set the algorithm to view using its name
+ *
+ * @param name :: The algorithm name*/
+void AlgorithmPropertiesWidget::setAlgorithmName(QString name) {
+  FrameworkManager::Instance();
+  m_algoName = name;
+  try {
+    Algorithm_sptr alg =
+        AlgorithmManager::Instance().createUnmanaged(m_algoName.toStdString());
+    auto algProxy = boost::make_shared<AlgorithmProxy>(alg);
+    algProxy->initialize();
+
+    // Set the algorithm ptr. This will redo the layout
+    this->setAlgorithm(algProxy);
+  } catch (std::runtime_error &) {
   }
-
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  AlgorithmPropertiesWidget::~AlgorithmPropertiesWidget()
-  {
-  }
-  
-  //----------------------------------------------------------------------------------------------
-  /** Sets the AlgorithmInputHistoryImpl object holding all histories.
-   * This object does NOT take ownership
-   *
-   * @param inputHistory :: AlgorithmInputHistoryImpl ptr
-   */
-  void AlgorithmPropertiesWidget::setInputHistory(MantidQt::API::AbstractAlgorithmInputHistory * inputHistory)
-  {
-    m_inputHistory = inputHistory;
+}
+
+//---------------------------------------------------------------------------------------------------------------
+/** Sets the properties to force as enabled/disabled */
+void AlgorithmPropertiesWidget::addEnabledAndDisableLists(
+    const QStringList &enabled, const QStringList &disabled) {
+  this->m_enabled = enabled;
+  this->m_disabled = disabled;
+}
+
+//---------------------------------------------------------------------------------------------------------------
+/** @return true if the workspace has an input workspace */
+bool haveInputWS(const std::vector<Property *> &prop_list) {
+  // For the few algorithms (mainly loading) that do not have input workspaces,
+  // we do not
+  // want to render the 'replace input workspace button'. Do a quick scan to
+  // check.
+  // Also the ones that don't have a set of allowed values as input workspace
+  std::vector<Property *>::const_iterator pEnd = prop_list.end();
+  for (std::vector<Property *>::const_iterator pIter = prop_list.begin();
+       pIter != pEnd; ++pIter) {
+    Property *prop = *pIter;
+    if (prop->direction() == Direction::Input &&
+        dynamic_cast<IWorkspaceProperty *>(prop)) {
+      return true;
+    }
   }
-
-  //----------------------------------------------------------------------------------------------
-  ///@return the algorithm being viewed
-  Mantid::API::IAlgorithm_sptr AlgorithmPropertiesWidget::getAlgorithm()
-  {
-    return m_algo;
+  return false;
+}
+
+//---------------------------------------------------------------------------------------------------------------
+/**
+* Create the layout for this dialog.
+*/
+void AlgorithmPropertiesWidget::initLayout() {
+  if (!getAlgorithm())
+    return;
+
+  // Delete all widgets in the layout
+  QLayoutItem *child;
+  while ((child = m_inputGrid->takeAt(0)) != 0) {
+    if (child->widget())
+      child->widget()->deleteLater();
+
+    delete child;
   }
 
-  //----------------------------------------------------------------------------------------------
-  /** Directly set the algorithm to view. Sets the name to match
-   *
-   * @param algo :: IAlgorithm bare ptr */
-  void AlgorithmPropertiesWidget::setAlgorithm(Mantid::API::IAlgorithm_sptr algo)
-  {
-    if (!algo) return;
-    saveInput();
-    m_algo = algo;
-    m_algoName = QString::fromStdString(m_algo->name());
-    this->initLayout();
-  }
+  // This also deletes the PropertyWidget, which does not actually
+  // contain the sub-widgets because they are shared in the grid layout
+  for (auto it = m_propWidgets.begin(); it != m_propWidgets.end(); it++)
+    (*it)->deleteLater();
+  QCoreApplication::processEvents();
+  m_propWidgets.clear();
 
-  //----------------------------------------------------------------------------------------------
-  ///@return the name of the algorithm being displayed
-  QString AlgorithmPropertiesWidget::getAlgorithmName() const
-  {
-    return m_algoName;
-  }
+  // Create a grid of properties if there are any available
+  const std::vector<Property *> &prop_list = getAlgorithm()->getProperties();
+  bool hasInputWS = haveInputWS(prop_list);
 
-  /** Set the algorithm to view using its name
-   *
-   * @param name :: The algorithm name*/
-  void AlgorithmPropertiesWidget::setAlgorithmName(QString name)
-  {
-    FrameworkManager::Instance();
-    m_algoName = name;
-    try
-    {
-      Algorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged(m_algoName.toStdString());
-      auto algProxy = boost::make_shared<AlgorithmProxy>(alg);
-      algProxy->initialize();
-
-      // Set the algorithm ptr. This will redo the layout
-      this->setAlgorithm(algProxy);
-    }
-    catch (std::runtime_error & )
-    {
-    }
-  }
+  if (!prop_list.empty()) {
+    // Put the property boxes in a grid
+    m_currentGrid = m_inputGrid;
 
+    std::string group = "";
 
-  //---------------------------------------------------------------------------------------------------------------
-  /** Sets the properties to force as enabled/disabled */
-  void AlgorithmPropertiesWidget::addEnabledAndDisableLists(const QStringList & enabled, const QStringList & disabled)
-  {
-    this->m_enabled = enabled;
-    this->m_disabled = disabled;
-  }
+    // Each property is on its own row
+    int row = 0;
 
-  //---------------------------------------------------------------------------------------------------------------
-  /** @return true if the workspace has an input workspace */
-  bool haveInputWS(const std::vector<Property*> & prop_list)
-  {
-    // For the few algorithms (mainly loading) that do not have input workspaces, we do not
-    // want to render the 'replace input workspace button'. Do a quick scan to check.
-    // Also the ones that don't have a set of allowed values as input workspace
-    std::vector<Property*>::const_iterator pEnd = prop_list.end();
-    for(std::vector<Property*>::const_iterator pIter = prop_list.begin();
-      pIter != pEnd; ++pIter)
-    {
+    for (std::vector<Property *>::const_iterator pIter = prop_list.begin();
+         pIter != prop_list.end(); ++pIter) {
       Property *prop = *pIter;
-      if( prop->direction() == Direction::Input && dynamic_cast<IWorkspaceProperty*>(prop) )
-      {
-        return true;
-      }
-    }
-    return false;
-  }
-
-
-
-  //---------------------------------------------------------------------------------------------------------------
-  /**
-  * Create the layout for this dialog.
-  */
-  void AlgorithmPropertiesWidget::initLayout()
-  {
-    if (!getAlgorithm())
-      return;
-
-    // Delete all widgets in the layout
-    QLayoutItem *child;
-    while ((child = m_inputGrid->takeAt(0)) != 0) {
-      if(child->widget())
-        child->widget()->deleteLater();
-
-      delete child;
-    }
-
-    // This also deletes the PropertyWidget, which does not actually
-    // contain the sub-widgets because they are shared in the grid layout
-    for (auto it = m_propWidgets.begin(); it != m_propWidgets.end(); it++)
-        (*it)->deleteLater();
-    QCoreApplication::processEvents();
-    m_propWidgets.clear();
-
-    // Create a grid of properties if there are any available
-    const std::vector<Property*> & prop_list = getAlgorithm()->getProperties();
-    bool hasInputWS = haveInputWS(prop_list);
-
-    if ( !prop_list.empty() )
-    {
-      //Put the property boxes in a grid
-      m_currentGrid = m_inputGrid;
-
-      std::string group = "";
-
-      //Each property is on its own row
-      int row = 0;
-
-      for(std::vector<Property*>::const_iterator pIter = prop_list.begin();
-        pIter != prop_list.end(); ++pIter)
-      {
-        Property* prop = *pIter;
-        QString propName = QString::fromStdString(prop->name());
-
-        // Are we entering a new group?
-        if (prop->getGroup() != group)
-        {
-          group = prop->getGroup();
-
-          if (group == "")
-          {
-            // Return to the original grid
-            m_currentGrid = m_inputGrid;
-          }
-          else
-          {
-            // Make a groupbox with a border and a light background
-            QGroupBox* grpBox = new QGroupBox(QString::fromStdString(group) );
-            grpBox->setAutoFillBackground(true);
-            grpBox->setStyleSheet(
-                "QGroupBox { border: 1px solid gray;  border-radius: 4px; font-weight: bold; margin-top: 4px; margin-bottom: 4px; padding-top: 16px; }"
-                "QGroupBox::title { background-color: transparent;  subcontrol-position: top center;  padding-top:4px; padding-bottom:4px; } ");
-            QPalette pal = grpBox->palette();
-            pal.setColor(grpBox->backgroundRole(), pal.alternateBase().color());
-            grpBox->setPalette(pal);
-
-            // Put the frame in the main grid
-            m_inputGrid->addWidget(grpBox, row, 0, 1, 4);
-
-            m_groupWidgets[QString::fromStdString(group)] = grpBox;
-
-            // Make a layout in the grp box
-            m_currentGrid = new QGridLayout;
-            grpBox->setLayout(m_currentGrid);
-
-            row++;
-          }
+      QString propName = QString::fromStdString(prop->name());
+
+      // Are we entering a new group?
+      if (prop->getGroup() != group) {
+        group = prop->getGroup();
+
+        if (group == "") {
+          // Return to the original grid
+          m_currentGrid = m_inputGrid;
+        } else {
+          // Make a groupbox with a border and a light background
+          QGroupBox *grpBox = new QGroupBox(QString::fromStdString(group));
+          grpBox->setAutoFillBackground(true);
+          grpBox->setStyleSheet(
+              "QGroupBox { border: 1px solid gray;  border-radius: 4px; "
+              "font-weight: bold; margin-top: 4px; margin-bottom: 4px; "
+              "padding-top: 16px; }"
+              "QGroupBox::title { background-color: transparent;  "
+              "subcontrol-position: top center;  padding-top:4px; "
+              "padding-bottom:4px; } ");
+          QPalette pal = grpBox->palette();
+          pal.setColor(grpBox->backgroundRole(), pal.alternateBase().color());
+          grpBox->setPalette(pal);
+
+          // Put the frame in the main grid
+          m_inputGrid->addWidget(grpBox, row, 0, 1, 4);
+
+          m_groupWidgets[QString::fromStdString(group)] = grpBox;
+
+          // Make a layout in the grp box
+          m_currentGrid = new QGridLayout;
+          grpBox->setLayout(m_currentGrid);
+
+          row++;
         }
+      }
 
-        // Only accept input for output properties or workspace properties
-        bool isWorkspaceProp(dynamic_cast<IWorkspaceProperty*>(prop));
-        if( prop->direction() == Direction::Output && !isWorkspaceProp )
-          continue;
-
-        // Create the appropriate widget at this row in the grid.
-        PropertyWidget * widget = PropertyWidgetFactory::createWidget(prop, this, m_currentGrid, row);
-
-        // Set the previous input value, if any
-        if (m_inputHistory)
-        {
-          QString oldValue = m_inputHistory->previousInput(m_algoName, propName);
-          // Empty string if not found. This means use the default.
-          if (!oldValue.isEmpty())
-          {
-            auto error = prop->setValue(oldValue.toStdString());
-            widget->setError(QString::fromStdString(error));
-            widget->setPreviousValue(oldValue);
-          }
+      // Only accept input for output properties or workspace properties
+      bool isWorkspaceProp(dynamic_cast<IWorkspaceProperty *>(prop));
+      if (prop->direction() == Direction::Output && !isWorkspaceProp)
+        continue;
+
+      // Create the appropriate widget at this row in the grid.
+      PropertyWidget *widget =
+          PropertyWidgetFactory::createWidget(prop, this, m_currentGrid, row);
+
+      // Set the previous input value, if any
+      if (m_inputHistory) {
+        QString oldValue = m_inputHistory->previousInput(m_algoName, propName);
+        // Empty string if not found. This means use the default.
+        if (!oldValue.isEmpty()) {
+          auto error = prop->setValue(oldValue.toStdString());
+          widget->setError(QString::fromStdString(error));
+          widget->setPreviousValue(oldValue);
         }
+      }
 
-        m_propWidgets[propName] = widget;
-
-        // Whenever the value changes in the widget, this fires propertyChanged()
-        connect(widget, SIGNAL( valueChanged(const QString &)), this, SLOT(propertyChanged(const QString &)));
-
-        // For clicking the "Replace Workspace" button (if any)
-        connect(widget, SIGNAL( replaceWorkspaceName(const QString &)), this, SLOT(replaceWSClicked(const QString &)));
-
-        // Only show the "Replace Workspace" button if the algorithm has an input workspace.
-        if (hasInputWS)
-          widget->addReplaceWSButton();
-
-        ++row;
-      } //(end for each property)
-
-    } // (there are properties)
-  }
-
-
-
-  //--------------------------------------------------------------------------------------
-  /** SLOT to be called whenever a property's value has just been changed
-   * and the widget has lost focus/value has been changed.
-   * @param pName :: name of the property that was changed
-   */
-  void AlgorithmPropertiesWidget::propertyChanged(const QString & pName)
-  {
-    UNUSED_ARG(pName);
-    //PropertyWidget * widget = m_propWidgets[pName];
-    this->hideOrDisableProperties();
-  }
-
-  bool isCalledInputWorkspace(PropertyWidget * const candidate)
-  {
-    Mantid::Kernel::Property const * const  property  = candidate->getProperty();
-    const std::string& propertyName = property->name();
-    return propertyName == "InputWorkspace";
-  }
-
-  //-------------------------------------------------------------------------------------------------
-  /** A slot to handle the replace workspace button click
-   *
-   * @param propName :: the property for which we clicked "Replace Workspace"
-   */
-  void AlgorithmPropertiesWidget::replaceWSClicked(const QString & propName)
-  {
-    if (m_propWidgets.contains(propName))
-    {
-      typedef std::vector<PropertyWidget*> CollectionOfPropertyWidget;
-      CollectionOfPropertyWidget candidateReplacementSources;
-      PropertyWidget * propWidget = m_propWidgets[propName];
-      if (propWidget)
-      {
-        // Find the name to put in the spot
-        QString wsName("");
-        for (auto it = m_propWidgets.begin(); it != m_propWidgets.end(); it++)
-        {
-          // Only look at workspace properties
-          PropertyWidget* otherWidget = it.value();
-          Property * prop = it.value()->getProperty();
-          IWorkspaceProperty * wsProp = dynamic_cast<IWorkspaceProperty*>(prop);
-          if (otherWidget && wsProp)
-          {
-            if (prop->direction() == Direction::Input)
-            {
-              // Input workspace property. Get the text typed in.
-              wsName = otherWidget->getValue();
-              if (!wsName.isEmpty())
-              {
-                // Add the candidate to the list of candidates.
-                candidateReplacementSources.push_back(otherWidget);
-              }
+      m_propWidgets[propName] = widget;
+
+      // Whenever the value changes in the widget, this fires propertyChanged()
+      connect(widget, SIGNAL(valueChanged(const QString &)), this,
+              SLOT(propertyChanged(const QString &)));
+
+      // For clicking the "Replace Workspace" button (if any)
+      connect(widget, SIGNAL(replaceWorkspaceName(const QString &)), this,
+              SLOT(replaceWSClicked(const QString &)));
+
+      // Only show the "Replace Workspace" button if the algorithm has an input
+      // workspace.
+      if (hasInputWS)
+        widget->addReplaceWSButton();
+
+      ++row;
+    } //(end for each property)
+
+  } // (there are properties)
+}
+
+//--------------------------------------------------------------------------------------
+/** SLOT to be called whenever a property's value has just been changed
+ * and the widget has lost focus/value has been changed.
+ * @param pName :: name of the property that was changed
+ */
+void AlgorithmPropertiesWidget::propertyChanged(const QString &pName) {
+  UNUSED_ARG(pName);
+  // PropertyWidget * widget = m_propWidgets[pName];
+  this->hideOrDisableProperties();
+}
+
+bool isCalledInputWorkspace(PropertyWidget *const candidate) {
+  Mantid::Kernel::Property const *const property = candidate->getProperty();
+  const std::string &propertyName = property->name();
+  return propertyName == "InputWorkspace";
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A slot to handle the replace workspace button click
+ *
+ * @param propName :: the property for which we clicked "Replace Workspace"
+ */
+void AlgorithmPropertiesWidget::replaceWSClicked(const QString &propName) {
+  if (m_propWidgets.contains(propName)) {
+    typedef std::vector<PropertyWidget *> CollectionOfPropertyWidget;
+    CollectionOfPropertyWidget candidateReplacementSources;
+    PropertyWidget *propWidget = m_propWidgets[propName];
+    if (propWidget) {
+      // Find the name to put in the spot
+      QString wsName("");
+      for (auto it = m_propWidgets.begin(); it != m_propWidgets.end(); it++) {
+        // Only look at workspace properties
+        PropertyWidget *otherWidget = it.value();
+        Property *prop = it.value()->getProperty();
+        IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop);
+        if (otherWidget && wsProp) {
+          if (prop->direction() == Direction::Input) {
+            // Input workspace property. Get the text typed in.
+            wsName = otherWidget->getValue();
+            if (!wsName.isEmpty()) {
+              // Add the candidate to the list of candidates.
+              candidateReplacementSources.push_back(otherWidget);
             }
           }
         }
+      }
 
-        // Choose from candidates, only do this if there are candidates to select from.
-        if(candidateReplacementSources.size() > 0)
-        {
-          CollectionOfPropertyWidget::iterator selectedIt = std::find_if(candidateReplacementSources.begin(), candidateReplacementSources.end(), isCalledInputWorkspace);
-          if(selectedIt != candidateReplacementSources.end())
-          {
-            // Use the InputWorkspace property called "InputWorkspace" as the source for the OutputWorkspace.
-            propWidget->setValue((*selectedIt)->getValue());
-          }
-          else
-          {
-            // Take the first candidate if there are none called "InputWorkspace" as the source for the OutputWorkspace.
-            propWidget->setValue(candidateReplacementSources.front()->getValue());
-          }
-          propWidget->userEditedProperty();
+      // Choose from candidates, only do this if there are candidates to select
+      // from.
+      if (candidateReplacementSources.size() > 0) {
+        CollectionOfPropertyWidget::iterator selectedIt = std::find_if(
+            candidateReplacementSources.begin(),
+            candidateReplacementSources.end(), isCalledInputWorkspace);
+        if (selectedIt != candidateReplacementSources.end()) {
+          // Use the InputWorkspace property called "InputWorkspace" as the
+          // source for the OutputWorkspace.
+          propWidget->setValue((*selectedIt)->getValue());
+        } else {
+          // Take the first candidate if there are none called "InputWorkspace"
+          // as the source for the OutputWorkspace.
+          propWidget->setValue(candidateReplacementSources.front()->getValue());
         }
+        propWidget->userEditedProperty();
       }
     }
-
   }
-
-
-  //-------------------------------------------------------------------------------------------------
-  /** Check if the control should be enabled for this property
-   * @param property :: the property that allows to check for the settings.
-   * @param propName :: The name of the property
-   */
-  bool AlgorithmPropertiesWidget::isWidgetEnabled(Property * property, const QString & propName) const
-  {
-    // To avoid errors
-    if( propName.isEmpty() ) return true;
-    if (!property) return true;
-
-    // Keep things enabled if requested
-    if( m_enabled.contains(propName) ) return true;
-
-    /** The control is disabled if
-    *   (1) It is contained in the disabled list or
-    *   (2) A user passed a value into the dialog
-    */
-    if(m_disabled.contains(propName))
-    {
-      return false;
-    }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Check if the control should be enabled for this property
+ * @param property :: the property that allows to check for the settings.
+ * @param propName :: The name of the property
+ */
+bool AlgorithmPropertiesWidget::isWidgetEnabled(Property *property,
+                                                const QString &propName) const {
+  // To avoid errors
+  if (propName.isEmpty())
+    return true;
+  if (!property)
+    return true;
+
+  // Keep things enabled if requested
+  if (m_enabled.contains(propName))
+    return true;
+
+  /** The control is disabled if
+  *   (1) It is contained in the disabled list or
+  *   (2) A user passed a value into the dialog
+  */
+  if (m_disabled.contains(propName)) {
+    return false;
+  } else {
+    // Regular C++ algo. Let the property tell us,
+    // possibly using validators, if it is to be shown enabled
+    if (property->getSettings())
+      return property->getSettings()->isEnabled(m_algo.get());
     else
-    {
-      // Regular C++ algo. Let the property tell us,
-      // possibly using validators, if it is to be shown enabled
-      if (property->getSettings())
-        return property->getSettings()->isEnabled(m_algo.get());
-      else
-        return true;
-    }
-
+      return true;
   }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Go through all the properties, and check their validators to determine
+ * whether they should be made disabled/invisible.
+ * It also shows/hids the validators.
+ * All properties' values should be set already, otherwise the validators
+ * will be running on old data.
+ */
+void AlgorithmPropertiesWidget::hideOrDisableProperties() {
+  for (auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end(); ++pitr) {
+    PropertyWidget *widget = pitr.value();
+    Mantid::Kernel::Property *prop = widget->getProperty();
+    QString propName = pitr.key();
+    IPropertySettings *settings = prop->getSettings();
+
+    // Set the enabled and visible flags based on what the validators say.
+    // Default is always true.
+    bool visible = true;
+    // Dynamically check if the widget should be enabled.
+    bool enabled = this->isWidgetEnabled(prop, propName);
+
+    // Do we have a custom IPropertySettings?
+    if (settings) {
+      // Set the visible flag
+      visible = settings->isVisible(m_algo.get());
+
+      // Dynamic PropertySettings objects allow a property to change validators.
+      // This removes the old widget and creates a new one instead.
+      if (settings->isConditionChanged(m_algo.get())) {
+        settings->applyChanges(m_algo.get(), prop);
+
+        // Delete the old widget
+        int row = widget->getGridRow();
+        QGridLayout *layout = widget->getGridLayout();
+        widget->setVisible(false);
+        widget->deleteLater();
 
-  //-------------------------------------------------------------------------------------------------
-  /** Go through all the properties, and check their validators to determine
-   * whether they should be made disabled/invisible.
-   * It also shows/hids the validators.
-   * All properties' values should be set already, otherwise the validators
-   * will be running on old data.
-   */
-  void AlgorithmPropertiesWidget::hideOrDisableProperties()
-  {
-    for( auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end(); ++pitr )
-    {
-      PropertyWidget * widget = pitr.value();
-      Mantid::Kernel::Property *prop = widget->getProperty();
-      QString propName = pitr.key();
-      IPropertySettings * settings = prop->getSettings();
-
-      // Set the enabled and visible flags based on what the validators say. Default is always true.
-      bool visible = true;
-      // Dynamically check if the widget should be enabled.
-      bool enabled = this->isWidgetEnabled(prop, propName);
-
-      // Do we have a custom IPropertySettings?
-      if (settings)
-      {
-        // Set the visible flag
-        visible = settings->isVisible(m_algo.get());
-
-        // Dynamic PropertySettings objects allow a property to change validators.
-        // This removes the old widget and creates a new one instead.
-        if (settings->isConditionChanged(m_algo.get()))
-        {
-          settings->applyChanges(m_algo.get(), prop);
-
-          // Delete the old widget
-          int row = widget->getGridRow();
-          QGridLayout * layout = widget->getGridLayout();
-          widget->setVisible(false);
-          widget->deleteLater();
-
-          // Create the appropriate widget at this row in the grid.
-          widget = PropertyWidgetFactory::createWidget(prop, this, layout, row);
-
-          // Replace in the list of prop widgets
-          pitr.value() = widget;
-
-          // Whenever the value changes in the widget, this fires propertyChanged()
-          connect(widget, SIGNAL( valueChanged(const QString &)), this, SLOT(propertyChanged(const QString &)));
-        }
-      }
-
-      // Show/hide the validator label (that red star)
-      QString error = "";
-      if (m_errors.contains(propName)) error = m_errors[propName];
-      // Always show controls that are in error
-      if (error.length() != 0)
-        visible = true;
-
-      // Hide/disable the widget
-      widget->setEnabled( enabled );
-      widget->setVisible( visible );
-    } // for each property
+        // Create the appropriate widget at this row in the grid.
+        widget = PropertyWidgetFactory::createWidget(prop, this, layout, row);
 
-    this->repaint();
-  }
+        // Replace in the list of prop widgets
+        pitr.value() = widget;
 
-  //-------------------------------------------------------------------------------------------------
-  /** When closing or changing algorithm, this saves the input
-   * history to QSettings
-   */
-  void AlgorithmPropertiesWidget::saveInput()
-  {
-    if (m_inputHistory)
-    {
-      for( auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end(); ++pitr )
-      {
-        PropertyWidget * widget = pitr.value();
-        QString propName = pitr.key();
-        QString value = widget->getValue();
-//        Mantid::Kernel::Property *prop = widget->getProperty();
-//        if (!prop || prop->remember())
-        m_inputHistory->storeNewValue(m_algoName, QPair<QString, QString>(propName, value));
+        // Whenever the value changes in the widget, this fires
+        // propertyChanged()
+        connect(widget, SIGNAL(valueChanged(const QString &)), this,
+                SLOT(propertyChanged(const QString &)));
       }
     }
+
+    // Show/hide the validator label (that red star)
+    QString error = "";
+    if (m_errors.contains(propName))
+      error = m_errors[propName];
+    // Always show controls that are in error
+    if (error.length() != 0)
+      visible = true;
+
+    // Hide/disable the widget
+    widget->setEnabled(enabled);
+    widget->setVisible(visible);
+  } // for each property
+
+  this->repaint();
+}
+
+//-------------------------------------------------------------------------------------------------
+/** When closing or changing algorithm, this saves the input
+ * history to QSettings
+ */
+void AlgorithmPropertiesWidget::saveInput() {
+  if (m_inputHistory) {
+    for (auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end();
+         ++pitr) {
+      PropertyWidget *widget = pitr.value();
+      QString propName = pitr.key();
+      QString value = widget->getValue();
+      //        Mantid::Kernel::Property *prop = widget->getProperty();
+      //        if (!prop || prop->remember())
+      m_inputHistory->storeNewValue(m_algoName,
+                                    QPair<QString, QString>(propName, value));
+    }
   }
+}
 
 } // namespace Mantid
 } // namespace API
diff --git a/MantidQt/API/src/AlgorithmRunner.cpp b/MantidQt/API/src/AlgorithmRunner.cpp
index b02e5c453155b3585a22737ab10ed1fd7c935404..75488da12bd3cde94b8da6ccce357d7529c6b522 100644
--- a/MantidQt/API/src/AlgorithmRunner.cpp
+++ b/MantidQt/API/src/AlgorithmRunner.cpp
@@ -5,133 +5,125 @@
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace API
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  AlgorithmRunner::AlgorithmRunner(QObject * parent) : QObject(parent),
-    m_finishedObserver(*this, &AlgorithmRunner::handleAlgorithmFinishedNotification),
-    m_progressObserver(*this, &AlgorithmRunner::handleAlgorithmProgressNotification),
-    m_errorObserver(*this, &AlgorithmRunner::handleAlgorithmErrorNotification),
-    m_asyncResult(NULL)
-  {
+namespace MantidQt {
+namespace API {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+AlgorithmRunner::AlgorithmRunner(QObject *parent)
+    : QObject(parent),
+      m_finishedObserver(*this,
+                         &AlgorithmRunner::handleAlgorithmFinishedNotification),
+      m_progressObserver(*this,
+                         &AlgorithmRunner::handleAlgorithmProgressNotification),
+      m_errorObserver(*this,
+                      &AlgorithmRunner::handleAlgorithmErrorNotification),
+      m_asyncResult(NULL) {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+AlgorithmRunner::~AlgorithmRunner() {
+  if (m_asyncAlg) {
+    m_asyncAlg->removeObserver(m_finishedObserver);
+    m_asyncAlg->removeObserver(m_errorObserver);
+    m_asyncAlg->removeObserver(m_progressObserver);
   }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  AlgorithmRunner::~AlgorithmRunner()
-  {
-    if (m_asyncAlg)
-    {
-      m_asyncAlg->removeObserver(m_finishedObserver);
-      m_asyncAlg->removeObserver(m_errorObserver);
-      m_asyncAlg->removeObserver(m_progressObserver);
+  delete m_asyncResult;
+}
+
+//--------------------------------------------------------------------------------------
+/** If an algorithm is already running, cancel it.
+ * Does nothing if no algorithm is running. This blocks
+ * for up to 1 second to wait for the algorithm to finish cancelling.
+ */
+void AlgorithmRunner::cancelRunningAlgorithm() {
+  // Cancel any currently running algorithms
+  if (m_asyncAlg) {
+    if (m_asyncAlg->isRunning()) {
+      m_asyncAlg->cancel();
     }
-    delete m_asyncResult;
-  }
-  
-
-  //--------------------------------------------------------------------------------------
-  /** If an algorithm is already running, cancel it.
-   * Does nothing if no algorithm is running. This blocks
-   * for up to 1 second to wait for the algorithm to finish cancelling.
-   */
-  void AlgorithmRunner::cancelRunningAlgorithm()
-  {
-    // Cancel any currently running algorithms
-    if (m_asyncAlg)
-    {
-      if (m_asyncAlg->isRunning())
-      {
-        m_asyncAlg->cancel();
-      }
-      if (m_asyncResult)
-      {
-        m_asyncResult->tryWait(1000);
-        delete m_asyncResult;
-        m_asyncResult = NULL;
-      }
-      m_asyncAlg->removeObserver(m_finishedObserver);
-      m_asyncAlg->removeObserver(m_errorObserver);
-      m_asyncAlg->removeObserver(m_progressObserver);
-      m_asyncAlg.reset();
+    if (m_asyncResult) {
+      m_asyncResult->tryWait(1000);
+      delete m_asyncResult;
+      m_asyncResult = NULL;
     }
+    m_asyncAlg->removeObserver(m_finishedObserver);
+    m_asyncAlg->removeObserver(m_errorObserver);
+    m_asyncAlg->removeObserver(m_progressObserver);
+    m_asyncAlg.reset();
   }
-
-  //--------------------------------------------------------------------------------------
-  /** Begin asynchronous execution of an algorithm and observe its execution
-   *
-   * @param alg :: algorithm to execute. All properties should have been set properly.
-   */
-  void AlgorithmRunner::startAlgorithm(Mantid::API::IAlgorithm_sptr alg)
-  {
-    if (!alg)
-      throw std::invalid_argument("AlgorithmRunner::startAlgorithm() given a NULL Algorithm");
-    if (!alg->isInitialized())
-      throw std::invalid_argument("AlgorithmRunner::startAlgorithm() given an uninitialized Algorithm");
-
-    cancelRunningAlgorithm();
-
-    // Start asynchronous execution
-    m_asyncAlg = alg;
-    m_asyncResult = new Poco::ActiveResult<bool>(m_asyncAlg->executeAsync());
-
-    // Observe the algorithm
-    alg->addObserver(m_finishedObserver);
-    alg->addObserver(m_errorObserver);
-    alg->addObserver(m_progressObserver);
-  }
-
-  /// Get back a pointer to the running algorithm
-  Mantid::API::IAlgorithm_sptr AlgorithmRunner::getAlgorithm() const
-  {
-    return m_asyncAlg;
-  }
-
-  //--------------------------------------------------------------------------------------
-  /** Observer called when the asynchronous algorithm has completed.
-   *
-   * Emits a signal for the GUI widget
-   *
-   * This is called in a separate (non-GUI) thread and so
-   * CANNOT directly change the gui.
-   *
-   * @param pNf :: finished notification object.
-   */
-  void AlgorithmRunner::handleAlgorithmFinishedNotification(const Poco::AutoPtr<Algorithm::FinishedNotification>& pNf)
-  {
-    UNUSED_ARG(pNf);
-    emit algorithmComplete(false);
-  }
-
-  //--------------------------------------------------------------------------------------
-  /** Observer called when the async algorithm has progress to report
-   *
-   * @param pNf :: notification object
-   */
-  void AlgorithmRunner::handleAlgorithmProgressNotification(const Poco::AutoPtr<Algorithm::ProgressNotification>& pNf)
-  {
-    emit algorithmProgress(pNf->progress, pNf->message);
-  }
-
-  //--------------------------------------------------------------------------------------
-  /** Observer called when the async algorithm has encountered an error.
-   * Emits a signal for the GUI widget
-   *
-   * @param pNf :: notification object
-   */
-  void AlgorithmRunner::handleAlgorithmErrorNotification(const Poco::AutoPtr<Algorithm::ErrorNotification>& pNf)
-  {
-    UNUSED_ARG(pNf);
-    emit algorithmComplete(true);
-  }
-
+}
+
+//--------------------------------------------------------------------------------------
+/** Begin asynchronous execution of an algorithm and observe its execution
+ *
+ * @param alg :: algorithm to execute. All properties should have been set
+ *properly.
+ */
+void AlgorithmRunner::startAlgorithm(Mantid::API::IAlgorithm_sptr alg) {
+  if (!alg)
+    throw std::invalid_argument(
+        "AlgorithmRunner::startAlgorithm() given a NULL Algorithm");
+  if (!alg->isInitialized())
+    throw std::invalid_argument(
+        "AlgorithmRunner::startAlgorithm() given an uninitialized Algorithm");
+
+  cancelRunningAlgorithm();
+
+  // Start asynchronous execution
+  m_asyncAlg = alg;
+  m_asyncResult = new Poco::ActiveResult<bool>(m_asyncAlg->executeAsync());
+
+  // Observe the algorithm
+  alg->addObserver(m_finishedObserver);
+  alg->addObserver(m_errorObserver);
+  alg->addObserver(m_progressObserver);
+}
+
+/// Get back a pointer to the running algorithm
+Mantid::API::IAlgorithm_sptr AlgorithmRunner::getAlgorithm() const {
+  return m_asyncAlg;
+}
+
+//--------------------------------------------------------------------------------------
+/** Observer called when the asynchronous algorithm has completed.
+ *
+ * Emits a signal for the GUI widget
+ *
+ * This is called in a separate (non-GUI) thread and so
+ * CANNOT directly change the gui.
+ *
+ * @param pNf :: finished notification object.
+ */
+void AlgorithmRunner::handleAlgorithmFinishedNotification(
+    const Poco::AutoPtr<Algorithm::FinishedNotification> &pNf) {
+  UNUSED_ARG(pNf);
+  emit algorithmComplete(false);
+}
+
+//--------------------------------------------------------------------------------------
+/** Observer called when the async algorithm has progress to report
+ *
+ * @param pNf :: notification object
+ */
+void AlgorithmRunner::handleAlgorithmProgressNotification(
+    const Poco::AutoPtr<Algorithm::ProgressNotification> &pNf) {
+  emit algorithmProgress(pNf->progress, pNf->message);
+}
+
+//--------------------------------------------------------------------------------------
+/** Observer called when the async algorithm has encountered an error.
+ * Emits a signal for the GUI widget
+ *
+ * @param pNf :: notification object
+ */
+void AlgorithmRunner::handleAlgorithmErrorNotification(
+    const Poco::AutoPtr<Algorithm::ErrorNotification> &pNf) {
+  UNUSED_ARG(pNf);
+  emit algorithmComplete(true);
+}
 
 } // namespace Mantid
 } // namespace API
diff --git a/MantidQt/API/src/BatchAlgorithmRunner.cpp b/MantidQt/API/src/BatchAlgorithmRunner.cpp
index d2bc3d0ebe618b5f0be7b4227acbf61b9c206603..52159a31bf42163053ddf04189b650cfd243d6f8 100644
--- a/MantidQt/API/src/BatchAlgorithmRunner.cpp
+++ b/MantidQt/API/src/BatchAlgorithmRunner.cpp
@@ -5,188 +5,168 @@
 
 using namespace Mantid::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("BatchAlgorithmRunner");
+namespace {
+Mantid::Kernel::Logger g_log("BatchAlgorithmRunner");
 }
 
-namespace MantidQt
-{
-namespace API
-{
-  BatchAlgorithmRunner::BatchAlgorithmRunner(QObject * parent) : QObject(parent),
-    m_stopOnFailure(true),
-    m_notificationCenter(),
-    m_notificationObserver(*this, &BatchAlgorithmRunner::handleNotification),
-    m_executeAsync(this, &BatchAlgorithmRunner::executeBatchAsyncImpl)
-  {
-  }
-
-  BatchAlgorithmRunner::~BatchAlgorithmRunner()
-  {
-    m_notificationCenter.removeObserver(m_notificationObserver);
-  }
-
-  /**
-   * Sets if the execution of the queue should be stopped if an algorithm fails.
-   *
-   * Defaults to true
-   *
-   * @param stopOnFailure Flase to continue to tnd of queue on failure
-   */
-  void BatchAlgorithmRunner::stopOnFailure(bool stopOnFailure)
-  {
-    m_stopOnFailure = stopOnFailure;
-  }
+namespace MantidQt {
+namespace API {
+BatchAlgorithmRunner::BatchAlgorithmRunner(QObject *parent)
+    : QObject(parent), m_stopOnFailure(true), m_notificationCenter(),
+      m_notificationObserver(*this, &BatchAlgorithmRunner::handleNotification),
+      m_executeAsync(this, &BatchAlgorithmRunner::executeBatchAsyncImpl) {}
 
-  /**
-   * Adds an algorithm to the end of the queue.
-   *
-   * @param algo Algorithm to add to queue
-   * @param props Optional map of property name to property values to be set just before execution (mainly intended for input and inout workspace names)
-   */
-  void BatchAlgorithmRunner::addAlgorithm(IAlgorithm_sptr algo, AlgorithmRuntimeProps props)
-  {
-    m_algorithms.emplace_back(algo, props);
-
-    g_log.debug() << "Added algorithm \"" << m_algorithms.back().first->name() << "\" to batch queue\n";
-  }
+BatchAlgorithmRunner::~BatchAlgorithmRunner() {
+  m_notificationCenter.removeObserver(m_notificationObserver);
+}
 
-  /**
-   * Removes all algorithms from the queue.
-   */
-  void BatchAlgorithmRunner::clearQueue()
-  {
-    m_algorithms.clear();
-  }
+/**
+ * Sets if the execution of the queue should be stopped if an algorithm fails.
+ *
+ * Defaults to true
+ *
+ * @param stopOnFailure Flase to continue to tnd of queue on failure
+ */
+void BatchAlgorithmRunner::stopOnFailure(bool stopOnFailure) {
+  m_stopOnFailure = stopOnFailure;
+}
 
-  /**
-   * Returns the number of algorithms in the queue.
-   */
-  size_t BatchAlgorithmRunner::queueLength()
-  {
-    return m_algorithms.size();
-  }
+/**
+ * Adds an algorithm to the end of the queue.
+ *
+ * @param algo Algorithm to add to queue
+ * @param props Optional map of property name to property values to be set just
+ *before execution (mainly intended for input and inout workspace names)
+ */
+void BatchAlgorithmRunner::addAlgorithm(IAlgorithm_sptr algo,
+                                        AlgorithmRuntimeProps props) {
+  m_algorithms.emplace_back(algo, props);
+
+  g_log.debug() << "Added algorithm \"" << m_algorithms.back().first->name()
+                << "\" to batch queue\n";
+}
 
-  /**
-   * Executes the algorithms on a separate thread and waits for their completion.
-   *
-   * @return False if the batch was stopped due to error
-   */
-  bool BatchAlgorithmRunner::executeBatch()
-  {
-    m_notificationCenter.addObserver(m_notificationObserver);
-    Poco::ActiveResult<bool> result = m_executeAsync(Poco::Void());
-    result.wait();
-    m_notificationCenter.removeObserver(m_notificationObserver);
-    return result.data();
-  }
+/**
+ * Removes all algorithms from the queue.
+ */
+void BatchAlgorithmRunner::clearQueue() { m_algorithms.clear(); }
+
+/**
+ * Returns the number of algorithms in the queue.
+ */
+size_t BatchAlgorithmRunner::queueLength() { return m_algorithms.size(); }
+
+/**
+ * Executes the algorithms on a separate thread and waits for their completion.
+ *
+ * @return False if the batch was stopped due to error
+ */
+bool BatchAlgorithmRunner::executeBatch() {
+  m_notificationCenter.addObserver(m_notificationObserver);
+  Poco::ActiveResult<bool> result = m_executeAsync(Poco::Void());
+  result.wait();
+  m_notificationCenter.removeObserver(m_notificationObserver);
+  return result.data();
+}
 
-  /**
-   * Starts executing the queue of algorithms on a separate thread.
-   */
-  void BatchAlgorithmRunner::executeBatchAsync()
-  {
-    m_notificationCenter.addObserver(m_notificationObserver);
-    Poco::ActiveResult<bool> result = m_executeAsync(Poco::Void());
-  }
+/**
+ * Starts executing the queue of algorithms on a separate thread.
+ */
+void BatchAlgorithmRunner::executeBatchAsync() {
+  m_notificationCenter.addObserver(m_notificationObserver);
+  Poco::ActiveResult<bool> result = m_executeAsync(Poco::Void());
+}
 
-  /**
-   * Implementation of sequential algorithm scheduler.
-   */
-  bool BatchAlgorithmRunner::executeBatchAsyncImpl(const Poco::Void&)
-  {
-    bool cancelFlag = false;
-
-    for(auto it = m_algorithms.begin(); it != m_algorithms.end(); ++it)
-    {
-      // Try to execute the algorithm
-      if(!executeAlgo(*it))
-      {
-        g_log.warning() << "Got error from algorithm \"" << m_currentAlgorithm->name() << "\"\n";
-
-        // Stop executing the entire batch if appropriate
-        if(m_stopOnFailure)
-        {
-          g_log.warning("Stopping batch algorithm because of execution error");
-          cancelFlag = true;
-          break;
-        }
-      }
-      else
-      {
-        g_log.information() << "Algorithm \"" << m_currentAlgorithm->name() << "\" finished\n";
+/**
+ * Implementation of sequential algorithm scheduler.
+ */
+bool BatchAlgorithmRunner::executeBatchAsyncImpl(const Poco::Void &) {
+  bool cancelFlag = false;
+
+  for (auto it = m_algorithms.begin(); it != m_algorithms.end(); ++it) {
+    // Try to execute the algorithm
+    if (!executeAlgo(*it)) {
+      g_log.warning() << "Got error from algorithm \""
+                      << m_currentAlgorithm->name() << "\"\n";
+
+      // Stop executing the entire batch if appropriate
+      if (m_stopOnFailure) {
+        g_log.warning("Stopping batch algorithm because of execution error");
+        cancelFlag = true;
+        break;
       }
+    } else {
+      g_log.information() << "Algorithm \"" << m_currentAlgorithm->name()
+                          << "\" finished\n";
     }
+  }
 
-    // Clear queue
-    m_algorithms.clear();
+  // Clear queue
+  m_algorithms.clear();
 
-    m_notificationCenter.postNotification(new BatchNotification(false, cancelFlag));
-    m_notificationCenter.removeObserver(m_notificationObserver);
+  m_notificationCenter.postNotification(
+      new BatchNotification(false, cancelFlag));
+  m_notificationCenter.removeObserver(m_notificationObserver);
 
-    return !cancelFlag;
-  }
+  return !cancelFlag;
+}
 
-  /**
-   * Assigns properties to an algorithm then executes it
-   *
-   * @param algorithm Algorithm and properties to assign to it
-   * @return False if algorithm execution failed
-   */
-  bool BatchAlgorithmRunner::executeAlgo(ConfiguredAlgorithm algorithm)
-  {
-    try
-    {
-      m_currentAlgorithm = algorithm.first;
-
-      // Assign the properties to be set at runtime
-      for(auto it = algorithm.second.begin(); it != algorithm.second.end(); ++it)
-      {
-        m_currentAlgorithm->setProperty(it->first, it->second);
-      }
+/**
+ * Assigns properties to an algorithm then executes it
+ *
+ * @param algorithm Algorithm and properties to assign to it
+ * @return False if algorithm execution failed
+ */
+bool BatchAlgorithmRunner::executeAlgo(ConfiguredAlgorithm algorithm) {
+  try {
+    m_currentAlgorithm = algorithm.first;
+
+    // Assign the properties to be set at runtime
+    for (auto it = algorithm.second.begin(); it != algorithm.second.end();
+         ++it) {
+      m_currentAlgorithm->setProperty(it->first, it->second);
+    }
 
-      g_log.information() << "Starting next algorithm in queue: " << m_currentAlgorithm->name() << "\n";
+    g_log.information() << "Starting next algorithm in queue: "
+                        << m_currentAlgorithm->name() << "\n";
 
-      // Start algorithm running
-      return m_currentAlgorithm->execute();
-    }
-    // If a property name was given that does not match a property
-    catch(Mantid::Kernel::Exception::NotFoundError &notFoundEx)
-    {
-      UNUSED_ARG(notFoundEx);
-      g_log.warning("Algorithm property does not exist.\nStopping queue execution.");
-      return false;
-    }
-    // If a property was assigned a value of the wrong type
-    catch(std::invalid_argument &invalidArgEx)
-    {
-      UNUSED_ARG(invalidArgEx);
-      g_log.warning("Algorithm property given value of incorrect type.\nStopping queue execution.");
-      return false;
-    }
-    // For anything else that could go wrong
-    catch(...)
-    {
-      g_log.warning("Unknown error starting next batch algorithm");
-      return false;
-    }
+    // Start algorithm running
+    return m_currentAlgorithm->execute();
+  }
+  // If a property name was given that does not match a property
+  catch (Mantid::Kernel::Exception::NotFoundError &notFoundEx) {
+    UNUSED_ARG(notFoundEx);
+    g_log.warning(
+        "Algorithm property does not exist.\nStopping queue execution.");
+    return false;
+  }
+  // If a property was assigned a value of the wrong type
+  catch (std::invalid_argument &invalidArgEx) {
+    UNUSED_ARG(invalidArgEx);
+    g_log.warning("Algorithm property given value of incorrect type.\nStopping "
+                  "queue execution.");
+    return false;
+  }
+  // For anything else that could go wrong
+  catch (...) {
+    g_log.warning("Unknown error starting next batch algorithm");
+    return false;
   }
+}
 
-  /**
-   * Handles the notification posted when the algorithm queue stops execution.
-   *
-   * @param pNf Notification object
-   */
-  void BatchAlgorithmRunner::handleNotification(const Poco::AutoPtr<BatchNotification>& pNf)
-  {
-    bool inProgress = pNf->isInProgress();
-    if(!inProgress)
-    {
-      // Notify UI elements waiting for algorithm completion
-      emit batchComplete(pNf->hasError());
-    }
+/**
+ * Handles the notification posted when the algorithm queue stops execution.
+ *
+ * @param pNf Notification object
+ */
+void BatchAlgorithmRunner::handleNotification(
+    const Poco::AutoPtr<BatchNotification> &pNf) {
+  bool inProgress = pNf->isInProgress();
+  if (!inProgress) {
+    // Notify UI elements waiting for algorithm completion
+    emit batchComplete(pNf->hasError());
   }
+}
 
 } // namespace Mantid
 } // namespace API
diff --git a/MantidQt/API/src/BoolPropertyWidget.cpp b/MantidQt/API/src/BoolPropertyWidget.cpp
index 40bb7e50200c9888c79f8e6bf48efff84e208f7d..0bf1d67dc3ea4aee5c44c27cd43062a6c6af9fc3 100644
--- a/MantidQt/API/src/BoolPropertyWidget.cpp
+++ b/MantidQt/API/src/BoolPropertyWidget.cpp
@@ -3,58 +3,52 @@
 
 using namespace Mantid::Kernel;
 
-namespace MantidQt
-{
-namespace API
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  BoolPropertyWidget::BoolPropertyWidget(Mantid::Kernel::PropertyWithValue<bool> * prop, QWidget * parent, QGridLayout * layout, int row)
-  : PropertyWidget(prop, parent, layout, row)
-  {
-    m_checkBox = new QCheckBox(QString::fromStdString(prop->name()), m_parent);
-    m_checkBox->setToolTip(m_doc);
-    connect(m_checkBox, SIGNAL(stateChanged(int)), this, SLOT(userEditedProperty()));
-    m_widgets.push_back(m_checkBox);
-
-    // Add the checkbox at column 1
-    m_gridLayout->addWidget(m_checkBox, m_row, 1, 0);
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  BoolPropertyWidget::~BoolPropertyWidget()
-  {
-  }
-  
-
-
-  //----------------------------------------------------------------------------------------------
-  /** @return the value of the property, as typed in the GUI, as a string */
-  QString BoolPropertyWidget::getValue() const
-  {
-    if (m_checkBox->isChecked())
-      return "1";
-    else
-      return "0";
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Set the value into the GUI
-   *
-   * @param value :: string representation of the value */
-  void BoolPropertyWidget::setValueImpl(const QString & value)
-  {
-    const QString temp = value.isEmpty() ? QString::fromStdString(m_prop->getDefault()) : value;
-    
-    if (temp == "0")
-      m_checkBox->setCheckState(Qt::Unchecked);
-    else
-      m_checkBox->setCheckState(Qt::Checked);
-  }
+namespace MantidQt {
+namespace API {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+BoolPropertyWidget::BoolPropertyWidget(
+    Mantid::Kernel::PropertyWithValue<bool> *prop, QWidget *parent,
+    QGridLayout *layout, int row)
+    : PropertyWidget(prop, parent, layout, row) {
+  m_checkBox = new QCheckBox(QString::fromStdString(prop->name()), m_parent);
+  m_checkBox->setToolTip(m_doc);
+  connect(m_checkBox, SIGNAL(stateChanged(int)), this,
+          SLOT(userEditedProperty()));
+  m_widgets.push_back(m_checkBox);
+
+  // Add the checkbox at column 1
+  m_gridLayout->addWidget(m_checkBox, m_row, 1, 0);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+BoolPropertyWidget::~BoolPropertyWidget() {}
+
+//----------------------------------------------------------------------------------------------
+/** @return the value of the property, as typed in the GUI, as a string */
+QString BoolPropertyWidget::getValue() const {
+  if (m_checkBox->isChecked())
+    return "1";
+  else
+    return "0";
+}
+
+//----------------------------------------------------------------------------------------------
+/** Set the value into the GUI
+ *
+ * @param value :: string representation of the value */
+void BoolPropertyWidget::setValueImpl(const QString &value) {
+  const QString temp =
+      value.isEmpty() ? QString::fromStdString(m_prop->getDefault()) : value;
+
+  if (temp == "0")
+    m_checkBox->setCheckState(Qt::Unchecked);
+  else
+    m_checkBox->setCheckState(Qt::Checked);
+}
 } // namespace MantidQt
 } // namespace API
diff --git a/MantidQt/API/src/GenericDialog.cpp b/MantidQt/API/src/GenericDialog.cpp
index 852585ba8ab6106c091515495cfa1268fd31b1db..cfad329e99df845f41a0a7493d6cf5540c5c8d90 100644
--- a/MantidQt/API/src/GenericDialog.cpp
+++ b/MantidQt/API/src/GenericDialog.cpp
@@ -43,21 +43,13 @@ using namespace Mantid::API;
 /**
 * Default Constructor
 */
-GenericDialog::GenericDialog(QWidget* parent) : AlgorithmDialog(parent),
-  m_algoPropertiesWidget(NULL)
-{
-}
+GenericDialog::GenericDialog(QWidget *parent)
+    : AlgorithmDialog(parent), m_algoPropertiesWidget(NULL) {}
 
 /**
 * Destructor
 */
-GenericDialog::~GenericDialog()
-{
-}
-
-
-
-
+GenericDialog::~GenericDialog() {}
 
 //----------------------------------
 // Protected member functions
@@ -65,14 +57,13 @@ GenericDialog::~GenericDialog()
 /**
 * Create the layout for this dialog.
 */
-void GenericDialog::initLayout()
-{
+void GenericDialog::initLayout() {
 
   // Add a layout for QDialog
   QVBoxLayout *dialog_layout = new QVBoxLayout();
   setLayout(dialog_layout);
   // Add the helpful summary message
-  if( isMessageAvailable() )
+  if (isMessageAvailable())
     this->addOptionalMessage(dialog_layout);
 
   // Make the widget with all the properties
@@ -90,11 +81,11 @@ void GenericDialog::initLayout()
   disabled += m_python_arguments;
   m_algoPropertiesWidget->addEnabledAndDisableLists(enabled, disabled);
 
-
   // At this point, all the widgets have been added and are visible.
-  // This makes sure the viewport does not get scaled smaller, even if some controls are hidden.
-  QWidget * viewport = m_algoPropertiesWidget->m_viewport;
-  //QScrollArea * scroll = m_algoPropertiesWidget->m_scroll;
+  // This makes sure the viewport does not get scaled smaller, even if some
+  // controls are hidden.
+  QWidget *viewport = m_algoPropertiesWidget->m_viewport;
+  // QScrollArea * scroll = m_algoPropertiesWidget->m_scroll;
   viewport->layout()->update();
   // This makes the layout minimum size = that of the widgets inside
   viewport->layout()->setSizeConstraint(QLayout::SetMinimumSize);
@@ -106,16 +97,16 @@ void GenericDialog::initLayout()
 
   // If the thing won't end up too big compared to the screen height,
   // resize the scroll area so we don't get a scroll bar
-  if ( (dialogHeight+100) < 0.8*screenHeight )
-  {
-    m_algoPropertiesWidget->m_scroll->setMinimumHeight(dialogHeight+10);
+  if ((dialogHeight + 100) < 0.8 * screenHeight) {
+    m_algoPropertiesWidget->m_scroll->setMinimumHeight(dialogHeight + 10);
 
     // Find the size that the dialog WANTS to be.
     dialogHeight = this->sizeHint().height();
 
     // Choose a width given the desired size, but limit it
     int dialogWidth = this->sizeHint().width() + 25;
-    if (dialogWidth > 640) dialogWidth = 640;
+    if (dialogWidth > 640)
+      dialogWidth = 640;
 
     // But allow the scroll area to resize smaller again
     m_algoPropertiesWidget->m_scroll->setMinimumHeight(60);
@@ -124,25 +115,21 @@ void GenericDialog::initLayout()
   }
 
   // Set all previous values (from history, etc.)
-  for( auto it = m_algoPropertiesWidget->m_propWidgets.begin(); it != m_algoPropertiesWidget->m_propWidgets.end(); it++)
-  {
+  for (auto it = m_algoPropertiesWidget->m_propWidgets.begin();
+       it != m_algoPropertiesWidget->m_propWidgets.end(); it++) {
     this->setPreviousValue(it.value(), it.key());
   }
 
   // Using the default values, hide or disable the dynamically shown properties
   m_algoPropertiesWidget->hideOrDisableProperties();
-
 }
 
-
 //-----------------------------------------------------------------------------
 /** Parse out information from the dialog
  */
-void GenericDialog::parseInput()
-{
+void GenericDialog::parseInput() {
   auto itr = m_algoPropertiesWidget->m_propWidgets.begin();
-  for(; itr != m_algoPropertiesWidget->m_propWidgets.end(); itr++ )
-  {
+  for (; itr != m_algoPropertiesWidget->m_propWidgets.end(); itr++) {
     // Get the value from each widget and store it
     storePropertyValue(itr.key(), itr.value()->getValue());
   }
@@ -153,33 +140,30 @@ void GenericDialog::parseInput()
  * A slot that can be used to connect a button that accepts the dialog if
  * all of the properties are valid
  */
-void GenericDialog::accept()
-{
+void GenericDialog::accept() {
   // Get property values
   parse();
 
-  //Try and set and validate the properties and
-  if( setPropertyValues() )
-  {
-    //Store input for next time
+  // Try and set and validate the properties and
+  if (setPropertyValues()) {
+    // Store input for next time
     saveInput();
     if (!this->m_keepOpen) {
       QDialog::accept();
+    } else {
+      executeAlgorithmAsync();
     }
-    else {
-       executeAlgorithmAsync();
-    }
-  }
-  else
-  {
-    // Highlight the validators that are in error (combined from them + whole algorithm)
+  } else {
+    // Highlight the validators that are in error (combined from them + whole
+    // algorithm)
     // If got there, there were errors
-    for(auto it = m_errors.begin(); it != m_errors.end(); it++)
-      m_algoPropertiesWidget->m_propWidgets[it.key()]->updateIconVisibility(it.value());
-
-    QMessageBox::critical(this, "",
-              "One or more properties are invalid. The invalid properties are\n"
-        "marked with a *, hold your mouse over the * for more information." );
+    for (auto it = m_errors.begin(); it != m_errors.end(); it++)
+      m_algoPropertiesWidget->m_propWidgets[it.key()]->updateIconVisibility(
+          it.value());
+
+    QMessageBox::critical(
+        this, "",
+        "One or more properties are invalid. The invalid properties are\n"
+        "marked with a *, hold your mouse over the * for more information.");
   }
 }
-
diff --git a/MantidQt/API/src/HelpWindow.cpp b/MantidQt/API/src/HelpWindow.cpp
index 78357ac445c956c5c00ffd353a2244b3f6c43506..5638f1ca3ca1dbb55bffb62313a477073ef437e0 100644
--- a/MantidQt/API/src/HelpWindow.cpp
+++ b/MantidQt/API/src/HelpWindow.cpp
@@ -10,143 +10,116 @@
 #include <QUrl>
 #include <QWidget>
 
-namespace MantidQt
-{
-namespace API
-{
-  namespace
-  {
-    /// static logger
-    Mantid::Kernel::Logger g_log("HelpWindow");
+namespace MantidQt {
+namespace API {
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("HelpWindow");
 
-    /**
-     * Attach the parent to the gui and connect the shutdown signal
-     *
-     * @param gui The help window that will render the url.
-     * @param parent The parent widget.
-     */
-    void connectParent(MantidHelpInterface *gui, QWidget *parent)
-    {
-      if (parent)
-      {
-        QObject::connect(parent, SIGNAL(shutting_down()), gui, SLOT(shutdown()));
-        gui->setParent(parent);
-      }
-    }
+/**
+ * Attach the parent to the gui and connect the shutdown signal
+ *
+ * @param gui The help window that will render the url.
+ * @param parent The parent widget.
+ */
+void connectParent(MantidHelpInterface *gui, QWidget *parent) {
+  if (parent) {
+    QObject::connect(parent, SIGNAL(shutting_down()), gui, SLOT(shutdown()));
+    gui->setParent(parent);
   }
+}
+}
 
-  using std::string;
+using std::string;
 
-  void HelpWindow::showPage(QWidget *parent, const std::string & url)
-  {
-    showPage(parent, QString(url.c_str()));
-  }
+void HelpWindow::showPage(QWidget *parent, const std::string &url) {
+  showPage(parent, QString(url.c_str()));
+}
 
-  void HelpWindow::showPage(QWidget *parent, const QString & url)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showPage(url);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for page " << url.toStdString() << "\n";
-    }
+void HelpWindow::showPage(QWidget *parent, const QString &url) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showPage(url);
+  } else {
+    g_log.error() << "Failed to launch help for page " << url.toStdString()
+                  << "\n";
   }
+}
 
-  void HelpWindow::showPage(QWidget *parent, const QUrl & url)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showPage(url);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for page " << url.toString().toStdString() << "\n";
-    }
+void HelpWindow::showPage(QWidget *parent, const QUrl &url) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showPage(url);
+  } else {
+    g_log.error() << "Failed to launch help for page "
+                  << url.toString().toStdString() << "\n";
   }
+}
 
-  void HelpWindow::showAlgorithm(QWidget *parent, const std::string &name, const int version)
-  {
-    showAlgorithm(parent, QString(name.c_str()), version);
-  }
+void HelpWindow::showAlgorithm(QWidget *parent, const std::string &name,
+                               const int version) {
+  showAlgorithm(parent, QString(name.c_str()), version);
+}
 
-  void HelpWindow::showAlgorithm(QWidget *parent, const QString &name, const int version)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showAlgorithm(name, version);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for algorithm " << name.toStdString()
-                    << " v" << version << "\n";
-    }
-  }
-  
-  void HelpWindow::showConcept(QWidget *parent, const std::string &name)
-  {
-    showConcept(parent, QString(name.c_str()));
+void HelpWindow::showAlgorithm(QWidget *parent, const QString &name,
+                               const int version) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showAlgorithm(name, version);
+  } else {
+    g_log.error() << "Failed to launch help for algorithm "
+                  << name.toStdString() << " v" << version << "\n";
   }
+}
 
-  void HelpWindow::showConcept(QWidget *parent, const QString &name)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showConcept(name);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for concept " << name.toStdString() << "\n";
-    }
-  }
+void HelpWindow::showConcept(QWidget *parent, const std::string &name) {
+  showConcept(parent, QString(name.c_str()));
+}
 
-  void HelpWindow::showFitFunction(QWidget *parent, const std::string &name)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showFitFunction(name);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for fit function " << name << "\n";
-    }
+void HelpWindow::showConcept(QWidget *parent, const QString &name) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showConcept(name);
+  } else {
+    g_log.error() << "Failed to launch help for concept " << name.toStdString()
+                  << "\n";
   }
+}
 
-  void HelpWindow::showCustomInterface(QWidget *parent, const std::string &name)
-  {
-    showCustomInterface(parent, QString(name.c_str()));
+void HelpWindow::showFitFunction(QWidget *parent, const std::string &name) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showFitFunction(name);
+  } else {
+    g_log.error() << "Failed to launch help for fit function " << name << "\n";
   }
+}
+
+void HelpWindow::showCustomInterface(QWidget *parent, const std::string &name) {
+  showCustomInterface(parent, QString(name.c_str()));
+}
 
-  void HelpWindow::showCustomInterface(QWidget *parent, const QString &name)
-  {
-    InterfaceManager interfaceManager;
-    MantidHelpInterface *gui = interfaceManager.createHelpWindow();
-    if (gui)
-    {
-      connectParent(gui, parent);
-      gui->showCustomInterface(name);
-    }
-    else
-    {
-      g_log.error() << "Failed to launch help for custom interface " << name.toStdString() << "\n";
-    }
+void HelpWindow::showCustomInterface(QWidget *parent, const QString &name) {
+  InterfaceManager interfaceManager;
+  MantidHelpInterface *gui = interfaceManager.createHelpWindow();
+  if (gui) {
+    connectParent(gui, parent);
+    gui->showCustomInterface(name);
+  } else {
+    g_log.error() << "Failed to launch help for custom interface "
+                  << name.toStdString() << "\n";
   }
+}
 
 } // namespace API
 } // namespace MantidQt
diff --git a/MantidQt/API/src/InterfaceFactory.cpp b/MantidQt/API/src/InterfaceFactory.cpp
index d1f5a8d434337a4fe9cca63586ef73867cec609a..8fb82902eb0e22a88d5f479262089fea51a42bb3 100644
--- a/MantidQt/API/src/InterfaceFactory.cpp
+++ b/MantidQt/API/src/InterfaceFactory.cpp
@@ -8,14 +8,13 @@
 
 using namespace MantidQt::API;
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("UserSubWindowFactoryImpl");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("UserSubWindowFactoryImpl");
 }
 
 //*********************************************************
-//                 UserSubWindow 
+//                 UserSubWindow
 //*********************************************************
 
 //----------------------------------------
@@ -24,43 +23,47 @@ namespace
 
 /**
  * Create a raw pointer to the interface with the given name
- * @param name :: The name of the interface that should have been registered into the factory
+ * @param name :: The name of the interface that should have been registered
+ * into the factory
  */
-UserSubWindow * UserSubWindowFactoryImpl::createUnwrapped(const std::string & name) const
-{
+UserSubWindow *
+UserSubWindowFactoryImpl::createUnwrapped(const std::string &name) const {
   // Try primary name as a start
   UserSubWindow *window;
-  try
-  {
-    window = Mantid::Kernel::DynamicFactory<UserSubWindow>::createUnwrapped(name);
-  }
-  catch(Mantid::Kernel::Exception::NotFoundError&)
-  {
-    g_log.debug() << "\"" << name << "\" not registered as a real name, trying an alias.\n";
+  try {
+    window =
+        Mantid::Kernel::DynamicFactory<UserSubWindow>::createUnwrapped(name);
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+    g_log.debug() << "\"" << name
+                  << "\" not registered as a real name, trying an alias.\n";
     window = NULL;
   }
-  if( !window )
-  {
+  if (!window) {
     window = createFromAlias(name);
   }
-  if( !window ) 
-  {
-    g_log.error() << "UserSubWindowFactory: \""+ name + "\" is not registered as an interface name.\n";
-    throw Mantid::Kernel::Exception::NotFoundError("UserSubWindowFactory:"+ name + " is not registered or recognised as an alias of a known interface.\n", name);
+  if (!window) {
+    g_log.error() << "UserSubWindowFactory: \"" + name +
+                         "\" is not registered as an interface name.\n";
+    throw Mantid::Kernel::Exception::NotFoundError(
+        "UserSubWindowFactory:" + name + " is not registered or recognised as "
+                                         "an alias of a known interface.\n",
+        name);
   }
-  return window;   
+  return window;
 }
 
 /**
- * Return the set of categories that the interface with the given name belongs to.
+ * Return the set of categories that the interface with the given name belongs
+ *to.
  *
  * @param interfaceName :: The name of the interface.
- * @returns the set of category names if an interface with the given name has been registered,
+ * @returns the set of category names if an interface with the given name has
+ *been registered,
  *          else an empty set.
  */
-QSet<QString> UserSubWindowFactoryImpl::getInterfaceCategories(const QString & interfaceName) const
-{
-  if( !m_categoryLookup.contains(interfaceName) )
+QSet<QString> UserSubWindowFactoryImpl::getInterfaceCategories(
+    const QString &interfaceName) const {
+  if (!m_categoryLookup.contains(interfaceName))
     return QSet<QString>();
 
   return m_categoryLookup[interfaceName];
@@ -71,42 +74,35 @@ QSet<QString> UserSubWindowFactoryImpl::getInterfaceCategories(const QString & i
 //----------------------------------------
 
 /// Default constructor
-UserSubWindowFactoryImpl::UserSubWindowFactoryImpl() : m_aliasLookup(), m_badAliases()
-{
-}
+UserSubWindowFactoryImpl::UserSubWindowFactoryImpl()
+    : m_aliasLookup(), m_badAliases() {}
 
 /**
  * Create a user sub window by searching for an alias name
  * @param name :: The alias name to use to try and create an interface
- * @returns A pointer to a created interface pointer if this alias exists and is not multiply defined
+ * @returns A pointer to a created interface pointer if this alias exists and is
+ * not multiply defined
  */
-UserSubWindow * UserSubWindowFactoryImpl::createFromAlias(const std::string & name) const
-{
+UserSubWindow *
+UserSubWindowFactoryImpl::createFromAlias(const std::string &name) const {
   QString alias = QString::fromStdString(name);
-  if( m_badAliases.contains(alias) )
-  {
-    std::string error = "Alias \"" + name + "\" is defined for multiple real interfaces: \"";
+  if (m_badAliases.contains(alias)) {
+    std::string error =
+        "Alias \"" + name + "\" is defined for multiple real interfaces: \"";
     QListIterator<std::string> itr(m_badAliases.value(alias));
-    while( itr.hasNext() )
-    {
+    while (itr.hasNext()) {
       error += itr.next();
-      if( itr.hasNext() )
-      {
+      if (itr.hasNext()) {
         error += ",";
       }
     }
-      g_log.error() << error + "\n";
+    g_log.error() << error + "\n";
     return NULL;
   }
 
-  if( m_aliasLookup.contains(alias) )
-  {
+  if (m_aliasLookup.contains(alias)) {
     return this->createUnwrapped(m_aliasLookup.value(alias));
-  }
-  else
-  {
+  } else {
     return NULL;
   }
-}	
-
-
+}
diff --git a/MantidQt/API/src/InterfaceManager.cpp b/MantidQt/API/src/InterfaceManager.cpp
index 9bba267c27daf9362ab6344cc4508745b45ec889..2ecb6a920887920198e2a77ba008ba3fe566d1d5 100644
--- a/MantidQt/API/src/InterfaceManager.cpp
+++ b/MantidQt/API/src/InterfaceManager.cpp
@@ -21,53 +21,57 @@
 
 using namespace MantidQt::API;
 
-namespace
-{
-  // static logger
-  Mantid::Kernel::Logger g_log("InterfaceManager");
+namespace {
+// static logger
+Mantid::Kernel::Logger g_log("InterfaceManager");
 }
 
 // initialise VATES factory
-Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *InterfaceManager::m_vatesGuiFactory = NULL;
+Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *
+    InterfaceManager::m_vatesGuiFactory = NULL;
 // initialise HelpWindow factory
-Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *InterfaceManager::m_helpViewer = NULL;
+Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *
+    InterfaceManager::m_helpViewer = NULL;
 
 //----------------------------------
 // Public member functions
 //----------------------------------
 /**
- * Return a specialized dialog for the given algorithm. If none exists then the default is returned
+ * Return a specialized dialog for the given algorithm. If none exists then the
+ * default is returned
  * @param alg :: A pointer to the algorithm
  * @param parent :: An optional parent widget
- * @param forScript :: A boolean indicating if this dialog is to be use for from a script or not. If true disables the autoexecution of the dialog
- * @param presetValues :: A hash of property names to preset values for the dialog
- * @param optionalMsg :: An optional message string to be placed at the top of the dialog
+ * @param forScript :: A boolean indicating if this dialog is to be use for from
+ * a script or not. If true disables the autoexecution of the dialog
+ * @param presetValues :: A hash of property names to preset values for the
+ * dialog
+ * @param optionalMsg :: An optional message string to be placed at the top of
+ * the dialog
  * @param enabled :: These properties will be left enabled
  * @param disabled :: These properties will be left disabled
  * @returns An AlgorithmDialog object
  */
-AlgorithmDialog*
-InterfaceManager::createDialog(boost::shared_ptr<Mantid::API::IAlgorithm> alg, QWidget* parent,
-                               bool forScript, const QHash<QString,QString> & presetValues,
-                               const QString & optionalMsg,  const QStringList & enabled, const QStringList & disabled)
-{
-  AlgorithmDialog* dlg = NULL;
-  if( AlgorithmDialogFactory::Instance().exists(alg->name() + "Dialog") )
-  {
-    g_log.debug() << "Creating a specialised dialog for " << alg->name() << std::endl;
-    dlg = AlgorithmDialogFactory::Instance().createUnwrapped(alg->name() + "Dialog");
-  }
-  else
-  {
+AlgorithmDialog *InterfaceManager::createDialog(
+    boost::shared_ptr<Mantid::API::IAlgorithm> alg, QWidget *parent,
+    bool forScript, const QHash<QString, QString> &presetValues,
+    const QString &optionalMsg, const QStringList &enabled,
+    const QStringList &disabled) {
+  AlgorithmDialog *dlg = NULL;
+  if (AlgorithmDialogFactory::Instance().exists(alg->name() + "Dialog")) {
+    g_log.debug() << "Creating a specialised dialog for " << alg->name()
+                  << std::endl;
+    dlg = AlgorithmDialogFactory::Instance().createUnwrapped(alg->name() +
+                                                             "Dialog");
+  } else {
     dlg = new GenericDialog;
-    g_log.debug() << "No specialised dialog exists for the " << alg->name() 
+    g_log.debug() << "No specialised dialog exists for the " << alg->name()
                   << " algorithm: a generic one has been created" << std::endl;
   }
 
   // The parent so that the dialog appears on top of it
   dlg->setParent(parent);
   dlg->setAttribute(Qt::WA_DeleteOnClose, true);
-  
+
   // Set the QDialog window flags to ensure the dialog ends up on top
   Qt::WindowFlags flags = 0;
   flags |= Qt::Dialog;
@@ -84,7 +88,8 @@ InterfaceManager::createDialog(boost::shared_ptr<Mantid::API::IAlgorithm> alg, Q
   // Setup the layout
   dlg->initializeLayout();
 
-  if(forScript) dlg->executeOnAccept(false); //override default
+  if (forScript)
+    dlg->executeOnAccept(false); // override default
   return dlg;
 }
 
@@ -92,21 +97,27 @@ InterfaceManager::createDialog(boost::shared_ptr<Mantid::API::IAlgorithm> alg, Q
  * @param algorithmName :: Name of AlgorithmDialog
  * @param version :: Version number
  * @param parent :: An optional parent widget
- * @param forScript :: A boolean indicating if this dialog is to be use for from a script or not
- * @param presetValues :: A hash of property names to preset values for the dialog
- * @param optionalMsg :: An optional message string to be placed at the top of the dialog
+ * @param forScript :: A boolean indicating if this dialog is to be use for from
+ * a script or not
+ * @param presetValues :: A hash of property names to preset values for the
+ * dialog
+ * @param optionalMsg :: An optional message string to be placed at the top of
+ * the dialog
  * @param enabled :: These properties will be left enabled
  * @param disabled :: These properties will be left disabled
  */
-AlgorithmDialog* InterfaceManager::createDialogFromName(const QString& algorithmName, const int version, QWidget* parent, bool forScript,
-                                                        const QHash<QString, QString> &presetValues,
-                                                        const QString &optionalMsg, const QStringList &enabled, const QStringList &disabled)
-{
-    // Create the algorithm. This should throw if the algorithm can't be found.
-    auto alg = Mantid::API::AlgorithmManager::Instance().create(algorithmName.toStdString(), version);
+AlgorithmDialog *InterfaceManager::createDialogFromName(
+    const QString &algorithmName, const int version, QWidget *parent,
+    bool forScript, const QHash<QString, QString> &presetValues,
+    const QString &optionalMsg, const QStringList &enabled,
+    const QStringList &disabled) {
+  // Create the algorithm. This should throw if the algorithm can't be found.
+  auto alg = Mantid::API::AlgorithmManager::Instance().create(
+      algorithmName.toStdString(), version);
 
-    // Forward call.
-    return createDialog(alg, parent, forScript, presetValues, optionalMsg, enabled, disabled);
+  // Forward call.
+  return createDialog(alg, parent, forScript, presetValues, optionalMsg,
+                      enabled, disabled);
 }
 
 /**
@@ -114,27 +125,22 @@ AlgorithmDialog* InterfaceManager::createDialogFromName(const QString& algorithm
  * @param interface_name :: The registered name of the interface
  * @param parent :: The parent widget
  */
-UserSubWindow* InterfaceManager::createSubWindow(const QString & interface_name, QWidget* parent)
-{
+UserSubWindow *InterfaceManager::createSubWindow(const QString &interface_name,
+                                                 QWidget *parent) {
   UserSubWindow *user_win = NULL;
   std::string iname = interface_name.toStdString();
-  try
-  {
+  try {
     user_win = UserSubWindowFactory::Instance().createUnwrapped(iname);
-  }
-  catch(Mantid::Kernel::Exception::NotFoundError &)
-  {
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
     user_win = NULL;
   }
-  if( user_win )
-  {
-    g_log.debug() << "Created a specialised interface for " << iname << std::endl;
+  if (user_win) {
+    g_log.debug() << "Created a specialised interface for " << iname
+                  << std::endl;
     user_win->setParent(parent);
     user_win->setInterfaceName(interface_name);
-    user_win->initializeLayout(); 
-  }
-  else
-  {
+    user_win->initializeLayout();
+  } else {
     g_log.error() << "Error creating interface " << iname << "\n";
   }
   return user_win;
@@ -142,15 +148,15 @@ UserSubWindow* InterfaceManager::createSubWindow(const QString & interface_name,
 
 /**
  * The keys associated with UserSubWindow classes
- * @returns A QStringList containing the keys from the InterfaceFactory that refer to UserSubWindow classes
+ * @returns A QStringList containing the keys from the InterfaceFactory that
+ * refer to UserSubWindow classes
  */
-QStringList InterfaceManager::getUserSubWindowKeys() const
-{
+QStringList InterfaceManager::getUserSubWindowKeys() const {
   QStringList key_list;
   std::vector<std::string> keys = UserSubWindowFactory::Instance().getKeys();
   std::vector<std::string>::const_iterator iend = keys.end();
-  for( std::vector<std::string>::const_iterator itr = keys.begin(); itr != iend; ++itr )
-  {
+  for (std::vector<std::string>::const_iterator itr = keys.begin(); itr != iend;
+       ++itr) {
     key_list.append(QString::fromStdString(*itr));
   }
   return key_list;
@@ -160,23 +166,23 @@ QStringList InterfaceManager::getUserSubWindowKeys() const
 // Private member functions
 //----------------------------------
 /// Default Constructor
-InterfaceManager::InterfaceManager()
-{
+InterfaceManager::InterfaceManager() {
   // Attempt to load libraries that may contain custom interface classes
-  const std::string libpath = Mantid::Kernel::ConfigService::Instance().getString("mantidqt.plugins.directory");
-  if( !libpath.empty() )
-  {
-    // Lazy loading. Avoid loading libraries every time a new instance is created.
+  const std::string libpath =
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "mantidqt.plugins.directory");
+  if (!libpath.empty()) {
+    // Lazy loading. Avoid loading libraries every time a new instance is
+    // created.
     static bool isLoaded;
-    if(!isLoaded)
-    {
-      int nloaded = Mantid::Kernel::LibraryManager::Instance().OpenAllLibraries(libpath);
-      if( nloaded == 0 )
-      {
+    if (!isLoaded) {
+      int nloaded =
+          Mantid::Kernel::LibraryManager::Instance().OpenAllLibraries(libpath);
+      if (nloaded == 0) {
         g_log.warning() << "Unable to load Qt plugin libraries.\n"
-          << "Please check that the 'mantidqt.plugins.directory' variable in the .properties file points to "
-          << "the correct location."
-          << std::endl;
+                        << "Please check that the 'mantidqt.plugins.directory' "
+                           "variable in the .properties file points to "
+                        << "the correct location." << std::endl;
       }
       isLoaded = true;
     }
@@ -184,12 +190,10 @@ InterfaceManager::InterfaceManager()
 }
 
 /// Destructor
-InterfaceManager::~InterfaceManager()
-{
-}
+InterfaceManager::~InterfaceManager() {}
 
-void InterfaceManager::registerVatesGuiFactory(Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *factory)
-{
+void InterfaceManager::registerVatesGuiFactory(
+    Mantid::Kernel::AbstractInstantiator<VatesViewerInterface> *factory) {
   m_vatesGuiFactory = factory;
 }
 
@@ -197,49 +201,38 @@ void InterfaceManager::registerVatesGuiFactory(Mantid::Kernel::AbstractInstantia
 Getter to determine if vates components have been installed.
 @return true if they are available.
 */
-bool InterfaceManager::hasVatesLibraries()
-{
-  return NULL != m_vatesGuiFactory;
-}
+bool InterfaceManager::hasVatesLibraries() { return NULL != m_vatesGuiFactory; }
 
-
-
-VatesViewerInterface *InterfaceManager::createVatesSimpleGui() const
-{
-  if(m_vatesGuiFactory == NULL)
-  {
-    g_log.error() << "InterfaceManager::createVatesSimpleGui is null. Mantid Vates package is probably not installed." << std::endl;
-    throw Mantid::Kernel::Exception::NullPointerException("InterfaceManager::createVatesSimpleGui", "m_vatesGuiFactory");
-  }
-  else 
-  {
-    VatesViewerInterface *vsg = this->m_vatesGuiFactory->createUnwrappedInstance();
-    if (!vsg)
-    {
+VatesViewerInterface *InterfaceManager::createVatesSimpleGui() const {
+  if (m_vatesGuiFactory == NULL) {
+    g_log.error() << "InterfaceManager::createVatesSimpleGui is null. Mantid "
+                     "Vates package is probably not installed." << std::endl;
+    throw Mantid::Kernel::Exception::NullPointerException(
+        "InterfaceManager::createVatesSimpleGui", "m_vatesGuiFactory");
+  } else {
+    VatesViewerInterface *vsg =
+        this->m_vatesGuiFactory->createUnwrappedInstance();
+    if (!vsg) {
       g_log.error() << "Error creating Vates Simple GUI" << std::endl;
     }
     return vsg;
   }
 }
 
-
-void InterfaceManager::registerHelpWindowFactory(Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *factory)
-{
+void InterfaceManager::registerHelpWindowFactory(
+    Mantid::Kernel::AbstractInstantiator<MantidHelpInterface> *factory) {
   m_helpViewer = factory;
 }
 
-MantidHelpInterface *InterfaceManager::createHelpWindow() const
-{
-  if(m_helpViewer == NULL)
-  {
+MantidHelpInterface *InterfaceManager::createHelpWindow() const {
+  if (m_helpViewer == NULL) {
     g_log.error("InterfaceManager::createHelpWindow is null.");
-    throw Mantid::Kernel::Exception::NullPointerException("InterfaceManager::createHelpWindow", "m_helpViewer");
-  }
-  else
-  {
-    MantidHelpInterface *interface = this->m_helpViewer->createUnwrappedInstance();
-    if (!interface)
-    {
+    throw Mantid::Kernel::Exception::NullPointerException(
+        "InterfaceManager::createHelpWindow", "m_helpViewer");
+  } else {
+    MantidHelpInterface *interface =
+        this->m_helpViewer->createUnwrappedInstance();
+    if (!interface) {
       g_log.error("Error creating help window");
     }
     return interface;
diff --git a/MantidQt/API/src/ManageUserDirectories.cpp b/MantidQt/API/src/ManageUserDirectories.cpp
index b116ed30c9abc1c82bff8871eb028be1975aec79..abd2830acdf14bd257abd574f2fb168e9a4b88fd 100644
--- a/MantidQt/API/src/ManageUserDirectories.cpp
+++ b/MantidQt/API/src/ManageUserDirectories.cpp
@@ -5,17 +5,16 @@
 
 using namespace MantidQt::API;
 
-ManageUserDirectories::ManageUserDirectories(QWidget *parent) : QDialog(parent)
-{
+ManageUserDirectories::ManageUserDirectories(QWidget *parent)
+    : QDialog(parent) {
   setAttribute(Qt::WA_DeleteOnClose);
-	m_uiForm.setupUi(this);
+  m_uiForm.setupUi(this);
   initLayout();
 }
 
 ManageUserDirectories::~ManageUserDirectories() {}
 
-void ManageUserDirectories::initLayout()
-{
+void ManageUserDirectories::initLayout() {
   loadProperties();
 
   // Make Connections
@@ -23,55 +22,69 @@ void ManageUserDirectories::initLayout()
   connect(m_uiForm.pbCancel, SIGNAL(clicked()), this, SLOT(cancelClicked()));
   connect(m_uiForm.pbConfirm, SIGNAL(clicked()), this, SLOT(confirmClicked()));
 
-  connect(m_uiForm.pbAddDirectory, SIGNAL(clicked()), this, SLOT(addDirectory()));
-  connect(m_uiForm.pbAddDirectoryPython, SIGNAL(clicked()), this, SLOT(addDirectory()));
-  connect(m_uiForm.pbBrowseToDir, SIGNAL(clicked()), this, SLOT(browseToDirectory()));
-  connect(m_uiForm.pbBrowseToDirPython, SIGNAL(clicked()), this, SLOT(browseToDirectory()));
+  connect(m_uiForm.pbAddDirectory, SIGNAL(clicked()), this,
+          SLOT(addDirectory()));
+  connect(m_uiForm.pbAddDirectoryPython, SIGNAL(clicked()), this,
+          SLOT(addDirectory()));
+  connect(m_uiForm.pbBrowseToDir, SIGNAL(clicked()), this,
+          SLOT(browseToDirectory()));
+  connect(m_uiForm.pbBrowseToDirPython, SIGNAL(clicked()), this,
+          SLOT(browseToDirectory()));
   connect(m_uiForm.pbRemDir, SIGNAL(clicked()), this, SLOT(remDir()));
   connect(m_uiForm.pbRemDirPython, SIGNAL(clicked()), this, SLOT(remDir()));
   connect(m_uiForm.pbMoveUp, SIGNAL(clicked()), this, SLOT(moveUp()));
   connect(m_uiForm.pbMoveUpPython, SIGNAL(clicked()), this, SLOT(moveUp()));
   connect(m_uiForm.pbMoveDown, SIGNAL(clicked()), this, SLOT(moveDown()));
   connect(m_uiForm.pbMoveDownPython, SIGNAL(clicked()), this, SLOT(moveDown()));
-  
-  connect(m_uiForm.pbSaveBrowse, SIGNAL(clicked()), this, SLOT(selectSaveDir()));
+
+  connect(m_uiForm.pbSaveBrowse, SIGNAL(clicked()), this,
+          SLOT(selectSaveDir()));
 }
 
-void ManageUserDirectories::loadProperties()
-{
-  m_userPropFile = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getUserFilename()).trimmed();
+void ManageUserDirectories::loadProperties() {
+  m_userPropFile =
+      QString::fromStdString(
+          Mantid::Kernel::ConfigService::Instance().getUserFilename())
+          .trimmed();
 
   // get data search directories and populate the list widget (lwDataSearchDirs)
-  QString directories = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).trimmed();
-  QStringList list = directories.split(";",QString::SkipEmptyParts);
+  QString directories = QString::fromStdString(
+                            Mantid::Kernel::ConfigService::Instance().getString(
+                                "datasearch.directories")).trimmed();
+  QStringList list = directories.split(";", QString::SkipEmptyParts);
   m_uiForm.lwDataSearchDirs->clear();
   m_uiForm.lwDataSearchDirs->addItems(list);
 
   // Do the same thing for the "pythonscripts.directories" property.
-  directories = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directories")).trimmed();
+  directories = QString::fromStdString(
+                    Mantid::Kernel::ConfigService::Instance().getString(
+                        "pythonscripts.directories")).trimmed();
   list = directories.split(";", QString::SkipEmptyParts);
   m_uiForm.lwUserSearchDirs->clear();
   m_uiForm.lwUserSearchDirs->addItems(list);
 
   // set flag of whether to search the data archive
-  QString archive = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.searcharchive")).trimmed();
-  if ( archive == "On" )
+  QString archive = QString::fromStdString(
+                        Mantid::Kernel::ConfigService::Instance().getString(
+                            "datasearch.searcharchive")).trimmed();
+  if (archive == "On")
     m_uiForm.ckSearchArchive->setChecked(true);
   else
     m_uiForm.ckSearchArchive->setChecked(false);
 
   // default save directory
-  QString saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory")).trimmed();
+  QString saveDir = QString::fromStdString(
+                        Mantid::Kernel::ConfigService::Instance().getString(
+                            "defaultsave.directory")).trimmed();
   m_uiForm.leDefaultSave->setText(saveDir);
 }
-void ManageUserDirectories::saveProperties()
-{
+void ManageUserDirectories::saveProperties() {
   QString newSearchArchive;
   QString newDataDirs;
   QString newUserDirs;
   QString newSaveDir;
 
-  if ( m_uiForm.ckSearchArchive->isChecked() )
+  if (m_uiForm.ckSearchArchive->isChecked())
     newSearchArchive = "On";
   else
     newSearchArchive = "Off";
@@ -79,13 +92,11 @@ void ManageUserDirectories::saveProperties()
   QStringList dataDirs;
   QStringList userDirs;
 
-  for ( int i = 0; i < m_uiForm.lwDataSearchDirs->count(); i++ )
-  {
+  for (int i = 0; i < m_uiForm.lwDataSearchDirs->count(); i++) {
     dataDirs.append(m_uiForm.lwDataSearchDirs->item(i)->text());
   }
 
-  for ( int i = 0; i < m_uiForm.lwUserSearchDirs->count(); i++ )
-  {
+  for (int i = 0; i < m_uiForm.lwUserSearchDirs->count(); i++) {
     userDirs.append(m_uiForm.lwUserSearchDirs->item(i)->text());
   }
 
@@ -97,7 +108,8 @@ void ManageUserDirectories::saveProperties()
   newSaveDir = m_uiForm.leDefaultSave->text();
   newSaveDir.replace('\\', '/');
 
-  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
+  Mantid::Kernel::ConfigServiceImpl &config =
+      Mantid::Kernel::ConfigService::Instance();
 
   config.setString("datasearch.searcharchive", newSearchArchive.toStdString());
   config.setString("datasearch.directories", newDataDirs.toStdString());
@@ -106,139 +118,111 @@ void ManageUserDirectories::saveProperties()
   config.saveConfig(m_userPropFile.toStdString());
 }
 
-QListWidget* ManageUserDirectories::listWidget()
-{
-  if ( m_uiForm.tabWidget->currentWidget() == m_uiForm.tabDataSearch )
-  {
+QListWidget *ManageUserDirectories::listWidget() {
+  if (m_uiForm.tabWidget->currentWidget() == m_uiForm.tabDataSearch) {
     return m_uiForm.lwDataSearchDirs;
-  }
-  else if ( m_uiForm.tabWidget->currentWidget() == m_uiForm.tabPythonDirectories )
-  {
+  } else if (m_uiForm.tabWidget->currentWidget() ==
+             m_uiForm.tabPythonDirectories) {
     return m_uiForm.lwUserSearchDirs;
-  }
-  else
-  {
+  } else {
     return NULL;
   }
 }
 
 // SLOTS
-void ManageUserDirectories::helpClicked()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ManageUserDirectories"));
-}
-void ManageUserDirectories::cancelClicked()
-{
-  this->close();
+void ManageUserDirectories::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/ManageUserDirectories"));
 }
-void ManageUserDirectories::confirmClicked()
-{
+void ManageUserDirectories::cancelClicked() { this->close(); }
+void ManageUserDirectories::confirmClicked() {
   saveProperties();
   this->close();
 }
 
-void ManageUserDirectories::addDirectory()
-{
-  QLineEdit* input(NULL);
-  
-  if ( m_uiForm.tabWidget->currentWidget() == m_uiForm.tabDataSearch )
-  {
+void ManageUserDirectories::addDirectory() {
+  QLineEdit *input(NULL);
+
+  if (m_uiForm.tabWidget->currentWidget() == m_uiForm.tabDataSearch) {
     input = m_uiForm.leDirectoryPath;
-  }
-  else if ( m_uiForm.tabWidget->currentWidget() == m_uiForm.tabPythonDirectories )
-  {
+  } else if (m_uiForm.tabWidget->currentWidget() ==
+             m_uiForm.tabPythonDirectories) {
     input = m_uiForm.leDirectoryPathPython;
   }
 
-  if ( input->text() != "" )
-  {
+  if (input->text() != "") {
     listWidget()->addItem(input->text());
     input->clear();
   }
 }
 
-void ManageUserDirectories::browseToDirectory()
-{
+void ManageUserDirectories::browseToDirectory() {
   QSettings settings;
-  QString lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
+  QString lastDirectory =
+      settings.value("ManageUserSettings/last_directory", "").toString();
 
-  QString newDir = QFileDialog::getExistingDirectory(this,
-    tr("Select New Data Directory"),
-    lastDirectory,
-    QFileDialog::ShowDirsOnly );
+  QString newDir = QFileDialog::getExistingDirectory(
+      this, tr("Select New Data Directory"), lastDirectory,
+      QFileDialog::ShowDirsOnly);
 
-  if ( newDir != "" )
-  {
+  if (newDir != "") {
     settings.setValue("ManageUserSettings/last_directory", newDir);
     listWidget()->addItem(newDir);
   }
-
 }
-void ManageUserDirectories::remDir()
-{
-  QList<QListWidgetItem*> selected = listWidget()->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
+void ManageUserDirectories::remDir() {
+  QList<QListWidgetItem *> selected = listWidget()->selectedItems();
+  for (int i = 0; i < selected.size(); i++) {
     delete selected[i];
   }
 }
-void ManageUserDirectories::moveUp()
-{
-  QListWidget* list = listWidget();
-  QList<QListWidgetItem*> selected = list->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
+void ManageUserDirectories::moveUp() {
+  QListWidget *list = listWidget();
+  QList<QListWidgetItem *> selected = list->selectedItems();
+  for (int i = 0; i < selected.size(); i++) {
     int index = list->row(selected[i]);
-    if ( index != 0 )
-    {
-      QListWidgetItem* move = list->takeItem(index);
-      list->insertItem(index-1, move);
+    if (index != 0) {
+      QListWidgetItem *move = list->takeItem(index);
+      list->insertItem(index - 1, move);
     }
     list->setCurrentItem(selected[i]);
   }
 }
-void ManageUserDirectories::moveDown()
-{
-  QListWidget* list = listWidget();
+void ManageUserDirectories::moveDown() {
+  QListWidget *list = listWidget();
   int count = list->count();
-  QList<QListWidgetItem*> selected = list->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
+  QList<QListWidgetItem *> selected = list->selectedItems();
+  for (int i = 0; i < selected.size(); i++) {
     int index = list->row(selected[i]);
-    if ( index != ( count - 1 ) )
-    {
-      QListWidgetItem* move = list->takeItem(index);
-      list->insertItem(index+1, move);
+    if (index != (count - 1)) {
+      QListWidgetItem *move = list->takeItem(index);
+      list->insertItem(index + 1, move);
     }
     list->setCurrentItem(selected[i]);
   }
 }
-void ManageUserDirectories::selectSaveDir()
-{
+void ManageUserDirectories::selectSaveDir() {
   QSettings settings;
   QString lastDirectory = m_uiForm.leDefaultSave->text();
-  if ( lastDirectory.trimmed() == "" )
-    lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
+  if (lastDirectory.trimmed() == "")
+    lastDirectory =
+        settings.value("ManageUserSettings/last_directory", "").toString();
 
-  const QString newDir = QFileDialog::getExistingDirectory(this,
-    tr("Select New Default Save Directory"),
-    lastDirectory,
-    QFileDialog::ShowDirsOnly );
+  const QString newDir = QFileDialog::getExistingDirectory(
+      this, tr("Select New Default Save Directory"), lastDirectory,
+      QFileDialog::ShowDirsOnly);
 
-  if ( newDir != "" )
-  {
+  if (newDir != "") {
     QString path = newDir + QDir::separator();
     path.replace('\\', '/');
-    settings.setValue("ManageUserSettings/last_directory", path );
+    settings.setValue("ManageUserSettings/last_directory", path);
     m_uiForm.leDefaultSave->setText(path);
   }
-
 }
 /** Opens a manage directories dialog and gives it focus
 *  @param parent :: the parent window, probably the window that called it
 */
-void ManageUserDirectories::openUserDirsDialog(QWidget * parent)
-{
+void ManageUserDirectories::openUserDirsDialog(QWidget *parent) {
   ManageUserDirectories *ad = new ManageUserDirectories(parent);
   ad->show();
   ad->setFocus();
diff --git a/MantidQt/API/src/MantidColorMap.cpp b/MantidQt/API/src/MantidColorMap.cpp
index 9d857c3a000da22b3a7a2f26889690b75fa01e5a..fd56d07761f0f64672ebfe31cc195ae49fb539a1 100644
--- a/MantidQt/API/src/MantidColorMap.cpp
+++ b/MantidQt/API/src/MantidColorMap.cpp
@@ -19,10 +19,10 @@
 
 using Mantid::Kernel::ConfigService;
 
-namespace
-{
-  // Log(0) -> inf. Any values less than this cutoff will get set to 1 before the log is taken
-  const double LOG_ZERO_CUTOFF = 1e-15;
+namespace {
+// Log(0) -> inf. Any values less than this cutoff will get set to 1 before the
+// log is taken
+const double LOG_ZERO_CUTOFF = 1e-15;
 }
 
 //--------------------------------------
@@ -31,11 +31,11 @@ namespace
 /**
  * Default
  */
-MantidColorMap::MantidColorMap() : QwtColorMap(QwtColorMap::Indexed), m_scale_type(GraphOptions::Log10),
-				     m_colors(0), m_num_colors(0), m_name(), m_path(), m_nth_power(2.0)
-{
+MantidColorMap::MantidColorMap()
+    : QwtColorMap(QwtColorMap::Indexed), m_scale_type(GraphOptions::Log10),
+      m_colors(0), m_num_colors(0), m_name(), m_path(), m_nth_power(2.0) {
   m_nan = std::numeric_limits<double>::quiet_NaN();
-  this->setNanColor(255,255,255);
+  this->setNanColor(255, 255, 255);
   setupDefaultMap();
 }
 
@@ -45,15 +45,14 @@ MantidColorMap::MantidColorMap() : QwtColorMap(QwtColorMap::Indexed), m_scale_ty
  * @param filename :: color map file to load
  * @param type :: The scale type
  */
-MantidColorMap::MantidColorMap(const QString & filename, GraphOptions::ScaleType type) : 
-  QwtColorMap(QwtColorMap::Indexed), m_scale_type(type), m_colors(0), m_num_colors(0),
-  m_name(), m_path(), m_nth_power(2.0)
-{
+MantidColorMap::MantidColorMap(const QString &filename,
+                               GraphOptions::ScaleType type)
+    : QwtColorMap(QwtColorMap::Indexed), m_scale_type(type), m_colors(0),
+      m_num_colors(0), m_name(), m_path(), m_nth_power(2.0) {
   m_nan = std::numeric_limits<double>::quiet_NaN();
-  this->setNanColor(255,255,255);
+  this->setNanColor(255, 255, 255);
   // Check and load default if this doesn't work
-  if( !loadMap(filename) )
-  {
+  if (!loadMap(filename)) {
     setupDefaultMap();
   }
 }
@@ -62,16 +61,13 @@ MantidColorMap::MantidColorMap(const QString & filename, GraphOptions::ScaleType
 /**
  * Destructor
  */
-MantidColorMap::~MantidColorMap()
-{
-}
+MantidColorMap::~MantidColorMap() {}
 
 //-------------------------------------------------------------------------------------------------
 /**
  * Create a clone of the color map
  */
-QwtColorMap* MantidColorMap::copy() const
-{
+QwtColorMap *MantidColorMap::copy() const {
   MantidColorMap *map = new MantidColorMap;
   *map = *this;
 
@@ -83,9 +79,8 @@ QwtColorMap* MantidColorMap::copy() const
  * Change the scale type
  * @param type :: The new scale type
  */
-void MantidColorMap::changeScaleType(GraphOptions::ScaleType type)
-{
-    m_scale_type = type;
+void MantidColorMap::changeScaleType(GraphOptions::ScaleType type) {
+  m_scale_type = type;
 }
 
 //-------------------------------------------------------------------------------------------------
@@ -93,12 +88,12 @@ void MantidColorMap::changeScaleType(GraphOptions::ScaleType type)
  * Load a color map from a file
  * @param filename :: The full path to the color map file
  */
-bool MantidColorMap::loadMap(const QString & filename)
-{
-  std::ifstream cmapfile(filename.toStdString().c_str(),std::ios::in);
-  if( !cmapfile.is_open() ) return false;
+bool MantidColorMap::loadMap(const QString &filename) {
+  std::ifstream cmapfile(filename.toStdString().c_str(), std::ios::in);
+  if (!cmapfile.is_open())
+    return false;
 
-  // Reading directly to the color store will mean that if the file is corrupt 
+  // Reading directly to the color store will mean that if the file is corrupt
   // at some point then I can't revert to my previous map. Using a QVector means
   // that copying the data at the end is not an expensive operation
   QVector<QRgb> new_colormap;
@@ -108,36 +103,32 @@ bool MantidColorMap::loadMap(const QString & filename)
   std::string line;
   short count(0);
   bool is_success(true);
-  while ( std::getline(cmapfile, line) )
-  {
-    if(line.empty() || count == getLargestAllowedCIndex() + 1 ) break;
+  while (std::getline(cmapfile, line)) {
+    if (line.empty() || count == getLargestAllowedCIndex() + 1)
+      break;
     std::stringstream reader(line);
     reader >> red >> green >> blue;
-    if( reader )
-    {
-      new_colormap.push_back(qRgb((unsigned char)(red), (unsigned char)green, (unsigned char)blue));
+    if (reader) {
+      new_colormap.push_back(qRgb((unsigned char)(red), (unsigned char)green,
+                                  (unsigned char)blue));
       ++count;
-    }
-    else 
-    {
+    } else {
       is_success = false;
       break;
     }
-
   }
   cmapfile.close();
 
-  if( is_success )
-  {
+  if (is_success) {
     m_num_colors = count;
     m_colors = new_colormap;
     if (m_num_colors > 1)
       m_colors[0] = m_nan_color;
     m_path = filename;
-    //set the name of the color map to the filename
+    // set the name of the color map to the filename
     QFileInfo fileinfo(filename);
-    m_name=fileinfo.baseName(); 
-  } 
+    m_name = fileinfo.baseName();
+  }
 
   return is_success;
 }
@@ -150,21 +141,19 @@ bool MantidColorMap::loadMap(const QString & filename)
  * @param parent :: widget owner of the dialog
  * @return QString of the filename
  */
-QString MantidColorMap::loadMapDialog(QString previousFile, QWidget * parent)
-{
+QString MantidColorMap::loadMapDialog(QString previousFile, QWidget *parent) {
   QString fileselection;
   // Get the installed color maps directory.
-  QString colormapdir = QString::fromStdString( ConfigService::Instance().getString("colormaps.directory") );
+  QString colormapdir = QString::fromStdString(
+      ConfigService::Instance().getString("colormaps.directory"));
   if (colormapdir.isEmpty())
     colormapdir = QFileInfo(previousFile).absoluteFilePath();
   // Ask the user to point to the .map file
-  fileselection = QFileDialog::getOpenFileName(parent, "Pick a Colormap",
-      colormapdir, "Colormaps (*.map *.MAP)");
+  fileselection = QFileDialog::getOpenFileName(
+      parent, "Pick a Colormap", colormapdir, "Colormaps (*.map *.MAP)");
   return fileselection;
 }
 
-
-
 //-------------------------------------------------------------------------------------------------
 /** Set a color for Not-a-number
  *
@@ -172,9 +161,8 @@ QString MantidColorMap::loadMapDialog(QString previousFile, QWidget * parent)
  * @param g :: green, from 0 to 255
  * @param b :: blue, from 0 to 255
  */
-void MantidColorMap::setNanColor(int r, int g, int b)
-{
-  m_nan_color = qRgb(r,g,b);
+void MantidColorMap::setNanColor(int r, int g, int b) {
+  m_nan_color = qRgb(r, g, b);
   if (m_num_colors > 1)
     m_colors[0] = m_nan_color;
 }
@@ -183,36 +171,61 @@ void MantidColorMap::setNanColor(int r, int g, int b)
 /**
  * Define a default color map to be used if a file is unavailable.
  */
-void MantidColorMap::setupDefaultMap()
-{
-  // The __default map distrubuted with qtiplot is the default and putting this into a string with an @ separator was the
-  // easiest way to construct it as it doesn't have a regular pattern so a loop wouldn't work.
-  std::string colorstring = 
-    "0 172 252@0 170 252@0 168 252@0 164 252@0 160 252@0 156 252@0 152 252@0 152 252@0 148 252@0 144 252@0 140 252@0 136 252"
-    "@0 132 252@0 132 252@0 128 252@0 124 252@0 120 252@0 116 252@0 112 252@0 112 252@0 108 252@0 104 252@0 100 252@0  96 252"
-    "@0  92 252@0  92 252@0  88 252@0  84 252@0  80 252@0  76 252@0  72 252@0  68 252@0  64 252@0  60 252@0  56 252@0  52 252"
-    "@0  48 252@0  44 252@0  40 252@0  36 252@0  32 252@0  28 252@0  24 252@0  20 252@0  16 252@0  12 252@0   8 252@0   4 252"
-    "@0   4 252@4   4 248@4   4 248@8   4 244@8   8 240@12   8 240@12   8 236@16   8 232@16  12 232@20  12 228@20  12 224"
-    "@24  12 224@24  16 220@28  16 216@28  16 216@32  16 212@32  20 212@36  20 208@36  20 204@40  20 204@40  24 200@44  24 196"
-    "@44  24 196@48  24 192@48  24 188@52  28 188@52  28 184@56  28 180@56  28 180@60  32 176@60  32 172@64  32 172@64  32 168"
-    "@68  36 168@68  36 164@72  36 160@72  36 160@76  40 156@76  40 152@80  40 152@80  40 148@84  44 144@84  44 144@88  44 140"
-    "@88  44 136@92  48 136@92  48 132@96  48 128@100  48 128@100  48 124@104  52 124@104  52 120@108  52 116@108  52 116"
-    "@112  56 112@112  56 108@116  56 108@116  56 104@120  60 100@120  60 100@124  60  96@124  60  92@128  64  92@128  64  88"
-    "@132  64  88@132  64  84@136  68  80@136  68  80@140  68  76@140  68  72@144  72  72@144  72  68@148  72  64@148  72  64"
-    "@152  72  60@152  76  56@156  76  56@156  76  52@160  76  48@160  80  48@164  80  44@164  80  44@168  80  40@168  84  36"
-    "@172  84  36@172  84  32@176  84  28@176  88  28@180  88  24@180  88  20@184  88  20@184  92  16@188  92  12@188  92  12"
-    "@192  92   8@196  96   4@196  96   4@196 100   4@196 100   4@196 104   4@200 108   4@200 108   4@200 112   4@200 112   4"
-    "@200 116   4@204 120   4@204 120   4@204 124   4@204 124   4@208 128   4@208 132   4@208 132   4@208 136   4@208 136   4"
-    "@212 140   4@212 144   4@212 144   4@212 148   4@216 152   4@216 152   4@216 156   4@216 156   4@216 160   4@220 164   4"
-    "@220 164   4@220 168   4@220 168   4@224 172   4@224 176   4@224 176   4@224 180   4@224 180   4@228 184   4@228 188   4"
-    "@228 188   4@228 192   4@228 192   4@232 196   4@232 200   4@232 200   4@232 204   4@236 208   4@236 208   4@236 212   4"
-    "@236 212   4@236 216   4@240 220   4@240 220   4@240 224   4@240 224   4@244 228   4@244 232   4@244 232   4@244 236   4"
-    "@244 236   4@248 240   4@248 244   4@248 244   4@248 248   4@252 252   0@252 252 104@252 252 104@252 252 108@252 252 112"
-    "@252 252 116@252 252 120@252 252 120@252 252 124@252 252 128@252 252 132@252 252 136@252 252 136@252 252 140@252 252 144"
-    "@252 252 148@252 252 152@252 252 152@252 252 156@252 252 160@252 252 164@252 252 168@252 252 168@252 252 172@252 252 176"
-    "@252 252 180@252 252 184@252 252 184@252 252 188@252 252 192@252 252 196@252 252 200@252 252 200@252 252 204@252 252 208"
-    "@252 252 212@252 252 216@252 252 216@252 252 220@252 252 224@252 252 228@252 252 232@252 252 232@252 252 236@252 252 240"
-    "@252 252 244@252 252 248@252 252 252@255 255 255@";
+void MantidColorMap::setupDefaultMap() {
+  // The __default map distrubuted with qtiplot is the default and putting this
+  // into a string with an @ separator was the
+  // easiest way to construct it as it doesn't have a regular pattern so a loop
+  // wouldn't work.
+  std::string colorstring =
+      "0 172 252@0 170 252@0 168 252@0 164 252@0 160 252@0 156 252@0 152 252@0 "
+      "152 252@0 148 252@0 144 252@0 140 252@0 136 252"
+      "@0 132 252@0 132 252@0 128 252@0 124 252@0 120 252@0 116 252@0 112 "
+      "252@0 112 252@0 108 252@0 104 252@0 100 252@0  96 252"
+      "@0  92 252@0  92 252@0  88 252@0  84 252@0  80 252@0  76 252@0  72 "
+      "252@0  68 252@0  64 252@0  60 252@0  56 252@0  52 252"
+      "@0  48 252@0  44 252@0  40 252@0  36 252@0  32 252@0  28 252@0  24 "
+      "252@0  20 252@0  16 252@0  12 252@0   8 252@0   4 252"
+      "@0   4 252@4   4 248@4   4 248@8   4 244@8   8 240@12   8 240@12   8 "
+      "236@16   8 232@16  12 232@20  12 228@20  12 224"
+      "@24  12 224@24  16 220@28  16 216@28  16 216@32  16 212@32  20 212@36  "
+      "20 208@36  20 204@40  20 204@40  24 200@44  24 196"
+      "@44  24 196@48  24 192@48  24 188@52  28 188@52  28 184@56  28 180@56  "
+      "28 180@60  32 176@60  32 172@64  32 172@64  32 168"
+      "@68  36 168@68  36 164@72  36 160@72  36 160@76  40 156@76  40 152@80  "
+      "40 152@80  40 148@84  44 144@84  44 144@88  44 140"
+      "@88  44 136@92  48 136@92  48 132@96  48 128@100  48 128@100  48 "
+      "124@104  52 124@104  52 120@108  52 116@108  52 116"
+      "@112  56 112@112  56 108@116  56 108@116  56 104@120  60 100@120  60 "
+      "100@124  60  96@124  60  92@128  64  92@128  64  88"
+      "@132  64  88@132  64  84@136  68  80@136  68  80@140  68  76@140  68  "
+      "72@144  72  72@144  72  68@148  72  64@148  72  64"
+      "@152  72  60@152  76  56@156  76  56@156  76  52@160  76  48@160  80  "
+      "48@164  80  44@164  80  44@168  80  40@168  84  36"
+      "@172  84  36@172  84  32@176  84  28@176  88  28@180  88  24@180  88  "
+      "20@184  88  20@184  92  16@188  92  12@188  92  12"
+      "@192  92   8@196  96   4@196  96   4@196 100   4@196 100   4@196 104   "
+      "4@200 108   4@200 108   4@200 112   4@200 112   4"
+      "@200 116   4@204 120   4@204 120   4@204 124   4@204 124   4@208 128   "
+      "4@208 132   4@208 132   4@208 136   4@208 136   4"
+      "@212 140   4@212 144   4@212 144   4@212 148   4@216 152   4@216 152   "
+      "4@216 156   4@216 156   4@216 160   4@220 164   4"
+      "@220 164   4@220 168   4@220 168   4@224 172   4@224 176   4@224 176   "
+      "4@224 180   4@224 180   4@228 184   4@228 188   4"
+      "@228 188   4@228 192   4@228 192   4@232 196   4@232 200   4@232 200   "
+      "4@232 204   4@236 208   4@236 208   4@236 212   4"
+      "@236 212   4@236 216   4@240 220   4@240 220   4@240 224   4@240 224   "
+      "4@244 228   4@244 232   4@244 232   4@244 236   4"
+      "@244 236   4@248 240   4@248 244   4@248 244   4@248 248   4@252 252   "
+      "0@252 252 104@252 252 104@252 252 108@252 252 112"
+      "@252 252 116@252 252 120@252 252 120@252 252 124@252 252 128@252 252 "
+      "132@252 252 136@252 252 136@252 252 140@252 252 144"
+      "@252 252 148@252 252 152@252 252 152@252 252 156@252 252 160@252 252 "
+      "164@252 252 168@252 252 168@252 252 172@252 252 176"
+      "@252 252 180@252 252 184@252 252 184@252 252 188@252 252 192@252 252 "
+      "196@252 252 200@252 252 200@252 252 204@252 252 208"
+      "@252 252 212@252 252 216@252 252 216@252 252 220@252 252 224@252 252 "
+      "228@252 252 232@252 252 232@252 252 236@252 252 240"
+      "@252 252 244@252 252 248@252 252 252@255 255 255@";
 
   m_colors.clear();
   m_num_colors = 256;
@@ -222,17 +235,16 @@ void MantidColorMap::setupDefaultMap()
   float red(0.0f), green(0.0f), blue(0.0f);
   std::string line;
 
-  while ( std::getline(colorstream, line, '@') )
-  {
+  while (std::getline(colorstream, line, '@')) {
     std::stringstream reader(line);
     reader >> red >> green >> blue;
-    m_colors.push_back(qRgb((unsigned char)(red), (unsigned char)green, (unsigned char)blue));
+    m_colors.push_back(
+        qRgb((unsigned char)(red), (unsigned char)green, (unsigned char)blue));
   }
 
-  this->setNanColor(255,255,255);
+  this->setNanColor(255, 255, 255);
 }
 
-
 //-------------------------------------------------------------------------------------------------
 /**
  * Normalize the value to the range[0,1]
@@ -240,62 +252,55 @@ void MantidColorMap::setupDefaultMap()
  * @param value :: The data value
  * @returns The fraction along the given interval using the current scale type
  */
-double MantidColorMap::normalize(const QwtDoubleInterval &interval, double value) const
-{
+double MantidColorMap::normalize(const QwtDoubleInterval &interval,
+                                 double value) const {
   // nan numbers have the property that nan != nan, treat nan as being invalid
-  if( interval.isNull() || m_num_colors == 0 || boost::math::isnan(value) )
+  if (interval.isNull() || m_num_colors == 0 || boost::math::isnan(value))
     return m_nan;
 
   const double width = interval.width();
-  if( width <= 0.0 || value <= interval.minValue() )
+  if (width <= 0.0 || value <= interval.minValue())
     return 0.0;
 
-  if ( value >= interval.maxValue())
+  if (value >= interval.maxValue())
     return 1.0;
 
   double ratio(0.0);
-  if( m_scale_type == GraphOptions::Linear)
-  {
+  if (m_scale_type == GraphOptions::Linear) {
     ratio = (value - interval.minValue()) / width;
-  }
-  else if (m_scale_type == GraphOptions::Power)
-  {
+  } else if (m_scale_type == GraphOptions::Power) {
     ratio = (pow(value, m_nth_power) - pow(interval.minValue(), m_nth_power)) /
-            (pow(interval.maxValue(), m_nth_power) - pow(interval.minValue(), m_nth_power));
-  }
-  else
-  {
+            (pow(interval.maxValue(), m_nth_power) -
+             pow(interval.minValue(), m_nth_power));
+  } else {
     // Assume log10 type
     // Have to deal with the possibility that a user has entered 0 as a minimum
     double minValue = interval.minValue();
-    if( minValue < LOG_ZERO_CUTOFF )
-    {
+    if (minValue < LOG_ZERO_CUTOFF) {
       minValue = 1.0;
     }
-    ratio = std::log10(value/minValue)/std::log10(interval.maxValue()/minValue);
+    ratio = std::log10(value / minValue) /
+            std::log10(interval.maxValue() / minValue);
   }
   return ratio;
 }
 
-
 //-------------------------------------------------------------------------------------------------
 /**
  * Compute an rgb value for the given data value and interval
  * @param interval :: The data range
  * @param value :: Compute an RGB color for this data value
  */
-QRgb MantidColorMap::rgb(const QwtDoubleInterval & interval, double value) const
-{
+QRgb MantidColorMap::rgb(const QwtDoubleInterval &interval,
+                         double value) const {
   short ci = static_cast<short>(colorIndex(interval, value));
-  if( ci >= 0 && ci < m_num_colors )
-  {
+  if (ci >= 0 && ci < m_num_colors) {
     return m_colors[ci];
   }
   // Return black
   return QRgb();
 }
 
-
 //-------------------------------------------------------------------------------------------------
 /**
  * Compute a color index
@@ -304,28 +309,27 @@ QRgb MantidColorMap::rgb(const QwtDoubleInterval & interval, double value) const
  * @returns A color index as an unsigned character
  */
 
-unsigned char MantidColorMap::colorIndex (const QwtDoubleInterval &interval, double value) const
-{
+unsigned char MantidColorMap::colorIndex(const QwtDoubleInterval &interval,
+                                         double value) const {
   double fraction = normalize(interval, value);
   // NAN: return index 0
-  if (fraction != fraction) return static_cast<unsigned char>(0);
+  if (fraction != fraction)
+    return static_cast<unsigned char>(0);
   // Below minimum: return index 1
-  if( fraction < 0.0 ) return static_cast<unsigned char>(1);
+  if (fraction < 0.0)
+    return static_cast<unsigned char>(1);
 
   short index = short(std::floor(fraction * m_num_colors));
   // If the ratio gives back 1 then we need to adjust the index down 1
-  if( index >= m_num_colors )
-  {
+  if (index >= m_num_colors) {
     index = short(m_num_colors - 1);
   }
-  if( index < 1 )
-  {
+  if (index < 1) {
     index = 1;
   }
   return static_cast<unsigned char>(index);
 }
 
-
 //-------------------------------------------------------------------------------------------------
 /**
  * Compute a lookup table
@@ -333,27 +337,24 @@ unsigned char MantidColorMap::colorIndex (const QwtDoubleInterval &interval, dou
  * @param interval :: The interval of values of the RGB component for
  * the table to cover
  */
-QVector<QRgb> MantidColorMap::colorTable(const QwtDoubleInterval & interval) const
-{
+QVector<QRgb>
+MantidColorMap::colorTable(const QwtDoubleInterval &interval) const {
   // Swicth to linear scaling when computing the lookup table
-  GraphOptions::ScaleType current_type = m_scale_type;   
+  GraphOptions::ScaleType current_type = m_scale_type;
   m_scale_type = GraphOptions::Linear;
 
   short table_size = (m_num_colors > 1) ? m_num_colors : 2;
-  QVector<QRgb> rgbtable(table_size+1);
-  if( interval.isValid() )
-  {
+  QVector<QRgb> rgbtable(table_size + 1);
+  if (interval.isValid()) {
     const double step = interval.width() / table_size;
-    for( short i = 0; i < table_size; ++i )
-    {
-      rgbtable[i+1] = rgb(interval, interval.minValue() + step*i);
+    for (short i = 0; i < table_size; ++i) {
+      rgbtable[i + 1] = rgb(interval, interval.minValue() + step * i);
     }
     // Special NAN at index 0
     rgbtable[0] = rgb(interval, m_nan);
   }
-  
-  //Restore scaling type
+
+  // Restore scaling type
   m_scale_type = current_type;
   return rgbtable;
 }
-
diff --git a/MantidQt/API/src/MantidDialog.cpp b/MantidQt/API/src/MantidDialog.cpp
index 9ae45fdd1ec2c0d443c7f4635fffb918acf6cbeb..7cf8ac4ef9a099e8636bc773adfdb67de1534378 100644
--- a/MantidQt/API/src/MantidDialog.cpp
+++ b/MantidQt/API/src/MantidDialog.cpp
@@ -13,57 +13,53 @@ using namespace MantidQt::API;
 /**
  * Default Constructor
  */
-MantidDialog::MantidDialog(QWidget* parent):QDialog(parent), m_pyRunner()
-{
-  // re-emit the run Python code from m_pyRunner, to work this signal must reach the slot in QtiPlot
-  connect(&m_pyRunner, SIGNAL(runAsPythonScript(const QString&, bool)),
-    this, SIGNAL(runAsPythonScript(const QString&, bool)));
+MantidDialog::MantidDialog(QWidget *parent) : QDialog(parent), m_pyRunner() {
+  // re-emit the run Python code from m_pyRunner, to work this signal must reach
+  // the slot in QtiPlot
+  connect(&m_pyRunner, SIGNAL(runAsPythonScript(const QString &, bool)), this,
+          SIGNAL(runAsPythonScript(const QString &, bool)));
 }
 
 /**
  * Destructor
  */
-MantidDialog::~MantidDialog()
-{
-}
+MantidDialog::~MantidDialog() {}
 
 /**
- *   Checks if receiver derives from MantidDialog. If it does calls the virtual handleException method.
+ *   Checks if receiver derives from MantidDialog. If it does calls the virtual
+ * handleException method.
  *   @param receiver :: The Qt event receiver
  *   @param e :: The exception
  *   @return True if the exception was handled, false otherwise.
  */
-bool MantidDialog::handle( QObject* receiver, const std::exception& e )
-{
-    QObject* obj = receiver;
-    while(obj)
-    {
-        if (obj->inherits("MantidQt::API::MantidDialog"))
-        {
-            qobject_cast<MantidDialog*>(obj)->handleException(e);
-            return true;
-        }
-        obj = obj->parent();
-    };
-    return false;
+bool MantidDialog::handle(QObject *receiver, const std::exception &e) {
+  QObject *obj = receiver;
+  while (obj) {
+    if (obj->inherits("MantidQt::API::MantidDialog")) {
+      qobject_cast<MantidDialog *>(obj)->handleException(e);
+      return true;
+    }
+    obj = obj->parent();
+  };
+  return false;
 }
 
 /** Override this method to handle an exception in a derived class.
  *  @param e :: exception to handle
  */
-void MantidDialog::handleException( const std::exception& e )
-{
-    QMessageBox::critical(qobject_cast<QWidget*>(parent()),"Mantid - Error",
-        "Exception is caught in dialog:\n\n"+QString::fromStdString(e.what()));
-    close();
+void MantidDialog::handleException(const std::exception &e) {
+  QMessageBox::critical(qobject_cast<QWidget *>(parent()), "Mantid - Error",
+                        "Exception is caught in dialog:\n\n" +
+                            QString::fromStdString(e.what()));
+  close();
 }
 
 /** Run a piece of python code and return any output that it writes to stdout
 *  @param code :: the Python commands to execute
-*  @param no_output :: if set to true this method returns an empty string, if false it returns the output from any Python print statements
+*  @param no_output :: if set to true this method returns an empty string, if
+* false it returns the output from any Python print statements
 *  @return output from Python print statements unless no_output is false
 */
-QString MantidDialog::runPythonCode(const QString & code, bool no_output)
-{
+QString MantidDialog::runPythonCode(const QString &code, bool no_output) {
   return m_pyRunner.runPythonCode(code, no_output);
 }
diff --git a/MantidQt/API/src/MantidHelpInterface.cpp b/MantidQt/API/src/MantidHelpInterface.cpp
index c5d67b0569f1ded10fa2a60a33e6df3da56d4325..7aaeed94820dafbe47df926adb6a54fad4c21051 100644
--- a/MantidQt/API/src/MantidHelpInterface.cpp
+++ b/MantidQt/API/src/MantidHelpInterface.cpp
@@ -5,78 +5,56 @@
 using namespace MantidQt::API;
 using std::string;
 
-MantidHelpInterface::MantidHelpInterface()
-{}
+MantidHelpInterface::MantidHelpInterface() {}
 
-MantidHelpInterface::~MantidHelpInterface()
-{}
+MantidHelpInterface::~MantidHelpInterface() {}
 
-void MantidHelpInterface::showPage(const std::string & url)
-{
-  UNUSED_ARG(url);
-}
+void MantidHelpInterface::showPage(const std::string &url) { UNUSED_ARG(url); }
 
-void MantidHelpInterface::showPage(const QString & url)
-{
-  UNUSED_ARG(url);
-}
+void MantidHelpInterface::showPage(const QString &url) { UNUSED_ARG(url); }
 
-void MantidHelpInterface::showPage(const QUrl & url)
-{
-  UNUSED_ARG(url);
-}
+void MantidHelpInterface::showPage(const QUrl &url) { UNUSED_ARG(url); }
 
-void MantidHelpInterface::showWikiPage(const std::string &page)
-{
+void MantidHelpInterface::showWikiPage(const std::string &page) {
   UNUSED_ARG(page);
 }
 
-void MantidHelpInterface::showWikiPage(const QString &page)
-{
+void MantidHelpInterface::showWikiPage(const QString &page) {
   UNUSED_ARG(page);
 }
 
-void MantidHelpInterface::showConcept(const std::string &page)
-{
+void MantidHelpInterface::showConcept(const std::string &page) {
   UNUSED_ARG(page);
 }
 
-void MantidHelpInterface::showConcept(const QString &page)
-{
-  UNUSED_ARG(page);
-}
+void MantidHelpInterface::showConcept(const QString &page) { UNUSED_ARG(page); }
 
-void MantidHelpInterface::showAlgorithm(const std::string &name, const int version)
-{
+void MantidHelpInterface::showAlgorithm(const std::string &name,
+                                        const int version) {
   UNUSED_ARG(name);
   UNUSED_ARG(version);
 }
 
-void MantidHelpInterface::showAlgorithm(const QString &name, const int version)
-{
+void MantidHelpInterface::showAlgorithm(const QString &name,
+                                        const int version) {
   UNUSED_ARG(name);
-  UNUSED_ARG(version); }
+  UNUSED_ARG(version);
+}
 
-void MantidHelpInterface::showFitFunction(const std::string &name)
-{
+void MantidHelpInterface::showFitFunction(const std::string &name) {
   UNUSED_ARG(name);
 }
 
-void MantidHelpInterface::showFitFunction(const QString &name)
-{
+void MantidHelpInterface::showFitFunction(const QString &name) {
   UNUSED_ARG(name);
 }
 
-void MantidHelpInterface::showCustomInterface(const std::string &name)
-{
+void MantidHelpInterface::showCustomInterface(const std::string &name) {
   UNUSED_ARG(name);
 }
 
-void MantidHelpInterface::showCustomInterface(const QString &name)
-{
+void MantidHelpInterface::showCustomInterface(const QString &name) {
   UNUSED_ARG(name);
 }
 
-void MantidHelpInterface::shutdown()
-{
-}
+void MantidHelpInterface::shutdown() {}
diff --git a/MantidQt/API/src/MantidWidget.cpp b/MantidQt/API/src/MantidWidget.cpp
index 667e841662845e96112b947ad237c9b2edba16e1..4edd183c777bb6bd9fb52516d1dc8068ce0d3d0f 100644
--- a/MantidQt/API/src/MantidWidget.cpp
+++ b/MantidQt/API/src/MantidWidget.cpp
@@ -7,19 +7,19 @@ using namespace MantidQt::API;
 * Default constructor
 * @param parent :: The parent widget
 */
-MantidWidget::MantidWidget(QWidget *parent) : QWidget(parent), m_pyRunner()
-{
-  // re-emit the run Python code from m_pyRunner, to work this signal must reach the slot in QtiPlot
-  connect(&m_pyRunner, SIGNAL(runAsPythonScript(const QString&, bool)),
-    this, SIGNAL(runAsPythonScript(const QString&, bool)));
+MantidWidget::MantidWidget(QWidget *parent) : QWidget(parent), m_pyRunner() {
+  // re-emit the run Python code from m_pyRunner, to work this signal must reach
+  // the slot in QtiPlot
+  connect(&m_pyRunner, SIGNAL(runAsPythonScript(const QString &, bool)), this,
+          SIGNAL(runAsPythonScript(const QString &, bool)));
 }
 
 /** Run a piece of python code and return any output that it writes to stdout
 *  @param code :: the Python commands to execute
-*  @param no_output :: if set to true this method returns an empty string, if false it returns the output from any Python print statements
+*  @param no_output :: if set to true this method returns an empty string, if
+* false it returns the output from any Python print statements
 *  @return output from Python print statements unless no_output is false
 */
-QString MantidWidget::runPythonCode(const QString & code, bool no_output)
-{
+QString MantidWidget::runPythonCode(const QString &code, bool no_output) {
   return m_pyRunner.runPythonCode(code, no_output);
 }
diff --git a/MantidQt/API/src/MdConstants.cpp b/MantidQt/API/src/MdConstants.cpp
index e773a253dce6b986774a3dc0c8e77203c533166c..5b3fb015b9269e6b8b9abf7c1b47ef1a125e4e72 100644
--- a/MantidQt/API/src/MdConstants.cpp
+++ b/MantidQt/API/src/MdConstants.cpp
@@ -4,154 +4,130 @@
 #include <QStringList>
 #include <QColor>
 
-namespace MantidQt
-{
-  namespace API
-  {
-    // Specifiers for ParaView filters
-    const QString MdConstants::MantidParaViewSplatterPlot = "MantidParaViewSplatterPlot";
-    const QString MdConstants::MantidParaViewSpecialCoordinates = "SpecialCoordinates";
-    const QString MdConstants::MDPeaksFilter = "MDPeaksFilter";
-    const QString MdConstants::MantidParaViewPeaksFilter = "MantidParaViewPeaksFilter";
-    const QString MdConstants::PeakDimensions = "Peak Dimensions";
-    const QString MdConstants::PeaksWorkspace = "PeaksWorkspace";
-    const QString MdConstants::Delimiter = "Delimiter";
-    const QString MdConstants::WorkspaceName = "WorkspaceName";
-    const QString MdConstants::ProbePoint = "ProbePoint";
-    const QString MdConstants::Threshold = "Threshold";
-
-    MdConstants::MdConstants() : m_colorScaleStandardMax(0.1), m_logScaleDefaultValue(0.1)
-    {
-      initializeSettingsConstants();
-      initializeViewConstants();
-    }
-
-    MdConstants::~MdConstants(){}
-
-    void MdConstants::initializeSettingsConstants()
-    {
-      // General MD Color Map
-      m_generalMdColorMap = "ColdFire";
-
-      // Background color
-      m_defaultBackgroundColor = QColor(84,89,109);
-
-      // Populate the optional color maps
-      m_vsiColorMaps.append("Viridis (matplotlib)");
-      m_vsiColorMaps.append("Cool to Warm");
-      m_vsiColorMaps.append("Blue to Red Rainbow");
-      m_vsiColorMaps.append("Red to Blue Rainbow");
-      m_vsiColorMaps.append("Grayscale");
-      m_vsiColorMaps.append("X Ray");
-      m_vsiColorMaps.append("Blue to Yellow");
-    }
-
-    void MdConstants::initializeViewConstants()
-    {
-      m_techniqueDependence = "Technique-Dependent";
-      m_standardView = "Standard";
-      m_multiSliceView = "Multi Slice";
-      m_threeSliceView = "Three Slice";
-      m_splatterPlotView = "Splatter Plot";
-    }
-
-    /**
-     * Gets the general MD color map.
-     *@returns The general MD color map.
-     */
-    QString MdConstants::getGeneralMdColorMap() const
-    {
-      return m_generalMdColorMap;
-    }
-
-    /**
-     * Gets the label for the background color.
-     *@returns The label for the background color.
-     */
-    QColor MdConstants::getDefaultBackgroundColor() const
-    {
-      return m_defaultBackgroundColor;
-    }
-
-    /**
-     * Gets a list of VSI color maps.
-     *@returns The list of VSI color maps.
-     */
-    QStringList MdConstants::getVsiColorMaps() const
-    {
-      return m_vsiColorMaps;
-    }
-
-    /**
-     * Get the standard view.
-     *@returns The standard view in the VSI.
-     */
-    QString MdConstants::getStandardView() const
-    {
-      return m_standardView;
-    }
-
-     /**
-     * Get the multi slice view.
-     *@returns The multi slice view in the VSI.
-     */
-    QString MdConstants::getMultiSliceView() const
-    {
-      return m_multiSliceView;
-    }
-
-     /**
-     * Get the three slice view.
-     *@returns The three slice view in the VSI.
-     */
-    QString MdConstants::getThreeSliceView() const
-    {
-      return m_threeSliceView;
-    }
-
-     /**
-     * Get the splatter plot view.
-     *@returns The splatter plot view in the VSI.
-     */
-    QString MdConstants::getSplatterPlotView() const
-    {
-      return m_splatterPlotView;
-    }
-    
-    double MdConstants::getColorScaleStandardMax()
-    {
-      return m_colorScaleStandardMax;
-    }
-
-    double MdConstants::getLogScaleDefaultValue()
-    {
-      return m_logScaleDefaultValue;
-    }
-
-     /**
-     * Get the technique dependence.
-     *@returns The technique dependence.
-     */
-    QString MdConstants::getTechniqueDependence() const
-    {
-      return m_techniqueDependence;
-    }
-
-     /**
-     * Get a list of all initial views.
-     *@returns A list of all viewss, including a technique-dependent view
-     */
-    QStringList MdConstants::getAllInitialViews() const
-    {
-      QStringList views;
-
-      views.append(getTechniqueDependence());
-      views.append(getStandardView());
-      views.append(getMultiSliceView());
-      views.append(getThreeSliceView());
-      views.append(getSplatterPlotView());
-
-      return views;
-    }
-  }
+namespace MantidQt {
+namespace API {
+// Specifiers for ParaView filters
+const QString MdConstants::MantidParaViewSplatterPlot =
+    "MantidParaViewSplatterPlot";
+const QString MdConstants::MantidParaViewSpecialCoordinates =
+    "SpecialCoordinates";
+const QString MdConstants::MDPeaksFilter = "MDPeaksFilter";
+const QString MdConstants::MantidParaViewPeaksFilter =
+    "MantidParaViewPeaksFilter";
+const QString MdConstants::PeakDimensions = "Peak Dimensions";
+const QString MdConstants::PeaksWorkspace = "PeaksWorkspace";
+const QString MdConstants::Delimiter = "Delimiter";
+const QString MdConstants::WorkspaceName = "WorkspaceName";
+const QString MdConstants::ProbePoint = "ProbePoint";
+const QString MdConstants::Threshold = "Threshold";
+
+MdConstants::MdConstants()
+    : m_colorScaleStandardMax(0.1), m_logScaleDefaultValue(0.1) {
+  initializeSettingsConstants();
+  initializeViewConstants();
+}
+
+MdConstants::~MdConstants() {}
+
+void MdConstants::initializeSettingsConstants() {
+  // General MD Color Map
+  m_generalMdColorMap = "ColdFire";
+
+  // Background color
+  m_defaultBackgroundColor = QColor(84, 89, 109);
+
+  // Populate the optional color maps
+  m_vsiColorMaps.append("Viridis (matplotlib)");
+  m_vsiColorMaps.append("Cool to Warm");
+  m_vsiColorMaps.append("Blue to Red Rainbow");
+  m_vsiColorMaps.append("Red to Blue Rainbow");
+  m_vsiColorMaps.append("Grayscale");
+  m_vsiColorMaps.append("X Ray");
+  m_vsiColorMaps.append("Blue to Yellow");
+}
+
+void MdConstants::initializeViewConstants() {
+  m_techniqueDependence = "Technique-Dependent";
+  m_standardView = "Standard";
+  m_multiSliceView = "Multi Slice";
+  m_threeSliceView = "Three Slice";
+  m_splatterPlotView = "Splatter Plot";
+}
+
+/**
+ * Gets the general MD color map.
+ *@returns The general MD color map.
+ */
+QString MdConstants::getGeneralMdColorMap() const {
+  return m_generalMdColorMap;
+}
+
+/**
+ * Gets the label for the background color.
+ *@returns The label for the background color.
+ */
+QColor MdConstants::getDefaultBackgroundColor() const {
+  return m_defaultBackgroundColor;
+}
+
+/**
+ * Gets a list of VSI color maps.
+ *@returns The list of VSI color maps.
+ */
+QStringList MdConstants::getVsiColorMaps() const { return m_vsiColorMaps; }
+
+/**
+ * Get the standard view.
+ *@returns The standard view in the VSI.
+ */
+QString MdConstants::getStandardView() const { return m_standardView; }
+
+/**
+* Get the multi slice view.
+*@returns The multi slice view in the VSI.
+*/
+QString MdConstants::getMultiSliceView() const { return m_multiSliceView; }
+
+/**
+* Get the three slice view.
+*@returns The three slice view in the VSI.
+*/
+QString MdConstants::getThreeSliceView() const { return m_threeSliceView; }
+
+/**
+* Get the splatter plot view.
+*@returns The splatter plot view in the VSI.
+*/
+QString MdConstants::getSplatterPlotView() const { return m_splatterPlotView; }
+
+double MdConstants::getColorScaleStandardMax() {
+  return m_colorScaleStandardMax;
+}
+
+double MdConstants::getLogScaleDefaultValue() { return m_logScaleDefaultValue; }
+
+/**
+* Get the technique dependence.
+*@returns The technique dependence.
+*/
+QString MdConstants::getTechniqueDependence() const {
+  return m_techniqueDependence;
+}
+
+/**
+* Get a list of all initial views.
+*@returns A list of all viewss, including a technique-dependent view
+*/
+QStringList MdConstants::getAllInitialViews() const {
+  QStringList views;
+
+  views.append(getTechniqueDependence());
+  views.append(getStandardView());
+  views.append(getMultiSliceView());
+  views.append(getThreeSliceView());
+  views.append(getSplatterPlotView());
+
+  return views;
+}
+}
 }
diff --git a/MantidQt/API/src/MdPlottingCmapsProvider.cpp b/MantidQt/API/src/MdPlottingCmapsProvider.cpp
index 329123d1a9e213d8dfa69991feb4a0217e99830c..3517301dbddbca5f2e2adc8078c732e5cd27e9e6 100644
--- a/MantidQt/API/src/MdPlottingCmapsProvider.cpp
+++ b/MantidQt/API/src/MdPlottingCmapsProvider.cpp
@@ -13,110 +13,109 @@
 #include "vtk_jsoncpp.h"
 #endif
 
-namespace MantidQt{
-  namespace API{
-    namespace
-    {
-      /// Static logger
-      Mantid::Kernel::Logger g_log("MdViewerWidget");
-    }
+namespace MantidQt {
+namespace API {
+namespace {
+/// Static logger
+Mantid::Kernel::Logger g_log("MdViewerWidget");
+}
+
+MdPlottingCmapsProvider::MdPlottingCmapsProvider() {}
+
+MdPlottingCmapsProvider::~MdPlottingCmapsProvider() {}
+
+void MdPlottingCmapsProvider::getColorMapsForMdPlotting(
+    QStringList &colorMapNames, QStringList &colorMapFiles) {
+  // Get the installed color maps directory.
+  QString colorMapDirectory = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "colormaps.directory"));
+  if (colorMapDirectory.isEmpty()) {
+    return;
+  }
 
-    MdPlottingCmapsProvider::MdPlottingCmapsProvider()
-    {
-    }
+  // We show only those color maps as options which can be found in the .map
+  // files and in the .xml files of the VSI
+  QStringList colorMapNamesSliceViewer;
+  QStringList colorMapFilesSliceViewer;
+  appendAllFileNamesForFileType(colorMapNamesSliceViewer,
+                                colorMapFilesSliceViewer, colorMapDirectory,
+                                "map");
 
-    MdPlottingCmapsProvider::~MdPlottingCmapsProvider()
-    {
-    }
+  QStringList colorMapNamesVsi;
+  getColorMapsForVSI(colorMapNamesVsi);
 
-    void MdPlottingCmapsProvider::getColorMapsForMdPlotting(QStringList& colorMapNames, QStringList& colorMapFiles)
-    {
-      // Get the installed color maps directory.
-      QString colorMapDirectory = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("colormaps.directory"));
-      if (colorMapDirectory.isEmpty())
-      {
-        return;
-      }
-
-      // We show only those color maps as options which can be found in the .map files and in the .xml files of the VSI
-      QStringList colorMapNamesSliceViewer;
-      QStringList colorMapFilesSliceViewer;
-      appendAllFileNamesForFileType(colorMapNamesSliceViewer, colorMapFilesSliceViewer, colorMapDirectory, "map");
-
-      QStringList colorMapNamesVsi;
-      getColorMapsForVSI(colorMapNamesVsi);
-
-      std::vector<int> indexList = getSliceViewerIndicesForCommonColorMaps(colorMapNamesSliceViewer, colorMapNamesVsi);
-
-      for (std::vector<int>::iterator it = indexList.begin(); it != indexList.end(); ++it)
-      {
-        colorMapNames.append(colorMapNamesSliceViewer[*it]);
-        colorMapFiles.append(colorMapFilesSliceViewer[*it]);
-      }
-    }
+  std::vector<int> indexList = getSliceViewerIndicesForCommonColorMaps(
+      colorMapNamesSliceViewer, colorMapNamesVsi);
 
-    void MdPlottingCmapsProvider::getColorMapsForVSI(QStringList& colorMapNames)
-    {
+  for (std::vector<int>::iterator it = indexList.begin(); it != indexList.end();
+       ++it) {
+    colorMapNames.append(colorMapNamesSliceViewer[*it]);
+    colorMapFiles.append(colorMapFilesSliceViewer[*it]);
+  }
+}
+
+void MdPlottingCmapsProvider::getColorMapsForVSI(QStringList &colorMapNames) {
 #ifdef MAKE_VATES
-      vtkNew<vtkSMTransferFunctionPresets> presets;
-
-      // Check for colormap "hot". If preset, assume custom colormaps have
-      // already been loaded.
-      auto viridisColormap = presets->GetFirstPresetWithName("hot");
-      if (viridisColormap.empty()) {
-        const std::string filenames[3] = {"All_slice_viewer_cmaps_for_vsi.json",
-                                          "All_idl_cmaps.json",
-                                          "All_mpl_cmaps.json"};
-        const std::string colorMapDirectory =
-            Mantid::Kernel::ConfigService::Instance().getString(
-                "colormaps.directory");
-        for (const auto &baseName : filenames) {
-          std::string colorMap = colorMapDirectory + baseName;
-          presets->ImportPresets(colorMap.c_str());
-        }
-      }
-
-      unsigned int numberOfPresets = presets->GetNumberOfPresets();
-      for (unsigned int i = 0; i < numberOfPresets; ++i) {
-        colorMapNames.append(QString::fromStdString(presets->GetPresetName(i)));
-        }
-#else
-      (void)colorMapNames;
-#endif
+  vtkNew<vtkSMTransferFunctionPresets> presets;
+
+  // Check for colormap "hot". If preset, assume custom colormaps have
+  // already been loaded.
+  auto viridisColormap = presets->GetFirstPresetWithName("hot");
+  if (viridisColormap.empty()) {
+    const std::string filenames[3] = {"All_slice_viewer_cmaps_for_vsi.json",
+                                      "All_idl_cmaps.json",
+                                      "All_mpl_cmaps.json"};
+    const std::string colorMapDirectory =
+        Mantid::Kernel::ConfigService::Instance().getString(
+            "colormaps.directory");
+    for (const auto &baseName : filenames) {
+      std::string colorMap = colorMapDirectory + baseName;
+      presets->ImportPresets(colorMap.c_str());
     }
+  }
 
-    void MdPlottingCmapsProvider::appendAllFileNamesForFileType(QStringList& colorMapNames, QStringList& colorMapFiles, QString colorMapDirectory, QString fileType)
-    {
-      QDir directory(colorMapDirectory);
-
-      QStringList filter(QString("*.%1").arg(fileType));
+  unsigned int numberOfPresets = presets->GetNumberOfPresets();
+  for (unsigned int i = 0; i < numberOfPresets; ++i) {
+    colorMapNames.append(QString::fromStdString(presets->GetPresetName(i)));
+  }
+#else
+  (void)colorMapNames;
+#endif
+}
 
-      QFileInfoList info = directory.entryInfoList(filter, QDir::Files);
+void MdPlottingCmapsProvider::appendAllFileNamesForFileType(
+    QStringList &colorMapNames, QStringList &colorMapFiles,
+    QString colorMapDirectory, QString fileType) {
+  QDir directory(colorMapDirectory);
 
-      for (QFileInfoList::iterator it = info.begin(); it != info.end(); ++it)
-      {
-        colorMapNames.append(it->baseName());
-        colorMapFiles.append(it->absoluteFilePath());
-      }
-    }
+  QStringList filter(QString("*.%1").arg(fileType));
 
-    std::vector<int> MdPlottingCmapsProvider::getSliceViewerIndicesForCommonColorMaps(QStringList colorMapNamesSliceViewer,QStringList colorMapNamesVsi)
-    {
-      int index = 0;
+  QFileInfoList info = directory.entryInfoList(filter, QDir::Files);
 
-      std::vector<int> indexVector;
+  for (QFileInfoList::iterator it = info.begin(); it != info.end(); ++it) {
+    colorMapNames.append(it->baseName());
+    colorMapFiles.append(it->absoluteFilePath());
+  }
+}
 
-      for (QStringList::iterator it = colorMapNamesSliceViewer.begin(); it != colorMapNamesSliceViewer.end(); ++it)
-      {
-        if (colorMapNamesVsi.indexOf(*it) != -1)
-        {
-          indexVector.push_back(index);
-        }
+std::vector<int>
+MdPlottingCmapsProvider::getSliceViewerIndicesForCommonColorMaps(
+    QStringList colorMapNamesSliceViewer, QStringList colorMapNamesVsi) {
+  int index = 0;
 
-        index++;
-      }
+  std::vector<int> indexVector;
 
-      return indexVector;
+  for (QStringList::iterator it = colorMapNamesSliceViewer.begin();
+       it != colorMapNamesSliceViewer.end(); ++it) {
+    if (colorMapNamesVsi.indexOf(*it) != -1) {
+      indexVector.push_back(index);
     }
+
+    index++;
   }
-  }
+
+  return indexVector;
+}
+}
+}
diff --git a/MantidQt/API/src/MdSettings.cpp b/MantidQt/API/src/MdSettings.cpp
index a8802d619b13fb6b77375629eb1e3049012006cb..a7a6f3c58fd3b49f5f7be0b5115968abdf9ed6c9 100644
--- a/MantidQt/API/src/MdSettings.cpp
+++ b/MantidQt/API/src/MdSettings.cpp
@@ -6,39 +6,40 @@
 
 using namespace MantidQt::API;
 
-MdSettings::MdSettings() : m_vsiGroup("Mantid/MdPlotting/Vsi"),
-                           m_generalMdGroup("Mantid/MdPlotting/General"),
-                           m_sliceViewerGroup("Mantid/SliceViewer"),// This is the same as in Slice Viewer !!
-                           m_lblUserSettingColorMap("usersettingcolormap"),
-                           m_lblLastSessionColorMap("lastsessioncolormap"),
-                           m_lblGeneralMdColorMap("generalcolormap"),
-                           m_lblGeneralMdColorMapName("generalcolormapname"),
-                           m_lblUseGeneralMdColorMap("usegeneralcolormap"),
-                           m_lblUseLastSessionColorMap("uselastsessioncolormap"),
-                           m_lblUserSettingBackgroundColor("usersettingbackgroundcolor"),
-                           m_lblLastSessionBackgroundColor("lastsessionbackgroundcolor"),
-                           m_lblSliceViewerColorMap("ColormapFile"), // This is the same as in Slice Viewer !!,
-                           m_lblUserSettingInitialView("initialview"),
-                           m_lblLastSessionLogScale("lastsessionlogscale")
-{
+MdSettings::MdSettings()
+    : m_vsiGroup("Mantid/MdPlotting/Vsi"),
+      m_generalMdGroup("Mantid/MdPlotting/General"),
+      m_sliceViewerGroup(
+          "Mantid/SliceViewer"), // This is the same as in Slice Viewer !!
+      m_lblUserSettingColorMap("usersettingcolormap"),
+      m_lblLastSessionColorMap("lastsessioncolormap"),
+      m_lblGeneralMdColorMap("generalcolormap"),
+      m_lblGeneralMdColorMapName("generalcolormapname"),
+      m_lblUseGeneralMdColorMap("usegeneralcolormap"),
+      m_lblUseLastSessionColorMap("uselastsessioncolormap"),
+      m_lblUserSettingBackgroundColor("usersettingbackgroundcolor"),
+      m_lblLastSessionBackgroundColor("lastsessionbackgroundcolor"),
+      m_lblSliceViewerColorMap(
+          "ColormapFile"), // This is the same as in Slice Viewer !!,
+      m_lblUserSettingInitialView("initialview"),
+      m_lblLastSessionLogScale("lastsessionlogscale") {
   m_mdConstants.initializeSettingsConstants();
 }
 
-MdSettings::~MdSettings(){}
+MdSettings::~MdSettings() {}
 
-QString MdSettings::getUserSettingColorMap()
-{
-    QSettings settings;
+QString MdSettings::getUserSettingColorMap() {
+  QSettings settings;
+
+  settings.beginGroup(m_vsiGroup);
+  QString userSettingColorMap =
+      settings.value(m_lblUserSettingColorMap, QString("")).toString();
+  settings.endGroup();
 
-    settings.beginGroup(m_vsiGroup);
-    QString userSettingColorMap = settings.value(m_lblUserSettingColorMap, QString("")).toString();
-    settings.endGroup();
-        
-    return userSettingColorMap;
+  return userSettingColorMap;
 }
 
-void MdSettings::setUserSettingColorMap(QString colorMap)
-{
+void MdSettings::setUserSettingColorMap(QString colorMap) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -46,19 +47,18 @@ void MdSettings::setUserSettingColorMap(QString colorMap)
   settings.endGroup();
 }
 
-QString MdSettings::getLastSessionColorMap()
-{
+QString MdSettings::getLastSessionColorMap() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
-  QString colormap = settings.value(m_lblLastSessionColorMap, QString("")).toString();
+  QString colormap =
+      settings.value(m_lblLastSessionColorMap, QString("")).toString();
   settings.endGroup();
 
   return colormap;
 }
 
-void MdSettings::setLastSessionColorMap(QString colorMap)
-{
+void MdSettings::setLastSessionColorMap(QString colorMap) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -66,20 +66,19 @@ void MdSettings::setLastSessionColorMap(QString colorMap)
   settings.endGroup();
 }
 
-QColor MdSettings::getUserSettingBackgroundColor()
-{
+QColor MdSettings::getUserSettingBackgroundColor() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
-  QColor backgroundColor= settings.value(m_lblUserSettingBackgroundColor,
-                                         m_mdConstants.getDefaultBackgroundColor()).value<QColor>();
+  QColor backgroundColor =
+      settings.value(m_lblUserSettingBackgroundColor,
+                     m_mdConstants.getDefaultBackgroundColor()).value<QColor>();
   settings.endGroup();
 
   return backgroundColor;
 }
 
-void MdSettings::setUserSettingBackgroundColor(QColor backgroundColor)
-{
+void MdSettings::setUserSettingBackgroundColor(QColor backgroundColor) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -87,25 +86,23 @@ void MdSettings::setUserSettingBackgroundColor(QColor backgroundColor)
   settings.endGroup();
 }
 
-QColor MdSettings::getLastSessionBackgroundColor()
-{
+QColor MdSettings::getLastSessionBackgroundColor() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
-  QColor backgroundColor= settings.value(m_lblLastSessionBackgroundColor,
-                                         m_mdConstants.getDefaultBackgroundColor()).value<QColor>();
+  QColor backgroundColor =
+      settings.value(m_lblLastSessionBackgroundColor,
+                     m_mdConstants.getDefaultBackgroundColor()).value<QColor>();
   settings.endGroup();
 
   return backgroundColor;
 }
 
-QColor MdSettings::getDefaultBackgroundColor()
-{
+QColor MdSettings::getDefaultBackgroundColor() {
   return m_mdConstants.getDefaultBackgroundColor();
 }
 
-void MdSettings::setLastSessionBackgroundColor(QColor backgroundColor)
-{
+void MdSettings::setLastSessionBackgroundColor(QColor backgroundColor) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -113,8 +110,8 @@ void MdSettings::setLastSessionBackgroundColor(QColor backgroundColor)
   settings.endGroup();
 }
 
-void MdSettings::setGeneralMdColorMap(QString colorMapName, QString colorMapFile)
-{
+void MdSettings::setGeneralMdColorMap(QString colorMapName,
+                                      QString colorMapFile) {
   QSettings settings;
 
   settings.beginGroup(m_generalMdGroup);
@@ -123,32 +120,30 @@ void MdSettings::setGeneralMdColorMap(QString colorMapName, QString colorMapFile
   settings.endGroup();
 }
 
-QString  MdSettings::getGeneralMdColorMapFile()
-{
+QString MdSettings::getGeneralMdColorMapFile() {
   QSettings settings;
 
   settings.beginGroup(m_generalMdGroup);
-  QString colorMap = settings.value(m_lblGeneralMdColorMap, QString("")).toString();
+  QString colorMap =
+      settings.value(m_lblGeneralMdColorMap, QString("")).toString();
   settings.endGroup();
 
   return colorMap;
 }
 
-
-QString MdSettings::getGeneralMdColorMapName()
-{
+QString MdSettings::getGeneralMdColorMapName() {
   QSettings settings;
 
   settings.beginGroup(m_generalMdGroup);
-  QString  colorMap = settings.value(m_lblGeneralMdColorMapName, m_mdConstants.getGeneralMdColorMap()).toString();
+  QString colorMap =
+      settings.value(m_lblGeneralMdColorMapName,
+                     m_mdConstants.getGeneralMdColorMap()).toString();
   settings.endGroup();
 
   return colorMap;
 }
 
-
-void MdSettings::setUsageGeneralMdColorMap(bool flag)
-{
+void MdSettings::setUsageGeneralMdColorMap(bool flag) {
   QSettings settings;
 
   settings.beginGroup(m_generalMdGroup);
@@ -156,8 +151,7 @@ void MdSettings::setUsageGeneralMdColorMap(bool flag)
   settings.endGroup();
 }
 
-bool MdSettings::getUsageGeneralMdColorMap()
-{
+bool MdSettings::getUsageGeneralMdColorMap() {
   QSettings settings;
 
   settings.beginGroup(m_generalMdGroup);
@@ -167,8 +161,7 @@ bool MdSettings::getUsageGeneralMdColorMap()
   return flag;
 }
 
-void MdSettings::setUsageLastSession(bool flag)
-{
+void MdSettings::setUsageLastSession(bool flag) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -176,8 +169,7 @@ void MdSettings::setUsageLastSession(bool flag)
   settings.endGroup();
 }
 
-bool MdSettings::getUsageLastSession()
-{
+bool MdSettings::getUsageLastSession() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -187,8 +179,7 @@ bool MdSettings::getUsageLastSession()
   return flag;
 }
 
-void MdSettings::setLastSessionLogScale(bool logScale)
-{
+void MdSettings::setLastSessionLogScale(bool logScale) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -196,22 +187,19 @@ void MdSettings::setLastSessionLogScale(bool logScale)
   settings.endGroup();
 }
 
-QString MdSettings::getUserSettingInitialView()
-{
+QString MdSettings::getUserSettingInitialView() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
-  QString initialView = settings
-                            .value(m_lblUserSettingInitialView,
-                                   m_mdConstants.getTechniqueDependence())
-                            .toString();
+  QString initialView =
+      settings.value(m_lblUserSettingInitialView,
+                     m_mdConstants.getTechniqueDependence()).toString();
   settings.endGroup();
 
   return initialView;
 }
 
-bool MdSettings::getLastSessionLogScale()
-{
+bool MdSettings::getLastSessionLogScale() {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
@@ -221,9 +209,7 @@ bool MdSettings::getLastSessionLogScale()
   return logScale;
 }
 
-
-void MdSettings::setUserSettingIntialView(QString initialView)
-{
+void MdSettings::setUserSettingIntialView(QString initialView) {
   QSettings settings;
 
   settings.beginGroup(m_vsiGroup);
diff --git a/MantidQt/API/src/Message.cpp b/MantidQt/API/src/Message.cpp
index 4e44f3dadb4778950990c35340bbdae68e72b054..505d076d51a2445bc10122dd444bfd309c70db0f 100644
--- a/MantidQt/API/src/Message.cpp
+++ b/MantidQt/API/src/Message.cpp
@@ -3,51 +3,42 @@
 //-------------------------------------------
 #include "MantidQtAPI/Message.h"
 
-namespace MantidQt
-{
-  namespace API
-  {
-    //-----------------------------------------------------------------------------------
-    // Public member functions
-    //-----------------------------------------------------------------------------------
-    /**
-     * Constructs a blank message with notice priority
-     * (here to satisfy Qt meta-type system)
-     */
-    Message::Message() : QObject(), m_text(), m_priority(Priority::PRIO_NOTICE)
-    {}
+namespace MantidQt {
+namespace API {
+//-----------------------------------------------------------------------------------
+// Public member functions
+//-----------------------------------------------------------------------------------
+/**
+ * Constructs a blank message with notice priority
+ * (here to satisfy Qt meta-type system)
+ */
+Message::Message() : QObject(), m_text(), m_priority(Priority::PRIO_NOTICE) {}
 
-    /**
-     * @param text A QString containing the message text
-     * @param priority A enumeration indicating the priority
-     */
-    Message::Message(const QString & text, Priority priority)
-      : QObject(), m_text(text), m_priority(priority)
-    {}
+/**
+ * @param text A QString containing the message text
+ * @param priority A enumeration indicating the priority
+ */
+Message::Message(const QString &text, Priority priority)
+    : QObject(), m_text(text), m_priority(priority) {}
 
-    /**
-     * @param text A std::string containing the message text
-     * @param priority A enumeration indicating the priority
-     */
-    Message::Message(const std::string & text, Priority priority)
-      : QObject(), m_text(QString::fromStdString(text)), m_priority(priority)
-    {}
+/**
+ * @param text A std::string containing the message text
+ * @param priority A enumeration indicating the priority
+ */
+Message::Message(const std::string &text, Priority priority)
+    : QObject(), m_text(QString::fromStdString(text)), m_priority(priority) {}
 
-    /**
-     * @param text A c-style string containing the message text
-     * @param priority A enumeration indicating the priority
-     */
-    Message::Message(const char * text, Priority priority)
-      : QObject(), m_text(text), m_priority(priority)
-    {}
+/**
+ * @param text A c-style string containing the message text
+ * @param priority A enumeration indicating the priority
+ */
+Message::Message(const char *text, Priority priority)
+    : QObject(), m_text(text), m_priority(priority) {}
 
-    /**
-     * Construct a message from another object
-     */
-    Message::Message(const Message & msg)
-      : QObject(), m_text(msg.text()), m_priority(msg.priority())
-    {
-    }
-
-  }
+/**
+ * Construct a message from another object
+ */
+Message::Message(const Message &msg)
+    : QObject(), m_text(msg.text()), m_priority(msg.priority()) {}
+}
 }
diff --git a/MantidQt/API/src/OptionsPropertyWidget.cpp b/MantidQt/API/src/OptionsPropertyWidget.cpp
index f190d2600c1734af6bc346ad76e59bdbc0ae7bbe..d965156458b6433a06ba656ae4591fefcfe13bfd 100644
--- a/MantidQt/API/src/OptionsPropertyWidget.cpp
+++ b/MantidQt/API/src/OptionsPropertyWidget.cpp
@@ -9,71 +9,66 @@
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  OptionsPropertyWidget::~OptionsPropertyWidget()
-  {
-  }
-  
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+OptionsPropertyWidget::~OptionsPropertyWidget() {}
 
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  OptionsPropertyWidget::OptionsPropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent, QGridLayout * layout, int row)
-  : PropertyWidget(prop, parent, layout, row)
-  {
-    // Label at column 0
-    m_label = new QLabel(QString::fromStdString(prop->name()), m_parent);
-    m_label->setToolTip(m_doc);
-    m_gridLayout->addWidget(m_label, m_row, 0, 0);
-    m_widgets.push_back(m_label);
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+OptionsPropertyWidget::OptionsPropertyWidget(Mantid::Kernel::Property *prop,
+                                             QWidget *parent,
+                                             QGridLayout *layout, int row)
+    : PropertyWidget(prop, parent, layout, row) {
+  // Label at column 0
+  m_label = new QLabel(QString::fromStdString(prop->name()), m_parent);
+  m_label->setToolTip(m_doc);
+  m_gridLayout->addWidget(m_label, m_row, 0, 0);
+  m_widgets.push_back(m_label);
 
-    //It is a choice of certain allowed values and can use a combination box
-    //Check if this is the row that matches the one that we want to link to the
-    //output box and used the saved combo box
-    m_combo = new QComboBox(this);
-    m_combo->setToolTip(m_doc);
-    m_widgets.push_back(m_combo);
+  // It is a choice of certain allowed values and can use a combination box
+  // Check if this is the row that matches the one that we want to link to the
+  // output box and used the saved combo box
+  m_combo = new QComboBox(this);
+  m_combo->setToolTip(m_doc);
+  m_widgets.push_back(m_combo);
 
-    std::vector<std::string> items = prop->allowedValues();
-    for(auto vitr = items.begin(); vitr != items.end(); ++vitr)
-    {
-      m_combo->addItem(QString::fromStdString(*vitr));
-    }
-    // Make current value visible
-    this->setValue(QString::fromStdString(m_prop->value()));
+  std::vector<std::string> items = prop->allowedValues();
+  for (auto vitr = items.begin(); vitr != items.end(); ++vitr) {
+    m_combo->addItem(QString::fromStdString(*vitr));
+  }
+  // Make current value visible
+  this->setValue(QString::fromStdString(m_prop->value()));
 
-    // Make sure the connection comes after updating any values
-    connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(userEditedProperty()));
+  // Make sure the connection comes after updating any values
+  connect(m_combo, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(userEditedProperty()));
 
-    // Put the combo in column 1
-    m_gridLayout->addWidget(m_combo, m_row, 1, 0);
-  }
+  // Put the combo in column 1
+  m_gridLayout->addWidget(m_combo, m_row, 1, 0);
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** @return the value of the property, as typed in the GUI, as a string */
-  QString OptionsPropertyWidget::getValue() const
-  {
-    return m_combo->currentText();
-  }
+//----------------------------------------------------------------------------------------------
+/** @return the value of the property, as typed in the GUI, as a string */
+QString OptionsPropertyWidget::getValue() const {
+  return m_combo->currentText();
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Set the value into the GUI
-   *
-   * @param value :: string representation of the value */
-  void OptionsPropertyWidget::setValueImpl(const QString & value)
-  {
-    const QString temp = value.isEmpty() ? QString::fromStdString(m_prop->getDefault()) : value;
+//----------------------------------------------------------------------------------------------
+/** Set the value into the GUI
+ *
+ * @param value :: string representation of the value */
+void OptionsPropertyWidget::setValueImpl(const QString &value) {
+  const QString temp =
+      value.isEmpty() ? QString::fromStdString(m_prop->getDefault()) : value;
 
-    int index = m_combo->findText(temp);
-    if( index >= 0 )
-      m_combo->setCurrentIndex(index);
-  }
+  int index = m_combo->findText(temp);
+  if (index >= 0)
+    m_combo->setCurrentIndex(index);
+}
 } // namespace MantidQt
 } // namespace API
diff --git a/MantidQt/API/src/PowerScaleEngine.cpp b/MantidQt/API/src/PowerScaleEngine.cpp
index bc1c985c4b088e364d562d24d17392d5f848d1f4..8530251b00fd5e59e06dd65a48fc5336fe17b3a0 100644
--- a/MantidQt/API/src/PowerScaleEngine.cpp
+++ b/MantidQt/API/src/PowerScaleEngine.cpp
@@ -33,9 +33,8 @@
 /*!
   Return a dummy transformation
 */
-QwtScaleTransformation *PowerScaleEngine::transformation() const
-{
-    return new QwtScaleTransformation(QwtScaleTransformation::Other);
+QwtScaleTransformation *PowerScaleEngine::transformation() const {
+  return new QwtScaleTransformation(QwtScaleTransformation::Other);
 }
 
 PowerScaleEngine::~PowerScaleEngine() {}
@@ -48,37 +47,35 @@ PowerScaleEngine::~PowerScaleEngine() {}
    \param x2 Second limit of the interval (In/Out)
    \param stepSize Step size (Out)
 */
-void PowerScaleEngine::autoScale(int maxNumSteps,
-    double &x1, double &x2, double &stepSize) const
-{
-    QwtDoubleInterval interval(x1, x2);
-    interval = interval.normalized();
+void PowerScaleEngine::autoScale(int maxNumSteps, double &x1, double &x2,
+                                 double &stepSize) const {
+  QwtDoubleInterval interval(x1, x2);
+  interval = interval.normalized();
 
-    interval.setMinValue(interval.minValue() - lowerMargin());
-    interval.setMaxValue(interval.maxValue() + upperMargin());
+  interval.setMinValue(interval.minValue() - lowerMargin());
+  interval.setMaxValue(interval.maxValue() + upperMargin());
 
-    if (testAttribute(QwtScaleEngine::Symmetric))
-        interval = interval.symmetrize(reference());
+  if (testAttribute(QwtScaleEngine::Symmetric))
+    interval = interval.symmetrize(reference());
 
-    if (testAttribute(QwtScaleEngine::IncludeReference))
-        interval = interval.extend(reference());
+  if (testAttribute(QwtScaleEngine::IncludeReference))
+    interval = interval.extend(reference());
 
-    if (interval.width() == 0.0)
-        interval = buildInterval(interval.minValue());
+  if (interval.width() == 0.0)
+    interval = buildInterval(interval.minValue());
 
-    stepSize = divideInterval(interval.width(), qwtMax(maxNumSteps, 1));
+  stepSize = divideInterval(interval.width(), qwtMax(maxNumSteps, 1));
 
-    if ( !testAttribute(QwtScaleEngine::Floating) )
-        interval = align(interval, stepSize);
+  if (!testAttribute(QwtScaleEngine::Floating))
+    interval = align(interval, stepSize);
 
-    x1 = interval.minValue();
-    x2 = interval.maxValue();
+  x1 = interval.minValue();
+  x2 = interval.maxValue();
 
-    if (testAttribute(QwtScaleEngine::Inverted))
-    {
-        qSwap(x1, x2);
-        stepSize = -stepSize;
-    }
+  if (testAttribute(QwtScaleEngine::Inverted)) {
+    qSwap(x1, x2);
+    stepSize = -stepSize;
+  }
 }
 
 /*!
@@ -93,130 +90,118 @@ void PowerScaleEngine::autoScale(int maxNumSteps,
 
    \sa QwtScaleEngine::stepSize(), QwtScaleEngine::subDivide()
 */
-QwtScaleDiv PowerScaleEngine::divideScale(double x1, double x2,
-    int maxMajSteps, int maxMinSteps, double stepSize) const
-{
-    QwtDoubleInterval interval = QwtDoubleInterval(x1, x2).normalized();
-    if (interval.width() <= 0 )
-        return QwtScaleDiv();
-
-    stepSize = qwtAbs(stepSize);
-    if ( stepSize == 0.0 )
-    {
-        if ( maxMajSteps < 1 )
-            maxMajSteps = 1;
-
-        stepSize = divideInterval(interval.width(), maxMajSteps);
-    }
-
-    QwtScaleDiv scaleDiv;
-
-    if ( stepSize != 0.0 )
-    {
-        QwtValueList ticks[QwtScaleDiv::NTickTypes];
-        buildTicks(interval, stepSize, maxMinSteps, ticks);
+QwtScaleDiv PowerScaleEngine::divideScale(double x1, double x2, int maxMajSteps,
+                                          int maxMinSteps,
+                                          double stepSize) const {
+  QwtDoubleInterval interval = QwtDoubleInterval(x1, x2).normalized();
+  if (interval.width() <= 0)
+    return QwtScaleDiv();
 
-        scaleDiv = QwtScaleDiv(interval, ticks);
-    }
+  stepSize = qwtAbs(stepSize);
+  if (stepSize == 0.0) {
+    if (maxMajSteps < 1)
+      maxMajSteps = 1;
 
-    if ( x1 > x2 )
-        scaleDiv.invert();
+    stepSize = divideInterval(interval.width(), maxMajSteps);
+  }
 
-    return scaleDiv;
-}
+  QwtScaleDiv scaleDiv;
 
-void PowerScaleEngine::buildTicks(
-    const QwtDoubleInterval& interval, double stepSize, int maxMinSteps,
-    QwtValueList ticks[QwtScaleDiv::NTickTypes]) const
-{
-    const QwtDoubleInterval boundingInterval =
-        align(interval, stepSize);
-
-    ticks[QwtScaleDiv::MajorTick] =
-        buildMajorTicks(boundingInterval, stepSize);
-
-    if ( maxMinSteps > 0 )
-    {
-        buildMinorTicks(ticks[QwtScaleDiv::MajorTick], maxMinSteps, stepSize,
-            ticks[QwtScaleDiv::MinorTick], ticks[QwtScaleDiv::MediumTick]);
-    }
+  if (stepSize != 0.0) {
+    QwtValueList ticks[QwtScaleDiv::NTickTypes];
+    buildTicks(interval, stepSize, maxMinSteps, ticks);
 
-    for ( int i = 0; i < QwtScaleDiv::NTickTypes; i++ )
-    {
-        ticks[i] = strip(ticks[i], interval);
+    scaleDiv = QwtScaleDiv(interval, ticks);
+  }
 
-        // ticks very close to 0.0 are
-        // explicitly set to 0.0
+  if (x1 > x2)
+    scaleDiv.invert();
 
-        for ( int j = 0; j < (int)ticks[i].count(); j++ )
-        {
-            if ( QwtScaleArithmetic::compareEps(ticks[i][j], 0.0, stepSize) == 0 )
-                ticks[i][j] = 0.0;
-        }
-    }
+  return scaleDiv;
 }
 
-QwtValueList PowerScaleEngine::buildMajorTicks(
-    const QwtDoubleInterval &interval, double stepSize) const
-{
-    int numTicks = qRound(interval.width() / stepSize) + 1;
-    if ( numTicks > 10000 )
-        numTicks = 10000;
+void PowerScaleEngine::buildTicks(
+    const QwtDoubleInterval &interval, double stepSize, int maxMinSteps,
+    QwtValueList ticks[QwtScaleDiv::NTickTypes]) const {
+  const QwtDoubleInterval boundingInterval = align(interval, stepSize);
+
+  ticks[QwtScaleDiv::MajorTick] = buildMajorTicks(boundingInterval, stepSize);
 
-    QwtValueList ticks;
+  if (maxMinSteps > 0) {
+    buildMinorTicks(ticks[QwtScaleDiv::MajorTick], maxMinSteps, stepSize,
+                    ticks[QwtScaleDiv::MinorTick],
+                    ticks[QwtScaleDiv::MediumTick]);
+  }
 
-    ticks += interval.minValue();
-    for (int i = 1; i < numTicks - 1; i++)
-        ticks += interval.minValue() + i * stepSize;
-    ticks += interval.maxValue();
+  for (int i = 0; i < QwtScaleDiv::NTickTypes; i++) {
+    ticks[i] = strip(ticks[i], interval);
 
-    return ticks;
-}
+    // ticks very close to 0.0 are
+    // explicitly set to 0.0
 
-void PowerScaleEngine::buildMinorTicks(
-    const QwtValueList& majorTicks,
-    int maxMinSteps, double stepSize,
-    QwtValueList &minorTicks,
-    QwtValueList &mediumTicks) const
-{
-    double minStep = divideInterval(stepSize, maxMinSteps);
-    if (minStep == 0.0)
-        return;
-
-    // # ticks per interval
-    int numTicks = (int)::ceil(qwtAbs(stepSize / minStep)) - 1;
-
-    // Do the minor steps fit into the interval?
-    if ( QwtScaleArithmetic::compareEps((numTicks +  1) * qwtAbs(minStep),
-        qwtAbs(stepSize), stepSize) > 0)
-    {
-        numTicks = 1;
-        minStep = stepSize * 0.5;
+    for (int j = 0; j < (int)ticks[i].count(); j++) {
+      if (QwtScaleArithmetic::compareEps(ticks[i][j], 0.0, stepSize) == 0)
+        ticks[i][j] = 0.0;
     }
+  }
+}
 
-    int medIndex = -1;
-    if ( numTicks % 2 )
-        medIndex = numTicks / 2;
+QwtValueList
+PowerScaleEngine::buildMajorTicks(const QwtDoubleInterval &interval,
+                                  double stepSize) const {
+  int numTicks = qRound(interval.width() / stepSize) + 1;
+  if (numTicks > 10000)
+    numTicks = 10000;
 
-    // calculate minor ticks
+  QwtValueList ticks;
 
-    for (int i = 0; i < (int)majorTicks.count(); i++)
-    {
-        double val = majorTicks[i];
-        for (int k = 0; k < numTicks; k++)
-        {
-            val += minStep;
+  ticks += interval.minValue();
+  for (int i = 1; i < numTicks - 1; i++)
+    ticks += interval.minValue() + i * stepSize;
+  ticks += interval.maxValue();
 
-            double alignedValue = val;
-            if (QwtScaleArithmetic::compareEps(val, 0.0, stepSize) == 0)
-                alignedValue = 0.0;
+  return ticks;
+}
 
-            if ( k == medIndex )
-                mediumTicks += alignedValue;
-            else
-                minorTicks += alignedValue;
-        }
+void PowerScaleEngine::buildMinorTicks(const QwtValueList &majorTicks,
+                                       int maxMinSteps, double stepSize,
+                                       QwtValueList &minorTicks,
+                                       QwtValueList &mediumTicks) const {
+  double minStep = divideInterval(stepSize, maxMinSteps);
+  if (minStep == 0.0)
+    return;
+
+  // # ticks per interval
+  int numTicks = (int)::ceil(qwtAbs(stepSize / minStep)) - 1;
+
+  // Do the minor steps fit into the interval?
+  if (QwtScaleArithmetic::compareEps((numTicks + 1) * qwtAbs(minStep),
+                                     qwtAbs(stepSize), stepSize) > 0) {
+    numTicks = 1;
+    minStep = stepSize * 0.5;
+  }
+
+  int medIndex = -1;
+  if (numTicks % 2)
+    medIndex = numTicks / 2;
+
+  // calculate minor ticks
+
+  for (int i = 0; i < (int)majorTicks.count(); i++) {
+    double val = majorTicks[i];
+    for (int k = 0; k < numTicks; k++) {
+      val += minStep;
+
+      double alignedValue = val;
+      if (QwtScaleArithmetic::compareEps(val, 0.0, stepSize) == 0)
+        alignedValue = 0.0;
+
+      if (k == medIndex)
+        mediumTicks += alignedValue;
+      else
+        minorTicks += alignedValue;
     }
+  }
 }
 
 /*!
@@ -230,21 +215,17 @@ void PowerScaleEngine::buildMinorTicks(
 
   \return Aligned interval
 */
-QwtDoubleInterval PowerScaleEngine::align(
-    const QwtDoubleInterval &interval, double stepSize) const
-{
-    const double x1 =
-        QwtScaleArithmetic::floorEps(interval.minValue(), stepSize);
-    const double x2 =
-        QwtScaleArithmetic::ceilEps(interval.maxValue(), stepSize);
-
-    return QwtDoubleInterval(x1, x2);
+QwtDoubleInterval PowerScaleEngine::align(const QwtDoubleInterval &interval,
+                                          double stepSize) const {
+  const double x1 = QwtScaleArithmetic::floorEps(interval.minValue(), stepSize);
+  const double x2 = QwtScaleArithmetic::ceilEps(interval.maxValue(), stepSize);
+
+  return QwtDoubleInterval(x1, x2);
 }
 
 //! Create a clone of the transformation
-QwtScaleTransformation *PowerScaleTransformation::copy() const
-{
-	return new PowerScaleTransformation(d_engine);
+QwtScaleTransformation *PowerScaleTransformation::copy() const {
+  return new PowerScaleTransformation(d_engine);
 }
 
 PowerScaleTransformation::~PowerScaleTransformation() {}
@@ -258,10 +239,11 @@ PowerScaleTransformation::~PowerScaleTransformation() {}
  * \param p1 first border of target interval
  * \param p2 second border of target interval
  */
-double PowerScaleTransformation::xForm(
-    double s, double s1, double s2, double p1, double p2) const
-{
-	return p1 + (p2 - p1) / (pow(s2, nth_power) - pow(s1, nth_power)) * (pow(s, nth_power) - pow(s1, nth_power));
+double PowerScaleTransformation::xForm(double s, double s1, double s2,
+                                       double p1, double p2) const {
+  return p1 +
+         (p2 - p1) / (pow(s2, nth_power) - pow(s1, nth_power)) *
+             (pow(s, nth_power) - pow(s1, nth_power));
 }
 
 /*
@@ -274,8 +256,8 @@ double PowerScaleTransformation::xForm(
  * \param s2 second border of logarithmic interval
  */
 double PowerScaleTransformation::invXForm(double p, double p1, double p2,
-    double s1, double s2) const
-{
-	return pow((p - p1) / (p2 - p1) * (pow(s2, nth_power) - pow(s1, nth_power)), 1.0/nth_power) + s1;
+                                          double s1, double s2) const {
+  return pow((p - p1) / (p2 - p1) * (pow(s2, nth_power) - pow(s1, nth_power)),
+             1.0 / nth_power) +
+         s1;
 }
-
diff --git a/MantidQt/API/src/PropertyWidget.cpp b/MantidQt/API/src/PropertyWidget.cpp
index 4cbd7a870a39b4a0205d929fe493f936a23f6e02..27eedd7ca76d3d300ea0c6fc34161586c3b1e725 100644
--- a/MantidQt/API/src/PropertyWidget.cpp
+++ b/MantidQt/API/src/PropertyWidget.cpp
@@ -89,12 +89,8 @@ bool isEmptyNumMacro(const std::string &value) {
   }
 
   static const std::vector<double> EMPTY_NUM_MACROS = {
-      EMPTY_DBL(),
-      -DBL_MAX,
-      DBL_MAX,
-      static_cast<double>(EMPTY_INT()),
-      static_cast<double>(EMPTY_LONG()),
-      static_cast<double>(-INT_MAX),
+      EMPTY_DBL(), -DBL_MAX, DBL_MAX, static_cast<double>(EMPTY_INT()),
+      static_cast<double>(EMPTY_LONG()), static_cast<double>(-INT_MAX),
       static_cast<double>(-LONG_MAX)};
 
   return std::find(EMPTY_NUM_MACROS.begin(), EMPTY_NUM_MACROS.end(),
@@ -200,7 +196,7 @@ PropertyWidget::PropertyWidget(Mantid::Kernel::Property *prop, QWidget *parent,
   if (!m_gridLayout) {
     // Create a LOCAL grid layout
     m_gridLayout = new QGridLayout(this);
-      
+
     m_gridLayout->setSpacing(5);
     this->setLayout(m_gridLayout);
     m_row = 0;
diff --git a/MantidQt/API/src/PropertyWidgetFactory.cpp b/MantidQt/API/src/PropertyWidgetFactory.cpp
index 4625c3009705c36b23e69d3de4858d8d367d7c5b..7a6f33c2086768d012ed6ba8ddfa79de10261117 100644
--- a/MantidQt/API/src/PropertyWidgetFactory.cpp
+++ b/MantidQt/API/src/PropertyWidgetFactory.cpp
@@ -11,67 +11,54 @@
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+PropertyWidgetFactory::PropertyWidgetFactory() {}
 
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  PropertyWidgetFactory::PropertyWidgetFactory()
-  {
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  PropertyWidgetFactory::~PropertyWidgetFactory()
-  {
-  }
-  
-  //----------------------------------------------------------------------------------------------
-  /** Create the appropriate PropertyWidget for the given Property
-   *
-   * @param prop :: property for the widget
-   * @param parent :: parent widget
-   * @param layout :: QGridLayout of the parent, in the case of the GenericDialog
-   * @param row :: row in the above QGridLayout, if specified
-   * @return the right PropertyWidget * subclass
-   */
-  PropertyWidget * PropertyWidgetFactory::createWidget(Mantid::Kernel::Property * prop,
-      QWidget * parent, QGridLayout * layout, int row)
-  {
-    Mantid::API::FileProperty* fileType = dynamic_cast<Mantid::API::FileProperty*>(prop);
-    Mantid::API::MultipleFileProperty* multipleFileType = dynamic_cast<Mantid::API::MultipleFileProperty*>(prop);
-    PropertyWithValue<bool>* boolProp = dynamic_cast<PropertyWithValue<bool>* >(prop);
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+PropertyWidgetFactory::~PropertyWidgetFactory() {}
 
-    if (boolProp)
-    {
-      // CheckBox shown for BOOL properties
-      return new BoolPropertyWidget(boolProp, parent, layout, row);
-    }
-    else if ( !prop->allowedValues().empty() && !fileType && !multipleFileType )
-    {
-      //Check if there are only certain allowed values for the property
-      return new OptionsPropertyWidget(prop, parent, layout, row);
-    }
-    else
-    {
-      if (fileType || multipleFileType)
-      {
-        return new FilePropertyWidget(prop, parent, layout, row);
-      }
-      else
-      {
-        // Generic text property
-        return new TextPropertyWidget(prop, parent, layout, row);
-      }
-    }
+//----------------------------------------------------------------------------------------------
+/** Create the appropriate PropertyWidget for the given Property
+ *
+ * @param prop :: property for the widget
+ * @param parent :: parent widget
+ * @param layout :: QGridLayout of the parent, in the case of the GenericDialog
+ * @param row :: row in the above QGridLayout, if specified
+ * @return the right PropertyWidget * subclass
+ */
+PropertyWidget *
+PropertyWidgetFactory::createWidget(Mantid::Kernel::Property *prop,
+                                    QWidget *parent, QGridLayout *layout,
+                                    int row) {
+  Mantid::API::FileProperty *fileType =
+      dynamic_cast<Mantid::API::FileProperty *>(prop);
+  Mantid::API::MultipleFileProperty *multipleFileType =
+      dynamic_cast<Mantid::API::MultipleFileProperty *>(prop);
+  PropertyWithValue<bool> *boolProp =
+      dynamic_cast<PropertyWithValue<bool> *>(prop);
 
+  if (boolProp) {
+    // CheckBox shown for BOOL properties
+    return new BoolPropertyWidget(boolProp, parent, layout, row);
+  } else if (!prop->allowedValues().empty() && !fileType && !multipleFileType) {
+    // Check if there are only certain allowed values for the property
+    return new OptionsPropertyWidget(prop, parent, layout, row);
+  } else {
+    if (fileType || multipleFileType) {
+      return new FilePropertyWidget(prop, parent, layout, row);
+    } else {
+      // Generic text property
+      return new TextPropertyWidget(prop, parent, layout, row);
+    }
   }
-
+}
 
 } // namespace MantidQt
 } // namespace API
diff --git a/MantidQt/API/src/PythonRunner.cpp b/MantidQt/API/src/PythonRunner.cpp
index 95b142679beb6d1b4fccbcbda62827a5718d8d84..d8053437b4a0f36fef59f6df1a6b6f45d4aae684 100644
--- a/MantidQt/API/src/PythonRunner.cpp
+++ b/MantidQt/API/src/PythonRunner.cpp
@@ -9,57 +9,60 @@
 
 using namespace MantidQt::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("PythonRunner");
+namespace {
+Mantid::Kernel::Logger g_log("PythonRunner");
 
-  /// Format of python warning message. It will be removed from any output string
-  QString PYTHON_V1_WARN = "Warning: Python API v1 call has been made.\n";
+/// Format of python warning message. It will be removed from any output string
+QString PYTHON_V1_WARN = "Warning: Python API v1 call has been made.\n";
 }
 
-
 /** Run a piece of python code and return any output that it writes to stdout
 *  @param code :: the Python commands to execute
-*  @param no_output :: if set to true this method returns an empty string, if false it returns the output from any Python print statements
+*  @param no_output :: if set to true this method returns an empty string, if
+* false it returns the output from any Python print statements
 *  @return output from Python print statements unless no_output is false
 */
-QString PythonRunner::runPythonCode(const QString & code, bool no_output)
-{
+QString PythonRunner::runPythonCode(const QString &code, bool no_output) {
   using Mantid::Kernel::Logger;
 
-  if(g_log.is(Logger::Priority::PRIO_DEBUG)) g_log.debug() << "Running Python code:\n" << code.toAscii().data() << "\n";
+  if (g_log.is(Logger::Priority::PRIO_DEBUG))
+    g_log.debug() << "Running Python code:\n" << code.toAscii().data() << "\n";
 
-  if( no_output )
-  {
+  if (no_output) {
     emit runAsPythonScript(code, true);
     return QString();
   }
 
-  // Otherwise we need to gather the information from stdout. This is achieved by redirecting the stdout stream
+  // Otherwise we need to gather the information from stdout. This is achieved
+  // by redirecting the stdout stream
   // to a temproary file and then reading its contents
-  // A QTemporaryFile object is used since the file is automatically deleted when the object goes out of scope
+  // A QTemporaryFile object is used since the file is automatically deleted
+  // when the object goes out of scope
   QTemporaryFile tmp_file;
-  if( !tmp_file.open() )
-  {
-    throw std::runtime_error("An error occurred opening a temporary file in " + QDir::tempPath().toStdString());
+  if (!tmp_file.open()) {
+    throw std::runtime_error("An error occurred opening a temporary file in " +
+                             QDir::tempPath().toStdString());
   }
-  //The file name is only valid when the file is open
+  // The file name is only valid when the file is open
   QString tmpstring = tmp_file.fileName();
   tmp_file.close();
-  QString code_to_run = "import sys; sys.stdout = open(\"" + tmpstring + "\", 'w');\n" + code;
+  QString code_to_run =
+      "import sys; sys.stdout = open(\"" + tmpstring + "\", 'w');\n" + code;
   emit runAsPythonScript(code_to_run, true);
 
-  //Now get the output
+  // Now get the output
   tmp_file.open();
   QTextStream stream(&tmp_file);
   tmpstring.clear();
 
-  while( !stream.atEnd() )
-  {
+  while (!stream.atEnd()) {
     tmpstring.append(stream.readLine().trimmed() + "\n");
   }
-  //FIXME: Ticket-9217 - Commented out for the moment to try and get working with clang
-  if(g_log.is(Logger::Priority::PRIO_DEBUG)) g_log.debug() << "Raw output from execution:\n" << tmpstring.toAscii().data() << "\n";
+  // FIXME: Ticket-9217 - Commented out for the moment to try and get working
+  // with clang
+  if (g_log.is(Logger::Priority::PRIO_DEBUG))
+    g_log.debug() << "Raw output from execution:\n"
+                  << tmpstring.toAscii().data() << "\n";
   return tmpstring;
 }
 /** This Python helper function converts a list of strings into one
@@ -67,13 +70,11 @@ QString PythonRunner::runPythonCode(const QString & code, bool no_output)
 * @param list string entries
 * @return the strings as a comma separated list in brakets
 */
-const QString PythonRunner::stringList2Tuple(const QStringList & list)
-{
+const QString PythonRunner::stringList2Tuple(const QStringList &list) {
   QString tuple("(");
   QStringList::const_iterator end = list.end();
-  for(QStringList::const_iterator it = list.begin(); it != end; ++it)
-  {
-    tuple += "'"+*it+"',";
+  for (QStringList::const_iterator it = list.begin(); it != end; ++it) {
+    tuple += "'" + *it + "',";
   }
   tuple += ")";
   return tuple;
diff --git a/MantidQt/API/src/PythonThreading.cpp b/MantidQt/API/src/PythonThreading.cpp
index 16956d4e29d69bd87a86b8a9ee9db2aee0781472..4848580021ba53a8a20159cde08b997f7275227d 100644
--- a/MantidQt/API/src/PythonThreading.cpp
+++ b/MantidQt/API/src/PythonThreading.cpp
@@ -35,7 +35,7 @@ void PythonGIL::release() { PyGILState_Release(m_state); }
 RecursivePythonGIL::RecursivePythonGIL() : m_count(0), m_lock() {}
 
 void RecursivePythonGIL::acquire() {
-  if(m_count == 0) {
+  if (m_count == 0) {
     m_lock.acquire();
   }
   m_count += 1;
diff --git a/MantidQt/API/src/QtSignalChannel.cpp b/MantidQt/API/src/QtSignalChannel.cpp
index ea529ef505c2ba496e2d1311c0fd6ec8526fe3fc..f741eb56fdb489831438765ec46a9ae06f941351 100644
--- a/MantidQt/API/src/QtSignalChannel.cpp
+++ b/MantidQt/API/src/QtSignalChannel.cpp
@@ -4,61 +4,50 @@
 
 #include <Poco/Message.h>
 
-namespace MantidQt
-{
-  namespace API
-  {
-
-    /**
-     * Creates a QtSignalChannel. This channel receives
-     * Poco::Message objects and re-emits MantidQt Message objects
-     * with the option to specify that only messages from a defined
-     * source are emitted.
-     * @param source A string specifying a source for the message
-     */
-    QtSignalChannel::QtSignalChannel(const QString & source)
-      :  QObject(), Poco::Channel(), m_source(source)
-    {
-    }
-
-    /**
-     */
-    QtSignalChannel::~QtSignalChannel()
-    {
-    }
-
-    /**
-     * @param source A string specifying the required source for messages
-     * that will be emitted
-     */
-    void QtSignalChannel::setSource(const QString & source)
-    {
-      m_source = source;
-    }
-
-    /**
-     * If the source is set then only messages with a matching source
-     * cause a Qt signal to be emitted. A newline is appended as the
-     * Poco log stream emits the message when a newline is received but doesn't
-     * actually send a newline character
-     * @param msg A Poco message object containing a priority & the string message
-     */
-    void QtSignalChannel::log(const Poco::Message& msg)
-    {
-      if(m_source.isEmpty() || this->source() == msg.getSource().c_str())
-      {
-        emit messageReceived(API::Message(QString::fromStdString(msg.getText() + "\n"), msg.getPriority()));
-      }
-    }
-
-    /*
-     * @param priority An integer that must match the Poco::Message priority enumeration
-     */
-    void QtSignalChannel::setGlobalLogLevel(int priority)
-    {
-      using Mantid::Kernel::Logger;
-      Logger::setLevelForAll(priority);
-    }
-
+namespace MantidQt {
+namespace API {
+
+/**
+ * Creates a QtSignalChannel. This channel receives
+ * Poco::Message objects and re-emits MantidQt Message objects
+ * with the option to specify that only messages from a defined
+ * source are emitted.
+ * @param source A string specifying a source for the message
+ */
+QtSignalChannel::QtSignalChannel(const QString &source)
+    : QObject(), Poco::Channel(), m_source(source) {}
+
+/**
+ */
+QtSignalChannel::~QtSignalChannel() {}
+
+/**
+ * @param source A string specifying the required source for messages
+ * that will be emitted
+ */
+void QtSignalChannel::setSource(const QString &source) { m_source = source; }
+
+/**
+ * If the source is set then only messages with a matching source
+ * cause a Qt signal to be emitted. A newline is appended as the
+ * Poco log stream emits the message when a newline is received but doesn't
+ * actually send a newline character
+ * @param msg A Poco message object containing a priority & the string message
+ */
+void QtSignalChannel::log(const Poco::Message &msg) {
+  if (m_source.isEmpty() || this->source() == msg.getSource().c_str()) {
+    emit messageReceived(API::Message(
+        QString::fromStdString(msg.getText() + "\n"), msg.getPriority()));
   }
 }
+
+/*
+ * @param priority An integer that must match the Poco::Message priority
+ * enumeration
+ */
+void QtSignalChannel::setGlobalLogLevel(int priority) {
+  using Mantid::Kernel::Logger;
+  Logger::setLevelForAll(priority);
+}
+}
+}
diff --git a/MantidQt/API/src/QwtRasterDataMD.cpp b/MantidQt/API/src/QwtRasterDataMD.cpp
index d845f1c5756538461cdc0c92913f09c800b3ec3d..768344967c4126fc4de1facd0e5a1e066c50be0e 100644
--- a/MantidQt/API/src/QwtRasterDataMD.cpp
+++ b/MantidQt/API/src/QwtRasterDataMD.cpp
@@ -108,9 +108,7 @@ void QwtRasterDataMD::setFastMode(bool fast) { this->m_fast = fast; }
  */
 void QwtRasterDataMD::setZerosAsNan(bool val) { this->m_zerosAsNan = val; }
 
-bool QwtRasterDataMD::isZerosAsNan() const {
-  return this->m_zerosAsNan;
-}
+bool QwtRasterDataMD::isZerosAsNan() const { return this->m_zerosAsNan; }
 
 //------------------------------------------------------------------------------------------------------
 /** Set how the signal is normalized
diff --git a/MantidQt/API/src/QwtWorkspaceBinData.cpp b/MantidQt/API/src/QwtWorkspaceBinData.cpp
index bfb8d0c648f76e31d9c463045b66753192420ef8..37e9454000f0557cbe4283efdcd90a9ea2f5d786 100644
--- a/MantidQt/API/src/QwtWorkspaceBinData.cpp
+++ b/MantidQt/API/src/QwtWorkspaceBinData.cpp
@@ -10,8 +10,8 @@
 QwtWorkspaceBinData::QwtWorkspaceBinData(
     const Mantid::API::MatrixWorkspace &workspace, int binIndex,
     const bool logScaleY)
-    : MantidQwtMatrixWorkspaceData(logScaleY), m_binIndex(binIndex), m_X(), m_Y(), m_E(), m_xTitle(), m_yTitle()
-       {
+    : MantidQwtMatrixWorkspaceData(logScaleY), m_binIndex(binIndex), m_X(),
+      m_Y(), m_E(), m_xTitle(), m_yTitle() {
   init(workspace);
 }
 
@@ -38,28 +38,20 @@ Return the x value of data point i
 @param i :: Index
 @return x X value of data point i
 */
-double QwtWorkspaceBinData::getX(size_t i) const {
-  return m_X[i];
-}
+double QwtWorkspaceBinData::getX(size_t i) const { return m_X[i]; }
 
 /**
 Return the y value of data point i
 @param i :: Index
 @return y Y value of data point i
 */
-double QwtWorkspaceBinData::getY(size_t i) const {
-  return m_Y[i];
-}
+double QwtWorkspaceBinData::getY(size_t i) const { return m_Y[i]; }
 
-double QwtWorkspaceBinData::getEX(size_t i) const {
-  return m_X[i];
-}
+double QwtWorkspaceBinData::getEX(size_t i) const { return m_X[i]; }
 
-double QwtWorkspaceBinData::getE(size_t i) const {
-  return m_E[i];
-}
+double QwtWorkspaceBinData::getE(size_t i) const { return m_E[i]; }
 
-//size_t QwtWorkspaceBinData::esize() const { return this->size(); }
+// size_t QwtWorkspaceBinData::esize() const { return this->size(); }
 
 /**
  * @return A string containin the text to use as an X axis label
@@ -78,7 +70,7 @@ QString QwtWorkspaceBinData::getYAxisLabel() const { return m_yTitle; }
 QwtWorkspaceBinData &QwtWorkspaceBinData::
 operator=(const QwtWorkspaceBinData &rhs) {
   if (this != &rhs) {
-    static_cast<MantidQwtMatrixWorkspaceData&>(*this) = rhs;
+    static_cast<MantidQwtMatrixWorkspaceData &>(*this) = rhs;
     m_binIndex = rhs.m_binIndex;
     m_X = rhs.m_X;
     m_Y = rhs.m_Y;
diff --git a/MantidQt/API/src/QwtWorkspaceSpectrumData.cpp b/MantidQt/API/src/QwtWorkspaceSpectrumData.cpp
index e0181252d65568ab3dd71ab3fbd4695c4b803ac0..1c1af2e4584898088869fbac26698cdae9117657 100644
--- a/MantidQt/API/src/QwtWorkspaceSpectrumData.cpp
+++ b/MantidQt/API/src/QwtWorkspaceSpectrumData.cpp
@@ -16,9 +16,10 @@
 QwtWorkspaceSpectrumData::QwtWorkspaceSpectrumData(
     const Mantid::API::MatrixWorkspace &workspace, int wsIndex,
     const bool logScaleY, const bool plotAsDistribution)
-    : MantidQwtMatrixWorkspaceData(logScaleY), m_wsIndex(wsIndex), m_X(workspace.readX(wsIndex)),
-      m_Y(workspace.readY(wsIndex)), m_E(workspace.readE(wsIndex)),
-      m_xTitle(), m_yTitle(), m_isHistogram(workspace.isHistogramData()),
+    : MantidQwtMatrixWorkspaceData(logScaleY), m_wsIndex(wsIndex),
+      m_X(workspace.readX(wsIndex)), m_Y(workspace.readY(wsIndex)),
+      m_E(workspace.readE(wsIndex)), m_xTitle(), m_yTitle(),
+      m_isHistogram(workspace.isHistogramData()),
       m_dataIsNormalized(workspace.isDistribution()), m_binCentres(false),
       m_isDistribution(false) {
   // Actual plotting based on what type of data we have
@@ -28,8 +29,7 @@ QwtWorkspaceSpectrumData::QwtWorkspaceSpectrumData(
 
   m_xTitle = MantidQt::API::PlotAxis(workspace, 0).title();
   m_yTitle = MantidQt::API::PlotAxis((m_dataIsNormalized || m_isDistribution),
-                                     workspace)
-                 .title();
+                                     workspace).title();
 
   // Calculate the min and max values
   calculateYMinAndMax();
@@ -121,7 +121,7 @@ bool QwtWorkspaceSpectrumData::setAsDistribution(bool on) {
 QwtWorkspaceSpectrumData &QwtWorkspaceSpectrumData::
 operator=(const QwtWorkspaceSpectrumData &rhs) {
   if (this != &rhs) {
-    static_cast<MantidQwtMatrixWorkspaceData&>(*this) = rhs;
+    static_cast<MantidQwtMatrixWorkspaceData &>(*this) = rhs;
     m_wsIndex = rhs.m_wsIndex;
     m_X = rhs.m_X;
     m_Y = rhs.m_Y;
diff --git a/MantidQt/API/src/RepoModel.cpp b/MantidQt/API/src/RepoModel.cpp
index b0a890208b9922caf2bbda32c8a7a35ddb9e33bf..f6911c9228733a7a5e3eafe7e811d8ecb751bee7 100644
--- a/MantidQt/API/src/RepoModel.cpp
+++ b/MantidQt/API/src/RepoModel.cpp
@@ -9,7 +9,7 @@
 #include <QIcon>
 #include <QPixmap>
 using namespace MantidQt::API;
-using Mantid::Kernel::ConfigServiceImpl; 
+using Mantid::Kernel::ConfigServiceImpl;
 using Mantid::Kernel::ConfigService;
 #include <QDebug>
 #include <stdexcept>
@@ -23,229 +23,222 @@ using Mantid::Kernel::ConfigService;
 #include <QtConcurrentRun>
 #include <QTextStream>
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("RepoModel");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("RepoModel");
 }
 
 // flag to indicate that the thread is delete thread
-const char * delete_mark = "*DELETE*";
-const char * nofile_flag = "nofile"; 
-
-
-/// Executes the download from ScriptRepository. This function will be executed in a separate thread
-static QString download_thread(Mantid::API::ScriptRepository_sptr & pt, const std::string & path){
-  QString result; 
-  try{
-    pt->download(path);     
-  }catch(Mantid::API::ScriptRepoException & ex){
+const char *delete_mark = "*DELETE*";
+const char *nofile_flag = "nofile";
+
+/// Executes the download from ScriptRepository. This function will be executed
+/// in a separate thread
+static QString download_thread(Mantid::API::ScriptRepository_sptr &pt,
+                               const std::string &path) {
+  QString result;
+  try {
+    pt->download(path);
+  } catch (Mantid::API::ScriptRepoException &ex) {
     QString info = QString::fromStdString(ex.what());
-     // make the exception a nice html message
-    info.replace("\n","</p><p>");
-    return info; 
+    // make the exception a nice html message
+    info.replace("\n", "</p><p>");
+    return info;
   }
-  return result; 
+  return result;
 }
 
-/// Execute the upload from ScriptRepository. This function will be executed in a separate thread
-static QString upload_thread(Mantid::API::ScriptRepository_sptr & pt, 
-                             const std::string & path, const QString & email, 
-                             const QString & author, const QString & comment)
-  {
-  try{
-    pt->upload(path, comment.toStdString(), 
-               author.toStdString(), email.toStdString() );
-  }catch(Mantid::API::ScriptRepoException & ex){
-    QString info = QString::fromStdString(ex.what()); 
-    info.replace("\n","</p><p>"); 
-    return info; 
+/// Execute the upload from ScriptRepository. This function will be executed in
+/// a separate thread
+static QString upload_thread(Mantid::API::ScriptRepository_sptr &pt,
+                             const std::string &path, const QString &email,
+                             const QString &author, const QString &comment) {
+  try {
+    pt->upload(path, comment.toStdString(), author.toStdString(),
+               email.toStdString());
+  } catch (Mantid::API::ScriptRepoException &ex) {
+    QString info = QString::fromStdString(ex.what());
+    info.replace("\n", "</p><p>");
+    return info;
   }
-  return QString(); 
+  return QString();
 }
-/// Execute the remove from ScriptRepository. This function will be executed in a separate thread.
-static QString delete_thread(Mantid::API::ScriptRepository_sptr & pt,
-                             const std::string & path, const QString & email, 
-                             const QString & author, const QString & comment)
-  {
-  try{
-    pt->remove(path, comment.toStdString(), 
-                 author.toStdString(), email.toStdString()); 
-  }catch(Mantid::API::ScriptRepoException & ex){
-    QString info = QString::fromStdString(ex.what()); 
-    info.replace("\n","</p><p>");
-    // it adds the mark *DELETE* so to recognize that it was used to delete an entry.
-    return info+delete_mark; 
+/// Execute the remove from ScriptRepository. This function will be executed in
+/// a separate thread.
+static QString delete_thread(Mantid::API::ScriptRepository_sptr &pt,
+                             const std::string &path, const QString &email,
+                             const QString &author, const QString &comment) {
+  try {
+    pt->remove(path, comment.toStdString(), author.toStdString(),
+               email.toStdString());
+  } catch (Mantid::API::ScriptRepoException &ex) {
+    QString info = QString::fromStdString(ex.what());
+    info.replace("\n", "</p><p>");
+    // it adds the mark *DELETE* so to recognize that it was used to delete an
+    // entry.
+    return info + delete_mark;
   }
-  return delete_mark;  
+  return delete_mark;
 }
 
-
 /*
-  An auxiliary nested class to help RepoModel to rebuild the hierarchical 
-  tree of ScriptRepository. 
-  
+  An auxiliary nested class to help RepoModel to rebuild the hierarchical
+  tree of ScriptRepository.
+
   It will keep track of the path that is the main key to access metadata
-  on ScriptRepository and an auxiliary label to easy the display on a 
+  on ScriptRepository and an auxiliary label to easy the display on a
   user nicer way.
-  
+
 */
-RepoModel::RepoItem::RepoItem(const QString & label,
-                   const QString & path,
-                   RepoItem * parent):
-  m_label(label), keypath(path), parentItem(parent)
-{
-}
-/// destruct all the childItems. 
-RepoModel::RepoItem::~RepoItem()
-{
-    qDeleteAll(childItems);
-}
+RepoModel::RepoItem::RepoItem(const QString &label, const QString &path,
+                              RepoItem *parent)
+    : m_label(label), keypath(path), parentItem(parent) {}
+/// destruct all the childItems.
+RepoModel::RepoItem::~RepoItem() { qDeleteAll(childItems); }
 /** This method is the very responsible to allow the reconstruction of the
-    hierarchical tree, keeping track of the children of one item. 
+    hierarchical tree, keeping track of the children of one item.
  */
-void RepoModel::RepoItem::appendChild(RepoItem *child)
-{
-    childItems.append(child);
+void RepoModel::RepoItem::appendChild(RepoItem *child) {
+  childItems.append(child);
 }
 
-/** Gives access to the row_th children of RepoItem. Note that 
-    the row can not be greater than RepoModel::childCount(). 
+/** Gives access to the row_th children of RepoItem. Note that
+    the row can not be greater than RepoModel::childCount().
 
     But we do not test it, because this method will be called
-    indirectly from the QView, and will never go beyond that value. 
-    
+    indirectly from the QView, and will never go beyond that value.
+
     @param row: Number between 0 and RepoModel::childCount().
 
     @return The pointer to the row_th children.
-    
+
  */
-RepoModel::RepoItem * RepoModel::RepoItem::child(int row) const
-{  
-    return childItems.value(row);
+RepoModel::RepoItem *RepoModel::RepoItem::child(int row) const {
+  return childItems.value(row);
 }
 
-/** Return the number of children that this entry may find. 
+/** Return the number of children that this entry may find.
     @return Number of children
  */
-int RepoModel::RepoItem::childCount() const
-{
-    return childItems.count();
-}
-/** Provide the row number of this entry related to its parent. 
+int RepoModel::RepoItem::childCount() const { return childItems.count(); }
+/** Provide the row number of this entry related to its parent.
     @return It's child position.
  */
-int RepoModel::RepoItem::row() const
-{
-    if (parentItem)
-        return parentItem->childItems.indexOf(const_cast<RepoItem*>(this));
-    return 0;
+int RepoModel::RepoItem::row() const {
+  if (parentItem)
+    return parentItem->childItems.indexOf(const_cast<RepoItem *>(this));
+  return 0;
 }
-/** Remove the given child from the childItems. Used to allow removing rows from the view*/
-bool RepoModel::RepoItem::removeChild(int row){
+/** Remove the given child from the childItems. Used to allow removing rows from
+ * the view*/
+bool RepoModel::RepoItem::removeChild(int row) {
   if (row < 0 || row >= childCount())
     return false;
-  
-  childItems.removeAt(row); 
+
+  childItems.removeAt(row);
   return true;
 }
 
 //////////////////////////////////////////////////
 // MODEL
 ///////////////////////////////////////////////////
-/** The constructor of RepoModel. It is intended to have just one model and to pass 
-    on through shared pointer. To enforce this, the copy constructor is disabled. 
-    It will construct the hierarchical tree of ScriptRepository through 
+/** The constructor of RepoModel. It is intended to have just one model and to
+   pass
+    on through shared pointer. To enforce this, the copy constructor is
+   disabled.
+    It will construct the hierarchical tree of ScriptRepository through
     the setuptModelData.
  */
-RepoModel::RepoModel(QObject *parent):
-  QAbstractItemModel(parent)  
-{
-  ConfigServiceImpl & config = ConfigService::Instance();
+RepoModel::RepoModel(QObject *parent) : QAbstractItemModel(parent) {
+  ConfigServiceImpl &config = ConfigService::Instance();
   repo_path = QString::fromStdString(config.getString("ScriptLocalRepository"));
   rootItem = new RepoItem("/");
   using Mantid::API::ScriptRepositoryFactory;
   using Mantid::API::ScriptRepository_sptr;
   using Mantid::API::ScriptRepository;
   repo_ptr = ScriptRepositoryFactory::Instance().create("ScriptRepositoryImpl");
-  connect(&download_watcher, SIGNAL(finished()), this, SLOT(downloadFinished()));
+  connect(&download_watcher, SIGNAL(finished()), this,
+          SLOT(downloadFinished()));
   connect(&upload_watcher, SIGNAL(finished()), this, SLOT(uploadFinished()));
-  uploading_path = nofile_flag; 
+  uploading_path = nofile_flag;
   downloading_path = nofile_flag;
   setupModelData(rootItem);
 }
 
 /// desctructor of repomodel.
-RepoModel::~RepoModel()
-{
-     delete rootItem;
-}
-/**Provide access to the data through the defined QAbstractItemModel definition. 
-   The index parameter defines how to access the corresponded data while the role
-   define the kind of information desired from RepoModel. This method will be queried
-   from QView in order to populate the view. 
-
-   From the index.internalPointer the RepoModel will have access to the path, 
-   which uniquely define its entry on ScriptRepository. 
-
-   The RepoModel defines 4 columns: 
+RepoModel::~RepoModel() { delete rootItem; }
+/**Provide access to the data through the defined QAbstractItemModel definition.
+   The index parameter defines how to access the corresponded data while the
+   role
+   define the kind of information desired from RepoModel. This method will be
+   queried
+   from QView in order to populate the view.
+
+   From the index.internalPointer the RepoModel will have access to the path,
+   which uniquely define its entry on ScriptRepository.
+
+   The RepoModel defines 4 columns:
     - Path
     - Status
     - AutoUpdate
     - Delete
-   
-   The path, provides the name of the file. The status, give information on the ScriptRepository
-   entries. Currently, an entry may be found on the following states: 
-     - LOCAL_ONLY: The file only exists locally. 
-     - REMTOE_ONLY: The file has not been downloaded. 
+
+   The path, provides the name of the file. The status, give information on the
+   ScriptRepository
+   entries. Currently, an entry may be found on the following states:
+     - LOCAL_ONLY: The file only exists locally.
+     - REMTOE_ONLY: The file has not been downloaded.
      - REMOTE_CHANGED: A new version of the file is available.
-     - LOCAL_CHANGED: The file has been changed from the original one. 
-     - BOTH_CHANGED: Locally and remotelly changed. 
-     - UPDATED: The remote and local file are identical. 
-   
-   The AutoUpdate allow to flag the entries to receive the updates automatically when new files 
+     - LOCAL_CHANGED: The file has been changed from the original one.
+     - BOTH_CHANGED: Locally and remotelly changed.
+     - UPDATED: The remote and local file are identical.
+
+   The AutoUpdate allow to flag the entries to receive the updates automatically
+   when new files
    are available at the central repository.
 
-   The delete column will return a string "protected" or "deletable" that will be used to know if it
-   can be deleted or not. For the current version, folders are protected, and files are deletable.
+   The delete column will return a string "protected" or "deletable" that will
+   be used to know if it
+   can be deleted or not. For the current version, folders are protected, and
+   files are deletable.
 
-   The repomodel will react to the following roles: 
-     - DisplayRole: to provide the main information. 
-     - DecorationRole: to provide icons to make easier and fancier to identify the files and folders. 
-     - ToolTipRole: to provide user help to interact with this class. 
+   The repomodel will react to the following roles:
+     - DisplayRole: to provide the main information.
+     - DecorationRole: to provide icons to make easier and fancier to identify
+   the files and folders.
+     - ToolTipRole: to provide user help to interact with this class.
  */
-QVariant RepoModel::data(const QModelIndex &index, int role) const
-{
+QVariant RepoModel::data(const QModelIndex &index, int role) const {
   using namespace Mantid::API;
   if (!index.isValid())
     return QVariant();
-  RepoItem *item = static_cast<RepoItem*>(index.internalPointer());
-  try{
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
+  try {
     QString path = item->path();
-    Mantid::API::ScriptInfo inf ; 
+    Mantid::API::ScriptInfo inf;
     Mantid::API::SCRIPTSTATUS status;
-    // return the data for the display role    
-    if (role == Qt::DisplayRole){
-      switch(index.column()){
+    // return the data for the display role
+    if (role == Qt::DisplayRole) {
+      switch (index.column()) {
       case 0: // return the label (the path of the file/folder)
-        return item->label(); 
-        break; 
+        return item->label();
+        break;
       case 1: // ask for the status
         if (isDownloading(index))
           return downloadSt();
         if (isUploading(index))
           return uploadSt();
         status = repo_ptr->fileStatus(path.toStdString());
-        return fromStatus(status); 
-        break; 
-      case 2:// autoupdate option
-    	status = repo_ptr->fileStatus(path.toStdString());
-    	if (status == REMOTE_ONLY || status == LOCAL_ONLY)
-    		return QVariant();
-        inf = repo_ptr->fileInfo(path.toStdString()); 
-        return inf.auto_update?QString("true"):QString("false");
+        return fromStatus(status);
         break;
-      case 3:// delete action
+      case 2: // autoupdate option
+        status = repo_ptr->fileStatus(path.toStdString());
+        if (status == REMOTE_ONLY || status == LOCAL_ONLY)
+          return QVariant();
+        inf = repo_ptr->fileInfo(path.toStdString());
+        return inf.auto_update ? QString("true") : QString("false");
+        break;
+      case 3: // delete action
         inf = repo_ptr->fileInfo(path.toStdString());
         if (inf.directory)
           return PROTECTEDENTRY;
@@ -256,808 +249,819 @@ QVariant RepoModel::data(const QModelIndex &index, int role) const
         break;
       }
     }
-    
+
     // return the data for the DecorationRole
-    if (role == Qt::DecorationRole){
-      if (index.column() == 0){
+    if (role == Qt::DecorationRole) {
+      if (index.column() == 0) {
         inf = repo_ptr->fileInfo(path.toStdString());
-        if (inf.directory){
+        if (inf.directory) {
           status = repo_ptr->fileStatus(path.toStdString());
           if (status == Mantid::API::REMOTE_ONLY)
-            return QIcon::fromTheme("folder-remote",QIcon(QPixmap(":/win/folder-remote")));
+            return QIcon::fromTheme("folder-remote",
+                                    QIcon(QPixmap(":/win/folder-remote")));
           else
             return QIcon::fromTheme("folder", QIcon(QPixmap(":/win/folder")));
-        }
-        else{
+        } else {
           int pos = QString(path).lastIndexOf('.');
           if (pos < 0)
-            return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown"))); 
-          if (path.contains("readme",Qt::CaseInsensitive))
-            return QIcon::fromTheme("text-x-readme", QIcon(QPixmap(":/win/txt_file.png"))); 
-          
-          QString extension = QString(path).remove(0,pos);
-          if (extension == ".cpp" || extension == ".CPP" || extension == ".c" || extension == ".C")
-            return QIcon::fromTheme("text-x-c++", QIcon(QPixmap(":/win/unknown")));
+            return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
+          if (path.contains("readme", Qt::CaseInsensitive))
+            return QIcon::fromTheme("text-x-readme",
+                                    QIcon(QPixmap(":/win/txt_file.png")));
+
+          QString extension = QString(path).remove(0, pos);
+          if (extension == ".cpp" || extension == ".CPP" || extension == ".c" ||
+              extension == ".C")
+            return QIcon::fromTheme("text-x-c++",
+                                    QIcon(QPixmap(":/win/unknown")));
           else if (extension == ".py" || extension == ".PY")
-            return QIcon::fromTheme("text-x-python", QIcon(QPixmap(":/win/text-x-python"))); 
+            return QIcon::fromTheme("text-x-python",
+                                    QIcon(QPixmap(":/win/text-x-python")));
           else if (extension == ".ui")
-            return QIcon::fromTheme("document", QIcon(QPixmap(":/win/document")));
-          else if (extension == ".docx" || extension == ".doc" || extension == ".odf")
-            return QIcon::fromTheme("x-office-document", QIcon(QPixmap(":/win/office-document"))); 
+            return QIcon::fromTheme("document",
+                                    QIcon(QPixmap(":/win/document")));
+          else if (extension == ".docx" || extension == ".doc" ||
+                   extension == ".odf")
+            return QIcon::fromTheme("x-office-document",
+                                    QIcon(QPixmap(":/win/office-document")));
           else if (extension == ".pdf")
-            return QIcon::fromTheme("application-pdf", QIcon(QPixmap(":/win/file_pdf"))); 
+            return QIcon::fromTheme("application-pdf",
+                                    QIcon(QPixmap(":/win/file_pdf")));
           else
-            return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));           
-        }        
-      }        
-    }// end decorationRole
-    
+            return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
+        }
+      }
+    } // end decorationRole
+
     // tool tip role
-    if (role == Qt::ToolTipRole){
-      if (index.column() == 1){
+    if (role == Qt::ToolTipRole) {
+      if (index.column() == 1) {
         if (isDownloading(index))
           return "Downloading... Be patient.";
         if (isUploading(index))
           return "Uploading... Be patient.";
         status = repo_ptr->fileStatus(path.toStdString());
         inf = repo_ptr->fileInfo(path.toStdString());
-        switch(status){
-          
+        switch (status) {
+
         case REMOTE_ONLY:
-          return (inf.directory)?"Click here to download this folder and all its files"
-            :"Click here to download this file";
-          break;         
+          return (inf.directory)
+                     ? "Click here to download this folder and all its files"
+                     : "Click here to download this file";
+          break;
         case BOTH_UNCHANGED:
-          return (inf.directory)? "This folder is up-to-date" : "This file is up-to-date"; 
+          return (inf.directory) ? "This folder is up-to-date"
+                                 : "This file is up-to-date";
           break;
-        case LOCAL_CHANGED:         
+        case LOCAL_CHANGED:
           return "Click here to publish your changes";
         case REMOTE_CHANGED:
-          return (inf.directory)?
-                 "There is a new version of the files inside this folder. Click here to install them.":
-                 "There is a new version of this file available. Click here to install it.";
+          return (inf.directory) ? "There is a new version of the files inside "
+                                   "this folder. Click here to install them."
+                                 : "There is a new version of this file "
+                                   "available. Click here to install it.";
         case BOTH_CHANGED:
-          return (inf.directory)?
-                 "Files in this folder may have changed both locally and remotely.\nClick here to install the remote version, "
-                   "a backup of the local version will also be created.":
-                 "This file may have changed both locally and remotely.\nClick here to install the remote version, "
-                   "a backup of the local version will also be created.";
+          return (inf.directory)
+                     ? "Files in this folder may have changed both locally and "
+                       "remotely.\nClick here to install the remote version, "
+                       "a backup of the local version will also be created."
+                     : "This file may have changed both locally and "
+                       "remotely.\nClick here to install the remote version, "
+                       "a backup of the local version will also be created.";
           break;
         case LOCAL_ONLY:
           return "Click here to share this file with the Mantid community!";
-          
         }
-      }else if (index.column() == 2){
-        return "Enable or disable this item to be downloaded automatically when new versions will be available";
-      }else if (index.column() == 3){ 
+      } else if (index.column() == 2) {
+        return "Enable or disable this item to be downloaded automatically "
+               "when new versions will be available";
+      } else if (index.column() == 3) {
         if (isUploading(index))
           return "Connection busy... Be patient.";
         inf = repo_ptr->fileInfo(path.toStdString());
         if (inf.directory)
-          return QVariant(); 
-        status = repo_ptr->fileStatus(path.toStdString()); 
+          return QVariant();
+        status = repo_ptr->fileStatus(path.toStdString());
         if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
           return QVariant();
-        return "Click here to delete this file from the Central Repository"; 
+        return "Click here to delete this file from the Central Repository";
       }
-    }// end tool tip
-  }catch(Mantid::API::ScriptRepoException & ex){
-    handleExceptions(ex,"",false);
+    } // end tool tip
+  } catch (Mantid::API::ScriptRepoException &ex) {
+    handleExceptions(ex, "", false);
   }
-    return QVariant(); 
+  return QVariant();
 }
 
-/** Match the Mantid::API::SCRIPTSTATUS to a string for the user to understand. 
+/** Match the Mantid::API::SCRIPTSTATUS to a string for the user to understand.
  *
  *   @param status: the SCRIPTSTATUS
- *   @return The string that defines the status. 
+ *   @return The string that defines the status.
  */
-const QString & RepoModel::fromStatus(Mantid::API::SCRIPTSTATUS status) const {
+const QString &RepoModel::fromStatus(Mantid::API::SCRIPTSTATUS status) const {
   using namespace Mantid::API;
-  switch(status){
+  switch (status) {
   case BOTH_UNCHANGED:
-    return updatedSt(); 
+    return updatedSt();
   case REMOTE_ONLY:
     return remoteOnlySt();
   case LOCAL_ONLY:
-    return localOnlySt(); 
+    return localOnlySt();
   case REMOTE_CHANGED:
-    return remoteChangedSt(); 
+    return remoteChangedSt();
   case LOCAL_CHANGED:
-    return localChangedSt(); 
+    return localChangedSt();
   case BOTH_CHANGED:
-    return bothChangedSt(); 
+    return bothChangedSt();
   }
-  return bothChangedSt(); 
+  return bothChangedSt();
 }
 
-/** The ScriptRepository allows to download and upload file and folders. And to 
- * configure the AutoUpdate option for the entries. These actions will be available
+/** The ScriptRepository allows to download and upload file and folders. And to
+ * configure the AutoUpdate option for the entries. These actions will be
+ *available
  * through the setData method.
- * 
+ *
  * The setData will recognize only the EditRole as a valid Role.
- * The RepoModel will recognize the following entries. The path can not be edited
- * (column 0) is not editable. the AutoUpdate flag (column 2) will accept the following 
- * actions: setTrue and setFalse, to enable or disable the automatic update. 
- * 
- * The Status (column 1) will accept the following actions: Download and Upload. 
- * 
- * 
+ * The RepoModel will recognize the following entries. The path can not be
+ *edited
+ * (column 0) is not editable. the AutoUpdate flag (column 2) will accept the
+ *following
+ * actions: setTrue and setFalse, to enable or disable the automatic update.
+ *
+ * The Status (column 1) will accept the following actions: Download and Upload.
+ *
+ *
  *
  */
-bool RepoModel::setData(const QModelIndex & index, const QVariant & value, 
-                        int role){
+bool RepoModel::setData(const QModelIndex &index, const QVariant &value,
+                        int role) {
   if (!index.isValid())
-    return false; 
+    return false;
   if (role != Qt::EditRole)
     // only EditRole is acceptable for the role
-    return false; 
+    return false;
   if (index.column() == 0)
     // the path can not be changed
-    return false; 
+    return false;
   int count_changed = 0;
-  RepoItem * item = static_cast<RepoItem*>(index.internalPointer());
-  std::string path = item->path().toStdString(); 
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
+  std::string path = item->path().toStdString();
 
   bool ret = false;
   // get the action
   QString action = value.toString();
-  if (index.column() ==2){// set auto update   
-    bool option; 
+  if (index.column() == 2) { // set auto update
+    bool option;
     if (action == "setTrue")
-      option = true; 
+      option = true;
     else if (action == "setFalse")
-      option = false; 
+      option = false;
     else
-      return false; // only setTrue and setFalse are allowed values for set auto update.
+      return false; // only setTrue and setFalse are allowed values for set auto
+                    // update.
     count_changed = repo_ptr->setAutoUpdate(path, option);
-    ret = true; 
+    ret = true;
   }
-  
-  if (index.column() == 1){ // trigger actions: Download and Upload
-    if (action == "Download"){
-      if (!download_threads.isFinished()){
-        QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-        QMessageBox::information(father, "Wait", "Downloading... "); 
+
+  if (index.column() == 1) { // trigger actions: Download and Upload
+    if (action == "Download") {
+      if (!download_threads.isFinished()) {
+        QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+        QMessageBox::information(father, "Wait", "Downloading... ");
         return false;
       }
       downloading_path = QString::fromStdString(path);
       download_index = index;
       emit executingThread(true);
       download_threads = QtConcurrent::run(download_thread, repo_ptr, path);
-      download_watcher.setFuture(download_threads);       
+      download_watcher.setFuture(download_threads);
       ret = true;
-    }else if (action == "Upload"){
-      if (!upload_threads.isFinished()){
-        QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-        QMessageBox::information(father, "Wait", "Uploading... "); 
+    } else if (action == "Upload") {
+      if (!upload_threads.isFinished()) {
+        QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+        QMessageBox::information(father, "Wait", "Uploading... ");
         return false;
       }
 
-      QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-      if (repo_ptr->fileInfo(path).directory){
-        QMessageBox::information(father, 
-                                 "Not Supported", 
-                                 "The current version does not support uploading recursively. Please, upload one-by-one"); 
-        return false; 
+      QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+      if (repo_ptr->fileInfo(path).directory) {
+        QMessageBox::information(father, "Not Supported",
+                                 "The current version does not support "
+                                 "uploading recursively. Please, upload "
+                                 "one-by-one");
+        return false;
       };
 
-      UploadForm * form = new UploadForm(QString::fromStdString(path), father);
-      QSettings settings; 
-      settings.beginGroup("Mantid/ScriptRepository"); 
-      QString email = settings.value("UploadEmail",QString()).toString();
-      QString author = settings.value("UploadAuthor",QString()).toString();
-      bool lastChk = settings.value("UploadSaveInfo",false).toBool();
+      UploadForm *form = new UploadForm(QString::fromStdString(path), father);
+      QSettings settings;
+      settings.beginGroup("Mantid/ScriptRepository");
+      QString email = settings.value("UploadEmail", QString()).toString();
+      QString author = settings.value("UploadAuthor", QString()).toString();
+      bool lastChk = settings.value("UploadSaveInfo", false).toBool();
       if (!email.isEmpty())
-        form->setEmail(email); 
+        form->setEmail(email);
       if (!author.isEmpty())
         form->setAuthor(author);
       form->lastSaveOption(lastChk);
-      if (form->exec()){
-        settings.setValue("UploadEmail",form->saveInfo()?form->email():""); 
-        settings.setValue("UploadAuthor",form->saveInfo()?form->author():"");
-        settings.setValue("UploadSaveInfo",form->saveInfo()); 
-
-        qDebug() << "Uploading... "<< QString::fromStdString(path) << form->comment()
-                   << form->author() << form->email() << endl;
-        uploading_path = QString::fromStdString(path); 
+      if (form->exec()) {
+        settings.setValue("UploadEmail", form->saveInfo() ? form->email() : "");
+        settings.setValue("UploadAuthor",
+                          form->saveInfo() ? form->author() : "");
+        settings.setValue("UploadSaveInfo", form->saveInfo());
+
+        qDebug() << "Uploading... " << QString::fromStdString(path)
+                 << form->comment() << form->author() << form->email() << endl;
+        uploading_path = QString::fromStdString(path);
         upload_index = index;
         emit executingThread(true);
-        upload_threads = QtConcurrent::run(upload_thread, repo_ptr, path, form->email(), 
-                                           form->author(), form->comment()); 
-        upload_watcher.setFuture(upload_threads); 
+        upload_threads =
+            QtConcurrent::run(upload_thread, repo_ptr, path, form->email(),
+                              form->author(), form->comment());
+        upload_watcher.setFuture(upload_threads);
         ret = true;
-      }else{
-        ret = false; 
+      } else {
+        ret = false;
       }
-      settings.endGroup(); 
-      delete form; 
-    }   
+      settings.endGroup();
+      delete form;
+    }
   }
 
-
-  if (index.column() == 3){ // trigger actions: delete
+  if (index.column() == 3) { // trigger actions: delete
     using namespace Mantid::API;
     if (action != "delete")
       return false;
     // used to show qwidgets
-    QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-    
+    QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+
     SCRIPTSTATUS status = repo_ptr->fileStatus(path);
 
-    /* We do not remove files directly from the central repository, but, usually, 
-       this option is not available from the GUI (no button), so, just return false*/
+    /* We do not remove files directly from the central repository, but,
+       usually,
+       this option is not available from the GUI (no button), so, just return
+       false*/
     if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
       return false;
-    
+
     // it requires a new connection to the uploader server
-    if (!upload_threads.isFinished()){
-      QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-      QMessageBox::information(father, "Wait", "The connection with the server is busy now, wait a while and try again. "); 
+    if (!upload_threads.isFinished()) {
+      QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+      QMessageBox::information(father, "Wait", "The connection with the server "
+                                               "is busy now, wait a while and "
+                                               "try again. ");
       return false;
     }
-    //query the user if he wants to delete only locally or remote as well.
-    DeleteQueryBox * box = new DeleteQueryBox(QString::fromStdString(path), father);
-    
-    if (box->exec() != QMessageBox::Yes){
+    // query the user if he wants to delete only locally or remote as well.
+    DeleteQueryBox *box =
+        new DeleteQueryBox(QString::fromStdString(path), father);
+
+    if (box->exec() != QMessageBox::Yes) {
       // the user gave up deleting this entry, release memory
-      delete box; 
+      delete box;
       box = 0;
-      return false; 
+      return false;
     }
 
     // get the options from the user
-    QString comment(box->comment()); 
+    QString comment(box->comment());
     { // release memory
-      delete box; 
-      box = 0; 
+      delete box;
+      box = 0;
     }
-    
+
     // remove from central repository
     // currently, directories can not be deleted recursively
-    if (repo_ptr->fileInfo(path).directory){
-      QMessageBox::information(father, 
-                               "Not Supported", 
-                               "The current version does not support deleting from the central repository recursively. Please, delete one-by-one"); 
-      return false; 
+    if (repo_ptr->fileInfo(path).directory) {
+      QMessageBox::information(father, "Not Supported",
+                               "The current version does not support deleting "
+                               "from the central repository recursively. "
+                               "Please, delete one-by-one");
+      return false;
     };
-    
+
     // check if the reason was given and it is valid
-    if (comment.isEmpty()){
-      QMessageBox::information(father, "Not Allowed",
-                               "You are not allowed to delete one file without a reason"); 
-      return false; 
+    if (comment.isEmpty()) {
+      QMessageBox::information(
+          father, "Not Allowed",
+          "You are not allowed to delete one file without a reason");
+      return false;
     }
-    
+
     // we will not allow them to remove if they have no e-mail and author saved
-    QSettings settings; 
-    settings.beginGroup("Mantid/ScriptRepository"); 
-    QString email = settings.value("UploadEmail",QString()).toString();
-    QString author = settings.value("UploadAuthor",QString()).toString();
-    settings.endGroup(); 
-    
-    if (author.isEmpty() || email.isEmpty()){
+    QSettings settings;
+    settings.beginGroup("Mantid/ScriptRepository");
+    QString email = settings.value("UploadEmail", QString()).toString();
+    QString author = settings.value("UploadAuthor", QString()).toString();
+    settings.endGroup();
+
+    if (author.isEmpty() || email.isEmpty()) {
       QMessageBox::information(father, "You have not uploaded this file",
-                               "You are not allowed to remove files that you have not updloaded through ScriptRepository");
-      return false; 
+                               "You are not allowed to remove files that you "
+                               "have not updloaded through ScriptRepository");
+      return false;
     }
-    
+
     // we have all we need to delete from the central repository
-    // execute the delete in a separate thread, we will use the upload established way, because,
+    // execute the delete in a separate thread, we will use the upload
+    // established way, because,
     // it will connect to the same server to delete.
     upload_index = index;
     uploading_path = QString::fromStdString(path);
     emit executingThread(true);
-    upload_threads = QtConcurrent::run(delete_thread, repo_ptr, path, 
-                                       email, author, comment);
-    upload_watcher.setFuture(upload_threads); 
+    upload_threads = QtConcurrent::run(delete_thread, repo_ptr, path, email,
+                                       author, comment);
+    upload_watcher.setFuture(upload_threads);
     ret = true;
-  }// end delete action
+  } // end delete action
+
+  if (ret)
+    emit dataChanged(index, this->index(count_changed, 0, index));
 
-  if (ret)       
-    emit dataChanged(index, this->index(count_changed,0,index));
-  
   return ret;
 }
 
-
-/**Define the interaction with the user allowed. 
+/**Define the interaction with the user allowed.
  *
  * Currently the user is allowed to select the path column, to collapse,
  * expand the folders, and he is allowed to submit actions to the columns
- * 1 and 2 (download/upload triggers) and (auto update flag). 
- * 
+ * 1 and 2 (download/upload triggers) and (auto update flag).
+ *
  */
-Qt::ItemFlags RepoModel::flags(const QModelIndex &index) const
-{
+Qt::ItemFlags RepoModel::flags(const QModelIndex &index) const {
   if (!index.isValid())
-    return 0 ;
+    return 0;
   if (index.column() == 0)
-    return  QAbstractItemModel::flags(index); 
+    return QAbstractItemModel::flags(index);
   // define that setData will accept the EditRole.
   return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
 }
 
-/** Return the header for the columns. 
- * The RepoModel defines 4 columns with the following information: 
+/** Return the header for the columns.
+ * The RepoModel defines 4 columns with the following information:
  *  - Path
  *  - Status
  *  - AutoUpdate
  *  - Delete
  *  @param section: The column number
  *  @param orientation: It will accept only the Horizontal orientation.
- *  @param role: Only the DisplayRole will be accepted. It will not provide tool tip 
+ *  @param role: Only the DisplayRole will be accepted. It will not provide tool
+ *tip
  *  for the headers.
- * 
+ *
  *  @return The title for the columns.
  */
-QVariant RepoModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
-  if (orientation == Qt::Horizontal && role == Qt::DisplayRole){
-    switch(section){
+QVariant RepoModel::headerData(int section, Qt::Orientation orientation,
+                               int role) const {
+  if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
+    switch (section) {
     case 0:
       return "Path";
     case 1:
-      return "Status"; 
-    case 2: 
+      return "Status";
+    case 2:
       return "AutoUpdate";
-    case 3: 
+    case 3:
       return "Delete";
     default:
       return QVariant();
     }
-
   }
-    return QVariant();
+  return QVariant();
 }
 
-/** An hierarchical structure is able to define any point giving the parent, the row and the 
- *  column. This method is ment to be used to the View to iterate through the model. 
- *  
- * @param row: the index of the children  (file/folder) under the given folder(parent)
- * @param column: The related column (repomodel defines 3 (path, status, autoupdate)
- * @param parent: The QModelIndex parent which refers to the parent folder. 
- * 
- * @return The QModelIndex that allows to retrieve the information of the desired child. 
+/** An hierarchical structure is able to define any point giving the parent, the
+ *row and the
+ *  column. This method is ment to be used to the View to iterate through the
+ *model.
+ *
+ * @param row: the index of the children  (file/folder) under the given
+ *folder(parent)
+ * @param column: The related column (repomodel defines 3 (path, status,
+ *autoupdate)
+ * @param parent: The QModelIndex parent which refers to the parent folder.
+ *
+ * @return The QModelIndex that allows to retrieve the information of the
+ *desired child.
  */
-QModelIndex RepoModel::index(int row, int column, const QModelIndex &parent) const
-{
-  // check if the row and column are allowed, 
-  // for example, it will not accept column == 3, or row = 1 
-  // for parent that refers to file and not to folder. 
-    if (!hasIndex(row, column, parent))
-        return QModelIndex();
-    // retrieve the pointer ot the RepoItem from the parent
-    RepoItem *parentItem;   
-    if (!parent.isValid())
-        parentItem = rootItem;
-    else
-        parentItem = static_cast<RepoItem*>(parent.internalPointer());
+QModelIndex RepoModel::index(int row, int column,
+                             const QModelIndex &parent) const {
+  // check if the row and column are allowed,
+  // for example, it will not accept column == 3, or row = 1
+  // for parent that refers to file and not to folder.
+  if (!hasIndex(row, column, parent))
+    return QModelIndex();
+  // retrieve the pointer ot the RepoItem from the parent
+  RepoItem *parentItem;
+  if (!parent.isValid())
+    parentItem = rootItem;
+  else
+    parentItem = static_cast<RepoItem *>(parent.internalPointer());
 
-    // given the row, we can find the childItem from the RepoItem::child method.
-    RepoItem *childItem = parentItem->child(row);
+  // given the row, we can find the childItem from the RepoItem::child method.
+  RepoItem *childItem = parentItem->child(row);
 
-    if (childItem)
-        return createIndex(row, column, childItem);
-    else
-        return QModelIndex();
+  if (childItem)
+    return createIndex(row, column, childItem);
+  else
+    return QModelIndex();
 }
 
-/** Provide the parent of a given entry, through the QModelIndex abstraction. 
+/** Provide the parent of a given entry, through the QModelIndex abstraction.
  *
- * @param index: The QModelIndex that identifies one entry. 
+ * @param index: The QModelIndex that identifies one entry.
  * @return A QModelIndex that indentifies the parent of the given index.
  */
-QModelIndex RepoModel::parent(const QModelIndex &index) const
-{
-    if (!index.isValid())
-        return QModelIndex();
-    // the child is the RepoItem pointed by the index.
-    RepoItem *childItem = static_cast<RepoItem*>(index.internalPointer());
-    // the parent is the parent of the RepoItem.
-    RepoItem *parentItem = childItem->parent();
-    // the root item does not have a parent
-    if (parentItem == rootItem)
-        return QModelIndex();
-    // create the index and return
-    return createIndex(parentItem->row(), 0, parentItem);
+QModelIndex RepoModel::parent(const QModelIndex &index) const {
+  if (!index.isValid())
+    return QModelIndex();
+  // the child is the RepoItem pointed by the index.
+  RepoItem *childItem = static_cast<RepoItem *>(index.internalPointer());
+  // the parent is the parent of the RepoItem.
+  RepoItem *parentItem = childItem->parent();
+  // the root item does not have a parent
+  if (parentItem == rootItem)
+    return QModelIndex();
+  // create the index and return
+  return createIndex(parentItem->row(), 0, parentItem);
 }
 /** Count how many file/folders are direct children of the given folder,
- * through the abstraction of QModelIndex. 
- * 
- * @param parent: the index to the folder. 
+ * through the abstraction of QModelIndex.
+ *
+ * @param parent: the index to the folder.
  * @return the number of children of the given folder.
  */
-int RepoModel::rowCount(const QModelIndex &parent) const
-{
-    RepoItem *parentItem;
+int RepoModel::rowCount(const QModelIndex &parent) const {
+  RepoItem *parentItem;
 
-    if (parent.column() > 0)
-      return 0; // there are rows defined only of the column 0
+  if (parent.column() > 0)
+    return 0; // there are rows defined only of the column 0
 
-    if (!parent.isValid())
-        parentItem = rootItem;
-    else
-        parentItem = static_cast<RepoItem*>(parent.internalPointer());
-    // return the number of children 
-    return parentItem->childCount();
+  if (!parent.isValid())
+    parentItem = rootItem;
+  else
+    parentItem = static_cast<RepoItem *>(parent.internalPointer());
+  // return the number of children
+  return parentItem->childCount();
 }
 
-/** Return the number of columns defined for the given index. 
- * But, for all the index, the number of columns will be always 3. 
+/** Return the number of columns defined for the given index.
+ * But, for all the index, the number of columns will be always 3.
  * (path, status, autoupdate)
  *
  * @return 4.
  */
-int RepoModel::columnCount(const QModelIndex &/*parent*/) const
-{
-  return 4;
-}
+int RepoModel::columnCount(const QModelIndex & /*parent*/) const { return 4; }
 
 /** Return the description of the file for a defined entry
  **/
-QString RepoModel::fileDescription(const QModelIndex & index){
-   RepoItem * item = static_cast<RepoItem*>(index.internalPointer());
-   if (!item)
-     return ""; 
-   QString desc;
-   try{
-     desc = QString::fromStdString(repo_ptr->description(item->path().toStdString()));
-   }catch(...){
-     // just ignore
-   }
-   return desc;
+QString RepoModel::fileDescription(const QModelIndex &index) {
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
+  if (!item)
+    return "";
+  QString desc;
+  try {
+    desc = QString::fromStdString(
+        repo_ptr->description(item->path().toStdString()));
+  } catch (...) {
+    // just ignore
+  }
+  return desc;
 }
 
-QString RepoModel::author(const QModelIndex & index){
- RepoItem * item = static_cast<RepoItem*>(index.internalPointer());
- QString author = "Not defined";
-   if (!item)
-     return author; 
-   try{
-     author = QString::fromStdString(repo_ptr->info(item->path().toStdString()).author);
-   }catch(...){
-     // just ignore
-   }
-   return author;  
+QString RepoModel::author(const QModelIndex &index) {
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
+  QString author = "Not defined";
+  if (!item)
+    return author;
+  try {
+    author = QString::fromStdString(
+        repo_ptr->info(item->path().toStdString()).author);
+  } catch (...) {
+    // just ignore
+  }
+  return author;
 }
-/** Return the operative system file path if it exists. 
+/** Return the operative system file path if it exists.
     otherwise it returns an empty string
     @param index: to find the entry
     @return The operative system path or empty string
 */
-QString RepoModel::filePath(const QModelIndex & index){
-   RepoItem * item = static_cast<RepoItem*>(index.internalPointer());
-   //   qDebug() << "Get file path from : " <<  item->path()<< endl; 
-   Mantid::API::SCRIPTSTATUS state = repo_ptr->fileStatus(item->path().toStdString());
-   
-   if (state == Mantid::API::REMOTE_ONLY)
-     return ""; 
-   Mantid::API::ScriptInfo info = repo_ptr->fileInfo(item->path().toStdString());   
-   if (info.directory)
-     return ""; 
-   QString path = repo_path + "/" + item->path(); 
-   return path;
+QString RepoModel::filePath(const QModelIndex &index) {
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
+  //   qDebug() << "Get file path from : " <<  item->path()<< endl;
+  Mantid::API::SCRIPTSTATUS state =
+      repo_ptr->fileStatus(item->path().toStdString());
+
+  if (state == Mantid::API::REMOTE_ONLY)
+    return "";
+  Mantid::API::ScriptInfo info = repo_ptr->fileInfo(item->path().toStdString());
+  if (info.directory)
+    return "";
+  QString path = repo_path + "/" + item->path();
+  return path;
 }
 
-/**Auxiliary method to help setupModelData to populate all the 
+/**Auxiliary method to help setupModelData to populate all the
    entries of RepoModel.
-   
-   For any entry of ScriptRepository should have a parent (by definition, all the entries
-   are children of the root entry). Besides, given an entry, if the path contains a '/' this 
-   means that the entry is child of one folder. And all the folders are parents by definition. 
 
-   So, the idea of this getParent is that given a folder name, it must be related to a RepoItem 
+   For any entry of ScriptRepository should have a parent (by definition, all
+the entries
+   are children of the root entry). Besides, given an entry, if the path
+contains a '/' this
+   means that the entry is child of one folder. And all the folders are parents
+by definition.
+
+   So, the idea of this getParent is that given a folder name, it must be
+related to a RepoItem
    that is a parent. If it does not exists, it should be created.
-   
-   @param folder: relative path inside the repository for the folder. 
+
+   @param folder: relative path inside the repository for the folder.
    @param parents Reference to the list of parents
-   @return Pointer to the RepoItem related to the given folder. 
-   
+   @return Pointer to the RepoItem related to the given folder.
+
 **/
-RepoModel::RepoItem * RepoModel::getParent(const QString & folder, QList<RepoItem*>&parents){
-  // in order to speed the algorithm, check if the 
+RepoModel::RepoItem *RepoModel::getParent(const QString &folder,
+                                          QList<RepoItem *> &parents) {
+  // in order to speed the algorithm, check if the
   // folder is the same of the last folder.
   if (parents.last()->path() == folder)
-    return parents.last(); 
+    return parents.last();
 
-  // try to find this  
+  // try to find this
   if (folder.isEmpty())
     return parents.first(); // the parents first will always contain the root
 
-  // it will iterate through all the parents of the given folder, in order to 
-  // create any folder that has not been created. 
+  // it will iterate through all the parents of the given folder, in order to
+  // create any folder that has not been created.
   QStringList folder_parts = folder.split("/");
   QString aux_folder;
-  RepoItem * father = parents.first();
-  // there is no reason to try to find entry A/B/C if the entry A/B was not found
+  RepoItem *father = parents.first();
+  // there is no reason to try to find entry A/B/C if the entry A/B was not
+  // found
   bool try_to_find = true;
 
-  for(int i = 0; i< folder_parts.size(); i++){
-    if (i ==0)
-      aux_folder = folder_parts[i]; 
+  for (int i = 0; i < folder_parts.size(); i++) {
+    if (i == 0)
+      aux_folder = folder_parts[i];
     else
-      aux_folder += "/" + folder_parts[i]; 
-    
+      aux_folder += "/" + folder_parts[i];
+
     bool found = false;
 
-    if (try_to_find){
+    if (try_to_find) {
       // this means that the previous folders were found
-      foreach(RepoItem* the_parent, parents){
-        if (the_parent->path() == aux_folder)
-          {
-            found = true;
-            father = the_parent; 
-            break;
-          }
+      foreach (RepoItem *the_parent, parents) {
+        if (the_parent->path() == aux_folder) {
+          found = true;
+          father = the_parent;
+          break;
+        }
       }
     }
-    // there is not RepoItem related to the current folder, 
-    // create it 
-    if (!found)
-      {
-        RepoItem * m = new RepoItem(folder_parts[i], aux_folder, father);
-        father->appendChild(m); 
-        parents.append(m); 
-        father = m; 
-        try_to_find = false;
-      }    
+    // there is not RepoItem related to the current folder,
+    // create it
+    if (!found) {
+      RepoItem *m = new RepoItem(folder_parts[i], aux_folder, father);
+      father->appendChild(m);
+      parents.append(m);
+      father = m;
+      try_to_find = false;
+    }
   }
   return father;
 }
 
-/** Populate the RepoModel with RepoItem entries that reproduce the hierarchical 
- *  organization of ScriptRepository entries. 
- * 
- * It will get the information from ScriptRepository from the listFiles, which means, 
- * that it will reconstruct the hierarchical organization of the files and folders
- * through the list of strings with the relative path of each entry. 
- * 
- * @param root: The RepoItem root 
+/** Populate the RepoModel with RepoItem entries that reproduce the hierarchical
+ *  organization of ScriptRepository entries.
+ *
+ * It will get the information from ScriptRepository from the listFiles, which
+ *means,
+ * that it will reconstruct the hierarchical organization of the files and
+ *folders
+ * through the list of strings with the relative path of each entry.
+ *
+ * @param root: The RepoItem root
  */
-void RepoModel::setupModelData(RepoItem *root)
-{
+void RepoModel::setupModelData(RepoItem *root) {
 
   QStringList lines;
   // check server for updates to repository
   repo_ptr->check4Update();
   // get the list of entries inside the scriptrepository
   std::vector<std::string> list = repo_ptr->listFiles();
-  
+
   // auxiliary list of pointers to repoitem that are related to folders
-  QList<RepoItem*> parents;
+  QList<RepoItem *> parents;
   // the first one will always be the root
   parents << root;
 
-  
   QString last_directory = "";
-  
-  //FOREACH entry in LISTFILES
+
+  // FOREACH entry in LISTFILES
   for (unsigned int number = 0; number < list.size(); number++) {
     // folder or file inside the repository
     QString lineData = QString::fromStdString(list[number]);
 
-    
-    // Read the column data from the rest of the line.      
+    // Read the column data from the rest of the line.
     QStringList pathStrings = lineData.split("/");
     // separate the folder and the current entry (folder or file)
-    QString current_file = pathStrings.last(); 
-    QString folder = ""; 
-    pathStrings.removeLast(); 
+    QString current_file = pathStrings.last();
+    QString folder = "";
+    pathStrings.removeLast();
     if (pathStrings.size() > 0)
-      folder = pathStrings.join("/"); 
-    
+      folder = pathStrings.join("/");
+
     // get parent for this entry
-    RepoItem * parent = getParent(folder, parents);    
+    RepoItem *parent = getParent(folder, parents);
     // a new folder has started
-    if (parent == root){
-      // this test is just for the sake of performance, to reduce the numbers of parents
-      parents.clear(); 
+    if (parent == root) {
+      // this test is just for the sake of performance, to reduce the numbers of
+      // parents
+      parents.clear();
       parents << root;
     }
-    
+
     // check if the current entry is a directory
-    if (repo_ptr->info(lineData.toStdString()).directory){
+    if (repo_ptr->info(lineData.toStdString()).directory) {
       // directories will be appended to parents list
-      RepoItem * aux = new RepoItem(current_file, lineData, parent); 
-      parent->appendChild(aux); 
-      parents << aux;                           
-    }else{
+      RepoItem *aux = new RepoItem(current_file, lineData, parent);
+      parent->appendChild(aux);
+      parents << aux;
+    } else {
       // files will just be created and appended to the parent
       parent->appendChild(new RepoItem(current_file, lineData, parent));
-      
     }
-    
   }
-  
-}
-void RepoModel::handleExceptions(const Mantid::API::ScriptRepoException & ex,
-                                 const QString & title, 
-                                 bool showWarning) const{
-   g_log.information() << "Download failed " << ex.what() << "\n Detail: " 
-                            << ex.systemError()<< std::endl;
-   if (showWarning){
-
-     QWidget * father = qobject_cast<QWidget*>(QObject::parent());
-     QString info = QString::fromStdString(ex.what());
-     // make the exception a nice html message
-     info.replace("\n","</p><p>");
-     QMessageBox::warning(father, title,
-                          QString("<html><body><p>%1</p></body></html>")
-                          .arg(info));   
-   }
 }
+void RepoModel::handleExceptions(const Mantid::API::ScriptRepoException &ex,
+                                 const QString &title, bool showWarning) const {
+  g_log.information() << "Download failed " << ex.what()
+                      << "\n Detail: " << ex.systemError() << std::endl;
+  if (showWarning) {
 
+    QWidget *father = qobject_cast<QWidget *>(QObject::parent());
+    QString info = QString::fromStdString(ex.what());
+    // make the exception a nice html message
+    info.replace("\n", "</p><p>");
+    QMessageBox::warning(
+        father, title,
+        QString("<html><body><p>%1</p></body></html>").arg(info));
+  }
+}
 
-void RepoModel::downloadFinished(void){  
+void RepoModel::downloadFinished(void) {
   QString info = download_threads.result();
-  if (!info.isEmpty()){
-    QMessageBox::warning( qobject_cast<QWidget*>(QObject::parent()), 
-                          "Download Failed",
-                          QString("<html><body><p>%1</p></body></html>")
-                          .arg(info));  
+  if (!info.isEmpty()) {
+    QMessageBox::warning(
+        qobject_cast<QWidget *>(QObject::parent()), "Download Failed",
+        QString("<html><body><p>%1</p></body></html>").arg(info));
   }
   downloading_path = nofile_flag;
-  RepoItem * repo_item = static_cast<RepoItem*>(download_index.internalPointer());
-  QModelIndex top_left = createIndex(0,0,repo_item);
-  QModelIndex bottom_right = createIndex(0,3,repo_item);
+  RepoItem *repo_item =
+      static_cast<RepoItem *>(download_index.internalPointer());
+  QModelIndex top_left = createIndex(0, 0, repo_item);
+  QModelIndex bottom_right = createIndex(0, 3, repo_item);
   emit dataChanged(top_left, bottom_right);
   emit executingThread(false);
 }
 
-  
-bool RepoModel::isDownloading(const QModelIndex & index)const{
-  RepoItem *item = static_cast<RepoItem*>(index.internalPointer());
+bool RepoModel::isDownloading(const QModelIndex &index) const {
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
   if (item)
     return item->path() == downloading_path;
   return false;
 }
 
-
-void RepoModel::uploadFinished(void){
+void RepoModel::uploadFinished(void) {
   QString info = upload_threads.result();
-  QString title =  "Upload Failed"; 
-  if (info.contains(delete_mark)){
-    info.replace(delete_mark,""); 
+  QString title = "Upload Failed";
+  if (info.contains(delete_mark)) {
+    info.replace(delete_mark, "");
     title = "Delete Failed";
   }
-  
-  if (!info.isEmpty()){
-    QMessageBox::warning( qobject_cast<QWidget*>(QObject::parent()), 
-                          title,
-                          QString("<html><body><p>%1</p></body></html>")
-                          .arg(info));
+
+  if (!info.isEmpty()) {
+    QMessageBox::warning(
+        qobject_cast<QWidget *>(QObject::parent()), title,
+        QString("<html><body><p>%1</p></body></html>").arg(info));
   }
-  
+
   uploading_path = nofile_flag;
-  RepoItem * repo_item = static_cast<RepoItem*>(upload_index.internalPointer());
-  QModelIndex top_left = createIndex(0,0,repo_item);
-  QModelIndex bottom_right = createIndex(0,3,repo_item);
+  RepoItem *repo_item = static_cast<RepoItem *>(upload_index.internalPointer());
+  QModelIndex top_left = createIndex(0, 0, repo_item);
+  QModelIndex bottom_right = createIndex(0, 3, repo_item);
   emit dataChanged(top_left, bottom_right);
   emit executingThread(false);
 }
 
-  
-bool RepoModel::isUploading(const QModelIndex & index)const{
-  RepoItem *item = static_cast<RepoItem*>(index.internalPointer());
+bool RepoModel::isUploading(const QModelIndex &index) const {
+  RepoItem *item = static_cast<RepoItem *>(index.internalPointer());
   if (item)
     return item->path() == uploading_path;
-  return false; 
+  return false;
 }
 
-
 /// @return string to define the LOCAL_ONLY state
-const QString & RepoModel::localOnlySt(){return LOCALONLY;}
+const QString &RepoModel::localOnlySt() { return LOCALONLY; }
 /// @return string to define the REMOTE_ONLY state
-const QString & RepoModel::remoteOnlySt(){return REMOTEONLY;}
+const QString &RepoModel::remoteOnlySt() { return REMOTEONLY; }
 /// @return string to define the LOCAL_CHANGED state
-const QString & RepoModel::localChangedSt(){return LOCALCHANGED;}
+const QString &RepoModel::localChangedSt() { return LOCALCHANGED; }
 /// @return string to define the REMOTE_CHANGED state
-const QString & RepoModel::remoteChangedSt(){return REMOTECHANGED;}
+const QString &RepoModel::remoteChangedSt() { return REMOTECHANGED; }
 /// @return string to define the BOTH_UNCHANGED state
-const QString & RepoModel::updatedSt(){return BOTHUNCHANGED;}
+const QString &RepoModel::updatedSt() { return BOTHUNCHANGED; }
 /// @return string to define the BOTH_CHANGED state
-const QString & RepoModel::bothChangedSt(){return BOTHCHANGED;}
+const QString &RepoModel::bothChangedSt() { return BOTHCHANGED; }
 /// @return string to define the downloading state
-const QString & RepoModel::downloadSt(){return DOWNLOADST;}
+const QString &RepoModel::downloadSt() { return DOWNLOADST; }
 /// @return string to define the uploading state
-const QString & RepoModel::uploadSt(){return UPLOADST;}
-
-
-
-
-RepoModel::UploadForm::UploadForm( const QString & file2upload,
-                                   QWidget * parent): QDialog(parent){
-      author_le = new QLineEdit(); 
-      email_le = new QLineEdit(); 
-      save_ck = new QCheckBox("Save your personal information");
-      save_ck->setToolTip("The author and email will be saved and will be written to you next time");
-      comment_te = new QTextEdit(); 
-
-      // setup the layout
-
-      QGroupBox * personalGroupBox = new QGroupBox("Personal Group Box");    
-      QFormLayout * personalLayout = new QFormLayout();       
-      personalLayout->addRow("Author",author_le); 
-      personalLayout->addRow("Email",email_le); 
-      QVBoxLayout * gpBox = new QVBoxLayout();
-      gpBox->addWidget(save_ck); 
-      gpBox->addLayout(personalLayout);
-      personalGroupBox->setLayout(gpBox);
-
-      QLabel * cmLabel = new QLabel("Comment"); 
-      QDialogButtonBox * buttonBox = new QDialogButtonBox();
-      buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
-
-      QVBoxLayout * layout = new QVBoxLayout(); 
-      layout->addWidget(personalGroupBox); 
-      layout->addWidget(cmLabel); 
-      layout->addWidget(comment_te); 
-      layout->addWidget(buttonBox);
-      setLayout(layout);
-
-      setWindowTitle(QString("Upload - %2").arg(file2upload));
-      connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); 
-      connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
-  }
-  RepoModel::UploadForm::~UploadForm(){
-    
-  } 
-QString RepoModel::UploadForm::email(){
-  return email_le->text(); 
-}
-QString RepoModel::UploadForm::author(){
-  return author_le->text(); 
+const QString &RepoModel::uploadSt() { return UPLOADST; }
+
+RepoModel::UploadForm::UploadForm(const QString &file2upload, QWidget *parent)
+    : QDialog(parent) {
+  author_le = new QLineEdit();
+  email_le = new QLineEdit();
+  save_ck = new QCheckBox("Save your personal information");
+  save_ck->setToolTip("The author and email will be saved and will be written "
+                      "to you next time");
+  comment_te = new QTextEdit();
+
+  // setup the layout
+
+  QGroupBox *personalGroupBox = new QGroupBox("Personal Group Box");
+  QFormLayout *personalLayout = new QFormLayout();
+  personalLayout->addRow("Author", author_le);
+  personalLayout->addRow("Email", email_le);
+  QVBoxLayout *gpBox = new QVBoxLayout();
+  gpBox->addWidget(save_ck);
+  gpBox->addLayout(personalLayout);
+  personalGroupBox->setLayout(gpBox);
+
+  QLabel *cmLabel = new QLabel("Comment");
+  QDialogButtonBox *buttonBox = new QDialogButtonBox();
+  buttonBox->setStandardButtons(QDialogButtonBox::Cancel |
+                                QDialogButtonBox::Ok);
+
+  QVBoxLayout *layout = new QVBoxLayout();
+  layout->addWidget(personalGroupBox);
+  layout->addWidget(cmLabel);
+  layout->addWidget(comment_te);
+  layout->addWidget(buttonBox);
+  setLayout(layout);
+
+  setWindowTitle(QString("Upload - %2").arg(file2upload));
+  connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
+  connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
 }
+RepoModel::UploadForm::~UploadForm() {}
+QString RepoModel::UploadForm::email() { return email_le->text(); }
+QString RepoModel::UploadForm::author() { return author_le->text(); }
 QString RepoModel::UploadForm::comment() { return comment_te->toPlainText(); }
-bool RepoModel::UploadForm::saveInfo(){
-   return save_ck->isChecked();
+bool RepoModel::UploadForm::saveInfo() { return save_ck->isChecked(); }
+void RepoModel::UploadForm::setEmail(const QString &email) {
+  email_le->setText(email);
 }
-void RepoModel::UploadForm::setEmail(const QString & email){
-  email_le->setText(email); 
-}
-void RepoModel::UploadForm::setAuthor(const QString & author){
+void RepoModel::UploadForm::setAuthor(const QString &author) {
   author_le->setText(author);
 }
-void RepoModel::UploadForm::lastSaveOption(bool option){
-  save_ck->setCheckState(option?Qt::Checked:Qt::Unchecked);
+void RepoModel::UploadForm::lastSaveOption(bool option) {
+  save_ck->setCheckState(option ? Qt::Checked : Qt::Unchecked);
 }
 
-
-RepoModel::DeleteQueryBox::DeleteQueryBox( const QString & path,
-                                           QWidget * parent):
-  QMessageBox(QMessageBox::Question, "Delete file", "", QMessageBox::Yes|QMessageBox::No,
-              parent){
+RepoModel::DeleteQueryBox::DeleteQueryBox(const QString &path, QWidget *parent)
+    : QMessageBox(QMessageBox::Question, "Delete file", "",
+                  QMessageBox::Yes | QMessageBox::No, parent) {
   using namespace Mantid::API;
-  QString info_str; 
-  QTextStream info(&info_str); 
+  QString info_str;
+  QTextStream info(&info_str);
+
+  info << "<html><head/><body><p>Are you sure you want to delete this file "
+          "from the Repository?</p><p align=\"center\"><span style=\" "
+          "font-style:italic;\">" << path << "</span></p></body></html>";
 
-  info << "<html><head/><body><p>Are you sure you want to delete this file from the Repository?</p><p align=\"center\"><span style=\" font-style:italic;\">"<<path<<"</span></p></body></html>"; 
-  
   // creation of the new widgets
-  comment_te = NULL; 
+  comment_te = NULL;
 
-  setText(info_str); 
+  setText(info_str);
 
-  QGridLayout * _lay = qobject_cast<QGridLayout*>(layout()); 
-  if (_lay){
-    QLayoutItem * buttons = _lay->takeAt(_lay->count()-1);
-    QLabel * la = new QLabel("Please, give the reason for deleting:", this);
+  QGridLayout *_lay = qobject_cast<QGridLayout *>(layout());
+  if (_lay) {
+    QLayoutItem *buttons = _lay->takeAt(_lay->count() - 1);
+    QLabel *la = new QLabel("Please, give the reason for deleting:", this);
     comment_te = new QTextEdit(this);
     comment_te->setMaximumHeight(70);
     _lay->addWidget(la, _lay->rowCount(), 0, 1, -1);
     _lay->addWidget(comment_te, _lay->rowCount(), 0, 2, -1);
-    _lay->addItem(buttons, _lay->rowCount(), 0,1,-1); 
+    _lay->addItem(buttons, _lay->rowCount(), 0, 1, -1);
   }
 }
 
-RepoModel::DeleteQueryBox::~DeleteQueryBox(){
-} 
-QString RepoModel::DeleteQueryBox::comment(){
+RepoModel::DeleteQueryBox::~DeleteQueryBox() {}
+QString RepoModel::DeleteQueryBox::comment() {
   if (comment_te)
     return comment_te->toPlainText();
   else
-    return QString(); 
-
+    return QString();
 }
-
diff --git a/MantidQt/API/src/ScriptRepositoryView.cpp b/MantidQt/API/src/ScriptRepositoryView.cpp
index 5f76e642dc0ec7aab6683f0c939dbfc7f2ecebd0..74c86fd9f584be6b29f118ec797fd76981c200fa 100644
--- a/MantidQt/API/src/ScriptRepositoryView.cpp
+++ b/MantidQt/API/src/ScriptRepositoryView.cpp
@@ -14,410 +14,451 @@
 #include <QFileDialog>
 #include <QPainter>
 #include <QDesktopServices>
-namespace MantidQt
-{
-namespace API
-{
-  namespace
-  {
-    /// static logger
-    Mantid::Kernel::Logger g_log("ScriptRepositoryView");
-  }
+namespace MantidQt {
+namespace API {
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("ScriptRepositoryView");
+}
 
-  const QString install_mantid_label = "<html><head/><body><p>The <span style=\" font-weight:600;\">"
+const QString install_mantid_label =
+    "<html><head/><body><p>The <span style=\" font-weight:600;\">"
     "Script Repository</span> allows you to:</p>"
     "<p>  * Share your scripts and reduction algorithms;</p>"
-    "<p>  * Get <span style=\" font-weight:600;\">Mantid</span> Scripts from the mantid developers and the community. </p>"
+    "<p>  * Get <span style=\" font-weight:600;\">Mantid</span> Scripts from "
+    "the mantid developers and the community. </p>"
     "<p><span style=\" font-style:italic;\">"
-    "N.B. The installation usually requires a couple of minutes, depending on your network bandwidth. </span></p>"
+    "N.B. The installation usually requires a couple of minutes, depending on "
+    "your network bandwidth. </span></p>"
     "<p>More Information available at "
-    "<a href=\"http://www.mantidproject.org/ScriptRepository\"><span style=\" text-decoration: underline; color:#0000ff;\">"
-    "http://www.mantidproject.org/ScriptRepository</span></a></p></br><p><span style=\" font-weight:600;\">"
+    "<a href=\"http://www.mantidproject.org/ScriptRepository\"><span style=\" "
+    "text-decoration: underline; color:#0000ff;\">"
+    "http://www.mantidproject.org/ScriptRepository</span></a></p></br><p><span "
+    "style=\" font-weight:600;\">"
     "Would you like to install it now?</span></p></body></html>";
 
-  const QString installation_in_progress = "<html><head/><body><p><span style=\" font-weight:600;\">"
+const QString installation_in_progress =
+    "<html><head/><body><p><span style=\" font-weight:600;\">"
     "Installing Script Repository Installation in background!</span></p>"
     "<p>You may continue to use mantid.</p>"
-    "<p>The Result Log willl give you information of the installation progress.</p>"
-    "<p>When finished, please, reopen the <span style=\" font-weight:600;\">Script Repository</span>. </p></body></html>";
+    "<p>The Result Log willl give you information of the installation "
+    "progress.</p>"
+    "<p>When finished, please, reopen the <span style=\" "
+    "font-weight:600;\">Script Repository</span>. </p></body></html>";
 
-  const QString installation_failed = "<html><head/><body><p>The installation of Script Repository "
+const QString installation_failed =
+    "<html><head/><body><p>The installation of Script Repository "
     "<span style=\" font-weight:600;\">Failed</span>!</p>"
-    "<p>Please, check the Result Log to see why the installation failed. </p></body></html>";
-
-  const QString dir_not_empty_label = "<html><head/><body><p>The directory/folder that you have selected is not empty</p>"
-    "<p>Are you sure that you want to install the script repository here? All the files and directories found in "
-    "the selected directory/folder could be shared in the repository by mistake.</p>"
-    "<p>If you are not sure, please choose 'no' and then select an empty (or newly created) directory/folder.</p>"
-    "<p>If this is your home directory, desktop or similar you should definitely choose 'no'.</p>"
-    "<p>If you are sure of what you are doing, please choose 'yes'. The installation may take a couple of minutes.</p>"
+    "<p>Please, check the Result Log to see why the installation failed. "
+    "</p></body></html>";
+
+const QString dir_not_empty_label =
+    "<html><head/><body><p>The directory/folder that you have selected is not "
+    "empty</p>"
+    "<p>Are you sure that you want to install the script repository here? All "
+    "the files and directories found in "
+    "the selected directory/folder could be shared in the repository by "
+    "mistake.</p>"
+    "<p>If you are not sure, please choose 'no' and then select an empty (or "
+    "newly created) directory/folder.</p>"
+    "<p>If this is your home directory, desktop or similar you should "
+    "definitely choose 'no'.</p>"
+    "<p>If you are sure of what you are doing, please choose 'yes'. The "
+    "installation may take a couple of minutes.</p>"
     "</body></html>";
 
-  //----------------------------------------------------------------------------------------------
-  /** Creates the widget for the ScriptRepositoryView
-   *
-   *  Before constructing the widget, it must ensure that the ScriptRepository was installed before. 
-   *
-   *  If it has not been installed, them, it will first try to install it. 
-   *  If it fails to install, them, it will not be able to create the widget, and it will fail gracelly. 
-   *  
-   *  In normal condition, it will create the widget (Ui::ScriptRepositoryView) and populate it with the 
-   *  RepoModel, and define the delegates ScriptRepositoryView::RepoDelegate and ScriptRepositoryView::CheckBoxDelegate
-   *  and ScriptRepositoryView::RemoveEntryDelegate.
-   *  
-   */
-  ScriptRepositoryView::ScriptRepositoryView(QWidget * parent):
-    QDialog(parent),
-    ui(new Ui::ScriptRepositoryView)
-  {
-    using Mantid::API::ScriptRepositoryFactory; 
-    using Mantid::Kernel::ConfigServiceImpl; 
-    using Mantid::Kernel::ConfigService;
-    enum EXC_OPTIONS{NOTWANTED,NODIRECTORY};
-
-    try{
-
-      // create and instance of ScriptRepository
-      Mantid::API::ScriptRepository_sptr repo_ptr =   ScriptRepositoryFactory::Instance().create("ScriptRepositoryImpl");
-    
-      // check if the ScriptRepository was ever installed    
-      if (!repo_ptr->isValid()){
-        // No. It has never been installed. 
-        // Ask the user if he wants to install the ScriptRepository
-        if (QMessageBox::Ok != QMessageBox::question(this,"Install Script Repository?",
-                                                     install_mantid_label,
-                                                     QMessageBox::Ok|QMessageBox::Cancel)){
-          throw NOTWANTED;          
+//----------------------------------------------------------------------------------------------
+/** Creates the widget for the ScriptRepositoryView
+ *
+ *  Before constructing the widget, it must ensure that the ScriptRepository was
+ *installed before.
+ *
+ *  If it has not been installed, them, it will first try to install it.
+ *  If it fails to install, them, it will not be able to create the widget, and
+ *it will fail gracelly.
+ *
+ *  In normal condition, it will create the widget (Ui::ScriptRepositoryView)
+ *and populate it with the
+ *  RepoModel, and define the delegates ScriptRepositoryView::RepoDelegate and
+ *ScriptRepositoryView::CheckBoxDelegate
+ *  and ScriptRepositoryView::RemoveEntryDelegate.
+ *
+ */
+ScriptRepositoryView::ScriptRepositoryView(QWidget *parent)
+    : QDialog(parent), ui(new Ui::ScriptRepositoryView) {
+  using Mantid::API::ScriptRepositoryFactory;
+  using Mantid::Kernel::ConfigServiceImpl;
+  using Mantid::Kernel::ConfigService;
+  enum EXC_OPTIONS { NOTWANTED, NODIRECTORY };
+
+  try {
+
+    // create and instance of ScriptRepository
+    Mantid::API::ScriptRepository_sptr repo_ptr =
+        ScriptRepositoryFactory::Instance().create("ScriptRepositoryImpl");
+
+    // check if the ScriptRepository was ever installed
+    if (!repo_ptr->isValid()) {
+      // No. It has never been installed.
+      // Ask the user if he wants to install the ScriptRepository
+      if (QMessageBox::Ok !=
+          QMessageBox::question(this, "Install Script Repository?",
+                                install_mantid_label,
+                                QMessageBox::Ok | QMessageBox::Cancel)) {
+        throw NOTWANTED;
       }
       // get the directory to install the script repository
-      ConfigServiceImpl & config = ConfigService::Instance();
-      QString loc = QString::fromStdString(config.getString("ScriptLocalRepository")); 
+      ConfigServiceImpl &config = ConfigService::Instance();
+      QString loc =
+          QString::fromStdString(config.getString("ScriptLocalRepository"));
 
       bool sureAboutDir = false;
 
       QString dir;
-      while (!sureAboutDir)
-      {
-        dir = QFileDialog::getExistingDirectory(this, tr("Where do you want to install Script Repository?"),
-                                                loc,
-                                                QFileDialog::ShowDirsOnly
-                                                | QFileDialog::DontResolveSymlinks);
+      while (!sureAboutDir) {
+        dir = QFileDialog::getExistingDirectory(
+            this, tr("Where do you want to install Script Repository?"), loc,
+            QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
 
         // configuring
-        if (dir.isEmpty())
-        {
+        if (dir.isEmpty()) {
           throw NODIRECTORY;
         }
 
         // warn if dir is not empty
-        if (0 == QDir(dir).entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot).count())
-        {
+        if (0 ==
+            QDir(dir)
+                .entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)
+                .count()) {
           // empty dir, just go ahead
           sureAboutDir = true;
-        }
-        else
-        {
-          // warn user in case the repo is being installed in its home, etc. directory
-          QMessageBox::StandardButton sel =
-            QMessageBox::question(this,
-                                  "Are you sure you want to install the Script Repository here?",
-                                  dir_not_empty_label,
-                                  QMessageBox::Yes|QMessageBox::No);
+        } else {
+          // warn user in case the repo is being installed in its home, etc.
+          // directory
+          QMessageBox::StandardButton sel = QMessageBox::question(
+              this,
+              "Are you sure you want to install the Script Repository here?",
+              dir_not_empty_label, QMessageBox::Yes | QMessageBox::No);
           if (QMessageBox::Yes == sel)
             sureAboutDir = true;
         }
       }
 
-      // attempt to install 
+      // attempt to install
       repo_ptr->install(dir.toStdString());
-      g_log.information() << "ScriptRepository installed at " << dir.toStdString() << std::endl;
-
+      g_log.information() << "ScriptRepository installed at "
+                          << dir.toStdString() << std::endl;
     }
-      // create the model
-    model = new RepoModel(this);   
-
-    }catch( EXC_OPTIONS  ex){
-      if (ex == NODIRECTORY)
-         // probably the user change mind. He does not want to install any more.
-        QMessageBox::warning(this, "Installation Failed",
-            "Invalid Folder to install Script Repository!\n"); 
-        
-      close();
-      deleteLater(); 
-      return;      
-    }catch(Mantid::API::ScriptRepoException & ex){
-      // means that the installation failed
-      g_log.warning() << "ScriptRepository installation: " << ex.what() << std::endl; 
-      g_log.information() << "ScriptRepository installation failed with this information: " << ex.systemError() << std::endl; 
-      QMessageBox::warning(this,"Installation Failed",
-                           QString(ex.what()));
-      close(); 
-      deleteLater();         
-      return;
-    }catch(...){
-      g_log.error() << "Unknown error occurred to install ScriptRepository. It will not be shown." << std::endl; 
-      close(); 
-      deleteLater(); 
-      return;
-    }
-    // from this point, it is assumed that ScriptRepository is installed.    
-
-    // configure the Ui
-    ui->setupUi(this);
-    connect(ui->reloadPushButton, SIGNAL(clicked()),this,SLOT(updateModel()));
-    connect(ui->pbHelp, SIGNAL(clicked()),this,SLOT(helpClicked()));
-    connect(model, SIGNAL(executingThread(bool)),ui->reloadPushButton, SLOT(setDisabled(bool)));
-
-    // setup the model and delegates   
-    ui->repo_treeView->setModel(model);
-    ui->repo_treeView->setItemDelegateForColumn(1, new RepoDelegate(this));
-    ui->repo_treeView->setItemDelegateForColumn(2, new CheckBoxDelegate(this));
-    ui->repo_treeView->setItemDelegateForColumn(3, new RemoveEntryDelegate(this));
-    ui->repo_treeView->setColumnWidth(0,290);
-    
-
-    // stablish the connections.
-    connect(ui->repo_treeView, SIGNAL(activated(const QModelIndex &)),
-            this, SLOT(cell_activated(const QModelIndex&)));
-    connect(ui->repo_treeView, SIGNAL(currentCell(const QModelIndex&)),
-            this, SLOT(currentChanged(const QModelIndex&)));
-
-    ConfigServiceImpl & config = ConfigService::Instance();
-    QString loc = QString::fromStdString(config.getString("ScriptLocalRepository"));
-    QString loc_info = "<html><head/><body><p><a href=\"%1\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a></p></body></html>";
-    QString path_label; 
-    if (loc.size()<50)
-      path_label = loc; 
-    else{
-      path_label = QString("%1...%2").arg(loc.left(20)).arg(loc.right(27));      
-    }
-    
-    ui->folderPathLabel->setText(loc_info.arg(loc).arg(path_label));
-    ui->folderPathLabel->setToolTip(QString("Click here to open Script Repository Folder: %1.").arg(loc));
-    connect(ui->folderPathLabel, SIGNAL(linkActivated(QString)),this,SLOT(openFolderLink(QString)));
- }
-
-  /** This method refreshes the ScriptRepository and allows it 
-   *  to check list the files again. It will also check for 
-   *  new files and folders. It is easier to just recreate RepoModel
-   *  than figuring out the entries that were inserted or deleted 
-   *  from the ScriptRepository. This method could be rewritten
-   *  in order to be more efficient.
-   */
-  void ScriptRepositoryView::updateModel(){
-    RepoModel * before = model; 
-    model = new RepoModel(); 
-    connect(model, SIGNAL(executingThread(bool)),ui->reloadPushButton, SLOT(setDisabled(bool)));
-    ui->repo_treeView->setModel(model); 
-    delete before; 
-  }
+    // create the model
+    model = new RepoModel(this);
 
+  } catch (EXC_OPTIONS ex) {
+    if (ex == NODIRECTORY)
+      // probably the user change mind. He does not want to install any more.
+      QMessageBox::warning(this, "Installation Failed",
+                           "Invalid Folder to install Script Repository!\n");
 
-  //----------------------------------------------------------------------------------------------
-  /** Destructor 
-   */
-  ScriptRepositoryView::~ScriptRepositoryView()
-  {
-    delete ui;
+    close();
+    deleteLater();
+    return;
+  } catch (Mantid::API::ScriptRepoException &ex) {
+    // means that the installation failed
+    g_log.warning() << "ScriptRepository installation: " << ex.what()
+                    << std::endl;
+    g_log.information()
+        << "ScriptRepository installation failed with this information: "
+        << ex.systemError() << std::endl;
+    QMessageBox::warning(this, "Installation Failed", QString(ex.what()));
+    close();
+    deleteLater();
+    return;
+  } catch (...) {
+    g_log.error() << "Unknown error occurred to install ScriptRepository. It "
+                     "will not be shown." << std::endl;
+    close();
+    deleteLater();
+    return;
+  }
+  // from this point, it is assumed that ScriptRepository is installed.
+
+  // configure the Ui
+  ui->setupUi(this);
+  connect(ui->reloadPushButton, SIGNAL(clicked()), this, SLOT(updateModel()));
+  connect(ui->pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  connect(model, SIGNAL(executingThread(bool)), ui->reloadPushButton,
+          SLOT(setDisabled(bool)));
+
+  // setup the model and delegates
+  ui->repo_treeView->setModel(model);
+  ui->repo_treeView->setItemDelegateForColumn(1, new RepoDelegate(this));
+  ui->repo_treeView->setItemDelegateForColumn(2, new CheckBoxDelegate(this));
+  ui->repo_treeView->setItemDelegateForColumn(3, new RemoveEntryDelegate(this));
+  ui->repo_treeView->setColumnWidth(0, 290);
+
+  // stablish the connections.
+  connect(ui->repo_treeView, SIGNAL(activated(const QModelIndex &)), this,
+          SLOT(cell_activated(const QModelIndex &)));
+  connect(ui->repo_treeView, SIGNAL(currentCell(const QModelIndex &)), this,
+          SLOT(currentChanged(const QModelIndex &)));
+
+  ConfigServiceImpl &config = ConfigService::Instance();
+  QString loc =
+      QString::fromStdString(config.getString("ScriptLocalRepository"));
+  QString loc_info = "<html><head/><body><p><a href=\"%1\"><span style=\" "
+                     "text-decoration: underline; "
+                     "color:#0000ff;\">%2</span></a></p></body></html>";
+  QString path_label;
+  if (loc.size() < 50)
+    path_label = loc;
+  else {
+    path_label = QString("%1...%2").arg(loc.left(20)).arg(loc.right(27));
   }
 
+  ui->folderPathLabel->setText(loc_info.arg(loc).arg(path_label));
+  ui->folderPathLabel->setToolTip(
+      QString("Click here to open Script Repository Folder: %1.").arg(loc));
+  connect(ui->folderPathLabel, SIGNAL(linkActivated(QString)), this,
+          SLOT(openFolderLink(QString)));
+}
 
-  /** Allows the user to open a file to investigate it.
-   *  If the user selects and activate one Row, double-clicking on the first 
-   *  column, it will try to retrieve the file path (if it is local) and emit 
-   *  the signal loadScript. MantidPlot will get this signal to load the file and 
-   *  show its contents to the user. 
-   */
-  void ScriptRepositoryView::cell_activated(const QModelIndex & in){
-
-    RepoModel * _model = qobject_cast<RepoModel*>(ui->repo_treeView->model());
-    if (_model){
-      QString path = _model->filePath(in); 
-      if (path.isEmpty()){
-        // no real file to be opened. 
-        return;
-      }
-      emit loadScript(path);
-    }
-  }
+/** This method refreshes the ScriptRepository and allows it
+ *  to check list the files again. It will also check for
+ *  new files and folders. It is easier to just recreate RepoModel
+ *  than figuring out the entries that were inserted or deleted
+ *  from the ScriptRepository. This method could be rewritten
+ *  in order to be more efficient.
+ */
+void ScriptRepositoryView::updateModel() {
+  RepoModel *before = model;
+  model = new RepoModel();
+  connect(model, SIGNAL(executingThread(bool)), ui->reloadPushButton,
+          SLOT(setDisabled(bool)));
+  ui->repo_treeView->setModel(model);
+  delete before;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+ScriptRepositoryView::~ScriptRepositoryView() { delete ui; }
+
+/** Allows the user to open a file to investigate it.
+ *  If the user selects and activate one Row, double-clicking on the first
+ *  column, it will try to retrieve the file path (if it is local) and emit
+ *  the signal loadScript. MantidPlot will get this signal to load the file and
+ *  show its contents to the user.
+ */
+void ScriptRepositoryView::cell_activated(const QModelIndex &in) {
 
-  /** This method will be executed every time the user change the selection. It allows
-   *  to update all the entries that are related to the current selection. Currently, 
-   *  the description field will be updated.  
-   */
-  void ScriptRepositoryView::currentChanged(const QModelIndex & in){
-    RepoModel * _model = qobject_cast<RepoModel*>(ui->repo_treeView->model());    
-    if (_model){
-      // try to get the description of the file pointed at the current index.
-      // and update the description text browser. 
-      QString description = _model->fileDescription(in);
-      ui->desc_textBrowser->setText(description);
-      QString author_name = _model->author(in);
-      if (author_name.isEmpty())
-        ui->authorNameLabel->setText(""); 
-      else
-        ui->authorNameLabel->setText(QString("<b>Author:</b> ")+ author_name);
+  RepoModel *_model = qobject_cast<RepoModel *>(ui->repo_treeView->model());
+  if (_model) {
+    QString path = _model->filePath(in);
+    if (path.isEmpty()) {
+      // no real file to be opened.
       return;
     }
+    emit loadScript(path);
   }
+}
 
-  /** Open the ScriptRepository Page on Web Browser*/
-void ScriptRepositoryView::helpClicked(){
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ScriptRepository"));
-} 
+/** This method will be executed every time the user change the selection. It
+ * allows
+ *  to update all the entries that are related to the current selection.
+ * Currently,
+ *  the description field will be updated.
+ */
+void ScriptRepositoryView::currentChanged(const QModelIndex &in) {
+  RepoModel *_model = qobject_cast<RepoModel *>(ui->repo_treeView->model());
+  if (_model) {
+    // try to get the description of the file pointed at the current index.
+    // and update the description text browser.
+    QString description = _model->fileDescription(in);
+    ui->desc_textBrowser->setText(description);
+    QString author_name = _model->author(in);
+    if (author_name.isEmpty())
+      ui->authorNameLabel->setText("");
+    else
+      ui->authorNameLabel->setText(QString("<b>Author:</b> ") + author_name);
+    return;
+  }
+}
+
+/** Open the ScriptRepository Page on Web Browser*/
+void ScriptRepositoryView::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/ScriptRepository"));
+}
 
 //////////////////////////////////////////////////
-// DELEGATE : Allow to display and interact with the View in a nicer way. Improve the User Experience. 
+// DELEGATE : Allow to display and interact with the View in a nicer way.
+// Improve the User Experience.
 ///////////////////////////////////////////////////
 
 ScriptRepositoryView::RepoDelegate::RepoDelegate(QObject *parent)
-  :QStyledItemDelegate(parent)
-{}
-  /** Draws the column 1 (Status) of ScriptRepositoryView. 
-   *
-   *  This function is called every time the ScriptRepository needs to draw the widget 
-   *  for the Status of the file/folder inside the ScriptRepository. 
-   *  Instead of displaying the status (REMOTE_ONLY, LOCAL_ONLY, and so on), it will draw
-   *  an Icon that 'hoppefully' will better indicate to the user the condition of the entry
-   *  as well as encourage him to act. The action will be dealt with through the editorEvent. 
-   *
-   *  When this method is called, it will get the index in order to retrieve the information 
-   *  about the status of the entry (folder/file). 
-   *  
-   *  It will them decide which icon better describes the current status of the entry, and will 
-   * draw it using the option and the painter given. 
-   * 
-   * @param painter: Required to draw the widget
-   * @param option: Provided by the framework and has information displaying the widget. 
-   * @param index: Identifies the entry inside the RepoModel (indirectly the file / folder).
-   */
+    : QStyledItemDelegate(parent) {}
+/** Draws the column 1 (Status) of ScriptRepositoryView.
+ *
+ *  This function is called every time the ScriptRepository needs to
+ *draw the widget for the Status of the file/folder inside the
+ *ScriptRepository.  Instead of displaying the status (REMOTE_ONLY,
+ *LOCAL_ONLY, and so on), it will draw an Icon that 'hoppefully' will
+ *better indicate to the user the condition of the entry as well as
+ *encourage him to act. The action will be dealt with through the
+ *editorEvent.
+ *
+ *  When this method is called, it will get the index in order to
+ *retrieve the information about the status of the entry
+ *(folder/file).
+ *
+ *  It will them decide which icon better describes the current status
+ *of the entry, and will draw it using the option and the painter
+ *given.
+ *
+ * @param painter: Required to draw the widget
+ * @param option: Provided by the framework and has information
+ *displaying the widget.
+ * @param index: Identifies the entry inside the RepoModel (indirectly
+ * the file/folder).
+ */
 void ScriptRepositoryView::RepoDelegate::paint(
-       QPainter* painter,
-       const QStyleOptionViewItem & option,
-       const QModelIndex & index
-       ) const
-{
-  
+    QPainter *painter, const QStyleOptionViewItem &option,
+    const QModelIndex &index) const {
+
   if (!index.isValid())
     return;
-  if (painter->device() ==0)
+  if (painter->device() == 0)
     return;
 
-  QIcon icon ; 
+  QIcon icon;
   // get the state and chose the best fit icon
   QString state = index.model()->data(index, Qt::DisplayRole).toString();
   if (state == RepoModel::remoteOnlySt())
-    icon = QIcon::fromTheme("system-software-install", QIcon(QPixmap(":/win/download")));
-  else if (state == RepoModel::remoteChangedSt() || state == RepoModel::bothChangedSt())
-    icon = QIcon::fromTheme("bottom", QIcon(QPixmap(":win/system-software-update")));
+    icon = QIcon::fromTheme("system-software-install",
+                            QIcon(QPixmap(":/win/download")));
+  else if (state == RepoModel::remoteChangedSt() ||
+           state == RepoModel::bothChangedSt())
+    icon = QIcon::fromTheme("bottom",
+                            QIcon(QPixmap(":win/system-software-update")));
   else if (state == RepoModel::updatedSt())
     icon = QIcon::fromTheme("dialog-ok", QIcon(QPixmap(":/win/dialog-ok")));
-  else if (state == RepoModel::localOnlySt() || state == RepoModel::localChangedSt())
-    icon = QIcon::fromTheme("add-files-to-archive", QIcon(QPixmap(":win/upload")));
+  else if (state == RepoModel::localOnlySt() ||
+           state == RepoModel::localChangedSt())
+    icon =
+        QIcon::fromTheme("add-files-to-archive", QIcon(QPixmap(":win/upload")));
   else if (state == RepoModel::downloadSt() || state == RepoModel::uploadSt())
     icon = QIcon(QPixmap(":win/running_process"));
   // define the region to draw the icon
-  QRect buttonRect( option.rect);  
-  int min_val = buttonRect.width()<buttonRect.height() ? buttonRect.width() : buttonRect.height();
+  QRect buttonRect(option.rect);
+  int min_val = buttonRect.width() < buttonRect.height() ? buttonRect.width()
+                                                         : buttonRect.height();
   // make it square
-  buttonRect.setWidth(min_val); 
-  buttonRect.setHeight(min_val); 
+  buttonRect.setWidth(min_val);
+  buttonRect.setHeight(min_val);
   buttonRect.moveCenter(option.rect.center());
 
   // define the options to draw a push button with the icon displayed
   QStyleOptionButton button;
   button.rect = buttonRect;
   button.icon = icon;
-  int icon_size =(int) (min_val*.8); 
-  button.iconSize = QSize(icon_size,icon_size);
-  button.state =  QStyle::State_Enabled;
+  int icon_size = (int)(min_val * .8);
+  button.iconSize = QSize(icon_size, icon_size);
+  button.state = QStyle::State_Enabled;
   // draw a push button
-  QApplication::style()->drawControl
-    (QStyle::CE_PushButton, &button, painter);
+  QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter);
 }
 
-/** Reacts to the iteraction with the user when he clicks on the buttons displayed at paint. 
+/** Reacts to the iteraction with the user when he clicks on the buttons
+ *displayed at paint.
+ *
+ *  Given the state of an entry (folder/file) there is only on available action.
+ *So,
+ *  it is enough to get the event that the user interact with the pushbutton to
+ *decide what
+ *  to do.
  *
- *  Given the state of an entry (folder/file) there is only on available action. So, 
- *  it is enough to get the event that the user interact with the pushbutton to decide what 
- *  to do. 
- *  
- *  It will filter the event in order to get the Left-Click of mouse. If it gets the 
- *  click of the mouse, it will trigger the action: 
+ *  It will filter the event in order to get the Left-Click of mouse. If it gets
+ *the
+ *  click of the mouse, it will trigger the action:
  *   - Upload: if the file/folder is local_only or local_changed
  *   - No Action when the entry is in Updated state.
  *   - Download: for the other cases
- *  
+ *
  * @param event: The event given by the framework
  * @param model: Pointer to the model needed to retrive the status of the entry
  * @param index: identifies the entry (file/folder)
  * @param option: Provided by the framewor, and passed on to the base class.
  * @return true if it handles or false to ignore.
 */
-bool  ScriptRepositoryView::RepoDelegate::editorEvent(QEvent *event,
-                                   QAbstractItemModel *model,
-                                                      const QStyleOptionViewItem &/*option*/,
-                                   const QModelIndex &index) {
-  // if event is mouse click 
-  if (event->type() == QEvent::MouseButtonPress){
+bool ScriptRepositoryView::RepoDelegate::editorEvent(
+    QEvent *event, QAbstractItemModel *model,
+    const QStyleOptionViewItem & /*option*/, const QModelIndex &index) {
+  // if event is mouse click
+  if (event->type() == QEvent::MouseButtonPress) {
     QString value = model->data(index, Qt::DisplayRole).toString();
     QString action = "Download";
-    if (value == RepoModel::localOnlySt() || value ==  RepoModel::localChangedSt())
+    if (value == RepoModel::localOnlySt() ||
+        value == RepoModel::localChangedSt())
       action = "Upload";
     if (value == RepoModel::updatedSt())
-      return false;// ignore 
-    return model->setData(index, action, Qt::EditRole);  
-  }else{
-    return true; //Does not allow others events to be processed (example: double-click)
-  }   
+      return false; // ignore
+    return model->setData(index, action, Qt::EditRole);
+  } else {
+    return true; // Does not allow others events to be processed (example:
+                 // double-click)
+  }
 }
 /** Provides the ideal size for this column
  *  @return ideal size for this column
  */
-QSize ScriptRepositoryView::RepoDelegate::sizeHint(const QStyleOptionViewItem & /*option*/, const QModelIndex & /*index*/ ) const{
-  return QSize(35,35);
-
+QSize ScriptRepositoryView::RepoDelegate::sizeHint(
+    const QStyleOptionViewItem & /*option*/,
+    const QModelIndex & /*index*/) const {
+  return QSize(35, 35);
 }
 
-
 //////////////////////////////////////////////////
 // CheckBoxDelegate
 ///////////////////////////////////////////////////
 
 ScriptRepositoryView::CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
-:QStyledItemDelegate(parent)
-{
-}
- /** Draws the column 2 (AutoUpdate) of ScriptRepositoryView.
-   *
-   *  This function is called every time the ScriptRepository needs to draw the widget 
-   *  for the AutoUpdate of the file/folder inside the ScriptRepository. 
-   *  Instead of displaying the strings 'true' and 'false' it will draw a checkbox
-   *  that 'hoppefully' will better indicate to the user the condition of the entry
-   *  as well as encourage him to act. The action will be dealt with at the editorEvent. 
-   *
-   *  When this method is called, it will get the index in order to retrieve the information 
-   *  about the state of the entry (folder/file). 
-   *  
-   * 
-   * @param painter: Required to draw the widget
-   * @param option: Provided by the framework and has information displaying the widget. 
-   * @param index: Identifies the entry inside the RepoModel (indirectly the file / folder).
-   */
-void ScriptRepositoryView::CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
+    : QStyledItemDelegate(parent) {}
+/** Draws the column 2 (AutoUpdate) of ScriptRepositoryView.
+  *
+  *  This function is called every time the ScriptRepository needs to
+  *draw the widget for the AutoUpdate of the file/folder inside the
+  *ScriptRepository.  Instead of displaying the strings 'true' and
+  *'false' it will draw a checkbox that 'hoppefully' will better
+  *indicate to the user the condition of the entry as well as
+  *encourage him to act. The action will be dealt with at the
+  *editorEvent.
+  *
+  *  When this method is called, it will get the index in order to
+  *retrieve the information about the state of the entry
+  *(folder/file).
+  *
+  *
+  * @param painter: Required to draw the widget
+  * @param option: Provided by the framework and has information
+  *displaying the widget.
+  * @param index: Identifies the entry inside the RepoModel
+  * (indirectly the file / folder).
+  */
+void ScriptRepositoryView::CheckBoxDelegate::paint(
+    QPainter *painter, const QStyleOptionViewItem &option,
+    const QModelIndex &index) const {
   if (!index.isValid())
     return;
   if (painter->device() == 0)
-    return;  
-  
+    return;
+
   QStyleOptionViewItemV4 modifiedOption(option);
-  
-  QPoint p = modifiedOption.rect.center(); 
-  QSize curr = modifiedOption.rect.size(); 
-  int min_value = (int)((curr.width()<curr.height())?curr.width():curr.height()*.8);
-  //make the checkbox a square in the center of the cell
-  modifiedOption.rect.setSize(QSize(min_value,min_value));
+
+  QPoint p = modifiedOption.rect.center();
+  QSize curr = modifiedOption.rect.size();
+  int min_value =
+      (int)((curr.width() < curr.height()) ? curr.width() : curr.height() * .8);
+  // make the checkbox a square in the center of the cell
+  modifiedOption.rect.setSize(QSize(min_value, min_value));
   modifiedOption.rect.moveCenter(p);
   // get the current state of this entry
   QString state = index.model()->data(index, Qt::DisplayRole).toString();
@@ -427,130 +468,137 @@ void ScriptRepositoryView::CheckBoxDelegate::paint(QPainter *painter, const QSty
   else if (state == "false")
     modifiedOption.state |= QStyle::State_Off;
   else
-  	return;
-  // draw it 
-  QApplication::style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck, &modifiedOption, painter); 
-
+    return;
+  // draw it
+  QApplication::style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck,
+                                       &modifiedOption, painter);
 }
 
-/** Reacts to the iteraction with the user when he clicks on the buttons displayed at paint. 
+/** Reacts to the iteraction with the user when he clicks on the buttons
+ *displayed at paint.
  *
- *  Given the state of an entry (folder/file) there is only on available action. So, 
- *  it is enough to get the event that the user interact with the checkbox to decide what 
- *  to do. 
- *  
- *  It will filter the event in order to get the Left-Click of mouse. If it gets the 
- *  click of the mouse, it will trigger the action to toggle the state of the checkbox, 
- *  which means, trigger the action 'setTrue' if the current state is 'false' of 
+ *  Given the state of an entry (folder/file) there is only on available action.
+ *So,
+ *  it is enough to get the event that the user interact with the checkbox to
+ *decide what
+ *  to do.
+ *
+ *  It will filter the event in order to get the Left-Click of mouse. If it gets
+ *the
+ *  click of the mouse, it will trigger the action to toggle the state of the
+ *checkbox,
+ *  which means, trigger the action 'setTrue' if the current state is 'false' of
  *  trigger the action 'setFalse' if the current state is 'true'.
- *  
+ *
  * @param event: The event given by the framework
  * @param model: Pointer to the model needed to retrive the status of the entry
  * @param index: identifies the entry (file/folder)
  * @param option: Provided by the framewor, and passed on to the base class.
  * @return true if it handles or false to ignore.
 */
-bool ScriptRepositoryView::CheckBoxDelegate::editorEvent(QEvent *event,
-                                                         QAbstractItemModel *model,
-                                                         const QStyleOptionViewItem &/*option*/,
-                                                         const QModelIndex &index){
- if (event->type() == QEvent::MouseButtonPress){
-  QString value = model->data(index, Qt::DisplayRole).toString();
-  QString action = "setFalse";
-  if (value == "false")
-    action = "setTrue";
-  return model->setData(index, action, Qt::EditRole);
- }else{
-   // QStyledItemDelegate::editorEvent(event, model, option, index);
-   return true;// Does not allow the event to be catched by another one
- }
+bool ScriptRepositoryView::CheckBoxDelegate::editorEvent(
+    QEvent *event, QAbstractItemModel *model,
+    const QStyleOptionViewItem & /*option*/, const QModelIndex &index) {
+  if (event->type() == QEvent::MouseButtonPress) {
+    QString value = model->data(index, Qt::DisplayRole).toString();
+    QString action = "setFalse";
+    if (value == "false")
+      action = "setTrue";
+    return model->setData(index, action, Qt::EditRole);
+  } else {
+    // QStyledItemDelegate::editorEvent(event, model, option, index);
+    return true; // Does not allow the event to be catched by another one
+  }
 }
 /////////////////////
 // RemoveEntryDelegate
 /////////////////////
 
 ScriptRepositoryView::RemoveEntryDelegate::RemoveEntryDelegate(QObject *parent)
-  :QStyledItemDelegate(parent)
-{}
-  /** Draws the column 3 (delete) of ScriptRepositoryView. 
-   *
-   *  This function is called every time the ScriptRepository needs to draw the widget 
-   *  for the delete column of the file/folder inside the ScriptRepository. 
-   *  It displays a trash icon to indicate user that it is used to remove entries.
-   * 
-   * @param painter: Required to draw the widget
-   * @param option: Provided by the framework and has information displaying the widget. 
-   * @param index: Identifies the entry inside the RepoModel (indirectly the file / folder).
-   */
+    : QStyledItemDelegate(parent) {}
+/** Draws the column 3 (delete) of ScriptRepositoryView.
+ *
+ *  This function is called every time the ScriptRepository needs to
+ *draw the widget for the delete column of the file/folder inside the
+ *ScriptRepository.  It displays a trash icon to indicate user that it
+ *is used to remove entries.
+ *
+ * @param painter: Required to draw the widget
+ * @param option: Provided by the framework and has information
+ *displaying the widget.
+ * @param index: Identifies the entry inside the RepoModel (indirectly
+ * the file / folder).
+ */
 void ScriptRepositoryView::RemoveEntryDelegate::paint(
-       QPainter* painter,
-       const QStyleOptionViewItem & option,
-       const QModelIndex & index
-       ) const
-{
-  
+    QPainter *painter, const QStyleOptionViewItem &option,
+    const QModelIndex &index) const {
+
   if (!index.isValid())
     return;
-  if (painter->device() ==0)
+  if (painter->device() == 0)
     return;
 
-  QIcon icon ; 
+  QIcon icon;
   // get the state and chose the best fit icon
   QString entry_type = index.model()->data(index, Qt::DisplayRole).toString();
 
   if (entry_type == "protected")
     return;
-  icon =  QIcon::fromTheme("emptytrash", QIcon(QPixmap(":/win/emptytrash")));
+  icon = QIcon::fromTheme("emptytrash", QIcon(QPixmap(":/win/emptytrash")));
 
   // define the region to draw the icon
-  QRect buttonRect( option.rect);  
-  int min_val = buttonRect.width()<buttonRect.height() ? buttonRect.width() : buttonRect.height();
+  QRect buttonRect(option.rect);
+  int min_val = buttonRect.width() < buttonRect.height() ? buttonRect.width()
+                                                         : buttonRect.height();
   // make it square
-  buttonRect.setWidth(min_val); 
-  buttonRect.setHeight(min_val); 
+  buttonRect.setWidth(min_val);
+  buttonRect.setHeight(min_val);
   buttonRect.moveCenter(option.rect.center());
 
   // define the options to draw a push button with the icon displayed
   QStyleOptionButton button;
   button.rect = buttonRect;
   button.icon = icon;
-  int icon_size =(int) (min_val*.8); 
-  button.iconSize = QSize(icon_size,icon_size);
-  button.state =  QStyle::State_Enabled;
+  int icon_size = (int)(min_val * .8);
+  button.iconSize = QSize(icon_size, icon_size);
+  button.state = QStyle::State_Enabled;
   // draw a push button
-  QApplication::style()->drawControl
-    (QStyle::CE_PushButton, &button, painter);
+  QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter);
 }
 
-/** Reacts to the iteraction with the user when he clicks on the buttons displayed at paint. 
+/** Reacts to the iteraction with the user when he clicks on the buttons
+ *displayed at paint.
+ *
+ *  Clicking on the delete icon there is only on available action (to delete the
+ *entry). So,
+ *  it is enough to get the event that the user interact with the pushbutton to
+ *decide what
+ *  to do.
+ *
+ *  It will filter the event in order to get the Left-Click of mouse. If it gets
+ *the
+ *  click of the mouse, it will trigger the action delete to the model
  *
- *  Clicking on the delete icon there is only on available action (to delete the entry). So, 
- *  it is enough to get the event that the user interact with the pushbutton to decide what 
- *  to do. 
- *  
- *  It will filter the event in order to get the Left-Click of mouse. If it gets the 
- *  click of the mouse, it will trigger the action delete to the model 
- *  
  * @param event: The event given by the framework
  * @param model: Pointer to the model needed to retrive the status of the entry
  * @param index: identifies the entry (file/folder)
  * @param option: Provided by the framewor, and passed on to the base class.
  * @return true if it handles or false to ignore.
 */
-bool  ScriptRepositoryView::RemoveEntryDelegate::editorEvent(QEvent *event,
-                                   QAbstractItemModel *model,
-                                                      const QStyleOptionViewItem &/*option*/,
-                                   const QModelIndex &index) {
-  // if event is mouse click 
-  if (event->type() == QEvent::MouseButtonPress){
+bool ScriptRepositoryView::RemoveEntryDelegate::editorEvent(
+    QEvent *event, QAbstractItemModel *model,
+    const QStyleOptionViewItem & /*option*/, const QModelIndex &index) {
+  // if event is mouse click
+  if (event->type() == QEvent::MouseButtonPress) {
     QString entry = index.model()->data(index, Qt::DisplayRole).toString();
     if (entry == "protected")
       return true;
     QString action = "delete";
-    return model->setData(index, action, Qt::EditRole);  
-  }else{
-    return true; //Does not allow others events to be processed (example: double-click)
-  }   
+    return model->setData(index, action, Qt::EditRole);
+  } else {
+    return true; // Does not allow others events to be processed (example:
+                 // double-click)
+  }
 }
 
 /**
@@ -558,20 +606,21 @@ bool  ScriptRepositoryView::RemoveEntryDelegate::editorEvent(QEvent *event,
  *
  * @param link :: the folder link to open.
  */
-void ScriptRepositoryView::openFolderLink(QString link){
-  const std::string error_msg = "Unable to open \"" + link.toStdString() + "\".  Reason: ";
+void ScriptRepositoryView::openFolderLink(QString link) {
+  const std::string error_msg =
+      "Unable to open \"" + link.toStdString() + "\".  Reason: ";
 
-  // QUrl::fromLocalFile seems to be the most robust way of constructing QUrls on
+  // QUrl::fromLocalFile seems to be the most robust way of constructing QUrls
+  // on
   // the local file system for all platforms.
   const QUrl url = QUrl::fromLocalFile(link);
-  if( !url.isValid() )
-  {
+  if (!url.isValid()) {
     g_log.error() << error_msg << "Invalid (malformed) URL." << std::endl;
     return;
   }
 
   const bool openSuccessful = QDesktopServices::openUrl(url);
-  if( !openSuccessful )
+  if (!openSuccessful)
     g_log.error() << error_msg << "Could not find directory." << std::endl;
 }
 
diff --git a/MantidQt/API/src/SelectionNotificationService.cpp b/MantidQt/API/src/SelectionNotificationService.cpp
index 428f83720a2395c3609d55d68e1f2c8981562b45..9fc1bea6be9fc8142bb71302609bd21519fbf71a 100644
--- a/MantidQt/API/src/SelectionNotificationService.cpp
+++ b/MantidQt/API/src/SelectionNotificationService.cpp
@@ -6,21 +6,15 @@ using namespace MantidQt::API;
 /**
  * Empty private constructor
  */
-SelectionNotificationServiceImpl::SelectionNotificationServiceImpl()
-{
-}
-
+SelectionNotificationServiceImpl::SelectionNotificationServiceImpl() {}
 
 /**
  * Empty private destructor
  */
-SelectionNotificationServiceImpl:: ~SelectionNotificationServiceImpl()
-{
-}
-
+SelectionNotificationServiceImpl::~SelectionNotificationServiceImpl() {}
 
 /**
- *  Method to send out the QPointSelection signal to all objects that 
+ *  Method to send out the QPointSelection signal to all objects that
  *  have connected a slot to this signal.  A class just needs to call
  *  SelectionNotificationService::Instance().sendQPointSelection() with
  *  the required information.  This method then emits the corresponding
@@ -32,10 +26,9 @@ SelectionNotificationServiceImpl:: ~SelectionNotificationServiceImpl()
  *  @param qy            The y-component of the Mantid Q-vector.
  *  @param qz            The z-component of the Mantid Q-vector.
  */
-void SelectionNotificationServiceImpl::sendQPointSelection( bool lab_coords, double qx, double qy, double qz )
-{
-  emit QPointSelection_signal( lab_coords, qx, qy, qz );
-//  std::cout << "QPointSelection_signal emitted" << std::endl;
+void SelectionNotificationServiceImpl::sendQPointSelection(bool lab_coords,
+                                                           double qx, double qy,
+                                                           double qz) {
+  emit QPointSelection_signal(lab_coords, qx, qy, qz);
+  //  std::cout << "QPointSelection_signal emitted" << std::endl;
 }
-
-
diff --git a/MantidQt/API/src/SignalBlocker.cpp b/MantidQt/API/src/SignalBlocker.cpp
index c545ccd82070d639710bc5071cb073c195f53965..bb1ac18c91adeead2e22cacca30d0857fdab905f 100644
--- a/MantidQt/API/src/SignalBlocker.cpp
+++ b/MantidQt/API/src/SignalBlocker.cpp
@@ -13,9 +13,9 @@ namespace API {
  */
 template <typename Type>
 SignalBlocker<Type>::SignalBlocker(Type *obj)
-    : m_obj(obj){
-  if(m_obj == NULL){
-      throw std::runtime_error("Object to block is NULL");
+    : m_obj(obj) {
+  if (m_obj == NULL) {
+    throw std::runtime_error("Object to block is NULL");
   }
   m_obj->blockSignals(true);
 }
@@ -31,15 +31,13 @@ template <typename Type> SignalBlocker<Type>::~SignalBlocker() {
 
 template <typename Type> Type *SignalBlocker<Type>::operator->() {
   if (m_obj != NULL) {
-      return m_obj;
+    return m_obj;
   } else {
-      throw std::runtime_error("SignalBlocker cannot access released object");
+    throw std::runtime_error("SignalBlocker cannot access released object");
   }
 }
 
-template <typename Type> void SignalBlocker<Type>::release() {
-    m_obj = NULL;
-}
+template <typename Type> void SignalBlocker<Type>::release() { m_obj = NULL; }
 
 // Template instances we need.
 template class SignalBlocker<QObject>;
diff --git a/MantidQt/API/src/SignalRange.cpp b/MantidQt/API/src/SignalRange.cpp
index cdc9072721b8b44f29cd81e137443d568478d29f..1d0377c9b4a1715a6328546dda979203a677847f 100644
--- a/MantidQt/API/src/SignalRange.cpp
+++ b/MantidQt/API/src/SignalRange.cpp
@@ -2,79 +2,75 @@
 #include "MantidAPI/IMDIterator.h"
 #include "MantidKernel/MultiThreaded.h"
 #include <boost/math/special_functions/fpclassify.hpp>
-namespace MantidQt
-{
-  namespace API
-  {
-    //-------------------------------------------------------------------------
-    // Public methods
-    //-------------------------------------------------------------------------
+namespace MantidQt {
+namespace API {
+//-------------------------------------------------------------------------
+// Public methods
+//-------------------------------------------------------------------------
 
-    /**
-     * Create a signal range that covers the whole workspace. The signal
-     * values are treated with the specified normalization.
-     * [Default: NoNormalization]
-     * @param workspace A reference to a workspace object
-     * @param normalization The type of normalization
-     */
-    SignalRange::SignalRange(const Mantid::API::IMDWorkspace &workspace,
-                             const Mantid::API::MDNormalization normalization)
-      : m_interval(), m_normalization(normalization)
-    {
-      findFullRange(workspace, NULL);
-    }
+/**
+ * Create a signal range that covers the whole workspace. The signal
+ * values are treated with the specified normalization.
+ * [Default: NoNormalization]
+ * @param workspace A reference to a workspace object
+ * @param normalization The type of normalization
+ */
+SignalRange::SignalRange(const Mantid::API::IMDWorkspace &workspace,
+                         const Mantid::API::MDNormalization normalization)
+    : m_interval(), m_normalization(normalization) {
+  findFullRange(workspace, NULL);
+}
 
-    /**
-     * Find the signal range that region defined by the function gives on the workspace
-     * using the given normalization
-     * @param workspace A reference to a workspace object
-     * @param function A reference to an MDImplicitFunction object that defines a region
-     *                 of the workspace
-     * @param normalization The type of normalization
-     */
-    SignalRange::SignalRange(const Mantid::API::IMDWorkspace &workspace,
-                             Mantid::Geometry::MDImplicitFunction &function,
-                             const Mantid::API::MDNormalization normalization)
-      :m_interval(), m_normalization(normalization)
-    {
-      findFullRange(workspace, &function);
-    }
+/**
+ * Find the signal range that region defined by the function gives on the
+ * workspace
+ * using the given normalization
+ * @param workspace A reference to a workspace object
+ * @param function A reference to an MDImplicitFunction object that defines a
+ * region
+ *                 of the workspace
+ * @param normalization The type of normalization
+ */
+SignalRange::SignalRange(const Mantid::API::IMDWorkspace &workspace,
+                         Mantid::Geometry::MDImplicitFunction &function,
+                         const Mantid::API::MDNormalization normalization)
+    : m_interval(), m_normalization(normalization) {
+  findFullRange(workspace, &function);
+}
 
-    /**
-     * @return A QwtDoubleInterval defining the range
-     */
-    QwtDoubleInterval SignalRange::interval() const
-    {
-      return m_interval;
-    }
+/**
+ * @return A QwtDoubleInterval defining the range
+ */
+QwtDoubleInterval SignalRange::interval() const { return m_interval; }
 
-    //-------------------------------------------------------------------------
-    // Private methods
-    //-------------------------------------------------------------------------
-    /**
-     * @param workspace A reference to the workspace the explore
-     * @param function A pointer to an MDImplicitFunction object that defines a region
-     *                 of the workspace. NULL indicates use whole workspace
-     */
-    void SignalRange::findFullRange(const Mantid::API::IMDWorkspace &workspace,
-                                    Mantid::Geometry::MDImplicitFunction *function)
-    {
-      auto iterators = workspace.createIterators(PARALLEL_GET_MAX_THREADS, function);
-      m_interval = getRange(iterators);
-    }
+//-------------------------------------------------------------------------
+// Private methods
+//-------------------------------------------------------------------------
+/**
+ * @param workspace A reference to the workspace the explore
+ * @param function A pointer to an MDImplicitFunction object that defines a
+ * region
+ *                 of the workspace. NULL indicates use whole workspace
+ */
+void SignalRange::findFullRange(
+    const Mantid::API::IMDWorkspace &workspace,
+    Mantid::Geometry::MDImplicitFunction *function) {
+  auto iterators =
+      workspace.createIterators(PARALLEL_GET_MAX_THREADS, function);
+  m_interval = getRange(iterators);
+}
 
-    /**
-     * @param iterators :: vector of IMDIterator of what to find
-     * @return the min/max range, or 0-1.0 if not found
-     */
-    QwtDoubleInterval SignalRange::getRange(const std::vector<Mantid::API::IMDIterator *> &iterators)
-    {
-      std::vector<QwtDoubleInterval> intervals(iterators.size());
-      // cppcheck-suppress syntaxError
+/**
+ * @param iterators :: vector of IMDIterator of what to find
+ * @return the min/max range, or 0-1.0 if not found
+ */
+QwtDoubleInterval SignalRange::getRange(
+    const std::vector<Mantid::API::IMDIterator *> &iterators) {
+  std::vector<QwtDoubleInterval> intervals(iterators.size());
+  // cppcheck-suppress syntaxError
       PRAGMA_OMP( parallel for schedule(dynamic, 1))
-      for (int i=0; i < int(iterators.size()); i++)
-      {
-        Mantid::API::IMDIterator * it = iterators[i];
+      for (int i = 0; i < int(iterators.size()); i++) {
+        Mantid::API::IMDIterator *it = iterators[i];
         QwtDoubleInterval range = this->getRange(it);
         intervals[i] = range;
         // don't delete iterator in parallel. MSVC doesn't like it
@@ -84,74 +80,71 @@ namespace MantidQt
       // Combine the overall min/max
       double minSignal = DBL_MAX;
       double maxSignal = -DBL_MAX;
-      for (size_t i=0; i < iterators.size(); i++)
-      {
+      for (size_t i = 0; i < iterators.size(); i++) {
         delete iterators[i];
 
         double signal;
         signal = intervals[i].minValue();
-        if (boost::math::isnan(signal) || boost::math::isinf(signal)) continue;
-        if ( signal < minSignal) minSignal = signal;
+        if (boost::math::isnan(signal) || boost::math::isinf(signal))
+          continue;
+        if (signal < minSignal)
+          minSignal = signal;
 
         signal = intervals[i].maxValue();
-        if (boost::math::isnan(signal) || boost::math::isinf(signal)) continue;
-        if ( signal > maxSignal) maxSignal = signal;
+        if (boost::math::isnan(signal) || boost::math::isinf(signal))
+          continue;
+        if (signal > maxSignal)
+          maxSignal = signal;
       }
 
-      if (minSignal == DBL_MAX)
-      {
+      if (minSignal == DBL_MAX) {
         minSignal = 0.0;
         maxSignal = 1.0;
       }
       if (minSignal < maxSignal)
         return QwtDoubleInterval(minSignal, maxSignal);
-      else
-      {
+      else {
         if (minSignal != 0)
           // Possibly only one value in range
-          return QwtDoubleInterval(minSignal*0.5, minSignal*1.5);
+          return QwtDoubleInterval(minSignal * 0.5, minSignal * 1.5);
         else
           // Other default value
           return QwtDoubleInterval(0., 1.0);
       }
-    }
+}
 
-    /**
-     * @param it :: IMDIterator of what to find
-     * @return the min/max range, or INFINITY if not found
-     */
-    QwtDoubleInterval SignalRange::getRange(Mantid::API::IMDIterator * it)
-    {
-      if (!it)
-        return QwtDoubleInterval(0., 1.0);
-      if (!it->valid())
-        return QwtDoubleInterval(0., 1.0);
-      // Use the current normalization
-      it->setNormalization(m_normalization);
+/**
+ * @param it :: IMDIterator of what to find
+ * @return the min/max range, or INFINITY if not found
+ */
+QwtDoubleInterval SignalRange::getRange(Mantid::API::IMDIterator *it) {
+  if (!it)
+    return QwtDoubleInterval(0., 1.0);
+  if (!it->valid())
+    return QwtDoubleInterval(0., 1.0);
+  // Use the current normalization
+  it->setNormalization(m_normalization);
 
-      double minSignal = DBL_MAX;
-      double maxSignal = -DBL_MAX;
-      auto inf = std::numeric_limits<double>::infinity();
-      do
-      {
-        double signal = it->getNormalizedSignal();
-        // Skip any 'infs' as it screws up the color scale
-        if (signal != inf)
-        {
-          if (signal < minSignal) minSignal = signal;
-          if (signal > maxSignal) maxSignal = signal;
-        }
-      } while (it->next());
-
-
-      if (minSignal == DBL_MAX)
-      {
-        minSignal = inf;
-        maxSignal = inf;
-      }
-      return QwtDoubleInterval(minSignal, maxSignal);
+  double minSignal = DBL_MAX;
+  double maxSignal = -DBL_MAX;
+  auto inf = std::numeric_limits<double>::infinity();
+  do {
+    double signal = it->getNormalizedSignal();
+    // Skip any 'infs' as it screws up the color scale
+    if (signal != inf) {
+      if (signal < minSignal)
+        minSignal = signal;
+      if (signal > maxSignal)
+        maxSignal = signal;
     }
+  } while (it->next());
 
+  if (minSignal == DBL_MAX) {
+    minSignal = inf;
+    maxSignal = inf;
+  }
+  return QwtDoubleInterval(minSignal, maxSignal);
+}
 
-  } //namespace API
-} //namespace MantidQt
+} // namespace API
+} // namespace MantidQt
diff --git a/MantidQt/API/src/SyncedCheckboxes.cpp b/MantidQt/API/src/SyncedCheckboxes.cpp
index b7ffd02c236b9e3795fa54cd74ce80c90035ac76..94c6244abb34f0a538618972fe89b430c34d1bec 100644
--- a/MantidQt/API/src/SyncedCheckboxes.cpp
+++ b/MantidQt/API/src/SyncedCheckboxes.cpp
@@ -1,102 +1,91 @@
 #include "MantidQtAPI/SyncedCheckboxes.h"
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-namespace API
-{
+namespace MantidQt {
+namespace API {
 
+//----------------------------------------------------------------------------------------------
+/** Constructor that links a menu and a button
+ *
+ * @param menu :: menu to link
+ * @param button :: button to link
+ * @param checked :: state (checked or not) that they start in
+ */
+SyncedCheckboxes::SyncedCheckboxes(QAction *menu, QAbstractButton *button,
+                                   bool checked)
+    : m_menu(menu), m_button(button) {
+  m_menu->setCheckable(true);
+  m_button->setCheckable(true);
+  m_menu->setChecked(checked);
+  m_button->setChecked(checked);
+  // Now connect each signal to this object
+  connect(m_menu, SIGNAL(toggled(bool)), this, SLOT(on_menu_toggled(bool)));
+  connect(m_button, SIGNAL(toggled(bool)), this, SLOT(on_button_toggled(bool)));
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Constructor that links a menu and a button
-   *
-   * @param menu :: menu to link
-   * @param button :: button to link
-   * @param checked :: state (checked or not) that they start in
-   */
-  SyncedCheckboxes::SyncedCheckboxes(QAction * menu, QAbstractButton * button, bool checked)
-  : m_menu(menu), m_button(button)
-  {
-    m_menu->setCheckable(true);
-    m_button->setCheckable(true);
-    m_menu->setChecked(checked);
-    m_button->setChecked(checked);
-    // Now connect each signal to this object
-    connect(m_menu, SIGNAL(toggled(bool)), this, SLOT(on_menu_toggled(bool)));
-    connect(m_button, SIGNAL(toggled(bool)), this, SLOT(on_button_toggled(bool)));
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  SyncedCheckboxes::~SyncedCheckboxes()
-  {
-  }
-  
-  //----------------------------------------------------------------------------------------------
-  /** Manually toggle the state of both checkboxes
-   *
-   * @param val :: True to check the boxes.
-   */
-  void SyncedCheckboxes::toggle(bool val)
-  {
-    // Set both GUI elements
-    m_button->blockSignals(true);
-    m_button->setChecked(val);
-    m_button->blockSignals(false);
-    m_menu->blockSignals(true);
-    m_menu->setChecked(val);
-    m_menu->blockSignals(false);
-    // Re-transmit the signal
-    emit toggled(val);
-  }
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+SyncedCheckboxes::~SyncedCheckboxes() {}
 
-  //----------------------------------------------------------------------------------------------
-  /** Enable or disable both the menu and the checkboxes
-   *
-   * @param val :: true for Enabled
-   */
-  void SyncedCheckboxes::setEnabled(bool val)
-  {
-    m_menu->setEnabled(val);
-    m_button->setEnabled(val);
-  }
+//----------------------------------------------------------------------------------------------
+/** Manually toggle the state of both checkboxes
+ *
+ * @param val :: True to check the boxes.
+ */
+void SyncedCheckboxes::toggle(bool val) {
+  // Set both GUI elements
+  m_button->blockSignals(true);
+  m_button->setChecked(val);
+  m_button->blockSignals(false);
+  m_menu->blockSignals(true);
+  m_menu->setChecked(val);
+  m_menu->blockSignals(false);
+  // Re-transmit the signal
+  emit toggled(val);
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Set the visibility of both the menu and the checkboxes
-   *
-   * @param val :: true for visible
-   */
-  void SyncedCheckboxes::setVisible(bool val)
-  {
-    m_menu->setVisible(val);
-    m_button->setVisible(val);
-  }
+//----------------------------------------------------------------------------------------------
+/** Enable or disable both the menu and the checkboxes
+ *
+ * @param val :: true for Enabled
+ */
+void SyncedCheckboxes::setEnabled(bool val) {
+  m_menu->setEnabled(val);
+  m_button->setEnabled(val);
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Slot called when the menu is toggled */
-  void SyncedCheckboxes::on_menu_toggled(bool val)
-  {
-    // Adjust the state of the other
-    m_button->blockSignals(true);
-    m_button->setChecked(val);
-    m_button->blockSignals(false);
-    // Re-transmit the signal
-    emit toggled(val);
-  }
+//----------------------------------------------------------------------------------------------
+/** Set the visibility of both the menu and the checkboxes
+ *
+ * @param val :: true for visible
+ */
+void SyncedCheckboxes::setVisible(bool val) {
+  m_menu->setVisible(val);
+  m_button->setVisible(val);
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Slot called when the button is toggled */
-  void SyncedCheckboxes::on_button_toggled(bool val)
-  {
-    // Adjust the state of the other
-    m_menu->blockSignals(true);
-    m_menu->setChecked(val);
-    m_menu->blockSignals(false);
-    // Re-transmit the signal
-    emit toggled(val);
-  }
+//----------------------------------------------------------------------------------------------
+/** Slot called when the menu is toggled */
+void SyncedCheckboxes::on_menu_toggled(bool val) {
+  // Adjust the state of the other
+  m_button->blockSignals(true);
+  m_button->setChecked(val);
+  m_button->blockSignals(false);
+  // Re-transmit the signal
+  emit toggled(val);
+}
 
+//----------------------------------------------------------------------------------------------
+/** Slot called when the button is toggled */
+void SyncedCheckboxes::on_button_toggled(bool val) {
+  // Adjust the state of the other
+  m_menu->blockSignals(true);
+  m_menu->setChecked(val);
+  m_menu->blockSignals(false);
+  // Re-transmit the signal
+  emit toggled(val);
+}
 
 } // namespace Mantid
 } // namespace API
diff --git a/MantidQt/API/src/TextPropertyWidget.cpp b/MantidQt/API/src/TextPropertyWidget.cpp
index 86d516f332c493f39d6eeb742ff595f4b4dad091..bfed8b9aa7203199d92ea188c773671488999b1b 100644
--- a/MantidQt/API/src/TextPropertyWidget.cpp
+++ b/MantidQt/API/src/TextPropertyWidget.cpp
@@ -4,64 +4,56 @@
 
 using namespace Mantid::Kernel;
 
-namespace MantidQt
-{
-namespace API
-{
-
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  TextPropertyWidget::TextPropertyWidget(Mantid::Kernel::Property * prop, QWidget * parent, QGridLayout * layout, int row)
-  : PropertyWidget(prop, parent, layout, row)
-  {
-    // Label at column 0
-    m_label = new QLabel(QString::fromStdString(prop->name()), m_parent);
-    m_label->setToolTip(m_doc);
-    setLabelFont(prop, m_label);
-    m_gridLayout->addWidget(m_label, m_row, 0, 0);
-    m_widgets.push_back(m_label);
-
-    // Text box at column 1
-    m_textbox = new QLineEdit(m_parent);
-    m_textbox->setToolTip(m_doc);
-    setFieldPlaceholderText(prop, m_textbox);
-    connect(m_textbox, SIGNAL(editingFinished()), this, SLOT(userEditedProperty()));
-    m_gridLayout->addWidget(m_textbox, m_row, 1, 0);
-    m_widgets.push_back(m_textbox);
-
-    // Check if this is a masked property
-    Mantid::Kernel::MaskedProperty<std::string> * maskedProp = dynamic_cast<Mantid::Kernel::MaskedProperty<std::string> *>(prop);
-    // Make it echo those little stars
-    if (maskedProp)
-      m_textbox->setEchoMode(QLineEdit::Password);
-
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  TextPropertyWidget::~TextPropertyWidget()
-  {
-  }
-  
-  //----------------------------------------------------------------------------------------------
-  /** @return the value of the property, as typed in the GUI, as a string */
-  QString TextPropertyWidget::getValue() const
-  {
-    return m_textbox->text();
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Set the value into the GUI
-   *
-   * @param value :: string representation of the value */
-  void TextPropertyWidget::setValueImpl(const QString & value)
-  {
-    m_textbox->setText(value);
-  }
+namespace MantidQt {
+namespace API {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+TextPropertyWidget::TextPropertyWidget(Mantid::Kernel::Property *prop,
+                                       QWidget *parent, QGridLayout *layout,
+                                       int row)
+    : PropertyWidget(prop, parent, layout, row) {
+  // Label at column 0
+  m_label = new QLabel(QString::fromStdString(prop->name()), m_parent);
+  m_label->setToolTip(m_doc);
+  setLabelFont(prop, m_label);
+  m_gridLayout->addWidget(m_label, m_row, 0, 0);
+  m_widgets.push_back(m_label);
+
+  // Text box at column 1
+  m_textbox = new QLineEdit(m_parent);
+  m_textbox->setToolTip(m_doc);
+  setFieldPlaceholderText(prop, m_textbox);
+  connect(m_textbox, SIGNAL(editingFinished()), this,
+          SLOT(userEditedProperty()));
+  m_gridLayout->addWidget(m_textbox, m_row, 1, 0);
+  m_widgets.push_back(m_textbox);
+
+  // Check if this is a masked property
+  Mantid::Kernel::MaskedProperty<std::string> *maskedProp =
+      dynamic_cast<Mantid::Kernel::MaskedProperty<std::string> *>(prop);
+  // Make it echo those little stars
+  if (maskedProp)
+    m_textbox->setEchoMode(QLineEdit::Password);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+TextPropertyWidget::~TextPropertyWidget() {}
+
+//----------------------------------------------------------------------------------------------
+/** @return the value of the property, as typed in the GUI, as a string */
+QString TextPropertyWidget::getValue() const { return m_textbox->text(); }
+
+//----------------------------------------------------------------------------------------------
+/** Set the value into the GUI
+ *
+ * @param value :: string representation of the value */
+void TextPropertyWidget::setValueImpl(const QString &value) {
+  m_textbox->setText(value);
+}
 
 } // namespace MantidQt
 } // namespace API
diff --git a/MantidQt/API/src/UserSubWindow.cpp b/MantidQt/API/src/UserSubWindow.cpp
index 6dace365d7f4fcdb8535a853873e8c3ac22c9547..7f72dc90de2f5fcd8a31eba02633a4fff459ea6c 100644
--- a/MantidQt/API/src/UserSubWindow.cpp
+++ b/MantidQt/API/src/UserSubWindow.cpp
@@ -20,38 +20,36 @@ using namespace MantidQt::API;
 /**
  * Default Constructor
  */
-UserSubWindow::UserSubWindow(QWidget* parent) :  
-  QMainWindow(parent), m_bIsInitialized(false), m_isPyInitialized(false), m_ifacename(""), m_pythonRunner()
-{
+UserSubWindow::UserSubWindow(QWidget *parent)
+    : QMainWindow(parent), m_bIsInitialized(false), m_isPyInitialized(false),
+      m_ifacename(""), m_pythonRunner() {
   setAttribute(Qt::WA_DeleteOnClose, false);
 
-  // re-emit the run Python code from m_pyRunner, to work this signal must reach the slot in QtiPlot
-  connect(&m_pythonRunner, SIGNAL(runAsPythonScript(const QString&, bool)),
-    this, SIGNAL(runAsPythonScript(const QString&, bool)));
-
+  // re-emit the run Python code from m_pyRunner, to work this signal must reach
+  // the slot in QtiPlot
+  connect(&m_pythonRunner, SIGNAL(runAsPythonScript(const QString &, bool)),
+          this, SIGNAL(runAsPythonScript(const QString &, bool)));
 }
 
 /**
  * Destructor
  */
-UserSubWindow::~UserSubWindow()
-{
-}
+UserSubWindow::~UserSubWindow() {}
 
 /**
  * Create the layout for this dialog.
  */
-void UserSubWindow::initializeLayout()
-{
-  if( isInitialized() ) return;
+void UserSubWindow::initializeLayout() {
+  if (isInitialized())
+    return;
 
-  //Calls the derived class function
+  // Calls the derived class function
   this->initLayout();
 
-  //Se the object name to the interface name
+  // Se the object name to the interface name
   setObjectName(m_ifacename);
 
-  //Set the icon
+  // Set the icon
   setWindowIcon(QIcon(":/MantidPlot_Icon_32offset.png"));
 
   m_bIsInitialized = true;
@@ -61,29 +59,24 @@ void UserSubWindow::initializeLayout()
  * Has this window been initialized yet
  *  @returns Whether initialzedLayout has been called yet
  */
-bool UserSubWindow::isInitialized() const
-{ 
-  return m_bIsInitialized; 
-}
+bool UserSubWindow::isInitialized() const { return m_bIsInitialized; }
 
 /**
  * Has the Python initialization function been called yet?
  * @returns Whether initializeLocalPython  has been called yet
  */
-bool UserSubWindow::isPyInitialized() const
-{ 
-  return m_isPyInitialized; 
-}
+bool UserSubWindow::isPyInitialized() const { return m_isPyInitialized; }
 
 /**
- * Initialize local Python environment. This is called once when the interface is created and
+ * Initialize local Python environment. This is called once when the interface
+ * is created and
  * is meant to be used to run one off code, i.e. importing modules.
  */
-void UserSubWindow::initializeLocalPython()
-{
-  if( isPyInitialized() ) return;
+void UserSubWindow::initializeLocalPython() {
+  if (isPyInitialized())
+    return;
 
-  //Call overridable function
+  // Call overridable function
   this->initLocalPython();
   m_isPyInitialized = true;
 }
@@ -96,39 +89,39 @@ void UserSubWindow::initializeLocalPython()
  * @param message :: The message to show
  */
 
-void UserSubWindow::showInformationBox(const QString & message) const
-{
-  if( !message.isEmpty() )
-  {
-    QMessageBox::information(const_cast<UserSubWindow*>(this), this->windowTitle(), message);
+void UserSubWindow::showInformationBox(const QString &message) const {
+  if (!message.isEmpty()) {
+    QMessageBox::information(const_cast<UserSubWindow *>(this),
+                             this->windowTitle(), message);
   }
 }
 
 /**
- * Execute a piece of Python code and the output that was written to stdout, i.e. the output from print
+ * Execute a piece of Python code and the output that was written to stdout,
+ * i.e. the output from print
  * statements
  * @param code :: The code to execute
- * @param no_output :: An optional flag to specify that no output is needed. If running only small commands enable this
+ * @param no_output :: An optional flag to specify that no output is needed. If
+ * running only small commands enable this
  * as it should be faster. The default value is false
  */
-QString UserSubWindow::runPythonCode(const QString & code, bool no_output)
-{
-  return m_pythonRunner.runPythonCode(code,no_output);
+QString UserSubWindow::runPythonCode(const QString &code, bool no_output) {
+  return m_pythonRunner.runPythonCode(code, no_output);
 }
 
 /**
  * Open a file selection box
- * @param save :: if true a save dialog box used (prompts for replace if file exists) otherwise a load file (file must then exist)
- * @param exts :: the dialog boxes will only show files that have extensions that match one of the QStrings in the list
+ * @param save :: if true a save dialog box used (prompts for replace if file
+ * exists) otherwise a load file (file must then exist)
+ * @param exts :: the dialog boxes will only show files that have extensions
+ * that match one of the QStrings in the list
  */
-QString UserSubWindow::openFileDialog(const bool save, const QStringList &exts)
-{
+QString UserSubWindow::openFileDialog(const bool save,
+                                      const QStringList &exts) {
   QString filter;
-  if ( !exts.empty() )
-  {
+  if (!exts.empty()) {
     filter = "";
-    for ( int i = 0; i < exts.size(); i ++ )
-    {
+    for (int i = 0; i < exts.size(); i++) {
       filter.append("*." + exts[i] + " ");
     }
     filter = filter.trimmed();
@@ -136,18 +129,19 @@ QString UserSubWindow::openFileDialog(const bool save, const QStringList &exts)
   filter.append(";;All Files (*.*)");
 
   QString filename;
-  if( save )
-  {
-    filename = MantidQt::API::FileDialogHandler::getSaveFileName(this, "Save file", AlgorithmInputHistory::Instance().getPreviousDirectory(), filter);
-  }
-  else
-  {
-    filename = QFileDialog::getOpenFileName(this, "Open file", AlgorithmInputHistory::Instance().getPreviousDirectory(), filter);
+  if (save) {
+    filename = MantidQt::API::FileDialogHandler::getSaveFileName(
+        this, "Save file",
+        AlgorithmInputHistory::Instance().getPreviousDirectory(), filter);
+  } else {
+    filename = QFileDialog::getOpenFileName(
+        this, "Open file",
+        AlgorithmInputHistory::Instance().getPreviousDirectory(), filter);
   }
 
-  if( !filename.isEmpty() ) 
-  {
-    AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filename).absoluteDir().path());
+  if (!filename.isEmpty()) {
+    AlgorithmInputHistory::Instance().setPreviousDirectory(
+        QFileInfo(filename).absoluteDir().path());
   }
   return filename;
 }
@@ -155,8 +149,7 @@ QString UserSubWindow::openFileDialog(const bool save, const QStringList &exts)
 *  AlgorithmDialog.cpp and wont know if the validator label changes there
 *  @param parent :: a pointer to an object that will look after it deleting it
 */
-QLabel* UserSubWindow::newValidator(QWidget *parent)
-{
+QLabel *UserSubWindow::newValidator(QWidget *parent) {
   QLabel *validLbl = new QLabel("*", parent);
   QPalette pal = validLbl->palette();
   pal.setColor(QPalette::WindowText, Qt::darkRed);
@@ -171,7 +164,6 @@ QLabel* UserSubWindow::newValidator(QWidget *parent)
  * Set the interface name
  * @param iface_name :: The name of the interface
  */
-void UserSubWindow::setInterfaceName(const QString & iface_name)
-{
+void UserSubWindow::setInterfaceName(const QString &iface_name) {
   m_ifacename = iface_name;
 }
diff --git a/MantidQt/API/src/VatesViewerInterface.cpp b/MantidQt/API/src/VatesViewerInterface.cpp
index 7fc9cbbb73933619099e6c4614b27f774310edfd..85a04361d8b96ff941607395b16c1e48045f36a5 100644
--- a/MantidQt/API/src/VatesViewerInterface.cpp
+++ b/MantidQt/API/src/VatesViewerInterface.cpp
@@ -2,29 +2,20 @@
 
 using namespace MantidQt::API;
 
-VatesViewerInterface::VatesViewerInterface() : QWidget()
-{
-}
+VatesViewerInterface::VatesViewerInterface() : QWidget() {}
 
-VatesViewerInterface::VatesViewerInterface(QWidget *parent) : QWidget(parent)
-{
-}
+VatesViewerInterface::VatesViewerInterface(QWidget *parent) : QWidget(parent) {}
 
-VatesViewerInterface::~VatesViewerInterface()
-{
-}
+VatesViewerInterface::~VatesViewerInterface() {}
 
-void VatesViewerInterface::setupPluginMode()
-{
-}
+void VatesViewerInterface::setupPluginMode() {}
 
-void VatesViewerInterface::renderWorkspace(QString workSpaceName, int workspaceType, std::string instrumentName)
-{
+void VatesViewerInterface::renderWorkspace(QString workSpaceName,
+                                           int workspaceType,
+                                           std::string instrumentName) {
   UNUSED_ARG(workSpaceName);
   UNUSED_ARG(workspaceType);
   UNUSED_ARG(instrumentName);
 }
 
-void VatesViewerInterface::shutdown()
-{
-}
+void VatesViewerInterface::shutdown() {}
diff --git a/MantidQt/API/src/WidgetScrollbarDecorator.cpp b/MantidQt/API/src/WidgetScrollbarDecorator.cpp
index ae24867d077981d12bf26a66ba8e3d17f90b9012..c222bf9b777a92dafbea6676165aa61f30e7526f 100644
--- a/MantidQt/API/src/WidgetScrollbarDecorator.cpp
+++ b/MantidQt/API/src/WidgetScrollbarDecorator.cpp
@@ -38,7 +38,7 @@ WidgetScrollbarDecorator::WidgetScrollbarDecorator(QWidget *target)
   m_scrollarea->setWidgetResizable(true);
 
   // With QMainWindows we must work on the centralWidget instead
-  auto mainwindow = dynamic_cast<QMainWindow*>(m_target);
+  auto mainwindow = dynamic_cast<QMainWindow *>(m_target);
   if (mainwindow)
     m_target = mainwindow->centralWidget();
 }
@@ -111,8 +111,7 @@ void WidgetScrollbarDecorator::setEnabled(bool enable) {
  *
  * @param width Minimum width target may shrink to before scrollbars appear
  */
-void WidgetScrollbarDecorator::setThresholdWidth(int width)
-{
+void WidgetScrollbarDecorator::setThresholdWidth(int width) {
   m_viewport->setMinimumWidth(width);
 }
 
@@ -129,8 +128,7 @@ void WidgetScrollbarDecorator::setThresholdWidth(int width)
  *
  * @param height Minimum height target may shrink to before scrollbars appear
  */
-void WidgetScrollbarDecorator::setThresholdHeight(int height)
-{
+void WidgetScrollbarDecorator::setThresholdHeight(int height) {
   m_viewport->setMinimumHeight(height);
 }
 
@@ -148,7 +146,6 @@ void WidgetScrollbarDecorator::setThresholdHeight(int height)
  * @param width Minimum width target may shrink to before scrollbars appear
  * @param height Minimum height target may shrink to before scrollbars appear
  */
-void WidgetScrollbarDecorator::setThresholdSize(int width, int height)
-{
+void WidgetScrollbarDecorator::setThresholdSize(int width, int height) {
   m_viewport->setMinimumSize(width, height);
 }
diff --git a/MantidQt/API/src/WorkspaceObserver.cpp b/MantidQt/API/src/WorkspaceObserver.cpp
index 7569110bd7d271f3c0df5384efa24e715b81ecfa..3390cb5f9f5c22f427600faefe6ce0b92ef53306 100644
--- a/MantidQt/API/src/WorkspaceObserver.cpp
+++ b/MantidQt/API/src/WorkspaceObserver.cpp
@@ -4,232 +4,218 @@
 #include "MantidQtAPI/WorkspaceObserver.h"
 #include "MantidAPI/AnalysisDataService.h"
 
-namespace MantidQt
-{
-  namespace API
+namespace MantidQt {
+namespace API {
+
+//---------------------------------------------------------------------------
+// Observer callback
+//---------------------------------------------------------------------------
+void ObserverCallback::handlePreDelete(const std::string &name,
+                                       Mantid::API::Workspace_sptr workspace) {
+  m_observer->preDeleteHandle(name, workspace);
+}
+
+void ObserverCallback::handlePostDelete(const std::string &name) {
+  m_observer->postDeleteHandle(name);
+}
+
+void ObserverCallback::handleAdd(const std::string &name,
+                                 Mantid::API::Workspace_sptr workspace) {
+  m_observer->addHandle(name, workspace);
+}
+
+void ObserverCallback::handleAfterReplace(
+    const std::string &name, Mantid::API::Workspace_sptr workspace) {
+  m_observer->afterReplaceHandle(name, workspace);
+}
+
+void ObserverCallback::handleRename(const std::string &oldName,
+                                    const std::string &newName) {
+  m_observer->renameHandle(oldName, newName);
+}
+
+void ObserverCallback::handleClearADS() { m_observer->clearADSHandle(); }
+
+//---------------------------------------------------------------------------
+// WorkspaceObserver
+//---------------------------------------------------------------------------
+
+/// Default constructor
+WorkspaceObserver::WorkspaceObserver()
+    : m_preDeleteObserver(*this, &WorkspaceObserver::_preDeleteHandle),
+      m_postDeleteObserver(*this, &WorkspaceObserver::_postDeleteHandle),
+      m_addObserver(*this, &WorkspaceObserver::_addHandle),
+      m_afterReplaceObserver(*this, &WorkspaceObserver::_afterReplaceHandle),
+      m_renameObserver(*this, &WorkspaceObserver::_renameHandle),
+      m_clearADSObserver(*this, &WorkspaceObserver::_clearADSHandle),
+      m_predel_observed(false), m_postdel_observed(false),
+      m_add_observed(false), m_repl_observed(false), m_rename_observed(false),
+      m_clr_observed(false) {
+  m_proxy = new ObserverCallback(this);
+}
+
+/// Destructor
+WorkspaceObserver::~WorkspaceObserver() {
+  observePreDelete(false);
+  observePostDelete(false);
+  observeAdd(false);
+  observeAfterReplace(false);
+  observeRename(false);
+  observeADSClear(false);
+
+  m_proxy->disconnect();
+  delete m_proxy;
+}
+
+/**
+ * Turn on observations of workspace delete notifications from the ADS
+ * @param turnOn :: If true observe the notifications, otherwise disable
+ * observation [default=true]
+ */
+void WorkspaceObserver::observePreDelete(bool turnOn) {
+  if (turnOn && !m_predel_observed) // Turning it on
   {
-
-    //---------------------------------------------------------------------------
-    // Observer callback
-    //---------------------------------------------------------------------------
-    void ObserverCallback::handlePreDelete(const std::string &name, Mantid::API::Workspace_sptr workspace)
-    {
-      m_observer->preDeleteHandle(name, workspace);
-    }
-
-    void ObserverCallback::handlePostDelete(const std::string &name)
-    {
-      m_observer->postDeleteHandle(name);
-    }
-
-    void ObserverCallback::handleAdd(const std::string &name, Mantid::API::Workspace_sptr workspace)
-    {
-      m_observer->addHandle(name, workspace);
-    }
-
-    void ObserverCallback::handleAfterReplace(const std::string &name, Mantid::API::Workspace_sptr workspace)
-    {
-      m_observer->afterReplaceHandle(name, workspace);
-    }
-
-    void ObserverCallback::handleRename(const std::string &oldName, const std::string &newName)
-    {
-      m_observer->renameHandle(oldName, newName);
-    }
-
-    void ObserverCallback::handleClearADS()
-    {
-      m_observer->clearADSHandle();
-    }
-
-    //---------------------------------------------------------------------------
-    // WorkspaceObserver
-    //---------------------------------------------------------------------------
-
-    /// Default constructor
-    WorkspaceObserver::WorkspaceObserver() 
-      : m_preDeleteObserver(*this,&WorkspaceObserver::_preDeleteHandle),
-        m_postDeleteObserver(*this,&WorkspaceObserver::_postDeleteHandle),
-      m_addObserver(*this,&WorkspaceObserver::_addHandle),
-      m_afterReplaceObserver(*this,&WorkspaceObserver::_afterReplaceHandle),
-      m_renameObserver(*this,&WorkspaceObserver::_renameHandle),
-      m_clearADSObserver(*this,&WorkspaceObserver::_clearADSHandle),
-      m_predel_observed(false), m_postdel_observed(false), m_add_observed(false), m_repl_observed(false),
-      m_rename_observed(false), m_clr_observed(false)
-    {
-      m_proxy = new ObserverCallback(this);
-    }
-
-    /// Destructor
-    WorkspaceObserver::~WorkspaceObserver()
-    {
-      observePreDelete(false);
-      observePostDelete(false);
-      observeAdd(false);
-      observeAfterReplace(false);
-      observeRename(false);
-      observeADSClear(false);
-
-      m_proxy->disconnect();
-      delete m_proxy;
-    }
-
-    /**
-     * Turn on observations of workspace delete notifications from the ADS
-     * @param turnOn :: If true observe the notifications, otherwise disable observation [default=true]
-     */
-    void WorkspaceObserver::observePreDelete(bool turnOn)
-    {
-      if( turnOn && !m_predel_observed) // Turning it on
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_preDeleteObserver);
-        m_proxy->connect(m_proxy, 
-          SIGNAL(preDeleteRequested(const std::string &,Mantid::API::Workspace_sptr)),
-          SLOT(handlePreDelete(const std::string &, Mantid::API::Workspace_sptr)),
-          Qt::QueuedConnection);
-      }
-      else if( !turnOn && m_predel_observed ) // Turning it off
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_preDeleteObserver);
-        m_proxy->disconnect(m_proxy, 
-          SIGNAL(preDeleteRequested(const std::string &,Mantid::API::Workspace_sptr)),
-          m_proxy,
-          SLOT(handlePreDelete(const std::string &, Mantid::API::Workspace_sptr)));
-      }
-      else {}
-      m_predel_observed = turnOn;
-    }
-
-    /**
-     * Turn on observations of workspace post delete notifications from the ADS
-     * @param turnOn :: If true observe the notifications, other wise disable observation [default=true]
-     */
-    void WorkspaceObserver::observePostDelete(bool turnOn)
-    {
-      if( turnOn && !m_postdel_observed) // Turning it on
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_postDeleteObserver);
-        m_proxy->connect(m_proxy,
-          SIGNAL(postDeleteRequested(const std::string &)),
-          SLOT(handlePostDelete(const std::string &)),
-          Qt::QueuedConnection);
-      }
-      else if( !turnOn && m_postdel_observed ) // Turning it off
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_postDeleteObserver);
-        m_proxy->disconnect(m_proxy,
-          SIGNAL(postDeleteRequested(const std::string &)),
-          m_proxy,
-          SLOT(handlePostDelete(const std::string &)));
-      }
-      else {}
-      m_postdel_observed = turnOn;
-    }
-
-
-    /**
-    * Turn on observations of workspace replacement notifications from the ADS
-    * @param turnOn :: If true observe the notifications, otherwise disable observation [default=true]
-    */
-    void WorkspaceObserver::observeAfterReplace(bool turnOn)
-    {
-      if( turnOn && !m_repl_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_afterReplaceObserver);
-        m_proxy->connect(m_proxy, 
-          SIGNAL(afterReplaced(const std::string &,Mantid::API::Workspace_sptr)),
-          SLOT(handleAfterReplace(const std::string &, Mantid::API::Workspace_sptr)),
-          Qt::QueuedConnection
-          );
-      }
-      else if( !turnOn && m_repl_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_afterReplaceObserver);
-        m_proxy->disconnect(m_proxy, 
-          SIGNAL(afterReplaced(const std::string &,Mantid::API::Workspace_sptr)),
-          m_proxy,
-          SLOT(handleAfterReplace(const std::string &, Mantid::API::Workspace_sptr)));
-      }
-      m_repl_observed = turnOn;
-    }
-
-    /**
-    * Turn on observations of workspace renaming notifications from the ADS
-    * @param turnOn :: If true observe the notifications, otherwise disable observation [default=true]
-    */
-    void WorkspaceObserver::observeRename(bool turnOn)
-    {
-      if( turnOn && !m_rename_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_renameObserver);
-        m_proxy->connect(m_proxy, 
-          SIGNAL(renamed(const std::string &,const std::string &)),
-          SLOT(handleRename(const std::string &, const std::string &)),
-          Qt::QueuedConnection
-          );
-      }
-      else if( !turnOn && m_rename_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_renameObserver);
-        m_proxy->disconnect(m_proxy, 
-          SIGNAL(renamed(const std::string &,const std::string &)),
-          m_proxy,
-          SLOT(handleRename(const std::string &, const std::string &)));
-      }
-      m_rename_observed = turnOn;
-    }
-
-    /**
-    * Turn on observations of workspace add notifications from the ADS
-    * @param turnOn :: If true observe the notifications, otherwise disable observation [default=true]
-    */
-    void WorkspaceObserver::observeAdd(bool turnOn)
-    {
-      if( turnOn && !m_add_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_addObserver);
-        m_proxy->connect(m_proxy, 
-          SIGNAL(addRequested(const std::string &,Mantid::API::Workspace_sptr)),
-          SLOT(handleAdd(const std::string &, Mantid::API::Workspace_sptr)),
-          Qt::QueuedConnection
-          );
-      }
-      else if( !turnOn && m_add_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_addObserver);
-        m_proxy->disconnect(m_proxy, 
-          SIGNAL(addRequested(const std::string &,Mantid::API::Workspace_sptr)),
-          m_proxy,
-          SLOT(handleAdd(const std::string &, Mantid::API::Workspace_sptr)));
-      }
-      m_add_observed = turnOn;
-    }
-
-    /**
-    * Turn on observations of workspace clear notifications from the ADS
-    * @param turnOn :: If true observe the notifications, otherwise disable observation [default=true]
-    */
-    void WorkspaceObserver::observeADSClear(bool turnOn)
-    {
-      if( turnOn && !m_clr_observed)
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(m_clearADSObserver);
-        m_proxy->connect(m_proxy,
-          SIGNAL(adsCleared()), 
-          SLOT(handleClearADS()),
-          Qt::QueuedConnection);
-      }
-      else if( !turnOn && m_clr_observed )
-      {
-        Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_clearADSObserver);
-        m_proxy->disconnect(m_proxy,
-          SIGNAL(adsCleared()),
-          m_proxy,
-          SLOT(handleClearADS()));
-      }
-      m_clr_observed = turnOn;
-    }
-
-
-  } // MantidQt
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_preDeleteObserver);
+    m_proxy->connect(
+        m_proxy, SIGNAL(preDeleteRequested(const std::string &,
+                                           Mantid::API::Workspace_sptr)),
+        SLOT(handlePreDelete(const std::string &, Mantid::API::Workspace_sptr)),
+        Qt::QueuedConnection);
+  } else if (!turnOn && m_predel_observed) // Turning it off
+  {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_preDeleteObserver);
+    m_proxy->disconnect(
+        m_proxy, SIGNAL(preDeleteRequested(const std::string &,
+                                           Mantid::API::Workspace_sptr)),
+        m_proxy, SLOT(handlePreDelete(const std::string &,
+                                      Mantid::API::Workspace_sptr)));
+  } else {
+  }
+  m_predel_observed = turnOn;
+}
+
+/**
+ * Turn on observations of workspace post delete notifications from the ADS
+ * @param turnOn :: If true observe the notifications, other wise disable
+ * observation [default=true]
+ */
+void WorkspaceObserver::observePostDelete(bool turnOn) {
+  if (turnOn && !m_postdel_observed) // Turning it on
+  {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_postDeleteObserver);
+    m_proxy->connect(m_proxy, SIGNAL(postDeleteRequested(const std::string &)),
+                     SLOT(handlePostDelete(const std::string &)),
+                     Qt::QueuedConnection);
+  } else if (!turnOn && m_postdel_observed) // Turning it off
+  {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_postDeleteObserver);
+    m_proxy->disconnect(m_proxy,
+                        SIGNAL(postDeleteRequested(const std::string &)),
+                        m_proxy, SLOT(handlePostDelete(const std::string &)));
+  } else {
+  }
+  m_postdel_observed = turnOn;
+}
+
+/**
+* Turn on observations of workspace replacement notifications from the ADS
+* @param turnOn :: If true observe the notifications, otherwise disable
+* observation [default=true]
+*/
+void WorkspaceObserver::observeAfterReplace(bool turnOn) {
+  if (turnOn && !m_repl_observed) {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_afterReplaceObserver);
+    m_proxy->connect(
+        m_proxy,
+        SIGNAL(afterReplaced(const std::string &, Mantid::API::Workspace_sptr)),
+        SLOT(handleAfterReplace(const std::string &,
+                                Mantid::API::Workspace_sptr)),
+        Qt::QueuedConnection);
+  } else if (!turnOn && m_repl_observed) {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_afterReplaceObserver);
+    m_proxy->disconnect(
+        m_proxy,
+        SIGNAL(afterReplaced(const std::string &, Mantid::API::Workspace_sptr)),
+        m_proxy, SLOT(handleAfterReplace(const std::string &,
+                                         Mantid::API::Workspace_sptr)));
+  }
+  m_repl_observed = turnOn;
+}
+
+/**
+* Turn on observations of workspace renaming notifications from the ADS
+* @param turnOn :: If true observe the notifications, otherwise disable
+* observation [default=true]
+*/
+void WorkspaceObserver::observeRename(bool turnOn) {
+  if (turnOn && !m_rename_observed) {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_renameObserver);
+    m_proxy->connect(
+        m_proxy, SIGNAL(renamed(const std::string &, const std::string &)),
+        SLOT(handleRename(const std::string &, const std::string &)),
+        Qt::QueuedConnection);
+  } else if (!turnOn && m_rename_observed) {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_renameObserver);
+    m_proxy->disconnect(
+        m_proxy, SIGNAL(renamed(const std::string &, const std::string &)),
+        m_proxy, SLOT(handleRename(const std::string &, const std::string &)));
+  }
+  m_rename_observed = turnOn;
+}
+
+/**
+* Turn on observations of workspace add notifications from the ADS
+* @param turnOn :: If true observe the notifications, otherwise disable
+* observation [default=true]
+*/
+void WorkspaceObserver::observeAdd(bool turnOn) {
+  if (turnOn && !m_add_observed) {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_addObserver);
+    m_proxy->connect(
+        m_proxy,
+        SIGNAL(addRequested(const std::string &, Mantid::API::Workspace_sptr)),
+        SLOT(handleAdd(const std::string &, Mantid::API::Workspace_sptr)),
+        Qt::QueuedConnection);
+  } else if (!turnOn && m_add_observed) {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_addObserver);
+    m_proxy->disconnect(
+        m_proxy,
+        SIGNAL(addRequested(const std::string &, Mantid::API::Workspace_sptr)),
+        m_proxy,
+        SLOT(handleAdd(const std::string &, Mantid::API::Workspace_sptr)));
+  }
+  m_add_observed = turnOn;
+}
+
+/**
+* Turn on observations of workspace clear notifications from the ADS
+* @param turnOn :: If true observe the notifications, otherwise disable
+* observation [default=true]
+*/
+void WorkspaceObserver::observeADSClear(bool turnOn) {
+  if (turnOn && !m_clr_observed) {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_clearADSObserver);
+    m_proxy->connect(m_proxy, SIGNAL(adsCleared()), SLOT(handleClearADS()),
+                     Qt::QueuedConnection);
+  } else if (!turnOn && m_clr_observed) {
+    Mantid::API::AnalysisDataService::Instance()
+        .notificationCenter.removeObserver(m_clearADSObserver);
+    m_proxy->disconnect(m_proxy, SIGNAL(adsCleared()), m_proxy,
+                        SLOT(handleClearADS()));
+  }
+  m_clr_observed = turnOn;
+}
+
+} // MantidQt
 } // API
diff --git a/MantidQt/API/test/BatchAlgorithmRunnerTest.h b/MantidQt/API/test/BatchAlgorithmRunnerTest.h
index 00244561ebe57174966fd286e7dc204e6ab3ebfa..9cf971a861c70378b834ac85b11d3ffe23ccc9b8 100644
--- a/MantidQt/API/test/BatchAlgorithmRunnerTest.h
+++ b/MantidQt/API/test/BatchAlgorithmRunnerTest.h
@@ -11,152 +11,163 @@
 using namespace Mantid::API;
 using MantidQt::API::BatchAlgorithmRunner;
 
-class BatchAlgorithmRunnerTest : public CxxTest::TestSuite
-{
-  public:
-    // This pair of boilerplate methods prevent the suite being created statically
-    // This means the constructor isn't called when running other tests
-    static BatchAlgorithmRunnerTest *createSuite() { return new BatchAlgorithmRunnerTest; }
-    static void destroySuite(BatchAlgorithmRunnerTest *suite) { delete suite; }
-
-    BatchAlgorithmRunnerTest()
-    {
-      // To make sure API is initialized properly
-      FrameworkManager::Instance();
-    }
-
-    /**
-     * Configures some algorithms and their runtime properties to be used in tests.
-     */
-    void setUp() override {
-      // Create some algorithms
-      // Each algorithm depends on the output workspace of the previous
-      createWsAlg = AlgorithmManager::Instance().create("CreateSampleWorkspace", -1);
-      createWsAlg->initialize();
-      createWsAlg->setProperty("OutputWorkspace", "BatchAlgorithmRunnerTest_Create");
-      createWsAlg->setProperty("Function", "Exp Decay");
-      createWsAlg->setProperty("XMax", 20.0);
-      createWsAlg->setProperty("BinWidth", 1.0);
-      inputFromCreateProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Create";
-
-      cropWsAlg = AlgorithmManager::Instance().create("CropWorkspace", -1);
-      cropWsAlg->initialize();
-      cropWsAlg->setProperty("OutputWorkspace", "BatchAlgorithmRunnerTest_Crop");
-      cropWsAlg->setProperty("StartWorkspaceIndex", 4);
-      cropWsAlg->setProperty("EndWorkspaceIndex", 5);
-      inputFromCropProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Crop";
-
-      scaleWsAlg = AlgorithmManager::Instance().create("Scale", -1);
-      scaleWsAlg->initialize();
-      scaleWsAlg->setProperty("OutputWorkspace", "BatchAlgorithmRunnerTest_Scale");
-      scaleWsAlg->setProperty("Factor", 5.0);
-      scaleWsAlg->setProperty("Operation", "Add");
-      inputFromScaleProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Scale";
-    }
-
-    /**
-     * Tests a standard run of algorithms.
-     */
-    void test_basicBatch()
-    {
-      BatchAlgorithmRunner runner(NULL);
-
-      // Add them to the queue
-      // Define the input (and inout, if used) WS properties here
-      runner.addAlgorithm(createWsAlg);
-      runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
-      runner.addAlgorithm(scaleWsAlg, inputFromCropProps);
-
-      // Run queue
-      TS_ASSERT_EQUALS(runner.queueLength(), 3);
-      TS_ASSERT(runner.executeBatch());
-      TS_ASSERT_EQUALS(runner.queueLength(), 0);
-
-      // Get workspace history
-      std::string wsName = "BatchAlgorithmRunnerTest_Scale";
-      auto history = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName)->getHistory();
-
-      // Check the algorithm history of the workspace matches what should have been done to it
-      TS_ASSERT_EQUALS("CreateSampleWorkspace", history.getAlgorithmHistory(0)->name())
-      TS_ASSERT_EQUALS("CropWorkspace", history.getAlgorithmHistory(1)->name())
-      TS_ASSERT_EQUALS("Scale", history.getAlgorithmHistory(2)->name())
-    }
-
-    /**
-     * Tests runs of multiple batches on the same runner.
-     */
-    void test_basicMultipleBatch()
-    {
-      BatchAlgorithmRunner runner(NULL);
-      std::string wsName = "BatchAlgorithmRunnerTest_Crop";
-
-      // Run 1
-      runner.addAlgorithm(createWsAlg);
-      runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
-      TS_ASSERT(runner.executeBatch());
-
-      auto historyRun1 = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName)->getHistory();
-      TS_ASSERT_EQUALS("CreateSampleWorkspace", historyRun1.getAlgorithmHistory(0)->name())
-      TS_ASSERT_EQUALS("CropWorkspace", historyRun1.getAlgorithmHistory(1)->name())
-
-      // Run 2
-      runner.addAlgorithm(scaleWsAlg, inputFromCreateProps);
-      runner.addAlgorithm(cropWsAlg, inputFromScaleProps);
-      TS_ASSERT(runner.executeBatch());
-
-      auto historyRun2 = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName)->getHistory();
-      TS_ASSERT_EQUALS("CreateSampleWorkspace", historyRun1.getAlgorithmHistory(0)->name())
-      TS_ASSERT_EQUALS("Scale", historyRun2.getAlgorithmHistory(1)->name())
-      TS_ASSERT_EQUALS("CropWorkspace", historyRun2.getAlgorithmHistory(2)->name())
-    }
-
-    /**
-     * Tests failure caused by setting a property such that it fails validation.
-     */
-    void test_basicBatchWorkspaceFailure()
-    {
-      BatchAlgorithmRunner runner(NULL);
-
-      inputFromCreateProps["InputWorkspace"] = "BatchAlgorithmRunner_NoWorkspace";
-
-      // Add them to the queue
-      // Define the input (and inout, if used) WS properties here
-      runner.addAlgorithm(createWsAlg);
-      runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
-
-      // Run queue
-      TS_ASSERT(!runner.executeBatch());
-      TS_ASSERT_EQUALS(runner.queueLength(), 0);
-    }
-
-    /**
-     * Tests failure casused by setting a property that does not exist.
-     */
-    void test_basicBatchPropertyFailure()
-    {
-      BatchAlgorithmRunner runner(NULL);
-
-      inputFromCreateProps["NotAValidProperty"] = "sample_data.nxs";
-
-      // Add them to the queue
-      // Define the input (and inout, if used) WS properties here
-      runner.addAlgorithm(createWsAlg);
-      runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
-
-      // Run queue
-      TS_ASSERT(!runner.executeBatch());
-      TS_ASSERT_EQUALS(runner.queueLength(), 0);
-    }
-
-  private:
-    IAlgorithm_sptr createWsAlg;
-    IAlgorithm_sptr cropWsAlg;
-    IAlgorithm_sptr scaleWsAlg;
-
-    BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromCreateProps;
-    BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromCropProps;
-    BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromScaleProps;
-
+class BatchAlgorithmRunnerTest : public CxxTest::TestSuite {
+public:
+  // This pair of boilerplate methods prevent the suite being created statically
+  // This means the constructor isn't called when running other tests
+  static BatchAlgorithmRunnerTest *createSuite() {
+    return new BatchAlgorithmRunnerTest;
+  }
+  static void destroySuite(BatchAlgorithmRunnerTest *suite) { delete suite; }
+
+  BatchAlgorithmRunnerTest() {
+    // To make sure API is initialized properly
+    FrameworkManager::Instance();
+  }
+
+  /**
+   * Configures some algorithms and their runtime properties to be used in
+   * tests.
+   */
+  void setUp() override {
+    // Create some algorithms
+    // Each algorithm depends on the output workspace of the previous
+    createWsAlg =
+        AlgorithmManager::Instance().create("CreateSampleWorkspace", -1);
+    createWsAlg->initialize();
+    createWsAlg->setProperty("OutputWorkspace",
+                             "BatchAlgorithmRunnerTest_Create");
+    createWsAlg->setProperty("Function", "Exp Decay");
+    createWsAlg->setProperty("XMax", 20.0);
+    createWsAlg->setProperty("BinWidth", 1.0);
+    inputFromCreateProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Create";
+
+    cropWsAlg = AlgorithmManager::Instance().create("CropWorkspace", -1);
+    cropWsAlg->initialize();
+    cropWsAlg->setProperty("OutputWorkspace", "BatchAlgorithmRunnerTest_Crop");
+    cropWsAlg->setProperty("StartWorkspaceIndex", 4);
+    cropWsAlg->setProperty("EndWorkspaceIndex", 5);
+    inputFromCropProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Crop";
+
+    scaleWsAlg = AlgorithmManager::Instance().create("Scale", -1);
+    scaleWsAlg->initialize();
+    scaleWsAlg->setProperty("OutputWorkspace",
+                            "BatchAlgorithmRunnerTest_Scale");
+    scaleWsAlg->setProperty("Factor", 5.0);
+    scaleWsAlg->setProperty("Operation", "Add");
+    inputFromScaleProps["InputWorkspace"] = "BatchAlgorithmRunnerTest_Scale";
+  }
+
+  /**
+   * Tests a standard run of algorithms.
+   */
+  void test_basicBatch() {
+    BatchAlgorithmRunner runner(NULL);
+
+    // Add them to the queue
+    // Define the input (and inout, if used) WS properties here
+    runner.addAlgorithm(createWsAlg);
+    runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
+    runner.addAlgorithm(scaleWsAlg, inputFromCropProps);
+
+    // Run queue
+    TS_ASSERT_EQUALS(runner.queueLength(), 3);
+    TS_ASSERT(runner.executeBatch());
+    TS_ASSERT_EQUALS(runner.queueLength(), 0);
+
+    // Get workspace history
+    std::string wsName = "BatchAlgorithmRunnerTest_Scale";
+    auto history = AnalysisDataService::Instance()
+                       .retrieveWS<MatrixWorkspace>(wsName)
+                       ->getHistory();
+
+    // Check the algorithm history of the workspace matches what should have
+    // been done to it
+    TS_ASSERT_EQUALS("CreateSampleWorkspace",
+                     history.getAlgorithmHistory(0)->name())
+    TS_ASSERT_EQUALS("CropWorkspace", history.getAlgorithmHistory(1)->name())
+    TS_ASSERT_EQUALS("Scale", history.getAlgorithmHistory(2)->name())
+  }
+
+  /**
+   * Tests runs of multiple batches on the same runner.
+   */
+  void test_basicMultipleBatch() {
+    BatchAlgorithmRunner runner(NULL);
+    std::string wsName = "BatchAlgorithmRunnerTest_Crop";
+
+    // Run 1
+    runner.addAlgorithm(createWsAlg);
+    runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
+    TS_ASSERT(runner.executeBatch());
+
+    auto historyRun1 = AnalysisDataService::Instance()
+                           .retrieveWS<MatrixWorkspace>(wsName)
+                           ->getHistory();
+    TS_ASSERT_EQUALS("CreateSampleWorkspace",
+                     historyRun1.getAlgorithmHistory(0)->name())
+    TS_ASSERT_EQUALS("CropWorkspace",
+                     historyRun1.getAlgorithmHistory(1)->name())
+
+    // Run 2
+    runner.addAlgorithm(scaleWsAlg, inputFromCreateProps);
+    runner.addAlgorithm(cropWsAlg, inputFromScaleProps);
+    TS_ASSERT(runner.executeBatch());
+
+    auto historyRun2 = AnalysisDataService::Instance()
+                           .retrieveWS<MatrixWorkspace>(wsName)
+                           ->getHistory();
+    TS_ASSERT_EQUALS("CreateSampleWorkspace",
+                     historyRun1.getAlgorithmHistory(0)->name())
+    TS_ASSERT_EQUALS("Scale", historyRun2.getAlgorithmHistory(1)->name())
+    TS_ASSERT_EQUALS("CropWorkspace",
+                     historyRun2.getAlgorithmHistory(2)->name())
+  }
+
+  /**
+   * Tests failure caused by setting a property such that it fails validation.
+   */
+  void test_basicBatchWorkspaceFailure() {
+    BatchAlgorithmRunner runner(NULL);
+
+    inputFromCreateProps["InputWorkspace"] = "BatchAlgorithmRunner_NoWorkspace";
+
+    // Add them to the queue
+    // Define the input (and inout, if used) WS properties here
+    runner.addAlgorithm(createWsAlg);
+    runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
+
+    // Run queue
+    TS_ASSERT(!runner.executeBatch());
+    TS_ASSERT_EQUALS(runner.queueLength(), 0);
+  }
+
+  /**
+   * Tests failure casused by setting a property that does not exist.
+   */
+  void test_basicBatchPropertyFailure() {
+    BatchAlgorithmRunner runner(NULL);
+
+    inputFromCreateProps["NotAValidProperty"] = "sample_data.nxs";
+
+    // Add them to the queue
+    // Define the input (and inout, if used) WS properties here
+    runner.addAlgorithm(createWsAlg);
+    runner.addAlgorithm(cropWsAlg, inputFromCreateProps);
+
+    // Run queue
+    TS_ASSERT(!runner.executeBatch());
+    TS_ASSERT_EQUALS(runner.queueLength(), 0);
+  }
+
+private:
+  IAlgorithm_sptr createWsAlg;
+  IAlgorithm_sptr cropWsAlg;
+  IAlgorithm_sptr scaleWsAlg;
+
+  BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromCreateProps;
+  BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromCropProps;
+  BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromScaleProps;
 };
 
 #endif /* MANTIDQT_API_BATCHALGORITHMRUNNERTEST_H_ */
diff --git a/MantidQt/API/test/GenericDialogDemo.cpp b/MantidQt/API/test/GenericDialogDemo.cpp
index 8d6d1c52f1f4ede73bc18e1cd1f916dabe8d70a8..5b3e468131bade990c125e3607b5e1ef94d3d112 100644
--- a/MantidQt/API/test/GenericDialogDemo.cpp
+++ b/MantidQt/API/test/GenericDialogDemo.cpp
@@ -30,15 +30,14 @@ using namespace Mantid::Kernel;
 using namespace Mantid::API;
 using namespace MantidQt::API;
 
-
-void showAlgo(IAlgorithm_sptr alg, QStringList enabled, QStringList disabled, QApplication & app)
-{
-  GenericDialog * dlg = new GenericDialog(NULL);
+void showAlgo(IAlgorithm_sptr alg, QStringList enabled, QStringList disabled,
+              QApplication &app) {
+  GenericDialog *dlg = new GenericDialog(NULL);
 
   // Set the content
   dlg->setAlgorithm(alg.get());
-  //dlg->setPresetValues(preset_values);
-  //dlg->isForScript(forScript);
+  // dlg->setPresetValues(preset_values);
+  // dlg->isForScript(forScript);
   dlg->setOptionalMessage(QString::fromStdString(alg->getOptionalMessage()));
 
   dlg->addEnabledAndDisableLists(enabled, disabled);
@@ -51,47 +50,43 @@ void showAlgo(IAlgorithm_sptr alg, QStringList enabled, QStringList disabled, QA
   app.exec();
   dlg->close();
   delete dlg;
-
 }
 
 /** This application will be used for debugging and testing the
  * GenericDialog and the AlgorithmPropertiesWidget.
  */
-int main( int argc, char ** argv )
-{
+int main(int argc, char **argv) {
   QApplication app(argc, argv);
   app.setApplicationName("PropertyWidgets demo");
 
   FrameworkManager::Instance();
 
   QStringList enabled;
-  if (argc > 2) enabled = QStringList::split(",", argv[2], false);
+  if (argc > 2)
+    enabled = QStringList::split(",", argv[2], false);
   QStringList disabled;
-  if (argc > 3) disabled = QStringList::split(",", argv[3], false);
+  if (argc > 3)
+    disabled = QStringList::split(",", argv[3], false);
 
   // Create the algorithm using the argument, with a default
   std::string algo = "LoadEventNexus";
   if (argc > 1)
     algo = std::string(argv[1]);
-  if (algo=="ALL")
-  {
+  if (algo == "ALL") {
     std::vector<std::string> names = AlgorithmFactory::Instance().getKeys();
     std::cout << names.size() << " algos.\n";
-    for(auto it = names.begin(); it != names.end(); it++)
-    {
-      std::pair<std::string,int> decoded = AlgorithmFactory::Instance().decodeName(*it);
+    for (auto it = names.begin(); it != names.end(); it++) {
+      std::pair<std::string, int> decoded =
+          AlgorithmFactory::Instance().decodeName(*it);
       std::string name = decoded.first;
       std::cout << name << std::endl;
       IAlgorithm_sptr alg = AlgorithmManager::Instance().create(name);
       showAlgo(alg, enabled, disabled, app);
     }
-  }
-  else
-  {
+  } else {
     IAlgorithm_sptr alg = AlgorithmManager::Instance().create(algo);
     showAlgo(alg, enabled, disabled, app);
   }
 
-
   return 0;
 }
diff --git a/MantidQt/API/test/InterfaceManagerTest.h b/MantidQt/API/test/InterfaceManagerTest.h
index 2cb1dcf637946db02b73015b83764b4672a4b261..af9f15defd99733fbbaa43966b86a6f77fe207e4 100644
--- a/MantidQt/API/test/InterfaceManagerTest.h
+++ b/MantidQt/API/test/InterfaceManagerTest.h
@@ -13,18 +13,14 @@
 #include "MantidKernel/Exception.h"
 
 using namespace MantidQt::API;
-class InterfaceManagerTest : public CxxTest::TestSuite
-{
+class InterfaceManagerTest : public CxxTest::TestSuite {
 
 public:
-
-  void testCreateManyInstances()
-  {
+  void testCreateManyInstances() {
     InterfaceManager objA;
     InterfaceManager objB;
     TS_ASSERT_DIFFERS(&objA, &objB);
   }
-
 };
 
 #endif /* INTERFACEMANAGERTEST_H_ */
diff --git a/MantidQt/API/test/MantidColorMapTest.h b/MantidQt/API/test/MantidColorMapTest.h
index 21cacf06e872d7fdd7a4146732f25df254882f63..e7cdd9a30300a7be5c0685709008b30a461b7fee 100644
--- a/MantidQt/API/test/MantidColorMapTest.h
+++ b/MantidQt/API/test/MantidColorMapTest.h
@@ -6,72 +6,65 @@
 #include <limits>
 #include <QRgb>
 
-class MantidColorMapTest : public CxxTest::TestSuite
-{
+class MantidColorMapTest : public CxxTest::TestSuite {
 public:
-
   /// Check default color map
-  void test_constructor()
-  {
+  void test_constructor() {
     MantidColorMap map;
     QRgb col;
-    col = map.rgb( QwtDoubleInterval( 0.0, 1.0 ), 0.0);
-    TSM_ASSERT_EQUALS("Default min color.", col, qRgb(0, 170, 252) );
-    col = map.rgb( QwtDoubleInterval( 0.0, 1.0 ), 1.0);
-    TSM_ASSERT_EQUALS("Default max color.", col, qRgb(255,255,255) );
-    TSM_ASSERT_EQUALS("Default map is linear", map.getScaleType(), GraphOptions::Log10 );
+    col = map.rgb(QwtDoubleInterval(0.0, 1.0), 0.0);
+    TSM_ASSERT_EQUALS("Default min color.", col, qRgb(0, 170, 252));
+    col = map.rgb(QwtDoubleInterval(0.0, 1.0), 1.0);
+    TSM_ASSERT_EQUALS("Default max color.", col, qRgb(255, 255, 255));
+    TSM_ASSERT_EQUALS("Default map is linear", map.getScaleType(),
+                      GraphOptions::Log10);
   }
 
-  void test_normalize_linear()
-  {
+  void test_normalize_linear() {
     MantidColorMap map;
     QwtDoubleInterval range(10.0, 20.0);
-    map.changeScaleType( GraphOptions::Linear );
-    TS_ASSERT_DELTA( map.normalize(range, 15.), 0.5, 1e-5);
+    map.changeScaleType(GraphOptions::Linear);
+    TS_ASSERT_DELTA(map.normalize(range, 15.), 0.5, 1e-5);
   }
 
-  void test_normalize_log()
-  {
+  void test_normalize_log() {
     MantidColorMap map;
     QwtDoubleInterval range(1.0, 10000.0);
-    map.changeScaleType( GraphOptions::Log10 );
-    TS_ASSERT_DELTA( map.normalize(range, 1000.), 0.75, 1e-5);
+    map.changeScaleType(GraphOptions::Log10);
+    TS_ASSERT_DELTA(map.normalize(range, 1000.), 0.75, 1e-5);
   }
 
-  void test_normalize_power()
-  {
+  void test_normalize_power() {
     MantidColorMap map;
     QwtDoubleInterval range(10.0, 20.0);
-    map.changeScaleType( GraphOptions::Power );
-    map.setNthPower( 2.0 );
-    TS_ASSERT_DELTA( map.normalize(range, 16.), 0.52, 1e-5);
+    map.changeScaleType(GraphOptions::Power);
+    map.setNthPower(2.0);
+    TS_ASSERT_DELTA(map.normalize(range, 16.), 0.52, 1e-5);
   }
 
   /// Setting a NAN color
-  void test_nan_color()
-  {
+  void test_nan_color() {
     MantidColorMap map;
     map.setNanColor(123, 23, 34);
     QRgb col;
     QwtDoubleInterval range(10.0, 20.0);
     double nan = std::numeric_limits<double>::quiet_NaN();
-    col = map.rgb( range, nan);
-    TSM_ASSERT_EQUALS("Passing NAN to rgb returns the set color.", col, qRgb(123, 23, 34) );
+    col = map.rgb(range, nan);
+    TSM_ASSERT_EQUALS("Passing NAN to rgb returns the set color.", col,
+                      qRgb(123, 23, 34));
   }
 
-  void test_colorIndex()
-  {
+  void test_colorIndex() {
     MantidColorMap map;
     QwtDoubleInterval range(10.0, 20.0);
     double nan = std::numeric_limits<double>::quiet_NaN();
-    TSM_ASSERT_EQUALS("Color index is 0 for NAN", map.colorIndex(range, nan), 0);
-    TSM_ASSERT_EQUALS("Color index is 1 for small numbers", map.colorIndex(range, -123.0), 1);
-    TSM_ASSERT_EQUALS("Color index is 255 for large numbers", map.colorIndex(range, +123.0), 255);
+    TSM_ASSERT_EQUALS("Color index is 0 for NAN", map.colorIndex(range, nan),
+                      0);
+    TSM_ASSERT_EQUALS("Color index is 1 for small numbers",
+                      map.colorIndex(range, -123.0), 1);
+    TSM_ASSERT_EQUALS("Color index is 255 for large numbers",
+                      map.colorIndex(range, +123.0), 255);
   }
-
-
-
 };
 
-
 #endif /* MANTIDQT_API_MANTIDCOLORMAPTEST_H_ */
diff --git a/MantidQt/API/test/QwtWorkspaceBinDataTest.h b/MantidQt/API/test/QwtWorkspaceBinDataTest.h
index 580c66902186c817391520b18238dcced707cab2..5a7cab60963beba78c2a10d3b8e92312bd848fe6 100644
--- a/MantidQt/API/test/QwtWorkspaceBinDataTest.h
+++ b/MantidQt/API/test/QwtWorkspaceBinDataTest.h
@@ -8,74 +8,64 @@
 #include "MantidAPI/NumericAxis.h"
 #include "MantidTestHelpers/WorkspaceCreationHelper.h"
 
-class QwtWorkspaceBinDataTest : public CxxTest::TestSuite
-{
+class QwtWorkspaceBinDataTest : public CxxTest::TestSuite {
   Mantid::API::MatrixWorkspace_sptr ws;
 
 public:
   void setUp() override {
     ws = WorkspaceCreationHelper::Create2DWorkspace(3, 4);
     auto *ax1 = new Mantid::API::NumericAxis(3);
-    ws->replaceAxis(1,ax1);
-    for (size_t i=0; i<3; i++)
-    {
+    ws->replaceAxis(1, ax1);
+    for (size_t i = 0; i < 3; i++) {
       ax1->setValue(i, 10.0 + static_cast<double>(i));
-      for (size_t j=0; j<5; j++)
+      for (size_t j = 0; j < 5; j++)
         ws->dataX(i)[j] = double(i) + double(j);
-      for (size_t j=0; j<4; j++)
-      {
-        ws->dataY(i)[j] = double(i) + double(j)*2;
-        ws->dataE(i)[j] = double(i) + double(j)*3;
+      for (size_t j = 0; j < 4; j++) {
+        ws->dataY(i)[j] = double(i) + double(j) * 2;
+        ws->dataE(i)[j] = double(i) + double(j) * 3;
       }
     }
   }
 
-  void checkData(QwtWorkspaceBinData & data, double binIndex)
-  {
-    TS_ASSERT_EQUALS( data.size(), 3);
-    for (size_t i=0; i<1; i++)
-    {
-      TS_ASSERT_DELTA( data.x(i), 10.0 + static_cast<double>(i), 1e-5);
-      TS_ASSERT_DELTA( data.y(i), binIndex*2.0 + double(i), 1e-5);
-      TS_ASSERT_DELTA( data.e(i), binIndex*3.0 + double(i), 1e-5);
+  void checkData(QwtWorkspaceBinData &data, double binIndex) {
+    TS_ASSERT_EQUALS(data.size(), 3);
+    for (size_t i = 0; i < 1; i++) {
+      TS_ASSERT_DELTA(data.x(i), 10.0 + static_cast<double>(i), 1e-5);
+      TS_ASSERT_DELTA(data.y(i), binIndex * 2.0 + double(i), 1e-5);
+      TS_ASSERT_DELTA(data.e(i), binIndex * 3.0 + double(i), 1e-5);
     }
   }
 
-  void test_data()
-  {
+  void test_data() {
     QwtWorkspaceBinData data(*ws, 1, false);
     checkData(data, 1.0);
     QwtWorkspaceBinData data2(*ws, 2, false);
     checkData(data2, 2.0);
   }
 
-  void test_assigmentOperator()
-  {
+  void test_assigmentOperator() {
     QwtWorkspaceBinData data1(*ws, 1, false);
     QwtWorkspaceBinData data2 = data1;
     checkData(data2, 1.0);
   }
 
-  void test_copy()
-  {
+  void test_copy() {
     QwtWorkspaceBinData data1(*ws, 1, false);
-    QwtWorkspaceBinData * data2 = dynamic_cast<QwtWorkspaceBinData *>(data1.copy());
+    QwtWorkspaceBinData *data2 =
+        dynamic_cast<QwtWorkspaceBinData *>(data1.copy());
     checkData(*data2, 1.0);
   }
 
   /** In log scale, points below a minimum value are clipped to the minimum */
-  void test_logScale()
-  {
+  void test_logScale() {
     ws->dataY(2)[2] = -10;
     QwtWorkspaceBinData data(*ws, 2, true);
-    TS_ASSERT_DELTA( data.y(1), 5.0, 1e-6);
-    TS_ASSERT_DELTA( data.e(1), 7.0, 1e-6);
-    TS_ASSERT_DELTA( data.y(2), 4.0, 1e-6);
+    TS_ASSERT_DELTA(data.y(1), 5.0, 1e-6);
+    TS_ASSERT_DELTA(data.e(1), 7.0, 1e-6);
+    TS_ASSERT_DELTA(data.y(2), 4.0, 1e-6);
     // Errors should also be zero-ed out.
-    TS_ASSERT_DELTA( data.e(2), 0.0, 1e-6);
+    TS_ASSERT_DELTA(data.e(2), 0.0, 1e-6);
   }
-
 };
 
-
 #endif /* MANTIDQT_API_MANTIDQWTWORKSPACEBINDATA_H_ */
diff --git a/MantidQt/API/test/QwtWorkspaceSpectrumDataTest.h b/MantidQt/API/test/QwtWorkspaceSpectrumDataTest.h
index c2537da005c8fc0ae86be9d7505fe43e97f8680f..fab0e833a7799958bd72c324c781563263fce52e 100644
--- a/MantidQt/API/test/QwtWorkspaceSpectrumDataTest.h
+++ b/MantidQt/API/test/QwtWorkspaceSpectrumDataTest.h
@@ -8,75 +8,65 @@
 #include "MantidTestHelpers/WorkspaceCreationHelper.h"
 #include "MantidQtAPI/QwtWorkspaceSpectrumData.h"
 
-class QwtWorkspaceSpectrumDataTest : public CxxTest::TestSuite
-{
+class QwtWorkspaceSpectrumDataTest : public CxxTest::TestSuite {
   Mantid::API::MatrixWorkspace_sptr ws;
 
 public:
   void setUp() override {
     ws = WorkspaceCreationHelper::Create2DWorkspace(3, 4);
-    for (size_t i=0; i<3; i++)
-    {
-      for (size_t j=0; j<5; j++)
+    for (size_t i = 0; i < 3; i++) {
+      for (size_t j = 0; j < 5; j++)
         ws->dataX(i)[j] = double(i) + double(j);
-      for (size_t j=0; j<4; j++)
-      {
-        ws->dataY(i)[j] = double(i) + double(j)*2;
-        ws->dataE(i)[j] = double(i) + double(j)*3;
+      for (size_t j = 0; j < 4; j++) {
+        ws->dataY(i)[j] = double(i) + double(j) * 2;
+        ws->dataE(i)[j] = double(i) + double(j) * 3;
       }
     }
   }
 
-  void checkHistogramData(QwtWorkspaceSpectrumData & data, double offset)
-  {
-    TS_ASSERT_EQUALS( data.size(), 4);
-    for (size_t i=0; i<4; i++)
-    {
-      TS_ASSERT_DELTA( data.x(i), offset + double(i), 1e-5);
-      TS_ASSERT_DELTA( data.y(i), offset + double(i)*2, 1e-5);
-      TS_ASSERT_DELTA( data.e(i), offset + double(i)*3, 1e-5);
+  void checkHistogramData(QwtWorkspaceSpectrumData &data, double offset) {
+    TS_ASSERT_EQUALS(data.size(), 4);
+    for (size_t i = 0; i < 4; i++) {
+      TS_ASSERT_DELTA(data.x(i), offset + double(i), 1e-5);
+      TS_ASSERT_DELTA(data.y(i), offset + double(i) * 2, 1e-5);
+      TS_ASSERT_DELTA(data.e(i), offset + double(i) * 3, 1e-5);
     }
-    TS_ASSERT_DELTA( data.x(4), offset + double(4), 1e-5);
+    TS_ASSERT_DELTA(data.x(4), offset + double(4), 1e-5);
     // Go past the end in Y/E is safe
-    TS_ASSERT_DELTA( data.y(4), offset + double(3)*2, 1e-5);
+    TS_ASSERT_DELTA(data.y(4), offset + double(3) * 2, 1e-5);
   }
 
-  void test_histogram()
-  {
+  void test_histogram() {
     QwtWorkspaceSpectrumData data(*ws, 1, false, false);
     checkHistogramData(data, 1.0);
-    TS_ASSERT( data.isHistogram() );
+    TS_ASSERT(data.isHistogram());
     QwtWorkspaceSpectrumData data2(*ws, 2, false, false);
     checkHistogramData(data2, 2.0);
   }
 
-  void test_assigmentOperator()
-  {
+  void test_assigmentOperator() {
     QwtWorkspaceSpectrumData data1(*ws, 1, false, false);
     QwtWorkspaceSpectrumData data2 = data1;
     checkHistogramData(data2, 1.0);
   }
 
-  void test_copy()
-  {
+  void test_copy() {
     QwtWorkspaceSpectrumData data1(*ws, 1, false, false);
-    QwtWorkspaceSpectrumData * data2 = dynamic_cast<QwtWorkspaceSpectrumData *>(data1.copy());
+    QwtWorkspaceSpectrumData *data2 =
+        dynamic_cast<QwtWorkspaceSpectrumData *>(data1.copy());
     checkHistogramData(*data2, 1.0);
   }
 
   /** In log scale, points below a minimum value are clipped to the minimum */
-  void test_logScale()
-  {
+  void test_logScale() {
     ws->dataY(0)[2] = -10;
     QwtWorkspaceSpectrumData data(*ws, 0, true, false);
-    TS_ASSERT_DELTA( data.y(1), 2.0, 1e-6);
-    TS_ASSERT_DELTA( data.e(1), 3.0, 1e-6);
-    TS_ASSERT_DELTA( data.y(2), 2.0, 1e-6);
+    TS_ASSERT_DELTA(data.y(1), 2.0, 1e-6);
+    TS_ASSERT_DELTA(data.e(1), 3.0, 1e-6);
+    TS_ASSERT_DELTA(data.y(2), 2.0, 1e-6);
     // Errors should also be zero-ed out.
-    TS_ASSERT_DELTA( data.e(2), 0.0, 1e-6);
+    TS_ASSERT_DELTA(data.e(2), 0.0, 1e-6);
   }
-
 };
 
-
 #endif /* MANTIDQT_API_MANTIDQWTWORKSPACESPECTRUMDATA_H_ */
diff --git a/MantidQt/API/test/ScriptRepositoryViewTest.h b/MantidQt/API/test/ScriptRepositoryViewTest.h
index 0f1905834d08ccb8acf997c3363cff9cca70bd6c..ed9ca9141e9f5f1f54b68a08aef478ac0850a334 100644
--- a/MantidQt/API/test/ScriptRepositoryViewTest.h
+++ b/MantidQt/API/test/ScriptRepositoryViewTest.h
@@ -7,22 +7,16 @@
 
 using Mantid::API::ScriptRepositoryView;
 
-class ScriptRepositoryViewTest : public CxxTest::TestSuite
-{
+class ScriptRepositoryViewTest : public CxxTest::TestSuite {
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static ScriptRepositoryViewTest *createSuite() { return new ScriptRepositoryViewTest(); }
-  static void destroySuite( ScriptRepositoryViewTest *suite ) { delete suite; }
-
-
-  void test_Something()
-  {
-    TSM_ASSERT( "You forgot to write a test!", 0);
+  static ScriptRepositoryViewTest *createSuite() {
+    return new ScriptRepositoryViewTest();
   }
+  static void destroySuite(ScriptRepositoryViewTest *suite) { delete suite; }
 
-
+  void test_Something() { TSM_ASSERT("You forgot to write a test!", 0); }
 };
 
-
 #endif /* MANTID_API_SCRIPTREPOSITORYVIEWTEST_H_ */
\ No newline at end of file
diff --git a/MantidQt/API/test/SelectionNotificationServiceTest.h b/MantidQt/API/test/SelectionNotificationServiceTest.h
index 310227121170a7b7dfdc96fe93085efe92009d6e..ab05ba2f04eb160f2e3617c002fbdeaef530b4f8 100644
--- a/MantidQt/API/test/SelectionNotificationServiceTest.h
+++ b/MantidQt/API/test/SelectionNotificationServiceTest.h
@@ -1,17 +1,17 @@
 #ifndef MANTIDQT_API_SELECTION_NOTIFICATION_SERVICE_H_
-#define MANTIDQT_API_SELECTION_NOTIFICATION_SERVICE_H_ 
+#define MANTIDQT_API_SELECTION_NOTIFICATION_SERVICE_H_
 
 #include <cxxtest/TestSuite.h>
 #include "MantidQtAPI/SelectionNotificationService.h"
 
-class SelectionNotificationServiceTest : public CxxTest::TestSuite
-{
-  public:
-
-  /// check that we can get the singleton and call the send method, to emit a Qt signal
-  void test_sendQSelection()
-  {
-    TS_ASSERT_THROWS_NOTHING( MantidQt::API::SelectionNotificationService::Instance().sendQPointSelection( false, 1, 2, 3 ) );
+class SelectionNotificationServiceTest : public CxxTest::TestSuite {
+public:
+  /// check that we can get the singleton and call the send method, to emit a Qt
+  /// signal
+  void test_sendQSelection() {
+    TS_ASSERT_THROWS_NOTHING(
+        MantidQt::API::SelectionNotificationService::Instance()
+            .sendQPointSelection(false, 1, 2, 3));
   }
 };
 
diff --git a/MantidQt/API/test/main_PropertyWidgetsDemo.cpp b/MantidQt/API/test/main_PropertyWidgetsDemo.cpp
index 8f658086f1883dce42688ec4d9459f463a8c3a75..9500627a6c0798a20143b67a388a5aa93aa7f96b 100644
--- a/MantidQt/API/test/main_PropertyWidgetsDemo.cpp
+++ b/MantidQt/API/test/main_PropertyWidgetsDemo.cpp
@@ -31,57 +31,66 @@ using Mantid::API::WorkspaceProperty;
  * @param argv :: ignored
  * @return return code
  */
-int main( int argc, char ** argv )
-{
+int main(int argc, char **argv) {
   QApplication app(argc, argv);
   app.setApplicationName("PropertyWidgets demo");
-  QMainWindow * mainWin = new QMainWindow();
+  QMainWindow *mainWin = new QMainWindow();
 
-  QFrame * frame = new QFrame(mainWin);
+  QFrame *frame = new QFrame(mainWin);
   mainWin->setCentralWidget(frame);
 
-  QHBoxLayout * layout = new QHBoxLayout(frame);
+  QHBoxLayout *layout = new QHBoxLayout(frame);
   frame->setLayout(layout);
 
-  QFrame * frame1 = new QFrame(mainWin);
+  QFrame *frame1 = new QFrame(mainWin);
   frame1->setFrameStyle(QFrame::Box);
-  QFrame * frame2 = new QFrame(mainWin);
+  QFrame *frame2 = new QFrame(mainWin);
   frame2->setFrameStyle(QFrame::Box);
 
   layout->addWidget(frame1);
   layout->addWidget(frame2);
 
-  QVBoxLayout * layout1 = new QVBoxLayout(frame1);
-  QGridLayout * grid = new QGridLayout(frame2);
+  QVBoxLayout *layout1 = new QVBoxLayout(frame1);
+  QGridLayout *grid = new QGridLayout(frame2);
 
-  std::vector<Property*> props;
+  std::vector<Property *> props;
   props.push_back(new PropertyWithValue<bool>("BooleanProp", true));
-  props.push_back(new PropertyWithValue<std::string>("StringProperty", "default value"));
+  props.push_back(
+      new PropertyWithValue<std::string>("StringProperty", "default value"));
 
   std::vector<std::string> exts;
   exts.push_back(".txt");
   exts.push_back(".nxs");
-  props.push_back(new FileProperty("SaveFileProperty", "default.file.txt", FileProperty::Save, exts));
-  props.push_back(new FileProperty("LoadFileProperty", "default.file.txt", FileProperty::Load, exts));
-  props.push_back(new FileProperty("DirectoryFileProperty", "default.file.txt", FileProperty::Directory, exts));
+  props.push_back(new FileProperty("SaveFileProperty", "default.file.txt",
+                                   FileProperty::Save, exts));
+  props.push_back(new FileProperty("LoadFileProperty", "default.file.txt",
+                                   FileProperty::Load, exts));
+  props.push_back(new FileProperty("DirectoryFileProperty", "default.file.txt",
+                                   FileProperty::Directory, exts));
   props.push_back(new MultipleFileProperty("MultipleFileProperty", exts));
-  props.push_back(new WorkspaceProperty<>("InputWorkspaceProp", "", Direction::Input));
-  props.push_back(new WorkspaceProperty<>("InOutWorkspaceProp", "", Direction::InOut));
-  props.push_back(new WorkspaceProperty<>("OutputWorkspaceProp", "", Direction::Output));
-  props.push_back(new WorkspaceProperty<>("OutputWorkspaceProp2", "", Direction::Output));
+  props.push_back(
+      new WorkspaceProperty<>("InputWorkspaceProp", "", Direction::Input));
+  props.push_back(
+      new WorkspaceProperty<>("InOutWorkspaceProp", "", Direction::InOut));
+  props.push_back(
+      new WorkspaceProperty<>("OutputWorkspaceProp", "", Direction::Output));
+  props.push_back(
+      new WorkspaceProperty<>("OutputWorkspaceProp2", "", Direction::Output));
 
   std::vector<std::string> propOptions;
   propOptions.push_back("OptionA");
   propOptions.push_back("OptionTwo");
   propOptions.push_back("Yet Another Option");
-  props.push_back(new PropertyWithValue<std::string>("OptionsProperty", "OptionTwo", new ListValidator(propOptions)));
+  props.push_back(new PropertyWithValue<std::string>(
+      "OptionsProperty", "OptionTwo", new ListValidator(propOptions)));
 
-  for (size_t i=0; i<props.size(); i++)
-  {
+  for (size_t i = 0; i < props.size(); i++) {
     props[i]->setDocumentation("Tooltip for " + props[i]->name());
-    PropertyWidget * widget1 = PropertyWidgetFactory::createWidget(props[i], frame1, NULL);
+    PropertyWidget *widget1 =
+        PropertyWidgetFactory::createWidget(props[i], frame1, NULL);
     layout1->addWidget(widget1);
-    PropertyWidget * widget2 = PropertyWidgetFactory::createWidget(props[i], frame2, grid, int(i));
+    PropertyWidget *widget2 =
+        PropertyWidgetFactory::createWidget(props[i], frame2, grid, int(i));
     UNUSED_ARG(widget2);
   }
 
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CatalogPublishDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CatalogPublishDialog.h
index 40bc45f17499fbc58c8b157c5a7d52d29833c56b..e74233985c6e1a85b7696e45af1eb7b98cebcdf5 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CatalogPublishDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CatalogPublishDialog.h
@@ -4,68 +4,67 @@
 #include "MantidQtAPI/AlgorithmDialog.h"
 #include "ui_CatalogPublishDialog.h"
 
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    /**
-     This class gives specialised dialog for the CatalogPublish algorithm.
+namespace MantidQt {
+namespace CustomDialogs {
+/**
+ This class gives specialised dialog for the CatalogPublish algorithm.
 
-     @author Jay Rainey, ISIS Rutherford Appleton Laboratory
-     @date 14/01/2014
-     Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ @author Jay Rainey, ISIS Rutherford Appleton Laboratory
+ @date 14/01/2014
+ Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-     This file is part of Mantid.
+ This file is part of Mantid.
 
-     Mantid is free software; you can redistribute it and/or modify
-     it under the terms of the GNU General Public License as published by
-     the Free Software Foundation; either version 3 of the License, or
-     (at your option) any later version.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-     Mantid is distributed in the hope that it will be useful,
-     but WITHOUT ANY WARRANTY; without even the implied warranty of
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-     GNU General Public License for more details.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-     You should have received a copy of the GNU General Public License
-     along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-     File change history is stored at: <https://github.com/mantidproject/mantid>.
-     Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class CatalogPublishDialog : public API::AlgorithmDialog
-    {
-      Q_OBJECT
+ File change history is stored at: <https://github.com/mantidproject/mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class CatalogPublishDialog : public API::AlgorithmDialog {
+  Q_OBJECT
 
-      public:
-        /// Constructor
-        CatalogPublishDialog(QWidget *parent = 0);
+public:
+  /// Constructor
+  CatalogPublishDialog(QWidget *parent = 0);
 
-      private:
-        /// Create the inital layout.
-        void initLayout() override;
-        /// Populate the investigation number combo-box with investigations that the user can publish to.
-        void populateUserInvestigations();
+private:
+  /// Create the inital layout.
+  void initLayout() override;
+  /// Populate the investigation number combo-box with investigations that the
+  /// user can publish to.
+  void populateUserInvestigations();
 
-      private slots:
-        /// When the "browse" button is clicked open a file browser.
-        void workspaceSelected(const QString& wsName);
-        /// Set the "FileName" property when a file is selected from the file browser.
-        void fileSelected();
-        /// Diables fields on dialog to improve usability
-        void disableDialog();
-        /// Set session property when user selects an investigation to publish to.
-        void setSessionProperty(int index);
+private slots:
+  /// When the "browse" button is clicked open a file browser.
+  void workspaceSelected(const QString &wsName);
+  /// Set the "FileName" property when a file is selected from the file browser.
+  void fileSelected();
+  /// Diables fields on dialog to improve usability
+  void disableDialog();
+  /// Set session property when user selects an investigation to publish to.
+  void setSessionProperty(int index);
 
-      protected:
-        /// Overridden to enable dataselector validators
-        void accept() override;
+protected:
+  /// Overridden to enable dataselector validators
+  void accept() override;
 
-      protected:
-        /// The form generated by QT Designer.
-        Ui::CatalogPublishDialog m_uiForm;
-    };
-  }
+protected:
+  /// The form generated by QT Designer.
+  Ui::CatalogPublishDialog m_uiForm;
+};
+}
 }
 
 #endif /* MANTIDQT_CUSTOM_DIALOGS_CATALOGPUBLISHDIALOG_H */
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/ConvertTableToMatrixWorkspaceDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/ConvertTableToMatrixWorkspaceDialog.h
index 2d335e266f5f4ba62aefa578a79e02c87f862b5a..d1f7c31e7f39c84b6786339d19de6ebf0c85fa67 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/ConvertTableToMatrixWorkspaceDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/ConvertTableToMatrixWorkspaceDialog.h
@@ -12,67 +12,64 @@
 //------------------------------------------------------------------------------
 class QVBoxLayout;
 
-namespace MantidQt
-{
-  //------------------------------------------------------------------------------
-  // Mantid Forward declarations
-  //------------------------------------------------------------------------------
-  namespace MantidWidgets
-  {
-    class MWRunFiles;
-  }
-
-  namespace CustomDialogs
-  {
-
-    /** 
-      This class gives specialised dialog for the ConvertTableToMatrixWorkspace algorithm.
-
-      @author Roman Tolchenov, Tessella plc
-      @date 26/01/2012
-      
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-      
-      This file is part of Mantid.
-      
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-      
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-      
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-      
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class ConvertTableToMatrixWorkspaceDialog : public API::AlgorithmDialog
-    {
-      Q_OBJECT
-      
-    public:
-      /// Default constructor
-      ConvertTableToMatrixWorkspaceDialog(QWidget *parent = NULL);
-
-    private slots:
-      /// Update the column name widgets
-      void fillColumnNames(const QString&);
-
-    private:
-      /// Initialize the layout
-      void initLayout() override;
-
-    private:
-      /// Form
-      Ui::ConvertTableToMatrixWorkspaceDialog m_form;
-    };
-
-  }
+namespace MantidQt {
+//------------------------------------------------------------------------------
+// Mantid Forward declarations
+//------------------------------------------------------------------------------
+namespace MantidWidgets {
+class MWRunFiles;
+}
+
+namespace CustomDialogs {
+
+/**
+  This class gives specialised dialog for the ConvertTableToMatrixWorkspace
+  algorithm.
+
+  @author Roman Tolchenov, Tessella plc
+  @date 26/01/2012
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class ConvertTableToMatrixWorkspaceDialog : public API::AlgorithmDialog {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  ConvertTableToMatrixWorkspaceDialog(QWidget *parent = NULL);
+
+private slots:
+  /// Update the column name widgets
+  void fillColumnNames(const QString &);
+
+private:
+  /// Initialize the layout
+  void initLayout() override;
+
+private:
+  /// Form
+  Ui::ConvertTableToMatrixWorkspaceDialog m_form;
+};
+}
 }
 
-#endif //MANTIDQT_CUSTOM_DIALOGS_CONVERTTABLETOMATRIXWORKSPACEDIALOG_H
+#endif // MANTIDQT_CUSTOM_DIALOGS_CONVERTTABLETOMATRIXWORKSPACEDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CreateSampleShapeDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CreateSampleShapeDialog.h
index 2783c3c859c5d001cb50d00ef774f2d458f33033..053b2938eb71978fa0010a71caa6b91b567623aa 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CreateSampleShapeDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/CreateSampleShapeDialog.h
@@ -19,10 +19,8 @@
 //---------------------------------
 class QCloseEvent;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
 class BinaryTreeWidget;
 class BinaryTreeWidgetItem;
@@ -31,14 +29,15 @@ struct BaseInstantiator;
 struct Operation;
 class MantidGLWidget;
 
-/** 
+/**
     This class gives specialised dialog for the sample shape definition
     algorithm
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 13/03/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -56,14 +55,12 @@ class MantidGLWidget;
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class CreateSampleShapeDialog : public MantidQt::API::AlgorithmDialog
-{
+class CreateSampleShapeDialog : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 
 public:
-  
   /// Default constructor
   CreateSampleShapeDialog(QWidget *parent = 0);
 
@@ -72,8 +69,8 @@ public:
 
 private slots:
   /// Context menu request
-  void handleTreeContextMenuRequest(const QPoint & pos);
-  /// Toggle the flag on 
+  void handleTreeContextMenuRequest(const QPoint &pos);
+  /// Toggle the flag on
   void toggleShapeComplement(bool state);
   /// Add a new shape
   void addShape(QAction *shape);
@@ -82,11 +79,11 @@ private slots:
   /// Connects to the delete slot
   void handleDeleteRequest();
   /// Remove an item from the tree (recursive)
-  void removeItem(BinaryTreeWidgetItem* item);
+  void removeItem(BinaryTreeWidgetItem *item);
   /// Setup the details box based currently selected item
   void setupDetailsBox();
   ///  Change item data
-  void changeTreeData(BinaryTreeWidgetItem* item, int data);
+  void changeTreeData(BinaryTreeWidgetItem *item, int data);
   /// Update the object within the 3D widget
   void update3DView();
 
@@ -96,9 +93,9 @@ private:
   /// Get the input out of the dialog
   void parseInput() override;
   /// Find the parent
-  BinaryTreeWidgetItem* getSelectedItem();
+  BinaryTreeWidgetItem *getSelectedItem();
   /// Create a details widget based upon the shape name given
-  ShapeDetails* createDetailsWidget(const QString & shapename) const;
+  ShapeDetails *createDetailsWidget(const QString &shapename) const;
   /// Construct the XML from the current tree
   QString constructShapeXML() const;
 
@@ -108,36 +105,36 @@ private:
   /// A pointer to the model for the shape tree
   BinaryTreeWidget *m_shapeTree;
   /// A map of shape names to instantiator objects
-  QHash<QString, BaseInstantiator*> m_setup_map;
-  ///A map of QTreeWidgetItem objects to their details objects
-  QMap<BinaryTreeWidgetItem*, ShapeDetails*> m_details_map;
-  ///A map of QTreeWidgetItem objects to their operation objects
-  QMap<BinaryTreeWidgetItem*, Operation*> m_ops_map;
-  ///The 3D object viewer
+  QHash<QString, BaseInstantiator *> m_setup_map;
+  /// A map of QTreeWidgetItem objects to their details objects
+  QMap<BinaryTreeWidgetItem *, ShapeDetails *> m_details_map;
+  /// A map of QTreeWidgetItem objects to their operation objects
+  QMap<BinaryTreeWidgetItem *, Operation *> m_ops_map;
+  /// The 3D object viewer
   MantidGLWidget *m_object_viewer;
 };
 
 /**
  * A custom item to use in the BinaryTree widget
  */
-class BinaryTreeWidgetItem : public QTreeWidgetItem
-{
+class BinaryTreeWidgetItem : public QTreeWidgetItem {
 
 public:
   /// Default Constructor
   BinaryTreeWidgetItem(int type = QTreeWidgetItem::UserType);
 
   /// Constructor taking a string list and an optional type
-  BinaryTreeWidgetItem(const QStringList & strings, int type = QTreeWidgetItem::UserType);
+  BinaryTreeWidgetItem(const QStringList &strings,
+                       int type = QTreeWidgetItem::UserType);
 
-  /// Add a child item 
+  /// Add a child item
   bool addChildItem(BinaryTreeWidgetItem *child);
 
   /// A pointer to the left child
-  BinaryTreeWidgetItem* leftChild() const;
+  BinaryTreeWidgetItem *leftChild() const;
 
   /// A pointer to the right child
-  BinaryTreeWidgetItem* rightChild() const;
+  BinaryTreeWidgetItem *rightChild() const;
 
 private:
   /// The index of the left child (0 or 1)
@@ -149,19 +146,19 @@ private:
 /**
  * A widget to implement a binary tree display.
  */
-class BinaryTreeWidget : public QTreeWidget
-{
+class BinaryTreeWidget : public QTreeWidget {
   Q_OBJECT
-  
+
 public:
   /// Default constructor
   BinaryTreeWidget(QWidget *parent = 0);
 
-  //Return the root of the binary tree
-  BinaryTreeWidgetItem* root() const;
+  // Return the root of the binary tree
+  BinaryTreeWidgetItem *root() const;
 
   /// Recurse through the tree in a post-order
-  void traverseInPostOrder(BinaryTreeWidgetItem* node, QList<BinaryTreeWidgetItem*> & expression);
+  void traverseInPostOrder(BinaryTreeWidgetItem *node,
+                           QList<BinaryTreeWidgetItem *> &expression);
 
   /// Called when the data in the model is changed
   void dataChanged(const QModelIndex &topLeft,
@@ -169,14 +166,13 @@ public:
 
 signals:
   /// Emitted when data has changed
-  void treeDataChange(BinaryTreeWidgetItem* item, int data);
+  void treeDataChange(BinaryTreeWidgetItem *item, int data);
 };
 
 /**
  * A custom delegate class used for item editing
  */
-class ComboBoxDelegate : public QItemDelegate
-{
+class ComboBoxDelegate : public QItemDelegate {
   Q_OBJECT
 
 public:
@@ -185,17 +181,16 @@ public:
   /// Create an editor for the item
   QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                         const QModelIndex &index) const override;
-  ///Set the data for the editor when it has been created
+  /// Set the data for the editor when it has been created
   void setEditorData(QWidget *editor, const QModelIndex &index) const override;
-  ///Set the data for the model when editing has finished
+  /// Set the data for the model when editing has finished
   void setModelData(QWidget *editor, QAbstractItemModel *model,
                     const QModelIndex &index) const override;
   /// Ensure that the editor has the correct geometry when it is created
   void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const override;
 };
-
 }
 }
 
-#endif //MANTIDQT_CUSTOMDIALOGS_CREATESAMPLESHAPE_H_
+#endif // MANTIDQT_CUSTOMDIALOGS_CREATESAMPLESHAPE_H_
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/FitDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/FitDialog.h
index 94d2d86eaee0cfe56ab4ed2d15958eb7091911a2..5734b42f133237445ab154c42178750e9b5323fe 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/FitDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/FitDialog.h
@@ -13,216 +13,215 @@
 class QVBoxLayout;
 class QSpinBox;
 
-namespace MantidQt
-{
-  //------------------------------------------------------------------------------
-  // Mantid Forward declarations
-  //------------------------------------------------------------------------------
-  namespace MantidWidgets
-  {
-    class MWRunFiles;
-  }
+namespace MantidQt {
+//------------------------------------------------------------------------------
+// Mantid Forward declarations
+//------------------------------------------------------------------------------
+namespace MantidWidgets {
+class MWRunFiles;
+}
 
-  namespace CustomDialogs
-  {
-
-    //------------------------------------------------------------------------------
-    // Local Forward declarations
-    //------------------------------------------------------------------------------
-    class InputWorkspaceWidget;
-    class DynamicPropertiesWidget;
-
-    /** 
-      This class gives specialised dialog for the Load algorithm. It requires that the specific 
-      load algorithm has at least 2 properties with these names:
-
-      <UL>
-      <LI>Filename - A text property containing the filename </LI>
-      <LI>OutputWorkspace - A text property containing the name of the OutputWorkspace </LI>
-      </UL>
-
-      There is no UI form as the most of the thing is dynamic.
-
-      @author Martyn Gigg, Tessella plc
-      @date 31/01/2011
-      
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-      
-      This file is part of Mantid.
-      
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-      
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-      
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-      
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class FitDialog : public API::AlgorithmDialog
-    {
-      Q_OBJECT
-      
-    public:
-      /// Default constructor
-      FitDialog(QWidget *parent = NULL);
-
-    private slots:
-      /// Override the help button clicked method
-      //void helpClicked();
-      void workspaceChanged(const QString&);
-      void functionChanged();
-      /// Create InputWorkspaceWidgets and populate the tabs of the tab widget
-      void createInputWorkspaceWidgets();
-      void domainTypeChanged();
-
-    private:
-      /// Initialize the layout
-      void initLayout() override;
-      /// Save the input history
-      void saveInput() override;
-      void parseInput() override;
-      /// Tie static widgets to their properties
-      void tieStaticWidgets(const bool readHistory);
-      /// Get the domain type: Simple, Sequential, or Parallel
-      int getDomainType() const;
-      /// Get the domain type: Simple, Sequential, or Parallel
-      QString getDomainTypeString() const;
-
-      /// Return property value stored in history
-      QString getStoredPropertyValue(const QString& propName) const;
-      /// Get allowed values for a property
-      QStringList getAllowedPropertyValues(const QString& propName) const;
-      /// Set i-th workspace name
-      void setWorkspaceName( int i, const QString& wsName );
-
-      /// Is the function MD?
-      bool isMD() const;
-
-    private:
-      /// Form
-      Ui::FitDialog m_form;
-      QList<QWidget*> m_tabs;
-
-      friend class InputWorkspaceWidget;
-    };
-
-    /**
-     * Widget for inputting workspace information. 
-     */
-    class InputWorkspaceWidget: public QWidget
-    {
-      Q_OBJECT
-    public:
-      /// Constructor
-      InputWorkspaceWidget(FitDialog* parent, int domainIndex = 0);
-      /// Return property value stored in history
-      QString getStoredPropertyValue(const QString& propName) const
-      {return m_fitDialog->getStoredPropertyValue(propName);}
-      /// Get allowed values for a property
-      QStringList getAllowedPropertyValues(const QString& propName) const
-      {return m_fitDialog->getAllowedPropertyValues(propName);}
-      /// Get workspace name
-      QString getWorkspaceName() const ;
-      /// Set workspace name
-      void setWorkspaceName(const QString& wsName);
-      /// Return the domain index
-      int getDomainIndex() const {return m_domainIndex;} 
-      /// Set a property
-      void setPropertyValue(const QString& propName, const QString& propValue);
-      /// Set all workspace properties
-      void setProperties();
-      /// Get the domain type: Simple, Sequential, or Parallel
-      int getDomainType() const {return m_fitDialog->getDomainType();}
-    protected slots:
-      /// Set the dynamic properties
-      void setDynamicProperties();
-    protected:
-      /// Is ws name set?
-      bool isWSNameSet() const;
-      /// Is the workspace MW?
-      bool isMatrixWorkspace() const;
-      /// Is the workspace MD?
-      bool isMDWorkspace() const;
-      /// is current workspace supported by Fit?
-      bool isWorkspaceSupported() const;
-
-      /// Parent FitDialog
-      FitDialog *m_fitDialog;
-      /// In multidomain fitting it is index of domain created from this workspace
-      /// In single domain case == 0
-      int m_domainIndex;
-      /// Name of the property for the input workspace
-      QString m_wsPropName;
-      /// Workspace name widget
-      QComboBox *m_workspaceName;
-      /// Dynamic propeties widget
-      DynamicPropertiesWidget *m_dynamicProperties;
-
-      /// The main layout
-      QVBoxLayout *m_layout;
-    };
-
-    /**
-     * Base class for input workspace's dynamic properties widget
-     */
-    class DynamicPropertiesWidget: public QWidget
-    {
-    public:
-      /// Constructor
-      DynamicPropertiesWidget(InputWorkspaceWidget* parent):QWidget(parent),m_wsWidget(parent){}
-      /// Initialize the child widgets with stored and allowed values
-      virtual void init() = 0;
-      /// Set all workspace properties
-      virtual void setProperties() = 0;
-    protected:
-      /// Parent InputWorkspaceWidget
-      InputWorkspaceWidget *m_wsWidget;
-    };
-
-    /**
-     * Widgets to set properties for a MatrixWorkspace: WorkspaceIndex, StartX, EndX
-     */
-    class MWPropertiesWidget: public DynamicPropertiesWidget
-    {
-    public:
-      MWPropertiesWidget(InputWorkspaceWidget* parent);
-      /// Initialize the child widgets with stored and allowed values
-      void init() override;
-      /// Set all workspace properties
-      void setProperties() override;
-
-    protected:
-      QSpinBox *m_workspaceIndex;
-      QLineEdit *m_startX;
-      QLineEdit *m_endX;
-      QSpinBox *m_maxSize;
-    };
-
-    /**
-     * Widgets to set properties for a IMDWorkspace: MaxSize
-     */
-    class MDPropertiesWidget: public DynamicPropertiesWidget
-    {
-    public:
-      MDPropertiesWidget(InputWorkspaceWidget* parent);
-      /// Initialize the child widgets with stored and allowed values
-      void init() override {}
-      /// Set all workspace properties
-      void setProperties() override;
-
-    protected:
-      QSpinBox *m_maxSize;
-    };
+namespace CustomDialogs {
 
+//------------------------------------------------------------------------------
+// Local Forward declarations
+//------------------------------------------------------------------------------
+class InputWorkspaceWidget;
+class DynamicPropertiesWidget;
+
+/**
+  This class gives specialised dialog for the Load algorithm. It requires that
+  the specific
+  load algorithm has at least 2 properties with these names:
+
+  <UL>
+  <LI>Filename - A text property containing the filename </LI>
+  <LI>OutputWorkspace - A text property containing the name of the
+  OutputWorkspace </LI>
+  </UL>
+
+  There is no UI form as the most of the thing is dynamic.
+
+  @author Martyn Gigg, Tessella plc
+  @date 31/01/2011
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class FitDialog : public API::AlgorithmDialog {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  FitDialog(QWidget *parent = NULL);
+
+private slots:
+  /// Override the help button clicked method
+  // void helpClicked();
+  void workspaceChanged(const QString &);
+  void functionChanged();
+  /// Create InputWorkspaceWidgets and populate the tabs of the tab widget
+  void createInputWorkspaceWidgets();
+  void domainTypeChanged();
+
+private:
+  /// Initialize the layout
+  void initLayout() override;
+  /// Save the input history
+  void saveInput() override;
+  void parseInput() override;
+  /// Tie static widgets to their properties
+  void tieStaticWidgets(const bool readHistory);
+  /// Get the domain type: Simple, Sequential, or Parallel
+  int getDomainType() const;
+  /// Get the domain type: Simple, Sequential, or Parallel
+  QString getDomainTypeString() const;
+
+  /// Return property value stored in history
+  QString getStoredPropertyValue(const QString &propName) const;
+  /// Get allowed values for a property
+  QStringList getAllowedPropertyValues(const QString &propName) const;
+  /// Set i-th workspace name
+  void setWorkspaceName(int i, const QString &wsName);
+
+  /// Is the function MD?
+  bool isMD() const;
+
+private:
+  /// Form
+  Ui::FitDialog m_form;
+  QList<QWidget *> m_tabs;
+
+  friend class InputWorkspaceWidget;
+};
+
+/**
+ * Widget for inputting workspace information.
+ */
+class InputWorkspaceWidget : public QWidget {
+  Q_OBJECT
+public:
+  /// Constructor
+  InputWorkspaceWidget(FitDialog *parent, int domainIndex = 0);
+  /// Return property value stored in history
+  QString getStoredPropertyValue(const QString &propName) const {
+    return m_fitDialog->getStoredPropertyValue(propName);
   }
+  /// Get allowed values for a property
+  QStringList getAllowedPropertyValues(const QString &propName) const {
+    return m_fitDialog->getAllowedPropertyValues(propName);
+  }
+  /// Get workspace name
+  QString getWorkspaceName() const;
+  /// Set workspace name
+  void setWorkspaceName(const QString &wsName);
+  /// Return the domain index
+  int getDomainIndex() const { return m_domainIndex; }
+  /// Set a property
+  void setPropertyValue(const QString &propName, const QString &propValue);
+  /// Set all workspace properties
+  void setProperties();
+  /// Get the domain type: Simple, Sequential, or Parallel
+  int getDomainType() const { return m_fitDialog->getDomainType(); }
+protected slots:
+  /// Set the dynamic properties
+  void setDynamicProperties();
+
+protected:
+  /// Is ws name set?
+  bool isWSNameSet() const;
+  /// Is the workspace MW?
+  bool isMatrixWorkspace() const;
+  /// Is the workspace MD?
+  bool isMDWorkspace() const;
+  /// is current workspace supported by Fit?
+  bool isWorkspaceSupported() const;
+
+  /// Parent FitDialog
+  FitDialog *m_fitDialog;
+  /// In multidomain fitting it is index of domain created from this workspace
+  /// In single domain case == 0
+  int m_domainIndex;
+  /// Name of the property for the input workspace
+  QString m_wsPropName;
+  /// Workspace name widget
+  QComboBox *m_workspaceName;
+  /// Dynamic propeties widget
+  DynamicPropertiesWidget *m_dynamicProperties;
+
+  /// The main layout
+  QVBoxLayout *m_layout;
+};
+
+/**
+ * Base class for input workspace's dynamic properties widget
+ */
+class DynamicPropertiesWidget : public QWidget {
+public:
+  /// Constructor
+  DynamicPropertiesWidget(InputWorkspaceWidget *parent)
+      : QWidget(parent), m_wsWidget(parent) {}
+  /// Initialize the child widgets with stored and allowed values
+  virtual void init() = 0;
+  /// Set all workspace properties
+  virtual void setProperties() = 0;
+
+protected:
+  /// Parent InputWorkspaceWidget
+  InputWorkspaceWidget *m_wsWidget;
+};
+
+/**
+ * Widgets to set properties for a MatrixWorkspace: WorkspaceIndex, StartX, EndX
+ */
+class MWPropertiesWidget : public DynamicPropertiesWidget {
+public:
+  MWPropertiesWidget(InputWorkspaceWidget *parent);
+  /// Initialize the child widgets with stored and allowed values
+  void init() override;
+  /// Set all workspace properties
+  void setProperties() override;
+
+protected:
+  QSpinBox *m_workspaceIndex;
+  QLineEdit *m_startX;
+  QLineEdit *m_endX;
+  QSpinBox *m_maxSize;
+};
+
+/**
+ * Widgets to set properties for a IMDWorkspace: MaxSize
+ */
+class MDPropertiesWidget : public DynamicPropertiesWidget {
+public:
+  MDPropertiesWidget(InputWorkspaceWidget *parent);
+  /// Initialize the child widgets with stored and allowed values
+  void init() override {}
+  /// Set all workspace properties
+  void setProperties() override;
+
+protected:
+  QSpinBox *m_maxSize;
+};
+}
 }
 
-#endif //MANTIDQT_CUSTOM_DIALOGS_FITDIALOG_H
+#endif // MANTIDQT_CUSTOM_DIALOGS_FITDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LOQScriptInputDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LOQScriptInputDialog.h
index ce38e0135dbf916e6ddc70c4054bab23d6b1290a..c915d061f6d0cf1a353546db4c814128e69d40bd 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LOQScriptInputDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LOQScriptInputDialog.h
@@ -7,18 +7,17 @@
 #include "ui_LOQScriptInputDialog.h"
 #include "MantidQtAPI/AlgorithmDialog.h"
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
+/**
     This class gives specialised dialog for the LOQ input algorithm.
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 05/03/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -36,36 +35,32 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class LOQScriptInputDialog : public MantidQt::API::AlgorithmDialog
-{
+class LOQScriptInputDialog : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 
-  public:
-  
+public:
   /// Default constructor
   LOQScriptInputDialog(QWidget *parent = 0);
 
-  private:
-
+private:
   /// Initialize the layout
-    void initLayout() override;
+  void initLayout() override;
 
-    /// Get the input out of the dialog
-    void parseInput() override;
+  /// Get the input out of the dialog
+  void parseInput() override;
 
-  private slots:
+private slots:
 
-    /// browse clicked method
-    void browseClicked();
+  /// browse clicked method
+  void browseClicked();
 
-  private:
+private:
   // The form generated with Qt Designer
   Ui::LOQScriptInputDialog m_uiForm;
 };
-
 }
 }
 
-#endif //MANTIDQT_CUSTOMDIALOGS_LOQSCRIPTINPUTDIALOG_H_
+#endif // MANTIDQT_CUSTOMDIALOGS_LOQSCRIPTINPUTDIALOG_H_
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadAsciiDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadAsciiDialog.h
index 549da7a97f3c3ff960a1e0481345e291885fee33..b8ecf1809f8ac18a7445e48a00952bf2edd1b989 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadAsciiDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadAsciiDialog.h
@@ -16,18 +16,17 @@ class QString;
 class QVBoxLayout;
 class QCheckBox;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
+/**
     This class gives specialised dialog for the LoadAscii algorithm.
 
     @author Roman Tolchenov, Tessella Support Services plc
     @date 06/08/2010
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -45,14 +44,12 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class LoadAsciiDialog : public MantidQt::API::AlgorithmDialog
-{
+class LoadAsciiDialog : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 
 public:
-
   /// Constructor
   LoadAsciiDialog(QWidget *parent = 0);
   /// Destruktor
@@ -73,9 +70,7 @@ private:
   QLineEdit *m_lineCommentIndicator;
   QLineEdit *m_lineCustomSeparator;
   QComboBox *m_separatorBox;
-
 };
-
 }
 }
 
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDAEDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDAEDialog.h
index 0bfef5d0fda4947826e917cd4c0ed0deeb36b37a..599353af0e200d9bfc574732ad221290b25b0ce0 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDAEDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDAEDialog.h
@@ -16,18 +16,17 @@ class QString;
 class QVBoxLayout;
 class QCheckBox;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
+/**
     This class gives specialised dialog for the LoadDAE algorithm.
 
     @author Roman Tolchenov, Tessella Support Services plc
     @date 14/07/2010
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -45,14 +44,12 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class LoadDAEDialog : public MantidQt::API::AlgorithmDialog
-{
+class LoadDAEDialog : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 
 public:
-
   /// Constructor
   LoadDAEDialog(QWidget *parent = 0);
   /// Destruktor
@@ -70,9 +67,7 @@ private:
   QLineEdit *maxSpLineEdit;
   QLineEdit *listSpLineEdit;
   QLineEdit *updateLineEdit;
-
 };
-
 }
 }
 
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDialog.h
index 8ca8ec663a6f4ca9df2c879f894b8941b4ae7d01..d773bede626129dbcc32abf4517f2c1164423d55 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadDialog.h
@@ -12,101 +12,100 @@
 //------------------------------------------------------------------------------
 class QVBoxLayout;
 
-namespace MantidQt
-{
-  //------------------------------------------------------------------------------
-  // Mantid Forward declarations
-  //------------------------------------------------------------------------------
-  namespace MantidWidgets
-  {
-    class MWRunFiles;
-  }
-
-  namespace CustomDialogs
-  {
-
-    /** 
-      This class gives specialised dialog for the Load algorithm. It requires that the specific 
-      load algorithm has at least 2 properties with these names:
-
-      <UL>
-      <LI>Filename - A text property containing the filename </LI>
-      <LI>OutputWorkspace - A text property containing the name of the OutputWorkspace </LI>
-      </UL>
-
-      There is no UI form as the most of the thing is dynamic.
-
-      @author Martyn Gigg, Tessella plc
-      @date 31/01/2011
-      
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-      
-      This file is part of Mantid.
-      
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-      
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-      
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-      
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class LoadDialog : public API::AlgorithmDialog
-    {
-      Q_OBJECT
-      
-    public:
-      /// Default constructor
-      LoadDialog(QWidget *parent = NULL);
-
-    private slots:
-      /// Create the widgets and layouts that are dynamic, i.e they depend on 
-      /// the specific load algorithm
-      void createDynamicWidgets();
-      /// Override the help button clicked method
-      void helpClicked() override;
-      /// Suggest a workspace name from the file
-      void suggestWSName();
-      /// Connect/Disconnect the signal that updates the workspace name with a suggested value
-      void enableNameSuggestion(const bool on = false);
-      /// Override accept() slot
-      void accept() override;
-
-    private:
-      /// Initialize the layout
-      void initLayout() override;
-      /// Save the input history
-      void saveInput() override;
-      /// Tie static widgets to their properties
-      void tieStaticWidgets(const bool readHistory);
-      /// Clears all of the widgets from the old layout
-      void removeOldInputWidgets(QVBoxLayout *layout);
-      /// Create
-      void createDynamicLayout();
-      /// Create the widgets for a given property
-      int createWidgetsForProperty(const Mantid::Kernel::Property* prop,
-					                         QVBoxLayout *propertyLayout, QWidget *parent);
-
-    private:
-      /// Form
-      Ui::LoadDialog m_form;
-      /// The current file
-      QString m_currentFiles;
-      /// The initial height
-      int m_initialHeight;
-      /// Flag to indicating if we are populating the dialog
-      bool m_populating;
-    };
-
-  }
+namespace MantidQt {
+//------------------------------------------------------------------------------
+// Mantid Forward declarations
+//------------------------------------------------------------------------------
+namespace MantidWidgets {
+class MWRunFiles;
+}
+
+namespace CustomDialogs {
+
+/**
+  This class gives specialised dialog for the Load algorithm. It requires that
+  the specific
+  load algorithm has at least 2 properties with these names:
+
+  <UL>
+  <LI>Filename - A text property containing the filename </LI>
+  <LI>OutputWorkspace - A text property containing the name of the
+  OutputWorkspace </LI>
+  </UL>
+
+  There is no UI form as the most of the thing is dynamic.
+
+  @author Martyn Gigg, Tessella plc
+  @date 31/01/2011
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class LoadDialog : public API::AlgorithmDialog {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  LoadDialog(QWidget *parent = NULL);
+
+private slots:
+  /// Create the widgets and layouts that are dynamic, i.e they depend on
+  /// the specific load algorithm
+  void createDynamicWidgets();
+  /// Override the help button clicked method
+  void helpClicked() override;
+  /// Suggest a workspace name from the file
+  void suggestWSName();
+  /// Connect/Disconnect the signal that updates the workspace name with a
+  /// suggested value
+  void enableNameSuggestion(const bool on = false);
+  /// Override accept() slot
+  void accept() override;
+
+private:
+  /// Initialize the layout
+  void initLayout() override;
+  /// Save the input history
+  void saveInput() override;
+  /// Tie static widgets to their properties
+  void tieStaticWidgets(const bool readHistory);
+  /// Clears all of the widgets from the old layout
+  void removeOldInputWidgets(QVBoxLayout *layout);
+  /// Create
+  void createDynamicLayout();
+  /// Create the widgets for a given property
+  int createWidgetsForProperty(const Mantid::Kernel::Property *prop,
+                               QVBoxLayout *propertyLayout, QWidget *parent);
+
+private:
+  /// Form
+  Ui::LoadDialog m_form;
+  /// The current file
+  QString m_currentFiles;
+  /// The initial height
+  int m_initialHeight;
+  /// Flag to indicating if we are populating the dialog
+  bool m_populating;
+};
+}
 }
 
-#endif //MANTIDQT_CUSTOM_DIALOGS_LOADDIALOG_H
+#endif // MANTIDQT_CUSTOM_DIALOGS_LOADDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadRawDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadRawDialog.h
index b68a321a0fd7843b6c137078066b8d21f6db892e..76fcf0884afaaa34bf705affaabb6bbffb458c42 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadRawDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/LoadRawDialog.h
@@ -16,18 +16,17 @@ class QLineEdit;
 class QComboBox;
 class QPushButton;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
+/**
     This class gives specialised dialog for the LoadRaw algorithm.
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 24/02/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -45,40 +44,35 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class LoadRawDialog : public MantidQt::API::AlgorithmDialog
-{
+class LoadRawDialog : public MantidQt::API::AlgorithmDialog {
 
   Q_OBJECT
-  
-public:
 
+public:
   /// Constructor
   LoadRawDialog(QWidget *parent = 0);
-  ///Destructor
+  /// Destructor
   ~LoadRawDialog() override;
 
 private:
-
   /** @name Virtual functions. */
   //@{
   /// Create the layout
   void initLayout() override;
   //@}
-  
+
 private slots:
 
   /// A slot for the browse button clicked signal
   void browseClicked();
 
 private:
-
-  ///The line inputs
+  /// The line inputs
   QLineEdit *m_pathBox, *m_wsBox;
 };
-
 }
 }
 
-#endif //MANTIDQT_CUSTOMDIALOGS_LOADRAWDIALOG_H
+#endif // MANTIDQT_CUSTOMDIALOGS_LOADRAWDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/MantidGLWidget.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/MantidGLWidget.h
index da4336564c415240ddf0a63adfba44bf4f0a4de0..3cef157ee46528588014960c21d0dd402170bd9f 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/MantidGLWidget.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/MantidGLWidget.h
@@ -12,27 +12,24 @@
 //-----------------------------------------
 // Forward Declarations
 //-----------------------------------------
-namespace Mantid
-{
-namespace Geometry
-{
-  class Object;
+namespace Mantid {
+namespace Geometry {
+class Object;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
-    This class provides a widget to display a Mantid Geometry object using 
+/**
+    This class provides a widget to display a Mantid Geometry object using
     OpenGL.
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 18/05/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -50,17 +47,16 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MantidGLWidget : public QGLWidget
-{
+class MantidGLWidget : public QGLWidget {
 
   Q_OBJECT
 
 public:
-  ///Default constructor
+  /// Default constructor
   MantidGLWidget(QWidget *parent = 0);
-  ///Destructor
+  /// Destructor
   ~MantidGLWidget() override;
 
   /// Set the Mantid geometry object
@@ -93,7 +89,7 @@ private:
   void mouseMoveEvent(QMouseEvent *event) override;
   /// A Mantid geometry object
   boost::shared_ptr<Mantid::Geometry::Object> m_display_object;
-  /// The current X, Y and Z rotations 
+  /// The current X, Y and Z rotations
   GLdouble m_x_rot, m_y_rot, m_z_rot;
   /// The scaling factor to use
   GLdouble m_scale_factor;
@@ -104,8 +100,7 @@ private:
   /// The centre of the bounding box
   GLdouble m_bb_centres[3];
 };
-
 }
 }
 
-#endif //MANTIDQT_CUSTOMDIALOGS_MANTIDGLWIDGET_H_
+#endif // MANTIDQT_CUSTOMDIALOGS_MANTIDGLWIDGET_H_
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.h
index 8526a07ff53a848e83564fec6b7f3252ba2a6dd6..3a87542d37b57a16e2f4058225ad3d1ffabfca56 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.h
@@ -18,18 +18,17 @@ class QLineEdit;
 class QComboBox;
 class QPushButton;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-/** 
+/**
     This class gives specialised dialog for the LoadRaw algorithm.
 
     @author Martyn Gigg, Tessella Support Services plc
     @date 24/02/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -47,47 +46,44 @@ namespace CustomDialogs
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class PlotAsymmetryByLogValueDialog : public MantidQt::API::AlgorithmDialog
-{
+class PlotAsymmetryByLogValueDialog : public MantidQt::API::AlgorithmDialog {
 
   Q_OBJECT
-	
-public:
 
+public:
   /// Constructor
   PlotAsymmetryByLogValueDialog(QWidget *parent = 0);
-  ///Destructor
+  /// Destructor
   ~PlotAsymmetryByLogValueDialog() override;
 
 private:
-
   /** @name Virtual functions. */
   //@{
   /// Create the layout
   void initLayout() override;
   //@}
-	
+
 private slots:
 
-  /// Opens a file dialog. Updates the QLineEdit provided when the dialog is closed.
-  void openFileDialog(const QString& filePropName);
-  void fillLogBox(const QString&);
+  /// Opens a file dialog. Updates the QLineEdit provided when the dialog is
+  /// closed.
+  void openFileDialog(const QString &filePropName);
+  void fillLogBox(const QString &);
 
-  /// Show or hide Dead Time file widget depending on which Dead Time type is selected.
+  /// Show or hide Dead Time file widget depending on which Dead Time type is
+  /// selected.
   void showHideDeadTimeFileWidget(int deadTimeTypeIndex);
 
 private:
-
   // The form generated with Qt Designer
   Ui::PlotAsymmetryByLogValueDialog m_uiForm;
 
   /// Maps Browse buttons to file properties
-  QSignalMapper* browseButtonMapper;
+  QSignalMapper *browseButtonMapper;
 };
-
 }
 }
 
-#endif //MANTIDQT_CUSTOM_DIALOGSLPLOTASYMMETRYBYLOGVALUEDIALOG_H
+#endif // MANTIDQT_CUSTOM_DIALOGSLPLOTASYMMETRYBYLOGVALUEDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PrecompiledHeader.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PrecompiledHeader.h
index 8c133bd80cc593e755d4ef567c082e5616877b62..fed677e1cbdf4ce3b74169d122917bb0539398b6 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PrecompiledHeader.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PrecompiledHeader.h
@@ -11,7 +11,7 @@
 #include <QDialog>
 #include <QString>
 
-//STL
+// STL
 #include <vector>
 #include <map>
 #include <set>
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SampleShapeHelpers.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SampleShapeHelpers.h
index bd2f72bd861302b02ea33e04bd9c0d9ca6d87371..a1579847c3489d313995dffb9603feaead4101f9 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SampleShapeHelpers.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SampleShapeHelpers.h
@@ -21,10 +21,8 @@ class QLabel;
  * a widget that is to be displayed within the CreateSampleShapeDialog.
  * The base class exists so that they can be stored in a container.
  */
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
 // Forward declartion
 class ShapeDetails;
@@ -32,16 +30,15 @@ class ShapeDetails;
 /**
  * A custom group box for a 3D point
  */
-class PointGroupBox : public QGroupBox
-{
+class PointGroupBox : public QGroupBox {
   Q_OBJECT
 
 public:
-  //Default constructor
-  PointGroupBox(QWidget* parent = 0);
+  // Default constructor
+  PointGroupBox(QWidget *parent = 0);
 
-  ///Write the element tag for a 3D point
-  QString write3DElement(const QString & elem_name) const;
+  /// Write the element tag for a 3D point
+  QString write3DElement(const QString &elem_name) const;
 
 private slots:
   // Switch to cartesian coordinates
@@ -50,25 +47,24 @@ private slots:
   void changeToSpherical();
 
 private:
-  //Labels for fields
+  // Labels for fields
   QLabel *m_xlabel, *m_ylabel, *m_zlabel;
   // Edit fields (also used for r,theta,phi) if in spherical mode
   QLineEdit *m_midx, *m_midy, *m_midz;
-  //Unit choice boxes (x is used for r in spherical mode)
+  // Unit choice boxes (x is used for r in spherical mode)
   QComboBox *m_xunits, *m_yunits, *m_zunits;
-  //Radio button selection for coordinates
+  // Radio button selection for coordinates
   QRadioButton *m_cartesian, *m_spherical;
-  //The current coordinate system (0 = cartesian, 1 = spherical)
+  // The current coordinate system (0 = cartesian, 1 = spherical)
   int m_icoord;
 };
 
-
 /**
  * A struct describing a binary operation
- * Note: The constructor takes an integer where 0 = intersection, 1 = union and 2 = difference
+ * Note: The constructor takes an integer where 0 = intersection, 1 = union and
+ * 2 = difference
  */
-struct Operation
-{
+struct Operation {
   /// Default constructor
   Operation(int op = 0) : binaryop(op) {}
 
@@ -82,69 +78,64 @@ struct Operation
 /**
  * Base instantiator to store in a map
  */
-struct BaseInstantiator
-{
+struct BaseInstantiator {
   /// Default constructor
   BaseInstantiator() {}
   /// Virtual destructor
   virtual ~BaseInstantiator() {}
-  ///Create an instance
-virtual ShapeDetails* createInstance() const = 0;
+  /// Create an instance
+  virtual ShapeDetails *createInstance() const = 0;
+
 private:
   /// Private copy constructor
-  BaseInstantiator(const BaseInstantiator&);
+  BaseInstantiator(const BaseInstantiator &);
   /// Private assignment operator
-  BaseInstantiator& operator =(const BaseInstantiator&);
+  BaseInstantiator &operator=(const BaseInstantiator &);
 };
 
 /**
  * A structure used for holding the type of a details widget
  */
-template<class T>
-struct ShapeDetailsInstantiator : public BaseInstantiator
-{
+template <class T> struct ShapeDetailsInstantiator : public BaseInstantiator {
   /// Default constructor
   ShapeDetailsInstantiator() {}
-  ///Create an instance of this type
+  /// Create an instance of this type
   ShapeDetails *createInstance() const override {
-    return static_cast<ShapeDetails*>(new T);
+    return static_cast<ShapeDetails *>(new T);
   }
 
 private:
   /// Private copy constructor
-  ShapeDetailsInstantiator(const ShapeDetailsInstantiator&);
+  ShapeDetailsInstantiator(const ShapeDetailsInstantiator &);
   /// Private assignment operator
-  ShapeDetailsInstantiator& operator =(const ShapeDetailsInstantiator&);
+  ShapeDetailsInstantiator &operator=(const ShapeDetailsInstantiator &);
 };
 
 /**
  * The base class for the details widgets
  */
-class ShapeDetails : public QWidget
-{
+class ShapeDetails : public QWidget {
   Q_OBJECT
 
 public:
-  ///Constructor
-  ShapeDetails(QWidget *parent = 0) : QWidget(parent), m_idvalue(""), m_isComplement(false) {}
-  ///Constructor
+  /// Constructor
+  ShapeDetails(QWidget *parent = 0)
+      : QWidget(parent), m_idvalue(""), m_isComplement(false) {}
+  /// Constructor
   ~ShapeDetails() override {}
 
-  ///Write out the XML definition for this shape
+  /// Write out the XML definition for this shape
   virtual QString writeXML() const = 0;
 
   /// Get the id string
-  QString getShapeID() const
-  {
-    return m_idvalue;
-  }
+  QString getShapeID() const { return m_idvalue; }
 
-  ///Create a new length units box
-  static  QComboBox* createLengthUnitsCombo();
+  /// Create a new length units box
+  static QComboBox *createLengthUnitsCombo();
   // Units enum
   enum Unit { millimetre = 0, centimetre = 1, metre = 2 };
   // Convert a string value from the given unit to metres
-  static QString convertToMetres(const QString & value, Unit start_unit);
+  static QString convertToMetres(const QString &value, Unit start_unit);
 
   /// Set the complement flag
   void setComplementFlag(bool flag);
@@ -158,14 +149,12 @@ protected:
 private:
   /// Take the complement of the shape
   bool m_isComplement;
-
 };
 
 /**
  * A widget to define a sphere
  */
-class SphereDetails : public ShapeDetails
-{
+class SphereDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -173,13 +162,13 @@ private:
   static int g_nspheres;
 
 public:
-  ///Default constructor
+  /// Default constructor
   SphereDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~SphereDetails() override { --g_nspheres; }
 
-  //Write the XML definition of a sphere
+  // Write the XML definition of a sphere
   QString writeXML() const override;
 
 private:
@@ -194,8 +183,7 @@ private:
 /**
  * A widget to define a cylinder
  */
-class CylinderDetails : public ShapeDetails
-{
+class CylinderDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -203,19 +191,19 @@ private:
   static int g_ncylinders;
 
 public:
-  ///Default constructor
+  /// Default constructor
   CylinderDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~CylinderDetails() override { --g_ncylinders; }
 
-  //Write the XML definition of a sphere
+  // Write the XML definition of a sphere
   QString writeXML() const override;
 
 private:
   /// Line edits to enter values
   QLineEdit *m_radius_box, *m_height_box;
-  //Unit choice boxes
+  // Unit choice boxes
   QComboBox *m_runits, *m_hunits;
   /// Centre and axis point boxes
   PointGroupBox *m_lower_centre, *m_axis;
@@ -224,8 +212,7 @@ private:
 /**
  * A widget to define an infinite cylinder
  */
-class InfiniteCylinderDetails : public ShapeDetails
-{
+class InfiniteCylinderDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -233,19 +220,19 @@ private:
   static int g_ninfcyls;
 
 public:
-  ///Default constructor
+  /// Default constructor
   InfiniteCylinderDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~InfiniteCylinderDetails() override { --g_ninfcyls; }
 
-  //Write the XML definition of a sphere
+  // Write the XML definition of a sphere
   QString writeXML() const override;
 
 private:
   /// Line edits to enter values
   QLineEdit *m_radius_box;
-  //Unit choice boxes
+  // Unit choice boxes
   QComboBox *m_runits;
   /// Centre and axis point boxes
   PointGroupBox *m_centre, *m_axis;
@@ -254,8 +241,7 @@ private:
 /**
  * A widget to define an infinite cylinder
  */
-class SliceOfCylinderRingDetails : public ShapeDetails
-{
+class SliceOfCylinderRingDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -263,10 +249,10 @@ private:
   static int g_ncylrings;
 
 public:
-  ///Default constructor
+  /// Default constructor
   SliceOfCylinderRingDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~SliceOfCylinderRingDetails() override { --g_ncylrings; }
 
   /// Write the XML definition of a sphere
@@ -275,15 +261,14 @@ public:
 private:
   /// Line edits to enter values
   QLineEdit *m_rinner_box, *m_router_box, *m_depth_box, *m_arc_box;
-  //Unit choice boxes
+  // Unit choice boxes
   QComboBox *m_iunits, *m_ounits, *m_dunits;
 };
 
 /**
  * A widget to define a cone
  */
-class ConeDetails : public ShapeDetails
-{
+class ConeDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -291,10 +276,10 @@ private:
   static int g_ncones;
 
 public:
-  ///Default constructor
+  /// Default constructor
   ConeDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~ConeDetails() override { --g_ncones; }
 
   /// Write the XML definition of a sphere
@@ -303,7 +288,7 @@ public:
 private:
   /// Line edits to enter values
   QLineEdit *m_height_box, *m_angle_box;
-  //Unit choice boxes
+  // Unit choice boxes
   QComboBox *m_hunits;
   /// Centre and axis point boxes
   PointGroupBox *m_tippoint, *m_axis;
@@ -312,8 +297,7 @@ private:
 /**
  * A widget to define an infinite cone
  */
-class InfiniteConeDetails : public ShapeDetails
-{
+class InfiniteConeDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -321,10 +305,10 @@ private:
   static int g_ninfcones;
 
 public:
-  ///Default constructor
+  /// Default constructor
   InfiniteConeDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~InfiniteConeDetails() override { --g_ninfcones; }
 
   /// Write the XML definition of a sphere
@@ -340,8 +324,7 @@ private:
 /**
  * A widget to define an infinite plane
  */
-class InfinitePlaneDetails : public ShapeDetails
-{
+class InfinitePlaneDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -349,10 +332,10 @@ private:
   static int g_ninfplanes;
 
 public:
-  ///Default constructor
+  /// Default constructor
   InfinitePlaneDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~InfinitePlaneDetails() override { --g_ninfplanes; }
 
   /// Write the XML definition of a sphere
@@ -366,8 +349,7 @@ private:
 /**
  * A widget to define an infinite plane
  */
-class CuboidDetails : public ShapeDetails
-{
+class CuboidDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -375,10 +357,10 @@ private:
   static int g_ncuboids;
 
 public:
-  ///Default constructor
+  /// Default constructor
   CuboidDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~CuboidDetails() override { --g_ncuboids; }
 
   /// Write the XML definition of a sphere
@@ -386,14 +368,14 @@ public:
 
 private:
   /// Corner points
-  PointGroupBox *m_left_frt_bot, *m_left_frt_top, *m_left_bck_bot, *m_right_frt_bot;
+  PointGroupBox *m_left_frt_bot, *m_left_frt_top, *m_left_bck_bot,
+      *m_right_frt_bot;
 };
 
 /**
  * A widget to define a hexahedron
  */
-class HexahedronDetails : public ShapeDetails
-{
+class HexahedronDetails : public ShapeDetails {
   Q_OBJECT
 
 private:
@@ -401,10 +383,10 @@ private:
   static int g_nhexahedrons;
 
 public:
-  ///Default constructor
+  /// Default constructor
   HexahedronDetails(QWidget *parent = 0);
 
-  ///Default destructor
+  /// Default destructor
   ~HexahedronDetails() override { --g_nhexahedrons; }
 
   /// Write the XML definition of a sphere
@@ -412,8 +394,9 @@ public:
 
 private:
   /// Corner points
-  PointGroupBox *m_left_bck_bot, *m_left_frt_bot, *m_right_frt_bot, *m_right_bck_bot,
-    *m_left_bck_top, *m_left_frt_top, *m_right_frt_top, *m_right_bck_top;
+  PointGroupBox *m_left_bck_bot, *m_left_frt_bot, *m_right_frt_bot,
+      *m_right_bck_bot, *m_left_bck_top, *m_left_frt_top, *m_right_frt_top,
+      *m_right_bck_top;
 };
 
 // /**
@@ -445,9 +428,6 @@ private:
 //   /// Corner points
 //   PointGroupBox *m_centre, *m_axis;
 // };
-
-
-
 }
 }
 
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SmoothNeighboursDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SmoothNeighboursDialog.h
index 4d16c9b3cce63f4328b3d61378cb79acbb015075..179f189bd71c1b1ee43f3617e0d256342ebe5f2f 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SmoothNeighboursDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SmoothNeighboursDialog.h
@@ -6,13 +6,12 @@
 
 using namespace MantidQt::API;
 
-class SmoothNeighboursDialog : public AlgorithmDialog
-{
-Q_OBJECT
+class SmoothNeighboursDialog : public AlgorithmDialog {
+  Q_OBJECT
 
 public:
   /// Constructor
-  SmoothNeighboursDialog(QWidget* parent = 0);
+  SmoothNeighboursDialog(QWidget *parent = 0);
 
 protected:
   /// Overridden to enable validators
@@ -20,8 +19,8 @@ protected:
 
 private slots:
   /// Called when input workspace get changed
-  void inputWorkspaceChanged(const QString& pName);
- 
+  void inputWorkspaceChanged(const QString &pName);
+
 private:
   /// Non rectangular detector group name
   static const QString NON_UNIFORM_GROUP;
@@ -34,10 +33,10 @@ private:
   void initLayout() override;
 
   /// Widget for all the PropertyWidgets
-  AlgorithmPropertiesWidget* m_propertiesWidget;
+  AlgorithmPropertiesWidget *m_propertiesWidget;
 
   /// Main layout for the dialog
-  QVBoxLayout* m_dialogLayout;
+  QVBoxLayout *m_dialogLayout;
 };
 
 #endif
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SortTableWorkspaceDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SortTableWorkspaceDialog.h
index 1d4b31aae4dba1d86b7780c43d3e4704fe1c0a8a..24cd9a9a15ee0c3cdcd959bb50f1aa578a6dd905 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SortTableWorkspaceDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/SortTableWorkspaceDialog.h
@@ -9,73 +9,72 @@
 
 #include <QMap>
 
-namespace MantidQt
-{
-
-  namespace CustomDialogs
-  {
-
-    /** 
-      This class gives specialised dialog for the SortTableWorkspace algorithm.
-
-      @date 1/12/2014
-      
-      Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
-      
-      This file is part of Mantid.
-      
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-      
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-      
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-      
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class SortTableWorkspaceDialog : public API::AlgorithmDialog
-    {
-      Q_OBJECT
-      
-    public:
-      /// Default constructor
-      SortTableWorkspaceDialog(QWidget *parent = NULL);
-
-    private:
-      /// Initialize the layout
-      void initLayout() override;
-      /// Pass input from non-standard GUI elements to the algorithm
-      void parseInput() override;
-      /// Tie static widgets to their properties
-      void tieStaticWidgets(const bool readHistory);
-    private slots:
-      /// Update GUI after workspace changes
-      void workspaceChanged(const QString& wsName);
-      /// Add GUI elements to set a new column as a sorting key
-      void addColumn();
-      /// Sync the GUI after a sorting column name changes
-      void changedColumnName(int);
-      /// Remove a column to sort by.
-      void removeColumn();
-      /// Clear the GUI form the workspace specific data/elements
-      void clearGUI();
-    private:
-      /// Form
-      Ui::SortTableWorkspaceDialog m_form;
-      /// Names of the columns in the workspace
-      QStringList m_columnNames;
-      /// Names of columns used to sort the table
-      QStringList m_sortColumns;
-    };
-
-  } // CustomDialogs
+namespace MantidQt {
+
+namespace CustomDialogs {
+
+/**
+  This class gives specialised dialog for the SortTableWorkspace algorithm.
+
+  @date 1/12/2014
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+  National Laboratory
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class SortTableWorkspaceDialog : public API::AlgorithmDialog {
+  Q_OBJECT
+
+public:
+  /// Default constructor
+  SortTableWorkspaceDialog(QWidget *parent = NULL);
+
+private:
+  /// Initialize the layout
+  void initLayout() override;
+  /// Pass input from non-standard GUI elements to the algorithm
+  void parseInput() override;
+  /// Tie static widgets to their properties
+  void tieStaticWidgets(const bool readHistory);
+private slots:
+  /// Update GUI after workspace changes
+  void workspaceChanged(const QString &wsName);
+  /// Add GUI elements to set a new column as a sorting key
+  void addColumn();
+  /// Sync the GUI after a sorting column name changes
+  void changedColumnName(int);
+  /// Remove a column to sort by.
+  void removeColumn();
+  /// Clear the GUI form the workspace specific data/elements
+  void clearGUI();
+
+private:
+  /// Form
+  Ui::SortTableWorkspaceDialog m_form;
+  /// Names of the columns in the workspace
+  QStringList m_columnNames;
+  /// Names of columns used to sort the table
+  QStringList m_sortColumns;
+};
+
+} // CustomDialogs
 } // MantidQt
 
-#endif //MANTIDQT_CUSTOM_DIALOGS_SORTTABLEWORKSPACEDIALOG_H
+#endif // MANTIDQT_CUSTOM_DIALOGS_SORTTABLEWORKSPACEDIALOG_H
diff --git a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/StartLiveDataDialog.h b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/StartLiveDataDialog.h
index 32f5d65ff66bbb3320e4b8a4f512d2ff66dcfdc8..47968140a5856630940a4c19a488f4e7dda9b4da 100644
--- a/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/StartLiveDataDialog.h
+++ b/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/StartLiveDataDialog.h
@@ -11,12 +11,9 @@
 #include "MantidQtAPI/AlgorithmInputHistory.h"
 #include "MantidQtAPI/WidgetScrollbarDecorator.h"
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-class StartLiveDataDialog : public MantidQt::API::AlgorithmDialog
-{
+namespace MantidQt {
+namespace CustomDialogs {
+class StartLiveDataDialog : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 
 public:
@@ -33,10 +30,10 @@ public slots:
   void chkPreserveEventsToggled();
 
 private slots:
-  void setDefaultAccumulationMethod(const QString&);
-  void updateUiElements(const QString&);
+  void setDefaultAccumulationMethod(const QString &);
+  void updateUiElements(const QString &);
   void accept() override;
-  void initListenerPropLayout(const QString&);
+  void initListenerPropLayout(const QString &);
 
 private:
   /// Initialize the layout
@@ -45,7 +42,9 @@ private:
   /// Parse the input from the dialog when it has been accepted
   void parseInput() override;
 
-  Mantid::API::Algorithm_sptr changeAlgorithm(MantidQt::MantidWidgets::AlgorithmSelectorWidget * selector, MantidQt::API::AlgorithmPropertiesWidget * propWidget);
+  Mantid::API::Algorithm_sptr
+  changeAlgorithm(MantidQt::MantidWidgets::AlgorithmSelectorWidget *selector,
+                  MantidQt::API::AlgorithmPropertiesWidget *propWidget);
 
 private:
   /// The form generated by Qt Designer
@@ -64,10 +63,8 @@ private:
 
   /// The algorithm for processing the accumulated workspace
   Mantid::API::Algorithm_sptr m_postProcessingAlg;
-
 };
-
 }
 }
 
-#endif //MANTIDQTCUSTOMDIALOGS_STARTLIVEDATADIALOG_H_
+#endif // MANTIDQTCUSTOMDIALOGS_STARTLIVEDATADIALOG_H_
diff --git a/MantidQt/CustomDialogs/src/CatalogPublishDialog.cpp b/MantidQt/CustomDialogs/src/CatalogPublishDialog.cpp
index 5d633a0b009727e50fa0b02fd43949650542b013..74ad703a088cb26727a4e7ae4fb8060d946fa379 100644
--- a/MantidQt/CustomDialogs/src/CatalogPublishDialog.cpp
+++ b/MantidQt/CustomDialogs/src/CatalogPublishDialog.cpp
@@ -11,162 +11,169 @@
 #include "MantidQtAPI/AlgorithmInputHistory.h"
 #include "MantidQtMantidWidgets/DataSelector.h"
 
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    DECLARE_DIALOG(CatalogPublishDialog)
-
-    /**
-     * Default constructor.
-     * @param parent :: Parent dialog.
-     */
-    CatalogPublishDialog::CatalogPublishDialog(QWidget *parent) : API::AlgorithmDialog(parent), m_uiForm() {}
-
-    /// Initialise the layout
-    void CatalogPublishDialog::initLayout()
-    {
-      m_uiForm.setupUi(this);
-      this->setWindowTitle(m_algName);
-
-      tie(m_uiForm.nameInCatalogTxt,"NameInCatalog");
-      tie(m_uiForm.investigationNumberCb,"InvestigationNumber");
-      tie(m_uiForm.descriptionInput,"DataFileDescription");
-
-      // Assign the buttons with the inherited methods.
-      connect(m_uiForm.runBtn,SIGNAL(clicked()),this,SLOT(accept()));
-      connect(m_uiForm.cancelBtn,SIGNAL(clicked()),this,SLOT(reject()));
-      connect(m_uiForm.helpBtn,SIGNAL(clicked()),this,SLOT(helpClicked()));
-      connect(m_uiForm.investigationNumberCb,SIGNAL(currentIndexChanged(int)),this,SLOT(setSessionProperty(int)));
-      connect(m_uiForm.dataSelector,SIGNAL(dataReady(const QString&)),this,SLOT(workspaceSelected(const QString&)));
-      // When a file is chosen to be published, set the related "FileName" property of the algorithm.
-      connect(m_uiForm.dataSelector,SIGNAL(filesFound()),this,SLOT(fileSelected()));
-
-      // Populate "investigationNumberCb" with the investigation IDs that the user can publish to.
-      populateUserInvestigations();
-
-      // Get optional message here as we may set it if user has no investigations to publish to.
-      m_uiForm.instructions->setText(getOptionalMessage());
-      // This is required as we use the currentIndexChanged SLOT.
-      storePropertyValue("Session",m_uiForm.investigationNumberCb->itemData(0,Qt::UserRole).toString());
-    }
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(CatalogPublishDialog)
+
+/**
+ * Default constructor.
+ * @param parent :: Parent dialog.
+ */
+CatalogPublishDialog::CatalogPublishDialog(QWidget *parent)
+    : API::AlgorithmDialog(parent), m_uiForm() {}
+
+/// Initialise the layout
+void CatalogPublishDialog::initLayout() {
+  m_uiForm.setupUi(this);
+  this->setWindowTitle(m_algName);
+
+  tie(m_uiForm.nameInCatalogTxt, "NameInCatalog");
+  tie(m_uiForm.investigationNumberCb, "InvestigationNumber");
+  tie(m_uiForm.descriptionInput, "DataFileDescription");
+
+  // Assign the buttons with the inherited methods.
+  connect(m_uiForm.runBtn, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(m_uiForm.cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(m_uiForm.helpBtn, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  connect(m_uiForm.investigationNumberCb, SIGNAL(currentIndexChanged(int)),
+          this, SLOT(setSessionProperty(int)));
+  connect(m_uiForm.dataSelector, SIGNAL(dataReady(const QString &)), this,
+          SLOT(workspaceSelected(const QString &)));
+  // When a file is chosen to be published, set the related "FileName" property
+  // of the algorithm.
+  connect(m_uiForm.dataSelector, SIGNAL(filesFound()), this,
+          SLOT(fileSelected()));
+
+  // Populate "investigationNumberCb" with the investigation IDs that the user
+  // can publish to.
+  populateUserInvestigations();
+
+  // Get optional message here as we may set it if user has no investigations to
+  // publish to.
+  m_uiForm.instructions->setText(getOptionalMessage());
+  // This is required as we use the currentIndexChanged SLOT.
+  storePropertyValue(
+      "Session",
+      m_uiForm.investigationNumberCb->itemData(0, Qt::UserRole).toString());
+}
 
-    /**
-     * Populate the investigation number combo-box with investigations that the user can publish to.
-     */
-    void CatalogPublishDialog::populateUserInvestigations()
-    {
-      auto workspace = Mantid::API::WorkspaceFactory::Instance().createTable();
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-
-      // We need to catch the exception to prevent a fatal error.
-      try
-      {
-        if (!session.empty())
-        {
-          // Cast a catalog to a catalogInfoService to access downloading functionality.
-          auto catalogInfoService = boost::dynamic_pointer_cast<Mantid::API::ICatalogInfoService>(
-              Mantid::API::CatalogManager::Instance().getCatalog(session.front()->getSessionId()));
-          // Check if the catalog created supports publishing functionality.
-          if (!catalogInfoService) throw std::runtime_error("The catalog that you are using does not support publishing.");
-          // Populate the workspace with investigations that the user has CREATE access to.
-          workspace = catalogInfoService->getPublishInvestigations();
-        }
-      }
-      catch(std::runtime_error& e)
-      {
-        setOptionalMessage(e.what());
-      }
-
-      if (workspace->rowCount() > 0)
-      {
-        // Populate the form with investigations that the user can publish to.
-        for (size_t row = 0; row < workspace->rowCount(); row++)
-        {
-          m_uiForm.investigationNumberCb->addItem(QString::fromStdString(workspace->getRef<std::string>("InvestigationID",row)));
-          // Added tooltips to improve usability.
-          m_uiForm.investigationNumberCb->setItemData(static_cast<int>(row),
-            QString::fromStdString("The title of the investigation is: \"" + workspace->getRef<std::string>("Title",row) +
-              "\".\nThe instrument of the investigation is: \"" + workspace->getRef<std::string>("Instrument",row)) + "\".",
-              Qt::ToolTipRole);
-          // Set the user role to the sessionID.
-          m_uiForm.investigationNumberCb->setItemData(static_cast<int>(row),
-            QString::fromStdString(workspace->getRef<std::string>("SessionID",row)),Qt::UserRole);
-        }
-      }
-      else
-      {
-        disableDialog();
-      }
+/**
+ * Populate the investigation number combo-box with investigations that the user
+ * can publish to.
+ */
+void CatalogPublishDialog::populateUserInvestigations() {
+  auto workspace = Mantid::API::WorkspaceFactory::Instance().createTable();
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
+
+  // We need to catch the exception to prevent a fatal error.
+  try {
+    if (!session.empty()) {
+      // Cast a catalog to a catalogInfoService to access downloading
+      // functionality.
+      auto catalogInfoService =
+          boost::dynamic_pointer_cast<Mantid::API::ICatalogInfoService>(
+              Mantid::API::CatalogManager::Instance().getCatalog(
+                  session.front()->getSessionId()));
+      // Check if the catalog created supports publishing functionality.
+      if (!catalogInfoService)
+        throw std::runtime_error(
+            "The catalog that you are using does not support publishing.");
+      // Populate the workspace with investigations that the user has CREATE
+      // access to.
+      workspace = catalogInfoService->getPublishInvestigations();
     }
+  } catch (std::runtime_error &e) {
+    setOptionalMessage(e.what());
+  }
 
-    /**
-     * Obtain the name of the workspace selected, and set it to the algorithm's property.
-     * @param wsName :: The name of the workspace to publish.
-     */
-    void CatalogPublishDialog::workspaceSelected(const QString& wsName)
-    {
-      // Prevents both a file and workspace being published at same time.
-      storePropertyValue("FileName", "");
-      setPropertyValue("FileName", true);
-      // Set the workspace property to the one the user has selected to publish.
-      storePropertyValue("InputWorkspace", wsName);
-      setPropertyValue("InputWorkspace", true);
+  if (workspace->rowCount() > 0) {
+    // Populate the form with investigations that the user can publish to.
+    for (size_t row = 0; row < workspace->rowCount(); row++) {
+      m_uiForm.investigationNumberCb->addItem(QString::fromStdString(
+          workspace->getRef<std::string>("InvestigationID", row)));
+      // Added tooltips to improve usability.
+      m_uiForm.investigationNumberCb->setItemData(
+          static_cast<int>(row),
+          QString::fromStdString(
+              "The title of the investigation is: \"" +
+              workspace->getRef<std::string>("Title", row) +
+              "\".\nThe instrument of the investigation is: \"" +
+              workspace->getRef<std::string>("Instrument", row)) +
+              "\".",
+          Qt::ToolTipRole);
+      // Set the user role to the sessionID.
+      m_uiForm.investigationNumberCb->setItemData(
+          static_cast<int>(row),
+          QString::fromStdString(
+              workspace->getRef<std::string>("SessionID", row)),
+          Qt::UserRole);
     }
+  } else {
+    disableDialog();
+  }
+}
 
-    /**
-     * Set the "FileName" property when a file is selected from the file browser.
-     */
-    void CatalogPublishDialog::fileSelected()
-    {
-      // Reset workspace property as the input is a file. This prevents both being selected.
-      storePropertyValue("InputWorkspace", "");
-      setPropertyValue("InputWorkspace", true);
-      // Set the FileName property to the path that appears in the input field on the dialog.
-      storePropertyValue("FileName", m_uiForm.dataSelector->getFullFilePath());
-      setPropertyValue("FileName", true);
-    }
+/**
+ * Obtain the name of the workspace selected, and set it to the algorithm's
+ * property.
+ * @param wsName :: The name of the workspace to publish.
+ */
+void CatalogPublishDialog::workspaceSelected(const QString &wsName) {
+  // Prevents both a file and workspace being published at same time.
+  storePropertyValue("FileName", "");
+  setPropertyValue("FileName", true);
+  // Set the workspace property to the one the user has selected to publish.
+  storePropertyValue("InputWorkspace", wsName);
+  setPropertyValue("InputWorkspace", true);
+}
 
-    /**
-     * Diables fields on dialog to improve usability
-     */
-    void CatalogPublishDialog::disableDialog()
-    {
-      m_uiForm.scrollArea->setDisabled(true);
-      m_uiForm.runBtn->setDisabled(true);
-    }
+/**
+ * Set the "FileName" property when a file is selected from the file browser.
+ */
+void CatalogPublishDialog::fileSelected() {
+  // Reset workspace property as the input is a file. This prevents both being
+  // selected.
+  storePropertyValue("InputWorkspace", "");
+  setPropertyValue("InputWorkspace", true);
+  // Set the FileName property to the path that appears in the input field on
+  // the dialog.
+  storePropertyValue("FileName", m_uiForm.dataSelector->getFullFilePath());
+  setPropertyValue("FileName", true);
+}
 
-    /**
-     * Set/Update the sessionID of the `Session` property when
-     * the user selects an investigation from the combo-box.
-     */
-    void CatalogPublishDialog::setSessionProperty(int index)
-    {
-      storePropertyValue("Session",
-          m_uiForm.investigationNumberCb->itemData(index,Qt::UserRole).toString());
-    }
+/**
+ * Diables fields on dialog to improve usability
+ */
+void CatalogPublishDialog::disableDialog() {
+  m_uiForm.scrollArea->setDisabled(true);
+  m_uiForm.runBtn->setDisabled(true);
+}
 
-    /**
-     * Overridden to enable dataselector validators.
-     */
-    void CatalogPublishDialog::accept()
-    {
-      if (!m_uiForm.dataSelector->isValid())
-      {
-        if (m_uiForm.dataSelector->getFullFilePath().isEmpty())
-        {
-          QMessageBox::critical(this,"Error in catalog publishing.","No file specified.");
-        }
-        else
-        {
-          QMessageBox::critical(this,"Error in catalog publishing.",m_uiForm.dataSelector->getProblem());
-        }
-      }
-      else
-      {
-        AlgorithmDialog::accept();
-      }
-    }
+/**
+ * Set/Update the sessionID of the `Session` property when
+ * the user selects an investigation from the combo-box.
+ */
+void CatalogPublishDialog::setSessionProperty(int index) {
+  storePropertyValue(
+      "Session",
+      m_uiForm.investigationNumberCb->itemData(index, Qt::UserRole).toString());
+}
 
+/**
+ * Overridden to enable dataselector validators.
+ */
+void CatalogPublishDialog::accept() {
+  if (!m_uiForm.dataSelector->isValid()) {
+    if (m_uiForm.dataSelector->getFullFilePath().isEmpty()) {
+      QMessageBox::critical(this, "Error in catalog publishing.",
+                            "No file specified.");
+    } else {
+      QMessageBox::critical(this, "Error in catalog publishing.",
+                            m_uiForm.dataSelector->getProblem());
+    }
+  } else {
+    AlgorithmDialog::accept();
   }
 }
+}
+}
diff --git a/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp b/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp
index 5d87331f8a3f1b4b25bd16c00e4a51703e3d8173..4541e22535110d03199f6b19834c8c8591f67f6e 100644
--- a/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp
+++ b/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp
@@ -17,124 +17,115 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include "MantidAPI/ITableWorkspace.h"
 
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    // Declare the dialog. Name must match the class name
-    DECLARE_DIALOG(ConvertTableToMatrixWorkspaceDialog)
+namespace MantidQt {
+namespace CustomDialogs {
+// Declare the dialog. Name must match the class name
+DECLARE_DIALOG(ConvertTableToMatrixWorkspaceDialog)
 
-    //--------------------------------------------------------------------------
-    // Public methods
-    //---------------------------------------------------------------------------
+//--------------------------------------------------------------------------
+// Public methods
+//---------------------------------------------------------------------------
 
-    /// Default constructor
-    ConvertTableToMatrixWorkspaceDialog:: ConvertTableToMatrixWorkspaceDialog(QWidget *parent) 
-      : API::AlgorithmDialog(parent), m_form()
-    {
-    }
+/// Default constructor
+ConvertTableToMatrixWorkspaceDialog::ConvertTableToMatrixWorkspaceDialog(
+    QWidget *parent)
+    : API::AlgorithmDialog(parent), m_form() {}
 
-    //--------------------------------------------------------------------------
-    // Private methods (slot)
-    //---------------------------------------------------------------------------
+//--------------------------------------------------------------------------
+// Private methods (slot)
+//---------------------------------------------------------------------------
 
-    /** 
-    * When the input workspace changes the column name comboboxes have to
-    * be updated.
-    * @param qWSName :: The new table workspace name
-    */
-    void ConvertTableToMatrixWorkspaceDialog::fillColumnNames(const QString& qWSName)
+/**
+* When the input workspace changes the column name comboboxes have to
+* be updated.
+* @param qWSName :: The new table workspace name
+*/
+void ConvertTableToMatrixWorkspaceDialog::fillColumnNames(
+    const QString &qWSName) {
+  m_form.cbColumnX->clear();
+  m_form.cbColumnY->clear();
+  m_form.cbColumnE->clear();
+  std::string wsName = qWSName.toStdString();
+  if (wsName.empty())
+    return;
+  Mantid::API::ITableWorkspace_sptr tws =
+      boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(wsName));
+  if (!tws)
+    return;                             // just in case
+  m_form.cbColumnE->insertItem(-1, ""); // the default value
+  std::vector<std::string> columns = tws->getColumnNames();
+  if (columns.empty())
+    return;
+  QString defaultXColumn;
+  QString defaultYColumn;
+  QString defaultEColumn;
+  for (std::vector<std::string>::const_iterator column = columns.begin();
+       column != columns.end(); ++column) {
+    QString qName = QString::fromStdString(*column);
+    m_form.cbColumnX->insertItem(-1, qName);
+    m_form.cbColumnY->insertItem(-1, qName);
+    m_form.cbColumnE->insertItem(-1, qName);
+    Mantid::API::Column_sptr col = tws->getColumn(*column);
+    if (col->getPlotType() == 1 && defaultXColumn.isEmpty()) // type X
     {
-      m_form.cbColumnX->clear();
-      m_form.cbColumnY->clear();
-      m_form.cbColumnE->clear();
-      std::string wsName = qWSName.toStdString();
-      if (wsName.empty()) return;
-      Mantid::API::ITableWorkspace_sptr tws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(wsName)
-        );
-      if (!tws) return; // just in case
-      m_form.cbColumnE->insertItem(-1, ""); // the default value
-      std::vector<std::string> columns = tws->getColumnNames();
-      if (columns.empty()) return;
-      QString defaultXColumn;
-      QString defaultYColumn;
-      QString defaultEColumn;
-      for(std::vector<std::string>::const_iterator column = columns.begin(); column != columns.end(); ++column)
-      {
-        QString qName = QString::fromStdString(*column);
-        m_form.cbColumnX->insertItem(-1, qName);
-        m_form.cbColumnY->insertItem(-1, qName);
-        m_form.cbColumnE->insertItem(-1, qName);
-        Mantid::API::Column_sptr col = tws->getColumn(*column);
-        if (col->getPlotType() == 1 && defaultXColumn.isEmpty()) // type X
-        {
-          defaultXColumn = qName;
-        }
-        if (col->getPlotType() == 2 && defaultYColumn.isEmpty()) // type Y
-        {
-          defaultYColumn = qName;
-        }
-        if (col->getPlotType() == 5 && defaultEColumn.isEmpty()) // type yErr
-        {
-          defaultEColumn = qName;
-        }
-      }
-      // set initial guesses for column names
-      if ( !defaultXColumn.isEmpty() )
-      {
-        int i = m_form.cbColumnX->findText(defaultXColumn);
-        if (i >= 0)
-        {
-          m_form.cbColumnX->setCurrentIndex(i);
-        }
-      }
-      if ( !defaultYColumn.isEmpty() )
-      {
-        int i = m_form.cbColumnY->findText(defaultYColumn);
-        if (i >= 0)
-        {
-          m_form.cbColumnY->setCurrentIndex(i);
-        }
-      }
-      if ( !defaultEColumn.isEmpty() )
-      {
-        int i = m_form.cbColumnE->findText(defaultEColumn);
-        if (i >= 0)
-        {
-          m_form.cbColumnE->setCurrentIndex(i);
-        }
-      }
+      defaultXColumn = qName;
+    }
+    if (col->getPlotType() == 2 && defaultYColumn.isEmpty()) // type Y
+    {
+      defaultYColumn = qName;
+    }
+    if (col->getPlotType() == 5 && defaultEColumn.isEmpty()) // type yErr
+    {
+      defaultEColumn = qName;
+    }
+  }
+  // set initial guesses for column names
+  if (!defaultXColumn.isEmpty()) {
+    int i = m_form.cbColumnX->findText(defaultXColumn);
+    if (i >= 0) {
+      m_form.cbColumnX->setCurrentIndex(i);
+    }
+  }
+  if (!defaultYColumn.isEmpty()) {
+    int i = m_form.cbColumnY->findText(defaultYColumn);
+    if (i >= 0) {
+      m_form.cbColumnY->setCurrentIndex(i);
+    }
+  }
+  if (!defaultEColumn.isEmpty()) {
+    int i = m_form.cbColumnE->findText(defaultEColumn);
+    if (i >= 0) {
+      m_form.cbColumnE->setCurrentIndex(i);
     }
+  }
+}
 
-    //--------------------------------------------------------------------------
-    // Private methods (non-slot)
-    //---------------------------------------------------------------------------
+//--------------------------------------------------------------------------
+// Private methods (non-slot)
+//---------------------------------------------------------------------------
 
-    /// Initialize the layout
-    void ConvertTableToMatrixWorkspaceDialog::initLayout()
-    {
-      m_form.setupUi(this);
-      ((QVBoxLayout*)this->layout())->addLayout(createDefaultButtonLayout());
-      tie(m_form.cbInputWorkspace,"InputWorkspace",m_form.gridLayout);
-      tie(m_form.leOutputWorkspace,"OutputWorkspace",m_form.gridLayout);
-      tie(m_form.cbColumnX,"ColumnX",m_form.gridLayout);
-      tie(m_form.cbColumnY,"ColumnY",m_form.gridLayout);
-      tie(m_form.cbColumnE,"ColumnE",m_form.gridLayout);
+/// Initialize the layout
+void ConvertTableToMatrixWorkspaceDialog::initLayout() {
+  m_form.setupUi(this);
+  ((QVBoxLayout *)this->layout())->addLayout(createDefaultButtonLayout());
+  tie(m_form.cbInputWorkspace, "InputWorkspace", m_form.gridLayout);
+  tie(m_form.leOutputWorkspace, "OutputWorkspace", m_form.gridLayout);
+  tie(m_form.cbColumnX, "ColumnX", m_form.gridLayout);
+  tie(m_form.cbColumnY, "ColumnY", m_form.gridLayout);
+  tie(m_form.cbColumnE, "ColumnE", m_form.gridLayout);
 
-      QString presetInputWorkspace = this->getInputValue("InputWorkspace");
-      fillAndSetComboBox("InputWorkspace", m_form.cbInputWorkspace);
-      if (!presetInputWorkspace.isEmpty())
-      {
-        int i = m_form.cbInputWorkspace->findText(presetInputWorkspace);
-        if ( i >= 0 )
-        {
-          m_form.cbInputWorkspace->setCurrentIndex(i);
-        }
-      }
-      connect(m_form.cbInputWorkspace,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(fillColumnNames(const QString&)));
-      fillColumnNames(m_form.cbInputWorkspace->currentText());
+  QString presetInputWorkspace = this->getInputValue("InputWorkspace");
+  fillAndSetComboBox("InputWorkspace", m_form.cbInputWorkspace);
+  if (!presetInputWorkspace.isEmpty()) {
+    int i = m_form.cbInputWorkspace->findText(presetInputWorkspace);
+    if (i >= 0) {
+      m_form.cbInputWorkspace->setCurrentIndex(i);
     }
-
   }
+  connect(m_form.cbInputWorkspace, SIGNAL(currentIndexChanged(const QString &)),
+          this, SLOT(fillColumnNames(const QString &)));
+  fillColumnNames(m_form.cbInputWorkspace->currentText());
+}
+}
 }
diff --git a/MantidQt/CustomDialogs/src/LOQScriptInputDialog.cpp b/MantidQt/CustomDialogs/src/LOQScriptInputDialog.cpp
index 15280c6c137d709330b7f28fcdd760c936618603..79b8bfc8938e9486f89e02e3e7a557d0218d3c99 100644
--- a/MantidQt/CustomDialogs/src/LOQScriptInputDialog.cpp
+++ b/MantidQt/CustomDialogs/src/LOQScriptInputDialog.cpp
@@ -6,18 +6,14 @@
 #include <QFileInfo>
 #include <QDir>
 
-
-
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-  DECLARE_DIALOG(LOQScriptInputDialog)
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(LOQScriptInputDialog)
 }
 }
 
-// Just to save writing this everywhere 
+// Just to save writing this everywhere
 using namespace MantidQt::CustomDialogs;
 
 //---------------------------------------
@@ -25,26 +21,24 @@ using namespace MantidQt::CustomDialogs;
 //---------------------------------------
 
 /// Constructor
-LOQScriptInputDialog::LOQScriptInputDialog(QWidget* parent) :
-  AlgorithmDialog(parent)
-{
-}
+LOQScriptInputDialog::LOQScriptInputDialog(QWidget *parent)
+    : AlgorithmDialog(parent) {}
 
 /**
  * Set up the dialog
  */
-void LOQScriptInputDialog::initLayout()
-{
+void LOQScriptInputDialog::initLayout() {
   m_uiForm.setupUi(this);
-  
-  connect( m_uiForm.browseButton, SIGNAL(clicked()), this, SLOT(browseClicked()) );
+
+  connect(m_uiForm.browseButton, SIGNAL(clicked()), this,
+          SLOT(browseClicked()));
 
   fillLineEdit("SampleWorkspace", m_uiForm.sampleBox);
   fillLineEdit("EmptyCanWorkspace", m_uiForm.emptycanBox);
   fillLineEdit("TransmissionSampleWorkspace", m_uiForm.transSampleBox);
   fillLineEdit("TransmissionDirectWorkspace", m_uiForm.transDirectBox);
   fillLineEdit("TransmissionEmptyCanWorkspace", m_uiForm.transEmptyBox);
-  
+
   fillLineEdit("Radius_min", m_uiForm.radMinBox);
   fillLineEdit("Radius_max", m_uiForm.radMaxBox);
 
@@ -58,31 +52,35 @@ void LOQScriptInputDialog::initLayout()
 
   fillLineEdit("Beam_Centre_X", m_uiForm.beamXBox);
   fillLineEdit("Beam_Centre_Y", m_uiForm.beamYBox);
-  
-  //Efficiency correction
+
+  // Efficiency correction
   fillLineEdit("EfficiencyCorrectionFile", m_uiForm.effFileBox);
 
   m_uiForm.sampleBox->setFocus();
-  
 }
 
 /**
  * Retrieve the input from the dialog
  */
-void LOQScriptInputDialog::parseInput()
-{
-  // All elements within the dialog are public memebers of the LOQScriptInputDialog class
+void LOQScriptInputDialog::parseInput() {
+  // All elements within the dialog are public memebers of the
+  // LOQScriptInputDialog class
   // and have the names given to them in Qt Designer
-  
-  //Simply access each widget and use storePropertyValue( propName, m_uiForm->propValue)    
-  //method of the AlgorithmDialog base class to add the input value for this property
+
+  // Simply access each widget and use storePropertyValue( propName,
+  // m_uiForm->propValue)
+  // method of the AlgorithmDialog base class to add the input value for this
+  // property
 
   storePropertyValue("SampleWorkspace", m_uiForm.sampleBox->text());
   storePropertyValue("EmptyCanWorkspace", m_uiForm.emptycanBox->text());
-  storePropertyValue("TransmissionSampleWorkspace", m_uiForm.transSampleBox->text());
-  storePropertyValue("TransmissionDirectWorkspace", m_uiForm.transDirectBox->text());
-  storePropertyValue("TransmissionEmptyCanWorkspace", m_uiForm.transEmptyBox->text());
-  
+  storePropertyValue("TransmissionSampleWorkspace",
+                     m_uiForm.transSampleBox->text());
+  storePropertyValue("TransmissionDirectWorkspace",
+                     m_uiForm.transDirectBox->text());
+  storePropertyValue("TransmissionEmptyCanWorkspace",
+                     m_uiForm.transEmptyBox->text());
+
   storePropertyValue("Radius_min", m_uiForm.radMinBox->text());
   storePropertyValue("Radius_max", m_uiForm.radMaxBox->text());
 
@@ -96,24 +94,21 @@ void LOQScriptInputDialog::parseInput()
 
   storePropertyValue("Beam_Centre_X", m_uiForm.beamXBox->text());
   storePropertyValue("Beam_Centre_Y", m_uiForm.beamYBox->text());
-  
-  //Efficiency correction
-  storePropertyValue("EfficiencyCorrectionFile", m_uiForm.effFileBox->text());
 
+  // Efficiency correction
+  storePropertyValue("EfficiencyCorrectionFile", m_uiForm.effFileBox->text());
 }
 
 /**
   * A slot for the browse button "clicked" signal
   */
-void LOQScriptInputDialog::browseClicked()
-{
-  if( !m_uiForm.effFileBox->text().isEmpty() )
-  {
+void LOQScriptInputDialog::browseClicked() {
+  if (!m_uiForm.effFileBox->text().isEmpty()) {
     QString dir = QFileInfo(m_uiForm.effFileBox->text()).absoluteDir().path();
     MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(dir);
-  }  
+  }
 
   QString filepath = this->openFileDialog("EfficiencyCorrectionFile");
-  if( !filepath.isEmpty() ) m_uiForm.effFileBox->setText(filepath);
+  if (!filepath.isEmpty())
+    m_uiForm.effFileBox->setText(filepath);
 }
-
diff --git a/MantidQt/CustomDialogs/src/LoadAsciiDialog.cpp b/MantidQt/CustomDialogs/src/LoadAsciiDialog.cpp
index 97e65a3689a1db89ac1907a486bdb80e4ded73d9..cfb2e542f3c808cc8fc03e29b98e88c7097f3996 100644
--- a/MantidQt/CustomDialogs/src/LoadAsciiDialog.cpp
+++ b/MantidQt/CustomDialogs/src/LoadAsciiDialog.cpp
@@ -8,139 +8,124 @@
 #include <QtGui>
 #include <QFileInfo>
 
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    DECLARE_DIALOG(LoadAsciiDialog)
-
-    LoadAsciiDialog::LoadAsciiDialog(QWidget *parent)
-      : MantidQt::API::AlgorithmDialog(parent),
-      m_lineFilename(NULL),
-      m_lineOutputWorkspace(NULL),
-      m_lineCommentIndicator(NULL),
-      m_lineCustomSeparator(NULL),
-      m_separatorBox(NULL)
-    {
-    }
-
-    LoadAsciiDialog::~LoadAsciiDialog()
-    {
-    }
-
-    void LoadAsciiDialog::initLayout()
-    {
-      QGridLayout *paramsLayout = new QGridLayout;
-
-      QLabel *label = new QLabel(tr("Filename"));
-      m_lineFilename = new QLineEdit;
-      label->setBuddy(m_lineFilename);
-      paramsLayout->addWidget(label,0,0);
-      paramsLayout->addWidget(m_lineFilename,0,1);
-      tie(m_lineFilename, "Filename", paramsLayout);
-      connect(m_lineFilename,SIGNAL(editingFinished()),this,SLOT(checkFileExtension()));
-
-      QPushButton *browseBtn = new QPushButton("Browse");
-      connect(browseBtn, SIGNAL(clicked()), this, SLOT(browseClicked()));
-      browseBtn->setEnabled(isWidgetEnabled("Filename"));
-      paramsLayout->addWidget(browseBtn,0,3);
-
-      label = new QLabel(tr("Workspace"));
-      m_lineOutputWorkspace = new QLineEdit;
-      label->setBuddy(m_lineOutputWorkspace);
-      paramsLayout->addWidget(label,1,0);
-      paramsLayout->addWidget(m_lineOutputWorkspace,1,1);
-      tie(m_lineOutputWorkspace, "OutputWorkspace", paramsLayout);
-
-      m_separatorBox = new QComboBox;
-      fillAndSetComboBox("Separator",m_separatorBox);
-      paramsLayout->addWidget(new QLabel("Separator"),2,0);
-      paramsLayout->addWidget(m_separatorBox,2,1);
-      tie(m_separatorBox,"Separator",paramsLayout);
-
-      if (getAlgorithm()->version() == 2)
-      {
-        label = new QLabel(tr("CustomSeparator"));
-        m_lineCustomSeparator = new QLineEdit;
-        label->setBuddy(m_lineCustomSeparator);
-        paramsLayout->addWidget(label,3,0);
-        paramsLayout->addWidget(m_lineCustomSeparator,3,1);
-        tie(m_lineCustomSeparator, "CustomSeparator", paramsLayout);
-
-        label = new QLabel(tr("CommentIndicator"));
-        m_lineCommentIndicator = new QLineEdit;
-        label->setBuddy(m_lineCommentIndicator);
-        paramsLayout->addWidget(label,4,0);
-        paramsLayout->addWidget(m_lineCommentIndicator,4,1);
-        tie(m_lineCommentIndicator, "CommentIndicator", paramsLayout);
-
-        QComboBox *unitBox = new QComboBox;
-        fillAndSetComboBox("Unit",unitBox );
-        paramsLayout->addWidget(new QLabel("Unit"),5,0);
-        paramsLayout->addWidget(unitBox ,5,1);
-        tie(unitBox ,"Unit",paramsLayout);
-      }
-      else
-      {
-        QComboBox *unitBox = new QComboBox;
-        fillAndSetComboBox("Unit",unitBox );
-        paramsLayout->addWidget(new QLabel("Unit"),3,0);
-        paramsLayout->addWidget(unitBox ,3,1);
-        tie(unitBox ,"Unit",paramsLayout);
-      }
-
-      QVBoxLayout *mainLayout = new QVBoxLayout;
-
-      //Adds the yellow optional message
-      if( isMessageAvailable() )
-      {
-        this->addOptionalMessage(mainLayout);
-      }
-
-      mainLayout->addLayout(paramsLayout);
-      mainLayout->addLayout(createDefaultButtonLayout("?", "Load", "Cancel"));
-
-      setLayout(mainLayout);
-      setFixedHeight(sizeHint().height());
-
-      checkFileExtension();
-    }
-
-    /**
-    * A slot for the browse button "clicked" signal
-    */
-    void LoadAsciiDialog::browseClicked()
-    {
-      if( !m_lineFilename->text().isEmpty() )
-      {
-        MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(m_lineFilename->text()).absoluteDir().path());
-      }
-
-      QString filepath = this->openFileDialog("Filename");
-      if( !filepath.isEmpty() )
-      {
-        m_lineFilename->clear();
-        m_lineFilename->setText(filepath.trimmed());
-      }
-
-      //Add a suggestion for workspace name
-      if( m_lineOutputWorkspace->isEnabled() && !filepath.isEmpty() ) m_lineOutputWorkspace->setText(QFileInfo(filepath).baseName());
-
-      checkFileExtension();
-    }
-
-    /**
-    * Check for consistency between the file extension and the separator
-    */
-    void LoadAsciiDialog::checkFileExtension()
-    {
-      QString fileName = m_lineFilename->text();
-      if (fileName.isEmpty()) return;
-      QFileInfo file(fileName);
-      if (file.suffix().toLower() == "csv")
-      {
-        m_separatorBox->setCurrentIndex(m_separatorBox->findText("CSV"));
-      }
-    }
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(LoadAsciiDialog)
+
+LoadAsciiDialog::LoadAsciiDialog(QWidget *parent)
+    : MantidQt::API::AlgorithmDialog(parent), m_lineFilename(NULL),
+      m_lineOutputWorkspace(NULL), m_lineCommentIndicator(NULL),
+      m_lineCustomSeparator(NULL), m_separatorBox(NULL) {}
+
+LoadAsciiDialog::~LoadAsciiDialog() {}
+
+void LoadAsciiDialog::initLayout() {
+  QGridLayout *paramsLayout = new QGridLayout;
+
+  QLabel *label = new QLabel(tr("Filename"));
+  m_lineFilename = new QLineEdit;
+  label->setBuddy(m_lineFilename);
+  paramsLayout->addWidget(label, 0, 0);
+  paramsLayout->addWidget(m_lineFilename, 0, 1);
+  tie(m_lineFilename, "Filename", paramsLayout);
+  connect(m_lineFilename, SIGNAL(editingFinished()), this,
+          SLOT(checkFileExtension()));
+
+  QPushButton *browseBtn = new QPushButton("Browse");
+  connect(browseBtn, SIGNAL(clicked()), this, SLOT(browseClicked()));
+  browseBtn->setEnabled(isWidgetEnabled("Filename"));
+  paramsLayout->addWidget(browseBtn, 0, 3);
+
+  label = new QLabel(tr("Workspace"));
+  m_lineOutputWorkspace = new QLineEdit;
+  label->setBuddy(m_lineOutputWorkspace);
+  paramsLayout->addWidget(label, 1, 0);
+  paramsLayout->addWidget(m_lineOutputWorkspace, 1, 1);
+  tie(m_lineOutputWorkspace, "OutputWorkspace", paramsLayout);
+
+  m_separatorBox = new QComboBox;
+  fillAndSetComboBox("Separator", m_separatorBox);
+  paramsLayout->addWidget(new QLabel("Separator"), 2, 0);
+  paramsLayout->addWidget(m_separatorBox, 2, 1);
+  tie(m_separatorBox, "Separator", paramsLayout);
+
+  if (getAlgorithm()->version() == 2) {
+    label = new QLabel(tr("CustomSeparator"));
+    m_lineCustomSeparator = new QLineEdit;
+    label->setBuddy(m_lineCustomSeparator);
+    paramsLayout->addWidget(label, 3, 0);
+    paramsLayout->addWidget(m_lineCustomSeparator, 3, 1);
+    tie(m_lineCustomSeparator, "CustomSeparator", paramsLayout);
+
+    label = new QLabel(tr("CommentIndicator"));
+    m_lineCommentIndicator = new QLineEdit;
+    label->setBuddy(m_lineCommentIndicator);
+    paramsLayout->addWidget(label, 4, 0);
+    paramsLayout->addWidget(m_lineCommentIndicator, 4, 1);
+    tie(m_lineCommentIndicator, "CommentIndicator", paramsLayout);
+
+    QComboBox *unitBox = new QComboBox;
+    fillAndSetComboBox("Unit", unitBox);
+    paramsLayout->addWidget(new QLabel("Unit"), 5, 0);
+    paramsLayout->addWidget(unitBox, 5, 1);
+    tie(unitBox, "Unit", paramsLayout);
+  } else {
+    QComboBox *unitBox = new QComboBox;
+    fillAndSetComboBox("Unit", unitBox);
+    paramsLayout->addWidget(new QLabel("Unit"), 3, 0);
+    paramsLayout->addWidget(unitBox, 3, 1);
+    tie(unitBox, "Unit", paramsLayout);
   }
+
+  QVBoxLayout *mainLayout = new QVBoxLayout;
+
+  // Adds the yellow optional message
+  if (isMessageAvailable()) {
+    this->addOptionalMessage(mainLayout);
+  }
+
+  mainLayout->addLayout(paramsLayout);
+  mainLayout->addLayout(createDefaultButtonLayout("?", "Load", "Cancel"));
+
+  setLayout(mainLayout);
+  setFixedHeight(sizeHint().height());
+
+  checkFileExtension();
+}
+
+/**
+* A slot for the browse button "clicked" signal
+*/
+void LoadAsciiDialog::browseClicked() {
+  if (!m_lineFilename->text().isEmpty()) {
+    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(
+        QFileInfo(m_lineFilename->text()).absoluteDir().path());
+  }
+
+  QString filepath = this->openFileDialog("Filename");
+  if (!filepath.isEmpty()) {
+    m_lineFilename->clear();
+    m_lineFilename->setText(filepath.trimmed());
+  }
+
+  // Add a suggestion for workspace name
+  if (m_lineOutputWorkspace->isEnabled() && !filepath.isEmpty())
+    m_lineOutputWorkspace->setText(QFileInfo(filepath).baseName());
+
+  checkFileExtension();
+}
+
+/**
+* Check for consistency between the file extension and the separator
+*/
+void LoadAsciiDialog::checkFileExtension() {
+  QString fileName = m_lineFilename->text();
+  if (fileName.isEmpty())
+    return;
+  QFileInfo file(fileName);
+  if (file.suffix().toLower() == "csv") {
+    m_separatorBox->setCurrentIndex(m_separatorBox->findText("CSV"));
+  }
+}
+}
 }
diff --git a/MantidQt/CustomDialogs/src/LoadDAEDialog.cpp b/MantidQt/CustomDialogs/src/LoadDAEDialog.cpp
index a378f5bc1b4163f792d4d9e9a9bea4e81ba728af..c752896afadd209fc5990b17298082004ffa743f 100644
--- a/MantidQt/CustomDialogs/src/LoadDAEDialog.cpp
+++ b/MantidQt/CustomDialogs/src/LoadDAEDialog.cpp
@@ -8,86 +8,73 @@
 #include <QtGui>
 #include <qfiledialog.h>
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
-  DECLARE_DIALOG(LoadDAEDialog)
+DECLARE_DIALOG(LoadDAEDialog)
 
 /// An object for constructing a shared_ptr that won't ever delete its pointee
-class NoDeleting
-{
+class NoDeleting {
 public:
   /// Does nothing
-  void operator()(void*){}
+  void operator()(void *) {}
   /// Does nothing
-  void operator()(const void*){}
+  void operator()(const void *) {}
 };
-        
-LoadDAEDialog::LoadDAEDialog(QWidget *parent) 
-  : MantidQt::API::AlgorithmDialog(parent),
-  lineHost(NULL),
-  lineName(NULL),
-  minSpLineEdit(NULL),
-  maxSpLineEdit(NULL),
-  listSpLineEdit(NULL),
-  updateLineEdit(NULL)
-{
-}
 
-LoadDAEDialog::~LoadDAEDialog()
-{
-	
-}
+LoadDAEDialog::LoadDAEDialog(QWidget *parent)
+    : MantidQt::API::AlgorithmDialog(parent), lineHost(NULL), lineName(NULL),
+      minSpLineEdit(NULL), maxSpLineEdit(NULL), listSpLineEdit(NULL),
+      updateLineEdit(NULL) {}
+
+LoadDAEDialog::~LoadDAEDialog() {}
 
-void LoadDAEDialog::initLayout()
-{
+void LoadDAEDialog::initLayout() {
   QGridLayout *paramsLayout = new QGridLayout;
   QLabel *label = new QLabel(tr("DAE Name"));
   lineHost = new QLineEdit;
   label->setBuddy(lineHost);
-  paramsLayout->addWidget(label,0,0);
-  paramsLayout->addWidget(lineHost,0,1);
+  paramsLayout->addWidget(label, 0, 0);
+  paramsLayout->addWidget(lineHost, 0, 1);
   tie(lineHost, "DAEname", paramsLayout);
 
   label = new QLabel(tr("Workspace Name"));
   lineName = new QLineEdit;
   label->setBuddy(lineName);
-  paramsLayout->addWidget(label,1,0);
-  paramsLayout->addWidget(lineName,1,1);
+  paramsLayout->addWidget(label, 1, 0);
+  paramsLayout->addWidget(lineName, 1, 1);
   tie(lineName, "OutputWorkspace", paramsLayout);
 
   QLabel *minSpLabel = new QLabel("Starting spectrum");
   minSpLineEdit = new QLineEdit;
-  paramsLayout->addWidget(minSpLabel,2,0);
-  paramsLayout->addWidget(minSpLineEdit,2,1);
+  paramsLayout->addWidget(minSpLabel, 2, 0);
+  paramsLayout->addWidget(minSpLineEdit, 2, 1);
   tie(minSpLineEdit, "SpectrumMin", paramsLayout);
 
   QLabel *maxSpLabel = new QLabel("Ending spectrum");
   maxSpLineEdit = new QLineEdit;
-  paramsLayout->addWidget(maxSpLabel,3,0);
-  paramsLayout->addWidget(maxSpLineEdit,3,1);
+  paramsLayout->addWidget(maxSpLabel, 3, 0);
+  paramsLayout->addWidget(maxSpLineEdit, 3, 1);
   tie(maxSpLineEdit, "SpectrumMax", paramsLayout);
 
   QLabel *listSpLabel = new QLabel("Spectrum List");
   listSpLineEdit = new QLineEdit;
-  paramsLayout->addWidget(listSpLabel,4,0);
-  paramsLayout->addWidget(listSpLineEdit,4,1);
+  paramsLayout->addWidget(listSpLabel, 4, 0);
+  paramsLayout->addWidget(listSpLineEdit, 4, 1);
   tie(listSpLineEdit, "SpectrumList", paramsLayout);
 
   QHBoxLayout *updateLayout = new QHBoxLayout;
   QLabel *updateLabel = new QLabel("Update every");
   updateLineEdit = new QLineEdit;
-  QIntValidator *ival = new QIntValidator(1,99999999,updateLineEdit);
+  QIntValidator *ival = new QIntValidator(1, 99999999, updateLineEdit);
   updateLineEdit->setValidator(ival);
 
   label = new QLabel(" seconds");
-  paramsLayout->addWidget(updateLabel,5,0);
+  paramsLayout->addWidget(updateLabel, 5, 0);
   updateLayout->addWidget(updateLineEdit);
   updateLayout->addWidget(label);
-  paramsLayout->addLayout(updateLayout,5,1);
-  tie(updateLineEdit,"UpdateRate",updateLayout);
+  paramsLayout->addLayout(updateLayout, 5, 1);
+  tie(updateLineEdit, "UpdateRate", updateLayout);
 
   QVBoxLayout *mainLayout = new QVBoxLayout;
   mainLayout->addLayout(paramsLayout);
@@ -96,8 +83,6 @@ void LoadDAEDialog::initLayout()
   setLayout(mainLayout);
   setWindowTitle(tr("Load Workspace from DAE"));
   setFixedHeight(sizeHint().height());
-
 }
-
 }
 }
diff --git a/MantidQt/CustomDialogs/src/LoadDialog.cpp b/MantidQt/CustomDialogs/src/LoadDialog.cpp
index 8c94564cac603288673ccfdaca05239b4f9e8989..ab6bf93645314511c8c71476f99e5c46de05bebb 100644
--- a/MantidQt/CustomDialogs/src/LoadDialog.cpp
+++ b/MantidQt/CustomDialogs/src/LoadDialog.cpp
@@ -20,374 +20,361 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include "MantidQtAPI/HelpWindow.h"
 
-namespace MantidQt
-{
-  namespace CustomDialogs
-  {
-    namespace
-    {
-      /// Holds a flag at a given value
-      /// and flips it back to its starting value on destruction
-      struct HoldFlag
-      {
-        HoldFlag(bool& current, const bool holdValue) : initial(current), heldflag(current)
-        {
-          heldflag = holdValue;
-        }
-        ~HoldFlag() { heldflag = initial; }
-        bool initial;
-        bool & heldflag;
-      };
-    }
-
-    // Declare the dialog. Name must match the class name
-    DECLARE_DIALOG(LoadDialog)
+namespace MantidQt {
+namespace CustomDialogs {
+namespace {
+/// Holds a flag at a given value
+/// and flips it back to its starting value on destruction
+struct HoldFlag {
+  HoldFlag(bool &current, const bool holdValue)
+      : initial(current), heldflag(current) {
+    heldflag = holdValue;
+  }
+  ~HoldFlag() { heldflag = initial; }
+  bool initial;
+  bool &heldflag;
+};
+}
 
-    //--------------------------------------------------------------------------
-    // Public methods
-    //---------------------------------------------------------------------------
+// Declare the dialog. Name must match the class name
+DECLARE_DIALOG(LoadDialog)
 
-    /// Default constructor
-    LoadDialog:: LoadDialog(QWidget *parent)
-      : API::AlgorithmDialog(parent), m_form(), m_currentFiles(), m_initialHeight(0),
-        m_populating(false)
-    {
-      // We will handle parsing the input ourselves on startup
-      m_autoParseOnInit = false;
-    }
+//--------------------------------------------------------------------------
+// Public methods
+//---------------------------------------------------------------------------
 
-    //--------------------------------------------------------------------------
-    // Private methods (slot)
-    //---------------------------------------------------------------------------
+/// Default constructor
+LoadDialog::LoadDialog(QWidget *parent)
+    : API::AlgorithmDialog(parent), m_form(), m_currentFiles(),
+      m_initialHeight(0), m_populating(false) {
+  // We will handle parsing the input ourselves on startup
+  m_autoParseOnInit = false;
+}
 
-    /**
-    * Activated when the file has been changed
-    */
-    void LoadDialog::createDynamicWidgets()
-    {
-      HoldFlag hold(m_populating, true);
+//--------------------------------------------------------------------------
+// Private methods (slot)
+//---------------------------------------------------------------------------
 
-      m_form.fileWidget->blockSignals(true);
-      createDynamicLayout();
-      m_form.fileWidget->blockSignals(false);
-    }
+/**
+* Activated when the file has been changed
+*/
+void LoadDialog::createDynamicWidgets() {
+  HoldFlag hold(m_populating, true);
 
-    /// Override the help button clicked method
-    void LoadDialog::helpClicked()
-    {
-      const std::string & loaderName = getAlgorithm()->getPropertyValue("LoaderName");
-      QString helpPage = (loaderName.empty()) ? QString("Load") : QString::fromStdString(loaderName);
-      MantidQt::API::HelpWindow::showAlgorithm(this->nativeParentWidget(), helpPage);
-    }
+  m_form.fileWidget->blockSignals(true);
+  createDynamicLayout();
+  m_form.fileWidget->blockSignals(false);
+}
 
-    /**
-    * Use property 'OutputWorkspace' as suggestion if present, otherwise derive a workspace name from 
-    * the file (base) name
-    */
-    void LoadDialog::suggestWSName()
-    {
-      if( !m_form.workspaceEdit->isEnabled() )
-        return;
-
-      // suggest ws name based on file name
-      QString fileSuggestion;
-      if( m_form.fileWidget->isValid() )
-      {
-        if( m_form.fileWidget->getFilenames().size() == 1 )
-          fileSuggestion = QFileInfo(m_form.fileWidget->getFirstFilename()).completeBaseName();
-        else
-          fileSuggestion = "MultiFiles";
-      }
-      m_form.workspaceEdit->setText(fileSuggestion);
-    }
+/// Override the help button clicked method
+void LoadDialog::helpClicked() {
+  const std::string &loaderName =
+      getAlgorithm()->getPropertyValue("LoaderName");
+  QString helpPage = (loaderName.empty()) ? QString("Load")
+                                          : QString::fromStdString(loaderName);
+  MantidQt::API::HelpWindow::showAlgorithm(this->nativeParentWidget(),
+                                           helpPage);
+}
 
-    /**
-    * Connect/Disconnect the signal that updates the workspace name with a suggested value
-    * @param on :: If true then a workspace name will be suggested
-    */
-    void LoadDialog::enableNameSuggestion(const bool on)
-    {
-      if( on )
-      {
-        connect(m_form.fileWidget, SIGNAL(filesFound()), this, SLOT(suggestWSName()));
-      }
-      else
-      {
-        disconnect(m_form.fileWidget, SIGNAL(filesFound()), this, SLOT(suggestWSName()));
-      }
-    }
+/**
+* Use property 'OutputWorkspace' as suggestion if present, otherwise derive a
+* workspace name from
+* the file (base) name
+*/
+void LoadDialog::suggestWSName() {
+  if (!m_form.workspaceEdit->isEnabled())
+    return;
+
+  // suggest ws name based on file name
+  QString fileSuggestion;
+  if (m_form.fileWidget->isValid()) {
+    if (m_form.fileWidget->getFilenames().size() == 1)
+      fileSuggestion =
+          QFileInfo(m_form.fileWidget->getFirstFilename()).completeBaseName();
+    else
+      fileSuggestion = "MultiFiles";
+  }
+  m_form.workspaceEdit->setText(fileSuggestion);
+}
 
-    /**
-     * Called when the run button is clicked
-     */
-    void LoadDialog::accept()
-    {
-      // The file widget may have been edited but not lost focus so that the search wasn't
-      // attempted for the new contents. Force one here.
-      // The widget does nothing if the contents have not changed so it will be quick for this case
-      m_form.fileWidget->findFiles();
-      while(m_form.fileWidget->isSearching() || m_populating)
-      {
-        QApplication::instance()->processEvents();
-      }
+/**
+* Connect/Disconnect the signal that updates the workspace name with a suggested
+* value
+* @param on :: If true then a workspace name will be suggested
+*/
+void LoadDialog::enableNameSuggestion(const bool on) {
+  if (on) {
+    connect(m_form.fileWidget, SIGNAL(filesFound()), this,
+            SLOT(suggestWSName()));
+  } else {
+    disconnect(m_form.fileWidget, SIGNAL(filesFound()), this,
+               SLOT(suggestWSName()));
+  }
+}
 
-      // Check that the file still exists just incase it somehow got removed
-      std::string errMess = getAlgorithm()->getPointerToProperty("Filename")->isValid();
-      if ( !errMess.empty() )
-      {
-        m_currentFiles = "";
-        createDynamicWidgets();
-        return;
-      }
-      AlgorithmDialog::accept();
-    }
+/**
+ * Called when the run button is clicked
+ */
+void LoadDialog::accept() {
+  // The file widget may have been edited but not lost focus so that the search
+  // wasn't
+  // attempted for the new contents. Force one here.
+  // The widget does nothing if the contents have not changed so it will be
+  // quick for this case
+  m_form.fileWidget->findFiles();
+  while (m_form.fileWidget->isSearching() || m_populating) {
+    QApplication::instance()->processEvents();
+  }
 
+  // Check that the file still exists just incase it somehow got removed
+  std::string errMess =
+      getAlgorithm()->getPointerToProperty("Filename")->isValid();
+  if (!errMess.empty()) {
+    m_currentFiles = "";
+    createDynamicWidgets();
+    return;
+  }
+  AlgorithmDialog::accept();
+}
 
-    //--------------------------------------------------------------------------
-    // Private methods (non-slot)
-    //---------------------------------------------------------------------------
+//--------------------------------------------------------------------------
+// Private methods (non-slot)
+//---------------------------------------------------------------------------
+
+/// Initialize the layout
+void LoadDialog::initLayout() {
+  m_form.setupUi(this);
+
+  // Add the helpful summary message
+  if (isMessageAvailable())
+    m_form.instructions->setText(getOptionalMessage());
+
+  m_form.dialogLayout->addLayout(this->createDefaultButtonLayout());
+  m_form.fileWidget->readSettings("Mantid/Algorithms/Load");
+  m_initialHeight = this->height();
+
+  const std::string &outWsName =
+      getAlgorithm()->getPropertyValue("OutputWorkspace");
+  if (!outWsName.empty()) {
+    // OutputWorkspace name suggestion received as parameter, just take it and
+    // don't change it
+    m_form.workspaceEdit->setText(QString::fromStdString(outWsName));
+  } else {
+    // Guess at an output workspace name but only if the user hasn't changed
+    // anything
+    enableNameSuggestion(true);
+    connect(m_form.workspaceEdit, SIGNAL(textEdited(const QString &)), this,
+            SLOT(enableNameSuggestion()));
+  }
 
-    /// Initialize the layout
-    void LoadDialog::initLayout()
-    {
-      m_form.setupUi(this);
+  // Connect the file finder's file found signal to the dynamic property create
+  // method.
+  // When the file text is set the Load algorithm finds the concrete loader and
+  // then we
+  // know what extra properties to create
+  connect(m_form.fileWidget, SIGNAL(filesFound()), this,
+          SLOT(createDynamicWidgets()));
+  tieStaticWidgets(true);
+}
 
-      // Add the helpful summary message
-      if(isMessageAvailable())
-        m_form.instructions->setText(getOptionalMessage());
+/**
+* Save the input after OK is clicked
+*/
+void LoadDialog::saveInput() {
+  m_form.fileWidget->saveSettings("Mantid/Algorithms/Load");
+  AlgorithmDialog::saveInput();
+  // Ensure the filename is store as the full file
+  API::AlgorithmInputHistory::Instance().storeNewValue(
+      "Load", QPair<QString, QString>("Filename", m_currentFiles));
+}
 
-      m_form.dialogLayout->addLayout(this->createDefaultButtonLayout());
-      m_form.fileWidget->readSettings("Mantid/Algorithms/Load");
-      m_initialHeight = this->height();
+/**
+* Tie static widgets to their properties
+* @param readHistory :: If true then the history will be re read.
+*/
+void LoadDialog::tieStaticWidgets(const bool readHistory) {
+  // If a workspace validator asterisk exists, remove it since the underlying
+  // AlgorithmDialog gets confused
+  if (m_form.workspaceLayout->count() == 3) {
+    QLayoutItem *validLbl = m_form.workspaceLayout->takeAt(2);
+    delete validLbl->widget();
+    delete validLbl;
+  }
+  tie(m_form.workspaceEdit, "OutputWorkspace", m_form.workspaceLayout,
+      readHistory);
+  tie(m_form.fileWidget, "Filename", NULL, readHistory);
+}
 
-      const std::string& outWsName = getAlgorithm()->getPropertyValue("OutputWorkspace");
-      if (!outWsName.empty())
-      {
-        // OutputWorkspace name suggestion received as parameter, just take it and don't change it
-        m_form.workspaceEdit->setText(QString::fromStdString(outWsName));
-      }
-      else
-      {
-        // Guess at an output workspace name but only if the user hasn't changed anything
-        enableNameSuggestion(true);
-        connect(m_form.workspaceEdit, SIGNAL(textEdited(const QString&)), this, SLOT(enableNameSuggestion()));
+/**
+* Clear the old widgets for a new Loader type
+* @param layout :: The layout containing the child layouts/widgets
+*/
+void LoadDialog::removeOldInputWidgets(QVBoxLayout *layout) {
+  // Remove the old widgets if necessary
+  if (layout->count() > 2) {
+    int count = layout->count();
+    while (count > 2) {
+      QLayoutItem *child = layout->takeAt(count - 1);
+      if (QWidget *w = child->widget()) {
+        w->deleteLater();
+      } else if (QLayout *l = child->layout()) {
+        QLayoutItem *subChild(NULL);
+        while ((subChild = l->takeAt(0)) != NULL) {
+          subChild->widget()->deleteLater();
+        }
       }
-
-      // Connect the file finder's file found signal to the dynamic property create method.
-      // When the file text is set the Load algorithm finds the concrete loader and then we
-      // know what extra properties to create
-      connect(m_form.fileWidget, SIGNAL(filesFound()), this, SLOT(createDynamicWidgets()));
-      tieStaticWidgets(true);
+      count = layout->count();
     }
+  }
+}
 
-    /**
-    * Save the input after OK is clicked
-    */
-    void LoadDialog::saveInput()
-    {
-      m_form.fileWidget->saveSettings("Mantid/Algorithms/Load");
-      AlgorithmDialog::saveInput();
-      //Ensure the filename is store as the full file
-      API::AlgorithmInputHistory::Instance().storeNewValue("Load",
-							   QPair<QString, QString>("Filename", m_currentFiles));
+/**
+* Create the dynamic widgets for the concrete loader
+*/
+void LoadDialog::createDynamicLayout() {
+  // Disable the layout so that a widget cannot be interacted with while it may
+  // be being deleted
+  m_form.propertyLayout->setEnabled(false);
+
+  using namespace Mantid::API;
+  using namespace Mantid::Kernel;
+
+  if (!m_form.fileWidget->isValid())
+    return;
+  // First step is the get the specific loader that is responsible
+  auto loadAlg = getAlgorithm();
+  const QString filenames = m_form.fileWidget->getUserInput().toString();
+  if (filenames == m_currentFiles)
+    return;
+  m_currentFiles = filenames;
+  removeOldInputWidgets(m_form.propertyLayout); // The new file might be invalid
+  try {
+    loadAlg->setPropertyValue("Filename", filenames.toStdString());
+  } catch (std::exception &exc) {
+    m_form.fileWidget->setFileProblem(QString::fromStdString(exc.what()));
+    m_form.propertyLayout->setEnabled(true);
+    m_form.propertyLayout->activate();
+    this->resize(this->width(), m_initialHeight + 15);
+
+    // Reset the algorithm pointer so that the base class re-reads the
+    // properties and drops links from
+    // old widgets meaning they are safe to remove
+    setAlgorithm(loadAlg);
+    tieStaticWidgets(false); // The ties are cleared when resetting the
+                             // algorithm
+
+    return;
+  }
+  // Reset the algorithm pointer so that the base class re-reads the properties
+  // and drops links from
+  // old widgets meaning they are safe to remove
+  setAlgorithm(loadAlg);
+  tieStaticWidgets(false); // The ties are cleared when resetting the algorithm
+  // Add the new ones
+  const std::vector<Property *> &inputProps = loadAlg->getProperties();
+  int dialogHeight = m_initialHeight;
+  for (size_t i = 0; i < inputProps.size(); ++i) {
+    const Property *prop = inputProps[i];
+    const QString propName = QString::fromStdString(prop->name());
+    if (propName == "OutputWorkspace" || propName == "Filename")
+      continue;
+    if (requiresUserInput(propName)) {
+      dialogHeight += createWidgetsForProperty(prop, m_form.propertyLayout,
+                                               m_form.scrollAreaWidgetContents);
     }
+  }
+  // Re-enable and recompute the size of the layout
+  m_form.propertyLayout->setEnabled(true);
+  m_form.propertyLayout->activate();
+
+  const int screenHeight = QApplication::desktop()->height();
+  // If the thing won't end up too big compared to the screen height,
+  // resize the scroll area so we don't get a scroll bar
+  if (dialogHeight < 0.8 * screenHeight)
+    this->resize(this->width(), dialogHeight + 20);
+
+  // Make sure the OutputWorkspace value has been stored so that the validator
+  // is cleared appropriately
+  QString wsName(m_form.workspaceEdit->text());
+  if (!wsName.isEmpty())
+    storePropertyValue("OutputWorkspace", wsName);
+  setPropertyValues(QStringList("Filename"));
+}
 
-    /**
-    * Tie static widgets to their properties
-    * @param readHistory :: If true then the history will be re read.
-    */
-    void LoadDialog::tieStaticWidgets(const bool readHistory)
-    {
-      // If a workspace validator asterisk exists, remove it since the underlying AlgorithmDialog gets confused
-      if( m_form.workspaceLayout->count() == 3 )
-      {
-        QLayoutItem *validLbl = m_form.workspaceLayout->takeAt(2);
-        delete validLbl->widget();
-        delete validLbl;
-      }
-      tie(m_form.workspaceEdit, "OutputWorkspace", m_form.workspaceLayout, readHistory);
-      tie(m_form.fileWidget, "Filename", NULL, readHistory);
+/**
+* Return a layout containing suitable widgets for the given property
+* @param prop A pointer to the algorithm property
+* @param propertyLayout A layout where the widgets are to be placed
+* @param parent The parent widget
+*/
+int LoadDialog::createWidgetsForProperty(const Mantid::Kernel::Property *prop,
+                                         QVBoxLayout *propertyLayout,
+                                         QWidget *parent) {
+  using namespace Mantid::API;
+  using namespace Mantid::Kernel;
+  using MantidQt::MantidWidgets::MWRunFiles;
+
+  QString propName = QString::fromStdString(prop->name());
+  QWidget *inputWidget(NULL);
+  QHBoxLayout *widgetLayout(NULL);
+  bool addValidator(true);
+
+  // Boolean properties use the name labels differently
+  if (const FileProperty *fileType = dynamic_cast<const FileProperty *>(prop)) {
+    MWRunFiles *fileFinder = new MWRunFiles(parent);
+    inputWidget = fileFinder;
+    fileFinder->setLabelText(propName);
+    fileFinder->isForRunFiles(false);
+    fileFinder->isOptional(fileType->isOptional());
+    fileFinder->doMultiEntry(false);
+    addValidator = false;
+    propertyLayout->addWidget(inputWidget);
+  } else {
+    QLabel *nameLbl = new QLabel(propName, parent);
+    nameLbl->setToolTip(QString::fromStdString(prop->briefDocumentation()));
+    if (dynamic_cast<const PropertyWithValue<bool> *>(prop)) {
+      QCheckBox *checkBox = new QCheckBox(parent);
+      inputWidget = checkBox;
+      addValidator = false;
     }
-
-    /**
-    * Clear the old widgets for a new Loader type
-    * @param layout :: The layout containing the child layouts/widgets
-    */
-    void LoadDialog::removeOldInputWidgets(QVBoxLayout *layout)
-    {
-      // Remove the old widgets if necessary
-      if( layout->count() > 2 )
-      {
-        int count = layout->count();
-        while( count > 2 )
-        {
-          QLayoutItem *child = layout->takeAt(count - 1);
-          if( QWidget *w = child->widget() )
-          {
-            w->deleteLater();
-          }
-          else if( QLayout *l = child->layout() )
-          {
-            QLayoutItem *subChild(NULL);
-            while( (subChild = l->takeAt(0)) != NULL )
-            {
-              subChild->widget()->deleteLater();
-            }
-          }
-          count = layout->count();
-        }
+    // Options box
+    else if (!prop->allowedValues().empty()) {
+      QComboBox *optionsBox = new QComboBox(parent);
+      inputWidget = optionsBox;
+      std::vector<std::string> items = prop->allowedValues();
+      std::vector<std::string>::const_iterator vend = items.end();
+      for (std::vector<std::string>::const_iterator vitr = items.begin();
+           vitr != vend; ++vitr) {
+        optionsBox->addItem(QString::fromStdString(*vitr));
       }
-    }
+      // Set current as visible
+      int index = optionsBox->findText(QString::fromStdString(prop->value()));
+      if (index >= 0)
+        optionsBox->setCurrentIndex(index);
 
-    /**
-    * Create the dynamic widgets for the concrete loader
-    */
-    void LoadDialog::createDynamicLayout()
-    {
-      // Disable the layout so that a widget cannot be interacted with while it may be being deleted
-      m_form.propertyLayout->setEnabled(false);
-
-      using namespace Mantid::API;
-      using namespace Mantid::Kernel;
-
-      if( !m_form.fileWidget->isValid() ) return;
-      // First step is the get the specific loader that is responsible
-      auto loadAlg = getAlgorithm();
-      const QString filenames = m_form.fileWidget->getUserInput().toString();
-      if( filenames == m_currentFiles ) return;
-      m_currentFiles = filenames;
-      removeOldInputWidgets(m_form.propertyLayout); // The new file might be invalid
-      try
-      {
-        loadAlg->setPropertyValue("Filename", filenames.toStdString());
-      }
-      catch(std::exception & exc)
-      {
-        m_form.fileWidget->setFileProblem(QString::fromStdString(exc.what()));
-        m_form.propertyLayout->setEnabled(true);
-        m_form.propertyLayout->activate();
-        this->resize(this->width(), m_initialHeight + 15);
-
-        // Reset the algorithm pointer so that the base class re-reads the properties and drops links from
-        // old widgets meaning they are safe to remove
-        setAlgorithm(loadAlg);
-        tieStaticWidgets(false); //The ties are cleared when resetting the algorithm
-
-        return;
-      }
-      // Reset the algorithm pointer so that the base class re-reads the properties and drops links from
-      // old widgets meaning they are safe to remove
-      setAlgorithm(loadAlg);
-      tieStaticWidgets(false); //The ties are cleared when resetting the algorithm
-      // Add the new ones
-      const std::vector<Property*> & inputProps = loadAlg->getProperties();
-      int dialogHeight = m_initialHeight;
-      for( size_t i = 0; i < inputProps.size(); ++i )
-      {
-        const Property* prop = inputProps[i];
-        const QString propName = QString::fromStdString(prop->name());
-        if( propName == "OutputWorkspace" || propName == "Filename" ) continue;
-        if( requiresUserInput(propName) )
-        {
-          dialogHeight += createWidgetsForProperty(prop, m_form.propertyLayout, m_form.scrollAreaWidgetContents);
-        }
-      }
-      // Re-enable and recompute the size of the layout
-      m_form.propertyLayout->setEnabled(true);
-      m_form.propertyLayout->activate();
-
-      const int screenHeight = QApplication::desktop()->height();
-      // If the thing won't end up too big compared to the screen height,
-      // resize the scroll area so we don't get a scroll bar
-      if ( dialogHeight < 0.8*screenHeight ) this->resize(this->width(),dialogHeight + 20);
-
-      // Make sure the OutputWorkspace value has been stored so that the validator is cleared appropriately
-      QString wsName(m_form.workspaceEdit->text());
-      if(!wsName.isEmpty()) storePropertyValue("OutputWorkspace",wsName);
-      setPropertyValues(QStringList("Filename"));
+      addValidator = false;
     }
-
-    /**
-    * Return a layout containing suitable widgets for the given property
-    * @param prop A pointer to the algorithm property
-    * @param propertyLayout A layout where the widgets are to be placed
-    * @param parent The parent widget
-    */
-    int LoadDialog::createWidgetsForProperty(const Mantid::Kernel::Property* prop,
-                                             QVBoxLayout *propertyLayout, QWidget *parent)
-    {
-      using namespace Mantid::API;
-      using namespace Mantid::Kernel;
-      using MantidQt::MantidWidgets::MWRunFiles;
-
-      QString propName = QString::fromStdString(prop->name());
-      QWidget *inputWidget(NULL);
-      QHBoxLayout *widgetLayout(NULL);
-      bool addValidator(true);
-
-      // Boolean properties use the name labels differently
-      if( const FileProperty* fileType = dynamic_cast<const FileProperty*>(prop) )
-      {
-        MWRunFiles *fileFinder = new MWRunFiles(parent);
-        inputWidget = fileFinder;
-        fileFinder->setLabelText(propName);
-        fileFinder->isForRunFiles(false);
-        fileFinder->isOptional(fileType->isOptional());
-        fileFinder->doMultiEntry(false);
-        addValidator = false;
-        propertyLayout->addWidget(inputWidget);
-      }
-      else
-      {
-        QLabel *nameLbl = new QLabel(propName, parent);
-        nameLbl->setToolTip(QString::fromStdString(prop->briefDocumentation()));
-        if( dynamic_cast<const PropertyWithValue<bool>* >(prop) )
-        {
-          QCheckBox *checkBox = new QCheckBox(parent);
-          inputWidget = checkBox;
-          addValidator = false;
-        }
-        // Options box
-        else if( !prop->allowedValues().empty() )
-        {
-          QComboBox *optionsBox = new QComboBox(parent);
-          inputWidget = optionsBox;
-          std::vector<std::string> items = prop->allowedValues();
-          std::vector<std::string>::const_iterator vend = items.end();
-          for(std::vector<std::string>::const_iterator vitr = items.begin(); vitr != vend;
-            ++vitr)
-          {
-            optionsBox->addItem(QString::fromStdString(*vitr));
-          }
-          // Set current as visible
-          int index = optionsBox->findText(QString::fromStdString(prop->value()));
-          if( index >= 0 ) optionsBox->setCurrentIndex(index);
-
-          addValidator = false;
-        }
-        // else render a text box
-        else
-        {
-          QLineEdit *textBox = new QLineEdit(parent);
-          inputWidget = textBox;
-          if( dynamic_cast<const MaskedProperty<std::string> *>(prop) )
-          {
-            textBox->setEchoMode(QLineEdit::Password);
-          }
-        }
-        nameLbl->setBuddy(inputWidget);
-        widgetLayout = new QHBoxLayout();
-        widgetLayout->addWidget(nameLbl);
-        widgetLayout->addWidget(inputWidget);
-        propertyLayout->addLayout(widgetLayout);
+    // else render a text box
+    else {
+      QLineEdit *textBox = new QLineEdit(parent);
+      inputWidget = textBox;
+      if (dynamic_cast<const MaskedProperty<std::string> *>(prop)) {
+        textBox->setEchoMode(QLineEdit::Password);
       }
-
-      if( addValidator ) tie(inputWidget, propName, widgetLayout);
-      else tie(inputWidget, propName, NULL);
-
-      return inputWidget->geometry().height();
     }
+    nameLbl->setBuddy(inputWidget);
+    widgetLayout = new QHBoxLayout();
+    widgetLayout->addWidget(nameLbl);
+    widgetLayout->addWidget(inputWidget);
+    propertyLayout->addLayout(widgetLayout);
+  }
 
+  if (addValidator)
+    tie(inputWidget, propName, widgetLayout);
+  else
+    tie(inputWidget, propName, NULL);
 
-  }
+  return inputWidget->geometry().height();
+}
+}
 }
diff --git a/MantidQt/CustomDialogs/src/LoadRawDialog.cpp b/MantidQt/CustomDialogs/src/LoadRawDialog.cpp
index 685a349fbdce70ab18e47a1929d5073ff8814b40..d5ba446b1934e6f2e53bc3e057125ef072affd77 100644
--- a/MantidQt/CustomDialogs/src/LoadRawDialog.cpp
+++ b/MantidQt/CustomDialogs/src/LoadRawDialog.cpp
@@ -17,16 +17,14 @@
 #include <QDir>
 #include <QCheckBox>
 
-//Add this class to the list of specialized dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-  DECLARE_DIALOG(LoadRawDialog)
+// Add this class to the list of specialized dialogs in this namespace
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(LoadRawDialog)
 }
 }
 
-// Just to save writing this everywhere 
+// Just to save writing this everywhere
 using namespace MantidQt::CustomDialogs;
 
 //---------------------------------------
@@ -35,17 +33,13 @@ using namespace MantidQt::CustomDialogs;
 /**
  * Constructor
  */
-LoadRawDialog::LoadRawDialog(QWidget *parent) : AlgorithmDialog(parent),
-  m_pathBox(NULL), m_wsBox(NULL)
-{
-}
+LoadRawDialog::LoadRawDialog(QWidget *parent)
+    : AlgorithmDialog(parent), m_pathBox(NULL), m_wsBox(NULL) {}
 
 /**
   *Destructor
   */
-LoadRawDialog::~LoadRawDialog()
-{	
-}
+LoadRawDialog::~LoadRawDialog() {}
 
 //---------------------------------------
 // Private member functions
@@ -53,51 +47,49 @@ LoadRawDialog::~LoadRawDialog()
 /**
  * Reimplemented virtual function to set up the dialog
  */
-void LoadRawDialog::initLayout()
-{
-  QVBoxLayout *main_layout = new QVBoxLayout(this);  
+void LoadRawDialog::initLayout() {
+  QVBoxLayout *main_layout = new QVBoxLayout(this);
 
   // Add the helpful summary message
-  if( isMessageAvailable() )
+  if (isMessageAvailable())
     this->addOptionalMessage(main_layout);
 
-  
   //------------- Filename property ---------------------
   QHBoxLayout *prop_line = new QHBoxLayout;
-  prop_line->addWidget(new QLabel("Select a file to load:"));  
+  prop_line->addWidget(new QLabel("Select a file to load:"));
 
   m_pathBox = new QLineEdit;
-  m_pathBox->setMinimumWidth(m_pathBox->fontMetrics().maxWidth()*13);
+  m_pathBox->setMinimumWidth(m_pathBox->fontMetrics().maxWidth() * 13);
   prop_line->addWidget(m_pathBox);
   tie(m_pathBox, "Filename", prop_line);
-  
+
   QPushButton *browseBtn = new QPushButton("Browse");
   connect(browseBtn, SIGNAL(clicked()), this, SLOT(browseClicked()));
   browseBtn->setEnabled(isWidgetEnabled("Filename"));
   prop_line->addWidget(browseBtn);
-  
-  main_layout->addLayout(prop_line); 
+
+  main_layout->addLayout(prop_line);
 
   //------------- OutputWorkspace property ---------------------
   m_wsBox = new QLineEdit;
 
   prop_line = new QHBoxLayout;
-  prop_line->addWidget(new QLabel("Enter name for workspace:"));  
+  prop_line->addWidget(new QLabel("Enter name for workspace:"));
   prop_line->addWidget(m_wsBox);
   tie(m_wsBox, "OutputWorkspace", prop_line);
   prop_line->addStretch();
-  main_layout->addLayout(prop_line); 
+  main_layout->addLayout(prop_line);
 
   //------------- Spectra properties ---------------------
   QGroupBox *groupbox = new QGroupBox("Spectra Options");
   prop_line = new QHBoxLayout;
-  
+
   QLineEdit *text_field = new QLineEdit;
   text_field->setMaximumWidth(m_wsBox->fontMetrics().width("888888"));
   prop_line->addWidget(new QLabel("Start:"));
   prop_line->addWidget(text_field);
   tie(text_field, "SpectrumMin", prop_line);
-  
+
   text_field = new QLineEdit;
   text_field->setMaximumWidth(m_wsBox->fontMetrics().width("888888"));
   prop_line->addWidget(new QLabel("End:"));
@@ -106,7 +98,7 @@ void LoadRawDialog::initLayout()
 
   text_field = new QLineEdit;
   prop_line->addWidget(new QLabel("List:"));
-  prop_line->addWidget(text_field); 
+  prop_line->addWidget(text_field);
   tie(text_field, "SpectrumList", prop_line);
 
   prop_line->addStretch();
@@ -117,23 +109,22 @@ void LoadRawDialog::initLayout()
   prop_line = new QHBoxLayout;
   text_field = new QLineEdit;
   prop_line->addWidget(new QLabel("Periods:"));
-  prop_line->addWidget(text_field); 
+  prop_line->addWidget(text_field);
   prop_line->addStretch();
   tie(text_field, "PeriodList", prop_line);
 
   main_layout->addLayout(prop_line);
-  
-  //------------- Cache option , log files options and Monitors Options ---------------------
-   
-  Mantid::Kernel::Property* cacheProp= getAlgorithmProperty("Cache");
-  if(cacheProp)
-  {
+
+  //------------- Cache option , log files options and Monitors Options
+  //---------------------
+
+  Mantid::Kernel::Property *cacheProp = getAlgorithmProperty("Cache");
+  if (cacheProp) {
     QComboBox *cacheBox = new QComboBox;
-    std::vector<std::string> items =cacheProp->allowedValues();
+    std::vector<std::string> items = cacheProp->allowedValues();
     std::vector<std::string>::const_iterator vend = items.end();
-    for(std::vector<std::string>::const_iterator vitr = items.begin(); vitr != vend; 
-        ++vitr)
-    {
+    for (std::vector<std::string>::const_iterator vitr = items.begin();
+         vitr != vend; ++vitr) {
       cacheBox->addItem(QString::fromStdString(*vitr));
     }
     prop_line = new QHBoxLayout;
@@ -143,57 +134,54 @@ void LoadRawDialog::initLayout()
   }
 
   prop_line->addStretch();
-  //If the algorithm version supports the LoadLog property add a check box for it
+  // If the algorithm version supports the LoadLog property add a check box for
+  // it
   Mantid::Kernel::Property *loadlogs = getAlgorithmProperty("LoadLogFiles");
-  if( loadlogs )
-  {   
-    QCheckBox *checkbox = new QCheckBox ("Load Log Files",this);
+  if (loadlogs) {
+    QCheckBox *checkbox = new QCheckBox("Load Log Files", this);
     prop_line->addWidget(checkbox);
     tie(checkbox, "LoadLogFiles", prop_line);
   }
-  prop_line->addStretch();  
-  //------------- If the algorithm version supports the LoadMonitors property add a check box for it ----
-  Mantid::Kernel::Property* loadMonitors=getAlgorithmProperty("LoadMonitors");
-  if(loadMonitors)
-  {
-    QComboBox *monitorsBox =new QComboBox;
-    std::vector<std::string> monitoritems =loadMonitors->allowedValues();
+  prop_line->addStretch();
+  //------------- If the algorithm version supports the LoadMonitors property
+  // add a check box for it ----
+  Mantid::Kernel::Property *loadMonitors = getAlgorithmProperty("LoadMonitors");
+  if (loadMonitors) {
+    QComboBox *monitorsBox = new QComboBox;
+    std::vector<std::string> monitoritems = loadMonitors->allowedValues();
     std::vector<std::string>::const_iterator mend = monitoritems.end();
-    for(std::vector<std::string>::const_iterator mitr = monitoritems.begin(); mitr != mend; 
-        ++mitr)
-    {
-        monitorsBox->addItem(QString::fromStdString(*mitr));
+    for (std::vector<std::string>::const_iterator mitr = monitoritems.begin();
+         mitr != mend; ++mitr) {
+      monitorsBox->addItem(QString::fromStdString(*mitr));
     }
     prop_line->addWidget(new QLabel("LoadMonitors:"), 0, Qt::AlignRight);
     prop_line->addWidget(monitorsBox);
     tie(monitorsBox, "LoadMonitors", prop_line);
   }
-  
-  
-  if(prop_line)main_layout->addLayout(prop_line);
-  
-  //Buttons 
+
+  if (prop_line)
+    main_layout->addLayout(prop_line);
+
+  // Buttons
   main_layout->addLayout(createDefaultButtonLayout("?", "Load", "Cancel"));
 }
 
-
 /**
   * A slot for the browse button "clicked" signal
   */
-void LoadRawDialog::browseClicked()
-{
-  if( !m_pathBox->text().isEmpty() )
-  {
-    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(m_pathBox->text()).absoluteDir().path());
-  }  
+void LoadRawDialog::browseClicked() {
+  if (!m_pathBox->text().isEmpty()) {
+    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(
+        QFileInfo(m_pathBox->text()).absoluteDir().path());
+  }
 
   QString filepath = this->openFileDialog("Filename");
-  if( !filepath.isEmpty() ) 
-  {
+  if (!filepath.isEmpty()) {
     m_pathBox->clear();
     m_pathBox->setText(filepath.trimmed());
   }
 
-  //Add a suggestion for workspace name
-  if( m_wsBox->isEnabled() && !filepath.isEmpty() ) m_wsBox->setText(QFileInfo(filepath).baseName());
+  // Add a suggestion for workspace name
+  if (m_wsBox->isEnabled() && !filepath.isEmpty())
+    m_wsBox->setText(QFileInfo(filepath).baseName());
 }
diff --git a/MantidQt/CustomDialogs/src/MantidGLWidget.cpp b/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
index ee4db7c25710964b641d90247e3ef9d2293fab53..d4e5a9579b50a91b4e1c3f44e46943232b8f3513 100644
--- a/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
+++ b/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
@@ -17,11 +17,12 @@ using namespace MantidQt::CustomDialogs;
 /**
  * Constructor
  */
-MantidGLWidget::MantidGLWidget(QWidget *parent) : 
-  QGLWidget(QGLFormat(QGL::DepthBuffer|QGL::NoAlphaChannel|QGL::SampleBuffers), parent), 
-  m_display_object(boost::shared_ptr<Mantid::Geometry::Object>()),
-  m_x_rot(0.0), m_y_rot(0.0), m_z_rot(0.0), m_scale_factor(1.0)
-{
+MantidGLWidget::MantidGLWidget(QWidget *parent)
+    : QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::NoAlphaChannel |
+                          QGL::SampleBuffers),
+                parent),
+      m_display_object(boost::shared_ptr<Mantid::Geometry::Object>()),
+      m_x_rot(0.0), m_y_rot(0.0), m_z_rot(0.0), m_scale_factor(1.0) {
   setAutoFillBackground(false);
   m_bb_widths[0] = 0.0;
   m_bb_widths[1] = 0.0;
@@ -35,34 +36,34 @@ MantidGLWidget::MantidGLWidget(QWidget *parent) :
 /**
  * Destructor
  */
-MantidGLWidget::~MantidGLWidget()
-{
-  makeCurrent();
-}
+MantidGLWidget::~MantidGLWidget() { makeCurrent(); }
 
 /**
  * Set the shape object
  * @param object :: A pointer to the Mantid::Geometry::Object
  */
-void MantidGLWidget::setDisplayObject(boost::shared_ptr<Mantid::Geometry::Object> object)
-{
+void MantidGLWidget::setDisplayObject(
+    boost::shared_ptr<Mantid::Geometry::Object> object) {
   m_display_object = object;
   m_x_rot = 0.0;
   m_y_rot = 0.0;
   m_z_rot = 0.0;
-  
+
   // Calculate a scale factor from the objects bounding box
-  // The bounding box function seems to require maxima to be set for each of 
+  // The bounding box function seems to require maxima to be set for each of
   // the numbers or else it returns rubbish
   // I'll set them to big numbers here
   const double bb_large(1e10);
-  double bbox[6] = { bb_large, bb_large, bb_large, -bb_large, -bb_large, -bb_large };
-  m_display_object->getBoundingBox(bbox[0], bbox[1], bbox[2], bbox[3], bbox[4], bbox[5]);
-
-  // The abs function kept casting my doubles to integers, hence the next two lines
-  //double max_bb = bbox[0];
-  //if( max_bb < 0. ) max_bb *=-1;
-  //for( int i = 1; i < 6; ++i )
+  double bbox[6] = {bb_large,  bb_large,  bb_large,
+                    -bb_large, -bb_large, -bb_large};
+  m_display_object->getBoundingBox(bbox[0], bbox[1], bbox[2], bbox[3], bbox[4],
+                                   bbox[5]);
+
+  // The abs function kept casting my doubles to integers, hence the next two
+  // lines
+  // double max_bb = bbox[0];
+  // if( max_bb < 0. ) max_bb *=-1;
+  // for( int i = 1; i < 6; ++i )
   //{
   //  double d = bbox[i];
   //  if( d < 0. ) d *= -1.;
@@ -71,29 +72,29 @@ void MantidGLWidget::setDisplayObject(boost::shared_ptr<Mantid::Geometry::Object
   //    max_bb = d;
   //  }
   //}
-//  m_min_bb *= 2.0; m_max_bb *= 2.0;
-  //std::cerr << "\n";
-  //Calculate the widths and save for resize events
-  for( int i = 0; i < 3; ++i )
-  {
-
-    //std::cerr << "Bounding box max:" << bbox[i] << "  min: " << bbox[i+3] << "\n"; 
-    m_bb_widths[i] = 1.1*(bbox[i] - bbox[i + 3]);
-    if( m_bb_widths[i] < 0.0 ) m_bb_widths[i] *= -1.0;
-    if( std::fabs(bbox[i]) < 1e10 && std::fabs(bbox[i+3]) < 1e10 )
-    {
+  //  m_min_bb *= 2.0; m_max_bb *= 2.0;
+  // std::cerr << "\n";
+  // Calculate the widths and save for resize events
+  for (int i = 0; i < 3; ++i) {
+
+    // std::cerr << "Bounding box max:" << bbox[i] << "  min: " << bbox[i+3] <<
+    // "\n";
+    m_bb_widths[i] = 1.1 * (bbox[i] - bbox[i + 3]);
+    if (m_bb_widths[i] < 0.0)
+      m_bb_widths[i] *= -1.0;
+    if (std::fabs(bbox[i]) < 1e10 && std::fabs(bbox[i + 3]) < 1e10) {
       m_bb_centres[i] = (bbox[i] + bbox[i + 3]) / 2.0;
-    }
-    else
-    {
+    } else {
       m_bb_centres[i] = 0.0;
     }
-    if( m_bb_centres[i] < 0.0 ) m_bb_centres[i] *= -1.0;
+    if (m_bb_centres[i] < 0.0)
+      m_bb_centres[i] *= -1.0;
   }
-  
-//  std::cerr << "centres: " << m_bb_centres[0] << " " << m_bb_centres[1] << " " << m_bb_centres[2] << "\n";
 
-  GLdouble aspect_ratio((GLdouble)this->width() / (GLdouble)this->height());
+  //  std::cerr << "centres: " << m_bb_centres[0] << " " << m_bb_centres[1] << "
+  //  " << m_bb_centres[2] << "\n";
+
+  GLdouble aspect_ratio((GLdouble) this->width() / (GLdouble) this->height());
   setOrthoProjectionMatrix(aspect_ratio);
 
   updateGL();
@@ -105,29 +106,33 @@ void MantidGLWidget::setDisplayObject(boost::shared_ptr<Mantid::Geometry::Object
 /**
  * Initialize the OpenGL display
  */
-void MantidGLWidget::initializeGL()
-{
-  // Without this the initial display draws random rubbish from the graphics memory
-  glClearColor(0.0,0.0,0.0, 0.0);
-  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
-  
-  setCursor(Qt::PointingHandCursor); // This is to set the initial window mouse cursor to Hand icon
-  glEnable(GL_DEPTH_TEST);           // Enable opengl depth test to render 3D object properly
-  glShadeModel(GL_SMOOTH);           // Shade model is smooth (expensive but looks pleasing)
-  glEnable(GL_LINE_SMOOTH);          // Set line should be drawn smoothly
-  
-  //glEnable(GL_NORMALIZE);
-
-  glEnable (GL_LIGHTING);            // Enable light
-  glEnable(GL_LIGHT0);               // Enable opengl first light
-  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);  // This model lits both sides of the triangle
-  //Set Light0 Attributes, Ambient, diffuse,specular and position
- //Its a directional light which follows camera position
+void MantidGLWidget::initializeGL() {
+  // Without this the initial display draws random rubbish from the graphics
+  // memory
+  glClearColor(0.0, 0.0, 0.0, 0.0);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+  setCursor(Qt::PointingHandCursor); // This is to set the initial window mouse
+                                     // cursor to Hand icon
+  glEnable(
+      GL_DEPTH_TEST); // Enable opengl depth test to render 3D object properly
+  glShadeModel(
+      GL_SMOOTH); // Shade model is smooth (expensive but looks pleasing)
+  glEnable(GL_LINE_SMOOTH); // Set line should be drawn smoothly
+
+  // glEnable(GL_NORMALIZE);
+
+  glEnable(GL_LIGHTING); // Enable light
+  glEnable(GL_LIGHT0);   // Enable opengl first light
+  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,
+                GL_TRUE); // This model lits both sides of the triangle
+  // Set Light0 Attributes, Ambient, diffuse,specular and position
+  // Its a directional light which follows camera position
   GLfloat lamp_ambient[4] = {0.40f, 0.0f, 1.0f, 0.0f};
   GLfloat lamp_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat lamp_specular[4] = {1.0f, 1.0f, 1.0f, 1.0f};
 
-  glLightfv(GL_LIGHT0, GL_AMBIENT,lamp_ambient );
+  glLightfv(GL_LIGHT0, GL_AMBIENT, lamp_ambient);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, lamp_diffuse);
   glLightfv(GL_LIGHT0, GL_SPECULAR, lamp_specular);
   GLfloat lamp_pos[4] = {0.0f, 0.0f, 1.0f, 0.0};
@@ -137,11 +142,11 @@ void MantidGLWidget::initializeGL()
 /**
  * Render the 3D scene
  */
-void MantidGLWidget::paintGL()
-{
+void MantidGLWidget::paintGL() {
   // Nothing to draw
-  if( m_display_object == boost::shared_ptr<Mantid::Geometry::Object>() ) return;
-  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
+  if (m_display_object == boost::shared_ptr<Mantid::Geometry::Object>())
+    return;
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
@@ -153,18 +158,15 @@ void MantidGLWidget::paintGL()
   glRotated(m_y_rot / 16.0, 0.0, 1.0, 0.0);
   glRotated(m_z_rot / 16.0, 0.0, 0.0, 1.0);
 
-
-  try 
-  {
+  try {
     m_display_object->draw();
+  } catch (...) {
+    QMessageBox::information(
+        this, "MantidGLWidget",
+        QString("An error occurred while attempting to render the shape.\n") +
+            "Please check that all objects intersect each other.");
   }
-  catch( ... )
-  {
-    QMessageBox::information(this,"MantidGLWidget", 
-			     QString("An error occurred while attempting to render the shape.\n") +
-			     "Please check that all objects intersect each other.");
-  }
-  glPopMatrix();  
+  glPopMatrix();
 }
 
 /**
@@ -172,12 +174,12 @@ void MantidGLWidget::paintGL()
  * @param width :: The width of the resized viewport
  * @param height :: The height of the resized viewport
  */
-void MantidGLWidget::resizeGL(int width, int height)
-{
+void MantidGLWidget::resizeGL(int width, int height) {
   glViewport(0, 0, (GLsizei)width, (GLsizei)height);
-  if( height == 0 ) height = 1;
+  if (height == 0)
+    height = 1;
 
-  GLdouble aspect_ratio = (GLdouble)width/(GLdouble)height;
+  GLdouble aspect_ratio = (GLdouble)width / (GLdouble)height;
   setOrthoProjectionMatrix(aspect_ratio);
 }
 
@@ -185,8 +187,7 @@ void MantidGLWidget::resizeGL(int width, int height)
  * Handle an event when a mouse button is pressed.
  * @param event A pointer to the QMouseEvent
  */
-void MantidGLWidget::mousePressEvent(QMouseEvent *event)
-{
+void MantidGLWidget::mousePressEvent(QMouseEvent *event) {
   m_click_point = event->pos();
 }
 
@@ -194,13 +195,12 @@ void MantidGLWidget::mousePressEvent(QMouseEvent *event)
  * Handle an event where the cursor is moved with the mouse
  * @param event A pointer to the QMouseEvent
  */
-void MantidGLWidget::mouseMoveEvent(QMouseEvent *event)
-{
+void MantidGLWidget::mouseMoveEvent(QMouseEvent *event) {
   int dx = event->x() - m_click_point.x();
   int dy = event->y() - m_click_point.y();
   // Points in Qt only have integer precision
   int x_rot = static_cast<int>(m_x_rot);
-  
+
   if (event->buttons() & Qt::LeftButton) {
     setXRotation(x_rot + 8 * dy);
     setYRotation(static_cast<int>(m_y_rot) + 8 * dx);
@@ -209,15 +209,13 @@ void MantidGLWidget::mouseMoveEvent(QMouseEvent *event)
     setZRotation(static_cast<int>(m_z_rot) + 8 * dx);
   }
   m_click_point = event->pos();
-
 }
 
 /**
  * Set the current rotation angle around the X-axis.
  * @param angle :: The angle of rotation
  */
-void MantidGLWidget::setXRotation(int angle)
-{
+void MantidGLWidget::setXRotation(int angle) {
   normalizeAngle(&angle);
   if (angle != m_x_rot) {
     m_x_rot = angle;
@@ -229,8 +227,7 @@ void MantidGLWidget::setXRotation(int angle)
  * Set the current rotation angle around the Y-axis.
  * @param angle :: The angle of rotation
  */
-void MantidGLWidget::setYRotation(int angle)
-{
+void MantidGLWidget::setYRotation(int angle) {
   normalizeAngle(&angle);
   if (angle != m_y_rot) {
     m_y_rot = angle;
@@ -242,8 +239,7 @@ void MantidGLWidget::setYRotation(int angle)
  * Set the current rotation angle around the Z-axis.
  * @param angle :: The angle of rotation
  */
-void MantidGLWidget::setZRotation(int angle)
-{
+void MantidGLWidget::setZRotation(int angle) {
   normalizeAngle(&angle);
   if (angle != m_z_rot) {
     m_z_rot = angle;
@@ -251,28 +247,25 @@ void MantidGLWidget::setZRotation(int angle)
   }
 }
 
-void MantidGLWidget::setOrthoProjectionMatrix(GLdouble aspect_ratio)
-{
-  GLdouble left = - m_bb_widths[0]/2.0;
-  GLdouble right = m_bb_widths[0]/2.0;
-  GLdouble bottom = - m_bb_widths[1]/2.0;
-  GLdouble top = + m_bb_widths[1]/2.0;
-  
-  //std::cerr << "Projection volume points: " << left << " " << right << " " << bottom << " " << top << std::endl;
+void MantidGLWidget::setOrthoProjectionMatrix(GLdouble aspect_ratio) {
+  GLdouble left = -m_bb_widths[0] / 2.0;
+  GLdouble right = m_bb_widths[0] / 2.0;
+  GLdouble bottom = -m_bb_widths[1] / 2.0;
+  GLdouble top = +m_bb_widths[1] / 2.0;
+
+  // std::cerr << "Projection volume points: " << left << " " << right << " " <<
+  // bottom << " " << top << std::endl;
 
   // width / height ratio in world coordinates must be equal to aspect_ratio
   auto ratio = m_bb_widths[0] / m_bb_widths[1];
 
-  if (ratio < aspect_ratio)
-  {
+  if (ratio < aspect_ratio) {
     auto width = m_bb_widths[1] * aspect_ratio;
-    left  = - width/2.0;
-    right = width/2.0;
-  }
-  else
-  {
+    left = -width / 2.0;
+    right = width / 2.0;
+  } else {
     auto height = m_bb_widths[0] / aspect_ratio;
-    bottom = - height / 2.0;
+    bottom = -height / 2.0;
     top = height / 2.0;
   }
 
@@ -281,24 +274,24 @@ void MantidGLWidget::setOrthoProjectionMatrix(GLdouble aspect_ratio)
   bottom += m_bb_centres[1];
   top += m_bb_centres[1];
 
-  //std::cerr << "Projection volume points 2: " << left << " " << right << " " << bottom << " " << top << std::endl;
-  //std::cerr << "Aspect ratio: " << aspect_ratio << " == " << (right - left) / (top - bottom) << std::endl;
+  // std::cerr << "Projection volume points 2: " << left << " " << right << " "
+  // << bottom << " " << top << std::endl;
+  // std::cerr << "Aspect ratio: " << aspect_ratio << " == " << (right - left) /
+  // (top - bottom) << std::endl;
 
-  // Set the correct projection 
+  // Set the correct projection
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glOrtho(left, right, bottom, top, -10.0, 10000.0);
   glMatrixMode(GL_MODELVIEW);
 }
-  
-  
-  /**
- * Adjust the angle given so that it is within the range 0 < x < (360 * 16)
- * (Note: The factor of 16 is due to Qt using angles in 1/16th of a degree)
- * @param angle :: The angle of rotation
- */
-void MantidGLWidget::normalizeAngle(int *angle)
-{
+
+/**
+*Adjust the angle given so that it is within the range 0 < x < (360 * 16)
+*(Note: The factor of 16 is due to Qt using angles in 1/16th of a degree)
+*@param angle :: The angle of rotation
+*/
+void MantidGLWidget::normalizeAngle(int *angle) {
   while (*angle < 0)
     *angle += 360 * 16;
   while (*angle > 360 * 16)
diff --git a/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp b/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp
index 90c10141607ed65f8c299f938ec887f6f561013f..4e597c62e2c5d8ad78657abe1e1f62c7f2f15ad9 100644
--- a/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp
+++ b/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp
@@ -20,17 +20,15 @@
 #include <QCheckBox>
 #include <QSignalMapper>
 
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-  DECLARE_DIALOG(PlotAsymmetryByLogValueDialog)
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(PlotAsymmetryByLogValueDialog)
 }
 }
 
 using namespace MantidQt::CustomDialogs;
-using namespace MantidQt::API; 
+using namespace MantidQt::API;
 
 //---------------------------------------
 // Public member functions
@@ -38,18 +36,18 @@ using namespace MantidQt::API;
 /**
  * Constructor
  */
-PlotAsymmetryByLogValueDialog::PlotAsymmetryByLogValueDialog(QWidget *parent) : AlgorithmDialog(parent)
-{
+PlotAsymmetryByLogValueDialog::PlotAsymmetryByLogValueDialog(QWidget *parent)
+    : AlgorithmDialog(parent) {
   browseButtonMapper = new QSignalMapper();
 
-  connect(browseButtonMapper, SIGNAL(mapped(const QString&)), this, SLOT(openFileDialog(const QString&)));
+  connect(browseButtonMapper, SIGNAL(mapped(const QString &)), this,
+          SLOT(openFileDialog(const QString &)));
 }
 
 /**
   *Destructor
   */
-PlotAsymmetryByLogValueDialog::~PlotAsymmetryByLogValueDialog()
-{	
+PlotAsymmetryByLogValueDialog::~PlotAsymmetryByLogValueDialog() {
   delete browseButtonMapper;
 }
 
@@ -59,8 +57,7 @@ PlotAsymmetryByLogValueDialog::~PlotAsymmetryByLogValueDialog()
 /**
  * Reimplemented virtual function to set up the dialog
  */
-void PlotAsymmetryByLogValueDialog::initLayout()
-{
+void PlotAsymmetryByLogValueDialog::initLayout() {
   m_uiForm.setupUi(this);
 
   // Tie all the properties
@@ -81,17 +78,23 @@ void PlotAsymmetryByLogValueDialog::initLayout()
 
   // Set-up browse button mapping
   browseButtonMapper->setMapping(m_uiForm.browseFirstButton, "FirstRun");
-  browseButtonMapper->setMapping(m_uiForm.browseLastButton,  "LastRun");
-  browseButtonMapper->setMapping(m_uiForm.dtcFileBrowseButton, "DeadTimeCorrFile");
+  browseButtonMapper->setMapping(m_uiForm.browseLastButton, "LastRun");
+  browseButtonMapper->setMapping(m_uiForm.dtcFileBrowseButton,
+                                 "DeadTimeCorrFile");
 
   // Connect Browse buttons to the mapper
-  connect(m_uiForm.browseFirstButton, SIGNAL(clicked()), browseButtonMapper, SLOT(map()));
-  connect(m_uiForm.browseLastButton, SIGNAL(clicked()), browseButtonMapper, SLOT(map()));
-  connect(m_uiForm.dtcFileBrowseButton, SIGNAL(clicked()), browseButtonMapper, SLOT(map()));
+  connect(m_uiForm.browseFirstButton, SIGNAL(clicked()), browseButtonMapper,
+          SLOT(map()));
+  connect(m_uiForm.browseLastButton, SIGNAL(clicked()), browseButtonMapper,
+          SLOT(map()));
+  connect(m_uiForm.dtcFileBrowseButton, SIGNAL(clicked()), browseButtonMapper,
+          SLOT(map()));
 
-  connect( m_uiForm.firstRunBox, SIGNAL(textChanged(const QString&)), this, SLOT(fillLogBox(const QString&)) );
+  connect(m_uiForm.firstRunBox, SIGNAL(textChanged(const QString &)), this,
+          SLOT(fillLogBox(const QString &)));
 
-  connect( m_uiForm.dtcType, SIGNAL(currentIndexChanged(int)), this, SLOT(showHideDeadTimeFileWidget(int)));
+  connect(m_uiForm.dtcType, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(showHideDeadTimeFileWidget(int)));
 
   // Fill ComboBoxes with allowed values
   fillAndSetComboBox("Type", m_uiForm.typeBox);
@@ -99,7 +102,7 @@ void PlotAsymmetryByLogValueDialog::initLayout()
   fillAndSetComboBox("DeadTimeCorrType", m_uiForm.dtcType);
 
   // Fill log values from the file
-  if ( !m_uiForm.firstRunBox->text().isEmpty() )
+  if (!m_uiForm.firstRunBox->text().isEmpty())
     fillLogBox(m_uiForm.firstRunBox->text());
 
   // So user can enter a custom value
@@ -110,21 +113,23 @@ void PlotAsymmetryByLogValueDialog::initLayout()
 }
 
 /**
- * Opens a file dialog. Updates the QLineEdit provided when the dialog is closed.
+ * Opens a file dialog. Updates the QLineEdit provided when the dialog is
+ * closed.
  */
-void PlotAsymmetryByLogValueDialog::openFileDialog(const QString& filePropName)
-{
+void PlotAsymmetryByLogValueDialog::openFileDialog(
+    const QString &filePropName) {
   QString selectedPath = AlgorithmDialog::openFileDialog(filePropName);
 
-  if(!selectedPath.isEmpty())
-  {
+  if (!selectedPath.isEmpty()) {
     // Save used directory for the next time
-    AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(selectedPath).absoluteDir().path());
+    AlgorithmInputHistory::Instance().setPreviousDirectory(
+        QFileInfo(selectedPath).absoluteDir().path());
 
     // Get the widget for the file property
-    QLineEdit* lineEdit = dynamic_cast<QLineEdit*>(m_tied_properties[filePropName]);
+    QLineEdit *lineEdit =
+        dynamic_cast<QLineEdit *>(m_tied_properties[filePropName]);
 
-    if(!lineEdit)
+    if (!lineEdit)
       throw std::runtime_error("Widget of the file property was not found");
 
     lineEdit->setText(selectedPath.trimmed());
@@ -132,89 +137,87 @@ void PlotAsymmetryByLogValueDialog::openFileDialog(const QString& filePropName)
 }
 
 /**
- * Fill m_uiForm.logBox with names of the log values read from one of the input files
+ * Fill m_uiForm.logBox with names of the log values read from one of the input
+ * files
  */
-void PlotAsymmetryByLogValueDialog::fillLogBox(const QString&)
-{
+void PlotAsymmetryByLogValueDialog::fillLogBox(const QString &) {
   QString nexusFileName = m_uiForm.firstRunBox->text();
   QFileInfo file(nexusFileName);
-  if (!file.exists())
-  {
+  if (!file.exists()) {
     return;
   }
 
   m_uiForm.logBox->clear();
 
-  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmFactory::Instance().create("LoadMuonNexus",-1);
+  Mantid::API::IAlgorithm_sptr alg =
+      Mantid::API::AlgorithmFactory::Instance().create("LoadMuonNexus", -1);
   alg->initialize();
-  try
-  {
-    alg->setPropertyValue("Filename",nexusFileName.toStdString());
-    alg->setPropertyValue("OutputWorkspace","PlotAsymmetryByLogValueDialog_tmp");
-    alg->setPropertyValue("SpectrumList","1"); // Need to load at least one spectrum
+  try {
+    alg->setPropertyValue("Filename", nexusFileName.toStdString());
+    alg->setPropertyValue("OutputWorkspace",
+                          "PlotAsymmetryByLogValueDialog_tmp");
+    alg->setPropertyValue("SpectrumList",
+                          "1"); // Need to load at least one spectrum
     alg->execute();
-    if (alg->isExecuted())
-    {
+    if (alg->isExecuted()) {
       std::string wsName = alg->getPropertyValue("OutputWorkspace");
-      Mantid::API::Workspace_sptr ws = Mantid::API::AnalysisDataService::Instance().retrieve(wsName);
-      if ( !ws )
-      {
+      Mantid::API::Workspace_sptr ws =
+          Mantid::API::AnalysisDataService::Instance().retrieve(wsName);
+      if (!ws) {
         return;
       }
-      Mantid::API::MatrixWorkspace_sptr mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws);
-      Mantid::API::WorkspaceGroup_sptr gws = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws);
-      if (gws)
-      {
-        if (gws->getNumberOfEntries() < 2) return;
+      Mantid::API::MatrixWorkspace_sptr mws =
+          boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws);
+      Mantid::API::WorkspaceGroup_sptr gws =
+          boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws);
+      if (gws) {
+        if (gws->getNumberOfEntries() < 2)
+          return;
         mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-          Mantid::API::AnalysisDataService::Instance().retrieve(gws->getNames()[1])
-        );
+            Mantid::API::AnalysisDataService::Instance().retrieve(
+                gws->getNames()[1]));
       }
-      const std::vector< Mantid::Kernel::Property* >& props = mws->run().getLogData();
-      if (gws)
-      {
+      const std::vector<Mantid::Kernel::Property *> &props =
+          mws->run().getLogData();
+      if (gws) {
         std::vector<std::string> wsNames = gws->getNames();
-        for(std::vector<std::string>::iterator it=wsNames.begin();it!=wsNames.end();++it)
-        {
+        for (std::vector<std::string>::iterator it = wsNames.begin();
+             it != wsNames.end(); ++it) {
           Mantid::API::AnalysisDataService::Instance().remove(*it);
         }
+      } else {
+        Mantid::API::AnalysisDataService::Instance().remove(
+            "PlotAsymmetryByLogValueDialog_tmp");
       }
-      else
-      {
-        Mantid::API::AnalysisDataService::Instance().remove("PlotAsymmetryByLogValueDialog_tmp");
-      }
-      for(size_t i=0;i<props.size();i++)
-      {
+      for (size_t i = 0; i < props.size(); i++) {
         m_uiForm.logBox->addItem(QString::fromStdString(props[i]->name()));
       }
       // Display the appropriate value
       QString displayed("");
-      if( !isForScript() )
-      {
-        displayed = MantidQt::API::AlgorithmInputHistory::Instance().previousInput("PlotAsymmetryByLogValue", "LogValue");
+      if (!isForScript()) {
+        displayed =
+            MantidQt::API::AlgorithmInputHistory::Instance().previousInput(
+                "PlotAsymmetryByLogValue", "LogValue");
       }
-      if( !displayed.isEmpty() )
-      {
+      if (!displayed.isEmpty()) {
         int index = m_uiForm.logBox->findText(displayed);
-        if( index >= 0 )
-        {
+        if (index >= 0) {
           m_uiForm.logBox->setCurrentIndex(index);
         }
       }
     }
-    
-  }
-  catch(std::exception& )
-  {
+
+  } catch (std::exception &) {
   }
 }
 
 /**
- * Show or hide Dead Time file widget depending on which Dead Time type is selected.
+ * Show or hide Dead Time file widget depending on which Dead Time type is
+ * selected.
  * @param deadTimeTypeIndex Selected Dead Time Correction type index
  */
-void PlotAsymmetryByLogValueDialog::showHideDeadTimeFileWidget(int deadTimeTypeIndex)
-{
+void PlotAsymmetryByLogValueDialog::showHideDeadTimeFileWidget(
+    int deadTimeTypeIndex) {
   // Show only if "Using specified file" selected
   m_uiForm.dtcFileContainer->setVisible(deadTimeTypeIndex == 2);
 }
diff --git a/MantidQt/CustomDialogs/src/SampleShapeHelpers.cpp b/MantidQt/CustomDialogs/src/SampleShapeHelpers.cpp
index 4d58cfc22c24a4a7c632434aee819f235d8a4b56..ec469a02eac3ec183c228a226f1177f9cfe65c1e 100644
--- a/MantidQt/CustomDialogs/src/SampleShapeHelpers.cpp
+++ b/MantidQt/CustomDialogs/src/SampleShapeHelpers.cpp
@@ -15,10 +15,9 @@ using namespace MantidQt::CustomDialogs;
 //         PointGroupBox helper class
 //--------------------------------------------------------//
 
-PointGroupBox::PointGroupBox(QWidget* parent) : QGroupBox(parent), m_icoord(0)
-{
+PointGroupBox::PointGroupBox(QWidget *parent) : QGroupBox(parent), m_icoord(0) {
   QGridLayout *grid = new QGridLayout;
-  
+
   // The line edit fields
   m_midx = new QLineEdit;
   m_midy = new QLineEdit;
@@ -40,18 +39,18 @@ PointGroupBox::PointGroupBox(QWidget* parent) : QGroupBox(parent), m_icoord(0)
   grid->addWidget(m_cartesian, row, 0, 1, 2);
   grid->addWidget(m_spherical, row, 2, 1, 2);
   ++row;
-  //labels
+  // labels
   m_xlabel = new QLabel("x: ");
   m_ylabel = new QLabel("y: ");
   m_zlabel = new QLabel("z: ");
-  
+
   // x
   grid->addWidget(m_xlabel, row, 0, Qt::AlignRight);
   grid->addWidget(m_midx, row, 1);
   grid->addWidget(m_xunits, row, 2);
   ++row;
   // y
-  grid->addWidget(m_ylabel, row, 0);//, Qt::AlignRight);
+  grid->addWidget(m_ylabel, row, 0); //, Qt::AlignRight);
   grid->addWidget(m_midy, row, 1);
   grid->addWidget(m_yunits, row, 2);
   ++row;
@@ -59,14 +58,14 @@ PointGroupBox::PointGroupBox(QWidget* parent) : QGroupBox(parent), m_icoord(0)
   grid->addWidget(m_zlabel, row, 0, Qt::AlignRight);
   grid->addWidget(m_midz, row, 1);
   grid->addWidget(m_zunits, row, 2);
-  
+
   setLayout(grid);
 }
 
 // Switch to cartesian coordinates
-void PointGroupBox::changeToCartesian()
-{
-  if( m_icoord == 0 ) return;
+void PointGroupBox::changeToCartesian() {
+  if (m_icoord == 0)
+    return;
 
   m_xlabel->setText("x: ");
   m_ylabel->setText("y: ");
@@ -81,15 +80,15 @@ void PointGroupBox::changeToCartesian()
 }
 
 // Switch to spherical coordinates
-void PointGroupBox::changeToSpherical()
-{
-  if( m_icoord == 1 ) return;
+void PointGroupBox::changeToSpherical() {
+  if (m_icoord == 1)
+    return;
 
   m_xlabel->setText("r: ");
   m_ylabel->setText("theta: ");
   m_zlabel->setText("phi: ");
 
-  //Units are in degrees for theta and phi
+  // Units are in degrees for theta and phi
   m_yunits->setItemText(0, "deg");
   m_zunits->setItemText(0, "deg");
   m_yunits->setEnabled(false);
@@ -102,43 +101,35 @@ void PointGroupBox::changeToSpherical()
  * Write the element tag for a 3D point.
  * elem_name The name of the element
  */
-QString PointGroupBox::write3DElement(const QString & elem_name) const
-{
+QString PointGroupBox::write3DElement(const QString &elem_name) const {
   QString valx("0.0"), valy("0.0"), valz("0.0");
-  if( !m_midx->text().isEmpty() )
-  {
-    valx = ShapeDetails::convertToMetres(m_midx->text(), ShapeDetails::Unit(m_xunits->currentIndex()));
+  if (!m_midx->text().isEmpty()) {
+    valx = ShapeDetails::convertToMetres(
+        m_midx->text(), ShapeDetails::Unit(m_xunits->currentIndex()));
   }
-  if( !m_midy->text().isEmpty() )
-  {
-    if( m_icoord == 0 )
-    {
-      valy = ShapeDetails::convertToMetres(m_midy->text(), ShapeDetails::Unit(m_yunits->currentIndex()));
-    }
-    else 
-    {
+  if (!m_midy->text().isEmpty()) {
+    if (m_icoord == 0) {
+      valy = ShapeDetails::convertToMetres(
+          m_midy->text(), ShapeDetails::Unit(m_yunits->currentIndex()));
+    } else {
       valy = m_midy->text();
-    }      
-  }
-  if( !m_midz->text().isEmpty() )
-  {
-    if( m_icoord == 0 )
-    {
-      valz = ShapeDetails::convertToMetres(m_midz->text(), ShapeDetails::Unit(m_zunits->currentIndex()));
     }
-    else 
-    {
+  }
+  if (!m_midz->text().isEmpty()) {
+    if (m_icoord == 0) {
+      valz = ShapeDetails::convertToMetres(
+          m_midz->text(), ShapeDetails::Unit(m_zunits->currentIndex()));
+    } else {
       valz = m_midz->text();
-    }      
+    }
   }
   QString tag;
-  if( m_icoord == 0 )
-  {
-    tag = "<" + elem_name + " x=\"" + valx + "\" y=\"" + valy + "\" z= \"" + valz + "\" />\n";
-  }
-  else
-  {
-    tag = "<" + elem_name + " r=\"" + valx + "\" t=\"" + valy + "\" p= \"" + valz + "\" />\n";
+  if (m_icoord == 0) {
+    tag = "<" + elem_name + " x=\"" + valx + "\" y=\"" + valy + "\" z= \"" +
+          valz + "\" />\n";
+  } else {
+    tag = "<" + elem_name + " r=\"" + valx + "\" t=\"" + valy + "\" p= \"" +
+          valz + "\" />\n";
   }
   return tag;
 }
@@ -153,21 +144,19 @@ QString PointGroupBox::write3DElement(const QString & elem_name) const
  * @param right Right-hand side of binary operation
  * @returns A string representing the result of the operation on the arguments
  */
-QString Operation::toString(QString left, QString right) const
-{
+QString Operation::toString(QString left, QString right) const {
   QString result;
-  switch( binaryop )
-  {
+  switch (binaryop) {
   // union
   case 1:
-   result = left + ":" + right;
+    result = left + ":" + right;
     break;
   // difference (intersection of the complement)
   case 2:
     result = left + " (# " + right + ")";
     break;
   // intersection
-  case 0: 
+  case 0:
   default:
     result = left + " " + right;
     break;
@@ -181,11 +170,11 @@ QString Operation::toString(QString left, QString right) const
 /**
  * Create a QComboBox filled with length units (static)
  */
-QComboBox* ShapeDetails::createLengthUnitsCombo()
-{
+QComboBox *ShapeDetails::createLengthUnitsCombo() {
   QComboBox *units = new QComboBox;
   QStringList unit_labels("mm");
-  unit_labels << "cm" << "m";
+  unit_labels << "cm"
+              << "m";
   units->addItems(unit_labels);
   return units;
 }
@@ -195,18 +184,16 @@ QComboBox* ShapeDetails::createLengthUnitsCombo()
  * @param start_unit :: Initial unit
  * @returns A new string value in metres
  */
-QString ShapeDetails::convertToMetres(const QString & value, Unit start_unit)
-{
+QString ShapeDetails::convertToMetres(const QString &value, Unit start_unit) {
   QString converted;
-  switch( start_unit )
-  {
-  case ShapeDetails::centimetre: 
+  switch (start_unit) {
+  case ShapeDetails::centimetre:
     converted = QString::number(value.toDouble() / 100.0);
     break;
-  case ShapeDetails::millimetre: 
+  case ShapeDetails::millimetre:
     converted = QString::number(value.toDouble() / 1000.0);
     break;
-  default: 
+  default:
     converted = value;
   }
   return converted;
@@ -216,35 +203,28 @@ QString ShapeDetails::convertToMetres(const QString & value, Unit start_unit)
  * Set the complement flag
  * @param flag :: The value of the flag
  */
-void ShapeDetails::setComplementFlag(bool flag)
-{
-  m_isComplement = flag;
-}
+void ShapeDetails::setComplementFlag(bool flag) { m_isComplement = flag; }
 
 /**
  * Get the complement flag
  * @returns The value of the complement flag
  */
-bool ShapeDetails::getComplementFlag() const
-{
-  return m_isComplement;
-}
+bool ShapeDetails::getComplementFlag() const { return m_isComplement; }
 
 //--------------------------------------------//
-//                Sphere 
+//                Sphere
 //--------------------------------------------//
 /// Static counter
 int SphereDetails::g_nspheres = 0;
 
 /// Default constructor
-SphereDetails::SphereDetails(QWidget *parent) : ShapeDetails(parent)
-{
-  //Update number of sphere objects and the set the ID of this one
+SphereDetails::SphereDetails(QWidget *parent) : ShapeDetails(parent) {
+  // Update number of sphere objects and the set the ID of this one
   ++g_nspheres;
   m_idvalue = "sphere_" + QString::number(g_nspheres);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //radius
+  // radius
   m_radius_box = new QLineEdit;
   m_runits = createLengthUnitsCombo();
   QHBoxLayout *rad_layout = new QHBoxLayout;
@@ -254,7 +234,7 @@ SphereDetails::SphereDetails(QWidget *parent) : ShapeDetails(parent)
 
   m_centre = new PointGroupBox;
   m_centre->setTitle("Centre");
-  
+
   main_layout->addLayout(rad_layout);
   main_layout->addWidget(m_centre);
 }
@@ -262,17 +242,16 @@ SphereDetails::SphereDetails(QWidget *parent) : ShapeDetails(parent)
 /**
  * Write the XML definition
  */
-QString SphereDetails::writeXML() const
-{
+QString SphereDetails::writeXML() const {
   QString valr("0.0");
-  if( !m_radius_box->text().isEmpty() )
-  {
-    valr = convertToMetres(m_radius_box->text(), ShapeDetails::Unit(m_runits->currentIndex()));
+  if (!m_radius_box->text().isEmpty()) {
+    valr = convertToMetres(m_radius_box->text(),
+                           ShapeDetails::Unit(m_runits->currentIndex()));
   }
-  QString xmldef = 
-    "<sphere id=\"" + m_idvalue + "\">\n" + m_centre->write3DElement("centre") +
-    "<radius val=\"" + valr + "\" />\n"
-    "</sphere>\n";
+  QString xmldef = "<sphere id=\"" + m_idvalue + "\">\n" +
+                   m_centre->write3DElement("centre") + "<radius val=\"" +
+                   valr + "\" />\n"
+                          "</sphere>\n";
   return xmldef;
 }
 
@@ -283,14 +262,13 @@ QString SphereDetails::writeXML() const
 int CylinderDetails::g_ncylinders = 0;
 
 /// Default constructor
-CylinderDetails::CylinderDetails(QWidget *parent) : ShapeDetails(parent)
-{
+CylinderDetails::CylinderDetails(QWidget *parent) : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ncylinders;
   m_idvalue = "cylinder_" + QString::number(g_ncylinders);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //radius
+  // radius
   m_radius_box = new QLineEdit;
   m_runits = createLengthUnitsCombo();
   QHBoxLayout *rad_layout = new QHBoxLayout;
@@ -298,7 +276,7 @@ CylinderDetails::CylinderDetails(QWidget *parent) : ShapeDetails(parent)
   rad_layout->addWidget(m_radius_box);
   rad_layout->addWidget(m_runits);
 
-  //height
+  // height
   m_height_box = new QLineEdit;
   m_hunits = createLengthUnitsCombo();
   QHBoxLayout *hgt_layout = new QHBoxLayout;
@@ -306,13 +284,13 @@ CylinderDetails::CylinderDetails(QWidget *parent) : ShapeDetails(parent)
   hgt_layout->addWidget(m_height_box);
   hgt_layout->addWidget(m_hunits);
 
-  //Point boxes
+  // Point boxes
   m_lower_centre = new PointGroupBox;
   m_lower_centre->setTitle("Bottom Base Centre");
 
   m_axis = new PointGroupBox;
   m_axis->setTitle("Axis");
-  
+
   main_layout->addLayout(rad_layout);
   main_layout->addLayout(hgt_layout);
   main_layout->addWidget(m_lower_centre);
@@ -322,24 +300,23 @@ CylinderDetails::CylinderDetails(QWidget *parent) : ShapeDetails(parent)
 /**
  * Write the XML definition
  */
-QString CylinderDetails::writeXML() const
-{
+QString CylinderDetails::writeXML() const {
   QString valr("0.0"), valh("0.0");
-  if( !m_radius_box->text().isEmpty() )
-  {
-    valr = convertToMetres(m_radius_box->text(), ShapeDetails::Unit(m_runits->currentIndex()));
+  if (!m_radius_box->text().isEmpty()) {
+    valr = convertToMetres(m_radius_box->text(),
+                           ShapeDetails::Unit(m_runits->currentIndex()));
   }
-  if( !m_height_box->text().isEmpty() )
-  {
-    valh = convertToMetres(m_height_box->text(), ShapeDetails::Unit(m_hunits->currentIndex()));
+  if (!m_height_box->text().isEmpty()) {
+    valh = convertToMetres(m_height_box->text(),
+                           ShapeDetails::Unit(m_hunits->currentIndex()));
   }
-  QString xmldef = 
-    "<cylinder id=\"" + m_idvalue + "\" >\n"
-    "<radius val=\"" + valr + "\" />\n"
-    "<height val=\"" + valh + "\" />\n" + 
-    m_lower_centre->write3DElement("centre-of-bottom-base") +
-    m_axis->write3DElement("axis") +
-    "</cylinder>\n";
+  QString xmldef = "<cylinder id=\"" + m_idvalue + "\" >\n"
+                                                   "<radius val=\"" +
+                   valr + "\" />\n"
+                          "<height val=\"" +
+                   valh + "\" />\n" +
+                   m_lower_centre->write3DElement("centre-of-bottom-base") +
+                   m_axis->write3DElement("axis") + "</cylinder>\n";
   return xmldef;
 }
 
@@ -350,14 +327,14 @@ QString CylinderDetails::writeXML() const
 int InfiniteCylinderDetails::g_ninfcyls = 0;
 
 /// Default constructor
-InfiniteCylinderDetails::InfiniteCylinderDetails(QWidget *parent) : ShapeDetails(parent)
-{
+InfiniteCylinderDetails::InfiniteCylinderDetails(QWidget *parent)
+    : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ninfcyls;
   m_idvalue = "infcyl_" + QString::number(g_ninfcyls);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //radius
+  // radius
   m_radius_box = new QLineEdit;
   m_runits = createLengthUnitsCombo();
   QHBoxLayout *rad_layout = new QHBoxLayout;
@@ -365,13 +342,13 @@ InfiniteCylinderDetails::InfiniteCylinderDetails(QWidget *parent) : ShapeDetails
   rad_layout->addWidget(m_radius_box);
   rad_layout->addWidget(m_runits);
 
-  //Point boxes
+  // Point boxes
   m_centre = new PointGroupBox;
   m_centre->setTitle("Centre");
 
   m_axis = new PointGroupBox;
   m_axis->setTitle("Axis");
-  
+
   main_layout->addLayout(rad_layout);
   main_layout->addWidget(m_centre);
   main_layout->addWidget(m_axis);
@@ -380,19 +357,16 @@ InfiniteCylinderDetails::InfiniteCylinderDetails(QWidget *parent) : ShapeDetails
 /**
  * Write the XML definition
  */
-QString InfiniteCylinderDetails::writeXML() const
-{
+QString InfiniteCylinderDetails::writeXML() const {
   QString valr("0.0");
-  if( !m_radius_box->text().isEmpty() )
-  {
-    valr = convertToMetres(m_radius_box->text(), ShapeDetails::Unit(m_runits->currentIndex()));
+  if (!m_radius_box->text().isEmpty()) {
+    valr = convertToMetres(m_radius_box->text(),
+                           ShapeDetails::Unit(m_runits->currentIndex()));
   }
-  QString xmldef = 
-    "<infinite-cylinder id=\"" + m_idvalue + "\" >\n"
-    "<radius val=\"" + valr + "\" />\n" +
-    m_centre->write3DElement("centre") +
-    m_axis->write3DElement("axis") +
-    "</infinite-cylinder>\n";
+  QString xmldef = "<infinite-cylinder id=\"" + m_idvalue + "\" >\n"
+                                                            "<radius val=\"" +
+                   valr + "\" />\n" + m_centre->write3DElement("centre") +
+                   m_axis->write3DElement("axis") + "</infinite-cylinder>\n";
   return xmldef;
 }
 
@@ -403,80 +377,81 @@ QString InfiniteCylinderDetails::writeXML() const
 int SliceOfCylinderRingDetails::g_ncylrings = 0;
 
 /// Default constructor
-SliceOfCylinderRingDetails::SliceOfCylinderRingDetails(QWidget *parent) : ShapeDetails(parent)
-{
+SliceOfCylinderRingDetails::SliceOfCylinderRingDetails(QWidget *parent)
+    : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ncylrings;
   m_idvalue = "cylslice_" + QString::number(g_ncylrings);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //inner radius
+  // inner radius
   m_rinner_box = new QLineEdit;
   m_iunits = createLengthUnitsCombo();
   QHBoxLayout *rad_layout = new QHBoxLayout;
   rad_layout->addWidget(new QLabel("Inner radius: "));
   rad_layout->addWidget(m_rinner_box);
   rad_layout->addWidget(m_iunits);
-  //Outer
+  // Outer
   m_router_box = new QLineEdit;
   m_ounits = createLengthUnitsCombo();
   QHBoxLayout *rad2_layout = new QHBoxLayout;
   rad2_layout->addWidget(new QLabel("Outer radius: "));
   rad2_layout->addWidget(m_router_box);
   rad2_layout->addWidget(m_ounits);
-  //Depth
+  // Depth
   m_depth_box = new QLineEdit;
   m_dunits = createLengthUnitsCombo();
   QHBoxLayout *dep_layout = new QHBoxLayout;
   dep_layout->addWidget(new QLabel("       Depth: "));
   dep_layout->addWidget(m_depth_box);
   dep_layout->addWidget(m_dunits);
-  
-  //Arc
+
+  // Arc
   m_arc_box = new QLineEdit;
   QHBoxLayout *arc_layout = new QHBoxLayout;
   arc_layout->addWidget(new QLabel("Arc: "));
   arc_layout->addWidget(m_arc_box);
   arc_layout->addWidget(new QLabel(" deg "));
-  
+
   main_layout->addLayout(rad_layout);
   main_layout->addLayout(rad2_layout);
   main_layout->addLayout(dep_layout);
   main_layout->addLayout(arc_layout);
-
 }
 
 /**
  * Write the XML definition
  */
-QString SliceOfCylinderRingDetails::writeXML() const
-{
+QString SliceOfCylinderRingDetails::writeXML() const {
   QString valir("0.0"), valor("0.0"), vald("0.0"), vala("0.0");
-  if( !m_rinner_box->text().isEmpty() )
-  {
-    valir = convertToMetres(m_rinner_box->text(), ShapeDetails::Unit(m_iunits->currentIndex()));
+  if (!m_rinner_box->text().isEmpty()) {
+    valir = convertToMetres(m_rinner_box->text(),
+                            ShapeDetails::Unit(m_iunits->currentIndex()));
   }
-  if( !m_router_box->text().isEmpty() )
-  {
-    valor = convertToMetres(m_router_box->text(), ShapeDetails::Unit(m_ounits->currentIndex()));
+  if (!m_router_box->text().isEmpty()) {
+    valor = convertToMetres(m_router_box->text(),
+                            ShapeDetails::Unit(m_ounits->currentIndex()));
   }
-  if( !m_depth_box->text().isEmpty() )
-  {
-    vald = convertToMetres(m_depth_box->text(), ShapeDetails::Unit(m_dunits->currentIndex()));
+  if (!m_depth_box->text().isEmpty()) {
+    vald = convertToMetres(m_depth_box->text(),
+                           ShapeDetails::Unit(m_dunits->currentIndex()));
   }
-  if( !m_arc_box->text().isEmpty() )
-  {
+  if (!m_arc_box->text().isEmpty()) {
     vala = m_arc_box->text();
   }
-  
-  QString xmldef = 
-    "<slice-of-cylinder-ring id=\"" + m_idvalue + "\" >\n"
-    "<inner-radius val=\"" + valir + "\" />\n"
-    "<outer-radius val=\"" + valor + "\" />\n"
-    "<depth val=\"" + vald + "\" />\n"
-    "<arc val=\"" + vala + "\" />\n"
-    "</slice-of-cylinder-ring>\n";
-  
+
+  QString xmldef = "<slice-of-cylinder-ring id=\"" + m_idvalue +
+                   "\" >\n"
+                   "<inner-radius val=\"" +
+                   valir + "\" />\n"
+                           "<outer-radius val=\"" +
+                   valor + "\" />\n"
+                           "<depth val=\"" +
+                   vald + "\" />\n"
+                          "<arc val=\"" +
+                   vala + "\" />\n"
+                          "</slice-of-cylinder-ring>\n";
+
   return xmldef;
 }
 
@@ -487,14 +462,13 @@ QString SliceOfCylinderRingDetails::writeXML() const
 int ConeDetails::g_ncones = 0;
 
 /// Default constructor
-ConeDetails::ConeDetails(QWidget *parent) : ShapeDetails(parent)
-{
+ConeDetails::ConeDetails(QWidget *parent) : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ncones;
   m_idvalue = "cone_" + QString::number(g_ncones);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //Height
+  // Height
   m_height_box = new QLineEdit;
   m_hunits = createLengthUnitsCombo();
   QHBoxLayout *hgt_layout = new QHBoxLayout;
@@ -502,14 +476,14 @@ ConeDetails::ConeDetails(QWidget *parent) : ShapeDetails(parent)
   hgt_layout->addWidget(m_height_box);
   hgt_layout->addWidget(m_hunits);
 
-  //Angle
+  // Angle
   m_angle_box = new QLineEdit;
   QHBoxLayout *ang_layout = new QHBoxLayout;
   ang_layout->addWidget(new QLabel("Angle: "));
   ang_layout->addWidget(m_angle_box);
   ang_layout->addWidget(new QLabel(" deg "));
- 
-  //Point boxes
+
+  // Point boxes
   m_tippoint = new PointGroupBox;
   m_tippoint->setTitle("Tip point");
 
@@ -525,26 +499,23 @@ ConeDetails::ConeDetails(QWidget *parent) : ShapeDetails(parent)
 /**
  * Write the XML definition
  */
-QString ConeDetails::writeXML() const
-{
+QString ConeDetails::writeXML() const {
   QString valh("0.0"), valan("0.0");
-  if( !m_height_box->text().isEmpty() )
-  {
-    valh = convertToMetres(m_height_box->text(), ShapeDetails::Unit(m_hunits->currentIndex()));
+  if (!m_height_box->text().isEmpty()) {
+    valh = convertToMetres(m_height_box->text(),
+                           ShapeDetails::Unit(m_hunits->currentIndex()));
   }
-  if( !m_angle_box->text().isEmpty() )
-  {
+  if (!m_angle_box->text().isEmpty()) {
     valan = m_angle_box->text();
   }
 
-  QString xmldef = 
-    "<cone id=\"" + m_idvalue + "\" >\n"
-    "<height val=\"" + valh + "\" />\n"
-    "<angle val=\"" + valan + "\" />\n" +
-    m_tippoint->write3DElement("tip-point") + 
-    m_axis->write3DElement("axis") + 
-    "</cone>\n";
-  
+  QString xmldef = "<cone id=\"" + m_idvalue + "\" >\n"
+                                               "<height val=\"" +
+                   valh + "\" />\n"
+                          "<angle val=\"" +
+                   valan + "\" />\n" + m_tippoint->write3DElement("tip-point") +
+                   m_axis->write3DElement("axis") + "</cone>\n";
+
   return xmldef;
 }
 
@@ -555,21 +526,21 @@ QString ConeDetails::writeXML() const
 int InfiniteConeDetails::g_ninfcones = 0;
 
 /// Default constructor
-InfiniteConeDetails::InfiniteConeDetails(QWidget *parent) : ShapeDetails(parent)
-{
+InfiniteConeDetails::InfiniteConeDetails(QWidget *parent)
+    : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ninfcones;
   m_idvalue = "infcone_" + QString::number(g_ninfcones);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
-  //Angle
+  // Angle
   m_angle_box = new QLineEdit;
   QHBoxLayout *ang_layout = new QHBoxLayout;
   ang_layout->addWidget(new QLabel("Angle: "));
   ang_layout->addWidget(m_angle_box);
   ang_layout->addWidget(new QLabel(" deg "));
- 
-  //Point boxes
+
+  // Point boxes
   m_tippoint = new PointGroupBox;
   m_tippoint->setTitle("Tip point");
 
@@ -584,21 +555,17 @@ InfiniteConeDetails::InfiniteConeDetails(QWidget *parent) : ShapeDetails(parent)
 /**
  * Write the XML definition
  */
-QString InfiniteConeDetails::writeXML() const
-{
+QString InfiniteConeDetails::writeXML() const {
   QString valan("0.0");
-  if( !m_angle_box->text().isEmpty() )
-  {
+  if (!m_angle_box->text().isEmpty()) {
     valan = m_angle_box->text();
   }
 
-  QString xmldef = 
-    "<infinite-cone id=\"" + m_idvalue + "\" >\n"
-    "<angle val=\"" + valan + "\" />\n" +
-    m_tippoint->write3DElement("tip-point") + 
-    m_axis->write3DElement("axis") + 
-    "</infinite-cone>\n";
-  
+  QString xmldef = "<infinite-cone id=\"" + m_idvalue + "\" >\n"
+                                                        "<angle val=\"" +
+                   valan + "\" />\n" + m_tippoint->write3DElement("tip-point") +
+                   m_axis->write3DElement("axis") + "</infinite-cone>\n";
+
   return xmldef;
 }
 
@@ -609,15 +576,15 @@ QString InfiniteConeDetails::writeXML() const
 int InfinitePlaneDetails::g_ninfplanes = 0;
 
 /// Default constructor
-InfinitePlaneDetails::InfinitePlaneDetails(QWidget *parent) : ShapeDetails(parent)
-{
+InfinitePlaneDetails::InfinitePlaneDetails(QWidget *parent)
+    : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ninfplanes;
   m_idvalue = "infplane_" + QString::number(g_ninfplanes);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
 
-  //Point boxes
+  // Point boxes
   m_plane = new PointGroupBox;
   m_plane->setTitle("Point in plane");
 
@@ -631,14 +598,12 @@ InfinitePlaneDetails::InfinitePlaneDetails(QWidget *parent) : ShapeDetails(paren
 /**
  * Write the XML definition
  */
-QString InfinitePlaneDetails::writeXML() const
-{
-  QString xmldef = 
-    "<infinite-plane id=\"" + m_idvalue + "\" >\n" +
-    m_plane->write3DElement("point-in-plane") + 
-    m_normal->write3DElement("normal-to-plane") + 
-    "</infinite-plane>\n";
-  
+QString InfinitePlaneDetails::writeXML() const {
+  QString xmldef = "<infinite-plane id=\"" + m_idvalue + "\" >\n" +
+                   m_plane->write3DElement("point-in-plane") +
+                   m_normal->write3DElement("normal-to-plane") +
+                   "</infinite-plane>\n";
+
   return xmldef;
 }
 
@@ -649,21 +614,20 @@ QString InfinitePlaneDetails::writeXML() const
 int CuboidDetails::g_ncuboids = 0;
 
 /// Default constructor
-CuboidDetails::CuboidDetails(QWidget *parent) : ShapeDetails(parent)
-{
+CuboidDetails::CuboidDetails(QWidget *parent) : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_ncuboids;
   m_idvalue = "cuboid_" + QString::number(g_ncuboids);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
 
-  //Point boxes
+  // Point boxes
   m_left_frt_bot = new PointGroupBox;
   m_left_frt_bot->setTitle("Left front bottom point");
 
   m_left_frt_top = new PointGroupBox;
   m_left_frt_top->setTitle("Left front top point");
-  
+
   m_left_bck_bot = new PointGroupBox;
   m_left_bck_bot->setTitle("Left back bottom point");
 
@@ -674,21 +638,18 @@ CuboidDetails::CuboidDetails(QWidget *parent) : ShapeDetails(parent)
   main_layout->addWidget(m_left_frt_top);
   main_layout->addWidget(m_left_bck_bot);
   main_layout->addWidget(m_right_frt_bot);
-
 }
 
 /**
  * Write the XML definition
  */
-QString CuboidDetails::writeXML() const
-{
-  QString xmldef = 
-    "<cuboid id=\"" + m_idvalue + "\" >\n" +
-    m_left_frt_bot->write3DElement("left-front-bottom-point") + 
-    m_left_frt_top->write3DElement("left-front-top-point") + 
-    m_left_bck_bot->write3DElement("left-back-bottom-point") + 
-    m_right_frt_bot->write3DElement("right-front-bottom-point") + 
-    "</cuboid>\n";
+QString CuboidDetails::writeXML() const {
+  QString xmldef = "<cuboid id=\"" + m_idvalue + "\" >\n" +
+                   m_left_frt_bot->write3DElement("left-front-bottom-point") +
+                   m_left_frt_top->write3DElement("left-front-top-point") +
+                   m_left_bck_bot->write3DElement("left-back-bottom-point") +
+                   m_right_frt_bot->write3DElement("right-front-bottom-point") +
+                   "</cuboid>\n";
   return xmldef;
 }
 
@@ -699,15 +660,14 @@ QString CuboidDetails::writeXML() const
 int HexahedronDetails::g_nhexahedrons = 0;
 
 /// Default constructor
-HexahedronDetails::HexahedronDetails(QWidget *parent) : ShapeDetails(parent)
-{
+HexahedronDetails::HexahedronDetails(QWidget *parent) : ShapeDetails(parent) {
   /// Update number of sphere objects and the set the ID of this one
   ++g_nhexahedrons;
   m_idvalue = "hexahedron_" + QString::number(g_nhexahedrons);
 
   QVBoxLayout *main_layout = new QVBoxLayout(this);
 
-  //Point boxes
+  // Point boxes
   m_left_bck_bot = new PointGroupBox;
   m_left_bck_bot->setTitle("Left back bottom point");
 
@@ -740,29 +700,26 @@ HexahedronDetails::HexahedronDetails(QWidget *parent) : ShapeDetails(parent)
   main_layout->addWidget(m_left_frt_top);
   main_layout->addWidget(m_right_bck_top);
   main_layout->addWidget(m_right_frt_top);
-  
 }
 
 /**
  * Write the XML definition
  */
-QString HexahedronDetails::writeXML() const
-{
-  QString xmldef = 
-    "<hexahedron id=\"" + m_idvalue + "\" >\n" +
-    m_left_bck_bot->write3DElement("left-back-bottom-point") + 
-    m_left_frt_bot->write3DElement("left-front-bottom-point") + 
-    m_right_bck_bot->write3DElement("right-back-bottom-point") + 
-    m_right_frt_bot->write3DElement("right-front-bottom-point") + 
-    m_left_bck_top->write3DElement("left-back-top-point") + 
-    m_left_frt_top->write3DElement("left-front-top-point") + 
-    m_right_bck_top->write3DElement("right-back-top-point") + 
-    m_right_frt_top->write3DElement("right-front-top-point") + 
-    "</hexahedron>\n";
+QString HexahedronDetails::writeXML() const {
+  QString xmldef = "<hexahedron id=\"" + m_idvalue + "\" >\n" +
+                   m_left_bck_bot->write3DElement("left-back-bottom-point") +
+                   m_left_frt_bot->write3DElement("left-front-bottom-point") +
+                   m_right_bck_bot->write3DElement("right-back-bottom-point") +
+                   m_right_frt_bot->write3DElement("right-front-bottom-point") +
+                   m_left_bck_top->write3DElement("left-back-top-point") +
+                   m_left_frt_top->write3DElement("left-front-top-point") +
+                   m_right_bck_top->write3DElement("right-back-top-point") +
+                   m_right_frt_top->write3DElement("right-front-top-point") +
+                   "</hexahedron>\n";
   return xmldef;
 }
 
-// This is not implemented in OpenCascade yet 
+// This is not implemented in OpenCascade yet
 
 //--------------------------------------------------------//
 //                Torus
@@ -793,7 +750,7 @@ QString HexahedronDetails::writeXML() const
 //   hol_layout->addWidget(new QLabel("Hole radius: "));
 //   hol_layout->addWidget(m_inner_rad);
 //   hol_layout->addWidget(m_iunits);
-  
+
 //   //Point boxes
 //   m_centre = new PointGroupBox;
 //   m_centre->setTitle("Centre");
@@ -815,13 +772,15 @@ QString HexahedronDetails::writeXML() const
 //   QString valt("0.0"), vali("0.0");
 //   if( !m_tube_rad->text().isEmpty() )
 //   {
-//     valt = convertToMetres(m_tube_rad->text(), ShapeDetails::Unit(m_tunits->currentIndex()));
+//     valt = convertToMetres(m_tube_rad->text(),
+//     ShapeDetails::Unit(m_tunits->currentIndex()));
 //   }
 //   if( !m_inner_rad->text().isEmpty() )
 //   {
-//     vali = convertToMetres(m_inner_rad->text(), ShapeDetails::Unit(m_iunits->currentIndex())); 
+//     vali = convertToMetres(m_inner_rad->text(),
+//     ShapeDetails::Unit(m_iunits->currentIndex()));
 //   }
-//   QString xmldef = 
+//   QString xmldef =
 //     "<torus id=\"" + m_idvalue + "\" >\n"
 //     "<radius-tube val=\"" + valt + "\" />\n"
 //     "<radius-from-centre-to-tube val=\"" + vali + "\" />\n" +
diff --git a/MantidQt/CustomDialogs/src/SmoothNeighboursDialog.cpp b/MantidQt/CustomDialogs/src/SmoothNeighboursDialog.cpp
index 5abdd440d7fde4d6a76471ac0f57d161eeb5bf5d..445de70b5c9081a1b3ada4a442524b0f5665602a 100644
--- a/MantidQt/CustomDialogs/src/SmoothNeighboursDialog.cpp
+++ b/MantidQt/CustomDialogs/src/SmoothNeighboursDialog.cpp
@@ -6,22 +6,21 @@
 using namespace Mantid::API;
 using namespace Mantid::Geometry;
 
-//Register the class with the factory
+// Register the class with the factory
 DECLARE_DIALOG(SmoothNeighboursDialog)
 
-// As defined in algorithm. Make sure you change them in SmoothNeighbours.cpp as well.
-const QString SmoothNeighboursDialog::NON_UNIFORM_GROUP = "NonUniform Detectors";
-const QString SmoothNeighboursDialog::RECTANGULAR_GROUP = "Rectangular Detectors";
+// As defined in algorithm. Make sure you change them in SmoothNeighbours.cpp as
+// well.
+const QString SmoothNeighboursDialog::NON_UNIFORM_GROUP =
+    "NonUniform Detectors";
+const QString SmoothNeighboursDialog::RECTANGULAR_GROUP =
+    "Rectangular Detectors";
 const QString SmoothNeighboursDialog::INPUT_WORKSPACE = "InputWorkspace";
 
-SmoothNeighboursDialog::SmoothNeighboursDialog(QWidget* parent) 
-  : AlgorithmDialog(parent),
-  m_propertiesWidget(NULL), m_dialogLayout(NULL)
-{
-}
- 
-void SmoothNeighboursDialog::initLayout()
-{
+SmoothNeighboursDialog::SmoothNeighboursDialog(QWidget *parent)
+    : AlgorithmDialog(parent), m_propertiesWidget(NULL), m_dialogLayout(NULL) {}
+
+void SmoothNeighboursDialog::initLayout() {
   // Create main layout
   m_dialogLayout = new QVBoxLayout();
 
@@ -38,18 +37,21 @@ void SmoothNeighboursDialog::initLayout()
   m_propertiesWidget->setAlgorithm(this->getAlgorithm());
 
   // Mark the properties that will be forced enabled or disabled
-  m_propertiesWidget->addEnabledAndDisableLists(m_enabled, m_disabled + m_python_arguments);
+  m_propertiesWidget->addEnabledAndDisableLists(
+      m_enabled, m_disabled + m_python_arguments);
 
   // Tie all the widgets to properties
-  for (auto it = m_propertiesWidget->m_propWidgets.begin(); it != m_propertiesWidget->m_propWidgets.end(); it++)
+  for (auto it = m_propertiesWidget->m_propWidgets.begin();
+       it != m_propertiesWidget->m_propWidgets.end(); it++)
     this->tie(it.value(), it.key());
 
   m_propertiesWidget->hideOrDisableProperties();
 
-  PropertyWidget* inputWorkspaceWidget = m_propertiesWidget->m_propWidgets[INPUT_WORKSPACE];
+  PropertyWidget *inputWorkspaceWidget =
+      m_propertiesWidget->m_propWidgets[INPUT_WORKSPACE];
 
-  connect(inputWorkspaceWidget, SIGNAL(valueChanged(const QString&)),
-          this, SLOT(inputWorkspaceChanged(const QString&)));
+  connect(inputWorkspaceWidget, SIGNAL(valueChanged(const QString &)), this,
+          SLOT(inputWorkspaceChanged(const QString &)));
 
   m_dialogLayout->addWidget(m_propertiesWidget);
 
@@ -60,8 +62,7 @@ void SmoothNeighboursDialog::initLayout()
   inputWorkspaceWidget->valueChangedSlot();
 }
 
-void SmoothNeighboursDialog::inputWorkspaceChanged(const QString& pName)
-{
+void SmoothNeighboursDialog::inputWorkspaceChanged(const QString &pName) {
   UNUSED_ARG(pName);
 
   m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(false);
@@ -69,42 +70,48 @@ void SmoothNeighboursDialog::inputWorkspaceChanged(const QString& pName)
 
   std::string inWsName = INPUT_WORKSPACE.toStdString();
 
-  // Workspace should have been set by PropertyWidget before emitting valueChanged
+  // Workspace should have been set by PropertyWidget before emitting
+  // valueChanged
   MatrixWorkspace_sptr inWs = this->getAlgorithm()->getProperty(inWsName);
 
-  if(!inWs)
-  {
-    // Workspace groups are NOT returned by IWP->getWorkspace(), as they are not MatrixWorkspace,
+  if (!inWs) {
+    // Workspace groups are NOT returned by IWP->getWorkspace(), as they are not
+    // MatrixWorkspace,
     // so check the ADS for the GroupWorkspace with the same name
-    std::string inWsValue = this->getAlgorithm()->getPointerToProperty(inWsName)->value();
+    std::string inWsValue =
+        this->getAlgorithm()->getPointerToProperty(inWsName)->value();
 
     // If it really doesn't exist, don't do anything
-    if(!AnalysisDataService::Instance().doesExist(inWsValue))
+    if (!AnalysisDataService::Instance().doesExist(inWsValue))
       return;
 
-    WorkspaceGroup_sptr inGroupWs = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(inWsValue);
+    WorkspaceGroup_sptr inGroupWs =
+        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(inWsValue);
 
-    if(inGroupWs)
-      // If is a group workspace, use the first workspace to determine the instrument type,
+    if (inGroupWs)
+      // If is a group workspace, use the first workspace to determine the
+      // instrument type,
       // as most of the times it will be the same for all the workspaces
-      inWs = boost::dynamic_pointer_cast<MatrixWorkspace>(inGroupWs->getItem(0));
+      inWs =
+          boost::dynamic_pointer_cast<MatrixWorkspace>(inGroupWs->getItem(0));
     else
       // If is not a GroupWorkspace as well, do nothing
       return;
   }
-  Instrument::ContainsState containsRectDetectors = inWs->getInstrument()->containsRectDetectors();
+  Instrument::ContainsState containsRectDetectors =
+      inWs->getInstrument()->containsRectDetectors();
 
-  if(containsRectDetectors == Instrument::ContainsState::Full)
+  if (containsRectDetectors == Instrument::ContainsState::Full)
     m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(true);
   else
     m_propertiesWidget->m_groupWidgets[NON_UNIFORM_GROUP]->setVisible(true);
 }
 
-void SmoothNeighboursDialog::accept()
-{
+void SmoothNeighboursDialog::accept() {
   AlgorithmDialog::accept();
 
   // If got there, there were errors
-  for(auto it = m_errors.begin(); it != m_errors.end(); it++)
-    m_propertiesWidget->m_propWidgets[it.key()]->updateIconVisibility(it.value());
+  for (auto it = m_errors.begin(); it != m_errors.end(); it++)
+    m_propertiesWidget->m_propWidgets[it.key()]->updateIconVisibility(
+        it.value());
 }
diff --git a/MantidQt/CustomDialogs/src/SortTableWorkspaceDialog.cpp b/MantidQt/CustomDialogs/src/SortTableWorkspaceDialog.cpp
index bed55e6687962aa829f31a218944237fa63be864..f9d0bc7f2de7ce94afd416c7d782a07e0d340287 100644
--- a/MantidQt/CustomDialogs/src/SortTableWorkspaceDialog.cpp
+++ b/MantidQt/CustomDialogs/src/SortTableWorkspaceDialog.cpp
@@ -7,27 +7,20 @@
 #include "MantidAPI/ITableWorkspace.h"
 #include "MantidKernel/Exception.h"
 
-
 using namespace MantidQt::API;
 
-namespace MantidQt
-{
-namespace CustomDialogs
-{
+namespace MantidQt {
+namespace CustomDialogs {
 
 // Declare the dialog. Name must match the class name
 DECLARE_DIALOG(SortTableWorkspaceDialog)
 
-
 /// Default constructor
-SortTableWorkspaceDialog::SortTableWorkspaceDialog(QWidget *parent) 
-  : API::AlgorithmDialog(parent), m_form()
-{
-}
+SortTableWorkspaceDialog::SortTableWorkspaceDialog(QWidget *parent)
+    : API::AlgorithmDialog(parent), m_form() {}
 
 /// Initialize the layout
-void SortTableWorkspaceDialog::initLayout()
-{
+void SortTableWorkspaceDialog::initLayout() {
   // set up the GUI elements
   m_form.setupUi(this);
 
@@ -35,19 +28,22 @@ void SortTableWorkspaceDialog::initLayout()
   m_form.dialogLayout->addLayout(this->createDefaultButtonLayout());
 
   // correct the tab order
-  QWidget::setTabOrder( m_form.groupBox, m_form.cbColumnName );
-  QWidget::setTabOrder( m_form.cbColumnName, m_form.cbAscending );
+  QWidget::setTabOrder(m_form.groupBox, m_form.cbColumnName);
+  QWidget::setTabOrder(m_form.cbColumnName, m_form.cbAscending);
 
   // disable Add/Remove buttons in case there are no table workspaces at all
   m_form.btnRemoveColumn->setEnabled(false);
   m_form.btnAddColumn->setEnabled(false);
 
   // connect the slots
-  connect( m_form.workspace, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(workspaceChanged(const QString&)) );
-  connect( m_form.workspace, SIGNAL(emptied()), this, SLOT(clearGUI()) );
-  connect( m_form.cbColumnName, SIGNAL(currentIndexChanged(int)), this, SLOT(changedColumnName(int)) );
-  connect( m_form.btnAddColumn, SIGNAL(clicked()), this, SLOT(addColumn()) );
-  connect( m_form.btnRemoveColumn, SIGNAL(clicked()), this, SLOT(removeColumn()) );
+  connect(m_form.workspace, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(workspaceChanged(const QString &)));
+  connect(m_form.workspace, SIGNAL(emptied()), this, SLOT(clearGUI()));
+  connect(m_form.cbColumnName, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(changedColumnName(int)));
+  connect(m_form.btnAddColumn, SIGNAL(clicked()), this, SLOT(addColumn()));
+  connect(m_form.btnRemoveColumn, SIGNAL(clicked()), this,
+          SLOT(removeColumn()));
 
   tieStaticWidgets(true);
 }
@@ -55,48 +51,46 @@ void SortTableWorkspaceDialog::initLayout()
 /**
  * Parse input
  */
-void SortTableWorkspaceDialog::parseInput()
-{
+void SortTableWorkspaceDialog::parseInput() {
   QStringList columns;
   QStringList ascending;
 
   // extract column names to sort by from the controls, sort order too
   auto n = m_sortColumns.size();
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     auto itemColumn = m_form.columnsLayout->itemAtPosition(i, 1);
     auto itemAscending = m_form.columnsLayout->itemAtPosition(i, 2);
-    if ( !itemColumn || !itemColumn->widget() || !itemAscending || !itemAscending->widget() )
-    {
-      throw std::logic_error("Logic error in SortTableWorkspaceDialog: internal inconsistency.");
+    if (!itemColumn || !itemColumn->widget() || !itemAscending ||
+        !itemAscending->widget()) {
+      throw std::logic_error(
+          "Logic error in SortTableWorkspaceDialog: internal inconsistency.");
     }
-    
-    auto name = dynamic_cast<QComboBox*>(itemColumn->widget())->currentText();
-    auto ia = dynamic_cast<QComboBox*>(itemAscending->widget())->currentIndex();
+
+    auto name = dynamic_cast<QComboBox *>(itemColumn->widget())->currentText();
+    auto ia =
+        dynamic_cast<QComboBox *>(itemAscending->widget())->currentIndex();
     columns << name;
-    ascending << QString::number( ia == 0 ? 1 : 0 );
+    ascending << QString::number(ia == 0 ? 1 : 0);
   }
 
   // pass the properties to the algorithm
-  storePropertyValue( "Columns", columns.join(",") );
-  storePropertyValue( "Ascending", ascending.join(",") );
+  storePropertyValue("Columns", columns.join(","));
+  storePropertyValue("Ascending", ascending.join(","));
 }
 
 /**
 * Tie static widgets to their properties
 * @param readHistory :: If true then the history will be re read.
 */
-void SortTableWorkspaceDialog::tieStaticWidgets(const bool)
-{
+void SortTableWorkspaceDialog::tieStaticWidgets(const bool) {
   QStringList allowedTypes;
   allowedTypes << "TableWorkspace";
   m_form.workspace->setWorkspaceTypes(allowedTypes);
-  tie( m_form.workspace, "InputWorkspace" );
-  tie( m_form.output, "OutputWorkspace" );
-  if ( !m_form.workspace->currentText().isEmpty() )
-  {
+  tie(m_form.workspace, "InputWorkspace");
+  tie(m_form.output, "OutputWorkspace");
+  if (!m_form.workspace->currentText().isEmpty()) {
     // start with output == input
-    m_form.output->setText( m_form.workspace->currentText() );
+    m_form.output->setText(m_form.workspace->currentText());
   }
 }
 
@@ -104,40 +98,36 @@ void SortTableWorkspaceDialog::tieStaticWidgets(const bool)
  * Call to update the interface when the input workspace changes.
  * @param wsName :: Name of the new input workspace.
  */
-void SortTableWorkspaceDialog::workspaceChanged(const QString& wsName)
-{
+void SortTableWorkspaceDialog::workspaceChanged(const QString &wsName) {
   // start with output == input
-  m_form.output->setText( wsName );
+  m_form.output->setText(wsName);
   // prepare the controls for new values
   clearGUI();
-  if ( wsName.isEmpty() ) return;
-  try
-  {
-    auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::ITableWorkspace>( wsName.toStdString() );
-    if ( !ws ) return;
+  if (wsName.isEmpty())
+    return;
+  try {
+    auto ws =
+        Mantid::API::AnalysisDataService::Instance()
+            .retrieveWS<Mantid::API::ITableWorkspace>(wsName.toStdString());
+    if (!ws)
+      return;
     m_columnNames.clear();
     // get and cache the column names from the workspace
     auto columnNames = ws->getColumnNames();
-    for(auto name = columnNames.begin(); name != columnNames.end(); ++name)
-    {
+    for (auto name = columnNames.begin(); name != columnNames.end(); ++name) {
       m_columnNames << QString::fromStdString(*name);
     }
-    m_form.cbColumnName->addItems( m_columnNames );
+    m_form.cbColumnName->addItems(m_columnNames);
     // the GUI already has the controls to set the first column
     // if there are no other columns in the table no more names can be added
-    if ( m_columnNames.size() <= 1 )
-    {
+    if (m_columnNames.size() <= 1) {
       m_form.btnAddColumn->setEnabled(false);
-    }
-    else
-    {
+    } else {
       m_form.btnAddColumn->setEnabled(true);
     }
     // cache the selected column name
     m_sortColumns[0] = m_form.cbColumnName->currentText();
-  }
-  catch(Mantid::Kernel::Exception::NotFoundError&)
-  {
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
     return;
   }
 }
@@ -145,25 +135,21 @@ void SortTableWorkspaceDialog::workspaceChanged(const QString& wsName)
 /**
  * Clear the UI
  */
-void SortTableWorkspaceDialog::clearGUI()
-{
+void SortTableWorkspaceDialog::clearGUI() {
   m_columnNames.clear();
-  m_form.lblColumnName->setText( "Column" );
+  m_form.lblColumnName->setText("Column");
   m_form.cbColumnName->clear();
   m_form.cbAscending->setCurrentIndex(0);
   m_form.btnAddColumn->setEnabled(false);
   m_form.btnRemoveColumn->setEnabled(false);
   // remove controls for any additional columns
   auto nRows = m_form.columnsLayout->rowCount();
-  for(auto row = nRows - 1; row > 0; --row)
-  {
-    for(int col = 0; col < 3; ++col)
-    {
-      auto item = m_form.columnsLayout->itemAtPosition( row, col );
-      if ( item )
-      {
-        auto index = m_form.columnsLayout->indexOf( item->widget() );
-        m_form.columnsLayout->takeAt( index );
+  for (auto row = nRows - 1; row > 0; --row) {
+    for (int col = 0; col < 3; ++col) {
+      auto item = m_form.columnsLayout->itemAtPosition(row, col);
+      if (item) {
+        auto index = m_form.columnsLayout->indexOf(item->widget());
+        m_form.columnsLayout->takeAt(index);
         item->widget()->deleteLater();
       }
     }
@@ -177,36 +163,36 @@ void SortTableWorkspaceDialog::clearGUI()
 /**
  * Add elements to set additional column name and sort order
  */
-void SortTableWorkspaceDialog::addColumn()
-{
-  m_form.lblColumnName->setText( "Column 1" );
+void SortTableWorkspaceDialog::addColumn() {
+  m_form.lblColumnName->setText("Column 1");
   // create controls for setting new column
   auto newRow = m_sortColumns.size();
-  assert( newRow <= m_columnNames.size() );
-  QLabel *label = new QLabel( QString("Column %1").arg(newRow+1) );
+  assert(newRow <= m_columnNames.size());
+  QLabel *label = new QLabel(QString("Column %1").arg(newRow + 1));
   QComboBox *columnName = new QComboBox();
-  columnName->addItems( m_columnNames );
-  columnName->setToolTip( m_form.cbColumnName->toolTip() );
-  connect( columnName, SIGNAL(currentIndexChanged(int)), this, SLOT(changedColumnName(int)) );
+  columnName->addItems(m_columnNames);
+  columnName->setToolTip(m_form.cbColumnName->toolTip());
+  connect(columnName, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(changedColumnName(int)));
   QComboBox *ascending = new QComboBox();
   ascending->addItem("Ascending");
   ascending->addItem("Descending");
-  ascending->setToolTip( m_form.cbAscending->toolTip() );
+  ascending->setToolTip(m_form.cbAscending->toolTip());
   // add them to the layout
-  m_form.columnsLayout->addWidget(label,newRow,0);
-  m_form.columnsLayout->addWidget(columnName,newRow,1);
-  m_form.columnsLayout->addWidget(ascending,newRow,2);
+  m_form.columnsLayout->addWidget(label, newRow, 0);
+  m_form.columnsLayout->addWidget(columnName, newRow, 1);
+  m_form.columnsLayout->addWidget(ascending, newRow, 2);
   // correct the tab order
-  QWidget::setTabOrder( m_form.columnsLayout->itemAtPosition( newRow - 1, 2 )->widget(), columnName );
-  QWidget::setTabOrder( columnName, ascending );
+  QWidget::setTabOrder(
+      m_form.columnsLayout->itemAtPosition(newRow - 1, 2)->widget(),
+      columnName);
+  QWidget::setTabOrder(columnName, ascending);
 
-  // suggest a name for the new column: one that hasn't been used in 
+  // suggest a name for the new column: one that hasn't been used in
   // other sort columns
   QString newColumnName;
-  foreach(QString name, m_columnNames)
-  {
-    if ( !m_sortColumns.contains(name) )
-    {
+  foreach (QString name, m_columnNames) {
+    if (!m_sortColumns.contains(name)) {
       columnName->setItemText(-1, name);
       break;
     }
@@ -214,8 +200,7 @@ void SortTableWorkspaceDialog::addColumn()
   // cache the column name
   m_sortColumns << columnName->currentText();
   // set the Add/Remove buttons into a correct state
-  if ( m_sortColumns.size() == m_columnNames.size() )
-  {
+  if (m_sortColumns.size() == m_columnNames.size()) {
     m_form.btnAddColumn->setEnabled(false);
   }
   m_form.btnRemoveColumn->setEnabled(true);
@@ -224,19 +209,18 @@ void SortTableWorkspaceDialog::addColumn()
 /**
  * Sync column names in the combo-boxes and m_sortColumns.
  */
-void SortTableWorkspaceDialog::changedColumnName(int)
-{
+void SortTableWorkspaceDialog::changedColumnName(int) {
   // don't try to figure out which column changed - just reset all cached names
   auto n = m_sortColumns.size();
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     auto item = m_form.columnsLayout->itemAtPosition(i, 1);
-    if ( !item || !item->widget() || !dynamic_cast<QComboBox*>(item->widget()) )
-    {
-      throw std::logic_error("Logic error in SortTableWorkspaceDialog: internal inconsistency.");
+    if (!item || !item->widget() ||
+        !dynamic_cast<QComboBox *>(item->widget())) {
+      throw std::logic_error(
+          "Logic error in SortTableWorkspaceDialog: internal inconsistency.");
     }
-    
-    auto name = dynamic_cast<QComboBox*>(item->widget())->currentText();
+
+    auto name = dynamic_cast<QComboBox *>(item->widget())->currentText();
     m_sortColumns[i] = name;
   }
 }
@@ -244,27 +228,23 @@ void SortTableWorkspaceDialog::changedColumnName(int)
 /**
  * Remove GUI elements for additional column to sort by.
  */
-void SortTableWorkspaceDialog::removeColumn()
-{
-  assert( m_columnNames.size() > 1 );
+void SortTableWorkspaceDialog::removeColumn() {
+  assert(m_columnNames.size() > 1);
   // remove the last column
   m_sortColumns.removeLast();
   auto row = m_sortColumns.size();
-  for(int col = 0; col < 3; ++col)
-  {
-    auto item = m_form.columnsLayout->itemAtPosition( row, col );
-    if ( item )
-    {
-      auto index = m_form.columnsLayout->indexOf( item->widget() );
-      m_form.columnsLayout->takeAt( index );
+  for (int col = 0; col < 3; ++col) {
+    auto item = m_form.columnsLayout->itemAtPosition(row, col);
+    if (item) {
+      auto index = m_form.columnsLayout->indexOf(item->widget());
+      m_form.columnsLayout->takeAt(index);
       item->widget()->deleteLater();
     }
   }
   // leave the Add/Remove buttons in a correct state
-  if ( m_sortColumns.size() == 1 )
-  {
+  if (m_sortColumns.size() == 1) {
     m_form.btnRemoveColumn->setEnabled(false);
-    m_form.lblColumnName->setText( "Column" );
+    m_form.lblColumnName->setText("Column");
   }
   m_form.btnAddColumn->setEnabled(true);
 }
diff --git a/MantidQt/CustomDialogs/src/StartLiveDataDialog.cpp b/MantidQt/CustomDialogs/src/StartLiveDataDialog.cpp
index c477b01fe3e3058d3503479c0a46f6716ec1e470..f71d5c8021fa70900c2ebe54aff0d9c5094ff563 100644
--- a/MantidQt/CustomDialogs/src/StartLiveDataDialog.cpp
+++ b/MantidQt/CustomDialogs/src/StartLiveDataDialog.cpp
@@ -23,82 +23,86 @@ using Mantid::API::Algorithm_sptr;
 using Mantid::Kernel::DateAndTime;
 
 namespace {
-  class LiveDataAlgInputHistoryImpl : public AbstractAlgorithmInputHistory
-  {
-  private:
-    LiveDataAlgInputHistoryImpl() : AbstractAlgorithmInputHistory("LiveDataAlgorithms") {}
-    ~LiveDataAlgInputHistoryImpl() {}
-
-  private:
-    friend struct Mantid::Kernel::CreateUsingNew<LiveDataAlgInputHistoryImpl>;
-  };
-
-  #ifdef _WIN32
-  // this breaks new namespace declaraion rules; need to find a better fix
-    template class Mantid::Kernel::SingletonHolder<LiveDataAlgInputHistoryImpl>;
-  #endif /* _WIN32 */
-  /// The specific instantiation of the templated type
-  typedef Mantid::Kernel::SingletonHolder<LiveDataAlgInputHistoryImpl> LiveDataAlgInputHistory;
-
-  class LiveDataPostProcessingAlgInputHistoryImpl : public AbstractAlgorithmInputHistory
-  {
-  private:
-    LiveDataPostProcessingAlgInputHistoryImpl() : AbstractAlgorithmInputHistory("LiveDataPostProcessingAlgorithms") {}
-    ~LiveDataPostProcessingAlgInputHistoryImpl() {}
-
-  private:
-    friend struct Mantid::Kernel::CreateUsingNew<LiveDataPostProcessingAlgInputHistoryImpl>;
-  };
-
-  #ifdef _WIN32
-  // this breaks new namespace declaraion rules; need to find a better fix
-    template class Mantid::Kernel::SingletonHolder<LiveDataPostProcessingAlgInputHistoryImpl>;
-  #endif /* _WIN32 */
-    /// The specific instantiation of the templated type
-    typedef Mantid::Kernel::SingletonHolder<LiveDataPostProcessingAlgInputHistoryImpl> LiveDataPostProcessingAlgInputHistory;
+class LiveDataAlgInputHistoryImpl : public AbstractAlgorithmInputHistory {
+private:
+  LiveDataAlgInputHistoryImpl()
+      : AbstractAlgorithmInputHistory("LiveDataAlgorithms") {}
+  ~LiveDataAlgInputHistoryImpl() {}
+
+private:
+  friend struct Mantid::Kernel::CreateUsingNew<LiveDataAlgInputHistoryImpl>;
+};
+
+#ifdef _WIN32
+// this breaks new namespace declaraion rules; need to find a better fix
+template class Mantid::Kernel::SingletonHolder<LiveDataAlgInputHistoryImpl>;
+#endif /* _WIN32 */
+/// The specific instantiation of the templated type
+typedef Mantid::Kernel::SingletonHolder<LiveDataAlgInputHistoryImpl>
+    LiveDataAlgInputHistory;
+
+class LiveDataPostProcessingAlgInputHistoryImpl
+    : public AbstractAlgorithmInputHistory {
+private:
+  LiveDataPostProcessingAlgInputHistoryImpl()
+      : AbstractAlgorithmInputHistory("LiveDataPostProcessingAlgorithms") {}
+  ~LiveDataPostProcessingAlgInputHistoryImpl() {}
+
+private:
+  friend struct Mantid::Kernel::CreateUsingNew<
+      LiveDataPostProcessingAlgInputHistoryImpl>;
+};
+
+#ifdef _WIN32
+// this breaks new namespace declaraion rules; need to find a better fix
+template class Mantid::Kernel::SingletonHolder<
+    LiveDataPostProcessingAlgInputHistoryImpl>;
+#endif /* _WIN32 */
+/// The specific instantiation of the templated type
+typedef Mantid::Kernel::SingletonHolder<
+    LiveDataPostProcessingAlgInputHistoryImpl>
+    LiveDataPostProcessingAlgInputHistory;
 }
 
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomDialogs
-{
-  DECLARE_DIALOG(StartLiveDataDialog)
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomDialogs {
+DECLARE_DIALOG(StartLiveDataDialog)
 
 //----------------------
 // Public member functions
 //----------------------
-///Constructor
-StartLiveDataDialog::StartLiveDataDialog(QWidget *parent) :
-  AlgorithmDialog(parent),
-  m_scrollbars(this), m_useProcessAlgo(false), m_useProcessScript(false),
-  m_usePostProcessAlgo(false), m_usePostProcessScript(false)
-{
+/// Constructor
+StartLiveDataDialog::StartLiveDataDialog(QWidget *parent)
+    : AlgorithmDialog(parent), m_scrollbars(this), m_useProcessAlgo(false),
+      m_useProcessScript(false), m_usePostProcessAlgo(false),
+      m_usePostProcessScript(false) {
   // Create the input history. This loads it too.
   LiveDataAlgInputHistory::Instance();
 }
 
 /// Destructor
-StartLiveDataDialog::~StartLiveDataDialog()
-{
+StartLiveDataDialog::~StartLiveDataDialog() {
   // Save the input history to QSettings
   LiveDataAlgInputHistory::Instance().save();
   LiveDataPostProcessingAlgInputHistory::Instance().save();
 }
 
 /// Set up the dialog layout
-void StartLiveDataDialog::initLayout()
-{
+void StartLiveDataDialog::initLayout() {
   ui.setupUi(this);
 
   // Enable scrollbars (must happen after setupUi()!)
   m_scrollbars.setEnabled(true);
 
   // To save the history of inputs
-  // RJT: I don't much like this, but at least it's safe from a lifetime point of view.
-  AbstractAlgorithmInputHistory * history1 = &LiveDataAlgInputHistory::Instance();
+  // RJT: I don't much like this, but at least it's safe from a lifetime point
+  // of view.
+  AbstractAlgorithmInputHistory *history1 =
+      &LiveDataAlgInputHistory::Instance();
   ui.processingAlgo->setInputHistory(history1);
-  AbstractAlgorithmInputHistory * history2 = &LiveDataPostProcessingAlgInputHistory::Instance();
+  AbstractAlgorithmInputHistory *history2 =
+      &LiveDataPostProcessingAlgInputHistory::Instance();
   ui.postAlgo->setInputHistory(history2);
 
   // ========== Set previous values from history =============
@@ -130,18 +134,20 @@ void StartLiveDataDialog::initLayout()
   ui.splitterMain->setStretchFactor(1, 1);
 
   // ========== Set previous values for Algorithms/scripts ============
-  for (int i=0; i<2; i++)
-  {
+  for (int i = 0; i < 2; i++) {
     bool post = i > 0;
     QString prefix = "Processing";
 
-    if (post) prefix = "PostProcessing";
-    QString algo = AlgorithmInputHistory::Instance().previousInput("StartLiveData", prefix+"Algorithm");
-    QString algoProps = AlgorithmInputHistory::Instance().previousInput("StartLiveData", prefix+"Properties");
-    QString script = AlgorithmInputHistory::Instance().previousInput("StartLiveData", prefix+"Script");
+    if (post)
+      prefix = "PostProcessing";
+    QString algo = AlgorithmInputHistory::Instance().previousInput(
+        "StartLiveData", prefix + "Algorithm");
+    QString algoProps = AlgorithmInputHistory::Instance().previousInput(
+        "StartLiveData", prefix + "Properties");
+    QString script = AlgorithmInputHistory::Instance().previousInput(
+        "StartLiveData", prefix + "Script");
 
-    if (!post)
-    {
+    if (!post) {
       if (!algo.isEmpty())
         ui.radProcessAlgorithm->setChecked(true);
       else if (!script.isEmpty())
@@ -153,9 +159,7 @@ void StartLiveDataDialog::initLayout()
       ui.processingAlgo->setScriptText(script);
       ui.processingAlgo->setSelectedAlgorithm(algo);
       changeProcessingAlgorithm();
-    }
-    else
-    {
+    } else {
       if (!algo.isEmpty())
         ui.radPostProcessAlgorithm->setChecked(true);
       else if (!script.isEmpty())
@@ -171,48 +175,62 @@ void StartLiveDataDialog::initLayout()
   }
 
   radioPostProcessClicked();
-  setDefaultAccumulationMethod( ui.cmbInstrument->currentText() );
-  updateUiElements( ui.cmbInstrument->currentText());
+  setDefaultAccumulationMethod(ui.cmbInstrument->currentText());
+  updateUiElements(ui.cmbInstrument->currentText());
 
   //=========== Listener's properties =============
 
   initListenerPropLayout(ui.cmbInstrument->currentText());
 
   //=========== SLOTS =============
-  connect(ui.processingAlgo, SIGNAL(changedAlgorithm()), this, SLOT(changeProcessingAlgorithm()));
-  connect(ui.postAlgo, SIGNAL(changedAlgorithm()), this, SLOT(changePostProcessingAlgorithm()));
-
-  connect(ui.radProcessNone, SIGNAL(toggled(bool)), this, SLOT(radioProcessClicked()));
-  connect(ui.radProcessAlgorithm, SIGNAL(toggled(bool)), this, SLOT(radioProcessClicked()));
-  connect(ui.radProcessScript, SIGNAL(toggled(bool)), this, SLOT(radioProcessClicked()));
-
-  connect(ui.radPostProcessNone, SIGNAL(toggled(bool)), this, SLOT(radioPostProcessClicked()));
-  connect(ui.radPostProcessAlgorithm, SIGNAL(toggled(bool)), this, SLOT(radioPostProcessClicked()));
-  connect(ui.radPostProcessScript, SIGNAL(toggled(bool)), this, SLOT(radioPostProcessClicked()));
+  connect(ui.processingAlgo, SIGNAL(changedAlgorithm()), this,
+          SLOT(changeProcessingAlgorithm()));
+  connect(ui.postAlgo, SIGNAL(changedAlgorithm()), this,
+          SLOT(changePostProcessingAlgorithm()));
+
+  connect(ui.radProcessNone, SIGNAL(toggled(bool)), this,
+          SLOT(radioProcessClicked()));
+  connect(ui.radProcessAlgorithm, SIGNAL(toggled(bool)), this,
+          SLOT(radioProcessClicked()));
+  connect(ui.radProcessScript, SIGNAL(toggled(bool)), this,
+          SLOT(radioProcessClicked()));
+
+  connect(ui.radPostProcessNone, SIGNAL(toggled(bool)), this,
+          SLOT(radioPostProcessClicked()));
+  connect(ui.radPostProcessAlgorithm, SIGNAL(toggled(bool)), this,
+          SLOT(radioPostProcessClicked()));
+  connect(ui.radPostProcessScript, SIGNAL(toggled(bool)), this,
+          SLOT(radioPostProcessClicked()));
 
   connect(ui.radNow, SIGNAL(toggled(bool)), this, SLOT(radioTimeClicked()));
-  connect(ui.radStartOfRun, SIGNAL(toggled(bool)), this, SLOT(radioTimeClicked()));
-  connect(ui.radAbsoluteTime, SIGNAL(toggled(bool)), this, SLOT(radioTimeClicked()));
-
-  connect(ui.chkPreserveEvents, SIGNAL(toggled(bool)), this, SLOT(chkPreserveEventsToggled()));
-
-  connect(ui.cmbInstrument,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(setDefaultAccumulationMethod(const QString&)));
-  connect(ui.cmbInstrument,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(initListenerPropLayout(const QString&)));
-  connect(ui.cmbInstrument,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(updateUiElements(const QString&)));
-
-  QLayout * buttonLayout = this->createDefaultButtonLayout();
+  connect(ui.radStartOfRun, SIGNAL(toggled(bool)), this,
+          SLOT(radioTimeClicked()));
+  connect(ui.radAbsoluteTime, SIGNAL(toggled(bool)), this,
+          SLOT(radioTimeClicked()));
+
+  connect(ui.chkPreserveEvents, SIGNAL(toggled(bool)), this,
+          SLOT(chkPreserveEventsToggled()));
+
+  connect(ui.cmbInstrument, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(setDefaultAccumulationMethod(const QString &)));
+  connect(ui.cmbInstrument, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(initListenerPropLayout(const QString &)));
+  connect(ui.cmbInstrument, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(updateUiElements(const QString &)));
+
+  QLayout *buttonLayout = this->createDefaultButtonLayout();
   ui.mainLayout->addLayout(buttonLayout);
 }
 
-
 //------------------------------------------------------------------------------
 /// Parse input when the dialog is accepted
-void StartLiveDataDialog::parseInput()
-{
+void StartLiveDataDialog::parseInput() {
   storePropertyValue("Instrument", ui.cmbInstrument->currentText());
-  storePropertyValue("AccumulationMethod", ui.cmbAccumulationMethod->currentText());
+  storePropertyValue("AccumulationMethod",
+                     ui.cmbAccumulationMethod->currentText());
 
-  storePropertyValue("AccumulationWorkspace", ui.editAccumulationWorkspace->text());
+  storePropertyValue("AccumulationWorkspace",
+                     ui.editAccumulationWorkspace->text());
   if (!m_usePostProcessAlgo && !m_usePostProcessScript)
     storePropertyValue("AccumulationWorkspace", "");
 
@@ -221,27 +239,26 @@ void StartLiveDataDialog::parseInput()
   storePropertyValue("ProcessingAlgorithm", "");
   storePropertyValue("ProcessingProperties", "");
   storePropertyValue("ProcessingScript", "");
-  if (m_useProcessAlgo && m_processingAlg)
-  {
-    storePropertyValue("ProcessingAlgorithm", ui.processingAlgo->getSelectedAlgorithm());
+  if (m_useProcessAlgo && m_processingAlg) {
+    storePropertyValue("ProcessingAlgorithm",
+                       ui.processingAlgo->getSelectedAlgorithm());
     std::string props;
-    props = m_processingAlg->asString(false); 
+    props = m_processingAlg->asString(false);
     storePropertyValue("ProcessingProperties", QString::fromStdString(props));
-  }
-  else if (m_useProcessScript)
+  } else if (m_useProcessScript)
     storePropertyValue("ProcessingScript", ui.processingAlgo->getScriptText());
 
   storePropertyValue("PostProcessingAlgorithm", "");
   storePropertyValue("PostProcessingProperties", "");
   storePropertyValue("PostProcessingScript", "");
-  if (m_usePostProcessAlgo && m_postProcessingAlg)
-  {
-    storePropertyValue("PostProcessingAlgorithm", ui.postAlgo->getSelectedAlgorithm());
+  if (m_usePostProcessAlgo && m_postProcessingAlg) {
+    storePropertyValue("PostProcessingAlgorithm",
+                       ui.postAlgo->getSelectedAlgorithm());
     std::string props;
-    props = m_postProcessingAlg->asString(false); 
-    storePropertyValue("PostProcessingProperties", QString::fromStdString(props));
-  }
-  else if (m_usePostProcessScript)
+    props = m_postProcessingAlg->asString(false);
+    storePropertyValue("PostProcessingProperties",
+                       QString::fromStdString(props));
+  } else if (m_usePostProcessScript)
     storePropertyValue("PostProcessingScript", ui.postAlgo->getScriptText());
 
   // Save to QSettings
@@ -249,11 +266,9 @@ void StartLiveDataDialog::parseInput()
   ui.postAlgo->saveInput();
 }
 
-
 //------------------------------------------------------------------------------
 /** Slot called when one of the radio buttons in "processing" are picked */
-void StartLiveDataDialog::radioProcessClicked()
-{
+void StartLiveDataDialog::radioProcessClicked() {
   m_useProcessAlgo = ui.radProcessAlgorithm->isChecked();
   ui.processingAlgo->algoVisible(m_useProcessAlgo);
   m_useProcessScript = ui.radProcessScript->isChecked();
@@ -262,47 +277,46 @@ void StartLiveDataDialog::radioProcessClicked()
 
 //------------------------------------------------------------------------------
 /** Slot called when one of the radio buttons in "processing" are picked */
-void StartLiveDataDialog::radioPostProcessClicked()
-{
+void StartLiveDataDialog::radioPostProcessClicked() {
   m_usePostProcessAlgo = ui.radPostProcessAlgorithm->isChecked();
   ui.postAlgo->algoVisible(m_usePostProcessAlgo);
   m_usePostProcessScript = ui.radPostProcessScript->isChecked();
   ui.postAlgo->editorVisible(m_usePostProcessScript);
   // Disable the AccumulationWorkspace widget unless it is needed
-  ui.editAccumulationWorkspace->setEnabled(m_usePostProcessAlgo || m_usePostProcessScript);
-  ui.lblAccumulationWorkspace->setEnabled(m_usePostProcessAlgo || m_usePostProcessScript);
+  ui.editAccumulationWorkspace->setEnabled(m_usePostProcessAlgo ||
+                                           m_usePostProcessScript);
+  ui.lblAccumulationWorkspace->setEnabled(m_usePostProcessAlgo ||
+                                          m_usePostProcessScript);
 }
 
 //------------------------------------------------------------------------------
 /** Slot called when one of the radio buttons in "starting time" are picked */
-void StartLiveDataDialog::radioTimeClicked()
-{
-  ui.dateTimeEdit->setEnabled( ui.radAbsoluteTime->isChecked() );
+void StartLiveDataDialog::radioTimeClicked() {
+  ui.dateTimeEdit->setEnabled(ui.radAbsoluteTime->isChecked());
 }
 
 /** Slot called when the preserve events checkbox changes */
-void StartLiveDataDialog::chkPreserveEventsToggled()
-{
-  ui.lblPreserveEventsWarning->setVisible( ui.chkPreserveEvents->isChecked());
+void StartLiveDataDialog::chkPreserveEventsToggled() {
+  ui.lblPreserveEventsWarning->setVisible(ui.chkPreserveEvents->isChecked());
 }
 
 //------------------------------------------------------------------------------
 /** Slot called when picking a different algorithm
  * in the AlgorithmSelectorWidget */
-void StartLiveDataDialog::changeProcessingAlgorithm()
-{
+void StartLiveDataDialog::changeProcessingAlgorithm() {
   Algorithm_sptr alg = ui.processingAlgo->getAlgorithm();
-  if (!alg) return;
+  if (!alg)
+    return;
   m_processingAlg = alg;
 }
 
 //------------------------------------------------------------------------------
 /** Slot called when picking a different algorithm
  * in the AlgorithmSelectorWidget */
-void StartLiveDataDialog::changePostProcessingAlgorithm()
-{
+void StartLiveDataDialog::changePostProcessingAlgorithm() {
   Algorithm_sptr alg = ui.postAlgo->getAlgorithm();
-  if (!alg) return;
+  if (!alg)
+    return;
   m_postProcessingAlg = alg;
 }
 
@@ -311,22 +325,24 @@ void StartLiveDataDialog::changePostProcessingAlgorithm()
  *  Disables the 'Add' option if the listener is going to pass back histograms.
  *  @param inst :: The instrument name.
  */
-void StartLiveDataDialog::setDefaultAccumulationMethod(const QString& inst)
-{
-  if ( inst.isEmpty() ) return;
-  try
-  {
+void StartLiveDataDialog::setDefaultAccumulationMethod(const QString &inst) {
+  if (inst.isEmpty())
+    return;
+  try {
     // Make sure 'Add' is enabled ahead of the check (the check may throw)
     int addIndex = ui.cmbAccumulationMethod->findText("Add");
-    ui.cmbAccumulationMethod->setItemData(addIndex, QVariant(Qt::ItemIsSelectable | Qt::ItemIsEnabled), Qt::UserRole - 1);
+    ui.cmbAccumulationMethod->setItemData(
+        addIndex, QVariant(Qt::ItemIsSelectable | Qt::ItemIsEnabled),
+        Qt::UserRole - 1);
 
-    // Check whether this listener will give back events. If not, disable 'Add' as an option
+    // Check whether this listener will give back events. If not, disable 'Add'
+    // as an option
     // The 'false' 2nd argument means don't connect the created listener
-    if ( ! Mantid::API::LiveListenerFactory::Instance().create(inst.toStdString(),false)->buffersEvents() )
-    {
+    if (!Mantid::API::LiveListenerFactory::Instance()
+             .create(inst.toStdString(), false)
+             ->buffersEvents()) {
       // If 'Add' is currently selected, select 'Replace' instead
-      if ( ui.cmbAccumulationMethod->currentIndex() == addIndex )
-      {
+      if (ui.cmbAccumulationMethod->currentIndex() == addIndex) {
         ui.cmbAccumulationMethod->setItemText(-1, "Replace");
       }
       // Disable the 'Add' option in the combobox. It just wouldn't make sense.
@@ -334,9 +350,9 @@ void StartLiveDataDialog::setDefaultAccumulationMethod(const QString& inst)
     }
   }
   // If an exception is thrown, just swallow it and do nothing
-  // getInstrument can throw, particularly while we allow listener names to be passed in directly
-  catch( Mantid::Kernel::Exception::NotFoundError& )
-  {
+  // getInstrument can throw, particularly while we allow listener names to be
+  // passed in directly
+  catch (Mantid::Kernel::Exception::NotFoundError &) {
   }
 }
 
@@ -347,48 +363,39 @@ void StartLiveDataDialog::setDefaultAccumulationMethod(const QString& inst)
  *  "Starting Time" group.
  *  @param inst :: The instrument name.
  */
-void StartLiveDataDialog::updateUiElements(const QString& inst)
-{
-  if ( inst.isEmpty() ) return;
-  try
-  {
-    if (inst == "TOPAZ")
-    {
-      ui.groupBox->setEnabled( false);
-      ui.radNow->setChecked( true);  
+void StartLiveDataDialog::updateUiElements(const QString &inst) {
+  if (inst.isEmpty())
+    return;
+  try {
+    if (inst == "TOPAZ") {
+      ui.groupBox->setEnabled(false);
+      ui.radNow->setChecked(true);
+    } else {
+      ui.groupBox->setEnabled(true);
     }
-    else
-    {
-      ui.groupBox->setEnabled( true);
-    }        
-  }  
+  }
   // If an exception is thrown, just swallow it and do nothing
-  // getInstrument can throw, particularly while we allow listener names to be passed in directly
-  catch( Mantid::Kernel::Exception::NotFoundError& )
-  {
+  // getInstrument can throw, particularly while we allow listener names to be
+  // passed in directly
+  catch (Mantid::Kernel::Exception::NotFoundError &) {
   }
 }
 
-
-
-void StartLiveDataDialog::accept()
-{
+void StartLiveDataDialog::accept() {
   // Now manually set the StartTime property as there's a computation needed
-  DateAndTime startTime = DateAndTime::getCurrentTime() - ui.dateTimeEdit->value()*60.0;
-  m_algorithm->setPropertyValue("StartTime",startTime.toISO8601String());
+  DateAndTime startTime =
+      DateAndTime::getCurrentTime() - ui.dateTimeEdit->value() * 60.0;
+  m_algorithm->setPropertyValue("StartTime", startTime.toISO8601String());
 
   AlgorithmDialog::accept(); // accept executes the algorithm
 }
 
-void StartLiveDataDialog::initListenerPropLayout(const QString& inst)
-{
+void StartLiveDataDialog::initListenerPropLayout(const QString &inst) {
   // remove previous listener's properties
   auto props = m_algorithm->getPropertiesInGroup("ListenerProperties");
-  for(auto prop = props.begin(); prop != props.end(); ++prop)
-  {
+  for (auto prop = props.begin(); prop != props.end(); ++prop) {
     QString propName = QString::fromStdString((**prop).name());
-    if ( m_algProperties.contains( propName ) )
-    {
+    if (m_algProperties.contains(propName)) {
       m_algProperties.removeAll(propName);
     }
   }
@@ -397,16 +404,12 @@ void StartLiveDataDialog::initListenerPropLayout(const QString& inst)
   m_algorithm->setPropertyValue("Instrument", inst.toStdString());
   // create or clear the layout
   QLayout *layout = ui.listenerProps->layout();
-  if ( !layout )
-  {
+  if (!layout) {
     QGridLayout *listenerPropLayout = new QGridLayout(ui.listenerProps);
     layout = listenerPropLayout;
-  }
-  else
-  {
+  } else {
     QLayoutItem *child;
-    while ((child = layout->takeAt(0)) != NULL)  
-    {
+    while ((child = layout->takeAt(0)) != NULL) {
       child->widget()->close();
       delete child;
     }
@@ -416,31 +419,25 @@ void StartLiveDataDialog::initListenerPropLayout(const QString& inst)
   props = m_algorithm->getPropertiesInGroup("ListenerProperties");
 
   // no properties - don't show the box
-  if ( props.empty() )
-  {
+  if (props.empty()) {
     ui.listenerProps->setVisible(false);
     return;
   }
-  
-  auto gridLayout = static_cast<QGridLayout*>( layout );
+
+  auto gridLayout = static_cast<QGridLayout *>(layout);
   // add widgets for the listener's properties
-  for(auto prop = props.begin(); prop != props.end(); ++prop)
-  {
-    int row = static_cast<int>(std::distance( props.begin(), prop ));
+  for (auto prop = props.begin(); prop != props.end(); ++prop) {
+    int row = static_cast<int>(std::distance(props.begin(), prop));
     QString propName = QString::fromStdString((**prop).name());
-    gridLayout->addWidget( new QLabel(propName), row, 0 );
+    gridLayout->addWidget(new QLabel(propName), row, 0);
     QLineEdit *propWidget = new QLineEdit();
-    gridLayout->addWidget( propWidget, row, 1 );
-    if ( !m_algProperties.contains( propName ) )
-    {
-      m_algProperties.append( propName );
+    gridLayout->addWidget(propWidget, row, 1);
+    if (!m_algProperties.contains(propName)) {
+      m_algProperties.append(propName);
     }
     tie(propWidget, propName, gridLayout);
   }
   ui.listenerProps->setVisible(true);
-
 }
-
-
 }
 }
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
index a35a31c79cb62db9740fe4ab6f2a6b72f05a853c..a00701a402ab5d241d259636cb67c27d048f0ea0 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
@@ -12,42 +12,38 @@
 class QShowEvent;
 class QCloseEvent;
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-
-    class Background : public API::MantidDialog
-    {
-      Q_OBJECT
-
-    public:
-      Background(QWidget *parent = NULL);
-      
-      bool removeBackground() const;
-      void removeBackground(bool remove);
-      QPair<double, double> getRange() const;
-      void setRange(double min, double max);
-      
-    private:
-      void initLayout();
-      void showEvent(QShowEvent *) override;
-      void closeEvent(QCloseEvent *) override;
-      bool sanityCheck();
-    
-    private:
-      QCheckBox *m_ckDoRemove;
-      QLineEdit *m_leStart;
-      QLineEdit *m_leEnd;
-
-      /// Actual values for analysis, stored separately so that the dialog can be reverted
-      double m_rangeMin;
-      double m_rangeMax;
-      bool m_doRemoval;
-
-    };
-
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+
+class Background : public API::MantidDialog {
+  Q_OBJECT
+
+public:
+  Background(QWidget *parent = NULL);
+
+  bool removeBackground() const;
+  void removeBackground(bool remove);
+  QPair<double, double> getRange() const;
+  void setRange(double min, double max);
+
+private:
+  void initLayout();
+  void showEvent(QShowEvent *) override;
+  void closeEvent(QCloseEvent *) override;
+  bool sanityCheck();
+
+private:
+  QCheckBox *m_ckDoRemove;
+  QLineEdit *m_leStart;
+  QLineEdit *m_leEnd;
+
+  /// Actual values for analysis, stored separately so that the dialog can be
+  /// reverted
+  double m_rangeMin;
+  double m_rangeMax;
+  bool m_doRemoval;
+};
+}
 }
 
 #endif // MANTIDQTCUSTOMINTERFACES_BACKGROUND_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DataComparison.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DataComparison.h
index b5891c43c69c9a7e05d995a21b3659ecfe73b5c9..218b86470d3cf61d5e938626d1e3ddffa0217b28 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DataComparison.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DataComparison.h
@@ -15,106 +15,95 @@
 #include <qwt_plot_panner.h>
 #include <qwt_plot_zoomer.h>
 
-
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  class DataComparison : public MantidQt::API::UserSubWindow, public MantidQt::API::WorkspaceObserver
-  {
-    Q_OBJECT
-
-  public:
-    /// The name of the interface as registered into the factory
-    static std::string name() { return "Data Comparison"; }
-    // This interface's categories.
-    static QString categoryInfo() { return "General"; }
-
-  public:
-    /// Default Constructor
-    DataComparison(QWidget *parent = 0);
-
-    /// Tests if a workspace is shown in the UI
-    bool containsWorkspace(Mantid::API::MatrixWorkspace_const_sptr ws);
-
-  private slots:
-    /// Add selected data to plot
-    void addData();
-    /// Remove selected data from plot
-    void removeSelectedData();
-    /// Remove all data from plot
-    void removeAllData();
-    /// Create a diff of the two selected workspaces
-    void diffSelected();
-    /// Remove the diff from the plot
-    void clearDiff();
-    /// Handles replotting workspace spectra
-    void plotWorkspaces();
-    /// Handles updating the plot
-    void updatePlot();
-    /// Handles updating th eplot after a spectum index is changed
-    void workspaceIndexChanged();
-    /// Handles creating and plotting a diff worksapce
-    void plotDiffWorkspace();
-    /// Toggle the pan plot tool
-    void togglePan(bool enabled);
-    /// Toggle the zoom plot tool
-    void toggleZoom(bool enabled);
-    /// Resets the zoom level to show all curves
-    void resetView();
-
-  private:
-    /// Enumeration for column index
-    enum Column
-    {
-      COLOUR,
-      WORKSPACE_NAME,
-      SPEC_OFFSET,
-      CURRENT_SPEC
-    };
-
-    /// Initialize the layout
-    void initLayout() override;
-    /// Adds a workspace to the data table
-    void addDataItem(Mantid::API::Workspace_const_sptr ws);
-    /// Normalises spectra offsets in table
-    void normaliseSpectraOffsets();
-    /// Gets an initial curve colour for a new workspace
-    int getInitialColourIndex();
-
-  private:
-    // Handlers for ADS events
-    void preDeleteHandle(
-        const std::string &wsName,
-        const boost::shared_ptr<Mantid::API::Workspace> ws) override;
-    void renameHandle(const std::string &oldName,
-                      const std::string &newName) override;
-    void afterReplaceHandle(
-        const std::string &wsName,
-        const boost::shared_ptr<Mantid::API::Workspace> ws) override;
-
-    // The form generated by Qt Designer
-    Ui::DataComparison m_uiForm;
-
-    // The plot object
-    QwtPlot *m_plot;
-    // Curves shown on plot, indexed by workspace name
-    QMap<QString, boost::shared_ptr<QwtPlotCurve>> m_curves;
-
-    // Plot zoom tool
-    QwtPlotZoomer *m_zoomTool;
-    // Plot pan tool
-    QwtPlotPanner *m_panTool;
-    // Plot magnify tool
-    QwtPlotMagnifier *m_magnifyTool;
-
-    boost::shared_ptr<QwtPlotCurve> m_diffCurve;
-    // The two workspaces that are currently being diffed
-    QPair<QString, QString> m_diffWorkspaceNames;
-
-  };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+class DataComparison : public MantidQt::API::UserSubWindow,
+                       public MantidQt::API::WorkspaceObserver {
+  Q_OBJECT
+
+public:
+  /// The name of the interface as registered into the factory
+  static std::string name() { return "Data Comparison"; }
+  // This interface's categories.
+  static QString categoryInfo() { return "General"; }
+
+public:
+  /// Default Constructor
+  DataComparison(QWidget *parent = 0);
+
+  /// Tests if a workspace is shown in the UI
+  bool containsWorkspace(Mantid::API::MatrixWorkspace_const_sptr ws);
+
+private slots:
+  /// Add selected data to plot
+  void addData();
+  /// Remove selected data from plot
+  void removeSelectedData();
+  /// Remove all data from plot
+  void removeAllData();
+  /// Create a diff of the two selected workspaces
+  void diffSelected();
+  /// Remove the diff from the plot
+  void clearDiff();
+  /// Handles replotting workspace spectra
+  void plotWorkspaces();
+  /// Handles updating the plot
+  void updatePlot();
+  /// Handles updating th eplot after a spectum index is changed
+  void workspaceIndexChanged();
+  /// Handles creating and plotting a diff worksapce
+  void plotDiffWorkspace();
+  /// Toggle the pan plot tool
+  void togglePan(bool enabled);
+  /// Toggle the zoom plot tool
+  void toggleZoom(bool enabled);
+  /// Resets the zoom level to show all curves
+  void resetView();
+
+private:
+  /// Enumeration for column index
+  enum Column { COLOUR, WORKSPACE_NAME, SPEC_OFFSET, CURRENT_SPEC };
+
+  /// Initialize the layout
+  void initLayout() override;
+  /// Adds a workspace to the data table
+  void addDataItem(Mantid::API::Workspace_const_sptr ws);
+  /// Normalises spectra offsets in table
+  void normaliseSpectraOffsets();
+  /// Gets an initial curve colour for a new workspace
+  int getInitialColourIndex();
+
+private:
+  // Handlers for ADS events
+  void
+  preDeleteHandle(const std::string &wsName,
+                  const boost::shared_ptr<Mantid::API::Workspace> ws) override;
+  void renameHandle(const std::string &oldName,
+                    const std::string &newName) override;
+  void afterReplaceHandle(
+      const std::string &wsName,
+      const boost::shared_ptr<Mantid::API::Workspace> ws) override;
+
+  // The form generated by Qt Designer
+  Ui::DataComparison m_uiForm;
+
+  // The plot object
+  QwtPlot *m_plot;
+  // Curves shown on plot, indexed by workspace name
+  QMap<QString, boost::shared_ptr<QwtPlotCurve>> m_curves;
+
+  // Plot zoom tool
+  QwtPlotZoomer *m_zoomTool;
+  // Plot pan tool
+  QwtPlotPanner *m_panTool;
+  // Plot magnify tool
+  QwtPlotMagnifier *m_magnifyTool;
+
+  boost::shared_ptr<QwtPlotCurve> m_diffCurve;
+  // The two workspaces that are currently being diffed
+  QPair<QString, QString> m_diffWorkspaceNames;
+};
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_DATACOMPARISON_H_
+#endif // MANTIDQTCUSTOMINTERFACES_DATACOMPARISON_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DirectConvertToEnergy.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DirectConvertToEnergy.h
index fad56bdbd2a6377643f96357cb218a80969c6c81..3a74051cd795d31c9eb4edcd5e18c467c2c66ab6 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DirectConvertToEnergy.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DirectConvertToEnergy.h
@@ -8,106 +8,105 @@
 #include "MantidQtAPI/AlgorithmRunner.h"
 #include "MantidQtAPI/UserSubWindow.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    //-------------------------------------------
-    // Forward declarations
-    //-------------------------------------------
-    class Homer;
-
-    /** 
-    This class defines the DirectConvertToEnergy interface. It handles the overall instrument settings
-    and sets up the appropriate interface depending on the deltaE mode of the instrument. The deltaE
-    mode is defined in the instrument definition file using the "deltaE-mode".    
-
-    @author Martyn Gigg, Tessella Support Services plc
-    @author Michael Whitty
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-
-    class DirectConvertToEnergy : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-    public: // public constants, ennumerations and types
-      enum DeltaEMode { Direct, InDirect, Undefined};
-
-    public: // public constructor, destructor and functions
-      /// Default Constructor
-      DirectConvertToEnergy(QWidget *parent = 0);
-      ///Destructor
-      ~DirectConvertToEnergy() override;
-      /// Interface name
-      static std::string name() { return "Convert To Energy (Direct)"; }
-      /// Aliases for this interface
-      static std::set<std::string> aliases()
-      { 
-        std::set<std::string> aliasList;
-        aliasList.insert("Homer");
-        return aliasList;
-      }
-      // This interface's categories.
-      static QString categoryInfo() { return "Direct"; }
-
-    private slots:
-      void helpClicked();
-      void runClicked();
-      void instrumentLoadingDone(bool error);
-
-    private: // private functions (and slots)
-      /// Initialize the layout
-      void initLayout() override;
-      void initLocalPython() override;
-      void readSettings();
-      void saveSettings();
-      void setDefaultInstrument(const QString & name);
-      void instrumentSelectChanged(const QString& name);
-      ///// Find path to instrument's _Definition.xml file (and check there is a parameter file).
-      //QString getIDFPath(const QString& prefix);
-      /// Find the DeltaEMode (Direct or Indirect) of the instrument.
-      DeltaEMode instrumentDeltaEMode(const QString& defFile);
-
-    private slots:
-      void userSelectInstrument(const QString& name);
-      void openDirectoryDialog();
-
-    private: // member variables
-      /// The .ui form generated by Qt Designer
-      Ui::DirectConvertToEnergy m_uiForm;
-      /// Direct Instruments interface object
-      Homer *m_directInstruments;
-      /// Instrument the interface is currently set for.
-      QString m_curInterfaceSetup;
-      /// "DeltaE-mode" of the current instrument.
-      DeltaEMode m_curEmodeType;
-      /// The settings group
-      QString m_settingsGroup;
-      /// Runner for insturment load algorithm
-      MantidQt::API::AlgorithmRunner* m_algRunner;
-    };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+//-------------------------------------------
+// Forward declarations
+//-------------------------------------------
+class Homer;
+
+/**
+This class defines the DirectConvertToEnergy interface. It handles the overall
+instrument settings
+and sets up the appropriate interface depending on the deltaE mode of the
+instrument. The deltaE
+mode is defined in the instrument definition file using the "deltaE-mode".
+
+@author Martyn Gigg, Tessella Support Services plc
+@author Michael Whitty
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class DirectConvertToEnergy : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public: // public constants, ennumerations and types
+  enum DeltaEMode { Direct, InDirect, Undefined };
+
+public: // public constructor, destructor and functions
+  /// Default Constructor
+  DirectConvertToEnergy(QWidget *parent = 0);
+  /// Destructor
+  ~DirectConvertToEnergy() override;
+  /// Interface name
+  static std::string name() { return "Convert To Energy (Direct)"; }
+  /// Aliases for this interface
+  static std::set<std::string> aliases() {
+    std::set<std::string> aliasList;
+    aliasList.insert("Homer");
+    return aliasList;
   }
+  // This interface's categories.
+  static QString categoryInfo() { return "Direct"; }
+
+private slots:
+  void helpClicked();
+  void runClicked();
+  void instrumentLoadingDone(bool error);
+
+private: // private functions (and slots)
+  /// Initialize the layout
+  void initLayout() override;
+  void initLocalPython() override;
+  void readSettings();
+  void saveSettings();
+  void setDefaultInstrument(const QString &name);
+  void instrumentSelectChanged(const QString &name);
+  ///// Find path to instrument's _Definition.xml file (and check there is a
+  /// parameter file).
+  // QString getIDFPath(const QString& prefix);
+  /// Find the DeltaEMode (Direct or Indirect) of the instrument.
+  DeltaEMode instrumentDeltaEMode(const QString &defFile);
+
+private slots:
+  void userSelectInstrument(const QString &name);
+  void openDirectoryDialog();
+
+private: // member variables
+  /// The .ui form generated by Qt Designer
+  Ui::DirectConvertToEnergy m_uiForm;
+  /// Direct Instruments interface object
+  Homer *m_directInstruments;
+  /// Instrument the interface is currently set for.
+  QString m_curInterfaceSetup;
+  /// "DeltaE-mode" of the current instrument.
+  DeltaEMode m_curEmodeType;
+  /// The settings group
+  QString m_settingsGroup;
+  /// Runner for insturment load algorithm
+  MantidQt::API::AlgorithmRunner *m_algRunner;
+};
+}
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
+#endif // MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DllConfig.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DllConfig.h
index 0ac41e522ba2405421a278e7f2cb4b718c5177fd..b2a8a6eb63d570295ca32d50d5c4752601cbc136 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DllConfig.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DllConfig.h
@@ -3,11 +3,12 @@
 
 #include "MantidKernel/System.h"
 
-/*  
-    This file contains the DLLExport/DLLImport linkage configuration for the 
+/*
+    This file contains the DLLExport/DLLImport linkage configuration for the
     MantidQt CustomInterfaces library
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -23,7 +24,7 @@
 
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
-    
+
     File change history is stored at: <https://github.com/mantidproject/mantid>.
     Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFBackgroundRemover.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFBackgroundRemover.h
index de47ebabbe193f859cdb2276aca5e3ed734f0a37..4dddab8393625533163a444ca5f02ea091cbb610 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFBackgroundRemover.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFBackgroundRemover.h
@@ -1,27 +1,27 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_BACKGROUNDREMOVER_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_BACKGROUNDREMOVER_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "ui_DPDFBackgroundRemover.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidQtCustomInterfaces/DllConfig.h"
 #include "MantidQtAPI/UserSubWindow.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QDialog>
 #include <boost/shared_ptr.hpp>
 
 // Class forward declarations
 namespace MantidQt {
-  namespace CustomInterfaces {
-    namespace DynamicPDF {
-      class InputDataControl;
-      class SliceSelector;
-      class DisplayControl;
-      class FitControl;
-      class FourierTrasform;
-    }
-  }
+namespace CustomInterfaces {
+namespace DynamicPDF {
+class InputDataControl;
+class SliceSelector;
+class DisplayControl;
+class FitControl;
+class FourierTrasform;
+}
+}
 }
 
 namespace MantidQt {
@@ -53,8 +53,8 @@ namespace DynamicPDF {
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MANTIDQT_CUSTOMINTERFACES_DLL BackgroundRemover: public MantidQt::API::UserSubWindow
-{
+class MANTIDQT_CUSTOMINTERFACES_DLL BackgroundRemover
+    : public MantidQt::API::UserSubWindow {
   Q_OBJECT
 
 public:
@@ -83,7 +83,6 @@ private:
   FitControl *m_fitControl;
   FourierTransform *m_fourierTransform;
 };
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFDisplayControl.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFDisplayControl.h
index 34f04efb3dd68cb0324fac0c041a80ae52d9aed0..b4b30b5c3dcb57c9dc92af45320649203f7562d5 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFDisplayControl.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFDisplayControl.h
@@ -1,24 +1,24 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_DISPLAYCONTROL_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_DISPLAYCONTROL_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
-//Mantid headers from other projects
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
+// Mantid headers from other projects
 #include "MantidQtCustomInterfaces/DllConfig.h"
 #include "MantidAPI/MatrixWorkspace.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QObject>
-//system headers
+// system headers
 
 // Class forward declarations
 namespace MantidQt {
 namespace MantidWidgets {
-  class DisplayCurveFit;
-  class RangeSelector;
+class DisplayCurveFit;
+class RangeSelector;
 }
 namespace CustomInterfaces {
 namespace DynamicPDF {
-  class InputDataControl;
+class InputDataControl;
 }
 }
 }
@@ -57,10 +57,10 @@ class MANTIDQT_CUSTOMINTERFACES_DLL DisplayControl : public QObject {
 
 public:
   DisplayControl(InputDataControl *inputDataControl,
-    MantidQt::MantidWidgets::DisplayCurveFit *displayModelFit);
+                 MantidQt::MantidWidgets::DisplayCurveFit *displayModelFit);
   ~DisplayControl();
   void init();
-  std::pair<double,double> getFitMinMax();
+  std::pair<double, double> getFitMinMax();
   void setFitMin(const double &);
   void setFitMax(const double &);
 
@@ -85,12 +85,8 @@ private:
   const std::string m_dataShownName;
 
 }; // class DisplayControl
-
-
-
 }
 }
 }
 
-
 #endif // MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_INPUTDATACONTROL_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h
index 290ae2b544c92214acf120ca8f7da99fc4789b4f..47eb9a29cd10929bab2f3f490529e2e7625178f0 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h
@@ -1,38 +1,38 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_FITCONTROL_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_FITCONTROL_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "ui_DPDFFitControl.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidAPI/IFunction.h"
 #include "MantidQtCustomInterfaces/DllConfig.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QWidget>
-//System headers
+// System headers
 
 // Forward Declarations
 class QAction;
 class QMenu;
 namespace Mantid {
 namespace API {
-  class IFunction;
+class IFunction;
 }
 }
 namespace MantidQt {
 namespace API {
- class AlgorithmRunner;
+class AlgorithmRunner;
 }
 namespace MantidWidgets {
-  class FunctionBrowser;
-  class FitOptionsBrowser;
+class FunctionBrowser;
+class FitOptionsBrowser;
 }
 namespace CustomInterfaces {
 namespace DynamicPDF {
-  class BackgroundRemover;
-  class DPDFFitOptionsBrowser;
-  class InputDataControl;
-  class DisplayControl;
+class BackgroundRemover;
+class DPDFFitOptionsBrowser;
+class InputDataControl;
+class DisplayControl;
 }
 }
 }
@@ -67,9 +67,9 @@ namespace DynamicPDF {
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 class MANTIDQT_CUSTOMINTERFACES_DLL FitControl : public QWidget {
-Q_OBJECT
+  Q_OBJECT
 
-friend class BackgroundRemover;
+  friend class BackgroundRemover;
 
 public:
   FitControl(QWidget *parent = nullptr);
@@ -103,10 +103,10 @@ private:
   void setDisplayControl(DisplayControl *displayControl);
   void fitSequential();
   void fitSimultaneous();
-  void fitIndividual(const bool &isEvaluation=false);
+  void fitIndividual(const bool &isEvaluation = false);
   void updateFunctionBrowser(Mantid::API::IFunction_sptr fun);
   void updateFunctionBrowser(const QString &directory,
-    const QString &modelName);
+                             const QString &modelName);
   void initBuiltInModels();
   void saveBuiltInModels();
   void loadBuiltInModels(QMenu *menuBuiltIn);
@@ -130,8 +130,7 @@ private:
   /// Workspace root name for model evaluation
   const std::string m_modelEvaluationName;
 
-};  // class FitControl
-
+}; // class FitControl
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h
index bef943c2e27d1849b5bebfb7434516fdb8fca9d9..cfdf81f83df2b725e3c85d10383ffa4a8a312629 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h
@@ -1,13 +1,13 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_DPDFFITOPTIONSBROWSER_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_DPDFFITOPTIONSBROWSER_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
-//Mantid headers from other projects
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
+// Mantid headers from other projects
 #include "MantidQtMantidWidgets/FitOptionsBrowser.h"
 #include "MantidQtCustomInterfaces/DllConfig.h"
-//3rd party library headers
-//System headers
+// 3rd party library headers
+// System headers
 
 namespace MantidQt {
 namespace CustomInterfaces {
@@ -40,10 +40,10 @@ namespace DynamicPDF {
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MANTIDQT_CUSTOMINTERFACES_DLL DPDFFitOptionsBrowser:
-  public MantidQt::MantidWidgets::FitOptionsBrowser {
+class MANTIDQT_CUSTOMINTERFACES_DLL DPDFFitOptionsBrowser
+    : public MantidQt::MantidWidgets::FitOptionsBrowser {
 
-Q_OBJECT
+  Q_OBJECT
 
 public:
   DPDFFitOptionsBrowser(QWidget *parent = NULL);
@@ -52,14 +52,9 @@ private:
   void createAdditionalProperties();
   void customizeBrowser();
   /// Starting fitting range
-  QtProperty* m_startX;
+  QtProperty *m_startX;
   /// Ending fitting range
-  QtProperty* m_endX;
-
-
-
-
-
+  QtProperty *m_endX;
 
 }; // class DPDFFitOptionsBrowser
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFourierTransform.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFourierTransform.h
index 50315c626b52f9b5e33cd502f89440ddf6f37cdd..5641ca12480cfec96fa631e6633af4654746f53b 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFourierTransform.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFFourierTransform.h
@@ -1,16 +1,16 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_FOURIERTRANSFORM_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_FOURIERTRANSFORM_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "ui_DPDFFourierTransform.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidQtCustomInterfaces/DllConfig.h"
 #include "DoubleEditorFactory.h"
 #include "qteditorfactory.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QWidget>
-//System headers
+// System headers
 
 // Forward declarations
 class QtProperty;
@@ -23,13 +23,13 @@ class QSettings;
 
 namespace MantidQt {
 namespace API {
-  class AlgorithmRunner;
+class AlgorithmRunner;
 }
 namespace CustomInterfaces {
 namespace DynamicPDF {
-  class BackgroundRemover;
-  class InputDataControl;
-  class FitControl;
+class BackgroundRemover;
+class InputDataControl;
+class FitControl;
 }
 }
 }
@@ -66,9 +66,9 @@ namespace DynamicPDF {
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 class MANTIDQT_CUSTOMINTERFACES_DLL FourierTransform : public QWidget {
-Q_OBJECT
+  Q_OBJECT
 
-friend class BackgroundRemover;
+  friend class BackgroundRemover;
 
 public:
   FourierTransform(QWidget *parent = nullptr);
@@ -102,7 +102,7 @@ private:
   /// object generated from the Qt -designer form
   Ui::FourierTransform m_uiForm;
   /// widget displaying properties for algorithm PDFFourierTransform
-  QtTreePropertyBrowser* m_propertyTree;
+  QtTreePropertyBrowser *m_propertyTree;
   /// handy map to get a pointer to any property
   QMap<QString, QtProperty *> m_properties;
   /// Precision of doubles in m_doubleManager
@@ -114,13 +114,13 @@ private:
   /// Associate a color to each type of transform
   QMap<QString, QColor> m_colors;
   /// Manager for double properties
-  QtDoublePropertyManager* m_doubleManager;
+  QtDoublePropertyManager *m_doubleManager;
   /// Manager for bool properties
-  QtBoolPropertyManager* m_boolManager;
+  QtBoolPropertyManager *m_boolManager;
   /// Manager for the string list properties
-  QtEnumPropertyManager* m_enumManager;
+  QtEnumPropertyManager *m_enumManager;
   /// Manager for groups of properties
-  QtGroupPropertyManager* m_groupManager;
+  QtGroupPropertyManager *m_groupManager;
   /// Fit algorithm runner
   std::unique_ptr<MantidQt::API::AlgorithmRunner> m_algorithmRunner;
 }; // class FourierTransform
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h
index ddc9598fba8af28e2b9eb6f9c23afdf95ce9b016..29bea7963ece9f0437fc7550fef6109f6de20075 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h
@@ -1,20 +1,20 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_INPUTDATACONTROL_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_INPUTDATACONTROL_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
-//Mantid headers from other projects
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
+// Mantid headers from other projects
 #include "MantidAPI/AnalysisDataService.h"
 #include "MantidQtCustomInterfaces/DllConfig.h"
 #include "MantidAPI/MatrixWorkspace.h"
 #include "MantidQtAPI/WorkspaceObserver.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QObject>
-//system headers
+// system headers
 
 // Class forward declarations
 namespace MantidAPI {
-  class MatrixWorkspace;
+class MatrixWorkspace;
 }
 
 namespace MantidQt {
@@ -48,9 +48,9 @@ namespace DynamicPDF {
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MANTIDQT_CUSTOMINTERFACES_DLL InputDataControl :
-  public QObject,
-  public MantidQt::API::WorkspaceObserver {
+class MANTIDQT_CUSTOMINTERFACES_DLL InputDataControl
+    : public QObject,
+      public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 
 public:
@@ -63,11 +63,12 @@ public:
   std::string getWorkspaceName();
   size_t getWorkspaceIndex();
   bool isSliceSelectedForFitting();
-  std::pair<double,double> getCurrentRange();
-    
+  std::pair<double, double> getCurrentRange();
+
 protected:
-  void preDeleteHandle(const std::string &workspaceName,
-    const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
+  void preDeleteHandle(
+      const std::string &workspaceName,
+      const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
 
 signals:
   void signalWorkspaceUpdated();
@@ -85,13 +86,11 @@ private:
   size_t m_selectedWorkspaceIndex;
   /// energy range for each slice with non-zero signal. We use the
   /// the indexes along the Energy range
-  std::vector<std::pair<int,int>> m_domain;
+  std::vector<std::pair<int, int>> m_domain;
 
 }; // class InputDataControl
-
 }
 }
 }
 
-
 #endif // MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_INPUTDATACONTROL_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DisplayCurveFitTest.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DisplayCurveFitTest.h
index 9920485f20595b354fad6a7fd19cdb6a9dac8a30..6a6d07531fdae39562e4d4ad3ff5b82a57b9e773 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DisplayCurveFitTest.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/DisplayCurveFitTest.h
@@ -54,7 +54,8 @@ private slots:
 
 private:
   void initLayout() override;
-  /// The object containing the widgets defined in the form created in Qt Designer
+  /// The object containing the widgets defined in the form created in Qt
+  /// Designer
   Ui::DisplayCurveFitTest m_uiForm;
 
 }; // class DisplayCurveFitTest
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/SliceSelector.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/SliceSelector.h
index 2d5e7bac045c479fc72d859d0f8b61ef9147d209..27574472ed23f3d9b9ad51458c905722ae0462f7 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/SliceSelector.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/DynamicPDF/SliceSelector.h
@@ -1,10 +1,10 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_SLICESELECTOR_H_
 #define MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_SLICESELECTOR_H_
 
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "ui_SliceSelector.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidAPI/MatrixWorkspace.h"
 #include "MantidQtAPI/WorkspaceObserver.h"
 // includes for interface
@@ -12,14 +12,14 @@
 #include "MantidQtAPI/UserSubWindow.h"
 #include <QMainWindow>
 
-//3rd party library headers
+// 3rd party library headers
 #include <qwt_plot_spectrogram.h>
 
 // Forward Declarations
 namespace MantidQt {
 namespace MantidWidgets {
-  class MWView;
-  class RangeSelector;
+class MWView;
+class RangeSelector;
 }
 }
 
@@ -28,13 +28,13 @@ namespace CustomInterfaces {
 namespace DynamicPDF {
 
 /// Helper class containing pointer and some metadata for the loaded workspace
-class WorkspaceRecord{
+class WorkspaceRecord {
 
 public:
   WorkspaceRecord(const std::string &workspaceName);
   ~WorkspaceRecord();
   void updateMetadata(const size_t &newIndex);
-  std::pair<double,double> getErange();
+  std::pair<double, double> getErange();
 
   boost::shared_ptr<Mantid::API::MatrixWorkspace> m_ws;
   const std::string m_name;
@@ -42,9 +42,8 @@ public:
   std::string m_label;
 };
 
-class SliceSelector :
-  public QMainWindow,
-  public MantidQt::API::WorkspaceObserver {
+class SliceSelector : public QMainWindow,
+                      public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 
 public:
@@ -52,8 +51,9 @@ public:
   ~SliceSelector();
 
 protected:
-  void preDeleteHandle(const std::string &workspaceName,
-    const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
+  void preDeleteHandle(
+      const std::string &workspaceName,
+      const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
 
 signals:
   void signalSlicesLoaded(const QString &workspaceName);
@@ -85,9 +85,8 @@ private:
   std::unique_ptr<WorkspaceRecord> m_loadedWorkspace;
   size_t m_selectedWorkspaceIndex;
 
-}; //class SliceSelector
-
+}; // class SliceSelector
 }
 }
 }
-#endif //MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_SLICESELECTOR_H_
+#endif // MANTIDQTCUSTOMINTERFACES_DYNAMICPDF_SLICESELECTOR_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/EnggDiffraction/EnggDiffractionPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/EnggDiffraction/EnggDiffractionPresenter.h
index 23f1a94e9441a2d76a9f6c4bf79ef06ae61566f5..e7b2448b9d4e109d4cf7bbca5c94d8fbd0500719 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/EnggDiffraction/EnggDiffractionPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/EnggDiffraction/EnggDiffractionPresenter.h
@@ -107,8 +107,10 @@ public:
   void plotFitPeaksCurves();
 
   void runEvaluateFunctionAlg(const std::string &bk2BkExpFunction,
-                              const std::string &InputName, const std::string &OutputName,
-                              const std::string &startX, const std::string &endX);
+                              const std::string &InputName,
+                              const std::string &OutputName,
+                              const std::string &startX,
+                              const std::string &endX);
 
   void runCropWorkspaceAlg(std::string workspaceName);
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
index b232af60dde8e4834355affb65e0f5de0439ab47..3e447d6c9bf6d2e58993991712c5c2968079e0ce 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
@@ -17,135 +17,134 @@ class QHideEvent;
 class QCloseEvent;
 class QShowEvent;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    //-----------------------------------------------------
-    // Forward declarations
-    //-----------------------------------------------------
-    class MWDiag;
-  }
-
-  namespace CustomInterfaces
-  {
-    //-----------------------------------------------------
-    // Forward declarations
-    //-----------------------------------------------------
-    class Background;
-
-    /** 
-    This class implements the DirectConvertToEnergy interface for the direct instruments
-
-    @author Steve Williams, ISIS Computing Group, RAL
-    @author Martyn Gigg, Tessella Support Services plc
-    @date 24/02/2009
-
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class Homer : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-    public:
-      Homer(QWidget *parent, Ui::DirectConvertToEnergy & uiForm);
-
-      // Initialize the layout
-      void initLayout() override;
-
-      void runClicked();
-      void helpClicked();
-      void setIDFValues(const QString & prefix);  
-
-    private:
-      void showEvent(QShowEvent *event) override;
-      void hideEvent(QHideEvent *event) override;
-      void closeEvent(QCloseEvent *event) override;
-      /// Enable the run button if the results dialog has been closed and the python has stopped
-      void pythonIsRunning(bool running = true);
-      QString defaultName();
-      std::string insertNumber(const std::string &filename, const int number);
-
-      void setUpPage1();
-      void page1FileWidgs();
-      void page1Validators();
-      void setUpPage2();
-      void setUpPage3();
-
-      bool isInputValid() const;
-      bool isFileInputValid() const;
-      bool isParamInputValid() const;
-      bool isRebinStringValid() const;
-      bool checkEi(const QString & text) const;
-
-      bool runScripts();
-      void readSettings();
-      void saveSettings();
-      QString getGeneralSettingsGroup() const;
-      QString getInstrumentSettingsGroup() const;
-      QString openFileDia(const bool save, const QStringList &exts);
-      void syncBackgroundSettings();
-
-    signals:
-      // these signals send data to the find bad detectors (diag) widget
-      void MWDiag_updateWBV(const QString &);
-      void MWDiag_updateTOFs(const double &, const double &);
-      void MWDiag_sendRuns(const QStringList&);
-
-    private slots:
-      void validateAbsEi(const QString &);
-      void validateRunEi(const QString &);
-      void validateRebinBox(const QString &);
-
-      void browseSaveFile();
-
-      void runFilesChanged();
-      void updateVanadiumMapFile();
-      void updateSaveName();
-      void saveNameUpd();
-      void updateWBV();
-      void bgRemoveClick();
-      void bgRemoveReadSets();
-      void saveFormatOptionClicked(QAbstractButton*);
-      void updateAbsEi(const QString & text);
-      void markAbsEiDirty(bool dirty = true);
-
-    private:
-      Ui::DirectConvertToEnergy m_uiForm;
-      Background *m_backgroundDialog;
-      /// A pointer to the widget with the user controls for finding bad detectors
-      MantidWidgets::MWDiag *m_diagPage;
-
-      /// Saves if the user specified their own name for the SPE output file
-      bool m_saveChanged; 
-      bool m_backgroundWasVisible;
-      bool m_absEiDirty;
-      QHash<const QWidget * const, QLabel *> m_validators;
-      QButtonGroup *m_saveChecksGroup;
-      QString m_topSettingsGroup;
-      //@todo These all should be handled by the file widget
-      QString m_lastSaveDir;
-      QString m_lastLoadDir;
-    };
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+//-----------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------
+class MWDiag;
+}
+
+namespace CustomInterfaces {
+//-----------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------
+class Background;
+
+/**
+This class implements the DirectConvertToEnergy interface for the direct
+instruments
+
+@author Steve Williams, ISIS Computing Group, RAL
+@author Martyn Gigg, Tessella Support Services plc
+@date 24/02/2009
+
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class Homer : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public:
+  Homer(QWidget *parent, Ui::DirectConvertToEnergy &uiForm);
+
+  // Initialize the layout
+  void initLayout() override;
+
+  void runClicked();
+  void helpClicked();
+  void setIDFValues(const QString &prefix);
+
+private:
+  void showEvent(QShowEvent *event) override;
+  void hideEvent(QHideEvent *event) override;
+  void closeEvent(QCloseEvent *event) override;
+  /// Enable the run button if the results dialog has been closed and the python
+  /// has stopped
+  void pythonIsRunning(bool running = true);
+  QString defaultName();
+  std::string insertNumber(const std::string &filename, const int number);
+
+  void setUpPage1();
+  void page1FileWidgs();
+  void page1Validators();
+  void setUpPage2();
+  void setUpPage3();
+
+  bool isInputValid() const;
+  bool isFileInputValid() const;
+  bool isParamInputValid() const;
+  bool isRebinStringValid() const;
+  bool checkEi(const QString &text) const;
+
+  bool runScripts();
+  void readSettings();
+  void saveSettings();
+  QString getGeneralSettingsGroup() const;
+  QString getInstrumentSettingsGroup() const;
+  QString openFileDia(const bool save, const QStringList &exts);
+  void syncBackgroundSettings();
+
+signals:
+  // these signals send data to the find bad detectors (diag) widget
+  void MWDiag_updateWBV(const QString &);
+  void MWDiag_updateTOFs(const double &, const double &);
+  void MWDiag_sendRuns(const QStringList &);
+
+private slots:
+  void validateAbsEi(const QString &);
+  void validateRunEi(const QString &);
+  void validateRebinBox(const QString &);
+
+  void browseSaveFile();
+
+  void runFilesChanged();
+  void updateVanadiumMapFile();
+  void updateSaveName();
+  void saveNameUpd();
+  void updateWBV();
+  void bgRemoveClick();
+  void bgRemoveReadSets();
+  void saveFormatOptionClicked(QAbstractButton *);
+  void updateAbsEi(const QString &text);
+  void markAbsEiDirty(bool dirty = true);
+
+private:
+  Ui::DirectConvertToEnergy m_uiForm;
+  Background *m_backgroundDialog;
+  /// A pointer to the widget with the user controls for finding bad detectors
+  MantidWidgets::MWDiag *m_diagPage;
+
+  /// Saves if the user specified their own name for the SPE output file
+  bool m_saveChanged;
+  bool m_backgroundWasVisible;
+  bool m_absEiDirty;
+  QHash<const QWidget *const, QLabel *> m_validators;
+  QButtonGroup *m_saveChecksGroup;
+  QString m_topSettingsGroup;
+  //@todo These all should be handled by the file widget
+  QString m_lastSaveDir;
+  QString m_lastLoadDir;
+};
+}
 }
 
 #endif // MANTIDQTCUSTOMINTERFACES_HOMER_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflPresenter.h
index 9acf1b47564a38313f2d7b1cdeecaf941a68f1a2..329b4ce411749fae40744126df6830e038f8cb29 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflPresenter.h
@@ -8,70 +8,68 @@
 
 #include <QVariant>
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** @class IReflPresenter
+namespace MantidQt {
+namespace CustomInterfaces {
+/** @class IReflPresenter
 
-    IReflPresenter is an interface which defines the functions any reflectometry interface presenter needs to support.
+IReflPresenter is an interface which defines the functions any reflectometry
+interface presenter needs to support.
 
-    Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class IReflPresenter
-    {
-    public:
-      virtual ~IReflPresenter() {};
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class IReflPresenter {
+public:
+  virtual ~IReflPresenter(){};
 
-      enum Flag
-      {
-        SaveFlag,
-        SaveAsFlag,
-        AppendRowFlag,
-        PrependRowFlag,
-        DeleteRowFlag,
-        ProcessFlag,
-        GroupRowsFlag,
-        OpenTableFlag,
-        NewTableFlag,
-        TableUpdatedFlag,
-        ExpandSelectionFlag,
-        OptionsDialogFlag,
-        ClearSelectedFlag,
-        CopySelectedFlag,
-        CutSelectedFlag,
-        PasteSelectedFlag,
-        SearchFlag,
-        TransferFlag,
-        ImportTableFlag,
-        ExportTableFlag,
-        PlotRowFlag,
-        PlotGroupFlag
-      };
+  enum Flag {
+    SaveFlag,
+    SaveAsFlag,
+    AppendRowFlag,
+    PrependRowFlag,
+    DeleteRowFlag,
+    ProcessFlag,
+    GroupRowsFlag,
+    OpenTableFlag,
+    NewTableFlag,
+    TableUpdatedFlag,
+    ExpandSelectionFlag,
+    OptionsDialogFlag,
+    ClearSelectedFlag,
+    CopySelectedFlag,
+    CutSelectedFlag,
+    PasteSelectedFlag,
+    SearchFlag,
+    TransferFlag,
+    ImportTableFlag,
+    ExportTableFlag,
+    PlotRowFlag,
+    PlotGroupFlag
+  };
 
-      //Tell the presenter something happened
-      virtual void notify(IReflPresenter::Flag flag) = 0;
-      virtual const std::map<std::string,QVariant>& options() const = 0;
-      virtual void setOptions(const std::map<std::string,QVariant>& options) = 0;
-    };
-  }
+  // Tell the presenter something happened
+  virtual void notify(IReflPresenter::Flag flag) = 0;
+  virtual const std::map<std::string, QVariant> &options() const = 0;
+  virtual void setOptions(const std::map<std::string, QVariant> &options) = 0;
+};
+}
 }
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflSearcher.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflSearcher.h
index a7a989f4fe30e55dd473f194508b6e7f2789c867..71c7f9aac77ebfe9ec56224c321a7624c4b72c72 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflSearcher.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IReflSearcher.h
@@ -6,41 +6,39 @@
 #include "MantidQtCustomInterfaces/IReflPresenter.h"
 #include "MantidAPI/ITableWorkspace_fwd.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** @class IReflSearcher
-
-    IReflSearcher is an interface for search implementations used by IReflPresenter implementations.
-
-    Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class IReflSearcher
-    {
-    public:
-      virtual ~IReflSearcher() {};
-      virtual Mantid::API::ITableWorkspace_sptr
-      search(const std::string &text) = 0;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/** @class IReflSearcher
+
+IReflSearcher is an interface for search implementations used by IReflPresenter
+implementations.
+
+Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class IReflSearcher {
+public:
+  virtual ~IReflSearcher(){};
+  virtual Mantid::API::ITableWorkspace_sptr search(const std::string &text) = 0;
+};
+}
 }
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.h
index 666f09ac36f4db2dfd3ad8981aea674e03b167c0..e7623373a0d775067c141c14331f97120f7862c0 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.h
@@ -4,34 +4,32 @@
 #include "ui_AbsorptionCorrections.h"
 #include "CorrectionsTab.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  class DLLExport AbsorptionCorrections : public CorrectionsTab
-  {
-    Q_OBJECT
-
-  public:
-    AbsorptionCorrections(QWidget * parent = 0);
-
-  private:
-    void setup() override;
-    void run() override;
-    bool validate() override;
-    void loadSettings(const QSettings &settings) override;
-
-  private slots:
-    virtual void algorithmComplete(bool error);
-
-  private:
-    void addSaveWorkspace(QString wsName);
-    void addShapeSpecificSampleOptions(Mantid::API::IAlgorithm_sptr alg, QString shape);
-    void addShapeSpecificCanOptions(Mantid::API::IAlgorithm_sptr alg, QString shape);
-
-    Ui::AbsorptionCorrections m_uiForm;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport AbsorptionCorrections : public CorrectionsTab {
+  Q_OBJECT
+
+public:
+  AbsorptionCorrections(QWidget *parent = 0);
+
+private:
+  void setup() override;
+  void run() override;
+  bool validate() override;
+  void loadSettings(const QSettings &settings) override;
+
+private slots:
+  virtual void algorithmComplete(bool error);
+
+private:
+  void addSaveWorkspace(QString wsName);
+  void addShapeSpecificSampleOptions(Mantid::API::IAlgorithm_sptr alg,
+                                     QString shape);
+  void addShapeSpecificCanOptions(Mantid::API::IAlgorithm_sptr alg,
+                                  QString shape);
+
+  Ui::AbsorptionCorrections m_uiForm;
+};
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyPaalmanPings.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyPaalmanPings.h
index fe6822e455d32382d9cf505d66d1d6e15835c654..b423e92991e0079246a8274ea196a1bfef6dbcd3 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyPaalmanPings.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyPaalmanPings.h
@@ -45,7 +45,6 @@ private:
 
   std::string m_sampleWorkspaceName;
   std::string m_containerWorkspaceName;
-
 };
 
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
index 398af907a467ebed1b986ff2d60513bf5e462c73..96fbdb315a13774da530e60db0b15e89f79a749d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h
@@ -46,7 +46,6 @@ private slots:
   void fitFunctionSelected(const QString &);
   void algorithmComplete(bool error);
 
-
 private:
   boost::shared_ptr<Mantid::API::CompositeFunction>
   createFunction(bool tieCentres = false);
@@ -83,7 +82,6 @@ private:
 
   // Used in auto generating defaults for parameters
   QStringList m_defaultParams;
-
 };
 } // namespace IDA
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CorrectionsTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CorrectionsTab.h
index a87d142b402be6405c5e3a5f668387e0f5999b72..2503975b2798d0ec202798c11e14819983ad24ab 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CorrectionsTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CorrectionsTab.h
@@ -10,79 +10,78 @@ class QwtPlot;
 class QSettings;
 class QString;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class RangeSelector;
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+class RangeSelector;
+}
 }
 
 // Suppress a warning coming out of code that isn't ours
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1125
+#pragma warning disable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Woverloaded-virtual"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 #include "qttreepropertybrowser.h"
 #include "qtpropertymanager.h"
 #include "qteditorfactory.h"
 #include "DoubleEditorFactory.h"
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1125
+#pragma warning enable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  class DLLExport CorrectionsTab : public IndirectTab
-  {
-    Q_OBJECT
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport CorrectionsTab : public IndirectTab {
+  Q_OBJECT
 
-  public:
-    /// Constructor
-    CorrectionsTab(QWidget * parent = 0);
+public:
+  /// Constructor
+  CorrectionsTab(QWidget *parent = 0);
 
-    /// Loads the tab's settings.
-    void loadTabSettings(const QSettings & settings);
+  /// Loads the tab's settings.
+  void loadTabSettings(const QSettings &settings);
 
-  protected:
-    /// Function to run a string as python code
-    void runPythonScript(const QString& pyInput);
-    /// Check the binning between two workspaces match
-    bool checkWorkspaceBinningMatches(Mantid::API::MatrixWorkspace_const_sptr left,
-                                      Mantid::API::MatrixWorkspace_const_sptr right);
-    /// Adds a unit conversion step to the algorithm queue
-    std::string addConvertUnitsStep(Mantid::API::MatrixWorkspace_sptr ws, const std::string & unitID, const std::string & suffix = "UNIT", std::string eMode = "");
+protected:
+  /// Function to run a string as python code
+  void runPythonScript(const QString &pyInput);
+  /// Check the binning between two workspaces match
+  bool
+  checkWorkspaceBinningMatches(Mantid::API::MatrixWorkspace_const_sptr left,
+                               Mantid::API::MatrixWorkspace_const_sptr right);
+  /// Adds a unit conversion step to the algorithm queue
+  std::string addConvertUnitsStep(Mantid::API::MatrixWorkspace_sptr ws,
+                                  const std::string &unitID,
+                                  const std::string &suffix = "UNIT",
+                                  std::string eMode = "");
 
-    /// DoubleEditorFactory
-    DoubleEditorFactory* m_dblEdFac;
-    /// QtCheckBoxFactory
-    QtCheckBoxFactory* m_blnEdFac;
+  /// DoubleEditorFactory
+  DoubleEditorFactory *m_dblEdFac;
+  /// QtCheckBoxFactory
+  QtCheckBoxFactory *m_blnEdFac;
 
-  protected slots:
-    /// Slot that can be called when a user eidts an input.
-    void inputChanged();
+protected slots:
+  /// Slot that can be called when a user eidts an input.
+  void inputChanged();
 
-  private:
-    /// Overidden by child class.
-    void setup() override = 0;
-    /// Overidden by child class.
-    void run() override = 0;
-    /// Overidden by child class.
-    bool validate() override = 0;
+private:
+  /// Overidden by child class.
+  void setup() override = 0;
+  /// Overidden by child class.
+  void run() override = 0;
+  /// Overidden by child class.
+  bool validate() override = 0;
 
-    /// Overidden by child class.
-    virtual void loadSettings(const QSettings & settings) = 0;
-  };
+  /// Overidden by child class.
+  virtual void loadSettings(const QSettings &settings) = 0;
+};
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.h
index 15756c178a957154c6c75a14e9f97a936eb048e6..93cce53e5b2f0646353af70464380630b64654bd 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.h
@@ -5,43 +5,38 @@
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 #include "MantidQtCustomInterfaces/Indirect/IndirectDataAnalysisTab.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  class DLLExport Elwin : public IndirectDataAnalysisTab
-  {
-    Q_OBJECT
-
-  public:
-    Elwin(QWidget* parent = 0);
-
-  private:
-    void setup() override;
-    void run() override;
-    bool validate() override;
-    void loadSettings(const QSettings &settings) override;
-    void setDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws);
-    void setDefaultSampleLog(Mantid::API::MatrixWorkspace_const_sptr ws);
-
-  private slots:
-    void newInputFiles();
-    void newPreviewFileSelected(int index);
-    void plotInput();
-    void twoRanges(QtProperty* prop, bool);
-    void minChanged(double val);
-    void maxChanged(double val);
-    void updateRS(QtProperty* prop, double val);
-
-  private:
-    void addSaveAlgorithm(QString workspaceName, QString filename="");
-
-    Ui::Elwin m_uiForm;
-    QtTreePropertyBrowser* m_elwTree;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+class DLLExport Elwin : public IndirectDataAnalysisTab {
+  Q_OBJECT
+
+public:
+  Elwin(QWidget *parent = 0);
+
+private:
+  void setup() override;
+  void run() override;
+  bool validate() override;
+  void loadSettings(const QSettings &settings) override;
+  void setDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws);
+  void setDefaultSampleLog(Mantid::API::MatrixWorkspace_const_sptr ws);
+
+private slots:
+  void newInputFiles();
+  void newPreviewFileSelected(int index);
+  void plotInput();
+  void twoRanges(QtProperty *prop, bool);
+  void minChanged(double val);
+  void maxChanged(double val);
+  void updateRS(QtProperty *prop, double val);
+
+private:
+  void addSaveAlgorithm(QString workspaceName, QString filename = "");
+
+  Ui::Elwin m_uiForm;
+  QtTreePropertyBrowser *m_elwTree;
+};
 } // namespace IDA
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLCalibration.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLCalibration.h
index f62151c0fbec9da075f36f20a9ce9cc032d03276..275d31d118edcc918538d02ccb51e471b436e7d8 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLCalibration.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLCalibration.h
@@ -6,56 +6,53 @@
 #include "MantidKernel/System.h"
 #include "MantidQtCustomInterfaces/UserInputValidator.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** ILLCalibration
+namespace MantidQt {
+namespace CustomInterfaces {
+/** ILLCalibration
 
-    @author Dan Nixon
+  @author Dan Nixon
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport ILLCalibration : public IndirectDataReductionTab
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport ILLCalibration : public IndirectDataReductionTab {
+  Q_OBJECT
 
-  public:
-    ILLCalibration(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~ILLCalibration() override;
+public:
+  ILLCalibration(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~ILLCalibration() override;
 
-    void setup() override;
-    void run() override;
-    bool validate() override;
+  void setup() override;
+  void run() override;
+  bool validate() override;
 
-  private slots:
-    void algorithmComplete(bool error);
-    void newInstrumentSelected();
+private slots:
+  void algorithmComplete(bool error);
+  void newInstrumentSelected();
 
-  private:
-    Ui::ILLCalibration m_uiForm;
-
-  };
+private:
+  Ui::ILLCalibration m_uiForm;
+};
 
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif //MANTIDQTCUSTOMINTERFACES_ILLCALIBRATION_H_
+#endif // MANTIDQTCUSTOMINTERFACES_ILLCALIBRATION_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLEnergyTransfer.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLEnergyTransfer.h
index 75a5159cf503f3bcd80eae307905f4638c4a84e1..c4e8e634ee52da391ef5eebba0f2ce63ab340098 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLEnergyTransfer.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ILLEnergyTransfer.h
@@ -5,58 +5,55 @@
 #include "ui_ILLEnergyTransfer.h"
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** ILLEnergyTransfer
+namespace MantidQt {
+namespace CustomInterfaces {
+/** ILLEnergyTransfer
 
-    @author Dan Nixon
-    @date 23/07/2014
+  @author Dan Nixon
+  @date 23/07/2014
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport ILLEnergyTransfer : public IndirectDataReductionTab
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport ILLEnergyTransfer : public IndirectDataReductionTab {
+  Q_OBJECT
 
-  public:
-    ILLEnergyTransfer(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~ILLEnergyTransfer() override;
+public:
+  ILLEnergyTransfer(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~ILLEnergyTransfer() override;
 
-    void setup() override;
-    void run() override;
+  void setup() override;
+  void run() override;
 
-  public slots:
-    bool validate() override;
+public slots:
+  bool validate() override;
 
-  private slots:
-    void algorithmComplete(bool error);
-    void setInstrumentDefault();
+private slots:
+  void algorithmComplete(bool error);
+  void setInstrumentDefault();
 
-  private:
-    Ui::ILLEnergyTransfer m_uiForm;
-
-  };
+private:
+  Ui::ILLEnergyTransfer m_uiForm;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif //MANTIDQTCUSTOMINTERFACES_ILLENERGYTRANSFER_H_
+#endif // MANTIDQTCUSTOMINTERFACES_ILLENERGYTRANSFER_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.h
index 3efb3ad7d3cdda5965341d5d7562ea2b82f1dc1d..2296ff201aa57917c126e3fee099d8d077fec9bb 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISCalibration.h
@@ -6,73 +6,73 @@
 #include "MantidKernel/System.h"
 #include "MantidQtCustomInterfaces/UserInputValidator.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** ISISCalibration
-    Handles vanadium run calibration for ISIS instruments.
-
-    @author Dan Nixon
-    @date 23/07/2014
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport ISISCalibration : public IndirectDataReductionTab
-  {
-    Q_OBJECT
-
-  public:
-    ISISCalibration(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~ISISCalibration() override;
-
-    void setup() override;
-    void run() override;
-    bool validate() override;
-
-  private slots:
-    void algorithmComplete(bool error);
-    void calPlotRaw();
-    void calPlotEnergy();
-    void calMinChanged(double);
-    void calMaxChanged(double);
-    void calUpdateRS(QtProperty*, double);
-    void calSetDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws);
-    void resCheck(bool state); ///< handles checking/unchecking of "Create RES File" checkbox
-    void setDefaultInstDetails();
-    void pbRunEditing();  //< Called when a user starts to type / edit the runs to load.
-    void pbRunFinding();  //< Called when the FileFinder starts finding the files.
-    void pbRunFinished(); //< Called when the FileFinder has finished finding the files.
-
-  private:
-    void createRESfile(const QString& file);
-
-    Ui::ISISCalibration m_uiForm;
-    QString m_lastCalPlotFilename;
-
-    QString m_outputCalibrationName;
-    QString m_outputResolutionName;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+/** ISISCalibration
+  Handles vanadium run calibration for ISIS instruments.
+
+  @author Dan Nixon
+  @date 23/07/2014
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport ISISCalibration : public IndirectDataReductionTab {
+  Q_OBJECT
+
+public:
+  ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~ISISCalibration() override;
+
+  void setup() override;
+  void run() override;
+  bool validate() override;
+
+private slots:
+  void algorithmComplete(bool error);
+  void calPlotRaw();
+  void calPlotEnergy();
+  void calMinChanged(double);
+  void calMaxChanged(double);
+  void calUpdateRS(QtProperty *, double);
+  void calSetDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws);
+  void resCheck(bool state); ///< handles checking/unchecking of "Create RES
+  /// File" checkbox
+  void setDefaultInstDetails();
+  void
+  pbRunEditing(); //< Called when a user starts to type / edit the runs to load.
+  void pbRunFinding();  //< Called when the FileFinder starts finding the files.
+  void pbRunFinished(); //< Called when the FileFinder has finished finding the
+  // files.
+
+private:
+  void createRESfile(const QString &file);
+
+  Ui::ISISCalibration m_uiForm;
+  QString m_lastCalPlotFilename;
+
+  QString m_outputCalibrationName;
+  QString m_outputResolutionName;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif //MANTIDQTCUSTOMINTERFACES_ISISCALIBRATION_H_
+#endif // MANTIDQTCUSTOMINTERFACES_ISISCALIBRATION_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.h
index f0f370fc10950d1101d01db1d6ac19e23cfd92bc..023232eea17a5930f754d42b1b244ffde4b981a6 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISDiagnostics.h
@@ -77,7 +77,7 @@ private slots:
   pbRunEditing(); //< Called when a user starts to type / edit the runs to load.
   void pbRunFinding();  //< Called when the FileFinder starts finding the files.
   void pbRunFinished(); //< Called when the FileFinder has finished finding the
-                        //files.
+  // files.
 
 private:
   Ui::ISISDiagnostics m_uiForm;
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
index 700f390077fb0fbd788e7240e4b245f754f1bb3b..fbccfef3994d5a309b45d0441a6dfb6886dda215 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ISISEnergyTransfer.h
@@ -52,17 +52,23 @@ private slots:
   void algorithmComplete(bool error);
   void
   setInstrumentDefault(); ///< Sets default parameters for current instrument
-  void mappingOptionSelected(const QString &groupType); ///< change ui to display appropriate options
-  void plotRaw();       ///< plot raw data from instrument
-  void pbRunEditing();  //< Called when a user starts to type / edit the runs to load.
+  void mappingOptionSelected(
+      const QString &groupType); ///< change ui to display appropriate options
+  void plotRaw();                ///< plot raw data from instrument
+  void
+  pbRunEditing(); //< Called when a user starts to type / edit the runs to load.
   void pbRunFinding();  //< Called when the FileFinder starts finding the files.
-  void pbRunFinished(); //< Called when the FileFinder has finished finding the files.
-  void plotRawComplete(bool error); //< Called when the Plot Raw algorithmm chain completes
+  void pbRunFinished(); //< Called when the FileFinder has finished finding the
+  // files.
+  void plotRawComplete(
+      bool error); //< Called when the Plot Raw algorithmm chain completes
 
 private:
   Ui::ISISEnergyTransfer m_uiForm;
 
-  QPair<QString, QString> createMapFile(const QString &groupType); ///< create the mapping file with which to group results
+  QPair<QString, QString> createMapFile(
+      const QString &
+          groupType); ///< create the mapping file with which to group results
   std::vector<std::string> getSaveFormats(); ///< get a vector of save formats
 };
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataAnalysisTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataAnalysisTab.h
index 5b7cf0b44c5c8cb7af1821a98a9a8a825d9639db..b4ff375f87fff1dfa2d64d5a9021347c15701cf4 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataAnalysisTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataAnalysisTab.h
@@ -11,80 +11,73 @@ class QwtPlot;
 class QSettings;
 class QString;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class RangeSelector;
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+class RangeSelector;
+}
 }
 
 // Suppress a warning coming out of code that isn't ours
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1125
+#pragma warning disable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Woverloaded-virtual"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 #include "qttreepropertybrowser.h"
 #include "qtpropertymanager.h"
 #include "qteditorfactory.h"
 #include "DoubleEditorFactory.h"
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1125
+#pragma warning enable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  class DLLExport IndirectDataAnalysisTab : public IndirectTab
-  {
-    Q_OBJECT
-
-  public:
-    /// Constructor
-    IndirectDataAnalysisTab(QWidget * parent = 0);
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+class DLLExport IndirectDataAnalysisTab : public IndirectTab {
+  Q_OBJECT
 
-    /// Loads the tab's settings.
-    void loadTabSettings(const QSettings & settings);
+public:
+  /// Constructor
+  IndirectDataAnalysisTab(QWidget *parent = 0);
 
-  protected:
-    /// Function to run a string as python code
-    void runPythonScript(const QString& pyInput);
+  /// Loads the tab's settings.
+  void loadTabSettings(const QSettings &settings);
 
-    /// DoubleEditorFactory
-    DoubleEditorFactory* m_dblEdFac;
-    /// QtCheckBoxFactory
-    QtCheckBoxFactory* m_blnEdFac;
+protected:
+  /// Function to run a string as python code
+  void runPythonScript(const QString &pyInput);
 
-  protected slots:
-    /// Slot that can be called when a user eidts an input.
-    void inputChanged();
+  /// DoubleEditorFactory
+  DoubleEditorFactory *m_dblEdFac;
+  /// QtCheckBoxFactory
+  QtCheckBoxFactory *m_blnEdFac;
 
-  private:
-    /// Overidden by child class.
-    void setup() override = 0;
-    /// Overidden by child class.
-    void run() override = 0;
-    /// Overidden by child class.
-    bool validate() override = 0;
+protected slots:
+  /// Slot that can be called when a user eidts an input.
+  void inputChanged();
 
-    /// Overidden by child class.
-    virtual void loadSettings(const QSettings & settings) = 0;
+private:
+  /// Overidden by child class.
+  void setup() override = 0;
+  /// Overidden by child class.
+  void run() override = 0;
+  /// Overidden by child class.
+  bool validate() override = 0;
 
-    /// A pointer to the parent (friend) IndirectDataAnalysis object.
-    IndirectDataAnalysis * m_parent;
+  /// Overidden by child class.
+  virtual void loadSettings(const QSettings &settings) = 0;
 
-  };
+  /// A pointer to the parent (friend) IndirectDataAnalysis object.
+  IndirectDataAnalysis *m_parent;
+};
 } // namespace IDA
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReduction.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReduction.h
index 4d40350c4df0101e7c151a7d17ee0d973c716ebc..9d9828655f0a99a99d020958cfec7cddcc797b0c 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReduction.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReduction.h
@@ -15,171 +15,180 @@
 #include <QRegExp>
 #include <QScrollArea>
 
-
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    //-------------------------------------------
-    // Forward declarations
-    //-------------------------------------------
-    class IndirectDataReductionTab;
-
-    /**
-    This class defines the IndirectDataReduction interface. It handles the overall instrument settings
-    and sets up the appropriate interface depending on the deltaE mode of the instrument. The deltaE
-    mode is defined in the instrument definition file using the "deltaE-mode".
-
-    @author Martyn Gigg, Tessella Support Services plc
-    @author Michael Whitty
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-    class IndirectDataReduction : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-    public:
-      /// Default Constructor
-      IndirectDataReduction(QWidget *parent = 0);
-      ///Destructor
-      ~IndirectDataReduction() override;
-      /// Interface name
-      static std::string name() { return "Data Reduction"; }
-      // This interface's categories.
-      static QString categoryInfo() { return "Indirect"; }
-
-      /// Initialize the layout
-      void initLayout() override;
-      /// Run Python-based initialisation commands
-      void initLocalPython() override;
-
-      /// Handled configuration changes
-      void handleConfigChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
-
-      Mantid::API::MatrixWorkspace_sptr loadInstrumentIfNotExist(std::string instrumentName,
-          std::string analyser = "", std::string reflection = "");
-
-      std::vector<std::pair<std::string, std::vector<std::string> > > getInstrumentModes();
-      QMap<QString, QString> getInstrumentDetails();
-
-    signals:
-      /// Emitted when the instrument setup is changed
-      void newInstrumentConfiguration();
-
-    private slots:
-      /// Shows/hides tabs based on facility
-      void filterUiForFacility(QString facility);
-      /// Opens the help page for the current tab
-      void helpClicked();
-      /// Exports the current tab algorithms as a Python script
-      void exportTabPython();
-      /// Runs the current tab
-      void runClicked();
-      /// Opens the manage directory dialog
-      void openDirectoryDialog();
-
-      /// Shows a information dialog box
-      void showMessageBox(const QString& message);
-      /// Updates the state of the Run button
-      void updateRunButton(bool enabled = true, QString message = "Run", QString tooltip = "");
-
-      /// Called when the load instrument algorithms complete
-      void instrumentLoadingDone(bool error);
-
-      /// Called when the instrument setup has been changed
-      void instrumentSetupChanged(const QString & instrumentName, const QString & analyser, const QString & reflection);
-
-    private:
-      QString getInstrumentParameterFrom(Mantid::Geometry::IComponent_const_sptr comp, std::string param);
-
-      void readSettings();
-      void saveSettings();
-
-      /// Set and show an instrument-specific widget
-      void closeEvent(QCloseEvent *close) override;
-
-      /**
-       * Adds a tab to the cache of tabs that can be shown.
-       *
-       * THis method is used to ensure that the tabs are always loaded and their
-       * layouts setup for the sake of screenshoting them for documentation.
-       *
-       * @param name Name to be displayed on tab
-       */
-      template <typename T>
-      void addTab(const QString & name)
-      {
-        QWidget * tabWidget = new QWidget(m_uiForm.twIDRTabs);
-        QVBoxLayout * tabLayout = new QVBoxLayout(tabWidget);
-        tabWidget->setLayout(tabLayout);
-
-        QScrollArea * tabScrollArea = new QScrollArea(tabWidget);
-        tabLayout->addWidget(tabScrollArea);
-        tabScrollArea->setWidgetResizable(true);
-
-        QWidget * tabContent = new QWidget(tabScrollArea);
-        tabContent->setObjectName("tab" + QString(name).remove(QRegExp("[ ,()]")));
-        tabScrollArea->setWidget(tabContent);
-        tabScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
-
-        IndirectDataReductionTab * tabIDRContent = new T(this, tabContent);
-        tabIDRContent->setupTab();
-        tabContent->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
-
-        connect(tabIDRContent, SIGNAL(runAsPythonScript(const QString&, bool)), this, SIGNAL(runAsPythonScript(const QString&, bool)));
-        connect(tabIDRContent, SIGNAL(showMessageBox(const QString&)), this, SLOT(showMessageBox(const QString&)));
-        connect(tabIDRContent, SIGNAL(updateRunButton(bool, QString, QString)), this, SLOT(updateRunButton(bool, QString, QString)));
-
-        // Add to the cache
-        m_tabs[name] = qMakePair(tabWidget, tabIDRContent);
-
-        // Add all tabs to UI initially
-        m_uiForm.twIDRTabs->addTab(tabWidget, name);
-      }
-
-      friend class IndirectDataReductionTab;
-      /// The .ui form generated by Qt Designer
-      Ui::IndirectDataReduction m_uiForm;
-      /// Instrument the interface is currently set for.
-      QString m_instrument;
-      /// The settings group
-      QString m_settingsGroup;
-      /// Runner for insturment load algorithm
-      MantidQt::API::AlgorithmRunner* m_algRunner;
-
-      // All indirect tabs
-      QMap<QString, QPair<QWidget *, IndirectDataReductionTab *>> m_tabs;
-
-      /// Poco observer for changes in user directory settings
-      Poco::NObserver<IndirectDataReduction, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
-      QString m_dataDir; ///< default data search directory
-      QString m_saveDir; ///< default data save directory
-
-      // Pointer to the current empty instrument workspace
-      Mantid::API::MatrixWorkspace_sptr m_instWorkspace;
-    };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+//-------------------------------------------
+// Forward declarations
+//-------------------------------------------
+class IndirectDataReductionTab;
+
+/**
+This class defines the IndirectDataReduction interface. It handles the overall
+instrument settings
+and sets up the appropriate interface depending on the deltaE mode of the
+instrument. The deltaE
+mode is defined in the instrument definition file using the "deltaE-mode".
+
+@author Martyn Gigg, Tessella Support Services plc
+@author Michael Whitty
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class IndirectDataReduction : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public:
+  /// Default Constructor
+  IndirectDataReduction(QWidget *parent = 0);
+  /// Destructor
+  ~IndirectDataReduction() override;
+  /// Interface name
+  static std::string name() { return "Data Reduction"; }
+  // This interface's categories.
+  static QString categoryInfo() { return "Indirect"; }
+
+  /// Initialize the layout
+  void initLayout() override;
+  /// Run Python-based initialisation commands
+  void initLocalPython() override;
+
+  /// Handled configuration changes
+  void handleConfigChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
+
+  Mantid::API::MatrixWorkspace_sptr
+  loadInstrumentIfNotExist(std::string instrumentName,
+                           std::string analyser = "",
+                           std::string reflection = "");
+
+  std::vector<std::pair<std::string, std::vector<std::string>>>
+  getInstrumentModes();
+  QMap<QString, QString> getInstrumentDetails();
+
+signals:
+  /// Emitted when the instrument setup is changed
+  void newInstrumentConfiguration();
+
+private slots:
+  /// Shows/hides tabs based on facility
+  void filterUiForFacility(QString facility);
+  /// Opens the help page for the current tab
+  void helpClicked();
+  /// Exports the current tab algorithms as a Python script
+  void exportTabPython();
+  /// Runs the current tab
+  void runClicked();
+  /// Opens the manage directory dialog
+  void openDirectoryDialog();
+
+  /// Shows a information dialog box
+  void showMessageBox(const QString &message);
+  /// Updates the state of the Run button
+  void updateRunButton(bool enabled = true, QString message = "Run",
+                       QString tooltip = "");
+
+  /// Called when the load instrument algorithms complete
+  void instrumentLoadingDone(bool error);
+
+  /// Called when the instrument setup has been changed
+  void instrumentSetupChanged(const QString &instrumentName,
+                              const QString &analyser,
+                              const QString &reflection);
+
+private:
+  QString
+  getInstrumentParameterFrom(Mantid::Geometry::IComponent_const_sptr comp,
+                             std::string param);
+
+  void readSettings();
+  void saveSettings();
+
+  /// Set and show an instrument-specific widget
+  void closeEvent(QCloseEvent *close) override;
+
+  /**
+   * Adds a tab to the cache of tabs that can be shown.
+   *
+   * THis method is used to ensure that the tabs are always loaded and their
+   * layouts setup for the sake of screenshoting them for documentation.
+   *
+   * @param name Name to be displayed on tab
+   */
+  template <typename T> void addTab(const QString &name) {
+    QWidget *tabWidget = new QWidget(m_uiForm.twIDRTabs);
+    QVBoxLayout *tabLayout = new QVBoxLayout(tabWidget);
+    tabWidget->setLayout(tabLayout);
+
+    QScrollArea *tabScrollArea = new QScrollArea(tabWidget);
+    tabLayout->addWidget(tabScrollArea);
+    tabScrollArea->setWidgetResizable(true);
+
+    QWidget *tabContent = new QWidget(tabScrollArea);
+    tabContent->setObjectName("tab" + QString(name).remove(QRegExp("[ ,()]")));
+    tabScrollArea->setWidget(tabContent);
+    tabScrollArea->setSizePolicy(QSizePolicy::Expanding,
+                                 QSizePolicy::Expanding);
+
+    IndirectDataReductionTab *tabIDRContent = new T(this, tabContent);
+    tabIDRContent->setupTab();
+    tabContent->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+
+    connect(tabIDRContent, SIGNAL(runAsPythonScript(const QString &, bool)),
+            this, SIGNAL(runAsPythonScript(const QString &, bool)));
+    connect(tabIDRContent, SIGNAL(showMessageBox(const QString &)), this,
+            SLOT(showMessageBox(const QString &)));
+    connect(tabIDRContent, SIGNAL(updateRunButton(bool, QString, QString)),
+            this, SLOT(updateRunButton(bool, QString, QString)));
+
+    // Add to the cache
+    m_tabs[name] = qMakePair(tabWidget, tabIDRContent);
+
+    // Add all tabs to UI initially
+    m_uiForm.twIDRTabs->addTab(tabWidget, name);
   }
+
+  friend class IndirectDataReductionTab;
+  /// The .ui form generated by Qt Designer
+  Ui::IndirectDataReduction m_uiForm;
+  /// Instrument the interface is currently set for.
+  QString m_instrument;
+  /// The settings group
+  QString m_settingsGroup;
+  /// Runner for insturment load algorithm
+  MantidQt::API::AlgorithmRunner *m_algRunner;
+
+  // All indirect tabs
+  QMap<QString, QPair<QWidget *, IndirectDataReductionTab *>> m_tabs;
+
+  /// Poco observer for changes in user directory settings
+  Poco::NObserver<IndirectDataReduction,
+                  Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
+  QString m_dataDir; ///< default data search directory
+  QString m_saveDir; ///< default data save directory
+
+  // Pointer to the current empty instrument workspace
+  Mantid::API::MatrixWorkspace_sptr m_instWorkspace;
+};
+}
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTDATAREDUCTION_H_
+#endif // MANTIDQTCUSTOMINTERFACES_INDIRECTDATAREDUCTION_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReductionTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReductionTab.h
index b7befd805f5be04f7938d9618decee0813c22b94..acd803f6d7dbc0697ab06b162cf6fc92372121e3 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReductionTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDataReductionTab.h
@@ -22,89 +22,93 @@
 
 // Suppress a warning coming out of code that isn't ours
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1125
+#pragma warning disable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Woverloaded-virtual"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 #include "DoubleEditorFactory.h"
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1125
+#pragma warning enable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  class IndirectDataReduction;
-
-  /** IndirectDataReductionTab
-
-    This class defines common functionality of tabs used in the Indirect Data Reduction interface.
-
-    @author Samuel Jackson
-    @date 13/08/2013
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport IndirectDataReductionTab : public IndirectTab
-  {
-    Q_OBJECT
-
-  public:
-    IndirectDataReductionTab(IndirectDataReduction * idrUI, QObject * parent = 0);
-    ~IndirectDataReductionTab() override;
-
-  public slots:
-    void runTab();
-
-  signals:
-    /// Update the Run button on the IDR main window
-    void updateRunButton(bool enabled = true, QString message = "Run", QString tooltip = "");
-    /// Emitted when the instrument setup is changed
-    void newInstrumentConfiguration();
-
-  protected:
-    Mantid::API::MatrixWorkspace_sptr loadInstrumentIfNotExist(std::string instrumentName, std::string analyser="", std::string reflection="");
-    /// Function to get details about the instrumet from a given workspace
-    QMap<QString, QString> getInstrumentDetails();
-    std::map<std::string, double> getRangesFromInstrument(QString instName = "", QString analyser = "", QString reflection = "");
-    /// Get the instrument config widget
-    MantidWidgets::IndirectInstrumentConfig *getInstrumentConfiguration();
-
-  private slots:
-    void tabExecutionComplete(bool error);
-
-  private:
-    IndirectDataReduction *m_idrUI;
-    bool m_tabRunning;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+class IndirectDataReduction;
+
+/** IndirectDataReductionTab
+
+  This class defines common functionality of tabs used in the Indirect Data
+  Reduction interface.
+
+  @author Samuel Jackson
+  @date 13/08/2013
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport IndirectDataReductionTab : public IndirectTab {
+  Q_OBJECT
+
+public:
+  IndirectDataReductionTab(IndirectDataReduction *idrUI, QObject *parent = 0);
+  ~IndirectDataReductionTab() override;
+
+public slots:
+  void runTab();
+
+signals:
+  /// Update the Run button on the IDR main window
+  void updateRunButton(bool enabled = true, QString message = "Run",
+                       QString tooltip = "");
+  /// Emitted when the instrument setup is changed
+  void newInstrumentConfiguration();
+
+protected:
+  Mantid::API::MatrixWorkspace_sptr
+  loadInstrumentIfNotExist(std::string instrumentName,
+                           std::string analyser = "",
+                           std::string reflection = "");
+  /// Function to get details about the instrumet from a given workspace
+  QMap<QString, QString> getInstrumentDetails();
+  std::map<std::string, double>
+  getRangesFromInstrument(QString instName = "", QString analyser = "",
+                          QString reflection = "");
+  /// Get the instrument config widget
+  MantidWidgets::IndirectInstrumentConfig *getInstrumentConfiguration();
+
+private slots:
+  void tabExecutionComplete(bool error);
+
+private:
+  IndirectDataReduction *m_idrUI;
+  bool m_tabRunning;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif  /* MANTID_CUSTOMINTERFACES_INDIRECTDATAREDUCTIONTAB_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_INDIRECTDATAREDUCTIONTAB_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectLoadILL.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectLoadILL.h
index 05dbf0b3bae9bbde61ddfd9d921cb17907497093..434d6ad7267b1d4f79961029990c236cfb9b6ef1 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectLoadILL.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectLoadILL.h
@@ -9,37 +9,33 @@
 #include <QMap>
 #include <QStringList>
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		class DLLExport IndirectLoadILL : public IndirectToolsTab
-		{
-			Q_OBJECT
-
-		public:
-			IndirectLoadILL(QWidget * parent = 0);
-
-			/// Load default settings into the interface
-                        void loadSettings(const QSettings &settings) override;
-
-                      protected:
-                        void setup() override;
-                        bool validate() override;
-                        void run() override;
-
-                      private slots:
-			/// Set the instrument based on the file name if possible
-			void handleFilesFound();
-
-		private:
-			/// Map to store instrument analysers and reflections for this instrument
-			QMap<QString, QStringList> m_paramMap;
-			/// The ui form
-			Ui::IndirectLoadILL m_uiForm;
-
-		};
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport IndirectLoadILL : public IndirectToolsTab {
+  Q_OBJECT
+
+public:
+  IndirectLoadILL(QWidget *parent = 0);
+
+  /// Load default settings into the interface
+  void loadSettings(const QSettings &settings) override;
+
+protected:
+  void setup() override;
+  bool validate() override;
+  void run() override;
+
+private slots:
+  /// Set the instrument based on the file name if possible
+  void handleFilesFound();
+
+private:
+  /// Map to store instrument analysers and reflections for this instrument
+  QMap<QString, QStringList> m_paramMap;
+  /// The ui form
+  Ui::IndirectLoadILL m_uiForm;
+};
+} // namespace CustomInterfaces
 } // namespace MantidQt
 
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.h
index b1568d89e0f46936b75e13ba7263483f238cb87a..4a683f9ba10c45adc06eb0b1fb9f10db2a96d32f 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.h
@@ -8,63 +8,61 @@
 
 #include <QFont>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** IndirectMoments : Calculates the S(Q,w) Moments of the provided data with the user specified range and scale factor
-
-
-    @author Samuel Jackson
-    @date 13/08/2013
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport IndirectMoments : public IndirectDataReductionTab
-  {
-    Q_OBJECT
-
-  public:
-    IndirectMoments(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~IndirectMoments() override;
-
-    void setup() override;
-    void run() override;
-    bool validate() override;
-
-  protected slots:
-    // Handle when a file/workspace is ready for plotting
-    void handleSampleInputReady(const QString&);
-    /// Slot for when the range selector changes
-    void rangeChanged(double min, double max);
-    /// Slot to update the guides when the range properties change
-	void updateProperties(QtProperty* prop, double val);
-    /// Called when the algorithm completes to update preview plot
-    void momentsAlgComplete(bool error);
-
-  private:
-    Ui::IndirectMoments m_uiForm;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+/** IndirectMoments : Calculates the S(Q,w) Moments of the provided data with
+  the user specified range and scale factor
+
+
+  @author Samuel Jackson
+  @date 13/08/2013
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport IndirectMoments : public IndirectDataReductionTab {
+  Q_OBJECT
+
+public:
+  IndirectMoments(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~IndirectMoments() override;
+
+  void setup() override;
+  void run() override;
+  bool validate() override;
+
+protected slots:
+  // Handle when a file/workspace is ready for plotting
+  void handleSampleInputReady(const QString &);
+  /// Slot for when the range selector changes
+  void rangeChanged(double min, double max);
+  /// Slot to update the guides when the range properties change
+  void updateProperties(QtProperty *prop, double val);
+  /// Called when the algorithm completes to update preview plot
+  void momentsAlgComplete(bool error);
+
+private:
+  Ui::IndirectMoments m_uiForm;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif  /* MANTID_CUSTOMINTERFACES_INDIRECTMOMENTS_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_INDIRECTMOMENTS_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSassena.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSassena.h
index 32ed04c22e479c0922eaa53725d539a8e01e7594..a0a8ef7e2bedadfe2f47e53a74a22240ebc29d45 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSassena.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSassena.h
@@ -4,36 +4,32 @@
 #include "ui_IndirectSassena.h"
 #include "IndirectSimulationTab.h"
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		class DLLExport IndirectSassena : public IndirectSimulationTab
-		{
-			Q_OBJECT
-
-		public:
-			IndirectSassena(QWidget * parent = 0);
-
-                        void setup() override;
-                        bool validate() override;
-                        void run() override;
-
-                        /// Load default settings into the interface
-                        void loadSettings(const QSettings &settings) override;
-
-                      private slots:
-                        /// Handle completion of the algorithm batch
-                        void handleAlgorithmFinish(bool error);
-
-                      private:
-			/// The ui form
-			Ui::IndirectSassena m_uiForm;
-      /// Name of the output workspace group
-      QString m_outWsName;
-
-		};
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport IndirectSassena : public IndirectSimulationTab {
+  Q_OBJECT
+
+public:
+  IndirectSassena(QWidget *parent = 0);
+
+  void setup() override;
+  bool validate() override;
+  void run() override;
+
+  /// Load default settings into the interface
+  void loadSettings(const QSettings &settings) override;
+
+private slots:
+  /// Handle completion of the algorithm batch
+  void handleAlgorithmFinish(bool error);
+
+private:
+  /// The ui form
+  Ui::IndirectSassena m_uiForm;
+  /// Name of the output workspace group
+  QString m_outWsName;
+};
+} // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTSASSENA_H_
+#endif // MANTIDQTCUSTOMINTERFACES_INDIRECTSASSENA_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulation.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulation.h
index 8bf4b23e1f0acd03cfbc5323665494c021a23320..4624a4acc6474678e7f39bc5d898594637b77c5b 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulation.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulation.h
@@ -11,89 +11,83 @@
 
 #include <Poco/NObserver.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /**
-    This class defines the Indirect Simulation interface. It handles the creation of the interface window and
-    handles the interaction between the child tabs on the window.
-
-    @author Samuel Jackson, STFC
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-  class DLLExport IndirectSimulation : public MantidQt::API::UserSubWindow
-  {
-    Q_OBJECT
-
-    public: //public constants and enums
-
-      /// Enumeration for the index of each tab
-      enum TabChoice
-      {
-        MOLDYN,
-        SASSENA,
-        DOS
-      };
-
-    public: // public constructor, destructor and functions
-      /// Default Constructor
-      IndirectSimulation(QWidget *parent = 0);
-      /// Destructor
-      ~IndirectSimulation() override;
-      /// Interface name
-      static std::string name() { return "Simulation"; }
-      /// This interface's categories.
-      static QString categoryInfo() { return "Indirect"; }
-      /// Setup tab UI
-      void initLayout() override;
-
-    private slots:
-      /// Slot for clicking on the run button
-      void runClicked();
-      /// Slot for clicking on the help button
-      void helpClicked();
-      /// Slot for clicking on the manage directories button
-      void manageUserDirectories();
-      /// Slot showing a message box to the user
-      void showMessageBox(const QString& message);
-
-    private:
-      /// Load default interface settings for each tab
-      void loadSettings();
-      /// Called upon a close event.
-      void closeEvent(QCloseEvent *) override;
-      /// handle POCO event
-      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
-
-      /// Map of tabs indexed by position on the window
-      std::map<unsigned int, IndirectSimulationTab*> m_simulationTabs;
-      /// Change Observer for ConfigService (monitors user directories)
-      Poco::NObserver<IndirectSimulation, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
-      ///Main interface window
-      Ui::IndirectSimulation m_uiForm;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+/**
+  This class defines the Indirect Simulation interface. It handles the creation
+  of the interface window and
+  handles the interaction between the child tabs on the window.
+
+  @author Samuel Jackson, STFC
+
+  Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+  */
+
+class DLLExport IndirectSimulation : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public: // public constants and enums
+  /// Enumeration for the index of each tab
+  enum TabChoice { MOLDYN, SASSENA, DOS };
+
+public: // public constructor, destructor and functions
+  /// Default Constructor
+  IndirectSimulation(QWidget *parent = 0);
+  /// Destructor
+  ~IndirectSimulation() override;
+  /// Interface name
+  static std::string name() { return "Simulation"; }
+  /// This interface's categories.
+  static QString categoryInfo() { return "Indirect"; }
+  /// Setup tab UI
+  void initLayout() override;
+
+private slots:
+  /// Slot for clicking on the run button
+  void runClicked();
+  /// Slot for clicking on the help button
+  void helpClicked();
+  /// Slot for clicking on the manage directories button
+  void manageUserDirectories();
+  /// Slot showing a message box to the user
+  void showMessageBox(const QString &message);
+
+private:
+  /// Load default interface settings for each tab
+  void loadSettings();
+  /// Called upon a close event.
+  void closeEvent(QCloseEvent *) override;
+  /// handle POCO event
+  void
+  handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
+
+  /// Map of tabs indexed by position on the window
+  std::map<unsigned int, IndirectSimulationTab *> m_simulationTabs;
+  /// Change Observer for ConfigService (monitors user directories)
+  Poco::NObserver<IndirectSimulation,
+                  Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
+  /// Main interface window
+  Ui::IndirectSimulation m_uiForm;
+};
 }
 }
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulationTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulationTab.h
index 1c246c33d8fbd893b74d9b308dddb4725cf80a42..231d4b5b2eaa2d86cc1b33bf631e34032a634e4a 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulationTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSimulationTab.h
@@ -8,50 +8,50 @@
 #include <QSettings>
 #include <QWidget>
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		/**
-			This class defines a abstract base class for the different tabs of the Indirect Simulation interface.
-			Any joint functionality shared between each of the tabs should be implemented here as well as defining
-			shared member functions.
-
-			@author Samuel Jackson, STFC
-
-			Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-			This file is part of Mantid.
-
-			Mantid is free software; you can redistribute it and/or modify
-			it under the terms of the GNU General Public License as published by
-			the Free Software Foundation; either version 3 of the License, or
-			(at your option) any later version.
-
-			Mantid is distributed in the hope that it will be useful,
-			but WITHOUT ANY WARRANTY; without even the implied warranty of
-			MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-			GNU General Public License for more details.
-
-			You should have received a copy of the GNU General Public License
-			along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-			File change history is stored at: <https://github.com/mantidproject/mantid>
-			Code Documentation is available at: <http://doxygen.mantidproject.org>
-		*/
-
-		class DLLExport IndirectSimulationTab : public IndirectTab
-		{
-			Q_OBJECT
-
-		public:
-			IndirectSimulationTab(QWidget * parent = 0);
-                        ~IndirectSimulationTab() override;
-
-                        virtual void loadSettings(const QSettings& settings) = 0;
-
-		};
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+/**
+        This class defines a abstract base class for the different tabs of the
+   Indirect Simulation interface.
+        Any joint functionality shared between each of the tabs should be
+   implemented here as well as defining
+        shared member functions.
+
+        @author Samuel Jackson, STFC
+
+        Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak
+   Ridge National Laboratory & European Spallation Source
+
+        This file is part of Mantid.
+
+        Mantid is free software; you can redistribute it and/or modify
+        it under the terms of the GNU General Public License as published by
+        the Free Software Foundation; either version 3 of the License, or
+        (at your option) any later version.
+
+        Mantid is distributed in the hope that it will be useful,
+        but WITHOUT ANY WARRANTY; without even the implied warranty of
+        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+        GNU General Public License for more details.
+
+        You should have received a copy of the GNU General Public License
+        along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+        File change history is stored at:
+   <https://github.com/mantidproject/mantid>
+        Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class DLLExport IndirectSimulationTab : public IndirectTab {
+  Q_OBJECT
+
+public:
+  IndirectSimulationTab(QWidget *parent = 0);
+  ~IndirectSimulationTab() override;
+
+  virtual void loadSettings(const QSettings &settings) = 0;
+};
+} // namespace CustomInterfaces
 } // namespace Mantid
 
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.h
index 4c74c7cdcdd86c9254d05ca620288224f219ecfa..bad6a2e4bad227c329bbf3f3edba4ceae463b07d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSqw.h
@@ -6,56 +6,53 @@
 #include "ui_IndirectSqw.h"
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** IndirectSqw
+namespace MantidQt {
+namespace CustomInterfaces {
+/** IndirectSqw
 
-    @author Dan Nixon
-    @date 23/07/2014
+  @author Dan Nixon
+  @date 23/07/2014
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport IndirectSqw : public IndirectDataReductionTab
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport IndirectSqw : public IndirectDataReductionTab {
+  Q_OBJECT
 
-  public:
-    IndirectSqw(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~IndirectSqw() override;
+public:
+  IndirectSqw(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~IndirectSqw() override;
 
-    void setup() override;
-    void run() override;
-    bool validate() override;
+  void setup() override;
+  void run() override;
+  bool validate() override;
 
-  private slots:
-    void plotContour();
-    void sqwAlgDone(bool error);
+private slots:
+  void plotContour();
+  void sqwAlgDone(bool error);
 
-  private:
-    Ui::IndirectSqw m_uiForm;
-
-  };
+private:
+  Ui::IndirectSqw m_uiForm;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTSQW_H_
+#endif // MANTIDQTCUSTOMINTERFACES_INDIRECTSQW_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h
index ffb02b5d7cababcf765f7be73569e48bde75ced3..ea7976eb522b6adf14e38a74cd6a3e2f84e37ae5 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h
@@ -9,80 +9,77 @@
 
 // Suppress a warning coming out of code that isn't ours
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1125
+#pragma warning disable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Woverloaded-virtual"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 #include <QtCheckBoxFactory>
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1125
+#pragma warning enable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** IndirectSymmetrise
-
-    @author Dan Nixon
-    @date 23/07/2014
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport IndirectSymmetrise : public IndirectDataReductionTab
-  {
-    Q_OBJECT
-
-  public:
-    IndirectSymmetrise(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~IndirectSymmetrise() override;
-
-    void setup() override;
-    void run() override;
-    bool validate() override;
-
-  private slots:
-    void algorithmComplete(bool error);
-    void plotRawInput(const QString &workspaceName);
-    void updateMiniPlots();
-    void replotNewSpectrum(QtProperty *prop, double value);
-    void verifyERange(QtProperty *prop, double value);
-    void updateRangeSelectors(QtProperty *prop, double value);
-    void preview();
-    void previewAlgDone(bool error);
-    void xRangeMaxChanged(double value);
-    void xRangeMinChanged(double value);
-
-  private:
-    Ui::IndirectSymmetrise m_uiForm;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+/** IndirectSymmetrise
+
+  @author Dan Nixon
+  @date 23/07/2014
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport IndirectSymmetrise : public IndirectDataReductionTab {
+  Q_OBJECT
+
+public:
+  IndirectSymmetrise(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~IndirectSymmetrise() override;
+
+  void setup() override;
+  void run() override;
+  bool validate() override;
+
+private slots:
+  void algorithmComplete(bool error);
+  void plotRawInput(const QString &workspaceName);
+  void updateMiniPlots();
+  void replotNewSpectrum(QtProperty *prop, double value);
+  void verifyERange(QtProperty *prop, double value);
+  void updateRangeSelectors(QtProperty *prop, double value);
+  void preview();
+  void previewAlgDone(bool error);
+  void xRangeMaxChanged(double value);
+  void xRangeMinChanged(double value);
+
+private:
+  Ui::IndirectSymmetrise m_uiForm;
+};
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTSYMMETRISE_H_
+#endif // MANTIDQTCUSTOMINTERFACES_INDIRECTSYMMETRISE_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTools.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTools.h
index 028fa0f64ae7608bba1d746eab39aef78c2c22dc..d5f4105d319eba8bdd7bd08a1fd6ddfb684f1455 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTools.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTools.h
@@ -11,88 +11,84 @@
 
 #include <Poco/NObserver.h>
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /**
-    This class defines the Indirect Foreign interface. It handles the creation of the interface window and
-		handles the interaction between the child tabs on the window.
-
-    @author Samuel Jackson, STFC
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-    class DLLExport IndirectTools : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-		public: //public constants and enums
-
-      /// Enumeration for the index of each tab
-			enum TabChoice
-			{
-        TRANSMISSION,
-				LOAD_ILL
-			};
-
-    public: // public constructor, destructor and functions
-      /// Default Constructor
-      IndirectTools(QWidget *parent = 0);
-      ///Destructor
-      ~IndirectTools() override;
-      /// Interface name
-      static std::string name() { return "Tools"; }
-      // This interface's categories.
-      static QString categoryInfo() { return "Indirect"; }
-
-      void initLayout() override;
-
-    private slots:
-      /// Slot for clicking on the run button
-      void runClicked();
-      /// Slot for clicking on the hlep button
-      void helpClicked();
-      /// Slot for clicking on the manage directories button
-      void manageUserDirectories();
-      /// Slot showing a message box to the user
-      void showMessageBox(const QString& message);
-
-		private:
-      /// Load default interface settings for each tab
-      void loadSettings();
-      /// Called upon a close event.
-      void closeEvent(QCloseEvent *) override;
-      /// Handle POCO event
-      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
-
-      /// Map of tabs indexed by position on the window
-			std::map<unsigned int, IndirectToolsTab*> m_tabs;
-      /// Change Observer for ConfigService (monitors user directories)
-      Poco::NObserver<IndirectTools, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
-      /// Main interface window
-      Ui::IndirectTools m_uiForm;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/**
+This class defines the Indirect Foreign interface. It handles the creation of
+the interface window and
+            handles the interaction between the child tabs on the window.
+
+@author Samuel Jackson, STFC
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class DLLExport IndirectTools : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public: // public constants and enums
+  /// Enumeration for the index of each tab
+  enum TabChoice { TRANSMISSION, LOAD_ILL };
+
+public: // public constructor, destructor and functions
+  /// Default Constructor
+  IndirectTools(QWidget *parent = 0);
+  /// Destructor
+  ~IndirectTools() override;
+  /// Interface name
+  static std::string name() { return "Tools"; }
+  // This interface's categories.
+  static QString categoryInfo() { return "Indirect"; }
+
+  void initLayout() override;
+
+private slots:
+  /// Slot for clicking on the run button
+  void runClicked();
+  /// Slot for clicking on the hlep button
+  void helpClicked();
+  /// Slot for clicking on the manage directories button
+  void manageUserDirectories();
+  /// Slot showing a message box to the user
+  void showMessageBox(const QString &message);
+
+private:
+  /// Load default interface settings for each tab
+  void loadSettings();
+  /// Called upon a close event.
+  void closeEvent(QCloseEvent *) override;
+  /// Handle POCO event
+  void
+  handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
+
+  /// Map of tabs indexed by position on the window
+  std::map<unsigned int, IndirectToolsTab *> m_tabs;
+  /// Change Observer for ConfigService (monitors user directories)
+  Poco::NObserver<IndirectTools, Mantid::Kernel::ConfigValChangeNotification>
+      m_changeObserver;
+  /// Main interface window
+  Ui::IndirectTools m_uiForm;
+};
+}
 }
 
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectToolsTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectToolsTab.h
index a651fdf45c77cabd1308106a76be7b4621c15600..bf2b36131fc6d2b74d216efdc34b15357a678925 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectToolsTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectToolsTab.h
@@ -10,15 +10,15 @@ namespace MantidQt {
 namespace CustomInterfaces {
 /**
     This class defines a abstract base class for the different tabs of the
-	Indirect Foreign interface.
+        Indirect Foreign interface.
     Any joint functionality shared between each of the tabs should be
-	implemented here as well as defining
+        implemented here as well as defining
     shared member functions.
 
     @author Samuel Jackson, STFC
 
     Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak
-	Ridge National Laboratory & European Spallation Source
+        Ridge National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -32,12 +32,12 @@ namespace CustomInterfaces {
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
 
-	You should have received a copy of the GNU General Public License
+        You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at:
-	<https://github.com/mantidproject/mantid>
-	Code Documentation is available at: <http://doxygen.mantidproject.org>
+        <https://github.com/mantidproject/mantid>
+        Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
 class DLLExport IndirectToolsTab : public IndirectTab {
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h
index d696d8aa31e2e41a67e03a917b3b8429a525497c..70af3e7d0f5febd4c83623c05e58f6ad716e9185 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h
@@ -5,64 +5,61 @@
 #include "ui_IndirectTransmission.h"
 #include "MantidKernel/System.h"
 
+namespace MantidQt {
+namespace CustomInterfaces {
+/** IndirectTransmission
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** IndirectTransmission
+  Provides the UI interface to the IndirectTransmissionMonitor algorithm to
+  calculate
+  sample transmission using a sample and container raw run file.
 
-    Provides the UI interface to the IndirectTransmissionMonitor algorithm to calculate
-    sample transmission using a sample and container raw run file.
 
+  @author Samuel Jackson
+  @date 13/08/2013
 
-    @author Samuel Jackson
-    @date 13/08/2013
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  This file is part of Mantid.
 
-    This file is part of Mantid.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport IndirectTransmission : public IndirectDataReductionTab {
+  Q_OBJECT
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport IndirectTransmission : public IndirectDataReductionTab
-  {
-    Q_OBJECT
+public:
+  IndirectTransmission(IndirectDataReduction *idrUI, QWidget *parent = 0);
+  ~IndirectTransmission() override;
 
-  public:
-    IndirectTransmission(IndirectDataReduction * idrUI, QWidget * parent = 0);
-    ~IndirectTransmission() override;
+  void setup() override;
+  void run() override;
+  bool validate() override;
 
-    void setup() override;
-    void run() override;
-    bool validate() override;
+private slots:
+  void dataLoaded();
+  void previewPlot();
+  void transAlgDone(bool error);
+  void instrumentSet();
 
-  private slots:
-    void dataLoaded();
-    void previewPlot();
-    void transAlgDone(bool error);
-    void instrumentSet();
-
-  private:
-    Ui::IndirectTransmission m_uiForm;
-
-  };
+private:
+  Ui::IndirectTransmission m_uiForm;
+};
 
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif  /* MANTID_CUSTOMINTERFACES_INDIRECTTRANSMISSION_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_INDIRECTTRANSMISSION_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.h
index e94ee9bcc203cabe9e8e7b9e8c73eb88a3499ecc..88c2a5eeca2a0c5bf29442bd4218d2240678ffe3 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.h
@@ -9,37 +9,33 @@
 #include <QMap>
 #include <QStringList>
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		class DLLExport IndirectTransmissionCalc : public IndirectToolsTab
-		{
-			Q_OBJECT
-
-		public:
-			IndirectTransmissionCalc(QWidget * parent = 0);
-
-			/// Load default settings into the interface
-                        void loadSettings(const QSettings &settings) override;
-
-                      protected:
-                        void setup() override;
-                        bool validate() override;
-                        void run() override;
-
-                      private slots:
-                        /// Handles completion of the algorithm
-                        void algorithmComplete(bool error);
-
-                      private:
-			/// The UI form
-			Ui::IndirectTransmissionCalc m_uiForm;
-      /// The name of the current instrument
-      QString m_instrument;
-
-		};
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport IndirectTransmissionCalc : public IndirectToolsTab {
+  Q_OBJECT
+
+public:
+  IndirectTransmissionCalc(QWidget *parent = 0);
+
+  /// Load default settings into the interface
+  void loadSettings(const QSettings &settings) override;
+
+protected:
+  void setup() override;
+  bool validate() override;
+  void run() override;
+
+private slots:
+  /// Handles completion of the algorithm
+  void algorithmComplete(bool error);
+
+private:
+  /// The UI form
+  Ui::IndirectTransmissionCalc m_uiForm;
+  /// The name of the current instrument
+  QString m_instrument;
+};
+} // namespace CustomInterfaces
 } // namespace MantidQt
 
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.h
index 5fae81441816c48738ec5a3c2131e9738b63e0c7..cb97adadb0ee26ab64393d58d1ea1060793a5777 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.h
@@ -4,42 +4,37 @@
 #include "ui_MSDFit.h"
 #include "IndirectDataAnalysisTab.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  class DLLExport MSDFit : public IndirectDataAnalysisTab
-  {
-    Q_OBJECT
-
-  public:
-    MSDFit(QWidget * parent = 0);
-
-  private:
-    void setup() override;
-    void run() override;
-    bool validate() override;
-    void loadSettings(const QSettings &settings) override;
-
-  private slots:
-    void singleFit();
-    void plotFit(QString wsName = QString(), int specNo = -1);
-    void newDataLoaded(const QString wsName);
-    void plotInput();
-    void specMinChanged(int value);
-    void specMaxChanged(int value);
-    void minChanged(double val);
-    void maxChanged(double val);
-    void updateRS(QtProperty* prop, double val);
-
-  private:
-    Ui::MSDFit m_uiForm;
-    QString m_currentWsName;
-    QtTreePropertyBrowser* m_msdTree;
-
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+class DLLExport MSDFit : public IndirectDataAnalysisTab {
+  Q_OBJECT
+
+public:
+  MSDFit(QWidget *parent = 0);
+
+private:
+  void setup() override;
+  void run() override;
+  bool validate() override;
+  void loadSettings(const QSettings &settings) override;
+
+private slots:
+  void singleFit();
+  void plotFit(QString wsName = QString(), int specNo = -1);
+  void newDataLoaded(const QString wsName);
+  void plotInput();
+  void specMinChanged(int value);
+  void specMaxChanged(int value);
+  void minChanged(double val);
+  void maxChanged(double val);
+  void updateRS(QtProperty *prop, double val);
+
+private:
+  Ui::MSDFit m_uiForm;
+  QString m_currentWsName;
+  QtTreePropertyBrowser *m_msdTree;
+};
 } // namespace IDA
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.h
index 90e111e33575efc6568da4757b7cdda75c867296..de342d04e901b733d72793c5eba36c1424de9334 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.h
@@ -4,41 +4,36 @@
 #include "ui_Stretch.h"
 #include "IndirectBayesTab.h"
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		class DLLExport Stretch : public IndirectBayesTab
-		{
-			Q_OBJECT
-
-		public:
-			Stretch(QWidget * parent = 0);
-
-			// Inherited methods from IndirectBayesTab
-                        void setup() override;
-                        bool validate() override;
-                        void run() override;
-                        /// Load default settings into the interface
-                        void loadSettings(const QSettings &settings) override;
-
-                      private slots:
-			/// Slot for when the min range on the range selector changes
-			void minValueChanged(double min);
-			/// Slot for when the min range on the range selector changes
-			void maxValueChanged(double max);
-			/// Slot to update the guides when the range properties change
-                        void updateProperties(QtProperty *prop,
-                                              double val) override;
-                        /// Slot to handle when a new sample file is available
-			void handleSampleInputReady(const QString& filename);
-
-		private:
-			//The ui form
-			Ui::Stretch m_uiForm;
-
-		};
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+class DLLExport Stretch : public IndirectBayesTab {
+  Q_OBJECT
+
+public:
+  Stretch(QWidget *parent = 0);
+
+  // Inherited methods from IndirectBayesTab
+  void setup() override;
+  bool validate() override;
+  void run() override;
+  /// Load default settings into the interface
+  void loadSettings(const QSettings &settings) override;
+
+private slots:
+  /// Slot for when the min range on the range selector changes
+  void minValueChanged(double min);
+  /// Slot for when the min range on the range selector changes
+  void maxValueChanged(double max);
+  /// Slot to update the guides when the range properties change
+  void updateProperties(QtProperty *prop, double val) override;
+  /// Slot to handle when a new sample file is available
+  void handleSampleInputReady(const QString &filename);
+
+private:
+  // The ui form
+  Ui::Stretch m_uiForm;
+};
+} // namespace CustomInterfaces
 } // namespace MantidQt
 
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticePresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticePresenter.h
index d73c3f773b228c71ed521be5e56c6f81aa851439..f29ea2adbfec5a6d930d6531a7208ff43e938451 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticePresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticePresenter.h
@@ -3,51 +3,51 @@
 
 #include "MantidQtCustomInterfaces/Updateable.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    class LatticeView;
-    class LoanedMemento;
-
-
-    /** Presenter of MVP type for controlling interaction of lattice view with WorkspaceMementos.
-  
-      @author Owen Arnold, RAL ISIS
-      @date 06/Oct/2011
-
-      Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>.
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-     */
-    class DLLExport LatticePresenter : public Updateable
-    {
-    public:
-      LatticePresenter(LoanedMemento& memento);
-      ~LatticePresenter();
-      void update();
-      void acceptView(LatticeView* view);
-    private:
-      bool checkInput(double a1, double a2, double a3, double b1, double b2, double b3);
-      LatticeView* m_view;
-      LoanedMemento& m_WsMemento;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+class LatticeView;
+class LoanedMemento;
+
+/** Presenter of MVP type for controlling interaction of lattice view with
+  WorkspaceMementos.
+
+  @author Owen Arnold, RAL ISIS
+  @date 06/Oct/2011
+
+  Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>.
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class DLLExport LatticePresenter : public Updateable {
+public:
+  LatticePresenter(LoanedMemento &memento);
+  ~LatticePresenter();
+  void update();
+  void acceptView(LatticeView *view);
+
+private:
+  bool checkInput(double a1, double a2, double a3, double b1, double b2,
+                  double b3);
+  LatticeView *m_view;
+  LoanedMemento &m_WsMemento;
+};
+}
 }
 #endif
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticeView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticeView.h
index bef0be654e69dd9cffc0e597e1f18faeff0ea65a..e075d84b2c8874f7c7ec9afb58b64cebe8b7b605 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticeView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/LatticeView.h
@@ -1,50 +1,49 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_LATTICE_VIEW_H
 #define MANTIDQTCUSTOMINTERFACES_LATTICE_VIEW_H
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** Abstract lattice view.
-  
-      @author Owen Arnold, RAL ISIS
-      @date 06/Oct/2011
-
-      Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>.
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-     */
-    class LatticeView 
-    {
-    public:
-      virtual double getA1() const = 0;
-      virtual double getA2() const = 0;
-      virtual double getA3() const = 0;
-      virtual double getB1() const = 0;
-      virtual double getB2() const = 0;
-      virtual double getB3() const = 0;
-      virtual void indicateModified() = 0;
-      virtual void indicateDefault() = 0;
-      virtual void indicateInvalid() = 0;
-      virtual void initalize(double a1, double a2, double a3, double b1, double b2, double b3) = 0;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/** Abstract lattice view.
+
+  @author Owen Arnold, RAL ISIS
+  @date 06/Oct/2011
+
+  Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>.
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class LatticeView {
+public:
+  virtual double getA1() const = 0;
+  virtual double getA2() const = 0;
+  virtual double getA3() const = 0;
+  virtual double getB1() const = 0;
+  virtual double getB2() const = 0;
+  virtual double getB3() const = 0;
+  virtual void indicateModified() = 0;
+  virtual void indicateDefault() = 0;
+  virtual void indicateInvalid() = 0;
+  virtual void initalize(double a1, double a2, double a3, double b1, double b2,
+                         double b3) = 0;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEV.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEV.h
index 5f2a6d561e9bf9c9e24eb89cdb2fa4ad1617606e..01e3b75bdec19a131e5f0faceaa5e3094b67685c 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEV.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEV.h
@@ -14,14 +14,12 @@
 #include "MantidQtAPI/UserSubWindow.h"
 #include "MantidQtAPI/SelectionNotificationService.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 // NOTE: The first several internal classes are just simple QRunnable
 // objects that will run worker code using one or more algorithms, in
-// a separate thread.  This avoids blocking the MantidPlot GUI by 
+// a separate thread.  This avoids blocking the MantidPlot GUI by
 // keeping the main Qt thread free.
 //
 
@@ -30,23 +28,17 @@ namespace CustomInterfaces
 //
 
 /// Local class to load file and convert to MD in a Non-Qt thread.
-class RunLoadAndConvertToMD : public QRunnable
-{
-  public:
-
+class RunLoadAndConvertToMD : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunLoadAndConvertToMD(MantidEVWorker * worker,
-                         const std::string    & file_name,
-                         const std::string    & ev_ws_name,
-                         const std::string    & md_ws_name,
-                         const double           modQ,
-                         const double           minQ,
-                         const double           maxQ,
-                         const bool             do_lorentz_corr,
-                         const bool             load_data,
-                         const bool             load_det_cal,
-                         const std::string    & det_cal_file,
-                         const std::string    & det_cal_file2 );
+  RunLoadAndConvertToMD(MantidEVWorker *worker, const std::string &file_name,
+                        const std::string &ev_ws_name,
+                        const std::string &md_ws_name, const double modQ,
+                        const double minQ, const double maxQ,
+                        const bool do_lorentz_corr, const bool load_data,
+                        const bool load_det_cal,
+                        const std::string &det_cal_file,
+                        const std::string &det_cal_file2);
 
   /// Calls worker->loadAndConvertToMD from a separate thread
   void run() override;
@@ -66,22 +58,14 @@ private:
   std::string det_cal_file2;
 };
 
-
 /// Local class to run FindPeaks in a Non-Qt thread.
-class RunFindPeaks : public QRunnable
-{
-  public:
-
+class RunFindPeaks : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunFindPeaks(       MantidEVWorker * worker,
-                const std::string    & ev_ws_name,
-                const std::string    & md_ws_name,
-                const std::string    & peaks_ws_name,
-                      double           max_abc,
-                      size_t           num_to_find,
-                      double           min_intensity,
-                      double minQPeaks,
-                      double maxQPeaks);
+  RunFindPeaks(MantidEVWorker *worker, const std::string &ev_ws_name,
+               const std::string &md_ws_name, const std::string &peaks_ws_name,
+               double max_abc, size_t num_to_find, double min_intensity,
+               double minQPeaks, double maxQPeaks);
 
   /// Calls worker->findPeaks from a separate thread
   void run() override;
@@ -99,17 +83,12 @@ private:
 };
 
 /// Local class to run PredictPeaks in a Non-Qt thread.
-class RunPredictPeaks : public QRunnable
-{
-  public:
-
+class RunPredictPeaks : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunPredictPeaks(       MantidEVWorker * worker,
-                const std::string    & peaks_ws_name,
-                      double           min_pred_wl,
-                      double           max_pred_wl,
-                      double           min_pred_dspacing,
-                      double           max_pred_dspacing );
+  RunPredictPeaks(MantidEVWorker *worker, const std::string &peaks_ws_name,
+                  double min_pred_wl, double max_pred_wl,
+                  double min_pred_dspacing, double max_pred_dspacing);
 
   /// Calls worker->predictPeaks from a separate thread
   void run() override;
@@ -124,22 +103,15 @@ private:
 };
 
 /// Local class to run IntegratePeaksMD in a Non-Qt thread.
-class RunSphereIntegrate : public QRunnable
-{
-  public:
-
+class RunSphereIntegrate : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunSphereIntegrate(       MantidEVWorker * worker,
-                      const std::string    & peaks_ws_name,
-                      const std::string    & event_ws_name,
-                            double           peak_radius,
-                            double           inner_radius,
-                            double           outer_radius,
-                            bool             integrate_edge,
-                            bool             use_cylinder_integration,
-                            double           cylinder_length,
-                            double           cylinder_percent_bkg,
-                      const std::string &    cylinder_profile_fit);
+  RunSphereIntegrate(MantidEVWorker *worker, const std::string &peaks_ws_name,
+                     const std::string &event_ws_name, double peak_radius,
+                     double inner_radius, double outer_radius,
+                     bool integrate_edge, bool use_cylinder_integration,
+                     double cylinder_length, double cylinder_percent_bkg,
+                     const std::string &cylinder_profile_fit);
 
   /// Calls worker->sphereIntegrate from a separate thread
   void run() override;
@@ -158,19 +130,14 @@ private:
   std::string cylinder_profile_fit;
 };
 
-
 /// Local class to run PeakIntegration in a Non-Qt thread.
-class RunFitIntegrate : public QRunnable
-{
-  public:
-
+class RunFitIntegrate : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunFitIntegrate(       MantidEVWorker * worker,
-                   const std::string    & peaks_ws_name,
-                   const std::string    & event_ws_name,
-                   const std::string    & rebin_params,
-                         size_t           n_bad_edge_pix,
-                         bool             use_ikeda_carpenter );
+  RunFitIntegrate(MantidEVWorker *worker, const std::string &peaks_ws_name,
+                  const std::string &event_ws_name,
+                  const std::string &rebin_params, size_t n_bad_edge_pix,
+                  bool use_ikeda_carpenter);
 
   /// Calls worker->fitIntegrate from a separate thread
   void run() override;
@@ -184,21 +151,15 @@ private:
   bool use_ikeda_carpenter;
 };
 
-
 /// Local class to run ellipsoidIntegrate in a Non-Qt thread.
-class RunEllipsoidIntegrate : public QRunnable
-{
-  public:
-
+class RunEllipsoidIntegrate : public QRunnable {
+public:
   /// Constructor just saves the info needed by the run() method
-  RunEllipsoidIntegrate(       MantidEVWorker * worker,
-                         const std::string    & peaks_ws_name,
-                         const std::string    & event_ws_name,
-                               double           region_radius,
-                               bool             specify_size,
-                               double           peak_size, 
-                               double           inner_size, 
-                               double           outer_size );
+  RunEllipsoidIntegrate(MantidEVWorker *worker,
+                        const std::string &peaks_ws_name,
+                        const std::string &event_ws_name, double region_radius,
+                        bool specify_size, double peak_size, double inner_size,
+                        double outer_size);
 
   /// Calls worker->ellipsoidIntegrate from a separate thread
   void run() override;
@@ -214,7 +175,6 @@ private:
   double outer_size;
 };
 
-
 //
 // END OF SIMPLE QRunnable classes -------------------------------------
 //
@@ -226,12 +186,10 @@ private:
  *  and then call methods in the MantidEVWorker class.  Roughly speaking,
  *  MantidEV deals with the Qt GUI and MantideEVWorker deals with Mantid.
  */
-class MantidEV : public API::UserSubWindow
-{
+class MantidEV : public API::UserSubWindow {
   Q_OBJECT
 
 public:
-
   /// Constructor
   MantidEV(QWidget *parent = 0);
 
@@ -245,56 +203,56 @@ public:
 
 public slots:
   /// Slot for Q-Point selection notification
-  void QPointSelection_slot( bool, double, double, double );
+  void QPointSelection_slot(bool, double, double, double);
 
 private slots:
 
   /// Go to help page
   void help_slot();
 
-  /// Slot for the select workspace tab's Apply button 
+  /// Slot for the select workspace tab's Apply button
   void selectWorkspace_slot();
 
-  /// Slot for the Finished Editing text for loading an event file 
+  /// Slot for the Finished Editing text for loading an event file
   void loadEventFileEntered_slot();
 
-  /// Slot for the Browse button for loading an event file 
+  /// Slot for the Browse button for loading an event file
   void loadEventFile_slot();
 
-  /// Slot for the Browse button for loading the first calibration file 
+  /// Slot for the Browse button for loading the first calibration file
   void selectDetCalFile_slot();
 
-  /// Slot for the Browse button for loading the second calibration file 
+  /// Slot for the Browse button for loading the second calibration file
   void selectDetCalFile2_slot();
 
-  /// Slot for the find peaks tab's Apply button 
+  /// Slot for the find peaks tab's Apply button
   void findPeaks_slot();
 
   /// Slot for choosing a peaks file name
   void getLoadPeaksFileName_slot();
 
-  /// Slot for the find UB tab's Apply button 
+  /// Slot for the find UB tab's Apply button
   void findUB_slot();
 
   /// Slot for choosing a matrix file name
   void getLoadUB_FileName_slot();
 
-  /// Slot for the choose cell tab's Apply button 
+  /// Slot for the choose cell tab's Apply button
   void chooseCell_slot();
 
-  /// Slot for the change HKL tab's Apply button 
+  /// Slot for the change HKL tab's Apply button
   void changeHKL_slot();
 
-  /// Slot for the integrate tab's Apply button 
+  /// Slot for the integrate tab's Apply button
   void integratePeaks_slot();
 
   /// Slot for Show Info button on Point Info form
   void showInfo_slot();
 
-  // 
+  //
   // The following slots take care of the menu items
   //
- 
+
   /// Slot to save the current MantidEV GUI state
   void saveState_slot();
 
@@ -310,7 +268,7 @@ private slots:
   /// Slot to a previous UB matrix into the current MantidEV peaks workspace
   void loadIsawUB_slot();
 
-  /// Slot to save the current MantidEV peaks workspace 
+  /// Slot to save the current MantidEV peaks workspace
   void saveIsawPeaks_slot();
 
   /// Slot to load a peaks workspace to the current MantidEV named workspace
@@ -324,146 +282,144 @@ private slots:
 
   /// Slot to show the UB matrix
   void showUB_slot();
-  
+
   //
   // The following slots just take care of enabling and disabling
   // some of the controls, as needed
   //
 
   /// Slot to enable/disable the Load Event File controls
-  void setEnabledLoadEventFileParams_slot( bool on );
+  void setEnabledLoadEventFileParams_slot(bool on);
 
   /// Slot to enable/disable the .DetCal file info
   void setEnabledLoadCalFiles_slot();
 
   /// Slot to enable/disable the find peaks controls
-  void setEnabledFindPeaksParams_slot( bool on );
+  void setEnabledFindPeaksParams_slot(bool on);
 
   /// Slot to enable/disable the predict peaks controls
   void setEnabledPredictPeaksParams_slot();
 
   /// Slot to enable/disable the Load Peaks File controls
-  void setEnabledLoadPeaksParams_slot( bool on );
+  void setEnabledLoadPeaksParams_slot(bool on);
 
   /// Slot to enable/disable the find UB using FFT controls
-  void setEnabledFindUBFFTParams_slot( bool on );
+  void setEnabledFindUBFFTParams_slot(bool on);
 
   /// Slot to enable/disable the find UB using Indexed Peaks controls
-  void setEnabledFindUBUsingIndexedPeaksParams_slot( bool on );
+  void setEnabledFindUBUsingIndexedPeaksParams_slot(bool on);
 
   /// Slot to enable/disable the load UB controls
-  void setEnabledLoadUBParams_slot( bool on );
+  void setEnabledLoadUBParams_slot(bool on);
 
   /// Slot to enable/disable the optimize goniometer angles controls
   void setEnabledMaxOptimizeDegrees_slot();
 
   /// Slot to enable/disable the index peaks controls
-  void setEnabledIndexParams_slot( bool on );
+  void setEnabledIndexParams_slot(bool on);
 
   /// Slot to enable/disable the show conventional cell controls
-  void setEnabledShowCellsParams_slot( bool on );
+  void setEnabledShowCellsParams_slot(bool on);
 
   /// Slot to enable/disable the select cell based on cell type controls
-  void setEnabledSetCellTypeParams_slot(bool on );
+  void setEnabledSetCellTypeParams_slot(bool on);
 
   /// Slot to enable/disable the select cell based on cell number controls
-  void setEnabledSetCellFormParams_slot(bool on );
+  void setEnabledSetCellFormParams_slot(bool on);
 
   /// Slot to enable/disable the sphere integration controls
-  void setEnabledSphereIntParams_slot( bool on );
+  void setEnabledSphereIntParams_slot(bool on);
 
   /// Slot to enable/disable the 2D fitting integration controls
-  void setEnabledFitIntParams_slot( bool on );
+  void setEnabledFitIntParams_slot(bool on);
 
   /// Slot to enable/disable the ellipsoidal integration controls
-  void setEnabledEllipseIntParams_slot( bool on );
+  void setEnabledEllipseIntParams_slot(bool on);
 
   /// Slot to enable/disable the ellipse size options controls
   void setEnabledEllipseSizeOptions_slot();
 
   /// Method to get and display info about the specified Q-vector
-  void showInfo( bool lab_coords, Mantid::Kernel::V3D  q_point );
+  void showInfo(bool lab_coords, Mantid::Kernel::V3D q_point);
 
 private:
   /// super class pure virtual method we MUST implement
   void initLayout() override;
 
   /// Utility method to display an error message
-  void errorMessage( const std::string & message );
+  void errorMessage(const std::string &message);
 
   /// Utility method to parse a double value in a string
-  bool getDouble( std::string str, double & value );
+  bool getDouble(std::string str, double &value);
 
-  /// Utility method to get a double value from a QtLineEdit widget 
-  bool getDouble( QLineEdit *ledt, double & value );
+  /// Utility method to get a double value from a QtLineEdit widget
+  bool getDouble(QLineEdit *ledt, double &value);
 
-  /// Utility method to get a positive double from a QtLineEdit widget 
-  bool getPositiveDouble( QLineEdit *ledt, double & value );
+  /// Utility method to get a positive double from a QtLineEdit widget
+  bool getPositiveDouble(QLineEdit *ledt, double &value);
 
-  /// Utility method to get a positive integer value from a QtLineEdit widget 
-  bool getPositiveInt( QLineEdit *ledt, size_t & value );
+  /// Utility method to get a positive integer value from a QtLineEdit widget
+  bool getPositiveInt(QLineEdit *ledt, size_t &value);
 
   /// Get base file name to form names for event, MD and peaks workspaces
-  std::string extractBaseFileName( std::string FullFileName) const;
+  std::string extractBaseFileName(std::string FullFileName) const;
 
   /// Get path name from file, or user's home directory
-  QString getFilePath( const std::string & file_name );
+  QString getFilePath(const std::string &file_name);
 
   /// Get name of file for saving peaks
   void getSavePeaksFileName();
 
-  /// Get name of file for saving UB matrix 
+  /// Get name of file for saving UB matrix
   void getSaveUB_FileName();
 
   /// Save QSettings to specified file, or default, if filename empty
-  void saveSettings( const std::string & filename );
+  void saveSettings(const std::string &filename);
 
   /// Load QSettings from specified file, or default, if filename empty
-  void loadSettings( const std::string & filename );
+  void loadSettings(const std::string &filename);
 
   /// Restore the value of the QLineEdit component from QSettings
-  void restore( QSettings *state, QString name, QLineEdit *ledt );
+  void restore(QSettings *state, QString name, QLineEdit *ledt);
 
   /// Restore the value of the QCheckbox or QRadioButton from QSettings
-  void restore( QSettings *state, QString name, QAbstractButton *btn );
+  void restore(QSettings *state, QString name, QAbstractButton *btn);
 
   /// Restore the value of a QComboBox from QSettings
-  void restore( QSettings *state, QString name, QComboBox *cmbx );
+  void restore(QSettings *state, QString name, QComboBox *cmbx);
 
+  Ui::MantidEV m_uiForm; /// The form generated by Qt Designer
 
-  Ui::MantidEV   m_uiForm;     /// The form generated by Qt Designer
+  MantidEVWorker *worker; /// class that uses Mantid algorithms
+                          /// to do the actual work
 
-  MantidEVWorker *worker;      /// class that uses Mantid algorithms
-                               /// to do the actual work
+  std::string last_cal_file; /// filename of last ISAW DetCal file for
+                             /// the whole instrument or for panel 1 of SNAP
 
-  std::string  last_cal_file;  /// filename of last ISAW DetCal file for
-                               /// the whole instrument or for panel 1 of SNAP
+  std::string last_cal_file2; /// filename of last ISAW DetCal file for
+                              /// panel 2 of SNAP
 
-  std::string  last_cal_file2; /// filename of last ISAW DetCal file for
-                               /// panel 2 of SNAP
-
-  std::string  last_UB_file;   /// filename of last UB file that was loaded
-                               /// or saved from MantidEV, if any.
+  std::string last_UB_file; /// filename of last UB file that was loaded
+                            /// or saved from MantidEV, if any.
 
-  std::string  last_event_file;/// filename of last event file that was loaded
+  std::string last_event_file; /// filename of last event file that was loaded
                                /// or saved from MantidEV, if any.
 
-  std::string  last_peaks_file;/// filename of last peaks file that was loaded
+  std::string last_peaks_file; /// filename of last peaks file that was loaded
                                /// or saved from MantidEV, if any.
- 
-  std::string  last_ini_file;  /// filename of last settings file that was
-                               /// loaded or saved, if any. 
 
-  Mantid::Kernel::V3D last_Q;  /// the last_Q vector that was received from
-                               /// the SelectionNotificationService
+  std::string last_ini_file; /// filename of last settings file that was
+                             /// loaded or saved, if any.
 
-  QThreadPool  *m_thread_pool; /// local thread pool with only one thread to 
-                               /// allow running precisely one operation 
-                               /// at a time in a separate thread.
+  Mantid::Kernel::V3D last_Q; /// the last_Q vector that was received from
+                              /// the SelectionNotificationService
 
+  QThreadPool *m_thread_pool; /// local thread pool with only one thread to
+                              /// allow running precisely one operation
+                              /// at a time in a separate thread.
 };
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif //MANTIDQTCUSTOMINTERFACES_MANTID_EV_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MANTID_EV_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEVWorker.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEVWorker.h
index 8bf454e5a492cc38f6ccd586e417c80a7cc4f3d5..c9a9bf7e1878b89a738ef1a69f206fa7995ac917 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEVWorker.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MantidEVWorker.h
@@ -3,21 +3,21 @@
 #include "MantidKernel/V3D.h"
 #include <vector>
 
-#ifndef  INTERFACES_MANTID_EV_WORKER_H
-#define  INTERFACES_MANTID_EV_WORKER_H
+#ifndef INTERFACES_MANTID_EV_WORKER_H
+#define INTERFACES_MANTID_EV_WORKER_H
 
 /**
-   @class MantidEVWorker 
-  
+   @class MantidEVWorker
+
       This class has methods that call Mantid algorithms to do most of the
    calculations for MantidEV.  These methods are typically called by code in
    the MantidEV_Connections class, in response to user input.
 
-    @author Dennis Mikkelson 
-    @date   2013-02-19 
-     
+    @author Dennis Mikkelson
+    @date   2013-02-19
+
     Copyright © 2013 ORNL, STFC Rutherford Appleton Laboratories
-  
+
     This file is part of Mantid.
 
     Mantid is free software; you can redistribute it and/or modify
@@ -32,188 +32,152 @@
 
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
-    
-    Code Documentation is available at 
+
+    Code Documentation is available at
                  <http://doxygen.mantidproject.org>
 */
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class DLLExport MantidEVWorker
-{
+class DLLExport MantidEVWorker {
 
 public:
-
   /// Default constructor
   MantidEVWorker();
 
-
   /// Default destructor
- ~MantidEVWorker();
+  ~MantidEVWorker();
 
-  
   /// check for existence of MD workspace in analysis data service
-  bool isMDWorkspace( const std::string & md_ws_name );
+  bool isMDWorkspace(const std::string &md_ws_name);
 
   /// check for existence of peaks workspace in analysis data service
-  bool isPeaksWorkspace( const std::string & peaks_ws_name );
+  bool isPeaksWorkspace(const std::string &peaks_ws_name);
 
   /// check for existence of event workspace in analysis data service
-  bool isEventWorkspace( const std::string & event_ws_name );
+  bool isEventWorkspace(const std::string &event_ws_name);
 
   /// Load and event file and convert to MD workspace
-  bool loadAndConvertToMD(const std::string & file_name,
-                          const std::string & ev_ws_name,
-                          const std::string & md_ws_name,
-                          const double        modQ,
-                          const double        minQ,
-                          const double        maxQ,
-                          const bool          do_lorentz_corr,
-                          const bool          load_data,
-                          const bool          load_det_cal,
-                          const std::string & det_cal_file,
-                          const std::string & det_cal_file2 );
+  bool loadAndConvertToMD(const std::string &file_name,
+                          const std::string &ev_ws_name,
+                          const std::string &md_ws_name, const double modQ,
+                          const double minQ, const double maxQ,
+                          const bool do_lorentz_corr, const bool load_data,
+                          const bool load_det_cal,
+                          const std::string &det_cal_file,
+                          const std::string &det_cal_file2);
 
   /// Find peaks in MD workspace and set peaks into peaks workspace
-  bool findPeaks( const std::string & ev_ws_name,
-		          const std::string & md_ws_name,
-                  const std::string & peaks_ws_name,
-                        double        max_abc,
-                        size_t        num_to_find,
-                        double        min_intensity,
-                        double minQPeaks,
-                        double maxQPeaks );
+  bool findPeaks(const std::string &ev_ws_name, const std::string &md_ws_name,
+                 const std::string &peaks_ws_name, double max_abc,
+                 size_t num_to_find, double min_intensity, double minQPeaks,
+                 double maxQPeaks);
 
   /// Predict peaks and overwrite the peaks workspace
-  bool predictPeaks( const std::string & peaks_ws_name,
-                                           double        min_pred_wl,
-                                           double        max_pred_wl,
-                                           double        min_pred_dspacing,
-                                           double        max_pred_dspacing );
+  bool predictPeaks(const std::string &peaks_ws_name, double min_pred_wl,
+                    double max_pred_wl, double min_pred_dspacing,
+                    double max_pred_dspacing);
 
   /// Load the peaks workspace from a .peaks or .integrate file
-  bool loadIsawPeaks( const std::string & peaks_ws_name,
-                      const std::string & file_name );
+  bool loadIsawPeaks(const std::string &peaks_ws_name,
+                     const std::string &file_name);
 
-  bool loadNexusPeaks( const std::string & peaks_ws_name,
-                                      const std::string & file_name );
+  bool loadNexusPeaks(const std::string &peaks_ws_name,
+                      const std::string &file_name);
 
   /// Save the peaks workspace to a .peaks or .integrate file
-  bool saveIsawPeaks( const std::string & peaks_ws_name,
-                      const std::string & file_name,
-                            bool          append );
+  bool saveIsawPeaks(const std::string &peaks_ws_name,
+                     const std::string &file_name, bool append);
 
   /// Save the peaks workspace to a .nxs file
-  bool saveNexusPeaks( const std::string & peaks_ws_name,
-                      const std::string & file_name,
-                            bool          append );
+  bool saveNexusPeaks(const std::string &peaks_ws_name,
+                      const std::string &file_name, bool append);
 
   /// Index the peaks using the FFT method
-  bool findUBUsingFFT( const std::string & peaks_ws_name,
-                       double              min_abc,
-                       double              max_abc,
-                       double              tolerance );
+  bool findUBUsingFFT(const std::string &peaks_ws_name, double min_abc,
+                      double max_abc, double tolerance);
 
   /// Index the peaks using the indexing of the peaks in the peaks workspace
-  bool findUBUsingIndexedPeaks(const std::string & peaks_ws_name, double tolerance );
+  bool findUBUsingIndexedPeaks(const std::string &peaks_ws_name,
+                               double tolerance);
 
   /// Load the UB matrix from a file
-  bool loadIsawUB( const std::string & peaks_ws_name,
-                   const std::string & file_name );
+  bool loadIsawUB(const std::string &peaks_ws_name,
+                  const std::string &file_name);
 
   /// Save the UB matrix to a file
-  bool saveIsawUB( const std::string & peaks_ws_name,
-                   const std::string & file_name );
+  bool saveIsawUB(const std::string &peaks_ws_name,
+                  const std::string &file_name);
 
   /// Optimize the phi, chi, omega angles in the peaks wkspace, using stored UB
-  bool optimizePhiChiOmega( const std::string & peaks_ws_name, 
-                                  double        max_change );
+  bool optimizePhiChiOmega(const std::string &peaks_ws_name, double max_change);
 
   /// Actually index the peaks, using the stored UB
-  bool indexPeaksWithUB( const std::string & peaks_ws_name,
-                               double        tolerance,
-                               bool          round_hkls );
+  bool indexPeaksWithUB(const std::string &peaks_ws_name, double tolerance,
+                        bool round_hkls);
 
   /// Show the possible conventional cells for a Niggli cell
-  bool showCells( const std::string & peaks_ws_name,
-                        double        max_scalar_error,
-                        bool          best_only,
-                        bool          allow_perm);
+  bool showCells(const std::string &peaks_ws_name, double max_scalar_error,
+                 bool best_only, bool allow_perm);
 
   /// Select conventional cell using the cell type and centering
-  bool selectCellOfType( const std::string & peaks_ws_name,
-                         const std::string & cell_type,
-                         const std::string & centering,
-                         bool          allow_perm);
+  bool selectCellOfType(const std::string &peaks_ws_name,
+                        const std::string &cell_type,
+                        const std::string &centering, bool allow_perm);
 
   /// Select conventional cell using the form number from the Mighell paper
-  bool selectCellWithForm( const std::string & peaks_ws_name,
-                                 size_t        form_num,
-                                 bool          allow_perm);
-
-  /// Apply a mapping to the h,k,l indices and the UB matrix 
-  bool changeHKL( const std::string & peaks_ws_name,
-                  const std::string & row_1_str,
-                  const std::string & row_2_str,
-                  const std::string & row_3_str );
-
-  /// Integrate an MD event workspace using spherical integration 
-  bool sphereIntegrate( const std::string & peaks_ws_name,
-                        const std::string & event_ws_name,
-                              double        peak_radius,
-                              double        inner_radius,
-                              double        outer_radius,
-                              bool          integrate_edge,
-                              bool          use_cylinder_integration,
-                              double        cylinder_length,
-                              double        cylinder_percent_bkg,
-                        const std::string & cylinder_profile_fit);
-
-  /// Integrate an event workspace using 2-D peak fitting integration 
-  bool fitIntegrate( const std::string & peaks_ws_name,
-                     const std::string & event_ws_name,
-                     const std::string & rebin_param_str,
-                           size_t        n_bad_edge_pix,
-                           bool          use_ikeda_carpenter );
-
-  /// Integrate an event workspace using 3D ellipsoids 
-  bool ellipsoidIntegrate( const std::string & peaks_ws_name,
-                           const std::string & event_ws_name,
-                                 double        region_radius,
-                                 bool          specify_size,
-                                 double        peak_size,
-                                 double        inner_size,
-                                 double        outer_size );
+  bool selectCellWithForm(const std::string &peaks_ws_name, size_t form_num,
+                          bool allow_perm);
+
+  /// Apply a mapping to the h,k,l indices and the UB matrix
+  bool changeHKL(const std::string &peaks_ws_name, const std::string &row_1_str,
+                 const std::string &row_2_str, const std::string &row_3_str);
+
+  /// Integrate an MD event workspace using spherical integration
+  bool sphereIntegrate(const std::string &peaks_ws_name,
+                       const std::string &event_ws_name, double peak_radius,
+                       double inner_radius, double outer_radius,
+                       bool integrate_edge, bool use_cylinder_integration,
+                       double cylinder_length, double cylinder_percent_bkg,
+                       const std::string &cylinder_profile_fit);
+
+  /// Integrate an event workspace using 2-D peak fitting integration
+  bool fitIntegrate(const std::string &peaks_ws_name,
+                    const std::string &event_ws_name,
+                    const std::string &rebin_param_str, size_t n_bad_edge_pix,
+                    bool use_ikeda_carpenter);
+
+  /// Integrate an event workspace using 3D ellipsoids
+  bool ellipsoidIntegrate(const std::string &peaks_ws_name,
+                          const std::string &event_ws_name,
+                          double region_radius, bool specify_size,
+                          double peak_size, double inner_size,
+                          double outer_size);
 
   /// Display UB and lattice parameters in MantidPlot
-  bool showUB( const std::string & peaks_ws_name );
+  bool showUB(const std::string &peaks_ws_name);
 
   /// Get the current UB matrix from the peaks workspace in sample or lab coords
-  bool getUB( const std::string & peaks_ws_name,
-                    bool          lab_coords,
-                    Mantid::Kernel::Matrix<double> & UB );
+  bool getUB(const std::string &peaks_ws_name, bool lab_coords,
+             Mantid::Kernel::Matrix<double> &UB);
 
   /// Copy the oriented lattice from the peaks workspace to the ND workspace
-  bool copyLattice(const std::string & peaks_ws_name,
-                    const std::string & md_ws_name , const std::string &event_ws_name);
+  bool copyLattice(const std::string &peaks_ws_name,
+                   const std::string &md_ws_name,
+                   const std::string &event_ws_name);
 
   /// Get Info about a Q-Vector from a PeaksWorkspace
-  std::vector< std::pair< std::string, std::string > >
-                               PointInfo( const std::string & peaks_ws_name, 
-                                                bool          lab_coords,
-                                          Mantid::Kernel::V3D Q);
-
+  std::vector<std::pair<std::string, std::string>>
+  PointInfo(const std::string &peaks_ws_name, bool lab_coords,
+            Mantid::Kernel::V3D Q);
 
 private:
-
   /// Utility to get workspace ID from ADS, blank if none
-  std::string workspaceType( const std::string & ws_name );  
+  std::string workspaceType(const std::string &ws_name);
 };
 
-}  // namespace CustomInterfaces 
-}  // namespace MantidQt
+} // namespace CustomInterfaces
+} // namespace MantidQt
 
-#endif  // INTERFACES_MANTID_EV_WORKER_H
+#endif // INTERFACES_MANTID_EV_WORKER_H
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h
index 29be79bef2eb0dc84ad1a29d84ad91260e212767..8340ac6b60d77ce7b361eaf450ddd08e4c31e908 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFAddWorkspaceDialog.h
@@ -4,28 +4,25 @@
 #include <QDialog>
 #include "ui_MDFAddWorkspaceDialog.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /**
   * A dialog for selecting a workspace from the ADS.
   */
-class AddWorkspaceDialog: public QDialog
-{
+class AddWorkspaceDialog : public QDialog {
   Q_OBJECT
 public:
   AddWorkspaceDialog(QWidget *parent);
-  QString workspaceName() const {return m_workspaceName;} 
-  std::vector<int> workspaceIndices() const {return m_wsIndices;}
+  QString workspaceName() const { return m_workspaceName; }
+  std::vector<int> workspaceIndices() const { return m_wsIndices; }
 private slots:
   void accept() override;
   void reject() override;
-  void workspaceNameChanged(const QString&);
+  void workspaceNameChanged(const QString &);
   void selectAllSpectra(int state);
+
 private:
   /// Name of the selected workspace
   QString m_workspaceName;
@@ -40,5 +37,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFADDWORKSPACEDIALOG_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h
index 4c50ea54532f0074ff1a6ef12c307e3740ee39fe..56fe2c5c3e68d8ad63de91e317b5a917fabc7c1e 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDataController.h
@@ -7,25 +7,20 @@
 class QTableWidget;
 
 // Forward declaration
-namespace Mantid
-{
-namespace API
-{
+namespace Mantid {
+namespace API {
 class MatrixWorkspace;
 }
 }
 
-namespace MantidQt
-{
+namespace MantidQt {
 
-namespace CustomInterfaces
-{
+namespace CustomInterfaces {
 
 // Forward declaration
 class MultiDatasetFit;
 
-namespace MDF
-{
+namespace MDF {
 
 /**
   * A class for controlling a table widget containing a list of
@@ -40,8 +35,7 @@ namespace MDF
   * This controller has a pointer to the table widget and controls
   * its behaviour but not its position on the parent widget.
   */
-class DataController: public QObject
-{
+class DataController : public QObject {
   Q_OBJECT
 public:
   DataController(MultiDatasetFit *parent, QTableWidget *dataTable);
@@ -49,7 +43,7 @@ public:
   int getWorkspaceIndex(int i) const;
   int getNumberOfSpectra() const;
   void checkSpectra();
-  std::pair<double,double> getFittingRange(int i) const;
+  std::pair<double, double> getFittingRange(int i) const;
 
 signals:
   void dataTableUpdated();
@@ -70,7 +64,8 @@ private slots:
 
 private:
   MultiDatasetFit *owner() const;
-  void addWorkspaceSpectrum(const QString &wsName, int wsIndex, const Mantid::API::MatrixWorkspace& ws);
+  void addWorkspaceSpectrum(const QString &wsName, int wsIndex,
+                            const Mantid::API::MatrixWorkspace &ws);
   void removeSpectra(QList<int> rows);
 
   /// Table with data set names and other data.
@@ -83,5 +78,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFDATACONTROLLER_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDatasetPlotData.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDatasetPlotData.h
index 66b3e4bc728dc52ba65221cea52bb00bb7d7511e..2092f9679a27007e14651319e233d49cf21bacc8 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDatasetPlotData.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFDatasetPlotData.h
@@ -9,46 +9,42 @@
 class QwtPlot;
 class QwtPlotCurve;
 
-namespace Mantid
-{
-namespace API
-{
-  class MatrixWorkspace;
+namespace Mantid {
+namespace API {
+class MatrixWorkspace;
 }
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class ErrorCurve;
+namespace MantidQt {
+namespace MantidWidgets {
+class ErrorCurve;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /**
- * Contains graphics for a single data set: fitting data, claculated result, difference.
+ * Contains graphics for a single data set: fitting data, claculated result,
+ * difference.
  */
-class DatasetPlotData
-{
+class DatasetPlotData {
 public:
-  DatasetPlotData(const QString& wsName, int wsIndex, const QString& outputWSName);
+  DatasetPlotData(const QString &wsName, int wsIndex,
+                  const QString &outputWSName);
   ~DatasetPlotData();
   void show(QwtPlot *plot);
   void hide();
   QwtDoubleRect boundingRect() const;
   void showDataErrorBars(bool on);
+
 private:
   // no copying
-  DatasetPlotData(const DatasetPlotData&);
-  DatasetPlotData& operator=(const DatasetPlotData&);
-  void setData(const Mantid::API::MatrixWorkspace *ws, int wsIndex, const Mantid::API::MatrixWorkspace *outputWS);
+  DatasetPlotData(const DatasetPlotData &);
+  DatasetPlotData &operator=(const DatasetPlotData &);
+  void setData(const Mantid::API::MatrixWorkspace *ws, int wsIndex,
+               const Mantid::API::MatrixWorkspace *outputWS);
   /// Curve object for the fit data (spectrum).
   QwtPlotCurve *m_dataCurve;
   /// Error bar curve for the data
@@ -65,5 +61,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFDATASETPLOTDATA_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h
index 27623f7ab30565b680da6179f921cf876dcf5b9f..70b20946a839ebb1dfcd549da4008482f3bc2c4b 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFEditLocalParameterDialog.h
@@ -4,44 +4,41 @@
 #include "ui_EditLocalParameterDialog.h"
 #include <QDialog>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 class MultiDatasetFit;
 
-namespace MDF
-{
+namespace MDF {
 
 /**
   * A dialog for displaying and editing values of local parameters.
   * Parameters can be set individually or all to the same value.
   * They also can be fixed and unfixed.
   */
-class EditLocalParameterDialog: public QDialog
-{
+class EditLocalParameterDialog : public QDialog {
   Q_OBJECT
 public:
   EditLocalParameterDialog(MultiDatasetFit *parent, const QString &parName);
   QList<double> getValues() const;
   QList<bool> getFixes() const;
   QStringList getTies() const;
-  double getValue(int i) const {return m_values[i];}
-  bool isFixed(int i) const {return m_fixes[i];}
-  QString getTie(int i) const {return m_ties[i];}
+  double getValue(int i) const { return m_values[i]; }
+  bool isFixed(int i) const { return m_fixes[i]; }
+  QString getTie(int i) const { return m_ties[i]; }
   bool areOthersFixed(int i) const;
   bool areAllOthersFixed(int i) const;
   bool areOthersTied(int i) const;
-  private slots:
-  void valueChanged(int,int);
+private slots:
+  void valueChanged(int, int);
   void setAllValues(double);
-  void fixParameter(int,bool);
+  void fixParameter(int, bool);
   void setAllFixed(bool);
-  void setTie(int,QString);
+  void setTie(int, QString);
   void setTieAll(QString);
   void copy();
   void paste();
+
 private:
   bool eventFilter(QObject *obj, QEvent *ev) override;
   void showContextMenu();
@@ -59,10 +56,8 @@ private:
   QStringList m_ties;
 };
 
-
 } // MDF
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFEDITLOCALPARAMETERDIALOG_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFFunctionPlotData.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFFunctionPlotData.h
index b82d9ee04902db6e6b57a8b077b5ae27e7b3e43d..e4c39b7c4855b04220ba571b76822ac0a2ff003f 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFFunctionPlotData.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFFunctionPlotData.h
@@ -10,26 +10,20 @@
 class QwtPlot;
 class QwtPlotCurve;
 
-namespace Mantid
-{
-namespace API
-{
-  class IFunction;
+namespace Mantid {
+namespace API {
+class IFunction;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /**
  * Contains the curve and helps to set the data to plot a function.
  */
-class MDFFunctionPlotData
-{
+class MDFFunctionPlotData {
 public:
   MDFFunctionPlotData(boost::shared_ptr<Mantid::API::IFunction> fun,
                       double startX, double endX,
@@ -41,11 +35,12 @@ public:
   /// Set curve data
   void setDomain(double startX, double endX, size_t nX = g_defaultDomainSize);
   /// Update function parameters and attributes
-  void updateFunction(const Mantid::API::IFunction& fun);
+  void updateFunction(const Mantid::API::IFunction &fun);
+
 private:
   // No copying
-  MDFFunctionPlotData(const MDFFunctionPlotData&);
-  MDFFunctionPlotData& operator=(const MDFFunctionPlotData&);
+  MDFFunctionPlotData(const MDFFunctionPlotData &);
+  MDFFunctionPlotData &operator=(const MDFFunctionPlotData &);
 
   /// The function
   boost::shared_ptr<Mantid::API::IFunction> m_function;
@@ -60,5 +55,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFFUNCTIONPLOTDATA_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h
index fd129e495ae82e569ea89e3a99dbe945079d07ad..12ceabc18215289a7a2f453bb520d613277b057a 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterEditor.h
@@ -7,19 +7,15 @@ class QLineEdit;
 class QAction;
 class QPushButton;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /**
  * An editor widget for editing a local parameter value.
  * It allows edit the values as well as fix/unfix the parameter.
  */
-class LocalParameterEditor: public QWidget
-{
+class LocalParameterEditor : public QWidget {
   Q_OBJECT
 public:
   LocalParameterEditor(QWidget *parent, int index, double value, bool fixed,
@@ -27,9 +23,9 @@ public:
                        bool othersTied);
 signals:
   void setAllValues(double);
-  void fixParameter(int,bool);
+  void fixParameter(int, bool);
   void setAllFixed(bool);
-  void setTie(int,QString);
+  void setTie(int, QString);
   void setTieAll(QString);
 private slots:
   void setAll();
@@ -46,8 +42,8 @@ private:
   bool eventFilter(QObject *widget, QEvent *evn) override;
   void setEditorState();
   static QString setTieDialog(QString tie);
-  QLineEdit* m_editor;
-  QPushButton* m_button;
+  QLineEdit *m_editor;
+  QPushButton *m_button;
   QAction *m_setAllAction;
   QAction *m_fixAction;
   QAction *m_fixAllAction;
@@ -66,10 +62,8 @@ private:
   bool m_othersTied;
 };
 
-
 } // MDF
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFDATASETPLOTDATA_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h
index d7541615e940c2afc2dabc5abb61c2558ad16f8c..04f7d23ac689eb7113541a63ff037f23b96f3681 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFLocalParameterItemDelegate.h
@@ -3,12 +3,9 @@
 
 #include <QStyledItemDelegate>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 // Forward declarations.
 class EditLocalParameterDialog;
@@ -22,8 +19,7 @@ class LocalParameterEditor;
  *  - paint(...) method shows which parameters are fixed.
  *  - createEditor(...) method creates a custom editor for parameter values.
  */
-class LocalParameterItemDelegate: public QStyledItemDelegate
-{
+class LocalParameterItemDelegate : public QStyledItemDelegate {
   Q_OBJECT
 public:
   LocalParameterItemDelegate(EditLocalParameterDialog *parent = NULL);
@@ -34,10 +30,11 @@ public:
                     const QModelIndex &index) const override;
 signals:
   void setAllValues(double);
-  void fixParameter(int,bool);
+  void fixParameter(int, bool);
   void setAllFixed(bool);
-  void setTie(int,QString);
+  void setTie(int, QString);
   void setTieAll(QString);
+
 protected:
   void paint(QPainter *painter, const QStyleOptionViewItem &option,
              const QModelIndex &index) const override;
@@ -45,13 +42,11 @@ protected:
 private:
   bool eventFilter(QObject *obj, QEvent *ev) override;
   EditLocalParameterDialog *owner() const;
-  mutable LocalParameterEditor* m_currentEditor;
+  mutable LocalParameterEditor *m_currentEditor;
 };
 
-
 } // MDF
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFLOCALPARAMETERITEMDELEGATE_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h
index e7e16c66b8d1cc727eb8d63e6612cb9de3d2dea8..18792d831d16b8ef3c2728a91713b7b49e1792c6 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MDFPlotController.h
@@ -16,28 +16,22 @@ class QComboBox;
 class QPushButton;
 class QwtPlotCurve;
 
-namespace Mantid
-{
-namespace API
-{
-  class IFunction;
+namespace Mantid {
+namespace API {
+class IFunction;
 }
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 class RangeSelector;
 }
 
-namespace CustomInterfaces
-{
+namespace CustomInterfaces {
 
 class MultiDatasetFit;
 
-namespace MDF
-{
+namespace MDF {
 
 class DatasetPlotData;
 class MDFFunctionPlotData;
@@ -50,20 +44,20 @@ class MDFFunctionPlotData;
   *
   * Manages the plot tools.
   */
-class PlotController: public QObject
-{
+class PlotController : public QObject {
   Q_OBJECT
 public:
-  PlotController(MultiDatasetFit *parent, QwtPlot *plot, QTableWidget *table, QComboBox *plotSelector, QPushButton *prev, QPushButton *next);
+  PlotController(MultiDatasetFit *parent, QwtPlot *plot, QTableWidget *table,
+                 QComboBox *plotSelector, QPushButton *prev, QPushButton *next);
   ~PlotController() override;
   void clear(bool clearGuess = false);
   void update();
-  int getCurrentIndex() const {return m_currentIndex;}
+  int getCurrentIndex() const { return m_currentIndex; }
   bool isZoomEnabled() const;
   bool isPanEnabled() const;
   bool isRangeSelectorEnabled() const;
-  void setGuessFunction(const QString& funStr);
-  void updateGuessFunction(const Mantid::API::IFunction& fun);
+  void setGuessFunction(const QString &funStr);
+  void updateGuessFunction(const Mantid::API::IFunction &fun);
 signals:
   void currentIndexChanged(int);
   void fittingRangeChanged(int, double, double);
@@ -85,11 +79,11 @@ private slots:
   void plotDataSet(int);
   void updateFittingRange(double startX, double endX);
   void updateGuessPlot();
+
 private:
   MultiDatasetFit *owner() const;
   void disableAllTools();
-  template<class Tool>
-  void enableTool(Tool* tool, int cursor);
+  template <class Tool> void enableTool(Tool *tool, int cursor);
   boost::shared_ptr<DatasetPlotData> getData(int i);
   void exportPlot(int index);
   QString makePyPlotSource(int index) const;
@@ -108,7 +102,7 @@ private:
   /// The magnifier
   QwtPlotMagnifier *m_magnifier;
   /// The fitting range selector
-  MantidWidgets::RangeSelector* m_rangeSelector;
+  MantidWidgets::RangeSelector *m_rangeSelector;
   ///@}
 
   /// The workspace table
@@ -116,7 +110,7 @@ private:
   QComboBox *m_plotSelector;
   QPushButton *m_prevPlot;
   QPushButton *m_nextPlot;
-  QMap<int,boost::shared_ptr<DatasetPlotData>> m_plotData;
+  QMap<int, boost::shared_ptr<DatasetPlotData>> m_plotData;
   int m_currentIndex;
   bool m_showDataErrors;
 
@@ -129,5 +123,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MDFPLOTCONTROLLER_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.h
index 91fa74b4658df1bba630ec70f74950ca528c3053..f3403a15aad79ef80e9e33a32adde9a6f686bed0 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/MultiDatasetFit/MultiDatasetFit.h
@@ -5,46 +5,40 @@
 #include "MantidQtAPI/UserSubWindow.h"
 #include "ui_MultiDatasetFit.h"
 
-namespace Mantid
-{
-namespace API
-{
-  class IFunction;
-  class IAlgorithm;
-  class MatrixWorkspace;
+namespace Mantid {
+namespace API {
+class IFunction;
+class IAlgorithm;
+class MatrixWorkspace;
 }
 }
 
-namespace MantidQt
-{
+namespace MantidQt {
 
 // Forward declarations
-namespace MantidWidgets
-{
-  class FunctionBrowser;
-  class FitOptionsBrowser;
+namespace MantidWidgets {
+class FunctionBrowser;
+class FitOptionsBrowser;
 }
-namespace API
-{
-  class AlgorithmRunner;
+namespace API {
+class AlgorithmRunner;
 }
 
-namespace CustomInterfaces
-{
+namespace CustomInterfaces {
 
 // Forward declarations
-namespace MDF
-{
-  class DataController;
-  class PlotController;
+namespace MDF {
+class DataController;
+class PlotController;
 }
 
 /**
- * Class MultiDatasetFitDialog implements a dialog for setting up a multi-dataset fit
+ * Class MultiDatasetFitDialog implements a dialog for setting up a
+ * multi-dataset fit
  * and displaying the results.
  */
-class MANTIDQT_CUSTOMINTERFACES_DLL MultiDatasetFit: public API::UserSubWindow
-{
+class MANTIDQT_CUSTOMINTERFACES_DLL MultiDatasetFit
+    : public API::UserSubWindow {
   Q_OBJECT
 public:
   /// The name of the interface as registered into the factory
@@ -62,7 +56,7 @@ public:
   /// Workspace index of the i-th spectrum
   int getWorkspaceIndex(int i) const;
   /// Get the fitting range for the i-th spectrum
-  std::pair<double,double> getFittingRange(int i) const;
+  std::pair<double, double> getFittingRange(int i) const;
   /// Total number of spectra (datasets).
   int getNumberOfSpectra() const;
   /// Display info about the plot.
@@ -70,17 +64,17 @@ public:
   /// Check that the data sets in the table are valid
   void checkSpectra();
   /// Get value of a local parameter
-  double getLocalParameterValue(const QString& parName, int i) const;
+  double getLocalParameterValue(const QString &parName, int i) const;
   /// Set value of a local parameter
-  void setLocalParameterValue(const QString& parName, int i, double value);
+  void setLocalParameterValue(const QString &parName, int i, double value);
   /// Check if a local parameter is fixed
-  bool isLocalParameterFixed(const QString& parName, int i) const;
+  bool isLocalParameterFixed(const QString &parName, int i) const;
   /// Fix/unfix local parameter
-  void setLocalParameterFixed(const QString& parName, int i, bool fixed);
+  void setLocalParameterFixed(const QString &parName, int i, bool fixed);
   /// Get the tie for a local parameter.
-  QString getLocalParameterTie(const QString& parName, int i) const;
+  QString getLocalParameterTie(const QString &parName, int i) const;
   /// Set a tie for a local parameter.
-  void setLocalParameterTie(const QString& parName, int i, QString tie);
+  void setLocalParameterTie(const QString &parName, int i, QString tie);
 
   /// Make it public
   using API::UserSubWindow::runPythonCode;
@@ -90,7 +84,7 @@ public slots:
 
 private slots:
   void fit();
-  void editLocalParameterValues(const QString& parName);
+  void editLocalParameterValues(const QString &parName);
   void finishFit(bool);
   void enableZoom();
   void enablePan();
@@ -101,7 +95,7 @@ private slots:
   void setLogNames();
   void setParameterNamesForPlotting();
   void invalidateOutput();
-  void updateGuessFunction(const QString&, const QString&);
+  void updateGuessFunction(const QString &, const QString &);
 
 protected:
   void initLayout() override;
@@ -109,8 +103,8 @@ protected:
 private:
   void createPlotToolbar();
   boost::shared_ptr<Mantid::API::IFunction> createFunction() const;
-  void updateParameters(const Mantid::API::IFunction& fun);
-  void showInfo(const QString& text);
+  void updateParameters(const Mantid::API::IFunction &fun);
+  void showInfo(const QString &text);
   bool eventFilter(QObject *widget, QEvent *evn) override;
   void showFunctionBrowserInfo();
   void showFitOptionsBrowserInfo();
@@ -144,5 +138,4 @@ private:
 } // CustomInterfaces
 } // MantidQt
 
-
 #endif /*MULTIDATASETFITDIALOG_H_*/
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
index 32e7595260517148f091f61f540d5b7a59c5be9b..41bd6fc99f6dbe512d169a5228a625deda3fccef 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingModel.h
@@ -9,98 +9,100 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** ALCBaselineModellingModel : Concrete ALC Baseline Modelling step model implementation.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+namespace MantidQt {
+namespace CustomInterfaces {
+/** ALCBaselineModellingModel : Concrete ALC Baseline Modelling step model
+  implementation.
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingModel : public IALCBaselineModellingModel
-  {
-  public:
-    // -- IALCBaselineModellingModel interface -----------------------------------------------------
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    MatrixWorkspace_const_sptr data() const override;
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingModel
+    : public IALCBaselineModellingModel {
+public:
+  // -- IALCBaselineModellingModel interface
+  // -----------------------------------------------------
 
-    void fit(IFunction_const_sptr function,
-             const std::vector<Section> &sections) override;
+  MatrixWorkspace_const_sptr data() const override;
 
-    IFunction_const_sptr fittedFunction() const override {
-      return m_fittedFunction;
-    }
+  void fit(IFunction_const_sptr function,
+           const std::vector<Section> &sections) override;
 
-    MatrixWorkspace_const_sptr correctedData() const override;
+  IFunction_const_sptr fittedFunction() const override {
+    return m_fittedFunction;
+  }
 
-    ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
+  MatrixWorkspace_const_sptr correctedData() const override;
 
-    const std::vector<Section>& sections() const { return m_sections; }
+  ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
 
-    // -- End of IALCBaselineModellingModel interface ----------------------------------------------
+  const std::vector<Section> &sections() const { return m_sections; }
 
-    /// Set the data we should fit baseline for
-    void setData(MatrixWorkspace_const_sptr data);
+  // -- End of IALCBaselineModellingModel interface
+  // ----------------------------------------------
 
-    /// Set the corrected data resulting from fit
-    void setCorrectedData(MatrixWorkspace_const_sptr data);
+  /// Set the data we should fit baseline for
+  void setData(MatrixWorkspace_const_sptr data);
 
-    /// Export data + baseline + corrected data as a single workspace
-    MatrixWorkspace_sptr exportWorkspace();
+  /// Set the corrected data resulting from fit
+  void setCorrectedData(MatrixWorkspace_const_sptr data);
 
-    /// Export sections used for the last fit as a table workspace
-    ITableWorkspace_sptr exportSections();
+  /// Export data + baseline + corrected data as a single workspace
+  MatrixWorkspace_sptr exportWorkspace();
 
-    /// Exports baseline model as a table workspace
-    ITableWorkspace_sptr exportModel();
+  /// Export sections used for the last fit as a table workspace
+  ITableWorkspace_sptr exportSections();
 
+  /// Exports baseline model as a table workspace
+  ITableWorkspace_sptr exportModel();
 
-  private:
-    /// Data used for fitting
-    MatrixWorkspace_const_sptr m_data;
+private:
+  /// Data used for fitting
+  MatrixWorkspace_const_sptr m_data;
 
-    /// Result function of the last fit
-    IFunction_const_sptr m_fittedFunction;
+  /// Result function of the last fit
+  IFunction_const_sptr m_fittedFunction;
 
-    /// Fit table containing parameters and errors
-    ITableWorkspace_sptr m_parameterTable;
+  /// Fit table containing parameters and errors
+  ITableWorkspace_sptr m_parameterTable;
 
-    /// Sections used for the last fit
-    std::vector<Section> m_sections;
+  /// Sections used for the last fit
+  std::vector<Section> m_sections;
 
-    // Setters for convenience
-    void setFittedFunction(IFunction_const_sptr function);
+  // Setters for convenience
+  void setFittedFunction(IFunction_const_sptr function);
 
-    // Set errors in the ws after the fit
-    void setErrorsAfterFit(MatrixWorkspace_sptr data);
+  // Set errors in the ws after the fit
+  void setErrorsAfterFit(MatrixWorkspace_sptr data);
 
-    /// Disables points which shouldn't be used for fitting
-    static void disableUnwantedPoints(MatrixWorkspace_sptr ws, const std::vector<Section>& sections);
+  /// Disables points which shouldn't be used for fitting
+  static void disableUnwantedPoints(MatrixWorkspace_sptr ws,
+                                    const std::vector<Section> &sections);
 
-    /// Enable previously disabled points
-    static void enableDisabledPoints(MatrixWorkspace_sptr destWs, MatrixWorkspace_const_sptr sourceWs);
-
-  };
+  /// Enable previously disabled points
+  static void enableDisabledPoints(MatrixWorkspace_sptr destWs,
+                                   MatrixWorkspace_const_sptr sourceWs);
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTID_CUSTOMINTERFACES_ALCBASELINEMODELLINGMODEL_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_ALCBASELINEMODELLINGMODEL_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
index 9b4b13970b18b0d29beb784b8d0d993f64b47008..da2c9afc50978eded33d148c981e7d8f7acf86e1 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingPresenter.h
@@ -9,79 +9,79 @@
 
 #include <QObject>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** ALCBaselineModellingPresenter : Presenter for ALC Baseline Modelling step
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** ALCBaselineModellingPresenter : Presenter for ALC Baseline Modelling step
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingPresenter : public QObject
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    ALCBaselineModellingPresenter(IALCBaselineModellingView* view, IALCBaselineModellingModel* model);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingPresenter
+    : public QObject {
+  Q_OBJECT
 
-    void initialize();
+public:
+  ALCBaselineModellingPresenter(IALCBaselineModellingView *view,
+                                IALCBaselineModellingModel *model);
 
-  private slots:
-    /// Perform a fit
-    void fit();
+  void initialize();
 
-    /// Add a new section
-    void addSection();
+private slots:
+  /// Perform a fit
+  void fit();
 
-    /// Remove existing section
-    void removeSection(int row);
+  /// Add a new section
+  void addSection();
 
-    /// Called when one of sections is modified
-    void onSectionRowModified(int row);
+  /// Remove existing section
+  void removeSection(int row);
 
-    /// Called when on of section selectors is modified
-    void onSectionSelectorModified(int index);
+  /// Called when one of sections is modified
+  void onSectionRowModified(int row);
 
-    /// Updates data curve from the model
-    void updateDataCurve();
+  /// Called when on of section selectors is modified
+  void onSectionSelectorModified(int index);
 
-    /// Updates corrected data curve from the model
-    void updateCorrectedCurve();
+  /// Updates data curve from the model
+  void updateDataCurve();
 
-    /// Updated baseline curve from the model
-    void updateBaselineCurve();
+  /// Updates corrected data curve from the model
+  void updateCorrectedCurve();
 
-    /// Updates function in the view from the model
-    void updateFunction();
+  /// Updated baseline curve from the model
+  void updateBaselineCurve();
 
-  private:
-    /// Associated view
-    IALCBaselineModellingView* const m_view;
+  /// Updates function in the view from the model
+  void updateFunction();
 
-    /// Associated model
-    IALCBaselineModellingModel* const m_model;
-  };
+private:
+  /// Associated view
+  IALCBaselineModellingView *const m_view;
+
+  /// Associated model
+  IALCBaselineModellingModel *const m_model;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCBASELINEMODELLINGPRESENTER_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCBASELINEMODELLINGPRESENTER_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.h
index 8bfcaefb2ddf0bf54e34525dbd5531338147b0e4..848ed7d404b4780465fa9f4f8b31218f9ef4c4d6 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCBaselineModellingView.h
@@ -11,109 +11,104 @@
 
 #include <qwt_plot_curve.h>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class ErrorCurve;
+namespace MantidQt {
+namespace MantidWidgets {
+class ErrorCurve;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  using namespace MantidWidgets;
-
-  /** ALCBaselineModellingView : Widget-based implementation of the ALC Baseline Modelling step
-                                 interface.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingView : public IALCBaselineModellingView
-  {
-    Q_OBJECT
-
-  public:
-    ALCBaselineModellingView(QWidget* widget);
-    ~ALCBaselineModellingView() override;
-
-    // -- IALCBaselineModellingView interface
-    // --------------------------------------------------------
-  public:
-    QString function() const override;
-    SectionRow sectionRow(int row) const override;
-    SectionSelector sectionSelector(int index) const override;
-    int noOfSectionRows() const override;
-    void emitFitRequested();
-
-  public slots:
-    void initialize() override;
-    void setDataCurve(const QwtData &data,
-                      const std::vector<double> &errors) override;
-    void setCorrectedCurve(const QwtData &data,
-                           const std::vector<double> &errors) override;
-    void setBaselineCurve(const QwtData &data) override;
-    void setFunction(Mantid::API::IFunction_const_sptr func) override;
-    void setNoOfSectionRows(int rows) override;
-    void setSectionRow(int row, SectionRow values) override;
-    void addSectionSelector(int index, SectionSelector values) override;
-    void deleteSectionSelector(int index) override;
-    void updateSectionSelector(int index, SectionSelector values) override;
-    void displayError(const QString &message) override;
-    void help() override;
-    // -- End of IALCBaselineModellingView interface
-    // -------------------------------------------------
-
-  private slots:
-    /// Show context menu for sections table
-    void sectionsContextMenu(const QPoint& widgetPoint);
-
-  private:
-
-    /// Helper to set range selector values
-    void setSelectorValues(RangeSelector* selector, SectionSelector values);
-
-    /// The widget used
-    QWidget* const m_widget;
-
-    /// UI form
-    Ui::ALCBaselineModellingView m_ui;
-
-    /// Plot curves
-    QwtPlotCurve *m_dataCurve, *m_fitCurve, *m_correctedCurve;
-
-    /// Error curves
-    MantidQt::MantidWidgets::ErrorCurve *m_dataErrorCurve,
-        *m_correctedErrorCurve;
-
-    /// Range selectors
-    std::map<int, RangeSelector*> m_rangeSelectors;
-
-    QSignalMapper* m_selectorModifiedMapper;
-  };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+
+using namespace MantidWidgets;
+
+/** ALCBaselineModellingView : Widget-based implementation of the ALC Baseline
+  Modelling step
+                               interface.
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCBaselineModellingView
+    : public IALCBaselineModellingView {
+  Q_OBJECT
+
+public:
+  ALCBaselineModellingView(QWidget *widget);
+  ~ALCBaselineModellingView() override;
+
+  // -- IALCBaselineModellingView interface
+  // --------------------------------------------------------
+public:
+  QString function() const override;
+  SectionRow sectionRow(int row) const override;
+  SectionSelector sectionSelector(int index) const override;
+  int noOfSectionRows() const override;
+  void emitFitRequested();
+
+public slots:
+  void initialize() override;
+  void setDataCurve(const QwtData &data,
+                    const std::vector<double> &errors) override;
+  void setCorrectedCurve(const QwtData &data,
+                         const std::vector<double> &errors) override;
+  void setBaselineCurve(const QwtData &data) override;
+  void setFunction(Mantid::API::IFunction_const_sptr func) override;
+  void setNoOfSectionRows(int rows) override;
+  void setSectionRow(int row, SectionRow values) override;
+  void addSectionSelector(int index, SectionSelector values) override;
+  void deleteSectionSelector(int index) override;
+  void updateSectionSelector(int index, SectionSelector values) override;
+  void displayError(const QString &message) override;
+  void help() override;
+  // -- End of IALCBaselineModellingView interface
+  // -------------------------------------------------
+
+private slots:
+  /// Show context menu for sections table
+  void sectionsContextMenu(const QPoint &widgetPoint);
+
+private:
+  /// Helper to set range selector values
+  void setSelectorValues(RangeSelector *selector, SectionSelector values);
+
+  /// The widget used
+  QWidget *const m_widget;
+
+  /// UI form
+  Ui::ALCBaselineModellingView m_ui;
+
+  /// Plot curves
+  QwtPlotCurve *m_dataCurve, *m_fitCurve, *m_correctedCurve;
+
+  /// Error curves
+  MantidQt::MantidWidgets::ErrorCurve *m_dataErrorCurve, *m_correctedErrorCurve;
+
+  /// Range selectors
+  std::map<int, RangeSelector *> m_rangeSelectors;
+
+  QSignalMapper *m_selectorModifiedMapper;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCBASELINEMODELLINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCBASELINEMODELLINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingPresenter.h
index 63d7fa51012c0a19feca7bd114f914bc8da26cea..f175004cbb33efee4474ccedbe8508e6c73ed813 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingPresenter.h
@@ -11,103 +11,100 @@
 
 #include <atomic>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** ALCDataLoadingPresenter : Presenter for ALC Data Loading step
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** ALCDataLoadingPresenter : Presenter for ALC Data Loading step
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCDataLoadingPresenter : public QObject
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    ALCDataLoadingPresenter(IALCDataLoadingView* view);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCDataLoadingPresenter : public QObject {
+  Q_OBJECT
 
-    void initialize();
+public:
+  ALCDataLoadingPresenter(IALCDataLoadingView *view);
 
-    /// @return Last loaded data workspace
-    MatrixWorkspace_const_sptr loadedData() const { return m_loadedData; }
+  void initialize();
 
-    /// @return Loaded data as MatrixWorkspace_sptr
-    MatrixWorkspace_sptr exportWorkspace();
+  /// @return Last loaded data workspace
+  MatrixWorkspace_const_sptr loadedData() const { return m_loadedData; }
 
-    /// Sets some data
-    void setData (MatrixWorkspace_const_sptr data);
+  /// @return Loaded data as MatrixWorkspace_sptr
+  MatrixWorkspace_sptr exportWorkspace();
 
-  private slots:
-    /// Check file range and call method to load new data
-    void handleLoadRequested();
+  /// Sets some data
+  void setData(MatrixWorkspace_const_sptr data);
 
-    /// Updates the list of logs and number of periods
-    void updateAvailableInfo();
+private slots:
+  /// Check file range and call method to load new data
+  void handleLoadRequested();
 
-    /// When directory contents change, set flag
-    void updateDirectoryChangedFlag(const QString &path);
+  /// Updates the list of logs and number of periods
+  void updateAvailableInfo();
 
-    /// When "Auto" selected/deselected, start/stop watching directory
-    void changeWatchState(int state);
+  /// When directory contents change, set flag
+  void updateDirectoryChangedFlag(const QString &path);
 
-  signals:
-    /// Signal emitted when data get changed
-    void dataChanged();
+  /// When "Auto" selected/deselected, start/stop watching directory
+  void changeWatchState(int state);
 
-  protected:
-    /// Signal emitted when timer event occurs
-    void timerEvent(QTimerEvent *timeup) override;
+signals:
+  /// Signal emitted when data get changed
+  void dataChanged();
 
-  private:
-    /// Load new data and update the view accordingly
-    void load(const std::string &lastFile);
+protected:
+  /// Signal emitted when timer event occurs
+  void timerEvent(QTimerEvent *timeup) override;
 
-    /// Start/stop watching directory
-    void changeWatchState(bool watching);
+private:
+  /// Load new data and update the view accordingly
+  void load(const std::string &lastFile);
 
-    /// Check custom grouping is sensible
-    bool checkCustomGrouping();
+  /// Start/stop watching directory
+  void changeWatchState(bool watching);
 
-    /// View which the object works with
-    IALCDataLoadingView* const m_view;
+  /// Check custom grouping is sensible
+  bool checkCustomGrouping();
 
-    /// Last loaded data workspace
-    MatrixWorkspace_const_sptr m_loadedData;
+  /// View which the object works with
+  IALCDataLoadingView *const m_view;
 
-    /// Watch a directory for changes
-    QFileSystemWatcher m_watcher;
+  /// Last loaded data workspace
+  MatrixWorkspace_const_sptr m_loadedData;
 
-    /// Flag to indicate directory has had changes since last load
-    std::atomic_bool m_directoryChanged;
+  /// Watch a directory for changes
+  QFileSystemWatcher m_watcher;
 
-    /// ID of timer, if one is running
-    int m_timerID;
+  /// Flag to indicate directory has had changes since last load
+  std::atomic_bool m_directoryChanged;
 
-    /// Number of detectors for current first run
-    size_t m_numDetectors;
-  };
+  /// ID of timer, if one is running
+  int m_timerID;
 
+  /// Number of detectors for current first run
+  size_t m_numDetectors;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCDATALOADINGPRESENTER_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCDATALOADINGPRESENTER_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingView.h
index 53333646f368ecccf34469bf8d9da436583249b0..549d5a6c0a66875cf0c9e03d6d5d481a57c7b621 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCDataLoadingView.h
@@ -11,118 +11,118 @@
 
 #include <qwt_plot_curve.h>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class ErrorCurve;
+namespace MantidQt {
+namespace MantidWidgets {
+class ErrorCurve;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  /** ALCDataLoadingView : ALC Data Loading view interface implementation using Qt widgets
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  /**
-   *
-   */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCDataLoadingView : public IALCDataLoadingView
-  {
-  public:
-    ALCDataLoadingView(QWidget* widget);
-    ~ALCDataLoadingView();
-
-    // -- IALCDataLoadingView interface ------------------------------------------------------------
-
-    void initialize() override;
-
-    std::string firstRun() const override;
-    std::string lastRun() const override;
-    std::string log() const override;
-    std::string function() const override;
-    std::string deadTimeType() const override;
-    std::string deadTimeFile() const override;
-    std::string detectorGroupingType() const override;
-    std::string getForwardGrouping() const override;
-    std::string getBackwardGrouping() const override;
-    std::string redPeriod() const override;
-    std::string greenPeriod() const override;
-    bool subtractIsChecked() const override;
-    std::string calculationType() const override;
-    boost::optional<std::pair<double, double>> timeRange() const override;
-
-    void setDataCurve(const QwtData &data,
-                      const std::vector<double> &errors) override;
-    void displayError(const std::string &error) override;
-    void setAvailableLogs(const std::vector<std::string> &logs) override;
-    void setAvailablePeriods(const std::vector<std::string> &periods) override;
-    void setTimeLimits(double tMin, double tMax) override;
-    void setTimeRange(double tMin, double tMax) override;
-    void help() override;
-    void disableAll() override;
-    void enableAll() override;
-    void checkBoxAutoChanged(int state) override;
-    void handleFirstFileChanged() override;
-
-    /// returns the string "Auto"
-    std::string autoString() const override { return g_autoString; }
-
-    /// If Auto mode on, store name of currently loaded file
-    /// @param file :: [input] name of file loaded
-    void setCurrentAutoFile(const std::string &file) override {
-      m_currentAutoFile = file;
-    }
-
-    // -- End of IALCDataLoadingView interface -----------------------------------------------------
-
-  private:
-    /// Common function to set available items in a combo box
-    void setAvailableItems(QComboBox *comboBox,
-                           const std::vector<std::string> &items);
-
-    /// UI form
-    Ui::ALCDataLoadingView m_ui;
-
-    /// The widget used
-    QWidget* const m_widget;
-
-    /// Loaded data curve
-    QwtPlotCurve* m_dataCurve;
-
-    /// Loaded errors
-    MantidQt::MantidWidgets::ErrorCurve* m_dataErrorCurve;
-
-    /// the string "Auto"
-    static const std::string g_autoString;
-
-    /// If Auto in use, the file last loaded
-    std::string m_currentAutoFile;
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/** ALCDataLoadingView : ALC Data Loading view interface implementation using Qt
+  widgets
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+/**
+ *
+ */
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCDataLoadingView
+    : public IALCDataLoadingView {
+public:
+  ALCDataLoadingView(QWidget *widget);
+  ~ALCDataLoadingView();
+
+  // -- IALCDataLoadingView interface
+  // ------------------------------------------------------------
+
+  void initialize() override;
+
+  std::string firstRun() const override;
+  std::string lastRun() const override;
+  std::string log() const override;
+  std::string function() const override;
+  std::string deadTimeType() const override;
+  std::string deadTimeFile() const override;
+  std::string detectorGroupingType() const override;
+  std::string getForwardGrouping() const override;
+  std::string getBackwardGrouping() const override;
+  std::string redPeriod() const override;
+  std::string greenPeriod() const override;
+  bool subtractIsChecked() const override;
+  std::string calculationType() const override;
+  boost::optional<std::pair<double, double>> timeRange() const override;
+
+  void setDataCurve(const QwtData &data,
+                    const std::vector<double> &errors) override;
+  void displayError(const std::string &error) override;
+  void setAvailableLogs(const std::vector<std::string> &logs) override;
+  void setAvailablePeriods(const std::vector<std::string> &periods) override;
+  void setTimeLimits(double tMin, double tMax) override;
+  void setTimeRange(double tMin, double tMax) override;
+  void help() override;
+  void disableAll() override;
+  void enableAll() override;
+  void checkBoxAutoChanged(int state) override;
+  void handleFirstFileChanged() override;
+
+  /// returns the string "Auto"
+  std::string autoString() const override { return g_autoString; }
+
+  /// If Auto mode on, store name of currently loaded file
+  /// @param file :: [input] name of file loaded
+  void setCurrentAutoFile(const std::string &file) override {
+    m_currentAutoFile = file;
+  }
+
+  // -- End of IALCDataLoadingView interface
+  // -----------------------------------------------------
+
+private:
+  /// Common function to set available items in a combo box
+  void setAvailableItems(QComboBox *comboBox,
+                         const std::vector<std::string> &items);
+
+  /// UI form
+  Ui::ALCDataLoadingView m_ui;
+
+  /// The widget used
+  QWidget *const m_widget;
+
+  /// Loaded data curve
+  QwtPlotCurve *m_dataCurve;
+
+  /// Loaded errors
+  MantidQt::MantidWidgets::ErrorCurve *m_dataErrorCurve;
+
+  /// the string "Auto"
+  static const std::string g_autoString;
+
+  /// If Auto in use, the file last loaded
+  std::string m_currentAutoFile;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCDATALOADINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCDATALOADINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCHelper.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCHelper.h
index db5d4d350ecd7b3d42aa7a81ba6a6a1227a400a7..c2ad1db08d40d0c22a78bb8c371391c9c839e01d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCHelper.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCHelper.h
@@ -9,34 +9,35 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace ALCHelper
-{
-  /// Create Qwt curve data from a workspace
-  boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex);
-
-  /// Create vector of Qwt curve data from a workspace, used for EnggDiffraction GUI
-  std::vector<boost::shared_ptr<QwtData>> curveDataFromWs(MatrixWorkspace_const_sptr ws);
-
-  /// Create error vector from a workspace
-  std::vector<double> curveErrorsFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex);
-
-  /// Create Qwt curve data from a function
-  boost::shared_ptr<QwtData> curveDataFromFunction(IFunction_const_sptr func,
-                                                 const std::vector<double>& xValues);
-
-  /// Create workspace filled with function values
-  MatrixWorkspace_sptr createWsFromFunction(IFunction_const_sptr func,
-                                            const std::vector<double>& xValues);
-
-  /// Creates empty Qwt curve data
-  boost::shared_ptr<QwtData> emptyCurveData();
-
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace ALCHelper {
+/// Create Qwt curve data from a workspace
+boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws,
+                                           size_t wsIndex);
+
+/// Create vector of Qwt curve data from a workspace, used for EnggDiffraction
+/// GUI
+std::vector<boost::shared_ptr<QwtData>>
+curveDataFromWs(MatrixWorkspace_const_sptr ws);
+
+/// Create error vector from a workspace
+std::vector<double> curveErrorsFromWs(MatrixWorkspace_const_sptr ws,
+                                      size_t wsIndex);
+
+/// Create Qwt curve data from a function
+boost::shared_ptr<QwtData>
+curveDataFromFunction(IFunction_const_sptr func,
+                      const std::vector<double> &xValues);
+
+/// Create workspace filled with function values
+MatrixWorkspace_sptr createWsFromFunction(IFunction_const_sptr func,
+                                          const std::vector<double> &xValues);
+
+/// Creates empty Qwt curve data
+boost::shared_ptr<QwtData> emptyCurveData();
 }
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTID_CUSTOMINTERFACES_ALCHELPER_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_ALCHELPER_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCInterface.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCInterface.h
index cc4ac35055f434dbca28c104436c8e173f0f6fbf..5d46d031f172be6b1ec2ad7dd88c5740dbc328f5 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCInterface.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCInterface.h
@@ -11,94 +11,91 @@
 
 #include <qwt_symbol.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  class ALCDataLoadingPresenter;
+class ALCDataLoadingPresenter;
 
-  class ALCBaselineModellingView;
-  class ALCBaselineModellingPresenter;
-  class ALCBaselineModellingModel;
+class ALCBaselineModellingView;
+class ALCBaselineModellingPresenter;
+class ALCBaselineModellingModel;
 
-  class ALCPeakFittingView;
-  class ALCPeakFittingPresenter;
-  class ALCPeakFittingModel;
+class ALCPeakFittingView;
+class ALCPeakFittingPresenter;
+class ALCPeakFittingModel;
 
-  /** ALCInterface : Custom interface for Avoided Level Crossing analysis
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** ALCInterface : Custom interface for Avoided Level Crossing analysis
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCInterface : public API::UserSubWindow
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    ALCInterface(QWidget* parent = 0);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCInterface : public API::UserSubWindow {
+  Q_OBJECT
 
-    static std::string name() { return "ALC"; }
-    static QString categoryInfo() { return "Muon"; }
+public:
+  ALCInterface(QWidget *parent = 0);
 
-  protected:
-    void initLayout() override;
+  static std::string name() { return "ALC"; }
+  static QString categoryInfo() { return "Muon"; }
 
-  private slots:
-    void nextStep();
-    void previousStep();
+protected:
+  void initLayout() override;
 
-    void switchStep(int newStepIndex);
+private slots:
+  void nextStep();
+  void previousStep();
 
-    void exportResults();
-    void importResults();
+  void switchStep(int newStepIndex);
 
-    void updateBaselineData();
-    void updatePeakData();
+  void exportResults();
+  void importResults();
 
-  private:
+  void updateBaselineData();
+  void updatePeakData();
 
-    /// UI form
-    Ui::ALCInterface m_ui;
+private:
+  /// UI form
+  Ui::ALCInterface m_ui;
 
-    // Step views
-    ALCBaselineModellingView* m_baselineModellingView;
-    ALCPeakFittingView* m_peakFittingView;
+  // Step views
+  ALCBaselineModellingView *m_baselineModellingView;
+  ALCPeakFittingView *m_peakFittingView;
 
-    // Step presenters
-    ALCDataLoadingPresenter* m_dataLoading;
-    ALCBaselineModellingPresenter* m_baselineModelling;
-    ALCPeakFittingPresenter* m_peakFitting;
+  // Step presenters
+  ALCDataLoadingPresenter *m_dataLoading;
+  ALCBaselineModellingPresenter *m_baselineModelling;
+  ALCPeakFittingPresenter *m_peakFitting;
 
-    // Models
-    ALCBaselineModellingModel* m_baselineModellingModel;
-    ALCPeakFittingModel* m_peakFittingModel;
+  // Models
+  ALCBaselineModellingModel *m_baselineModellingModel;
+  ALCPeakFittingModel *m_peakFittingModel;
 
-    /// Name for every step for labels
-    static const QStringList STEP_NAMES;
+  /// Name for every step for labels
+  static const QStringList STEP_NAMES;
 
-    /// Format of the label at the bottom
-    static const QString LABEL_FORMAT;
-  };
+  /// Format of the label at the bottom
+  static const QString LABEL_FORMAT;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCINTERFACE_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCINTERFACE_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
index 710397861b3b3fcd8ac416e3948d3a21e7c2dce5..82124d36f0845739a198b4a8223f3ae91cec7f9f 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingModel.h
@@ -9,69 +9,69 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** ALCPeakFittingModel : Concrete model for ALC peak fitting
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** ALCPeakFittingModel : Concrete model for ALC peak fitting
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingModel : public IALCPeakFittingModel
-  {
-  public:
-    // -- IALCPeakFittingModel interface -----------------------------------------------------------
-    IFunction_const_sptr fittedPeaks() const override { return m_fittedPeaks; }
-    MatrixWorkspace_const_sptr data() const override { return m_data; }
-    ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    void fitPeaks(IFunction_const_sptr peaks) override;
-    // -- End of IALCPeakFittingModel interface ----------------------------------------------------
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingModel
+    : public IALCPeakFittingModel {
+public:
+  // -- IALCPeakFittingModel interface
+  // -----------------------------------------------------------
+  IFunction_const_sptr fittedPeaks() const override { return m_fittedPeaks; }
+  MatrixWorkspace_const_sptr data() const override { return m_data; }
+  ITableWorkspace_sptr parameterTable() const { return m_parameterTable; }
 
-    /// Update the data
-    void setData(MatrixWorkspace_const_sptr newData);
+  void fitPeaks(IFunction_const_sptr peaks) override;
+  // -- End of IALCPeakFittingModel interface
+  // ----------------------------------------------------
 
-    /// Export data and fitted peaks as a single workspace
-    MatrixWorkspace_sptr exportWorkspace();
+  /// Update the data
+  void setData(MatrixWorkspace_const_sptr newData);
 
-    /// Export fitted peaks as a table workspace
-    ITableWorkspace_sptr exportFittedPeaks();
+  /// Export data and fitted peaks as a single workspace
+  MatrixWorkspace_sptr exportWorkspace();
 
-  private:
-    /// The data we are fitting peaks to
-    MatrixWorkspace_const_sptr m_data;
+  /// Export fitted peaks as a table workspace
+  ITableWorkspace_sptr exportFittedPeaks();
 
-    /// Parameter table containing fit results
-    ITableWorkspace_sptr m_parameterTable;
+private:
+  /// The data we are fitting peaks to
+  MatrixWorkspace_const_sptr m_data;
 
-    /// Setter for convenience
-    void setFittedPeaks(IFunction_const_sptr fittedPeaks);
+  /// Parameter table containing fit results
+  ITableWorkspace_sptr m_parameterTable;
 
-    /// Last fitted peaks
-    IFunction_const_sptr m_fittedPeaks;
-  };
+  /// Setter for convenience
+  void setFittedPeaks(IFunction_const_sptr fittedPeaks);
 
+  /// Last fitted peaks
+  IFunction_const_sptr m_fittedPeaks;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTID_CUSTOMINTERFACES_ALCPEAKFITTINGMODEL_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_ALCPEAKFITTINGMODEL_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingPresenter.h
index 3e2420da03a4fdcc60b7b315a090b652badd2188..02735d7ec4012cc19add48588df35e3a5cdece7c 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingPresenter.h
@@ -8,80 +8,78 @@
 #include "MantidQtCustomInterfaces/Muon/IALCPeakFittingView.h"
 #include "MantidQtCustomInterfaces/Muon/IALCPeakFittingModel.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** ALCPeakFittingPresenter : Presenter for Peak Fitting step of ALC interface.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** ALCPeakFittingPresenter : Presenter for Peak Fitting step of ALC interface.
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingPresenter : public QObject
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    ALCPeakFittingPresenter(IALCPeakFittingView* view, IALCPeakFittingModel* model);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingPresenter : public QObject {
+  Q_OBJECT
 
-    void initialize();
+public:
+  ALCPeakFittingPresenter(IALCPeakFittingView *view,
+                          IALCPeakFittingModel *model);
 
-  private slots:
-    /// Fit the data using the peaks from the view, and update them
-    void fit();
+  void initialize();
 
-    /// Executed when user selects a function in a Function Browser
-    void onCurrentFunctionChanged();
+private slots:
+  /// Fit the data using the peaks from the view, and update them
+  void fit();
 
-    /// Executed when Peak Picker if moved/resized
-    void onPeakPickerChanged();
+  /// Executed when user selects a function in a Function Browser
+  void onCurrentFunctionChanged();
 
-    /// Executed when user changes parameter in Function Browser
-    void onParameterChanged(const QString& funcIndex);
+  /// Executed when Peak Picker if moved/resized
+  void onPeakPickerChanged();
 
-    void onFittedPeaksChanged();
-    void onDataChanged();
+  /// Executed when user changes parameter in Function Browser
+  void onParameterChanged(const QString &funcIndex);
 
-    /// Executed when user clicks "Plot guess"
-    void onPlotGuessClicked();
+  void onFittedPeaksChanged();
+  void onDataChanged();
 
-  private:
-    /// Plot guess on graph
-    bool plotGuessOnGraph();
+  /// Executed when user clicks "Plot guess"
+  void onPlotGuessClicked();
 
-    /// Remove plots from graph
-    void removePlots();
+private:
+  /// Plot guess on graph
+  bool plotGuessOnGraph();
 
-    /// Associated view
-    IALCPeakFittingView* const m_view;
+  /// Remove plots from graph
+  void removePlots();
 
-    /// Associated model
-    IALCPeakFittingModel* const m_model;
+  /// Associated view
+  IALCPeakFittingView *const m_view;
 
-    /// Whether guess is currently plotted
-    bool m_guessPlotted;
-  };
+  /// Associated model
+  IALCPeakFittingModel *const m_model;
 
+  /// Whether guess is currently plotted
+  bool m_guessPlotted;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCPEAKFITTINGPRESENTER_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCPEAKFITTINGPRESENTER_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingView.h
index c883f19a068a77097e6bfe7cf92a1e23ed1d3b09..a3d297354888cd80c2fc8b9224a1ddf85a0d4cab 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/ALCPeakFittingView.h
@@ -12,90 +12,89 @@
 #include <QWidget>
 #include <qwt_plot_curve.h>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class ErrorCurve;
+namespace MantidQt {
+namespace MantidWidgets {
+class ErrorCurve;
 }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  /** ALCPeakFittingView : Qt implementation of the ALC Peak Fitting step interface.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingView : public IALCPeakFittingView
-  {
-  public:
-    ALCPeakFittingView(QWidget* widget);
-    ~ALCPeakFittingView();
-
-    // -- IALCPeakFitting interface ----------------------------------------------------------------
-
-    IFunction_const_sptr function(QString index) const override;
-    boost::optional<QString> currentFunctionIndex() const override;
-    IPeakFunction_const_sptr peakPicker() const override;
-    void emitFitRequested();
-
-  public slots:
-
-    void initialize() override;
-    void setDataCurve(const QwtData &data,
-                      const std::vector<double> &errors) override;
-    void setFittedCurve(const QwtData &data) override;
-    void setFunction(const IFunction_const_sptr &newFunction) override;
-    void setParameter(const QString &funcIndex, const QString &paramName,
-                      double value) override;
-    void setPeakPickerEnabled(bool enabled) override;
-    void setPeakPicker(const IPeakFunction_const_sptr &peak) override;
-    void displayError(const QString &message) override;
-    void help() override;
-    void plotGuess() override;
-    void changePlotGuessState(bool plotted) override;
-
-    // -- End of IALCPeakFitting interface ---------------------------------------------------------
-  private:
-    /// The widget used
-    QWidget* const m_widget;
-
-    /// UI form
-    Ui::ALCPeakFittingView m_ui;
-
-    /// Plot curves
-    QwtPlotCurve *m_dataCurve, *m_fittedCurve;
-
-    /// Error curves
-    MantidQt::MantidWidgets::ErrorCurve *m_dataErrorCurve;
-
-    /// Peak picker tool - only one on the plot at any given moment
-    MantidWidgets::PeakPicker* m_peakPicker;
-  };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/** ALCPeakFittingView : Qt implementation of the ALC Peak Fitting step
+  interface.
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL ALCPeakFittingView
+    : public IALCPeakFittingView {
+public:
+  ALCPeakFittingView(QWidget *widget);
+  ~ALCPeakFittingView();
+
+  // -- IALCPeakFitting interface
+  // ----------------------------------------------------------------
+
+  IFunction_const_sptr function(QString index) const override;
+  boost::optional<QString> currentFunctionIndex() const override;
+  IPeakFunction_const_sptr peakPicker() const override;
+  void emitFitRequested();
+
+public slots:
+
+  void initialize() override;
+  void setDataCurve(const QwtData &data,
+                    const std::vector<double> &errors) override;
+  void setFittedCurve(const QwtData &data) override;
+  void setFunction(const IFunction_const_sptr &newFunction) override;
+  void setParameter(const QString &funcIndex, const QString &paramName,
+                    double value) override;
+  void setPeakPickerEnabled(bool enabled) override;
+  void setPeakPicker(const IPeakFunction_const_sptr &peak) override;
+  void displayError(const QString &message) override;
+  void help() override;
+  void plotGuess() override;
+  void changePlotGuessState(bool plotted) override;
+
+  // -- End of IALCPeakFitting interface
+  // ---------------------------------------------------------
+private:
+  /// The widget used
+  QWidget *const m_widget;
+
+  /// UI form
+  Ui::ALCPeakFittingView m_ui;
+
+  /// Plot curves
+  QwtPlotCurve *m_dataCurve, *m_fittedCurve;
+
+  /// Error curves
+  MantidQt::MantidWidgets::ErrorCurve *m_dataErrorCurve;
+
+  /// Peak picker tool - only one on the plot at any given moment
+  MantidWidgets::PeakPicker *m_peakPicker;
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_ALCPEAKFITTINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_ALCPEAKFITTINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingModel.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingModel.h
index 5f1c629d8349eb239aebec43314d02af6076f66f..32cea239df06c90de5e5bd60bca5f4d66788e9c7 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingModel.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingModel.h
@@ -12,72 +12,73 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  /** IALCBaselineModellingModel : Model interface for ALC BaselineModelling step
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL IALCBaselineModellingModel : public QObject
-  {
-    Q_OBJECT
-
-  public:
-    typedef std::pair<double, double> Section;
-
-    /**
-     * @return Function produced by the last fit
-     */
-    virtual IFunction_const_sptr fittedFunction() const = 0;
-
-    /**
-     * @return Corrected data produced by the last fit
-     */
-    virtual MatrixWorkspace_const_sptr correctedData() const = 0;
-
-    /**
-     * @return Current data used for fitting
-     */
-    virtual MatrixWorkspace_const_sptr data() const = 0;
-
-    /**
-     * Perform a fit using current data and specified function and sections. Modified values returned
-     * by fittedFunction and correctedData.
-     * @param function :: Function to fit
-     * @param sections :: Data sections to include in the fit
-     */
-    virtual void fit(IFunction_const_sptr function, const std::vector<Section>& sections) = 0;
-
-  signals:
-
-    // Signals emitted when various properties get changed
-    void dataChanged();
-    void fittedFunctionChanged();
-    void correctedDataChanged();
-  };
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/** IALCBaselineModellingModel : Model interface for ALC BaselineModelling step
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL IALCBaselineModellingModel
+    : public QObject {
+  Q_OBJECT
+
+public:
+  typedef std::pair<double, double> Section;
+
+  /**
+   * @return Function produced by the last fit
+   */
+  virtual IFunction_const_sptr fittedFunction() const = 0;
+
+  /**
+   * @return Corrected data produced by the last fit
+   */
+  virtual MatrixWorkspace_const_sptr correctedData() const = 0;
+
+  /**
+   * @return Current data used for fitting
+   */
+  virtual MatrixWorkspace_const_sptr data() const = 0;
+
+  /**
+   * Perform a fit using current data and specified function and sections.
+   * Modified values returned
+   * by fittedFunction and correctedData.
+   * @param function :: Function to fit
+   * @param sections :: Data sections to include in the fit
+   */
+  virtual void fit(IFunction_const_sptr function,
+                   const std::vector<Section> &sections) = 0;
+
+signals:
+
+  // Signals emitted when various properties get changed
+  void dataChanged();
+  void fittedFunctionChanged();
+  void correctedDataChanged();
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTID_CUSTOMINTERFACES_IALCBASELINEMODELLINGMODEL_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_IALCBASELINEMODELLINGMODEL_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingView.h
index 18a8723f363786c06ef32e327551ea80548d562b..518257973108e132436f9e2c12aa7744ea257709 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCBaselineModellingView.h
@@ -9,164 +9,161 @@
 #include <QObject>
 #include "qwt_data.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  /** IALCBaselineModellingView : Interface for ALC Baseline Modelling view step
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL IALCBaselineModellingView : public QObject
-  {
-    Q_OBJECT
-
-  public:
-    typedef std::pair<QString,QString> SectionRow;
-    typedef std::pair<double,double> SectionSelector;
-
-    /// Function chosen to fit the data to
-    /// @return Function string, or empty string if nothing chosen
-    virtual QString function() const = 0;
-
-    /**
-     * @param row :: Row number
-     * @return Row values from the section table
-     */
-    virtual SectionRow sectionRow(int row) const = 0;
-
-    /**
-     * @param index :: Section selector index
-     * @return Section selector values
-     */
-    virtual SectionSelector sectionSelector(int index) const = 0;
-
-    /**
-     * @return Number of rows in section table
-     */
-    virtual int noOfSectionRows() const = 0;
-
-  public slots:
-    /// Performs any necessary initialization
-    virtual void initialize() = 0;
-
-    /**
-     * Update displayed data curve
-     * @param data :: New curve data
-     * @param errors :: Curve errors
-     */
-    virtual void setDataCurve(const QwtData &data,
-                              const std::vector<double> &errors) = 0;
-
-    /**
-     * Update displayed corrected data curve
-     * @param data :: New curve data
-     * @param errors :: Curve errors
-     */
-    virtual void setCorrectedCurve(const QwtData &data,
-                                   const std::vector<double> &errors) = 0;
-
-    /**
-     * Update displayed baseline curve
-     * @param data :: New curve data
-     */
-    virtual void setBaselineCurve(const QwtData& data) = 0;
-
-    /**
-     * Update displayed function
-     * @param func :: New function
-     */
-    virtual void setFunction(Mantid::API::IFunction_const_sptr func) = 0;
-
-    /**
-     * Resize sections table
-     * @param rows :: New number of rows
-     */
-    virtual void setNoOfSectionRows(int rows) = 0;
-
-    /**
-     * Updates the row values in the table
-     * @param row :: Row in sections table
-     * @param values :: New row values
-     */
-    virtual void setSectionRow(int row, SectionRow values) = 0;
-
-    /**
-     * Adds a new section selector
-     * @param index :: Index of added section selector, to find it later
-     * @param values :: Initial values
-     */
-    virtual void addSectionSelector(int index, SectionSelector values) = 0;
-
-    /**
-     * Deletes section selector at specified index
-     * @param index :: Section selector index
-     */
-    virtual void deleteSectionSelector(int index) = 0;
-
-    /**
-     * Update section selector values
-     * @param index :: Index of the selector to update
-     * @param values :: New values
-     */
-    virtual void updateSectionSelector(int index, SectionSelector values) = 0;
-
-    /**
-     * Pops-up an error box
-     * @param message :: Error message to display
-     */
-    virtual void displayError(const QString& message) = 0;
-
-    /// Links help button to wiki page
-    virtual void help() = 0;
-
-  signals:
-    /// Fit requested
-    void fitRequested();
-
-    /// New section addition requested
-    void addSectionRequested();
-
-    /**
-     * Section removal requested
-     * @param row :: Section row to remove
-     */
-    void removeSectionRequested(int row);
-
-    /**
-     * One of the section rows in the table was modified
-     * @param row :: Modified section row
-     */
-    void sectionRowModified(int row);
-
-    /**
-     * One of section selectors has been modified
-     * @param index :: Index of modified selector
-     */
-    void sectionSelectorModified(int index);
-  };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+
+/** IALCBaselineModellingView : Interface for ALC Baseline Modelling view step
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL IALCBaselineModellingView : public QObject {
+  Q_OBJECT
+
+public:
+  typedef std::pair<QString, QString> SectionRow;
+  typedef std::pair<double, double> SectionSelector;
+
+  /// Function chosen to fit the data to
+  /// @return Function string, or empty string if nothing chosen
+  virtual QString function() const = 0;
+
+  /**
+   * @param row :: Row number
+   * @return Row values from the section table
+   */
+  virtual SectionRow sectionRow(int row) const = 0;
+
+  /**
+   * @param index :: Section selector index
+   * @return Section selector values
+   */
+  virtual SectionSelector sectionSelector(int index) const = 0;
+
+  /**
+   * @return Number of rows in section table
+   */
+  virtual int noOfSectionRows() const = 0;
+
+public slots:
+  /// Performs any necessary initialization
+  virtual void initialize() = 0;
+
+  /**
+   * Update displayed data curve
+   * @param data :: New curve data
+   * @param errors :: Curve errors
+   */
+  virtual void setDataCurve(const QwtData &data,
+                            const std::vector<double> &errors) = 0;
+
+  /**
+   * Update displayed corrected data curve
+   * @param data :: New curve data
+   * @param errors :: Curve errors
+   */
+  virtual void setCorrectedCurve(const QwtData &data,
+                                 const std::vector<double> &errors) = 0;
+
+  /**
+   * Update displayed baseline curve
+   * @param data :: New curve data
+   */
+  virtual void setBaselineCurve(const QwtData &data) = 0;
+
+  /**
+   * Update displayed function
+   * @param func :: New function
+   */
+  virtual void setFunction(Mantid::API::IFunction_const_sptr func) = 0;
+
+  /**
+   * Resize sections table
+   * @param rows :: New number of rows
+   */
+  virtual void setNoOfSectionRows(int rows) = 0;
+
+  /**
+   * Updates the row values in the table
+   * @param row :: Row in sections table
+   * @param values :: New row values
+   */
+  virtual void setSectionRow(int row, SectionRow values) = 0;
+
+  /**
+   * Adds a new section selector
+   * @param index :: Index of added section selector, to find it later
+   * @param values :: Initial values
+   */
+  virtual void addSectionSelector(int index, SectionSelector values) = 0;
+
+  /**
+   * Deletes section selector at specified index
+   * @param index :: Section selector index
+   */
+  virtual void deleteSectionSelector(int index) = 0;
+
+  /**
+   * Update section selector values
+   * @param index :: Index of the selector to update
+   * @param values :: New values
+   */
+  virtual void updateSectionSelector(int index, SectionSelector values) = 0;
+
+  /**
+   * Pops-up an error box
+   * @param message :: Error message to display
+   */
+  virtual void displayError(const QString &message) = 0;
+
+  /// Links help button to wiki page
+  virtual void help() = 0;
+
+signals:
+  /// Fit requested
+  void fitRequested();
+
+  /// New section addition requested
+  void addSectionRequested();
+
+  /**
+   * Section removal requested
+   * @param row :: Section row to remove
+   */
+  void removeSectionRequested(int row);
+
+  /**
+   * One of the section rows in the table was modified
+   * @param row :: Modified section row
+   */
+  void sectionRowModified(int row);
+
+  /**
+   * One of section selectors has been modified
+   * @param index :: Index of modified selector
+   */
+  void sectionSelectorModified(int index);
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_IALCBASELINEMODELLINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_IALCBASELINEMODELLINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCDataLoadingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCDataLoadingView.h
index 10cd333d5c81e251b31e014a32944d4476e7f745..8042401657beaef348bf7a8f71ce0d7c6fce1dbd 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCDataLoadingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCDataLoadingView.h
@@ -12,150 +12,151 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /** IALCDataLoadingView : View interface for ALC Data Loading step
+namespace MantidQt {
+namespace CustomInterfaces {
+/** IALCDataLoadingView : View interface for ALC Data Loading step
 
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL IALCDataLoadingView : public QObject
-  {
-    Q_OBJECT
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL IALCDataLoadingView : public QObject {
+  Q_OBJECT
 
-  public:
-    /// @return Full path to first run data file, or empty string if invalid/not selected
-    virtual std::string firstRun() const = 0;
+public:
+  /// @return Full path to first run data file, or empty string if invalid/not
+  /// selected
+  virtual std::string firstRun() const = 0;
 
-    /// @return Full path to last run data file, or empty string if invalid/not selected
-    virtual std::string lastRun() const = 0;
+  /// @return Full path to last run data file, or empty string if invalid/not
+  /// selected
+  virtual std::string lastRun() const = 0;
 
-    /// Returns the name of the log to use
-    /// @return Log name
-    virtual std::string log() const = 0;
+  /// Returns the name of the log to use
+  /// @return Log name
+  virtual std::string log() const = 0;
 
-    /// Returns the function to apply
-    /// @return Log function
-    virtual std::string function() const = 0;
+  /// Returns the function to apply
+  /// @return Log function
+  virtual std::string function() const = 0;
 
-    /// @return dead time correction type to use
-    virtual std::string deadTimeType() const = 0;
+  /// @return dead time correction type to use
+  virtual std::string deadTimeType() const = 0;
 
-    /// @return dead time correction file
-    virtual std::string deadTimeFile() const = 0;
+  /// @return dead time correction file
+  virtual std::string deadTimeFile() const = 0;
 
-    /// @return detector grouping type
-    virtual std::string detectorGroupingType() const = 0;
+  /// @return detector grouping type
+  virtual std::string detectorGroupingType() const = 0;
 
-    /// @return forward grouping
-    virtual std::string getForwardGrouping() const = 0;
+  /// @return forward grouping
+  virtual std::string getForwardGrouping() const = 0;
 
-    /// @return backward grouping
-    virtual std::string getBackwardGrouping() const = 0;
+  /// @return backward grouping
+  virtual std::string getBackwardGrouping() const = 0;
 
-    /// @return red period
-    virtual std::string redPeriod() const = 0;
+  /// @return red period
+  virtual std::string redPeriod() const = 0;
 
-    /// @return green period
-    virtual std::string greenPeriod() const = 0;
+  /// @return green period
+  virtual std::string greenPeriod() const = 0;
 
-    /// @return subtract checkbox
-    virtual bool subtractIsChecked() const =0;
+  /// @return subtract checkbox
+  virtual bool subtractIsChecked() const = 0;
 
-    /// @return Selected calculation type - "Integral" or "Differential"
-    virtual std::string calculationType() const = 0;
+  /// @return Selected calculation type - "Integral" or "Differential"
+  virtual std::string calculationType() const = 0;
 
-    /// @return Selected integration time range, or nothing if limiting is disabled
-    virtual boost::optional< std::pair<double,double> > timeRange() const = 0;
+  /// @return Selected integration time range, or nothing if limiting is
+  /// disabled
+  virtual boost::optional<std::pair<double, double>> timeRange() const = 0;
 
-    /// @return The string "Auto"
-    virtual std::string autoString() const = 0;
+  /// @return The string "Auto"
+  virtual std::string autoString() const = 0;
 
-    /// If Auto mode on, store name of currently loaded file
-    /// @param file :: [input] name of file loaded
-    virtual void setCurrentAutoFile(const std::string &file) = 0;
+  /// If Auto mode on, store name of currently loaded file
+  /// @param file :: [input] name of file loaded
+  virtual void setCurrentAutoFile(const std::string &file) = 0;
 
-  public slots:
-    /// Performs any necessary initialization
-    virtual void initialize() = 0;
+public slots:
+  /// Performs any necessary initialization
+  virtual void initialize() = 0;
 
-    /// Updates the data curve
-    /// @param data :: New curve data to set
-    /// @param errors :: New curve errors to set
-    virtual void setDataCurve(const QwtData &data,
-                              const std::vector<double> &errors) = 0;
+  /// Updates the data curve
+  /// @param data :: New curve data to set
+  /// @param errors :: New curve errors to set
+  virtual void setDataCurve(const QwtData &data,
+                            const std::vector<double> &errors) = 0;
 
-    /// Displays an error
-    /// @param error :: Error message to display
-    virtual void displayError(const std::string& error) = 0;
+  /// Displays an error
+  /// @param error :: Error message to display
+  virtual void displayError(const std::string &error) = 0;
 
-    /// Update the list of logs user can select
-    /// @param logs :: New list of log names
-    virtual void setAvailableLogs(const std::vector<std::string>& logs) = 0;
+  /// Update the list of logs user can select
+  /// @param logs :: New list of log names
+  virtual void setAvailableLogs(const std::vector<std::string> &logs) = 0;
 
-    /// Update the list of periods user can select
-    /// @param periods :: New list of periods
-    virtual void setAvailablePeriods(const std::vector<std::string>& periods) = 0;
+  /// Update the list of periods user can select
+  /// @param periods :: New list of periods
+  virtual void setAvailablePeriods(const std::vector<std::string> &periods) = 0;
 
-    /// Update the time limits
-    /// @param tMin :: Minimum X value available
-    /// @param tMax :: Maximum X value available
-    virtual void setTimeLimits(double tMin, double tMax) = 0;
+  /// Update the time limits
+  /// @param tMin :: Minimum X value available
+  /// @param tMax :: Maximum X value available
+  virtual void setTimeLimits(double tMin, double tMax) = 0;
 
-    /// Update the time limits
-    /// @param tMin :: Minimum X value available
-    /// @param tMax :: Maximum X value available
-    virtual void setTimeRange(double tMin, double tMax) = 0;
+  /// Update the time limits
+  /// @param tMin :: Minimum X value available
+  /// @param tMax :: Maximum X value available
+  virtual void setTimeRange(double tMin, double tMax) = 0;
 
-    /// Opens the Mantid Wiki web page
-    virtual void help() = 0;
+  /// Opens the Mantid Wiki web page
+  virtual void help() = 0;
 
-    /// Disables all the widgets
-    virtual void disableAll() = 0;
+  /// Disables all the widgets
+  virtual void disableAll() = 0;
 
-    /// Enables all the widgets
-    virtual void enableAll() = 0;
+  /// Enables all the widgets
+  virtual void enableAll() = 0;
 
-    /// Toggles "auto" mode for last file
-    virtual void checkBoxAutoChanged(int state) = 0;
+  /// Toggles "auto" mode for last file
+  virtual void checkBoxAutoChanged(int state) = 0;
 
-    /// Gets directory from first file and sets last file directory
-    virtual void handleFirstFileChanged() = 0;
+  /// Gets directory from first file and sets last file directory
+  virtual void handleFirstFileChanged() = 0;
 
-  signals:
-    /// Request to load data
-    void loadRequested();
+signals:
+  /// Request to load data
+  void loadRequested();
 
-    /// User has selected the first run
-    void firstRunSelected();
+  /// User has selected the first run
+  void firstRunSelected();
 
-    /// New data have been loaded
-    void dataChanged();
+  /// New data have been loaded
+  void dataChanged();
 
-    /// "Auto" box has been checked/unchecked
-    void lastRunAutoCheckedChanged(int state);
-  };
+  /// "Auto" box has been checked/unchecked
+  void lastRunAutoCheckedChanged(int state);
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_IALCDATALOADINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_IALCDATALOADINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingModel.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingModel.h
index b579a192c672c20378f6725c143bb9580b0e2be7..3b406c6fbb68f11e91b7de2dc4ba3ebbad94edd9 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingModel.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingModel.h
@@ -11,68 +11,65 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** IALCPeakFittingModel : ALC peak fitting step model interface.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** IALCPeakFittingModel : ALC peak fitting step model interface.
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL IALCPeakFittingModel : public QObject
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    /**
-     * @return Last fitted peaks
-     */
-    virtual IFunction_const_sptr fittedPeaks() const = 0;
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL IALCPeakFittingModel : public QObject {
+  Q_OBJECT
 
-    /**
-     * @return Data we are fitting peaks to
-     */
-    virtual MatrixWorkspace_const_sptr data() const = 0;
+public:
+  /**
+   * @return Last fitted peaks
+   */
+  virtual IFunction_const_sptr fittedPeaks() const = 0;
 
-    /**
-     * Fit specified peaks to the data of the model
-     * @param peaks :: Function representing peaks to fit
-     */
-    virtual void fitPeaks(IFunction_const_sptr peaks) = 0;
+  /**
+   * @return Data we are fitting peaks to
+   */
+  virtual MatrixWorkspace_const_sptr data() const = 0;
 
-  signals:
+  /**
+   * Fit specified peaks to the data of the model
+   * @param peaks :: Function representing peaks to fit
+   */
+  virtual void fitPeaks(IFunction_const_sptr peaks) = 0;
 
-    /// Signal to inform that the fitting was done and fitted peaks were updated
-    void fittedPeaksChanged();
+signals:
 
-    /// Signal to inform that data was set
-    void dataChanged();
+  /// Signal to inform that the fitting was done and fitted peaks were updated
+  void fittedPeaksChanged();
 
-    /// Signal to inform presenter of an error with fitting
-    void errorInModel(const QString &message);
-  };
+  /// Signal to inform that data was set
+  void dataChanged();
 
+  /// Signal to inform presenter of an error with fitting
+  void errorInModel(const QString &message);
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTID_CUSTOMINTERFACES_IALCPEAKFITTINGMODEL_H_ */
+#endif /* MANTID_CUSTOMINTERFACES_IALCPEAKFITTINGMODEL_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingView.h
index b1ea060e6c9dfa4b01951ef5841a92d23a254577..c56e9fa5eefbc0434170b4040820ee808ca92a34 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingView.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IALCPeakFittingView.h
@@ -14,113 +14,113 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-  /** IALCPeakFittingView : Interface for ALC Peak Fitting step view.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** IALCPeakFittingView : Interface for ALC Peak Fitting step view.
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class MANTIDQT_CUSTOMINTERFACES_DLL IALCPeakFittingView : public QObject
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MANTIDQT_CUSTOMINTERFACES_DLL IALCPeakFittingView : public QObject {
+  Q_OBJECT
 
-    /// @return If index empty - total function, otherwise - function at index
-    virtual IFunction_const_sptr function(QString index) const = 0;
+public:
+  /// @return If index empty - total function, otherwise - function at index
+  virtual IFunction_const_sptr function(QString index) const = 0;
 
-    /// @return Index of the function currently seleted in the Function Browser
-    virtual boost::optional<QString> currentFunctionIndex() const = 0;
+  /// @return Index of the function currently seleted in the Function Browser
+  virtual boost::optional<QString> currentFunctionIndex() const = 0;
 
-    /// @return A peak currently represented by the peak picker
-    virtual IPeakFunction_const_sptr peakPicker() const = 0;
+  /// @return A peak currently represented by the peak picker
+  virtual IPeakFunction_const_sptr peakPicker() const = 0;
 
-  public slots:
-    /// Performs any necessary initialization
-    virtual void initialize() = 0;
+public slots:
+  /// Performs any necessary initialization
+  virtual void initialize() = 0;
 
-    /// Update the data curve displayed
-    /// @param data :: New curve data
-    /// @param errors :: New curve errors
-    virtual void setDataCurve(const QwtData &data,
-                              const std::vector<double> &errors) = 0;
+  /// Update the data curve displayed
+  /// @param data :: New curve data
+  /// @param errors :: New curve errors
+  virtual void setDataCurve(const QwtData &data,
+                            const std::vector<double> &errors) = 0;
 
-    /// Update the fitted curve displayed
-    /// @param data :: New curve data
-    virtual void setFittedCurve(const QwtData& data) = 0;
+  /// Update the fitted curve displayed
+  /// @param data :: New curve data
+  virtual void setFittedCurve(const QwtData &data) = 0;
 
-    /// Set function displayed in Function Browser
-    /// @param newFunction :: New function to display
-    virtual void setFunction(const IFunction_const_sptr& newFunction) = 0;
+  /// Set function displayed in Function Browser
+  /// @param newFunction :: New function to display
+  virtual void setFunction(const IFunction_const_sptr &newFunction) = 0;
 
-    /// Update a single parameter in Function Browser
-    /// @param funcIndex :: Index of the function where to update parameter
-    /// @param paramName :: Name of the parameter to udpate
-    /// @param value :: New parameter value
-    virtual void setParameter(const QString& funcIndex, const QString& paramName, double value) = 0;
+  /// Update a single parameter in Function Browser
+  /// @param funcIndex :: Index of the function where to update parameter
+  /// @param paramName :: Name of the parameter to udpate
+  /// @param value :: New parameter value
+  virtual void setParameter(const QString &funcIndex, const QString &paramName,
+                            double value) = 0;
 
-    /// Enabled/disable PeakPicker on the plot
-    /// @param enabled :: New enabled status
-    virtual void setPeakPickerEnabled(bool enabled) = 0;
+  /// Enabled/disable PeakPicker on the plot
+  /// @param enabled :: New enabled status
+  virtual void setPeakPickerEnabled(bool enabled) = 0;
 
-    /// Resize/move PeakPicker so that it represents specified peak
-    /// @param peak :: A new peak to represent
-    virtual void setPeakPicker(const IPeakFunction_const_sptr& peak) = 0;
+  /// Resize/move PeakPicker so that it represents specified peak
+  /// @param peak :: A new peak to represent
+  virtual void setPeakPicker(const IPeakFunction_const_sptr &peak) = 0;
 
-    /**
-     * Pops-up an error box
-     * @param message :: Error message to display
-     */
-    virtual void displayError(const QString& message) = 0;
+  /**
+   * Pops-up an error box
+   * @param message :: Error message to display
+   */
+  virtual void displayError(const QString &message) = 0;
 
-    /// Opens the Mantid Wiki web page
-    virtual void help() = 0;
+  /// Opens the Mantid Wiki web page
+  virtual void help() = 0;
 
-    /// Emits signal
-    virtual void plotGuess() = 0;
+  /// Emits signal
+  virtual void plotGuess() = 0;
 
-    /// Changes button state
-    virtual void changePlotGuessState(bool plotted) = 0;
+  /// Changes button state
+  virtual void changePlotGuessState(bool plotted) = 0;
 
-  signals:
-    /// Request to perform peak fitting
-    void fitRequested();
+signals:
+  /// Request to perform peak fitting
+  void fitRequested();
 
-    /// Currently selected function in Function Browser has changed
-    void currentFunctionChanged();
+  /// Currently selected function in Function Browser has changed
+  void currentFunctionChanged();
 
-    /// PeakPicker was resized/moved _by user_ (not thrown if changed programmatically)
-    void peakPickerChanged();
+  /// PeakPicker was resized/moved _by user_ (not thrown if changed
+  /// programmatically)
+  void peakPickerChanged();
 
-    /// Parameter value is changed in the Function Browser _either by user or programmatically_
-    void parameterChanged(const QString &funcIndex, const QString &paramName);
+  /// Parameter value is changed in the Function Browser _either by user or
+  /// programmatically_
+  void parameterChanged(const QString &funcIndex, const QString &paramName);
 
-    /// Request to plot guess
-    void plotGuessClicked();
-  };
+  /// Request to plot guess
+  void plotGuessClicked();
+};
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_IALCPEAKFITTINGVIEW_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_IALCPEAKFITTINGVIEW_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IO_MuonGrouping.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IO_MuonGrouping.h
index 3286b5455770b65c9b3a808481fcca7294820569..f511478e064fde4a7da4e2d94d3782601804e7d2 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IO_MuonGrouping.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/IO_MuonGrouping.h
@@ -8,12 +8,9 @@
 #include "MantidAPI/GroupingLoader.h"
 #include "MantidQtCustomInterfaces/DllConfig.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace Muon
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace Muon {
 
 /**
 This is a collection of helper functions for MuonAnalysis.h. In particular
@@ -79,4 +76,4 @@ private:
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MUONANALYSIS_IO_GROUPING_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MUONANALYSIS_IO_GROUPING_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysis.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysis.h
index b48b7c35302791cc5a2a06b2bde37290c3a31c80..054f1e2b2630d5888928455e973d78f3c99ac54a 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysis.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysis.h
@@ -20,48 +20,46 @@
 
 #include <map>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 using namespace Mantid;
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 using namespace Mantid::Geometry;
 
-namespace Muon
-{
-  // Tab classes
-  class MuonAnalysisOptionTab;
-  class MuonAnalysisFitDataTab;
-  class MuonAnalysisResultTableTab;
-
-  struct LoadResult {
-    Workspace_sptr loadedWorkspace;
-    Workspace_sptr loadedGrouping;
-    Workspace_sptr loadedDeadTimes;
-    std::string mainFieldDirection;
-    double timeZero;
-    double firstGoodData;
-    std::string label;
-  };
-
-  struct GroupResult {
-    bool usedExistGrouping;
-    boost::shared_ptr<Mantid::API::Grouping> groupingUsed;
-  };
+namespace Muon {
+// Tab classes
+class MuonAnalysisOptionTab;
+class MuonAnalysisFitDataTab;
+class MuonAnalysisResultTableTab;
+
+struct LoadResult {
+  Workspace_sptr loadedWorkspace;
+  Workspace_sptr loadedGrouping;
+  Workspace_sptr loadedDeadTimes;
+  std::string mainFieldDirection;
+  double timeZero;
+  double firstGoodData;
+  std::string label;
+};
+
+struct GroupResult {
+  bool usedExistGrouping;
+  boost::shared_ptr<Mantid::API::Grouping> groupingUsed;
+};
 }
 
 using namespace Muon;
 
-/** 
+/**
 This is the main class for the MuonAnalysis interface
-see <http://www.mantidproject.org/MuonAnalysis>.    
+see <http://www.mantidproject.org/MuonAnalysis>.
 
 @author Anders Markvardsen, ISIS, RAL
 
-Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -79,12 +77,10 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-
-class MuonAnalysis : public MantidQt::API::UserSubWindow
-{
+class MuonAnalysis : public MantidQt::API::UserSubWindow {
   Q_OBJECT
 
 public:
@@ -105,13 +101,14 @@ public:
 
 signals:
   /// Request to hide/show Mantid toolbars
-  void setToolbarsHidden(bool isHidden); 
+  void setToolbarsHidden(bool isHidden);
 
 private slots:
   /// Guess Alpha clicked
   void guessAlphaClicked();
 
-  /// Checks whether two specified periods are equal and, if they are, sets second one to None
+  /// Checks whether two specified periods are equal and, if they are, sets
+  /// second one to None
   void checkForEqualPeriods();
 
   /// Input file changed in MWRunFiles widget
@@ -151,10 +148,10 @@ private slots:
   void runLoadGroupButton();
 
   /// Clear grouping button
-  void runClearGroupingButton(); 
+  void runClearGroupingButton();
 
   /// User select instrument
-  void userSelectInstrument(const QString& prefix);
+  void userSelectInstrument(const QString &prefix);
 
   /// Hide/show MantidPlot toolbars
   void doSetToolbarsHidden(bool hidden);
@@ -171,7 +168,8 @@ private slots:
   /// Link to the wiki for the grouping tab.
   void muonAnalysisHelpGroupingClicked();
 
-  /// Check to see if the user want to append the previous run and set accordingly
+  /// Check to see if the user want to append the previous run and set
+  /// accordingly
   void checkAppendingPreviousRun();
 
   /// Check to see if the user want to append the next run and set accordingly
@@ -189,10 +187,12 @@ private slots:
   /// Update the plot based on changes on the grouping options tab
   void groupTabUpdatePlot();
 
-  /// Sets plot type combo box on the Home tab to the same value as the one under Group Table
+  /// Sets plot type combo box on the Home tab to the same value as the one
+  /// under Group Table
   void syncGroupTablePlotTypeWithHome();
 
-  /// Updates the style of the current plot according to actual parameters on settings tab.
+  /// Updates the style of the current plot according to actual parameters on
+  /// settings tab.
   void updateCurrentPlotStyle();
 
   /// Checks whether plots should be auto-updated when some settings change.
@@ -202,10 +202,10 @@ private slots:
   bool isOverwriteEnabled();
 
   /// Checks if the plot for the workspace does exist.
-  bool plotExists(const QString& wsName);
+  bool plotExists(const QString &wsName);
 
   /// Enable PP tool for the plot of the given WS
-  void selectMultiPeak(const QString& wsName);
+  void selectMultiPeak(const QString &wsName);
 
   /// Disable tools for all the graphs within MantidPlot
   void disableAllTools();
@@ -222,13 +222,16 @@ private slots:
   /// Auto-update the plot after user has changed dead time correction type.
   void deadTimeTypeAutoUpdate(int choice);
 
-  /// Change to the dead time file, make sure graph is updated next time it is plotted.
+  /// Change to the dead time file, make sure graph is updated next time it is
+  /// plotted.
   void deadTimeFileSelected();
 
-  /// Updates the enabled-state and value of Time Zero using "auto" check-box state
+  /// Updates the enabled-state and value of Time Zero using "auto" check-box
+  /// state
   void setTimeZeroState(int checkBoxState = -1);
 
-  /// Updates the enabled-state and value of First Good Data using "auto" check-box state
+  /// Updates the enabled-state and value of First Good Data using "auto"
+  /// check-box state
   void setFirstGoodDataState(int checkBoxState = -1);
 
   /// Saves the value of the widget which called the slot
@@ -244,10 +247,9 @@ private slots:
   void openDirectoryDialog();
 
 private:
- 
   /// Types of entities we are dealing with
   enum ItemType { Pair, Group };
-  
+
   /// Possible plot types users might request
   enum PlotType { Asymmetry, Counts, Logarithm };
 
@@ -264,7 +266,7 @@ private:
   void startUpLook();
 
   /// Change the connected data name
-  void setCurrentDataName(const QString& name);
+  void setCurrentDataName(const QString &name);
 
   /// Executed when interface gets hidden or closed
   void hideEvent(QHideEvent *e) override;
@@ -273,10 +275,10 @@ private:
   void showEvent(QShowEvent *e) override;
 
   /// Input file changed - update GUI accordingly
-  void inputFileChanged(const QStringList& filenames);
+  void inputFileChanged(const QStringList &filenames);
 
   /// Loads the given list of files
-  boost::shared_ptr<LoadResult> load(const QStringList& files) const;
+  boost::shared_ptr<LoadResult> load(const QStringList &files) const;
 
   /// Get grouping for the loaded workspace
   boost::shared_ptr<GroupResult>
@@ -288,18 +290,19 @@ private:
   /// is grouping set
   bool isGroupingSet() const;
 
-  /// Creates workspace for specified group/pair and plots it 
+  /// Creates workspace for specified group/pair and plots it
   void plotItem(ItemType itemType, int tableRow, PlotType plotType);
 
   /// Creates workspace ready for analysis and plotting
   Workspace_sptr createAnalysisWorkspace(ItemType itemType, int tableRow,
                                          PlotType type, bool isRaw = false);
 
-  /// Returns PlotType as chosen using given selector 
-  PlotType parsePlotType(QComboBox* selector);
+  /// Returns PlotType as chosen using given selector
+  PlotType parsePlotType(QComboBox *selector);
 
-  /// Finds a name for new analysis workspace 
-  std::string getNewAnalysisWSName(ItemType itemType, int tableRow, PlotType plotType);
+  /// Finds a name for new analysis workspace
+  std::string getNewAnalysisWSName(ItemType itemType, int tableRow,
+                                   PlotType plotType);
 
   /// Update front anc pair combo box
   void updateFrontAndCombo();
@@ -308,7 +311,7 @@ private:
   void updatePeriodWidgets(size_t numPeriods);
 
   /// Calculate number of detectors from string of type 1-3, 5, 10-15
-  int numOfDetectors(const std::string& str) const;
+  int numOfDetectors(const std::string &str) const;
 
   /// Clear tables and front combo box
   void clearTablesAndCombo();
@@ -316,8 +319,9 @@ private:
   /// Clear run info and loaded run
   void clearLoadedRun();
 
-  /// Deletes a workspace _or_ a workspace group with the given name, if one exists
-  void deleteWorkspaceIfExists(const std::string& wsName);
+  /// Deletes a workspace _or_ a workspace group with the given name, if one
+  /// exists
+  void deleteWorkspaceIfExists(const std::string &wsName);
 
   /// Return number of pairs
   int numPairs();
@@ -329,7 +333,7 @@ private:
   std::string deadTimeFilename() const;
 
   /// Loads dead time table (group of tables) from the file.
-  Workspace_sptr loadDeadTimes(const std::string& filename) const;
+  Workspace_sptr loadDeadTimes(const std::string &filename) const;
 
   /// Convert dead times workspace to table workspace
   ITableWorkspace_sptr deadTimesToTable(const Workspace_sptr &deadTimes) const;
@@ -338,15 +342,17 @@ private:
   ITableWorkspace_sptr
   getDeadTimeCorrection(boost::shared_ptr<LoadResult> loadResult) const;
 
-  /// Creates and algorithm with all the properties set according to widget values on the interface
+  /// Creates and algorithm with all the properties set according to widget
+  /// values on the interface
   Algorithm_sptr createLoadAlgorithm();
 
   /// Plots specific WS spectrum (used by plotPair and plotGroup)
-  void plotSpectrum(const QString& wsName, bool logScale = false);
+  void plotSpectrum(const QString &wsName, bool logScale = false);
 
-  /// Get current plot style parameters. wsName and wsIndex are used to get default values if 
+  /// Get current plot style parameters. wsName and wsIndex are used to get
+  /// default values if
   /// something is not specified
-  QMap<QString, QString> getPlotStyleParams(const QString& wsName);
+  QMap<QString, QString> getPlotStyleParams(const QString &wsName);
 
   /// get period labels
   std::string getPeriodLabels() const;
@@ -379,12 +385,12 @@ private:
   int m_pairTableRowInFocus;
 
   /// Widget of the current tab
-  QWidget* m_currentTab;
+  QWidget *m_currentTab;
 
-  /// used to test that a new filename has been entered 
+  /// used to test that a new filename has been entered
   QStringList m_previousFilenames;
 
-  /// List of current group names 
+  /// List of current group names
   std::vector<std::string> m_groupNames;
 
   /// Deal with input file changes.
@@ -402,11 +408,11 @@ private:
   /// tell which group is in which row
   std::vector<int> m_groupToRow;
 
-  /// Return the group-number for the group in a row. 
+  /// Return the group-number for the group in a row.
   /// Return -1 if invalid group in row
   int getGroupNumberFromRow(int row);
 
-  /// Return the pair-number for the pair in a row. 
+  /// Return the pair-number for the pair in a row.
   /// Return -1 if invalid pair in row
   int getPairNumberFromRow(int row);
 
@@ -422,7 +428,8 @@ private:
   /// time zero returned in ms
   double timeZero();
 
-  /// Returns params string which can be passed to Rebin, according to what user specified
+  /// Returns params string which can be passed to Rebin, according to what user
+  /// specified
   std::string rebinParams(Workspace_sptr wsForRebin);
 
   /// title of run
@@ -437,7 +444,8 @@ private:
   /// Flag to indicate that grouping table is being updated
   bool m_updatingGrouping;
 
-  /// Boolean to show when data has been loaded. (Can't auto-update data that hasn't been loaded)
+  /// Boolean to show when data has been loaded. (Can't auto-update data that
+  /// hasn't been loaded)
   bool m_loaded;
 
   /// If the dead times have changed.
@@ -447,7 +455,7 @@ private:
   QString m_textToDisplay;
 
   /// Load auto saved values
-  void loadAutoSavedValues(const QString& group);
+  void loadAutoSavedValues(const QString &group);
 
   /// connect the settings for the fit function to their respective slots
   void loadFittings();
@@ -458,11 +466,14 @@ private:
   /// change and load the run depending on the value passed as a parameter
   void changeRun(int amountToChange);
 
-  /// Separate the muon file. The current File will remove the path (i.e MUSR002413.nxs)
-  void separateMuonFile(QString & filePath, QString & currentFile, QString & run, int & runSize);
+  /// Separate the muon file. The current File will remove the path (i.e
+  /// MUSR002413.nxs)
+  void separateMuonFile(QString &filePath, QString &currentFile, QString &run,
+                        int &runSize);
 
-  /// Include the 0's fromt eh beginning of the file that were lost in conversion from QString to int
-  void getFullCode(int originalSize, QString & run);
+  /// Include the 0's fromt eh beginning of the file that were lost in
+  /// conversion from QString to int
+  void getFullCode(int originalSize, QString &run);
 
   /// Setup the signals for updating
   void connectAutoUpdate();
@@ -471,16 +482,17 @@ private:
   void connectAutoSave();
 
   /// Saves the value of the widget which called the slot
-  void loadWidgetValue(QWidget* target, const QVariant& defaultValue);
+  void loadWidgetValue(QWidget *target, const QVariant &defaultValue);
 
   /// Groups the workspace
-  Workspace_sptr groupWorkspace(const std::string& wsName, const std::string& groupingName) const;
+  Workspace_sptr groupWorkspace(const std::string &wsName,
+                                const std::string &groupingName) const;
 
   /// Groups loaded workspace using information from Grouping Options tab
   void groupLoadedWorkspace();
 
   /// Parses grouping information from the UI table.
-  ITableWorkspace_sptr parseGrouping();  
+  ITableWorkspace_sptr parseGrouping();
 
   /// When no data loaded set various buttons etc to inactive
   void noDataAvailable();
@@ -492,11 +504,12 @@ private:
   void fillGroupingTable(const Mantid::API::Grouping &grouping);
 
   /// handles option tab work
-  MantidQt::CustomInterfaces::Muon::MuonAnalysisOptionTab* m_optionTab;
+  MantidQt::CustomInterfaces::Muon::MuonAnalysisOptionTab *m_optionTab;
   /// handles fit data work
-  MantidQt::CustomInterfaces::Muon::MuonAnalysisFitDataTab* m_fitDataTab;
+  MantidQt::CustomInterfaces::Muon::MuonAnalysisFitDataTab *m_fitDataTab;
   /// handles result table tab work
-  MantidQt::CustomInterfaces::Muon::MuonAnalysisResultTableTab* m_resultTableTab;
+  MantidQt::CustomInterfaces::Muon::MuonAnalysisResultTableTab *
+      m_resultTableTab;
 
   /// Time Zero as loaded from Data file
   double m_dataTimeZero;
@@ -528,4 +541,4 @@ private:
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MUONANALYSIS_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MUONANALYSIS_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisFitDataTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisFitDataTab.h
index b8d33819d083ddc837de143f11fa49fb90ef97b7..1cbc19dec42901ef123ec6f81455d0c220d40d02 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisFitDataTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisFitDataTab.h
@@ -10,25 +10,22 @@
 #include "MantidAPI/AnalysisDataService.h"
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 
-namespace Ui
-{
-  class MuonAnalysis;
+namespace Ui {
+class MuonAnalysis;
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace Muon
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace Muon {
 
-/** 
+/**
 This is a Helper class for MuonAnalysis. In particular this helper class deals
-callbacks from the Plot Options tab.    
+callbacks from the Plot Options tab.
 
 @author Robert Whitley, ISIS, RAL
 
-Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -46,20 +43,19 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MuonAnalysisFitDataTab : MantidQt::API::UserSubWindow
-{
- Q_OBJECT
+class MuonAnalysisFitDataTab : MantidQt::API::UserSubWindow {
+  Q_OBJECT
 
 public:
   /// Constructor.
-  MuonAnalysisFitDataTab(Ui::MuonAnalysis& uiForm) : m_uiForm(uiForm) {}
+  MuonAnalysisFitDataTab(Ui::MuonAnalysis &uiForm) : m_uiForm(uiForm) {}
   /// Initialise.
   void init();
   /// Copy the given raw workspace and keep for later.
-  void makeRawWorkspace(const std::string & wsName);
+  void makeRawWorkspace(const std::string &wsName);
 
 signals:
 
@@ -67,7 +63,7 @@ private:
   /// Initialize the layout.
   void initLayout() override{};
   /// Reference to MuonAnalysis form.
-  Ui::MuonAnalysis& m_uiForm;
+  Ui::MuonAnalysis &m_uiForm;
 
 private slots:
   /// Open up the wiki help.
@@ -75,10 +71,8 @@ private slots:
   /// Group all the workspaces made after a fitting.
   void groupFittedWorkspaces(QString workspaceName);
 };
-
-
 }
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MUONANALYSISFITDATATAB_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MUONANALYSISFITDATATAB_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h
index 5fb71eff60b9ab1897f05009911a97ca34d97afc..5e8adb731789871d66f64923c3a80ee3dc49df8d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h
@@ -13,44 +13,48 @@
 #include <QDoubleValidator>
 #include <QLineEdit>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MuonAnalysisHelper
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MuonAnalysisHelper {
 
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
 
 /// Sets double validator for specified field
-MANTIDQT_CUSTOMINTERFACES_DLL void setDoubleValidator(QLineEdit* field, bool allowEmpty = false);
+MANTIDQT_CUSTOMINTERFACES_DLL void setDoubleValidator(QLineEdit *field,
+                                                      bool allowEmpty = false);
 
 /// Returns a first period MatrixWorkspace in a run workspace
-MANTIDQT_CUSTOMINTERFACES_DLL MatrixWorkspace_sptr firstPeriod(Workspace_sptr ws);
+MANTIDQT_CUSTOMINTERFACES_DLL MatrixWorkspace_sptr
+firstPeriod(Workspace_sptr ws);
 
 /// Validates the field and returns the value
-MANTIDQT_CUSTOMINTERFACES_DLL double getValidatedDouble(QLineEdit* field, const QString& defaultValue,
-                                    const QString& valueDescr, Logger& log);
+MANTIDQT_CUSTOMINTERFACES_DLL double
+getValidatedDouble(QLineEdit *field, const QString &defaultValue,
+                   const QString &valueDescr, Logger &log);
 
 /// Returns a number of periods in a run workspace
 MANTIDQT_CUSTOMINTERFACES_DLL size_t numPeriods(Workspace_sptr ws);
 
 /// Print various information about the run
-MANTIDQT_CUSTOMINTERFACES_DLL void printRunInfo(MatrixWorkspace_sptr runWs, std::ostringstream& out);
+MANTIDQT_CUSTOMINTERFACES_DLL void printRunInfo(MatrixWorkspace_sptr runWs,
+                                                std::ostringstream &out);
 
 /// Get a run label for the workspace
-MANTIDQT_CUSTOMINTERFACES_DLL std::string getRunLabel(const Workspace_sptr& ws);
+MANTIDQT_CUSTOMINTERFACES_DLL std::string getRunLabel(const Workspace_sptr &ws);
 
 /// Get a run label for a list of workspaces
-MANTIDQT_CUSTOMINTERFACES_DLL std::string getRunLabel(std::vector<Workspace_sptr> wsList);
+MANTIDQT_CUSTOMINTERFACES_DLL std::string
+getRunLabel(std::vector<Workspace_sptr> wsList);
 
 /// Sums a list of workspaces together
-MANTIDQT_CUSTOMINTERFACES_DLL Workspace_sptr sumWorkspaces(const std::vector<Workspace_sptr>& workspaces);
+MANTIDQT_CUSTOMINTERFACES_DLL Workspace_sptr
+sumWorkspaces(const std::vector<Workspace_sptr> &workspaces);
 
 /// Makes sure the specified workspaces are in specified group
-MANTIDQT_CUSTOMINTERFACES_DLL void groupWorkspaces(const std::string& groupName,
-                                                   const std::vector<std::string>& inputWorkspaces);
+MANTIDQT_CUSTOMINTERFACES_DLL void
+groupWorkspaces(const std::string &groupName,
+                const std::vector<std::string> &inputWorkspaces);
 
 /// Finds runs of consecutive numbers
 MANTIDQT_CUSTOMINTERFACES_DLL std::vector<std::pair<int, int>>
@@ -96,19 +100,19 @@ MANTIDQT_CUSTOMINTERFACES_DLL bool isReloadGroupingNecessary(
  * registered and then on any
  * change, their value is stored using QSettings.
  */
-class MANTIDQT_CUSTOMINTERFACES_DLL WidgetAutoSaver : QObject
-{
+class MANTIDQT_CUSTOMINTERFACES_DLL WidgetAutoSaver : QObject {
   Q_OBJECT
 
 public:
   /// Constructor
-  WidgetAutoSaver(const QString& groupName);
+  WidgetAutoSaver(const QString &groupName);
 
   /// Register new widget for auto-saving
-  void registerWidget(QWidget* widget, const QString& name, QVariant defaultValue);
+  void registerWidget(QWidget *widget, const QString &name,
+                      QVariant defaultValue);
 
   /// Begin new auto-save group
-  void beginGroup(const QString& name);
+  void beginGroup(const QString &name);
 
   /// End current auto-save group
   void endGroup();
@@ -117,55 +121,53 @@ public:
   void setAutoSaveEnabled(bool enabled);
 
   /// Enable/disable auto-saving of the given widget
-  void setAutoSaveEnabled(QWidget* widget, bool enabled);
+  void setAutoSaveEnabled(QWidget *widget, bool enabled);
 
   /// Load the auto-saved (or default) value of all the registered widgets
   void loadWidgetValues();
 
   /// Load the auto-saved (or default) value of the given widget
-  void loadWidgetValue(QWidget* widget);
+  void loadWidgetValue(QWidget *widget);
 
 private slots:
   /// Save the caller value
   void saveWidgetValue();
 
 private:
-  /// Return a signal (which can be used instead of SIGNAL()) which is emmited when given widget is changed
-  const char* changedSignal(QWidget* widget);
+  /// Return a signal (which can be used instead of SIGNAL()) which is emmited
+  /// when given widget is changed
+  const char *changedSignal(QWidget *widget);
 
   /// A list of all the registered widgets
-  QVector<QWidget*> m_registeredWidgets;
+  QVector<QWidget *> m_registeredWidgets;
 
   /// Names of registered widgets
-  QMap<QWidget*, QString> m_widgetNames;
+  QMap<QWidget *, QString> m_widgetNames;
 
   /// Default values of registered widgets
-  QMap<QWidget*, QVariant> m_widgetDefaultValues;
+  QMap<QWidget *, QVariant> m_widgetDefaultValues;
 
   /// Groups of registered widgets
-  QMap<QWidget*, QString> m_widgetGroups;
+  QMap<QWidget *, QString> m_widgetGroups;
 
   /// Settings used to keep track of the groups
   QSettings m_settings;
 };
 
 /// Validator which accepts valid doubles OR empty strings
-class MANTIDQT_CUSTOMINTERFACES_DLL DoubleOrEmptyValidator : public QDoubleValidator
-{
+class MANTIDQT_CUSTOMINTERFACES_DLL DoubleOrEmptyValidator
+    : public QDoubleValidator {
   Q_OBJECT
 
 public:
-
-  DoubleOrEmptyValidator(QObject* parent = NULL)
-    : QDoubleValidator(parent)
-  {}
+  DoubleOrEmptyValidator(QObject *parent = NULL) : QDoubleValidator(parent) {}
 
   // See QValidator
   QValidator::State validate(QString &input, int &pos) const override {
     if (input.isEmpty())
       return QValidator::Acceptable;
     else
-      return QDoubleValidator::validate(input,pos);
+      return QDoubleValidator::validate(input, pos);
   }
 };
 
@@ -173,4 +175,4 @@ public:
 } // namespace CustomInterfaces
 } // namespace Mantid
 
-#endif  /* MANTIDQT_CUSTOMINTERFACES_MUONANALYSISHELPER_H_ */
+#endif /* MANTIDQT_CUSTOMINTERFACES_MUONANALYSISHELPER_H_ */
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisOptionTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisOptionTab.h
index 970123e807d5b9c6be9f4526be883c9de3af03cd..bbbb53bb5f8a1ff8bbdaada8a5762456670e9d53 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisOptionTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisOptionTab.h
@@ -8,22 +8,20 @@
 
 #include "MantidQtCustomInterfaces/Muon/MuonAnalysisHelper.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  using namespace MuonAnalysisHelper;
+namespace MantidQt {
+namespace CustomInterfaces {
+using namespace MuonAnalysisHelper;
 
-namespace Muon
-{
+namespace Muon {
 
-/** 
+/**
 This is a Helper class for MuonAnalysis. In particular this helper class deals
-callbacks from the Plot Options tab.    
+callbacks from the Plot Options tab.
 
 @author Anders Markvardsen, ISIS, RAL
 
-Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -41,12 +39,11 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MuonAnalysisOptionTab : public QWidget
-{
- Q_OBJECT
+class MuonAnalysisOptionTab : public QWidget {
+  Q_OBJECT
 public:
   /// Types of the start time
   enum StartTimeType { FirstGoodData, TimeZero, Custom };
@@ -58,7 +55,7 @@ public:
   enum NewPlotPolicy { NewWindow, PreviousWindow };
 
   /// Constructor
-  MuonAnalysisOptionTab(Ui::MuonAnalysis& uiForm, const QString& settingsGroup);
+  MuonAnalysisOptionTab(Ui::MuonAnalysis &uiForm, const QString &settingsGroup);
 
   /// Initialise the layout of the tab
   void initLayout();
@@ -104,12 +101,12 @@ private:
   static const QString VARIABLE_REBIN_DEFAULT;
 
   /// The Muon Analysis UI file.
-  Ui::MuonAnalysis& m_uiForm;
+  Ui::MuonAnalysis &m_uiForm;
 
   /// Auto-saver for all the widgets
   WidgetAutoSaver m_autoSaver;
 
-private slots:  
+private slots:
   /// Open the Muon Analysis Settings help (Wiki).
   void muonAnalysisHelpSettingsClicked();
 
@@ -122,9 +119,8 @@ private slots:
   /// Run when autoscale check-box state is changed
   void onAutoscaleToggled(bool state);
 };
-
 }
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MUONANALYSISOPTIONTAB_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MUONANALYSISOPTIONTAB_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisResultTableTab.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisResultTableTab.h
index 5ec4946f0288b1dacae763e5cb63105e966c337a..58e5d79557fb3ec0bd84769c041557e52f918cb0 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisResultTableTab.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Muon/MuonAnalysisResultTableTab.h
@@ -7,26 +7,22 @@
 #include "ui_MuonAnalysis.h"
 #include <QTableWidget>
 
-namespace Ui
-{
-  class MuonAnalysis;
+namespace Ui {
+class MuonAnalysis;
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace Muon
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace Muon {
 
-
-/** 
+/**
 This is a Helper class for MuonAnalysis. In particular this helper class deals
-callbacks from the Plot Options tab.    
+callbacks from the Plot Options tab.
 
 @author Robert Whitley, ISIS, RAL
 
-Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -44,21 +40,20 @@ You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://github.com/mantidproject/mantid>
-Code Documentation is available at: <http://doxygen.mantidproject.org>    
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-class MuonAnalysisResultTableTab : public QWidget
-{
- Q_OBJECT
+class MuonAnalysisResultTableTab : public QWidget {
+  Q_OBJECT
 public:
-  MuonAnalysisResultTableTab(Ui::MuonAnalysis& uiForm);
+  MuonAnalysisResultTableTab(Ui::MuonAnalysis &uiForm);
 
   // Refresh the label list and re-populate the tables
   void refresh();
 
 signals:
   /// Emitted to run some (usually simple) Python code
-  void runPythonCode(const QString& code, bool async);
+  void runPythonCode(const QString &code, bool async);
 
 private slots:
   void helpResultsClicked();
@@ -85,35 +80,36 @@ private:
   static const QString RUN_NUMBER_LOG;
 
   /// LessThan function used to sort log names
-  static bool logNameLessThan(const QString& logName1, const QString& logName2);
+  static bool logNameLessThan(const QString &logName1, const QString &logName2);
 
   /**
-   * Retrieve the workspace, checking if it is of the expected type. If workspace with given and name
+   * Retrieve the workspace, checking if it is of the expected type. If
+   * workspace with given and name
    * and type is not found in the ADS - NotFoundError is thrown.
    * @param wsName :: Name of the workspace to retrieve
    * @return Retrieved workspace
    */
   template <typename T>
-  static boost::shared_ptr<T> retrieveWSChecked(const std::string& wsName)
-  {
-    auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<T>(wsName);
+  static boost::shared_ptr<T> retrieveWSChecked(const std::string &wsName) {
+    auto ws =
+        Mantid::API::AnalysisDataService::Instance().retrieveWS<T>(wsName);
 
-    if ( ! ws )
+    if (!ws)
       throw Mantid::Kernel::Exception::NotFoundError("Incorrect type", wsName);
 
     return ws;
   }
 
   /// Returns name of the fitted workspace with WORKSPACE_POSTFIX removed
-  static std::string wsBaseName(const std::string& wsName);
+  static std::string wsBaseName(const std::string &wsName);
 
   /// Does a few basic checks for whether the workspace is a fitted workspace
-  static bool isFittedWs(const std::string& wsName);
+  static bool isFittedWs(const std::string &wsName);
 
   void storeUserSettings();
   void applyUserSettings();
-  void populateLogsAndValues(const QStringList& fittedWsList);
-  void populateFittings(const QStringList& fittedWsList);
+  void populateLogsAndValues(const QStringList &fittedWsList);
+  void populateFittings(const QStringList &fittedWsList);
 
   /// Creates the results table
   void createTable();
@@ -125,33 +121,32 @@ private:
   QStringList getIndividualFitWorkspaces();
 
   /// Returns a list of sequentially fitted workspaces names
-  QStringList getSequentialFitWorkspaces(const QString& label);
+  QStringList getSequentialFitWorkspaces(const QString &label);
 
   /// Returns a list of labels user has made sequential fits for
   QStringList getSequentialFitLabels();
 
-  bool haveSameParameters(const QStringList& wsList);
+  bool haveSameParameters(const QStringList &wsList);
   QStringList getSelectedWs();
   QStringList getSelectedLogs();
   std::string getFileName();
-  QMap<int,int> getWorkspaceColors(const QStringList& wsList);
-  
-  Ui::MuonAnalysis& m_uiForm;
+  QMap<int, int> getWorkspaceColors(const QStringList &wsList);
+
+  Ui::MuonAnalysis &m_uiForm;
   int m_numLogsdisplayed;
-  
-  // Log values for all the fitted workspaces  
-  QMap<QString, QMap<QString, QVariant> > m_logValues;
-  
-  // Saved states of log value check-boxes. Used to remember what user has chosen when
+
+  // Log values for all the fitted workspaces
+  QMap<QString, QMap<QString, QVariant>> m_logValues;
+
+  // Saved states of log value check-boxes. Used to remember what user has
+  // chosen when
   // re-creating the table
   QMap<QString, Qt::CheckState> m_savedLogsState;
 
   QList<QString> m_unselectedFittings;
-
 };
-
 }
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MUONANALYSISRESULTTABLETAB_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MUONANALYSISRESULTTABLETAB_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ParseKeyValueString.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ParseKeyValueString.h
index 0a1bd1f02df2515be13ed2310a0050009937a8dd..f78a322f8b4946eecf29a1bb15e744d61a1b569b 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ParseKeyValueString.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ParseKeyValueString.h
@@ -3,9 +3,11 @@
 
 /** parseKeyValueString
 
-Parses a string in the format `a = 1,b=2, c = "1,2,3,4", d = 5.0, e='a,b,c'` into a map of key/value pairs.
+Parses a string in the format `a = 1,b=2, c = "1,2,3,4", d = 5.0, e='a,b,c'`
+into a map of key/value pairs.
 
-Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -31,13 +33,12 @@ Code Documentation is available at: <http://doxygen.mantidproject.org>
 #include <string>
 #include <map>
 
-
 namespace MantidQt {
-  namespace CustomInterfaces {
-
-    std::map<std::string,std::string> DLLExport parseKeyValueString(const std::string& str);
+namespace CustomInterfaces {
 
-  }
+std::map<std::string, std::string> DLLExport
+parseKeyValueString(const std::string &str);
+}
 }
 
-#endif //MANTID_CUSTOMINTERFACES_PARSEKEYVALUESTRING_H
+#endif // MANTID_CUSTOMINTERFACES_PARSEKEYVALUESTRING_H
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/PrecompiledHeader.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/PrecompiledHeader.h
index e7dfab8e858aa38442bc17555f1cb7d636bd768b..adab264ffb1076c52ec2433ee7c922201dfaf489 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/PrecompiledHeader.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/PrecompiledHeader.h
@@ -11,7 +11,7 @@
 #include <QDialog>
 #include <QString>
 
-//STL
+// STL
 #include <vector>
 #include <map>
 #include <set>
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandAdapter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandAdapter.h
index c5deffa09baebb9a12271978f958a8c92178dfa6..16fcfbc15ef4135b0843b87f977fbd92669a4fee 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandAdapter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandAdapter.h
@@ -15,7 +15,8 @@ using DataProcessorCommand_uptr = std::unique_ptr<DataProcessorCommand>;
 
 /** @class DataProcessorCommandAdapter
 
-DataProcessorCommandAdapter is an adapter that allows DataProcessorCommands to be treated as
+DataProcessorCommandAdapter is an adapter that allows DataProcessorCommands to
+be treated as
 QObjects for signals.
 
 Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
@@ -54,8 +55,9 @@ public:
       // Add the actions
       auto &child = m_adaptee->getChild();
       for (auto &ch : child) {
-        m_adapter.push_back(Mantid::Kernel::make_unique<DataProcessorCommandAdapter>(
-            submenu, std::move(ch)));
+        m_adapter.push_back(
+            Mantid::Kernel::make_unique<DataProcessorCommandAdapter>(
+                submenu, std::move(ch)));
       }
     } else {
       // We are dealing with an action
@@ -77,7 +79,8 @@ private:
   std::vector<std::unique_ptr<DataProcessorCommandAdapter>> m_adapter;
 };
 
-typedef std::unique_ptr<DataProcessorCommandAdapter> DataProcessorCommandAdapter_uptr;
+typedef std::unique_ptr<DataProcessorCommandAdapter>
+    DataProcessorCommandAdapter_uptr;
 }
 }
 #endif /*MANTID_CUSTOMINTERFACES_DATAPROCESSORCOMMANDADAPTER_H*/
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandBase.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandBase.h
index eb32382f95b2d21aa844864a73c2c57ad22cb405..69dbd8d07e8c1a1122c41b5f75117a44212a6e3d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandBase.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorCommandBase.h
@@ -40,6 +40,7 @@ public:
       throw std::invalid_argument("Invalid abstract presenter");
     }
   };
+
 protected:
   DataProcessorPresenter *const m_presenter;
 };
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorGenerateNotebook.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorGenerateNotebook.h
index 5fdac8538b7ae5e191109e0f289da9c4c30d5c78..fbb7aac55879831af3c6fbac9fa5c67140680f1a 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorGenerateNotebook.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorGenerateNotebook.h
@@ -44,8 +44,8 @@
 namespace MantidQt {
 namespace CustomInterfaces {
 
-std::vector<std::string>
-    DLLExport splitByCommas(const std::string &names_string);
+std::vector<std::string> DLLExport
+splitByCommas(const std::string &names_string);
 
 std::string DLLExport plot1DString(const std::vector<std::string> &ws_names);
 
@@ -96,13 +96,12 @@ plusString(const std::string &input_name, const std::string &output_name,
            const DataProcessorPreprocessingAlgorithm &preprocessor,
            const std::string &options);
 
-boost::tuple<std::string, std::string>
-    DLLExport loadRunString(const std::string &run,
-                            const std::string &instrument,
-                            const std::string &prefix);
+boost::tuple<std::string, std::string> DLLExport
+loadRunString(const std::string &run, const std::string &instrument,
+              const std::string &prefix);
 
-std::string DLLExport completeOutputProperties(const std::string &algName,
-                                               size_t currentProperties);
+std::string DLLExport
+completeOutputProperties(const std::string &algName, size_t currentProperties);
 
 class DLLExport DataProcessorGenerateNotebook {
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorPresenter.h
index d0e5cbee7cb6a03ac0f162d09bea745fbb25d2fb..8b32d1eb6dfb258fe61c911a9639e142d95c64f9 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorPresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorPresenter.h
@@ -84,7 +84,7 @@ public:
   virtual std::vector<DataProcessorCommand_uptr> publishCommands() = 0;
   virtual void accept(WorkspaceReceiver *workspaceReceiver) = 0;
   virtual void acceptViews(DataProcessorView *tableView,
-                          ProgressableView *progressView) = 0;
+                           ProgressableView *progressView) = 0;
   virtual void setModel(std::string name) = 0;
 };
 }
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorVectorString.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorVectorString.h
index a33a368d5b668dc951849872c484aec60cf8cc20..5c3bee8c983ff3c8323c02beee758685c08fee00 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorVectorString.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/DataProcessorVectorString.h
@@ -26,47 +26,44 @@
 */
 
 namespace MantidQt {
-  namespace CustomInterfaces {
+namespace CustomInterfaces {
 
-    /**
-    Create string of comma separated list of values from a vector
-    @param param_vec : vector of values
-    @return string of comma separated list of values
-    */
-    template<typename T, typename A>
-    std::string vectorString(const std::vector<T,A> &param_vec)
-    {
-      std::ostringstream vector_string;
-      const char* separator = "";
-      for(auto paramIt = param_vec.begin(); paramIt != param_vec.end(); ++paramIt)
-      {
-        vector_string << separator << *paramIt;
-        separator = ", ";
-      }
-
-      return vector_string.str();
-    }
+/**
+Create string of comma separated list of values from a vector
+@param param_vec : vector of values
+@return string of comma separated list of values
+*/
+template <typename T, typename A>
+std::string vectorString(const std::vector<T, A> &param_vec) {
+  std::ostringstream vector_string;
+  const char *separator = "";
+  for (auto paramIt = param_vec.begin(); paramIt != param_vec.end();
+       ++paramIt) {
+    vector_string << separator << *paramIt;
+    separator = ", ";
+  }
 
-    /**
-    Create string of comma separated list of parameter values from a vector
-    @param param_name : name of the parameter we are creating a list of
-    @param param_vec : vector of parameter values
-    @return string of comma separated list of parameter values
-    */
-    template<typename T, typename A>
-    std::string vectorParamString(const std::string & param_name, const std::vector<T,A> &param_vec)
-    {
-      std::ostringstream param_vector_string;
+  return vector_string.str();
+}
 
-      param_vector_string << param_name << " = '";
-      param_vector_string << vectorString(param_vec);
-      param_vector_string << "'";
+/**
+Create string of comma separated list of parameter values from a vector
+@param param_name : name of the parameter we are creating a list of
+@param param_vec : vector of parameter values
+@return string of comma separated list of parameter values
+*/
+template <typename T, typename A>
+std::string vectorParamString(const std::string &param_name,
+                              const std::vector<T, A> &param_vec) {
+  std::ostringstream param_vector_string;
 
-      return param_vector_string.str();
-    }
+  param_vector_string << param_name << " = '";
+  param_vector_string << vectorString(param_vec);
+  param_vector_string << "'";
 
-  }
+  return param_vector_string.str();
+}
+}
 }
 
-
-#endif //MANTID_CUSTOMINTERFACES_DATAPROCESSORVECTORSTRING_H
+#endif // MANTID_CUSTOMINTERFACES_DATAPROCESSORVECTORSTRING_H
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflSearcher.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflSearcher.h
index 9ca40bae6b65de7ee69338283de198671a74945c..8d3e1f08462e0e7f4890a5a6abf97827fc800c47 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflSearcher.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflSearcher.h
@@ -6,41 +6,39 @@
 #include "MantidQtCustomInterfaces/Reflectometry/IReflPresenter.h"
 #include "MantidAPI/ITableWorkspace_fwd.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** @class IReflSearcher
-
-    IReflSearcher is an interface for search implementations used by IReflPresenter implementations.
-
-    Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class IReflSearcher
-    {
-    public:
-      virtual ~IReflSearcher() {};
-      virtual Mantid::API::ITableWorkspace_sptr
-      search(const std::string &text) = 0;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/** @class IReflSearcher
+
+IReflSearcher is an interface for search implementations used by IReflPresenter
+implementations.
+
+Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class IReflSearcher {
+public:
+  virtual ~IReflSearcher(){};
+  virtual Mantid::API::ITableWorkspace_sptr search(const std::string &text) = 0;
+};
+}
 }
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/MeasurementItem.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/MeasurementItem.h
index d6672e8d416d973fc62e09f8171ca2f69b1447d5..25576f0180bc74aa98fe42594018b60e873ca38a 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/MeasurementItem.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/MeasurementItem.h
@@ -37,8 +37,8 @@ public:
 
   /// Constructor
   MeasurementItem(const IDType &measurementItemId, const IDType &subId,
-              const std::string &label, const std::string &type,
-              const double angle, const std::string &run);
+                  const std::string &label, const std::string &type,
+                  const double angle, const std::string &run);
 
   /// Constructional method
   static MeasurementItem InvalidMeasurementItem(const std::string &why);
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflCatalogSearcher.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflCatalogSearcher.h
index 84beae2e32f81f0e2e44a354182539036f2c72f8..c9dd04e0eb712a9c402514b1097c5f18120d1521 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflCatalogSearcher.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflCatalogSearcher.h
@@ -3,41 +3,39 @@
 
 #include "MantidQtCustomInterfaces/Reflectometry/IReflSearcher.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** @class ReflCatalogSearcher
-
-    ReflCatalogSearcher implements IReflSearcher to provide ICAT search functionality.
-
-    Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class ReflCatalogSearcher : public IReflSearcher
-    {
-    public:
-      ~ReflCatalogSearcher() override{};
-      Mantid::API::ITableWorkspace_sptr
-      search(const std::string &text) override;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/** @class ReflCatalogSearcher
+
+ReflCatalogSearcher implements IReflSearcher to provide ICAT search
+functionality.
+
+Copyright &copy; 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class ReflCatalogSearcher : public IReflSearcher {
+public:
+  ~ReflCatalogSearcher() override{};
+  Mantid::API::ITableWorkspace_sptr search(const std::string &text) override;
+};
+}
 }
 #endif
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMeasurementItemSource.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMeasurementItemSource.h
index a38355a73204613cc522e62f57017eb2aca27eed..48c915021999f0afc7be74dac759e2af6832ab33 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMeasurementItemSource.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMeasurementItemSource.h
@@ -8,7 +8,6 @@
 namespace MantidQt {
 namespace CustomInterfaces {
 
-
 /** ReflMeasurementSource : Repository pattern abstracting data mapping from
  domain. Specifically for accessing
  * measurement information from some data map/repository.
@@ -38,7 +37,7 @@ class MANTIDQT_CUSTOMINTERFACES_DLL ReflMeasurementItemSource {
 public:
   /// Get the measurement somehow using location, or fuzzy path
   virtual MeasurementItem obtain(const std::string &definedPath,
-                             const std::string &fuzzyName) const = 0;
+                                 const std::string &fuzzyName) const = 0;
   /// Virtual destructor
   virtual ReflMeasurementItemSource *clone() const = 0;
   /// Destructor
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflNexusMeasurementItemSource.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflNexusMeasurementItemSource.h
index d70c458a7486fef0f9841c1f40b6bfd86b96559c..f756a71346278015b852c55b30f08efd4d4434e1 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflNexusMeasurementItemSource.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflNexusMeasurementItemSource.h
@@ -10,7 +10,8 @@
 namespace MantidQt {
 namespace CustomInterfaces {
 
-/** ReflNexusMeasurementSource : ReflMeasurementSource repository realization that
+/** ReflNexusMeasurementSource : ReflMeasurementSource repository realization
+  that
   fetches data out off disk using load algorithms and Nexus formats.
 
   Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
@@ -34,7 +35,8 @@ namespace CustomInterfaces {
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MANTIDQT_CUSTOMINTERFACES_DLL ReflNexusMeasurementItemSource : public ReflMeasurementItemSource {
+class MANTIDQT_CUSTOMINTERFACES_DLL ReflNexusMeasurementItemSource
+    : public ReflMeasurementItemSource {
 public:
   ReflNexusMeasurementItemSource();
   MeasurementItem obtain(const std::string &definedPath,
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflTableSchema.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflTableSchema.h
index abbca73e88ac4d23aa3b3e9ef48de5db4fbc41b3..c07f004aaebd59ddb9419dd973ae41308ab990b7 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflTableSchema.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflTableSchema.h
@@ -7,7 +7,7 @@
 
 namespace MantidQt {
 namespace CustomInterfaces {
-namespace ReflTableSchema{
+namespace ReflTableSchema {
 
 typedef std::string ColumnNameType;
 typedef std::string ColumnValueType;
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/TransferResults.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/TransferResults.h
index fba4954d39b647e75a9b2592d6c4ed10c0a4c0df..c1768018301b969dc15e6f65c41bf96a4e89afb9 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/TransferResults.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/TransferResults.h
@@ -10,25 +10,23 @@ namespace MantidQt {
 namespace CustomInterfaces {
 class MANTIDQT_CUSTOMINTERFACES_DLL TransferResults {
 public:
+  using COLUMN_NAME_TYPE = std::string;
+  using COLUMN_VALUE_TYPE = std::string;
 
-    using COLUMN_NAME_TYPE = std::string;
-    using COLUMN_VALUE_TYPE = std::string;
+  using COLUMN_MAP_TYPE = std::map<COLUMN_NAME_TYPE, COLUMN_VALUE_TYPE>;
 
-    using COLUMN_MAP_TYPE = std::map<COLUMN_NAME_TYPE, COLUMN_VALUE_TYPE>;
+  TransferResults(std::vector<COLUMN_MAP_TYPE> transferRuns,
+                  std::vector<COLUMN_MAP_TYPE> errorRuns);
 
-    TransferResults(std::vector<COLUMN_MAP_TYPE> transferRuns,
-        std::vector<COLUMN_MAP_TYPE> errorRuns);
-    
-    std::vector<COLUMN_MAP_TYPE> getTransferRuns();
-    std::vector<COLUMN_MAP_TYPE> getErrorRuns();
+  std::vector<COLUMN_MAP_TYPE> getTransferRuns();
+  std::vector<COLUMN_MAP_TYPE> getErrorRuns();
 
-    void addTransferRow(const COLUMN_MAP_TYPE& row);
-    void addErrorRow(COLUMN_NAME_TYPE id, COLUMN_VALUE_TYPE error);
+  void addTransferRow(const COLUMN_MAP_TYPE &row);
+  void addErrorRow(COLUMN_NAME_TYPE id, COLUMN_VALUE_TYPE error);
 
-    std::vector<COLUMN_MAP_TYPE> m_transferRuns;
-    std::vector<COLUMN_MAP_TYPE> m_errorRuns;
+  std::vector<COLUMN_MAP_TYPE> m_transferRuns;
+  std::vector<COLUMN_MAP_TYPE> m_errorRuns;
 };
-
 }
 }
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
index 67617bd6861f90576cf85f55260a94d09ac7d930..985437d2f623f3b00f87d9ad76cacbd5ec788c93 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
@@ -8,13 +8,10 @@
 #include <Poco/NObserver.h>
 #include <QString>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class SANSAddFiles : public MantidQt::API::UserSubWindow
-{
+class SANSAddFiles : public MantidQt::API::UserSubWindow {
   Q_OBJECT
 public:
   /// Default Constructor
@@ -23,22 +20,24 @@ public:
   ~SANSAddFiles() override;
 
 private:
-  ///set to point to the object that has the Add Files controls
+  /// set to point to the object that has the Add Files controls
   Ui::SANSRunWindow *m_SANSForm;
-  //set to a pointer to the parent form
+  // set to a pointer to the parent form
   QWidget *parForm;
-  //set to true when execution of the python scripts starts and false on completion
+  // set to true when execution of the python scripts starts and false on
+  // completion
   bool m_pythonRunning;
-  //this is set to the extensions supported by the Load algorithm
+  // this is set to the extensions supported by the Load algorithm
   std::vector<std::string> m_exts;
-  //this is set to the extensions supported by LoadRaw
+  // this is set to the extensions supported by LoadRaw
   std::vector<std::string> m_rawExts;
-  ///the directory to which files will be saved
+  /// the directory to which files will be saved
   QString m_outDir;
-  ///The text that goes into the beginning of the output directory message
+  /// The text that goes into the beginning of the output directory message
   static const QString OUT_MSG;
 
-  Poco::NObserver<SANSAddFiles, Mantid::Kernel::ConfigValChangeNotification> m_newOutDir;
+  Poco::NObserver<SANSAddFiles, Mantid::Kernel::ConfigValChangeNotification>
+      m_newOutDir;
 
   /// Cache for custom binning string
   QString m_customBinning;
@@ -51,7 +50,8 @@ private:
   /// Text for tooltip for save event data
   QString m_saveEventDataToolTip;
   /// Set the bin field
-  void setHistogramUiLogic(QString label, QString toolTip, QString lineEditText,bool enabled);
+  void setHistogramUiLogic(QString label, QString toolTip, QString lineEditText,
+                           bool enabled);
   /// Set the histo gram input enabled or disabled
   void setInputEnabled(bool enabled);
   /// Create Python string list
@@ -61,42 +61,46 @@ private:
 
   void initLayout() override;
   void setToolTips();
-  QListWidgetItem* insertListFront(const QString &text);
-  void changeOutputDir(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo);
+  QListWidgetItem *insertListFront(const QString &text);
+  void
+  changeOutputDir(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo);
   void setOutDir(std::string dir);
   void readSettings();
   void saveSettings();
   bool checkValidityTimeShiftsForAddedEventFiles();
 
 private slots:
-  ///insert another row into the files to sum table (tbRunsToAdd), in response to a click on the pbNewRow button
+  /// insert another row into the files to sum table (tbRunsToAdd), in response
+  /// to a click on the pbNewRow button
   void add2Runs2Add();
-  ///run the Python that sums the files together in response to a pbSum button click
+  /// run the Python that sums the files together in response to a pbSum button
+  /// click
   void runPythonAddFiles();
   void outPathSel();
-  ///this slot opens a browser to select a new file to add
+  /// this slot opens a browser to select a new file to add
   void new2AddBrowse();
-  ///sets data associated with the cell
+  /// sets data associated with the cell
   void setCellData(QListWidgetItem *);
-  ///clears the table that contains the names of the files to add
+  /// clears the table that contains the names of the files to add
   void clearClicked();
-  ///clears the contents of the selected row
+  /// clears the contents of the selected row
   void removeSelected();
   /// Enables/disables the "Sum" button based on whether there are files to sum.
   void enableSumming();
-  /// reacts to changges of the combo box selection for the histogram options for event data
+  /// reacts to changges of the combo box selection for the histogram options
+  /// for event data
   void onCurrentIndexChangedForHistogramChoice(int index);
   /// reacts to changes of the overlay check box
   void onStateChangedForOverlayCheckBox(int);
   /// checks if a file corresponds to a histogram worksapce
   bool isEventWorkspace(QString file_name);
-  /// checks if the files which are to be added are all based on event workspaces
+  /// checks if the files which are to be added are all based on event
+  /// workspaces
   bool existNonEventFiles();
   /// sets the binning options
   void setBinningOptions(bool enable);
 };
-
 }
 }
 
-#endif  //MANTIDQTCUSTOMINTERFACES_SANSADDFILES_H_
+#endif // MANTIDQTCUSTOMINTERFACES_SANSADDFILES_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSConstants.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSConstants.h
index d30875cdc8b39bed82cfab28910d543269e471e0..a04f1626baf073658e39db61e9b59d3bea57c287 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSConstants.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSConstants.h
@@ -3,13 +3,10 @@
 
 #include <QString>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class SANSConstants
-{
+class SANSConstants {
 public:
   SANSConstants();
   ~SANSConstants();
@@ -24,14 +21,13 @@ public:
   static QString getQResolutionH2ToolTipText();
   static QString getQResolutionA1ToolTipText();
   static QString getQResolutionA2ToolTipText();
-  
+
   // Input related
   static double getMaxDoubleValue();
   static int getMaxIntValue();
   static int getDecimals();
 };
-
 }
 }
 
-#endif  //MANTIDQTCUSTOMINTERFACES_SANSADDFILES_H_
\ No newline at end of file
+#endif // MANTIDQTCUSTOMINTERFACES_SANSADDFILES_H_
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSEventSlicing.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSEventSlicing.h
index a608aad6d9ccc85e630d59eef66ebf2e906ee151..a026b261b9e17d9f81df24af87c4ea255bd7cd59 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSEventSlicing.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSEventSlicing.h
@@ -5,54 +5,50 @@
 #include "MantidQtAPI/UserSubWindow.h"
 #include <QString>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class SANSEventSlicing : public API::UserSubWindow
-{
+class SANSEventSlicing : public API::UserSubWindow {
   Q_OBJECT
 
 public:
   /// Default Constructor
-  SANSEventSlicing(QWidget *parent=0);
+  SANSEventSlicing(QWidget *parent = 0);
   /// Destructor
   ~SANSEventSlicing() override;
 
-  static std::string name(){return "SANS ISIS Slicing";}
-  static QString categoryInfo() {return "SANS";}
+  static std::string name() { return "SANS ISIS Slicing"; }
+  static QString categoryInfo() { return "SANS"; }
 
 private:
-
-  struct ChargeAndTime{
-    QString charge; 
+  struct ChargeAndTime {
+    QString charge;
     QString time;
   };
 
   void initLayout() override;
 
-  ChargeAndTime getFullChargeAndTime(const QString & name_ws); 
-  QString createSliceEventCode(const QString & name_ws, const QString & start, const QString & stop); 
-  ChargeAndTime runSliceEvent(const QString & code2run); 
-  void checkPythonOutput(const QString & result); 
-  ChargeAndTime values2ChargeAndTime(const QString & input);
-  void raiseWarning(QString title, QString message); 
-
- protected:
-   void showEvent(QShowEvent *) override;
- private slots:
-
-   /// Apply the slice for the SANS data, and update the view with the last
-   /// sliced data.
-   void doApplySlice();
-   void onChangeWorkspace(const QString &newWs);
-  
- private:
-  Ui::SANSEventSlicing ui; 
-};
+  ChargeAndTime getFullChargeAndTime(const QString &name_ws);
+  QString createSliceEventCode(const QString &name_ws, const QString &start,
+                               const QString &stop);
+  ChargeAndTime runSliceEvent(const QString &code2run);
+  void checkPythonOutput(const QString &result);
+  ChargeAndTime values2ChargeAndTime(const QString &input);
+  void raiseWarning(QString title, QString message);
+
+protected:
+  void showEvent(QShowEvent *) override;
+private slots:
 
+  /// Apply the slice for the SANS data, and update the view with the last
+  /// sliced data.
+  void doApplySlice();
+  void onChangeWorkspace(const QString &newWs);
+
+private:
+  Ui::SANSEventSlicing ui;
+};
 }
 }
 
-#endif  //MANTIDQTCUSTOMINTERFACES_SANSEVENTSLICING_H_
+#endif // MANTIDQTCUSTOMINTERFACES_SANSEVENTSLICING_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSPlotSpecial.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSPlotSpecial.h
index 4845e609c137bb1639b47752b2d48aa8cacc6502..4cf8adedb87b8f3ca5fa3f576dfefafec98f84de 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSPlotSpecial.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSPlotSpecial.h
@@ -5,70 +5,80 @@
 #include "ui_SANSPlotSpecial.h"
 
 // Forward Declarations
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class RangeSelector;
+namespace MantidQt {
+namespace MantidWidgets {
+class RangeSelector;
 }
 }
-namespace Mantid
-{
-namespace API
-{
-  class MatrixWorkspace;
+namespace Mantid {
+namespace API {
+class MatrixWorkspace;
 }
 }
 class QwtPlotCurve;
 // End of forward declarations
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class SANSPlotSpecial : public QFrame
-{
+class SANSPlotSpecial : public QFrame {
   Q_OBJECT
 
 public:
   /**
   * Small utility class to hold information about the different functions.
   */
-  class Transform
-  {
+  class Transform {
   public:
-    enum TransformType { GuinierSpheres, GuinierRods, GuinierSheets, Zimm, DebyeBueche,
-      Holtzer, Kratky, Porod, LogLog, General };
+    enum TransformType {
+      GuinierSpheres,
+      GuinierRods,
+      GuinierSheets,
+      Zimm,
+      DebyeBueche,
+      Holtzer,
+      Kratky,
+      Porod,
+      LogLog,
+      General
+    };
     Transform(TransformType type);
     ~Transform();
     void init();
     std::vector<double> functionConstants();
-    QPair<QStringList, QList<QPair<int, int> > > derivatives();
-    QList<QWidget*> xWidgets() { return m_xWidgets; }
-    QList<QWidget*> yWidgets() { return m_yWidgets; }
+    QPair<QStringList, QList<QPair<int, int>>> derivatives();
+    QList<QWidget *> xWidgets() { return m_xWidgets; }
+    QList<QWidget *> yWidgets() { return m_yWidgets; }
     TransformType type() { return m_type; }
     QStringList interceptDerivatives();
     void tidyGeneral();
-    
+
   private:
     TransformType m_type;
-    QList<QWidget*> m_xWidgets;
-    QList<QWidget*> m_yWidgets;
+    QList<QWidget *> m_xWidgets;
+    QList<QWidget *> m_yWidgets;
     QString m_gDeriv;
     QString m_iDeriv;
   };
 
 public:
-  enum Column { FitInformation, FitInformationValues, GradientLabels, GradientDerived, GradientUnits,
-    InterceptLabels, InterceptDerived, InterceptUnits };
+  enum Column {
+    FitInformation,
+    FitInformationValues,
+    GradientLabels,
+    GradientDerived,
+    GradientUnits,
+    InterceptLabels,
+    InterceptDerived,
+    InterceptUnits
+  };
   SANSPlotSpecial(QWidget *parent = 0);
   ~SANSPlotSpecial() override;
 
 public slots:
   void rangeChanged(double, double);
   void plot();
-  void updateAxisLabels(const QString&);
+  void updateAxisLabels(const QString &);
   void clearTable();
   void calculateDerivatives();
   void tableUpdated(int row, int column);
@@ -79,13 +89,14 @@ public slots:
 private:
   void initLayout();
   boost::shared_ptr<Mantid::API::MatrixWorkspace> runIQTransform();
-  void tableDisplay(QStringList properties, QList<QPair<int, int> > positions);
+  void tableDisplay(QStringList properties, QList<QPair<int, int>> positions);
   bool validatePlotOptions();
   void setupTable();
   void createTransforms();
-  QwtPlotCurve* plotMiniplot(QwtPlotCurve* curve, 
-    boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace,
-    size_t workspaceIndex=0);
+  QwtPlotCurve *
+  plotMiniplot(QwtPlotCurve *curve,
+               boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace,
+               size_t workspaceIndex = 0);
 
   void deriveGuinierSpheres();
   void deriveGuinierRods();
@@ -93,24 +104,24 @@ private:
   void deriveKratky();
   void derivePorod();
 
-  double getValue(QTableWidgetItem*);
-  QPair<QStringList, QMap<QString, double> > getProperties(const QString & transform);
-  
+  double getValue(QTableWidgetItem *);
+  QPair<QStringList, QMap<QString, double>>
+  getProperties(const QString &transform);
+
 private:
   Ui::SANSPlotSpecial m_uiForm;
-  MantidWidgets::RangeSelector* m_rangeSelector;
-  QMap<QString, Transform*> m_transforms;
-  QMap<QString, QTableWidgetItem*> m_derivatives;
+  MantidWidgets::RangeSelector *m_rangeSelector;
+  QMap<QString, Transform *> m_transforms;
+  QMap<QString, QTableWidgetItem *> m_derivatives;
   QMap<QString, QString> m_units;
   QString m_current;
-  QwtPlotCurve* m_dataCurve;
-  QwtPlotCurve* m_linearCurve;
+  QwtPlotCurve *m_dataCurve;
+  QwtPlotCurve *m_linearCurve;
   boost::shared_ptr<Mantid::API::MatrixWorkspace> m_workspaceIQT;
   boost::shared_ptr<Mantid::API::MatrixWorkspace> m_workspaceLinear;
   bool m_rearrangingTable;
-  QTableWidgetItem* m_emptyCell;
+  QTableWidgetItem *m_emptyCell;
 };
-
 }
 }
 
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
index 953a2d8ac6d3b7f55f3c8dbbca043d4c8c370a6a..24b9ee880f813ba1bb69ff75a9c036f4c7e07071 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
@@ -493,11 +493,12 @@ private:
                                   bool w1W2Disabled);
   /// Initialize the QResolution settings
   void initQResolutionSettings();
-  
+
   /// Gets the BackgroundCorrection settings
   void retrieveBackgroundCorrection();
   /// Get Background runner
-  SANSBackgroundCorrectionSettings retrieveBackgroundCorrectionSetting(bool isTime, bool isMon);
+  SANSBackgroundCorrectionSettings
+  retrieveBackgroundCorrectionSetting(bool isTime, bool isMon);
   /// Initialize the background correction
   void initializeBackgroundCorrection();
   /// Sets the BackgroundCorrection settings
@@ -514,7 +515,6 @@ private:
   /// Update IDF file path
   void updateIDFFilePath();
 
-      
   UserSubWindow *slicingWindow;
 };
 }
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h
index 616d0e8e8111f0872a998e374c43068ebbe8795e..9b9c94b64b7470bb6ffae1629855f8523ba5754b 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h
@@ -10,48 +10,42 @@
 #include "MantidQtAPI/WorkspaceObserver.h"
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 
-
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  class SampleTransmission : public MantidQt::API::UserSubWindow
-  {
-    Q_OBJECT
-
-  public:
-    /// The name of the interface as registered into the factory
-    static std::string name() { return "Sample Transmission Calculator"; }
-    // This interface's categories.
-    static QString categoryInfo() { return "General"; }
-
-  public:
-    /// Default Constructor
-    SampleTransmission(QWidget *parent = 0);
-
-  private slots:
-    /// Opens the Qt help page for the interface
-    void showHelp();
-    /// Runs the calculation
-    void calculate();
-    /// Handle completion of the calculation algorithm
-    void algorithmComplete(bool error);
-
-  private:
-    /// Initialize the layout
-    void initLayout() override;
-    /// Validates UI input
-    bool validate(bool silent = false);
-
-  private:
-    /// The form generated by Qt Designer
-    Ui::SampleTransmission m_uiForm;
-    /// Algorithm runner
-    API::AlgorithmRunner * m_algRunner;
-
-  };
-
+namespace MantidQt {
+namespace CustomInterfaces {
+class SampleTransmission : public MantidQt::API::UserSubWindow {
+  Q_OBJECT
+
+public:
+  /// The name of the interface as registered into the factory
+  static std::string name() { return "Sample Transmission Calculator"; }
+  // This interface's categories.
+  static QString categoryInfo() { return "General"; }
+
+public:
+  /// Default Constructor
+  SampleTransmission(QWidget *parent = 0);
+
+private slots:
+  /// Opens the Qt help page for the interface
+  void showHelp();
+  /// Runs the calculation
+  void calculate();
+  /// Handle completion of the calculation algorithm
+  void algorithmComplete(bool error);
+
+private:
+  /// Initialize the layout
+  void initLayout() override;
+  /// Validates UI input
+  bool validate(bool silent = false);
+
+private:
+  /// The form generated by Qt Designer
+  Ui::SampleTransmission m_uiForm;
+  /// Algorithm runner
+  API::AlgorithmRunner *m_algRunner;
+};
 }
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_
+#endif // MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/StepScan.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/StepScan.h
index 58d9e1a8547d173bfdbdd7e788a2fa472b81e8c9..2d7b30102ff1177c38f104b6d4f4212bd7edc11d 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/StepScan.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/StepScan.h
@@ -10,13 +10,10 @@
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 #include "MantidAPI/IAlgorithm.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-class StepScan : public API::UserSubWindow
-{
+class StepScan : public API::UserSubWindow {
   Q_OBJECT
 
 public:
@@ -29,9 +26,9 @@ public:
   ~StepScan() override;
 
 signals:
-  void logsAvailable( const Mantid::API::MatrixWorkspace_const_sptr& );
-  void logsUpdated( const Mantid::API::MatrixWorkspace_const_sptr& );
-  void updatePlot( const QString& );
+  void logsAvailable(const Mantid::API::MatrixWorkspace_const_sptr &);
+  void logsUpdated(const Mantid::API::MatrixWorkspace_const_sptr &);
+  void updatePlot(const QString &);
 
 private slots:
   void triggerLiveListener(bool checked);
@@ -39,14 +36,14 @@ private slots:
   void loadFile(bool async = true);
   void loadFileComplete(bool error);
   void launchInstrumentWindow();
-  void fillPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr& ws);
-  void expandPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr& ws);
+  void fillPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr &ws);
+  void expandPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr &ws);
   void fillNormalizationCombobox();
   void runStepScanAlg();
   bool runStepScanAlgLive(std::string stepScanProperties);
 
   void updateForNormalizationChange();
-  void generateCurve(const QString& var);
+  void generateCurve(const QString &var);
 
   void helpClicked();
 
@@ -63,22 +60,25 @@ private:
   void handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf);
   void handleReplEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf);
   void addReplaceObserverOnce();
-  void checkForMaskWorkspace(const std::string& wsName);
-  void checkForResultTableUpdate(const std::string& wsName);
-  void checkForVaryingLogs(const std::string& wsName);
+  void checkForMaskWorkspace(const std::string &wsName);
+  void checkForResultTableUpdate(const std::string &wsName);
+  void checkForVaryingLogs(const std::string &wsName);
 
-  Ui::StepScan m_uiForm;  ///< The form generated by Qt Designer
+  Ui::StepScan m_uiForm; ///< The form generated by Qt Designer
   std::string m_inputWSName, m_tableWSName, m_plotWSName;
   QString m_inputFilename;
   const std::string m_instrument; ///< The default instrument (for live data)
 
-  API::AlgorithmRunner * m_algRunner; ///< Object for running algorithms asynchronously
-  Poco::NObserver<StepScan, Mantid::API::WorkspaceAddNotification> m_addObserver;
-  Poco::NObserver<StepScan, Mantid::API::WorkspaceAfterReplaceNotification> m_replObserver;
+  API::AlgorithmRunner *
+      m_algRunner; ///< Object for running algorithms asynchronously
+  Poco::NObserver<StepScan, Mantid::API::WorkspaceAddNotification>
+      m_addObserver;
+  Poco::NObserver<StepScan, Mantid::API::WorkspaceAfterReplaceNotification>
+      m_replObserver;
   bool m_replaceObserverAdded;
 };
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
 
-#endif //MANTIDQTCUSTOMINTERFACES_ROCKINGCURVE_H_
+#endif // MANTIDQTCUSTOMINTERFACES_ROCKINGCURVE_H_
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfacePresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfacePresenter.h
index fcbd1137ffef1c1de1abaf1ae0ad92c2eb86c9f6..e071c302a15ebe5974c77803b4f5e2f1a0c13858 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfacePresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfacePresenter.h
@@ -43,7 +43,7 @@ public:
     ToolChanged,      ///< 'current' tomographic reconstruction tool changed
     TomoPathsChanged, ///< user selects tomography data paths
     TomoPathsEditedByUser, ///< user edits manually paths that may modify other
-                           ///paths
+    /// paths
     LogInRequested,        ///< user hits 'log in' or similar
     LogOutRequested,       ///< user hits 'log out' or similar
     SetupReconTool,        ///< To start the setup (open dialog, etc.)
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h
index 2aee1fef361bfa6371e9889d70075cb64c2bdb7b..8b966e6018324b4cc26af5a5565b2813b18928e6 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h
@@ -19,9 +19,9 @@ etc.).
 The parameters include:
 - center of rotation
 - region of interest (clip from original or raw images)
-- region for normalization (where the beam is not blocked by any sample 
+- region for normalization (where the beam is not blocked by any sample
   object throughout the stack of images) other parameters describing
-  the stack of images: 
+  the stack of images:
 
 Copyright &copy; 2014,2015 ISIS Rutherford Appleton Laboratory, NScD
 Oak Ridge National Laboratory & European Spallation Source
@@ -46,15 +46,14 @@ Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 class MANTIDQT_CUSTOMINTERFACES_DLL ImageStackPreParams {
 public:
-
   ImageStackPreParams();
 
   typedef std::pair<Mantid::Kernel::V2D, Mantid::Kernel::V2D> Box2D;
 
   Mantid::Kernel::V2D cor;
   Box2D roi;
-  Box2D normalizationRegion;  //< also known as 'air' region
-  float rotation; //< rotation angle in degrees
+  Box2D normalizationRegion; //< also known as 'air' region
+  float rotation;            //< rotation angle in degrees
 };
 
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h
index 64e4a4d1d6814a55ad71287d1e333db4c14b292a..dc05e618418840879027d8b208fba1c76f17825f 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h
@@ -100,7 +100,8 @@ protected:
   /// auto-guess additional directories when the user gives the samples path
   void findFlatsDarksFromSampleGivenByUser(TomoPathsConfig &cfg);
 
-  bool usableEnergyBandsPaths(const std::map<std::string, std::string> &algParams);
+  bool
+  usableEnergyBandsPaths(const std::map<std::string, std::string> &algParams);
 
   /// Starts a periodic query just to keep sessions alive when logged in
   void startKeepAliveMechanism(int period);
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Updateable.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Updateable.h
index 5e74c227e791d1d8d1dca4c28b01eeb3ffca611a..22f7c042d389d37520778488b7183a95c546b41e 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Updateable.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Updateable.h
@@ -1,43 +1,41 @@
 #ifndef MANTIDQTCUSTOMINTERFACES_UPDATABLE_H
-#define MANTIDQTCUSTOMINTERFACES_UPDATABLE_H 
+#define MANTIDQTCUSTOMINTERFACES_UPDATABLE_H
 
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-     /** Abstraction of an updateable item, i.e. a MVP presenter or Qt MVC Model.
-  
-      @author Owen Arnold, RAL ISIS
-      @date 06/Oct/2011
-
-      Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-      This file is part of Mantid.
-
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
-
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
-
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-      File change history is stored at: <https://github.com/mantidproject/mantid>.
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-     */
-    class DLLExport Updateable
-    {
-    public:
-      virtual void update() = 0;
-    };
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+/** Abstraction of an updateable item, i.e. a MVP presenter or Qt MVC Model.
+
+ @author Owen Arnold, RAL ISIS
+ @date 06/Oct/2011
+
+ Copyright &copy; 2010-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+ This file is part of Mantid.
+
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+ File change history is stored at: <https://github.com/mantidproject/mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport Updateable {
+public:
+  virtual void update() = 0;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/deltaECalc.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/deltaECalc.h
index a161c4ac809b19aa717cfafc1020f8c715e83843..ae9e670e5631696fd34b7b9ce22034944fc29348 100644
--- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/deltaECalc.h
+++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/deltaECalc.h
@@ -5,49 +5,52 @@
 #include "ui_DirectConvertToEnergy.h"
 #include <QFileInfo>
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {	
-    class deltaECalc : public MantidWidgets::pythonCalc
-    {
-    public:
-      deltaECalc(QWidget * const interface, const Ui::DirectConvertToEnergy &userSettings, const bool removalBg, 
-     const double TOFWinSt, const double TOFWinEnd);
-      void setDiagnosedWorkspaceName(const QString &maskWS);
-      void createProcessingScript(const QStringList & inFiles, const QString &whiteB,
-          const QStringList &absInFiles, const QString &absWhiteB,
-          const QString & saveName);
- 
-      /** Removes the path from the filename passed and replaces extensions with .spe
-      * @param inputFilename :: name of the file that the .SPE file is based on
-      */
-      static QString SPEFileName(const QString &inputFilename)
-      {
-        QString root = QFileInfo(inputFilename).baseName();
-        if( root.isEmpty() ) return "";
-        return root + ".spe";
-      }
-      std::string insertNumber(const std::string &filename, const int number) const;
-    private:
-      /// the form that ws filled in by the user
-      const Ui::DirectConvertToEnergy &m_sets;
-      /// whether to the remove background count rate from the data
-      const bool m_bgRemove;
-      /// used in remove background, the start of the background region
-      const double m_TOFWinSt;
-      /// used in remove background, the end of the background region
-      const double m_TOFWinEnd;
+namespace MantidQt {
+namespace CustomInterfaces {
+class deltaECalc : public MantidWidgets::pythonCalc {
+public:
+  deltaECalc(QWidget *const interface,
+             const Ui::DirectConvertToEnergy &userSettings,
+             const bool removalBg, const double TOFWinSt,
+             const double TOFWinEnd);
+  void setDiagnosedWorkspaceName(const QString &maskWS);
+  void createProcessingScript(const QStringList &inFiles, const QString &whiteB,
+                              const QStringList &absInFiles,
+                              const QString &absWhiteB,
+                              const QString &saveName);
 
-      QString m_diagnosedWS;
-      void addAnalysisOptions(QString & analysisScript);
-      void addMaskingCommands(QString & analysisScript);
-      QString createPyListAsString(const QStringList & names) const;
-  
-      // holds the prefix that we give to output workspaces that will be deleted in the Python
-      static const QString tempWS;
-    };
+  /** Removes the path from the filename passed and replaces extensions with
+  * .spe
+  * @param inputFilename :: name of the file that the .SPE file is based on
+  */
+  static QString SPEFileName(const QString &inputFilename) {
+    QString root = QFileInfo(inputFilename).baseName();
+    if (root.isEmpty())
+      return "";
+    return root + ".spe";
   }
+  std::string insertNumber(const std::string &filename, const int number) const;
+
+private:
+  /// the form that ws filled in by the user
+  const Ui::DirectConvertToEnergy &m_sets;
+  /// whether to the remove background count rate from the data
+  const bool m_bgRemove;
+  /// used in remove background, the start of the background region
+  const double m_TOFWinSt;
+  /// used in remove background, the end of the background region
+  const double m_TOFWinEnd;
+
+  QString m_diagnosedWS;
+  void addAnalysisOptions(QString &analysisScript);
+  void addMaskingCommands(QString &analysisScript);
+  QString createPyListAsString(const QStringList &names) const;
+
+  // holds the prefix that we give to output workspaces that will be deleted in
+  // the Python
+  static const QString tempWS;
+};
+}
 }
 
-#endif	//MANTIDQTCUSTOMINTERFACES_DELTAECALC_H_
+#endif // MANTIDQTCUSTOMINTERFACES_DELTAECALC_H_
diff --git a/MantidQt/CustomInterfaces/src/DataComparison.cpp b/MantidQt/CustomInterfaces/src/DataComparison.cpp
index 532987ab26cce20bc3a7012d83e080cee48a3802..43d0fd89a61adbfd007dd58e54a26d9718538d7c 100644
--- a/MantidQt/CustomInterfaces/src/DataComparison.cpp
+++ b/MantidQt/CustomInterfaces/src/DataComparison.cpp
@@ -7,51 +7,41 @@
 #include "MantidAPI/MatrixWorkspace.h"
 #include "MantidQtAPI/QwtWorkspaceSpectrumData.h"
 
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("DataComparison");
+namespace {
+Mantid::Kernel::Logger g_log("DataComparison");
 }
 
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  DECLARE_SUBWINDOW(DataComparison)
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(DataComparison)
 }
 }
 
 using namespace MantidQt::CustomInterfaces;
 using namespace Mantid::API;
 
-
 //----------------------
 // Public member functions
 //----------------------
-///Constructor
-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()))
-{
+/// Constructor
+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();
   observeRename();
   observePreDelete();
 }
 
-
 /// Set up the dialog layout
-void DataComparison::initLayout()
-{
+void DataComparison::initLayout() {
   m_uiForm.setupUi(this);
 
-  m_zoomTool = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
-      QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, m_plot->canvas());
+  m_zoomTool =
+      new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
+                        QwtPicker::DragSelection | QwtPicker::CornerToCorner,
+                        QwtPicker::AlwaysOff, m_plot->canvas());
   m_zoomTool->setEnabled(false);
 
   m_panTool = new QwtPlotPanner(m_plot->canvas());
@@ -67,10 +57,13 @@ void DataComparison::initLayout()
   // Connect push buttons
   connect(m_uiForm.pbAddData, SIGNAL(clicked()), this, SLOT(addData()));
 
-  connect(m_uiForm.pbRemoveSelectedData, SIGNAL(clicked()), this, SLOT(removeSelectedData()));
-  connect(m_uiForm.pbRemoveAllData, SIGNAL(clicked()), this, SLOT(removeAllData()));
+  connect(m_uiForm.pbRemoveSelectedData, SIGNAL(clicked()), this,
+          SLOT(removeSelectedData()));
+  connect(m_uiForm.pbRemoveAllData, SIGNAL(clicked()), this,
+          SLOT(removeAllData()));
 
-  connect(m_uiForm.pbDiffSelected, SIGNAL(clicked()), this, SLOT(diffSelected()));
+  connect(m_uiForm.pbDiffSelected, SIGNAL(clicked()), this,
+          SLOT(diffSelected()));
   connect(m_uiForm.pbClearDiff, SIGNAL(clicked()), this, SLOT(clearDiff()));
 
   connect(m_uiForm.pbPan, SIGNAL(toggled(bool)), this, SLOT(togglePan(bool)));
@@ -78,11 +71,15 @@ void DataComparison::initLayout()
   connect(m_uiForm.pbResetView, SIGNAL(clicked()), this, SLOT(resetView()));
 
   // Replot spectra when the workspace index is changed
-  connect(m_uiForm.sbSpectrum, SIGNAL(valueChanged(int)), this, SLOT(workspaceIndexChanged()));
+  connect(m_uiForm.sbSpectrum, SIGNAL(valueChanged(int)), this,
+          SLOT(workspaceIndexChanged()));
 
   // Add headers to data table
   QStringList headerLabels;
-  headerLabels << "Colour" << "Workspace" << "Offset" << "Spec.";
+  headerLabels << "Colour"
+               << "Workspace"
+               << "Offset"
+               << "Spec.";
   m_uiForm.twCurrentData->setColumnCount(headerLabels.size());
   m_uiForm.twCurrentData->setHorizontalHeaderLabels(headerLabels);
 
@@ -93,36 +90,34 @@ void DataComparison::initLayout()
   m_uiForm.twCurrentData->resizeColumnsToContents();
 }
 
-
 /**
  * Adds the data currently selected by the data selector to the plot.
  */
-void DataComparison::addData()
-{
+void DataComparison::addData() {
   const QString dataName = m_uiForm.dsData->getCurrentDataName();
 
   // Do nothing if the data is not found
-  if(!AnalysisDataService::Instance().doesExist(dataName.toStdString()))
+  if (!AnalysisDataService::Instance().doesExist(dataName.toStdString()))
     return;
 
   // Get the workspace
-  Workspace_const_sptr ws = AnalysisDataService::Instance().retrieveWS<Workspace>(dataName.toStdString());
-  WorkspaceGroup_const_sptr wsGroup = boost::dynamic_pointer_cast<const WorkspaceGroup>(ws);
+  Workspace_const_sptr ws =
+      AnalysisDataService::Instance().retrieveWS<Workspace>(
+          dataName.toStdString());
+  WorkspaceGroup_const_sptr wsGroup =
+      boost::dynamic_pointer_cast<const WorkspaceGroup>(ws);
 
   m_uiForm.twCurrentData->blockSignals(true);
 
   // If this is a WorkspaceGroup then add all items
-  if(wsGroup != NULL)
-  {
+  if (wsGroup != NULL) {
     size_t numWs = wsGroup->size();
-    for(size_t wsIdx = 0; wsIdx < numWs; wsIdx++)
-    {
+    for (size_t wsIdx = 0; wsIdx < numWs; wsIdx++) {
       addDataItem(wsGroup->getItem(wsIdx));
     }
   }
   // Otherwise just add the single workspace
-  else
-  {
+  else {
     addDataItem(ws);
   }
 
@@ -135,26 +130,25 @@ void DataComparison::addData()
   plotWorkspaces();
 }
 
-
 /**
  * Adds a MatrixWorkspace by name to the data table.
  *
  * @param ws Pointer to workspace to add.
  */
-void DataComparison::addDataItem(Workspace_const_sptr ws)
-{
+void DataComparison::addDataItem(Workspace_const_sptr ws) {
   // Check that the workspace is the correct type
-  MatrixWorkspace_const_sptr matrixWs = boost::dynamic_pointer_cast<const MatrixWorkspace>(ws);
-  if(!matrixWs)
-  {
-    g_log.error() << "Workspace " << ws->name() << "is of incorrect type!" << std::endl;
+  MatrixWorkspace_const_sptr matrixWs =
+      boost::dynamic_pointer_cast<const MatrixWorkspace>(ws);
+  if (!matrixWs) {
+    g_log.error() << "Workspace " << ws->name() << "is of incorrect type!"
+                  << std::endl;
     return;
   }
 
   // Check that the workspace does not already exist in the comparison
-  if(containsWorkspace(matrixWs))
-  {
-    g_log.information() << "Workspace " << matrixWs->name() << " already shown in comparison." << std::endl;
+  if (containsWorkspace(matrixWs)) {
+    g_log.information() << "Workspace " << matrixWs->name()
+                        << " already shown in comparison." << std::endl;
     return;
   }
 
@@ -186,7 +180,8 @@ void DataComparison::addDataItem(Workspace_const_sptr ws)
   // Set the initial colour
   colourCombo->setCurrentIndex(getInitialColourIndex());
   // Update plots when colour changed
-  connect(colourCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(plotWorkspaces()));
+  connect(colourCombo, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(plotWorkspaces()));
   // Add widget to table
   m_uiForm.twCurrentData->setCellWidget(currentRows, COLOUR, colourCombo);
 
@@ -199,7 +194,8 @@ void DataComparison::addDataItem(Workspace_const_sptr ws)
   QSpinBox *offsetSpin = new QSpinBox();
   offsetSpin->setMinimum(0);
   offsetSpin->setMaximum(INT_MAX);
-  connect(offsetSpin, SIGNAL(valueChanged(int)), this, SLOT(spectrumIndexChanged()));
+  connect(offsetSpin, SIGNAL(valueChanged(int)), this,
+          SLOT(spectrumIndexChanged()));
   m_uiForm.twCurrentData->setCellWidget(currentRows, SPEC_OFFSET, offsetSpin);
 
   // Insert the current displayed spectra
@@ -208,81 +204,75 @@ void DataComparison::addDataItem(Workspace_const_sptr ws)
   m_uiForm.twCurrentData->setItem(currentRows, CURRENT_SPEC, currentSpecItem);
 }
 
-
 /**
  * Determines if a given workspace is currently shown in the UI.
  *
  * @param ws Pointer to the workspace
  */
-bool DataComparison::containsWorkspace(MatrixWorkspace_const_sptr ws)
-{
+bool DataComparison::containsWorkspace(MatrixWorkspace_const_sptr ws) {
   QString testWsName = QString::fromStdString(ws->name());
 
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
-    if(workspaceName == testWsName)
+  for (int row = 0; row < numRows; row++) {
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    if (workspaceName == testWsName)
       return true;
   }
 
   return false;
 }
 
-
 /**
  * Gets a colour as an index for the combo box for a new workspace.
  * Looks for the lowest unused index, if all colours are used then returns 0.
  *
  * @return An index to set for the conbo box
  */
-int DataComparison::getInitialColourIndex()
-{
+int DataComparison::getInitialColourIndex() {
   int numRows = m_uiForm.twCurrentData->rowCount();
 
   // Just use the first colour if this is the first row
-  if(numRows <= 1)
+  if (numRows <= 1)
     return 0;
 
   // Build a list of used colours
   QList<int> usedColours;
-  for(int row = 0; row < numRows - 1; row++)
-  {
-    QComboBox *colourSelector = dynamic_cast<QComboBox *>(m_uiForm.twCurrentData->cellWidget(row, COLOUR));
+  for (int row = 0; row < numRows - 1; row++) {
+    QComboBox *colourSelector = dynamic_cast<QComboBox *>(
+        m_uiForm.twCurrentData->cellWidget(row, COLOUR));
     int index = colourSelector->currentIndex();
     usedColours << index;
   }
 
   // Find the smallest unused colour
-  int numColours = dynamic_cast<QComboBox *>(m_uiForm.twCurrentData->cellWidget(0, COLOUR))->count();
-  for(int i = 0; i < numColours; i++)
-  {
-    if(!usedColours.contains(i))
+  int numColours = dynamic_cast<QComboBox *>(
+                       m_uiForm.twCurrentData->cellWidget(0, COLOUR))->count();
+  for (int i = 0; i < numColours; i++) {
+    if (!usedColours.contains(i))
       return i;
   }
 
   return 0;
 }
 
-
 /**
  * Removes the data currently selected in the table from the plot.
  */
-void DataComparison::removeSelectedData()
-{
-  QList<QTableWidgetItem *> selectedItems = m_uiForm.twCurrentData->selectedItems();
+void DataComparison::removeSelectedData() {
+  QList<QTableWidgetItem *> selectedItems =
+      m_uiForm.twCurrentData->selectedItems();
 
-  while(!selectedItems.isEmpty())
-  {
+  while (!selectedItems.isEmpty()) {
     // Get the row number of the item
     int row = selectedItems[0]->row();
 
     // Get workspace name
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
 
-    if(m_diffWorkspaceNames.first == workspaceName ||
-       m_diffWorkspaceNames.second == workspaceName)
-    {
+    if (m_diffWorkspaceNames.first == workspaceName ||
+        m_diffWorkspaceNames.second == workspaceName) {
       clearDiff();
     }
 
@@ -290,7 +280,7 @@ void DataComparison::removeSelectedData()
     m_uiForm.twCurrentData->removeRow(row);
 
     // Detach the old curve from the plot if it exists
-    if(m_curves.contains(workspaceName))
+    if (m_curves.contains(workspaceName))
       m_curves[workspaceName]->attach(NULL);
 
     selectedItems = m_uiForm.twCurrentData->selectedItems();
@@ -300,25 +290,23 @@ void DataComparison::removeSelectedData()
   updatePlot();
 }
 
-
 /**
  * Removed all loaded data from the plot.
  */
-void DataComparison::removeAllData()
-{
+void DataComparison::removeAllData() {
   clearDiff();
 
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
+  for (int row = 0; row < numRows; row++) {
     // Get workspace name
-    QString workspaceName = m_uiForm.twCurrentData->item(0, WORKSPACE_NAME)->text();
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(0, WORKSPACE_NAME)->text();
 
     // Remove from data tabel
     m_uiForm.twCurrentData->removeRow(0);
 
     // Detach the old curve from the plot if it exists
-    if(m_curves.contains(workspaceName))
+    if (m_curves.contains(workspaceName))
       m_curves[workspaceName]->attach(NULL);
   }
 
@@ -326,47 +314,48 @@ void DataComparison::removeAllData()
   workspaceIndexChanged();
 }
 
-
 /**
  * Replots the currently loaded workspaces.
  */
-void DataComparison::plotWorkspaces()
-{
+void DataComparison::plotWorkspaces() {
   int globalWsIndex = m_uiForm.sbSpectrum->value();
   int maxGlobalWsIndex = 0;
 
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
+  for (int row = 0; row < numRows; row++) {
     // Get workspace
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
     MatrixWorkspace_const_sptr workspace =
-      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName.toStdString());
+        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+            workspaceName.toStdString());
     int numSpec = static_cast<int>(workspace->getNumberHistograms());
 
     // Calculate spectrum number
-    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
+    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(
+        m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
     int specOffset = specOffsetSpin->value();
     int wsIndex = globalWsIndex - specOffset;
-    g_log.debug() << "Workspace index for workspace " << workspaceName.toStdString()
-                  << " is " << wsIndex << ", with offset " << specOffset << std::endl;
+    g_log.debug() << "Workspace index for workspace "
+                  << workspaceName.toStdString() << " is " << wsIndex
+                  << ", with offset " << specOffset << std::endl;
 
     // See if this workspace extends the reach of the global spectrum selector
     int maxGlobalWsIndexForWs = numSpec + specOffset - 1;
-    if(maxGlobalWsIndexForWs > maxGlobalWsIndex)
+    if (maxGlobalWsIndexForWs > maxGlobalWsIndex)
       maxGlobalWsIndex = maxGlobalWsIndexForWs;
 
     // Check the workspace index is in range
-    if(wsIndex >= numSpec || wsIndex < 0)
-    {
+    if (wsIndex >= numSpec || wsIndex < 0) {
       g_log.debug() << "Workspace " << workspaceName.toStdString()
-                    << ", workspace index out of range." << std::endl;;
+                    << ", workspace index out of range." << std::endl;
+      ;
 
       // Give "n/a" in current spectrum display
       m_uiForm.twCurrentData->item(row, CURRENT_SPEC)->setText(tr("n/a"));
 
       // Detech the curve from the plot
-      if(m_curves.contains(workspaceName))
+      if (m_curves.contains(workspaceName))
         m_curves[workspaceName]->attach(NULL);
 
       continue;
@@ -378,14 +367,18 @@ void DataComparison::plotWorkspaces()
 
     // Create the curve data
     const bool logScale(false), distribution(false);
-    QwtWorkspaceSpectrumData wsData(*workspace, static_cast<int>(wsIndex), logScale, distribution);
+    QwtWorkspaceSpectrumData wsData(*workspace, static_cast<int>(wsIndex),
+                                    logScale, distribution);
 
     // Detach the old curve from the plot if it exists
-    if(m_curves.contains(workspaceName))
+    if (m_curves.contains(workspaceName))
       m_curves[workspaceName]->attach(NULL);
 
-    QComboBox *colourSelector = dynamic_cast<QComboBox *>(m_uiForm.twCurrentData->cellWidget(row, COLOUR));
-    QColor curveColour = colourSelector->itemData(colourSelector->currentIndex()).value<QColor>();
+    QComboBox *colourSelector = dynamic_cast<QComboBox *>(
+        m_uiForm.twCurrentData->cellWidget(row, COLOUR));
+    QColor curveColour =
+        colourSelector->itemData(colourSelector->currentIndex())
+            .value<QColor>();
 
     // Create a new curve and attach it to the plot
     auto curve = boost::make_shared<QwtPlotCurve>();
@@ -406,30 +399,29 @@ void DataComparison::plotWorkspaces()
   m_uiForm.sbSpectrum->setSuffix(" / " + QString::number(maxGlobalWsIndex));
 }
 
-
 /**
  * Normalises the workspace index offsets in the data table to zero.
  */
-void DataComparison::normaliseSpectraOffsets()
-{
+void DataComparison::normaliseSpectraOffsets() {
   m_uiForm.twCurrentData->blockSignals(true);
 
   int numRows = m_uiForm.twCurrentData->rowCount();
   int lowestOffset = INT_MAX;
 
   // Find the lowest offset in the data table
-  for(int row = 0; row < numRows; row++)
-  {
-    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
+  for (int row = 0; row < numRows; row++) {
+    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(
+        m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
     int specOffset = specOffsetSpin->value();
-    if(specOffset < lowestOffset)
+    if (specOffset < lowestOffset)
       lowestOffset = specOffset;
   }
 
-  // Subtract the lowest offset from all offsets to ensure at least one offset is zero
-  for(int row = 0; row < numRows; row++)
-  {
-    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
+  // Subtract the lowest offset from all offsets to ensure at least one offset
+  // is zero
+  for (int row = 0; row < numRows; row++) {
+    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(
+        m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
     int specOffset = specOffsetSpin->value();
     specOffset -= lowestOffset;
     specOffsetSpin->setValue(specOffset);
@@ -438,76 +430,71 @@ void DataComparison::normaliseSpectraOffsets()
   m_uiForm.twCurrentData->blockSignals(false);
 }
 
-
 /**
  * Handles updating the plot, i.e. normalising offsets and replotting spectra.
  */
-void DataComparison::updatePlot()
-{
+void DataComparison::updatePlot() {
   normaliseSpectraOffsets();
   plotWorkspaces();
 }
 
-
 /**
  * Handles a workspace index or offset being modified.
  */
-void DataComparison::workspaceIndexChanged()
-{
+void DataComparison::workspaceIndexChanged() {
   normaliseSpectraOffsets();
   plotWorkspaces();
 
   bool maintainZoom = m_uiForm.cbMaintainZoom->isChecked();
-  if(!maintainZoom)
+  if (!maintainZoom)
     resetView();
 }
 
-
 /**
  * Handles creating a diff of two workspaces and plotting it.
  */
-void DataComparison::plotDiffWorkspace()
-{
+void DataComparison::plotDiffWorkspace() {
   // Detach old curve
-  if(m_diffCurve != NULL)
+  if (m_diffCurve != NULL)
     m_diffCurve->attach(NULL);
 
   // Do nothing if there are not two workspaces
-  if(m_diffWorkspaceNames.first.isEmpty() || m_diffWorkspaceNames.second.isEmpty())
+  if (m_diffWorkspaceNames.first.isEmpty() ||
+      m_diffWorkspaceNames.second.isEmpty())
     return;
 
   // Get pointers to the workspaces to be diffed
-  MatrixWorkspace_sptr ws1 = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
-      m_diffWorkspaceNames.first.toStdString());
-  MatrixWorkspace_sptr ws2 = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
-      m_diffWorkspaceNames.second.toStdString());
+  MatrixWorkspace_sptr ws1 =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          m_diffWorkspaceNames.first.toStdString());
+  MatrixWorkspace_sptr ws2 =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          m_diffWorkspaceNames.second.toStdString());
 
   int ws1Spec = 0;
   int ws2Spec = 0;
 
   // Get the current spectrum for each workspace
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
-    QString currentSpecName = m_uiForm.twCurrentData->item(row, CURRENT_SPEC)->text();
+  for (int row = 0; row < numRows; row++) {
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    QString currentSpecName =
+        m_uiForm.twCurrentData->item(row, CURRENT_SPEC)->text();
     bool ok = false;
     bool found = false;
 
-    if(workspaceName == m_diffWorkspaceNames.first)
-    {
+    if (workspaceName == m_diffWorkspaceNames.first) {
       ws1Spec = currentSpecName.toInt(&ok);
       found = true;
     }
-    if(workspaceName == m_diffWorkspaceNames.second)
-    {
+    if (workspaceName == m_diffWorkspaceNames.second) {
       ws2Spec = currentSpecName.toInt(&ok);
       found = true;
     }
 
     // Check that the spectra are not out of range
-    if(!ok && found)
-    {
+    if (!ok && found) {
       // Set info message
       QString infoMessage = workspaceName + ": Index out of range.";
       m_uiForm.lbDiffInfo->setText(infoMessage);
@@ -516,34 +503,40 @@ void DataComparison::plotDiffWorkspace()
   }
 
   // Extract the current spectrum for both workspaces
-  IAlgorithm_sptr extractWs1Alg = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+  IAlgorithm_sptr extractWs1Alg =
+      AlgorithmManager::Instance().create("ExtractSingleSpectrum");
   extractWs1Alg->setChild(true);
   extractWs1Alg->initialize();
   extractWs1Alg->setProperty("InputWorkspace", ws1);
   extractWs1Alg->setProperty("OutputWorkspace", "__ws1_spec");
   extractWs1Alg->setProperty("WorkspaceIndex", ws1Spec);
   extractWs1Alg->execute();
-  MatrixWorkspace_sptr ws1SpecWs = extractWs1Alg->getProperty("OutputWorkspace");
+  MatrixWorkspace_sptr ws1SpecWs =
+      extractWs1Alg->getProperty("OutputWorkspace");
 
-  IAlgorithm_sptr extractWs2Alg = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+  IAlgorithm_sptr extractWs2Alg =
+      AlgorithmManager::Instance().create("ExtractSingleSpectrum");
   extractWs2Alg->setChild(true);
   extractWs2Alg->initialize();
   extractWs2Alg->setProperty("InputWorkspace", ws2);
   extractWs2Alg->setProperty("OutputWorkspace", "__ws2_spec");
   extractWs2Alg->setProperty("WorkspaceIndex", ws2Spec);
   extractWs2Alg->execute();
-  MatrixWorkspace_sptr ws2SpecWs = extractWs2Alg->getProperty("OutputWorkspace");
+  MatrixWorkspace_sptr ws2SpecWs =
+      extractWs2Alg->getProperty("OutputWorkspace");
 
   // Rebin the second workspace to the first
   // (needed for identical binning for Minus algorithm)
-  IAlgorithm_sptr rebinAlg = AlgorithmManager::Instance().create("RebinToWorkspace");
+  IAlgorithm_sptr rebinAlg =
+      AlgorithmManager::Instance().create("RebinToWorkspace");
   rebinAlg->setChild(true);
   rebinAlg->initialize();
   rebinAlg->setProperty("WorkspaceToRebin", ws2SpecWs);
   rebinAlg->setProperty("WorkspaceToMatch", ws1SpecWs);
   rebinAlg->setProperty("OutputWorkspace", "__ws2_spec_rebin");
   rebinAlg->execute();
-  MatrixWorkspace_sptr rebinnedWs2SpecWs = rebinAlg->getProperty("OutputWorkspace");
+  MatrixWorkspace_sptr rebinnedWs2SpecWs =
+      rebinAlg->getProperty("OutputWorkspace");
 
   // Subtract the two extracted spectra
   IAlgorithm_sptr minusAlg = AlgorithmManager::Instance().create("Minus");
@@ -564,53 +557,52 @@ void DataComparison::plotDiffWorkspace()
   m_diffCurve = curve;
 
   // Set info message
-  QString infoMessage = m_diffWorkspaceNames.first + "(" + QString::number(ws1Spec) + ") - "
-                      + m_diffWorkspaceNames.second + "(" + QString::number(ws2Spec) + ")";
+  QString infoMessage =
+      m_diffWorkspaceNames.first + "(" + QString::number(ws1Spec) + ") - " +
+      m_diffWorkspaceNames.second + "(" + QString::number(ws2Spec) + ")";
   m_uiForm.lbDiffInfo->setText(infoMessage);
 }
 
-
 /**
- * Configures a diff of the two currently selected workspaces in the table to be plotted
+ * Configures a diff of the two currently selected workspaces in the table to be
+ *plotted
  * when plotWorkspaces is called.
  *
  * Does nothing if there are not 2 workspaces selected.
  */
-void DataComparison::diffSelected()
-{
-  QList<QTableWidgetItem *> selectedItems = m_uiForm.twCurrentData->selectedItems();
+void DataComparison::diffSelected() {
+  QList<QTableWidgetItem *> selectedItems =
+      m_uiForm.twCurrentData->selectedItems();
   QList<int> selectedRows;
 
   // Generate a list of selected row numbers
-  for(auto it = selectedItems.begin(); it != selectedItems.end(); ++it)
-  {
+  for (auto it = selectedItems.begin(); it != selectedItems.end(); ++it) {
     int row = (*it)->row();
-    if(!selectedRows.contains(row))
+    if (!selectedRows.contains(row))
       selectedRows << (*it)->row();
   }
 
   // Check there is the correct number of selected items
-  if(selectedRows.size() != 2)
-  {
-    g_log.error() << "Need to have exactly 2 workspaces selected for diff (have "
-                  << selectedRows.size() << ")" << std::endl;
+  if (selectedRows.size() != 2) {
+    g_log.error()
+        << "Need to have exactly 2 workspaces selected for diff (have "
+        << selectedRows.size() << ")" << std::endl;
     return;
   }
 
   // Record the workspace names
-  m_diffWorkspaceNames = qMakePair(m_uiForm.twCurrentData->item(selectedRows[0], WORKSPACE_NAME)->text(),
-                                   m_uiForm.twCurrentData->item(selectedRows[1], WORKSPACE_NAME)->text());
+  m_diffWorkspaceNames = qMakePair(
+      m_uiForm.twCurrentData->item(selectedRows[0], WORKSPACE_NAME)->text(),
+      m_uiForm.twCurrentData->item(selectedRows[1], WORKSPACE_NAME)->text());
 
   // Update the plot
   plotWorkspaces();
 }
 
-
 /**
  * Removes the configured diff.
  */
-void DataComparison::clearDiff()
-{
+void DataComparison::clearDiff() {
   // Clear the info message
   m_uiForm.lbDiffInfo->setText("No current diff.");
 
@@ -621,16 +613,14 @@ void DataComparison::clearDiff()
   plotWorkspaces();
 }
 
-
 /**
  * Toggles the pan plot tool.
  *
  * @param enabled If the tool should be enabled
  */
-void DataComparison::togglePan(bool enabled)
-{
+void DataComparison::togglePan(bool enabled) {
   // First disbale the zoom tool
-  if(enabled && m_uiForm.pbZoom->isChecked())
+  if (enabled && m_uiForm.pbZoom->isChecked())
     m_uiForm.pbZoom->setChecked(false);
 
   g_log.debug() << "Pan tool enabled: " << enabled << std::endl;
@@ -639,16 +629,14 @@ void DataComparison::togglePan(bool enabled)
   m_magnifyTool->setEnabled(enabled);
 }
 
-
 /**
  * Toggles the zoom plot tool.
  *
  * @param enabled If the tool should be enabled
  */
-void DataComparison::toggleZoom(bool enabled)
-{
+void DataComparison::toggleZoom(bool enabled) {
   // First disbale the pan tool
-  if(enabled && m_uiForm.pbPan->isChecked())
+  if (enabled && m_uiForm.pbPan->isChecked())
     m_uiForm.pbPan->setChecked(false);
 
   g_log.debug() << "Zoom tool enabled: " << enabled << std::endl;
@@ -657,12 +645,10 @@ void DataComparison::toggleZoom(bool enabled)
   m_magnifyTool->setEnabled(enabled);
 }
 
-
 /**
  * Rests the zoom level to fit all curves on the plot.
  */
-void DataComparison::resetView()
-{
+void DataComparison::resetView() {
   g_log.debug("Reset plot view");
 
   // Auto scale the axis
@@ -673,80 +659,78 @@ void DataComparison::resetView()
   m_zoomTool->setZoomBase(true);
 }
 
-
 /**
  * Handles removing a workspace when it is deleted from ADS.
  *
  * @param wsName Name of the workspace being deleted
  * @param ws Pointer to the workspace
  */
-void DataComparison::preDeleteHandle(const std::string& wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
+void DataComparison::preDeleteHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
   UNUSED_ARG(ws);
   QString oldWsName = QString::fromStdString(wsName);
 
   // Find the row in the data table for the workspace
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
+  for (int row = 0; row < numRows; row++) {
     // Remove the row
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
-    if(workspaceName == oldWsName)
-    {
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    if (workspaceName == oldWsName) {
       m_uiForm.twCurrentData->removeRow(row);
       break;
     }
   }
 
   // Detach the old curve from the plot if it exists
-  if(m_curves.contains(oldWsName))
+  if (m_curves.contains(oldWsName))
     m_curves[oldWsName]->attach(NULL);
 
   // Update the plot
   plotWorkspaces();
 }
 
-
 /**
  * Handle a workspace being renamed.
  *
  * @param oldName Old name for the workspace
  * @param newName New name for the workspace
  */
-void DataComparison::renameHandle(const std::string &oldName, const std::string &newName)
-{
+void DataComparison::renameHandle(const std::string &oldName,
+                                  const std::string &newName) {
   QString oldWsName = QString::fromStdString(oldName);
 
   // Find the row in the data table for the workspace
   int numRows = m_uiForm.twCurrentData->rowCount();
-  for(int row = 0; row < numRows; row++)
-  {
+  for (int row = 0; row < numRows; row++) {
     // Rename the workspace in the data table
-    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
-    if(workspaceName == oldWsName)
-    {
-      m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->setText(QString::fromStdString(newName));
+    QString workspaceName =
+        m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
+    if (workspaceName == oldWsName) {
+      m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)
+          ->setText(QString::fromStdString(newName));
       break;
     }
   }
 
   // Detach the old curve from the plot if it exists
-  if(m_curves.contains(oldWsName))
+  if (m_curves.contains(oldWsName))
     m_curves[oldWsName]->attach(NULL);
 
   // Update the plot
   plotWorkspaces();
 }
 
-
 /**
  * Handle replotting after a workspace has been changed.
  *
  * @param wsName Name of changed workspace
  * @param ws Pointer to changed workspace
  */
-void DataComparison::afterReplaceHandle(const std::string& wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
+void DataComparison::afterReplaceHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
   UNUSED_ARG(wsName);
   UNUSED_ARG(ws);
 
diff --git a/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp b/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp
index bbb7e3d71242d485f3a1cc8a93ebc36b5b2f2e44..d3fb62bd429a052cd2f19d8b37e88b3dfe45906b 100644
--- a/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp
+++ b/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp
@@ -16,18 +16,15 @@
 #include <QDesktopServices>
 #include <QUrl>
 
-//Add this class to the list of specialized dialogs in this namespace
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    DECLARE_SUBWINDOW(DirectConvertToEnergy)
-  }
+// Add this class to the list of specialized dialogs in this namespace
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(DirectConvertToEnergy)
+}
 }
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("DirectConvertToEnergy");
+namespace {
+Mantid::Kernel::Logger g_log("DirectConvertToEnergy");
 }
 
 using namespace MantidQt::CustomInterfaces;
@@ -37,51 +34,49 @@ using namespace MantidQt::CustomInterfaces;
 
 /**
  * Default constructor for class. Initializes interface pointers to NULL values.
- * @param parent :: This is a pointer to the "parent" object in Qt, most likely the main MantidPlot window.
+ * @param parent :: This is a pointer to the "parent" object in Qt, most likely
+ * the main MantidPlot window.
  */
-DirectConvertToEnergy::DirectConvertToEnergy(QWidget *parent) :
-  UserSubWindow(parent), m_directInstruments(NULL),
-  m_curInterfaceSetup(""), m_curEmodeType(DirectConvertToEnergy::Undefined), m_settingsGroup("CustomInterfaces/DirectConvertToEnergy"),
-  m_algRunner(new MantidQt::API::AlgorithmRunner(this))
-{
-  //Signals to report load instrument algo result
-  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(instrumentLoadingDone(bool)));
+DirectConvertToEnergy::DirectConvertToEnergy(QWidget *parent)
+    : UserSubWindow(parent), m_directInstruments(NULL), m_curInterfaceSetup(""),
+      m_curEmodeType(DirectConvertToEnergy::Undefined),
+      m_settingsGroup("CustomInterfaces/DirectConvertToEnergy"),
+      m_algRunner(new MantidQt::API::AlgorithmRunner(this)) {
+  // Signals to report load instrument algo result
+  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this,
+          SLOT(instrumentLoadingDone(bool)));
 }
 
 /**
  * Destructor
  */
-DirectConvertToEnergy::~DirectConvertToEnergy()
-{
-  //Make sure no algos are sunning after the window has been closed
+DirectConvertToEnergy::~DirectConvertToEnergy() {
+  // Make sure no algos are sunning after the window has been closed
   m_algRunner->cancelRunningAlgorithm();
 
   saveSettings();
 }
 
 /**
- * On user clicking the "help" button on the interface, directs their request to the relevant
+ * On user clicking the "help" button on the interface, directs their request to
+ * the relevant
  * interface's helpClicked() function.
  */
-void DirectConvertToEnergy::helpClicked()
-{
+void DirectConvertToEnergy::helpClicked() {
   m_directInstruments->helpClicked();
 }
 
 /**
- * This is the function called when the "Run" button is clicked. It will call the relevant function
+ * This is the function called when the "Run" button is clicked. It will call
+ * the relevant function
  * in the subclass.
  */
-void DirectConvertToEnergy::runClicked()
-{
-  m_directInstruments->runClicked();
-}
+void DirectConvertToEnergy::runClicked() { m_directInstruments->runClicked(); }
 
 /**
- * Sets up Qt UI file and connects signals, slots. 
+ * Sets up Qt UI file and connects signals, slots.
  */
-void DirectConvertToEnergy::initLayout()
-{
+void DirectConvertToEnergy::initLayout() {
   m_uiForm.setupUi(this);
   m_curInterfaceSetup = "";
   m_curEmodeType = Undefined;
@@ -91,30 +86,32 @@ void DirectConvertToEnergy::initLayout()
 
   // Signal / Slot Connections Set Up Here
 
-  // signal/slot connections to respond to changes in instrument selection combo boxes
-  connect(m_uiForm.cbInst, SIGNAL(instrumentSelectionChanged(const QString&)), this, SLOT(userSelectInstrument(const QString&)));
+  // signal/slot connections to respond to changes in instrument selection combo
+  // boxes
+  connect(m_uiForm.cbInst, SIGNAL(instrumentSelectionChanged(const QString &)),
+          this, SLOT(userSelectInstrument(const QString &)));
 
   // connect "?" (Help) Button
   connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
   // connect the "Run" button
   connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked()));
   // connect the "Manage User Directories" Button
-  connect(m_uiForm.pbManageDirectories, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
-
+  connect(m_uiForm.pbManageDirectories, SIGNAL(clicked()), this,
+          SLOT(openDirectoryDialog()));
 }
 
 /**
- * This function is ran after initLayout(), and runPythonCode is unavailable before this function
- * has run (because of the setup of the base class). For this reason, "setup" functions that require
+ * This function is ran after initLayout(), and runPythonCode is unavailable
+ * before this function
+ * has run (because of the setup of the base class). For this reason, "setup"
+ * functions that require
  * Python scripts are located here.
  */
-void DirectConvertToEnergy::initLocalPython()
-{
+void DirectConvertToEnergy::initLocalPython() {
   // select starting instrument
   readSettings();
 
-  if ( m_curInterfaceSetup == "" )
-  {
+  if (m_curInterfaceSetup == "") {
     userSelectInstrument(m_uiForm.cbInst->currentText());
   }
 }
@@ -122,8 +119,7 @@ void DirectConvertToEnergy::initLocalPython()
 /**
  * Read settings from the persistent store
  */
-void DirectConvertToEnergy::readSettings()
-{
+void DirectConvertToEnergy::readSettings() {
   QSettings settings;
   settings.beginGroup(m_settingsGroup);
   QString instrName = settings.value("instrument-name", "").toString();
@@ -135,17 +131,13 @@ void DirectConvertToEnergy::readSettings()
 /**
  * Save settings to a persistent storage
  */
-void DirectConvertToEnergy::saveSettings()
-{
+void DirectConvertToEnergy::saveSettings() {
   QSettings settings;
   settings.beginGroup(m_settingsGroup);
   QString instrName;
-  if( m_curEmodeType == Undefined )
-  {
+  if (m_curEmodeType == Undefined) {
     instrName = "";
-  }
-  else
-  {
+  } else {
     instrName = m_uiForm.cbInst->currentText();
   }
 
@@ -154,31 +146,34 @@ void DirectConvertToEnergy::saveSettings()
 }
 
 /**
- * Sets up the initial instrument for the interface. This value is taken from the users'
+ * Sets up the initial instrument for the interface. This value is taken from
+ * the users'
  * settings in the menu View -> Preferences -> Mantid -> Instrument
  * @param name :: The name of the default instrument
  */
-void DirectConvertToEnergy::setDefaultInstrument(const QString & name)
-{
-  if( name.isEmpty() ) return;
+void DirectConvertToEnergy::setDefaultInstrument(const QString &name) {
+  if (name.isEmpty())
+    return;
 
   int index = m_uiForm.cbInst->findText(name);
-  if( index >= 0 )
-  {
+  if (index >= 0) {
     m_uiForm.cbInst->setCurrentIndex(index);
   }
 }
 
 /**
- * This function: 1. loads the instrument and gets the value of deltaE-mode parameter
- *				 2. Based on this value, makes the necessary changes to the form setup (direct or indirect).
+ * This function: 1. loads the instrument and gets the value of deltaE-mode
+ *parameter
+ *				 2. Based on this value, makes the necessary
+ *changes
+ *to the form setup (direct or indirect).
  * @param name :: name of the instrument from the QComboBox
  */
-void DirectConvertToEnergy::instrumentSelectChanged(const QString& name)
-{
-  QString defFile = (Mantid::API::ExperimentInfo::getInstrumentFilename(name.toStdString())).c_str();
-  if((defFile == "") || !m_uiForm.cbInst->isVisible())
-  {
+void DirectConvertToEnergy::instrumentSelectChanged(const QString &name) {
+  QString defFile =
+      (Mantid::API::ExperimentInfo::getInstrumentFilename(name.toStdString()))
+          .c_str();
+  if ((defFile == "") || !m_uiForm.cbInst->isVisible()) {
     g_log.error("Instrument loading failed!");
     m_uiForm.cbInst->setEnabled(true);
     m_uiForm.pbRun->setEnabled(true);
@@ -189,12 +184,14 @@ void DirectConvertToEnergy::instrumentSelectChanged(const QString& name)
 
   QString outWS = "__empty_" + m_uiForm.cbInst->currentText();
 
-  Mantid::API::IAlgorithm_sptr instLoader = Mantid::API::AlgorithmManager::Instance().create("LoadEmptyInstrument", -1);
+  Mantid::API::IAlgorithm_sptr instLoader =
+      Mantid::API::AlgorithmManager::Instance().create("LoadEmptyInstrument",
+                                                       -1);
   instLoader->initialize();
   instLoader->setProperty("Filename", defFile.toStdString());
   instLoader->setProperty("OutputWorkspace", outWS.toStdString());
- 
-  //Ensure no other algorithm is running
+
+  // Ensure no other algorithm is running
   m_algRunner->cancelRunningAlgorithm();
   m_algRunner->startAlgorithm(instLoader);
 }
@@ -202,23 +199,24 @@ void DirectConvertToEnergy::instrumentSelectChanged(const QString& name)
 /**
  * Tasks to be carried out after an empty instrument has finished loading
  */
-void DirectConvertToEnergy::instrumentLoadingDone(bool error)
-{
-  QString curInstPrefix = m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString();
-  if((curInstPrefix == "") || error)
-  {
-    g_log.error("Instrument loading failed! (this can be caused by having both direct and indirect interfaces open)");
+void DirectConvertToEnergy::instrumentLoadingDone(bool error) {
+  QString curInstPrefix =
+      m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString();
+  if ((curInstPrefix == "") || error) {
+    g_log.error("Instrument loading failed! (this can be caused by having both "
+                "direct and indirect interfaces open)");
     m_uiForm.cbInst->setEnabled(true);
     m_uiForm.pbRun->setEnabled(true);
     return;
   }
 
-  if(m_directInstruments == NULL)
-  {
-    m_directInstruments = new Homer(qobject_cast<QWidget*>(this->parent()), m_uiForm);
+  if (m_directInstruments == NULL) {
+    m_directInstruments =
+        new Homer(qobject_cast<QWidget *>(this->parent()), m_uiForm);
     m_directInstruments->initLayout();
-    connect(m_directInstruments, SIGNAL(runAsPythonScript(const QString&, bool)),
-        this, SIGNAL(runAsPythonScript(const QString&, bool)));
+    connect(m_directInstruments,
+            SIGNAL(runAsPythonScript(const QString &, bool)), this,
+            SIGNAL(runAsPythonScript(const QString &, bool)));
     m_directInstruments->initializeLocalPython();
   }
   m_directInstruments->setIDFValues(curInstPrefix);
@@ -231,8 +229,7 @@ void DirectConvertToEnergy::instrumentLoadingDone(bool error)
  * If the instrument selection has changed, calls instrumentSelectChanged
  * @param prefix :: instrument name from QComboBox object
  */
-void DirectConvertToEnergy::userSelectInstrument(const QString& prefix) 
-{
+void DirectConvertToEnergy::userSelectInstrument(const QString &prefix) {
   // Search for files for the current selected instrument
   m_uiForm.runFiles->setInstrumentOverride(prefix);
   m_uiForm.mapFile->setInstrumentOverride(prefix);
@@ -241,13 +238,12 @@ void DirectConvertToEnergy::userSelectInstrument(const QString& prefix)
   m_uiForm.absMapFile->setInstrumentOverride(prefix);
   m_uiForm.absWhiteFile->setInstrumentOverride(prefix);
 
-  if ( prefix != m_curInterfaceSetup )
-  {
+  if (prefix != m_curInterfaceSetup) {
     // Remove the old empty instrument workspace if it is there
     std::string ws_name = "__empty_" + m_curInterfaceSetup.toStdString();
-    Mantid::API::AnalysisDataServiceImpl& dataStore = Mantid::API::AnalysisDataService::Instance();
-    if( dataStore.doesExist(ws_name) )
-    {
+    Mantid::API::AnalysisDataServiceImpl &dataStore =
+        Mantid::API::AnalysisDataService::Instance();
+    if (dataStore.doesExist(ws_name)) {
       dataStore.remove(ws_name);
     }
 
@@ -257,9 +253,9 @@ void DirectConvertToEnergy::userSelectInstrument(const QString& prefix)
   }
 }
 
-void DirectConvertToEnergy::openDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+void DirectConvertToEnergy::openDirectoryDialog() {
+  MantidQt::API::ManageUserDirectories *ad =
+      new MantidQt::API::ManageUserDirectories(this);
   ad->show();
   ad->setFocus();
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFBackgroundRemover.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFBackgroundRemover.cpp
index 9f7aa81a09529911da3128d2e73f50ff835a8cb9..5c988b560fc8c5e04579d4b20e713a422c0454c4 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFBackgroundRemover.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFBackgroundRemover.cpp
@@ -28,14 +28,10 @@ DECLARE_SUBWINDOW(BackgroundRemover)
  *              **  Public Methods  **
  *              **********************/
 
-BackgroundRemover::BackgroundRemover(QWidget *parent) :
-  UserSubWindow{parent},
-  m_sliceSelector(),
-  m_inputDataControl(),
-  m_displayControl(),
-  m_fitControl{nullptr},
-  m_fourierTransform{nullptr} {
-  //nothing in the body
+BackgroundRemover::BackgroundRemover(QWidget *parent)
+    : UserSubWindow{parent}, m_sliceSelector(), m_inputDataControl(),
+      m_displayControl(), m_fitControl{nullptr}, m_fourierTransform{nullptr} {
+  // nothing in the body
 }
 
 /**
@@ -59,7 +55,7 @@ void BackgroundRemover::initLayout() {
   m_uiForm.splitterModelResiduals->setSizes(sizes);
   // user wants to load new slices
   connect(m_uiForm.pushButtonSummonSliceSelector, SIGNAL(clicked()), this,
-    SLOT(summonSliceSelector()));
+          SLOT(summonSliceSelector()));
   // user wants help
   connect(m_uiForm.pushButtonHelp, SIGNAL(clicked()), this, SLOT(showHelp()));
 }
@@ -73,23 +69,23 @@ void BackgroundRemover::initLayout() {
  */
 void BackgroundRemover::showHelp() {
   MantidQt::API::HelpWindow::showCustomInterface(
-    NULL, QString("DPDFBackgroundRemover"));
+      NULL, QString("DPDFBackgroundRemover"));
 }
 
 /**
  * @brief Spawn the SliceSelector widget to load a matrix workspace (or file)
  * containing they dynamic structure factor.
  */
-void BackgroundRemover::summonSliceSelector(){
-  if(!m_sliceSelector){
+void BackgroundRemover::summonSliceSelector() {
+  if (!m_sliceSelector) {
     // Initialize all the components
     // Initialize the slice selector
     m_sliceSelector = Mantid::Kernel::make_unique<SliceSelector>(this);
     // Initialize the InputDataControl object
     m_inputDataControl = Mantid::Kernel::make_unique<InputDataControl>();
     // Initialize the DisplayControl object
-    m_displayControl = Mantid::Kernel::make_unique<DisplayControl>
-      (m_inputDataControl.get(), m_uiForm.displayModelFit);
+    m_displayControl = Mantid::Kernel::make_unique<DisplayControl>(
+        m_inputDataControl.get(), m_uiForm.displayModelFit);
     m_displayControl->init();
     // Initialize the FitControl object
     m_fitControl->setInputDataControl(m_inputDataControl.get());
@@ -101,30 +97,26 @@ void BackgroundRemover::summonSliceSelector(){
     // user loaded a workspace in the SliceSelector
     // (use get() for required raw pointer)
     connect(m_sliceSelector.get(), SIGNAL(signalSlicesLoaded(QString)),
-      m_inputDataControl.get(), SLOT(updateWorkspace(QString)));
+            m_inputDataControl.get(), SLOT(updateWorkspace(QString)));
     // user selected a slice for fitting in SliceSelector
     connect(m_sliceSelector.get(),
-      SIGNAL(signalSliceForFittingSelected(size_t)),
-      m_inputDataControl.get(), SLOT(updateSliceForFitting(size_t)));
+            SIGNAL(signalSliceForFittingSelected(size_t)),
+            m_inputDataControl.get(), SLOT(updateSliceForFitting(size_t)));
     // slice for fitting updated
     connect(m_inputDataControl.get(), SIGNAL(signalSliceForFittingUpdated()),
-      m_displayControl.get(), SLOT(updateSliceForFitting()));
+            m_displayControl.get(), SLOT(updateSliceForFitting()));
     m_fitControl->setConnections();
     m_fourierTransform->setConnections();
-    connect(m_uiForm.pbFourier, SIGNAL(clicked()),
-      m_fourierTransform, SLOT(transform()));
-    connect(m_uiForm.pbClearFourierPlot, SIGNAL(clicked()),
-      m_fourierTransform, SLOT(clearFourierPlot()));
+    connect(m_uiForm.pbFourier, SIGNAL(clicked()), m_fourierTransform,
+            SLOT(transform()));
+    connect(m_uiForm.pbClearFourierPlot, SIGNAL(clicked()), m_fourierTransform,
+            SLOT(clearFourierPlot()));
   }
 
   m_sliceSelector->show();
-  m_sliceSelector->raise(); // raise on top
+  m_sliceSelector->raise();          // raise on top
   m_sliceSelector->activateWindow(); // set as active window
 }
-
-
-
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFDisplayControl.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFDisplayControl.cpp
index 1faa2edac0c89e90f2339cf885da11a60e438857..9f84236a5fa44e4759b28ba0a792f3270793d629 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFDisplayControl.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFDisplayControl.cpp
@@ -14,7 +14,7 @@
 #include <iostream>
 
 namespace {
-  Mantid::Kernel::Logger g_log("DynamicPDF");
+Mantid::Kernel::Logger g_log("DynamicPDF");
 }
 
 namespace MantidQt {
@@ -33,13 +33,12 @@ using dcRange = MantidQt::MantidWidgets::DisplayCurveFit::dcRange;
  * @param inputDataControl to handle the input data
  * @param displayModelFit to handle displaying the curves
  */
-DisplayControl::DisplayControl(InputDataControl *inputDataControl,
-    MantidQt::MantidWidgets::DisplayCurveFit *displayModelFit) :
-  m_inputDataControl{inputDataControl},
-  m_displayModelFit{displayModelFit},
-  m_fitRangeSelector{nullptr},
-  m_dataShown(),
-  m_dataShownName{"__DPDFDataShown"} {
+DisplayControl::DisplayControl(
+    InputDataControl *inputDataControl,
+    MantidQt::MantidWidgets::DisplayCurveFit *displayModelFit)
+    : m_inputDataControl{inputDataControl}, m_displayModelFit{displayModelFit},
+      m_fitRangeSelector{nullptr}, m_dataShown(),
+      m_dataShownName{"__DPDFDataShown"} {
   // nothing in the body
 }
 
@@ -53,10 +52,10 @@ void DisplayControl::init() {
 
   // SIGNAL/SLOT connections
   // user manipulated the fit-range selector
-  connect(m_fitRangeSelector, SIGNAL(minValueChanged(double)),
-    this, SLOT(rangeSelectorFitUpdated(double)));
-  connect(m_fitRangeSelector, SIGNAL(maxValueChanged(double)),
-    this, SLOT(rangeSelectorFitUpdated(double)));
+  connect(m_fitRangeSelector, SIGNAL(minValueChanged(double)), this,
+          SLOT(rangeSelectorFitUpdated(double)));
+  connect(m_fitRangeSelector, SIGNAL(maxValueChanged(double)), this,
+          SLOT(rangeSelectorFitUpdated(double)));
 }
 
 /**
@@ -67,9 +66,9 @@ DisplayControl::~DisplayControl() = default;
 /**
  * @brief get the current boundaries of the rangeSelectorFit
  */
-std::pair<double,double> DisplayControl::getFitMinMax() {
-  return std::pair<double,double>(m_fitRangeSelector->getMinimum(),
-    m_fitRangeSelector->getMaximum());
+std::pair<double, double> DisplayControl::getFitMinMax() {
+  return std::pair<double, double>(m_fitRangeSelector->getMinimum(),
+                                   m_fitRangeSelector->getMaximum());
 }
 
 /**
@@ -94,19 +93,22 @@ void DisplayControl::setFitMax(const double &boundary) {
  * @brief Reset the data to be displayed. Remove model evaluation curves
  */
 void DisplayControl::updateSliceForFitting() {
-  try{
-    //check the workspace is registered in the Analysis Data Service
-    auto workspace = Mantid::API::AnalysisDataService::Instance().retrieveWS
-    <Mantid::API::MatrixWorkspace>(m_dataShownName);
+  try {
+    // check the workspace is registered in the Analysis Data Service
+    auto workspace =
+        Mantid::API::AnalysisDataService::Instance()
+            .retrieveWS<Mantid::API::MatrixWorkspace>(m_dataShownName);
     // delete the workspace being shown
-    auto deleteWsAlg = Mantid::API::AlgorithmManager::Instance().create("DeleteWorkspace");
+    auto deleteWsAlg =
+        Mantid::API::AlgorithmManager::Instance().create("DeleteWorkspace");
     deleteWsAlg->initialize();
     deleteWsAlg->setChild(true);
     deleteWsAlg->setLogging(false);
     deleteWsAlg->setProperty("Workspace", m_dataShownName);
     deleteWsAlg->execute();
-  }catch (Mantid::Kernel::Exception::NotFoundError &) {}
-  if(m_displayModelFit->hasCurve(curveType::fit)) {
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+  }
+  if (m_displayModelFit->hasCurve(curveType::fit)) {
     m_displayModelFit->removeSpectrum(curveType::fit);
     m_displayModelFit->removeSpectrum(curveType::residuals);
   }
@@ -117,8 +119,9 @@ void DisplayControl::updateSliceForFitting() {
   auto energy = m_inputDataControl->getSelectedEnergy();
   std::ostringstream energyLabelStream;
   energyLabelStream << energy;
-  //create internal workspace containing the non-zero signal
-  auto createWsAlg = Mantid::API::AlgorithmManager::Instance().create("CreateWorkspace");
+  // create internal workspace containing the non-zero signal
+  auto createWsAlg =
+      Mantid::API::AlgorithmManager::Instance().create("CreateWorkspace");
   createWsAlg->initialize();
   createWsAlg->setChild(true);
   createWsAlg->setLogging(false);
@@ -132,9 +135,9 @@ void DisplayControl::updateSliceForFitting() {
   createWsAlg->setProperty("VerticalAxisValues", energyLabelStream.str());
   createWsAlg->execute();
   Mantid::API::MatrixWorkspace_sptr m_dataShown =
-    createWsAlg->getProperty("OutputWorkspace");
-  Mantid::API::AnalysisDataService::Instance()
-    .add(m_dataShownName, m_dataShown);
+      createWsAlg->getProperty("OutputWorkspace");
+  Mantid::API::AnalysisDataService::Instance().add(m_dataShownName,
+                                                   m_dataShown);
   // show the workspace with appropriate range selector
   m_displayModelFit->addSpectrum(curveType::data, m_dataShown);
   auto curveRange = m_displayModelFit->getCurveRange(curveType::data);
@@ -142,7 +145,7 @@ void DisplayControl::updateSliceForFitting() {
   rangeSelectorFit->setRange(curveRange.first, curveRange.second);
   rangeSelectorFit->setMinimum(curveRange.first);
   rangeSelectorFit->setMaximum(curveRange.second);
-  //emit signalRangeSelectorFitUpdated();
+  // emit signalRangeSelectorFitUpdated();
 }
 
 /**
@@ -158,13 +161,14 @@ void DisplayControl::rangeSelectorFitUpdated(const double &boundary) {
  * @param workspaceName workspace name containing the evaluation of the model
  */
 void DisplayControl::updateModelEvaluationDisplay(
-  const QString &workspaceName) {
+    const QString &workspaceName) {
   auto modelWorkspace = Mantid::API::AnalysisDataService::Instance()
-    .retrieveWS<Mantid::API::MatrixWorkspace>(workspaceName.toStdString());
-  if(!modelWorkspace) {
+                            .retrieveWS<Mantid::API::MatrixWorkspace>(
+                                workspaceName.toStdString());
+  if (!modelWorkspace) {
     throw std::runtime_error("Unfound workspace containing model evaluation");
   }
-  if(m_displayModelFit->hasCurve(curveType::fit)) {
+  if (m_displayModelFit->hasCurve(curveType::fit)) {
     m_displayModelFit->removeSpectrum(curveType::fit);
     m_displayModelFit->removeSpectrum(curveType::residuals);
   }
@@ -172,9 +176,6 @@ void DisplayControl::updateModelEvaluationDisplay(
   m_displayModelFit->addSpectrum(curveType::fit, modelWorkspace, 1);
   m_displayModelFit->addSpectrum(curveType::residuals, modelWorkspace, 2);
 }
-
-
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitControl.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitControl.cpp
index 39cd23676ac6f85536d3659ed55955e00935c594..b024c73c915610a26a2e4a621925657f861213a4 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitControl.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitControl.cpp
@@ -1,27 +1,27 @@
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h"
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h"
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h"
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFDisplayControl.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidAPI/IFunction.h"
 #include "MantidQtMantidWidgets/FunctionBrowser.h"
 #include "MantidQtMantidWidgets/FitOptionsBrowser.h"
 #include "MantidQtAPI/AlgorithmRunner.h"
 #include "MantidKernel/Logger.h"
 #include "MantidAPI/AlgorithmManager.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QMessageBox>
 #include <QMenu>
 #include <QPushButton>
 #include <QSettings>
 #include <QSignalMapper>
-//System headers
-#include<iostream>
+// System headers
+#include <iostream>
 
 namespace {
-  Mantid::Kernel::Logger g_log("DynamicPDF");
+Mantid::Kernel::Logger g_log("DynamicPDF");
 }
 
 namespace MantidQt {
@@ -35,15 +35,11 @@ namespace DynamicPDF {
 /**
  * @brief Constructor
  */
-FitControl::FitControl(QWidget *parent) :
-  QWidget(parent),
-  m_functionBrowser{nullptr},
-  m_fitOptionsBrowser{nullptr},
-  m_inputDataControl{nullptr},
-  m_displayControl{nullptr},
-  m_fitRunner(),
-  m_individualFitName{"DPDFIndivFit"},
-  m_modelEvaluationName{"DPDFModelEval"} {
+FitControl::FitControl(QWidget *parent)
+    : QWidget(parent), m_functionBrowser{nullptr}, m_fitOptionsBrowser{nullptr},
+      m_inputDataControl{nullptr}, m_displayControl{nullptr}, m_fitRunner(),
+      m_individualFitName{"DPDFIndivFit"},
+      m_modelEvaluationName{"DPDFModelEval"} {
   this->initLayout();
 }
 
@@ -63,9 +59,7 @@ FitControl::~FitControl() {
  * only single fitting is implemented.
  * @return 1
  */
-int FitControl::getNumberOfSpectra() const {
-  return 1;
-}
+int FitControl::getNumberOfSpectra() const { return 1; }
 
 /*                *********************
  *                **  Private Slots  **
@@ -82,11 +76,11 @@ void FitControl::updateFitRangeFromDisplayControl() {
   // the fit-range in the property browser, wwhich in turn changed
   // the fit-range in the DisplayCurveFit, which in turn sent a
   //  signal that is being received now by this slot.
-  if( (startX != fitRange.first) || (endX != fitRange.second) ) {
+  if ((startX != fitRange.first) || (endX != fitRange.second)) {
     m_fitOptionsBrowser->setProperty(QString::fromStdString("StartX"),
-      QString::number(fitRange.first));
+                                     QString::number(fitRange.first));
     m_fitOptionsBrowser->setProperty(QString::fromStdString("EndX"),
-      QString::number(fitRange.second));
+                                     QString::number(fitRange.second));
   }
 }
 
@@ -97,13 +91,13 @@ void FitControl::updateFitRangeFromDisplayControl() {
  */
 void FitControl::updateFitRangeSelector(const QString &propertyName) {
   auto name = QString::fromStdString("StartX");
-  if( propertyName== name) {
+  if (propertyName == name) {
     auto startX = (m_fitOptionsBrowser->getProperty(propertyName)).toDouble();
     m_displayControl->setFitMin(startX);
     return;
   }
   name = QString::fromStdString("EndX");
-  if( propertyName== name) {
+  if (propertyName == name) {
     auto endX = (m_fitOptionsBrowser->getProperty(propertyName)).toDouble();
     m_displayControl->setFitMax(endX);
     return;
@@ -111,23 +105,20 @@ void FitControl::updateFitRangeSelector(const QString &propertyName) {
 }
 
 void FitControl::fit() {
-  if(!isSliceSelectedForFitting()){
-    QMessageBox::warning( this, "MantidPlot - Warning",
-      "Select a slice first." );
+  if (!isSliceSelectedForFitting()) {
+    QMessageBox::warning(this, "MantidPlot - Warning", "Select a slice first.");
     return;
   }
-  if ( !m_functionBrowser->hasFunction() ) {
-    QMessageBox::warning( this, "MantidPlot - Warning","Function wasn't set." );
+  if (!m_functionBrowser->hasFunction()) {
+    QMessageBox::warning(this, "MantidPlot - Warning", "Function wasn't set.");
     return;
   }
   auto fittingType = m_fitOptionsBrowser->getCurrentFittingType();
   if (fittingType == MantidWidgets::FitOptionsBrowser::Simultaneous) {
     fitSimultaneous();
-  }
-  else if (fittingType == MantidWidgets::FitOptionsBrowser::Sequential) {
+  } else if (fittingType == MantidWidgets::FitOptionsBrowser::Sequential) {
     fitSequential();
-  }
-  else {
+  } else {
     throw std::logic_error("Unrecognised fitting type");
   }
 }
@@ -137,7 +128,7 @@ void FitControl::fit() {
  * @param error do nothing if fitting did not complete
  */
 void FitControl::finishIndividualFit(bool error) {
-  if(error) {
+  if (error) {
     return;
   }
   std::cout << "FitControl::finishIndividualFit\n";
@@ -145,12 +136,12 @@ void FitControl::finishIndividualFit(bool error) {
   fun = m_fitRunner->getAlgorithm()->getProperty("Function");
   // prevent the function browser to emit signal after update
   disconnect(m_functionBrowser,
-    SIGNAL(parameterChanged(const QString &, const QString &)),
-    this, SLOT(slotEvaluateModel(const QString &, const QString &)));
+             SIGNAL(parameterChanged(const QString &, const QString &)), this,
+             SLOT(slotEvaluateModel(const QString &, const QString &)));
   this->updateFunctionBrowser(fun);
   connect(m_functionBrowser,
-    SIGNAL(parameterChanged(const QString &, const QString &)),
-    this, SLOT(slotEvaluateModel(const QString &, const QString &)));
+          SIGNAL(parameterChanged(const QString &, const QString &)), this,
+          SLOT(slotEvaluateModel(const QString &, const QString &)));
   const bool evaluateModel{true};
   this->fitIndividual(evaluateModel);
 }
@@ -160,20 +151,20 @@ void FitControl::finishIndividualFit(bool error) {
  * This is just a slot matching the signal from the function browser
  * that calls evaluateModel()
  */
-void FitControl::slotEvaluateModel(const QString &, const QString &){
+void FitControl::slotEvaluateModel(const QString &, const QString &) {
   const bool evaluateModel{true};
   this->fitIndividual(evaluateModel);
 }
 
- /*
- * @brief Emit signal after model evaluation
- */
+/*
+* @brief Emit signal after model evaluation
+*/
 void FitControl::finishModelEvaluation(bool error) {
-  if(error) {
+  if (error) {
     return;
   }
   emit signalModelEvaluationFinished(
-    QString::fromStdString(m_modelEvaluationName + "_Workspace"));
+      QString::fromStdString(m_modelEvaluationName + "_Workspace"));
 }
 
 /*
@@ -181,7 +172,7 @@ void FitControl::finishModelEvaluation(bool error) {
  * @param modelName name of the model function
  */
 void FitControl::updateFunctionBrowserWithBuiltInModel(
-  const QString &modelName){
+    const QString &modelName) {
   this->updateFunctionBrowser("BuiltInModels", modelName);
 }
 
@@ -201,14 +192,14 @@ void FitControl::initLayout() {
 
   // set SIGNAL/SLOTS connections between "internal" objects
   // update the range selector in StartX or EndX has changed in the browser
-  connect(m_fitOptionsBrowser, SIGNAL(doublePropertyChanged(QString)),
-    this, SLOT(updateFitRangeSelector(QString)));
+  connect(m_fitOptionsBrowser, SIGNAL(doublePropertyChanged(QString)), this,
+          SLOT(updateFitRangeSelector(QString)));
   // user clicks the Fit push buttom to carry out the fit
-  connect( m_uiForm.pushButtonFit, SIGNAL(clicked()), this, SLOT(fit()) );
+  connect(m_uiForm.pushButtonFit, SIGNAL(clicked()), this, SLOT(fit()));
   // update the model evaluation after changes in the function browser
   connect(m_functionBrowser,
-    SIGNAL(parameterChanged(const QString &, const QString &)),
-    this, SLOT(slotEvaluateModel(const QString &, const QString &)));
+          SIGNAL(parameterChanged(const QString &, const QString &)), this,
+          SLOT(slotEvaluateModel(const QString &, const QString &)));
 }
 
 /**
@@ -224,10 +215,11 @@ bool FitControl::isSliceSelectedForFitting() {
  */
 void FitControl::setConnections() {
   // rangeSelectorFit has been changed in the DisplayControl
-  connect(m_displayControl, SIGNAL(signalRangeSelectorFitUpdated()),
-    this, SLOT(updateFitRangeFromDisplayControl()));
+  connect(m_displayControl, SIGNAL(signalRangeSelectorFitUpdated()), this,
+          SLOT(updateFitRangeFromDisplayControl()));
   connect(this, SIGNAL(signalModelEvaluationFinished(const QString &)),
-    m_displayControl, SLOT(updateModelEvaluationDisplay(const QString &)));
+          m_displayControl,
+          SLOT(updateModelEvaluationDisplay(const QString &)));
 }
 
 /**
@@ -249,7 +241,7 @@ void FitControl::setDisplayControl(DisplayControl *displayControl) {
  */
 void FitControl::fitSequential() {
   int n = this->getNumberOfSpectra();
-  if(n==1) {
+  if (n == 1) {
     this->fitIndividual();
     return;
   }
@@ -261,7 +253,7 @@ void FitControl::fitSequential() {
  */
 void FitControl::fitSimultaneous() {
   int n = this->getNumberOfSpectra();
-  if(n==1) {
+  if (n == 1) {
     this->fitIndividual();
     return;
   }
@@ -278,38 +270,36 @@ void FitControl::fitIndividual(const bool &isEvaluation) {
     auto fun = m_functionBrowser->getFunction();
     auto fit = Mantid::API::AlgorithmManager::Instance().create("Fit");
     fit->initialize();
-    fit->setProperty("Function", fun );
+    fit->setProperty("Function", fun);
     fit->setPropertyValue("InputWorkspace",
-      m_inputDataControl->getWorkspaceName());
+                          m_inputDataControl->getWorkspaceName());
     auto index = static_cast<int>(m_inputDataControl->getWorkspaceIndex());
     fit->setProperty("WorkspaceIndex", index);
     m_fitOptionsBrowser->copyPropertiesToAlgorithm(*fit);
-    m_fitRunner.reset( new API::AlgorithmRunner() );
+    m_fitRunner.reset(new API::AlgorithmRunner());
     if (isEvaluation) {
       fit->setPropertyValue("Output", m_modelEvaluationName);
       fit->setProperty("MaxIterations", 0);
       auto range = m_inputDataControl->getCurrentRange();
       fit->setProperty("StartX", range.first);
       fit->setProperty("EndX", range.second);
-      connect( m_fitRunner.get(),SIGNAL(algorithmComplete(bool)),
-        this, SLOT(finishModelEvaluation(bool)), Qt::QueuedConnection );
-    }
-    else {
+      connect(m_fitRunner.get(), SIGNAL(algorithmComplete(bool)), this,
+              SLOT(finishModelEvaluation(bool)), Qt::QueuedConnection);
+    } else {
       fit->setPropertyValue("Output", m_individualFitName);
-      connect( m_fitRunner.get(),SIGNAL(algorithmComplete(bool)),
-        this, SLOT(finishIndividualFit(bool)), Qt::QueuedConnection );
+      connect(m_fitRunner.get(), SIGNAL(algorithmComplete(bool)), this,
+              SLOT(finishIndividualFit(bool)), Qt::QueuedConnection);
     }
     m_fitRunner->startAlgorithm(fit);
-  }
-  catch(std::exception& e) {
+  } catch (std::exception &e) {
     QString mess(e.what());
     const int maxSize = 500;
-     if ( mess.size() > maxSize )  {
-      mess = mess.mid(0,maxSize);
+    if (mess.size() > maxSize) {
+      mess = mess.mid(0, maxSize);
       mess += "...";
     }
-    QMessageBox::critical( this, "DynamicPDF - Error",
-      QString("fitIndividual failed:\n\n  %1").arg(mess) );
+    QMessageBox::critical(this, "DynamicPDF - Error",
+                          QString("fitIndividual failed:\n\n  %1").arg(mess));
   }
 } // FitControl::fitIndividual
 
@@ -327,9 +317,9 @@ void FitControl::updateFunctionBrowser(Mantid::API::IFunction_sptr fun) {
  * @param modelName name of the model function
  */
 void FitControl::updateFunctionBrowser(const QString &directory,
-  const QString &modelName) {
+                                       const QString &modelName) {
   QSettings settings;
-  settings.beginGroup("Mantid/DynamicPDF/"+directory);
+  settings.beginGroup("Mantid/DynamicPDF/" + directory);
   QString function = settings.value(modelName).toString();
   m_functionBrowser->setFunction(function);
 }
@@ -345,7 +335,7 @@ void FitControl::initBuiltInModels() {
   QSettings settings;
   settings.beginGroup("Mantid/DynamicPDF/BuiltInModels");
   QStringList names = settings.childKeys();
-  if(names.size()==0) {
+  if (names.size() == 0) {
     this->saveBuiltInModels();
   }
   this->loadBuiltInModels(menuBuiltIn);
@@ -361,11 +351,15 @@ void FitControl::saveBuiltInModels() {
   settings.beginGroup("Mantid/DynamicPDF/BuiltInModels");
   QMap<QString, QString> models;
   // Quadratic
-  models["Quadratic"]="name=Quadratic,A0=0,A1=0,A2=0";
+  models["Quadratic"] = "name=Quadratic,A0=0,A1=0,A2=0";
   // Gaussian plus a linear background
-  models["Gaussian+LB"]="name=Gaussian,Height=0,PeakCentre=0,Sigma=0;name=LinearBackground,A0=0,A1=0";
+  models["Gaussian+LB"] = "name=Gaussian,Height=0,PeakCentre=0,Sigma=0;name="
+                          "LinearBackground,A0=0,A1=0";
   // (Quadratic times Gaussian ) plus linear background
-  models["QuadXGauss+LB"]="(composite=ProductFunction,NumDeriv=false;name=Quadratic,A0=0,A1=0,A2=0;name=Gaussian,Height=0,PeakCentre=0,Sigma=0);name=LinearBackground,A0=0,A1=0";
+  models["QuadXGauss+LB"] = "(composite=ProductFunction,NumDeriv=false;name="
+                            "Quadratic,A0=0,A1=0,A2=0;name=Gaussian,Height=0,"
+                            "PeakCentre=0,Sigma=0);name=LinearBackground,A0=0,"
+                            "A1=0";
   for (auto modelName : models.keys()) {
     settings.setValue(modelName, models[modelName]);
   }
@@ -381,12 +375,12 @@ void FitControl::loadBuiltInModels(QMenu *menuModels) {
   QStringList modelNames = settings.childKeys();
   for (int i = 0; i < modelNames.size(); i++) {
     QAction *actionModel = new QAction(modelNames.at(i), this);
-     mapperModel->setMapping(actionModel, modelNames.at(i));
-     connect(actionModel, SIGNAL(activated()), mapperModel, SLOT(map()));
-     menuModels->addAction(actionModel);
+    mapperModel->setMapping(actionModel, modelNames.at(i));
+    connect(actionModel, SIGNAL(activated()), mapperModel, SLOT(map()));
+    menuModels->addAction(actionModel);
   }
-  connect(mapperModel, SIGNAL(mapped(const QString &)),
-    this, SLOT(updateFunctionBrowserWithBuiltInModel(const QString &)));
+  connect(mapperModel, SIGNAL(mapped(const QString &)), this,
+          SLOT(updateFunctionBrowserWithBuiltInModel(const QString &)));
 }
 /**
  * @brief Load the models from the Mantid settings
@@ -404,7 +398,6 @@ void FitControl::initCustomModels() {
   menuCustom->addAction(actionLoad);
   menuCustom->addAction(actionDelete);
 }
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitOptionsBrowser.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitOptionsBrowser.cpp
index 65165935b37bacdca8d85df6253e5cb4190d0183..aff82bc86d864889268c96f29335e564551aed7d 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitOptionsBrowser.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFitOptionsBrowser.cpp
@@ -1,16 +1,16 @@
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFFitOptionsBrowser.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "qttreepropertybrowser.h"
 #include "qtpropertymanager.h"
-//3rd party library headers
+// 3rd party library headers
 #include "MantidKernel/Logger.h"
-//System headers
+// System headers
 //#include<iostream>
 
 namespace {
-  Mantid::Kernel::Logger g_log("DynamicPDF");
+Mantid::Kernel::Logger g_log("DynamicPDF");
 }
 
 using Fittype = MantidQt::MantidWidgets::FitOptionsBrowser::FittingType;
@@ -26,8 +26,8 @@ namespace DynamicPDF {
 /**
  * @brief Constructor, override fitting type with Sequential
  */
-DPDFFitOptionsBrowser::DPDFFitOptionsBrowser(QWidget *parent) :
-  FitOptionsBrowser(parent, Fittype::Sequential) {
+DPDFFitOptionsBrowser::DPDFFitOptionsBrowser(QWidget *parent)
+    : FitOptionsBrowser(parent, Fittype::Sequential) {
   this->createAdditionalProperties();
   this->customizeBrowser();
 }
@@ -39,7 +39,7 @@ DPDFFitOptionsBrowser::DPDFFitOptionsBrowser(QWidget *parent) :
 /**
  * @brief Include properties not defined in the parent class
  */
-void DPDFFitOptionsBrowser::createAdditionalProperties(){
+void DPDFFitOptionsBrowser::createAdditionalProperties() {
   // fitting range
   m_startX = this->addDoubleProperty("StartX");
   m_endX = this->addDoubleProperty("EndX");
@@ -48,14 +48,13 @@ void DPDFFitOptionsBrowser::createAdditionalProperties(){
 /**
  * @brief Show additional properties in the browser
  */
-void DPDFFitOptionsBrowser::customizeBrowser(){
+void DPDFFitOptionsBrowser::customizeBrowser() {
   // show the fitting range
   this->displayProperty("StartX");
   this->displayProperty("EndX");
   this->setProperty("CreateOutput", "true");
 }
 
-
 } // DynamicPDF
 } // CustomInterfaces
 } // MantidQt
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFourierTransform.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFourierTransform.cpp
index 7a6521d0b37cba10a06ac040c5e3c4913afa3650..547b3118b54c679342d3f97c45684002ff0a860e 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFourierTransform.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFFourierTransform.cpp
@@ -1,9 +1,9 @@
-//Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
-//Mantid Headers from the same project
+// Mantid Coding standars <http://www.mantidproject.org/Coding_Standards>
+// Mantid Headers from the same project
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFFourierTransform.h"
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFInputDataControl.h"
 #include "MantidQtCustomInterfaces/DynamicPDF/DPDFFitControl.h"
-//Mantid headers from other projects
+// Mantid headers from other projects
 #include "MantidKernel/Logger.h"
 #include "MantidAPI/AnalysisDataService.h"
 #include "MantidAPI/WorkspaceFactory.h"
@@ -12,13 +12,13 @@
 #include "MantidQtMantidWidgets/RangeSelector.h"
 #include "qttreepropertybrowser.h"
 #include "qtpropertymanager.h"
-//3rd party library headers
+// 3rd party library headers
 #include <QMessageBox>
-//System headers
-#include<iostream>
+// System headers
+#include <iostream>
 
 namespace {
-  Mantid::Kernel::Logger g_log("DynamicPDF");
+Mantid::Kernel::Logger g_log("DynamicPDF");
 }
 
 namespace MantidQt {
@@ -32,29 +32,22 @@ namespace DynamicPDF {
 /**
  * @brief Constructor
  */
-FourierTransform::FourierTransform(QWidget *parent):
-  QWidget(parent),
-  m_inputDataControl{nullptr},
-  m_propertyTree(new QtTreePropertyBrowser()),
-  m_properties(),
-  m_decimals(6),
-  m_residualsName{"DPDFResiduals"},
-  m_fourierName{"DPDFFourierTransform"},
-  m_colors(),
-  m_doubleManager(new QtDoublePropertyManager(this)),
-  m_boolManager(new QtBoolPropertyManager(this)),
-  m_enumManager(new QtEnumPropertyManager(this)),
-  m_groupManager(new QtGroupPropertyManager(this)),
-  m_algorithmRunner() {
+FourierTransform::FourierTransform(QWidget *parent)
+    : QWidget(parent), m_inputDataControl{nullptr},
+      m_propertyTree(new QtTreePropertyBrowser()), m_properties(),
+      m_decimals(6), m_residualsName{"DPDFResiduals"},
+      m_fourierName{"DPDFFourierTransform"}, m_colors(),
+      m_doubleManager(new QtDoublePropertyManager(this)),
+      m_boolManager(new QtBoolPropertyManager(this)),
+      m_enumManager(new QtEnumPropertyManager(this)),
+      m_groupManager(new QtGroupPropertyManager(this)), m_algorithmRunner() {
   this->initLayout();
 }
 
 /**
  * @brief Destructor
  */
-FourierTransform::~FourierTransform() {
-  delete m_propertyTree;
-}
+FourierTransform::~FourierTransform() { delete m_propertyTree; }
 
 /*                *********************
  *                **  Private Slots  **
@@ -63,26 +56,24 @@ FourierTransform::~FourierTransform() {
 /**
  * @brief reset actions after user selects a new slice for fitting
 */
-void FourierTransform::resetAfterSliceSelected(){
+void FourierTransform::resetAfterSliceSelected() {
   // clear previewplot
   m_uiForm.previewPlotFourier->clear();
   // remove residuals and fourier workspaces
-  if(Mantid::API::AnalysisDataService::Instance()
-     .doesExist(m_residualsName)) {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(m_residualsName)) {
     Mantid::API::AnalysisDataService::Instance().remove(m_residualsName);
   }
-  if(Mantid::API::AnalysisDataService::Instance()
-     .doesExist(m_fourierName)) {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(m_fourierName)) {
     Mantid::API::AnalysisDataService::Instance().remove(m_fourierName);
   }
   // update [Qmin, Qmax] range but do not emit any signal
-  disconnect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)),
-    this, SLOT(transformAfterPropertyChanged(QtProperty *)));
+  disconnect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
+             SLOT(transformAfterPropertyChanged(QtProperty *)));
   auto range = m_inputDataControl->getCurrentRange();
   m_doubleManager->setValue(m_properties["Qmin"], range.first);
   m_doubleManager->setValue(m_properties["Qmax"], range.second);
-  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)),
-    this, SLOT(transformAfterPropertyChanged(QtProperty *)));
+  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(transformAfterPropertyChanged(QtProperty *)));
 }
 
 /**
@@ -92,28 +83,35 @@ void FourierTransform::resetAfterSliceSelected(){
  *  data, model evaluation, and residuals
 */
 void FourierTransform::extractResidualsHistogram(
-  const QString &modelWorkspaceName){
+    const QString &modelWorkspaceName) {
   try {
 
     auto modelWorkspace = Mantid::API::AnalysisDataService::Instance()
-      .retrieveWS<Mantid::API::MatrixWorkspace>(modelWorkspaceName.toStdString());
-    if(!modelWorkspace) { std::cout << "Empty modelWorkspace\n";}
+                              .retrieveWS<Mantid::API::MatrixWorkspace>(
+                                  modelWorkspaceName.toStdString());
+    if (!modelWorkspace) {
+      std::cout << "Empty modelWorkspace\n";
+    }
     // use modelWorkspace as template for the residuals workspace
-    auto residualsWorkspace = Mantid::API::WorkspaceFactory::Instance().create(modelWorkspace, 1);
+    auto residualsWorkspace =
+        Mantid::API::WorkspaceFactory::Instance().create(modelWorkspace, 1);
     residualsWorkspace->dataX(0) = modelWorkspace->dataX(0);
-    residualsWorkspace->dataY(0) = modelWorkspace->dataY(2); // residuals is the third spectrum
-    residualsWorkspace->dataE(0) = modelWorkspace->dataE(0); // errors are coming from experiment
-    Mantid::API::AnalysisDataService::Instance().addOrReplace(m_residualsName, residualsWorkspace);
-  }
-  catch(std::exception& e) {
+    residualsWorkspace->dataY(0) =
+        modelWorkspace->dataY(2); // residuals is the third spectrum
+    residualsWorkspace->dataE(0) =
+        modelWorkspace->dataE(0); // errors are coming from experiment
+    Mantid::API::AnalysisDataService::Instance().addOrReplace(
+        m_residualsName, residualsWorkspace);
+  } catch (std::exception &e) {
     QString mess(e.what());
     const int maxSize = 500;
-     if ( mess.size() > maxSize )  {
-      mess = mess.mid(0,maxSize);
+    if (mess.size() > maxSize) {
+      mess = mess.mid(0, maxSize);
       mess += "...";
     }
-    QMessageBox::critical( this, "DynamicPDF - Error",
-      QString("extractModelHistogram failed:\n\n  %1").arg(mess) );
+    QMessageBox::critical(
+        this, "DynamicPDF - Error",
+        QString("extractModelHistogram failed:\n\n  %1").arg(mess));
   }
   emit signalExtractResidualsHistogramFinished();
 }
@@ -124,13 +122,13 @@ void FourierTransform::extractResidualsHistogram(
 */
 void FourierTransform::transform() {
   try {
-    if(!Mantid::API::AnalysisDataService::Instance()
-       .doesExist(m_residualsName)) {
+    if (!Mantid::API::AnalysisDataService::Instance().doesExist(
+            m_residualsName)) {
       throw std::runtime_error("No residuals found from any model evaluation");
     }
     // set up the PDFFourierTransform algorithm
-    auto fourier = Mantid::API::AlgorithmManager::Instance().
-      create("PDFFourierTransform");
+    auto fourier =
+        Mantid::API::AlgorithmManager::Instance().create("PDFFourierTransform");
     fourier->initialize();
     fourier->setPropertyValue("InputWorkspace", m_residualsName);
     fourier->setPropertyValue("OutputWorkspace", m_fourierName);
@@ -154,28 +152,28 @@ void FourierTransform::transform() {
     fourier->setProperty("rho0", rho0);
     // Asynchronous execution of the algorithm, so that we can keep on
     // working with the interface
-    m_algorithmRunner.reset( new API::AlgorithmRunner() );
-    connect( m_algorithmRunner.get(),SIGNAL(algorithmComplete(bool)),
-      this, SLOT(finishTransform(bool)), Qt::QueuedConnection );
+    m_algorithmRunner.reset(new API::AlgorithmRunner());
+    connect(m_algorithmRunner.get(), SIGNAL(algorithmComplete(bool)), this,
+            SLOT(finishTransform(bool)), Qt::QueuedConnection);
     m_algorithmRunner->startAlgorithm(fourier);
-  }
-  catch(std::exception& e) {
+  } catch (std::exception &e) {
     QString mess(e.what());
     const int maxSize = 500;
-    if ( mess.size() > maxSize ) {
-      mess = mess.mid(0,maxSize);
+    if (mess.size() > maxSize) {
+      mess = mess.mid(0, maxSize);
       mess += "...";
     }
-    QMessageBox::critical( this, "DynamicPDF - Error",
-      QString("FourierTransform::transform failed:\n\n  %1").arg(mess) );
+    QMessageBox::critical(
+        this, "DynamicPDF - Error",
+        QString("FourierTransform::transform failed:\n\n  %1").arg(mess));
   }
 }
 
 /**
  * @brief Just signal that the residuals extraction finished
  */
-  void FourierTransform::finishTransform(bool error) {
-  if(error) {
+void FourierTransform::finishTransform(bool error) {
+  if (error) {
     return;
   }
   this->updatePlot();
@@ -228,14 +226,16 @@ void FourierTransform::createPropertyTree() {
 
   // properties for "Reciprocal Space" group of algorithm PDFFourierTransform
   m_properties["Reciprocal Space"] =
-    m_groupManager->addProperty("Reciprocal Space");
+      m_groupManager->addProperty("Reciprocal Space");
   // insert type of structure factor
   QStringList sOfQTypes;
-  sOfQTypes << "S(Q)-1" << "S(Q)" << "Q[S(Q)-1]";
+  sOfQTypes << "S(Q)-1"
+            << "S(Q)"
+            << "Q[S(Q)-1]";
   m_properties["InputSofQType"] = m_enumManager->addProperty("InputSofQType");
   m_enumManager->setEnumNames(m_properties["InputSofQType"], sOfQTypes);
-  m_properties["Reciprocal Space"]->
-    addSubProperty(m_properties["InputSofQType"]);
+  m_properties["Reciprocal Space"]->addSubProperty(
+      m_properties["InputSofQType"]);
   // insert Qmin property
   m_properties["Qmin"] = m_doubleManager->addProperty("Qmin");
   m_doubleManager->setDecimals(m_properties["Qmin"], m_decimals);
@@ -251,15 +251,15 @@ void FourierTransform::createPropertyTree() {
   m_properties["Reciprocal Space"]->addSubProperty(m_properties["Filter"]);
 
   // properties for "Real Space" group of algorithm PDFFourierTransform
-  m_properties["Real Space"] =
-    m_groupManager->addProperty("Real Space");
+  m_properties["Real Space"] = m_groupManager->addProperty("Real Space");
   // insert type of PDF
   QStringList pdfTypes;
-  pdfTypes << "G(r)" << "g(r)" << "RDF(r)";
+  pdfTypes << "G(r)"
+           << "g(r)"
+           << "RDF(r)";
   m_properties["PDFType"] = m_enumManager->addProperty("PDFType");
   m_enumManager->setEnumNames(m_properties["PDFType"], pdfTypes);
-  m_properties["Real Space"]->
-    addSubProperty(m_properties["PDFType"]);
+  m_properties["Real Space"]->addSubProperty(m_properties["PDFType"]);
   // insert DeltaR property
   m_properties["DeltaR"] = m_doubleManager->addProperty("DeltaR");
   m_doubleManager->setDecimals(m_properties["DeltaR"], m_decimals);
@@ -287,7 +287,7 @@ void FourierTransform::createPropertyTree() {
 
   // insert the widget tree in the UI form
   m_uiForm.verticalLayoutProperties->addWidget(m_propertyTree);
-  m_uiForm.verticalLayoutProperties->setContentsMargins(0,0,0,0);
+  m_uiForm.verticalLayoutProperties->setContentsMargins(0, 0, 0, 0);
 }
 
 /*
@@ -297,27 +297,26 @@ void FourierTransform::createPropertyTree() {
  * algorithm PDFFourierTransform
  */
 void FourierTransform::setConnections() {
-  connect(m_inputDataControl, SIGNAL(signalSliceForFittingUpdated()),
-    this, SLOT(resetAfterSliceSelected()));
+  connect(m_inputDataControl, SIGNAL(signalSliceForFittingUpdated()), this,
+          SLOT(resetAfterSliceSelected()));
   connect(m_fitControl, SIGNAL(signalModelEvaluationFinished(const QString &)),
-    this, SLOT(extractResidualsHistogram(const QString &)));
-  connect(this, SIGNAL(signalExtractResidualsHistogramFinished()),
-    this, SLOT(transform()));
-  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)),
-    this, SLOT(transformAfterPropertyChanged(QtProperty *)));
- }
+          this, SLOT(extractResidualsHistogram(const QString &)));
+  connect(this, SIGNAL(signalExtractResidualsHistogramFinished()), this,
+          SLOT(transform()));
+  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(transformAfterPropertyChanged(QtProperty *)));
+}
 
 /*
  * @brief Insert a dashed line at Y=0 and show legends
  */
 void FourierTransform::setupPlotDisplay() {
   m_uiForm.previewPlotFourier->showLegend(true);
-  if(m_uiForm.previewPlotFourier->hasRangeSelector(QString("zeroLine"))){
+  if (m_uiForm.previewPlotFourier->hasRangeSelector(QString("zeroLine"))) {
     return; // do nothing
   }
-  auto zeroLine = m_uiForm.previewPlotFourier->
-    addRangeSelector(QString("zeroLine"),
-    MantidQt::MantidWidgets::RangeSelector::YSINGLE);
+  auto zeroLine = m_uiForm.previewPlotFourier->addRangeSelector(
+      QString("zeroLine"), MantidQt::MantidWidgets::RangeSelector::YSINGLE);
   zeroLine->setColour(QColor(Qt::darkGreen));
   zeroLine->setMinimum(0.0);
 }
@@ -357,12 +356,11 @@ void FourierTransform::updatePlot() {
   auto i = m_enumManager->value(m_properties["PDFType"]);
   auto name = names[i];
   if (plotter->hasCurve(name)) {
-      plotter->removeSpectrum(name);
+    plotter->removeSpectrum(name);
   }
-  plotter->addSpectrum(name,
-    QString::fromStdString(m_fourierName), 0, m_colors[name]);
+  plotter->addSpectrum(name, QString::fromStdString(m_fourierName), 0,
+                       m_colors[name]);
 }
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFInputDataControl.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFInputDataControl.cpp
index 82adbf129f7b866e17c307fde1e60101092d2916..933f1a66889fb66c38b8e28826e8801926137132 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFInputDataControl.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DPDFInputDataControl.cpp
@@ -10,14 +10,13 @@
 // System #includes
 
 namespace {
-  Mantid::Kernel::Logger g_log("DynamicPDF");
+Mantid::Kernel::Logger g_log("DynamicPDF");
 }
 
 namespace MantidQt {
 namespace CustomInterfaces {
 namespace DynamicPDF {
 
-
 /*              **********************
  *              **  Public Members  **
  *              **********************/
@@ -25,10 +24,8 @@ namespace DynamicPDF {
 /**
  * @brief Constructor.
  */
-InputDataControl::InputDataControl() :
-  m_workspace(),
-  m_selectedWorkspaceIndex{0},
-  m_domain() {
+InputDataControl::InputDataControl()
+    : m_workspace(), m_selectedWorkspaceIndex{0}, m_domain() {
   this->observePreDelete(true); // Subscribe to notifications
 }
 
@@ -37,18 +34,18 @@ InputDataControl::InputDataControl() :
  */
 InputDataControl::~InputDataControl() {
   m_workspace.reset();
-  this->observePreDelete(false);  // Cancel subscription to notifications
+  this->observePreDelete(false); // Cancel subscription to notifications
 }
 
 /**
  * @brief report the energy domain with non-zero signal
  */
-std::vector<double> InputDataControl::selectedDataX(){
+std::vector<double> InputDataControl::selectedDataX() {
   auto first = m_domain.at(m_selectedWorkspaceIndex).first;
   auto second = m_domain.at(m_selectedWorkspaceIndex).second;
   auto X = m_workspace->dataX(m_selectedWorkspaceIndex);
- // crop the zero signal
-  std::vector<double> x(X.begin() + first, X.begin()+second);
+  // crop the zero signal
+  std::vector<double> x(X.begin() + first, X.begin() + second);
   return x;
 }
 
@@ -56,41 +53,43 @@ std::vector<double> InputDataControl::selectedDataX(){
  * @brief report the first and last values of Q with non-zero signal
  * for the current selected slice
  */
-  std::pair<double,double> InputDataControl::getCurrentRange() {
-    auto domain = m_domain.at(m_selectedWorkspaceIndex);
-    auto X = m_workspace->dataX(m_selectedWorkspaceIndex);
-    auto second = domain.second;
-    if(m_workspace->isHistogramData()){
-      second -= 1;
-    }
-    return std::pair<double,double>(X.at(domain.first),X.at(second));
+std::pair<double, double> InputDataControl::getCurrentRange() {
+  auto domain = m_domain.at(m_selectedWorkspaceIndex);
+  auto X = m_workspace->dataX(m_selectedWorkspaceIndex);
+  auto second = domain.second;
+  if (m_workspace->isHistogramData()) {
+    second -= 1;
   }
+  return std::pair<double, double>(X.at(domain.first), X.at(second));
+}
 
 /**
  * @brief report the non-zero signal
  */
-std::vector<double> InputDataControl::selectedDataY(){
+std::vector<double> InputDataControl::selectedDataY() {
   auto first = m_domain.at(m_selectedWorkspaceIndex).first;
   auto second = m_domain.at(m_selectedWorkspaceIndex).second;
-  if(m_workspace->isHistogramData()){
+  if (m_workspace->isHistogramData()) {
     second -= 1;
   }
   auto Y = m_workspace->dataY(m_selectedWorkspaceIndex);
-  std::vector<double> y(Y.begin() + first, Y.begin()+second); // crop the zero signal
+  std::vector<double> y(Y.begin() + first,
+                        Y.begin() + second); // crop the zero signal
   return y;
 }
 
 /**
  * @brief report the error for the non-zero signal
  */
-std::vector<double> InputDataControl::selectedDataE(){
+std::vector<double> InputDataControl::selectedDataE() {
   auto first = m_domain.at(m_selectedWorkspaceIndex).first;
   auto second = m_domain.at(m_selectedWorkspaceIndex).second;
-    if(m_workspace->isHistogramData()){
-      second -= 1;
-    }
+  if (m_workspace->isHistogramData()) {
+    second -= 1;
+  }
   auto E = m_workspace->dataE(m_selectedWorkspaceIndex);
-  std::vector<double> e(E.begin()+first, E.begin()+second); // crop the zero signal
+  std::vector<double> e(E.begin() + first,
+                        E.begin() + second); // crop the zero signal
   return e;
 }
 
@@ -107,7 +106,7 @@ double InputDataControl::getSelectedEnergy() {
  * @return name of the workspace containing the slices
  */
 std::string InputDataControl::getWorkspaceName() {
-  if(!m_workspace) {
+  if (!m_workspace) {
     throw std::runtime_error("InpuDataControl has not set m_workspace!");
   }
   return m_workspace->name();
@@ -119,7 +118,7 @@ std::string InputDataControl::getWorkspaceName() {
  * @return the workspace index of the slice selected
  */
 size_t InputDataControl::getWorkspaceIndex() {
-  if(!m_workspace) {
+  if (!m_workspace) {
     throw std::runtime_error("InpuDataControl has not set m_workspace!");
   }
   return m_selectedWorkspaceIndex;
@@ -129,7 +128,7 @@ size_t InputDataControl::getWorkspaceIndex() {
  * @brief Query if user selected a slice for fitting
  */
 bool InputDataControl::isSliceSelectedForFitting() {
-  if(m_workspace) {
+  if (m_workspace) {
     return true;
   }
   return false;
@@ -142,12 +141,13 @@ bool InputDataControl::isSliceSelectedForFitting() {
 /**
  * @brief Actions when slices workspace is deleted
  */
-void InputDataControl::preDeleteHandle(const std::string &workspaceName,
-  const boost::shared_ptr<Mantid::API::Workspace> workspace) {
+void InputDataControl::preDeleteHandle(
+    const std::string &workspaceName,
+    const boost::shared_ptr<Mantid::API::Workspace> workspace) {
   UNUSED_ARG(workspaceName);
   Mantid::API::MatrixWorkspace_sptr ws =
-    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
-  if ( !ws || (ws != m_workspace) ){
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
+  if (!ws || (ws != m_workspace)) {
     return;
   }
   m_workspace.reset();
@@ -165,7 +165,8 @@ void InputDataControl::preDeleteHandle(const std::string &workspaceName,
  */
 void InputDataControl::updateWorkspace(const QString &workspaceName) {
   m_workspace = Mantid::API::AnalysisDataService::Instance()
-    .retrieveWS<Mantid::API::MatrixWorkspace>(workspaceName.toStdString());
+                    .retrieveWS<Mantid::API::MatrixWorkspace>(
+                        workspaceName.toStdString());
   m_domain.resize(m_workspace->getNumberHistograms());
   emit signalWorkspaceUpdated();
 }
@@ -192,15 +193,14 @@ void InputDataControl::updateSliceForFitting(const size_t &workspaceIndex) {
 void InputDataControl::updateDomain() {
   auto y = m_workspace->dataY(m_selectedWorkspaceIndex);
   // find first index with non-zero signal
-  auto it = std::find_if(y.begin(), y.end(), [](const double &s){return s>0.0;});
+  auto it =
+      std::find_if(y.begin(), y.end(), [](const double &s) { return s > 0.0; });
   int first = static_cast<int>(std::distance(y.begin(), it));
   // find first index with zero signal after the non-zero signal range
-  it = std::find_if(it, y.end(), [](const double &s){return s==0.0;});
+  it = std::find_if(it, y.end(), [](const double &s) { return s == 0.0; });
   int second = static_cast<int>(std::distance(y.begin(), it));
-  m_domain.at(m_selectedWorkspaceIndex) = std::pair<int,int>(first,second);
+  m_domain.at(m_selectedWorkspaceIndex) = std::pair<int, int>(first, second);
 }
-
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/DisplayCurveFitTest.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/DisplayCurveFitTest.cpp
index cb41306c697b46f19956216a94d8a9582025195f..edf1445bce42fea1c79af2bcdfbd863143477d5c 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/DisplayCurveFitTest.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/DisplayCurveFitTest.cpp
@@ -60,13 +60,14 @@ void DisplayCurveFitTest::loadSpectra(const QString &workspaceName) {
                            workspaceName.toStdString());
   if (!workspace) {
     auto title = QString::fromStdString(this->name());
-    auto error = QString::fromStdString("Workspace must be of type MatrixWorkspace");
+    auto error =
+        QString::fromStdString("Workspace must be of type MatrixWorkspace");
     QMessageBox::warning(this, title, error);
     return;
   }
   if (workspace->getNumberHistograms() < 4) {
     auto title = QString::fromStdString(this->name());
-    auto error= QString("Not enough number of histograms in the workspace");
+    auto error = QString("Not enough number of histograms in the workspace");
     QMessageBox::warning(this, title, error);
     return;
   }
diff --git a/MantidQt/CustomInterfaces/src/DynamicPDF/SliceSelector.cpp b/MantidQt/CustomInterfaces/src/DynamicPDF/SliceSelector.cpp
index 7c07fc2e1c201bc2654670569fda118680413d02..5e81e2830a92c6cbb44598f69b69c95be192308d 100644
--- a/MantidQt/CustomInterfaces/src/DynamicPDF/SliceSelector.cpp
+++ b/MantidQt/CustomInterfaces/src/DynamicPDF/SliceSelector.cpp
@@ -22,20 +22,16 @@ namespace DynamicPDF {
  * @brief Constructor
  * @param workspaceName retrieve the workspace with the Analysis Data Service
  */
-WorkspaceRecord::WorkspaceRecord(const std::string &workspaceName) :
-  m_name{workspaceName},
-  m_energy{0.0},
-  m_label() {
+WorkspaceRecord::WorkspaceRecord(const std::string &workspaceName)
+    : m_name{workspaceName}, m_energy{0.0}, m_label() {
   m_ws = Mantid::API::AnalysisDataService::Instance()
-    .retrieveWS<Mantid::API::MatrixWorkspace>(workspaceName);
+             .retrieveWS<Mantid::API::MatrixWorkspace>(workspaceName);
 }
 
 /**
  * @brief Destructor. Reset the pointer to the workspace
  */
-WorkspaceRecord::~WorkspaceRecord(){
-  m_ws.reset();
-}
+WorkspaceRecord::~WorkspaceRecord() { m_ws.reset(); }
 
 void WorkspaceRecord::updateMetadata(const size_t &newIndex) {
   m_energy = m_ws->getAxis(1)->getValue(newIndex);
@@ -51,10 +47,10 @@ void WorkspaceRecord::updateMetadata(const size_t &newIndex) {
  * @brief Find out minimum and maximum energies in the loaded workspace
  * @return (minimum, maximum) as std::pair
  */
-std::pair<double,double> WorkspaceRecord::getErange(){
+std::pair<double, double> WorkspaceRecord::getErange() {
   auto minimum = m_ws->getAxis(1)->getMin();
   auto maximum = m_ws->getAxis(1)->getMax();
-  return std::pair<double,double>(minimum, maximum);
+  return std::pair<double, double>(minimum, maximum);
 }
 
 /*        **********************
@@ -64,17 +60,15 @@ std::pair<double,double> WorkspaceRecord::getErange(){
 /**
  * @brief Constructor
  */
-SliceSelector::SliceSelector(QWidget *parent) :
-  QMainWindow(parent),
-  m_pickerLine{nullptr},
-  m_loadedWorkspace(),
-  m_selectedWorkspaceIndex{0} {
+SliceSelector::SliceSelector(QWidget *parent)
+    : QMainWindow(parent), m_pickerLine{nullptr}, m_loadedWorkspace(),
+      m_selectedWorkspaceIndex{0} {
   this->observePreDelete(true); // Subscribe to notifications
   this->initLayout();
 }
 
 SliceSelector::~SliceSelector() {
-  this->observePreDelete(false);  // Cancel subscription to notifications
+  this->observePreDelete(false); // Cancel subscription to notifications
   delete m_pickerLine;
 }
 
@@ -85,18 +79,20 @@ SliceSelector::~SliceSelector() {
 /**
  * @brief Actions when slices workspace is deleted
  */
-void SliceSelector::preDeleteHandle(const std::string &workspaceName,
-  const boost::shared_ptr<Mantid::API::Workspace> workspace) {
+void SliceSelector::preDeleteHandle(
+    const std::string &workspaceName,
+    const boost::shared_ptr<Mantid::API::Workspace> workspace) {
   UNUSED_ARG(workspaceName);
   Mantid::API::MatrixWorkspace_sptr ws =
-    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
-  if ( !ws || (ws != m_loadedWorkspace->m_ws) ){
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
+  if (!ws || (ws != m_loadedWorkspace->m_ws)) {
     return;
   }
 
   // Clean the 2D view
   m_pickerLine->setVisible(false);
-  // Clean the 1D view (automatically taken care by the underlying PreviewPlot objet)
+  // Clean the 1D view (automatically taken care by the underlying PreviewPlot
+  // objet)
   // Clean the rest of the widgets
   m_uiForm.labelSliceEnergy->setText(QString::fromStdString("Energy = NAN"));
   // Clean the data structure
@@ -116,9 +112,9 @@ void SliceSelector::preDeleteHandle(const std::string &workspaceName,
  */
 void SliceSelector::loadSlices(const QString &workspaceName) {
   m_loadedWorkspace =
-    Mantid::Kernel::make_unique<WorkspaceRecord>(workspaceName.toStdString());
+      Mantid::Kernel::make_unique<WorkspaceRecord>(workspaceName.toStdString());
   /// don't process if workspace is not valid
-  if(!this->isWorkspaceValid()){
+  if (!this->isWorkspaceValid()) {
     return;
   }
   m_selectedWorkspaceIndex = 0;
@@ -156,8 +152,8 @@ void SliceSelector::loadSlices(const QString &workspaceName) {
 void SliceSelector::updatePreviewPlotSelectedSlice() {
   m_uiForm.previewPlotSelectedSlice->clear();
   m_uiForm.previewPlotSelectedSlice->addSpectrum(
-  QString::fromStdString(m_loadedWorkspace->m_label),
-  m_loadedWorkspace->m_ws, m_selectedWorkspaceIndex);
+      QString::fromStdString(m_loadedWorkspace->m_label),
+      m_loadedWorkspace->m_ws, m_selectedWorkspaceIndex);
 }
 
 /**
@@ -171,7 +167,7 @@ void SliceSelector::updateSelectedSlice(const int &newSelectedIndex) {
   if (m_loadedWorkspace) {
     m_loadedWorkspace->updateMetadata(m_selectedWorkspaceIndex);
     m_uiForm.labelSliceEnergy->setText(
-    QString::fromStdString(m_loadedWorkspace->m_label));
+        QString::fromStdString(m_loadedWorkspace->m_label));
     m_uiForm.spinboxSliceSelector->setValue(newSelectedIndex);
     this->updatePickerLine();
     this->updatePreviewPlotSelectedSlice();
@@ -184,23 +180,24 @@ void SliceSelector::updateSelectedSlice(const int &newSelectedIndex) {
  * slice.
  * @param newEnergySelected the new energy retrieved from the pickerLine
  */
-void SliceSelector::newIndexFromPickedEnergy(const double &newEnergySelected){
+void SliceSelector::newIndexFromPickedEnergy(const double &newEnergySelected) {
   auto axis = m_loadedWorkspace->m_ws->getAxis(1);
   auto newSelectedIndex = axis->indexOfValue(newEnergySelected);
-  if(m_selectedWorkspaceIndex != newSelectedIndex){
+  if (m_selectedWorkspaceIndex != newSelectedIndex) {
     updateSelectedSlice(static_cast<int>(newSelectedIndex));
   }
 }
 
 /**
  * @brief Update the position of the picker line as a response to changes in the
- * SliceSelector, unless the energy being pointed to corresponds to the current index.
+ * SliceSelector, unless the energy being pointed to corresponds to the current
+ * index.
  */
-void SliceSelector::updatePickerLine(){
+void SliceSelector::updatePickerLine() {
   auto energyBeingPointedTo = m_pickerLine->getMinimum();
   auto axis = m_loadedWorkspace->m_ws->getAxis(1);
   auto indexBeingPointedTo = axis->indexOfValue(energyBeingPointedTo);
-  if(m_selectedWorkspaceIndex != indexBeingPointedTo){
+  if (m_selectedWorkspaceIndex != indexBeingPointedTo) {
     m_pickerLine->setMinimum(m_loadedWorkspace->m_energy);
   }
 }
@@ -209,7 +206,7 @@ void SliceSelector::updatePickerLine(){
  * @brief Public broadcast of the slice that user selected for fitting
  */
 void SliceSelector::selectSliceForFitting() {
-  if(m_loadedWorkspace) {
+  if (m_loadedWorkspace) {
     emit this->signalSliceForFittingSelected(m_selectedWorkspaceIndex);
   }
 }
@@ -235,53 +232,56 @@ void SliceSelector::initLayout() {
   // user wants help
   connect(m_uiForm.buttonpushHelp, SIGNAL(clicked()), this, SLOT(showHelp()));
   // user wants to fit the selected slice with the Background remover
-  connect(m_uiForm.pushButtonFit, SIGNAL(clicked()), this, SLOT(selectSliceForFitting()));
+  connect(m_uiForm.pushButtonFit, SIGNAL(clicked()), this,
+          SLOT(selectSliceForFitting()));
   // user has loaded slices from a workspace or file
   connect(m_uiForm.dataSelector, SIGNAL(dataReady(const QString &)), this,
-    SLOT(loadSlices(const QString &)));
+          SLOT(loadSlices(const QString &)));
   this->setupConnections();
 }
 
 /**
  * @brief Establish signals/connections between widgets components
  */
-void  SliceSelector::setupConnections() {
+void SliceSelector::setupConnections() {
   // user is selecting a slice with the spin box
   connect(m_uiForm.spinboxSliceSelector, SIGNAL(valueChanged(int)), this,
-    SLOT(updateSelectedSlice(int)));
+          SLOT(updateSelectedSlice(int)));
   // user is selecting a slice with the picker line
   connect(m_pickerLine, SIGNAL(minValueChanged(double)), this,
-    SLOT(newIndexFromPickedEnergy(double)));
+          SLOT(newIndexFromPickedEnergy(double)));
 }
 
 /**
  * @brief disconnect the signals/connections established
  *  in setupConnections
  */
-void  SliceSelector::tearConnections() {
+void SliceSelector::tearConnections() {
   // user is selecting a slice with the spin box
   disconnect(m_uiForm.spinboxSliceSelector, SIGNAL(valueChanged(int)), this,
-    SLOT(updateSelectedSlice(int)));
+             SLOT(updateSelectedSlice(int)));
   // user is selecting a slice with the picker line
   disconnect(m_pickerLine, SIGNAL(minValueChanged(double)), this,
-    SLOT(newIndexFromPickedEnergy(double)));
+             SLOT(newIndexFromPickedEnergy(double)));
 }
 
 /**
- * @brief Allocate the slice selector in the 2D view. No workspace loading is necessary.
+ * @brief Allocate the slice selector in the 2D view. No workspace loading is
+ * necessary.
  */
-void SliceSelector::spawnPickerLine(){
+void SliceSelector::spawnPickerLine() {
   auto qwtplot = m_uiForm.slices2DPlot->getPlot2D();
   bool isVisible{false};
   m_pickerLine = new MantidWidgets::RangeSelector(
-    qwtplot, MantidWidgets::RangeSelector::YSINGLE, isVisible);
+      qwtplot, MantidWidgets::RangeSelector::YSINGLE, isVisible);
   m_pickerLine->setColour(QColor(Qt::black));
 }
 
 /**
- * @brief Initialize the picker line with default options after workspace is loaded.
+ * @brief Initialize the picker line with default options after workspace is
+ * loaded.
  */
-void SliceSelector::initPickerLine(){
+void SliceSelector::initPickerLine() {
   auto eRange = m_loadedWorkspace->getErange();
   m_pickerLine->setRange(eRange);
   m_pickerLine->setMinimum(eRange.first);
@@ -292,11 +292,12 @@ void SliceSelector::initPickerLine(){
 /**
  * @brief Check for correct units and workspace type
  */
-bool SliceSelector::isWorkspaceValid(){
+bool SliceSelector::isWorkspaceValid() {
   /// check the pointer to the workspace is not empty
-  if(!m_loadedWorkspace->m_ws){
+  if (!m_loadedWorkspace->m_ws) {
     auto title = this->objectName();
-    auto error = QString::fromStdString("Workspace must be of type MatrixWorkspace");
+    auto error =
+        QString::fromStdString("Workspace must be of type MatrixWorkspace");
     QMessageBox::warning(this, title, error);
     return false;
   }
@@ -304,7 +305,8 @@ bool SliceSelector::isWorkspaceValid(){
   auto axis = m_loadedWorkspace->m_ws->getAxis(0);
   if (axis->unit()->unitID() != "MomentumTransfer") {
     auto title = this->objectName();
-    auto error = QString::fromStdString("X-axis units must be momentum transfer");
+    auto error =
+        QString::fromStdString("X-axis units must be momentum transfer");
     QMessageBox::warning(this, title, error);
     return false;
   }
@@ -312,14 +314,13 @@ bool SliceSelector::isWorkspaceValid(){
   axis = m_loadedWorkspace->m_ws->getAxis(1);
   if (axis->unit()->unitID() != "DeltaE") {
     auto title = this->objectName();
-    auto error = QString::fromStdString("Y-axis units must be energy transfer (meV)");
+    auto error =
+        QString::fromStdString("Y-axis units must be energy transfer (meV)");
     QMessageBox::warning(this, title, error);
     return false;
   }
   return true;
 }
-
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/Homer.cpp b/MantidQt/CustomInterfaces/src/Homer.cpp
index f1bfe07e3ffc2bfa6dd2df7b46c6ed49ce8456e9..02527955f93d68f2546f90e412d5a9e3674c3098 100644
--- a/MantidQt/CustomInterfaces/src/Homer.cpp
+++ b/MantidQt/CustomInterfaces/src/Homer.cpp
@@ -512,8 +512,8 @@ void Homer::runClicked() {
       m_saveChanged = false;
       saveSettings();
     }
-  } catch (std::invalid_argument
-               &e) { // can be caused by an invalid user entry that was detected
+  } catch (std::invalid_argument &
+               e) { // can be caused by an invalid user entry that was detected
     QMessageBox::critical(this, "", QString::fromStdString(e.what()));
   } catch (std::runtime_error &e) { // possibly a Python run time error
     QMessageBox::critical(
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ApplyPaalmanPings.cpp b/MantidQt/CustomInterfaces/src/Indirect/ApplyPaalmanPings.cpp
index e60dbc9ba27ffff6f0723740c54d3f4d78456f5a..0a40526606815b4a489782a1e25a54f8a608f5d7 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ApplyPaalmanPings.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ApplyPaalmanPings.cpp
@@ -101,21 +101,21 @@ void ApplyPaalmanPings::updateContainer() {
 
     IAlgorithm_sptr scaleXAlg = AlgorithmManager::Instance().create("ScaleX");
     scaleXAlg->initialize();
-	scaleXAlg->setLogging(false);
-	scaleXAlg->setProperty("InputWorkspace", canName.toStdString());
-	scaleXAlg->setProperty("OutputWorkspace", m_containerWorkspaceName);
-	scaleXAlg->setProperty("Factor", shift);
-	scaleXAlg->setProperty("Operation", "Add");
-	scaleXAlg->execute();
+    scaleXAlg->setLogging(false);
+    scaleXAlg->setProperty("InputWorkspace", canName.toStdString());
+    scaleXAlg->setProperty("OutputWorkspace", m_containerWorkspaceName);
+    scaleXAlg->setProperty("Factor", shift);
+    scaleXAlg->setProperty("Operation", "Add");
+    scaleXAlg->execute();
 
     IAlgorithm_sptr scaleAlg = AlgorithmManager::Instance().create("Scale");
-	scaleAlg->initialize();
-	scaleAlg->setLogging(false);
-	scaleAlg->setProperty("InputWorkspace", m_containerWorkspaceName);
-	scaleAlg->setProperty("OutputWorkspace", m_containerWorkspaceName);
-	scaleAlg->setProperty("Factor", scale);
-	scaleAlg->setProperty("Operation", "Multiply");
-	scaleAlg->execute();
+    scaleAlg->initialize();
+    scaleAlg->setLogging(false);
+    scaleAlg->setProperty("InputWorkspace", m_containerWorkspaceName);
+    scaleAlg->setProperty("OutputWorkspace", m_containerWorkspaceName);
+    scaleAlg->setProperty("Factor", scale);
+    scaleAlg->setProperty("Operation", "Multiply");
+    scaleAlg->execute();
 
     const auto sampleValid = m_uiForm.dsSample->isValid();
     if (sampleValid) {
@@ -129,12 +129,12 @@ void ApplyPaalmanPings::updateContainer() {
       rebin->execute();
     } else {
       // Sample was not valid so do not rebin
-	  m_uiForm.ppPreview->removeSpectrum("Container");
+      m_uiForm.ppPreview->removeSpectrum("Container");
       return;
     }
   } else {
     // Can was not valid so do not replot
-	m_uiForm.ppPreview->removeSpectrum("Container");
+    m_uiForm.ppPreview->removeSpectrum("Container");
     return;
   }
   plotPreview(m_uiForm.spPreviewSpec->value());
@@ -170,33 +170,35 @@ void ApplyPaalmanPings::run() {
   if (useCan) {
     const auto canName =
         m_uiForm.dsContainer->getCurrentDataName().toStdString();
-	const auto cloneName = "__algorithm_can";
-	IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace");
-	clone->initialize();
-	clone->setProperty("InputWorkspace", canName);
-	clone->setProperty("Outputworkspace", cloneName);
-	clone->execute();
+    const auto cloneName = "__algorithm_can";
+    IAlgorithm_sptr clone =
+        AlgorithmManager::Instance().create("CloneWorkspace");
+    clone->initialize();
+    clone->setProperty("InputWorkspace", canName);
+    clone->setProperty("Outputworkspace", cloneName);
+    clone->execute();
 
     const bool useShift = m_uiForm.ckShiftCan->isChecked();
-	if (useShift) {
-		IAlgorithm_sptr scaleX = AlgorithmManager::Instance().create("ScaleX");
-		scaleX->initialize();
-		scaleX->setLogging(false);
-		scaleX->setProperty("InputWorkspace", cloneName);
-		scaleX->setProperty("OutputWorkspace", cloneName);
-		scaleX->setProperty("Factor", m_uiForm.spCanShift->value());
-		scaleX->setProperty("Operation", "Add");
-		scaleX->execute();
-		IAlgorithm_sptr rebin =
-			AlgorithmManager::Instance().create("RebinToWorkspace");
-		rebin->initialize();
-		rebin->setLogging(false);
-		rebin->setProperty("WorkspaceToRebin", cloneName);
-		rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName);
-		rebin->setProperty("OutputWorkspace", cloneName);
-		rebin->execute();
-	}
-	canClone = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(cloneName);
+    if (useShift) {
+      IAlgorithm_sptr scaleX = AlgorithmManager::Instance().create("ScaleX");
+      scaleX->initialize();
+      scaleX->setLogging(false);
+      scaleX->setProperty("InputWorkspace", cloneName);
+      scaleX->setProperty("OutputWorkspace", cloneName);
+      scaleX->setProperty("Factor", m_uiForm.spCanShift->value());
+      scaleX->setProperty("Operation", "Add");
+      scaleX->execute();
+      IAlgorithm_sptr rebin =
+          AlgorithmManager::Instance().create("RebinToWorkspace");
+      rebin->initialize();
+      rebin->setLogging(false);
+      rebin->setProperty("WorkspaceToRebin", cloneName);
+      rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName);
+      rebin->setProperty("OutputWorkspace", cloneName);
+      rebin->execute();
+    }
+    canClone =
+        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(cloneName);
     // Check for same binning across sample and container
     if (!checkWorkspaceBinningMatches(sampleWs, canClone)) {
       const char *text =
diff --git a/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp b/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp
index 4b8253e852b187127f1cc83e021372cd2031ec4b..0bb4b76b56351bff8d0ed6023fc4c1c6771f8cdd 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp
@@ -163,22 +163,20 @@ bool CalculatePaalmanPings::doValidation(bool silent) {
   uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSample);
 
   const auto sampleChem =
-	  m_uiForm.leSampleChemicalFormula->text().toStdString();
+      m_uiForm.leSampleChemicalFormula->text().toStdString();
   const auto containerChem =
-	  m_uiForm.leCanChemicalFormula->text().toStdString();
+      m_uiForm.leCanChemicalFormula->text().toStdString();
   try {
-	  Mantid::Kernel::Material::parseChemicalFormula(sampleChem);
-  }
-  catch (std::runtime_error &ex) {
-	  UNUSED_ARG(ex);
-	  uiv.addErrorMessage("Chemical Formula for Sample was not recognised.");
+    Mantid::Kernel::Material::parseChemicalFormula(sampleChem);
+  } catch (std::runtime_error &ex) {
+    UNUSED_ARG(ex);
+    uiv.addErrorMessage("Chemical Formula for Sample was not recognised.");
   }
   try {
-	  Mantid::Kernel::Material::parseChemicalFormula(containerChem);
-  }
-  catch (std::runtime_error &ex) {
-	  UNUSED_ARG(ex);
-	  uiv.addErrorMessage("Chemical Formula for Container was not recognised.");
+    Mantid::Kernel::Material::parseChemicalFormula(containerChem);
+  } catch (std::runtime_error &ex) {
+    UNUSED_ARG(ex);
+    uiv.addErrorMessage("Chemical Formula for Container was not recognised.");
   }
 
   // Validate chemical formula
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
index 731da972b9448e8a7f1d9ae271fcb60e86477690..0156d1d0ebd05ad5edfbc6fd3123396a0fd4b6ba 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp
@@ -1158,8 +1158,7 @@ void ConvFit::singleFit() {
       runPythonCode(
           QString(
               "from IndirectCommon import getWSprefix\nprint getWSprefix('") +
-          m_cfInputWSName + QString("')\n"))
-          .trimmed();
+          m_cfInputWSName + QString("')\n")).trimmed();
   m_singleFitOutputName +=
       QString("conv_") + fitType + bgType + m_uiForm.spPlotSpectrum->text();
   int maxIterations =
diff --git a/MantidQt/CustomInterfaces/src/Indirect/CorrectionsTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/CorrectionsTab.cpp
index 4797b73095dc705f84c166f4df4fdd73f996788a..eb27f5b09dbfd68d8e65de0c00240756b80b566d 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/CorrectionsTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/CorrectionsTab.cpp
@@ -10,109 +10,100 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  /**
-   * Constructor.
-   *
-   * @param parent :: the parent widget
-   */
-  CorrectionsTab::CorrectionsTab(QWidget * parent) : IndirectTab(parent),
-    m_dblEdFac(NULL), m_blnEdFac(NULL)
+namespace MantidQt {
+namespace CustomInterfaces {
+/**
+ * Constructor.
+ *
+ * @param parent :: the parent widget
+ */
+CorrectionsTab::CorrectionsTab(QWidget *parent)
+    : IndirectTab(parent), m_dblEdFac(NULL), m_blnEdFac(NULL) {
+  // Create Editor Factories
+  m_dblEdFac = new DoubleEditorFactory(this);
+  m_blnEdFac = new QtCheckBoxFactory(this);
+}
+
+/**
+ * Loads the tab's settings.
+ *
+ * Calls overridden version of loadSettings() in child class.
+ *
+ * @param settings :: the QSettings object from which to load
+ */
+void CorrectionsTab::loadTabSettings(const QSettings &settings) {
+  loadSettings(settings);
+}
+
+/**
+ * Slot that can be called when a user edits an input.
+ */
+void CorrectionsTab::inputChanged() { validate(); }
+
+/**
+* Check that the binning between two workspaces matches.
+*
+* @param left :: left hand workspace for the equality operator
+* @param right :: right hand workspace for the equality operator
+* @return whether the binning matches
+* @throws std::runtime_error if one of the workspaces is an invalid pointer
+*/
+bool CorrectionsTab::checkWorkspaceBinningMatches(
+    MatrixWorkspace_const_sptr left, MatrixWorkspace_const_sptr right) {
+  if (left && right) // check the workspaces actually point to something first
   {
-    // Create Editor Factories
-    m_dblEdFac = new DoubleEditorFactory(this);
-    m_blnEdFac = new QtCheckBoxFactory(this);
-  }
-
-
-  /**
-   * Loads the tab's settings.
-   *
-   * Calls overridden version of loadSettings() in child class.
-   *
-   * @param settings :: the QSettings object from which to load
-   */
-  void CorrectionsTab::loadTabSettings(const QSettings & settings)
-  {
-    loadSettings(settings);
-  }
-
-
-  /**
-   * Slot that can be called when a user edits an input.
-   */
-  void CorrectionsTab::inputChanged()
-  {
-    validate();
-  }
-
-
-  /**
-  * Check that the binning between two workspaces matches.
-  *
-  * @param left :: left hand workspace for the equality operator
-  * @param right :: right hand workspace for the equality operator
-  * @return whether the binning matches
-  * @throws std::runtime_error if one of the workspaces is an invalid pointer
-  */
-  bool CorrectionsTab::checkWorkspaceBinningMatches(MatrixWorkspace_const_sptr left, MatrixWorkspace_const_sptr right)
-  {
-    if (left && right) //check the workspaces actually point to something first
-    {
-      auto leftX = left->readX(0);
-      auto rightX = right->readX(0);
-      return std::equal(leftX.begin(), leftX.end(), rightX.begin());
-    }
-    else
-    {
-      throw std::runtime_error("CorrectionsTab: One of the operands is an invalid MatrixWorkspace pointer");
-    }
-  }
-
-
-  /**
-   * Adds a unit converstion step to the batch algorithm queue.
-   *
-   * Note that if converting diffraction data in wavelength then eMode must be set.
-   *
-   * @param ws Pointer to the workspace to convert
-   * @param unitID ID of unit to convert to
-   * @param suffix Suffix to append to output workspace name
-   * @param eMode Emode to use (if not set will determine based on current X unit)
-   * @return Name of output workspace
-   */
-  std::string CorrectionsTab::addConvertUnitsStep(MatrixWorkspace_sptr ws, const std::string & unitID, const std::string & suffix, std::string eMode)
-  {
-    std::string outputName = ws->name();
-
-    if(suffix != "UNIT")
-      outputName += suffix;
-    else
-      outputName += "_" + unitID;
-
-
-    IAlgorithm_sptr convertAlg = AlgorithmManager::Instance().create("ConvertUnits");
-    convertAlg->initialize();
-
-    convertAlg->setProperty("InputWorkspace", ws->name());
-    convertAlg->setProperty("OutputWorkspace", outputName);
-    convertAlg->setProperty("Target", unitID);
-
-    if(eMode.empty())
-      eMode = getEMode(ws);
-
-    convertAlg->setProperty("EMode", eMode);
-
-    if(eMode == "Indirect")
-      convertAlg->setProperty("EFixed", getEFixed(ws));
-
-    m_batchAlgoRunner->addAlgorithm(convertAlg);
-
-    return outputName;
+    auto leftX = left->readX(0);
+    auto rightX = right->readX(0);
+    return std::equal(leftX.begin(), leftX.end(), rightX.begin());
+  } else {
+    throw std::runtime_error("CorrectionsTab: One of the operands is an "
+                             "invalid MatrixWorkspace pointer");
   }
+}
+
+/**
+ * Adds a unit converstion step to the batch algorithm queue.
+ *
+ * Note that if converting diffraction data in wavelength then eMode must be
+ *set.
+ *
+ * @param ws Pointer to the workspace to convert
+ * @param unitID ID of unit to convert to
+ * @param suffix Suffix to append to output workspace name
+ * @param eMode Emode to use (if not set will determine based on current X unit)
+ * @return Name of output workspace
+ */
+std::string CorrectionsTab::addConvertUnitsStep(MatrixWorkspace_sptr ws,
+                                                const std::string &unitID,
+                                                const std::string &suffix,
+                                                std::string eMode) {
+  std::string outputName = ws->name();
+
+  if (suffix != "UNIT")
+    outputName += suffix;
+  else
+    outputName += "_" + unitID;
+
+  IAlgorithm_sptr convertAlg =
+      AlgorithmManager::Instance().create("ConvertUnits");
+  convertAlg->initialize();
+
+  convertAlg->setProperty("InputWorkspace", ws->name());
+  convertAlg->setProperty("OutputWorkspace", outputName);
+  convertAlg->setProperty("Target", unitID);
+
+  if (eMode.empty())
+    eMode = getEMode(ws);
+
+  convertAlg->setProperty("EMode", eMode);
+
+  if (eMode == "Indirect")
+    convertAlg->setProperty("EFixed", getEFixed(ws));
+
+  m_batchAlgoRunner->addAlgorithm(convertAlg);
+
+  return outputName;
+}
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp b/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
index fc37d0089b3ec70da8da172e0a1e85e262c5eff9..4ed79ce1a2ffcdc112f390a7f6baca3b5e21f7a6 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp
@@ -11,430 +11,445 @@
 using namespace Mantid::API;
 using namespace MantidQt::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("Elwin");
+namespace {
+Mantid::Kernel::Logger g_log("Elwin");
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  Elwin::Elwin(QWidget * parent) :
-    IndirectDataAnalysisTab(parent),
-    m_elwTree(NULL)
-  {
-    m_uiForm.setupUi(parent);
-  }
-
-  void Elwin::setup()
-  {
-    // Create QtTreePropertyBrowser object
-    m_elwTree = new QtTreePropertyBrowser();
-    m_uiForm.properties->addWidget(m_elwTree);
-
-    // Editor Factories
-    m_elwTree->setFactoryForManager(m_dblManager, m_dblEdFac);
-    m_elwTree->setFactoryForManager(m_blnManager, m_blnEdFac);
-
-    // Create Properties
-    m_properties["IntegrationStart"] = m_dblManager->addProperty("Start");
-    m_dblManager->setDecimals(m_properties["IntegrationStart"], NUM_DECIMALS);
-    m_properties["IntegrationEnd"] = m_dblManager->addProperty("End");
-    m_dblManager->setDecimals(m_properties["IntegrationEnd"], NUM_DECIMALS);
-    m_properties["BackgroundStart"] = m_dblManager->addProperty("Start");
-    m_dblManager->setDecimals(m_properties["BackgroundStart"], NUM_DECIMALS);
-    m_properties["BackgroundEnd"] = m_dblManager->addProperty("End");
-    m_dblManager->setDecimals(m_properties["BackgroundEnd"], NUM_DECIMALS);
-
-    m_properties["BackgroundSubtraction"] = m_blnManager->addProperty("Background Subtraction");
-    m_properties["Normalise"] = m_blnManager->addProperty("Normalise to Lowest Temp");
-
-    m_properties["IntegrationRange"] = m_grpManager->addProperty("Integration Range");
-    m_properties["IntegrationRange"]->addSubProperty(m_properties["IntegrationStart"]);
-    m_properties["IntegrationRange"]->addSubProperty(m_properties["IntegrationEnd"]);
-    m_properties["BackgroundRange"] = m_grpManager->addProperty("Background Range");
-    m_properties["BackgroundRange"]->addSubProperty(m_properties["BackgroundStart"]);
-    m_properties["BackgroundRange"]->addSubProperty(m_properties["BackgroundEnd"]);
-
-    m_elwTree->addProperty(m_properties["IntegrationRange"]);
-    m_elwTree->addProperty(m_properties["BackgroundSubtraction"]);
-    m_elwTree->addProperty(m_properties["BackgroundRange"]);
-    m_elwTree->addProperty(m_properties["Normalise"]);
-
-    // We always want one range selector... the second one can be controlled from
-    // within the elwinTwoRanges(bool state) function
-    auto integrationRangeSelector = m_uiForm.ppPlot->addRangeSelector("ElwinIntegrationRange");
-    connect(integrationRangeSelector, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double)));
-    connect(integrationRangeSelector, SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double)));
-    // create the second range
-    auto backgroundRangeSelector = m_uiForm.ppPlot->addRangeSelector("ElwinBackgroundRange");
-    backgroundRangeSelector->setColour(Qt::darkGreen); // dark green for background
-    connect(integrationRangeSelector, SIGNAL(rangeChanged(double, double)),
-            backgroundRangeSelector, SLOT(setRange(double, double)));
-    connect(backgroundRangeSelector, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double)));
-    connect(backgroundRangeSelector, SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double)));
-    backgroundRangeSelector->setRange(integrationRangeSelector->getRange());
-
-    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateRS(QtProperty*, double)));
-    connect(m_blnManager, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(twoRanges(QtProperty*, bool)));
-    twoRanges(m_properties["BackgroundSubtraction"], false);
-
-    connect(m_uiForm.dsInputFiles, SIGNAL(filesFound()), this, SLOT(newInputFiles()));
-    connect(m_uiForm.cbPreviewFile, SIGNAL(currentIndexChanged(int)), this, SLOT(newPreviewFileSelected(int)));
-    connect(m_uiForm.spPreviewSpec, SIGNAL(valueChanged(int)), this, SLOT(plotInput()));
-
-    // Set any default values
-    m_dblManager->setValue(m_properties["IntegrationStart"], -0.02);
-    m_dblManager->setValue(m_properties["IntegrationEnd"], 0.02);
-
-    m_dblManager->setValue(m_properties["BackgroundStart"], -0.24);
-    m_dblManager->setValue(m_properties["BackgroundEnd"], -0.22);
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+Elwin::Elwin(QWidget *parent)
+    : IndirectDataAnalysisTab(parent), m_elwTree(NULL) {
+  m_uiForm.setupUi(parent);
+}
 
-  void Elwin::run()
-  {
-    QStringList inputFilenames = m_uiForm.dsInputFiles->getFilenames();
-    inputFilenames.sort();
+void Elwin::setup() {
+  // Create QtTreePropertyBrowser object
+  m_elwTree = new QtTreePropertyBrowser();
+  m_uiForm.properties->addWidget(m_elwTree);
+
+  // Editor Factories
+  m_elwTree->setFactoryForManager(m_dblManager, m_dblEdFac);
+  m_elwTree->setFactoryForManager(m_blnManager, m_blnEdFac);
+
+  // Create Properties
+  m_properties["IntegrationStart"] = m_dblManager->addProperty("Start");
+  m_dblManager->setDecimals(m_properties["IntegrationStart"], NUM_DECIMALS);
+  m_properties["IntegrationEnd"] = m_dblManager->addProperty("End");
+  m_dblManager->setDecimals(m_properties["IntegrationEnd"], NUM_DECIMALS);
+  m_properties["BackgroundStart"] = m_dblManager->addProperty("Start");
+  m_dblManager->setDecimals(m_properties["BackgroundStart"], NUM_DECIMALS);
+  m_properties["BackgroundEnd"] = m_dblManager->addProperty("End");
+  m_dblManager->setDecimals(m_properties["BackgroundEnd"], NUM_DECIMALS);
+
+  m_properties["BackgroundSubtraction"] =
+      m_blnManager->addProperty("Background Subtraction");
+  m_properties["Normalise"] =
+      m_blnManager->addProperty("Normalise to Lowest Temp");
+
+  m_properties["IntegrationRange"] =
+      m_grpManager->addProperty("Integration Range");
+  m_properties["IntegrationRange"]->addSubProperty(
+      m_properties["IntegrationStart"]);
+  m_properties["IntegrationRange"]->addSubProperty(
+      m_properties["IntegrationEnd"]);
+  m_properties["BackgroundRange"] =
+      m_grpManager->addProperty("Background Range");
+  m_properties["BackgroundRange"]->addSubProperty(
+      m_properties["BackgroundStart"]);
+  m_properties["BackgroundRange"]->addSubProperty(
+      m_properties["BackgroundEnd"]);
+
+  m_elwTree->addProperty(m_properties["IntegrationRange"]);
+  m_elwTree->addProperty(m_properties["BackgroundSubtraction"]);
+  m_elwTree->addProperty(m_properties["BackgroundRange"]);
+  m_elwTree->addProperty(m_properties["Normalise"]);
+
+  // We always want one range selector... the second one can be controlled from
+  // within the elwinTwoRanges(bool state) function
+  auto integrationRangeSelector =
+      m_uiForm.ppPlot->addRangeSelector("ElwinIntegrationRange");
+  connect(integrationRangeSelector, SIGNAL(minValueChanged(double)), this,
+          SLOT(minChanged(double)));
+  connect(integrationRangeSelector, SIGNAL(maxValueChanged(double)), this,
+          SLOT(maxChanged(double)));
+  // create the second range
+  auto backgroundRangeSelector =
+      m_uiForm.ppPlot->addRangeSelector("ElwinBackgroundRange");
+  backgroundRangeSelector->setColour(
+      Qt::darkGreen); // dark green for background
+  connect(integrationRangeSelector, SIGNAL(rangeChanged(double, double)),
+          backgroundRangeSelector, SLOT(setRange(double, double)));
+  connect(backgroundRangeSelector, SIGNAL(minValueChanged(double)), this,
+          SLOT(minChanged(double)));
+  connect(backgroundRangeSelector, SIGNAL(maxValueChanged(double)), this,
+          SLOT(maxChanged(double)));
+  backgroundRangeSelector->setRange(integrationRangeSelector->getRange());
+
+  connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
+          SLOT(updateRS(QtProperty *, double)));
+  connect(m_blnManager, SIGNAL(valueChanged(QtProperty *, bool)), this,
+          SLOT(twoRanges(QtProperty *, bool)));
+  twoRanges(m_properties["BackgroundSubtraction"], false);
+
+  connect(m_uiForm.dsInputFiles, SIGNAL(filesFound()), this,
+          SLOT(newInputFiles()));
+  connect(m_uiForm.cbPreviewFile, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(newPreviewFileSelected(int)));
+  connect(m_uiForm.spPreviewSpec, SIGNAL(valueChanged(int)), this,
+          SLOT(plotInput()));
+
+  // Set any default values
+  m_dblManager->setValue(m_properties["IntegrationStart"], -0.02);
+  m_dblManager->setValue(m_properties["IntegrationEnd"], 0.02);
+
+  m_dblManager->setValue(m_properties["BackgroundStart"], -0.24);
+  m_dblManager->setValue(m_properties["BackgroundEnd"], -0.22);
+}
 
-    // Get workspace names
-    std::string inputGroupWsName = "IDA_Elwin_Input";
+void Elwin::run() {
+  QStringList inputFilenames = m_uiForm.dsInputFiles->getFilenames();
+  inputFilenames.sort();
 
-    QFileInfo firstFileInfo(inputFilenames[0]);
-    QString filename = firstFileInfo.baseName();
-    QString workspaceBaseName = filename.left(filename.lastIndexOf("_")) + "_elwin_";
+  // Get workspace names
+  std::string inputGroupWsName = "IDA_Elwin_Input";
 
-    QString qWorkspace = workspaceBaseName + "eq";
-    QString qSquaredWorkspace = workspaceBaseName + "eq2";
-    QString elfWorkspace = workspaceBaseName + "elf";
-    QString eltWorkspace = workspaceBaseName + "elt";
+  QFileInfo firstFileInfo(inputFilenames[0]);
+  QString filename = firstFileInfo.baseName();
+  QString workspaceBaseName =
+      filename.left(filename.lastIndexOf("_")) + "_elwin_";
 
-    // Load input files
-    std::vector<std::string> inputWorkspaceNames;
+  QString qWorkspace = workspaceBaseName + "eq";
+  QString qSquaredWorkspace = workspaceBaseName + "eq2";
+  QString elfWorkspace = workspaceBaseName + "elf";
+  QString eltWorkspace = workspaceBaseName + "elt";
 
-    for(auto it = inputFilenames.begin(); it != inputFilenames.end(); ++it)
-    {
-      QFileInfo inputFileInfo(*it);
-      std::string workspaceName = inputFileInfo.baseName().toStdString();
+  // Load input files
+  std::vector<std::string> inputWorkspaceNames;
 
-      IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadNexus");
-      loadAlg->initialize();
-      loadAlg->setProperty("Filename", (*it).toStdString());
-      loadAlg->setProperty("OutputWorkspace", workspaceName);
+  for (auto it = inputFilenames.begin(); it != inputFilenames.end(); ++it) {
+    QFileInfo inputFileInfo(*it);
+    std::string workspaceName = inputFileInfo.baseName().toStdString();
 
-      m_batchAlgoRunner->addAlgorithm(loadAlg);
-      inputWorkspaceNames.push_back(workspaceName);
-    }
+    IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadNexus");
+    loadAlg->initialize();
+    loadAlg->setProperty("Filename", (*it).toStdString());
+    loadAlg->setProperty("OutputWorkspace", workspaceName);
 
-    // Group input workspaces
-    IAlgorithm_sptr groupWsAlg = AlgorithmManager::Instance().create("GroupWorkspaces");
-    groupWsAlg->initialize();
-    groupWsAlg->setProperty("InputWorkspaces", inputWorkspaceNames);
-    groupWsAlg->setProperty("OutputWorkspace", inputGroupWsName);
+    m_batchAlgoRunner->addAlgorithm(loadAlg);
+    inputWorkspaceNames.push_back(workspaceName);
+  }
 
-    m_batchAlgoRunner->addAlgorithm(groupWsAlg);
+  // Group input workspaces
+  IAlgorithm_sptr groupWsAlg =
+      AlgorithmManager::Instance().create("GroupWorkspaces");
+  groupWsAlg->initialize();
+  groupWsAlg->setProperty("InputWorkspaces", inputWorkspaceNames);
+  groupWsAlg->setProperty("OutputWorkspace", inputGroupWsName);
+
+  m_batchAlgoRunner->addAlgorithm(groupWsAlg);
+
+  // Configure ElasticWindowMultiple algorithm
+  IAlgorithm_sptr elwinMultAlg =
+      AlgorithmManager::Instance().create("ElasticWindowMultiple");
+  elwinMultAlg->initialize();
+
+  elwinMultAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked());
+
+  elwinMultAlg->setProperty("OutputInQ", qWorkspace.toStdString());
+  elwinMultAlg->setProperty("OutputInQSquared",
+                            qSquaredWorkspace.toStdString());
+  elwinMultAlg->setProperty("OutputELF", elfWorkspace.toStdString());
+
+  elwinMultAlg->setProperty("SampleEnvironmentLogName",
+                            m_uiForm.leLogName->text().toStdString());
+  elwinMultAlg->setProperty("SampleEnvironmentLogValue",
+                            m_uiForm.leLogValue->currentText().toStdString());
+
+  elwinMultAlg->setProperty(
+      "IntegrationRangeStart",
+      m_dblManager->value(m_properties["IntegrationStart"]));
+  elwinMultAlg->setProperty(
+      "IntegrationRangeEnd",
+      m_dblManager->value(m_properties["IntegrationEnd"]));
+
+  if (m_blnManager->value(m_properties["BackgroundSubtraction"])) {
+    elwinMultAlg->setProperty(
+        "BackgroundRangeStart",
+        m_dblManager->value(m_properties["BackgroundStart"]));
+    elwinMultAlg->setProperty(
+        "BackgroundRangeEnd",
+        m_dblManager->value(m_properties["BackgroundEnd"]));
+  }
 
-    // Configure ElasticWindowMultiple algorithm
-    IAlgorithm_sptr elwinMultAlg = AlgorithmManager::Instance().create("ElasticWindowMultiple");
-    elwinMultAlg->initialize();
+  if (m_blnManager->value(m_properties["Normalise"])) {
+    elwinMultAlg->setProperty("OutputELT", eltWorkspace.toStdString());
+  }
 
-    elwinMultAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked());
+  BatchAlgorithmRunner::AlgorithmRuntimeProps elwinInputProps;
+  elwinInputProps["InputWorkspaces"] = inputGroupWsName;
 
-    elwinMultAlg->setProperty("OutputInQ", qWorkspace.toStdString());
-    elwinMultAlg->setProperty("OutputInQSquared", qSquaredWorkspace.toStdString());
-    elwinMultAlg->setProperty("OutputELF", elfWorkspace.toStdString());
+  m_batchAlgoRunner->addAlgorithm(elwinMultAlg, elwinInputProps);
 
-    elwinMultAlg->setProperty("SampleEnvironmentLogName", m_uiForm.leLogName->text().toStdString());
-    elwinMultAlg->setProperty("SampleEnvironmentLogValue", m_uiForm.leLogValue->currentText().toStdString());
+  // Configure Save algorithms
+  if (m_uiForm.ckSave->isChecked()) {
+    addSaveAlgorithm(qWorkspace);
+    addSaveAlgorithm(qSquaredWorkspace);
+    addSaveAlgorithm(elfWorkspace);
 
-    elwinMultAlg->setProperty("IntegrationRangeStart", m_dblManager->value(m_properties["IntegrationStart"]));
-    elwinMultAlg->setProperty("IntegrationRangeEnd", m_dblManager->value(m_properties["IntegrationEnd"]));
+    if (m_blnManager->value(m_properties["Normalise"]))
+      addSaveAlgorithm(eltWorkspace);
+  }
 
-    if(m_blnManager->value(m_properties["BackgroundSubtraction"]))
-    {
-      elwinMultAlg->setProperty("BackgroundRangeStart", m_dblManager->value(m_properties["BackgroundStart"]));
-      elwinMultAlg->setProperty("BackgroundRangeEnd", m_dblManager->value(m_properties["BackgroundEnd"]));
-    }
+  m_batchAlgoRunner->executeBatchAsync();
 
-    if(m_blnManager->value(m_properties["Normalise"]))
-    {
-      elwinMultAlg->setProperty("OutputELT", eltWorkspace.toStdString());
-    }
-
-    BatchAlgorithmRunner::AlgorithmRuntimeProps elwinInputProps;
-    elwinInputProps["InputWorkspaces"] = inputGroupWsName;
+  // Set the result workspace for Python script export
+  m_pythonExportWsName = qSquaredWorkspace.toStdString();
+}
 
-    m_batchAlgoRunner->addAlgorithm(elwinMultAlg, elwinInputProps);
+/**
+ * Configures and adds a SaveNexus algorithm to the batch runner.
+ *
+ * @param workspaceName Name of the workspace to save
+ * @param filename Name of the file to save it as
+ */
+void Elwin::addSaveAlgorithm(QString workspaceName, QString filename) {
+  // Set a default filename if none provided
+  if (filename.isEmpty())
+    filename = workspaceName + ".nxs";
+
+  // Configure the algorithm
+  IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("SaveNexus");
+  loadAlg->initialize();
+  loadAlg->setProperty("Filename", filename.toStdString());
+
+  BatchAlgorithmRunner::AlgorithmRuntimeProps saveAlgProps;
+  saveAlgProps["InputWorkspace"] = workspaceName.toStdString();
+
+  // Add it to the batch runner
+  m_batchAlgoRunner->addAlgorithm(loadAlg, saveAlgProps);
+}
 
-    // Configure Save algorithms
-    if(m_uiForm.ckSave->isChecked())
-    {
-      addSaveAlgorithm(qWorkspace);
-      addSaveAlgorithm(qSquaredWorkspace);
-      addSaveAlgorithm(elfWorkspace);
+bool Elwin::validate() {
+  UserInputValidator uiv;
 
-      if(m_blnManager->value(m_properties["Normalise"]))
-        addSaveAlgorithm(eltWorkspace);
-    }
+  uiv.checkMWRunFilesIsValid("Input", m_uiForm.dsInputFiles);
 
-    m_batchAlgoRunner->executeBatchAsync();
+  auto rangeOne =
+      std::make_pair(m_dblManager->value(m_properties["IntegrationStart"]),
+                     m_dblManager->value(m_properties["IntegrationEnd"]));
+  uiv.checkValidRange("Range One", rangeOne);
 
-    // Set the result workspace for Python script export
-    m_pythonExportWsName = qSquaredWorkspace.toStdString();
+  bool useTwoRanges =
+      m_blnManager->value(m_properties["BackgroundSubtraction"]);
+  if (useTwoRanges) {
+    auto rangeTwo =
+        std::make_pair(m_dblManager->value(m_properties["BackgroundStart"]),
+                       m_dblManager->value(m_properties["BackgroundEnd"]));
+    uiv.checkValidRange("Range Two", rangeTwo);
+    uiv.checkRangesDontOverlap(rangeOne, rangeTwo);
   }
 
-  /**
-   * Configures and adds a SaveNexus algorithm to the batch runner.
-   *
-   * @param workspaceName Name of the workspace to save
-   * @param filename Name of the file to save it as
-   */
-  void Elwin::addSaveAlgorithm(QString workspaceName, QString filename)
-  {
-    // Set a default filename if none provided
-    if(filename.isEmpty())
-      filename = workspaceName + ".nxs";
-
-    // Configure the algorithm
-    IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("SaveNexus");
-    loadAlg->initialize();
-    loadAlg->setProperty("Filename", filename.toStdString());
+  QString error = uiv.generateErrorMessage();
+  showMessageBox(error);
 
-    BatchAlgorithmRunner::AlgorithmRuntimeProps saveAlgProps;
-    saveAlgProps["InputWorkspace"] = workspaceName.toStdString();
+  return error.isEmpty();
+}
 
-    // Add it to the batch runner
-    m_batchAlgoRunner->addAlgorithm(loadAlg, saveAlgProps);
-  }
+void Elwin::loadSettings(const QSettings &settings) {
+  m_uiForm.dsInputFiles->readSettings(settings.group());
+}
 
-  bool Elwin::validate()
-  {
-    UserInputValidator uiv;
+void Elwin::setDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws) {
+  auto inst = ws->getInstrument();
+  auto analyser = inst->getStringParameter("analyser");
 
-    uiv.checkMWRunFilesIsValid("Input", m_uiForm.dsInputFiles);
+  if (analyser.size() > 0) {
+    auto comp = inst->getComponentByName(analyser[0]);
+    auto params = comp->getNumberParameter("resolution", true);
 
-    auto rangeOne = std::make_pair(m_dblManager->value(m_properties["IntegrationStart"]), m_dblManager->value(m_properties["IntegrationEnd"]));
-    uiv.checkValidRange("Range One", rangeOne);
+    // set the default instrument resolution
+    if (params.size() > 0) {
+      double res = params[0];
+      m_dblManager->setValue(m_properties["IntegrationStart"], -res);
+      m_dblManager->setValue(m_properties["IntegrationEnd"], res);
 
-    bool useTwoRanges = m_blnManager->value(m_properties["BackgroundSubtraction"]);
-    if( useTwoRanges )
-    {
-      auto rangeTwo = std::make_pair(m_dblManager->value(m_properties["BackgroundStart"]), m_dblManager->value(m_properties["BackgroundEnd"]));
-      uiv.checkValidRange("Range Two", rangeTwo);
-      uiv.checkRangesDontOverlap(rangeOne, rangeTwo);
+      m_dblManager->setValue(m_properties["BackgroundStart"], -10 * res);
+      m_dblManager->setValue(m_properties["BackgroundEnd"], -9 * res);
     }
-
-    QString error = uiv.generateErrorMessage();
-    showMessageBox(error);
-
-    return error.isEmpty();
   }
+}
 
-  void Elwin::loadSettings(const QSettings & settings)
-  {
-    m_uiForm.dsInputFiles->readSettings(settings.group());
+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]);
   }
-
-  void Elwin::setDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws)
-  {
-    auto inst = ws->getInstrument();
-    auto analyser = inst->getStringParameter("analyser");
-
-    if(analyser.size() > 0)
-    {
-      auto comp = inst->getComponentByName(analyser[0]);
-      auto params = comp->getNumberParameter("resolution", true);
-
-      //set the default instrument resolution
-      if(params.size() > 0)
-      {
-        double res = params[0];
-        m_dblManager->setValue(m_properties["IntegrationStart"], -res);
-        m_dblManager->setValue(m_properties["IntegrationEnd"], res);
-
-        m_dblManager->setValue(m_properties["BackgroundStart"], -10*res);
-        m_dblManager->setValue(m_properties["BackgroundEnd"], -9*res);
-      }
+  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);
     }
   }
+}
 
-  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);
-      }
-    }
+/**
+ * Handles a new set of input files being entered.
+ *
+ * Updates preview seletcion combo box.
+ */
+void Elwin::newInputFiles() {
+  // Clear the existing list of files
+  m_uiForm.cbPreviewFile->clear();
+
+  // Populate the combo box with the filenames
+  QStringList filenames = m_uiForm.dsInputFiles->getFilenames();
+  for (auto it = filenames.begin(); it != filenames.end(); ++it) {
+    QString rawFilename = *it;
+    QFileInfo inputFileInfo(rawFilename);
+    QString sampleName = inputFileInfo.baseName();
+
+    // Add the item using the base filename as the display string and the raw
+    // filename as the data value
+    m_uiForm.cbPreviewFile->addItem(sampleName, rawFilename);
   }
 
-  /**
-   * Handles a new set of input files being entered.
-   *
-   * Updates preview seletcion combo box.
-   */
-  void Elwin::newInputFiles()
-  {
-    // Clear the existing list of files
-    m_uiForm.cbPreviewFile->clear();
-
-    // Populate the combo box with the filenames
-    QStringList filenames = m_uiForm.dsInputFiles->getFilenames();
-    for(auto it = filenames.begin(); it != filenames.end(); ++it)
-    {
-      QString rawFilename = *it;
-      QFileInfo inputFileInfo(rawFilename);
-      QString sampleName = inputFileInfo.baseName();
-
-      // Add the item using the base filename as the display string and the raw filename as the data value
-      m_uiForm.cbPreviewFile->addItem(sampleName, rawFilename);
-    }
+  // Default to the first file
+  m_uiForm.cbPreviewFile->setCurrentIndex(0);
+}
 
-    // Default to the first file
-    m_uiForm.cbPreviewFile->setCurrentIndex(0);
+/**
+ * Handles a new input file being selected for preview.
+ *
+ * Loads the file and resets the spectra selection spinner.
+ *
+ * @param index Index of the new selected file
+ */
+void Elwin::newPreviewFileSelected(int index) {
+  QString wsName = m_uiForm.cbPreviewFile->itemText(index);
+  QString filename = m_uiForm.cbPreviewFile->itemData(index).toString();
+
+  // Ignore empty filenames (can happen when new files are loaded and the widget
+  // is being populated)
+  if (filename.isEmpty())
+    return;
+
+  if (!loadFile(filename, wsName)) {
+    g_log.error("Failed to load input workspace.");
+    return;
   }
 
-  /**
-   * Handles a new input file being selected for preview.
-   *
-   * Loads the file and resets the spectra selection spinner.
-   *
-   * @param index Index of the new selected file
-   */
-  void Elwin::newPreviewFileSelected(int index)
-  {
-    QString wsName = m_uiForm.cbPreviewFile->itemText(index);
-    QString filename = m_uiForm.cbPreviewFile->itemData(index).toString();
-
-    // Ignore empty filenames (can happen when new files are loaded and the widget is being populated)
-    if(filename.isEmpty())
-      return;
-
-    if(!loadFile(filename, wsName))
-    {
-      g_log.error("Failed to load input workspace.");
-      return;
-    }
-
-    auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName.toStdString());
-    int numHist = static_cast<int>(ws->getNumberHistograms()) - 1;
+  auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+      wsName.toStdString());
+  int numHist = static_cast<int>(ws->getNumberHistograms()) - 1;
 
-    m_uiForm.spPreviewSpec->setMaximum(numHist);
-    m_uiForm.spPreviewSpec->setValue(0);
+  m_uiForm.spPreviewSpec->setMaximum(numHist);
+  m_uiForm.spPreviewSpec->setValue(0);
 
-    plotInput();
-  }
+  plotInput();
+}
 
-  /**
-   * Replots the preview plot.
-   */
-  void Elwin::plotInput()
-  {
-    QString wsName = m_uiForm.cbPreviewFile->currentText();
-
-    if(!AnalysisDataService::Instance().doesExist(wsName.toStdString()))
-    {
-      g_log.error("Workspace not found in ADS. Try reloading input files.");
-      return;
-    }
+/**
+ * Replots the preview plot.
+ */
+void Elwin::plotInput() {
+  QString wsName = m_uiForm.cbPreviewFile->currentText();
 
-    auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName.toStdString());
+  if (!AnalysisDataService::Instance().doesExist(wsName.toStdString())) {
+    g_log.error("Workspace not found in ADS. Try reloading input files.");
+    return;
+  }
 
-    if(!ws)
-    {
-      g_log.error("Failed to get input workspace from ADS.");
-      return;
-    }
+  auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+      wsName.toStdString());
 
-    int specNo = m_uiForm.spPreviewSpec->value();
-
-    setDefaultResolution(ws);
-    setDefaultSampleLog(ws);
-
-    m_uiForm.ppPlot->clear();
-    m_uiForm.ppPlot->addSpectrum("Sample", ws, specNo);
-
-    try {
-      QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample");
-      // Set maximum range of Integration
-      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
-          ->setRange(range.first, range.second);
-      // Set initial values
-      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
-          ->setMinimum(range.first);
-      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
-          ->setMaximum(range.second);
-    } catch (std::invalid_argument &exc) {
-      showMessageBox(exc.what());
-    }
+  if (!ws) {
+    g_log.error("Failed to get input workspace from ADS.");
+    return;
   }
 
-  void Elwin::twoRanges(QtProperty* prop, bool val)
-  {
-    if(prop == m_properties["BackgroundSubtraction"])
-      m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange")->setVisible(val);
+  int specNo = m_uiForm.spPreviewSpec->value();
+
+  setDefaultResolution(ws);
+  setDefaultSampleLog(ws);
+
+  m_uiForm.ppPlot->clear();
+  m_uiForm.ppPlot->addSpectrum("Sample", ws, specNo);
+
+  try {
+    QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample");
+    // Set maximum range of Integration
+    m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
+        ->setRange(range.first, range.second);
+    // Set initial values
+    m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
+        ->setMinimum(range.first);
+    m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange")
+        ->setMaximum(range.second);
+  } catch (std::invalid_argument &exc) {
+    showMessageBox(exc.what());
   }
+}
 
-  void Elwin::minChanged(double val)
-  {
-    auto integrationRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
-    auto backgroundRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
+void Elwin::twoRanges(QtProperty *prop, bool val) {
+  if (prop == m_properties["BackgroundSubtraction"])
+    m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange")->setVisible(val);
+}
 
-    MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+void Elwin::minChanged(double val) {
+  auto integrationRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
+  auto backgroundRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
 
-    if(from == integrationRangeSelector)
-    {
-      m_dblManager->setValue(m_properties["IntegrationStart"], val);
-    }
-    else if(from == backgroundRangeSelector)
-    {
-      m_dblManager->setValue(m_properties["BackgroundStart"], val);
-    }
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
+
+  if (from == integrationRangeSelector) {
+    m_dblManager->setValue(m_properties["IntegrationStart"], val);
+  } else if (from == backgroundRangeSelector) {
+    m_dblManager->setValue(m_properties["BackgroundStart"], val);
   }
+}
 
-  void Elwin::maxChanged(double val)
-  {
-    auto integrationRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
-    auto backgroundRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
+void Elwin::maxChanged(double val) {
+  auto integrationRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
+  auto backgroundRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
 
-    MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
 
-    if(from == integrationRangeSelector)
-    {
-      m_dblManager->setValue(m_properties["IntegrationEnd"], val);
-    }
-    else if(from == backgroundRangeSelector)
-    {
-      m_dblManager->setValue(m_properties["BackgroundEnd"], val);
-    }
+  if (from == integrationRangeSelector) {
+    m_dblManager->setValue(m_properties["IntegrationEnd"], val);
+  } else if (from == backgroundRangeSelector) {
+    m_dblManager->setValue(m_properties["BackgroundEnd"], val);
   }
+}
 
-  void Elwin::updateRS(QtProperty* prop, double val)
-  {
-    auto integrationRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
-    auto backgroundRangeSelector = m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
-
-    if ( prop == m_properties["IntegrationStart"] )     integrationRangeSelector->setMinimum(val);
-    else if ( prop == m_properties["IntegrationEnd"] )  integrationRangeSelector->setMaximum(val);
-    else if ( prop == m_properties["BackgroundStart"] ) backgroundRangeSelector->setMinimum(val);
-    else if ( prop == m_properties["BackgroundEnd"] )   backgroundRangeSelector->setMaximum(val);
-  }
+void Elwin::updateRS(QtProperty *prop, double val) {
+  auto integrationRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinIntegrationRange");
+  auto backgroundRangeSelector =
+      m_uiForm.ppPlot->getRangeSelector("ElwinBackgroundRange");
+
+  if (prop == m_properties["IntegrationStart"])
+    integrationRangeSelector->setMinimum(val);
+  else if (prop == m_properties["IntegrationEnd"])
+    integrationRangeSelector->setMaximum(val);
+  else if (prop == m_properties["BackgroundStart"])
+    backgroundRangeSelector->setMinimum(val);
+  else if (prop == m_properties["BackgroundEnd"])
+    backgroundRangeSelector->setMaximum(val);
+}
 
 } // namespace IDA
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ILLCalibration.cpp b/MantidQt/CustomInterfaces/src/Indirect/ILLCalibration.cpp
index 0669951dff9641a141e41f44c95682ad4303f78b..76ba547eb4598878420a787de34eabd14719d169 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ILLCalibration.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ILLCalibration.cpp
@@ -5,151 +5,135 @@
 using namespace Mantid::API;
 using MantidQt::API::BatchAlgorithmRunner;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("ILLCalibration");
+namespace {
+Mantid::Kernel::Logger g_log("ILLCalibration");
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  ILLCalibration::ILLCalibration(IndirectDataReduction * idrUI, QWidget * parent) :
-    IndirectDataReductionTab(idrUI, parent)
-  {
-    m_uiForm.setupUi(parent);
-
-    connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(newInstrumentSelected()));
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+ILLCalibration::ILLCalibration(IndirectDataReduction *idrUI, QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent) {
+  m_uiForm.setupUi(parent);
+
+  connect(this, SIGNAL(newInstrumentConfiguration()), this,
+          SLOT(newInstrumentSelected()));
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
+}
 
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  ILLCalibration::~ILLCalibration()
-  {
-  }
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+ILLCalibration::~ILLCalibration() {}
 
+void ILLCalibration::setup() {}
 
-  void ILLCalibration::setup()
-  {
-  }
+void ILLCalibration::run() {
+  QMap<QString, QString> instDetails = getInstrumentDetails();
 
+  IAlgorithm_sptr calibrationAlg =
+      AlgorithmManager::Instance().create("ILLIN16BCalibration");
+  calibrationAlg->initialize();
 
-  void ILLCalibration::run()
-  {
-    QMap<QString, QString> instDetails = getInstrumentDetails();
-
-    IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("ILLIN16BCalibration");
-    calibrationAlg->initialize();
-
-    // Handle einput files
-    QString runFilename = m_uiForm.rfRunFile->getFirstFilename();
-    calibrationAlg->setProperty("Run", runFilename.toStdString());
-
-    // Set options
-    bool mirrorMode = m_uiForm.ckMirrorMode->isChecked();
-    calibrationAlg->setProperty("MirrorMode", mirrorMode);
-
-    bool useMapFile = m_uiForm.cbGrouping->currentText() == "File";
-    if(useMapFile)
-    {
-      QString mapFilename = m_uiForm.rfMapFile->getFirstFilename();
-      calibrationAlg->setProperty("MapFile", mapFilename.toStdString());
-    }
-
-    std::vector<double> peakRange;
-    peakRange.push_back(m_uiForm.spPeakLower->value());
-    peakRange.push_back(m_uiForm.spPeakUpper->value());
-    calibrationAlg->setProperty("PeakRange", peakRange);
-
-    double scaleFactor = m_uiForm.spScaleFactor->value();
-    calibrationAlg->setProperty("ScaleFactor", scaleFactor);
-
-    // Get the name format for output files
-    QFileInfo runFileInfo(runFilename);
-    QString outputWsName = runFileInfo.baseName() +
-                           "_" + instDetails["analyser"] +
-                           "_" + instDetails["reflection"] +
-                           "_calib";
-
-    // Set output workspace properties
-    calibrationAlg->setProperty("OutputWorkspace", outputWsName.toStdString());
-
-    m_batchAlgoRunner->addAlgorithm(calibrationAlg);
-
-    // Handle saving
-    bool save = m_uiForm.ckSave->isChecked();
-    if(save)
-    {
-      BatchAlgorithmRunner::AlgorithmRuntimeProps saveProps;
-      saveProps["InputWorkspace"] = outputWsName.toStdString();
-      IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexusProcessed");
-      saveAlg->initialize();
-      saveAlg->setProperty("Filename", outputWsName.toStdString() + ".nxs");
-      m_batchAlgoRunner->addAlgorithm(saveAlg, saveProps);
-    }
-
-    m_batchAlgoRunner->executeBatchAsync();
-    m_pythonExportWsName = outputWsName.toStdString();
-  }
+  // Handle einput files
+  QString runFilename = m_uiForm.rfRunFile->getFirstFilename();
+  calibrationAlg->setProperty("Run", runFilename.toStdString());
 
+  // Set options
+  bool mirrorMode = m_uiForm.ckMirrorMode->isChecked();
+  calibrationAlg->setProperty("MirrorMode", mirrorMode);
 
-  void ILLCalibration::algorithmComplete(bool error)
-  {
-    if(error)
-      return;
+  bool useMapFile = m_uiForm.cbGrouping->currentText() == "File";
+  if (useMapFile) {
+    QString mapFilename = m_uiForm.rfMapFile->getFirstFilename();
+    calibrationAlg->setProperty("MapFile", mapFilename.toStdString());
+  }
 
-    // Handle plotting
-    bool plot = m_uiForm.ckPlot->isChecked();
-    if(plot)
-      plotTimeBin(QString::fromStdString(m_pythonExportWsName), 0);
+  std::vector<double> peakRange;
+  peakRange.push_back(m_uiForm.spPeakLower->value());
+  peakRange.push_back(m_uiForm.spPeakUpper->value());
+  calibrationAlg->setProperty("PeakRange", peakRange);
+
+  double scaleFactor = m_uiForm.spScaleFactor->value();
+  calibrationAlg->setProperty("ScaleFactor", scaleFactor);
+
+  // Get the name format for output files
+  QFileInfo runFileInfo(runFilename);
+  QString outputWsName = runFileInfo.baseName() + "_" +
+                         instDetails["analyser"] + "_" +
+                         instDetails["reflection"] + "_calib";
+
+  // Set output workspace properties
+  calibrationAlg->setProperty("OutputWorkspace", outputWsName.toStdString());
+
+  m_batchAlgoRunner->addAlgorithm(calibrationAlg);
+
+  // Handle saving
+  bool save = m_uiForm.ckSave->isChecked();
+  if (save) {
+    BatchAlgorithmRunner::AlgorithmRuntimeProps saveProps;
+    saveProps["InputWorkspace"] = outputWsName.toStdString();
+    IAlgorithm_sptr saveAlg =
+        AlgorithmManager::Instance().create("SaveNexusProcessed");
+    saveAlg->initialize();
+    saveAlg->setProperty("Filename", outputWsName.toStdString() + ".nxs");
+    m_batchAlgoRunner->addAlgorithm(saveAlg, saveProps);
   }
 
+  m_batchAlgoRunner->executeBatchAsync();
+  m_pythonExportWsName = outputWsName.toStdString();
+}
 
-  bool ILLCalibration::validate()
-  {
-    MantidQt::CustomInterfaces::UserInputValidator uiv;
+void ILLCalibration::algorithmComplete(bool error) {
+  if (error)
+    return;
 
-    bool useMapFile = m_uiForm.cbGrouping->currentText() == "File";
-    if(useMapFile && !m_uiForm.rfMapFile->isValid())
-      uiv.addErrorMessage("Grouping file is invalid.");
+  // Handle plotting
+  bool plot = m_uiForm.ckPlot->isChecked();
+  if (plot)
+    plotTimeBin(QString::fromStdString(m_pythonExportWsName), 0);
+}
 
-    // Validate peak range
-    auto peakRange = std::make_pair<double, double>(m_uiForm.spPeakLower->value(), m_uiForm.spPeakUpper->value());
-    uiv.checkValidRange("Peak Range", peakRange);
+bool ILLCalibration::validate() {
+  MantidQt::CustomInterfaces::UserInputValidator uiv;
 
-    // Validate run file
-    if(!m_uiForm.rfRunFile->isValid())
-      uiv.addErrorMessage("Run File is invalid.");
+  bool useMapFile = m_uiForm.cbGrouping->currentText() == "File";
+  if (useMapFile && !m_uiForm.rfMapFile->isValid())
+    uiv.addErrorMessage("Grouping file is invalid.");
 
-    // Show error for failed validation
-    if(!uiv.isAllInputValid())
-      emit showMessageBox(uiv.generateErrorMessage());
+  // Validate peak range
+  auto peakRange = std::make_pair<double, double>(
+      m_uiForm.spPeakLower->value(), m_uiForm.spPeakUpper->value());
+  uiv.checkValidRange("Peak Range", peakRange);
 
-    return uiv.isAllInputValid();
-  }
+  // Validate run file
+  if (!m_uiForm.rfRunFile->isValid())
+    uiv.addErrorMessage("Run File is invalid.");
 
+  // Show error for failed validation
+  if (!uiv.isAllInputValid())
+    emit showMessageBox(uiv.generateErrorMessage());
 
-  void ILLCalibration::newInstrumentSelected()
-  {
-    QMap<QString, QString> instDetails = getInstrumentDetails();
+  return uiv.isAllInputValid();
+}
+
+void ILLCalibration::newInstrumentSelected() {
+  QMap<QString, QString> instDetails = getInstrumentDetails();
 
-    if(instDetails.contains("resolution"))
-    {
-      double res = instDetails["resolution"].toDouble();
-      double peakLower = -res * 10;
-      double peakUpper = res * 10;
+  if (instDetails.contains("resolution")) {
+    double res = instDetails["resolution"].toDouble();
+    double peakLower = -res * 10;
+    double peakUpper = res * 10;
 
-      g_log.debug() << "Resolution is " << res << std::endl;
+    g_log.debug() << "Resolution is " << res << std::endl;
 
-      m_uiForm.spPeakLower->setValue(peakLower);
-      m_uiForm.spPeakUpper->setValue(peakUpper);
-    }
+    m_uiForm.spPeakLower->setValue(peakLower);
+    m_uiForm.spPeakUpper->setValue(peakUpper);
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ILLEnergyTransfer.cpp b/MantidQt/CustomInterfaces/src/Indirect/ILLEnergyTransfer.cpp
index 8e7769e82d4ca81059f14653d07ca2eb94a0f795..4b0f502f8ca8c9cdd7c293b9f67ee18fff64b3dd 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ILLEnergyTransfer.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ILLEnergyTransfer.cpp
@@ -8,151 +8,137 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  ILLEnergyTransfer::ILLEnergyTransfer(IndirectDataReduction * idrUI, QWidget * parent) :
-      IndirectDataReductionTab(idrUI, parent)
-  {
-    m_uiForm.setupUi(parent);
-
-    connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(setInstrumentDefault()));
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
-
-    // Validate to remove invalid markers
-    validateTab();
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+ILLEnergyTransfer::ILLEnergyTransfer(IndirectDataReduction *idrUI,
+                                     QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent) {
+  m_uiForm.setupUi(parent);
+
+  connect(this, SIGNAL(newInstrumentConfiguration()), this,
+          SLOT(setInstrumentDefault()));
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
+
+  // Validate to remove invalid markers
+  validateTab();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+ILLEnergyTransfer::~ILLEnergyTransfer() {}
+
+void ILLEnergyTransfer::setup() {}
+
+bool ILLEnergyTransfer::validate() {
+  UserInputValidator uiv;
+
+  // Validate run file
+  if (!m_uiForm.rfInput->isValid())
+    uiv.addErrorMessage("Run File is invalid.");
+
+  // Validate calibration file/workspace if it is being used
+  if (m_uiForm.ckUseCalibration->isChecked())
+    uiv.checkDataSelectorIsValid("Calibration", m_uiForm.dsCalibration);
+
+  // Validate map file if it is being used
+  bool useMapFile = m_uiForm.cbGroupingType->currentText() == "File";
+  if (useMapFile && !m_uiForm.rfMapFile->isValid())
+    uiv.addErrorMessage("Grouping file is invalid.");
+
+  // Show error message for errors
+  if (!uiv.isAllInputValid())
+    showMessageBox(uiv.generateErrorMessage());
+
+  return uiv.isAllInputValid();
+}
+
+void ILLEnergyTransfer::run() {
+  QMap<QString, QString> instDetails = getInstrumentDetails();
+
+  IAlgorithm_sptr reductionAlg =
+      AlgorithmManager::Instance().create("IndirectILLReduction");
+  reductionAlg->initialize();
+
+  reductionAlg->setProperty("Analyser", instDetails["analyser"].toStdString());
+  reductionAlg->setProperty("Reflection",
+                            instDetails["reflection"].toStdString());
+
+  // Handle input files
+  QString runFilename = m_uiForm.rfInput->getFirstFilename();
+  reductionAlg->setProperty("Run", runFilename.toStdString());
+
+  // Handle calibration
+  bool useCalibration = m_uiForm.ckUseCalibration->isChecked();
+  if (useCalibration) {
+    QString calibrationWsName = m_uiForm.dsCalibration->getCurrentDataName();
+    reductionAlg->setProperty("CalibrationWorkspace",
+                              calibrationWsName.toStdString());
   }
 
-
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  ILLEnergyTransfer::~ILLEnergyTransfer()
-  {
-  }
-
-
-  void ILLEnergyTransfer::setup()
-  {
+  // Handle mapping file
+  bool useMapFile = m_uiForm.cbGroupingType->currentText() == "File";
+  if (useMapFile) {
+    QString mapFilename = m_uiForm.rfMapFile->getFirstFilename();
+    reductionAlg->setProperty("MapFile", mapFilename.toStdString());
   }
 
-
-  bool ILLEnergyTransfer::validate()
-  {
-    UserInputValidator uiv;
-
-    // Validate run file
-    if(!m_uiForm.rfInput->isValid())
-      uiv.addErrorMessage("Run File is invalid.");
-
-    // Validate calibration file/workspace if it is being used
-    if(m_uiForm.ckUseCalibration->isChecked())
-      uiv.checkDataSelectorIsValid("Calibration", m_uiForm.dsCalibration);
-
-    // Validate map file if it is being used
-    bool useMapFile = m_uiForm.cbGroupingType->currentText() == "File";
-    if(useMapFile && !m_uiForm.rfMapFile->isValid())
-      uiv.addErrorMessage("Grouping file is invalid.");
-
-    // Show error message for errors
-    if(!uiv.isAllInputValid())
-      showMessageBox(uiv.generateErrorMessage());
-
-    return uiv.isAllInputValid();
-  }
-
-
-  void ILLEnergyTransfer::run()
-  {
-    QMap<QString, QString> instDetails = getInstrumentDetails();
-
-    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("IndirectILLReduction");
-    reductionAlg->initialize();
-
-    reductionAlg->setProperty("Analyser", instDetails["analyser"].toStdString());
-    reductionAlg->setProperty("Reflection", instDetails["reflection"].toStdString());
-
-    // Handle input files
-    QString runFilename = m_uiForm.rfInput->getFirstFilename();
-    reductionAlg->setProperty("Run", runFilename.toStdString());
-
-    // Handle calibration
-    bool useCalibration = m_uiForm.ckUseCalibration->isChecked();
-    if(useCalibration)
-    {
-      QString calibrationWsName = m_uiForm.dsCalibration->getCurrentDataName();
-      reductionAlg->setProperty("CalibrationWorkspace", calibrationWsName.toStdString());
-    }
-
-    // Handle mapping file
-    bool useMapFile = m_uiForm.cbGroupingType->currentText() == "File";
-    if(useMapFile)
-    {
-      QString mapFilename = m_uiForm.rfMapFile->getFirstFilename();
-      reductionAlg->setProperty("MapFile", mapFilename.toStdString());
-    }
-
-    // Set mirror mode option
-    bool mirrorMode = m_uiForm.ckMirrorMode->isChecked();
-    reductionAlg->setProperty("MirrorMode", mirrorMode);
-
-    // Get the name format for output files
-    QFileInfo runFileInfo(runFilename);
-    QString outputFilenameBase = runFileInfo.baseName() +
-                                 "_" + instDetails["analyser"] +
-                                 "_" + instDetails["reflection"];
-    std::string outputFilenameBaseStd = outputFilenameBase.toStdString();
-
-    // Set left and right workspaces when using mirror mode
-    if(mirrorMode)
-    {
-      reductionAlg->setProperty("LeftWorkspace", outputFilenameBaseStd + "_left");
-      reductionAlg->setProperty("RightWorkspace", outputFilenameBaseStd + "_right");
-    }
-
-    // Set output workspace properties
-    reductionAlg->setProperty("RawWorkspace", outputFilenameBaseStd + "_raw");
-    reductionAlg->setProperty("ReducedWorkspace", outputFilenameBaseStd + "_red");
-
-    // Set output options
-    reductionAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked());
-    reductionAlg->setProperty("Save", m_uiForm.ckSave->isChecked());
-
-    m_batchAlgoRunner->addAlgorithm(reductionAlg);
-    m_batchAlgoRunner->executeBatchAsync();
-  }
-
-
-  /**
-   * Handles completion of the algorithm.
-   *
-   * @param error True if the algorithm was stopped due to error, false otherwise
-   */
-  void ILLEnergyTransfer::algorithmComplete(bool error)
-  {
-    if(error)
-      return;
-
-    // Nothing to do here
-  }
-
-
-  /**
-   * Called when the instrument has changed, used to update default values.
-   */
-  void ILLEnergyTransfer::setInstrumentDefault()
-  {
-    QMap<QString, QString> instDetails = getInstrumentDetails();
-
-    // Set instrument in run file widgets
-    m_uiForm.rfInput->setInstrumentOverride(instDetails["instrument"]);
-    m_uiForm.rfMapFile->setInstrumentOverride(instDetails["instrument"]);
+  // Set mirror mode option
+  bool mirrorMode = m_uiForm.ckMirrorMode->isChecked();
+  reductionAlg->setProperty("MirrorMode", mirrorMode);
+
+  // Get the name format for output files
+  QFileInfo runFileInfo(runFilename);
+  QString outputFilenameBase = runFileInfo.baseName() + "_" +
+                               instDetails["analyser"] + "_" +
+                               instDetails["reflection"];
+  std::string outputFilenameBaseStd = outputFilenameBase.toStdString();
+
+  // Set left and right workspaces when using mirror mode
+  if (mirrorMode) {
+    reductionAlg->setProperty("LeftWorkspace", outputFilenameBaseStd + "_left");
+    reductionAlg->setProperty("RightWorkspace",
+                              outputFilenameBaseStd + "_right");
   }
 
+  // Set output workspace properties
+  reductionAlg->setProperty("RawWorkspace", outputFilenameBaseStd + "_raw");
+  reductionAlg->setProperty("ReducedWorkspace", outputFilenameBaseStd + "_red");
+
+  // Set output options
+  reductionAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked());
+  reductionAlg->setProperty("Save", m_uiForm.ckSave->isChecked());
+
+  m_batchAlgoRunner->addAlgorithm(reductionAlg);
+  m_batchAlgoRunner->executeBatchAsync();
+}
+
+/**
+ * Handles completion of the algorithm.
+ *
+ * @param error True if the algorithm was stopped due to error, false otherwise
+ */
+void ILLEnergyTransfer::algorithmComplete(bool error) {
+  if (error)
+    return;
+
+  // Nothing to do here
+}
+
+/**
+ * Called when the instrument has changed, used to update default values.
+ */
+void ILLEnergyTransfer::setInstrumentDefault() {
+  QMap<QString, QString> instDetails = getInstrumentDetails();
+
+  // Set instrument in run file widgets
+  m_uiForm.rfInput->setInstrumentOverride(instDetails["instrument"]);
+  m_uiForm.rfMapFile->setInstrumentOverride(instDetails["instrument"]);
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp b/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
index aff11c0aa4d7b2382d8dae1116986e64bb6714a2..ad7c03a7dbce71c4af137c2215815cad331a2acf 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp
@@ -7,673 +7,707 @@
 
 using namespace Mantid::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("ISISCalibration");
+namespace {
+Mantid::Kernel::Logger g_log("ISISCalibration");
 }
 
 using namespace Mantid::API;
 using MantidQt::API::BatchAlgorithmRunner;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  ISISCalibration::ISISCalibration(IndirectDataReduction * idrUI, QWidget * parent) :
-    IndirectDataReductionTab(idrUI, parent),
-    m_lastCalPlotFilename("")
-  {
-    m_uiForm.setupUi(parent);
-
-    DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
-
-    // CAL PROPERTY TREE
-    m_propTrees["CalPropTree"] = new QtTreePropertyBrowser();
-    m_propTrees["CalPropTree"]->setFactoryForManager(m_dblManager, doubleEditorFactory);
-    m_uiForm.propertiesCalibration->addWidget(m_propTrees["CalPropTree"]);
-
-    // Cal Property Tree: Peak/Background
-    m_properties["CalPeakMin"] = m_dblManager->addProperty("Peak Min");
-    m_properties["CalPeakMax"] = m_dblManager->addProperty("Peak Max");
-    m_properties["CalBackMin"] = m_dblManager->addProperty("Back Min");
-    m_properties["CalBackMax"] = m_dblManager->addProperty("Back Max");
-
-    m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMin"]);
-    m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMax"]);
-    m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMin"]);
-    m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMax"]);
-
-    // Cal plot range selectors
-    auto calPeak = m_uiForm.ppCalibration->addRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->addRangeSelector("CalBackground");
-    calBackground->setColour(Qt::darkGreen); //Dark green to signify background range
-
-    // RES PROPERTY TREE
-    m_propTrees["ResPropTree"] = new QtTreePropertyBrowser();
-    m_propTrees["ResPropTree"]->setFactoryForManager(m_dblManager, doubleEditorFactory);
-    m_uiForm.loResolutionOptions->addWidget(m_propTrees["ResPropTree"]);
-
-    // Res Property Tree: Spectra Selection
-    m_properties["ResSpecMin"] = m_dblManager->addProperty("Spectra Min");
-    m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMin"]);
-    m_dblManager->setDecimals(m_properties["ResSpecMin"], 0);
-
-    m_properties["ResSpecMax"] = m_dblManager->addProperty("Spectra Max");
-    m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMax"]);
-    m_dblManager->setDecimals(m_properties["ResSpecMax"], 0);
-
-    // Res Property Tree: Background Properties
-    QtProperty* resBG = m_grpManager->addProperty("Background");
-    m_propTrees["ResPropTree"]->addProperty(resBG);
-
-    m_properties["ResStart"] = m_dblManager->addProperty("Start");
-    resBG->addSubProperty(m_properties["ResStart"]);
-
-    m_properties["ResEnd"] = m_dblManager->addProperty("End");
-    resBG->addSubProperty(m_properties["ResEnd"]);
-
-    // Res Property Tree: Rebinning
-    const int NUM_DECIMALS = 3;
-    QtProperty* resRB = m_grpManager->addProperty("Rebinning");
-    m_propTrees["ResPropTree"]->addProperty(resRB);
-
-    m_properties["ResELow"] = m_dblManager->addProperty("Low");
-    m_dblManager->setDecimals(m_properties["ResELow"], NUM_DECIMALS);
-    m_dblManager->setValue(m_properties["ResELow"], -0.2);
-    resRB->addSubProperty(m_properties["ResELow"]);
-
-    m_properties["ResEWidth"] = m_dblManager->addProperty("Width");
-    m_dblManager->setDecimals(m_properties["ResEWidth"], NUM_DECIMALS);
-    m_dblManager->setValue(m_properties["ResEWidth"], 0.002);
-    m_dblManager->setMinimum(m_properties["ResEWidth"], 0.001);
-    resRB->addSubProperty(m_properties["ResEWidth"]);
-
-    m_properties["ResEHigh"] = m_dblManager->addProperty("High");
-    m_dblManager->setDecimals(m_properties["ResEHigh"], NUM_DECIMALS);
-    m_dblManager->setValue(m_properties["ResEHigh"], 0.2);
-    resRB->addSubProperty(m_properties["ResEHigh"]);
-
-    // Res plot range selectors
-    // Create ResBackground first so ResPeak is drawn above it
-    auto resBackground = m_uiForm.ppResolution->addRangeSelector("ResBackground");
-    resBackground->setColour(Qt::darkGreen);
-    auto resPeak = m_uiForm.ppResolution->addRangeSelector("ResPeak");
-
-    // SIGNAL/SLOT CONNECTIONS
-    // Update instrument information when a new instrument config is selected
-    connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(setDefaultInstDetails()));
-
-    connect(resPeak, SIGNAL(rangeChanged(double, double)),
-            resBackground, SLOT(setRange(double, double)));
-
-    // Update property map when a range seclector is moved
-    connect(calPeak, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-    connect(calPeak, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-    connect(calBackground, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-    connect(calBackground, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-    connect(resPeak, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-    connect(resPeak, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-    connect(resBackground, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-    connect(resBackground, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-
-    // Update range selctor positions when a value in the double manager changes
-    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
-    // Plot miniplots after a file has loaded
-    connect(m_uiForm.leRunNo, SIGNAL(filesFound()), this, SLOT(calPlotRaw()));
-    // Plot miniplots when the user clicks Plot Raw
-    connect(m_uiForm.pbPlotRaw, SIGNAL(clicked()), this, SLOT(calPlotRaw()));
-    // Toggle RES file options when user toggles Create RES File checkbox
-    connect(m_uiForm.ckCreateResolution, SIGNAL(toggled(bool)), this, SLOT(resCheck(bool)));
-
-    // Shows message on run buton when user is inputting a run number
-    connect(m_uiForm.leRunNo, SIGNAL(fileTextChanged(const QString &)), this, SLOT(pbRunEditing()));
-    // Shows message on run button when Mantid is finding the file for a given run number
-    connect(m_uiForm.leRunNo, SIGNAL(findingFiles()), this, SLOT(pbRunFinding()));
-    // Reverts run button back to normal when file finding has finished
-    connect(m_uiForm.leRunNo, SIGNAL(fileFindingFinished()), this, SLOT(pbRunFinished()));
-
-    // Nudge resCheck to ensure res range selectors are only shown when Create RES file is checked
-    resCheck(m_uiForm.ckCreateResolution->isChecked());
-
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  ISISCalibration::~ISISCalibration()
-  {
-  }
-
-  void ISISCalibration::setup()
-  {
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+ISISCalibration::ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent), m_lastCalPlotFilename("") {
+  m_uiForm.setupUi(parent);
+
+  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
+
+  // CAL PROPERTY TREE
+  m_propTrees["CalPropTree"] = new QtTreePropertyBrowser();
+  m_propTrees["CalPropTree"]->setFactoryForManager(m_dblManager,
+                                                   doubleEditorFactory);
+  m_uiForm.propertiesCalibration->addWidget(m_propTrees["CalPropTree"]);
+
+  // Cal Property Tree: Peak/Background
+  m_properties["CalPeakMin"] = m_dblManager->addProperty("Peak Min");
+  m_properties["CalPeakMax"] = m_dblManager->addProperty("Peak Max");
+  m_properties["CalBackMin"] = m_dblManager->addProperty("Back Min");
+  m_properties["CalBackMax"] = m_dblManager->addProperty("Back Max");
+
+  m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMin"]);
+  m_propTrees["CalPropTree"]->addProperty(m_properties["CalPeakMax"]);
+  m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMin"]);
+  m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMax"]);
+
+  // Cal plot range selectors
+  auto calPeak = m_uiForm.ppCalibration->addRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->addRangeSelector("CalBackground");
+  calBackground->setColour(
+      Qt::darkGreen); // Dark green to signify background range
+
+  // RES PROPERTY TREE
+  m_propTrees["ResPropTree"] = new QtTreePropertyBrowser();
+  m_propTrees["ResPropTree"]->setFactoryForManager(m_dblManager,
+                                                   doubleEditorFactory);
+  m_uiForm.loResolutionOptions->addWidget(m_propTrees["ResPropTree"]);
+
+  // Res Property Tree: Spectra Selection
+  m_properties["ResSpecMin"] = m_dblManager->addProperty("Spectra Min");
+  m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMin"]);
+  m_dblManager->setDecimals(m_properties["ResSpecMin"], 0);
+
+  m_properties["ResSpecMax"] = m_dblManager->addProperty("Spectra Max");
+  m_propTrees["ResPropTree"]->addProperty(m_properties["ResSpecMax"]);
+  m_dblManager->setDecimals(m_properties["ResSpecMax"], 0);
+
+  // Res Property Tree: Background Properties
+  QtProperty *resBG = m_grpManager->addProperty("Background");
+  m_propTrees["ResPropTree"]->addProperty(resBG);
+
+  m_properties["ResStart"] = m_dblManager->addProperty("Start");
+  resBG->addSubProperty(m_properties["ResStart"]);
+
+  m_properties["ResEnd"] = m_dblManager->addProperty("End");
+  resBG->addSubProperty(m_properties["ResEnd"]);
+
+  // Res Property Tree: Rebinning
+  const int NUM_DECIMALS = 3;
+  QtProperty *resRB = m_grpManager->addProperty("Rebinning");
+  m_propTrees["ResPropTree"]->addProperty(resRB);
+
+  m_properties["ResELow"] = m_dblManager->addProperty("Low");
+  m_dblManager->setDecimals(m_properties["ResELow"], NUM_DECIMALS);
+  m_dblManager->setValue(m_properties["ResELow"], -0.2);
+  resRB->addSubProperty(m_properties["ResELow"]);
+
+  m_properties["ResEWidth"] = m_dblManager->addProperty("Width");
+  m_dblManager->setDecimals(m_properties["ResEWidth"], NUM_DECIMALS);
+  m_dblManager->setValue(m_properties["ResEWidth"], 0.002);
+  m_dblManager->setMinimum(m_properties["ResEWidth"], 0.001);
+  resRB->addSubProperty(m_properties["ResEWidth"]);
+
+  m_properties["ResEHigh"] = m_dblManager->addProperty("High");
+  m_dblManager->setDecimals(m_properties["ResEHigh"], NUM_DECIMALS);
+  m_dblManager->setValue(m_properties["ResEHigh"], 0.2);
+  resRB->addSubProperty(m_properties["ResEHigh"]);
+
+  // Res plot range selectors
+  // Create ResBackground first so ResPeak is drawn above it
+  auto resBackground = m_uiForm.ppResolution->addRangeSelector("ResBackground");
+  resBackground->setColour(Qt::darkGreen);
+  auto resPeak = m_uiForm.ppResolution->addRangeSelector("ResPeak");
+
+  // SIGNAL/SLOT CONNECTIONS
+  // Update instrument information when a new instrument config is selected
+  connect(this, SIGNAL(newInstrumentConfiguration()), this,
+          SLOT(setDefaultInstDetails()));
+
+  connect(resPeak, SIGNAL(rangeChanged(double, double)), resBackground,
+          SLOT(setRange(double, double)));
+
+  // Update property map when a range seclector is moved
+  connect(calPeak, SIGNAL(minValueChanged(double)), this,
+          SLOT(calMinChanged(double)));
+  connect(calPeak, SIGNAL(maxValueChanged(double)), this,
+          SLOT(calMaxChanged(double)));
+  connect(calBackground, SIGNAL(minValueChanged(double)), this,
+          SLOT(calMinChanged(double)));
+  connect(calBackground, SIGNAL(maxValueChanged(double)), this,
+          SLOT(calMaxChanged(double)));
+  connect(resPeak, SIGNAL(minValueChanged(double)), this,
+          SLOT(calMinChanged(double)));
+  connect(resPeak, SIGNAL(maxValueChanged(double)), this,
+          SLOT(calMaxChanged(double)));
+  connect(resBackground, SIGNAL(minValueChanged(double)), this,
+          SLOT(calMinChanged(double)));
+  connect(resBackground, SIGNAL(maxValueChanged(double)), this,
+          SLOT(calMaxChanged(double)));
+
+  // Update range selctor positions when a value in the double manager changes
+  connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
+          SLOT(calUpdateRS(QtProperty *, double)));
+  // Plot miniplots after a file has loaded
+  connect(m_uiForm.leRunNo, SIGNAL(filesFound()), this, SLOT(calPlotRaw()));
+  // Plot miniplots when the user clicks Plot Raw
+  connect(m_uiForm.pbPlotRaw, SIGNAL(clicked()), this, SLOT(calPlotRaw()));
+  // Toggle RES file options when user toggles Create RES File checkbox
+  connect(m_uiForm.ckCreateResolution, SIGNAL(toggled(bool)), this,
+          SLOT(resCheck(bool)));
+
+  // Shows message on run buton when user is inputting a run number
+  connect(m_uiForm.leRunNo, SIGNAL(fileTextChanged(const QString &)), this,
+          SLOT(pbRunEditing()));
+  // Shows message on run button when Mantid is finding the file for a given run
+  // number
+  connect(m_uiForm.leRunNo, SIGNAL(findingFiles()), this, SLOT(pbRunFinding()));
+  // Reverts run button back to normal when file finding has finished
+  connect(m_uiForm.leRunNo, SIGNAL(fileFindingFinished()), this,
+          SLOT(pbRunFinished()));
+
+  // Nudge resCheck to ensure res range selectors are only shown when Create RES
+  // file is checked
+  resCheck(m_uiForm.ckCreateResolution->isChecked());
+
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
+}
 
-  void ISISCalibration::run() {
-    // Get properties
-    QStringList filenameList = m_uiForm.leRunNo->getFilenames();
-    QString filenames = filenameList.join(",");
-    QString userInFiles = m_uiForm.leRunNo->getText();
-    QString firstFileNumber("");
-    auto cutIndexDash = userInFiles.indexOf("-");
-    auto cutIndexComma = userInFiles.indexOf(",");
-
-    if (cutIndexDash == -1 && cutIndexComma == -1) {
-      firstFileNumber = userInFiles;
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+ISISCalibration::~ISISCalibration() {}
+
+void ISISCalibration::setup() {}
+
+void ISISCalibration::run() {
+  // Get properties
+  QStringList filenameList = m_uiForm.leRunNo->getFilenames();
+  QString filenames = filenameList.join(",");
+  QString userInFiles = m_uiForm.leRunNo->getText();
+  QString firstFileNumber("");
+  auto cutIndexDash = userInFiles.indexOf("-");
+  auto cutIndexComma = userInFiles.indexOf(",");
+
+  if (cutIndexDash == -1 && cutIndexComma == -1) {
+    firstFileNumber = userInFiles;
+  } else {
+    if (cutIndexDash != -1) {
+      firstFileNumber = userInFiles.left(cutIndexDash);
     } else {
-      if (cutIndexDash != -1) {
+      firstFileNumber = userInFiles.left(cutIndexComma);
+    }
+    if (cutIndexDash != -1 && cutIndexComma != -1) {
+      if (cutIndexDash < cutIndexComma) {
         firstFileNumber = userInFiles.left(cutIndexDash);
       } else {
         firstFileNumber = userInFiles.left(cutIndexComma);
       }
-      if (cutIndexDash != -1 && cutIndexComma != -1) {
-        if (cutIndexDash < cutIndexComma) {
-          firstFileNumber = userInFiles.left(cutIndexDash);
-        } else {
-          firstFileNumber = userInFiles.left(cutIndexComma);
-        }
-      }
     }
+  }
 
-    auto instDetails = getInstrumentDetails();
-    QString instDetectorRange =
-        instDetails["spectra-min"] + "," + instDetails["spectra-max"];
-
-    QString peakRange = m_properties["CalPeakMin"]->valueText() + "," +
-                        m_properties["CalPeakMax"]->valueText();
-    QString backgroundRange = m_properties["CalBackMin"]->valueText() + "," +
-                              m_properties["CalBackMax"]->valueText();
-
-    QString outputWorkspaceNameStem =
-        getInstrumentConfiguration()->getInstrumentName() + firstFileNumber +
-        QString::fromStdString("_") +
-        getInstrumentConfiguration()->getAnalyserName() +
-        getInstrumentConfiguration()->getReflectionName();
-
-        outputWorkspaceNameStem = outputWorkspaceNameStem.toLower();
-
-    m_outputCalibrationName = outputWorkspaceNameStem;
-    if(filenameList.size() > 1)
-        m_outputCalibrationName += "_multi";
-    m_outputCalibrationName += "_calib";
-
-    // Configure the calibration algorithm
-    IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("IndirectCalibration");
-    calibrationAlg->initialize();
-
-    calibrationAlg->setProperty("InputFiles", filenames.toStdString());
-    calibrationAlg->setProperty("OutputWorkspace", m_outputCalibrationName.toStdString());
-    calibrationAlg->setProperty("DetectorRange", instDetectorRange.toStdString());
-    calibrationAlg->setProperty("PeakRange", peakRange.toStdString());
-    calibrationAlg->setProperty("BackgroundRange", backgroundRange.toStdString());
-
-    if(m_uiForm.ckScale->isChecked())
-    {
-      double scale = m_uiForm.spScale->value();
-      calibrationAlg->setProperty("ScaleFactor", scale);
-    }
+  auto instDetails = getInstrumentDetails();
+  QString instDetectorRange =
+      instDetails["spectra-min"] + "," + instDetails["spectra-max"];
+
+  QString peakRange = m_properties["CalPeakMin"]->valueText() + "," +
+                      m_properties["CalPeakMax"]->valueText();
+  QString backgroundRange = m_properties["CalBackMin"]->valueText() + "," +
+                            m_properties["CalBackMax"]->valueText();
+
+  QString outputWorkspaceNameStem =
+      getInstrumentConfiguration()->getInstrumentName() + firstFileNumber +
+      QString::fromStdString("_") +
+      getInstrumentConfiguration()->getAnalyserName() +
+      getInstrumentConfiguration()->getReflectionName();
+
+  outputWorkspaceNameStem = outputWorkspaceNameStem.toLower();
+
+  m_outputCalibrationName = outputWorkspaceNameStem;
+  if (filenameList.size() > 1)
+    m_outputCalibrationName += "_multi";
+  m_outputCalibrationName += "_calib";
+
+  // Configure the calibration algorithm
+  IAlgorithm_sptr calibrationAlg =
+      AlgorithmManager::Instance().create("IndirectCalibration");
+  calibrationAlg->initialize();
+
+  calibrationAlg->setProperty("InputFiles", filenames.toStdString());
+  calibrationAlg->setProperty("OutputWorkspace",
+                              m_outputCalibrationName.toStdString());
+  calibrationAlg->setProperty("DetectorRange", instDetectorRange.toStdString());
+  calibrationAlg->setProperty("PeakRange", peakRange.toStdString());
+  calibrationAlg->setProperty("BackgroundRange", backgroundRange.toStdString());
+
+  if (m_uiForm.ckScale->isChecked()) {
+    double scale = m_uiForm.spScale->value();
+    calibrationAlg->setProperty("ScaleFactor", scale);
+  }
 
-    bool save = m_uiForm.ckSave->isChecked();
+  bool save = m_uiForm.ckSave->isChecked();
 
-    m_batchAlgoRunner->addAlgorithm(calibrationAlg);
+  m_batchAlgoRunner->addAlgorithm(calibrationAlg);
 
-    // Initially take the calibration workspace as the result
-    m_pythonExportWsName = m_outputCalibrationName.toStdString();
+  // Initially take the calibration workspace as the result
+  m_pythonExportWsName = m_outputCalibrationName.toStdString();
 
-    // Add save algorithm to queue if ticked
-    if(save)
-      addSaveWorkspaceToQueue(m_outputCalibrationName);
+  // Add save algorithm to queue if ticked
+  if (save)
+    addSaveWorkspaceToQueue(m_outputCalibrationName);
 
-    // Configure the resolution algorithm
-    if(m_uiForm.ckCreateResolution->isChecked())
-    {
-      m_outputResolutionName = outputWorkspaceNameStem;
-      if(filenameList.size() > 1)
-        m_outputResolutionName += "_multi";
-      m_outputResolutionName += "_res";
+  // Configure the resolution algorithm
+  if (m_uiForm.ckCreateResolution->isChecked()) {
+    m_outputResolutionName = outputWorkspaceNameStem;
+    if (filenameList.size() > 1)
+      m_outputResolutionName += "_multi";
+    m_outputResolutionName += "_res";
 
-      QString resDetectorRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + ","
-          + QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
+    QString resDetectorRange =
+        QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + "," +
+        QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
 
-      QString rebinString = QString::number(m_dblManager->value(m_properties["ResELow"])) + "," +
+    QString rebinString =
+        QString::number(m_dblManager->value(m_properties["ResELow"])) + "," +
         QString::number(m_dblManager->value(m_properties["ResEWidth"])) + "," +
         QString::number(m_dblManager->value(m_properties["ResEHigh"]));
 
-      QString background = QString::number(m_dblManager->value(m_properties["ResStart"])) + ","
-          + QString::number(m_dblManager->value(m_properties["ResEnd"]));
-
-      bool smooth = m_uiForm.ckSmoothResolution->isChecked();
-
-      IAlgorithm_sptr resAlg = AlgorithmManager::Instance().create("IndirectResolution", -1);
-      resAlg->initialize();
-
-      resAlg->setProperty("InputFiles", filenames.toStdString());
-      resAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString());
-      resAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString());
-      resAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString());
-      resAlg->setProperty("RebinParam", rebinString.toStdString());
-      resAlg->setProperty("DetectorRange", resDetectorRange.toStdString());
-      resAlg->setProperty("BackgroundRange", background.toStdString());
-
-      if(m_uiForm.ckResolutionScale->isChecked())
-        resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value());
-
-      if(smooth)
-        resAlg->setProperty("OutputWorkspace", m_outputResolutionName.toStdString() + "_pre_smooth");
-      else
-        resAlg->setProperty("OutputWorkspace", m_outputResolutionName.toStdString());
-
-      m_batchAlgoRunner->addAlgorithm(resAlg);
+    QString background =
+        QString::number(m_dblManager->value(m_properties["ResStart"])) + "," +
+        QString::number(m_dblManager->value(m_properties["ResEnd"]));
+
+    bool smooth = m_uiForm.ckSmoothResolution->isChecked();
+
+    IAlgorithm_sptr resAlg =
+        AlgorithmManager::Instance().create("IndirectResolution", -1);
+    resAlg->initialize();
+
+    resAlg->setProperty("InputFiles", filenames.toStdString());
+    resAlg->setProperty(
+        "Instrument",
+        getInstrumentConfiguration()->getInstrumentName().toStdString());
+    resAlg->setProperty(
+        "Analyser",
+        getInstrumentConfiguration()->getAnalyserName().toStdString());
+    resAlg->setProperty(
+        "Reflection",
+        getInstrumentConfiguration()->getReflectionName().toStdString());
+    resAlg->setProperty("RebinParam", rebinString.toStdString());
+    resAlg->setProperty("DetectorRange", resDetectorRange.toStdString());
+    resAlg->setProperty("BackgroundRange", background.toStdString());
+
+    if (m_uiForm.ckResolutionScale->isChecked())
+      resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value());
+
+    if (smooth)
+      resAlg->setProperty("OutputWorkspace",
+                          m_outputResolutionName.toStdString() + "_pre_smooth");
+    else
+      resAlg->setProperty("OutputWorkspace",
+                          m_outputResolutionName.toStdString());
 
-      if(smooth)
-      {
-        IAlgorithm_sptr smoothAlg = AlgorithmManager::Instance().create("WienerSmooth");
-        smoothAlg->initialize();
-        smoothAlg->setProperty("OutputWorkspace", m_outputResolutionName.toStdString());
+    m_batchAlgoRunner->addAlgorithm(resAlg);
 
-        BatchAlgorithmRunner::AlgorithmRuntimeProps smoothAlgInputProps;
-        smoothAlgInputProps["InputWorkspace"] = m_outputResolutionName.toStdString() + "_pre_smooth";
+    if (smooth) {
+      IAlgorithm_sptr smoothAlg =
+          AlgorithmManager::Instance().create("WienerSmooth");
+      smoothAlg->initialize();
+      smoothAlg->setProperty("OutputWorkspace",
+                             m_outputResolutionName.toStdString());
 
-        m_batchAlgoRunner->addAlgorithm(smoothAlg, smoothAlgInputProps);
-      }
+      BatchAlgorithmRunner::AlgorithmRuntimeProps smoothAlgInputProps;
+      smoothAlgInputProps["InputWorkspace"] =
+          m_outputResolutionName.toStdString() + "_pre_smooth";
 
-      if(save)
-        addSaveWorkspaceToQueue(m_outputResolutionName);
-
-      // When creating resolution file take the resolution workspace as the result
-      m_pythonExportWsName = m_outputResolutionName.toStdString();
+      m_batchAlgoRunner->addAlgorithm(smoothAlg, smoothAlgInputProps);
     }
 
-    m_batchAlgoRunner->executeBatchAsync();
-  }
+    if (save)
+      addSaveWorkspaceToQueue(m_outputResolutionName);
 
-  /*
-   * Handle completion of the calibration and resolution algorithms.
-   *
-   * @param error If the algorithms failed.
-   */
-  void ISISCalibration::algorithmComplete(bool error)
-  {
-    if(error)
-      return;
+    // When creating resolution file take the resolution workspace as the result
+    m_pythonExportWsName = m_outputResolutionName.toStdString();
+  }
 
-    if(m_uiForm.ckPlot->isChecked())
-    {
-      plotTimeBin(m_outputCalibrationName);
+  m_batchAlgoRunner->executeBatchAsync();
+}
 
-      QStringList plotWorkspaces;
-      if(m_uiForm.ckCreateResolution->isChecked())
-      {
-        plotWorkspaces << m_outputResolutionName;
-        if(m_uiForm.ckSmoothResolution->isChecked())
-          plotWorkspaces << m_outputResolutionName + "_pre_smooth";
-      }
-      plotSpectrum(plotWorkspaces);
+/*
+ * Handle completion of the calibration and resolution algorithms.
+ *
+ * @param error If the algorithms failed.
+ */
+void ISISCalibration::algorithmComplete(bool error) {
+  if (error)
+    return;
+
+  if (m_uiForm.ckPlot->isChecked()) {
+    plotTimeBin(m_outputCalibrationName);
+
+    QStringList plotWorkspaces;
+    if (m_uiForm.ckCreateResolution->isChecked()) {
+      plotWorkspaces << m_outputResolutionName;
+      if (m_uiForm.ckSmoothResolution->isChecked())
+        plotWorkspaces << m_outputResolutionName + "_pre_smooth";
     }
+    plotSpectrum(plotWorkspaces);
   }
+}
 
-  bool ISISCalibration::validate()
-  {
-    MantidQt::CustomInterfaces::UserInputValidator uiv;
+bool ISISCalibration::validate() {
+  MantidQt::CustomInterfaces::UserInputValidator uiv;
 
-    uiv.checkMWRunFilesIsValid("Run", m_uiForm.leRunNo);
+  uiv.checkMWRunFilesIsValid("Run", m_uiForm.leRunNo);
 
-    auto peakRange = std::make_pair(m_dblManager->value(m_properties["CalPeakMin"]), m_dblManager->value(m_properties["CalPeakMax"]));
-    auto backRange = std::make_pair(m_dblManager->value(m_properties["CalBackMin"]), m_dblManager->value(m_properties["CalBackMax"]));
+  auto peakRange =
+      std::make_pair(m_dblManager->value(m_properties["CalPeakMin"]),
+                     m_dblManager->value(m_properties["CalPeakMax"]));
+  auto backRange =
+      std::make_pair(m_dblManager->value(m_properties["CalBackMin"]),
+                     m_dblManager->value(m_properties["CalBackMax"]));
 
-    uiv.checkValidRange("Peak Range", peakRange);
-    uiv.checkValidRange("Back Range", backRange);
-    uiv.checkRangesDontOverlap(peakRange, backRange);
+  uiv.checkValidRange("Peak Range", peakRange);
+  uiv.checkValidRange("Back Range", backRange);
+  uiv.checkRangesDontOverlap(peakRange, backRange);
 
-    if ( m_uiForm.ckCreateResolution->isChecked() )
-    {
-      auto backgroundRange = std::make_pair(m_dblManager->value(m_properties["ResStart"]), m_dblManager->value(m_properties["ResEnd"]));
-      uiv.checkValidRange("Background", backgroundRange);
+  if (m_uiForm.ckCreateResolution->isChecked()) {
+    auto backgroundRange =
+        std::make_pair(m_dblManager->value(m_properties["ResStart"]),
+                       m_dblManager->value(m_properties["ResEnd"]));
+    uiv.checkValidRange("Background", backgroundRange);
 
-      double eLow   = m_dblManager->value(m_properties["ResELow"]);
-      double eHigh  = m_dblManager->value(m_properties["ResEHigh"]);
-      double eWidth = m_dblManager->value(m_properties["ResEWidth"]);
+    double eLow = m_dblManager->value(m_properties["ResELow"]);
+    double eHigh = m_dblManager->value(m_properties["ResEHigh"]);
+    double eWidth = m_dblManager->value(m_properties["ResEWidth"]);
 
-      uiv.checkBins(eLow, eWidth, eHigh);
-    }
+    uiv.checkBins(eLow, eWidth, eHigh);
+  }
 
-    QString error = uiv.generateErrorMessage();
+  QString error = uiv.generateErrorMessage();
 
-    if(error != "")
-      g_log.warning(error.toStdString());
+  if (error != "")
+    g_log.warning(error.toStdString());
 
-    return (error == "");
-  }
+  return (error == "");
+}
 
-  /**
-   * Sets default spectra, peak and background ranges.
-   */
-  void ISISCalibration::setDefaultInstDetails()
-  {
-    // Get spectra, peak and background details
-    QMap<QString, QString> instDetails = getInstrumentDetails();
+/**
+ * Sets default spectra, peak and background ranges.
+ */
+void ISISCalibration::setDefaultInstDetails() {
+  // Get spectra, peak and background details
+  QMap<QString, QString> instDetails = getInstrumentDetails();
+
+  // Set the search instrument for runs
+  m_uiForm.leRunNo->setInstrumentOverride(instDetails["instrument"]);
+
+  // Set spectra range
+  m_dblManager->setValue(m_properties["ResSpecMin"],
+                         instDetails["spectra-min"].toDouble());
+  m_dblManager->setValue(m_properties["ResSpecMax"],
+                         instDetails["spectra-max"].toDouble());
+
+  // Set peak and background ranges
+  std::map<std::string, double> ranges = getRangesFromInstrument();
+
+  QPair<double, double> peakRange(ranges["peak-start-tof"],
+                                  ranges["peak-end-tof"]);
+  QPair<double, double> backgroundRange(ranges["back-start-tof"],
+                                        ranges["back-end-tof"]);
+
+  auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->getRangeSelector("CalBackground");
+  setRangeSelector(calPeak, m_properties["CalPeakMin"],
+                   m_properties["CalPeakMax"], peakRange);
+  setRangeSelector(calBackground, m_properties["CalBackMin"],
+                   m_properties["CalBackMax"], backgroundRange);
+}
 
-    // Set the search instrument for runs
-    m_uiForm.leRunNo->setInstrumentOverride(instDetails["instrument"]);
+/**
+ * Replots the raw data mini plot and the energy mini plot
+ */
+void ISISCalibration::calPlotRaw() {
 
-    // Set spectra range
-    m_dblManager->setValue(m_properties["ResSpecMin"], instDetails["spectra-min"].toDouble());
-    m_dblManager->setValue(m_properties["ResSpecMax"], instDetails["spectra-max"].toDouble());
+  QString filename = m_uiForm.leRunNo->getFirstFilename();
 
-    // Set peak and background ranges
-    std::map<std::string, double> ranges = getRangesFromInstrument();
+  // Don't do anything if the file we would plot has not changed
+  if (filename == m_lastCalPlotFilename)
+    return;
 
-    QPair<double, double> peakRange(ranges["peak-start-tof"], ranges["peak-end-tof"]);
-    QPair<double, double> backgroundRange(ranges["back-start-tof"], ranges["back-end-tof"]);
+  m_lastCalPlotFilename = filename;
 
-    auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground");
-    setRangeSelector(calPeak, m_properties["CalPeakMin"], m_properties["CalPeakMax"], peakRange);
-    setRangeSelector(calBackground, m_properties["CalBackMin"], m_properties["CalBackMax"], backgroundRange);
+  if (filename.isEmpty()) {
+    emit showMessageBox("Cannot plot raw data without filename");
+    return;
   }
 
-  /**
-   * Replots the raw data mini plot and the energy mini plot
-   */
-  void ISISCalibration::calPlotRaw()
-  {
+  QFileInfo fi(filename);
+  QString wsname = fi.baseName();
 
-    QString filename = m_uiForm.leRunNo->getFirstFilename();
+  auto instDetails = getInstrumentDetails();
+  int specMin = instDetails["spectra-min"].toInt();
+  int specMax = instDetails["spectra-max"].toInt();
 
-    // Don't do anything if the file we would plot has not changed
-    if(filename == m_lastCalPlotFilename)
-      return;
-
-    m_lastCalPlotFilename = filename;
+  if (!loadFile(filename, wsname, specMin, specMax)) {
+    emit showMessageBox("Unable to load file.\nCheck whether your file exists "
+                        "and matches the selected instrument in the Energy "
+                        "Transfer tab.");
+    return;
+  }
 
-    if ( filename.isEmpty() )
-    {
-      emit showMessageBox("Cannot plot raw data without filename");
-      return;
-    }
+  MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<MatrixWorkspace>(
+      AnalysisDataService::Instance().retrieve(wsname.toStdString()));
 
-    QFileInfo fi(filename);
-    QString wsname = fi.baseName();
+  const Mantid::MantidVec &dataX = input->readX(0);
+  QPair<double, double> range(dataX.front(), dataX.back());
 
-    auto instDetails = getInstrumentDetails();
-    int specMin = instDetails["spectra-min"].toInt();
-    int specMax = instDetails["spectra-max"].toInt();
+  m_uiForm.ppCalibration->clear();
+  m_uiForm.ppCalibration->addSpectrum("Raw", input, 0);
+  m_uiForm.ppCalibration->resizeX();
 
-    if(!loadFile(filename, wsname, specMin, specMax))
-    {
-      emit showMessageBox("Unable to load file.\nCheck whether your file exists and matches the selected instrument in the Energy Transfer tab.");
-      return;
-    }
+  auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->getRangeSelector("CalBackground");
+  setPlotPropertyRange(calPeak, m_properties["CalELow"],
+                       m_properties["CalEHigh"], range);
+  setPlotPropertyRange(calBackground, m_properties["CalStart"],
+                       m_properties["CalEnd"], range);
 
-    MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<MatrixWorkspace>(
-        AnalysisDataService::Instance().retrieve(wsname.toStdString()));
+  setDefaultInstDetails();
 
-    const Mantid::MantidVec & dataX = input->readX(0);
-    QPair<double, double> range(dataX.front(), dataX.back());
+  m_uiForm.ppCalibration->replot();
 
-    m_uiForm.ppCalibration->clear();
-    m_uiForm.ppCalibration->addSpectrum("Raw", input, 0);
-    m_uiForm.ppCalibration->resizeX();
+  // Also replot the energy
+  calPlotEnergy();
+}
 
-    auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground");
-    setPlotPropertyRange(calPeak, m_properties["CalELow"], m_properties["CalEHigh"], range);
-    setPlotPropertyRange(calBackground, m_properties["CalStart"], m_properties["CalEnd"], range);
+/**
+ * Replots the energy mini plot
+ */
+void ISISCalibration::calPlotEnergy() {
+  if (!m_uiForm.leRunNo->isValid()) {
+    emit showMessageBox("Run number not valid.");
+    return;
+  }
 
-    setDefaultInstDetails();
+  QString files = m_uiForm.leRunNo->getFilenames().join(",");
+
+  QFileInfo fi(m_uiForm.leRunNo->getFirstFilename());
+
+  QString detRange =
+      QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + "," +
+      QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
+
+  IAlgorithm_sptr reductionAlg =
+      AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer");
+  reductionAlg->initialize();
+  reductionAlg->setProperty(
+      "Instrument",
+      getInstrumentConfiguration()->getInstrumentName().toStdString());
+  reductionAlg->setProperty(
+      "Analyser",
+      getInstrumentConfiguration()->getAnalyserName().toStdString());
+  reductionAlg->setProperty(
+      "Reflection",
+      getInstrumentConfiguration()->getReflectionName().toStdString());
+  reductionAlg->setProperty("InputFiles", files.toStdString());
+  reductionAlg->setProperty("OutputWorkspace",
+                            "__IndirectCalibration_reduction");
+  reductionAlg->setProperty("SpectraRange", detRange.toStdString());
+  reductionAlg->execute();
+
+  if (!reductionAlg->isExecuted()) {
+    g_log.warning("Could not generate energy preview plot.");
+    return;
+  }
 
-    m_uiForm.ppCalibration->replot();
+  WorkspaceGroup_sptr reductionOutputGroup =
+      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+          "__IndirectCalibration_reduction");
+  if (reductionOutputGroup->size() == 0) {
+    g_log.warning("No result workspaces, cannot plot energy preview.");
+    return;
+  }
 
-    //Also replot the energy
-    calPlotEnergy();
+  MatrixWorkspace_sptr energyWs = boost::dynamic_pointer_cast<MatrixWorkspace>(
+      reductionOutputGroup->getItem(0));
+  if (!energyWs) {
+    g_log.warning("No result workspaces, cannot plot energy preview.");
+    return;
   }
 
-  /**
-   * Replots the energy mini plot
-   */
-  void ISISCalibration::calPlotEnergy()
-  {
-    if ( ! m_uiForm.leRunNo->isValid() )
-    {
-      emit showMessageBox("Run number not valid.");
-      return;
-    }
+  const Mantid::MantidVec &dataX = energyWs->readX(0);
+  QPair<double, double> range(dataX.front(), dataX.back());
 
-    QString files = m_uiForm.leRunNo->getFilenames().join(",");
+  auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
+  setPlotPropertyRange(resBackground, m_properties["ResStart"],
+                       m_properties["ResEnd"], range);
 
-    QFileInfo fi(m_uiForm.leRunNo->getFirstFilename());
+  m_uiForm.ppResolution->clear();
+  m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0);
+  m_uiForm.ppResolution->resizeX();
 
-    QString detRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + ","
-                     + QString::number(m_dblManager->value(m_properties["ResSpecMax"]));
+  calSetDefaultResolution(energyWs);
 
-    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer");
-    reductionAlg->initialize();
-    reductionAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString());
-    reductionAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString());
-    reductionAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString());
-    reductionAlg->setProperty("InputFiles", files.toStdString());
-    reductionAlg->setProperty("OutputWorkspace", "__IndirectCalibration_reduction");
-    reductionAlg->setProperty("SpectraRange", detRange.toStdString());
-    reductionAlg->execute();
+  m_uiForm.ppResolution->replot();
+}
 
-    if(!reductionAlg->isExecuted())
-    {
-      g_log.warning("Could not generate energy preview plot.");
-      return;
-    }
+/**
+ * Set default background and rebinning properties for a given instument
+ * and analyser
+ *
+ * @param ws :: Mantid workspace containing the loaded instument
+ */
+void ISISCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws) {
+  auto inst = ws->getInstrument();
+  auto analyser = inst->getStringParameter("analyser");
 
-    WorkspaceGroup_sptr reductionOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("__IndirectCalibration_reduction");
-    if(reductionOutputGroup->size() == 0)
-    {
-      g_log.warning("No result workspaces, cannot plot energy preview.");
-      return;
-	}
+  if (analyser.size() > 0) {
+    auto comp = inst->getComponentByName(analyser[0]);
 
-    MatrixWorkspace_sptr energyWs = boost::dynamic_pointer_cast<MatrixWorkspace>(reductionOutputGroup->getItem(0));
-    if(!energyWs)
-    {
-      g_log.warning("No result workspaces, cannot plot energy preview.");
+    if (!comp)
       return;
-    }
-
-    const Mantid::MantidVec & dataX = energyWs->readX(0);
-    QPair<double, double> range(dataX.front(), dataX.back());
-
-    auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
-    setPlotPropertyRange(resBackground, m_properties["ResStart"], m_properties["ResEnd"], range);
 
-    m_uiForm.ppResolution->clear();
-    m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0);
-    m_uiForm.ppResolution->resizeX();
-
-    calSetDefaultResolution(energyWs);
-
-    m_uiForm.ppResolution->replot();
-  }
-
-  /**
-   * Set default background and rebinning properties for a given instument
-   * and analyser
-   *
-   * @param ws :: Mantid workspace containing the loaded instument
-   */
-  void ISISCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws)
-  {
-    auto inst = ws->getInstrument();
-    auto analyser = inst->getStringParameter("analyser");
-
-    if(analyser.size() > 0)
-    {
-      auto comp = inst->getComponentByName(analyser[0]);
-
-      if(!comp)
-        return;
-
-      auto params = comp->getNumberParameter("resolution", true);
-
-      //Set the default instrument resolution
-      if(params.size() > 0)
-      {
-        double res = params[0];
-
-        // Set default rebinning bounds
-        QPair<double, double> peakRange(-res * 10, res * 10);
-        auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
-        setPlotPropertyRange(resPeak, m_properties["ResELow"],
-                             m_properties["ResEHigh"], peakRange);
-        setRangeSelector(resPeak, m_properties["ResELow"],
-                         m_properties["ResEHigh"], peakRange);
-
-        // Set default background bounds
-        QPair<double, double> backgroundRange(-res * 9, -res * 8);
-        auto resBackground =
-            m_uiForm.ppResolution->getRangeSelector("ResBackground");
-        setRangeSelector(resBackground, m_properties["ResStart"],
-                         m_properties["ResEnd"], backgroundRange);
-      }
-    }
-  }
-
-  /**
-   * Handles a range selector having it's minumum value changed.
-   * Updates property in property map.
-   *
-   * @param val :: New minumum value
-   */
-  void ISISCalibration::calMinChanged(double val)
-  {
-    auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground");
-    auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
-    auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
-
-    MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-
-    if(from == calPeak)
-    {
-      m_dblManager->setValue(m_properties["CalPeakMin"], val);
-    }
-    else if(from == calBackground)
-    {
-      m_dblManager->setValue(m_properties["CalBackMin"], val);
-    }
-    else if(from == resPeak)
-    {
-      m_dblManager->setValue(m_properties["ResELow"], val);
-    }
-    else if(from == resBackground)
-    {
-      m_dblManager->setValue(m_properties["ResStart"], val);
+    auto params = comp->getNumberParameter("resolution", true);
+
+    // Set the default instrument resolution
+    if (params.size() > 0) {
+      double res = params[0];
+
+      // Set default rebinning bounds
+      QPair<double, double> peakRange(-res * 10, res * 10);
+      auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
+      setPlotPropertyRange(resPeak, m_properties["ResELow"],
+                           m_properties["ResEHigh"], peakRange);
+      setRangeSelector(resPeak, m_properties["ResELow"],
+                       m_properties["ResEHigh"], peakRange);
+
+      // Set default background bounds
+      QPair<double, double> backgroundRange(-res * 9, -res * 8);
+      auto resBackground =
+          m_uiForm.ppResolution->getRangeSelector("ResBackground");
+      setRangeSelector(resBackground, m_properties["ResStart"],
+                       m_properties["ResEnd"], backgroundRange);
     }
   }
+}
 
-  /**
-   * Handles a range selector having it's maxumum value changed.
-   * Updates property in property map.
-   *
-   * @param val :: New maxumum value
-   */
-  void ISISCalibration::calMaxChanged(double val)
-  {
-    auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground");
-    auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
-    auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
-
-    MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-
-    if(from == calPeak)
-    {
-      m_dblManager->setValue(m_properties["CalPeakMax"], val);
-    }
-    else if(from == calBackground)
-    {
-      m_dblManager->setValue(m_properties["CalBackMax"], val);
-    }
-    else if(from == resPeak)
-    {
-      m_dblManager->setValue(m_properties["ResEHigh"], val);
-    }
-    else if(from == resBackground)
-    {
-      m_dblManager->setValue(m_properties["ResEnd"], val);
-    }
+/**
+ * Handles a range selector having it's minumum value changed.
+ * Updates property in property map.
+ *
+ * @param val :: New minumum value
+ */
+void ISISCalibration::calMinChanged(double val) {
+  auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->getRangeSelector("CalBackground");
+  auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
+  auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
+
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
+
+  if (from == calPeak) {
+    m_dblManager->setValue(m_properties["CalPeakMin"], val);
+  } else if (from == calBackground) {
+    m_dblManager->setValue(m_properties["CalBackMin"], val);
+  } else if (from == resPeak) {
+    m_dblManager->setValue(m_properties["ResELow"], val);
+  } else if (from == resBackground) {
+    m_dblManager->setValue(m_properties["ResStart"], val);
   }
+}
 
-  /**
-   * Update a range selector given a QtProperty and new value
-   *
-   * @param prop :: The property to update
-   * @param val :: New value for property
-   */
-  void ISISCalibration::calUpdateRS(QtProperty* prop, double val)
-  {
-    auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
-    auto calBackground = m_uiForm.ppCalibration->getRangeSelector("CalBackground");
-    auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
-    auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
-
-    if ( prop == m_properties["CalPeakMin"] )       calPeak->setMinimum(val);
-    else if ( prop == m_properties["CalPeakMax"] )  calPeak->setMaximum(val);
-    else if ( prop == m_properties["CalBackMin"] )  calBackground->setMinimum(val);
-    else if ( prop == m_properties["CalBackMax"] )  calBackground->setMaximum(val);
-    else if ( prop == m_properties["ResStart"] )    resBackground->setMinimum(val);
-    else if ( prop == m_properties["ResEnd"] )      resBackground->setMaximum(val);
-    else if ( prop == m_properties["ResELow"] )     resPeak->setMinimum(val);
-    else if ( prop == m_properties["ResEHigh"] )    resPeak->setMaximum(val);
+/**
+ * Handles a range selector having it's maxumum value changed.
+ * Updates property in property map.
+ *
+ * @param val :: New maxumum value
+ */
+void ISISCalibration::calMaxChanged(double val) {
+  auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->getRangeSelector("CalBackground");
+  auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
+  auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
+
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
+
+  if (from == calPeak) {
+    m_dblManager->setValue(m_properties["CalPeakMax"], val);
+  } else if (from == calBackground) {
+    m_dblManager->setValue(m_properties["CalBackMax"], val);
+  } else if (from == resPeak) {
+    m_dblManager->setValue(m_properties["ResEHigh"], val);
+  } else if (from == resBackground) {
+    m_dblManager->setValue(m_properties["ResEnd"], val);
   }
+}
 
-  /**
-  * This function enables/disables the display of the options involved in creating the RES file.
-  *
-  * @param state :: whether checkbox is checked or unchecked
-  */
-  void ISISCalibration::resCheck(bool state)
-  {
-    m_uiForm.ppResolution->getRangeSelector("ResPeak")->setVisible(state);
-    m_uiForm.ppResolution->getRangeSelector("ResBackground")->setVisible(state);
-
-    // Toggle scale and smooth options
-    m_uiForm.ckResolutionScale->setEnabled(state);
-    m_uiForm.ckSmoothResolution->setEnabled(state);
-  }
+/**
+ * Update a range selector given a QtProperty and new value
+ *
+ * @param prop :: The property to update
+ * @param val :: New value for property
+ */
+void ISISCalibration::calUpdateRS(QtProperty *prop, double val) {
+  auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak");
+  auto calBackground =
+      m_uiForm.ppCalibration->getRangeSelector("CalBackground");
+  auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak");
+  auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
+
+  if (prop == m_properties["CalPeakMin"])
+    calPeak->setMinimum(val);
+  else if (prop == m_properties["CalPeakMax"])
+    calPeak->setMaximum(val);
+  else if (prop == m_properties["CalBackMin"])
+    calBackground->setMinimum(val);
+  else if (prop == m_properties["CalBackMax"])
+    calBackground->setMaximum(val);
+  else if (prop == m_properties["ResStart"])
+    resBackground->setMinimum(val);
+  else if (prop == m_properties["ResEnd"])
+    resBackground->setMaximum(val);
+  else if (prop == m_properties["ResELow"])
+    resPeak->setMinimum(val);
+  else if (prop == m_properties["ResEHigh"])
+    resPeak->setMaximum(val);
+}
 
-  /**
-   * Called when a user starts to type / edit the runs to load.
-   */
-  void ISISCalibration::pbRunEditing()
-  {
-    emit updateRunButton(false, "Editing...", "Run numbers are curently being edited.");
-  }
+/**
+* This function enables/disables the display of the options involved in creating
+*the RES file.
+*
+* @param state :: whether checkbox is checked or unchecked
+*/
+void ISISCalibration::resCheck(bool state) {
+  m_uiForm.ppResolution->getRangeSelector("ResPeak")->setVisible(state);
+  m_uiForm.ppResolution->getRangeSelector("ResBackground")->setVisible(state);
+
+  // Toggle scale and smooth options
+  m_uiForm.ckResolutionScale->setEnabled(state);
+  m_uiForm.ckSmoothResolution->setEnabled(state);
+}
 
-  /**
-   * Called when the FileFinder starts finding the files.
-   */
-  void ISISCalibration::pbRunFinding()
-  {
-    emit updateRunButton(false, "Finding files...", "Searchig for data files for the run numbers entered...");
-    m_uiForm.leRunNo->setEnabled(false);
-  }
+/**
+ * Called when a user starts to type / edit the runs to load.
+ */
+void ISISCalibration::pbRunEditing() {
+  emit updateRunButton(false, "Editing...",
+                       "Run numbers are curently being edited.");
+}
 
-  /**
-   * Called when the FileFinder has finished finding the files.
-   */
-  void ISISCalibration::pbRunFinished()
-  {
-    if(!m_uiForm.leRunNo->isValid())
-    {
-      emit updateRunButton(false, "Invalid Run(s)", "Cannot find data files for some of the run numbers enetered.");
-    }
-    else
-    {
-      emit updateRunButton();
-    }
+/**
+ * Called when the FileFinder starts finding the files.
+ */
+void ISISCalibration::pbRunFinding() {
+  emit updateRunButton(
+      false, "Finding files...",
+      "Searchig for data files for the run numbers entered...");
+  m_uiForm.leRunNo->setEnabled(false);
+}
 
-    m_uiForm.leRunNo->setEnabled(true);
+/**
+ * Called when the FileFinder has finished finding the files.
+ */
+void ISISCalibration::pbRunFinished() {
+  if (!m_uiForm.leRunNo->isValid()) {
+    emit updateRunButton(
+        false, "Invalid Run(s)",
+        "Cannot find data files for some of the run numbers enetered.");
+  } else {
+    emit updateRunButton();
   }
 
+  m_uiForm.leRunNo->setEnabled(true);
+}
+
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/ISISDiagnostics.cpp b/MantidQt/CustomInterfaces/src/Indirect/ISISDiagnostics.cpp
index fbbcad36334b02f898ec373df452f8b09f47dcd2..9100a5b0e3d4d583263a3fdc7aafaa0f1c599477 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/ISISDiagnostics.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/ISISDiagnostics.cpp
@@ -390,7 +390,6 @@ void ISISDiagnostics::doublePropertyChanged(QtProperty *prop, double val) {
   }
 }
 
-
 /**
  * Updates the preview plot when the algorithm is complete.
  *
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp
index c3e169fbbdd19f6d491fc828064ceb411188eb64..1794dc83c3f4e9e776ee160f8c6f3e69e6fb25cf 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp
@@ -35,6 +35,5 @@ IndirectBayesTab::~IndirectBayesTab() {}
 void IndirectBayesTab::runPythonScript(const QString &pyInput) {
   emit runAsPythonScript(pyInput, true);
 }
-
 }
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysisTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysisTab.cpp
index aa5f7a069f69ec64eebd32fbc1385697cce6e721..b32e154bdf21567e10199e84b0e2c6fc8cf303b8 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysisTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysisTab.cpp
@@ -10,49 +10,38 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  /**
-   * Constructor.
-   *
-   * @param parent :: the parent widget (an IndirectDataAnalysis object).
-   */
-  IndirectDataAnalysisTab::IndirectDataAnalysisTab(QWidget * parent) : IndirectTab(parent),
-    m_dblEdFac(NULL), m_blnEdFac(NULL),
-    m_parent(NULL)
-  {
-    m_parent = dynamic_cast<IndirectDataAnalysis*>(parent);
-
-    // Create Editor Factories
-    m_dblEdFac = new DoubleEditorFactory(this);
-    m_blnEdFac = new QtCheckBoxFactory(this);
-  }
-
-
-  /**
-   * Loads the tab's settings.
-   *
-   * Calls overridden version of loadSettings() in child class.
-   *
-   * @param settings :: the QSettings object from which to load
-   */
-  void IndirectDataAnalysisTab::loadTabSettings(const QSettings & settings)
-  {
-    loadSettings(settings);
-  }
-
-
-  /**
-   * Slot that can be called when a user edits an input.
-   */
-  void IndirectDataAnalysisTab::inputChanged()
-  {
-    validate();
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+/**
+ * Constructor.
+ *
+ * @param parent :: the parent widget (an IndirectDataAnalysis object).
+ */
+IndirectDataAnalysisTab::IndirectDataAnalysisTab(QWidget *parent)
+    : IndirectTab(parent), m_dblEdFac(NULL), m_blnEdFac(NULL), m_parent(NULL) {
+  m_parent = dynamic_cast<IndirectDataAnalysis *>(parent);
+
+  // Create Editor Factories
+  m_dblEdFac = new DoubleEditorFactory(this);
+  m_blnEdFac = new QtCheckBoxFactory(this);
+}
+
+/**
+ * Loads the tab's settings.
+ *
+ * Calls overridden version of loadSettings() in child class.
+ *
+ * @param settings :: the QSettings object from which to load
+ */
+void IndirectDataAnalysisTab::loadTabSettings(const QSettings &settings) {
+  loadSettings(settings);
+}
+
+/**
+ * Slot that can be called when a user edits an input.
+ */
+void IndirectDataAnalysisTab::inputChanged() { validate(); }
 
 } // namespace IDA
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
index b0e819fc0320a0cee569323f7ebfa7465de6ec66..336dd4e15238be805163690f925bf466f64d7726 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp
@@ -26,52 +26,43 @@
 #include <QMessageBox>
 #include <QUrl>
 
-
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    DECLARE_SUBWINDOW(IndirectDataReduction)
-  }
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(IndirectDataReduction)
 }
-
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("IndirectDataReduction");
 }
 
+namespace {
+Mantid::Kernel::Logger g_log("IndirectDataReduction");
+}
 
 using namespace Mantid::API;
 using namespace Mantid::Geometry;
 using namespace MantidQt::CustomInterfaces;
 using namespace MantidQt;
 
-
 /**
  * Default constructor for class. Initialises interface pointers to NULL values.
- * @param parent :: This is a pointer to the "parent" object in Qt, most likely the main MantidPlot window.
+ * @param parent :: This is a pointer to the "parent" object in Qt, most likely
+ * the main MantidPlot window.
  */
-IndirectDataReduction::IndirectDataReduction(QWidget *parent) :
-  UserSubWindow(parent),
-  m_instrument(""),
-  m_settingsGroup("CustomInterfaces/IndirectDataReduction"),
-  m_algRunner(new MantidQt::API::AlgorithmRunner(this)),
-  m_changeObserver(*this, &IndirectDataReduction::handleConfigChange)
-{
+IndirectDataReduction::IndirectDataReduction(QWidget *parent)
+    : UserSubWindow(parent), m_instrument(""),
+      m_settingsGroup("CustomInterfaces/IndirectDataReduction"),
+      m_algRunner(new MantidQt::API::AlgorithmRunner(this)),
+      m_changeObserver(*this, &IndirectDataReduction::handleConfigChange) {
   // Signals to report load instrument algo result
-  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(instrumentLoadingDone(bool)));
+  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this,
+          SLOT(instrumentLoadingDone(bool)));
 
   Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
 }
 
-
 /**
  * Destructor
  */
-IndirectDataReduction::~IndirectDataReduction()
-{
+IndirectDataReduction::~IndirectDataReduction() {
   Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
 
   // Make sure no algos are running after the window has been closed
@@ -80,47 +71,45 @@ IndirectDataReduction::~IndirectDataReduction()
   saveSettings();
 }
 
-
 /**
- * On user clicking the "help" button on the interface, directs their request to the relevant
+ * On user clicking the "help" button on the interface, directs their request to
+ * the relevant
  * interface's helpClicked() function.
  */
-void IndirectDataReduction::helpClicked()
-{
-  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Indirect_DataReduction"));
+void IndirectDataReduction::helpClicked() {
+  MantidQt::API::HelpWindow::showCustomInterface(
+      NULL, QString("Indirect_DataReduction"));
 }
 
-
 /**
  * Called when the user clicks the Python export button.
  */
-void IndirectDataReduction::exportTabPython()
-{
-  QString tabName = m_uiForm.twIDRTabs->tabText(m_uiForm.twIDRTabs->currentIndex());
+void IndirectDataReduction::exportTabPython() {
+  QString tabName =
+      m_uiForm.twIDRTabs->tabText(m_uiForm.twIDRTabs->currentIndex());
   m_tabs[tabName].second->exportPythonScript();
 }
 
-
 /**
- * This is the function called when the "Run" button is clicked. It will call the relevent function
+ * This is the function called when the "Run" button is clicked. It will call
+ * the relevent function
  * in the subclass.
  */
-void IndirectDataReduction::runClicked()
-{
-  QString tabName = m_uiForm.twIDRTabs->tabText(m_uiForm.twIDRTabs->currentIndex());
+void IndirectDataReduction::runClicked() {
+  QString tabName =
+      m_uiForm.twIDRTabs->tabText(m_uiForm.twIDRTabs->currentIndex());
   m_tabs[tabName].second->runTab();
 }
 
-
 /**
  * Sets up Qt UI file and connects signals, slots.
  */
-void IndirectDataReduction::initLayout()
-{
+void IndirectDataReduction::initLayout() {
   m_uiForm.setupUi(this);
 
   // Do not allow running until setup  and instrument laoding are done
-  updateRunButton(false, "Loading UI", "Initialising user interface components...");
+  updateRunButton(false, "Loading UI",
+                  "Initialising user interface components...");
 
   // Create the tabs
   addTab<ISISEnergyTransfer>("ISIS Energy Transfer");
@@ -136,64 +125,73 @@ void IndirectDataReduction::initLayout()
   // Connect "?" (Help) Button
   connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
   // Connect the Python export buton
-  connect(m_uiForm.pbPythonExport, SIGNAL(clicked()), this, SLOT(exportTabPython()));
+  connect(m_uiForm.pbPythonExport, SIGNAL(clicked()), this,
+          SLOT(exportTabPython()));
   // Connect the "Run" button
   connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked()));
   // Connect the "Manage User Directories" Button
-  connect(m_uiForm.pbManageDirectories, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
+  connect(m_uiForm.pbManageDirectories, SIGNAL(clicked()), this,
+          SLOT(openDirectoryDialog()));
 
   // Reset the Run button state when the tab is changed
-  connect(m_uiForm.twIDRTabs, SIGNAL(currentChanged(int)), this, SLOT(updateRunButton()));
+  connect(m_uiForm.twIDRTabs, SIGNAL(currentChanged(int)), this,
+          SLOT(updateRunButton()));
 
   // Handle instrument configuration changes
-  connect(m_uiForm.iicInstrumentConfiguration, SIGNAL(instrumentConfigurationUpdated(const QString &, const QString &, const QString &)),
-          this, SLOT(instrumentSetupChanged(const QString &, const QString &, const QString &)));
+  connect(m_uiForm.iicInstrumentConfiguration,
+          SIGNAL(instrumentConfigurationUpdated(
+              const QString &, const QString &, const QString &)),
+          this, SLOT(instrumentSetupChanged(const QString &, const QString &,
+                                            const QString &)));
 
   // Update the instrument configuration across the UI
   m_uiForm.iicInstrumentConfiguration->newInstrumentConfiguration();
 
-  std::string facility = Mantid::Kernel::ConfigService::Instance().getString("default.facility");
+  std::string facility =
+      Mantid::Kernel::ConfigService::Instance().getString("default.facility");
   filterUiForFacility(QString::fromStdString(facility));
   emit newInstrumentConfiguration();
 }
 
-
 /**
- * This function is ran after initLayout(), and runPythonCode is unavailable before this function
- * has run (because of the setup of the base class). For this reason, "setup" functions that require
+ * This function is ran after initLayout(), and runPythonCode is unavailable
+ * before this function
+ * has run (because of the setup of the base class). For this reason, "setup"
+ * functions that require
  * Python scripts are located here.
  */
-void IndirectDataReduction::initLocalPython()
-{
+void IndirectDataReduction::initLocalPython() {
   // select starting instrument
   readSettings();
 }
 
-
 /**
  * Called when any of the instrument configuration options are changed.
  *
- * Used to notify tabs that rely on the instrument config when the config changes.
+ * Used to notify tabs that rely on the instrument config when the config
+ *changes.
  *
  * @param instrumentName Name of selected instrument
  * @param analyser Name of selected analyser bank
  * @param reflection Name of selected reflection mode
  */
-void IndirectDataReduction::instrumentSetupChanged(const QString & instrumentName, const QString & analyser,
-                                                   const QString & reflection)
-{
-  m_instWorkspace = loadInstrumentIfNotExist(instrumentName.toStdString(), analyser.toStdString(), reflection.toStdString());
+void IndirectDataReduction::instrumentSetupChanged(
+    const QString &instrumentName, const QString &analyser,
+    const QString &reflection) {
+  m_instWorkspace = loadInstrumentIfNotExist(instrumentName.toStdString(),
+                                             analyser.toStdString(),
+                                             reflection.toStdString());
   instrumentLoadingDone(m_instWorkspace == NULL);
 
-  if(m_instWorkspace != NULL)
+  if (m_instWorkspace != NULL)
     emit newInstrumentConfiguration();
 }
 
-
 /**
  * Loads an empty instrument into a workspace and returns a pointer to it.
  *
- * If an analyser and reflection are supplied then the corresponding IPF is also loaded.
+ * If an analyser and reflection are supplied then the corresponding IPF is also
+ *loaded.
  * The workspace is not stored in ADS.
  *
  * @param instrumentName Name of the instrument to load
@@ -201,28 +199,34 @@ void IndirectDataReduction::instrumentSetupChanged(const QString & instrumentNam
  * @param reflection Relection being used (optional)
  * @returns Pointer to instrument workspace
  */
-Mantid::API::MatrixWorkspace_sptr IndirectDataReduction::loadInstrumentIfNotExist(std::string instrumentName,
-    std::string analyser, std::string reflection)
-{
-  std::string idfDirectory = Mantid::Kernel::ConfigService::Instance().getString("instrumentDefinition.directory");
-
-  try
-  {
-    std::string parameterFilename = idfDirectory + instrumentName + "_Definition.xml";
-    IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument");
+Mantid::API::MatrixWorkspace_sptr
+IndirectDataReduction::loadInstrumentIfNotExist(std::string instrumentName,
+                                                std::string analyser,
+                                                std::string reflection) {
+  std::string idfDirectory =
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "instrumentDefinition.directory");
+
+  try {
+    std::string parameterFilename =
+        idfDirectory + instrumentName + "_Definition.xml";
+    IAlgorithm_sptr loadAlg =
+        AlgorithmManager::Instance().create("LoadEmptyInstrument");
     loadAlg->setChild(true);
     loadAlg->setLogging(false);
     loadAlg->initialize();
     loadAlg->setProperty("Filename", parameterFilename);
     loadAlg->setProperty("OutputWorkspace", "__IDR_Inst");
     loadAlg->execute();
-    MatrixWorkspace_sptr instWorkspace = loadAlg->getProperty("OutputWorkspace");
+    MatrixWorkspace_sptr instWorkspace =
+        loadAlg->getProperty("OutputWorkspace");
 
     // Load the IPF if given an analyser and reflection
-    if(!analyser.empty() && !reflection.empty())
-    {
-      std::string ipfFilename = idfDirectory + instrumentName + "_" + analyser + "_" + reflection + "_Parameters.xml";
-      IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile");
+    if (!analyser.empty() && !reflection.empty()) {
+      std::string ipfFilename = idfDirectory + instrumentName + "_" + analyser +
+                                "_" + reflection + "_Parameters.xml";
+      IAlgorithm_sptr loadParamAlg =
+          AlgorithmManager::Instance().create("LoadParameterFile");
       loadParamAlg->setChild(true);
       loadParamAlg->setLogging(false);
       loadParamAlg->initialize();
@@ -232,30 +236,28 @@ Mantid::API::MatrixWorkspace_sptr IndirectDataReduction::loadInstrumentIfNotExis
     }
 
     return instWorkspace;
-  }
-  catch(std::exception &ex)
-  {
-    g_log.warning() << "Failed to load instrument with error: "
-                    << ex.what()
+  } catch (std::exception &ex) {
+    g_log.warning() << "Failed to load instrument with error: " << ex.what()
                     << ". The current facility may not be fully supported."
                     << std::endl;
     return MatrixWorkspace_sptr();
   }
 }
 
-
 /**
  * Gets details for the current instrument configuration.
  *
  * @return Map of information ID to value
  */
-QMap<QString, QString> IndirectDataReduction::getInstrumentDetails()
-{
+QMap<QString, QString> IndirectDataReduction::getInstrumentDetails() {
   QMap<QString, QString> instDetails;
 
-  std::string instrumentName = m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
-  std::string analyser = m_uiForm.iicInstrumentConfiguration->getAnalyserName().toStdString();
-  std::string reflection = m_uiForm.iicInstrumentConfiguration->getReflectionName().toStdString();
+  std::string instrumentName =
+      m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
+  std::string analyser =
+      m_uiForm.iicInstrumentConfiguration->getAnalyserName().toStdString();
+  std::string reflection =
+      m_uiForm.iicInstrumentConfiguration->getReflectionName().toStdString();
 
   instDetails["instrument"] = QString::fromStdString(instrumentName);
   instDetails["analyser"] = QString::fromStdString(analyser);
@@ -263,28 +265,23 @@ QMap<QString, QString> IndirectDataReduction::getInstrumentDetails()
 
   // List of values to get from IPF
   std::vector<std::string> ipfElements{
-      "analysis-type",      "spectra-min",
-      "spectra-max",        "Efixed",
-      "peak-start",         "peak-end",
-      "back-start",         "back-end",
-      "rebin-default",      "cm-1-convert-choice",
-      "save-nexus-choice",  "save-ascii-choice",
+      "analysis-type", "spectra-min", "spectra-max", "Efixed", "peak-start",
+      "peak-end", "back-start", "back-end", "rebin-default",
+      "cm-1-convert-choice", "save-nexus-choice", "save-ascii-choice",
       "fold-frames-choice", "resolution"};
 
   // In the IRIS IPF there is no fmica component
-  if(instrumentName == "IRIS" && analyser == "fmica")
+  if (instrumentName == "IRIS" && analyser == "fmica")
     analyser = "mica";
 
-  if(m_instWorkspace == NULL)
-  {
+  if (m_instWorkspace == NULL) {
     g_log.warning("Instrument workspace not loaded");
     return instDetails;
   }
 
   // Get the instrument
   auto instrument = m_instWorkspace->getInstrument();
-  if(instrument == NULL)
-  {
+  if (instrument == NULL) {
     g_log.warning("Instrument workspace has no instrument");
     return instDetails;
   }
@@ -293,33 +290,28 @@ QMap<QString, QString> IndirectDataReduction::getInstrumentDetails()
   auto component = instrument->getComponentByName(analyser);
 
   // For each parameter we want to get
-  for(auto it = ipfElements.begin(); it != ipfElements.end(); ++it)
-  {
-    try
-    {
+  for (auto it = ipfElements.begin(); it != ipfElements.end(); ++it) {
+    try {
       std::string key = *it;
 
       QString value = getInstrumentParameterFrom(instrument, key);
 
-      if(value.isEmpty() && component != NULL)
+      if (value.isEmpty() && component != NULL)
         value = getInstrumentParameterFrom(component, key);
 
       instDetails[QString::fromStdString(key)] = value;
     }
     // In the case that the parameter does not exist
-    catch(Mantid::Kernel::Exception::NotFoundError &nfe)
-    {
+    catch (Mantid::Kernel::Exception::NotFoundError &nfe) {
       UNUSED_ARG(nfe);
-      g_log.warning() << "Could not find parameter " << *it
-                      << " in instrument " << instrumentName
-                      << std::endl;
+      g_log.warning() << "Could not find parameter " << *it << " in instrument "
+                      << instrumentName << std::endl;
     }
   }
 
   return instDetails;
 }
 
-
 /**
  * Gets a parameter from an instrument component as a string.
  *
@@ -327,56 +319,50 @@ QMap<QString, QString> IndirectDataReduction::getInstrumentDetails()
  * @param param Parameter name
  * @return Value as QString
  */
-QString IndirectDataReduction::getInstrumentParameterFrom(Mantid::Geometry::IComponent_const_sptr comp, std::string param)
-{
+QString IndirectDataReduction::getInstrumentParameterFrom(
+    Mantid::Geometry::IComponent_const_sptr comp, std::string param) {
   QString value;
 
-  if(!comp->hasParameter(param))
-  {
-    g_log.debug() << "Component " << comp->getName()
-                  << " has no parameter " << param
-                  << std::endl;
+  if (!comp->hasParameter(param)) {
+    g_log.debug() << "Component " << comp->getName() << " has no parameter "
+                  << param << std::endl;
     return "";
   }
 
   // Determine it's type and call the corresponding get function
   std::string paramType = comp->getParameterType(param);
 
-  if(paramType == "string")
+  if (paramType == "string")
     value = QString::fromStdString(comp->getStringParameter(param)[0]);
 
-  if(paramType == "double")
+  if (paramType == "double")
     value = QString::number(comp->getNumberParameter(param)[0]);
 
   return value;
 }
 
-
 /**
  * Tasks to be carried out after an empty instument has finished loading
  */
-void IndirectDataReduction::instrumentLoadingDone(bool error)
-{
-  if(error)
-  {
-    g_log.warning("Instument loading failed! This instrument (or analyser/reflection configuration) may not be supported by the interface.");
+void IndirectDataReduction::instrumentLoadingDone(bool error) {
+  if (error) {
+    g_log.warning("Instument loading failed! This instrument (or "
+                  "analyser/reflection configuration) may not be supported by "
+                  "the interface.");
     return;
   }
 }
 
-
 /**
  * Remove the Poco observer on the config service when the interfaces is closed.
  *
  * @param close Close event (unused)
  */
-void IndirectDataReduction::closeEvent(QCloseEvent* close)
-{
+void IndirectDataReduction::closeEvent(QCloseEvent *close) {
   UNUSED_ARG(close);
   Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
 }
 
-
 /**
  * Handles configuration values being changed.
  *
@@ -384,17 +370,14 @@ void IndirectDataReduction::closeEvent(QCloseEvent* close)
  *
  * @param pNf Poco notification
  */
-void IndirectDataReduction::handleConfigChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
-{
+void IndirectDataReduction::handleConfigChange(
+    Mantid::Kernel::ConfigValChangeNotification_ptr pNf) {
   std::string key = pNf->key();
   std::string value = pNf->curValue();
 
-  if(key == "datasearch.directories" || key == "defaultsave.directory")
-  {
+  if (key == "datasearch.directories" || key == "defaultsave.directory") {
     readSettings();
-  }
-  else if(key == "default.facility")
-  {
+  } else if (key == "default.facility") {
     QString facility = QString::fromStdString(value);
 
     filterUiForFacility(facility);
@@ -402,23 +385,25 @@ void IndirectDataReduction::handleConfigChange(Mantid::Kernel::ConfigValChangeNo
   }
 }
 
-
 /**
  * Read Qt settings for the interface.
  */
-void IndirectDataReduction::readSettings()
-{
+void IndirectDataReduction::readSettings() {
   // Set values of m_dataDir and m_saveDir
-  m_dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories"));
+  m_dataDir = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "datasearch.directories"));
   m_dataDir.replace(" ", "");
-  if(m_dataDir.length() > 0)
+  if (m_dataDir.length() > 0)
     m_dataDir = m_dataDir.split(";", QString::SkipEmptyParts)[0];
-  m_saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+  m_saveDir = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "defaultsave.directory"));
 
   QSettings settings;
 
   // Load settings for MWRunFile widgets
-  //TODO
+  // TODO
   /* settings.beginGroup(m_settingsGroup + "DataFiles"); */
   /* settings.setValue("last_directory", m_dataDir); */
   /* m_uiForm.ind_runFiles->readSettings(settings.group()); */
@@ -439,76 +424,74 @@ void IndirectDataReduction::readSettings()
   settings.beginGroup(m_settingsGroup);
 
   QString instrumentName = settings.value("instrument-name", "").toString();
-  if(!instrumentName.isEmpty())
+  if (!instrumentName.isEmpty())
     m_uiForm.iicInstrumentConfiguration->setInstrument(instrumentName);
 
   QString analyserName = settings.value("analyser-name", "").toString();
-  if(!analyserName.isEmpty())
+  if (!analyserName.isEmpty())
     m_uiForm.iicInstrumentConfiguration->setAnalyser(analyserName);
 
   QString reflectionName = settings.value("reflection-name", "").toString();
-  if(!reflectionName.isEmpty())
+  if (!reflectionName.isEmpty())
     m_uiForm.iicInstrumentConfiguration->setReflection(reflectionName);
 
   settings.endGroup();
 }
 
-
 /**
  * Save settings to a persistent storage.
  */
-void IndirectDataReduction::saveSettings()
-{
+void IndirectDataReduction::saveSettings() {
   QSettings settings;
   settings.beginGroup(m_settingsGroup);
 
-  QString instrumentName = m_uiForm.iicInstrumentConfiguration->getInstrumentName();
+  QString instrumentName =
+      m_uiForm.iicInstrumentConfiguration->getInstrumentName();
   settings.setValue("instrument-name", instrumentName);
 
   QString analyserName = m_uiForm.iicInstrumentConfiguration->getAnalyserName();
   settings.setValue("analyser-name", analyserName);
 
-  QString reflectionName = m_uiForm.iicInstrumentConfiguration->getReflectionName();
+  QString reflectionName =
+      m_uiForm.iicInstrumentConfiguration->getReflectionName();
   settings.setValue("reflection-name", reflectionName);
 
   settings.endGroup();
 }
 
-
 /**
  * Filters the displayed tabs based on the current facility.
  *
  * @param facility Name of facility
  */
-void IndirectDataReduction::filterUiForFacility(QString facility)
-{
-  g_log.information() << "Facility selected: "
-                      << facility.toStdString()
+void IndirectDataReduction::filterUiForFacility(QString facility) {
+  g_log.information() << "Facility selected: " << facility.toStdString()
                       << std::endl;
 
   QStringList enabledTabs;
   QStringList disabledInstruments;
 
   // Add facility specific tabs and disable instruments
-  if(facility == "ISIS")
-  {
+  if (facility == "ISIS") {
     enabledTabs << "ISIS Energy Transfer"
                 << "ISIS Calibration"
                 << "ISIS Diagnostics";
-  }
-  else if(facility == "ILL")
-  {
+  } else if (facility == "ILL") {
     enabledTabs << "ILL Energy Transfer"
                 << "ILL Calibration";
-    disabledInstruments << "IN10" << "IN13" << "IN16";
+    disabledInstruments << "IN10"
+                        << "IN13"
+                        << "IN16";
   }
 
   // These tabs work at any facility (always at end of tabs)
-  enabledTabs << "Transmission" << "Symmetrise" << "S(Q, w)" << "Moments";
+  enabledTabs << "Transmission"
+              << "Symmetrise"
+              << "S(Q, w)"
+              << "Moments";
 
   // First remove all tabs
-  while(m_uiForm.twIDRTabs->count() > 0)
-  {
+  while (m_uiForm.twIDRTabs->count() > 0) {
     // Disconnect the instrument changed signal
     QString tabName = m_uiForm.twIDRTabs->tabText(0);
     disconnect(this, SIGNAL(newInstrumentConfiguration()),
@@ -517,52 +500,46 @@ void IndirectDataReduction::filterUiForFacility(QString facility)
     // Remove the tab
     m_uiForm.twIDRTabs->removeTab(0);
 
-    g_log.debug() << "Removing tab " << tabName.toStdString()
-                  << std::endl;
+    g_log.debug() << "Removing tab " << tabName.toStdString() << std::endl;
   }
 
   // Add the required tabs
-  for(auto it = enabledTabs.begin(); it != enabledTabs.end(); ++it)
-  {
+  for (auto it = enabledTabs.begin(); it != enabledTabs.end(); ++it) {
     // Connect the insturment changed signal
-    connect(this, SIGNAL(newInstrumentConfiguration()),
-            m_tabs[*it].second, SIGNAL(newInstrumentConfiguration()));
+    connect(this, SIGNAL(newInstrumentConfiguration()), m_tabs[*it].second,
+            SIGNAL(newInstrumentConfiguration()));
 
     // Add the tab
     m_uiForm.twIDRTabs->addTab(m_tabs[*it].first, *it);
 
-    g_log.debug() << "Adding tab " << (*it).toStdString()
-                  << std::endl;
+    g_log.debug() << "Adding tab " << (*it).toStdString() << std::endl;
   }
 
   // Disable instruments as required
-  m_uiForm.iicInstrumentConfiguration->setDisabledInstruments(disabledInstruments);
+  m_uiForm.iicInstrumentConfiguration->setDisabledInstruments(
+      disabledInstruments);
 }
 
-
 /**
  * Handles showing the manage directory dialog box.
  */
-void IndirectDataReduction::openDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+void IndirectDataReduction::openDirectoryDialog() {
+  MantidQt::API::ManageUserDirectories *ad =
+      new MantidQt::API::ManageUserDirectories(this);
   ad->show();
   ad->setFocus();
 }
 
-
 /**
  * Slot to wrap the protected showInformationBox method defined
  * in UserSubWindow and provide access to composed tabs.
  *
  * @param message The message to display in the message box
  */
-void IndirectDataReduction::showMessageBox(const QString& message)
-{
+void IndirectDataReduction::showMessageBox(const QString &message) {
   showInformationBox(message);
 }
 
-
 /**
  * Slot to allow setting the state of the Run button.
  *
@@ -570,8 +547,8 @@ void IndirectDataReduction::showMessageBox(const QString& message)
  * @param message Message shown on the button
  * @param tooltip Tooltip shown when hovering over button
  */
-void IndirectDataReduction::updateRunButton(bool enabled, QString message, QString tooltip)
-{
+void IndirectDataReduction::updateRunButton(bool enabled, QString message,
+                                            QString tooltip) {
   m_uiForm.pbRun->setEnabled(enabled);
   m_uiForm.pbRun->setText(message);
   m_uiForm.pbRun->setToolTip(tooltip);
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
index 483693fc96cf2a6251b5c35cb96e84874282a732..fabd3305deb9d275b1ec8490038d60c6f81edf3c 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp
@@ -361,7 +361,8 @@ void IndirectDiffractionReduction::runOSIRISdiffonlyReduction() {
 
   if (m_uiForm.ckUseCan->isChecked()) {
     osirisDiffReduction->setProperty(
-        "Container", m_uiForm.rfCanFiles->getFilenames().join(",").toStdString());
+        "Container",
+        m_uiForm.rfCanFiles->getFilenames().join(",").toStdString());
     if (m_uiForm.ckCanScale->isChecked())
       osirisDiffReduction->setProperty("ContainerScaleFactor",
                                        m_uiForm.spCanScale->value());
@@ -555,8 +556,7 @@ void IndirectDiffractionReduction::loadSettings() {
   QSettings settings;
   QString dataDir = QString::fromStdString(
                         Mantid::Kernel::ConfigService::Instance().getString(
-                            "datasearch.directories"))
-                        .split(";")[0];
+                            "datasearch.directories")).split(";")[0];
 
   settings.beginGroup(m_settingsGroup);
   settings.setValue("last_directory", dataDir);
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSassena.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSassena.cpp
index e4121cc5867c5f38ad6950c065f57e744b514e89..e8d4a3e4f25ae03a518f7286cbdc41172b998339 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSassena.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSassena.cpp
@@ -3,104 +3,96 @@
 #include <QFileInfo>
 #include <QString>
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-		IndirectSassena::IndirectSassena(QWidget * parent) :
-			IndirectSimulationTab(parent)
-		{
-			m_uiForm.setupUi(parent);
-      connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(handleAlgorithmFinish(bool)));
-		}
-
-    void IndirectSassena::setup()
-    {
-    }
-
-    /**
-     * Validate the form to check the program can be run.
-     *
-     * @return Whether the form was valid
-     */
-		bool IndirectSassena::validate()
-		{
-      // There is very little to actually be invalid here
-      // that was not already done via restrictions on input
-      return true;
-		}
-
-    /**
-     * Configures and executes the LoadSassena algorithm.
-     */
-		void IndirectSassena::run()
-    {
-      using namespace Mantid::API;
-      using MantidQt::API::BatchAlgorithmRunner;
-
-			QString inputFileName = m_uiForm.mwInputFile->getFirstFilename();
-			QFileInfo inputFileInfo(inputFileName);
-      m_outWsName = inputFileInfo.baseName();
-      bool save = m_uiForm.chkSave->isChecked();
-
-      // If the workspace group already exists then remove it
-      if(AnalysisDataService::Instance().doesExist(m_outWsName.toStdString()))
-        AnalysisDataService::Instance().deepRemoveGroup(m_outWsName.toStdString());
-
-      IAlgorithm_sptr sassenaAlg = AlgorithmManager::Instance().create("LoadSassena");
-      sassenaAlg->initialize();
-
-      sassenaAlg->setProperty("Filename", inputFileName.toStdString());
-      sassenaAlg->setProperty("SortByQVectors", m_uiForm.cbSortQ->isChecked());
-      sassenaAlg->setProperty("TimeUnit", m_uiForm.sbTimeUnit->value());
-      sassenaAlg->setProperty("OutputWorkspace", m_outWsName.toStdString());
-
-      m_batchAlgoRunner->addAlgorithm(sassenaAlg);
-
-      BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromSassenaAlg;
-      inputFromSassenaAlg["InputWorkspace"] = m_outWsName.toStdString();
-
-      if(save)
-      {
-        QString saveFilename = m_outWsName + ".nxs";
-
-        IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexus");
-        saveAlg->initialize();
-
-        saveAlg->setProperty("Filename", saveFilename.toStdString());
-
-        m_batchAlgoRunner->addAlgorithm(saveAlg, inputFromSassenaAlg);
-      }
-
-      m_batchAlgoRunner->executeBatchAsync();
-		}
-
-    /**
-     * Handles completion of the algorithm batch.
-     *
-     * @param error If the batch was stopped due to error
-     */
-    void IndirectSassena::handleAlgorithmFinish(bool error)
-    {
-      bool plot = m_uiForm.chkPlot->isChecked();
-
-      // Nothing to do if the algorithm failed or we do not want to plot
-      if(error || !plot)
-        return;
-
-      plotSpectrum(m_outWsName);
-    }
-
-    /**
-     * Set the data selectors to use the default save directory
-     * when browsing for input files.
-     *
-     * @param settings :: The settings to loading into the interface
-     */
-		void IndirectSassena::loadSettings(const QSettings& settings)
-		{
-			m_uiForm.mwInputFile->readSettings(settings.group());
-		}
-
-	} // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+IndirectSassena::IndirectSassena(QWidget *parent)
+    : IndirectSimulationTab(parent) {
+  m_uiForm.setupUi(parent);
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(handleAlgorithmFinish(bool)));
+}
+
+void IndirectSassena::setup() {}
+
+/**
+ * Validate the form to check the program can be run.
+ *
+ * @return Whether the form was valid
+ */
+bool IndirectSassena::validate() {
+  // There is very little to actually be invalid here
+  // that was not already done via restrictions on input
+  return true;
+}
+
+/**
+ * Configures and executes the LoadSassena algorithm.
+ */
+void IndirectSassena::run() {
+  using namespace Mantid::API;
+  using MantidQt::API::BatchAlgorithmRunner;
+
+  QString inputFileName = m_uiForm.mwInputFile->getFirstFilename();
+  QFileInfo inputFileInfo(inputFileName);
+  m_outWsName = inputFileInfo.baseName();
+  bool save = m_uiForm.chkSave->isChecked();
+
+  // If the workspace group already exists then remove it
+  if (AnalysisDataService::Instance().doesExist(m_outWsName.toStdString()))
+    AnalysisDataService::Instance().deepRemoveGroup(m_outWsName.toStdString());
+
+  IAlgorithm_sptr sassenaAlg =
+      AlgorithmManager::Instance().create("LoadSassena");
+  sassenaAlg->initialize();
+
+  sassenaAlg->setProperty("Filename", inputFileName.toStdString());
+  sassenaAlg->setProperty("SortByQVectors", m_uiForm.cbSortQ->isChecked());
+  sassenaAlg->setProperty("TimeUnit", m_uiForm.sbTimeUnit->value());
+  sassenaAlg->setProperty("OutputWorkspace", m_outWsName.toStdString());
+
+  m_batchAlgoRunner->addAlgorithm(sassenaAlg);
+
+  BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromSassenaAlg;
+  inputFromSassenaAlg["InputWorkspace"] = m_outWsName.toStdString();
+
+  if (save) {
+    QString saveFilename = m_outWsName + ".nxs";
+
+    IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexus");
+    saveAlg->initialize();
+
+    saveAlg->setProperty("Filename", saveFilename.toStdString());
+
+    m_batchAlgoRunner->addAlgorithm(saveAlg, inputFromSassenaAlg);
+  }
+
+  m_batchAlgoRunner->executeBatchAsync();
+}
+
+/**
+ * Handles completion of the algorithm batch.
+ *
+ * @param error If the batch was stopped due to error
+ */
+void IndirectSassena::handleAlgorithmFinish(bool error) {
+  bool plot = m_uiForm.chkPlot->isChecked();
+
+  // Nothing to do if the algorithm failed or we do not want to plot
+  if (error || !plot)
+    return;
+
+  plotSpectrum(m_outWsName);
+}
+
+/**
+ * Set the data selectors to use the default save directory
+ * when browsing for input files.
+ *
+ * @param settings :: The settings to loading into the interface
+ */
+void IndirectSassena::loadSettings(const QSettings &settings) {
+  m_uiForm.mwInputFile->readSettings(settings.group());
+}
+
+} // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp
index 4c9e4808cecb04eb06f47dbb963350b6661cb477..895565b444881f36daab527d84a26baaa312ab05 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp
@@ -10,27 +10,21 @@
 #include <QUrl>
 
 // Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    DECLARE_SUBWINDOW(IndirectSimulation)
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(IndirectSimulation)
+}
 }
 
 using namespace MantidQt::CustomInterfaces;
 
-IndirectSimulation::IndirectSimulation(QWidget *parent) : UserSubWindow(parent),
-  m_changeObserver(*this, &IndirectSimulation::handleDirectoryChange)
-{
-}
+IndirectSimulation::IndirectSimulation(QWidget *parent)
+    : UserSubWindow(parent),
+      m_changeObserver(*this, &IndirectSimulation::handleDirectoryChange) {}
 
-IndirectSimulation::~IndirectSimulation()
-{
-}
+IndirectSimulation::~IndirectSimulation() {}
 
-void IndirectSimulation::initLayout()
-{
+void IndirectSimulation::initLayout() {
   m_uiForm.setupUi(this);
 
   // Connect Poco Notification Observer
@@ -47,19 +41,23 @@ void IndirectSimulation::initLayout()
       DOS, new DensityOfStates(m_uiForm.IndirectSimulationTabs->widget(DOS)));
 
   // Connect each tab to the actions available in this GUI
-  std::map<unsigned int, IndirectSimulationTab*>::iterator iter;
-  for (iter = m_simulationTabs.begin(); iter != m_simulationTabs.end(); ++iter)
-  {
-    connect(iter->second, SIGNAL(runAsPythonScript(const QString&, bool)), this, SIGNAL(runAsPythonScript(const QString&, bool)));
-    connect(iter->second, SIGNAL(showMessageBox(const QString&)), this, SLOT(showMessageBox(const QString&)));
+  std::map<unsigned int, IndirectSimulationTab *>::iterator iter;
+  for (iter = m_simulationTabs.begin(); iter != m_simulationTabs.end();
+       ++iter) {
+    connect(iter->second, SIGNAL(runAsPythonScript(const QString &, bool)),
+            this, SIGNAL(runAsPythonScript(const QString &, bool)));
+    connect(iter->second, SIGNAL(showMessageBox(const QString &)), this,
+            SLOT(showMessageBox(const QString &)));
   }
 
   loadSettings();
 
-  // Connect statements for the buttons shared between all tabs on the Indirect Bayes interface
+  // Connect statements for the buttons shared between all tabs on the Indirect
+  // Bayes interface
   connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked()));
   connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
-  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(manageUserDirectories()));
+  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this,
+          SLOT(manageUserDirectories()));
 }
 
 /**
@@ -67,8 +65,7 @@ void IndirectSimulation::initLayout()
  *
  * @param :: the detected close event
  */
-void IndirectSimulation::closeEvent(QCloseEvent*)
-{
+void IndirectSimulation::closeEvent(QCloseEvent *) {
   Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
 }
 
@@ -77,11 +74,10 @@ void IndirectSimulation::closeEvent(QCloseEvent*)
  *
  * @param pNf :: notification
  */
-void IndirectSimulation::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
-{
+void IndirectSimulation::handleDirectoryChange(
+    Mantid::Kernel::ConfigValChangeNotification_ptr pNf) {
   std::string key = pNf->key();
-  if ( key == "defaultsave.directory" )
-  {
+  if (key == "defaultsave.directory") {
     loadSettings();
   }
 }
@@ -89,20 +85,22 @@ void IndirectSimulation::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNo
 /**
  * Load the setting for each tab on the interface.
  *
- * This includes setting the default browsing directory to be the default save directory.
+ * This includes setting the default browsing directory to be the default save
+ *directory.
  */
-void IndirectSimulation::loadSettings()
-{
+void IndirectSimulation::loadSettings() {
   QSettings settings;
   QString settingsGroup = "CustomInterfaces/IndirectAnalysis/";
-  QString saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+  QString saveDir = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "defaultsave.directory"));
 
   settings.beginGroup(settingsGroup + "ProcessedFiles");
   settings.setValue("last_directory", saveDir);
 
-  std::map<unsigned int, IndirectSimulationTab*>::iterator iter;
-  for (iter = m_simulationTabs.begin(); iter != m_simulationTabs.end(); ++iter)
-  {
+  std::map<unsigned int, IndirectSimulationTab *>::iterator iter;
+  for (iter = m_simulationTabs.begin(); iter != m_simulationTabs.end();
+       ++iter) {
     iter->second->loadSettings(settings);
   }
 
@@ -116,8 +114,7 @@ void IndirectSimulation::loadSettings()
  * This method checks the tabs validate method is passing before calling
  * the run method.
  */
-void IndirectSimulation::runClicked()
-{
+void IndirectSimulation::runClicked() {
   int tabIndex = m_uiForm.IndirectSimulationTabs->currentIndex();
   m_simulationTabs[tabIndex]->runTab();
 }
@@ -126,18 +123,18 @@ void IndirectSimulation::runClicked()
  * Slot to open a new browser window and navigate to the help page
  * on the wiki for the currently selected tab.
  */
-void IndirectSimulation::helpClicked()
-{
-  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Indirect_Simulation"));
+void IndirectSimulation::helpClicked() {
+  MantidQt::API::HelpWindow::showCustomInterface(
+      NULL, QString("Indirect_Simulation"));
 }
 
 /**
  * Slot to show the manage user dicrectories dialog when the user clicks
  * the button on the interface.
  */
-void IndirectSimulation::manageUserDirectories()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+void IndirectSimulation::manageUserDirectories() {
+  MantidQt::API::ManageUserDirectories *ad =
+      new MantidQt::API::ManageUserDirectories(this);
   ad->show();
   ad->setFocus();
 }
@@ -148,7 +145,6 @@ void IndirectSimulation::manageUserDirectories()
  *
  * @param message :: The message to display in the message box
  */
-void IndirectSimulation::showMessageBox(const QString& message)
-{
+void IndirectSimulation::showMessageBox(const QString &message) {
   showInformationBox(message);
 }
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulationTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulationTab.cpp
index 28473c29fd3d14a6bddeff645c280853dc50bd88..9b88ab0942753cd8f4b7923c2e5ae7388182ffea 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulationTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulationTab.cpp
@@ -3,23 +3,17 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
-    //----------------------------------------------------------------------------------------------
-    /** Constructor
-     */
-    IndirectSimulationTab::IndirectSimulationTab(QWidget * parent) : IndirectTab(parent)
-    {
-    }
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IndirectSimulationTab::IndirectSimulationTab(QWidget *parent)
+    : IndirectTab(parent) {}
 
-    //----------------------------------------------------------------------------------------------
-    /** Destructor
-     */
-    IndirectSimulationTab::~IndirectSimulationTab()
-    {
-    }
-
-  }
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IndirectSimulationTab::~IndirectSimulationTab() {}
+}
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
index ae95af54d1a0d2da6c4d7ba5955fd38b9248079e..2934259b8851c61c5e12308a4b2255d2848c433e 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSqw.cpp
@@ -8,196 +8,192 @@
 using namespace Mantid::API;
 using MantidQt::API::BatchAlgorithmRunner;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  IndirectSqw::IndirectSqw(IndirectDataReduction * idrUI, QWidget * parent) :
-    IndirectDataReductionTab(idrUI, parent)
-  {
-    m_uiForm.setupUi(parent);
-
-    connect(m_uiForm.dsSampleInput, SIGNAL(loadClicked()), this, SLOT(plotContour()));
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(sqwAlgDone(bool)));
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IndirectSqw::IndirectSqw(IndirectDataReduction *idrUI, QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent) {
+  m_uiForm.setupUi(parent);
+
+  connect(m_uiForm.dsSampleInput, SIGNAL(loadClicked()), this,
+          SLOT(plotContour()));
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(sqwAlgDone(bool)));
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IndirectSqw::~IndirectSqw() {}
+
+void IndirectSqw::setup() {}
+
+bool IndirectSqw::validate() {
+  double tolerance = 1e-10;
+  UserInputValidator uiv;
+
+  // Validate the data selector
+  uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSampleInput);
+
+  // Validate Q binning
+  uiv.checkBins(m_uiForm.spQLow->value(), m_uiForm.spQWidth->value(),
+                m_uiForm.spQHigh->value(), tolerance);
+
+  // If selected, validate energy binning
+  if (m_uiForm.ckRebinInEnergy->isChecked())
+    uiv.checkBins(m_uiForm.spELow->value(), m_uiForm.spEWidth->value(),
+                  m_uiForm.spEHigh->value(), tolerance);
+
+  QString errorMessage = uiv.generateErrorMessage();
+
+  // Show an error message if needed
+  if (!errorMessage.isEmpty())
+    emit showMessageBox(errorMessage);
+
+  return errorMessage.isEmpty();
+}
+
+void IndirectSqw::run() {
+  QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  QString sqwWsName = sampleWsName.left(sampleWsName.length() - 4) + "_sqw";
+  QString eRebinWsName = sampleWsName.left(sampleWsName.length() - 4) + "_r";
+  QString method = m_uiForm.cbMethod->currentText();
+
+  QString rebinString = m_uiForm.spQLow->text() + "," +
+                        m_uiForm.spQWidth->text() + "," +
+                        m_uiForm.spQHigh->text();
+
+  // Rebin in energy
+  bool rebinInEnergy = m_uiForm.ckRebinInEnergy->isChecked();
+  if (rebinInEnergy) {
+    QString eRebinString = m_uiForm.spELow->text() + "," +
+                           m_uiForm.spEWidth->text() + "," +
+                           m_uiForm.spEHigh->text();
+
+    IAlgorithm_sptr energyRebinAlg =
+        AlgorithmManager::Instance().create("Rebin");
+    energyRebinAlg->initialize();
+
+    energyRebinAlg->setProperty("InputWorkspace", sampleWsName.toStdString());
+    energyRebinAlg->setProperty("OutputWorkspace", eRebinWsName.toStdString());
+    energyRebinAlg->setProperty("Params", eRebinString.toStdString());
+
+    m_batchAlgoRunner->addAlgorithm(energyRebinAlg);
   }
 
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  IndirectSqw::~IndirectSqw()
-  {
-  }
-
-  void IndirectSqw::setup()
-  {
-  }
-
-  bool IndirectSqw::validate()
-  {
-    double tolerance = 1e-10;
-    UserInputValidator uiv;
-
-    // Validate the data selector
-    uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSampleInput);
-
-    // Validate Q binning
-    uiv.checkBins(m_uiForm.spQLow->value(), m_uiForm.spQWidth->value(), m_uiForm.spQHigh->value(), tolerance);
-
-    // If selected, validate energy binning
-    if(m_uiForm.ckRebinInEnergy->isChecked())
-      uiv.checkBins(m_uiForm.spELow->value(), m_uiForm.spEWidth->value(), m_uiForm.spEHigh->value(), tolerance);
-
-    QString errorMessage = uiv.generateErrorMessage();
-
-    // Show an error message if needed
-    if(!errorMessage.isEmpty())
-      emit showMessageBox(errorMessage);
+  QString eFixed = getInstrumentDetails()["Efixed"];
 
-    return errorMessage.isEmpty();
-  }
-
-  void IndirectSqw::run()
-  {
-    QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    QString sqwWsName = sampleWsName.left(sampleWsName.length() - 4) + "_sqw";
-    QString eRebinWsName = sampleWsName.left(sampleWsName.length() - 4) + "_r";
-    QString method = m_uiForm.cbMethod->currentText();
-
-    QString rebinString = m_uiForm.spQLow->text() + "," + m_uiForm.spQWidth->text() +
-      "," + m_uiForm.spQHigh->text();
-
-    // Rebin in energy
-    bool rebinInEnergy = m_uiForm.ckRebinInEnergy->isChecked();
-    if(rebinInEnergy)
-    {
-      QString eRebinString = m_uiForm.spELow->text() + "," + m_uiForm.spEWidth->text() +
-                             "," + m_uiForm.spEHigh->text();
+  IAlgorithm_sptr sqwAlg = AlgorithmManager::Instance().create("SofQW");
+  sqwAlg->initialize();
 
-      IAlgorithm_sptr energyRebinAlg = AlgorithmManager::Instance().create("Rebin");
-      energyRebinAlg->initialize();
+  BatchAlgorithmRunner::AlgorithmRuntimeProps sqwInputProps;
+  if (rebinInEnergy)
+    sqwInputProps["InputWorkspace"] = eRebinWsName.toStdString();
+  else
+    sqwInputProps["InputWorkspace"] = sampleWsName.toStdString();
 
-      energyRebinAlg->setProperty("InputWorkspace", sampleWsName.toStdString());
-      energyRebinAlg->setProperty("OutputWorkspace", eRebinWsName.toStdString());
-      energyRebinAlg->setProperty("Params", eRebinString.toStdString());
+  sqwAlg->setProperty("OutputWorkspace", sqwWsName.toStdString());
+  sqwAlg->setProperty("QAxisBinning", rebinString.toStdString());
+  sqwAlg->setProperty("EMode", "Indirect");
+  sqwAlg->setProperty("EFixed", eFixed.toStdString());
+  sqwAlg->setProperty("Method", method.toStdString());
 
-      m_batchAlgoRunner->addAlgorithm(energyRebinAlg);
-    }
+  m_batchAlgoRunner->addAlgorithm(sqwAlg, sqwInputProps);
 
-    QString eFixed = getInstrumentDetails()["Efixed"];
+  // Add sample log for S(Q, w) algorithm used
+  IAlgorithm_sptr sampleLogAlg =
+      AlgorithmManager::Instance().create("AddSampleLog");
+  sampleLogAlg->initialize();
 
-    IAlgorithm_sptr sqwAlg = AlgorithmManager::Instance().create("SofQW");
-    sqwAlg->initialize();
+  sampleLogAlg->setProperty("LogName", "rebin_type");
+  sampleLogAlg->setProperty("LogType", "String");
+  sampleLogAlg->setProperty("LogText", method.toStdString());
 
-    BatchAlgorithmRunner::AlgorithmRuntimeProps sqwInputProps;
-    if(rebinInEnergy)
-      sqwInputProps["InputWorkspace"] = eRebinWsName.toStdString();
-    else
-      sqwInputProps["InputWorkspace"] = sampleWsName.toStdString();
+  BatchAlgorithmRunner::AlgorithmRuntimeProps inputToAddSampleLogProps;
+  inputToAddSampleLogProps["Workspace"] = sqwWsName.toStdString();
 
-    sqwAlg->setProperty("OutputWorkspace", sqwWsName.toStdString());
-    sqwAlg->setProperty("QAxisBinning", rebinString.toStdString());
-    sqwAlg->setProperty("EMode", "Indirect");
-    sqwAlg->setProperty("EFixed", eFixed.toStdString());
-    sqwAlg->setProperty("Method", method.toStdString());
+  m_batchAlgoRunner->addAlgorithm(sampleLogAlg, inputToAddSampleLogProps);
 
-    m_batchAlgoRunner->addAlgorithm(sqwAlg, sqwInputProps);
+  // Save S(Q, w) workspace
+  if (m_uiForm.ckSave->isChecked()) {
+    QString saveFilename = sqwWsName + ".nxs";
 
-    // Add sample log for S(Q, w) algorithm used
-    IAlgorithm_sptr sampleLogAlg = AlgorithmManager::Instance().create("AddSampleLog");
-    sampleLogAlg->initialize();
+    IAlgorithm_sptr saveNexusAlg =
+        AlgorithmManager::Instance().create("SaveNexus");
+    saveNexusAlg->initialize();
 
-    sampleLogAlg->setProperty("LogName", "rebin_type");
-    sampleLogAlg->setProperty("LogType", "String");
-    sampleLogAlg->setProperty("LogText", method.toStdString());
+    saveNexusAlg->setProperty("Filename", saveFilename.toStdString());
 
-    BatchAlgorithmRunner::AlgorithmRuntimeProps inputToAddSampleLogProps;
-    inputToAddSampleLogProps["Workspace"] = sqwWsName.toStdString();
+    BatchAlgorithmRunner::AlgorithmRuntimeProps inputToSaveNexusProps;
+    inputToSaveNexusProps["InputWorkspace"] = sqwWsName.toStdString();
 
-    m_batchAlgoRunner->addAlgorithm(sampleLogAlg, inputToAddSampleLogProps);
+    m_batchAlgoRunner->addAlgorithm(saveNexusAlg, inputToSaveNexusProps);
+  }
 
-    // Save S(Q, w) workspace
-    if(m_uiForm.ckSave->isChecked())
-    {
-      QString saveFilename = sqwWsName + ".nxs";
+  // Set the name of the result workspace for Python export
+  m_pythonExportWsName = sqwWsName.toStdString();
 
-      IAlgorithm_sptr saveNexusAlg = AlgorithmManager::Instance().create("SaveNexus");
-      saveNexusAlg->initialize();
+  m_batchAlgoRunner->executeBatch();
+}
 
-      saveNexusAlg->setProperty("Filename", saveFilename.toStdString());
+/**
+ * Handles plotting the S(Q, w) workspace when the algorithm chain is finished.
+ *
+ * @param error If the algorithm chain failed
+ */
+void IndirectSqw::sqwAlgDone(bool error) {
+  if (error)
+    return;
 
-      BatchAlgorithmRunner::AlgorithmRuntimeProps inputToSaveNexusProps;
-      inputToSaveNexusProps["InputWorkspace"] = sqwWsName.toStdString();
+  // Get the workspace name
+  QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  QString sqwWsName = sampleWsName.left(sampleWsName.length() - 4) + "_sqw";
 
-      m_batchAlgoRunner->addAlgorithm(saveNexusAlg, inputToSaveNexusProps);
-    }
+  QString plotType = m_uiForm.cbPlotType->currentText();
 
-    // Set the name of the result workspace for Python export
-    m_pythonExportWsName = sqwWsName.toStdString();
+  if (plotType == "Contour")
+    plot2D(sqwWsName);
 
-    m_batchAlgoRunner->executeBatch();
+  else if (plotType == "Spectra") {
+    auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+        sqwWsName.toStdString());
+    int numHist = static_cast<int>(ws->getNumberHistograms());
+    plotSpectrum(sqwWsName, 0, numHist - 1);
   }
-
-  /**
-   * Handles plotting the S(Q, w) workspace when the algorithm chain is finished.
-   *
-   * @param error If the algorithm chain failed
-   */
-  void IndirectSqw::sqwAlgDone(bool error)
-  {
-    if(error)
-      return;
-
-    // Get the workspace name
+}
+
+/**
+ * Handles the Plot Input button
+ *
+ * Creates a colour 2D plot of the data
+ */
+void IndirectSqw::plotContour() {
+  if (m_uiForm.dsSampleInput->isValid()) {
     QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    QString sqwWsName = sampleWsName.left(sampleWsName.length() - 4) + "_sqw";
 
-    QString plotType = m_uiForm.cbPlotType->currentText();
+    QString convertedWsName =
+        sampleWsName.left(sampleWsName.length() - 4) + "_rqw";
 
-    if(plotType == "Contour")
-      plot2D(sqwWsName);
+    IAlgorithm_sptr convertSpecAlg =
+        AlgorithmManager::Instance().create("ConvertSpectrumAxis");
+    convertSpecAlg->initialize();
 
-    else if(plotType == "Spectra")
-    {
-      auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(sqwWsName.toStdString());
-      int numHist = static_cast<int>(ws->getNumberHistograms());
-      plotSpectrum(sqwWsName, 0, numHist-1);
-    }
-  }
+    convertSpecAlg->setProperty("InputWorkspace", sampleWsName.toStdString());
+    convertSpecAlg->setProperty("OutputWorkspace",
+                                convertedWsName.toStdString());
+    convertSpecAlg->setProperty("Target", "ElasticQ");
+    convertSpecAlg->setProperty("EMode", "Indirect");
+
+    convertSpecAlg->execute();
 
-  /**
-   * Handles the Plot Input button
-   *
-   * Creates a colour 2D plot of the data
-   */
-  void IndirectSqw::plotContour()
-  {
-    if(m_uiForm.dsSampleInput->isValid())
-    {
-      QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-
-      QString convertedWsName = sampleWsName.left(sampleWsName.length() - 4) + "_rqw";
-
-      IAlgorithm_sptr convertSpecAlg = AlgorithmManager::Instance().create("ConvertSpectrumAxis");
-      convertSpecAlg->initialize();
-
-      convertSpecAlg->setProperty("InputWorkspace", sampleWsName.toStdString());
-      convertSpecAlg->setProperty("OutputWorkspace", convertedWsName.toStdString());
-      convertSpecAlg->setProperty("Target", "ElasticQ");
-      convertSpecAlg->setProperty("EMode", "Indirect");
-
-      convertSpecAlg->execute();
-
-      QString pyInput = "plot2D('" + convertedWsName + "')\n";
-      m_pythonRunner.runPythonCode(pyInput);
-    }
-    else
-    {
-      emit showMessageBox("Invalid filename.");
-    }
+    QString pyInput = "plot2D('" + convertedWsName + "')\n";
+    m_pythonRunner.runPythonCode(pyInput);
+  } else {
+    emit showMessageBox("Invalid filename.");
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp
index 666a817cc0f6001528d8a84d7f54d211b697e802..663116b4e5510a1f7ba09c3da3f73c8a6bef50f5 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp
@@ -1,4 +1,4 @@
-# include "MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h"
+#include "MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.h"
 
 #include "MantidAPI/MatrixWorkspace.h"
 #include "MantidAPI/ITableWorkspace.h"
@@ -7,515 +7,519 @@
 
 #include <QFileInfo>
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("IndirectSymmetrise");
+namespace {
+Mantid::Kernel::Logger g_log("IndirectSymmetrise");
 }
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  IndirectSymmetrise::IndirectSymmetrise(IndirectDataReduction * idrUI, QWidget * parent) :
-    IndirectDataReductionTab(idrUI, parent)
-  {
-    m_uiForm.setupUi(parent);
-
-    int numDecimals = 6;
-
-    // Property Trees
-    m_propTrees["SymmPropTree"] = new QtTreePropertyBrowser();
-    m_uiForm.properties->addWidget(m_propTrees["SymmPropTree"]);
-
-    m_propTrees["SymmPVPropTree"] = new QtTreePropertyBrowser();
-    m_uiForm.propertiesPreview->addWidget(m_propTrees["SymmPVPropTree"]);
-
-    // Editor Factories
-    DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
-    m_propTrees["SymmPropTree"]->setFactoryForManager(m_dblManager, doubleEditorFactory);
-
-    // Raw Properties
-    m_properties["EMin"] = m_dblManager->addProperty("EMin");
-    m_dblManager->setDecimals(m_properties["EMin"], numDecimals);
-    m_propTrees["SymmPropTree"]->addProperty(m_properties["EMin"]);
-    m_properties["EMax"] = m_dblManager->addProperty("EMax");
-    m_dblManager->setDecimals(m_properties["EMax"], numDecimals);
-    m_propTrees["SymmPropTree"]->addProperty(m_properties["EMax"]);
-
-    QtProperty* rawPlotProps = m_grpManager->addProperty("Raw Plot");
-    m_propTrees["SymmPropTree"]->addProperty(rawPlotProps);
-
-    m_properties["PreviewSpec"] = m_dblManager->addProperty("Spectrum No");
-    m_dblManager->setDecimals(m_properties["PreviewSpec"], 0);
-    rawPlotProps->addSubProperty(m_properties["PreviewSpec"]);
-
-    // Preview Properties
-    // Mainly used for display rather than getting user input
-    m_properties["NegativeYValue"] = m_dblManager->addProperty("Negative Y");
-    m_dblManager->setDecimals(m_properties["NegativeYValue"], numDecimals);
-    m_propTrees["SymmPVPropTree"]->addProperty(m_properties["NegativeYValue"]);
-
-    m_properties["PositiveYValue"] = m_dblManager->addProperty("Positive Y");
-    m_dblManager->setDecimals(m_properties["PositiveYValue"], numDecimals);
-    m_propTrees["SymmPVPropTree"]->addProperty(m_properties["PositiveYValue"]);
-
-    m_properties["DeltaY"] = m_dblManager->addProperty("Delta Y");
-    m_dblManager->setDecimals(m_properties["DeltaY"], numDecimals);
-    m_propTrees["SymmPVPropTree"]->addProperty(m_properties["DeltaY"]);
-
-    // Indicators for Y value at each EMin position
-    auto negativeEMinYPos = m_uiForm.ppRawPlot->addRangeSelector("NegativeEMinYPos",
-                                                                 MantidWidgets::RangeSelector::YSINGLE);
-    negativeEMinYPos->setInfoOnly(true);
-    negativeEMinYPos->setColour(Qt::blue);
-    negativeEMinYPos->setMinimum(0.0);
-
-    auto positiveEMinYPos = m_uiForm.ppRawPlot->addRangeSelector("PositiveEMinYPos",
-                                                                 MantidWidgets::RangeSelector::YSINGLE);
-    positiveEMinYPos->setInfoOnly(true);
-    positiveEMinYPos->setColour(Qt::red);
-    positiveEMinYPos->setMinimum(0.0);
-
-    // Indicator for centre of symmetry (x=0)
-    auto centreMarkRaw = m_uiForm.ppRawPlot->addRangeSelector("CentreMark",
-                                                              MantidWidgets::RangeSelector::XSINGLE);
-    centreMarkRaw->setInfoOnly(true);
-    centreMarkRaw->setColour(Qt::cyan);
-    centreMarkRaw->setMinimum(0.0);
-
-    // Indicators for negative and positive X range values on X axis
-    // The user can use these to move the X range
-    // Note that the max and min of the negative range selector corespond to the opposite X value
-    // i.e. RS min is X max
-    auto negativeERaw = m_uiForm.ppRawPlot->addRangeSelector("NegativeE");
-    negativeERaw->setColour(Qt::darkGreen);
-
-    auto positiveERaw = m_uiForm.ppRawPlot->addRangeSelector("PositiveE");
-    positiveERaw->setColour(Qt::darkGreen);
-
-    // Indicators for negative and positive X range values on X axis
-    auto negativeEPV = m_uiForm.ppPreviewPlot->addRangeSelector("NegativeE");
-    negativeEPV->setInfoOnly(true);
-    negativeEPV->setColour(Qt::darkGreen);
-
-    auto positiveEPV = m_uiForm.ppPreviewPlot->addRangeSelector("PositiveE");
-    positiveEPV->setInfoOnly(true);
-    positiveEPV->setColour(Qt::darkGreen);
-
-    // Indicator for centre of symmetry (x=0)
-    auto centreMarkPV = m_uiForm.ppPreviewPlot->addRangeSelector("CentreMark",
-                                                                 MantidWidgets::RangeSelector::XSINGLE);
-    centreMarkPV->setInfoOnly(true);
-    centreMarkPV->setColour(Qt::cyan);
-    centreMarkPV->setMinimum(0.0);
-
-    // SIGNAL/SLOT CONNECTIONS
-    // Validate the E range when it is changed
-    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(verifyERange(QtProperty*, double)));
-    // Plot a new spectrum when the user changes the value of the preview spectrum
-    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(replotNewSpectrum(QtProperty*, double)));
-    // Plot miniplot when file has finished loading
-    connect(m_uiForm.dsInput, SIGNAL(dataReady(const QString&)), this, SLOT(plotRawInput(const QString&)));
-    // Preview symmetrise
-    connect(m_uiForm.pbPreview, SIGNAL(clicked()), this, SLOT(preview()));
-    // X range selectors
-    connect(positiveERaw, SIGNAL(minValueChanged(double)), this, SLOT(xRangeMinChanged(double)));
-    connect(positiveERaw, SIGNAL(maxValueChanged(double)), this, SLOT(xRangeMaxChanged(double)));
-    connect(negativeERaw, SIGNAL(minValueChanged(double)), this, SLOT(xRangeMinChanged(double)));
-    connect(negativeERaw, SIGNAL(maxValueChanged(double)), this, SLOT(xRangeMaxChanged(double)));
-
-    // Set default X range values
-    m_dblManager->setValue(m_properties["EMin"], 0.1);
-    m_dblManager->setValue(m_properties["EMax"], 0.5);
-
-    // Set default x axis range
-    QPair<double, double> defaultRange(-1.0, 1.0);
-    m_uiForm.ppRawPlot->setAxisRange(defaultRange, QwtPlot::xBottom);
-    m_uiForm.ppPreviewPlot->setAxisRange(defaultRange, QwtPlot::xBottom);
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  IndirectSymmetrise::~IndirectSymmetrise()
-  {
-  }
-
-  void IndirectSymmetrise::setup()
-  {
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IndirectSymmetrise::IndirectSymmetrise(IndirectDataReduction *idrUI,
+                                       QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent) {
+  m_uiForm.setupUi(parent);
+
+  int numDecimals = 6;
+
+  // Property Trees
+  m_propTrees["SymmPropTree"] = new QtTreePropertyBrowser();
+  m_uiForm.properties->addWidget(m_propTrees["SymmPropTree"]);
+
+  m_propTrees["SymmPVPropTree"] = new QtTreePropertyBrowser();
+  m_uiForm.propertiesPreview->addWidget(m_propTrees["SymmPVPropTree"]);
+
+  // Editor Factories
+  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
+  m_propTrees["SymmPropTree"]->setFactoryForManager(m_dblManager,
+                                                    doubleEditorFactory);
+
+  // Raw Properties
+  m_properties["EMin"] = m_dblManager->addProperty("EMin");
+  m_dblManager->setDecimals(m_properties["EMin"], numDecimals);
+  m_propTrees["SymmPropTree"]->addProperty(m_properties["EMin"]);
+  m_properties["EMax"] = m_dblManager->addProperty("EMax");
+  m_dblManager->setDecimals(m_properties["EMax"], numDecimals);
+  m_propTrees["SymmPropTree"]->addProperty(m_properties["EMax"]);
+
+  QtProperty *rawPlotProps = m_grpManager->addProperty("Raw Plot");
+  m_propTrees["SymmPropTree"]->addProperty(rawPlotProps);
+
+  m_properties["PreviewSpec"] = m_dblManager->addProperty("Spectrum No");
+  m_dblManager->setDecimals(m_properties["PreviewSpec"], 0);
+  rawPlotProps->addSubProperty(m_properties["PreviewSpec"]);
+
+  // Preview Properties
+  // Mainly used for display rather than getting user input
+  m_properties["NegativeYValue"] = m_dblManager->addProperty("Negative Y");
+  m_dblManager->setDecimals(m_properties["NegativeYValue"], numDecimals);
+  m_propTrees["SymmPVPropTree"]->addProperty(m_properties["NegativeYValue"]);
+
+  m_properties["PositiveYValue"] = m_dblManager->addProperty("Positive Y");
+  m_dblManager->setDecimals(m_properties["PositiveYValue"], numDecimals);
+  m_propTrees["SymmPVPropTree"]->addProperty(m_properties["PositiveYValue"]);
+
+  m_properties["DeltaY"] = m_dblManager->addProperty("Delta Y");
+  m_dblManager->setDecimals(m_properties["DeltaY"], numDecimals);
+  m_propTrees["SymmPVPropTree"]->addProperty(m_properties["DeltaY"]);
+
+  // Indicators for Y value at each EMin position
+  auto negativeEMinYPos = m_uiForm.ppRawPlot->addRangeSelector(
+      "NegativeEMinYPos", MantidWidgets::RangeSelector::YSINGLE);
+  negativeEMinYPos->setInfoOnly(true);
+  negativeEMinYPos->setColour(Qt::blue);
+  negativeEMinYPos->setMinimum(0.0);
+
+  auto positiveEMinYPos = m_uiForm.ppRawPlot->addRangeSelector(
+      "PositiveEMinYPos", MantidWidgets::RangeSelector::YSINGLE);
+  positiveEMinYPos->setInfoOnly(true);
+  positiveEMinYPos->setColour(Qt::red);
+  positiveEMinYPos->setMinimum(0.0);
+
+  // Indicator for centre of symmetry (x=0)
+  auto centreMarkRaw = m_uiForm.ppRawPlot->addRangeSelector(
+      "CentreMark", MantidWidgets::RangeSelector::XSINGLE);
+  centreMarkRaw->setInfoOnly(true);
+  centreMarkRaw->setColour(Qt::cyan);
+  centreMarkRaw->setMinimum(0.0);
+
+  // Indicators for negative and positive X range values on X axis
+  // The user can use these to move the X range
+  // Note that the max and min of the negative range selector corespond to the
+  // opposite X value
+  // i.e. RS min is X max
+  auto negativeERaw = m_uiForm.ppRawPlot->addRangeSelector("NegativeE");
+  negativeERaw->setColour(Qt::darkGreen);
+
+  auto positiveERaw = m_uiForm.ppRawPlot->addRangeSelector("PositiveE");
+  positiveERaw->setColour(Qt::darkGreen);
+
+  // Indicators for negative and positive X range values on X axis
+  auto negativeEPV = m_uiForm.ppPreviewPlot->addRangeSelector("NegativeE");
+  negativeEPV->setInfoOnly(true);
+  negativeEPV->setColour(Qt::darkGreen);
+
+  auto positiveEPV = m_uiForm.ppPreviewPlot->addRangeSelector("PositiveE");
+  positiveEPV->setInfoOnly(true);
+  positiveEPV->setColour(Qt::darkGreen);
+
+  // Indicator for centre of symmetry (x=0)
+  auto centreMarkPV = m_uiForm.ppPreviewPlot->addRangeSelector(
+      "CentreMark", MantidWidgets::RangeSelector::XSINGLE);
+  centreMarkPV->setInfoOnly(true);
+  centreMarkPV->setColour(Qt::cyan);
+  centreMarkPV->setMinimum(0.0);
+
+  // SIGNAL/SLOT CONNECTIONS
+  // Validate the E range when it is changed
+  connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
+          SLOT(verifyERange(QtProperty *, double)));
+  // Plot a new spectrum when the user changes the value of the preview spectrum
+  connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
+          SLOT(replotNewSpectrum(QtProperty *, double)));
+  // Plot miniplot when file has finished loading
+  connect(m_uiForm.dsInput, SIGNAL(dataReady(const QString &)), this,
+          SLOT(plotRawInput(const QString &)));
+  // Preview symmetrise
+  connect(m_uiForm.pbPreview, SIGNAL(clicked()), this, SLOT(preview()));
+  // X range selectors
+  connect(positiveERaw, SIGNAL(minValueChanged(double)), this,
+          SLOT(xRangeMinChanged(double)));
+  connect(positiveERaw, SIGNAL(maxValueChanged(double)), this,
+          SLOT(xRangeMaxChanged(double)));
+  connect(negativeERaw, SIGNAL(minValueChanged(double)), this,
+          SLOT(xRangeMinChanged(double)));
+  connect(negativeERaw, SIGNAL(maxValueChanged(double)), this,
+          SLOT(xRangeMaxChanged(double)));
+
+  // Set default X range values
+  m_dblManager->setValue(m_properties["EMin"], 0.1);
+  m_dblManager->setValue(m_properties["EMax"], 0.5);
+
+  // Set default x axis range
+  QPair<double, double> defaultRange(-1.0, 1.0);
+  m_uiForm.ppRawPlot->setAxisRange(defaultRange, QwtPlot::xBottom);
+  m_uiForm.ppPreviewPlot->setAxisRange(defaultRange, QwtPlot::xBottom);
+}
 
-  bool IndirectSymmetrise::validate()
-  {
-    // Check for a valid input file
-    if(!m_uiForm.dsInput->isValid())
-      return false;
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IndirectSymmetrise::~IndirectSymmetrise() {}
 
-    // EMin and EMax must be positive
-    if(m_dblManager->value(m_properties["EMin"]) <= 0.0)
-      return false;
-    if(m_dblManager->value(m_properties["EMax"]) <= 0.0)
-      return false;
+void IndirectSymmetrise::setup() {}
 
-    return true;
-  }
+bool IndirectSymmetrise::validate() {
+  // Check for a valid input file
+  if (!m_uiForm.dsInput->isValid())
+    return false;
 
-  void IndirectSymmetrise::run()
-  {
-    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
-    QString outputWorkspaceName = workspaceName.left(workspaceName.length() - 4) + "_sym" + workspaceName.right(4);
+  // EMin and EMax must be positive
+  if (m_dblManager->value(m_properties["EMin"]) <= 0.0)
+    return false;
+  if (m_dblManager->value(m_properties["EMax"]) <= 0.0)
+    return false;
 
-    double e_min = m_dblManager->value(m_properties["EMin"]);
-    double e_max = m_dblManager->value(m_properties["EMax"]);
+  return true;
+}
 
-    IAlgorithm_sptr symmetriseAlg = AlgorithmManager::Instance().create("Symmetrise", -1);
-    symmetriseAlg->initialize();
-    symmetriseAlg->setProperty("InputWorkspace", workspaceName.toStdString());
-    symmetriseAlg->setProperty("XMin", e_min);
-    symmetriseAlg->setProperty("XMax", e_max);
-    symmetriseAlg->setProperty("OutputWorkspace", outputWorkspaceName.toStdString());
-    symmetriseAlg->setProperty("OutputPropertiesTable", "__SymmetriseProps_temp");
+void IndirectSymmetrise::run() {
+  QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
+  QString outputWorkspaceName = workspaceName.left(workspaceName.length() - 4) +
+                                "_sym" + workspaceName.right(4);
 
-    m_batchAlgoRunner->addAlgorithm(symmetriseAlg);
+  double e_min = m_dblManager->value(m_properties["EMin"]);
+  double e_max = m_dblManager->value(m_properties["EMax"]);
 
-    if(m_uiForm.ckSave->isChecked())
-      addSaveWorkspaceToQueue(outputWorkspaceName);
+  IAlgorithm_sptr symmetriseAlg =
+      AlgorithmManager::Instance().create("Symmetrise", -1);
+  symmetriseAlg->initialize();
+  symmetriseAlg->setProperty("InputWorkspace", workspaceName.toStdString());
+  symmetriseAlg->setProperty("XMin", e_min);
+  symmetriseAlg->setProperty("XMax", e_max);
+  symmetriseAlg->setProperty("OutputWorkspace",
+                             outputWorkspaceName.toStdString());
+  symmetriseAlg->setProperty("OutputPropertiesTable", "__SymmetriseProps_temp");
 
-    // Set the workspace name for Python script export
-    m_pythonExportWsName = outputWorkspaceName.toStdString();
+  m_batchAlgoRunner->addAlgorithm(symmetriseAlg);
 
-    // Handle algorithm completion signal
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
+  if (m_uiForm.ckSave->isChecked())
+    addSaveWorkspaceToQueue(outputWorkspaceName);
 
-    // Execute algorithm on seperate thread
-    m_batchAlgoRunner->executeBatchAsync();
-  }
+  // Set the workspace name for Python script export
+  m_pythonExportWsName = outputWorkspaceName.toStdString();
 
-  /**
-   * Handle plotting result workspace.
-   *
-   * @param error If the algorithm failed
-   */
-  void IndirectSymmetrise::algorithmComplete(bool error)
-  {
-    disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
+  // Handle algorithm completion signal
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
 
-    if(error)
-      return;
+  // Execute algorithm on seperate thread
+  m_batchAlgoRunner->executeBatchAsync();
+}
 
-    if(m_uiForm.ckPlot->isChecked())
-    {
-      QStringList workspaces;
-      workspaces << m_uiForm.dsInput->getCurrentDataName()
-                 << QString::fromStdString(m_pythonExportWsName);
-      plotSpectrum(workspaces);
-    }
+/**
+ * Handle plotting result workspace.
+ *
+ * @param error If the algorithm failed
+ */
+void IndirectSymmetrise::algorithmComplete(bool error) {
+  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+             SLOT(algorithmComplete(bool)));
+
+  if (error)
+    return;
+
+  if (m_uiForm.ckPlot->isChecked()) {
+    QStringList workspaces;
+    workspaces << m_uiForm.dsInput->getCurrentDataName()
+               << QString::fromStdString(m_pythonExportWsName);
+    plotSpectrum(workspaces);
   }
+}
 
-  /**
-   * Plots a new workspace in the mini plot when it is loaded form the data selector.
-   *
-   * @param workspaceName Name of the workspace that has been laoded
-   */
-  void IndirectSymmetrise::plotRawInput(const QString &workspaceName)
-  {
-    // Set the preview spectrum number to the first spectrum in the workspace
-    MatrixWorkspace_sptr sampleWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName.toStdString());
-    int minSpectrumRange = sampleWS->getSpectrum(0)->getSpectrumNo();
-    m_dblManager->setValue(m_properties["PreviewSpec"], static_cast<double>(minSpectrumRange));
+/**
+ * Plots a new workspace in the mini plot when it is loaded form the data
+ *selector.
+ *
+ * @param workspaceName Name of the workspace that has been laoded
+ */
+void IndirectSymmetrise::plotRawInput(const QString &workspaceName) {
+  // Set the preview spectrum number to the first spectrum in the workspace
+  MatrixWorkspace_sptr sampleWS =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          workspaceName.toStdString());
+  int minSpectrumRange = sampleWS->getSpectrum(0)->getSpectrumNo();
+  m_dblManager->setValue(m_properties["PreviewSpec"],
+                         static_cast<double>(minSpectrumRange));
+
+  updateMiniPlots();
+
+  // Set the preview range to the maximum absolute X value
+  QPair<double, double> axisRange = m_uiForm.ppRawPlot->getCurveRange("Raw");
+  double symmRange = std::max(fabs(axisRange.first), fabs(axisRange.second));
+
+  // Set valid range for range selectors
+  m_uiForm.ppRawPlot->getRangeSelector("NegativeE")->setRange(-symmRange, 0);
+  m_uiForm.ppRawPlot->getRangeSelector("PositiveE")->setRange(0, symmRange);
+
+  // Set some default (and valid) values for E range
+  m_dblManager->setValue(m_properties["EMax"], axisRange.second);
+  m_dblManager->setValue(m_properties["EMin"], axisRange.second / 10);
+
+  updateMiniPlots();
+}
 
-    updateMiniPlots();
+/**
+ * Updates the mini plots.
+ */
+void IndirectSymmetrise::updateMiniPlots() {
+  if (!m_uiForm.dsInput->isValid())
+    return;
+
+  QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
+  int spectrumNumber =
+      static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));
+
+  Mantid::API::MatrixWorkspace_sptr input =
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(
+              workspaceName.toStdString()));
+
+  // Plot the spectrum chosen by the user
+  size_t spectrumIndex = input->getIndexFromSpectrumNumber(spectrumNumber);
+  m_uiForm.ppRawPlot->clear();
+  m_uiForm.ppRawPlot->addSpectrum("Raw", input, spectrumIndex);
+
+  // Match X axis range on preview plot
+  m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange("Raw"),
+                                       QwtPlot::xBottom);
+  m_uiForm.ppPreviewPlot->replot();
+}
 
-    // Set the preview range to the maximum absolute X value
-    QPair<double, double> axisRange = m_uiForm.ppRawPlot->getCurveRange("Raw");
-    double symmRange = std::max(fabs(axisRange.first), fabs(axisRange.second));
+/**
+ * Redraws mini plots when user changes previw range or spectrum.
+ *
+ * @param prop QtProperty that was changed
+ * @param value Value it was changed to
+ */
+void IndirectSymmetrise::replotNewSpectrum(QtProperty *prop, double value) {
+  // Validate the preview spectra
+  if (prop == m_properties["PreviewSpec"]) {
+    // Get the range of possible spectra numbers
+    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
+    MatrixWorkspace_sptr sampleWS =
+        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+            workspaceName.toStdString());
+    int minSpectrumRange = sampleWS->getSpectrum(0)->getSpectrumNo();
+    int maxSpectrumRange =
+        sampleWS->getSpectrum(sampleWS->getNumberHistograms() - 1)
+            ->getSpectrumNo();
 
-    // Set valid range for range selectors
-    m_uiForm.ppRawPlot->getRangeSelector("NegativeE")->setRange(-symmRange, 0);
-    m_uiForm.ppRawPlot->getRangeSelector("PositiveE")->setRange(0, symmRange);
+    // If entered value is lower then set spectra number to lowest valid value
+    if (value < minSpectrumRange) {
+      m_dblManager->setValue(m_properties["PreviewSpec"], minSpectrumRange);
+      return;
+    }
 
-    // Set some default (and valid) values for E range
-    m_dblManager->setValue(m_properties["EMax"], axisRange.second);
-    m_dblManager->setValue(m_properties["EMin"], axisRange.second/10);
+    // If entered value is higer then set spectra number to highest valid value
+    if (value > maxSpectrumRange) {
+      m_dblManager->setValue(m_properties["PreviewSpec"], maxSpectrumRange);
+      return;
+    }
+  }
 
+  // If we get this far then properties are valid so update mini plots
+  if (prop == m_properties["PreviewSpec"])
     updateMiniPlots();
-  }
+}
 
-  /**
-   * Updates the mini plots.
-   */
-  void IndirectSymmetrise::updateMiniPlots()
-  {
-    if(!m_uiForm.dsInput->isValid())
+/**
+ * Verifies that the E Range is valid.
+ *
+ * @param prop QtProperty changed
+ * @param value Value it was changed to (unused)
+ */
+void IndirectSymmetrise::verifyERange(QtProperty *prop, double value) {
+  UNUSED_ARG(value);
+
+  double eMin = m_dblManager->value(m_properties["EMin"]);
+  double eMax = m_dblManager->value(m_properties["EMax"]);
+
+  if (prop == m_properties["EMin"]) {
+    // If the value of EMin is negative try negating it to get a valid range
+    if (eMin < 0) {
+      eMin = -eMin;
+      m_dblManager->setValue(m_properties["EMin"], eMin);
       return;
-
-    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
-    int spectrumNumber = static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));
-
-    Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName.toStdString()));
-
-    // Plot the spectrum chosen by the user
-    size_t spectrumIndex = input->getIndexFromSpectrumNumber(spectrumNumber);
-    m_uiForm.ppRawPlot->clear();
-    m_uiForm.ppRawPlot->addSpectrum("Raw", input, spectrumIndex);
-
-    // Match X axis range on preview plot
-    m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange("Raw"), QwtPlot::xBottom);
-    m_uiForm.ppPreviewPlot->replot();
-  }
-
-  /**
-   * Redraws mini plots when user changes previw range or spectrum.
-   *
-   * @param prop QtProperty that was changed
-   * @param value Value it was changed to
-   */
-  void IndirectSymmetrise::replotNewSpectrum(QtProperty *prop, double value)
-  {
-    // Validate the preview spectra
-    if(prop == m_properties["PreviewSpec"])
-    {
-      // Get the range of possible spectra numbers
-      QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
-      MatrixWorkspace_sptr sampleWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName.toStdString());
-      int minSpectrumRange = sampleWS->getSpectrum(0)->getSpectrumNo();
-      int maxSpectrumRange = sampleWS->getSpectrum(sampleWS->getNumberHistograms()-1)->getSpectrumNo();
-
-      // If entered value is lower then set spectra number to lowest valid value
-      if(value < minSpectrumRange)
-      {
-        m_dblManager->setValue(m_properties["PreviewSpec"], minSpectrumRange);
-        return;
-      }
-
-      // If entered value is higer then set spectra number to highest valid value
-      if(value > maxSpectrumRange)
-      {
-        m_dblManager->setValue(m_properties["PreviewSpec"], maxSpectrumRange);
-        return;
-      }
     }
 
-    // If we get this far then properties are valid so update mini plots
-    if(prop == m_properties["PreviewSpec"])
-      updateMiniPlots();
-  }
-
-  /**
-   * Verifies that the E Range is valid.
-   *
-   * @param prop QtProperty changed
-   * @param value Value it was changed to (unused)
-   */
-  void IndirectSymmetrise::verifyERange(QtProperty *prop, double value)
-  {
-    UNUSED_ARG(value);
-
-    double eMin = m_dblManager->value(m_properties["EMin"]);
-    double eMax = m_dblManager->value(m_properties["EMax"]);
-
-    if(prop == m_properties["EMin"])
-    {
-      // If the value of EMin is negative try negating it to get a valid range
-      if(eMin < 0)
-      {
-        eMin = -eMin;
-        m_dblManager->setValue(m_properties["EMin"], eMin);
-        return;
-      }
-
-      // If range is still invalid reset EMin to half EMax
-      if(eMin > eMax)
-      {
-        m_dblManager->setValue(m_properties["EMin"], eMax/2);
-        return;
-      }
+    // If range is still invalid reset EMin to half EMax
+    if (eMin > eMax) {
+      m_dblManager->setValue(m_properties["EMin"], eMax / 2);
+      return;
     }
-    else if(prop == m_properties["EMax"])
-    {
-      // If the value of EMax is negative try negating it to get a valid range
-      if(eMax < 0)
-      {
-        eMax = -eMax;
-        m_dblManager->setValue(m_properties["EMax"], eMax);
-        return;
-      }
-
-      // If range is invalid reset EMax to double EMin
-      if(eMin > eMax)
-      {
-        m_dblManager->setValue(m_properties["EMax"], eMin*2);
-        return;
-      }
+  } else if (prop == m_properties["EMax"]) {
+    // If the value of EMax is negative try negating it to get a valid range
+    if (eMax < 0) {
+      eMax = -eMax;
+      m_dblManager->setValue(m_properties["EMax"], eMax);
+      return;
     }
 
-    // If we get this far then the E range is valid
-    // Update the range selectors with the new values.
-    updateRangeSelectors(prop, value);
-  }
-
-  /**
-   * Handles a request to preview the symmetrise.
-   *
-   * Runs Symmetrise on the current spectrum and plots in preview mini plot.
-   *
-   * @see IndirectSymmetrise::previewAlgDone()
-   */
-  void IndirectSymmetrise::preview()
-  {
-    // Handle algorithm completion signal
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(previewAlgDone(bool)));
-
-    // Do nothing if no data has been laoded
-    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
-    if(workspaceName.isEmpty())
+    // If range is invalid reset EMax to double EMin
+    if (eMin > eMax) {
+      m_dblManager->setValue(m_properties["EMax"], eMin * 2);
       return;
-
-    double e_min = m_dblManager->value(m_properties["EMin"]);
-    double e_max = m_dblManager->value(m_properties["EMax"]);
-    long spectrumNumber = static_cast<long>(m_dblManager->value(m_properties["PreviewSpec"]));
-    std::vector<long> spectraRange(2, spectrumNumber);
-
-    // Run the algorithm on the preview spectrum only
-    IAlgorithm_sptr symmetriseAlg = AlgorithmManager::Instance().create("Symmetrise", -1);
-    symmetriseAlg->initialize();
-    symmetriseAlg->setProperty("InputWorkspace", workspaceName.toStdString());
-    symmetriseAlg->setProperty("XMin", e_min);
-    symmetriseAlg->setProperty("XMax", e_max);
-    symmetriseAlg->setProperty("SpectraRange", spectraRange);
-    symmetriseAlg->setProperty("OutputWorkspace", "__Symmetrise_temp");
-    symmetriseAlg->setProperty("OutputPropertiesTable", "__SymmetriseProps_temp");
-
-    runAlgorithm(symmetriseAlg);
+    }
   }
 
-  /**
-   * Handles completion of the preview algorithm.
-   *
-   * @param error If the algorithm failed
-   */
-  void IndirectSymmetrise::previewAlgDone(bool error)
-  {
-    if(error)
-      return;
-
-    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
-    int spectrumNumber = static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));
-
-    MatrixWorkspace_sptr sampleWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName.toStdString());
-    ITableWorkspace_sptr propsTable = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>("__SymmetriseProps_temp");
-    MatrixWorkspace_sptr symmWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("__Symmetrise_temp");
-
-    // Get the index of XCut on each side of zero
-    int negativeIndex = propsTable->getColumn("NegativeXMinIndex")->cell<int>(0);
-    int positiveIndex = propsTable->getColumn("PositiveXMinIndex")->cell<int>(0);
-
-    // Get the Y values for each XCut and the difference between them
-    double negativeY = sampleWS->dataY(0)[negativeIndex];
-    double positiveY = sampleWS->dataY(0)[positiveIndex];
-    double deltaY = fabs(negativeY - positiveY);
-
-    // Show values in property tree
-    m_dblManager->setValue(m_properties["NegativeYValue"], negativeY);
-    m_dblManager->setValue(m_properties["PositiveYValue"], positiveY);
-    m_dblManager->setValue(m_properties["DeltaY"], deltaY);
+  // If we get this far then the E range is valid
+  // Update the range selectors with the new values.
+  updateRangeSelectors(prop, value);
+}
 
-    // Set indicator positions
-    m_uiForm.ppRawPlot->getRangeSelector("NegativeEMinYPos")->setMinimum(negativeY);
-    m_uiForm.ppRawPlot->getRangeSelector("PositiveEMinYPos")->setMinimum(positiveY);
+/**
+ * Handles a request to preview the symmetrise.
+ *
+ * Runs Symmetrise on the current spectrum and plots in preview mini plot.
+ *
+ * @see IndirectSymmetrise::previewAlgDone()
+ */
+void IndirectSymmetrise::preview() {
+  // Handle algorithm completion signal
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(previewAlgDone(bool)));
+
+  // Do nothing if no data has been laoded
+  QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
+  if (workspaceName.isEmpty())
+    return;
+
+  double e_min = m_dblManager->value(m_properties["EMin"]);
+  double e_max = m_dblManager->value(m_properties["EMax"]);
+  long spectrumNumber =
+      static_cast<long>(m_dblManager->value(m_properties["PreviewSpec"]));
+  std::vector<long> spectraRange(2, spectrumNumber);
+
+  // Run the algorithm on the preview spectrum only
+  IAlgorithm_sptr symmetriseAlg =
+      AlgorithmManager::Instance().create("Symmetrise", -1);
+  symmetriseAlg->initialize();
+  symmetriseAlg->setProperty("InputWorkspace", workspaceName.toStdString());
+  symmetriseAlg->setProperty("XMin", e_min);
+  symmetriseAlg->setProperty("XMax", e_max);
+  symmetriseAlg->setProperty("SpectraRange", spectraRange);
+  symmetriseAlg->setProperty("OutputWorkspace", "__Symmetrise_temp");
+  symmetriseAlg->setProperty("OutputPropertiesTable", "__SymmetriseProps_temp");
+
+  runAlgorithm(symmetriseAlg);
+}
 
-    // Plot preview plot
-    size_t spectrumIndex = symmWS->getIndexFromSpectrumNumber(spectrumNumber);
-    m_uiForm.ppPreviewPlot->clear();
-    m_uiForm.ppPreviewPlot->addSpectrum("Symmetrised", "__Symmetrise_temp", spectrumIndex);
+/**
+ * Handles completion of the preview algorithm.
+ *
+ * @param error If the algorithm failed
+ */
+void IndirectSymmetrise::previewAlgDone(bool error) {
+  if (error)
+    return;
+
+  QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
+  int spectrumNumber =
+      static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));
+
+  MatrixWorkspace_sptr sampleWS =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          workspaceName.toStdString());
+  ITableWorkspace_sptr propsTable =
+      AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(
+          "__SymmetriseProps_temp");
+  MatrixWorkspace_sptr symmWS =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          "__Symmetrise_temp");
+
+  // Get the index of XCut on each side of zero
+  int negativeIndex = propsTable->getColumn("NegativeXMinIndex")->cell<int>(0);
+  int positiveIndex = propsTable->getColumn("PositiveXMinIndex")->cell<int>(0);
+
+  // Get the Y values for each XCut and the difference between them
+  double negativeY = sampleWS->dataY(0)[negativeIndex];
+  double positiveY = sampleWS->dataY(0)[positiveIndex];
+  double deltaY = fabs(negativeY - positiveY);
+
+  // Show values in property tree
+  m_dblManager->setValue(m_properties["NegativeYValue"], negativeY);
+  m_dblManager->setValue(m_properties["PositiveYValue"], positiveY);
+  m_dblManager->setValue(m_properties["DeltaY"], deltaY);
+
+  // Set indicator positions
+  m_uiForm.ppRawPlot->getRangeSelector("NegativeEMinYPos")
+      ->setMinimum(negativeY);
+  m_uiForm.ppRawPlot->getRangeSelector("PositiveEMinYPos")
+      ->setMinimum(positiveY);
+
+  // Plot preview plot
+  size_t spectrumIndex = symmWS->getIndexFromSpectrumNumber(spectrumNumber);
+  m_uiForm.ppPreviewPlot->clear();
+  m_uiForm.ppPreviewPlot->addSpectrum("Symmetrised", "__Symmetrise_temp",
+                                      spectrumIndex);
+
+  // Don't want this to trigger when the algorithm is run for all spectra
+  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+             SLOT(previewAlgDone(bool)));
+}
 
-    // Don't want this to trigger when the algorithm is run for all spectra
-    disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(previewAlgDone(bool)));
+/**
+ * Updates position of XCut range selectors when used changed value of XCut.
+ *
+ * @param prop QtProperty changed
+ * @param value Value it was changed to (unused)
+ */
+void IndirectSymmetrise::updateRangeSelectors(QtProperty *prop, double value) {
+  auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
+  auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
+  auto negativeEPV = m_uiForm.ppPreviewPlot->getRangeSelector("NegativeE");
+  auto positiveEPV = m_uiForm.ppPreviewPlot->getRangeSelector("PositiveE");
+
+  value = fabs(value);
+
+  if (prop == m_properties["EMin"]) {
+    negativeERaw->setMaximum(-value);
+    positiveERaw->setMinimum(value);
+
+    negativeEPV->setMinimum(-value);
+    positiveEPV->setMinimum(value);
   }
 
-  /**
-   * Updates position of XCut range selectors when used changed value of XCut.
-   *
-   * @param prop QtProperty changed
-   * @param value Value it was changed to (unused)
-   */
-  void IndirectSymmetrise::updateRangeSelectors(QtProperty *prop, double value)
-  {
-    auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
-    auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
-    auto negativeEPV = m_uiForm.ppPreviewPlot->getRangeSelector("NegativeE");
-    auto positiveEPV = m_uiForm.ppPreviewPlot->getRangeSelector("PositiveE");
-
-    value = fabs(value);
-
-    if(prop == m_properties["EMin"])
-    {
-      negativeERaw->setMaximum(-value);
-      positiveERaw->setMinimum(value);
-
-      negativeEPV->setMinimum(-value);
-      positiveEPV->setMinimum(value);
-    }
-
-    if(prop == m_properties["EMax"])
-    {
-      negativeERaw->setMinimum(-value);
-      positiveERaw->setMaximum(value);
+  if (prop == m_properties["EMax"]) {
+    negativeERaw->setMinimum(-value);
+    positiveERaw->setMaximum(value);
 
-      negativeEPV->setMaximum(-value);
-      positiveEPV->setMaximum(value);
-    }
+    negativeEPV->setMaximum(-value);
+    positiveEPV->setMaximum(value);
   }
+}
 
-  /**
-   * Handles the X minimum value being changed from a range selector.
-   *
-   * @param value New range selector value
-   */
-  void IndirectSymmetrise::xRangeMinChanged(double value)
-  {
-    auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
-    auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
-
-    MantidWidgets::RangeSelector *from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-
-    if(from == positiveERaw)
-    {
-      m_dblManager->setValue(m_properties["EMin"], std::abs(value));
-    }
-    else if(from == negativeERaw)
-    {
-      m_dblManager->setValue(m_properties["EMax"], std::abs(value));
-    }
+/**
+ * Handles the X minimum value being changed from a range selector.
+ *
+ * @param value New range selector value
+ */
+void IndirectSymmetrise::xRangeMinChanged(double value) {
+  auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
+  auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
+
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
+
+  if (from == positiveERaw) {
+    m_dblManager->setValue(m_properties["EMin"], std::abs(value));
+  } else if (from == negativeERaw) {
+    m_dblManager->setValue(m_properties["EMax"], std::abs(value));
   }
+}
 
-  /**
-   * Handles the X maximum value being changed from a range selector.
-   *
-   * @param value New range selector value
-   */
-  void IndirectSymmetrise::xRangeMaxChanged(double value)
-  {
-    auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
-    auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
-
-    MantidWidgets::RangeSelector *from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-
-    if(from == positiveERaw)
-    {
-      m_dblManager->setValue(m_properties["EMax"], std::abs(value));
-    }
-    else if(from == negativeERaw)
-    {
-      m_dblManager->setValue(m_properties["EMin"], std::abs(value));
-    }
+/**
+ * Handles the X maximum value being changed from a range selector.
+ *
+ * @param value New range selector value
+ */
+void IndirectSymmetrise::xRangeMaxChanged(double value) {
+  auto negativeERaw = m_uiForm.ppRawPlot->getRangeSelector("NegativeE");
+  auto positiveERaw = m_uiForm.ppRawPlot->getRangeSelector("PositiveE");
+
+  MantidWidgets::RangeSelector *from =
+      qobject_cast<MantidWidgets::RangeSelector *>(sender());
+
+  if (from == positiveERaw) {
+    m_dblManager->setValue(m_properties["EMax"], std::abs(value));
+  } else if (from == negativeERaw) {
+    m_dblManager->setValue(m_properties["EMin"], std::abs(value));
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
index c90fb72d6f90f4fe4dd27f61715b02ed0e62c88e..43290b6476bdd59adf58d1ea510db239907ab38e 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp
@@ -217,8 +217,7 @@ QString IndirectTab::getWorkspaceBasename(const QString &wsName) {
  * @param workspaceNames List of names of workspaces to plot
  * @param wsIndex Index of spectrum from each workspace to plot
  */
-void IndirectTab::plotSpectrum(const QStringList &workspaceNames,
-                               int wsIndex) {
+void IndirectTab::plotSpectrum(const QStringList &workspaceNames, int wsIndex) {
   if (workspaceNames.isEmpty())
     return;
 
@@ -326,8 +325,7 @@ void IndirectTab::plot2D(const QString &workspaceName) {
  * @param workspaceNames List of names of workspaces to plot
  * @param binIndex Index of spectrum from each workspace to plot
  */
-void IndirectTab::plotTimeBin(const QStringList &workspaceNames,
-                              int binIndex) {
+void IndirectTab::plotTimeBin(const QStringList &workspaceNames, int binIndex) {
   if (workspaceNames.isEmpty())
     return;
 
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp
index 09d37af4c935155d1c7ab7e1a30e40d2f3a26a33..f5d71e115dec9754ee849388f7e8dd9fb6c9bb97 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp
@@ -8,102 +8,98 @@
 #include <QDesktopServices>
 #include <QUrl>
 
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    DECLARE_SUBWINDOW(IndirectTools)
-  }
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(IndirectTools)
+}
 }
 
 using namespace MantidQt::CustomInterfaces;
 
-IndirectTools::IndirectTools(QWidget *parent) : UserSubWindow(parent),
-	m_changeObserver(*this, &IndirectTools::handleDirectoryChange)
-{
-
-}
+IndirectTools::IndirectTools(QWidget *parent)
+    : UserSubWindow(parent),
+      m_changeObserver(*this, &IndirectTools::handleDirectoryChange) {}
 
-void IndirectTools::initLayout()
-{
-	m_uiForm.setupUi(this);
+void IndirectTools::initLayout() {
+  m_uiForm.setupUi(this);
 
   // Connect Poco Notification Observer
   Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
 
-	// Insert each tab into the interface on creation
+  // Insert each tab into the interface on creation
   m_tabs.emplace(TRANSMISSION,
                  new IndirectTransmissionCalc(
                      m_uiForm.IndirectToolsTabs->widget(TRANSMISSION)));
   m_tabs.emplace(LOAD_ILL, new IndirectLoadILL(
                                m_uiForm.IndirectToolsTabs->widget(LOAD_ILL)));
 
-        //Connect each tab to the actions available in this GUI
-	std::map<unsigned int, IndirectToolsTab*>::iterator iter;
-	for (iter = m_tabs.begin(); iter != m_tabs.end(); ++iter)
-	{
-		connect(iter->second, SIGNAL(executePythonScript(const QString&, bool)), this, SIGNAL(runAsPythonScript(const QString&, bool)));
-		connect(iter->second, SIGNAL(showMessageBox(const QString&)), this, SLOT(showMessageBox(const QString&)));
+  // Connect each tab to the actions available in this GUI
+  std::map<unsigned int, IndirectToolsTab *>::iterator iter;
+  for (iter = m_tabs.begin(); iter != m_tabs.end(); ++iter) {
+    connect(iter->second, SIGNAL(executePythonScript(const QString &, bool)),
+            this, SIGNAL(runAsPythonScript(const QString &, bool)));
+    connect(iter->second, SIGNAL(showMessageBox(const QString &)), this,
+            SLOT(showMessageBox(const QString &)));
     iter->second->setupTab();
-	}
+  }
 
-	loadSettings();
+  loadSettings();
 
-	//Connect statements for the buttons shared between all tabs on the Indirect Bayes interface
-	connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked()));
-	connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
-	connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(manageUserDirectories()));
+  // Connect statements for the buttons shared between all tabs on the Indirect
+  // Bayes interface
+  connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(runClicked()));
+  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this,
+          SLOT(manageUserDirectories()));
 }
 
-  /**
-   * Handles closing the window.
-   *
-   * @param :: the detected close event
-   */
-  void IndirectTools::closeEvent(QCloseEvent*)
-  {
-    Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
-  }
+/**
+ * Handles closing the window.
+ *
+ * @param :: the detected close event
+ */
+void IndirectTools::closeEvent(QCloseEvent *) {
+  Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
+}
 
-  /**
-   * Handles a change in directory.
-   *
-   * @param pNf :: notification
-   */
-  void IndirectTools::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
-  {
-    std::string key = pNf->key();
-    if ( key == "defaultsave.directory" )
-    {
-      loadSettings();
-    }
+/**
+ * Handles a change in directory.
+ *
+ * @param pNf :: notification
+ */
+void IndirectTools::handleDirectoryChange(
+    Mantid::Kernel::ConfigValChangeNotification_ptr pNf) {
+  std::string key = pNf->key();
+  if (key == "defaultsave.directory") {
+    loadSettings();
   }
+}
 
 /**
  * Load the setting for each tab on the interface.
  *
- * This includes setting the default browsing directory to be the default save directory.
+ * This includes setting the default browsing directory to be the default save
+ *directory.
  */
-void IndirectTools::loadSettings()
-{
+void IndirectTools::loadSettings() {
   QSettings settings;
   QString settingsGroup = "CustomInterfaces/IndirectAnalysis/";
-  QString saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+  QString saveDir = QString::fromStdString(
+      Mantid::Kernel::ConfigService::Instance().getString(
+          "defaultsave.directory"));
 
   settings.beginGroup(settingsGroup + "ProcessedFiles");
   settings.setValue("last_directory", saveDir);
 
-	std::map<unsigned int, IndirectToolsTab*>::iterator iter;
-	for (iter = m_tabs.begin(); iter != m_tabs.end(); ++iter)
-	{
-  	iter->second->loadSettings(settings);
+  std::map<unsigned int, IndirectToolsTab *>::iterator iter;
+  for (iter = m_tabs.begin(); iter != m_tabs.end(); ++iter) {
+    iter->second->loadSettings(settings);
   }
 
   settings.endGroup();
 }
 
-
 /**
  * Slot to run the underlying algorithm code based on the currently selected
  * tab.
@@ -111,9 +107,8 @@ void IndirectTools::loadSettings()
  * This method checks the tabs validate method is passing before calling
  * the run method.
  */
-void IndirectTools::runClicked()
-{
-	int tabIndex = m_uiForm.IndirectToolsTabs->currentIndex();
+void IndirectTools::runClicked() {
+  int tabIndex = m_uiForm.IndirectToolsTabs->currentIndex();
   m_tabs[tabIndex]->runTab();
 }
 
@@ -121,18 +116,18 @@ void IndirectTools::runClicked()
  * Slot to open a new browser window and navigate to the help page
  * on the wiki for the currently selected tab.
  */
-void IndirectTools::helpClicked()
-{
-  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Indirect_Tools"));
+void IndirectTools::helpClicked() {
+  MantidQt::API::HelpWindow::showCustomInterface(NULL,
+                                                 QString("Indirect_Tools"));
 }
 
 /**
  * Slot to show the manage user dicrectories dialog when the user clicks
  * the button on the interface.
  */
-void IndirectTools::manageUserDirectories()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+void IndirectTools::manageUserDirectories() {
+  MantidQt::API::ManageUserDirectories *ad =
+      new MantidQt::API::ManageUserDirectories(this);
   ad->show();
   ad->setFocus();
 }
@@ -143,11 +138,8 @@ void IndirectTools::manageUserDirectories()
  *
  * @param message :: The message to display in the message box
  */
-void IndirectTools::showMessageBox(const QString& message)
-{
+void IndirectTools::showMessageBox(const QString &message) {
   showInformationBox(message);
 }
 
-IndirectTools::~IndirectTools()
-{
-}
+IndirectTools::~IndirectTools() {}
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectToolsTab.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectToolsTab.cpp
index f50ce19ac19f5263557cc300271c6871e7f2b9a0..fa23bfe46616247e048136f10b516bbd19177057 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectToolsTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectToolsTab.cpp
@@ -1,34 +1,27 @@
 #include "MantidQtAPI/UserSubWindow.h"
 #include "MantidQtCustomInterfaces/Indirect/IndirectToolsTab.h"
 
-namespace MantidQt
-{
-	namespace CustomInterfaces
-	{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-    //----------------------------------------------------------------------------------------------
-    /** Constructor
-     */
-    IndirectToolsTab::IndirectToolsTab(QWidget * parent) : IndirectTab(parent)
-    {
-    }
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IndirectToolsTab::IndirectToolsTab(QWidget *parent) : IndirectTab(parent) {}
 
-    //----------------------------------------------------------------------------------------------
-    /** Destructor
-     */
-    IndirectToolsTab::~IndirectToolsTab()
-    {
-    }
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IndirectToolsTab::~IndirectToolsTab() {}
 
-    /**
-     * Emits a signal to run a python script using the method in the parent
-     * UserSubWindow
-     *
-     * @param pyInput :: A string of python code to execute
-     */
-    void IndirectToolsTab::runPythonScript(const QString& pyInput)
-    {
-      emit executePythonScript(pyInput, false);
-    }
-  }
+/**
+ * Emits a signal to run a python script using the method in the parent
+ * UserSubWindow
+ *
+ * @param pyInput :: A string of python code to execute
+ */
+void IndirectToolsTab::runPythonScript(const QString &pyInput) {
+  emit executePythonScript(pyInput, false);
+}
+}
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp
index e65ff61d9205be15f9b99ca5716e70225126b627..651af67c277a406d04ce6a62f54db02961c471a2 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp
@@ -4,135 +4,134 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  IndirectTransmission::IndirectTransmission(IndirectDataReduction * idrUI, QWidget * parent) :
-    IndirectDataReductionTab(idrUI, parent)
-  {
-    m_uiForm.setupUi(parent);
-
-    connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(instrumentSet()));
-
-    // Update the preview plot when the algorithm is complete
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(transAlgDone(bool)));
-    connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(QString)), this, SLOT(dataLoaded()));
-    connect(m_uiForm.dsCanInput, SIGNAL(dataReady(QString)), this, SLOT(dataLoaded()));
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  IndirectTransmission::~IndirectTransmission()
-  {
-  }
-
-  void IndirectTransmission::setup()
-  {
-  }
-
-  void IndirectTransmission::run()
-  {
-    QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    QString canWsName = m_uiForm.dsCanInput->getCurrentDataName();
-    QString outWsName = sampleWsName + "_trans";
-
-    IAlgorithm_sptr transAlg = AlgorithmManager::Instance().create("IndirectTransmissionMonitor", -1);
-    transAlg->initialize();
-
-    transAlg->setProperty("SampleWorkspace", sampleWsName.toStdString());
-    transAlg->setProperty("CanWorkspace", canWsName.toStdString());
-    transAlg->setProperty("OutputWorkspace", outWsName.toStdString());
-
-    m_batchAlgoRunner->addAlgorithm(transAlg);
-
-    if(m_uiForm.ckSave->isChecked())
-      addSaveWorkspaceToQueue(outWsName);
-
-    m_batchAlgoRunner->executeBatchAsync();
-  }
-
-  bool IndirectTransmission::validate()
-  {
-    // Check if we have an appropriate instrument
-    QString currentInst = getInstrumentConfiguration()->getInstrumentName();
-    if(currentInst != "IRIS" && currentInst != "OSIRIS")
-      return false;
-
-    // Check for an invalid sample input
-    if(!m_uiForm.dsSampleInput->isValid())
-      return false;
-
-    // Check for an invalid can input
-    if(!m_uiForm.dsCanInput->isValid())
-      return false;
-
-    return true;
-  }
-
-  void IndirectTransmission::dataLoaded()
-  {
-    if(validate())
-      previewPlot();
-  }
-
-  void IndirectTransmission::previewPlot()
-  {
-    QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    QString canWsName = m_uiForm.dsCanInput->getCurrentDataName();
-    QString outWsName = sampleWsName + "_trans";
-
-    IAlgorithm_sptr transAlg = AlgorithmManager::Instance().create("IndirectTransmissionMonitor", -1);
-    transAlg->initialize();
-
-    transAlg->setProperty("SampleWorkspace", sampleWsName.toStdString());
-    transAlg->setProperty("CanWorkspace", canWsName.toStdString());
-    transAlg->setProperty("OutputWorkspace", outWsName.toStdString());
-
-    // Set the workspace name for Python script export
-    m_pythonExportWsName = sampleWsName.toStdString() + "_Trans";
-
-    runAlgorithm(transAlg);
-  }
-
-  void IndirectTransmission::transAlgDone(bool error)
-  {
-    if(error)
-      return;
-
-    QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    QString outWsName = sampleWsName + "_trans";
-
-    if(m_uiForm.ckPlot->isChecked())
-      plotSpectrum(outWsName);
-
-    WorkspaceGroup_sptr resultWsGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(outWsName.toStdString());
-    std::vector<std::string> resultWsNames = resultWsGroup->getNames();
-
-    if(resultWsNames.size() < 3)
-      return;
-
-    // Do plotting
-    m_uiForm.ppPlot->clear();
-    m_uiForm.ppPlot->addSpectrum("Can", QString::fromStdString(resultWsNames[0]), 0, Qt::red);
-    m_uiForm.ppPlot->addSpectrum("Sample", QString::fromStdString(resultWsNames[1]), 0, Qt::black);
-    m_uiForm.ppPlot->addSpectrum("Transmission", QString::fromStdString(resultWsNames[2]), 0, Qt::green);
-    m_uiForm.ppPlot->resizeX();
-  }
-
-  void IndirectTransmission::instrumentSet()
-  {
-    QMap<QString, QString> instDetails = getInstrumentDetails();
-
-    // Set the search instrument for runs
-    m_uiForm.dsSampleInput->setInstrumentOverride(instDetails["instrument"]);
-    m_uiForm.dsCanInput->setInstrumentOverride(instDetails["instrument"]);
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+IndirectTransmission::IndirectTransmission(IndirectDataReduction *idrUI,
+                                           QWidget *parent)
+    : IndirectDataReductionTab(idrUI, parent) {
+  m_uiForm.setupUi(parent);
+
+  connect(this, SIGNAL(newInstrumentConfiguration()), this,
+          SLOT(instrumentSet()));
+
+  // Update the preview plot when the algorithm is complete
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(transAlgDone(bool)));
+  connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(QString)), this,
+          SLOT(dataLoaded()));
+  connect(m_uiForm.dsCanInput, SIGNAL(dataReady(QString)), this,
+          SLOT(dataLoaded()));
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+IndirectTransmission::~IndirectTransmission() {}
+
+void IndirectTransmission::setup() {}
+
+void IndirectTransmission::run() {
+  QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  QString canWsName = m_uiForm.dsCanInput->getCurrentDataName();
+  QString outWsName = sampleWsName + "_trans";
+
+  IAlgorithm_sptr transAlg =
+      AlgorithmManager::Instance().create("IndirectTransmissionMonitor", -1);
+  transAlg->initialize();
+
+  transAlg->setProperty("SampleWorkspace", sampleWsName.toStdString());
+  transAlg->setProperty("CanWorkspace", canWsName.toStdString());
+  transAlg->setProperty("OutputWorkspace", outWsName.toStdString());
+
+  m_batchAlgoRunner->addAlgorithm(transAlg);
+
+  if (m_uiForm.ckSave->isChecked())
+    addSaveWorkspaceToQueue(outWsName);
+
+  m_batchAlgoRunner->executeBatchAsync();
+}
+
+bool IndirectTransmission::validate() {
+  // Check if we have an appropriate instrument
+  QString currentInst = getInstrumentConfiguration()->getInstrumentName();
+  if (currentInst != "IRIS" && currentInst != "OSIRIS")
+    return false;
+
+  // Check for an invalid sample input
+  if (!m_uiForm.dsSampleInput->isValid())
+    return false;
+
+  // Check for an invalid can input
+  if (!m_uiForm.dsCanInput->isValid())
+    return false;
+
+  return true;
+}
+
+void IndirectTransmission::dataLoaded() {
+  if (validate())
+    previewPlot();
+}
+
+void IndirectTransmission::previewPlot() {
+  QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  QString canWsName = m_uiForm.dsCanInput->getCurrentDataName();
+  QString outWsName = sampleWsName + "_trans";
+
+  IAlgorithm_sptr transAlg =
+      AlgorithmManager::Instance().create("IndirectTransmissionMonitor", -1);
+  transAlg->initialize();
+
+  transAlg->setProperty("SampleWorkspace", sampleWsName.toStdString());
+  transAlg->setProperty("CanWorkspace", canWsName.toStdString());
+  transAlg->setProperty("OutputWorkspace", outWsName.toStdString());
+
+  // Set the workspace name for Python script export
+  m_pythonExportWsName = sampleWsName.toStdString() + "_Trans";
+
+  runAlgorithm(transAlg);
+}
+
+void IndirectTransmission::transAlgDone(bool error) {
+  if (error)
+    return;
+
+  QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  QString outWsName = sampleWsName + "_trans";
+
+  if (m_uiForm.ckPlot->isChecked())
+    plotSpectrum(outWsName);
+
+  WorkspaceGroup_sptr resultWsGroup =
+      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
+          outWsName.toStdString());
+  std::vector<std::string> resultWsNames = resultWsGroup->getNames();
+
+  if (resultWsNames.size() < 3)
+    return;
+
+  // Do plotting
+  m_uiForm.ppPlot->clear();
+  m_uiForm.ppPlot->addSpectrum("Can", QString::fromStdString(resultWsNames[0]),
+                               0, Qt::red);
+  m_uiForm.ppPlot->addSpectrum(
+      "Sample", QString::fromStdString(resultWsNames[1]), 0, Qt::black);
+  m_uiForm.ppPlot->addSpectrum(
+      "Transmission", QString::fromStdString(resultWsNames[2]), 0, Qt::green);
+  m_uiForm.ppPlot->resizeX();
+}
+
+void IndirectTransmission::instrumentSet() {
+  QMap<QString, QString> instDetails = getInstrumentDetails();
+
+  // Set the search instrument for runs
+  m_uiForm.dsSampleInput->setInstrumentOverride(instDetails["instrument"]);
+  m_uiForm.dsCanInput->setInstrumentOverride(instDetails["instrument"]);
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp
index 45104a907465c190f00176fb5feb83016bbe9402..afd13961a70f7c3c718a3300d65830a4852ca5ba 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp
@@ -10,119 +10,117 @@
 using namespace Mantid::API;
 using namespace Mantid::Geometry;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("IndirectTransmissionCalc");
+namespace {
+Mantid::Kernel::Logger g_log("IndirectTransmissionCalc");
 }
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    IndirectTransmissionCalc::IndirectTransmissionCalc(QWidget * parent) :
-      IndirectToolsTab(parent)
-    {
-      m_uiForm.setupUi(parent);
-
-      connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));
-    }
-
-
-    /*
-     * Run any tab setup code.
-     */
-    void IndirectTransmissionCalc::setup()
-    {
-      QRegExp chemicalFormulaRegex("[A-Za-z0-9\\-\\(\\)]*");
-      QValidator *chemicalFormulaValidator = new QRegExpValidator(chemicalFormulaRegex, this);
-      m_uiForm.leChemicalFormula->setValidator(chemicalFormulaValidator);
-    }
-
-
-    /**
-     * Validate the form to check the algorithm can be run.
-     *
-     * @return Whether the form was valid
-     */
-    bool IndirectTransmissionCalc::validate()
-    {
-      UserInputValidator uiv;
-
-      uiv.checkFieldIsNotEmpty("Chemical Formula", m_uiForm.leChemicalFormula, m_uiForm.valChemicalFormula);
-
-      QString error = uiv.generateErrorMessage();
-      showMessageBox(error);
-
-      return error.isEmpty();
-    }
-
-
-    /**
-     * Run the tab, invoking the IndirectTransmission algorithm.
-     */
-    void IndirectTransmissionCalc::run()
-    {
-      std::string instrumentName = m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
-      std::string outWsName = instrumentName + "_transmission";
-
-      IAlgorithm_sptr transAlg = AlgorithmManager::Instance().create("IndirectTransmission");
-      transAlg->initialize();
-      transAlg->setProperty("Instrument", instrumentName);
-      transAlg->setProperty("Analyser", m_uiForm.iicInstrumentConfiguration->getAnalyserName().toStdString());
-      transAlg->setProperty("Reflection", m_uiForm.iicInstrumentConfiguration->getReflectionName().toStdString());
-      transAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString());
-      transAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value());
-      transAlg->setProperty("Thickness", m_uiForm.spThickness->value());
-      transAlg->setProperty("OutputWorkspace", outWsName);
-
-      // Run the algorithm async
-      runAlgorithm(transAlg);
-    }
-
-
-    /**
-     * Handles completion of the IndirectTransmission algorithm.
-     *
-     * @param error If the algorithm encountered an error during execution
-     */
-    void IndirectTransmissionCalc::algorithmComplete(bool error)
-    {
-      if(error)
-      {
-        emit showMessageBox("Failed to execute IndirectTransmission algorithm.\nSee Results Log for details.");
-        return;
-      }
-
-      std::string instrumentName = m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
-      std::string outWsName = instrumentName + "_transmission";
-
-      ITableWorkspace_const_sptr resultTable = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(outWsName);
-      Column_const_sptr propertyNames = resultTable->getColumn("Name");
-      Column_const_sptr propertyValues = resultTable->getColumn("Value");
-
-      // Update the table in the GUI
-      m_uiForm.tvResultsTable->clear();
-
-      for(size_t i = 0; i < resultTable->rowCount(); i++)
-      {
-        QTreeWidgetItem *item = new QTreeWidgetItem();
-        item->setText(0, QString::fromStdString(propertyNames->cell<std::string>(i)));
-        item->setText(1, QString::number(propertyValues->cell<double>(i)));
-        m_uiForm.tvResultsTable->addTopLevelItem(item);
-      }
-    }
-
-
-    /**
-     * Set the file browser to use the default save directory
-     * when browsing for input files.
-     *
-     * @param settings The settings to loading into the interface
-     */
-    void IndirectTransmissionCalc::loadSettings(const QSettings& settings)
-    {
-      UNUSED_ARG(settings);
-    }
-
-  } // namespace CustomInterfaces
+namespace MantidQt {
+namespace CustomInterfaces {
+IndirectTransmissionCalc::IndirectTransmissionCalc(QWidget *parent)
+    : IndirectToolsTab(parent) {
+  m_uiForm.setupUi(parent);
+
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
+}
+
+/*
+ * Run any tab setup code.
+ */
+void IndirectTransmissionCalc::setup() {
+  QRegExp chemicalFormulaRegex("[A-Za-z0-9\\-\\(\\)]*");
+  QValidator *chemicalFormulaValidator =
+      new QRegExpValidator(chemicalFormulaRegex, this);
+  m_uiForm.leChemicalFormula->setValidator(chemicalFormulaValidator);
+}
+
+/**
+ * Validate the form to check the algorithm can be run.
+ *
+ * @return Whether the form was valid
+ */
+bool IndirectTransmissionCalc::validate() {
+  UserInputValidator uiv;
+
+  uiv.checkFieldIsNotEmpty("Chemical Formula", m_uiForm.leChemicalFormula,
+                           m_uiForm.valChemicalFormula);
+
+  QString error = uiv.generateErrorMessage();
+  showMessageBox(error);
+
+  return error.isEmpty();
+}
+
+/**
+ * Run the tab, invoking the IndirectTransmission algorithm.
+ */
+void IndirectTransmissionCalc::run() {
+  std::string instrumentName =
+      m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
+  std::string outWsName = instrumentName + "_transmission";
+
+  IAlgorithm_sptr transAlg =
+      AlgorithmManager::Instance().create("IndirectTransmission");
+  transAlg->initialize();
+  transAlg->setProperty("Instrument", instrumentName);
+  transAlg->setProperty(
+      "Analyser",
+      m_uiForm.iicInstrumentConfiguration->getAnalyserName().toStdString());
+  transAlg->setProperty(
+      "Reflection",
+      m_uiForm.iicInstrumentConfiguration->getReflectionName().toStdString());
+  transAlg->setProperty("ChemicalFormula",
+                        m_uiForm.leChemicalFormula->text().toStdString());
+  transAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value());
+  transAlg->setProperty("Thickness", m_uiForm.spThickness->value());
+  transAlg->setProperty("OutputWorkspace", outWsName);
+
+  // Run the algorithm async
+  runAlgorithm(transAlg);
+}
+
+/**
+ * Handles completion of the IndirectTransmission algorithm.
+ *
+ * @param error If the algorithm encountered an error during execution
+ */
+void IndirectTransmissionCalc::algorithmComplete(bool error) {
+  if (error) {
+    emit showMessageBox("Failed to execute IndirectTransmission "
+                        "algorithm.\nSee Results Log for details.");
+    return;
+  }
+
+  std::string instrumentName =
+      m_uiForm.iicInstrumentConfiguration->getInstrumentName().toStdString();
+  std::string outWsName = instrumentName + "_transmission";
+
+  ITableWorkspace_const_sptr resultTable =
+      AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(outWsName);
+  Column_const_sptr propertyNames = resultTable->getColumn("Name");
+  Column_const_sptr propertyValues = resultTable->getColumn("Value");
+
+  // Update the table in the GUI
+  m_uiForm.tvResultsTable->clear();
+
+  for (size_t i = 0; i < resultTable->rowCount(); i++) {
+    QTreeWidgetItem *item = new QTreeWidgetItem();
+    item->setText(0,
+                  QString::fromStdString(propertyNames->cell<std::string>(i)));
+    item->setText(1, QString::number(propertyValues->cell<double>(i)));
+    m_uiForm.tvResultsTable->addTopLevelItem(item);
+  }
+}
+
+/**
+ * Set the file browser to use the default save directory
+ * when browsing for input files.
+ *
+ * @param settings The settings to loading into the interface
+ */
+void IndirectTransmissionCalc::loadSettings(const QSettings &settings) {
+  UNUSED_ARG(settings);
+}
+
+} // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp b/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp
index 882fc57cb701bb78442707eb8c93d10ca9c5023d..6da59b65c98cff517a7091dbf1b65cd195ee97e6 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp
@@ -298,7 +298,7 @@ void Iqt::calculateBinning() {
   int resolutionBins = propsTable->getColumn("ResolutionBins")->cell<int>(0);
 
   disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
-	  SLOT(updatePropertyValues(QtProperty *, double)));
+             SLOT(updatePropertyValues(QtProperty *, double)));
 
   // Update data in property editor
   m_dblManager->setValue(m_properties["EWidth"], energyWidth);
diff --git a/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp b/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
index eed372e9be4d375136b3516cf25cfafbfd86da33..1d21621ed6133368868ddd45a450f3aa4ccaaa55 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/IqtFit.cpp
@@ -546,7 +546,7 @@ void IqtFit::typeSelection(int index) {
  * Update the current plot option selected
  */
 void IqtFit::updateCurrentPlotOption(QString newOption) {
-	m_plotOption = newOption.toStdString();
+  m_plotOption = newOption.toStdString();
 }
 
 void IqtFit::updatePlot() {
diff --git a/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp b/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp
index 11d6f8f9d82ca5cefd06a2aa6159df8ccc096010..af37affb24d501b681e0c8c0e118f59bf9251e40 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp
@@ -11,295 +11,291 @@
 
 using namespace Mantid::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("MSDFit");
+namespace {
+Mantid::Kernel::Logger g_log("MSDFit");
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace IDA
-{
-  MSDFit::MSDFit(QWidget * parent) : IndirectDataAnalysisTab(parent),
-    m_currentWsName(""), m_msdTree(NULL)
-  {
-    m_uiForm.setupUi(parent);
-  }
-
-  void MSDFit::setup()
-  {
-    // Tree Browser
-    m_msdTree = new QtTreePropertyBrowser();
-    m_uiForm.properties->addWidget(m_msdTree);
-
-    m_msdTree->setFactoryForManager(m_dblManager, m_dblEdFac);
-
-    m_properties["Start"] = m_dblManager->addProperty("StartX");
-    m_dblManager->setDecimals(m_properties["Start"], NUM_DECIMALS);
-    m_properties["End"] = m_dblManager->addProperty("EndX");
-    m_dblManager->setDecimals(m_properties["End"], NUM_DECIMALS);
-
-    m_msdTree->addProperty(m_properties["Start"]);
-    m_msdTree->addProperty(m_properties["End"]);
-
-    auto fitRangeSelector = m_uiForm.ppPlot->addRangeSelector("MSDRange");
-
-    connect(fitRangeSelector, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double)));
-    connect(fitRangeSelector, SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double)));
-    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateRS(QtProperty*, double)));
-
-    connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString&)), this, SLOT(newDataLoaded(const QString&)));
-    connect(m_uiForm.pbSingleFit, SIGNAL(clicked()), this, SLOT(singleFit()));
-    connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, SLOT(plotInput()));
-    connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, SLOT(plotFit()));
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace IDA {
+MSDFit::MSDFit(QWidget *parent)
+    : IndirectDataAnalysisTab(parent), m_currentWsName(""), m_msdTree(NULL) {
+  m_uiForm.setupUi(parent);
+}
 
-    connect(m_uiForm.spSpectraMin, SIGNAL(valueChanged(int)), this, SLOT(specMinChanged(int)));
-    connect(m_uiForm.spSpectraMax, SIGNAL(valueChanged(int)), this, SLOT(specMaxChanged(int)));
+void MSDFit::setup() {
+  // Tree Browser
+  m_msdTree = new QtTreePropertyBrowser();
+  m_uiForm.properties->addWidget(m_msdTree);
+
+  m_msdTree->setFactoryForManager(m_dblManager, m_dblEdFac);
+
+  m_properties["Start"] = m_dblManager->addProperty("StartX");
+  m_dblManager->setDecimals(m_properties["Start"], NUM_DECIMALS);
+  m_properties["End"] = m_dblManager->addProperty("EndX");
+  m_dblManager->setDecimals(m_properties["End"], NUM_DECIMALS);
+
+  m_msdTree->addProperty(m_properties["Start"]);
+  m_msdTree->addProperty(m_properties["End"]);
+
+  auto fitRangeSelector = m_uiForm.ppPlot->addRangeSelector("MSDRange");
+
+  connect(fitRangeSelector, SIGNAL(minValueChanged(double)), this,
+          SLOT(minChanged(double)));
+  connect(fitRangeSelector, SIGNAL(maxValueChanged(double)), this,
+          SLOT(maxChanged(double)));
+  connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
+          SLOT(updateRS(QtProperty *, double)));
+
+  connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString &)), this,
+          SLOT(newDataLoaded(const QString &)));
+  connect(m_uiForm.pbSingleFit, SIGNAL(clicked()), this, SLOT(singleFit()));
+  connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this,
+          SLOT(plotInput()));
+  connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this,
+          SLOT(plotFit()));
+
+  connect(m_uiForm.spSpectraMin, SIGNAL(valueChanged(int)), this,
+          SLOT(specMinChanged(int)));
+  connect(m_uiForm.spSpectraMax, SIGNAL(valueChanged(int)), this,
+          SLOT(specMaxChanged(int)));
+
+  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
+          SLOT(plotFit()));
+}
 
-    connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(plotFit()));
+void MSDFit::run() {
+  if (!validate())
+    return;
+
+  // Set the result workspace for Python script export
+  QString dataName = m_uiForm.dsSampleInput->getCurrentDataName();
+  m_pythonExportWsName =
+      dataName.left(dataName.lastIndexOf("_")).toStdString() + "_msd";
+
+  QString wsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  double xStart = m_dblManager->value(m_properties["Start"]);
+  double xEnd = m_dblManager->value(m_properties["End"]);
+  long specMin = m_uiForm.spSpectraMin->value();
+  long specMax = m_uiForm.spSpectraMax->value();
+  bool plot = m_uiForm.ckPlot->isChecked();
+  bool save = m_uiForm.ckSave->isChecked();
+
+  IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit");
+  msdAlg->initialize();
+  msdAlg->setProperty("InputWorkspace", wsName.toStdString());
+  msdAlg->setProperty("XStart", xStart);
+  msdAlg->setProperty("XEnd", xEnd);
+  msdAlg->setProperty("SpecMin", specMin);
+  msdAlg->setProperty("SpecMax", specMax);
+  msdAlg->setProperty("Plot", plot);
+  msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName);
+
+  m_batchAlgoRunner->addAlgorithm(msdAlg);
+
+  // Handle saving results
+  if (save) {
+    API::BatchAlgorithmRunner::AlgorithmRuntimeProps saveInputProps;
+    saveInputProps["InputWorkspace"] = m_pythonExportWsName;
+
+    IAlgorithm_sptr saveAlg =
+        AlgorithmManager::Instance().create("SaveNexusProcessed");
+    saveAlg->initialize();
+    saveAlg->setProperty("Filename", m_pythonExportWsName + ".nxs");
+
+    m_batchAlgoRunner->addAlgorithm(saveAlg, saveInputProps);
   }
 
-  void MSDFit::run()
-  {
-    if(!validate())
-      return;
-
-    // Set the result workspace for Python script export
-    QString dataName = m_uiForm.dsSampleInput->getCurrentDataName();
-    m_pythonExportWsName = dataName.left(dataName.lastIndexOf("_")).toStdString() + "_msd";
-
-    QString wsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    double xStart = m_dblManager->value(m_properties["Start"]);
-    double xEnd = m_dblManager->value(m_properties["End"]);
-    long specMin = m_uiForm.spSpectraMin->value();
-    long specMax = m_uiForm.spSpectraMax->value();
-    bool plot = m_uiForm.ckPlot->isChecked();
-    bool save = m_uiForm.ckSave->isChecked();
-
-    IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit");
-    msdAlg->initialize();
-    msdAlg->setProperty("InputWorkspace", wsName.toStdString());
-    msdAlg->setProperty("XStart", xStart);
-    msdAlg->setProperty("XEnd", xEnd);
-    msdAlg->setProperty("SpecMin", specMin);
-    msdAlg->setProperty("SpecMax", specMax);
-    msdAlg->setProperty("Plot", plot);
-    msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName);
-
-    m_batchAlgoRunner->addAlgorithm(msdAlg);
-
-    // Handle saving results
-    if(save)
-    {
-      API::BatchAlgorithmRunner::AlgorithmRuntimeProps saveInputProps;
-      saveInputProps["InputWorkspace"] = m_pythonExportWsName;
-
-      IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexusProcessed");
-      saveAlg->initialize();
-      saveAlg->setProperty("Filename", m_pythonExportWsName + ".nxs");
-
-      m_batchAlgoRunner->addAlgorithm(saveAlg, saveInputProps);
-    }
-
-    m_batchAlgoRunner->executeBatchAsync();
-  }
+  m_batchAlgoRunner->executeBatchAsync();
+}
 
-  void MSDFit::singleFit()
-  {
-    if(!validate())
-      return;
+void MSDFit::singleFit() {
+  if (!validate())
+    return;
 
-    // Set the result workspace for Python script export
-    QString dataName = m_uiForm.dsSampleInput->getCurrentDataName();
-    m_pythonExportWsName = dataName.left(dataName.lastIndexOf("_")).toStdString() + "_msd";
+  // Set the result workspace for Python script export
+  QString dataName = m_uiForm.dsSampleInput->getCurrentDataName();
+  m_pythonExportWsName =
+      dataName.left(dataName.lastIndexOf("_")).toStdString() + "_msd";
 
-    QString wsName = m_uiForm.dsSampleInput->getCurrentDataName();
-    double xStart = m_dblManager->value(m_properties["Start"]);
-    double xEnd = m_dblManager->value(m_properties["End"]);
-    long fitSpec = m_uiForm.spPlotSpectrum->value();
+  QString wsName = m_uiForm.dsSampleInput->getCurrentDataName();
+  double xStart = m_dblManager->value(m_properties["Start"]);
+  double xEnd = m_dblManager->value(m_properties["End"]);
+  long fitSpec = m_uiForm.spPlotSpectrum->value();
 
-    IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit");
-    msdAlg->initialize();
-    msdAlg->setProperty("InputWorkspace", wsName.toStdString());
-    msdAlg->setProperty("XStart", xStart);
-    msdAlg->setProperty("XEnd", xEnd);
-    msdAlg->setProperty("SpecMin", fitSpec);
-    msdAlg->setProperty("SpecMax", fitSpec);
-    msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName);
+  IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit");
+  msdAlg->initialize();
+  msdAlg->setProperty("InputWorkspace", wsName.toStdString());
+  msdAlg->setProperty("XStart", xStart);
+  msdAlg->setProperty("XEnd", xEnd);
+  msdAlg->setProperty("SpecMin", fitSpec);
+  msdAlg->setProperty("SpecMax", fitSpec);
+  msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName);
 
-    m_batchAlgoRunner->addAlgorithm(msdAlg);
+  m_batchAlgoRunner->addAlgorithm(msdAlg);
 
-    m_batchAlgoRunner->executeBatchAsync();
-  }
+  m_batchAlgoRunner->executeBatchAsync();
+}
 
-  bool MSDFit::validate()
-  {
-    UserInputValidator uiv;
+bool MSDFit::validate() {
+  UserInputValidator uiv;
 
-    uiv.checkDataSelectorIsValid("Sample input", m_uiForm.dsSampleInput);
+  uiv.checkDataSelectorIsValid("Sample input", m_uiForm.dsSampleInput);
 
-    auto range = std::make_pair(m_dblManager->value(m_properties["Start"]), m_dblManager->value(m_properties["End"]));
-    uiv.checkValidRange("a range", range);
+  auto range = std::make_pair(m_dblManager->value(m_properties["Start"]),
+                              m_dblManager->value(m_properties["End"]));
+  uiv.checkValidRange("a range", range);
 
-    int specMin = m_uiForm.spSpectraMin->value();
-    int specMax = m_uiForm.spSpectraMax->value();
-    auto specRange = std::make_pair(specMin, specMax+1);
-    uiv.checkValidRange("spectrum range", specRange);
+  int specMin = m_uiForm.spSpectraMin->value();
+  int specMax = m_uiForm.spSpectraMax->value();
+  auto specRange = std::make_pair(specMin, specMax + 1);
+  uiv.checkValidRange("spectrum range", specRange);
 
-    QString errors = uiv.generateErrorMessage();
-    showMessageBox(errors);
+  QString errors = uiv.generateErrorMessage();
+  showMessageBox(errors);
 
-    return errors.isEmpty();
-  }
+  return errors.isEmpty();
+}
 
-  void MSDFit::loadSettings(const QSettings & settings)
-  {
-    m_uiForm.dsSampleInput->readSettings(settings.group());
-  }
+void MSDFit::loadSettings(const QSettings &settings) {
+  m_uiForm.dsSampleInput->readSettings(settings.group());
+}
 
-  /**
-   * Plots fitted data on the mini plot.
-   *
-   * @param wsName Name of fit _Workspaces workspace group (defaults to
-   *               Python export WS name + _Workspaces)
-   * @param specNo Spectrum number relating to input workspace to plot fit
-   *               for (defaults to value of preview spectrum index)
-   */
-  void MSDFit::plotFit(QString wsName, int specNo)
-  {
-    if(wsName.isEmpty())
-      wsName = QString::fromStdString(m_pythonExportWsName) + "_Workspaces";
-
-    if(specNo == -1)
-      specNo = m_uiForm.spPlotSpectrum->value();
-
-    if(Mantid::API::AnalysisDataService::Instance().doesExist(wsName.toStdString()))
-    {
-      // Remove the old fit
-      m_uiForm.ppPlot->removeSpectrum("Fit");
-
-      // Get the workspace
-      auto groupWs = AnalysisDataService::Instance().retrieveWS<const WorkspaceGroup>(wsName.toStdString());
-      auto groupWsNames = groupWs->getNames();
-
-      // Find the correct fit workspace and plot it
-      std::stringstream searchString;
-      searchString << "_" << specNo << "_Workspace";
-      for(auto it = groupWsNames.begin(); it != groupWsNames.end(); ++it)
-      {
-        std::string wsName = *it;
-        if(wsName.find(searchString.str()) != std::string::npos)
-        {
-          // Get the fit workspace
-          auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName);
-          // Plot the new fit
-          m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red);
-          // Nothing else to do
-          return;
-        }
+/**
+ * Plots fitted data on the mini plot.
+ *
+ * @param wsName Name of fit _Workspaces workspace group (defaults to
+ *               Python export WS name + _Workspaces)
+ * @param specNo Spectrum number relating to input workspace to plot fit
+ *               for (defaults to value of preview spectrum index)
+ */
+void MSDFit::plotFit(QString wsName, int specNo) {
+  if (wsName.isEmpty())
+    wsName = QString::fromStdString(m_pythonExportWsName) + "_Workspaces";
+
+  if (specNo == -1)
+    specNo = m_uiForm.spPlotSpectrum->value();
+
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(
+          wsName.toStdString())) {
+    // Remove the old fit
+    m_uiForm.ppPlot->removeSpectrum("Fit");
+
+    // Get the workspace
+    auto groupWs =
+        AnalysisDataService::Instance().retrieveWS<const WorkspaceGroup>(
+            wsName.toStdString());
+    auto groupWsNames = groupWs->getNames();
+
+    // Find the correct fit workspace and plot it
+    std::stringstream searchString;
+    searchString << "_" << specNo << "_Workspace";
+    for (auto it = groupWsNames.begin(); it != groupWsNames.end(); ++it) {
+      std::string wsName = *it;
+      if (wsName.find(searchString.str()) != std::string::npos) {
+        // Get the fit workspace
+        auto ws =
+            AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName);
+        // Plot the new fit
+        m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red);
+        // Nothing else to do
+        return;
       }
     }
   }
+}
 
-  /**
-   * Called when new data has been loaded by the data selector.
-   *
-   * Configures ranges for spin boxes before raw plot is done.
-   *
-   * @param wsName Name of new workspace loaded
-   */
-  void MSDFit::newDataLoaded(const QString wsName)
-  {
-    auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<const MatrixWorkspace>(wsName.toStdString());
-    int maxWsIndex = static_cast<int>(ws->getNumberHistograms()) - 1;
-
-    m_uiForm.spPlotSpectrum->setMaximum(maxWsIndex);
-    m_uiForm.spPlotSpectrum->setMinimum(0);
-    m_uiForm.spPlotSpectrum->setValue(0);
-
-    m_uiForm.spSpectraMin->setMaximum(maxWsIndex);
-    m_uiForm.spSpectraMin->setMinimum(0);
-
-    m_uiForm.spSpectraMax->setMaximum(maxWsIndex);
-    m_uiForm.spSpectraMax->setMinimum(0);
-    m_uiForm.spSpectraMax->setValue(maxWsIndex);
-
-    plotInput();
-  }
-
-  void MSDFit::plotInput()
-  {
-    m_uiForm.ppPlot->clear();
+/**
+ * Called when new data has been loaded by the data selector.
+ *
+ * Configures ranges for spin boxes before raw plot is done.
+ *
+ * @param wsName Name of new workspace loaded
+ */
+void MSDFit::newDataLoaded(const QString wsName) {
+  auto ws = Mantid::API::AnalysisDataService::Instance()
+                .retrieveWS<const MatrixWorkspace>(wsName.toStdString());
+  int maxWsIndex = static_cast<int>(ws->getNumberHistograms()) - 1;
+
+  m_uiForm.spPlotSpectrum->setMaximum(maxWsIndex);
+  m_uiForm.spPlotSpectrum->setMinimum(0);
+  m_uiForm.spPlotSpectrum->setValue(0);
+
+  m_uiForm.spSpectraMin->setMaximum(maxWsIndex);
+  m_uiForm.spSpectraMin->setMinimum(0);
+
+  m_uiForm.spSpectraMax->setMaximum(maxWsIndex);
+  m_uiForm.spSpectraMax->setMinimum(0);
+  m_uiForm.spSpectraMax->setValue(maxWsIndex);
+
+  plotInput();
+}
 
-    QString wsname = m_uiForm.dsSampleInput->getCurrentDataName();
+void MSDFit::plotInput() {
+  m_uiForm.ppPlot->clear();
 
-    if(!AnalysisDataService::Instance().doesExist(wsname.toStdString()))
-    {
-      g_log.error("No workspace loaded, cannot create preview plot.");
-      return;
-    }
+  QString wsname = m_uiForm.dsSampleInput->getCurrentDataName();
 
-    auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsname.toStdString());
+  if (!AnalysisDataService::Instance().doesExist(wsname.toStdString())) {
+    g_log.error("No workspace loaded, cannot create preview plot.");
+    return;
+  }
 
-    int wsIndex = m_uiForm.spPlotSpectrum->value();
-    m_uiForm.ppPlot->addSpectrum("Sample", ws, wsIndex);
+  auto ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+      wsname.toStdString());
 
-    try
-    {
-      QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample");
-      m_uiForm.ppPlot->getRangeSelector("MSDRange")->setRange(range.first, range.second);
-    }
-    catch(std::invalid_argument & exc)
-    {
-      showMessageBox(exc.what());
-    }
+  int wsIndex = m_uiForm.spPlotSpectrum->value();
+  m_uiForm.ppPlot->addSpectrum("Sample", ws, wsIndex);
 
-    m_currentWsName = wsname;
+  try {
+    QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample");
+    m_uiForm.ppPlot->getRangeSelector("MSDRange")
+        ->setRange(range.first, range.second);
+  } catch (std::invalid_argument &exc) {
+    showMessageBox(exc.what());
   }
 
-  /**
-   * Handles the user entering a new minimum spectrum index.
-   *
-   * Prevents the user entering an overlapping spectra range.
-   *
-   * @param value Minimum spectrum index
-   */
-  void MSDFit::specMinChanged(int value)
-  {
-    m_uiForm.spSpectraMax->setMinimum(value);
-  }
+  m_currentWsName = wsname;
+}
 
-  /**
-   * Handles the user entering a new maximum spectrum index.
-   *
-   * Prevents the user entering an overlapping spectra range.
-   *
-   * @param value Maximum spectrum index
-   */
-  void MSDFit::specMaxChanged(int value)
-  {
-    m_uiForm.spSpectraMin->setMaximum(value);
-  }
+/**
+ * Handles the user entering a new minimum spectrum index.
+ *
+ * Prevents the user entering an overlapping spectra range.
+ *
+ * @param value Minimum spectrum index
+ */
+void MSDFit::specMinChanged(int value) {
+  m_uiForm.spSpectraMax->setMinimum(value);
+}
 
-  void MSDFit::minChanged(double val)
-  {
-    m_dblManager->setValue(m_properties["Start"], val);
-  }
+/**
+ * Handles the user entering a new maximum spectrum index.
+ *
+ * Prevents the user entering an overlapping spectra range.
+ *
+ * @param value Maximum spectrum index
+ */
+void MSDFit::specMaxChanged(int value) {
+  m_uiForm.spSpectraMin->setMaximum(value);
+}
 
-  void MSDFit::maxChanged(double val)
-  {
-    m_dblManager->setValue(m_properties["End"], val);
-  }
+void MSDFit::minChanged(double val) {
+  m_dblManager->setValue(m_properties["Start"], val);
+}
 
-  void MSDFit::updateRS(QtProperty* prop, double val)
-  {
-    auto fitRangeSelector = m_uiForm.ppPlot->getRangeSelector("MSDRange");
+void MSDFit::maxChanged(double val) {
+  m_dblManager->setValue(m_properties["End"], val);
+}
 
-    if(prop == m_properties["Start"])    fitRangeSelector->setMinimum(val);
-    else if(prop == m_properties["End"]) fitRangeSelector->setMaximum(val);
-  }
+void MSDFit::updateRS(QtProperty *prop, double val) {
+  auto fitRangeSelector = m_uiForm.ppPlot->getRangeSelector("MSDRange");
+
+  if (prop == m_properties["Start"])
+    fitRangeSelector->setMinimum(val);
+  else if (prop == m_properties["End"])
+    fitRangeSelector->setMaximum(val);
+}
 
 } // namespace IDA
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp b/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp
index 1e8bf799a95dc237a26c1402c8d2104be78ca55b..b5f3f2fff9177722777d44ae6c5d2b27391212d8 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp
@@ -102,7 +102,7 @@ bool Quasi::validate() {
   const auto eMin = m_dblManager->value(m_properties["EMin"]);
   const auto eMax = m_dblManager->value(m_properties["EMax"]);
   if (eMin >= eMax)
-	  errors.append("EMin must be strictly less than EMax.\n");
+    errors.append("EMin must be strictly less than EMax.\n");
 
   // Create and show error messages
   errors.append(uiv.generateErrorMessage());
@@ -112,7 +112,7 @@ bool Quasi::validate() {
     return false;
   }
 
-  //Validate program
+  // Validate program
   QString program = m_uiForm.cbProgram->currentText();
   if (program == "Stretched Exponential") {
     QString resName = m_uiForm.dsResolution->getCurrentDataName();
diff --git a/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp b/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp
index 89484e8991e4542d12ff0cc93a5cfd4c17b40867..c287f03b9aafe1a98de0827edd918d45a037d69b 100644
--- a/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp
+++ b/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp
@@ -175,7 +175,7 @@ void Stretch::handleSampleInputReady(const QString &filename) {
                    range);
   setPlotPropertyRange(eRangeSelector, m_properties["EMin"],
                        m_properties["EMax"], range);
-  //update the current positions of the range bars
+  // update the current positions of the range bars
   eRangeSelector->setMinimum(range.first);
   eRangeSelector->setMaximum(range.second);
 }
diff --git a/MantidQt/CustomInterfaces/src/LatticePresenter.cpp b/MantidQt/CustomInterfaces/src/LatticePresenter.cpp
index ebdbe6950c60dee3c996921042681d8f4b9f9558..9d99c0ba70bca5e45f74a79a42d9789fcf9dd928 100644
--- a/MantidQt/CustomInterfaces/src/LatticePresenter.cpp
+++ b/MantidQt/CustomInterfaces/src/LatticePresenter.cpp
@@ -6,94 +6,80 @@
 #include "MantidQtCustomInterfaces/WorkspaceMementoService.h"
 #include "MantidGeometry/Crystal/OrientedLattice.h"
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /// Constructor
-    LatticePresenter::LatticePresenter(LoanedMemento& memento) : m_WsMemento(memento)
-    {
+namespace MantidQt {
+namespace CustomInterfaces {
+/// Constructor
+LatticePresenter::LatticePresenter(LoanedMemento &memento)
+    : m_WsMemento(memento) {}
 
-    }
-    
-    /// Destructor
-    LatticePresenter::~LatticePresenter()
-    {
-      //Explicitly DO NOT manage/release view as view owns presenter. Presenter is view visitor.
-    }
-    
-    /**
-    Accept the lattice view and configure it.
-    */
-    void LatticePresenter::acceptView(LatticeView* view)
-    {
-      m_view = view;
-      double a1, a2, a3, b1, b2, b3;
+/// Destructor
+LatticePresenter::~LatticePresenter() {
+  // Explicitly DO NOT manage/release view as view owns presenter. Presenter is
+  // view visitor.
+}
 
-      WorkspaceMementoService<LoanedMemento> service(m_WsMemento);
-      a1 = service.getA1();
-      a2 = service.getA2();
-      a3 = service.getA3();
-      b1 = service.getB1();
-      b2 = service.getB2();
-      b3 = service.getB3();
+/**
+Accept the lattice view and configure it.
+*/
+void LatticePresenter::acceptView(LatticeView *view) {
+  m_view = view;
+  double a1, a2, a3, b1, b2, b3;
 
-      checkInput(a1, a2, a3, b1, b2, b3);
-      m_view->initalize(a1, a2, a3, b1, b2, b3);
-    }
+  WorkspaceMementoService<LoanedMemento> service(m_WsMemento);
+  a1 = service.getA1();
+  a2 = service.getA2();
+  a3 = service.getA3();
+  b1 = service.getB1();
+  b2 = service.getB2();
+  b3 = service.getB3();
 
-    /**
-    Check that the inputs are okay. If not then pass up to view and return false.
-    @param a1: Lattice parameter indicating component in x
-    @param a2: Lattice parameter indicating component in y
-    @param a3: Lattice parameter indicating component in z
-    @param b1: Lattice parameter giving alpha angle
-    @param b2: Lattice parameter giving beta angle
-    @param b3: Lattice parameter giving gamma angle
-    @return false if invalid unit cell.
-    */
-    bool LatticePresenter::checkInput(double a1, double a2, double a3, double b1, double b2, double b3)
-    {
-      bool parametersOk = false;
-      try
-      {
-        Mantid::Geometry::OrientedLattice lattice(a1, a2, a3, b1, b2, b3);
-        parametersOk = true;
-      }
-      catch(std::range_error&)
-      {
-        m_view->indicateInvalid();
-      }
-      return parametersOk;
-    }
-    
-    /**
-    Update method, externally triggered.
-    */
-    void LatticePresenter::update()
-    {
-      double a1 = m_view->getA1();
-      double a2 = m_view->getA2();
-      double a3 = m_view->getA3();
-      double b1 = m_view->getB1();
-      double b2 = m_view->getB2();
-      double b3 = m_view->getB3();
+  checkInput(a1, a2, a3, b1, b2, b3);
+  m_view->initalize(a1, a2, a3, b1, b2, b3);
+}
+
+/**
+Check that the inputs are okay. If not then pass up to view and return false.
+@param a1: Lattice parameter indicating component in x
+@param a2: Lattice parameter indicating component in y
+@param a3: Lattice parameter indicating component in z
+@param b1: Lattice parameter giving alpha angle
+@param b2: Lattice parameter giving beta angle
+@param b3: Lattice parameter giving gamma angle
+@return false if invalid unit cell.
+*/
+bool LatticePresenter::checkInput(double a1, double a2, double a3, double b1,
+                                  double b2, double b3) {
+  bool parametersOk = false;
+  try {
+    Mantid::Geometry::OrientedLattice lattice(a1, a2, a3, b1, b2, b3);
+    parametersOk = true;
+  } catch (std::range_error &) {
+    m_view->indicateInvalid();
+  }
+  return parametersOk;
+}
+
+/**
+Update method, externally triggered.
+*/
+void LatticePresenter::update() {
+  double a1 = m_view->getA1();
+  double a2 = m_view->getA2();
+  double a3 = m_view->getA3();
+  double b1 = m_view->getB1();
+  double b2 = m_view->getB2();
+  double b3 = m_view->getB3();
 
-      WorkspaceMementoService<LoanedMemento> service(m_WsMemento);
-      service.setLatticeParameters(a1, a2, a3, b1, b2, b3);
+  WorkspaceMementoService<LoanedMemento> service(m_WsMemento);
+  service.setLatticeParameters(a1, a2, a3, b1, b2, b3);
 
-      if(checkInput(a1, a2, a3, b1, b2, b3))
-      {
-        if(m_WsMemento->hasChanged())
-        {
-          m_view->indicateModified();
-        }
-        else
-        {
-          m_view->indicateDefault();
-        }
-      }
-      
+  if (checkInput(a1, a2, a3, b1, b2, b3)) {
+    if (m_WsMemento->hasChanged()) {
+      m_view->indicateModified();
+    } else {
+      m_view->indicateDefault();
     }
   }
+}
+}
 }
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/src/MantidEV.cpp b/MantidQt/CustomInterfaces/src/MantidEV.cpp
index 0395f8910a24447752b712aec9e18c87b60fbca5..86a7ec583e882f7bac8776ac18d33aa3f1878f58 100644
--- a/MantidQt/CustomInterfaces/src/MantidEV.cpp
+++ b/MantidQt/CustomInterfaces/src/MantidEV.cpp
@@ -10,132 +10,105 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include "MantidAPI/IEventWorkspace.h"
 
+namespace MantidQt {
+namespace CustomInterfaces {
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-//Register the class with the factory
+// Register the class with the factory
 DECLARE_SUBWINDOW(MantidEV)
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-
 /**
  *  Class to call loadEvents in a separate thread.
  */
-RunLoadAndConvertToMD::RunLoadAndConvertToMD(MantidEVWorker * worker,
-                                             const std::string & file_name,
-                                             const std::string & ev_ws_name,
-                                             const std::string & md_ws_name,
-                                             const double        modQ,
-                                             const double        minQ,
-                                             const double        maxQ,
-                                             const bool          do_lorentz_corr,
-                                             const bool          load_data,
-                                             const bool          load_det_cal,
-                                             const std::string & det_cal_file,
-                                             const std::string & det_cal_file2 ) :
-  worker(worker),
-  file_name(file_name), ev_ws_name(ev_ws_name), md_ws_name(md_ws_name),
-  modQ(modQ), minQ(minQ), maxQ(maxQ), do_lorentz_corr(do_lorentz_corr),
-  load_data(load_data), load_det_cal(load_det_cal),
-  det_cal_file(det_cal_file), det_cal_file2(det_cal_file2)
-{
-}
+RunLoadAndConvertToMD::RunLoadAndConvertToMD(
+    MantidEVWorker *worker, const std::string &file_name,
+    const std::string &ev_ws_name, const std::string &md_ws_name,
+    const double modQ, const double minQ, const double maxQ,
+    const bool do_lorentz_corr, const bool load_data, const bool load_det_cal,
+    const std::string &det_cal_file, const std::string &det_cal_file2)
+    : worker(worker), file_name(file_name), ev_ws_name(ev_ws_name),
+      md_ws_name(md_ws_name), modQ(modQ), minQ(minQ), maxQ(maxQ),
+      do_lorentz_corr(do_lorentz_corr), load_data(load_data),
+      load_det_cal(load_det_cal), det_cal_file(det_cal_file),
+      det_cal_file2(det_cal_file2) {}
 
-void RunLoadAndConvertToMD::run()
-{
-  worker->loadAndConvertToMD( file_name, ev_ws_name, md_ws_name,
-                              modQ, minQ, maxQ, do_lorentz_corr, load_data,
-                              load_det_cal, det_cal_file, det_cal_file2 );
+void RunLoadAndConvertToMD::run() {
+  worker->loadAndConvertToMD(file_name, ev_ws_name, md_ws_name, modQ, minQ,
+                             maxQ, do_lorentz_corr, load_data, load_det_cal,
+                             det_cal_file, det_cal_file2);
 }
 
 /**
  * Class to call findPeaks in a separate thread.
  */
-RunFindPeaks::RunFindPeaks(        MantidEVWorker * worker,
-                            const std::string     & ev_ws_name,
-                            const std::string     & md_ws_name,
-                            const std::string     & peaks_ws_name,
-                                  double            max_abc,
-                                  size_t            num_to_find,
-                                  double            min_intensity,
-                                  double            minQPeaks,
-                                  double            maxQPeaks)
-{
-  this->worker        = worker;
-  this->ev_ws_name    = ev_ws_name;
-  this->md_ws_name    = md_ws_name;
+RunFindPeaks::RunFindPeaks(MantidEVWorker *worker,
+                           const std::string &ev_ws_name,
+                           const std::string &md_ws_name,
+                           const std::string &peaks_ws_name, double max_abc,
+                           size_t num_to_find, double min_intensity,
+                           double minQPeaks, double maxQPeaks) {
+  this->worker = worker;
+  this->ev_ws_name = ev_ws_name;
+  this->md_ws_name = md_ws_name;
   this->peaks_ws_name = peaks_ws_name;
-  this->max_abc       = max_abc;
-  this->num_to_find   = num_to_find;
+  this->max_abc = max_abc;
+  this->num_to_find = num_to_find;
   this->min_intensity = min_intensity;
   this->minQPeaks = minQPeaks;
   this->maxQPeaks = maxQPeaks;
 }
 
-
 /**
  *  Class to call findPeaks in a separate thread.
  */
-void RunFindPeaks::run()
-{
-  worker->findPeaks( ev_ws_name, md_ws_name, peaks_ws_name,
-                     max_abc, num_to_find, min_intensity, minQPeaks, maxQPeaks );
+void RunFindPeaks::run() {
+  worker->findPeaks(ev_ws_name, md_ws_name, peaks_ws_name, max_abc, num_to_find,
+                    min_intensity, minQPeaks, maxQPeaks);
 }
 
 /**
  * Class to call predictPeaks in a separate thread.
  */
-RunPredictPeaks::RunPredictPeaks(        MantidEVWorker * worker,
-                            const std::string     & peaks_ws_name,
-                                  double            min_pred_wl,
-                                  double            max_pred_wl,
-                                  double            min_pred_dspacing,
-                                  double            max_pred_dspacing )
-{
-  this->worker        = worker;
+RunPredictPeaks::RunPredictPeaks(MantidEVWorker *worker,
+                                 const std::string &peaks_ws_name,
+                                 double min_pred_wl, double max_pred_wl,
+                                 double min_pred_dspacing,
+                                 double max_pred_dspacing) {
+  this->worker = worker;
   this->peaks_ws_name = peaks_ws_name;
-  this->min_pred_wl       = min_pred_wl;
-  this->max_pred_wl       = max_pred_wl;
+  this->min_pred_wl = min_pred_wl;
+  this->max_pred_wl = max_pred_wl;
   this->min_pred_dspacing = min_pred_dspacing;
   this->max_pred_dspacing = max_pred_dspacing;
 }
 
-
 /**
  *  Class to call predictPeaks in a separate thread.
  */
-void RunPredictPeaks::run()
-{
-  worker->predictPeaks( peaks_ws_name, min_pred_wl, max_pred_wl, min_pred_dspacing, max_pred_dspacing );
+void RunPredictPeaks::run() {
+  worker->predictPeaks(peaks_ws_name, min_pred_wl, max_pred_wl,
+                       min_pred_dspacing, max_pred_dspacing);
 }
 
 /**
  *  Class to call sphereIntegrate in a separate thread.
  */
-RunSphereIntegrate::RunSphereIntegrate(       MantidEVWorker * worker,
-                                        const std::string    & peaks_ws_name,
-                                        const std::string    & event_ws_name,
-                                              double           peak_radius,
-                                              double           inner_radius,
-                                              double           outer_radius,
-                                              bool             integrate_edge,
-                                              bool          use_cylinder_integration,
-                                              double        cylinder_length,
-                                              double        cylinder_percent_bkg,
-                                        const std::string & cylinder_profile_fit)
-
-{ 
-  this->worker         = worker;
-  this->peaks_ws_name  = peaks_ws_name;
-  this->event_ws_name  = event_ws_name;
-  this->peak_radius    = peak_radius;
-  this->inner_radius   = inner_radius;
-  this->outer_radius   = outer_radius;
+RunSphereIntegrate::RunSphereIntegrate(
+    MantidEVWorker *worker, const std::string &peaks_ws_name,
+    const std::string &event_ws_name, double peak_radius, double inner_radius,
+    double outer_radius, bool integrate_edge, bool use_cylinder_integration,
+    double cylinder_length, double cylinder_percent_bkg,
+    const std::string &cylinder_profile_fit)
+
+{
+  this->worker = worker;
+  this->peaks_ws_name = peaks_ws_name;
+  this->event_ws_name = event_ws_name;
+  this->peak_radius = peak_radius;
+  this->inner_radius = inner_radius;
+  this->outer_radius = outer_radius;
   this->integrate_edge = integrate_edge;
   this->use_cylinder_integration = use_cylinder_integration;
   this->cylinder_length = cylinder_length;
@@ -143,1138 +116,1067 @@ RunSphereIntegrate::RunSphereIntegrate(       MantidEVWorker * worker,
   this->cylinder_profile_fit = cylinder_profile_fit;
 }
 
-
 /**
  *  Class to call sphereIntegrate in a separate thread.
  */
-void RunSphereIntegrate::run()
-{ 
-  worker->sphereIntegrate( peaks_ws_name, event_ws_name,
-                           peak_radius, inner_radius, outer_radius,
-                           integrate_edge, use_cylinder_integration,
-                           cylinder_length, cylinder_percent_bkg,
-                           cylinder_profile_fit);
+void RunSphereIntegrate::run() {
+  worker->sphereIntegrate(peaks_ws_name, event_ws_name, peak_radius,
+                          inner_radius, outer_radius, integrate_edge,
+                          use_cylinder_integration, cylinder_length,
+                          cylinder_percent_bkg, cylinder_profile_fit);
 }
 
-
 /**
  *  Class to call fitIntegrate in a separate thread.
  */
-RunFitIntegrate::RunFitIntegrate(       MantidEVWorker * worker,
-                                  const std::string    & peaks_ws_name,
-                                  const std::string    & event_ws_name,
-                                  const std::string    & rebin_params,
-                                        size_t           n_bad_edge_pix,
-                                        bool             use_ikeda_carpenter )
-{
-  this->worker              = worker;
-  this->peaks_ws_name       = peaks_ws_name;
-  this->event_ws_name       = event_ws_name;
-  this->rebin_params        = rebin_params;
-  this->n_bad_edge_pix      = n_bad_edge_pix;
+RunFitIntegrate::RunFitIntegrate(MantidEVWorker *worker,
+                                 const std::string &peaks_ws_name,
+                                 const std::string &event_ws_name,
+                                 const std::string &rebin_params,
+                                 size_t n_bad_edge_pix,
+                                 bool use_ikeda_carpenter) {
+  this->worker = worker;
+  this->peaks_ws_name = peaks_ws_name;
+  this->event_ws_name = event_ws_name;
+  this->rebin_params = rebin_params;
+  this->n_bad_edge_pix = n_bad_edge_pix;
   this->use_ikeda_carpenter = use_ikeda_carpenter;
 }
 
-
 /**
  *  Class to call fitIntegrate in a separate thread.
  */
-void RunFitIntegrate::run()
-{
-  worker->fitIntegrate( peaks_ws_name, event_ws_name,
-                        rebin_params, n_bad_edge_pix, use_ikeda_carpenter );
+void RunFitIntegrate::run() {
+  worker->fitIntegrate(peaks_ws_name, event_ws_name, rebin_params,
+                       n_bad_edge_pix, use_ikeda_carpenter);
 }
 
-
 /**
  *  Class to call ellipsoidIntegrate in a separate thread.
  */
-RunEllipsoidIntegrate::RunEllipsoidIntegrate(   MantidEVWorker * worker,
-                                          const std::string    & peaks_ws_name,
-                                          const std::string    & event_ws_name,
-                                                double           region_radius,
-                                                bool             specify_size,
-                                                double           peak_size,
-                                                double           inner_size,
-                                                double           outer_size )
-{
-  this->worker        = worker;
+RunEllipsoidIntegrate::RunEllipsoidIntegrate(
+    MantidEVWorker *worker, const std::string &peaks_ws_name,
+    const std::string &event_ws_name, double region_radius, bool specify_size,
+    double peak_size, double inner_size, double outer_size) {
+  this->worker = worker;
   this->peaks_ws_name = peaks_ws_name;
   this->event_ws_name = event_ws_name;
   this->region_radius = region_radius;
-  this->specify_size  = specify_size;
-  this->peak_size     = peak_size;
-  this->inner_size    = inner_size;
-  this->outer_size    = outer_size;
+  this->specify_size = specify_size;
+  this->peak_size = peak_size;
+  this->inner_size = inner_size;
+  this->outer_size = outer_size;
 }
 
-
 /**
  *  Class to call ellipsoidIntegrate in a separate thread.
  */
-void RunEllipsoidIntegrate::run()
-{
-  worker->ellipsoidIntegrate( peaks_ws_name, event_ws_name,
-                              region_radius, specify_size,
-                              peak_size, inner_size, outer_size );
+void RunEllipsoidIntegrate::run() {
+  worker->ellipsoidIntegrate(peaks_ws_name, event_ws_name, region_radius,
+                             specify_size, peak_size, inner_size, outer_size);
 }
 
-
-/// 
-/// Start of the MantidEV class 
 ///
-
+/// Start of the MantidEV class
+///
 
 /**
  *  Constructor for MantidEV.  Makes the thread pool and instance of
  *  MantidEVWorker.
  */
-MantidEV::MantidEV(QWidget *parent) : UserSubWindow(parent)
-{
-  last_Q        = V3D(0,0,0);
-  worker        = new MantidEVWorker();
-  m_thread_pool = new QThreadPool( this );
+MantidEV::MantidEV(QWidget *parent) : UserSubWindow(parent) {
+  last_Q = V3D(0, 0, 0);
+  worker = new MantidEVWorker();
+  m_thread_pool = new QThreadPool(this);
   m_thread_pool->setMaxThreadCount(1);
-   
-  QObject::connect( &(MantidQt::API::SelectionNotificationService::Instance()),
-                    SIGNAL( QPointSelection_signal( bool, double, double, double )),
-                    this, SLOT(QPointSelection_slot( bool, double, double, double )) );
-}
 
+  QObject::connect(&(MantidQt::API::SelectionNotificationService::Instance()),
+                   SIGNAL(QPointSelection_signal(bool, double, double, double)),
+                   this,
+                   SLOT(QPointSelection_slot(bool, double, double, double)));
+}
 
 /**
  *  Destructor for MantidEV.  Deletes the thread pool and instance of
  *  MantidEVWorker.
  */
-MantidEV::~MantidEV()
-{
+MantidEV::~MantidEV() {
   saveSettings("");
   delete worker;
   delete m_thread_pool;
 }
 
-
 /**
  *  This method is called by the super class to initialize the GUI.
  */
-void MantidEV::initLayout()
-{
+void MantidEV::initLayout() {
   m_uiForm.setupUi(this);
 
-                          // connect the apply buttons to the code that
-                          // gathers the parameters and will call a method
-                          // to carry out the requested action
+  // connect the apply buttons to the code that
+  // gathers the parameters and will call a method
+  // to carry out the requested action
 
   // apply button on "Select Data" tab
-  QObject::connect( m_uiForm.ApplySelectData_btn, SIGNAL(clicked()),
-                    this, SLOT(selectWorkspace_slot()) );
-
-   // browse button for event filename
-   QObject::connect( m_uiForm.SelectEventFile_btn, SIGNAL(clicked()),
-                     this, SLOT(loadEventFile_slot()) );
-
-   QObject::connect( m_uiForm.SelectCalFile_btn, SIGNAL(clicked()),
-                     this, SLOT(selectDetCalFile_slot()) );
-
-   QObject::connect( m_uiForm.SelectCalFile2_btn, SIGNAL(clicked()),
-                     this, SLOT(selectDetCalFile2_slot()) );
+  QObject::connect(m_uiForm.ApplySelectData_btn, SIGNAL(clicked()), this,
+                   SLOT(selectWorkspace_slot()));
 
-   QObject::connect( m_uiForm.ApplyFindPeaks_btn, SIGNAL(clicked()),
-                    this, SLOT(findPeaks_slot()) );
+  // browse button for event filename
+  QObject::connect(m_uiForm.SelectEventFile_btn, SIGNAL(clicked()), this,
+                   SLOT(loadEventFile_slot()));
 
-   QObject::connect( m_uiForm.SelectPeaksFile_btn, SIGNAL(clicked()),
-                     this, SLOT(getLoadPeaksFileName_slot()) );
+  QObject::connect(m_uiForm.SelectCalFile_btn, SIGNAL(clicked()), this,
+                   SLOT(selectDetCalFile_slot()));
 
-   QObject::connect( m_uiForm.ApplyFindUB_btn, SIGNAL(clicked()),
-                    this, SLOT(findUB_slot()) );
+  QObject::connect(m_uiForm.SelectCalFile2_btn, SIGNAL(clicked()), this,
+                   SLOT(selectDetCalFile2_slot()));
 
-   QObject::connect( m_uiForm.SelectUBFile_btn, SIGNAL(clicked()),
-                     this, SLOT(getLoadUB_FileName_slot()) );
+  QObject::connect(m_uiForm.ApplyFindPeaks_btn, SIGNAL(clicked()), this,
+                   SLOT(findPeaks_slot()));
 
-   QObject::connect( m_uiForm.ApplyChooseCell_btn, SIGNAL(clicked()),
-                    this, SLOT(chooseCell_slot()) );
+  QObject::connect(m_uiForm.SelectPeaksFile_btn, SIGNAL(clicked()), this,
+                   SLOT(getLoadPeaksFileName_slot()));
 
-   QObject::connect( m_uiForm.ApplyChangeHKL_btn, SIGNAL(clicked()),
-                    this, SLOT(changeHKL_slot()) );
+  QObject::connect(m_uiForm.ApplyFindUB_btn, SIGNAL(clicked()), this,
+                   SLOT(findUB_slot()));
 
-   QObject::connect( m_uiForm.ApplyIntegrate_btn, SIGNAL(clicked()),
-                    this, SLOT(integratePeaks_slot()) );
+  QObject::connect(m_uiForm.SelectUBFile_btn, SIGNAL(clicked()), this,
+                   SLOT(getLoadUB_FileName_slot()));
 
-   QObject::connect( m_uiForm.ShowInfo_btn, SIGNAL(clicked()),
-                    this, SLOT(showInfo_slot()) );
+  QObject::connect(m_uiForm.ApplyChooseCell_btn, SIGNAL(clicked()), this,
+                   SLOT(chooseCell_slot()));
 
-                          // connect the slots for the menu items
-   QObject::connect( m_uiForm.actionSave_State, SIGNAL(triggered()),
-                     this, SLOT(saveState_slot()) );
+  QObject::connect(m_uiForm.ApplyChangeHKL_btn, SIGNAL(clicked()), this,
+                   SLOT(changeHKL_slot()));
 
-   QObject::connect( m_uiForm.actionLoad_State, SIGNAL(triggered()),
-                     this, SLOT(loadState_slot()) );
+  QObject::connect(m_uiForm.ApplyIntegrate_btn, SIGNAL(clicked()), this,
+                   SLOT(integratePeaks_slot()));
 
-   QObject::connect( m_uiForm.actionReset_Default_Settings, SIGNAL(triggered()),
-                     this, SLOT( setDefaultState_slot()) );
+  QObject::connect(m_uiForm.ShowInfo_btn, SIGNAL(clicked()), this,
+                   SLOT(showInfo_slot()));
 
-   QObject::connect( m_uiForm.actionSave_Isaw_UB, SIGNAL(triggered()),
-                     this, SLOT(saveIsawUB_slot()) );
+  // connect the slots for the menu items
+  QObject::connect(m_uiForm.actionSave_State, SIGNAL(triggered()), this,
+                   SLOT(saveState_slot()));
 
-   QObject::connect( m_uiForm.actionLoad_Isaw_UB, SIGNAL(triggered()),
-                     this, SLOT(loadIsawUB_slot()) );
+  QObject::connect(m_uiForm.actionLoad_State, SIGNAL(triggered()), this,
+                   SLOT(loadState_slot()));
 
-   QObject::connect( m_uiForm.actionSave_Isaw_Peaks, SIGNAL(triggered()),
-                     this, SLOT(saveIsawPeaks_slot()) );
+  QObject::connect(m_uiForm.actionReset_Default_Settings, SIGNAL(triggered()),
+                   this, SLOT(setDefaultState_slot()));
 
-   QObject::connect( m_uiForm.actionLoad_Isaw_Peaks, SIGNAL(triggered()),
-                     this, SLOT(loadIsawPeaks_slot()) );
+  QObject::connect(m_uiForm.actionSave_Isaw_UB, SIGNAL(triggered()), this,
+                   SLOT(saveIsawUB_slot()));
 
-   QObject::connect( m_uiForm.actionSave_Nexus_Peaks, SIGNAL(triggered()),
-                     this, SLOT(saveNexusPeaks_slot()) );
+  QObject::connect(m_uiForm.actionLoad_Isaw_UB, SIGNAL(triggered()), this,
+                   SLOT(loadIsawUB_slot()));
 
-   QObject::connect( m_uiForm.actionLoad_Nexus_Peaks, SIGNAL(triggered()),
-                     this, SLOT(loadNexusPeaks_slot()) );
+  QObject::connect(m_uiForm.actionSave_Isaw_Peaks, SIGNAL(triggered()), this,
+                   SLOT(saveIsawPeaks_slot()));
 
-   QObject::connect( m_uiForm.actionShow_UB, SIGNAL(triggered()),
-                     this, SLOT(showUB_slot()) );
-   
-   QObject::connect( m_uiForm.actionOnline_Help_Page, SIGNAL(triggered()),
-                     this, SLOT(help_slot()) );
+  QObject::connect(m_uiForm.actionLoad_Isaw_Peaks, SIGNAL(triggered()), this,
+                   SLOT(loadIsawPeaks_slot()));
 
-  QObject::connect( m_uiForm.EventFileName_ledt, SIGNAL(editingFinished()),
-                     this, SLOT(loadEventFileEntered_slot()) );
+  QObject::connect(m_uiForm.actionSave_Nexus_Peaks, SIGNAL(triggered()), this,
+                   SLOT(saveNexusPeaks_slot()));
 
-                           // connect the slots for enabling and disabling
-                           // various subsets of widgets
-   QObject::connect( m_uiForm.   convertToMDGroupBox, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledLoadEventFileParams_slot(bool) ) );
+  QObject::connect(m_uiForm.actionLoad_Nexus_Peaks, SIGNAL(triggered()), this,
+                   SLOT(loadNexusPeaks_slot()));
+
+  QObject::connect(m_uiForm.actionShow_UB, SIGNAL(triggered()), this,
+                   SLOT(showUB_slot()));
+
+  QObject::connect(m_uiForm.actionOnline_Help_Page, SIGNAL(triggered()), this,
+                   SLOT(help_slot()));
+
+  QObject::connect(m_uiForm.EventFileName_ledt, SIGNAL(editingFinished()), this,
+                   SLOT(loadEventFileEntered_slot()));
+
+  // connect the slots for enabling and disabling
+  // various subsets of widgets
+  QObject::connect(m_uiForm.convertToMDGroupBox, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledLoadEventFileParams_slot(bool)));
+
+  QObject::connect(m_uiForm.LoadDetCal_ckbx, SIGNAL(clicked()), this,
+                   SLOT(setEnabledLoadCalFiles_slot()));
+
+  QObject::connect(m_uiForm.FindPeaks_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledFindPeaksParams_slot(bool)));
+
+  QObject::connect(m_uiForm.PredictPeaks_ckbx, SIGNAL(clicked()), this,
+                   SLOT(setEnabledPredictPeaksParams_slot()));
+
+  QObject::connect(m_uiForm.LoadIsawPeaks_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledLoadPeaksParams_slot(bool)));
+
+  QObject::connect(m_uiForm.FindUBUsingFFT_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledFindUBFFTParams_slot(bool)));
+
+  QObject::connect(m_uiForm.LoadISAWUB_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledLoadUBParams_slot(bool)));
+
+  QObject::connect(m_uiForm.OptimizeGoniometerAngles_ckbx, SIGNAL(clicked()),
+                   this, SLOT(setEnabledMaxOptimizeDegrees_slot()));
+
+  QObject::connect(m_uiForm.IndexPeaks_ckbx, SIGNAL(clicked(bool)), this,
+                   SLOT(setEnabledIndexParams_slot(bool)));
 
-    QObject::connect( m_uiForm.LoadDetCal_ckbx, SIGNAL(clicked()),
-                     this, SLOT( setEnabledLoadCalFiles_slot() ) );
+  QObject::connect(m_uiForm.ShowPossibleCells_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledShowCellsParams_slot(bool)));
 
-   QObject::connect( m_uiForm.FindPeaks_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledFindPeaksParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.PredictPeaks_ckbx, SIGNAL(clicked()),
-                     this, SLOT( setEnabledPredictPeaksParams_slot() ) );
-
-   QObject::connect( m_uiForm.LoadIsawPeaks_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledLoadPeaksParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.FindUBUsingFFT_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledFindUBFFTParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.LoadISAWUB_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledLoadUBParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.OptimizeGoniometerAngles_ckbx, SIGNAL(clicked()),
-                     this, SLOT( setEnabledMaxOptimizeDegrees_slot() ) );
-
-   QObject::connect( m_uiForm.IndexPeaks_ckbx, SIGNAL(clicked(bool)),
-                     this, SLOT( setEnabledIndexParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.ShowPossibleCells_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledShowCellsParams_slot(bool) ) );
-
-   QObject::connect( m_uiForm.SelectCellOfType_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledSetCellTypeParams_slot(bool) ) );
+  QObject::connect(m_uiForm.SelectCellOfType_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledSetCellTypeParams_slot(bool)));
+
+  QObject::connect(m_uiForm.SelectCellWithForm_rbtn, SIGNAL(toggled(bool)),
+                   this, SLOT(setEnabledSetCellFormParams_slot(bool)));
+
+  QObject::connect(m_uiForm.SphereIntegration_rbtn, SIGNAL(toggled(bool)), this,
+                   SLOT(setEnabledSphereIntParams_slot(bool)));
+
+  QObject::connect(m_uiForm.TwoDFitIntegration_rbtn, SIGNAL(toggled(bool)),
+                   this, SLOT(setEnabledFitIntParams_slot(bool)));
+
+  QObject::connect(m_uiForm.EllipsoidIntegration_rbtn, SIGNAL(toggled(bool)),
+                   this, SLOT(setEnabledEllipseIntParams_slot(bool)));
+
+  QObject::connect(m_uiForm.SpecifySize_ckbx, SIGNAL(clicked(bool)), this,
+                   SLOT(setEnabledEllipseSizeOptions_slot()));
+
+  // Add validators to all QLineEdit objects that require numeric values
+  m_uiForm.MaxMagQ_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.MaxMagQ_ledt));
+  m_uiForm.MaxABC_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.MaxABC_ledt));
+  m_uiForm.NumToFind_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.NumToFind_ledt));
+  m_uiForm.MinIntensity_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.MinIntensity_ledt));
+  m_uiForm.MinD_ledt->setValidator(new QDoubleValidator(m_uiForm.MinD_ledt));
+  m_uiForm.MaxD_ledt->setValidator(new QDoubleValidator(m_uiForm.MaxD_ledt));
+  m_uiForm.FFTTolerance_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.FFTTolerance_ledt));
+  m_uiForm.IndexedPeaksTolerance_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.IndexedPeaksTolerance_ledt));
+  m_uiForm.MaxGoniometerChange_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.MaxGoniometerChange_ledt));
+  m_uiForm.IndexingTolerance_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.IndexingTolerance_ledt));
+  m_uiForm.MaxScalarError_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.MaxScalarError_ledt));
+  m_uiForm.min_pred_wl_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.min_pred_wl_ledt));
+  m_uiForm.max_pred_wl_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.max_pred_wl_ledt));
+  m_uiForm.min_pred_dspacing_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.min_pred_dspacing_ledt));
+  m_uiForm.max_pred_dspacing_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.max_pred_dspacing_ledt));
+  m_uiForm.PeakRadius_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.PeakRadius_ledt));
+  m_uiForm.BackgroundInnerRadius_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.BackgroundInnerRadius_ledt));
+  m_uiForm.BackgroundOuterRadius_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.BackgroundOuterRadius_ledt));
+  m_uiForm.CylinderLength_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.CylinderLength_ledt));
+  m_uiForm.CylinderPercentBkg_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.CylinderPercentBkg_ledt));
+  m_uiForm.NBadEdgePixels_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.NBadEdgePixels_ledt));
+  m_uiForm.RegionRadius_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.RegionRadius_ledt));
+  m_uiForm.PeakSize_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.PeakSize_ledt));
+  m_uiForm.BackgroundInnerSize_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.BackgroundInnerSize_ledt));
+  m_uiForm.BackgroundOuterSize_ledt->setValidator(
+      new QDoubleValidator(m_uiForm.BackgroundOuterSize_ledt));
+  m_uiForm.Qx_ledt->setValidator(new QDoubleValidator(m_uiForm.Qx_ledt));
+  m_uiForm.Qy_ledt->setValidator(new QDoubleValidator(m_uiForm.Qy_ledt));
+  m_uiForm.Qz_ledt->setValidator(new QDoubleValidator(m_uiForm.Qz_ledt));
+
+  setDefaultState_slot(); // call method to set all controls to default state
+
+  loadSettings(""); // reload any previously saved user settings
+}
+
+/**
+ * Set up default values for the input controls, and set groups of
+ * widgets to be enabled or disabled as needed.
+ */
+void MantidEV::setDefaultState_slot() {
+  m_uiForm.MantidEV_tabwidg->setCurrentIndex(0);
+  // Select Data tab
+  m_uiForm.SelectEventWorkspace_ledt->setText("");
+  m_uiForm.MDworkspace_ledt->setText("");
+  m_uiForm.convertToMDGroupBox->setChecked(true);
+  m_uiForm.loadDataGroupBox->setChecked(true);
+  m_uiForm.EventFileName_ledt->setText("");
+  m_uiForm.MaxMagQ_ledt->setText("25");
+  m_uiForm.ModQ_ledt->setText("0");
+  m_uiForm.LorentzCorrection_ckbx->setChecked(true);
+  setEnabledLoadEventFileParams_slot(true);
+  m_uiForm.LoadDetCal_ckbx->setChecked(false);
+  setEnabledLoadCalFiles_slot();
+  m_uiForm.CalFileName_ledt->setText("");
+  m_uiForm.CalFileName2_ledt->setText("");
+  last_event_file.clear();
+  // Find Peaks tab
+  m_uiForm.PeaksWorkspace_ledt->setText("");
+  m_uiForm.FindPeaks_rbtn->setChecked(true);
+  m_uiForm.MaxABC_ledt->setText("15");
+  m_uiForm.NumToFind_ledt->setText("50");
+  m_uiForm.MinIntensity_ledt->setText("100");
+  m_uiForm.UseExistingPeaksWorkspace_rbtn->setChecked(false);
+  m_uiForm.LoadIsawPeaks_rbtn->setChecked(false);
+  m_uiForm.SelectPeaksFile_ledt->setText("");
+  m_uiForm.PredictPeaks_ckbx->setChecked(false);
+  m_uiForm.min_pred_wl_ledt->setText("0.4");
+  m_uiForm.max_pred_wl_ledt->setText("3.5");
+  m_uiForm.min_pred_dspacing_ledt->setText("0.4");
+  m_uiForm.max_pred_dspacing_ledt->setText("8.5");
+  setEnabledFindPeaksParams_slot(true);
+  setEnabledPredictPeaksParams_slot();
+  setEnabledLoadPeaksParams_slot(false);
+  last_peaks_file.clear();
+  // Find UB tab
+  m_uiForm.FindUBUsingFFT_rbtn->setChecked(true);
+  m_uiForm.MinD_ledt->setText("3");
+  m_uiForm.MaxD_ledt->setText("15");
+  m_uiForm.FFTTolerance_ledt->setText("0.12");
+  m_uiForm.FindUBUsingIndexedPeaks_rbtn->setChecked(false);
+  m_uiForm.IndexedPeaksTolerance_ledt->setText("0.1");
+  m_uiForm.LoadISAWUB_rbtn->setChecked(false);
+  m_uiForm.SelectUBFile_ledt->setText("");
+  m_uiForm.OptimizeGoniometerAngles_ckbx->setChecked(false);
+  m_uiForm.MaxGoniometerChange_ledt->setText("5");
+  m_uiForm.UseCurrentUB_rbtn->setChecked(false);
+  m_uiForm.IndexPeaks_ckbx->setChecked(true);
+  m_uiForm.IndexingTolerance_ledt->setText("0.12");
+  m_uiForm.RoundHKLs_ckbx->setChecked(true);
+  setEnabledFindUBFFTParams_slot(true);
+  setEnabledLoadUBParams_slot(false);
+  setEnabledMaxOptimizeDegrees_slot();
+  setEnabledIndexParams_slot(true);
+  last_UB_file.clear();
+  // Choose Cell tab
+  m_uiForm.ShowPossibleCells_rbtn->setChecked(true);
+  m_uiForm.MaxScalarError_ledt->setText("0.2");
+  m_uiForm.BestCellOnly_ckbx->setChecked(true);
+  m_uiForm.AllowPermutations_ckbx->setChecked(true);
+  m_uiForm.SelectCellOfType_rbtn->setChecked(false);
+  m_uiForm.CellType_cmbx->setCurrentIndex(0);
+  m_uiForm.CellCentering_cmbx->setCurrentIndex(0);
+  m_uiForm.SelectCellWithForm_rbtn->setChecked(false);
+  m_uiForm.CellFormNumber_cmbx->setCurrentIndex(0);
+  setEnabledShowCellsParams_slot(true);
+  setEnabledSetCellTypeParams_slot(false);
+  setEnabledSetCellFormParams_slot(false);
+  // Change HKL tab
+  m_uiForm.HKL_tran_row_1_ledt->setText("1, 0, 0");
+  m_uiForm.HKL_tran_row_2_ledt->setText("0, 1, 0");
+  m_uiForm.HKL_tran_row_3_ledt->setText("0, 0, 1");
+  // Integrate tab
+  m_uiForm.SphereIntegration_rbtn->setChecked(true);
+  m_uiForm.PeakRadius_ledt->setText("0.18");
+  m_uiForm.BackgroundInnerRadius_ledt->setText("0.18");
+  m_uiForm.BackgroundOuterRadius_ledt->setText("0.23");
+  m_uiForm.CylinderLength_ledt->setText("0.40");
+  m_uiForm.CylinderPercentBkg_ledt->setText("20.0");
+  m_uiForm.IntegrateEdge_ckbx->setChecked(true);
+  m_uiForm.Cylinder_ckbx->setChecked(false);
+  m_uiForm.CylinderProfileFit_cmbx->setCurrentIndex(5);
+  m_uiForm.TwoDFitIntegration_rbtn->setChecked(false);
+  m_uiForm.FitRebinParams_ledt->setText("1000,-0.004,16000");
+  m_uiForm.NBadEdgePixels_ledt->setText("5");
+  m_uiForm.IkedaCarpenter_ckbx->setChecked(false);
+  m_uiForm.EllipsoidIntegration_rbtn->setChecked(false);
+  m_uiForm.RegionRadius_ledt->setText("0.25");
+  m_uiForm.SpecifySize_ckbx->setChecked(false);
+  m_uiForm.PeakSize_ledt->setText("0.18");
+  m_uiForm.BackgroundInnerSize_ledt->setText("0.18");
+  m_uiForm.BackgroundOuterSize_ledt->setText("0.23");
+  setEnabledSphereIntParams_slot(true);
+  setEnabledFitIntParams_slot(false);
+  setEnabledEllipseIntParams_slot(false);
+  setEnabledEllipseSizeOptions_slot();
+  // Point Info tab
+  m_uiForm.Qx_ledt->setText("");
+  m_uiForm.Qy_ledt->setText("");
+  m_uiForm.Qz_ledt->setText("");
+  m_uiForm.SelectedPoint_tbl->clear();
+}
 
-   QObject::connect( m_uiForm.SelectCellWithForm_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledSetCellFormParams_slot(bool) ) );
+/**
+ * Go to MantidEV web page when help menu item is chosen
+ */
+void MantidEV::help_slot() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/"
+           "SCD_Event_Data_Reduction_Interface_(MantidEV)"));
+}
 
-   QObject::connect( m_uiForm.SphereIntegration_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledSphereIntParams_slot(bool) ) );
+/**
+ *  Slot called when the Apply button is pressed on the Select Data tab.
+ */
+void MantidEV::selectWorkspace_slot() {
+  // Check that the event workspace name is non-blank.
+  std::string ev_ws_name =
+      m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
 
-   QObject::connect( m_uiForm.TwoDFitIntegration_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledFitIntParams_slot(bool) ) );
+  if (ev_ws_name.length() == 0) {
+    errorMessage("Specify the name of an Event Workspace on Select Data tab.");
+    return;
+  }
 
-   QObject::connect( m_uiForm.EllipsoidIntegration_rbtn, SIGNAL(toggled(bool)),
-                     this, SLOT( setEnabledEllipseIntParams_slot(bool) ) );
+  // Check that the MD workspace name is non-blank.
+  std::string md_ws_name =
+      m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
 
-   QObject::connect( m_uiForm.SpecifySize_ckbx, SIGNAL(clicked(bool)),
-                     this, SLOT( setEnabledEllipseSizeOptions_slot() ) );
+  if (md_ws_name.length() == 0) {
+    errorMessage("Specify the name of an MD Workspace on Select Data tab.");
+    return;
+  }
 
-   // Add validators to all QLineEdit objects that require numeric values
-   m_uiForm.MaxMagQ_ledt->setValidator( new QDoubleValidator(m_uiForm.MaxMagQ_ledt));
-   m_uiForm.MaxABC_ledt->setValidator( new QDoubleValidator(m_uiForm.MaxABC_ledt));
-   m_uiForm.NumToFind_ledt->setValidator( new QDoubleValidator(m_uiForm.NumToFind_ledt));
-   m_uiForm.MinIntensity_ledt->setValidator( new QDoubleValidator(m_uiForm.MinIntensity_ledt));
-   m_uiForm.MinD_ledt->setValidator( new QDoubleValidator(m_uiForm.MinD_ledt));
-   m_uiForm.MaxD_ledt->setValidator( new QDoubleValidator(m_uiForm.MaxD_ledt));
-   m_uiForm.FFTTolerance_ledt->setValidator( new QDoubleValidator(m_uiForm.FFTTolerance_ledt));
-   m_uiForm.IndexedPeaksTolerance_ledt->setValidator( new QDoubleValidator(m_uiForm.IndexedPeaksTolerance_ledt));
-   m_uiForm.MaxGoniometerChange_ledt->setValidator( new QDoubleValidator(m_uiForm.MaxGoniometerChange_ledt));
-   m_uiForm.IndexingTolerance_ledt->setValidator( new QDoubleValidator(m_uiForm.IndexingTolerance_ledt));
-   m_uiForm.MaxScalarError_ledt->setValidator( new QDoubleValidator(m_uiForm.MaxScalarError_ledt));
-   m_uiForm.min_pred_wl_ledt->setValidator( new QDoubleValidator( m_uiForm.min_pred_wl_ledt));
-   m_uiForm.max_pred_wl_ledt->setValidator( new QDoubleValidator( m_uiForm.max_pred_wl_ledt));
-   m_uiForm.min_pred_dspacing_ledt->setValidator( new QDoubleValidator( m_uiForm.min_pred_dspacing_ledt));
-   m_uiForm.max_pred_dspacing_ledt->setValidator( new QDoubleValidator( m_uiForm.max_pred_dspacing_ledt));
-   m_uiForm.PeakRadius_ledt->setValidator( new QDoubleValidator(m_uiForm.PeakRadius_ledt));
-   m_uiForm.BackgroundInnerRadius_ledt->setValidator( new QDoubleValidator(m_uiForm.BackgroundInnerRadius_ledt));
-   m_uiForm.BackgroundOuterRadius_ledt->setValidator( new QDoubleValidator(m_uiForm.BackgroundOuterRadius_ledt));
-   m_uiForm.CylinderLength_ledt->setValidator( new QDoubleValidator(m_uiForm.CylinderLength_ledt));
-   m_uiForm.CylinderPercentBkg_ledt->setValidator( new QDoubleValidator(m_uiForm.CylinderPercentBkg_ledt));
-   m_uiForm.NBadEdgePixels_ledt->setValidator( new QDoubleValidator(m_uiForm.NBadEdgePixels_ledt));
-   m_uiForm.RegionRadius_ledt->setValidator( new QDoubleValidator(m_uiForm.RegionRadius_ledt));
-   m_uiForm.PeakSize_ledt->setValidator( new QDoubleValidator(m_uiForm.PeakSize_ledt));
-   m_uiForm.BackgroundInnerSize_ledt->setValidator( new QDoubleValidator(m_uiForm.BackgroundInnerSize_ledt));
-   m_uiForm.BackgroundOuterSize_ledt->setValidator( new QDoubleValidator(m_uiForm.BackgroundOuterSize_ledt));
-   m_uiForm.Qx_ledt->setValidator( new QDoubleValidator(m_uiForm.Qx_ledt));
-   m_uiForm.Qy_ledt->setValidator( new QDoubleValidator(m_uiForm.Qy_ledt));
-   m_uiForm.Qz_ledt->setValidator( new QDoubleValidator(m_uiForm.Qz_ledt));
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
+  std::string file_name =
+      m_uiForm.EventFileName_ledt->text().trimmed().toStdString();
+  if (m_uiForm.convertToMDGroupBox->isChecked()) {
+    if (!m_uiForm.loadDataGroupBox->isChecked()) {
+      if (!worker->isEventWorkspace(ev_ws_name)) {
+        errorMessage(
+            "Requested Event Workspace is NOT a valid Event workspace");
+        return;
+      }
+    } else {
+      if (file_name.empty()) {
+        errorMessage("Specify the name of an event file to load.");
+        return;
+      }
+    }
 
-   setDefaultState_slot();      // call method to set all controls to default state
+    double modQ;
+    getDouble(m_uiForm.ModQ_ledt, modQ);
 
-   loadSettings("");            // reload any previously saved user settings
-}
+    double minQ;
+    getDouble(m_uiForm.MinMagQ_ledt, minQ);
 
-/**
- * Set up default values for the input controls, and set groups of 
- * widgets to be enabled or disabled as needed.
- */
-void MantidEV::setDefaultState_slot()
-{
-   m_uiForm.MantidEV_tabwidg->setCurrentIndex(0);
-                                                    // Select Data tab
-   m_uiForm.SelectEventWorkspace_ledt->setText("");
-   m_uiForm.MDworkspace_ledt->setText("");
-   m_uiForm.convertToMDGroupBox->setChecked(true);
-   m_uiForm.loadDataGroupBox->setChecked(true);
-   m_uiForm.EventFileName_ledt->setText(""); 
-   m_uiForm.MaxMagQ_ledt->setText("25");
-   m_uiForm.ModQ_ledt->setText("0");
-   m_uiForm.LorentzCorrection_ckbx->setChecked(true);
-   setEnabledLoadEventFileParams_slot(true);
-   m_uiForm.LoadDetCal_ckbx->setChecked(false);
-   setEnabledLoadCalFiles_slot();
-   m_uiForm.CalFileName_ledt->setText("");
-   m_uiForm.CalFileName2_ledt->setText("");
-   last_event_file.clear();
-                                                    // Find Peaks tab
-   m_uiForm.PeaksWorkspace_ledt->setText("");
-   m_uiForm.FindPeaks_rbtn->setChecked(true);
-   m_uiForm.MaxABC_ledt->setText("15");
-   m_uiForm.NumToFind_ledt->setText("50");
-   m_uiForm.MinIntensity_ledt->setText("100");
-   m_uiForm.UseExistingPeaksWorkspace_rbtn->setChecked(false);
-   m_uiForm.LoadIsawPeaks_rbtn->setChecked(false);
-   m_uiForm.SelectPeaksFile_ledt->setText("");
-   m_uiForm.PredictPeaks_ckbx->setChecked(false);
-   m_uiForm.min_pred_wl_ledt->setText("0.4");
-   m_uiForm.max_pred_wl_ledt->setText("3.5");
-   m_uiForm.min_pred_dspacing_ledt->setText("0.4");
-   m_uiForm.max_pred_dspacing_ledt->setText("8.5");
-   setEnabledFindPeaksParams_slot(true);
-   setEnabledPredictPeaksParams_slot();
-   setEnabledLoadPeaksParams_slot(false);
-   last_peaks_file.clear();
-                                                    // Find UB tab
-   m_uiForm.FindUBUsingFFT_rbtn->setChecked(true);
-   m_uiForm.MinD_ledt->setText("3");
-   m_uiForm.MaxD_ledt->setText("15");
-   m_uiForm.FFTTolerance_ledt->setText("0.12");
-   m_uiForm.FindUBUsingIndexedPeaks_rbtn->setChecked(false);
-   m_uiForm.IndexedPeaksTolerance_ledt->setText("0.1");
-   m_uiForm.LoadISAWUB_rbtn->setChecked(false);
-   m_uiForm.SelectUBFile_ledt->setText("");
-   m_uiForm.OptimizeGoniometerAngles_ckbx->setChecked(false);
-   m_uiForm.MaxGoniometerChange_ledt->setText("5");
-   m_uiForm.UseCurrentUB_rbtn->setChecked(false);
-   m_uiForm.IndexPeaks_ckbx->setChecked(true);
-   m_uiForm.IndexingTolerance_ledt->setText("0.12");
-   m_uiForm.RoundHKLs_ckbx->setChecked( true );
-   setEnabledFindUBFFTParams_slot(true);
-   setEnabledLoadUBParams_slot(false);
-   setEnabledMaxOptimizeDegrees_slot();
-   setEnabledIndexParams_slot(true);
-   last_UB_file.clear();
-                                                     // Choose Cell tab
-   m_uiForm.ShowPossibleCells_rbtn->setChecked(true);
-   m_uiForm.MaxScalarError_ledt->setText("0.2");
-   m_uiForm.BestCellOnly_ckbx->setChecked(true);
-   m_uiForm.AllowPermutations_ckbx->setChecked(true);
-   m_uiForm.SelectCellOfType_rbtn->setChecked(false);
-   m_uiForm.CellType_cmbx->setCurrentIndex(0);
-   m_uiForm.CellCentering_cmbx->setCurrentIndex(0);
-   m_uiForm.SelectCellWithForm_rbtn->setChecked(false);
-   m_uiForm.CellFormNumber_cmbx->setCurrentIndex(0);
-   setEnabledShowCellsParams_slot(true);
-   setEnabledSetCellTypeParams_slot(false);
-   setEnabledSetCellFormParams_slot(false);
-                                                     // Change HKL tab
-   m_uiForm.HKL_tran_row_1_ledt->setText("1, 0, 0");
-   m_uiForm.HKL_tran_row_2_ledt->setText("0, 1, 0");
-   m_uiForm.HKL_tran_row_3_ledt->setText("0, 0, 1");
-                                                     // Integrate tab
-   m_uiForm.SphereIntegration_rbtn->setChecked(true);
-   m_uiForm.PeakRadius_ledt->setText("0.18");
-   m_uiForm.BackgroundInnerRadius_ledt->setText("0.18");
-   m_uiForm.BackgroundOuterRadius_ledt->setText("0.23");
-   m_uiForm.CylinderLength_ledt->setText("0.40");
-   m_uiForm.CylinderPercentBkg_ledt->setText("20.0");
-   m_uiForm.IntegrateEdge_ckbx->setChecked(true);
-   m_uiForm.Cylinder_ckbx->setChecked(false);
-   m_uiForm.CylinderProfileFit_cmbx->setCurrentIndex(5);
-   m_uiForm.TwoDFitIntegration_rbtn->setChecked(false);
-   m_uiForm.FitRebinParams_ledt->setText("1000,-0.004,16000");
-   m_uiForm.NBadEdgePixels_ledt->setText("5");
-   m_uiForm.IkedaCarpenter_ckbx->setChecked(false);
-   m_uiForm.EllipsoidIntegration_rbtn->setChecked(false);
-   m_uiForm.RegionRadius_ledt->setText("0.25");
-   m_uiForm.SpecifySize_ckbx->setChecked(false);
-   m_uiForm.PeakSize_ledt->setText("0.18");
-   m_uiForm.BackgroundInnerSize_ledt->setText("0.18");
-   m_uiForm.BackgroundOuterSize_ledt->setText("0.23");
-   setEnabledSphereIntParams_slot(true);
-   setEnabledFitIntParams_slot(false);
-   setEnabledEllipseIntParams_slot(false);
-   setEnabledEllipseSizeOptions_slot();
-                                                     // Point Info tab
-   m_uiForm.Qx_ledt->setText("");
-   m_uiForm.Qy_ledt->setText("");
-   m_uiForm.Qz_ledt->setText("");
-   m_uiForm.SelectedPoint_tbl->clear();
-}
+    double maxQ;
+    getDouble(m_uiForm.MaxMagQ_ledt, maxQ);
 
+    std::string det_cal_file =
+        m_uiForm.CalFileName_ledt->text().trimmed().toStdString();
+    std::string det_cal_file2 =
+        m_uiForm.CalFileName2_ledt->text().trimmed().toStdString();
+    bool load_det_cal = m_uiForm.LoadDetCal_ckbx->isChecked();
+    if (load_det_cal && det_cal_file.length() == 0) {
+      errorMessage("Specify the name of a .DetCal file if Load ISAW Detector "
+                   "Calibration is selected");
+      return;
+    }
 
-/**
- * Go to MantidEV web page when help menu item is chosen
- */
-void MantidEV::help_slot()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/SCD_Event_Data_Reduction_Interface_(MantidEV)"));
+    RunLoadAndConvertToMD *runner = new RunLoadAndConvertToMD(
+        worker, file_name, ev_ws_name, md_ws_name, modQ, minQ, maxQ,
+        m_uiForm.LorentzCorrection_ckbx->isChecked(),
+        m_uiForm.loadDataGroupBox->isChecked(), load_det_cal, det_cal_file,
+        det_cal_file2);
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage("Failed to start Load and ConvertToMD thread...previous "
+                   "operation not complete");
+  } else // check existing workspaces
+  {
+    if (!worker->isEventWorkspace(ev_ws_name)) {
+      errorMessage("Requested Event Workspace is NOT a valid Event workspace");
+      return;
+    }
+    if (!worker->isMDWorkspace(md_ws_name)) {
+      errorMessage("Requested MD Workspace is NOT a valid MD workspace");
+      return;
+    }
+  }
 }
 
-
 /**
- *  Slot called when the Apply button is pressed on the Select Data tab.
- */
-void MantidEV::selectWorkspace_slot()
-{
-   // Check that the event workspace name is non-blank.
-   std::string ev_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-
-   if ( ev_ws_name.length() == 0 )
-   {
-     errorMessage("Specify the name of an Event Workspace on Select Data tab.");
-     return;
-   }
-
-   // Check that the MD workspace name is non-blank.
-   std::string md_ws_name = m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
-
-   if ( md_ws_name.length() == 0 )
-   {
-     errorMessage("Specify the name of an MD Workspace on Select Data tab.");
-     return;
-   }
-
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
-   std::string file_name = m_uiForm.EventFileName_ledt->text().trimmed().toStdString();
-   if (m_uiForm.convertToMDGroupBox->isChecked())
-   {
-     if (!m_uiForm.loadDataGroupBox->isChecked())
-     {
-       if ( !worker->isEventWorkspace( ev_ws_name ) )
-       {
-         errorMessage("Requested Event Workspace is NOT a valid Event workspace");
-         return;
-       }
-     }
-     else
-     {
-       if (file_name.empty())
-       {
-         errorMessage("Specify the name of an event file to load.");
-         return;
-       }
-     }
-
-     double modQ;
-     getDouble( m_uiForm.ModQ_ledt, modQ );
-
-     double minQ;
-     getDouble( m_uiForm.MinMagQ_ledt, minQ );
-
-     double maxQ;
-     getDouble( m_uiForm.MaxMagQ_ledt, maxQ );
-
-     std::string det_cal_file  = m_uiForm.CalFileName_ledt->text().trimmed().toStdString();
-     std::string det_cal_file2 = m_uiForm.CalFileName2_ledt->text().trimmed().toStdString();
-     bool        load_det_cal  = m_uiForm.LoadDetCal_ckbx->isChecked();
-     if ( load_det_cal && det_cal_file.length() == 0 )
-     {
-       errorMessage("Specify the name of a .DetCal file if Load ISAW Detector Calibration is selected");
-       return;
-     }
-
-     RunLoadAndConvertToMD* runner = new RunLoadAndConvertToMD(worker,file_name,
-                                                               ev_ws_name, md_ws_name,
-                                                               modQ, minQ, maxQ,
-                                                               m_uiForm.LorentzCorrection_ckbx->isChecked(),
-                                                               m_uiForm.loadDataGroupBox->isChecked(),
-                                                               load_det_cal, det_cal_file, det_cal_file2 );
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start Load and ConvertToMD thread...previous operation not complete" );
-   }
-   else // check existing workspaces
-   {
-     if ( !worker->isEventWorkspace( ev_ws_name ) )
-     {
-       errorMessage("Requested Event Workspace is NOT a valid Event workspace");
-       return;
-     }
-     if ( !worker->isMDWorkspace( md_ws_name ) )
-     {
-       errorMessage("Requested MD Workspace is NOT a valid MD workspace");
-       return;
-     }
-   }
-}
-
-
-/**
- *  Set the default workspace names when editing the event filename is 
+ *  Set the default workspace names when editing the event filename is
  *  finished on the Select Data tab, or a file is selected with the
  *  Browse button.
  */
-void MantidEV::loadEventFileEntered_slot()
-{
-  QString Qfile_name =m_uiForm.EventFileName_ledt->text().trimmed();
-  if ( Qfile_name.length() > 0 )
-  {
-    last_event_file = Qfile_name.toStdString();   
+void MantidEV::loadEventFileEntered_slot() {
+  QString Qfile_name = m_uiForm.EventFileName_ledt->text().trimmed();
+  if (Qfile_name.length() > 0) {
+    last_event_file = Qfile_name.toStdString();
 
-    std::string base_name = extractBaseFileName( last_event_file );
+    std::string base_name = extractBaseFileName(last_event_file);
     std::string event_ws_name = base_name + "_event";
-    std::string md_ws_name    = base_name + "_md";
+    std::string md_ws_name = base_name + "_md";
     std::string peaks_ws_name = base_name + "_peaks";
 
-    m_uiForm.SelectEventWorkspace_ledt->setText( QString::fromStdString( event_ws_name ));
-    m_uiForm.MDworkspace_ledt->setText( QString::fromStdString( md_ws_name ));
-    m_uiForm.PeaksWorkspace_ledt->setText( QString::fromStdString( peaks_ws_name ));
+    m_uiForm.SelectEventWorkspace_ledt->setText(
+        QString::fromStdString(event_ws_name));
+    m_uiForm.MDworkspace_ledt->setText(QString::fromStdString(md_ws_name));
+    m_uiForm.PeaksWorkspace_ledt->setText(
+        QString::fromStdString(peaks_ws_name));
   }
 }
 
-
 /**
  *  Slot called when the Browse button for loading data from an event file
  *  is pressed on the SelectData tab.
  */
-void MantidEV::loadEventFile_slot()
-{
-  QString file_path  = getFilePath( last_event_file );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                              tr("Load event file"),
-                              file_path,
-                              tr("Nexus Files (*.nxs);; All files(*.*)"));
+void MantidEV::loadEventFile_slot() {
+  QString file_path = getFilePath(last_event_file);
+  QString Qfile_name =
+      QFileDialog::getOpenFileName(this, tr("Load event file"), file_path,
+                                   tr("Nexus Files (*.nxs);; All files(*.*)"));
 
-  if ( Qfile_name.length() > 0 )
-  {
-    m_uiForm.EventFileName_ledt->setText( Qfile_name );
-    loadEventFileEntered_slot();    // set up the default workspace names
+  if (Qfile_name.length() > 0) {
+    m_uiForm.EventFileName_ledt->setText(Qfile_name);
+    loadEventFileEntered_slot(); // set up the default workspace names
   }
 }
 
-
 /**
  *  Slot called when the Browse button for loading the first ISAW
  *  .DetCal file is pressed on the SelectData tab.
  */
-void MantidEV::selectDetCalFile_slot()
-{
-  QString file_path  = getFilePath( last_cal_file );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                              tr("Load calibration file"),
-                              file_path,
-                              tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)"));
+void MantidEV::selectDetCalFile_slot() {
+  QString file_path = getFilePath(last_cal_file);
+  QString Qfile_name = QFileDialog::getOpenFileName(
+      this, tr("Load calibration file"), file_path,
+      tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)"));
 
-  if ( Qfile_name.length() > 0 )
-  {
-    m_uiForm.CalFileName_ledt->setText( Qfile_name );
+  if (Qfile_name.length() > 0) {
+    m_uiForm.CalFileName_ledt->setText(Qfile_name);
     last_cal_file = Qfile_name.toStdString();
   }
 }
 
-
 /**
  *  Slot called when the Browse button for loading the second ISAW
  *  .DetCal file is pressed on the SelectData tab.
  */
-void MantidEV::selectDetCalFile2_slot()
-{
-  QString file_path  = getFilePath( last_cal_file2 );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                              tr("Load calibration file"),
-                              file_path,
-                              tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)"));
+void MantidEV::selectDetCalFile2_slot() {
+  QString file_path = getFilePath(last_cal_file2);
+  QString Qfile_name = QFileDialog::getOpenFileName(
+      this, tr("Load calibration file"), file_path,
+      tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)"));
 
-  if ( Qfile_name.length() > 0 )
-  {
-    m_uiForm.CalFileName2_ledt->setText( Qfile_name );
+  if (Qfile_name.length() > 0) {
+    m_uiForm.CalFileName2_ledt->setText(Qfile_name);
     last_cal_file2 = Qfile_name.toStdString();
   }
 }
 
-
 /**
  *  Slot called when the Apply button is pressed on the Find Peaks tab.
  */
-void MantidEV::findPeaks_slot()
-{
-   std::string peaks_ws_name = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-   if ( peaks_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
-     return;
-   }
-
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
-
-   bool find_new_peaks     = m_uiForm.FindPeaks_rbtn->isChecked();
-   bool use_existing_peaks = m_uiForm.UseExistingPeaksWorkspace_rbtn->isChecked();
-   bool load_peaks         = m_uiForm.LoadIsawPeaks_rbtn->isChecked();
-
-   if ( find_new_peaks )
-   {
-     std::string md_ws_name  = m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
-     if ( md_ws_name.length() == 0 )
-     {
-       errorMessage("Specify an MD workspace name on Select Data tab.");
-       return;
-     }
-
-     double max_abc       = 15;
-     size_t num_to_find   = 50;
-     double min_intensity = 10;
-
-     if ( !getPositiveDouble( m_uiForm.MaxABC_ledt, max_abc ) )
-       return;
-
-     if ( !getPositiveInt( m_uiForm.NumToFind_ledt, num_to_find ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.MinIntensity_ledt, min_intensity ) )
-       return;
-
-     double minQPeaks;
-     getDouble( m_uiForm.MinQPeaks_ledt, minQPeaks );
-
-     double maxQPeaks;
-     getDouble( m_uiForm.MaxQPeaks_ledt, maxQPeaks );
-
-     std::string ev_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-     RunFindPeaks* runner = new RunFindPeaks( worker, ev_ws_name,
-                                         md_ws_name, peaks_ws_name,
-                                         max_abc, num_to_find, min_intensity,
-                                         minQPeaks, maxQPeaks);
-
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start findPeaks thread...previous operation not complete" );   
-   }
-   else if ( use_existing_peaks )
-   {
-     if ( !worker->isPeaksWorkspace( peaks_ws_name ) )
-     {
-       errorMessage("Requested Peaks Workspace Doesn't Exist");
-     }
-   }
-   else if ( load_peaks )
-   {
-     std::string file_name = m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
-     std::string extension = Poco::Path(file_name).getExtension();
-     if ( file_name.length() == 0 )
-     {
-       errorMessage("Specify a peaks file with the peaks to be loaded.");
-       return;
-     }
-     if (extension.compare("nxs") == 0 || extension.compare("h5") == 0){
-       if ( !worker->loadNexusPeaks( peaks_ws_name, file_name ) ){
-         errorMessage("Could not load requested peaks file");
-       }
-     }
-     else {
-       if ( !worker->loadIsawPeaks( peaks_ws_name, file_name ) )
-       {
-         errorMessage("Could not load requested NeXus file");
-       }
-     }
-   }
+void MantidEV::findPeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
+    errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
+    return;
+  }
+
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
+
+  bool find_new_peaks = m_uiForm.FindPeaks_rbtn->isChecked();
+  bool use_existing_peaks =
+      m_uiForm.UseExistingPeaksWorkspace_rbtn->isChecked();
+  bool load_peaks = m_uiForm.LoadIsawPeaks_rbtn->isChecked();
+
+  if (find_new_peaks) {
+    std::string md_ws_name =
+        m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
+    if (md_ws_name.length() == 0) {
+      errorMessage("Specify an MD workspace name on Select Data tab.");
+      return;
+    }
+
+    double max_abc = 15;
+    size_t num_to_find = 50;
+    double min_intensity = 10;
+
+    if (!getPositiveDouble(m_uiForm.MaxABC_ledt, max_abc))
+      return;
+
+    if (!getPositiveInt(m_uiForm.NumToFind_ledt, num_to_find))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.MinIntensity_ledt, min_intensity))
+      return;
+
+    double minQPeaks;
+    getDouble(m_uiForm.MinQPeaks_ledt, minQPeaks);
+
+    double maxQPeaks;
+    getDouble(m_uiForm.MaxQPeaks_ledt, maxQPeaks);
+
+    std::string ev_ws_name =
+        m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
+    RunFindPeaks *runner =
+        new RunFindPeaks(worker, ev_ws_name, md_ws_name, peaks_ws_name, max_abc,
+                         num_to_find, min_intensity, minQPeaks, maxQPeaks);
+
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage(
+          "Failed to start findPeaks thread...previous operation not complete");
+  } else if (use_existing_peaks) {
+    if (!worker->isPeaksWorkspace(peaks_ws_name)) {
+      errorMessage("Requested Peaks Workspace Doesn't Exist");
+    }
+  } else if (load_peaks) {
+    std::string file_name =
+        m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
+    std::string extension = Poco::Path(file_name).getExtension();
+    if (file_name.length() == 0) {
+      errorMessage("Specify a peaks file with the peaks to be loaded.");
+      return;
+    }
+    if (extension.compare("nxs") == 0 || extension.compare("h5") == 0) {
+      if (!worker->loadNexusPeaks(peaks_ws_name, file_name)) {
+        errorMessage("Could not load requested peaks file");
+      }
+    } else {
+      if (!worker->loadIsawPeaks(peaks_ws_name, file_name)) {
+        errorMessage("Could not load requested NeXus file");
+      }
+    }
+  }
 }
 
 /**
  *  Slot called when the Browse button for loading peaks from a peaks file
  *  is pressed on the FindPeaks tab.
  */
-void MantidEV::getLoadPeaksFileName_slot()
-{
-  QString file_path  = getFilePath( last_peaks_file );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                         tr("Load peaks file"),
-                         file_path,
-                         tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)"));
+void MantidEV::getLoadPeaksFileName_slot() {
+  QString file_path = getFilePath(last_peaks_file);
+  QString Qfile_name = QFileDialog::getOpenFileName(
+      this, tr("Load peaks file"), file_path,
+      tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)"));
 
-  if ( Qfile_name.length()> 0 )
-  {
+  if (Qfile_name.length() > 0) {
     last_peaks_file = Qfile_name.toStdString();
-    m_uiForm.SelectPeaksFile_ledt->setText( Qfile_name );
+    m_uiForm.SelectPeaksFile_ledt->setText(Qfile_name);
   }
 }
 
-
 /**
  *  Utility to pop up a dialog box to get the name of a peaks file to
  *  save.
  */
-void MantidEV::getSavePeaksFileName()
-{
-  QString file_path  = getFilePath( last_peaks_file );
-  QString Qfile_name = QFileDialog::getSaveFileName( this,
-                          tr("Save peaks file"),
-                          file_path,
-                          tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)"),
-                          0, QFileDialog::DontConfirmOverwrite );
-
-  if ( Qfile_name.length() > 0 )
-  {
+void MantidEV::getSavePeaksFileName() {
+  QString file_path = getFilePath(last_peaks_file);
+  QString Qfile_name = QFileDialog::getSaveFileName(
+      this, tr("Save peaks file"), file_path,
+      tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)"), 0,
+      QFileDialog::DontConfirmOverwrite);
+
+  if (Qfile_name.length() > 0) {
     last_peaks_file = Qfile_name.toStdString();
-    m_uiForm.SelectPeaksFile_ledt->setText( Qfile_name );
+    m_uiForm.SelectPeaksFile_ledt->setText(Qfile_name);
   }
 }
 
-
 /**
  *  Slot called when the Apply button is pressed on the Find UB tab
  */
-void MantidEV::findUB_slot()
-{
-   std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-   if ( peaks_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
-     return;
-   }
-
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
-
-   bool use_FFT          = m_uiForm.FindUBUsingFFT_rbtn->isChecked();
-   bool use_IndexedPeaks = m_uiForm.FindUBUsingIndexedPeaks_rbtn->isChecked();
-   bool load_UB          = m_uiForm.LoadISAWUB_rbtn->isChecked();
-   bool index_peaks      = m_uiForm.IndexPeaks_ckbx->isChecked();
-   bool round_hkls       = m_uiForm.RoundHKLs_ckbx->isChecked();
-   bool optimize_angles  = m_uiForm.OptimizeGoniometerAngles_ckbx->isChecked();
-
-   if ( use_FFT )
-   {
-     double min_abc         = 3;
-     double max_abc         = 15;
-     double fft_tolerance   = 0.12;
-
-     if ( !getPositiveDouble( m_uiForm.MinD_ledt, min_abc ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.MaxD_ledt, max_abc ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.FFTTolerance_ledt, fft_tolerance ) )
-       return;
-
-     if (!worker->findUBUsingFFT(peaks_ws_name,min_abc,max_abc,fft_tolerance))
-     {
-       errorMessage( "Find UB Using FFT Failed" );
-       return;
-     }
-   }
-
-   else if ( use_IndexedPeaks )
-   {
-	   double indPeaks_tolerance   = 0.1;
-
-	   if ( !getPositiveDouble( m_uiForm.IndexedPeaksTolerance_ledt, indPeaks_tolerance ) )
-	     return;
-
-     if ( !worker->findUBUsingIndexedPeaks( peaks_ws_name,indPeaks_tolerance) )
-     {
-       errorMessage( "Find UB Using Indexed Peaks Failed" );
-       return;
-     }
-   }
-
-   else if ( load_UB )
-   {
-     std::string file_name = m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
-     if ( file_name.length() == 0 )
-     {
-       errorMessage("Select a .mat file with the UB matrix to be loaded.");
-       return;
-     }
-     else
-     {
-       if ( !worker->loadIsawUB( peaks_ws_name, file_name ) )
-       {
-         errorMessage( "Failed to Load UB Matrix" );
-         return;
-       }
-       if ( optimize_angles )
-       {
-         double max_degrees = 5;
-         if ( getPositiveDouble( m_uiForm.MaxGoniometerChange_ledt,max_degrees) )
-         { 
-           if ( !worker->optimizePhiChiOmega( peaks_ws_name, max_degrees ) )
-           {
-             errorMessage("Failed to Optimize Phi, Chi and Omega");
-             // Don't return here, since we did still change UB by loading it.
-             // proceed to copyLattice, below.
-           }
-         }
-         else
-         {
-           errorMessage( "Enter a POSITIVE number for Maximum Change (degrees)" );
-         }
-       }
-     }
-   }
-                               // Now that we set a UB copy it to md_workspace.  If
-                               // copy fails a log notice is output by copyLattice
-   std::string md_ws_name = m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
-   std::string event_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-   worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
-
-   if ( index_peaks )
-   {
-     double index_tolerance = 0.12;
-     if ( !getPositiveDouble( m_uiForm.IndexingTolerance_ledt, index_tolerance ) )
-       return;
-
-     if ( !worker->indexPeaksWithUB( peaks_ws_name, index_tolerance, round_hkls ) )
-     {
-       errorMessage("Failed to Index Peaks with the Existing UB Matrix");
-     }
-   }
-   bool predict_new_peaks     = m_uiForm.PredictPeaks_ckbx->isChecked();
-
-   if ( predict_new_peaks )
-   {
-	 double min_pred_wl       =          0.4;
-	 double max_pred_wl       =          3.5;
-	 double min_pred_dspacing =          0.4;
-	 double max_pred_dspacing =          8.5;
-
-     if ( !getPositiveDouble( m_uiForm.min_pred_wl_ledt, min_pred_wl ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.max_pred_wl_ledt, max_pred_wl ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.min_pred_dspacing_ledt, min_pred_dspacing ) )
-       return;
-
-     if ( !getPositiveDouble( m_uiForm.max_pred_dspacing_ledt, max_pred_dspacing ) )
-       return;
-
-     RunPredictPeaks* runner = new RunPredictPeaks( worker,
-                                         peaks_ws_name,
-                                         min_pred_wl,
-                                         max_pred_wl,
-                                         min_pred_dspacing,
-                                         max_pred_dspacing );
-
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start predictPeaks thread...previous operation not complete" );
-   }
+void MantidEV::findUB_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
+    errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
+    return;
+  }
 
-}
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
+
+  bool use_FFT = m_uiForm.FindUBUsingFFT_rbtn->isChecked();
+  bool use_IndexedPeaks = m_uiForm.FindUBUsingIndexedPeaks_rbtn->isChecked();
+  bool load_UB = m_uiForm.LoadISAWUB_rbtn->isChecked();
+  bool index_peaks = m_uiForm.IndexPeaks_ckbx->isChecked();
+  bool round_hkls = m_uiForm.RoundHKLs_ckbx->isChecked();
+  bool optimize_angles = m_uiForm.OptimizeGoniometerAngles_ckbx->isChecked();
+
+  if (use_FFT) {
+    double min_abc = 3;
+    double max_abc = 15;
+    double fft_tolerance = 0.12;
+
+    if (!getPositiveDouble(m_uiForm.MinD_ledt, min_abc))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.MaxD_ledt, max_abc))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.FFTTolerance_ledt, fft_tolerance))
+      return;
+
+    if (!worker->findUBUsingFFT(peaks_ws_name, min_abc, max_abc,
+                                fft_tolerance)) {
+      errorMessage("Find UB Using FFT Failed");
+      return;
+    }
+  }
+
+  else if (use_IndexedPeaks) {
+    double indPeaks_tolerance = 0.1;
+
+    if (!getPositiveDouble(m_uiForm.IndexedPeaksTolerance_ledt,
+                           indPeaks_tolerance))
+      return;
+
+    if (!worker->findUBUsingIndexedPeaks(peaks_ws_name, indPeaks_tolerance)) {
+      errorMessage("Find UB Using Indexed Peaks Failed");
+      return;
+    }
+  }
+
+  else if (load_UB) {
+    std::string file_name =
+        m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
+    if (file_name.length() == 0) {
+      errorMessage("Select a .mat file with the UB matrix to be loaded.");
+      return;
+    } else {
+      if (!worker->loadIsawUB(peaks_ws_name, file_name)) {
+        errorMessage("Failed to Load UB Matrix");
+        return;
+      }
+      if (optimize_angles) {
+        double max_degrees = 5;
+        if (getPositiveDouble(m_uiForm.MaxGoniometerChange_ledt, max_degrees)) {
+          if (!worker->optimizePhiChiOmega(peaks_ws_name, max_degrees)) {
+            errorMessage("Failed to Optimize Phi, Chi and Omega");
+            // Don't return here, since we did still change UB by loading it.
+            // proceed to copyLattice, below.
+          }
+        } else {
+          errorMessage("Enter a POSITIVE number for Maximum Change (degrees)");
+        }
+      }
+    }
+  }
+  // Now that we set a UB copy it to md_workspace.  If
+  // copy fails a log notice is output by copyLattice
+  std::string md_ws_name =
+      m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
+  std::string event_ws_name =
+      m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
+  worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
+
+  if (index_peaks) {
+    double index_tolerance = 0.12;
+    if (!getPositiveDouble(m_uiForm.IndexingTolerance_ledt, index_tolerance))
+      return;
+
+    if (!worker->indexPeaksWithUB(peaks_ws_name, index_tolerance, round_hkls)) {
+      errorMessage("Failed to Index Peaks with the Existing UB Matrix");
+    }
+  }
+  bool predict_new_peaks = m_uiForm.PredictPeaks_ckbx->isChecked();
+
+  if (predict_new_peaks) {
+    double min_pred_wl = 0.4;
+    double max_pred_wl = 3.5;
+    double min_pred_dspacing = 0.4;
+    double max_pred_dspacing = 8.5;
+
+    if (!getPositiveDouble(m_uiForm.min_pred_wl_ledt, min_pred_wl))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.max_pred_wl_ledt, max_pred_wl))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.min_pred_dspacing_ledt, min_pred_dspacing))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.max_pred_dspacing_ledt, max_pred_dspacing))
+      return;
+
+    RunPredictPeaks *runner =
+        new RunPredictPeaks(worker, peaks_ws_name, min_pred_wl, max_pred_wl,
+                            min_pred_dspacing, max_pred_dspacing);
 
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage("Failed to start predictPeaks thread...previous operation "
+                   "not complete");
+  }
+}
 
 /**
  *  Slot called when the brows button is pressed for getting the UB file name
  *  to load, on the Find UB tab.
  */
-void MantidEV::getLoadUB_FileName_slot()
-{
-  QString file_path  = getFilePath( last_UB_file );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                         tr("Load matrix file"),
-                         file_path,
-                         tr("Matrix Files (*.mat);; All files(*.*)"));
-  if ( Qfile_name.length()> 0 )
-  {
+void MantidEV::getLoadUB_FileName_slot() {
+  QString file_path = getFilePath(last_UB_file);
+  QString Qfile_name =
+      QFileDialog::getOpenFileName(this, tr("Load matrix file"), file_path,
+                                   tr("Matrix Files (*.mat);; All files(*.*)"));
+  if (Qfile_name.length() > 0) {
     last_UB_file = Qfile_name.toStdString();
-    m_uiForm.SelectUBFile_ledt->setText( Qfile_name );
+    m_uiForm.SelectUBFile_ledt->setText(Qfile_name);
   }
-} 
-
+}
 
 /**
  *  Utility to get the name of a UB file to save.
  */
-void MantidEV::getSaveUB_FileName()
-{
-  QString file_path  = getFilePath( last_UB_file );
-  QString Qfile_name = QFileDialog::getSaveFileName( this,
-                            tr("Save matrix file"),
-                            file_path,
-                            tr("Matrix Files (*.mat);; All files(*.*)"));
+void MantidEV::getSaveUB_FileName() {
+  QString file_path = getFilePath(last_UB_file);
+  QString Qfile_name =
+      QFileDialog::getSaveFileName(this, tr("Save matrix file"), file_path,
+                                   tr("Matrix Files (*.mat);; All files(*.*)"));
 
-  if ( Qfile_name.length() > 0 )
-  {
+  if (Qfile_name.length() > 0) {
     last_UB_file = Qfile_name.toStdString();
-    m_uiForm.SelectUBFile_ledt->setText( Qfile_name );
+    m_uiForm.SelectUBFile_ledt->setText(Qfile_name);
   }
 }
 
-
 /**
  *  Slot called when the apply button is pressed on the Choose Cell tab.
  */
-void MantidEV::chooseCell_slot()
-{
-   std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-   if ( peaks_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
-     return;
-   }
-
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
-
-   bool show_cells       = m_uiForm.ShowPossibleCells_rbtn->isChecked();
-   bool select_cell_type = m_uiForm.SelectCellOfType_rbtn->isChecked();
-   bool select_cell_form = m_uiForm.SelectCellWithForm_rbtn->isChecked();
-   bool allow_perm          = m_uiForm.AllowPermutations_ckbx->isChecked();
-
-   if ( show_cells )
-   {
-     bool best_only          = m_uiForm.BestCellOnly_ckbx->isChecked();
-     double max_scalar_error = 0;
-     if ( !getPositiveDouble( m_uiForm.MaxScalarError_ledt, max_scalar_error ) )
-       return;
-     if ( !worker->showCells( peaks_ws_name, max_scalar_error, best_only, allow_perm ) )
-     {
-       errorMessage("Failed to Show Conventional Cells");
-     }
-   }
-
-   else if ( select_cell_type )
-   {
-     std::string cell_type = m_uiForm.CellType_cmbx->currentText().toStdString();
-     std::string centering = m_uiForm.CellCentering_cmbx->currentText().toStdString();
-     if ( !worker->selectCellOfType( peaks_ws_name, cell_type, centering, allow_perm ) )
-     {
-       errorMessage("Failed to Select Specified Conventional Cell");
-     }
-   }
-
-   else if ( select_cell_form )
-   {
-     std::string form = m_uiForm.CellFormNumber_cmbx->currentText().toStdString();
-     double form_num = 0;
-     getDouble( form, form_num );
-     if ( !worker->selectCellWithForm( peaks_ws_name, (size_t)form_num, allow_perm ) )
-     {
-       errorMessage("Failed to Select the Requested Form Number");
-     }
-   }
-
-   if ( select_cell_type || select_cell_form )
-   {                                 // Try to copy the UB to md_workspace.  If it
-                                     // fails a log notice is output by copyLattice
-     std::string md_ws_name = m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
-     std::string event_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-     worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
-   }
-}
+void MantidEV::chooseCell_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
+    errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
+    return;
+  }
+
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
+
+  bool show_cells = m_uiForm.ShowPossibleCells_rbtn->isChecked();
+  bool select_cell_type = m_uiForm.SelectCellOfType_rbtn->isChecked();
+  bool select_cell_form = m_uiForm.SelectCellWithForm_rbtn->isChecked();
+  bool allow_perm = m_uiForm.AllowPermutations_ckbx->isChecked();
 
+  if (show_cells) {
+    bool best_only = m_uiForm.BestCellOnly_ckbx->isChecked();
+    double max_scalar_error = 0;
+    if (!getPositiveDouble(m_uiForm.MaxScalarError_ledt, max_scalar_error))
+      return;
+    if (!worker->showCells(peaks_ws_name, max_scalar_error, best_only,
+                           allow_perm)) {
+      errorMessage("Failed to Show Conventional Cells");
+    }
+  }
+
+  else if (select_cell_type) {
+    std::string cell_type = m_uiForm.CellType_cmbx->currentText().toStdString();
+    std::string centering =
+        m_uiForm.CellCentering_cmbx->currentText().toStdString();
+    if (!worker->selectCellOfType(peaks_ws_name, cell_type, centering,
+                                  allow_perm)) {
+      errorMessage("Failed to Select Specified Conventional Cell");
+    }
+  }
+
+  else if (select_cell_form) {
+    std::string form =
+        m_uiForm.CellFormNumber_cmbx->currentText().toStdString();
+    double form_num = 0;
+    getDouble(form, form_num);
+    if (!worker->selectCellWithForm(peaks_ws_name, (size_t)form_num,
+                                    allow_perm)) {
+      errorMessage("Failed to Select the Requested Form Number");
+    }
+  }
+
+  if (select_cell_type ||
+      select_cell_form) { // Try to copy the UB to md_workspace.  If it
+                          // fails a log notice is output by copyLattice
+    std::string md_ws_name =
+        m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
+    std::string event_ws_name =
+        m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
+    worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
+  }
+}
 
 /**
  *  Slot called when the Apply button is pressed on the Change HKL tab.
  */
-void MantidEV::changeHKL_slot()
-{
-   std::string peaks_ws_name = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-   if ( peaks_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
-     return;
-   }
+void MantidEV::changeHKL_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
+    errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
+    return;
+  }
 
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
 
-   std::string row_1_str = m_uiForm.HKL_tran_row_1_ledt->text().toStdString();
-   std::string row_2_str = m_uiForm.HKL_tran_row_2_ledt->text().toStdString();
-   std::string row_3_str = m_uiForm.HKL_tran_row_3_ledt->text().toStdString();
+  std::string row_1_str = m_uiForm.HKL_tran_row_1_ledt->text().toStdString();
+  std::string row_2_str = m_uiForm.HKL_tran_row_2_ledt->text().toStdString();
+  std::string row_3_str = m_uiForm.HKL_tran_row_3_ledt->text().toStdString();
 
-   if ( !worker->changeHKL( peaks_ws_name, row_1_str, row_2_str, row_3_str ) )
-   {
-     errorMessage( "Failed to Change the Miller Indicies and UB" );
-   }
+  if (!worker->changeHKL(peaks_ws_name, row_1_str, row_2_str, row_3_str)) {
+    errorMessage("Failed to Change the Miller Indicies and UB");
+  }
 
-                                     // Try to copy the UB to md_workspace.  If it
-                                     // fails a log notice is output by copyLattice
-   std::string md_ws_name = m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
-   std::string event_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-   worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
+  // Try to copy the UB to md_workspace.  If it
+  // fails a log notice is output by copyLattice
+  std::string md_ws_name =
+      m_uiForm.MDworkspace_ledt->text().trimmed().toStdString();
+  std::string event_ws_name =
+      m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
+  worker->copyLattice(peaks_ws_name, md_ws_name, event_ws_name);
 }
 
-
 /**
  *  Slot called when the Apply button is pressed on the Integrate tab.
  */
-void MantidEV::integratePeaks_slot()
-{
-   std::string peaks_ws_name = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-
-   if ( peaks_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
-     return;
-   }
-
-   std::string event_ws_name = m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
-   if ( event_ws_name.length() == 0 )
-   {
-     errorMessage("Specify a time-of-flight event workspace name.");
-     return;
-   }
-
-   if ( m_thread_pool->activeThreadCount() >= 1 )
-   {
-     errorMessage("Previous operation still running, please wait until it is finished");
-     return;
-   }
-
-   bool sphere_integrate    = m_uiForm.SphereIntegration_rbtn->isChecked();
-   bool fit_integrate       = m_uiForm.TwoDFitIntegration_rbtn->isChecked();
-   bool ellipsoid_integrate = m_uiForm.EllipsoidIntegration_rbtn->isChecked();
-   bool use_cylinder_integration = m_uiForm.Cylinder_ckbx->isChecked();
-
-   if ( sphere_integrate || use_cylinder_integration)
-   {
-     double peak_radius    = 0.20;
-     double inner_radius   = 0.20;
-     double outer_radius   = 0.25;
-     double cylinder_length = 0.0;
-     double cylinder_percent_bkg = 0.0;
-
-     if ( !getPositiveDouble( m_uiForm.PeakRadius_ledt, peak_radius ) )
-       return;
-
-     if ( !getPositiveDouble(m_uiForm.BackgroundInnerRadius_ledt, inner_radius))
-       return;
-
-     if ( !getPositiveDouble(m_uiForm.BackgroundOuterRadius_ledt, outer_radius))
-       return;
-
-     bool integrate_edge = m_uiForm.IntegrateEdge_ckbx->isChecked();
-
-     if ( !getPositiveDouble(m_uiForm.CylinderLength_ledt, cylinder_length))
-            return;
-
-     if ( !getPositiveDouble(m_uiForm.CylinderPercentBkg_ledt, cylinder_percent_bkg))
-            return;
-
-     std::string cylinder_profile_fit = m_uiForm.CylinderProfileFit_cmbx->currentText().toStdString();
-
-     RunSphereIntegrate * runner = new RunSphereIntegrate( worker,
-                                        peaks_ws_name, event_ws_name,
-                                        peak_radius, inner_radius, outer_radius,
-                                        integrate_edge, use_cylinder_integration,
-                                        cylinder_length, cylinder_percent_bkg,
-                                        cylinder_profile_fit);
-
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start sphere integrate thread...previous operation not complete" );
-   }
-   else if ( fit_integrate )
-   {
-     bool use_ikeda_carpenter = m_uiForm.IkedaCarpenter_ckbx->isChecked();
-     std::string rebin_params = m_uiForm.FitRebinParams_ledt->text().toStdString();
-     double n_bad_edge_pix = 5;
-     if ( !getPositiveDouble( m_uiForm.NBadEdgePixels_ledt, n_bad_edge_pix ) )
-       return;
-
-     RunFitIntegrate * runner = new RunFitIntegrate( worker,
-                                              peaks_ws_name, event_ws_name,
-                                              rebin_params, 
-                                              (size_t)n_bad_edge_pix,
-                                              use_ikeda_carpenter );
-
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start sphere integrate thread...previous operation not complete" );
-   }
-   else if ( ellipsoid_integrate )
-   {
-     double region_radius  = 0.20;
-     if ( !getPositiveDouble( m_uiForm.RegionRadius_ledt, region_radius ) )
-       return;
-
-     double peak_size  = 0.20;
-     double inner_size = 0.20;
-     double outer_size = 0.25;
-     bool specify_size = m_uiForm.SpecifySize_ckbx->isChecked();
-     if ( specify_size )
-     {
-       if ( !getPositiveDouble( m_uiForm.PeakSize_ledt, peak_size ) )
-         return;
-
-       if ( !getPositiveDouble(m_uiForm.BackgroundInnerSize_ledt, inner_size) )
-         return;
-
-       if ( !getPositiveDouble(m_uiForm.BackgroundOuterSize_ledt, outer_size) )
-         return;
-     }
-
-     RunEllipsoidIntegrate * runner = new RunEllipsoidIntegrate( worker,
-                                            peaks_ws_name, event_ws_name,
-                                            region_radius, specify_size,
-                                            peak_size, inner_size, outer_size );
-
-     bool running = m_thread_pool->tryStart( runner );
-     if ( !running )
-       errorMessage( "Failed to start sphere integrate thread...previous operation not complete" );
-   }
-}
+void MantidEV::integratePeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+
+  if (peaks_ws_name.length() == 0) {
+    errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
+    return;
+  }
+
+  std::string event_ws_name =
+      m_uiForm.SelectEventWorkspace_ledt->text().trimmed().toStdString();
+  if (event_ws_name.length() == 0) {
+    errorMessage("Specify a time-of-flight event workspace name.");
+    return;
+  }
+
+  if (m_thread_pool->activeThreadCount() >= 1) {
+    errorMessage(
+        "Previous operation still running, please wait until it is finished");
+    return;
+  }
 
+  bool sphere_integrate = m_uiForm.SphereIntegration_rbtn->isChecked();
+  bool fit_integrate = m_uiForm.TwoDFitIntegration_rbtn->isChecked();
+  bool ellipsoid_integrate = m_uiForm.EllipsoidIntegration_rbtn->isChecked();
+  bool use_cylinder_integration = m_uiForm.Cylinder_ckbx->isChecked();
+
+  if (sphere_integrate || use_cylinder_integration) {
+    double peak_radius = 0.20;
+    double inner_radius = 0.20;
+    double outer_radius = 0.25;
+    double cylinder_length = 0.0;
+    double cylinder_percent_bkg = 0.0;
+
+    if (!getPositiveDouble(m_uiForm.PeakRadius_ledt, peak_radius))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.BackgroundInnerRadius_ledt, inner_radius))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.BackgroundOuterRadius_ledt, outer_radius))
+      return;
+
+    bool integrate_edge = m_uiForm.IntegrateEdge_ckbx->isChecked();
+
+    if (!getPositiveDouble(m_uiForm.CylinderLength_ledt, cylinder_length))
+      return;
+
+    if (!getPositiveDouble(m_uiForm.CylinderPercentBkg_ledt,
+                           cylinder_percent_bkg))
+      return;
+
+    std::string cylinder_profile_fit =
+        m_uiForm.CylinderProfileFit_cmbx->currentText().toStdString();
+
+    RunSphereIntegrate *runner = new RunSphereIntegrate(
+        worker, peaks_ws_name, event_ws_name, peak_radius, inner_radius,
+        outer_radius, integrate_edge, use_cylinder_integration, cylinder_length,
+        cylinder_percent_bkg, cylinder_profile_fit);
+
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage("Failed to start sphere integrate thread...previous "
+                   "operation not complete");
+  } else if (fit_integrate) {
+    bool use_ikeda_carpenter = m_uiForm.IkedaCarpenter_ckbx->isChecked();
+    std::string rebin_params =
+        m_uiForm.FitRebinParams_ledt->text().toStdString();
+    double n_bad_edge_pix = 5;
+    if (!getPositiveDouble(m_uiForm.NBadEdgePixels_ledt, n_bad_edge_pix))
+      return;
+
+    RunFitIntegrate *runner =
+        new RunFitIntegrate(worker, peaks_ws_name, event_ws_name, rebin_params,
+                            (size_t)n_bad_edge_pix, use_ikeda_carpenter);
+
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage("Failed to start sphere integrate thread...previous "
+                   "operation not complete");
+  } else if (ellipsoid_integrate) {
+    double region_radius = 0.20;
+    if (!getPositiveDouble(m_uiForm.RegionRadius_ledt, region_radius))
+      return;
+
+    double peak_size = 0.20;
+    double inner_size = 0.20;
+    double outer_size = 0.25;
+    bool specify_size = m_uiForm.SpecifySize_ckbx->isChecked();
+    if (specify_size) {
+      if (!getPositiveDouble(m_uiForm.PeakSize_ledt, peak_size))
+        return;
+
+      if (!getPositiveDouble(m_uiForm.BackgroundInnerSize_ledt, inner_size))
+        return;
+
+      if (!getPositiveDouble(m_uiForm.BackgroundOuterSize_ledt, outer_size))
+        return;
+    }
+
+    RunEllipsoidIntegrate *runner = new RunEllipsoidIntegrate(
+        worker, peaks_ws_name, event_ws_name, region_radius, specify_size,
+        peak_size, inner_size, outer_size);
+
+    bool running = m_thread_pool->tryStart(runner);
+    if (!running)
+      errorMessage("Failed to start sphere integrate thread...previous "
+                   "operation not complete");
+  }
+}
 
 /**
  *  Slot called when Show Info button is pressed
  */
-void MantidEV::showInfo_slot()
-{
-   double qx = 0.0;
-   double qy = 0.0;
-   double qz = 0.0;
-   getDouble( m_uiForm.Qx_ledt, qx );
-   getDouble( m_uiForm.Qy_ledt, qy );
-   getDouble( m_uiForm.Qz_ledt, qz );
+void MantidEV::showInfo_slot() {
+  double qx = 0.0;
+  double qy = 0.0;
+  double qz = 0.0;
+  getDouble(m_uiForm.Qx_ledt, qx);
+  getDouble(m_uiForm.Qy_ledt, qy);
+  getDouble(m_uiForm.Qz_ledt, qz);
 
-   /// loop back test of SelectionNotificationService
-   MantidQt::API::SelectionNotificationService::Instance().sendQPointSelection( true, qx, qy, qz );
+  /// loop back test of SelectionNotificationService
+  MantidQt::API::SelectionNotificationService::Instance().sendQPointSelection(
+      true, qx, qy, qz);
 }
 
-
 /**
  *  This slot is connected to the QPointSelection signal, which will be emitted
  *  when a QPoint is selected by some participating object.
@@ -1285,13 +1187,12 @@ void MantidEV::showInfo_slot()
  *  @param qy           The y-component of the Mantid Q-vector.
  *  @param qz           The z-component of the Mantid Q-vector.
  */
-void MantidEV::QPointSelection_slot( bool lab_coords, double qx, double qy, double qz )
-{
-  Mantid::Kernel::V3D q_point( qx, qy, qz );
-  showInfo( lab_coords, q_point );
+void MantidEV::QPointSelection_slot(bool lab_coords, double qx, double qy,
+                                    double qz) {
+  Mantid::Kernel::V3D q_point(qx, qy, qz);
+  showInfo(lab_coords, q_point);
 }
 
-
 /**
  *  Use the peaks workspace to get information about the specified
  *  Q-vector.
@@ -1300,227 +1201,204 @@ void MantidEV::QPointSelection_slot( bool lab_coords, double qx, double qy, doub
  *                      and false if they are in sample coordinates.
  *  @param  q_point     Vector containing the Q-coordinates.
  */
-void MantidEV::showInfo( bool lab_coords, Mantid::Kernel::V3D  q_point )
-{
-   std::string peaks_ws_name = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-
-   std::vector< std::pair< std::string, std::string > > info;
-
-   if ( !worker->isPeaksWorkspace( peaks_ws_name ) )  // just show the Q vector
-   {
-     errorMessage("NOTE: Peaks Workspace Doesn't Exist");
-     if ( lab_coords )
-     {
-       std::pair<std::string, std::string> QlabStr("Qlab", boost::lexical_cast<std::string>(q_point));
-       info.push_back( QlabStr );
-     }
-     else
-     {
-       std::pair<std::string, std::string> QSampleStr("QSample", boost::lexical_cast<std::string>(q_point));
-       info.push_back( QSampleStr );
-     }
-   }
-   else   // get the info from the peaks workspace
-   {
-     info = worker->PointInfo( peaks_ws_name, lab_coords, q_point );
-   }
-
-   double q_dist = ( q_point - last_Q ).norm();
-   std::pair<std::string, std::string> Q_dist_str("|Q2-Q1|", boost::lexical_cast<std::string>(q_dist));
-   info.push_back( Q_dist_str );
-
-   Mantid::Kernel::Matrix<double> UB(3,3,false);
-   if ( worker->getUB( peaks_ws_name, lab_coords, UB ) ) // if the peaks workspace has a UB, also find the
-   {                                                     // distance between points in HKL.
-     Mantid::Kernel::Matrix<double> UBinv( UB ); 
-     UBinv.Invert();
-     Mantid::Kernel::V3D  hkl_1 = UBinv * last_Q;
-     Mantid::Kernel::V3D  hkl_2 = UBinv * q_point;
-     hkl_1 = hkl_1 / (2 * M_PI); 
-     hkl_2 = hkl_2 / (2 * M_PI);
-     double hkl_dist = (hkl_2 - hkl_1).norm();
-     std::pair<std::string, std::string> hkl_dist_str("|hkl2-hkl1|", boost::lexical_cast<std::string>(hkl_dist));
-     info.push_back( hkl_dist_str );
-   }
-
-   last_Q = q_point;
-   
-   m_uiForm.SelectedPoint_tbl->setRowCount((int)info.size());
-   m_uiForm.SelectedPoint_tbl->setColumnCount(2);
-   m_uiForm.SelectedPoint_tbl->verticalHeader()->hide();
-   m_uiForm.SelectedPoint_tbl->horizontalHeader()->hide();
-
-   for ( size_t row = 0; row < info.size(); row++ )
-   {
-     QString first_str = QString::fromStdString( info[row].first );
-     QTableWidgetItem *item = new QTableWidgetItem( first_str );
-     m_uiForm.SelectedPoint_tbl->setItem( (int)row, 0, item );
-     QString second_str = QString::fromStdString( info[row].second );
-     item = new QTableWidgetItem( second_str );
-     m_uiForm.SelectedPoint_tbl->setItem( (int)row, 1, item );
-   }
-   m_uiForm.SelectedPoint_tbl->resizeColumnToContents(0);
-   m_uiForm.SelectedPoint_tbl->resizeColumnToContents(1);
-}
+void MantidEV::showInfo(bool lab_coords, Mantid::Kernel::V3D q_point) {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+
+  std::vector<std::pair<std::string, std::string>> info;
+
+  if (!worker->isPeaksWorkspace(peaks_ws_name)) // just show the Q vector
+  {
+    errorMessage("NOTE: Peaks Workspace Doesn't Exist");
+    if (lab_coords) {
+      std::pair<std::string, std::string> QlabStr(
+          "Qlab", boost::lexical_cast<std::string>(q_point));
+      info.push_back(QlabStr);
+    } else {
+      std::pair<std::string, std::string> QSampleStr(
+          "QSample", boost::lexical_cast<std::string>(q_point));
+      info.push_back(QSampleStr);
+    }
+  } else // get the info from the peaks workspace
+  {
+    info = worker->PointInfo(peaks_ws_name, lab_coords, q_point);
+  }
+
+  double q_dist = (q_point - last_Q).norm();
+  std::pair<std::string, std::string> Q_dist_str(
+      "|Q2-Q1|", boost::lexical_cast<std::string>(q_dist));
+  info.push_back(Q_dist_str);
+
+  Mantid::Kernel::Matrix<double> UB(3, 3, false);
+  if (worker->getUB(peaks_ws_name, lab_coords,
+                    UB)) // if the peaks workspace has a UB, also find the
+  {                      // distance between points in HKL.
+    Mantid::Kernel::Matrix<double> UBinv(UB);
+    UBinv.Invert();
+    Mantid::Kernel::V3D hkl_1 = UBinv * last_Q;
+    Mantid::Kernel::V3D hkl_2 = UBinv * q_point;
+    hkl_1 = hkl_1 / (2 * M_PI);
+    hkl_2 = hkl_2 / (2 * M_PI);
+    double hkl_dist = (hkl_2 - hkl_1).norm();
+    std::pair<std::string, std::string> hkl_dist_str(
+        "|hkl2-hkl1|", boost::lexical_cast<std::string>(hkl_dist));
+    info.push_back(hkl_dist_str);
+  }
+
+  last_Q = q_point;
 
+  m_uiForm.SelectedPoint_tbl->setRowCount((int)info.size());
+  m_uiForm.SelectedPoint_tbl->setColumnCount(2);
+  m_uiForm.SelectedPoint_tbl->verticalHeader()->hide();
+  m_uiForm.SelectedPoint_tbl->horizontalHeader()->hide();
+
+  for (size_t row = 0; row < info.size(); row++) {
+    QString first_str = QString::fromStdString(info[row].first);
+    QTableWidgetItem *item = new QTableWidgetItem(first_str);
+    m_uiForm.SelectedPoint_tbl->setItem((int)row, 0, item);
+    QString second_str = QString::fromStdString(info[row].second);
+    item = new QTableWidgetItem(second_str);
+    m_uiForm.SelectedPoint_tbl->setItem((int)row, 1, item);
+  }
+  m_uiForm.SelectedPoint_tbl->resizeColumnToContents(0);
+  m_uiForm.SelectedPoint_tbl->resizeColumnToContents(1);
+}
 
 /**
  *  Slot called when the Save Settings action is selected from the File menu.
  */
-void MantidEV::saveState_slot()
-{
-  QString file_path  = getFilePath( last_ini_file );
-  QString Qfile_name = QFileDialog::getSaveFileName( this,
-                          tr("Save Settings File(.ini)"),
-                          file_path,
-                          tr("Settings Files (*.ini);; All files(*.*) "));
+void MantidEV::saveState_slot() {
+  QString file_path = getFilePath(last_ini_file);
+  QString Qfile_name = QFileDialog::getSaveFileName(
+      this, tr("Save Settings File(.ini)"), file_path,
+      tr("Settings Files (*.ini);; All files(*.*) "));
 
-  if ( Qfile_name.length() > 0 )
-  {
+  if (Qfile_name.length() > 0) {
     last_ini_file = Qfile_name.toStdString();
-    saveSettings( last_ini_file );
+    saveSettings(last_ini_file);
   }
-
 }
 
-
 /**
  *  Slot called when the Load Settings action is selected from the File menu.
  */
-void MantidEV::loadState_slot()
-{
-  QString file_path  = getFilePath( last_ini_file );
-  QString Qfile_name = QFileDialog::getOpenFileName( this,
-                         tr("Load Settings File(.ini)"),
-                         file_path,
-                         tr("Settings Files (*.ini);; All files(*.*)"));
+void MantidEV::loadState_slot() {
+  QString file_path = getFilePath(last_ini_file);
+  QString Qfile_name = QFileDialog::getOpenFileName(
+      this, tr("Load Settings File(.ini)"), file_path,
+      tr("Settings Files (*.ini);; All files(*.*)"));
 
-  if ( Qfile_name.length()> 0 )
-  {
+  if (Qfile_name.length() > 0) {
     last_ini_file = Qfile_name.toStdString();
-    loadSettings( last_ini_file );
+    loadSettings(last_ini_file);
   }
 }
 
-
 /**
  *  Slot called when the Save Isaw UB action is selected from the File menu.
  */
-void MantidEV::saveIsawUB_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::saveIsawUB_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getSaveUB_FileName();
 
-  std::string file_name = m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Select a .mat file with the UB matrix to be loaded.");
-     return;
-  }
-  else
-  {
-    if ( !worker->saveIsawUB( peaks_ws_name, file_name ) )
-    {
-      errorMessage( "Failed to Save UB Matrix" );
+  std::string file_name =
+      m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Select a .mat file with the UB matrix to be loaded.");
+    return;
+  } else {
+    if (!worker->saveIsawUB(peaks_ws_name, file_name)) {
+      errorMessage("Failed to Save UB Matrix");
       return;
     }
   }
 }
 
-
 /**
  *  Slot called when the Load Isaw UB action is selected from the File menu.
  */
-void MantidEV::loadIsawUB_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::loadIsawUB_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getLoadUB_FileName_slot();
 
-  std::string file_name = m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Select a .mat file with the UB matrix to be loaded.");
-     return;
-  }
-  else
-  {
-    if ( !worker->loadIsawUB( peaks_ws_name, file_name ) )
-    {
-      errorMessage( "Failed to Load UB Matrix" );
+  std::string file_name =
+      m_uiForm.SelectUBFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Select a .mat file with the UB matrix to be loaded.");
+    return;
+  } else {
+    if (!worker->loadIsawUB(peaks_ws_name, file_name)) {
+      errorMessage("Failed to Load UB Matrix");
       return;
     }
   }
 }
 
-
 /**
  *  Slot called when the Save Isaw Peaks action is selected from the File menu.
  */
-void MantidEV::saveIsawPeaks_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::saveIsawPeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getSavePeaksFileName();
 
-  std::string file_name = m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Specify a peaks file name for saving the peaks workspace.");
-     return;
-  }
-  else
-  {
-                              // if the file exists, check for overwrite or append
+  std::string file_name =
+      m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Specify a peaks file name for saving the peaks workspace.");
+    return;
+  } else {
+    // if the file exists, check for overwrite or append
     bool append = false;
-    QFile peaks_file( QString::fromStdString( file_name ) );
-    if ( peaks_file.exists() )
-    {
-      QMessageBox message_box( this->window() );
-      message_box.setText( tr("File Exists") );
+    QFile peaks_file(QString::fromStdString(file_name));
+    if (peaks_file.exists()) {
+      QMessageBox message_box(this->window());
+      message_box.setText(tr("File Exists"));
       message_box.setInformativeText("Replace file, or append peaks to file?");
-      QAbstractButton *replace_btn = message_box.addButton( tr("Replace"), QMessageBox::NoRole );
-      QAbstractButton *append_btn  = message_box.addButton( tr("Append"),  QMessageBox::YesRole );
-      message_box.setIcon( QMessageBox::Question );
-                                                   // it should not be necessary to do the next
-                                                   // four lines, but without them the message box
-                                                   // appears at random locations on RHEL 6
-      message_box.show();                               
-      QSize box_size = message_box.sizeHint(); 
+      QAbstractButton *replace_btn =
+          message_box.addButton(tr("Replace"), QMessageBox::NoRole);
+      QAbstractButton *append_btn =
+          message_box.addButton(tr("Append"), QMessageBox::YesRole);
+      message_box.setIcon(QMessageBox::Question);
+      // it should not be necessary to do the next
+      // four lines, but without them the message box
+      // appears at random locations on RHEL 6
+      message_box.show();
+      QSize box_size = message_box.sizeHint();
       QRect screen_rect = QDesktopWidget().screen()->rect();
-      message_box.move( QPoint( screen_rect.width()/2 - box_size.width()/2, 
-                                screen_rect.height()/2 - box_size.height()/2 ) );
+      message_box.move(
+          QPoint(screen_rect.width() / 2 - box_size.width() / 2,
+                 screen_rect.height() / 2 - box_size.height() / 2));
       message_box.exec();
- 
-      if ( message_box.clickedButton() == append_btn )
-      {
+
+      if (message_box.clickedButton() == append_btn) {
         append = true;
-      } 
-      else if ( message_box.clickedButton() == replace_btn )  // no strictly needed, but clearer
+      } else if (message_box.clickedButton() ==
+                 replace_btn) // no strictly needed, but clearer
       {
         append = false;
       }
     }
 
-    if ( !worker->saveIsawPeaks( peaks_ws_name, file_name, append ) )
-    {
-      errorMessage( "Failed to save peaks to file" );
+    if (!worker->saveIsawPeaks(peaks_ws_name, file_name, append)) {
+      errorMessage("Failed to save peaks to file");
       return;
     }
   }
@@ -1529,90 +1407,82 @@ void MantidEV::saveIsawPeaks_slot()
 /**
  *  Slot called when the Save Nexus Peaks action is selected from the File menu.
  */
-void MantidEV::saveNexusPeaks_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::saveNexusPeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getSavePeaksFileName();
 
-  std::string file_name = m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Specify a peaks file name for saving the peaks workspace.");
-     return;
-  }
-  else
-  {
-                              // if the file exists, check for overwrite or append
+  std::string file_name =
+      m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Specify a peaks file name for saving the peaks workspace.");
+    return;
+  } else {
+    // if the file exists, check for overwrite or append
     bool append = false;
-    QFile peaks_file( QString::fromStdString( file_name ) );
-    if ( peaks_file.exists() )
-    {
-      QMessageBox message_box( this->window() );
-      message_box.setText( tr("File Exists") );
+    QFile peaks_file(QString::fromStdString(file_name));
+    if (peaks_file.exists()) {
+      QMessageBox message_box(this->window());
+      message_box.setText(tr("File Exists"));
       message_box.setInformativeText("Replace file, or append peaks to file?");
-      QAbstractButton *replace_btn = message_box.addButton( tr("Replace"), QMessageBox::NoRole );
-      QAbstractButton *append_btn  = message_box.addButton( tr("Append"),  QMessageBox::YesRole );
-      message_box.setIcon( QMessageBox::Question );
-                                                   // it should not be necessary to do the next
-                                                   // four lines, but without them the message box
-                                                   // appears at random locations on RHEL 6
+      QAbstractButton *replace_btn =
+          message_box.addButton(tr("Replace"), QMessageBox::NoRole);
+      QAbstractButton *append_btn =
+          message_box.addButton(tr("Append"), QMessageBox::YesRole);
+      message_box.setIcon(QMessageBox::Question);
+      // it should not be necessary to do the next
+      // four lines, but without them the message box
+      // appears at random locations on RHEL 6
       message_box.show();
       QSize box_size = message_box.sizeHint();
       QRect screen_rect = QDesktopWidget().screen()->rect();
-      message_box.move( QPoint( screen_rect.width()/2 - box_size.width()/2,
-                                screen_rect.height()/2 - box_size.height()/2 ) );
+      message_box.move(
+          QPoint(screen_rect.width() / 2 - box_size.width() / 2,
+                 screen_rect.height() / 2 - box_size.height() / 2));
       message_box.exec();
 
-      if ( message_box.clickedButton() == append_btn )
-      {
+      if (message_box.clickedButton() == append_btn) {
         append = true;
-      }
-      else if ( message_box.clickedButton() == replace_btn )  // no strictly needed, but clearer
+      } else if (message_box.clickedButton() ==
+                 replace_btn) // no strictly needed, but clearer
       {
         append = false;
       }
     }
 
-    if ( !worker->saveNexusPeaks( peaks_ws_name, file_name, append ) )
-    {
-      errorMessage( "Failed to save peaks to file" );
+    if (!worker->saveNexusPeaks(peaks_ws_name, file_name, append)) {
+      errorMessage("Failed to save peaks to file");
       return;
     }
   }
 }
 
-
 /**
  *  Slot called when the Load Isaw Peaks action is selected from the File menu.
  */
-void MantidEV::loadIsawPeaks_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::loadIsawPeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getLoadPeaksFileName_slot();
 
-  std::string file_name = m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Select a peaks file to be loaded.");
-     return;
-  }
-  else
-  {
-    if ( !worker->loadIsawPeaks( peaks_ws_name, file_name ) )
-    {
-      errorMessage( "Failed to Load Peaks File" );
+  std::string file_name =
+      m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Select a peaks file to be loaded.");
+    return;
+  } else {
+    if (!worker->loadIsawPeaks(peaks_ws_name, file_name)) {
+      errorMessage("Failed to Load Peaks File");
       return;
     }
   }
@@ -1621,98 +1491,86 @@ void MantidEV::loadIsawPeaks_slot()
 /**
  *  Slot called when the Load Nexus Peaks action is selected from the File menu.
  */
-void MantidEV::loadNexusPeaks_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::loadNexusPeaks_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
   getLoadPeaksFileName_slot();
 
-  std::string file_name = m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
-  if ( file_name.length() == 0 )
-  {
-     errorMessage("Select a peaks file to be loaded.");
-     return;
-  }
-  else
-  {
-    if ( !worker->loadNexusPeaks( peaks_ws_name, file_name ) )
-    {
-      errorMessage( "Failed to Load Peaks File" );
+  std::string file_name =
+      m_uiForm.SelectPeaksFile_ledt->text().trimmed().toStdString();
+  if (file_name.length() == 0) {
+    errorMessage("Select a peaks file to be loaded.");
+    return;
+  } else {
+    if (!worker->loadNexusPeaks(peaks_ws_name, file_name)) {
+      errorMessage("Failed to Load Peaks File");
       return;
     }
   }
 }
 
-
 /**
  *  Slot called when the Show UB action is selected from the View menu.
  */
-void MantidEV::showUB_slot()
-{
-  std::string peaks_ws_name  = m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
-  if ( peaks_ws_name.length() == 0 )
-  {
+void MantidEV::showUB_slot() {
+  std::string peaks_ws_name =
+      m_uiForm.PeaksWorkspace_ledt->text().trimmed().toStdString();
+  if (peaks_ws_name.length() == 0) {
     errorMessage("Specify a peaks workspace name on the Find Peaks tab.");
     return;
   }
 
-  if ( !worker->showUB( peaks_ws_name ) )
+  if (!worker->showUB(peaks_ws_name))
     errorMessage("The specified workspace does not have a UB matrix");
 }
 
-
 /**
  * Set the enabled state of the load event file components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledLoadEventFileParams_slot( bool on )
-{
+void MantidEV::setEnabledLoadEventFileParams_slot(bool on) {
   m_uiForm.loadDataGroupBox->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the calibration file labels,
- * line edits and browse buttons based on the state of the 
+ * line edits and browse buttons based on the state of the
  * load from event file and load ISAW detector calibration
  * buttons.
  *
  */
-void MantidEV::setEnabledLoadCalFiles_slot()
-{
+void MantidEV::setEnabledLoadCalFiles_slot() {
   bool enabled = m_uiForm.LoadDetCal_ckbx->isChecked();
-  m_uiForm.CalFileName_lbl->setEnabled( enabled );
-  m_uiForm.CalFileName_ledt->setEnabled( enabled );
-  m_uiForm.SelectCalFile_btn->setEnabled( enabled );
-  m_uiForm.CalFileName2_lbl->setEnabled( enabled );
-  m_uiForm.CalFileName2_ledt->setEnabled( enabled );
-  m_uiForm.SelectCalFile2_btn->setEnabled( enabled );
+  m_uiForm.CalFileName_lbl->setEnabled(enabled);
+  m_uiForm.CalFileName_ledt->setEnabled(enabled);
+  m_uiForm.SelectCalFile_btn->setEnabled(enabled);
+  m_uiForm.CalFileName2_lbl->setEnabled(enabled);
+  m_uiForm.CalFileName2_ledt->setEnabled(enabled);
+  m_uiForm.SelectCalFile2_btn->setEnabled(enabled);
 }
 
-
 /**
  * Set the enabled state of the load find peaks components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledFindPeaksParams_slot( bool on )
-{
-  m_uiForm.MaxABC_lbl->setEnabled( on );
-  m_uiForm.MaxABC_ledt->setEnabled( on );
-  m_uiForm.NumToFind_lbl->setEnabled( on );
-  m_uiForm.NumToFind_ledt->setEnabled( on );
-  m_uiForm.MinIntensity_lbl->setEnabled( on );
-  m_uiForm.MinIntensity_ledt->setEnabled( on );
-  m_uiForm.MinQPeaks_ledt->setEnabled( on );
-  m_uiForm.MaxQPeaks_ledt->setEnabled( on );
+void MantidEV::setEnabledFindPeaksParams_slot(bool on) {
+  m_uiForm.MaxABC_lbl->setEnabled(on);
+  m_uiForm.MaxABC_ledt->setEnabled(on);
+  m_uiForm.NumToFind_lbl->setEnabled(on);
+  m_uiForm.NumToFind_ledt->setEnabled(on);
+  m_uiForm.MinIntensity_lbl->setEnabled(on);
+  m_uiForm.MinIntensity_ledt->setEnabled(on);
+  m_uiForm.MinQPeaks_ledt->setEnabled(on);
+  m_uiForm.MaxQPeaks_ledt->setEnabled(on);
 }
 
 /**
@@ -1720,30 +1578,26 @@ void MantidEV::setEnabledFindPeaksParams_slot( bool on )
  * specified value.
  *
  */
-void MantidEV::setEnabledPredictPeaksParams_slot()
-{
-  bool predict_new_peaks     = m_uiForm.PredictPeaks_ckbx->isChecked();
-  if ( predict_new_peaks )
-  {
-    m_uiForm.min_pred_wl_lbl->setEnabled( true );
-    m_uiForm.min_pred_wl_ledt->setEnabled( true );
-    m_uiForm.max_pred_wl_lbl->setEnabled( true );
-    m_uiForm.max_pred_wl_ledt->setEnabled( true );
-    m_uiForm.min_pred_dspacing_lbl->setEnabled( true );
-    m_uiForm.min_pred_dspacing_ledt->setEnabled( true );
-    m_uiForm.max_pred_dspacing_lbl->setEnabled( true );
-    m_uiForm.max_pred_dspacing_ledt->setEnabled( true );
-  }
-  else
-  {
-    m_uiForm.min_pred_wl_lbl->setEnabled( false );
-    m_uiForm.min_pred_wl_ledt->setEnabled( false );
-    m_uiForm.max_pred_wl_lbl->setEnabled( false );
-    m_uiForm.max_pred_wl_ledt->setEnabled( false );
-    m_uiForm.min_pred_dspacing_lbl->setEnabled( false );
-    m_uiForm.min_pred_dspacing_ledt->setEnabled( false );
-    m_uiForm.max_pred_dspacing_lbl->setEnabled( false );
-    m_uiForm.max_pred_dspacing_ledt->setEnabled( false );
+void MantidEV::setEnabledPredictPeaksParams_slot() {
+  bool predict_new_peaks = m_uiForm.PredictPeaks_ckbx->isChecked();
+  if (predict_new_peaks) {
+    m_uiForm.min_pred_wl_lbl->setEnabled(true);
+    m_uiForm.min_pred_wl_ledt->setEnabled(true);
+    m_uiForm.max_pred_wl_lbl->setEnabled(true);
+    m_uiForm.max_pred_wl_ledt->setEnabled(true);
+    m_uiForm.min_pred_dspacing_lbl->setEnabled(true);
+    m_uiForm.min_pred_dspacing_ledt->setEnabled(true);
+    m_uiForm.max_pred_dspacing_lbl->setEnabled(true);
+    m_uiForm.max_pred_dspacing_ledt->setEnabled(true);
+  } else {
+    m_uiForm.min_pred_wl_lbl->setEnabled(false);
+    m_uiForm.min_pred_wl_ledt->setEnabled(false);
+    m_uiForm.max_pred_wl_lbl->setEnabled(false);
+    m_uiForm.max_pred_wl_ledt->setEnabled(false);
+    m_uiForm.min_pred_dspacing_lbl->setEnabled(false);
+    m_uiForm.min_pred_dspacing_ledt->setEnabled(false);
+    m_uiForm.max_pred_dspacing_lbl->setEnabled(false);
+    m_uiForm.max_pred_dspacing_ledt->setEnabled(false);
   }
 }
 
@@ -1753,28 +1607,25 @@ void MantidEV::setEnabledPredictPeaksParams_slot()
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledLoadPeaksParams_slot( bool on )
-{
-  m_uiForm.SelectPeaksFile_lbl->setEnabled( on );
-  m_uiForm.SelectPeaksFile_ledt->setEnabled( on );
-  m_uiForm.SelectPeaksFile_btn->setEnabled( on );
+void MantidEV::setEnabledLoadPeaksParams_slot(bool on) {
+  m_uiForm.SelectPeaksFile_lbl->setEnabled(on);
+  m_uiForm.SelectPeaksFile_ledt->setEnabled(on);
+  m_uiForm.SelectPeaksFile_btn->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the find UB using FFT components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledFindUBFFTParams_slot( bool on )
-{
-  m_uiForm.MinD_lbl->setEnabled( on );
-  m_uiForm.MinD_ledt->setEnabled( on );
-  m_uiForm.MaxD_lbl->setEnabled( on );
-  m_uiForm.MaxD_ledt->setEnabled( on );
-  m_uiForm.FFTTolerance_lbl->setEnabled( on );
-  m_uiForm.FFTTolerance_ledt->setEnabled( on );
+void MantidEV::setEnabledFindUBFFTParams_slot(bool on) {
+  m_uiForm.MinD_lbl->setEnabled(on);
+  m_uiForm.MinD_ledt->setEnabled(on);
+  m_uiForm.MaxD_lbl->setEnabled(on);
+  m_uiForm.MaxD_ledt->setEnabled(on);
+  m_uiForm.FFTTolerance_lbl->setEnabled(on);
+  m_uiForm.FFTTolerance_ledt->setEnabled(on);
 }
 
 /**
@@ -1783,10 +1634,9 @@ void MantidEV::setEnabledFindUBFFTParams_slot( bool on )
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledFindUBUsingIndexedPeaksParams_slot( bool on )
-{
-  m_uiForm.IndexedPeaksTolerance_lbl->setEnabled( on );
-  m_uiForm.IndexedPeaksTolerance_ledt->setEnabled( on );
+void MantidEV::setEnabledFindUBUsingIndexedPeaksParams_slot(bool on) {
+  m_uiForm.IndexedPeaksTolerance_lbl->setEnabled(on);
+  m_uiForm.IndexedPeaksTolerance_ledt->setEnabled(on);
 }
 
 /**
@@ -1795,175 +1645,150 @@ void MantidEV::setEnabledFindUBUsingIndexedPeaksParams_slot( bool on )
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledLoadUBParams_slot( bool on )
-{
-  m_uiForm.SelectUBFile_lbl->setEnabled( on );
-  m_uiForm.SelectUBFile_ledt->setEnabled( on );
-  m_uiForm.SelectUBFile_btn->setEnabled( on );
-  m_uiForm.OptimizeGoniometerAngles_ckbx->setEnabled( on );
+void MantidEV::setEnabledLoadUBParams_slot(bool on) {
+  m_uiForm.SelectUBFile_lbl->setEnabled(on);
+  m_uiForm.SelectUBFile_ledt->setEnabled(on);
+  m_uiForm.SelectUBFile_btn->setEnabled(on);
+  m_uiForm.OptimizeGoniometerAngles_ckbx->setEnabled(on);
   setEnabledMaxOptimizeDegrees_slot();
 }
 
-
 /**
  * Set the enabled state of the optimize goniometer angle components
- * based on the state of the Load UB button and the Optiimze 
+ * based on the state of the Load UB button and the Optiimze
  * Goniometer Angle buttons.
  *
  */
-void MantidEV::setEnabledMaxOptimizeDegrees_slot()
-{
-  bool load_ub         = m_uiForm.LoadISAWUB_rbtn->isChecked();
+void MantidEV::setEnabledMaxOptimizeDegrees_slot() {
+  bool load_ub = m_uiForm.LoadISAWUB_rbtn->isChecked();
   bool optimize_angles = m_uiForm.OptimizeGoniometerAngles_ckbx->isChecked();
-  if ( load_ub && optimize_angles )
-  {
-    m_uiForm.MaxGoniometerChange_lbl->setEnabled( true );
-    m_uiForm.MaxGoniometerChange_ledt->setEnabled( true );
-  }
-  else
-  {
-    m_uiForm.MaxGoniometerChange_lbl->setEnabled( false );
-    m_uiForm.MaxGoniometerChange_ledt->setEnabled( false );
+  if (load_ub && optimize_angles) {
+    m_uiForm.MaxGoniometerChange_lbl->setEnabled(true);
+    m_uiForm.MaxGoniometerChange_ledt->setEnabled(true);
+  } else {
+    m_uiForm.MaxGoniometerChange_lbl->setEnabled(false);
+    m_uiForm.MaxGoniometerChange_ledt->setEnabled(false);
   }
 }
 
-
 /**
  * Set the enabled state of the index peaks components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledIndexParams_slot( bool on )
-{
-  m_uiForm.IndexingTolerance_lbl->setEnabled( on );
-  m_uiForm.IndexingTolerance_ledt->setEnabled( on );
-  m_uiForm.RoundHKLs_ckbx->setEnabled( on );
+void MantidEV::setEnabledIndexParams_slot(bool on) {
+  m_uiForm.IndexingTolerance_lbl->setEnabled(on);
+  m_uiForm.IndexingTolerance_ledt->setEnabled(on);
+  m_uiForm.RoundHKLs_ckbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the show cells components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledShowCellsParams_slot( bool on )
-{
-  m_uiForm.MaxScalarError_lbl->setEnabled( on );
-  m_uiForm.MaxScalarError_ledt->setEnabled( on );
-  m_uiForm.BestCellOnly_ckbx->setEnabled( on );
-  m_uiForm.AllowPermutations_ckbx->setEnabled( on );
+void MantidEV::setEnabledShowCellsParams_slot(bool on) {
+  m_uiForm.MaxScalarError_lbl->setEnabled(on);
+  m_uiForm.MaxScalarError_ledt->setEnabled(on);
+  m_uiForm.BestCellOnly_ckbx->setEnabled(on);
+  m_uiForm.AllowPermutations_ckbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the select cell of type components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledSetCellTypeParams_slot( bool on )
-{
-  m_uiForm.CellType_cmbx->setEnabled( on );
-  m_uiForm.CellCentering_cmbx->setEnabled( on );
+void MantidEV::setEnabledSetCellTypeParams_slot(bool on) {
+  m_uiForm.CellType_cmbx->setEnabled(on);
+  m_uiForm.CellCentering_cmbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the select cell with form components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledSetCellFormParams_slot( bool on )
-{
-  m_uiForm.CellFormNumber_cmbx->setEnabled( on );
+void MantidEV::setEnabledSetCellFormParams_slot(bool on) {
+  m_uiForm.CellFormNumber_cmbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the sphere integration components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledSphereIntParams_slot( bool on )
-{
-  m_uiForm.PeakRadius_lbl->setEnabled( on );
-  m_uiForm.PeakRadius_ledt->setEnabled( on );
-  m_uiForm.BackgroundInnerRadius_lbl->setEnabled( on );
-  m_uiForm.BackgroundInnerRadius_ledt->setEnabled( on );
-  m_uiForm.BackgroundOuterRadius_lbl->setEnabled( on );
-  m_uiForm.BackgroundOuterRadius_ledt->setEnabled( on );
-  m_uiForm.IntegrateEdge_ckbx->setEnabled( on );
-  m_uiForm.Cylinder_ckbx->setEnabled( on );
-  m_uiForm.CylinderLength_ledt->setEnabled( on );
-  m_uiForm.CylinderPercentBkg_ledt->setEnabled( on );
-  m_uiForm.CylinderProfileFit_cmbx->setEnabled( on );
+void MantidEV::setEnabledSphereIntParams_slot(bool on) {
+  m_uiForm.PeakRadius_lbl->setEnabled(on);
+  m_uiForm.PeakRadius_ledt->setEnabled(on);
+  m_uiForm.BackgroundInnerRadius_lbl->setEnabled(on);
+  m_uiForm.BackgroundInnerRadius_ledt->setEnabled(on);
+  m_uiForm.BackgroundOuterRadius_lbl->setEnabled(on);
+  m_uiForm.BackgroundOuterRadius_ledt->setEnabled(on);
+  m_uiForm.IntegrateEdge_ckbx->setEnabled(on);
+  m_uiForm.Cylinder_ckbx->setEnabled(on);
+  m_uiForm.CylinderLength_ledt->setEnabled(on);
+  m_uiForm.CylinderPercentBkg_ledt->setEnabled(on);
+  m_uiForm.CylinderProfileFit_cmbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the fit integration components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledFitIntParams_slot( bool on )
-{
-  m_uiForm.FitRebinParams_lbl->setEnabled( on );
-  m_uiForm.FitRebinParams_ledt->setEnabled( on );
-  m_uiForm.NBadEdgePixels_lbl->setEnabled( on );
-  m_uiForm.NBadEdgePixels_ledt->setEnabled( on );
-  m_uiForm.IkedaCarpenter_ckbx->setEnabled( on );
+void MantidEV::setEnabledFitIntParams_slot(bool on) {
+  m_uiForm.FitRebinParams_lbl->setEnabled(on);
+  m_uiForm.FitRebinParams_ledt->setEnabled(on);
+  m_uiForm.NBadEdgePixels_lbl->setEnabled(on);
+  m_uiForm.NBadEdgePixels_ledt->setEnabled(on);
+  m_uiForm.IkedaCarpenter_ckbx->setEnabled(on);
 }
 
-
 /**
  * Set the enabled state of the ellipse integration components to the
  * specified value.
  *
  * @param on  If true, components will be enabled, if false, disabled.
  */
-void MantidEV::setEnabledEllipseIntParams_slot( bool on )
-{
-  m_uiForm.RegionRadius_lbl->setEnabled( on );
-  m_uiForm.RegionRadius_ledt->setEnabled( on );
-  m_uiForm.SpecifySize_ckbx->setEnabled( on );
+void MantidEV::setEnabledEllipseIntParams_slot(bool on) {
+  m_uiForm.RegionRadius_lbl->setEnabled(on);
+  m_uiForm.RegionRadius_ledt->setEnabled(on);
+  m_uiForm.SpecifySize_ckbx->setEnabled(on);
   setEnabledEllipseSizeOptions_slot();
 }
 
-
 /**
  * Set the enabled state of the load event file components base on
  * the state of the ellipse integrate radio button and the
  * specify size checkbox.
  */
-void MantidEV::setEnabledEllipseSizeOptions_slot()
-{
+void MantidEV::setEnabledEllipseSizeOptions_slot() {
   bool on = m_uiForm.EllipsoidIntegration_rbtn->isChecked() &&
             m_uiForm.SpecifySize_ckbx->isChecked();
-  m_uiForm.PeakSize_lbl->setEnabled( on );
-  m_uiForm.PeakSize_ledt->setEnabled( on );
-  m_uiForm.BackgroundInnerSize_lbl->setEnabled( on );
-  m_uiForm.BackgroundInnerSize_ledt->setEnabled( on );
-  m_uiForm.BackgroundOuterSize_lbl->setEnabled( on );
-  m_uiForm.BackgroundOuterSize_ledt->setEnabled( on );
+  m_uiForm.PeakSize_lbl->setEnabled(on);
+  m_uiForm.PeakSize_ledt->setEnabled(on);
+  m_uiForm.BackgroundInnerSize_lbl->setEnabled(on);
+  m_uiForm.BackgroundInnerSize_ledt->setEnabled(on);
+  m_uiForm.BackgroundOuterSize_lbl->setEnabled(on);
+  m_uiForm.BackgroundOuterSize_ledt->setEnabled(on);
 }
 
-
 /**
  * Utility to display an error message.
  *
  * @param  message  The error message to display.
  */
-void MantidEV::errorMessage( const std::string & message )
-{
-  QMessageBox::critical(this,"ERROR", QString::fromStdString(message));
+void MantidEV::errorMessage(const std::string &message) {
+  QMessageBox::critical(this, "ERROR", QString::fromStdString(message));
 }
 
-
 /**
  *  Utility to get a double precision value from the specified string.
  *
@@ -1973,17 +1798,14 @@ void MantidEV::errorMessage( const std::string & message )
  *
  *  @return true if a double was extacted from the string.
  */
-bool MantidEV::getDouble( std::string str, double &value )
-{
-  std::istringstream strs( str );
-  if ( strs >> value )
-  {
+bool MantidEV::getDouble(std::string str, double &value) {
+  std::istringstream strs(str);
+  if (strs >> value) {
     return true;
   }
   return false;
 }
 
-
 /**
  *  Utility to get a double precision value from the specified
  *  QLineEdit component.
@@ -1995,28 +1817,23 @@ bool MantidEV::getDouble( std::string str, double &value )
  *
  *  @return true if a double was successfully extacted.
  */
-bool MantidEV::getDouble( QLineEdit *ledt,
-                          double    &value )
-{
+bool MantidEV::getDouble(QLineEdit *ledt, double &value) {
   std::string strValue = ledt->text().trimmed().toStdString();
-  if (strValue.empty())
-  {
+  if (strValue.empty()) {
     value = Mantid::EMPTY_DBL();
     return true;
   }
 
-  if ( getDouble( strValue, value ) )
-  {
+  if (getDouble(strValue, value)) {
     return true;
   }
 
-  std::string message( "Invalid Numeric Value: " );
+  std::string message("Invalid Numeric Value: ");
   message += ledt->text().toStdString();
-  errorMessage( message );
+  errorMessage(message);
   return false;
 }
 
-
 /**
  *  Utility to get a positive double precision value from the specified
  *  QLineEdit component.
@@ -2028,27 +1845,23 @@ bool MantidEV::getDouble( QLineEdit *ledt,
  *
  *  @return true if a positive double value was successfully extacted.
  */
-bool MantidEV::getPositiveDouble( QLineEdit *ledt,
-                                  double    &value )
-{
-  if ( !getDouble( ledt, value ) )
+bool MantidEV::getPositiveDouble(QLineEdit *ledt, double &value) {
+  if (!getDouble(ledt, value))
     return false;
 
-  if ( value > 0.0 )
-  {
+  if (value > 0.0) {
     return true;
   }
 
-  std::string message( "Positive Double Value Required: " );
+  std::string message("Positive Double Value Required: ");
   message += ledt->text().toStdString();
-  errorMessage( message );
+  errorMessage(message);
   return false;
 }
 
-
 /**
  *  Utility to get a positive integer value from the specified
- *  QLineEdit component.          
+ *  QLineEdit component.
  *
  *  @param  ledt   Pointer to a QLineEdit object that should contain
  *                 the string form of a positive integer.
@@ -2057,120 +1870,108 @@ bool MantidEV::getPositiveDouble( QLineEdit *ledt,
  *
  *  @return true if a positive integer value was successfully extacted.
  */
-bool MantidEV::getPositiveInt( QLineEdit *ledt,
-                               size_t    &value )
-{
+bool MantidEV::getPositiveInt(QLineEdit *ledt, size_t &value) {
   double double_value = 0;
-  if ( !getDouble( ledt, double_value ) )
+  if (!getDouble(ledt, double_value))
     return false;
 
-  if ( double_value > 0.0 )
-  {
+  if (double_value > 0.0) {
     value = (size_t)double_value;
-    if ( value > 0 )
-    {
+    if (value > 0) {
       return true;
     }
   }
 
-  std::string message( "Positive Integer Value Required: " );
+  std::string message("Positive Integer Value Required: ");
   message += ledt->text().toStdString();
-  errorMessage( message );
+  errorMessage(message);
   return false;
 }
 
-
 /**
  * Get base file name to form names for event, MD and peaks workspaces
  *
- * @param  full_file_name   The full name of the file that is being loaded. 
+ * @param  full_file_name   The full name of the file that is being loaded.
  *
  * @return  The base file name, with the directory and extension removed.
  */
-std::string MantidEV::extractBaseFileName( std::string full_file_name ) const
-{
+std::string MantidEV::extractBaseFileName(std::string full_file_name) const {
   size_t dot_index = full_file_name.find_last_of(".");
 
-  if ( dot_index != std::string::npos )
-  {
-    full_file_name = full_file_name.substr( 0, dot_index );
+  if (dot_index != std::string::npos) {
+    full_file_name = full_file_name.substr(0, dot_index);
   }
 
   size_t path_sep_index = full_file_name.find_last_of("/\\:");
 
-  if ( path_sep_index != std::string::npos )
-  {
-    full_file_name = full_file_name.substr( path_sep_index + 1 );
+  if (path_sep_index != std::string::npos) {
+    full_file_name = full_file_name.substr(path_sep_index + 1);
   }
 
-  size_t ev_suffix_index = full_file_name.rfind( "_event", std::string::npos );
-  if ( ev_suffix_index != std::string::npos )
-  {
-    full_file_name = full_file_name.substr( 0, ev_suffix_index );
+  size_t ev_suffix_index = full_file_name.rfind("_event", std::string::npos);
+  if (ev_suffix_index != std::string::npos) {
+    full_file_name = full_file_name.substr(0, ev_suffix_index);
   }
 
   return full_file_name;
 }
 
-
 /**
  * Get a path to use in a file dialog from the specified file_name
- * or the user's home directory if the file_name has length 0.  
+ * or the user's home directory if the file_name has length 0.
  *
- * @param file_name  The name of a file to use to determine a 
+ * @param file_name  The name of a file to use to determine a
  *                   file path to use when starting a QFileDialog
  *
  * @return The path from the specified file_name or the user's
  *         home directory if the file_name has length 0.
  */
-QString MantidEV::getFilePath( const std::string & file_name )
-{
+QString MantidEV::getFilePath(const std::string &file_name) {
   QString file_path;
-  if ( file_name.length() != 0 )
-  {
-    QString Qfile_name = QString::fromStdString( file_name );
-    QFileInfo file_info( Qfile_name );
+  if (file_name.length() != 0) {
+    QString Qfile_name = QString::fromStdString(file_name);
+    QFileInfo file_info(Qfile_name);
     file_path = file_info.absolutePath();
-  }
-  else
-  {
+  } else {
     file_path = QDir::homePath();
   }
   return file_path;
 }
 
-
 /**
  *  Utility to save the current state of all GUI components into the
  *  specified file name.  If the filename has length zero, the settings
- *  will be saved to a system dependent default location.  This is 
+ *  will be saved to a system dependent default location.  This is
  *  called in the destructor to automatically save the last settings to
- *  the default location.  It is also called to save the settings to 
+ *  the default location.  It is also called to save the settings to
  *  a specific file when the Save Settings File menu item is selected.
  *
- *  @param  filename   The name of the file to save the settings to, 
+ *  @param  filename   The name of the file to save the settings to,
  *                     or a blank string to use the default location.
  */
-void MantidEV::saveSettings( const std::string & filename )
-{
-  QSettings* state;
-  if ( filename.length() > 0 )
-    state = new QSettings( QString::fromStdString(filename), QSettings::IniFormat, this );
+void MantidEV::saveSettings(const std::string &filename) {
+  QSettings *state;
+  if (filename.length() > 0)
+    state = new QSettings(QString::fromStdString(filename),
+                          QSettings::IniFormat, this);
   else
     state = new QSettings;
-                                                // Save Tab 1, Select Data
-  state->setValue("SelectEventWorkspace_ledt", m_uiForm.SelectEventWorkspace_ledt->text());
+  // Save Tab 1, Select Data
+  state->setValue("SelectEventWorkspace_ledt",
+                  m_uiForm.SelectEventWorkspace_ledt->text());
   state->setValue("MDworkspace_ledt", m_uiForm.MDworkspace_ledt->text());
   state->setValue("LoadEventFile_rbtn", m_uiForm.loadDataGroupBox->isChecked());
   state->setValue("EventFileName_ledt", m_uiForm.EventFileName_ledt->text());
   state->setValue("MaxMagQ_ledt", m_uiForm.MaxMagQ_ledt->text());
-  state->setValue("LorentzCorrection_ckbx", m_uiForm.LorentzCorrection_ckbx->isChecked());
+  state->setValue("LorentzCorrection_ckbx",
+                  m_uiForm.LorentzCorrection_ckbx->isChecked());
   state->setValue("LoadDetCal_ckbx", m_uiForm.LoadDetCal_ckbx->isChecked());
   state->setValue("CalFileName_ledt", m_uiForm.CalFileName_ledt->text());
   state->setValue("CalFileName2_ledt", m_uiForm.CalFileName2_ledt->text());
-  state->setValue("ConvertToMD_rbtn", m_uiForm.convertToMDGroupBox->isChecked());
+  state->setValue("ConvertToMD_rbtn",
+                  m_uiForm.convertToMDGroupBox->isChecked());
 
-                                                // Save Tab 2, Find Peaks
+  // Save Tab 2, Find Peaks
   state->setValue("PeaksWorkspace_ledt", m_uiForm.PeaksWorkspace_ledt->text());
   state->setValue("FindPeaks_rbtn", m_uiForm.FindPeaks_rbtn->isChecked());
   state->setValue("MaxABC_ledt", m_uiForm.MaxABC_ledt->text());
@@ -2178,197 +1979,235 @@ void MantidEV::saveSettings( const std::string & filename )
   state->setValue("MinIntensity_ledt", m_uiForm.MinIntensity_ledt->text());
   state->setValue("MinQPeaks_ledt", m_uiForm.MinQPeaks_ledt->text());
   state->setValue("MaxQPeaks_ledt", m_uiForm.MaxQPeaks_ledt->text());
-  state->setValue("UseExistingPeaksWorkspace_rbtn", m_uiForm.UseExistingPeaksWorkspace_rbtn->isChecked());
-  state->setValue("LoadIsawPeaks_rbtn", m_uiForm.LoadIsawPeaks_rbtn->isChecked());
-  state->setValue("SelectPeaksFile_ledt", m_uiForm.SelectPeaksFile_ledt->text());
+  state->setValue("UseExistingPeaksWorkspace_rbtn",
+                  m_uiForm.UseExistingPeaksWorkspace_rbtn->isChecked());
+  state->setValue("LoadIsawPeaks_rbtn",
+                  m_uiForm.LoadIsawPeaks_rbtn->isChecked());
+  state->setValue("SelectPeaksFile_ledt",
+                  m_uiForm.SelectPeaksFile_ledt->text());
   state->setValue("PredictPeaks_ckbx", m_uiForm.PredictPeaks_ckbx->isChecked());
   state->setValue("min_pred_wl_ledt", m_uiForm.min_pred_wl_ledt->text());
   state->setValue("max_pred_wl_ledt", m_uiForm.max_pred_wl_ledt->text());
-  state->setValue("min_pred_dspacing_ledt", m_uiForm.min_pred_dspacing_ledt->text());
-  state->setValue("max_pred_dspacing_ledt", m_uiForm.max_pred_dspacing_ledt->text());
-
-                                                // Save Tab 3, Find UB 
-  state->setValue("FindUBUsingFFT_rbtn", m_uiForm.FindUBUsingFFT_rbtn->isChecked());
+  state->setValue("min_pred_dspacing_ledt",
+                  m_uiForm.min_pred_dspacing_ledt->text());
+  state->setValue("max_pred_dspacing_ledt",
+                  m_uiForm.max_pred_dspacing_ledt->text());
+
+  // Save Tab 3, Find UB
+  state->setValue("FindUBUsingFFT_rbtn",
+                  m_uiForm.FindUBUsingFFT_rbtn->isChecked());
   state->setValue("MinD_ledt", m_uiForm.MinD_ledt->text());
   state->setValue("MaxD_ledt", m_uiForm.MaxD_ledt->text());
   state->setValue("FFTTolerance_ledt", m_uiForm.FFTTolerance_ledt->text());
-  state->setValue("FindUBUsingIndexedPeaks_rbtn", m_uiForm.FindUBUsingIndexedPeaks_rbtn->isChecked());
-  state->setValue("IndexedPeaksTolerance_ledt", m_uiForm.IndexedPeaksTolerance_ledt->text());
+  state->setValue("FindUBUsingIndexedPeaks_rbtn",
+                  m_uiForm.FindUBUsingIndexedPeaks_rbtn->isChecked());
+  state->setValue("IndexedPeaksTolerance_ledt",
+                  m_uiForm.IndexedPeaksTolerance_ledt->text());
   state->setValue("LoadISAWUB_rbtn", m_uiForm.LoadISAWUB_rbtn->isChecked());
   state->setValue("SelectUBFile_ledt", m_uiForm.SelectUBFile_ledt->text());
-  state->setValue("OptimizeGoniometerAngles_ckbx", m_uiForm.OptimizeGoniometerAngles_ckbx->isChecked());
-  state->setValue("MaxGoniometerChange_ledt", m_uiForm.MaxGoniometerChange_ledt->text());
+  state->setValue("OptimizeGoniometerAngles_ckbx",
+                  m_uiForm.OptimizeGoniometerAngles_ckbx->isChecked());
+  state->setValue("MaxGoniometerChange_ledt",
+                  m_uiForm.MaxGoniometerChange_ledt->text());
   state->setValue("UseCurrentUB_rbtn", m_uiForm.UseCurrentUB_rbtn->isChecked());
   state->setValue("IndexPeaks_ckbx", m_uiForm.IndexPeaks_ckbx->isChecked());
-  state->setValue("IndexingTolerance_ledt", m_uiForm.IndexingTolerance_ledt->text());
+  state->setValue("IndexingTolerance_ledt",
+                  m_uiForm.IndexingTolerance_ledt->text());
   state->setValue("RoundHKLs_ckbx", m_uiForm.RoundHKLs_ckbx->isChecked());
 
-                                                // Save Tab 4, Choose Cell
-  state->setValue("ShowPossibleCells_rbtn",m_uiForm.ShowPossibleCells_rbtn->isChecked());
-  state->setValue("MaxScalarError_ledt",m_uiForm.MaxScalarError_ledt->text());
-  state->setValue("BestCellOnly_ckbx",m_uiForm.BestCellOnly_ckbx->isChecked());
-  state->setValue("BestCellOnly_ckbx",m_uiForm.AllowPermutations_ckbx->isChecked());
-  state->setValue("SelectCellOfType_rbtn",m_uiForm.SelectCellOfType_rbtn->isChecked());
-  state->setValue("CellType_cmbx",m_uiForm.CellType_cmbx->currentIndex());
-  state->setValue("CellCentering_cmbx",m_uiForm.CellCentering_cmbx->currentIndex());
-  state->setValue("SelectCellWithForm_rbtn",m_uiForm.SelectCellWithForm_rbtn->isChecked());
-  state->setValue("CellFormNumber_cmbx",m_uiForm.CellFormNumber_cmbx->currentIndex());
-
-                                                // Save Tab 5,Change HKL 
-  state->setValue("HKL_tran_row_1_ledt",m_uiForm.HKL_tran_row_1_ledt->text());
-  state->setValue("HKL_tran_row_2_ledt",m_uiForm.HKL_tran_row_2_ledt->text());
-  state->setValue("HKL_tran_row_3_ledt",m_uiForm.HKL_tran_row_3_ledt->text());
-
-                                                // Save Tab 6, Integrate
-  state->setValue("SphereIntegration_rbtn",m_uiForm.SphereIntegration_rbtn->isChecked());
-  state->setValue("PeakRadius_ledt",m_uiForm.PeakRadius_ledt->text());
-  state->setValue("BackgroundInnerRadius_ledt",m_uiForm.BackgroundInnerRadius_ledt->text());
-  state->setValue("BackgroundOuterRadius_ledt",m_uiForm.BackgroundOuterRadius_ledt->text());
-  state->setValue("CylinderLength_ledt",m_uiForm.CylinderLength_ledt->text());
-  state->setValue("CylinderPercentBkg_ledt",m_uiForm.CylinderPercentBkg_ledt->text());
-  state->setValue("IntegrateEdge_ckbx",m_uiForm.IntegrateEdge_ckbx->isChecked());
-  state->setValue("Cylinder_ckbx",m_uiForm.Cylinder_ckbx->isChecked());
-  state->setValue("CylinderProfileFit_cmbx",m_uiForm.CylinderProfileFit_cmbx->currentIndex());
-  state->setValue("TwoDFitIntegration_rbtn",m_uiForm.TwoDFitIntegration_rbtn->isChecked());
-  state->setValue("FitRebinParams_ledt",m_uiForm.FitRebinParams_ledt->text());
-  state->setValue("NBadEdgePixels_ledt",m_uiForm.NBadEdgePixels_ledt->text());
-  state->setValue("IkedaCarpenter_ckbx",m_uiForm.IkedaCarpenter_ckbx->isChecked());
-  state->setValue("EllipsoidIntegration_rbtn",m_uiForm.EllipsoidIntegration_rbtn->isChecked());
-  state->setValue("RegionRadius_ledt",m_uiForm.RegionRadius_ledt->text());
-  state->setValue("SpecifySize_ckbx",m_uiForm.SpecifySize_ckbx->isChecked());
-  state->setValue("PeakSize_ledt",m_uiForm.PeakSize_ledt->text());
-  state->setValue("BackgroundInnerSize_ledt",m_uiForm.BackgroundInnerSize_ledt->text());
-  state->setValue("BackgroundOuterSize_ledt",m_uiForm.BackgroundOuterSize_ledt->text());
-
-                                                // save info for file paths
-  state->setValue("last_UB_file",QString::fromStdString(last_UB_file));
-  state->setValue("last_event_file",QString::fromStdString(last_event_file));
-  state->setValue("last_peaks_file",QString::fromStdString(last_peaks_file));
-  state->setValue("last_ini_file",QString::fromStdString(last_ini_file));
-  state->setValue("last_cal_file",QString::fromStdString(last_cal_file));
-  state->setValue("last_cal_file2",QString::fromStdString(last_cal_file2));
+  // Save Tab 4, Choose Cell
+  state->setValue("ShowPossibleCells_rbtn",
+                  m_uiForm.ShowPossibleCells_rbtn->isChecked());
+  state->setValue("MaxScalarError_ledt", m_uiForm.MaxScalarError_ledt->text());
+  state->setValue("BestCellOnly_ckbx", m_uiForm.BestCellOnly_ckbx->isChecked());
+  state->setValue("BestCellOnly_ckbx",
+                  m_uiForm.AllowPermutations_ckbx->isChecked());
+  state->setValue("SelectCellOfType_rbtn",
+                  m_uiForm.SelectCellOfType_rbtn->isChecked());
+  state->setValue("CellType_cmbx", m_uiForm.CellType_cmbx->currentIndex());
+  state->setValue("CellCentering_cmbx",
+                  m_uiForm.CellCentering_cmbx->currentIndex());
+  state->setValue("SelectCellWithForm_rbtn",
+                  m_uiForm.SelectCellWithForm_rbtn->isChecked());
+  state->setValue("CellFormNumber_cmbx",
+                  m_uiForm.CellFormNumber_cmbx->currentIndex());
+
+  // Save Tab 5,Change HKL
+  state->setValue("HKL_tran_row_1_ledt", m_uiForm.HKL_tran_row_1_ledt->text());
+  state->setValue("HKL_tran_row_2_ledt", m_uiForm.HKL_tran_row_2_ledt->text());
+  state->setValue("HKL_tran_row_3_ledt", m_uiForm.HKL_tran_row_3_ledt->text());
+
+  // Save Tab 6, Integrate
+  state->setValue("SphereIntegration_rbtn",
+                  m_uiForm.SphereIntegration_rbtn->isChecked());
+  state->setValue("PeakRadius_ledt", m_uiForm.PeakRadius_ledt->text());
+  state->setValue("BackgroundInnerRadius_ledt",
+                  m_uiForm.BackgroundInnerRadius_ledt->text());
+  state->setValue("BackgroundOuterRadius_ledt",
+                  m_uiForm.BackgroundOuterRadius_ledt->text());
+  state->setValue("CylinderLength_ledt", m_uiForm.CylinderLength_ledt->text());
+  state->setValue("CylinderPercentBkg_ledt",
+                  m_uiForm.CylinderPercentBkg_ledt->text());
+  state->setValue("IntegrateEdge_ckbx",
+                  m_uiForm.IntegrateEdge_ckbx->isChecked());
+  state->setValue("Cylinder_ckbx", m_uiForm.Cylinder_ckbx->isChecked());
+  state->setValue("CylinderProfileFit_cmbx",
+                  m_uiForm.CylinderProfileFit_cmbx->currentIndex());
+  state->setValue("TwoDFitIntegration_rbtn",
+                  m_uiForm.TwoDFitIntegration_rbtn->isChecked());
+  state->setValue("FitRebinParams_ledt", m_uiForm.FitRebinParams_ledt->text());
+  state->setValue("NBadEdgePixels_ledt", m_uiForm.NBadEdgePixels_ledt->text());
+  state->setValue("IkedaCarpenter_ckbx",
+                  m_uiForm.IkedaCarpenter_ckbx->isChecked());
+  state->setValue("EllipsoidIntegration_rbtn",
+                  m_uiForm.EllipsoidIntegration_rbtn->isChecked());
+  state->setValue("RegionRadius_ledt", m_uiForm.RegionRadius_ledt->text());
+  state->setValue("SpecifySize_ckbx", m_uiForm.SpecifySize_ckbx->isChecked());
+  state->setValue("PeakSize_ledt", m_uiForm.PeakSize_ledt->text());
+  state->setValue("BackgroundInnerSize_ledt",
+                  m_uiForm.BackgroundInnerSize_ledt->text());
+  state->setValue("BackgroundOuterSize_ledt",
+                  m_uiForm.BackgroundOuterSize_ledt->text());
+
+  // save info for file paths
+  state->setValue("last_UB_file", QString::fromStdString(last_UB_file));
+  state->setValue("last_event_file", QString::fromStdString(last_event_file));
+  state->setValue("last_peaks_file", QString::fromStdString(last_peaks_file));
+  state->setValue("last_ini_file", QString::fromStdString(last_ini_file));
+  state->setValue("last_cal_file", QString::fromStdString(last_cal_file));
+  state->setValue("last_cal_file2", QString::fromStdString(last_cal_file2));
   delete state;
 }
 
-
 /**
- *  Utility to load the current state of all GUI components from the 
+ *  Utility to load the current state of all GUI components from the
  *  specified file name.  If the filename has length zero, the settings
- *  will be loaded from a system dependent default location.  This is 
- *  called at the end of initLayout() to automatically restore the last 
+ *  will be loaded from a system dependent default location.  This is
+ *  called at the end of initLayout() to automatically restore the last
  *  settings from the default location.  It is also called to load the
  *  settings from a specific file when the Load Settings File menu item
  *  is selected.
  *
- *  @param  filename   The name of the file to load the settings from, 
+ *  @param  filename   The name of the file to load the settings from,
  *                     or a blank string to use the default location.
  */
-void MantidEV::loadSettings( const std::string & filename )
-{
-  QSettings* state;
-  if ( filename.length() > 0 )
-    state = new QSettings( QString::fromStdString(filename), QSettings::IniFormat, this );
+void MantidEV::loadSettings(const std::string &filename) {
+  QSettings *state;
+  if (filename.length() > 0)
+    state = new QSettings(QString::fromStdString(filename),
+                          QSettings::IniFormat, this);
   else
     state = new QSettings;
 
-                                                  // Load Tab 1, Select Data 
-  restore( state, "SelectEventWorkspace_ledt", m_uiForm.SelectEventWorkspace_ledt );
-  restore( state, "MDworkspace_ledt", m_uiForm.MDworkspace_ledt );
-  m_uiForm.loadDataGroupBox->setChecked( state->value("LoadEventFile_rbtn", true).toBool() );
-  restore( state, "EventFileName_ledt", m_uiForm.EventFileName_ledt );
-  restore( state, "MaxMagQ_ledt", m_uiForm.MaxMagQ_ledt );
-  restore( state, "LorentzCorrection_ckbx", m_uiForm.LorentzCorrection_ckbx );
-  restore( state, "LoadDetCal_ckbx", m_uiForm.LoadDetCal_ckbx );
-  restore( state, "CalFileName_ledt", m_uiForm.CalFileName_ledt );
-  restore( state, "CalFileName2_ledt", m_uiForm.CalFileName2_ledt );
+  // Load Tab 1, Select Data
+  restore(state, "SelectEventWorkspace_ledt",
+          m_uiForm.SelectEventWorkspace_ledt);
+  restore(state, "MDworkspace_ledt", m_uiForm.MDworkspace_ledt);
+  m_uiForm.loadDataGroupBox->setChecked(
+      state->value("LoadEventFile_rbtn", true).toBool());
+  restore(state, "EventFileName_ledt", m_uiForm.EventFileName_ledt);
+  restore(state, "MaxMagQ_ledt", m_uiForm.MaxMagQ_ledt);
+  restore(state, "LorentzCorrection_ckbx", m_uiForm.LorentzCorrection_ckbx);
+  restore(state, "LoadDetCal_ckbx", m_uiForm.LoadDetCal_ckbx);
+  restore(state, "CalFileName_ledt", m_uiForm.CalFileName_ledt);
+  restore(state, "CalFileName2_ledt", m_uiForm.CalFileName2_ledt);
   setEnabledLoadCalFiles_slot();
-  m_uiForm.convertToMDGroupBox->setChecked( state->value("ConvertToMD_rbtn", true).toBool() );
-                                                  // Load Tab 2, Find Peaks
-  restore( state, "PeaksWorkspace_ledt", m_uiForm.PeaksWorkspace_ledt );
-  restore( state, "FindPeaks_rbtn", m_uiForm.FindPeaks_rbtn );
-  restore( state, "MaxABC_ledt", m_uiForm.MaxABC_ledt );
-  restore( state, "NumToFind_ledt", m_uiForm.NumToFind_ledt );
-  restore( state, "MinIntensity_ledt", m_uiForm.MinIntensity_ledt );
-  restore( state, "MinQPeaks_ledt", m_uiForm.MinQPeaks_ledt );
-  restore( state, "MaxQPeaks_ledt", m_uiForm.MaxQPeaks_ledt );
-  restore( state, "UseExistingPeaksWorkspace_rbtn", m_uiForm.UseExistingPeaksWorkspace_rbtn );
-  restore( state, "LoadIsawPeaks_rbtn", m_uiForm.LoadIsawPeaks_rbtn );
-  restore( state, "SelectPeaksFile_ledt", m_uiForm.SelectPeaksFile_ledt );
-  restore( state, "PredictPeaks_ckbx", m_uiForm.PredictPeaks_ckbx );
+  m_uiForm.convertToMDGroupBox->setChecked(
+      state->value("ConvertToMD_rbtn", true).toBool());
+  // Load Tab 2, Find Peaks
+  restore(state, "PeaksWorkspace_ledt", m_uiForm.PeaksWorkspace_ledt);
+  restore(state, "FindPeaks_rbtn", m_uiForm.FindPeaks_rbtn);
+  restore(state, "MaxABC_ledt", m_uiForm.MaxABC_ledt);
+  restore(state, "NumToFind_ledt", m_uiForm.NumToFind_ledt);
+  restore(state, "MinIntensity_ledt", m_uiForm.MinIntensity_ledt);
+  restore(state, "MinQPeaks_ledt", m_uiForm.MinQPeaks_ledt);
+  restore(state, "MaxQPeaks_ledt", m_uiForm.MaxQPeaks_ledt);
+  restore(state, "UseExistingPeaksWorkspace_rbtn",
+          m_uiForm.UseExistingPeaksWorkspace_rbtn);
+  restore(state, "LoadIsawPeaks_rbtn", m_uiForm.LoadIsawPeaks_rbtn);
+  restore(state, "SelectPeaksFile_ledt", m_uiForm.SelectPeaksFile_ledt);
+  restore(state, "PredictPeaks_ckbx", m_uiForm.PredictPeaks_ckbx);
   setEnabledPredictPeaksParams_slot();
-  restore( state, "min_pred_wl_ledt", m_uiForm.min_pred_wl_ledt );
-  restore( state, "max_pred_wl_ledt", m_uiForm.max_pred_wl_ledt );
-  restore( state, "min_pred_dspacing_ledt", m_uiForm.min_pred_dspacing_ledt );
-  restore( state, "max_pred_dspacing_ledt", m_uiForm.max_pred_dspacing_ledt );
-
-                                                  // Load Tab 3, Find UB 
-  restore( state, "FindUBUsingFFT_rbtn", m_uiForm.FindUBUsingFFT_rbtn );
-  restore( state, "MinD_ledt", m_uiForm.MinD_ledt );
-  restore( state, "MaxD_ledt", m_uiForm.MaxD_ledt );
-  restore( state, "FFTTolerance_ledt", m_uiForm.FFTTolerance_ledt );
-  restore( state, "FindUBUsingIndexedPeaks_rbtn", m_uiForm.FindUBUsingIndexedPeaks_rbtn );
-  restore( state, "IndexedPeaksTolerance_ledt", m_uiForm.IndexedPeaksTolerance_ledt );
-  restore( state, "LoadISAWUB_rbtn", m_uiForm.LoadISAWUB_rbtn );
-  restore( state, "SelectUBFile_ledt", m_uiForm.SelectUBFile_ledt );
-  restore( state, "OptimizeGoniometerAngles_ckbx", m_uiForm.OptimizeGoniometerAngles_ckbx );
-  restore( state, "MaxGoniometerChange_ledt", m_uiForm.MaxGoniometerChange_ledt );
+  restore(state, "min_pred_wl_ledt", m_uiForm.min_pred_wl_ledt);
+  restore(state, "max_pred_wl_ledt", m_uiForm.max_pred_wl_ledt);
+  restore(state, "min_pred_dspacing_ledt", m_uiForm.min_pred_dspacing_ledt);
+  restore(state, "max_pred_dspacing_ledt", m_uiForm.max_pred_dspacing_ledt);
+
+  // Load Tab 3, Find UB
+  restore(state, "FindUBUsingFFT_rbtn", m_uiForm.FindUBUsingFFT_rbtn);
+  restore(state, "MinD_ledt", m_uiForm.MinD_ledt);
+  restore(state, "MaxD_ledt", m_uiForm.MaxD_ledt);
+  restore(state, "FFTTolerance_ledt", m_uiForm.FFTTolerance_ledt);
+  restore(state, "FindUBUsingIndexedPeaks_rbtn",
+          m_uiForm.FindUBUsingIndexedPeaks_rbtn);
+  restore(state, "IndexedPeaksTolerance_ledt",
+          m_uiForm.IndexedPeaksTolerance_ledt);
+  restore(state, "LoadISAWUB_rbtn", m_uiForm.LoadISAWUB_rbtn);
+  restore(state, "SelectUBFile_ledt", m_uiForm.SelectUBFile_ledt);
+  restore(state, "OptimizeGoniometerAngles_ckbx",
+          m_uiForm.OptimizeGoniometerAngles_ckbx);
+  restore(state, "MaxGoniometerChange_ledt", m_uiForm.MaxGoniometerChange_ledt);
   setEnabledMaxOptimizeDegrees_slot();
-  restore( state, "UseCurrentUB_rbtn", m_uiForm.UseCurrentUB_rbtn );
-  restore( state, "IndexPeaks_ckbx", m_uiForm.IndexPeaks_ckbx );
-  restore( state, "IndexingTolerance_ledt", m_uiForm.IndexingTolerance_ledt );
-  restore( state, "RoundHKLs_ckbx", m_uiForm.RoundHKLs_ckbx );
-
-                                                // Load Tab 4, Choose Cell
-  restore( state, "ShowPossibleCells_rbtn", m_uiForm.ShowPossibleCells_rbtn );
-  restore( state, "MaxScalarError_ledt", m_uiForm.MaxScalarError_ledt );
-  restore( state, "BestCellOnly_ckbx", m_uiForm.BestCellOnly_ckbx );
-  restore( state, "AllowPermutations_ckbx", m_uiForm.AllowPermutations_ckbx );
-  restore( state, "SelectCellOfType_rbtn", m_uiForm.SelectCellOfType_rbtn );
-  restore( state, "CellType_cmbx", m_uiForm.CellType_cmbx );
-  restore( state, "CellCentering_cmbx", m_uiForm.CellCentering_cmbx );
-  restore( state, "SelectCellWithForm_rbtn", m_uiForm.SelectCellWithForm_rbtn );
-  restore( state, "CellFormNumber_cmbx", m_uiForm.CellFormNumber_cmbx );
-  
-                                                // Load Tab 5,Change HKL 
-  restore( state, "HKL_tran_row_1_ledt", m_uiForm.HKL_tran_row_1_ledt );
-  restore( state, "HKL_tran_row_2_ledt", m_uiForm.HKL_tran_row_2_ledt );
-  restore( state, "HKL_tran_row_3_ledt", m_uiForm.HKL_tran_row_3_ledt );
-
-                                                // Load Tab 6, Integrate
-  restore( state, "SphereIntegration_rbtn", m_uiForm.SphereIntegration_rbtn );
-  restore( state, "PeakRadius_ledt", m_uiForm.PeakRadius_ledt );
-  restore( state, "BackgroundInnerRadius_ledt", m_uiForm.BackgroundInnerRadius_ledt );
-  restore( state, "BackgroundOuterRadius_ledt", m_uiForm.BackgroundOuterRadius_ledt );
-  restore( state, "CylinderLength_ledt", m_uiForm.CylinderLength_ledt );
-  restore( state, "CylinderPercentBkg_ledt", m_uiForm.CylinderPercentBkg_ledt );
-  restore( state, "IntegrateEdge_ckbx", m_uiForm.IntegrateEdge_ckbx );
-  restore( state, "Cylinder_ckbx", m_uiForm.Cylinder_ckbx );
-  restore( state, "CylinderProfileFit_cmbx", m_uiForm.CylinderProfileFit_cmbx);
-  restore( state, "TwoDFitIntegration_rbtn", m_uiForm.TwoDFitIntegration_rbtn );
-  restore( state, "FitRebinParams_ledt", m_uiForm.FitRebinParams_ledt );
-  restore( state, "NBadEdgePixels_ledt", m_uiForm.NBadEdgePixels_ledt );
-  restore( state, "IkedaCarpenter_ckbx", m_uiForm.IkedaCarpenter_ckbx );
-  restore( state, "EllipsoidIntegration_rbtn", m_uiForm.EllipsoidIntegration_rbtn );
-  restore( state, "RegionRadius_ledt", m_uiForm.RegionRadius_ledt );
-  restore( state, "SpecifySize_ckbx", m_uiForm.SpecifySize_ckbx );
-  restore( state, "PeakSize_ledt", m_uiForm.PeakSize_ledt );
-  restore( state, "BackgroundInnerSize_ledt", m_uiForm.BackgroundInnerSize_ledt );
-  restore( state, "BackgroundOuterSize_ledt", m_uiForm.BackgroundOuterSize_ledt );
+  restore(state, "UseCurrentUB_rbtn", m_uiForm.UseCurrentUB_rbtn);
+  restore(state, "IndexPeaks_ckbx", m_uiForm.IndexPeaks_ckbx);
+  restore(state, "IndexingTolerance_ledt", m_uiForm.IndexingTolerance_ledt);
+  restore(state, "RoundHKLs_ckbx", m_uiForm.RoundHKLs_ckbx);
+
+  // Load Tab 4, Choose Cell
+  restore(state, "ShowPossibleCells_rbtn", m_uiForm.ShowPossibleCells_rbtn);
+  restore(state, "MaxScalarError_ledt", m_uiForm.MaxScalarError_ledt);
+  restore(state, "BestCellOnly_ckbx", m_uiForm.BestCellOnly_ckbx);
+  restore(state, "AllowPermutations_ckbx", m_uiForm.AllowPermutations_ckbx);
+  restore(state, "SelectCellOfType_rbtn", m_uiForm.SelectCellOfType_rbtn);
+  restore(state, "CellType_cmbx", m_uiForm.CellType_cmbx);
+  restore(state, "CellCentering_cmbx", m_uiForm.CellCentering_cmbx);
+  restore(state, "SelectCellWithForm_rbtn", m_uiForm.SelectCellWithForm_rbtn);
+  restore(state, "CellFormNumber_cmbx", m_uiForm.CellFormNumber_cmbx);
+
+  // Load Tab 5,Change HKL
+  restore(state, "HKL_tran_row_1_ledt", m_uiForm.HKL_tran_row_1_ledt);
+  restore(state, "HKL_tran_row_2_ledt", m_uiForm.HKL_tran_row_2_ledt);
+  restore(state, "HKL_tran_row_3_ledt", m_uiForm.HKL_tran_row_3_ledt);
+
+  // Load Tab 6, Integrate
+  restore(state, "SphereIntegration_rbtn", m_uiForm.SphereIntegration_rbtn);
+  restore(state, "PeakRadius_ledt", m_uiForm.PeakRadius_ledt);
+  restore(state, "BackgroundInnerRadius_ledt",
+          m_uiForm.BackgroundInnerRadius_ledt);
+  restore(state, "BackgroundOuterRadius_ledt",
+          m_uiForm.BackgroundOuterRadius_ledt);
+  restore(state, "CylinderLength_ledt", m_uiForm.CylinderLength_ledt);
+  restore(state, "CylinderPercentBkg_ledt", m_uiForm.CylinderPercentBkg_ledt);
+  restore(state, "IntegrateEdge_ckbx", m_uiForm.IntegrateEdge_ckbx);
+  restore(state, "Cylinder_ckbx", m_uiForm.Cylinder_ckbx);
+  restore(state, "CylinderProfileFit_cmbx", m_uiForm.CylinderProfileFit_cmbx);
+  restore(state, "TwoDFitIntegration_rbtn", m_uiForm.TwoDFitIntegration_rbtn);
+  restore(state, "FitRebinParams_ledt", m_uiForm.FitRebinParams_ledt);
+  restore(state, "NBadEdgePixels_ledt", m_uiForm.NBadEdgePixels_ledt);
+  restore(state, "IkedaCarpenter_ckbx", m_uiForm.IkedaCarpenter_ckbx);
+  restore(state, "EllipsoidIntegration_rbtn",
+          m_uiForm.EllipsoidIntegration_rbtn);
+  restore(state, "RegionRadius_ledt", m_uiForm.RegionRadius_ledt);
+  restore(state, "SpecifySize_ckbx", m_uiForm.SpecifySize_ckbx);
+  restore(state, "PeakSize_ledt", m_uiForm.PeakSize_ledt);
+  restore(state, "BackgroundInnerSize_ledt", m_uiForm.BackgroundInnerSize_ledt);
+  restore(state, "BackgroundOuterSize_ledt", m_uiForm.BackgroundOuterSize_ledt);
   setEnabledEllipseSizeOptions_slot();
-                                                // load info for file paths
-  last_UB_file    = state->value("last_UB_file", "").toString().toStdString();
-  last_event_file = state->value("last_event_file", "").toString().toStdString();
-  last_peaks_file = state->value("last_peaks_file", "").toString().toStdString();
-  last_ini_file   = state->value("last_ini_file", "").toString().toStdString();
-  last_cal_file   = state->value("last_cal_file", "").toString().toStdString();
-  last_cal_file2  = state->value("last_cal_file2", "").toString().toStdString();
+  // load info for file paths
+  last_UB_file = state->value("last_UB_file", "").toString().toStdString();
+  last_event_file =
+      state->value("last_event_file", "").toString().toStdString();
+  last_peaks_file =
+      state->value("last_peaks_file", "").toString().toStdString();
+  last_ini_file = state->value("last_ini_file", "").toString().toStdString();
+  last_cal_file = state->value("last_cal_file", "").toString().toStdString();
+  last_cal_file2 = state->value("last_cal_file2", "").toString().toStdString();
 
   delete state;
 }
 
-
 /*
- * Restore the value of the specified QLineEdit component from the 
+ * Restore the value of the specified QLineEdit component from the
  * specifed QSettings object.
  *
  * @param state    pointer to the QSettings object to use
@@ -2376,53 +2215,45 @@ void MantidEV::loadSettings( const std::string & filename )
  * @param ledt     pointer to the QLineEdit component whose state
  *                 is to be restored.
  */
-void MantidEV::restore( QSettings *state, QString name, QLineEdit *ledt )
-{
+void MantidEV::restore(QSettings *state, QString name, QLineEdit *ledt) {
   // NOTE: If state was not saved yet, we don't want to change the
   // default value, so we only change the text if it's non-empty
   QString sText = state->value(name, "").toString();
-  if ( sText.length() > 0 )
-  {
-    ledt->setText( sText );
+  if (sText.length() > 0) {
+    ledt->setText(sText);
   }
 }
 
-
 /*
  * Restore the value of the QCheckbox or QRadioButton component from the
  * specifed QSettings object.
  *
  * @param state    pointer to the QSettings object to use
  * @param name     the name of the setting to use
- * @param btn      pointer to the QCheckbox or QRadioButton component 
+ * @param btn      pointer to the QCheckbox or QRadioButton component
  *                 whose state is to be restored.
  */
-void MantidEV::restore( QSettings *state, QString name, QAbstractButton *btn )
-{
-  btn->setChecked( state->value(name, false).toBool() );
+void MantidEV::restore(QSettings *state, QString name, QAbstractButton *btn) {
+  btn->setChecked(state->value(name, false).toBool());
 }
 
-
 /*
  * Restore the value of a QComboBox from the specified QSettings object
  *
  * @param state    pointer to the QSettings object to use
  * @param name     the name of the setting to use
- * @param cmbx     pointer to the QComboBox component whose state is 
+ * @param cmbx     pointer to the QComboBox component whose state is
  *                 to be restored.
  */
-void MantidEV::restore( QSettings *state, QString name, QComboBox *cmbx )
-{
+void MantidEV::restore(QSettings *state, QString name, QComboBox *cmbx) {
   // NOTE: If state was not saved yet, we don't want to change the
   // default value, so we only change the selected item if the index
-  // has been set to a valid value. 
+  // has been set to a valid value.
   int val = state->value(name, -1).toInt();
-  if ( val > 0 )
-  {
+  if (val > 0) {
     cmbx->setCurrentIndex(val);
   }
 }
 
-
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/MantidEVWorker.cpp b/MantidQt/CustomInterfaces/src/MantidEVWorker.cpp
index a33a7a2979a56c4d894095cbe4cde85d6a3a97b9..a1d422974df693ac8dee2037a0f211c4667f305d 100644
--- a/MantidQt/CustomInterfaces/src/MantidEVWorker.cpp
+++ b/MantidQt/CustomInterfaces/src/MantidEVWorker.cpp
@@ -993,16 +993,14 @@ bool MantidEVWorker::showUB(const std::string &peaks_ws_name) {
     g_log.notice() << std::endl;
     g_log.notice() << "Mantid UB = " << std::endl;
     sprintf(logInfo, std::string(" %12.8f %12.8f %12.8f\n %12.8f %12.8f "
-                                 "%12.8f\n %12.8f %12.8f %12.8f\n")
-                         .c_str(),
+                                 "%12.8f\n %12.8f %12.8f %12.8f\n").c_str(),
             UB[0][0], UB[0][1], UB[0][2], UB[1][0], UB[1][1], UB[1][2],
             UB[2][0], UB[2][1], UB[2][2]);
     g_log.notice(std::string(logInfo));
 
     g_log.notice() << "ISAW UB = " << std::endl;
     sprintf(logInfo, std::string(" %12.8f %12.8f %12.8f\n %12.8f %12.8f "
-                                 "%12.8f\n %12.8f %12.8f %12.8f\n")
-                         .c_str(),
+                                 "%12.8f\n %12.8f %12.8f %12.8f\n").c_str(),
             UB[2][0], UB[0][0], UB[1][0], UB[2][1], UB[0][1], UB[1][1],
             UB[2][2], UB[0][2], UB[1][2]);
     g_log.notice(std::string(logInfo));
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
index 86d1ce65d3be27a7a3946eae8bf6253244c91129..c96419ddd04c0b88075327c7760b5154c3597153 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFAddWorkspaceDialog.cpp
@@ -8,67 +8,63 @@
 
 #include <QMessageBox>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Constructor.
 /// @param parent :: A parent widget.
-AddWorkspaceDialog::AddWorkspaceDialog(QWidget *parent):QDialog(parent),m_maxIndex(0)
-{
+AddWorkspaceDialog::AddWorkspaceDialog(QWidget *parent)
+    : QDialog(parent), m_maxIndex(0) {
   m_uiForm.setupUi(this);
   // populate the combo box with names of eligible workspaces
   QStringList workspaceNames;
   auto wsNames = Mantid::API::AnalysisDataService::Instance().getObjectNames();
-  for(auto name = wsNames.begin(); name != wsNames.end(); ++name)
-  {
-    auto mws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>( *name );
-    auto grp = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::WorkspaceGroup>( *name );
-    if ( mws || grp )
-    {
-      workspaceNames << QString::fromStdString( *name );
+  for (auto name = wsNames.begin(); name != wsNames.end(); ++name) {
+    auto mws = Mantid::API::AnalysisDataService::Instance()
+                   .retrieveWS<Mantid::API::MatrixWorkspace>(*name);
+    auto grp = Mantid::API::AnalysisDataService::Instance()
+                   .retrieveWS<Mantid::API::WorkspaceGroup>(*name);
+    if (mws || grp) {
+      workspaceNames << QString::fromStdString(*name);
     }
   }
   workspaceNames.sort();
-  connect(m_uiForm.cbWorkspaceName,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(workspaceNameChanged(const QString&)));
-  m_uiForm.cbWorkspaceName->addItems( workspaceNames );
+  connect(m_uiForm.cbWorkspaceName,
+          SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(workspaceNameChanged(const QString &)));
+  m_uiForm.cbWorkspaceName->addItems(workspaceNames);
 
-  connect(m_uiForm.cbAllSpectra,SIGNAL(stateChanged(int)),this,SLOT(selectAllSpectra(int)));
+  connect(m_uiForm.cbAllSpectra, SIGNAL(stateChanged(int)), this,
+          SLOT(selectAllSpectra(int)));
 }
 
 /// Slot. Reacts on change of workspace name in the selection combo box.
 /// @param wsName :: Name of newly selected workspace.
-void AddWorkspaceDialog::workspaceNameChanged(const QString& wsName)
-{
+void AddWorkspaceDialog::workspaceNameChanged(const QString &wsName) {
   auto stdWsName = wsName.toStdString();
-  auto mws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>( stdWsName );
+  auto mws = Mantid::API::AnalysisDataService::Instance()
+                 .retrieveWS<Mantid::API::MatrixWorkspace>(stdWsName);
 
-  auto grp = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::WorkspaceGroup>( stdWsName );
-  if ( grp && !grp->isEmpty() )
-  {
-    mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(grp->getItem(0));
+  auto grp = Mantid::API::AnalysisDataService::Instance()
+                 .retrieveWS<Mantid::API::WorkspaceGroup>(stdWsName);
+  if (grp && !grp->isEmpty()) {
+    mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+        grp->getItem(0));
   }
 
-  if ( mws )
-  {
+  if (mws) {
     int maxValue = static_cast<int>(mws->getNumberHistograms()) - 1;
-    if ( maxValue < 0 ) maxValue = 0;
+    if (maxValue < 0)
+      maxValue = 0;
     m_maxIndex = maxValue;
-    if ( m_uiForm.cbAllSpectra->isChecked() || m_maxIndex == 0 )
-    {
+    if (m_uiForm.cbAllSpectra->isChecked() || m_maxIndex == 0) {
       auto text = m_maxIndex > 0 ? QString("0-%1").arg(m_maxIndex) : "0";
       m_uiForm.leWSIndices->setText(text);
-    }
-    else
-    {
+    } else {
       m_uiForm.leWSIndices->clear();
     }
-  }
-  else
-  {
+  } else {
     m_maxIndex = 0;
     m_uiForm.leWSIndices->clear();
     m_uiForm.cbAllSpectra->setChecked(false);
@@ -77,46 +73,40 @@ void AddWorkspaceDialog::workspaceNameChanged(const QString& wsName)
 
 /// Slot. Called when "All Spectra" check box changes its state
 /// @param state :: The state of the check box (Qt::Checked or not).
-void AddWorkspaceDialog::selectAllSpectra(int state)
-{
-  if ( state == Qt::Checked )
-  {
+void AddWorkspaceDialog::selectAllSpectra(int state) {
+  if (state == Qt::Checked) {
     m_uiForm.leWSIndices->setText(QString("0-%1").arg(m_maxIndex));
     m_uiForm.leWSIndices->setEnabled(false);
-  }
-  else
-  {
+  } else {
     m_uiForm.leWSIndices->setEnabled(true);
   }
-
 }
 
 /// Called on close if selection accepted.
-void AddWorkspaceDialog::accept()
-{
+void AddWorkspaceDialog::accept() {
   m_workspaceName = m_uiForm.cbWorkspaceName->currentText();
   m_wsIndices.clear();
   QString indexInput = m_uiForm.leWSIndices->text();
-  if ( !m_workspaceName.isEmpty() && !indexInput.isEmpty() )
-  {
-    auto validator = boost::make_shared<Mantid::Kernel::ArrayBoundedValidator<int>>(0,m_maxIndex);
-    Mantid::Kernel::ArrayProperty<int> prop("Indices",validator);
-    std::string err = prop.setValue( indexInput.toStdString() );
-    if ( err.empty() )
-    {
+  if (!m_workspaceName.isEmpty() && !indexInput.isEmpty()) {
+    auto validator =
+        boost::make_shared<Mantid::Kernel::ArrayBoundedValidator<int>>(
+            0, m_maxIndex);
+    Mantid::Kernel::ArrayProperty<int> prop("Indices", validator);
+    std::string err = prop.setValue(indexInput.toStdString());
+    if (err.empty()) {
       m_wsIndices = prop;
-    }
-    else
-    {
-      QMessageBox::warning(this, "MantidPlot - Error", QString("Some of the indices are outside the allowed range [0,%1]").arg(m_maxIndex));
+    } else {
+      QMessageBox::warning(
+          this, "MantidPlot - Error",
+          QString("Some of the indices are outside the allowed range [0,%1]")
+              .arg(m_maxIndex));
     }
   }
   QDialog::accept();
 }
 
 /// Called on close if selection rejected.
-void AddWorkspaceDialog::reject()
-{
+void AddWorkspaceDialog::reject() {
   m_workspaceName.clear();
   m_wsIndices.clear();
   QDialog::reject();
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDataController.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDataController.cpp
index b591988b0ddaebb4420565158897bc67da084ddf..40232b887591a193392c098dc4fc27b0e43f8052 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDataController.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDataController.cpp
@@ -9,82 +9,78 @@
 #include <QTableWidget>
 #include <QMessageBox>
 
-namespace{
-  // columns in the data table
-  const int wsColumn      = 0;
-  const int wsIndexColumn = 1;
-  const int startXColumn  = 2;
-  const int endXColumn    = 3;
-
-  QString makeNumber(double d) {return QString::number(d,'g',16);}
+namespace {
+// columns in the data table
+const int wsColumn = 0;
+const int wsIndexColumn = 1;
+const int startXColumn = 2;
+const int endXColumn = 3;
+
+QString makeNumber(double d) { return QString::number(d, 'g', 16); }
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Constructor.
-DataController::DataController(MultiDatasetFit *parent, QTableWidget *dataTable):
-  QObject(parent),m_dataTable(dataTable),m_isFittingRangeGlobal(false)
-{
-  connect(dataTable,SIGNAL(itemSelectionChanged()), this,SLOT(workspaceSelectionChanged()));
-  connect(dataTable,SIGNAL(cellChanged(int,int)),this,SLOT(updateDataset(int,int)));
+DataController::DataController(MultiDatasetFit *parent, QTableWidget *dataTable)
+    : QObject(parent), m_dataTable(dataTable), m_isFittingRangeGlobal(false) {
+  connect(dataTable, SIGNAL(itemSelectionChanged()), this,
+          SLOT(workspaceSelectionChanged()));
+  connect(dataTable, SIGNAL(cellChanged(int, int)), this,
+          SLOT(updateDataset(int, int)));
 }
 
 /// Show a dialog to select a workspace from the ADS.
-void DataController::addWorkspace()
-{
+void DataController::addWorkspace() {
   AddWorkspaceDialog dialog(owner());
-  if ( dialog.exec() == QDialog::Accepted )
-  {
+  if (dialog.exec() == QDialog::Accepted) {
     QString wsName = dialog.workspaceName().trimmed();
     // if name is empty assume that there are no workspaces in the ADS
-    if ( wsName.isEmpty() ) return;
-    if ( Mantid::API::AnalysisDataService::Instance().doesExist( wsName.toStdString()) )
-    {
+    if (wsName.isEmpty())
+      return;
+    if (Mantid::API::AnalysisDataService::Instance().doesExist(
+            wsName.toStdString())) {
       auto indices = dialog.workspaceIndices();
       std::vector<Mantid::API::MatrixWorkspace_sptr> matrixWorkspaces;
-      auto mws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>( wsName.toStdString() );
-      if ( mws )
-      {
+      auto mws =
+          Mantid::API::AnalysisDataService::Instance()
+              .retrieveWS<Mantid::API::MatrixWorkspace>(wsName.toStdString());
+      if (mws) {
         matrixWorkspaces.push_back(mws);
-      }
-      else
-      {
-        auto grp = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::WorkspaceGroup>( wsName.toStdString() );
-        if ( grp )
-        {
-          for(size_t i = 0; i < static_cast<size_t>(grp->getNumberOfEntries()); ++i)
-          {
-            mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(grp->getItem(i));
-            if ( mws )
-            {
+      } else {
+        auto grp =
+            Mantid::API::AnalysisDataService::Instance()
+                .retrieveWS<Mantid::API::WorkspaceGroup>(wsName.toStdString());
+        if (grp) {
+          for (size_t i = 0; i < static_cast<size_t>(grp->getNumberOfEntries());
+               ++i) {
+            mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+                grp->getItem(i));
+            if (mws) {
               matrixWorkspaces.push_back(mws);
             }
           }
         }
       }
 
-      if ( !matrixWorkspaces.empty() )
-      {
-        for(auto iws = matrixWorkspaces.begin(); iws != matrixWorkspaces.end(); ++iws)
-        {
+      if (!matrixWorkspaces.empty()) {
+        for (auto iws = matrixWorkspaces.begin(); iws != matrixWorkspaces.end();
+             ++iws) {
           auto name = QString::fromStdString((**iws).name());
-          for(auto i = indices.begin(); i != indices.end(); ++i)
-          {
-            addWorkspaceSpectrum( name, *i, **iws );
+          for (auto i = indices.begin(); i != indices.end(); ++i) {
+            addWorkspaceSpectrum(name, *i, **iws);
           }
         }
-        emit spectraAdded(static_cast<int>(indices.size() * matrixWorkspaces.size()));
+        emit spectraAdded(
+            static_cast<int>(indices.size() * matrixWorkspaces.size()));
         emit dataTableUpdated();
       }
-    }
-    else
-    {
-      QMessageBox::warning(owner(),"MantidPlot - Warning",QString("Workspace \"%1\" doesn't exist.").arg(wsName));
+    } else {
+      QMessageBox::warning(
+          owner(), "MantidPlot - Warning",
+          QString("Workspace \"%1\" doesn't exist.").arg(wsName));
     }
   }
 }
@@ -93,35 +89,35 @@ void DataController::addWorkspace()
 /// @param wsName :: Name of a workspace.
 /// @param wsIndex :: Index of a spectrum in the workspace (workspace index).
 /// @param ws :: The workspace.
-void DataController::addWorkspaceSpectrum(const QString &wsName, int wsIndex, const Mantid::API::MatrixWorkspace& ws)
-{
+void DataController::addWorkspaceSpectrum(
+    const QString &wsName, int wsIndex,
+    const Mantid::API::MatrixWorkspace &ws) {
   int row = m_dataTable->rowCount();
   m_dataTable->insertRow(row);
 
-  auto cell = new QTableWidgetItem( wsName );
-  m_dataTable->setItem( row, wsColumn, cell );
+  auto cell = new QTableWidgetItem(wsName);
+  m_dataTable->setItem(row, wsColumn, cell);
   auto flags = cell->flags();
   flags ^= Qt::ItemIsEditable;
   cell->setFlags(flags);
 
-  cell = new QTableWidgetItem( QString::number(wsIndex) );
-  m_dataTable->setItem( row, wsIndexColumn, cell );
+  cell = new QTableWidgetItem(QString::number(wsIndex));
+  m_dataTable->setItem(row, wsIndexColumn, cell);
   flags = cell->flags();
   flags ^= Qt::ItemIsEditable;
   cell->setFlags(flags);
 
   const double startX = ws.readX(wsIndex).front();
-  cell = new QTableWidgetItem( makeNumber(startX) );
-  m_dataTable->setItem( row, startXColumn, cell );
+  cell = new QTableWidgetItem(makeNumber(startX));
+  m_dataTable->setItem(row, startXColumn, cell);
 
   const double endX = ws.readX(wsIndex).back();
-  cell = new QTableWidgetItem( makeNumber(endX) );
-  m_dataTable->setItem( row, endXColumn, cell );
+  cell = new QTableWidgetItem(makeNumber(endX));
+  m_dataTable->setItem(row, endXColumn, cell);
 }
 
 /// Slot. Called when selection in the data table changes.
-void DataController::workspaceSelectionChanged()
-{
+void DataController::workspaceSelectionChanged() {
   auto selection = m_dataTable->selectionModel();
   bool enableRemoveButton = selection->hasSelection();
 
@@ -129,109 +125,95 @@ void DataController::workspaceSelectionChanged()
 }
 
 /// Slot. Called when "Remove" button is pressed.
-void DataController::removeSelectedSpectra()
-{
+void DataController::removeSelectedSpectra() {
   auto ranges = m_dataTable->selectedRanges();
-  if ( ranges.isEmpty() ) return;
+  if (ranges.isEmpty())
+    return;
   QList<int> rows;
-  for(auto range = ranges.begin(); range != ranges.end(); ++range)
-  {
-    for(int row = range->topRow(); row <= range->bottomRow(); ++row)
-    {
-      rows.push_back( row );
+  for (auto range = ranges.begin(); range != ranges.end(); ++range) {
+    for (int row = range->topRow(); row <= range->bottomRow(); ++row) {
+      rows.push_back(row);
     }
   }
-  removeSpectra( rows );
+  removeSpectra(rows);
 }
 
 /// Remove some spectra from fitting.
 /// @param rows :: A list of indices of the spacetra to remove.
-void DataController::removeSpectra( QList<int> rows )
-{
-  if ( rows.isEmpty() ) return;
+void DataController::removeSpectra(QList<int> rows) {
+  if (rows.isEmpty())
+    return;
   qSort(rows);
-  for(int i = rows.size() - 1; i >= 0; --i)
-  {
-    m_dataTable->removeRow( rows[i] );
+  for (int i = rows.size() - 1; i >= 0; --i) {
+    m_dataTable->removeRow(rows[i]);
   }
   emit spectraRemoved(rows);
   emit dataTableUpdated();
 }
 
 /// Check that the data sets in the table are valid and remove invalid ones.
-void DataController::checkSpectra()
-{
+void DataController::checkSpectra() {
   QList<int> rows;
   int nrows = getNumberOfSpectra();
-  auto& ADS = Mantid::API::AnalysisDataService::Instance();
-  for( int row = 0; row < nrows; ++row)
-  {
-    auto wsName = getWorkspaceName( row ).toStdString();
-    auto i = getWorkspaceIndex( row );
-    if ( !ADS.doesExist( wsName ) )
-    {
-      rows.push_back( row );
+  auto &ADS = Mantid::API::AnalysisDataService::Instance();
+  for (int row = 0; row < nrows; ++row) {
+    auto wsName = getWorkspaceName(row).toStdString();
+    auto i = getWorkspaceIndex(row);
+    if (!ADS.doesExist(wsName)) {
+      rows.push_back(row);
       continue;
     }
-    auto ws = ADS.retrieveWS<Mantid::API::MatrixWorkspace>( wsName );
-    if ( !ws || i >= static_cast<int>( ws->getNumberHistograms() ) )
-    {
-      rows.push_back( row );
+    auto ws = ADS.retrieveWS<Mantid::API::MatrixWorkspace>(wsName);
+    if (!ws || i >= static_cast<int>(ws->getNumberHistograms())) {
+      rows.push_back(row);
       continue;
     }
   }
 
-  removeSpectra( rows );
+  removeSpectra(rows);
 }
 
 /// Get the workspace name of the i-th spectrum.
 /// @param i :: Index of a spectrum in the data table.
-QString DataController::getWorkspaceName(int i) const
-{
+QString DataController::getWorkspaceName(int i) const {
   return m_dataTable->item(i, wsColumn)->text();
 }
 
 /// Get the workspace index of the i-th spectrum.
 /// @param i :: Index of a spectrum in the data table.
-int DataController::getWorkspaceIndex(int i) const
-{
+int DataController::getWorkspaceIndex(int i) const {
   return m_dataTable->item(i, wsIndexColumn)->text().toInt();
 }
 
 /// Get the number of spectra to fit to.
-int DataController::getNumberOfSpectra() const
-{
+int DataController::getNumberOfSpectra() const {
   return m_dataTable->rowCount();
 }
 
 /// Enable global setting of fitting range (calls to setFittingRage(...)
 /// will set ranges of all datasets.)
 /// @param on :: True for global setting, false for individual.
-void DataController::setFittingRangeGlobal(bool on)
-{
+void DataController::setFittingRangeGlobal(bool on) {
   m_isFittingRangeGlobal = on;
 }
 
 /// Set the fitting range for a data set or all data sets.
-/// @param i :: Index of a data set (spectrum). If m_isFittingRangeGlobal == true
+/// @param i :: Index of a data set (spectrum). If m_isFittingRangeGlobal ==
+/// true
 ///   the index is ignored and fitting range is set for all spectra.
 /// @param startX :: Start of the fitting range.
 /// @param endX :: End of the fitting range.
-void DataController::setFittingRange(int i, double startX, double endX)
-{
-  if ( i < 0 || i >= m_dataTable->rowCount() ) return;
+void DataController::setFittingRange(int i, double startX, double endX) {
+  if (i < 0 || i >= m_dataTable->rowCount())
+    return;
   auto start = makeNumber(startX);
   auto end = makeNumber(endX);
-  if ( m_isFittingRangeGlobal )
-  {
-    for(int k = 0; k < getNumberOfSpectra(); ++k)
-    {
+  if (m_isFittingRangeGlobal) {
+    for (int k = 0; k < getNumberOfSpectra(); ++k) {
       m_dataTable->item(k, startXColumn)->setText(start);
       m_dataTable->item(k, endXColumn)->setText(end);
     }
-  }
-  else
-  {
+  } else {
     m_dataTable->item(i, startXColumn)->setText(start);
     m_dataTable->item(i, endXColumn)->setText(end);
   }
@@ -239,21 +221,19 @@ void DataController::setFittingRange(int i, double startX, double endX)
 
 /// Get the fitting range for a i-th data set.
 /// @param i :: Index of a dataset.
-std::pair<double,double> DataController::getFittingRange(int i) const
-{
+std::pair<double, double> DataController::getFittingRange(int i) const {
   double startX = m_dataTable->item(i, startXColumn)->text().toDouble();
   double endX = m_dataTable->item(i, endXColumn)->text().toDouble();
-  return std::make_pair(startX,endX);
+  return std::make_pair(startX, endX);
 }
 
 /// Inform the others that a dataset was updated.
-void DataController::updateDataset(int row, int)
-{
-  emit dataSetUpdated(row);
-}
+void DataController::updateDataset(int row, int) { emit dataSetUpdated(row); }
 
 /// Object's parent cast to MultiDatasetFit.
-MultiDatasetFit *DataController::owner() const {return static_cast<MultiDatasetFit*>(parent());}
+MultiDatasetFit *DataController::owner() const {
+  return static_cast<MultiDatasetFit *>(parent());
+}
 
 } // MDF
 } // CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDatasetPlotData.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDatasetPlotData.cpp
index d32a80914f435c5134403bda33fa91b6f59d940b..ae10594652238e5911666c2d8a3979cfe7c2d2fb 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDatasetPlotData.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFDatasetPlotData.cpp
@@ -7,80 +7,77 @@
 
 #include <qwt_plot_curve.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
-  
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
+
 /// Constructor.
 /// @param wsName :: Name of a MatrixWorkspace with the data for fitting.
 /// @param wsIndex :: Workspace index of a spectrum in wsName to plot.
-/// @param outputWSName :: Name of the Fit's output workspace containing at least 3 spectra:
-///    #0 - original data (the same as in wsName[wsIndex]), #1 - calculated data, #3 - difference.
+/// @param outputWSName :: Name of the Fit's output workspace containing at
+/// least 3 spectra:
+///    #0 - original data (the same as in wsName[wsIndex]), #1 - calculated
+///    data, #3 - difference.
 ///    If empty - ignore this workspace.
-DatasetPlotData::DatasetPlotData(const QString& wsName, int wsIndex, const QString& outputWSName):
-  m_dataCurve(new QwtPlotCurve(wsName + QString(" (%1)").arg(wsIndex))),
-  m_dataErrorCurve(NULL),
-  m_calcCurve(NULL),
-  m_diffCurve(NULL),
-  m_showDataErrorBars(false)
-{
+DatasetPlotData::DatasetPlotData(const QString &wsName, int wsIndex,
+                                 const QString &outputWSName)
+    : m_dataCurve(new QwtPlotCurve(wsName + QString(" (%1)").arg(wsIndex))),
+      m_dataErrorCurve(NULL), m_calcCurve(NULL), m_diffCurve(NULL),
+      m_showDataErrorBars(false) {
   // get the data workspace
-  auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>( wsName.toStdString() );
-  if ( !ws )
-  {
-    QString mess = QString("Workspace %1 either doesn't exist or isn't a MatrixWorkspace").arg(wsName);
-    throw std::runtime_error( mess.toStdString() );
+  auto ws = Mantid::API::AnalysisDataService::Instance()
+                .retrieveWS<Mantid::API::MatrixWorkspace>(wsName.toStdString());
+  if (!ws) {
+    QString mess =
+        QString("Workspace %1 either doesn't exist or isn't a MatrixWorkspace")
+            .arg(wsName);
+    throw std::runtime_error(mess.toStdString());
   }
   // check that the index is in range
-  if ( static_cast<size_t>(wsIndex) >= ws->getNumberHistograms() )
-  {
-    QString mess = QString("Spectrum %1 doesn't exist in workspace %2").arg(wsIndex).arg(wsName);
-    throw std::runtime_error( mess.toStdString() );
+  if (static_cast<size_t>(wsIndex) >= ws->getNumberHistograms()) {
+    QString mess = QString("Spectrum %1 doesn't exist in workspace %2")
+                       .arg(wsIndex)
+                       .arg(wsName);
+    throw std::runtime_error(mess.toStdString());
   }
 
   // get the data workspace
   Mantid::API::MatrixWorkspace_sptr outputWS;
-  if ( !outputWSName.isEmpty() )
-  {
+  if (!outputWSName.isEmpty()) {
     std::string stdOutputWSName = outputWSName.toStdString();
-    if ( Mantid::API::AnalysisDataService::Instance().doesExist(stdOutputWSName) )
-    {
-      try
-      {
-        outputWS = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>( stdOutputWSName );
-      }
-      catch ( Mantid::Kernel::Exception::NotFoundError& )
-      {
-        QString mess = QString("Workspace %1 either doesn't exist or isn't a MatrixWorkspace").arg(outputWSName);
-        throw std::runtime_error( mess.toStdString() );
+    if (Mantid::API::AnalysisDataService::Instance().doesExist(
+            stdOutputWSName)) {
+      try {
+        outputWS =
+            Mantid::API::AnalysisDataService::Instance()
+                .retrieveWS<Mantid::API::MatrixWorkspace>(stdOutputWSName);
+      } catch (Mantid::Kernel::Exception::NotFoundError &) {
+        QString mess =
+            QString(
+                "Workspace %1 either doesn't exist or isn't a MatrixWorkspace")
+                .arg(outputWSName);
+        throw std::runtime_error(mess.toStdString());
       }
     }
   }
 
   // create the curves
-  setData( ws.get(), wsIndex, outputWS.get() );
+  setData(ws.get(), wsIndex, outputWS.get());
 }
 
 /// Destructor.
-DatasetPlotData::~DatasetPlotData()
-{
+DatasetPlotData::~DatasetPlotData() {
   m_dataCurve->detach();
   delete m_dataCurve;
-  if ( m_dataErrorCurve )
-  {
+  if (m_dataErrorCurve) {
     m_dataErrorCurve->detach();
     delete m_dataErrorCurve;
   }
-  if ( m_calcCurve )
-  {
+  if (m_calcCurve) {
     m_calcCurve->detach();
     delete m_calcCurve;
   }
-  if ( m_diffCurve )
-  {
+  if (m_diffCurve) {
     m_diffCurve->detach();
     delete m_diffCurve;
   }
@@ -88,105 +85,94 @@ DatasetPlotData::~DatasetPlotData()
 
 /// Set the data to the curves.
 /// @param ws :: A Fit's input workspace.
-/// @param wsIndex :: Workspace index of a spectrum to costruct the plot data for.
-/// @param outputWS :: The output workspace from Fit containing the calculated spectrum.
-void DatasetPlotData::setData(const Mantid::API::MatrixWorkspace *ws, int wsIndex, const Mantid::API::MatrixWorkspace *outputWS)
-{
+/// @param wsIndex :: Workspace index of a spectrum to costruct the plot data
+/// for.
+/// @param outputWS :: The output workspace from Fit containing the calculated
+/// spectrum.
+void DatasetPlotData::setData(const Mantid::API::MatrixWorkspace *ws,
+                              int wsIndex,
+                              const Mantid::API::MatrixWorkspace *outputWS) {
   bool haveFitCurves = outputWS && outputWS->getNumberHistograms() >= 3;
   std::vector<double> xValues = ws->readX(wsIndex);
-  if ( ws->isHistogramData() )
-  {
+  if (ws->isHistogramData()) {
     auto xend = xValues.end() - 1;
-    for(auto x = xValues.begin(); x != xend; ++x)
-    {
-      *x = (*x + *(x+1))/2;
+    for (auto x = xValues.begin(); x != xend; ++x) {
+      *x = (*x + *(x + 1)) / 2;
     }
     xValues.pop_back();
   }
-  m_dataCurve->setData( xValues.data(), ws->readY(wsIndex).data(), static_cast<int>(xValues.size()) );
+  m_dataCurve->setData(xValues.data(), ws->readY(wsIndex).data(),
+                       static_cast<int>(xValues.size()));
 
-  if (m_dataErrorCurve)
-  {
+  if (m_dataErrorCurve) {
     m_dataErrorCurve->detach();
     delete m_dataErrorCurve;
   }
-  m_dataErrorCurve = new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, ws->readE(wsIndex));
+  m_dataErrorCurve =
+      new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, ws->readE(wsIndex));
 
-  if ( haveFitCurves )
-  {
-    auto xBegin = std::lower_bound(xValues.begin(),xValues.end(), outputWS->readX(1).front());
-    if ( xBegin == xValues.end() ) return;
-    int i0 = static_cast<int>(std::distance(xValues.begin(),xBegin));
+  if (haveFitCurves) {
+    auto xBegin = std::lower_bound(xValues.begin(), xValues.end(),
+                                   outputWS->readX(1).front());
+    if (xBegin == xValues.end())
+      return;
+    int i0 = static_cast<int>(std::distance(xValues.begin(), xBegin));
     int n = static_cast<int>(outputWS->readY(1).size());
-    if ( i0 + n > static_cast<int>(xValues.size()) ) return;
+    if (i0 + n > static_cast<int>(xValues.size()))
+      return;
     m_calcCurve = new QwtPlotCurve("calc");
-    m_calcCurve->setData( xValues.data() + i0, outputWS->readY(1).data(), n );
+    m_calcCurve->setData(xValues.data() + i0, outputWS->readY(1).data(), n);
     QPen penCalc("red");
     m_calcCurve->setPen(penCalc);
     m_diffCurve = new QwtPlotCurve("diff");
-    m_diffCurve->setData( xValues.data() + i0, outputWS->readY(2).data(), n );
+    m_diffCurve->setData(xValues.data() + i0, outputWS->readY(2).data(), n);
     QPen penDiff("green");
     m_diffCurve->setPen(penDiff);
   }
 }
 
 /// Show the curves on a plot.
-void DatasetPlotData::show(QwtPlot *plot)
-{
+void DatasetPlotData::show(QwtPlot *plot) {
   m_dataCurve->attach(plot);
-  if (m_showDataErrorBars)
-  {
+  if (m_showDataErrorBars) {
     m_dataErrorCurve->attach(plot);
-  }
-  else
-  {
+  } else {
     m_dataErrorCurve->detach();
   }
-  if ( m_calcCurve )
-  {
+  if (m_calcCurve) {
     m_calcCurve->attach(plot);
   }
-  if ( m_diffCurve )
-  {
+  if (m_diffCurve) {
     m_diffCurve->attach(plot);
   }
 }
 
 /// Hide the curves from any plot.
-void DatasetPlotData::hide()
-{
+void DatasetPlotData::hide() {
   m_dataCurve->detach();
   m_dataErrorCurve->detach();
-  if ( m_calcCurve )
-  {
+  if (m_calcCurve) {
     m_calcCurve->detach();
   }
-  if ( m_diffCurve )
-  {
+  if (m_diffCurve) {
     m_diffCurve->detach();
   }
 }
 
 /// Get the bounding rect including all plotted data.
-QwtDoubleRect DatasetPlotData::boundingRect() const
-{
+QwtDoubleRect DatasetPlotData::boundingRect() const {
   QwtDoubleRect rect = m_dataCurve->boundingRect();
-  if ( m_calcCurve )
-  {
-    rect = rect.united( m_calcCurve->boundingRect() );
+  if (m_calcCurve) {
+    rect = rect.united(m_calcCurve->boundingRect());
   }
-  if ( m_diffCurve )
-  {
-    rect = rect.united( m_diffCurve->boundingRect() );
+  if (m_diffCurve) {
+    rect = rect.united(m_diffCurve->boundingRect());
   }
   return rect;
 }
 
 /// Toggle the error bars on the data curve.
-void DatasetPlotData::showDataErrorBars(bool on)
-{
-  m_showDataErrorBars = on;
-}
+void DatasetPlotData::showDataErrorBars(bool on) { m_showDataErrorBars = on; }
 
 } // MDF
 } // CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFEditLocalParameterDialog.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFEditLocalParameterDialog.cpp
index 8245272e3bfa60d3d2661ae42376725e3066c5ed..55c7ca862ddd1437beb7d3c397ae25ad28c55a01 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFEditLocalParameterDialog.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFEditLocalParameterDialog.cpp
@@ -5,40 +5,37 @@
 #include <QMenu>
 #include <QClipboard>
 
-namespace{
-  QString makeNumber(double d) {return QString::number(d,'g',16);}
-  const int valueColumn = 0;
-  const int roleColumn  = 1;
+namespace {
+QString makeNumber(double d) { return QString::number(d, 'g', 16); }
+const int valueColumn = 0;
+const int roleColumn = 1;
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Constructor.
-EditLocalParameterDialog::EditLocalParameterDialog(MultiDatasetFit *multifit, const QString &parName):
-  QDialog(multifit),m_parName(parName)
-{
+EditLocalParameterDialog::EditLocalParameterDialog(MultiDatasetFit *multifit,
+                                                   const QString &parName)
+    : QDialog(multifit), m_parName(parName) {
   m_uiForm.setupUi(this);
   QHeaderView *header = m_uiForm.tableWidget->horizontalHeader();
-  header->setResizeMode(0,QHeaderView::Stretch);
-  connect(m_uiForm.tableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(valueChanged(int,int)));
+  header->setResizeMode(0, QHeaderView::Stretch);
+  connect(m_uiForm.tableWidget, SIGNAL(cellChanged(int, int)), this,
+          SLOT(valueChanged(int, int)));
   m_uiForm.lblParameterName->setText("Parameter: " + parName);
 
   auto n = multifit->getNumberOfSpectra();
-  for(int i = 0; i < n; ++i)
-  {
-    double value = multifit->getLocalParameterValue(parName,i);
+  for (int i = 0; i < n; ++i) {
+    double value = multifit->getLocalParameterValue(parName, i);
     m_values.push_back(value);
-    bool fixed = multifit->isLocalParameterFixed(parName,i);
+    bool fixed = multifit->isLocalParameterFixed(parName, i);
     m_fixes.push_back(fixed);
-    auto tie = multifit->getLocalParameterTie(parName,i);
+    auto tie = multifit->getLocalParameterTie(parName, i);
     m_ties.push_back(tie);
     m_uiForm.tableWidget->insertRow(i);
-    auto cell = new QTableWidgetItem( makeNumber(value) );
+    auto cell = new QTableWidgetItem(makeNumber(value));
     m_uiForm.tableWidget->setItem(i, valueColumn, cell);
     auto headerItem = new QTableWidgetItem(
         multifit->getWorkspaceName(i) + " (" +
@@ -55,11 +52,14 @@ EditLocalParameterDialog::EditLocalParameterDialog(MultiDatasetFit *multifit, co
   }
   auto deleg = new LocalParameterItemDelegate(this);
   m_uiForm.tableWidget->setItemDelegateForColumn(valueColumn, deleg);
-  connect(deleg,SIGNAL(setAllValues(double)),this,SLOT(setAllValues(double)));
-  connect(deleg,SIGNAL(fixParameter(int,bool)),this,SLOT(fixParameter(int,bool)));
-  connect(deleg,SIGNAL(setAllFixed(bool)),this,SLOT(setAllFixed(bool)));
-  connect(deleg,SIGNAL(setTie(int,QString)),this,SLOT(setTie(int,QString)));
-  connect(deleg,SIGNAL(setTieAll(QString)),this,SLOT(setTieAll(QString)));
+  connect(deleg, SIGNAL(setAllValues(double)), this,
+          SLOT(setAllValues(double)));
+  connect(deleg, SIGNAL(fixParameter(int, bool)), this,
+          SLOT(fixParameter(int, bool)));
+  connect(deleg, SIGNAL(setAllFixed(bool)), this, SLOT(setAllFixed(bool)));
+  connect(deleg, SIGNAL(setTie(int, QString)), this,
+          SLOT(setTie(int, QString)));
+  connect(deleg, SIGNAL(setTieAll(QString)), this, SLOT(setTieAll(QString)));
 
   m_uiForm.tableWidget->installEventFilter(this);
 }
@@ -67,13 +67,10 @@ EditLocalParameterDialog::EditLocalParameterDialog(MultiDatasetFit *multifit, co
 /// Slot. Called when a value changes.
 /// @param row :: Row index of the changed cell.
 /// @param col :: Column index of the changed cell.
-void EditLocalParameterDialog::valueChanged(int row, int col)
-{
-  if ( col == valueColumn )
-  {
-    QString text = m_uiForm.tableWidget->item(row,col)->text();
-    try
-    {
+void EditLocalParameterDialog::valueChanged(int row, int col) {
+  if (col == valueColumn) {
+    QString text = m_uiForm.tableWidget->item(row, col)->text();
+    try {
       bool ok = false;
       double value = text.toDouble(&ok);
       if (ok) {
@@ -81,51 +78,37 @@ void EditLocalParameterDialog::valueChanged(int row, int col)
       } else {
         m_ties[row] = text;
       }
-    }
-    catch(std::exception&)
-    {
+    } catch (std::exception &) {
       // restore old value
-      m_uiForm.tableWidget->item(row,col)->setText( makeNumber(m_values[row]) );
+      m_uiForm.tableWidget->item(row, col)->setText(makeNumber(m_values[row]));
     }
   }
 }
 
 /// Set all parameters to the same value.
 /// @param value :: A new value.
-void EditLocalParameterDialog::setAllValues(double value)
-{
+void EditLocalParameterDialog::setAllValues(double value) {
   int n = m_values.size();
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     m_values[i] = value;
-    m_uiForm.tableWidget->item(i, valueColumn)->setText( makeNumber(value) );
+    m_uiForm.tableWidget->item(i, valueColumn)->setText(makeNumber(value));
     updateRoleColumn(i);
   }
 }
 
 /// Get the list of new parameter values.
-QList<double> EditLocalParameterDialog::getValues() const
-{
-  return m_values;
-}
+QList<double> EditLocalParameterDialog::getValues() const { return m_values; }
 
 /// Get a list with the "fixed" attribute.
-QList<bool> EditLocalParameterDialog::getFixes() const
-{
-  return m_fixes;
-}
+QList<bool> EditLocalParameterDialog::getFixes() const { return m_fixes; }
 
 /// Get a list of the ties.
-QStringList EditLocalParameterDialog::getTies() const
-{
-  return m_ties;
-}
+QStringList EditLocalParameterDialog::getTies() const { return m_ties; }
 
 /// Fix/unfix a single parameter.
 /// @param index :: Index of a paramter to fix or unfix.
 /// @param fix :: Fix (true) or unfix (false).
-void EditLocalParameterDialog::fixParameter(int index, bool fix)
-{
+void EditLocalParameterDialog::fixParameter(int index, bool fix) {
   m_fixes[index] = fix;
   m_ties[index] = "";
   updateRoleColumn(index);
@@ -134,8 +117,7 @@ void EditLocalParameterDialog::fixParameter(int index, bool fix)
 /// Set a new tie for a parameter
 /// @param index :: Index of a paramter to tie.
 /// @param tie :: A tie string.
-void EditLocalParameterDialog::setTie(int index, QString tie)
-{
+void EditLocalParameterDialog::setTie(int index, QString tie) {
   m_ties[index] = tie;
   m_fixes[index] = false;
   updateRoleColumn(index);
@@ -143,10 +125,8 @@ void EditLocalParameterDialog::setTie(int index, QString tie)
 
 /// Set the same tie to all parameters.
 /// @param tie :: A tie string.
-void EditLocalParameterDialog::setTieAll(QString tie)
-{
-  for(int i = 0; i < m_ties.size(); ++i)
-  {
+void EditLocalParameterDialog::setTieAll(QString tie) {
+  for (int i = 0; i < m_ties.size(); ++i) {
     m_ties[i] = tie;
     m_fixes[i] = false;
     updateRoleColumn(i);
@@ -156,11 +136,10 @@ void EditLocalParameterDialog::setTieAll(QString tie)
 
 /// Fix/unfix all parameters.
 /// @param fix :: Fix (true) or unfix (false).
-void EditLocalParameterDialog::setAllFixed(bool fix)
-{
-  if ( m_fixes.empty() ) return;
-  for(int i = 0; i < m_fixes.size(); ++i)
-  {
+void EditLocalParameterDialog::setAllFixed(bool fix) {
+  if (m_fixes.empty())
+    return;
+  for (int i = 0; i < m_fixes.size(); ++i) {
     m_fixes[i] = fix;
     m_ties[i] = "";
     updateRoleColumn(i);
@@ -169,40 +148,38 @@ void EditLocalParameterDialog::setAllFixed(bool fix)
 }
 
 /// Event filter for managing the context menu.
-bool EditLocalParameterDialog::eventFilter(QObject * obj, QEvent * ev)
-{
-  if ( obj == m_uiForm.tableWidget && ev->type() == QEvent::ContextMenu )
-  {
+bool EditLocalParameterDialog::eventFilter(QObject *obj, QEvent *ev) {
+  if (obj == m_uiForm.tableWidget && ev->type() == QEvent::ContextMenu) {
     showContextMenu();
   }
-  return QDialog::eventFilter(obj,ev);
+  return QDialog::eventFilter(obj, ev);
 }
 
 /// Show the context menu.
-void EditLocalParameterDialog::showContextMenu()
-{
+void EditLocalParameterDialog::showContextMenu() {
   auto selection = m_uiForm.tableWidget->selectionModel()->selectedColumns();
 
   bool hasSelection = false;
 
-  for(auto index = selection.begin(); index != selection.end(); ++index)
-  {
-    if ( index->column() == valueColumn ) hasSelection = true;
+  for (auto index = selection.begin(); index != selection.end(); ++index) {
+    if (index->column() == valueColumn)
+      hasSelection = true;
   }
 
-  if ( !hasSelection ) return;
+  if (!hasSelection)
+    return;
 
   QMenu *menu = new QMenu(this);
   {
-    QAction *action = new QAction("Copy",this);
+    QAction *action = new QAction("Copy", this);
     action->setToolTip("Copy data to clipboard.");
-    connect(action,SIGNAL(activated()),this,SLOT(copy()));
+    connect(action, SIGNAL(activated()), this, SLOT(copy()));
     menu->addAction(action);
   }
   {
-    QAction *action = new QAction("Paste",this);
+    QAction *action = new QAction("Paste", this);
     action->setToolTip("Paste data from clipboard.");
-    connect(action,SIGNAL(activated()),this,SLOT(paste()));
+    connect(action, SIGNAL(activated()), this, SLOT(paste()));
     auto text = QApplication::clipboard()->text();
     action->setEnabled(!text.isEmpty());
     menu->addAction(action);
@@ -213,92 +190,78 @@ void EditLocalParameterDialog::showContextMenu()
 
 /// Copy all parameter values to the clipboard.
 /// Values will be separated by '\n'
-void EditLocalParameterDialog::copy()
-{
+void EditLocalParameterDialog::copy() {
   QStringList text;
   auto n = m_values.size();
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     text << makeNumber(m_values[i]);
   }
-  QApplication::clipboard()->setText( text.join("\n") );
+  QApplication::clipboard()->setText(text.join("\n"));
 }
 
 /// Paste a list of values from the clipboard.
-void EditLocalParameterDialog::paste()
-{
+void EditLocalParameterDialog::paste() {
   auto text = QApplication::clipboard()->text();
-  auto vec = text.split(QRegExp("\\s|,"),QString::SkipEmptyParts);
+  auto vec = text.split(QRegExp("\\s|,"), QString::SkipEmptyParts);
   auto n = qMin(vec.size(), m_uiForm.tableWidget->rowCount());
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     auto str = vec[i];
     bool ok;
     m_values[i] = str.toDouble(&ok);
-    if ( !ok ) str = "0";
-    m_uiForm.tableWidget->item(i,1)->setText( str );
+    if (!ok)
+      str = "0";
+    m_uiForm.tableWidget->item(i, 1)->setText(str);
   }
 }
 
 /// Force the table to redraw its cells.
-void EditLocalParameterDialog::redrawCells()
-{
-  for(int i = 0; i < m_values.size(); ++i)
-  {
+void EditLocalParameterDialog::redrawCells() {
+  for (int i = 0; i < m_values.size(); ++i) {
     // it's the only way I am able to make the table to repaint itself
     auto text = makeNumber(m_values[i]);
-    m_uiForm.tableWidget->item(i, valueColumn)->setText( text + " " );
-    m_uiForm.tableWidget->item(i, valueColumn)->setText( text );
+    m_uiForm.tableWidget->item(i, valueColumn)->setText(text + " ");
+    m_uiForm.tableWidget->item(i, valueColumn)->setText(text);
   }
 }
 
 /// Update the text in the role column
-void EditLocalParameterDialog::updateRoleColumn(int index)
-{
+void EditLocalParameterDialog::updateRoleColumn(int index) {
   auto cell = m_uiForm.tableWidget->item(index, roleColumn);
-  if (m_fixes[index])
-  {
+  if (m_fixes[index]) {
     cell->setText("fixed");
     cell->setForeground(QBrush(Qt::red));
-  }
-  else if (!m_ties[index].isEmpty())
-  {
+  } else if (!m_ties[index].isEmpty()) {
     cell->setText("tied");
     cell->setForeground(QBrush(Qt::blue));
-  }
-  else
-  {
+  } else {
     cell->setText("fitted");
     cell->setForeground(QBrush(Qt::darkGreen));
   }
 }
 
 /// Check if there are any other fixed parameters
-bool EditLocalParameterDialog::areOthersFixed(int i) const
-{
-  for (int j = 0; j < m_fixes.size(); ++j)
-  {
-    if (j != i && m_fixes[j]) return true;
+bool EditLocalParameterDialog::areOthersFixed(int i) const {
+  for (int j = 0; j < m_fixes.size(); ++j) {
+    if (j != i && m_fixes[j])
+      return true;
   }
   return false;
 }
 
 /// Check if all other parameters are fixed
-bool EditLocalParameterDialog::areAllOthersFixed(int i) const
-{
-  for (int j = 0; j < m_fixes.size(); ++j)
-  {
-    if (j != i && !m_fixes[j]) return false;
+bool EditLocalParameterDialog::areAllOthersFixed(int i) const {
+  for (int j = 0; j < m_fixes.size(); ++j) {
+    if (j != i && !m_fixes[j])
+      return false;
   }
   return true;
 }
 
 /// Check if there are any other tied parameters
-bool EditLocalParameterDialog::areOthersTied(int i) const
-{
-  for (int j = 0; j < m_fixes.size(); ++j)
-  {
-    if (j != i && !m_ties[j].isEmpty()) return true;
+bool EditLocalParameterDialog::areOthersTied(int i) const {
+  for (int j = 0; j < m_fixes.size(); ++j) {
+    if (j != i && !m_ties[j].isEmpty())
+      return true;
   }
   return false;
 }
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFFunctionPlotData.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFFunctionPlotData.cpp
index 3bc18fe14253cabd4849973f1d3dcfb43b2f09be..10971dcb0635f754c5e2260ad60cffb540272a99 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFFunctionPlotData.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFFunctionPlotData.cpp
@@ -11,23 +11,18 @@
 #include <qwt_plot.h>
 #include <qwt_plot_curve.h>
 
-
-
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Default size of the function domain
 size_t MDFFunctionPlotData::g_defaultDomainSize = 100;
 
 namespace {
-  /// Default curve color
-  auto FUNCTION_CURVE_COLOR = Qt::magenta;
+/// Default curve color
+auto FUNCTION_CURVE_COLOR = Qt::magenta;
 }
-  
+
 /// Constructor.
 /// @param fun :: A function to plot.
 /// @param startX :: A lower bound of the evaluation interval.
@@ -36,8 +31,7 @@ namespace {
 MDFFunctionPlotData::MDFFunctionPlotData(
     boost::shared_ptr<Mantid::API::IFunction> fun, double startX, double endX,
     size_t nX)
-    : m_function(fun), m_functionCurve(new QwtPlotCurve()) 
-{
+    : m_function(fun), m_functionCurve(new QwtPlotCurve()) {
   setDomain(startX, endX, nX);
   auto pen = m_functionCurve->pen();
   pen.setColor(FUNCTION_CURVE_COLOR);
@@ -45,19 +39,18 @@ MDFFunctionPlotData::MDFFunctionPlotData(
 }
 
 /// Destructor.
-MDFFunctionPlotData::~MDFFunctionPlotData()
-{
+MDFFunctionPlotData::~MDFFunctionPlotData() {
   m_functionCurve->detach();
   delete m_functionCurve;
 }
 
 /// Define function's domain and set the data to the curve.
-void MDFFunctionPlotData::setDomain(double startX, double endX, size_t nX)
-{
+void MDFFunctionPlotData::setDomain(double startX, double endX, size_t nX) {
   Mantid::API::FunctionDomain1DVector x(startX, endX, nX);
   Mantid::API::FunctionValues y(x);
   m_function->function(x, y);
-  m_functionCurve->setData(x.getPointerAt(0), y.getPointerToCalculated(0), static_cast<int>(x.size()));
+  m_functionCurve->setData(x.getPointerAt(0), y.getPointerToCalculated(0),
+                           static_cast<int>(x.size()));
 }
 
 /// Show the curves on a plot.
@@ -78,48 +71,41 @@ void MDFFunctionPlotData::show(QwtPlot *plot) {
 }
 
 /// Hide the curves from any plot.
-void MDFFunctionPlotData::hide()
-{
-  m_functionCurve->detach();
-}
+void MDFFunctionPlotData::hide() { m_functionCurve->detach(); }
 
 /// Get the bounding rect including all plotted data.
-QwtDoubleRect MDFFunctionPlotData::boundingRect() const
-{
+QwtDoubleRect MDFFunctionPlotData::boundingRect() const {
   QwtDoubleRect rect = m_functionCurve->boundingRect();
   return rect;
 }
 
 /// Update function parameters and attributes
 /// @param fun :: A function to copy attributes and parameters from.
-void MDFFunctionPlotData::updateFunction(const Mantid::API::IFunction& fun)
-{
-  if (!m_function) return;
-  if (m_function->nParams() != fun.nParams())
-  {
-    throw std::logic_error("Cannot update function: different number of parameters.");
+void MDFFunctionPlotData::updateFunction(const Mantid::API::IFunction &fun) {
+  if (!m_function)
+    return;
+  if (m_function->nParams() != fun.nParams()) {
+    throw std::logic_error(
+        "Cannot update function: different number of parameters.");
   }
-  if (m_function->nAttributes() != fun.nAttributes())
-  {
-    throw std::logic_error("Cannot update function: different number of attributes.");
+  if (m_function->nAttributes() != fun.nAttributes()) {
+    throw std::logic_error(
+        "Cannot update function: different number of attributes.");
   }
   // Copy the attributes
   auto attributes = fun.getAttributeNames();
-  for(auto attr = attributes.begin(); attr != attributes.end(); ++attr)
-  {
+  for (auto attr = attributes.begin(); attr != attributes.end(); ++attr) {
     auto value = fun.getAttribute(*attr);
     m_function->setAttribute(*attr, value);
   }
   // Copy the parameters
-  for(size_t i = 0; i < fun.nParams(); ++i)
-  {
+  for (size_t i = 0; i < fun.nParams(); ++i) {
     auto name = fun.parameterName(i);
     auto value = fun.getParameter(i);
     m_function->setParameter(name, value);
   }
 }
 
-
 } // MDF
 } // CustomInterfaces
 } // MantidQt
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterEditor.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterEditor.cpp
index b0b9d75b82e29940d9333ebe1c80a6686b09308f..813ad46e06f15cc8ca136ee402ef459060c46ae4 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterEditor.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterEditor.cpp
@@ -10,12 +10,9 @@
 #include <QKeyEvent>
 #include <QInputDialog>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 /// Constructor
 /// @param parent :: Parent widget.
 /// @param index :: Index of the spectrum which parameter is edited.
@@ -25,74 +22,75 @@ namespace MDF
 /// @param othersFixed :: True if some other local parameters are fixed.
 /// @param allOthersFixed :: True if all other local parameters are fixed.
 /// @param othersTied :: True if there are other tied parameters.
-  LocalParameterEditor::LocalParameterEditor(QWidget *parent, int index,
+LocalParameterEditor::LocalParameterEditor(QWidget *parent, int index,
                                            double value, bool fixed,
                                            QString tie, bool othersFixed,
                                            bool allOthersFixed, bool othersTied)
-    : QWidget(parent), m_index(index), m_value(QString::number(value,'g',16)),
+    : QWidget(parent), m_index(index), m_value(QString::number(value, 'g', 16)),
       m_fixed(fixed), m_tie(tie), m_othersFixed(othersFixed),
       m_allOthersFixed(allOthersFixed), m_othersTied(othersTied) {
   auto layout = new QHBoxLayout(this);
   layout->setMargin(0);
   layout->setSpacing(0);
-  layout->setContentsMargins(0,0,0,0);
+  layout->setContentsMargins(0, 0, 0, 0);
 
   m_editor = new QLineEdit(parent);
-  m_editor->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
+  m_editor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
   this->setFocusPolicy(Qt::StrongFocus);
   this->setFocusProxy(m_editor);
 
   m_button = new QPushButton("&Set");
-  m_button->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
+  m_button->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
   m_button->setFocusPolicy(Qt::NoFocus);
 
   layout->addWidget(m_editor);
   layout->addWidget(m_button);
-  layout->setStretch(0,1);
-  layout->setStretch(1,0);
+  layout->setStretch(0, 1);
+  layout->setStretch(1, 0);
 
   auto setMenu = new QMenu(this);
 
-  m_setAllAction = new QAction("Set to all",this);
+  m_setAllAction = new QAction("Set to all", this);
   m_setAllAction->setToolTip("Set all parameters to this value");
-  connect(m_setAllAction,SIGNAL(activated()),this,SLOT(setAll()));
+  connect(m_setAllAction, SIGNAL(activated()), this, SLOT(setAll()));
   setMenu->addAction(m_setAllAction);
 
   setMenu->addSeparator();
-  m_fixAction = new QAction(m_fixed? "Unfix" : "Fix", this);
+  m_fixAction = new QAction(m_fixed ? "Unfix" : "Fix", this);
   m_fixAction->setToolTip("Fix value of this parameter");
-  connect(m_fixAction,SIGNAL(activated()),this,SLOT(fixParameter()));
+  connect(m_fixAction, SIGNAL(activated()), this, SLOT(fixParameter()));
   setMenu->addAction(m_fixAction);
 
-  m_fixAllAction = new QAction("Fix all",this);
+  m_fixAllAction = new QAction("Fix all", this);
   m_fixAllAction->setToolTip("Fix all parameters.");
-  connect(m_fixAllAction,SIGNAL(activated()),this,SLOT(fixAll()));
+  connect(m_fixAllAction, SIGNAL(activated()), this, SLOT(fixAll()));
   setMenu->addAction(m_fixAllAction);
 
-  m_unfixAllAction = new QAction("Unfix all",this);
+  m_unfixAllAction = new QAction("Unfix all", this);
   m_unfixAllAction->setToolTip("Unfix all parameters.");
-  connect(m_unfixAllAction,SIGNAL(activated()),this,SLOT(unfixAll()));
+  connect(m_unfixAllAction, SIGNAL(activated()), this, SLOT(unfixAll()));
   setMenu->addAction(m_unfixAllAction);
 
   setMenu->addSeparator();
-  m_setTieAction = new QAction("Set tie",this);
+  m_setTieAction = new QAction("Set tie", this);
   m_setTieAction->setToolTip("Set a tie for this parameter.");
-  connect(m_setTieAction,SIGNAL(activated()),this,SLOT(setTie()));
+  connect(m_setTieAction, SIGNAL(activated()), this, SLOT(setTie()));
   setMenu->addAction(m_setTieAction);
 
-  m_removeTieAction = new QAction("Remove tie",this);
+  m_removeTieAction = new QAction("Remove tie", this);
   m_removeTieAction->setToolTip("Remove the tie for this parameter.");
-  connect(m_removeTieAction,SIGNAL(activated()),this,SLOT(removeTie()));
+  connect(m_removeTieAction, SIGNAL(activated()), this, SLOT(removeTie()));
   setMenu->addAction(m_removeTieAction);
 
-  m_setTieToAllAction = new QAction("Set tie to all",this);
+  m_setTieToAllAction = new QAction("Set tie to all", this);
   m_setTieToAllAction->setToolTip("Set this tie for all parameters.");
-  connect(m_setTieToAllAction,SIGNAL(activated()),this,SLOT(setTieAll()));
+  connect(m_setTieToAllAction, SIGNAL(activated()), this, SLOT(setTieAll()));
   setMenu->addAction(m_setTieToAllAction);
 
-  m_removeAllTiesAction = new QAction("Remove all ties",this);
+  m_removeAllTiesAction = new QAction("Remove all ties", this);
   m_removeAllTiesAction->setToolTip("Remove ties for all parameters.");
-  connect(m_removeAllTiesAction,SIGNAL(activated()),this,SLOT(removeAllTies()));
+  connect(m_removeAllTiesAction, SIGNAL(activated()), this,
+          SLOT(removeAllTies()));
   setMenu->addAction(m_removeAllTiesAction);
 
   m_button->setMenu(setMenu);
@@ -106,23 +104,20 @@ namespace MDF
 }
 
 /// Send a signal to set all parameters to the value in the editor.
-void LocalParameterEditor::setAll()
-{
+void LocalParameterEditor::setAll() {
   double value = m_editor->text().toDouble();
   emit setAllValues(value);
 }
 
 /// Toggle the fix state of the current parameter.
-void LocalParameterEditor::fixParameter()
-{
+void LocalParameterEditor::fixParameter() {
   m_fixed = !m_fixed;
   setEditorState();
   emit fixParameter(m_index, m_fixed);
 }
 
 /// Send a signal to fix all parameters.
-void LocalParameterEditor::fixAll()
-{
+void LocalParameterEditor::fixAll() {
   m_fixed = true;
   m_allOthersFixed = true;
   m_othersFixed = true;
@@ -131,8 +126,7 @@ void LocalParameterEditor::fixAll()
 }
 
 /// Send a signal to unfix all parameters.
-void LocalParameterEditor::unfixAll()
-{
+void LocalParameterEditor::unfixAll() {
   m_fixed = false;
   m_allOthersFixed = false;
   m_othersFixed = false;
@@ -141,8 +135,7 @@ void LocalParameterEditor::unfixAll()
 }
 
 /// Send a signal to tie a parameter.
-void LocalParameterEditor::setTie()
-{
+void LocalParameterEditor::setTie() {
   auto tie = setTieDialog(m_tie);
   if (!tie.isEmpty()) {
     m_tie = tie;
@@ -152,16 +145,14 @@ void LocalParameterEditor::setTie()
 }
 
 /// Send a signal to remove a tie.
-void LocalParameterEditor::removeTie()
-{
+void LocalParameterEditor::removeTie() {
   m_tie = "";
   emit setTie(m_index, "");
   setEditorState();
 }
 
 /// Set all ties for all parameters
-void LocalParameterEditor::setTieAll()
-{
+void LocalParameterEditor::setTieAll() {
   auto tie = setTieDialog(m_tie);
   if (!tie.isEmpty()) {
     m_tie = tie;
@@ -172,8 +163,7 @@ void LocalParameterEditor::setTieAll()
 }
 
 /// Remove ties form all parameters
-void LocalParameterEditor::removeAllTies()
-{
+void LocalParameterEditor::removeAllTies() {
   m_tie = "";
   m_othersTied = false;
   emit setTieAll("");
@@ -181,19 +171,15 @@ void LocalParameterEditor::removeAllTies()
 }
 
 /// Filter events in the line editor to emulate a shortcut (F to fix/unfix).
-bool LocalParameterEditor::eventFilter(QObject *, QEvent *evn)
-{
-  if ( evn->type() == QEvent::KeyPress )
-  {
-    auto keyEvent = static_cast<QKeyEvent*>(evn);
+bool LocalParameterEditor::eventFilter(QObject *, QEvent *evn) {
+  if (evn->type() == QEvent::KeyPress) {
+    auto keyEvent = static_cast<QKeyEvent *>(evn);
     if (keyEvent->key() == Qt::Key_F &&
-        keyEvent->modifiers() == Qt::ControlModifier && m_tie.isEmpty()) 
-    {
+        keyEvent->modifiers() == Qt::ControlModifier && m_tie.isEmpty()) {
       fixParameter();
       return true;
     }
-    if (m_tie.isEmpty())
-    {
+    if (m_tie.isEmpty()) {
       m_value = m_editor->text();
     } else {
       m_tie = m_editor->text();
@@ -205,8 +191,7 @@ bool LocalParameterEditor::eventFilter(QObject *, QEvent *evn)
 
 /// Set the state of the editor elements (the line editor and the button)
 /// according to the state of the parameter (fixed, tied, etc)
-void LocalParameterEditor::setEditorState()
-{
+void LocalParameterEditor::setEditorState() {
   bool isNumber = m_tie.isEmpty();
   bool isTie = !isNumber;
 
@@ -224,7 +209,8 @@ void LocalParameterEditor::setEditorState()
     validator->setDecimals(16);
     m_editor->setValidator(validator);
     m_editor->setText(m_value);
-    m_editor->setToolTip("Edit local parameter value. Press Ctrl+F to fix/unfix it.");
+    m_editor->setToolTip(
+        "Edit local parameter value. Press Ctrl+F to fix/unfix it.");
   } else {
     m_editor->setValidator(nullptr);
     m_editor->setText(m_tie);
@@ -233,8 +219,7 @@ void LocalParameterEditor::setEditorState()
 }
 
 /// Open an input dialog to enter a tie expression.
-QString LocalParameterEditor::setTieDialog(QString tie)
-{
+QString LocalParameterEditor::setTieDialog(QString tie) {
   QInputDialog input;
   input.setWindowTitle("Set a tie.");
   input.setTextValue(tie);
@@ -255,4 +240,3 @@ void LocalParameterEditor::updateValue(const QString &value) {
 } // MDF
 } // CustomInterfaces
 } // MantidQt
-
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterItemDelegate.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterItemDelegate.cpp
index 7601ca2f29df345f0679412ee09610d7e49c2ac8..5090e150617190a438a1f8bc1c1ff7f2227456c6 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterItemDelegate.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFLocalParameterItemDelegate.cpp
@@ -5,23 +5,20 @@
 
 #include <QPainter>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Constructor.
-LocalParameterItemDelegate::LocalParameterItemDelegate(EditLocalParameterDialog *parent):
-  QStyledItemDelegate(parent),
-  m_currentEditor(NULL)
-{
-}
+LocalParameterItemDelegate::LocalParameterItemDelegate(
+    EditLocalParameterDialog *parent)
+    : QStyledItemDelegate(parent), m_currentEditor(NULL) {}
 
 /// Create a custom editor LocalParameterEditor.
-QWidget* LocalParameterItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem &, const QModelIndex & index) const
-{
+QWidget *
+LocalParameterItemDelegate::createEditor(QWidget *parent,
+                                         const QStyleOptionViewItem &,
+                                         const QModelIndex &index) const {
   auto row = index.row();
   m_currentEditor = new LocalParameterEditor(
       parent, row, owner()->getValue(row), owner()->isFixed(row),
@@ -29,62 +26,64 @@ QWidget* LocalParameterItemDelegate::createEditor(QWidget * parent, const QStyle
       owner()->areAllOthersFixed(row), owner()->areOthersTied(row));
   connect(m_currentEditor, SIGNAL(setAllValues(double)), this,
           SIGNAL(setAllValues(double)));
-  connect(m_currentEditor,SIGNAL(fixParameter(int,bool)),this,SIGNAL(fixParameter(int,bool)));
-  connect(m_currentEditor,SIGNAL(setAllFixed(bool)),this,SIGNAL(setAllFixed(bool)));
-  connect(m_currentEditor,SIGNAL(setTie(int,QString)),this,SIGNAL(setTie(int,QString)));
-  connect(m_currentEditor,SIGNAL(setTieAll(QString)),this,SIGNAL(setTieAll(QString)));
-  m_currentEditor->installEventFilter(const_cast<LocalParameterItemDelegate*>(this));
- return m_currentEditor;
+  connect(m_currentEditor, SIGNAL(fixParameter(int, bool)), this,
+          SIGNAL(fixParameter(int, bool)));
+  connect(m_currentEditor, SIGNAL(setAllFixed(bool)), this,
+          SIGNAL(setAllFixed(bool)));
+  connect(m_currentEditor, SIGNAL(setTie(int, QString)), this,
+          SIGNAL(setTie(int, QString)));
+  connect(m_currentEditor, SIGNAL(setTieAll(QString)), this,
+          SIGNAL(setTieAll(QString)));
+  m_currentEditor->installEventFilter(
+      const_cast<LocalParameterItemDelegate *>(this));
+  return m_currentEditor;
 }
 
 /// Initialize the editor with the current data in the cell.
-void LocalParameterItemDelegate::setEditorData(QWidget*, const QModelIndex&) const
-{
+void LocalParameterItemDelegate::setEditorData(QWidget *,
+                                               const QModelIndex &) const {
   // Needs to be empty to prevent Qt's default behaviour.
 }
 
 /// Update the data in the cell with the text in the editor.
-void LocalParameterItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
-{
-  QStyledItemDelegate::setModelData(editor->layout()->itemAt(0)->widget(), model, index);
+void LocalParameterItemDelegate::setModelData(QWidget *editor,
+                                              QAbstractItemModel *model,
+                                              const QModelIndex &index) const {
+  QStyledItemDelegate::setModelData(editor->layout()->itemAt(0)->widget(),
+                                    model, index);
 }
 
 /// Re-implemented to resolve an issue: if the parent dialog closes with
 /// the editor is active any changes in it get ignored.
-bool LocalParameterItemDelegate::eventFilter(QObject * obj, QEvent * ev)
-{
-  if ( ev->type() == QEvent::WindowDeactivate )
-  {
+bool LocalParameterItemDelegate::eventFilter(QObject *obj, QEvent *ev) {
+  if (ev->type() == QEvent::WindowDeactivate) {
     // Force to save the changes to the underlying model.
     emit commitData(m_currentEditor);
     return true;
   }
-  return QStyledItemDelegate::eventFilter(obj,ev);
+  return QStyledItemDelegate::eventFilter(obj, ev);
 }
 
 /// Paint the table cell.
-void LocalParameterItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
-{
+void LocalParameterItemDelegate::paint(QPainter *painter,
+                                       const QStyleOptionViewItem &option,
+                                       const QModelIndex &index) const {
   auto tie = owner()->getTie(index.row());
 
-  if (!tie.isEmpty())
-  {
+  if (!tie.isEmpty()) {
     auto rect = option.rect;
     auto dHeight = (option.rect.height() - option.fontMetrics.height()) / 2;
-    rect.adjust(0, dHeight, 0 ,-dHeight);
+    rect.adjust(0, dHeight, 0, -dHeight);
     painter->drawText(rect, tie);
-  }
-  else
-  {
+  } else {
     QStyledItemDelegate::paint(painter, option, index);
   }
 }
 
 /// Cast the parent to EditLocalParameterDialog. Get access to parameter
 /// values and fixes.
-EditLocalParameterDialog *LocalParameterItemDelegate::owner() const 
-{
-  return static_cast<EditLocalParameterDialog*>(parent());
+EditLocalParameterDialog *LocalParameterItemDelegate::owner() const {
+  return static_cast<EditLocalParameterDialog *>(parent());
 }
 
 } // MDF
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFPlotController.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFPlotController.cpp
index 3917a5e765cf9dc32dc057d7c18df7e485f0ad49..887f7d272b3f69c949e181640ac6e72599b0c960 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFPlotController.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MDFPlotController.cpp
@@ -22,22 +22,19 @@
 
 #include <qwt_scale_widget.h>
 
-namespace{
-  // columns in the data table
-  const int wsColumn      = 0;
-  const int wsIndexColumn = 1;
-  const int startXColumn  = 2;
-  const int endXColumn    = 3;
-  QColor rangeSelectorDisabledColor = Qt::darkGray;
-  QColor rangeSelectorEnabledColor = Qt::blue;
+namespace {
+// columns in the data table
+const int wsColumn = 0;
+const int wsIndexColumn = 1;
+const int startXColumn = 2;
+const int endXColumn = 3;
+QColor rangeSelectorDisabledColor = Qt::darkGray;
+QColor rangeSelectorEnabledColor = Qt::blue;
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MDF
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MDF {
 
 /// Constructor
 PlotController::PlotController(MultiDatasetFit *parent, QwtPlot *plot,
@@ -45,106 +42,100 @@ PlotController::PlotController(MultiDatasetFit *parent, QwtPlot *plot,
                                QPushButton *prev, QPushButton *next)
     : QObject(parent), m_plot(plot), m_table(table),
       m_plotSelector(plotSelector), m_prevPlot(prev), m_nextPlot(next),
-      m_currentIndex(-1), m_showDataErrors(false), m_showGuessFunction(false)
-{
-  connect(prev,SIGNAL(clicked()),this,SLOT(prevPlot()));
-  connect(next,SIGNAL(clicked()),this,SLOT(nextPlot()));
-  connect(plotSelector,SIGNAL(currentIndexChanged(int)),this,SLOT(plotDataSet(int)));
+      m_currentIndex(-1), m_showDataErrors(false), m_showGuessFunction(false) {
+  connect(prev, SIGNAL(clicked()), this, SLOT(prevPlot()));
+  connect(next, SIGNAL(clicked()), this, SLOT(nextPlot()));
+  connect(plotSelector, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(plotDataSet(int)));
 
-  m_zoomer = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
-      QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, plot->canvas());
+  m_zoomer =
+      new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
+                        QwtPicker::DragSelection | QwtPicker::CornerToCorner,
+                        QwtPicker::AlwaysOff, plot->canvas());
 
-  m_panner = new QwtPlotPanner( plot->canvas() );
+  m_panner = new QwtPlotPanner(plot->canvas());
 
-  m_magnifier = new QwtPlotMagnifier( plot->canvas() );
+  m_magnifier = new QwtPlotMagnifier(plot->canvas());
 
   m_rangeSelector = new MantidWidgets::RangeSelector(m_plot);
-  m_rangeSelector->setRange( -1e30, 1e30 );
+  m_rangeSelector->setRange(-1e30, 1e30);
   m_rangeSelector->setMinimum(10);
   m_rangeSelector->setMaximum(990);
-  connect(m_rangeSelector,SIGNAL(selectionChanged(double, double)),this,SLOT(updateFittingRange(double, double)));
+  connect(m_rangeSelector, SIGNAL(selectionChanged(double, double)), this,
+          SLOT(updateFittingRange(double, double)));
 
   disableAllTools();
 
-  connect( plot->axisWidget(QwtPlot::xBottom), SIGNAL(scaleDivChanged()), this, SLOT(updateGuessPlot()));
+  connect(plot->axisWidget(QwtPlot::xBottom), SIGNAL(scaleDivChanged()), this,
+          SLOT(updateGuessPlot()));
 }
 
 /// Destructor.
-PlotController::~PlotController()
-{
+PlotController::~PlotController() {
   m_plotData.clear();
   m_guessFunctionData.reset();
 }
 
 /// Slot. Respond to changes in the data table.
-void PlotController::tableUpdated()
-{
+void PlotController::tableUpdated() {
   m_plotSelector->blockSignals(true);
   m_plotSelector->clear();
   int rowCount = m_table->rowCount();
-  for(int row = 0; row < rowCount; ++row)
-  {
-    QString itemText = QString("%1 (%2)").arg(m_table->item(row,wsColumn)->text(),m_table->item(row,wsIndexColumn)->text());
+  for (int row = 0; row < rowCount; ++row) {
+    QString itemText =
+        QString("%1 (%2)").arg(m_table->item(row, wsColumn)->text(),
+                               m_table->item(row, wsIndexColumn)->text());
     m_plotSelector->insertItem(row, itemText);
   }
   m_plotData.clear();
   m_currentIndex = -1;
   m_plotSelector->blockSignals(false);
-  plotDataSet( m_plotSelector->currentIndex() );
+  plotDataSet(m_plotSelector->currentIndex());
 }
 
 /// Display the previous plot if there is one.
-void PlotController::prevPlot()
-{
+void PlotController::prevPlot() {
   int index = m_plotSelector->currentIndex();
-  if ( index > 0 )
-  {
+  if (index > 0) {
     --index;
-    m_plotSelector->setCurrentIndex( index );
+    m_plotSelector->setCurrentIndex(index);
   }
 }
 
 /// Display the next plot if there is one.
-void PlotController::nextPlot()
-{
+void PlotController::nextPlot() {
   int index = m_plotSelector->currentIndex();
-  if ( index < m_plotSelector->count() - 1 )
-  {
+  if (index < m_plotSelector->count() - 1) {
     ++index;
-    m_plotSelector->setCurrentIndex( index );
+    m_plotSelector->setCurrentIndex(index);
   }
 }
 
 /// Get a pointer to a dataset data.
 /// @param index :: Index of a dataset.
-boost::shared_ptr<DatasetPlotData> PlotController::getData(int index)
-{
+boost::shared_ptr<DatasetPlotData> PlotController::getData(int index) {
   auto data = boost::shared_ptr<DatasetPlotData>();
-  if (index < 0) return data;
-  if ( !m_plotData.contains(index) )
-  {
+  if (index < 0)
+    return data;
+  if (!m_plotData.contains(index)) {
     QString wsName = owner()->getWorkspaceName(index);
     int wsIndex = owner()->getWorkspaceIndex(index);
     QString outputWorkspaceName = owner()->getOutputWorkspaceName(index);
     try {
-      data = boost::make_shared<DatasetPlotData>(wsName, wsIndex, outputWorkspaceName);
-      m_plotData.insert(index, data );
-    }
-    catch(std::exception& e)
-    {
-      QMessageBox::critical(owner(),"MantidPlot - Error",e.what());
+      data = boost::make_shared<DatasetPlotData>(wsName, wsIndex,
+                                                 outputWorkspaceName);
+      m_plotData.insert(index, data);
+    } catch (std::exception &e) {
+      QMessageBox::critical(owner(), "MantidPlot - Error", e.what());
       clear();
       owner()->checkSpectra();
       m_plot->replot();
     }
-  }
-  else
-  {
+  } else {
     data = m_plotData[index];
   }
 
-  if (data)
-  {
+  if (data) {
     data->showDataErrorBars(m_showDataErrors);
   }
 
@@ -153,10 +144,8 @@ boost::shared_ptr<DatasetPlotData> PlotController::getData(int index)
 
 /// Plot a data set.
 /// @param index :: Index (row) of the data set in the table.
-void PlotController::plotDataSet(int index)
-{
-  if ( index < 0 || index >= m_table->rowCount() )
-  {
+void PlotController::plotDataSet(int index) {
+  if (index < 0 || index >= m_table->rowCount()) {
     clear();
     owner()->checkSpectra();
     m_plot->replot();
@@ -168,8 +157,7 @@ void PlotController::plotDataSet(int index)
   auto plotData = getData(index);
 
   // hide the previously shown data
-  if ( m_currentIndex > -1 ) 
-  {
+  if (m_currentIndex > -1) {
     m_plotData[m_currentIndex]->hide();
   }
 
@@ -177,8 +165,7 @@ void PlotController::plotDataSet(int index)
   // but if zoom rect doesn't show any data reset zoom base to show all
   auto dataRect = m_plotData[index]->boundingRect();
   auto zoomRect = m_zoomer->zoomRect();
-  if (!zoomRect.intersects( dataRect ) || resetZoom)
-  {
+  if (!zoomRect.intersects(dataRect) || resetZoom) {
     dataRect = plotData->boundingRect();
     m_plot->setAxisScale(QwtPlot::xBottom, dataRect.left(), dataRect.right());
     m_plot->setAxisScale(QwtPlot::yLeft, dataRect.top(), dataRect.bottom());
@@ -186,54 +173,49 @@ void PlotController::plotDataSet(int index)
   // change the current data set index
   m_currentIndex = index;
   updateRange(index);
-  
+
   // show the new data
-  plotData->show( m_plot );
+  plotData->show(m_plot);
   m_plot->replot();
-  // the idea is to set the zoom base (the largest view) to the data's bounding rect
-  // but it looks like the base is set to the union of dataRect and current zoomRect
-  m_zoomer->setZoomBase( dataRect );
+  // the idea is to set the zoom base (the largest view) to the data's bounding
+  // rect
+  // but it looks like the base is set to the union of dataRect and current
+  // zoomRect
+  m_zoomer->setZoomBase(dataRect);
   // if it's first data set ever set the zoomer's base
-  // if it's not done the base is set to some default rect that has nothing to do with the data
-  if ( resetZoom ) 
-  {
+  // if it's not done the base is set to some default rect that has nothing to
+  // do with the data
+  if (resetZoom) {
     m_zoomer->setZoomBase(true);
   }
-  emit currentIndexChanged( index );
+  emit currentIndexChanged(index);
 }
 
 /// Clear all plot data.
-void PlotController::clear(bool clearGuess)
-{
+void PlotController::clear(bool clearGuess) {
   m_plotData.clear();
-  if (clearGuess)
-  {
+  if (clearGuess) {
     m_guessFunctionData.reset();
   }
 }
 
 /// Update the plot.
-void PlotController::update()
-{
-  plotDataSet( m_currentIndex );
-}
+void PlotController::update() { plotDataSet(m_currentIndex); }
 
 /// Reset the fitting range to the current limits on the x axis.
-void PlotController::resetRange()
-{
+void PlotController::resetRange() {
   QwtScaleMap xMap = m_plot->canvasMap(QwtPlot::xBottom);
   double startX = xMap.s1();
   double endX = xMap.s2();
-  m_rangeSelector->setMinimum( startX );
-  m_rangeSelector->setMaximum( endX );
+  m_rangeSelector->setMinimum(startX);
+  m_rangeSelector->setMaximum(endX);
 }
 
 /// Set zooming to the current fitting range.
-void PlotController::zoomToRange()
-{
+void PlotController::zoomToRange() {
   QwtDoubleRect rect = m_zoomer->zoomRect();
-  rect.setX( m_rangeSelector->getMinimum() );
-  rect.setRight( m_rangeSelector->getMaximum() );
+  rect.setX(m_rangeSelector->getMinimum());
+  rect.setRight(m_rangeSelector->getMaximum());
   // In case the scales were set by the panning tool we need to
   // reset the zoomer first.
   m_zoomer->zoom(-1);
@@ -243,13 +225,14 @@ void PlotController::zoomToRange()
 
 /// Make a string of python code to be used as 'source, indices' arguments
 /// to plotSpectrum(...)
-QString PlotController::makePyPlotSource(int index) const
-{
+QString PlotController::makePyPlotSource(int index) const {
   QString pyCode;
   auto outputWsorkspaceName = owner()->getOutputWorkspaceName(index);
   auto wsIndex = owner()->getWorkspaceIndex(index);
   if (outputWsorkspaceName.isEmpty()) {
-    pyCode = QString("['%1'], %2").arg(owner()->getWorkspaceName(index)).arg(wsIndex);
+    pyCode = QString("['%1'], %2")
+                 .arg(owner()->getWorkspaceName(index))
+                 .arg(wsIndex);
   } else {
     pyCode = QString("['%1'], [0,1,2]").arg(outputWsorkspaceName);
   }
@@ -258,19 +241,16 @@ QString PlotController::makePyPlotSource(int index) const
 
 /// Export i-th plot.
 /// @param index :: Index of a plot to export.
-void PlotController::exportPlot(int index)
-{
-  if (index < 0) return;
+void PlotController::exportPlot(int index) {
+  if (index < 0)
+    return;
   QString pyInput = "from mantidplot import plotSpectrum\n";
   pyInput += QString("plotSpectrum(%1)\n").arg(makePyPlotSource(index));
   owner()->runPythonCode(pyInput);
 }
 
 /// Export current plot
-void PlotController::exportCurrentPlot()
-{
-  exportPlot(m_currentIndex);
-}
+void PlotController::exportCurrentPlot() { exportPlot(m_currentIndex); }
 
 /// Export all plots
 void PlotController::exportAllPlots() {
@@ -301,10 +281,9 @@ void PlotController::exportAllPlots() {
   }
 }
 
-/// Disable all plot tools. It is a helper method 
+/// Disable all plot tools. It is a helper method
 /// to simplify switchig between tools.
-void PlotController::disableAllTools()
-{
+void PlotController::disableAllTools() {
   m_zoomer->setEnabled(false);
   m_panner->setEnabled(false);
   m_magnifier->setEnabled(false);
@@ -313,9 +292,7 @@ void PlotController::disableAllTools()
 }
 
 /// Generic tool enabler.
-template<class Tool>
-void PlotController::enableTool(Tool* tool, int cursor)
-{
+template <class Tool> void PlotController::enableTool(Tool *tool, int cursor) {
   disableAllTools();
   tool->setEnabled(true);
   m_plot->canvas()->setCursor(QCursor(static_cast<Qt::CursorShape>(cursor)));
@@ -323,60 +300,44 @@ void PlotController::enableTool(Tool* tool, int cursor)
   owner()->showPlotInfo();
 }
 
-
 /// Enable zooming tool.
-void PlotController::enableZoom()
-{
-  enableTool(m_zoomer,Qt::CrossCursor);
-}
+void PlotController::enableZoom() { enableTool(m_zoomer, Qt::CrossCursor); }
 
 /// Enable panning tool.
-void PlotController::enablePan()
-{
+void PlotController::enablePan() {
   enableTool(m_panner, Qt::PointingHandCursor);
   m_magnifier->setEnabled(true);
 }
 
 /// Enable range selector tool.
-void PlotController::enableRange()
-{
+void PlotController::enableRange() {
   enableTool(m_rangeSelector, Qt::PointingHandCursor);
   m_rangeSelector->setColour(rangeSelectorEnabledColor);
   m_plot->replot();
 }
 
 /// Check if zooming tool is on.
-bool PlotController::isZoomEnabled() const
-{
-  return m_zoomer->isEnabled();
-}
+bool PlotController::isZoomEnabled() const { return m_zoomer->isEnabled(); }
 
 /// Check if panning tool is on.
-bool PlotController::isPanEnabled() const
-{
-  return m_panner->isEnabled();
-}
+bool PlotController::isPanEnabled() const { return m_panner->isEnabled(); }
 
 /// Check if range seletcor is on.
-bool PlotController::isRangeSelectorEnabled() const
-{
+bool PlotController::isRangeSelectorEnabled() const {
   return m_rangeSelector->isEnabled();
 }
 
 /// Signal others that fitting range has been updated.
-void PlotController::updateFittingRange(double startX, double endX)
-{
+void PlotController::updateFittingRange(double startX, double endX) {
   emit fittingRangeChanged(m_currentIndex, startX, endX);
 }
 
 /// Sync the range selector with the data in the data table.
 /// @param index :: Index of a spectrum that has been updated.
-void PlotController::updateRange(int index)
-{
-  if ( index >= 0 && index == m_currentIndex )
-  {
-    const double startX = m_table->item(index,startXColumn)->text().toDouble();
-    const double endX = m_table->item(index,endXColumn)->text().toDouble();
+void PlotController::updateRange(int index) {
+  if (index >= 0 && index == m_currentIndex) {
+    const double startX = m_table->item(index, startXColumn)->text().toDouble();
+    const double endX = m_table->item(index, endXColumn)->text().toDouble();
     m_rangeSelector->blockSignals(true);
     m_rangeSelector->setMinimum(startX);
     m_rangeSelector->setMaximum(endX);
@@ -384,58 +345,53 @@ void PlotController::updateRange(int index)
   }
 }
 
-MultiDatasetFit *PlotController::owner() const {return static_cast<MultiDatasetFit*>(parent());}
+MultiDatasetFit *PlotController::owner() const {
+  return static_cast<MultiDatasetFit *>(parent());
+}
 
 /// Toggle display of the data error bars.
-void PlotController::showDataErrors(bool on)
-{
+void PlotController::showDataErrors(bool on) {
   m_showDataErrors = on;
-  if (auto data = getData(m_currentIndex))
-  {
+  if (auto data = getData(m_currentIndex)) {
     data->show(m_plot);
     m_plot->replot();
   }
 }
 
-void PlotController::setGuessFunction(const QString& funStr)
-{
-  if (funStr.isEmpty())
-  {
+void PlotController::setGuessFunction(const QString &funStr) {
+  if (funStr.isEmpty()) {
     m_guessFunctionData.reset();
     m_plot->replot();
-  }
-  else
-  {
+  } else {
     QwtScaleMap xMap = m_plot->canvasMap(QwtPlot::xBottom);
     double startX = xMap.s1();
     double endX = xMap.s2();
     auto fun = Mantid::API::FunctionFactory::Instance().createInitialized(
         funStr.toStdString());
     m_guessFunctionData.reset(new MDFFunctionPlotData(fun, startX, endX));
-    if (m_showGuessFunction)
-    {
+    if (m_showGuessFunction) {
       plotGuess();
     }
   }
 }
 
-void PlotController::plotGuess()
-{
-  if (!m_guessFunctionData) return;
+void PlotController::plotGuess() {
+  if (!m_guessFunctionData)
+    return;
   m_guessFunctionData->show(m_plot);
   m_plot->replot();
 }
 
-void PlotController::hideGuess()
-{
-  if (!m_guessFunctionData) return;
+void PlotController::hideGuess() {
+  if (!m_guessFunctionData)
+    return;
   m_guessFunctionData->hide();
   m_plot->replot();
 }
 
-void PlotController::updateGuessPlot()
-{
-  if (!m_guessFunctionData) return;
+void PlotController::updateGuessPlot() {
+  if (!m_guessFunctionData)
+    return;
   QwtScaleMap xMap = m_plot->canvasMap(QwtPlot::xBottom);
   double startX = xMap.s1();
   double endX = xMap.s2();
@@ -443,24 +399,18 @@ void PlotController::updateGuessPlot()
   m_plot->replot();
 }
 
-void PlotController::updateGuessFunction(const Mantid::API::IFunction& fun)
-{
-  if (m_guessFunctionData)
-  {
+void PlotController::updateGuessFunction(const Mantid::API::IFunction &fun) {
+  if (m_guessFunctionData) {
     m_guessFunctionData->updateFunction(fun);
     updateGuessPlot();
   }
 }
 
-void PlotController::showGuessFunction(bool ok)
-{
+void PlotController::showGuessFunction(bool ok) {
   m_showGuessFunction = ok;
-  if (ok)
-  {
-	plotGuess();
-  }
-  else
-  {
+  if (ok) {
+    plotGuess();
+  } else {
     hideGuess();
   }
 }
diff --git a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
index d9b42d7415d1d34cb0f735ac16c2b7b20845df29..dbbac4a6c6ecf319364d9a46537a7c6a93f74ebe 100644
--- a/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
+++ b/MantidQt/CustomInterfaces/src/MultiDatasetFit/MultiDatasetFit.cpp
@@ -18,137 +18,153 @@
 #include <QToolBar>
 #include <QSettings>
 
-namespace{
-  // tool options pages
-  const int zoomToolPage  = 0;
-  const int rangeToolPage = 1;
+namespace {
+// tool options pages
+const int zoomToolPage = 0;
+const int rangeToolPage = 1;
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-//Register the class with the factory
+// Register the class with the factory
 DECLARE_SUBWINDOW(MultiDatasetFit)
 
 /// Constructor
 /// @param parent :: The parent widget
 MultiDatasetFit::MultiDatasetFit(QWidget *parent)
-:UserSubWindow(parent), m_plotController(NULL), m_dataController(NULL), m_functionBrowser(NULL),
- m_fitOptionsBrowser(NULL), m_fitAllSettings(QMessageBox::No)
-{
-}
+    : UserSubWindow(parent), m_plotController(NULL), m_dataController(NULL),
+      m_functionBrowser(NULL), m_fitOptionsBrowser(NULL),
+      m_fitAllSettings(QMessageBox::No) {}
 
-MultiDatasetFit::~MultiDatasetFit()
-{
+MultiDatasetFit::~MultiDatasetFit() {
   saveSettings();
   bool clearGuess = true;
   m_plotController->clear(clearGuess);
 }
 
-/// Initilize the layout. 
-void MultiDatasetFit::initLayout()
-{
+/// Initilize the layout.
+void MultiDatasetFit::initLayout() {
   m_uiForm.setupUi(this);
-  m_uiForm.hSplitter->setStretchFactor(0,0);
-  m_uiForm.hSplitter->setStretchFactor(1,1);
-  m_uiForm.vSplitter->setStretchFactor(0,0);
-  m_uiForm.vSplitter->setStretchFactor(1,1);
+  m_uiForm.hSplitter->setStretchFactor(0, 0);
+  m_uiForm.hSplitter->setStretchFactor(1, 1);
+  m_uiForm.vSplitter->setStretchFactor(0, 0);
+  m_uiForm.vSplitter->setStretchFactor(1, 1);
 
   QHeaderView *header = m_uiForm.dataTable->horizontalHeader();
-  header->setResizeMode(0,QHeaderView::Stretch);
-  header->setResizeMode(1,QHeaderView::Fixed);
+  header->setResizeMode(0, QHeaderView::Stretch);
+  header->setResizeMode(1, QHeaderView::Fixed);
 
-  m_uiForm.btnRemove->setEnabled( false );
+  m_uiForm.btnRemove->setEnabled(false);
 
-  connect(m_uiForm.btnFit,SIGNAL(clicked()),this,SLOT(fit()));
+  connect(m_uiForm.btnFit, SIGNAL(clicked()), this, SLOT(fit()));
 
   m_dataController = new MDF::DataController(this, m_uiForm.dataTable);
-  connect(m_dataController,SIGNAL(hasSelection(bool)),  m_uiForm.btnRemove, SLOT(setEnabled(bool)));
-  connect(m_uiForm.btnAddWorkspace,SIGNAL(clicked()),m_dataController,SLOT(addWorkspace()));
-  connect(m_uiForm.btnRemove,SIGNAL(clicked()),m_dataController,SLOT(removeSelectedSpectra()));
-  connect(m_uiForm.cbApplyRangeToAll,SIGNAL(toggled(bool)),m_dataController,SLOT(setFittingRangeGlobal(bool)));
-
-  m_plotController = new MDF::PlotController(this,
-                                        m_uiForm.plot,
-                                        m_uiForm.dataTable,
-                                        m_uiForm.cbPlotSelector,
-                                        m_uiForm.btnPrev,
-                                        m_uiForm.btnNext);
-  connect(m_dataController,SIGNAL(dataTableUpdated()),m_plotController,SLOT(tableUpdated()));
-  connect(m_dataController,SIGNAL(dataSetUpdated(int)),m_plotController,SLOT(updateRange(int)));
-  connect(m_dataController,SIGNAL(dataTableUpdated()),this,SLOT(setLogNames()));
-  connect(m_dataController,SIGNAL(dataTableUpdated()),this,SLOT(invalidateOutput()));
-  connect(m_plotController,SIGNAL(fittingRangeChanged(int, double, double)),m_dataController,SLOT(setFittingRange(int, double, double)));
-  connect(m_uiForm.cbShowDataErrors,SIGNAL(toggled(bool)),m_plotController,SLOT(showDataErrors(bool)));
-  connect(m_uiForm.btnToVisibleRange,SIGNAL(clicked()),m_plotController,SLOT(resetRange()));
-  connect(m_uiForm.btnToFittingRange,SIGNAL(clicked()),m_plotController,SLOT(zoomToRange()));
-  connect(m_uiForm.cbPlotGuess,SIGNAL(toggled(bool)),m_plotController,SLOT(showGuessFunction(bool)));
-
-  QSplitter* splitter = new QSplitter(Qt::Vertical,this);
+  connect(m_dataController, SIGNAL(hasSelection(bool)), m_uiForm.btnRemove,
+          SLOT(setEnabled(bool)));
+  connect(m_uiForm.btnAddWorkspace, SIGNAL(clicked()), m_dataController,
+          SLOT(addWorkspace()));
+  connect(m_uiForm.btnRemove, SIGNAL(clicked()), m_dataController,
+          SLOT(removeSelectedSpectra()));
+  connect(m_uiForm.cbApplyRangeToAll, SIGNAL(toggled(bool)), m_dataController,
+          SLOT(setFittingRangeGlobal(bool)));
+
+  m_plotController = new MDF::PlotController(
+      this, m_uiForm.plot, m_uiForm.dataTable, m_uiForm.cbPlotSelector,
+      m_uiForm.btnPrev, m_uiForm.btnNext);
+  connect(m_dataController, SIGNAL(dataTableUpdated()), m_plotController,
+          SLOT(tableUpdated()));
+  connect(m_dataController, SIGNAL(dataSetUpdated(int)), m_plotController,
+          SLOT(updateRange(int)));
+  connect(m_dataController, SIGNAL(dataTableUpdated()), this,
+          SLOT(setLogNames()));
+  connect(m_dataController, SIGNAL(dataTableUpdated()), this,
+          SLOT(invalidateOutput()));
+  connect(m_plotController, SIGNAL(fittingRangeChanged(int, double, double)),
+          m_dataController, SLOT(setFittingRange(int, double, double)));
+  connect(m_uiForm.cbShowDataErrors, SIGNAL(toggled(bool)), m_plotController,
+          SLOT(showDataErrors(bool)));
+  connect(m_uiForm.btnToVisibleRange, SIGNAL(clicked()), m_plotController,
+          SLOT(resetRange()));
+  connect(m_uiForm.btnToFittingRange, SIGNAL(clicked()), m_plotController,
+          SLOT(zoomToRange()));
+  connect(m_uiForm.cbPlotGuess, SIGNAL(toggled(bool)), m_plotController,
+          SLOT(showGuessFunction(bool)));
+
+  QSplitter *splitter = new QSplitter(Qt::Vertical, this);
 
   m_functionBrowser = new MantidQt::MantidWidgets::FunctionBrowser(NULL, true);
   m_functionBrowser->setColumnSizes(100, 100, 45);
-  splitter->addWidget( m_functionBrowser );
-  connect(m_functionBrowser,SIGNAL(localParameterButtonClicked(const QString&)),this,SLOT(editLocalParameterValues(const QString&)));
-  connect(m_functionBrowser,SIGNAL(functionStructureChanged()),this,SLOT(reset()));
-  connect(m_functionBrowser,SIGNAL(globalsChanged()),this,SLOT(checkFittingType()));
-  connect(m_functionBrowser,SIGNAL(globalsChanged()),this,SLOT(setParameterNamesForPlotting()));
-  connect(m_functionBrowser,SIGNAL(parameterChanged(const QString&, const QString&)),this,SLOT(updateGuessFunction(const QString&, const QString&)));
-  connect(m_plotController,SIGNAL(currentIndexChanged(int)),m_functionBrowser,SLOT(setCurrentDataset(int)));
-  connect(m_dataController,SIGNAL(spectraRemoved(QList<int>)),m_functionBrowser,SLOT(removeDatasets(QList<int>)));
-  connect(m_dataController,SIGNAL(spectraAdded(int)),m_functionBrowser,SLOT(addDatasets(int)));
+  splitter->addWidget(m_functionBrowser);
+  connect(m_functionBrowser,
+          SIGNAL(localParameterButtonClicked(const QString &)), this,
+          SLOT(editLocalParameterValues(const QString &)));
+  connect(m_functionBrowser, SIGNAL(functionStructureChanged()), this,
+          SLOT(reset()));
+  connect(m_functionBrowser, SIGNAL(globalsChanged()), this,
+          SLOT(checkFittingType()));
+  connect(m_functionBrowser, SIGNAL(globalsChanged()), this,
+          SLOT(setParameterNamesForPlotting()));
+  connect(m_functionBrowser,
+          SIGNAL(parameterChanged(const QString &, const QString &)), this,
+          SLOT(updateGuessFunction(const QString &, const QString &)));
+  connect(m_plotController, SIGNAL(currentIndexChanged(int)), m_functionBrowser,
+          SLOT(setCurrentDataset(int)));
+  connect(m_dataController, SIGNAL(spectraRemoved(QList<int>)),
+          m_functionBrowser, SLOT(removeDatasets(QList<int>)));
+  connect(m_dataController, SIGNAL(spectraAdded(int)), m_functionBrowser,
+          SLOT(addDatasets(int)));
 
   m_fitOptionsBrowser = new MantidQt::MantidWidgets::FitOptionsBrowser(
-      NULL, MantidQt::MantidWidgets::FitOptionsBrowser::SimultaneousAndSequential);
-  connect(m_fitOptionsBrowser,SIGNAL(changedToSequentialFitting()),this,SLOT(setLogNames()));
+      NULL,
+      MantidQt::MantidWidgets::FitOptionsBrowser::SimultaneousAndSequential);
+  connect(m_fitOptionsBrowser, SIGNAL(changedToSequentialFitting()), this,
+          SLOT(setLogNames()));
   splitter->addWidget(m_fitOptionsBrowser);
 
-  m_uiForm.browserLayout->addWidget( splitter );
+  m_uiForm.browserLayout->addWidget(splitter);
 
   createPlotToolbar();
 
   // filters
-  m_functionBrowser->installEventFilter( this );
-  m_fitOptionsBrowser->installEventFilter( this );
-  m_uiForm.plot->installEventFilter( this );
-  m_uiForm.dataTable->installEventFilter( this );
+  m_functionBrowser->installEventFilter(this);
+  m_fitOptionsBrowser->installEventFilter(this);
+  m_uiForm.plot->installEventFilter(this);
+  m_uiForm.dataTable->installEventFilter(this);
 
   m_plotController->enableZoom();
-  showInfo( "Add some data, define fitting function" );
+  showInfo("Add some data, define fitting function");
 
   loadSettings();
 }
 
 /// Create the tool bar for the plot widget.
-void MultiDatasetFit::createPlotToolbar()
-{
+void MultiDatasetFit::createPlotToolbar() {
   // ----- Main tool bar --------
   auto toolBar = new QToolBar(this);
-  toolBar->setIconSize(QSize(16,16));
+  toolBar->setIconSize(QSize(16, 16));
   auto group = new QActionGroup(this);
- 
+
   auto action = new QAction(this);
   action->setIcon(QIcon(":/MultiDatasetFit/icons/zoom.png"));
   action->setCheckable(true);
   action->setChecked(true);
   action->setToolTip("Zooming tool");
-  connect(action,SIGNAL(triggered()),this,SLOT(enableZoom()));
+  connect(action, SIGNAL(triggered()), this, SLOT(enableZoom()));
   group->addAction(action);
 
   action = new QAction(this);
   action->setIcon(QIcon(":/MultiDatasetFit/icons/panning.png"));
   action->setCheckable(true);
   action->setToolTip("Panning tool");
-  connect(action,SIGNAL(triggered()),this,SLOT(enablePan()));
+  connect(action, SIGNAL(triggered()), this, SLOT(enablePan()));
   group->addAction(action);
 
   action = new QAction(this);
   action->setIcon(QIcon(":/MultiDatasetFit/icons/range.png"));
   action->setCheckable(true);
   action->setToolTip("Set fitting range");
-  connect(action,SIGNAL(triggered()),this,SLOT(enableRange()));
+  connect(action, SIGNAL(triggered()), this, SLOT(enableRange()));
   group->addAction(action);
 
   toolBar->addActions(group->actions());
@@ -157,30 +173,27 @@ void MultiDatasetFit::createPlotToolbar()
   action = new QAction(this);
   action->setIcon(QIcon(":/MultiDatasetFit/icons/export-plot.png"));
   action->setToolTip("Export current plot");
-  connect(action,SIGNAL(triggered()),this,SLOT(exportCurrentPlot()));
+  connect(action, SIGNAL(triggered()), this, SLOT(exportCurrentPlot()));
   toolBar->addAction(action);
 
   action = new QAction(this);
   action->setIcon(QIcon(":/MultiDatasetFit/icons/export-all-plots.png"));
   action->setToolTip("Export all plots");
-  connect(action,SIGNAL(triggered()),this,SLOT(exportAllPlots()));
+  connect(action, SIGNAL(triggered()), this, SLOT(exportAllPlots()));
   toolBar->addAction(action);
 
-  m_uiForm.horizontalLayout->insertWidget(3,toolBar);
-
+  m_uiForm.horizontalLayout->insertWidget(3, toolBar);
 }
 
 /// Create a multi-domain function to fit all the spectra in the data table.
-boost::shared_ptr<Mantid::API::IFunction> MultiDatasetFit::createFunction() const
-{
+boost::shared_ptr<Mantid::API::IFunction>
+MultiDatasetFit::createFunction() const {
   return m_functionBrowser->getGlobalFunction();
 }
 
 /// Fit the data sets sequentially if there are no global parameters.
-void MultiDatasetFit::fitSequential()
-{
-  try
-  {
+void MultiDatasetFit::fitSequential() {
+  try {
 
     /// disable button to avoid multiple fit click
     m_uiForm.btnFit->setEnabled(false);
@@ -188,110 +201,105 @@ void MultiDatasetFit::fitSequential()
     std::ostringstream input;
 
     int n = getNumberOfSpectra();
-    for(int ispec = 0; ispec < n; ++ispec)
-    {
-      input << getWorkspaceName(ispec).toStdString() << ",i" << getWorkspaceIndex(ispec) << ";";
+    for (int ispec = 0; ispec < n; ++ispec) {
+      input << getWorkspaceName(ispec).toStdString() << ",i"
+            << getWorkspaceIndex(ispec) << ";";
     }
 
     auto fun = m_functionBrowser->getFunction();
-    auto fit = Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
+    auto fit =
+        Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
     fit->initialize();
-    fit->setPropertyValue("Function", fun->asString() );
+    fit->setPropertyValue("Function", fun->asString());
     fit->setPropertyValue("Input", input.str());
     auto range = getFittingRange(0);
-    fit->setProperty( "StartX", range.first );
-    fit->setProperty( "EndX", range.second );
+    fit->setProperty("StartX", range.first);
+    fit->setProperty("EndX", range.second);
 
     m_fitOptionsBrowser->copyPropertiesToAlgorithm(*fit);
 
-    m_outputWorkspaceName = m_fitOptionsBrowser->getProperty("OutputWorkspace") + "_Workspaces";
+    m_outputWorkspaceName =
+        m_fitOptionsBrowser->getProperty("OutputWorkspace") + "_Workspaces";
 
     removeOldOutput();
 
-    m_fitRunner.reset( new API::AlgorithmRunner() );
-    connect( m_fitRunner.get(),SIGNAL(algorithmComplete(bool)), this, SLOT(finishFit(bool)), Qt::QueuedConnection );
+    m_fitRunner.reset(new API::AlgorithmRunner());
+    connect(m_fitRunner.get(), SIGNAL(algorithmComplete(bool)), this,
+            SLOT(finishFit(bool)), Qt::QueuedConnection);
 
     m_fitRunner->startAlgorithm(fit);
 
-  }
-  catch(std::exception& e)
-  {
+  } catch (std::exception &e) {
     QString mess(e.what());
     const int maxSize = 500;
-    if ( mess.size() > maxSize )
-    {
-      mess = mess.mid(0,maxSize);
+    if (mess.size() > maxSize) {
+      mess = mess.mid(0, maxSize);
       mess += "...";
     }
-    QMessageBox::critical( this, "MantidPlot - Error", QString("PlotPeakByLogValue failed:\n\n  %1").arg(mess) );
+    QMessageBox::critical(
+        this, "MantidPlot - Error",
+        QString("PlotPeakByLogValue failed:\n\n  %1").arg(mess));
     m_uiForm.btnFit->setEnabled(true);
   }
 }
 
 /// Fit the data simultaneously.
-void MultiDatasetFit::fitSimultaneous()
-{
-  try
-  {
+void MultiDatasetFit::fitSimultaneous() {
+  try {
 
     m_uiForm.btnFit->setEnabled(false);
     auto fun = createFunction();
     auto fit = Mantid::API::AlgorithmManager::Instance().create("Fit");
     fit->initialize();
-    fit->setProperty("Function", fun );
+    fit->setProperty("Function", fun);
     fit->setPropertyValue("InputWorkspace", getWorkspaceName(0).toStdString());
     fit->setProperty("WorkspaceIndex", getWorkspaceIndex(0));
     auto range = getFittingRange(0);
-    fit->setProperty( "StartX", range.first );
-    fit->setProperty( "EndX", range.second );
+    fit->setProperty("StartX", range.first);
+    fit->setProperty("EndX", range.second);
 
     int n = getNumberOfSpectra();
-    for(int ispec = 1; ispec < n; ++ispec)
-    {
+    for (int ispec = 1; ispec < n; ++ispec) {
       std::string suffix = boost::lexical_cast<std::string>(ispec);
-      fit->setPropertyValue( "InputWorkspace_" + suffix, getWorkspaceName(ispec).toStdString() );
-      fit->setProperty( "WorkspaceIndex_" + suffix, getWorkspaceIndex(ispec) );
+      fit->setPropertyValue("InputWorkspace_" + suffix,
+                            getWorkspaceName(ispec).toStdString());
+      fit->setProperty("WorkspaceIndex_" + suffix, getWorkspaceIndex(ispec));
       auto range = getFittingRange(ispec);
-      fit->setProperty( "StartX_" + suffix, range.first );
-      fit->setProperty( "EndX_" + suffix, range.second );
+      fit->setProperty("StartX_" + suffix, range.first);
+      fit->setProperty("EndX_" + suffix, range.second);
     }
 
     m_fitOptionsBrowser->copyPropertiesToAlgorithm(*fit);
 
     m_outputWorkspaceName = m_fitOptionsBrowser->getProperty("Output");
-    if ( m_outputWorkspaceName.isEmpty() )
-    {
+    if (m_outputWorkspaceName.isEmpty()) {
       m_outputWorkspaceName = "out";
-      fit->setPropertyValue("Output",m_outputWorkspaceName.toStdString());
-      m_fitOptionsBrowser->setProperty("Output","out");
+      fit->setPropertyValue("Output", m_outputWorkspaceName.toStdString());
+      m_fitOptionsBrowser->setProperty("Output", "out");
     }
-    if (n == 1)
-    {
+    if (n == 1) {
       m_outputWorkspaceName += "_Workspace";
-    }
-    else
-    {
+    } else {
       m_outputWorkspaceName += "_Workspaces";
     }
 
     removeOldOutput();
 
-    m_fitRunner.reset( new API::AlgorithmRunner() );
-    connect( m_fitRunner.get(),SIGNAL(algorithmComplete(bool)), this, SLOT(finishFit(bool)), Qt::QueuedConnection );
+    m_fitRunner.reset(new API::AlgorithmRunner());
+    connect(m_fitRunner.get(), SIGNAL(algorithmComplete(bool)), this,
+            SLOT(finishFit(bool)), Qt::QueuedConnection);
 
     m_fitRunner->startAlgorithm(fit);
 
-  }
-  catch(std::exception& e)
-  {
+  } catch (std::exception &e) {
     QString mess(e.what());
     const int maxSize = 500;
-    if ( mess.size() > maxSize )
-    {
-      mess = mess.mid(0,maxSize);
+    if (mess.size() > maxSize) {
+      mess = mess.mid(0, maxSize);
       mess += "...";
     }
-    QMessageBox::critical( this, "MantidPlot - Error", QString("Fit failed:\n\n  %1").arg(mess) );
+    QMessageBox::critical(this, "MantidPlot - Error",
+                          QString("Fit failed:\n\n  %1").arg(mess));
     m_uiForm.btnFit->setEnabled(true);
   }
 }
@@ -343,27 +351,25 @@ void MultiDatasetFit::fit() {
 
 /// Get the workspace name of the i-th spectrum.
 /// @param i :: Index of a spectrum in the data table.
-QString MultiDatasetFit::getWorkspaceName(int i) const
-{
+QString MultiDatasetFit::getWorkspaceName(int i) const {
   return m_dataController->getWorkspaceName(i);
 }
 
 /// Get the workspace index of the i-th spectrum.
 /// @param i :: Index of a spectrum in the data table.
-int MultiDatasetFit::getWorkspaceIndex(int i) const
-{
+int MultiDatasetFit::getWorkspaceIndex(int i) const {
   return m_dataController->getWorkspaceIndex(i);
 }
 
 /// Get the name of the output workspace
 /// @param i :: Index of a spectrum in the data table.
-QString MultiDatasetFit::getOutputWorkspaceName(int i) const
-{
+QString MultiDatasetFit::getOutputWorkspaceName(int i) const {
   auto wsName = m_outputWorkspaceName.toStdString();
   if (!wsName.empty() &&
       Mantid::API::AnalysisDataService::Instance().doesExist(wsName)) {
     auto ws = Mantid::API::AnalysisDataService::Instance().retrieve(wsName);
-    if (auto  group = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws)) {
+    if (auto group =
+            boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws)) {
       wsName = group->getItem(i)->name();
     }
   }
@@ -372,30 +378,26 @@ QString MultiDatasetFit::getOutputWorkspaceName(int i) const
 
 /// Get the fitting range for the i-th spectrum
 /// @param i :: Index of a spectrum in the data table.
-std::pair<double,double> MultiDatasetFit::getFittingRange(int i) const
-{
+std::pair<double, double> MultiDatasetFit::getFittingRange(int i) const {
   return m_dataController->getFittingRange(i);
 }
 
 /// Get the number of spectra to fit to.
-int MultiDatasetFit::getNumberOfSpectra() const
-{
+int MultiDatasetFit::getNumberOfSpectra() const {
   return m_dataController->getNumberOfSpectra();
 }
 
 /// Start an editor to display and edit individual local parameter values.
-/// @param parName :: Fully qualified name for a local parameter (Global unchecked).
-void MultiDatasetFit::editLocalParameterValues(const QString& parName)
-{
-  MDF::EditLocalParameterDialog dialog(this,parName);
-  if ( dialog.exec() == QDialog::Accepted )
-  {
+/// @param parName :: Fully qualified name for a local parameter (Global
+/// unchecked).
+void MultiDatasetFit::editLocalParameterValues(const QString &parName) {
+  MDF::EditLocalParameterDialog dialog(this, parName);
+  if (dialog.exec() == QDialog::Accepted) {
     auto values = dialog.getValues();
     auto fixes = dialog.getFixes();
     auto ties = dialog.getTies();
-    assert( values.size() == getNumberOfSpectra() );
-    for(int i = 0; i < values.size(); ++i)
-    {
+    assert(values.size() == getNumberOfSpectra());
+    for (int i = 0; i < values.size(); ++i) {
       setLocalParameterValue(parName, i, values[i]);
       setLocalParameterFixed(parName, i, fixes[i]);
       setLocalParameterTie(parName, i, ties[i]);
@@ -405,44 +407,43 @@ void MultiDatasetFit::editLocalParameterValues(const QString& parName)
 
 /// Slot called on completion of the Fit algorithm.
 /// @param error :: Set to true if Fit finishes with an error.
-void MultiDatasetFit::finishFit(bool error)
-{
-  if ( !error )
-  {
+void MultiDatasetFit::finishFit(bool error) {
+  if (!error) {
     m_plotController->clear();
     m_plotController->update();
     Mantid::API::IFunction_sptr fun;
-    if (m_fitOptionsBrowser->getCurrentFittingType() == MantidWidgets::FitOptionsBrowser::Simultaneous)
-    {
+    if (m_fitOptionsBrowser->getCurrentFittingType() ==
+        MantidWidgets::FitOptionsBrowser::Simultaneous) {
       // After a simultaneous fit
       fun = m_fitRunner->getAlgorithm()->getProperty("Function");
-      updateParameters( *fun );
-    }
-    else 
-    {
+      updateParameters(*fun);
+    } else {
       // After a sequential fit
-      auto paramsWSName = m_fitOptionsBrowser->getProperty("OutputWorkspace").toStdString();
-      if (!Mantid::API::AnalysisDataService::Instance().doesExist(paramsWSName)) return;
+      auto paramsWSName =
+          m_fitOptionsBrowser->getProperty("OutputWorkspace").toStdString();
+      if (!Mantid::API::AnalysisDataService::Instance().doesExist(paramsWSName))
+        return;
       size_t nSpectra = getNumberOfSpectra();
-      if (nSpectra == 0) return;
+      if (nSpectra == 0)
+        return;
       fun = m_functionBrowser->getGlobalFunction();
       auto nParams = fun->nParams() / nSpectra;
-      auto params = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::ITableWorkspace>(paramsWSName);
-      if (nParams * 2 + 2 != params->columnCount())
-      {
-        throw std::logic_error("Output table workspace has unexpected number of columns.");
+      auto params = Mantid::API::AnalysisDataService::Instance()
+                        .retrieveWS<Mantid::API::ITableWorkspace>(paramsWSName);
+      if (nParams * 2 + 2 != params->columnCount()) {
+        throw std::logic_error(
+            "Output table workspace has unexpected number of columns.");
       }
-      for(size_t index = 0; index < nSpectra; ++index)
-      {
-        std::string prefix = "f" + boost::lexical_cast<std::string>(index) + ".";
-        for(size_t ip = 0; ip < nParams; ++ip)
-        {
+      for (size_t index = 0; index < nSpectra; ++index) {
+        std::string prefix =
+            "f" + boost::lexical_cast<std::string>(index) + ".";
+        for (size_t ip = 0; ip < nParams; ++ip) {
           auto colIndex = ip * 2 + 1;
           auto column = params->getColumn(colIndex);
           fun->setParameter(prefix + column->name(), column->toDouble(index));
         }
       }
-      updateParameters( *fun );
+      updateParameters(*fun);
       showParameterPlot();
     }
   }
@@ -451,41 +452,28 @@ void MultiDatasetFit::finishFit(bool error)
 
 /// Update the interface to have the same parameter values as in a function.
 /// @param fun :: A function from which to take the parameters.
-void MultiDatasetFit::updateParameters(const Mantid::API::IFunction& fun)
-{
-  m_functionBrowser->updateMultiDatasetParameters( fun );
+void MultiDatasetFit::updateParameters(const Mantid::API::IFunction &fun) {
+  m_functionBrowser->updateMultiDatasetParameters(fun);
 }
 
 /// Show a message in the info bar at the bottom of the interface.
-void MultiDatasetFit::showInfo(const QString& text)
-{
+void MultiDatasetFit::showInfo(const QString &text) {
   m_uiForm.infoBar->setText(text);
 }
 
 /// Intersept mouse-enter events to display context-specific info
 /// in the "status bar".
-bool MultiDatasetFit::eventFilter(QObject *widget, QEvent *evn)
-{
-  if ( evn->type() == QEvent::Enter )
-  {
-    if ( qobject_cast<QObject*>( m_functionBrowser ) == widget )
-    {
+bool MultiDatasetFit::eventFilter(QObject *widget, QEvent *evn) {
+  if (evn->type() == QEvent::Enter) {
+    if (qobject_cast<QObject *>(m_functionBrowser) == widget) {
       showFunctionBrowserInfo();
-    }
-    else if ( qobject_cast<QObject*>( m_fitOptionsBrowser ) == widget )
-    {
+    } else if (qobject_cast<QObject *>(m_fitOptionsBrowser) == widget) {
       showFitOptionsBrowserInfo();
-    }
-    else if ( qobject_cast<QObject*>( m_uiForm.plot ) == widget )
-    {
+    } else if (qobject_cast<QObject *>(m_uiForm.plot) == widget) {
       showPlotInfo();
-    }
-    else if ( qobject_cast<QObject*>( m_uiForm.dataTable ) == widget )
-    {
+    } else if (qobject_cast<QObject *>(m_uiForm.dataTable) == widget) {
       showTableInfo();
-    }
-    else
-    {
+    } else {
       showInfo("");
     }
   }
@@ -493,119 +481,95 @@ bool MultiDatasetFit::eventFilter(QObject *widget, QEvent *evn)
 }
 
 /// Show info about the function browser.
-void MultiDatasetFit::showFunctionBrowserInfo()
-{
-  if ( m_functionBrowser->hasFunction() )
-  {
-    showInfo( "Use context menu to add more functions. Set parameters and attributes." );
-  }
-  else
-  {
-    showInfo( "Use context menu to add a function." );
+void MultiDatasetFit::showFunctionBrowserInfo() {
+  if (m_functionBrowser->hasFunction()) {
+    showInfo("Use context menu to add more functions. Set parameters and "
+             "attributes.");
+  } else {
+    showInfo("Use context menu to add a function.");
   }
 }
 
 /// Show info about the Fit options browser.
-void MultiDatasetFit::showFitOptionsBrowserInfo()
-{
-  showInfo( "Set Fit properties." );
+void MultiDatasetFit::showFitOptionsBrowserInfo() {
+  showInfo("Set Fit properties.");
 }
 
 /// Show info / tips on the plot widget.
-void MultiDatasetFit::showPlotInfo()
-{
+void MultiDatasetFit::showPlotInfo() {
   QString text = "Use Alt+. and Alt+, to change the data set. ";
 
-  if ( m_plotController->isZoomEnabled() )
-  {
+  if (m_plotController->isZoomEnabled()) {
     text += "Click and drag to zoom in. Use middle or right button to zoom out";
-  }
-  else if ( m_plotController->isPanEnabled() )
-  {
+  } else if (m_plotController->isPanEnabled()) {
     text += "Click and drag to move. Use mouse wheel to zoom in and out.";
-  }
-  else if ( m_plotController->isRangeSelectorEnabled() )
-  {
+  } else if (m_plotController->isRangeSelectorEnabled()) {
     text += "Drag the vertical dashed lines to adjust the fitting range.";
   }
-  
-  showInfo( text );
+
+  showInfo(text);
 }
 
 /// Show info / tips on the dataset table.
-void MultiDatasetFit::showTableInfo()
-{
-  if ( getNumberOfSpectra() > 0 )
-  {
-    showInfo("Select spectra by selecting rows. For multiple selection use Shift or Ctrl keys.");
-  }
-  else
-  {
+void MultiDatasetFit::showTableInfo() {
+  if (getNumberOfSpectra() > 0) {
+    showInfo("Select spectra by selecting rows. For multiple selection use "
+             "Shift or Ctrl keys.");
+  } else {
     showInfo("Add some data sets. Click \"Add Workspace\" button.");
   }
 }
 
 /// Check that the data sets in the table are valid and remove invalid ones.
-void MultiDatasetFit::checkSpectra()
-{
-  m_dataController->checkSpectra();
-}
+void MultiDatasetFit::checkSpectra() { m_dataController->checkSpectra(); }
 
 /// Enable the zoom tool.
-void MultiDatasetFit::enableZoom()
-{
+void MultiDatasetFit::enableZoom() {
   m_plotController->enableZoom();
   m_uiForm.toolOptions->setCurrentIndex(zoomToolPage);
 }
 
 /// Enable the panning tool.
-void MultiDatasetFit::enablePan()
-{
+void MultiDatasetFit::enablePan() {
   m_plotController->enablePan();
   m_uiForm.toolOptions->setCurrentIndex(zoomToolPage);
 }
 
 /// Enable the fitting range selection tool.
-void MultiDatasetFit::enableRange()
-{
+void MultiDatasetFit::enableRange() {
   m_plotController->enableRange();
   m_uiForm.toolOptions->setCurrentIndex(rangeToolPage);
 }
 
-/// Export current plot 
-void MultiDatasetFit::exportCurrentPlot()
-{
+/// Export current plot
+void MultiDatasetFit::exportCurrentPlot() {
   m_plotController->exportCurrentPlot();
 }
 
-/// Export all plots 
-void MultiDatasetFit::exportAllPlots()
-{
-  m_plotController->exportAllPlots();
-}
+/// Export all plots
+void MultiDatasetFit::exportAllPlots() { m_plotController->exportAllPlots(); }
 
 /// Set value of a local parameter
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
 /// @param value :: New value for the parameter.
-void MultiDatasetFit::setLocalParameterValue(const QString& parName, int i, double value)
-{
+void MultiDatasetFit::setLocalParameterValue(const QString &parName, int i,
+                                             double value) {
   m_functionBrowser->setLocalParameterValue(parName, i, value);
 }
 
 /// Get value of a local parameter
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
-double MultiDatasetFit::getLocalParameterValue(const QString& parName, int i) const
-{
+double MultiDatasetFit::getLocalParameterValue(const QString &parName,
+                                               int i) const {
   return m_functionBrowser->getLocalParameterValue(parName, i);
 }
 
 /// Reset the caches. Prepare to fill them in lazily.
-void MultiDatasetFit::reset()
-{
+void MultiDatasetFit::reset() {
   m_functionBrowser->resetLocalParameters();
-  m_functionBrowser->setNumberOfDatasets( getNumberOfSpectra() );
+  m_functionBrowser->setNumberOfDatasets(getNumberOfSpectra());
   setParameterNamesForPlotting();
   m_plotController->setGuessFunction(m_functionBrowser->getFunctionString());
 }
@@ -613,8 +577,8 @@ void MultiDatasetFit::reset()
 /// Check if a local parameter is fixed
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
-bool MultiDatasetFit::isLocalParameterFixed(const QString& parName, int i) const
-{
+bool MultiDatasetFit::isLocalParameterFixed(const QString &parName,
+                                            int i) const {
   return m_functionBrowser->isLocalParameterFixed(parName, i);
 }
 
@@ -622,16 +586,16 @@ bool MultiDatasetFit::isLocalParameterFixed(const QString& parName, int i) const
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
 /// @param fixed :: Should the parameter be fixed (true) or unfixed (false).
-void MultiDatasetFit::setLocalParameterFixed(const QString& parName, int i, bool fixed)
-{
+void MultiDatasetFit::setLocalParameterFixed(const QString &parName, int i,
+                                             bool fixed) {
   m_functionBrowser->setLocalParameterFixed(parName, i, fixed);
 }
 
 /// Get the tie for a local parameter.
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
-QString MultiDatasetFit::getLocalParameterTie(const QString& parName, int i) const
-{
+QString MultiDatasetFit::getLocalParameterTie(const QString &parName,
+                                              int i) const {
   return m_functionBrowser->getLocalParameterTie(parName, i);
 }
 
@@ -639,17 +603,16 @@ QString MultiDatasetFit::getLocalParameterTie(const QString& parName, int i) con
 /// @param parName : Name of a local parameter.
 /// @param i :: Index of the dataset (spectrum).
 /// @param tie :: A tie string to set.
-void MultiDatasetFit::setLocalParameterTie(const QString& parName, int i, QString tie)
-{
+void MultiDatasetFit::setLocalParameterTie(const QString &parName, int i,
+                                           QString tie) {
   m_functionBrowser->setLocalParameterTie(parName, i, tie);
 }
 
 /// Load settings
-void MultiDatasetFit::loadSettings()
-{
+void MultiDatasetFit::loadSettings() {
   QSettings settings;
   settings.beginGroup("Mantid/MultiDatasetFit");
-  m_fitOptionsBrowser->loadSettings( settings );
+  m_fitOptionsBrowser->loadSettings(settings);
   bool option = settings.value("ShowDataErrors", false).toBool();
   m_uiForm.cbShowDataErrors->setChecked(option);
   option = settings.value("ApplyRangeToAll", false).toBool();
@@ -659,80 +622,72 @@ void MultiDatasetFit::loadSettings()
 }
 
 /// Save settings
-void MultiDatasetFit::saveSettings() const
-{
+void MultiDatasetFit::saveSettings() const {
   QSettings settings;
   settings.beginGroup("Mantid/MultiDatasetFit");
-  m_fitOptionsBrowser->saveSettings( settings );
-  settings.setValue("ShowDataErrors",m_uiForm.cbShowDataErrors->isChecked());
-  settings.setValue("ApplyRangeToAll",m_uiForm.cbApplyRangeToAll->isChecked());
-  settings.setValue("PlotGuess",m_uiForm.cbPlotGuess->isChecked());
+  m_fitOptionsBrowser->saveSettings(settings);
+  settings.setValue("ShowDataErrors", m_uiForm.cbShowDataErrors->isChecked());
+  settings.setValue("ApplyRangeToAll", m_uiForm.cbApplyRangeToAll->isChecked());
+  settings.setValue("PlotGuess", m_uiForm.cbPlotGuess->isChecked());
 }
 
 /// Make sure that simultaneous fitting is on
 /// when the function has at least one global parameter.
-void MultiDatasetFit::checkFittingType()
-{
+void MultiDatasetFit::checkFittingType() {
   auto globals = m_functionBrowser->getGlobalParameters();
-  if (globals.isEmpty())
-  {
+  if (globals.isEmpty()) {
     m_fitOptionsBrowser->unlockCurrentFittingType();
-  }
-  else
-  {
-    m_fitOptionsBrowser->lockCurrentFittingType(MantidWidgets::FitOptionsBrowser::Simultaneous);
+  } else {
+    m_fitOptionsBrowser->lockCurrentFittingType(
+        MantidWidgets::FitOptionsBrowser::Simultaneous);
   }
 }
 
 /**
- * Collect names of the logs in the data workspaces and pass them on to m_fitOptionsBrowser.
+ * Collect names of the logs in the data workspaces and pass them on to
+ * m_fitOptionsBrowser.
  */
-void MultiDatasetFit::setLogNames()
-{
-  if (getNumberOfSpectra() > 0)
-  {
-    try
-    {
-      auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>(getWorkspaceName(0).toStdString());
-      const std::vector<Mantid::Kernel::Property*> logs = ws->run().getLogData();
+void MultiDatasetFit::setLogNames() {
+  if (getNumberOfSpectra() > 0) {
+    try {
+      auto ws = Mantid::API::AnalysisDataService::Instance()
+                    .retrieveWS<Mantid::API::MatrixWorkspace>(
+                        getWorkspaceName(0).toStdString());
+      const std::vector<Mantid::Kernel::Property *> logs =
+          ws->run().getLogData();
       QStringList logNames;
-      for(int i=0;i<static_cast<int>(logs.size());++i)
-      {
-        if (dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double>*>(logs[i]))
-        {
+      for (int i = 0; i < static_cast<int>(logs.size()); ++i) {
+        if (dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(
+                logs[i])) {
           logNames << QString::fromStdString(logs[i]->name());
         }
       }
-      if (!logNames.isEmpty())
-      {
+      if (!logNames.isEmpty()) {
         m_fitOptionsBrowser->setLogNames(logNames);
       }
+    } catch (...) { /*Maybe the data table hasn't updated yet*/
     }
-    catch (...) 
-    {/*Maybe the data table hasn't updated yet*/}
   }
 }
 
 /// Collect names of local parameters and pass them to m_fitOptionsBrowser.
-void MultiDatasetFit::setParameterNamesForPlotting()
-{
-  m_fitOptionsBrowser->setParameterNamesForPlotting(m_functionBrowser->getLocalParameters());
+void MultiDatasetFit::setParameterNamesForPlotting() {
+  m_fitOptionsBrowser->setParameterNamesForPlotting(
+      m_functionBrowser->getLocalParameters());
 }
 
 /// Remove old output from Fit.
-void MultiDatasetFit::removeOldOutput()
-{
+void MultiDatasetFit::removeOldOutput() {
   auto outWS = m_outputWorkspaceName.toStdString();
   if (Mantid::API::AnalysisDataService::Instance().doesExist(outWS) &&
-      Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::WorkspaceGroup>(outWS))
-  {
+      Mantid::API::AnalysisDataService::Instance()
+          .retrieveWS<Mantid::API::WorkspaceGroup>(outWS)) {
     Mantid::API::AnalysisDataService::Instance().deepRemoveGroup(outWS);
   }
 }
 
 /// Invalidate the previous fit output
-void MultiDatasetFit::invalidateOutput()
-{
+void MultiDatasetFit::invalidateOutput() {
   m_outputWorkspaceName = "";
   m_plotController->clear();
   m_plotController->update();
@@ -741,20 +696,20 @@ void MultiDatasetFit::invalidateOutput()
 /// Open a new graph window and plot a fitting parameter
 /// against a log value. The name of the parameter to plot
 /// and the log name must be selected in m_fitOptionsBrowser.
-void MultiDatasetFit::showParameterPlot()
-{
+void MultiDatasetFit::showParameterPlot() {
   auto table = m_fitOptionsBrowser->getProperty("OutputWorkspace");
   auto logValue = m_fitOptionsBrowser->getProperty("LogValue");
-  auto parName  = m_fitOptionsBrowser->getParameterToPlot();
-  if (table.isEmpty() || parName.isEmpty()) return;
+  auto parName = m_fitOptionsBrowser->getParameterToPlot();
+  if (table.isEmpty() || parName.isEmpty())
+    return;
 
   auto pyInput = QString("table = importTableWorkspace('%1')\n"
-                         "plotTableColumns(table, ('%2','%3_Err'))\n").arg(table, parName, parName);
+                         "plotTableColumns(table, ('%2','%3_Err'))\n")
+                     .arg(table, parName, parName);
   runPythonCode(pyInput);
 }
 
-void MultiDatasetFit::updateGuessFunction(const QString&, const QString&)
-{
+void MultiDatasetFit::updateGuessFunction(const QString &, const QString &) {
   m_plotController->updateGuessFunction(*m_functionBrowser->getFunction());
 }
 
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
index d71132402cfb5779a62a6ffd7e14ff6acc204568..96a6226c5f4100ff07ee374c7436856c8ef29717 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingModel.cpp
@@ -15,215 +15,211 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-  void ALCBaselineModellingModel::fit(IFunction_const_sptr function, const std::vector<Section>& sections)
-  {
-    // Create a copy of the data
-    IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace");
-    clone->setChild(true);
-    clone->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-    clone->setProperty("OutputWorkspace", "__NotUsed__");
-    clone->execute();
-
-    Workspace_sptr cloned = clone->getProperty("OutputWorkspace");
-    MatrixWorkspace_sptr dataToFit = boost::dynamic_pointer_cast<MatrixWorkspace>(cloned);
-    assert(dataToFit); // CloneWorkspace should take care of that
-
-    disableUnwantedPoints(dataToFit, sections);
-
-    IFunction_sptr funcToFit =
-        FunctionFactory::Instance().createInitialized(function->asString());
-
-    IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
-    fit->setChild(true);
-    fit->setProperty("Function", funcToFit);
-    fit->setProperty("InputWorkspace", dataToFit);
-    fit->setProperty("CreateOutput", true);
-
-    // Run async so that progress can be shown
-    Poco::ActiveResult<bool> result(fit->executeAsync());
-    while (!result.available()) {
-      QCoreApplication::processEvents();
-    }
-    if (!result.error().empty()) {
-      throw std::runtime_error(result.error());
-    }
-
-    MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace");
-    m_parameterTable = fit->getProperty("OutputParameters");
-
-    enableDisabledPoints(fitOutput,m_data);
-    setErrorsAfterFit(fitOutput);
-
-    setCorrectedData(fitOutput);
-    setFittedFunction(funcToFit);
-    m_sections = sections;
-
+namespace MantidQt {
+namespace CustomInterfaces {
+
+void ALCBaselineModellingModel::fit(IFunction_const_sptr function,
+                                    const std::vector<Section> &sections) {
+  // Create a copy of the data
+  IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace");
+  clone->setChild(true);
+  clone->setProperty("InputWorkspace",
+                     boost::const_pointer_cast<MatrixWorkspace>(m_data));
+  clone->setProperty("OutputWorkspace", "__NotUsed__");
+  clone->execute();
+
+  Workspace_sptr cloned = clone->getProperty("OutputWorkspace");
+  MatrixWorkspace_sptr dataToFit =
+      boost::dynamic_pointer_cast<MatrixWorkspace>(cloned);
+  assert(dataToFit); // CloneWorkspace should take care of that
+
+  disableUnwantedPoints(dataToFit, sections);
+
+  IFunction_sptr funcToFit =
+      FunctionFactory::Instance().createInitialized(function->asString());
+
+  IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
+  fit->setChild(true);
+  fit->setProperty("Function", funcToFit);
+  fit->setProperty("InputWorkspace", dataToFit);
+  fit->setProperty("CreateOutput", true);
+
+  // Run async so that progress can be shown
+  Poco::ActiveResult<bool> result(fit->executeAsync());
+  while (!result.available()) {
+    QCoreApplication::processEvents();
   }
-
-  void ALCBaselineModellingModel::setData(MatrixWorkspace_const_sptr data)
-  {
-    m_data = data;
-    emit dataChanged();
+  if (!result.error().empty()) {
+    throw std::runtime_error(result.error());
   }
 
-  /**
-   * Disable points in the workpsace in the way that points which are not included in any of specified
-   * sections are not used when fitting given workspace
-   * @param ws :: Workspace to disable points in
-   * @param sections :: Section we want to use for fitting
-   */
-  void ALCBaselineModellingModel::disableUnwantedPoints(MatrixWorkspace_sptr ws,
-    const std::vector<IALCBaselineModellingModel::Section>& sections)
-  {
-    // Whether point with particular index should be disabled
-    std::vector<bool> toDisable(ws->blocksize(), true);
-
-    // Find points which are in at least one section, and exclude them from disable list
-    for (size_t i = 0; i < ws->blocksize(); ++i)
-    {
-      for (auto it = sections.begin(); it != sections.end(); ++it)
-      {
-        if ( ws->dataX(0)[i] >= it->first && ws->dataX(0)[i] <= it->second )
-        {
-          toDisable[i] = false;
-          break; // No need to check other sections
-        }
+  MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace");
+  m_parameterTable = fit->getProperty("OutputParameters");
+
+  enableDisabledPoints(fitOutput, m_data);
+  setErrorsAfterFit(fitOutput);
+
+  setCorrectedData(fitOutput);
+  setFittedFunction(funcToFit);
+  m_sections = sections;
+}
+
+void ALCBaselineModellingModel::setData(MatrixWorkspace_const_sptr data) {
+  m_data = data;
+  emit dataChanged();
+}
+
+/**
+ * Disable points in the workpsace in the way that points which are not included
+ * in any of specified
+ * sections are not used when fitting given workspace
+ * @param ws :: Workspace to disable points in
+ * @param sections :: Section we want to use for fitting
+ */
+void ALCBaselineModellingModel::disableUnwantedPoints(
+    MatrixWorkspace_sptr ws,
+    const std::vector<IALCBaselineModellingModel::Section> &sections) {
+  // Whether point with particular index should be disabled
+  std::vector<bool> toDisable(ws->blocksize(), true);
+
+  // Find points which are in at least one section, and exclude them from
+  // disable list
+  for (size_t i = 0; i < ws->blocksize(); ++i) {
+    for (auto it = sections.begin(); it != sections.end(); ++it) {
+      if (ws->dataX(0)[i] >= it->first && ws->dataX(0)[i] <= it->second) {
+        toDisable[i] = false;
+        break; // No need to check other sections
       }
     }
+  }
 
-    // XXX: Points are disabled by settings their errors to very high value. This makes those
-    //      points to have very low weights during the fitting, effectively disabling them.
+  // XXX: Points are disabled by settings their errors to very high value. This
+  // makes those
+  //      points to have very low weights during the fitting, effectively
+  //      disabling them.
 
-    const double DISABLED_ERR = std::numeric_limits<double>::max();
+  const double DISABLED_ERR = std::numeric_limits<double>::max();
 
-    // Disable chosen points
-    for (size_t i = 0; i < ws->blocksize(); ++i)
-    {
-      if (toDisable[i])
-      {
-        ws->dataE(0)[i] = DISABLED_ERR;
-      }
+  // Disable chosen points
+  for (size_t i = 0; i < ws->blocksize(); ++i) {
+    if (toDisable[i]) {
+      ws->dataE(0)[i] = DISABLED_ERR;
     }
   }
-
-  /**
-   * Enable points that were disabled for fit
-   * @param destWs :: Workspace to enable points in
-   * @param sourceWs :: Workspace with original errors
-   */
-  void ALCBaselineModellingModel::enableDisabledPoints (MatrixWorkspace_sptr destWs, MatrixWorkspace_const_sptr sourceWs)
-  {
-    // Unwanted points were disabled by setting their errors to very high values.
-    // We recover here the original errors stored in sourceWs
-    destWs->dataE(0) = sourceWs->readE(0);
+}
+
+/**
+ * Enable points that were disabled for fit
+ * @param destWs :: Workspace to enable points in
+ * @param sourceWs :: Workspace with original errors
+ */
+void ALCBaselineModellingModel::enableDisabledPoints(
+    MatrixWorkspace_sptr destWs, MatrixWorkspace_const_sptr sourceWs) {
+  // Unwanted points were disabled by setting their errors to very high values.
+  // We recover here the original errors stored in sourceWs
+  destWs->dataE(0) = sourceWs->readE(0);
+}
+
+/**
+ * Set errors in Diff spectrum after a fit
+ * @param data :: [input/output] Workspace containing spectrum to set errors to
+ */
+void ALCBaselineModellingModel::setErrorsAfterFit(MatrixWorkspace_sptr data) {
+
+  data->dataE(2) = data->readE(0);
+}
+
+MatrixWorkspace_sptr ALCBaselineModellingModel::exportWorkspace() {
+  if (m_data && m_data->getNumberHistograms() == 3) {
+
+    // Export results only if data have been fit, that is,
+    // if m_data has three histograms
+    return boost::const_pointer_cast<MatrixWorkspace>(m_data);
+
+  } else {
+
+    return MatrixWorkspace_sptr();
   }
+}
 
-  /**
-   * Set errors in Diff spectrum after a fit
-   * @param data :: [input/output] Workspace containing spectrum to set errors to
-   */
-  void ALCBaselineModellingModel::setErrorsAfterFit (MatrixWorkspace_sptr data) {
+ITableWorkspace_sptr ALCBaselineModellingModel::exportSections() {
+  if (!m_sections.empty()) {
 
-    data->dataE(2)=data->readE(0);
-  }
+    ITableWorkspace_sptr table =
+        WorkspaceFactory::Instance().createTable("TableWorkspace");
 
-  MatrixWorkspace_sptr ALCBaselineModellingModel::exportWorkspace()
-  {
-    if ( m_data && m_data->getNumberHistograms() == 3 ) {
+    table->addColumn("double", "Start X");
+    table->addColumn("double", "End X");
 
-      // Export results only if data have been fit, that is,
-      // if m_data has three histograms
-      return boost::const_pointer_cast<MatrixWorkspace>(m_data);
-
-    } else {
-    
-      return MatrixWorkspace_sptr();
+    for (auto it = m_sections.begin(); it != m_sections.end(); ++it) {
+      TableRow newRow = table->appendRow();
+      newRow << it->first << it->second;
     }
-  }
-
-  ITableWorkspace_sptr ALCBaselineModellingModel::exportSections()
-  {
-    if ( !m_sections.empty() ) {
 
-      ITableWorkspace_sptr table = WorkspaceFactory::Instance().createTable("TableWorkspace");
+    return table;
 
-      table->addColumn("double", "Start X");
-      table->addColumn("double", "End X");
+  } else {
 
-      for(auto it = m_sections.begin(); it != m_sections.end(); ++it)
-      {
-        TableRow newRow = table->appendRow();
-        newRow << it->first << it->second;
-      }
-
-      return table;
-
-    } else {
-
-      return ITableWorkspace_sptr();
-    }
+    return ITableWorkspace_sptr();
   }
+}
 
-  ITableWorkspace_sptr ALCBaselineModellingModel::exportModel()
-  {
-    if ( m_parameterTable ) {
+ITableWorkspace_sptr ALCBaselineModellingModel::exportModel() {
+  if (m_parameterTable) {
 
-      return m_parameterTable;
+    return m_parameterTable;
 
-    } else {
-      
-      return ITableWorkspace_sptr();
-    }
-  }
+  } else {
 
-  void ALCBaselineModellingModel::setCorrectedData(MatrixWorkspace_const_sptr data)
-  {
-    m_data = data;
-    emit correctedDataChanged();
+    return ITableWorkspace_sptr();
   }
-
-  void ALCBaselineModellingModel::setFittedFunction(IFunction_const_sptr function)
-  {
-    m_fittedFunction = function;
-    emit fittedFunctionChanged();
-  }
-
-  MatrixWorkspace_const_sptr ALCBaselineModellingModel::data() const
-  {
-    if (m_data) {
-      IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
-      extract->setChild(true);
-      extract->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-      extract->setProperty("WorkspaceIndex", 0);
-      extract->setProperty("OutputWorkspace", "__NotUsed__");
-      extract->execute();
-      MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
-      return result;
-    } else {
-      return MatrixWorkspace_const_sptr();
-    }
+}
+
+void ALCBaselineModellingModel::setCorrectedData(
+    MatrixWorkspace_const_sptr data) {
+  m_data = data;
+  emit correctedDataChanged();
+}
+
+void ALCBaselineModellingModel::setFittedFunction(
+    IFunction_const_sptr function) {
+  m_fittedFunction = function;
+  emit fittedFunctionChanged();
+}
+
+MatrixWorkspace_const_sptr ALCBaselineModellingModel::data() const {
+  if (m_data) {
+    IAlgorithm_sptr extract =
+        AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+    extract->setChild(true);
+    extract->setProperty("InputWorkspace",
+                         boost::const_pointer_cast<MatrixWorkspace>(m_data));
+    extract->setProperty("WorkspaceIndex", 0);
+    extract->setProperty("OutputWorkspace", "__NotUsed__");
+    extract->execute();
+    MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
+    return result;
+  } else {
+    return MatrixWorkspace_const_sptr();
   }
-
-  MatrixWorkspace_const_sptr ALCBaselineModellingModel::correctedData() const
-  {
-    if (m_data && (m_data->getNumberHistograms()==3) ) {
-      IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
-      extract->setChild(true);
-      extract->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-      extract->setProperty("WorkspaceIndex", 2);
-      extract->setProperty("OutputWorkspace", "__NotUsed__");
-      extract->execute();
-      MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
-      return result;
-    } else {
-      return MatrixWorkspace_const_sptr();
-    }
+}
+
+MatrixWorkspace_const_sptr ALCBaselineModellingModel::correctedData() const {
+  if (m_data && (m_data->getNumberHistograms() == 3)) {
+    IAlgorithm_sptr extract =
+        AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+    extract->setChild(true);
+    extract->setProperty("InputWorkspace",
+                         boost::const_pointer_cast<MatrixWorkspace>(m_data));
+    extract->setProperty("WorkspaceIndex", 2);
+    extract->setProperty("OutputWorkspace", "__NotUsed__");
+    extract->execute();
+    MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace");
+    return result;
+  } else {
+    return MatrixWorkspace_const_sptr();
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
index 891366f2857e23db3ff088e657c9de4bd3c2db8e..4750f4a95683a7d5235f9da9c18c0af137702065 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingPresenter.cpp
@@ -9,215 +9,188 @@
 using namespace Mantid::API;
 
 namespace MantidQt {
-namespace CustomInterfaces
-{
-
-  ALCBaselineModellingPresenter::ALCBaselineModellingPresenter(IALCBaselineModellingView* view,
-                                                               IALCBaselineModellingModel* model)
-    : m_view(view), m_model(model)
-  {}
-
-  void ALCBaselineModellingPresenter::initialize()
-  {
-    m_view->initialize();
-
-    // View actions
-    connect(m_view, SIGNAL(fitRequested()), SLOT(fit()));
-    connect(m_view, SIGNAL(addSectionRequested()), SLOT(addSection()));
-    connect(m_view, SIGNAL(removeSectionRequested(int)), SLOT(removeSection(int)));
-
-    // View events (sync)
-    connect(m_view, SIGNAL(sectionRowModified(int)), SLOT(onSectionRowModified(int)));
-    connect(m_view, SIGNAL(sectionSelectorModified(int)), SLOT(onSectionSelectorModified(int)));
-
-    // Model updates
-    connect(m_model, SIGNAL(dataChanged()), SLOT(updateDataCurve()));
-    connect(m_model, SIGNAL(correctedDataChanged()), SLOT(updateCorrectedCurve()));
-    connect(m_model, SIGNAL(fittedFunctionChanged()), SLOT(updateFunction()));
-    connect(m_model, SIGNAL(fittedFunctionChanged()), SLOT(updateBaselineCurve()));
+namespace CustomInterfaces {
+
+ALCBaselineModellingPresenter::ALCBaselineModellingPresenter(
+    IALCBaselineModellingView *view, IALCBaselineModellingModel *model)
+    : m_view(view), m_model(model) {}
+
+void ALCBaselineModellingPresenter::initialize() {
+  m_view->initialize();
+
+  // View actions
+  connect(m_view, SIGNAL(fitRequested()), SLOT(fit()));
+  connect(m_view, SIGNAL(addSectionRequested()), SLOT(addSection()));
+  connect(m_view, SIGNAL(removeSectionRequested(int)),
+          SLOT(removeSection(int)));
+
+  // View events (sync)
+  connect(m_view, SIGNAL(sectionRowModified(int)),
+          SLOT(onSectionRowModified(int)));
+  connect(m_view, SIGNAL(sectionSelectorModified(int)),
+          SLOT(onSectionSelectorModified(int)));
+
+  // Model updates
+  connect(m_model, SIGNAL(dataChanged()), SLOT(updateDataCurve()));
+  connect(m_model, SIGNAL(correctedDataChanged()),
+          SLOT(updateCorrectedCurve()));
+  connect(m_model, SIGNAL(fittedFunctionChanged()), SLOT(updateFunction()));
+  connect(m_model, SIGNAL(fittedFunctionChanged()),
+          SLOT(updateBaselineCurve()));
+}
+
+/**
+ * Perform a fit and updates the view accordingly
+ */
+void ALCBaselineModellingPresenter::fit() {
+  std::vector<IALCBaselineModellingModel::Section> parsedSections;
+
+  for (int i = 0; i < m_view->noOfSectionRows(); ++i) {
+    auto sectionRow = m_view->sectionRow(i);
+
+    double min = sectionRow.first.toDouble();
+    double max = sectionRow.second.toDouble();
+
+    IALCBaselineModellingModel::Section parsedSection(min, max);
+
+    parsedSections.push_back(parsedSection);
   }
 
-  /**
-   * Perform a fit and updates the view accordingly
-   */
-  void ALCBaselineModellingPresenter::fit()
-  {
-    std::vector<IALCBaselineModellingModel::Section> parsedSections;
-
-    for (int i = 0; i < m_view->noOfSectionRows(); ++i)
-    {
-      auto sectionRow = m_view->sectionRow(i);
-
-      double min = sectionRow.first.toDouble();
-      double max = sectionRow.second.toDouble();
-
-      IALCBaselineModellingModel::Section parsedSection(min, max);
-
-      parsedSections.push_back(parsedSection);
-    }
-
-    std::string funcStr = m_view->function().toStdString();
-
-    if (funcStr.empty())
-    {
-      m_view->displayError("Couldn't fit an empty function");
-    }
-    else if(parsedSections.empty())
-    {
-      m_view->displayError("No sections to fit");
-    }
-    else
-    {
-      try
-      {
-        IFunction_sptr funcToFit = FunctionFactory::Instance().createInitialized(funcStr);
-        m_model->fit(funcToFit, parsedSections);
-      }
-      catch(std::exception& e)
-      {
-        m_view->displayError(QString::fromStdString(e.what()));
-      }
+  std::string funcStr = m_view->function().toStdString();
+
+  if (funcStr.empty()) {
+    m_view->displayError("Couldn't fit an empty function");
+  } else if (parsedSections.empty()) {
+    m_view->displayError("No sections to fit");
+  } else {
+    try {
+      IFunction_sptr funcToFit =
+          FunctionFactory::Instance().createInitialized(funcStr);
+      m_model->fit(funcToFit, parsedSections);
+    } catch (std::exception &e) {
+      m_view->displayError(QString::fromStdString(e.what()));
     }
   }
+}
 
-  /**
-   * Adds new section in the view
-   */
-  void ALCBaselineModellingPresenter::addSection()
-  {
-    if (MatrixWorkspace_const_sptr data = m_model->data()) {
-      double xMin = data->getXMin();
-      double xMax = data->getXMax();
+/**
+ * Adds new section in the view
+ */
+void ALCBaselineModellingPresenter::addSection() {
+  if (MatrixWorkspace_const_sptr data = m_model->data()) {
+    double xMin = data->getXMin();
+    double xMax = data->getXMax();
 
-      int noOfSections = m_view->noOfSectionRows();
+    int noOfSections = m_view->noOfSectionRows();
 
-      m_view->setNoOfSectionRows(noOfSections + 1);
+    m_view->setNoOfSectionRows(noOfSections + 1);
 
-      m_view->setSectionRow(
-          noOfSections,
-          std::make_pair(QString::number(xMin), QString::number(xMax)));
+    m_view->setSectionRow(noOfSections, std::make_pair(QString::number(xMin),
+                                                       QString::number(xMax)));
 
-      m_view->addSectionSelector(noOfSections, std::make_pair(xMin, xMax));
-    } else {
-      m_view->displayError("Please load some data first");
-    }
+    m_view->addSectionSelector(noOfSections, std::make_pair(xMin, xMax));
+  } else {
+    m_view->displayError("Please load some data first");
+  }
+}
+
+/**
+ * @param row :: Section row to remove
+ */
+void ALCBaselineModellingPresenter::removeSection(int row) {
+  // The view should make sure the row is valid
+  assert(row >= 0);
+  assert(row < m_view->noOfSectionRows());
+
+  // Delete all section selectors
+  for (int i = 0; i < m_view->noOfSectionRows(); ++i) {
+    m_view->deleteSectionSelector(i);
   }
 
-  /**
-   * @param row :: Section row to remove
-   */
-  void ALCBaselineModellingPresenter::removeSection(int row)
-  {
-    // The view should make sure the row is valid
-    assert(row >= 0);
-    assert(row < m_view->noOfSectionRows());
-
-    // Delete all section selectors
-    for (int i = 0; i < m_view->noOfSectionRows(); ++i)
-    {
-      m_view->deleteSectionSelector(i);
-    }
-
-    std::vector<IALCBaselineModellingView::SectionRow> allRows;
+  std::vector<IALCBaselineModellingView::SectionRow> allRows;
 
-    for (int i = 0; i < m_view->noOfSectionRows(); ++i)
-    {
-      allRows.push_back(m_view->sectionRow(i));
-    }
+  for (int i = 0; i < m_view->noOfSectionRows(); ++i) {
+    allRows.push_back(m_view->sectionRow(i));
+  }
 
-    allRows.erase(allRows.begin() + row);
+  allRows.erase(allRows.begin() + row);
 
-    // Shrink sections table
-    m_view->setNoOfSectionRows(static_cast<int>(allRows.size()));
+  // Shrink sections table
+  m_view->setNoOfSectionRows(static_cast<int>(allRows.size()));
 
-    // Update row values and add sections selectors
-    for (size_t i = 0; i < allRows.size(); ++i)
-    {
-      m_view->setSectionRow(static_cast<int>(i), allRows[i]);
+  // Update row values and add sections selectors
+  for (size_t i = 0; i < allRows.size(); ++i) {
+    m_view->setSectionRow(static_cast<int>(i), allRows[i]);
 
-      double startX = allRows[i].first.toDouble();
-      double endX = allRows[i].second.toDouble();
+    double startX = allRows[i].first.toDouble();
+    double endX = allRows[i].second.toDouble();
 
-      IALCBaselineModellingView::SectionSelector newSelector(startX, endX);
-      m_view->addSectionSelector(static_cast<int>(i), newSelector);
-    }
+    IALCBaselineModellingView::SectionSelector newSelector(startX, endX);
+    m_view->addSectionSelector(static_cast<int>(i), newSelector);
   }
+}
 
-  void ALCBaselineModellingPresenter::onSectionRowModified(int row)
-  {
-    auto sectionRow = m_view->sectionRow(row);
+void ALCBaselineModellingPresenter::onSectionRowModified(int row) {
+  auto sectionRow = m_view->sectionRow(row);
 
-    double startX = sectionRow.first.toDouble();
-    double endX = sectionRow.second.toDouble();
+  double startX = sectionRow.first.toDouble();
+  double endX = sectionRow.second.toDouble();
 
-    int index(row); // That's what we make sure of in addSection()
-    IALCBaselineModellingView::SectionSelector sectionSelector(startX, endX);
+  int index(row); // That's what we make sure of in addSection()
+  IALCBaselineModellingView::SectionSelector sectionSelector(startX, endX);
 
-    m_view->updateSectionSelector(index, sectionSelector);
-  }
+  m_view->updateSectionSelector(index, sectionSelector);
+}
 
-  /**
-   * @param index :: Index of section selector
-   */
-  void ALCBaselineModellingPresenter::onSectionSelectorModified(int index)
-  {
-    auto selectorValues = m_view->sectionSelector(index);
+/**
+ * @param index :: Index of section selector
+ */
+void ALCBaselineModellingPresenter::onSectionSelectorModified(int index) {
+  auto selectorValues = m_view->sectionSelector(index);
 
-    QString startX = QString::number(selectorValues.first);
-    QString endX = QString::number(selectorValues.second);
+  QString startX = QString::number(selectorValues.first);
+  QString endX = QString::number(selectorValues.second);
 
-    int row(index); // That's what we make sure of in addSection()
-    IALCBaselineModellingView::SectionRow rowValues(startX, endX);
+  int row(index); // That's what we make sure of in addSection()
+  IALCBaselineModellingView::SectionRow rowValues(startX, endX);
 
-    m_view->setSectionRow(row, rowValues);
-  }
+  m_view->setSectionRow(row, rowValues);
+}
 
-  void ALCBaselineModellingPresenter::updateDataCurve()
-  {
-    MatrixWorkspace_const_sptr data = m_model->data();
-    assert(data);
-    m_view->setDataCurve(*(ALCHelper::curveDataFromWs(data, 0)),
-                         ALCHelper::curveErrorsFromWs(data, 0));
-  }
+void ALCBaselineModellingPresenter::updateDataCurve() {
+  MatrixWorkspace_const_sptr data = m_model->data();
+  assert(data);
+  m_view->setDataCurve(*(ALCHelper::curveDataFromWs(data, 0)),
+                       ALCHelper::curveErrorsFromWs(data, 0));
+}
 
-  void ALCBaselineModellingPresenter::updateCorrectedCurve()
-  {
-    if(MatrixWorkspace_const_sptr correctedData = m_model->correctedData())
-    {
-      m_view->setCorrectedCurve(*(ALCHelper::curveDataFromWs(correctedData, 0)),
-                                ALCHelper::curveErrorsFromWs(correctedData, 0));
-    }
-    else
-    {
-      m_view->setCorrectedCurve(*(ALCHelper::emptyCurveData()),
-                                std::vector<double>());
-    }
+void ALCBaselineModellingPresenter::updateCorrectedCurve() {
+  if (MatrixWorkspace_const_sptr correctedData = m_model->correctedData()) {
+    m_view->setCorrectedCurve(*(ALCHelper::curveDataFromWs(correctedData, 0)),
+                              ALCHelper::curveErrorsFromWs(correctedData, 0));
+  } else {
+    m_view->setCorrectedCurve(*(ALCHelper::emptyCurveData()),
+                              std::vector<double>());
   }
-
-  void ALCBaselineModellingPresenter::updateBaselineCurve()
-  {
-    if (IFunction_const_sptr fittedFunc = m_model->fittedFunction())
-    {
-      const std::vector<double>& xValues = m_model->data()->readX(0);
-      m_view->setBaselineCurve(*(ALCHelper::curveDataFromFunction(fittedFunc, xValues)));
-    }
-    else
-    {
-      m_view->setBaselineCurve(*(ALCHelper::emptyCurveData()));
-    }
+}
+
+void ALCBaselineModellingPresenter::updateBaselineCurve() {
+  if (IFunction_const_sptr fittedFunc = m_model->fittedFunction()) {
+    const std::vector<double> &xValues = m_model->data()->readX(0);
+    m_view->setBaselineCurve(
+        *(ALCHelper::curveDataFromFunction(fittedFunc, xValues)));
+  } else {
+    m_view->setBaselineCurve(*(ALCHelper::emptyCurveData()));
   }
+}
 
-  void ALCBaselineModellingPresenter::updateFunction()
-  {
-    if (IFunction_const_sptr fittedFunc = m_model->fittedFunction())
-    {
-      m_view->setFunction(fittedFunc);
-    }
-    else
-    {
-      m_view->setFunction(IFunction_const_sptr());
-    }
+void ALCBaselineModellingPresenter::updateFunction() {
+  if (IFunction_const_sptr fittedFunc = m_model->fittedFunction()) {
+    m_view->setFunction(fittedFunc);
+  } else {
+    m_view->setFunction(IFunction_const_sptr());
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingView.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingView.cpp
index 18c79d68002fb7da3f9b4a16536dd2b6bd186d5d..1577607a182f794b50208d3b076e0c56bd238aeb 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingView.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCBaselineModellingView.cpp
@@ -16,266 +16,250 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  ALCBaselineModellingView::ALCBaselineModellingView(QWidget* widget)
-    : m_widget(widget), m_ui(),
-      m_dataCurve(new QwtPlotCurve()), m_fitCurve(new QwtPlotCurve()),
-      m_correctedCurve(new QwtPlotCurve()), m_dataErrorCurve(NULL), 
-      m_correctedErrorCurve(NULL), m_rangeSelectors(),
-      m_selectorModifiedMapper(new QSignalMapper(this))
-  {}
-
-  ALCBaselineModellingView::~ALCBaselineModellingView()
-  {
-    m_dataCurve->detach();
-    delete m_dataCurve;
-    m_correctedCurve->detach();
-    delete m_correctedCurve;
-    if (m_dataErrorCurve) {
-      m_dataErrorCurve->detach();
-      delete m_dataErrorCurve;
-    }
-    if (m_correctedErrorCurve) {
-      m_correctedErrorCurve->detach();
-      delete m_correctedErrorCurve;
-    }
+namespace MantidQt {
+namespace CustomInterfaces {
+ALCBaselineModellingView::ALCBaselineModellingView(QWidget *widget)
+    : m_widget(widget), m_ui(), m_dataCurve(new QwtPlotCurve()),
+      m_fitCurve(new QwtPlotCurve()), m_correctedCurve(new QwtPlotCurve()),
+      m_dataErrorCurve(NULL), m_correctedErrorCurve(NULL), m_rangeSelectors(),
+      m_selectorModifiedMapper(new QSignalMapper(this)) {}
+
+ALCBaselineModellingView::~ALCBaselineModellingView() {
+  m_dataCurve->detach();
+  delete m_dataCurve;
+  m_correctedCurve->detach();
+  delete m_correctedCurve;
+  if (m_dataErrorCurve) {
+    m_dataErrorCurve->detach();
+    delete m_dataErrorCurve;
   }
-    
-  void ALCBaselineModellingView::initialize()
-  {
-    m_ui.setupUi(m_widget);
-    connect(m_ui.fit, SIGNAL(clicked()), SIGNAL(fitRequested()));
-
-    m_ui.dataPlot->setCanvasBackground(Qt::white);
-    m_ui.dataPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
-    m_ui.dataPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
-
-    m_ui.correctedPlot->setCanvasBackground(Qt::white);
-    m_ui.correctedPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
-    m_ui.correctedPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
-
-    m_dataCurve->setStyle(QwtPlotCurve::NoCurve);
-    m_dataCurve->setSymbol(QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7,7)));
-    m_dataCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
-    m_dataCurve->attach(m_ui.dataPlot);
-
-    m_fitCurve->setPen(QPen(Qt::red, 1.5));
-    m_fitCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
-    m_fitCurve->attach(m_ui.dataPlot);
-
-    m_correctedCurve->setStyle(QwtPlotCurve::NoCurve);
-    m_correctedCurve->setPen(QPen(Qt::green));
-    m_correctedCurve->setSymbol(QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(Qt::green), QSize(7,7)));
-    m_correctedCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
-    m_correctedCurve->attach(m_ui.correctedPlot);
-
-    // Context menu for sections table
-    m_ui.sections->setContextMenuPolicy(Qt::CustomContextMenu);
-    connect(m_ui.sections, SIGNAL(customContextMenuRequested(const QPoint &)),
-            SLOT(sectionsContextMenu(const QPoint&)));
-
-    // Make columns non-resizeable and to fill all the available space
-    m_ui.sections->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
-
-    connect(m_ui.sections, SIGNAL(cellChanged(int,int)), SIGNAL(sectionRowModified(int)));
-
-    connect(m_selectorModifiedMapper, SIGNAL(mapped(int)), SIGNAL(sectionSelectorModified(int)));
-
-    connect(m_ui.help, SIGNAL(clicked()), this, SLOT(help()));
-  }
-
-  QString ALCBaselineModellingView::function() const
-  {
-    return m_ui.function->getFunctionString();
-  }
-
-  IALCBaselineModellingView::SectionRow ALCBaselineModellingView::sectionRow(int row) const
-  {
-    QString first = m_ui.sections->item(row, 0)->text();
-    QString second = m_ui.sections->item(row, 1)->text();
-    return SectionRow(first, second);
+  if (m_correctedErrorCurve) {
+    m_correctedErrorCurve->detach();
+    delete m_correctedErrorCurve;
   }
-
-  IALCBaselineModellingView::SectionSelector ALCBaselineModellingView::sectionSelector(int index) const
-  {
-    auto rangeSelector = m_rangeSelectors.find(index)->second;
-    return std::make_pair(rangeSelector->getMinimum(), rangeSelector->getMaximum());
-  }
-
-  int ALCBaselineModellingView::noOfSectionRows() const
-  {
-    return m_ui.sections->rowCount();
+}
+
+void ALCBaselineModellingView::initialize() {
+  m_ui.setupUi(m_widget);
+  connect(m_ui.fit, SIGNAL(clicked()), SIGNAL(fitRequested()));
+
+  m_ui.dataPlot->setCanvasBackground(Qt::white);
+  m_ui.dataPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
+  m_ui.dataPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
+
+  m_ui.correctedPlot->setCanvasBackground(Qt::white);
+  m_ui.correctedPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
+  m_ui.correctedPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
+
+  m_dataCurve->setStyle(QwtPlotCurve::NoCurve);
+  m_dataCurve->setSymbol(
+      QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7, 7)));
+  m_dataCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
+  m_dataCurve->attach(m_ui.dataPlot);
+
+  m_fitCurve->setPen(QPen(Qt::red, 1.5));
+  m_fitCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
+  m_fitCurve->attach(m_ui.dataPlot);
+
+  m_correctedCurve->setStyle(QwtPlotCurve::NoCurve);
+  m_correctedCurve->setPen(QPen(Qt::green));
+  m_correctedCurve->setSymbol(
+      QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(Qt::green), QSize(7, 7)));
+  m_correctedCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
+  m_correctedCurve->attach(m_ui.correctedPlot);
+
+  // Context menu for sections table
+  m_ui.sections->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(m_ui.sections, SIGNAL(customContextMenuRequested(const QPoint &)),
+          SLOT(sectionsContextMenu(const QPoint &)));
+
+  // Make columns non-resizeable and to fill all the available space
+  m_ui.sections->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
+
+  connect(m_ui.sections, SIGNAL(cellChanged(int, int)),
+          SIGNAL(sectionRowModified(int)));
+
+  connect(m_selectorModifiedMapper, SIGNAL(mapped(int)),
+          SIGNAL(sectionSelectorModified(int)));
+
+  connect(m_ui.help, SIGNAL(clicked()), this, SLOT(help()));
+}
+
+QString ALCBaselineModellingView::function() const {
+  return m_ui.function->getFunctionString();
+}
+
+IALCBaselineModellingView::SectionRow
+ALCBaselineModellingView::sectionRow(int row) const {
+  QString first = m_ui.sections->item(row, 0)->text();
+  QString second = m_ui.sections->item(row, 1)->text();
+  return SectionRow(first, second);
+}
+
+IALCBaselineModellingView::SectionSelector
+ALCBaselineModellingView::sectionSelector(int index) const {
+  auto rangeSelector = m_rangeSelectors.find(index)->second;
+  return std::make_pair(rangeSelector->getMinimum(),
+                        rangeSelector->getMaximum());
+}
+
+int ALCBaselineModellingView::noOfSectionRows() const {
+  return m_ui.sections->rowCount();
+}
+
+void ALCBaselineModellingView::setDataCurve(const QwtData &data,
+                                            const std::vector<double> &errors) {
+  // Set data
+  m_dataCurve->setData(data);
+
+  // Set errors
+  if (m_dataErrorCurve) {
+    m_dataErrorCurve->detach();
+    delete m_dataErrorCurve;
   }
-
-  void
-  ALCBaselineModellingView::setDataCurve(const QwtData &data,
-                                         const std::vector<double> &errors)
-  {
-    // Set data
-    m_dataCurve->setData(data);
-
-    // Set errors
-    if (m_dataErrorCurve) {
-      m_dataErrorCurve->detach();
-      delete m_dataErrorCurve;
-    }
-    m_dataErrorCurve =
-        new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, errors);
-    m_dataErrorCurve->attach(m_ui.dataPlot);
-
-    // Replot
-    m_ui.dataPlot->replot();
+  m_dataErrorCurve =
+      new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, errors);
+  m_dataErrorCurve->attach(m_ui.dataPlot);
+
+  // Replot
+  m_ui.dataPlot->replot();
+}
+
+void ALCBaselineModellingView::setCorrectedCurve(
+    const QwtData &data, const std::vector<double> &errors) {
+  // Set data
+  m_correctedCurve->setData(data);
+
+  // Set errors
+  if (m_correctedErrorCurve) {
+    m_correctedErrorCurve->detach();
+    delete m_correctedErrorCurve;
   }
-
-  void ALCBaselineModellingView::setCorrectedCurve(
-      const QwtData &data, const std::vector<double> &errors) 
-  {
-    // Set data
-    m_correctedCurve->setData(data);
-
-    // Set errors
-    if (m_correctedErrorCurve) {
-      m_correctedErrorCurve->detach();
-      delete m_correctedErrorCurve;
+  m_correctedErrorCurve =
+      new MantidQt::MantidWidgets::ErrorCurve(m_correctedCurve, errors);
+  m_correctedErrorCurve->attach(m_ui.correctedPlot);
+
+  // Replot
+  m_ui.correctedPlot->replot();
+}
+
+void ALCBaselineModellingView::setBaselineCurve(const QwtData &data) {
+  m_fitCurve->setData(data);
+  m_ui.dataPlot->replot();
+}
+
+void ALCBaselineModellingView::setFunction(IFunction_const_sptr func) {
+  if (!func) {
+    m_ui.function->clear();
+  } else {
+    size_t nParams = func->nParams();
+    for (size_t i = 0; i < nParams; i++) {
+
+      QString name = QString::fromStdString(func->parameterName(i));
+      double value = func->getParameter(i);
+      double error = func->getError(i);
+
+      m_ui.function->setParameter(name, value);
+      m_ui.function->setParamError(name, error);
     }
-    m_correctedErrorCurve =
-        new MantidQt::MantidWidgets::ErrorCurve(m_correctedCurve, errors);
-    m_correctedErrorCurve->attach(m_ui.correctedPlot);
-
-    // Replot
-    m_ui.correctedPlot->replot();
   }
-
-  void ALCBaselineModellingView::setBaselineCurve(const QwtData &data)
-  {
-    m_fitCurve->setData(data);
-    m_ui.dataPlot->replot();
+}
+
+void ALCBaselineModellingView::setNoOfSectionRows(int rows) {
+  m_ui.sections->setRowCount(rows);
+}
+
+void ALCBaselineModellingView::setSectionRow(
+    int row, IALCBaselineModellingView::SectionRow values) {
+  m_ui.sections->blockSignals(
+      true); // Setting values, no need for 'modified' signals
+  m_ui.sections->setFocus();
+  m_ui.sections->selectRow(row);
+  m_ui.sections->setItem(row, 0, new QTableWidgetItem(values.first));
+  m_ui.sections->setItem(row, 1, new QTableWidgetItem(values.second));
+  m_ui.sections->blockSignals(false);
+}
+
+void ALCBaselineModellingView::addSectionSelector(
+    int index, IALCBaselineModellingView::SectionSelector values) {
+  RangeSelector *newSelector = new RangeSelector(m_ui.dataPlot);
+
+  if (index % 3 == 0) {
+    newSelector->setColour(Qt::blue);
+  } else if ((index - 1) % 3 == 0) {
+    newSelector->setColour(Qt::red);
+  } else {
+    newSelector->setColour(Qt::green);
   }
 
-  void ALCBaselineModellingView::setFunction(IFunction_const_sptr func)
-  {
-    if (!func)
-    {
-      m_ui.function->clear();
-    }
-    else
-    {
-      size_t nParams = func->nParams();
-      for (size_t i=0; i<nParams; i++) {
-
-        QString name = QString::fromStdString(func->parameterName(i));
-        double value = func->getParameter(i);
-        double error = func->getError(i);
-
-        m_ui.function->setParameter(name,value);
-        m_ui.function->setParamError(name,error);
-      }
-    }
-  }
+  m_selectorModifiedMapper->setMapping(newSelector, index);
+  connect(newSelector, SIGNAL(selectionChanged(double, double)),
+          m_selectorModifiedMapper, SLOT(map()));
 
-  void ALCBaselineModellingView::setNoOfSectionRows(int rows)
-  {
-    m_ui.sections->setRowCount(rows);
-  }
+  m_rangeSelectors[index] = newSelector;
 
-  void ALCBaselineModellingView::setSectionRow(int row, IALCBaselineModellingView::SectionRow values)
-  {
-    m_ui.sections->blockSignals(true); // Setting values, no need for 'modified' signals
-    m_ui.sections->setFocus();
-    m_ui.sections->selectRow(row);
-    m_ui.sections->setItem(row, 0, new QTableWidgetItem(values.first));
-    m_ui.sections->setItem(row, 1, new QTableWidgetItem(values.second));
-    m_ui.sections->blockSignals(false);
-  }
+  // Set initial values
+  setSelectorValues(newSelector, values);
 
-  void ALCBaselineModellingView::addSectionSelector(int index,
-                                                    IALCBaselineModellingView::SectionSelector values)
-  {
-    RangeSelector* newSelector = new RangeSelector(m_ui.dataPlot);
-
-    if (index%3==0) {
-      newSelector->setColour(Qt::blue);
-    } else if ( (index-1)%3==0 ) {
-      newSelector->setColour(Qt::red);
-    } else {
-      newSelector->setColour(Qt::green);
-    }
+  m_ui.dataPlot->replot();
+}
 
-    m_selectorModifiedMapper->setMapping(newSelector,index);
-    connect(newSelector, SIGNAL(selectionChanged(double,double)),
-            m_selectorModifiedMapper, SLOT(map()));
+void ALCBaselineModellingView::deleteSectionSelector(int index) {
+  auto rangeSelector = m_rangeSelectors[index];
+  m_rangeSelectors.erase(index);
 
-    m_rangeSelectors[index] = newSelector;
+  rangeSelector->detach(); // This is not done when it's deleted
+  m_selectorModifiedMapper->removeMappings(rangeSelector);
+  delete rangeSelector;
 
-    // Set initial values
-    setSelectorValues(newSelector, values);
+  m_ui.dataPlot->replot();
+}
 
-    m_ui.dataPlot->replot();
-  }
+void ALCBaselineModellingView::updateSectionSelector(
+    int index, IALCBaselineModellingView::SectionSelector values) {
+  setSelectorValues(m_rangeSelectors[index], values);
+}
 
-  void ALCBaselineModellingView::deleteSectionSelector(int index)
-  {
-    auto rangeSelector = m_rangeSelectors[index];
-    m_rangeSelectors.erase(index);
+void ALCBaselineModellingView::displayError(const QString &message) {
+  QMessageBox::critical(m_widget, "Error", message);
+}
 
-    rangeSelector->detach(); // This is not done when it's deleted
-    m_selectorModifiedMapper->removeMappings(rangeSelector);
-    delete rangeSelector;
+void ALCBaselineModellingView::sectionsContextMenu(const QPoint &widgetPoint) {
+  QMenu menu(m_widget);
+  menu.addAction("Add section", this, SIGNAL(addSectionRequested()));
 
-    m_ui.dataPlot->replot();
-  }
+  // Helper mapper to map removal action to row id
+  QSignalMapper removalActionMapper;
+  connect(&removalActionMapper, SIGNAL(mapped(int)),
+          SIGNAL(removeSectionRequested(int)));
 
-  void ALCBaselineModellingView::updateSectionSelector(int index,
-                                                       IALCBaselineModellingView::SectionSelector values)
-  {
-    setSelectorValues(m_rangeSelectors[index], values);
+  int row = m_ui.sections->rowAt(widgetPoint.y());
+  if (row != -1) {
+    // Add removal action
+    QAction *removeAction =
+        menu.addAction("Remove section", &removalActionMapper, SLOT(map()));
+    removalActionMapper.setMapping(removeAction, row);
   }
 
-  void ALCBaselineModellingView::displayError(const QString& message)
-  {
-    QMessageBox::critical(m_widget, "Error", message);
-  }
-
-  void ALCBaselineModellingView::sectionsContextMenu(const QPoint& widgetPoint)
-  {
-    QMenu menu(m_widget);
-    menu.addAction("Add section", this, SIGNAL(addSectionRequested()));
-
-    // Helper mapper to map removal action to row id
-    QSignalMapper removalActionMapper;
-    connect(&removalActionMapper, SIGNAL(mapped(int)), SIGNAL(removeSectionRequested(int)));
-
-    int row = m_ui.sections->rowAt(widgetPoint.y());
-    if (row != -1)
-    {
-      // Add removal action
-      QAction* removeAction = menu.addAction("Remove section", &removalActionMapper, SLOT(map()));
-      removalActionMapper.setMapping(removeAction, row);
-    }
-
-    menu.exec(QCursor::pos());
-  }
+  menu.exec(QCursor::pos());
+}
 
-  void ALCBaselineModellingView::setSelectorValues(RangeSelector* selector,
-                                                   IALCBaselineModellingView::SectionSelector values)
-  {
-    // TODO: range sould be set to something meaningful
-    selector->setRange(std::numeric_limits<double>::min(), std::numeric_limits<double>::max());
+void ALCBaselineModellingView::setSelectorValues(
+    RangeSelector *selector,
+    IALCBaselineModellingView::SectionSelector values) {
+  // TODO: range sould be set to something meaningful
+  selector->setRange(std::numeric_limits<double>::min(),
+                     std::numeric_limits<double>::max());
 
-    selector->setMinimum(values.first);
-    selector->setMaximum(values.second);
-  }
+  selector->setMinimum(values.first);
+  selector->setMaximum(values.second);
+}
 
-  void ALCBaselineModellingView::help() {
-    MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Muon_ALC"));
-  }
+void ALCBaselineModellingView::help() {
+  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Muon_ALC"));
+}
 
-  void ALCBaselineModellingView::emitFitRequested() {
-    emit fitRequested();
-  }
+void ALCBaselineModellingView::emitFitRequested() { emit fitRequested(); }
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingView.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingView.cpp
index 724b51fe930df3eb5114788c79468654a4291eac..03e384382be3781ffadb91679f757d5a94484717 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingView.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCDataLoadingView.cpp
@@ -7,10 +7,8 @@
 
 #include <qwt_symbol.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 /// This is the string "Auto", used for last file
 const std::string ALCDataLoadingView::g_autoString = "Auto";
 
@@ -25,304 +23,286 @@ ALCDataLoadingView::~ALCDataLoadingView() {
     m_dataErrorCurve->detach();
     delete m_dataErrorCurve;
   }
+}
+
+void ALCDataLoadingView::initialize() {
+  m_ui.setupUi(m_widget);
+  connect(m_ui.load, SIGNAL(clicked()), SIGNAL(loadRequested()));
+  connect(m_ui.firstRun, SIGNAL(fileFindingFinished()),
+          SIGNAL(firstRunSelected()));
+  connect(m_ui.firstRun, SIGNAL(filesFoundChanged()), this,
+          SLOT(handleFirstFileChanged()));
+  connect(m_ui.help, SIGNAL(clicked()), this, SLOT(help()));
+  connect(m_ui.lastRunAuto, SIGNAL(stateChanged(int)), this,
+          SLOT(checkBoxAutoChanged(int)));
+
+  m_ui.dataPlot->setCanvasBackground(Qt::white);
+  m_ui.dataPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
+  m_ui.dataPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
+
+  m_dataCurve->setStyle(QwtPlotCurve::NoCurve);
+  m_dataCurve->setSymbol(
+      QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7, 7)));
+  m_dataCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
+  m_dataCurve->attach(m_ui.dataPlot);
+
+  // The following lines disable the groups' titles when the
+  // group is disabled
+  QPalette palette;
+  palette.setColor(
+      QPalette::Disabled, QPalette::WindowText,
+      QApplication::palette().color(QPalette::Disabled, QPalette::WindowText));
+  m_ui.dataGroup->setPalette(palette);
+  m_ui.deadTimeGroup->setPalette(palette);
+  m_ui.detectorGroupingGroup->setPalette(palette);
+  m_ui.periodsGroup->setPalette(palette);
+  m_ui.calculationGroup->setPalette(palette);
+}
+
+std::string ALCDataLoadingView::firstRun() const {
+  if (m_ui.firstRun->isValid()) {
+    return m_ui.firstRun->getFirstFilename().toStdString();
+  } else {
+    return "";
   }
-
-  void ALCDataLoadingView::initialize()
-  {
-    m_ui.setupUi(m_widget);
-    connect(m_ui.load, SIGNAL(clicked()), SIGNAL(loadRequested()));
-    connect(m_ui.firstRun, SIGNAL(fileFindingFinished()), SIGNAL(firstRunSelected()));
-    connect(m_ui.firstRun, SIGNAL(filesFoundChanged()), this,
-            SLOT(handleFirstFileChanged()));
-    connect(m_ui.help, SIGNAL(clicked()), this, SLOT(help()));
-    connect(m_ui.lastRunAuto, SIGNAL(stateChanged(int)), this, SLOT(checkBoxAutoChanged(int)));
-
-    m_ui.dataPlot->setCanvasBackground(Qt::white);
-    m_ui.dataPlot->setAxisFont(QwtPlot::xBottom, m_widget->font());
-    m_ui.dataPlot->setAxisFont(QwtPlot::yLeft, m_widget->font());
-
-    m_dataCurve->setStyle(QwtPlotCurve::NoCurve);
-    m_dataCurve->setSymbol(QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7,7)));
-    m_dataCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
-    m_dataCurve->attach(m_ui.dataPlot);
-
-    // The following lines disable the groups' titles when the
-    // group is disabled
-    QPalette palette;
-    palette.setColor(QPalette::Disabled, QPalette::WindowText,
-                     QApplication::palette().color(QPalette::Disabled,
-                                                   QPalette::WindowText));
-    m_ui.dataGroup->setPalette(palette);
-    m_ui.deadTimeGroup->setPalette(palette);
-    m_ui.detectorGroupingGroup->setPalette(palette);
-    m_ui.periodsGroup->setPalette(palette);
-    m_ui.calculationGroup->setPalette(palette);
-  }
-
-  std::string ALCDataLoadingView::firstRun() const
-  {
-    if (m_ui.firstRun->isValid())
-    {
-      return m_ui.firstRun->getFirstFilename().toStdString();
-    }
-    else
-    {
-      return "";
-    }
-  }
-
-  /**
-   * If the last run is valid, return the filename.
-   * If user entered "Auto", return this.
-   * Otherwise, return an empty string.
-   */
-  std::string ALCDataLoadingView::lastRun() const {
-    std::string toReturn("");
-
-    if (m_ui.lastRun->isValid()) {
-      toReturn = m_ui.lastRun->getFirstFilename().toStdString();
-      QString userInput = m_ui.lastRun->getText();
-      if (0 ==
-          userInput.compare(QString(autoString().c_str()),
-                            Qt::CaseInsensitive)) {
-        toReturn = autoString();
-      }
-    }
-    return toReturn;
-  }
-
-  std::string ALCDataLoadingView::log() const
-  {
-    return m_ui.log->currentText().toStdString();
-  }
-
-  std::string ALCDataLoadingView::function() const
-  {
-    return m_ui.function->currentText().toStdString();
-  }
-
-  std::string ALCDataLoadingView::calculationType() const
-  {
-    // XXX: "text" property of the buttons should be set correctly, as accepted by
-    //      PlotAsymmetryByLogValue
-    return m_ui.calculationType->checkedButton()->text().toStdString();
-  }
-
-  std::string ALCDataLoadingView::deadTimeType() const
-  {
-    std::string checkedButton = m_ui.deadTimeCorrType->checkedButton()->text().toStdString();
-    if ( checkedButton == "From Data File" ) {
-        return std::string("FromRunData");
-    } else if ( checkedButton == "From Custom File" ) {
-      return std::string("FromSpecifiedFile");
-    } else {
-      return checkedButton;
+}
+
+/**
+ * If the last run is valid, return the filename.
+ * If user entered "Auto", return this.
+ * Otherwise, return an empty string.
+ */
+std::string ALCDataLoadingView::lastRun() const {
+  std::string toReturn("");
+
+  if (m_ui.lastRun->isValid()) {
+    toReturn = m_ui.lastRun->getFirstFilename().toStdString();
+    QString userInput = m_ui.lastRun->getText();
+    if (0 ==
+        userInput.compare(QString(autoString().c_str()), Qt::CaseInsensitive)) {
+      toReturn = autoString();
     }
   }
-
-  std::string ALCDataLoadingView::deadTimeFile() const
-  {
-    if (deadTimeType()=="FromSpecifiedFile") {
-      return m_ui.deadTimeFile->getFirstFilename().toStdString();
-    } else {
-      return "";
-    }
-  }
-
-  std::string ALCDataLoadingView::detectorGroupingType() const
-  {
-    std::string checkedButton = m_ui.detectorGroupingType->checkedButton()->text().toStdString();
+  return toReturn;
+}
+
+std::string ALCDataLoadingView::log() const {
+  return m_ui.log->currentText().toStdString();
+}
+
+std::string ALCDataLoadingView::function() const {
+  return m_ui.function->currentText().toStdString();
+}
+
+std::string ALCDataLoadingView::calculationType() const {
+  // XXX: "text" property of the buttons should be set correctly, as accepted by
+  //      PlotAsymmetryByLogValue
+  return m_ui.calculationType->checkedButton()->text().toStdString();
+}
+
+std::string ALCDataLoadingView::deadTimeType() const {
+  std::string checkedButton =
+      m_ui.deadTimeCorrType->checkedButton()->text().toStdString();
+  if (checkedButton == "From Data File") {
+    return std::string("FromRunData");
+  } else if (checkedButton == "From Custom File") {
+    return std::string("FromSpecifiedFile");
+  } else {
     return checkedButton;
   }
+}
 
-  std::string ALCDataLoadingView::getForwardGrouping() const
-  {
-    return m_ui.forwardEdit->text().toStdString();
+std::string ALCDataLoadingView::deadTimeFile() const {
+  if (deadTimeType() == "FromSpecifiedFile") {
+    return m_ui.deadTimeFile->getFirstFilename().toStdString();
+  } else {
+    return "";
   }
+}
 
-  std::string ALCDataLoadingView::getBackwardGrouping() const
-  {
-    return m_ui.backwardEdit->text().toStdString();
-  }
+std::string ALCDataLoadingView::detectorGroupingType() const {
+  std::string checkedButton =
+      m_ui.detectorGroupingType->checkedButton()->text().toStdString();
+  return checkedButton;
+}
 
-  std::string ALCDataLoadingView::redPeriod() const
-  {
-    return m_ui.redPeriod->currentText().toStdString();
-  }
+std::string ALCDataLoadingView::getForwardGrouping() const {
+  return m_ui.forwardEdit->text().toStdString();
+}
 
-  std::string ALCDataLoadingView::greenPeriod() const
-  {
-    return m_ui.greenPeriod->currentText().toStdString();
-  }
+std::string ALCDataLoadingView::getBackwardGrouping() const {
+  return m_ui.backwardEdit->text().toStdString();
+}
 
-  bool ALCDataLoadingView::subtractIsChecked() const
-  {
-    return m_ui.subtractCheckbox->isChecked();
-  }
+std::string ALCDataLoadingView::redPeriod() const {
+  return m_ui.redPeriod->currentText().toStdString();
+}
 
-  boost::optional< std::pair<double,double> > ALCDataLoadingView::timeRange() const
-  {
-    auto range = std::make_pair(m_ui.minTime->value(), m_ui.maxTime->value());
-    return boost::make_optional(range);
-  }
+std::string ALCDataLoadingView::greenPeriod() const {
+  return m_ui.greenPeriod->currentText().toStdString();
+}
 
-  void ALCDataLoadingView::setDataCurve(const QwtData &data,
-                                        const std::vector<double> &errors) {
+bool ALCDataLoadingView::subtractIsChecked() const {
+  return m_ui.subtractCheckbox->isChecked();
+}
 
-    // Set data
-    m_dataCurve->setData(data);
+boost::optional<std::pair<double, double>>
+ALCDataLoadingView::timeRange() const {
+  auto range = std::make_pair(m_ui.minTime->value(), m_ui.maxTime->value());
+  return boost::make_optional(range);
+}
 
-    // Set errors
-    if (m_dataErrorCurve) {
-      m_dataErrorCurve->detach();
-      delete m_dataErrorCurve;
-    }
-    m_dataErrorCurve =
-        new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, errors);
-    m_dataErrorCurve->attach(m_ui.dataPlot);
-    m_dataErrorCurve->setItemAttribute(QwtPlotItem::AutoScale, true);
+void ALCDataLoadingView::setDataCurve(const QwtData &data,
+                                      const std::vector<double> &errors) {
 
-    m_ui.dataPlot->replot();
-  }
+  // Set data
+  m_dataCurve->setData(data);
 
-  void ALCDataLoadingView::displayError(const std::string& error)
-  {
-    QMessageBox::critical(m_widget, "Loading error", QString::fromStdString(error));
-  }
-
-  /**
-   * Set list of available log values
-   * @param logs :: [input] List of log values
-   */
-  void
-  ALCDataLoadingView::setAvailableLogs(const std::vector<std::string> &logs) {
-    setAvailableItems(m_ui.log, logs);
-  }
-
-  /**
-   * Set list of available periods in both boxes
-   * @param periods :: [input] List of periods
-   */
-  void ALCDataLoadingView::setAvailablePeriods(
-      const std::vector<std::string> &periods) {
-    setAvailableItems(m_ui.redPeriod, periods);
-    setAvailableItems(m_ui.greenPeriod, periods);
-
-    // If single period, disable "Subtract" checkbox and green period box
-    const bool multiPeriod = periods.size() > 1;
-    m_ui.subtractCheckbox->setEnabled(multiPeriod);
-    m_ui.greenPeriod->setEnabled(multiPeriod);
-  }
-
-  /**
-   * Sets available items in a combo box from given list.
-   * If the current value is in the new list, keep it.
-   * @param comboBox :: [input] Pointer to combo box to populate
-   * @param items :: [input] Vector of items to populate box with
-   */
-  void
-  ALCDataLoadingView::setAvailableItems(QComboBox *comboBox,
-                                        const std::vector<std::string> &items) {
-    if (!comboBox) {
-      throw std::invalid_argument(
-          "No combobox to set items in: this should never happen");
-    }
-
-    // Keep the current value
-    const auto previousValue = comboBox->currentText().toStdString();
-
-    // Clear previous list
-    comboBox->clear();
-
-    // If previous value is in the list, add it at the beginning
-    if (std::find(items.begin(), items.end(), previousValue) != items.end()) {
-      comboBox->addItem(QString::fromStdString(previousValue));
-    }
-
-    // Add new items
-    for (const auto item : items) {
-      if (item != previousValue) { // has already been added
-        comboBox->addItem(QString::fromStdString(item));
-      }
-    }
-  }
-
-  void ALCDataLoadingView::setTimeLimits(double tMin, double tMax)
-  {
-    // Set initial values
-    m_ui.minTime->setValue(tMin);
-    m_ui.maxTime->setValue(tMax);
-  }
-
-  void ALCDataLoadingView::setTimeRange(double tMin, double tMax)
-  {
-    // Set range for minTime
-    m_ui.minTime->setMinimum(tMin);
-    m_ui.minTime->setMaximum(tMax);
-    // Set range for maxTime
-    m_ui.maxTime->setMinimum(tMin);
-    m_ui.maxTime->setMaximum(tMax);
+  // Set errors
+  if (m_dataErrorCurve) {
+    m_dataErrorCurve->detach();
+    delete m_dataErrorCurve;
   }
-
-  void ALCDataLoadingView::help()
-  {
-    MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Muon_ALC"));
+  m_dataErrorCurve =
+      new MantidQt::MantidWidgets::ErrorCurve(m_dataCurve, errors);
+  m_dataErrorCurve->attach(m_ui.dataPlot);
+  m_dataErrorCurve->setItemAttribute(QwtPlotItem::AutoScale, true);
+
+  m_ui.dataPlot->replot();
+}
+
+void ALCDataLoadingView::displayError(const std::string &error) {
+  QMessageBox::critical(m_widget, "Loading error",
+                        QString::fromStdString(error));
+}
+
+/**
+ * Set list of available log values
+ * @param logs :: [input] List of log values
+ */
+void ALCDataLoadingView::setAvailableLogs(
+    const std::vector<std::string> &logs) {
+  setAvailableItems(m_ui.log, logs);
+}
+
+/**
+ * Set list of available periods in both boxes
+ * @param periods :: [input] List of periods
+ */
+void ALCDataLoadingView::setAvailablePeriods(
+    const std::vector<std::string> &periods) {
+  setAvailableItems(m_ui.redPeriod, periods);
+  setAvailableItems(m_ui.greenPeriod, periods);
+
+  // If single period, disable "Subtract" checkbox and green period box
+  const bool multiPeriod = periods.size() > 1;
+  m_ui.subtractCheckbox->setEnabled(multiPeriod);
+  m_ui.greenPeriod->setEnabled(multiPeriod);
+}
+
+/**
+ * Sets available items in a combo box from given list.
+ * If the current value is in the new list, keep it.
+ * @param comboBox :: [input] Pointer to combo box to populate
+ * @param items :: [input] Vector of items to populate box with
+ */
+void ALCDataLoadingView::setAvailableItems(
+    QComboBox *comboBox, const std::vector<std::string> &items) {
+  if (!comboBox) {
+    throw std::invalid_argument(
+        "No combobox to set items in: this should never happen");
   }
 
-  void ALCDataLoadingView::disableAll() {
+  // Keep the current value
+  const auto previousValue = comboBox->currentText().toStdString();
 
-    // Disable all the widgets in the view
-    m_ui.dataGroup->setEnabled(false);
-    m_ui.deadTimeGroup->setEnabled(false);
-    m_ui.detectorGroupingGroup->setEnabled(false);
-    m_ui.periodsGroup->setEnabled(false);
-    m_ui.calculationGroup->setEnabled(false);
-    m_ui.load->setEnabled(false);
+  // Clear previous list
+  comboBox->clear();
 
+  // If previous value is in the list, add it at the beginning
+  if (std::find(items.begin(), items.end(), previousValue) != items.end()) {
+    comboBox->addItem(QString::fromStdString(previousValue));
   }
 
-  void ALCDataLoadingView::enableAll() {
-
-    // Enable all the widgets in the view
-    m_ui.deadTimeGroup->setEnabled(true);
-    m_ui.dataGroup->setEnabled(true);
-    m_ui.detectorGroupingGroup->setEnabled(true);
-    m_ui.periodsGroup->setEnabled(true);
-    m_ui.calculationGroup->setEnabled(true);
-    m_ui.load->setEnabled(true);
-
-  }
-
-  /**
-   * Called when the check state of the "Auto" checkbox changes.
-   * Set text before setting read-only to validate the right text.
-   * @param state :: [input] Check state - member of Qt::CheckState enum
-   */
-  void ALCDataLoadingView::checkBoxAutoChanged(int state) {
-    // Tell the presenter about the change
-    emit lastRunAutoCheckedChanged(state);
-    if (state == Qt::Checked) {
-      // Auto mode on
-      m_ui.lastRun->setText(autoString().c_str());
-      m_ui.lastRun->setReadOnly(true);
-    } else {
-      // Replace "auto" with the currently loaded file
-      // The search is necessary to clear the validator
-      m_ui.lastRun->setFileTextWithSearch(m_currentAutoFile.c_str());
-      m_ui.lastRun->setReadOnly(false);
+  // Add new items
+  for (const auto item : items) {
+    if (item != previousValue) { // has already been added
+      comboBox->addItem(QString::fromStdString(item));
     }
   }
-
-  /**
-   * Called when the "first run" file has changed.
-   * Sets the "last run" box to look in the same directory.
-   */
-  void ALCDataLoadingView::handleFirstFileChanged() {
-    QString directory = m_ui.firstRun->getLastDirectory();
-    if (!directory.isEmpty()) {
-      m_ui.lastRun->setLastDirectory(directory);
-    }
+}
+
+void ALCDataLoadingView::setTimeLimits(double tMin, double tMax) {
+  // Set initial values
+  m_ui.minTime->setValue(tMin);
+  m_ui.maxTime->setValue(tMax);
+}
+
+void ALCDataLoadingView::setTimeRange(double tMin, double tMax) {
+  // Set range for minTime
+  m_ui.minTime->setMinimum(tMin);
+  m_ui.minTime->setMaximum(tMax);
+  // Set range for maxTime
+  m_ui.maxTime->setMinimum(tMin);
+  m_ui.maxTime->setMaximum(tMax);
+}
+
+void ALCDataLoadingView::help() {
+  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Muon_ALC"));
+}
+
+void ALCDataLoadingView::disableAll() {
+
+  // Disable all the widgets in the view
+  m_ui.dataGroup->setEnabled(false);
+  m_ui.deadTimeGroup->setEnabled(false);
+  m_ui.detectorGroupingGroup->setEnabled(false);
+  m_ui.periodsGroup->setEnabled(false);
+  m_ui.calculationGroup->setEnabled(false);
+  m_ui.load->setEnabled(false);
+}
+
+void ALCDataLoadingView::enableAll() {
+
+  // Enable all the widgets in the view
+  m_ui.deadTimeGroup->setEnabled(true);
+  m_ui.dataGroup->setEnabled(true);
+  m_ui.detectorGroupingGroup->setEnabled(true);
+  m_ui.periodsGroup->setEnabled(true);
+  m_ui.calculationGroup->setEnabled(true);
+  m_ui.load->setEnabled(true);
+}
+
+/**
+ * Called when the check state of the "Auto" checkbox changes.
+ * Set text before setting read-only to validate the right text.
+ * @param state :: [input] Check state - member of Qt::CheckState enum
+ */
+void ALCDataLoadingView::checkBoxAutoChanged(int state) {
+  // Tell the presenter about the change
+  emit lastRunAutoCheckedChanged(state);
+  if (state == Qt::Checked) {
+    // Auto mode on
+    m_ui.lastRun->setText(autoString().c_str());
+    m_ui.lastRun->setReadOnly(true);
+  } else {
+    // Replace "auto" with the currently loaded file
+    // The search is necessary to clear the validator
+    m_ui.lastRun->setFileTextWithSearch(m_currentAutoFile.c_str());
+    m_ui.lastRun->setReadOnly(false);
+  }
+}
+
+/**
+ * Called when the "first run" file has changed.
+ * Sets the "last run" box to look in the same directory.
+ */
+void ALCDataLoadingView::handleFirstFileChanged() {
+  QString directory = m_ui.firstRun->getLastDirectory();
+  if (!directory.isEmpty()) {
+    m_ui.lastRun->setLastDirectory(directory);
   }
+}
 
-  } // namespace CustomInterfaces
-  } // namespace MantidQt
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCHelper.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCHelper.cpp
index e6a50a20f1d84421c93186787290be77734b2729..461af9619003a21b0d3a3831116fe7f97c7073c9 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCHelper.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCHelper.cpp
@@ -7,115 +7,115 @@
 
 #include "QMessageBox"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace ALCHelper
-{
-  /**
-   * Creates QwtData using X and Y values from the workspace spectra.
-   * @param ws :: Workspace with X and Y values to use
-   * @param wsIndex :: Workspace index to use
-   * @return Pointer to created QwtData
-   */
-  boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex)
-  {
-    const double* x = &ws->readX(wsIndex)[0];
-    const double* y = &ws->readY(wsIndex)[0];
-    size_t size = ws->blocksize();
-
-    return boost::make_shared<QwtArrayData>(x,y,size);
-  }
-
-  /**
-  * Creates a vector of QwtData using X and Y values from every single
-  * workspace index in ws, written for only Engg Diffraction fitting tab
-  * @param ws :: Workspace with X and Y values to use
-  * @return Pointer to created Vector QwtData
-  */
-  std::vector<boost::shared_ptr<QwtData>>
-  curveDataFromWs(MatrixWorkspace_const_sptr ws) {
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace ALCHelper {
+/**
+ * Creates QwtData using X and Y values from the workspace spectra.
+ * @param ws :: Workspace with X and Y values to use
+ * @param wsIndex :: Workspace index to use
+ * @return Pointer to created QwtData
+ */
+boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws,
+                                           size_t wsIndex) {
+  const double *x = &ws->readX(wsIndex)[0];
+  const double *y = &ws->readY(wsIndex)[0];
+  size_t size = ws->blocksize();
+
+  return boost::make_shared<QwtArrayData>(x, y, size);
+}
 
-    std::vector<boost::shared_ptr<QwtData>> dataVector;
-    auto histograms = ws->getNumberHistograms();
+/**
+* Creates a vector of QwtData using X and Y values from every single
+* workspace index in ws, written for only Engg Diffraction fitting tab
+* @param ws :: Workspace with X and Y values to use
+* @return Pointer to created Vector QwtData
+*/
+std::vector<boost::shared_ptr<QwtData>>
+curveDataFromWs(MatrixWorkspace_const_sptr ws) {
 
-    for (size_t wsIndex = 0; wsIndex < histograms; wsIndex++) {
+  std::vector<boost::shared_ptr<QwtData>> dataVector;
+  auto histograms = ws->getNumberHistograms();
 
-      const double *x = &ws->readX(wsIndex)[0];
-      const double *y = &ws->readY(wsIndex)[0];
-      size_t size = ws->blocksize();
+  for (size_t wsIndex = 0; wsIndex < histograms; wsIndex++) {
 
-      auto wsIdxData = boost::make_shared<QwtArrayData>(x, y, size);
+    const double *x = &ws->readX(wsIndex)[0];
+    const double *y = &ws->readY(wsIndex)[0];
+    size_t size = ws->blocksize();
 
-      dataVector.push_back(wsIdxData);
-    }
-    return dataVector;
-  }
+    auto wsIdxData = boost::make_shared<QwtArrayData>(x, y, size);
 
-  /**
-   * Creates vector of errors using E values from the workspace spectra.
-   * @param ws :: Workspace with E values to use
-   * @param wsIndex :: Workspace index to use
-   * @return Vector of errors
-   */
-  std::vector<double> curveErrorsFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex)
-  {
-    return ws->readE(wsIndex);
+    dataVector.push_back(wsIdxData);
   }
+  return dataVector;
+}
 
-  /**
-   * Creates QwtData with Y values produced by the function for specified X values.
-   * @param func :: Function to use
-   * @param xValues :: X values which we want Y values for. QwtData will have those as well.
-   * @return Pointer to create QwtData
-   */
-  boost::shared_ptr<QwtData> curveDataFromFunction(IFunction_const_sptr func,
-                                                   const std::vector<double>& xValues)
-  {
-    MatrixWorkspace_sptr ws = createWsFromFunction(func, xValues);
-    return curveDataFromWs(ws, 0);
-  }
+/**
+ * Creates vector of errors using E values from the workspace spectra.
+ * @param ws :: Workspace with E values to use
+ * @param wsIndex :: Workspace index to use
+ * @return Vector of errors
+ */
+std::vector<double> curveErrorsFromWs(MatrixWorkspace_const_sptr ws,
+                                      size_t wsIndex) {
+  return ws->readE(wsIndex);
+}
 
-  /**
-   * Creates a single-spectrum workspace filled with function values for given X values
-   * @param func :: Function to calculate values
-   * @param xValues :: X values to use
-   * @return Single-spectrum workspace with calculated function values
-   */
-  MatrixWorkspace_sptr createWsFromFunction(IFunction_const_sptr func,
-                                            const std::vector<double>& xValues)
-  {
-    auto inputWs = boost::dynamic_pointer_cast<MatrixWorkspace>(
-          WorkspaceFactory::Instance().create("Workspace2D", 1, xValues.size(), xValues.size()));
-    inputWs->dataX(0) = xValues;
-
-    IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
-    fit->setChild(true); // Don't want workspace in the ADS
-    fit->setProperty("Function", func->asString());
-    fit->setProperty("InputWorkspace", inputWs);
-    fit->setProperty("MaxIterations", 0); // Don't want to fit, just calculate output workspace
-    fit->setProperty("CreateOutput", true);
-    fit->execute();
-
-    MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace");
-
-    IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum");
-    extract->setChild(true); // Don't want workspace in the ADS
-    extract->setProperty("InputWorkspace", fitOutput);
-    extract->setProperty("WorkspaceIndex", 1); // "Calc"
-    extract->setPropertyValue("OutputWorkspace", "__NotUsed");
-    extract->execute();
-
-    return extract->getProperty("OutputWorkspace");
-  }
+/**
+ * Creates QwtData with Y values produced by the function for specified X
+ * values.
+ * @param func :: Function to use
+ * @param xValues :: X values which we want Y values for. QwtData will have
+ * those as well.
+ * @return Pointer to create QwtData
+ */
+boost::shared_ptr<QwtData>
+curveDataFromFunction(IFunction_const_sptr func,
+                      const std::vector<double> &xValues) {
+  MatrixWorkspace_sptr ws = createWsFromFunction(func, xValues);
+  return curveDataFromWs(ws, 0);
+}
 
-  boost::shared_ptr<QwtData> emptyCurveData()
-  {
-    QwtArray<double> x,y; // Empty arrays -> empty data
-    return boost::make_shared<QwtArrayData>(x,y);
-  }
+/**
+ * Creates a single-spectrum workspace filled with function values for given X
+ * values
+ * @param func :: Function to calculate values
+ * @param xValues :: X values to use
+ * @return Single-spectrum workspace with calculated function values
+ */
+MatrixWorkspace_sptr createWsFromFunction(IFunction_const_sptr func,
+                                          const std::vector<double> &xValues) {
+  auto inputWs = boost::dynamic_pointer_cast<MatrixWorkspace>(
+      WorkspaceFactory::Instance().create("Workspace2D", 1, xValues.size(),
+                                          xValues.size()));
+  inputWs->dataX(0) = xValues;
+
+  IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
+  fit->setChild(true); // Don't want workspace in the ADS
+  fit->setProperty("Function", func->asString());
+  fit->setProperty("InputWorkspace", inputWs);
+  fit->setProperty("MaxIterations",
+                   0); // Don't want to fit, just calculate output workspace
+  fit->setProperty("CreateOutput", true);
+  fit->execute();
+
+  MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace");
+
+  IAlgorithm_sptr extract =
+      AlgorithmManager::Instance().create("ExtractSingleSpectrum");
+  extract->setChild(true); // Don't want workspace in the ADS
+  extract->setProperty("InputWorkspace", fitOutput);
+  extract->setProperty("WorkspaceIndex", 1); // "Calc"
+  extract->setPropertyValue("OutputWorkspace", "__NotUsed");
+  extract->execute();
+
+  return extract->getProperty("OutputWorkspace");
+}
 
+boost::shared_ptr<QwtData> emptyCurveData() {
+  QwtArray<double> x, y; // Empty arrays -> empty data
+  return boost::make_shared<QwtArrayData>(x, y);
+}
 }
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCInterface.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCInterface.cpp
index f70fe204e98fc0c6d7dd30b80c2caff417715d33..f4dd9dc49a299a92f1aa6e5568567a9469b6419c 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCInterface.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCInterface.cpp
@@ -17,302 +17,302 @@
 #include "MantidAPI/WorkspaceGroup.h"
 #include "MantidAPI/ITableWorkspace.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  DECLARE_SUBWINDOW(ALCInterface)
-
-  const QStringList ALCInterface::STEP_NAMES =
-      QStringList() << "Data loading" << "Baseline modelling" << "Peak fitting";
-
-  // %1 - current step no., %2 - total no. of steps, %3 - current step label
-  const QString ALCInterface::LABEL_FORMAT = "Step %1/%2 - %3";
-
-  ALCInterface::ALCInterface(QWidget* parent)
-    : UserSubWindow(parent), m_ui(),
-      m_baselineModellingView(NULL), m_peakFittingView(NULL),
-      m_dataLoading(NULL), m_baselineModelling(NULL), m_peakFitting(NULL),
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(ALCInterface)
+
+const QStringList ALCInterface::STEP_NAMES = QStringList()
+                                             << "Data loading"
+                                             << "Baseline modelling"
+                                             << "Peak fitting";
+
+// %1 - current step no., %2 - total no. of steps, %3 - current step label
+const QString ALCInterface::LABEL_FORMAT = "Step %1/%2 - %3";
+
+ALCInterface::ALCInterface(QWidget *parent)
+    : UserSubWindow(parent), m_ui(), m_baselineModellingView(NULL),
+      m_peakFittingView(NULL), m_dataLoading(NULL), m_baselineModelling(NULL),
+      m_peakFitting(NULL),
       m_baselineModellingModel(new ALCBaselineModellingModel()),
-      m_peakFittingModel(new ALCPeakFittingModel())
-  {}
+      m_peakFittingModel(new ALCPeakFittingModel()) {}
 
-  void ALCInterface::initLayout()
-  {
-    m_ui.setupUi(this);
+void ALCInterface::initLayout() {
+  m_ui.setupUi(this);
 
-    connect(m_ui.nextStep, SIGNAL(clicked()), SLOT(nextStep()));
-    connect(m_ui.previousStep, SIGNAL(clicked()), SLOT(previousStep()));
-    connect(m_ui.exportResults, SIGNAL(clicked()), SLOT(exportResults()));
-    connect(m_ui.importResults, SIGNAL(clicked()), SLOT(importResults()));
+  connect(m_ui.nextStep, SIGNAL(clicked()), SLOT(nextStep()));
+  connect(m_ui.previousStep, SIGNAL(clicked()), SLOT(previousStep()));
+  connect(m_ui.exportResults, SIGNAL(clicked()), SLOT(exportResults()));
+  connect(m_ui.importResults, SIGNAL(clicked()), SLOT(importResults()));
 
-    auto dataLoadingView = new ALCDataLoadingView(m_ui.dataLoadingView);
-    m_dataLoading = new ALCDataLoadingPresenter(dataLoadingView);
-    m_dataLoading->initialize();
+  auto dataLoadingView = new ALCDataLoadingView(m_ui.dataLoadingView);
+  m_dataLoading = new ALCDataLoadingPresenter(dataLoadingView);
+  m_dataLoading->initialize();
 
-    m_baselineModellingView = new ALCBaselineModellingView(m_ui.baselineModellingView);
-    m_baselineModelling = new ALCBaselineModellingPresenter(m_baselineModellingView, m_baselineModellingModel);
-    m_baselineModelling->initialize();
+  m_baselineModellingView =
+      new ALCBaselineModellingView(m_ui.baselineModellingView);
+  m_baselineModelling = new ALCBaselineModellingPresenter(
+      m_baselineModellingView, m_baselineModellingModel);
+  m_baselineModelling->initialize();
 
-    m_peakFittingView = new ALCPeakFittingView(m_ui.peakFittingView);
-    m_peakFitting = new ALCPeakFittingPresenter(m_peakFittingView, m_peakFittingModel);
-    m_peakFitting->initialize();
+  m_peakFittingView = new ALCPeakFittingView(m_ui.peakFittingView);
+  m_peakFitting =
+      new ALCPeakFittingPresenter(m_peakFittingView, m_peakFittingModel);
+  m_peakFitting->initialize();
 
-    connect(m_dataLoading, SIGNAL(dataChanged()), SLOT(updateBaselineData()));
-    connect(m_baselineModellingModel, SIGNAL(correctedDataChanged()), SLOT(updatePeakData()));
+  connect(m_dataLoading, SIGNAL(dataChanged()), SLOT(updateBaselineData()));
+  connect(m_baselineModellingModel, SIGNAL(correctedDataChanged()),
+          SLOT(updatePeakData()));
 
-    assert(m_ui.stepView->count() == STEP_NAMES.count()); // Should have names for all steps
+  assert(m_ui.stepView->count() ==
+         STEP_NAMES.count()); // Should have names for all steps
 
-    switchStep(0); // We always start from the first step
-  }
+  switchStep(0); // We always start from the first step
+}
 
-  void ALCInterface::updateBaselineData() {
+void ALCInterface::updateBaselineData() {
 
-    // Make sure we do have some data
-    if (m_dataLoading->loadedData()) {
+  // Make sure we do have some data
+  if (m_dataLoading->loadedData()) {
 
-      // Send the data to BaselineModelling
-      m_baselineModellingModel->setData(m_dataLoading->loadedData());
+    // Send the data to BaselineModelling
+    m_baselineModellingModel->setData(m_dataLoading->loadedData());
 
-      // If we have a fitting function and a fitting range
-      // we can update the baseline model
-      if ((!m_baselineModellingView->function().isEmpty()) &&
-          (m_baselineModellingView->noOfSectionRows() > 0)) {
+    // If we have a fitting function and a fitting range
+    // we can update the baseline model
+    if ((!m_baselineModellingView->function().isEmpty()) &&
+        (m_baselineModellingView->noOfSectionRows() > 0)) {
 
-            // Fit the data
-            m_baselineModellingView->emitFitRequested();
-      }
+      // Fit the data
+      m_baselineModellingView->emitFitRequested();
     }
   }
+}
 
-  void ALCInterface::updatePeakData() {
+void ALCInterface::updatePeakData() {
 
-    // Make sure we do have some data
-    if (m_baselineModellingModel->correctedData()) {
+  // Make sure we do have some data
+  if (m_baselineModellingModel->correctedData()) {
 
-      // Send the data to PeakFitting
-      m_peakFittingModel->setData(m_baselineModellingModel->correctedData());
+    // Send the data to PeakFitting
+    m_peakFittingModel->setData(m_baselineModellingModel->correctedData());
 
-      // If we have a fitting function
-      if (m_peakFittingView->function("")) {
+    // If we have a fitting function
+    if (m_peakFittingView->function("")) {
 
-        // Fit the data
-        m_peakFittingView->emitFitRequested();
-      }
+      // Fit the data
+      m_peakFittingView->emitFitRequested();
     }
   }
+}
 
-  void ALCInterface::nextStep()
-  {
-    int next = m_ui.stepView->currentIndex() + 1;
+void ALCInterface::nextStep() {
+  int next = m_ui.stepView->currentIndex() + 1;
 
-    switchStep(next);
-  }
+  switchStep(next);
+}
 
-  void ALCInterface::previousStep()
-  {
-    int previous = m_ui.stepView->currentIndex() - 1;
+void ALCInterface::previousStep() {
+  int previous = m_ui.stepView->currentIndex() - 1;
 
-    switchStep(previous);
-  }
+  switchStep(previous);
+}
 
-  void ALCInterface::switchStep(int newStepIndex)
-  {
-    // Should be disallowed by disabling buttons
-    assert(newStepIndex >= 0);
-    assert(newStepIndex < m_ui.stepView->count());
+void ALCInterface::switchStep(int newStepIndex) {
+  // Should be disallowed by disabling buttons
+  assert(newStepIndex >= 0);
+  assert(newStepIndex < m_ui.stepView->count());
 
-    m_ui.label->setText(LABEL_FORMAT.arg(newStepIndex + 1).arg(STEP_NAMES.count()).arg(STEP_NAMES[newStepIndex]));
+  m_ui.label->setText(LABEL_FORMAT.arg(newStepIndex + 1)
+                          .arg(STEP_NAMES.count())
+                          .arg(STEP_NAMES[newStepIndex]));
 
-    int nextStepIndex = newStepIndex + 1;
-    int prevStepIndex = newStepIndex - 1;
+  int nextStepIndex = newStepIndex + 1;
+  int prevStepIndex = newStepIndex - 1;
 
-    bool hasNextStep = (nextStepIndex < m_ui.stepView->count());
-    bool hasPrevStep = (prevStepIndex >= 0);
+  bool hasNextStep = (nextStepIndex < m_ui.stepView->count());
+  bool hasPrevStep = (prevStepIndex >= 0);
 
-    m_ui.previousStep->setVisible(hasPrevStep);
+  m_ui.previousStep->setVisible(hasPrevStep);
 
-    // On last step - hide next step button, but show "Export results..."
-    m_ui.nextStep->setVisible(hasNextStep);
+  // On last step - hide next step button, but show "Export results..."
+  m_ui.nextStep->setVisible(hasNextStep);
 
-    if (hasPrevStep)
-    {
-      m_ui.previousStep->setText("< " + STEP_NAMES[prevStepIndex]);
-    }
-
-    if (hasNextStep)
-    {
-      m_ui.nextStep->setText(STEP_NAMES[nextStepIndex] + " >");
-    }
-
-    m_ui.stepView->setCurrentIndex(newStepIndex);
+  if (hasPrevStep) {
+    m_ui.previousStep->setText("< " + STEP_NAMES[prevStepIndex]);
   }
 
-  void ALCInterface::exportResults()
-  {
+  if (hasNextStep) {
+    m_ui.nextStep->setText(STEP_NAMES[nextStepIndex] + " >");
+  }
 
-    bool ok;
-    QString label = QInputDialog::getText(this, "Results label", "Label to assign to the results: ",
-                                         QLineEdit::Normal, "ALCResults", &ok);
+  m_ui.stepView->setCurrentIndex(newStepIndex);
+}
 
-    if (!ok) // Cancelled
-    {
-      return;
-    }
+void ALCInterface::exportResults() {
 
-    std::string groupName = label.toStdString();
+  bool ok;
+  QString label = QInputDialog::getText(this, "Results label",
+                                        "Label to assign to the results: ",
+                                        QLineEdit::Normal, "ALCResults", &ok);
 
-    using namespace Mantid::API;
+  if (!ok) // Cancelled
+  {
+    return;
+  }
 
-    std::map<std::string, Workspace_sptr> results;
+  std::string groupName = label.toStdString();
 
-    results["Loaded_Data"] = m_dataLoading->exportWorkspace();
+  using namespace Mantid::API;
 
-    results["Baseline_Workspace"] = m_baselineModellingModel->exportWorkspace();
-    results["Baseline_Sections"] = m_baselineModellingModel->exportSections();
-    results["Baseline_Model"] = m_baselineModellingModel->exportModel();
+  std::map<std::string, Workspace_sptr> results;
 
-    results["Peaks_Workspace"] = m_peakFittingModel->exportWorkspace();
-    results["Peaks_FitResults"] = m_peakFittingModel->exportFittedPeaks();
+  results["Loaded_Data"] = m_dataLoading->exportWorkspace();
 
-    // Check if any of the above is not empty
-    bool nothingToExport = true;
-    for (auto it=results.begin(); it!=results.end(); ++it) {
-    
-      if ( it->second ) {
-        nothingToExport = false;
-        break;
-      }
-    }
+  results["Baseline_Workspace"] = m_baselineModellingModel->exportWorkspace();
+  results["Baseline_Sections"] = m_baselineModellingModel->exportSections();
+  results["Baseline_Model"] = m_baselineModellingModel->exportModel();
 
-    // There is something to export
-    if (!nothingToExport) {
+  results["Peaks_Workspace"] = m_peakFittingModel->exportWorkspace();
+  results["Peaks_FitResults"] = m_peakFittingModel->exportFittedPeaks();
 
-      // Add output group to the ADS
-      AnalysisDataService::Instance().addOrReplace(groupName, boost::make_shared<WorkspaceGroup>());
+  // Check if any of the above is not empty
+  bool nothingToExport = true;
+  for (auto it = results.begin(); it != results.end(); ++it) {
 
-      for(auto it = results.begin(); it != results.end(); ++it)
-      {
-        if ( it->second ) {
-          std::string wsName = groupName + "_" + it->first;
-          AnalysisDataService::Instance().addOrReplace(wsName, it->second);
-          AnalysisDataService::Instance().addToGroup(groupName, wsName);
-        }
-      }
-    } else {
-      // Nothing to export, show error message
-      QMessageBox::critical(this, "Error", "Nothing to export");
+    if (it->second) {
+      nothingToExport = false;
+      break;
     }
   }
 
-  void ALCInterface::importResults() {
+  // There is something to export
+  if (!nothingToExport) {
 
-    bool ok;
-    QString label = QInputDialog::getText(this, "Results label", "Label to assign to the results: ",
-      QLineEdit::Normal, "ALCResults", &ok);
+    // Add output group to the ADS
+    AnalysisDataService::Instance().addOrReplace(
+        groupName, boost::make_shared<WorkspaceGroup>());
 
-    if (!ok) // Cancelled
-    {
-      return;
+    for (auto it = results.begin(); it != results.end(); ++it) {
+      if (it->second) {
+        std::string wsName = groupName + "_" + it->first;
+        AnalysisDataService::Instance().addOrReplace(wsName, it->second);
+        AnalysisDataService::Instance().addToGroup(groupName, wsName);
+      }
     }
+  } else {
+    // Nothing to export, show error message
+    QMessageBox::critical(this, "Error", "Nothing to export");
+  }
+}
 
-    std::string groupName = label.toStdString();
+void ALCInterface::importResults() {
 
-    using namespace Mantid::API;
+  bool ok;
+  QString label = QInputDialog::getText(this, "Results label",
+                                        "Label to assign to the results: ",
+                                        QLineEdit::Normal, "ALCResults", &ok);
 
-    int currentStep = m_ui.stepView->currentIndex();
+  if (!ok) // Cancelled
+  {
+    return;
+  }
 
-    if (currentStep == 0) {
-      // DataLoading step
+  std::string groupName = label.toStdString();
 
-      std::string wsData = groupName + "_Loaded_Data";
+  using namespace Mantid::API;
 
-      if(AnalysisDataService::Instance().doesExist(wsData)) {
+  int currentStep = m_ui.stepView->currentIndex();
 
-        MatrixWorkspace_sptr ws =
-            AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
+  if (currentStep == 0) {
+    // DataLoading step
 
-        // Check that ws contains one spectrum only
-        if (ws->getNumberHistograms() != 1) {
-          QMessageBox::critical(this, "Error",
-                                "Workspace " + QString::fromStdString(wsData) +
-                                    " must contain one spectrum only");
-          return;
-        }
+    std::string wsData = groupName + "_Loaded_Data";
 
-        // Set the retrieved data
-        m_dataLoading->setData(ws);
+    if (AnalysisDataService::Instance().doesExist(wsData)) {
 
-      } else {
-        // Error message
+      MatrixWorkspace_sptr ws =
+          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
+
+      // Check that ws contains one spectrum only
+      if (ws->getNumberHistograms() != 1) {
         QMessageBox::critical(this, "Error",
                               "Workspace " + QString::fromStdString(wsData) +
-                                  " was not found");
+                                  " must contain one spectrum only");
+        return;
       }
 
+      // Set the retrieved data
+      m_dataLoading->setData(ws);
 
-    } else if (currentStep == 1) {
-      // BaselineModelling step
-
-      std::string wsData = groupName + "_Baseline_Workspace";
+    } else {
+      // Error message
+      QMessageBox::critical(this, "Error", "Workspace " +
+                                               QString::fromStdString(wsData) +
+                                               " was not found");
+    }
 
-      if (AnalysisDataService::Instance().doesExist(wsData)) {
+  } else if (currentStep == 1) {
+    // BaselineModelling step
 
-        MatrixWorkspace_sptr dataWs =
-            AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
+    std::string wsData = groupName + "_Baseline_Workspace";
 
-        // Check that ws contains three spectra
-        if (dataWs->getNumberHistograms() != 3) {
-          QMessageBox::critical(this, "Error",
-                                "Workspace " + QString::fromStdString(wsData) +
-                                    " must contain three spectra");
-          return;
-        }
+    if (AnalysisDataService::Instance().doesExist(wsData)) {
 
-        // Set the retrieved workspace
-        m_baselineModellingModel->setData(dataWs);
-        m_baselineModellingModel->setCorrectedData(dataWs);
+      MatrixWorkspace_sptr dataWs =
+          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
 
-      } else {
-        // Error message
+      // Check that ws contains three spectra
+      if (dataWs->getNumberHistograms() != 3) {
         QMessageBox::critical(this, "Error",
                               "Workspace " + QString::fromStdString(wsData) +
-                                  " was not found");
+                                  " must contain three spectra");
+        return;
       }
 
-    } else if (currentStep == 2) {
-      // PeakFitting step
+      // Set the retrieved workspace
+      m_baselineModellingModel->setData(dataWs);
+      m_baselineModellingModel->setCorrectedData(dataWs);
 
-      std::string wsData = groupName + "_Peaks_Workspace";
+    } else {
+      // Error message
+      QMessageBox::critical(this, "Error", "Workspace " +
+                                               QString::fromStdString(wsData) +
+                                               " was not found");
+    }
 
-      if (AnalysisDataService::Instance().doesExist(wsData)) {
+  } else if (currentStep == 2) {
+    // PeakFitting step
 
-        MatrixWorkspace_sptr data =
-            AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
+    std::string wsData = groupName + "_Peaks_Workspace";
 
-        // Check that ws contains one spectrum only
-        if (data->getNumberHistograms() < 3) {
-          QMessageBox::critical(this, "Error",
-                                "Workspace " + QString::fromStdString(wsData) +
-                                    " must contain at least three spectra");
-          return;
-        }
+    if (AnalysisDataService::Instance().doesExist(wsData)) {
 
-        // Set the retrieved data
-        m_peakFittingModel->setData(data);
+      MatrixWorkspace_sptr data =
+          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsData);
 
-      } else {
-        // Error message
+      // Check that ws contains one spectrum only
+      if (data->getNumberHistograms() < 3) {
         QMessageBox::critical(this, "Error",
                               "Workspace " + QString::fromStdString(wsData) +
-                                  " was not found");
+                                  " must contain at least three spectra");
+        return;
       }
 
+      // Set the retrieved data
+      m_peakFittingModel->setData(data);
+
     } else {
-      // Exception: we can never get here
-      throw std::runtime_error("Fatal error in ALC interface");
+      // Error message
+      QMessageBox::critical(this, "Error", "Workspace " +
+                                               QString::fromStdString(wsData) +
+                                               " was not found");
     }
+
+  } else {
+    // Exception: we can never get here
+    throw std::runtime_error("Fatal error in ALC interface");
   }
+}
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
index ea3ef494f3c754ee31541e2dfee49323c7408f9a..368a640bd2b6236a46ca1a008c24fc1e775ee767 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingModel.cpp
@@ -12,71 +12,64 @@
 #include <Poco/ActiveResult.h>
 #include <QApplication>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  void ALCPeakFittingModel::setData(MatrixWorkspace_const_sptr newData)
-  {
-    m_data = newData;
-    emit dataChanged();
-  }
+namespace MantidQt {
+namespace CustomInterfaces {
+void ALCPeakFittingModel::setData(MatrixWorkspace_const_sptr newData) {
+  m_data = newData;
+  emit dataChanged();
+}
+
+MatrixWorkspace_sptr ALCPeakFittingModel::exportWorkspace() {
+  if (m_data && m_data->getNumberHistograms() > 2) {
 
-  MatrixWorkspace_sptr ALCPeakFittingModel::exportWorkspace()
-  {
-    if ( m_data && m_data->getNumberHistograms() > 2 ) {
+    return boost::const_pointer_cast<MatrixWorkspace>(m_data);
 
-      return boost::const_pointer_cast<MatrixWorkspace>(m_data);
+  } else {
 
-    } else {
-    
-      return MatrixWorkspace_sptr();
-    }
+    return MatrixWorkspace_sptr();
   }
+}
 
-  ITableWorkspace_sptr ALCPeakFittingModel::exportFittedPeaks()
-  {
-    if ( m_parameterTable ) {
+ITableWorkspace_sptr ALCPeakFittingModel::exportFittedPeaks() {
+  if (m_parameterTable) {
 
-      return m_parameterTable;
+    return m_parameterTable;
 
-    } else {
-    
-      return ITableWorkspace_sptr();
-    }
-  }
+  } else {
 
-  void ALCPeakFittingModel::setFittedPeaks(IFunction_const_sptr fittedPeaks)
-  {
-    m_fittedPeaks = fittedPeaks;
-    emit fittedPeaksChanged();
+    return ITableWorkspace_sptr();
   }
-
-  void ALCPeakFittingModel::fitPeaks(IFunction_const_sptr peaks)
-  {
-    IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
-    fit->setChild(true);
-    fit->setProperty("Function", peaks->asString());
-    fit->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data));
-    fit->setProperty("CreateOutput", true);
-    fit->setProperty("OutputCompositeMembers", true);
-
-    // Execute async so we can show progress bar
-    Poco::ActiveResult<bool> result(fit->executeAsync());
-    while (!result.available()) {
-      QCoreApplication::processEvents();
-    }
-    if (!result.error().empty()) {
-      QString msg =
-          "Fit algorithm failed.\n\n" + QString(result.error().c_str()) + "\n";
-      emit errorInModel(msg);
-    }
-
-    m_data = fit->getProperty("OutputWorkspace");
-    m_parameterTable = fit->getProperty("OutputParameters");
-    setFittedPeaks(static_cast<IFunction_sptr>(fit->getProperty("Function")));
+}
+
+void ALCPeakFittingModel::setFittedPeaks(IFunction_const_sptr fittedPeaks) {
+  m_fittedPeaks = fittedPeaks;
+  emit fittedPeaksChanged();
+}
+
+void ALCPeakFittingModel::fitPeaks(IFunction_const_sptr peaks) {
+  IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit");
+  fit->setChild(true);
+  fit->setProperty("Function", peaks->asString());
+  fit->setProperty("InputWorkspace",
+                   boost::const_pointer_cast<MatrixWorkspace>(m_data));
+  fit->setProperty("CreateOutput", true);
+  fit->setProperty("OutputCompositeMembers", true);
+
+  // Execute async so we can show progress bar
+  Poco::ActiveResult<bool> result(fit->executeAsync());
+  while (!result.available()) {
+    QCoreApplication::processEvents();
   }
+  if (!result.error().empty()) {
+    QString msg =
+        "Fit algorithm failed.\n\n" + QString(result.error().c_str()) + "\n";
+    emit errorInModel(msg);
+  }
+
+  m_data = fit->getProperty("OutputWorkspace");
+  m_parameterTable = fit->getProperty("OutputParameters");
+  setFittedPeaks(static_cast<IFunction_sptr>(fit->getProperty("Function")));
+}
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
-
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingPresenter.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingPresenter.cpp
index 6e2782d8fe335ee92c7702de824688494fb96769..c153ffc5bb48d70b53067816244af221ded56e39 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingPresenter.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingPresenter.cpp
@@ -6,10 +6,8 @@
 
 #include "MantidQtCustomInterfaces/Muon/ALCHelper.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 ALCPeakFittingPresenter::ALCPeakFittingPresenter(IALCPeakFittingView *view,
                                                  IALCPeakFittingModel *model)
@@ -32,138 +30,135 @@ void ALCPeakFittingPresenter::initialize() {
   connect(m_view, SIGNAL(plotGuessClicked()), SLOT(onPlotGuessClicked()));
   connect(m_model, SIGNAL(errorInModel(const QString &)), m_view,
           SLOT(displayError(const QString &)));
+}
+
+void ALCPeakFittingPresenter::fit() {
+  IFunction_const_sptr func = m_view->function("");
+  auto dataWS = m_model->data();
+  if (func && dataWS) {
+    removePlots();
+    m_model->fitPeaks(func);
+  } else {
+    m_view->displayError("Couldn't fit with empty function/data");
   }
+}
 
-  void ALCPeakFittingPresenter::fit() {
-    IFunction_const_sptr func = m_view->function("");
-    auto dataWS = m_model->data();
-    if (func && dataWS) {
-      removePlots();
-      m_model->fitPeaks(func);
-    } else {
-      m_view->displayError("Couldn't fit with empty function/data");
-    }
-  }
-
-  void ALCPeakFittingPresenter::onCurrentFunctionChanged()
+void ALCPeakFittingPresenter::onCurrentFunctionChanged() {
+  if (auto index = m_view->currentFunctionIndex()) // If any function selected
   {
-    if(auto index = m_view->currentFunctionIndex()) // If any function selected
-    {
-      IFunction_const_sptr currentFunc = m_view->function(*index);
-
-      if (auto peakFunc = boost::dynamic_pointer_cast<const IPeakFunction>(currentFunc))
-      {
-        // If peak function selected - update and enable
-        m_view->setPeakPicker(peakFunc);
-        m_view->setPeakPickerEnabled(true);
-        return;
-      }
+    IFunction_const_sptr currentFunc = m_view->function(*index);
+
+    if (auto peakFunc =
+            boost::dynamic_pointer_cast<const IPeakFunction>(currentFunc)) {
+      // If peak function selected - update and enable
+      m_view->setPeakPicker(peakFunc);
+      m_view->setPeakPickerEnabled(true);
+      return;
     }
-
-    // Nothing or a non-peak function selected - disable Peak Picker
-    m_view->setPeakPickerEnabled(false);
   }
 
-  void ALCPeakFittingPresenter::onPeakPickerChanged()
-  {
-    auto index = m_view->currentFunctionIndex();
+  // Nothing or a non-peak function selected - disable Peak Picker
+  m_view->setPeakPickerEnabled(false);
+}
 
-    // If PeakPicker is changed, it should be enabled, which means a peak function should be selected
-    // (See onCurrentFunctionChanged)
-    assert(index);
+void ALCPeakFittingPresenter::onPeakPickerChanged() {
+  auto index = m_view->currentFunctionIndex();
 
-    auto peakFunc = m_view->peakPicker();
+  // If PeakPicker is changed, it should be enabled, which means a peak function
+  // should be selected
+  // (See onCurrentFunctionChanged)
+  assert(index);
 
-    // Update all the defined parameters of the peak function
-    for (size_t i = 0; i < peakFunc->nParams(); ++i)
-    {
-      QString paramName = QString::fromStdString(peakFunc->parameterName(i));
-      m_view->setParameter(*index, paramName, peakFunc->getParameter(paramName.toStdString()));
-    }
-  }
+  auto peakFunc = m_view->peakPicker();
 
-  void ALCPeakFittingPresenter::onParameterChanged(const QString& funcIndex)
-  {
-    auto currentIndex = m_view->currentFunctionIndex();
-
-    // We are interested in parameter changed of the currently selected function only - that's what
-    // PeakPicker is showing
-    if (currentIndex && *currentIndex == funcIndex)
-    {
-      if(auto peak = boost::dynamic_pointer_cast<const IPeakFunction>(m_view->function(funcIndex)))
-      {
-        m_view->setPeakPicker(peak);
-      }
-    }
+  // Update all the defined parameters of the peak function
+  for (size_t i = 0; i < peakFunc->nParams(); ++i) {
+    QString paramName = QString::fromStdString(peakFunc->parameterName(i));
+    m_view->setParameter(*index, paramName,
+                         peakFunc->getParameter(paramName.toStdString()));
   }
-
-  void ALCPeakFittingPresenter::onFittedPeaksChanged() {
-    IFunction_const_sptr fittedPeaks = m_model->fittedPeaks();
-    auto dataWS = m_model->data();
-    if (fittedPeaks && dataWS) {
-      auto x = dataWS->readX(0);
-      m_view->setFittedCurve(
-          *(ALCHelper::curveDataFromFunction(fittedPeaks, x)));
-      m_view->setFunction(fittedPeaks);
-    } else {
-      m_view->setFittedCurve(*(ALCHelper::emptyCurveData()));
-      m_view->setFunction(IFunction_const_sptr());
+}
+
+void ALCPeakFittingPresenter::onParameterChanged(const QString &funcIndex) {
+  auto currentIndex = m_view->currentFunctionIndex();
+
+  // We are interested in parameter changed of the currently selected function
+  // only - that's what
+  // PeakPicker is showing
+  if (currentIndex && *currentIndex == funcIndex) {
+    if (auto peak = boost::dynamic_pointer_cast<const IPeakFunction>(
+            m_view->function(funcIndex))) {
+      m_view->setPeakPicker(peak);
     }
   }
-
-  void ALCPeakFittingPresenter::onDataChanged() {
-    auto dataWS = m_model->data();
-    if (dataWS) {
-      m_view->setDataCurve(*(ALCHelper::curveDataFromWs(m_model->data(), 0)),
-                           ALCHelper::curveErrorsFromWs(m_model->data(), 0));
-    } else {
-      m_view->setDataCurve(*(ALCHelper::emptyCurveData()), Mantid::MantidVec{});
-    }
+}
+
+void ALCPeakFittingPresenter::onFittedPeaksChanged() {
+  IFunction_const_sptr fittedPeaks = m_model->fittedPeaks();
+  auto dataWS = m_model->data();
+  if (fittedPeaks && dataWS) {
+    auto x = dataWS->readX(0);
+    m_view->setFittedCurve(*(ALCHelper::curveDataFromFunction(fittedPeaks, x)));
+    m_view->setFunction(fittedPeaks);
+  } else {
+    m_view->setFittedCurve(*(ALCHelper::emptyCurveData()));
+    m_view->setFunction(IFunction_const_sptr());
   }
-
-  /**
-   * Called when user clicks "Plot/Remove guess" on the view.
-   * Plots the current guess fit on the graph, or removes it.
-   */
-  void ALCPeakFittingPresenter::onPlotGuessClicked() {
-    if (m_guessPlotted) {
-      removePlots();
-    } else {
-      if (plotGuessOnGraph()) {
-        m_view->changePlotGuessState(true);
-        m_guessPlotted = true;
-      } else {
-        m_view->displayError("Couldn't plot with empty function/data");
-        removePlots();
-      }
-    }
+}
+
+void ALCPeakFittingPresenter::onDataChanged() {
+  auto dataWS = m_model->data();
+  if (dataWS) {
+    m_view->setDataCurve(*(ALCHelper::curveDataFromWs(m_model->data(), 0)),
+                         ALCHelper::curveErrorsFromWs(m_model->data(), 0));
+  } else {
+    m_view->setDataCurve(*(ALCHelper::emptyCurveData()), Mantid::MantidVec{});
   }
-
-  /**
-   * Plots current guess on the graph, if possible
-   * Not possible if function or data are null
-   * @returns :: success or failure
-   */
-  bool ALCPeakFittingPresenter::plotGuessOnGraph() {
-    bool plotted = false;
-    auto func = m_view->function("");
-    auto dataWS = m_model->data();
-    if (func && dataWS) {
-      auto xdata = dataWS->readX(0);
-      m_view->setFittedCurve(*(ALCHelper::curveDataFromFunction(func, xdata)));
-      plotted = true;
+}
+
+/**
+ * Called when user clicks "Plot/Remove guess" on the view.
+ * Plots the current guess fit on the graph, or removes it.
+ */
+void ALCPeakFittingPresenter::onPlotGuessClicked() {
+  if (m_guessPlotted) {
+    removePlots();
+  } else {
+    if (plotGuessOnGraph()) {
+      m_view->changePlotGuessState(true);
+      m_guessPlotted = true;
+    } else {
+      m_view->displayError("Couldn't plot with empty function/data");
+      removePlots();
     }
-    return plotted;
   }
-
-  /**
-   * Removes any fit function from the graph.
-   */
-  void ALCPeakFittingPresenter::removePlots() {
-    m_view->setFittedCurve(*(ALCHelper::emptyCurveData()));
-    m_view->changePlotGuessState(false);
-    m_guessPlotted = false;
+}
+
+/**
+ * Plots current guess on the graph, if possible
+ * Not possible if function or data are null
+ * @returns :: success or failure
+ */
+bool ALCPeakFittingPresenter::plotGuessOnGraph() {
+  bool plotted = false;
+  auto func = m_view->function("");
+  auto dataWS = m_model->data();
+  if (func && dataWS) {
+    auto xdata = dataWS->readX(0);
+    m_view->setFittedCurve(*(ALCHelper::curveDataFromFunction(func, xdata)));
+    plotted = true;
   }
-
-  } // namespace CustomInterfaces
-  } // namespace MantidQt
+  return plotted;
+}
+
+/**
+ * Removes any fit function from the graph.
+ */
+void ALCPeakFittingPresenter::removePlots() {
+  m_view->setFittedCurve(*(ALCHelper::emptyCurveData()));
+  m_view->changePlotGuessState(false);
+  m_guessPlotted = false;
+}
+
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingView.cpp b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingView.cpp
index 33ba7e7ff0aec64358c319926b8ec84d83eda23f..afb0a529fbc7e18c69153a341759b853d23a9047 100644
--- a/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingView.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/ALCPeakFittingView.cpp
@@ -7,18 +7,15 @@
 
 #include <qwt_symbol.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 ALCPeakFittingView::ALCPeakFittingView(QWidget *widget)
     : m_widget(widget), m_ui(), m_dataCurve(new QwtPlotCurve()),
       m_fittedCurve(new QwtPlotCurve()), m_dataErrorCurve(NULL),
       m_peakPicker(NULL) {}
 
-ALCPeakFittingView::~ALCPeakFittingView()
-{
+ALCPeakFittingView::~ALCPeakFittingView() {
   m_dataCurve->detach();
   delete m_dataCurve;
   if (m_dataErrorCurve) {
@@ -27,23 +24,19 @@ ALCPeakFittingView::~ALCPeakFittingView()
   }
 }
 
-IFunction_const_sptr ALCPeakFittingView::function(QString index) const
-{
+IFunction_const_sptr ALCPeakFittingView::function(QString index) const {
   return m_ui.peaks->getFunctionByIndex(index);
 }
 
-boost::optional<QString> ALCPeakFittingView::currentFunctionIndex() const
-{
+boost::optional<QString> ALCPeakFittingView::currentFunctionIndex() const {
   return m_ui.peaks->currentFunctionIndex();
 }
 
-IPeakFunction_const_sptr ALCPeakFittingView::peakPicker() const
-{
+IPeakFunction_const_sptr ALCPeakFittingView::peakPicker() const {
   return m_peakPicker->peak();
 }
 
-void ALCPeakFittingView::initialize()
-{
+void ALCPeakFittingView::initialize() {
   m_ui.setupUi(m_widget);
 
   connect(m_ui.fit, SIGNAL(clicked()), this, SIGNAL(fitRequested()));
@@ -53,7 +46,8 @@ void ALCPeakFittingView::initialize()
   m_ui.plot->setAxisFont(QwtPlot::yLeft, m_widget->font());
 
   m_dataCurve->setStyle(QwtPlotCurve::NoCurve);
-  m_dataCurve->setSymbol(QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7,7)));
+  m_dataCurve->setSymbol(
+      QwtSymbol(QwtSymbol::Ellipse, QBrush(), QPen(), QSize(7, 7)));
   m_dataCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
   m_dataCurve->attach(m_ui.plot);
 
@@ -61,14 +55,16 @@ void ALCPeakFittingView::initialize()
   m_fittedCurve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
   m_fittedCurve->attach(m_ui.plot);
 
-  // XXX: Being a QwtPlotItem, should get deleted when m_ui.plot gets deleted (auto-delete option)
+  // XXX: Being a QwtPlotItem, should get deleted when m_ui.plot gets deleted
+  // (auto-delete option)
   m_peakPicker = new MantidWidgets::PeakPicker(m_ui.plot, Qt::red);
 
   connect(m_peakPicker, SIGNAL(changed()), SIGNAL(peakPickerChanged()));
 
-  connect(m_ui.peaks, SIGNAL(currentFunctionChanged()), SIGNAL(currentFunctionChanged()));
-  connect(m_ui.peaks, SIGNAL(parameterChanged(QString,QString)),
-          SIGNAL(parameterChanged(QString,QString)));
+  connect(m_ui.peaks, SIGNAL(currentFunctionChanged()),
+          SIGNAL(currentFunctionChanged()));
+  connect(m_ui.peaks, SIGNAL(parameterChanged(QString, QString)),
+          SIGNAL(parameterChanged(QString, QString)));
 
   connect(m_ui.help, SIGNAL(clicked()), this, SLOT(help()));
   connect(m_ui.plotGuess, SIGNAL(clicked()), this, SLOT(plotGuess()));
@@ -93,58 +89,49 @@ void ALCPeakFittingView::setDataCurve(const QwtData &data,
   m_ui.plot->replot();
 }
 
-void ALCPeakFittingView::setFittedCurve(const QwtData& data)
-{
+void ALCPeakFittingView::setFittedCurve(const QwtData &data) {
   m_fittedCurve->setData(data);
   m_ui.plot->replot();
 }
 
-void ALCPeakFittingView::setFunction(const IFunction_const_sptr& newFunction)
-{
-  if (newFunction)
-  {
+void ALCPeakFittingView::setFunction(const IFunction_const_sptr &newFunction) {
+  if (newFunction) {
     size_t nParams = newFunction->nParams();
-    for (size_t i=0; i<nParams; i++) {
+    for (size_t i = 0; i < nParams; i++) {
 
       QString name = QString::fromStdString(newFunction->parameterName(i));
       double value = newFunction->getParameter(i);
       double error = newFunction->getError(i);
 
-      m_ui.peaks->setParameter(name,value);
-      m_ui.peaks->setParamError(name,error);
+      m_ui.peaks->setParameter(name, value);
+      m_ui.peaks->setParamError(name, error);
     }
-  }
-  else
-  {
+  } else {
     m_ui.peaks->clear();
   }
 }
 
-void ALCPeakFittingView::setParameter(const QString& funcIndex, const QString& paramName, double value)
-{
+void ALCPeakFittingView::setParameter(const QString &funcIndex,
+                                      const QString &paramName, double value) {
   m_ui.peaks->setParameter(funcIndex, paramName, value);
 }
 
-void ALCPeakFittingView::setPeakPickerEnabled(bool enabled)
-{
+void ALCPeakFittingView::setPeakPickerEnabled(bool enabled) {
   m_peakPicker->setEnabled(enabled);
   m_peakPicker->setVisible(enabled);
   m_ui.plot->replot(); // PeakPicker might get hidden/shown
 }
 
-void ALCPeakFittingView::setPeakPicker(const IPeakFunction_const_sptr& peak)
-{
+void ALCPeakFittingView::setPeakPicker(const IPeakFunction_const_sptr &peak) {
   m_peakPicker->setPeak(peak);
   m_ui.plot->replot();
 }
 
-void ALCPeakFittingView::help()
-{
+void ALCPeakFittingView::help() {
   MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("Muon_ALC"));
 }
 
-void ALCPeakFittingView::displayError(const QString& message)
-{
+void ALCPeakFittingView::displayError(const QString &message) {
   QMessageBox::critical(m_widget, "Error", message);
 }
 
@@ -168,4 +155,3 @@ void ALCPeakFittingView::changePlotGuessState(bool plotted) {
 
 } // namespace CustomInterfaces
 } // namespace Mantid
-
diff --git a/MantidQt/CustomInterfaces/src/Muon/IO_MuonGrouping.cpp b/MantidQt/CustomInterfaces/src/Muon/IO_MuonGrouping.cpp
index e965dbe0baf79ab77f3e19253ff2671cbf79b4f9..8b516abc4425bec827ec53c367e1e6bf59c3abd0 100644
--- a/MantidQt/CustomInterfaces/src/Muon/IO_MuonGrouping.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/IO_MuonGrouping.cpp
@@ -191,9 +191,8 @@ int MuonGroupingHelper::fillGroupingTable(
 
     // Set alpha
     m_uiForm.pairTable->setItem(
-        pi, 3,
-        new QTableWidgetItem(
-            boost::lexical_cast<std::string>(grouping.pairAlphas[pi]).c_str()));
+        pi, 3, new QTableWidgetItem(boost::lexical_cast<std::string>(
+                                        grouping.pairAlphas[pi]).c_str()));
   }
 
   // Set description
diff --git a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp
index fea746352481fb574b68d40829edd5a141f4e634..d8f935d5165c7c53bbd8bc7c92df7b5281c829fa 100644
--- a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp
@@ -667,8 +667,7 @@ void MuonAnalysis::runSaveGroupButton() {
   QString prevPath =
       prevValues.value("dir", QString::fromStdString(
                                   ConfigService::Instance().getString(
-                                      "defaultsave.directory")))
-          .toString();
+                                      "defaultsave.directory"))).toString();
 
   QString filter;
   filter.append("Files (*.xml *.XML)");
@@ -707,8 +706,7 @@ void MuonAnalysis::runLoadGroupButton() {
   QString prevPath =
       prevValues.value("dir", QString::fromStdString(
                                   ConfigService::Instance().getString(
-                                      "defaultload.directory")))
-          .toString();
+                                      "defaultload.directory"))).toString();
 
   QString filter;
   filter.append("Files (*.xml *.XML)");
diff --git a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisFitDataTab.cpp b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisFitDataTab.cpp
index 9a318125f2b55d5708059496b5925c42cd6f8b10..bb612b7964d2df9d88c1b446520255cbe5dbcd49 100644
--- a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisFitDataTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisFitDataTab.cpp
@@ -14,43 +14,41 @@
 #include <QUrl>
 //-----------------------------------------------------------------------------
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace Muon
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace Muon {
 
+void MuonAnalysisFitDataTab::init() {
+  connect(m_uiForm.muonAnalysisHelpDataAnalysis, SIGNAL(clicked()), this,
+          SLOT(muonAnalysisHelpDataAnalysisClicked()));
 
-void MuonAnalysisFitDataTab::init()
-{
-  connect(m_uiForm.muonAnalysisHelpDataAnalysis, SIGNAL(clicked()), this, SLOT(muonAnalysisHelpDataAnalysisClicked()));
-  
-  // Detect when the fit has finished and group the workspaces that have been created as a result.
-  connect(m_uiForm.fitBrowser, SIGNAL(fittingDone(QString)), this, SLOT(groupFittedWorkspaces(QString)));
+  // Detect when the fit has finished and group the workspaces that have been
+  // created as a result.
+  connect(m_uiForm.fitBrowser, SIGNAL(fittingDone(QString)), this,
+          SLOT(groupFittedWorkspaces(QString)));
 }
 
-
 /**
 * Muon Analysis Data Analysis help (slot)
 */
-void MuonAnalysisFitDataTab::muonAnalysisHelpDataAnalysisClicked()
-{
+void MuonAnalysisFitDataTab::muonAnalysisHelpDataAnalysisClicked() {
   QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
-            "MuonAnalysisDataAnalysis"));
+                                 "MuonAnalysisDataAnalysis"));
 }
 
-
 /**
 * Make a raw workspace by cloning the workspace given which isn't bunched.
 *
 * @param wsName :: The name of the current data (shouldn't be bunched) to clone.
 */
-void MuonAnalysisFitDataTab::makeRawWorkspace(const std::string& wsName)
-{
-  Mantid::API::Workspace_sptr inputWs = boost::dynamic_pointer_cast<Mantid::API::Workspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
-  Mantid::API::IAlgorithm_sptr duplicate = Mantid::API::AlgorithmManager::Instance().create("CloneWorkspace");
-  duplicate->setProperty<Mantid::API::Workspace_sptr>("InputWorkspace", inputWs);
+void MuonAnalysisFitDataTab::makeRawWorkspace(const std::string &wsName) {
+  Mantid::API::Workspace_sptr inputWs =
+      boost::dynamic_pointer_cast<Mantid::API::Workspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(wsName));
+  Mantid::API::IAlgorithm_sptr duplicate =
+      Mantid::API::AlgorithmManager::Instance().create("CloneWorkspace");
+  duplicate->setProperty<Mantid::API::Workspace_sptr>("InputWorkspace",
+                                                      inputWs);
   duplicate->setPropertyValue("OutputWorkspace", wsName + "_Raw");
   duplicate->execute();
 }
@@ -60,23 +58,20 @@ void MuonAnalysisFitDataTab::makeRawWorkspace(const std::string& wsName)
 *
 * @param workspaceName :: The workspaceName that the fit has been done against
 */
-void MuonAnalysisFitDataTab::groupFittedWorkspaces(QString workspaceName)
-{
-  std::string wsNormalised = workspaceName.toStdString() + "_NormalisedCovarianceMatrix";
+void MuonAnalysisFitDataTab::groupFittedWorkspaces(QString workspaceName) {
+  std::string wsNormalised =
+      workspaceName.toStdString() + "_NormalisedCovarianceMatrix";
   std::string wsParameters = workspaceName.toStdString() + "_Parameters";
   std::string wsWorkspace = workspaceName.toStdString() + "_Workspace";
   std::vector<std::string> inputWorkspaces;
 
-  if ( Mantid::API::AnalysisDataService::Instance().doesExist(wsNormalised) )
-  {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(wsNormalised)) {
     inputWorkspaces.push_back(wsNormalised);
   }
-  if ( Mantid::API::AnalysisDataService::Instance().doesExist(wsParameters) )
-  {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(wsParameters)) {
     inputWorkspaces.push_back(wsParameters);
   }
-  if ( Mantid::API::AnalysisDataService::Instance().doesExist(wsWorkspace) )
-  {
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(wsWorkspace)) {
     inputWorkspaces.push_back(wsWorkspace);
   }
 
diff --git a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisHelper.cpp b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisHelper.cpp
index e408e56ee90a7049ed3ac644a8df2d8564f8e2a6..46ae6407a2178e4e2e6b7200f5a0e618988f7c8f 100644
--- a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisHelper.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisHelper.cpp
@@ -18,12 +18,9 @@
 #include <boost/scope_exit.hpp>
 #include <stdexcept>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-namespace MuonAnalysisHelper
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+namespace MuonAnalysisHelper {
 
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
@@ -33,16 +30,12 @@ using namespace Mantid::API;
  * @param field :: Field to set validator for
  * @param allowEmpty :: Whether the validator should accept empty inputs as well
  */
-void setDoubleValidator(QLineEdit* field, bool allowEmpty)
-{
-  QDoubleValidator* newValidator;
+void setDoubleValidator(QLineEdit *field, bool allowEmpty) {
+  QDoubleValidator *newValidator;
 
-  if (allowEmpty)
-  {
+  if (allowEmpty) {
     newValidator = new DoubleOrEmptyValidator(field);
-  }
-  else
-  {
+  } else {
     newValidator = new QDoubleValidator(field);
   }
 
@@ -50,20 +43,16 @@ void setDoubleValidator(QLineEdit* field, bool allowEmpty)
   field->setValidator(newValidator);
 }
 
-
 /**
- * Return a first period MatrixWorkspace in a run workspace. If the run workspace has one period
+ * Return a first period MatrixWorkspace in a run workspace. If the run
+ * workspace has one period
  * only - it is returned.
  * @param ws :: Run workspace
  */
-MatrixWorkspace_sptr firstPeriod(Workspace_sptr ws)
-{
-  if ( auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(ws) )
-  {
-    return boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(0) );
-  }
-  else
-  {
+MatrixWorkspace_sptr firstPeriod(Workspace_sptr ws) {
+  if (auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(ws)) {
+    return boost::dynamic_pointer_cast<MatrixWorkspace>(group->getItem(0));
+  } else {
     return boost::dynamic_pointer_cast<MatrixWorkspace>(ws);
   }
 }
@@ -73,14 +62,10 @@ MatrixWorkspace_sptr firstPeriod(Workspace_sptr ws)
  * @param ws :: Run wokspace
  * @return Number of periods
  */
-size_t numPeriods(Workspace_sptr ws)
-{
-  if ( auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(ws) )
-  {
+size_t numPeriods(Workspace_sptr ws) {
+  if (auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(ws)) {
     return group->size();
-  }
-  else
-  {
+  } else {
     return 1;
   }
 }
@@ -90,14 +75,12 @@ size_t numPeriods(Workspace_sptr ws)
  * @param runWs :: Run workspace to retrieve information from
  * @param out :: Stream to print to
  */
-void printRunInfo(MatrixWorkspace_sptr runWs, std::ostringstream& out)
-{
+void printRunInfo(MatrixWorkspace_sptr runWs, std::ostringstream &out) {
   // Remember current out stream format
   std::ios_base::fmtflags outFlags(out.flags());
   std::streamsize outPrecision(out.precision());
 
-  BOOST_SCOPE_EXIT((&out)(&outFlags)(&outPrecision))
-  {
+  BOOST_SCOPE_EXIT((&out)(&outFlags)(&outPrecision)) {
     // Restore the flags when exiting the function
     out.precision(outPrecision);
     out.flags(outFlags);
@@ -110,68 +93,57 @@ void printRunInfo(MatrixWorkspace_sptr runWs, std::ostringstream& out)
   out << "\nTitle: " << runWs->getTitle();
   out << "\nComment: " << runWs->getComment();
 
-  const Run& run = runWs->run();
+  const Run &run = runWs->run();
 
   Mantid::Kernel::DateAndTime start, end;
 
   // Add the start time for the run
   out << "\nStart: ";
-  if ( run.hasProperty("run_start") )
-  {
+  if (run.hasProperty("run_start")) {
     start = run.getProperty("run_start")->value();
     out << start.toSimpleString();
   }
 
   // Add the end time for the run
   out << "\nEnd: ";
-  if ( run.hasProperty("run_end") )
-  {
+  if (run.hasProperty("run_end")) {
     end = run.getProperty("run_end")->value();
     out << end.toSimpleString();
   }
 
   // Add the end time for the run
   out << "\nGood frames: ";
-  if ( run.hasProperty("goodfrm") )
-  {
+  if (run.hasProperty("goodfrm")) {
     out << run.getProperty("goodfrm")->value();
   }
 
   // Add counts to run information
   out << "\nCounts: ";
   double counts(0.0);
-  for (size_t i=0; i<runWs->getNumberHistograms(); ++i)
-  {
-    for (size_t j=0; j<runWs->blocksize(); ++j)
-    {
+  for (size_t i = 0; i < runWs->getNumberHistograms(); ++i) {
+    for (size_t j = 0; j < runWs->blocksize(); ++j) {
       counts += runWs->dataY(i)[j];
     }
   }
   // output this number to three decimal places
   out << std::setprecision(3);
-  out << counts/1000000 << " MEv";
+  out << counts / 1000000 << " MEv";
   out << std::setprecision(12);
   // Add average temperature.
   out << "\nAverage Temperature: ";
-  if ( run.hasProperty("Temp_Sample") )
-  {
+  if (run.hasProperty("Temp_Sample")) {
     // Filter the temperatures by the start and end times for the run.
     run.getProperty("Temp_Sample")->filterByTime(start, end);
 
     // Get average of the values
     double average = run.getPropertyAsSingleValue("Temp_Sample");
 
-    if (average != 0.0)
-    {
+    if (average != 0.0) {
       out << average;
-    }
-    else
-    {
+    } else {
       out << "Not set";
     }
-  }
-  else
-  {
+  } else {
     out << "Not found";
   }
 
@@ -198,8 +170,7 @@ void printRunInfo(MatrixWorkspace_sptr runWs, std::ostringstream& out)
  * Constructor
  * @param groupName :: The top-level group to use for all the widgets
  */
-WidgetAutoSaver::WidgetAutoSaver(const QString& groupName)
-{
+WidgetAutoSaver::WidgetAutoSaver(const QString &groupName) {
   m_settings.beginGroup(groupName);
 }
 
@@ -209,37 +180,33 @@ WidgetAutoSaver::WidgetAutoSaver(const QString& groupName)
  * @param name :: A name to use when saving/loading
  * @param defaultValue :: A value to load when the widget has not been saved yet
  */
-void WidgetAutoSaver::registerWidget(QWidget *widget, const QString& name, QVariant defaultValue)
-{
+void WidgetAutoSaver::registerWidget(QWidget *widget, const QString &name,
+                                     QVariant defaultValue) {
   m_registeredWidgets.push_back(widget);
   m_widgetNames[widget] = name;
   m_widgetDefaultValues[widget] = defaultValue;
-  m_widgetGroups[widget] = m_settings.group(); // Current group set up using beginGroup and endGroup
+  m_widgetGroups[widget] =
+      m_settings.group(); // Current group set up using beginGroup and endGroup
 }
 
 /**
- * Return a signal (which can be used instead of SIGNAL()) which is emmited when given widget is
+ * Return a signal (which can be used instead of SIGNAL()) which is emmited when
+ * given widget is
  * changed.
  * @param widget
- * @return A signal you can use instead of SIGNAL() to determine when widget value was changed
+ * @return A signal you can use instead of SIGNAL() to determine when widget
+ * value was changed
  */
-const char* WidgetAutoSaver::changedSignal(QWidget *widget)
-{
-  if ( qobject_cast<QLineEdit*>(widget) )
-  {
+const char *WidgetAutoSaver::changedSignal(QWidget *widget) {
+  if (qobject_cast<QLineEdit *>(widget)) {
     return SIGNAL(textChanged(QString));
-  }
-  else if ( qobject_cast<QCheckBox*>(widget) )
-  {
+  } else if (qobject_cast<QCheckBox *>(widget)) {
     return SIGNAL(stateChanged(int));
-  }
-  else if ( qobject_cast<QComboBox*>(widget) )
-  {
+  } else if (qobject_cast<QComboBox *>(widget)) {
     return SIGNAL(currentIndexChanged(int));
   }
   // ... add more as neccessary
-  else
-  {
+  else {
     throw std::runtime_error("Unsupported widget type");
   }
 }
@@ -248,12 +215,8 @@ const char* WidgetAutoSaver::changedSignal(QWidget *widget)
  * Enable/disable auto-saving of all the registered widgets.
  * @param enabled :: Whether auto-saving should be enabled or disabled
  */
-void WidgetAutoSaver::setAutoSaveEnabled(bool enabled)
-{
-  foreach (QWidget* w, m_registeredWidgets)
-  {
-    setAutoSaveEnabled(w, enabled);
-  }
+void WidgetAutoSaver::setAutoSaveEnabled(bool enabled) {
+  foreach (QWidget *w, m_registeredWidgets) { setAutoSaveEnabled(w, enabled); }
 }
 
 /**
@@ -261,8 +224,7 @@ void WidgetAutoSaver::setAutoSaveEnabled(bool enabled)
  * @param widget :: Registered widget for which to enable/disable auto-saving
  * @param enabled :: Whether auto-saving should be enabled or disabled
  */
-void WidgetAutoSaver::setAutoSaveEnabled(QWidget* widget, bool enabled)
-{
+void WidgetAutoSaver::setAutoSaveEnabled(QWidget *widget, bool enabled) {
   if (enabled)
     connect(widget, changedSignal(widget), this, SLOT(saveWidgetValue()));
   else
@@ -272,30 +234,24 @@ void WidgetAutoSaver::setAutoSaveEnabled(QWidget* widget, bool enabled)
 /**
  * Saves the value of the registered widget which signalled the slot
  */
-void WidgetAutoSaver::saveWidgetValue()
-{
+void WidgetAutoSaver::saveWidgetValue() {
   // Get the widget which called the slot
-  QWidget* sender = qobject_cast<QWidget*>(QObject::sender());
+  QWidget *sender = qobject_cast<QWidget *>(QObject::sender());
 
-  if(!sender)
+  if (!sender)
     throw std::runtime_error("Unable to save value of non-widget QObject");
 
-  const QString& senderName = m_widgetNames[sender];
-  const QString& senderGroup = m_widgetGroups[sender];
+  const QString &senderName = m_widgetNames[sender];
+  const QString &senderGroup = m_widgetGroups[sender];
 
   QSettings settings;
   settings.beginGroup(senderGroup);
 
-  if ( auto w = qobject_cast<QLineEdit*>(sender) )
-  {
+  if (auto w = qobject_cast<QLineEdit *>(sender)) {
     settings.setValue(senderName, w->text());
-  }
-  else if ( auto w = qobject_cast<QCheckBox*>(sender) )
-  {
+  } else if (auto w = qobject_cast<QCheckBox *>(sender)) {
     settings.setValue(senderName, w->isChecked());
-  }
-  else if ( auto w = qobject_cast<QComboBox*>(sender) )
-  {
+  } else if (auto w = qobject_cast<QComboBox *>(sender)) {
     settings.setValue(senderName, w->currentIndex());
   }
   // ... add more as neccessary
@@ -305,10 +261,9 @@ void WidgetAutoSaver::saveWidgetValue()
  * Load the auto-saved (or default) value of the given widget.
  * @param widget :: Widget to load saved value for
  */
-void WidgetAutoSaver::loadWidgetValue(QWidget *widget)
-{
-  const QString& name = m_widgetNames[widget];
-  const QString& group = m_widgetGroups[widget];
+void WidgetAutoSaver::loadWidgetValue(QWidget *widget) {
+  const QString &name = m_widgetNames[widget];
+  const QString &group = m_widgetGroups[widget];
   QVariant defaultValue = m_widgetDefaultValues[widget];
 
   QSettings settings;
@@ -316,16 +271,11 @@ void WidgetAutoSaver::loadWidgetValue(QWidget *widget)
 
   QVariant value = settings.value(name, defaultValue);
 
-  if ( auto w = qobject_cast<QLineEdit*>(widget) )
-  {
+  if (auto w = qobject_cast<QLineEdit *>(widget)) {
     w->setText(value.toString());
-  }
-  else if ( auto w = qobject_cast<QCheckBox*>(widget) )
-  {
+  } else if (auto w = qobject_cast<QCheckBox *>(widget)) {
     w->setChecked(value.toBool());
-  }
-  else if ( auto w = qobject_cast<QComboBox*>(widget) )
-  {
+  } else if (auto w = qobject_cast<QComboBox *>(widget)) {
     w->setCurrentIndex(value.toInt());
   }
   // ... add more as neccessary
@@ -334,31 +284,24 @@ void WidgetAutoSaver::loadWidgetValue(QWidget *widget)
 /**
  * Load the auto-saved (or default) value of all the registered widgets.
  */
-void WidgetAutoSaver::loadWidgetValues()
-{
-  foreach (QWidget* w, m_registeredWidgets)
-  {
-    loadWidgetValue(w);
-  }
+void WidgetAutoSaver::loadWidgetValues() {
+  foreach (QWidget *w, m_registeredWidgets) { loadWidgetValue(w); }
 }
 
 /**
- * Begin new-auto save group. All the registerWidget calls between this and next beginGroup will be
+ * Begin new-auto save group. All the registerWidget calls between this and next
+ * beginGroup will be
  * put in the given group.
  * @param name :: The name of the group
  */
-void WidgetAutoSaver::beginGroup(const QString &name)
-{
+void WidgetAutoSaver::beginGroup(const QString &name) {
   m_settings.beginGroup(name);
 }
 
 /**
  * Ends the scope of the previous begin group.
  */
-void WidgetAutoSaver::endGroup()
-{
-  m_settings.endGroup();
-}
+void WidgetAutoSaver::endGroup() { m_settings.endGroup(); }
 
 /**
  * Get a run label for the workspace.
@@ -366,8 +309,7 @@ void WidgetAutoSaver::endGroup()
  * @param ws :: Workspace to get label for.
  * @return
  */
-std::string getRunLabel(const Workspace_sptr& ws)
-{
+std::string getRunLabel(const Workspace_sptr &ws) {
   MatrixWorkspace_const_sptr firstPrd = firstPeriod(ws);
 
   int runNumber = firstPrd->getRunNumber();
@@ -385,7 +327,8 @@ std::string getRunLabel(const Workspace_sptr& ws)
 
   std::ostringstream label;
   label << instrName;
-  label << std::setw(zeroPadding) << std::setfill('0') << std::right << runNumber;
+  label << std::setw(zeroPadding) << std::setfill('0') << std::right
+        << runNumber;
   return label.str();
 }
 
@@ -484,8 +427,7 @@ findConsecutiveRuns(const std::vector<int> &runs) {
  * @param workspaces :: List of workspaces
  * @return Result workspace
  */
-Workspace_sptr sumWorkspaces(const std::vector<Workspace_sptr>& workspaces)
-{
+Workspace_sptr sumWorkspaces(const std::vector<Workspace_sptr> &workspaces) {
   if (workspaces.size() < 1)
     throw std::invalid_argument("Couldn't sum an empty list of workspaces");
 
@@ -498,24 +440,26 @@ Workspace_sptr sumWorkspaces(const std::vector<Workspace_sptr>& workspaces)
   };
 
   // Comparison function for doubles
-  auto numericalCompare = [](const std::string &first,
-                             const std::string &second) {
-    try {
-      return boost::lexical_cast<double>(first) <
-             boost::lexical_cast<double>(second);
-    } catch (boost::bad_lexical_cast & /*e*/) {
-      return false;
-    }
-  };
+  auto numericalCompare =
+      [](const std::string &first, const std::string &second) {
+        try {
+          return boost::lexical_cast<double>(first) <
+                 boost::lexical_cast<double>(second);
+        } catch (boost::bad_lexical_cast & /*e*/) {
+          return false;
+        }
+      };
 
   // Range of log values
   auto startRange = findLogRange(workspaces, "run_start", dateCompare);
   auto endRange = findLogRange(workspaces, "run_end", dateCompare);
   auto tempRange = findLogRange(workspaces, "sample_temp", numericalCompare);
-  auto fieldRange = findLogRange(workspaces, "sample_magn_field", numericalCompare);
+  auto fieldRange =
+      findLogRange(workspaces, "sample_magn_field", numericalCompare);
 
   // Create accumulator workspace by cloning the first one from the list
-  IAlgorithm_sptr cloneAlg = AlgorithmManager::Instance().create("CloneWorkspace");
+  IAlgorithm_sptr cloneAlg =
+      AlgorithmManager::Instance().create("CloneWorkspace");
   cloneAlg->setLogging(false);
   cloneAlg->setRethrows(true);
   cloneAlg->setPropertyValue("InputWorkspace", firstEntry.name());
@@ -560,32 +504,30 @@ Workspace_sptr sumWorkspaces(const std::vector<Workspace_sptr>& workspaces)
 }
 
 /*
- * Validates and returns a double value. If it is not invalid, the widget is set to default value,
+ * Validates and returns a double value. If it is not invalid, the widget is set
+ * to default value,
  * appropriate warning is printed and default value is returned.
  * @param field :: Field to get value from
  * @param defaultValue :: Default value to return/set if field value is invalid
  * @param valueDescr :: Description of the value
  * @param log :: Log to print warning to in case value is invalid
- * @return Value if field is valid, default value otherwise. If default value is empty, EMPTY_DBL() is returned
+ * @return Value if field is valid, default value otherwise. If default value is
+ * empty, EMPTY_DBL() is returned
  */
-double getValidatedDouble(QLineEdit* field, const QString& defaultValue,
-                          const QString& valueDescr, Logger& log)
-{
+double getValidatedDouble(QLineEdit *field, const QString &defaultValue,
+                          const QString &valueDescr, Logger &log) {
   bool ok;
   double value = field->text().toDouble(&ok);
 
-  if (!ok)
-  {
-    log.warning() << "The value of " << valueDescr.toStdString() << " is invalid. ";
+  if (!ok) {
+    log.warning() << "The value of " << valueDescr.toStdString()
+                  << " is invalid. ";
     log.warning() << "Reset to default.\n";
     field->setText(defaultValue);
 
-    if(defaultValue.isEmpty())
-    {
+    if (defaultValue.isEmpty()) {
       return Mantid::EMPTY_DBL();
-    }
-    else
-    {
+    } else {
       return defaultValue.toDouble();
     }
   }
@@ -594,37 +536,34 @@ double getValidatedDouble(QLineEdit* field, const QString& defaultValue,
 }
 
 /**
- * Makes sure the specified workspaces are in specified group. If group exists already - missing
- * workspaces are added to it, otherwise new group is created. If ws exists in ADS under groupName,
+ * Makes sure the specified workspaces are in specified group. If group exists
+ * already - missing
+ * workspaces are added to it, otherwise new group is created. If ws exists in
+ * ADS under groupName,
  * and it is not a group - it's overwritten.
  * @param groupName :: Name of the group workspaces should be in
  * @param inputWorkspaces :: Names of the workspaces to group
  */
-void groupWorkspaces(const std::string& groupName, const std::vector<std::string>& inputWorkspaces)
-{
-  auto& ads = AnalysisDataService::Instance();
+void groupWorkspaces(const std::string &groupName,
+                     const std::vector<std::string> &inputWorkspaces) {
+  auto &ads = AnalysisDataService::Instance();
 
   WorkspaceGroup_sptr group;
-  if (ads.doesExist(groupName))
-  {
+  if (ads.doesExist(groupName)) {
     group = ads.retrieveWS<WorkspaceGroup>(groupName);
   }
 
-  if(group)
-  {
+  if (group) {
     // Exists and is a group -> add missing workspaces to it
-    for (auto it = inputWorkspaces.begin(); it != inputWorkspaces.end(); ++it)
-    {
-      if (!group->contains(*it))
-      {
+    for (auto it = inputWorkspaces.begin(); it != inputWorkspaces.end(); ++it) {
+      if (!group->contains(*it)) {
         group->add(*it);
       }
     }
-  }
-  else
-  {
+  } else {
     // Doesn't exist or isn't a group -> create/overwrite
-    IAlgorithm_sptr groupingAlg = AlgorithmManager::Instance().create("GroupWorkspaces");
+    IAlgorithm_sptr groupingAlg =
+        AlgorithmManager::Instance().create("GroupWorkspaces");
     groupingAlg->setProperty("InputWorkspaces", inputWorkspaces);
     groupingAlg->setPropertyValue("OutputWorkspace", groupName);
     groupingAlg->execute();
diff --git a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisOptionTab.cpp b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisOptionTab.cpp
index cd2a7296cbac60451254c7e1aab4fd51374079a2..8fa4b7d20ad468657f3294a6cd816aac3ab63107 100644
--- a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisOptionTab.cpp
+++ b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysisOptionTab.cpp
@@ -12,17 +12,14 @@
 //-----------------------------------------------------------------------------
 using namespace Mantid::Kernel;
 
-namespace MantidQt
-{
-  using namespace API;
-  using namespace MantidWidgets;
+namespace MantidQt {
+using namespace API;
+using namespace MantidWidgets;
 
-namespace CustomInterfaces
-{
-  using namespace MuonAnalysisHelper;
+namespace CustomInterfaces {
+using namespace MuonAnalysisHelper;
 
-namespace Muon
-{
+namespace Muon {
 
 const QString MuonAnalysisOptionTab::START_TIME_DEFAULT("0.3");
 const QString MuonAnalysisOptionTab::FINISH_TIME_DEFAULT("16.0");
@@ -31,36 +28,41 @@ const QString MuonAnalysisOptionTab::MAX_Y_DEFAULT("");
 const QString MuonAnalysisOptionTab::FIXED_REBIN_DEFAULT("2");
 const QString MuonAnalysisOptionTab::VARIABLE_REBIN_DEFAULT("0.032");
 
-namespace
-{
-  /// static logger instance
-  Logger g_log("MuonAnalysis");
+namespace {
+/// static logger instance
+Logger g_log("MuonAnalysis");
 }
 
-MuonAnalysisOptionTab::MuonAnalysisOptionTab(Ui::MuonAnalysis &uiForm, const QString &settingsGroup)
-  : m_uiForm(uiForm), m_autoSaver(settingsGroup)
-{}
+MuonAnalysisOptionTab::MuonAnalysisOptionTab(Ui::MuonAnalysis &uiForm,
+                                             const QString &settingsGroup)
+    : m_uiForm(uiForm), m_autoSaver(settingsGroup) {}
 
 /**
  * Initialise the layout of the tab
  */
-void MuonAnalysisOptionTab::initLayout()
-{
+void MuonAnalysisOptionTab::initLayout() {
   // Register all the widgets for auto-saving
   m_autoSaver.beginGroup("PlotStyleOptions");
   m_autoSaver.registerWidget(m_uiForm.connectPlotType, "connectPlotStyle", 0);
-  m_autoSaver.registerWidget(m_uiForm.timeAxisStartAtInput, "timeAxisStart", START_TIME_DEFAULT);
-  m_autoSaver.registerWidget(m_uiForm.timeAxisFinishAtInput, "timeAxisFinish", FINISH_TIME_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.timeAxisStartAtInput, "timeAxisStart",
+                             START_TIME_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.timeAxisFinishAtInput, "timeAxisFinish",
+                             FINISH_TIME_DEFAULT);
   m_autoSaver.registerWidget(m_uiForm.timeComboBox, "timeComboBoxIndex", 0);
-  m_autoSaver.registerWidget(m_uiForm.yAxisMinimumInput, "yAxisStart", MIN_Y_DEFAULT);
-  m_autoSaver.registerWidget(m_uiForm.yAxisMaximumInput, "yAxisFinish", MAX_Y_DEFAULT);
-  m_autoSaver.registerWidget(m_uiForm.yAxisAutoscale, "axisAutoScaleOnOff", true);
+  m_autoSaver.registerWidget(m_uiForm.yAxisMinimumInput, "yAxisStart",
+                             MIN_Y_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.yAxisMaximumInput, "yAxisFinish",
+                             MAX_Y_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.yAxisAutoscale, "axisAutoScaleOnOff",
+                             true);
   m_autoSaver.registerWidget(m_uiForm.showErrorBars, "errorBars", 0);
   m_autoSaver.endGroup();
 
   m_autoSaver.beginGroup("BinningOptions");
-  m_autoSaver.registerWidget(m_uiForm.optionStepSizeText, "rebinFixed", FIXED_REBIN_DEFAULT);
-  m_autoSaver.registerWidget(m_uiForm.binBoundaries, "rebinVariable", VARIABLE_REBIN_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.optionStepSizeText, "rebinFixed",
+                             FIXED_REBIN_DEFAULT);
+  m_autoSaver.registerWidget(m_uiForm.binBoundaries, "rebinVariable",
+                             VARIABLE_REBIN_DEFAULT);
   m_autoSaver.registerWidget(m_uiForm.rebinComboBox, "rebinComboBoxIndex", 0);
   m_autoSaver.endGroup();
 
@@ -84,62 +86,74 @@ void MuonAnalysisOptionTab::initLayout()
   // Run slots manually, because default values might not have been changed
   onTimeAxisChanged(m_uiForm.timeComboBox->currentIndex());
   onAutoscaleToggled(m_uiForm.yAxisAutoscale->isChecked());
-  m_uiForm.rebinEntryState->setCurrentIndex(m_uiForm.rebinComboBox->currentIndex());
+  m_uiForm.rebinEntryState->setCurrentIndex(
+      m_uiForm.rebinComboBox->currentIndex());
 
   // Enable auto-saving
   m_autoSaver.setAutoSaveEnabled(true);
 
   // Connect various sync stuff
-  connect(m_uiForm.timeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onTimeAxisChanged(int)));
-  connect(m_uiForm.yAxisAutoscale, SIGNAL(toggled(bool)), this, SLOT(onAutoscaleToggled(bool)));
-  connect(m_uiForm.rebinComboBox, SIGNAL(currentIndexChanged(int)), m_uiForm.rebinEntryState,
-          SLOT(setCurrentIndex(int)));
+  connect(m_uiForm.timeComboBox, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(onTimeAxisChanged(int)));
+  connect(m_uiForm.yAxisAutoscale, SIGNAL(toggled(bool)), this,
+          SLOT(onAutoscaleToggled(bool)));
+  connect(m_uiForm.rebinComboBox, SIGNAL(currentIndexChanged(int)),
+          m_uiForm.rebinEntryState, SLOT(setCurrentIndex(int)));
 
   // Connect help clicked
-  connect(m_uiForm.muonAnalysisHelpPlotting, SIGNAL(clicked()), this, SLOT(muonAnalysisHelpSettingsClicked()));
-  connect(m_uiForm.binBoundariesHelp, SIGNAL(clicked()), this, SLOT(rebinHelpClicked()));
+  connect(m_uiForm.muonAnalysisHelpPlotting, SIGNAL(clicked()), this,
+          SLOT(muonAnalysisHelpSettingsClicked()));
+  connect(m_uiForm.binBoundariesHelp, SIGNAL(clicked()), this,
+          SLOT(rebinHelpClicked()));
 
   // Connect auto-updates for plot style
-  connect(m_uiForm.connectPlotType, SIGNAL(currentIndexChanged(int)), this, SIGNAL(plotStyleChanged()));
-  connect(m_uiForm.showErrorBars, SIGNAL(clicked()), this, SIGNAL(plotStyleChanged()));
-  connect(m_uiForm.yAxisAutoscale, SIGNAL(clicked()), this, SIGNAL(plotStyleChanged()));
-  connect(m_uiForm.yAxisMinimumInput, SIGNAL(returnPressed ()), this, SIGNAL(plotStyleChanged()));
-  connect(m_uiForm.yAxisMaximumInput, SIGNAL(returnPressed ()), this, SIGNAL(plotStyleChanged()));
-  
+  connect(m_uiForm.connectPlotType, SIGNAL(currentIndexChanged(int)), this,
+          SIGNAL(plotStyleChanged()));
+  connect(m_uiForm.showErrorBars, SIGNAL(clicked()), this,
+          SIGNAL(plotStyleChanged()));
+  connect(m_uiForm.yAxisAutoscale, SIGNAL(clicked()), this,
+          SIGNAL(plotStyleChanged()));
+  connect(m_uiForm.yAxisMinimumInput, SIGNAL(returnPressed()), this,
+          SIGNAL(plotStyleChanged()));
+  connect(m_uiForm.yAxisMaximumInput, SIGNAL(returnPressed()), this,
+          SIGNAL(plotStyleChanged()));
+
   // Connect auto updates of plot data
-  connect(m_uiForm.timeComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(settingsTabUpdatePlot()));
-  connect(m_uiForm.timeAxisStartAtInput, SIGNAL(returnPressed ()), this, SIGNAL(settingsTabUpdatePlot()));
-  connect(m_uiForm.timeAxisFinishAtInput, SIGNAL(returnPressed ()), this, SIGNAL(settingsTabUpdatePlot()));
-  connect(m_uiForm.rebinComboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(settingsTabUpdatePlot()));
-  connect(m_uiForm.optionStepSizeText, SIGNAL(returnPressed()), this, SIGNAL(settingsTabUpdatePlot()));
-  connect(m_uiForm.binBoundaries, SIGNAL(returnPressed()), this, SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.timeComboBox, SIGNAL(currentIndexChanged(int)), this,
+          SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.timeAxisStartAtInput, SIGNAL(returnPressed()), this,
+          SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.timeAxisFinishAtInput, SIGNAL(returnPressed()), this,
+          SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.rebinComboBox, SIGNAL(currentIndexChanged(int)), this,
+          SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.optionStepSizeText, SIGNAL(returnPressed()), this,
+          SIGNAL(settingsTabUpdatePlot()));
+  connect(m_uiForm.binBoundaries, SIGNAL(returnPressed()), this,
+          SIGNAL(settingsTabUpdatePlot()));
 }
 
 /**
 * Muon Analysis Settings help.
 */
-void MuonAnalysisOptionTab::muonAnalysisHelpSettingsClicked()
-{
-  QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
-            "MuonAnalysisSettings"));
+void MuonAnalysisOptionTab::muonAnalysisHelpSettingsClicked() {
+  QDesktopServices::openUrl(
+      QUrl(QString("http://www.mantidproject.org/") + "MuonAnalysisSettings"));
 }
 
-
 /*
 * Muon Analysis Rebin help (located on settings wiki).
 */
-void MuonAnalysisOptionTab::rebinHelpClicked()
-{
+void MuonAnalysisOptionTab::rebinHelpClicked() {
   QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
-            "MuonAnalysisSettings#Variable_Rebin"));
+                                 "MuonAnalysisSettings#Variable_Rebin"));
 }
 
 /**
  * Run when autoscale check-box state is changed
  * @param state :: New state of the check-box
  */
-void MuonAnalysisOptionTab::onAutoscaleToggled(bool state)
-{
+void MuonAnalysisOptionTab::onAutoscaleToggled(bool state) {
   // Max and min input widgets
   auto maxInput = m_uiForm.yAxisMaximumInput;
   auto minInput = m_uiForm.yAxisMinimumInput;
@@ -152,13 +166,10 @@ void MuonAnalysisOptionTab::onAutoscaleToggled(bool state)
   m_autoSaver.setAutoSaveEnabled(maxInput, !state);
   m_autoSaver.setAutoSaveEnabled(minInput, !state);
 
-  if(state)
-  {
+  if (state) {
     maxInput->setText("N/A");
     minInput->setText("N/A");
-  }
-  else
-  {
+  } else {
     m_autoSaver.loadWidgetValue(maxInput);
     m_autoSaver.loadWidgetValue(minInput);
   }
@@ -168,8 +179,7 @@ void MuonAnalysisOptionTab::onAutoscaleToggled(bool state)
  * Run when time axis combo-box is changed
  * @param index :: New index selected in the combo box
  */
-void MuonAnalysisOptionTab::onTimeAxisChanged(int index)
-{
+void MuonAnalysisOptionTab::onTimeAxisChanged(int index) {
   // Start input widget
   auto startInput = m_uiForm.timeAxisStartAtInput;
 
@@ -180,31 +190,28 @@ void MuonAnalysisOptionTab::onTimeAxisChanged(int index)
   m_autoSaver.setAutoSaveEnabled(startInput, index == 2);
 
   // Get new value of the Start input
-  switch(index)
-  {
-  case(0): // Start at First Good Data
+  switch (index) {
+  case (0): // Start at First Good Data
     startInput->setText(m_uiForm.firstGoodBinFront->text());
     break;
-  case(1): // Start at Time Zero
+  case (1): // Start at Time Zero
     startInput->setText("0.0");
     break;
-  case(2): // Custom Value
+  case (2): // Custom Value
     m_autoSaver.loadWidgetValue(startInput);
     break;
   }
 
-  if(index == 0)
-  {
-    // Synchronize First Good Data box on Home tab with the one on this tab, if Start at First Good
+  if (index == 0) {
+    // Synchronize First Good Data box on Home tab with the one on this tab, if
+    // Start at First Good
     // Data is enabled.
-    connect(m_uiForm.firstGoodBinFront, SIGNAL(textChanged(const QString&)),
-            startInput, SLOT(setText(const QString&)));
-  }
-  else
-  {
+    connect(m_uiForm.firstGoodBinFront, SIGNAL(textChanged(const QString &)),
+            startInput, SLOT(setText(const QString &)));
+  } else {
     // Disable synchronization otherwise
-    disconnect(m_uiForm.firstGoodBinFront, SIGNAL(textChanged(const QString&)),
-               startInput, SLOT(setText(const QString&)));
+    disconnect(m_uiForm.firstGoodBinFront, SIGNAL(textChanged(const QString &)),
+               startInput, SLOT(setText(const QString &)));
   }
 }
 
@@ -215,11 +222,11 @@ void MuonAnalysisOptionTab::onTimeAxisChanged(int index)
  *   - YAxisAuto: True or False
  *   - YAxisMin/YAxisMax: Double values
  */
-QMap<QString, QString> MuonAnalysisOptionTab::parsePlotStyleParams() const
-{
+QMap<QString, QString> MuonAnalysisOptionTab::parsePlotStyleParams() const {
   QMap<QString, QString> params;
 
-  params["ConnectType"] = QString::number(m_uiForm.connectPlotType->currentIndex());
+  params["ConnectType"] =
+      QString::number(m_uiForm.connectPlotType->currentIndex());
 
   params["ShowErrors"] = m_uiForm.showErrorBars->isChecked() ? "True" : "False";
 
@@ -229,99 +236,86 @@ QMap<QString, QString> MuonAnalysisOptionTab::parsePlotStyleParams() const
 
   params["YAxisMin"] = params["YAxisMax"] = "";
 
-  if ( ! isAutoScaleEnabled )
-  {
+  if (!isAutoScaleEnabled) {
     // If auto-scale not enabled, retrieve start/end values
 
-    QLineEdit* minY = m_uiForm.yAxisMinimumInput;
-    QLineEdit* maxY = m_uiForm.yAxisMaximumInput;
+    QLineEdit *minY = m_uiForm.yAxisMinimumInput;
+    QLineEdit *maxY = m_uiForm.yAxisMaximumInput;
 
     double minYVal(Mantid::EMPTY_DBL());
     double maxYVal(Mantid::EMPTY_DBL());
 
-    if ( ! minY->text().isEmpty() )
-    {
-      minYVal = getValidatedDouble(minY, MIN_Y_DEFAULT, "Y axis minimum", g_log);
+    if (!minY->text().isEmpty()) {
+      minYVal =
+          getValidatedDouble(minY, MIN_Y_DEFAULT, "Y axis minimum", g_log);
     }
 
-    if ( ! maxY->text().isEmpty() )
-    {
-      maxYVal = getValidatedDouble(maxY, MAX_Y_DEFAULT, "Y axis maximum", g_log);
+    if (!maxY->text().isEmpty()) {
+      maxYVal =
+          getValidatedDouble(maxY, MAX_Y_DEFAULT, "Y axis maximum", g_log);
     }
 
     // If both specified, check if min is less than max
-    if ( minYVal != Mantid::EMPTY_DBL() && maxYVal != Mantid::EMPTY_DBL() && minYVal >= maxYVal )
-    {
+    if (minYVal != Mantid::EMPTY_DBL() && maxYVal != Mantid::EMPTY_DBL() &&
+        minYVal >= maxYVal) {
       g_log.warning("Y min should be less than Y max. Reset to default.");
       minY->setText(MIN_Y_DEFAULT);
       maxY->setText(MAX_Y_DEFAULT);
-    }
-    else
-    {
-      if ( minYVal != Mantid::EMPTY_DBL() )
+    } else {
+      if (minYVal != Mantid::EMPTY_DBL())
         params["YAxisMin"] = QString::number(minYVal);
 
-      if ( maxYVal != Mantid::EMPTY_DBL() )
+      if (maxYVal != Mantid::EMPTY_DBL())
         params["YAxisMax"] = QString::number(maxYVal);
     }
   }
 
-  return(params);
+  return (params);
 }
 
 /**
  * Retrieve selected type of the start time
  * @return Type of the start time as selected by user
  */
-MuonAnalysisOptionTab::StartTimeType MuonAnalysisOptionTab::getStartTimeType()
-{
+MuonAnalysisOptionTab::StartTimeType MuonAnalysisOptionTab::getStartTimeType() {
   QString selectedType = m_uiForm.timeComboBox->currentText();
 
-  if (selectedType == "Start at First Good Data")
-  {
+  if (selectedType == "Start at First Good Data") {
     return FirstGoodData;
-  }
-  else if (selectedType == "Start at Time Zero")
-  {
+  } else if (selectedType == "Start at Time Zero") {
     return TimeZero;
-  }
-  else if (selectedType == "Custom Value")
-  {
+  } else if (selectedType == "Custom Value") {
     return Custom;
-  }
-  else
-  {
+  } else {
     // Just in case misspelled type or added a new one
     throw std::runtime_error("Unknown start time type selection");
   }
 }
 
 /**
- * Retrieve custom start time value. This only makes sense when getStartTimeType() is Custom.
+ * Retrieve custom start time value. This only makes sense when
+ * getStartTimeType() is Custom.
  * @return Value in the custom start time field
  */
-double MuonAnalysisOptionTab::getCustomStartTime()
-{
-  QLineEdit* w = m_uiForm.timeAxisStartAtInput;
+double MuonAnalysisOptionTab::getCustomStartTime() {
+  QLineEdit *w = m_uiForm.timeAxisStartAtInput;
 
   return getValidatedDouble(w, START_TIME_DEFAULT, "custom start time", g_log);
 }
 
 /**
- * Retrieve custom finish time value. If the value is not specified - returns EMPTY_DBL().
+ * Retrieve custom finish time value. If the value is not specified - returns
+ * EMPTY_DBL().
  * @return Value in the custom finish field or EMPTY_DBL()
  */
-double MuonAnalysisOptionTab::getCustomFinishTime()
-{
-  QLineEdit* w = m_uiForm.timeAxisFinishAtInput;
+double MuonAnalysisOptionTab::getCustomFinishTime() {
+  QLineEdit *w = m_uiForm.timeAxisFinishAtInput;
 
-  if (w->text().isEmpty())
-  {
+  if (w->text().isEmpty()) {
     return Mantid::EMPTY_DBL();
-  }
-  else
-  {
-    return getValidatedDouble(w, FINISH_TIME_DEFAULT, "custom finish time", g_log);
+  } else {
+    return getValidatedDouble(w, FINISH_TIME_DEFAULT, "custom finish time",
+                              g_log);
   }
 }
 
@@ -329,77 +323,62 @@ double MuonAnalysisOptionTab::getCustomFinishTime()
  * Returns rebin type as selected by user
  * @return Rebin type
  */
-MuonAnalysisOptionTab::RebinType MuonAnalysisOptionTab::getRebinType()
-{
+MuonAnalysisOptionTab::RebinType MuonAnalysisOptionTab::getRebinType() {
   QString selectedType = m_uiForm.rebinComboBox->currentText();
 
-  if (selectedType == "None")
-  {
+  if (selectedType == "None") {
     return NoRebin;
-  }
-  else if (selectedType == "Fixed")
-  {
+  } else if (selectedType == "Fixed") {
     return FixedRebin;
-  }
-  else if (selectedType == "Variable")
-  {
+  } else if (selectedType == "Variable") {
     return VariableRebin;
-  }
-  else
-  {
+  } else {
     throw std::runtime_error("Unknow rebin type selection");
   }
 }
 
 /**
- * Returns variable rebing params as set by user. Makes sense only if getRebinType() is VariableRebin
+ * Returns variable rebing params as set by user. Makes sense only if
+ * getRebinType() is VariableRebin
  * @return Rebin params string
  */
-std::string MuonAnalysisOptionTab::getRebinParams()
-{
-  QLineEdit* w = m_uiForm.binBoundaries;
+std::string MuonAnalysisOptionTab::getRebinParams() {
+  QLineEdit *w = m_uiForm.binBoundaries;
 
-  if (w->text().isEmpty())
-  {
+  if (w->text().isEmpty()) {
     g_log.warning("Binning parameters are empty. Reset to default value.");
     w->setText(VARIABLE_REBIN_DEFAULT);
     return VARIABLE_REBIN_DEFAULT.toStdString();
-  }
-  else
-  {
+  } else {
     return w->text().toStdString();
   }
 }
 
 /**
- * Returns rebin step size as set by user. Make sense only if getRebinType() is FixedRebin
+ * Returns rebin step size as set by user. Make sense only if getRebinType() is
+ * FixedRebin
  * @return Rebin step size
  */
-double MuonAnalysisOptionTab::getRebinStep()
-{
-  return getValidatedDouble(m_uiForm.optionStepSizeText, FIXED_REBIN_DEFAULT, "binning step", g_log);
+double MuonAnalysisOptionTab::getRebinStep() {
+  return getValidatedDouble(m_uiForm.optionStepSizeText, FIXED_REBIN_DEFAULT,
+                            "binning step", g_log);
 }
 
 /**
  * @return Currently selected new plot policy
  */
-MuonAnalysisOptionTab::NewPlotPolicy MuonAnalysisOptionTab::newPlotPolicy()
-{
+MuonAnalysisOptionTab::NewPlotPolicy MuonAnalysisOptionTab::newPlotPolicy() {
   QMap<QString, NewPlotPolicy> policyMap;
   policyMap["Create new window"] = NewWindow;
   policyMap["Use previous window"] = PreviousWindow;
 
   QString selectedPolicy = m_uiForm.newPlotPolicy->currentText();
-  if ( !policyMap.contains(selectedPolicy) )
-  {
+  if (!policyMap.contains(selectedPolicy)) {
     throw std::runtime_error("Unknown new plot policy selection");
-  }
-  else
-  {
+  } else {
     return policyMap[selectedPolicy];
   }
 }
-
 }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/ParseKeyValueString.cpp b/MantidQt/CustomInterfaces/src/ParseKeyValueString.cpp
index 31056835f1e619e110611f8ea012375b5757e3b5..e95c5ea084b0fdf48ebf716d49d94801ddf2584e 100644
--- a/MantidQt/CustomInterfaces/src/ParseKeyValueString.cpp
+++ b/MantidQt/CustomInterfaces/src/ParseKeyValueString.cpp
@@ -3,48 +3,48 @@
 #include <boost/algorithm/string.hpp>
 #include <boost/tokenizer.hpp>
 
-
 namespace MantidQt {
-  namespace CustomInterfaces {
+namespace CustomInterfaces {
 /**
-    Parses a string in the format `a = 1,b=2, c = "1,2,3,4", d = 5.0, e='a,b,c'` into a map of key/value pairs
+    Parses a string in the format `a = 1,b=2, c = "1,2,3,4", d = 5.0, e='a,b,c'`
+   into a map of key/value pairs
     @param str The input string
     @throws std::runtime_error on an invalid input string
     */
-    std::map<std::string, std::string> parseKeyValueString(const std::string &str) {
-      //Tokenise, using '\' as an escape character, ',' as a delimiter and " and ' as quote characters
-      boost::tokenizer <boost::escaped_list_separator<char>> tok(str,
-                                                                 boost::escaped_list_separator<char>("\\", ",", "\"'"));
-
-      std::map<std::string, std::string> kvp;
-
-      for (auto it = tok.begin(); it != tok.end(); ++it) {
-        std::vector<std::string> valVec;
-        boost::split(valVec, *it, boost::is_any_of("="));
-
-        if (valVec.size() > 1) {
-          //We split on all '='s. The first delimits the key, the rest are assumed to be part of the value
-          std::string key = valVec[0];
-          //Drop the key from the values vector
-          valVec.erase(valVec.begin());
-          //Join the remaining sections,
-          std::string value = boost::algorithm::join(valVec, "=");
-
-          //Remove any unwanted whitespace
-          boost::trim(key);
-          boost::trim(value);
-
-          if (key.empty() || value.empty())
-            throw std::runtime_error("Invalid key value pair, '" + *it + "'");
-
-
-          kvp[key] = value;
-        }
-        else {
-          throw std::runtime_error("Invalid key value pair, '" + *it + "'");
-        }
-      }
-      return kvp;
+std::map<std::string, std::string> parseKeyValueString(const std::string &str) {
+  // Tokenise, using '\' as an escape character, ',' as a delimiter and " and '
+  // as quote characters
+  boost::tokenizer<boost::escaped_list_separator<char>> tok(
+      str, boost::escaped_list_separator<char>("\\", ",", "\"'"));
+
+  std::map<std::string, std::string> kvp;
+
+  for (auto it = tok.begin(); it != tok.end(); ++it) {
+    std::vector<std::string> valVec;
+    boost::split(valVec, *it, boost::is_any_of("="));
+
+    if (valVec.size() > 1) {
+      // We split on all '='s. The first delimits the key, the rest are assumed
+      // to be part of the value
+      std::string key = valVec[0];
+      // Drop the key from the values vector
+      valVec.erase(valVec.begin());
+      // Join the remaining sections,
+      std::string value = boost::algorithm::join(valVec, "=");
+
+      // Remove any unwanted whitespace
+      boost::trim(key);
+      boost::trim(value);
+
+      if (key.empty() || value.empty())
+        throw std::runtime_error("Invalid key value pair, '" + *it + "'");
+
+      kvp[key] = value;
+    } else {
+      throw std::runtime_error("Invalid key value pair, '" + *it + "'");
     }
   }
+  return kvp;
+}
+}
 }
\ No newline at end of file
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/DataProcessorGenerateNotebook.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/DataProcessorGenerateNotebook.cpp
index 448e10d3f19f567a069df914da5a3c77b1693d08..27624267957f4155378f68c216c74432b30cc631 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/DataProcessorGenerateNotebook.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/DataProcessorGenerateNotebook.cpp
@@ -327,8 +327,7 @@ boost::tuple<std::string, std::string> postprocessGroupString(
   stitch_string << outputWSName;
   stitch_string << completeOutputProperties(
                        postprocessor.name(),
-                       postprocessor.numberOfOutputProperties())
-                << " = ";
+                       postprocessor.numberOfOutputProperties()) << " = ";
   stitch_string << postprocessor.name() << "(";
   stitch_string << postprocessor.inputProperty() << " = '";
   stitch_string << boost::algorithm::join(inputNames, ", ") << "'";
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/MeasurementItem.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/MeasurementItem.cpp
index e6b82c21ba2f65a94a962dc10089e585c0ef585c..b777af5555cadd7a019cf5523a4840df07fc9f80 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/MeasurementItem.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/MeasurementItem.cpp
@@ -14,10 +14,10 @@ namespace CustomInterfaces {
  * @param angle
  * @param run
  */
-MeasurementItem::MeasurementItem(const MeasurementItem::IDType &measurementItemId,
-                         const MeasurementItem::IDType &subId,
-                         const std::string &label, const std::string &type,
-                         const double angle, const std::string &run)
+MeasurementItem::MeasurementItem(
+    const MeasurementItem::IDType &measurementItemId,
+    const MeasurementItem::IDType &subId, const std::string &label,
+    const std::string &type, const double angle, const std::string &run)
     : m_measurementItemId(measurementItemId), m_subId(subId), m_label(label),
       m_type(type), m_angle(angle), m_run(run) {
 
@@ -54,13 +54,16 @@ MeasurementItem::~MeasurementItem() {}
  * InvalidMeasurement static creational method
  * @return Invalid measurement
  */
-MeasurementItem MeasurementItem::InvalidMeasurementItem(const std::string &why) {
+MeasurementItem
+MeasurementItem::InvalidMeasurementItem(const std::string &why) {
   return MeasurementItem(why);
 }
 
 bool MeasurementItem::isUseable() const { return m_whyUnuseable.empty(); }
 
-MeasurementItem::IDType MeasurementItem::id() const { return m_measurementItemId; }
+MeasurementItem::IDType MeasurementItem::id() const {
+  return m_measurementItemId;
+}
 
 MeasurementItem::IDType MeasurementItem::subId() const { return m_subId; }
 
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/ReflCatalogSearcher.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/ReflCatalogSearcher.cpp
index e6f207a74401a292f325e206964f911f9588b182..2c1d393cfe5e270c0ea75ab98ec4377bea993755 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/ReflCatalogSearcher.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/ReflCatalogSearcher.cpp
@@ -6,47 +6,42 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-
-  ITableWorkspace_sptr ReflCatalogSearcher::search(const std::string &text) {
-      auto sessions = CatalogManager::Instance().getActiveSessions();
-      if(sessions.empty())
-        throw std::runtime_error("You are not logged into any catalogs.");
-
-      const std::string sessionId = sessions.front()->getSessionId();
-
-      auto algSearch = AlgorithmManager::Instance().create("CatalogGetDataFiles");
-      algSearch->initialize();
-      algSearch->setChild(true);
-      algSearch->setLogging(false);
-      algSearch->setProperty("Session", sessionId);
-      algSearch->setProperty("InvestigationId", text);
-      algSearch->setProperty("OutputWorkspace", "_ReflSearchResults");
-      algSearch->execute();
-      ITableWorkspace_sptr results = algSearch->getProperty("OutputWorkspace");
-
-      //Now, tidy up the data
-      std::set<size_t> toRemove;
-      for(size_t i = 0; i < results->rowCount(); ++i)
-      {
-        std::string& run = results->String(i,0);
-
-        // Too short to be more than ".raw or .nxs"
-        if(run.size() < 5)
-        {
-          toRemove.insert(i);
-        }
-
-      }
-
-      //Sets are sorted so if we go from back to front we won't trip over ourselves
-      for(auto row = toRemove.rbegin(); row != toRemove.rend(); ++row)
-        results->removeRow(*row);
-
-      return results;
+namespace MantidQt {
+namespace CustomInterfaces {
+
+ITableWorkspace_sptr ReflCatalogSearcher::search(const std::string &text) {
+  auto sessions = CatalogManager::Instance().getActiveSessions();
+  if (sessions.empty())
+    throw std::runtime_error("You are not logged into any catalogs.");
+
+  const std::string sessionId = sessions.front()->getSessionId();
+
+  auto algSearch = AlgorithmManager::Instance().create("CatalogGetDataFiles");
+  algSearch->initialize();
+  algSearch->setChild(true);
+  algSearch->setLogging(false);
+  algSearch->setProperty("Session", sessionId);
+  algSearch->setProperty("InvestigationId", text);
+  algSearch->setProperty("OutputWorkspace", "_ReflSearchResults");
+  algSearch->execute();
+  ITableWorkspace_sptr results = algSearch->getProperty("OutputWorkspace");
+
+  // Now, tidy up the data
+  std::set<size_t> toRemove;
+  for (size_t i = 0; i < results->rowCount(); ++i) {
+    std::string &run = results->String(i, 0);
+
+    // Too short to be more than ".raw or .nxs"
+    if (run.size() < 5) {
+      toRemove.insert(i);
     }
   }
+
+  // Sets are sorted so if we go from back to front we won't trip over ourselves
+  for (auto row = toRemove.rbegin(); row != toRemove.rend(); ++row)
+    results->removeRow(*row);
+
+  return results;
+}
+}
 }
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/ReflGenericDataProcessorPresenterFactory.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/ReflGenericDataProcessorPresenterFactory.cpp
index 628c576d8f167fcbb59587154148cd99fd8c2f6f..0342228de3c2535f31cd2d506a14053a2933c7f4 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/ReflGenericDataProcessorPresenterFactory.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/ReflGenericDataProcessorPresenterFactory.cpp
@@ -6,104 +6,105 @@
 
 namespace MantidQt {
 namespace CustomInterfaces {
-  /**
-  * Creates a Reflectometry Data Processor Presenter
-  */
-  boost::shared_ptr<GenericDataProcessorPresenter> ReflGenericDataProcessorPresenterFactory::create() {
+/**
+* Creates a Reflectometry Data Processor Presenter
+*/
+boost::shared_ptr<GenericDataProcessorPresenter>
+ReflGenericDataProcessorPresenterFactory::create() {
 
-    // The whitelist, elements will appear in order in the table
-    // 'Run(s)' column will be linked to 'InputWorkspace' property
-    // 'Angle' column will be linked to 'ThetaIn'
-    // 'Transmission Run(s)' column will be linked to 'FirstTransmissionRun'
-    // 'Q min' column will be linked to 'MomentumTransferMinimum'
-    // 'Q max' column will be linked to 'MomentumTransferMaximum'
-    // 'dq/Q' column will be linked to 'MomentumTransferStep'
-    // 'Scale' column will be linked to 'ScaleFactor'
-    // Descriptions can also be added
-    DataProcessorWhiteList whitelist;
-    whitelist.addElement("Run(s)", "InputWorkspace",
-                         "<b>Sample runs to be processed.</b><br "
-                         "/><i>required</i><br />Runs may be given as run "
-                         "numbers or workspace names. Multiple runs may be "
-                         "added together by separating them with a '+'. <br "
-                         "/><br /><b>Example:</b> <samp>1234+1235+1236</samp>");
-    whitelist.addElement(
-        "Angle", "ThetaIn",
-        "<b>Angle used during the run.< / b><br / ><i>optional</i><br />Unit: "
-        "degrees<br />If left blank, this is set to the last value for 'THETA' "
-        "in the run's sample log. If multiple runs were given in the Run(s) "
-        "column, the first listed run's sample log will be used. <br /><br "
-        "/><b>Example:</b> <samp>0.7</samp>");
-    whitelist.addElement(
-        "Transmission Run(s)", "FirstTransmissionRun",
-        "<b>Transmission run(s) to use to normalise the sample runs.</b><br "
-        "/><i>optional</i><br />To specify two transmission runs, separate "
-        "them with a '+'. If left blank, the sample runs will be normalised "
-        "by monitor only.<br /><br /><b>Example:</b> <samp>1234+12345</samp>");
-    whitelist.addElement("Q min", "MomentumTransferMinimum",
-                         "<b>Minimum value of Q to be used</b><br "
-                         "/><i>optional</i><br />Unit: &#197;<sup>-1</sup><br "
-                         "/>Data with a value of Q lower than this will be "
-                         "discarded. If left blank, this is set to the lowest "
-                         "Q value found. This is useful for discarding noisy "
-                         "data. <br /><br /><b>Example:</b> <samp>0.1</samp>");
-    whitelist.addElement("Q max", "MomentumTransferMaximum",
-                         "<b>Maximum value of Q to be used</b><br "
-                         "/><i>optional</i><br />Unit: &#197;<sup>-1</sup><br "
-                         "/>Data with a value of Q higher than this will be "
-                         "discarded. If left blank, this is set to the highest "
-                         "Q value found. This is useful for discarding noisy "
-                         "data. <br /><br /><b>Example:</b> <samp>0.9</samp>");
-    whitelist.addElement(
-        "dQ/Q", "MomentumTransferStep",
-        "<b>Resolution used when rebinning</b><br /><i>optional</i><br />If "
-        "left blank, this is calculated for you using the CalculateResolution "
-        "algorithm. <br /><br /><b>Example:</b> <samp>0.9</samp>");
-    whitelist.addElement(
-        "Scale", "ScaleFactor",
-        "<b>Scaling factor</b><br /><i>required</i><br />The created IvsQ "
-        "workspaces will be Scaled by <samp>1/i</samp> where <samp>i</samp> is "
-        "the value of this column. <br /><br /><b>Example:</b> <samp>1</samp>");
+  // The whitelist, elements will appear in order in the table
+  // 'Run(s)' column will be linked to 'InputWorkspace' property
+  // 'Angle' column will be linked to 'ThetaIn'
+  // 'Transmission Run(s)' column will be linked to 'FirstTransmissionRun'
+  // 'Q min' column will be linked to 'MomentumTransferMinimum'
+  // 'Q max' column will be linked to 'MomentumTransferMaximum'
+  // 'dq/Q' column will be linked to 'MomentumTransferStep'
+  // 'Scale' column will be linked to 'ScaleFactor'
+  // Descriptions can also be added
+  DataProcessorWhiteList whitelist;
+  whitelist.addElement("Run(s)", "InputWorkspace",
+                       "<b>Sample runs to be processed.</b><br "
+                       "/><i>required</i><br />Runs may be given as run "
+                       "numbers or workspace names. Multiple runs may be "
+                       "added together by separating them with a '+'. <br "
+                       "/><br /><b>Example:</b> <samp>1234+1235+1236</samp>");
+  whitelist.addElement(
+      "Angle", "ThetaIn",
+      "<b>Angle used during the run.< / b><br / ><i>optional</i><br />Unit: "
+      "degrees<br />If left blank, this is set to the last value for 'THETA' "
+      "in the run's sample log. If multiple runs were given in the Run(s) "
+      "column, the first listed run's sample log will be used. <br /><br "
+      "/><b>Example:</b> <samp>0.7</samp>");
+  whitelist.addElement(
+      "Transmission Run(s)", "FirstTransmissionRun",
+      "<b>Transmission run(s) to use to normalise the sample runs.</b><br "
+      "/><i>optional</i><br />To specify two transmission runs, separate "
+      "them with a '+'. If left blank, the sample runs will be normalised "
+      "by monitor only.<br /><br /><b>Example:</b> <samp>1234+12345</samp>");
+  whitelist.addElement("Q min", "MomentumTransferMinimum",
+                       "<b>Minimum value of Q to be used</b><br "
+                       "/><i>optional</i><br />Unit: &#197;<sup>-1</sup><br "
+                       "/>Data with a value of Q lower than this will be "
+                       "discarded. If left blank, this is set to the lowest "
+                       "Q value found. This is useful for discarding noisy "
+                       "data. <br /><br /><b>Example:</b> <samp>0.1</samp>");
+  whitelist.addElement("Q max", "MomentumTransferMaximum",
+                       "<b>Maximum value of Q to be used</b><br "
+                       "/><i>optional</i><br />Unit: &#197;<sup>-1</sup><br "
+                       "/>Data with a value of Q higher than this will be "
+                       "discarded. If left blank, this is set to the highest "
+                       "Q value found. This is useful for discarding noisy "
+                       "data. <br /><br /><b>Example:</b> <samp>0.9</samp>");
+  whitelist.addElement(
+      "dQ/Q", "MomentumTransferStep",
+      "<b>Resolution used when rebinning</b><br /><i>optional</i><br />If "
+      "left blank, this is calculated for you using the CalculateResolution "
+      "algorithm. <br /><br /><b>Example:</b> <samp>0.9</samp>");
+  whitelist.addElement(
+      "Scale", "ScaleFactor",
+      "<b>Scaling factor</b><br /><i>required</i><br />The created IvsQ "
+      "workspaces will be Scaled by <samp>1/i</samp> where <samp>i</samp> is "
+      "the value of this column. <br /><br /><b>Example:</b> <samp>1</samp>");
 
-    // The data processor algorithm
-    DataProcessorProcessingAlgorithm processor(
-        /*The name of the algorithm */
-        "ReflectometryReductionOneAuto",
-        /*Prefixes to the output workspaces*/
-        std::vector<std::string>{"IvsQ_", "IvsLam_"},
-        /*The blacklist*/
-        std::set<std::string>{
-            "ThetaIn", "ThetaOut", "InputWorkspace", "OutputWorkspace",
-            "OutputWorkspaceWavelength", "FirstTransmissionRun",
-            "SecondTransmissionRun", "MomentumTransferMinimum",
-            "MomentumTransferMaximum", "MomentumTransferStep", "ScaleFactor"});
+  // The data processor algorithm
+  DataProcessorProcessingAlgorithm processor(
+      /*The name of the algorithm */
+      "ReflectometryReductionOneAuto",
+      /*Prefixes to the output workspaces*/
+      std::vector<std::string>{"IvsQ_", "IvsLam_"},
+      /*The blacklist*/
+      std::set<std::string>{
+          "ThetaIn", "ThetaOut", "InputWorkspace", "OutputWorkspace",
+          "OutputWorkspaceWavelength", "FirstTransmissionRun",
+          "SecondTransmissionRun", "MomentumTransferMinimum",
+          "MomentumTransferMaximum", "MomentumTransferStep", "ScaleFactor"});
 
-    // Pre-processing instructions as a map:
-    // Keys are the column names
-    // Values are the associated pre-processing algorithms
-    std::map<std::string, DataProcessorPreprocessingAlgorithm> preprocessMap = {
-        /*This pre-processor will be applied to column 'Run(s)'*/
-        {/*The name of the column*/ "Run(s)",
-         /*The pre-processor algorithm, 'Plus' by default*/ DataProcessorPreprocessingAlgorithm()},
-        /*This pre-processor will be applied to column 'Transmission Run(s)'*/
-        {/*The name of the column*/ "Transmission Run(s)",
-         /*The pre-processor algorithm: CreateTransmissionWorkspaceAuto*/
-         DataProcessorPreprocessingAlgorithm(
-             "CreateTransmissionWorkspaceAuto",
-             /*Prefix for the output workspace*/
-             "TRANS_",
-             /*Blacklist of properties we don't want to show*/
-             std::set<std::string>{"FirstTransmissionRun",
-                                   "SecondTransmissionRun", "OutputWorkspace"},
-             /*I don't want to show the transmission runs in the output ws
-                name*/
-             false)}};
+  // Pre-processing instructions as a map:
+  // Keys are the column names
+  // Values are the associated pre-processing algorithms
+  std::map<std::string, DataProcessorPreprocessingAlgorithm> preprocessMap = {
+      /*This pre-processor will be applied to column 'Run(s)'*/
+      {/*The name of the column*/ "Run(s)",
+       /*The pre-processor algorithm, 'Plus' by default*/ DataProcessorPreprocessingAlgorithm()},
+      /*This pre-processor will be applied to column 'Transmission Run(s)'*/
+      {/*The name of the column*/ "Transmission Run(s)",
+       /*The pre-processor algorithm: CreateTransmissionWorkspaceAuto*/
+       DataProcessorPreprocessingAlgorithm(
+           "CreateTransmissionWorkspaceAuto",
+           /*Prefix for the output workspace*/
+           "TRANS_",
+           /*Blacklist of properties we don't want to show*/
+           std::set<std::string>{"FirstTransmissionRun",
+                                 "SecondTransmissionRun", "OutputWorkspace"},
+           /*I don't want to show the transmission runs in the output ws
+              name*/
+           false)}};
 
-    // The post-processor algorithm's name, 'Stitch1DMany' by default
-    DataProcessorPostprocessingAlgorithm postprocessor;
+  // The post-processor algorithm's name, 'Stitch1DMany' by default
+  DataProcessorPostprocessingAlgorithm postprocessor;
 
-    return boost::make_shared<GenericDataProcessorPresenter>(
-        whitelist, preprocessMap, processor, postprocessor);
-  }
+  return boost::make_shared<GenericDataProcessorPresenter>(
+      whitelist, preprocessMap, processor, postprocessor);
+}
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/ReflTableSchema.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/ReflTableSchema.cpp
index c6082d7ca6d198c758560108611f2878c2f5d205..b2ff19d216041f4f42b3643eebdc8586af81c6a3 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/ReflTableSchema.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/ReflTableSchema.cpp
@@ -5,7 +5,7 @@ namespace MantidQt {
 namespace CustomInterfaces {
 namespace ReflTableSchema {
 
-ColumnIndexNameMap makeColumnIndexMap(){
+ColumnIndexNameMap makeColumnIndexMap() {
   return {{COL_RUNS, RUNS},
           {COL_ANGLE, ANGLE},
           {COL_TRANSMISSION, TRANSMISSION},
@@ -17,15 +17,14 @@ ColumnIndexNameMap makeColumnIndexMap(){
           {COL_OPTIONS, OPTIONS}};
 }
 
-ColumnNameIndexMap makeColumnNameMap(){
-    auto indexMap = makeColumnIndexMap();
-    ColumnNameIndexMap columnMap;
-    for(auto it = indexMap.begin(); it != indexMap.end(); ++it){
-      columnMap.emplace(it->second, it->first);
-    }
-    return columnMap;
+ColumnNameIndexMap makeColumnNameMap() {
+  auto indexMap = makeColumnIndexMap();
+  ColumnNameIndexMap columnMap;
+  for (auto it = indexMap.begin(); it != indexMap.end(); ++it) {
+    columnMap.emplace(it->second, it->first);
+  }
+  return columnMap;
 }
-
 }
 } // namespace CustomInterfaces
 } // namespace Mantid
diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/TransferResults.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/TransferResults.cpp
index 94c86b0407a29302db488b4b64a8f7414568e4de..6fee46731d1322cabc37ac1f03b6a8f49ca451a0 100644
--- a/MantidQt/CustomInterfaces/src/Reflectometry/TransferResults.cpp
+++ b/MantidQt/CustomInterfaces/src/Reflectometry/TransferResults.cpp
@@ -9,11 +9,13 @@ TransferResults::TransferResults(std::vector<COLUMN_MAP_TYPE> transferRuns,
   m_errorRuns = errorRuns;
 }
 
-std::vector<std::map<std::string, std::string> > TransferResults::getTransferRuns() {
+std::vector<std::map<std::string, std::string>>
+TransferResults::getTransferRuns() {
   return m_transferRuns;
 }
 
-std::vector<std::map<std::string, std::string> > TransferResults::getErrorRuns() {
+std::vector<std::map<std::string, std::string>>
+TransferResults::getErrorRuns() {
   return m_errorRuns;
 }
 
diff --git a/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp b/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
index e41439b5f60bf37e9cfa9260dbaa94e27da49405..c905d49d5395126690bedc03aea2edf669bd5638 100644
--- a/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
@@ -16,57 +16,55 @@
 
 #include <algorithm>
 
-
 namespace {
-  enum BINOPTIONS {CUSTOMBINNING, FROMMONITORS, SAVEASEVENTDATA};
+enum BINOPTIONS { CUSTOMBINNING, FROMMONITORS, SAVEASEVENTDATA };
 }
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 using namespace MantidQt::CustomInterfaces;
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace
-{
-  /// static logger for main window
-  Logger g_log("SANSAddFiles");
-
-  /**
-   * Helper function used to filter QListWidgetItems based on whether or not
-   * they contain only whitespace.
-   *
-   * @param item :: the QListWidgetItem to check
-   *
-   * @returns false if the item is empty or contains only whitespace, else true
-   */
-  bool isNonEmptyItem(const QListWidgetItem * item)
-  {
-    return item->data(Qt::WhatsThisRole).toString().trimmed().length() > 0;
-  }
+namespace {
+/// static logger for main window
+Logger g_log("SANSAddFiles");
+
+/**
+ * Helper function used to filter QListWidgetItems based on whether or not
+ * they contain only whitespace.
+ *
+ * @param item :: the QListWidgetItem to check
+ *
+ * @returns false if the item is empty or contains only whitespace, else true
+ */
+bool isNonEmptyItem(const QListWidgetItem *item) {
+  return item->data(Qt::WhatsThisRole).toString().trimmed().length() > 0;
+}
 }
 
 const QString SANSAddFiles::OUT_MSG("Output Directory: ");
 
-SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets) :
-  m_SANSForm(ParWidgets), parForm(parent), m_pythonRunning(false),
-  m_newOutDir(*this, &SANSAddFiles::changeOutputDir), m_customBinning(""),
-  m_customBinningText("Bin Settings: "), m_customBinningToolTip("Sets the bin options for custom binning"),
-  m_saveEventDataText("Additional Time Shifts: "),
-  m_saveEventDataToolTip("Set optional, comma-separated time shifts in seconds.\n"
-                         "You can either specify non or N-1 time shifts for N files.\n"
-                         "Note that the time shifts are relative to the time of the workspace which was added last.")
-{
+SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets)
+    : m_SANSForm(ParWidgets), parForm(parent), m_pythonRunning(false),
+      m_newOutDir(*this, &SANSAddFiles::changeOutputDir), m_customBinning(""),
+      m_customBinningText("Bin Settings: "),
+      m_customBinningToolTip("Sets the bin options for custom binning"),
+      m_saveEventDataText("Additional Time Shifts: "),
+      m_saveEventDataToolTip(
+          "Set optional, comma-separated time shifts in seconds.\n"
+          "You can either specify non or N-1 time shifts for N files.\n"
+          "Note that the time shifts are relative to the time of the workspace "
+          "which was added last.") {
   initLayout();
 
-  //get lists of suported extentions
+  // get lists of suported extentions
   IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Load");
   Property *prop = alg->getProperty("Filename");
   m_exts = prop->allowedValues();
-  //a log file must be copied across if it was a raw file, find out from the extention if a raw file was selected
+  // a log file must be copied across if it was a raw file, find out from the
+  // extention if a raw file was selected
   alg = AlgorithmManager::Instance().create("LoadRaw");
   prop = alg->getProperty("Filename");
   m_rawExts = prop->allowedValues();
@@ -74,56 +72,55 @@ SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets) :
   ConfigService::Instance().addObserver(m_newOutDir);
 }
 
-SANSAddFiles::~SANSAddFiles()
-{
-  try
-  {
+SANSAddFiles::~SANSAddFiles() {
+  try {
     ConfigService::Instance().removeObserver(m_newOutDir);
     saveSettings();
-  }
-  catch(...)
-  {
-    //we've cleaned up the best we can, move on
+  } catch (...) {
+    // we've cleaned up the best we can, move on
   }
 }
 
-//Connect signals and setup widgets
-void SANSAddFiles::initLayout()
-{
+// Connect signals and setup widgets
+void SANSAddFiles::initLayout() {
   connect(m_SANSForm->new2Add_edit, SIGNAL(returnPressed()), this,
-    SLOT(add2Runs2Add()));
-  
-  //the runAsPythonScript() signal needs to get to Qtiplot, here it is connected to the parent, which is connected to Qtiplot
-  connect(this, SIGNAL(runAsPythonScript(const QString&, bool)),
-          parForm, SIGNAL(runAsPythonScript(const QString&, bool)));
+          SLOT(add2Runs2Add()));
+
+  // the runAsPythonScript() signal needs to get to Qtiplot, here it is
+  // connected to the parent, which is connected to Qtiplot
+  connect(this, SIGNAL(runAsPythonScript(const QString &, bool)), parForm,
+          SIGNAL(runAsPythonScript(const QString &, bool)));
 
   insertListFront("");
 
-  connect(m_SANSForm->toAdd_List, SIGNAL(itemChanged(QListWidgetItem *)),
-    this, SLOT(setCellData(QListWidgetItem *)));
-  
+  connect(m_SANSForm->toAdd_List, SIGNAL(itemChanged(QListWidgetItem *)), this,
+          SLOT(setCellData(QListWidgetItem *)));
+
   // Unfortunately, three signals are needed to track everything that could
   // happen to our QListWidget; this covers adding and removing items as
   // well changes to existing items and clearing all items.
   connect(m_SANSForm->toAdd_List->model(),
-          SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),
-          this, SLOT(enableSumming()));
+          SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this,
+          SLOT(enableSumming()));
   connect(m_SANSForm->toAdd_List->model(),
-          SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
-          this, SLOT(enableSumming()));
-  connect(m_SANSForm->toAdd_List->model(),
-          SIGNAL(modelReset()),
-          this, SLOT(enableSumming()));
+          SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this,
+          SLOT(enableSumming()));
+  connect(m_SANSForm->toAdd_List->model(), SIGNAL(modelReset()), this,
+          SLOT(enableSumming()));
 
   enableSumming();
 
-  //buttons on the Add Runs tab
+  // buttons on the Add Runs tab
   connect(m_SANSForm->add_Btn, SIGNAL(clicked()), this, SLOT(add2Runs2Add()));
-  connect(m_SANSForm->sum_Btn, SIGNAL(clicked()), this, SLOT(runPythonAddFiles()));
-  connect(m_SANSForm->summedPath_Btn, SIGNAL(clicked()), this, SLOT(outPathSel()));
-  connect(m_SANSForm->browse_to_add_Btn, SIGNAL(clicked()), this, SLOT(new2AddBrowse()));
+  connect(m_SANSForm->sum_Btn, SIGNAL(clicked()), this,
+          SLOT(runPythonAddFiles()));
+  connect(m_SANSForm->summedPath_Btn, SIGNAL(clicked()), this,
+          SLOT(outPathSel()));
+  connect(m_SANSForm->browse_to_add_Btn, SIGNAL(clicked()), this,
+          SLOT(new2AddBrowse()));
   connect(m_SANSForm->clear_Btn, SIGNAL(clicked()), this, SLOT(clearClicked()));
-  connect(m_SANSForm->remove_Btn, SIGNAL(clicked()), this, SLOT(removeSelected()));
+  connect(m_SANSForm->remove_Btn, SIGNAL(clicked()), this,
+          SLOT(removeSelected()));
 
   readSettings();
 
@@ -132,43 +129,47 @@ void SANSAddFiles::initLayout()
   setOutDir(ConfigService::Instance().getString("defaultsave.directory"));
 
   // Track changes in the selection of the histogram option
-  connect(m_SANSForm->comboBox_histogram_choice, SIGNAL(currentIndexChanged (int)), this, SLOT(onCurrentIndexChangedForHistogramChoice(int)));
+  connect(m_SANSForm->comboBox_histogram_choice,
+          SIGNAL(currentIndexChanged(int)), this,
+          SLOT(onCurrentIndexChangedForHistogramChoice(int)));
 
-  // Track changes in the overlay options 
+  // Track changes in the overlay options
   m_SANSForm->overlayCheckBox->setEnabled(false);
   m_customBinning = m_SANSForm->eventToHistBinning->text();
-  connect(m_SANSForm->overlayCheckBox, SIGNAL(stateChanged(int)), this, SLOT(onStateChangedForOverlayCheckBox(int)));
+  connect(m_SANSForm->overlayCheckBox, SIGNAL(stateChanged(int)), this,
+          SLOT(onStateChangedForOverlayCheckBox(int)));
 }
 /**
  * Restore previous input
  */
-void SANSAddFiles::readSettings()
-{
+void SANSAddFiles::readSettings() {
   QSettings value_store;
   value_store.beginGroup("CustomInterfaces/AddRuns");
-  
+
   m_SANSForm->loadSeparateEntries->setChecked(
-    value_store.value("Minimise_memory", false).toBool());
+      value_store.value("Minimise_memory", false).toBool());
 
   value_store.endGroup();
 }
 /**
  * Save input for future use
  */
-void SANSAddFiles::saveSettings()
-{
+void SANSAddFiles::saveSettings() {
   QSettings value_store;
   value_store.beginGroup("CustomInterfaces/AddRuns");
-  value_store.setValue(
-    "Minimise_memory", m_SANSForm->loadSeparateEntries->isChecked());
+  value_store.setValue("Minimise_memory",
+                       m_SANSForm->loadSeparateEntries->isChecked());
 }
 /** sets tool tip strings for the components on the form
 */
-void SANSAddFiles::setToolTips()
-{
-  m_SANSForm->summedPath_lb->setToolTip("The output files from summing the workspaces\nwill be saved to this directory");
-  m_SANSForm->summedPath_Btn->setToolTip("Set the directories used both for loading and\nsaving run data");
-  m_SANSForm->loadSeparateEntries->setToolTip("Where possible load a minimum amount into\nmemory at any time");
+void SANSAddFiles::setToolTips() {
+  m_SANSForm->summedPath_lb->setToolTip("The output files from summing the "
+                                        "workspaces\nwill be saved to this "
+                                        "directory");
+  m_SANSForm->summedPath_Btn->setToolTip(
+      "Set the directories used both for loading and\nsaving run data");
+  m_SANSForm->loadSeparateEntries->setToolTip(
+      "Where possible load a minimum amount into\nmemory at any time");
 
   m_SANSForm->add_Btn->setToolTip("Click here to do the sum");
   m_SANSForm->clear_Btn->setToolTip("Clear the run files to sum box");
@@ -181,8 +182,7 @@ void SANSAddFiles::setToolTips()
 *  @param[in] text the text to insert
 *  @return a pointer to the inserted widget
 */
-QListWidgetItem* SANSAddFiles::insertListFront(const QString &text)
-{
+QListWidgetItem *SANSAddFiles::insertListFront(const QString &text) {
   QListWidgetItem *newItem = new QListWidgetItem(text);
   newItem->setFlags(newItem->flags() | Qt::ItemIsEditable);
   m_SANSForm->toAdd_List->insertItem(0, newItem);
@@ -192,64 +192,62 @@ QListWidgetItem* SANSAddFiles::insertListFront(const QString &text)
 *  that users see
 *  @param dir :: full path of the output directory
 */
-void SANSAddFiles::setOutDir(std::string dir)
-{
+void SANSAddFiles::setOutDir(std::string dir) {
   m_outDir = QString::fromStdString(dir);
-  m_SANSForm->summedPath_lb->setText(OUT_MSG+m_outDir);
+  m_SANSForm->summedPath_lb->setText(OUT_MSG + m_outDir);
 }
 /** Update the output directory label if the Mantid system output
 *  directory has changed
-*  @param pDirInfo :: a pointer to an object with the output directory name in it
+*  @param pDirInfo :: a pointer to an object with the output directory name in
+* it
 */
-void SANSAddFiles::changeOutputDir(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo)
-{
-  if ( pDirInfo->key() == "defaultsave.directory" )
-  {
+void SANSAddFiles::changeOutputDir(
+    Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo) {
+  if (pDirInfo->key() == "defaultsave.directory") {
     setOutDir(pDirInfo->curValue());
   }
 }
 /**Moves the entry in the line edit new2Add_edit to the
 *  listbox toAdd_List, expanding any run number lists
 */
-void SANSAddFiles::add2Runs2Add()
-{
-  //split comma separated file names or run numbers into a list
-  ArrayProperty<std::string> commaSep("unusedName",
-    m_SANSForm->new2Add_edit->text().toStdString() );
+void SANSAddFiles::add2Runs2Add() {
+  // split comma separated file names or run numbers into a list
+  ArrayProperty<std::string> commaSep(
+      "unusedName", m_SANSForm->new2Add_edit->text().toStdString());
   const std::vector<std::string> nam = commaSep;
 
-  for(std::vector<std::string>::const_iterator i=nam.begin();i!=nam.end();++i)
-  {//each comma separated item could be a range of run numbers specified with a ':' or '-' 
+  for (std::vector<std::string>::const_iterator i = nam.begin(); i != nam.end();
+       ++i) { // each comma separated item could be a range of run numbers
+              // specified with a ':' or '-'
     QStringList ranges;
     std::vector<int> runNumRanges;
-    try
-    {//if the entry is in the form 454:456, runNumRanges will be filled with the integers ({454, 455, 456}) otherwise it will throw
+    try { // if the entry is in the form 454:456, runNumRanges will be filled
+          // with the integers ({454, 455, 456}) otherwise it will throw
       appendValue(*i, runNumRanges);
       std::vector<int>::const_iterator num = runNumRanges.begin();
-      for( ; num != runNumRanges.end(); ++num)
-      {
+      for (; num != runNumRanges.end(); ++num) {
         ranges.append(QString::number(*num));
       }
-    }
-    catch(boost::bad_lexical_cast &)
-    {//this means that we don't have a list of integers, treat it as full (and valid) filename
+    } catch (boost::bad_lexical_cast &) { // this means that we don't have a
+                                          // list of integers, treat it as full
+                                          // (and valid) filename
       ranges.append(QString::fromStdString(*i));
     }
 
-    for(QStringList::const_iterator k = ranges.begin(); k != ranges.end(); ++k)
-    {
-      //Don't display the full file path in the box, it's too long
+    for (QStringList::const_iterator k = ranges.begin(); k != ranges.end();
+         ++k) {
+      // Don't display the full file path in the box, it's too long
       QListWidgetItem *newL = insertListFront(QFileInfo(*k).fileName());
       newL->setData(Qt::WhatsThisRole, QVariant(*k));
-      //Put the full path in the tooltip so people can see it if they want to
-      //do this with the file finding functionality of the FileProperty
+      // Put the full path in the tooltip so people can see it if they want to
+      // do this with the file finding functionality of the FileProperty
       FileProperty search("dummy", k->toStdString(), FileProperty::Load,
-        std::vector<std::string>(), Direction::Input);
-      if ( search.isValid() == "" )
-      {//this means the file was found
+                          std::vector<std::string>(), Direction::Input);
+      if (search.isValid() == "") { // this means the file was found
         newL->setToolTip(QString::fromStdString(search.value()));
 
-        // If we don't have an event workspace data set, then we disable the event options
+        // If we don't have an event workspace data set, then we disable the
+        // event options
         if (!isEventWorkspace(QString::fromStdString(search.value()))) {
           setBinningOptions(false);
         }
@@ -260,21 +258,22 @@ void SANSAddFiles::add2Runs2Add()
 }
 /** Executes the add_runs() function inside the SANSadd2 script
 */
-void SANSAddFiles::runPythonAddFiles()
-{
-  // Check the validty of the input for the 
+void SANSAddFiles::runPythonAddFiles() {
+  // Check the validty of the input for the
   if (!checkValidityTimeShiftsForAddedEventFiles()) {
     return;
   }
 
-  if (m_pythonRunning)
-  {//it is only possible to run one python script at a time
+  if (m_pythonRunning) { // it is only possible to run one python script at a
+                         // time
     return;
   }
 
-  if( ConfigService::Instance().getString("defaultsave.directory").empty() )
-  {
-    QMessageBox::critical(this, "Setting Required", "Unable to add runs until a default save directory has been specified.  Please set this using the Manage User Directories dialog.");
+  if (ConfigService::Instance().getString("defaultsave.directory").empty()) {
+    QMessageBox::critical(this, "Setting Required",
+                          "Unable to add runs until a default save directory "
+                          "has been specified.  Please set this using the "
+                          "Manage User Directories dialog.");
     return;
   }
 
@@ -282,89 +281,86 @@ void SANSAddFiles::runPythonAddFiles()
 
   QString code_torun = "import SANSadd2\n";
   code_torun += "print SANSadd2.add_runs((";
-  //there are multiple file list inputs that can be filled in loop through them
-  for(int i = 0; i < m_SANSForm->toAdd_List->count(); ++i )
-  {
-     QString filename =
-      m_SANSForm->toAdd_List->item(i)->data(Qt::WhatsThisRole).toString();
-    //allow but do nothing with empty entries
-    if ( ! filename.isEmpty() )
-    {
+  // there are multiple file list inputs that can be filled in loop through them
+  for (int i = 0; i < m_SANSForm->toAdd_List->count(); ++i) {
+    QString filename =
+        m_SANSForm->toAdd_List->item(i)->data(Qt::WhatsThisRole).toString();
+    // allow but do nothing with empty entries
+    if (!filename.isEmpty()) {
       // Make sure that the file separators are valid
       filename.replace("\\", "/");
-      code_torun += "'"+filename+"',";
+      code_torun += "'" + filename + "',";
     }
   }
-  if ( code_torun.endsWith(',') )
-  {//we've made a comma separated list, there can be no comma at the end
-    code_torun.truncate(code_torun.size()-1);
+  if (code_torun.endsWith(',')) { // we've made a comma separated list, there
+                                  // can be no comma at the end
+    code_torun.truncate(code_torun.size() - 1);
   }
-  //pass the current instrument
-  code_torun += "),'"+m_SANSForm->inst_opt->currentText()+"', '";
-  QString ext = m_SANSForm->file_opt->itemData(
-    m_SANSForm->file_opt->currentIndex()).toString();
-  code_torun += ext+"'";
-  
+  // pass the current instrument
+  code_torun += "),'" + m_SANSForm->inst_opt->currentText() + "', '";
+  QString ext =
+      m_SANSForm->file_opt->itemData(m_SANSForm->file_opt->currentIndex())
+          .toString();
+  code_torun += ext + "'";
+
   code_torun += ", rawTypes=(";
   std::vector<std::string>::const_iterator end = m_rawExts.end();
-  for(std::vector<std::string>::const_iterator j=m_rawExts.begin(); j != end; ++j)
-  {
-    code_torun += "'"+QString::fromStdString(*j)+"',";
+  for (std::vector<std::string>::const_iterator j = m_rawExts.begin(); j != end;
+       ++j) {
+    code_torun += "'" + QString::fromStdString(*j) + "',";
   }
-  //remove the comma that would remain at the end of the list
-  code_torun.truncate(code_torun.length()-1);
+  // remove the comma that would remain at the end of the list
+  code_torun.truncate(code_torun.length() - 1);
   code_torun += ")";
-  
-  QString lowMem = m_SANSForm->loadSeparateEntries->isChecked()?"True":"False";
-  code_torun += ", lowMem="+lowMem;
 
-  QString overlay = m_SANSForm->overlayCheckBox->isChecked()?"True":"False";
-  // In case of event data, check if the user either wants 
+  QString lowMem =
+      m_SANSForm->loadSeparateEntries->isChecked() ? "True" : "False";
+  code_torun += ", lowMem=" + lowMem;
+
+  QString overlay = m_SANSForm->overlayCheckBox->isChecked() ? "True" : "False";
+  // In case of event data, check if the user either wants
   // 0. Custom historgram binning
   // 1. A binning which is set by the data set
   // 2. To save the actual event data
-  switch (m_SANSForm->comboBox_histogram_choice->currentIndex())
-  {
-    case CUSTOMBINNING:
-      code_torun += ", binning='" + m_SANSForm->eventToHistBinning->text() + "'";
-      break;
-    case FROMMONITORS:
-      break;
-    case SAVEASEVENTDATA:
-      code_torun += ", saveAsEvent=True";
-      code_torun += ", isOverlay=" + overlay;
-      code_torun += ", time_shifts="+ createPythonStringList(m_SANSForm->eventToHistBinning->text());
-      break;
-    default:
-      break;
+  switch (m_SANSForm->comboBox_histogram_choice->currentIndex()) {
+  case CUSTOMBINNING:
+    code_torun += ", binning='" + m_SANSForm->eventToHistBinning->text() + "'";
+    break;
+  case FROMMONITORS:
+    break;
+  case SAVEASEVENTDATA:
+    code_torun += ", saveAsEvent=True";
+    code_torun += ", isOverlay=" + overlay;
+    code_torun +=
+        ", time_shifts=" +
+        createPythonStringList(m_SANSForm->eventToHistBinning->text());
+    break;
+  default:
+    break;
   }
 
   code_torun += ")\n";
 
-  g_log.debug() << "Executing Python: \n" << code_torun.toStdString() << std::endl;
+  g_log.debug() << "Executing Python: \n" << code_torun.toStdString()
+                << std::endl;
 
   m_SANSForm->sum_Btn->setEnabled(false);
   m_pythonRunning = true;
 
-  //call the algorithms by executing the above script as Python
+  // call the algorithms by executing the above script as Python
   QString status = runPythonCode(code_torun, false);
-  
+
   // reset the controls and display any errors
   m_SANSForm->sum_Btn->setEnabled(true);
   m_pythonRunning = false;
-  if (status.startsWith("The following file has been created:"))
-  {
+  if (status.startsWith("The following file has been created:")) {
     QMessageBox::information(this, "Files summed", status);
-  }
-  else if (status.startsWith("Error copying log file:"))
-  {
+  } else if (status.startsWith("Error copying log file:")) {
     QMessageBox::warning(this, "Error adding files", status);
-  }
-  else
-  {
-    if (status.isEmpty())
-    {
-      status = "Could not sum files, there may be more\ninformation in the Results Log window";
+  } else {
+    if (status.isEmpty()) {
+      status = "Could not sum files, there may be more\ninformation in the "
+               "Results Log window";
     }
     QMessageBox::critical(this, "Error adding files", status);
   }
@@ -372,50 +368,48 @@ void SANSAddFiles::runPythonAddFiles()
 /** This slot opens a manage user directories dialog to allowing the default
 *  output directory to be changed
 */
-void SANSAddFiles::outPathSel()
-{
+void SANSAddFiles::outPathSel() {
   MantidQt::API::ManageUserDirectories::openUserDirsDialog(this);
 }
 /** This slot opens a file browser allowing a user select files, which is
 * copied into the new2Add_edit ready to be copied to the listbox (toAdd_List)
 */
-void SANSAddFiles::new2AddBrowse()
-{
+void SANSAddFiles::new2AddBrowse() {
   QSettings prevVals;
   prevVals.beginGroup("CustomInterfaces/SANSRunWindow/AddRuns");
-  //get the previous data input directory or, if there wasn't one, the first directory of on the default load path
+  // get the previous data input directory or, if there wasn't one, the first
+  // directory of on the default load path
   std::string d0 = ConfigService::Instance().getDataSearchDirs()[0];
-  QString dir = prevVals.value("InPath",QString::fromStdString(d0)).toString();
-  
-	QString fileFilter = "Files (";
+  QString dir = prevVals.value("InPath", QString::fromStdString(d0)).toString();
+
+  QString fileFilter = "Files (";
 
   std::vector<std::string>::const_iterator end = m_exts.end();
-  for(std::vector<std::string>::const_iterator i = m_exts.begin(); i != end; ++i)
-  {
-    fileFilter += " *"+QString::fromStdString(*i);
+  for (std::vector<std::string>::const_iterator i = m_exts.begin(); i != end;
+       ++i) {
+    fileFilter += " *" + QString::fromStdString(*i);
   }
 
   fileFilter += ")";
   const QStringList files =
-    QFileDialog::getOpenFileNames(parForm, "Select files", dir, fileFilter);
+      QFileDialog::getOpenFileNames(parForm, "Select files", dir, fileFilter);
 
-  if( ! files.isEmpty() )
-  {
-    // next time the user clicks browse they will see the directory that they last loaded a file from
+  if (!files.isEmpty()) {
+    // next time the user clicks browse they will see the directory that they
+    // last loaded a file from
     QFileInfo defPath(files[0]);
     prevVals.setValue("InPath", defPath.absoluteDir().absolutePath());
-    //join turns the list into a single string with the entries seperated, in this case, by ,
+    // join turns the list into a single string with the entries seperated, in
+    // this case, by ,
     m_SANSForm->new2Add_edit->setText(files.join(", "));
   }
 }
 /** Normally in responce to an edit this sets data associated with the cell
 *  to the cells text and removes the tooltip
 */
-void SANSAddFiles::setCellData(QListWidgetItem *)
-{
-  QListWidgetItem* editting = m_SANSForm->toAdd_List->currentItem();
-  if (editting)
-  {
+void SANSAddFiles::setCellData(QListWidgetItem *) {
+  QListWidgetItem *editting = m_SANSForm->toAdd_List->currentItem();
+  if (editting) {
     editting->setData(Qt::WhatsThisRole, QVariant(editting->text()));
     editting->setToolTip("");
   }
@@ -423,18 +417,15 @@ void SANSAddFiles::setCellData(QListWidgetItem *)
 /** Called when the clear button is clicked it clears the list of file
 * names to add table
 */
-void SANSAddFiles::clearClicked()
-{
+void SANSAddFiles::clearClicked() {
   m_SANSForm->toAdd_List->clear();
   insertListFront("");
   setBinningOptions(true);
 }
 
-void SANSAddFiles::removeSelected()
-{
-  QList<QListWidgetItem*> sels = m_SANSForm->toAdd_List->selectedItems();
-  while( sels.count() > 0 )
-  {
+void SANSAddFiles::removeSelected() {
+  QList<QListWidgetItem *> sels = m_SANSForm->toAdd_List->selectedItems();
+  while (sels.count() > 0) {
     int selRow = m_SANSForm->toAdd_List->row(sels.front());
     delete m_SANSForm->toAdd_List->takeItem(selRow);
     sels = m_SANSForm->toAdd_List->selectedItems();
@@ -449,45 +440,46 @@ void SANSAddFiles::removeSelected()
 /**
  * Enables/disables the "Sum" button based on whether there are files to sum.
  */
-void SANSAddFiles::enableSumming()
-{
-  const auto allItems = m_SANSForm->toAdd_List->findItems("*", Qt::MatchWildcard);
-  const auto nonEmptyItemsCount = std::count_if(
-    allItems.begin(), allItems.end(), isNonEmptyItem
-  );
+void SANSAddFiles::enableSumming() {
+  const auto allItems =
+      m_SANSForm->toAdd_List->findItems("*", Qt::MatchWildcard);
+  const auto nonEmptyItemsCount =
+      std::count_if(allItems.begin(), allItems.end(), isNonEmptyItem);
 
   m_SANSForm->sum_Btn->setEnabled(nonEmptyItemsCount > 1);
 }
 
 /**
- * Reacts to changges of the combo box selection for the histogram options for event data
+ * Reacts to changges of the combo box selection for the histogram options for
+ * event data
  * @param index the new index of the combo box.
  */
-void SANSAddFiles::onCurrentIndexChangedForHistogramChoice(int index) 
-{
+void SANSAddFiles::onCurrentIndexChangedForHistogramChoice(int index) {
   // Set the overlay checkbox enabled or disabled
   // Set the input field enabled or disabled
-  switch(index) {
-    case CUSTOMBINNING: 
-      m_SANSForm->overlayCheckBox->setEnabled(false);
-      setHistogramUiLogic(m_customBinningText, m_customBinningToolTip, m_customBinning, true);
-      break;
-    case FROMMONITORS:
-      setHistogramUiLogic(m_customBinningText, m_customBinningToolTip, m_customBinning, false);
-      setInputEnabled(false);
-      break;
-    case SAVEASEVENTDATA:
-      m_customBinning = this->m_SANSForm->eventToHistBinning->text();
-      m_SANSForm->eventToHistBinning->setText("");
-
-      setHistogramUiLogic(m_saveEventDataText, m_saveEventDataToolTip, "", true);
-      m_SANSForm->overlayCheckBox->setEnabled(true);
-
-      setInputEnabled(m_SANSForm->overlayCheckBox->isChecked());
-      break;
-    default:
-      setInputEnabled(false);
-      break;
+  switch (index) {
+  case CUSTOMBINNING:
+    m_SANSForm->overlayCheckBox->setEnabled(false);
+    setHistogramUiLogic(m_customBinningText, m_customBinningToolTip,
+                        m_customBinning, true);
+    break;
+  case FROMMONITORS:
+    setHistogramUiLogic(m_customBinningText, m_customBinningToolTip,
+                        m_customBinning, false);
+    setInputEnabled(false);
+    break;
+  case SAVEASEVENTDATA:
+    m_customBinning = this->m_SANSForm->eventToHistBinning->text();
+    m_SANSForm->eventToHistBinning->setText("");
+
+    setHistogramUiLogic(m_saveEventDataText, m_saveEventDataToolTip, "", true);
+    m_SANSForm->overlayCheckBox->setEnabled(true);
+
+    setInputEnabled(m_SANSForm->overlayCheckBox->isChecked());
+    break;
+  default:
+    setInputEnabled(false);
+    break;
   }
 }
 
@@ -505,11 +497,14 @@ void SANSAddFiles::onStateChangedForOverlayCheckBox(int state) {
 bool SANSAddFiles::checkValidityTimeShiftsForAddedEventFiles() {
   bool state = true;
 
-  if (m_SANSForm->comboBox_histogram_choice->currentIndex() == SAVEASEVENTDATA && m_SANSForm->overlayCheckBox->isChecked()) {
+  if (m_SANSForm->comboBox_histogram_choice->currentIndex() ==
+          SAVEASEVENTDATA &&
+      m_SANSForm->overlayCheckBox->isChecked()) {
     QString code_torun = "import ISISCommandInterface as i\n";
     code_torun += "i.check_time_shifts_for_added_event_files(number_of_files=";
     code_torun += QString::number(m_SANSForm->toAdd_List->count() - 1);
-    code_torun += ", time_shifts='" + m_SANSForm->eventToHistBinning->text() + "')\n";
+    code_torun +=
+        ", time_shifts='" + m_SANSForm->eventToHistBinning->text() + "')\n";
 
     QString status = runPythonCode(code_torun, false);
     if (!status.isEmpty()) {
@@ -531,7 +526,8 @@ bool SANSAddFiles::checkValidityTimeShiftsForAddedEventFiles() {
  * @param lineEditText :: text for the line edit field
  * @param enabled :: if the input should be enabled.
  */
-void SANSAddFiles::setHistogramUiLogic(QString label, QString toolTip, QString lineEditText, bool enabled) {
+void SANSAddFiles::setHistogramUiLogic(QString label, QString toolTip,
+                                       QString lineEditText, bool enabled) {
   // Line edit field
   m_SANSForm->eventToHistBinning->setText(lineEditText);
   m_SANSForm->eventToHistBinning->setToolTip(toolTip);
@@ -544,7 +540,8 @@ void SANSAddFiles::setHistogramUiLogic(QString label, QString toolTip, QString l
 }
 
 /**
- * Enables or disables the line editr field for histograms and time shifts, as well 
+ * Enables or disables the line editr field for histograms and time shifts, as
+ * well
  * as the corresponding labels
  * @param enabled :: is enabled or not
  */
@@ -576,7 +573,8 @@ QString SANSAddFiles::createPythonStringList(QString inputString) {
     formattedString += quotationMark + *it + quotationMark + delimiter;
   }
 
-  formattedString.remove(formattedString.length()-delimiter.length(), delimiter.length());
+  formattedString.remove(formattedString.length() - delimiter.length(),
+                         delimiter.length());
   formattedString += finalizer;
   return formattedString;
 }
@@ -592,11 +590,11 @@ bool SANSAddFiles::isEventWorkspace(QString fileName) {
   QString code_torun = "import ISISCommandInterface as i\n";
   code_torun += "i.check_if_event_workspace(file_name='";
   code_torun += fileName;
-  code_torun += + "')\n";
+  code_torun += +"')\n";
 
   auto status = runPythonCode(code_torun, false);
   if (status.contains(m_constants.getPythonTrueKeyword())) {
-      isEvent = true;
+    isEvent = true;
   }
   return isEvent;
 }
@@ -620,9 +618,9 @@ void SANSAddFiles::setBinningOptions(bool enable) {
 bool SANSAddFiles::existNonEventFiles() {
   auto elements = m_SANSForm->toAdd_List->count();
   for (int i = 0; i < elements; ++i) {
-     auto  fileName = m_SANSForm->toAdd_List->item(i)->data(Qt::WhatsThisRole).toString();
-    if ( !fileName.isEmpty() )
-    {
+    auto fileName =
+        m_SANSForm->toAdd_List->item(i)->data(Qt::WhatsThisRole).toString();
+    if (!fileName.isEmpty()) {
       // Make sure that the file separators are valid
       fileName.replace("\\", "/");
       // Run the check
@@ -635,6 +633,5 @@ bool SANSAddFiles::existNonEventFiles() {
   return false;
 }
 
-
-}//namespace CustomInterfaces
-}//namespace MantidQt
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/SANSBackgroundCorrectionWidget.cpp b/MantidQt/CustomInterfaces/src/SANSBackgroundCorrectionWidget.cpp
index 0d3161ef3a19bd5cd646d4eb4415e834d2b90235..7ffdc7dcf2bb1fc7583afa0b119b18114db03324 100644
--- a/MantidQt/CustomInterfaces/src/SANSBackgroundCorrectionWidget.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSBackgroundCorrectionWidget.cpp
@@ -85,22 +85,21 @@ void SANSBackgroundCorrectionWidget::setDarkRunSettingForTimeMonitors(
   m_ui.bckgnd_cor_mon_time_mon_num_line_edit->setText(setting.getMonNumber());
 }
 
-
 /**
 * Set the dark run settings for uamp-based subtractions for detectors
 * @param setting: the dark run settings for uamp-based subtractions, ie when we
 * want
 */
 void SANSBackgroundCorrectionWidget::setDarkRunSettingForUampDetectors(
-  SANSBackgroundCorrectionSettings setting) {
+    SANSBackgroundCorrectionSettings setting) {
   if (!hasRunNumber(setting)) {
     return;
   }
 
   if (setting.getUseMon()) {
     g_log.warning("SANSBackgroundCorrectionWidget: Trying to pass a background "
-      "correction "
-      "setting of a monitor to a detector display.");
+                  "correction "
+                  "setting of a monitor to a detector display.");
     return;
   }
   m_ui.bckgnd_cor_det_uamp_use_check_box->setChecked(true);
@@ -148,10 +147,9 @@ SANSBackgroundCorrectionWidget::getDarkRunSettingForTimeDetectors() {
     useMean = m_ui.bckgnd_cor_det_mean_check_box->isChecked();
   }
   return SANSBackgroundCorrectionSettings(runNumber, useMean, useMon,
-    monNumber);
+                                          monNumber);
 }
 
-
 /**
 * Get the dark run settings for time-based subtractions for detectors
 * @returns the dark run settings for time-based subtractions
@@ -169,7 +167,7 @@ SANSBackgroundCorrectionWidget::getDarkRunSettingForTimeMonitors() {
     monNumber = m_ui.bckgnd_cor_mon_time_mon_num_line_edit->text();
   }
   return SANSBackgroundCorrectionSettings(runNumber, useMean, useMon,
-    monNumber);
+                                          monNumber);
 }
 
 /**
@@ -187,7 +185,7 @@ SANSBackgroundCorrectionWidget::getDarkRunSettingForUampDetectors() {
     runNumber = m_ui.bckgnd_cor_det_uamp_run_line_edit->text();
   }
   return SANSBackgroundCorrectionSettings(runNumber, useMean, useMon,
-    monNumber);
+                                          monNumber);
 }
 
 /**
diff --git a/MantidQt/CustomInterfaces/src/SANSConstants.cpp b/MantidQt/CustomInterfaces/src/SANSConstants.cpp
index f4ebb7860159f9ba54412ff4b20e5d6389e62444..33f3a8c9253ea355cf6e0a0b56402b0ff132c603 100644
--- a/MantidQt/CustomInterfaces/src/SANSConstants.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSConstants.cpp
@@ -1,10 +1,8 @@
 #include "MantidQtCustomInterfaces/SANSConstants.h"
 #include <limits>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 SANSConstants::SANSConstants() {}
 
 SANSConstants::~SANSConstants() {}
@@ -50,7 +48,8 @@ QString SANSConstants::getPythonFalseKeyword() {
  * @returns tooltip text for h1
  */
 QString SANSConstants::getQResolutionH1ToolTipText() {
-  const QString qResolutionH1ToolTipText = "The height of the first aperture in mm.";
+  const QString qResolutionH1ToolTipText =
+      "The height of the first aperture in mm.";
   return qResolutionH1ToolTipText;
 }
 
@@ -59,7 +58,8 @@ QString SANSConstants::getQResolutionH1ToolTipText() {
  * @returns tooltip text for h2
  */
 QString SANSConstants::getQResolutionH2ToolTipText() {
-  const QString qResolutionH2ToolTipText = "The height of the seoncd aperture in mm.";
+  const QString qResolutionH2ToolTipText =
+      "The height of the seoncd aperture in mm.";
   return qResolutionH2ToolTipText;
 }
 
@@ -68,7 +68,8 @@ QString SANSConstants::getQResolutionH2ToolTipText() {
  * @returns tooltip text for a1
  */
 QString SANSConstants::getQResolutionA1ToolTipText() {
-  const QString qResolutionA1ToolTipText = "The diameter for the first aperture";
+  const QString qResolutionA1ToolTipText =
+      "The diameter for the first aperture";
   return qResolutionA1ToolTipText;
 }
 
@@ -77,34 +78,29 @@ QString SANSConstants::getQResolutionA1ToolTipText() {
  * @returns tooltip text for a2
  */
 QString SANSConstants::getQResolutionA2ToolTipText() {
-  const QString qResolutionA2ToolTipText = "The diameter for the second aperture";
+  const QString qResolutionA2ToolTipText =
+      "The diameter for the second aperture";
   return qResolutionA2ToolTipText;
 }
 
-
 /**
  * Gets the max double value
  * @returns the max double
  */
 double SANSConstants::getMaxDoubleValue() {
-    return std::numeric_limits<double>::max();
+  return std::numeric_limits<double>::max();
 }
 
 /**
  * Get the number of decimals
  * @returns the number of decimals
  */
-int SANSConstants::getDecimals() {
-  return 6;
-}
+int SANSConstants::getDecimals() { return 6; }
 
 /**
  * Get the max integer value
  * @returns the max integer value
  */
-int SANSConstants::getMaxIntValue() {
-  return std::numeric_limits<int>::max();
-}
-
+int SANSConstants::getMaxIntValue() { return std::numeric_limits<int>::max(); }
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp b/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
index 22842c5d4fa2f24fa4cc19480edb37490f226eff..60f3b9aeb35a7eb38171303e4bb71b8680abc6cf 100644
--- a/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
@@ -209,8 +209,7 @@ QString SANSDiagnostics::getMemberWorkspace(int period) {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         m_outws_load.toStdString()
-                  << std::endl;
+                         m_outws_load.toStdString() << std::endl;
     return "";
   }
   if (Mantid::API::WorkspaceGroup_sptr wsgrp_sptr =
@@ -279,8 +278,7 @@ void SANSDiagnostics::displayRectangularDetectors(const QString &wsName) {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         wsName.toStdString()
-                  << std::endl;
+                         wsName.toStdString() << std::endl;
   }
   if (!ws_sptr) {
     return;
@@ -569,7 +567,6 @@ QString SANSDiagnostics::getDataLoadedWorkspace() {
   return wsName;
 }
 
-
 /// This method returns name of the whole workspace loaded from
 /// the data file, which will be further processed to separate the data from the
 /// banks (Rear-Detector and Front-Detector)
@@ -597,13 +594,11 @@ bool SANSDiagnostics::isValidSpectra(const QString &specMin,
   }
   if (spec_min < 1) {
     g_log.error() << "Inavlid spectrum minimum " + specMin.toStdString() +
-                         " found in  the selected detector bank "
-                  << std::endl;
+                         " found in  the selected detector bank " << std::endl;
   }
   if (spec_max > Mantid::EMPTY_INT()) {
     g_log.error() << "Inavlid spectrum maximum " + specMax.toStdString() +
-                         " found in  the selected detector bank  "
-                  << std::endl;
+                         " found in  the selected detector bank  " << std::endl;
   }
   return ((spec_min >= 1 && spec_max <= Mantid::EMPTY_INT()) ? true : false);
 }
@@ -623,8 +618,7 @@ void SANSDiagnostics::firstDetectorHorizontalIntegralClicked() {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         ipwsName.toStdString()
-                  << std::endl;
+                         ipwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -666,8 +660,7 @@ void SANSDiagnostics::firstDetectorVerticalIntegralClicked() {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         ipwsName.toStdString()
-                  << std::endl;
+                         ipwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -708,8 +701,7 @@ void SANSDiagnostics::firstDetectorTimeIntegralClicked() {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         ipwsName.toStdString()
-                  << std::endl;
+                         ipwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -896,8 +888,7 @@ void SANSDiagnostics::TimeIntegralClicked(const QString &range,
         loadedws.toStdString());
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         loadedws.toStdString()
-                  << std::endl;
+                         loadedws.toStdString() << std::endl;
     return;
   }
 
@@ -1018,8 +1009,7 @@ void SANSDiagnostics::secondDetectorHorizontalIntegralClicked() {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         ipwsName.toStdString()
-                  << std::endl;
+                         ipwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -1059,8 +1049,7 @@ void SANSDiagnostics::secondDetectorVerticalIntegralClicked() {
 
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         ipwsName.toStdString()
-                  << std::endl;
+                         ipwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -1100,8 +1089,7 @@ void SANSDiagnostics::secondDetectorTimeIntegralClicked() {
         initialwsName.toStdString());
   } catch (Exception::NotFoundError &) {
     g_log.error() << "Error when accessing the Workspace " +
-                         initialwsName.toStdString()
-                  << std::endl;
+                         initialwsName.toStdString() << std::endl;
     return;
   }
   Mantid::API::MatrixWorkspace_sptr mws_sptr =
@@ -1248,20 +1236,17 @@ bool SANSDiagnostics::runsumRowColumn(const QString ipwsName,
   }
   if (opwsName.isEmpty()) {
     g_log.error() << "Output workspace name is empty , can't create workspace "
-                     "with empty name"
-                  << std::endl;
+                     "with empty name" << std::endl;
     return false;
   }
   if (hvMin.isEmpty()) {
     g_log.error() << "Error when executing SumRowColumn algorithm :Empty "
-                     "H/V_Min String value "
-                  << std::endl;
+                     "H/V_Min String value " << std::endl;
     return false;
   }
   if (hvMax.isEmpty()) {
     g_log.error() << "Error when executing SumRowColumn algorithm :Empty "
-                     "H/V_Max String value "
-                  << std::endl;
+                     "H/V_Max String value " << std::endl;
     return false;
   }
 
@@ -1305,8 +1290,7 @@ bool SANSDiagnostics::runsumSpectra(const QString &ipwsName,
 
   if (opwsName.isEmpty()) {
     g_log.error() << "Output workspace name is empty , can't create workspace "
-                     "with empty name"
-                  << std::endl;
+                     "with empty name" << std::endl;
     return false;
   }
 
@@ -1356,8 +1340,7 @@ bool SANSDiagnostics::runLoadAlgorithm(const QString &fileName,
   m_outws_load = getWorkspaceNameFileName(fileName);
   if (m_outws_load.isEmpty()) {
     g_log.error() << "Output workspace name is empty , can't create workspace "
-                     "with empty name"
-                  << std::endl;
+                     "with empty name" << std::endl;
     return false;
   }
 
@@ -1454,8 +1437,7 @@ QString SANSDiagnostics::createOutputWorkspaceName(
   } catch (...) {
     g_log.error()
         << "Error when extracting the run number from the Workspace " +
-               originalWorkspaceName.toStdString()
-        << std::endl;
+               originalWorkspaceName.toStdString() << std::endl;
   }
 
   // Build the output name
diff --git a/MantidQt/CustomInterfaces/src/SANSEventSlicing.cpp b/MantidQt/CustomInterfaces/src/SANSEventSlicing.cpp
index 7a24cc282e408fd73df7fd3406ef34f661077dc7..6e7d8f5d42e7afefa9cc1e509e1d4c972552f7cf 100644
--- a/MantidQt/CustomInterfaces/src/SANSEventSlicing.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSEventSlicing.cpp
@@ -7,175 +7,150 @@
 #include <QTextStream>
 #include <stdexcept>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
 using namespace MantidQt::CustomInterfaces;
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("SANSEventSlicing");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("SANSEventSlicing");
 }
 
-
-SANSEventSlicing::SANSEventSlicing(QWidget *parent) :
-  UserSubWindow(parent)
-{
+SANSEventSlicing::SANSEventSlicing(QWidget *parent) : UserSubWindow(parent) {
   setWindowFlags(windowFlags() | Qt::Dialog); //| Qt::Popup);
 }
 
-SANSEventSlicing::~SANSEventSlicing()
-{
-
-}
+SANSEventSlicing::~SANSEventSlicing() {}
 
-//Connect signals and setup widgets
-void SANSEventSlicing::initLayout()
-{
+// Connect signals and setup widgets
+void SANSEventSlicing::initLayout() {
   ui.setupUi(this);
-  connect(ui.applyPb, SIGNAL(clicked()), 
-          this, SLOT(doApplySlice()));
-  connect(ui.run_opt, SIGNAL(currentIndexChanged(const QString&)), 
-          this, SLOT(onChangeWorkspace(const QString & )));
+  connect(ui.applyPb, SIGNAL(clicked()), this, SLOT(doApplySlice()));
+  connect(ui.run_opt, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(onChangeWorkspace(const QString &)));
 }
 
-void SANSEventSlicing::onChangeWorkspace(const QString & newWS)
-{
-  if (newWS.isEmpty()) return;
-  try
-  {
-    ChargeAndTime exp = getFullChargeAndTime(newWS); 
+void SANSEventSlicing::onChangeWorkspace(const QString &newWS) {
+  if (newWS.isEmpty())
+    return;
+  try {
+    ChargeAndTime exp = getFullChargeAndTime(newWS);
 
-    ui.total_label->setText(exp.charge); 
-    ui.time_label->setText(exp.time); 
-  }
-  catch(std::runtime_error& ex)
-  {
-    raiseWarning("On load failure",ex.what()); 
+    ui.total_label->setText(exp.charge);
+    ui.time_label->setText(exp.time);
+  } catch (std::runtime_error &ex) {
+    raiseWarning("On load failure", ex.what());
   }
 }
 
-void SANSEventSlicing::doApplySlice()
-{
-  QString run_name  = ui.run_opt->currentText();
-  if (run_name.isEmpty()){
-    raiseWarning("Wrong Input", "Invalid run Number.\nPlease, provide a correct run number of file!");
+void SANSEventSlicing::doApplySlice() {
+  QString run_name = ui.run_opt->currentText();
+  if (run_name.isEmpty()) {
+    raiseWarning(
+        "Wrong Input",
+        "Invalid run Number.\nPlease, provide a correct run number of file!");
     return;
   }
-  try
-  {
-    QString code = createSliceEventCode(run_name, ui.startDouble->text(), 
-                                      ui.stopDouble->text()); 
+  try {
+    QString code = createSliceEventCode(run_name, ui.startDouble->text(),
+                                        ui.stopDouble->text());
 
-    ChargeAndTime info = runSliceEvent(code); 
+    ChargeAndTime info = runSliceEvent(code);
 
-    ui.sliced_label->setText(info.charge); 
-  }
-  catch(std::exception & ex)
-  {
-    raiseWarning("Failed to Slice", ex.what()); 
+    ui.sliced_label->setText(info.charge);
+  } catch (std::exception &ex) {
+    raiseWarning("Failed to Slice", ex.what());
   }
 }
 
-SANSEventSlicing::ChargeAndTime SANSEventSlicing::getFullChargeAndTime(const QString & name_ws)
-{
+SANSEventSlicing::ChargeAndTime
+SANSEventSlicing::getFullChargeAndTime(const QString &name_ws) {
+
+  QString code;
+  QTextStream stream(&code);
 
-  QString code; 
-  QTextStream stream (&code); 
-  
   stream << "import SANSUtility as su\n"
          << "import sys\n"
-         << "ws = mtd['"<<name_ws << "']\n"
+         << "ws = mtd['" << name_ws << "']\n"
          << "try:\n"
          << "  charge, t_passed = su.getChargeAndTime(ws)\n"
          << "  print '%.2f, %.2f' %(charge, t_passed)\n"
          << "except :\n"
          << "  print 'EXCEPTION:',sys.exc_info()[1]\n";
 
-  QString result = runPythonCode(code).simplified(); 
+  QString result = runPythonCode(code).simplified();
 
-  checkPythonOutput(result); 
+  checkPythonOutput(result);
 
   return values2ChargeAndTime(result);
 }
 
-SANSEventSlicing::ChargeAndTime SANSEventSlicing::values2ChargeAndTime(const QString & input)
-{
+SANSEventSlicing::ChargeAndTime
+SANSEventSlicing::values2ChargeAndTime(const QString &input) {
   QStringList values = input.split(" ");
-  ChargeAndTime inf; 
+  ChargeAndTime inf;
   if (values.size() < 2)
-    throw std::runtime_error(QString("Unexpected result: %1").arg(input).toStdString());
+    throw std::runtime_error(
+        QString("Unexpected result: %1").arg(input).toStdString());
 
-  inf.charge = values[0]; 
+  inf.charge = values[0];
   inf.time = values[1];
-  return inf; 
-  
+  return inf;
 }
 
-
-void SANSEventSlicing::checkPythonOutput(const QString & result)
-{
+void SANSEventSlicing::checkPythonOutput(const QString &result) {
   const QString MARK("EXCEPTION:");
-  if (result.contains(MARK))
-  {
-    
-    throw std::runtime_error(QString(result).replace(MARK, "").toStdString()); 
+  if (result.contains(MARK)) {
+
+    throw std::runtime_error(QString(result).replace(MARK, "").toStdString());
   }
 }
 
+QString SANSEventSlicing::createSliceEventCode(const QString &name_ws,
+                                               const QString &start,
+                                               const QString &stop) {
+  if (start.isEmpty() && stop.isEmpty()) {
+    throw std::invalid_argument("You must provide the limits for the slicing");
+  }
 
-QString SANSEventSlicing::createSliceEventCode(const QString & name_ws, 
-                              const QString & start, const QString & stop)
-{
-  if (start.isEmpty() && stop.isEmpty())
-    {
-      throw std::invalid_argument("You must provide the limits for the slicing"); 
-    }
+  QString code;
+  QTextStream stream(&code);
 
-  QString code; 
-  QTextStream stream(&code); 
-  
   stream << "import sys\n"
          << "import SANSUtility as su\n"
-         << "ws = mtd['"<<name_ws<<"']\n"
+         << "ws = mtd['" << name_ws << "']\n"
          << "outname = str(ws)+'_T'+'" << start << "'+'_T'+'" << stop << "'\n"
          << "ws = ws.clone(OutputWorkspace=outname)\n"
          << "try:\n"
          << "  mon = mtd['" << name_ws << "_monitors']\n"
-         << "  hist, times = su.slice2histogram(ws" 
-         << ", " << start << ", " << stop
-         << ", mon)\n"
+         << "  hist, times = su.slice2histogram(ws"
+         << ", " << start << ", " << stop << ", mon)\n"
          << "  print '%.2f, %.2f' %(times[3], times[2])\n"
          << "except:\n"
          << "  print 'EXCEPTION:',sys.exc_info()[1]";
 
-  return code; 
-
+  return code;
 }
 
-SANSEventSlicing::ChargeAndTime SANSEventSlicing::runSliceEvent(const QString & code)
-{
-  QString result = runPythonCode(code).simplified(); 
-  
-  checkPythonOutput(result); 
+SANSEventSlicing::ChargeAndTime
+SANSEventSlicing::runSliceEvent(const QString &code) {
+  QString result = runPythonCode(code).simplified();
+
+  checkPythonOutput(result);
 
   return values2ChargeAndTime(result);
 }
 
-void SANSEventSlicing::raiseWarning(QString title, QString message){
-   QMessageBox::warning(this, title, message); 
+void SANSEventSlicing::raiseWarning(QString title, QString message) {
+  QMessageBox::warning(this, title, message);
 }
 
-void SANSEventSlicing::showEvent(QShowEvent * ev ){
+void SANSEventSlicing::showEvent(QShowEvent *ev) {
   if (ui.run_opt->count() > 0)
-    onChangeWorkspace(ui.run_opt->currentText()); 
+    onChangeWorkspace(ui.run_opt->currentText());
   UserSubWindow::showEvent(ev);
 }
 
-
-
-}//namespace CustomInterfaces
-}//namespace MantidQt
+} // namespace CustomInterfaces
+} // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/SANSPlotSpecial.cpp b/MantidQt/CustomInterfaces/src/SANSPlotSpecial.cpp
index ec06f56e5abe84cd5c2058e47d90100651ca83a6..57edbc0a1b376c02361f49978e381cadff452e2e 100644
--- a/MantidQt/CustomInterfaces/src/SANSPlotSpecial.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSPlotSpecial.cpp
@@ -10,41 +10,45 @@
 #include <QLineEdit>
 #include "qwt_plot_curve.h"
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-
-SANSPlotSpecial::SANSPlotSpecial(QWidget *parent) : 
-  QFrame(parent), m_rangeSelector(NULL), m_transforms(), m_current(""),
-  m_dataCurve(new QwtPlotCurve()), m_linearCurve(new QwtPlotCurve()), m_rearrangingTable(false)
-{
+namespace MantidQt {
+namespace CustomInterfaces {
+
+SANSPlotSpecial::SANSPlotSpecial(QWidget *parent)
+    : QFrame(parent), m_rangeSelector(NULL), m_transforms(), m_current(""),
+      m_dataCurve(new QwtPlotCurve()), m_linearCurve(new QwtPlotCurve()),
+      m_rearrangingTable(false) {
   m_uiForm.setupUi(this);
   initLayout();
 }
 
-SANSPlotSpecial::~SANSPlotSpecial()
-{
+SANSPlotSpecial::~SANSPlotSpecial() {
   //
 }
 
-void SANSPlotSpecial::rangeChanged(double low, double high)
-{
-  if ( ! m_workspaceIQT ) { return; }
+void SANSPlotSpecial::rangeChanged(double low, double high) {
+  if (!m_workspaceIQT) {
+    return;
+  }
 
-  Mantid::API::IAlgorithm_sptr fit = Mantid::API::AlgorithmManager::Instance().create("Fit");
+  Mantid::API::IAlgorithm_sptr fit =
+      Mantid::API::AlgorithmManager::Instance().create("Fit");
   fit->initialize();
-  fit->setPropertyValue("Function", "name=UserFunction, Formula=Intercept+Gradient*x");
-  fit->setProperty<Mantid::API::MatrixWorkspace_sptr>("InputWorkspace", m_workspaceIQT);
+  fit->setPropertyValue("Function",
+                        "name=UserFunction, Formula=Intercept+Gradient*x");
+  fit->setProperty<Mantid::API::MatrixWorkspace_sptr>("InputWorkspace",
+                                                      m_workspaceIQT);
   fit->setPropertyValue("Output", "__sans_isis_display_linear");
   fit->setProperty<double>("StartX", low);
   fit->setProperty<double>("EndX", high);
   fit->execute();
 
-  if ( ! fit->isExecuted() ) { return; }
+  if (!fit->isExecuted()) {
+    return;
+  }
 
-  m_workspaceLinear = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>
-    (Mantid::API::AnalysisDataService::Instance().retrieve("__sans_isis_display_linear_Workspace"));
+  m_workspaceLinear = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+      Mantid::API::AnalysisDataService::Instance().retrieve(
+          "__sans_isis_display_linear_Workspace"));
   m_linearCurve = plotMiniplot(m_linearCurve, m_workspaceLinear, 1);
 
   QPen fitPen(Qt::red, Qt::SolidLine);
@@ -55,108 +59,102 @@ void SANSPlotSpecial::rangeChanged(double low, double high)
 
   double chisqrd = fit->getProperty("OutputChi2overDoF");
 
-  m_derivatives["Intercept"]->setText(QString::number(func->getParameter("Intercept")));
-  m_derivatives["Gradient"]->setText(QString::number(func->getParameter("Gradient")));
+  m_derivatives["Intercept"]->setText(
+      QString::number(func->getParameter("Intercept")));
+  m_derivatives["Gradient"]->setText(
+      QString::number(func->getParameter("Gradient")));
   m_derivatives["Chi Squared"]->setText(QString::number(chisqrd));
 
   calculateDerivatives();
 }
 
-void SANSPlotSpecial::plot()
-{
+void SANSPlotSpecial::plot() {
   // validate input
-  if ( ! validatePlotOptions() )
-  {
+  if (!validatePlotOptions()) {
     return;
   }
   // Run iq transform algorithm
   m_workspaceIQT = runIQTransform();
-  if ( m_workspaceIQT )
-  {
+  if (m_workspaceIQT) {
     // plot data to the plotWindow
     m_dataCurve = plotMiniplot(m_dataCurve, m_workspaceIQT);
     // update fields of table of "derived" values?
-    QPair<QStringList, QList<QPair<int, int> > > deriv = m_transforms[m_uiForm.cbPlotType->currentText()]->derivatives();
+    QPair<QStringList, QList<QPair<int, int>>> deriv =
+        m_transforms[m_uiForm.cbPlotType->currentText()]->derivatives();
     tableDisplay(deriv.first, deriv.second);
     calculateDerivatives();
   }
 }
 
-void SANSPlotSpecial::updateAxisLabels(const QString & value)
-{
-  if ( m_current != "" )
-  {
-    foreach ( QWidget* item, m_transforms[m_current]->xWidgets() )
-    {
+void SANSPlotSpecial::updateAxisLabels(const QString &value) {
+  if (m_current != "") {
+    foreach (QWidget *item, m_transforms[m_current]->xWidgets()) {
       m_uiForm.layoutXAxis->removeWidget(item);
       delete item;
     }
-    foreach ( QWidget* item, m_transforms[m_current]->yWidgets() )
-    {
+    foreach (QWidget *item, m_transforms[m_current]->yWidgets()) {
       m_uiForm.layoutYAxis->removeWidget(item);
       delete item;
     }
     m_transforms[m_current]->init();
   }
 
-  foreach ( QWidget* item, m_transforms[value]->xWidgets() )
-  {
+  foreach (QWidget *item, m_transforms[value]->xWidgets()) {
     m_uiForm.layoutXAxis->addWidget(item);
   }
-  foreach ( QWidget* item, m_transforms[value]->yWidgets() )
-  {
+  foreach (QWidget *item, m_transforms[value]->yWidgets()) {
     m_uiForm.layoutYAxis->addWidget(item);
   }
 
   m_current = value;
 }
 
-void SANSPlotSpecial::clearTable()
-{
+void SANSPlotSpecial::clearTable() {
   // Removes items from the G Derived and I Derived columns
   // deleting the labels but preserving the actual objects
   int nrows = m_uiForm.tbDerived->rowCount();
-  for ( int i = 0; i < nrows; i++ )
-  {
-    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::GradientLabels, new QTableWidgetItem(*m_emptyCell));
-    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::GradientUnits, new QTableWidgetItem(*m_emptyCell));
-    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::InterceptLabels, new QTableWidgetItem(*m_emptyCell));
-    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::InterceptUnits, new QTableWidgetItem(*m_emptyCell));
+  for (int i = 0; i < nrows; i++) {
+    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::GradientLabels,
+                                new QTableWidgetItem(*m_emptyCell));
+    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::GradientUnits,
+                                new QTableWidgetItem(*m_emptyCell));
+    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::InterceptLabels,
+                                new QTableWidgetItem(*m_emptyCell));
+    m_uiForm.tbDerived->setItem(i, SANSPlotSpecial::InterceptUnits,
+                                new QTableWidgetItem(*m_emptyCell));
     m_uiForm.tbDerived->takeItem(i, SANSPlotSpecial::GradientDerived);
     m_uiForm.tbDerived->takeItem(i, SANSPlotSpecial::InterceptDerived);
   }
 
-  while ( m_uiForm.tbDerived->rowCount() > 3 )
-  {
+  while (m_uiForm.tbDerived->rowCount() > 3) {
     m_uiForm.tbDerived->removeRow(3);
-  } 
+  }
 }
 
-void SANSPlotSpecial::calculateDerivatives()
-{
+void SANSPlotSpecial::calculateDerivatives() {
   m_rearrangingTable = true;
 
-  Transform* transform = m_transforms[m_uiForm.cbPlotType->currentText()];
+  Transform *transform = m_transforms[m_uiForm.cbPlotType->currentText()];
   Transform::TransformType type = transform->type();
   double temp = 0.0;
   const double gradient = m_derivatives["Gradient"]->text().toDouble();
   const double intercept = m_derivatives["Intercept"]->text().toDouble();
-  switch ( type )
-  {
+  switch (type) {
   case Transform::GuinierSpheres:
     // Gradient = -(Rg**2)/3 = -(R**2)/5
-    temp = std::sqrt(3 * std::abs(gradient) );
+    temp = std::sqrt(3 * std::abs(gradient));
     m_derivatives["Rg"]->setText(QString::number(temp));
-    temp = std::sqrt(5 * std::abs(gradient) );
+    temp = std::sqrt(5 * std::abs(gradient));
     m_derivatives["R"]->setText(QString::number(temp));
-    // Intercept = M.[(c.(deltarho**2) / (NA.d**2)] = M.[(phi.(deltarho**2) / (NA.d)]
+    // Intercept = M.[(c.(deltarho**2) / (NA.d**2)] = M.[(phi.(deltarho**2) /
+    // (NA.d)]
     deriveGuinierSpheres();
     break;
   case Transform::GuinierRods:
     // Gradient = -(Rg,xs**2)/2  (note dividing by 2 this time)
-    temp = std::sqrt(2 * std::abs(gradient) );
+    temp = std::sqrt(2 * std::abs(gradient));
     m_derivatives["Rg,xs"]->setText(QString::number(temp));
-    //Intercept (Q**2=0) = Ln[(pi.c.(deltarho**2).ML) / (NA.d**2)]
+    // Intercept (Q**2=0) = Ln[(pi.c.(deltarho**2).ML) / (NA.d**2)]
     deriveGuinierRods();
     break;
   case Transform::GuinierSheets:
@@ -165,23 +163,25 @@ void SANSPlotSpecial::calculateDerivatives()
     break;
   case Transform::Zimm:
     // Gradient = (Rg**2)/3 = (R**2)/5
-    temp = std::sqrt(3 * std::abs(gradient) / intercept );
+    temp = std::sqrt(3 * std::abs(gradient) / intercept);
     m_derivatives["Rg"]->setText(QString::number(temp));
-    temp = std::sqrt(5 * std::abs(gradient) / intercept );
+    temp = std::sqrt(5 * std::abs(gradient) / intercept);
     m_derivatives["R"]->setText(QString::number(temp));
-    // Intercept = (1/M).[(NA.d**2) / (c.(deltarho**2)] = (1/M).[(NA.d) / (phi.(deltarho**2)]
+    // Intercept = (1/M).[(NA.d**2) / (c.(deltarho**2)] = (1/M).[(NA.d) /
+    // (phi.(deltarho**2)]
     deriveZimm();
     break;
   case Transform::Kratky:
-    // Plateau Intercept = [(2.c.M.(deltarho**2)) / (NA.(d**2).(Rg**2))] = [(2.phi.M.(deltarho**2)) / (NA.d.(Rg**2))]
+    // Plateau Intercept = [(2.c.M.(deltarho**2)) / (NA.(d**2).(Rg**2))] =
+    // [(2.phi.M.(deltarho**2)) / (NA.d.(Rg**2))]
     deriveKratky();
     break;
   case Transform::DebyeBueche:
-    temp = std::sqrt( gradient / intercept );
+    temp = std::sqrt(gradient / intercept);
     m_derivatives["Zeta"]->setText(QString::number(temp));
     break;
   case Transform::LogLog:
-    temp = - gradient;
+    temp = -gradient;
     m_derivatives["N"]->setText(QString::number(temp));
     temp = -1 / gradient;
     m_derivatives["V"]->setText(QString::number(temp));
@@ -197,22 +197,24 @@ void SANSPlotSpecial::calculateDerivatives()
   m_rearrangingTable = false;
 }
 
-void SANSPlotSpecial::tableUpdated(int row, int column)
-{
+void SANSPlotSpecial::tableUpdated(int row, int column) {
   UNUSED_ARG(row);
 
-  if ( m_rearrangingTable ) { return; }
-  if ( ! ( column == SANSPlotSpecial::GradientDerived || column == SANSPlotSpecial::InterceptDerived ) ) { return; }
+  if (m_rearrangingTable) {
+    return;
+  }
+  if (!(column == SANSPlotSpecial::GradientDerived ||
+        column == SANSPlotSpecial::InterceptDerived)) {
+    return;
+  }
 
   calculateDerivatives();
 }
 
-void SANSPlotSpecial::clearInterceptDerived()
-{
+void SANSPlotSpecial::clearInterceptDerived() {
   m_rearrangingTable = true;
 
-  for ( int i = 0; i < m_uiForm.tbDerived->rowCount(); i++ )
-  {
+  for (int i = 0; i < m_uiForm.tbDerived->rowCount(); i++) {
     auto wi = m_uiForm.tbDerived->item(i, SANSPlotSpecial::InterceptDerived);
     if (wi)
       wi->setText("");
@@ -221,19 +223,16 @@ void SANSPlotSpecial::clearInterceptDerived()
   m_rearrangingTable = false;
 }
 
-void SANSPlotSpecial::scalePlot(double start, double end)
-{
+void SANSPlotSpecial::scalePlot(double start, double end) {
   double delta = end - start;
-  double limA = start - ( delta / 10 );
-  double limB = end + ( delta / 10 );
+  double limA = start - (delta / 10);
+  double limB = end + (delta / 10);
   m_uiForm.plotWindow->setAxisScale(QwtPlot::xBottom, limA, limB);
   m_uiForm.plotWindow->replot();
 }
 
-void SANSPlotSpecial::resetSelectors()
-{
-  if ( m_dataCurve )
-  {
+void SANSPlotSpecial::resetSelectors() {
+  if (m_dataCurve) {
     const double min = m_dataCurve->minXValue();
     const double max = m_dataCurve->maxXValue();
     m_uiForm.plotWindow->setAxisScale(QwtPlot::xBottom, min, max);
@@ -243,8 +242,7 @@ void SANSPlotSpecial::resetSelectors()
   }
 }
 
-void SANSPlotSpecial::initLayout()
-{
+void SANSPlotSpecial::initLayout() {
   createTransforms();
   setupTable();
 
@@ -255,112 +253,115 @@ void SANSPlotSpecial::initLayout()
 
   // Setup RangeSelector widget for use on the plotWindow
   m_rangeSelector = new MantidWidgets::RangeSelector(m_uiForm.plotWindow);
-  connect(m_rangeSelector, SIGNAL(selectionChanged(double, double)), this, SLOT(rangeChanged(double, double)));
+  connect(m_rangeSelector, SIGNAL(selectionChanged(double, double)), this,
+          SLOT(rangeChanged(double, double)));
 
   // Scale the plot based on the range selection
-  connect(m_rangeSelector, SIGNAL(selectionChangedLazy(double, double)), this, SLOT(scalePlot(double, double)));
+  connect(m_rangeSelector, SIGNAL(selectionChangedLazy(double, double)), this,
+          SLOT(scalePlot(double, double)));
 
-  connect(m_uiForm.pbResetRangeSelectors, SIGNAL(clicked()), this, SLOT(resetSelectors()));
+  connect(m_uiForm.pbResetRangeSelectors, SIGNAL(clicked()), this,
+          SLOT(resetSelectors()));
 
   // Other signal/slot connections
   connect(m_uiForm.pbPlot, SIGNAL(clicked()), this, SLOT(plot()));
-  connect(m_uiForm.cbBackground, SIGNAL(currentIndexChanged(int)), m_uiForm.swBackground, SLOT(setCurrentIndex(int)));
-  connect(m_uiForm.cbPlotType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(updateAxisLabels(const QString &)));
-  connect(m_uiForm.tbDerived, SIGNAL(cellChanged(int, int)), this, SLOT(tableUpdated(int, int)));
-  connect(m_uiForm.pbClearIDerived, SIGNAL(clicked()), this, SLOT(clearInterceptDerived()));
+  connect(m_uiForm.cbBackground, SIGNAL(currentIndexChanged(int)),
+          m_uiForm.swBackground, SLOT(setCurrentIndex(int)));
+  connect(m_uiForm.cbPlotType, SIGNAL(currentIndexChanged(const QString &)),
+          this, SLOT(updateAxisLabels(const QString &)));
+  connect(m_uiForm.tbDerived, SIGNAL(cellChanged(int, int)), this,
+          SLOT(tableUpdated(int, int)));
+  connect(m_uiForm.pbClearIDerived, SIGNAL(clicked()), this,
+          SLOT(clearInterceptDerived()));
   updateAxisLabels(m_uiForm.cbPlotType->currentText());
 }
 
-Mantid::API::MatrixWorkspace_sptr SANSPlotSpecial::runIQTransform()
-{
+Mantid::API::MatrixWorkspace_sptr SANSPlotSpecial::runIQTransform() {
   // Run the IQTransform algorithm for the current settings on the GUI
-  Mantid::API::IAlgorithm_sptr iqt = Mantid::API::AlgorithmManager::Instance().create("IQTransform");
+  Mantid::API::IAlgorithm_sptr iqt =
+      Mantid::API::AlgorithmManager::Instance().create("IQTransform");
   iqt->initialize();
-  try
-  {
-    iqt->setPropertyValue("InputWorkspace", m_uiForm.wsInput->currentText().toStdString());
-  } catch ( std::invalid_argument & )
-  {
-    m_uiForm.lbPlotOptionsError->setText("Selected input workspace is not appropriate for the IQTransform algorithm. Please refer to the documentation for guidelines.");
+  try {
+    iqt->setPropertyValue("InputWorkspace",
+                          m_uiForm.wsInput->currentText().toStdString());
+  } catch (std::invalid_argument &) {
+    m_uiForm.lbPlotOptionsError->setText(
+        "Selected input workspace is not appropriate for the IQTransform "
+        "algorithm. Please refer to the documentation for guidelines.");
     return Mantid::API::MatrixWorkspace_sptr();
   }
   iqt->setPropertyValue("OutputWorkspace", "__sans_isis_display_iqt");
-  iqt->setPropertyValue("TransformType", m_uiForm.cbPlotType->currentText().toStdString());
-  
-  if ( m_uiForm.cbBackground->currentText() == "Value" )
-  { 
+  iqt->setPropertyValue("TransformType",
+                        m_uiForm.cbPlotType->currentText().toStdString());
+
+  if (m_uiForm.cbBackground->currentText() == "Value") {
     iqt->setProperty<double>("BackgroundValue", m_uiForm.dsBackground->value());
-  }
-  else
-  { 
-    iqt->setPropertyValue("BackgroundWorkspace", m_uiForm.wsBackground->currentText().toStdString());
+  } else {
+    iqt->setPropertyValue("BackgroundWorkspace",
+                          m_uiForm.wsBackground->currentText().toStdString());
   }
 
-  if ( m_uiForm.cbPlotType->currentText() == "General" )
-  {
-    std::vector<double> constants = m_transforms["General"]->functionConstants();
+  if (m_uiForm.cbPlotType->currentText() == "General") {
+    std::vector<double> constants =
+        m_transforms["General"]->functionConstants();
     iqt->setProperty("GeneralFunctionConstants", constants);
   }
 
   iqt->execute();
 
   Mantid::API::MatrixWorkspace_sptr result =
-    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve("__sans_isis_display_iqt"));
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(
+              "__sans_isis_display_iqt"));
   return result;
 }
 
-void SANSPlotSpecial::tableDisplay(QStringList properties, QList<QPair<int, int> > positions)
-{
+void SANSPlotSpecial::tableDisplay(QStringList properties,
+                                   QList<QPair<int, int>> positions) {
   m_rearrangingTable = true;
 
   clearTable();
 
-  QList<QPair<int, int> >::iterator pos = positions.begin();
-  for ( QStringList::iterator it = properties.begin(); it != properties.end(); ++it, ++pos )
-  {
+  QList<QPair<int, int>>::iterator pos = positions.begin();
+  for (QStringList::iterator it = properties.begin(); it != properties.end();
+       ++it, ++pos) {
     int row = (*pos).first;
-    if ( row > ( m_uiForm.tbDerived->rowCount() - 1 ) )
-    {
+    if (row > (m_uiForm.tbDerived->rowCount() - 1)) {
       m_uiForm.tbDerived->insertRow(row);
     }
     int column = (*pos).second;
-    QTableWidgetItem* lblItm = new QTableWidgetItem(*m_emptyCell);
+    QTableWidgetItem *lblItm = new QTableWidgetItem(*m_emptyCell);
     lblItm->setToolTip(m_derivatives[(*it)]->toolTip());
     lblItm->setText((*it));
-    QTableWidgetItem* unitItm = new QTableWidgetItem(*m_emptyCell);
+    QTableWidgetItem *unitItm = new QTableWidgetItem(*m_emptyCell);
     unitItm->setText(m_units[(*it)]);
     m_uiForm.tbDerived->setItem(row, column, lblItm);
-    m_uiForm.tbDerived->setItem(row, column+1, m_derivatives[(*it)]);
-    m_uiForm.tbDerived->setItem(row, column+2, unitItm);
+    m_uiForm.tbDerived->setItem(row, column + 1, m_derivatives[(*it)]);
+    m_uiForm.tbDerived->setItem(row, column + 2, unitItm);
   }
 
   m_rearrangingTable = false;
 }
 
-bool SANSPlotSpecial::validatePlotOptions()
-{
+bool SANSPlotSpecial::validatePlotOptions() {
   bool valid = true;
   m_uiForm.lbPlotOptionsError->setText("");
   QString error = "";
 
-  if ( m_uiForm.wsInput->currentText() == "" )
-  {
+  if (m_uiForm.wsInput->currentText() == "") {
     error += "Please select an input workspace.\n";
     valid = false;
   }
 
-  if ( m_uiForm.cbBackground->currentText() == "Workspace" &&
-    m_uiForm.wsBackground->currentText() == "" )
-  {
+  if (m_uiForm.cbBackground->currentText() == "Workspace" &&
+      m_uiForm.wsBackground->currentText() == "") {
     error += "Please select a background workspace.\n";
     valid = false;
   }
 
-  if ( m_uiForm.cbPlotType->currentText() == "General" )
-  {
+  if (m_uiForm.cbPlotType->currentText() == "General") {
     std::vector<double> params = m_transforms["General"]->functionConstants();
-    if ( params.size() != 10 )
-    {
+    if (params.size() != 10) {
       error += "Constants for general function not provided.";
       valid = false;
     }
@@ -370,8 +371,7 @@ bool SANSPlotSpecial::validatePlotOptions()
   return valid;
 }
 
-void SANSPlotSpecial::createTransforms()
-{
+void SANSPlotSpecial::createTransforms() {
   m_transforms.clear();
 
   m_transforms["Guinier (spheres)"] = new Transform(Transform::GuinierSpheres);
@@ -396,26 +396,31 @@ void SANSPlotSpecial::createTransforms()
   m_uiForm.cbPlotType->addItem("General");
 }
 
-void SANSPlotSpecial::setupTable()
-{
+void SANSPlotSpecial::setupTable() {
   m_emptyCell = new QTableWidgetItem();
-  m_emptyCell->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled );
+  m_emptyCell->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
   m_uiForm.tbDerived->setItemPrototype(m_emptyCell);
 
   m_derivatives["Gradient"] = new QTableWidgetItem(*m_emptyCell);
   m_derivatives["Intercept"] = new QTableWidgetItem(*m_emptyCell);
   m_derivatives["Chi Squared"] = new QTableWidgetItem(*m_emptyCell);
 
-  QTableWidgetItem* lbl = new QTableWidgetItem(*m_emptyCell); lbl->setText("Gradient");
+  QTableWidgetItem *lbl = new QTableWidgetItem(*m_emptyCell);
+  lbl->setText("Gradient");
   m_uiForm.tbDerived->setItem(0, SANSPlotSpecial::FitInformation, lbl);
-  m_uiForm.tbDerived->setItem(0, SANSPlotSpecial::FitInformationValues, m_derivatives["Gradient"]);
-  lbl = new QTableWidgetItem(*m_emptyCell); lbl->setText("Intercept");
+  m_uiForm.tbDerived->setItem(0, SANSPlotSpecial::FitInformationValues,
+                              m_derivatives["Gradient"]);
+  lbl = new QTableWidgetItem(*m_emptyCell);
+  lbl->setText("Intercept");
   m_uiForm.tbDerived->setItem(1, SANSPlotSpecial::FitInformation, lbl);
-  m_uiForm.tbDerived->setItem(1, SANSPlotSpecial::FitInformationValues, m_derivatives["Intercept"]);
-  lbl = new QTableWidgetItem(*m_emptyCell); lbl->setText("Chi Squared");
+  m_uiForm.tbDerived->setItem(1, SANSPlotSpecial::FitInformationValues,
+                              m_derivatives["Intercept"]);
+  lbl = new QTableWidgetItem(*m_emptyCell);
+  lbl->setText("Chi Squared");
   m_uiForm.tbDerived->setItem(2, SANSPlotSpecial::FitInformation, lbl);
-  m_uiForm.tbDerived->setItem(2, SANSPlotSpecial::FitInformationValues, m_derivatives["Chi Squared"]);
-    
+  m_uiForm.tbDerived->setItem(2, SANSPlotSpecial::FitInformationValues,
+                              m_derivatives["Chi Squared"]);
+
   m_derivatives["Rg"] = new QTableWidgetItem();
   m_derivatives["Rg"]->setToolTip("Radius of gyration");
   m_units["Rg"] = QString::fromUtf8("\xc3\x85");
@@ -435,7 +440,8 @@ void SANSPlotSpecial::setupTable()
   m_derivatives["Phi"]->setToolTip("Volume fraction");
   m_units["Phi"] = "%/100";
   m_derivatives["Deltarho"] = new QTableWidgetItem();
-  m_derivatives["Deltarho"]->setToolTip("Difference in neutron scattering length densities (solute-solvent)");
+  m_derivatives["Deltarho"]->setToolTip(
+      "Difference in neutron scattering length densities (solute-solvent)");
   m_units["Deltarho"] = "cm^-2";
   m_derivatives["M"] = new QTableWidgetItem();
   m_derivatives["M"]->setToolTip("Molecular weight");
@@ -460,13 +466,13 @@ void SANSPlotSpecial::setupTable()
   m_units["(S/V)"] = "cm^-1";
 }
 
-QwtPlotCurve* SANSPlotSpecial::plotMiniplot(QwtPlotCurve* curve, boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace,
-  size_t workspaceIndex)
-{
-  bool data = ( curve == m_dataCurve );
+QwtPlotCurve *SANSPlotSpecial::plotMiniplot(
+    QwtPlotCurve *curve,
+    boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace,
+    size_t workspaceIndex) {
+  bool data = (curve == m_dataCurve);
 
-  if ( curve != NULL )
-  {
+  if (curve != NULL) {
     curve->attach(0);
     delete curve;
     curve = 0;
@@ -475,104 +481,89 @@ QwtPlotCurve* SANSPlotSpecial::plotMiniplot(QwtPlotCurve* curve, boost::shared_p
   curve = new QwtPlotCurve();
 
   using Mantid::MantidVec;
-  const MantidVec & dataX = workspace->readX(workspaceIndex);
-  const MantidVec & dataY = workspace->readY(workspaceIndex);
+  const MantidVec &dataX = workspace->readX(workspaceIndex);
+  const MantidVec &dataY = workspace->readY(workspaceIndex);
 
-  curve->setData(&dataX[0], &dataY[0], static_cast<int>(workspace->blocksize()));
+  curve->setData(&dataX[0], &dataY[0],
+                 static_cast<int>(workspace->blocksize()));
   curve->attach(m_uiForm.plotWindow);
 
   m_uiForm.plotWindow->replot();
-  
-  if ( data )
-  {
+
+  if (data) {
     m_rangeSelector->setRange(dataX.front(), dataX.back());
   }
 
   return curve;
 }
 
-void SANSPlotSpecial::deriveGuinierSpheres()
-{
-  // Intercept = M.[(c.(deltarho**2) / (NA.d**2)] = M.[(phi.(deltarho**2) / (NA.d)]
-  QPair<QStringList, QMap<QString, double> > props = getProperties("Guinier (spheres)");
+void SANSPlotSpecial::deriveGuinierSpheres() {
+  // Intercept = M.[(c.(deltarho**2) / (NA.d**2)] = M.[(phi.(deltarho**2) /
+  // (NA.d)]
+  QPair<QStringList, QMap<QString, double>> props =
+      getProperties("Guinier (spheres)");
   QStringList unknown = props.first;
   QMap<QString, double> values = props.second;
 
-  bool doable = ( unknown.indexOf("C") != -1 ) ^ ( unknown.indexOf("Phi") != -1 );
+  bool doable = (unknown.indexOf("C") != -1) ^ (unknown.indexOf("Phi") != -1);
 
-  if ( ( ( unknown.size() > 1 ) && ! doable ) || ( unknown.size() > 2 ) )
-  {
+  if (((unknown.size() > 1) && !doable) || (unknown.size() > 2)) {
     return;
   }
   QString route = "Phi";
-  if ( unknown.indexOf("C") == -1 ) { route = "C"; }
+  if (unknown.indexOf("C") == -1) {
+    route = "C";
+  }
 
   const double lhs = values["Intercept"] * Mantid::PhysicalConstants::N_A;
 
-  foreach ( QString item, unknown )
-  {
+  foreach (QString item, unknown) {
     double val;
-    if ( item == "M" )
-    {
+    if (item == "M") {
       val = lhs * values["D"] / std::pow(values["Deltarho"], 2.0);
-      if ( route == "C" )
-      {
-        val = val * ( values["D"] / values["C"] );
-      }
-      else
-      {
+      if (route == "C") {
+        val = val * (values["D"] / values["C"]);
+      } else {
         val = val / values["Phi"];
       }
-    }
-    else if ( item == "C" )
-    {
-      val = ( lhs * std::pow(values["D"], 2.0) ) / ( values["M"] * std::pow(values["Deltarho"], 2.0) );
-    }
-    else if ( item == "Deltarho" )
-    {
+    } else if (item == "C") {
+      val = (lhs * std::pow(values["D"], 2.0)) /
+            (values["M"] * std::pow(values["Deltarho"], 2.0));
+    } else if (item == "Deltarho") {
       val = lhs * values["D"] / values["M"];
-      if ( route == "C" )
-      {
+      if (route == "C") {
         val = val * values["D"] / values["C"];
-      }
-      else
-      {
+      } else {
         val = val / values["Phi"];
       }
-      val = std::sqrt( val );
-    }
-    else if ( item == "D" )
-    {
-      val = lhs / ( values["M"] * std::pow(values["Deltarho"], 2.0) );
-      if ( route == "C" )
-      {
-        val = 1 / ( std::sqrt( val / values["C"] ) );
-      }
-      else
-      {
-        val = 1 / ( val / values["Phi"] );
+      val = std::sqrt(val);
+    } else if (item == "D") {
+      val = lhs / (values["M"] * std::pow(values["Deltarho"], 2.0));
+      if (route == "C") {
+        val = 1 / (std::sqrt(val / values["C"]));
+      } else {
+        val = 1 / (val / values["Phi"]);
       }
+    } else if (item == "Phi") {
+      val = (lhs * values["D"]) /
+            (values["M"] * std::pow(values["Deltarho"], 2.0));
+    } else {
+      continue;
     }
-    else if ( item == "Phi" )
-    {
-      val = ( lhs * values["D"] ) / ( values["M"] * std::pow(values["Deltarho"], 2.0) );
-    }
-    else { continue; }
 
     values[item] = val;
     m_derivatives[item]->setText(QString::number(val));
   }
 }
 
-void SANSPlotSpecial::deriveGuinierRods()
-{
-  //Intercept (Q**2=0) = Ln[(pi.c.(deltarho**2).ML) / (NA.d**2)]
-  QPair<QStringList, QMap<QString, double> > props = getProperties("Guinier (rods)");
+void SANSPlotSpecial::deriveGuinierRods() {
+  // Intercept (Q**2=0) = Ln[(pi.c.(deltarho**2).ML) / (NA.d**2)]
+  QPair<QStringList, QMap<QString, double>> props =
+      getProperties("Guinier (rods)");
   QStringList unknown = props.first;
   QMap<QString, double> values = props.second;
 
-  if ( unknown.size() != 1 )
-  {
+  if (unknown.size() != 1) {
     return;
   }
 
@@ -580,258 +571,216 @@ void SANSPlotSpecial::deriveGuinierRods()
 
   double val;
 
-  const double lhs = ( std::pow(2.71828183, values["Intercept"]) * Mantid::PhysicalConstants::N_A ) / M_PI;
-  
-  if ( item == "C" )
-  {
-    val = lhs * ( std::pow(values["D"], 2) / ( std::pow(values["Deltarho"], 2) * values["ML"] ) );
-  }
-  else if ( item == "Deltarho" )
-  {
-    val = std::sqrt( lhs * ( std::pow(values["D"], 2) / ( values["C"] * values["ML"] ) ) );
-  }
-  else if ( item == "ML" )
-  {
-    val = lhs * ( std::pow(values["D"], 2) / ( std::pow(values["Deltarho"], 2) * values["C"] ) );
-  }
-  else if ( item == "D" )
-  {
-    val = std::sqrt( 1 / ( lhs / ( values["C"] * values["ML"] * std::pow(values["Deltarho"], 2) ) ) );
+  const double lhs = (std::pow(2.71828183, values["Intercept"]) *
+                      Mantid::PhysicalConstants::N_A) /
+                     M_PI;
+
+  if (item == "C") {
+    val = lhs * (std::pow(values["D"], 2) /
+                 (std::pow(values["Deltarho"], 2) * values["ML"]));
+  } else if (item == "Deltarho") {
+    val = std::sqrt(lhs *
+                    (std::pow(values["D"], 2) / (values["C"] * values["ML"])));
+  } else if (item == "ML") {
+    val = lhs * (std::pow(values["D"], 2) /
+                 (std::pow(values["Deltarho"], 2) * values["C"]));
+  } else if (item == "D") {
+    val = std::sqrt(1 / (lhs / (values["C"] * values["ML"] *
+                                std::pow(values["Deltarho"], 2))));
+  } else {
+    return;
   }
-  else { return; }
 
   m_derivatives[item]->setText(QString::number(val));
-
 }
 
-void SANSPlotSpecial::deriveZimm()
-{
-  // Intercept = (1/M).[(NA.d**2) / (c.(deltarho**2)] = (1/M).[(NA.d) / (phi.(deltarho**2)]
-  QPair<QStringList, QMap<QString, double> > props = getProperties("Zimm");
+void SANSPlotSpecial::deriveZimm() {
+  // Intercept = (1/M).[(NA.d**2) / (c.(deltarho**2)] = (1/M).[(NA.d) /
+  // (phi.(deltarho**2)]
+  QPair<QStringList, QMap<QString, double>> props = getProperties("Zimm");
   QStringList unknown = props.first;
   QMap<QString, double> values = props.second;
 
   const double lhs = values["Intercept"] / Mantid::PhysicalConstants::N_A;
 
-  bool doable = ( unknown.indexOf("C") != -1 ) ^ ( unknown.indexOf("Phi") != -1 );
-  if ( ( ( unknown.size() > 1 ) && ! doable ) || ( unknown.size() > 2 ) )
-  {
+  bool doable = (unknown.indexOf("C") != -1) ^ (unknown.indexOf("Phi") != -1);
+  if (((unknown.size() > 1) && !doable) || (unknown.size() > 2)) {
     return;
   }
   QString route = "Phi";
-  if ( unknown.indexOf("C") == -1 ) { route = "C"; }
-
+  if (unknown.indexOf("C") == -1) {
+    route = "C";
+  }
 
-  foreach ( QString item, unknown )
-  {
+  foreach (QString item, unknown) {
     double val;
-    if ( item == "D" )
-    {
+    if (item == "D") {
       val = lhs * values["M"] * std::pow(values["Deltarho"], 2);
-      if ( route == "C" )
-      {
-        val = std::sqrt( val * values["C"] );
-      }
-      else
-      {
+      if (route == "C") {
+        val = std::sqrt(val * values["C"]);
+      } else {
         val = val * values["Phi"];
       }
-    }
-    else if ( item == "M" )
-    {
+    } else if (item == "M") {
       val = lhs * std::pow(values["Deltarho"], 2.0) / values["D"];
-      if ( route == "C" )
-      {
-        val = 1 / ( val * values["C"] / values["D"] );
-      }
-      else
-      {
-        val = 1 / ( val * values["Phi"] );
+      if (route == "C") {
+        val = 1 / (val * values["C"] / values["D"]);
+      } else {
+        val = 1 / (val * values["Phi"]);
       }
-    }
-    else if ( item == "C" )
-    {
-      val = 1 / ( lhs * ( values["M"] * std::pow(values["Deltarho"], 2) ) / std::pow(values["D"], 2) );
-    }
-    else if ( item == "Deltarho" )
-    {
+    } else if (item == "C") {
+      val = 1 / (lhs * (values["M"] * std::pow(values["Deltarho"], 2)) /
+                 std::pow(values["D"], 2));
+    } else if (item == "Deltarho") {
       val = lhs * values["M"] / values["D"];
-      if ( route == "C" )
-      {
+      if (route == "C") {
         val = val * values["C"] / values["D"];
-      }
-      else
-      {
+      } else {
         val = val * values["Phi"];
       }
-      val = std::sqrt( 1 / val ) ;
-    }
-    else if ( item == "Phi" )
-    {
-      val = lhs * ( values["M"] * std::pow(values["Deltarho"], 2) ) / values["D"];
+      val = std::sqrt(1 / val);
+    } else if (item == "Phi") {
+      val = lhs * (values["M"] * std::pow(values["Deltarho"], 2)) / values["D"];
+    } else {
+      continue;
     }
-    else { continue; }
-    
+
     values[item] = val;
     m_derivatives[item]->setText(QString::number(val));
   }
 }
 
-void SANSPlotSpecial::deriveKratky()
-{
-  // Plateau Intercept = [(2.c.M.(deltarho**2)) / (NA.(d**2).(Rg**2))] = [(2.phi.M.(deltarho**2)) / (NA.d.(Rg**2))]
-  QPair<QStringList, QMap<QString, double> > props = getProperties("Kratky");
+void SANSPlotSpecial::deriveKratky() {
+  // Plateau Intercept = [(2.c.M.(deltarho**2)) / (NA.(d**2).(Rg**2))] =
+  // [(2.phi.M.(deltarho**2)) / (NA.d.(Rg**2))]
+  QPair<QStringList, QMap<QString, double>> props = getProperties("Kratky");
   QStringList unknown = props.first;
   QMap<QString, double> values = props.second;
 
   const double lhs = Mantid::PhysicalConstants::N_A * values["Intercept"] / 2.0;
 
-  bool doable = ( unknown.indexOf("C") != -1 ) ^ ( unknown.indexOf("Phi") != -1 );
-  if ( ( ( unknown.size() > 1 ) && ! doable ) || ( unknown.size() > 2 ) )
-  {
+  bool doable = (unknown.indexOf("C") != -1) ^ (unknown.indexOf("Phi") != -1);
+  if (((unknown.size() > 1) && !doable) || (unknown.size() > 2)) {
     return;
   }
   QString route = "Phi";
-  if ( unknown.indexOf("C") == -1 ) { route = "C"; }
-  
-  foreach ( QString item, unknown )
-  {
+  if (unknown.indexOf("C") == -1) {
+    route = "C";
+  }
+
+  foreach (QString item, unknown) {
     double val;
 
-    if ( item == "C" )
-    {
-      val = lhs * ( std::pow(values["D"], 2) * std::pow(values["Rg"], 2) ) / ( values["M"] * std::pow(values["Deltarho"], 2) );
-    }
-    else if ( item == "M" )
-    {
-      val = lhs * ( values["D"] * std::pow(values["Rg"], 2) ) / std::pow(values["Deltarho"], 2);
-      if ( route == "C" )
-      {
-        val = val * ( values["D"] / values["C"] );
-      }
-      else
-      {
+    if (item == "C") {
+      val = lhs * (std::pow(values["D"], 2) * std::pow(values["Rg"], 2)) /
+            (values["M"] * std::pow(values["Deltarho"], 2));
+    } else if (item == "M") {
+      val = lhs * (values["D"] * std::pow(values["Rg"], 2)) /
+            std::pow(values["Deltarho"], 2);
+      if (route == "C") {
+        val = val * (values["D"] / values["C"]);
+      } else {
         val = val / values["Phi"];
       }
-    }
-    else if ( item == "Deltarho" )
-    {
-      val = lhs * ( values["D"] * std::pow(values["Rg"], 2) ) / values["M"];
-      if ( route == "C" )
-      {
-        val = val * ( values["D"] / values["C"] );
-      }
-      else
-      {
+    } else if (item == "Deltarho") {
+      val = lhs * (values["D"] * std::pow(values["Rg"], 2)) / values["M"];
+      if (route == "C") {
+        val = val * (values["D"] / values["C"]);
+      } else {
         val = val / values["Phi"];
       }
-      val = std::sqrt( val );
-    }
-    else if ( item == "D" )
-    {
-      val = lhs * std::pow(values["Rg"], 2) / ( values["M"] * std::pow(values["Deltarho"], 2 ) );
-      if ( route == "C" )
-      {
-        val = std::sqrt( 1 / ( val / values["C"] ) );
-      }
-      else
-      {
-        val = 1 / ( val / values["Phi"] );
+      val = std::sqrt(val);
+    } else if (item == "D") {
+      val = lhs * std::pow(values["Rg"], 2) /
+            (values["M"] * std::pow(values["Deltarho"], 2));
+      if (route == "C") {
+        val = std::sqrt(1 / (val / values["C"]));
+      } else {
+        val = 1 / (val / values["Phi"]);
       }
-    }
-    else if ( item == "Rg" )
-    {
-      val = lhs * values["D"] / ( values["M"] * std::pow(values["Deltarho"], 2 ) );
-      if ( route == "C" )
-      {
+    } else if (item == "Rg") {
+      val = lhs * values["D"] / (values["M"] * std::pow(values["Deltarho"], 2));
+      if (route == "C") {
         val = val * values["D"] / values["C"];
-      }
-      else
-      {
+      } else {
         val = val / values["Phi"];
       }
-      val = std::sqrt( 1 / val );
+      val = std::sqrt(1 / val);
+    } else if (item == "Phi") {
+      val = lhs * (values["D"] * std::pow(values["Rg"], 2)) /
+            (values["M"] * std::pow(values["Deltarho"], 2));
+    } else {
+      continue;
     }
-    else if ( item == "Phi" )
-    {
-      val = lhs * ( values["D"] * std::pow(values["Rg"], 2) ) / ( values["M"] * std::pow(values["Deltarho"], 2) );
-    }
-    else { continue; }
 
     values[item] = val;
     m_derivatives[item]->setText(QString::number(val));
   }
 }
 
-void SANSPlotSpecial::derivePorod()
-{
+void SANSPlotSpecial::derivePorod() {
   // Plateau Intercept = [(2.pi.c.(deltarho**2)) / d].(S / V)
-  QPair<QStringList, QMap<QString, double> > props = getProperties("Porod");
+  QPair<QStringList, QMap<QString, double>> props = getProperties("Porod");
   QStringList unknown = props.first;
   QMap<QString, double> values = props.second;
 
-  if ( unknown.size() != 1 ) { return; }
+  if (unknown.size() != 1) {
+    return;
+  }
 
   QString item = unknown.front();
   double val;
-  double lhs = values["Intercept"] / ( 2 * M_PI );
-
-  if ( item == "C" )
-  {
-    val = ( lhs * values["D"] ) / ( std::pow(values["Deltarho"], 2) * values["(S/V)"] );
-  }
-  else if ( item == "Deltarho" )
-  {
-    val = std::sqrt( ( lhs * values["D"] ) / ( values["C"] * values["(S/V)"] ) );
-  }
-  else if ( item == "(S/V)" )
-  {
-    val = ( lhs * values["D"] ) / ( std::pow(values["Deltarho"], 2) * values["C"] );
-  }
-  else if ( item == "D" )
-  {
-    val =  1 / ( lhs / ( values["C"] * std::pow(values["Deltarho"], 2) * values["(S/V)"] ) );
+  double lhs = values["Intercept"] / (2 * M_PI);
+
+  if (item == "C") {
+    val = (lhs * values["D"]) /
+          (std::pow(values["Deltarho"], 2) * values["(S/V)"]);
+  } else if (item == "Deltarho") {
+    val = std::sqrt((lhs * values["D"]) / (values["C"] * values["(S/V)"]));
+  } else if (item == "(S/V)") {
+    val = (lhs * values["D"]) / (std::pow(values["Deltarho"], 2) * values["C"]);
+  } else if (item == "D") {
+    val = 1 / (lhs / (values["C"] * std::pow(values["Deltarho"], 2) *
+                      values["(S/V)"]));
+  } else {
+    return;
   }
-  else { return; }
 
   m_derivatives[item]->setText(QString::number(val));
 }
 
-double SANSPlotSpecial::getValue(QTableWidgetItem* item)
-{
+double SANSPlotSpecial::getValue(QTableWidgetItem *item) {
   QString text = item->text().trimmed();
-  if ( text == "nan" ) { item->setText(""); }
+  if (text == "nan") {
+    item->setText("");
+  }
 
   bool ok(false);
   const double result = item->text().trimmed().toDouble(&ok);
 
-  if ( text.isEmpty() || !ok )
-  {
+  if (text.isEmpty() || !ok) {
     throw std::invalid_argument("Could not convert value given to a double.");
   }
 
   return result;
 }
 
-QPair<QStringList, QMap<QString, double> > SANSPlotSpecial::getProperties(const QString & transform)
-{
+QPair<QStringList, QMap<QString, double>>
+SANSPlotSpecial::getProperties(const QString &transform) {
   QStringList items = m_transforms[transform]->interceptDerivatives();
   items << "Intercept";
   QMap<QString, double> values;
   QStringList unknown;
-  foreach ( QString item, items )
-  {
-    try
-    {
+  foreach (QString item, items) {
+    try {
       double val = getValue(m_derivatives[item]);
       values[item] = val;
-    } catch ( std::invalid_argument & )
-    {
+    } catch (std::invalid_argument &) {
       unknown << item;
     }
   }
 
-  QPair<QStringList, QMap<QString, double> > result;
+  QPair<QStringList, QMap<QString, double>> result;
   result.first = unknown;
   result.second = values;
 
@@ -841,21 +790,19 @@ QPair<QStringList, QMap<QString, double> > SANSPlotSpecial::getProperties(const
 //--------------------------------------------------------------------
 //------- Utility "Transform" Class ----------------------------------
 //--------------------------------------------------------------------
-SANSPlotSpecial::Transform::Transform(Transform::TransformType type) : m_type(type), 
-  m_xWidgets(QList<QWidget*>()), m_yWidgets(QList<QWidget*>()), m_gDeriv(""), m_iDeriv("")
-{
+SANSPlotSpecial::Transform::Transform(Transform::TransformType type)
+    : m_type(type), m_xWidgets(QList<QWidget *>()),
+      m_yWidgets(QList<QWidget *>()), m_gDeriv(""), m_iDeriv("") {
   init();
 }
 
 SANSPlotSpecial::Transform::~Transform() {}
 
-void SANSPlotSpecial::Transform::init()
-{
+void SANSPlotSpecial::Transform::init() {
   m_xWidgets.clear();
   m_yWidgets.clear();
 
-  switch ( m_type )
-  {
+  switch (m_type) {
   case GuinierSpheres:
     m_xWidgets.append(new QLabel("Q^2"));
     m_yWidgets.append(new QLabel("ln (I)"));
@@ -929,84 +876,72 @@ void SANSPlotSpecial::Transform::init()
     tidyGeneral();
     break;
   }
-
 }
 
-std::vector<double> SANSPlotSpecial::Transform::functionConstants()
-{
+std::vector<double> SANSPlotSpecial::Transform::functionConstants() {
   std::vector<double> result;
-  if ( m_type != General ) { return result; }
-
-  foreach ( QWidget* item, m_yWidgets )
-  {
-    if ( strcmp(item->metaObject()->className(), "QLineEdit") == 0 )
-    {
-      item->setMaximumSize(25,20);
-      QString le = dynamic_cast<QLineEdit*>(item)->text();
+  if (m_type != General) {
+    return result;
+  }
+
+  foreach (QWidget *item, m_yWidgets) {
+    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0) {
+      item->setMaximumSize(25, 20);
+      QString le = dynamic_cast<QLineEdit *>(item)->text();
       result.push_back(le.toDouble());
     }
   }
 
-  foreach ( QWidget* item, m_xWidgets )
-  {
-    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0 )
-    {
-      item->setMaximumSize(25,20);
-      QString le = dynamic_cast<QLineEdit*>(item)->text();
+  foreach (QWidget *item, m_xWidgets) {
+    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0) {
+      item->setMaximumSize(25, 20);
+      QString le = dynamic_cast<QLineEdit *>(item)->text();
       result.push_back(le.toDouble());
     }
   }
   return result;
 }
 
-QPair<QStringList, QList<QPair<int, int> > > SANSPlotSpecial::Transform::derivatives()
-{
+QPair<QStringList, QList<QPair<int, int>>>
+SANSPlotSpecial::Transform::derivatives() {
   QStringList dg = m_gDeriv.split("|", QString::SkipEmptyParts);
   QStringList di = m_iDeriv.split("|", QString::SkipEmptyParts);
   QStringList items = dg + di;
 
-  QList<QPair<int, int> > positions;
+  QList<QPair<int, int>> positions;
 
-  for ( int i = 0; i < dg.size(); i++ )
-  {
+  for (int i = 0; i < dg.size(); i++) {
     positions.append(QPair<int, int>(i, SANSPlotSpecial::GradientLabels));
   }
 
-  for ( int i = 0; i < di.size(); i++ )
-  {
+  for (int i = 0; i < di.size(); i++) {
     positions.append(QPair<int, int>(i, SANSPlotSpecial::InterceptLabels));
   }
 
-  QPair<QStringList, QList<QPair<int, int> > > result = QPair<QStringList, QList<QPair<int, int> > >(items, positions);
+  QPair<QStringList, QList<QPair<int, int>>> result =
+      QPair<QStringList, QList<QPair<int, int>>>(items, positions);
   return result;
 }
 
-QStringList SANSPlotSpecial::Transform::interceptDerivatives()
-{
+QStringList SANSPlotSpecial::Transform::interceptDerivatives() {
   QStringList result = m_iDeriv.split("|", QString::SkipEmptyParts);
   return result;
 }
 
-void SANSPlotSpecial::Transform::tidyGeneral()
-{
-  foreach ( QWidget* item, m_xWidgets )
-  {
+void SANSPlotSpecial::Transform::tidyGeneral() {
+  foreach (QWidget *item, m_xWidgets) {
     item->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
-    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0)
-    {
-      item->setMaximumSize(25,20);
+    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0) {
+      item->setMaximumSize(25, 20);
     }
   }
 
-  foreach ( QWidget* item, m_yWidgets )
-  {
+  foreach (QWidget *item, m_yWidgets) {
     item->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
-    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0)
-    {
-      item->setMaximumSize(25,20);
+    if (strcmp(item->metaObject()->className(), "QLineEdit") == 0) {
+      item->setMaximumSize(25, 20);
     }
   }
 }
-
 }
 }
diff --git a/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp b/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
index 21c5973e69407b7308eac8284b160f35f0ef8b1f..f53dd25d38cdb9f8f3577468a7f8a186e478a9df 100644
--- a/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
+++ b/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
@@ -471,8 +471,8 @@ void SANSRunWindow::saveWorkspacesDialog() {
   // Connect the request for a zero-error-free workspace
   // cpp-check does not understand that the input are two references
   connect(m_saveWorkspaces,
-          SIGNAL(createZeroErrorFreeWorkspace(QString &, QString &)),
-          this, SLOT(createZeroErrorFreeClone(QString &, QString &)));
+          SIGNAL(createZeroErrorFreeWorkspace(QString &, QString &)), this,
+          SLOT(createZeroErrorFreeClone(QString &, QString &)));
   // Connect the request for deleting a zero-error-free workspace
   connect(m_saveWorkspaces, SIGNAL(deleteZeroErrorFreeWorkspace(QString &)),
           this, SLOT(deleteZeroErrorFreeClone(QString &)));
@@ -808,8 +808,7 @@ bool SANSRunWindow::loadUserFile() {
   QString errors =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().user_settings.execute(i."
-                              "ReductionSingleton())")
-          .trimmed();
+                              "ReductionSingleton())").trimmed();
   // create a string list with a string for each line
   const QStringList allOutput = errors.split("\n");
   errors.clear();
@@ -835,9 +834,8 @@ bool SANSRunWindow::loadUserFile() {
       runReduceScriptFunction("print i.ReductionSingleton().mask.min_radius")
           .toDouble();
   m_uiForm.rad_min->setText(QString::number(dbl_param * unit_conv));
-  dbl_param =
-      runReduceScriptFunction("print i.ReductionSingleton().mask.max_radius")
-          .toDouble();
+  dbl_param = runReduceScriptFunction(
+                  "print i.ReductionSingleton().mask.max_radius").toDouble();
   m_uiForm.rad_max->setText(QString::number(dbl_param * unit_conv));
   // EventsTime
   m_uiForm.l_events_binning->setText(
@@ -847,12 +845,10 @@ bool SANSRunWindow::loadUserFile() {
       "print i.ReductionSingleton().to_wavelen.wav_low"));
   m_uiForm.wav_max->setText(
       runReduceScriptFunction(
-          "print i.ReductionSingleton().to_wavelen.wav_high")
-          .trimmed());
+          "print i.ReductionSingleton().to_wavelen.wav_high").trimmed());
   const QString wav_step =
       runReduceScriptFunction(
-          "print i.ReductionSingleton().to_wavelen.wav_step")
-          .trimmed();
+          "print i.ReductionSingleton().to_wavelen.wav_step").trimmed();
   setLimitStepParameter("wavelength", wav_step, m_uiForm.wav_dw,
                         m_uiForm.wav_dw_opt);
   // Q
@@ -884,24 +880,20 @@ bool SANSRunWindow::loadUserFile() {
   m_uiForm.frontDetRescale->setText(
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().instrument.getDetector('"
-                              "FRONT').rescaleAndShift.scale")
-          .trimmed());
+                              "FRONT').rescaleAndShift.scale").trimmed());
   m_uiForm.frontDetShift->setText(
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().instrument.getDetector('"
-                              "FRONT').rescaleAndShift.shift")
-          .trimmed());
+                              "FRONT').rescaleAndShift.shift").trimmed());
 
   QString fitScale =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().instrument.getDetector('"
-                              "FRONT').rescaleAndShift.fitScale")
-          .trimmed();
+                              "FRONT').rescaleAndShift.fitScale").trimmed();
   QString fitShift =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().instrument.getDetector('"
-                              "FRONT').rescaleAndShift.fitShift")
-          .trimmed();
+                              "FRONT').rescaleAndShift.fitShift").trimmed();
 
   if (fitScale == "True")
     m_uiForm.frontDetRescaleCB->setChecked(true);
@@ -923,13 +915,11 @@ bool SANSRunWindow::loadUserFile() {
     m_uiForm.frontDetQmin->setText(
         runReduceScriptFunction("print "
                                 "i.ReductionSingleton().instrument.getDetector("
-                                "'FRONT').rescaleAndShift.qMin")
-            .trimmed());
+                                "'FRONT').rescaleAndShift.qMin").trimmed());
     m_uiForm.frontDetQmax->setText(
         runReduceScriptFunction("print "
                                 "i.ReductionSingleton().instrument.getDetector("
-                                "'FRONT').rescaleAndShift.qMax")
-            .trimmed());
+                                "'FRONT').rescaleAndShift.qMax").trimmed());
   } else
     m_uiForm.frontDetQrangeOnOff->setChecked(false);
 
@@ -979,15 +969,15 @@ bool SANSRunWindow::loadUserFile() {
       m_uiForm.enableFrontFlood_ck->checkState() == Qt::Checked);
 
   // Scale factor
-  dbl_param = runReduceScriptFunction(
-                  "print i.ReductionSingleton()._corr_and_scale.rescale")
-                  .toDouble();
+  dbl_param =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton()._corr_and_scale.rescale").toDouble();
   m_uiForm.scale_factor->setText(QString::number(dbl_param / 100.));
 
   // Sample offset if one has been specified
-  dbl_param = runReduceScriptFunction(
-                  "print i.ReductionSingleton().instrument.SAMPLE_Z_CORR")
-                  .toDouble();
+  dbl_param =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton().instrument.SAMPLE_Z_CORR").toDouble();
   m_uiForm.smpl_offset->setText(QString::number(dbl_param * unit_conv));
 
   // Centre coordinates
@@ -996,9 +986,9 @@ bool SANSRunWindow::loadUserFile() {
   // Set the beam finder specific settings
   setBeamFinderDetails();
   // get the scale factor1 for the beam centre to scale it correctly
-  dbl_param = runReduceScriptFunction(
-                  "print i.ReductionSingleton().get_beam_center('rear')[0]")
-                  .toDouble();
+  dbl_param =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton().get_beam_center('rear')[0]").toDouble();
   double dbl_paramsf =
       runReduceScriptFunction(
           "print i.ReductionSingleton().get_beam_center_scale_factor1()")
@@ -1009,9 +999,9 @@ bool SANSRunWindow::loadUserFile() {
       runReduceScriptFunction(
           "print i.ReductionSingleton().get_beam_center_scale_factor2()")
           .toDouble();
-  dbl_param = runReduceScriptFunction(
-                  "print i.ReductionSingleton().get_beam_center('rear')[1]")
-                  .toDouble();
+  dbl_param =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton().get_beam_center('rear')[1]").toDouble();
   m_uiForm.rear_beam_y->setText(QString::number(dbl_param * dbl_paramsf));
   // front
   dbl_param = runReduceScriptFunction(
@@ -1035,15 +1025,14 @@ bool SANSRunWindow::loadUserFile() {
   // Read the extra length for the gravity correction
   const double extraLengthParam =
       runReduceScriptFunction(
-          "print i.ReductionSingleton().to_Q.get_extra_length()")
-          .toDouble();
+          "print i.ReductionSingleton().to_Q.get_extra_length()").toDouble();
   m_uiForm.gravity_extra_length_line_edit->setText(
       QString::number(extraLengthParam));
 
   ////Detector bank: support REAR, FRONT, HAB, BOTH, MERGED, MERGE options
-  QString detName = runReduceScriptFunction(
-                        "print i.ReductionSingleton().instrument.det_selection")
-                        .trimmed();
+  QString detName =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton().instrument.det_selection").trimmed();
 
   if (detName == "REAR" || detName == "MAIN") {
     m_uiForm.detbank_sel->setCurrentIndex(0);
@@ -1945,8 +1934,7 @@ void SANSRunWindow::saveFileBrowse() {
   QString prevPath =
       prevValues.value("dir", QString::fromStdString(
                                   ConfigService::Instance().getString(
-                                      "defaultsave.directory")))
-          .toString();
+                                      "defaultsave.directory"))).toString();
 
   const QString filter = ";;AllFiles (*.*)";
 
@@ -2872,8 +2860,7 @@ void SANSRunWindow::handleRunFindCentre() {
   QString errors =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().user_settings.execute(i."
-                              "ReductionSingleton())")
-          .trimmed();
+                              "ReductionSingleton())").trimmed();
 
   g_centreFinderLog.notice() << result.toStdString() << "\n";
 
@@ -3099,8 +3086,7 @@ void SANSRunWindow::handleInstrumentChange() {
       "print i.ReductionSingleton().instrument.cur_detector().name()");
   QString detectorSelection =
       runReduceScriptFunction(
-          "print i.ReductionSingleton().instrument.det_selection")
-          .trimmed();
+          "print i.ReductionSingleton().instrument.det_selection").trimmed();
   int ind = m_uiForm.detbank_sel->findText(detect);
   // We set the detector selection only if nothing is set yet.
   // Previously, we didn't handle merged and both at this point
@@ -3323,14 +3309,14 @@ void SANSRunWindow::updateTransInfo(int state) {
 
   if (state == Qt::Checked) {
     _min->setEnabled(true);
-    _min->setText(runReduceScriptFunction(
-                      "print i.ReductionSingleton().instrument.WAV_RANGE_MIN")
-                      .trimmed());
+    _min->setText(
+        runReduceScriptFunction(
+            "print i.ReductionSingleton().instrument.WAV_RANGE_MIN").trimmed());
 
     _max->setEnabled(true);
-    _max->setText(runReduceScriptFunction(
-                      "print i.ReductionSingleton().instrument.WAV_RANGE_MAX")
-                      .trimmed());
+    _max->setText(
+        runReduceScriptFunction(
+            "print i.ReductionSingleton().instrument.WAV_RANGE_MAX").trimmed());
 
   } else {
     _min->setEnabled(false);
@@ -3821,8 +3807,7 @@ void SANSRunWindow::loadTransmissionSettings() {
   QString transMin =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().transmission_calculator."
-                              "lambdaMin('SAMPLE')")
-          .trimmed();
+                              "lambdaMin('SAMPLE')").trimmed();
   if (transMin == "None") {
     m_uiForm.transFit_ck->setChecked(false);
   } else {
@@ -3831,15 +3816,13 @@ void SANSRunWindow::loadTransmissionSettings() {
     m_uiForm.trans_max->setText(
         runReduceScriptFunction("print "
                                 "i.ReductionSingleton().transmission_"
-                                "calculator.lambdaMax('SAMPLE')")
-            .trimmed());
+                                "calculator.lambdaMax('SAMPLE')").trimmed());
   }
 
   QString text =
       runReduceScriptFunction("print "
                               "i.ReductionSingleton().transmission_calculator."
-                              "fitMethod('SAMPLE')")
-          .trimmed();
+                              "fitMethod('SAMPLE')").trimmed();
   int index = m_uiForm.trans_opt->findText(text, Qt::MatchFixedString);
   if (index >= 0) {
     m_uiForm.trans_opt->setCurrentIndex(index);
@@ -3851,8 +3834,7 @@ void SANSRunWindow::loadTransmissionSettings() {
 
   transMin = runReduceScriptFunction("print "
                                      "i.ReductionSingleton().transmission_"
-                                     "calculator.lambdaMin('CAN')")
-                 .trimmed();
+                                     "calculator.lambdaMin('CAN')").trimmed();
   if (transMin == "None") {
     m_uiForm.transFit_ck_can->setChecked(false);
   } else {
@@ -3861,13 +3843,11 @@ void SANSRunWindow::loadTransmissionSettings() {
     m_uiForm.trans_max_can->setText(
         runReduceScriptFunction("print "
                                 "i.ReductionSingleton().transmission_"
-                                "calculator.lambdaMax('CAN')")
-            .trimmed());
+                                "calculator.lambdaMax('CAN')").trimmed());
   }
   text = runReduceScriptFunction("print "
                                  "i.ReductionSingleton().transmission_"
-                                 "calculator.fitMethod('CAN')")
-             .trimmed();
+                                 "calculator.fitMethod('CAN')").trimmed();
   index = m_uiForm.trans_opt_can->findText(text, Qt::MatchFixedString);
   if (index >= 0) {
     m_uiForm.trans_opt_can->setCurrentIndex(index);
@@ -4534,8 +4514,7 @@ void SANSRunWindow::updateBeamCenterCoordinates() {
   // from the ticket #5942 both detectors have center coordinates
   double dbl_param =
       runReduceScriptFunction(
-          "print i.ReductionSingleton().get_beam_center('rear')[0]")
-          .toDouble();
+          "print i.ReductionSingleton().get_beam_center('rear')[0]").toDouble();
   // get the scale factor1 for the beam centre to scale it correctly
   double dbl_paramsf =
       runReduceScriptFunction(
@@ -4547,9 +4526,9 @@ void SANSRunWindow::updateBeamCenterCoordinates() {
       runReduceScriptFunction(
           "print i.ReductionSingleton().get_beam_center_scale_factor2()")
           .toDouble();
-  dbl_param = runReduceScriptFunction(
-                  "print i.ReductionSingleton().get_beam_center('rear')[1]")
-                  .toDouble();
+  dbl_param =
+      runReduceScriptFunction(
+          "print i.ReductionSingleton().get_beam_center('rear')[1]").toDouble();
   m_uiForm.rear_beam_y->setText(QString::number(dbl_param * dbl_paramsf));
   // front
   dbl_param = runReduceScriptFunction(
@@ -4570,9 +4549,9 @@ void SANSRunWindow::setBeamFinderDetails() {
   auto instrumentName = m_uiForm.inst_opt->currentText();
 
   // Set the labels according to the instrument
-  auto requiresAngle = runReduceScriptFunction(
-                           "print i.is_current_workspace_an_angle_workspace()")
-                           .simplified();
+  auto requiresAngle =
+      runReduceScriptFunction(
+          "print i.is_current_workspace_an_angle_workspace()").simplified();
   QString labelPosition;
   if (requiresAngle == m_constants.getPythonTrueKeyword()) {
     labelPosition = "Current ( " + QString(QChar(0x03B2)) + " , y ) [";
diff --git a/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/MantidQt/CustomInterfaces/src/SampleTransmission.cpp
index 429180263ff52a01d992b9aaaeb745a2eee2e091..969378233a87772fe533bb8a2a74202addf3ffe9 100644
--- a/MantidQt/CustomInterfaces/src/SampleTransmission.cpp
+++ b/MantidQt/CustomInterfaces/src/SampleTransmission.cpp
@@ -8,42 +8,34 @@
 #include "MantidQtAPI/HelpWindow.h"
 #include "MantidQtCustomInterfaces/UserInputValidator.h"
 
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("SampleTransmission");
+namespace {
+Mantid::Kernel::Logger g_log("SampleTransmission");
 }
 
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  DECLARE_SUBWINDOW(SampleTransmission)
+// Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt {
+namespace CustomInterfaces {
+DECLARE_SUBWINDOW(SampleTransmission)
 }
 }
 
 using namespace MantidQt::CustomInterfaces;
 using namespace Mantid::API;
 
-
 //----------------------
 // Public member functions
 //----------------------
-///Constructor
-SampleTransmission::SampleTransmission(QWidget *parent) :
-  UserSubWindow(parent),
-  m_algRunner(new API::AlgorithmRunner(this))
-{
-  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(algorithmComplete(bool)));
+/// Constructor
+SampleTransmission::SampleTransmission(QWidget *parent)
+    : UserSubWindow(parent), m_algRunner(new API::AlgorithmRunner(this)) {
+  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this,
+          SLOT(algorithmComplete(bool)));
 }
 
-
 /**
  * Set up the dialog layout.
  */
-void SampleTransmission::initLayout()
-{
+void SampleTransmission::initLayout() {
   m_uiForm.setupUi(this);
   connect(m_uiForm.pbCalculate, SIGNAL(clicked()), this, SLOT(calculate()));
   connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(showHelp()));
@@ -51,16 +43,14 @@ void SampleTransmission::initLayout()
   validate(true);
 }
 
-
 /**
  * Opens the Qt help page for the interface.
  */
-void SampleTransmission::showHelp()
-{
-  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("SampleTransmissionCalculator"));
+void SampleTransmission::showHelp() {
+  MantidQt::API::HelpWindow::showCustomInterface(
+      NULL, QString("SampleTransmissionCalculator"));
 }
 
-
 /**
  * Validate user input.
  * Outputs any warnings to the results log at warning level.
@@ -68,87 +58,83 @@ void SampleTransmission::showHelp()
  * @param silent If the results should not be logged
  * @return Result of validation
  */
-bool SampleTransmission::validate(bool silent)
-{
+bool SampleTransmission::validate(bool silent) {
   UserInputValidator uiv;
 
   // Valudate input binning
   int wavelengthBinning = m_uiForm.cbBinningType->currentIndex();
-  switch(wavelengthBinning)
-  {
-    // Single
-    case 0:
-      uiv.checkBins(m_uiForm.spSingleLow->value(),
-                    m_uiForm.spSingleWidth->value(),
-                    m_uiForm.spSingleHigh->value());
-      break;
-
-    // Multiple
-    case 1:
-      uiv.checkFieldIsNotEmpty("Multiple binning",
-                               m_uiForm.leMultiple,
-                               m_uiForm.valMultiple);
-      break;
+  switch (wavelengthBinning) {
+  // Single
+  case 0:
+    uiv.checkBins(m_uiForm.spSingleLow->value(),
+                  m_uiForm.spSingleWidth->value(),
+                  m_uiForm.spSingleHigh->value());
+    break;
+
+  // Multiple
+  case 1:
+    uiv.checkFieldIsNotEmpty("Multiple binning", m_uiForm.leMultiple,
+                             m_uiForm.valMultiple);
+    break;
   }
 
   // Validate chemical formula
-  uiv.checkFieldIsNotEmpty("Chemical Formula",
-                           m_uiForm.leChemicalFormula,
+  uiv.checkFieldIsNotEmpty("Chemical Formula", m_uiForm.leChemicalFormula,
                            m_uiForm.valChemicalFormula);
 
   // Ensure number density is not zero
-  uiv.setErrorLabel(m_uiForm.valNumberDensity,
-    uiv.checkNotEqual("Number Density", m_uiForm.spNumberDensity->value()));
+  uiv.setErrorLabel(
+      m_uiForm.valNumberDensity,
+      uiv.checkNotEqual("Number Density", m_uiForm.spNumberDensity->value()));
 
   // Ensure thickness is not zero
-  uiv.setErrorLabel(m_uiForm.valThickness,
-    uiv.checkNotEqual("Thickness", m_uiForm.spThickness->value()));
+  uiv.setErrorLabel(
+      m_uiForm.valThickness,
+      uiv.checkNotEqual("Thickness", m_uiForm.spThickness->value()));
 
   // Give error message
-  if(!silent && !uiv.isAllInputValid())
+  if (!silent && !uiv.isAllInputValid())
     showInformationBox(uiv.generateErrorMessage());
 
   return uiv.isAllInputValid();
 }
 
-
 /**
  * Performs a calculation with the current settings
  */
-void SampleTransmission::calculate()
-{
+void SampleTransmission::calculate() {
   // Do not try to run with invalid input
-  if(!validate())
+  if (!validate())
     return;
 
   // Create the transmission calculation algorithm
-  IAlgorithm_sptr transCalcAlg = AlgorithmManager::Instance().create("CalculateSampleTransmission");
+  IAlgorithm_sptr transCalcAlg =
+      AlgorithmManager::Instance().create("CalculateSampleTransmission");
   transCalcAlg->initialize();
 
   // Set the wavelength binning based on type set in UI
   int wavelengthBinning = m_uiForm.cbBinningType->currentIndex();
-  switch(wavelengthBinning)
-  {
-    // Single
-    case 0:
-    {
-      QStringList params;
-      params << m_uiForm.spSingleLow->text()
-             << m_uiForm.spSingleWidth->text()
-             << m_uiForm.spSingleHigh->text();
-      QString binString = params.join(",");
-      transCalcAlg->setProperty("WavelengthRange", binString.toStdString());
-      break;
-    }
-
-    // Multiple
-    case 1:
-      transCalcAlg->setProperty("WavelengthRange", m_uiForm.leMultiple->text().toStdString());
-      break;
+  switch (wavelengthBinning) {
+  // Single
+  case 0: {
+    QStringList params;
+    params << m_uiForm.spSingleLow->text() << m_uiForm.spSingleWidth->text()
+           << m_uiForm.spSingleHigh->text();
+    QString binString = params.join(",");
+    transCalcAlg->setProperty("WavelengthRange", binString.toStdString());
+    break;
+  }
+
+  // Multiple
+  case 1:
+    transCalcAlg->setProperty("WavelengthRange",
+                              m_uiForm.leMultiple->text().toStdString());
+    break;
   }
 
   // Set sample material properties
-  transCalcAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString());
+  transCalcAlg->setProperty("ChemicalFormula",
+                            m_uiForm.leChemicalFormula->text().toStdString());
   transCalcAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value());
   transCalcAlg->setProperty("Thickness", m_uiForm.spThickness->value());
 
@@ -162,25 +148,24 @@ void SampleTransmission::calculate()
   m_algRunner->startAlgorithm(transCalcAlg);
 }
 
-
 /**
  * Handles completion of the calculation algorithm.
  *
  * @param error If the algorithm exited with an error
  */
-void SampleTransmission::algorithmComplete(bool error)
-{
+void SampleTransmission::algorithmComplete(bool error) {
   using namespace Mantid::Kernel;
 
   // Ignore errors
-  if(error)
-  {
-    showInformationBox("Transmission calculation failed.\nSee Results Log for details.");
+  if (error) {
+    showInformationBox(
+        "Transmission calculation failed.\nSee Results Log for details.");
     return;
   }
 
   MatrixWorkspace_sptr ws =
-    AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("CalculatedSampleTransmission");
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          "CalculatedSampleTransmission");
 
   // Fill the output table
   double scattering = ws->dataY(1)[0];
@@ -204,8 +189,8 @@ void SampleTransmission::algorithmComplete(bool error)
   transmissionStats["Median"] = stats.median;
   transmissionStats["Std. Dev."] = stats.standard_deviation;
 
-  for(auto it = transmissionStats.begin(); it != transmissionStats.end(); ++it)
-  {
+  for (auto it = transmissionStats.begin(); it != transmissionStats.end();
+       ++it) {
     QTreeWidgetItem *item = new QTreeWidgetItem();
     item->setText(0, it.key());
     item->setText(1, QString::number(it.value()));
diff --git a/MantidQt/CustomInterfaces/src/StepScan.cpp b/MantidQt/CustomInterfaces/src/StepScan.cpp
index 7d00bb3d8125789af76f097685b3a4456cdfd37a..dd6701a6c5003a3e3ea4901d15ed661faf03a5f9 100644
--- a/MantidQt/CustomInterfaces/src/StepScan.cpp
+++ b/MantidQt/CustomInterfaces/src/StepScan.cpp
@@ -15,12 +15,10 @@
 #include <Poco/ActiveResult.h>
 #include <Poco/Thread.h>
 
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
+namespace MantidQt {
+namespace CustomInterfaces {
 
-//Register the class with the factory
+// Register the class with the factory
 DECLARE_SUBWINDOW(StepScan)
 
 using namespace Mantid::Kernel;
@@ -28,31 +26,29 @@ using namespace Mantid::API;
 
 /// Constructor
 StepScan::StepScan(QWidget *parent)
-  : UserSubWindow(parent),
-    m_instrument(ConfigService::Instance().getInstrument().name()),
-    m_algRunner(new API::AlgorithmRunner(this)),
-    m_addObserver(*this, &StepScan::handleAddEvent),
-    m_replObserver(*this, &StepScan::handleReplEvent),
-    m_replaceObserverAdded(false)
-{
-}
-
-StepScan::~StepScan()
-{
+    : UserSubWindow(parent),
+      m_instrument(ConfigService::Instance().getInstrument().name()),
+      m_algRunner(new API::AlgorithmRunner(this)),
+      m_addObserver(*this, &StepScan::handleAddEvent),
+      m_replObserver(*this, &StepScan::handleReplEvent),
+      m_replaceObserverAdded(false) {}
+
+StepScan::~StepScan() {
   // Stop any async algorithm
   m_algRunner->cancelRunningAlgorithm();
   // Stop live data collection, if running
   m_uiForm.mWRunFiles->stopLiveAlgorithm();
   // Disconnect the observers for the mask workspace combobox
-  AnalysisDataService::Instance().notificationCenter.removeObserver(m_addObserver);
-  AnalysisDataService::Instance().notificationCenter.removeObserver(m_replObserver);
+  AnalysisDataService::Instance().notificationCenter.removeObserver(
+      m_addObserver);
+  AnalysisDataService::Instance().notificationCenter.removeObserver(
+      m_replObserver);
   // Clean up any hidden workspaces created
   cleanupWorkspaces();
 }
 
 /// Set up the dialog layout
-void StepScan::initLayout()
-{
+void StepScan::initLayout() {
   m_uiForm.setupUi(this);
 
   // I couldn't see a way to set a validator on a qlineedit in designer
@@ -61,64 +57,72 @@ void StepScan::initLayout()
 
   setWindowTitle(windowTitle() + " - " + QString::fromStdString(m_instrument));
 
-  connect( m_uiForm.mWRunFiles, SIGNAL(liveButtonPressed(bool)), SLOT(triggerLiveListener(bool)), Qt::QueuedConnection );
+  connect(m_uiForm.mWRunFiles, SIGNAL(liveButtonPressed(bool)),
+          SLOT(triggerLiveListener(bool)), Qt::QueuedConnection);
 
-  connect( m_uiForm.launchInstView, SIGNAL(clicked()), SLOT(launchInstrumentWindow()) );
+  connect(m_uiForm.launchInstView, SIGNAL(clicked()),
+          SLOT(launchInstrumentWindow()));
 
-  connect( m_uiForm.mWRunFiles, SIGNAL(filesFound()), SLOT(loadFile()) );
-  connect( this, SIGNAL(logsAvailable(const Mantid::API::MatrixWorkspace_const_sptr &)),
-           SLOT(fillPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr &)) );
+  connect(m_uiForm.mWRunFiles, SIGNAL(filesFound()), SLOT(loadFile()));
+  connect(this, SIGNAL(logsAvailable(
+                    const Mantid::API::MatrixWorkspace_const_sptr &)),
+          SLOT(fillPlotVarCombobox(
+              const Mantid::API::MatrixWorkspace_const_sptr &)));
 
-  connect( m_uiForm.helpButton, SIGNAL(clicked()), SLOT(helpClicked()) );
-  connect( m_uiForm.startButton, SIGNAL(clicked()), SLOT(runStepScanAlg()) );
-  connect( m_uiForm.closeButton, SIGNAL(clicked()), this->parent(), SLOT(close()) );
+  connect(m_uiForm.helpButton, SIGNAL(clicked()), SLOT(helpClicked()));
+  connect(m_uiForm.startButton, SIGNAL(clicked()), SLOT(runStepScanAlg()));
+  connect(m_uiForm.closeButton, SIGNAL(clicked()), this->parent(),
+          SLOT(close()));
 }
 
-void StepScan::cleanupWorkspaces()
-{
-  if ( ! m_inputWSName.empty() )
-  {
+void StepScan::cleanupWorkspaces() {
+  if (!m_inputWSName.empty()) {
     // Get a reference to the analysis data service
-    auto& ADS = AnalysisDataService::Instance();
-    // Clean up, checking first that those that may not exist do (to avoid a warning in the log)
-    ADS.remove( m_inputWSName );
+    auto &ADS = AnalysisDataService::Instance();
+    // Clean up, checking first that those that may not exist do (to avoid a
+    // warning in the log)
+    ADS.remove(m_inputWSName);
     const std::string monitorWSName = m_inputWSName + "_monitors";
-    if ( ADS.doesExist( monitorWSName ) ) ADS.remove( monitorWSName );
+    if (ADS.doesExist(monitorWSName))
+      ADS.remove(monitorWSName);
     m_inputWSName.clear();
-    if ( ADS.doesExist( m_plotWSName ) ) ADS.remove( m_plotWSName );
+    if (ADS.doesExist(m_plotWSName))
+      ADS.remove(m_plotWSName);
     m_plotWSName.clear();
-    disconnect( SIGNAL(logsUpdated(const Mantid::API::MatrixWorkspace_const_sptr &)) );
+    disconnect(
+        SIGNAL(logsUpdated(const Mantid::API::MatrixWorkspace_const_sptr &)));
   }
 
   m_uiForm.startButton->setEnabled(false);
   m_uiForm.launchInstView->setEnabled(false);
   m_uiForm.plotVariable->setEnabled(false);
   // Disconnect anything listening to the comboboxes
-  m_uiForm.plotVariable->disconnect(SIGNAL(currentIndexChanged(const QString &)));
-  m_uiForm.normalization->disconnect(SIGNAL(currentIndexChanged(const QString &)));
+  m_uiForm.plotVariable->disconnect(
+      SIGNAL(currentIndexChanged(const QString &)));
+  m_uiForm.normalization->disconnect(
+      SIGNAL(currentIndexChanged(const QString &)));
 }
 
 /** Slot that is called when the live data button is clicked
  *  @param checked Whether the button is being enabled (true) or disabled
  */
-void StepScan::triggerLiveListener(bool checked)
-{
-  if ( checked )
-  {
+void StepScan::triggerLiveListener(bool checked) {
+  if (checked) {
     startLiveListener();
-  }
-  else
-  {
+  } else {
     m_uiForm.mWRunFiles->stopLiveAlgorithm();
     cleanupWorkspaces();
   }
 }
 
-void StepScan::startLiveListener()
-{
-  if ( ! LiveListenerFactory::Instance().create(m_instrument,false)->buffersEvents() )
-  {
-    QMessageBox::critical(this,"Invalid live stream","This interface requires event data.\nThe live data for " + QString::fromStdString(m_instrument) + " is in histogram form");
+void StepScan::startLiveListener() {
+  if (!LiveListenerFactory::Instance()
+           .create(m_instrument, false)
+           ->buffersEvents()) {
+    QMessageBox::critical(
+        this, "Invalid live stream",
+        "This interface requires event data.\nThe live data for " +
+            QString::fromStdString(m_instrument) + " is in histogram form");
     m_uiForm.mWRunFiles->liveButtonSetChecked(false);
     m_uiForm.mWRunFiles->liveButtonSetEnabled(false);
     return;
@@ -127,18 +131,20 @@ void StepScan::startLiveListener()
   // Remove any previously-loaded workspaces
   cleanupWorkspaces();
 
-  connect(m_algRunner, SIGNAL(algorithmComplete(bool)), SLOT(startLiveListenerComplete(bool)));
+  connect(m_algRunner, SIGNAL(algorithmComplete(bool)),
+          SLOT(startLiveListenerComplete(bool)));
 
-  IAlgorithm_sptr startLiveData = AlgorithmManager::Instance().create("StartLiveData");
-  startLiveData->setProperty("UpdateEvery",5.0);
-  startLiveData->setProperty("FromNow",false);
-  startLiveData->setProperty("FromStartOfRun",true);
-  startLiveData->setProperty("Instrument",m_instrument);
+  IAlgorithm_sptr startLiveData =
+      AlgorithmManager::Instance().create("StartLiveData");
+  startLiveData->setProperty("UpdateEvery", 5.0);
+  startLiveData->setProperty("FromNow", false);
+  startLiveData->setProperty("FromStartOfRun", true);
+  startLiveData->setProperty("Instrument", m_instrument);
   m_inputWSName = "__live";
-  startLiveData->setProperty("OutputWorkspace",m_inputWSName);
-  if ( ! startLiveData->validateInputs().empty() )
-  {
-    QMessageBox::critical(this,"StartLiveData failed","Unable to start live data collection");
+  startLiveData->setProperty("OutputWorkspace", m_inputWSName);
+  if (!startLiveData->validateInputs().empty()) {
+    QMessageBox::critical(this, "StartLiveData failed",
+                          "Unable to start live data collection");
     m_uiForm.mWRunFiles->liveButtonSetChecked(false);
     return;
   }
@@ -146,34 +152,34 @@ void StepScan::startLiveListener()
   m_algRunner->startAlgorithm(startLiveData);
 }
 
-void StepScan::startLiveListenerComplete(bool error)
-{
-  disconnect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(startLiveListenerComplete(bool)));
-  if ( ! error )
-  {
+void StepScan::startLiveListenerComplete(bool error) {
+  disconnect(m_algRunner, SIGNAL(algorithmComplete(bool)), this,
+             SLOT(startLiveListenerComplete(bool)));
+  if (!error) {
     // Keep track of the algorithm that's pulling in the live data
-    m_uiForm.mWRunFiles->setLiveAlgorithm(m_algRunner->getAlgorithm()->getProperty("MonitorLiveData"));
+    m_uiForm.mWRunFiles->setLiveAlgorithm(
+        m_algRunner->getAlgorithm()->getProperty("MonitorLiveData"));
 
     setupOptionControls();
 
     addReplaceObserverOnce();
-    connect( this, SIGNAL(logsUpdated(const Mantid::API::MatrixWorkspace_const_sptr &)),
-             SLOT(expandPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr &)) );
-  }
-  else
-  {
-    QMessageBox::critical(this,"StartLiveData failed","Unable to start live data collection");
+    connect(this, SIGNAL(logsUpdated(
+                      const Mantid::API::MatrixWorkspace_const_sptr &)),
+            SLOT(expandPlotVarCombobox(
+                const Mantid::API::MatrixWorkspace_const_sptr &)));
+  } else {
+    QMessageBox::critical(this, "StartLiveData failed",
+                          "Unable to start live data collection");
     m_uiForm.mWRunFiles->liveButtonSetChecked(false);
   }
 }
 
-void StepScan::loadFile(bool async)
-{
+void StepScan::loadFile(bool async) {
   const QString filename = m_uiForm.mWRunFiles->getUserInput().toString();
   // This handles the fact that mwRunFiles emits the filesFound signal more than
-  // we want (on some platforms). TODO: Consider dealing with this up in mwRunFiles.
-  if ( filename != m_inputFilename && m_uiForm.mWRunFiles->isValid() )
-  {
+  // we want (on some platforms). TODO: Consider dealing with this up in
+  // mwRunFiles.
+  if (filename != m_inputFilename && m_uiForm.mWRunFiles->isValid()) {
     m_inputFilename = filename;
 
     // Remove any previously-loaded workspaces
@@ -182,266 +188,269 @@ void StepScan::loadFile(bool async)
     IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Load");
     try {
       alg->setPropertyValue("Filename", filename.toStdString());
-      if ( m_uiForm.mWRunFiles->getFilenames().size() == 1 )
-      {
+      if (m_uiForm.mWRunFiles->getFilenames().size() == 1) {
         m_inputWSName = "__" + QFileInfo(filename).baseName().toStdString();
-      }
-      else
-      {
+      } else {
         m_inputWSName = "__multifiles";
       }
       alg->setPropertyValue("OutputWorkspace", m_inputWSName);
       alg->setProperty("LoadMonitors", true);
-    }
-    catch (std::exception&) // Have to catch at this level as different exception types can happen
+    } catch (std::exception &) // Have to catch at this level as different
+                               // exception types can happen
     {
-      QMessageBox::warning(this,"File loading failed","Is this an event nexus file?");
+      QMessageBox::warning(this, "File loading failed",
+                           "Is this an event nexus file?");
       return;
     }
 
-    m_uiForm.statusText->setText("<i><font color='darkblue'>Loading data...</font></i>");
+    m_uiForm.statusText->setText(
+        "<i><font color='darkblue'>Loading data...</font></i>");
 
-    if ( async )
-    {
-      connect(m_algRunner, SIGNAL(algorithmComplete(bool)), SLOT(loadFileComplete(bool)));
+    if (async) {
+      connect(m_algRunner, SIGNAL(algorithmComplete(bool)),
+              SLOT(loadFileComplete(bool)));
       m_algRunner->startAlgorithm(alg);
-    }
-    else
-    {
+    } else {
       alg->execute();
       loadFileComplete(!alg->isExecuted());
     }
   }
 }
 
-void StepScan::loadFileComplete(bool error)
-{
+void StepScan::loadFileComplete(bool error) {
   m_uiForm.statusText->clear();
-  disconnect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(loadFileComplete(bool)));
+  disconnect(m_algRunner, SIGNAL(algorithmComplete(bool)), this,
+             SLOT(loadFileComplete(bool)));
 
-  if ( m_inputWSName == "__multifiles" && !error ) error = mergeRuns();
+  if (m_inputWSName == "__multifiles" && !error)
+    error = mergeRuns();
 
-  if ( ! error )
-  {
+  if (!error) {
     setupOptionControls();
-  }
-  else
-  {
-    QMessageBox::warning(this,"File loading failed","Is this an event nexus file?");
+  } else {
+    QMessageBox::warning(this, "File loading failed",
+                         "Is this an event nexus file?");
   }
 }
 
 namespace {
-  class ScopedStatusText
-  {
-  public:
-    ScopedStatusText(QLabel * label, QString labelText) : status_label(label)
-    {
-      status_label->setText("<i><font color='darkblue'>" + labelText + "</font></i>");
-    }
-
-    ~ScopedStatusText()
-    {
-      status_label->clear();
-    }
-
-  private:
-    QLabel * const status_label;
-  };
-
+class ScopedStatusText {
+public:
+  ScopedStatusText(QLabel *label, QString labelText) : status_label(label) {
+    status_label->setText("<i><font color='darkblue'>" + labelText +
+                          "</font></i>");
+  }
 
-  // Small class to handle disabling mouse clicks and showing the busy cursor in an RAII manner.
-  // Used in the runStepScanAlg below to ensure these things are unset when the method is exited.
-  class DisableGUI_RAII
-  {
-  public:
-    explicit DisableGUI_RAII(StepScan *gui) : the_gui(gui) {
-      QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
-      the_gui->setAttribute( Qt::WA_TransparentForMouseEvents );
-    }
+  ~ScopedStatusText() { status_label->clear(); }
+
+private:
+  QLabel *const status_label;
+};
+
+// Small class to handle disabling mouse clicks and showing the busy cursor in
+// an RAII manner.
+// Used in the runStepScanAlg below to ensure these things are unset when the
+// method is exited.
+class DisableGUI_RAII {
+public:
+  explicit DisableGUI_RAII(StepScan *gui) : the_gui(gui) {
+    QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
+    the_gui->setAttribute(Qt::WA_TransparentForMouseEvents);
+  }
 
-    ~DisableGUI_RAII()
-    {
-      QApplication::restoreOverrideCursor();
-      the_gui->setAttribute( Qt::WA_TransparentForMouseEvents, false );
-    }
+  ~DisableGUI_RAII() {
+    QApplication::restoreOverrideCursor();
+    the_gui->setAttribute(Qt::WA_TransparentForMouseEvents, false);
+  }
 
-  private:
-    StepScan * const the_gui;
-  };
+private:
+  StepScan *const the_gui;
+};
 }
 
-bool StepScan::mergeRuns()
-{
-  ScopedStatusText _merging(this->m_uiForm.statusText,"Merging runs...");
-  // This can be slow and will lock the GUI, but will probably be so rarely used that it's
+bool StepScan::mergeRuns() {
+  ScopedStatusText _merging(this->m_uiForm.statusText, "Merging runs...");
+  // This can be slow and will lock the GUI, but will probably be so rarely used
+  // that it's
   // not worth making it asynchronous
   // Block mouse clicks while the algorithm runs. Also set the busy cursor.
   DisableGUI_RAII _blockclicks(this);
 
-  // Get hold of the group workspace and go through the entries adding an incrementing scan_index variable
-  WorkspaceGroup_const_sptr wsGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(m_inputWSName);
-  if ( !wsGroup ) return true; // Shouldn't be possible, but be defensive
+  // Get hold of the group workspace and go through the entries adding an
+  // incrementing scan_index variable
+  WorkspaceGroup_const_sptr wsGroup =
+      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(m_inputWSName);
+  if (!wsGroup)
+    return true; // Shouldn't be possible, but be defensive
 
-  for ( size_t i = 0; i < wsGroup->size(); ++i )
-  {
+  for (size_t i = 0; i < wsGroup->size(); ++i) {
     // Add a scan_index variable to each workspace, counting from 1
-    MatrixWorkspace_sptr ws = boost::static_pointer_cast<MatrixWorkspace>(wsGroup->getItem(i));
-    if ( !ws ) return true; // Again, shouldn't be possible (unless there's a group within a group?)
-    IAlgorithm_sptr addScanIndex = AlgorithmManager::Instance().create("AddSampleLog");
-    addScanIndex->setPropertyValue("Workspace",ws->name());
-    addScanIndex->setProperty("LogName","scan_index");
-    addScanIndex->setProperty("LogType","Number Series");
-    addScanIndex->setProperty("LogText",Strings::toString(i+1));
+    MatrixWorkspace_sptr ws =
+        boost::static_pointer_cast<MatrixWorkspace>(wsGroup->getItem(i));
+    if (!ws)
+      return true; // Again, shouldn't be possible (unless there's a group
+                   // within a group?)
+    IAlgorithm_sptr addScanIndex =
+        AlgorithmManager::Instance().create("AddSampleLog");
+    addScanIndex->setPropertyValue("Workspace", ws->name());
+    addScanIndex->setProperty("LogName", "scan_index");
+    addScanIndex->setProperty("LogType", "Number Series");
+    addScanIndex->setProperty("LogText", Strings::toString(i + 1));
     auto result = addScanIndex->executeAsync();
-    while ( !result.available() )
-    {
+    while (!result.available()) {
       QApplication::processEvents();
     }
-    if ( ! addScanIndex->isExecuted() ) return true;
+    if (!addScanIndex->isExecuted())
+      return true;
 
     // Add a scan_index = 0 to the end time for each workspace
-    try
-    {
-      ws->run().getTimeSeriesProperty<int>("scan_index")->addValue(ws->run().endTime(),0);
-    } catch (std::runtime_error&) {
-      /* Swallow the error if there's no run end time. It shouldn't happen for real data. */
+    try {
+      ws->run()
+          .getTimeSeriesProperty<int>("scan_index")
+          ->addValue(ws->run().endTime(), 0);
+    } catch (std::runtime_error &) {
+      /* Swallow the error if there's no run end time. It shouldn't happen for
+       * real data. */
     }
   }
 
   IAlgorithm_sptr merge = AlgorithmManager::Instance().create("MergeRuns");
-  merge->setPropertyValue("InputWorkspaces",m_inputWSName);
+  merge->setPropertyValue("InputWorkspaces", m_inputWSName);
   const std::string summedWSName = "__summed_multifiles";
-  merge->setPropertyValue("OutputWorkspace",summedWSName);
+  merge->setPropertyValue("OutputWorkspace", summedWSName);
   auto result = merge->executeAsync();
-  while ( !result.available() )
-  {
+  while (!result.available()) {
     QApplication::processEvents();
   }
-  if ( ! merge->isExecuted() ) return true;
+  if (!merge->isExecuted())
+    return true;
   m_inputWSName = summedWSName;
 
   return false;
 }
 
-void StepScan::setupOptionControls()
-{
-  MatrixWorkspace_const_sptr outWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_inputWSName);
+void StepScan::setupOptionControls() {
+  MatrixWorkspace_const_sptr outWS =
+      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+          m_inputWSName);
   // Trigger population of the logs combobox
-  emit logsAvailable( outWS );
+  emit logsAvailable(outWS);
   fillNormalizationCombobox();
   // Enable the button to launch the instrument view (for defining a mask)
   m_uiForm.launchInstView->setEnabled(true);
 }
 
-void StepScan::launchInstrumentWindow()
-{
+void StepScan::launchInstrumentWindow() {
   // Gotta do this in python
-  std::string pyCode = "instrument_view = getInstrumentView('" + m_inputWSName + "',2)\n"
+  std::string pyCode = "instrument_view = getInstrumentView('" + m_inputWSName +
+                       "',2)\n"
                        "instrument_view.show()";
 
-  runPythonCode( QString::fromStdString(pyCode) );
+  runPythonCode(QString::fromStdString(pyCode));
 
-  // Attach the observers so that if a mask workspace is generated over in the instrument view,
+  // Attach the observers so that if a mask workspace is generated over in the
+  // instrument view,
   // it is automatically selected by the combobox over here
   AnalysisDataService::Instance().notificationCenter.addObserver(m_addObserver);
   addReplaceObserverOnce();
 }
 
-void StepScan::fillPlotVarCombobox(const MatrixWorkspace_const_sptr& ws)
-{
+void StepScan::fillPlotVarCombobox(const MatrixWorkspace_const_sptr &ws) {
   // Hold the name of the scan index log in a common place
   const std::string scan_index("scan_index");
   // If this has already been set to something, keep track of what
   auto currentSetting = m_uiForm.plotVariable->currentText();
-  // Clear the combobox and immediately re-insert 'scan_index' (so it's the first entry)
+  // Clear the combobox and immediately re-insert 'scan_index' (so it's the
+  // first entry)
   m_uiForm.plotVariable->clear();
-  m_uiForm.plotVariable->addItem( QString::fromStdString(scan_index) );
+  m_uiForm.plotVariable->addItem(QString::fromStdString(scan_index));
 
-  // First check that the provided workspace has the scan_index - complain if it doesn't
+  // First check that the provided workspace has the scan_index - complain if it
+  // doesn't
   try {
     auto scan_index_prop = ws->run().getTimeSeriesProperty<int>(scan_index);
-    if ( !m_uiForm.mWRunFiles->liveButtonIsChecked() && scan_index_prop->realSize() < 2 )
-    {
-      QMessageBox::warning(this,"scan_index log empty","This data does not appear to be an alignment scan");
+    if (!m_uiForm.mWRunFiles->liveButtonIsChecked() &&
+        scan_index_prop->realSize() < 2) {
+      QMessageBox::warning(this, "scan_index log empty",
+                           "This data does not appear to be an alignment scan");
       return;
     }
-  } catch ( std::exception& ) {
-    QMessageBox::warning(this,"scan_index log not found","Is this an ADARA-style dataset?");
+  } catch (std::exception &) {
+    QMessageBox::warning(this, "scan_index log not found",
+                         "Is this an ADARA-style dataset?");
     return;
   }
 
-  expandPlotVarCombobox( ws );
+  expandPlotVarCombobox(ws);
 
   // Set back to whatever it was set to before
-  m_uiForm.plotVariable->setCurrentIndex(m_uiForm.plotVariable->findText(currentSetting));
+  m_uiForm.plotVariable->setCurrentIndex(
+      m_uiForm.plotVariable->findText(currentSetting));
   // Now that this has been populated, allow the user to select from it
   m_uiForm.plotVariable->setEnabled(true);
   // Now's the time to enable the start button as well
   m_uiForm.startButton->setEnabled(true);
 }
 
-void StepScan::expandPlotVarCombobox(const Mantid::API::MatrixWorkspace_const_sptr& ws)
-{
-  // This is unfortunately more or less a copy of SumEventsByLogValue::getNumberSeriesLogs
+void StepScan::expandPlotVarCombobox(
+    const Mantid::API::MatrixWorkspace_const_sptr &ws) {
+  // This is unfortunately more or less a copy of
+  // SumEventsByLogValue::getNumberSeriesLogs
   // but I want to populate the box before running the algorithm
-  const auto & logs = ws->run().getLogData();
-  for ( auto log = logs.begin(); log != logs.end(); ++log )
-  {
-    const QString logName = QString::fromStdString( (*log)->name() );
+  const auto &logs = ws->run().getLogData();
+  for (auto log = logs.begin(); log != logs.end(); ++log) {
+    const QString logName = QString::fromStdString((*log)->name());
     // Don't add scan_index - that's already there
-    if ( logName == "scan_index" ) continue;
+    if (logName == "scan_index")
+      continue;
     // Try to cast to an ITimeSeriesProperty
-    auto tsp = dynamic_cast<const ITimeSeriesProperty*>(*log);
+    auto tsp = dynamic_cast<const ITimeSeriesProperty *>(*log);
     // Move on to the next one if this is not a TSP
-    if ( tsp == NULL ) continue;
+    if (tsp == NULL)
+      continue;
     // Don't keep ones with only one entry
-    if ( tsp->realSize() < 2 ) continue;
+    if (tsp->realSize() < 2)
+      continue;
     // Now make sure it's either an int or double tsp
-    if ( dynamic_cast<TimeSeriesProperty<double>* >(*log) || dynamic_cast<TimeSeriesProperty<int>* >(*log))
-    {
+    if (dynamic_cast<TimeSeriesProperty<double> *>(*log) ||
+        dynamic_cast<TimeSeriesProperty<int> *>(*log)) {
       // Add it to the list if it isn't already there
-      if ( m_uiForm.plotVariable->findText( logName ) == -1 )
-      {
-        m_uiForm.plotVariable->addItem( logName );
+      if (m_uiForm.plotVariable->findText(logName) == -1) {
+        m_uiForm.plotVariable->addItem(logName);
       }
     }
   }
 }
 
-void StepScan::fillNormalizationCombobox()
-{
+void StepScan::fillNormalizationCombobox() {
   clearNormalizationCombobox();
 
   // Add the monitors to the normalization combobox
   try {
-    auto inputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_inputWSName);
+    auto inputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+        m_inputWSName);
     auto monWS = inputWS->monitorWorkspace();
-    if ( monWS )
-    {
-      for ( std::size_t i = 0; i < monWS->getNumberHistograms(); ++i )
-      {
+    if (monWS) {
+      for (std::size_t i = 0; i < monWS->getNumberHistograms(); ++i) {
         const std::string monitorName = monWS->getDetector(i)->getName();
-        m_uiForm.normalization->addItem( QString::fromStdString( monitorName ) );
+        m_uiForm.normalization->addItem(QString::fromStdString(monitorName));
       }
     }
-  } catch (Exception::NotFoundError&) {
+  } catch (Exception::NotFoundError &) {
     // No monitors workspace....carry on
   }
 }
 
-void StepScan::clearNormalizationCombobox()
-{
-  // If there are more than 3 entries in the combobox (nothing, time, proton_charge) then
+void StepScan::clearNormalizationCombobox() {
+  // If there are more than 3 entries in the combobox (nothing, time,
+  // proton_charge) then
   // remove any stale ones
-  while ( m_uiForm.normalization->count() > 3 )
-  {
-    m_uiForm.normalization->removeItem(m_uiForm.normalization->count()-1);
+  while (m_uiForm.normalization->count() > 3) {
+    m_uiForm.normalization->removeItem(m_uiForm.normalization->count() - 1);
   }
 }
 
-IAlgorithm_sptr StepScan::setupStepScanAlg()
-{
+IAlgorithm_sptr StepScan::setupStepScanAlg() {
   IAlgorithm_sptr stepScan = AlgorithmManager::Instance().create("StepScan");
   // The table should not be hidden, so leave off the prefix
   m_tableWSName = m_inputWSName.substr(2) + "_StepScan";
@@ -449,7 +458,7 @@ IAlgorithm_sptr StepScan::setupStepScanAlg()
 
   // ROI masking
   const QString maskWS = m_uiForm.maskWorkspace->currentText();
-  stepScan->setPropertyValue("MaskWorkspace",maskWS.toStdString());
+  stepScan->setPropertyValue("MaskWorkspace", maskWS.toStdString());
 
   // Filtering on time (or other unit)
   const QString xminStr = m_uiForm.xmin->text();
@@ -457,149 +466,158 @@ IAlgorithm_sptr StepScan::setupStepScanAlg()
   const double xmin = xminStr.toDouble();
   const double xmax = xmaxStr.toDouble();
   // If both set, check that xmax > xmin
-  if ( !xminStr.isEmpty() && !xmaxStr.isEmpty() && xmin >= xmax )
-  {
-    QMessageBox::critical(this,"Invalid filtering range set","For the filtering range, min has to be less than max");
+  if (!xminStr.isEmpty() && !xmaxStr.isEmpty() && xmin >= xmax) {
+    QMessageBox::critical(
+        this, "Invalid filtering range set",
+        "For the filtering range, min has to be less than max");
     return IAlgorithm_sptr();
   }
-  if ( ! xminStr.isEmpty() ) stepScan->setProperty("XMin",xmin);
-  if ( ! xmaxStr.isEmpty() ) stepScan->setProperty("XMax",xmax);
-  switch (m_uiForm.rangeUnit->currentIndex())
-  {
+  if (!xminStr.isEmpty())
+    stepScan->setProperty("XMin", xmin);
+  if (!xmaxStr.isEmpty())
+    stepScan->setProperty("XMax", xmax);
+  switch (m_uiForm.rangeUnit->currentIndex()) {
   case 1:
-    stepScan->setProperty("RangeUnit","dSpacing");
+    stepScan->setProperty("RangeUnit", "dSpacing");
     break;
   default:
-    // The default value for the property is TOF (which is index 0 in the combobox)
+    // The default value for the property is TOF (which is index 0 in the
+    // combobox)
     break;
   }
 
   return stepScan;
 }
 
-void StepScan::runStepScanAlg()
-{
+void StepScan::runStepScanAlg() {
   IAlgorithm_sptr stepScan = setupStepScanAlg();
-  if ( !stepScan ) return;
+  if (!stepScan)
+    return;
 
   // Block mouse clicks while the algorithm runs. Also set the busy cursor.
   DisableGUI_RAII _blockclicks(this);
 
   bool algSuccessful;
-  if ( m_uiForm.mWRunFiles->liveButtonIsChecked() )  // Live data
+  if (m_uiForm.mWRunFiles->liveButtonIsChecked()) // Live data
   {
     algSuccessful = runStepScanAlgLive(stepScan->toString());
-  }
-  else  // Offline data
+  } else // Offline data
   {
     // Check just in case the user has deleted the loaded workspace
-    if ( ! AnalysisDataService::Instance().doesExist(m_inputWSName) )
-    {
+    if (!AnalysisDataService::Instance().doesExist(m_inputWSName)) {
       m_inputFilename.clear();
       loadFile(false);
     }
     stepScan->setPropertyValue("InputWorkspace", m_inputWSName);
-    ScopedStatusText _merging(this->m_uiForm.statusText,"Analyzing scan...");
+    ScopedStatusText _merging(this->m_uiForm.statusText, "Analyzing scan...");
     auto result = stepScan->executeAsync();
-    while ( !result.available() )
-    {
+    while (!result.available()) {
       QApplication::processEvents();
     }
     algSuccessful = stepScan->isExecuted();
   }
 
-  if ( !algSuccessful )
-  {
+  if (!algSuccessful) {
     return;
   }
 
-  // Now that the algorithm's been run, connect up the signal to change the plot variable
-  connect( m_uiForm.plotVariable, SIGNAL(currentIndexChanged(const QString &)),
-           SLOT(generateCurve(const QString &)) );
+  // Now that the algorithm's been run, connect up the signal to change the plot
+  // variable
+  connect(m_uiForm.plotVariable, SIGNAL(currentIndexChanged(const QString &)),
+          SLOT(generateCurve(const QString &)));
   // and the one if the normalisation's been changed
-  connect( m_uiForm.normalization, SIGNAL(currentIndexChanged(const QString &)),
-           SLOT(updateForNormalizationChange()) );
+  connect(m_uiForm.normalization, SIGNAL(currentIndexChanged(const QString &)),
+          SLOT(updateForNormalizationChange()));
   // Create the plot for the first time
-  generateCurve( m_uiForm.plotVariable->currentText() );
+  generateCurve(m_uiForm.plotVariable->currentText());
 }
 
-bool StepScan::runStepScanAlgLive(std::string stepScanProperties)
-{
+bool StepScan::runStepScanAlgLive(std::string stepScanProperties) {
   // First stop the currently running live algorithm
-  IAlgorithm_const_sptr oldMonitorLiveData = m_uiForm.mWRunFiles->stopLiveAlgorithm();
+  IAlgorithm_const_sptr oldMonitorLiveData =
+      m_uiForm.mWRunFiles->stopLiveAlgorithm();
 
-  stepScanProperties.erase(0,stepScanProperties.find_first_of('(')+1);
+  stepScanProperties.erase(0, stepScanProperties.find_first_of('(') + 1);
   stepScanProperties.erase(stepScanProperties.find_last_of(')'));
-  std::replace(stepScanProperties.begin(),stepScanProperties.end(),',',';');
+  std::replace(stepScanProperties.begin(), stepScanProperties.end(), ',', ';');
 
-  IAlgorithm_sptr startLiveData = AlgorithmManager::Instance().create("StartLiveData");
+  IAlgorithm_sptr startLiveData =
+      AlgorithmManager::Instance().create("StartLiveData");
   startLiveData->setProperty("Instrument", m_instrument);
-  startLiveData->setProperty("FromNow",false);
-  startLiveData->setProperty("FromStartOfRun",true);
-  startLiveData->setProperty("UpdateEvery",10.0);
-  startLiveData->setProperty("PreserveEvents",true);
-  startLiveData->setProperty("PostProcessingAlgorithm","StepScan");
-  startLiveData->setProperty("PostProcessingProperties",stepScanProperties);
-  startLiveData->setProperty("RunTransitionBehavior","Stop");
-  startLiveData->setProperty("AccumulationWorkspace",m_inputWSName);
-  startLiveData->setProperty("OutputWorkspace",m_tableWSName);
+  startLiveData->setProperty("FromNow", false);
+  startLiveData->setProperty("FromStartOfRun", true);
+  startLiveData->setProperty("UpdateEvery", 10.0);
+  startLiveData->setProperty("PreserveEvents", true);
+  startLiveData->setProperty("PostProcessingAlgorithm", "StepScan");
+  startLiveData->setProperty("PostProcessingProperties", stepScanProperties);
+  startLiveData->setProperty("RunTransitionBehavior", "Stop");
+  startLiveData->setProperty("AccumulationWorkspace", m_inputWSName);
+  startLiveData->setProperty("OutputWorkspace", m_tableWSName);
   // The previous listener needs to finish before this one can start
-  while ( oldMonitorLiveData->isRunning() )
-  {
+  while (oldMonitorLiveData->isRunning()) {
     Poco::Thread::sleep(100);
   }
   auto result = startLiveData->executeAsync();
-  while ( !result.available() )
-  {
+  while (!result.available()) {
     QApplication::processEvents();
   }
-  if ( ! startLiveData->isExecuted() ) return false;
+  if (!startLiveData->isExecuted())
+    return false;
 
   // Keep track of the algorithm that's pulling in the live data
-  m_uiForm.mWRunFiles->setLiveAlgorithm(startLiveData->getProperty("MonitorLiveData"));
+  m_uiForm.mWRunFiles->setLiveAlgorithm(
+      startLiveData->getProperty("MonitorLiveData"));
 
-  connect( this, SIGNAL(updatePlot(const QString&)), SLOT(generateCurve(const QString&)) );
+  connect(this, SIGNAL(updatePlot(const QString &)),
+          SLOT(generateCurve(const QString &)));
   return true;
 }
 
-void StepScan::updateForNormalizationChange()
-{
-  generateCurve( m_uiForm.plotVariable->currentText() );
+void StepScan::updateForNormalizationChange() {
+  generateCurve(m_uiForm.plotVariable->currentText());
 }
 
-void StepScan::generateCurve( const QString& var )
-{
-  if ( ! AnalysisDataService::Instance().doesExist(m_tableWSName) )
-  {
-    QMessageBox::critical(this,"Unable to generate plot","Table workspace "+ QString::fromStdString(m_tableWSName) +"\nhas been deleted!");
+void StepScan::generateCurve(const QString &var) {
+  if (!AnalysisDataService::Instance().doesExist(m_tableWSName)) {
+    QMessageBox::critical(this, "Unable to generate plot",
+                          "Table workspace " +
+                              QString::fromStdString(m_tableWSName) +
+                              "\nhas been deleted!");
     return;
   }
 
   // Create a matrix workspace out of the variable that's asked for
-  IAlgorithm_sptr alg = AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace");
+  IAlgorithm_sptr alg =
+      AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace");
   alg->setLogging(false); // Don't log this algorithm
   alg->setPropertyValue("InputWorkspace", m_tableWSName);
   m_plotWSName = m_tableWSName + "_plot";
   alg->setPropertyValue("OutputWorkspace", m_plotWSName);
-  alg->setPropertyValue("ColumnX", var.toStdString() );
-  alg->setPropertyValue("ColumnY", "Counts" );
-  alg->setPropertyValue("ColumnE", "Error" );
-  if ( ! alg->execute() ) return;
+  alg->setPropertyValue("ColumnX", var.toStdString());
+  alg->setPropertyValue("ColumnY", "Counts");
+  alg->setPropertyValue("ColumnE", "Error");
+  if (!alg->execute())
+    return;
 
   // Now create one for the normalisation, if required
-  if ( m_uiForm.normalization->currentIndex() !=  0 )
-  {
-    IAlgorithm_sptr norm = AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace");
+  if (m_uiForm.normalization->currentIndex() != 0) {
+    IAlgorithm_sptr norm =
+        AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace");
     norm->setChild(true);
     norm->setLogging(false); // Don't log this algorithm
     norm->setPropertyValue("InputWorkspace", m_tableWSName);
     norm->setPropertyValue("OutputWorkspace", "dummyName");
-    norm->setPropertyValue("ColumnX", var.toStdString() );
-    // TODO: Protect against column being missing (e.g. if monitor not found in data)
-    norm->setPropertyValue("ColumnY", m_uiForm.normalization->currentText().toStdString() );
-    if ( ! norm->execute() ) return;
+    norm->setPropertyValue("ColumnX", var.toStdString());
+    // TODO: Protect against column being missing (e.g. if monitor not found in
+    // data)
+    norm->setPropertyValue("ColumnY",
+                           m_uiForm.normalization->currentText().toStdString());
+    if (!norm->execute())
+      return;
 
-    MatrixWorkspace_sptr top = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_plotWSName);
+    MatrixWorkspace_sptr top =
+        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+            m_plotWSName);
     MatrixWorkspace_sptr bottom = norm->getProperty("OutputWorkspace");
     top /= bottom;
   }
@@ -607,91 +625,95 @@ void StepScan::generateCurve( const QString& var )
   plotCurve();
 }
 
-void StepScan::plotCurve()
-{
+void StepScan::plotCurve() {
   // Get the name of the dataset to produce the plot title
   std::string title = m_inputWSName.substr(2);
   // qtiplot may unhelpfully change '_' to '-' so I need to as well
   std::replace(title.begin(), title.end(), '_', '-');
 
   // Figure out the axis titles
-  const std::string xAxisTitle = m_uiForm.plotVariable->currentText().toStdString();
+  const std::string xAxisTitle =
+      m_uiForm.plotVariable->currentText().toStdString();
   std::string yAxisTitle = "Counts";
-  const std::string normalization = m_uiForm.normalization->currentText().toStdString();
-  if ( normalization == "nothing") /* Do nothing */;
-  else if ( normalization == "time" ) yAxisTitle += " / second";
-  else if ( normalization == "proton_charge" ) yAxisTitle += " / picocoulomb";
-  else yAxisTitle += " / " + normalization;
+  const std::string normalization =
+      m_uiForm.normalization->currentText().toStdString();
+  if (normalization == "nothing") /* Do nothing */
+    ;
+  else if (normalization == "time")
+    yAxisTitle += " / second";
+  else if (normalization == "proton_charge")
+    yAxisTitle += " / picocoulomb";
+  else
+    yAxisTitle += " / " + normalization;
 
   // Has to be done via python
   std::string pyCode = "g = graph('" + title + "')\n"
-                       "if g is None:\n"
-                       "    g = plotSpectrum('" + m_plotWSName + "',0,True,type=Layer.Scatter)\n"
-                       "    l = g.activeLayer()\n"
-                       "    l.legend().hide()\n"
-                       "    l.removeTitle()\n"
-                       "    setWindowName(g,'" + title + "')\n"
-                       "    g.setWindowLabel('Step Scan')\n"
-                       "l = g.activeLayer()\n"
-                       "l.setAxisTitle(Layer.Bottom,'" + xAxisTitle + "')\n"
-                       "l.setAxisTitle(Layer.Left,'" + yAxisTitle + "')";
-
-  runPythonCode( QString::fromStdString(pyCode) );
+                                               "if g is None:\n"
+                                               "    g = plotSpectrum('" +
+                       m_plotWSName + "',0,True,type=Layer.Scatter)\n"
+                                      "    l = g.activeLayer()\n"
+                                      "    l.legend().hide()\n"
+                                      "    l.removeTitle()\n"
+                                      "    setWindowName(g,'" +
+                       title + "')\n"
+                               "    g.setWindowLabel('Step Scan')\n"
+                               "l = g.activeLayer()\n"
+                               "l.setAxisTitle(Layer.Bottom,'" +
+                       xAxisTitle + "')\n"
+                                    "l.setAxisTitle(Layer.Left,'" +
+                       yAxisTitle + "')";
+
+  runPythonCode(QString::fromStdString(pyCode));
 }
 
-void StepScan::handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf)
-{
+void StepScan::handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf) {
   checkForMaskWorkspace(pNf->objectName());
 }
 
-void StepScan::handleReplEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf)
-{
+void StepScan::handleReplEvent(
+    Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf) {
   checkForMaskWorkspace(pNf->objectName());
   checkForResultTableUpdate(pNf->objectName());
   checkForVaryingLogs(pNf->objectName());
 }
 
-void StepScan::addReplaceObserverOnce()
-{
-  if ( ! m_replaceObserverAdded )
-  {
-    AnalysisDataService::Instance().notificationCenter.addObserver(m_replObserver);
+void StepScan::addReplaceObserverOnce() {
+  if (!m_replaceObserverAdded) {
+    AnalysisDataService::Instance().notificationCenter.addObserver(
+        m_replObserver);
     m_replaceObserverAdded = true;
   }
 }
 
-void StepScan::checkForMaskWorkspace(const std::string & wsName)
-{
-  if ( wsName == "MaskWorkspace" )
-  {
+void StepScan::checkForMaskWorkspace(const std::string &wsName) {
+  if (wsName == "MaskWorkspace") {
     // Make sure the combobox has picked up the new workspace
     m_uiForm.maskWorkspace->refresh();
     // Now set it to point at the mask workspace
     const int index = m_uiForm.maskWorkspace->findText("MaskWorkspace");
-    if ( index != -1 ) m_uiForm.maskWorkspace->setCurrentIndex(index);
+    if (index != -1)
+      m_uiForm.maskWorkspace->setCurrentIndex(index);
   }
 }
 
-void StepScan::checkForResultTableUpdate(const std::string& wsName)
-{
-  if ( wsName == m_tableWSName )
-  {
-    emit updatePlot( m_uiForm.plotVariable->currentText() );
+void StepScan::checkForResultTableUpdate(const std::string &wsName) {
+  if (wsName == m_tableWSName) {
+    emit updatePlot(m_uiForm.plotVariable->currentText());
   }
 }
 
-void StepScan::checkForVaryingLogs(const std::string& wsName)
-{
-  if ( wsName == m_inputWSName )
-  {
-    MatrixWorkspace_const_sptr ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_inputWSName);
-    emit logsUpdated( ws );
+void StepScan::checkForVaryingLogs(const std::string &wsName) {
+  if (wsName == m_inputWSName) {
+    MatrixWorkspace_const_sptr ws =
+        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
+            m_inputWSName);
+    emit logsUpdated(ws);
   }
 }
 
-void StepScan::helpClicked()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Step_Scan_Interface"));
+void StepScan::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/Step_Scan_Interface"));
 }
 
 } // namespace CustomInterfaces
diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomoReconPostprocSettings.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomoReconPostprocSettings.cpp
index f3dda704697a9d3d933672b9cf3d2185a28ea26b..cd3bd710c97846b75b0c2b43f6bd8693f7f8f839 100644
--- a/MantidQt/CustomInterfaces/src/Tomography/TomoReconPostprocSettings.cpp
+++ b/MantidQt/CustomInterfaces/src/Tomography/TomoReconPostprocSettings.cpp
@@ -9,7 +9,7 @@ namespace CustomInterfaces {
  * GUIs, etc.
  */
 TomoReconPostprocSettings::TomoReconPostprocSettings()
-  : circMaskRadius(0.94), cutOffLevel(0.0) {}
+    : circMaskRadius(0.94), cutOffLevel(0.0) {}
 
 } // namespace CustomInterfaces
 } // namespace MantidQt
diff --git a/MantidQt/CustomInterfaces/src/UserInputValidator.cpp b/MantidQt/CustomInterfaces/src/UserInputValidator.cpp
index 131691de008b6859d0644d39ddee3615974f9e58..2fc1206d8718eefe5dabe87296563d8f2ec5f042 100644
--- a/MantidQt/CustomInterfaces/src/UserInputValidator.cpp
+++ b/MantidQt/CustomInterfaces/src/UserInputValidator.cpp
@@ -10,7 +10,7 @@
 using namespace MantidQt::MantidWidgets;
 
 namespace // anonymous
-{
+    {
 template <typename T> void sortPair(std::pair<T, T> &pair) {
   if (pair.first > pair.second) {
     T temp = pair.first;
@@ -157,9 +157,8 @@ bool UserInputValidator::checkValidRange(const QString &name,
  * @param rangeB :: the end of the range
  * @returns True if the input was valid
  */
-bool
-UserInputValidator::checkRangesDontOverlap(std::pair<double, double> rangeA,
-                                           std::pair<double, double> rangeB) {
+bool UserInputValidator::checkRangesDontOverlap(
+    std::pair<double, double> rangeA, std::pair<double, double> rangeB) {
   sortPair(rangeA);
   sortPair(rangeB);
 
diff --git a/MantidQt/CustomInterfaces/src/background.cpp b/MantidQt/CustomInterfaces/src/background.cpp
index 0f713221d1aa0bab80c748f68e9bf756cdd3c8c9..b59f977ddd59c08105f3d5078371d855b05433d8 100644
--- a/MantidQt/CustomInterfaces/src/background.cpp
+++ b/MantidQt/CustomInterfaces/src/background.cpp
@@ -22,11 +22,10 @@ using namespace MantidQt::CustomInterfaces;
  *  the passed group string, the settings must be setup before this called
  *  @param parent :: used by QT
  */
-Background::Background(QWidget *parent) :
-  API::MantidDialog(parent), m_ckDoRemove(new QCheckBox),
-  m_leStart(new QLineEdit), m_leEnd(new QLineEdit), m_rangeMin(-1.0), 
-  m_rangeMax(-1.0), m_doRemoval(false)
-{
+Background::Background(QWidget *parent)
+    : API::MantidDialog(parent), m_ckDoRemove(new QCheckBox),
+      m_leStart(new QLineEdit), m_leEnd(new QLineEdit), m_rangeMin(-1.0),
+      m_rangeMax(-1.0), m_doRemoval(false) {
   setWindowTitle("Background Removal Settings");
 
   m_ckDoRemove->setText("Remove background as found between these points");
@@ -52,16 +51,16 @@ Background::Background(QWidget *parent) :
   QPushButton *pbCancel = new QPushButton("Cancel");
   connect(pbCancel, SIGNAL(clicked()), this, SLOT(reject()));
   connect(pbOK, SIGNAL(clicked()), this, SLOT(close()));
-   QHBoxLayout *lineThree = new QHBoxLayout;
+  QHBoxLayout *lineThree = new QHBoxLayout;
   lineThree->addStretch();
   lineThree->addWidget(pbOK);
   lineThree->addWidget(pbCancel);
- 
+
   QVBoxLayout *dialogLayout = new QVBoxLayout;
   dialogLayout->addLayout(lineOne);
   dialogLayout->addLayout(lineTwo);
   dialogLayout->addLayout(lineThree);
-   
+
   setLayout(dialogLayout);
 }
 
@@ -73,26 +72,19 @@ Background::Background(QWidget *parent) :
  * Whether we are removing background or not
  * @returns A boolean indicating whether the background should be removed or not
  */
-bool Background::removeBackground() const
-{
-  return m_doRemoval;
-}
+bool Background::removeBackground() const { return m_doRemoval; }
 
 /**
  * Set whether to remove the background or not
  * @param remove :: If true, the background will be removed
  */
-void Background::removeBackground(bool remove)
-{
-   m_doRemoval = remove;
-}
+void Background::removeBackground(bool remove) { m_doRemoval = remove; }
 
 /**
  * Retrieve the time-of-flight range from the dialog
  * @returns A pair containing the TOF range
  */
-QPair<double, double> Background::getRange() const
-{
+QPair<double, double> Background::getRange() const {
   return QPair<double, double>(m_rangeMin, m_rangeMax);
 }
 
@@ -101,8 +93,7 @@ QPair<double, double> Background::getRange() const
  * @param min :: Minimum value
  * @param max :: Maximum value
  */
-void Background::setRange(double min, double max)
-{
+void Background::setRange(double min, double max) {
   m_rangeMin = min;
   m_rangeMax = max;
 }
@@ -112,16 +103,13 @@ void Background::setRange(double min, double max)
 //----------------------------------------------------
 
 /// Set up the dialog layout
-void Background::initLayout()
-{
-}
+void Background::initLayout() {}
 
 /**
  * Called in response to a show() event
  * @param e :: The event details
  */
-void Background::showEvent(QShowEvent* e)
-{
+void Background::showEvent(QShowEvent *e) {
   m_leStart->setText(QString::number(m_rangeMin));
   m_leEnd->setText(QString::number(m_rangeMax));
   m_ckDoRemove->setChecked(m_doRemoval);
@@ -133,38 +121,29 @@ void Background::showEvent(QShowEvent* e)
  * Called in response to a close event
  * @param event The event details
  */
-void Background::closeEvent(QCloseEvent* event)
-{
-  if( sanityCheck() )
-  {
+void Background::closeEvent(QCloseEvent *event) {
+  if (sanityCheck()) {
     m_doRemoval = m_ckDoRemove->isChecked();
-    m_rangeMin = m_leStart->text().toDouble();;
+    m_rangeMin = m_leStart->text().toDouble();
+    ;
     m_rangeMax = m_leEnd->text().toDouble();
     event->accept();
     emit accepted();
-  }
-  else
-  {
+  } else {
     event->ignore();
   }
 }
 
-bool Background::sanityCheck()
-{
+bool Background::sanityCheck() {
   double min = m_leStart->text().toDouble();
   double max = m_leEnd->text().toDouble();
-  if( m_ckDoRemove->isChecked() && min > max )
-  {
+  if (m_ckDoRemove->isChecked() && min > max) {
     m_leStart->setStyleSheet("background-color: red");
     m_leEnd->setStyleSheet("background-color: red");
     return false;
-  }
-  else
-  {
+  } else {
     m_leStart->setStyleSheet("background-color: white");
     m_leEnd->setStyleSheet("background-color: white");
     return true;
   }
 }
-
-
diff --git a/MantidQt/CustomInterfaces/src/deltaECalc.cpp b/MantidQt/CustomInterfaces/src/deltaECalc.cpp
index f9cdb1f24b99a09face13cb609df1fc8dd69929d..a8361a75f05c7e7122cd2e2630f402b3dbf8f9e9 100644
--- a/MantidQt/CustomInterfaces/src/deltaECalc.cpp
+++ b/MantidQt/CustomInterfaces/src/deltaECalc.cpp
@@ -13,19 +13,22 @@ using namespace Mantid::API;
 
 const QString deltaECalc::tempWS = "mono_sample_temporyWS";
 
-/** Read the data the user supplied to create Python code to do their calculation
+/** Read the data the user supplied to create Python code to do their
+* calculation
 * @param interface :: handle to the widget for the interface
 * @param userSettings :: the form that the user filled in
 * @param removalBg :: if true, remove background
 * @param TOFWinSt :: start of TOF range for background
 * @param TOFWinEnd :: end of TOF range for background
-* @throw invalid_argument where problems with user data prevent the calculation from proceeding
+* @throw invalid_argument where problems with user data prevent the calculation
+* from proceeding
 */
-deltaECalc::deltaECalc(QWidget * const interface, const Ui::DirectConvertToEnergy &userSettings, 
-                       const bool removalBg, const double TOFWinSt, const double TOFWinEnd) :
-pythonCalc(interface), m_sets(userSettings), m_bgRemove(removalBg), m_TOFWinSt(TOFWinSt), m_TOFWinEnd(TOFWinEnd), m_diagnosedWS("")
-{
-}
+deltaECalc::deltaECalc(QWidget *const interface,
+                       const Ui::DirectConvertToEnergy &userSettings,
+                       const bool removalBg, const double TOFWinSt,
+                       const double TOFWinEnd)
+    : pythonCalc(interface), m_sets(userSettings), m_bgRemove(removalBg),
+      m_TOFWinSt(TOFWinSt), m_TOFWinEnd(TOFWinEnd), m_diagnosedWS("") {}
 
 /** Adds user values from the GUI into the Python script
 * @param runFiles :: a comma separated list of data file names
@@ -34,101 +37,97 @@ pythonCalc(interface), m_sets(userSettings), m_bgRemove(removalBg), m_TOFWinSt(T
 * @param absWhiteBeam :: run file for absolute white beam normalization
 * @param saveName :: filename for output saving
 */
-void deltaECalc::createProcessingScript(const QStringList &runFiles, const QString &whiteBeam,
-                                        const QStringList &absRunFiles, const QString &absWhiteBeam,
-                                        const QString & saveName)
-{ 
+void deltaECalc::createProcessingScript(const QStringList &runFiles,
+                                        const QString &whiteBeam,
+                                        const QStringList &absRunFiles,
+                                        const QString &absWhiteBeam,
+                                        const QString &saveName) {
   QString pyCode = "import Direct.DirectEnergyConversion as direct\n";
-  pyCode += QString("mono_sample = direct.DirectEnergyConversion('%1')\n").arg(m_sets.cbInst->currentText());
-  //Turn off printing to stdout
+  pyCode += QString("mono_sample = direct.DirectEnergyConversion('%1')\n")
+                .arg(m_sets.cbInst->currentText());
+  // Turn off printing to stdout
   pyCode += QString("mono_sample.prop_man.log_to_mantid = True\n");
 
   addAnalysisOptions(pyCode);
   addMaskingCommands(pyCode);
   // Check save formats
   QStringList fileExts;
-  if( m_sets.save_ckSPE->isChecked() )
-  {
+  if (m_sets.save_ckSPE->isChecked()) {
     fileExts.append("'spe'");
   }
-  if( m_sets.save_ckNexus->isChecked() )
-  {
+  if (m_sets.save_ckNexus->isChecked()) {
     fileExts.append("'nxs'");
   }
-  if( m_sets.save_ckNxSPE->isChecked() )
-  {
+  if (m_sets.save_ckNxSPE->isChecked()) {
     fileExts.append("'nxspe'");
   }
 
-  if (fileExts.size()==0)
+  if (fileExts.size() == 0)
     pyCode += "mono_sample.prop_man.save_format = None\n";
   else
-    pyCode += "mono_sample.prop_man.save_format = " + fileExts.join(",") + "\n\n";
+    pyCode +=
+        "mono_sample.prop_man.save_format = " + fileExts.join(",") + "\n\n";
 
-  // Create the python variables. The strings are wrapped with r'' for slash safety
+  // Create the python variables. The strings are wrapped with r'' for slash
+  // safety
   QString pyRunFiles = createPyListAsString(runFiles);
   QString eiGuess = m_sets.leEGuess->text();
-  QString pyWhiteBeam = (whiteBeam.isEmpty()) ? "None" : QString("r'" + whiteBeam + "'");
+  QString pyWhiteBeam =
+      (whiteBeam.isEmpty()) ? "None" : QString("r'" + whiteBeam + "'");
   // Absolute values
   QString pyAbsRunFiles = createPyListAsString(absRunFiles);
   QString absEiGuess = m_sets.leVanEi->text();
-  QString pyAbsWhiteBeam = (absWhiteBeam.isEmpty()) ? "None" : QString("r'" + absWhiteBeam + "'");
+  QString pyAbsWhiteBeam =
+      (absWhiteBeam.isEmpty()) ? "None" : QString("r'" + absWhiteBeam + "'");
   // SE Offset value
   QString seOffset = m_sets.seOffsetEdit->text();
   QString pySeOffset = (seOffset.isEmpty()) ? "None" : seOffset;
   // SE Motor Name
   QString motorName = m_sets.motorNameEdit->text();
-  QString pyMotorName = (motorName.isEmpty()) ? "None" : QString("r'" + motorName + "'");
+  QString pyMotorName =
+      (motorName.isEmpty()) ? "None" : QString("r'" + motorName + "'");
 
   QString None = "None";
-  auto rebin    = None;
+  auto rebin = None;
   auto map_file = None;
   pyCode += "mono_sample.prop_man.motor_name = " + pyMotorName + "\n";
   pyCode += "mono_sample.prop_man.motor_offset = " + pySeOffset + "\n";
 
-
-  if( m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1)
-  {
-    if  (m_sets.ckSumSpecs->isChecked() )
+  if (m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1) {
+    if (m_sets.ckSumSpecs->isChecked())
       pyCode += "mono_sample.prop_man.sum_runs = True\n";
 
     QString pySaveName;
-    if( saveName.isEmpty() )
-    {
+    if (saveName.isEmpty()) {
       pyCode += "mono_sample.prop_man.save_file_name = None\n";
 
+    } else {
+      pyCode += "mono_sample.prop_man.save_file_name = r'" + saveName + "'\n";
     }
-    else
-    {
-      pyCode += "mono_sample.prop_man.save_file_name = r'"+saveName + "'\n";
-    }
-    pyCode += QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7)");
-    pyCode = pyCode.arg(pyWhiteBeam,pyRunFiles, eiGuess,rebin,map_file,pyAbsRunFiles, pyAbsWhiteBeam);
-  }
-  else
-  {
+    pyCode +=
+        QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7)");
+    pyCode = pyCode.arg(pyWhiteBeam, pyRunFiles, eiGuess, rebin, map_file,
+                        pyAbsRunFiles, pyAbsWhiteBeam);
+  } else {
     QString pySaveName;
-    if( saveName.isEmpty() )
-    {
+    if (saveName.isEmpty()) {
       pySaveName = "r'" + QFileInfo(saveName).absolutePath() + "'";
-      pyCode += "mono_sample.prop_man.save_file = "+pySaveName + "\n";
+      pyCode += "mono_sample.prop_man.save_file = " + pySaveName + "\n";
     }
     pyCode += "rfiles = " + pyRunFiles + "\n";
-    if( absRunFiles.isEmpty() )
-    {
-      pyCode +=
-        "for run in rfiles:\n"
-        "  mono_sample.convert_to_energy(run, %1, %2)\n";
+    if (absRunFiles.isEmpty()) {
+      pyCode += "for run in rfiles:\n"
+                "  mono_sample.convert_to_energy(run, %1, %2)\n";
       pyCode = pyCode.arg(eiGuess, pyWhiteBeam);
-    }
-    else
-    {
+    } else {
       pyCode += "abs_rfiles = " + pyAbsRunFiles + "\n";
-      pyCode +=
-        "for run, abs in zip(rfiles, abs_rfiles):\n"
-        "  mono_sample.convert_to_energy(%1, run, %2, %3,abs, %6)\n";
-      pyCode = pyCode.arg(pyWhiteBeam,eiGuess,rebin,map_file,pyAbsRunFiles, pyAbsWhiteBeam);
-      //                         pyWhiteBeam,pyRunFiles, eiGuess,rebin,map_file,pyAbsRunFiles, pyAbsWhiteBeam
+      pyCode += "for run, abs in zip(rfiles, abs_rfiles):\n"
+                "  mono_sample.convert_to_energy(%1, run, %2, %3,abs, %6)\n";
+      pyCode = pyCode.arg(pyWhiteBeam, eiGuess, rebin, map_file, pyAbsRunFiles,
+                          pyAbsWhiteBeam);
+      //                         pyWhiteBeam,pyRunFiles,
+      //                         eiGuess,rebin,map_file,pyAbsRunFiles,
+      //                         pyAbsWhiteBeam
     }
   }
   m_pyScript = pyCode;
@@ -138,87 +137,85 @@ void deltaECalc::createProcessingScript(const QStringList &runFiles, const QStri
 * Add the analysis options from the form to the script
 * @param pyCode :: The string containing the script to update
 */
-void deltaECalc::addAnalysisOptions(QString & pyCode)
-{
-  //Analysis options
-  QString inputValue = m_sets.cbNormal->currentText();  ;
-  pyCode += QString("mono_sample.prop_man.normalise_method = '%1'\n").arg(inputValue);
+void deltaECalc::addAnalysisOptions(QString &pyCode) {
+  // Analysis options
+  QString inputValue = m_sets.cbNormal->currentText();
+  ;
+  pyCode +=
+      QString("mono_sample.prop_man.normalise_method = '%1'\n").arg(inputValue);
 
   pyCode += QString("mono_sample.prop_man.background = %1\n");
-  if( this->m_bgRemove )
-  {
+  if (this->m_bgRemove) {
     pyCode = pyCode.arg("True");
-    pyCode += QString("mono_sample.prop_man.background_range = [%1, %2]\n").arg(this->m_TOFWinSt).arg(this->m_TOFWinEnd);
-  }
-  else
-  {
+    pyCode += QString("mono_sample.prop_man.background_range = [%1, %2]\n")
+                  .arg(this->m_TOFWinSt)
+                  .arg(this->m_TOFWinEnd);
+  } else {
     pyCode = pyCode.arg("False");
   }
 
-  //Convert to energy
+  // Convert to energy
   pyCode += QString("mono_sample.prop_man.fix_ei = %1\n");
-  if( m_sets.ckFixEi->isChecked() )
-  {
+  if (m_sets.ckFixEi->isChecked()) {
     pyCode = pyCode.arg("True");
-  }
-  else
-  {
+  } else {
     pyCode = pyCode.arg("False");
   }
-  pyCode += QString("mono_sample.prop_man.energy_bins = '%1,%2,%3'\n").arg(m_sets.leELow->text(), m_sets.leEWidth->text(), m_sets.leEHigh->text());
+  pyCode += QString("mono_sample.prop_man.energy_bins = '%1,%2,%3'\n")
+                .arg(m_sets.leELow->text(), m_sets.leEWidth->text(),
+                     m_sets.leEHigh->text());
   QString mapFile = m_sets.mapFile->getFirstFilename();
-  if( !mapFile.isEmpty() )
-  {
+  if (!mapFile.isEmpty()) {
     pyCode += QString("mono_sample.prop_man.map_file = r'%1'\n").arg(mapFile);
   }
-  if( m_sets.ckRunAbsol->isChecked() )
-  {
+  if (m_sets.ckRunAbsol->isChecked()) {
     QString absMapFile = m_sets.absMapFile->getFirstFilename();
-    if ( !absMapFile.isEmpty() )
-    {
-      pyCode += QString("mono_sample.prop_man.monovan_mapfile = r'%1'\n").arg(absMapFile);
+    if (!absMapFile.isEmpty()) {
+      pyCode += QString("mono_sample.prop_man.monovan_mapfile = r'%1'\n")
+                    .arg(absMapFile);
     }
     // Set the mono vanadium integration range
-    pyCode += QString("mono_sample.prop_man.monovan_integr_range=[float(%1),float(%2)]\n");
+    pyCode += QString(
+        "mono_sample.prop_man.monovan_integr_range=[float(%1),float(%2)]\n");
     pyCode = pyCode.arg(m_sets.leVanELow->text(), m_sets.leVanEHigh->text());
     // Set the sample mass and rmm
-    pyCode += QString("mono_sample.prop_man.sample_mass = %1\n").arg(m_sets.leSamMass->text());
-    pyCode += QString("mono_sample.prop_man.sample_rmm = %1\n").arg(m_sets.leRMMMass->text());
+    pyCode += QString("mono_sample.prop_man.sample_mass = %1\n")
+                  .arg(m_sets.leSamMass->text());
+    pyCode += QString("mono_sample.prop_man.sample_rmm = %1\n")
+                  .arg(m_sets.leRMMMass->text());
     // And any changed vanadium mass
-    pyCode += QString("mono_sample.prop_man.van_mass = %1\n").arg(m_sets.leVanMass->text());
+    pyCode += QString("mono_sample.prop_man.van_mass = %1\n")
+                  .arg(m_sets.leVanMass->text());
   }
 }
 
-
-void deltaECalc::addMaskingCommands(QString & analysisScript)
-{
-  if (!m_sets.ckRunAbsol->isChecked())
-  {
+void deltaECalc::addMaskingCommands(QString &analysisScript) {
+  if (!m_sets.ckRunAbsol->isChecked()) {
     analysisScript += "mono_sample.prop_man.run_diagnostics = False\n";
   }
 
-  if( m_diagnosedWS.isEmpty() )
-  {
+  if (m_diagnosedWS.isEmpty()) {
     return;
   }
   // provide pre-calculated masks
   analysisScript += "mono_sample.spectra_masks = '" + m_diagnosedWS + "'\n";
-  // disable internal convert_to_energy diagnostics. We already have diagnostics workspace
+  // disable internal convert_to_energy diagnostics. We already have diagnostics
+  // workspace
   analysisScript += "mono_sample.prop_man.run_diagnostics = False\n";
 
   //   QString tmpWS = QString("tmp_") + m_diagnosedWS;
 
-  //   analysisScript += "fdol_alg = FindDetectorsOutsideLimits(InputWorkspace='%1',OutputWorkspace='%2',HighThreshold=10,LowThreshold=-1,OutputFile='')\n";
-  //   analysisScript += "mono_sample.spectra_masks = fdol_alg.getPropertyValue('BadSpectraNums')\n";
+  //   analysisScript += "fdol_alg =
+  //   FindDetectorsOutsideLimits(InputWorkspace='%1',OutputWorkspace='%2',HighThreshold=10,LowThreshold=-1,OutputFile='')\n";
+  //   analysisScript += "mono_sample.spectra_masks =
+  //   fdol_alg.getPropertyValue('BadSpectraNums')\n";
   //   analysisScript += "mtd.deleteWorkspace('%2')\n";
 
   //   analysisScript = analysisScript.arg(m_diagnosedWS).arg(tmpWS);
 }
 
-QString deltaECalc::createPyListAsString(const QStringList & names) const
-{
-  if( names.isEmpty() )
-  {
+QString deltaECalc::createPyListAsString(const QStringList &names) const {
+  if (names.isEmpty()) {
     return "None";
   }
   QString asString = "[r'";
@@ -231,8 +228,7 @@ QString deltaECalc::createPyListAsString(const QStringList & names) const
 *  the input workspace/s
 *  @param maskWS :: name of the workspace whose detector masking will be copied
 */
-void deltaECalc::setDiagnosedWorkspaceName(const QString &maskWS)
-{
+void deltaECalc::setDiagnosedWorkspaceName(const QString &maskWS) {
   m_diagnosedWS = maskWS;
 }
 /** Insert the number before the dot of the extension
@@ -240,16 +236,17 @@ void deltaECalc::setDiagnosedWorkspaceName(const QString &maskWS)
 * @param number :: the number to insert
 * @return the filename with the number inserted
 */
-std::string deltaECalc::insertNumber(const std::string &filename, const int number) const
-{
+std::string deltaECalc::insertNumber(const std::string &filename,
+                                     const int number) const {
   // we're going to break up the file name to insert a number into it
   Poco::Path f(filename);
   // check if the path is given in the filename
-  if ( f.depth() > 0 )
-  {// get the directory name, the full path of the file minus its name and add it back to the result so that we don't lose the path
-    return f.directory(f.depth()-1)+"/"+f.getBaseName()+"_"+
-      boost::lexical_cast<std::string>(number)+"."+f.getExtension();
+  if (f.depth() > 0) { // get the directory name, the full path of the file
+                       // minus its name and add it back to the result so that
+                       // we don't lose the path
+    return f.directory(f.depth() - 1) + "/" + f.getBaseName() + "_" +
+           boost::lexical_cast<std::string>(number) + "." + f.getExtension();
   }
-  return f.getBaseName()+"_"+boost::lexical_cast<std::string>(number)+
-    "."+f.getExtension();
+  return f.getBaseName() + "_" + boost::lexical_cast<std::string>(number) +
+         "." + f.getExtension();
 }
diff --git a/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h b/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
index e6ccdfd682bb4fd9a73982bf03ba46846660b608..8dfda5b8aad765843607d3e4b3632690b6959e8d 100644
--- a/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
+++ b/MantidQt/CustomInterfaces/test/ALCDataLoadingPresenterTest.h
@@ -13,20 +13,21 @@
 using namespace MantidQt::CustomInterfaces;
 using namespace testing;
 
-namespace boost{
-  template<class CharType, class CharTrait>
-  std::basic_ostream<CharType, CharTrait>& operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<std::pair<double,double> > const& maybe)
-  {
-    if (maybe)
-        out << maybe->first << ", " << maybe->second;
-    return out;
-  }
+namespace boost {
+template <class CharType, class CharTrait>
+std::basic_ostream<CharType, CharTrait> &
+operator<<(std::basic_ostream<CharType, CharTrait> &out,
+           optional<std::pair<double, double>> const &maybe) {
+  if (maybe)
+    out << maybe->first << ", " << maybe->second;
+  return out;
+}
 }
 
-class MockALCDataLoadingView : public IALCDataLoadingView
-{
-  // XXX: A workaround, needed because of the way the comma is treated in a macro
-  typedef std::pair<double,double> PAIR_OF_DOUBLES;
+class MockALCDataLoadingView : public IALCDataLoadingView {
+  // XXX: A workaround, needed because of the way the comma is treated in a
+  // macro
+  typedef std::pair<double, double> PAIR_OF_DOUBLES;
 
 public:
   MOCK_CONST_METHOD0(firstRun, std::string());
@@ -46,12 +47,13 @@ public:
   MOCK_CONST_METHOD0(autoString, std::string());
 
   MOCK_METHOD0(initialize, void());
-  MOCK_METHOD2(setDataCurve, void(const QwtData&, const std::vector<double>&));
-  MOCK_METHOD1(displayError, void(const std::string&));
-  MOCK_METHOD1(setAvailableLogs, void(const std::vector<std::string>&));
-  MOCK_METHOD1(setAvailablePeriods, void(const std::vector<std::string>&));
-  MOCK_METHOD2(setTimeLimits, void(double,double));
-  MOCK_METHOD2(setTimeRange, void(double,double));
+  MOCK_METHOD2(setDataCurve,
+               void(const QwtData &, const std::vector<double> &));
+  MOCK_METHOD1(displayError, void(const std::string &));
+  MOCK_METHOD1(setAvailableLogs, void(const std::vector<std::string> &));
+  MOCK_METHOD1(setAvailablePeriods, void(const std::vector<std::string> &));
+  MOCK_METHOD2(setTimeLimits, void(double, double));
+  MOCK_METHOD2(setTimeRange, void(double, double));
   MOCK_METHOD0(disableAll, void());
   MOCK_METHOD0(enableAll, void());
   MOCK_METHOD0(help, void());
@@ -63,23 +65,29 @@ public:
   void selectFirstRun() { emit firstRunSelected(); }
 };
 
-MATCHER_P3(QwtDataX, i, value, delta, "") { return fabs(arg.x(i) - value) < delta; }
-MATCHER_P3(QwtDataY, i, value, delta, "") { return fabs(arg.y(i) - value) < delta; }
-MATCHER_P3(VectorValue, i, value, delta, "") { return fabs(arg.at(i) - value) < delta; }
+MATCHER_P3(QwtDataX, i, value, delta, "") {
+  return fabs(arg.x(i) - value) < delta;
+}
+MATCHER_P3(QwtDataY, i, value, delta, "") {
+  return fabs(arg.y(i) - value) < delta;
+}
+MATCHER_P3(VectorValue, i, value, delta, "") {
+  return fabs(arg.at(i) - value) < delta;
+}
 
-class ALCDataLoadingPresenterTest : public CxxTest::TestSuite
-{
-  MockALCDataLoadingView* m_view;
-  ALCDataLoadingPresenter* m_presenter;
+class ALCDataLoadingPresenterTest : public CxxTest::TestSuite {
+  MockALCDataLoadingView *m_view;
+  ALCDataLoadingPresenter *m_presenter;
 
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static ALCDataLoadingPresenterTest *createSuite() { return new ALCDataLoadingPresenterTest(); }
-  static void destroySuite( ALCDataLoadingPresenterTest *suite ) { delete suite; }
+  static ALCDataLoadingPresenterTest *createSuite() {
+    return new ALCDataLoadingPresenterTest();
+  }
+  static void destroySuite(ALCDataLoadingPresenterTest *suite) { delete suite; }
 
-  ALCDataLoadingPresenterTest()
-  {
+  ALCDataLoadingPresenterTest() {
     FrameworkManager::Instance(); // To make sure everything is initialized
   }
 
@@ -94,7 +102,9 @@ public:
     ON_CALL(*m_view, calculationType()).WillByDefault(Return("Integral"));
     ON_CALL(*m_view, log()).WillByDefault(Return("sample_magn_field"));
     ON_CALL(*m_view, function()).WillByDefault(Return("Last"));
-    ON_CALL(*m_view, timeRange()).WillByDefault(Return(boost::make_optional(std::make_pair(-6.0,32.0))));
+    ON_CALL(*m_view, timeRange())
+        .WillByDefault(
+            Return(boost::make_optional(std::make_pair(-6.0, 32.0))));
     ON_CALL(*m_view, deadTimeType()).WillByDefault(Return("None"));
     ON_CALL(*m_view, detectorGroupingType()).WillByDefault(Return("Auto"));
     ON_CALL(*m_view, redPeriod()).WillByDefault(Return("1"));
@@ -107,82 +117,78 @@ public:
     delete m_view;
   }
 
-  void test_initialize()
-  {
+  void test_initialize() {
     MockALCDataLoadingView view;
     ALCDataLoadingPresenter presenter(&view);
     EXPECT_CALL(view, initialize());
     presenter.initialize();
   }
 
-  void test_defaultLoad()
-  {
+  void test_defaultLoad() {
     InSequence s;
     EXPECT_CALL(*m_view, disableAll());
 
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size,3),
-                                            QwtDataX(0, 1350, 1E-8),
-                                            QwtDataX(1, 1360, 1E-8),
-                                            QwtDataX(2, 1370, 1E-8),
-                                            QwtDataY(0, 0.150, 1E-3),
-                                            QwtDataY(1, 0.143, 1E-3),
-                                            QwtDataY(2, 0.128, 1E-3)),
-                                      AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,1.285E-3,1E-6),
-                                            VectorValue(1,1.284E-3,1E-6),
-                                            VectorValue(2,1.280E-3,1E-6))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(AllOf(Property(&QwtData::size, 3), QwtDataX(0, 1350, 1E-8),
+                           QwtDataX(1, 1360, 1E-8), QwtDataX(2, 1370, 1E-8),
+                           QwtDataY(0, 0.150, 1E-3), QwtDataY(1, 0.143, 1E-3),
+                           QwtDataY(2, 0.128, 1E-3)),
+                     AllOf(Property(&std::vector<double>::size, 3),
+                           VectorValue(0, 1.285E-3, 1E-6),
+                           VectorValue(1, 1.284E-3, 1E-6),
+                           VectorValue(2, 1.280E-3, 1E-6))));
 
     EXPECT_CALL(*m_view, enableAll());
 
     m_view->requestLoading();
   }
 
-  void test_load_differential()
-  {
+  void test_load_differential() {
     // Change to differential calculation type
     ON_CALL(*m_view, calculationType()).WillByDefault(Return("Differential"));
 
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size,3),
-                                            QwtDataY(0, 3.00349, 1E-3),
-                                            QwtDataY(1, 2.3779, 1E-3),
-                                            QwtDataY(2, 2.47935, 1E-3)),
-                                      AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,0.539,1E-3),
-                                            VectorValue(1,0.535,1E-3),
-                                            VectorValue(2,0.541,1E-3))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(
+            AllOf(Property(&QwtData::size, 3), QwtDataY(0, 3.00349, 1E-3),
+                  QwtDataY(1, 2.3779, 1E-3), QwtDataY(2, 2.47935, 1E-3)),
+            AllOf(Property(&std::vector<double>::size, 3),
+                  VectorValue(0, 0.539, 1E-3), VectorValue(1, 0.535, 1E-3),
+                  VectorValue(2, 0.541, 1E-3))));
 
     m_view->requestLoading();
   }
 
-  void test_load_timeLimits()
-  {
+  void test_load_timeLimits() {
     // Set time limit
-    ON_CALL(*m_view, timeRange()).WillByDefault(Return(boost::make_optional(std::make_pair(5.0,10.0))));
+    ON_CALL(*m_view, timeRange())
+        .WillByDefault(Return(boost::make_optional(std::make_pair(5.0, 10.0))));
 
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size,3),
-                                            QwtDataY(0, 0.137, 1E-3),
-                                            QwtDataY(1, 0.141, 1E-3),
-                                            QwtDataY(2, 0.111, 1E-3)),
-                                      AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,4.244E-3,1E-6),
-                                            VectorValue(1,4.243E-3,1E-6),
-                                            VectorValue(2,4.200E-3,1E-6))));
+    EXPECT_CALL(*m_view,
+                setDataCurve(
+                    AllOf(Property(&QwtData::size, 3), QwtDataY(0, 0.137, 1E-3),
+                          QwtDataY(1, 0.141, 1E-3), QwtDataY(2, 0.111, 1E-3)),
+                    AllOf(Property(&std::vector<double>::size, 3),
+                          VectorValue(0, 4.244E-3, 1E-6),
+                          VectorValue(1, 4.243E-3, 1E-6),
+                          VectorValue(2, 4.200E-3, 1E-6))));
 
     m_view->requestLoading();
   }
 
-  void test_updateAvailableInfo()
-  {
+  void test_updateAvailableInfo() {
     EXPECT_CALL(*m_view, firstRun()).WillRepeatedly(Return("MUSR00015189.nxs"));
     // Test logs
-    EXPECT_CALL(*m_view, setAvailableLogs(AllOf(Property(&std::vector<std::string>::size, 39),
-                                                Contains("run_number"),
-                                                Contains("sample_magn_field"),
-                                                Contains("Field_Danfysik")))).Times(1);
+    EXPECT_CALL(*m_view,
+                setAvailableLogs(
+                    AllOf(Property(&std::vector<std::string>::size, 39),
+                          Contains("run_number"), Contains("sample_magn_field"),
+                          Contains("Field_Danfysik")))).Times(1);
     // Test periods
-    EXPECT_CALL(*m_view, setAvailablePeriods(AllOf(Property(&std::vector<std::string>::size, 2),
-                                                Contains("1"),
-                                                Contains("2")))).Times(1);
+    EXPECT_CALL(*m_view, setAvailablePeriods(
+                             AllOf(Property(&std::vector<std::string>::size, 2),
+                                   Contains("1"), Contains("2")))).Times(1);
     // Test time limits
     auto timeRange = std::make_pair<double, double>(0.0, 0.0);
     ON_CALL(*m_view, timeRange())
@@ -198,13 +204,11 @@ public:
                 setAvailableLogs(
                     AllOf(Property(&std::vector<std::string>::size, 39),
                           Contains("run_number"), Contains("sample_magn_field"),
-                          Contains("Field_Danfysik"))))
-        .Times(1);
+                          Contains("Field_Danfysik")))).Times(1);
     // Test periods
     EXPECT_CALL(*m_view, setAvailablePeriods(
                              AllOf(Property(&std::vector<std::string>::size, 2),
-                                   Contains("1"), Contains("2"))))
-        .Times(1);
+                                   Contains("1"), Contains("2")))).Times(1);
     // Test time limits
     auto timeRange =
         std::make_pair<double, double>(0.1, 10.0); // not the first run loaded
@@ -225,66 +229,64 @@ public:
     m_view->requestLoading();
   }
 
-  void test_updateAvailableLogs_invalidFirstRun()
-  {
+  void test_updateAvailableLogs_invalidFirstRun() {
     ON_CALL(*m_view, firstRun()).WillByDefault(Return(""));
-    EXPECT_CALL(*m_view, setAvailableLogs(ElementsAre())); // Empty array expected
+    EXPECT_CALL(*m_view,
+                setAvailableLogs(ElementsAre())); // Empty array expected
     TS_ASSERT_THROWS_NOTHING(m_view->selectFirstRun());
   }
 
-  void test_updateAvailableLogs_unsupportedFirstRun()
-  {
-    ON_CALL(*m_view, firstRun()).WillByDefault(Return("LOQ49886.nxs")); // XXX: not a Muon file
-    EXPECT_CALL(*m_view, setAvailableLogs(ElementsAre())); // Empty array expected
+  void test_updateAvailableLogs_unsupportedFirstRun() {
+    ON_CALL(*m_view, firstRun())
+        .WillByDefault(Return("LOQ49886.nxs")); // XXX: not a Muon file
+    EXPECT_CALL(*m_view,
+                setAvailableLogs(ElementsAre())); // Empty array expected
     TS_ASSERT_THROWS_NOTHING(m_view->selectFirstRun());
   }
 
-  void test_load_error()
-  {
-    // Set last run to one of the different instrument - should cause error within algorithms exec
+  void test_load_error() {
+    // Set last run to one of the different instrument - should cause error
+    // within algorithms exec
     ON_CALL(*m_view, lastRun()).WillByDefault(Return("EMU00006473.nxs"));
-    EXPECT_CALL(*m_view, setDataCurve(_,_)).Times(0);
+    EXPECT_CALL(*m_view, setDataCurve(_, _)).Times(0);
     EXPECT_CALL(*m_view, displayError(StrNe(""))).Times(1);
     m_view->requestLoading();
   }
 
-  void test_load_invalidRun()
-  {
+  void test_load_invalidRun() {
     ON_CALL(*m_view, firstRun()).WillByDefault(Return(""));
-    EXPECT_CALL(*m_view, setDataCurve(_,_)).Times(0);
+    EXPECT_CALL(*m_view, setDataCurve(_, _)).Times(0);
     EXPECT_CALL(*m_view, displayError(StrNe(""))).Times(1);
     m_view->requestLoading();
   }
 
-  void test_load_nonExistentFile()
-  {
+  void test_load_nonExistentFile() {
     ON_CALL(*m_view, lastRun()).WillByDefault(Return("non-existent-file"));
-    EXPECT_CALL(*m_view, setDataCurve(_,_)).Times(0);
+    EXPECT_CALL(*m_view, setDataCurve(_, _)).Times(0);
     EXPECT_CALL(*m_view, displayError(StrNe(""))).Times(1);
     m_view->requestLoading();
   }
 
-  void test_correctionsFromDataFile ()
-  {
+  void test_correctionsFromDataFile() {
     // Change dead time correction type
     // Test results with corrections from run data
     ON_CALL(*m_view, deadTimeType()).WillByDefault(Return("FromRunData"));
     EXPECT_CALL(*m_view, deadTimeType()).Times(2);
     EXPECT_CALL(*m_view, deadTimeFile()).Times(0);
     EXPECT_CALL(*m_view, enableAll()).Times(1);
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size,3),
-                                            QwtDataY(0, 0.150616, 1E-3),
-                                            QwtDataY(1, 0.143444, 1E-3),
-                                            QwtDataY(2, 0.128856, 1E-3)),
-                                      AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,1.278E-3,1E-6),
-                                            VectorValue(1,1.278E-3,1E-6),
-                                            VectorValue(2,1.274E-3,1E-6))));
+    EXPECT_CALL(*m_view,
+                setDataCurve(AllOf(Property(&QwtData::size, 3),
+                                   QwtDataY(0, 0.150616, 1E-3),
+                                   QwtDataY(1, 0.143444, 1E-3),
+                                   QwtDataY(2, 0.128856, 1E-3)),
+                             AllOf(Property(&std::vector<double>::size, 3),
+                                   VectorValue(0, 1.278E-3, 1E-6),
+                                   VectorValue(1, 1.278E-3, 1E-6),
+                                   VectorValue(2, 1.274E-3, 1E-6))));
     m_view->requestLoading();
   }
 
-  void test_correctionsFromCustomFile ()
-  {
+  void test_correctionsFromCustomFile() {
     // Change dead time correction type
     // Test only expected number of calls
     ON_CALL(*m_view, deadTimeType()).WillByDefault(Return("FromSpecifiedFile"));
@@ -294,8 +296,7 @@ public:
     m_view->requestLoading();
   }
 
-  void test_customGrouping ()
-  {
+  void test_customGrouping() {
     // Change grouping type to 'Custom'
     ON_CALL(*m_view, detectorGroupingType()).WillByDefault(Return("Custom"));
     // Set grouping, the same as the default
@@ -304,23 +305,21 @@ public:
     EXPECT_CALL(*m_view, getForwardGrouping()).Times(2);
     EXPECT_CALL(*m_view, getBackwardGrouping()).Times(2);
     EXPECT_CALL(*m_view, enableAll()).Times(1);
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size, 3),
-                                            QwtDataX(0, 1350, 1E-8),
-                                            QwtDataX(1, 1360, 1E-8),
-                                            QwtDataX(2, 1370, 1E-8),
-                                            QwtDataY(0, 0.150, 1E-3),
-                                            QwtDataY(1, 0.143, 1E-3),
-                                            QwtDataY(2, 0.128, 1E-3)),
-                                       AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,1.285E-3,1E-6),
-                                            VectorValue(1,1.284E-3,1E-6),
-                                            VectorValue(2,1.280E-3,1E-6))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(AllOf(Property(&QwtData::size, 3), QwtDataX(0, 1350, 1E-8),
+                           QwtDataX(1, 1360, 1E-8), QwtDataX(2, 1370, 1E-8),
+                           QwtDataY(0, 0.150, 1E-3), QwtDataY(1, 0.143, 1E-3),
+                           QwtDataY(2, 0.128, 1E-3)),
+                     AllOf(Property(&std::vector<double>::size, 3),
+                           VectorValue(0, 1.285E-3, 1E-6),
+                           VectorValue(1, 1.284E-3, 1E-6),
+                           VectorValue(2, 1.280E-3, 1E-6))));
     m_view->selectFirstRun();
     m_view->requestLoading();
   }
 
-  void test_customPeriods ()
-  {
+  void test_customPeriods() {
     // Change red period to 2
     // Change green period to 1
     // Check Subtract, greenPeriod() should be called once
@@ -329,44 +328,41 @@ public:
     ON_CALL(*m_view, greenPeriod()).WillByDefault(Return("1"));
     EXPECT_CALL(*m_view, greenPeriod()).Times(1);
     // Check results
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size, 3),
-                                            QwtDataX(0, 1350, 1E-8),
-                                            QwtDataX(1, 1360, 1E-8),
-                                            QwtDataX(2, 1370, 1E-8),
-                                            QwtDataY(0, 0.012884, 1E-6),
-                                            QwtDataY(1, 0.022489, 1E-6),
-                                            QwtDataY(2, 0.038717, 1E-6)),
-                                       AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,1.821E-3,1E-6),
-                                            VectorValue(1,1.821E-3,1E-6),
-                                            VectorValue(2,1.817E-3,1E-6))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(AllOf(Property(&QwtData::size, 3), QwtDataX(0, 1350, 1E-8),
+                           QwtDataX(1, 1360, 1E-8), QwtDataX(2, 1370, 1E-8),
+                           QwtDataY(0, 0.012884, 1E-6),
+                           QwtDataY(1, 0.022489, 1E-6),
+                           QwtDataY(2, 0.038717, 1E-6)),
+                     AllOf(Property(&std::vector<double>::size, 3),
+                           VectorValue(0, 1.821E-3, 1E-6),
+                           VectorValue(1, 1.821E-3, 1E-6),
+                           VectorValue(2, 1.817E-3, 1E-6))));
     m_view->requestLoading();
   }
 
-  void test_logFunction ()
-  {
+  void test_logFunction() {
     ON_CALL(*m_view, function()).WillByDefault(Return("First"));
     ON_CALL(*m_view, log()).WillByDefault(Return("Field_Danfysik"));
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size,3),
-                                            QwtDataX(0, 1398.090, 1E-3),
-                                            QwtDataX(1, 1360.200, 1E-3),
-                                            QwtDataX(2, 1364.520, 1E-3),
-                                            QwtDataY(0, 0.15004, 1E-5),
-                                            QwtDataY(1, 0.14289, 1E-5),
-                                            QwtDataY(2, 0.12837, 1E-5)),
-                                       AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0,1.285E-3,1E-6),
-                                            VectorValue(1,1.284E-3,1E-6),
-                                            VectorValue(2,1.280E-3,1E-6))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(
+            AllOf(Property(&QwtData::size, 3), QwtDataX(0, 1398.090, 1E-3),
+                  QwtDataX(1, 1360.200, 1E-3), QwtDataX(2, 1364.520, 1E-3),
+                  QwtDataY(0, 0.15004, 1E-5), QwtDataY(1, 0.14289, 1E-5),
+                  QwtDataY(2, 0.12837, 1E-5)),
+            AllOf(Property(&std::vector<double>::size, 3),
+                  VectorValue(0, 1.285E-3, 1E-6),
+                  VectorValue(1, 1.284E-3, 1E-6),
+                  VectorValue(2, 1.280E-3, 1E-6))));
     m_view->requestLoading();
   }
 
-  void test_helpPage ()
-  {
+  void test_helpPage() {
     EXPECT_CALL(*m_view, help()).Times(1);
     m_view->help();
   }
 };
 
-
 #endif /* MANTID_CUSTOMINTERFACES_ALCDATALOADINGTEST_H_ */
diff --git a/MantidQt/CustomInterfaces/test/ALCPeakFittingPresenterTest.h b/MantidQt/CustomInterfaces/test/ALCPeakFittingPresenterTest.h
index fc582ca0f337339bf10d70a649c49e8c600ea461..2b3f61c40a22eb40a6fc2337d4fdf21fcdc264e3 100644
--- a/MantidQt/CustomInterfaces/test/ALCPeakFittingPresenterTest.h
+++ b/MantidQt/CustomInterfaces/test/ALCPeakFittingPresenterTest.h
@@ -17,25 +17,23 @@ using namespace Mantid;
 using namespace MantidQt::CustomInterfaces;
 using namespace testing;
 
-namespace boost
-{
-  template<class CharType, class CharTrait>
-  std::basic_ostream<CharType, CharTrait>& operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<QString> const& maybe)
-  {
-    if (maybe)
-      out << maybe->toStdString();
-    return out;
-  }
+namespace boost {
+template <class CharType, class CharTrait>
+std::basic_ostream<CharType, CharTrait> &
+operator<<(std::basic_ostream<CharType, CharTrait> &out,
+           optional<QString> const &maybe) {
+  if (maybe)
+    out << maybe->toStdString();
+  return out;
+}
 }
 
-class MockALCPeakFittingView : public IALCPeakFittingView
-{
+class MockALCPeakFittingView : public IALCPeakFittingView {
 public:
   void requestFit() { emit fitRequested(); }
   void changeCurrentFunction() { emit currentFunctionChanged(); }
   void changePeakPicker() { emit peakPickerChanged(); }
-  void changeParameter(const QString& funcIndex, const QString& paramName)
-  {
+  void changeParameter(const QString &funcIndex, const QString &paramName) {
     emit parameterChanged(funcIndex, paramName);
   }
   void plotGuess() override { emit plotGuessClicked(); }
@@ -45,19 +43,19 @@ public:
   MOCK_CONST_METHOD0(peakPicker, IPeakFunction_const_sptr());
 
   MOCK_METHOD0(initialize, void());
-  MOCK_METHOD2(setDataCurve, void(const QwtData&, const std::vector<double>&));
-  MOCK_METHOD1(setFittedCurve, void(const QwtData&));
+  MOCK_METHOD2(setDataCurve,
+               void(const QwtData &, const std::vector<double> &));
+  MOCK_METHOD1(setFittedCurve, void(const QwtData &));
   MOCK_METHOD1(setPeakPickerEnabled, void(bool));
-  MOCK_METHOD1(setPeakPicker, void(const IPeakFunction_const_sptr&));
-  MOCK_METHOD1(setFunction, void(const IFunction_const_sptr&));
-  MOCK_METHOD3(setParameter, void(const QString&, const QString&, double));
-  MOCK_METHOD1(displayError, void(const QString&));
+  MOCK_METHOD1(setPeakPicker, void(const IPeakFunction_const_sptr &));
+  MOCK_METHOD1(setFunction, void(const IFunction_const_sptr &));
+  MOCK_METHOD3(setParameter, void(const QString &, const QString &, double));
+  MOCK_METHOD1(displayError, void(const QString &));
   MOCK_METHOD0(help, void());
   MOCK_METHOD1(changePlotGuessState, void(bool));
 };
 
-class MockALCPeakFittingModel : public IALCPeakFittingModel
-{
+class MockALCPeakFittingModel : public IALCPeakFittingModel {
 public:
   void changeFittedPeaks() { emit fittedPeaksChanged(); }
   void changeData() { emit dataChanged(); }
@@ -68,25 +66,29 @@ public:
   MOCK_METHOD1(fitPeaks, void(IFunction_const_sptr));
 };
 
-MATCHER_P3(QwtDataX, i, value, delta, "") { return fabs(arg.x(i) - value) < delta; }
-MATCHER_P3(QwtDataY, i, value, delta, "") { return fabs(arg.y(i) - value) < delta; }
-MATCHER_P3(VectorValue, i, value, delta, "") { return fabs(arg.at(i) - value) < delta; }
+MATCHER_P3(QwtDataX, i, value, delta, "") {
+  return fabs(arg.x(i) - value) < delta;
+}
+MATCHER_P3(QwtDataY, i, value, delta, "") {
+  return fabs(arg.y(i) - value) < delta;
+}
+MATCHER_P3(VectorValue, i, value, delta, "") {
+  return fabs(arg.at(i) - value) < delta;
+}
 
 // DoubleNear matcher was introduced in gmock 1.7 only
 MATCHER_P2(DoubleDelta, value, delta, "") { return fabs(arg - value) < delta; }
 
 using namespace MantidQt::CustomInterfaces;
 
-class ALCPeakFittingPresenterTest : public CxxTest::TestSuite
-{
-  MockALCPeakFittingView* m_view;
-  MockALCPeakFittingModel* m_model;
-  ALCPeakFittingPresenter* m_presenter;
+class ALCPeakFittingPresenterTest : public CxxTest::TestSuite {
+  MockALCPeakFittingView *m_view;
+  MockALCPeakFittingModel *m_model;
+  ALCPeakFittingPresenter *m_presenter;
 
-  IPeakFunction_sptr createGaussian(double centre, double fwhm, double height)
-  {
+  IPeakFunction_sptr createGaussian(double centre, double fwhm, double height) {
     auto peak = boost::dynamic_pointer_cast<IPeakFunction>(
-          API::FunctionFactory::Instance().createFunction("Gaussian"));
+        API::FunctionFactory::Instance().createFunction("Gaussian"));
     peak->setCentre(centre);
     peak->setFwhm(fwhm);
     peak->setHeight(height);
@@ -96,11 +98,12 @@ class ALCPeakFittingPresenterTest : public CxxTest::TestSuite
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static ALCPeakFittingPresenterTest *createSuite() { return new ALCPeakFittingPresenterTest(); }
-  static void destroySuite( ALCPeakFittingPresenterTest *suite ) { delete suite; }
+  static ALCPeakFittingPresenterTest *createSuite() {
+    return new ALCPeakFittingPresenterTest();
+  }
+  static void destroySuite(ALCPeakFittingPresenterTest *suite) { delete suite; }
 
-  ALCPeakFittingPresenterTest()
-  {
+  ALCPeakFittingPresenterTest() {
     API::FrameworkManager::Instance(); // To make sure everything is initialized
   }
 
@@ -121,8 +124,7 @@ public:
     delete m_view;
   }
 
-  void test_initialize()
-  {
+  void test_initialize() {
     MockALCPeakFittingView view;
     MockALCPeakFittingModel model;
     ALCPeakFittingPresenter presenter(&view, &model);
@@ -146,41 +148,39 @@ public:
     auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1, 3);
     ON_CALL(*m_model, data()).WillByDefault(Return(ws));
 
-    IFunction_sptr peaks = createGaussian(1,2,3);
+    IFunction_sptr peaks = createGaussian(1, 2, 3);
 
     ON_CALL(*m_view, function(QString(""))).WillByDefault(Return(peaks));
 
     EXPECT_CALL(*m_model, fitPeaks(Property(&IFunction_const_sptr::get,
-                                            Property(&IFunction::asString, peaks->asString()))));
+                                            Property(&IFunction::asString,
+                                                     peaks->asString()))));
 
     m_view->requestFit();
   }
 
-  void test_onDataChanged()
-  {
-    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1,3);
+  void test_onDataChanged() {
+    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1, 3);
 
     ON_CALL(*m_model, data()).WillByDefault(Return(ws));
 
-    EXPECT_CALL(*m_view, setDataCurve(AllOf(Property(&QwtData::size, 3),
-                                            QwtDataX(0, 1, 1E-8),
-                                            QwtDataX(1, 1, 1E-8),
-                                            QwtDataX(2, 1, 1E-8),
-                                            QwtDataY(0, 2, 1E-8),
-                                            QwtDataY(1, 2, 1E-8),
-                                            QwtDataY(2, 2, 1E-8)),
-                                      AllOf(Property(&std::vector<double>::size,3),
-                                            VectorValue(0, 3, 1E-6),
-                                            VectorValue(1, 3, 1E-6),
-                                            VectorValue(2, 3, 1E-6))));
+    EXPECT_CALL(
+        *m_view,
+        setDataCurve(AllOf(Property(&QwtData::size, 3), QwtDataX(0, 1, 1E-8),
+                           QwtDataX(1, 1, 1E-8), QwtDataX(2, 1, 1E-8),
+                           QwtDataY(0, 2, 1E-8), QwtDataY(1, 2, 1E-8),
+                           QwtDataY(2, 2, 1E-8)),
+                     AllOf(Property(&std::vector<double>::size, 3),
+                           VectorValue(0, 3, 1E-6), VectorValue(1, 3, 1E-6),
+                           VectorValue(2, 3, 1E-6))));
     m_model->changeData();
   }
 
-  void test_onFittedPeaksChanged()
-  {
-    ON_CALL(*m_model, fittedPeaks()).WillByDefault(Return(createGaussian(1,2,3)));
+  void test_onFittedPeaksChanged() {
+    ON_CALL(*m_model, fittedPeaks())
+        .WillByDefault(Return(createGaussian(1, 2, 3)));
 
-    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1,3);
+    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1, 3);
     ON_CALL(*m_model, data()).WillByDefault(Return(ws));
 
     // TODO: check better
@@ -190,11 +190,11 @@ public:
     m_model->changeFittedPeaks();
   }
 
-  void test_onFittedPeaksChanged_toEmpty()
-  {
-    ON_CALL(*m_model, fittedPeaks()).WillByDefault(Return(IFunction_const_sptr()));
+  void test_onFittedPeaksChanged_toEmpty() {
+    ON_CALL(*m_model, fittedPeaks())
+        .WillByDefault(Return(IFunction_const_sptr()));
 
-    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1,3);
+    auto ws = WorkspaceCreationHelper::Create2DWorkspace123(1, 3);
     ON_CALL(*m_model, data()).WillByDefault(Return(ws));
 
     EXPECT_CALL(*m_view, setFittedCurve(Property(&QwtData::size, 0)));
@@ -203,8 +203,7 @@ public:
     m_model->changeFittedPeaks();
   }
 
-  void test_onCurrentFunctionChanged_nothing()
-  {
+  void test_onCurrentFunctionChanged_nothing() {
     ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::none));
 
     EXPECT_CALL(*m_view, setPeakPickerEnabled(false));
@@ -212,81 +211,91 @@ public:
     m_view->changeCurrentFunction();
   }
 
-  void test_onCurrentFunctionChanged_peak()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f1")));
-    ON_CALL(*m_view, function(QString("f1"))).WillByDefault(Return(createGaussian(1,2,3)));
+  void test_onCurrentFunctionChanged_peak() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f1")));
+    ON_CALL(*m_view, function(QString("f1")))
+        .WillByDefault(Return(createGaussian(1, 2, 3)));
 
     EXPECT_CALL(*m_view, setPeakPickerEnabled(true));
-    EXPECT_CALL(*m_view, setPeakPicker(Property(&IPeakFunction_const_sptr::get,
-                                                AllOf(Property(&IPeakFunction::centre, 1),
-                                                      Property(&IPeakFunction::fwhm, 2),
-                                                      Property(&IPeakFunction::height, 3)))));
+    EXPECT_CALL(*m_view, setPeakPicker(Property(
+                             &IPeakFunction_const_sptr::get,
+                             AllOf(Property(&IPeakFunction::centre, 1),
+                                   Property(&IPeakFunction::fwhm, 2),
+                                   Property(&IPeakFunction::height, 3)))));
 
     m_view->changeCurrentFunction();
   }
 
-  void test_onCurrentFunctionChanged_nonPeak()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f1")));
-    ON_CALL(*m_view, function(QString("f1"))).WillByDefault(
-          Return(API::FunctionFactory::Instance().createFunction("LinearBackground")));
+  void test_onCurrentFunctionChanged_nonPeak() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f1")));
+    ON_CALL(*m_view, function(QString("f1")))
+        .WillByDefault(Return(API::FunctionFactory::Instance().createFunction(
+            "LinearBackground")));
 
     EXPECT_CALL(*m_view, setPeakPickerEnabled(false));
 
     m_view->changeCurrentFunction();
   }
 
-  void test_onPeakPickerChanged()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f1")));
-    ON_CALL(*m_view, peakPicker()).WillByDefault(Return(createGaussian(4,5,6)));
+  void test_onPeakPickerChanged() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f1")));
+    ON_CALL(*m_view, peakPicker())
+        .WillByDefault(Return(createGaussian(4, 5, 6)));
 
     EXPECT_CALL(*m_view, setParameter(QString("f1"), QString("PeakCentre"), 4));
-    EXPECT_CALL(*m_view, setParameter(QString("f1"), QString("Sigma"), DoubleDelta(2.123, 1E-3)));
+    EXPECT_CALL(*m_view, setParameter(QString("f1"), QString("Sigma"),
+                                      DoubleDelta(2.123, 1E-3)));
     EXPECT_CALL(*m_view, setParameter(QString("f1"), QString("Height"), 6));
 
     m_view->changePeakPicker();
   }
 
-  void test_onParameterChanged_peak()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f1")));
-    ON_CALL(*m_view, function(QString("f1"))).WillByDefault(Return(createGaussian(4,2,6)));
-    ON_CALL(*m_view, peakPicker()).WillByDefault(Return(createGaussian(4,5,6)));
+  void test_onParameterChanged_peak() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f1")));
+    ON_CALL(*m_view, function(QString("f1")))
+        .WillByDefault(Return(createGaussian(4, 2, 6)));
+    ON_CALL(*m_view, peakPicker())
+        .WillByDefault(Return(createGaussian(4, 5, 6)));
 
-    EXPECT_CALL(*m_view, setPeakPicker(Property(&IPeakFunction_const_sptr::get,
-                                                AllOf(Property(&IPeakFunction::centre, 4),
-                                                      Property(&IPeakFunction::fwhm, 2),
-                                                      Property(&IPeakFunction::height, 6)))));
+    EXPECT_CALL(*m_view, setPeakPicker(Property(
+                             &IPeakFunction_const_sptr::get,
+                             AllOf(Property(&IPeakFunction::centre, 4),
+                                   Property(&IPeakFunction::fwhm, 2),
+                                   Property(&IPeakFunction::height, 6)))));
 
     m_view->changeParameter(QString("f1"), QString("Sigma"));
   }
 
-  // parameterChanged signal is thrown in many scenarios - we want to update the PeakPicker only
-  // if it's thrown for currently selected peak function, because that's when PeakPicker is displayed
-  void test_onParameterChanged_notACurrentFunction()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f2")));
+  // parameterChanged signal is thrown in many scenarios - we want to update the
+  // PeakPicker only
+  // if it's thrown for currently selected peak function, because that's when
+  // PeakPicker is displayed
+  void test_onParameterChanged_notACurrentFunction() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f2")));
 
     EXPECT_CALL(*m_view, setPeakPicker(_)).Times(0);
 
     m_view->changeParameter(QString("f1"), QString("Sigma"));
   }
 
-  void test_onParameterChanged_nonPeak()
-  {
-    ON_CALL(*m_view, currentFunctionIndex()).WillByDefault(Return(boost::optional<QString>("f1")));
-    ON_CALL(*m_view, function(QString("f1"))).WillByDefault(
-          Return(API::FunctionFactory::Instance().createFunction("LinearBackground")));
+  void test_onParameterChanged_nonPeak() {
+    ON_CALL(*m_view, currentFunctionIndex())
+        .WillByDefault(Return(boost::optional<QString>("f1")));
+    ON_CALL(*m_view, function(QString("f1")))
+        .WillByDefault(Return(API::FunctionFactory::Instance().createFunction(
+            "LinearBackground")));
 
     EXPECT_CALL(*m_view, setPeakPicker(_)).Times(0);
 
     m_view->changeParameter(QString("f1"), QString("A0"));
   }
 
-  void test_helpPage ()
-  {
+  void test_helpPage() {
     EXPECT_CALL(*m_view, help()).Times(1);
     m_view->help();
   }
diff --git a/MantidQt/CustomInterfaces/test/DataProcessorGenerateNotebookTest.h b/MantidQt/CustomInterfaces/test/DataProcessorGenerateNotebookTest.h
index e90065be7cdf720a1af55f5bae7844b6f5df7e4a..27ced4bb3709f3802d0ea2cc68f68a97b0f5ee42 100644
--- a/MantidQt/CustomInterfaces/test/DataProcessorGenerateNotebookTest.h
+++ b/MantidQt/CustomInterfaces/test/DataProcessorGenerateNotebookTest.h
@@ -182,17 +182,10 @@ public:
     std::vector<std::string> notebookLines;
     boost::split(notebookLines, generatedNotebook, boost::is_any_of("\n"));
     const std::string result[] = {
-        "{",
-        "   \"metadata\" : {",
-        "      \"name\" : \"Mantid Notebook\"",
-        "   },",
-        "   \"nbformat\" : 3,",
-        "   \"nbformat_minor\" : 0,",
-        "   \"worksheets\" : [",
-        "      {",
-        "         \"cells\" : [",
-        "            {",
-        "               \"cell_type\" : \"markdown\",",
+        "{", "   \"metadata\" : {", "      \"name\" : \"Mantid Notebook\"",
+        "   },", "   \"nbformat\" : 3,", "   \"nbformat_minor\" : 0,",
+        "   \"worksheets\" : [", "      {", "         \"cells\" : [",
+        "            {", "               \"cell_type\" : \"markdown\",",
     };
 
     // Check that the first 10 lines are output as expected
diff --git a/MantidQt/CustomInterfaces/test/DataProcessorMockObjects.h b/MantidQt/CustomInterfaces/test/DataProcessorMockObjects.h
index 5eea61efc05e9478b7153d8d724c36426e0e1af8..88041dd78094f4346335f1ec227b6a008a36c125 100644
--- a/MantidQt/CustomInterfaces/test/DataProcessorMockObjects.h
+++ b/MantidQt/CustomInterfaces/test/DataProcessorMockObjects.h
@@ -93,7 +93,7 @@ private:
     for (size_t i = 0; i < 26; i++)
       commands.push_back(
           Mantid::Kernel::make_unique<DataProcessorAppendRowCommand>(this));
-		return commands;
+    return commands;
   };
   std::set<std::string> getTableList() const {
     return std::set<std::string>();
diff --git a/MantidQt/CustomInterfaces/test/GenericDataProcessorPresenterTest.h b/MantidQt/CustomInterfaces/test/GenericDataProcessorPresenterTest.h
index 6d60b4a90d37c7403aed32c52d893d511217883a..468290b5a504e3198a3afb80d069c9592c8279b3 100644
--- a/MantidQt/CustomInterfaces/test/GenericDataProcessorPresenterTest.h
+++ b/MantidQt/CustomInterfaces/test/GenericDataProcessorPresenterTest.h
@@ -33,7 +33,6 @@
 #include "ProgressableViewMockObject.h"
 #include "DataProcessorMockObjects.h"
 
-
 using namespace MantidQt::CustomInterfaces;
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
@@ -234,8 +233,7 @@ public:
         "Plus", "CreateTransmissionWorkspaceAuto",
         "ReflectometryReductionOneAuto", "Stitch1DMany"};
 
-    EXPECT_CALL(mockDataProcessorView,
-                setGlobalOptions(stages, algorithms, _))
+    EXPECT_CALL(mockDataProcessorView, setGlobalOptions(stages, algorithms, _))
         .Times(Exactly(1));
     // Expect that the autocompletion hints are populated
     EXPECT_CALL(mockDataProcessorView, setOptionsHintStrategy(_, 8))
@@ -1968,29 +1966,45 @@ public:
     TS_ASSERT(dynamic_cast<DataProcessorOpenTableCommand *>(commands[0].get()));
     TS_ASSERT(dynamic_cast<DataProcessorNewTableCommand *>(commands[1].get()));
     TS_ASSERT(dynamic_cast<DataProcessorSaveTableCommand *>(commands[2].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorSaveTableAsCommand *>(commands[3].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorSaveTableAsCommand *>(commands[3].get()));
     TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[4].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorImportTableCommand *>(commands[5].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorExportTableCommand *>(commands[6].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorImportTableCommand *>(commands[5].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorExportTableCommand *>(commands[6].get()));
     TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[7].get()));
     TS_ASSERT(dynamic_cast<DataProcessorOptionsCommand *>(commands[8].get()));
     TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[9].get()));
     TS_ASSERT(dynamic_cast<DataProcessorProcessCommand *>(commands[10].get()));
     TS_ASSERT(dynamic_cast<DataProcessorExpandCommand *>(commands[11].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[12].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorSeparatorCommand *>(commands[12].get()));
     TS_ASSERT(dynamic_cast<DataProcessorPlotRowCommand *>(commands[13].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorPlotGroupCommand *>(commands[14].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[15].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorAppendRowCommand *>(commands[16].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorPrependRowCommand *>(commands[17].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[18].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorGroupRowsCommand *>(commands[19].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorCopySelectedCommand *>(commands[20].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorCutSelectedCommand *>(commands[21].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorPasteSelectedCommand *>(commands[22].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorClearSelectedCommand *>(commands[23].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorSeparatorCommand *>(commands[24].get()));
-    TS_ASSERT(dynamic_cast<DataProcessorDeleteRowCommand *>(commands[25].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorPlotGroupCommand *>(commands[14].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorSeparatorCommand *>(commands[15].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorAppendRowCommand *>(commands[16].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorPrependRowCommand *>(commands[17].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorSeparatorCommand *>(commands[18].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorGroupRowsCommand *>(commands[19].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorCopySelectedCommand *>(commands[20].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorCutSelectedCommand *>(commands[21].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorPasteSelectedCommand *>(commands[22].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorClearSelectedCommand *>(commands[23].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorSeparatorCommand *>(commands[24].get()));
+    TS_ASSERT(
+        dynamic_cast<DataProcessorDeleteRowCommand *>(commands[25].get()));
   }
 };
 
diff --git a/MantidQt/CustomInterfaces/test/IO_MuonGroupingTest.h b/MantidQt/CustomInterfaces/test/IO_MuonGroupingTest.h
index cfee1e560922fdfca5b33f48b1a84a6d529dfe18..81d872c30d1ffc59f5317dd353f2d10b51a44896 100644
--- a/MantidQt/CustomInterfaces/test/IO_MuonGroupingTest.h
+++ b/MantidQt/CustomInterfaces/test/IO_MuonGroupingTest.h
@@ -15,34 +15,33 @@
 using namespace Mantid::API;
 using namespace MantidQt::CustomInterfaces::Muon;
 
-class IO_MuonGroupingTest : public CxxTest::TestSuite
-{
+class IO_MuonGroupingTest : public CxxTest::TestSuite {
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static IO_MuonGroupingTest *createSuite() { return new IO_MuonGroupingTest(); }
-  static void destroySuite( IO_MuonGroupingTest *suite ) { delete suite; }
+  static IO_MuonGroupingTest *createSuite() {
+    return new IO_MuonGroupingTest();
+  }
+  static void destroySuite(IO_MuonGroupingTest *suite) { delete suite; }
 
   /// Constructor
-  IO_MuonGroupingTest()
-  {
+  IO_MuonGroupingTest() {
     using Mantid::Kernel::ConfigService;
 
     auto dataPaths = ConfigService::Instance().getDataSearchDirs();
 
     // Find the path of AutoTestData
-    for(auto it = dataPaths.begin(); it != dataPaths.end(); ++it)
-    {
+    for (auto it = dataPaths.begin(); it != dataPaths.end(); ++it) {
       Poco::Path path(*it);
 
-      if(path.directory(path.depth() - 1) == "UnitTest")
-      {
+      if (path.directory(path.depth() - 1) == "UnitTest") {
         m_testDataDir = *it;
         break;
       }
     }
 
-    TSM_ASSERT("Unable to find UnitTest data directory", !m_testDataDir.empty());
+    TSM_ASSERT("Unable to find UnitTest data directory",
+               !m_testDataDir.empty());
 
     m_tmpDir = ConfigService::Instance().getTempDir();
 
@@ -50,8 +49,7 @@ public:
     FrameworkManager::Instance();
   }
 
-  void test_saveGroupingToXML()
-  {
+  void test_saveGroupingToXML() {
     Grouping g, lg;
 
     std::string tmpFile = m_tmpDir + "tmp_MUSRGrouping.xml";
@@ -97,17 +95,14 @@ private:
   std::string m_testDataDir;
   std::string m_tmpDir;
 
-  std::set<int> setFromRange(int from, int to)
-  {
+  std::set<int> setFromRange(int from, int to) {
     std::set<int> result;
 
-    for(int i = from; i <= to; i++)
+    for (int i = from; i <= to; i++)
       result.insert(i);
-    
+
     return result;
   }
-
 };
 
-
 #endif /* MANTID_CUSTOMINTERFACES_IO_MUONGROUPINGTEST_H_ */
diff --git a/MantidQt/CustomInterfaces/test/MeasurementItemTest.h b/MantidQt/CustomInterfaces/test/MeasurementItemTest.h
index c9e3d01c241970841a71e0d2e9d4c78c38607494..efd737ba924095c7387d9f3f3efb3f25822e278e 100644
--- a/MantidQt/CustomInterfaces/test/MeasurementItemTest.h
+++ b/MantidQt/CustomInterfaces/test/MeasurementItemTest.h
@@ -11,7 +11,9 @@ class MeasurementItemTest : public CxxTest::TestSuite {
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static MeasurementItemTest *createSuite() { return new MeasurementItemTest(); }
+  static MeasurementItemTest *createSuite() {
+    return new MeasurementItemTest();
+  }
   static void destroySuite(MeasurementItemTest *suite) { delete suite; }
 
   void test_invalid_construction_via_constructional_method() {
@@ -29,8 +31,8 @@ public:
     const double angle = 0.1;
     const std::string run = "123";
 
-    MeasurementItem measurement(measurementId, measurementSubId, measurementLabel,
-                            measurementType, angle, run);
+    MeasurementItem measurement(measurementId, measurementSubId,
+                                measurementLabel, measurementType, angle, run);
 
     TS_ASSERT(measurement.isUseable());
     TS_ASSERT_EQUALS(measurementId, measurement.id());
@@ -44,7 +46,7 @@ public:
   void test_invalid_construction_when_measurementId_empty() {
 
     MeasurementItem measurement("", "measurementSubId", "measurementLabel",
-                            "measurementType", 0.1, "111");
+                                "measurementType", 0.1, "111");
 
     TS_ASSERT(!measurement.isUseable());
   }
@@ -52,7 +54,7 @@ public:
   void test_invalid_construction_when_measurementSubId_empty() {
 
     MeasurementItem measurement("measurementId", "", "measurementLabel",
-                            "measurementType", 0.1, "111");
+                                "measurementType", 0.1, "111");
 
     TS_ASSERT(!measurement.isUseable());
   }
@@ -60,16 +62,16 @@ public:
   void test_valid_construction_when_label_empty() {
 
     MeasurementItem measurement("measurementId", "measurementSubId", "",
-                            "measurementType", 0.1, "111");
+                                "measurementType", 0.1, "111");
 
     TSM_ASSERT("Empty labels are not terminal", measurement.isUseable());
   }
 
   void test_valid_construction_when_type_empty() {
     MeasurementItem measurement("measurementId", "measurementSubId",
-                            "measurementLabel", "", 0.1, "111");
+                                "measurementLabel", "", 0.1, "111");
 
-    TSM_ASSERT("Empty type info is not terminal",measurement.isUseable());
+    TSM_ASSERT("Empty type info is not terminal", measurement.isUseable());
   }
 };
 
diff --git a/MantidQt/CustomInterfaces/test/ParseKeyValueStringTest.h b/MantidQt/CustomInterfaces/test/ParseKeyValueStringTest.h
index bab4ccf555535117bc2a8846757bbbd1f37db11c..04c330bb75d84cc8c3a3af0779c33cbfeafa70ff 100644
--- a/MantidQt/CustomInterfaces/test/ParseKeyValueStringTest.h
+++ b/MantidQt/CustomInterfaces/test/ParseKeyValueStringTest.h
@@ -7,11 +7,10 @@
 class ParseKeyValueStringTest : public CxxTest::TestSuite {
 
 public:
-
   void testParseKeyValueString() {
     std::map<std::string, std::string> kvp =
-    MantidQt::CustomInterfaces::parseKeyValueString(
-        "a = 1,b=2.0, c=3, d='1,2,3',e=\"4,5,6\",f=1+1=2, g = '\\''");
+        MantidQt::CustomInterfaces::parseKeyValueString(
+            "a = 1,b=2.0, c=3, d='1,2,3',e=\"4,5,6\",f=1+1=2, g = '\\''");
 
     TS_ASSERT_EQUALS(kvp["a"], "1");
     TS_ASSERT_EQUALS(kvp["b"], "2.0");
@@ -22,19 +21,19 @@ public:
     TS_ASSERT_EQUALS(kvp["g"], "'");
 
     TS_ASSERT_THROWS(
-      MantidQt::CustomInterfaces::parseKeyValueString("a = 1, b = 2, c = 3,"),
-      std::runtime_error);
-    TS_ASSERT_THROWS(
-      MantidQt::CustomInterfaces::parseKeyValueString("a = 1, b = 2, c = 3,d"),
-      std::runtime_error);
-    TS_ASSERT_THROWS(MantidQt::CustomInterfaces::parseKeyValueString(",a = 1"),
+        MantidQt::CustomInterfaces::parseKeyValueString("a = 1, b = 2, c = 3,"),
+        std::runtime_error);
+    TS_ASSERT_THROWS(MantidQt::CustomInterfaces::parseKeyValueString(
+                         "a = 1, b = 2, c = 3,d"),
                      std::runtime_error);
-    TS_ASSERT_THROWS(MantidQt::CustomInterfaces::parseKeyValueString(",a = 1 = 2,="),
+    TS_ASSERT_THROWS(MantidQt::CustomInterfaces::parseKeyValueString(",a = 1"),
                      std::runtime_error);
+    TS_ASSERT_THROWS(
+        MantidQt::CustomInterfaces::parseKeyValueString(",a = 1 = 2,="),
+        std::runtime_error);
     TS_ASSERT_THROWS(MantidQt::CustomInterfaces::parseKeyValueString("=,=,="),
                      std::runtime_error);
   }
-
 };
 
-#endif //MANTID_CUSTOMINTERFACES_PARSEKEYVALUESTRINGTEST_H
+#endif // MANTID_CUSTOMINTERFACES_PARSEKEYVALUESTRINGTEST_H
diff --git a/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h b/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h
index 775ef03668e425fc911208a1ec463e131f7caf4f..ccacfc0a4fcc3b2bbec2b33eeb08b38c24b30936 100644
--- a/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h
+++ b/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h
@@ -8,93 +8,96 @@
 
 using namespace MantidQt::CustomInterfaces;
 
-class UserInputValidatorTest : public CxxTest::TestSuite
-{
+class UserInputValidatorTest : public CxxTest::TestSuite {
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static UserInputValidatorTest *createSuite() { return new UserInputValidatorTest(); }
-  static void destroySuite( UserInputValidatorTest *suite ) { delete suite; }
-
-  UserInputValidatorTest()
-  {
+  static UserInputValidatorTest *createSuite() {
+    return new UserInputValidatorTest();
   }
+  static void destroySuite(UserInputValidatorTest *suite) { delete suite; }
+
+  UserInputValidatorTest() {}
 
-  void test_validRebin()
-  {
+  void test_validRebin() {
     UserInputValidator uiv;
     TS_ASSERT(uiv.checkBins(0.6, 0.1, 1.8));
     TS_ASSERT(uiv.isAllInputValid());
   }
 
-  void test_negativeWidthRebin()
-  {
+  void test_negativeWidthRebin() {
     UserInputValidator uiv;
     TS_ASSERT(!uiv.checkBins(0.6, -0.1, 1.8));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be a positive value.");
+    TS_ASSERT_EQUALS(
+        uiv.generateErrorMessage(),
+        "Please correct the following:\nBin width must be a positive value.");
   }
 
-  void test_zeroWidthRebin()
-  {
+  void test_zeroWidthRebin() {
     UserInputValidator uiv;
     TS_ASSERT(!uiv.checkBins(0.6, 0.0, 1.8));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be non-zero.");
+    TS_ASSERT_EQUALS(
+        uiv.generateErrorMessage(),
+        "Please correct the following:\nBin width must be non-zero.");
   }
 
-  void test_zeroRangeRebin()
-  {
+  void test_zeroRangeRebin() {
     UserInputValidator uiv;
     TS_ASSERT(!uiv.checkBins(0.6, 0.1, 0.6));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBinning ranges must be non-zero.");
+    TS_ASSERT_EQUALS(
+        uiv.generateErrorMessage(),
+        "Please correct the following:\nBinning ranges must be non-zero.");
   }
 
-  void test_reverseRangeRebin()
-  {
+  void test_reverseRangeRebin() {
     UserInputValidator uiv;
     TS_ASSERT(!uiv.checkBins(1.8, 0.1, 0.6));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of a binning range must be less than the end.");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(),
+                     "Please correct the following:\nThe start of a binning "
+                     "range must be less than the end.");
   }
 
-  void test_binsNotFactorsRebin()
-  {
+  void test_binsNotFactorsRebin() {
     UserInputValidator uiv;
     TS_ASSERT(!uiv.checkBins(0.0, 0.2, 0.7));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must allow for even splitting of the range.");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(),
+                     "Please correct the following:\nBin width must allow for "
+                     "even splitting of the range.");
   }
 
-  void test_validRange()
-  {
+  void test_validRange() {
     UserInputValidator uiv;
     std::pair<double, double> range(1, 5);
     TS_ASSERT(uiv.checkValidRange("test range", range));
     TS_ASSERT(uiv.isAllInputValid());
   }
 
-  void test_invalidRangeReversed()
-  {
+  void test_invalidRangeReversed() {
     UserInputValidator uiv;
     std::pair<double, double> range(10, 5);
     TS_ASSERT(!uiv.checkValidRange("test range", range));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of test range must be less than the end.");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(),
+                     "Please correct the following:\nThe start of test range "
+                     "must be less than the end.");
   }
 
-  void test_invalidRangeZeroWidth()
-  {
+  void test_invalidRangeZeroWidth() {
     UserInputValidator uiv;
     std::pair<double, double> range(5, 5);
     TS_ASSERT(!uiv.checkValidRange("test range", range));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\ntest range must have a non-zero width.");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the "
+                                                 "following:\ntest range must "
+                                                 "have a non-zero width.");
   }
 
-  void test_nonOverlappingRanges()
-  {
+  void test_nonOverlappingRanges() {
     UserInputValidator uiv;
     std::pair<double, double> rangeA(1, 5);
     std::pair<double, double> rangeB(6, 10);
@@ -102,35 +105,37 @@ public:
     TS_ASSERT(uiv.isAllInputValid());
   }
 
-  void test_overlappingRanges()
-  {
+  void test_overlappingRanges() {
     UserInputValidator uiv;
     std::pair<double, double> rangeA(1, 5);
     std::pair<double, double> rangeB(3, 8);
     TS_ASSERT(!uiv.checkRangesDontOverlap(rangeA, rangeB));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe ranges must not overlap: [1,5], [3,8].");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the "
+                                                 "following:\nThe ranges must "
+                                                 "not overlap: [1,5], [3,8].");
   }
 
-  void test_enclosedRange()
-  {
+  void test_enclosedRange() {
     UserInputValidator uiv;
     std::pair<double, double> outer(1, 10);
     std::pair<double, double> inner(3, 8);
-    TS_ASSERT(uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner));
+    TS_ASSERT(
+        uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner));
     TS_ASSERT(uiv.isAllInputValid());
   }
 
-  void test_nonEnclosedRange()
-  {
+  void test_nonEnclosedRange() {
     UserInputValidator uiv;
     std::pair<double, double> outer(1, 10);
     std::pair<double, double> inner(3, 15);
-    TS_ASSERT(!uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner));
+    TS_ASSERT(
+        !uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner));
     TS_ASSERT(!uiv.isAllInputValid());
-    TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nouter range must completely enclose inner range.");
+    TS_ASSERT_EQUALS(uiv.generateErrorMessage(),
+                     "Please correct the following:\nouter range must "
+                     "completely enclose inner range.");
   }
-
 };
 
 #endif
diff --git a/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/DesignerPlugin.h b/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/DesignerPlugin.h
index 1c3b7837b2d73f138d5e2569b8611d5e3493ea5b..3478d0b60bad050b0e3f39249e052891d312e153 100644
--- a/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/DesignerPlugin.h
+++ b/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/DesignerPlugin.h
@@ -3,13 +3,14 @@
 
 #include <QDesignerCustomWidgetInterface>
 
-/** 
+/**
 The DesignerPlugin creates a Qt designer plugin of the AlgorithmSelectorWidget.
 
 @author Martyn Gigg, Tessella plc
 @date 03/08/2009
 
-Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -26,10 +27,9 @@ GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-File change history is stored at: <https://github.com/mantidproject/mantid>    
+File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-class DesignerPlugin : public QObject, public QDesignerCustomWidgetInterface
-{
+class DesignerPlugin : public QObject, public QDesignerCustomWidgetInterface {
   Q_OBJECT
   Q_INTERFACES(QDesignerCustomWidgetInterface)
 
@@ -68,7 +68,7 @@ public:
 private:
   std::string getShortName() const;
 
-  /// Are we initialized? 
+  /// Are we initialized?
   bool m_initialized;
 };
 
diff --git a/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/PluginCollectionInterface.h b/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/PluginCollectionInterface.h
index 0856b0c5cb2a8af5c235894bbf2d52d2beeeb802..75fb028caa96a81916ddf0e67063d73328730fa8 100644
--- a/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/PluginCollectionInterface.h
+++ b/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/PluginCollectionInterface.h
@@ -23,14 +23,16 @@
 #include "MantidQtMantidWidgets/PreviewPlot.h"
 #include "MantidQtMantidWidgets/DisplayCurveFit.h"
 
-/** 
-The PluginCollectionInterface implements the interface for the plugin library and holds a 
+/**
+The PluginCollectionInterface implements the interface for the plugin library
+and holds a
 list of plugins defined by the library.
 
 @author Martyn Gigg, Tessella plc
 @date 10/08/2009
 
-Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
@@ -47,10 +49,11 @@ GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-File change history is stored at: <https://github.com/mantidproject/mantid>    
+File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-class PluginCollectionInterface : public QObject, public QDesignerCustomWidgetCollectionInterface
-{
+class PluginCollectionInterface
+    : public QObject,
+      public QDesignerCustomWidgetCollectionInterface {
   Q_OBJECT
   Q_INTERFACES(QDesignerCustomWidgetCollectionInterface)
 
@@ -58,14 +61,12 @@ public:
   /// Default constructor
   PluginCollectionInterface(QObject *parent = 0);
   /// Returns a list of the custom widgets within this library
-  virtual QList<QDesignerCustomWidgetInterface*> customWidgets() const;
+  virtual QList<QDesignerCustomWidgetInterface *> customWidgets() const;
 
 private:
-  QList<QDesignerCustomWidgetInterface*> m_widgets;
+  QList<QDesignerCustomWidgetInterface *> m_widgets;
 };
 
-
-
 //==============================================================================
 /** Macro to REALLY quickly declare a plugin for
  * a widget in MantidWidgets
@@ -74,93 +75,83 @@ private:
  * @param WidgetClass :: fully-qualified name of the widget class
  * @param ToolTip :: a string with the tooltip
  */
-#define DECLARE_WIDGET_PLUGIN(PluginClass, WidgetClass, ToolTip) \
-class PluginClass : public DesignerPlugin { \
-public: \
-  PluginClass(QObject * parent) : DesignerPlugin(parent) {} \
-  QWidget *createWidget(QWidget *parent) \
-  { return new WidgetClass(parent); } \
-  QString name() const \
-  { return #WidgetClass; } \
-  QString toolTip() const \
-  { return ToolTip; } \
-};
-
+#define DECLARE_WIDGET_PLUGIN(PluginClass, WidgetClass, ToolTip)               \
+  class PluginClass : public DesignerPlugin {                                  \
+  public:                                                                      \
+    PluginClass(QObject *parent) : DesignerPlugin(parent) {}                   \
+    QWidget *createWidget(QWidget *parent) { return new WidgetClass(parent); } \
+    QString name() const { return #WidgetClass; }                              \
+    QString toolTip() const { return ToolTip; }                                \
+  };
 
 //==============================================================================
 // Declare plugins for several types of widgets in MantidWidgets
 // REMEMBER TO ADD THESE TO PluginCollectionInterface.cpp -> customWidgets
 //==============================================================================
 DECLARE_WIDGET_PLUGIN(AlgorithmSelectorWidgetPlugin,
-    MantidQt::MantidWidgets::AlgorithmSelectorWidget,
-    "Widget for picking algorithms");
+                      MantidQt::MantidWidgets::AlgorithmSelectorWidget,
+                      "Widget for picking algorithms");
 
-DECLARE_WIDGET_PLUGIN(ScriptEditorPlugin,
-    ScriptEditor,
-    "Widget for editing python script");
+DECLARE_WIDGET_PLUGIN(ScriptEditorPlugin, ScriptEditor,
+                      "Widget for editing python script");
 
-DECLARE_WIDGET_PLUGIN(FileFinderPlugin,
-    MantidQt::MantidWidgets::MWRunFiles,
-    "Searches for the given files within the paths defined by\nMantid's datasearch.directories property");
+DECLARE_WIDGET_PLUGIN(FileFinderPlugin, MantidQt::MantidWidgets::MWRunFiles,
+                      "Searches for the given files within the paths defined "
+                      "by\nMantid's datasearch.directories property");
 
 DECLARE_WIDGET_PLUGIN(InstrumentSelectorPlugin,
-    MantidQt::MantidWidgets::InstrumentSelector,
-    "Sets the current instrument within Mantid");
+                      MantidQt::MantidWidgets::InstrumentSelector,
+                      "Sets the current instrument within Mantid");
 
 DECLARE_WIDGET_PLUGIN(MuonFitBrowserPlugin,
-    MantidQt::MantidWidgets::MuonFitPropertyBrowser,
-    "The menu for fitting functions within Muon Analysis");
+                      MantidQt::MantidWidgets::MuonFitPropertyBrowser,
+                      "The menu for fitting functions within Muon Analysis");
 
 DECLARE_WIDGET_PLUGIN(FitBrowserPlugin,
-    MantidQt::MantidWidgets::FitPropertyBrowser,
-    "The menu for fitting functions");
+                      MantidQt::MantidWidgets::FitPropertyBrowser,
+                      "The menu for fitting functions");
 
 DECLARE_WIDGET_PLUGIN(WorkspaceSelectorPlugin,
-    MantidQt::MantidWidgets::WorkspaceSelector,
-    "Select a workspace for use in this operation");
+                      MantidQt::MantidWidgets::WorkspaceSelector,
+                      "Select a workspace for use in this operation");
 
 DECLARE_WIDGET_PLUGIN(ColorBarWidgetPlugin,
-    MantidQt::MantidWidgets::ColorBarWidget,
-    "Shows a color scale and allow user to change it");
+                      MantidQt::MantidWidgets::ColorBarWidget,
+                      "Shows a color scale and allow user to change it");
 
-DECLARE_WIDGET_PLUGIN(SliceViewerPlugin,
-    MantidQt::SliceViewer::SliceViewer,
-    "Shows 2D slices of MDWorkspaces");
+DECLARE_WIDGET_PLUGIN(SliceViewerPlugin, MantidQt::SliceViewer::SliceViewer,
+                      "Shows 2D slices of MDWorkspaces");
 
-DECLARE_WIDGET_PLUGIN(LineViewerPlugin,
-    MantidQt::SliceViewer::LineViewer,
-    "Shows 1D lines selected in a LineViewer");
+DECLARE_WIDGET_PLUGIN(LineViewerPlugin, MantidQt::SliceViewer::LineViewer,
+                      "Shows 1D lines selected in a LineViewer");
 
-DECLARE_WIDGET_PLUGIN(SafeQwtPlotPlugin,
-    MantidQt::MantidWidgets::SafeQwtPlot,
-    "Version of QwtPlot with workspace-level thread safety");
+DECLARE_WIDGET_PLUGIN(SafeQwtPlotPlugin, MantidQt::MantidWidgets::SafeQwtPlot,
+                      "Version of QwtPlot with workspace-level thread safety");
 
-DECLARE_WIDGET_PLUGIN(MWViewPlugin,
-    MantidQt::MantidWidgets::MWView,
-    "2D view of a MatrixWorkspace");
+DECLARE_WIDGET_PLUGIN(MWViewPlugin, MantidQt::MantidWidgets::MWView,
+                      "2D view of a MatrixWorkspace");
 
 DECLARE_WIDGET_PLUGIN(AlgorithmPropertiesWidgetPlugin,
-    MantidQt::API::AlgorithmPropertiesWidget,
-    "List of algorithm properties");
+                      MantidQt::API::AlgorithmPropertiesWidget,
+                      "List of algorithm properties");
 
-DECLARE_WIDGET_PLUGIN(ProcessingAlgoWidgetPlugin,
-    MantidQt::MantidWidgets::ProcessingAlgoWidget,
+DECLARE_WIDGET_PLUGIN(
+    ProcessingAlgoWidgetPlugin, MantidQt::MantidWidgets::ProcessingAlgoWidget,
     "Choose an algorithm or write a script as a processing step");
 
 DECLARE_WIDGET_PLUGIN(MessageDisplayPlugin,
-    MantidQt::MantidWidgets::MessageDisplay,
-    "Display messages with various priorities, optionally connecting to the logging framework");
+                      MantidQt::MantidWidgets::MessageDisplay,
+                      "Display messages with various priorities, optionally "
+                      "connecting to the logging framework");
 
-DECLARE_WIDGET_PLUGIN(DataSelectorPlugin,
-    MantidQt::MantidWidgets::DataSelector,
-    "Choose a file path or workspace to work with");
+DECLARE_WIDGET_PLUGIN(DataSelectorPlugin, MantidQt::MantidWidgets::DataSelector,
+                      "Choose a file path or workspace to work with");
 
-DECLARE_WIDGET_PLUGIN(PreviewPlotPlugin,
-    MantidQt::MantidWidgets::PreviewPlot,
-    "Curve plots for workspace spectra");
+DECLARE_WIDGET_PLUGIN(PreviewPlotPlugin, MantidQt::MantidWidgets::PreviewPlot,
+                      "Curve plots for workspace spectra");
 
 DECLARE_WIDGET_PLUGIN(DisplayCurveFitPlugin,
-    MantidQt::MantidWidgets::DisplayCurveFit,
-    "Curve plots for workspace spectra");
+                      MantidQt::MantidWidgets::DisplayCurveFit,
+                      "Curve plots for workspace spectra");
 
 #endif
diff --git a/MantidQt/DesignerPlugins/src/DesignerPlugin.cpp b/MantidQt/DesignerPlugins/src/DesignerPlugin.cpp
index 4a15d5122fd5fab26b843c92c5c4965dd013f987..67a2b171d61642f3f47ac8202a0971cc00ae1c11 100644
--- a/MantidQt/DesignerPlugins/src/DesignerPlugin.cpp
+++ b/MantidQt/DesignerPlugins/src/DesignerPlugin.cpp
@@ -10,19 +10,16 @@ using namespace MantidQt::MantidWidgets;
  * Default constructor
  * @param parent :: The parent of the plugin (default: NULL)
  */
-DesignerPlugin::DesignerPlugin(QObject *parent) : QObject(parent), m_initialized(false)
-{
-}
+DesignerPlugin::DesignerPlugin(QObject *parent)
+    : QObject(parent), m_initialized(false) {}
 
 /**
  * Initialize the plugin
  * @param formEditor :: A pointer to the interface that will control this plugin
  */
-void DesignerPlugin::initialize(QDesignerFormEditorInterface * formEditor)
-{
-  (void) formEditor;
-  if (m_initialized)
-  {
+void DesignerPlugin::initialize(QDesignerFormEditorInterface *formEditor) {
+  (void)formEditor;
+  if (m_initialized) {
     return;
   }
   m_initialized = true;
@@ -32,64 +29,46 @@ void DesignerPlugin::initialize(QDesignerFormEditorInterface * formEditor)
 * Returns whether the plugin initialized or not
 * @returns True if initialize() has been called, false otherwise
 */
-bool DesignerPlugin::isInitialized() const
-{
-  return m_initialized;
-}
+bool DesignerPlugin::isInitialized() const { return m_initialized; }
 
 /**
  * Returns whether this widget can contain other widgets
- * @returns True if other widgets can be placed within this widget, false otherwise
+ * @returns True if other widgets can be placed within this widget, false
+ * otherwise
  */
-bool DesignerPlugin::isContainer() const
-{
-  return false;
-}
+bool DesignerPlugin::isContainer() const { return false; }
 
 /**
  * Returns the group within the designer that this plugin should be placed
- * @returns The name of the group of widgets in the designer 
+ * @returns The name of the group of widgets in the designer
  */
-QString DesignerPlugin::group() const
-{
-  return "MantidWidgets";
-}
+QString DesignerPlugin::group() const { return "MantidWidgets"; }
 
 /**
  * Returns the icon to display in the designer
  * @returns An icon that is used within the designer
  */
-QIcon DesignerPlugin::icon() const
-{
-  return QIcon();
-}
+QIcon DesignerPlugin::icon() const { return QIcon(); }
 
 /**
  * The tooltip for the widget
  * @returns A string containing the tooltip for this widget
  */
-QString DesignerPlugin::toolTip() const
-{
+QString DesignerPlugin::toolTip() const {
   return "Creates a widget of type " + this->name();
 }
 
 /** A short description of the widget
  * @returns A string containing a short description of the widget
  */
-QString DesignerPlugin::whatsThis() const
-{  
-  return this->toolTip();
-}
-
+QString DesignerPlugin::whatsThis() const { return this->toolTip(); }
 
 /** @return the name of the widget without the namespace */
-std::string DesignerPlugin::getShortName() const
-{
+std::string DesignerPlugin::getShortName() const {
   std::string name = this->name().toStdString();
   size_t n = name.rfind(':');
-  if (n != std::string::npos)
-  {
-    name = name.substr(n+1, name.size() - n);
+  if (n != std::string::npos) {
+    name = name.substr(n + 1, name.size() - n);
   }
   return name;
 }
@@ -98,23 +77,22 @@ std::string DesignerPlugin::getShortName() const
  * The include file to use when generating the header file
  * @returns A string containing the path to the widget's header file
  */
-QString DesignerPlugin::includeFile() const
-{
+QString DesignerPlugin::includeFile() const {
   std::string thisNamespace = "MantidWidgets";
   std::string name = this->name().toStdString();
   size_t n = name.rfind("::");
   // Find the namespace
-  if (n != std::string::npos)
-  {
+  if (n != std::string::npos) {
     name = name.substr(0, n);
     size_t n = name.rfind("::");
     if (n == std::string::npos)
       n = 0;
     else
       n = n + 2;
-    thisNamespace = name.substr(n, name.size()-n);
+    thisNamespace = name.substr(n, name.size() - n);
   }
-  std::string include = "MantidQt" + thisNamespace + "/" + this->getShortName() + ".h";
+  std::string include =
+      "MantidQt" + thisNamespace + "/" + this->getShortName() + ".h";
   return QString::fromStdString(include);
 }
 
@@ -122,17 +100,13 @@ QString DesignerPlugin::includeFile() const
  * Returns the XML used to define the widget in the designer
  * @returns A string containing the XML for the widget
  */
-QString DesignerPlugin::domXml() const
-{
+QString DesignerPlugin::domXml() const {
   // Default name of a widget = class name, with first letter lower case.
   std::string name = this->getShortName();
   name[0] = static_cast<char>(tolower(static_cast<int>(name[0])));
 
-  return QString::fromStdString(
-      "<widget class=\""
-      + this->name().toStdString()
-      + "\" name=\""
-      + name +
-      "\">\n"
-    "</widget>\n");
+  return QString::fromStdString("<widget class=\"" +
+                                this->name().toStdString() + "\" name=\"" +
+                                name + "\">\n"
+                                       "</widget>\n");
 }
diff --git a/MantidQt/DesignerPlugins/src/PluginCollectionInterface.cpp b/MantidQt/DesignerPlugins/src/PluginCollectionInterface.cpp
index b45d4f5a2af59e1154453b4b8293dbdcca09301d..f18e425c65129ef00e7478f84821921533d68810 100644
--- a/MantidQt/DesignerPlugins/src/PluginCollectionInterface.cpp
+++ b/MantidQt/DesignerPlugins/src/PluginCollectionInterface.cpp
@@ -3,15 +3,14 @@
 //-------------------------------------------------------
 #include "MantidQtDesignerPlugins/PluginCollectionInterface.h"
 
-
 Q_EXPORT_PLUGIN2(LIBRARY_NAME, PluginCollectionInterface)
 
 /**
  * Default constructor
  * @param parent :: The parent widget
  */
-PluginCollectionInterface::PluginCollectionInterface(QObject *parent) : QObject(parent)
-{
+PluginCollectionInterface::PluginCollectionInterface(QObject *parent)
+    : QObject(parent) {
   m_widgets.append(new FileFinderPlugin(this));
   m_widgets.append(new InstrumentSelectorPlugin(this));
   m_widgets.append(new WorkspaceSelectorPlugin(this));
@@ -36,7 +35,7 @@ PluginCollectionInterface::PluginCollectionInterface(QObject *parent) : QObject(
  * Return the custom widgets exported by this library
  * @returns :: a list of custom widget interfaces contained within this library
  */
-QList<QDesignerCustomWidgetInterface*> PluginCollectionInterface::customWidgets() const
-{
+QList<QDesignerCustomWidgetInterface *>
+PluginCollectionInterface::customWidgets() const {
   return m_widgets;
 }
diff --git a/MantidQt/Factory/inc/MantidQtFactory/DllOption.h b/MantidQt/Factory/inc/MantidQtFactory/DllOption.h
index c6acd7e941ae3500a0b19db42b1fd3f6dbed468e..07e8f120ba4ae7f45e5e1ea38ae0bdc44b5627d0 100644
--- a/MantidQt/Factory/inc/MantidQtFactory/DllOption.h
+++ b/MantidQt/Factory/inc/MantidQtFactory/DllOption.h
@@ -9,4 +9,4 @@
 #define EXPORT_OPT_MANTIDQT_FACTORY DLLImport
 #endif /* IN_MANTIDQT_API */
 
-#endif //MANTIDQT_FACTORY_DLLOPTION_H_
+#endif // MANTIDQT_FACTORY_DLLOPTION_H_
diff --git a/MantidQt/Factory/inc/MantidQtFactory/WidgetFactory.h b/MantidQt/Factory/inc/MantidQtFactory/WidgetFactory.h
index 195435e5c2e9502905d4d0af3bb031c4768fccd5..f2cf079ae4f2b5fe98c641ad0f8533788393b01b 100644
--- a/MantidQt/Factory/inc/MantidQtFactory/WidgetFactory.h
+++ b/MantidQt/Factory/inc/MantidQtFactory/WidgetFactory.h
@@ -11,69 +11,66 @@
 #include <QtCore/QtCore>
 #include <QVector>
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    class SliceViewerWindow;
-  }
-namespace Factory
-{
-
-  /** Factory class that handles the creation
-   * of MantidQt widgets such as the SliceViewer.
-   * This allows both C++ and Python to create these widgets
-   * and both to handle them in a uniform way.
-    
-    @date 2011-12-15
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_FACTORY WidgetFactory : public QObject
-  {
-    Q_OBJECT
-  public:
-    static WidgetFactory* Instance();
-    ~WidgetFactory() override;
-
-    MantidQt::SliceViewer::SliceViewerWindow* createSliceViewerWindow(const QString& wsName, const QString& label);
-    MantidQt::SliceViewer::SliceViewerWindow* getSliceViewerWindow(const QString& wsName, const QString& label);
-    void closeAllSliceViewerWindows();
-    void closeSliceViewerWindow(SliceViewer::SliceViewerWindow* w);
-
-    MantidQt::SliceViewer::SliceViewer* createSliceViewer(const QString& wsName);
-
-  private:
-    WidgetFactory();
-
-  protected:
-    /// List of the open SliceViewerWindows
-    std::list<QPointer<MantidQt::SliceViewer::SliceViewerWindow> > m_windows;
-    /// Singleton instance
-    static WidgetFactory * m_pInstance;
-  };
-
-
+namespace MantidQt {
+namespace SliceViewer {
+class SliceViewerWindow;
+}
+namespace Factory {
+
+/** Factory class that handles the creation
+ * of MantidQt widgets such as the SliceViewer.
+ * This allows both C++ and Python to create these widgets
+ * and both to handle them in a uniform way.
+
+  @date 2011-12-15
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_FACTORY WidgetFactory : public QObject {
+  Q_OBJECT
+public:
+  static WidgetFactory *Instance();
+  ~WidgetFactory() override;
+
+  MantidQt::SliceViewer::SliceViewerWindow *
+  createSliceViewerWindow(const QString &wsName, const QString &label);
+  MantidQt::SliceViewer::SliceViewerWindow *
+  getSliceViewerWindow(const QString &wsName, const QString &label);
+  void closeAllSliceViewerWindows();
+  void closeSliceViewerWindow(SliceViewer::SliceViewerWindow *w);
+
+  MantidQt::SliceViewer::SliceViewer *createSliceViewer(const QString &wsName);
+
+private:
+  WidgetFactory();
+
+protected:
+  /// List of the open SliceViewerWindows
+  std::list<QPointer<MantidQt::SliceViewer::SliceViewerWindow>> m_windows;
+  /// Singleton instance
+  static WidgetFactory *m_pInstance;
+};
 
 } // namespace Factory
 } // namespace MantidQt
 
-#endif  /* MANTID_FACTORY_WIDGETFACTORY_H_ */
+#endif /* MANTID_FACTORY_WIDGETFACTORY_H_ */
diff --git a/MantidQt/Factory/src/WidgetFactory.cpp b/MantidQt/Factory/src/WidgetFactory.cpp
index 7fbf19d10ab14a8473ecf3628fda1cc0a43b2b11..9e9a6eda1e614a0ad8579756f0c20b8758b0b56b 100644
--- a/MantidQt/Factory/src/WidgetFactory.cpp
+++ b/MantidQt/Factory/src/WidgetFactory.cpp
@@ -5,140 +5,131 @@
 
 using namespace MantidQt::SliceViewer;
 
-namespace MantidQt
-{
-namespace Factory
-{
-
-  /// Initialize the instance to NULL
-  WidgetFactory* WidgetFactory::m_pInstance = NULL;
-
-  //----------------------------------------------------------------------------------------------
-  /** Private constructor. This is not accessible,
-   * use the Instance() method to access the singleton instance
-   * instead.
-   */
-  WidgetFactory::WidgetFactory()
-  {
-//    std::cout << "WidgetFactory constructor called" << std::endl;
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  WidgetFactory::~WidgetFactory()
-  {
-//    std::cout << "WidgetFactory destructor called" << std::endl;
-//    for (size_t i=0; i<m_windows.size(); i++)
-//      delete m_windows[i];
-//    m_windows.clear();
-  }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Retrieve the singleton instance of WidgetFactory */
-  WidgetFactory* WidgetFactory::Instance()
-  {
-    if (!m_pInstance)
-      m_pInstance = new WidgetFactory;
-
-    return m_pInstance;
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Create an instance of a SliceViewerWindow:
-   * a separate window containing a SliceViewer widget, to do 2D
-   * views of multidimensional workspace, as well as a
-   * LineViewer widget, to do 1D lines through the 2D slices.
-   *
-   * @param wsName :: name of the workspace to show
-   * @param label :: label for the window title
-   * @return the created SliceViewerWindow *
-   */
-  MantidQt::SliceViewer::SliceViewerWindow* WidgetFactory::createSliceViewerWindow(const QString& wsName,  const QString& label)
-  {
-    SliceViewerWindow * window = new SliceViewerWindow(wsName, label);
-    QPointer<MantidQt::SliceViewer::SliceViewerWindow> pWindow(window);
-
-    //Save in a list for later use
-    m_windows.push_back(pWindow);
-
-    return window;
-  }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Returns a previously-open instance of a SliceViewerWindow.
-   *
-   * @param wsName :: name of the workspace that was open
-   * @param label :: label for the window title
-   * @return the previously-created SliceViewerWindow *
-   * @throw std::runtime_error if no open windows match the parameters
-   */
-  MantidQt::SliceViewer::SliceViewerWindow* WidgetFactory::getSliceViewerWindow(const QString& wsName,  const QString& label)
-  {
-    for (auto it = m_windows.begin(); it != m_windows.end(); ++it)
-    {
-      QPointer<MantidQt::SliceViewer::SliceViewerWindow> window = *it;
-      if (window)
-      {
-        // Match the ws name and the label
-        if ((window->getSlicer()->getWorkspace()->getName() == wsName.toStdString())
-          && (window->getLabel() == label))
-          return window;
-      }
+namespace MantidQt {
+namespace Factory {
+
+/// Initialize the instance to NULL
+WidgetFactory *WidgetFactory::m_pInstance = NULL;
+
+//----------------------------------------------------------------------------------------------
+/** Private constructor. This is not accessible,
+ * use the Instance() method to access the singleton instance
+ * instead.
+ */
+WidgetFactory::WidgetFactory() {
+  //    std::cout << "WidgetFactory constructor called" << std::endl;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+WidgetFactory::~WidgetFactory() {
+  //    std::cout << "WidgetFactory destructor called" << std::endl;
+  //    for (size_t i=0; i<m_windows.size(); i++)
+  //      delete m_windows[i];
+  //    m_windows.clear();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Retrieve the singleton instance of WidgetFactory */
+WidgetFactory *WidgetFactory::Instance() {
+  if (!m_pInstance)
+    m_pInstance = new WidgetFactory;
+
+  return m_pInstance;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Create an instance of a SliceViewerWindow:
+ * a separate window containing a SliceViewer widget, to do 2D
+ * views of multidimensional workspace, as well as a
+ * LineViewer widget, to do 1D lines through the 2D slices.
+ *
+ * @param wsName :: name of the workspace to show
+ * @param label :: label for the window title
+ * @return the created SliceViewerWindow *
+ */
+MantidQt::SliceViewer::SliceViewerWindow *
+WidgetFactory::createSliceViewerWindow(const QString &wsName,
+                                       const QString &label) {
+  SliceViewerWindow *window = new SliceViewerWindow(wsName, label);
+  QPointer<MantidQt::SliceViewer::SliceViewerWindow> pWindow(window);
+
+  // Save in a list for later use
+  m_windows.push_back(pWindow);
+
+  return window;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Returns a previously-open instance of a SliceViewerWindow.
+ *
+ * @param wsName :: name of the workspace that was open
+ * @param label :: label for the window title
+ * @return the previously-created SliceViewerWindow *
+ * @throw std::runtime_error if no open windows match the parameters
+ */
+MantidQt::SliceViewer::SliceViewerWindow *
+WidgetFactory::getSliceViewerWindow(const QString &wsName,
+                                    const QString &label) {
+  for (auto it = m_windows.begin(); it != m_windows.end(); ++it) {
+    QPointer<MantidQt::SliceViewer::SliceViewerWindow> window = *it;
+    if (window) {
+      // Match the ws name and the label
+      if ((window->getSlicer()->getWorkspace()->getName() ==
+           wsName.toStdString()) &&
+          (window->getLabel() == label))
+        return window;
     }
-    throw std::runtime_error("No SliceViewer is open with the workspace '" +
-        wsName.toStdString() + "' and label '" + label.toStdString() + "'.");
   }
-
-  //----------------------------------------------------------------------------------------------
-  /** Closes every previously-open instance of a SliceViewerWindow.
-   */
-  void WidgetFactory::closeAllSliceViewerWindows()
-  {
-    for (auto it = m_windows.begin(); it != m_windows.end(); ++it)
-    {
-      QPointer<MantidQt::SliceViewer::SliceViewerWindow> window = *it;
-      if (window)
-        // Close with delete
-        window->close();
-    }
-    m_windows.clear();
+  throw std::runtime_error("No SliceViewer is open with the workspace '" +
+                           wsName.toStdString() + "' and label '" +
+                           label.toStdString() + "'.");
+}
+
+//----------------------------------------------------------------------------------------------
+/** Closes every previously-open instance of a SliceViewerWindow.
+ */
+void WidgetFactory::closeAllSliceViewerWindows() {
+  for (auto it = m_windows.begin(); it != m_windows.end(); ++it) {
+    QPointer<MantidQt::SliceViewer::SliceViewerWindow> window = *it;
+    if (window)
+      // Close with delete
+      window->close();
   }
-
-  /**
-   * Closes one instance
-   */
-  void WidgetFactory::closeSliceViewerWindow(SliceViewerWindow* w)
-  {
-    if (w)
-    {
-      w->close();
-      m_windows.remove(w);
-    }
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** 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.
-   *
-   * @param wsName :: name of the workspace to show. Optional, blank for no workspace.
-   * @return the created SliceViewer *
-   */
-  MantidQt::SliceViewer::SliceViewer* WidgetFactory::createSliceViewer(const QString& wsName)
-  {
-    MantidQt::SliceViewer::SliceViewer * slicer = new MantidQt::SliceViewer::SliceViewer();
-    //TODO: Save in a list ?
-    if (!wsName.isEmpty())
-      slicer->setWorkspace(wsName);
-    return slicer;
+  m_windows.clear();
+}
+
+/**
+ * Closes one instance
+ */
+void WidgetFactory::closeSliceViewerWindow(SliceViewerWindow *w) {
+  if (w) {
+    w->close();
+    m_windows.remove(w);
   }
-
-
+}
+
+//----------------------------------------------------------------------------------------------
+/** 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.
+ *
+ * @param wsName :: name of the workspace to show. Optional, blank for no
+ *workspace.
+ * @return the created SliceViewer *
+ */
+MantidQt::SliceViewer::SliceViewer *
+WidgetFactory::createSliceViewer(const QString &wsName) {
+  MantidQt::SliceViewer::SliceViewer *slicer =
+      new MantidQt::SliceViewer::SliceViewer();
+  // TODO: Save in a list ?
+  if (!wsName.isEmpty())
+    slicer->setWorkspace(wsName);
+  return slicer;
+}
 
 } // namespace Mantid
 } // namespace Factory
diff --git a/MantidQt/Factory/test/WidgetFactoryTest.h b/MantidQt/Factory/test/WidgetFactoryTest.h
index c71fdc3eb2f0b2adcb22296c1022943e81b60e05..61cdbdd84e35b764233503b268aee3d2c7dca4c4 100644
--- a/MantidQt/Factory/test/WidgetFactoryTest.h
+++ b/MantidQt/Factory/test/WidgetFactoryTest.h
@@ -11,21 +11,14 @@ using namespace Mantid;
 using namespace Mantid::Factory;
 using namespace Mantid::API;
 
-class WidgetFactoryTest : public CxxTest::TestSuite
-{
+class WidgetFactoryTest : public CxxTest::TestSuite {
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
   static WidgetFactoryTest *createSuite() { return new WidgetFactoryTest(); }
-  static void destroySuite( WidgetFactoryTest *suite ) { delete suite; }
-
-
-  void test_Something()
-  {
-  }
-
+  static void destroySuite(WidgetFactoryTest *suite) { delete suite; }
 
+  void test_Something() {}
 };
 
-
 #endif /* MANTID_FACTORY_WIDGETFACTORYTEST_H_ */
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmHintStrategy.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmHintStrategy.h
index bba238e518c38db8ef8aa176ebf284f2e9b97544..91ffbdcfbe95b0b90f892b5481a1616bb8263d23 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmHintStrategy.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmHintStrategy.h
@@ -6,61 +6,59 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /** AlgorithmHintStrategy : Produces hints using a given algorithm's properties.
-
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class AlgorithmHintStrategy : public HintStrategy
-    {
-    public:
-      AlgorithmHintStrategy(IAlgorithm_sptr algorithm, std::set<std::string> blacklist) : m_algorithm(algorithm), m_blacklist(blacklist)
-      {
-      }
-
-      ~AlgorithmHintStrategy() override{};
-
-      std::map<std::string, std::string> createHints() override {
-        std::map<std::string,std::string> hints;
-
-        auto properties = m_algorithm->getProperties();
-        for(auto it = properties.begin(); it != properties.end(); ++it)
-        {
-          const std::string name = (*it)->name();
-
-          //If it's not in the blacklist, add the property to our hints
-          if(m_blacklist.find(name) == m_blacklist.end())
-            hints[name] = (*it)->briefDocumentation();
-        }
-
-        return hints;
-      }
-    private:
-      IAlgorithm_sptr m_algorithm;
-      std::set<std::string> m_blacklist;
-    };
+namespace MantidQt {
+namespace MantidWidgets {
+/** AlgorithmHintStrategy : Produces hints using a given algorithm's properties.
+
+Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class AlgorithmHintStrategy : public HintStrategy {
+public:
+  AlgorithmHintStrategy(IAlgorithm_sptr algorithm,
+                        std::set<std::string> blacklist)
+      : m_algorithm(algorithm), m_blacklist(blacklist) {}
+
+  ~AlgorithmHintStrategy() override{};
+
+  std::map<std::string, std::string> createHints() override {
+    std::map<std::string, std::string> hints;
+
+    auto properties = m_algorithm->getProperties();
+    for (auto it = properties.begin(); it != properties.end(); ++it) {
+      const std::string name = (*it)->name();
+
+      // If it's not in the blacklist, add the property to our hints
+      if (m_blacklist.find(name) == m_blacklist.end())
+        hints[name] = (*it)->briefDocumentation();
+    }
+
+    return hints;
   }
+
+private:
+  IAlgorithm_sptr m_algorithm;
+  std::set<std::string> m_blacklist;
+};
+}
 }
 
 #endif /* MANTID_MANTIDWIDGETS_ALGORITHMHINTSTRATEGY_H */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmSelectorWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmSelectorWidget.h
index 08096cc64644d70452928cfe1dcdc88178cde3ce..1819566b0093af843d5aba33f039b7900f0b93cb 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmSelectorWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/AlgorithmSelectorWidget.h
@@ -12,145 +12,138 @@
 //------------------------------------------------------------------------------
 // Forward declaration
 //------------------------------------------------------------------------------
-namespace Mantid
-{
-namespace API
-{
-  struct Algorithm_descriptor;
+namespace Mantid {
+namespace API {
+struct Algorithm_descriptor;
 }
 }
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-
-  class AlgorithmTreeWidget;
-  class FindAlgComboBox;
-
-  /**
-   * Represents the algorithm selected by the user
-   * Contains name and version
-   */
-  struct SelectedAlgorithm {
-    QString name;
-    int version;
-    /// implicit conversion to QString
-    operator QString() { return name; }
-    /// constructor
-    SelectedAlgorithm(const QString nameIn, const int versionIn)
-        : name(nameIn), version(versionIn){};
-  };
-
-  //============================================================================
-  /** A widget consisting of a ComboBox and a TreeWidget
-   * to allow a user to select an algorithm either by category
-   * or by typing.
-
-    @date 2012-03-06
-    */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS AlgorithmSelectorWidget : public QWidget
-  {
-    Q_OBJECT
-    Q_PROPERTY(bool showExecuteButton READ showExecuteButton WRITE showExecuteButton)
-
-  public:
-    AlgorithmSelectorWidget(QWidget *parent);
-    ~AlgorithmSelectorWidget() override;
-    SelectedAlgorithm getSelectedAlgorithm();
-    void setSelectedAlgorithm(QString & algName);
-    bool showExecuteButton() const;
-    void showExecuteButton(const bool);
-
-  public slots:
-    void update();
-    void executeSelected();
-    void findAlgTextChanged(const QString& text);
-    void treeSelectionChanged();
+namespace MantidQt {
+namespace MantidWidgets {
+
+class AlgorithmTreeWidget;
+class FindAlgComboBox;
+
+/**
+ * Represents the algorithm selected by the user
+ * Contains name and version
+ */
+struct SelectedAlgorithm {
+  QString name;
+  int version;
+  /// implicit conversion to QString
+  operator QString() { return name; }
+  /// constructor
+  SelectedAlgorithm(const QString nameIn, const int versionIn)
+      : name(nameIn), version(versionIn){};
+};
+
+//============================================================================
+/** A widget consisting of a ComboBox and a TreeWidget
+ * to allow a user to select an algorithm either by category
+ * or by typing.
+
+  @date 2012-03-06
+  */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS AlgorithmSelectorWidget
+    : public QWidget {
+  Q_OBJECT
+  Q_PROPERTY(bool showExecuteButton READ showExecuteButton WRITE
+                 showExecuteButton)
+
+public:
+  AlgorithmSelectorWidget(QWidget *parent);
+  ~AlgorithmSelectorWidget() override;
+  SelectedAlgorithm getSelectedAlgorithm();
+  void setSelectedAlgorithm(QString &algName);
+  bool showExecuteButton() const;
+  void showExecuteButton(const bool);
+
+public slots:
+  void update();
+  void executeSelected();
+  void findAlgTextChanged(const QString &text);
+  void treeSelectionChanged();
+
+signals:
+  void algorithmFactoryUpdateReceived();
+  void executeAlgorithm(const QString &, int);
+  void algorithmSelectionChanged(const QString &, int);
+
+protected:
+  AlgorithmTreeWidget *m_tree;
+  FindAlgComboBox *m_findAlg;
+  QPushButton *m_execButton;
+
+private:
+  /// Callback for AlgorithmFactory update notifications
+  void handleAlgorithmFactoryUpdate(
+      Mantid::API::AlgorithmFactoryUpdateNotification_ptr);
+  /// Observes algorithm factory update notifications
+  Poco::NObserver<AlgorithmSelectorWidget,
+                  Mantid::API::AlgorithmFactoryUpdateNotification>
+      m_updateObserver;
+  // Flag to indicate that we are updating
+  bool m_updateInProgress;
+};
+
+//============================================================================
+/** Tree widget with the categories and algorithms listed
+ *
+ */
+class AlgorithmTreeWidget : public QTreeWidget {
+  Q_OBJECT
+public:
+  AlgorithmTreeWidget(QWidget *w) : QTreeWidget(w) {}
+  ~AlgorithmTreeWidget() override {}
+  void mousePressEvent(QMouseEvent *e) override;
+  void mouseMoveEvent(QMouseEvent *e) override;
+  void mouseDoubleClickEvent(QMouseEvent *e) override;
+  SelectedAlgorithm getSelectedAlgorithm();
+
+public slots:
+  void update();
+
+signals:
+  /// Signal emitted when the widget requests that we execute that algorithm
+  void executeAlgorithm(const QString &, int);
+
+private:
+  QPoint m_dragStartPosition;
+};
+
+//============================================================================
+/** ComboBox for finding algorithms
+ *
+ */
+class FindAlgComboBox : public QComboBox {
+  Q_OBJECT
+public:
+  ~FindAlgComboBox() override {}
+  SelectedAlgorithm getSelectedAlgorithm();
 
 signals:
-    void algorithmFactoryUpdateReceived();
-    void executeAlgorithm(const QString &, int);
-    void algorithmSelectionChanged(const QString &, int);
-
-  protected:
-    AlgorithmTreeWidget *m_tree;
-    FindAlgComboBox* m_findAlg;
-    QPushButton *m_execButton;
-
-  private:
-    /// Callback for AlgorithmFactory update notifications
-    void handleAlgorithmFactoryUpdate(Mantid::API::AlgorithmFactoryUpdateNotification_ptr);
-    /// Observes algorithm factory update notifications
-    Poco::NObserver<AlgorithmSelectorWidget,
-                    Mantid::API::AlgorithmFactoryUpdateNotification> m_updateObserver;
-    // Flag to indicate that we are updating
-    bool m_updateInProgress;
-  };
-
-  //============================================================================
-  /** Tree widget with the categories and algorithms listed
-   *
-   */
-  class AlgorithmTreeWidget:public QTreeWidget
-  {
-    Q_OBJECT
-  public:
-    AlgorithmTreeWidget(QWidget *w):QTreeWidget(w){}
-    ~AlgorithmTreeWidget() override {}
-    void mousePressEvent(QMouseEvent *e) override;
-    void mouseMoveEvent(QMouseEvent *e) override;
-    void mouseDoubleClickEvent(QMouseEvent *e) override;
-    SelectedAlgorithm getSelectedAlgorithm();
-
-  public slots:
-    void update();
-
-  signals:
-    /// Signal emitted when the widget requests that we execute that algorithm
-    void executeAlgorithm(const QString &, int);
-
-  private:
-    QPoint m_dragStartPosition;
-  };
-
-
-  //============================================================================
-  /** ComboBox for finding algorithms
-   *
-   */
-  class FindAlgComboBox: public QComboBox
-  {
-    Q_OBJECT
-  public:
-    ~FindAlgComboBox() override {}
-    SelectedAlgorithm getSelectedAlgorithm();
-
-  signals:
-    void enterPressed();
-
-  public slots:
-    void update();
-
-  protected:
-    void keyPressEvent(QKeyEvent *e) override;
-
-  private:
-    typedef std::vector<Mantid::API::Algorithm_descriptor> AlgNamesType;
-    void addAliases(AlgNamesType& algNamesList);
-    QString stripAlias(const QString& text) const;
-  };
+  void enterPressed();
 
+public slots:
+  void update();
 
+protected:
+  void keyPressEvent(QKeyEvent *e) override;
 
+private:
+  typedef std::vector<Mantid::API::Algorithm_descriptor> AlgNamesType;
+  void addAliases(AlgNamesType &algNamesList);
+  QString stripAlias(const QString &text) const;
+};
 
 } // namespace MantidWidgets
 } // namespace MantidQt
 
-#endif  /* MANTID_MANTIDWIDGETS_ALGORITHMSELECTORWIDGET_H_ */
-
+#endif /* MANTID_MANTIDWIDGETS_ALGORITHMSELECTORWIDGET_H_ */
 
 /**
-Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
 This file is part of Mantid.
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogHelper.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogHelper.h
index d27b0c61fc2d0deaff48c51e41df50d60369b82a..954448c4cb85c6f0651521df33d8d433b7d1ac09 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogHelper.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogHelper.h
@@ -4,54 +4,61 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include "WidgetDllOption.h"
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CatalogHelper
-    {
+namespace MantidQt {
+namespace MantidWidgets {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CatalogHelper {
 
-    public:
-      /// Obtain the list of instruments that are available for the given session information.
-      const std::vector<std::string> getInstrumentList(const std::vector<std::string> &sessionIDs);
-      /// Obtain the list of instruments that are available.
-      const std::vector<std::string> getInvestigationTypeList(
-          const std::vector<std::string> &sessionIDs);
-      /// Run the search algorithm with the given user input.
-      void executeSearch(const std::map<std::string, std::string> &userInputs, const int &offset,
-          const int &limit, const std::vector<std::string> &sessionIDs);
-      /// Obtain the number of search results to be returned by the query of the user.
-      int64_t getNumberOfSearchResults(const std::map<std::string, std::string> &userInputFields,
-          const std::vector<std::string> &sessionIDs);
-      /// Search for all related dataFiles for the specified investigation.
-      void executeGetDataFiles(const std::string &investigationId, const std::string &sessionID);
-      /// Download dataFile (via HTTP or copy if access to archive) and return the path to it.
-      const std::vector<std::string> downloadDataFiles(
-          const std::vector<std::pair<int64_t, std::string>> &userSelectedFiles,
-          const std::string &downloadPath, const std::string &sessionID);
-      /// Validate each input field against the related algorithm property.
-      const std::map<std::string, std::string> validateProperties(
-          const std::map<std::string, std::string> &inputFields);
-      /// Creates a time_t value from an input date ("23/06/2003") for comparison.
-      time_t getTimevalue(const std::string& inputDate);
-      /// Executes the catalog login algorithm dialog, returning immediately
-      void showLoginDialog();
-      /// Create a publishing dialog.
-      void showPublishDialog();
+public:
+  /// Obtain the list of instruments that are available for the given session
+  /// information.
+  const std::vector<std::string>
+  getInstrumentList(const std::vector<std::string> &sessionIDs);
+  /// Obtain the list of instruments that are available.
+  const std::vector<std::string>
+  getInvestigationTypeList(const std::vector<std::string> &sessionIDs);
+  /// Run the search algorithm with the given user input.
+  void executeSearch(const std::map<std::string, std::string> &userInputs,
+                     const int &offset, const int &limit,
+                     const std::vector<std::string> &sessionIDs);
+  /// Obtain the number of search results to be returned by the query of the
+  /// user.
+  int64_t getNumberOfSearchResults(
+      const std::map<std::string, std::string> &userInputFields,
+      const std::vector<std::string> &sessionIDs);
+  /// Search for all related dataFiles for the specified investigation.
+  void executeGetDataFiles(const std::string &investigationId,
+                           const std::string &sessionID);
+  /// Download dataFile (via HTTP or copy if access to archive) and return the
+  /// path to it.
+  const std::vector<std::string> downloadDataFiles(
+      const std::vector<std::pair<int64_t, std::string>> &userSelectedFiles,
+      const std::string &downloadPath, const std::string &sessionID);
+  /// Validate each input field against the related algorithm property.
+  const std::map<std::string, std::string>
+  validateProperties(const std::map<std::string, std::string> &inputFields);
+  /// Creates a time_t value from an input date ("23/06/2003") for comparison.
+  time_t getTimevalue(const std::string &inputDate);
+  /// Executes the catalog login algorithm dialog, returning immediately
+  void showLoginDialog();
+  /// Create a publishing dialog.
+  void showPublishDialog();
 
-    private:
-      /// Creates an algorithm with the name provided.
-      Mantid::API::IAlgorithm_sptr createCatalogAlgorithm(const std::string& algName);
-      /// Obtain the documentation for a given name from the given algorithm properties.
-      const std::string propertyDocumentation(const std::vector<Mantid::Kernel::Property*> &properties,
-          const std::string &name);
-      /// Execute the given algorithm asynchronously.
-      void executeAsynchronously(const Mantid::API::IAlgorithm_sptr &algorithm);
-      /// Set the "search" properties to their related input fields.
-      void setSearchProperties(const Mantid::API::IAlgorithm_sptr &catalogAlgorithm,
-          const std::map<std::string, std::string> &userInputFields);
-
-    };
-  } // namespace MantidWidgets
+private:
+  /// Creates an algorithm with the name provided.
+  Mantid::API::IAlgorithm_sptr
+  createCatalogAlgorithm(const std::string &algName);
+  /// Obtain the documentation for a given name from the given algorithm
+  /// properties.
+  const std::string propertyDocumentation(
+      const std::vector<Mantid::Kernel::Property *> &properties,
+      const std::string &name);
+  /// Execute the given algorithm asynchronously.
+  void executeAsynchronously(const Mantid::API::IAlgorithm_sptr &algorithm);
+  /// Set the "search" properties to their related input fields.
+  void setSearchProperties(
+      const Mantid::API::IAlgorithm_sptr &catalogAlgorithm,
+      const std::map<std::string, std::string> &userInputFields);
+};
+} // namespace MantidWidgets
 } // namespace MantidQt
 #endif // MANTIDQTWIDGETS_CATALOGHELPER_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogSelector.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogSelector.h
index 51a5ef96b3d0ac7fd2f7a390c07aae00434105f7..383d741f86121c559ebe9b9f7f1f2d350f0ca205 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogSelector.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CatalogSelector.h
@@ -4,35 +4,33 @@
 #include "ui_CatalogSelector.h"
 #include "WidgetDllOption.h"
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CatalogSelector : public QWidget
-    {
-      Q_OBJECT
+namespace MantidQt {
+namespace MantidWidgets {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CatalogSelector : public QWidget {
+  Q_OBJECT
 
-      public:
-        /// Default constructor
-        CatalogSelector(QWidget *parent = 0);
-        /// Obtain the session information for the facilities selected.
-        std::vector<std::string> getSelectedCatalogSessions();
-        /// Populate the ListWidget with the facilities of the catalogs the user is logged in to.
-        void populateFacilitySelection();
+public:
+  /// Default constructor
+  CatalogSelector(QWidget *parent = 0);
+  /// Obtain the session information for the facilities selected.
+  std::vector<std::string> getSelectedCatalogSessions();
+  /// Populate the ListWidget with the facilities of the catalogs the user is
+  /// logged in to.
+  void populateFacilitySelection();
 
-      private:
-        /// Initialise the layout
-        virtual void initLayout();
+private:
+  /// Initialise the layout
+  virtual void initLayout();
 
-      private slots:
-        /// Checks the checkbox of the list item selected.
-        void checkSelectedFacility(QListWidgetItem*item);
+private slots:
+  /// Checks the checkbox of the list item selected.
+  void checkSelectedFacility(QListWidgetItem *item);
 
-      protected:
-        /// The form generated by QT Designer.
-        Ui::CatalogSelector m_uiForm;
-    };
-  } // namespace MantidWidgets
+protected:
+  /// The form generated by QT Designer.
+  Ui::CatalogSelector m_uiForm;
+};
+} // namespace MantidWidgets
 } // namespace MantidQt
 
 #endif // MANTIDQTWIDGETS_CATALOGSELECTOR_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CheckboxHeader.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CheckboxHeader.h
index 87262f02f525ce525123f085d7f30d1652d21c02..ab8a1fe939aa940d4991e308985a2306cdfeb89a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CheckboxHeader.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/CheckboxHeader.h
@@ -7,62 +7,62 @@
 #include <QMouseEvent>
 #include <QPainter>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-      This class subclasses and overwrites QHeaderView methods to enable checkboxes to exist in the table header.
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+  This class subclasses and overwrites QHeaderView methods to enable checkboxes
+  to exist in the table header.
 
-      @author Jay Rainey
-      @date 15/10/2013
+  @author Jay Rainey
+  @date 15/10/2013
 
-      Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-      This file is part of Mantid.
+  This file is part of Mantid.
 
-      Mantid is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 3 of the License, or
-      (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-      Mantid is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-      You should have received a copy of the GNU General Public License
-      along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-      File change history is stored at: <https://github.com/mantidproject/mantid>
-      Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
 
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CheckboxHeader : public QHeaderView
-    {
-      Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CheckboxHeader : public QHeaderView {
+  Q_OBJECT
 
-    public:
-      /// Override QHeaderView constructor.
-      explicit CheckboxHeader(Qt::Orientation orientation, QWidget *parent = 0);
-      void setChecked(bool checked);
+public:
+  /// Override QHeaderView constructor.
+  explicit CheckboxHeader(Qt::Orientation orientation, QWidget *parent = 0);
+  void setChecked(bool checked);
 
-    signals:
-      void toggled(bool checked);
+signals:
+  void toggled(bool checked);
 
-    protected:
-      /// Overrides QHeaderView allowing checkbox functionality in the first column of the table.
-      void paintSection(QPainter *painter, const QRect &rect,
-                        int logicalIndex) const override;
-      /// Set the checkbox to checked when it is clicked.
-      void mousePressEvent(QMouseEvent *event) override;
+protected:
+  /// Overrides QHeaderView allowing checkbox functionality in the first column
+  /// of the table.
+  void paintSection(QPainter *painter, const QRect &rect,
+                    int logicalIndex) const override;
+  /// Set the checkbox to checked when it is clicked.
+  void mousePressEvent(QMouseEvent *event) override;
 
-    private:
-      /// The area around the checkbox.
-      QRect checkBoxRect(const QRect &sourceRect) const;
-      /// The state of the checkbox in the column header.
-      bool m_checked;
-    };
-  }
+private:
+  /// The area around the checkbox.
+  QRect checkBoxRect(const QRect &sourceRect) const;
+  /// The state of the checkbox in the column header.
+  bool m_checked;
+};
+}
 }
 #endif // MANTIDQTWIDGETS_CHECKBOXHEADER_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ColorBarWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ColorBarWidget.h
index 12cba499693f05ca6e6d6f8a9fb9ed292172f400..d6df55bd54ddb0101ed5b146da80fff4167f56a7 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ColorBarWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ColorBarWidget.h
@@ -10,36 +10,28 @@
 #include <QtGui>
 #include "MantidQtMantidWidgets/WidgetDllOption.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 //=============================================================================
 /** Extended version of QwtScaleWidget */
-class QwtScaleWidgetExtended : public QwtScaleWidget
-{
+class QwtScaleWidgetExtended : public QwtScaleWidget {
   Q_OBJECT
 
 public:
-  QwtScaleWidgetExtended(QWidget *parent = NULL)
-  : QwtScaleWidget(parent)
-  {
+  QwtScaleWidgetExtended(QWidget *parent = NULL) : QwtScaleWidget(parent) {
     this->setMouseTracking(true);
   }
 
-  void mouseMoveEvent(QMouseEvent * event) override
-  {
+  void mouseMoveEvent(QMouseEvent *event) override {
     double val = 1.0 - double(event->y()) / double(this->height());
     emit mouseMoved(event->globalPos(), val);
   }
 
 signals:
   void mouseMoved(QPoint, double);
-
 };
 
-
 //=============================================================================
 /** Widget for showing a color bar, modifying its
  * limits, etc.
@@ -47,8 +39,7 @@ signals:
  * @author Janik Zikovsky
  * @date Oct 31, 2011.
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ColorBarWidget : public QWidget
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ColorBarWidget : public QWidget {
   Q_OBJECT
   Q_PROPERTY(double minimum READ getMinimum WRITE setMinimum)
   Q_PROPERTY(double maximum READ getMaximum WRITE setMaximum)
@@ -68,7 +59,7 @@ public:
   double getMinimum() const;
   double getMaximum() const;
   QwtDoubleInterval getViewRange() const;
-  MantidColorMap & getColorMap();
+  MantidColorMap &getColorMap();
 
   bool getLog();
 
@@ -98,15 +89,15 @@ signals:
 
 private:
   void setSpinBoxesSteps();
-  void mouseDoubleClickEvent(QMouseEvent * event) override;
+  void mouseDoubleClickEvent(QMouseEvent *event) override;
   void updateMinMaxGUI();
-  void resizeEvent(QResizeEvent * event) override;
+  void resizeEvent(QResizeEvent *event) override;
 
   /// Auto-gen UI classes
   Ui::ColorBarWidgetClass ui;
 
   /// The color bar widget from QWT
-  QwtScaleWidget * m_colorBar;
+  QwtScaleWidget *m_colorBar;
 
   /// Color map being displayed
   MantidColorMap m_colorMap;
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DataSelector.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DataSelector.h
index 1e0bbe00506b07e333ca85beaf0e417b1df94abf..4a2ea7655538eedd6850cb54027ae2b2e6e32cc5 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DataSelector.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DataSelector.h
@@ -9,137 +9,142 @@
 
 #include <QWidget>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-    This class defines a widget for selecting a workspace of file path by using a combination
-    of two child MantidWidgets: MWRunFiles and WorkspaceSelector. This widget combines the two to
-    produce a single composite widget that emits signals when the user has chosen appropriate input.
-
-    @author Samuel Jackson
-    @date 07/08/2013
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DataSelector : public API::MantidWidget
-    {
-      Q_OBJECT
-
-      Q_PROPERTY(bool autoLoad READ willAutoLoad WRITE setAutoLoad)
-      Q_PROPERTY(QString loadLabelText READ getLoadBtnText WRITE setLoadBtnText)
-      Q_PROPERTY(QStringList workspaceSuffixes READ getWSSuffixes WRITE setWSSuffixes)
-      Q_PROPERTY(QStringList fileBrowserSuffixes READ getFBSuffixes WRITE setFBSuffixes)
-      Q_PROPERTY(bool showLoad READ willShowLoad WRITE setShowLoad)
-      Q_PROPERTY(QString instrumentOverride READ getInstrumentOverride WRITE setInstrumentOverride)
-
-    public:
-      DataSelector(QWidget *parent = 0);
-      ~DataSelector() override;
-
-      /// Get the current file path in the MWRunFiles widget
-      QString getFullFilePath() const;
-      /// Get the currently available file or workspace name
-      QString getCurrentDataName() const;
-      /// Get whether the file selector is currently being shown
-      bool isFileSelectorVisible() const;
-      /// Get whether the workspace selector is currently being shown
-      bool isWorkspaceSelectorVisible() const;
-      /// Checks if widget is in a valid state
-      bool isValid();
-      /// Get file problem, empty string means no error.
-      QString getProblem() const;
-      /// Check if the widget is set to automatically attempt to load files
-      bool willAutoLoad();
-      /// Set the widget to automatically attempt to load files
-      void setAutoLoad(bool load);
-      /// Get the text of the load files button
-      QString getLoadBtnText();
-      /// Set the text of the load files button
-      void setLoadBtnText(const QString &  text);
-      /// Get file suffixes to filter for in the workspace selector
-      QStringList getWSSuffixes();
-      /// Set file suffixes to filter for in the workspace selector
-      void setWSSuffixes(const QStringList & suffixes);
-      /// Get file suffixes to filter for in the file browser
-      QStringList getFBSuffixes();
-      /// Set file suffixes to filter for in the file browser
-      void setFBSuffixes(const QStringList & suffixes);
-      /// Read settings from the given group
-      void readSettings(const QString & group);
-      /// Save settings in the given group
-      void saveSettings(const QString & group);
-      /// Check if the widget will show the load button
-      bool willShowLoad();
-      /// Set if the load button should be shown
-      void setShowLoad(bool load);
-      /// Gets the instrument currently fixed to
-      QString getInstrumentOverride();
-      /// Overrides the value of default instrument
-      void setInstrumentOverride(const QString & instName);
-
-    signals:
-      /// Signal emitted when files were found but widget isn't autoloading
-      void filesFound();
-      /// Signal emitted when file input is visible
-      void fileViewVisible();
-      /// Signal emitted when workspace selector is visible
-      void workspaceViewVisible();
-      /// Signal emitted when data is ready from a workspace selector or file browser
-      void dataReady(const QString& wsname);
-      /// Signal emitted when the load button is clicked
-      void loadClicked();
-
-    protected:
-      //Method for handling drop events
-      void dropEvent(QDropEvent *) override;
-      //called when a drag event enters the class
-      void dragEnterEvent(QDragEnterEvent *) override;
-
-    private slots:
-      /// Slot called when the current view is changed
-      void handleViewChanged(int index);
-      /// Slot called when file input is available
-      void handleFileInput();
-      /// Slot called when workspace input is available
-      void handleWorkspaceInput();
-      /// Slot called if the widget fails to auto load the file.
-      void handleAutoLoadComplete(bool error);
-
-    private:
-      /// Attempt to automatically load a file
-      void autoLoadFile(const QString& filenames);
-      /// Member containing the widgets child widgets.
-      Ui::DataSelector m_uiForm;
-      /// Algorithm Runner used to run the load algorithm
-      MantidQt::API::AlgorithmRunner m_algRunner;
-      /// Flag to enable auto loading. By default this is set to true.
-      bool m_autoLoad;
-      /// Flag to show or hide the load button. By default this is set to true.
-      bool m_showLoad;
-
-    };
-
-  } /* namespace MantidWidgets */
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+This class defines a widget for selecting a workspace of file path by using a
+combination
+of two child MantidWidgets: MWRunFiles and WorkspaceSelector. This widget
+combines the two to
+produce a single composite widget that emits signals when the user has chosen
+appropriate input.
+
+@author Samuel Jackson
+@date 07/08/2013
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DataSelector
+    : public API::MantidWidget {
+  Q_OBJECT
+
+  Q_PROPERTY(bool autoLoad READ willAutoLoad WRITE setAutoLoad)
+  Q_PROPERTY(QString loadLabelText READ getLoadBtnText WRITE setLoadBtnText)
+  Q_PROPERTY(QStringList workspaceSuffixes READ getWSSuffixes WRITE
+                 setWSSuffixes)
+  Q_PROPERTY(QStringList fileBrowserSuffixes READ getFBSuffixes WRITE
+                 setFBSuffixes)
+  Q_PROPERTY(bool showLoad READ willShowLoad WRITE setShowLoad)
+  Q_PROPERTY(QString instrumentOverride READ getInstrumentOverride WRITE
+                 setInstrumentOverride)
+
+public:
+  DataSelector(QWidget *parent = 0);
+  ~DataSelector() override;
+
+  /// Get the current file path in the MWRunFiles widget
+  QString getFullFilePath() const;
+  /// Get the currently available file or workspace name
+  QString getCurrentDataName() const;
+  /// Get whether the file selector is currently being shown
+  bool isFileSelectorVisible() const;
+  /// Get whether the workspace selector is currently being shown
+  bool isWorkspaceSelectorVisible() const;
+  /// Checks if widget is in a valid state
+  bool isValid();
+  /// Get file problem, empty string means no error.
+  QString getProblem() const;
+  /// Check if the widget is set to automatically attempt to load files
+  bool willAutoLoad();
+  /// Set the widget to automatically attempt to load files
+  void setAutoLoad(bool load);
+  /// Get the text of the load files button
+  QString getLoadBtnText();
+  /// Set the text of the load files button
+  void setLoadBtnText(const QString &text);
+  /// Get file suffixes to filter for in the workspace selector
+  QStringList getWSSuffixes();
+  /// Set file suffixes to filter for in the workspace selector
+  void setWSSuffixes(const QStringList &suffixes);
+  /// Get file suffixes to filter for in the file browser
+  QStringList getFBSuffixes();
+  /// Set file suffixes to filter for in the file browser
+  void setFBSuffixes(const QStringList &suffixes);
+  /// Read settings from the given group
+  void readSettings(const QString &group);
+  /// Save settings in the given group
+  void saveSettings(const QString &group);
+  /// Check if the widget will show the load button
+  bool willShowLoad();
+  /// Set if the load button should be shown
+  void setShowLoad(bool load);
+  /// Gets the instrument currently fixed to
+  QString getInstrumentOverride();
+  /// Overrides the value of default instrument
+  void setInstrumentOverride(const QString &instName);
+
+signals:
+  /// Signal emitted when files were found but widget isn't autoloading
+  void filesFound();
+  /// Signal emitted when file input is visible
+  void fileViewVisible();
+  /// Signal emitted when workspace selector is visible
+  void workspaceViewVisible();
+  /// Signal emitted when data is ready from a workspace selector or file
+  /// browser
+  void dataReady(const QString &wsname);
+  /// Signal emitted when the load button is clicked
+  void loadClicked();
+
+protected:
+  // Method for handling drop events
+  void dropEvent(QDropEvent *) override;
+  // called when a drag event enters the class
+  void dragEnterEvent(QDragEnterEvent *) override;
+
+private slots:
+  /// Slot called when the current view is changed
+  void handleViewChanged(int index);
+  /// Slot called when file input is available
+  void handleFileInput();
+  /// Slot called when workspace input is available
+  void handleWorkspaceInput();
+  /// Slot called if the widget fails to auto load the file.
+  void handleAutoLoadComplete(bool error);
+
+private:
+  /// Attempt to automatically load a file
+  void autoLoadFile(const QString &filenames);
+  /// Member containing the widgets child widgets.
+  Ui::DataSelector m_uiForm;
+  /// Algorithm Runner used to run the load algorithm
+  MantidQt::API::AlgorithmRunner m_algRunner;
+  /// Flag to enable auto loading. By default this is set to true.
+  bool m_autoLoad;
+  /// Flag to show or hide the load button. By default this is set to true.
+  bool m_showLoad;
+};
+
+} /* namespace MantidWidgets */
 } /* namespace MantidQt */
 #endif /* DATASELECTOR_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
index 6ffea10d0f754e5dd909730fd84e3992c50df41d..ebac1cb2e326a186d9483bc96fe164e00cd14f57 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
@@ -7,33 +7,31 @@
 #include <QSignalMapper>
 #include <QGridLayout>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DiagResults : public API::MantidDialog
-    {
-      Q_OBJECT
-
-    public:
-      DiagResults(QWidget *parent);
-      void updateResults(const QString & testSummary);
-
-    signals:
-      /// is emitted just before the window dies to let the window that created this know the pointer it has is invalid
-      void died();
-
-    private:
-      void updateRow(int row, QString text);
-      int addRow(QString firstColumn, QString secondColumn);
-      void closeEvent(QCloseEvent *event) override;
-
-    private:
-      /// the layout that widgets are added to
-      QGridLayout *m_Grid;
-    };
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DiagResults : public API::MantidDialog {
+  Q_OBJECT
+
+public:
+  DiagResults(QWidget *parent);
+  void updateResults(const QString &testSummary);
+
+signals:
+  /// is emitted just before the window dies to let the window that created this
+  /// know the pointer it has is invalid
+  void died();
+
+private:
+  void updateRow(int row, QString text);
+  int addRow(QString firstColumn, QString secondColumn);
+  void closeEvent(QCloseEvent *event) override;
+
+private:
+  /// the layout that widgets are added to
+  QGridLayout *m_Grid;
+};
+}
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
+#endif // MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DisplayCurveFit.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DisplayCurveFit.h
index b42cb800b85fe57970a9b7bc6dc8e042e75256af..87eacd588787f3b7c0de5c062834f29ed5018c5a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DisplayCurveFit.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DisplayCurveFit.h
@@ -67,7 +67,7 @@ public:
   enum class dcRange {
     fit = 1, ///< range over which the fitting procedure is carried out.
     evaluate ///< range over which the fit and residuals curves are evaluated.
-             ///Usually extends beyond the boundaries of the fit range.
+    /// Usually extends beyond the boundaries of the fit range.
   };
   DisplayCurveFit(QWidget *parent = nullptr);
   ~DisplayCurveFit() override;
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleDialogEditor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleDialogEditor.h
index c3a9afa8eaceaabffdc34b9fbf3130a722c1e6c7..822ac370f631dfc52130a6392f413fe51c44af50 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleDialogEditor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleDialogEditor.h
@@ -8,54 +8,64 @@ class QLineEdit;
 class QPushButton;
 
 /**
- * Partially implemented string editor. It has a QLineEdit for manual editing and a button [...] next to it
- * to call a dialog for more complex editing. Clicking the button calls virtual runDialog() method.
+ * Partially implemented string editor. It has a QLineEdit for manual editing
+ * and a button [...] next to it
+ * to call a dialog for more complex editing. Clicking the button calls virtual
+ * runDialog() method.
  * Concrete classes must implement it.
  */
-class DoubleDialogEditor: public QWidget
-{
+class DoubleDialogEditor : public QWidget {
   Q_OBJECT
 public:
   DoubleDialogEditor(QtProperty *property, QWidget *parent);
 signals:
-  void buttonClicked(QtProperty*);
+  void buttonClicked(QtProperty *);
   void closeEditor();
 
 protected slots:
-  /// Implementations must open a dialog to edit the editor's text. If editing is successful
+  /// Implementations must open a dialog to edit the editor's text. If editing
+  /// is successful
   /// setText() and updateProperty() methods must be called.
   virtual void runDialog();
   void updateProperty();
-  void setText(const QString& txt);
-  QString getText()const;
+  void setText(const QString &txt);
+  QString getText() const;
+
 private:
   bool eventFilter(QObject *, QEvent *) override;
-  DoubleEditor* m_editor;
-  QPushButton* m_button;
-  QtProperty* m_property;
+  DoubleEditor *m_editor;
+  QPushButton *m_button;
+  QtProperty *m_property;
 };
 
 /**
-* An abstract editor factory to be used with QtPropertyBrowser. Implementations need to
-* implement QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
-* method which creates a specific editor. The underlying type of the edited property must be string.
+* An abstract editor factory to be used with QtPropertyBrowser. Implementations
+* need to
+* implement QWidget *createEditor(QtStringPropertyManager *manager, QtProperty
+* *property,QWidget *parent)
+* method which creates a specific editor. The underlying type of the edited
+* property must be string.
 */
-class DoubleDialogEditorFactory : public QtAbstractEditorFactory<ParameterPropertyManager>
-{
+class DoubleDialogEditorFactory
+    : public QtAbstractEditorFactory<ParameterPropertyManager> {
   Q_OBJECT
 public:
-  DoubleDialogEditorFactory(QObject *parent = 0) : QtAbstractEditorFactory<ParameterPropertyManager>(parent) {}
+  DoubleDialogEditorFactory(QObject *parent = 0)
+      : QtAbstractEditorFactory<ParameterPropertyManager>(parent) {}
   QWidget *createEditorForManager(ParameterPropertyManager *,
                                   QtProperty *property,
                                   QWidget *parent) override {
     auto editor = new DoubleDialogEditor(property, parent);
-    connect(editor, SIGNAL(buttonClicked(QtProperty*)), this, SIGNAL(buttonClicked(QtProperty*)));
-    connect(editor, SIGNAL(closeEditor()), this, SIGNAL(closeEditor()), Qt::QueuedConnection);
+    connect(editor, SIGNAL(buttonClicked(QtProperty *)), this,
+            SIGNAL(buttonClicked(QtProperty *)));
+    connect(editor, SIGNAL(closeEditor()), this, SIGNAL(closeEditor()),
+            Qt::QueuedConnection);
     return editor;
   }
 signals:
-  void buttonClicked(QtProperty*);
+  void buttonClicked(QtProperty *);
   void closeEditor();
+
 protected:
   void connectPropertyManager(ParameterPropertyManager *) override {}
   void disconnectPropertyManager(ParameterPropertyManager *) override {}
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleSpinBox.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleSpinBox.h
index dd8018a279397c8d7aa7caae33d999b9a70f66ca..92ab2ee9f163e13fbd7ea44713df1dfd5b41cdb2 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleSpinBox.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DoubleSpinBox.h
@@ -35,21 +35,23 @@
 #include <QAbstractSpinBox>
 #include <QCheckBox>
 
-//! A QDoubleSpinBox allowing to customize numbers display with respect to locale settings. 
+//! A QDoubleSpinBox allowing to customize numbers display with respect to
+// locale settings.
 /**
  * It allows the user to specify a custom display format.
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DoubleSpinBox : public QAbstractSpinBox
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DoubleSpinBox
+    : public QAbstractSpinBox {
   Q_OBJECT
 
 public:
   //! Constructor.
   /**
-   * \param format format used to display numbers: has the same meaning as in QLocale::toString ( double i, char f = 'g', int prec = 6 )
+   * \param format format used to display numbers: has the same meaning as in
+   * QLocale::toString ( double i, char f = 'g', int prec = 6 )
    * \param parent parent widget (only affects placement of the dialog)
    */
-  DoubleSpinBox(const char format = 'g', QWidget * parent = 0);
+  DoubleSpinBox(const char format = 'g', QWidget *parent = 0);
 
   void setSingleStep(double val);
   void setMaximum(double max);
@@ -59,26 +61,32 @@ public:
   double getMaximum();
   double getMinimum();
 
-  int decimals(){return d_prec;};
-  void setDecimals(int prec){if (prec >= 0) d_prec = prec;};
+  int decimals() { return d_prec; };
+  void setDecimals(int prec) {
+    if (prec >= 0)
+      d_prec = prec;
+  };
 
   double value();
   bool setValue(double val);
 
-  void setFormat(const char format, int prec = 1){d_format = format; setDecimals(prec);};
+  void setFormat(const char format, int prec = 1) {
+    d_format = format;
+    setDecimals(prec);
+  };
 
   void addSpecialTextMapping(QString text, double value);
 
-  QString textFromValue ( double value ) const;
+  QString textFromValue(double value) const;
   QValidator::State validate(QString &input, int &pos) const override;
 
-  signals:
-  void valueChanged ( double d );
+signals:
+  void valueChanged(double d);
   //! Signal emitted when the spin box gains focus
   void activated(DoubleSpinBox *);
 
 private slots:
-  void interpretText(bool notify=true);
+  void interpretText(bool notify = true);
 
 protected:
   void stepBy(int steps) override;
@@ -93,20 +101,21 @@ private:
   double d_step;
   int d_prec;
 
-  //A set of mappins from strings which the user can enter in the box to double values
+  // A set of mappins from strings which the user can enter in the box to double
+  // values
   std::map<QString, double> m_specialTextMappings;
 };
 
-//! A checkable DoubleSpinBox that can be used to select the limits of a double interval. 
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RangeLimitBox : public QWidget
-{
+//! A checkable DoubleSpinBox that can be used to select the limits of a double
+// interval.
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RangeLimitBox : public QWidget {
 public:
-  enum LimitType{LeftLimit, RightLimit};
+  enum LimitType { LeftLimit, RightLimit };
 
-  RangeLimitBox(LimitType type, QWidget * parent = 0);
-  void setDecimals(int prec){d_spin_box->setDecimals(prec);};
+  RangeLimitBox(LimitType type, QWidget *parent = 0);
+  void setDecimals(int prec) { d_spin_box->setDecimals(prec); };
   double value();
-  bool isChecked(){return d_checkbox->isChecked();};
+  bool isChecked() { return d_checkbox->isChecked(); };
 
 private:
   DoubleSpinBox *d_spin_box;
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ErrorCurve.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ErrorCurve.h
index b468fafa22c12b93127dc6ac8783d1682be09377..a3bb53382a429704799c453274de413f7906fa23 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ErrorCurve.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ErrorCurve.h
@@ -5,27 +5,25 @@
 #include <qwt_plot_item.h>
 #include <qwt_plot_curve.h>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /// Curve to draw error bars.
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ErrorCurve: public QwtPlotItem
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ErrorCurve : public QwtPlotItem {
 
 public:
-  ErrorCurve(const QwtPlotCurve* dataCurve, const std::vector<double>& errors = std::vector<double>());
+  ErrorCurve(const QwtPlotCurve *dataCurve,
+             const std::vector<double> &errors = std::vector<double>());
   /// Set error bars
-  void setErrorBars(const std::vector<double>& errors);
+  void setErrorBars(const std::vector<double> &errors);
   /// Number of points in the curve
   int dataSize() const;
   /// Draw this curve
   void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &canvasRect) const override;
   QRectF boundingRect() const override;
-private:
 
+private:
   std::vector<double> m_x; ///< The x coordinates
   std::vector<double> m_y; ///< The y coordinates
   std::vector<double> m_e; ///< The error bars
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FilenameDialogEditor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FilenameDialogEditor.h
index b32fe15ee35efefdfb20c8c3a94264146c3638a5..876cbc63493dfeb8f76b04c7c317f7321c99efde 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FilenameDialogEditor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FilenameDialogEditor.h
@@ -3,20 +3,17 @@
 
 #include "MantidQtMantidWidgets/StringDialogEditor.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
  * A stringDialogEditor for editing file names.
  */
-class FilenameDialogEditor: public StringDialogEditor
-{
+class FilenameDialogEditor : public StringDialogEditor {
   Q_OBJECT
 public:
   FilenameDialogEditor(QtProperty *property, QWidget *parent)
-    :StringDialogEditor(property,parent){}
+      : StringDialogEditor(property, parent) {}
 protected slots:
   void runDialog() override;
 };
@@ -24,21 +21,22 @@ protected slots:
 /**
  * The factory for the FilenameDialogEditor.
  */
-class FilenameDialogEditorFactory: public StringDialogEditorFactory
-{
+class FilenameDialogEditorFactory : public StringDialogEditorFactory {
   Q_OBJECT
 public:
-  FilenameDialogEditorFactory(QObject* parent):StringDialogEditorFactory(parent){}
+  FilenameDialogEditorFactory(QObject *parent)
+      : StringDialogEditorFactory(parent) {}
+
 protected:
-  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler warning
+  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler
+                                                   // warning
   QWidget *createEditorForManager(QtStringPropertyManager *manager,
                                   QtProperty *property,
                                   QWidget *parent) override {
-    (void) manager; //Avoid unused warning
-    return new FilenameDialogEditor(property,parent);
+    (void)manager; // Avoid unused warning
+    return new FilenameDialogEditor(property, parent);
   }
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindDialog.h
index 7c960beb397937cf6806d6418ea97ff30ee8c6ec..4b6759700ea4cb12db403b0fef9bcbe2d5037ad9 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindDialog.h
@@ -10,14 +10,11 @@
  * Specialisation of FindReplaceDialog that only
  * does finding
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FindDialog : public FindReplaceDialog
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FindDialog : public FindReplaceDialog {
   Q_OBJECT
 
 public:
   FindDialog(ScriptEditor *editor, Qt::WindowFlags flags = 0);
-
 };
 
 #endif // FINDDIALOG_H_
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindReplaceDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindReplaceDialog.h
index 62cfd5feb1c171b554b77d43265a5980f368a16a..8fba702244b5c6acc2f0274173549dcea5eeaf39 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindReplaceDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FindReplaceDialog.h
@@ -22,76 +22,74 @@ class QShowEvent;
  * Raises a dialog allowing the user to find/replace
  * text in the editor.
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FindReplaceDialog : public QDialog
-{
- Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FindReplaceDialog : public QDialog {
+  Q_OBJECT
 
 public:
- /// Constructor
- FindReplaceDialog(ScriptEditor *editor, 
-                   Qt::WindowFlags fl = 0);
+  /// Constructor
+  FindReplaceDialog(ScriptEditor *editor, Qt::WindowFlags fl = 0);
 
 protected:
- /// Create the layout
- void initLayout();
- /// Add replace box
- void addReplaceBox();
- /// Add the replace buttons
- void addReplaceButtons();
+  /// Create the layout
+  void initLayout();
+  /// Add replace box
+  void addReplaceBox();
+  /// Add the replace buttons
+  void addReplaceButtons();
 
 protected slots:
- /// Find
- bool find(bool backwards = false);
- /// Replace slot
- void replace();
- /// Replace all slot
- void replaceAll();
+  /// Find
+  bool find(bool backwards = false);
+  /// Replace slot
+  void replace();
+  /// Replace all slot
+  void replaceAll();
 
- /// A slot for the findClicked button
- void findClicked();
- /// Reset the search flags due to changes
- void resetSearchFlags();
- /// Set the flag about whether we are currently finding
- void findNotInProgress();
- /// Clear the editor selection
- void clearEditorSelection();
+  /// A slot for the findClicked button
+  void findClicked();
+  /// Reset the search flags due to changes
+  void resetSearchFlags();
+  /// Set the flag about whether we are currently finding
+  void findNotInProgress();
+  /// Clear the editor selection
+  void clearEditorSelection();
 
 private:
- /// Called when the widget is shown
+  /// Called when the widget is shown
   void showEvent(QShowEvent *event) override;
 
- /// The text editor we are working on
- ScriptEditor *m_editor;
- ///Find next match button
- QPushButton* buttonNext;
- /// Replace text button
- QPushButton* buttonReplace;
- /// Replace all text button
- QPushButton* buttonReplaceAll;
- /// Cancel dialog button
- QPushButton* buttonCancel;
+  /// The text editor we are working on
+  ScriptEditor *m_editor;
+  /// Find next match button
+  QPushButton *buttonNext;
+  /// Replace text button
+  QPushButton *buttonReplace;
+  /// Replace all text button
+  QPushButton *buttonReplaceAll;
+  /// Cancel dialog button
+  QPushButton *buttonCancel;
 
- /// Find box
- QComboBox* boxFind;
- /// Replace box
- QComboBox* boxReplace;
+  /// Find box
+  QComboBox *boxFind;
+  /// Replace box
+  QComboBox *boxReplace;
 
- /// Case-sensitive check box
- QCheckBox *boxCaseSensitive;
- /// Whole words check box
- QCheckBox *boxWholeWords;
- /// Search backwards
- QCheckBox *boxSearchBackwards;
- /// Wrap around
- QCheckBox *boxWrapAround;
- /// Treat as regular expressions
- QCheckBox *boxRegex;
+  /// Case-sensitive check box
+  QCheckBox *boxCaseSensitive;
+  /// Whole words check box
+  QCheckBox *boxWholeWords;
+  /// Search backwards
+  QCheckBox *boxSearchBackwards;
+  /// Wrap around
+  QCheckBox *boxWrapAround;
+  /// Treat as regular expressions
+  QCheckBox *boxRegex;
 
- /// If a find is in progress
- bool m_findInProgress;
+  /// If a find is in progress
+  bool m_findInProgress;
 
- QGridLayout *m_topLayout;
- QVBoxLayout *m_vb2;
+  QGridLayout *m_topLayout;
+  QVBoxLayout *m_vb2;
 };
 
-#endif //FINDREPLACEDIALOG_H_
+#endif // FINDREPLACEDIALOG_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitOptionsBrowser.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitOptionsBrowser.h
index 4b9306cafcc020d90e6f543863e1ea0dbf8817b1..23f195f74ef70f259b20ac8a23756dc4858c7485 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitOptionsBrowser.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitOptionsBrowser.h
@@ -17,30 +17,24 @@ class QtEnumPropertyManager;
 class QtGroupPropertyManager;
 class QSettings;
 
-namespace Mantid
-{
-namespace Kernel
-{
-  class Property;
+namespace Mantid {
+namespace Kernel {
+class Property;
 }
-namespace API
-{
-  class IAlgorithm;
+namespace API {
+class IAlgorithm;
 }
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
- * Class FitOptionsBrowser implements QtPropertyBrowser to display 
+ * Class FitOptionsBrowser implements QtPropertyBrowser to display
  * and set properties of Fit algorithm (excluding Function and Workspace)
- * 
+ *
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FitOptionsBrowser: public QWidget
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FitOptionsBrowser : public QWidget {
   Q_OBJECT
 public:
   /// Support for fitting algorithms:
@@ -48,21 +42,21 @@ public:
   ///   Sequential:   PlotPeakByLogValue
   ///   SimultaneousAndSequential: both Fit and PlotPeakByLogValue, toggled with
   ///       "Fitting" property.
-  enum FittingType {Simultaneous = 0, Sequential, SimultaneousAndSequential};
+  enum FittingType { Simultaneous = 0, Sequential, SimultaneousAndSequential };
 
   /// Constructor
   FitOptionsBrowser(QWidget *parent = NULL, FittingType fitType = Simultaneous);
-  QString getProperty(const QString& name) const;
-  void setProperty(const QString& name, const QString& value);
-  void copyPropertiesToAlgorithm(Mantid::API::IAlgorithm& fit) const;
-  void saveSettings(QSettings& settings) const;
-  void loadSettings(const QSettings& settings);
+  QString getProperty(const QString &name) const;
+  void setProperty(const QString &name, const QString &value);
+  void copyPropertiesToAlgorithm(Mantid::API::IAlgorithm &fit) const;
+  void saveSettings(QSettings &settings) const;
+  void loadSettings(const QSettings &settings);
   FittingType getCurrentFittingType() const;
   void setCurrentFittingType(FittingType fitType);
   void lockCurrentFittingType(FittingType fitType);
   void unlockCurrentFittingType();
-  void setLogNames(const QStringList& logNames);
-  void setParameterNamesForPlotting(const QStringList& parNames);
+  void setLogNames(const QStringList &logNames);
+  void setParameterNamesForPlotting(const QStringList &parNames);
   QString getParameterToPlot() const;
 
 signals:
@@ -71,16 +65,15 @@ signals:
   void doublePropertyChanged(const QString &propertyName);
 
 protected:
-  QtProperty* addDoubleProperty(const QString &propertyName);
-  void displayProperty(const QString &propertyName, bool show=true);
+  QtProperty *addDoubleProperty(const QString &propertyName);
+  void displayProperty(const QString &propertyName, bool show = true);
   void displaySequentialFitProperties();
 
 private slots:
-  void enumChanged(QtProperty*);
+  void enumChanged(QtProperty *);
   void doubleChanged(QtProperty *property);
 
 private:
-
   void createBrowser();
   void initFittingTypeProp();
   void createProperties();
@@ -91,93 +84,94 @@ private:
   void switchFitType();
   void displayNormalFitProperties();
 
-  QtProperty* createPropertyProperty(Mantid::Kernel::Property* prop);
+  QtProperty *createPropertyProperty(Mantid::Kernel::Property *prop);
 
-  void addProperty(const QString& name, QtProperty* prop,
-    QString (FitOptionsBrowser::*getter)(QtProperty*)const, 
-    void (FitOptionsBrowser::*setter)(QtProperty*,const QString&));
+  void addProperty(const QString &name, QtProperty *prop,
+                   QString (FitOptionsBrowser::*getter)(QtProperty *) const,
+                   void (FitOptionsBrowser::*setter)(QtProperty *,
+                                                     const QString &));
 
   void removeProperty(const QString &name);
 
   //  Setters and getters
-  QString getMinimizer(QtProperty*) const;
-  void setMinimizer(QtProperty*, const QString&);
-
-  QString getIntProperty(QtProperty*) const;
-  void setIntProperty(QtProperty*, const QString&);
-  QString getDoubleProperty(QtProperty*) const;
-  void setDoubleProperty(QtProperty*, const QString&);
-  QString getBoolProperty(QtProperty*) const;
-  void setBoolProperty(QtProperty*, const QString&);
-  QString getStringEnumProperty(QtProperty*) const;
-  void setStringEnumProperty(QtProperty*, const QString&);
-  QString getStringProperty(QtProperty*) const;
-  void setStringProperty(QtProperty*, const QString&);
-
-  void setPropertyEnumValues(QtProperty* prop, const QStringList& values);
+  QString getMinimizer(QtProperty *) const;
+  void setMinimizer(QtProperty *, const QString &);
+
+  QString getIntProperty(QtProperty *) const;
+  void setIntProperty(QtProperty *, const QString &);
+  QString getDoubleProperty(QtProperty *) const;
+  void setDoubleProperty(QtProperty *, const QString &);
+  QString getBoolProperty(QtProperty *) const;
+  void setBoolProperty(QtProperty *, const QString &);
+  QString getStringEnumProperty(QtProperty *) const;
+  void setStringEnumProperty(QtProperty *, const QString &);
+  QString getStringProperty(QtProperty *) const;
+  void setStringProperty(QtProperty *, const QString &);
+
+  void setPropertyEnumValues(QtProperty *prop, const QStringList &values);
 
   /// Manager for bool properties
-  QtBoolPropertyManager* m_boolManager;
+  QtBoolPropertyManager *m_boolManager;
   /// Manager for int properties
-  QtIntPropertyManager* m_intManager;
+  QtIntPropertyManager *m_intManager;
   /// Manager for double properties
-  QtDoublePropertyManager* m_doubleManager;
+  QtDoublePropertyManager *m_doubleManager;
   /// Manager for string properties
-  QtStringPropertyManager* m_stringManager;
+  QtStringPropertyManager *m_stringManager;
   /// Manager for the string list properties
-  QtEnumPropertyManager* m_enumManager;
+  QtEnumPropertyManager *m_enumManager;
   /// Manager for groups of properties
-  QtGroupPropertyManager* m_groupManager;
+  QtGroupPropertyManager *m_groupManager;
 
   /// FitType property
-  QtProperty* m_fittingTypeProp;
+  QtProperty *m_fittingTypeProp;
   /// Minimizer group property
-  QtProperty* m_minimizerGroup;
+  QtProperty *m_minimizerGroup;
   /// Minimizer property
-  QtProperty* m_minimizer;
+  QtProperty *m_minimizer;
   /// CostFunction property
-  QtProperty* m_costFunction;
+  QtProperty *m_costFunction;
   /// MaxIterations property
-  QtProperty* m_maxIterations;
+  QtProperty *m_maxIterations;
 
   // Fit properties
   /// Output property
-  QtProperty* m_output;
+  QtProperty *m_output;
   /// IgnoreInvalidData property
-  QtProperty* m_ignoreInvalidData;
+  QtProperty *m_ignoreInvalidData;
 
   // PlotPeakByLogValue properties
   /// Store special properties of the sequential Fit
-  QList<QtProperty*> m_sequentialProperties;
+  QList<QtProperty *> m_sequentialProperties;
   /// FitType property
-  QtProperty* m_fitType;
+  QtProperty *m_fitType;
   /// OutputWorkspace property
-  QtProperty* m_outputWorkspace;
+  QtProperty *m_outputWorkspace;
   /// LogValue property
-  QtProperty* m_logValue;
+  QtProperty *m_logValue;
   /// Property for a name of a parameter to plot
   /// against LogValue
-  QtProperty* m_plotParameter;
+  QtProperty *m_plotParameter;
 
   /// Qt property browser which displays properties
-  QtTreePropertyBrowser* m_browser;
+  QtTreePropertyBrowser *m_browser;
 
   /// Precision of doubles in m_doubleManager
   int m_decimals;
 
-  typedef  void (FitOptionsBrowser::*SetterType)(QtProperty*, const QString&);
-  typedef  QString (FitOptionsBrowser::*GetterType)(QtProperty*)const;
+  typedef void (FitOptionsBrowser::*SetterType)(QtProperty *, const QString &);
+  typedef QString (FitOptionsBrowser::*GetterType)(QtProperty *) const;
   /// Maps algorithm property name to the QtProperty
-  QMap<QString,QtProperty*> m_propertyNameMap;
+  QMap<QString, QtProperty *> m_propertyNameMap;
   /// Store for the properties setter methods
-  QMap<QtProperty*,SetterType> m_setters;
+  QMap<QtProperty *, SetterType> m_setters;
   /// Store for the properties getter methods
-  QMap<QtProperty*,GetterType> m_getters;
+  QMap<QtProperty *, GetterType> m_getters;
 
   /// The Fitting Type
   FittingType m_fittingType;
   /// Store special properties of the normal Fit
-  QList<QtProperty*> m_simultaneousProperties;
+  QList<QtProperty *> m_simultaneousProperties;
 };
 
 } // MantidWidgets
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitPropertyBrowser.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitPropertyBrowser.h
index db3f3e75d4738e2832d55c067aa3e414bc68bc34..811b08c2bdcf7b06c58ca795b700752b486c2667 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitPropertyBrowser.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FitPropertyBrowser.h
@@ -17,8 +17,7 @@
 #include "MantidAPI/FunctionFactory.h"
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 
-
-    /* Forward declarations */
+/* Forward declarations */
 
 class QtTreePropertyBrowser;
 class QtGroupPropertyManager;
@@ -41,55 +40,54 @@ class QMenu;
 class QAction;
 class QTreeWidget;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 class PropertyHandler;
 /**
- * Class FitPropertyBrowser implements QtPropertyBrowser to display 
+ * Class FitPropertyBrowser implements QtPropertyBrowser to display
  * and control fitting function parameters and settings.
- * 
+ *
  * @date 13/11/2009
  */
 
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FitPropertyBrowser: public QDockWidget, public Mantid::API::AlgorithmObserver,
-                          public MantidQt::API::WorkspaceObserver
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FitPropertyBrowser
+    : public QDockWidget,
+      public Mantid::API::AlgorithmObserver,
+      public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 public:
   /// Constructor
-  FitPropertyBrowser(QWidget *parent = NULL, QObject* mantidui = NULL);
+  FitPropertyBrowser(QWidget *parent = NULL, QObject *mantidui = NULL);
   /// Destructor
   ~FitPropertyBrowser() override;
   /// Get handler to the root composite function
-  PropertyHandler* getHandler()const;
+  PropertyHandler *getHandler() const;
   /// Initialise layout
   virtual void init();
 
   /// Centre of the current peak
-  double centre()const;
+  double centre() const;
   /// Set centre of the current peak
   void setCentre(double value);
   /// Height of the current peak
-  double height()const;
+  double height() const;
   /// Set height of the current peak
   void setHeight(double value);
   /// Width of the current peak
-  double fwhm()const;
+  double fwhm() const;
   /// Set width of the current peak
   void setFwhm(double value);
   /// Get count
-  int count()const;
+  int count() const;
   /// Is the current function a peak?
-  bool isPeak()const;
+  bool isPeak() const;
   /// Get the current function
-  PropertyHandler* currentHandler()const;
+  PropertyHandler *currentHandler() const;
   /// Set new current function
-  void setCurrentFunction(PropertyHandler* h)const;
+  void setCurrentFunction(PropertyHandler *h) const;
   /// Get the current function
-  boost::shared_ptr<const Mantid::API::IFunction> theFunction()const;
+  boost::shared_ptr<const Mantid::API::IFunction> theFunction() const;
   /// Update the function parameters
   void updateParameters();
   /// Get function parameter values
@@ -98,120 +96,130 @@ public:
   QStringList getParameterNames() const;
 
   /// Create a new function
-  PropertyHandler* addFunction(const std::string& fnName);
+  PropertyHandler *addFunction(const std::string &fnName);
 
   /// Get Composite Function
-  boost::shared_ptr<Mantid::API::CompositeFunction> compositeFunction()const{return m_compositeFunction;}
+  boost::shared_ptr<Mantid::API::CompositeFunction> compositeFunction() const {
+    return m_compositeFunction;
+  }
 
   /// Return the fitting function
   Mantid::API::IFunction_sptr getFittingFunction() const;
 
   /// Get the default function type
-  std::string defaultFunctionType()const;
+  std::string defaultFunctionType() const;
   /// Set the default function type
-  void setDefaultFunctionType(const std::string& fnType);
+  void setDefaultFunctionType(const std::string &fnType);
   /// Get the default peak type
-  std::string defaultPeakType()const;
+  std::string defaultPeakType() const;
   /// Set the default peak type
-  void setDefaultPeakType(const std::string& fnType);
+  void setDefaultPeakType(const std::string &fnType);
   /// Get the default background type
-  std::string defaultBackgroundType()const;
+  std::string defaultBackgroundType() const;
   /// Set the default background type
-  void setDefaultBackgroundType(const std::string& fnType);
+  void setDefaultBackgroundType(const std::string &fnType);
 
   /// Get the workspace
   boost::shared_ptr<Mantid::API::Workspace> getWorkspace() const;
   /// Get the input workspace name
-  std::string workspaceName()const;
+  std::string workspaceName() const;
   /// Set the input workspace name
-  virtual void setWorkspaceName(const QString& wsName);
+  virtual void setWorkspaceName(const QString &wsName);
   /// Get workspace index
-  int workspaceIndex()const;
+  int workspaceIndex() const;
   /// Set workspace index
   void setWorkspaceIndex(int i);
   /// Get the output name
-  std::string outputName()const;
+  std::string outputName() const;
   /// Set the output name
-  void setOutputName(const std::string&);
+  void setOutputName(const std::string &);
   /// Get the minimizer
-  std::string minimizer(bool withProperties = false)const;
+  std::string minimizer(bool withProperties = false) const;
   /// Get the ignore invalid data option
   bool ignoreInvalidData() const;
   /// Set the ignore invalid data option
   void setIgnoreInvalidData(bool on);
   /// Get the cost function
-  std::string costFunction()const;
+  std::string costFunction() const;
   /// Get the "ConvolveMembers" option
-  bool convolveMembers()const;
+  bool convolveMembers() const;
   /// Set if the data must be normalised before fitting
-  void normaliseData(bool on) {m_shouldBeNormalised = on;}
+  void normaliseData(bool on) { m_shouldBeNormalised = on; }
   /// Get the max number of iterations
   int maxIterations() const;
 
   /// Get the start X
-  double startX()const;
+  double startX() const;
   /// Set the start X
   void setStartX(double);
   /// Get the end X
-  double endX()const;
+  double endX() const;
   /// Set the end X
   void setEndX(double);
   /// Set LogValue for PlotPeakByLogValue
-  void setLogValue(const QString& lv = "");
+  void setLogValue(const QString &lv = "");
   /// Get LogValue
-  std::string getLogValue()const;
+  std::string getLogValue() const;
   /// Remove LogValue from the browser
   void removeLogValue();
 
   /// Return a list of registered functions
-  const QStringList& registeredFunctions()const{return m_registeredFunctions;}
+  const QStringList &registeredFunctions() const {
+    return m_registeredFunctions;
+  }
   /// Return a list of registered peaks
-  const QStringList& registeredPeaks()const{return m_registeredPeaks;}
+  const QStringList &registeredPeaks() const { return m_registeredPeaks; }
   /// Return a list of registered backgrounds
-  const QStringList& registeredBackgrounds()const{return m_registeredBackgrounds;}
+  const QStringList &registeredBackgrounds() const {
+    return m_registeredBackgrounds;
+  }
   /// Return a list of registered other functions
-  const QStringList& registeredOthers()const{return m_registeredOther;}
+  const QStringList &registeredOthers() const { return m_registeredOther; }
 
   /// Tells if undo can be done
-  bool isUndoEnabled()const;
+  bool isUndoEnabled() const;
   /// Returns true if the function is ready for a fit
-  bool isFitEnabled()const;
+  bool isFitEnabled() const;
 
   /// Display a tip
-  void setTip(const QString& txt);
+  void setTip(const QString &txt);
 
   /// return groupMember
-  //const std::string groupMember() const {return m_groupMember;};
-  /// alter text of Plot Guess 
+  // const std::string groupMember() const {return m_groupMember;};
+  /// alter text of Plot Guess
   void setTextPlotGuess(const QString text);
 
   /// Creates the "Ties" property value for the Fit algorithm
-  QString getTieString()const;
+  QString getTieString() const;
 
   /// Creates the "Constraints" property value for the Fit algorithm
-  QString getConstraintsString()const;
+  QString getConstraintsString() const;
 
   // send parameterChanged signal
-  void sendParameterChanged(const Mantid::API::IFunction* f){emit parameterChanged(f);}
+  void sendParameterChanged(const Mantid::API::IFunction *f) {
+    emit parameterChanged(f);
+  }
 
   /// Creates and adds the autobackground
   void addAutoBackground();
-  bool isAutoBack()const{return m_autoBackground!=NULL;}
-  void setAutoBackgroundName(const QString& aName);
+  bool isAutoBack() const { return m_autoBackground != NULL; }
+  void setAutoBackgroundName(const QString &aName);
   void refitAutoBackground();
-  QString getAutoBackgroundString()const{return m_autoBgName + " " + m_autoBgAttributes;}
+  QString getAutoBackgroundString() const {
+    return m_autoBgName + " " + m_autoBgAttributes;
+  }
 
   /// Number of decimal places in double properties
-  int getDecimals()const{return m_decimals;}
+  int getDecimals() const { return m_decimals; }
   void setDecimals(int d);
 
   /// Returns true if the difference plot should be drawn
-  bool plotDiff()const;
+  bool plotDiff() const;
   /// Returns true if a composite's member functions should be plotted also
   bool plotCompositeMembers() const;
 
-  /// Returns true if the fit should be done against binned (bunched) data.  	
-  bool rawData()const;
+  /// Returns true if the fit should be done against binned (bunched) data.
+  bool rawData() const;
 
   void setADSObserveEnabled(bool enabled);
 
@@ -222,11 +230,11 @@ public:
   /// Called when the Fit is finished
   void finishHandle(const Mantid::API::IAlgorithm *alg) override;
 
-  /// Returns the list of workspaces that are currently been worked on by the fit property browser.
+  /// Returns the list of workspaces that are currently been worked on by the
+  /// fit property browser.
   QStringList getWorkspaceNames();
   /// Create a MatrixWorkspace from a TableWorkspace
-  Mantid::API::Workspace_sptr createMatrixFromTableWorkspace()const;
-
+  Mantid::API::Workspace_sptr createMatrixFromTableWorkspace() const;
 
 public slots:
   virtual void fit();
@@ -236,38 +244,39 @@ public slots:
   void clearBrowser();
   void setPeakToolOn(bool on);
   void findPeaks();
-  void executeFitMenu(const QString&);
-  void executeDisplayMenu(const QString&);
-  void executeSetupMenu(const QString&);
-  void executeSetupManageMenu(const QString&);
+  void executeFitMenu(const QString &);
+  void executeDisplayMenu(const QString &);
+  void executeSetupMenu(const QString &);
+  void executeSetupManageMenu(const QString &);
 
 signals:
-  void currentChanged()const;
+  void currentChanged() const;
   void functionRemoved();
-  void algorithmFinished(const QString&);
+  void algorithmFinished(const QString &);
   void workspaceIndexChanged(int i);
-  void workspaceNameChanged(const QString&);
+  void workspaceNameChanged(const QString &);
 
-  void wsChangePPAssign(const QString&);
+  void wsChangePPAssign(const QString &);
   void functionChanged();
 
   void startXChanged(double);
   void endXChanged(double);
   void xRangeChanged(double, double);
-  void parameterChanged(const Mantid::API::IFunction*);
+  void parameterChanged(const Mantid::API::IFunction *);
   void functionCleared();
   void plotGuess();
   void plotCurrentGuess();
   void removeGuess();
   void removeCurrentGuess();
-  void changeWindowTitle(const QString&);
-  void removePlotSignal(MantidQt::MantidWidgets::PropertyHandler*);
+  void changeWindowTitle(const QString &);
+  void removePlotSignal(MantidQt::MantidWidgets::PropertyHandler *);
   void removeFitCurves();
 
-  void executeFit(QString,QHash<QString,QString>,Mantid::API::AlgorithmObserver*);
+  void executeFit(QString, QHash<QString, QString>,
+                  Mantid::API::AlgorithmObserver *);
   void multifitFinished();
 
-  /// signal which can optionally be caught for customization after a fit has 
+  /// signal which can optionally be caught for customization after a fit has
   /// been done
   void fittingDone(QString);
   void functionFactoryUpdateReceived();
@@ -278,17 +287,17 @@ protected slots:
 
 private slots:
 
-  void enumChanged(QtProperty* prop);
-  void boolChanged(QtProperty* prop);
-  void intChanged(QtProperty* prop);
-  virtual void doubleChanged(QtProperty* prop);
+  void enumChanged(QtProperty *prop);
+  void boolChanged(QtProperty *prop);
+  void intChanged(QtProperty *prop);
+  virtual void doubleChanged(QtProperty *prop);
   /// Called when one of the parameter values gets changed
-  void parameterChanged(QtProperty* prop);
-  void stringChanged(QtProperty* prop);
-  void filenameChanged(QtProperty* prop);
-  void columnChanged(QtProperty* prop);
-  void currentItemChanged(QtBrowserItem*);
-  void vectorDoubleChanged(QtProperty* prop);
+  void parameterChanged(QtProperty *prop);
+  void stringChanged(QtProperty *prop);
+  void filenameChanged(QtProperty *prop);
+  void columnChanged(QtProperty *prop);
+  void currentItemChanged(QtBrowserItem *);
+  void vectorDoubleChanged(QtProperty *prop);
   void addTie();
   void addTieToFunction();
   void addFixTie();
@@ -296,7 +305,7 @@ private slots:
   void addLowerBound10();
   void addLowerBound50();
   void addLowerBound();
-  void addConstraint(int f,bool lo,bool up);
+  void addConstraint(int f, bool lo, bool up);
   void addUpperBound10();
   void addUpperBound50();
   void addUpperBound();
@@ -315,11 +324,14 @@ private slots:
   void loadFunctionFromString();
   void acceptFit();
   void closeFit();
-  void copy();///< Copy the function string to the clipboard
-  void paste();///< Paste a function string from the clipboard
-  void reset();///< reset the function part, renew function, all handlers are new
-  void functionHelp(); ///< Open a web page with description of the current function
-  void browserHelp();  ///< Open a web page with description of FitPropertyBrowser
+  void copy();  ///< Copy the function string to the clipboard
+  void paste(); ///< Paste a function string from the clipboard
+  void
+  reset(); ///< reset the function part, renew function, all handlers are new
+  void
+  functionHelp(); ///< Open a web page with description of the current function
+  void
+  browserHelp(); ///< Open a web page with description of FitPropertyBrowser
 
   void popupMenu(const QPoint &);
   /* Context menu slots */
@@ -330,8 +342,8 @@ private slots:
   /// Process and create some output if it is a MultiBG fit
   void processMultiBGResults();
 
-  void executeCustomSetupLoad(const QString& name);
-  void executeCustomSetupRemove(const QString& name);
+  void executeCustomSetupLoad(const QString &name);
+  void executeCustomSetupRemove(const QString &name);
 
   /// Update structure tooltips for all functions
   void updateStructureTooltips();
@@ -350,19 +362,20 @@ protected:
   ///
   void updateDecimals();
   /// Sets the workspace to a function
-  void setWorkspace(boost::shared_ptr<Mantid::API::IFunction> f)const;
+  void setWorkspace(boost::shared_ptr<Mantid::API::IFunction> f) const;
   /// Display properties relevant to the selected workspace
   void setWorkspaceProperties();
 
   /// Create a double property and set some settings
-  QtProperty* addDoubleProperty(const QString& name, QtDoublePropertyManager *manager = NULL)const;
+  QtProperty *addDoubleProperty(const QString &name,
+                                QtDoublePropertyManager *manager = NULL) const;
   /// Called when the minimizer changes. Creates minimizes's properties.
   void minimizerChanged();
   /// Do the fitting
   void doFit(int maxIterations);
 
   /// Property managers:
-  QtGroupPropertyManager  *m_groupManager;
+  QtGroupPropertyManager *m_groupManager;
   QtDoublePropertyManager *m_doubleManager;
   QtEnumPropertyManager *m_enumManager;
   QtIntPropertyManager *m_intManager;
@@ -371,7 +384,7 @@ protected:
   QtStringPropertyManager *m_filenameManager;
   QtStringPropertyManager *m_formulaManager;
   QtEnumPropertyManager *m_columnManager;
-  QtGroupPropertyManager  *m_vectorManager;
+  QtGroupPropertyManager *m_vectorManager;
   QtIntPropertyManager *m_vectorSizeManager;
   QtDoublePropertyManager *m_vectorDoubleManager;
   ParameterPropertyManager *m_parameterManager;
@@ -394,31 +407,33 @@ protected:
   QtProperty *m_yColumn;
   QtProperty *m_errColumn;
   QtProperty *m_showParamErrors;
-  QList<QtProperty*> m_minimizerProperties;
+  QList<QtProperty *> m_minimizerProperties;
 
   /// A copy of the edited function
   boost::shared_ptr<Mantid::API::CompositeFunction> m_compositeFunction;
 
-  QtTreePropertyBrowser* m_browser;
+  QtTreePropertyBrowser *m_browser;
 
-  QAction* m_fitActionUndoFit;
-  QAction* m_fitActionSeqFit;
-  QAction* m_fitActionFit;
-  QAction* m_fitActionEvaluate;
+  QAction *m_fitActionUndoFit;
+  QAction *m_fitActionSeqFit;
+  QAction *m_fitActionFit;
+  QAction *m_fitActionEvaluate;
 
   /// Group for functions
-  QtBrowserItem* m_functionsGroup;
+  QtBrowserItem *m_functionsGroup;
   /// Group for input/output settings
-  QtBrowserItem* m_settingsGroup;
+  QtBrowserItem *m_settingsGroup;
   /// Group for custom options available on muon analysis widget
-  QtBrowserItem* m_customSettingsGroup;
+  QtBrowserItem *m_customSettingsGroup;
 
-  /// If false the change-slots (such as enumChanged(), doubleChanged()) are disabled
+  /// If false the change-slots (such as enumChanged(), doubleChanged()) are
+  /// disabled
   bool m_changeSlotsEnabled;
-  /// if true the output name will be guessed every time workspace name is changeed
+  /// if true the output name will be guessed every time workspace name is
+  /// changeed
   bool m_guessOutputName;
   /// Check if the input workspace is a group
-  bool isWorkspaceAGroup()const;
+  bool isWorkspaceAGroup() const;
 
   /// A list of registered functions
   mutable QStringList m_registeredFunctions;
@@ -429,7 +444,7 @@ protected:
   /// A list of registered functions that are neither peaks nor backgrounds
   mutable QStringList m_registeredOther;
   /// A list of available minimizers
-  mutable QStringList m_minimizers;  
+  mutable QStringList m_minimizers;
   /// A list of available workspaces
   mutable QStringList m_workspaceNames;
   /// A list of available cost functions
@@ -440,14 +455,14 @@ protected:
 
 private:
   /// load and save function
-  void loadFunction(const QString& funcString);
-  void saveFunction(const QString& fnName);
+  void loadFunction(const QString &funcString);
+  void saveFunction(const QString &fnName);
   /// Create CompositeFunction
-  void createCompositeFunction(const QString& str = "");
+  void createCompositeFunction(const QString &str = "");
   /// Check if the workspace can be used in the fit
-  virtual bool isWorkspaceValid(Mantid::API::Workspace_sptr)const;
-  /// Find QtBrowserItem for a property prop among the chidren of 
-  QtBrowserItem* findItem(QtBrowserItem* parent,QtProperty* prop)const;
+  virtual bool isWorkspaceValid(Mantid::API::Workspace_sptr) const;
+  /// Find QtBrowserItem for a property prop among the chidren of
+  QtBrowserItem *findItem(QtBrowserItem *parent, QtProperty *prop) const;
   /// Set the parameters to the fit outcome
   void getFitResults();
   /// disable undo when the function changes
@@ -455,58 +470,59 @@ private:
   /// Enable/disable the Fit button;
   virtual void setFitEnabled(bool yes);
   /// Create a string property and set some settings
-  QtProperty* addStringProperty(const QString& name)const;
-  void setStringPropertyValue(QtProperty* prop,const QString& value)const;
-  QString getStringPropertyValue(QtProperty* prop)const;
+  QtProperty *addStringProperty(const QString &name) const;
+  void setStringPropertyValue(QtProperty *prop, const QString &value) const;
+  QString getStringPropertyValue(QtProperty *prop) const;
   /// Check that the properties match the function
   void checkFunction();
 
-  void setCurrentFunction(Mantid::API::IFunction_const_sptr f)const;
+  void setCurrentFunction(Mantid::API::IFunction_const_sptr f) const;
 
   /// Sets the new workspace to the current one
-  virtual void workspaceChange(const QString& wsName);
+  virtual void workspaceChange(const QString &wsName);
 
   /// Does a parameter have a tie
-  void hasConstraints(QtProperty* parProp,bool& hasTie,bool& hasBounds)const;
+  void hasConstraints(QtProperty *parProp, bool &hasTie, bool &hasBounds) const;
   /// Returns the tie property for a parameter property, or NULL
-  QtProperty* getTieProperty(QtProperty* parProp)const;
+  QtProperty *getTieProperty(QtProperty *parProp) const;
 
   /// Callback for FunctionFactory update notifications
   void handleFactoryUpdate(Mantid::API::FunctionFactoryUpdateNotification_ptr);
   /// Observes algorithm factory update notifications
   Poco::NObserver<FitPropertyBrowser,
-                  Mantid::API::FunctionFactoryUpdateNotification> m_updateObserver;
-
+                  Mantid::API::FunctionFactoryUpdateNotification>
+      m_updateObserver;
 
   /// Make sure m_groupMember belongs to the group
-  //void validateGroupMember();
+  // void validateGroupMember();
 
   /// Fit and Display menu
-  QSignalMapper* m_fitMapper;
-  QMenu* m_fitMenu;
-  QAction* m_displayActionPlotGuess;
-  QAction* m_displayActionQuality;
-  QAction* m_displayActionClearAll;
+  QSignalMapper *m_fitMapper;
+  QMenu *m_fitMenu;
+  QAction *m_displayActionPlotGuess;
+  QAction *m_displayActionQuality;
+  QAction *m_displayActionClearAll;
   QString m_windowBaseString;
 
   /// Setup menu
-  QAction* m_setupActionCustomSetup;
-  QAction* m_setupActionRemove; 
+  QAction *m_setupActionCustomSetup;
+  QAction *m_setupActionRemove;
   void updateSetupMenus();
 
   /// To display a tip text
-  QLabel* m_tip;
+  QLabel *m_tip;
 
   // The widget for choosing the fit function.
-  QDialog* m_fitSelector;
+  QDialog *m_fitSelector;
   // The tree widget containing the fit functions.
-  QTreeWidget* m_fitTree;
-  
-  /// String property managers for special case attributes such as Filename or Formula
+  QTreeWidget *m_fitTree;
+
+  /// String property managers for special case attributes such as Filename or
+  /// Formula
   /// <attribute_name,string_manager>
-  QMap<QString,QtStringPropertyManager*> m_stringManagers;
+  QMap<QString, QtStringPropertyManager *> m_stringManagers;
 
-  mutable PropertyHandler* m_currentHandler;
+  mutable PropertyHandler *m_currentHandler;
 
   /// A list of available data types
   mutable QStringList m_dataTypes;
@@ -529,15 +545,17 @@ private:
 
   /// Name of the autobackground function
   QString m_autoBgName;
-  /// List of attributes of the autobackground function as name=value pairs separated by spaces
+  /// List of attributes of the autobackground function as name=value pairs
+  /// separated by spaces
   QString m_autoBgAttributes;
 
   /// The autobackground handler
-  PropertyHandler* m_autoBackground;
+  PropertyHandler *m_autoBackground;
 
-  /// if isWorkspaceAGroup() is true m_groupMember keeps name of the MatrixWorkspace
-  /// fitted with theFunction() 
-  //std::string m_groupMember;
+  /// if isWorkspaceAGroup() is true m_groupMember keeps name of the
+  /// MatrixWorkspace
+  /// fitted with theFunction()
+  // std::string m_groupMember;
 
   /// Log names
   QStringList m_logs;
@@ -546,7 +564,7 @@ private:
   int m_decimals;
 
   /// holds effectively a MantidUI for connecting
-  QObject* m_mantidui;
+  QObject *m_mantidui;
 
   /// store current workspace name
   std::string m_storedWorkspaceName;
@@ -559,10 +577,8 @@ private:
   friend class SetAttribute;
   friend class SetAttributeProperty;
   friend class SequentialFitDialog;
-
 };
 
-
 } // MantidQt
 } // API
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FormulaDialogEditor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FormulaDialogEditor.h
index 737ef03db66baefd5bbe40836cfc4fca10b9e42b..faf3eb5b5b088f1edaa6279e4aac37254fd228f0 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FormulaDialogEditor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FormulaDialogEditor.h
@@ -3,20 +3,17 @@
 
 #include "MantidQtMantidWidgets/StringDialogEditor.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
  * A stringDialogEditor for editing UserFunction.
  */
-class FormulaDialogEditor: public StringDialogEditor
-{
+class FormulaDialogEditor : public StringDialogEditor {
   Q_OBJECT
 public:
   FormulaDialogEditor(QtProperty *property, QWidget *parent)
-    :StringDialogEditor(property,parent){}
+      : StringDialogEditor(property, parent) {}
 protected slots:
   void runDialog() override;
 };
@@ -24,19 +21,19 @@ protected slots:
 /**
  * The factory for the FormulaDialogEditor.
  */
-class FormulaDialogEditorFactory: public StringDialogEditorFactory
-{
+class FormulaDialogEditorFactory : public StringDialogEditorFactory {
   Q_OBJECT
 public:
-  FormulaDialogEditorFactory(QObject* parent):StringDialogEditorFactory(parent){}
+  FormulaDialogEditorFactory(QObject *parent)
+      : StringDialogEditorFactory(parent) {}
+
 protected:
   QWidget *createEditorForManager(QtStringPropertyManager *,
                                   QtProperty *property,
                                   QWidget *parent) override {
-    return new FormulaDialogEditor(property,parent);
+    return new FormulaDialogEditor(property, parent);
   }
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FunctionBrowser.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FunctionBrowser.h
index 9e2405fe600d01fd51ec72cf45371cb97e1e666b..933c0274bfa95a7f5d98bf0712bf34fb4af50243 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FunctionBrowser.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/FunctionBrowser.h
@@ -10,7 +10,7 @@
 
 #include <boost/optional.hpp>
 
-    /* Forward declarations */
+/* Forward declarations */
 
 class QtTreePropertyBrowser;
 class QtGroupPropertyManager;
@@ -32,52 +32,44 @@ class QMenu;
 class QAction;
 class QTreeWidget;
 
-namespace Mantid
-{
-  namespace API
-  {
-    class CompositeFunction;
-    class Workspace;
-    class ParameterTie;
-  }
+namespace Mantid {
+namespace API {
+class CompositeFunction;
+class Workspace;
+class ParameterTie;
+}
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 class CreateAttributePropertyForFunctionBrowser;
 
 /**
- * Class FitPropertyBrowser implements QtPropertyBrowser to display 
+ * Class FitPropertyBrowser implements QtPropertyBrowser to display
  * and control fitting function parameters and settings.
- * 
+ *
  * @date 18/04/2012
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FunctionBrowser: public QWidget
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS FunctionBrowser : public QWidget {
   Q_OBJECT
 public:
   /// To keep QtProperty and its QtBrowserItem in one place
-  struct AProperty
-  {
+  struct AProperty {
     QtProperty *prop;
     QtBrowserItem *item;
     QtProperty *parent;
   };
   /// Tie structure
-  struct ATie
-  {
+  struct ATie {
     QtProperty *paramProp; ///< Parameter property
     QtProperty *tieProp;   ///< Tie property
   };
   /// Constraint structure
-  struct AConstraint
-  {
+  struct AConstraint {
     QtProperty *paramProp; ///< Parameter property
-    QtProperty *lower;   ///< Constraint property
-    QtProperty *upper;   ///< Constraint property
+    QtProperty *lower;     ///< Constraint property
+    QtProperty *upper;     ///< Constraint property
   };
 
   /// Constructor
@@ -87,36 +79,41 @@ public:
   /// Clear the contents
   void clear();
   /// Set the function in the browser
-  void setFunction(const QString& funStr);
+  void setFunction(const QString &funStr);
   /// Set the function in the browser
   void setFunction(Mantid::API::IFunction_sptr fun);
   /// Return FunctionFactory function string
   QString getFunctionString();
   /// Return the function
-  Mantid::API::IFunction_sptr getFunction(QtProperty* prop = NULL, bool attributesOnly = false);
+  Mantid::API::IFunction_sptr getFunction(QtProperty *prop = NULL,
+                                          bool attributesOnly = false);
   /// Check if a function is set
   bool hasFunction() const;
 
   /// Return a function with specified index
-  Mantid::API::IFunction_sptr getFunctionByIndex(const QString& index);
+  Mantid::API::IFunction_sptr getFunctionByIndex(const QString &index);
 
   /// Return index of the current function, if one is selected
-  boost::optional<QString> currentFunctionIndex() { return m_currentFunctionIndex; }
+  boost::optional<QString> currentFunctionIndex() {
+    return m_currentFunctionIndex;
+  }
 
   /// Update the function parameter value
-  void setParameter(const QString& funcIndex, const QString& paramName, double value);
+  void setParameter(const QString &funcIndex, const QString &paramName,
+                    double value);
   /// Update the function parameter error
-  void setParamError(const QString& funcIndex, const QString& paramName, double error);
+  void setParamError(const QString &funcIndex, const QString &paramName,
+                     double error);
   /// Get a value of a parameter
-  double getParameter(const QString& funcIndex, const QString& paramName) const;
+  double getParameter(const QString &funcIndex, const QString &paramName) const;
   /// Update the function parameter value
-  void setParameter(const QString& paramName, double value);
+  void setParameter(const QString &paramName, double value);
   /// Update the function parameter error
-  void setParamError(const QString& paramName, double error);
+  void setParamError(const QString &paramName, double error);
   /// Get a value of a parameter
-  double getParameter(const QString& paramName) const;
+  double getParameter(const QString &paramName) const;
   /// Update parameter values in the browser to match those of a function.
-  void updateParameters(const Mantid::API::IFunction& fun);
+  void updateParameters(const Mantid::API::IFunction &fun);
 
   /// Get a list of names of global parameters
   QStringList getGlobalParameters() const;
@@ -125,22 +122,22 @@ public:
   /// Get the number of datasets
   int getNumberOfDatasets() const;
   /// Get value of a local parameter
-  double getLocalParameterValue(const QString& parName, int i) const;
+  double getLocalParameterValue(const QString &parName, int i) const;
   /// Set value of a local parameter
-  void setLocalParameterValue(const QString& parName, int i, double value);
+  void setLocalParameterValue(const QString &parName, int i, double value);
   /// Check if a local parameter is fixed
-  bool isLocalParameterFixed(const QString& parName, int i) const;
+  bool isLocalParameterFixed(const QString &parName, int i) const;
   /// Fix/unfix local parameter
-  void setLocalParameterFixed(const QString& parName, int i, bool fixed);
+  void setLocalParameterFixed(const QString &parName, int i, bool fixed);
   /// Get the tie for a local parameter.
-  QString getLocalParameterTie(const QString& parName, int i) const;
+  QString getLocalParameterTie(const QString &parName, int i) const;
   /// Set a tie for a local parameter.
-  void setLocalParameterTie(const QString& parName, int i, QString tie);
+  void setLocalParameterTie(const QString &parName, int i, QString tie);
 
   /// Return the multidomain function if number of datasets is greater than 1
   Mantid::API::IFunction_sptr getGlobalFunction();
   /// Update parameter values in the browser to match those of a function.
-  void updateMultiDatasetParameters(const Mantid::API::IFunction& fun);
+  void updateMultiDatasetParameters(const Mantid::API::IFunction &fun);
 
   /// Resize the browser's columns
   void setColumnSizes(int s0, int s1, int s2 = -1);
@@ -152,10 +149,10 @@ signals:
   /// Function parameter gets changed
   /// @param funcIndex :: Index of the changed function
   /// @param paramName :: Name of the changed parameter
-  void parameterChanged(const QString& funcIndex, const QString& paramName);
+  void parameterChanged(const QString &funcIndex, const QString &paramName);
 
   /// In multi-dataset context a button value editor was clicked
-  void localParameterButtonClicked(const QString& parName);
+  void localParameterButtonClicked(const QString &parName);
 
   void functionStructureChanged();
   void globalsChanged();
@@ -175,90 +172,96 @@ protected:
   /// Create and connect actions
   void createActions();
   /// Add a sub-property
-  AProperty addProperty(QtProperty* parent, QtProperty* subproperty);
+  AProperty addProperty(QtProperty *parent, QtProperty *subproperty);
   /// Remove and delete property
   void removeProperty(QtProperty *prop);
   /// Set a function
-  void setFunction(QtProperty* prop, Mantid::API::IFunction_sptr fun);
+  void setFunction(QtProperty *prop, Mantid::API::IFunction_sptr fun);
   /// Add a function
-  void addFunction(QtProperty* prop, Mantid::API::IFunction_sptr fun);
+  void addFunction(QtProperty *prop, Mantid::API::IFunction_sptr fun);
   /// Add a function property
-  AProperty addFunctionProperty(QtProperty* parent, QString funName);
+  AProperty addFunctionProperty(QtProperty *parent, QString funName);
   /// Add a parameter property
-  AProperty addParameterProperty(QtProperty* parent, QString paramName, QString paramDesc, double paramValue);
+  AProperty addParameterProperty(QtProperty *parent, QString paramName,
+                                 QString paramDesc, double paramValue);
   /// Add a attribute property
-  AProperty addAttributeProperty(QtProperty* parent, QString attName, const Mantid::API::IFunction::Attribute& att);
+  AProperty addAttributeProperty(QtProperty *parent, QString attName,
+                                 const Mantid::API::IFunction::Attribute &att);
   /// Add attribute and parameter properties to a function property
-  void addAttributeAndParameterProperties(QtProperty* prop, Mantid::API::IFunction_sptr fun);
+  void addAttributeAndParameterProperties(QtProperty *prop,
+                                          Mantid::API::IFunction_sptr fun);
   /// Add property showing function's index in the composite function
-  AProperty addIndexProperty(QtProperty* prop);
-  /// Update function index properties 
-  void updateFunctionIndices(QtProperty* prop = NULL, QString index = "");
+  AProperty addIndexProperty(QtProperty *prop);
+  /// Update function index properties
+  void updateFunctionIndices(QtProperty *prop = NULL, QString index = "");
   /// Get property of the overall function
   AProperty getFunctionProperty() const;
   /// Check if property is a function group
-  bool isFunction(QtProperty* prop) const;
+  bool isFunction(QtProperty *prop) const;
   /// Check if property is a function attribute
-  bool isAttribute(QtProperty* prop) const;
+  bool isAttribute(QtProperty *prop) const;
   /// Check if property is a string attribute
-  bool isStringAttribute(QtProperty* prop) const;
+  bool isStringAttribute(QtProperty *prop) const;
   /// Check if property is a double attribute
-  bool isDoubleAttribute(QtProperty* prop) const;
+  bool isDoubleAttribute(QtProperty *prop) const;
   /// Check if property is a int attribute
-  bool isIntAttribute(QtProperty* prop) const;
+  bool isIntAttribute(QtProperty *prop) const;
   /// Check if property is a bool attribute
-  bool isBoolAttribute(QtProperty* prop) const;
+  bool isBoolAttribute(QtProperty *prop) const;
   /// Check if property is a vector attribute
-  bool isVectorAttribute(QtProperty* prop) const;
+  bool isVectorAttribute(QtProperty *prop) const;
   /// Check if property is a function paramater
-  bool isParameter(QtProperty* prop) const;
+  bool isParameter(QtProperty *prop) const;
   /// Get attribute as a string
-  double getParameter(QtProperty* prop) const;
+  double getParameter(QtProperty *prop) const;
   /// Check if a property is an index
-  bool isIndex(QtProperty* prop) const;
+  bool isIndex(QtProperty *prop) const;
   /// Get the function index for a property
-  QString getIndex(QtProperty* prop) const;
+  QString getIndex(QtProperty *prop) const;
   /// Get name of the parameter for a property
-  QString getParameterName(QtProperty* prop);
+  QString getParameterName(QtProperty *prop);
   /// Get function property for the index
-  QtProperty* getFunctionProperty(const QString& index)const;
-  /// Split a qualified parameter name into function index and local parameter name.
-  QStringList splitParameterName(const QString& paramName) const;
+  QtProperty *getFunctionProperty(const QString &index) const;
+  /// Split a qualified parameter name into function index and local parameter
+  /// name.
+  QStringList splitParameterName(const QString &paramName) const;
   /// Get a property for a parameter
-  QtProperty* getParameterProperty(const QString& paramName) const;
+  QtProperty *getParameterProperty(const QString &paramName) const;
   /// Get a property for a parameter
-  QtProperty* getParameterProperty(const QString& funcIndex, const QString& paramName) const;
+  QtProperty *getParameterProperty(const QString &funcIndex,
+                                   const QString &paramName) const;
   /// Get a tie property attached to a parameter property
-  QtProperty* getTieProperty(QtProperty* prop) const;
+  QtProperty *getTieProperty(QtProperty *prop) const;
 
   /// Add a tie property
-  AProperty addTieProperty(QtProperty* prop, QString tie);
+  AProperty addTieProperty(QtProperty *prop, QString tie);
   /// Check if a parameter property has a tie
-  bool hasTie(QtProperty* prop) const;
+  bool hasTie(QtProperty *prop) const;
   /// Check if a property is a tie
-  bool isTie(QtProperty* prop) const;
+  bool isTie(QtProperty *prop) const;
   /// Get a tie for a paramater
-  std::string getTie(QtProperty* prop) const;
+  std::string getTie(QtProperty *prop) const;
   /// Remove all local tie properties
   void removeAllLocalTieProperties();
 
   /// Add a constraint property
-  QList<AProperty> addConstraintProperties(QtProperty* prop, QString constraint);
+  QList<AProperty> addConstraintProperties(QtProperty *prop,
+                                           QString constraint);
   /// Check if a property is a constraint
-  bool isConstraint(QtProperty* prop) const;
+  bool isConstraint(QtProperty *prop) const;
   /// Check if a parameter property has a constraint
-  bool hasConstraint(QtProperty* prop) const;
+  bool hasConstraint(QtProperty *prop) const;
   /// Check if a parameter property has a lower bound
-  bool hasLowerBound(QtProperty* prop) const;
+  bool hasLowerBound(QtProperty *prop) const;
   /// Check if a parameter property has a upper bound
-  bool hasUpperBound(QtProperty* prop) const;
+  bool hasUpperBound(QtProperty *prop) const;
 
   /// Initialize storage and values for local parameters
-  void initLocalParameter(const QString& parName)const;
+  void initLocalParameter(const QString &parName) const;
   /// Make sure that the parameter is initialized
-  void checkLocalParameter(const QString& parName)const;
+  void checkLocalParameter(const QString &parName) const;
   /// Make sure that properties are in sync with the cached ties
-  void updateLocalTie(const QString& parName);
+  void updateLocalTie(const QString &parName);
 
 protected slots:
   /// Show the context menu
@@ -293,19 +296,19 @@ protected slots:
   //   Property change slots
 
   /// Called when a function attribute property is changed
-  void attributeChanged(QtProperty*);
+  void attributeChanged(QtProperty *);
   /// Called when a member of a vector attribute is changed
-  void attributeVectorDoubleChanged(QtProperty*);
+  void attributeVectorDoubleChanged(QtProperty *);
   /// Called when a function parameter property is changed
-  void parameterChanged(QtProperty*);
+  void parameterChanged(QtProperty *);
   /// Called when button in local parameter editor was clicked
-  void parameterButtonClicked(QtProperty*);
+  void parameterButtonClicked(QtProperty *);
   /// Called when a tie property changes
-  void tieChanged(QtProperty*);
+  void tieChanged(QtProperty *);
   /// Called when "Global" check-box was clicked
-  void globalChanged(QtProperty*, const QString&, bool);
+  void globalChanged(QtProperty *, const QString &, bool);
   /// Set value of an attribute (as a property) to a function
-  void setAttributeToFunction(Mantid::API::IFunction& fun, QtProperty* prop);
+  void setAttributeToFunction(Mantid::API::IFunction &fun, QtProperty *prop);
 
 protected:
   /// Manager for function group properties
@@ -339,15 +342,14 @@ protected:
   /// Manager for vector attribute size properties
   QtIntPropertyManager *m_attributeSizeManager;
 
-
   /// Qt property browser which displays properties
-  QtTreePropertyBrowser* m_browser;
+  QtTreePropertyBrowser *m_browser;
   /// Store all properties in a map for easy access
-  QMap<QtProperty*,AProperty> m_properties;
+  QMap<QtProperty *, AProperty> m_properties;
   /// Store parameter ties. Keys are function properties.
-  QMultiMap<QtProperty*,ATie> m_ties;
+  QMultiMap<QtProperty *, ATie> m_ties;
   /// Store parameter constraints. Keys are function properties.
-  QMultiMap<QtProperty*,AConstraint> m_constraints;
+  QMultiMap<QtProperty *, AConstraint> m_constraints;
 
   //   Actions
 
@@ -376,24 +378,24 @@ protected:
   /// Remove one constraints from current parameter
   QAction *m_actionRemoveConstraint;
 
-  /// Index of currently selected function. Gets updated in updateCurrentFunctionIndex()
+  /// Index of currently selected function. Gets updated in
+  /// updateCurrentFunctionIndex()
   boost::optional<QString> m_currentFunctionIndex;
 
-
-  struct LocalParameterData
-  {
-    explicit LocalParameterData(double v = 0.0):value(v),fixed(false){}
+  struct LocalParameterData {
+    explicit LocalParameterData(double v = 0.0) : value(v), fixed(false) {}
     double value;
     bool fixed;
     QString tie;
   };
 
-  /// Set true if the constructed function is intended to be used in a multi-dataset fit
+  /// Set true if the constructed function is intended to be used in a
+  /// multi-dataset fit
   bool m_multiDataset;
   /// Number of datasets this function is used for
   int m_numberOfDatasets;
   /// Storage for local paramter values
-  mutable QMap<QString,QVector<LocalParameterData>> m_localParameterValues;
+  mutable QMap<QString, QVector<LocalParameterData>> m_localParameterValues;
   /// Index of a dataset for which the parameters are currently displayed
   int m_currentDataset;
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintStrategy.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintStrategy.h
index 11cbc6cb34ff774c27d883d760a582afce752ce7..5fa7c0c05d9162a562dd829583da93b72ea91c18 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintStrategy.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintStrategy.h
@@ -4,45 +4,44 @@
 #include <map>
 #include <string>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /** HintStrategy : Provides an interface for generating hints to be used by a HintingLineEdit.
-
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class HintStrategy
-    {
-    public:
-      HintStrategy() {};
-      virtual ~HintStrategy() {};
-
-      /** Create a list of hints for auto completion
-
-          @returns A map of keywords to short descriptions for the keyword.
-       */
-      virtual std::map<std::string,std::string> createHints() = 0;
-    };
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+/** HintStrategy : Provides an interface for generating hints to be used by a
+HintingLineEdit.
+
+Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class HintStrategy {
+public:
+  HintStrategy(){};
+  virtual ~HintStrategy(){};
+
+  /** Create a list of hints for auto completion
+
+      @returns A map of keywords to short descriptions for the keyword.
+   */
+  virtual std::map<std::string, std::string> createHints() = 0;
+};
+}
 }
 
 #endif /* MANTID_MANTIDWIDGETS_HINTSTRATEGY_H */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEdit.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEdit.h
index 443febb6366d42bb2456d9fc59b9bd323cd3a2d3..c381f4a1df7460182598d733a41c9ca531bba577 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEdit.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEdit.h
@@ -12,58 +12,57 @@
 //------------------------------------------------------------------------------
 // Forward declaration
 //------------------------------------------------------------------------------
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /** HintingLineEdit : A QLineEdit widget providing autocompletion.
+namespace MantidQt {
+namespace MantidWidgets {
+/** HintingLineEdit : A QLineEdit widget providing autocompletion.
 
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS HintingLineEdit : public QLineEdit
-    {
-      Q_OBJECT
-    public:
-      HintingLineEdit(QWidget *parent, const std::map<std::string,std::string> &hints);
-      ~HintingLineEdit() override;
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS HintingLineEdit : public QLineEdit {
+  Q_OBJECT
+public:
+  HintingLineEdit(QWidget *parent,
+                  const std::map<std::string, std::string> &hints);
+  ~HintingLineEdit() override;
 
-    protected:
-      void keyPressEvent(QKeyEvent *e) override;
-      void updateMatches();
-      void showToolTip();
-      void insertSuggestion();
-      void clearSuggestion();
-      void nextSuggestion();
-      void prevSuggestion();
-      std::string m_curKey;
-      std::string m_curMatch;
-      std::map<std::string,std::string> m_matches;
-      std::map<std::string,std::string> m_hints;
-      bool m_dontComplete;
-      QLabel* m_hintLabel;
-    protected slots:
-      void updateHints(const QString &text);
-      void hideHints();
-    };
-  } //namespace MantidWidgets
-} //namepsace MantidQt
+protected:
+  void keyPressEvent(QKeyEvent *e) override;
+  void updateMatches();
+  void showToolTip();
+  void insertSuggestion();
+  void clearSuggestion();
+  void nextSuggestion();
+  void prevSuggestion();
+  std::string m_curKey;
+  std::string m_curMatch;
+  std::map<std::string, std::string> m_matches;
+  std::map<std::string, std::string> m_hints;
+  bool m_dontComplete;
+  QLabel *m_hintLabel;
+protected slots:
+  void updateHints(const QString &text);
+  void hideHints();
+};
+} // namespace MantidWidgets
+} // namepsace MantidQt
 
 #endif /* MANTID_MANTIDWIDGETS_HINTINGLINEEDIT_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEditFactory.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEditFactory.h
index c6463f74dce8ff2e428ff71220bbfad484aecb76..a8eb66470e8e29aeeb91d68739c284687db06ab6 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEditFactory.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/HintingLineEditFactory.h
@@ -12,50 +12,51 @@ using namespace Mantid::API;
 using namespace Mantid::Kernel;
 using namespace MantidQt::MantidWidgets;
 
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /** HintingLineEditFactory : A QStyledItemDelegate that produces HintingLineEdits using the given hint strategy.
-
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class HintingLineEditFactory : public QStyledItemDelegate
-    {
-    public:
-      HintingLineEditFactory(HintStrategy* hintStrategy) : m_strategy(hintStrategy) {};
-      QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
-                            const QModelIndex &index) const override {
-        Q_UNUSED(option);
-        Q_UNUSED(index);
-
-        auto editor = new HintingLineEdit(parent, m_strategy->createHints());
-        editor->setFrame(false);
-
-        return editor;
-      }
-    protected:
-      boost::scoped_ptr<HintStrategy> m_strategy;
-    };
+namespace MantidQt {
+namespace CustomInterfaces {
+/** HintingLineEditFactory : A QStyledItemDelegate that produces
+HintingLineEdits using the given hint strategy.
+
+Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class HintingLineEditFactory : public QStyledItemDelegate {
+public:
+  HintingLineEditFactory(HintStrategy *hintStrategy)
+      : m_strategy(hintStrategy){};
+  QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
+                        const QModelIndex &index) const override {
+    Q_UNUSED(option);
+    Q_UNUSED(index);
+
+    auto editor = new HintingLineEdit(parent, m_strategy->createHints());
+    editor->setFrame(false);
+
+    return editor;
   }
+
+protected:
+  boost::scoped_ptr<HintStrategy> m_strategy;
+};
+}
 }
 
 #endif /* MANTID_MANTIDWIDGETS_HINTINGLINEEDITFACTORY_H */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/IndirectInstrumentConfig.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/IndirectInstrumentConfig.h
index 4514a658e4b767fad5bc4b5ff3433b0c28b98784..ddba0382c6523fcce78ce10bc33961f27e8a5f37 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/IndirectInstrumentConfig.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/IndirectInstrumentConfig.h
@@ -10,123 +10,128 @@
 
 #include <QWidget>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-    Widget used to select an instrument configuration for indirect geometry spectrometers
-    (i.e. and instrument, analyser and reflection).
-
-    Instruments are populated using an InstrumentSelector widget, analysers and reflections
-    are populated by loading an empty instrument.
-
-    @author Dan Nixon
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS IndirectInstrumentConfig: public API::MantidWidget
-    {
-      Q_OBJECT
-
-      Q_PROPERTY(QStringList techniques READ getTechniques WRITE setTechniques)
-      Q_PROPERTY(QStringList disabledInstruments READ getDisabledInstruments WRITE setDisabledInstruments)
-      Q_PROPERTY(QString facility READ getFacility WRITE setFacility)
-      Q_PROPERTY(bool enableDiffraction READ isDiffractionEnabled WRITE enableDiffraction)
-      Q_PROPERTY(bool forceDiffraction READ isDiffractionForced WRITE forceDiffraction)
-      Q_PROPERTY(bool showInstrumentLabel READ isInstrumentLabelShown WRITE setShowInstrumentLabel)
-
-    public:
-      IndirectInstrumentConfig(QWidget *parent = 0);
-      ~IndirectInstrumentConfig() override;
-
-      /* Getters and setters for Qt properties */
-      QStringList getTechniques();
-      void setTechniques(const QStringList & techniques);
-
-      QStringList getDisabledInstruments();
-      void setDisabledInstruments(const QStringList & instrumentNames);
-
-      QString getFacility();
-      void setFacility(const QString & facilityName);
-
-      bool isDiffractionEnabled();
-      void enableDiffraction(bool enabled);
-
-      bool isDiffractionForced();
-      void forceDiffraction(bool forced);
-
-      bool isInstrumentLabelShown();
-      void setShowInstrumentLabel(bool visible);
-
-      /// Gets the name of the selected instrument
-      QString getInstrumentName();
-      /// Set the displayed instrument (if exists)
-      void setInstrument(const QString & instrumentName);
-
-      /// Gets the name of the selected analyser
-      QString getAnalyserName();
-      /// Set the displayed analyser bank (if exists)
-      void setAnalyser(const QString & analyserName);
-
-      /// Gets the name of the selected reflection
-      QString getReflectionName();
-      /// Set the displayed reflection mode (if exists)
-      void setReflection(const QString & reflectionName);
-
-    public slots:
-      /// Called when an instrument configuration is selected
-      void newInstrumentConfiguration();
-
-    signals:
-      /// Emitted when the instrument configuration is changed
-      void instrumentConfigurationUpdated(const QString & instrumentName,
-          const QString & analyserName, const QString & reflectionName);
-
-    private slots:
-      /// Handles an instrument being selected
-      void updateInstrumentConfigurations(const QString & instrumentName);
-      /// Updates the list of analysers when an instrument is selected
-      bool updateAnalysersList(Mantid::API::MatrixWorkspace_sptr ws);
-      /// Updates the list of reflections when an analyser is selected
-      void updateReflectionsList(int index);
-      /// Filters out any disabled instruments
-      void filterDisabledInstruments();
-
-    private:
-      /// Member containing the widgets child widgets.
-      Ui::IndirectInstrumentConfig m_uiForm;
-      /// Algorithm Runner used to load empty instrument workspaces
-      MantidQt::API::AlgorithmRunner m_algRunner;
-      /// Instrument selector widget
-      MantidQt::MantidWidgets::InstrumentSelector *m_instrumentSelector;
-
-      QStringList m_disabledInstruments;
-      bool m_removeDiffraction;
-      bool m_forceDiffraction;
-
-    };
-
-  } /* namespace MantidWidgets */
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+Widget used to select an instrument configuration for indirect geometry
+spectrometers
+(i.e. and instrument, analyser and reflection).
+
+Instruments are populated using an InstrumentSelector widget, analysers and
+reflections
+are populated by loading an empty instrument.
+
+@author Dan Nixon
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS IndirectInstrumentConfig
+    : public API::MantidWidget {
+  Q_OBJECT
+
+  Q_PROPERTY(QStringList techniques READ getTechniques WRITE setTechniques)
+  Q_PROPERTY(QStringList disabledInstruments READ getDisabledInstruments WRITE
+                 setDisabledInstruments)
+  Q_PROPERTY(QString facility READ getFacility WRITE setFacility)
+  Q_PROPERTY(bool enableDiffraction READ isDiffractionEnabled WRITE
+                 enableDiffraction)
+  Q_PROPERTY(bool forceDiffraction READ isDiffractionForced WRITE
+                 forceDiffraction)
+  Q_PROPERTY(bool showInstrumentLabel READ isInstrumentLabelShown WRITE
+                 setShowInstrumentLabel)
+
+public:
+  IndirectInstrumentConfig(QWidget *parent = 0);
+  ~IndirectInstrumentConfig() override;
+
+  /* Getters and setters for Qt properties */
+  QStringList getTechniques();
+  void setTechniques(const QStringList &techniques);
+
+  QStringList getDisabledInstruments();
+  void setDisabledInstruments(const QStringList &instrumentNames);
+
+  QString getFacility();
+  void setFacility(const QString &facilityName);
+
+  bool isDiffractionEnabled();
+  void enableDiffraction(bool enabled);
+
+  bool isDiffractionForced();
+  void forceDiffraction(bool forced);
+
+  bool isInstrumentLabelShown();
+  void setShowInstrumentLabel(bool visible);
+
+  /// Gets the name of the selected instrument
+  QString getInstrumentName();
+  /// Set the displayed instrument (if exists)
+  void setInstrument(const QString &instrumentName);
+
+  /// Gets the name of the selected analyser
+  QString getAnalyserName();
+  /// Set the displayed analyser bank (if exists)
+  void setAnalyser(const QString &analyserName);
+
+  /// Gets the name of the selected reflection
+  QString getReflectionName();
+  /// Set the displayed reflection mode (if exists)
+  void setReflection(const QString &reflectionName);
+
+public slots:
+  /// Called when an instrument configuration is selected
+  void newInstrumentConfiguration();
+
+signals:
+  /// Emitted when the instrument configuration is changed
+  void instrumentConfigurationUpdated(const QString &instrumentName,
+                                      const QString &analyserName,
+                                      const QString &reflectionName);
+
+private slots:
+  /// Handles an instrument being selected
+  void updateInstrumentConfigurations(const QString &instrumentName);
+  /// Updates the list of analysers when an instrument is selected
+  bool updateAnalysersList(Mantid::API::MatrixWorkspace_sptr ws);
+  /// Updates the list of reflections when an analyser is selected
+  void updateReflectionsList(int index);
+  /// Filters out any disabled instruments
+  void filterDisabledInstruments();
+
+private:
+  /// Member containing the widgets child widgets.
+  Ui::IndirectInstrumentConfig m_uiForm;
+  /// Algorithm Runner used to load empty instrument workspaces
+  MantidQt::API::AlgorithmRunner m_algRunner;
+  /// Instrument selector widget
+  MantidQt::MantidWidgets::InstrumentSelector *m_instrumentSelector;
+
+  QStringList m_disabledInstruments;
+  bool m_removeDiffraction;
+  bool m_forceDiffraction;
+};
+
+} /* namespace MantidWidgets */
 } /* namespace MantidQt */
 
 #endif /* INDIRECTINSTRUMENTCONFIG_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InputController.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InputController.h
index b8a0bd3aa0fe6205d3865547a497fed228527883..0988f1b7ba2163553f3a79fe07474d141b3e15e1 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InputController.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InputController.h
@@ -67,7 +67,8 @@ private:
     translation, rotation and zooming.
 
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputController3DMove : public InputController {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputController3DMove
+    : public InputController {
   Q_OBJECT
 
 public:
@@ -102,7 +103,8 @@ private:
 /**
     Controller for picking detectors.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerPick : public InputController {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerPick
+    : public InputController {
   Q_OBJECT
 
 public:
@@ -125,7 +127,8 @@ private:
 /**
     Controller for drawing mask shapes.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDrawShape : public InputController {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDrawShape
+    : public InputController {
   Q_OBJECT
 
 public:
@@ -179,7 +182,8 @@ private:
 /**
     Controller for moving the instrument on an unwrapped surface.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerMoveUnwrapped : public InputController {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerMoveUnwrapped
+    : public InputController {
   Q_OBJECT
 
 public:
@@ -201,7 +205,8 @@ private:
 /**
     Controller for free drawing on an unwrapped surface.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDraw : public InputController {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDraw
+    : public InputController {
   Q_OBJECT
 
 public:
@@ -216,10 +221,10 @@ public:
   void leaveEvent(QEvent *) override;
 
 protected:
-  int cursorSize() const {return m_size;}
-  bool isLeftButtonPressed() const {return m_isLeftButtonPressed;}
-  bool isRightButtonPressed() const {return m_isRightButtonPressed;}
-  bool isActive() const {return m_isActive;}
+  int cursorSize() const { return m_size; }
+  bool isLeftButtonPressed() const { return m_isLeftButtonPressed; }
+  bool isRightButtonPressed() const { return m_isRightButtonPressed; }
+  bool isActive() const { return m_isActive; }
 
 private:
   void redrawCursor();
@@ -240,7 +245,8 @@ private:
 /**
     Controller for erasing peaks on an unwrapped surface.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerErase : public InputControllerDraw {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerErase
+    : public InputControllerDraw {
   Q_OBJECT
 
 public:
@@ -264,7 +270,8 @@ private:
 /**
     Controller for drawing and erasing arbitrary shapes on an unwrapped surface.
   */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDrawAndErase : public InputControllerDraw {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InputControllerDrawAndErase
+    : public InputControllerDraw {
   Q_OBJECT
 
 public:
@@ -292,7 +299,6 @@ private:
   QColor m_borderColor, m_fillColor;
   bool m_creating;
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentSelector.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentSelector.h
index 336814917b043f0583f233fdf5e72a270c68dd4c..9617c7013b17705d74559e5b6953d4a4215989d0 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentSelector.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentSelector.h
@@ -12,111 +12,110 @@
 //----------------------------------------------------------------
 // Forward declarations
 //----------------------------------------------------------------
-namespace Mantid
-{
-  namespace Kernel
-  {
-    class FacilityInfo;
-  }
+namespace Mantid {
+namespace Kernel {
+class FacilityInfo;
+}
 }
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-    This class defines a widget for selecting an instrument known to Mantid
-
-    @author Martyn Gigg, Tessella Support Services plc
-    @date 10/08/2010
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentSelector : public QComboBox
-    {
-      Q_OBJECT
-
-      Q_PROPERTY(QStringList techniques READ getTechniques WRITE setTechniques)
-      Q_PROPERTY(bool updateOnFacilityChange READ getAutoUpdate WRITE setAutoUpdate)
-      Q_PROPERTY(QString facility READ getFacility WRITE setFacility)
-
-    public:
-      /// Default Constructor
-      InstrumentSelector(QWidget *parent = NULL, bool init = true);
-      /// Destructor
-      ~InstrumentSelector() override;
-      /// Return the list of techniques
-      QStringList getTechniques() const;
-      /// Set the list of techniques
-      void setTechniques(const QStringList & techniques);
-      /// Returns true of auto reloading on facility change is enabled
-      bool getAutoUpdate();
-      /// Enable or disable reloading on facility change
-      void setAutoUpdate(bool autoUpdate);
-      /// Get the name of the facility instrumetns are currently loaded from
-      QString getFacility();
-      /// Load instruments from a given facility
-      void setFacility(const QString & facilityName);
-      /// Sets whether to update the default instrument on selection change
-      void updateInstrumentOnSelection(const bool storeChanges);
-
-    public slots:
-      /// Update list for a new facility
-      void fillWithInstrumentsFromFacility(const QString & name = QString());
-
-    signals:
-      /// Indicate that the instrument selection has changed. The parameter will contain the new name
-      void instrumentSelectionChanged(const QString &);
-      void configValueChanged(const QString&, const QString&, const QString&);
-      /// Signals that the list of instruments has been updated
-      void instrumentListUpdated();
-
-    private slots:
-      /// Handle an instrument seelction
-      void updateInstrument(const QString & name);
-
-    private:
-      void handleConfigChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
-      /// Filter the list to only show those supporting the given technique
-      void filterByTechniquesAtFacility(const QStringList & techniques, const Mantid::Kernel::FacilityInfo & facility);
-
-    private: // members
-      /// Poco Observer for Config Service Notifications
-      Poco::NObserver<InstrumentSelector, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
-      /// A list of technqiues. Only those instruments supporting these techniques are shown.
-      QStringList m_techniques;
-      /// The current facility
-      const Mantid::Kernel::FacilityInfo *m_currentFacility;
-      /// Should the object be initialized
-      bool m_init;
-      /// Should the default instrument be changed when the selection changes
-      bool m_storeChanges;
-      /// If the instrument list should be reloaded when the facility changes
-      bool m_updateOnFacilityChange;
-      /// The last selected instrument
-      QString m_selectedInstrument;
-
-    };
-
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+This class defines a widget for selecting an instrument known to Mantid
+
+@author Martyn Gigg, Tessella Support Services plc
+@date 10/08/2010
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentSelector : public QComboBox {
+  Q_OBJECT
+
+  Q_PROPERTY(QStringList techniques READ getTechniques WRITE setTechniques)
+  Q_PROPERTY(bool updateOnFacilityChange READ getAutoUpdate WRITE setAutoUpdate)
+  Q_PROPERTY(QString facility READ getFacility WRITE setFacility)
+
+public:
+  /// Default Constructor
+  InstrumentSelector(QWidget *parent = NULL, bool init = true);
+  /// Destructor
+  ~InstrumentSelector() override;
+  /// Return the list of techniques
+  QStringList getTechniques() const;
+  /// Set the list of techniques
+  void setTechniques(const QStringList &techniques);
+  /// Returns true of auto reloading on facility change is enabled
+  bool getAutoUpdate();
+  /// Enable or disable reloading on facility change
+  void setAutoUpdate(bool autoUpdate);
+  /// Get the name of the facility instrumetns are currently loaded from
+  QString getFacility();
+  /// Load instruments from a given facility
+  void setFacility(const QString &facilityName);
+  /// Sets whether to update the default instrument on selection change
+  void updateInstrumentOnSelection(const bool storeChanges);
+
+public slots:
+  /// Update list for a new facility
+  void fillWithInstrumentsFromFacility(const QString &name = QString());
+
+signals:
+  /// Indicate that the instrument selection has changed. The parameter will
+  /// contain the new name
+  void instrumentSelectionChanged(const QString &);
+  void configValueChanged(const QString &, const QString &, const QString &);
+  /// Signals that the list of instruments has been updated
+  void instrumentListUpdated();
+
+private slots:
+  /// Handle an instrument seelction
+  void updateInstrument(const QString &name);
+
+private:
+  void handleConfigChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf);
+  /// Filter the list to only show those supporting the given technique
+  void
+  filterByTechniquesAtFacility(const QStringList &techniques,
+                               const Mantid::Kernel::FacilityInfo &facility);
+
+private: // members
+  /// Poco Observer for Config Service Notifications
+  Poco::NObserver<InstrumentSelector,
+                  Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
+  /// A list of technqiues. Only those instruments supporting these techniques
+  /// are shown.
+  QStringList m_techniques;
+  /// The current facility
+  const Mantid::Kernel::FacilityInfo *m_currentFacility;
+  /// Should the object be initialized
+  bool m_init;
+  /// Should the default instrument be changed when the selection changes
+  bool m_storeChanges;
+  /// If the instrument list should be reloaded when the facility changes
+  bool m_updateOnFacilityChange;
+  /// The last selected instrument
+  QString m_selectedInstrument;
+};
+}
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
+#endif // MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/BinDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/BinDialog.h
index 7ce6183517c6a8c5deefb6078ddcb16d36a7454e..71fcf41d81882a7106f7e0dfaeab65aab952983a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/BinDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/BinDialog.h
@@ -8,67 +8,62 @@
 class QLineEdit;
 class QRadioButton;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		\class  BinDialog
-		\brief  class to display Bin selection dialog
-		\author Srikanth Nagella
-		\date   November 2008
-		\version 1.0
-
-		BinDialog class handles the Input Dialog for bin selection:
-		e.g. enter bin range from X1 to X2.
-
-		Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-		This file is part of Mantid.
-
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
-
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
-
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-
-
-		class BinDialog : public QDialog
-		{
-			Q_OBJECT
-
-		public:
-			explicit BinDialog(QWidget *parent = 0);
-                        ~BinDialog() override;
-                        void setIntegralMinMax(double, double, bool);
-		signals:
-			/// This signal is sent when changing the bin range selected.
-			/// Parameters are: min, max, and a bool set to true to mean "everything"
-			void IntegralMinMax(double, double, bool);
-
-			public slots:
-			void btnOKClicked();
-			void mEntireRange_toggled(bool on);
-
-		private:
-			QLineEdit* mIntegralMinValue;
-			QLineEdit* mIntegralMaxValue;
-			QCheckBox* mEntireRange;
-
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+\class  BinDialog
+\brief  class to display Bin selection dialog
+\author Srikanth Nagella
+\date   November 2008
+\version 1.0
+
+BinDialog class handles the Input Dialog for bin selection:
+e.g. enter bin range from X1 to X2.
+
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+
+class BinDialog : public QDialog {
+  Q_OBJECT
+
+public:
+  explicit BinDialog(QWidget *parent = 0);
+  ~BinDialog() override;
+  void setIntegralMinMax(double, double, bool);
+signals:
+  /// This signal is sent when changing the bin range selected.
+  /// Parameters are: min, max, and a bool set to true to mean "everything"
+  void IntegralMinMax(double, double, bool);
+
+public slots:
+  void btnOKClicked();
+  void mEntireRange_toggled(bool on);
+
+private:
+  QLineEdit *mIntegralMinValue;
+  QLineEdit *mIntegralMaxValue;
+  QCheckBox *mEntireRange;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*BINDIALOG_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CollapsiblePanel.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CollapsiblePanel.h
index da98b97083613adb015ea54174a2d82e7977f7d8..962c9874b26b93feb4954b7f77b07ef637348600 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CollapsiblePanel.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CollapsiblePanel.h
@@ -6,65 +6,63 @@
 
 class QVBoxLayout;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class CaptionLabel : public QLabel
-		{
-			Q_OBJECT
-		public:
-			CaptionLabel(const QString& caption, QWidget* parent);
-                        void mousePressEvent(QMouseEvent *e) override;
-                        void paintEvent(QPaintEvent *event) override;
-                        bool isCollapsed()const { return m_collapsed; }
-			void collapse();
-			void expand();
-		signals:
-			void collapseOrExpand(bool);
-		private:
-			bool m_collapsed;
-		};
+namespace MantidQt {
+namespace MantidWidgets {
+class CaptionLabel : public QLabel {
+  Q_OBJECT
+public:
+  CaptionLabel(const QString &caption, QWidget *parent);
+  void mousePressEvent(QMouseEvent *e) override;
+  void paintEvent(QPaintEvent *event) override;
+  bool isCollapsed() const { return m_collapsed; }
+  void collapse();
+  void expand();
+signals:
+  void collapseOrExpand(bool);
 
-		/**
-		* Implements a collapsible panel.
-		*/
-		class CollapsiblePanel : public QWidget
-		{
-			Q_OBJECT
-		public:
-			CollapsiblePanel(const QString& caption, QWidget* parent);
-			void setWidget(QWidget* widget);
-			void setCaption(const QString& caption);
-			bool isCollapsed()const;
-		signals:
-			void collapsed();
-			void expanded();
-			public slots:
-			void collapse();
-			void expand();
-			private slots:
-			void collapseOrExpand(bool);
-		private:
-			QWidget *m_widget;
-			QVBoxLayout* m_layout;
-			CaptionLabel* m_label;
-		};
+private:
+  bool m_collapsed;
+};
 
-		class CollapsibleStack : public QWidget
-		{
-			Q_OBJECT
-		public:
-			explicit CollapsibleStack(QWidget *parent);
-			CollapsiblePanel* addPanel(const QString& caption, QWidget* widget);
-			private slots:
-			void updateStretch();
-		private:
-			bool allCollapsed()const;
-			QVBoxLayout* m_layout;
-		};
+/**
+* Implements a collapsible panel.
+*/
+class CollapsiblePanel : public QWidget {
+  Q_OBJECT
+public:
+  CollapsiblePanel(const QString &caption, QWidget *parent);
+  void setWidget(QWidget *widget);
+  void setCaption(const QString &caption);
+  bool isCollapsed() const;
+signals:
+  void collapsed();
+  void expanded();
+public slots:
+  void collapse();
+  void expand();
+private slots:
+  void collapseOrExpand(bool);
 
-	}//MantidWidgets
-}//MantidQt
+private:
+  QWidget *m_widget;
+  QVBoxLayout *m_layout;
+  CaptionLabel *m_label;
+};
+
+class CollapsibleStack : public QWidget {
+  Q_OBJECT
+public:
+  explicit CollapsibleStack(QWidget *parent);
+  CollapsiblePanel *addPanel(const QString &caption, QWidget *widget);
+private slots:
+  void updateStretch();
+
+private:
+  bool allCollapsed() const;
+  QVBoxLayout *m_layout;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*COLLAPSIBLEPANEL_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ColorMapWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ColorMapWidget.h
index 68bf489a4bce0f28fc050b9ba36866004bb946c3..1262d901269489d19bcdf32f6b64446422b18486 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ColorMapWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ColorMapWidget.h
@@ -11,61 +11,61 @@ class QComboBox;
 class QLabel;
 class DoubleSpinBox;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* Displays a color map with numeric axis and editable bounds
-		*/
-		class ColorMapWidget : public QFrame
-		{
-			Q_OBJECT
-			enum DragType { Bottom, Top };
-		public:
-			ColorMapWidget(int type, QWidget* parent, const double& minPositiveValue = 0.0001);
-			void setupColorBarScaling(const MantidColorMap&);
-			void setMinValue(double);
-			void setMaxValue(double);
-			QString getMinValue();
-			QString getMaxValue();
-			QString getNth_power();
-			void setMinPositiveValue(double);
-			int getScaleType()const;
-			void setScaleType(int);
-			void setNthPower(double);
-		signals:
-			void scaleTypeChanged(int);
-			void minValueChanged(double);
-			void maxValueChanged(double);
-			void nthPowerChanged(double);
-		protected:
-                  void mousePressEvent(QMouseEvent *) override;
-                  void mouseMoveEvent(QMouseEvent *) override;
-                  void mouseReleaseEvent(QMouseEvent *) override;
-                        void updateScale();
-			void setMinValueText(double);
-			void setMaxValueText(double);
-			private slots:
-			void scaleOptionsChanged(int);
-			void nPowerChanged(double);
-			void minValueChanged();
-			void maxValueChanged();
-		private:
-			QwtScaleWidget *m_scaleWidget;
-			QLineEdit *m_minValueBox, *m_maxValueBox;
-			QComboBox *m_scaleOptions;
-			QLabel *m_lblN;
-			DoubleSpinBox *m_dspnN;
-			double m_minPositiveValue;
-			bool m_dragging;
-			int m_y;
-			DragType m_dtype;
-			double m_nth_power;
-		};
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* Displays a color map with numeric axis and editable bounds
+*/
+class ColorMapWidget : public QFrame {
+  Q_OBJECT
+  enum DragType { Bottom, Top };
 
-	}//MantidWidgets
-}//MantidQt
+public:
+  ColorMapWidget(int type, QWidget *parent,
+                 const double &minPositiveValue = 0.0001);
+  void setupColorBarScaling(const MantidColorMap &);
+  void setMinValue(double);
+  void setMaxValue(double);
+  QString getMinValue();
+  QString getMaxValue();
+  QString getNth_power();
+  void setMinPositiveValue(double);
+  int getScaleType() const;
+  void setScaleType(int);
+  void setNthPower(double);
+signals:
+  void scaleTypeChanged(int);
+  void minValueChanged(double);
+  void maxValueChanged(double);
+  void nthPowerChanged(double);
 
+protected:
+  void mousePressEvent(QMouseEvent *) override;
+  void mouseMoveEvent(QMouseEvent *) override;
+  void mouseReleaseEvent(QMouseEvent *) override;
+  void updateScale();
+  void setMinValueText(double);
+  void setMaxValueText(double);
+private slots:
+  void scaleOptionsChanged(int);
+  void nPowerChanged(double);
+  void minValueChanged();
+  void maxValueChanged();
+
+private:
+  QwtScaleWidget *m_scaleWidget;
+  QLineEdit *m_minValueBox, *m_maxValueBox;
+  QComboBox *m_scaleOptions;
+  QLabel *m_lblN;
+  DoubleSpinBox *m_dspnN;
+  double m_minPositiveValue;
+  bool m_dragging;
+  int m_y;
+  DragType m_dtype;
+  double m_nth_power;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*COLORMAPWIDGET_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CompAssemblyActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CompAssemblyActor.h
index ac12bc79782fb96b3e264c4766dd19e1ab4a7924..84b3931f05dce548e455fa342e0225f4abba78e2 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CompAssemblyActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/CompAssemblyActor.h
@@ -13,10 +13,13 @@
   \date   March 2009
   \version 1.0
 
-  This class has the implementation for calling the children of ICompAssembly's IObjComponent to render themselves
-  and call the ICompAssemblys. This maintains the count of the children for easy lookup.
+  This class has the implementation for calling the children of ICompAssembly's
+  IObjComponent to render themselves
+  and call the ICompAssemblys. This maintains the count of the children for easy
+  lookup.
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -35,59 +38,53 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-namespace Mantid
-{
-namespace Kernel
-{
-  class V3D;
+namespace Mantid {
+namespace Kernel {
+class V3D;
 }
-namespace Geometry
-{
-  class ICompAssembly;
-  class Object;
+namespace Geometry {
+class ICompAssembly;
+class Object;
 }
-
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentActor;
-
-		class ObjComponentActor;
-
-		class CompAssemblyActor : public ICompAssemblyActor
-		{
-		public:
-			CompAssemblyActor(const InstrumentActor &instrActor, const Mantid::Geometry::ComponentID &compID); ///< Constructor
-                        ~CompAssemblyActor() override;
-                        std::string type() const override {
-                          return "CompAssemblyActor";
-                        } ///< Type of the GL object
-                        void draw(bool picking = false)
-                            const override; ///< Method that defines
-                                            ///ObjComponent geometry. Calls
-                                            ///ObjComponent draw method
-                        void setChildVisibility(bool) override;
-                        bool hasChildVisible() const override;
-                        bool accept(GLActorVisitor &visitor,
-                                    VisitorAcceptRule rule = VisitAll) override;
-                        bool accept(
-                            GLActorConstVisitor &visitor,
-                            VisitorAcceptRule rule = VisitAll) const override;
-                        void setColors() override;
-
-                protected:
-			mutable std::vector<ObjComponentActor*> mChildObjCompActors;     ///< List of ObjComponent Actors
-			mutable std::vector<ICompAssemblyActor*> mChildCompAssemActors;   ///< List of CompAssembly Actors
-		private:
-			void AppendBoundingBox(const Mantid::Kernel::V3D& minBound, const Mantid::Kernel::V3D& maxBound);
-		};
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentActor;
+
+class ObjComponentActor;
+
+class CompAssemblyActor : public ICompAssemblyActor {
+public:
+  CompAssemblyActor(
+      const InstrumentActor &instrActor,
+      const Mantid::Geometry::ComponentID &compID); ///< Constructor
+  ~CompAssemblyActor() override;
+  std::string type() const override {
+    return "CompAssemblyActor";
+  }                                               ///< Type of the GL object
+  void draw(bool picking = false) const override; ///< Method that defines
+  /// ObjComponent geometry. Calls
+  /// ObjComponent draw method
+  void setChildVisibility(bool) override;
+  bool hasChildVisible() const override;
+  bool accept(GLActorVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) override;
+  bool accept(GLActorConstVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) const override;
+  void setColors() override;
+
+protected:
+  mutable std::vector<ObjComponentActor *>
+      mChildObjCompActors; ///< List of ObjComponent Actors
+  mutable std::vector<ICompAssemblyActor *>
+      mChildCompAssemActors; ///< List of CompAssembly Actors
+private:
+  void AppendBoundingBox(const Mantid::Kernel::V3D &minBound,
+                         const Mantid::Kernel::V3D &maxBound);
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*GLTRIANGLE_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ComponentActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ComponentActor.h
index 7aea8ccde33d8fb93c0ab94f34b257a547c7afe8..ce4a12ef49c401ed1bcc026386a7782ca10d7e90 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ComponentActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ComponentActor.h
@@ -12,9 +12,11 @@
   \date   March 2009
   \version 1.0
 
-   This class has the implementation for rendering ObjComponents in OpenGL and it inherits from the GLActor
+   This class has the implementation for rendering ObjComponents in OpenGL and
+  it inherits from the GLActor
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -33,49 +35,48 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IObjComponent;
-    class IDetector;
-    class ObjCompAssembly;
-    class CompAssembly;
-  }
+namespace Mantid {
+namespace Geometry {
+class IObjComponent;
+class IDetector;
+class ObjCompAssembly;
+class CompAssembly;
+}
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentActor;
-
-		class ComponentActor : public GLActor
-		{
-		public:
-			ComponentActor(const InstrumentActor &instrActor, const Mantid::Geometry::ComponentID &compID); ///< Default Constructor
-			virtual std::string type()const { return "ComponentActor"; } ///< Type of the GL object
-                        bool accept(GLActorVisitor &visitor,
-                                    VisitorAcceptRule rule = VisitAll) override;
-                        bool accept(
-                            GLActorConstVisitor &visitor,
-                            VisitorAcceptRule rule = VisitAll) const override;
-                        boost::shared_ptr<const Mantid::Geometry::IComponent> getComponent() const;
-			boost::shared_ptr<const Mantid::Geometry::IObjComponent> getObjComponent() const;
-			boost::shared_ptr<const Mantid::Geometry::IDetector> getDetector() const;
-			boost::shared_ptr<const Mantid::Geometry::ObjCompAssembly> getObjCompAssembly() const;
-			boost::shared_ptr<const Mantid::Geometry::CompAssembly> getCompAssembly() const;
-			virtual void setColors() {}
-			/// Check if the component is a non-detector.
-			bool isNonDetector() const;
-		protected:
-			const InstrumentActor& m_instrActor;
-			Mantid::Geometry::ComponentID m_id; ///< Component ID
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentActor;
 
+class ComponentActor : public GLActor {
+public:
+  ComponentActor(
+      const InstrumentActor &instrActor,
+      const Mantid::Geometry::ComponentID &compID); ///< Default Constructor
+  virtual std::string type() const {
+    return "ComponentActor";
+  } ///< Type of the GL object
+  bool accept(GLActorVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) override;
+  bool accept(GLActorConstVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) const override;
+  boost::shared_ptr<const Mantid::Geometry::IComponent> getComponent() const;
+  boost::shared_ptr<const Mantid::Geometry::IObjComponent>
+  getObjComponent() const;
+  boost::shared_ptr<const Mantid::Geometry::IDetector> getDetector() const;
+  boost::shared_ptr<const Mantid::Geometry::ObjCompAssembly>
+  getObjCompAssembly() const;
+  boost::shared_ptr<const Mantid::Geometry::CompAssembly>
+  getCompAssembly() const;
+  virtual void setColors() {}
+  /// Check if the component is a non-detector.
+  bool isNonDetector() const;
 
+protected:
+  const InstrumentActor &m_instrActor;
+  Mantid::Geometry::ComponentID m_id; ///< Component ID
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*COMPONENT_ACTOR_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/DetXMLFile.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/DetXMLFile.h
index 8b91858304f1dafe16d6db3212dc79e76977d440..dffd16ff8bd2f64a427c5b66e99ef9603b57aaf4 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/DetXMLFile.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/DetXMLFile.h
@@ -6,46 +6,47 @@
 
 #include <vector>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-
-		A class for creating grouping xml files
-
-		*/
-		class DetXMLFile
-		{
-		public:
-			enum Option { List, Sum };
-			/// Create a grouping file to extract all detectors in detector_list excluding those in exclude
-			DetXMLFile(const std::vector<int>& detector_list, const QList<int>& exclude, const QString& fname);
-
-			/// Create a grouping file to extract detectors in dets. Option List - one group - one detector,
-			/// Option Sum - one group which is a sum of the detectors
-			/// If fname is empty create a temporary file
-			DetXMLFile(const QList<int>& dets, Option opt = List, const QString& fname = "");
-
-			/// Destructor
-			~DetXMLFile();
-
-			/// Make grouping file where each detector is put into its own group
-			void makeListFile(const QList<int>& dets);
-
-			/// Make grouping file for putting the detectors into one group (summing the detectors)
-			void makeSumFile(const QList<int>& dets);
-
-			/// Return the name of the created grouping file
-			const std::string operator()()const { return m_fileName.toStdString(); }
-
-		private:
-			QString m_fileName; ///< holds the grouping file name
-			bool m_delete;      ///< if true delete the file on destruction
-		};
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+
+A class for creating grouping xml files
+
+*/
+class DetXMLFile {
+public:
+  enum Option { List, Sum };
+  /// Create a grouping file to extract all detectors in detector_list excluding
+  /// those in exclude
+  DetXMLFile(const std::vector<int> &detector_list, const QList<int> &exclude,
+             const QString &fname);
+
+  /// Create a grouping file to extract detectors in dets. Option List - one
+  /// group - one detector,
+  /// Option Sum - one group which is a sum of the detectors
+  /// If fname is empty create a temporary file
+  DetXMLFile(const QList<int> &dets, Option opt = List,
+             const QString &fname = "");
+
+  /// Destructor
+  ~DetXMLFile();
+
+  /// Make grouping file where each detector is put into its own group
+  void makeListFile(const QList<int> &dets);
+
+  /// Make grouping file for putting the detectors into one group (summing the
+  /// detectors)
+  void makeSumFile(const QList<int> &dets);
+
+  /// Return the name of the created grouping file
+  const std::string operator()() const { return m_fileName.toStdString(); }
+
+private:
+  QString m_fileName; ///< holds the grouping file name
+  bool m_delete;      ///< if true delete the file on destruction
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif // DETXMLFILE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActor.h
index 0df8b3a7b4cdf7630f9fb19bb936e659d025aef8..078bd82e832059e0813e4b36a894e4aecbca9981 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActor.h
@@ -23,88 +23,92 @@
 #include <QList>
 #include <QRgb>
 
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IDetector;
-  }
+namespace Mantid {
+namespace Geometry {
+class IDetector;
 }
+}
+
+namespace MantidQt {
+namespace MantidWidgets {
+class GLActorVisitor;
+class GLActorConstVisitor;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class GLActorVisitor;
-		class GLActorConstVisitor;
+/**
+\class  GLActor
+\brief  An actor class that holds geometry objects with its position.
+\author Chapon Laurent & Srikanth Nagella
+\date   August 2008
+\version 1.0
 
-		/**
-		\class  GLActor
-		\brief  An actor class that holds geometry objects with its position.
-		\author Chapon Laurent & Srikanth Nagella
-		\date   August 2008
-		\version 1.0
+Base class for all objects in a 3D Scene. Methods are provided to position and
+rotate the objects.
+The objects can also be set as active or not. Actors maintain safe pointer to a
+GLObject.
 
-		Base class for all objects in a 3D Scene. Methods are provided to position and rotate the objects.
-		The objects can also be set as active or not. Actors maintain safe pointer to a GLObject.
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-		Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+This file is part of Mantid.
 
-		This file is part of Mantid.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+class GLActor : public QObject {
+public:
+  /// Rules for visitor propagation. If vistor's visit(...) method returns true
+  /// the propagation can be continued (VisitAll) or abandoned (Finish)
+  enum VisitorAcceptRule { VisitAll, Finish };
+  GLActor() : m_visible(true) {}
+  ///< Virtual destructor
+  ~GLActor() override;
+  /// Toggle the visibility of the actor.
+  virtual void setVisibility(bool on) { m_visible = on; }
+  /// Toggle the visibility of the child actors (if exist).
+  virtual void setChildVisibility(bool on) { setVisibility(on); }
+  /// Check if any child is visible
+  virtual bool hasChildVisible() const { return true; }
+  /// Get the visibility status.
+  bool isVisible() const { return m_visible; }
+  /// Draw the actor in 3D.
+  virtual void draw(bool picking = false) const = 0;
+  /// Get the 3D bounding box of the actor
+  virtual void getBoundingBox(Mantid::Kernel::V3D &minBound,
+                              Mantid::Kernel::V3D &maxBound) const = 0;
+  /// Accept a visitor
+  virtual bool accept(GLActorVisitor &visitor,
+                      VisitorAcceptRule rule = VisitAll);
+  /// Accept a const visitor
+  virtual bool accept(GLActorConstVisitor &visitor,
+                      VisitorAcceptRule rule = VisitAll) const;
+  /// Convert a "pick ID" to a colour to put into the pick image.
+  static GLColor makePickColor(size_t pickID);
+  /// Decode a pick colour and return corresponding "pick ID"
+  static size_t decodePickColor(const QRgb &c);
+  /// Decode a pick colour and return corresponding "pick ID"
+  static size_t decodePickColor(unsigned char r, unsigned char g,
+                                unsigned char b);
+  /// Get colour of a component which doesn't have any counts associated with
+  /// it.
+  static GLColor defaultDetectorColor();
 
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-		class GLActor : public QObject
-		{
-		public:
-			/// Rules for visitor propagation. If vistor's visit(...) method returns true
-			/// the propagation can be continued (VisitAll) or abandoned (Finish)
-			enum VisitorAcceptRule { VisitAll, Finish };
-			GLActor() :m_visible(true) {}
-			///< Virtual destructor
-                        ~GLActor() override;
-                        /// Toggle the visibility of the actor.
-			virtual void setVisibility(bool on) { m_visible = on; }
-			/// Toggle the visibility of the child actors (if exist).
-			virtual void setChildVisibility(bool on) { setVisibility(on); }
-			/// Check if any child is visible
-			virtual bool hasChildVisible() const { return true; }
-			/// Get the visibility status.
-			bool isVisible()const { return m_visible; }
-			/// Draw the actor in 3D.
-			virtual void draw(bool picking = false)const = 0;
-			/// Get the 3D bounding box of the actor
-			virtual void getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const = 0;
-			/// Accept a visitor
-			virtual bool accept(GLActorVisitor& visitor, VisitorAcceptRule rule = VisitAll);
-			/// Accept a const visitor
-			virtual bool accept(GLActorConstVisitor &visitor, VisitorAcceptRule rule = VisitAll) const;
-			/// Convert a "pick ID" to a colour to put into the pick image.
-			static GLColor makePickColor(size_t pickID);
-			/// Decode a pick colour and return corresponding "pick ID"
-			static size_t decodePickColor(const QRgb& c);
-			/// Decode a pick colour and return corresponding "pick ID"
-			static size_t decodePickColor(unsigned char r, unsigned char g, unsigned char b);
-			/// Get colour of a component which doesn't have any counts associated with it.
-			static GLColor defaultDetectorColor();
-		protected:
-			bool  m_visible;					 ///< Flag whether the actor is visible or not
-		};
+protected:
+  bool m_visible; ///< Flag whether the actor is visible or not
+};
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
 
 #endif /*GLACTOR_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorCollection.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorCollection.h
index 6d9a6b685ee13c0f7eeb49c4fb12f47e7edadea8..78c2d909ac6778f08d226d784e69396515688a7e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorCollection.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorCollection.h
@@ -6,73 +6,69 @@
 
 #include <vector>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		\class  GLActorCollection
-		\brief  An actor class collection
-		\author Chapon Laurent & Srikanth Nagella
-		\date   August 2008
-		\version 1.0
-
-
-		GLActorCollection has the list of GLActor.
-
-		Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-		This file is part of Mantid.
-
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
-
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
-
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-
-
-		class GLActorCollection : public GLActor
-		{
-		public:
-			GLActorCollection(); ///< Default Constructor
-                        ~GLActorCollection() override; ///< Destructor
-                        void setChildVisibility(bool) override;
-                        bool hasChildVisible() const override;
-                        void draw(bool picking = false) const override;
-                        void getBoundingBox(
-                            Mantid::Kernel::V3D &minBound,
-                            Mantid::Kernel::V3D &maxBound) const override;
-                        bool accept(GLActorVisitor &visitor,
-                                    VisitorAcceptRule rule = VisitAll) override;
-                        bool accept(
-                            GLActorConstVisitor &visitor,
-                            VisitorAcceptRule rule = VisitAll) const override;
-
-                        void addActor(GLActor*);
-			void removeActor(GLActor*);
-			int  getNumberOfActors();
-			GLActor* getActor(int index);
-			void invalidateDisplayList()const;
-		private:
-			void drawGL(bool picking = false)const;
-			mutable std::vector<GLActor*> mActorsList;    ///< Vector of GLActors for fast access.
-			Mantid::Kernel::V3D m_minBound;
-			Mantid::Kernel::V3D m_maxBound;
-			mutable GLuint m_displayListId[2];
-			mutable bool m_useDisplayList[2];
-		};
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+\class  GLActorCollection
+\brief  An actor class collection
+\author Chapon Laurent & Srikanth Nagella
+\date   August 2008
+\version 1.0
+
+
+GLActorCollection has the list of GLActor.
+
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+
+class GLActorCollection : public GLActor {
+public:
+  GLActorCollection();           ///< Default Constructor
+  ~GLActorCollection() override; ///< Destructor
+  void setChildVisibility(bool) override;
+  bool hasChildVisible() const override;
+  void draw(bool picking = false) const override;
+  void getBoundingBox(Mantid::Kernel::V3D &minBound,
+                      Mantid::Kernel::V3D &maxBound) const override;
+  bool accept(GLActorVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) override;
+  bool accept(GLActorConstVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) const override;
+
+  void addActor(GLActor *);
+  void removeActor(GLActor *);
+  int getNumberOfActors();
+  GLActor *getActor(int index);
+  void invalidateDisplayList() const;
+
+private:
+  void drawGL(bool picking = false) const;
+  mutable std::vector<GLActor *>
+      mActorsList; ///< Vector of GLActors for fast access.
+  Mantid::Kernel::V3D m_minBound;
+  Mantid::Kernel::V3D m_maxBound;
+  mutable GLuint m_displayListId[2];
+  mutable bool m_useDisplayList[2];
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*GLACTORCOLLECTION_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorVisitor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorVisitor.h
index 96294a8f08bb4acf03efd4c8cbf6504e8526743a..401783ed5355f659a9c80ae5475ced6dd7ab4ab0 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorVisitor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLActorVisitor.h
@@ -1,89 +1,77 @@
 #ifndef GLACTORVISITOR_H
 #define GLACTORVISITOR_H
 
+namespace MantidQt {
+namespace MantidWidgets {
+class GLActor;
+class GLActorCollection;
+class ComponentActor;
+class CompAssemblyActor;
+class ObjCompAssemblyActor;
+class RectangularDetectorActor;
+class StructuredDetectorActor;
+class InstrumentActor;
 
+/**
+* A base class for an actor visitor.
+*/
+class GLActorVisitor {
+public:
+  /// Virtual destructor.
+  virtual ~GLActorVisitor() {}
+  /// Abstract method that must be implemented in sub-classes
+  virtual bool visit(GLActor *) = 0;
+  virtual bool visit(GLActorCollection *);
+  virtual bool visit(CompAssemblyActor *);
+  virtual bool visit(ObjCompAssemblyActor *);
+  virtual bool visit(ComponentActor *);
+  virtual bool visit(InstrumentActor *);
+  virtual bool visit(RectangularDetectorActor *);
+  virtual bool visit(StructuredDetectorActor *);
+};
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class GLActor;
-		class GLActorCollection;
-		class ComponentActor;
-		class CompAssemblyActor;
-		class ObjCompAssemblyActor;
-		class RectangularDetectorActor;
-		class StructuredDetectorActor;
-		class InstrumentActor;
+/**
+* A base class for an actor visitor (const version).
+*/
+class GLActorConstVisitor {
+public:
+  /// Virtual destructor.
+  virtual ~GLActorConstVisitor() {}
+  /// Abstract method that must be implemented in sub-classes
+  virtual bool visit(const GLActor *) = 0;
+  virtual bool visit(const GLActorCollection *);
+  virtual bool visit(const CompAssemblyActor *);
+  virtual bool visit(const ObjCompAssemblyActor *);
+  virtual bool visit(const ComponentActor *);
+  virtual bool visit(const InstrumentActor *);
+  virtual bool visit(const RectangularDetectorActor *);
+  virtual bool visit(const StructuredDetectorActor *);
+};
 
+/*
+* The visit() method implemented by sub-classes must return true if an actor
+* is set visible and false otherwise. This is requered by
+*GLActorCollection::accept()
+* method to determine whether the collection itself is visible or not.
+*
+* All visitors changing visibility should be sub-classed from this base class.
+*/
+class SetVisibilityVisitor : public GLActorVisitor {};
 
-		/**
-		* A base class for an actor visitor.
-		*/
-		class GLActorVisitor
-		{
-		public:
-			/// Virtual destructor.
-			virtual ~GLActorVisitor() {}
-			/// Abstract method that must be implemented in sub-classes
-			virtual bool visit(GLActor*) = 0;
-			virtual bool visit(GLActorCollection*);
-			virtual bool visit(CompAssemblyActor*);
-			virtual bool visit(ObjCompAssemblyActor*);
-			virtual bool visit(ComponentActor*);
-			virtual bool visit(InstrumentActor*);
-			virtual bool visit(RectangularDetectorActor*);
-			virtual bool visit(StructuredDetectorActor*);
-		};
-
-		/**
-		* A base class for an actor visitor (const version).
-		*/
-		class GLActorConstVisitor
-		{
-		public:
-			/// Virtual destructor.
-			virtual ~GLActorConstVisitor() {}
-			/// Abstract method that must be implemented in sub-classes
-			virtual bool visit(const GLActor*) = 0;
-			virtual bool visit(const GLActorCollection*);
-			virtual bool visit(const CompAssemblyActor*);
-			virtual bool visit(const ObjCompAssemblyActor*);
-			virtual bool visit(const ComponentActor*);
-			virtual bool visit(const InstrumentActor*);
-			virtual bool visit(const RectangularDetectorActor*);
-			virtual bool visit(const StructuredDetectorActor *);
-		};
-
-
-
-		/*
-		* The visit() method implemented by sub-classes must return true if an actor
-		* is set visible and false otherwise. This is requered by GLActorCollection::accept()
-		* method to determine whether the collection itself is visible or not.
-		*
-		* All visitors changing visibility should be sub-classed from this base class.
-		*/
-		class SetVisibilityVisitor : public GLActorVisitor
-		{
-		};
-
-		/**
-		* Set all actors visible.
-		*/
-		class SetAllVisibleVisitor : public SetVisibilityVisitor
-		{
-		public:
-			explicit SetAllVisibleVisitor(bool showNonDet) : m_showNonDet(showNonDet) {}
-			using GLActorVisitor::visit;
-                        bool visit(GLActor *) override;
-                        bool visit(ComponentActor *actor) override;
-
-                private:
-			bool m_showNonDet;
-		};
-	}//MantidWidgets
-}//MantidQt
+/**
+* Set all actors visible.
+*/
+class SetAllVisibleVisitor : public SetVisibilityVisitor {
+public:
+  explicit SetAllVisibleVisitor(bool showNonDet) : m_showNonDet(showNonDet) {}
+  using GLActorVisitor::visit;
+  bool visit(GLActor *) override;
+  bool visit(ComponentActor *actor) override;
 
+private:
+  bool m_showNonDet;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif // GLACTORVISITOR_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLColor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLColor.h
index 093e2b98c3c908de4e2463d54ba597d6b6c74878..5cda5822dd6ab57edea8e1d88e9f5964f1b56e97 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLColor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLColor.h
@@ -3,74 +3,70 @@
 
 #include <iosfwd>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		\class  GLColor
-		\brief  class handling OpenGL color for objects
-		\author Chapon Laurent & Srikanth Nagella
-		\date   August 2008
-		\version 1.0
-
-		GLColor class handles the OpenGL color for an object based on the type of the
-		rendering selected. eg. MATERIAL by specifying color as glMaterial rather than
-		glColor.
-
-		Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-		This file is part of Mantid.
-
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
-
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
-
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-		class GLColor
-		{
-		public:
-
-			/// Default Constructor
-			GLColor(float red = 0, float green = 0, float blue = 0, float alpha = 1.0f);
-			GLColor(int r, int g, int b);
-			/// Destructor
-			virtual ~GLColor();
-
-			/// Set all four values atomically
-			void set(float red, float green, float blue, float alpha);
-			/// Retrieve the component colours
-			void get(float&, float&, float&, float&)const;
-			void get(unsigned char& r, unsigned char& g, unsigned char& b)const;
-			/// Retrieve the component colours
-			void getUB3(unsigned char* c)const;
-			/// Set the painting method
-			void paint()const;
-			int red()const { return int(m_rgba[0]); }
-			int green()const { return int(m_rgba[1]); }
-			int blue()const { return int(m_rgba[2]); }
-			int alpha()const { return int(m_rgba[3]); }
-
-		private:
-			/// The individual components
-			//float m_rgba[4];
-			unsigned char m_rgba[4];
-		};
-
-		std::ostream& operator<<(std::ostream& ostr, const GLColor& c);
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+\class  GLColor
+\brief  class handling OpenGL color for objects
+\author Chapon Laurent & Srikanth Nagella
+\date   August 2008
+\version 1.0
+
+GLColor class handles the OpenGL color for an object based on the type of the
+rendering selected. eg. MATERIAL by specifying color as glMaterial rather than
+glColor.
+
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+class GLColor {
+public:
+  /// Default Constructor
+  GLColor(float red = 0, float green = 0, float blue = 0, float alpha = 1.0f);
+  GLColor(int r, int g, int b);
+  /// Destructor
+  virtual ~GLColor();
+
+  /// Set all four values atomically
+  void set(float red, float green, float blue, float alpha);
+  /// Retrieve the component colours
+  void get(float &, float &, float &, float &) const;
+  void get(unsigned char &r, unsigned char &g, unsigned char &b) const;
+  /// Retrieve the component colours
+  void getUB3(unsigned char *c) const;
+  /// Set the painting method
+  void paint() const;
+  int red() const { return int(m_rgba[0]); }
+  int green() const { return int(m_rgba[1]); }
+  int blue() const { return int(m_rgba[2]); }
+  int alpha() const { return int(m_rgba[3]); }
+
+private:
+  /// The individual components
+  // float m_rgba[4];
+  unsigned char m_rgba[4];
+};
+
+std::ostream &operator<<(std::ostream &ostr, const GLColor &c);
+} // MantidWidgets
+} // MantidQt
 
 #endif /*GLCOLOR_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLObject.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLObject.h
index c68ae4e182285b103c796620f6f46586a87c8ca9..72ec2f6d741a5f1af8eb4f0f186471dd31d8ea5a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLObject.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/GLObject.h
@@ -4,73 +4,73 @@
 #include <string>
 #include "MantidGeometry/Rendering/OpenGL_Headers.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		\class  GLObject
-		\brief  Interface for OpenGL object stored in a display list
-		\author Chapon Laurent & Srikanth Nagella
-		\date   August 2008
-		\version 1.0
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+\class  GLObject
+\brief  Interface for OpenGL object stored in a display list
+\author Chapon Laurent & Srikanth Nagella
+\date   August 2008
+\version 1.0
 
-		Concrete GLObject need to overload the "define" function giving OpenGL commands for representing
-		the object. The device displaying OpenGL should call the initialization of OpenGL before any
-		GLObject is created otherwise glGenLists return systematically 0.
+Concrete GLObject need to overload the "define" function giving OpenGL commands
+for representing
+the object. The device displaying OpenGL should call the initialization of
+OpenGL before any
+GLObject is created otherwise glGenLists return systematically 0.
 
-		Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-		This file is part of Mantid.
+This file is part of Mantid.
 
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-		class GLObject
-		{
-		public:
-			/// Type of the GL object
-			static const std::string type() { return "GLObject"; }
-			/// Construct a GLObject in direct rendering mode (withDisplayList=false)
-			/// or using a display list (withDisplayList=true).
-			/// @param withDisplayList: rendering mode
-			/// @param name: name of the object
-			GLObject(bool withDisplayList, const std::string& name = "");
-			/// Destructor
-			virtual ~GLObject();
-			/// Draw the object in direct mode or using glCallList
-			void draw()const;
-			/// Define the drawing here.
-			virtual void define()const;
-			/// Don't know about this
-			virtual void init()const;
-			/// Set the name of the GLObject
-			void setName(const std::string& name);
-			/// Get the name of the GLObject
-			std::string getName() const;
-			/// Re-construct the opengl scene
-			void construct()const;
-			virtual void update()const { mChanged = true; }
-		protected:
-			/// Name
-			std::string mName;
-			mutable GLuint mDisplayListId;                   ///< OpengGL Display list id
-			mutable bool mChanged;                         ///< Flag holding the change in the object
-		};
-	}//MantidWidgets
-}//MantidQt
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+class GLObject {
+public:
+  /// Type of the GL object
+  static const std::string type() { return "GLObject"; }
+  /// Construct a GLObject in direct rendering mode (withDisplayList=false)
+  /// or using a display list (withDisplayList=true).
+  /// @param withDisplayList: rendering mode
+  /// @param name: name of the object
+  GLObject(bool withDisplayList, const std::string &name = "");
+  /// Destructor
+  virtual ~GLObject();
+  /// Draw the object in direct mode or using glCallList
+  void draw() const;
+  /// Define the drawing here.
+  virtual void define() const;
+  /// Don't know about this
+  virtual void init() const;
+  /// Set the name of the GLObject
+  void setName(const std::string &name);
+  /// Get the name of the GLObject
+  std::string getName() const;
+  /// Re-construct the opengl scene
+  void construct() const;
+  virtual void update() const { mChanged = true; }
 
-#endif /*MANTIDPLOT_GLOBJECT_H*/
+protected:
+  /// Name
+  std::string mName;
+  mutable GLuint mDisplayListId; ///< OpengGL Display list id
+  mutable bool mChanged;         ///< Flag holding the change in the object
+};
+} // MantidWidgets
+} // MantidQt
 
+#endif /*MANTIDPLOT_GLOBJECT_H*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeModel.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeModel.h
index 1e7c5b4b942672b4676eeaf5b52aaf87135cb05a..63b623fe1aef8203abdf13ece77b00e813fe9e9f 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeModel.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeModel.h
@@ -6,51 +6,41 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentActor;
-
-		/**
-		* The InstrumentTreeModel is a class used by a QTreeView
-		* in order to display the components of an instrument as a
-		* hierarchical tree view.
-		*
-		* It fills out the nodes in the tree as requested.
-		*
-		* Author: ???
-		*
-		*/
-		class InstrumentTreeModel :public QAbstractItemModel
-		{
-			Q_OBJECT
-		public:
-			InstrumentTreeModel(const InstrumentActor*, QObject *parent);
-                        ~InstrumentTreeModel() override;
-
-                        QVariant data(const QModelIndex &index,
-                                      int role) const override;
-                        Qt::ItemFlags
-                        flags(const QModelIndex &index) const override;
-                        QVariant
-                        headerData(int section, Qt::Orientation orientation,
-                                   int role = Qt::DisplayRole) const override;
-                        QModelIndex index(int row, int column,
-                                          const QModelIndex &parent =
-                                              QModelIndex()) const override;
-                        QModelIndex
-                        parent(const QModelIndex &index) const override;
-                        int rowCount(const QModelIndex &paren =
-                                         QModelIndex()) const override;
-                        int columnCount(const QModelIndex &parent =
-                                            QModelIndex()) const override;
-
-                private:
-			const InstrumentActor *m_instrumentActor; ///< actor of instrument to which the model corresponds
-		};
-	}//MantidWidgets
-}//MantidQt
-
-
-#endif //INSTRUMENTTREEMODEL_H
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentActor;
+
+/**
+* The InstrumentTreeModel is a class used by a QTreeView
+* in order to display the components of an instrument as a
+* hierarchical tree view.
+*
+* It fills out the nodes in the tree as requested.
+*
+* Author: ???
+*
+*/
+class InstrumentTreeModel : public QAbstractItemModel {
+  Q_OBJECT
+public:
+  InstrumentTreeModel(const InstrumentActor *, QObject *parent);
+  ~InstrumentTreeModel() override;
+
+  QVariant data(const QModelIndex &index, int role) const override;
+  Qt::ItemFlags flags(const QModelIndex &index) const override;
+  QVariant headerData(int section, Qt::Orientation orientation,
+                      int role = Qt::DisplayRole) const override;
+  QModelIndex index(int row, int column,
+                    const QModelIndex &parent = QModelIndex()) const override;
+  QModelIndex parent(const QModelIndex &index) const override;
+  int rowCount(const QModelIndex &paren = QModelIndex()) const override;
+  int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+
+private:
+  const InstrumentActor *
+      m_instrumentActor; ///< actor of instrument to which the model corresponds
+};
+} // MantidWidgets
+} // MantidQt
+
+#endif // INSTRUMENTTREEMODEL_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeWidget.h
index 3deff7c4913ca88f71abd7a240ec449794df989b..d7dd3f36826ce9546701ddb15b34e0f99a3339aa 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentTreeWidget.h
@@ -9,37 +9,37 @@
 #include "InstrumentTreeModel.h"
 #include "MantidGeometry/IComponent.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		//---------------------------------------
-		// Forward declarations
-		//--------------------------------------
-		class InstrumentActor;
+namespace MantidQt {
+namespace MantidWidgets {
+//---------------------------------------
+// Forward declarations
+//--------------------------------------
+class InstrumentActor;
 
-		/** The InstrumentTreeWidget is a tree view
-		*  of the components of an instrument.
-		*/
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentTreeWidget :public QTreeView
-		{
-			Q_OBJECT
-		public:
-			explicit InstrumentTreeWidget(QWidget *w);
-			void setInstrumentActor(InstrumentActor* instrActor);
-			void getSelectedBoundingBox(const QModelIndex& index, double &xmax, double &ymax, double &zmax, double &xmin, double &ymin, double &zmin);
-			//Mantid::Kernel::V3D getSamplePos()const;
-			QModelIndex findComponentByName(const QString & name) const;
-			public slots:
-			void sendComponentSelectedSignal(const QModelIndex);
-		signals:
-			void componentSelected(const Mantid::Geometry::ComponentID);
-		private:
-			InstrumentActor* m_instrActor;
-			InstrumentTreeModel *m_treeModel;
-		};
-	}//MantidWidgets
-}//MantidQt
+/** The InstrumentTreeWidget is a tree view
+*  of the components of an instrument.
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentTreeWidget
+    : public QTreeView {
+  Q_OBJECT
+public:
+  explicit InstrumentTreeWidget(QWidget *w);
+  void setInstrumentActor(InstrumentActor *instrActor);
+  void getSelectedBoundingBox(const QModelIndex &index, double &xmax,
+                              double &ymax, double &zmax, double &xmin,
+                              double &ymin, double &zmin);
+  // Mantid::Kernel::V3D getSamplePos()const;
+  QModelIndex findComponentByName(const QString &name) const;
+public slots:
+  void sendComponentSelectedSignal(const QModelIndex);
+signals:
+  void componentSelected(const Mantid::Geometry::ComponentID);
 
+private:
+  InstrumentActor *m_instrActor;
+  InstrumentTreeModel *m_treeModel;
+};
+} // MantidWidgets
+} // MantidQt
 
-#endif //INSTRUMENTTREEWIDGET_H
+#endif // INSTRUMENTTREEWIDGET_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetMaskTab.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetMaskTab.h
index caebffde5163ee15f474e97757dac07534701b66..71b3eda9337788e1a1838052f73273c4e3c0e395 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetMaskTab.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetMaskTab.h
@@ -14,7 +14,6 @@
 
 class Instrument3DWidget;
 
-
 class QPushButton;
 class QRadioButton;
 class QTextEdit;
@@ -34,160 +33,164 @@ class QtEnumPropertyManager;
 class QtProperty;
 class QtBrowserItem;
 
-namespace Mantid
-{
-  namespace API
-  {
-    class MatrixWorkspace;
-  }
+namespace Mantid {
+namespace API {
+class MatrixWorkspace;
+}
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class CollapsiblePanel;
-		class OneCurvePlot;
-		class Shape2D;
-
-		/**
-		* Implements the Mask/Group tab in InstrumentWidget.
-		*
-		* Contains controls to create, manipulate and apply masking and grouping to underlying workspace.
-		*
-		*/
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetMaskTab : public InstrumentWidgetTab
-		{
-			Q_OBJECT
-		public:
-			enum Mode { Mask, Group, ROI };
-			enum Activity { Move, Select, DrawEllipse, DrawRectangle, DrawEllipticalRing, DrawRectangularRing, DrawFree };
-
-			explicit InstrumentWidgetMaskTab(InstrumentWidget *instrWidget);
-                        void initSurface() override;
-                        void setMode(Mode mode);
-			void selectTool(Activity tool);
-
-		signals:
-			void executeAlgorithm(const QString&, const QString&);
-
-			public slots:
-			void changedIntegrationRange(double, double);
-
-			protected slots:
-			void setActivity();
-			void shapeCreated();
-			void shapeSelected();
-			void shapesDeselected();
-			void shapeChanged();
-			void shapesCleared();
-			void clearShapes();
-			void applyMask();
-			void applyMaskToView();
-			void storeDetectorMask(bool isROI = false);
-			void storeBinMask();
-			void storeMask();
-			void clearMask();
-			void saveInvertedMaskToWorkspace();
-			void saveInvertedMaskToFile();
-			void saveMaskToWorkspace();
-			void saveMaskToFile();
-			void saveMaskToCalFile();
-			void saveMaskToTable();
-			void saveInvertedMaskToCalFile();
-			void extractDetsToWorkspace();
-			void sumDetsToWorkspace();
-			void saveIncludeGroupToFile();
-			void saveExcludeGroupToFile();
-			void showSaveMenuTooltip(QAction*);
-			void toggleMaskGroup();
-
-			void doubleChanged(QtProperty*);
-		protected:
-                  void showEvent(QShowEvent *) override;
-
-                        void clearProperties();
-			void setProperties();
-			boost::shared_ptr<Mantid::API::MatrixWorkspace> createMaskWorkspace(bool invertMask, bool temp = false);
-			void saveMaskingToWorkspace(bool invertMask = false);
-			void saveMaskingToFile(bool invertMask = false);
-			void saveMaskingToCalFile(bool invertMask = false);
-			void saveMaskingToTableWorkspace(bool invertMask = false);
-			std::string generateMaskWorkspaceName(bool temp = false) const;
-			void enableApplyButtons();
-			void setSelectActivity();
-			Mode getMode() const;
-			/// Get mask/group border color
-			QColor getShapeBorderColor() const;
-			/// Get mask/group fill color
-			QColor getShapeFillColor() const;
-			/// Add a double property to the shape property browser
-			QtProperty* addDoubleProperty(const QString& name)const;
-
-			/// Is it used?
-			Activity m_activity;
-			/// True if there is a mask not applied to the data workspace
-			bool m_hasMaskToApply;
-
-			QRadioButton* m_masking_on;
-			QRadioButton* m_grouping_on;
-			QRadioButton* m_roi_on;
-
-			QLabel *m_activeTool; ///< Displays a tip on which tool is currently selected
-
-									// buttons
-			QPushButton* m_move;
-			QPushButton* m_pointer;
-			QPushButton* m_ellipse;
-			QPushButton* m_rectangle;
-			QPushButton* m_ring_ellipse;
-			QPushButton* m_ring_rectangle;
-			QPushButton* m_free_draw;
-
-			QPushButton* m_applyToData;
-			QPushButton* m_applyToView;
-			QPushButton* m_clearAll;
-			QPushButton* m_saveButton;
-			bool m_maskBins;
-
-
-			QMenu* m_saveMask;
-			QAction* m_save_as_file_exclude;
-			QAction* m_save_as_cal_file_exclude;
-			QAction *m_save_as_table_xrange_exclude;
-
-			QMenu* m_saveGroup;
-			QAction* m_extract_to_workspace;
-			QAction* m_sum_to_workspace;
-			QAction* m_save_group_file_include;
-			QAction* m_save_group_file_exclude;
-
-
-			QMenu* m_saveROI;
-			QAction* m_save_as_workspace_include;
-			QAction* m_save_as_workspace_exclude;
-			QAction* m_save_as_file_include;
-			QAction* m_save_as_cal_file_include;
-
-			// properties
-			bool m_userEditing;
-			QtGroupPropertyManager  *m_groupManager;
-			QtStringPropertyManager *m_stringManager;
-			QtDoublePropertyManager *m_doubleManager;
-
-			QtTreePropertyBrowser* m_browser;
-
-			QtProperty *m_left;
-			QtProperty *m_top;
-			QtProperty *m_right;
-			QtProperty *m_bottom;
-
-			QMap<QtProperty *, QString> m_doublePropertyMap;
-			QMap<QString, QtProperty *> m_pointPropertyMap;
-			QMap<QtProperty *, QString> m_pointComponentsMap;
-
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+class CollapsiblePanel;
+class OneCurvePlot;
+class Shape2D;
+
+/**
+* Implements the Mask/Group tab in InstrumentWidget.
+*
+* Contains controls to create, manipulate and apply masking and grouping to
+*underlying workspace.
+*
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetMaskTab
+    : public InstrumentWidgetTab {
+  Q_OBJECT
+public:
+  enum Mode { Mask, Group, ROI };
+  enum Activity {
+    Move,
+    Select,
+    DrawEllipse,
+    DrawRectangle,
+    DrawEllipticalRing,
+    DrawRectangularRing,
+    DrawFree
+  };
+
+  explicit InstrumentWidgetMaskTab(InstrumentWidget *instrWidget);
+  void initSurface() override;
+  void setMode(Mode mode);
+  void selectTool(Activity tool);
+
+signals:
+  void executeAlgorithm(const QString &, const QString &);
+
+public slots:
+  void changedIntegrationRange(double, double);
+
+protected slots:
+  void setActivity();
+  void shapeCreated();
+  void shapeSelected();
+  void shapesDeselected();
+  void shapeChanged();
+  void shapesCleared();
+  void clearShapes();
+  void applyMask();
+  void applyMaskToView();
+  void storeDetectorMask(bool isROI = false);
+  void storeBinMask();
+  void storeMask();
+  void clearMask();
+  void saveInvertedMaskToWorkspace();
+  void saveInvertedMaskToFile();
+  void saveMaskToWorkspace();
+  void saveMaskToFile();
+  void saveMaskToCalFile();
+  void saveMaskToTable();
+  void saveInvertedMaskToCalFile();
+  void extractDetsToWorkspace();
+  void sumDetsToWorkspace();
+  void saveIncludeGroupToFile();
+  void saveExcludeGroupToFile();
+  void showSaveMenuTooltip(QAction *);
+  void toggleMaskGroup();
+
+  void doubleChanged(QtProperty *);
+
+protected:
+  void showEvent(QShowEvent *) override;
+
+  void clearProperties();
+  void setProperties();
+  boost::shared_ptr<Mantid::API::MatrixWorkspace>
+  createMaskWorkspace(bool invertMask, bool temp = false);
+  void saveMaskingToWorkspace(bool invertMask = false);
+  void saveMaskingToFile(bool invertMask = false);
+  void saveMaskingToCalFile(bool invertMask = false);
+  void saveMaskingToTableWorkspace(bool invertMask = false);
+  std::string generateMaskWorkspaceName(bool temp = false) const;
+  void enableApplyButtons();
+  void setSelectActivity();
+  Mode getMode() const;
+  /// Get mask/group border color
+  QColor getShapeBorderColor() const;
+  /// Get mask/group fill color
+  QColor getShapeFillColor() const;
+  /// Add a double property to the shape property browser
+  QtProperty *addDoubleProperty(const QString &name) const;
+
+  /// Is it used?
+  Activity m_activity;
+  /// True if there is a mask not applied to the data workspace
+  bool m_hasMaskToApply;
+
+  QRadioButton *m_masking_on;
+  QRadioButton *m_grouping_on;
+  QRadioButton *m_roi_on;
+
+  QLabel *m_activeTool; ///< Displays a tip on which tool is currently selected
+
+  // buttons
+  QPushButton *m_move;
+  QPushButton *m_pointer;
+  QPushButton *m_ellipse;
+  QPushButton *m_rectangle;
+  QPushButton *m_ring_ellipse;
+  QPushButton *m_ring_rectangle;
+  QPushButton *m_free_draw;
+
+  QPushButton *m_applyToData;
+  QPushButton *m_applyToView;
+  QPushButton *m_clearAll;
+  QPushButton *m_saveButton;
+  bool m_maskBins;
+
+  QMenu *m_saveMask;
+  QAction *m_save_as_file_exclude;
+  QAction *m_save_as_cal_file_exclude;
+  QAction *m_save_as_table_xrange_exclude;
+
+  QMenu *m_saveGroup;
+  QAction *m_extract_to_workspace;
+  QAction *m_sum_to_workspace;
+  QAction *m_save_group_file_include;
+  QAction *m_save_group_file_exclude;
+
+  QMenu *m_saveROI;
+  QAction *m_save_as_workspace_include;
+  QAction *m_save_as_workspace_exclude;
+  QAction *m_save_as_file_include;
+  QAction *m_save_as_cal_file_include;
+
+  // properties
+  bool m_userEditing;
+  QtGroupPropertyManager *m_groupManager;
+  QtStringPropertyManager *m_stringManager;
+  QtDoublePropertyManager *m_doubleManager;
+
+  QtTreePropertyBrowser *m_browser;
+
+  QtProperty *m_left;
+  QtProperty *m_top;
+  QtProperty *m_right;
+  QtProperty *m_bottom;
+
+  QMap<QtProperty *, QString> m_doublePropertyMap;
+  QMap<QString, QtProperty *> m_pointPropertyMap;
+  QMap<QtProperty *, QString> m_pointComponentsMap;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*INSTRUMENTWIDGETMASKTAB_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetPickTab.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetPickTab.h
index 8b9c8996c38059872825d744e2c45fdd0b617ed6..bc2d55831b71b73a699ab3f3f9c793de7e4075e1 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetPickTab.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetPickTab.h
@@ -115,15 +115,15 @@ private:
   QPushButton *m_peak; ///< Button switching on peak creation mode
   QPushButton *m_peakSelect; ///< Button switching on peak selection mode
   QPushButton *m_rectangle;  ///< Button switching on drawing a rectangular
-                             ///selection region
-  QPushButton
-      *m_ellipse; ///< Button switching on drawing a elliptical selection region
-  QPushButton *m_ring_ellipse;   ///< Button switching on drawing a elliptical
-                                 ///ring selection region
+  /// selection region
+  QPushButton *
+      m_ellipse; ///< Button switching on drawing a elliptical selection region
+  QPushButton *m_ring_ellipse; ///< Button switching on drawing a elliptical
+  /// ring selection region
   QPushButton *m_ring_rectangle; ///< Button switching on drawing a rectangular
-                                 ///ring selection region
-  QPushButton
-      *m_free_draw; ///< Button switching on drawing a region of arbitrary shape
+  /// ring selection region
+  QPushButton *
+      m_free_draw; ///< Button switching on drawing a region of arbitrary shape
   QPushButton *m_edit; ///< Button switching on edditing the selection region
   bool m_plotSum;
 
@@ -141,13 +141,13 @@ private:
 
   // Instrument display context menu actions
   QAction *m_storeCurve; ///< add the current curve to the list of permanently
-                         ///displayed curves
+  /// displayed curves
   QAction *m_savePlotToWorkspace; ///< Save data plotted on the miniplot into a
-                                  ///MatrixWorkspace
+  /// MatrixWorkspace
 
   CollapsiblePanel *m_plotPanel;
   QTextEdit *m_selectionInfoDisplay; ///< Text control for displaying selection
-                                     ///information
+  /// information
   CollapsiblePanel *m_infoPanel;
   SelectionType m_selectionType;
   mutable bool m_freezePlot;
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTab.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTab.h
index b05a00b29d2609e3d9737216e1d16c98d57d990a..9b7dfa5250e9623ab7514ecdac37340dc8143a5f 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTab.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTab.h
@@ -14,36 +14,36 @@
 class QSettings;
 class QMenu;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentWidget;
-		class ProjectionSurface;
-
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTab : public QFrame, public InstrumentWidgetTypes
-		{
-			Q_OBJECT
-		public:
-			explicit InstrumentWidgetTab(InstrumentWidget *parent);
-			/// Called by InstrumentWidget after the projection surface crated
-			/// Use it for surface-specific initialization
-			virtual void initSurface() {}
-			/// Save tab's persistent settings to the provided QSettings instance
-			virtual void saveSettings(QSettings&)const {}
-			/// Load (read and apply) tab's persistent settings from the provided QSettings instance
-			virtual void loadSettings(const QSettings&) {}
-			/// Add tab-specific items to the context menu
-			/// Return true if at least 1 item was added or false otherwise.
-			virtual bool addToDisplayContextMenu(QMenu&) const { return false; }
-			/// Get the projection surface
-			boost::shared_ptr<ProjectionSurface> getSurface() const;
-		protected:
-			/// The parent InstrumentWidget
-			InstrumentWidget* m_instrWidget;
-
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentWidget;
+class ProjectionSurface;
+
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTab
+    : public QFrame,
+      public InstrumentWidgetTypes {
+  Q_OBJECT
+public:
+  explicit InstrumentWidgetTab(InstrumentWidget *parent);
+  /// Called by InstrumentWidget after the projection surface crated
+  /// Use it for surface-specific initialization
+  virtual void initSurface() {}
+  /// Save tab's persistent settings to the provided QSettings instance
+  virtual void saveSettings(QSettings &) const {}
+  /// Load (read and apply) tab's persistent settings from the provided
+  /// QSettings instance
+  virtual void loadSettings(const QSettings &) {}
+  /// Add tab-specific items to the context menu
+  /// Return true if at least 1 item was added or false otherwise.
+  virtual bool addToDisplayContextMenu(QMenu &) const { return false; }
+  /// Get the projection surface
+  boost::shared_ptr<ProjectionSurface> getSurface() const;
+
+protected:
+  /// The parent InstrumentWidget
+  InstrumentWidget *m_instrWidget;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif // INSTRUMENTWIDGETTAB_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTreeTab.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTreeTab.h
index 43116d7bdd4f0b5ed15ef86644236fd0c87f5004..907138bef671f0957beb8ade702782e0f80bf36a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTreeTab.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTreeTab.h
@@ -6,30 +6,28 @@
 
 #include <QModelIndex>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentTreeWidget;
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentTreeWidget;
 
-		/**
-			* Implements the instrument tree tab in InstrumentWidget
-			*/
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTreeTab : public InstrumentWidgetTab
-		{
-			Q_OBJECT
-		public:
-			explicit InstrumentWidgetTreeTab(InstrumentWidget *instrWidget);
-                        void initSurface() override;
-                        public slots:
-			void selectComponentByName(const QString& name);
-		private:
-                  void showEvent(QShowEvent *) override;
-                        /// Widget to display instrument tree
-			InstrumentTreeWidget* m_instrumentTree;
-		};
-	}//MantidWidgets
-}//MantidQt
+/**
+        * Implements the instrument tree tab in InstrumentWidget
+        */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTreeTab
+    : public InstrumentWidgetTab {
+  Q_OBJECT
+public:
+  explicit InstrumentWidgetTreeTab(InstrumentWidget *instrWidget);
+  void initSurface() override;
+public slots:
+  void selectComponentByName(const QString &name);
 
+private:
+  void showEvent(QShowEvent *) override;
+  /// Widget to display instrument tree
+  InstrumentTreeWidget *m_instrumentTree;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*INSTRUMENTWIDGETTREETAB_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTypes.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTypes.h
index e513c7516f1fc09dd2634894d17815193806b7df..86e9b045ed5f1e77cf50537d2e2e29f1d24aaf61 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTypes.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTypes.h
@@ -3,27 +3,24 @@
 
 #include <MantidQtMantidWidgets/WidgetDllOption.h>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTypes {
-
-		public:
-			enum SurfaceType {
-				FULL3D = 0,
-				CYLINDRICAL_X,
-				CYLINDRICAL_Y,
-				CYLINDRICAL_Z,
-				SPHERICAL_X,
-				SPHERICAL_Y,
-				SPHERICAL_Z,
-				SIDE_BY_SIDE,
-				RENDERMODE_SIZE
-			};
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS InstrumentWidgetTypes {
 
+public:
+  enum SurfaceType {
+    FULL3D = 0,
+    CYLINDRICAL_X,
+    CYLINDRICAL_Y,
+    CYLINDRICAL_Z,
+    SPHERICAL_X,
+    SPHERICAL_Y,
+    SPHERICAL_Z,
+    SIDE_BY_SIDE,
+    RENDERMODE_SIZE
+  };
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*INSTRUMENTWIDGETTYPES_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MantidGLWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MantidGLWidget.h
index 291a9a3f50ff4698d2febef11214845cd7545359..eb174f43fe7781d5103ab84aa155edc53dbf975e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MantidGLWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MantidGLWidget.h
@@ -8,69 +8,63 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-			class ProjectionSurface;
+namespace MantidQt {
+namespace MantidWidgets {
+class ProjectionSurface;
 
-			/**
-			\class  MantidGLWidget
-			\brief  OpenGL Qt Widget which renders Mantid Geometry ObjComponents
-			*/
+/**
+\class  MantidGLWidget
+\brief  OpenGL Qt Widget which renders Mantid Geometry ObjComponents
+*/
 
-			class MantidGLWidget : public QGLWidget
-			{
-				Q_OBJECT
-			public:
-				explicit MantidGLWidget(QWidget *parent = 0); ///< Constructor
-                                ~MantidGLWidget() override; ///< Destructor
-                                void setSurface(boost::shared_ptr<ProjectionSurface> surface);
-				boost::shared_ptr<ProjectionSurface> getSurface() { return m_surface; }
+class MantidGLWidget : public QGLWidget {
+  Q_OBJECT
+public:
+  explicit MantidGLWidget(QWidget *parent = 0); ///< Constructor
+  ~MantidGLWidget() override;                   ///< Destructor
+  void setSurface(boost::shared_ptr<ProjectionSurface> surface);
+  boost::shared_ptr<ProjectionSurface> getSurface() { return m_surface; }
 
-				void setBackgroundColor(QColor);
-				QColor currentBackgroundColor() const;
-				void saveToFile(const QString & filename);
-				//int getLightingState() const {return m_lightingState;}
+  void setBackgroundColor(QColor);
+  QColor currentBackgroundColor() const;
+  void saveToFile(const QString &filename);
+  // int getLightingState() const {return m_lightingState;}
 
-				public slots:
-				void enableLighting(bool);
-				void updateView(bool picking = true);
-				void updateDetectors();
-				void componentSelected(Mantid::Geometry::ComponentID id);
+public slots:
+  void enableLighting(bool);
+  void updateView(bool picking = true);
+  void updateDetectors();
+  void componentSelected(Mantid::Geometry::ComponentID id);
 
-			protected:
-                          void initializeGL() override;
-                                void resetWidget();
-				void MakeObject();
-                                void paintEvent(QPaintEvent *event) override;
-                                void resizeGL(int, int) override;
-                                void
-                                contextMenuEvent(QContextMenuEvent *) override;
-                                void mousePressEvent(QMouseEvent *) override;
-                                void mouseMoveEvent(QMouseEvent *) override;
-                                void mouseReleaseEvent(QMouseEvent *) override;
-                                void wheelEvent(QWheelEvent *) override;
-                                void keyPressEvent(QKeyEvent *) override;
-                                void keyReleaseEvent(QKeyEvent *) override;
-                                void enterEvent(QEvent *) override;
-                                void leaveEvent(QEvent *) override;
-                                void draw();
-				void checkGLError(const QString& funName);
-			private:
-				void setRenderingOptions();
+protected:
+  void initializeGL() override;
+  void resetWidget();
+  void MakeObject();
+  void paintEvent(QPaintEvent *event) override;
+  void resizeGL(int, int) override;
+  void contextMenuEvent(QContextMenuEvent *) override;
+  void mousePressEvent(QMouseEvent *) override;
+  void mouseMoveEvent(QMouseEvent *) override;
+  void mouseReleaseEvent(QMouseEvent *) override;
+  void wheelEvent(QWheelEvent *) override;
+  void keyPressEvent(QKeyEvent *) override;
+  void keyReleaseEvent(QKeyEvent *) override;
+  void enterEvent(QEvent *) override;
+  void leaveEvent(QEvent *) override;
+  void draw();
+  void checkGLError(const QString &funName);
 
-				//int m_lightingState;           ///< 0 = light off; 2 = light on
-				bool m_isKeyPressed;
-				bool m_firstFrame;
+private:
+  void setRenderingOptions();
 
-				/// Surface
-				boost::shared_ptr<ProjectionSurface> m_surface;
-
-			};
-	}//MantidWidgets
-}//MantidQt
+  // int m_lightingState;           ///< 0 = light off; 2 = light on
+  bool m_isKeyPressed;
+  bool m_firstFrame;
 
+  /// Surface
+  boost::shared_ptr<ProjectionSurface> m_surface;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MANTIDGLWIDGET_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MaskBinsData.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MaskBinsData.h
index ce613791a033f7ac4186cc00b5133cdc1ecd4141..63c5b6cac57deab633ffac73c2f9d5d4d9a3a35d 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MaskBinsData.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/MaskBinsData.h
@@ -9,53 +9,52 @@
 #include <QMap>
 #include <QList>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		Class for storing information on masked bins in a workspace.
-
-		Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-		This file is part of Mantid.
-
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
-
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
-
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-		class MaskBinsData {
-		public:
-			void addXRange(double start, double end, const QList<int>& indices);
-			void mask(const std::string& wsName) const;
-			bool isEmpty() const;
-			void subtractIntegratedSpectra(const Mantid::API::MatrixWorkspace& workspace, std::vector<double>& spectraIntgrs) const;
-			void clear();
-		private:
-			/// Range of x values to mask in a spectrum. (Using MaskBins)
-			struct BinMask
-			{
-				BinMask(double s = 0.0, double e = 0.0) : start(s), end(e) {}
-				double start;
-				double end;
-				QList<int> spectra;
-			};
-			QList<BinMask> m_masks;
-		};
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+Class for storing information on masked bins in a workspace.
+
+Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+class MaskBinsData {
+public:
+  void addXRange(double start, double end, const QList<int> &indices);
+  void mask(const std::string &wsName) const;
+  bool isEmpty() const;
+  void subtractIntegratedSpectra(const Mantid::API::MatrixWorkspace &workspace,
+                                 std::vector<double> &spectraIntgrs) const;
+  void clear();
+
+private:
+  /// Range of x values to mask in a spectrum. (Using MaskBins)
+  struct BinMask {
+    BinMask(double s = 0.0, double e = 0.0) : start(s), end(e) {}
+    double start;
+    double end;
+    QList<int> spectra;
+  };
+  QList<BinMask> m_masks;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MASKBINSDATA_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjCompAssemblyActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjCompAssemblyActor.h
index a59c296f257ebff5fa2752a3e691d57cd08c9874..8cde9c9a31afd8b7fe8a86968dee755097658063 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjCompAssemblyActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjCompAssemblyActor.h
@@ -7,87 +7,87 @@
 #include "MantidKernel/V3D.h"
 
 class TexObject;
-namespace Mantid{
-	namespace Geometry{
-    class ObjCompAssembly;
-	}
+namespace Mantid {
+namespace Geometry {
+class ObjCompAssembly;
+}
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		\class  ObjCompAssemblyActor
-		\brief  This class wraps the ICompAssembly into Actor.
-		\author Srikanth Nagella
-		\date   March 2009
-		\version 1.0
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+\class  ObjCompAssemblyActor
+\brief  This class wraps the ICompAssembly into Actor.
+\author Srikanth Nagella
+\date   March 2009
+\version 1.0
 
-		This class has the implementation for calling the children of ICompAssembly's IObjComponent to render themselves
-		and call the ICompAssemblys. This maintains the count of the children for easy lookup.
+This class has the implementation for calling the children of ICompAssembly's
+IObjComponent to render themselves
+and call the ICompAssemblys. This maintains the count of the children for easy
+lookup.
 
-		Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-		This file is part of Mantid.
+This file is part of Mantid.
 
-		Mantid is free software; you can redistribute it and/or modify
-		it under the terms of the GNU General Public License as published by
-		the Free Software Foundation; either version 3 of the License, or
-		(at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-		Mantid is distributed in the hope that it will be useful,
-		but WITHOUT ANY WARRANTY; without even the implied warranty of
-		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-		GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-		You should have received a copy of the GNU General Public License
-		along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-		File change history is stored at: <https://github.com/mantidproject/mantid>
-		*/
-		class ObjCompAssemblyActor : public ICompAssemblyActor
-		{
-		public:
-			/// Constructor
-			ObjCompAssemblyActor(const InstrumentActor& instrActor, Mantid::Geometry::ComponentID compID);
-                        ~ObjCompAssemblyActor() override; ///< Destructor
-                        std::string type() const override {
-                          return "ObjCompAssemblyActor";
-                        } ///< Type of the GL object
-                        void draw(bool picking = false)
-                            const override; ///< Method that defines
-                                            ///ObjComponent geometry. Calls
-                                            ///ObjComponent draw method
-                        // virtual void getBoundingBox(Mantid::Kernel::V3D&
-                        // minBound,Mantid::Kernel::V3D& maxBound)const;
-                        void setColors() override;
-                        bool accept(GLActorVisitor &visitor,
-                                    VisitorAcceptRule rule = VisitAll) override;
-                        bool accept(
-                            GLActorConstVisitor &visitor,
-                            VisitorAcceptRule rule = VisitAll) const override;
+File change history is stored at: <https://github.com/mantidproject/mantid>
+*/
+class ObjCompAssemblyActor : public ICompAssemblyActor {
+public:
+  /// Constructor
+  ObjCompAssemblyActor(const InstrumentActor &instrActor,
+                       Mantid::Geometry::ComponentID compID);
+  ~ObjCompAssemblyActor() override; ///< Destructor
+  std::string type() const override {
+    return "ObjCompAssemblyActor";
+  }                                               ///< Type of the GL object
+  void draw(bool picking = false) const override; ///< Method that defines
+  /// ObjComponent geometry. Calls
+  /// ObjComponent draw method
+  // virtual void getBoundingBox(Mantid::Kernel::V3D&
+  // minBound,Mantid::Kernel::V3D& maxBound)const;
+  void setColors() override;
+  bool accept(GLActorVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) override;
+  bool accept(GLActorConstVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) const override;
 
-                private:
-			void setDetectorColor(unsigned char* data, size_t i, GLColor c)const; ///< set colour to a detector
-			void setDataColors() const;
-			void setPickColors() const;
-			void generateTexture(unsigned char* data, unsigned int& id) const;
-			/// Swap between drawing counts and drawing detector code colours
-			void swap();
-			const unsigned char* getColor(int i)const;
+private:
+  void setDetectorColor(unsigned char *data, size_t i,
+                        GLColor c) const; ///< set colour to a detector
+  void setDataColors() const;
+  void setPickColors() const;
+  void generateTexture(unsigned char *data, unsigned int &id) const;
+  /// Swap between drawing counts and drawing detector code colours
+  void swap();
+  const unsigned char *getColor(int i) const;
 
-			std::vector<Mantid::detid_t> m_detIDs;     ///< List of Component IDs
-			mutable unsigned int m_idData;     ///< OpenGL texture id
-			mutable unsigned int m_idPick;     ///< OpenGL texture id
-			int m_n;               ///< texture size in one dimension, the other dimension is 1
-			unsigned char* m_data; ///< texture colour data
-			unsigned char* m_pick_data; ///< texture with detector code colours
-			mutable bool m_texturesGenerated; ///< true if the textures have been generated
-		};
+  std::vector<Mantid::detid_t> m_detIDs; ///< List of Component IDs
+  mutable unsigned int m_idData;         ///< OpenGL texture id
+  mutable unsigned int m_idPick;         ///< OpenGL texture id
+  int m_n; ///< texture size in one dimension, the other dimension is 1
+  unsigned char *m_data;      ///< texture colour data
+  unsigned char *m_pick_data; ///< texture with detector code colours
+  mutable bool
+      m_texturesGenerated; ///< true if the textures have been generated
+};
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
 
 #endif /*OBJCOMPASSEMBLY_ACTOR__H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjComponentActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjComponentActor.h
index d953452c0e66efa73c54512c260ab91eb820081f..6ffe582de33f1320781dbb6857e10fc32481172d 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjComponentActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ObjComponentActor.h
@@ -9,9 +9,11 @@
   \date   March 2009
   \version 1.0
 
-   This class has the implementation for rendering ObjComponents in OpenGL and it inherits from the GLActor
+   This class has the implementation for rendering ObjComponents in OpenGL and
+  it inherits from the GLActor
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -30,54 +32,47 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-namespace Mantid{
-  namespace Kernel
-  {
-    class V3D;
-  }
-
-  namespace Geometry
-  {
-		class IObjComponent;
-	}
+namespace Mantid {
+namespace Kernel {
+class V3D;
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentActor;
-
-		class ObjComponentActor : public ComponentActor
-		{
-		public:
-			ObjComponentActor(const InstrumentActor& instrActor, Mantid::Geometry::ComponentID compID); ///< Default Constructor
-                        ~ObjComponentActor() override; ///< Destructor
-                        std::string type() const override {
-                          return "ObjComponentActor";
-                        } ///< Type of the GL object
-                        void draw(bool picking = false)
-                            const override; ///< Method that defines
-                                            ///ObjComponent geometry. Calls
-                                            ///ObjComponent draw method
-                        void getBoundingBox(
-                            Mantid::Kernel::V3D &minBound,
-                            Mantid::Kernel::V3D &maxBound) const override;
-                        void setColors() override;
-
-                        void setColor(const GLColor& c) { m_dataColor = c; }
-
-		private:
-			void setPickColor(const GLColor& c) { m_pickColor = c; }
-
-			GLColor m_dataColor;
-			GLColor m_pickColor;
-
-			friend class InstrumentActor;
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace Geometry {
+class IObjComponent;
+}
+}
 
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentActor;
+
+class ObjComponentActor : public ComponentActor {
+public:
+  ObjComponentActor(
+      const InstrumentActor &instrActor,
+      Mantid::Geometry::ComponentID compID); ///< Default Constructor
+  ~ObjComponentActor() override;             ///< Destructor
+  std::string type() const override {
+    return "ObjComponentActor";
+  }                                               ///< Type of the GL object
+  void draw(bool picking = false) const override; ///< Method that defines
+  /// ObjComponent geometry. Calls
+  /// ObjComponent draw method
+  void getBoundingBox(Mantid::Kernel::V3D &minBound,
+                      Mantid::Kernel::V3D &maxBound) const override;
+  void setColors() override;
+
+  void setColor(const GLColor &c) { m_dataColor = c; }
+
+private:
+  void setPickColor(const GLColor &c) { m_pickColor = c; }
+
+  GLColor m_dataColor;
+  GLColor m_pickColor;
+
+  friend class InstrumentActor;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*OBJCOMPONENT_ACTOR_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OneCurvePlot.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OneCurvePlot.h
index ede3275afb503a86dd29afe5323bf65844f44a8c..36a75863968eeeb26b9605b0b3dbb55905612501 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OneCurvePlot.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OneCurvePlot.h
@@ -10,85 +10,80 @@
 class QwtPlotCurve;
 class QwtPlotZoomer;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class PeakLabel;
-		class PeakMarker2D;
+namespace MantidQt {
+namespace MantidWidgets {
+class PeakLabel;
+class PeakMarker2D;
 
-		/**
-		* Implements a simple widget for plotting a single curve.
-		* Allows to keep more than one curve.
-		*/
-		class OneCurvePlot : public QwtPlot
-		{
-			Q_OBJECT
-		public:
-			explicit OneCurvePlot(QWidget *parent);
-                        ~OneCurvePlot() override;
-                        void setData(const double* x, const double* y, int dataSize, const std::string& xUnits = "");
-			void setLabel(const QString& label);
-			QString label()const { return m_label; }
-			void setYAxisLabelRotation(double degrees);
-			void addPeakLabel(const PeakMarker2D*);
-			void clearPeakLabels();
-			bool hasCurve()const;
-			void store();
-			bool hasStored()const;
-			QStringList getLabels()const;
-			void removeCurve(const QString& label);
-			QColor getCurveColor(const QString& label)const;
-			void recalcXAxisDivs();
-			void recalcYAxisDivs();
-			bool isYLogScale()const;
-			const std::string& getXUnits() const { return m_xUnits; }
-			public slots:
-			void setXScale(double from, double to);
-			void setYScale(double from, double to);
-			void clearCurve();
-			void recalcAxisDivs();
-			void setYLogScale();
-			void setYLinearScale();
-			void clearAll();
-		signals:
-			void showContextMenu();
-			void clickedAt(double, double);
-		protected:
-                  void resizeEvent(QResizeEvent *e) override;
-                  void contextMenuEvent(QContextMenuEvent *e) override;
-                  void mousePressEvent(QMouseEvent *) override;
-                  void mouseReleaseEvent(QMouseEvent *) override;
+/**
+* Implements a simple widget for plotting a single curve.
+* Allows to keep more than one curve.
+*/
+class OneCurvePlot : public QwtPlot {
+  Q_OBJECT
+public:
+  explicit OneCurvePlot(QWidget *parent);
+  ~OneCurvePlot() override;
+  void setData(const double *x, const double *y, int dataSize,
+               const std::string &xUnits = "");
+  void setLabel(const QString &label);
+  QString label() const { return m_label; }
+  void setYAxisLabelRotation(double degrees);
+  void addPeakLabel(const PeakMarker2D *);
+  void clearPeakLabels();
+  bool hasCurve() const;
+  void store();
+  bool hasStored() const;
+  QStringList getLabels() const;
+  void removeCurve(const QString &label);
+  QColor getCurveColor(const QString &label) const;
+  void recalcXAxisDivs();
+  void recalcYAxisDivs();
+  bool isYLogScale() const;
+  const std::string &getXUnits() const { return m_xUnits; }
+public slots:
+  void setXScale(double from, double to);
+  void setYScale(double from, double to);
+  void clearCurve();
+  void recalcAxisDivs();
+  void setYLogScale();
+  void setYLinearScale();
+  void clearAll();
+signals:
+  void showContextMenu();
+  void clickedAt(double, double);
 
-                private:
-			QwtPlotCurve* m_curve;
-			QString m_label; ///< label to identify stored curve
-			QwtPlotZoomer* m_zoomer; ///< does zooming
-			int m_x0; ///< save x coord of last left mouse click
-			int m_y0; ///< save y coord of last left mouse click
-			QList<PeakLabel*> m_peakLabels;
-			QMap<QString, QwtPlotCurve*> m_stored; ///< stored curves
-			QList<QColor> m_colors; ///< colors for stored curves
-			int m_colorIndex;
-			std::string m_xUnits;
-		};
+protected:
+  void resizeEvent(QResizeEvent *e) override;
+  void contextMenuEvent(QContextMenuEvent *e) override;
+  void mousePressEvent(QMouseEvent *) override;
+  void mouseReleaseEvent(QMouseEvent *) override;
 
-		class PeakLabel : public QwtPlotItem
-		{
-		public:
-			PeakLabel(const PeakMarker2D* m, const OneCurvePlot* plot) :
-				m_marker(m),
-				m_plot(plot)
-			{}
-                        void draw(QPainter *painter, const QwtScaleMap &xMap,
-                                  const QwtScaleMap &yMap,
-                                  const QRect &canvasRect) const override;
+private:
+  QwtPlotCurve *m_curve;
+  QString m_label;         ///< label to identify stored curve
+  QwtPlotZoomer *m_zoomer; ///< does zooming
+  int m_x0;                ///< save x coord of last left mouse click
+  int m_y0;                ///< save y coord of last left mouse click
+  QList<PeakLabel *> m_peakLabels;
+  QMap<QString, QwtPlotCurve *> m_stored; ///< stored curves
+  QList<QColor> m_colors;                 ///< colors for stored curves
+  int m_colorIndex;
+  std::string m_xUnits;
+};
 
-                private:
-			const PeakMarker2D* m_marker;
-			const OneCurvePlot* m_plot;
-		};
+class PeakLabel : public QwtPlotItem {
+public:
+  PeakLabel(const PeakMarker2D *m, const OneCurvePlot *plot)
+      : m_marker(m), m_plot(plot) {}
+  void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+            const QRect &canvasRect) const override;
 
-	}//MantidWidgets
-}//MantidQt
+private:
+  const PeakMarker2D *m_marker;
+  const OneCurvePlot *m_plot;
+};
+
+} // MantidWidgets
+} // MantidQt
 #endif /*ONECURVEPLOT_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OpenGLError.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OpenGLError.h
index 801f824eee30d0c5d80b25a940a25c50e458bd0f..692d4f31ef0ca4cd21cc3b59bc5d862d0357cebe 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OpenGLError.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/OpenGLError.h
@@ -4,31 +4,24 @@
 #include <stdexcept>
 #include <string>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* Exception for wrapping an OpenGL error
-		*/
-		class OpenGLError : public std::exception
-		{
-		public:
-			explicit OpenGLError(const std::string& msg) :m_msg(msg) {}
-                        const char *what() const noexcept override {
-                          return m_msg.c_str();
-                        }
-                        static bool check(const std::string& funName);
-			static bool hasError(const std::string& funName) { return check(funName); }
-			static std::ostream& log();
-			static std::ostream& logDebug();
-
-		private:
-			std::string m_msg;
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* Exception for wrapping an OpenGL error
+*/
+class OpenGLError : public std::exception {
+public:
+  explicit OpenGLError(const std::string &msg) : m_msg(msg) {}
+  const char *what() const noexcept override { return m_msg.c_str(); }
+  static bool check(const std::string &funName);
+  static bool hasError(const std::string &funName) { return check(funName); }
+  static std::ostream &log();
+  static std::ostream &logDebug();
 
+private:
+  std::string m_msg;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*OPENGLERROR_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PanelsSurface.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PanelsSurface.h
index bb052332d38eb694ccf11d1116425fd2f8257ec9..2292e86c8fc134e01a7c028e54e7b7f43d92d3c2 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PanelsSurface.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PanelsSurface.h
@@ -3,116 +3,119 @@
 
 #include "UnwrappedSurface.h"
 
-
 #include <QPolygonF>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class PanelsSurface;
-
-		struct FlatBankInfo
-		{
-			explicit FlatBankInfo(PanelsSurface *s);
-			/// Component id of the bank
-			Mantid::Geometry::ComponentID id;
-			/// Bank's rotation
-			Mantid::Kernel::Quat rotation;
-			/// Starting index of bank's detectors in m_unwrappedDetectors vector
-			size_t startDetectorIndex;
-			/// Ending index of bank's detectors in m_unwrappedDetectors vector (1 past the last one)
-			size_t endDetectorIndex;
-			/// Bank's shape
-			QPolygonF polygon;
-			// translate the bank by a vector
-			void translate(const QPointF &shift);
-		private:
-			PanelsSurface *surface;
-		};
+namespace MantidQt {
+namespace MantidWidgets {
+class PanelsSurface;
 
-		/**
-		* @class PanelsSurface
-		* @brief Finds all flat banks of detectors and places them side by side.
-		*
-		* Who qualifies as a flat bank:
-		*
-		*  - Rectangular detector
-		*  - CompAssembly containing an array of ObjCompAssemblies
-		*     + all ObjCompAssemblies must be cylinders
-		*     + two first ObjCompAssemblies (returned by CompAssembly::getChild(i))
-		*       cannot lie on the same line (being parallel is alright)
-		*  - CompAssembly with detectors lying in the same plane
-		*/
-		class PanelsSurface : public UnwrappedSurface
-		{
-		public:
-			PanelsSurface(
-				const InstrumentActor *rootActor,
-				const Mantid::Kernel::V3D &origin, const Mantid::Kernel::V3D &axis);
-                        ~PanelsSurface() override;
-                        void init() override;
-                        void project(const Mantid::Kernel::V3D &, double &,
-                                     double &, double &,
-                                     double &) const override;
+struct FlatBankInfo {
+  explicit FlatBankInfo(PanelsSurface *s);
+  /// Component id of the bank
+  Mantid::Geometry::ComponentID id;
+  /// Bank's rotation
+  Mantid::Kernel::Quat rotation;
+  /// Starting index of bank's detectors in m_unwrappedDetectors vector
+  size_t startDetectorIndex;
+  /// Ending index of bank's detectors in m_unwrappedDetectors vector (1 past
+  /// the last one)
+  size_t endDetectorIndex;
+  /// Bank's shape
+  QPolygonF polygon;
+  // translate the bank by a vector
+  void translate(const QPointF &shift);
 
-                protected:
-                  void rotate(const UnwrappedDetector &udet,
-                              Mantid::Kernel::Quat &R) const override;
-                        //void drawCustom(QPainter *painter) const;
+private:
+  PanelsSurface *surface;
+};
 
-			// Setup the projection axes
-			void setupAxes();
-			// Setup the projection axes
-			void setupBasisAxes(const Mantid::Kernel::V3D &zaxis, Mantid::Kernel::V3D &xaxis, Mantid::Kernel::V3D &yaxis) const;
-			// Find all flat banks of detectors.
-			void findFlatBanks();
-			// Add a flat bank
-			void addFlatBank(Mantid::Geometry::ComponentID bankId, const Mantid::Kernel::V3D &normal, QList<Mantid::Geometry::ComponentID> objCompAssemblies);
-			// Add a flat bank
-			void addFlatBankOfDetectors(Mantid::Geometry::ComponentID bankId, const Mantid::Kernel::V3D &normal, QList<Mantid::Geometry::ComponentID> detectors);
-			// Add a component assembly containing a flat array of ObjCompAssemblies
-			void addObjCompAssemblies(Mantid::Geometry::ComponentID bankId);
-			// Add a component assembly
-			void addCompAssembly(Mantid::Geometry::ComponentID bankId);
-			// Add a rectangular detector
-			void addRectangularDetector(Mantid::Geometry::ComponentID bankId);
-			//Add a structured detector
-			void addStructuredDetector(Mantid::Geometry::ComponentID bankId);
-			// Calculate bank rotation
-			Mantid::Kernel::Quat calcBankRotation(const Mantid::Kernel::V3D &detPos, Mantid::Kernel::V3D normal) const;
-			// Add a detector from an assembly
-			void addDetector(const Mantid::Geometry::IDetector_const_sptr det, const Mantid::Kernel::V3D &refPos, int index, Mantid::Kernel::Quat &rotation);
-			// Spread the banks over the projection plane
-			void spreadBanks();
-			// Find index of the largest bank
-			int findLargestBank() const;
-			// Is a polygon overlapped with any of the flat banks
-			bool isOverlapped(QPolygonF &polygon, int iexclude) const;
-			// Remove all found flat banks
-			void clearBanks();
+/**
+* @class PanelsSurface
+* @brief Finds all flat banks of detectors and places them side by side.
+*
+* Who qualifies as a flat bank:
+*
+*  - Rectangular detector
+*  - CompAssembly containing an array of ObjCompAssemblies
+*     + all ObjCompAssemblies must be cylinders
+*     + two first ObjCompAssemblies (returned by CompAssembly::getChild(i))
+*       cannot lie on the same line (being parallel is alright)
+*  - CompAssembly with detectors lying in the same plane
+*/
+class PanelsSurface : public UnwrappedSurface {
+public:
+  PanelsSurface(const InstrumentActor *rootActor,
+                const Mantid::Kernel::V3D &origin,
+                const Mantid::Kernel::V3D &axis);
+  ~PanelsSurface() override;
+  void init() override;
+  void project(const Mantid::Kernel::V3D &, double &, double &, double &,
+               double &) const override;
 
-		protected:
+protected:
+  void rotate(const UnwrappedDetector &udet,
+              Mantid::Kernel::Quat &R) const override;
+  // void drawCustom(QPainter *painter) const;
 
-			const Mantid::Kernel::V3D m_pos;   ///< Origin (sample position)
-												/// The z axis defines the plane of the projection. All flat banks
-												/// are rotated to be parallel to this plane.
-			const Mantid::Kernel::V3D m_zaxis;
-			Mantid::Kernel::V3D m_xaxis;
-			Mantid::Kernel::V3D m_yaxis;
-			QPointF m_origin; ///< Origin in uv coords
+  // Setup the projection axes
+  void setupAxes();
+  // Setup the projection axes
+  void setupBasisAxes(const Mantid::Kernel::V3D &zaxis,
+                      Mantid::Kernel::V3D &xaxis,
+                      Mantid::Kernel::V3D &yaxis) const;
+  // Find all flat banks of detectors.
+  void findFlatBanks();
+  // Add a flat bank
+  void addFlatBank(Mantid::Geometry::ComponentID bankId,
+                   const Mantid::Kernel::V3D &normal,
+                   QList<Mantid::Geometry::ComponentID> objCompAssemblies);
+  // Add a flat bank
+  void addFlatBankOfDetectors(Mantid::Geometry::ComponentID bankId,
+                              const Mantid::Kernel::V3D &normal,
+                              QList<Mantid::Geometry::ComponentID> detectors);
+  // Add a component assembly containing a flat array of ObjCompAssemblies
+  void addObjCompAssemblies(Mantid::Geometry::ComponentID bankId);
+  // Add a component assembly
+  void addCompAssembly(Mantid::Geometry::ComponentID bankId);
+  // Add a rectangular detector
+  void addRectangularDetector(Mantid::Geometry::ComponentID bankId);
+  // Add a structured detector
+  void addStructuredDetector(Mantid::Geometry::ComponentID bankId);
+  // Calculate bank rotation
+  Mantid::Kernel::Quat calcBankRotation(const Mantid::Kernel::V3D &detPos,
+                                        Mantid::Kernel::V3D normal) const;
+  // Add a detector from an assembly
+  void addDetector(const Mantid::Geometry::IDetector_const_sptr det,
+                   const Mantid::Kernel::V3D &refPos, int index,
+                   Mantid::Kernel::Quat &rotation);
+  // Spread the banks over the projection plane
+  void spreadBanks();
+  // Find index of the largest bank
+  int findLargestBank() const;
+  // Is a polygon overlapped with any of the flat banks
+  bool isOverlapped(QPolygonF &polygon, int iexclude) const;
+  // Remove all found flat banks
+  void clearBanks();
 
-								/// Keep info of the flat banks
-			QList<FlatBankInfo*> m_flatBanks;
-			/// Maps detector ids to indices of FlatBankInfos in m_flatBanks
-			QMap<Mantid::detid_t, int> m_detector2bankMap;
+protected:
+  const Mantid::Kernel::V3D m_pos; ///< Origin (sample position)
+  /// The z axis defines the plane of the projection. All flat banks
+  /// are rotated to be parallel to this plane.
+  const Mantid::Kernel::V3D m_zaxis;
+  Mantid::Kernel::V3D m_xaxis;
+  Mantid::Kernel::V3D m_yaxis;
+  QPointF m_origin; ///< Origin in uv coords
 
-			friend class FlatBankFinder;
-			friend struct FlatBankInfo;
+  /// Keep info of the flat banks
+  QList<FlatBankInfo *> m_flatBanks;
+  /// Maps detector ids to indices of FlatBankInfos in m_flatBanks
+  QMap<Mantid::detid_t, int> m_detector2bankMap;
 
-		};
+  friend class FlatBankFinder;
+  friend struct FlatBankInfo;
+};
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
 
 #endif // PANELSSURFACE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakMarker2D.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakMarker2D.h
index 029910a0040bb95ef7cc0dbab32c5fbf0c7c5e3b..416646d2dce3f1c65c0c32b37273f012df6ab969 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakMarker2D.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakMarker2D.h
@@ -4,84 +4,81 @@
 #include "Shape2D.h"
 #include "MantidGeometry/Crystal/IPeak.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		class PeakOverlay;
+class PeakOverlay;
 
-		/**
-		* Shape representing a peak marker on un unwrapped surface.
-		* A marker consists of a symbol marking location of a peak
-		* and a text label.
-		*/
-		class PeakMarker2D : public Shape2D
-		{
-		public:
-			enum Symbol { Circle = 0, Diamond, Square };
-			struct Style
-			{
-				Style(Symbol sb = Circle, QColor c = Qt::red, int sz = g_defaultMarkerSize) :symbol(sb), color(c), size(sz) {}
-				Symbol symbol;
-				QColor color;
-				int size;
-			};
-			PeakMarker2D(PeakOverlay& peakOverlay, double u, double v, const Style& style = Style());
-			/* --- Implemented Shape2D virtual methods --- */
-                        Shape2D *clone() const override {
-                          return new PeakMarker2D(*this);
-                        }
-                        bool selectAt(const QPointF &p) const override;
-                        bool contains(const QPointF &p) const override {
-                          return m_boundingRect.contains(p);
-                        }
-                        void addToPath(QPainterPath &path) const override;
-                        /* --- Own public methods --- */
-			/// Set new marker size to s
-			void setMarkerSize(const int& s);
-			/// Get marker size
-			int getMarkerSize()const { return m_markerSize; }
-			/// Get default marker size
-			static int getDefaultMarkerSize() { return g_defaultMarkerSize; }
-			Symbol getSymbol()const { return m_symbol; }
-			void setSymbol(Symbol s) { m_symbol = s; }
-			Style getStyle() const;
-			void setPeak(const Mantid::Geometry::IPeak& peak, int row = -1);
-			const Mantid::Geometry::IPeak& getPeak() const;
-			double getH()const { return m_h; }
-			double getK()const { return m_k; }
-			double getL()const { return m_l; }
-			int getDetectorID()const { return m_detID; }
-			int getRow()const { return m_row; }
-			void setRow(int row) { m_row = row; }
-			/// Get label's area on the screen
-			const QRectF& getLabelRect()const { return m_labelRect; }
-			/// Allows PeakOverlay to move the label to avoid overlapping
-			void moveLabelRectTo(const QPointF& p)const { m_labelRect.moveTo(p); }
-			QString getLabel()const { return m_label; }
-		protected:
-			/* --- Implemented Shape2D protected virtual methods --- */
-                  void drawShape(QPainter &painter) const override;
-                  void refit() override {}
-                        /* --- Own protected methods --- */
-			void drawCircle(QPainter& painter)const;
-			void drawDiamond(QPainter& painter)const;
-			void drawSquare(QPainter& painter)const;
-		private:
+/**
+* Shape representing a peak marker on un unwrapped surface.
+* A marker consists of a symbol marking location of a peak
+* and a text label.
+*/
+class PeakMarker2D : public Shape2D {
+public:
+  enum Symbol { Circle = 0, Diamond, Square };
+  struct Style {
+    Style(Symbol sb = Circle, QColor c = Qt::red, int sz = g_defaultMarkerSize)
+        : symbol(sb), color(c), size(sz) {}
+    Symbol symbol;
+    QColor color;
+    int size;
+  };
+  PeakMarker2D(PeakOverlay &peakOverlay, double u, double v,
+               const Style &style = Style());
+  /* --- Implemented Shape2D virtual methods --- */
+  Shape2D *clone() const override { return new PeakMarker2D(*this); }
+  bool selectAt(const QPointF &p) const override;
+  bool contains(const QPointF &p) const override {
+    return m_boundingRect.contains(p);
+  }
+  void addToPath(QPainterPath &path) const override;
+  /* --- Own public methods --- */
+  /// Set new marker size to s
+  void setMarkerSize(const int &s);
+  /// Get marker size
+  int getMarkerSize() const { return m_markerSize; }
+  /// Get default marker size
+  static int getDefaultMarkerSize() { return g_defaultMarkerSize; }
+  Symbol getSymbol() const { return m_symbol; }
+  void setSymbol(Symbol s) { m_symbol = s; }
+  Style getStyle() const;
+  void setPeak(const Mantid::Geometry::IPeak &peak, int row = -1);
+  const Mantid::Geometry::IPeak &getPeak() const;
+  double getH() const { return m_h; }
+  double getK() const { return m_k; }
+  double getL() const { return m_l; }
+  int getDetectorID() const { return m_detID; }
+  int getRow() const { return m_row; }
+  void setRow(int row) { m_row = row; }
+  /// Get label's area on the screen
+  const QRectF &getLabelRect() const { return m_labelRect; }
+  /// Allows PeakOverlay to move the label to avoid overlapping
+  void moveLabelRectTo(const QPointF &p) const { m_labelRect.moveTo(p); }
+  QString getLabel() const { return m_label; }
 
-			PeakOverlay& m_peakOverlay; ///< Parent PeakOverlay
-			int m_markerSize;           ///< Size of the marker
-			static const int g_defaultMarkerSize;
-			Symbol m_symbol;            ///< Shape of the marker
-			double m_h, m_k, m_l;       ///< Peak's h,k,l
-			int m_detID;                ///< Peak's detector ID
-			QString m_label;            ///< Label string
-			mutable QRectF m_labelRect; ///< label's area on the screen
-			int m_row;                  ///< peaks row number in PeaksWorkspace
-		};
+protected:
+  /* --- Implemented Shape2D protected virtual methods --- */
+  void drawShape(QPainter &painter) const override;
+  void refit() override {}
+  /* --- Own protected methods --- */
+  void drawCircle(QPainter &painter) const;
+  void drawDiamond(QPainter &painter) const;
+  void drawSquare(QPainter &painter) const;
 
-	}//MantidWidgets
-}//MantidQt
+private:
+  PeakOverlay &m_peakOverlay; ///< Parent PeakOverlay
+  int m_markerSize;           ///< Size of the marker
+  static const int g_defaultMarkerSize;
+  Symbol m_symbol;            ///< Shape of the marker
+  double m_h, m_k, m_l;       ///< Peak's h,k,l
+  int m_detID;                ///< Peak's detector ID
+  QString m_label;            ///< Label string
+  mutable QRectF m_labelRect; ///< label's area on the screen
+  int m_row;                  ///< peaks row number in PeaksWorkspace
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MANTIDPLOT_PEAKMARKER2D_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakOverlay.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakOverlay.h
index a33ec896348c4c11dedbf5cdbd6702b91d33eafc..b864cf7a207b84f8250450e0a4a2b526297d11f4 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakOverlay.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/PeakOverlay.h
@@ -20,159 +20,156 @@ class IPeaksWorkspace;
 }
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		class UnwrappedSurface;
-
-		/**
-		* Class for managing overlapping peak labels and drawing them on screen.
-		* If labels of two or more peaks overlap they are combined into a single label.
-		* A label shows three numbers h,k, and l. A combined label replaces non-equal
-		* numbers of included markers with its letter.
-		*/
-		class PeakHKL {
-		public:
-			PeakHKL(PeakMarker2D *m, const QRectF &trect, bool sr);
-			bool add(PeakMarker2D *marker, const QRectF &trect);
-			void draw(QPainter &painter, int prec = 6);
-			void print() const;
-
-		private:
-			static QString formatNumber(double h, int prec);
-			QPointF p;       ///< untransformed marker origin
-			QRectF rect;     ///< label's screen area in transformed coords
-			double h, k, l;  ///< h,k, and l
-			bool nh, nk, nl; ///< true if h, k, or l is numeric
-			QList<int> rows; ///< row indices of the peaks in their PeaksWorkspace
-			bool showRows;
-		};
-
-		/// Helper class for scaling peak markers to intensities.
-		class AbstractIntensityScale {
-		public:
-			explicit AbstractIntensityScale(
-				const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws) {
-				setPeaksWorkspace(pws);
-			}
-
-			virtual ~AbstractIntensityScale() {}
-
-			void
-				setPeaksWorkspace(const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws);
-
-			virtual PeakMarker2D::Style
-				getScaledMarker(double intensity,
-					const PeakMarker2D::Style &baseStyle) const = 0;
-
-		protected:
-			double m_maxIntensity = 0.0;
-			double m_minIntensity = 0.0;
-		};
-
-		/// Default intensity scale leaves all markers unchanged.
-		class DefaultIntensityScale : public AbstractIntensityScale {
-		public:
-			explicit DefaultIntensityScale(
-				const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws)
-				: AbstractIntensityScale(pws) {}
-
-		protected:
-			/// Returns the base style unmodified.
-			PeakMarker2D::Style
-				getScaledMarker(double intensity,
-					const PeakMarker2D::Style &baseStyle) const override {
-				UNUSED_ARG(intensity);
-
-				return baseStyle;
-			}
-		};
-
-		/// Qualitative scaling of relative peak intensities to levels (weak, medium,
-		/// strong, very strong).
-		class QualitativeIntensityScale : public AbstractIntensityScale {
-		public:
-			explicit QualitativeIntensityScale(
-				const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws)
-				: AbstractIntensityScale(pws) {}
-
-		protected:
-			PeakMarker2D::Style
-				getScaledMarker(double intensity,
-					const PeakMarker2D::Style &baseStyle) const override;
-
-		private:
-			// cppcheck-suppress unusedPrivateFunction
-			int getIntensityLevel(double intensity) const;
-
-			// Scaling to weak < 0.1 <= medium <= 0.6 <= strong <= 0.9 <= very strong
-			std::vector<double> m_intensityLevels = { 0.1, 0.6, 0.9 };
-		};
-
-		/**
-		* Class for managing peak markers on an unwrapped instrument surface.
-		*/
-		class PeakOverlay : public Shape2DCollection,
-			public MantidQt::API::WorkspaceObserver {
-			Q_OBJECT
-		public:
-			PeakOverlay(UnwrappedSurface *surface,
-				boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws);
-                        ~PeakOverlay() override {}
-                        /// Override the drawing method
-                        void draw(QPainter &painter) const override;
-                        void removeShapes(const QList<Shape2D *> &) override;
-                        void clear() override;
-
-                        /// Create the markers
-			void createMarkers(const PeakMarker2D::Style &style);
-			void addMarker(PeakMarker2D *m);
-			QList<PeakMarker2D *> getMarkersWithID(int detID) const;
-			int getNumberPeaks() const;
-			Mantid::Geometry::IPeak &getPeak(int);
-			/// Return PeaksWorkspace associated with this overlay.
-			boost::shared_ptr<Mantid::API::IPeaksWorkspace> getPeaksWorkspace() {
-				return m_peaksWorkspace;
-			}
-			/// set HKL precision
-			void setPrecision(int prec) const { m_precision = prec; }
-			void setShowRowsFlag(bool yes) { m_showRows = yes; }
-			void setShowLabelsFlag(bool yes) { m_showLabels = yes; }
-			void setShowRelativeIntensityFlag(bool yes);
-			static PeakMarker2D::Style getDefaultStyle(int index);
-			void setPeakVisibility(double xmin, double xmax, QString units);
-
-		signals:
-			void executeAlgorithm(Mantid::API::IAlgorithm_sptr);
-
-		private:
-			/// A WorkspaceObserver handle implemented.
-                  void afterReplaceHandle(
-                      const std::string &wsName,
-                      const Mantid::API::Workspace_sptr ws) override;
-
-                        PeakMarker2D::Style getCurrentStyle() const;
-			void recreateMarkers(const PeakMarker2D::Style &style);
-
-			QMultiHash<int, PeakMarker2D *>
-				m_det2marker; ///< detector ID to PeakMarker2D map
-			mutable QList<PeakHKL> m_labels;
-			boost::shared_ptr<Mantid::API::IPeaksWorkspace>
-				m_peaksWorkspace; ///< peaks to be drawn ontop of the surface
-			UnwrappedSurface
-				*m_surface; ///< pointer to the surface this overlay is applied to
-			mutable int m_precision;
-			mutable bool m_showRows;   ///< flag to show peak row index
-			mutable bool m_showLabels; ///< flag to show peak hkl labels
-
-			std::unique_ptr<AbstractIntensityScale> m_peakIntensityScale;
-
-			static QList<PeakMarker2D::Style> g_defaultStyles; ///< default marker styles
-		};
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+class UnwrappedSurface;
+
+/**
+* Class for managing overlapping peak labels and drawing them on screen.
+* If labels of two or more peaks overlap they are combined into a single label.
+* A label shows three numbers h,k, and l. A combined label replaces non-equal
+* numbers of included markers with its letter.
+*/
+class PeakHKL {
+public:
+  PeakHKL(PeakMarker2D *m, const QRectF &trect, bool sr);
+  bool add(PeakMarker2D *marker, const QRectF &trect);
+  void draw(QPainter &painter, int prec = 6);
+  void print() const;
+
+private:
+  static QString formatNumber(double h, int prec);
+  QPointF p;       ///< untransformed marker origin
+  QRectF rect;     ///< label's screen area in transformed coords
+  double h, k, l;  ///< h,k, and l
+  bool nh, nk, nl; ///< true if h, k, or l is numeric
+  QList<int> rows; ///< row indices of the peaks in their PeaksWorkspace
+  bool showRows;
+};
+
+/// Helper class for scaling peak markers to intensities.
+class AbstractIntensityScale {
+public:
+  explicit AbstractIntensityScale(
+      const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws) {
+    setPeaksWorkspace(pws);
+  }
+
+  virtual ~AbstractIntensityScale() {}
+
+  void
+  setPeaksWorkspace(const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws);
+
+  virtual PeakMarker2D::Style
+  getScaledMarker(double intensity,
+                  const PeakMarker2D::Style &baseStyle) const = 0;
+
+protected:
+  double m_maxIntensity = 0.0;
+  double m_minIntensity = 0.0;
+};
+
+/// Default intensity scale leaves all markers unchanged.
+class DefaultIntensityScale : public AbstractIntensityScale {
+public:
+  explicit DefaultIntensityScale(
+      const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws)
+      : AbstractIntensityScale(pws) {}
+
+protected:
+  /// Returns the base style unmodified.
+  PeakMarker2D::Style
+  getScaledMarker(double intensity,
+                  const PeakMarker2D::Style &baseStyle) const override {
+    UNUSED_ARG(intensity);
+
+    return baseStyle;
+  }
+};
+
+/// Qualitative scaling of relative peak intensities to levels (weak, medium,
+/// strong, very strong).
+class QualitativeIntensityScale : public AbstractIntensityScale {
+public:
+  explicit QualitativeIntensityScale(
+      const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws)
+      : AbstractIntensityScale(pws) {}
+
+protected:
+  PeakMarker2D::Style
+  getScaledMarker(double intensity,
+                  const PeakMarker2D::Style &baseStyle) const override;
+
+private:
+  // cppcheck-suppress unusedPrivateFunction
+  int getIntensityLevel(double intensity) const;
+
+  // Scaling to weak < 0.1 <= medium <= 0.6 <= strong <= 0.9 <= very strong
+  std::vector<double> m_intensityLevels = {0.1, 0.6, 0.9};
+};
+
+/**
+* Class for managing peak markers on an unwrapped instrument surface.
+*/
+class PeakOverlay : public Shape2DCollection,
+                    public MantidQt::API::WorkspaceObserver {
+  Q_OBJECT
+public:
+  PeakOverlay(UnwrappedSurface *surface,
+              boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws);
+  ~PeakOverlay() override {}
+  /// Override the drawing method
+  void draw(QPainter &painter) const override;
+  void removeShapes(const QList<Shape2D *> &) override;
+  void clear() override;
+
+  /// Create the markers
+  void createMarkers(const PeakMarker2D::Style &style);
+  void addMarker(PeakMarker2D *m);
+  QList<PeakMarker2D *> getMarkersWithID(int detID) const;
+  int getNumberPeaks() const;
+  Mantid::Geometry::IPeak &getPeak(int);
+  /// Return PeaksWorkspace associated with this overlay.
+  boost::shared_ptr<Mantid::API::IPeaksWorkspace> getPeaksWorkspace() {
+    return m_peaksWorkspace;
+  }
+  /// set HKL precision
+  void setPrecision(int prec) const { m_precision = prec; }
+  void setShowRowsFlag(bool yes) { m_showRows = yes; }
+  void setShowLabelsFlag(bool yes) { m_showLabels = yes; }
+  void setShowRelativeIntensityFlag(bool yes);
+  static PeakMarker2D::Style getDefaultStyle(int index);
+  void setPeakVisibility(double xmin, double xmax, QString units);
+
+signals:
+  void executeAlgorithm(Mantid::API::IAlgorithm_sptr);
+
+private:
+  /// A WorkspaceObserver handle implemented.
+  void afterReplaceHandle(const std::string &wsName,
+                          const Mantid::API::Workspace_sptr ws) override;
+
+  PeakMarker2D::Style getCurrentStyle() const;
+  void recreateMarkers(const PeakMarker2D::Style &style);
+
+  QMultiHash<int, PeakMarker2D *>
+      m_det2marker; ///< detector ID to PeakMarker2D map
+  mutable QList<PeakHKL> m_labels;
+  boost::shared_ptr<Mantid::API::IPeaksWorkspace>
+      m_peaksWorkspace; ///< peaks to be drawn ontop of the surface
+  UnwrappedSurface *
+      m_surface; ///< pointer to the surface this overlay is applied to
+  mutable int m_precision;
+  mutable bool m_showRows;   ///< flag to show peak row index
+  mutable bool m_showLabels; ///< flag to show peak hkl labels
+
+  std::unique_ptr<AbstractIntensityScale> m_peakIntensityScale;
+
+  static QList<PeakMarker2D::Style> g_defaultStyles; ///< default marker styles
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MANTIDPLOT_PEAKOVERLAY_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Projection3D.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Projection3D.h
index 4ab2b5c112e1e617f4b11124400c502b6ff9a3dc..33977ec06c2c8e521ea645aa380e33e9e986f17a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Projection3D.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Projection3D.h
@@ -12,68 +12,67 @@
 #include <boost/shared_ptr.hpp>
 #include <boost/scoped_ptr.hpp>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		This is an implementation of ProjectionSurface for viewing the instrument in 3D.
-
-		*/
-		class Projection3D : public ProjectionSurface
-		{
-			Q_OBJECT
-			enum AxisDirection { XPOSITIVE, YPOSITIVE, ZPOSITIVE, XNEGATIVE, YNEGATIVE, ZNEGATIVE };
-
-		public:
-			Projection3D(const InstrumentActor* rootActor, int winWidth, int winHeight);
-                        ~Projection3D() override;
-                        RectF getSurfaceBounds() const override;
-
-                        void setViewDirection(const QString& vd);
-			void set3DAxesState(bool on);
-			void setWireframe(bool on);
-
-                        void componentSelected(
-                            Mantid::Geometry::ComponentID = NULL) override;
-                        void getSelectedDetectors(QList<int> &dets) override;
-                        void
-                        getMaskedDetectors(QList<int> &dets) const override;
-                        void resize(int, int) override;
-                        QString getInfoText() const override;
-
-                signals:
-			void finishedMove();
-
-			protected slots:
-			void initTranslation(int x, int y);
-			void translate(int x, int y);
-			void initZoom(int x, int y);
-			void zoom(int x, int y);
-			void wheelZoom(int x, int y, int d);
-			void initRotation(int x, int y);
-			void rotate(int x, int y);
-			void finishMove();
-
-		protected:
-                  void init() override {}
-                  void drawSurface(MantidGLWidget *widget,
-                                   bool picking = false) const override;
-                  void changeColorMap() override;
-
-                        void drawAxes(double axis_length = 100.0)const;
-			void setLightingModel(bool picking)const;
-
-			bool m_drawAxes;
-			bool m_wireframe;
-
-			Viewport m_viewport;
-
-		};
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+This is an implementation of ProjectionSurface for viewing the instrument in 3D.
+
+*/
+class Projection3D : public ProjectionSurface {
+  Q_OBJECT
+  enum AxisDirection {
+    XPOSITIVE,
+    YPOSITIVE,
+    ZPOSITIVE,
+    XNEGATIVE,
+    YNEGATIVE,
+    ZNEGATIVE
+  };
+
+public:
+  Projection3D(const InstrumentActor *rootActor, int winWidth, int winHeight);
+  ~Projection3D() override;
+  RectF getSurfaceBounds() const override;
+
+  void setViewDirection(const QString &vd);
+  void set3DAxesState(bool on);
+  void setWireframe(bool on);
+
+  void componentSelected(Mantid::Geometry::ComponentID = NULL) override;
+  void getSelectedDetectors(QList<int> &dets) override;
+  void getMaskedDetectors(QList<int> &dets) const override;
+  void resize(int, int) override;
+  QString getInfoText() const override;
+
+signals:
+  void finishedMove();
+
+protected slots:
+  void initTranslation(int x, int y);
+  void translate(int x, int y);
+  void initZoom(int x, int y);
+  void zoom(int x, int y);
+  void wheelZoom(int x, int y, int d);
+  void initRotation(int x, int y);
+  void rotate(int x, int y);
+  void finishMove();
+
+protected:
+  void init() override {}
+  void drawSurface(MantidGLWidget *widget, bool picking = false) const override;
+  void changeColorMap() override;
+
+  void drawAxes(double axis_length = 100.0) const;
+  void setLightingModel(bool picking) const;
+
+  bool m_drawAxes;
+  bool m_wireframe;
+
+  Viewport m_viewport;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /* PROJECTION3D_H_ */
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ProjectionSurface.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ProjectionSurface.h
index d6d4d679a21fd6b354aa903ba2c2ef951cc1d867..0f24fffe0ee03d83f4b160bd0ef7b0e833998b5e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ProjectionSurface.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/ProjectionSurface.h
@@ -20,18 +20,18 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid{
-  namespace Geometry{
-    class IDetector;
-  }
-  namespace API{
-    class IPeaksWorkspace;
-  }
+namespace Mantid {
+namespace Geometry {
+class IDetector;
+}
+namespace API {
+class IPeaksWorkspace;
+}
 }
 namespace MantidQt {
-   namespace MantidWidgets {
-    class InputController;
-    }
+namespace MantidWidgets {
+class InputController;
+}
 }
 
 class GLColor;
@@ -39,277 +39,315 @@ class GLColor;
 class QMouseEvent;
 class QWheelEvent;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class MantidGLWidget;
-
-		/**
-		* @class ProjectionSurface
-		* @brief Performs projection of an instrument onto a plane.
-		* @author Roman Tolchenov, Tessella plc
-		* @date 13 May 2011
-
-		* Performs projection of an instrument onto a plane. Draws the resulting image on the screen.
-		* Supports selection and zooming.
-		*
-		* Iherited classes must implement the pure virtual methods and set m_viewRect - the bounding
-		* rectangle in surface coordinates.
-		*/
-
-		class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ProjectionSurface : public QObject
-		{
-			Q_OBJECT
-		public:
-			enum InteractionMode {
-				MoveMode = 0,
-				PickSingleMode,
-				PickTubeMode,
-				AddPeakMode,
-				DrawRegularMode,
-				DrawFreeMode,
-				ErasePeakMode,
-				InteractionModeSize
-			};
-			/// Constructor
-			explicit ProjectionSurface(const InstrumentActor *rootActor);
-			/// Destructor
-                        ~ProjectionSurface() override;
-                        /// Resets the instrument actor.
-			void resetInstrumentActor(const InstrumentActor* rootActor);
-
-			//-----------------------------------
-			//     Public virtual methods
-			//-----------------------------------
-
-			/// draw the surface onto a GL widget
-			virtual void draw(MantidGLWidget* widget)const;
-			/// draw the surface onto a normal widget
-			virtual void drawSimple(QWidget* widget)const;
-			/// called when the gl widget gets resized
-			virtual void resize(int, int);
-			/// redraw surface without recalulationg of colours, etc
-			virtual void updateView(bool picking = true);
-			/// full update and redraw of the surface
-			virtual void updateDetectors();
-			/// returns the bounding rectangle in the real coordinates
-			virtual RectF getSurfaceBounds()const { return m_viewRect; }
-
-			virtual void mousePressEvent(QMouseEvent*);
-			virtual void mouseMoveEvent(QMouseEvent*);
-			virtual void mouseReleaseEvent(QMouseEvent*);
-			virtual void wheelEvent(QWheelEvent *);
-			virtual void keyPressEvent(QKeyEvent*);
-			virtual void enterEvent(QEvent*);
-			virtual void leaveEvent(QEvent*);
-
-			/// return true if any of the detectors have been selected
-			virtual bool hasSelection()const;
-
-			virtual int getDetectorID(int x, int y)const;
-			virtual boost::shared_ptr<const Mantid::Geometry::IDetector> getDetector(int x, int y)const;
-			/// NULL deselects components and selects the whole instrument
-			virtual void componentSelected(Mantid::Geometry::ComponentID = NULL) = 0;
-			/// fill in a list of detector ids which were selected by the selction tool
-			virtual void getSelectedDetectors(QList<int>& dets) = 0;
-			/// fill in a list of detector ids which were masked by the mask shapes
-			virtual void getMaskedDetectors(QList<int>& dets)const = 0;
-
-			virtual QString getInfoText()const;
-			/// Change the interaction mode
-			virtual void setInteractionMode(int mode);
-
-			//-----------------------------------
-
-			Mantid::Kernel::V3D getDetectorPos(int x, int y) const;
-			/// Return the current interaction mode
-			int getInteractionMode()const { return m_interactionMode; }
-			/// Ask current input controller if a context menu is allowed
-			bool canShowContextMenu() const;
-
-			/// Set background colour
-			void setBackgroundColor(const QColor& color) { m_backgroundColor = color; }
-			/// Get background colour
-			QColor getBackgroundColor() const { return m_backgroundColor; }
-			/// Send a redraw request to the surface owner
-			void requestRedraw(bool resetPeakVisibility = false);
-			/// Enable lighting if the implementation allows it
-			void enableLighting(bool on);
-
-			//-----------------------------------
-			//    Mask methods
-			//-----------------------------------
-
-			/// Return bounding rect of the currently selected shape in the "original" coord system.
-			/// It doesn't depend on the zooming of the surface
-			RectF getCurrentBoundingRect()const { return m_maskShapes.getCurrentBoundingRect(); }
-
-			/// Set new bounding rect of the currently selected shape in the "original" coord system.
-			/// This method resizes the shape to fit into the new rectangle.
-			void setCurrentBoundingRect(const RectF& rect) { m_maskShapes.setCurrentBoundingRect(rect); }
-
-			/// Initialize interactive shape creation.
-			/// @param type :: Type of the shape. For available types see code of Shape2DCollection::createShape(const QString& type,int x,int y) const
-			/// @param borderColor :: The color of the shape outline.
-			/// @param fillColor :: The fill color.
-			void startCreatingShape2D(const QString& type, const QColor& borderColor, const QColor& fillColor = QColor());
-
-			/// Initialize interactive creation of a free draw shape.
-			/// @param borderColor :: The color of the shape outline.
-			/// @param fillColor :: The fill color.
-			void startCreatingFreeShape(const QColor& borderColor, const QColor& fillColor = QColor());
-
-			// Properties methods which allow the mask shapes to be modified with a property browser.
-
-			/// Return a list of all properties of type double of the currently selected shape.
-			QStringList getCurrentDoubleNames()const { return m_maskShapes.getCurrentDoubleNames(); }
-
-			/// Get value of a "double" property of the currently selected shape.
-			/// @param prop :: Name of the property
-			double getCurrentDouble(const QString& prop) const { return m_maskShapes.getCurrentDouble(prop); }
-
-			/// Set value of a "double" property of the currently selected shape.
-			/// @param prop :: Name of the property
-			/// @param value :: New value
-			void setCurrentDouble(const QString& prop, double value) { m_maskShapes.setCurrentDouble(prop, value); }
-
-			/// Return a list of all properties of type QPointF of the currently selected shape.
-			QStringList getCurrentPointNames()const { return m_maskShapes.getCurrentPointNames(); }
-
-			/// Get value of a "QPointF" property of the currently selected shape.
-			/// @param prop :: Name of the property
-			QPointF getCurrentPoint(const QString& prop) const { return m_maskShapes.getCurrentPoint(prop); }
-
-			/// Set value of a "QPointF" property of the currently selected shape.
-			/// @param prop :: Name of the property
-			/// @param value :: New value
-			void setCurrentPoint(const QString& prop, const QPointF& value) { m_maskShapes.setCurrentPoint(prop, value); }
-
-			/// Check if a point on the scren is under any of the mask shapes
-			bool isMasked(double x, double y)const { return m_maskShapes.isMasked(x, y); }
-			/// Check if there are any masks defined
-			bool hasMasks() const { return m_maskShapes.size() > 0; }
-			/// Remove all mask shapes.
-			void clearMask() { m_maskShapes.clear(); }
-			/// Change all border colors.
-			void changeBorderColor(const QColor& color) { m_maskShapes.changeBorderColor(color); }
-
-			//-----------------------------------
-			//    Peaks overlay methods
-			//-----------------------------------
-
-			QList<PeakMarker2D*> getMarkersWithID(int detID)const;
-			boost::shared_ptr<Mantid::API::IPeaksWorkspace> getEditPeaksWorkspace() const;
-			QStringList getPeaksWorkspaceNames() const;
-			void deletePeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> ws);
-			void clearPeakOverlays();
-			bool hasPeakOverlays() const { return !m_peakShapes.isEmpty(); }
-			void setPeakLabelPrecision(int n);
-			int getPeakLabelPrecision() const { return m_peakLabelPrecision; }
-			void setShowPeakRowsFlag(bool on);
-			bool getShowPeakRowsFlag()const { return m_showPeakRows; }
-			void setShowPeakLabelsFlag(bool on);
-			bool getShowPeakLabelsFlag()const { return m_showPeakLabels; }
-			void setShowPeakRelativeIntensityFlag(bool on);
-			bool getShowPeakRelativeIntensityFlag() const { return m_showPeakRelativeIntensity; }
-
-		signals:
-
-			// detector selection
-			void singleComponentTouched(size_t);
-			void singleComponentPicked(size_t);
-
-			// shape manipulation
-			void signalToStartCreatingShape2D(const QString& type, const QColor& borderColor, const QColor& fillColor);
-			void signalToStartCreatingFreeShape(const QColor& borderColor, const QColor& fillColor);
-			void shapeCreated();
-			void shapeSelected();
-			void shapesDeselected();
-			void shapeChanged();
-			void shapesCleared();
-			void shapesRemoved();
-			void shapeChangeFinished();
-
-			// peaks
-			void peaksWorkspaceAdded();
-			void peaksWorkspaceDeleted();
-
-			// other
-			void redrawRequired();   ///< request redrawing of self
-			void updateInfoText();   ///< request update of the info string at bottom of InstrumentWindow
-			void executeAlgorithm(Mantid::API::IAlgorithm_sptr);
-
-			protected slots:
-
-			void setSelectionRect(const QRect& rect);
-			void emptySelectionRect();
-			void selectMultipleMasks(const QRect& rect);
-			void pickComponentAt(int x, int y);
-			void touchComponentAt(int x, int y);
-			void erasePeaks(const QRect& rect);
-
-			void colorMapChanged();
-
-		protected:
-
-			//-----------------------------------
-			//     Protected virtual methods
-			//-----------------------------------
-
-			virtual void init() = 0;
-			/// Draw the surface onto an OpenGL widget
-			virtual void drawSurface(MantidGLWidget* widget, bool picking = false)const = 0;
-			/// Respond to a change of color map in m_instrActor
-			virtual void changeColorMap() = 0;
-			/// Draw the surface onto an image without OpenGL
-			virtual void drawSimpleToImage(QImage* image, bool picking = false)const;
-
-			//-----------------------------------
-
-			void draw(MantidGLWidget* widget, bool picking)const;
-			void clear();
-			QRect selectionRect()const;
-			RectF selectionRectUV()const;
-			size_t getPickID(int x, int y)const;
-			void setInputController(int mode, MantidQt::MantidWidgets::InputController* controller);
-			void setPeakVisibility() const;
-
-			//-----------------------------------
-			//     Protected data
-			//-----------------------------------
-
-			const InstrumentActor* m_instrActor;
-			mutable QImage* m_viewImage;       ///< storage for view image
-			mutable QImage* m_pickImage;       ///< storage for picking image
-			QColor m_backgroundColor;          ///< The background colour
-			RectF m_viewRect;                  ///< Keeps the physical dimensions of the surface
-			QRect m_selectRect;
-			int m_interactionMode;             ///< mode of interaction - index in m_inputControllers
-			bool m_isLightingOn;               ///< Lighting on/off flag
-
-			Shape2DCollection m_maskShapes;    ///< to draw mask shapes
-			mutable QList<PeakOverlay*> m_peakShapes; ///< to draw peak labels
-			mutable int m_peakLabelPrecision;
-			mutable bool m_showPeakRows;        ///< flag to show peak row index
-			mutable bool m_showPeakLabels;     ///< flag to show peak hkl labels
-			bool m_showPeakRelativeIntensity;     ///< flag to show peak hkl labels
-			mutable int m_peakShapesStyle;     ///< index of a default PeakMarker2D style to use with a new PeakOverlay.
-
-		private:
-			/// Get the current input controller
-			MantidQt::MantidWidgets::InputController* getController() const;
-
-			QMap<int, MantidQt::MantidWidgets::InputController*> m_inputControllers; ///< controllers for mouse and keyboard input
-																						/// Set when the image must be redrawn
-			mutable bool m_viewChanged;
-			/// Set when the picking image must be redrawn regardless of the interaction mode
-			mutable bool m_redrawPicking;
-		};
-
-		typedef boost::shared_ptr<ProjectionSurface> ProjectionSurface_sptr;
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+class MantidGLWidget;
+
+/**
+* @class ProjectionSurface
+* @brief Performs projection of an instrument onto a plane.
+* @author Roman Tolchenov, Tessella plc
+* @date 13 May 2011
+
+* Performs projection of an instrument onto a plane. Draws the resulting image
+on the screen.
+* Supports selection and zooming.
+*
+* Iherited classes must implement the pure virtual methods and set m_viewRect -
+the bounding
+* rectangle in surface coordinates.
+*/
+
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ProjectionSurface : public QObject {
+  Q_OBJECT
+public:
+  enum InteractionMode {
+    MoveMode = 0,
+    PickSingleMode,
+    PickTubeMode,
+    AddPeakMode,
+    DrawRegularMode,
+    DrawFreeMode,
+    ErasePeakMode,
+    InteractionModeSize
+  };
+  /// Constructor
+  explicit ProjectionSurface(const InstrumentActor *rootActor);
+  /// Destructor
+  ~ProjectionSurface() override;
+  /// Resets the instrument actor.
+  void resetInstrumentActor(const InstrumentActor *rootActor);
+
+  //-----------------------------------
+  //     Public virtual methods
+  //-----------------------------------
+
+  /// draw the surface onto a GL widget
+  virtual void draw(MantidGLWidget *widget) const;
+  /// draw the surface onto a normal widget
+  virtual void drawSimple(QWidget *widget) const;
+  /// called when the gl widget gets resized
+  virtual void resize(int, int);
+  /// redraw surface without recalulationg of colours, etc
+  virtual void updateView(bool picking = true);
+  /// full update and redraw of the surface
+  virtual void updateDetectors();
+  /// returns the bounding rectangle in the real coordinates
+  virtual RectF getSurfaceBounds() const { return m_viewRect; }
+
+  virtual void mousePressEvent(QMouseEvent *);
+  virtual void mouseMoveEvent(QMouseEvent *);
+  virtual void mouseReleaseEvent(QMouseEvent *);
+  virtual void wheelEvent(QWheelEvent *);
+  virtual void keyPressEvent(QKeyEvent *);
+  virtual void enterEvent(QEvent *);
+  virtual void leaveEvent(QEvent *);
+
+  /// return true if any of the detectors have been selected
+  virtual bool hasSelection() const;
+
+  virtual int getDetectorID(int x, int y) const;
+  virtual boost::shared_ptr<const Mantid::Geometry::IDetector>
+  getDetector(int x, int y) const;
+  /// NULL deselects components and selects the whole instrument
+  virtual void componentSelected(Mantid::Geometry::ComponentID = NULL) = 0;
+  /// fill in a list of detector ids which were selected by the selction tool
+  virtual void getSelectedDetectors(QList<int> &dets) = 0;
+  /// fill in a list of detector ids which were masked by the mask shapes
+  virtual void getMaskedDetectors(QList<int> &dets) const = 0;
+
+  virtual QString getInfoText() const;
+  /// Change the interaction mode
+  virtual void setInteractionMode(int mode);
+
+  //-----------------------------------
+
+  Mantid::Kernel::V3D getDetectorPos(int x, int y) const;
+  /// Return the current interaction mode
+  int getInteractionMode() const { return m_interactionMode; }
+  /// Ask current input controller if a context menu is allowed
+  bool canShowContextMenu() const;
+
+  /// Set background colour
+  void setBackgroundColor(const QColor &color) { m_backgroundColor = color; }
+  /// Get background colour
+  QColor getBackgroundColor() const { return m_backgroundColor; }
+  /// Send a redraw request to the surface owner
+  void requestRedraw(bool resetPeakVisibility = false);
+  /// Enable lighting if the implementation allows it
+  void enableLighting(bool on);
+
+  //-----------------------------------
+  //    Mask methods
+  //-----------------------------------
+
+  /// Return bounding rect of the currently selected shape in the "original"
+  /// coord system.
+  /// It doesn't depend on the zooming of the surface
+  RectF getCurrentBoundingRect() const {
+    return m_maskShapes.getCurrentBoundingRect();
+  }
+
+  /// Set new bounding rect of the currently selected shape in the "original"
+  /// coord system.
+  /// This method resizes the shape to fit into the new rectangle.
+  void setCurrentBoundingRect(const RectF &rect) {
+    m_maskShapes.setCurrentBoundingRect(rect);
+  }
+
+  /// Initialize interactive shape creation.
+  /// @param type :: Type of the shape. For available types see code of
+  /// Shape2DCollection::createShape(const QString& type,int x,int y) const
+  /// @param borderColor :: The color of the shape outline.
+  /// @param fillColor :: The fill color.
+  void startCreatingShape2D(const QString &type, const QColor &borderColor,
+                            const QColor &fillColor = QColor());
+
+  /// Initialize interactive creation of a free draw shape.
+  /// @param borderColor :: The color of the shape outline.
+  /// @param fillColor :: The fill color.
+  void startCreatingFreeShape(const QColor &borderColor,
+                              const QColor &fillColor = QColor());
+
+  // Properties methods which allow the mask shapes to be modified with a
+  // property browser.
+
+  /// Return a list of all properties of type double of the currently selected
+  /// shape.
+  QStringList getCurrentDoubleNames() const {
+    return m_maskShapes.getCurrentDoubleNames();
+  }
+
+  /// Get value of a "double" property of the currently selected shape.
+  /// @param prop :: Name of the property
+  double getCurrentDouble(const QString &prop) const {
+    return m_maskShapes.getCurrentDouble(prop);
+  }
+
+  /// Set value of a "double" property of the currently selected shape.
+  /// @param prop :: Name of the property
+  /// @param value :: New value
+  void setCurrentDouble(const QString &prop, double value) {
+    m_maskShapes.setCurrentDouble(prop, value);
+  }
+
+  /// Return a list of all properties of type QPointF of the currently selected
+  /// shape.
+  QStringList getCurrentPointNames() const {
+    return m_maskShapes.getCurrentPointNames();
+  }
+
+  /// Get value of a "QPointF" property of the currently selected shape.
+  /// @param prop :: Name of the property
+  QPointF getCurrentPoint(const QString &prop) const {
+    return m_maskShapes.getCurrentPoint(prop);
+  }
+
+  /// Set value of a "QPointF" property of the currently selected shape.
+  /// @param prop :: Name of the property
+  /// @param value :: New value
+  void setCurrentPoint(const QString &prop, const QPointF &value) {
+    m_maskShapes.setCurrentPoint(prop, value);
+  }
+
+  /// Check if a point on the scren is under any of the mask shapes
+  bool isMasked(double x, double y) const {
+    return m_maskShapes.isMasked(x, y);
+  }
+  /// Check if there are any masks defined
+  bool hasMasks() const { return m_maskShapes.size() > 0; }
+  /// Remove all mask shapes.
+  void clearMask() { m_maskShapes.clear(); }
+  /// Change all border colors.
+  void changeBorderColor(const QColor &color) {
+    m_maskShapes.changeBorderColor(color);
+  }
+
+  //-----------------------------------
+  //    Peaks overlay methods
+  //-----------------------------------
+
+  QList<PeakMarker2D *> getMarkersWithID(int detID) const;
+  boost::shared_ptr<Mantid::API::IPeaksWorkspace> getEditPeaksWorkspace() const;
+  QStringList getPeaksWorkspaceNames() const;
+  void deletePeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> ws);
+  void clearPeakOverlays();
+  bool hasPeakOverlays() const { return !m_peakShapes.isEmpty(); }
+  void setPeakLabelPrecision(int n);
+  int getPeakLabelPrecision() const { return m_peakLabelPrecision; }
+  void setShowPeakRowsFlag(bool on);
+  bool getShowPeakRowsFlag() const { return m_showPeakRows; }
+  void setShowPeakLabelsFlag(bool on);
+  bool getShowPeakLabelsFlag() const { return m_showPeakLabels; }
+  void setShowPeakRelativeIntensityFlag(bool on);
+  bool getShowPeakRelativeIntensityFlag() const {
+    return m_showPeakRelativeIntensity;
+  }
+
+signals:
+
+  // detector selection
+  void singleComponentTouched(size_t);
+  void singleComponentPicked(size_t);
+
+  // shape manipulation
+  void signalToStartCreatingShape2D(const QString &type,
+                                    const QColor &borderColor,
+                                    const QColor &fillColor);
+  void signalToStartCreatingFreeShape(const QColor &borderColor,
+                                      const QColor &fillColor);
+  void shapeCreated();
+  void shapeSelected();
+  void shapesDeselected();
+  void shapeChanged();
+  void shapesCleared();
+  void shapesRemoved();
+  void shapeChangeFinished();
+
+  // peaks
+  void peaksWorkspaceAdded();
+  void peaksWorkspaceDeleted();
+
+  // other
+  void redrawRequired(); ///< request redrawing of self
+  void updateInfoText(); ///< request update of the info string at bottom of
+  /// InstrumentWindow
+  void executeAlgorithm(Mantid::API::IAlgorithm_sptr);
+
+protected slots:
+
+  void setSelectionRect(const QRect &rect);
+  void emptySelectionRect();
+  void selectMultipleMasks(const QRect &rect);
+  void pickComponentAt(int x, int y);
+  void touchComponentAt(int x, int y);
+  void erasePeaks(const QRect &rect);
+
+  void colorMapChanged();
+
+protected:
+  //-----------------------------------
+  //     Protected virtual methods
+  //-----------------------------------
+
+  virtual void init() = 0;
+  /// Draw the surface onto an OpenGL widget
+  virtual void drawSurface(MantidGLWidget *widget,
+                           bool picking = false) const = 0;
+  /// Respond to a change of color map in m_instrActor
+  virtual void changeColorMap() = 0;
+  /// Draw the surface onto an image without OpenGL
+  virtual void drawSimpleToImage(QImage *image, bool picking = false) const;
+
+  //-----------------------------------
+
+  void draw(MantidGLWidget *widget, bool picking) const;
+  void clear();
+  QRect selectionRect() const;
+  RectF selectionRectUV() const;
+  size_t getPickID(int x, int y) const;
+  void setInputController(int mode,
+                          MantidQt::MantidWidgets::InputController *controller);
+  void setPeakVisibility() const;
+
+  //-----------------------------------
+  //     Protected data
+  //-----------------------------------
+
+  const InstrumentActor *m_instrActor;
+  mutable QImage *m_viewImage; ///< storage for view image
+  mutable QImage *m_pickImage; ///< storage for picking image
+  QColor m_backgroundColor;    ///< The background colour
+  RectF m_viewRect;            ///< Keeps the physical dimensions of the surface
+  QRect m_selectRect;
+  int m_interactionMode; ///< mode of interaction - index in m_inputControllers
+  bool m_isLightingOn;   ///< Lighting on/off flag
+
+  Shape2DCollection m_maskShapes;            ///< to draw mask shapes
+  mutable QList<PeakOverlay *> m_peakShapes; ///< to draw peak labels
+  mutable int m_peakLabelPrecision;
+  mutable bool m_showPeakRows;      ///< flag to show peak row index
+  mutable bool m_showPeakLabels;    ///< flag to show peak hkl labels
+  bool m_showPeakRelativeIntensity; ///< flag to show peak hkl labels
+  mutable int m_peakShapesStyle; ///< index of a default PeakMarker2D style to
+  /// use with a new PeakOverlay.
+
+private:
+  /// Get the current input controller
+  MantidQt::MantidWidgets::InputController *getController() const;
+
+  QMap<int, MantidQt::MantidWidgets::InputController *>
+      m_inputControllers; ///< controllers for mouse and keyboard input
+                          /// Set when the image must be redrawn
+  mutable bool m_viewChanged;
+  /// Set when the picking image must be redrawn regardless of the interaction
+  /// mode
+  mutable bool m_redrawPicking;
+};
+
+typedef boost::shared_ptr<ProjectionSurface> ProjectionSurface_sptr;
+
+} // MantidWidgets
+} // MantidQt
 
 #endif // PROJECTIONSURFACE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectF.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectF.h
index ec224d438af95af807c59777ed8da9c6cc8c348f..f5d3e251b228e5d1ec1c0a74eb588fe6f320d34d 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectF.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectF.h
@@ -11,230 +11,196 @@
 #include <stdexcept>
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-
-		/**
-
-		A class for a axis aligned rectangle defined by its two opposite points.
-		If the rectangle is used to define a coord system the first of the two points
-		is its origin.
-
-		width() and height() always return a non-negative number.
-
-		*/
-		class RectF
-		{
-		public:
-			/// The default constructor creates an empty rectangle at (0,0)
-			RectF() :m_x0(), m_y0(), m_x1(), m_y1() {}
-			/// Set the first point at origin and the second is shifted in positive directions of the x and y axes by vector size.
-			RectF(const QPointF &origin, const QSizeF &size);
-			/// Explicitly set the two points
-			RectF(const QPointF &point0, const QPointF &point1);
-			explicit RectF(const QRectF &rect);
-			/// Copy constructor
-			RectF(const RectF &rect) { *this = rect; }
-			/// Copy assignment operator
-			RectF& operator =(const RectF& rect);
-
-			bool isEmpty() const;
-			QPointF center() const;
-			void moveCenter(const QPointF& p);
-
-			inline double x0() const { return m_x0; }
-			inline double y0() const { return m_y0; }
-			inline double x1() const { return m_x1; }
-			inline double y1() const { return m_y1; }
-
-			QPointF p0() const { return QPointF(m_x0, m_y0); }
-			QPointF p1() const { return QPointF(m_x1, m_y1); }
-
-			QPointF vertex(size_t i) const;
-			void setVertex(size_t i, const QPointF& p);
-
-			void translate(double dx, double dy);
-			void translate(const QPointF &p);
-
-			RectF translated(double dx, double dy) const;
-			RectF translated(const QPointF &p) const;
-
-			/**
-			* Adjust the rect by moving the defining points.
-			* @param dp0 :: Vector to be added to the first point.
-			* @param dp1 :: Vector to be added to the second point.
-			*/
-			void adjust(const QPointF& dp0, const QPointF& dp1);
-
-			/// Expand the rectangle if needed to include a point.
-			void include(const QPointF& p);
-			void unite(const RectF& rect);
-
-			inline void xFlip();
-			inline void yFlip();
-
-			QSizeF size() const;
-			double width() const;
-			double height() const;
-
-			/// x1 - x0
-			double xSpan() const;
-			/// y1 - y0
-			double ySpan() const;
-
-			bool contains(const QPointF &p) const { return contains(p.x(), p.y()); }
-			bool contains(double x, double y) const;
-			bool contains(const RectF& rect);
-
-			void findTransform(QTransform& trans, const QRectF& rect) const;
-
-			QRectF toQRectF() const;
-
-		private:
-			double m_x0;
-			double m_y0;
-			double m_x1;
-			double m_y1;
-		};
-
-		/*****************************************************************************
-		RectF inline member functions
-		*****************************************************************************/
-
-		inline RectF::RectF(const QPointF &origin, const QSizeF &size)
-		{
-			m_x0 = origin.x();
-			m_y0 = origin.y();
-			m_x1 = m_x0 + size.width();
-			m_y1 = m_y0 + size.height();
-		}
-
-		inline RectF::RectF(const QPointF &point0, const QPointF &point1)
-		{
-			m_x0 = point0.x();
-			m_y0 = point0.y();
-			m_x1 = point1.x();
-			m_y1 = point1.y();
-		}
-
-		inline RectF::RectF(const QRectF &rect)
-		{
-			m_x0 = rect.left();
-			m_y0 = rect.top();
-			m_x1 = rect.right();
-			m_y1 = rect.bottom();
-		}
-
-		inline RectF& RectF::operator =(const RectF& rect)
-		{
-			m_x0 = rect.m_x0; m_y0 = rect.m_y0; m_x1 = rect.m_x1; m_y1 = rect.m_y1; return *this;
-		}
-
-		inline bool RectF::isEmpty() const
-		{
-			return m_x0 == m_x1 || m_y0 == m_y1;
-		}
-
-		inline QPointF RectF::center() const
-		{
-			return QPointF((m_x0 + m_x1) / 2, (m_y0 + m_y1) / 2);
-		}
-
-		inline double RectF::width() const
-		{
-			return fabs(m_x1 - m_x0);
-		}
-
-		inline double RectF::height() const
-		{
-			return fabs(m_y1 - m_y0);
-		}
-
-		inline double RectF::xSpan() const
-		{
-			return m_x1 - m_x0;
-		}
-
-		inline double RectF::ySpan() const
-		{
-			return m_y1 - m_y0;
-		}
-
-		inline QSizeF RectF::size() const
-		{
-			return QSizeF(width(), height());
-		}
-
-		inline void RectF::translate(double dx, double dy)
-		{
-			m_x0 += dx;
-			m_y0 += dy;
-			m_x1 += dx;
-			m_y1 += dy;
-		}
-
-		inline void RectF::translate(const QPointF &p)
-		{
-			m_x0 += p.x();
-			m_y0 += p.y();
-			m_x1 += p.x();
-			m_y1 += p.y();
-		}
-
-		inline RectF RectF::translated(double dx, double dy) const
-		{
-			return RectF(QPointF(m_x0 + dx, m_y0 + dy), QPointF(m_x1 + dx, m_y1 + dy));
-		}
-
-		inline RectF RectF::translated(const QPointF &p) const
-		{
-			return RectF(QPointF(m_x0 + p.x(), m_y0 + p.y()), QPointF(m_x1 + p.x(), m_y1 + p.y()));
-		}
-
-		inline void RectF::adjust(const QPointF &dp0, const QPointF &dp1)
-		{
-			m_x0 += dp0.x();
-			m_y0 += dp0.y();
-			m_x1 += dp1.x();
-			m_y1 += dp1.y();
-		}
-
-		inline void RectF::xFlip()
-		{
-			std::swap(m_x0, m_x1);
-		}
-
-		inline void RectF::yFlip()
-		{
-			std::swap(m_y0, m_y1);
-		}
-
-		inline QRectF RectF::toQRectF() const
-		{
-			return QRectF(m_x0, m_y0, xSpan(), ySpan());
-		}
-
-		inline std::ostream& operator << (std::ostream& ostr, const RectF& rect)
-		{
-			ostr << '[' << rect.x0() << ',' << rect.x1() << ';' << rect.y0() << ',' << rect.y1() << ']';
-			return ostr;
-		}
-
-		inline std::ostream& operator << (std::ostream& ostr, const QRectF& rect)
-		{
-			ostr << '[' << rect.left() << ',' << rect.right() << ';' << rect.top() << ',' << rect.bottom() << ']';
-			return ostr;
-		}
-
-		inline std::ostream& operator << (std::ostream& ostr, const QPointF& p)
-		{
-			ostr << '(' << p.x() << ',' << p.y() << ')';
-			return ostr;
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+
+A class for a axis aligned rectangle defined by its two opposite points.
+If the rectangle is used to define a coord system the first of the two points
+is its origin.
+
+width() and height() always return a non-negative number.
+
+*/
+class RectF {
+public:
+  /// The default constructor creates an empty rectangle at (0,0)
+  RectF() : m_x0(), m_y0(), m_x1(), m_y1() {}
+  /// Set the first point at origin and the second is shifted in positive
+  /// directions of the x and y axes by vector size.
+  RectF(const QPointF &origin, const QSizeF &size);
+  /// Explicitly set the two points
+  RectF(const QPointF &point0, const QPointF &point1);
+  explicit RectF(const QRectF &rect);
+  /// Copy constructor
+  RectF(const RectF &rect) { *this = rect; }
+  /// Copy assignment operator
+  RectF &operator=(const RectF &rect);
+
+  bool isEmpty() const;
+  QPointF center() const;
+  void moveCenter(const QPointF &p);
+
+  inline double x0() const { return m_x0; }
+  inline double y0() const { return m_y0; }
+  inline double x1() const { return m_x1; }
+  inline double y1() const { return m_y1; }
+
+  QPointF p0() const { return QPointF(m_x0, m_y0); }
+  QPointF p1() const { return QPointF(m_x1, m_y1); }
+
+  QPointF vertex(size_t i) const;
+  void setVertex(size_t i, const QPointF &p);
+
+  void translate(double dx, double dy);
+  void translate(const QPointF &p);
+
+  RectF translated(double dx, double dy) const;
+  RectF translated(const QPointF &p) const;
+
+  /**
+  * Adjust the rect by moving the defining points.
+  * @param dp0 :: Vector to be added to the first point.
+  * @param dp1 :: Vector to be added to the second point.
+  */
+  void adjust(const QPointF &dp0, const QPointF &dp1);
+
+  /// Expand the rectangle if needed to include a point.
+  void include(const QPointF &p);
+  void unite(const RectF &rect);
+
+  inline void xFlip();
+  inline void yFlip();
+
+  QSizeF size() const;
+  double width() const;
+  double height() const;
+
+  /// x1 - x0
+  double xSpan() const;
+  /// y1 - y0
+  double ySpan() const;
+
+  bool contains(const QPointF &p) const { return contains(p.x(), p.y()); }
+  bool contains(double x, double y) const;
+  bool contains(const RectF &rect);
+
+  void findTransform(QTransform &trans, const QRectF &rect) const;
+
+  QRectF toQRectF() const;
+
+private:
+  double m_x0;
+  double m_y0;
+  double m_x1;
+  double m_y1;
+};
+
+/*****************************************************************************
+RectF inline member functions
+*****************************************************************************/
+
+inline RectF::RectF(const QPointF &origin, const QSizeF &size) {
+  m_x0 = origin.x();
+  m_y0 = origin.y();
+  m_x1 = m_x0 + size.width();
+  m_y1 = m_y0 + size.height();
+}
+
+inline RectF::RectF(const QPointF &point0, const QPointF &point1) {
+  m_x0 = point0.x();
+  m_y0 = point0.y();
+  m_x1 = point1.x();
+  m_y1 = point1.y();
+}
+
+inline RectF::RectF(const QRectF &rect) {
+  m_x0 = rect.left();
+  m_y0 = rect.top();
+  m_x1 = rect.right();
+  m_y1 = rect.bottom();
+}
+
+inline RectF &RectF::operator=(const RectF &rect) {
+  m_x0 = rect.m_x0;
+  m_y0 = rect.m_y0;
+  m_x1 = rect.m_x1;
+  m_y1 = rect.m_y1;
+  return *this;
+}
+
+inline bool RectF::isEmpty() const { return m_x0 == m_x1 || m_y0 == m_y1; }
+
+inline QPointF RectF::center() const {
+  return QPointF((m_x0 + m_x1) / 2, (m_y0 + m_y1) / 2);
+}
+
+inline double RectF::width() const { return fabs(m_x1 - m_x0); }
+
+inline double RectF::height() const { return fabs(m_y1 - m_y0); }
+
+inline double RectF::xSpan() const { return m_x1 - m_x0; }
+
+inline double RectF::ySpan() const { return m_y1 - m_y0; }
+
+inline QSizeF RectF::size() const { return QSizeF(width(), height()); }
+
+inline void RectF::translate(double dx, double dy) {
+  m_x0 += dx;
+  m_y0 += dy;
+  m_x1 += dx;
+  m_y1 += dy;
+}
+
+inline void RectF::translate(const QPointF &p) {
+  m_x0 += p.x();
+  m_y0 += p.y();
+  m_x1 += p.x();
+  m_y1 += p.y();
+}
+
+inline RectF RectF::translated(double dx, double dy) const {
+  return RectF(QPointF(m_x0 + dx, m_y0 + dy), QPointF(m_x1 + dx, m_y1 + dy));
+}
+
+inline RectF RectF::translated(const QPointF &p) const {
+  return RectF(QPointF(m_x0 + p.x(), m_y0 + p.y()),
+               QPointF(m_x1 + p.x(), m_y1 + p.y()));
+}
+
+inline void RectF::adjust(const QPointF &dp0, const QPointF &dp1) {
+  m_x0 += dp0.x();
+  m_y0 += dp0.y();
+  m_x1 += dp1.x();
+  m_y1 += dp1.y();
+}
+
+inline void RectF::xFlip() { std::swap(m_x0, m_x1); }
+
+inline void RectF::yFlip() { std::swap(m_y0, m_y1); }
+
+inline QRectF RectF::toQRectF() const {
+  return QRectF(m_x0, m_y0, xSpan(), ySpan());
+}
+
+inline std::ostream &operator<<(std::ostream &ostr, const RectF &rect) {
+  ostr << '[' << rect.x0() << ',' << rect.x1() << ';' << rect.y0() << ','
+       << rect.y1() << ']';
+  return ostr;
+}
+
+inline std::ostream &operator<<(std::ostream &ostr, const QRectF &rect) {
+  ostr << '[' << rect.left() << ',' << rect.right() << ';' << rect.top() << ','
+       << rect.bottom() << ']';
+  return ostr;
+}
+
+inline std::ostream &operator<<(std::ostream &ostr, const QPointF &p) {
+  ostr << '(' << p.x() << ',' << p.y() << ')';
+  return ostr;
+}
+} // MantidWidgets
+} // MantidQt
 
 #endif // RECTF_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectangularDetectorActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectangularDetectorActor.h
index 58f01ea096786f1bcd86feaf997ebbade810171e..ac19dc3a3b3e8ed0fbca5780662d730505de9e1e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectangularDetectorActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RectangularDetectorActor.h
@@ -15,7 +15,8 @@
 
   This class is used to render a RectangularDetector as a bitmap and plot it.
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -34,88 +35,80 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-namespace Mantid
-{
-namespace Kernel
-{
-  class V3D;
+namespace Mantid {
+namespace Kernel {
+class V3D;
 }
-namespace Geometry
-{
-  class ICompAssembly;
-  class Object;
+namespace Geometry {
+class ICompAssembly;
+class Object;
 }
-
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class ObjComponentActor;
-
-		class RectangularDetectorActor : public ICompAssemblyActor
-		{
-		public:
-			/// Constructor
-			RectangularDetectorActor(const InstrumentActor& instrActor, const Mantid::Geometry::ComponentID& compID);
-			/// Destructor
-                        ~RectangularDetectorActor() override;
-
-                private:
-			void AppendBoundingBox(const Mantid::Kernel::V3D& minBound, const Mantid::Kernel::V3D& maxBound);
-
-		protected:
-			/// The rectangular detector
-			boost::shared_ptr<const Mantid::Geometry::RectangularDetector> mDet;
-
-			void init()const;
-			void redraw();
-			int findDetectorIDUsingColor(int rgb);
-			virtual void initChilds(bool) {}
-
-		public:
-                  std::string type() const override {
-                    return "RectangularDetectorActor";
-                  } ///< Type of the GL object
-
-                  void
-                  draw(bool picking = false) const override; ///< Method that
-                                                             ///defines
-                                                             ///ObjComponent
-                                                             ///geometry. Calls
-                                                             ///ObjComponent
-                                                             ///draw method
-                  void
-                  getBoundingBox(Mantid::Kernel::V3D &minBound,
-                                 Mantid::Kernel::V3D &maxBound) const override;
-                  bool accept(GLActorVisitor &visitor,
-                              VisitorAcceptRule rule = VisitAll) override;
-                  bool accept(GLActorConstVisitor &visitor,
-                              VisitorAcceptRule rule = VisitAll) const override;
-                        bool isChildDetector(const Mantid::Geometry::ComponentID& id) const;
-                        void setColors() override;
-
-                        int genTexture(char * & image_data, std::vector<GLColor>& list, bool useDetectorIDs);
-			void uploadTexture(char * & image_data)const;
-
-		private:
-			/// Texture ID that holds the texture.
-			mutable unsigned int mTextureID;
-
-			/// Pointer to the array holding the texture color data
-			mutable char * image_data;
-
-			/// Pointer to the array holding the color data for picking the scene
-			mutable char * pick_data;
-
-			/// pick ids
-			std::vector<size_t> m_pickIDs;
-		};
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+class ObjComponentActor;
+
+class RectangularDetectorActor : public ICompAssemblyActor {
+public:
+  /// Constructor
+  RectangularDetectorActor(const InstrumentActor &instrActor,
+                           const Mantid::Geometry::ComponentID &compID);
+  /// Destructor
+  ~RectangularDetectorActor() override;
+
+private:
+  void AppendBoundingBox(const Mantid::Kernel::V3D &minBound,
+                         const Mantid::Kernel::V3D &maxBound);
+
+protected:
+  /// The rectangular detector
+  boost::shared_ptr<const Mantid::Geometry::RectangularDetector> mDet;
+
+  void init() const;
+  void redraw();
+  int findDetectorIDUsingColor(int rgb);
+  virtual void initChilds(bool) {}
+
+public:
+  std::string type() const override {
+    return "RectangularDetectorActor";
+  } ///< Type of the GL object
+
+  void draw(bool picking = false) const override; ///< Method that
+  /// defines
+  /// ObjComponent
+  /// geometry. Calls
+  /// ObjComponent
+  /// draw method
+  void getBoundingBox(Mantid::Kernel::V3D &minBound,
+                      Mantid::Kernel::V3D &maxBound) const override;
+  bool accept(GLActorVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) override;
+  bool accept(GLActorConstVisitor &visitor,
+              VisitorAcceptRule rule = VisitAll) const override;
+  bool isChildDetector(const Mantid::Geometry::ComponentID &id) const;
+  void setColors() override;
+
+  int genTexture(char *&image_data, std::vector<GLColor> &list,
+                 bool useDetectorIDs);
+  void uploadTexture(char *&image_data) const;
+
+private:
+  /// Texture ID that holds the texture.
+  mutable unsigned int mTextureID;
+
+  /// Pointer to the array holding the texture color data
+  mutable char *image_data;
+
+  /// Pointer to the array holding the color data for picking the scene
+  mutable char *pick_data;
+
+  /// pick ids
+  std::vector<size_t> m_pickIDs;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif /*RECTANGULAR_DETECTOR_ACTOR__H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RotationSurface.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RotationSurface.h
index 78036eeaed3a4f4f58f534b849d79f2f723c1050..5e21f753185e7748e35c8ea7a7aa57867a25f2d6 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RotationSurface.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/RotationSurface.h
@@ -3,54 +3,58 @@
 
 #include "UnwrappedSurface.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* @class RotationSurface
-		* @brief Performs projection of an instrument onto a 2D surface of rotation: cylinder, sphere, ...
-		*/
-		class RotationSurface : public UnwrappedSurface
-		{
-		public:
-			RotationSurface(const InstrumentActor* rootActor, const Mantid::Kernel::V3D& origin, const Mantid::Kernel::V3D& axis);
-                        void init() override;
-                        // Get the value of the u-correction - a shift in the u-coord added to automatically determined uv coordinates
-			QPointF getUCorrection() const { return QPointF(m_u_min, m_u_max); }
-			// Set new value for the u-correction
-			void setUCorrection(double umin, double umax);
-			// Set automatic u-correction
-			void setAutomaticUCorrection();
-			// Is u-correction applied manually?
-			bool isManualUCorrection() const { return m_manual_u_correction; }
-
-		protected:
-
-			/// Period in the u coordinate. 2pi by default.
-			virtual double uPeriod() const { return 2 * M_PI; }
-
-			/// Given the u and v coords for all detectors find their min and max values
-			/// and set m_u_min, m_u_max, m_v_min, m_v_max
-			void findUVBounds();
-
-			/// Automatic generation of the projection coordinates may leave a gap
-			/// in u when the surface is unwrapped. This method tries to minimize
-			/// this gap by shifting the origin of the u axis.
-			void findAndCorrectUGap();
-
-			/// Applies the shift (u-correction) found by findAndCorrectUGap() to a u-value.
-			/// This method should only be used inside an implementation of UnwrappedSurface::project().
-			double applyUCorrection(double u)const;
-
-			const Mantid::Kernel::V3D m_pos;   ///< Origin (sample position)
-			const Mantid::Kernel::V3D m_zaxis; ///< The z axis of the surface specific coord system
-			Mantid::Kernel::V3D m_xaxis;       ///< The x axis
-			Mantid::Kernel::V3D m_yaxis;       ///< The y axis
-			bool m_manual_u_correction;        ///< Flag set to prevent automatic FindAndCorrectUGap()
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* @class RotationSurface
+* @brief Performs projection of an instrument onto a 2D surface of rotation:
+* cylinder, sphere, ...
+*/
+class RotationSurface : public UnwrappedSurface {
+public:
+  RotationSurface(const InstrumentActor *rootActor,
+                  const Mantid::Kernel::V3D &origin,
+                  const Mantid::Kernel::V3D &axis);
+  void init() override;
+  // Get the value of the u-correction - a shift in the u-coord added to
+  // automatically determined uv coordinates
+  QPointF getUCorrection() const { return QPointF(m_u_min, m_u_max); }
+  // Set new value for the u-correction
+  void setUCorrection(double umin, double umax);
+  // Set automatic u-correction
+  void setAutomaticUCorrection();
+  // Is u-correction applied manually?
+  bool isManualUCorrection() const { return m_manual_u_correction; }
+
+protected:
+  /// Period in the u coordinate. 2pi by default.
+  virtual double uPeriod() const { return 2 * M_PI; }
+
+  /// Given the u and v coords for all detectors find their min and max values
+  /// and set m_u_min, m_u_max, m_v_min, m_v_max
+  void findUVBounds();
+
+  /// Automatic generation of the projection coordinates may leave a gap
+  /// in u when the surface is unwrapped. This method tries to minimize
+  /// this gap by shifting the origin of the u axis.
+  void findAndCorrectUGap();
+
+  /// Applies the shift (u-correction) found by findAndCorrectUGap() to a
+  /// u-value.
+  /// This method should only be used inside an implementation of
+  /// UnwrappedSurface::project().
+  double applyUCorrection(double u) const;
+
+  const Mantid::Kernel::V3D m_pos; ///< Origin (sample position)
+  const Mantid::Kernel::V3D
+      m_zaxis; ///< The z axis of the surface specific coord system
+  Mantid::Kernel::V3D m_xaxis; ///< The x axis
+  Mantid::Kernel::V3D m_yaxis; ///< The y axis
+  bool m_manual_u_correction;  ///< Flag set to prevent automatic
+  /// FindAndCorrectUGap()
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif // ROTATIONSURFACE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SampleActor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SampleActor.h
index 6af1b484113aa7589f29f81c7592b033bec558d5..cb46c0c637f357391b73d6be01f0068eec750a2c 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SampleActor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SampleActor.h
@@ -13,9 +13,11 @@
   \date   04/07/2011
   \version 1.0
 
-   This class has the implementation for rendering SampleActor in OpenGL and it inherits from the GLActor
+   This class has the implementation for rendering SampleActor in OpenGL and it
+  inherits from the GLActor
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -34,46 +36,44 @@
 
   File change history is stored at: <https://github.com/mantidproject/mantid>
 */
-namespace Mantid
-{
-  namespace API
-  {
-    class Sample;
-  }
-  namespace Geometry
-  {
-    class IObjComponent;
-  }
+namespace Mantid {
+namespace API {
+class Sample;
+}
+namespace Geometry {
+class IObjComponent;
+}
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		class InstrumentActor;
+namespace MantidQt {
+namespace MantidWidgets {
+class InstrumentActor;
 
-		class SampleActor : public GLActor
-		{
-		public:
-			SampleActor(const InstrumentActor& instrActor, const Mantid::API::Sample& sample, const ObjComponentActor* samplePosActor); ///< Constructor
-			virtual std::string type()const { return "SampleActor"; } ///< Type of the GL object
-                        void draw(bool picking) const override;
-                        void getBoundingBox(
-                            Mantid::Kernel::V3D &minBound,
-                            Mantid::Kernel::V3D &maxBound) const override;
-                        void setColor(const GLColor& c) { m_color = c; }
-			const ObjComponentActor* getSamplePosActor()const { return m_samplePosActor; }
-		protected:
-			const InstrumentActor& m_instrActor;
-			const Mantid::API::Sample& m_sample;
-			const ObjComponentActor* m_samplePosActor;
-			boost::shared_ptr<const Mantid::Geometry::IObjComponent> m_samplePos;
-			GLColor m_color;
-		};
+class SampleActor : public GLActor {
+public:
+  SampleActor(const InstrumentActor &instrActor,
+              const Mantid::API::Sample &sample,
+              const ObjComponentActor *samplePosActor); ///< Constructor
+  virtual std::string type() const {
+    return "SampleActor";
+  } ///< Type of the GL object
+  void draw(bool picking) const override;
+  void getBoundingBox(Mantid::Kernel::V3D &minBound,
+                      Mantid::Kernel::V3D &maxBound) const override;
+  void setColor(const GLColor &c) { m_color = c; }
+  const ObjComponentActor *getSamplePosActor() const {
+    return m_samplePosActor;
+  }
 
-	}//MantidWidgets
-}//MantidQt
+protected:
+  const InstrumentActor &m_instrActor;
+  const Mantid::API::Sample &m_sample;
+  const ObjComponentActor *m_samplePosActor;
+  boost::shared_ptr<const Mantid::Geometry::IObjComponent> m_samplePos;
+  GLColor m_color;
+};
 
+} // MantidWidgets
+} // MantidQt
 
 #endif /*SMAPLE_ACTOR_H_*/
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2D.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2D.h
index 672eca3b2ad2c09d87648db1c1534b5912685b41..fcd4a396000fda1b3eef126040bee808c7dc63eb 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2D.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2D.h
@@ -11,287 +11,285 @@ class QPainterPath;
 class QMouseEvent;
 class QWheelEvent;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
+/**
+* Base class for an editable 2D shape, which can be drawn on ProjectionSurface.
+*
+* Any shape must implement these pure virtual methods:
+*    clone()     -- to copy itself
+*    drawShape() -- to draw itself
+*    refit()     -- to make sure the shape is entirely within its bounding rect
+*                   ( returned by getBoundingRect() )
+*    addToPath() -- to add itself to a QPainterPath, to allow this shape to be
+*used to
+*                   construct more complex shapes
+*
+* A shape has a border and the area inside this border. A point on the screen
+* which is inside the border is considered to be masked by this shape.
+* To be able to mask anything a shape must implement selectAt(...) and
+*contains(...)
+* methods.
+*
+* A shape can be a part of a Shape2DCollection. Collections allow to apply
+*transformations to
+* their items. A scale transformation is used to implement zooming. By default a
+*shape resizes
+* with the transformation. To override this call setScalable( false ). In this
+*case zooming
+* only changes the visible position but not the size of the shape.
+*
+* Shapes can be edited (ie change their position and sizes) in a generic way
+*either by using coltrol
+* points or setting properties.
+*
+*/
+class Shape2D {
+public:
+  /// Constructor.
+  Shape2D();
+  /// Virtual destructor.
+  virtual ~Shape2D() {}
 
-		/**
-		* Base class for an editable 2D shape, which can be drawn on ProjectionSurface.
-		*
-		* Any shape must implement these pure virtual methods:
-		*    clone()     -- to copy itself
-		*    drawShape() -- to draw itself
-		*    refit()     -- to make sure the shape is entirely within its bounding rect
-		*                   ( returned by getBoundingRect() )
-		*    addToPath() -- to add itself to a QPainterPath, to allow this shape to be used to
-		*                   construct more complex shapes
-		*
-		* A shape has a border and the area inside this border. A point on the screen
-		* which is inside the border is considered to be masked by this shape.
-		* To be able to mask anything a shape must implement selectAt(...) and contains(...)
-		* methods.
-		*
-		* A shape can be a part of a Shape2DCollection. Collections allow to apply transformations to
-		* their items. A scale transformation is used to implement zooming. By default a shape resizes
-		* with the transformation. To override this call setScalable( false ). In this case zooming
-		* only changes the visible position but not the size of the shape.
-		*
-		* Shapes can be edited (ie change their position and sizes) in a generic way either by using coltrol
-		* points or setting properties.
-		*
-		*/
-		class Shape2D
-		{
-		public:
-			/// Constructor.
-			Shape2D();
-			/// Virtual destructor.
-			virtual ~Shape2D() {}
+  // --- Public pure virtual methods --- //
 
-			// --- Public pure virtual methods --- //
+  /// Virtual "costructor".
+  virtual Shape2D *clone() const = 0;
+  /// modify path so painter.drawPath(path) could be used to draw the shape.
+  /// needed for filling in complex shapes
+  virtual void addToPath(QPainterPath &path) const = 0;
+  /// make sure the shape is within the bounding box
+  virtual void refit() = 0;
 
-			/// Virtual "costructor".
-			virtual Shape2D* clone()const = 0;
-			/// modify path so painter.drawPath(path) could be used to draw the shape. needed for filling in complex shapes
-			virtual void addToPath(QPainterPath& path) const = 0;
-			/// make sure the shape is within the bounding box
-			virtual void refit() = 0;
+  // --- Public virtual methods --- //
 
-			// --- Public virtual methods --- //
+  /// Draw this shape.
+  virtual void draw(QPainter &painter) const;
+  /// Get the origin - the centre of the bounding rect.
+  virtual QPointF origin() const { return m_boundingRect.center(); }
+  /// Move the shape by a vector.
+  virtual void moveBy(const QPointF &pos);
+  /// Get total number of control points.
+  virtual size_t getNControlPoints() const;
+  /// Get a control point.
+  virtual QPointF getControlPoint(size_t i) const;
+  /// Set a control point.
+  virtual void setControlPoint(size_t i, const QPointF &pos);
+  /// Return the bounding rect of the shape.
+  virtual RectF getBoundingRect() const { return m_boundingRect; }
+  /// move the left, top, right and bottom sides of the bounding rect
+  /// by dx1, dy1, dx2, and dy2 correspondingly
+  virtual void adjustBoundingRect(double dx1, double dy1, double dx2,
+                                  double dy2);
+  /// Set new bounding rect.
+  virtual void setBoundingRect(const RectF &rect);
+  /// will the shape be selected if clicked at a point? By default return false.
+  virtual bool selectAt(const QPointF &) const { return false; }
+  /// is a point inside the shape (closed line)? By default return false.
+  virtual bool contains(const QPointF &) const { return false; }
+  /// is a point "masked" by the shape. Only filled regions of a shape mask a
+  /// point
+  virtual bool isMasked(const QPointF &) const;
+  /// Set border color.
+  virtual void setColor(const QColor &color) { m_color = color; }
+  /// Get border color.
+  virtual QColor getColor() const { return m_color; }
+  /// Set fill color.
+  virtual void setFillColor(const QColor &color) { m_fill_color = color; }
 
-			/// Draw this shape.
-			virtual void draw(QPainter& painter) const;
-			/// Get the origin - the centre of the bounding rect.
-			virtual QPointF origin() const { return m_boundingRect.center(); }
-			/// Move the shape by a vector.
-			virtual void moveBy(const QPointF& pos);
-			/// Get total number of control points.
-			virtual size_t getNControlPoints() const;
-			/// Get a control point.
-			virtual QPointF getControlPoint(size_t i) const;
-			/// Set a control point.
-			virtual void setControlPoint(size_t i, const QPointF& pos);
-			/// Return the bounding rect of the shape.
-			virtual RectF getBoundingRect() const { return m_boundingRect; }
-			/// move the left, top, right and bottom sides of the bounding rect
-			/// by dx1, dy1, dx2, and dy2 correspondingly
-			virtual void adjustBoundingRect(double dx1, double dy1, double dx2, double dy2);
-			/// Set new bounding rect.
-			virtual void setBoundingRect(const RectF& rect);
-			/// will the shape be selected if clicked at a point? By default return false.
-			virtual bool selectAt(const QPointF&)const { return false; }
-			/// is a point inside the shape (closed line)? By default return false.
-			virtual bool contains(const QPointF&)const { return false; }
-			/// is a point "masked" by the shape. Only filled regions of a shape mask a point
-			virtual bool isMasked(const QPointF&)const;
-			/// Set border color.
-			virtual void setColor(const QColor& color) { m_color = color; }
-			/// Get border color.
-			virtual QColor getColor()const { return m_color; }
-			/// Set fill color.
-			virtual void setFillColor(const QColor& color) { m_fill_color = color; }
+  // --- Public methods --- //
 
-			// --- Public methods --- //
+  /// Set the shape scalable (default).
+  void setScalable(bool on) { m_scalable = on; }
+  /// Can the shape be scaled by Shape2DCollection's transformation?
+  bool isScalable() const { return m_scalable; }
+  /// Set the shape editable. Makes visible the bounding rect and teh control
+  /// points.
+  void edit(bool on) { m_editing = on; }
+  /// Check if the shape is being edited.
+  bool isEditing() const { return m_editing; }
+  /// Show or hide the shape
+  void setVisible(bool on) { m_visible = on; }
+  /// Is shape visible?
+  bool isVisible() const { return m_visible; }
+  /// Select/deselect the shape
+  void setSelected(bool on) { m_selected = on; }
+  /// Is shape selected?
+  bool isSelected() const { return m_selected; }
 
-			/// Set the shape scalable (default).
-			void setScalable(bool on) { m_scalable = on; }
-			/// Can the shape be scaled by Shape2DCollection's transformation?
-			bool isScalable() const { return m_scalable; }
-			/// Set the shape editable. Makes visible the bounding rect and teh control points.
-			void edit(bool on) { m_editing = on; }
-			/// Check if the shape is being edited.
-			bool isEditing()const { return m_editing; }
-			/// Show or hide the shape
-			void setVisible(bool on) { m_visible = on; }
-			/// Is shape visible?
-			bool isVisible() const { return m_visible; }
-			/// Select/deselect the shape
-			void setSelected(bool on) { m_selected = on; }
-			/// Is shape selected?
-			bool isSelected() const { return m_selected; }
+  // --- Properties. for gui interaction --- //
 
-			// --- Properties. for gui interaction --- //
+  // double properties
+  virtual QStringList getDoubleNames() const { return QStringList(); }
+  virtual double getDouble(const QString &prop) const {
+    (void)prop;
+    return 0.0;
+  }
+  virtual void setDouble(const QString &prop, double value) {
+    (void)prop;
+    (void)value;
+  }
 
-			// double properties
-			virtual QStringList getDoubleNames()const { return QStringList(); }
-			virtual double getDouble(const QString& prop) const { (void)prop; return 0.0; }
-			virtual void setDouble(const QString& prop, double value) { (void)prop; (void)value; }
+  // QPointF properties
+  virtual QStringList getPointNames() const { return QStringList(); }
+  virtual QPointF getPoint(const QString &prop) const {
+    (void)prop;
+    return QPointF();
+  }
+  virtual void setPoint(const QString &prop, const QPointF &value) {
+    (void)prop;
+    (void)value;
+  }
 
-			// QPointF properties
-			virtual QStringList getPointNames()const { return QStringList(); }
-			virtual QPointF getPoint(const QString& prop) const { (void)prop; return QPointF(); }
-			virtual void setPoint(const QString& prop, const QPointF& value) { (void)prop; (void)value; }
+protected:
+  // --- Protected pure virtual methods --- //
 
-		protected:
-			// --- Protected pure virtual methods --- //
+  virtual void drawShape(QPainter &painter) const = 0;
 
-			virtual void drawShape(QPainter& painter) const = 0;
+  // --- Protected virtual methods --- //
 
-			// --- Protected virtual methods --- //
+  // return number of control points specific to this shape
+  virtual size_t getShapeNControlPoints() const { return 0; }
+  // returns position of a shape specific control point, 0 < i <
+  // getShapeNControlPoints()
+  virtual QPointF getShapeControlPoint(size_t) const { return QPointF(); }
+  // sets position of a shape specific control point, 0 < i <
+  // getShapeNControlPoints()
+  virtual void setShapeControlPoint(size_t, const QPointF &) {}
+  // make sure the bounding box is correct
+  virtual void resetBoundingRect() {}
 
-			// return number of control points specific to this shape
-			virtual size_t getShapeNControlPoints() const { return 0; }
-			// returns position of a shape specific control point, 0 < i < getShapeNControlPoints()
-			virtual QPointF getShapeControlPoint(size_t) const { return QPointF(); }
-			// sets position of a shape specific control point, 0 < i < getShapeNControlPoints()
-			virtual void setShapeControlPoint(size_t, const QPointF&) {}
-			// make sure the bounding box is correct
-			virtual void resetBoundingRect() {}
+  // --- Protected data --- //
 
-			// --- Protected data --- //
+  static const size_t NCommonCP;
+  static const qreal sizeCP;
+  RectF m_boundingRect;
+  QColor m_color;
+  QColor m_fill_color;
+  bool m_scalable; ///< shape can be scaled when zoomed
+  bool m_editing;  ///< shape is being edited
+  bool m_selected; ///< shape is selected
+  bool m_visible;  ///< flag to show or hide the shape
+};
 
-			static const size_t NCommonCP;
-			static const qreal sizeCP;
-			RectF m_boundingRect;
-			QColor m_color;
-			QColor m_fill_color;
-			bool m_scalable; ///< shape can be scaled when zoomed
-			bool m_editing;  ///< shape is being edited
-			bool m_selected; ///< shape is selected
-			bool m_visible;  ///< flag to show or hide the shape
-		};
+/**
+* An ellipse with the axes parallel to the x and y axes on the screen.
+*
+* It has a QPointF property "center" defining the centre of the ellipse
+* and double properties "radius1" and "radius2" equal to distances from
+* the centre to the curve along the x and y axes.
+*/
+class Shape2DEllipse : public Shape2D {
+public:
+  Shape2DEllipse(const QPointF &center, double radius1, double radius2 = 0);
+  Shape2D *clone() const override { return new Shape2DEllipse(*this); }
+  bool selectAt(const QPointF &p) const override;
+  bool contains(const QPointF &p) const override;
+  void addToPath(QPainterPath &path) const override;
+  // double properties
+  QStringList getDoubleNames() const override;
+  double getDouble(const QString &prop) const override;
+  void setDouble(const QString &prop, double value) override;
+  // QPointF properties
+  QStringList getPointNames() const override { return QStringList("center"); }
+  QPointF getPoint(const QString &prop) const override;
+  void setPoint(const QString &prop, const QPointF &value) override;
 
-		/**
-		* An ellipse with the axes parallel to the x and y axes on the screen.
-		*
-		* It has a QPointF property "center" defining the centre of the ellipse
-		* and double properties "radius1" and "radius2" equal to distances from
-		* the centre to the curve along the x and y axes.
-		*/
-		class Shape2DEllipse : public Shape2D
-		{
-		public:
-			Shape2DEllipse(const QPointF& center, double radius1, double radius2 = 0);
-                        Shape2D *clone() const override {
-                          return new Shape2DEllipse(*this);
-                        }
-                        bool selectAt(const QPointF &p) const override;
-                        bool contains(const QPointF &p) const override;
-                        void addToPath(QPainterPath &path) const override;
-                        // double properties
-                        QStringList getDoubleNames() const override;
-                        double getDouble(const QString &prop) const override;
-                        void setDouble(const QString &prop,
-                                       double value) override;
-                        // QPointF properties
-                        QStringList getPointNames() const override {
-                          return QStringList("center");
-                        }
-                        QPointF getPoint(const QString &prop) const override;
-                        void setPoint(const QString &prop,
-                                      const QPointF &value) override;
+protected:
+  void drawShape(QPainter &painter) const override;
+  void refit() override {}
+};
 
-                protected:
-                  void drawShape(QPainter &painter) const override;
-                  void refit() override {}
-                };
+/**
+* A axis aligned rectangle.
+*
+* No specific properties.
+*/
+class Shape2DRectangle : public Shape2D {
+public:
+  Shape2DRectangle();
+  Shape2DRectangle(const QPointF &p0, const QPointF &p1);
+  Shape2DRectangle(const QPointF &p0, const QSizeF &size);
+  Shape2D *clone() const override { return new Shape2DRectangle(*this); }
+  bool selectAt(const QPointF &p) const override;
+  bool contains(const QPointF &p) const override {
+    return m_boundingRect.contains(p);
+  }
+  void addToPath(QPainterPath &path) const override;
 
-		/**
-		* A axis aligned rectangle.
-		*
-		* No specific properties.
-		*/
-		class Shape2DRectangle : public Shape2D
-		{
-		public:
-			Shape2DRectangle();
-			Shape2DRectangle(const QPointF& p0, const QPointF& p1);
-			Shape2DRectangle(const QPointF& p0, const QSizeF& size);
-                        Shape2D *clone() const override {
-                          return new Shape2DRectangle(*this);
-                        }
-                        bool selectAt(const QPointF &p) const override;
-                        bool contains(const QPointF &p) const override {
-                          return m_boundingRect.contains(p);
-                        }
-                        void addToPath(QPainterPath &path) const override;
+protected:
+  void drawShape(QPainter &painter) const override;
+  void refit() override {}
+};
 
-                protected:
-                  void drawShape(QPainter &painter) const override;
-                  void refit() override {}
-                };
+/**
+* A ring: area bounded by two curves of the same shape but different size.
+*
+* The constructor takes a curve shape and the ring widths in the x and y
+* directions.
+* It has QPointF "centre" property and "xwidth" and "ywidth" double properties.
+*/
+class Shape2DRing : public Shape2D {
+public:
+  Shape2DRing(Shape2D *shape, double xWidth = 0.000001,
+              double yWidth = 0.000001);
+  Shape2DRing(const Shape2DRing &ring);
+  Shape2D *clone() const override { return new Shape2DRing(*this); }
+  bool selectAt(const QPointF &p) const override;
+  bool contains(const QPointF &p) const override;
+  // double properties
+  QStringList getDoubleNames() const override;
+  double getDouble(const QString &prop) const override;
+  void setDouble(const QString &prop, double value) override;
+  // QPointF properties
+  QStringList getPointNames() const override { return QStringList("center"); }
+  QPointF getPoint(const QString &prop) const override;
+  void setPoint(const QString &prop, const QPointF &value) override;
+  void setColor(const QColor &color) override;
+  QColor getColor() const override { return m_outer_shape->getColor(); }
 
-		/**
-		* A ring: area bounded by two curves of the same shape but different size.
-		*
-		* The constructor takes a curve shape and the ring widths in the x and y
-		* directions.
-		* It has QPointF "centre" property and "xwidth" and "ywidth" double properties.
-		*/
-		class Shape2DRing : public Shape2D
-		{
-		public:
-			Shape2DRing(Shape2D* shape, double xWidth = 0.000001, double yWidth = 0.000001);
-			Shape2DRing(const Shape2DRing& ring);
-                        Shape2D *clone() const override {
-                          return new Shape2DRing(*this);
-                        }
-                        bool selectAt(const QPointF &p) const override;
-                        bool contains(const QPointF &p) const override;
-                        // double properties
-                        QStringList getDoubleNames() const override;
-                        double getDouble(const QString &prop) const override;
-                        void setDouble(const QString &prop,
-                                       double value) override;
-                        // QPointF properties
-                        QStringList getPointNames() const override {
-                          return QStringList("center");
-                        }
-                        QPointF getPoint(const QString &prop) const override;
-                        void setPoint(const QString &prop,
-                                      const QPointF &value) override;
-                        void setColor(const QColor &color) override;
-                        QColor getColor() const override {
-                          return m_outer_shape->getColor();
-                        }
+protected:
+  void drawShape(QPainter &painter) const override;
+  void addToPath(QPainterPath &) const override {}
+  void refit() override;
+  void resetBoundingRect() override;
+  size_t getShapeNControlPoints() const override { return 4; }
+  QPointF getShapeControlPoint(size_t i) const override;
+  void setShapeControlPoint(size_t i, const QPointF &pos) override;
+  Shape2D *m_outer_shape;
+  Shape2D *m_inner_shape;
+  double m_xWidth;
+  double m_yWidth;
+};
 
-                protected:
-                  void drawShape(QPainter &painter) const override;
-                  void addToPath(QPainterPath &) const override {}
-                  void refit() override;
-                  void resetBoundingRect() override;
-                  size_t getShapeNControlPoints() const override { return 4; }
-                  QPointF getShapeControlPoint(size_t i) const override;
-                  void setShapeControlPoint(size_t i,
-                                            const QPointF &pos) override;
-                        Shape2D* m_outer_shape;
-			Shape2D* m_inner_shape;
-			double m_xWidth;
-			double m_yWidth;
-		};
+/**
+* An arbitrary shape. Implemented as a polygon.
+* It can have disjointed parts and holes.
+*
+* No shape specific properties.
+*/
+class Shape2DFree : public Shape2D {
+public:
+  explicit Shape2DFree(const QPointF &p);
+  Shape2D *clone() const override { return new Shape2DFree(*this); }
+  bool selectAt(const QPointF &p) const override;
+  bool contains(const QPointF &p) const override;
+  void addToPath(QPainterPath &path) const override;
+  void addPolygon(const QPolygonF &polygon);
+  void subtractPolygon(const QPolygonF &polygon);
 
-		/**
-		* An arbitrary shape. Implemented as a polygon.
-		* It can have disjointed parts and holes.
-		*
-		* No shape specific properties.
-		*/
-		class Shape2DFree : public Shape2D
-		{
-		public:
-			explicit Shape2DFree(const QPointF &p);
-                        Shape2D *clone() const override {
-                          return new Shape2DFree(*this);
-                        }
-                        bool selectAt(const QPointF &p) const override;
-                        bool contains(const QPointF &p) const override;
-                        void addToPath(QPainterPath &path) const override;
-                        void addPolygon(const QPolygonF& polygon);
-			void subtractPolygon(const QPolygonF& polygon);
-		protected:
-                  void drawShape(QPainter &painter) const override;
-                  void refit() override;
-                  void resetBoundingRect() override;
-
-                private:
-			RectF getPolygonBoundingRect() const;
-			QPolygonF m_polygon;    ///< Implements the shape.
-			QPainterPath m_outline; ///< Object to draw the shape's border.
-		};
-	}//MantidWidgets
-}//MantidQt
+protected:
+  void drawShape(QPainter &painter) const override;
+  void refit() override;
+  void resetBoundingRect() override;
 
+private:
+  RectF getPolygonBoundingRect() const;
+  QPolygonF m_polygon;    ///< Implements the shape.
+  QPainterPath m_outline; ///< Object to draw the shape's border.
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MANTIDPLOT_SHAPE2D_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2DCollection.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2DCollection.h
index 8a080442a197b11e6676b497c7fe2364d76e8661..662e4c27735f22a2d4d94d2ce74c92eb2fbe0fa6 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2DCollection.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Shape2DCollection.h
@@ -12,129 +12,138 @@ class QMouseEvent;
 class QWheelEvent;
 class QKeyEvent;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* Class Shape2DCollection is a collection of 2D shapes.
-		* It supports operations on teh shapes such as adding, removing, and aditting either
-		* with the mouse via control points (CPs) or via properties.
-		*
-		* The shapes operate in two coordinate systems:
-		* 1. 'Real' or logical coordinates
-		* 2. Transformed screen coordinates
-		*
-		* Shape2DCollection must know the boundaries of the drawing area in logical and transformed screen coords.
-		* They are set by calling setWindow(...) method. The first argument is the logical drawing rectangle and
-		* the second one is the corresponding screen viewport in pixels. The individual shapes draw themselves in the
-		* logical coords and unaware of the screen ones at all. If the size of the screen/widget changes setWindow
-		* must be called again. Changing the logical drawing bounds translates and zooms the picture.
-		* The transformation is done by Qt's QTransform object.
-		*/
-		class Shape2DCollection : public QObject, public Shape2D
-		{
-			Q_OBJECT
-		public:
-			Shape2DCollection();
-                        ~Shape2DCollection() override;
-                        Shape2D *clone() const override { return NULL; }
-                        void setWindow(const RectF& surface, const QRect& viewport) const;
-                        void draw(QPainter &painter) const override;
-                        virtual void addShape(Shape2D*, bool slct = false);
-			virtual void removeShape(Shape2D*, bool sendSignal = true);
-			virtual void removeShapes(const QList<Shape2D*>&);
-			virtual void clear();
-
-			void keyPressEvent(QKeyEvent*);
-
-			bool selectAtXY(int x, int y, bool edit = true);
-			void deselectAtXY(int x, int y);
-			bool selectIn(const QRect& rect);
-			void removeCurrentShape();
-			bool isEmpty()const { return m_shapes.isEmpty(); }
-			size_t size()const { return static_cast<size_t>(m_shapes.size()); }
-			void addToSelection(int i);
-			bool hasSelection() const;
-
-			RectF getCurrentBoundingRect()const;
-			void setCurrentBoundingRect(const RectF &rect);
-			// double properties
-			QStringList getCurrentDoubleNames()const;
-			double getCurrentDouble(const QString& prop) const;
-			void setCurrentDouble(const QString& prop, double value);
-			// QPointF properties
-			QStringList getCurrentPointNames()const;
-			QPointF getCurrentPoint(const QString& prop) const;
-			void setCurrentPoint(const QString& prop, const QPointF& value);
-
-			using Shape2D::isMasked; // Unhide base class method (avoids Intel compiler warning)
-										// is a point in real space masked by any of the shapes
-			bool isMasked(double x, double y)const;
-			// collect all screen pixels that are masked by the shapes
-			QList<QPoint> getMaskedPixels()const;
-
-			// set the bounding rect of the current shape such that its real rect is given by the argument
-			void setCurrentBoundingRectReal(const QRectF& rect);
-
-			/// Change border color of all shapes.
-			void changeBorderColor(const QColor& color);
-
-		signals:
-
-			void shapeCreated();
-			void shapeSelected();
-			void shapesDeselected();
-			void shapesRemoved();
-			void shapeChanged();
-			void shapeChangeFinished();
-			void cleared();
-
-			public slots:
-			void addShape(const QString& type, int x, int y, const QColor& borderColor, const QColor& fillColor);
-			void addFreeShape(const QPolygonF&, const QColor& borderColor, const QColor& fillColor);
-			void deselectAll();
-			void moveRightBottomTo(int, int);
-			void selectShapeOrControlPointAt(int x, int y);
-			void addToSelectionShapeAt(int x, int y);
-			void moveShapeOrControlPointBy(int dx, int dy);
-			void touchShapeOrControlPointAt(int x, int y);
-			void removeSelectedShapes();
-			void restoreOverrideCursor();
-			void drawFree(const QPolygonF& polygon);
-			void eraseFree(const QPolygonF& polygon);
-
-		protected:
-                  void drawShape(QPainter &) const override {} // never called
-                  void addToPath(QPainterPath &) const override {}
-                  void refit() override;
-                  void resetBoundingRect() override;
-
-                        Shape2D* createShape(const QString& type, int x, int y)const;
-			bool selectControlPointAt(int x, int y);
-			void deselectControlPoint();
-			bool isOverCurrentAt(int x, int y);
-			bool isOverSelectionAt(int x, int y);
-			void addToSelection(Shape2D* shape);
-			void removeFromSelection(Shape2D* shape);
-			void edit(Shape2D* shape);
-			void finishEdit();
-			QList<Shape2D*> getSelectedShapes() const { return m_selectedShapes; }
-
-			QList<Shape2D*> m_shapes;
-			mutable RectF m_surfaceRect;       ///< original surface window in "real" coordinates
-			mutable double m_wx, m_wy;
-			mutable int m_h;                   ///< original screen viewport height
-			mutable QRect m_viewport;          ///< current screen viewport
-			mutable QTransform m_transform;    ///< current transform
-
-			Shape2D*  m_currentShape;          ///< shape selected to edit (change size/shape)
-			size_t m_currentCP;                ///< control point of m_currentShape selected to edit
-			QList<Shape2D*> m_selectedShapes;  ///< A list of selected shapes (can be moved or deleted)
-			bool m_overridingCursor;
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* Class Shape2DCollection is a collection of 2D shapes.
+* It supports operations on teh shapes such as adding, removing, and aditting
+*either
+* with the mouse via control points (CPs) or via properties.
+*
+* The shapes operate in two coordinate systems:
+* 1. 'Real' or logical coordinates
+* 2. Transformed screen coordinates
+*
+* Shape2DCollection must know the boundaries of the drawing area in logical and
+*transformed screen coords.
+* They are set by calling setWindow(...) method. The first argument is the
+*logical drawing rectangle and
+* the second one is the corresponding screen viewport in pixels. The individual
+*shapes draw themselves in the
+* logical coords and unaware of the screen ones at all. If the size of the
+*screen/widget changes setWindow
+* must be called again. Changing the logical drawing bounds translates and zooms
+*the picture.
+* The transformation is done by Qt's QTransform object.
+*/
+class Shape2DCollection : public QObject, public Shape2D {
+  Q_OBJECT
+public:
+  Shape2DCollection();
+  ~Shape2DCollection() override;
+  Shape2D *clone() const override { return NULL; }
+  void setWindow(const RectF &surface, const QRect &viewport) const;
+  void draw(QPainter &painter) const override;
+  virtual void addShape(Shape2D *, bool slct = false);
+  virtual void removeShape(Shape2D *, bool sendSignal = true);
+  virtual void removeShapes(const QList<Shape2D *> &);
+  virtual void clear();
+
+  void keyPressEvent(QKeyEvent *);
+
+  bool selectAtXY(int x, int y, bool edit = true);
+  void deselectAtXY(int x, int y);
+  bool selectIn(const QRect &rect);
+  void removeCurrentShape();
+  bool isEmpty() const { return m_shapes.isEmpty(); }
+  size_t size() const { return static_cast<size_t>(m_shapes.size()); }
+  void addToSelection(int i);
+  bool hasSelection() const;
+
+  RectF getCurrentBoundingRect() const;
+  void setCurrentBoundingRect(const RectF &rect);
+  // double properties
+  QStringList getCurrentDoubleNames() const;
+  double getCurrentDouble(const QString &prop) const;
+  void setCurrentDouble(const QString &prop, double value);
+  // QPointF properties
+  QStringList getCurrentPointNames() const;
+  QPointF getCurrentPoint(const QString &prop) const;
+  void setCurrentPoint(const QString &prop, const QPointF &value);
+
+  using Shape2D::isMasked; // Unhide base class method (avoids Intel compiler
+                           // warning)
+  // is a point in real space masked by any of the shapes
+  bool isMasked(double x, double y) const;
+  // collect all screen pixels that are masked by the shapes
+  QList<QPoint> getMaskedPixels() const;
+
+  // set the bounding rect of the current shape such that its real rect is given
+  // by the argument
+  void setCurrentBoundingRectReal(const QRectF &rect);
+
+  /// Change border color of all shapes.
+  void changeBorderColor(const QColor &color);
+
+signals:
+
+  void shapeCreated();
+  void shapeSelected();
+  void shapesDeselected();
+  void shapesRemoved();
+  void shapeChanged();
+  void shapeChangeFinished();
+  void cleared();
+
+public slots:
+  void addShape(const QString &type, int x, int y, const QColor &borderColor,
+                const QColor &fillColor);
+  void addFreeShape(const QPolygonF &, const QColor &borderColor,
+                    const QColor &fillColor);
+  void deselectAll();
+  void moveRightBottomTo(int, int);
+  void selectShapeOrControlPointAt(int x, int y);
+  void addToSelectionShapeAt(int x, int y);
+  void moveShapeOrControlPointBy(int dx, int dy);
+  void touchShapeOrControlPointAt(int x, int y);
+  void removeSelectedShapes();
+  void restoreOverrideCursor();
+  void drawFree(const QPolygonF &polygon);
+  void eraseFree(const QPolygonF &polygon);
+
+protected:
+  void drawShape(QPainter &) const override {} // never called
+  void addToPath(QPainterPath &) const override {}
+  void refit() override;
+  void resetBoundingRect() override;
+
+  Shape2D *createShape(const QString &type, int x, int y) const;
+  bool selectControlPointAt(int x, int y);
+  void deselectControlPoint();
+  bool isOverCurrentAt(int x, int y);
+  bool isOverSelectionAt(int x, int y);
+  void addToSelection(Shape2D *shape);
+  void removeFromSelection(Shape2D *shape);
+  void edit(Shape2D *shape);
+  void finishEdit();
+  QList<Shape2D *> getSelectedShapes() const { return m_selectedShapes; }
+
+  QList<Shape2D *> m_shapes;
+  mutable RectF
+      m_surfaceRect; ///< original surface window in "real" coordinates
+  mutable double m_wx, m_wy;
+  mutable int m_h;                ///< original screen viewport height
+  mutable QRect m_viewport;       ///< current screen viewport
+  mutable QTransform m_transform; ///< current transform
+
+  Shape2D *m_currentShape; ///< shape selected to edit (change size/shape)
+  size_t m_currentCP;      ///< control point of m_currentShape selected to edit
+  QList<Shape2D *>
+      m_selectedShapes; ///< A list of selected shapes (can be moved or deleted)
+  bool m_overridingCursor;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*MANTIDPLOT_SHAPE2DCOLLECTION_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SimpleWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SimpleWidget.h
index 816d63ebbe5aa235cde66ce427b1d1070b97fe95..4b29450cb1616f8ef2c4b92965915d9b8b72ff5f 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SimpleWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/SimpleWidget.h
@@ -5,46 +5,44 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		class ProjectionSurface;
+class ProjectionSurface;
 
-		/**
-		* A simple widget for drawing unwrapped instrument images.
-		*/
-		class SimpleWidget : public QWidget
-		{
-		public:
-			/// Constructor
-			explicit SimpleWidget(QWidget *parent);
-                        ~SimpleWidget() override;
-                        /// Assign a surface to draw on
-			void setSurface(boost::shared_ptr<ProjectionSurface> surface);
-			/// Return the surface
-			boost::shared_ptr<ProjectionSurface> getSurface() { return m_surface; }
-			/// Redraw the view
-			void updateView(bool picking = true);
-			/// Update the detector information (count values) and redraw
-			void updateDetectors();
-			/// Save the image into a file
-			void saveToFile(const QString & filename);
-		protected:
-                  void paintEvent(QPaintEvent *) override;
-                  void resizeEvent(QResizeEvent *) override;
-                  void mousePressEvent(QMouseEvent *) override;
-                  void mouseMoveEvent(QMouseEvent *) override;
-                  void mouseReleaseEvent(QMouseEvent *) override;
-                  void wheelEvent(QWheelEvent *) override;
-                  void keyPressEvent(QKeyEvent *) override;
-                  void enterEvent(QEvent *) override;
-                  void leaveEvent(QEvent *) override;
-                        ///< The projection surface
-			boost::shared_ptr<ProjectionSurface> m_surface;
-		};
-	}//MantidWidgets
-}//MantidQt
+/**
+* A simple widget for drawing unwrapped instrument images.
+*/
+class SimpleWidget : public QWidget {
+public:
+  /// Constructor
+  explicit SimpleWidget(QWidget *parent);
+  ~SimpleWidget() override;
+  /// Assign a surface to draw on
+  void setSurface(boost::shared_ptr<ProjectionSurface> surface);
+  /// Return the surface
+  boost::shared_ptr<ProjectionSurface> getSurface() { return m_surface; }
+  /// Redraw the view
+  void updateView(bool picking = true);
+  /// Update the detector information (count values) and redraw
+  void updateDetectors();
+  /// Save the image into a file
+  void saveToFile(const QString &filename);
+
+protected:
+  void paintEvent(QPaintEvent *) override;
+  void resizeEvent(QResizeEvent *) override;
+  void mousePressEvent(QMouseEvent *) override;
+  void mouseMoveEvent(QMouseEvent *) override;
+  void mouseReleaseEvent(QMouseEvent *) override;
+  void wheelEvent(QWheelEvent *) override;
+  void keyPressEvent(QKeyEvent *) override;
+  void enterEvent(QEvent *) override;
+  void leaveEvent(QEvent *) override;
+  ///< The projection surface
+  boost::shared_ptr<ProjectionSurface> m_surface;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif // SIMPLEWIDGET_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UCorrectionDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UCorrectionDialog.h
index 2f069fbca2ece3cee93ce2c0df3658287c361eec..5ef0c9da5a9c696910e78b7209ec7cb1c1f2e744 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UCorrectionDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UCorrectionDialog.h
@@ -5,28 +5,26 @@
 #include <QPointF>
 
 namespace Ui {
-    class UCorrectionDialog;
+class UCorrectionDialog;
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		class UCorrectionDialog : public QDialog {
-			Q_OBJECT
-		public:
-			UCorrectionDialog(QWidget *parent, QPointF oldValue, bool isManual);
-                        ~UCorrectionDialog() override;
+class UCorrectionDialog : public QDialog {
+  Q_OBJECT
+public:
+  UCorrectionDialog(QWidget *parent, QPointF oldValue, bool isManual);
+  ~UCorrectionDialog() override;
 
-                        bool applyCorrection() const;
-			QPointF getValue() const;
+  bool applyCorrection() const;
+  QPointF getValue() const;
 
-		private:
-			Ui::UCorrectionDialog *ui;
-		};
+private:
+  Ui::UCorrectionDialog *ui;
+};
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
 
 #endif // REMOVEERRORSDIALOG_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedCylinder.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedCylinder.h
index 25981ee233bfa58680708f48a5e96437d5653639..3452806b4e9313681b2fb0713fdd72d5c08f7a3b 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedCylinder.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedCylinder.h
@@ -3,30 +3,25 @@
 
 #include "RotationSurface.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		/**
-		* Implementation of UnwrappedSurface as a cylinder
-		*/
-		class UnwrappedCylinder : public RotationSurface
-		{
-		public:
-			UnwrappedCylinder(const InstrumentActor *rootActor,
-				const Mantid::Kernel::V3D &origin,
-				const Mantid::Kernel::V3D &axis);
-
-		protected:
-                  void project(const Mantid::Kernel::V3D &pos, double &u,
-                               double &v, double &uscale,
-                               double &vscale) const override;
-                  void rotate(const UnwrappedDetector &udet,
-                              Mantid::Kernel::Quat &R) const override;
-                };
-	}//MantidWidgets
-}//MantidQt
+/**
+* Implementation of UnwrappedSurface as a cylinder
+*/
+class UnwrappedCylinder : public RotationSurface {
+public:
+  UnwrappedCylinder(const InstrumentActor *rootActor,
+                    const Mantid::Kernel::V3D &origin,
+                    const Mantid::Kernel::V3D &axis);
 
+protected:
+  void project(const Mantid::Kernel::V3D &pos, double &u, double &v,
+               double &uscale, double &vscale) const override;
+  void rotate(const UnwrappedDetector &udet,
+              Mantid::Kernel::Quat &R) const override;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif // UNWRAPPEDCYLINDER_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSphere.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSphere.h
index 39fc5c7084ca7a28e74521b721d012dca5a59045..a0aa42826363173c7316f2dce0d991535b836cc3 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSphere.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSphere.h
@@ -3,31 +3,26 @@
 
 #include "RotationSurface.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		/**
-		* Implementation of UnwrappedSurface as a cylinder
-		*/
-		class UnwrappedSphere : public RotationSurface
-		{
-		public:
-			UnwrappedSphere(const InstrumentActor *rootActor,
-				const Mantid::Kernel::V3D &origin,
-				const Mantid::Kernel::V3D &axis);
+/**
+* Implementation of UnwrappedSurface as a cylinder
+*/
+class UnwrappedSphere : public RotationSurface {
+public:
+  UnwrappedSphere(const InstrumentActor *rootActor,
+                  const Mantid::Kernel::V3D &origin,
+                  const Mantid::Kernel::V3D &axis);
 
-		protected:
-                  void rotate(const UnwrappedDetector &udet,
-                              Mantid::Kernel::Quat &R) const override;
-                  void project(const Mantid::Kernel::V3D &pos, double &u,
-                               double &v, double &uscale,
-                               double &vscale) const override;
-                };
-
-	}//MantidWidgets
-}//MantidQt
+protected:
+  void rotate(const UnwrappedDetector &udet,
+              Mantid::Kernel::Quat &R) const override;
+  void project(const Mantid::Kernel::V3D &pos, double &u, double &v,
+               double &uscale, double &vscale) const override;
+};
 
+} // MantidWidgets
+} // MantidQt
 
 #endif // UNWRAPPEDSPHERE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSurface.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSurface.h
index e3375a8d5e88bc741e0901da9bc3b92ce3af5b72..2d51cec021f5630f86b50924e8b20f770a2b025a 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSurface.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/UnwrappedSurface.h
@@ -15,183 +15,185 @@
 #include <QMap>
 #include <QPainter>
 
-namespace Mantid{
-  namespace Geometry{
-    class IDetector;
-  }
-  namespace API{
-    class IPeaksWorkspace;
-  }
+namespace Mantid {
+namespace Geometry {
+class IDetector;
+}
+namespace API {
+class IPeaksWorkspace;
+}
 }
 
 class GLColor;
 class QGLWidget;
 class GL3DWidget;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-
-		/**
-		\class UnwrappedDetector
-		\brief Class helper for drawing detectors on unwraped surfaces
-		\date 15 Nov 2010
-		\author Roman Tolchenov, Tessella plc
-
-		This class keeps information used to draw a detector on an unwrapped surface.
-
-		*/
-		class UnwrappedDetector
-		{
-		public:
-			UnwrappedDetector();
-			UnwrappedDetector(const unsigned char* c,
-				boost::shared_ptr<const Mantid::Geometry::IDetector> det
-				);
-			UnwrappedDetector(const UnwrappedDetector & other);
-			UnwrappedDetector & operator=(const UnwrappedDetector & other);
-			unsigned char color[3]; ///< red, green, blue colour components (0 - 255)
-			double u;      ///< horizontal "unwrapped" coordinate
-			double v;      ///< vertical "unwrapped" coordinate
-			double width;  ///< detector width in units of u
-			double height; ///< detector height in units of v
-			double uscale; ///< scaling factor in u direction
-			double vscale; ///< scaling factor in v direction
-			Mantid::Geometry::IDetector_const_sptr detector;
-		};
-
-		/**
-		* @class UnwrappedSurface
-		* @brief Performs projection of an instrument onto a 2D surface and unwrapping it into a plane. Draws the resulting image
-		*        on the screen.
-		* @author Roman Tolchenov, Tessella plc
-		* @date 18 Nov 2010
-		*
-		* Inherited classes must implement methods:
-		*
-		*   project(...)
-		*   rotate(...)
-		*   init()
-		*
-		* In init() the implementation must set values for:
-		*
-		*   m_u_min, m_u_max, m_v_min, m_v_max, m_height_max, m_width_max, m_viewRect,
-		*   m_unwrappedDetectors, m_assemblies
-		*
-		*/
-
-		class UnwrappedSurface : public ProjectionSurface
-		{
-			Q_OBJECT
-		public:
-			explicit UnwrappedSurface(const InstrumentActor *rootActor);
-
-			/** @name Implemented public virtual methods */
-			//@{
-                        void componentSelected(
-                            Mantid::Geometry::ComponentID = NULL) override;
-                        void getSelectedDetectors(QList<int> &dets) override;
-                        void
-                        getMaskedDetectors(QList<int> &dets) const override;
-                        void setPeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws);
-                        QString getInfoText() const override;
-                        RectF getSurfaceBounds() const override;
-                        //@}
-
-			/** @name New public virtual methods */
-			//@{
-			/**
-			* Project a point in the 3D space onto the surface. The method returns the u- and v- coordinates of the projection
-			* as well as the scaling factors along the u and v axes. The scaling factors help to draw an approximate projection
-			* of a 3D object on the surface which is an orthographic projection of the object onto the tagent plane to the
-			* surface at point (uv) and scaled along u and v by the corresponding factor.
-			*
-			* @param pos :: A position of a 3D point.
-			* @param u (output) :: u-coordinate of the projection.
-			* @param v (output) :: v-coordinate of the projection.
-			* @param uscale (output) :: The scaling factor along the u-coordinate.
-			* @param vscale (output) :: The scaling factor along the v-coordinate.
-			*/
-			virtual void project(const Mantid::Kernel::V3D & pos, double & u, double & v, double & uscale, double & vscale) const = 0;
-			//@}
-
-			/** @name Public methods */
-			//@{
-			/// Toggle between the normal view and the "filpped" view (from behind)
-			void setFlippedView(bool on);
-			/// Is the surface showing the flipped view?
-			bool isFlippedView() const { return m_flippedView; }
-			/// Zoom into an area of the screen
-			void zoom(const QRectF& area);
-			//@}
-
-			protected slots:
-
-			/// Zoom into the area returned by selectionRectUV()
-			void zoom();
-			/// Unzoom view to the previous zoom area or to full view
-			void unzoom();
-
-		protected:
-
-			/** @name Implemented protected virtual methods */
-			//@{
-                  void drawSurface(MantidGLWidget *widget,
-                                   bool picking = false) const override;
-                  void drawSimpleToImage(QImage *image,
-                                         bool picking = false) const override;
-                  void changeColorMap() override;
-                        //@}
-
-			/** @name New protected virtual methods */
-			//@{
-			/**
-			* Calculate a rotation needed to see a detector from the correct angle on the surface.
-			* The rotation should be such that the detector is seen from the tip of the normal
-			* to the surface at the detector's position.
-			* @param udet :: A detector.
-			* @param R :: The result rotaion.
-			*/
-			virtual void rotate(const UnwrappedDetector& udet, Mantid::Kernel::Quat& R)const = 0;
-			virtual void calcUV(UnwrappedDetector& udet, Mantid::Kernel::V3D & pos);
-			virtual void calcSize(UnwrappedDetector& udet);
-			virtual QString getDimInfo() const;
-			/// Called in non-picking drawSimpleToImage to draw something other than detectors
-			/// Useful for debuging
-			virtual void drawCustom(QPainter*) const {}
-			//@}
-
-			/** @name Protected methods */
-			//@{
-			void setColor(int index, bool picking)const;
-			void calcAssemblies(const Mantid::Geometry::IComponent * comp, const QRectF& compRect);
-			void cacheAllAssemblies();
-			void createPeakShapes(const QRect& viewport)const;
-			//@}
-
-			double m_u_min;       ///< Minimum u
-			double m_u_max;       ///< Maximum u
-			double m_v_min;       ///< Minimum v
-			double m_v_max;       ///< Maximum v
-			double m_height_max;  ///< Maximum detector height
-			double m_width_max;   ///< Maximum detector width
-
-									/// Info needed to draw detectors onto unwrapped image
-			std::vector<UnwrappedDetector> m_unwrappedDetectors;
-
-			/// Bounding rectangles of detector assemblies
-			QMap<Mantid::Geometry::ComponentID, QRectF> m_assemblies;
-
-			bool m_flippedView; ///< if false the image is seen from the sample. if true the view is looking towards the sample.
-			mutable bool m_startPeakShapes; ///< set to true to start creating m_peakShapes from m_peaksWorkspace, return to false after creation
-
-											/// Zoom stack
-			QStack<RectF> m_zoomStack;
-		};
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+\class UnwrappedDetector
+\brief Class helper for drawing detectors on unwraped surfaces
+\date 15 Nov 2010
+\author Roman Tolchenov, Tessella plc
+
+This class keeps information used to draw a detector on an unwrapped surface.
+
+*/
+class UnwrappedDetector {
+public:
+  UnwrappedDetector();
+  UnwrappedDetector(const unsigned char *c,
+                    boost::shared_ptr<const Mantid::Geometry::IDetector> det);
+  UnwrappedDetector(const UnwrappedDetector &other);
+  UnwrappedDetector &operator=(const UnwrappedDetector &other);
+  unsigned char color[3]; ///< red, green, blue colour components (0 - 255)
+  double u;               ///< horizontal "unwrapped" coordinate
+  double v;               ///< vertical "unwrapped" coordinate
+  double width;           ///< detector width in units of u
+  double height;          ///< detector height in units of v
+  double uscale;          ///< scaling factor in u direction
+  double vscale;          ///< scaling factor in v direction
+  Mantid::Geometry::IDetector_const_sptr detector;
+};
+
+/**
+* @class UnwrappedSurface
+* @brief Performs projection of an instrument onto a 2D surface and unwrapping
+*it into a plane. Draws the resulting image
+*        on the screen.
+* @author Roman Tolchenov, Tessella plc
+* @date 18 Nov 2010
+*
+* Inherited classes must implement methods:
+*
+*   project(...)
+*   rotate(...)
+*   init()
+*
+* In init() the implementation must set values for:
+*
+*   m_u_min, m_u_max, m_v_min, m_v_max, m_height_max, m_width_max, m_viewRect,
+*   m_unwrappedDetectors, m_assemblies
+*
+*/
+
+class UnwrappedSurface : public ProjectionSurface {
+  Q_OBJECT
+public:
+  explicit UnwrappedSurface(const InstrumentActor *rootActor);
+
+  /** @name Implemented public virtual methods */
+  //@{
+  void componentSelected(Mantid::Geometry::ComponentID = NULL) override;
+  void getSelectedDetectors(QList<int> &dets) override;
+  void getMaskedDetectors(QList<int> &dets) const override;
+  void setPeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws);
+  QString getInfoText() const override;
+  RectF getSurfaceBounds() const override;
+  //@}
+
+  /** @name New public virtual methods */
+  //@{
+  /**
+  * Project a point in the 3D space onto the surface. The method returns the u-
+  *and v- coordinates of the projection
+  * as well as the scaling factors along the u and v axes. The scaling factors
+  *help to draw an approximate projection
+  * of a 3D object on the surface which is an orthographic projection of the
+  *object onto the tagent plane to the
+  * surface at point (uv) and scaled along u and v by the corresponding factor.
+  *
+  * @param pos :: A position of a 3D point.
+  * @param u (output) :: u-coordinate of the projection.
+  * @param v (output) :: v-coordinate of the projection.
+  * @param uscale (output) :: The scaling factor along the u-coordinate.
+  * @param vscale (output) :: The scaling factor along the v-coordinate.
+  */
+  virtual void project(const Mantid::Kernel::V3D &pos, double &u, double &v,
+                       double &uscale, double &vscale) const = 0;
+  //@}
+
+  /** @name Public methods */
+  //@{
+  /// Toggle between the normal view and the "filpped" view (from behind)
+  void setFlippedView(bool on);
+  /// Is the surface showing the flipped view?
+  bool isFlippedView() const { return m_flippedView; }
+  /// Zoom into an area of the screen
+  void zoom(const QRectF &area);
+  //@}
+
+protected slots:
+
+  /// Zoom into the area returned by selectionRectUV()
+  void zoom();
+  /// Unzoom view to the previous zoom area or to full view
+  void unzoom();
+
+protected:
+  /** @name Implemented protected virtual methods */
+  //@{
+  void drawSurface(MantidGLWidget *widget, bool picking = false) const override;
+  void drawSimpleToImage(QImage *image, bool picking = false) const override;
+  void changeColorMap() override;
+  //@}
+
+  /** @name New protected virtual methods */
+  //@{
+  /**
+  * Calculate a rotation needed to see a detector from the correct angle on the
+  * surface.
+  * The rotation should be such that the detector is seen from the tip of the
+  * normal
+  * to the surface at the detector's position.
+  * @param udet :: A detector.
+  * @param R :: The result rotaion.
+  */
+  virtual void rotate(const UnwrappedDetector &udet,
+                      Mantid::Kernel::Quat &R) const = 0;
+  virtual void calcUV(UnwrappedDetector &udet, Mantid::Kernel::V3D &pos);
+  virtual void calcSize(UnwrappedDetector &udet);
+  virtual QString getDimInfo() const;
+  /// Called in non-picking drawSimpleToImage to draw something other than
+  /// detectors
+  /// Useful for debuging
+  virtual void drawCustom(QPainter *) const {}
+  //@}
+
+  /** @name Protected methods */
+  //@{
+  void setColor(int index, bool picking) const;
+  void calcAssemblies(const Mantid::Geometry::IComponent *comp,
+                      const QRectF &compRect);
+  void cacheAllAssemblies();
+  void createPeakShapes(const QRect &viewport) const;
+  //@}
+
+  double m_u_min;      ///< Minimum u
+  double m_u_max;      ///< Maximum u
+  double m_v_min;      ///< Minimum v
+  double m_v_max;      ///< Maximum v
+  double m_height_max; ///< Maximum detector height
+  double m_width_max;  ///< Maximum detector width
+
+  /// Info needed to draw detectors onto unwrapped image
+  std::vector<UnwrappedDetector> m_unwrappedDetectors;
+
+  /// Bounding rectangles of detector assemblies
+  QMap<Mantid::Geometry::ComponentID, QRectF> m_assemblies;
+
+  bool m_flippedView; ///< if false the image is seen from the sample. if true
+  /// the view is looking towards the sample.
+  mutable bool m_startPeakShapes; ///< set to true to start creating
+  /// m_peakShapes from m_peaksWorkspace, return
+  /// to false after creation
+
+  /// Zoom stack
+  QStack<RectF> m_zoomStack;
+};
+
+} // MantidWidgets
+} // MantidQt
 
 #endif // UNWRAPPEDSURFACE_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Viewport.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Viewport.h
index 97380f9b6ab96d514fd3b9b22331ef102538924e..5598b2a2c28a62c989d80a76815f278971fa9cbe 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Viewport.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/Viewport.h
@@ -4,154 +4,169 @@
 #include "MantidKernel/V3D.h"
 #include "MantidKernel/Quat.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-
-		/**
-		\class  Viewport
-		\brief  class handling OpenGL Viewport
-		\author Chapon Laurent & Srikanth Nagella
-		\date   August 2008
-		\author Roman Tolchenov
-		\date   March 2013
-		\version 1.0
-
-		Viewport sets up OpenGL projection (orthographic or perspective) and privides methods for
-		navigating around a 3D scene. With the orthographic projection it rotates, scales and translates
-		the scene in plane parallel to the screen. Navigation in the persective projection isn't fully
-		implemented.
-
-		A Viewport is initialized with the size of a GL widget it will be used with. When the widget is
-		resized the viewport must also be resized by calling resize() method.
-
-		The projection type must be set along with the dimensions of the scene by calling
-		setProjection(...) method. This method doesn't issue any GL commands only sets the projection type.
-
-		Call applyProjection() to issue the GL projection command and applyRotation() to apply the
-		transformation to the model.
-
-		*/
-		class Viewport
-		{
-		public:
-			enum ProjectionType { ORTHO, PERSPECTIVE };
-			Viewport(int w, int h); ///< Constructor with Width (w) and Height(h) as inputs
-									/// Called by the display device when viewport is resized
-			void resize(int, int);
-			/// Get the viewport width and height.
-			void getViewport(int& w, int& h) const;
-			/// Return the projection type.
-			ProjectionType getProjectionType()const;
-			/// Set a projection.
-			void setProjection(double, double, double, double, double, double, ProjectionType type = Viewport::ORTHO);
-			/// Set a projection.
-			void setProjection(const Mantid::Kernel::V3D& minBounds, const Mantid::Kernel::V3D& maxBounds, ProjectionType type = Viewport::ORTHO);
-			/// Apply the projection to OpenGL engine
-			void applyProjection() const;
-			/// Rotate the model
-			void applyRotation() const;
-			/// Clear all transforamtions (rotation, translation. scaling)
-			void reset();
-
-			/* Rotation */
-
-			/// Call to set the View to X+ direction
-			void setViewToXPositive();
-			/// Call to set the View to Y+ direction
-			void setViewToYPositive();
-			/// Call to set the View to Z+ direction
-			void setViewToZPositive();
-			/// Call to set the View to X- direction
-			void setViewToXNegative();
-			/// Call to set the View to Y- direction
-			void setViewToYNegative();
-			/// Call to set the View to Z- direction
-			void setViewToZNegative();
-
-			/// Init rotation at a point on the screen
-			void initRotationFrom(int a, int b);
-			/// Generate a new rotation matrix
-			void generateRotationTo(int a, int b);
-			/// Set rotation programmatically
-			void setRotation(const Mantid::Kernel::Quat& rot);
-			/// Get current rotation
-			Mantid::Kernel::Quat getRotation() const { return m_quaternion; }
-
-			/* Zooming */
-
-			/// Init zooming with a point on the screen
-			void initZoomFrom(int a, int b);
-			/// Generate new zooming factor
-			void generateZoomTo(int a, int b);
-			/// Generate zooming factor using mouse wheel
-			void wheelZoom(int a, int b, int d);
-			/// Set zoom programmatically
-			void setZoom(double zoom);
-
-			/* Translation */
-
-			/// Call when the mouse button is pressed to start translation
-			void initTranslateFrom(int, int);
-			/// Call when the mouse is moving during a translation
-			void generateTranslationTo(int, int);
-			/// Set translation programmatically
-			void setTranslation(double, double);
-
-			// void getProjection(double&,double&,double&,double&,double&,double&);
-			void getInstantProjection(double&, double&, double&, double&, double&, double&)const;
-
-			/// Apply the transformation to a vector 
-			void transform(Mantid::Kernel::V3D& pos) const;
-
-		protected:
-			/// Correct for aspect ratio
-			void correctForAspectRatioAndZoom(double& xmin, double& xmax, double& ymin, double& ymax, double& zmin, double& zmax)const;
-			/// Project a point onto a sphere centered at rotation point
-			void projectOnSphere(int a, int b, Mantid::Kernel::V3D& point) const;
-			/// Generate a 3D point coordinates from coordinates on the viewport.
-			void generateTranslationPoint(int x, int y, Mantid::Kernel::V3D& p) const;
-
-			/* Projection */
-
-			ProjectionType m_projectionType; ///< Type of display projection
-			int m_width;       ///< Width of the viewport in pixels
-			int m_height;      ///< Height of the viewport in pixels
-			double m_left;     ///< Ortho/Prespective Projection xmin value (Left side of the x axis)
-			double m_right;    ///< Ortho/Prespective Projection xmax value (Right side of the x axis)
-			double m_bottom;   ///< Ortho/Prespective Projection ymin value (Bottom side of the y axis)
-			double m_top;      ///< Ortho/Prespective Projection ymax value (Top side of the y axis)
-			double m_near;     ///< Ortho/Prespective Projection zmin value (Near side of the z axis)
-			double m_far;      ///< Ortho/Prespective Projection zmax value (Far side of the z axis)
-
-								/* Trackball rotation */
-
-								/// Previous point selected on sphere
-			Mantid::Kernel::V3D m_lastpoint;
-			/// Rotation matrix stored as a quaternion
-			Mantid::Kernel::Quat m_quaternion;
-			/// Rotation matrix (4x4 stored as linear array) used in OpenGL
-			mutable double m_rotationmatrix[16];
-			/// Rotation speed of the trackball
-			double m_rotationspeed;
-
-			/* Zooming */
-
-			double m_zoomFactor;
-
-			/* Translation */
-
-			/// Translation in x direction 
-			double m_xTrans;
-			/// Translation in y direction 
-			double m_yTrans;
-			/// Translation in z direction 
-			mutable double m_zTrans;
-
-		};
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+\class  Viewport
+\brief  class handling OpenGL Viewport
+\author Chapon Laurent & Srikanth Nagella
+\date   August 2008
+\author Roman Tolchenov
+\date   March 2013
+\version 1.0
+
+Viewport sets up OpenGL projection (orthographic or perspective) and privides
+methods for
+navigating around a 3D scene. With the orthographic projection it rotates,
+scales and translates
+the scene in plane parallel to the screen. Navigation in the persective
+projection isn't fully
+implemented.
+
+A Viewport is initialized with the size of a GL widget it will be used with.
+When the widget is
+resized the viewport must also be resized by calling resize() method.
+
+The projection type must be set along with the dimensions of the scene by
+calling
+setProjection(...) method. This method doesn't issue any GL commands only sets
+the projection type.
+
+Call applyProjection() to issue the GL projection command and applyRotation() to
+apply the
+transformation to the model.
+
+*/
+class Viewport {
+public:
+  enum ProjectionType { ORTHO, PERSPECTIVE };
+  Viewport(int w,
+           int h); ///< Constructor with Width (w) and Height(h) as inputs
+                   /// Called by the display device when viewport is resized
+  void resize(int, int);
+  /// Get the viewport width and height.
+  void getViewport(int &w, int &h) const;
+  /// Return the projection type.
+  ProjectionType getProjectionType() const;
+  /// Set a projection.
+  void setProjection(double, double, double, double, double, double,
+                     ProjectionType type = Viewport::ORTHO);
+  /// Set a projection.
+  void setProjection(const Mantid::Kernel::V3D &minBounds,
+                     const Mantid::Kernel::V3D &maxBounds,
+                     ProjectionType type = Viewport::ORTHO);
+  /// Apply the projection to OpenGL engine
+  void applyProjection() const;
+  /// Rotate the model
+  void applyRotation() const;
+  /// Clear all transforamtions (rotation, translation. scaling)
+  void reset();
+
+  /* Rotation */
+
+  /// Call to set the View to X+ direction
+  void setViewToXPositive();
+  /// Call to set the View to Y+ direction
+  void setViewToYPositive();
+  /// Call to set the View to Z+ direction
+  void setViewToZPositive();
+  /// Call to set the View to X- direction
+  void setViewToXNegative();
+  /// Call to set the View to Y- direction
+  void setViewToYNegative();
+  /// Call to set the View to Z- direction
+  void setViewToZNegative();
+
+  /// Init rotation at a point on the screen
+  void initRotationFrom(int a, int b);
+  /// Generate a new rotation matrix
+  void generateRotationTo(int a, int b);
+  /// Set rotation programmatically
+  void setRotation(const Mantid::Kernel::Quat &rot);
+  /// Get current rotation
+  Mantid::Kernel::Quat getRotation() const { return m_quaternion; }
+
+  /* Zooming */
+
+  /// Init zooming with a point on the screen
+  void initZoomFrom(int a, int b);
+  /// Generate new zooming factor
+  void generateZoomTo(int a, int b);
+  /// Generate zooming factor using mouse wheel
+  void wheelZoom(int a, int b, int d);
+  /// Set zoom programmatically
+  void setZoom(double zoom);
+
+  /* Translation */
+
+  /// Call when the mouse button is pressed to start translation
+  void initTranslateFrom(int, int);
+  /// Call when the mouse is moving during a translation
+  void generateTranslationTo(int, int);
+  /// Set translation programmatically
+  void setTranslation(double, double);
+
+  // void getProjection(double&,double&,double&,double&,double&,double&);
+  void getInstantProjection(double &, double &, double &, double &, double &,
+                            double &) const;
+
+  /// Apply the transformation to a vector
+  void transform(Mantid::Kernel::V3D &pos) const;
+
+protected:
+  /// Correct for aspect ratio
+  void correctForAspectRatioAndZoom(double &xmin, double &xmax, double &ymin,
+                                    double &ymax, double &zmin,
+                                    double &zmax) const;
+  /// Project a point onto a sphere centered at rotation point
+  void projectOnSphere(int a, int b, Mantid::Kernel::V3D &point) const;
+  /// Generate a 3D point coordinates from coordinates on the viewport.
+  void generateTranslationPoint(int x, int y, Mantid::Kernel::V3D &p) const;
+
+  /* Projection */
+
+  ProjectionType m_projectionType; ///< Type of display projection
+  int m_width;                     ///< Width of the viewport in pixels
+  int m_height;                    ///< Height of the viewport in pixels
+  double m_left; ///< Ortho/Prespective Projection xmin value (Left side of the
+  /// x axis)
+  double m_right; ///< Ortho/Prespective Projection xmax value (Right side of
+  /// the x axis)
+  double m_bottom; ///< Ortho/Prespective Projection ymin value (Bottom side of
+  /// the y axis)
+  double m_top; ///< Ortho/Prespective Projection ymax value (Top side of the y
+  /// axis)
+  double m_near; ///< Ortho/Prespective Projection zmin value (Near side of the
+  /// z axis)
+  double m_far; ///< Ortho/Prespective Projection zmax value (Far side of the z
+  /// axis)
+
+  /* Trackball rotation */
+
+  /// Previous point selected on sphere
+  Mantid::Kernel::V3D m_lastpoint;
+  /// Rotation matrix stored as a quaternion
+  Mantid::Kernel::Quat m_quaternion;
+  /// Rotation matrix (4x4 stored as linear array) used in OpenGL
+  mutable double m_rotationmatrix[16];
+  /// Rotation speed of the trackball
+  double m_rotationspeed;
+
+  /* Zooming */
+
+  double m_zoomFactor;
+
+  /* Translation */
+
+  /// Translation in x direction
+  double m_xTrans;
+  /// Translation in y direction
+  double m_yTrans;
+  /// Translation in z direction
+  mutable double m_zTrans;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*VIEWPORT_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/XIntegrationControl.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/XIntegrationControl.h
index 42a5b77fb651b1ba8eab1aca0bd4c561961dbda4..16dae586c06b39c5952d5e6bea6771c772184563 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/XIntegrationControl.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/InstrumentView/XIntegrationControl.h
@@ -4,7 +4,6 @@
 #include <QFrame>
 #include <QScrollBar>
 
-
 class Instrument3DWidget;
 
 class QScrollBar;
@@ -12,82 +11,80 @@ class QPushButton;
 class QLineEdit;
 class QLabel;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
+
+class InstrumentWidget;
 
-		class InstrumentWidget;
+class XIntegrationScrollBar : public QFrame {
+  Q_OBJECT
+public:
+  explicit XIntegrationScrollBar(QWidget *parent);
+  double getMinimum() const;
+  double getMaximum() const;
+  double getWidth() const;
+  void set(double minimum, double maximum);
+signals:
+  void changed(double, double);
+  void running(double, double);
 
+protected:
+  void mouseMoveEvent(QMouseEvent *e) override;
+  void resizeEvent(QResizeEvent *e) override;
+  bool eventFilter(QObject *object, QEvent *e) override;
+  void updateMinMax();
 
-		class XIntegrationScrollBar : public QFrame
-		{
-			Q_OBJECT
-		public:
-			explicit XIntegrationScrollBar(QWidget *parent);
-			double getMinimum()const;
-			double getMaximum()const;
-			double getWidth()const;
-			void set(double minimum, double maximum);
-		signals:
-			void changed(double, double);
-			void running(double, double);
-		protected:
-                  void mouseMoveEvent(QMouseEvent *e) override;
-                  void resizeEvent(QResizeEvent *e) override;
-                  bool eventFilter(QObject *object, QEvent *e) override;
-                        void updateMinMax();
-		private:
-			int m_resizeMargin; ///< distance from the left (or right) end of the slider within which it can be resized
-			bool m_init;
-			bool m_resizingLeft;    ///< the sider is in resizing mode
-			bool m_resizingRight;    ///< the sider is in resizing mode
-			bool m_moving;      ///< the sider is in moving mode
-			bool m_changed;
-			int m_x, m_width;
-			double m_minimum;
-			double m_maximum;
-			QPushButton* m_slider;
-		};
+private:
+  int m_resizeMargin; ///< distance from the left (or right) end of the slider
+  /// within which it can be resized
+  bool m_init;
+  bool m_resizingLeft;  ///< the sider is in resizing mode
+  bool m_resizingRight; ///< the sider is in resizing mode
+  bool m_moving;        ///< the sider is in moving mode
+  bool m_changed;
+  int m_x, m_width;
+  double m_minimum;
+  double m_maximum;
+  QPushButton *m_slider;
+};
 
-		/**
-		* Implements a control for setting the x integration range
-		*/
-		class XIntegrationControl : public QFrame
-		{
-			Q_OBJECT
-		public:
-			explicit XIntegrationControl(InstrumentWidget *instrWindow);
-			void setTotalRange(double minimum, double maximum);
-			void setUnits(const QString& units);
-			void setRange(double minimum, double maximum);
-			double getMinimum()const;
-			double getMaximum()const;
-			double getWidth()const;
-		signals:
-			void changed(double, double);
-			public slots:
-			void setWholeRange();
-			private slots:
-			void sliderChanged(double, double);
-			void sliderRunning(double, double);
-			void setMinimum();
-			void setMaximum();
-		private:
-			void updateTextBoxes();
-			InstrumentWidget* m_instrWindow;
-			XIntegrationScrollBar* m_scrollBar;
-			QLineEdit* m_minText;
-			QLineEdit* m_maxText;
-			QLabel* m_units;
-			QPushButton* m_setWholeRange;
-			double m_totalMinimum;
-			double m_totalMaximum;
-			double m_minimum;
-			double m_maximum;
-		};
-	}//MantidWidgets
-}//MantidQt
+/**
+* Implements a control for setting the x integration range
+*/
+class XIntegrationControl : public QFrame {
+  Q_OBJECT
+public:
+  explicit XIntegrationControl(InstrumentWidget *instrWindow);
+  void setTotalRange(double minimum, double maximum);
+  void setUnits(const QString &units);
+  void setRange(double minimum, double maximum);
+  double getMinimum() const;
+  double getMaximum() const;
+  double getWidth() const;
+signals:
+  void changed(double, double);
+public slots:
+  void setWholeRange();
+private slots:
+  void sliderChanged(double, double);
+  void sliderRunning(double, double);
+  void setMinimum();
+  void setMaximum();
 
+private:
+  void updateTextBoxes();
+  InstrumentWidget *m_instrWindow;
+  XIntegrationScrollBar *m_scrollBar;
+  QLineEdit *m_minText;
+  QLineEdit *m_maxText;
+  QLabel *m_units;
+  QPushButton *m_setWholeRange;
+  double m_totalMinimum;
+  double m_totalMaximum;
+  double m_minimum;
+  double m_maximum;
+};
+} // MantidWidgets
+} // MantidQt
 
 #endif /*XINTEGRATIONCONTROL_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/LineEditWithClear.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/LineEditWithClear.h
index 1789c91c110d5255c85f9895ac9afbcbed2d714f..18e9cdf4a4308bdaf4d2813ec69690d6842e31c1 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/LineEditWithClear.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/LineEditWithClear.h
@@ -16,30 +16,25 @@
 
 class QToolButton;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS LineEditWithClear : public QLineEdit
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS LineEditWithClear : public QLineEdit {
+  Q_OBJECT
 
 public:
-    LineEditWithClear(QWidget *parent = 0);
+  LineEditWithClear(QWidget *parent = 0);
 
 protected:
   void resizeEvent(QResizeEvent *) override;
 
 private slots:
-    void updateCloseButton(const QString &text);
+  void updateCloseButton(const QString &text);
 
 private:
-    QToolButton *clearButton;
+  QToolButton *clearButton;
 };
-
 }
-
 }
 
 #endif // LINEEDITWITHCLEAR_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
index 841269c2483ea2b3c59e67c0bce7773d067066bd..994bf5d219d445bb247a3ac463e791ddbaf94bd1 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
@@ -12,83 +12,89 @@
 //-----------------------------------------------
 // Forward declarations
 //------------------------------------------------
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class Instrument;
-  }
+namespace Mantid {
+namespace Geometry {
+class Instrument;
 }
+}
+
+namespace MantidQt {
+namespace MantidWidgets {
+//-----------------------------------------------
+// Forward declarations
+//------------------------------------------------
+class MWRunFiles;
+class DiagResults;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    //-----------------------------------------------
-    // Forward declarations
-    //------------------------------------------------
-    class MWRunFiles;
-    class DiagResults;
-    
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MWDiag : public API::MantidWidget
-    {
-      Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MWDiag : public API::MantidWidget {
+  Q_OBJECT
 
-    public:
-      /// there has to be a default constructor but you can call it with a pointer to the thing that will take ownership of it
-      MWDiag(QWidget *parent=NULL, QString prevSettingsGr="", const QComboBox * const instru = NULL);
-      QString run(const QString &outWS = "", const bool saveSettings = true);
-      void loadSettings();
+public:
+  /// there has to be a default constructor but you can call it with a pointer
+  /// to the thing that will take ownership of it
+  MWDiag(QWidget *parent = NULL, QString prevSettingsGr = "",
+         const QComboBox *const instru = NULL);
+  QString run(const QString &outWS = "", const bool saveSettings = true);
+  void loadSettings();
 
-    public slots:
-      /// Update the sum state
-      void setSumState(bool checked);
+public slots:
+  /// Update the sum state
+  void setSumState(bool checked);
 
-    private:
-      /// The form generated by Qt Designer
-      Ui::MWDiag m_designWidg;
-      /// check if ==NULL before use, set to point to the results dialog box which is deleted when it's closed!
-      mutable DiagResults *m_dispDialog;
-      /// points to the control with the user selected instrument
-      const QComboBox * const m_instru;
-      /// true if either of the TOF windows have been changed by the user, otherwise false
-      bool m_TOFChanged;
-      /// time of flight value for the start of the background window that was set through the update??? or -1 if no value was sent through
-      double m_sTOFAutoVal;
-      /// time of flight value for the end of the background window that was set through the update??? or -1 if no value was sent through
-      double m_eTOFAutoVal;
-      /// the name of the output workspace that contains many of the results from these tests
-      QString m_outputWS;
-      /// the run files that will be loaded to do the background test
-      QStringList m_monoFiles;
-      /// If true the mono files will be summed
-      bool m_sumMono;
-      /// the values on the form the last time it was SUCCESSFULLY run accessed through this object
-      QSettings m_prevSets;
+private:
+  /// The form generated by Qt Designer
+  Ui::MWDiag m_designWidg;
+  /// check if ==NULL before use, set to point to the results dialog box which
+  /// is deleted when it's closed!
+  mutable DiagResults *m_dispDialog;
+  /// points to the control with the user selected instrument
+  const QComboBox *const m_instru;
+  /// true if either of the TOF windows have been changed by the user, otherwise
+  /// false
+  bool m_TOFChanged;
+  /// time of flight value for the start of the background window that was set
+  /// through the update??? or -1 if no value was sent through
+  double m_sTOFAutoVal;
+  /// time of flight value for the end of the background window that was set
+  /// through the update??? or -1 if no value was sent through
+  double m_eTOFAutoVal;
+  /// the name of the output workspace that contains many of the results from
+  /// these tests
+  QString m_outputWS;
+  /// the run files that will be loaded to do the background test
+  QStringList m_monoFiles;
+  /// If true the mono files will be summed
+  bool m_sumMono;
+  /// the values on the form the last time it was SUCCESSFULLY run accessed
+  /// through this object
+  QSettings m_prevSets;
 
-      QString createDiagnosticScript() const;
-      void showTestResults(const QString & testSummary) const;
+  QString createDiagnosticScript() const;
+  void showTestResults(const QString &testSummary) const;
 
-      void closeDialog();
-      QString openFileDialog(const bool save, const QStringList &exts);
-      boost::shared_ptr<const Mantid::Geometry::Instrument> getInstrument(const QString & name);
-      QString getSetting(const QString & settingName, 
-       boost::shared_ptr<const Mantid::Geometry::Instrument> inst = boost::shared_ptr<const Mantid::Geometry::Instrument>(),
-       const QString & idfName = "") const;
-      void saveDefaults();
-      void setupToolTips();
-      void connectSignals(const QWidget * const parentInterface);
-      void setUpValidators();
-      bool isInputValid() const;
+  void closeDialog();
+  QString openFileDialog(const bool save, const QStringList &exts);
+  boost::shared_ptr<const Mantid::Geometry::Instrument>
+  getInstrument(const QString &name);
+  QString
+  getSetting(const QString &settingName,
+             boost::shared_ptr<const Mantid::Geometry::Instrument> inst =
+                 boost::shared_ptr<const Mantid::Geometry::Instrument>(),
+             const QString &idfName = "") const;
+  void saveDefaults();
+  void setupToolTips();
+  void connectSignals(const QWidget *const parentInterface);
+  void setUpValidators();
+  bool isInputValid() const;
 
-      private slots:
-      void browseClicked(const QString &buttonDis);
-      void updateTOFs(const double &start, const double &end);
-      void specifyRuns(const QStringList &runFileNames);
-      void TOFUpd();
-      void noDispDialog() {m_dispDialog = NULL;}
-    };
-  }
+private slots:
+  void browseClicked(const QString &buttonDis);
+  void updateTOFs(const double &start, const double &end);
+  void specifyRuns(const QStringList &runFileNames);
+  void TOFUpd();
+  void noDispDialog() { m_dispDialog = NULL; }
+};
+}
 }
 
-#endif //MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
+#endif // MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWRunFiles.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWRunFiles.h
index 96a6c63e8771ab758545f8b9f5163c87b7f1ae27..da23a5ca868e4c6b8d6ced837c4ef732314b1928 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWRunFiles.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWRunFiles.h
@@ -137,9 +137,9 @@ public:
   };
   /// Options for the live button
   enum LiveButtonOpts {
-    Hide,            ///< Don't use the live button
-    AlwaysShow,      ///< Show whether a connection is possible or not (will be
-                     ///disabled)
+    Hide,       ///< Don't use the live button
+    AlwaysShow, ///< Show whether a connection is possible or not (will be
+    /// disabled)
     ShowIfCanConnect ///< Only show if able to connect to the live data server
   };
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWView.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWView.h
index d935f264b7b01a98ea8cfe9dc6929f23b44812d7..cddfc7c946b6db588a4bab138a09be0811bf6a87 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWView.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWView.h
@@ -66,9 +66,9 @@ using MWDimension_const_sptr =
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MWView :
-  public QWidget,
-  public MantidQt::API::WorkspaceObserver {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MWView
+    : public QWidget,
+      public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 
 public:
@@ -77,7 +77,7 @@ public:
   void loadColorMap(QString filename = QString());
   void setWorkspace(Mantid::API::MatrixWorkspace_sptr ws);
   void updateDisplay();
-  SafeQwtPlot* getPlot2D();
+  SafeQwtPlot *getPlot2D();
 
 public slots:
   void colorRangeChangedSlot();
@@ -85,8 +85,9 @@ public slots:
   void setTransparentZerosSlot(bool transparent);
 
 protected:
-  void preDeleteHandle(const std::string &workspaceName,
-    const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
+  void preDeleteHandle(
+      const std::string &workspaceName,
+      const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
 
 private:
   void initLayout();
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
index 21a6fead2b61145024ebf6665f57fe45575186b1..f3b6fb5ca35417677062e70e6cf14f1ac2444215 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MantidHelpWindow.h
@@ -12,17 +12,15 @@ class QString;
 class QWidget;
 class pqHelpWindow;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MantidHelpWindow : public API::MantidHelpInterface
-{
-Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MantidHelpWindow
+    : public API::MantidHelpInterface {
+  Q_OBJECT
 
 public:
-  MantidHelpWindow(QWidget* parent=0, Qt::WindowFlags flags=0);
+  MantidHelpWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
   ~MantidHelpWindow() override;
 
   void showPage(const std::string &url = std::string()) override;
@@ -42,21 +40,21 @@ public:
 
 private:
   void showHelp(const QString &url);
-    void openWebpage(const QUrl &url);
+  void openWebpage(const QUrl &url);
 
-    /// The full path of the collection file.
-    std::string m_collectionFile;
-    /** The full path of the cache file. If it is not
-        determined this is an empty string. */
-    std::string m_cacheFile;
-    /// The window that renders the help information
-    static pqHelpWindow *g_helpWindow;
+  /// The full path of the collection file.
+  std::string m_collectionFile;
+  /** The full path of the cache file. If it is not
+      determined this is an empty string. */
+  std::string m_cacheFile;
+  /// The window that renders the help information
+  static pqHelpWindow *g_helpWindow;
 
-    /// Whether this is the very first startup of the helpwindow.
-    bool m_firstRun;
+  /// Whether this is the very first startup of the helpwindow.
+  bool m_firstRun;
 
-    void findCollectionFile(std::string & binDir);
-    void determineFileLocs();
+  void findCollectionFile(std::string &binDir);
+  void determineFileLocs();
 
 public slots:
   /// Perform any clean up on main window shutdown
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MessageDisplay.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MessageDisplay.h
index 738e87ff96447f24a3df015ed4d48b7b837bb17b..74c92ff7058cc90652dfaa04687c20d999b7132e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MessageDisplay.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MessageDisplay.h
@@ -24,121 +24,114 @@ class QShowEvent;
 class QSignalMapper;
 class QPlainTextEdit;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    using API::Message; // So that the slots work
-    //----------------------------------------------------------
-    // Forward declarations
-    //----------------------------------------------------------
+namespace MantidQt {
+namespace MantidWidgets {
+using API::Message; // So that the slots work
+                    //----------------------------------------------------------
+                    // Forward declarations
+                    //----------------------------------------------------------
 
-    /** @class MessageDisplay
-     * Provides a widget for display messages in a text box
-     * It deals with Message objects which in turn hide whether
-     * a message is a framework Poco message or a simple string.
-     * It can connect to the Mantid logging framework if required
-     */
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MessageDisplay : public QWidget
-    {
-      Q_OBJECT
-      Q_PROPERTY(QString source READ source WRITE setSource)
+/** @class MessageDisplay
+ * Provides a widget for display messages in a text box
+ * It deals with Message objects which in turn hide whether
+ * a message is a framework Poco message or a simple string.
+ * It can connect to the Mantid logging framework if required
+ */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MessageDisplay : public QWidget {
+  Q_OBJECT
+  Q_PROPERTY(QString source READ source WRITE setSource)
 
-    public:
-      /// Controls whether the display is allowed to set the log levels
-      enum LogLevelControl {
-        EnableLogLevelControl = 0,
-        DisableLogLevelControl
-      };
+public:
+  /// Controls whether the display is allowed to set the log levels
+  enum LogLevelControl { EnableLogLevelControl = 0, DisableLogLevelControl };
 
-      /// Default constructor with optional parent
-      MessageDisplay(QWidget *parent=NULL);
-      /// Constructor specifying if whether control over the global log level is allowed
-      MessageDisplay(LogLevelControl logLevelControl,
-                     QWidget *parent=NULL);
-      ///Destructor
-      ~MessageDisplay() override;
+  /// Default constructor with optional parent
+  MessageDisplay(QWidget *parent = NULL);
+  /// Constructor specifying if whether control over the global log level is
+  /// allowed
+  MessageDisplay(LogLevelControl logLevelControl, QWidget *parent = NULL);
+  /// Destructor
+  ~MessageDisplay() override;
 
-      // Setup logging framework connections
-      void attachLoggingChannel();
-      /// If set, only Mantid log messages from this source are emitted
-      void setSource(const QString & source);
-      /// Get the current source are emitted
-      inline const QString & source() const { return m_logChannel->source(); }
-      
-    signals:
-      /// Indicate that a message of error or higher has been received.
-      void errorReceived(const QString & text);
-      /// Indicate that a message of warning or higher has been received.
-      void warningReceived(const QString & text);
+  // Setup logging framework connections
+  void attachLoggingChannel();
+  /// If set, only Mantid log messages from this source are emitted
+  void setSource(const QString &source);
+  /// Get the current source are emitted
+  inline const QString &source() const { return m_logChannel->source(); }
 
-    public slots:
-      /// Convenience method for appending message at fatal level
-      void appendFatal(const QString & text);
-      /// Convenience method for appending message at error level
-      void appendError(const QString & text);
-      /// Convenience method for appending message at warning level
-      void appendWarning(const QString & text);
-      /// Convenience method for appending message at notice level
-      void appendNotice(const QString & text);
-      /// Convenience method for appending message at information level
-      void appendInformation(const QString & text);
-      /// Convenience method for appending message at debug level
-      void appendDebug(const QString & text);
-      /// Write a message after the current contents
-      void append(const Message & msg);
-      /// Replace the display text with the given contents
-      void replace(const Message & msg);
-      /// Clear all of the text
-      void clear();
-      /// Move the text cursor to after the last character
-      QTextCursor moveCursorToEnd();
-      /// Returns true if scroll-bar is at the bottom of widget
-      bool isScrollbarAtBottom() const;
-      /// Scroll to the bottom of the text
-      void scrollToTop();
-      /// Scroll to the bottom of the text
-      void scrollToBottom();
+signals:
+  /// Indicate that a message of error or higher has been received.
+  void errorReceived(const QString &text);
+  /// Indicate that a message of warning or higher has been received.
+  void warningReceived(const QString &text);
 
-    private slots:
-      /// Provide a custom context menu
-      void showContextMenu(const QPoint & event);
-      /// Set the global logging level
-      void setGlobalLogLevel(int priority);
+public slots:
+  /// Convenience method for appending message at fatal level
+  void appendFatal(const QString &text);
+  /// Convenience method for appending message at error level
+  void appendError(const QString &text);
+  /// Convenience method for appending message at warning level
+  void appendWarning(const QString &text);
+  /// Convenience method for appending message at notice level
+  void appendNotice(const QString &text);
+  /// Convenience method for appending message at information level
+  void appendInformation(const QString &text);
+  /// Convenience method for appending message at debug level
+  void appendDebug(const QString &text);
+  /// Write a message after the current contents
+  void append(const Message &msg);
+  /// Replace the display text with the given contents
+  void replace(const Message &msg);
+  /// Clear all of the text
+  void clear();
+  /// Move the text cursor to after the last character
+  QTextCursor moveCursorToEnd();
+  /// Returns true if scroll-bar is at the bottom of widget
+  bool isScrollbarAtBottom() const;
+  /// Scroll to the bottom of the text
+  void scrollToTop();
+  /// Scroll to the bottom of the text
+  void scrollToBottom();
 
-    private:
-      Q_DISABLE_COPY(MessageDisplay)
-      /// Setup the actions
-      void initActions();
-      /// Initialize the text formats
-      void initFormats();
-      /// Set the properties of the text display
-      void setupTextArea();
-      /// Return format for given log level
-      QTextCharFormat format(const API::Message::Priority priority) const;
+private slots:
+  /// Provide a custom context menu
+  void showContextMenu(const QPoint &event);
+  /// Set the global logging level
+  void setGlobalLogLevel(int priority);
 
-      /// Are we allowed to affect the log level
-      LogLevelControl m_logLevelControl;
-      /// A reference to the log channel
-      API::QtSignalChannel *m_logChannel;
-      /// A reference to the log channel
-      Poco::FilterChannel *m_filterChannel;
-      /// The actual widget holding the text
-      QPlainTextEdit * m_textDisplay;
-      /// Map priority to text formatting
-      QMap<API::Message::Priority,QTextCharFormat> m_formats;
-      /// Mutually exclusive log actions
-      QActionGroup *m_loglevels;
-      /// Map action signal to log level parameter
-      QSignalMapper *m_logLevelMapping;
-      /// Log level actions
-      QAction  *m_error,*m_warning,*m_notice, *m_information, *m_debug;
+private:
+  Q_DISABLE_COPY(MessageDisplay)
+  /// Setup the actions
+  void initActions();
+  /// Initialize the text formats
+  void initFormats();
+  /// Set the properties of the text display
+  void setupTextArea();
+  /// Return format for given log level
+  QTextCharFormat format(const API::Message::Priority priority) const;
 
-      // the name of the fliter channel
-      const std::string m_FilterChannelName = "MessageDisplayPriority";
-    };
+  /// Are we allowed to affect the log level
+  LogLevelControl m_logLevelControl;
+  /// A reference to the log channel
+  API::QtSignalChannel *m_logChannel;
+  /// A reference to the log channel
+  Poco::FilterChannel *m_filterChannel;
+  /// The actual widget holding the text
+  QPlainTextEdit *m_textDisplay;
+  /// Map priority to text formatting
+  QMap<API::Message::Priority, QTextCharFormat> m_formats;
+  /// Mutually exclusive log actions
+  QActionGroup *m_loglevels;
+  /// Map action signal to log level parameter
+  QSignalMapper *m_logLevelMapping;
+  /// Log level actions
+  QAction *m_error, *m_warning, *m_notice, *m_information, *m_debug;
 
-  }
+  // the name of the fliter channel
+  const std::string m_FilterChannelName = "MessageDisplayPriority";
+};
+}
 }
 
-#endif //MESSAGEDISPLAY_H_
+#endif // MESSAGEDISPLAY_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MultifitSetupDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MultifitSetupDialog.h
index 3ace84c4cf36a158034eb562ade78f795c978196..1d6ed6cb9c8278d86cc03d9cc59b941f73a1c3d6 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MultifitSetupDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MultifitSetupDialog.h
@@ -4,19 +4,18 @@
 #include "ui_MultifitSetupDialog.h"
 #include <QDialog>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class FitPropertyBrowser;
-/** 
+namespace MantidQt {
+namespace MantidWidgets {
+class FitPropertyBrowser;
+/**
     This is a dialog for doing setting up the MultiBG function.
-    
+
 
     @author Roman Tolchenov, Tessella plc
     @date 7/09/2011
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -34,40 +33,35 @@ namespace MantidWidgets
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class MultifitSetupDialog : public QDialog
-{
+class MultifitSetupDialog : public QDialog {
   Q_OBJECT
 
 public:
-  
   /// Default constructor
-  MultifitSetupDialog(FitPropertyBrowser* fitBrowser);
+  MultifitSetupDialog(FitPropertyBrowser *fitBrowser);
 
-  /// Returns a list of parameter ties. Empty string means no ties and parameter is local
-  QStringList getParameterTies()const{return m_ties;}
+  /// Returns a list of parameter ties. Empty string means no ties and parameter
+  /// is local
+  QStringList getParameterTies() const { return m_ties; }
 
 private slots:
 
   /// Setup the function and close dialog
   void accept() override;
-  void cellChanged(int,int);
+  void cellChanged(int, int);
 
 private:
-
   /// The form generated with Qt Designer
   Ui::MultifitSetupDialog ui;
 
   /// Pointer to the calling fit browser
-  FitPropertyBrowser* m_fitBrowser;
+  FitPropertyBrowser *m_fitBrowser;
 
   /// A list with parameter ties
   QStringList m_ties;
-
 };
-
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonFitPropertyBrowser.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonFitPropertyBrowser.h
index 22bcb74188c9de2ee04498ee4def3e8b54b1552f..c3122c5a65dc253004c1fc0d17dc369dfac1b843 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonFitPropertyBrowser.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonFitPropertyBrowser.h
@@ -15,29 +15,25 @@ class QtEnumPropertyManager;
 class QtProperty;
 class QtBrowserItem;
 
-namespace Mantid
-{
-  namespace API
-  {
-    class IFitFunction;
-    class IPeakFunction;
-    class CompositeFunction;
-  }
+namespace Mantid {
+namespace API {
+class IFitFunction;
+class IPeakFunction;
+class CompositeFunction;
+}
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 class PropertyHandler;
 
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MuonFitPropertyBrowser: public MantidQt::MantidWidgets::FitPropertyBrowser
-{  
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MuonFitPropertyBrowser
+    : public MantidQt::MantidWidgets::FitPropertyBrowser {
   Q_OBJECT
 
 public:
   /// Constructor.
-  MuonFitPropertyBrowser(QWidget *parent = NULL, QObject* mantidui = NULL);  
+  MuonFitPropertyBrowser(QWidget *parent = NULL, QObject *mantidui = NULL);
   /// Initialise the layout.
   void init() override;
   /// Set the input workspace name
@@ -61,7 +57,7 @@ protected:
 private slots:
   void doubleChanged(QtProperty *prop) override;
 
-private:  
+private:
   /// Get the registered function names
   void populateFunctionNames() override;
   /// Check if the workspace can be used in the fit
@@ -71,5 +67,4 @@ private:
 } // MantidQt
 } // API
 
-
 #endif /*MUONFITPROPERTYBROWSER_H_*/
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonSequentialFitDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonSequentialFitDialog.h
index e4424425c5a685c1d8005a5ebd039de9ee33bc45..4bed15764a7294eaa768a28667a4c232ec487e76 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonSequentialFitDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MuonSequentialFitDialog.h
@@ -9,132 +9,125 @@
 
 #include <QDialog>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  using namespace Mantid::Kernel;
-  using namespace Mantid::API;
+namespace MantidQt {
+namespace MantidWidgets {
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
 
-  /** MuonSequentialFitDialog : Dialog for running sequential fits for Muon data
+/** MuonSequentialFitDialog : Dialog for running sequential fits for Muon data
 
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
-    National Laboratory & European Spallation Source
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MuonSequentialFitDialog : public QDialog
-  {
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS MuonSequentialFitDialog
+    : public QDialog {
 
-    Q_OBJECT
+  Q_OBJECT
 
-  public:
-    MuonSequentialFitDialog(MuonFitPropertyBrowser* fitPropBrowser, Algorithm_sptr loadAlg);
-    ~MuonSequentialFitDialog() override;
+public:
+  MuonSequentialFitDialog(MuonFitPropertyBrowser *fitPropBrowser,
+                          Algorithm_sptr loadAlg);
+  ~MuonSequentialFitDialog() override;
 
-    enum DialogState 
-    {
-      Preparing,
-      Running,
-      Stopped
-    };
+  enum DialogState { Preparing, Running, Stopped };
 
-    // Prefix added to the names of the sequential fit result workspaces and groups
-    static const std::string SEQUENTIAL_PREFIX;
+  // Prefix added to the names of the sequential fit result workspaces and
+  // groups
+  static const std::string SEQUENTIAL_PREFIX;
 
-  signals:
-    void stateChanged(DialogState newState);
+signals:
+  void stateChanged(DialogState newState);
 
-  private:
+private:
+  // -- FUNCTIONS -----------------------------------------------------------
 
-    // -- FUNCTIONS -----------------------------------------------------------
+  /// Check if all the input field are valid
+  bool isInputValid();
 
-    /// Check if all the input field are valid 
-    bool isInputValid();
+  /// Set current dialog state
+  void setState(DialogState newState);
 
-    /// Set current dialog state
-    void setState(DialogState newState);
+  /// Initialize diagnosis table
+  void initDiagnosisTable();
 
-    /// Initialize diagnosis table 
-    void initDiagnosisTable();
+  /// Add a new entry to the diagnosis table
+  void addDiagnosisEntry(const std::string &runTitle, double fitQuality,
+                         IFunction_sptr fittedFunction);
 
-    /// Add a new entry to the diagnosis table 
-    void addDiagnosisEntry(const std::string& runTitle, double fitQuality,
-        IFunction_sptr fittedFunction);
+  /// Helper function to create new item for Diagnosis table
+  QTableWidgetItem *createTableWidgetItem(const QString &text);
 
-    /// Helper function to create new item for Diagnosis table
-    QTableWidgetItem* createTableWidgetItem(const QString& text);
-    
-    // -- VARIABLES -----------------------------------------------------------
+  // -- VARIABLES -----------------------------------------------------------
 
-    /// UI form
-    Ui::MuonSequentialFitDialog m_ui;
+  /// UI form
+  Ui::MuonSequentialFitDialog m_ui;
 
-    /// Fit properties browser used to start the dialog
-    MuonFitPropertyBrowser* m_fitPropBrowser;
+  /// Fit properties browser used to start the dialog
+  MuonFitPropertyBrowser *m_fitPropBrowser;
 
-    /// Current state of the dialog
-    DialogState m_state;
+  /// Current state of the dialog
+  DialogState m_state;
 
-    /// Whether user requested fitting to be stopped
-    bool m_stopRequested;
+  /// Whether user requested fitting to be stopped
+  bool m_stopRequested;
 
-    /// Algorithm the dialog should use for loading 
-    Algorithm_sptr m_loadAlg;
+  /// Algorithm the dialog should use for loading
+  Algorithm_sptr m_loadAlg;
 
-    // -- STATIC MEMBERS ------------------------------------------------------
+  // -- STATIC MEMBERS ------------------------------------------------------
 
-    /// Checks if specified name is valid as a name for label. 
-    static std::string isValidLabel(const std::string& label);
+  /// Checks if specified name is valid as a name for label.
+  static std::string isValidLabel(const std::string &label);
 
-    /// Returns displayable title for the given workspace
-    static std::string getRunTitle(Workspace_const_sptr ws);
+  /// Returns displayable title for the given workspace
+  static std::string getRunTitle(Workspace_const_sptr ws);
 
-  private slots:
-    /// Updates visibility/tooltip of label error asterisk
-    void updateLabelError(const QString& label);
+private slots:
+  /// Updates visibility/tooltip of label error asterisk
+  void updateLabelError(const QString &label);
 
-    /// Sets control button to be start/stop depending on new dialog state 
-    void updateControlButtonType(DialogState newState);
+  /// Sets control button to be start/stop depending on new dialog state
+  void updateControlButtonType(DialogState newState);
 
-    /// Update enabled state off all the input widgets depending on new dialog state
-    void updateInputEnabled(DialogState newState); 
+  /// Update enabled state off all the input widgets depending on new dialog
+  /// state
+  void updateInputEnabled(DialogState newState);
 
-    /// Update control button enabled status depending on the new state. 
-    void updateControlEnabled(DialogState newState); 
+  /// Update control button enabled status depending on the new state.
+  void updateControlEnabled(DialogState newState);
 
-    /// Update cursor depending on the new state of the dialog.
-    void updateCursor(DialogState newState); 
+  /// Update cursor depending on the new state of the dialog.
+  void updateCursor(DialogState newState);
 
-    /// Start fitting process
-    void startFit();
+  /// Start fitting process
+  void startFit();
 
-    /// Stop fitting process
-    void stopFit();
-
-    /// Run fit after getting file input
-    void continueFit();
-
-  };
+  /// Stop fitting process
+  void stopFit();
 
+  /// Run fit after getting file input
+  void continueFit();
+};
 
 } // namespace MantidWidgets
 } // namespace Mantid
 
-#endif  /* MANTID_MANTIDWIDGETS_MUONSEQUENTIALFITDIALOG_H_ */
+#endif /* MANTID_MANTIDWIDGETS_MUONSEQUENTIALFITDIALOG_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeakPicker.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeakPicker.h
index 9a96fa307b18820b0b952b07ec55acecf2fb4f74..0a9802433ea5865715f7b0bf786f59ec13349c65 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeakPicker.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeakPicker.h
@@ -10,87 +10,85 @@
 #include <qwt_plot_marker.h>
 #include <qwt_plot_picker.h>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-  /** PeakPicker : A simplified version of PeakPickerTool, available for use on general QwtPlots.
-    
-    Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** PeakPicker : A simplified version of PeakPickerTool, available for use on
+  general QwtPlots.
 
-    This file is part of Mantid.
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PeakPicker : public QwtPlotPicker, public QwtPlotItem
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    /// Constructor
-    PeakPicker(QwtPlot* plot, QColor color);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PeakPicker : public QwtPlotPicker,
+                                                     public QwtPlotItem {
+  Q_OBJECT
 
-    /// Correct QwtPlotItem type info
-    int rtti() const override { return QwtPlotItem::Rtti_PlotMarker; }
+public:
+  /// Constructor
+  PeakPicker(QwtPlot *plot, QColor color);
 
-    /// Draw the peak picker
-    /// @see QwtPlotItem::draw
-    void draw(QPainter *painter, const QwtScaleMap &xMap,
-              const QwtScaleMap &yMap, const QRect &canvasRect) const override;
+  /// Correct QwtPlotItem type info
+  int rtti() const override { return QwtPlotItem::Rtti_PlotMarker; }
 
-    /// @return Currently represented peak
-    Mantid::API::IPeakFunction_const_sptr peak() const;
+  /// Draw the peak picker
+  /// @see QwtPlotItem::draw
+  void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+            const QRect &canvasRect) const override;
 
-    /// @param peak :: New peak to represent
-    void setPeak(const Mantid::API::IPeakFunction_const_sptr& peak);
+  /// @return Currently represented peak
+  Mantid::API::IPeakFunction_const_sptr peak() const;
 
-  signals:
-    /// Emitted when the peak picker is moved or resized in any way
-    void changed();
+  /// @param peak :: New peak to represent
+  void setPeak(const Mantid::API::IPeakFunction_const_sptr &peak);
 
-  private:
-    /// Size of the dragging region. Bigger value means it's easier to hit the dragging area, though
-    /// harder to get to the right element if there are lots of them.
-    static const double DRAG_SENSITIVITY;
+signals:
+  /// Emitted when the peak picker is moved or resized in any way
+  void changed();
 
-    /// Default cursor to use when not dragging
-    static const Qt::CursorShape DEFAULT_CURSOR;
+private:
+  /// Size of the dragging region. Bigger value means it's easier to hit the
+  /// dragging area, though
+  /// harder to get to the right element if there are lots of them.
+  static const double DRAG_SENSITIVITY;
 
-    /// Event filter installed for the plot
-    bool eventFilter(QObject *object, QEvent *event) override;
+  /// Default cursor to use when not dragging
+  static const Qt::CursorShape DEFAULT_CURSOR;
 
-    /// The plot peak picker operates on
-    QwtPlot* m_plot;
+  /// Event filter installed for the plot
+  bool eventFilter(QObject *object, QEvent *event) override;
 
-    /// Pens used for drawing
-    QPen m_basePen, m_widthPen;
-
-    /// Dragging status flags
-    bool m_isMoving, m_isResizing;
-
-    /// Currently represented peak
-    Mantid::API::IPeakFunction_sptr m_peak;
-  };
+  /// The plot peak picker operates on
+  QwtPlot *m_plot;
 
+  /// Pens used for drawing
+  QPen m_basePen, m_widthPen;
 
+  /// Dragging status flags
+  bool m_isMoving, m_isResizing;
 
+  /// Currently represented peak
+  Mantid::API::IPeakFunction_sptr m_peak;
+};
 
 } // namespace MantidWidgets
 } // namespace MantidQt
 
-#endif  /* MANTIDQT_MANTIDWIDGETS_PEAKPICKER_H_ */
+#endif /* MANTIDQT_MANTIDWIDGETS_PEAKPICKER_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeriodicTableWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeriodicTableWidget.h
index 33cf613ca3bc64494fcbe0aac7dc3c63dc216479..0ee428808c5b01a8c534fbe1f2fcc6e0c8202203 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeriodicTableWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PeriodicTableWidget.h
@@ -6,38 +6,39 @@
 #include <QWidget>
 #include "ui_PeriodicTableWidget.h"
 
-  /**
-    PeriodicTableWidget: A Widget representing a colour coded Periodic Table of Elements, with corresponding buttons as the elements
+/**
+  PeriodicTableWidget: A Widget representing a colour coded Periodic Table of
+  Elements, with corresponding buttons as the elements
 
-    Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+  This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
 
 class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PeriodicTableWidget : public QWidget {
   Q_OBJECT
 
 public:
-  ///Constructor
+  /// Constructor
   PeriodicTableWidget(QWidget *parent = 0);
-  ///Destructor
+  /// Destructor
   ~PeriodicTableWidget() override{};
   /// Vectors to Hold the QPushButtons of Elements in corresponding Groups
   QVector<QPushButton *> OtherNonMetals;
@@ -53,12 +54,14 @@ public:
   QVector<QPushButton *> NobleGases;
 
   /// Vector to hold all group vectors for access to All Buttons at once
-  QVector<QVector <QPushButton *> > AllElementButtons;
+  QVector<QVector<QPushButton *>> AllElementButtons;
 
-  /// @return Comma-separated string of all the element buttons for one group that are currently checked 
+  /// @return Comma-separated string of all the element buttons for one group
+  /// that are currently checked
   QString elementsSelectedToString(QVector<QPushButton *> elementsSelected);
 
-  /// @return Comma-separated string of all element buttons that are checked in the whole PeriodicTableWidget
+  /// @return Comma-separated string of all element buttons that are checked in
+  /// the whole PeriodicTableWidget
   QString getAllCheckedElementsStr();
 
   /// Disables all buttons associated with a group.
@@ -67,33 +70,33 @@ public:
   /// Disables All buttons in periodicTableWidget.
   void disableAllElementButtons();
 
-  ///Enables a button for an element by the element name i.e 'Au' for Gold.
+  /// Enables a button for an element by the element name i.e 'Au' for Gold.
   void enableButtonByName(QString elementStr);
 
-  ///@return the result of the comparison between a string and the text of a button.
-  bool compareButtonNameToStr(QPushButton * buttonToCompare,QString stringToCompare);
+  ///@return the result of the comparison between a string and the text of a
+  /// button.
+  bool compareButtonNameToStr(QPushButton *buttonToCompare,
+                              QString stringToCompare);
 
-  ///Displays or hides the Legend for the colour coding of periodic groups
+  /// Displays or hides the Legend for the colour coding of periodic groups
   void showGroupLegend(bool checked);
 
   QString getValue();
 
-
 private:
-  ///The Form containing the PeriodicTableWidget
+  /// The Form containing the PeriodicTableWidget
   Ui::PeriodicTable ui;
   /// Methods to colour element buttons by periodic group
   void ColourNonMetals(const QVector<QPushButton *> &nonMetals);
   void ColourAlkaliMetals(const QVector<QPushButton *> &alkaliMetals);
-  void ColourAlkalineEarthMetals(
-      const QVector<QPushButton *> &alkalineEarthMetals);
+  void
+  ColourAlkalineEarthMetals(const QVector<QPushButton *> &alkalineEarthMetals);
   void ColourTransitionMetals(const QVector<QPushButton *> &transMetals);
   void ColourActinides(const QVector<QPushButton *> &actinides);
   void ColourLanthanides(const QVector<QPushButton *> &lanthanides);
   void
   ColourPostTransitionMetals(const QVector<QPushButton *> &postTransMetals);
-  void
-  ColourUnknownProperties(const QVector<QPushButton *> &unknownProperties);
+  void ColourUnknownProperties(const QVector<QPushButton *> &unknownProperties);
   void ColourMetalloids(const QVector<QPushButton *> &metalloids);
   void ColourHalogens(const QVector<QPushButton *> &halogens);
   void ColourNobleGases(const QVector<QPushButton *> &nobleGases);
@@ -101,10 +104,10 @@ private:
   /// Methods to colour single element button by setting styleSheet
   void ColourButton(QPushButton *elementButton, QString colour);
 
-  ///Method to populate Group Vectors with element QPushButtons
+  /// Method to populate Group Vectors with element QPushButtons
   void populateGroupVectors();
 
-  ///Method to populate Vector with all Group vectors
+  /// Method to populate Vector with all Group vectors
   void populateAllButtonsVector();
 
   /// Colour all of the elements by calls to individual group colouring methods
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PrecompiledHeader.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PrecompiledHeader.h
index e61743676e129c3173f5855b9200187e3ccc9960..4e1701324303edfc2b88f6322ea5668a8b019d55 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PrecompiledHeader.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PrecompiledHeader.h
@@ -4,12 +4,12 @@
 // Mantid
 #include "MantidAPI/Algorithm.h"
 
- // MantidQt API
+// MantidQt API
 #include "MantidQtAPI/MantidWidget.h"
 
-//STL
+// STL
 #include <vector>
 #include <map>
 #include <string>
 
-#endif //MANTIDQT_MANTIDWIDGETS_PRECOMPILEDHEADER_H_
\ No newline at end of file
+#endif // MANTIDQT_MANTIDWIDGETS_PRECOMPILEDHEADER_H_
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ProcessingAlgoWidget.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ProcessingAlgoWidget.h
index 1975871f1bd4439e73858b8b383a1bc6b1a3501c..0d2c8bf5d30876cb8766b1ebf13fbacd08aca1fa 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ProcessingAlgoWidget.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ProcessingAlgoWidget.h
@@ -6,85 +6,85 @@
 #include "ui_ProcessingAlgoWidget.h"
 #include "MantidAPI/Algorithm.h"
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /** A widget containing an algorithm selector and algorithm properties list,
-     * or a script editor window.
-     * Allows the user to pick a processing step, either as a python script
-     * or an algorithm.
-     *
-     * For use initially in the StartLiveDataDialog.
-     */
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ProcessingAlgoWidget : public QWidget
-    {
-      Q_OBJECT
-      Q_PROPERTY(QString infoString READ infoString WRITE infoString)
-      Q_PROPERTY(bool editorVisible READ editorVisible WRITE editorVisible)
-      Q_PROPERTY(bool algoVisible READ algoVisible WRITE algoVisible)
-
-    public:
-      /// Default Constructor
-      ProcessingAlgoWidget(QWidget *parent = 0);
-      ~ProcessingAlgoWidget() override;
-
-      /// @return the info string displayed at the top
-      QString infoString() { return ui.lblInfo->text(); }
-      /// Sets the info string displayed at the top
-      void infoString(QString text) { return ui.lblInfo->setText(text); }
-
-      /// @return true if the script editor is visible
-      bool editorVisible() { return ui.editorContainer->isVisible(); }
-      /// Sets whether the script editor is visible
-      void editorVisible(bool vis) { ui.editorContainer->setVisible(vis); }
-
-      /// @return true if the algorithm stuff is visible
-      bool algoVisible() { return ui.splitter->isVisible(); }
-      /// Sets whether the algorithm stuff is visible
-      void algoVisible(bool vis) { ui.splitter->setVisible(vis); }
-
-      /// @return the name of the selected algorithm
-      QString getSelectedAlgorithm() { return ui.algoSelector->getSelectedAlgorithm(); };
-      void setSelectedAlgorithm(QString algo);
-
-      /// @return the text in the script editor
-      QString getScriptText();
-      /// Set the script editor text
-      void setScriptText(QString text);
-
-      void saveInput();
-      /// Sets the AlgorithmInputHistory object recording the algorithm properties
-      void setInputHistory(MantidQt::API::AbstractAlgorithmInputHistory * inputHistory) { ui.algoProperties->setInputHistory(inputHistory); }
-
-      /// @return the last selected algorithm
-      Mantid::API::Algorithm_sptr getAlgorithm() { return m_alg; };
-
-    public slots:
-      void changeAlgorithm();
-      void btnSaveClicked();
-      void btnLoadClicked();
-
-    signals:
-      /// Signal emitted when the algorithm changes
-      void changedAlgorithm();
-
-    private:
-      void loadSettings();
-      void saveSettings();
-
-      ///The form generated by Qt Designer
-      Ui::ProcessingAlgoWidget ui;
-
-      /// Current algorithm with properties set.
-      Mantid::API::Algorithm_sptr m_alg;
-
-      /// Last saved file path
-      QString m_lastFile;
-
-    };
-
-
-  }// Namespace
-}// Namespace
+namespace MantidQt {
+namespace MantidWidgets {
+/** A widget containing an algorithm selector and algorithm properties list,
+ * or a script editor window.
+ * Allows the user to pick a processing step, either as a python script
+ * or an algorithm.
+ *
+ * For use initially in the StartLiveDataDialog.
+ */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ProcessingAlgoWidget : public QWidget {
+  Q_OBJECT
+  Q_PROPERTY(QString infoString READ infoString WRITE infoString)
+  Q_PROPERTY(bool editorVisible READ editorVisible WRITE editorVisible)
+  Q_PROPERTY(bool algoVisible READ algoVisible WRITE algoVisible)
+
+public:
+  /// Default Constructor
+  ProcessingAlgoWidget(QWidget *parent = 0);
+  ~ProcessingAlgoWidget() override;
+
+  /// @return the info string displayed at the top
+  QString infoString() { return ui.lblInfo->text(); }
+  /// Sets the info string displayed at the top
+  void infoString(QString text) { return ui.lblInfo->setText(text); }
+
+  /// @return true if the script editor is visible
+  bool editorVisible() { return ui.editorContainer->isVisible(); }
+  /// Sets whether the script editor is visible
+  void editorVisible(bool vis) { ui.editorContainer->setVisible(vis); }
+
+  /// @return true if the algorithm stuff is visible
+  bool algoVisible() { return ui.splitter->isVisible(); }
+  /// Sets whether the algorithm stuff is visible
+  void algoVisible(bool vis) { ui.splitter->setVisible(vis); }
+
+  /// @return the name of the selected algorithm
+  QString getSelectedAlgorithm() {
+    return ui.algoSelector->getSelectedAlgorithm();
+  };
+  void setSelectedAlgorithm(QString algo);
+
+  /// @return the text in the script editor
+  QString getScriptText();
+  /// Set the script editor text
+  void setScriptText(QString text);
+
+  void saveInput();
+  /// Sets the AlgorithmInputHistory object recording the algorithm properties
+  void
+  setInputHistory(MantidQt::API::AbstractAlgorithmInputHistory *inputHistory) {
+    ui.algoProperties->setInputHistory(inputHistory);
+  }
+
+  /// @return the last selected algorithm
+  Mantid::API::Algorithm_sptr getAlgorithm() { return m_alg; };
+
+public slots:
+  void changeAlgorithm();
+  void btnSaveClicked();
+  void btnLoadClicked();
+
+signals:
+  /// Signal emitted when the algorithm changes
+  void changedAlgorithm();
+
+private:
+  void loadSettings();
+  void saveSettings();
+
+  /// The form generated by Qt Designer
+  Ui::ProcessingAlgoWidget ui;
+
+  /// Current algorithm with properties set.
+  Mantid::API::Algorithm_sptr m_alg;
+
+  /// Last saved file path
+  QString m_lastFile;
+};
+
+} // Namespace
+} // Namespace
 #endif
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PropertyHandler.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PropertyHandler.h
index 6161eaa041da1af7c6c9d0d797f6aad4f6384cc9..894d907b161acdb956b90fa4dc5a60acbc188272 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PropertyHandler.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PropertyHandler.h
@@ -5,18 +5,16 @@
 #include "WidgetDllOption.h"
 
 /* Forward declarations */
-namespace Mantid
-{
-  namespace API
-  {
-    class IPeakFunction;
-    class CompositeFunction;
-  }
+namespace Mantid {
+namespace API {
+class IPeakFunction;
+class CompositeFunction;
+}
 }
 
-//class FunctionCurve;
-//class PlotCurve;
-//class Graph;
+// class FunctionCurve;
+// class PlotCurve;
+// class Graph;
 class QtBrowserItem;
 class QtProperty;
 
@@ -26,24 +24,22 @@ class QtProperty;
 #include <QMap>
 #include <QObject>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 class FitPropertyBrowser;
 
 /**
  * Helps display and edit functions in FitPropertyBrowser
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PropertyHandler:public QObject, public Mantid::API::FunctionHandler
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PropertyHandler
+    : public QObject,
+      public Mantid::API::FunctionHandler {
   Q_OBJECT
 public:
   // Constructor
   PropertyHandler(Mantid::API::IFunction_sptr fun,
                   boost::shared_ptr<Mantid::API::CompositeFunction> parent,
-                  FitPropertyBrowser* browser,
-                  QtBrowserItem* item = NULL);
+                  FitPropertyBrowser *browser, QtBrowserItem *item = NULL);
 
   /// Destructor
   ~PropertyHandler() override;
@@ -51,70 +47,74 @@ public:
   /// overrides virtual init() which is called from IFunction::setHandler(...)
   void init() override;
 
-  PropertyHandler* addFunction(const std::string& fnName);
-  // Removes handled function from its parent function and 
+  PropertyHandler *addFunction(const std::string &fnName);
+  // Removes handled function from its parent function and
   // properties from the browser
   void removeFunction();
 
-  void renameChildren()const;
+  void renameChildren() const;
 
   /// Creates name for this function to be displayed
   /// in the browser
-  QString functionName()const;
+  QString functionName() const;
 
-  QString functionPrefix()const;
+  QString functionPrefix() const;
 
   // Return composite function
-  boost::shared_ptr<Mantid::API::CompositeFunction> cfun()const{return m_cf;}
+  boost::shared_ptr<Mantid::API::CompositeFunction> cfun() const {
+    return m_cf;
+  }
   // Return peak function
-  boost::shared_ptr<Mantid::API::IPeakFunction> pfun()const{return m_pf;}
+  boost::shared_ptr<Mantid::API::IPeakFunction> pfun() const { return m_pf; }
   // Return IFunction
-  boost::shared_ptr<Mantid::API::IFunction> ifun()const{return m_fun;}
+  boost::shared_ptr<Mantid::API::IFunction> ifun() const { return m_fun; }
   // Return the browser item
-  QtBrowserItem* item()const{return m_item;}
+  QtBrowserItem *item() const { return m_item; }
   // Return the parent handler
-  PropertyHandler* parentHandler()const;
+  PropertyHandler *parentHandler() const;
   // Return the child's handler
-  PropertyHandler* getHandler(std::size_t i)const;
+  PropertyHandler *getHandler(std::size_t i) const;
   /** Returns 'this' if item == m_item and this is a composite function or
    * calls findCompositeFunction recursively with all its children or
    * zero
    */
-  boost::shared_ptr<const Mantid::API::CompositeFunction> findCompositeFunction(QtBrowserItem* item)const;
+  boost::shared_ptr<const Mantid::API::CompositeFunction>
+  findCompositeFunction(QtBrowserItem *item) const;
   /** Returns 'this' if item == m_item or
    * calls findFunction recursively with all its children or
    * zero
    */
-  boost::shared_ptr<const Mantid::API::IFunction> findFunction(QtBrowserItem* item)const;
+  boost::shared_ptr<const Mantid::API::IFunction>
+  findFunction(QtBrowserItem *item) const;
 
-  PropertyHandler* findHandler(QtProperty* prop);
+  PropertyHandler *findHandler(QtProperty *prop);
 
-  PropertyHandler* findHandler(Mantid::API::IFunction_const_sptr fun);
-  PropertyHandler* findHandler(const Mantid::API::IFunction* fun);
+  PropertyHandler *findHandler(Mantid::API::IFunction_const_sptr fun);
+  PropertyHandler *findHandler(const Mantid::API::IFunction *fun);
 
   /**
    * Set function parameter value read from a QtProperty
    * @param prop :: The (double) property with the new parameter value
    * @return true if successfull
    */
-  bool setParameter(QtProperty* prop);
+  bool setParameter(QtProperty *prop);
 
   // Check if it is a parameter property
-  bool isParameter(QtProperty* prop);
+  bool isParameter(QtProperty *prop);
 
   /**
    * Set function attribute value read from a QtProperty
    * @param prop :: The (string) property with the new attribute value
    * @return true if successfull
    */
-  bool setAttribute(QtProperty* prop);
+  bool setAttribute(QtProperty *prop);
 
   /**
    * Set function's double attribute
    * @param attName :: The name of the attribute
    * @param attValue :: The new attribute value
    */
-  void setAttribute(const QString& attName, const double& attValue);
+  void setAttribute(const QString &attName, const double &attValue);
 
   /**
    * Set function's attribute of any type.
@@ -122,10 +122,10 @@ public:
    * @param attValue :: The new attribute value as a string. If the attValue's
    *  format doesn't match the attribute's type it is ignored.
    */
-  void setAttribute(const QString& attName, const QString& attValue);
+  void setAttribute(const QString &attName, const QString &attValue);
 
   /// Set function vector attribute value
-  void setVectorAttribute(QtProperty* prop);
+  void setVectorAttribute(QtProperty *prop);
 
   /// Sync all parameter values with the manager
   void updateParameters();
@@ -137,55 +137,58 @@ public:
   void clearErrors();
 
   // Get property for function parameter parName
-  QtProperty* getParameterProperty(const QString& parName)const;
+  QtProperty *getParameterProperty(const QString &parName) const;
 
-  // Get parameter property which has the argument as a child (i.e. tie or conatraint)
-  QtProperty* getParameterProperty(QtProperty* prop)const;
+  // Get parameter property which has the argument as a child (i.e. tie or
+  // conatraint)
+  QtProperty *getParameterProperty(QtProperty *prop) const;
 
   /**
    * Change the type of the function (replace the function)
    * @param prop :: The "Type" property with new value
    */
-  boost::shared_ptr<Mantid::API::IFunction> changeType(QtProperty* prop);
-
-  void setHeight(const double& h);
-  void setCentre(const double& c);
-  void setFwhm(const double& w);
-  void setBase(const double& b){m_base = b;}
-  void calcBase();//< caclulate baseline from workspace data
-  void calcBaseAll();//< calc baseline for all peaks in the function
+  boost::shared_ptr<Mantid::API::IFunction> changeType(QtProperty *prop);
+
+  void setHeight(const double &h);
+  void setCentre(const double &c);
+  void setFwhm(const double &w);
+  void setBase(const double &b) { m_base = b; }
+  void calcBase();    //< caclulate baseline from workspace data
+  void calcBaseAll(); //< calc baseline for all peaks in the function
   /// Estimate the FwHM for a peak
   double EstimateFwhm() const;
 
-  double height()const;
-  double centre()const;
-  double fwhm()const;
-  double base()const{return m_base;}
-
-  void addTie(const QString& tieStr);
-  void fix(const QString& parName);
-  void removeTie(QtProperty* prop);
-  void removeTie(const QString& propName);
-  void addConstraint(QtProperty* parProp,bool lo,bool up,double loBound,double upBound);
-  void removeConstraint(QtProperty* parProp);
-
-  // Return list of handlers of peak functions which can be used in PeakPickerTool
+  double height() const;
+  double centre() const;
+  double fwhm() const;
+  double base() const { return m_base; }
+
+  void addTie(const QString &tieStr);
+  void fix(const QString &parName);
+  void removeTie(QtProperty *prop);
+  void removeTie(const QString &propName);
+  void addConstraint(QtProperty *parProp, bool lo, bool up, double loBound,
+                     double upBound);
+  void removeConstraint(QtProperty *parProp);
+
+  // Return list of handlers of peak functions which can be used in
+  // PeakPickerTool
   // The item->pfun() will return a correct pointer to a peak
   // Non-const because it may return a non-const pointer to this.
-  QList<PropertyHandler*> getPeakList();
+  QList<PropertyHandler *> getPeakList();
 
   // Plot the function on a graph
-  //void plot(Graph* g)const;
-  bool& hasPlot() {return m_hasPlot;}
-  //void replot()const;
-  //void removePlot();
+  // void plot(Graph* g)const;
+  bool &hasPlot() { return m_hasPlot; }
+  // void replot()const;
+  // void removePlot();
   void removeAllPlots();
 
   void fit();
 
   // update workspace property when workspaces added to or removed from ADS
   void updateWorkspaces(QStringList oldWorkspaces);
-  // set workspace in workspace property to the function 
+  // set workspace in workspace property to the function
   void setFunctionWorkspace();
 
   /// Update high-level structure tooltip and return it
@@ -193,46 +196,50 @@ public:
 
 protected slots:
 
-  // 
+  //
   void plotRemoved();
 
 protected:
-
   void initAttributes();
   void initParameters();
   void initWorkspace();
 
 private:
-  FitPropertyBrowser* m_browser;
-  boost::shared_ptr<Mantid::API::CompositeFunction> m_cf;//< if the function is composite holds pointer to it
-  boost::shared_ptr<Mantid::API::IPeakFunction> m_pf;//< if the function is peak holds pointer to it
-  boost::shared_ptr<Mantid::API::CompositeFunction> m_parent; //< if the function has parent holds pointer to it
-  QtProperty* m_type;
-  QtBrowserItem* m_item;//< the browser item
-  QList<QtProperty*> m_attributes; //< function attribute properties
-  QList<QtProperty*> m_parameters; //< function parameter properties
-  QMap<QString,QtProperty*> m_ties;//< tie properties
-  QMap<QString,std::pair<QtProperty*,QtProperty*> > m_constraints;//< constraints
-  QList<QtProperty*> m_vectorMembers; //< vector member properties
-  bool m_isMultispectral; ///< true if fitting to multiple spectra using MultiBG function
-  QtProperty* m_workspace; ///< workspace name for multispectral fitting
-  QtProperty* m_workspaceIndex; ///< workspace index for multispectral fitting
-  double m_base; //< the baseline for a peak
+  FitPropertyBrowser *m_browser;
+  boost::shared_ptr<Mantid::API::CompositeFunction>
+      m_cf; //< if the function is composite holds pointer to it
+  boost::shared_ptr<Mantid::API::IPeakFunction>
+      m_pf; //< if the function is peak holds pointer to it
+  boost::shared_ptr<Mantid::API::CompositeFunction>
+      m_parent; //< if the function has parent holds pointer to it
+  QtProperty *m_type;
+  QtBrowserItem *m_item;              //< the browser item
+  QList<QtProperty *> m_attributes;   //< function attribute properties
+  QList<QtProperty *> m_parameters;   //< function parameter properties
+  QMap<QString, QtProperty *> m_ties; //< tie properties
+  QMap<QString, std::pair<QtProperty *, QtProperty *>>
+      m_constraints;                   //< constraints
+  QList<QtProperty *> m_vectorMembers; //< vector member properties
+  bool m_isMultispectral; ///< true if fitting to multiple spectra using MultiBG
+  /// function
+  QtProperty *m_workspace;      ///< workspace name for multispectral fitting
+  QtProperty *m_workspaceIndex; ///< workspace index for multispectral fitting
+  double m_base;                //< the baseline for a peak
   int m_ci; //< approximate index in the workspace at the peak centre
-  //mutable FunctionCurve* m_curve;//< the curve to plot the handled function
+  // mutable FunctionCurve* m_curve;//< the curve to plot the handled function
   mutable bool m_hasPlot;
 
   /// Sync function parameter value with the manager
-  void updateParameter(QtProperty* prop);
+  void updateParameter(QtProperty *prop);
 
   /// Set function parameter error in the manager
-  void updateError(QtProperty* prop);
+  void updateError(QtProperty *prop);
 
   /// Clear function parameter error in the manager
-  void clearError(QtProperty* prop);
+  void clearError(QtProperty *prop);
 
   /// Applies given function to all the parameter properties recursively
-  void applyToAllParameters(void (PropertyHandler::*func)(QtProperty*));
+  void applyToAllParameters(void (PropertyHandler::*func)(QtProperty *));
 
   friend class CreateAttributeProperty;
 };
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
index c17ac9446f416b060c42d30d870a6d83b525fb2e..153c48dc17602f515ae69fb8a33e901e144f45b7 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
@@ -9,102 +9,102 @@
 
 #include <QPen>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class PreviewPlot;
-
-  /**
-  * Allows for simpler (in a way) selection of a range on a QwtPlot in MantidQt.
-  * @author Michael Whitty, RAL ISIS
-  * @date 11/10/2010
-  */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RangeSelector : public QwtPlotPicker
-  {
-    Q_OBJECT
-  public:
-    enum SelectType { XMINMAX, XSINGLE, YMINMAX, YSINGLE };
-
-    RangeSelector(QwtPlot* plot, SelectType type=XMINMAX, bool visible=true, bool infoOnly=false);
-    RangeSelector(PreviewPlot* plot, SelectType type=XMINMAX, bool visible=true, bool infoOnly=false);
-    ~RangeSelector() override{};
-
-    std::pair<double,double> getRange();
-    void setRange(std::pair<double,double> range); /// Overloaded function provided for convenience
-
-    double getMinimum() { return m_min; } ///< Returns current min value
-    double getMaximum() { return m_max; } ///< Reutnrs current max value
-
-    SelectType getType() { return m_type; }
-    bool isVisible() { return m_visible; }
-
-  signals:
-    void minValueChanged(double);
-    void maxValueChanged(double);
-    void rangeChanged(double, double);
-    void selectionChanged(double, double);
-    void selectionChangedLazy(double, double);
-
-  public slots:
-    void setRange(double, double);
-    void setMinimum(double); ///< outside setting of value
-    void setMaximum(double); ///< outside setting of value
-    void reapply(); ///< re-apply the range selector lines
-    void detach(); ///< Detach range selector lines from the plot
-    void setColour(QColor colour);
-    void setInfoOnly(bool state);
-    void setVisible(bool state);
-
-  private:
-    void init();
-    void setMin(double val);
-    void setMax(double val);
-    void setMaxMin(const double min, const double max);
-    void setMinLinePos(double);
-    void setMaxLinePos(double);
-    void verify();
-    bool inRange(double);
-    bool changingMin(double, double);
-    bool changingMax(double, double);
-    bool eventFilter(QObject *, QEvent *) override;
-
-    // MEMBER ATTRIBUTES
-    SelectType m_type; ///< type of selection widget is for
-
-    /// current position of the line marking the minimum
-    double m_min;
-    /// current position of the line marking the maximum
-    double m_max;
-    /// lowest allowed position of the line marking the minimum
-    double m_lower;
-    /// highest allowed position of the line marking the maximum
-    double m_higher;
-    /// the line object in the plot marking the position of the minimum
-    QwtPlotMarker* m_mrkMin;
-    /// the line object in the plot marking the position of the maximum
-    QwtPlotMarker* m_mrkMax;
-
-    /// widget receiving the  marker lines to be plotted
-    QwtPlot* m_plot;
-    /// the actual area of m_plot where the marker lines are plotted
-    QwtPlotCanvas* m_canvas;
-
-    /// signals the position of the line marking the minimum is to be changed
-    bool m_minChanging;
-    /// signals the position of the line marking the maximum is to be changed
-    bool m_maxChanging;
-
-    bool m_infoOnly;
-    /// whether the lines should be visible
-    bool m_visible;
-
-    /** Strictly UI options and settings below this point **/
-
-    QPen* m_pen; ///< pen object used to define line style, colour, etc
-    QCursor m_movCursor; ///< the cursor object to display when an item is being moved
-
-  };
+namespace MantidQt {
+namespace MantidWidgets {
+class PreviewPlot;
+
+/**
+* Allows for simpler (in a way) selection of a range on a QwtPlot in MantidQt.
+* @author Michael Whitty, RAL ISIS
+* @date 11/10/2010
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RangeSelector : public QwtPlotPicker {
+  Q_OBJECT
+public:
+  enum SelectType { XMINMAX, XSINGLE, YMINMAX, YSINGLE };
+
+  RangeSelector(QwtPlot *plot, SelectType type = XMINMAX, bool visible = true,
+                bool infoOnly = false);
+  RangeSelector(PreviewPlot *plot, SelectType type = XMINMAX,
+                bool visible = true, bool infoOnly = false);
+  ~RangeSelector() override{};
+
+  std::pair<double, double> getRange();
+  void setRange(std::pair<double, double>
+                    range); /// Overloaded function provided for convenience
+
+  double getMinimum() { return m_min; } ///< Returns current min value
+  double getMaximum() { return m_max; } ///< Reutnrs current max value
+
+  SelectType getType() { return m_type; }
+  bool isVisible() { return m_visible; }
+
+signals:
+  void minValueChanged(double);
+  void maxValueChanged(double);
+  void rangeChanged(double, double);
+  void selectionChanged(double, double);
+  void selectionChangedLazy(double, double);
+
+public slots:
+  void setRange(double, double);
+  void setMinimum(double); ///< outside setting of value
+  void setMaximum(double); ///< outside setting of value
+  void reapply();          ///< re-apply the range selector lines
+  void detach();           ///< Detach range selector lines from the plot
+  void setColour(QColor colour);
+  void setInfoOnly(bool state);
+  void setVisible(bool state);
+
+private:
+  void init();
+  void setMin(double val);
+  void setMax(double val);
+  void setMaxMin(const double min, const double max);
+  void setMinLinePos(double);
+  void setMaxLinePos(double);
+  void verify();
+  bool inRange(double);
+  bool changingMin(double, double);
+  bool changingMax(double, double);
+  bool eventFilter(QObject *, QEvent *) override;
+
+  // MEMBER ATTRIBUTES
+  SelectType m_type; ///< type of selection widget is for
+
+  /// current position of the line marking the minimum
+  double m_min;
+  /// current position of the line marking the maximum
+  double m_max;
+  /// lowest allowed position of the line marking the minimum
+  double m_lower;
+  /// highest allowed position of the line marking the maximum
+  double m_higher;
+  /// the line object in the plot marking the position of the minimum
+  QwtPlotMarker *m_mrkMin;
+  /// the line object in the plot marking the position of the maximum
+  QwtPlotMarker *m_mrkMax;
+
+  /// widget receiving the  marker lines to be plotted
+  QwtPlot *m_plot;
+  /// the actual area of m_plot where the marker lines are plotted
+  QwtPlotCanvas *m_canvas;
+
+  /// signals the position of the line marking the minimum is to be changed
+  bool m_minChanging;
+  /// signals the position of the line marking the maximum is to be changed
+  bool m_maxChanging;
+
+  bool m_infoOnly;
+  /// whether the lines should be visible
+  bool m_visible;
+
+  /** Strictly UI options and settings below this point **/
+
+  QPen *m_pen; ///< pen object used to define line style, colour, etc
+  QCursor
+      m_movCursor; ///< the cursor object to display when an item is being moved
+};
 
 } // MantidWidgets
 } // MantidQt
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RenameParDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RenameParDialog.h
index 5780f014492f46fb6d13e3d4e66cac6333fd3851..f77c510e617424fb43614ab61819a5a8b116b4f8 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RenameParDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RenameParDialog.h
@@ -7,35 +7,34 @@
 #include <vector>
 #include <string>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-     * A dialog for renaming parameters for a user function
-     */
-	  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RenameParDialog : public QDialog
-    {
-      Q_OBJECT
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+ * A dialog for renaming parameters for a user function
+ */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS RenameParDialog : public QDialog {
+  Q_OBJECT
 
-    public:
-      /// there has to be a default constructor but you can call it with a pointer to the thing that will take ownership of it
-      RenameParDialog(const std::vector<std::string>& old_params,
-        const std::vector<std::string>& new_params,
-        QWidget *parent=NULL);
-      std::vector<std::string> setOutput() const;
-    protected slots:
-      void uniqueIndexedNames(bool);
-      void doNotRename(bool);
-    protected:
-      bool isUnique(const QString& name)const;
-      QString makeUniqueIndexedName(const QString& name);
-      /// User interface elements
-      Ui::RenameParDialog m_uiForm;
-      const std::vector<std::string> m_old_params;
-      const std::vector<std::string> m_new_params;
-	  };
-  }
+public:
+  /// there has to be a default constructor but you can call it with a pointer
+  /// to the thing that will take ownership of it
+  RenameParDialog(const std::vector<std::string> &old_params,
+                  const std::vector<std::string> &new_params,
+                  QWidget *parent = NULL);
+  std::vector<std::string> setOutput() const;
+protected slots:
+  void uniqueIndexedNames(bool);
+  void doNotRename(bool);
+
+protected:
+  bool isUnique(const QString &name) const;
+  QString makeUniqueIndexedName(const QString &name);
+  /// User interface elements
+  Ui::RenameParDialog m_uiForm;
+  const std::vector<std::string> m_old_params;
+  const std::vector<std::string> m_new_params;
+};
+}
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_RENAMEPARDIALOG_H_
+#endif // MANTIDQTMANTIDWIDGETS_RENAMEPARDIALOG_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SafeQwtPlot.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SafeQwtPlot.h
index 0a0aaaed1b0cb997b0f80f75dfeae36597a15d1b..ba471906e86335b01fde295b552fa34d7d5ab3ea 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SafeQwtPlot.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SafeQwtPlot.h
@@ -8,63 +8,60 @@
 #include "MantidAPI/Workspace_fwd.h"
 #include "WidgetDllOption.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-  /** A version of QwtPlot that adds a layer of thread safety.
-   *
-   * Each SafeQwtPlot has a workspace associated with it.
-   * Before drawing, it acquires a ReadLock to prevent
-   * an algorithm from modifying the underlying workspace while it is
-   * drawing.
-   *
-   * If no workspace is set, no drawing occurs (silently).
-    
-    @date 2012-01-24
+/** A version of QwtPlot that adds a layer of thread safety.
+ *
+ * Each SafeQwtPlot has a workspace associated with it.
+ * Before drawing, it acquires a ReadLock to prevent
+ * an algorithm from modifying the underlying workspace while it is
+ * drawing.
+ *
+ * If no workspace is set, no drawing occurs (silently).
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  @date 2012-01-24
 
-    This file is part of Mantid.
+  Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SafeQwtPlot : public QwtPlot
-  {
-    Q_OBJECT
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  public:
-    explicit SafeQwtPlot(QWidget * parent = NULL);
-    explicit SafeQwtPlot(const QwtText &title, QWidget *p = NULL);
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SafeQwtPlot : public QwtPlot {
+  Q_OBJECT
 
-    ~SafeQwtPlot() override;
+public:
+  explicit SafeQwtPlot(QWidget *parent = NULL);
+  explicit SafeQwtPlot(const QwtText &title, QWidget *p = NULL);
 
-    void drawCanvas(QPainter *painter) override;
+  ~SafeQwtPlot() override;
 
-    void setWorkspace(Mantid::API::Workspace_sptr ws);
+  void drawCanvas(QPainter *painter) override;
 
-  private:
-    /// Workspace being read-locked
-    Mantid::API::Workspace_sptr m_ws;
-  };
+  void setWorkspace(Mantid::API::Workspace_sptr ws);
 
+private:
+  /// Workspace being read-locked
+  Mantid::API::Workspace_sptr m_ws;
+};
 
 } // namespace MantidWidgets
 } // namespace MantidQt
 
-#endif  /* MANTID_MANTIDWIDGETS_SAFEQWTPLOT_H_ */
+#endif /* MANTID_MANTIDWIDGETS_SAFEQWTPLOT_H_ */
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SaveWorkspaces.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SaveWorkspaces.h
index 7cdff7933c6435afdeff84e415209bfdb17c9659..9b68deccae29a8b8d4ac92a8eceb7cbf2b5d7b63 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SaveWorkspaces.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SaveWorkspaces.h
@@ -13,83 +13,87 @@
 
 #include "MantidAPI/FrameworkManager.h"
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-	/** 
-    Implements a dialog box that allows users to save multiple Mantid workspaces
-
-    @author Steve Williams
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SaveWorkspaces : public API::MantidDialog
-    {
-      Q_OBJECT
-
-    public: 
-      SaveWorkspaces(QWidget *parent, const QString & suggFname,
-        QHash<const QCheckBox * const, QString> & defSavs, bool saveAsZeroErrorFree);
-      void initLayout();
-      ///Returns the save extension expected the name algorithm
-      static QString getSaveAlgExt(const QString & algName);
-    public slots:
-      void onSaveAsZeroErrorFreeChanged(int state);
-
-    signals:
-      void closing();
-      void createZeroErrorFreeWorkspace(QString& originalWorkspace, QString& zeroFreeWorkspace);
-      void deleteZeroErrorFreeWorkspace(QString& zeroFreeWorkspace);
-
-    private:
-      QLineEdit *m_fNameEdit;
-      QListWidget *m_workspaces;
-      QCheckBox *m_append;
-      QString m_lastName;
-      bool m_saveAsZeroErrorFree;
-
-      QHash<QCheckBox * const, QString> m_savFormats;
-      typedef QHash<QCheckBox * const, QString>::const_iterator SavFormatsConstIt;
-      
-      void setupLine1(QHBoxLayout * const lineOne);
-      void setupLine2(QHBoxLayout * const lineTwo, const QHash<const QCheckBox * const, QString> & defSavs);
-      void readSettings();
-      void setFileName(const QString & newName);
-      void setupFormatTicks(const QHash<const QCheckBox * const, QString> & defSavs);
-      void saveSettings() const;
-
-      void addButtonsDisab(int row);
-      void closeEvent(QCloseEvent *event) override;
-      QString saveList(const QList<QListWidgetItem*> & list, const QString & algorithm, QString fileBase, bool toAppend, QHash<QString, QString> workspaceMap);
-      QHash<QString, QString> provideZeroFreeWorkspaces(const QListWidget * workspaces);
-      void removeZeroFreeWorkspaces(QHash<QString, QString> workspaces);
-
-    private slots:
-      void saveSel();
-      void setFileName(int row);
-      void saveFileBrowse();
-
-    };
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+Implements a dialog box that allows users to save multiple Mantid workspaces
+
+@author Steve Williams
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SaveWorkspaces
+    : public API::MantidDialog {
+  Q_OBJECT
+
+public:
+  SaveWorkspaces(QWidget *parent, const QString &suggFname,
+                 QHash<const QCheckBox *const, QString> &defSavs,
+                 bool saveAsZeroErrorFree);
+  void initLayout();
+  /// Returns the save extension expected the name algorithm
+  static QString getSaveAlgExt(const QString &algName);
+public slots:
+  void onSaveAsZeroErrorFreeChanged(int state);
+
+signals:
+  void closing();
+  void createZeroErrorFreeWorkspace(QString &originalWorkspace,
+                                    QString &zeroFreeWorkspace);
+  void deleteZeroErrorFreeWorkspace(QString &zeroFreeWorkspace);
+
+private:
+  QLineEdit *m_fNameEdit;
+  QListWidget *m_workspaces;
+  QCheckBox *m_append;
+  QString m_lastName;
+  bool m_saveAsZeroErrorFree;
+
+  QHash<QCheckBox *const, QString> m_savFormats;
+  typedef QHash<QCheckBox *const, QString>::const_iterator SavFormatsConstIt;
+
+  void setupLine1(QHBoxLayout *const lineOne);
+  void setupLine2(QHBoxLayout *const lineTwo,
+                  const QHash<const QCheckBox *const, QString> &defSavs);
+  void readSettings();
+  void setFileName(const QString &newName);
+  void setupFormatTicks(const QHash<const QCheckBox *const, QString> &defSavs);
+  void saveSettings() const;
+
+  void addButtonsDisab(int row);
+  void closeEvent(QCloseEvent *event) override;
+  QString saveList(const QList<QListWidgetItem *> &list,
+                   const QString &algorithm, QString fileBase, bool toAppend,
+                   QHash<QString, QString> workspaceMap);
+  QHash<QString, QString>
+  provideZeroFreeWorkspaces(const QListWidget *workspaces);
+  void removeZeroFreeWorkspaces(QHash<QString, QString> workspaces);
+
+private slots:
+  void saveSel();
+  void setFileName(int row);
+  void saveFileBrowse();
+};
+}
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_SAVEWORKSPACES_H_
+#endif // MANTIDQTMANTIDWIDGETS_SAVEWORKSPACES_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ScriptEditor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ScriptEditor.h
index 61511489587cfa5d6fce295280fa6a86580f310c..2c7ac0093281eddc4be8ff1e715ddaaec35f15ba 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ScriptEditor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ScriptEditor.h
@@ -21,17 +21,15 @@ class QKeyEvent;
 class QMouseEvent;
 class QsciAPIs;
 
-
 /**
  * A small wrapper around a QStringList to manage a command history
  */
-struct EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CommandHistory
-{
-  ///Default constructor
+struct EXPORT_OPT_MANTIDQT_MANTIDWIDGETS CommandHistory {
+  /// Default constructor
   CommandHistory() : m_commands(), m_hist_maxsize(1000), m_current(0) {}
   /// Add a block of lines
   void addCode(QString block);
-  /// Add a command. 
+  /// Add a command.
   void add(QString command);
   /// Is there a previous command
   bool hasPrevious() const;
@@ -51,14 +49,16 @@ private:
   mutable int m_current;
 };
 
-/** 
-    This class provides an area to write scripts. It inherits from QScintilla to use
+/**
+    This class provides an area to write scripts. It inherits from QScintilla to
+   use
     functionality such as auto-indent and if supported, syntax highlighting.
-        
+
     @author Martyn Gigg, Tessella Support Services plc
     @date 19/08/2009
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -76,10 +76,9 @@ private:
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>   
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ScriptEditor : public QsciScintilla
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ScriptEditor : public QsciScintilla {
   // Qt macro
   Q_OBJECT
 
@@ -87,8 +86,7 @@ public:
   /**
    * Exception type to indicate that saving was cancelled
    */
-  class SaveCancelledException : public std::exception
-  {
+  class SaveCancelledException : public std::exception {
   public:
     /// Return a message
     const char *what() const noexcept override { return m_msg.c_str(); }
@@ -97,16 +95,15 @@ public:
     std::string m_msg{"File Saving was cancelled"};
   };
 
-
 public:
   /// Constructor
-  ScriptEditor(QWidget* parent = 0, QsciLexer* lexer = NULL,
-               const QString & settingsGroup = "");
-  ///Destructor
+  ScriptEditor(QWidget *parent = 0, QsciLexer *lexer = NULL,
+               const QString &settingsGroup = "");
+  /// Destructor
   ~ScriptEditor() override;
 
   /// Set the name of the group to save the settings for
-  void setSettingsGroup(const QString & name);
+  void setSettingsGroup(const QString &name);
   /// Settings group
   QString settingsGroup() const;
   /// Read settings from persistent store
@@ -128,40 +125,30 @@ public:
   // Unhide base class method to avoid intel compiler warning
   using QsciScintilla::setText;
   /// Set the text on a given line number
-  void setText(int lineno, const QString& text,int index=0);
-  ///Capture key presses
+  void setText(int lineno, const QString &text, int index = 0);
+  /// Capture key presses
   void keyPressEvent(QKeyEvent *event) override;
   /// The current filename
-  inline QString fileName() const
-  {
-    return m_filename;
-  }
+  inline QString fileName() const { return m_filename; }
   /**
    * Set a new file name
    * @param filename :: The new filename
    */
-  inline void setFileName(const QString & filename)
-  {
-    m_filename = filename;
-  }
-  
+  inline void setFileName(const QString &filename) { m_filename = filename; }
 
   /// Override so that ctrl + mouse wheel will zoom in and out
   void wheelEvent(QWheelEvent *e) override;
 
   /// Return a pointer to the object responsible for code completion
-  inline QsciAPIs * scintillaAPI() const
-  {
-    return m_completer;
-  }
-  
+  inline QsciAPIs *scintillaAPI() const { return m_completer; }
+
 public slots:
   /// Save the script, opening a dialog
   void saveAs();
   /// Save to the current filename, opening a dialog if blank
   void saveToCurrentFile();
   /// Save a the text to the given filename
-  void saveScript(const QString & filename);
+  void saveScript(const QString &filename);
 
   /// Ensure the margin width is big enough to hold everything + padding
   void padMargin();
@@ -172,7 +159,7 @@ public slots:
   /// Mark the progress arrow as an error
   void markExecutingLineAsError();
   /// Refresh the autocomplete information base on a new set of keywords
-  void updateCompletionAPI(const QStringList & keywords);
+  void updateCompletionAPI(const QStringList &keywords);
   /// Print the text within the widget
   void print();
   /// Raise find replace dialog
@@ -193,7 +180,7 @@ signals:
 
 protected:
   /// Write to the given device
-  virtual void writeToDevice(QIODevice & device) const;
+  virtual void writeToDevice(QIODevice &device) const;
 
   void dropEvent(QDropEvent *de) override;
   void dragMoveEvent(QDragMoveEvent *de) override;
@@ -202,13 +189,14 @@ protected:
 private slots:
 
 private:
-  /// Forward a KeyPress event to QsciScintilla base class. Necessary due to bug in QsciScintilla
+  /// Forward a KeyPress event to QsciScintilla base class. Necessary due to bug
+  /// in QsciScintilla
   void forwardKeyPressToBase(QKeyEvent *event);
 
   /// The file name associated with this editor
   QString m_filename;
 
-  /// The margin marker 
+  /// The margin marker
   int m_progressArrowKey;
   /// Hold the line number of the currently executing line
   int m_currentExecLine;
@@ -226,9 +214,4 @@ private:
   QString m_settingsGroup;
 };
 
-
-
-
-
-
-#endif //SCRIPTEDITOR_H_
+#endif // SCRIPTEDITOR_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectFunctionDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectFunctionDialog.h
index fe78cec97d96fc8c4c6f71a267027d6ad0779571..a8fb6e00a5278bfac353113223a5dd9854f2cb54 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectFunctionDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectFunctionDialog.h
@@ -8,16 +8,14 @@
 
 #include <QDialog>
 
-namespace Ui
-{
-  class SelectFunctionDialog;
+namespace Ui {
+class SelectFunctionDialog;
 }
 
 /**
  * Select a function type out of a list of available ones.
  */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SelectFunctionDialog : public QDialog
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SelectFunctionDialog : public QDialog {
   Q_OBJECT
 
 public:
@@ -25,10 +23,10 @@ public:
   ~SelectFunctionDialog() override;
   /// Return selected function
   QString getFunction() const;
+
 protected:
   /// Ui elements form
   Ui::SelectFunctionDialog *m_form;
 };
 
 #endif // FINDDIALOG_H_
-
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectWorkspacesDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectWorkspacesDialog.h
index 477d71183dac3e7df1840a72e98c6b3a528d2484..d6eb1ed859ba26ecb15206e87b5688509f2c7c97 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectWorkspacesDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SelectWorkspacesDialog.h
@@ -11,18 +11,17 @@
 #include "WidgetDllOption.h"
 #include <string>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-/** 
+/**
     This is a dialog for selecting workspaces.
 
     @author Roman Tolchenov, Tessella plc
     @date 22/06/2010
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -40,21 +39,24 @@ namespace MantidWidgets
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SelectWorkspacesDialog : public QDialog
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SelectWorkspacesDialog
+    : public QDialog {
   Q_OBJECT
 
 public:
-  ///return value of the Custom button
-  static const int CustomButton = 45654;  //do not use this number direct, just refer to this static constant
-  
+  /// return value of the Custom button
+  static const int CustomButton = 45654; // do not use this number direct, just
+                                         // refer to this static constant
+
   /// Constructor
-  SelectWorkspacesDialog (QWidget* parent = NULL, const std::string& typeFilter = "", const std::string& customButtonLabel = "");
+  SelectWorkspacesDialog(QWidget *parent = NULL,
+                         const std::string &typeFilter = "",
+                         const std::string &customButtonLabel = "");
 
   /// Return the selected names
-  QStringList getSelectedNames()const;
+  QStringList getSelectedNames() const;
 
 private slots:
 
@@ -65,16 +67,13 @@ private slots:
   void customButtonPress();
 
 private:
-
   /// Displays available workspace names
-  QListWidget* m_wsList;
+  QListWidget *m_wsList;
   /// The OK button
-  QPushButton* m_okButton;
+  QPushButton *m_okButton;
   /// The OK button
-  QPushButton* m_customButton;
-
+  QPushButton *m_customButton;
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SequentialFitDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SequentialFitDialog.h
index a55287e025f3f65ccfe7fe04f9cc0cbe53d60a9a..3059f340c4641a13411e8d7bfa414891baa884c2 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SequentialFitDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SequentialFitDialog.h
@@ -8,20 +8,18 @@
 #include "ui_SequentialFitDialog.h"
 #include "MantidAPI/AlgorithmObserver.h"
 
-
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  class FitPropertyBrowser;
-/** 
+namespace MantidQt {
+namespace MantidWidgets {
+class FitPropertyBrowser;
+/**
     This is a dialog for doing sequential fit.
     (Calls algorithm PlotPeakByLogValue)
 
     @author Roman Tolchenov, Tessella plc
     @date 4/06/2010
 
-    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -39,34 +37,33 @@ namespace MantidWidgets
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
     File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class SequentialFitDialog : public QDialog, public Mantid::API::AlgorithmObserver
-{
+class SequentialFitDialog : public QDialog,
+                            public Mantid::API::AlgorithmObserver {
   Q_OBJECT
 
 public:
-  
   /// Default constructor
-  SequentialFitDialog(FitPropertyBrowser* fitBrowser, QObject* mantidui);
+  SequentialFitDialog(FitPropertyBrowser *fitBrowser, QObject *mantidui);
 
   /// Add a list of workspace names to the data list
   /// Returns false if neither of the workspaces can be loaded
   bool addWorkspaces(const QStringList wsNames);
 
 private:
-
   /// The form generated with Qt Designer
   Ui::SequentialFitDialog ui;
 
   /// Pointer to the calling fit browser
-  FitPropertyBrowser* m_fitBrowser;
+  FitPropertyBrowser *m_fitBrowser;
 
 signals:
 
   /// This signal is fired from finishHandle running in the algorithm's thread
   /// and caught by showPlot slot in the GUI thread
-  void needShowPlot(Ui::SequentialFitDialog*, MantidQt::MantidWidgets::FitPropertyBrowser*);
+  void needShowPlot(Ui::SequentialFitDialog *,
+                    MantidQt::MantidWidgets::FitPropertyBrowser *);
 
 private slots:
 
@@ -83,19 +80,18 @@ private slots:
   void accept() override;
 
   /// Show the result plot
-  //void showPlot();
+  // void showPlot();
   /// Display the help page for PlotPeakByLogValue algorithm
   void helpClicked();
 
   /// called when spectra or workspace index change
-  void spectraChanged(int row,int col);
+  void spectraChanged(int row, int col);
   /// called when selection in the workspace table changes
   void selectionChanged();
 
   void plotAgainstLog(bool);
 
 private:
-
   /// Checks that the logs in workspace wsName are consistent
   /// with logs of other workspaces
   bool validateLogs(const QString wsName);
@@ -107,28 +103,26 @@ private:
   void finishHandle(const Mantid::API::IAlgorithm *alg) override;
 
   /// set spectrum value for workspace/file in row row
-  void setSpectrum(int row,int spec);
+  void setSpectrum(int row, int spec);
 
   /// set workspace index for workspace/file in row row
-  void setWSIndex(int row,int wi);
+  void setWSIndex(int row, int wi);
 
-  void setRange(int row,double from,double to);
+  void setRange(int row, double from, double to);
 
-  /// Ret. index for the data source in row row to be used in "Input" property of PlotPeakByLogValue
-  QString getIndex(int row)const;
+  /// Ret. index for the data source in row row to be used in "Input" property
+  /// of PlotPeakByLogValue
+  QString getIndex(int row) const;
 
   /// Return true if data source in a row is a file (rather than a workspace)
-  bool isFile(int row)const;
+  bool isFile(int row) const;
 
-  int rowCount()const;
+  int rowCount() const;
 
-  int defaultSpectrum()const;
-
-  QString name(int row)const;
+  int defaultSpectrum() const;
 
+  QString name(int row) const;
 };
-
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.h
index 135520dd79225e4603322ac02d61553ac44fe6dd..c4ed01c063ae64aa7096757361ebe8da2fa1f264 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.h
@@ -11,10 +11,8 @@
 #include "MantidGeometry/MDGeometry/IMDDimension.h"
 #include "WidgetDllOption.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 typedef QMap<QString, QString> PropertyDimensionMap;
 
@@ -22,18 +20,19 @@ typedef QMap<QString, QString> PropertyDimensionMap;
 Class SlicingAlgorithmDialog
 Abstract SlicingAlgorithm Dialog geared for MD Slicing type algorithms
 
-This custom dialog provides two advantages over the default custom generated one.
+This custom dialog provides two advantages over the default custom generated
+one.
 
-1) It dynamically creates dimension input controls based on the nature of the input MD workspace
+1) It dynamically creates dimension input controls based on the nature of the
+input MD workspace
 2) It pre-populates those dimension input controls based on existing values.
 
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SlicingAlgorithmDialog : public MantidQt::API::AlgorithmDialog
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SlicingAlgorithmDialog
+    : public MantidQt::API::AlgorithmDialog {
   Q_OBJECT
 public:
-
-   /// Default Constructor
+  /// Default Constructor
   SlicingAlgorithmDialog(QWidget *parent = 0);
 
   /// Destructor
@@ -42,19 +41,18 @@ public:
   // Customisation for the VSI
   void customiseLayoutForVsi(std::string initialWorkspace);
 
-  ///Reset the aligned dim values for the VSI
+  /// Reset the aligned dim values for the VSI
   void resestAlignedDimProperty(size_t index, QString propertyValue);
 
 protected:
-
   /// view
-  Ui::SlicingAlgorithmDialog ui; 
+  Ui::SlicingAlgorithmDialog ui;
 
   /// Common slice md setup
   void commonSliceMDSetup(const bool);
 
   /// Build dimension inputs.
-  void buildDimensionInputs(const bool bForceForget=false);
+  void buildDimensionInputs(const bool bForceForget = false);
 
 protected slots:
 
@@ -67,14 +65,13 @@ protected slots:
   void onMaxFromInput(bool);
 
   void onRebuildDimensions();
-  
+
   void onCalculateChanged(bool checked);
 
 private:
+  enum History { Remember, Forget };
 
-  enum History{Remember, Forget};
-
-  enum HistoryChanged{HasChanged, HasNotChanged};
+  enum HistoryChanged { HasChanged, HasNotChanged };
 
   /// Initialize the layout
   void initLayout() override;
@@ -92,13 +89,17 @@ private:
   QString getCurrentOutputWorkspaceName() const;
 
   /// Build dimension inputs.
-  void makeDimensionInputs(const QString& propertyPrefix, QLayout* owningLayout, QString(*format)(Mantid::Geometry::IMDDimension_const_sptr), History history);
+  void makeDimensionInputs(
+      const QString &propertyPrefix, QLayout *owningLayout,
+      QString (*format)(Mantid::Geometry::IMDDimension_const_sptr),
+      History history);
 
   /// Determine if history should be used.
-  History useHistory(const HistoryChanged& criticalChange, const bool bForceForget);
+  History useHistory(const HistoryChanged &criticalChange,
+                     const bool bForceForget);
 
   /// Cleans a given layout.
-  void cleanLayoutOfDimensions(QLayout* layout);
+  void cleanLayoutOfDimensions(QLayout *layout);
 
   /// Clear out any exisiting dimension widgets.
   void clearExistingDimensions();
@@ -117,20 +118,17 @@ private:
 
   /// Do auto fill dimension inputs on changes.
   bool doAutoFillDimensions() const;
-
 };
 
 /*
 Class SliceMDDialog
 Concrete SlicingAlgorithm Dialog geared for SliceMD
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SliceMDDialog : public SlicingAlgorithmDialog
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS SliceMDDialog
+    : public SlicingAlgorithmDialog {
+  Q_OBJECT
 public:
-  SliceMDDialog(QWidget* parent=NULL) : SlicingAlgorithmDialog(parent)
-  {
-  }
+  SliceMDDialog(QWidget *parent = NULL) : SlicingAlgorithmDialog(parent) {}
 
   ~SliceMDDialog() override {}
 
@@ -141,17 +139,14 @@ public:
 Class BinMDDialog
 Concrete BinMDDialog Dialog geared for BinMD
 */
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS BinMDDialog : public SlicingAlgorithmDialog
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS BinMDDialog
+    : public SlicingAlgorithmDialog {
+  Q_OBJECT
 public:
-  BinMDDialog(QWidget* parent=NULL) : SlicingAlgorithmDialog(parent)
-  {
-  }
+  BinMDDialog(QWidget *parent = NULL) : SlicingAlgorithmDialog(parent) {}
   ~BinMDDialog() override {}
   void customiseInitLayout() override;
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringDialogEditor.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringDialogEditor.h
index e624f9227c3ae4d80bf7e7c2bd03f76609dab0a4..b2ca058788c77dcf9bd2de60338e78e74e737ae7 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringDialogEditor.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringDialogEditor.h
@@ -6,41 +6,49 @@
 class QLineEdit;
 
 /**
- * An abstract editor factory to be used with QtPropertyBrowser. Implementations need to 
- * implement QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
- * method which creates a specific editor. The underlying type of the edited property must be string.
+ * An abstract editor factory to be used with QtPropertyBrowser. Implementations
+ * need to
+ * implement QWidget *createEditor(QtStringPropertyManager *manager, QtProperty
+ * *property,QWidget *parent)
+ * method which creates a specific editor. The underlying type of the edited
+ * property must be string.
  */
-class StringDialogEditorFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
-{
-    Q_OBJECT
+class StringDialogEditorFactory
+    : public QtAbstractEditorFactory<QtStringPropertyManager> {
+  Q_OBJECT
 public:
-  StringDialogEditorFactory(QObject *parent = 0): QtAbstractEditorFactory<QtStringPropertyManager>(parent){}
+  StringDialogEditorFactory(QObject *parent = 0)
+      : QtAbstractEditorFactory<QtStringPropertyManager>(parent) {}
+
 protected:
   void connectPropertyManager(QtStringPropertyManager *manager) override;
   void disconnectPropertyManager(QtStringPropertyManager *manager) override;
 };
 
 /**
- * Partially implemented string editor. It has a QLineEdit for manual editing and a button [...] next to it
- * to call a dialog for more complex editing. Clicking the button calls virtual runDialog() method.
+ * Partially implemented string editor. It has a QLineEdit for manual editing
+ * and a button [...] next to it
+ * to call a dialog for more complex editing. Clicking the button calls virtual
+ * runDialog() method.
  * Concrete classes must implement it.
  */
-class StringDialogEditor: public QWidget
-{
+class StringDialogEditor : public QWidget {
   Q_OBJECT
 public:
   StringDialogEditor(QtProperty *property, QWidget *parent);
   ~StringDialogEditor() override;
 protected slots:
-  /// Implementations must open a dialog to edit the editor's text. If editing is successful
+  /// Implementations must open a dialog to edit the editor's text. If editing
+  /// is successful
   /// setText() and updateProperty() methods must be called.
   virtual void runDialog() = 0;
   void updateProperty();
-  void setText(const QString& txt);
-  QString getText()const;
+  void setText(const QString &txt);
+  QString getText() const;
+
 private:
-  QLineEdit* m_lineEdit;
-  QtProperty* m_property;
+  QLineEdit *m_lineEdit;
+  QtProperty *m_property;
 };
 
 #endif // STRINGDIALOGEDITORFACTORY_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringEditorFactory.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringEditorFactory.h
index 6afcef8fdc3ecf338493aeca3f68b3e2a0663c07..bc85c5d53eb03e33e80411fae7db84ac8017eb0d 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringEditorFactory.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/StringEditorFactory.h
@@ -4,13 +4,16 @@
 #include "qtpropertymanager.h"
 #include <QLineEdit>
 
-class StringEditorFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
-{
-    Q_OBJECT
+class StringEditorFactory
+    : public QtAbstractEditorFactory<QtStringPropertyManager> {
+  Q_OBJECT
 public:
-  StringEditorFactory(QObject *parent = 0): QtAbstractEditorFactory<QtStringPropertyManager>(parent){}
+  StringEditorFactory(QObject *parent = 0)
+      : QtAbstractEditorFactory<QtStringPropertyManager>(parent) {}
+
 protected:
-  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler warning
+  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler
+                                                   // warning
   void connectPropertyManager(QtStringPropertyManager *) override {}
   QWidget *createEditorForManager(QtStringPropertyManager *manager,
                                   QtProperty *property,
@@ -18,15 +21,15 @@ protected:
   void disconnectPropertyManager(QtStringPropertyManager *) override {}
 };
 
-class StringEditor: public QLineEdit
-{
+class StringEditor : public QLineEdit {
   Q_OBJECT
 public:
   StringEditor(QtProperty *property, QWidget *parent);
 protected slots:
   void updateProperty();
+
 private:
-  QtProperty* m_property;
+  QtProperty *m_property;
 };
 
 #endif // STRINGEDITORFACTORY_H
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/UserFunctionDialog.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/UserFunctionDialog.h
index 822d642ec63574428e290e9359a39fb83acab1ca..8a294dfd0928d0bd6b8c555e3062bd2fd675a995 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/UserFunctionDialog.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/UserFunctionDialog.h
@@ -11,72 +11,69 @@ class QComboBox;
 class QLineEdit;
 class QTextEdit;
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-     * A dialog for construction a user fitting function from existing components
-     */
-	  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS UserFunctionDialog : public QDialog
-    {
-      Q_OBJECT
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+ * A dialog for construction a user fitting function from existing components
+ */
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS UserFunctionDialog : public QDialog {
+  Q_OBJECT
 
-    public:
-      UserFunctionDialog(QWidget *parent=NULL,const QString& formula = "");
-      ~UserFunctionDialog() override;
-      QStringList categories()const;
-      QString getFormula()const{return m_uiForm.teUserFunction->toPlainText();}
+public:
+  UserFunctionDialog(QWidget *parent = NULL, const QString &formula = "");
+  ~UserFunctionDialog() override;
+  QStringList categories() const;
+  QString getFormula() const { return m_uiForm.teUserFunction->toPlainText(); }
 
-    private slots:
-      void selectCategory(const QString& cat);
-      void selectFunction(const QString& fun);
-      void addExpression();
-      void saveFunction();
-      void removeCurrentFunction();
-      void updateCategories();
-      void updateFunction();
-      void helpClicked();
+private slots:
+  void selectCategory(const QString &cat);
+  void selectFunction(const QString &fun);
+  void addExpression();
+  void saveFunction();
+  void removeCurrentFunction();
+  void updateCategories();
+  void updateFunction();
+  void helpClicked();
 
-    private:
-      bool eventFilter(QObject *obj, QEvent *ev) override;
+private:
+  bool eventFilter(QObject *obj, QEvent *ev) override;
 
-      void loadFunctions();
-      void checkParameters(QString& expr);
-      QSet<QString> categoryNames()const;
-      QSet<QString> functionNames(const QString& cat)const;
-      QString getCurrentCategory()const;
-      QString getFunction(const QString& cat,const QString& fun)const;
-      QString getComment(const QString& cat,const QString& fun)const;
-      void setFunction(const QString& cat,const QString& fun,const QString& expr,const QString& comment = "");
-      bool isBuiltin(const QString& cat)const;
-      void saveToFile();
+  void loadFunctions();
+  void checkParameters(QString &expr);
+  QSet<QString> categoryNames() const;
+  QSet<QString> functionNames(const QString &cat) const;
+  QString getCurrentCategory() const;
+  QString getFunction(const QString &cat, const QString &fun) const;
+  QString getComment(const QString &cat, const QString &fun) const;
+  void setFunction(const QString &cat, const QString &fun, const QString &expr,
+                   const QString &comment = "");
+  bool isBuiltin(const QString &cat) const;
+  void saveToFile();
 
-      /// User interface elements
-      Ui::UserFunctionDialog m_uiForm;
+  /// User interface elements
+  Ui::UserFunctionDialog m_uiForm;
 
-      /// Container for prerecorded functions: key = category.name, value = formula
-      /// Records with key = category.name.comment contain comments to corresponding functions
-      QMap<QString,QString> m_funs;
+  /// Container for prerecorded functions: key = category.name, value = formula
+  /// Records with key = category.name.comment contain comments to corresponding
+  /// functions
+  QMap<QString, QString> m_funs;
+};
 
-	  };
+/**
+ * A dialog to enter a category and function name for a new function for saving
+ */
+class InputFunctionNameDialog : public QDialog {
+  Q_OBJECT
+public:
+  InputFunctionNameDialog(QWidget *parent, const QString &category);
+  void getFunctionName(QString &category, QString &name, QString &comment);
 
-    /**
-     * A dialog to enter a category and function name for a new function for saving
-     */
-    class InputFunctionNameDialog: public QDialog
-    {
-      Q_OBJECT
-    public:
-      InputFunctionNameDialog(QWidget *parent,const QString& category);
-      void getFunctionName(QString& category,QString& name,QString& comment);
-    private:
-      QComboBox* m_category;
-      QLineEdit* m_name;
-      QTextEdit* m_comment;
-    };
-
-  }
+private:
+  QComboBox *m_category;
+  QLineEdit *m_name;
+  QTextEdit *m_comment;
+};
+}
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_USERFUNCTIONDIALOG_H_
+#endif // MANTIDQTMANTIDWIDGETS_USERFUNCTIONDIALOG_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
index 8b5f75125f4f38d803ac495ff59bb20ad1ad30fa..c56f3eb37e41e43f18b04aff89b846b1da7fe852 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
@@ -9,4 +9,4 @@
 #define EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DLLImport
 #endif /* IN_MANTIDQT_MANTIDWIDGETS */
 
-#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+#endif // MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceEditorFactory.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceEditorFactory.h
index 77859e469f7e72f00fbf27ca9c6556ce493d9f49..19b7cdc988370524cf6f5b443631f047f87bc4ed 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceEditorFactory.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceEditorFactory.h
@@ -4,18 +4,19 @@
 #include "qtpropertymanager.h"
 #include "MantidQtMantidWidgets/WorkspaceSelector.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-class WorkspaceEditorFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
-{
-    Q_OBJECT
+class WorkspaceEditorFactory
+    : public QtAbstractEditorFactory<QtStringPropertyManager> {
+  Q_OBJECT
 public:
-  WorkspaceEditorFactory(QObject *parent = 0): QtAbstractEditorFactory<QtStringPropertyManager>(parent){}
+  WorkspaceEditorFactory(QObject *parent = 0)
+      : QtAbstractEditorFactory<QtStringPropertyManager>(parent) {}
+
 protected:
-  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler warning
+  using QtAbstractEditorFactoryBase::createEditor; // Avoid Intel compiler
+                                                   // warning
   void connectPropertyManager(QtStringPropertyManager *) override {}
   QWidget *createEditorForManager(QtStringPropertyManager *manager,
                                   QtProperty *property,
@@ -23,17 +24,16 @@ protected:
   void disconnectPropertyManager(QtStringPropertyManager *) override {}
 };
 
-class WorkspaceEditor: public WorkspaceSelector
-{
+class WorkspaceEditor : public WorkspaceSelector {
   Q_OBJECT
 public:
   WorkspaceEditor(QtProperty *property, QWidget *parent);
 protected slots:
-  void updateProperty(const QString& text);
+  void updateProperty(const QString &text);
+
 private:
-  QtProperty* m_property;
+  QtProperty *m_property;
 };
-
 }
 }
 
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
index b94ea1f21ef5d1f403e2ef8f536e357d5829e8f1..5556ba18f057efb782ecc2336c28f5e7907eaa54 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
@@ -10,128 +10,138 @@
 #include <Poco/NObserver.h>
 
 // Forward declarations
-namespace Mantid
-{
-namespace API
-{
-  class Algorithm;
+namespace Mantid {
+namespace API {
+class Algorithm;
 }
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  /** 
-  This class defines a widget for selecting a workspace present in the AnalysisDataService
-    
-  Subscribes to the WorkspaceAddNotification and WorkspaceDeleteNotification from the ADS.
-
-  Types of workspace to show can be restricted in several ways:
-
-   * By listing allowed WorkspaceIDs to show (Workspace2D, TableWorkspace, etc)
-   * By deciding whether or not to show "hidden" workspaces (identified with a double underscore at the start of the
-            workspace name
-   * By providing a suffix that the workspace name must have
-   * By giving the name of an algorithm, each workspace will be validated as an input to the workspaces first input WorkspaceProperty
-
-  @author Michael Whitty
-  @date 23/02/2011
-
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-  This file is part of Mantid.
-
-  Mantid is free software; you can redistribute it and/or modify
-  it under the terms of the GNU General Public License as published by
-  the Free Software Foundation; either version 3 of the License, or
-  (at your option) any later version.
-
-  Mantid is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-  GNU General Public License for more details.
-
-  You should have received a copy of the GNU General Public License
-  along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-  File change history is stored at: <https://github.com/mantidproject/mantid>
-  Code Documentation is available at: <http://doxygen.mantidproject.org>    
-  */
-  class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS WorkspaceSelector : public QComboBox
-  {
-    Q_OBJECT
-    
-    Q_PROPERTY(QStringList WorkspaceTypes READ getWorkspaceTypes WRITE setWorkspaceTypes)
-    Q_PROPERTY(bool ShowHidden READ showHiddenWorkspaces WRITE showHiddenWorkspaces)
-    Q_PROPERTY(bool Optional READ isOptional WRITE setOptional)
-    Q_PROPERTY(QStringList Suffix READ getSuffixes WRITE setSuffixes)
-    Q_PROPERTY(QString Algorithm READ getValidatingAlgorithm WRITE setValidatingAlgorithm)
-    friend class DataSelector;
-  public:
-    /// Default Constructor
-    WorkspaceSelector(QWidget *parent = NULL, bool init = true);
-    /// Destructor
-    ~WorkspaceSelector() override;
-
-    QStringList getWorkspaceTypes() const;
-    void setWorkspaceTypes(const QStringList & types);
-    bool showHiddenWorkspaces() const;
-    void showHiddenWorkspaces(bool show);
-    bool isOptional() const;
-    void setOptional(bool optional);
-    QStringList getSuffixes() const;
-    void setSuffixes(const QStringList & suffix);
-    QString getValidatingAlgorithm() const;
-    void setValidatingAlgorithm(const QString & algName);
-    bool isValid() const;
-    void refresh();
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+This class defines a widget for selecting a workspace present in the
+AnalysisDataService
+
+Subscribes to the WorkspaceAddNotification and WorkspaceDeleteNotification from
+the ADS.
+
+Types of workspace to show can be restricted in several ways:
+
+ * By listing allowed WorkspaceIDs to show (Workspace2D, TableWorkspace, etc)
+ * By deciding whether or not to show "hidden" workspaces (identified with a
+double underscore at the start of the
+          workspace name
+ * By providing a suffix that the workspace name must have
+ * By giving the name of an algorithm, each workspace will be validated as an
+input to the workspaces first input WorkspaceProperty
+
+@author Michael Whitty
+@date 23/02/2011
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS WorkspaceSelector : public QComboBox {
+  Q_OBJECT
+
+  Q_PROPERTY(QStringList WorkspaceTypes READ getWorkspaceTypes WRITE
+                 setWorkspaceTypes)
+  Q_PROPERTY(bool ShowHidden READ showHiddenWorkspaces WRITE
+                 showHiddenWorkspaces)
+  Q_PROPERTY(bool Optional READ isOptional WRITE setOptional)
+  Q_PROPERTY(QStringList Suffix READ getSuffixes WRITE setSuffixes)
+  Q_PROPERTY(QString Algorithm READ getValidatingAlgorithm WRITE
+                 setValidatingAlgorithm)
+  friend class DataSelector;
+
+public:
+  /// Default Constructor
+  WorkspaceSelector(QWidget *parent = NULL, bool init = true);
+  /// Destructor
+  ~WorkspaceSelector() override;
+
+  QStringList getWorkspaceTypes() const;
+  void setWorkspaceTypes(const QStringList &types);
+  bool showHiddenWorkspaces() const;
+  void showHiddenWorkspaces(bool show);
+  bool isOptional() const;
+  void setOptional(bool optional);
+  QStringList getSuffixes() const;
+  void setSuffixes(const QStringList &suffix);
+  QString getValidatingAlgorithm() const;
+  void setValidatingAlgorithm(const QString &algName);
+  bool isValid() const;
+  void refresh();
 
 signals:
-    void emptied();
-
-  private:
-    void handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf);
-    void handleRemEvent(Mantid::API::WorkspacePostDeleteNotification_ptr pNf);
-    void handleClearEvent(Mantid::API::ClearADSNotification_ptr pNf);
-    void handleRenameEvent(Mantid::API::WorkspaceRenameNotification_ptr pNf);
-    void handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf);
-
-    bool checkEligibility(const QString & name, Mantid::API::Workspace_sptr object) const;
-    bool hasValidSuffix(const QString& name) const;
-      
-  protected:
-      //Method for handling drop events
-    void dropEvent(QDropEvent *) override;
-      //called when a drag event enters the class
-    void dragEnterEvent(QDragEnterEvent *) override;
-
-  private:
-    /// Poco Observers for ADS Notifications
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceAddNotification> m_addObserver;
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspacePostDeleteNotification> m_remObserver;
-    Poco::NObserver<WorkspaceSelector, Mantid::API::ClearADSNotification> m_clearObserver;
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceRenameNotification> m_renameObserver;
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceAfterReplaceNotification> m_replaceObserver;
-
-
-    bool m_init;
-
-    /// A list of workspace types that should be shown in the ComboBox
-    QStringList m_workspaceTypes;
-    /// Whether to show "hidden" workspaces
-    bool m_showHidden;
-    bool m_optional; ///< Whether to add an extra empty entry to the combobox
-    // suffix
-    QStringList m_suffix;
-    QString m_algName;
-    QString m_algPropName;
-
-    // Algorithm to validate against
-    boost::shared_ptr<Mantid::API::Algorithm> m_algorithm;
-  };
-
+  void emptied();
+
+private:
+  void handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf);
+  void handleRemEvent(Mantid::API::WorkspacePostDeleteNotification_ptr pNf);
+  void handleClearEvent(Mantid::API::ClearADSNotification_ptr pNf);
+  void handleRenameEvent(Mantid::API::WorkspaceRenameNotification_ptr pNf);
+  void
+  handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf);
+
+  bool checkEligibility(const QString &name,
+                        Mantid::API::Workspace_sptr object) const;
+  bool hasValidSuffix(const QString &name) const;
+
+protected:
+  // Method for handling drop events
+  void dropEvent(QDropEvent *) override;
+  // called when a drag event enters the class
+  void dragEnterEvent(QDragEnterEvent *) override;
+
+private:
+  /// Poco Observers for ADS Notifications
+  Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceAddNotification>
+      m_addObserver;
+  Poco::NObserver<WorkspaceSelector,
+                  Mantid::API::WorkspacePostDeleteNotification> m_remObserver;
+  Poco::NObserver<WorkspaceSelector, Mantid::API::ClearADSNotification>
+      m_clearObserver;
+  Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceRenameNotification>
+      m_renameObserver;
+  Poco::NObserver<WorkspaceSelector,
+                  Mantid::API::WorkspaceAfterReplaceNotification>
+      m_replaceObserver;
+
+  bool m_init;
+
+  /// A list of workspace types that should be shown in the ComboBox
+  QStringList m_workspaceTypes;
+  /// Whether to show "hidden" workspaces
+  bool m_showHidden;
+  bool m_optional; ///< Whether to add an extra empty entry to the combobox
+  // suffix
+  QStringList m_suffix;
+  QString m_algName;
+  QString m_algPropName;
+
+  // Algorithm to validate against
+  boost::shared_ptr<Mantid::API::Algorithm> m_algorithm;
+};
 }
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
+#endif // MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pqHelpWindow.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pqHelpWindow.h
index 2714b49337b986d4e561cb5fced8cf206272cb92..064fc415a3faa8218334f7186a0b05129b525fec 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pqHelpWindow.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pqHelpWindow.h
@@ -7,8 +7,8 @@
    All rights reserved.
 
    ParaView is a free software; you can redistribute it and/or modify it
-   under the terms of the ParaView license version 1.2. 
-   
+   under the terms of the ParaView license version 1.2.
+
    See License_v1.2.txt for the full ParaView license.
    A copy of this license can be obtained by contacting
    Kitware Inc.
@@ -29,7 +29,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 ========================================================================*/
-#ifndef __pqHelpWindow_h 
+#ifndef __pqHelpWindow_h
 #define __pqHelpWindow_h
 
 #include <QMainWindow>
@@ -43,44 +43,45 @@ class QWebView;
 
 /// pqHelpWindow provides a assistant-like window  for showing help provided by
 /// a QHelpEngine.
-class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS pqHelpWindow : public QMainWindow
-{
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS pqHelpWindow : public QMainWindow {
   Q_OBJECT
   typedef QMainWindow Superclass;
+
 public:
-  pqHelpWindow(QHelpEngine* engine,
-    QWidget* parent=0, Qt::WindowFlags flags=0);
+  pqHelpWindow(QHelpEngine *engine, QWidget *parent = 0,
+               Qt::WindowFlags flags = 0);
   ~pqHelpWindow() override;
 
 public slots:
   /// Requests showing of a particular page. The url must begin with "qthelp:"
   /// scheme when referring to pages from the help files.
-  virtual void showPage(const QString& url);
-  virtual void showPage(const QUrl& url);
+  virtual void showPage(const QString &url);
+  virtual void showPage(const QUrl &url);
 
   /// Tires to locate a file name index.html in the given namespace and then
   /// shows that page.
-  virtual void showHomePage(const QString& namespace_name);
+  virtual void showHomePage(const QString &namespace_name);
   virtual void showHomePage();
 
 signals:
   /// fired to relay warning messages from the help system.
-  void helpWarnings(const QString&);
+  void helpWarnings(const QString &);
 
 protected slots:
   void search();
-  void linkHovered(const QString & link, const QString & title, const QString & textContent);
+  void linkHovered(const QString &link, const QString &title,
+                   const QString &textContent);
   void updateNavButtons();
 
 protected:
-  QHelpEngine* m_helpEngine;
-  QWebView* m_browser;
-  QToolButton* m_forward;
-  QToolButton* m_backward;
+  QHelpEngine *m_helpEngine;
+  QWebView *m_browser;
+  QToolButton *m_forward;
+  QToolButton *m_backward;
 
 private:
   Q_DISABLE_COPY(pqHelpWindow)
-  void errorMissingPage(const QUrl& url);
+  void errorMissingPage(const QUrl &url);
 
   class pqNetworkAccessManager;
   friend class pqNetworkAccessManager;
diff --git a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pythonCalc.h b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pythonCalc.h
index 0573307b948984f4f6620cb6aaeddc7e1c8fc8ad..39a3090b4f30e6b637c6efd20f0b20a951c3929e 100644
--- a/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pythonCalc.h
+++ b/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/pythonCalc.h
@@ -12,39 +12,42 @@
 #include <map>
 #include <climits>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {    
-	class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS pythonCalc : public API::MantidWidget
-    {
-      Q_OBJECT
-	  
-    public:
-      const QString& python() const;
-	    /** Allows access to m_fails, the list of any validation errors
-	    *  return the map is empty if there were no errors, otherwise, the keys are the internal names of the controls, the values the errors
-	    */
-	    QString checkNoErrors(const QHash<const QWidget * const, QLabel *> &validLbls) const;
-	  
-	    QString run();
-    
-	protected:
-      pythonCalc(QWidget *interface);
-      ///this will store the executable python code when it is generated
-      QString m_pyScript;
-      ///stores the namees of controls with invalid entries as the keys and a discription of the error as the associated value
-      std::map<const QWidget * const , std::string> m_fails;
-  
-      virtual void appendFile(const QString &pythonFile);
-      virtual void loadFile(const QString &pythonFile);
-
-      void LEChkCp(QString pythonMark, const QLineEdit * const userVal, Mantid::Kernel::Property * const check);
-      std::string replaceErrsFind(QString pythonMark, const QString &setting, Mantid::Kernel::Property * const check);
-
-      void appendChk(const QLineEdit * const userVal, Mantid::Kernel::Property * const check);
-    };
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS pythonCalc : public API::MantidWidget {
+  Q_OBJECT
+
+public:
+  const QString &python() const;
+  /** Allows access to m_fails, the list of any validation errors
+  *  return the map is empty if there were no errors, otherwise, the keys are
+  * the internal names of the controls, the values the errors
+  */
+  QString
+  checkNoErrors(const QHash<const QWidget *const, QLabel *> &validLbls) const;
+
+  QString run();
+
+protected:
+  pythonCalc(QWidget *interface);
+  /// this will store the executable python code when it is generated
+  QString m_pyScript;
+  /// stores the namees of controls with invalid entries as the keys and a
+  /// discription of the error as the associated value
+  std::map<const QWidget *const, std::string> m_fails;
+
+  virtual void appendFile(const QString &pythonFile);
+  virtual void loadFile(const QString &pythonFile);
+
+  void LEChkCp(QString pythonMark, const QLineEdit *const userVal,
+               Mantid::Kernel::Property *const check);
+  std::string replaceErrsFind(QString pythonMark, const QString &setting,
+                              Mantid::Kernel::Property *const check);
+
+  void appendChk(const QLineEdit *const userVal,
+                 Mantid::Kernel::Property *const check);
+};
+}
 }
 
-#endif //MANTIDQTMANTIDWIDGETS_PYTHONCALC_H_
+#endif // MANTIDQTMANTIDWIDGETS_PYTHONCALC_H_
diff --git a/MantidQt/MantidWidgets/src/AlgorithmSelectorWidget.cpp b/MantidQt/MantidWidgets/src/AlgorithmSelectorWidget.cpp
index e05e545cfd6574ca6528ba5f6ed443209fa7690a..e3ee96b4d68d542f4688ce91330f4a756a026196 100644
--- a/MantidQt/MantidWidgets/src/AlgorithmSelectorWidget.cpp
+++ b/MantidQt/MantidWidgets/src/AlgorithmSelectorWidget.cpp
@@ -7,427 +7,396 @@
 using namespace Mantid::Kernel;
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  AlgorithmSelectorWidget::AlgorithmSelectorWidget(QWidget *parent)
-  : QWidget(parent), m_tree(NULL), m_findAlg(NULL), m_execButton(NULL),
-    m_updateObserver(*this, &AlgorithmSelectorWidget::handleAlgorithmFactoryUpdate),
-    m_updateInProgress(false)
-  {
-    QHBoxLayout * buttonLayout = new QHBoxLayout();
-
-    m_tree = new AlgorithmTreeWidget(this);
-    m_tree->setHeaderLabel("Algorithms");
-    connect(m_tree,SIGNAL(itemSelectionChanged()),
-        this,SLOT(treeSelectionChanged()));
-    connect(m_tree,SIGNAL(executeAlgorithm(const QString &, int)),
-        this,SLOT(executeSelected()));
-
-    m_findAlg = new FindAlgComboBox;
-    m_findAlg->setEditable(true);
-    m_findAlg->completer()->setCompletionMode(QCompleter::PopupCompletion);
-
-    // Make the algorithm drop down use all the sapce it can horizontally
-    QSizePolicy expandHoriz;
-    expandHoriz.setHorizontalPolicy(QSizePolicy::Expanding);
-    m_findAlg->setSizePolicy(expandHoriz);
-
-    connect(m_findAlg,SIGNAL(enterPressed()),
-        this,SLOT(executeSelected()));
-    connect(m_findAlg,SIGNAL(editTextChanged(const QString&)),
-        this,SLOT(findAlgTextChanged(const QString&)));
-
-    m_execButton = new QPushButton("Execute");
-    connect(m_execButton,SIGNAL(clicked()),
-        this,SLOT(executeSelected()));
-    buttonLayout->addWidget(m_execButton);
-
-    buttonLayout->addWidget(m_findAlg);
-
-    // Layout the tree and combo box
-    QVBoxLayout *layout = new QVBoxLayout(this);
-    //this->setLayout(layout);
-    layout->addLayout(buttonLayout);
-    layout->addWidget(m_tree);
-
-    // The poco notification will be dispatched from the callers thread but we need to
-    // make sure the updates to the widgets happen on the GUI thread. Dispatching
-    // through a Qt signal will make sure it is in the correct thread.
-    AlgorithmFactory::Instance().notificationCenter.addObserver(m_updateObserver);
-    connect(this, SIGNAL(algorithmFactoryUpdateReceived()), this, SLOT(update()));
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  AlgorithmSelectorWidget::~AlgorithmSelectorWidget()
-  {
-    AlgorithmFactory::Instance().notificationCenter.removeObserver(m_updateObserver);
-  }
-  
-
-  /** Is the the execute button visible */
-  bool AlgorithmSelectorWidget::showExecuteButton() const
-  {
-    return m_execButton->isVisible();
-  }
-
-  /** Show/hide the execute button */
-  void AlgorithmSelectorWidget::showExecuteButton(const bool val)
-  {
-    m_execButton->setVisible(val);
-  }
-
-  //---------------------------------------------------------------------------
-  /** Update the lists of algorithms */
-  void AlgorithmSelectorWidget::update()
-  {
-    m_updateInProgress = true;
-    m_findAlg->update();
-    m_tree->update();
-    m_updateInProgress = false;
-  }
-
-
-  //---------------------------------------------------------------------------
-  /** Slot called to execute whatever is the selected algorithm
-   **/
-  void AlgorithmSelectorWidget::executeSelected() {
-    auto alg = this->getSelectedAlgorithm();
-    if (!alg.name.isEmpty()) {
-      emit executeAlgorithm(alg.name, alg.version);
-    }
-  }
-
-  //---------------------------------------------------------------------------
-  /** Show the selection in the tree when it changes in the combo */
-  void AlgorithmSelectorWidget::findAlgTextChanged(const QString& text)
-  {
-    int i = m_findAlg->findText(text,Qt::MatchFixedString);
-    if (i >= 0) m_findAlg->setCurrentIndex(i);
-    // De-select from the tree
-    m_tree->blockSignals(true);
-    m_tree->setCurrentIndex(QModelIndex());
-    m_tree->blockSignals(false);
-
-    // Emit the signal
-    auto alg = this->getSelectedAlgorithm();
-    emit algorithmSelectionChanged(alg.name, alg.version);
-  }
-
-  //---------------------------------------------------------------------------
-  /** Show the selection in the combo when it changes in the tree */
-  void AlgorithmSelectorWidget::treeSelectionChanged()
-  {
-    auto alg = this->getSelectedAlgorithm();
-    // Select in the combo box
-    m_findAlg->blockSignals(true);
-    m_findAlg->setCurrentIndex(
-        m_findAlg->findText(alg.name, Qt::MatchFixedString));
-    m_findAlg->blockSignals(false);
-    // Emit the signal
-    emit algorithmSelectionChanged(alg.name, alg.version);
+namespace MantidQt {
+namespace MantidWidgets {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+AlgorithmSelectorWidget::AlgorithmSelectorWidget(QWidget *parent)
+    : QWidget(parent), m_tree(NULL), m_findAlg(NULL), m_execButton(NULL),
+      m_updateObserver(*this,
+                       &AlgorithmSelectorWidget::handleAlgorithmFactoryUpdate),
+      m_updateInProgress(false) {
+  QHBoxLayout *buttonLayout = new QHBoxLayout();
+
+  m_tree = new AlgorithmTreeWidget(this);
+  m_tree->setHeaderLabel("Algorithms");
+  connect(m_tree, SIGNAL(itemSelectionChanged()), this,
+          SLOT(treeSelectionChanged()));
+  connect(m_tree, SIGNAL(executeAlgorithm(const QString &, int)), this,
+          SLOT(executeSelected()));
+
+  m_findAlg = new FindAlgComboBox;
+  m_findAlg->setEditable(true);
+  m_findAlg->completer()->setCompletionMode(QCompleter::PopupCompletion);
+
+  // Make the algorithm drop down use all the sapce it can horizontally
+  QSizePolicy expandHoriz;
+  expandHoriz.setHorizontalPolicy(QSizePolicy::Expanding);
+  m_findAlg->setSizePolicy(expandHoriz);
+
+  connect(m_findAlg, SIGNAL(enterPressed()), this, SLOT(executeSelected()));
+  connect(m_findAlg, SIGNAL(editTextChanged(const QString &)), this,
+          SLOT(findAlgTextChanged(const QString &)));
+
+  m_execButton = new QPushButton("Execute");
+  connect(m_execButton, SIGNAL(clicked()), this, SLOT(executeSelected()));
+  buttonLayout->addWidget(m_execButton);
+
+  buttonLayout->addWidget(m_findAlg);
+
+  // Layout the tree and combo box
+  QVBoxLayout *layout = new QVBoxLayout(this);
+  // this->setLayout(layout);
+  layout->addLayout(buttonLayout);
+  layout->addWidget(m_tree);
+
+  // The poco notification will be dispatched from the callers thread but we
+  // need to
+  // make sure the updates to the widgets happen on the GUI thread. Dispatching
+  // through a Qt signal will make sure it is in the correct thread.
+  AlgorithmFactory::Instance().notificationCenter.addObserver(m_updateObserver);
+  connect(this, SIGNAL(algorithmFactoryUpdateReceived()), this, SLOT(update()));
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+AlgorithmSelectorWidget::~AlgorithmSelectorWidget() {
+  AlgorithmFactory::Instance().notificationCenter.removeObserver(
+      m_updateObserver);
+}
+
+/** Is the the execute button visible */
+bool AlgorithmSelectorWidget::showExecuteButton() const {
+  return m_execButton->isVisible();
+}
+
+/** Show/hide the execute button */
+void AlgorithmSelectorWidget::showExecuteButton(const bool val) {
+  m_execButton->setVisible(val);
+}
+
+//---------------------------------------------------------------------------
+/** Update the lists of algorithms */
+void AlgorithmSelectorWidget::update() {
+  m_updateInProgress = true;
+  m_findAlg->update();
+  m_tree->update();
+  m_updateInProgress = false;
+}
+
+//---------------------------------------------------------------------------
+/** Slot called to execute whatever is the selected algorithm
+ **/
+void AlgorithmSelectorWidget::executeSelected() {
+  auto alg = this->getSelectedAlgorithm();
+  if (!alg.name.isEmpty()) {
+    emit executeAlgorithm(alg.name, alg.version);
   }
-
-  //---------------------------------------------------------------------------
-  /** Return the selected algorithm.
-   * The tree has priority. If nothing is selected in the tree,
-   * return the ComboBox selection */
-  SelectedAlgorithm AlgorithmSelectorWidget::getSelectedAlgorithm() {
-    SelectedAlgorithm alg = m_tree->getSelectedAlgorithm();
-    if (alg.name.isEmpty())
-      alg = m_findAlg->getSelectedAlgorithm();
-    return alg;
-  }
-
-  //---------------------------------------------------------------------------
-  /** Set which algorithm is currently selected. Does not fire any signals.
-   * Updates the combobox, deselects in the tree.
-   *
-   * @param algName :: name of the algorithm
-   */
-  void AlgorithmSelectorWidget::setSelectedAlgorithm(QString & algName)
-  {
-    m_findAlg->blockSignals(true);
-    m_findAlg->setCurrentIndex(m_findAlg->findText(algName,Qt::MatchFixedString));
-    m_findAlg->blockSignals(false);
-    // De-select from the tree
-    m_tree->blockSignals(true);
-    m_tree->setCurrentIndex(QModelIndex());
-    m_tree->blockSignals(false);
+}
+
+//---------------------------------------------------------------------------
+/** Show the selection in the tree when it changes in the combo */
+void AlgorithmSelectorWidget::findAlgTextChanged(const QString &text) {
+  int i = m_findAlg->findText(text, Qt::MatchFixedString);
+  if (i >= 0)
+    m_findAlg->setCurrentIndex(i);
+  // De-select from the tree
+  m_tree->blockSignals(true);
+  m_tree->setCurrentIndex(QModelIndex());
+  m_tree->blockSignals(false);
+
+  // Emit the signal
+  auto alg = this->getSelectedAlgorithm();
+  emit algorithmSelectionChanged(alg.name, alg.version);
+}
+
+//---------------------------------------------------------------------------
+/** Show the selection in the combo when it changes in the tree */
+void AlgorithmSelectorWidget::treeSelectionChanged() {
+  auto alg = this->getSelectedAlgorithm();
+  // Select in the combo box
+  m_findAlg->blockSignals(true);
+  m_findAlg->setCurrentIndex(
+      m_findAlg->findText(alg.name, Qt::MatchFixedString));
+  m_findAlg->blockSignals(false);
+  // Emit the signal
+  emit algorithmSelectionChanged(alg.name, alg.version);
+}
+
+//---------------------------------------------------------------------------
+/** Return the selected algorithm.
+ * The tree has priority. If nothing is selected in the tree,
+ * return the ComboBox selection */
+SelectedAlgorithm AlgorithmSelectorWidget::getSelectedAlgorithm() {
+  SelectedAlgorithm alg = m_tree->getSelectedAlgorithm();
+  if (alg.name.isEmpty())
+    alg = m_findAlg->getSelectedAlgorithm();
+  return alg;
+}
+
+//---------------------------------------------------------------------------
+/** Set which algorithm is currently selected. Does not fire any signals.
+ * Updates the combobox, deselects in the tree.
+ *
+ * @param algName :: name of the algorithm
+ */
+void AlgorithmSelectorWidget::setSelectedAlgorithm(QString &algName) {
+  m_findAlg->blockSignals(true);
+  m_findAlg->setCurrentIndex(
+      m_findAlg->findText(algName, Qt::MatchFixedString));
+  m_findAlg->blockSignals(false);
+  // De-select from the tree
+  m_tree->blockSignals(true);
+  m_tree->setCurrentIndex(QModelIndex());
+  m_tree->blockSignals(false);
+}
+
+/**
+ * The algorithm factory has been updated, refresh the widget
+ *
+ */
+void AlgorithmSelectorWidget::handleAlgorithmFactoryUpdate(
+    Mantid::API::AlgorithmFactoryUpdateNotification_ptr) {
+  emit algorithmFactoryUpdateReceived();
+}
+
+//============================================================================
+//============================================================================
+//============================================================================
+// Use an anonymous namespace to keep these at file scope
+namespace {
+
+bool Algorithm_descriptor_less(const Algorithm_descriptor &d1,
+                               const Algorithm_descriptor &d2) {
+  if (d1.category < d2.category)
+    return true;
+  else if (d1.category == d2.category && d1.name < d2.name)
+    return true;
+  else if (d1.category == d2.category && d1.name == d2.name &&
+           d1.version > d2.version)
+    return true;
+
+  return false;
+}
+
+bool Algorithm_descriptor_name_less(const Algorithm_descriptor &d1,
+                                    const Algorithm_descriptor &d2) {
+  return d1.name < d2.name;
+}
+}
+
+//============================================================================
+//======================= AlgorithmTreeWidget ================================
+//============================================================================
+/** Return the selected algorithm in the tree
+ * @returns :: algorithm selected by user
+ */
+SelectedAlgorithm AlgorithmTreeWidget::getSelectedAlgorithm() {
+  SelectedAlgorithm alg("", 0);
+
+  auto isCategoryName = [](const QTreeWidgetItem *item) {
+    return (item->childCount() != 0 && !item->text(0).contains(" v."));
+  };
+
+  QList<QTreeWidgetItem *> items = this->selectedItems();
+  if (items.size() > 0 && !isCategoryName(items[0])) {
+    QString str = items[0]->text(0);
+    QStringList lst = str.split(" v.");
+    alg.name = lst[0];
+    alg.version = lst[1].toInt();
   }
-
-  /**
-   * The algorithm factory has been updated, refresh the widget
-   * 
-   */
-  void AlgorithmSelectorWidget::
-  handleAlgorithmFactoryUpdate(Mantid::API::AlgorithmFactoryUpdateNotification_ptr)
-  {
-    emit algorithmFactoryUpdateReceived();
+  return alg;
+}
+
+//---------------------------------------------------------------------------
+/** SLOT called when clicking the mouse around the tree */
+void AlgorithmTreeWidget::mousePressEvent(QMouseEvent *e) {
+  if (e->button() == Qt::LeftButton) {
+    if (!itemAt(e->pos()))
+      selectionModel()->clear();
+    m_dragStartPosition = e->pos();
   }
 
-  //============================================================================
-  //============================================================================
-  //============================================================================
-  //Use an anonymous namespace to keep these at file scope
-  namespace {
-
-    bool Algorithm_descriptor_less(const Algorithm_descriptor& d1,const Algorithm_descriptor& d2)
-    {
-      if (d1.category < d2.category) return true;
-      else if (d1.category == d2.category && d1.name < d2.name) return true;
-      else if (d1.category == d2.category && d1.name == d2.name && d1.version > d2.version) return true;
-
-      return false;
-    }
-
-    bool Algorithm_descriptor_name_less(const Algorithm_descriptor& d1,const Algorithm_descriptor& d2)
-    {
-      return d1.name < d2.name;
-    }
-
+  QTreeWidget::mousePressEvent(e);
+}
+
+//---------------------------------------------------------------------------
+/** SLOT called when dragging the mouse around the tree */
+void AlgorithmTreeWidget::mouseMoveEvent(QMouseEvent *e) {
+  if (!(e->buttons() & Qt::LeftButton))
+    return;
+  if ((e->pos() - m_dragStartPosition).manhattanLength() <
+      QApplication::startDragDistance())
+    return;
+
+  // Start dragging
+  QDrag *drag = new QDrag(this);
+  QMimeData *mimeData = new QMimeData;
+
+  mimeData->setText("Algorithm");
+  drag->setMimeData(mimeData);
+
+  Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
+  (void)dropAction;
+}
+
+//---------------------------------------------------------------------------
+/** SLOT called when double-clicking on an entry in the tree */
+void AlgorithmTreeWidget::mouseDoubleClickEvent(QMouseEvent *e) {
+  auto alg = this->getSelectedAlgorithm();
+  if (!alg.name.isEmpty()) {
+    // Emit the signal that we are executing
+    emit executeAlgorithm(alg.name, alg.version);
+    return;
   }
-
-
-
-  //============================================================================
-  //======================= AlgorithmTreeWidget ================================
-  //============================================================================
-  /** Return the selected algorithm in the tree 
-   * @returns :: algorithm selected by user
-   */
-  SelectedAlgorithm AlgorithmTreeWidget::getSelectedAlgorithm() {
-    SelectedAlgorithm alg("", 0);
-
-    auto isCategoryName = [](const QTreeWidgetItem *item) {
-      return (item->childCount() != 0 && !item->text(0).contains(" v."));
-    };
-
-    QList<QTreeWidgetItem *> items = this->selectedItems();
-    if (items.size() > 0 && !isCategoryName(items[0])) {
-      QString str = items[0]->text(0);
-      QStringList lst = str.split(" v.");
-      alg.name = lst[0];
-      alg.version = lst[1].toInt();
-    }
-    return alg;
-  }
-
-  //---------------------------------------------------------------------------
-  /** SLOT called when clicking the mouse around the tree */
-  void AlgorithmTreeWidget::mousePressEvent (QMouseEvent *e)
-  {
-    if (e->button() == Qt::LeftButton)
-    {
-      if( !itemAt(e->pos()) ) selectionModel()->clear();
-      m_dragStartPosition = e->pos();
-    }
-
-    QTreeWidget::mousePressEvent(e);
-  }
-
-  //---------------------------------------------------------------------------
-  /** SLOT called when dragging the mouse around the tree */
-  void AlgorithmTreeWidget::mouseMoveEvent(QMouseEvent *e)
-  {
-    if (!(e->buttons() & Qt::LeftButton))
-      return;
-    if ((e->pos() - m_dragStartPosition).manhattanLength() < QApplication::startDragDistance())
-      return;
-
-    // Start dragging
-    QDrag *drag = new QDrag(this);
-    QMimeData *mimeData = new QMimeData;
-
-    mimeData->setText("Algorithm");
-    drag->setMimeData(mimeData);
-
-    Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
-    (void) dropAction;
-  }
-
-  //---------------------------------------------------------------------------
-  /** SLOT called when double-clicking on an entry in the tree */
-  void AlgorithmTreeWidget::mouseDoubleClickEvent(QMouseEvent *e)
-  {
-    auto alg = this->getSelectedAlgorithm();
-    if (!alg.name.isEmpty()) {
-      // Emit the signal that we are executing
-      emit executeAlgorithm(alg.name, alg.version);
-      return;
-    }
-    QTreeWidget::mouseDoubleClickEvent(e);
-  }
-
-  //---------------------------------------------------------------------------
-  /** Update the list of algos in the tree */
-  void AlgorithmTreeWidget::update()
-  {
-    this->clear();
-
-    typedef std::vector<Algorithm_descriptor> AlgNamesType;
-    AlgNamesType names = AlgorithmFactory::Instance().getDescriptors();
-
-    // sort by category/name/version to fill QTreeWidget
-    sort(names.begin(),names.end(),Algorithm_descriptor_less);
-
-    QMap<QString,QTreeWidgetItem*> categories;// keeps track of categories added to the tree
-    QMap<QString,QTreeWidgetItem*> algorithms;// keeps track of algorithms added to the tree (needed in case there are different versions of an algorithm)
-
-    for(AlgNamesType::const_iterator i=names.begin();i!=names.end();++i)
-    {
-      QString algName = QString::fromStdString(i->name);
-      QString catName = QString::fromStdString(i->category);
-      QStringList subCats = catName.split('\\');
-      if (!categories.contains(catName))
-      {
-        if (subCats.size() == 1)
-        {
-          QTreeWidgetItem *catItem = new QTreeWidgetItem(QStringList(catName));
-          categories.insert(catName,catItem);
-          this->addTopLevelItem(catItem);
-        }
-        else
-        {
-          QString cn = subCats[0];
-          QTreeWidgetItem *catItem = NULL;
-          int n = subCats.size();
-          for(int j=0;j<n;j++)
-          {
-            if (categories.contains(cn))
-            {
-              catItem = categories[cn];
-            }
-            else
-            {
-              QTreeWidgetItem *newCatItem = new QTreeWidgetItem(QStringList(subCats[j]));
-              categories.insert(cn,newCatItem);
-              if (!catItem)
-              {
-                this->addTopLevelItem(newCatItem);
-              }
-              else
-              {
-                catItem->addChild(newCatItem);
-              }
-              catItem = newCatItem;
+  QTreeWidget::mouseDoubleClickEvent(e);
+}
+
+//---------------------------------------------------------------------------
+/** Update the list of algos in the tree */
+void AlgorithmTreeWidget::update() {
+  this->clear();
+
+  typedef std::vector<Algorithm_descriptor> AlgNamesType;
+  AlgNamesType names = AlgorithmFactory::Instance().getDescriptors();
+
+  // sort by category/name/version to fill QTreeWidget
+  sort(names.begin(), names.end(), Algorithm_descriptor_less);
+
+  QMap<QString, QTreeWidgetItem *>
+      categories; // keeps track of categories added to the tree
+  QMap<QString, QTreeWidgetItem *> algorithms; // keeps track of algorithms
+                                               // added to the tree (needed in
+                                               // case there are different
+                                               // versions of an algorithm)
+
+  for (AlgNamesType::const_iterator i = names.begin(); i != names.end(); ++i) {
+    QString algName = QString::fromStdString(i->name);
+    QString catName = QString::fromStdString(i->category);
+    QStringList subCats = catName.split('\\');
+    if (!categories.contains(catName)) {
+      if (subCats.size() == 1) {
+        QTreeWidgetItem *catItem = new QTreeWidgetItem(QStringList(catName));
+        categories.insert(catName, catItem);
+        this->addTopLevelItem(catItem);
+      } else {
+        QString cn = subCats[0];
+        QTreeWidgetItem *catItem = NULL;
+        int n = subCats.size();
+        for (int j = 0; j < n; j++) {
+          if (categories.contains(cn)) {
+            catItem = categories[cn];
+          } else {
+            QTreeWidgetItem *newCatItem =
+                new QTreeWidgetItem(QStringList(subCats[j]));
+            categories.insert(cn, newCatItem);
+            if (!catItem) {
+              this->addTopLevelItem(newCatItem);
+            } else {
+              catItem->addChild(newCatItem);
             }
-            if (j != n-1) cn += "\\" + subCats[j+1];
+            catItem = newCatItem;
           }
+          if (j != n - 1)
+            cn += "\\" + subCats[j + 1];
         }
       }
-
-      QTreeWidgetItem *algItem = new QTreeWidgetItem(QStringList(algName+" v."+QString::number(i->version)));
-      QString cat_algName = catName+algName;
-      if (!algorithms.contains(cat_algName))
-      {
-        algorithms.insert(cat_algName,algItem);
-        categories[catName]->addChild(algItem);
-      }
-      else
-        algorithms[cat_algName]->addChild(algItem);
-
     }
-  }
 
-  //============================================================================
-  //============================== FindAlgComboBox =============================
-  //============================================================================
-  /** Called when the combo box for finding algorithms has a key press
-   * event  */
-  void FindAlgComboBox::keyPressEvent(QKeyEvent *e)
-  {
-    if (e->key() == Qt::Key_Return)
-    {
-      emit enterPressed();
-      return;
-    }
-    QComboBox::keyPressEvent(e);
+    QTreeWidgetItem *algItem = new QTreeWidgetItem(
+        QStringList(algName + " v." + QString::number(i->version)));
+    QString cat_algName = catName + algName;
+    if (!algorithms.contains(cat_algName)) {
+      algorithms.insert(cat_algName, algItem);
+      categories[catName]->addChild(algItem);
+    } else
+      algorithms[cat_algName]->addChild(algItem);
   }
-
-  //---------------------------------------------------------------------------
-  /** Update the list of algos in the combo box */
-  void FindAlgComboBox::update()
-  {
-    //include hidden categories in the combo list box
-    AlgNamesType names = AlgorithmFactory::Instance().getDescriptors(true);
-    addAliases(names);
-
-    // sort by algorithm names only to fill this combobox
-    sort(names.begin(),names.end(),Algorithm_descriptor_name_less);
-
-    this->clear();
-    std::string prevName = "";
-    for(AlgNamesType::const_iterator i=names.begin();i!=names.end();++i)
-    {
-      if (i->name != prevName)
-        this->addItem(QString::fromStdString(i->name));
-      prevName = i->name;
-    }
-    this->setCurrentIndex(-1);
-
+}
+
+//============================================================================
+//============================== FindAlgComboBox =============================
+//============================================================================
+/** Called when the combo box for finding algorithms has a key press
+ * event  */
+void FindAlgComboBox::keyPressEvent(QKeyEvent *e) {
+  if (e->key() == Qt::Key_Return) {
+    emit enterPressed();
+    return;
   }
-  
-  /** Adds alias entries to the list of algorithms */
-  void FindAlgComboBox::addAliases(AlgNamesType& algNamesList)
-  {
-    AlgNamesType aliasList;
-    for(AlgNamesType::const_iterator i=algNamesList.begin();i!=algNamesList.end();++i)
-    {
-      //the alias is not empty and is not just different by case from the name
-      if ((!i->alias.empty()) && (!boost::iequals(i->alias,i->name)))
-      {
-        Algorithm_descriptor newAlias(*i);
-        newAlias.name = i->alias + " [" + i->name + "]";
-        aliasList.push_back(newAlias);
-      }
-    }
-    //add them to the list - unsorted
-    algNamesList.reserve( algNamesList.size() + aliasList.size() ); 
-    algNamesList.insert( algNamesList.end(), aliasList.begin(), aliasList.end() );
+  QComboBox::keyPressEvent(e);
+}
+
+//---------------------------------------------------------------------------
+/** Update the list of algos in the combo box */
+void FindAlgComboBox::update() {
+  // include hidden categories in the combo list box
+  AlgNamesType names = AlgorithmFactory::Instance().getDescriptors(true);
+  addAliases(names);
+
+  // sort by algorithm names only to fill this combobox
+  sort(names.begin(), names.end(), Algorithm_descriptor_name_less);
+
+  this->clear();
+  std::string prevName = "";
+  for (AlgNamesType::const_iterator i = names.begin(); i != names.end(); ++i) {
+    if (i->name != prevName)
+      this->addItem(QString::fromStdString(i->name));
+    prevName = i->name;
   }
-
-  /** if a string is for an alias convert it to the algorithm name */
-  QString FindAlgComboBox::stripAlias(const QString& text) const
-  {
-    QString retVal = text;
-    int foundOpen = text.indexOf("[");
-    if (foundOpen!=-1){
-      int foundClose=text.lastIndexOf("]");
-      if (foundClose!=-1)
-        retVal = text.mid(foundOpen+1, foundClose-foundOpen-1);
+  this->setCurrentIndex(-1);
+}
+
+/** Adds alias entries to the list of algorithms */
+void FindAlgComboBox::addAliases(AlgNamesType &algNamesList) {
+  AlgNamesType aliasList;
+  for (AlgNamesType::const_iterator i = algNamesList.begin();
+       i != algNamesList.end(); ++i) {
+    // the alias is not empty and is not just different by case from the name
+    if ((!i->alias.empty()) && (!boost::iequals(i->alias, i->name))) {
+      Algorithm_descriptor newAlias(*i);
+      newAlias.name = i->alias + " [" + i->name + "]";
+      aliasList.push_back(newAlias);
     }
-    return retVal;
   }
-
-  //---------------------------------------------------------------------------
-  /** Return the selected algorithm */
-  SelectedAlgorithm FindAlgComboBox::getSelectedAlgorithm()
+  // add them to the list - unsorted
+  algNamesList.reserve(algNamesList.size() + aliasList.size());
+  algNamesList.insert(algNamesList.end(), aliasList.begin(), aliasList.end());
+}
+
+/** if a string is for an alias convert it to the algorithm name */
+QString FindAlgComboBox::stripAlias(const QString &text) const {
+  QString retVal = text;
+  int foundOpen = text.indexOf("[");
+  if (foundOpen != -1) {
+    int foundClose = text.lastIndexOf("]");
+    if (foundClose != -1)
+      retVal = text.mid(foundOpen + 1, foundClose - foundOpen - 1);
+  }
+  return retVal;
+}
+
+//---------------------------------------------------------------------------
+/** Return the selected algorithm */
+SelectedAlgorithm FindAlgComboBox::getSelectedAlgorithm() {
+  // typed selection
+  QString typedText =
+      this->currentText().trimmed(); // text as typed in the combobox
+  if (!typedText.isEmpty())          // if the text is not empty
   {
-    //typed selection
-    QString typedText =
-        this->currentText().trimmed(); // text as typed in the combobox
-    if (!typedText.isEmpty()) // if the text is not empty
-    {
-      //find the closest matching entry
-      int matchedIndex = this->findText(typedText,Qt::MatchStartsWith);
-      if (matchedIndex > -1)
-      {
-        typedText = this->itemText(matchedIndex); //text in the combobox at the matched index
-        typedText = stripAlias(typedText);
-      }
+    // find the closest matching entry
+    int matchedIndex = this->findText(typedText, Qt::MatchStartsWith);
+    if (matchedIndex > -1) {
+      typedText = this->itemText(
+          matchedIndex); // text in the combobox at the matched index
+      typedText = stripAlias(typedText);
     }
-    return SelectedAlgorithm(typedText, -1);
   }
-
+  return SelectedAlgorithm(typedText, -1);
+}
 
 } // namespace Mantid
 } // namespace MantidWidgets
diff --git a/MantidQt/MantidWidgets/src/CatalogHelper.cpp b/MantidQt/MantidWidgets/src/CatalogHelper.cpp
index 6f8d1977f4a5d432950ce63e0fe49182cbc07aa7..7792b53f5f80a0b102c2ba9de140a430ef6f79af 100644
--- a/MantidQt/MantidWidgets/src/CatalogHelper.cpp
+++ b/MantidQt/MantidWidgets/src/CatalogHelper.cpp
@@ -9,340 +9,331 @@
 #include <QCoreApplication>
 #include <QTime>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-
-    /**
-     * Obtain a list of instruments for specified catalogs based on session information.
-     * @param sessionIDs :: The sessions information of each active catalog.
-     * @return A vector containing the list of all instruments available.
-     */
-    const std::vector<std::string> CatalogHelper::getInstrumentList(
-        const std::vector<std::string> &sessionIDs)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogListInstruments");
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-
-      // If ONE or ALL catalogs are selected to search through use no session (empty).
-      // This will invoke the compositeCatalog instead of specific catalogs for each session.
-      if (session.size() == sessionIDs.size())
-      {
-        executeAsynchronously(catalogAlgorithm);
-        return catalogAlgorithm->getProperty("InstrumentList");
-      }
-      else
-      {
-        // Use catalogs for the specified sessions.
-        for (unsigned i = 0; i < sessionIDs.size(); ++i)
-        {
-          catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
-          executeAsynchronously(catalogAlgorithm);
-        }
-        // Return the vector containing the list of instruments available.
-        return catalogAlgorithm->getProperty("InstrumentList");
-      }
-    }
-
-    /**
-     * Obtain the list of investigation types for specified catalogs based on session information.
-     * @param sessionIDs :: The sessions information of each active catalog.
-     * @return A vector containing the list of all investigation types available.
-     */
-    const std::vector<std::string> CatalogHelper::getInvestigationTypeList(
-        const std::vector<std::string> &sessionIDs)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogListInvestigationTypes");
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-
-      if (session.size() == sessionIDs.size())
-      {
-        executeAsynchronously(catalogAlgorithm);
-        return catalogAlgorithm->getProperty("InvestigationTypes");
-      }
-      else
-      {
-        for (unsigned i = 0; i < sessionIDs.size(); ++i)
-        {
-          catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
-          executeAsynchronously(catalogAlgorithm);
-        }
-        return catalogAlgorithm->getProperty("InvestigationTypes");
-      }
-    }
-
-    /**
-     * Search the archive with the user input terms provided and save them to a workspace ("searchResults").
-     * @param userInputFields :: A map containing all users' search fields - (key => FieldName, value => FieldValue).
-     * @param offset :: skip this many rows and start returning rows from this point.
-     * @param limit  :: limit the number of rows returned by the query.
-     * @param sessionIDs :: The sessions information of each active catalog.
-     */
-    void CatalogHelper::executeSearch(const std::map<std::string, std::string> &userInputFields,
-        const int &offset, const int &limit, const std::vector<std::string> &sessionIDs)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
-      // Set the properties to limit the number of results returned for paging purposes.
-      catalogAlgorithm->setProperty("Limit", limit);
-      catalogAlgorithm->setProperty("Offset", offset);
-      // Set the "search" properties to their related input fields.
-      setSearchProperties(catalogAlgorithm, userInputFields);
-
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-      if (session.size() == sessionIDs.size())
-      {
-        executeAsynchronously(catalogAlgorithm);
-      }
-      else
-      {
-        for (unsigned i = 0; i < sessionIDs.size(); ++i)
-        {
-          catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
-          executeAsynchronously(catalogAlgorithm);
-        }
-      }
-    }
-
-    /**
-     * The number of results returned by the search query (based on values of input fields).
-     * @param userInputFields :: A map containing the users' search input (key => FieldName, value => FieldValue).
-     * @param sessionIDs :: The sessions information of each active catalog.
-     * @return Number of results returned by the search query.
-     */
-    int64_t CatalogHelper::getNumberOfSearchResults(
-        const std::map<std::string, std::string> &userInputFields,
-        const std::vector<std::string> &sessionIDs)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
-      // Set the property to only perform a count search.
-      catalogAlgorithm->setProperty("CountOnly", true);
-      // Set the "search" properties to their related input fields.
-      setSearchProperties(catalogAlgorithm, userInputFields);
-
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-      if (session.size() == sessionIDs.size())
-      {
-        executeAsynchronously(catalogAlgorithm);
-        return catalogAlgorithm->getProperty("NumberOfSearchResults");
-      }
-      else
-      {
-        for (unsigned i = 0; i < sessionIDs.size(); ++i)
-        {
-          catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
-          executeAsynchronously(catalogAlgorithm);
-        }
-        return catalogAlgorithm->getProperty("NumberOfSearchResults");
-      }
-    }
-
-    /**
-     * Search the archives for all dataFiles related to an "investigation id" then save results to workspace ("dataFileResults").
-     * @param sessionID :: The sessions ID of the selected investigation.
-     * @param investigationId :: The investigation id to use for the search.
-     */
-    void CatalogHelper::executeGetDataFiles(const std::string &investigationId,
-        const std::string &sessionID)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogGetDataFiles");
-
-      catalogAlgorithm->setProperty("InvestigationId", investigationId);
-      catalogAlgorithm->setPropertyValue("OutputWorkspace", "__dataFileResults");
-      catalogAlgorithm->setProperty("Session", sessionID);
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+ * Obtain a list of instruments for specified catalogs based on session
+ * information.
+ * @param sessionIDs :: The sessions information of each active catalog.
+ * @return A vector containing the list of all instruments available.
+ */
+const std::vector<std::string>
+CatalogHelper::getInstrumentList(const std::vector<std::string> &sessionIDs) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogListInstruments");
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
+
+  // If ONE or ALL catalogs are selected to search through use no session
+  // (empty).
+  // This will invoke the compositeCatalog instead of specific catalogs for each
+  // session.
+  if (session.size() == sessionIDs.size()) {
+    executeAsynchronously(catalogAlgorithm);
+    return catalogAlgorithm->getProperty("InstrumentList");
+  } else {
+    // Use catalogs for the specified sessions.
+    for (unsigned i = 0; i < sessionIDs.size(); ++i) {
+      catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
       executeAsynchronously(catalogAlgorithm);
     }
-
-    /**
-     * Retrieve the path(s) to the file that was downloaded (via HTTP) or is stored in the archive.
-     * @param userSelectedFiles :: The file(s) the user has selected and wants to download.
-     * @param downloadPath      :: The location to save the datafile(s).
-     * @param sessionID :: The sessions ID of the selected investigation.
-     * @return A vector containing the paths to the file(s) the user wants.
-     */
-    const std::vector<std::string> CatalogHelper::downloadDataFiles(
-        const std::vector<std::pair<int64_t, std::string>> &userSelectedFiles,
-        const std::string &downloadPath, const std::string &sessionID)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogDownloadDataFiles");
-
-      // Prepare for the ugly!
-
-      // These two vectors are required by the "CatalogDownloadDataFiles" algorithm.
-      std::vector<int64_t> fileIDs;
-      fileIDs.reserve(userSelectedFiles.size());
-      std::vector<std::string> fileNames;
-      fileNames.reserve(userSelectedFiles.size());
-
-      // For each pair in userSelectedFiles we want to add them to their related vector to pass to the algorithm.
-      for (auto it = userSelectedFiles.begin(); it != userSelectedFiles.end(); ++it)
-      {
-        fileIDs.push_back(it->first);
-        fileNames.push_back(it->second);
-      }
-
-      // End of the ugly!
-
-      // The file IDs and file names of the data file(s) the user wants to download.
-      catalogAlgorithm->setProperty("FileIds", fileIDs);
-      catalogAlgorithm->setProperty("FileNames", fileNames);
-      catalogAlgorithm->setProperty("DownloadPath", downloadPath);
-      catalogAlgorithm->setProperty("Session", sessionID);
-
+    // Return the vector containing the list of instruments available.
+    return catalogAlgorithm->getProperty("InstrumentList");
+  }
+}
+
+/**
+ * Obtain the list of investigation types for specified catalogs based on
+ * session information.
+ * @param sessionIDs :: The sessions information of each active catalog.
+ * @return A vector containing the list of all investigation types available.
+ */
+const std::vector<std::string> CatalogHelper::getInvestigationTypeList(
+    const std::vector<std::string> &sessionIDs) {
+  auto catalogAlgorithm =
+      createCatalogAlgorithm("CatalogListInvestigationTypes");
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
+
+  if (session.size() == sessionIDs.size()) {
+    executeAsynchronously(catalogAlgorithm);
+    return catalogAlgorithm->getProperty("InvestigationTypes");
+  } else {
+    for (unsigned i = 0; i < sessionIDs.size(); ++i) {
+      catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
       executeAsynchronously(catalogAlgorithm);
-      // Return a vector containing the file paths to the files to download.
-      return (catalogAlgorithm->getProperty("FileLocations"));
     }
-
-    /**
-     * Validate each input field against the related algorithm property.
-     * @param inputFields :: The name of the input field and value of the field (key => "StartDate", value => "00/00/0000").
-     * @return The name of the input field(s) marker to update and related error to throw.
-     */
-    const std::map<std::string, std::string> CatalogHelper::validateProperties(
-        const std::map<std::string, std::string> &inputFields)
-    {
-      auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
-
-      // Holds the name of the marker to update if an error is found, and the related error message to use.
-      // E.g. key => "StartDate_err", value => "The start date for..."
-      std::map<std::string, std::string> errors;
-
-      // Validate all input elements in the map.
-      for (auto iter = inputFields.begin(); iter != inputFields.end(); ++iter)
-      {
-        try
-        {
-          catalogAlgorithm->setProperty(iter->first, iter->second);
-        } catch (std::invalid_argument&)
-        {
-          std::string documentation = propertyDocumentation(catalogAlgorithm->getProperties(),
-              iter->first);
-
-          // Add the input name + "_err" (to indicate the error marker in the GUI,
-          // rather than the input field) as the key, and the related error as the value.
-          errors.emplace(iter->first + "_err", documentation);
-        }
-      }
-      return errors;
-    }
-
-    /**
-     * Creates a time_t value from an input date ("23/06/2003") for comparison.
-     * @param inputDate :: string containing the date.
-     * @return time_t value of date
-     */
-    time_t CatalogHelper::getTimevalue(const std::string& inputDate)
-    {
-      // Prevent any possible errors.
-      if (inputDate.empty())
-        return 0;
-      // A container to hold the segments of the date.
-      std::vector<std::string> dateSegments;
-      // Split input by "/" prior to rearranging the date
-      boost::algorithm::split_regex(dateSegments, inputDate, boost::regex("/"));
-      // Reorganise the date to be ISO format.
-      std::string isoDate = dateSegments.at(2) + "-" + dateSegments.at(1) + "-" + dateSegments.at(0)
-          + " 0:00:00.000";
-      // Return the date as time_t value.
-      return Mantid::Kernel::DateAndTime(isoDate).to_time_t();
-    }
-
-    /**
-     * Opens auto-generated dialog, and executes the catalog login algorithm.
-     * Returns true if login was a success.
-     */
-    void CatalogHelper::showLoginDialog()
-    {
-      API::InterfaceManager interfaceMgr;
-      auto dlg = interfaceMgr.createDialogFromName("CatalogLogin");
-      dlg->setModal(false);
-      dlg->show();
-      dlg->raise();
-      dlg->activateWindow();
-    }
-
-    /**
-     * Creates a publishing dialog GUI and runs the publishing algorithm when "Run" is pressed.
-     */
-    void CatalogHelper::showPublishDialog()
-    {
-      API::InterfaceManager interfaceMgr;
-      auto dlg = interfaceMgr.createDialogFromName("CatalogPublish");
-      dlg->setModal(false);
-      dlg->show();
-      dlg->raise();
-      dlg->activateWindow();
+    return catalogAlgorithm->getProperty("InvestigationTypes");
+  }
+}
+
+/**
+ * Search the archive with the user input terms provided and save them to a
+ * workspace ("searchResults").
+ * @param userInputFields :: A map containing all users' search fields - (key =>
+ * FieldName, value => FieldValue).
+ * @param offset :: skip this many rows and start returning rows from this
+ * point.
+ * @param limit  :: limit the number of rows returned by the query.
+ * @param sessionIDs :: The sessions information of each active catalog.
+ */
+void CatalogHelper::executeSearch(
+    const std::map<std::string, std::string> &userInputFields,
+    const int &offset, const int &limit,
+    const std::vector<std::string> &sessionIDs) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
+  // Set the properties to limit the number of results returned for paging
+  // purposes.
+  catalogAlgorithm->setProperty("Limit", limit);
+  catalogAlgorithm->setProperty("Offset", offset);
+  // Set the "search" properties to their related input fields.
+  setSearchProperties(catalogAlgorithm, userInputFields);
+
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
+  if (session.size() == sessionIDs.size()) {
+    executeAsynchronously(catalogAlgorithm);
+  } else {
+    for (unsigned i = 0; i < sessionIDs.size(); ++i) {
+      catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
+      executeAsynchronously(catalogAlgorithm);
     }
-
-    /**
-     * Obtain the algorithm documentation for the given property.
-     * @param properties :: A list of properties for a provided algorithm.
-     * @param name       :: The name of the property to search for.
-     * @return The documentation for a given property name.
-     */
-    const std::string CatalogHelper::propertyDocumentation(
-        const std::vector<Mantid::Kernel::Property*> &properties, const std::string &name)
-    {
-      for (unsigned i = 0; i < properties.size(); i++)
-      {
-        if (properties.at(i)->name() == name)
-        {
-          return properties.at(i)->documentation();
-        }
-      }
-      return "";
+  }
+}
+
+/**
+ * The number of results returned by the search query (based on values of input
+ * fields).
+ * @param userInputFields :: A map containing the users' search input (key =>
+ * FieldName, value => FieldValue).
+ * @param sessionIDs :: The sessions information of each active catalog.
+ * @return Number of results returned by the search query.
+ */
+int64_t CatalogHelper::getNumberOfSearchResults(
+    const std::map<std::string, std::string> &userInputFields,
+    const std::vector<std::string> &sessionIDs) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
+  // Set the property to only perform a count search.
+  catalogAlgorithm->setProperty("CountOnly", true);
+  // Set the "search" properties to their related input fields.
+  setSearchProperties(catalogAlgorithm, userInputFields);
+
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
+  if (session.size() == sessionIDs.size()) {
+    executeAsynchronously(catalogAlgorithm);
+    return catalogAlgorithm->getProperty("NumberOfSearchResults");
+  } else {
+    for (unsigned i = 0; i < sessionIDs.size(); ++i) {
+      catalogAlgorithm->setProperty("Session", sessionIDs.at(i));
+      executeAsynchronously(catalogAlgorithm);
     }
-
-    /**
-     * Creates an algorithm with the provided name.
-     * @param algName :: The name of the algorithm to create.
-     * @return A shared pointer to the algorithm created.
-     */
-    Mantid::API::IAlgorithm_sptr CatalogHelper::createCatalogAlgorithm(const std::string &algName)
-    {
-      // If there is an exception we want it to be thrown.
-      return Mantid::API::AlgorithmManager::Instance().create(algName);
+    return catalogAlgorithm->getProperty("NumberOfSearchResults");
+  }
+}
+
+/**
+ * Search the archives for all dataFiles related to an "investigation id" then
+ * save results to workspace ("dataFileResults").
+ * @param sessionID :: The sessions ID of the selected investigation.
+ * @param investigationId :: The investigation id to use for the search.
+ */
+void CatalogHelper::executeGetDataFiles(const std::string &investigationId,
+                                        const std::string &sessionID) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogGetDataFiles");
+
+  catalogAlgorithm->setProperty("InvestigationId", investigationId);
+  catalogAlgorithm->setPropertyValue("OutputWorkspace", "__dataFileResults");
+  catalogAlgorithm->setProperty("Session", sessionID);
+
+  executeAsynchronously(catalogAlgorithm);
+}
+
+/**
+ * Retrieve the path(s) to the file that was downloaded (via HTTP) or is stored
+ * in the archive.
+ * @param userSelectedFiles :: The file(s) the user has selected and wants to
+ * download.
+ * @param downloadPath      :: The location to save the datafile(s).
+ * @param sessionID :: The sessions ID of the selected investigation.
+ * @return A vector containing the paths to the file(s) the user wants.
+ */
+const std::vector<std::string> CatalogHelper::downloadDataFiles(
+    const std::vector<std::pair<int64_t, std::string>> &userSelectedFiles,
+    const std::string &downloadPath, const std::string &sessionID) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogDownloadDataFiles");
+
+  // Prepare for the ugly!
+
+  // These two vectors are required by the "CatalogDownloadDataFiles" algorithm.
+  std::vector<int64_t> fileIDs;
+  fileIDs.reserve(userSelectedFiles.size());
+  std::vector<std::string> fileNames;
+  fileNames.reserve(userSelectedFiles.size());
+
+  // For each pair in userSelectedFiles we want to add them to their related
+  // vector to pass to the algorithm.
+  for (auto it = userSelectedFiles.begin(); it != userSelectedFiles.end();
+       ++it) {
+    fileIDs.push_back(it->first);
+    fileNames.push_back(it->second);
+  }
+
+  // End of the ugly!
+
+  // The file IDs and file names of the data file(s) the user wants to download.
+  catalogAlgorithm->setProperty("FileIds", fileIDs);
+  catalogAlgorithm->setProperty("FileNames", fileNames);
+  catalogAlgorithm->setProperty("DownloadPath", downloadPath);
+  catalogAlgorithm->setProperty("Session", sessionID);
+
+  executeAsynchronously(catalogAlgorithm);
+  // Return a vector containing the file paths to the files to download.
+  return (catalogAlgorithm->getProperty("FileLocations"));
+}
+
+/**
+ * Validate each input field against the related algorithm property.
+ * @param inputFields :: The name of the input field and value of the field (key
+ * => "StartDate", value => "00/00/0000").
+ * @return The name of the input field(s) marker to update and related error to
+ * throw.
+ */
+const std::map<std::string, std::string> CatalogHelper::validateProperties(
+    const std::map<std::string, std::string> &inputFields) {
+  auto catalogAlgorithm = createCatalogAlgorithm("CatalogSearch");
+
+  // Holds the name of the marker to update if an error is found, and the
+  // related error message to use.
+  // E.g. key => "StartDate_err", value => "The start date for..."
+  std::map<std::string, std::string> errors;
+
+  // Validate all input elements in the map.
+  for (auto iter = inputFields.begin(); iter != inputFields.end(); ++iter) {
+    try {
+      catalogAlgorithm->setProperty(iter->first, iter->second);
+    } catch (std::invalid_argument &) {
+      std::string documentation =
+          propertyDocumentation(catalogAlgorithm->getProperties(), iter->first);
+
+      // Add the input name + "_err" (to indicate the error marker in the GUI,
+      // rather than the input field) as the key, and the related error as the
+      // value.
+      errors.emplace(iter->first + "_err", documentation);
     }
-
-    /**
-     * Execute the given algorithm asynchronously.
-     * @param algorithm :: The algorithm to execute.
-     */
-    void CatalogHelper::executeAsynchronously(const Mantid::API::IAlgorithm_sptr &algorithm)
-    {
-      Poco::ActiveResult<bool> result(algorithm->executeAsync());
-      while (!result.available())
-      {
-        QCoreApplication::processEvents();
-      }
+  }
+  return errors;
+}
+
+/**
+ * Creates a time_t value from an input date ("23/06/2003") for comparison.
+ * @param inputDate :: string containing the date.
+ * @return time_t value of date
+ */
+time_t CatalogHelper::getTimevalue(const std::string &inputDate) {
+  // Prevent any possible errors.
+  if (inputDate.empty())
+    return 0;
+  // A container to hold the segments of the date.
+  std::vector<std::string> dateSegments;
+  // Split input by "/" prior to rearranging the date
+  boost::algorithm::split_regex(dateSegments, inputDate, boost::regex("/"));
+  // Reorganise the date to be ISO format.
+  std::string isoDate = dateSegments.at(2) + "-" + dateSegments.at(1) + "-" +
+                        dateSegments.at(0) + " 0:00:00.000";
+  // Return the date as time_t value.
+  return Mantid::Kernel::DateAndTime(isoDate).to_time_t();
+}
+
+/**
+ * Opens auto-generated dialog, and executes the catalog login algorithm.
+ * Returns true if login was a success.
+ */
+void CatalogHelper::showLoginDialog() {
+  API::InterfaceManager interfaceMgr;
+  auto dlg = interfaceMgr.createDialogFromName("CatalogLogin");
+  dlg->setModal(false);
+  dlg->show();
+  dlg->raise();
+  dlg->activateWindow();
+}
+
+/**
+ * Creates a publishing dialog GUI and runs the publishing algorithm when "Run"
+ * is pressed.
+ */
+void CatalogHelper::showPublishDialog() {
+  API::InterfaceManager interfaceMgr;
+  auto dlg = interfaceMgr.createDialogFromName("CatalogPublish");
+  dlg->setModal(false);
+  dlg->show();
+  dlg->raise();
+  dlg->activateWindow();
+}
+
+/**
+ * Obtain the algorithm documentation for the given property.
+ * @param properties :: A list of properties for a provided algorithm.
+ * @param name       :: The name of the property to search for.
+ * @return The documentation for a given property name.
+ */
+const std::string CatalogHelper::propertyDocumentation(
+    const std::vector<Mantid::Kernel::Property *> &properties,
+    const std::string &name) {
+  for (unsigned i = 0; i < properties.size(); i++) {
+    if (properties.at(i)->name() == name) {
+      return properties.at(i)->documentation();
     }
-
-    /**
-     * Set the "search" properties to their related input fields.
-     * @param catalogAlgorithm :: Algorithm to set the search properties for.
-     * @param userInputFields  :: The search properties to set against the algorithm.
-     */
-    void CatalogHelper::setSearchProperties(const Mantid::API::IAlgorithm_sptr &catalogAlgorithm,
-        const std::map<std::string, std::string> &userInputFields)
-    {
-      // This will be the workspace where the content of the search result is output to.
-      catalogAlgorithm->setProperty("OutputWorkspace", "__searchResults");
-
-      // Iterate over the provided map of user input fields. For each field that isn't empty (e.g. a value was input by the user)
-      // then we will set the algorithm property with the key and value of that specific value.
-      for (auto it = userInputFields.begin(); it != userInputFields.end(); it++)
-      {
-        std::string value = it->second;
-        // If the user has input any search terms.
-        if (!value.empty())
-        {
-          // Set the property that the search algorithm uses to: (key => FieldName, value => FieldValue) (e.g., (Keywords, bob))
-          catalogAlgorithm->setProperty(it->first, value);
-        }
-      }
+  }
+  return "";
+}
+
+/**
+ * Creates an algorithm with the provided name.
+ * @param algName :: The name of the algorithm to create.
+ * @return A shared pointer to the algorithm created.
+ */
+Mantid::API::IAlgorithm_sptr
+CatalogHelper::createCatalogAlgorithm(const std::string &algName) {
+  // If there is an exception we want it to be thrown.
+  return Mantid::API::AlgorithmManager::Instance().create(algName);
+}
+
+/**
+ * Execute the given algorithm asynchronously.
+ * @param algorithm :: The algorithm to execute.
+ */
+void CatalogHelper::executeAsynchronously(
+    const Mantid::API::IAlgorithm_sptr &algorithm) {
+  Poco::ActiveResult<bool> result(algorithm->executeAsync());
+  while (!result.available()) {
+    QCoreApplication::processEvents();
+  }
+}
+
+/**
+ * Set the "search" properties to their related input fields.
+ * @param catalogAlgorithm :: Algorithm to set the search properties for.
+ * @param userInputFields  :: The search properties to set against the
+ * algorithm.
+ */
+void CatalogHelper::setSearchProperties(
+    const Mantid::API::IAlgorithm_sptr &catalogAlgorithm,
+    const std::map<std::string, std::string> &userInputFields) {
+  // This will be the workspace where the content of the search result is output
+  // to.
+  catalogAlgorithm->setProperty("OutputWorkspace", "__searchResults");
+
+  // Iterate over the provided map of user input fields. For each field that
+  // isn't empty (e.g. a value was input by the user)
+  // then we will set the algorithm property with the key and value of that
+  // specific value.
+  for (auto it = userInputFields.begin(); it != userInputFields.end(); it++) {
+    std::string value = it->second;
+    // If the user has input any search terms.
+    if (!value.empty()) {
+      // Set the property that the search algorithm uses to: (key => FieldName,
+      // value => FieldValue) (e.g., (Keywords, bob))
+      catalogAlgorithm->setProperty(it->first, value);
     }
+  }
+}
 
-  } // namespace MantidWidgets
+} // namespace MantidWidgets
 } // namespace MantidQt
diff --git a/MantidQt/MantidWidgets/src/CatalogSearch.cpp b/MantidQt/MantidWidgets/src/CatalogSearch.cpp
index 03491ddc443fceb75679358600fdd499302d78b6..a2dd89e6330fd76757909e52c0dccbe393c151a7 100644
--- a/MantidQt/MantidWidgets/src/CatalogSearch.cpp
+++ b/MantidQt/MantidWidgets/src/CatalogSearch.cpp
@@ -918,9 +918,9 @@ void CatalogSearch::investigationSelected(QTableWidgetItem *item) {
   // investigation.
   m_icatHelper->executeGetDataFiles(
       investigationId->text().toStdString(),
-      searchResultsTable->item(
-                            item->row(),
-                            headerIndexByName(searchResultsTable, "SessionID"))
+      searchResultsTable->item(item->row(),
+                               headerIndexByName(searchResultsTable,
+                                                 "SessionID"))
           ->text()
           .toStdString());
 
@@ -1086,17 +1086,15 @@ void CatalogSearch::updateDataFileLabels(QTableWidgetItem *item) {
   // Set the instrument label using data from the investigation results
   // workspace.
   m_icatUiForm.dataFileInstrumentRes->setText(
-      searchResultsTable->item(
-                            item->row(),
-                            headerIndexByName(searchResultsTable, "Instrument"))
-          ->text());
+      searchResultsTable->item(item->row(),
+                               headerIndexByName(searchResultsTable,
+                                                 "Instrument"))->text());
 
   // Show the related "run-range" for the specific dataFiles.
   m_icatUiForm.dataFileRunRangeRes->setText(
-      searchResultsTable->item(
-                            item->row(),
-                            headerIndexByName(searchResultsTable, "Run range"))
-          ->text());
+      searchResultsTable->item(item->row(),
+                               headerIndexByName(searchResultsTable,
+                                                 "Run range"))->text());
 }
 
 /**
diff --git a/MantidQt/MantidWidgets/src/CatalogSelector.cpp b/MantidQt/MantidWidgets/src/CatalogSelector.cpp
index 30f86f21945134288b4b87ffcec8498edbcc8302..ae24af89a922b7322cd5086f596725aabf347d33 100644
--- a/MantidQt/MantidWidgets/src/CatalogSelector.cpp
+++ b/MantidQt/MantidWidgets/src/CatalogSelector.cpp
@@ -3,92 +3,95 @@
 
 #include <QDesktopWidget>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    /**
-     * Constructor
-     */
-    CatalogSelector::CatalogSelector(QWidget* parent) : QWidget(parent), m_uiForm()
-    {
-      initLayout();
-    }
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+ * Constructor
+ */
+CatalogSelector::CatalogSelector(QWidget *parent)
+    : QWidget(parent), m_uiForm() {
+  initLayout();
+}
 
-    /**
-     * Obtain the session information for the facilities selected.
-     * @return A vector holding the sessions ids of the selected facilities to search.
-     */
-    std::vector<std::string> CatalogSelector::getSelectedCatalogSessions()
-    {
-      std::vector<std::string> selectedSessions;
-      for (int row = 0; row < m_uiForm.selectedCatalogs->count(); ++row)
-      {
-        if (m_uiForm.selectedCatalogs->item(row)->isSelected())
-        {
-          selectedSessions.push_back(m_uiForm.selectedCatalogs->item(row)->data(Qt::UserRole).toString().toStdString());
-        }
-      }
-      return selectedSessions;
+/**
+ * Obtain the session information for the facilities selected.
+ * @return A vector holding the sessions ids of the selected facilities to
+ * search.
+ */
+std::vector<std::string> CatalogSelector::getSelectedCatalogSessions() {
+  std::vector<std::string> selectedSessions;
+  for (int row = 0; row < m_uiForm.selectedCatalogs->count(); ++row) {
+    if (m_uiForm.selectedCatalogs->item(row)->isSelected()) {
+      selectedSessions.push_back(m_uiForm.selectedCatalogs->item(row)
+                                     ->data(Qt::UserRole)
+                                     .toString()
+                                     .toStdString());
     }
+  }
+  return selectedSessions;
+}
 
+/**
+ * Populate the ListWidget with the facilities of the catalogs the user is
+ * logged in to.
+ */
+void CatalogSelector::populateFacilitySelection() {
+  auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
 
-    /**
-     * Populate the ListWidget with the facilities of the catalogs the user is logged in to.
-     */
-    void CatalogSelector::populateFacilitySelection()
-    {
-      auto session = Mantid::API::CatalogManager::Instance().getActiveSessions();
-
-      for (unsigned row = 0; row < session.size(); ++row)
-      {
-        // This prevents the same items being appended (again) to the list widget.
-        if (!m_uiForm.selectedCatalogs->item(row))
-        {
-          QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(session.at(row)->getFacility()));
-          // Set sessionID to user specific meta-data to easily obtain it later.
-          item->setData(Qt::UserRole,QVariant(QString::fromStdString(session.at(row)->getSessionId())));
-          // Add tooltip to see the difference if logged into two facilities with different end-points.
-          item->setData(Qt::ToolTipRole,QVariant(QString::fromStdString(
-              "The soap-endpoint for this catalog is: " + session.at(row)->getSoapEndpoint())));
-          // When a new item is added, we want to select & check it by default.
-          item->setCheckState(Qt::Checked);
-          m_uiForm.selectedCatalogs->insertItem(row,item);
-          m_uiForm.selectedCatalogs->item(row)->setSelected(true);
-        }
-      }
-      // Set the list widget as focus to better show the selected facilities.
-      m_uiForm.selectedCatalogs->setFocus();
+  for (unsigned row = 0; row < session.size(); ++row) {
+    // This prevents the same items being appended (again) to the list widget.
+    if (!m_uiForm.selectedCatalogs->item(row)) {
+      QListWidgetItem *item = new QListWidgetItem(
+          QString::fromStdString(session.at(row)->getFacility()));
+      // Set sessionID to user specific meta-data to easily obtain it later.
+      item->setData(Qt::UserRole, QVariant(QString::fromStdString(
+                                      session.at(row)->getSessionId())));
+      // Add tooltip to see the difference if logged into two facilities with
+      // different end-points.
+      item->setData(Qt::ToolTipRole,
+                    QVariant(QString::fromStdString(
+                        "The soap-endpoint for this catalog is: " +
+                        session.at(row)->getSoapEndpoint())));
+      // When a new item is added, we want to select & check it by default.
+      item->setCheckState(Qt::Checked);
+      m_uiForm.selectedCatalogs->insertItem(row, item);
+      m_uiForm.selectedCatalogs->item(row)->setSelected(true);
     }
+  }
+  // Set the list widget as focus to better show the selected facilities.
+  m_uiForm.selectedCatalogs->setFocus();
+}
 
-    /**
-     * Initialise the  default layout.
-     */
-    void CatalogSelector::initLayout()
-    {
-      m_uiForm.setupUi(this);
+/**
+ * Initialise the  default layout.
+ */
+void CatalogSelector::initLayout() {
+  m_uiForm.setupUi(this);
 
-      populateFacilitySelection();
+  populateFacilitySelection();
 
-      connect(m_uiForm.updateBtn,SIGNAL(clicked()),this,SLOT(close()));
-      connect(m_uiForm.cancelBtn,SIGNAL(clicked()),this,SLOT(close()));
+  connect(m_uiForm.updateBtn, SIGNAL(clicked()), this, SLOT(close()));
+  connect(m_uiForm.cancelBtn, SIGNAL(clicked()), this, SLOT(close()));
 
-      // Check/un-check the checkbox when an item is clicked or selected.
-      connect(m_uiForm.selectedCatalogs,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(checkSelectedFacility(QListWidgetItem*)));
+  // Check/un-check the checkbox when an item is clicked or selected.
+  connect(m_uiForm.selectedCatalogs, SIGNAL(itemClicked(QListWidgetItem *)),
+          this, SLOT(checkSelectedFacility(QListWidgetItem *)));
 
-      // Centre the GUI on screen.
-      this->setGeometry(QStyle::alignedRect(Qt::LeftToRight,Qt::AlignCenter,
-          this->window()->size(),QDesktopWidget().availableGeometry()));
-    }
+  // Centre the GUI on screen.
+  this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter,
+                                        this->window()->size(),
+                                        QDesktopWidget().availableGeometry()));
+}
 
-    /**
-     * SLOT: Checks the checkbox of the list item selected.
-     */
-    void CatalogSelector::checkSelectedFacility(QListWidgetItem* item)
-    {
-      if (item->isSelected()) item->setCheckState(Qt::Checked);
-      if (!item->isSelected()) item->setCheckState(Qt::Unchecked);
-    }
+/**
+ * SLOT: Checks the checkbox of the list item selected.
+ */
+void CatalogSelector::checkSelectedFacility(QListWidgetItem *item) {
+  if (item->isSelected())
+    item->setCheckState(Qt::Checked);
+  if (!item->isSelected())
+    item->setCheckState(Qt::Unchecked);
+}
 
-  } // namespace MantidWidgets
+} // namespace MantidWidgets
 } // namespace MantidQt
diff --git a/MantidQt/MantidWidgets/src/CheckboxHeader.cpp b/MantidQt/MantidWidgets/src/CheckboxHeader.cpp
index 9baad93b1513740211aa16138887017038b2b8e5..8e3752463482b360933ba6d6bc8ce0684779ea4c 100644
--- a/MantidQt/MantidWidgets/src/CheckboxHeader.cpp
+++ b/MantidQt/MantidWidgets/src/CheckboxHeader.cpp
@@ -1,96 +1,86 @@
 #include "MantidQtMantidWidgets/CheckboxHeader.h"
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-
-    /**
-     * Constructor
-     * @param orientation :: The orientation (horizontal or vertical) of the header.
-     * @param parent      :: The table to apply the header to.
-     */
-    CheckboxHeader::CheckboxHeader(Qt::Orientation orientation, QWidget *parent) : QHeaderView(orientation, parent), m_checked(false)
-    {
-      show();
-      setClickable(true);
-    }
-
-
-    /**
-     * Has the user checked the checkbox in the header?
-     * @param checked :: True if user has checked the checkbox in the header.
-     */
-    void CheckboxHeader::setChecked(bool checked)
-    {
-      if (isEnabled() && m_checked != checked)
-      {
-        m_checked = checked;
-        updateSection(0);
-        emit toggled(m_checked);
-      }
-    }
-
-    /**
-     * Implements the checkbox functionality into the first column of the table.
-     * @param painter :: Paints the specific widget.
-     * @param rect    :: The area to paint.
-     * @param logicalIndex :: The column in the table.
-     */
-    void CheckboxHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
-    {
-      painter->save();
-      QHeaderView::paintSection(painter, rect, logicalIndex);
-      painter->restore();
-
-      if (logicalIndex == 0)
-      {
-        // We have to clear the data otherwise the default "1" appears.
-        model()->setHeaderData(0, Qt::Horizontal, tr(""));
-
-        QStyleOptionButton option;
-
-        if (isEnabled())
-        {
-          option.state |= QStyle::State_Enabled;
-        }
-
-        option.rect = checkBoxRect(rect);
-        option.state |= m_checked ? QStyle::State_On : QStyle::State_Off;
-
-        style()->drawControl(QStyle::CE_CheckBox, &option, painter);
-      }
-
-    }
-
-    /**
-     * Set the checkbox to checked if clicked, otherwise unchecked.
-     * @param event :: The mouse event the user performs.
-     */
-    void CheckboxHeader::mousePressEvent(QMouseEvent *event)
-    {
-      if (isEnabled() && logicalIndexAt(event->pos()) == 0)
-      {
-        m_checked = !m_checked;
-        updateSection(0);
-        emit toggled(m_checked);
-      }
-      else
-      {
-        QHeaderView::mousePressEvent(event);
-      }
-    }
-
-    QRect CheckboxHeader::checkBoxRect(const QRect &sourceRect) const
-    {
-      QStyleOptionButton checkBoxStyleOption;
-
-      QRect checkBoxRect = style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkBoxStyleOption);
-
-      QPoint checkBoxPoint(sourceRect.x() + 3,sourceRect.y() + sourceRect.height() / 2 - checkBoxRect.height() / 2);
-
-      return QRect(checkBoxPoint, checkBoxRect.size());
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+ * Constructor
+ * @param orientation :: The orientation (horizontal or vertical) of the header.
+ * @param parent      :: The table to apply the header to.
+ */
+CheckboxHeader::CheckboxHeader(Qt::Orientation orientation, QWidget *parent)
+    : QHeaderView(orientation, parent), m_checked(false) {
+  show();
+  setClickable(true);
+}
+
+/**
+ * Has the user checked the checkbox in the header?
+ * @param checked :: True if user has checked the checkbox in the header.
+ */
+void CheckboxHeader::setChecked(bool checked) {
+  if (isEnabled() && m_checked != checked) {
+    m_checked = checked;
+    updateSection(0);
+    emit toggled(m_checked);
+  }
+}
+
+/**
+ * Implements the checkbox functionality into the first column of the table.
+ * @param painter :: Paints the specific widget.
+ * @param rect    :: The area to paint.
+ * @param logicalIndex :: The column in the table.
+ */
+void CheckboxHeader::paintSection(QPainter *painter, const QRect &rect,
+                                  int logicalIndex) const {
+  painter->save();
+  QHeaderView::paintSection(painter, rect, logicalIndex);
+  painter->restore();
+
+  if (logicalIndex == 0) {
+    // We have to clear the data otherwise the default "1" appears.
+    model()->setHeaderData(0, Qt::Horizontal, tr(""));
+
+    QStyleOptionButton option;
+
+    if (isEnabled()) {
+      option.state |= QStyle::State_Enabled;
     }
 
-  } // namespace MantidWidgets
+    option.rect = checkBoxRect(rect);
+    option.state |= m_checked ? QStyle::State_On : QStyle::State_Off;
+
+    style()->drawControl(QStyle::CE_CheckBox, &option, painter);
+  }
+}
+
+/**
+ * Set the checkbox to checked if clicked, otherwise unchecked.
+ * @param event :: The mouse event the user performs.
+ */
+void CheckboxHeader::mousePressEvent(QMouseEvent *event) {
+  if (isEnabled() && logicalIndexAt(event->pos()) == 0) {
+    m_checked = !m_checked;
+    updateSection(0);
+    emit toggled(m_checked);
+  } else {
+    QHeaderView::mousePressEvent(event);
+  }
+}
+
+QRect CheckboxHeader::checkBoxRect(const QRect &sourceRect) const {
+  QStyleOptionButton checkBoxStyleOption;
+
+  QRect checkBoxRect = style()->subElementRect(QStyle::SE_CheckBoxIndicator,
+                                               &checkBoxStyleOption);
+
+  QPoint checkBoxPoint(sourceRect.x() + 3, sourceRect.y() +
+                                               sourceRect.height() / 2 -
+                                               checkBoxRect.height() / 2);
+
+  return QRect(checkBoxPoint, checkBoxRect.size());
+}
+
+} // namespace MantidWidgets
 } // namespace MantidQt
diff --git a/MantidQt/MantidWidgets/src/DiagResults.cpp b/MantidQt/MantidWidgets/src/DiagResults.cpp
index 59a07507134df59424475602ddc2071de3f0e959..5a1fb910a767ffbf2d06a4d79ff5f307e6ad3fb1 100644
--- a/MantidQt/MantidWidgets/src/DiagResults.cpp
+++ b/MantidQt/MantidWidgets/src/DiagResults.cpp
@@ -18,41 +18,38 @@
 using namespace MantidQt::API;
 using namespace MantidQt::MantidWidgets;
 
+namespace {
+/// the total number of tests that results are reported for here
+const int NUMTESTS = 5;
+/// the list of tests that we display results for
+const QString TESTS[5] = {"Hard mask", "First detector vanadium test",
+                          "Second detector vanadium test", "Background test",
+                          "PSD Bleed test"};
 
-namespace
-{
-  /// the total number of tests that results are reported for here
-  const int NUMTESTS = 5;
-  /// the list of tests that we display results for
-  const QString TESTS[5] =
-  { "Hard mask", "First detector vanadium test", "Second detector vanadium test", "Background test", "PSD Bleed test"};
-
-  int find_test(const std::string &test_name){
-    int found = -1;
-    for(int i=0;i<5;i++){
-      if (TESTS[i].toStdString()==test_name){
-        found = i+1;
-        return found;
-      }
+int find_test(const std::string &test_name) {
+  int found = -1;
+  for (int i = 0; i < 5; i++) {
+    if (TESTS[i].toStdString() == test_name) {
+      found = i + 1;
+      return found;
     }
-    return found;
   }
+  return found;
+}
 }
 
 //----------------------
 // Public member functions
 //----------------------
-///Constructor
-DiagResults::DiagResults(QWidget *parent): MantidDialog(parent),
-  m_Grid(new QGridLayout)
-{
+/// Constructor
+DiagResults::DiagResults(QWidget *parent)
+    : MantidDialog(parent), m_Grid(new QGridLayout) {
   setWindowTitle("Failed detectors list");
-  
+
   addRow("Test", "Number of failed spectra");
   // make one row for each set of results
   int row = 0;
-  for ( int i = 0; i < NUMTESTS; i ++ )
-  {
+  for (int i = 0; i < NUMTESTS; i++) {
     QString col1 = TESTS[i];
     QString col2 = "N/A";
     row = addRow(col1, col2);
@@ -71,46 +68,48 @@ DiagResults::DiagResults(QWidget *parent): MantidDialog(parent),
  * Update the results on the dialog
  * @param testSummary :: A string containing the test results
  */
-void DiagResults::updateResults(const QString & testSummary)
-{
-  if( !testSummary.contains("Diagnostic Test Summary") )
-  {
-    throw std::runtime_error("Diagnostic results string does not have expected format.");
+void DiagResults::updateResults(const QString &testSummary) {
+  if (!testSummary.contains("Diagnostic Test Summary")) {
+    throw std::runtime_error(
+        "Diagnostic results string does not have expected format.");
   }
 
   QStringList results = testSummary.split("\n");
   int nTestStrings = results.length();
   int end_count(0);
   // First result line is the header
-  for(int i = 0; i <= nTestStrings; ++i)
-  {
+  for (int i = 0; i <= nTestStrings; ++i) {
     QString testName = results[i].section(":", 0, 1);
     std::string tn = testName.toStdString();
-    if (tn[0] == '='){
+    if (tn[0] == '=') {
       end_count++;
-      if (end_count>1)break;
-      else            continue;
+      if (end_count > 1)
+        break;
+      else
+        continue;
     }
     QStringList NameValPair = results[i].split(":");
     tn = NameValPair[0].toStdString();
-    QStringList columns = NameValPair[1].split(QRegExp("\\s+"), QString::SkipEmptyParts);
+    QStringList columns =
+        NameValPair[1].split(QRegExp("\\s+"), QString::SkipEmptyParts);
     Q_ASSERT(columns.size() == 2);
     QString status;
-    if( columns[0] == "None" ) status = "N/A";
-    else status = columns[1];
+    if (columns[0] == "None")
+      status = "N/A";
+    else
+      status = columns[1];
     int test_ind = find_test(tn);
-    if (test_ind<0)continue;
-    updateRow(test_ind+1, status);
+    if (test_ind < 0)
+      continue;
+    updateRow(test_ind + 1, status);
   }
-  
 }
 
 //----------------------
 // Private member functions
 //----------------------
 /// insert a row at the bottom of the grid
-int DiagResults::addRow(QString firstColumn, QString secondColumn)
-{
+int DiagResults::addRow(QString firstColumn, QString secondColumn) {
   // set row to one past the end of the number of rows that currently exist
   int row = m_Grid->rowCount();
   m_Grid->addWidget(new QLabel(firstColumn), row, 0);
@@ -122,17 +121,15 @@ int DiagResults::addRow(QString firstColumn, QString secondColumn)
 *  @param row :: the row where the data will be displayed
 *  @param text :: the text that should be displayed in the first column
 */
-void DiagResults::updateRow(int row, QString text)
-{
+void DiagResults::updateRow(int row, QString text) {
   // Get the text label from the grid
   QWidget *widget = m_Grid->itemAtPosition(row, 1)->widget();
-  QLabel *label = qobject_cast<QLabel*>(widget);
+  QLabel *label = qobject_cast<QLabel *>(widget);
   label->setText(text);
 }
 
 /// enables the run button on the parent window so the user can do more analysis
-void DiagResults::closeEvent(QCloseEvent *event)
-{
+void DiagResults::closeEvent(QCloseEvent *event) {
   emit died();
   event->accept();
 }
diff --git a/MantidQt/MantidWidgets/src/DisplayCurveFit.cpp b/MantidQt/MantidWidgets/src/DisplayCurveFit.cpp
index f4a854a0ed0ebb48f57382e677378a427f822c37..b49b7c0bf8248b56b421722544d5b4715d7199ef 100644
--- a/MantidQt/MantidWidgets/src/DisplayCurveFit.cpp
+++ b/MantidQt/MantidWidgets/src/DisplayCurveFit.cpp
@@ -50,7 +50,8 @@ DisplayCurveFit::DisplayCurveFit(QWidget *parent)
 DisplayCurveFit::~DisplayCurveFit() {}
 
 /**
- * @brief Sets the range of the given axis scale to a given range in the two fitting
+ * @brief Sets the range of the given axis scale to a given range in the two
+ * fitting
  * panels.
  * @param range Pair of values for range
  * @param axisID ID of axis
@@ -62,7 +63,8 @@ void DisplayCurveFit::setAxisRange(QPair<double, double> range, int axisID) {
 }
 
 /**
- * @brief Finds which stored fitting curves are associated with the query workspace
+ * @brief Finds which stored fitting curves are associated with the query
+ * workspace
  * @param workspace Pointer to workspace
  * @return a std::vector containing the curve types
  */
@@ -86,10 +88,12 @@ QPair<double, double> DisplayCurveFit::getCurveRange(const curveType &atype) {
 }
 
 /**
- * @brief Gets the X range of the first curve whose data is stored in the query workspace.
+ * @brief Gets the X range of the first curve whose data is stored in the query
+ * workspace.
  * @param workspace pointer to query workspace
  * @return the range of the first curve associated to the workspace
- * @exception std::runtime_error no stored curves are associated to the query workspace
+ * @exception std::runtime_error no stored curves are associated to the query
+ * workspace
  */
 QPair<double, double> DisplayCurveFit::getCurveRange(
     const Mantid::API::MatrixWorkspace_sptr workspace) {
@@ -107,10 +111,9 @@ QPair<double, double> DisplayCurveFit::getCurveRange(
  * @param workspace Pointer to the workspace holding the data to plot the curve.
  * @param specIndex Spectrum index of workspace argument.
  */
-void
-DisplayCurveFit::addSpectrum(const curveType &aType,
-                             const Mantid::API::MatrixWorkspace_sptr workspace,
-                             const size_t specIndex) {
+void DisplayCurveFit::addSpectrum(
+    const curveType &aType, const Mantid::API::MatrixWorkspace_sptr workspace,
+    const size_t specIndex) {
   const QString curveName{m_curveTypeToQString.at(aType)};
   const QColor curveColor(m_curveTypeToColor.at(aType));
   m_plotPanel.at(aType)
@@ -137,21 +140,22 @@ bool DisplayCurveFit::hasCurve(const curveType &aType) {
 
 /**
  * @brief Creates a RangeSelector of selected type and plots it.
- * @param adcRange the type of dcRange to be displayed, either "fit" or "evaluate".
+ * @param adcRange the type of dcRange to be displayed, either "fit" or
+ * "evaluate".
  * @param aType the RangeSelector::SelectType
  * @post does nothing if the RangeSelector already exists
  */
 void DisplayCurveFit::addRangeSelector(const dcRange &adcRange,
-                                  RangeSelector::SelectType aType) {
+                                       RangeSelector::SelectType aType) {
   if (m_rangeSelector.find(adcRange) == m_rangeSelector.end()) {
     const QString dcRangeName(m_dcRangeToQString.at(adcRange));
     m_rangeSelector.emplace(
         adcRange, m_uiForm.fitPlot->addRangeSelector(dcRangeName, aType));
     switch (adcRange) {
-      case dcRange::fit:
-        m_rangeSelector.at(adcRange)->setColour(QColor(Qt::black));
-        break;
-      case dcRange::evaluate:
+    case dcRange::fit:
+      m_rangeSelector.at(adcRange)->setColour(QColor(Qt::black));
+      break;
+    case dcRange::evaluate:
       m_rangeSelector.at(adcRange)->setColour(QColor(Qt::red));
       break;
     }
@@ -161,11 +165,12 @@ void DisplayCurveFit::addRangeSelector(const dcRange &adcRange,
 /**
  * @brief Display in the residuals panel the line at Y=0.
  */
-void DisplayCurveFit::addResidualsZeroline(){
-  if(m_uiForm.residualsPlot->hasRangeSelector(QString("zeroLine"))){
+void DisplayCurveFit::addResidualsZeroline() {
+  if (m_uiForm.residualsPlot->hasRangeSelector(QString("zeroLine"))) {
     return; // do nothing
   }
-  auto residualsZeroline = m_uiForm.residualsPlot->addRangeSelector(QString("zeroLine"), RangeSelector::YSINGLE);
+  auto residualsZeroline = m_uiForm.residualsPlot->addRangeSelector(
+      QString("zeroLine"), RangeSelector::YSINGLE);
   residualsZeroline->setColour(QColor(Qt::darkGreen));
   residualsZeroline->setMinimum(0.0);
 }
@@ -186,8 +191,8 @@ DisplayCurveFit::nameToType(const QString &name) const {
   auto foundPair =
       std::find_if(m_curveTypeToQString.begin(), m_curveTypeToQString.end(),
                    [&name](const std::pair<curveType, QString> &p) {
-        return p.second == name;
-      });
+                     return p.second == name;
+                   });
   if (foundPair == m_curveTypeToQString.end()) {
     throw std::domain_error("Curve name " + name.toStdString() +
                             " does not have a curveType");
diff --git a/MantidQt/MantidWidgets/src/DoubleDialogEditor.cpp b/MantidQt/MantidWidgets/src/DoubleDialogEditor.cpp
index 5b05c99d2e963654780855180af75270c8487502..d45b46f7c6976f9ab1c87c8ee6ba747efc3badcc 100644
--- a/MantidQt/MantidWidgets/src/DoubleDialogEditor.cpp
+++ b/MantidQt/MantidWidgets/src/DoubleDialogEditor.cpp
@@ -10,49 +10,41 @@
 #include <QDoubleValidator>
 #include <QEvent>
 
-
 /**
  * Constructor.
  * @param property :: A property to edit.
  * @param parent :: A widget parent for the editor widget.
  */
-DoubleDialogEditor::DoubleDialogEditor(QtProperty *property, QWidget *parent):QWidget(parent),m_property(property)
-{
+DoubleDialogEditor::DoubleDialogEditor(QtProperty *property, QWidget *parent)
+    : QWidget(parent), m_property(property) {
   QHBoxLayout *layout = new QHBoxLayout;
   m_editor = new DoubleEditor(property, this);
   layout->addWidget(m_editor);
   setFocusProxy(m_editor);
   setFocusPolicy(Qt::StrongFocus);
 
-  m_button = new QPushButton("...",this);
-  m_button->setMaximumSize(20,1000000);
-  connect(m_button,SIGNAL(clicked()),this,SLOT(runDialog()));
+  m_button = new QPushButton("...", this);
+  m_button->setMaximumSize(20, 1000000);
+  connect(m_button, SIGNAL(clicked()), this, SLOT(runDialog()));
   layout->addWidget(m_button);
-  layout->setContentsMargins(0,0,0,0);
+  layout->setContentsMargins(0, 0, 0, 0);
   layout->setSpacing(0);
-  layout->setStretchFactor(m_button,0);
+  layout->setStretchFactor(m_button, 0);
   this->setLayout(layout);
 
   m_editor->installEventFilter(this);
   m_button->installEventFilter(this);
 }
 
-bool DoubleDialogEditor::eventFilter(QObject* obj, QEvent* evt)
-{
-  if (evt->type() == QEvent::FocusOut)
-  {
-    if (obj == m_editor)
-    {
-      if (!m_button->hasFocus())
-      {
+bool DoubleDialogEditor::eventFilter(QObject *obj, QEvent *evt) {
+  if (evt->type() == QEvent::FocusOut) {
+    if (obj == m_editor) {
+      if (!m_button->hasFocus()) {
         updateProperty();
         emit closeEditor();
       }
-    }
-    else if (obj == m_button)
-    {
-      if (!m_editor->hasFocus())
-      {
+    } else if (obj == m_button) {
+      if (!m_editor->hasFocus()) {
         updateProperty();
         emit closeEditor();
       }
@@ -65,33 +57,22 @@ bool DoubleDialogEditor::eventFilter(QObject* obj, QEvent* evt)
  * Set the text in the editor.
  * @param txt :: A text to set.
  */
-void DoubleDialogEditor::setText(const QString& txt)
-{
-  m_editor->setText(txt);
-}
+void DoubleDialogEditor::setText(const QString &txt) { m_editor->setText(txt); }
 
 /**
  * Get the current text inside the editor.
  */
-QString DoubleDialogEditor::getText()const
-{
-  return m_editor->text();
-}
+QString DoubleDialogEditor::getText() const { return m_editor->text(); }
 
 /**
  * Slot which sets the property with the current text in the editor.
  */
-void DoubleDialogEditor::updateProperty()
-{
-  auto mgr = dynamic_cast<ParameterPropertyManager*>(m_property->propertyManager());
-  if (mgr)
-  {
-    mgr->setValue(m_property,m_editor->text().toDouble());
+void DoubleDialogEditor::updateProperty() {
+  auto mgr =
+      dynamic_cast<ParameterPropertyManager *>(m_property->propertyManager());
+  if (mgr) {
+    mgr->setValue(m_property, m_editor->text().toDouble());
   }
 }
 
-void DoubleDialogEditor::runDialog()
-{
-  emit buttonClicked(m_property);
-}
-
+void DoubleDialogEditor::runDialog() { emit buttonClicked(m_property); }
diff --git a/MantidQt/MantidWidgets/src/DoubleSpinBox.cpp b/MantidQt/MantidWidgets/src/DoubleSpinBox.cpp
index ec8a48e06e6162052a03f270fa380d52e7e661f8..2495bdd2761428a721c68f24d760316d554f0809 100644
--- a/MantidQt/MantidWidgets/src/DoubleSpinBox.cpp
+++ b/MantidQt/MantidWidgets/src/DoubleSpinBox.cpp
@@ -35,10 +35,9 @@
 #include <float.h>
 #include <math.h>
 
-DoubleSpinBox::DoubleSpinBox(const char format, QWidget * parent) :
-  QAbstractSpinBox(parent), d_format(format), d_min_val(-DBL_MAX), d_max_val(DBL_MAX), d_value(0.0),
-  d_step(0.1), d_prec(14)
-{
+DoubleSpinBox::DoubleSpinBox(const char format, QWidget *parent)
+    : QAbstractSpinBox(parent), d_format(format), d_min_val(-DBL_MAX),
+      d_max_val(DBL_MAX), d_value(0.0), d_step(0.1), d_prec(14) {
   if (format == 'f')
     d_prec = 1;
 
@@ -48,81 +47,68 @@ DoubleSpinBox::DoubleSpinBox(const char format, QWidget * parent) :
   connect(this, SIGNAL(editingFinished()), this, SLOT(interpretText()));
 }
 
-void DoubleSpinBox::setSingleStep(double val)
-{
+void DoubleSpinBox::setSingleStep(double val) {
   if (d_step != val && val < d_max_val)
     d_step = val;
 }
 
-void DoubleSpinBox::setMaximum(double max)
-{
+void DoubleSpinBox::setMaximum(double max) {
   if (max == d_max_val || max > DBL_MAX)
     return;
 
   d_max_val = max;
 }
 
-double DoubleSpinBox::getMaximum()
-{
-  return d_max_val;
-}
+double DoubleSpinBox::getMaximum() { return d_max_val; }
 
-void DoubleSpinBox::setMinimum(double min)
-{
+void DoubleSpinBox::setMinimum(double min) {
   if (min == d_min_val || min < -DBL_MAX)
     return;
 
   d_min_val = min;
 }
 
-double DoubleSpinBox::getMinimum()
-{
-  return d_min_val;
-}
+double DoubleSpinBox::getMinimum() { return d_min_val; }
 
-void DoubleSpinBox::setRange(double min, double max)
-{
+void DoubleSpinBox::setRange(double min, double max) {
   setMinimum(min);
   setMaximum(max);
 }
 
 /**
  * Interpret the text and update the stored value.
- * @param notify If true then emit signals to indicate if the value has changed (default=true)
- * The default is important so that connected signals ensure the correct updates are pushed
- * through but we need to be able to turn them off as there are cases where this causes
+ * @param notify If true then emit signals to indicate if the value has changed
+ * (default=true)
+ * The default is important so that connected signals ensure the correct updates
+ * are pushed
+ * through but we need to be able to turn them off as there are cases where this
+ * causes
  * a recursive call.
  */
-void DoubleSpinBox::interpretText(bool notify)
-{
-// RJT: Keep our version of this, which contains a bug fix (see [10521]).
-// Also, there are lines referring to methods that don't exist in our (older) MyParser class.
+void DoubleSpinBox::interpretText(bool notify) {
+  // RJT: Keep our version of this, which contains a bug fix (see [10521]).
+  // Also, there are lines referring to methods that don't exist in our (older)
+  // MyParser class.
   bool ok = false;
   double value = locale().toDouble(text(), &ok);
-  if (ok && setValue(value))
-  {
-    if(notify) emit valueChanged(d_value);
-  }
-  else
-  {
+  if (ok && setValue(value)) {
+    if (notify)
+      emit valueChanged(d_value);
+  } else {
     QString val = text().remove(",");
     value = locale().toDouble(val, &ok);
-    if ( ok && setValue(value) )
-    {
-      if(notify) emit valueChanged(d_value);
-    }
-    else
-    {
-      //Check for any registered test strings that map to a given value
-      for(auto it = m_specialTextMappings.begin(); it != m_specialTextMappings.end(); ++it)
-      {
-        if(it->first == text())
-        {
-          //Found a matching string, try to set the value
-          if(setValue(it->second))
-          {
+    if (ok && setValue(value)) {
+      if (notify)
+        emit valueChanged(d_value);
+    } else {
+      // Check for any registered test strings that map to a given value
+      for (auto it = m_specialTextMappings.begin();
+           it != m_specialTextMappings.end(); ++it) {
+        if (it->first == text()) {
+          // Found a matching string, try to set the value
+          if (setValue(it->second)) {
             lineEdit()->setText(text());
-            if(notify)
+            if (notify)
               emit valueChanged(d_value);
           }
         }
@@ -132,58 +118,57 @@ void DoubleSpinBox::interpretText(bool notify)
     }
   }
 
-//  bool ok = false;
-//  QString s = text();
-//  double value = locale().toDouble(s, &ok);
-//  if (ok && value == d_value)
-//    return;
-//
-//  if (!ok)
-//  {
-//    MyParser parser;
-//    parser.setLocale(QLocale());
-//    parser.addGSLConstants();
-//    try
-//    {
-//      parser.SetExpr(s.toAscii().constData());
-//      value = parser.Eval();
-//    } catch (mu::ParserError &e)
-//    {
-//      lineEdit()->setText(textFromValue(d_value));
-//      return;
-//    }
-//  }
-//
-//  if (setValue(value))
-//    emit valueChanged( d_value);
-//  else
-//    lineEdit()->setText(textFromValue(d_value));
+  //  bool ok = false;
+  //  QString s = text();
+  //  double value = locale().toDouble(s, &ok);
+  //  if (ok && value == d_value)
+  //    return;
+  //
+  //  if (!ok)
+  //  {
+  //    MyParser parser;
+  //    parser.setLocale(QLocale());
+  //    parser.addGSLConstants();
+  //    try
+  //    {
+  //      parser.SetExpr(s.toAscii().constData());
+  //      value = parser.Eval();
+  //    } catch (mu::ParserError &e)
+  //    {
+  //      lineEdit()->setText(textFromValue(d_value));
+  //      return;
+  //    }
+  //  }
+  //
+  //  if (setValue(value))
+  //    emit valueChanged( d_value);
+  //  else
+  //    lineEdit()->setText(textFromValue(d_value));
 }
 
 /**
- * Adds a mapping from string whihc may be entered into the edit box and a double value.
+ * Adds a mapping from string whihc may be entered into the edit box and a
+ *double value.
  * The mapping is case sensitive
  *
  * @param text QString with text to map
  * @param value Value to map it to
  */
-void DoubleSpinBox::addSpecialTextMapping(QString text, double value)
-{
+void DoubleSpinBox::addSpecialTextMapping(QString text, double value) {
   m_specialTextMappings[text] = value;
 }
 
-void DoubleSpinBox::stepBy(int steps)
-{
+void DoubleSpinBox::stepBy(int steps) {
   double val = d_value + steps * d_step;
-  if (fabs(fabs(d_value) - d_step) < 1e-14 && d_value * steps < 0)//possible zero
+  if (fabs(fabs(d_value) - d_step) < 1e-14 &&
+      d_value * steps < 0) // possible zero
     val = 0.0;
 
   if (setValue(val))
-    emit valueChanged( d_value);
+    emit valueChanged(d_value);
 }
 
-QAbstractSpinBox::StepEnabled DoubleSpinBox::stepEnabled() const
-{
+QAbstractSpinBox::StepEnabled DoubleSpinBox::stepEnabled() const {
   QAbstractSpinBox::StepEnabled stepDown = QAbstractSpinBox::StepNone;
   if (d_value > d_min_val)
     stepDown = StepDownEnabled;
@@ -195,17 +180,14 @@ QAbstractSpinBox::StepEnabled DoubleSpinBox::stepEnabled() const
   return stepDown | stepUp;
 }
 
-double DoubleSpinBox::value()
-{
+double DoubleSpinBox::value() {
   const bool notify(false);
   interpretText(notify);
   return d_value;
 }
 
-bool DoubleSpinBox::setValue(double val)
-{
-  if (val >= d_min_val && val <= d_max_val)
-  {
+bool DoubleSpinBox::setValue(double val) {
+  if (val >= d_min_val && val <= d_max_val) {
     d_value = val;
     lineEdit()->setText(textFromValue(d_value));
     return true;
@@ -215,8 +197,7 @@ bool DoubleSpinBox::setValue(double val)
   return false;
 }
 
-QString DoubleSpinBox::textFromValue(double value) const
-{
+QString DoubleSpinBox::textFromValue(double value) const {
   if (!specialValueText().isEmpty() && value == d_min_val)
     return specialValueText();
 
@@ -226,13 +207,11 @@ QString DoubleSpinBox::textFromValue(double value) const
   return locale().toString(value, d_format, 6);
 }
 
-QValidator::State DoubleSpinBox::validate(QString &, int &) const
-{
+QValidator::State DoubleSpinBox::validate(QString &, int &) const {
   return QValidator::Acceptable;
 }
 
-void DoubleSpinBox::focusInEvent(QFocusEvent * e)
-{
+void DoubleSpinBox::focusInEvent(QFocusEvent *e) {
   emit activated(this);
   return QAbstractSpinBox::focusInEvent(e);
 }
@@ -243,9 +222,8 @@ void DoubleSpinBox::focusInEvent(QFocusEvent * e)
  *
  *****************************************************************************/
 
-RangeLimitBox::RangeLimitBox(LimitType type, QWidget * parent) :
-      QWidget(parent), d_type(type)
-{
+RangeLimitBox::RangeLimitBox(LimitType type, QWidget *parent)
+    : QWidget(parent), d_type(type) {
   d_checkbox = new QCheckBox();
   d_spin_box = new DoubleSpinBox();
   d_spin_box->setSpecialValueText(" ");
@@ -260,12 +238,12 @@ RangeLimitBox::RangeLimitBox(LimitType type, QWidget * parent) :
   l->addWidget(d_spin_box);
 
   setFocusPolicy(Qt::StrongFocus);
-  setFocusProxy( d_spin_box);
-  connect(d_checkbox, SIGNAL(toggled(bool)), d_spin_box, SLOT(setEnabled(bool)));
+  setFocusProxy(d_spin_box);
+  connect(d_checkbox, SIGNAL(toggled(bool)), d_spin_box,
+          SLOT(setEnabled(bool)));
 }
 
-double RangeLimitBox::value()
-{
+double RangeLimitBox::value() {
   if (d_checkbox->isChecked())
     return d_spin_box->value();
 
diff --git a/MantidQt/MantidWidgets/src/ErrorCurve.cpp b/MantidQt/MantidWidgets/src/ErrorCurve.cpp
index f3c138ca8eed200d7c0818da1e0326bedab110df..fb26b3e3654b8b4fe446f0cb6b0b0855722f87e9 100644
--- a/MantidQt/MantidWidgets/src/ErrorCurve.cpp
+++ b/MantidQt/MantidWidgets/src/ErrorCurve.cpp
@@ -4,31 +4,26 @@
 #include <qwt_scale_map.h>
 #include <stdexcept>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /// Create a error curve dependent on a data curve.
 /// @param dataCurve :: The curve displaying the data.
 /// @param errors :: A vector with error bars.
-ErrorCurve::ErrorCurve(const QwtPlotCurve* dataCurve, const std::vector<double>& errors)
-{
-  if (!dataCurve)
-  {
+ErrorCurve::ErrorCurve(const QwtPlotCurve *dataCurve,
+                       const std::vector<double> &errors) {
+  if (!dataCurve) {
     throw std::runtime_error("Null pointer to a data curve.");
   }
   auto n = dataCurve->dataSize();
   m_x.resize(n);
   m_y.resize(n);
-  for(int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     m_x[i] = dataCurve->x(i);
     m_y[i] = dataCurve->y(i);
   }
 
-  if (!errors.empty())
-  {
+  if (!errors.empty()) {
     setErrorBars(errors);
   }
 
@@ -38,30 +33,28 @@ ErrorCurve::ErrorCurve(const QwtPlotCurve* dataCurve, const std::vector<double>&
 
 /// Set error bars
 /// @param errors :: A pointer to an array with error bars.
-void ErrorCurve::setErrorBars(const std::vector<double>& errors)
-{
-  if (errors.size() != m_x.size())
-  {
-    throw std::runtime_error("Number of error values is different form the number of data points.");
+void ErrorCurve::setErrorBars(const std::vector<double> &errors) {
+  if (errors.size() != m_x.size()) {
+    throw std::runtime_error(
+        "Number of error values is different form the number of data points.");
   }
   m_e = errors;
 }
 
 /// Draw this curve
-void ErrorCurve::draw(QPainter *painter, 
-      const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-      const QRect &) const
-{
-  if (m_e.empty()) return;
+void ErrorCurve::draw(QPainter *painter, const QwtScaleMap &xMap,
+                      const QwtScaleMap &yMap, const QRect &) const {
+  if (m_e.empty())
+    return;
   painter->save();
   painter->setPen(m_pen);
   int n = dataSize();
   const int dx = 4;
 
-  for (int i = 0; i < n; ++i)
-  {
+  for (int i = 0; i < n; ++i) {
     const double E = m_e[i];
-    if (E <= 0.0) continue;
+    if (E <= 0.0)
+      continue;
 
     const int xi = xMap.transform(m_x[i]);
     const double Y = m_y[i];
@@ -70,21 +63,17 @@ void ErrorCurve::draw(QPainter *painter,
     const int ei2 = yMap.transform(Y + E);
 
     painter->drawLine(xi, ei1, xi, yi);
-    painter->drawLine(xi-dx,ei1,xi+dx,ei1);
+    painter->drawLine(xi - dx, ei1, xi + dx, ei1);
 
     painter->drawLine(xi, yi, xi, ei2);
-    painter->drawLine(xi-dx,ei2,xi+dx,ei2);
-      
+    painter->drawLine(xi - dx, ei2, xi + dx, ei2);
   }
 
   painter->restore();
 }
 
 /// Number of points in the curve
-int ErrorCurve::dataSize() const
-{
-  return static_cast<int>(m_x.size());
-}
+int ErrorCurve::dataSize() const { return static_cast<int>(m_x.size()); }
 
 /**
  * Bounding rectangle of all points and error bars, used for autoscaling.
@@ -121,4 +110,3 @@ QRectF ErrorCurve::boundingRect() const {
 
 } // MantidWidgets
 } // MantidQt
-
diff --git a/MantidQt/MantidWidgets/src/FilenameDialogEditor.cpp b/MantidQt/MantidWidgets/src/FilenameDialogEditor.cpp
index cdc2d36e8282293d2645d0ff2bbce85a6cb2e189..9d826260fd8cc944f047351d0896845624b5ac41 100644
--- a/MantidQt/MantidWidgets/src/FilenameDialogEditor.cpp
+++ b/MantidQt/MantidWidgets/src/FilenameDialogEditor.cpp
@@ -3,25 +3,22 @@
 #include <QFileDialog>
 #include <QSettings>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
- * Open a file dialog to choose a file. Update the property if a file was selected.
+ * Open a file dialog to choose a file. Update the property if a file was
+ * selected.
  */
-void FilenameDialogEditor::runDialog()
-{
+void FilenameDialogEditor::runDialog() {
   QSettings settings;
   QString dir = settings.value("Mantid/FitBrowser/ResolutionDir").toString();
-  QString StringDialog = QFileDialog::getOpenFileName(this, tr("Open File"),dir);
-  if (!StringDialog.isEmpty())
-  {
+  QString StringDialog =
+      QFileDialog::getOpenFileName(this, tr("Open File"), dir);
+  if (!StringDialog.isEmpty()) {
     setText(StringDialog);
     updateProperty();
   }
 }
-
 }
 }
diff --git a/MantidQt/MantidWidgets/src/FindDialog.cpp b/MantidQt/MantidWidgets/src/FindDialog.cpp
index 889655d8588ab81e2c90deab2b0a24d123c59bfc..910e53061518d854689e26d102f2f7906392d2b9 100644
--- a/MantidQt/MantidWidgets/src/FindDialog.cpp
+++ b/MantidQt/MantidWidgets/src/FindDialog.cpp
@@ -13,10 +13,8 @@
 #include <QGridLayout>
 #include <QVBoxLayout>
 
-
 FindDialog::FindDialog(ScriptEditor *editor, Qt::WindowFlags flags)
-  : FindReplaceDialog(editor, flags)
-{
+    : FindReplaceDialog(editor, flags) {
   setWindowTitle(tr("MantidPlot") + " - " + tr("Find"));
   initLayout();
 }
diff --git a/MantidQt/MantidWidgets/src/FindReplaceDialog.cpp b/MantidQt/MantidWidgets/src/FindReplaceDialog.cpp
index 348798c5492a7df2810b0c9a6a181f44b99f752e..81e68a5fa24babd373b4b16519154c39ae312533 100644
--- a/MantidQt/MantidWidgets/src/FindReplaceDialog.cpp
+++ b/MantidQt/MantidWidgets/src/FindReplaceDialog.cpp
@@ -19,118 +19,115 @@
  * Constructor
  */
 FindReplaceDialog::FindReplaceDialog(ScriptEditor *editor, Qt::WFlags fl)
-  : QDialog(editor, fl), m_editor(editor), 
-    m_findInProgress(false)
-{
- initLayout();
- setSizeGripEnabled(true);
+    : QDialog(editor, fl), m_editor(editor), m_findInProgress(false) {
+  initLayout();
+  setSizeGripEnabled(true);
 }
 
 /**
- * Create the widgets and lay them out 
+ * Create the widgets and lay them out
  */
-void FindReplaceDialog::initLayout()
-{
- QGroupBox *gb1 = new QGroupBox();
- m_topLayout = new QGridLayout(gb1);
-
- m_topLayout->addWidget(new QLabel(tr("Find")), 0, 0);
- boxFind = new QComboBox();
- boxFind->setEditable(true);
- boxFind->setDuplicatesEnabled(false);
- boxFind->setInsertPolicy( QComboBox::InsertAtTop );
- boxFind->setAutoCompletion(true);
- boxFind->setMaxCount ( 10 );
- boxFind->setMaxVisibleItems ( 10 );
- boxFind->setMinimumWidth(250);
- boxFind->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- connect(boxFind, SIGNAL(editTextChanged(const QString &)), 
-         this, SLOT(resetSearchFlags()));
-
- m_topLayout->addWidget(boxFind, 0, 1);
- 
- addReplaceBox();
-
- QGroupBox *gb2 = new QGroupBox();
- QGridLayout * bottomLayout = new QGridLayout(gb2);
- QButtonGroup *find_options = new QButtonGroup(this);
- find_options->setExclusive(false);
-
- boxCaseSensitive = new QCheckBox(tr("&Match case"));
- boxCaseSensitive->setChecked(false);
- bottomLayout->addWidget( boxCaseSensitive, 0, 0);
- find_options->addButton(boxCaseSensitive);
-
- boxWholeWords = new QCheckBox(tr("&Whole word"));
- boxWholeWords->setChecked(false);
- bottomLayout->addWidget(boxWholeWords, 1, 0);
- find_options->addButton(boxWholeWords);
-
- boxRegex = new QCheckBox(tr("&Regular expression"));
- boxRegex->setChecked(false);
- bottomLayout->addWidget(boxRegex, 2, 0);
- find_options->addButton(boxRegex);
-
- boxSearchBackwards = new QCheckBox(tr("&Search backwards"));
- boxSearchBackwards->setChecked(false);
- bottomLayout->addWidget(boxSearchBackwards, 0, 1);
- find_options->addButton(boxSearchBackwards);
-
- boxWrapAround = new QCheckBox(tr("&Wrap around"));
- boxWrapAround->setChecked(true);
- bottomLayout->addWidget(boxWrapAround, 1, 1);
- find_options->addButton(boxWrapAround);
- connect(find_options, SIGNAL(buttonClicked(int)), this, 
-         SLOT(resetSearchFlags()));
-
- QVBoxLayout *vb1 = new QVBoxLayout();
- vb1->addWidget(gb1);
- vb1->addWidget(gb2);
-
- m_vb2 = new QVBoxLayout();
-
- buttonNext = new QPushButton(tr("&Next"));
- buttonNext->setShortcut(tr("Ctrl+F"));
- buttonNext->setDefault(true);
- m_vb2->addWidget(buttonNext);
- connect(buttonNext, SIGNAL(clicked()), this, SLOT(findClicked()));
-
- addReplaceButtons();
-
- buttonCancel = new QPushButton(tr("&Close"));
- m_vb2->addWidget(buttonCancel);
- m_vb2->addStretch();
- connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
-
- QHBoxLayout *hb = new QHBoxLayout(this);
- hb->addLayout(vb1);
- hb->addLayout(m_vb2);
+void FindReplaceDialog::initLayout() {
+  QGroupBox *gb1 = new QGroupBox();
+  m_topLayout = new QGridLayout(gb1);
+
+  m_topLayout->addWidget(new QLabel(tr("Find")), 0, 0);
+  boxFind = new QComboBox();
+  boxFind->setEditable(true);
+  boxFind->setDuplicatesEnabled(false);
+  boxFind->setInsertPolicy(QComboBox::InsertAtTop);
+  boxFind->setAutoCompletion(true);
+  boxFind->setMaxCount(10);
+  boxFind->setMaxVisibleItems(10);
+  boxFind->setMinimumWidth(250);
+  boxFind->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  connect(boxFind, SIGNAL(editTextChanged(const QString &)), this,
+          SLOT(resetSearchFlags()));
+
+  m_topLayout->addWidget(boxFind, 0, 1);
+
+  addReplaceBox();
+
+  QGroupBox *gb2 = new QGroupBox();
+  QGridLayout *bottomLayout = new QGridLayout(gb2);
+  QButtonGroup *find_options = new QButtonGroup(this);
+  find_options->setExclusive(false);
+
+  boxCaseSensitive = new QCheckBox(tr("&Match case"));
+  boxCaseSensitive->setChecked(false);
+  bottomLayout->addWidget(boxCaseSensitive, 0, 0);
+  find_options->addButton(boxCaseSensitive);
+
+  boxWholeWords = new QCheckBox(tr("&Whole word"));
+  boxWholeWords->setChecked(false);
+  bottomLayout->addWidget(boxWholeWords, 1, 0);
+  find_options->addButton(boxWholeWords);
+
+  boxRegex = new QCheckBox(tr("&Regular expression"));
+  boxRegex->setChecked(false);
+  bottomLayout->addWidget(boxRegex, 2, 0);
+  find_options->addButton(boxRegex);
+
+  boxSearchBackwards = new QCheckBox(tr("&Search backwards"));
+  boxSearchBackwards->setChecked(false);
+  bottomLayout->addWidget(boxSearchBackwards, 0, 1);
+  find_options->addButton(boxSearchBackwards);
+
+  boxWrapAround = new QCheckBox(tr("&Wrap around"));
+  boxWrapAround->setChecked(true);
+  bottomLayout->addWidget(boxWrapAround, 1, 1);
+  find_options->addButton(boxWrapAround);
+  connect(find_options, SIGNAL(buttonClicked(int)), this,
+          SLOT(resetSearchFlags()));
+
+  QVBoxLayout *vb1 = new QVBoxLayout();
+  vb1->addWidget(gb1);
+  vb1->addWidget(gb2);
+
+  m_vb2 = new QVBoxLayout();
+
+  buttonNext = new QPushButton(tr("&Next"));
+  buttonNext->setShortcut(tr("Ctrl+F"));
+  buttonNext->setDefault(true);
+  m_vb2->addWidget(buttonNext);
+  connect(buttonNext, SIGNAL(clicked()), this, SLOT(findClicked()));
+
+  addReplaceButtons();
+
+  buttonCancel = new QPushButton(tr("&Close"));
+  m_vb2->addWidget(buttonCancel);
+  m_vb2->addStretch();
+  connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
+
+  QHBoxLayout *hb = new QHBoxLayout(this);
+  hb->addLayout(vb1);
+  hb->addLayout(m_vb2);
 }
 
 /// Add replace box
-void FindReplaceDialog::addReplaceBox()
-{
- setWindowTitle (tr("MantidPlot") + " - " + tr("Find and Replace"));
- m_topLayout->addWidget(new QLabel(tr( "Replace with" )), 1, 0);
- boxReplace = new QComboBox();
- boxReplace->setEditable(true);
- boxReplace->setDuplicatesEnabled(false);
- boxReplace->setInsertPolicy( QComboBox::InsertAtTop );
- boxReplace->setAutoCompletion(true);
- boxReplace->setMaxCount ( 10 );
- boxReplace->setMaxVisibleItems ( 10 );
- boxReplace->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- m_topLayout->addWidget( boxReplace, 1, 1);
- m_topLayout->setColumnStretch(1, 10);
+void FindReplaceDialog::addReplaceBox() {
+  setWindowTitle(tr("MantidPlot") + " - " + tr("Find and Replace"));
+  m_topLayout->addWidget(new QLabel(tr("Replace with")), 1, 0);
+  boxReplace = new QComboBox();
+  boxReplace->setEditable(true);
+  boxReplace->setDuplicatesEnabled(false);
+  boxReplace->setInsertPolicy(QComboBox::InsertAtTop);
+  boxReplace->setAutoCompletion(true);
+  boxReplace->setMaxCount(10);
+  boxReplace->setMaxVisibleItems(10);
+  boxReplace->setSizePolicy(
+      QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+  m_topLayout->addWidget(boxReplace, 1, 1);
+  m_topLayout->setColumnStretch(1, 10);
 }
 
 /// Add the replace buttons
-void FindReplaceDialog::addReplaceButtons()
-{
+void FindReplaceDialog::addReplaceButtons() {
   buttonReplace = new QPushButton(tr("&Replace"));
   connect(buttonReplace, SIGNAL(clicked()), this, SLOT(replace()));
   m_vb2->addWidget(buttonReplace);
- 
+
   buttonReplaceAll = new QPushButton(tr("Replace &all"));
   connect(buttonReplaceAll, SIGNAL(clicked()), this, SLOT(replaceAll()));
   m_vb2->addWidget(buttonReplaceAll);
@@ -141,133 +138,125 @@ void FindReplaceDialog::addReplaceButtons()
 //------------------------------------------------------
 /**
  * Find the current search term
- * @param backwards :: If true then the search procedes backwards from the cursor's current position
+ * @param backwards :: If true then the search procedes backwards from the
+ * cursor's current position
  * @returns A boolean indicating success/failure
  */
-bool FindReplaceDialog::find(bool backwards)
-{
- QString searchString = boxFind->currentText();
- if (searchString.isEmpty()){
-   QMessageBox::warning(this, tr("Empty Search Field"),
-			 tr("The search field is empty. Please enter some text and try again."));
-   boxFind->setFocus();
-   return false;
- }
-
- if(boxFind->findText(searchString) == -1)
- {
-   boxFind->addItem(searchString);
- }
-
- if( m_findInProgress )
- {
-   m_findInProgress = m_editor->findNext();
- }
- else
- {
-   bool cs = boxCaseSensitive->isChecked();
-   bool whole = boxWholeWords->isChecked();
-   bool wrap = boxWrapAround->isChecked();
-   bool regex = boxRegex->isChecked();
-   m_findInProgress = m_editor->findFirst(searchString, regex, cs, whole, wrap, !backwards);
- }
- return m_findInProgress;
+bool FindReplaceDialog::find(bool backwards) {
+  QString searchString = boxFind->currentText();
+  if (searchString.isEmpty()) {
+    QMessageBox::warning(
+        this, tr("Empty Search Field"),
+        tr("The search field is empty. Please enter some text and try again."));
+    boxFind->setFocus();
+    return false;
+  }
+
+  if (boxFind->findText(searchString) == -1) {
+    boxFind->addItem(searchString);
+  }
+
+  if (m_findInProgress) {
+    m_findInProgress = m_editor->findNext();
+  } else {
+    bool cs = boxCaseSensitive->isChecked();
+    bool whole = boxWholeWords->isChecked();
+    bool wrap = boxWrapAround->isChecked();
+    bool regex = boxRegex->isChecked();
+    m_findInProgress =
+        m_editor->findFirst(searchString, regex, cs, whole, wrap, !backwards);
+  }
+  return m_findInProgress;
 }
 
 /**
  * Replace the next occurrence of the search term with the replacement text
  */
-void FindReplaceDialog::replace()
-{
- QString searchString = boxFind->currentText();
- if (searchString.isEmpty()){
-   QMessageBox::warning(this, tr("Empty Search Field"),
-			 tr("The search field is empty. Please enter some text and try again."));
-   boxFind->setFocus();
-   return;
- }
-
- if (!m_editor->hasSelectedText() || m_editor->selectedText() != searchString)
- {
-   find();//find and select next match
-   return;
- }
-
- QString replaceString = boxReplace->currentText();
- m_editor->replace(replaceString);
- find();//find and select next match
-
- if(boxReplace->findText(replaceString) == -1)
- {
-   boxReplace->addItem(replaceString);
- }
+void FindReplaceDialog::replace() {
+  QString searchString = boxFind->currentText();
+  if (searchString.isEmpty()) {
+    QMessageBox::warning(
+        this, tr("Empty Search Field"),
+        tr("The search field is empty. Please enter some text and try again."));
+    boxFind->setFocus();
+    return;
+  }
+
+  if (!m_editor->hasSelectedText() ||
+      m_editor->selectedText() != searchString) {
+    find(); // find and select next match
+    return;
+  }
+
+  QString replaceString = boxReplace->currentText();
+  m_editor->replace(replaceString);
+  find(); // find and select next match
+
+  if (boxReplace->findText(replaceString) == -1) {
+    boxReplace->addItem(replaceString);
+  }
 }
 
 /**
  * Replace all occurrences of the current search term with the replacement text
  */
-void FindReplaceDialog::replaceAll()
-{
- QString searchString = boxFind->currentText();
- if (searchString.isEmpty()){
-   QMessageBox::warning(this, tr("Empty Search Field"),
-			 tr("The search field is empty. Please enter some text and try again."));
-   boxFind->setFocus();
-   return;
- }
-
- if(boxFind->findText(searchString) == -1)
- {
-   boxFind->addItem (searchString);
- }
-
- QString replaceString = boxReplace->currentText();
- if(boxReplace->findText(replaceString) == -1)
- {
-   boxReplace->addItem(replaceString);
- }
-
- int line(-1), index(-1), prevLine(-1), prevIndex(-1);
- bool regex = boxRegex->isChecked();
- bool cs = boxCaseSensitive->isChecked();
- bool whole = boxWholeWords->isChecked();
- bool wrap = boxWrapAround->isChecked();
- bool backward = boxSearchBackwards->isChecked();
- // Mark this as a set of actions that can be undone as one
- m_editor->beginUndoAction();
- bool found = m_editor->findFirst(searchString, regex, cs, whole, wrap, !backward, 0, 0);
- // If find first fails then there is nothing to replace
- if( !found )
- {
-   QMessageBox::information(this, "MantidPlot - Find and Replace", "No matches found in current document.");
- }
-
- while( found )
- {
-   m_editor->replace(replaceString);
-   m_editor->getCursorPosition(&prevLine, &prevIndex);
-   found = m_editor->findNext();
-   m_editor->getCursorPosition(&line, &index);
-   if( line < prevLine || ( line == prevLine && index <= prevIndex ) )
-   {
-     break;
-   }
- }
- m_editor->endUndoAction();
+void FindReplaceDialog::replaceAll() {
+  QString searchString = boxFind->currentText();
+  if (searchString.isEmpty()) {
+    QMessageBox::warning(
+        this, tr("Empty Search Field"),
+        tr("The search field is empty. Please enter some text and try again."));
+    boxFind->setFocus();
+    return;
+  }
+
+  if (boxFind->findText(searchString) == -1) {
+    boxFind->addItem(searchString);
+  }
+
+  QString replaceString = boxReplace->currentText();
+  if (boxReplace->findText(replaceString) == -1) {
+    boxReplace->addItem(replaceString);
+  }
+
+  int line(-1), index(-1), prevLine(-1), prevIndex(-1);
+  bool regex = boxRegex->isChecked();
+  bool cs = boxCaseSensitive->isChecked();
+  bool whole = boxWholeWords->isChecked();
+  bool wrap = boxWrapAround->isChecked();
+  bool backward = boxSearchBackwards->isChecked();
+  // Mark this as a set of actions that can be undone as one
+  m_editor->beginUndoAction();
+  bool found = m_editor->findFirst(searchString, regex, cs, whole, wrap,
+                                   !backward, 0, 0);
+  // If find first fails then there is nothing to replace
+  if (!found) {
+    QMessageBox::information(this, "MantidPlot - Find and Replace",
+                             "No matches found in current document.");
+  }
+
+  while (found) {
+    m_editor->replace(replaceString);
+    m_editor->getCursorPosition(&prevLine, &prevIndex);
+    found = m_editor->findNext();
+    m_editor->getCursorPosition(&line, &index);
+    if (line < prevLine || (line == prevLine && index <= prevIndex)) {
+      break;
+    }
+  }
+  m_editor->endUndoAction();
 }
 
 /**
  * Find button clicked slot
  */
-void FindReplaceDialog::findClicked()
-{
- // Forward to worker function
- find(boxSearchBackwards->isChecked());
+void FindReplaceDialog::findClicked() {
+  // Forward to worker function
+  find(boxSearchBackwards->isChecked());
 }
 
 /// Reset the search flags due to changes
-void FindReplaceDialog::resetSearchFlags()
-{
+void FindReplaceDialog::resetSearchFlags() {
   findNotInProgress();
   clearEditorSelection();
 }
@@ -275,16 +264,12 @@ void FindReplaceDialog::resetSearchFlags()
 /**
  * Flip the in-progress flag
  */
-void FindReplaceDialog::findNotInProgress()
-{
-  m_findInProgress = false;
-}
+void FindReplaceDialog::findNotInProgress() { m_findInProgress = false; }
 
 /**
  * Clear the selection in the editor
  */
-void FindReplaceDialog::clearEditorSelection()
-{
+void FindReplaceDialog::clearEditorSelection() {
   m_editor->setSelection(-1, -1, -1, -1);
 }
 
@@ -292,11 +277,9 @@ void FindReplaceDialog::clearEditorSelection()
  * Called when the widget is shown
  * @param event :: Parameterizes the dialog
  */
-void FindReplaceDialog::showEvent(QShowEvent *event)
-{
+void FindReplaceDialog::showEvent(QShowEvent *event) {
   Q_UNUSED(event);
-  if( m_editor->hasSelectedText() )
-  {
+  if (m_editor->hasSelectedText()) {
     QString text = m_editor->selectedText();
     boxFind->setEditText(text);
     boxFind->addItem(text);
diff --git a/MantidQt/MantidWidgets/src/FitOptionsBrowser.cpp b/MantidQt/MantidWidgets/src/FitOptionsBrowser.cpp
index 6daf470d2ab4db0f28a7939d890128878ce96d12..60c94dc524c5f72158f51e757db0447f4511c2c0 100644
--- a/MantidQt/MantidWidgets/src/FitOptionsBrowser.cpp
+++ b/MantidQt/MantidWidgets/src/FitOptionsBrowser.cpp
@@ -9,26 +9,26 @@
 
 #include "qttreepropertybrowser.h"
 #include "qtpropertymanager.h"
-#include<iostream>
+#include <iostream>
 // Suppress a warning coming out of code that isn't ours
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1125
+#pragma warning disable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Woverloaded-virtual"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 #include "qteditorfactory.h"
 #include "DoubleEditorFactory.h"
 #include "CompositeEditorFactory.h"
 #include "ButtonEditorFactory.h"
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1125
+#pragma warning enable 1125
 #elif defined(__GNUC__)
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #include <QVBoxLayout>
@@ -36,10 +36,8 @@
 #include <QSettings>
 #include <limits>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
  * Constructor
@@ -47,25 +45,22 @@ namespace MantidWidgets
  * @param fitType :: The type of the underlying fitting algorithm.
  */
 FitOptionsBrowser::FitOptionsBrowser(QWidget *parent, FittingType fitType)
-  :QWidget(parent),
-  m_decimals(6), m_fittingType(fitType)
-{
+    : QWidget(parent), m_decimals(6), m_fittingType(fitType) {
   // create m_browser
   createBrowser();
   createProperties();
 
-  QVBoxLayout* layout = new QVBoxLayout(this);
+  QVBoxLayout *layout = new QVBoxLayout(this);
   layout->addWidget(m_browser);
-  layout->setContentsMargins(0,0,0,0);
-
+  layout->setContentsMargins(0, 0, 0, 0);
 }
 
 /**
  * Create the Qt property browser and set up property managers.
  */
-void FitOptionsBrowser::createBrowser()
-{
-  /* Create property managers: they create, own properties, get and set values  */
+void FitOptionsBrowser::createBrowser() {
+  /* Create property managers: they create, own properties, get and set values
+   */
   m_stringManager = new QtStringPropertyManager(this);
   m_doubleManager = new QtDoublePropertyManager(this);
   m_intManager = new QtIntPropertyManager(this);
@@ -88,12 +83,14 @@ void FitOptionsBrowser::createBrowser()
   m_browser->setFactoryForManager(m_boolManager, checkBoxFactory);
   m_browser->setFactoryForManager(m_enumManager, comboBoxFactory);
 
-  //m_browser->setContextMenuPolicy(Qt::CustomContextMenu);
-  //connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
+  // m_browser->setContextMenuPolicy(Qt::CustomContextMenu);
+  // connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)),
+  // this, SLOT(popupMenu(const QPoint &)));
 
-  connect(m_enumManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(enumChanged(QtProperty*)));
-  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)),
-    this, SLOT(doubleChanged(QtProperty*)));
+  connect(m_enumManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(enumChanged(QtProperty *)));
+  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(doubleChanged(QtProperty *)));
   // Fill in getter and setter maps
 }
 
@@ -104,14 +101,12 @@ void FitOptionsBrowser::createBrowser()
 void FitOptionsBrowser::initFittingTypeProp() {
   m_fittingTypeProp = m_enumManager->addProperty("Fitting");
   QStringList types;
-  types << "Simultaneous" << "Sequential";
+  types << "Simultaneous"
+        << "Sequential";
   m_enumManager->setEnumNames(m_fittingTypeProp, types);
-  if (m_fittingType == SimultaneousAndSequential)
-  {
+  if (m_fittingType == SimultaneousAndSequential) {
     m_browser->addProperty(m_fittingTypeProp);
-  }
-  else if (m_fittingType == Simultaneous || m_fittingType == Sequential)
-  {
+  } else if (m_fittingType == Simultaneous || m_fittingType == Sequential) {
     this->lockCurrentFittingType(m_fittingType);
   }
 }
@@ -119,30 +114,30 @@ void FitOptionsBrowser::initFittingTypeProp() {
 /**
  * Create browser's QtProperties
  */
-void FitOptionsBrowser::createProperties()
-{
+void FitOptionsBrowser::createProperties() {
   initFittingTypeProp();
   createCommonProperties();
-  if (m_fittingType == Simultaneous || m_fittingType == SimultaneousAndSequential)
-  {
+  if (m_fittingType == Simultaneous ||
+      m_fittingType == SimultaneousAndSequential) {
     createSimultaneousFitProperties();
   }
-  if (m_fittingType == Sequential || m_fittingType == SimultaneousAndSequential)
-  {
+  if (m_fittingType == Sequential ||
+      m_fittingType == SimultaneousAndSequential) {
     createSequentialFitProperties();
   }
 }
 
-void FitOptionsBrowser::createCommonProperties()
-{
+void FitOptionsBrowser::createCommonProperties() {
   // Create MaxIterations property
   m_maxIterations = m_intManager->addProperty("Max Iterations");
   {
-    m_intManager->setValue(m_maxIterations,500);
-    m_intManager->setMinimum(m_maxIterations,0);
+    m_intManager->setValue(m_maxIterations, 500);
+    m_intManager->setMinimum(m_maxIterations, 0);
     m_browser->addProperty(m_maxIterations);
 
-    addProperty("MaxIterations", m_maxIterations, &FitOptionsBrowser::getIntProperty, &FitOptionsBrowser::setIntProperty);
+    addProperty("MaxIterations", m_maxIterations,
+                &FitOptionsBrowser::getIntProperty,
+                &FitOptionsBrowser::setIntProperty);
   }
 
   // Set up the minimizer property.
@@ -161,18 +156,19 @@ void FitOptionsBrowser::createCommonProperties()
     QStringList minimizers;
 
     // Store them in the m_minimizer enum property
-    for(auto it = minimizerOptions.begin(); it != minimizerOptions.end(); ++it)
-    {
+    for (auto it = minimizerOptions.begin(); it != minimizerOptions.end();
+         ++it) {
       minimizers << QString::fromStdString(*it);
     }
-    m_enumManager->setEnumNames(m_minimizer,minimizers);
-    int i = m_enumManager->enumNames(m_minimizer).indexOf("Levenberg-Marquardt");
-    if ( i >= 0 )
-    {
-      m_enumManager->setValue(m_minimizer,i);
+    m_enumManager->setEnumNames(m_minimizer, minimizers);
+    int i =
+        m_enumManager->enumNames(m_minimizer).indexOf("Levenberg-Marquardt");
+    if (i >= 0) {
+      m_enumManager->setValue(m_minimizer, i);
     }
     m_browser->addProperty(m_minimizerGroup);
-    addProperty("Minimizer", m_minimizer, &FitOptionsBrowser::getMinimizer, &FitOptionsBrowser::setMinimizer);
+    addProperty("Minimizer", m_minimizer, &FitOptionsBrowser::getMinimizer,
+                &FitOptionsBrowser::setMinimizer);
   }
 
   // Create cost function property
@@ -180,27 +176,27 @@ void FitOptionsBrowser::createCommonProperties()
   {
     // Get names of registered cost functions from the factory
     std::vector<std::string> costOptions =
-      Mantid::API::CostFunctionFactory::Instance().getKeys();
+        Mantid::API::CostFunctionFactory::Instance().getKeys();
     QStringList costFunctions;
     // Store them in the m_minimizer enum property
-    for(auto it = costOptions.begin(); it != costOptions.end(); ++it)
-    {
+    for (auto it = costOptions.begin(); it != costOptions.end(); ++it) {
       costFunctions << QString::fromStdString(*it);
     }
-    m_enumManager->setEnumNames(m_costFunction,costFunctions);
+    m_enumManager->setEnumNames(m_costFunction, costFunctions);
     m_browser->addProperty(m_costFunction);
-    addProperty("CostFunction", m_costFunction, &FitOptionsBrowser::getStringEnumProperty, &FitOptionsBrowser::setStringEnumProperty);
+    addProperty("CostFunction", m_costFunction,
+                &FitOptionsBrowser::getStringEnumProperty,
+                &FitOptionsBrowser::setStringEnumProperty);
   }
-
 }
 
-void FitOptionsBrowser::createSimultaneousFitProperties()
-{
+void FitOptionsBrowser::createSimultaneousFitProperties() {
   // Create Output property
   m_output = m_stringManager->addProperty("Output");
   {
     m_browser->addProperty(m_output);
-    addProperty("Output", m_output, &FitOptionsBrowser::getStringProperty, &FitOptionsBrowser::setStringProperty);
+    addProperty("Output", m_output, &FitOptionsBrowser::getStringProperty,
+                &FitOptionsBrowser::setStringProperty);
     m_simultaneousProperties << m_output;
   }
 
@@ -208,78 +204,89 @@ void FitOptionsBrowser::createSimultaneousFitProperties()
   m_ignoreInvalidData = m_boolManager->addProperty("Ignore Invalid Data");
   {
     m_browser->addProperty(m_ignoreInvalidData);
-    addProperty("IgnoreInvalidData", m_ignoreInvalidData, &FitOptionsBrowser::getBoolProperty, &FitOptionsBrowser::setBoolProperty);
+    addProperty("IgnoreInvalidData", m_ignoreInvalidData,
+                &FitOptionsBrowser::getBoolProperty,
+                &FitOptionsBrowser::setBoolProperty);
     m_simultaneousProperties << m_ignoreInvalidData;
   }
 }
 
-void FitOptionsBrowser::createSequentialFitProperties()
-{
+void FitOptionsBrowser::createSequentialFitProperties() {
   // Create FitType property, a property of algorithm PlotPeakByLogValue
   m_fitType = m_enumManager->addProperty("Fit Type");
   {
     QStringList types;
-    types << "Sequential" << "Individual";
-    m_enumManager->setEnumNames(m_fitType,types);
-    m_enumManager->setValue(m_fitType,0);
-    addProperty("FitType", m_fitType, &FitOptionsBrowser::getStringEnumProperty, &FitOptionsBrowser::setStringEnumProperty);
+    types << "Sequential"
+          << "Individual";
+    m_enumManager->setEnumNames(m_fitType, types);
+    m_enumManager->setValue(m_fitType, 0);
+    addProperty("FitType", m_fitType, &FitOptionsBrowser::getStringEnumProperty,
+                &FitOptionsBrowser::setStringEnumProperty);
     m_sequentialProperties << m_fitType;
   }
 
   // Create OutputWorkspace property
   m_outputWorkspace = m_stringManager->addProperty("OutputWorkspace");
   {
-    addProperty("OutputWorkspace", m_outputWorkspace, &FitOptionsBrowser::getStringProperty, &FitOptionsBrowser::setStringProperty);
+    addProperty("OutputWorkspace", m_outputWorkspace,
+                &FitOptionsBrowser::getStringProperty,
+                &FitOptionsBrowser::setStringProperty);
     m_sequentialProperties << m_outputWorkspace;
   }
 
   // Create CreateOutput property
   auto prop = m_boolManager->addProperty("Create Output");
   {
-    addProperty("CreateOutput", prop, &FitOptionsBrowser::getBoolProperty, &FitOptionsBrowser::setBoolProperty);
+    addProperty("CreateOutput", prop, &FitOptionsBrowser::getBoolProperty,
+                &FitOptionsBrowser::setBoolProperty);
     m_sequentialProperties << prop;
   }
 
   // Create OutputCompositeMembers property
   prop = m_boolManager->addProperty("Output Composite Members");
   {
-    addProperty("OutputCompositeMembers", prop, &FitOptionsBrowser::getBoolProperty, &FitOptionsBrowser::setBoolProperty);
+    addProperty("OutputCompositeMembers", prop,
+                &FitOptionsBrowser::getBoolProperty,
+                &FitOptionsBrowser::setBoolProperty);
     m_sequentialProperties << prop;
   }
 
   // Create ConvolveMembers property
   prop = m_boolManager->addProperty("Convolve Members");
   {
-    addProperty("ConvolveMembers", prop, &FitOptionsBrowser::getBoolProperty, &FitOptionsBrowser::setBoolProperty);
+    addProperty("ConvolveMembers", prop, &FitOptionsBrowser::getBoolProperty,
+                &FitOptionsBrowser::setBoolProperty);
     m_sequentialProperties << prop;
   }
 
   // Create PassWSIndexToFunction property
   prop = m_boolManager->addProperty("Pass WS Index To Function");
   {
-    addProperty("PassWSIndexToFunction", prop, &FitOptionsBrowser::getBoolProperty, &FitOptionsBrowser::setBoolProperty);
+    addProperty("PassWSIndexToFunction", prop,
+                &FitOptionsBrowser::getBoolProperty,
+                &FitOptionsBrowser::setBoolProperty);
     m_sequentialProperties << prop;
   }
 
   // Create LogValue property
   m_logValue = m_enumManager->addProperty("Log Value");
   {
-    //m_enumManager->setValue(m_logValue,0);
-    addProperty("LogValue", m_logValue, &FitOptionsBrowser::getStringEnumProperty, &FitOptionsBrowser::setStringEnumProperty);
+    // m_enumManager->setValue(m_logValue,0);
+    addProperty("LogValue", m_logValue,
+                &FitOptionsBrowser::getStringEnumProperty,
+                &FitOptionsBrowser::setStringEnumProperty);
     m_sequentialProperties << m_logValue;
   }
 
   // Create LogValue property
   m_plotParameter = m_enumManager->addProperty("Plot parameter");
-  {
-    m_sequentialProperties << m_plotParameter;
-  }
+  { m_sequentialProperties << m_plotParameter; }
 }
 
-void FitOptionsBrowser::addProperty(const QString& name, QtProperty* prop,
-                                    QString (FitOptionsBrowser::*getter)(QtProperty*)const, 
-  void (FitOptionsBrowser::*setter)(QtProperty*,const QString&))
-{
+void FitOptionsBrowser::addProperty(
+    const QString &name, QtProperty *prop,
+    QString (FitOptionsBrowser::*getter)(QtProperty *) const,
+    void (FitOptionsBrowser::*setter)(QtProperty *, const QString &)) {
   m_propertyNameMap[name] = prop;
   m_getters[prop] = getter;
   m_setters[prop] = setter;
@@ -307,14 +314,10 @@ void FitOptionsBrowser::removeProperty(const QString &name) {
  * Update the browser when an enum property changes.
  * @param prop :: Property that changed its value.
  */
-void FitOptionsBrowser::enumChanged(QtProperty* prop)
-{
-  if (prop == m_minimizer)
-  {
+void FitOptionsBrowser::enumChanged(QtProperty *prop) {
+  if (prop == m_minimizer) {
     updateMinimizer();
-  }
-  else if (prop == m_fittingTypeProp)
-  {
+  } else if (prop == m_fittingTypeProp) {
     switchFitType();
   }
 }
@@ -329,49 +332,44 @@ void FitOptionsBrowser::doubleChanged(QtProperty *property) {
 /**
  * Update the browser when minimizer changes.
  */
-void FitOptionsBrowser::updateMinimizer()
-{
+void FitOptionsBrowser::updateMinimizer() {
   int i = m_enumManager->value(m_minimizer);
   QString minimizerName = m_enumManager->enumNames(m_minimizer)[i];
   m_minimizerGroup->setPropertyName("Minimizer " + minimizerName);
 
   // Remove properties of the old minimizer
   auto subProperties = m_minimizerGroup->subProperties();
-  foreach(QtProperty* prop, subProperties)
-  {
-    if ( prop != m_minimizer )
-    {
+  foreach (QtProperty *prop, subProperties) {
+    if (prop != m_minimizer) {
       m_minimizerGroup->removeSubProperty(prop);
       removeProperty(prop->propertyName());
     }
   }
 
   // Check if the new minimizer has its own properties
-  auto minimizer = 
-    Mantid::API::FuncMinimizerFactory::Instance().createMinimizer(minimizerName.toStdString());
+  auto minimizer =
+      Mantid::API::FuncMinimizerFactory::Instance().createMinimizer(
+          minimizerName.toStdString());
 
   // Create and add properties to the minimizer group
   auto minimizerProperties = minimizer->getProperties();
-  for(auto property = minimizerProperties.begin(); property != minimizerProperties.end(); ++property)
-  {
-    auto prop = createPropertyProperty( *property );
-    if ( !*property ) continue;
-    m_minimizerGroup->addSubProperty( prop );
+  for (auto property = minimizerProperties.begin();
+       property != minimizerProperties.end(); ++property) {
+    auto prop = createPropertyProperty(*property);
+    if (!*property)
+      continue;
+    m_minimizerGroup->addSubProperty(prop);
   }
 }
 
 /**
  * Switch the current fit type according to the value in the FitType property.
  */
-void FitOptionsBrowser::switchFitType()
-{
+void FitOptionsBrowser::switchFitType() {
   auto fitType = m_enumManager->value(m_fittingTypeProp);
-  if (fitType == 0)
-  {
+  if (fitType == 0) {
     displayNormalFitProperties();
-  }
-  else
-  {
+  } else {
     displaySequentialFitProperties();
   }
 }
@@ -379,14 +377,11 @@ void FitOptionsBrowser::switchFitType()
 /**
  * Show normal Fit properties and hide the others.
  */
-void FitOptionsBrowser::displayNormalFitProperties()
-{
-  foreach(QtProperty* prop, m_simultaneousProperties)
-  {
+void FitOptionsBrowser::displayNormalFitProperties() {
+  foreach (QtProperty *prop, m_simultaneousProperties) {
     m_browser->addProperty(prop);
   }
-  foreach(QtProperty* prop, m_sequentialProperties)
-  {
+  foreach (QtProperty *prop, m_sequentialProperties) {
     m_browser->removeProperty(prop);
   }
 }
@@ -396,81 +391,75 @@ void FitOptionsBrowser::displayNormalFitProperties()
  * and attach it to the correct manager.
  * @param property :: An algorithm property.
  */
-QtProperty* FitOptionsBrowser::createPropertyProperty(Mantid::Kernel::Property* property)
-{
-    QString propName = QString::fromStdString( property->name() );
-    QtProperty* prop = NULL;
-    if ( auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<bool>* >(property) )
-    {
-      prop = m_boolManager->addProperty( propName );
-      bool val = *prp;
-      m_boolManager->setValue( prop, val );
-    }
-    else if ( auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<double>* >(property) )
-    {
-      prop = this->addDoubleProperty( propName );
-      double val = *prp;
-      m_doubleManager->setValue( prop, val );
-    }
-    else if ( auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<int>* >(property) )
-    {
-      prop = m_intManager->addProperty( propName );
-      int val = *prp;
-      m_intManager->setValue( prop, val );
-    }
-    else if ( auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<size_t>* >(property) )
-    {
-      prop = m_intManager->addProperty( propName );
-      size_t val = *prp;
-      m_intManager->setValue( prop, static_cast<int>(val) );
-    }
-    else if ( auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<std::string>* >(property) )
-    {
-      prop = m_stringManager->addProperty( propName );
-      QString val = QString::fromStdString( prp->value() );
-      m_stringManager->setValue( prop, val );
-    }
-    else if ( dynamic_cast<Mantid::API::IWorkspaceProperty* >(property) )
-    {
-      prop = m_stringManager->addProperty( propName );
-      m_stringManager->setValue( prop, QString::fromStdString( property->value() ) );
-    }
-    else
-    {
-        QMessageBox::warning(this,"MantidPlot - Error","Type of minimizer's property " + propName + " is not yet supported by the browser.");
-        return NULL;
-    }
-
-    // Something bad happened in QtPropertyBrowser.
-    if ( !prop )
-    {
-      throw std::runtime_error("Failed to create a QtProperty.");
-    }
-
-    // set the tooltip from property doc string
-    QString toolTip = QString::fromStdString( property->documentation() );
-    if ( !toolTip.isEmpty() )
-    {
-      prop->setToolTip( toolTip );
-    }
-
-    return prop;
+QtProperty *
+FitOptionsBrowser::createPropertyProperty(Mantid::Kernel::Property *property) {
+  QString propName = QString::fromStdString(property->name());
+  QtProperty *prop = NULL;
+  if (auto prp =
+          dynamic_cast<Mantid::Kernel::PropertyWithValue<bool> *>(property)) {
+    prop = m_boolManager->addProperty(propName);
+    bool val = *prp;
+    m_boolManager->setValue(prop, val);
+  } else if (auto prp =
+                 dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(
+                     property)) {
+    prop = this->addDoubleProperty(propName);
+    double val = *prp;
+    m_doubleManager->setValue(prop, val);
+  } else if (auto prp = dynamic_cast<Mantid::Kernel::PropertyWithValue<int> *>(
+                 property)) {
+    prop = m_intManager->addProperty(propName);
+    int val = *prp;
+    m_intManager->setValue(prop, val);
+  } else if (auto prp =
+                 dynamic_cast<Mantid::Kernel::PropertyWithValue<size_t> *>(
+                     property)) {
+    prop = m_intManager->addProperty(propName);
+    size_t val = *prp;
+    m_intManager->setValue(prop, static_cast<int>(val));
+  } else if (auto prp =
+                 dynamic_cast<Mantid::Kernel::PropertyWithValue<std::string> *>(
+                     property)) {
+    prop = m_stringManager->addProperty(propName);
+    QString val = QString::fromStdString(prp->value());
+    m_stringManager->setValue(prop, val);
+  } else if (dynamic_cast<Mantid::API::IWorkspaceProperty *>(property)) {
+    prop = m_stringManager->addProperty(propName);
+    m_stringManager->setValue(prop, QString::fromStdString(property->value()));
+  } else {
+    QMessageBox::warning(this, "MantidPlot - Error",
+                         "Type of minimizer's property " + propName +
+                             " is not yet supported by the browser.");
+    return NULL;
+  }
+
+  // Something bad happened in QtPropertyBrowser.
+  if (!prop) {
+    throw std::runtime_error("Failed to create a QtProperty.");
+  }
+
+  // set the tooltip from property doc string
+  QString toolTip = QString::fromStdString(property->documentation());
+  if (!toolTip.isEmpty()) {
+    prop->setToolTip(toolTip);
+  }
+
+  return prop;
 }
 
 /**
  * Copy values of the properties to an algorithm.
  * @param fit :: An instance of the Fit algorithm.
  */
-void FitOptionsBrowser::copyPropertiesToAlgorithm(Mantid::API::IAlgorithm& fit) const
-{
-  for(auto p = m_propertyNameMap.constBegin(); p != m_propertyNameMap.constEnd(); ++p)
-  {
+void FitOptionsBrowser::copyPropertiesToAlgorithm(
+    Mantid::API::IAlgorithm &fit) const {
+  for (auto p = m_propertyNameMap.constBegin();
+       p != m_propertyNameMap.constEnd(); ++p) {
     auto propertyName = p.key().toStdString();
-    if (fit.existsProperty(propertyName))
-    {
+    if (fit.existsProperty(propertyName)) {
       auto prop = p.value();
       auto f = m_getters[prop];
-      fit.setPropertyValue(propertyName, (this->*f)(prop).toStdString() );
+      fit.setPropertyValue(propertyName, (this->*f)(prop).toStdString());
     }
   }
 }
@@ -479,11 +468,10 @@ void FitOptionsBrowser::copyPropertiesToAlgorithm(Mantid::API::IAlgorithm& fit)
  * Get a string representation of a Fit's property value.
  * @param name :: The name of a Fit's property.
  */
-QString FitOptionsBrowser::getProperty(const QString& name) const
-{
-  if ( !m_propertyNameMap.contains(name) )
-  {
-    throw std::runtime_error("Property " + name.toStdString() + " isn't supported by the browser.");
+QString FitOptionsBrowser::getProperty(const QString &name) const {
+  if (!m_propertyNameMap.contains(name)) {
+    throw std::runtime_error("Property " + name.toStdString() +
+                             " isn't supported by the browser.");
   }
   auto prop = m_propertyNameMap[name];
   auto f = m_getters[prop];
@@ -495,57 +483,45 @@ QString FitOptionsBrowser::getProperty(const QString& name) const
  * @param name :: The name of a Fit's property.
  * @param value :: The new value as a string.
  */
-void FitOptionsBrowser::setProperty(const QString& name, const QString& value)
-{
-  if ( !m_propertyNameMap.contains(name) )
-  {
-    throw std::runtime_error("Property " + name.toStdString() + " isn't supported by the browser.");
+void FitOptionsBrowser::setProperty(const QString &name, const QString &value) {
+  if (!m_propertyNameMap.contains(name)) {
+    throw std::runtime_error("Property " + name.toStdString() +
+                             " isn't supported by the browser.");
   }
   auto prop = m_propertyNameMap[name];
   auto f = m_setters[prop];
-  (this->*f)(prop,value);
+  (this->*f)(prop, value);
 }
 
 /**
  * Get the value of the Minimizer property.
  */
-QString FitOptionsBrowser::getMinimizer(QtProperty*) const
-{
+QString FitOptionsBrowser::getMinimizer(QtProperty *) const {
   int i = m_enumManager->value(m_minimizer);
   QString minimStr = m_enumManager->enumNames(m_minimizer)[i];
 
   auto subProperties = m_minimizerGroup->subProperties();
-  if ( subProperties.size() > 1 )
-  {
-    foreach(QtProperty* prop, subProperties)
-    {
-      if ( prop == m_minimizer ) continue;
-      if ( prop->propertyManager() == m_stringManager )
-      {
+  if (subProperties.size() > 1) {
+    foreach (QtProperty *prop, subProperties) {
+      if (prop == m_minimizer)
+        continue;
+      if (prop->propertyManager() == m_stringManager) {
         QString value = m_stringManager->value(prop);
-        if ( !value.isEmpty() )
-        {
+        if (!value.isEmpty()) {
           minimStr += "," + prop->propertyName() + "=" + value;
         }
-      }
-      else
-      {
+      } else {
         minimStr += "," + prop->propertyName() + "=";
-        if ( prop->propertyManager() == m_intManager )
-        {
-          minimStr += QString::number( m_intManager->value(prop) );
-        }
-        else if ( prop->propertyManager() == m_doubleManager )
-        {
-          minimStr += QString::number( m_doubleManager->value(prop) );
-        }
-        else if ( prop->propertyManager() == m_boolManager )
-        {
-          minimStr += QString::number( m_boolManager->value(prop) );
-        }
-        else
-        {
-          throw std::runtime_error("The fit browser doesn't support the type of minimizer's property " + prop->propertyName().toStdString() );
+        if (prop->propertyManager() == m_intManager) {
+          minimStr += QString::number(m_intManager->value(prop));
+        } else if (prop->propertyManager() == m_doubleManager) {
+          minimStr += QString::number(m_doubleManager->value(prop));
+        } else if (prop->propertyManager() == m_boolManager) {
+          minimStr += QString::number(m_boolManager->value(prop));
+        } else {
+          throw std::runtime_error("The fit browser doesn't support the type "
+                                   "of minimizer's property " +
+                                   prop->propertyName().toStdString());
         }
       }
     } // foreach
@@ -557,21 +533,20 @@ QString FitOptionsBrowser::getMinimizer(QtProperty*) const
  * Set new value to the Minimizer property.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setMinimizer(QtProperty*, const QString& value)
-{
+void FitOptionsBrowser::setMinimizer(QtProperty *, const QString &value) {
   QStringList terms = value.split(',');
   int i = m_enumManager->enumNames(m_minimizer).indexOf(terms[0]);
-  m_enumManager->setValue(m_minimizer,i);
+  m_enumManager->setValue(m_minimizer, i);
 }
 
-// ------------------------- Generic setters and getters ------------------------------//
+// ------------------------- Generic setters and getters
+// ------------------------------//
 
 /**
  * Get the value of an integer algorithm property.
  * @param prop :: The corresponding QtProperty.
  */
-QString FitOptionsBrowser::getIntProperty(QtProperty* prop) const
-{
+QString FitOptionsBrowser::getIntProperty(QtProperty *prop) const {
   return QString::number(m_intManager->value(prop));
 }
 
@@ -580,9 +555,8 @@ QString FitOptionsBrowser::getIntProperty(QtProperty* prop) const
  * @param prop :: The corresponding QtProperty.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setIntProperty(QtProperty* prop, const QString& value)
-{
-  m_intManager->setValue(prop,value.toInt());
+void FitOptionsBrowser::setIntProperty(QtProperty *prop, const QString &value) {
+  m_intManager->setValue(prop, value.toInt());
 }
 
 /**
@@ -590,7 +564,7 @@ void FitOptionsBrowser::setIntProperty(QtProperty* prop, const QString& value)
  * @param prop :: The corresponding QtProperty.
  * @return the stored value
  */
-QString FitOptionsBrowser::getDoubleProperty(QtProperty* prop) const {
+QString FitOptionsBrowser::getDoubleProperty(QtProperty *prop) const {
   return QString::number(m_doubleManager->value(prop));
 }
 
@@ -599,16 +573,16 @@ QString FitOptionsBrowser::getDoubleProperty(QtProperty* prop) const {
  * @param prop :: The corresponding QtProperty.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setDoubleProperty(QtProperty* prop, const QString& value) {
-  m_doubleManager->setValue(prop,value.toDouble());
+void FitOptionsBrowser::setDoubleProperty(QtProperty *prop,
+                                          const QString &value) {
+  m_doubleManager->setValue(prop, value.toDouble());
 }
 
 /**
  * Get the value of a bool algorithm property.
  * @param prop :: The corresponding QtProperty.
  */
-QString FitOptionsBrowser::getBoolProperty(QtProperty* prop) const
-{
+QString FitOptionsBrowser::getBoolProperty(QtProperty *prop) const {
   return QString::number(m_boolManager->value(prop));
 }
 
@@ -617,20 +591,20 @@ QString FitOptionsBrowser::getBoolProperty(QtProperty* prop) const
  * @param prop :: The corresponding QtProperty.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setBoolProperty(QtProperty* prop, const QString& value)
-{
+void FitOptionsBrowser::setBoolProperty(QtProperty *prop,
+                                        const QString &value) {
   bool boolValue = (value == "1") || (value.toLower() == "true");
-  m_boolManager->setValue( prop, boolValue );
+  m_boolManager->setValue(prop, boolValue);
 }
 
 /**
  * Get the value of a string algorithm property with predefined set of values.
  * @param prop :: The corresponding QtProperty.
  */
-QString FitOptionsBrowser::getStringEnumProperty(QtProperty* prop) const
-{
+QString FitOptionsBrowser::getStringEnumProperty(QtProperty *prop) const {
   int i = m_enumManager->value(prop);
-  if (i < 0) return "";
+  if (i < 0)
+    return "";
   return m_enumManager->enumNames(prop)[i];
 }
 
@@ -639,19 +613,18 @@ QString FitOptionsBrowser::getStringEnumProperty(QtProperty* prop) const
  * @param prop :: The corresponding QtProperty.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setStringEnumProperty(QtProperty* prop, const QString& value)
-{
+void FitOptionsBrowser::setStringEnumProperty(QtProperty *prop,
+                                              const QString &value) {
   int i = m_enumManager->enumNames(prop).indexOf(value);
   if (i >= 0)
-    m_enumManager->setValue(prop,i);
+    m_enumManager->setValue(prop, i);
 }
 
 /**
  * Get the value of a string algorithm property.
  * @param prop :: The corresponding QtProperty.
  */
-QString FitOptionsBrowser::getStringProperty(QtProperty* prop) const
-{
+QString FitOptionsBrowser::getStringProperty(QtProperty *prop) const {
   return m_stringManager->value(prop);
 }
 
@@ -660,8 +633,8 @@ QString FitOptionsBrowser::getStringProperty(QtProperty* prop) const
  * @param prop :: The corresponding QtProperty.
  * @param value :: The new value.
  */
-void FitOptionsBrowser::setStringProperty(QtProperty* prop, const QString& value)
-{
+void FitOptionsBrowser::setStringProperty(QtProperty *prop,
+                                          const QString &value) {
   m_stringManager->setValue(prop, value);
 }
 
@@ -671,13 +644,12 @@ void FitOptionsBrowser::setStringProperty(QtProperty* prop, const QString& value
  * Save the last property values in settings.
  * @param settings :: A QSettings instance provided by the user of this class.
  */
-void FitOptionsBrowser::saveSettings(QSettings& settings) const
-{
-  for(auto p = m_propertyNameMap.constBegin(); p != m_propertyNameMap.constEnd(); ++p)
-  {
+void FitOptionsBrowser::saveSettings(QSettings &settings) const {
+  for (auto p = m_propertyNameMap.constBegin();
+       p != m_propertyNameMap.constEnd(); ++p) {
     auto prop = p.value();
     auto f = m_getters[prop];
-    settings.setValue( p.key(), (this->*f)(prop) );
+    settings.setValue(p.key(), (this->*f)(prop));
   }
 }
 
@@ -685,13 +657,11 @@ void FitOptionsBrowser::saveSettings(QSettings& settings) const
  * Load property values from settings.
  * @param settings :: A QSettings instance provided by the user of this class.
  */
-void FitOptionsBrowser::loadSettings(const QSettings& settings)
-{
-  for(auto p = m_propertyNameMap.constBegin(); p != m_propertyNameMap.constEnd(); ++p)
-  {
-    QString value = settings.value( p.key() ).toString();
-    if ( !value.isEmpty() )
-    {
+void FitOptionsBrowser::loadSettings(const QSettings &settings) {
+  for (auto p = m_propertyNameMap.constBegin();
+       p != m_propertyNameMap.constEnd(); ++p) {
+    QString value = settings.value(p.key()).toString();
+    if (!value.isEmpty()) {
       auto prop = p.value();
       auto f = m_setters[prop];
       (this->*f)(prop, value);
@@ -703,8 +673,8 @@ void FitOptionsBrowser::loadSettings(const QSettings& settings)
  * Get the current fitting type, ie which algorithm to use:
  *    Simultaneous for Fit and Sequential for PlotPeakByLogValue.
  */
-FitOptionsBrowser::FittingType FitOptionsBrowser::getCurrentFittingType() const
-{
+FitOptionsBrowser::FittingType
+FitOptionsBrowser::getCurrentFittingType() const {
   auto value = m_enumManager->value(m_fittingTypeProp);
   return static_cast<FitOptionsBrowser::FittingType>(value);
 }
@@ -713,17 +683,18 @@ FitOptionsBrowser::FittingType FitOptionsBrowser::getCurrentFittingType() const
  * Set the current fitting type, ie which algorithm to use:
  *    Simultaneous for Fit and Sequential for PlotPeakByLogValue.
  */
-void FitOptionsBrowser::setCurrentFittingType(FitOptionsBrowser::FittingType fitType)
-{
+void FitOptionsBrowser::setCurrentFittingType(
+    FitOptionsBrowser::FittingType fitType) {
   m_enumManager->setValue(m_fittingTypeProp, fitType);
 }
 
 /**
- * Lock the browser in a particular fitting type state. Disable the switch option.
+ * Lock the browser in a particular fitting type state. Disable the switch
+ * option.
  * @param fitType :: Fitting type to lock the browser in.
  */
-void FitOptionsBrowser::lockCurrentFittingType(FitOptionsBrowser::FittingType fitType)
-{
+void FitOptionsBrowser::lockCurrentFittingType(
+    FitOptionsBrowser::FittingType fitType) {
   m_enumManager->setValue(m_fittingTypeProp, fitType);
   m_fittingTypeProp->setEnabled(false);
 }
@@ -731,8 +702,7 @@ void FitOptionsBrowser::lockCurrentFittingType(FitOptionsBrowser::FittingType fi
 /**
  * Make the fitting type changeable again.
  */
-void FitOptionsBrowser::unlockCurrentFittingType()
-{
+void FitOptionsBrowser::unlockCurrentFittingType() {
   m_fittingTypeProp->setEnabled(true);
 }
 
@@ -741,25 +711,19 @@ void FitOptionsBrowser::unlockCurrentFittingType()
  * @param prop :: A property to set the values to.
  * @param values :: New enum values.
  */
-void FitOptionsBrowser::setPropertyEnumValues(QtProperty* prop, const QStringList& values)
-{
+void FitOptionsBrowser::setPropertyEnumValues(QtProperty *prop,
+                                              const QStringList &values) {
   auto i = m_enumManager->value(prop);
-  if (!values.isEmpty() && values.front().isEmpty())
-  {
+  if (!values.isEmpty() && values.front().isEmpty()) {
     m_enumManager->setEnumNames(prop, values);
-  }
-  else
-  {
+  } else {
     QStringList names = values;
-    names.insert(0,"");
+    names.insert(0, "");
     m_enumManager->setEnumNames(prop, names);
   }
-  if (i < values.size())
-  {
+  if (i < values.size()) {
     m_enumManager->setValue(prop, i);
-  }
-  else
-  {
+  } else {
     m_enumManager->setValue(prop, 0);
   }
 }
@@ -768,26 +732,26 @@ void FitOptionsBrowser::setPropertyEnumValues(QtProperty* prop, const QStringLis
  * Define log names to use with the LogValue property.
  * @param logNames :: The log names
  */
-void FitOptionsBrowser::setLogNames(const QStringList& logNames)
-{
+void FitOptionsBrowser::setLogNames(const QStringList &logNames) {
   setPropertyEnumValues(m_logValue, logNames);
 }
 
 /**
  * Define names of function parameters that can be plotted against the LogValue.
  */
-void FitOptionsBrowser::setParameterNamesForPlotting(const QStringList& parNames)
-{
+void FitOptionsBrowser::setParameterNamesForPlotting(
+    const QStringList &parNames) {
   setPropertyEnumValues(m_plotParameter, parNames);
 }
 
 /**
- * Get name of a function parameter to plot against LogValue after sequential fitting.
+ * Get name of a function parameter to plot against LogValue after sequential
+ * fitting.
  */
-QString FitOptionsBrowser::getParameterToPlot() const
-{
+QString FitOptionsBrowser::getParameterToPlot() const {
   auto i = m_enumManager->value(m_plotParameter);
-  if (i < 0) i = 0;
+  if (i < 0)
+    i = 0;
   return m_enumManager->enumNames(m_plotParameter)[i];
 }
 
@@ -796,20 +760,24 @@ QString FitOptionsBrowser::getParameterToPlot() const
  *                *************************/
 
 /**
- * @brief Declares a property of type double, inserting it in the QMap attributes.
+ * @brief Declares a property of type double, inserting it in the QMap
+ * attributes.
  * Note: It does not add it to the browser. Use displayProperty() for this.
  * @exception std::runtime_error if property already declared
  * @return a raw pointer to the created property.
  */
-QtProperty* FitOptionsBrowser::addDoubleProperty(const QString &propertyName) {
-  if(m_propertyNameMap.contains(propertyName)){
-    throw std::runtime_error("Property " + propertyName.toStdString() + " already added.");
+QtProperty *FitOptionsBrowser::addDoubleProperty(const QString &propertyName) {
+  if (m_propertyNameMap.contains(propertyName)) {
+    throw std::runtime_error("Property " + propertyName.toStdString() +
+                             " already added.");
   }
   QtProperty *property = m_doubleManager->addProperty(propertyName);
   m_doubleManager->setDecimals(property, m_decimals);
-  m_doubleManager->setRange(property, -std::numeric_limits<double>::max(),std::numeric_limits<double>::max());
+  m_doubleManager->setRange(property, -std::numeric_limits<double>::max(),
+                            std::numeric_limits<double>::max());
   this->addProperty(propertyName, property,
-    &FitOptionsBrowser::getDoubleProperty, &FitOptionsBrowser::setDoubleProperty);
+                    &FitOptionsBrowser::getDoubleProperty,
+                    &FitOptionsBrowser::setDoubleProperty);
   return property;
 }
 
@@ -817,18 +785,21 @@ QtProperty* FitOptionsBrowser::addDoubleProperty(const QString &propertyName) {
  * @brief Show or hide in the browser a supported property
  * @param propertyName name of the existing property
  * @param show toggles the visibility of the property on/off
- * @pre if property is to be shown, property should not have been previously added to the browser
- * @pre if property is to be hidden, property should not have been previously removed from the browser
+ * @pre if property is to be shown, property should not have been previously
+ * added to the browser
+ * @pre if property is to be hidden, property should not have been previously
+ * removed from the browser
  */
-void FitOptionsBrowser::displayProperty(const QString &propertyName, bool show) {
-  if ( !m_propertyNameMap.contains(propertyName) ) {
-    throw std::runtime_error("Property " + propertyName.toStdString() + " isn't supported by the browser.");
+void FitOptionsBrowser::displayProperty(const QString &propertyName,
+                                        bool show) {
+  if (!m_propertyNameMap.contains(propertyName)) {
+    throw std::runtime_error("Property " + propertyName.toStdString() +
+                             " isn't supported by the browser.");
   }
   auto prop = m_propertyNameMap[propertyName];
-  if(show) {
+  if (show) {
     m_browser->addProperty(prop);
-  }
-  else {
+  } else {
     m_browser->removeProperty(prop);
   }
 }
@@ -837,15 +808,14 @@ void FitOptionsBrowser::displayProperty(const QString &propertyName, bool show)
  * Show sequential fit (PlotPeakByLogValue) properties and hide the others.
  */
 void FitOptionsBrowser::displaySequentialFitProperties() {
-  foreach(QtProperty* prop, m_sequentialProperties) {
+  foreach (QtProperty *prop, m_sequentialProperties) {
     m_browser->addProperty(prop);
   }
-  foreach(QtProperty* prop, m_simultaneousProperties) {
+  foreach (QtProperty *prop, m_simultaneousProperties) {
     m_browser->removeProperty(prop);
   }
   emit changedToSequentialFitting();
 }
 
-
 } // MantidWidgets
 } // MantidQt
diff --git a/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp b/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
index 4abf52af4c1dfae5cf61330cb3d9bca8d6ef81e4..c383bd716fb0524337b7f4112f576412cf81cbbc 100644
--- a/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
+++ b/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp
@@ -1502,8 +1502,8 @@ void FitPropertyBrowser::finishHandle(const Mantid::API::IAlgorithm *alg) {
   // the fit has been done against is sent as a parameter)
   QString name(QString::fromStdString(alg->getProperty("InputWorkspace")));
   if (name.contains('_')) // Must be fitting to raw data, need to group under
-                          // name without "_Raw".
-                          emit fittingDone(name.left(name.indexOf('_')));
+    // name without "_Raw".
+    emit fittingDone(name.left(name.indexOf('_')));
   else // else fitting to current workspace, group under same name.
     emit fittingDone(name);
 
@@ -2479,10 +2479,8 @@ void FitPropertyBrowser::setPeakToolOn(bool on) {
 /**
  * @brief impose a number of decimal places on all defined Double properties
  */
-void FitPropertyBrowser::updateDecimals()
-{
-  if (m_decimals < 0)
-  {
+void FitPropertyBrowser::updateDecimals() {
+  if (m_decimals < 0) {
     QSettings settings;
     settings.beginGroup("Mantid/FitBrowser");
     m_decimals = settings.value("decimals", 6).toInt();
diff --git a/MantidQt/MantidWidgets/src/FormulaDialogEditor.cpp b/MantidQt/MantidWidgets/src/FormulaDialogEditor.cpp
index a2582171da282ec0fc5218140a5675e50ba79acd..253787cd1a23547c671b1f7849875f39dc289608 100644
--- a/MantidQt/MantidWidgets/src/FormulaDialogEditor.cpp
+++ b/MantidQt/MantidWidgets/src/FormulaDialogEditor.cpp
@@ -4,23 +4,19 @@
 #include <QFileDialog>
 #include <QSettings>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
  * Open a UserFunctionDialog. Update the property if a file was selected.
  */
-void FormulaDialogEditor::runDialog()
-{
-    MantidQt::MantidWidgets::UserFunctionDialog dlg((QWidget*)parent(),getText());
-    if (dlg.exec() == QDialog::Accepted)
-    {
-      setText(dlg.getFormula());
-      updateProperty();
-    }
+void FormulaDialogEditor::runDialog() {
+  MantidQt::MantidWidgets::UserFunctionDialog dlg((QWidget *)parent(),
+                                                  getText());
+  if (dlg.exec() == QDialog::Accepted) {
+    setText(dlg.getFormula());
+    updateProperty();
+  }
 }
-
 }
 }
diff --git a/MantidQt/MantidWidgets/src/FunctionBrowser.cpp b/MantidQt/MantidWidgets/src/FunctionBrowser.cpp
index e8b40670d9135c71f8535a389587082298afaa58..8d7a7c576b6f846df0442dbf865e2d2f1e9702ce 100644
--- a/MantidQt/MantidWidgets/src/FunctionBrowser.cpp
+++ b/MantidQt/MantidWidgets/src/FunctionBrowser.cpp
@@ -39,15 +39,13 @@
 
 #include <algorithm>
 
-namespace{
-  const char * globalOptionName = "Global";
-  Mantid::Kernel::Logger g_log("Function Browser");
+namespace {
+const char *globalOptionName = "Global";
+Mantid::Kernel::Logger g_log("Function Browser");
 }
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /**
  * Constructor
@@ -55,42 +53,36 @@ namespace MantidWidgets
  * @param multi  :: Option to use the browser for multi-dataset fitting.
  */
 FunctionBrowser::FunctionBrowser(QWidget *parent, bool multi)
-  :QWidget(parent),m_multiDataset(multi),
-  m_numberOfDatasets(0),
-  m_currentDataset(0)
+    : QWidget(parent), m_multiDataset(multi), m_numberOfDatasets(0),
+      m_currentDataset(0)
 
 {
   // create m_browser
   createBrowser();
   createActions();
 
-  QVBoxLayout* layout = new QVBoxLayout(this);
+  QVBoxLayout *layout = new QVBoxLayout(this);
   layout->addWidget(m_browser);
-  layout->setContentsMargins(0,0,0,0);
-
+  layout->setContentsMargins(0, 0, 0, 0);
 }
 
 /**
  * Destructor
  */
-FunctionBrowser::~FunctionBrowser()
-{
-}
-
+FunctionBrowser::~FunctionBrowser() {}
 
 /**
  * Create the Qt property browser and set up property managers.
  */
-void FunctionBrowser::createBrowser()
-{
+void FunctionBrowser::createBrowser() {
   QStringList options;
-  if ( m_multiDataset )
-  {
+  if (m_multiDataset) {
     options << globalOptionName;
   }
   m_browser = new QtTreePropertyBrowser(NULL, options);
 
-  /* Create property managers: they create, own properties, get and set values  */
+  /* Create property managers: they create, own properties, get and set values
+   */
   m_functionManager = new QtGroupPropertyManager(this);
   m_parameterManager = new ParameterPropertyManager(this);
   m_attributeStringManager = new QtStringPropertyManager(this);
@@ -112,103 +104,129 @@ void FunctionBrowser::createBrowser()
   DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory(this);
   ParameterEditorFactory *paramEditorFactory = new ParameterEditorFactory(this);
 
-  QtAbstractEditorFactory<ParameterPropertyManager> *parameterEditorFactory(NULL);
-  if ( m_multiDataset )
-  {
+  QtAbstractEditorFactory<ParameterPropertyManager> *parameterEditorFactory(
+      NULL);
+  if (m_multiDataset) {
     auto buttonFactory = new DoubleDialogEditorFactory(this);
-    auto compositeFactory = new CompositeEditorFactory<ParameterPropertyManager>(this,buttonFactory);
+    auto compositeFactory =
+        new CompositeEditorFactory<ParameterPropertyManager>(this,
+                                                             buttonFactory);
     compositeFactory->setSecondaryFactory(globalOptionName, paramEditorFactory);
     parameterEditorFactory = compositeFactory;
-    connect(buttonFactory,SIGNAL(buttonClicked(QtProperty*)), this,SLOT(parameterButtonClicked(QtProperty*)));
-    connect(buttonFactory, SIGNAL(closeEditor()), m_browser, SLOT(closeEditor()));
-  }
-  else
-  {
+    connect(buttonFactory, SIGNAL(buttonClicked(QtProperty *)), this,
+            SLOT(parameterButtonClicked(QtProperty *)));
+    connect(buttonFactory, SIGNAL(closeEditor()), m_browser,
+            SLOT(closeEditor()));
+  } else {
     parameterEditorFactory = paramEditorFactory;
   }
-  
+
   QtLineEditFactory *lineEditFactory = new QtLineEditFactory(this);
   QtCheckBoxFactory *checkBoxFactory = new QtCheckBoxFactory(this);
-  FilenameDialogEditorFactory* filenameDialogEditorFactory = new FilenameDialogEditorFactory(this);
-  FormulaDialogEditorFactory* formulaDialogEditFactory = new FormulaDialogEditorFactory(this);
-  WorkspaceEditorFactory* workspaceEditorFactory = new WorkspaceEditorFactory(this);
+  FilenameDialogEditorFactory *filenameDialogEditorFactory =
+      new FilenameDialogEditorFactory(this);
+  FormulaDialogEditorFactory *formulaDialogEditFactory =
+      new FormulaDialogEditorFactory(this);
+  WorkspaceEditorFactory *workspaceEditorFactory =
+      new WorkspaceEditorFactory(this);
 
   // assign factories to property managers
   m_browser->setFactoryForManager(m_parameterManager, parameterEditorFactory);
   m_browser->setFactoryForManager(m_attributeStringManager, lineEditFactory);
-  m_browser->setFactoryForManager(m_attributeDoubleManager, doubleEditorFactory);
+  m_browser->setFactoryForManager(m_attributeDoubleManager,
+                                  doubleEditorFactory);
   m_browser->setFactoryForManager(m_attributeIntManager, spinBoxFactory);
   m_browser->setFactoryForManager(m_attributeBoolManager, checkBoxFactory);
   m_browser->setFactoryForManager(m_indexManager, lineEditFactory);
   m_browser->setFactoryForManager(m_tieManager, lineEditFactory);
   m_browser->setFactoryForManager(m_constraintManager, lineEditFactory);
-  m_browser->setFactoryForManager(m_filenameManager, filenameDialogEditorFactory);
+  m_browser->setFactoryForManager(m_filenameManager,
+                                  filenameDialogEditorFactory);
   m_browser->setFactoryForManager(m_formulaManager, formulaDialogEditFactory);
   m_browser->setFactoryForManager(m_workspaceManager, workspaceEditorFactory);
   m_browser->setFactoryForManager(m_attributeSizeManager, spinBoxFactory);
-  m_browser->setFactoryForManager(m_attributeVectorDoubleManager, doubleEditorFactory);
+  m_browser->setFactoryForManager(m_attributeVectorDoubleManager,
+                                  doubleEditorFactory);
 
   m_browser->setContextMenuPolicy(Qt::CustomContextMenu);
-  connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
-  connect(m_browser, SIGNAL(optionChanged(QtProperty*, const QString&, bool)), this, SLOT(globalChanged(QtProperty*, const QString&, bool)));
-
-  connect(m_attributeStringManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_attributeDoubleManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_attributeIntManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_attributeBoolManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_formulaManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_filenameManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(attributeChanged(QtProperty*)));
-  connect(m_attributeVectorDoubleManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(attributeVectorDoubleChanged(QtProperty*)));
-  connect(m_tieManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(tieChanged(QtProperty*)));
-  connect(m_parameterManager, SIGNAL(valueChanged(QtProperty*,double)),
-          SLOT(parameterChanged(QtProperty*)));
-
-  connect(m_browser, SIGNAL(currentItemChanged(QtBrowserItem*)), SLOT(updateCurrentFunctionIndex()));
+  connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)), this,
+          SLOT(popupMenu(const QPoint &)));
+  connect(m_browser, SIGNAL(optionChanged(QtProperty *, const QString &, bool)),
+          this, SLOT(globalChanged(QtProperty *, const QString &, bool)));
+
+  connect(m_attributeStringManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_attributeDoubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_attributeIntManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_attributeBoolManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_formulaManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_filenameManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(attributeChanged(QtProperty *)));
+  connect(m_attributeVectorDoubleManager, SIGNAL(propertyChanged(QtProperty *)),
+          this, SLOT(attributeVectorDoubleChanged(QtProperty *)));
+  connect(m_tieManager, SIGNAL(propertyChanged(QtProperty *)), this,
+          SLOT(tieChanged(QtProperty *)));
+  connect(m_parameterManager, SIGNAL(valueChanged(QtProperty *, double)),
+          SLOT(parameterChanged(QtProperty *)));
+
+  connect(m_browser, SIGNAL(currentItemChanged(QtBrowserItem *)),
+          SLOT(updateCurrentFunctionIndex()));
 
   m_browser->setFocusPolicy(Qt::StrongFocus);
-
 }
 
 /**
  * Create and connect actions
  */
-void FunctionBrowser::createActions()
-{
-  m_actionAddFunction = new QAction("Add function",this);
-  connect(m_actionAddFunction,SIGNAL(triggered()),this,SLOT(addFunction()));
+void FunctionBrowser::createActions() {
+  m_actionAddFunction = new QAction("Add function", this);
+  connect(m_actionAddFunction, SIGNAL(triggered()), this, SLOT(addFunction()));
 
-  m_actionRemoveFunction = new QAction("Remove function",this);
-  connect(m_actionRemoveFunction,SIGNAL(triggered()),this,SLOT(removeFunction()));
+  m_actionRemoveFunction = new QAction("Remove function", this);
+  connect(m_actionRemoveFunction, SIGNAL(triggered()), this,
+          SLOT(removeFunction()));
 
-  m_actionFixParameter = new QAction("Fix",this);
-  connect(m_actionFixParameter,SIGNAL(triggered()),this,SLOT(fixParameter()));
+  m_actionFixParameter = new QAction("Fix", this);
+  connect(m_actionFixParameter, SIGNAL(triggered()), this,
+          SLOT(fixParameter()));
 
-  m_actionRemoveTie = new QAction("Remove tie",this);
-  connect(m_actionRemoveTie,SIGNAL(triggered()),this,SLOT(removeTie()));
+  m_actionRemoveTie = new QAction("Remove tie", this);
+  connect(m_actionRemoveTie, SIGNAL(triggered()), this, SLOT(removeTie()));
 
-  m_actionAddTie = new QAction("Add tie",this);
-  connect(m_actionAddTie,SIGNAL(triggered()),this,SLOT(addTie()));
+  m_actionAddTie = new QAction("Add tie", this);
+  connect(m_actionAddTie, SIGNAL(triggered()), this, SLOT(addTie()));
 
-  m_actionFromClipboard = new QAction("Copy from clipboard",this);
-  connect(m_actionFromClipboard,SIGNAL(triggered()),this,SLOT(copyFromClipboard()));
+  m_actionFromClipboard = new QAction("Copy from clipboard", this);
+  connect(m_actionFromClipboard, SIGNAL(triggered()), this,
+          SLOT(copyFromClipboard()));
 
-  m_actionToClipboard = new QAction("Copy to clipboard",this);
-  connect(m_actionToClipboard,SIGNAL(triggered()),this,SLOT(copyToClipboard()));
+  m_actionToClipboard = new QAction("Copy to clipboard", this);
+  connect(m_actionToClipboard, SIGNAL(triggered()), this,
+          SLOT(copyToClipboard()));
 
-  m_actionConstraints = new QAction("Custom",this);
-  connect(m_actionConstraints,SIGNAL(triggered()),this,SLOT(addConstraints()));
+  m_actionConstraints = new QAction("Custom", this);
+  connect(m_actionConstraints, SIGNAL(triggered()), this,
+          SLOT(addConstraints()));
 
-  m_actionConstraints10 = new QAction("10%",this);
-  connect(m_actionConstraints10,SIGNAL(triggered()),this,SLOT(addConstraints10()));
+  m_actionConstraints10 = new QAction("10%", this);
+  connect(m_actionConstraints10, SIGNAL(triggered()), this,
+          SLOT(addConstraints10()));
 
-  m_actionConstraints50 = new QAction("50%",this);
-  connect(m_actionConstraints50,SIGNAL(triggered()),this,SLOT(addConstraints50()));
+  m_actionConstraints50 = new QAction("50%", this);
+  connect(m_actionConstraints50, SIGNAL(triggered()), this,
+          SLOT(addConstraints50()));
 
-  m_actionRemoveConstraints = new QAction("Remove constraints",this);
-  connect(m_actionRemoveConstraints,SIGNAL(triggered()),this,SLOT(removeConstraints()));
+  m_actionRemoveConstraints = new QAction("Remove constraints", this);
+  connect(m_actionRemoveConstraints, SIGNAL(triggered()), this,
+          SLOT(removeConstraints()));
 
-  m_actionRemoveConstraint = new QAction("Remove",this);
-  connect(m_actionRemoveConstraint,SIGNAL(triggered()),this,SLOT(removeConstraint()));
+  m_actionRemoveConstraint = new QAction("Remove", this);
+  connect(m_actionRemoveConstraint, SIGNAL(triggered()), this,
+          SLOT(removeConstraint()));
 
   m_parameterManager->setErrorsEnabled(true);
 }
@@ -216,8 +234,7 @@ void FunctionBrowser::createActions()
 /**
  * Clear the contents
  */
-void FunctionBrowser::clear()
-{
+void FunctionBrowser::clear() {
   m_browser->clear();
   m_properties.clear();
 }
@@ -226,17 +243,16 @@ void FunctionBrowser::clear()
  * Set the function in the browser
  * @param funStr :: FunctionFactory function creation string
  */
-void FunctionBrowser::setFunction(const QString& funStr)
-{
-  if ( funStr.isEmpty() ) return;
-  try
-  {
-    auto fun = Mantid::API::FunctionFactory::Instance().createInitialized( funStr.toStdString() );
-    if ( !fun ) return;
+void FunctionBrowser::setFunction(const QString &funStr) {
+  if (funStr.isEmpty())
+    return;
+  try {
+    auto fun = Mantid::API::FunctionFactory::Instance().createInitialized(
+        funStr.toStdString());
+    if (!fun)
+      return;
     this->setFunction(fun);
-  }
-  catch(...)
-  {
+  } catch (...) {
     // error in the input string
   }
 }
@@ -245,10 +261,9 @@ void FunctionBrowser::setFunction(const QString& funStr)
  * Set the function in the browser
  * @param fun :: A function
  */
-void FunctionBrowser::setFunction(Mantid::API::IFunction_sptr fun)
-{
+void FunctionBrowser::setFunction(Mantid::API::IFunction_sptr fun) {
   clear();
-  addFunction(NULL,fun);
+  addFunction(NULL, fun);
   emit functionStructureChanged();
 }
 
@@ -257,20 +272,16 @@ void FunctionBrowser::setFunction(Mantid::API::IFunction_sptr fun)
  * @param parent :: The parent property
  * @param subproperty :: New sub-property
  */
-FunctionBrowser::AProperty FunctionBrowser::addProperty(QtProperty* parent, QtProperty* subproperty)
-{
+FunctionBrowser::AProperty
+FunctionBrowser::addProperty(QtProperty *parent, QtProperty *subproperty) {
   AProperty ap;
   ap.prop = subproperty;
-  if (parent == NULL)
-  {
+  if (parent == NULL) {
     ap.item = m_browser->addProperty(subproperty);
-  }
-  else
-  {
+  } else {
     parent->addSubProperty(subproperty);
     auto items = m_browser->items(subproperty);
-    if (items.isEmpty())
-    {
+    if (items.isEmpty()) {
       throw std::runtime_error("Unexpected error in FunctionBrowser [1]");
     }
     ap.item = items[0];
@@ -284,10 +295,10 @@ FunctionBrowser::AProperty FunctionBrowser::addProperty(QtProperty* parent, QtPr
  * Remove and delete property
  * @param prop :: Property to remove.
  */
-void FunctionBrowser::removeProperty(QtProperty *prop)
-{
+void FunctionBrowser::removeProperty(QtProperty *prop) {
   auto p = m_properties.find(prop);
-  if (p == m_properties.end()) return;
+  if (p == m_properties.end())
+    return;
   AProperty ap = *p;
 
   // remove references to the children
@@ -295,48 +306,33 @@ void FunctionBrowser::removeProperty(QtProperty *prop)
   foreach (QtProperty *child, children) { m_properties.remove(child); }
   m_properties.erase(p);
 
-  if ( isFunction(prop) )
-  {
+  if (isFunction(prop)) {
     m_ties.remove(prop);
   }
 
-  if ( isTie(prop) )
-  {// 
-    for(auto it = m_ties.begin(); it != m_ties.end(); ++it)
-    {
-      if (it.value().tieProp == prop)
-      {
+  if (isTie(prop)) { //
+    for (auto it = m_ties.begin(); it != m_ties.end(); ++it) {
+      if (it.value().tieProp == prop) {
         m_ties.erase(it);
         break;
       }
     }
   }
 
-  if ( isConstraint(prop) )
-  {
-    for(auto it = m_constraints.begin(); it != m_constraints.end(); ++it)
-    {
-      auto& cp = it.value();
-      if ( cp.lower == prop )
-      {
-        if ( !cp.upper )
-        {
+  if (isConstraint(prop)) {
+    for (auto it = m_constraints.begin(); it != m_constraints.end(); ++it) {
+      auto &cp = it.value();
+      if (cp.lower == prop) {
+        if (!cp.upper) {
           m_constraints.erase(it);
-        }
-        else
-        {
+        } else {
           cp.lower = NULL;
         }
         break;
-      }
-      else if ( cp.upper == prop )
-      {
-        if ( !cp.lower )
-        {
+      } else if (cp.upper == prop) {
+        if (!cp.lower) {
           m_constraints.erase(it);
-        }
-        else
-        {
+        } else {
           cp.upper = NULL;
         }
         break;
@@ -345,12 +341,9 @@ void FunctionBrowser::removeProperty(QtProperty *prop)
   }
 
   // remove property from Qt browser
-  if (ap.parent)
-  {
+  if (ap.parent) {
     ap.parent->removeSubProperty(prop);
-  }
-  else
-  {
+  } else {
     m_browser->removeProperty(prop);
   }
   delete prop;
@@ -362,14 +355,15 @@ void FunctionBrowser::removeProperty(QtProperty *prop)
  * @param funName :: Function name
  * @return :: A set AProperty struct
  */
-FunctionBrowser::AProperty FunctionBrowser::addFunctionProperty(QtProperty* parent, QString funName)
-{
+FunctionBrowser::AProperty
+FunctionBrowser::addFunctionProperty(QtProperty *parent, QString funName) {
   // check that parent is a function property
-  if (parent && dynamic_cast<QtAbstractPropertyManager*>(m_functionManager) != parent->propertyManager())
-  {
+  if (parent &&
+      dynamic_cast<QtAbstractPropertyManager *>(m_functionManager) !=
+          parent->propertyManager()) {
     throw std::runtime_error("Unexpected error in FunctionBrowser [2]");
   }
-  QtProperty* prop = m_functionManager->addProperty(funName);
+  QtProperty *prop = m_functionManager->addProperty(funName);
   return addProperty(parent, prop);
 }
 
@@ -380,25 +374,26 @@ FunctionBrowser::AProperty FunctionBrowser::addFunctionProperty(QtProperty* pare
  * @param paramDesc :: Parameter description
  * @param paramValue :: Parameter value
  */
-FunctionBrowser::AProperty FunctionBrowser::addParameterProperty(QtProperty* parent, QString paramName, QString paramDesc, double paramValue)
-{
+FunctionBrowser::AProperty
+FunctionBrowser::addParameterProperty(QtProperty *parent, QString paramName,
+                                      QString paramDesc, double paramValue) {
   // check that parent is a function property
-  if (!parent || dynamic_cast<QtAbstractPropertyManager*>(m_functionManager) != parent->propertyManager())
-  {
+  if (!parent ||
+      dynamic_cast<QtAbstractPropertyManager *>(m_functionManager) !=
+          parent->propertyManager()) {
     throw std::runtime_error("Unexpected error in FunctionBrowser [3]");
   }
-  QtProperty* prop = m_parameterManager->addProperty(paramName);
+  QtProperty *prop = m_parameterManager->addProperty(paramName);
   m_parameterManager->blockSignals(true);
-  m_parameterManager->setDecimals(prop,6);
-  m_parameterManager->setValue(prop,paramValue);
-  m_parameterManager->setDescription(prop,paramDesc.toStdString());
+  m_parameterManager->setDecimals(prop, 6);
+  m_parameterManager->setValue(prop, paramValue);
+  m_parameterManager->setDescription(prop, paramDesc.toStdString());
   m_parameterManager->blockSignals(false);
 
-  if ( m_multiDataset )
-  {
-    prop->setOption(globalOptionName,false);
+  if (m_multiDataset) {
+    prop->setOption(globalOptionName, false);
   }
-  return addProperty(parent,prop);
+  return addProperty(parent, prop);
 }
 
 /**
@@ -406,13 +401,10 @@ FunctionBrowser::AProperty FunctionBrowser::addParameterProperty(QtProperty* par
  * @param prop :: Property of the function or NULL
  * @param fun :: A function
  */
-void FunctionBrowser::setFunction(QtProperty* prop, Mantid::API::IFunction_sptr fun)
-{
+void FunctionBrowser::setFunction(QtProperty *prop,
+                                  Mantid::API::IFunction_sptr fun) {
   auto children = prop->subProperties();
-  foreach(QtProperty* child, children)
-  {
-    removeProperty(child);
-  }
+  foreach (QtProperty *child, children) { removeProperty(child); }
   m_localParameterValues.clear();
   addAttributeAndParameterProperties(prop, fun);
 }
@@ -422,21 +414,21 @@ void FunctionBrowser::setFunction(QtProperty* prop, Mantid::API::IFunction_sptr
  * @param prop :: Property of the parent composite function or NULL
  * @param fun :: FunctionFactory function creation string
  */
-void FunctionBrowser::addFunction(QtProperty* prop, Mantid::API::IFunction_sptr fun)
-{
-  if ( !prop )
-  {
-    AProperty ap = addFunctionProperty(NULL,QString::fromStdString(fun->name()));
+void FunctionBrowser::addFunction(QtProperty *prop,
+                                  Mantid::API::IFunction_sptr fun) {
+  if (!prop) {
+    AProperty ap =
+        addFunctionProperty(NULL, QString::fromStdString(fun->name()));
     setFunction(ap.prop, fun);
-  }
-  else
-  {
-    Mantid::API::IFunction_sptr parentFun =  getFunction(prop);
-    if ( !parentFun ) return;
-    auto cf = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(parentFun);
-    if ( !cf )
-    {
-      throw std::runtime_error("FunctionBrowser: CompositeFunction is expected for addFunction");
+  } else {
+    Mantid::API::IFunction_sptr parentFun = getFunction(prop);
+    if (!parentFun)
+      return;
+    auto cf =
+        boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(parentFun);
+    if (!cf) {
+      throw std::runtime_error(
+          "FunctionBrowser: CompositeFunction is expected for addFunction");
     }
     cf->addFunction(fun);
     setFunction(prop, cf);
@@ -448,121 +440,119 @@ void FunctionBrowser::addFunction(QtProperty* prop, Mantid::API::IFunction_sptr
  * Attribute visitor to create a QtProperty. Depending on the attribute type
  * the appropriate apply() method is used.
  */
-class CreateAttributePropertyForFunctionBrowser: public Mantid::API::IFunction::ConstAttributeVisitor<FunctionBrowser::AProperty>
-{
+class CreateAttributePropertyForFunctionBrowser
+    : public Mantid::API::IFunction::ConstAttributeVisitor<
+          FunctionBrowser::AProperty> {
 public:
-  CreateAttributePropertyForFunctionBrowser(FunctionBrowser* browser, QtProperty* parent,QString attName)
-    :m_browser(browser),m_parent(parent),m_attName(attName)
-  {
+  CreateAttributePropertyForFunctionBrowser(FunctionBrowser *browser,
+                                            QtProperty *parent, QString attName)
+      : m_browser(browser), m_parent(parent), m_attName(attName) {
     // check that parent is a function property
-    if (!m_parent || dynamic_cast<QtAbstractPropertyManager*>(m_browser->m_functionManager) != m_parent->propertyManager())
-    {
+    if (!m_parent ||
+        dynamic_cast<QtAbstractPropertyManager *>(
+            m_browser->m_functionManager) != m_parent->propertyManager()) {
       throw std::runtime_error("Unexpected error in FunctionBrowser [4]");
     }
   }
+
 protected:
   /// Create string property
   FunctionBrowser::AProperty apply(const std::string &str) const override {
-    QtProperty* prop = NULL;
-    if (m_attName == "FileName")
-    {
+    QtProperty *prop = NULL;
+    if (m_attName == "FileName") {
       prop = m_browser->m_filenameManager->addProperty(m_attName);
       m_browser->m_filenameManager->setValue(prop, QString::fromStdString(str));
-    }
-    else if ( m_attName == "Formula" )
-    {
+    } else if (m_attName == "Formula") {
       prop = m_browser->m_formulaManager->addProperty(m_attName);
       m_browser->m_formulaManager->setValue(prop, QString::fromStdString(str));
-    }
-    else if ( m_attName == "Workspace" )
-    {
+    } else if (m_attName == "Workspace") {
       prop = m_browser->m_workspaceManager->addProperty(m_attName);
-      m_browser->m_workspaceManager->setValue(prop, QString::fromStdString(str));
-    }
-    else
-    {
+      m_browser->m_workspaceManager->setValue(prop,
+                                              QString::fromStdString(str));
+    } else {
       prop = m_browser->m_attributeStringManager->addProperty(m_attName);
-      m_browser->m_attributeStringManager->setValue(prop, QString::fromStdString(str));
+      m_browser->m_attributeStringManager->setValue(
+          prop, QString::fromStdString(str));
     }
-    return m_browser->addProperty(m_parent,prop);
+    return m_browser->addProperty(m_parent, prop);
   }
   /// Create double property
   FunctionBrowser::AProperty apply(const double &d) const override {
-    QtProperty* prop = m_browser->m_attributeDoubleManager->addProperty(m_attName);
+    QtProperty *prop =
+        m_browser->m_attributeDoubleManager->addProperty(m_attName);
     m_browser->m_attributeDoubleManager->setValue(prop, d);
-    return m_browser->addProperty(m_parent,prop);
+    return m_browser->addProperty(m_parent, prop);
   }
   /// Create int property
   FunctionBrowser::AProperty apply(const int &i) const override {
-    QtProperty* prop = m_browser->m_attributeIntManager->addProperty(m_attName);
+    QtProperty *prop = m_browser->m_attributeIntManager->addProperty(m_attName);
     m_browser->m_attributeIntManager->setValue(prop, i);
-    return m_browser->addProperty(m_parent,prop);
+    return m_browser->addProperty(m_parent, prop);
   }
   /// Create bool property
   FunctionBrowser::AProperty apply(const bool &b) const override {
-    QtProperty* prop = m_browser->m_attributeBoolManager->addProperty(m_attName);
+    QtProperty *prop =
+        m_browser->m_attributeBoolManager->addProperty(m_attName);
     m_browser->m_attributeBoolManager->setValue(prop, b);
-    return m_browser->addProperty(m_parent,prop);
+    return m_browser->addProperty(m_parent, prop);
   }
   /// Create vector property
   FunctionBrowser::AProperty
   apply(const std::vector<double> &v) const override {
-    QtProperty* prop = m_browser->m_attributeVectorManager->addProperty(m_attName);
-    FunctionBrowser::AProperty aprop = m_browser->addProperty(m_parent,prop);
-
-    QtProperty* sizeProp = m_browser->m_attributeSizeManager->addProperty("Size");
-    m_browser->m_attributeSizeManager->setValue( sizeProp, static_cast<int>(v.size()) );
-    m_browser->addProperty( prop, sizeProp );
+    QtProperty *prop =
+        m_browser->m_attributeVectorManager->addProperty(m_attName);
+    FunctionBrowser::AProperty aprop = m_browser->addProperty(m_parent, prop);
+
+    QtProperty *sizeProp =
+        m_browser->m_attributeSizeManager->addProperty("Size");
+    m_browser->m_attributeSizeManager->setValue(sizeProp,
+                                                static_cast<int>(v.size()));
+    m_browser->addProperty(prop, sizeProp);
     sizeProp->setEnabled(false);
 
     m_browser->m_attributeVectorDoubleManager->blockSignals(true);
     QString parName = "value[%1]";
-    for(size_t i = 0; i < v.size(); ++i)
-    {
-        QtProperty *dprop = m_browser->m_attributeVectorDoubleManager->addProperty( parName.arg(i) );
-        m_browser->m_attributeVectorDoubleManager->setValue( dprop, v[i] );
-        m_browser->addProperty( prop, dprop );
+    for (size_t i = 0; i < v.size(); ++i) {
+      QtProperty *dprop =
+          m_browser->m_attributeVectorDoubleManager->addProperty(
+              parName.arg(i));
+      m_browser->m_attributeVectorDoubleManager->setValue(dprop, v[i]);
+      m_browser->addProperty(prop, dprop);
     }
     m_browser->m_attributeVectorDoubleManager->blockSignals(false);
 
-    m_browser->m_browser->setExpanded( aprop.item, false );
+    m_browser->m_browser->setExpanded(aprop.item, false);
     return aprop;
   }
+
 private:
-  FunctionBrowser* m_browser;
-  QtProperty* m_parent;
+  FunctionBrowser *m_browser;
+  QtProperty *m_parent;
   QString m_attName;
 };
 
 /**
- * Attribute visitor to set an attribute from a QtProperty. Depending on the attribute type
+ * Attribute visitor to set an attribute from a QtProperty. Depending on the
+ * attribute type
  * the appropriate apply() method is used.
  */
-class SetAttributeFromProperty: public Mantid::API::IFunction::AttributeVisitor<>
-{
+class SetAttributeFromProperty
+    : public Mantid::API::IFunction::AttributeVisitor<> {
 public:
-  SetAttributeFromProperty(FunctionBrowser* browser, QtProperty* prop)
-    :m_browser(browser),m_prop(prop)
-  {
-  }
+  SetAttributeFromProperty(FunctionBrowser *browser, QtProperty *prop)
+      : m_browser(browser), m_prop(prop) {}
+
 protected:
   /// Set string attribute
   void apply(std::string &str) const override {
     QString attName = m_prop->propertyName();
-    if ( attName == "FileName" )
-    {
+    if (attName == "FileName") {
       str = m_browser->m_filenameManager->value(m_prop).toStdString();
-    }
-    else if ( attName == "Formula" )
-    {
+    } else if (attName == "Formula") {
       str = m_browser->m_formulaManager->value(m_prop).toStdString();
-    }
-    else if ( attName == "Workspace" )
-    {
+    } else if (attName == "Workspace") {
       str = m_browser->m_workspaceManager->value(m_prop).toStdString();
-    }
-    else
-    {
+    } else {
       str = m_browser->m_attributeStringManager->value(m_prop).toStdString();
     }
   }
@@ -595,9 +585,10 @@ protected:
       v[i] = m_browser->m_attributeVectorDoubleManager->value(members[i + 1]);
     }
   }
+
 private:
-  FunctionBrowser* m_browser;
-  QtProperty* m_prop;
+  FunctionBrowser *m_browser;
+  QtProperty *m_prop;
 };
 
 /**
@@ -606,61 +597,55 @@ private:
  * @param attName :: Attribute name
  * @param att :: Attribute value
  */
-FunctionBrowser::AProperty FunctionBrowser::addAttributeProperty(QtProperty* parent, QString attName, const Mantid::API::IFunction::Attribute& att)
-{
-  CreateAttributePropertyForFunctionBrowser cap(this,parent,attName);
+FunctionBrowser::AProperty FunctionBrowser::addAttributeProperty(
+    QtProperty *parent, QString attName,
+    const Mantid::API::IFunction::Attribute &att) {
+  CreateAttributePropertyForFunctionBrowser cap(this, parent, attName);
   return att.apply(cap);
 }
 
 /**
- * Add attribute and parameter properties to a function property. For a composite function
+ * Add attribute and parameter properties to a function property. For a
+ * composite function
  *  adds all member functions' properties
  * @param prop :: A function property
  * @param fun :: Shared pointer to a created function
  */
-void FunctionBrowser::addAttributeAndParameterProperties(QtProperty* prop, Mantid::API::IFunction_sptr fun)
-{
+void FunctionBrowser::addAttributeAndParameterProperties(
+    QtProperty *prop, Mantid::API::IFunction_sptr fun) {
   // add the function index property
   addIndexProperty(prop);
 
   // add attribute properties
   auto attributeNames = fun->getAttributeNames();
-  for(auto att = attributeNames.begin(); att != attributeNames.end(); ++att)
-  {
+  for (auto att = attributeNames.begin(); att != attributeNames.end(); ++att) {
     QString attName = QString::fromStdString(*att);
     addAttributeProperty(prop, attName, fun->getAttribute(*att));
   }
 
   auto cf = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(fun);
-  if (cf)
-  {// if composite add members
-    for(size_t i = 0; i < cf->nFunctions(); ++i)
-    {
-      AProperty ap = addFunctionProperty(prop,QString::fromStdString(cf->getFunction(i)->name()));
-      addAttributeAndParameterProperties(ap.prop,cf->getFunction(i));
-    }
-  }
-  else
-  {// if simple add parameters
-    for(size_t i = 0; i < fun->nParams(); ++i)
-    {
+  if (cf) { // if composite add members
+    for (size_t i = 0; i < cf->nFunctions(); ++i) {
+      AProperty ap = addFunctionProperty(
+          prop, QString::fromStdString(cf->getFunction(i)->name()));
+      addAttributeAndParameterProperties(ap.prop, cf->getFunction(i));
+    }
+  } else { // if simple add parameters
+    for (size_t i = 0; i < fun->nParams(); ++i) {
       QString name = QString::fromStdString(fun->parameterName(i));
       QString desc = QString::fromStdString(fun->parameterDescription(i));
       double value = fun->getParameter(i);
       AProperty ap = addParameterProperty(prop, name, desc, value);
       // if parameter has a tie
-      if (fun->isFixed(i))
-      {
+      if (fun->isFixed(i)) {
         auto tie = fun->getTie(i);
-        if (tie)
-        {
+        if (tie) {
           addTieProperty(ap.prop, QString::fromStdString(tie->asString()));
         }
       }
       auto c = fun->getConstraint(i);
-      if ( c )
-      {
-        addConstraintProperties( ap.prop, QString::fromStdString( c->asString() ) );
+      if (c) {
+        addConstraintProperties(ap.prop, QString::fromStdString(c->asString()));
       }
     }
   }
@@ -669,52 +654,49 @@ void FunctionBrowser::addAttributeAndParameterProperties(QtProperty* prop, Manti
 /**
  * Add property showing function's index in the composite function
  * @param prop :: A function property
- * @return :: AProperty struct for added property. If all fields are NULL - property wasn't added
+ * @return :: AProperty struct for added property. If all fields are NULL -
+ * property wasn't added
  *  because it is the top function
  */
-FunctionBrowser::AProperty FunctionBrowser::addIndexProperty(QtProperty* prop)
-{
+FunctionBrowser::AProperty FunctionBrowser::addIndexProperty(QtProperty *prop) {
   AProperty ap;
   ap.item = NULL;
   ap.parent = NULL;
   ap.prop = NULL;
-  if (!prop) return ap;
-  if (!isFunction(prop)) return ap;
-  if ( !m_properties[prop].parent ) return ap;
+  if (!prop)
+    return ap;
+  if (!isFunction(prop))
+    return ap;
+  if (!m_properties[prop].parent)
+    return ap;
 
   QString index = "fff";
-  QtProperty* ip = m_indexManager->addProperty("Index");
+  QtProperty *ip = m_indexManager->addProperty("Index");
   ip->setEnabled(false);
-  m_indexManager->setValue(ip,index);
-  return addProperty(prop,ip);
-
+  m_indexManager->setValue(ip, index);
+  return addProperty(prop, ip);
 }
 
 /**
- * Update function index properties 
+ * Update function index properties
  * @param prop :: A function property
  * @param index :: The parent function's index
  */
-void FunctionBrowser::updateFunctionIndices(QtProperty* prop, QString index)
-{
-  if ( prop == NULL )
-  {
+void FunctionBrowser::updateFunctionIndices(QtProperty *prop, QString index) {
+  if (prop == NULL) {
     auto top = m_browser->properties();
-    if (top.isEmpty()) return;
+    if (top.isEmpty())
+      return;
     prop = top[0];
   }
   auto children = prop->subProperties();
   size_t i = 0;
-  foreach(QtProperty* child, children)
-  {
-    if (isFunction(child))
-    {
-      updateFunctionIndices(child,index + "f" + QString::number(i) + ".");
+  foreach (QtProperty *child, children) {
+    if (isFunction(child)) {
+      updateFunctionIndices(child, index + "f" + QString::number(i) + ".");
       ++i;
-    }
-    else if (isIndex(child))
-    {
-      m_indexManager->setValue(child,index);
+    } else if (isIndex(child)) {
+      m_indexManager->setValue(child, index);
     }
   }
 }
@@ -722,32 +704,29 @@ void FunctionBrowser::updateFunctionIndices(QtProperty* prop, QString index)
 /**
  * Get property of the overall function.
  */
-FunctionBrowser::AProperty FunctionBrowser::getFunctionProperty() const
-{
+FunctionBrowser::AProperty FunctionBrowser::getFunctionProperty() const {
   auto props = m_browser->properties();
-  if ( props.isEmpty() )
-  {
+  if (props.isEmpty()) {
     AProperty ap;
     ap.item = NULL;
     ap.parent = NULL;
     ap.prop = NULL;
     return ap;
   }
-  QtProperty* prop = props[0];
+  QtProperty *prop = props[0];
   return m_properties[prop];
 }
 
 /**
  * Get a list of names of global parameters
  */
-QStringList FunctionBrowser::getGlobalParameters() const
-{
+QStringList FunctionBrowser::getGlobalParameters() const {
   QStringList out;
-  for(auto propIt = m_properties.begin(); propIt != m_properties.end(); ++propIt)
-  {
+  for (auto propIt = m_properties.begin(); propIt != m_properties.end();
+       ++propIt) {
     QtProperty *prop = propIt->prop;
-    if ( prop->hasOption(globalOptionName) && prop->checkOption(globalOptionName) )
-    {
+    if (prop->hasOption(globalOptionName) &&
+        prop->checkOption(globalOptionName)) {
       out << getIndex(prop) + prop->propertyName();
     }
   }
@@ -757,14 +736,13 @@ QStringList FunctionBrowser::getGlobalParameters() const
 /**
  * Get a list of names of local parameters
  */
-QStringList FunctionBrowser::getLocalParameters() const
-{
+QStringList FunctionBrowser::getLocalParameters() const {
   QStringList out;
-  for(auto propIt = m_properties.begin(); propIt != m_properties.end(); ++propIt)
-  {
+  for (auto propIt = m_properties.begin(); propIt != m_properties.end();
+       ++propIt) {
     QtProperty *prop = propIt->prop;
-    if ( prop->hasOption(globalOptionName) && !prop->checkOption(globalOptionName) )
-    {
+    if (prop->hasOption(globalOptionName) &&
+        !prop->checkOption(globalOptionName)) {
       out << getIndex(prop) + prop->propertyName();
     }
   }
@@ -775,86 +753,93 @@ QStringList FunctionBrowser::getLocalParameters() const
  * Check if property is a function group
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isFunction(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_functionManager) == prop->propertyManager();
+bool FunctionBrowser::isFunction(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_functionManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if property is any of the string attributes
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isStringAttribute(QtProperty* prop) const
-{
-  return prop && (
-    dynamic_cast<QtAbstractPropertyManager*>(m_attributeStringManager) == prop->propertyManager() ||
-    dynamic_cast<QtAbstractPropertyManager*>(m_formulaManager) == prop->propertyManager() ||
-    dynamic_cast<QtAbstractPropertyManager*>(m_filenameManager) == prop->propertyManager() ||
-    dynamic_cast<QtAbstractPropertyManager*>(m_workspaceManager) == prop->propertyManager()
-    );
+bool FunctionBrowser::isStringAttribute(QtProperty *prop) const {
+  return prop &&
+         (dynamic_cast<QtAbstractPropertyManager *>(m_attributeStringManager) ==
+              prop->propertyManager() ||
+          dynamic_cast<QtAbstractPropertyManager *>(m_formulaManager) ==
+              prop->propertyManager() ||
+          dynamic_cast<QtAbstractPropertyManager *>(m_filenameManager) ==
+              prop->propertyManager() ||
+          dynamic_cast<QtAbstractPropertyManager *>(m_workspaceManager) ==
+              prop->propertyManager());
 }
 
 /**
  * Check if property is a function attribute
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isDoubleAttribute(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_attributeDoubleManager) == prop->propertyManager();
+bool FunctionBrowser::isDoubleAttribute(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_attributeDoubleManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if property is a function attribute
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isIntAttribute(QtProperty* prop) const
-{
-    return prop && dynamic_cast<QtAbstractPropertyManager*>(m_attributeIntManager) == prop->propertyManager();
+bool FunctionBrowser::isIntAttribute(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_attributeIntManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if property is a function bool attribute
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isBoolAttribute(QtProperty *prop) const
-{
-    return prop && dynamic_cast<QtAbstractPropertyManager*>(m_attributeBoolManager) == prop->propertyManager();
+bool FunctionBrowser::isBoolAttribute(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_attributeBoolManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if property is a function vector attribute
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isVectorAttribute(QtProperty *prop) const
-{
-    return prop && dynamic_cast<QtAbstractPropertyManager*>(m_attributeVectorManager) == prop->propertyManager();
+bool FunctionBrowser::isVectorAttribute(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_attributeVectorManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if property is a function attribute
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isAttribute(QtProperty* prop) const
-{
-  return isStringAttribute(prop) || isDoubleAttribute(prop) || isIntAttribute(prop) ||
-          isBoolAttribute(prop) || isVectorAttribute(prop);
+bool FunctionBrowser::isAttribute(QtProperty *prop) const {
+  return isStringAttribute(prop) || isDoubleAttribute(prop) ||
+         isIntAttribute(prop) || isBoolAttribute(prop) ||
+         isVectorAttribute(prop);
 }
 
 /**
  * Check if property is a function parameter
  * @param prop :: Property to check
  */
-bool FunctionBrowser::isParameter(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_parameterManager) == prop->propertyManager();
+bool FunctionBrowser::isParameter(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_parameterManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Get parameter value as a string
  * @param prop :: A parameter property
  */
-double FunctionBrowser::getParameter(QtProperty* prop) const
-{
+double FunctionBrowser::getParameter(QtProperty *prop) const {
   return m_parameterManager->value(prop);
 }
 
@@ -862,26 +847,25 @@ double FunctionBrowser::getParameter(QtProperty* prop) const
  * Check if a property is an index
  * @param prop :: A property
  */
-bool FunctionBrowser::isIndex(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_indexManager) == prop->propertyManager();
+bool FunctionBrowser::isIndex(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_indexManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Get the function index for a property
  * @param prop :: A property
  */
-QString FunctionBrowser::getIndex(QtProperty* prop) const
-{
-  if ( !prop ) return "";
-  if (isFunction(prop))
-  {
+QString FunctionBrowser::getIndex(QtProperty *prop) const {
+  if (!prop)
+    return "";
+  if (isFunction(prop)) {
     auto props = prop->subProperties();
-    if (props.isEmpty()) return "";
-    for(auto it = props.begin(); it != props.end(); ++it)
-    {
-      if ( isIndex(*it) )
-      {
+    if (props.isEmpty())
+      return "";
+    for (auto it = props.begin(); it != props.end(); ++it) {
+      if (isIndex(*it)) {
         return m_indexManager->value(*it);
       }
     }
@@ -896,25 +880,22 @@ QString FunctionBrowser::getIndex(QtProperty* prop) const
  * Get name of the parameter for a property
  * @param prop :: A property
  */
-QString FunctionBrowser::getParameterName(QtProperty* prop)
-{
-  return  getIndex(prop) + prop->propertyName();
+QString FunctionBrowser::getParameterName(QtProperty *prop) {
+  return getIndex(prop) + prop->propertyName();
 }
 
-
 /**
  * Return function property for a function with given index.
- * @param index :: Function index to search, or empty string for top-level function
+ * @param index :: Function index to search, or empty string for top-level
+ * function
  * @return Function property, or NULL if not found
  */
-QtProperty* FunctionBrowser::getFunctionProperty(const QString& index) const
-{
-  // Might not be the most efficient way to do it. m_functionManager might be searched instead,
+QtProperty *FunctionBrowser::getFunctionProperty(const QString &index) const {
+  // Might not be the most efficient way to do it. m_functionManager might be
+  // searched instead,
   // but it is not being kept up-to-date at the moment (is not cleared).
-  foreach (auto property, m_properties.keys())
-  {
-    if(isFunction(property) && getIndex(property) == index)
-    {
+  foreach (auto property, m_properties.keys()) {
+    if (isFunction(property) && getIndex(property) == index) {
       return property;
     }
   }
@@ -923,16 +904,14 @@ QtProperty* FunctionBrowser::getFunctionProperty(const QString& index) const
   return NULL;
 }
 
-
 /**
  * Add a tie property
  * @param prop :: Parent parameter property
  * @param tie :: A tie string
  */
-FunctionBrowser::AProperty FunctionBrowser::addTieProperty(QtProperty* prop, QString tie)
-{
-  if ( !prop )
-  {
+FunctionBrowser::AProperty FunctionBrowser::addTieProperty(QtProperty *prop,
+                                                           QString tie) {
+  if (!prop) {
     throw std::runtime_error("FunctionBrowser: null property pointer");
   }
   AProperty ap;
@@ -940,50 +919,46 @@ FunctionBrowser::AProperty FunctionBrowser::addTieProperty(QtProperty* prop, QSt
   ap.prop = NULL;
   ap.parent = NULL;
 
-  if ( !isParameter(prop) ) return ap;
+  if (!isParameter(prop))
+    return ap;
 
   Mantid::API::Expression expr;
   expr.parse(tie.toStdString());
   // Do parameter names include composite function index
   bool isComposite = false;
   auto vars = expr.getVariables();
-  for(auto var = vars.begin(); var != vars.end(); ++var)
-  {
+  for (auto var = vars.begin(); var != vars.end(); ++var) {
     // nesting level of a particular variable
-    int n = static_cast<int>(std::count(var->begin(),var->end(),'.'));
-    if ( n != 0 )
-    {
+    int n = static_cast<int>(std::count(var->begin(), var->end(), '.'));
+    if (n != 0) {
       isComposite = true;
     }
   }
 
   // check that tie has form <paramName>=<expression>
-  if ( expr.name() != "=" )
-  {// prepend "<paramName>="
-    if ( !isComposite )
-    {
+  if (expr.name() != "=") { // prepend "<paramName>="
+    if (!isComposite) {
       tie.prepend(prop->propertyName() + "=");
-    }
-    else
-    {
+    } else {
       QString index = getIndex(prop);
       tie.prepend(index + prop->propertyName() + "=");
     }
   }
 
   // find the property of the function
-  QtProperty *funProp = isComposite? getFunctionProperty().prop : m_properties[prop].parent;
+  QtProperty *funProp =
+      isComposite ? getFunctionProperty().prop : m_properties[prop].parent;
 
   m_tieManager->blockSignals(true);
-  QtProperty* tieProp = m_tieManager->addProperty("Tie");
+  QtProperty *tieProp = m_tieManager->addProperty("Tie");
   m_tieManager->setValue(tieProp, tie);
-  ap = addProperty(prop,tieProp);
+  ap = addProperty(prop, tieProp);
   m_tieManager->blockSignals(false);
 
   ATie atie;
   atie.paramProp = prop;
   atie.tieProp = tieProp;
-  m_ties.insert(funProp,atie);
+  m_ties.insert(funProp, atie);
 
   return ap;
 }
@@ -992,14 +967,12 @@ FunctionBrowser::AProperty FunctionBrowser::addTieProperty(QtProperty* prop, QSt
  * Check if a parameter property has a tie
  * @param prop :: A parameter property
  */
-bool FunctionBrowser::hasTie(QtProperty* prop) const
-{
-  if ( !prop ) return false;
+bool FunctionBrowser::hasTie(QtProperty *prop) const {
+  if (!prop)
+    return false;
   auto children = prop->subProperties();
-  foreach(QtProperty* child, children)
-  {
-    if ( child->propertyName() == "Tie" )
-    {
+  foreach (QtProperty *child, children) {
+    if (child->propertyName() == "Tie") {
       return true;
     }
   }
@@ -1010,98 +983,82 @@ bool FunctionBrowser::hasTie(QtProperty* prop) const
  * Check if a property is a tie
  * @param prop :: A property
  */
-bool FunctionBrowser::isTie(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_tieManager) == prop->propertyManager();
+bool FunctionBrowser::isTie(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_tieManager) ==
+             prop->propertyManager();
 }
 
-
 /**
  * Get a tie for a parameter
  * @param prop :: A parameter property
  */
-std::string FunctionBrowser::getTie(QtProperty* prop) const
-{
-  if ( !prop ) return "";
+std::string FunctionBrowser::getTie(QtProperty *prop) const {
+  if (!prop)
+    return "";
   auto children = prop->subProperties();
-  foreach(QtProperty* child, children)
-  {
-    if ( child->propertyName() == "Tie" )
-    {
+  foreach (QtProperty *child, children) {
+    if (child->propertyName() == "Tie") {
       return m_tieManager->value(child).toStdString();
     }
   }
   return "";
 }
 
-/** 
+/**
  * Add a constraint property
  * @param prop :: Parent parameter property
  * @param constraint :: A constraint string
  */
-QList<FunctionBrowser::AProperty> FunctionBrowser::addConstraintProperties(QtProperty* prop, QString constraint)
-{
-  if ( !isParameter(prop) ) return QList<FunctionBrowser::AProperty>();
+QList<FunctionBrowser::AProperty>
+FunctionBrowser::addConstraintProperties(QtProperty *prop, QString constraint) {
+  if (!isParameter(prop))
+    return QList<FunctionBrowser::AProperty>();
   QString lowerBoundStr = "";
   QString upperBoundStr = "";
   Mantid::API::Expression expr;
   expr.parse(constraint.toStdString());
-  if ( expr.name() != "==" ) return QList<FunctionBrowser::AProperty>();
-  if ( expr.size() == 3 )
-  {// lower < param < upper
-    try
-    {
+  if (expr.name() != "==")
+    return QList<FunctionBrowser::AProperty>();
+  if (expr.size() == 3) { // lower < param < upper
+    try {
       // check that the first and third terms are numbers
-      double d1 = boost::lexical_cast<double>( expr[0].name() ); (void)d1;
-      double d2 = boost::lexical_cast<double>( expr[2].name() ); (void)d2;
-      if ( expr[1].operator_name() == "<" && expr[2].operator_name() == "<" )
+      double d1 = boost::lexical_cast<double>(expr[0].name());
+      (void)d1;
+      double d2 = boost::lexical_cast<double>(expr[2].name());
+      (void)d2;
+      if (expr[1].operator_name() == "<" && expr[2].operator_name() == "<") {
+        lowerBoundStr = QString::fromStdString(expr[0].name());
+        upperBoundStr = QString::fromStdString(expr[2].name());
+      } else // assume that the operators are ">"
       {
-        lowerBoundStr = QString::fromStdString( expr[0].name() );
-        upperBoundStr = QString::fromStdString( expr[2].name() );
+        lowerBoundStr = QString::fromStdString(expr[2].name());
+        upperBoundStr = QString::fromStdString(expr[0].name());
       }
-      else // assume that the operators are ">"
-      {
-        lowerBoundStr = QString::fromStdString( expr[2].name() );
-        upperBoundStr = QString::fromStdString( expr[0].name() );
-      }
-    }
-    catch(...)
-    {// error in constraint
+    } catch (...) { // error in constraint
       return QList<FunctionBrowser::AProperty>();
     }
-  }
-  else if ( expr.size() == 2 )
-  {// lower < param or param > lower etc
+  } else if (expr.size() == 2) { // lower < param or param > lower etc
     size_t paramPos = 0;
     try // find position of the parameter name in expression
     {
-      double d = boost::lexical_cast<double>( expr[1].name() );(void)d;
-    }
-    catch(...)
-    {
+      double d = boost::lexical_cast<double>(expr[1].name());
+      (void)d;
+    } catch (...) {
       paramPos = 1;
     }
     std::string op = expr[1].operator_name();
-    if ( paramPos == 0 )
-    {// parameter goes first
-      if ( op == "<" )
-      {// param < number
-        upperBoundStr = QString::fromStdString( expr[1].name() );
+    if (paramPos == 0) { // parameter goes first
+      if (op == "<") {   // param < number
+        upperBoundStr = QString::fromStdString(expr[1].name());
+      } else { // param > number
+        lowerBoundStr = QString::fromStdString(expr[1].name());
       }
-      else
-      {// param > number
-        lowerBoundStr = QString::fromStdString( expr[1].name() );
-      }
-    }
-    else
-    {// parameter is second
-      if ( op == "<" )
-      {// number < param
-        lowerBoundStr = QString::fromStdString( expr[0].name() );
-      }
-      else
-      {// number > param
-        upperBoundStr = QString::fromStdString( expr[0].name() );
+    } else {           // parameter is second
+      if (op == "<") { // number < param
+        lowerBoundStr = QString::fromStdString(expr[0].name());
+      } else { // number > param
+        upperBoundStr = QString::fromStdString(expr[0].name());
       }
     }
   }
@@ -1109,26 +1066,23 @@ QList<FunctionBrowser::AProperty> FunctionBrowser::addConstraintProperties(QtPro
   // add properties
   QList<FunctionBrowser::AProperty> plist;
   AConstraint ac;
-  //ac.constraint = constraint;
+  // ac.constraint = constraint;
   ac.paramProp = prop;
   ac.lower = ac.upper = NULL;
-  if ( !lowerBoundStr.isEmpty() )
-  {
-    auto ap = addProperty( prop, m_constraintManager->addProperty("LowerBound") );
+  if (!lowerBoundStr.isEmpty()) {
+    auto ap = addProperty(prop, m_constraintManager->addProperty("LowerBound"));
     plist << ap;
     ac.lower = ap.prop;
-    m_constraintManager->setValue( ac.lower, lowerBoundStr );
+    m_constraintManager->setValue(ac.lower, lowerBoundStr);
   }
-  if ( !upperBoundStr.isEmpty() )
-  {
-    auto ap = addProperty( prop, m_constraintManager->addProperty("UpperBound") );
+  if (!upperBoundStr.isEmpty()) {
+    auto ap = addProperty(prop, m_constraintManager->addProperty("UpperBound"));
     plist << ap;
     ac.upper = ap.prop;
-    m_constraintManager->setValue( ac.upper, upperBoundStr );
+    m_constraintManager->setValue(ac.upper, upperBoundStr);
   }
-  if ( ac.lower || ac.upper )
-  {
-    m_constraints.insert(m_properties[prop].parent,ac);
+  if (ac.lower || ac.upper) {
+    m_constraints.insert(m_properties[prop].parent, ac);
   }
 
   return plist;
@@ -1138,17 +1092,17 @@ QList<FunctionBrowser::AProperty> FunctionBrowser::addConstraintProperties(QtPro
  * Check if a property is a constraint
  * @param prop :: Property to check.
  */
-bool FunctionBrowser::isConstraint(QtProperty* prop) const
-{
-  return prop && dynamic_cast<QtAbstractPropertyManager*>(m_constraintManager) == prop->propertyManager();
+bool FunctionBrowser::isConstraint(QtProperty *prop) const {
+  return prop &&
+         dynamic_cast<QtAbstractPropertyManager *>(m_constraintManager) ==
+             prop->propertyManager();
 }
 
 /**
  * Check if a parameter property has a constraint
  * @param prop :: A parameter property.
  */
-bool FunctionBrowser::hasConstraint(QtProperty* prop) const
-{
+bool FunctionBrowser::hasConstraint(QtProperty *prop) const {
   return hasLowerBound(prop) || hasUpperBound(prop);
 }
 
@@ -1156,15 +1110,17 @@ bool FunctionBrowser::hasConstraint(QtProperty* prop) const
  * Check if a parameter property has a lower bound
  * @param prop :: A parameter property.
  */
-bool FunctionBrowser::hasLowerBound(QtProperty* prop) const
-{
-  if ( !isParameter(prop) ) return false;
+bool FunctionBrowser::hasLowerBound(QtProperty *prop) const {
+  if (!isParameter(prop))
+    return false;
   auto props = prop->subProperties();
-  if ( props.isEmpty() ) return false;
-  foreach(QtProperty* p, props)
-  {
-    if ( dynamic_cast<QtAbstractPropertyManager*>(m_constraintManager) == p->propertyManager() &&
-      p->propertyName() == "LowerBound" ) return true;
+  if (props.isEmpty())
+    return false;
+  foreach (QtProperty *p, props) {
+    if (dynamic_cast<QtAbstractPropertyManager *>(m_constraintManager) ==
+            p->propertyManager() &&
+        p->propertyName() == "LowerBound")
+      return true;
   }
   return false;
 }
@@ -1173,166 +1129,143 @@ bool FunctionBrowser::hasLowerBound(QtProperty* prop) const
  * Check if a parameter property has a upper bound
  * @param prop :: A parameter property.
  */
-bool FunctionBrowser::hasUpperBound(QtProperty* prop) const
-{
-  if ( !isParameter(prop) ) return false;
+bool FunctionBrowser::hasUpperBound(QtProperty *prop) const {
+  if (!isParameter(prop))
+    return false;
   auto props = prop->subProperties();
-  if ( props.isEmpty() ) return false;
-  foreach(QtProperty* p, props)
-  {
-    if ( dynamic_cast<QtAbstractPropertyManager*>(m_constraintManager) == p->propertyManager() &&
-      p->propertyName() == "UpperBound" ) return true;
+  if (props.isEmpty())
+    return false;
+  foreach (QtProperty *p, props) {
+    if (dynamic_cast<QtAbstractPropertyManager *>(m_constraintManager) ==
+            p->propertyManager() &&
+        p->propertyName() == "UpperBound")
+      return true;
   }
   return false;
 }
 
-
-
 /**
  * Show a pop up menu.
  */
-void FunctionBrowser::popupMenu(const QPoint &)
-{
+void FunctionBrowser::popupMenu(const QPoint &) {
   auto item = m_browser->currentItem();
-  if (!item)
-  {
+  if (!item) {
     QMenu context(this);
     context.addAction(m_actionAddFunction);
-    if ( !QApplication::clipboard()->text().isEmpty() )
-    {
+    if (!QApplication::clipboard()->text().isEmpty()) {
       context.addAction(m_actionFromClipboard);
     }
-    if ( !m_browser->properties().isEmpty() )
-    {
+    if (!m_browser->properties().isEmpty()) {
       context.addAction(m_actionToClipboard);
     }
     context.exec(QCursor::pos());
     return;
   }
-  QtProperty* prop = item->property();
-  if (isFunction(prop))
-  {// functions
+  QtProperty *prop = item->property();
+  if (isFunction(prop)) { // functions
     QMenu context(this);
-    Mantid::API::IFunction_sptr fun = Mantid::API::FunctionFactory::Instance().createFunction(prop->propertyName().toStdString());
+    Mantid::API::IFunction_sptr fun =
+        Mantid::API::FunctionFactory::Instance().createFunction(
+            prop->propertyName().toStdString());
     auto cf = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(fun);
-    if (cf || m_properties[prop].parent == NULL)
-    {
+    if (cf || m_properties[prop].parent == NULL) {
       context.addAction(m_actionAddFunction);
     }
     context.addAction(m_actionRemoveFunction);
-    if ( !QApplication::clipboard()->text().isEmpty() )
-    {
+    if (!QApplication::clipboard()->text().isEmpty()) {
       context.addAction(m_actionFromClipboard);
     }
-    if ( !m_browser->properties().isEmpty() )
-    {
+    if (!m_browser->properties().isEmpty()) {
       context.addAction(m_actionToClipboard);
     }
     context.exec(QCursor::pos());
-  }
-  else if (isParameter(prop))
-  {// parameters
-    //if ( prop->hasOption(globalOptionName) && !prop->checkOption(globalOptionName) ) return;
+  } else if (isParameter(prop)) { // parameters
+    // if ( prop->hasOption(globalOptionName) &&
+    // !prop->checkOption(globalOptionName) ) return;
     QMenu context(this);
-    if ( hasTie(prop) )
-    {
+    if (hasTie(prop)) {
       context.addAction(m_actionRemoveTie);
-    }
-    else
-    {
+    } else {
       context.addAction(m_actionFixParameter);
       context.addAction(m_actionAddTie);
     }
     bool hasLower = hasLowerBound(prop);
     bool hasUpper = hasUpperBound(prop);
-    if ( !hasLower && !hasUpper )
-    {
-      QMenu *constraintMenu = new QMenu("Constraints",this);
+    if (!hasLower && !hasUpper) {
+      QMenu *constraintMenu = new QMenu("Constraints", this);
       constraintMenu->addAction(m_actionConstraints10);
       constraintMenu->addAction(m_actionConstraints50);
       constraintMenu->addAction(m_actionConstraints);
       context.addMenu(constraintMenu);
-    }
-    else
-    {
+    } else {
       context.addAction(m_actionRemoveConstraints);
     }
     context.exec(QCursor::pos());
-  }
-  else if ( isConstraint(prop) )
-  {// constraints
+  } else if (isConstraint(prop)) { // constraints
     QMenu context(this);
     context.addAction(m_actionRemoveConstraint);
     context.exec(QCursor::pos());
   }
 }
 
-/** 
+/**
  * Add a function to currently selected composite function property
  */
-void FunctionBrowser::addFunction()
-{
+void FunctionBrowser::addFunction() {
   QString newFunction;
 
   auto item = m_browser->currentItem();
-  QtProperty* prop = NULL;
-  if ( item )
-  {
+  QtProperty *prop = NULL;
+  if (item) {
     prop = item->property();
-    if (!isFunction(prop)) return;
+    if (!isFunction(prop))
+      return;
   }
 
   // check if the browser is empty
-  if ( !prop )
-  {
+  if (!prop) {
     auto top = m_browser->properties();
-    if ( !top.isEmpty() )
-    {
+    if (!top.isEmpty()) {
       prop = top[0];
-      if (!isFunction(prop)) return;
+      if (!isFunction(prop))
+        return;
     }
   }
 
-  // Get new function type 
+  // Get new function type
   SelectFunctionDialog dlg(this);
-  if (dlg.exec() == QDialog::Accepted)
-  {
+  if (dlg.exec() == QDialog::Accepted) {
     newFunction = dlg.getFunction();
-  }
-  else
-  {
+  } else {
     return;
   }
 
-  if (newFunction.isEmpty()) return;
+  if (newFunction.isEmpty())
+    return;
 
   // create new function
-  auto f = Mantid::API::FunctionFactory::Instance().createFunction(newFunction.toStdString());
-  //newFunction = QString::fromStdString(f->asString());
-
-  if (prop)
-  {// there are other functions defined
-    Mantid::API::IFunction_sptr fun = Mantid::API::FunctionFactory::Instance().createFunction(prop->propertyName().toStdString());
+  auto f = Mantid::API::FunctionFactory::Instance().createFunction(
+      newFunction.toStdString());
+  // newFunction = QString::fromStdString(f->asString());
+
+  if (prop) { // there are other functions defined
+    Mantid::API::IFunction_sptr fun =
+        Mantid::API::FunctionFactory::Instance().createFunction(
+            prop->propertyName().toStdString());
     auto cf = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(fun);
-    if (cf)
-    {
-      addFunction(prop,f);
-    }
-    else
-    {
+    if (cf) {
+      addFunction(prop, f);
+    } else {
       cf.reset(new Mantid::API::CompositeFunction);
       auto f0 = getFunction(prop);
-      if ( f0 )
-      {
+      if (f0) {
         cf->addFunction(f0);
       }
       cf->addFunction(f);
       setFunction(cf);
     }
-  }
-  else
-  {// the browser is empty - add first function
-    addFunction(NULL,f);
+  } else { // the browser is empty - add first function
+    addFunction(NULL, f);
   }
   emit functionStructureChanged();
 }
@@ -1342,133 +1275,110 @@ void FunctionBrowser::addFunction()
  * @param fun :: Function to which attribute is set.
  * @param prop :: A property with the name and value of the attribute.
  */
-void FunctionBrowser::setAttributeToFunction(Mantid::API::IFunction& fun, QtProperty* prop)
-{
-    std::string attName = prop->propertyName().toStdString();
-    SetAttributeFromProperty setter(this,prop);
-    Mantid::API::IFunction::Attribute attr = fun.getAttribute(attName);
-    attr.apply(setter);
-    try
-    {
-      fun.setAttribute(attName,attr);
-    }
-    catch(std::exception& expt)
-    {
-      QMessageBox::critical(this,"MantidPlot - Error", "Cannot set attribute " + QString::fromStdString(attName) + 
-        " of function " + prop->propertyName() + ":\n\n" + QString::fromStdString(expt.what()));
-    }
+void FunctionBrowser::setAttributeToFunction(Mantid::API::IFunction &fun,
+                                             QtProperty *prop) {
+  std::string attName = prop->propertyName().toStdString();
+  SetAttributeFromProperty setter(this, prop);
+  Mantid::API::IFunction::Attribute attr = fun.getAttribute(attName);
+  attr.apply(setter);
+  try {
+    fun.setAttribute(attName, attr);
+  } catch (std::exception &expt) {
+    QMessageBox::critical(this, "MantidPlot - Error",
+                          "Cannot set attribute " +
+                              QString::fromStdString(attName) +
+                              " of function " + prop->propertyName() + ":\n\n" +
+                              QString::fromStdString(expt.what()));
+  }
 }
 
 /**
- * Return the function 
- * @param prop :: Function property 
+ * Return the function
+ * @param prop :: Function property
  * @param attributesOnly :: Only set attributes
  */
-Mantid::API::IFunction_sptr FunctionBrowser::getFunction(QtProperty* prop, bool attributesOnly)
-{
-  if (prop == NULL)
-  {// get overall function
+Mantid::API::IFunction_sptr FunctionBrowser::getFunction(QtProperty *prop,
+                                                         bool attributesOnly) {
+  if (prop == NULL) { // get overall function
     auto props = m_browser->properties();
-    if (props.isEmpty()) return Mantid::API::IFunction_sptr();
+    if (props.isEmpty())
+      return Mantid::API::IFunction_sptr();
     prop = props[0];
   }
-  if (!isFunction(prop)) return Mantid::API::IFunction_sptr();
+  if (!isFunction(prop))
+    return Mantid::API::IFunction_sptr();
 
-  // construct the function 
-  auto fun = Mantid::API::FunctionFactory::Instance().createFunction(prop->propertyName().toStdString());
+  // construct the function
+  auto fun = Mantid::API::FunctionFactory::Instance().createFunction(
+      prop->propertyName().toStdString());
   auto cf = boost::dynamic_pointer_cast<Mantid::API::CompositeFunction>(fun);
-  if (cf)
-  {
+  if (cf) {
     auto children = prop->subProperties();
-    foreach(QtProperty* child, children)
-    {
-      if (isFunction(child))
-      {
+    foreach (QtProperty *child, children) {
+      if (isFunction(child)) {
         auto f = getFunction(child);
         // if f is null ignore that function
-        if ( f )
-        {
+        if (f) {
           cf->addFunction(f);
         }
-      }
-      else if (isAttribute(child))
-      {
+      } else if (isAttribute(child)) {
         setAttributeToFunction(*fun, child);
       }
     }
-  }
-  else
-  {
+  } else {
     // loop over the children properties and set parameters and attributes
     auto children = prop->subProperties();
-    foreach(QtProperty* child, children)
-    {
-      if (isAttribute(child))
-      {
+    foreach (QtProperty *child, children) {
+      if (isAttribute(child)) {
         setAttributeToFunction(*fun, child);
-      }
-      else if (!attributesOnly && isParameter(child))
-      {
-          fun->setParameter(child->propertyName().toStdString(), getParameter(child));
+      } else if (!attributesOnly && isParameter(child)) {
+        fun->setParameter(child->propertyName().toStdString(),
+                          getParameter(child));
       }
     }
-
   }
 
   // if this flag is set the function requires attributes only
   // attempts to set other properties may result in exceptions
-  if ( attributesOnly ) return fun;
+  if (attributesOnly)
+    return fun;
 
   // add ties
   {
     auto from = m_ties.lowerBound(prop);
     auto to = m_ties.upperBound(prop);
-    QList<QtProperty*> filedTies; // ties can become invalid after some editing
-    for(auto it = from; it != to; ++it)
-    {
-      try
-      {
+    QList<QtProperty *> filedTies; // ties can become invalid after some editing
+    for (auto it = from; it != to; ++it) {
+      try {
         QString tie = m_tieManager->value(it.value().tieProp);
         fun->addTies(tie.toStdString());
-      }
-      catch(...)
-      {
+      } catch (...) {
         filedTies << it.value().tieProp;
       }
     }
     // remove failed ties from the browser
-    foreach(QtProperty* p, filedTies)
-    {
-      removeProperty(p);
-    }
+    foreach (QtProperty *p, filedTies) { removeProperty(p); }
   }
 
   // add constraints
   {
     auto from = m_constraints.lowerBound(prop);
     auto to = m_constraints.upperBound(prop);
-    for(auto it = from; it != to; ++it)
-    {
-      try
-      {
+    for (auto it = from; it != to; ++it) {
+      try {
         QString constraint;
         auto cp = it.value();
-        if ( cp.lower )
-        {
-          constraint += m_constraintManager->value(cp.lower) + "<" + cp.paramProp->propertyName();
-        }
-        else
-        {
+        if (cp.lower) {
+          constraint += m_constraintManager->value(cp.lower) + "<" +
+                        cp.paramProp->propertyName();
+        } else {
           constraint += cp.paramProp->propertyName();
         }
-        if ( cp.upper )
-        {
-          constraint += "<" + m_constraintManager->value(cp.upper) ;
+        if (cp.upper) {
+          constraint += "<" + m_constraintManager->value(cp.upper);
         }
         fun->addConstraints(constraint.toStdString());
-      }
-      catch(...)
-      {
+      } catch (...) {
       }
     }
   }
@@ -1481,14 +1391,11 @@ Mantid::API::IFunction_sptr FunctionBrowser::getFunction(QtProperty* prop, bool
  * @param index :: Index of the function, or empty string for top-level function
  * @return Function at index, or null pointer if not found
  */
-Mantid::API::IFunction_sptr FunctionBrowser::getFunctionByIndex(const QString& index)
-{
-  if(auto prop = getFunctionProperty(index))
-  {
+Mantid::API::IFunction_sptr
+FunctionBrowser::getFunctionByIndex(const QString &index) {
+  if (auto prop = getFunctionProperty(index)) {
     return getFunction(prop);
-  }
-  else
-  {
+  } else {
     return Mantid::API::IFunction_sptr();
   }
 }
@@ -1499,10 +1406,10 @@ Mantid::API::IFunction_sptr FunctionBrowser::getFunctionByIndex(const QString& i
  * @param paramName :: Parameter name
  * @param value :: New value
  */
-void FunctionBrowser::setParameter(const QString& funcIndex, const QString& paramName, double value)
-{
+void FunctionBrowser::setParameter(const QString &funcIndex,
+                                   const QString &paramName, double value) {
   auto prop = getParameterProperty(funcIndex, paramName);
-  m_parameterManager->setValue(prop,value);
+  m_parameterManager->setValue(prop, value);
 }
 
 /**
@@ -1511,15 +1418,12 @@ void FunctionBrowser::setParameter(const QString& funcIndex, const QString& para
  * @param paramName :: Parameter name
  * @param error :: New error
  */
-void FunctionBrowser::setParamError(const QString& funcIndex, const QString& paramName, double error)
-{
-  if (auto prop = getFunctionProperty(funcIndex))
-  {
+void FunctionBrowser::setParamError(const QString &funcIndex,
+                                    const QString &paramName, double error) {
+  if (auto prop = getFunctionProperty(funcIndex)) {
     auto children = prop->subProperties();
-    foreach(QtProperty* child, children)
-    {
-      if (isParameter(child) && child->propertyName() == paramName)
-      {
+    foreach (QtProperty *child, children) {
+      if (isParameter(child) && child->propertyName() == paramName) {
         m_parameterManager->setError(child, error);
         break;
       }
@@ -1532,27 +1436,28 @@ void FunctionBrowser::setParamError(const QString& funcIndex, const QString& par
  * @param funcIndex :: Index of the function
  * @param paramName :: Parameter name
  */
-double FunctionBrowser::getParameter(const QString& funcIndex, const QString& paramName) const
-{
+double FunctionBrowser::getParameter(const QString &funcIndex,
+                                     const QString &paramName) const {
   auto prop = getParameterProperty(funcIndex, paramName);
   return m_parameterManager->value(prop);
 }
 
 /**
- * Split a qualified parameter name into function index and local parameter name.
+ * Split a qualified parameter name into function index and local parameter
+ * name.
  * @param paramName :: Fully qualified parameter name (includes function index)
- * @return :: A string list with the first item is the function index and the second
+ * @return :: A string list with the first item is the function index and the
+ * second
  *   item is the param local name.
  */
-QStringList FunctionBrowser::splitParameterName(const QString& paramName) const
-{
+QStringList
+FunctionBrowser::splitParameterName(const QString &paramName) const {
   QString functionIndex;
   QString parameterName = paramName;
   int j = paramName.lastIndexOf('.');
-  if ( j > 0 )
-  {
+  if (j > 0) {
     ++j;
-    functionIndex = paramName.mid(0,j);
+    functionIndex = paramName.mid(0, j);
     parameterName = paramName.mid(j);
   }
   QStringList res;
@@ -1565,10 +1470,9 @@ QStringList FunctionBrowser::splitParameterName(const QString& paramName) const
  * @param paramName :: Fully qualified parameter name (includes function index)
  * @param value :: New value
  */
-void FunctionBrowser::setParameter(const QString& paramName, double value)
-{
+void FunctionBrowser::setParameter(const QString &paramName, double value) {
   QStringList name = splitParameterName(paramName);
-  setParameter(name[0],name[1],value);
+  setParameter(name[0], name[1], value);
 }
 
 /**
@@ -1576,44 +1480,41 @@ void FunctionBrowser::setParameter(const QString& paramName, double value)
  * @param paramName :: Fully qualified parameter name (includes function index)
  * @param error :: New error
  */
-void FunctionBrowser::setParamError(const QString& paramName, double error)
-{
+void FunctionBrowser::setParamError(const QString &paramName, double error) {
   QStringList name = splitParameterName(paramName);
-  setParamError(name[0],name[1],error);
+  setParamError(name[0], name[1], error);
 }
 
 /**
  * Get a value of a parameter
  * @param paramName :: Fully qualified parameter name (includes function index)
  */
-double FunctionBrowser::getParameter(const QString& paramName) const
-{
+double FunctionBrowser::getParameter(const QString &paramName) const {
   QStringList name = splitParameterName(paramName);
-  return getParameter(name[0],name[1]);
+  return getParameter(name[0], name[1]);
 }
 
 /// Get a property for a parameter
-QtProperty* FunctionBrowser::getParameterProperty(const QString& paramName) const
-{
+QtProperty *
+FunctionBrowser::getParameterProperty(const QString &paramName) const {
   QStringList name = splitParameterName(paramName);
-  return getParameterProperty(name[0],name[1]);
+  return getParameterProperty(name[0], name[1]);
 }
 
 /// Get a property for a parameter
-QtProperty* FunctionBrowser::getParameterProperty(const QString& funcIndex, const QString& paramName) const
-{
-  if (auto prop = getFunctionProperty(funcIndex))
-  {
+QtProperty *
+FunctionBrowser::getParameterProperty(const QString &funcIndex,
+                                      const QString &paramName) const {
+  if (auto prop = getFunctionProperty(funcIndex)) {
     auto children = prop->subProperties();
-    foreach(QtProperty* child, children)
-    {
-      if (isParameter(child) && child->propertyName() == paramName)
-      {
+    foreach (QtProperty *child, children) {
+      if (isParameter(child) && child->propertyName() == paramName) {
         return child;
       }
     }
   }
-  throw std::runtime_error("Unknown function parameter " + (funcIndex + paramName).toStdString());
+  throw std::runtime_error("Unknown function parameter " +
+                           (funcIndex + paramName).toStdString());
 }
 
 /**
@@ -1621,35 +1522,33 @@ QtProperty* FunctionBrowser::getParameterProperty(const QString& funcIndex, cons
  * @param fun :: A function to copy the values from. It must have the same
  *   type (composition) as the function in the browser.
  */
-void FunctionBrowser::updateParameters(const Mantid::API::IFunction& fun)
-{
+void FunctionBrowser::updateParameters(const Mantid::API::IFunction &fun) {
   auto paramNames = fun.getParameterNames();
-  for(auto par = paramNames.begin(); par != paramNames.end(); ++par)
-  {
-    setParameter( QString::fromStdString(*par), fun.getParameter(*par) );
+  for (auto par = paramNames.begin(); par != paramNames.end(); ++par) {
+    setParameter(QString::fromStdString(*par), fun.getParameter(*par));
   }
 }
 
-
 /**
  * Return FunctionFactory function string
  */
-QString FunctionBrowser::getFunctionString()
-{
+QString FunctionBrowser::getFunctionString() {
   auto fun = getFunction();
-  if ( !fun ) return "";
-  return QString::fromStdString( fun->asString() );
+  if (!fun)
+    return "";
+  return QString::fromStdString(fun->asString());
 }
 
 /**
  * Remove the function under currently selected property
  */
-void FunctionBrowser::removeFunction()
-{
+void FunctionBrowser::removeFunction() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isFunction(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isFunction(prop))
+    return;
   removeProperty(prop);
   updateFunctionIndices();
 
@@ -1691,18 +1590,18 @@ void FunctionBrowser::removeFunction()
 /**
  * Fix currently selected parameter
  */
-void FunctionBrowser::fixParameter()
-{
+void FunctionBrowser::fixParameter() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
-  if (prop->hasOption(globalOptionName) && !prop->checkOption(globalOptionName))
-  {
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
+  if (prop->hasOption(globalOptionName) &&
+      !prop->checkOption(globalOptionName)) {
     auto parName = getParameterName(prop);
     auto &localValues = m_localParameterValues[parName];
-    if (m_currentDataset >= localValues.size())
-    {
+    if (m_currentDataset >= localValues.size()) {
       initLocalParameter(parName);
     }
     localValues[m_currentDataset].fixed = true;
@@ -1710,22 +1609,18 @@ void FunctionBrowser::fixParameter()
   QString tie = QString::number(getParameter(prop));
   m_tieManager->blockSignals(true);
   auto ap = addTieProperty(prop, tie);
-  if (ap.prop)
-  {
+  if (ap.prop) {
     ap.prop->setEnabled(false);
   }
   m_tieManager->blockSignals(false);
 }
 
 /// Get a tie property attached to a parameter property
-QtProperty* FunctionBrowser::getTieProperty(QtProperty* prop) const
-{
+QtProperty *FunctionBrowser::getTieProperty(QtProperty *prop) const {
   auto children = prop->subProperties();
-  foreach(QtProperty* child, children)
-  {
-    if ( child->propertyName() == "Tie" )
-    {
-      return child; 
+  foreach (QtProperty *child, children) {
+    if (child->propertyName() == "Tie") {
+      return child;
     }
   }
   return NULL;
@@ -1734,23 +1629,22 @@ QtProperty* FunctionBrowser::getTieProperty(QtProperty* prop) const
 /**
  * Unfix currently selected parameter
  */
-void FunctionBrowser::removeTie()
-{
+void FunctionBrowser::removeTie() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
   auto tieProp = getTieProperty(prop);
-  if ( tieProp )
-  {
+  if (tieProp) {
     removeProperty(tieProp);
   }
-  if (prop->hasOption(globalOptionName) && !prop->checkOption(globalOptionName))
-  {
+  if (prop->hasOption(globalOptionName) &&
+      !prop->checkOption(globalOptionName)) {
     auto parName = getParameterName(prop);
     auto &localValues = m_localParameterValues[parName];
-    if (m_currentDataset < localValues.size())
-    {
+    if (m_currentDataset < localValues.size()) {
       localValues[m_currentDataset].tie = "";
       localValues[m_currentDataset].fixed = false;
     }
@@ -1763,11 +1657,9 @@ void FunctionBrowser::removeTie()
  * Ties on global parameters are left as they are.
  */
 void FunctionBrowser::removeAllLocalTieProperties() {
-  QList<QtProperty*> tieProperties;
-  for (auto p : m_properties)
-  {
-    if (p.prop->propertyManager() == m_tieManager)
-    {
+  QList<QtProperty *> tieProperties;
+  for (auto p : m_properties) {
+    if (p.prop->propertyManager() == m_tieManager) {
       tieProperties << p.prop;
     }
   }
@@ -1782,24 +1674,24 @@ void FunctionBrowser::removeAllLocalTieProperties() {
 /**
  * Add a custom tie to currently selected parameter
  */
-void FunctionBrowser::addTie()
-{
+void FunctionBrowser::addTie() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
 
   bool ok;
-  QString tie = QInputDialog::getText(this, "Add a tie", "Tie:", QLineEdit::Normal, "", &ok);
-  if ( ok && !tie.isEmpty() )
-  {
+  QString tie = QInputDialog::getText(this, "Add a tie", "Tie:",
+                                      QLineEdit::Normal, "", &ok);
+  if (ok && !tie.isEmpty()) {
     addTieProperty(prop, tie);
-    if (prop->hasOption(globalOptionName) && !prop->checkOption(globalOptionName))
-    {
+    if (prop->hasOption(globalOptionName) &&
+        !prop->checkOption(globalOptionName)) {
       auto parName = getParameterName(prop);
       auto &localValues = m_localParameterValues[parName];
-      if (m_currentDataset >= localValues.size())
-      {
+      if (m_currentDataset >= localValues.size()) {
         initLocalParameter(parName);
       }
       localValues[m_currentDataset].tie = tie;
@@ -1810,89 +1702,93 @@ void FunctionBrowser::addTie()
 /**
  * Copy function from the clipboard
  */
-void FunctionBrowser::copyFromClipboard()
-{
+void FunctionBrowser::copyFromClipboard() {
   QString funStr = QApplication::clipboard()->text();
-  if ( funStr.isEmpty() ) return;
-  try
-  {
-    auto fun = Mantid::API::FunctionFactory::Instance().createInitialized( funStr.toStdString() );
-    if ( !fun ) return;
+  if (funStr.isEmpty())
+    return;
+  try {
+    auto fun = Mantid::API::FunctionFactory::Instance().createInitialized(
+        funStr.toStdString());
+    if (!fun)
+      return;
     this->setFunction(fun);
-  }
-  catch(...)
-  {
+  } catch (...) {
     // text in the clipboard isn't a function definition
-    QMessageBox::warning(this,"MantidPlot - Warning", "Text in the clipboard isn't a function definition"
-      " or contains errors.");
+    QMessageBox::warning(this, "MantidPlot - Warning",
+                         "Text in the clipboard isn't a function definition"
+                         " or contains errors.");
   }
 }
 
 /**
  * Copy function to the clipboard
  */
-void FunctionBrowser::copyToClipboard()
-{
+void FunctionBrowser::copyToClipboard() {
   auto fun = getFunction();
-  if ( fun ) 
-  {
-    QApplication::clipboard()->setText( QString::fromStdString(fun->asString()) );
+  if (fun) {
+    QApplication::clipboard()->setText(QString::fromStdString(fun->asString()));
   }
 }
 
 /**
  * Add both constraints to current parameter
  */
-void FunctionBrowser::addConstraints()
-{
+void FunctionBrowser::addConstraints() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
-  addConstraintProperties(prop,"0<"+prop->propertyName()+"<0");
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
+  addConstraintProperties(prop, "0<" + prop->propertyName() + "<0");
 }
 
 /**
  * Add both constraints to current parameter
  */
-void FunctionBrowser::addConstraints10()
-{
+void FunctionBrowser::addConstraints10() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
   double val = getParameter(prop);
-  addConstraintProperties(prop,QString::number(val*0.9)+"<"+prop->propertyName()+"<"+QString::number(val*1.1));
+  addConstraintProperties(prop, QString::number(val * 0.9) + "<" +
+                                    prop->propertyName() + "<" +
+                                    QString::number(val * 1.1));
 }
 
 /**
  * Add both constraints to current parameter
  */
-void FunctionBrowser::addConstraints50()
-{
+void FunctionBrowser::addConstraints50() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
   double val = getParameter(prop);
-  addConstraintProperties(prop,QString::number(val*0.5)+"<"+prop->propertyName()+"<"+QString::number(val*1.5));
+  addConstraintProperties(prop, QString::number(val * 0.5) + "<" +
+                                    prop->propertyName() + "<" +
+                                    QString::number(val * 1.5));
 }
 
 /**
  * Remove both constraints from current parameter
  */
-void FunctionBrowser::removeConstraints()
-{
+void FunctionBrowser::removeConstraints() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isParameter(prop)) return;
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isParameter(prop))
+    return;
   auto props = prop->subProperties();
-  foreach(QtProperty* p, props)
-  {
-    if ( isConstraint(p) )
-    {
-      removeProperty( p );
+  foreach (QtProperty *p, props) {
+    if (isConstraint(p)) {
+      removeProperty(p);
     }
   }
 }
@@ -1900,42 +1796,41 @@ void FunctionBrowser::removeConstraints()
 /**
  * Remove one constraint from current parameter
  */
-void FunctionBrowser::removeConstraint()
-{
+void FunctionBrowser::removeConstraint() {
   auto item = m_browser->currentItem();
-  if ( !item ) return;
-  QtProperty* prop = item->property();
-  if (!isConstraint(prop)) return;
-  removeProperty( prop );
+  if (!item)
+    return;
+  QtProperty *prop = item->property();
+  if (!isConstraint(prop))
+    return;
+  removeProperty(prop);
 }
 
-void FunctionBrowser::updateCurrentFunctionIndex()
-{
+void FunctionBrowser::updateCurrentFunctionIndex() {
   boost::optional<QString> newIndex;
 
-  if (auto item = m_browser->currentItem())
-  {
+  if (auto item = m_browser->currentItem()) {
     auto prop = item->property();
     newIndex = getIndex(prop);
   }
 
-  if (m_currentFunctionIndex != newIndex)
-  {
+  if (m_currentFunctionIndex != newIndex) {
     m_currentFunctionIndex = newIndex;
     emit currentFunctionChanged();
   }
 }
 
 /**
- * Slot connected to all function attribute managers. Update the corresponding function.
+ * Slot connected to all function attribute managers. Update the corresponding
+ * function.
  * @param prop :: An attribute property that was changed
  */
-void FunctionBrowser::attributeChanged(QtProperty* prop)
-{
+void FunctionBrowser::attributeChanged(QtProperty *prop) {
   auto funProp = m_properties[prop].parent;
-  if ( !funProp ) return;
+  if (!funProp)
+    return;
   // get function with the changed attribute (it is set from prop's value)
-  auto fun = getFunction( funProp, true );
+  auto fun = getFunction(funProp, true);
 
   // delete and recreate all function's properties (attributes, parameters, etc)
   setFunction(funProp, fun);
@@ -1944,86 +1839,80 @@ void FunctionBrowser::attributeChanged(QtProperty* prop)
 }
 
 /**
- * Slot connected to a property displaying the value of a member of a vector attribute.
+ * Slot connected to a property displaying the value of a member of a vector
+ * attribute.
  * @param prop :: A property that was changed.
  */
-void FunctionBrowser::attributeVectorDoubleChanged(QtProperty *prop)
-{
-    QtProperty *vectorProp = m_properties[prop].parent;
-    if ( !vectorProp ) throw std::runtime_error("FunctionBrowser: inconsistency in vector properties.");
-    attributeChanged( vectorProp );
+void FunctionBrowser::attributeVectorDoubleChanged(QtProperty *prop) {
+  QtProperty *vectorProp = m_properties[prop].parent;
+  if (!vectorProp)
+    throw std::runtime_error(
+        "FunctionBrowser: inconsistency in vector properties.");
+  attributeChanged(vectorProp);
 }
 
-void FunctionBrowser::parameterChanged(QtProperty* prop)
-{
-  if (m_currentDataset < getNumberOfDatasets() && !prop->checkOption(globalOptionName))
-  {
-    setLocalParameterValue(getParameterName(prop), m_currentDataset, m_parameterManager->value(prop));
+void FunctionBrowser::parameterChanged(QtProperty *prop) {
+  if (m_currentDataset < getNumberOfDatasets() &&
+      !prop->checkOption(globalOptionName)) {
+    setLocalParameterValue(getParameterName(prop), m_currentDataset,
+                           m_parameterManager->value(prop));
   }
   auto tieProp = getTieProperty(prop);
-  if (tieProp && !tieProp->isEnabled())
-  {
+  if (tieProp && !tieProp->isEnabled()) {
     // it is a fixed tie
-    auto newTie = QString("%1=%2").arg(prop->propertyName()).arg(m_parameterManager->value(prop));
+    auto newTie = QString("%1=%2")
+                      .arg(prop->propertyName())
+                      .arg(m_parameterManager->value(prop));
     m_tieManager->setValue(tieProp, newTie);
   }
   emit parameterChanged(getIndex(prop), prop->propertyName());
 }
 
 /// Called when a tie property changes
-void FunctionBrowser::tieChanged(QtProperty* prop)
-{
-  if (m_currentDataset < getNumberOfDatasets() && !prop->checkOption(globalOptionName))
-  {
-    QtProperty* parProp = nullptr;
-    for (auto it = m_ties.begin(); it != m_ties.end(); ++it)
-    {
-      if (it.value().tieProp == prop)
-      {
+void FunctionBrowser::tieChanged(QtProperty *prop) {
+  if (m_currentDataset < getNumberOfDatasets() &&
+      !prop->checkOption(globalOptionName)) {
+    QtProperty *parProp = nullptr;
+    for (auto it = m_ties.begin(); it != m_ties.end(); ++it) {
+      if (it.value().tieProp == prop) {
         parProp = it.value().paramProp;
         break;
       }
     }
-    if (!parProp) return;
+    if (!parProp)
+      return;
 
     auto parName = getParameterName(parProp);
     checkLocalParameter(parName);
     auto &paramValue = m_localParameterValues[parName][m_currentDataset];
-    if (paramValue.fixed) return;
+    if (paramValue.fixed)
+      return;
     auto tie = QString::fromStdString(getTie(parProp));
     auto tieExpr = tie.split('=');
-    if (tieExpr.size() == 2)
-    {
+    if (tieExpr.size() == 2) {
       tie = tieExpr[1];
     }
     paramValue.tie = tie;
   }
 }
 
-
-void FunctionBrowser::parameterButtonClicked(QtProperty *prop)
-{
+void FunctionBrowser::parameterButtonClicked(QtProperty *prop) {
   emit localParameterButtonClicked(getIndex(prop) + prop->propertyName());
 }
 
-bool FunctionBrowser::hasFunction() const
-{
-  return ! m_functionManager->properties().isEmpty();
+bool FunctionBrowser::hasFunction() const {
+  return !m_functionManager->properties().isEmpty();
 }
 
 /// Get the number of datasets
-int FunctionBrowser::getNumberOfDatasets() const
-{
-  return m_numberOfDatasets;
-}
+int FunctionBrowser::getNumberOfDatasets() const { return m_numberOfDatasets; }
 
 /// Set new number of the datasets
 /// @param n :: New value for the number of datasets.
-void FunctionBrowser::setNumberOfDatasets(int n)
-{
-  if ( !m_multiDataset )
-  {
-    throw std::runtime_error("Function browser wasn't set up for multi-dataset fitting.");
+void FunctionBrowser::setNumberOfDatasets(int n) {
+  if (!m_multiDataset) {
+    throw std::runtime_error(
+        "Function browser wasn't set up for multi-dataset fitting.");
   }
   m_numberOfDatasets = n;
 }
@@ -2033,19 +1922,18 @@ void FunctionBrowser::setNumberOfDatasets(int n)
  * @param parName :: Name of a parameter.
  * @param i :: Data set index.
  */
-double FunctionBrowser::getLocalParameterValue(const QString& parName, int i) const
-{
+double FunctionBrowser::getLocalParameterValue(const QString &parName,
+                                               int i) const {
   checkLocalParameter(parName);
   return m_localParameterValues[parName][i].value;
 }
 
-void FunctionBrowser::setLocalParameterValue(const QString& parName, int i, double value)
-{
+void FunctionBrowser::setLocalParameterValue(const QString &parName, int i,
+                                             double value) {
   checkLocalParameter(parName);
   m_localParameterValues[parName][i].value = value;
-  if ( i == m_currentDataset )
-  {
-    setParameter( parName, value );
+  if (i == m_currentDataset) {
+    setParameter(parName, value);
   }
 }
 
@@ -2053,147 +1941,127 @@ void FunctionBrowser::setLocalParameterValue(const QString& parName, int i, doub
  * Init a local parameter. Define initial values for all datasets.
  * @param parName :: Name of parametere to init.
  */
-void FunctionBrowser::initLocalParameter(const QString& parName)const
-{
+void FunctionBrowser::initLocalParameter(const QString &parName) const {
   double value = getParameter(parName);
-  QVector<LocalParameterData> values( getNumberOfDatasets(), LocalParameterData(value) );
+  QVector<LocalParameterData> values(getNumberOfDatasets(),
+                                     LocalParameterData(value));
   m_localParameterValues[parName] = values;
 }
 
 /// Make sure that the parameter is initialized
 /// @param parName :: Name of a parameter to check
-void FunctionBrowser::checkLocalParameter(const QString& parName)const
-{
-  if ( !m_localParameterValues.contains(parName) || m_localParameterValues[parName].size() != getNumberOfDatasets() )
-  {
+void FunctionBrowser::checkLocalParameter(const QString &parName) const {
+  if (!m_localParameterValues.contains(parName) ||
+      m_localParameterValues[parName].size() != getNumberOfDatasets()) {
     initLocalParameter(parName);
   }
 }
 
-void FunctionBrowser::resetLocalParameters()
-{
-  m_localParameterValues.clear();
-}
+void FunctionBrowser::resetLocalParameters() { m_localParameterValues.clear(); }
 
 /// Set current dataset.
-void FunctionBrowser::setCurrentDataset(int i)
-{
+void FunctionBrowser::setCurrentDataset(int i) {
   m_currentDataset = i;
-  if ( m_currentDataset >= m_numberOfDatasets )
-  {
+  if (m_currentDataset >= m_numberOfDatasets) {
     throw std::runtime_error("Dataset index is outside the range");
   }
   removeAllLocalTieProperties();
   auto localParameters = getLocalParameters();
-  foreach(QString par, localParameters)
-  {
-    setParameter( par, getLocalParameterValue( par, m_currentDataset ) );
+  foreach (QString par, localParameters) {
+    setParameter(par, getLocalParameterValue(par, m_currentDataset));
     updateLocalTie(par);
   }
 }
 
 /// Remove local parameter values for a number of datasets.
 /// @param indices :: A list of indices of datasets to remove.
-void FunctionBrowser::removeDatasets(QList<int> indices)
-{
-  if (indices.size() > m_numberOfDatasets)
-  {
-    throw std::runtime_error("FunctionBrowser asked to removed too many datasets");
+void FunctionBrowser::removeDatasets(QList<int> indices) {
+  if (indices.size() > m_numberOfDatasets) {
+    throw std::runtime_error(
+        "FunctionBrowser asked to removed too many datasets");
   }
   qSort(indices);
-  for(auto par = m_localParameterValues.begin(); par != m_localParameterValues.end(); ++par)
-  {
-    for(int i = indices.size() - 1; i >= 0; --i)
-    {
+  for (auto par = m_localParameterValues.begin();
+       par != m_localParameterValues.end(); ++par) {
+    for (int i = indices.size() - 1; i >= 0; --i) {
       int index = indices[i];
-      if (index < 0)
-      {
-        throw std::runtime_error("Index of a dataset in FunctionBrowser cannot be negative.");
+      if (index < 0) {
+        throw std::runtime_error(
+            "Index of a dataset in FunctionBrowser cannot be negative.");
       }
-      if ( index < m_numberOfDatasets )
-      {
+      if (index < m_numberOfDatasets) {
         par.value().remove(index);
-      }
-      else
-      {
-        throw std::runtime_error("Index of a dataset in FunctionBrowser is out of range.");
+      } else {
+        throw std::runtime_error(
+            "Index of a dataset in FunctionBrowser is out of range.");
       }
     }
   }
-  setNumberOfDatasets( m_numberOfDatasets - indices.size() );
+  setNumberOfDatasets(m_numberOfDatasets - indices.size());
 }
 
 /// Add local parameters for additional datasets.
 /// @param n :: Number of datasets added.
-void FunctionBrowser::addDatasets(int n)
-{
-  if ( m_numberOfDatasets == 0 )
-  {
-    setNumberOfDatasets( n );
+void FunctionBrowser::addDatasets(int n) {
+  if (m_numberOfDatasets == 0) {
+    setNumberOfDatasets(n);
     return;
   }
-  for(auto par = m_localParameterValues.begin(); par != m_localParameterValues.end(); ++par)
-  {
+  for (auto par = m_localParameterValues.begin();
+       par != m_localParameterValues.end(); ++par) {
     auto &values = par.value();
     double value = values.back().value;
-    values.insert(values.end(),n,LocalParameterData(value));
+    values.insert(values.end(), n, LocalParameterData(value));
   }
   setNumberOfDatasets(m_numberOfDatasets + n);
 }
 
 /// Return the multidomain function for multi-dataset fitting
-Mantid::API::IFunction_sptr FunctionBrowser::getGlobalFunction()
-{
-  if ( !m_multiDataset )
-  {
-    throw std::runtime_error("Function browser wasn't set up for multi-dataset fitting.");
+Mantid::API::IFunction_sptr FunctionBrowser::getGlobalFunction() {
+  if (!m_multiDataset) {
+    throw std::runtime_error(
+        "Function browser wasn't set up for multi-dataset fitting.");
   }
   // number of spectra to fit == size of the multi-domain function
   int nOfDataSets = getNumberOfDatasets();
-  if ( nOfDataSets == 0 )
-  {
+  if (nOfDataSets == 0) {
     throw std::runtime_error("There are no data sets specified.");
   }
 
   // description of a single function
   QString funStr = getFunctionString();
 
-  if ( nOfDataSets == 1 )
-  {
-    return Mantid::API::FunctionFactory::Instance().createInitialized( funStr.toStdString() );
+  if (nOfDataSets == 1) {
+    return Mantid::API::FunctionFactory::Instance().createInitialized(
+        funStr.toStdString());
   }
 
-  bool isComposite = (std::find(funStr.begin(),funStr.end(),';') != funStr.end());
-  if ( isComposite )
-  {
+  bool isComposite =
+      (std::find(funStr.begin(), funStr.end(), ';') != funStr.end());
+  if (isComposite) {
     funStr = ";(" + funStr + ")";
-  }
-  else
-  {
+  } else {
     funStr = ";" + funStr;
   }
 
   QString multiFunStr = "composite=MultiDomainFunction,NumDeriv=1";
-  for(int i = 0; i < nOfDataSets; ++i)
-  {
+  for (int i = 0; i < nOfDataSets; ++i) {
     multiFunStr += funStr;
   }
 
   // add the global ties
   QStringList globals = getGlobalParameters();
   QString globalTies;
-  if ( !globals.isEmpty() )
-  {
+  if (!globals.isEmpty()) {
     globalTies = "ties=(";
     bool isFirst = true;
-    foreach(QString par, globals)
-    {
-      if ( !isFirst ) globalTies += ",";
+    foreach (QString par, globals) {
+      if (!isFirst)
+        globalTies += ",";
       else
         isFirst = false;
 
-      for(int i = 1; i < nOfDataSets; ++i)
-      {
+      for (int i = 1; i < nOfDataSets; ++i) {
         globalTies += QString("f%1.").arg(i) + par + "=";
       }
       globalTies += QString("f0.%1").arg(par);
@@ -2203,93 +2071,84 @@ Mantid::API::IFunction_sptr FunctionBrowser::getGlobalFunction()
   }
 
   // create the multi-domain function
-  auto fun = Mantid::API::FunctionFactory::Instance().createInitialized( multiFunStr.toStdString() );
-  boost::shared_ptr<Mantid::API::MultiDomainFunction> multiFun = boost::dynamic_pointer_cast<Mantid::API::MultiDomainFunction>( fun );
-  if ( !multiFun )
-  {
+  auto fun = Mantid::API::FunctionFactory::Instance().createInitialized(
+      multiFunStr.toStdString());
+  boost::shared_ptr<Mantid::API::MultiDomainFunction> multiFun =
+      boost::dynamic_pointer_cast<Mantid::API::MultiDomainFunction>(fun);
+  if (!multiFun) {
     throw std::runtime_error("Failed to create the MultiDomainFunction");
   }
-  
+
   auto globalParams = getGlobalParameters();
 
   // set the domain indices, initial local parameter values and ties
-  for(int i = 0; i < nOfDataSets; ++i)
-  {
-    multiFun->setDomainIndex(i,i);
+  for (int i = 0; i < nOfDataSets; ++i) {
+    multiFun->setDomainIndex(i, i);
     auto fun1 = multiFun->getFunction(i);
-    for(size_t j = 0; j < fun1->nParams(); ++j)
-    {
+    for (size_t j = 0; j < fun1->nParams(); ++j) {
       QString parName = QString::fromStdString(fun1->parameterName(j));
-      if ( globalParams.contains(parName) ) continue;
+      if (globalParams.contains(parName))
+        continue;
       auto tie = fun1->getTie(j);
-      if ( tie )
-      {
-        // If parameter has a tie at this stage then it gets it form the currently
-        // displayed function. But the i-th local parameters may not have this tie,
+      if (tie) {
+        // If parameter has a tie at this stage then it gets it form the
+        // currently
+        // displayed function. But the i-th local parameters may not have this
+        // tie,
         // so remove it
         fun1->removeTie(j);
       }
-      if ( isLocalParameterFixed(parName,i) )
-      {
+      if (isLocalParameterFixed(parName, i)) {
         // Fix this particular local parameter
-        fun1->tie(parName.toStdString(),boost::lexical_cast<std::string>( getLocalParameterValue(parName,i) ));
-      }
-      else
-      {
+        fun1->tie(parName.toStdString(),
+                  boost::lexical_cast<std::string>(
+                      getLocalParameterValue(parName, i)));
+      } else {
         auto tie = getLocalParameterTie(parName, i);
-        if ( !tie.isEmpty() )
-        {
+        if (!tie.isEmpty()) {
           fun1->tie(parName.toStdString(), tie.toStdString());
-        }
-        else
-        {
-          fun1->setParameter(j, getLocalParameterValue(parName,i));
+        } else {
+          fun1->setParameter(j, getLocalParameterValue(parName, i));
         }
       }
     }
   }
-  assert( multiFun->nFunctions() == static_cast<size_t>(nOfDataSets) );
+  assert(multiFun->nFunctions() == static_cast<size_t>(nOfDataSets));
 
   return fun;
 }
 
 /// Make sure that properties are in sync with the cached ties
 /// @param parName :: A parameter to check.
-void FunctionBrowser::updateLocalTie(const QString& parName)
-{
-    auto prop = getParameterProperty(parName);
-    if ( hasTie(prop) )
-    {
-      auto tieProp = getTieProperty(prop);
-      removeProperty(tieProp);
-    }
-    auto &localParam = m_localParameterValues[parName][m_currentDataset];
-    if ( localParam.fixed )
-    {
-      auto ap = addTieProperty(prop, QString::number(m_localParameterValues[parName][m_currentDataset].value));
-      if (ap.prop)
-      {
-        ap.prop->setEnabled(false);
-      }
-    }
-    else if (!localParam.tie.isEmpty())
-    {
-      auto ap = addTieProperty(prop, localParam.tie);
-      (void)ap;
+void FunctionBrowser::updateLocalTie(const QString &parName) {
+  auto prop = getParameterProperty(parName);
+  if (hasTie(prop)) {
+    auto tieProp = getTieProperty(prop);
+    removeProperty(tieProp);
+  }
+  auto &localParam = m_localParameterValues[parName][m_currentDataset];
+  if (localParam.fixed) {
+    auto ap = addTieProperty(
+        prop, QString::number(
+                  m_localParameterValues[parName][m_currentDataset].value));
+    if (ap.prop) {
+      ap.prop->setEnabled(false);
     }
+  } else if (!localParam.tie.isEmpty()) {
+    auto ap = addTieProperty(prop, localParam.tie);
+    (void)ap;
+  }
 }
 
-
 /// Fix/unfix a local parameter
 /// @param parName :: Parameter name
 /// @param i :: Index of a dataset.
 /// @param fixed :: Make it fixed (true) or free (false)
-void FunctionBrowser::setLocalParameterFixed(const QString& parName, int i, bool fixed)
-{
+void FunctionBrowser::setLocalParameterFixed(const QString &parName, int i,
+                                             bool fixed) {
   checkLocalParameter(parName);
   m_localParameterValues[parName][i].fixed = fixed;
-  if ( i == m_currentDataset )
-  {
+  if (i == m_currentDataset) {
     updateLocalTie(parName);
   }
 }
@@ -2297,18 +2156,17 @@ void FunctionBrowser::setLocalParameterFixed(const QString& parName, int i, bool
 /// Check if a local parameter is fixed
 /// @param parName :: Parameter name
 /// @param i :: Index of a dataset.
-bool FunctionBrowser::isLocalParameterFixed(const QString& parName, int i) const
-{
+bool FunctionBrowser::isLocalParameterFixed(const QString &parName,
+                                            int i) const {
   checkLocalParameter(parName);
   return m_localParameterValues[parName][i].fixed;
 }
 
-
 /// Get the tie for a local parameter.
 /// @param parName :: Parameter name
 /// @param i :: Index of a dataset.
-QString FunctionBrowser::getLocalParameterTie(const QString& parName, int i) const
-{
+QString FunctionBrowser::getLocalParameterTie(const QString &parName,
+                                              int i) const {
   checkLocalParameter(parName);
   return m_localParameterValues[parName][i].tie;
 }
@@ -2317,47 +2175,39 @@ QString FunctionBrowser::getLocalParameterTie(const QString& parName, int i) con
 /// @param parName :: Parameter name
 /// @param i :: Index of a dataset.
 /// @param tie :: A tie string.
-void FunctionBrowser::setLocalParameterTie(const QString& parName, int i, QString tie)
-{
+void FunctionBrowser::setLocalParameterTie(const QString &parName, int i,
+                                           QString tie) {
   checkLocalParameter(parName);
   m_localParameterValues[parName][i].tie = tie;
-  if ( i == m_currentDataset )
-  {
+  if (i == m_currentDataset) {
     updateLocalTie(parName);
   }
 }
 
-
 /// Update the interface to have the same parameter values as in a function.
 /// @param fun :: A function to get parameter values from.
-void FunctionBrowser::updateMultiDatasetParameters(const Mantid::API::IFunction& fun)
-{
-  auto cfun = dynamic_cast<const Mantid::API::CompositeFunction*>( &fun );
-  if ( cfun && cfun->nFunctions() > 0 )
-  {
+void FunctionBrowser::updateMultiDatasetParameters(
+    const Mantid::API::IFunction &fun) {
+  auto cfun = dynamic_cast<const Mantid::API::CompositeFunction *>(&fun);
+  if (cfun && cfun->nFunctions() > 0) {
     auto qLocalParameters = getLocalParameters();
     std::vector<std::string> localParameters;
-    foreach(QString par, qLocalParameters)
-    {
-      localParameters.push_back( par.toStdString() );
+    foreach (QString par, qLocalParameters) {
+      localParameters.push_back(par.toStdString());
     }
-    size_t currentIndex = static_cast<size_t>( m_currentDataset );
-    for(size_t i = 0; i < cfun->nFunctions(); ++i)
-    {
+    size_t currentIndex = static_cast<size_t>(m_currentDataset);
+    for (size_t i = 0; i < cfun->nFunctions(); ++i) {
       auto sfun = cfun->getFunction(i);
-      if ( i == currentIndex )
-      {
-        updateParameters( *sfun );
+      if (i == currentIndex) {
+        updateParameters(*sfun);
       }
-      for(int j = 0; j < qLocalParameters.size(); ++j)
-      {
-        setLocalParameterValue( qLocalParameters[j], static_cast<int>(i), sfun->getParameter(localParameters[j]) );
+      for (int j = 0; j < qLocalParameters.size(); ++j) {
+        setLocalParameterValue(qLocalParameters[j], static_cast<int>(i),
+                               sfun->getParameter(localParameters[j]));
       }
     }
-  }
-  else
-  {
-    updateParameters( fun );
+  } else {
+    updateParameters(fun);
   }
 }
 
@@ -2365,16 +2215,14 @@ void FunctionBrowser::updateMultiDatasetParameters(const Mantid::API::IFunction&
 /// @param s0 :: New size for the first column (Parameter).
 /// @param s1 :: New size for the second column (Value).
 /// @param s2 :: New size for the third optional column (Global).
-void FunctionBrowser::setColumnSizes(int s0, int s1, int s2)
-{
+void FunctionBrowser::setColumnSizes(int s0, int s1, int s2) {
   m_browser->setColumnSizes(s0, s1, s2);
 }
 
 /**
  * Emit a signal when any of the Global options change.
  */
-void FunctionBrowser::globalChanged(QtProperty*, const QString&, bool)
-{
+void FunctionBrowser::globalChanged(QtProperty *, const QString &, bool) {
   emit globalsChanged();
 }
 
diff --git a/MantidQt/MantidWidgets/src/HintingLineEdit.cpp b/MantidQt/MantidWidgets/src/HintingLineEdit.cpp
index d31a5b218196de7e622602f58b4f75958aec2cce..930550f3cc21f9dd644457ae678e014779f675c5 100644
--- a/MantidQt/MantidWidgets/src/HintingLineEdit.cpp
+++ b/MantidQt/MantidWidgets/src/HintingLineEdit.cpp
@@ -3,204 +3,192 @@
 #include <boost/algorithm/string.hpp>
 #include <QToolTip>
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    HintingLineEdit::HintingLineEdit(QWidget *parent, const std::map<std::string,std::string> &hints) : QLineEdit(parent), m_hints(hints), m_dontComplete(false)
-    {
-      m_hintLabel = new QLabel(this, Qt::ToolTip);
-      m_hintLabel->setMargin(1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, m_hintLabel));
-      m_hintLabel->setFrameStyle(QFrame::StyledPanel);
-      m_hintLabel->setAlignment(Qt::AlignLeft);
-      m_hintLabel->setWordWrap(true);
-      m_hintLabel->setIndent(1);
-      m_hintLabel->setAutoFillBackground(true);
-      m_hintLabel->setPalette(QToolTip::palette());
-      m_hintLabel->setForegroundRole(QPalette::ToolTipText);
-      m_hintLabel->setBackgroundRole(QPalette::ToolTipBase);
-      m_hintLabel->ensurePolished();
-
-      connect(this, SIGNAL(textEdited(const QString&)), this, SLOT(updateHints(const QString&)));
-      connect(this, SIGNAL(editingFinished()), this, SLOT(hideHints()));
-    }
-
-    HintingLineEdit::~HintingLineEdit()
-    {
-    }
-
-    /** Handle a key press event.
-
-        @param e : A pointer to the event
-     */
-    void HintingLineEdit::keyPressEvent(QKeyEvent* e)
-    {
-      m_dontComplete = (e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete || e->key() == Qt::Key_Space);
-
-      if(e->key() == Qt::Key_Up)
-      {
-        prevSuggestion();
-        return;
-      }
-
-      if(e->key() == Qt::Key_Down)
-      {
-        nextSuggestion();
-        return;
-      }
-      QLineEdit::keyPressEvent(e);
-    }
-
-    /** Rebuild a list of hints whenever the user edits the text, and use the hints
-        to make auto completion suggestions.
-
-        @param text : The new contents of the QLineEdit
-     */
-    void HintingLineEdit::updateHints(const QString& text)
-    {
-      const size_t curPos = (size_t)cursorPosition();
-      const std::string line = text.toStdString();
-
-      //Get everything before the cursor
-      std::string prefix = line.substr(0, curPos);
-
-      //Now remove everything before the last ',' to give us the current word
-      std::size_t startPos = prefix.find_last_of(",");
-      if(startPos != std::string::npos)
-        prefix = prefix.substr(startPos + 1, prefix.size() - (startPos + 1));
-
-      //Remove any leading or trailing whitespace
-      boost::trim(prefix);
-
-      //Set the current key/prefix
-      m_curKey = prefix;
-
-      //Update our current list of matches
-      updateMatches();
-
-      //Show the potential matches in a tooltip
-      showToolTip();
-
-      //Suggest one of them to the user via auto-completion
-      insertSuggestion();
-    }
-
-    /** Hides the list of hints
-    */
-    void HintingLineEdit::hideHints() { m_hintLabel->hide(); }
-
-    /** Updates the list of hints matching the user's current input */
-    void HintingLineEdit::updateMatches()
-    {
-      m_curMatch.clear();
-      m_matches.clear();
-
-      for(auto it = m_hints.begin(); it != m_hints.end(); ++it)
-      {
-        const std::string& hint = it->first;
-
-        if(hint.length() < m_curKey.length())
-          continue;
-
-        const std::string hintPrefix = hint.substr(0, m_curKey.length());
-
-        if(m_curKey == hintPrefix)
-          m_matches[hint] = it->second;
-      }
-    }
-
-    /** Show a tooltip with the current relevant hints */
-    void HintingLineEdit::showToolTip()
-    {
-      QString hintList;
-      for(auto mIt = m_matches.begin(); mIt != m_matches.end(); ++mIt)
-      {
-        hintList += "<b>" + QString::fromStdString(mIt->first) + "</b><br />\n";
-        if(!mIt->second.empty())
-          hintList += QString::fromStdString(mIt->second) + "<br />\n";
-      }
-
-      if(!hintList.trimmed().isEmpty())
-      {
-        m_hintLabel->show();
-        m_hintLabel->setText(hintList.trimmed());
-        m_hintLabel->adjustSize();
-        m_hintLabel->move(mapToGlobal(QPoint(0, height())));
-      }
-      else
-      {
-        m_hintLabel->hide();
-      }
-    }
-
-    /** Insert an auto completion suggestion beneath the user's cursor and select it */
-    void HintingLineEdit::insertSuggestion()
-    {
-      if(m_curKey.length() < 1 || m_matches.size() < 1 || m_dontComplete)
-        return;
-
-      //If we don't have a match, just use the first one in the map
-      if(m_curMatch.empty())
-        m_curMatch = m_matches.begin()->first;
-
-      QString line = text();
-      const int curPos = cursorPosition();
-
-      //Don't perform insertions mid-word
-      if(curPos + 1 < line.size() && line[curPos+1].isLetterOrNumber())
-        return;
-
-      //Insert a suggestion under the cursor, then select it
-      line = line.left(curPos) + QString::fromStdString(m_curMatch).mid((int)m_curKey.size()) + line.mid(curPos);
-
-      setText(line);
-      setSelection(curPos, (int)m_curMatch.size());
-    }
-
-    /** Remove any existing auto completion suggestion */
-    void HintingLineEdit::clearSuggestion()
-    {
-      if(!hasSelectedText())
-        return;
-
-      //Carefully cut out the selected text
-      QString line = text();
-      line = line.left(selectionStart()) + line.mid(selectionStart() + selectedText().length());
-      setText(line);
-    }
-
-    /** Change to the next available auto completion suggestion */
-    void HintingLineEdit::nextSuggestion()
-    {
-      clearSuggestion();
-      //Find the next suggestion in the hint map
-      auto it = m_matches.find(m_curMatch);
-      if(it != m_matches.end())
-      {
-        it++;
-        if(it == m_matches.end())
-          m_curMatch = m_matches.begin()->first;
-        else
-          m_curMatch = it->first;
-        insertSuggestion();
-      }
-    }
-
-    /** Change to the previous auto completion suggestion */
-    void HintingLineEdit::prevSuggestion()
-    {
-      clearSuggestion();
-      //Find the previous suggestion in the hint map
-      auto it = m_matches.find(m_curMatch);
-      if(it != m_matches.end())
-      {
-        it--;
-        if(it == m_matches.end())
-          m_curMatch = m_matches.rbegin()->first;
-        else
-          m_curMatch = it->first;
-        insertSuggestion();
-      }
-    }
-  } //namespace MantidWidgets
-} //namepsace MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+HintingLineEdit::HintingLineEdit(
+    QWidget *parent, const std::map<std::string, std::string> &hints)
+    : QLineEdit(parent), m_hints(hints), m_dontComplete(false) {
+  m_hintLabel = new QLabel(this, Qt::ToolTip);
+  m_hintLabel->setMargin(
+      1 +
+      style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, m_hintLabel));
+  m_hintLabel->setFrameStyle(QFrame::StyledPanel);
+  m_hintLabel->setAlignment(Qt::AlignLeft);
+  m_hintLabel->setWordWrap(true);
+  m_hintLabel->setIndent(1);
+  m_hintLabel->setAutoFillBackground(true);
+  m_hintLabel->setPalette(QToolTip::palette());
+  m_hintLabel->setForegroundRole(QPalette::ToolTipText);
+  m_hintLabel->setBackgroundRole(QPalette::ToolTipBase);
+  m_hintLabel->ensurePolished();
+
+  connect(this, SIGNAL(textEdited(const QString &)), this,
+          SLOT(updateHints(const QString &)));
+  connect(this, SIGNAL(editingFinished()), this, SLOT(hideHints()));
+}
+
+HintingLineEdit::~HintingLineEdit() {}
+
+/** Handle a key press event.
+
+    @param e : A pointer to the event
+ */
+void HintingLineEdit::keyPressEvent(QKeyEvent *e) {
+  m_dontComplete = (e->key() == Qt::Key_Backspace ||
+                    e->key() == Qt::Key_Delete || e->key() == Qt::Key_Space);
+
+  if (e->key() == Qt::Key_Up) {
+    prevSuggestion();
+    return;
+  }
+
+  if (e->key() == Qt::Key_Down) {
+    nextSuggestion();
+    return;
+  }
+  QLineEdit::keyPressEvent(e);
+}
+
+/** Rebuild a list of hints whenever the user edits the text, and use the hints
+    to make auto completion suggestions.
+
+    @param text : The new contents of the QLineEdit
+ */
+void HintingLineEdit::updateHints(const QString &text) {
+  const size_t curPos = (size_t)cursorPosition();
+  const std::string line = text.toStdString();
+
+  // Get everything before the cursor
+  std::string prefix = line.substr(0, curPos);
+
+  // Now remove everything before the last ',' to give us the current word
+  std::size_t startPos = prefix.find_last_of(",");
+  if (startPos != std::string::npos)
+    prefix = prefix.substr(startPos + 1, prefix.size() - (startPos + 1));
+
+  // Remove any leading or trailing whitespace
+  boost::trim(prefix);
+
+  // Set the current key/prefix
+  m_curKey = prefix;
+
+  // Update our current list of matches
+  updateMatches();
+
+  // Show the potential matches in a tooltip
+  showToolTip();
+
+  // Suggest one of them to the user via auto-completion
+  insertSuggestion();
+}
+
+/** Hides the list of hints
+*/
+void HintingLineEdit::hideHints() { m_hintLabel->hide(); }
+
+/** Updates the list of hints matching the user's current input */
+void HintingLineEdit::updateMatches() {
+  m_curMatch.clear();
+  m_matches.clear();
+
+  for (auto it = m_hints.begin(); it != m_hints.end(); ++it) {
+    const std::string &hint = it->first;
+
+    if (hint.length() < m_curKey.length())
+      continue;
+
+    const std::string hintPrefix = hint.substr(0, m_curKey.length());
+
+    if (m_curKey == hintPrefix)
+      m_matches[hint] = it->second;
+  }
+}
+
+/** Show a tooltip with the current relevant hints */
+void HintingLineEdit::showToolTip() {
+  QString hintList;
+  for (auto mIt = m_matches.begin(); mIt != m_matches.end(); ++mIt) {
+    hintList += "<b>" + QString::fromStdString(mIt->first) + "</b><br />\n";
+    if (!mIt->second.empty())
+      hintList += QString::fromStdString(mIt->second) + "<br />\n";
+  }
+
+  if (!hintList.trimmed().isEmpty()) {
+    m_hintLabel->show();
+    m_hintLabel->setText(hintList.trimmed());
+    m_hintLabel->adjustSize();
+    m_hintLabel->move(mapToGlobal(QPoint(0, height())));
+  } else {
+    m_hintLabel->hide();
+  }
+}
+
+/** Insert an auto completion suggestion beneath the user's cursor and select it
+ */
+void HintingLineEdit::insertSuggestion() {
+  if (m_curKey.length() < 1 || m_matches.size() < 1 || m_dontComplete)
+    return;
+
+  // If we don't have a match, just use the first one in the map
+  if (m_curMatch.empty())
+    m_curMatch = m_matches.begin()->first;
+
+  QString line = text();
+  const int curPos = cursorPosition();
+
+  // Don't perform insertions mid-word
+  if (curPos + 1 < line.size() && line[curPos + 1].isLetterOrNumber())
+    return;
+
+  // Insert a suggestion under the cursor, then select it
+  line = line.left(curPos) +
+         QString::fromStdString(m_curMatch).mid((int)m_curKey.size()) +
+         line.mid(curPos);
+
+  setText(line);
+  setSelection(curPos, (int)m_curMatch.size());
+}
+
+/** Remove any existing auto completion suggestion */
+void HintingLineEdit::clearSuggestion() {
+  if (!hasSelectedText())
+    return;
+
+  // Carefully cut out the selected text
+  QString line = text();
+  line = line.left(selectionStart()) +
+         line.mid(selectionStart() + selectedText().length());
+  setText(line);
+}
+
+/** Change to the next available auto completion suggestion */
+void HintingLineEdit::nextSuggestion() {
+  clearSuggestion();
+  // Find the next suggestion in the hint map
+  auto it = m_matches.find(m_curMatch);
+  if (it != m_matches.end()) {
+    it++;
+    if (it == m_matches.end())
+      m_curMatch = m_matches.begin()->first;
+    else
+      m_curMatch = it->first;
+    insertSuggestion();
+  }
+}
+
+/** Change to the previous auto completion suggestion */
+void HintingLineEdit::prevSuggestion() {
+  clearSuggestion();
+  // Find the previous suggestion in the hint map
+  auto it = m_matches.find(m_curMatch);
+  if (it != m_matches.end()) {
+    it--;
+    if (it == m_matches.end())
+      m_curMatch = m_matches.rbegin()->first;
+    else
+      m_curMatch = it->first;
+    insertSuggestion();
+  }
+}
+} // namespace MantidWidgets
+} // namepsace MantidQt
diff --git a/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp b/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
index 26fdabae88a6f02d627d3025105a5081a94ea15b..61a3d795026d9692894b9f8c7bdbd078a3aef7b9 100644
--- a/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
+++ b/MantidQt/MantidWidgets/src/IndirectInstrumentConfig.cpp
@@ -10,461 +10,395 @@ using namespace Mantid::API;
 using namespace Mantid::Geometry;
 using MantidQt::MantidWidgets::InstrumentSelector;
 
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("IndirectInstrumentConfig");
+namespace {
+Mantid::Kernel::Logger g_log("IndirectInstrumentConfig");
 }
 
+namespace MantidQt {
+namespace MantidWidgets {
 
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-
-    IndirectInstrumentConfig::IndirectInstrumentConfig(QWidget *parent): API::MantidWidget(parent),
-      m_algRunner(),
-      m_disabledInstruments(),
-      m_removeDiffraction(false),
-      m_forceDiffraction(false)
-    {
-      m_uiForm.setupUi(this);
-
-      m_instrumentSelector = new InstrumentSelector(0, false);
-      m_instrumentSelector->updateInstrumentOnSelection(false);
-			m_uiForm.loInstrument->addWidget(m_instrumentSelector);
-
-      // Use this signal to filter the instrument list for disabled instruments
-      connect(m_instrumentSelector, SIGNAL(instrumentListUpdated()),
-              this, SLOT(filterDisabledInstruments()));
-
-      connect(m_instrumentSelector, SIGNAL(instrumentSelectionChanged(const QString)),
-              this, SLOT(updateInstrumentConfigurations(const QString)));
-      connect(m_uiForm.cbAnalyser, SIGNAL(currentIndexChanged(int)),
-              this, SLOT(updateReflectionsList(int)));
-      connect(m_uiForm.cbReflection, SIGNAL(currentIndexChanged(int)),
-              this, SLOT(newInstrumentConfiguration()));
-
-      m_instrumentSelector->fillWithInstrumentsFromFacility();
-    }
-
-
-    IndirectInstrumentConfig::~IndirectInstrumentConfig()
-    {
-    }
-
-
-    /**
-     * Gets the list of techniques used to filter instruments by.
-     *
-     * @return List of techniques
-     */
-    QStringList IndirectInstrumentConfig::getTechniques()
-    {
-      return m_instrumentSelector->getTechniques();
-    }
-
-
-    /**
-     * Set a list of techniques by which the list of instruments should be filtered.
-     *
-     * @param techniques List of techniques
-     */
-    void IndirectInstrumentConfig::setTechniques(const QStringList & techniques)
-    {
-      m_instrumentSelector->setTechniques(techniques);
-    }
-
-
-    /**
-     * Gets a list of instruments that have been removed from the instrument list.
-     *
-     * @return List of disabled instruments
-     */
-    QStringList IndirectInstrumentConfig::getDisabledInstruments()
-    {
-      return m_disabledInstruments;
-    }
-
+IndirectInstrumentConfig::IndirectInstrumentConfig(QWidget *parent)
+    : API::MantidWidget(parent), m_algRunner(), m_disabledInstruments(),
+      m_removeDiffraction(false), m_forceDiffraction(false) {
+  m_uiForm.setupUi(this);
 
-    /**
-     * Removes a list of instruments from the instrument list.
-     *
-     * @param instrumentNames List of names of instruments to remove
-     */
-    void IndirectInstrumentConfig::setDisabledInstruments(const QStringList & instrumentNames)
-    {
-      m_disabledInstruments.append(instrumentNames);
-
-      filterDisabledInstruments();
-    }
+  m_instrumentSelector = new InstrumentSelector(0, false);
+  m_instrumentSelector->updateInstrumentOnSelection(false);
+  m_uiForm.loInstrument->addWidget(m_instrumentSelector);
 
+  // Use this signal to filter the instrument list for disabled instruments
+  connect(m_instrumentSelector, SIGNAL(instrumentListUpdated()), this,
+          SLOT(filterDisabledInstruments()));
 
-    /**
-     * Gets the name of the facility instruments are displayed from.
-     *
-     * @return Name of facility
-     */
-    QString IndirectInstrumentConfig::getFacility()
-    {
-      return m_instrumentSelector->getFacility();
-    }
-
-
-    /**
-     * Sets a facility to lock the widget to.
-     *
-     * @param facilityName Name of facility
-     */
-    void IndirectInstrumentConfig::setFacility(const QString & facilityName)
-    {
-      m_instrumentSelector->setAutoUpdate(false);
-      m_instrumentSelector->setFacility(facilityName);
-      filterDisabledInstruments();
-    }
+  connect(m_instrumentSelector,
+          SIGNAL(instrumentSelectionChanged(const QString)), this,
+          SLOT(updateInstrumentConfigurations(const QString)));
+  connect(m_uiForm.cbAnalyser, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(updateReflectionsList(int)));
+  connect(m_uiForm.cbReflection, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(newInstrumentConfiguration()));
 
+  m_instrumentSelector->fillWithInstrumentsFromFacility();
+}
 
-    /**
-     * Checks to see if diffraction is allowed in the analyser bank list.
-     *
-     * @return True if diffraction is an allowed analyser, false otherwise
-     */
-    bool IndirectInstrumentConfig::isDiffractionEnabled()
-    {
-      return !m_removeDiffraction;
-    }
-
+IndirectInstrumentConfig::~IndirectInstrumentConfig() {}
 
-    /**
-     * Sets if diffraction should bre removed from list of analyser banks.
-     *
-     * @param enabled Set to false to remove diffraction option
-     */
-    void IndirectInstrumentConfig::enableDiffraction(bool enabled)
-    {
-      if(!enabled)
-        forceDiffraction(false);
+/**
+ * Gets the list of techniques used to filter instruments by.
+ *
+ * @return List of techniques
+ */
+QStringList IndirectInstrumentConfig::getTechniques() {
+  return m_instrumentSelector->getTechniques();
+}
 
-      m_removeDiffraction = !enabled;
-      updateInstrumentConfigurations(getInstrumentName());
-    }
+/**
+ * Set a list of techniques by which the list of instruments should be filtered.
+ *
+ * @param techniques List of techniques
+ */
+void IndirectInstrumentConfig::setTechniques(const QStringList &techniques) {
+  m_instrumentSelector->setTechniques(techniques);
+}
 
+/**
+ * Gets a list of instruments that have been removed from the instrument list.
+ *
+ * @return List of disabled instruments
+ */
+QStringList IndirectInstrumentConfig::getDisabledInstruments() {
+  return m_disabledInstruments;
+}
 
-    /**
-     * Checks to see if diffraction is the only allowed analyser bank.
-     *
-     * @return True if diffraction is the only allowed analyser
-     */
-    bool IndirectInstrumentConfig::isDiffractionForced()
-    {
-      return m_forceDiffraction;
-    }
+/**
+ * Removes a list of instruments from the instrument list.
+ *
+ * @param instrumentNames List of names of instruments to remove
+ */
+void IndirectInstrumentConfig::setDisabledInstruments(
+    const QStringList &instrumentNames) {
+  m_disabledInstruments.append(instrumentNames);
 
+  filterDisabledInstruments();
+}
 
-    /**
-     * Sets if diffraction should be the only allowed analyser bank option.
-     *
-     * @param forced If diffraction is the only allowed analyser
-     */
-    void IndirectInstrumentConfig::forceDiffraction(bool forced)
-    {
-      if(forced)
-        enableDiffraction(true);
+/**
+ * Gets the name of the facility instruments are displayed from.
+ *
+ * @return Name of facility
+ */
+QString IndirectInstrumentConfig::getFacility() {
+  return m_instrumentSelector->getFacility();
+}
 
-      m_forceDiffraction = forced;
-      updateInstrumentConfigurations(getInstrumentName());
-    }
+/**
+ * Sets a facility to lock the widget to.
+ *
+ * @param facilityName Name of facility
+ */
+void IndirectInstrumentConfig::setFacility(const QString &facilityName) {
+  m_instrumentSelector->setAutoUpdate(false);
+  m_instrumentSelector->setFacility(facilityName);
+  filterDisabledInstruments();
+}
 
+/**
+ * Checks to see if diffraction is allowed in the analyser bank list.
+ *
+ * @return True if diffraction is an allowed analyser, false otherwise
+ */
+bool IndirectInstrumentConfig::isDiffractionEnabled() {
+  return !m_removeDiffraction;
+}
 
-    /**
-     * Check to see if the "Instrument" label is shown.
-     *
-     * @return If label is shown
-     */
-    bool IndirectInstrumentConfig::isInstrumentLabelShown()
-    {
-      return m_uiForm.lbInstrument->isVisible();
-    }
+/**
+ * Sets if diffraction should bre removed from list of analyser banks.
+ *
+ * @param enabled Set to false to remove diffraction option
+ */
+void IndirectInstrumentConfig::enableDiffraction(bool enabled) {
+  if (!enabled)
+    forceDiffraction(false);
+
+  m_removeDiffraction = !enabled;
+  updateInstrumentConfigurations(getInstrumentName());
+}
 
+/**
+ * Checks to see if diffraction is the only allowed analyser bank.
+ *
+ * @return True if diffraction is the only allowed analyser
+ */
+bool IndirectInstrumentConfig::isDiffractionForced() {
+  return m_forceDiffraction;
+}
 
-    /**
-     * Sets if the "Instrument" label should be shown or now.
-     *
-     * @param visible If the label is visible
-     */
-    void IndirectInstrumentConfig::setShowInstrumentLabel(bool visible)
-    {
-      m_uiForm.lbInstrument->setVisible(visible);
-    }
+/**
+ * Sets if diffraction should be the only allowed analyser bank option.
+ *
+ * @param forced If diffraction is the only allowed analyser
+ */
+void IndirectInstrumentConfig::forceDiffraction(bool forced) {
+  if (forced)
+    enableDiffraction(true);
+
+  m_forceDiffraction = forced;
+  updateInstrumentConfigurations(getInstrumentName());
+}
 
+/**
+ * Check to see if the "Instrument" label is shown.
+ *
+ * @return If label is shown
+ */
+bool IndirectInstrumentConfig::isInstrumentLabelShown() {
+  return m_uiForm.lbInstrument->isVisible();
+}
 
-    /**
-     * Sets the currently displayed instrument, providing that the name given
-     * exists in the list currently displayed.
-     *
-     * @param instrumentName Name of instrument to display
-     */
-    void IndirectInstrumentConfig::setInstrument(const QString & instrumentName)
-    {
-      int index = m_instrumentSelector->findText(instrumentName);
-
-      if(index >= 0)
-      {
-        m_instrumentSelector->setCurrentIndex(index);
-      }
-      else
-      {
-        g_log.information() << "Instrument " << instrumentName.toStdString()
-                            << " not found in current list, using default" << std::endl;
-      }
-    }
+/**
+ * Sets if the "Instrument" label should be shown or now.
+ *
+ * @param visible If the label is visible
+ */
+void IndirectInstrumentConfig::setShowInstrumentLabel(bool visible) {
+  m_uiForm.lbInstrument->setVisible(visible);
+}
 
+/**
+ * Sets the currently displayed instrument, providing that the name given
+ * exists in the list currently displayed.
+ *
+ * @param instrumentName Name of instrument to display
+ */
+void IndirectInstrumentConfig::setInstrument(const QString &instrumentName) {
+  int index = m_instrumentSelector->findText(instrumentName);
+
+  if (index >= 0) {
+    m_instrumentSelector->setCurrentIndex(index);
+  } else {
+    g_log.information() << "Instrument " << instrumentName.toStdString()
+                        << " not found in current list, using default"
+                        << std::endl;
+  }
+}
 
-    /**
-     * Gets the name of the instrument that is currently selected.
-     *
-     * @return Name of instrument.
-     */
-    QString IndirectInstrumentConfig::getInstrumentName()
-    {
-      return m_instrumentSelector->currentText();
-    }
+/**
+ * Gets the name of the instrument that is currently selected.
+ *
+ * @return Name of instrument.
+ */
+QString IndirectInstrumentConfig::getInstrumentName() {
+  return m_instrumentSelector->currentText();
+}
 
+/**
+ * Sets the currently displayed analyser, providing that the name given
+ * exists in the list currently displayed.
+ *
+ * @param analyserName Name of analyser to display
+ */
+void IndirectInstrumentConfig::setAnalyser(const QString &analyserName) {
+  int index = m_uiForm.cbAnalyser->findText(analyserName);
+
+  if (index >= 0) {
+    m_uiForm.cbAnalyser->setCurrentIndex(index);
+  } else {
+    g_log.information() << "Analyser " << analyserName.toStdString()
+                        << " not found in current list, using default"
+                        << std::endl;
+  }
+}
 
-    /**
-     * Sets the currently displayed analyser, providing that the name given
-     * exists in the list currently displayed.
-     *
-     * @param analyserName Name of analyser to display
-     */
-    void IndirectInstrumentConfig::setAnalyser(const QString & analyserName)
-    {
-      int index = m_uiForm.cbAnalyser->findText(analyserName);
-
-      if(index >= 0)
-      {
-        m_uiForm.cbAnalyser->setCurrentIndex(index);
-      }
-      else
-      {
-        g_log.information() << "Analyser " << analyserName.toStdString()
-                            << " not found in current list, using default" << std::endl;
-      }
-    }
+/**
+ * Gets the name of the analyser bank that is currently selected.
+ *
+ * @return Name of analyser bank
+ */
+QString IndirectInstrumentConfig::getAnalyserName() {
+  return m_uiForm.cbAnalyser->currentText();
+}
 
+/**
+ * Sets the currently displayed reflection, providing that the name given
+ * exists in the list currently displayed.
+ *
+ * @param reflectionName Name of reflection to display
+ */
+void IndirectInstrumentConfig::setReflection(const QString &reflectionName) {
+  int index = m_uiForm.cbReflection->findText(reflectionName);
+
+  if (index >= 0) {
+    m_uiForm.cbReflection->setCurrentIndex(index);
+  } else {
+    g_log.information() << "Reflection " << reflectionName.toStdString()
+                        << " not found in current list, using default"
+                        << std::endl;
+  }
+}
 
-    /**
-     * Gets the name of the analyser bank that is currently selected.
-     *
-     * @return Name of analyser bank
-     */
-    QString IndirectInstrumentConfig::getAnalyserName()
-    {
-      return m_uiForm.cbAnalyser->currentText();
-    }
+/**
+ * Gets the name of the reflection mode currently selected.
+ *
+ * @return Name of reflection mode
+ */
+QString IndirectInstrumentConfig::getReflectionName() {
+  return m_uiForm.cbReflection->currentText();
+}
 
+/**
+ * Updates the analyser and reflection names in the UI when an instrument is
+ *selected.
+ *
+ * @param instrumentName Nmae of instrument
+ */
+void IndirectInstrumentConfig::updateInstrumentConfigurations(
+    const QString &instrumentName) {
+  if (instrumentName.isEmpty())
+    return;
+
+  g_log.debug() << "Loading configuration for instrument: "
+                << instrumentName.toStdString() << std::endl;
+
+  bool analyserPreviousBlocking = m_uiForm.cbAnalyser->signalsBlocked();
+  m_uiForm.cbAnalyser->blockSignals(true);
+
+  m_uiForm.cbAnalyser->clear();
+
+  // Try to load the instrument into an empty workspace
+  MatrixWorkspace_sptr instWorkspace;
+  try {
+    IAlgorithm_sptr loadInstAlg =
+        AlgorithmManager::Instance().create("CreateSimulationWorkspace");
+    loadInstAlg->initialize();
+    loadInstAlg->setChild(true);
+    loadInstAlg->setLogging(false);
+    loadInstAlg->setProperty("Instrument", instrumentName.toStdString());
+    loadInstAlg->setProperty("BinParams", "0,0.5,1");
+    loadInstAlg->setProperty("OutputWorkspace", "__empty_instrument_workspace");
+    loadInstAlg->execute();
+    instWorkspace = loadInstAlg->getProperty("OutputWorkspace");
+  } catch (...) {
+  }
+
+  // Try to update the list of analysers
+  bool valid = updateAnalysersList(instWorkspace);
+  m_uiForm.cbAnalyser->setEnabled(valid);
+  if (!valid)
+    m_uiForm.cbAnalyser->addItem("No Valid Analysers");
+
+  // Update the list of reflections
+  int index = m_uiForm.cbAnalyser->currentIndex();
+  updateReflectionsList(index);
+
+  m_uiForm.cbAnalyser->blockSignals(analyserPreviousBlocking);
+}
 
-    /**
-     * Sets the currently displayed reflection, providing that the name given
-     * exists in the list currently displayed.
-     *
-     * @param reflectionName Name of reflection to display
-     */
-    void IndirectInstrumentConfig::setReflection(const QString & reflectionName)
-    {
-      int index = m_uiForm.cbReflection->findText(reflectionName);
-
-      if(index >= 0)
-      {
-        m_uiForm.cbReflection->setCurrentIndex(index);
-      }
-      else
-      {
-        g_log.information() << "Reflection " << reflectionName.toStdString()
-                            << " not found in current list, using default" << std::endl;
-      }
+/**
+ * Update the list of analysers based on an instrument workspace.
+ *
+ * @param ws Instrument workspace
+ * @return If the workspace contained valid analysers
+ */
+bool IndirectInstrumentConfig::updateAnalysersList(MatrixWorkspace_sptr ws) {
+  if (!ws)
+    return false;
+
+  QList<QPair<QString, QString>> instrumentModes;
+  Instrument_const_sptr instrument = ws->getInstrument();
+
+  std::vector<std::string> ipfAnalysers =
+      instrument->getStringParameter("analysers");
+  QStringList analysers;
+  if (ipfAnalysers.size() > 0)
+    analysers = QString::fromStdString(ipfAnalysers[0]).split(",");
+
+  // Do not try to display analysers if there are none
+  if (analysers.size() == 0)
+    return false;
+
+  for (auto it = analysers.begin(); it != analysers.end(); ++it) {
+    QString analyser = *it;
+    std::string ipfReflections =
+        instrument->getStringParameter("refl-" + analyser.toStdString())[0];
+    QStringList reflections = QString::fromStdString(ipfReflections).split(",");
+
+    if (m_removeDiffraction && analyser == "diffraction")
+      continue;
+
+    if (m_forceDiffraction && analyser != "diffraction")
+      continue;
+
+    if (reflections.size() > 0) {
+      QVariant data = QVariant(reflections);
+      m_uiForm.cbAnalyser->addItem(analyser, data);
+    } else {
+      m_uiForm.cbAnalyser->addItem(analyser);
     }
+  }
 
+  return true;
+}
 
-    /**
-     * Gets the name of the reflection mode currently selected.
-     *
-     * @return Name of reflection mode
-     */
-    QString IndirectInstrumentConfig::getReflectionName()
-    {
-      return m_uiForm.cbReflection->currentText();
-    }
+/**
+ * Updates the list of reflection model when an analyser bank is selected.
+ *
+ * @param index Index of the analyser selected
+ */
+void IndirectInstrumentConfig::updateReflectionsList(int index) {
+  bool reflectionPreviousBlocking = m_uiForm.cbReflection->signalsBlocked();
+  m_uiForm.cbReflection->blockSignals(true);
 
+  m_uiForm.cbReflection->clear();
 
-    /**
-     * Updates the analyser and reflection names in the UI when an instrument is selected.
-     *
-     * @param instrumentName Nmae of instrument
-     */
-    void IndirectInstrumentConfig::updateInstrumentConfigurations(const QString & instrumentName)
-    {
-      if(instrumentName.isEmpty())
-        return;
-
-      g_log.debug() << "Loading configuration for instrument: " << instrumentName.toStdString() << std::endl;
-
-      bool analyserPreviousBlocking = m_uiForm.cbAnalyser->signalsBlocked();
-      m_uiForm.cbAnalyser->blockSignals(true);
-
-      m_uiForm.cbAnalyser->clear();
-
-      // Try to load the instrument into an empty workspace
-      MatrixWorkspace_sptr instWorkspace;
-      try
-      {
-        IAlgorithm_sptr loadInstAlg = AlgorithmManager::Instance().create("CreateSimulationWorkspace");
-        loadInstAlg->initialize();
-        loadInstAlg->setChild(true);
-        loadInstAlg->setLogging(false);
-        loadInstAlg->setProperty("Instrument", instrumentName.toStdString());
-        loadInstAlg->setProperty("BinParams", "0,0.5,1");
-        loadInstAlg->setProperty("OutputWorkspace", "__empty_instrument_workspace");
-        loadInstAlg->execute();
-        instWorkspace = loadInstAlg->getProperty("OutputWorkspace");
-      }
-      catch(...)
-      {
-      }
-
-      // Try to update the list of analysers
-      bool valid = updateAnalysersList(instWorkspace);
-      m_uiForm.cbAnalyser->setEnabled(valid);
-      if(!valid)
-        m_uiForm.cbAnalyser->addItem("No Valid Analysers");
-
-      // Update the list of reflections
-      int index = m_uiForm.cbAnalyser->currentIndex();
-      updateReflectionsList(index);
-
-      m_uiForm.cbAnalyser->blockSignals(analyserPreviousBlocking);
-    }
+  QVariant currentData = m_uiForm.cbAnalyser->itemData(index);
+  bool valid = currentData != QVariant::Invalid;
+  m_uiForm.cbReflection->setEnabled(valid);
 
+  if (valid) {
+    QStringList reflections = currentData.toStringList();
+    for (int i = 0; i < reflections.count(); i++)
+      m_uiForm.cbReflection->addItem(reflections[i]);
+  } else {
+    m_uiForm.cbReflection->addItem("No Valid Reflections");
+  }
 
-    /**
-     * Update the list of analysers based on an instrument workspace.
-     *
-     * @param ws Instrument workspace
-     * @return If the workspace contained valid analysers
-     */
-    bool IndirectInstrumentConfig::updateAnalysersList(MatrixWorkspace_sptr ws)
-    {
-      if(!ws)
-        return false;
-
-      QList<QPair<QString, QString>> instrumentModes;
-      Instrument_const_sptr instrument = ws->getInstrument();
-
-      std::vector<std::string> ipfAnalysers = instrument->getStringParameter("analysers");
-      QStringList analysers;
-      if(ipfAnalysers.size() > 0)
-        analysers = QString::fromStdString(ipfAnalysers[0]).split(",");
-
-      // Do not try to display analysers if there are none
-      if(analysers.size() == 0)
-        return false;
-
-      for(auto it = analysers.begin(); it != analysers.end(); ++it)
-      {
-        QString analyser = *it;
-        std::string ipfReflections = instrument->getStringParameter("refl-" + analyser.toStdString())[0];
-        QStringList reflections = QString::fromStdString(ipfReflections).split(",");
-
-        if(m_removeDiffraction && analyser == "diffraction")
-          continue;
-
-        if(m_forceDiffraction && analyser != "diffraction")
-          continue;
-
-        if(reflections.size() > 0)
-        {
-          QVariant data = QVariant(reflections);
-          m_uiForm.cbAnalyser->addItem(analyser, data);
-        }
-        else
-        {
-          m_uiForm.cbAnalyser->addItem(analyser);
-        }
-      }
-
-      return true;
-    }
-
+  m_uiForm.cbReflection->blockSignals(reflectionPreviousBlocking);
 
-    /**
-     * Updates the list of reflection model when an analyser bank is selected.
-     *
-     * @param index Index of the analyser selected
-     */
-    void IndirectInstrumentConfig::updateReflectionsList(int index)
-    {
-      bool reflectionPreviousBlocking = m_uiForm.cbReflection->signalsBlocked();
-      m_uiForm.cbReflection->blockSignals(true);
-
-      m_uiForm.cbReflection->clear();
-
-      QVariant currentData = m_uiForm.cbAnalyser->itemData(index);
-      bool valid = currentData != QVariant::Invalid;
-      m_uiForm.cbReflection->setEnabled(valid);
-
-      if(valid)
-      {
-        QStringList reflections = currentData.toStringList();
-        for ( int i = 0; i < reflections.count(); i++ )
-          m_uiForm.cbReflection->addItem(reflections[i]);
-      }
-      else
-      {
-        m_uiForm.cbReflection->addItem("No Valid Reflections");
-      }
-
-      m_uiForm.cbReflection->blockSignals(reflectionPreviousBlocking);
-
-      newInstrumentConfiguration();
-    }
+  newInstrumentConfiguration();
+}
 
+/**
+ * Handles logging and signal emission when the instrument setup has been
+ *updated.
+ *
+ * Can be called manually to use instrumentConfigurationUpdated signal to init
+ *UI elements.
+ */
+void IndirectInstrumentConfig::newInstrumentConfiguration() {
+  g_log.debug() << "Instrument configuration: "
+                << "Instrument=" << getInstrumentName().toStdString()
+                << ", Analyser=" << getAnalyserName().toStdString()
+                << ", Reflection=" << getReflectionName().toStdString()
+                << std::endl;
+
+  emit instrumentConfigurationUpdated(getInstrumentName(), getAnalyserName(),
+                                      getReflectionName());
+}
 
-    /**
-     * Handles logging and signal emission when the instrument setup has been updated.
-     *
-     * Can be called manually to use instrumentConfigurationUpdated signal to init UI elements.
-     */
-    void IndirectInstrumentConfig::newInstrumentConfiguration()
-    {
-      g_log.debug() << "Instrument configuration: "
-                    << "Instrument=" << getInstrumentName().toStdString()
-                    << ", Analyser=" << getAnalyserName().toStdString()
-                    << ", Reflection=" << getReflectionName().toStdString()
-                    << std::endl;
-
-      emit instrumentConfigurationUpdated(getInstrumentName(), getAnalyserName(), getReflectionName());
+/**
+ * Filters all disabled instruments out of the instrument list.
+ */
+void IndirectInstrumentConfig::filterDisabledInstruments() {
+  for (int i = 0; i < m_instrumentSelector->count();) {
+    if (m_disabledInstruments.contains(m_instrumentSelector->itemText(i))) {
+      m_instrumentSelector->removeItem(i);
+    } else {
+      ++i;
     }
+  }
 
+  updateInstrumentConfigurations(getInstrumentName());
+}
 
-    /**
-     * Filters all disabled instruments out of the instrument list.
-     */
-    void IndirectInstrumentConfig::filterDisabledInstruments()
-    {
-      for(int i = 0; i < m_instrumentSelector->count();)
-      {
-        if(m_disabledInstruments.contains(m_instrumentSelector->itemText(i)))
-        {
-          m_instrumentSelector->removeItem(i);
-        }
-        else
-        {
-          ++i;
-        }
-      }
-
-      updateInstrumentConfigurations(getInstrumentName());
-    }
-
-  } /* namespace MantidWidgets */
+} /* namespace MantidWidgets */
 } /* namespace MantidQt */
diff --git a/MantidQt/MantidWidgets/src/InputController.cpp b/MantidQt/MantidWidgets/src/InputController.cpp
index afc5d3d445b33e9739ee4fc1cb6b667c42e17455..3f0b82621526c4986300d61a6b3938314c16dca5 100644
--- a/MantidQt/MantidWidgets/src/InputController.cpp
+++ b/MantidQt/MantidWidgets/src/InputController.cpp
@@ -13,10 +13,8 @@ namespace MantidWidgets {
 
 //--------------------------------------------------------------------------------
 
-InputController::InputController(QObject *parent, bool contextAllowed) :
-QObject(parent),m_canShowContextMenu(contextAllowed)
-{
-}
+InputController::InputController(QObject *parent, bool contextAllowed)
+    : QObject(parent), m_canShowContextMenu(contextAllowed) {}
 
 //--------------------------------------------------------------------------------
 
@@ -24,72 +22,55 @@ QObject(parent),m_canShowContextMenu(contextAllowed)
   * Constructor.
   * @param parent :: The parent object.
   */
-InputController3DMove::InputController3DMove(QObject *parent):
-InputController(parent,false),
-m_isButtonPressed(false)
-{
-}
+InputController3DMove::InputController3DMove(QObject *parent)
+    : InputController(parent, false), m_isButtonPressed(false) {}
 
 /**
   * Process the mouse press event.
   * Send out movement initialization signals.
   */
-void InputController3DMove::mousePressEvent(QMouseEvent *event)
-{
-    if (event->buttons() & Qt::MidButton)
-    {
-      emit initZoom(event->x(),event->y());
-      m_isButtonPressed=true;
-    }
-    else if (event->buttons() & Qt::LeftButton)
-    {
-      emit initRotation(event->x(),event->y());
-      m_isButtonPressed=true;
-    }
-    else if(event->buttons() & Qt::RightButton)
-    {
-      emit initTranslation(event->x(),event->y());
-      m_isButtonPressed=true;
-    }
+void InputController3DMove::mousePressEvent(QMouseEvent *event) {
+  if (event->buttons() & Qt::MidButton) {
+    emit initZoom(event->x(), event->y());
+    m_isButtonPressed = true;
+  } else if (event->buttons() & Qt::LeftButton) {
+    emit initRotation(event->x(), event->y());
+    m_isButtonPressed = true;
+  } else if (event->buttons() & Qt::RightButton) {
+    emit initTranslation(event->x(), event->y());
+    m_isButtonPressed = true;
+  }
 }
 
 /**
   * Process the mouse move event.
   * Send out surface movement signals.
   */
-void InputController3DMove::mouseMoveEvent(QMouseEvent *event)
-{
-    if (event->buttons() & Qt::LeftButton)
-    {
-      emit rotate(event->x(),event->y());
-    }
-    else if(event->buttons() & Qt::RightButton)
-    {
-      emit translate(event->x(),event->y());
-    }
-    else if(event->buttons() & Qt::MidButton)
-    {
-      emit zoom(event->x(),event->y());
-    }
+void InputController3DMove::mouseMoveEvent(QMouseEvent *event) {
+  if (event->buttons() & Qt::LeftButton) {
+    emit rotate(event->x(), event->y());
+  } else if (event->buttons() & Qt::RightButton) {
+    emit translate(event->x(), event->y());
+  } else if (event->buttons() & Qt::MidButton) {
+    emit zoom(event->x(), event->y());
+  }
 }
 
 /**
   * Process the mouse release event.
   * Finalize the interaction.
   */
-void InputController3DMove::mouseReleaseEvent(QMouseEvent *)
-{
-    m_isButtonPressed = false;
-    emit finish();
+void InputController3DMove::mouseReleaseEvent(QMouseEvent *) {
+  m_isButtonPressed = false;
+  emit finish();
 }
 
 /**
   * Process the mouse wheel event.
   * Send the wheel zoom signal.
   */
-void InputController3DMove::wheelEvent(QWheelEvent *event)
-{
-    emit wheelZoom( event->x(), event->y(), event->delta() );
+void InputController3DMove::wheelEvent(QWheelEvent *event) {
+  emit wheelZoom(event->x(), event->y(), event->delta());
 }
 
 //--------------------------------------------------------------------------------
@@ -98,48 +79,38 @@ void InputController3DMove::wheelEvent(QWheelEvent *event)
   * Constructor.
   * @param parent :: The parent object.
   */
-InputControllerPick::InputControllerPick(QObject *parent):
-InputController(parent),
-m_isButtonPressed(false)
-{
-}
+InputControllerPick::InputControllerPick(QObject *parent)
+    : InputController(parent), m_isButtonPressed(false) {}
 
 /**
   * Process the mouse press event.
   */
-void InputControllerPick::mousePressEvent(QMouseEvent *event)
-{
-    if (event->button() == Qt::LeftButton)
-    {
-      m_isButtonPressed = true;
-      m_rect.setRect( event->x(), event->y(), 1, 1 );
-      emit pickPointAt( event->x(), event->y() );
-    }
+void InputControllerPick::mousePressEvent(QMouseEvent *event) {
+  if (event->button() == Qt::LeftButton) {
+    m_isButtonPressed = true;
+    m_rect.setRect(event->x(), event->y(), 1, 1);
+    emit pickPointAt(event->x(), event->y());
+  }
 }
 
 /**
   * Process the mouse move event.
   */
-void InputControllerPick::mouseMoveEvent(QMouseEvent *event)
-{
-    if ( m_isButtonPressed )
-    {
-      m_rect.setBottomRight(QPoint( event->x(), event->y() ));
-      emit setSelection(m_rect);
-    }
-    else
-    {
-      emit touchPointAt( event->x(), event->y() );
-    }
+void InputControllerPick::mouseMoveEvent(QMouseEvent *event) {
+  if (m_isButtonPressed) {
+    m_rect.setBottomRight(QPoint(event->x(), event->y()));
+    emit setSelection(m_rect);
+  } else {
+    emit touchPointAt(event->x(), event->y());
+  }
 }
 
 /**
   * Process the mouse release event.
   */
-void InputControllerPick::mouseReleaseEvent(QMouseEvent *)
-{
-    m_isButtonPressed = false;
-    emit finishSelection();
+void InputControllerPick::mouseReleaseEvent(QMouseEvent *) {
+  m_isButtonPressed = false;
+  emit finishSelection();
 }
 
 //--------------------------------------------------------------------------------
@@ -147,104 +118,85 @@ void InputControllerPick::mouseReleaseEvent(QMouseEvent *)
 /**
   * Constructor.
   */
-InputControllerDrawShape::InputControllerDrawShape(QObject *parent):
-InputController(parent),
-m_creating(false),
-m_x(0),
-m_y(0),
-m_shapeType(),
-m_isButtonPressed(false)
-{
-}
+InputControllerDrawShape::InputControllerDrawShape(QObject *parent)
+    : InputController(parent), m_creating(false), m_x(0), m_y(0), m_shapeType(),
+      m_isButtonPressed(false) {}
 
 /**
   * Process the mouse press event. Sends addShape or selectAt signal.
   */
-void InputControllerDrawShape::mousePressEvent(QMouseEvent *event)
-{
-    if (event->button() == Qt::LeftButton)
-    {
-      m_isButtonPressed = true;
-      if ( m_creating && !m_shapeType.isEmpty() )
-      {
-        emit addShape( m_shapeType, event->x(), event->y(), m_borderColor, m_fillColor );
-      }
-      else if ( event->modifiers() & Qt::ControlModifier )
-      {
-          emit selectCtrlAt( event->x(), event->y() );
-      }
-      else
-      {
-          emit selectAt( event->x(), event->y() );
-      }
-      m_x = event->x();
-      m_y = event->y();
-      m_rect.setRect( event->x(), event->y(), 1, 1 );
+void InputControllerDrawShape::mousePressEvent(QMouseEvent *event) {
+  if (event->button() == Qt::LeftButton) {
+    m_isButtonPressed = true;
+    if (m_creating && !m_shapeType.isEmpty()) {
+      emit addShape(m_shapeType, event->x(), event->y(), m_borderColor,
+                    m_fillColor);
+    } else if (event->modifiers() & Qt::ControlModifier) {
+      emit selectCtrlAt(event->x(), event->y());
+    } else {
+      emit selectAt(event->x(), event->y());
     }
+    m_x = event->x();
+    m_y = event->y();
+    m_rect.setRect(event->x(), event->y(), 1, 1);
+  }
 }
 
 /**
-  * Process the mouse move event. If the left mouse button is down sends editing signals.
+  * Process the mouse move event. If the left mouse button is down sends editing
+ * signals.
   */
-void InputControllerDrawShape::mouseMoveEvent(QMouseEvent *event)
-{
-    if ( m_isButtonPressed )
-    {
-        if ( m_creating )
-        {
-            emit moveRightBottomTo( event->x(), event->y() );
-        }
-        else
-        {
-            emit moveBy( event->x() - m_x, event->y() - m_y );
-            m_rect.setBottomRight(QPoint( event->x(), event->y() ));
-            m_x = event->x();
-            m_y = event->y();
-            emit setSelection( m_rect );
-        }
-    }
-    else
-    {
-        emit touchPointAt( event->x(), event->y() );
+void InputControllerDrawShape::mouseMoveEvent(QMouseEvent *event) {
+  if (m_isButtonPressed) {
+    if (m_creating) {
+      emit moveRightBottomTo(event->x(), event->y());
+    } else {
+      emit moveBy(event->x() - m_x, event->y() - m_y);
+      m_rect.setBottomRight(QPoint(event->x(), event->y()));
+      m_x = event->x();
+      m_y = event->y();
+      emit setSelection(m_rect);
     }
+  } else {
+    emit touchPointAt(event->x(), event->y());
+  }
 }
 
 /**
   * Process the mouse button release event.
   */
-void InputControllerDrawShape::mouseReleaseEvent(QMouseEvent *)
-{
-    m_isButtonPressed = false;
-    m_creating = false;
-    m_shapeType = "";
-    emit finishSelection( m_rect );
+void InputControllerDrawShape::mouseReleaseEvent(QMouseEvent *) {
+  m_isButtonPressed = false;
+  m_creating = false;
+  m_shapeType = "";
+  emit finishSelection(m_rect);
 }
 
 /**
   * Process the keyboard key press event.
   */
-void InputControllerDrawShape::keyPressEvent(QKeyEvent *event)
-{
-    switch(event->key())
-    {
-    case Qt::Key_Delete:
-    case Qt::Key_Backspace: emit removeSelectedShapes(); break;
-    }
+void InputControllerDrawShape::keyPressEvent(QKeyEvent *event) {
+  switch (event->key()) {
+  case Qt::Key_Delete:
+  case Qt::Key_Backspace:
+    emit removeSelectedShapes();
+    break;
+  }
 }
 
 /**
   * Process event of the mouse leaving the widget.
   */
-void InputControllerDrawShape::leaveEvent(QEvent *)
-{
-    emit restoreOverrideCursor();
+void InputControllerDrawShape::leaveEvent(QEvent *) {
+  emit restoreOverrideCursor();
 }
 
 /**
   * Slot for defining the shape to draw and initializing drawing.
   */
-void InputControllerDrawShape::startCreatingShape2D(const QString& type,const QColor& borderColor,const QColor& fillColor)
-{
+void InputControllerDrawShape::startCreatingShape2D(const QString &type,
+                                                    const QColor &borderColor,
+                                                    const QColor &fillColor) {
   m_creating = true;
   m_shapeType = type;
   m_borderColor = borderColor;
@@ -254,60 +206,48 @@ void InputControllerDrawShape::startCreatingShape2D(const QString& type,const QC
 /**
  * Action on disabling.
  */
-void InputControllerDrawShape::onDisabled()
-{
-    m_creating = false;
-    emit disabled();
+void InputControllerDrawShape::onDisabled() {
+  m_creating = false;
+  emit disabled();
 }
 //--------------------------------------------------------------------------------
 
 /**
   * Constructor.
   */
-InputControllerMoveUnwrapped::InputControllerMoveUnwrapped(QObject *parent):
-InputController(parent,false),
-m_isButtonPressed(false)
-{
-}
+InputControllerMoveUnwrapped::InputControllerMoveUnwrapped(QObject *parent)
+    : InputController(parent, false), m_isButtonPressed(false) {}
 
 /**
   * Process the mouse press event.
   */
-void InputControllerMoveUnwrapped::mousePressEvent(QMouseEvent *event)
-{
-    if (event->button() == Qt::LeftButton)
-    {
-        m_isButtonPressed = true;
-        m_rect.setTopLeft(QPoint(event->x(),event->y()));
-    }
-    else if (event->button() == Qt::RightButton)
-    {
-        emit unzoom();
-    }
+void InputControllerMoveUnwrapped::mousePressEvent(QMouseEvent *event) {
+  if (event->button() == Qt::LeftButton) {
+    m_isButtonPressed = true;
+    m_rect.setTopLeft(QPoint(event->x(), event->y()));
+  } else if (event->button() == Qt::RightButton) {
+    emit unzoom();
+  }
 }
 
 /**
   * Process the mouse move event.
   */
-void InputControllerMoveUnwrapped::mouseMoveEvent(QMouseEvent *event)
-{
-    if ( m_isButtonPressed )
-    {
-        m_rect.setBottomRight(QPoint(event->x(),event->y()));
-        emit setSelectionRect(m_rect);
-    }
+void InputControllerMoveUnwrapped::mouseMoveEvent(QMouseEvent *event) {
+  if (m_isButtonPressed) {
+    m_rect.setBottomRight(QPoint(event->x(), event->y()));
+    emit setSelectionRect(m_rect);
+  }
 }
 
 /**
   * Process the mouse button release event.
   */
-void InputControllerMoveUnwrapped::mouseReleaseEvent(QMouseEvent *)
-{
-    if ( m_isButtonPressed )
-    {
-        emit zoom();
-    }
-    m_isButtonPressed = false;
+void InputControllerMoveUnwrapped::mouseReleaseEvent(QMouseEvent *) {
+  if (m_isButtonPressed) {
+    emit zoom();
+  }
+  m_isButtonPressed = false;
 }
 
 //--------------------------------------------------------------------------------
@@ -315,183 +255,139 @@ void InputControllerMoveUnwrapped::mouseReleaseEvent(QMouseEvent *)
 /**
   * Constructor.
   */
-InputControllerDraw::InputControllerDraw(QObject *parent):
-InputController(parent),
-m_max_size(32),
-m_size(30),
-m_isLeftButtonPressed(false),
-m_isRightButtonPressed(false),
-m_isActive(false),
-m_cursor(NULL)
-{
-}
+InputControllerDraw::InputControllerDraw(QObject *parent)
+    : InputController(parent), m_max_size(32), m_size(30),
+      m_isLeftButtonPressed(false), m_isRightButtonPressed(false),
+      m_isActive(false), m_cursor(NULL) {}
 
-InputControllerDraw::~InputControllerDraw()
-{
-    delete m_cursor;
-}
+InputControllerDraw::~InputControllerDraw() { delete m_cursor; }
 
 /**
   * Process the mouse press event.
   */
-void InputControllerDraw::mousePressEvent(QMouseEvent *event)
-{
-    m_isActive = true;
-    setPosition(QPoint(event->x(),event->y()));
-    if (event->button() == Qt::LeftButton)
-    {
-        m_isLeftButtonPressed = true;
-        signalLeftClick();
-    }
-    else if (event->button() == Qt::RightButton)
-    {
-        m_isRightButtonPressed = true;
-        signalRightClick();
-    }
+void InputControllerDraw::mousePressEvent(QMouseEvent *event) {
+  m_isActive = true;
+  setPosition(QPoint(event->x(), event->y()));
+  if (event->button() == Qt::LeftButton) {
+    m_isLeftButtonPressed = true;
+    signalLeftClick();
+  } else if (event->button() == Qt::RightButton) {
+    m_isRightButtonPressed = true;
+    signalRightClick();
+  }
 }
 
 /**
   * Process the mouse move event.
   */
-void InputControllerDraw::mouseMoveEvent(QMouseEvent *event)
-{
-    m_isActive = true;
-    setPosition(QPoint(event->x(),event->y()));
-    if ( m_isLeftButtonPressed )
-    {
-        signalLeftClick();
-    }
-    else if ( m_isRightButtonPressed )
-    {
-        signalRightClick();
-    }
+void InputControllerDraw::mouseMoveEvent(QMouseEvent *event) {
+  m_isActive = true;
+  setPosition(QPoint(event->x(), event->y()));
+  if (m_isLeftButtonPressed) {
+    signalLeftClick();
+  } else if (m_isRightButtonPressed) {
+    signalRightClick();
+  }
 }
 
 /**
   * Process the mouse button release event.
   */
-void InputControllerDraw::mouseReleaseEvent(QMouseEvent *event)
-{
-    if (event->button() == Qt::LeftButton)
-    {
-        m_isLeftButtonPressed = false;
-    }
-    else if (event->button() == Qt::RightButton)
-    {
-        m_isRightButtonPressed = false;
-    }
+void InputControllerDraw::mouseReleaseEvent(QMouseEvent *event) {
+  if (event->button() == Qt::LeftButton) {
+    m_isLeftButtonPressed = false;
+  } else if (event->button() == Qt::RightButton) {
+    m_isRightButtonPressed = false;
+  }
 }
 
-void InputControllerDraw::wheelEvent(QWheelEvent *event)
-{
-    int d = m_size + ( event->delta() > 0 ? 4 : -4 );
-    if ( d > 2 && d < m_max_size )
-    {
-        m_size = d;
-        resize();
-        redrawCursor();
-        QApplication::restoreOverrideCursor();
-        QApplication::setOverrideCursor(QCursor( *m_cursor, 0, 0 ));
-    }
+void InputControllerDraw::wheelEvent(QWheelEvent *event) {
+  int d = m_size + (event->delta() > 0 ? 4 : -4);
+  if (d > 2 && d < m_max_size) {
+    m_size = d;
+    resize();
+    redrawCursor();
+    QApplication::restoreOverrideCursor();
+    QApplication::setOverrideCursor(QCursor(*m_cursor, 0, 0));
+  }
 }
 
-void InputControllerDraw::enterEvent(QEvent *)
-{
-    redrawCursor();
-    QApplication::setOverrideCursor(QCursor( *m_cursor, 0, 0 ));
-    m_isActive = true;
+void InputControllerDraw::enterEvent(QEvent *) {
+  redrawCursor();
+  QApplication::setOverrideCursor(QCursor(*m_cursor, 0, 0));
+  m_isActive = true;
 }
 
-void InputControllerDraw::leaveEvent(QEvent *)
-{
-    QApplication::restoreOverrideCursor();
-    m_isActive = false;
+void InputControllerDraw::leaveEvent(QEvent *) {
+  QApplication::restoreOverrideCursor();
+  m_isActive = false;
 }
 
-void InputControllerDraw::redrawCursor()
-{
-  if (!m_cursor)
-  {
-    m_cursor = new QPixmap(m_max_size,m_max_size);
+void InputControllerDraw::redrawCursor() {
+  if (!m_cursor) {
+    m_cursor = new QPixmap(m_max_size, m_max_size);
   }
   drawCursor(m_cursor);
 }
 
-void InputControllerDraw::signalRightClick()
-{
-}
+void InputControllerDraw::signalRightClick() {}
 
 //--------------------------------------------------------------------------------
 
-InputControllerErase::InputControllerErase(QObject *parent): InputControllerDraw(parent),
-  m_rect( 0, 0, cursorSize(), cursorSize() ) 
-{
+InputControllerErase::InputControllerErase(QObject *parent)
+    : InputControllerDraw(parent), m_rect(0, 0, cursorSize(), cursorSize()) {
   m_image = new QPixmap(":/PickTools/eraser.png");
 }
 
-InputControllerErase::~InputControllerErase()
-{
-  delete m_image;
-}
+InputControllerErase::~InputControllerErase() { delete m_image; }
 
-void InputControllerErase::signalLeftClick()
-{
-  emit erase(m_rect);
-}
+void InputControllerErase::signalLeftClick() { emit erase(m_rect); }
 
-void InputControllerErase::onPaint(QPainter& painter)
-{
-    if ( isActive() && !isLeftButtonPressed() )
-    {
-        painter.drawPixmap(m_rect.bottomRight(),*m_image);
-    }
+void InputControllerErase::onPaint(QPainter &painter) {
+  if (isActive() && !isLeftButtonPressed()) {
+    painter.drawPixmap(m_rect.bottomRight(), *m_image);
+  }
 }
 
-void InputControllerErase::drawCursor(QPixmap *cursor)
-{
-    cursor->fill(QColor(255,255,255,0));
-    QPainter painter( cursor );
-    auto size = cursorSize();
+void InputControllerErase::drawCursor(QPixmap *cursor) {
+  cursor->fill(QColor(255, 255, 255, 0));
+  QPainter painter(cursor);
+  auto size = cursorSize();
 
-    auto pen = QPen(Qt::DashLine);
-    QVector<qreal> dashPattern;
-    dashPattern << 4 << 4;
-    pen.setDashPattern(dashPattern);
-    pen.setColor(QColor(0,0,0));
-    painter.setPen(pen);
-    painter.drawRect( QRect( 0, 0, size, size ) );
+  auto pen = QPen(Qt::DashLine);
+  QVector<qreal> dashPattern;
+  dashPattern << 4 << 4;
+  pen.setDashPattern(dashPattern);
+  pen.setColor(QColor(0, 0, 0));
+  painter.setPen(pen);
+  painter.drawRect(QRect(0, 0, size, size));
 
-    pen.setColor(QColor(255,255,255));
-    pen.setDashOffset(4);
-    painter.setPen(pen);
-    painter.drawRect( QRect( 0, 0, size, size ) );
+  pen.setColor(QColor(255, 255, 255));
+  pen.setDashOffset(4);
+  painter.setPen(pen);
+  painter.drawRect(QRect(0, 0, size, size));
 }
 
-void InputControllerErase::setPosition(const QPoint &pos)
-{
+void InputControllerErase::setPosition(const QPoint &pos) {
   m_rect.moveTopLeft(pos);
 }
 
-void InputControllerErase::resize()
-{
-    auto size = cursorSize();
-    m_rect.setSize( QSize(size, size) );
+void InputControllerErase::resize() {
+  auto size = cursorSize();
+  m_rect.setSize(QSize(size, size));
 }
 
 //--------------------------------------------------------------------------------
 
-InputControllerDrawAndErase::InputControllerDrawAndErase(QObject *parent): InputControllerDraw(parent),
-  m_pos(0,0), m_rect(8), m_creating(false)
-{
+InputControllerDrawAndErase::InputControllerDrawAndErase(QObject *parent)
+    : InputControllerDraw(parent), m_pos(0, 0), m_rect(8), m_creating(false) {
   makePolygon();
 }
 
-void InputControllerDrawAndErase::makePolygon()
-{
+void InputControllerDrawAndErase::makePolygon() {
   auto r = double(cursorSize()) / 2.0;
   double a = 2.0 * M_PI / double(m_rect.size());
-  for(int i = 0; i < m_rect.size(); ++i)
-  {
+  for (int i = 0; i < m_rect.size(); ++i) {
     double ia = double(i) * a;
     auto x = r + static_cast<int>(r * cos(ia));
     auto y = r + static_cast<int>(r * sin(ia));
@@ -499,66 +395,54 @@ void InputControllerDrawAndErase::makePolygon()
   }
 }
 
-void InputControllerDrawAndErase::signalLeftClick()
-{
+void InputControllerDrawAndErase::signalLeftClick() {
   auto poly = m_rect.translated(m_pos);
-  if (m_creating)
-  {
+  if (m_creating) {
     m_creating = false;
     emit addShape(poly, m_borderColor, m_fillColor);
-  }
-  else
-  {
+  } else {
     emit draw(poly);
   }
 }
 
-void InputControllerDrawAndErase::signalRightClick()
-{
+void InputControllerDrawAndErase::signalRightClick() {
   auto poly = m_rect.translated(m_pos);
   emit erase(poly);
 }
 
-void InputControllerDrawAndErase::drawCursor(QPixmap *cursor)
-{
-    cursor->fill(QColor(255,255,255,0));
-    QPainter painter( cursor );
+void InputControllerDrawAndErase::drawCursor(QPixmap *cursor) {
+  cursor->fill(QColor(255, 255, 255, 0));
+  QPainter painter(cursor);
 
-    auto bRect = m_rect.boundingRect();
-    auto poly = m_rect.translated(-bRect.topLeft());
+  auto bRect = m_rect.boundingRect();
+  auto poly = m_rect.translated(-bRect.topLeft());
 
-    auto pen = QPen(Qt::DashLine);
-    QVector<qreal> dashPattern;
-    qreal dashLength = cursorSize() < 10 ? 1 : 2;
-    dashPattern << dashLength << dashLength;
-    pen.setDashPattern(dashPattern);
-    pen.setColor(QColor(0,0,0));
-    painter.setPen(pen);
-    painter.drawPolygon(poly);
+  auto pen = QPen(Qt::DashLine);
+  QVector<qreal> dashPattern;
+  qreal dashLength = cursorSize() < 10 ? 1 : 2;
+  dashPattern << dashLength << dashLength;
+  pen.setDashPattern(dashPattern);
+  pen.setColor(QColor(0, 0, 0));
+  painter.setPen(pen);
+  painter.drawPolygon(poly);
 
-    pen.setColor(QColor(255,255,255));
-    pen.setDashOffset(dashLength);
-    painter.setPen(pen);
-    painter.drawPolygon(poly);
+  pen.setColor(QColor(255, 255, 255));
+  pen.setDashOffset(dashLength);
+  painter.setPen(pen);
+  painter.drawPolygon(poly);
 }
 
-void InputControllerDrawAndErase::setPosition(const QPoint &pos)
-{
+void InputControllerDrawAndErase::setPosition(const QPoint &pos) {
   m_pos = pos;
 }
 
-void InputControllerDrawAndErase::resize()
-{
-  makePolygon();
-}
+void InputControllerDrawAndErase::resize() { makePolygon(); }
 
-void InputControllerDrawAndErase::startCreatingShape2D(const QColor &borderColor, const QColor &fillColor)
-{
+void InputControllerDrawAndErase::startCreatingShape2D(
+    const QColor &borderColor, const QColor &fillColor) {
   m_borderColor = borderColor;
   m_fillColor = fillColor;
   m_creating = true;
 }
-
 }
 }
-
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/BinDialog.cpp b/MantidQt/MantidWidgets/src/InstrumentView/BinDialog.cpp
index 9753d4fee57077ce60e79360c3241d9d2d2146b4..82002f9616f7522e4c3feae694119b9bfdd6c788 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/BinDialog.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/BinDialog.cpp
@@ -10,91 +10,86 @@
 #include <QLineEdit>
 #include <QRadioButton>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		*Constructor
-		*/
-		BinDialog::BinDialog(QWidget* parent) :QDialog(parent)
-		{
-			//Set the tile of the window
-			setWindowTitle(QString("Select X Range"));
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+*Constructor
+*/
+BinDialog::BinDialog(QWidget *parent) : QDialog(parent) {
+  // Set the tile of the window
+  setWindowTitle(QString("Select X Range"));
 
-			//frame for group box
-			QFrame* groupBox = new QFrame();
-			//Double Validator
-			QValidator *validator = new QDoubleValidator(this);
-			//Input value for Integral option
-			mIntegralMinValue = new QLineEdit();
-			mIntegralMinValue->setValidator(validator);
-			mIntegralMaxValue = new QLineEdit();
-			mIntegralMaxValue->setValidator(validator);
+  // frame for group box
+  QFrame *groupBox = new QFrame();
+  // Double Validator
+  QValidator *validator = new QDoubleValidator(this);
+  // Input value for Integral option
+  mIntegralMinValue = new QLineEdit();
+  mIntegralMinValue->setValidator(validator);
+  mIntegralMaxValue = new QLineEdit();
+  mIntegralMaxValue->setValidator(validator);
 
-			//Checkbco
-			mEntireRange = new QCheckBox("Use the entire X range", this);
-			connect(mEntireRange, SIGNAL(toggled(bool)), this, SLOT(mEntireRange_toggled(bool)));
+  // Checkbco
+  mEntireRange = new QCheckBox("Use the entire X range", this);
+  connect(mEntireRange, SIGNAL(toggled(bool)), this,
+          SLOT(mEntireRange_toggled(bool)));
 
-			//Create a grid layout
-			QGridLayout  *gridbox = new QGridLayout;
-			gridbox->addWidget(new QLabel("Min X Value:"), 0, 0);
-			gridbox->addWidget(mIntegralMinValue, 0, 1);
-			gridbox->addWidget(new QLabel("Max X Value:"), 1, 0);
-			gridbox->addWidget(mIntegralMaxValue, 1, 1);
-			gridbox->addWidget(mEntireRange, 2, 1);
-			groupBox->setLayout(gridbox);
+  // Create a grid layout
+  QGridLayout *gridbox = new QGridLayout;
+  gridbox->addWidget(new QLabel("Min X Value:"), 0, 0);
+  gridbox->addWidget(mIntegralMinValue, 0, 1);
+  gridbox->addWidget(new QLabel("Max X Value:"), 1, 0);
+  gridbox->addWidget(mIntegralMaxValue, 1, 1);
+  gridbox->addWidget(mEntireRange, 2, 1);
+  groupBox->setLayout(gridbox);
 
-			//create a frame for Ok and Cancel btn
-			QFrame* okcancelFrame = new QFrame();
-			QPushButton* okButton = new QPushButton("Ok");
-			QPushButton* cancelButton = new QPushButton("Cancel");
-			QHBoxLayout* okcancelLayout = new QHBoxLayout;
-			okcancelLayout->addWidget(okButton);
-			okcancelLayout->addWidget(cancelButton);
-			okcancelFrame->setLayout(okcancelLayout);
-			QVBoxLayout *dialogLayout = new QVBoxLayout();
-			dialogLayout->addWidget(groupBox);
-			dialogLayout->addWidget(okcancelFrame);
-			this->setLayout(dialogLayout);
-			connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
-			connect(okButton, SIGNAL(clicked()), this, SLOT(btnOKClicked()));
-		}
+  // create a frame for Ok and Cancel btn
+  QFrame *okcancelFrame = new QFrame();
+  QPushButton *okButton = new QPushButton("Ok");
+  QPushButton *cancelButton = new QPushButton("Cancel");
+  QHBoxLayout *okcancelLayout = new QHBoxLayout;
+  okcancelLayout->addWidget(okButton);
+  okcancelLayout->addWidget(cancelButton);
+  okcancelFrame->setLayout(okcancelLayout);
+  QVBoxLayout *dialogLayout = new QVBoxLayout();
+  dialogLayout->addWidget(groupBox);
+  dialogLayout->addWidget(okcancelFrame);
+  this->setLayout(dialogLayout);
+  connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(okButton, SIGNAL(clicked()), this, SLOT(btnOKClicked()));
+}
 
-		/**
-		* Destructor
-		*/
-		BinDialog::~BinDialog()
-		{
-		}
+/**
+* Destructor
+*/
+BinDialog::~BinDialog() {}
 
-		/** Set the values in the GUI. */
-		void BinDialog::setIntegralMinMax(double minBin, double maxBin, bool useEverything)
-		{
+/** Set the values in the GUI. */
+void BinDialog::setIntegralMinMax(double minBin, double maxBin,
+                                  bool useEverything) {
 
-			QString strBinNum;
-			mIntegralMinValue->setText(strBinNum.setNum(minBin));
-			mIntegralMaxValue->setText(strBinNum.setNum(maxBin));
-			//And the checkbox
-			mEntireRange->setChecked(useEverything);
-			this->mEntireRange_toggled(useEverything);
-		}
+  QString strBinNum;
+  mIntegralMinValue->setText(strBinNum.setNum(minBin));
+  mIntegralMaxValue->setText(strBinNum.setNum(maxBin));
+  // And the checkbox
+  mEntireRange->setChecked(useEverything);
+  this->mEntireRange_toggled(useEverything);
+}
 
+/** Called when the OK button is pressed. */
+void BinDialog::btnOKClicked() {
+  emit IntegralMinMax(mIntegralMinValue->displayText().toDouble(),
+                      mIntegralMaxValue->displayText().toDouble(),
+                      mEntireRange->isChecked());
+  accept();
+}
 
-		/** Called when the OK button is pressed. */
-		void BinDialog::btnOKClicked()
-		{
-			emit IntegralMinMax(mIntegralMinValue->displayText().toDouble(), mIntegralMaxValue->displayText().toDouble(), mEntireRange->isChecked());
-			accept();
-		}
-
-		/** Called when the mEntireRange checkbox state toggles.
-		* Disables the textboxes if the checkbox is on.
-		* */
-		void BinDialog::mEntireRange_toggled(bool on)
-		{
-			this->mIntegralMaxValue->setEnabled(!on);
-			this->mIntegralMinValue->setEnabled(!on);
-		}
-	}//MantidWidgets
-}//MantidQt
+/** Called when the mEntireRange checkbox state toggles.
+* Disables the textboxes if the checkbox is on.
+* */
+void BinDialog::mEntireRange_toggled(bool on) {
+  this->mIntegralMaxValue->setEnabled(!on);
+  this->mIntegralMinValue->setEnabled(!on);
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/CollapsiblePanel.cpp b/MantidQt/MantidWidgets/src/InstrumentView/CollapsiblePanel.cpp
index 5ef259f03708a4d2acbdb419b0c583b1c4a41685..3dd179aeb6df871281789144bd7d5f01673c68ba 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/CollapsiblePanel.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/CollapsiblePanel.cpp
@@ -7,184 +7,151 @@
 
 #include <stdexcept>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		CaptionLabel::CaptionLabel(const QString& caption, QWidget* parent) :QLabel(caption, parent), m_collapsed(false)
-		{
-			setFrameStyle(QFrame::WinPanel);
-			setFrameShadow(QFrame::Raised);
-		}
-
-		void CaptionLabel::mousePressEvent(QMouseEvent* e)
-		{
-			if (e->buttons() & Qt::LeftButton)
-			{
-				e->accept();
-				m_collapsed = !m_collapsed;
-				emit collapseOrExpand(m_collapsed);
-			}
-			else
-			{
-				e->ignore();
-			}
-		}
-
-		void CaptionLabel::paintEvent(QPaintEvent *e)
-		{
-			QLabel::paintEvent(e);
-			QPainter painter(this);
-			QFontMetrics fm(this->font());
-			int h = fm.height() - 4;
-			h = h / 2 * 2; // h is even
-			if (h > 0)
-			{
-				int w = h / 2;
-				int x = this->width() - 2 * h;
-				int y = (this->height() - h) / 2;
-				QPolygon tri(3);
-				if (m_collapsed)
-				{
-					tri.setPoint(0, x, y);
-					tri.setPoint(1, x + w + w, y);
-					tri.setPoint(2, x + w, y + h);
-				}
-				else
-				{
-					tri.setPoint(0, x, y + h);
-					tri.setPoint(1, x + w + w, y + h);
-					tri.setPoint(2, x + w, y);
-				}
-				painter.setBrush(QBrush(QColor(Qt::black)));
-				painter.drawPolygon(tri);
-			}
-		}
-
-		void CaptionLabel::collapse()
-		{
-			m_collapsed = true;
-			emit collapseOrExpand(m_collapsed);
-		}
-
-		void CaptionLabel::expand()
-		{
-			m_collapsed = false;
-			emit collapseOrExpand(m_collapsed);
-		}
-
-		CollapsiblePanel::CollapsiblePanel(const QString& caption, QWidget* parent) :
-			QWidget(parent), m_widget(NULL)
-		{
-			m_layout = new QVBoxLayout(this);
-			m_label = new CaptionLabel(caption, this);
-			m_layout->addWidget(m_label);
-			m_layout->setMargin(0);
-			connect(m_label, SIGNAL(collapseOrExpand(bool)), this, SLOT(collapseOrExpand(bool)));
-		}
-
-		void CollapsiblePanel::setWidget(QWidget* widget)
-		{
-			if (m_widget)
-			{
-				throw std::runtime_error("CollapsiblePanel already has a widget");
-			}
-			m_widget = widget;
-			m_widget->setParent(this);
-			m_layout->addWidget(m_widget);
-		}
-
-		void CollapsiblePanel::setCaption(const QString& caption)
-		{
-			m_label->setText(caption);
-		}
-
-		void CollapsiblePanel::collapseOrExpand(bool collapse)
-		{
-			if (!m_widget) return;
-			if (collapse)
-			{
-				m_widget->hide();
-				emit collapsed();
-			}
-			else
-			{
-				m_widget->show();
-				emit expanded();
-			}
-		}
-
-		bool CollapsiblePanel::isCollapsed()const
-		{
-			return m_label->isCollapsed();
-		}
-
-		void CollapsiblePanel::collapse()
-		{
-			collapseOrExpand(true);
-		}
-
-		void CollapsiblePanel::expand()
-		{
-			collapseOrExpand(false);
-		}
-
-		CollapsibleStack::CollapsibleStack(QWidget* parent) :
-			QWidget(parent)
-		{
-			m_layout = new QVBoxLayout(this);
-			m_layout->setMargin(0);
-			setLayout(m_layout);
-		}
-
-		/**
-		* Add a new panel to the bottom of the stack and set its caption and the inner widget
-		*/
-		CollapsiblePanel* CollapsibleStack::addPanel(const QString& caption, QWidget* widget)
-		{
-			CollapsiblePanel *panel = new CollapsiblePanel(caption, this);
-			panel->setWidget(widget);
-			m_layout->addWidget(panel);
-			connect(panel, SIGNAL(collapsed()), this, SLOT(updateStretch()));
-			connect(panel, SIGNAL(expanded()), this, SLOT(updateStretch()));
-			return panel;
-		}
-
-		bool CollapsibleStack::allCollapsed()const
-		{
-			int n = m_layout->count();
-			for (int i = 0; i < n; ++i)
-			{
-				CollapsiblePanel* panel = dynamic_cast<CollapsiblePanel*>(m_layout->itemAt(i)->widget());
-				if (panel && !panel->isCollapsed())
-				{
-					return false;
-				}
-			}
-			return true;
-		}
-
-		void CollapsibleStack::updateStretch()
-		{
-			int i = m_layout->count();
-			if (i == 0) return;
-			--i; // point to the last item
-			CollapsiblePanel* panel = dynamic_cast<CollapsiblePanel*>(m_layout->itemAt(i)->widget());
-			if (allCollapsed())
-			{// make sure that the last item is a stretch
-				if (panel) // if it's a panel there is no stretch
-				{
-					m_layout->addStretch();
-				}
-			}
-			else
-			{
-				if (!panel) // then it must be a stretch
-				{
-					m_layout->removeItem(m_layout->itemAt(i));
-				}
-			}
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+CaptionLabel::CaptionLabel(const QString &caption, QWidget *parent)
+    : QLabel(caption, parent), m_collapsed(false) {
+  setFrameStyle(QFrame::WinPanel);
+  setFrameShadow(QFrame::Raised);
+}
+
+void CaptionLabel::mousePressEvent(QMouseEvent *e) {
+  if (e->buttons() & Qt::LeftButton) {
+    e->accept();
+    m_collapsed = !m_collapsed;
+    emit collapseOrExpand(m_collapsed);
+  } else {
+    e->ignore();
+  }
+}
+
+void CaptionLabel::paintEvent(QPaintEvent *e) {
+  QLabel::paintEvent(e);
+  QPainter painter(this);
+  QFontMetrics fm(this->font());
+  int h = fm.height() - 4;
+  h = h / 2 * 2; // h is even
+  if (h > 0) {
+    int w = h / 2;
+    int x = this->width() - 2 * h;
+    int y = (this->height() - h) / 2;
+    QPolygon tri(3);
+    if (m_collapsed) {
+      tri.setPoint(0, x, y);
+      tri.setPoint(1, x + w + w, y);
+      tri.setPoint(2, x + w, y + h);
+    } else {
+      tri.setPoint(0, x, y + h);
+      tri.setPoint(1, x + w + w, y + h);
+      tri.setPoint(2, x + w, y);
+    }
+    painter.setBrush(QBrush(QColor(Qt::black)));
+    painter.drawPolygon(tri);
+  }
+}
+
+void CaptionLabel::collapse() {
+  m_collapsed = true;
+  emit collapseOrExpand(m_collapsed);
+}
+
+void CaptionLabel::expand() {
+  m_collapsed = false;
+  emit collapseOrExpand(m_collapsed);
+}
+
+CollapsiblePanel::CollapsiblePanel(const QString &caption, QWidget *parent)
+    : QWidget(parent), m_widget(NULL) {
+  m_layout = new QVBoxLayout(this);
+  m_label = new CaptionLabel(caption, this);
+  m_layout->addWidget(m_label);
+  m_layout->setMargin(0);
+  connect(m_label, SIGNAL(collapseOrExpand(bool)), this,
+          SLOT(collapseOrExpand(bool)));
+}
+
+void CollapsiblePanel::setWidget(QWidget *widget) {
+  if (m_widget) {
+    throw std::runtime_error("CollapsiblePanel already has a widget");
+  }
+  m_widget = widget;
+  m_widget->setParent(this);
+  m_layout->addWidget(m_widget);
+}
+
+void CollapsiblePanel::setCaption(const QString &caption) {
+  m_label->setText(caption);
+}
+
+void CollapsiblePanel::collapseOrExpand(bool collapse) {
+  if (!m_widget)
+    return;
+  if (collapse) {
+    m_widget->hide();
+    emit collapsed();
+  } else {
+    m_widget->show();
+    emit expanded();
+  }
+}
+
+bool CollapsiblePanel::isCollapsed() const { return m_label->isCollapsed(); }
+
+void CollapsiblePanel::collapse() { collapseOrExpand(true); }
+
+void CollapsiblePanel::expand() { collapseOrExpand(false); }
+
+CollapsibleStack::CollapsibleStack(QWidget *parent) : QWidget(parent) {
+  m_layout = new QVBoxLayout(this);
+  m_layout->setMargin(0);
+  setLayout(m_layout);
+}
+
+/**
+* Add a new panel to the bottom of the stack and set its caption and the inner
+* widget
+*/
+CollapsiblePanel *CollapsibleStack::addPanel(const QString &caption,
+                                             QWidget *widget) {
+  CollapsiblePanel *panel = new CollapsiblePanel(caption, this);
+  panel->setWidget(widget);
+  m_layout->addWidget(panel);
+  connect(panel, SIGNAL(collapsed()), this, SLOT(updateStretch()));
+  connect(panel, SIGNAL(expanded()), this, SLOT(updateStretch()));
+  return panel;
+}
+
+bool CollapsibleStack::allCollapsed() const {
+  int n = m_layout->count();
+  for (int i = 0; i < n; ++i) {
+    CollapsiblePanel *panel =
+        dynamic_cast<CollapsiblePanel *>(m_layout->itemAt(i)->widget());
+    if (panel && !panel->isCollapsed()) {
+      return false;
+    }
+  }
+  return true;
+}
+
+void CollapsibleStack::updateStretch() {
+  int i = m_layout->count();
+  if (i == 0)
+    return;
+  --i; // point to the last item
+  CollapsiblePanel *panel =
+      dynamic_cast<CollapsiblePanel *>(m_layout->itemAt(i)->widget());
+  if (allCollapsed()) { // make sure that the last item is a stretch
+    if (panel)          // if it's a panel there is no stretch
+    {
+      m_layout->addStretch();
+    }
+  } else {
+    if (!panel) // then it must be a stretch
+    {
+      m_layout->removeItem(m_layout->itemAt(i));
+    }
+  }
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ColorMapWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ColorMapWidget.cpp
index f91eb246492f80fb05d7053d9f025aeee5bcfbd1..d3e414e18fd4ff71813e5873e737ce4240eeee0f 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ColorMapWidget.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ColorMapWidget.cpp
@@ -15,332 +15,310 @@
 #include <qwt_scale_engine.h>
 #include <QLabel>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* Constructor.
-		* @param type The scale type, e.g. "Linear" or "Log10"
-		* @param parent A parent widget
-		* @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), m_y(0), m_dtype(), m_nth_power(2.0)
-		{
-			m_scaleWidget = new QwtScaleWidget(QwtScaleDraw::RightScale);
-			m_scaleWidget->setColorBarEnabled(true);
-			m_scaleWidget->setColorBarWidth(20);
-			m_scaleWidget->setAlignment(QwtScaleDraw::RightScale);
-			m_scaleWidget->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
-			m_scaleWidget->setCursor(Qt::OpenHandCursor);
-
-			m_minValueBox = new QLineEdit();
-			m_maxValueBox = new QLineEdit();
-			m_minValueBox->setMinimumWidth(40);
-			m_maxValueBox->setMinimumWidth(40);
-			m_minValueBox->setMaximumWidth(60);
-			m_maxValueBox->setMaximumWidth(60);
-			m_minValueBox->setValidator(new QDoubleValidator(m_minValueBox));
-			m_maxValueBox->setValidator(new QDoubleValidator(m_maxValueBox));
-			//Ensure the boxes start empty, this is important for checking if values have been set from the scripting side
-			m_minValueBox->setText("");
-			m_maxValueBox->setText("");
-			connect(m_minValueBox, SIGNAL(editingFinished()), this, SLOT(minValueChanged()));
-			connect(m_maxValueBox, SIGNAL(editingFinished()), this, SLOT(maxValueChanged()));
-
-			QVBoxLayout* lColormapLayout = new QVBoxLayout;
-			lColormapLayout->addWidget(m_maxValueBox);
-			lColormapLayout->addWidget(m_scaleWidget);
-			lColormapLayout->addWidget(m_minValueBox);
-
-			m_scaleOptions = new QComboBox;
-			m_scaleOptions->addItem("Log10", QVariant(GraphOptions::Log10));
-			m_scaleOptions->addItem("Linear", QVariant(GraphOptions::Linear));
-			m_scaleOptions->addItem("Power", QVariant(GraphOptions::Power));
-			m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
-			connect(m_scaleOptions, SIGNAL(currentIndexChanged(int)), this, SLOT(scaleOptionsChanged(int)));
-
-			// Controls for exponent for power scale type
-			m_lblN = new QLabel(tr("n ="));
-			m_lblN->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
-			m_dspnN = new DoubleSpinBox();
-			m_dspnN->setValue(m_nth_power);
-			connect(m_dspnN, SIGNAL(valueChanged(double)), this, SLOT(nPowerChanged(double)));
-
-			QGridLayout* options_layout = new QGridLayout;
-			options_layout->addWidget(m_scaleOptions, 1, 0, 1, 2);
-			options_layout->addWidget(m_lblN, 2, 0);
-			options_layout->addWidget(m_dspnN, 2, 1);
-			options_layout->setRowStretch(0, 4);
-			options_layout->setRowStretch(1, 1);
-			options_layout->setRowStretch(2, 1);
-
-			QHBoxLayout *colourmap_layout = new QHBoxLayout;
-			colourmap_layout->addLayout(lColormapLayout);
-			colourmap_layout->addLayout(options_layout);
-			this->setLayout(colourmap_layout);
-
-		}
-
-		void ColorMapWidget::scaleOptionsChanged(int i)
-		{
-			if (m_scaleOptions->itemData(i).toUInt() == 2) {
-				m_dspnN->setEnabled(true);
-			}
-			else m_dspnN->setEnabled(false);
-
-			emit scaleTypeChanged(m_scaleOptions->itemData(i).toUInt());
-		}
-
-		void ColorMapWidget::nPowerChanged(double nth_power)
-		{
-			emit nthPowerChanged(nth_power);
-		}
-
-		/**
-		* Set up a new colour map.
-		* @param colorMap :: Reference to the new colour map.
-		*/
-		void ColorMapWidget::setupColorBarScaling(const MantidColorMap& colorMap)
-		{
-			double minValue = m_minValueBox->displayText().toDouble();
-			double maxValue = m_maxValueBox->displayText().toDouble();
-
-			GraphOptions::ScaleType type = colorMap.getScaleType();
-			if (type == GraphOptions::Linear)
-			{
-				QwtLinearScaleEngine linScaler;
-				m_scaleWidget->setScaleDiv(linScaler.transformation(), linScaler.divideScale(minValue, maxValue, 20, 5));
-				m_scaleWidget->setColorMap(QwtDoubleInterval(minValue, maxValue), colorMap);
-			}
-			else if (type == GraphOptions::Power)
-			{
-				PowerScaleEngine powerScaler;
-				m_scaleWidget->setScaleDiv(powerScaler.transformation(), powerScaler.divideScale(minValue, maxValue, 20, 5));
-				m_scaleWidget->setColorMap(QwtDoubleInterval(minValue, maxValue), colorMap);
-			}
-			else
-			{
-				QwtLog10ScaleEngine logScaler;
-				double logmin(minValue);
-				if (logmin <= 0.0)
-				{
-					logmin = m_minPositiveValue;
-					m_minValueBox->blockSignals(true);
-					setMinValue(logmin);
-					m_minValueBox->blockSignals(false);
-				}
-				if (maxValue <= 0)
-				{
-					maxValue = 10.;
-					m_maxValueBox->blockSignals(true);
-					setMaxValue(maxValue);
-					m_maxValueBox->blockSignals(false);
-				}
-				m_scaleWidget->setScaleDiv(logScaler.transformation(), logScaler.divideScale(logmin, maxValue, 20, 5));
-				m_scaleWidget->setColorMap(QwtDoubleInterval(logmin, maxValue), colorMap);
-			}
-			m_scaleOptions->blockSignals(true);
-			m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
-			if (m_scaleOptions->findData(type) == 2) {
-				m_dspnN->setEnabled(true);
-			}
-			else {
-				m_dspnN->setEnabled(false);
-			}
-			m_scaleOptions->blockSignals(false);
-		}
-
-		/// Send the minValueChanged signal
-		void ColorMapWidget::minValueChanged()
-		{
-			emit minValueChanged(m_minValueBox->text().toDouble());
-		}
-
-		/// Send the maxValueChanged signal
-		void ColorMapWidget::maxValueChanged()
-		{
-			emit maxValueChanged(m_maxValueBox->text().toDouble());
-		}
-
-		/**
-		* Set a new min value and update the widget.
-		* @param value :: The new value
-		*/
-		void ColorMapWidget::setMinValue(double value)
-		{
-			setMinValueText(value);
-			updateScale();
-			if (!m_minValueBox->signalsBlocked())
-			{
-				minValueChanged();
-			}
-		}
-
-		/**
-		* Set a new max value and update the widget.
-		* @param value :: The new value
-		*/
-		void ColorMapWidget::setMaxValue(double value)
-		{
-			setMaxValueText(value);
-			updateScale();
-			if (!m_maxValueBox->signalsBlocked())
-			{
-				maxValueChanged();
-			}
-		}
-
-		/**
-		* returns the min value as QString
-		*/
-		QString ColorMapWidget::getMinValue() { return m_minValueBox->text(); }
-
-		/**
-		* returns the min value as QString
-		*/
-		QString ColorMapWidget::getMaxValue() { return m_maxValueBox->text(); }
-
-		/**
-		* returns the mnth powder as QString
-		*/
-		QString ColorMapWidget::getNth_power() { return m_dspnN->text(); }
-
-		/**
-		* Update the min value text box.
-		* @param value :: Value to be displayed in the text box.
-		*/
-		void ColorMapWidget::setMinValueText(double value)
-		{
-			m_minValueBox->setText(QString::number(value));
-		}
-
-		/**
-		* Update the max value text box.
-		* @param value :: Value to be displayed in the text box.
-		*/
-		void ColorMapWidget::setMaxValueText(double value)
-		{
-			m_maxValueBox->setText(QString::number(value));
-		}
-
-		/**
-		* Set the minimum positive value for use with the Log10 scale. Values below this will
-		* not be displayed on a Log10 scale.
-		*/
-		void ColorMapWidget::setMinPositiveValue(double value)
-		{
-			m_minPositiveValue = value;
-		}
-
-		/**
-		* Return the scale type: Log10 or Linear.
-		*/
-		int ColorMapWidget::getScaleType()const
-		{
-			return m_scaleOptions->itemData(m_scaleOptions->currentIndex()).toUInt();
-		}
-
-		/**
-		* Set the scale type: Log10 or Linear.
-		*/
-		void ColorMapWidget::setScaleType(int type)
-		{
-			m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
-		}
-
-		void ColorMapWidget::setNthPower(double nth_power)
-		{
-			m_dspnN->setValue(nth_power);
-		}
-
-		/**
-		* Update the colour scale after the range changes.
-		*/
-		void ColorMapWidget::updateScale()
-		{
-			double minValue = m_minValueBox->displayText().toDouble();
-			double maxValue = m_maxValueBox->displayText().toDouble();
-			GraphOptions::ScaleType type = (GraphOptions::ScaleType)m_scaleOptions->itemData(m_scaleOptions->currentIndex()).toUInt();
-			if (type == GraphOptions::Linear)
-			{
-				QwtLinearScaleEngine linScaler;
-				m_scaleWidget->setScaleDiv(linScaler.transformation(), linScaler.divideScale(minValue, maxValue, 20, 5));
-			}
-			else if (type == GraphOptions::Power)
-			{
-				PowerScaleEngine powerScaler;
-				m_scaleWidget->setScaleDiv(powerScaler.transformation(), powerScaler.divideScale(minValue, maxValue, 20, 5));
-			}
-			else
-			{
-				QwtLog10ScaleEngine logScaler;
-				double logmin(minValue);
-				if (logmin <= 0.0)
-				{
-					logmin = m_minPositiveValue;
-				}
-				m_scaleWidget->setScaleDiv(logScaler.transformation(), logScaler.divideScale(logmin, maxValue, 20, 5));
-			}
-		}
-
-		/**
-		* Respond to a mouse press event. Start dragging to modify the range (min or max value).
-		*/
-		void ColorMapWidget::mousePressEvent(QMouseEvent* e)
-		{
-			QRect rect = m_scaleWidget->rect();
-			if (e->x() > rect.left() && e->x() < rect.right())
-			{
-				m_dragging = true;
-				m_y = e->y();
-				m_dtype = (m_y > height() / 2) ? Bottom : Top;
-				QApplication::setOverrideCursor(Qt::ClosedHandCursor);
-			}
-		}
-
-		/**
-		* Respond to mouse move event. If the left button is down change the min or max.
-		*/
-		void ColorMapWidget::mouseMoveEvent(QMouseEvent* e)
-		{
-			if (!m_dragging) return;
-
-			double minValue = m_minValueBox->displayText().toDouble();
-			double maxValue = m_maxValueBox->displayText().toDouble();
-
-			if (m_dtype == Bottom)
-			{
-				minValue += double(e->y() - m_y) / height()*(maxValue - minValue);
-				setMinValueText(minValue);
-			}
-			else
-			{
-				maxValue += double(e->y() - m_y) / height()*(maxValue - minValue);
-				setMaxValueText(maxValue);
-			}
-			m_y = e->y();
-			updateScale();
-		}
-
-		/**
-		* Respond to a mouse release event. Finish all dragging.
-		*/
-		void ColorMapWidget::mouseReleaseEvent(QMouseEvent* /*e*/)
-		{
-			if (!m_dragging) return;
-			if (m_dtype == Bottom)
-			{
-				minValueChanged();
-			}
-			else
-			{
-				maxValueChanged();
-			}
-			QApplication::restoreOverrideCursor();
-			m_dragging = false;
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* Constructor.
+* @param type The scale type, e.g. "Linear" or "Log10"
+* @param parent A parent widget
+* @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),
+      m_y(0), m_dtype(), m_nth_power(2.0) {
+  m_scaleWidget = new QwtScaleWidget(QwtScaleDraw::RightScale);
+  m_scaleWidget->setColorBarEnabled(true);
+  m_scaleWidget->setColorBarWidth(20);
+  m_scaleWidget->setAlignment(QwtScaleDraw::RightScale);
+  m_scaleWidget->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
+  m_scaleWidget->setCursor(Qt::OpenHandCursor);
+
+  m_minValueBox = new QLineEdit();
+  m_maxValueBox = new QLineEdit();
+  m_minValueBox->setMinimumWidth(40);
+  m_maxValueBox->setMinimumWidth(40);
+  m_minValueBox->setMaximumWidth(60);
+  m_maxValueBox->setMaximumWidth(60);
+  m_minValueBox->setValidator(new QDoubleValidator(m_minValueBox));
+  m_maxValueBox->setValidator(new QDoubleValidator(m_maxValueBox));
+  // Ensure the boxes start empty, this is important for checking if values have
+  // been set from the scripting side
+  m_minValueBox->setText("");
+  m_maxValueBox->setText("");
+  connect(m_minValueBox, SIGNAL(editingFinished()), this,
+          SLOT(minValueChanged()));
+  connect(m_maxValueBox, SIGNAL(editingFinished()), this,
+          SLOT(maxValueChanged()));
+
+  QVBoxLayout *lColormapLayout = new QVBoxLayout;
+  lColormapLayout->addWidget(m_maxValueBox);
+  lColormapLayout->addWidget(m_scaleWidget);
+  lColormapLayout->addWidget(m_minValueBox);
+
+  m_scaleOptions = new QComboBox;
+  m_scaleOptions->addItem("Log10", QVariant(GraphOptions::Log10));
+  m_scaleOptions->addItem("Linear", QVariant(GraphOptions::Linear));
+  m_scaleOptions->addItem("Power", QVariant(GraphOptions::Power));
+  m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
+  connect(m_scaleOptions, SIGNAL(currentIndexChanged(int)), this,
+          SLOT(scaleOptionsChanged(int)));
+
+  // Controls for exponent for power scale type
+  m_lblN = new QLabel(tr("n ="));
+  m_lblN->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
+  m_dspnN = new DoubleSpinBox();
+  m_dspnN->setValue(m_nth_power);
+  connect(m_dspnN, SIGNAL(valueChanged(double)), this,
+          SLOT(nPowerChanged(double)));
+
+  QGridLayout *options_layout = new QGridLayout;
+  options_layout->addWidget(m_scaleOptions, 1, 0, 1, 2);
+  options_layout->addWidget(m_lblN, 2, 0);
+  options_layout->addWidget(m_dspnN, 2, 1);
+  options_layout->setRowStretch(0, 4);
+  options_layout->setRowStretch(1, 1);
+  options_layout->setRowStretch(2, 1);
+
+  QHBoxLayout *colourmap_layout = new QHBoxLayout;
+  colourmap_layout->addLayout(lColormapLayout);
+  colourmap_layout->addLayout(options_layout);
+  this->setLayout(colourmap_layout);
+}
+
+void ColorMapWidget::scaleOptionsChanged(int i) {
+  if (m_scaleOptions->itemData(i).toUInt() == 2) {
+    m_dspnN->setEnabled(true);
+  } else
+    m_dspnN->setEnabled(false);
+
+  emit scaleTypeChanged(m_scaleOptions->itemData(i).toUInt());
+}
+
+void ColorMapWidget::nPowerChanged(double nth_power) {
+  emit nthPowerChanged(nth_power);
+}
+
+/**
+* Set up a new colour map.
+* @param colorMap :: Reference to the new colour map.
+*/
+void ColorMapWidget::setupColorBarScaling(const MantidColorMap &colorMap) {
+  double minValue = m_minValueBox->displayText().toDouble();
+  double maxValue = m_maxValueBox->displayText().toDouble();
+
+  GraphOptions::ScaleType type = colorMap.getScaleType();
+  if (type == GraphOptions::Linear) {
+    QwtLinearScaleEngine linScaler;
+    m_scaleWidget->setScaleDiv(
+        linScaler.transformation(),
+        linScaler.divideScale(minValue, maxValue, 20, 5));
+    m_scaleWidget->setColorMap(QwtDoubleInterval(minValue, maxValue), colorMap);
+  } else if (type == GraphOptions::Power) {
+    PowerScaleEngine powerScaler;
+    m_scaleWidget->setScaleDiv(
+        powerScaler.transformation(),
+        powerScaler.divideScale(minValue, maxValue, 20, 5));
+    m_scaleWidget->setColorMap(QwtDoubleInterval(minValue, maxValue), colorMap);
+  } else {
+    QwtLog10ScaleEngine logScaler;
+    double logmin(minValue);
+    if (logmin <= 0.0) {
+      logmin = m_minPositiveValue;
+      m_minValueBox->blockSignals(true);
+      setMinValue(logmin);
+      m_minValueBox->blockSignals(false);
+    }
+    if (maxValue <= 0) {
+      maxValue = 10.;
+      m_maxValueBox->blockSignals(true);
+      setMaxValue(maxValue);
+      m_maxValueBox->blockSignals(false);
+    }
+    m_scaleWidget->setScaleDiv(logScaler.transformation(),
+                               logScaler.divideScale(logmin, maxValue, 20, 5));
+    m_scaleWidget->setColorMap(QwtDoubleInterval(logmin, maxValue), colorMap);
+  }
+  m_scaleOptions->blockSignals(true);
+  m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
+  if (m_scaleOptions->findData(type) == 2) {
+    m_dspnN->setEnabled(true);
+  } else {
+    m_dspnN->setEnabled(false);
+  }
+  m_scaleOptions->blockSignals(false);
+}
+
+/// Send the minValueChanged signal
+void ColorMapWidget::minValueChanged() {
+  emit minValueChanged(m_minValueBox->text().toDouble());
+}
+
+/// Send the maxValueChanged signal
+void ColorMapWidget::maxValueChanged() {
+  emit maxValueChanged(m_maxValueBox->text().toDouble());
+}
+
+/**
+* Set a new min value and update the widget.
+* @param value :: The new value
+*/
+void ColorMapWidget::setMinValue(double value) {
+  setMinValueText(value);
+  updateScale();
+  if (!m_minValueBox->signalsBlocked()) {
+    minValueChanged();
+  }
+}
+
+/**
+* Set a new max value and update the widget.
+* @param value :: The new value
+*/
+void ColorMapWidget::setMaxValue(double value) {
+  setMaxValueText(value);
+  updateScale();
+  if (!m_maxValueBox->signalsBlocked()) {
+    maxValueChanged();
+  }
+}
+
+/**
+* returns the min value as QString
+*/
+QString ColorMapWidget::getMinValue() { return m_minValueBox->text(); }
+
+/**
+* returns the min value as QString
+*/
+QString ColorMapWidget::getMaxValue() { return m_maxValueBox->text(); }
+
+/**
+* returns the mnth powder as QString
+*/
+QString ColorMapWidget::getNth_power() { return m_dspnN->text(); }
+
+/**
+* Update the min value text box.
+* @param value :: Value to be displayed in the text box.
+*/
+void ColorMapWidget::setMinValueText(double value) {
+  m_minValueBox->setText(QString::number(value));
+}
+
+/**
+* Update the max value text box.
+* @param value :: Value to be displayed in the text box.
+*/
+void ColorMapWidget::setMaxValueText(double value) {
+  m_maxValueBox->setText(QString::number(value));
+}
+
+/**
+* Set the minimum positive value for use with the Log10 scale. Values below this
+* will
+* not be displayed on a Log10 scale.
+*/
+void ColorMapWidget::setMinPositiveValue(double value) {
+  m_minPositiveValue = value;
+}
+
+/**
+* Return the scale type: Log10 or Linear.
+*/
+int ColorMapWidget::getScaleType() const {
+  return m_scaleOptions->itemData(m_scaleOptions->currentIndex()).toUInt();
+}
+
+/**
+* Set the scale type: Log10 or Linear.
+*/
+void ColorMapWidget::setScaleType(int type) {
+  m_scaleOptions->setCurrentIndex(m_scaleOptions->findData(type));
+}
+
+void ColorMapWidget::setNthPower(double nth_power) {
+  m_dspnN->setValue(nth_power);
+}
+
+/**
+* Update the colour scale after the range changes.
+*/
+void ColorMapWidget::updateScale() {
+  double minValue = m_minValueBox->displayText().toDouble();
+  double maxValue = m_maxValueBox->displayText().toDouble();
+  GraphOptions::ScaleType type =
+      (GraphOptions::ScaleType)
+          m_scaleOptions->itemData(m_scaleOptions->currentIndex()).toUInt();
+  if (type == GraphOptions::Linear) {
+    QwtLinearScaleEngine linScaler;
+    m_scaleWidget->setScaleDiv(
+        linScaler.transformation(),
+        linScaler.divideScale(minValue, maxValue, 20, 5));
+  } else if (type == GraphOptions::Power) {
+    PowerScaleEngine powerScaler;
+    m_scaleWidget->setScaleDiv(
+        powerScaler.transformation(),
+        powerScaler.divideScale(minValue, maxValue, 20, 5));
+  } else {
+    QwtLog10ScaleEngine logScaler;
+    double logmin(minValue);
+    if (logmin <= 0.0) {
+      logmin = m_minPositiveValue;
+    }
+    m_scaleWidget->setScaleDiv(logScaler.transformation(),
+                               logScaler.divideScale(logmin, maxValue, 20, 5));
+  }
+}
+
+/**
+* Respond to a mouse press event. Start dragging to modify the range (min or max
+* value).
+*/
+void ColorMapWidget::mousePressEvent(QMouseEvent *e) {
+  QRect rect = m_scaleWidget->rect();
+  if (e->x() > rect.left() && e->x() < rect.right()) {
+    m_dragging = true;
+    m_y = e->y();
+    m_dtype = (m_y > height() / 2) ? Bottom : Top;
+    QApplication::setOverrideCursor(Qt::ClosedHandCursor);
+  }
+}
+
+/**
+* Respond to mouse move event. If the left button is down change the min or max.
+*/
+void ColorMapWidget::mouseMoveEvent(QMouseEvent *e) {
+  if (!m_dragging)
+    return;
+
+  double minValue = m_minValueBox->displayText().toDouble();
+  double maxValue = m_maxValueBox->displayText().toDouble();
+
+  if (m_dtype == Bottom) {
+    minValue += double(e->y() - m_y) / height() * (maxValue - minValue);
+    setMinValueText(minValue);
+  } else {
+    maxValue += double(e->y() - m_y) / height() * (maxValue - minValue);
+    setMaxValueText(maxValue);
+  }
+  m_y = e->y();
+  updateScale();
+}
+
+/**
+* Respond to a mouse release event. Finish all dragging.
+*/
+void ColorMapWidget::mouseReleaseEvent(QMouseEvent * /*e*/) {
+  if (!m_dragging)
+    return;
+  if (m_dtype == Bottom) {
+    minValueChanged();
+  } else {
+    maxValueChanged();
+  }
+  QApplication::restoreOverrideCursor();
+  m_dragging = false;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/CompAssemblyActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/CompAssemblyActor.cpp
index d1a0c8bbcbdf27fd9c254ff2ee5a9a1f942fdabd..eecd5f9f859324c03eb81ae0dcff4427951be124 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/CompAssemblyActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/CompAssemblyActor.cpp
@@ -30,223 +30,245 @@ using Mantid::Geometry::StructuredDetector;
 using Mantid::Geometry::IDetector;
 using Mantid::Geometry::Object;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* This is a constructor for CompAssembly Actor
-		* @param instrActor :: the current instrument actor
-		* @param compID :: the current component ID
-		*/
-		CompAssemblyActor::CompAssemblyActor(const InstrumentActor &instrActor, const Mantid::Geometry::ComponentID &compID)
-			: ICompAssemblyActor(instrActor, compID) {
-			boost::shared_ptr<const IComponent> CompPtr = getComponent();
-
-			//bounding box of the overall instrument
-			Mantid::Kernel::V3D minBound;
-			Mantid::Kernel::V3D maxBound;
-			//Iterate through CompAssembly children
-			boost::shared_ptr<const ICompAssembly> CompAssemPtr = boost::dynamic_pointer_cast<const ICompAssembly>(CompPtr);
-			if (CompAssemPtr != boost::shared_ptr<ICompAssembly>())
-			{
-				int nChild = CompAssemPtr->nelements();
-				for (int i = 0; i<nChild; i++)
-				{
-					boost::shared_ptr<IComponent> ChildCompPtr = (*CompAssemPtr)[i];
-					boost::shared_ptr<ICompAssembly> ChildCAPtr = boost::dynamic_pointer_cast<ICompAssembly>(ChildCompPtr);
-
-					//If the child is a CompAssembly then create a CompAssemblyActor for the child
-					if (ChildCAPtr)
-					{
-						boost::shared_ptr<ObjCompAssembly> ChildOCAPtr = boost::dynamic_pointer_cast<ObjCompAssembly>(ChildCompPtr);
-						boost::shared_ptr<RectangularDetector> ChildRDPtr = boost::dynamic_pointer_cast<RectangularDetector>(ChildCompPtr);
-						boost::shared_ptr<StructuredDetector> ChildSDPtr = boost::dynamic_pointer_cast<StructuredDetector>(ChildCompPtr);
-
-						if (ChildSDPtr)
-						{
-							StructuredDetectorActor *iActor = new StructuredDetectorActor(instrActor, ChildSDPtr->getComponentID());
-							iActor->getBoundingBox(minBound, maxBound);
-							AppendBoundingBox(minBound, maxBound);
-							mNumberOfDetectors += iActor->getNumberOfDetectors();
-							mChildCompAssemActors.push_back(iActor);
-						}
-						else if (ChildRDPtr)
-						{
-							//If the child is a RectangularDetector, then create a RectangularDetectorActor for it.
-							RectangularDetectorActor* iActor = new RectangularDetectorActor(instrActor, ChildCAPtr->getComponentID());
-							iActor->getBoundingBox(minBound, maxBound);
-							AppendBoundingBox(minBound, maxBound);
-							mNumberOfDetectors += iActor->getNumberOfDetectors();
-							mChildCompAssemActors.push_back(iActor);
-						}
-						else if (ChildOCAPtr)
-						{
-							ObjCompAssemblyActor* iActor =
-								new ObjCompAssemblyActor(instrActor, ChildCAPtr->getComponentID());
-							iActor->getBoundingBox(minBound, maxBound);
-							AppendBoundingBox(minBound, maxBound);
-							mNumberOfDetectors += iActor->getNumberOfDetectors();
-							mChildCompAssemActors.push_back(iActor);
-						}
-						else
-						{
-							CompAssemblyActor* iActor = new CompAssemblyActor(instrActor, ChildCAPtr->getComponentID());
-							iActor->getBoundingBox(minBound, maxBound);
-							AppendBoundingBox(minBound, maxBound);
-							mNumberOfDetectors += iActor->getNumberOfDetectors();
-							mChildCompAssemActors.push_back(iActor);
-						}
-					}
-					else //it has to be a ObjComponent child, create a ObjComponentActor for the child use the same display list attribute
-					{
-						boost::shared_ptr<Mantid::Geometry::IObjComponent> ChildObjPtr = boost::dynamic_pointer_cast<Mantid::Geometry::IObjComponent>(ChildCompPtr);
-						ObjComponentActor* iActor = new ObjComponentActor(instrActor, ChildCompPtr->getComponentID());
-						iActor->getBoundingBox(minBound, maxBound);
-						AppendBoundingBox(minBound, maxBound);
-						mChildObjCompActors.push_back(iActor);
-						mNumberOfDetectors++;
-					}
-				}
-			}
-		}
-
-		/**
-		* Destructor which removes the actors created by this object
-		*/
-		CompAssemblyActor::~CompAssemblyActor()
-		{
-			//Remove all the child CompAssembly Actors
-			for (std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin(); iAssem != mChildCompAssemActors.end(); ++iAssem)
-				delete (*iAssem);
-			mChildCompAssemActors.clear();
-			//Remove all the child ObjComponent Actors
-			for (std::vector<ObjComponentActor*>::iterator iObjComp = mChildObjCompActors.begin(); iObjComp != mChildObjCompActors.end(); ++iObjComp)
-				delete (*iObjComp);
-			mChildObjCompActors.clear();
-		}
-
-		/**
-		* This function is concrete implementation that renders the Child ObjComponents and Child CompAssembly's
-		*/
-		void CompAssemblyActor::draw(bool picking)const
-		{
-			OpenGLError::check("CompAssemblyActor::draw(0)");
-			//Only draw the CompAssembly Children only if they are visible
-			if (isVisible())
-			{
-				//Iterate through the ObjCompActor children and draw them
-				for (std::vector<ObjComponentActor*>::iterator itrObjComp = mChildObjCompActors.begin(); itrObjComp != mChildObjCompActors.end(); ++itrObjComp)
-				{
-					//Only draw the ObjCompActor if its visible
-					if ((*itrObjComp)->isVisible())
-					{
-						//std::cout << (*itrObjComp)->getName() << " is gonna draw. From define()\n";
-						(*itrObjComp)->draw(picking);
-						OpenGLError::check("draw " + (*itrObjComp)->getComponent()->getName());
-					}
-					else
-					{
-						//std::cout << (*itrObjComp)->getName() << " is not visible\n";
-					}
-				}
-				//Iterate through the CompAssemblyActor children and draw them
-				for (std::vector<ICompAssemblyActor*>::iterator itrObjAssem = mChildCompAssemActors.begin(); itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem)
-				{
-					if ((*itrObjAssem)->isVisible())
-					{
-						//std::cout << (*itrObjAssem)->getName() << " is gonna draw. From define()\n";
-						(*itrObjAssem)->draw(picking);
-					}
-				}
-			}
-			else
-			{
-				//std::cout << this->getName() << " is not visible\n";
-			}
-			OpenGLError::check("CompAssemblyActor::draw()");
-		}
-
-		bool CompAssemblyActor::accept(GLActorVisitor& visitor, VisitorAcceptRule rule)
-		{
-			for (std::vector<ObjComponentActor*>::iterator itrObjComp = mChildObjCompActors.begin(); itrObjComp != mChildObjCompActors.end(); ++itrObjComp)
-			{
-				if ((**itrObjComp).accept(visitor, rule) && rule == Finish) return true;
-			}
-			for (std::vector<ICompAssemblyActor*>::iterator itrObjAssem = mChildCompAssemActors.begin(); itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem)
-			{
-				if ((**itrObjAssem).accept(visitor, rule) && rule == Finish) return true;
-			}
-			return visitor.visit(this);
-		}
-
-		bool CompAssemblyActor::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule rule) const
-		{
-			for (std::vector<ObjComponentActor*>::iterator itrObjComp = mChildObjCompActors.begin(); itrObjComp != mChildObjCompActors.end(); ++itrObjComp)
-			{
-				if ((**itrObjComp).accept(visitor, rule) && rule == Finish) return true;
-			}
-			for (std::vector<ICompAssemblyActor*>::iterator itrObjAssem = mChildCompAssemActors.begin(); itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem)
-			{
-				if ((**itrObjAssem).accept(visitor, rule) && rule == Finish) return true;
-			}
-			return visitor.visit(this);
-		}
-
-		//------------------------------------------------------------------------------------------------
-		/**
-		* Append the bounding box CompAssembly bounding box
-		* @param minBound :: min point of the bounding box
-		* @param maxBound :: max point of the bounding box
-		*/
-		void CompAssemblyActor::AppendBoundingBox(const Mantid::Kernel::V3D& minBound, const Mantid::Kernel::V3D& maxBound)
-		{
-			if (minBoundBox[0]>minBound[0]) minBoundBox[0] = minBound[0];
-			if (minBoundBox[1]>minBound[1]) minBoundBox[1] = minBound[1];
-			if (minBoundBox[2]>minBound[2]) minBoundBox[2] = minBound[2];
-			if (maxBoundBox[0]<maxBound[0]) maxBoundBox[0] = maxBound[0];
-			if (maxBoundBox[1]<maxBound[1]) maxBoundBox[1] = maxBound[1];
-			if (maxBoundBox[2]<maxBound[2]) maxBoundBox[2] = maxBound[2];
-		}
-
-		void CompAssemblyActor::setColors()
-		{
-			for (std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin(); iAssem != mChildCompAssemActors.end(); ++iAssem)
-			{
-				(**iAssem).setColors();
-			}
-			for (std::vector<ObjComponentActor*>::iterator iObjComp = mChildObjCompActors.begin(); iObjComp != mChildObjCompActors.end(); ++iObjComp)
-			{
-				(**iObjComp).setColors();
-			}
-		}
-
-		void CompAssemblyActor::setChildVisibility(bool on)
-		{
-			GLActor::setVisibility(on);
-			for (std::vector<ObjComponentActor*>::iterator itrObjComp = mChildObjCompActors.begin(); itrObjComp != mChildObjCompActors.end(); ++itrObjComp)
-			{
-				(**itrObjComp).setVisibility(on);
-			}
-			for (std::vector<ICompAssemblyActor*>::iterator itrObjAssem = mChildCompAssemActors.begin(); itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem)
-			{
-				(**itrObjAssem).setChildVisibility(on);
-			}
-		}
-
-		bool CompAssemblyActor::hasChildVisible() const
-		{
-			for (std::vector<ObjComponentActor*>::iterator itrObjComp = mChildObjCompActors.begin(); itrObjComp != mChildObjCompActors.end(); ++itrObjComp)
-			{
-				if ((**itrObjComp).isVisible()) return true;
-			}
-			for (std::vector<ICompAssemblyActor*>::iterator itrObjAssem = mChildCompAssemActors.begin(); itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem)
-			{
-				if ((**itrObjAssem).hasChildVisible()) return true;
-			}
-			return false;
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* This is a constructor for CompAssembly Actor
+* @param instrActor :: the current instrument actor
+* @param compID :: the current component ID
+*/
+CompAssemblyActor::CompAssemblyActor(
+    const InstrumentActor &instrActor,
+    const Mantid::Geometry::ComponentID &compID)
+    : ICompAssemblyActor(instrActor, compID) {
+  boost::shared_ptr<const IComponent> CompPtr = getComponent();
+
+  // bounding box of the overall instrument
+  Mantid::Kernel::V3D minBound;
+  Mantid::Kernel::V3D maxBound;
+  // Iterate through CompAssembly children
+  boost::shared_ptr<const ICompAssembly> CompAssemPtr =
+      boost::dynamic_pointer_cast<const ICompAssembly>(CompPtr);
+  if (CompAssemPtr != boost::shared_ptr<ICompAssembly>()) {
+    int nChild = CompAssemPtr->nelements();
+    for (int i = 0; i < nChild; i++) {
+      boost::shared_ptr<IComponent> ChildCompPtr = (*CompAssemPtr)[i];
+      boost::shared_ptr<ICompAssembly> ChildCAPtr =
+          boost::dynamic_pointer_cast<ICompAssembly>(ChildCompPtr);
+
+      // If the child is a CompAssembly then create a CompAssemblyActor for the
+      // child
+      if (ChildCAPtr) {
+        boost::shared_ptr<ObjCompAssembly> ChildOCAPtr =
+            boost::dynamic_pointer_cast<ObjCompAssembly>(ChildCompPtr);
+        boost::shared_ptr<RectangularDetector> ChildRDPtr =
+            boost::dynamic_pointer_cast<RectangularDetector>(ChildCompPtr);
+        boost::shared_ptr<StructuredDetector> ChildSDPtr =
+            boost::dynamic_pointer_cast<StructuredDetector>(ChildCompPtr);
+
+        if (ChildSDPtr) {
+          StructuredDetectorActor *iActor = new StructuredDetectorActor(
+              instrActor, ChildSDPtr->getComponentID());
+          iActor->getBoundingBox(minBound, maxBound);
+          AppendBoundingBox(minBound, maxBound);
+          mNumberOfDetectors += iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        } else if (ChildRDPtr) {
+          // If the child is a RectangularDetector, then create a
+          // RectangularDetectorActor for it.
+          RectangularDetectorActor *iActor = new RectangularDetectorActor(
+              instrActor, ChildCAPtr->getComponentID());
+          iActor->getBoundingBox(minBound, maxBound);
+          AppendBoundingBox(minBound, maxBound);
+          mNumberOfDetectors += iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        } else if (ChildOCAPtr) {
+          ObjCompAssemblyActor *iActor = new ObjCompAssemblyActor(
+              instrActor, ChildCAPtr->getComponentID());
+          iActor->getBoundingBox(minBound, maxBound);
+          AppendBoundingBox(minBound, maxBound);
+          mNumberOfDetectors += iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        } else {
+          CompAssemblyActor *iActor =
+              new CompAssemblyActor(instrActor, ChildCAPtr->getComponentID());
+          iActor->getBoundingBox(minBound, maxBound);
+          AppendBoundingBox(minBound, maxBound);
+          mNumberOfDetectors += iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        }
+      } else // it has to be a ObjComponent child, create a ObjComponentActor
+             // for the child use the same display list attribute
+      {
+        boost::shared_ptr<Mantid::Geometry::IObjComponent> ChildObjPtr =
+            boost::dynamic_pointer_cast<Mantid::Geometry::IObjComponent>(
+                ChildCompPtr);
+        ObjComponentActor *iActor =
+            new ObjComponentActor(instrActor, ChildCompPtr->getComponentID());
+        iActor->getBoundingBox(minBound, maxBound);
+        AppendBoundingBox(minBound, maxBound);
+        mChildObjCompActors.push_back(iActor);
+        mNumberOfDetectors++;
+      }
+    }
+  }
+}
+
+/**
+* Destructor which removes the actors created by this object
+*/
+CompAssemblyActor::~CompAssemblyActor() {
+  // Remove all the child CompAssembly Actors
+  for (std::vector<ICompAssemblyActor *>::iterator iAssem =
+           mChildCompAssemActors.begin();
+       iAssem != mChildCompAssemActors.end(); ++iAssem)
+    delete (*iAssem);
+  mChildCompAssemActors.clear();
+  // Remove all the child ObjComponent Actors
+  for (std::vector<ObjComponentActor *>::iterator iObjComp =
+           mChildObjCompActors.begin();
+       iObjComp != mChildObjCompActors.end(); ++iObjComp)
+    delete (*iObjComp);
+  mChildObjCompActors.clear();
+}
+
+/**
+* This function is concrete implementation that renders the Child ObjComponents
+* and Child CompAssembly's
+*/
+void CompAssemblyActor::draw(bool picking) const {
+  OpenGLError::check("CompAssemblyActor::draw(0)");
+  // Only draw the CompAssembly Children only if they are visible
+  if (isVisible()) {
+    // Iterate through the ObjCompActor children and draw them
+    for (std::vector<ObjComponentActor *>::iterator itrObjComp =
+             mChildObjCompActors.begin();
+         itrObjComp != mChildObjCompActors.end(); ++itrObjComp) {
+      // Only draw the ObjCompActor if its visible
+      if ((*itrObjComp)->isVisible()) {
+        // std::cout << (*itrObjComp)->getName() << " is gonna draw. From
+        // define()\n";
+        (*itrObjComp)->draw(picking);
+        OpenGLError::check("draw " + (*itrObjComp)->getComponent()->getName());
+      } else {
+        // std::cout << (*itrObjComp)->getName() << " is not visible\n";
+      }
+    }
+    // Iterate through the CompAssemblyActor children and draw them
+    for (std::vector<ICompAssemblyActor *>::iterator itrObjAssem =
+             mChildCompAssemActors.begin();
+         itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem) {
+      if ((*itrObjAssem)->isVisible()) {
+        // std::cout << (*itrObjAssem)->getName() << " is gonna draw. From
+        // define()\n";
+        (*itrObjAssem)->draw(picking);
+      }
+    }
+  } else {
+    // std::cout << this->getName() << " is not visible\n";
+  }
+  OpenGLError::check("CompAssemblyActor::draw()");
+}
+
+bool CompAssemblyActor::accept(GLActorVisitor &visitor,
+                               VisitorAcceptRule rule) {
+  for (std::vector<ObjComponentActor *>::iterator itrObjComp =
+           mChildObjCompActors.begin();
+       itrObjComp != mChildObjCompActors.end(); ++itrObjComp) {
+    if ((**itrObjComp).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  for (std::vector<ICompAssemblyActor *>::iterator itrObjAssem =
+           mChildCompAssemActors.begin();
+       itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem) {
+    if ((**itrObjAssem).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  return visitor.visit(this);
+}
+
+bool CompAssemblyActor::accept(GLActorConstVisitor &visitor,
+                               GLActor::VisitorAcceptRule rule) const {
+  for (std::vector<ObjComponentActor *>::iterator itrObjComp =
+           mChildObjCompActors.begin();
+       itrObjComp != mChildObjCompActors.end(); ++itrObjComp) {
+    if ((**itrObjComp).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  for (std::vector<ICompAssemblyActor *>::iterator itrObjAssem =
+           mChildCompAssemActors.begin();
+       itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem) {
+    if ((**itrObjAssem).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  return visitor.visit(this);
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+* Append the bounding box CompAssembly bounding box
+* @param minBound :: min point of the bounding box
+* @param maxBound :: max point of the bounding box
+*/
+void CompAssemblyActor::AppendBoundingBox(const Mantid::Kernel::V3D &minBound,
+                                          const Mantid::Kernel::V3D &maxBound) {
+  if (minBoundBox[0] > minBound[0])
+    minBoundBox[0] = minBound[0];
+  if (minBoundBox[1] > minBound[1])
+    minBoundBox[1] = minBound[1];
+  if (minBoundBox[2] > minBound[2])
+    minBoundBox[2] = minBound[2];
+  if (maxBoundBox[0] < maxBound[0])
+    maxBoundBox[0] = maxBound[0];
+  if (maxBoundBox[1] < maxBound[1])
+    maxBoundBox[1] = maxBound[1];
+  if (maxBoundBox[2] < maxBound[2])
+    maxBoundBox[2] = maxBound[2];
+}
+
+void CompAssemblyActor::setColors() {
+  for (std::vector<ICompAssemblyActor *>::iterator iAssem =
+           mChildCompAssemActors.begin();
+       iAssem != mChildCompAssemActors.end(); ++iAssem) {
+    (**iAssem).setColors();
+  }
+  for (std::vector<ObjComponentActor *>::iterator iObjComp =
+           mChildObjCompActors.begin();
+       iObjComp != mChildObjCompActors.end(); ++iObjComp) {
+    (**iObjComp).setColors();
+  }
+}
+
+void CompAssemblyActor::setChildVisibility(bool on) {
+  GLActor::setVisibility(on);
+  for (std::vector<ObjComponentActor *>::iterator itrObjComp =
+           mChildObjCompActors.begin();
+       itrObjComp != mChildObjCompActors.end(); ++itrObjComp) {
+    (**itrObjComp).setVisibility(on);
+  }
+  for (std::vector<ICompAssemblyActor *>::iterator itrObjAssem =
+           mChildCompAssemActors.begin();
+       itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem) {
+    (**itrObjAssem).setChildVisibility(on);
+  }
+}
+
+bool CompAssemblyActor::hasChildVisible() const {
+  for (std::vector<ObjComponentActor *>::iterator itrObjComp =
+           mChildObjCompActors.begin();
+       itrObjComp != mChildObjCompActors.end(); ++itrObjComp) {
+    if ((**itrObjComp).isVisible())
+      return true;
+  }
+  for (std::vector<ICompAssemblyActor *>::iterator itrObjAssem =
+           mChildCompAssemActors.begin();
+       itrObjAssem != mChildCompAssemActors.end(); ++itrObjAssem) {
+    if ((**itrObjAssem).hasChildVisible())
+      return true;
+  }
+  return false;
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ComponentActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ComponentActor.cpp
index 8833a92a60f78f3eee9e140e47db0837cb0f061e..b8c72ea6b20c4be943e18f7ff7256583410ceb5e 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ComponentActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ComponentActor.cpp
@@ -11,62 +11,66 @@
 using namespace Mantid;
 using namespace Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		ComponentActor::ComponentActor(const InstrumentActor &instrActor, const Mantid::Geometry::ComponentID &compID)
-			: GLActor(), m_instrActor(instrActor), m_id(compID) {}
+namespace MantidQt {
+namespace MantidWidgets {
+ComponentActor::ComponentActor(const InstrumentActor &instrActor,
+                               const Mantid::Geometry::ComponentID &compID)
+    : GLActor(), m_instrActor(instrActor), m_id(compID) {}
 
-		bool ComponentActor::accept(GLActorVisitor &visitor, GLActor::VisitorAcceptRule)
-		{
-			return visitor.visit(this);
-		}
+bool ComponentActor::accept(GLActorVisitor &visitor,
+                            GLActor::VisitorAcceptRule) {
+  return visitor.visit(this);
+}
 
-		bool ComponentActor::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule) const
-		{
-			return visitor.visit(this);
-		}
+bool ComponentActor::accept(GLActorConstVisitor &visitor,
+                            GLActor::VisitorAcceptRule) const {
+  return visitor.visit(this);
+}
 
-		boost::shared_ptr<const Mantid::Geometry::IComponent> ComponentActor::getComponent() const
-		{
-			return m_instrActor.getInstrument()->getComponentByID(m_id);
-		}
+boost::shared_ptr<const Mantid::Geometry::IComponent>
+ComponentActor::getComponent() const {
+  return m_instrActor.getInstrument()->getComponentByID(m_id);
+}
 
-		boost::shared_ptr<const Mantid::Geometry::IObjComponent> ComponentActor::getObjComponent() const
-		{
-			return boost::dynamic_pointer_cast<const Mantid::Geometry::IObjComponent>(getComponent());
-		}
+boost::shared_ptr<const Mantid::Geometry::IObjComponent>
+ComponentActor::getObjComponent() const {
+  return boost::dynamic_pointer_cast<const Mantid::Geometry::IObjComponent>(
+      getComponent());
+}
 
-		boost::shared_ptr<const Mantid::Geometry::IDetector> ComponentActor::getDetector() const
-		{
-			return boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector>(getComponent());
-		}
+boost::shared_ptr<const Mantid::Geometry::IDetector>
+ComponentActor::getDetector() const {
+  return boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector>(
+      getComponent());
+}
 
-		boost::shared_ptr<const Mantid::Geometry::ObjCompAssembly> ComponentActor::getObjCompAssembly() const
-		{
-			return boost::dynamic_pointer_cast<const Mantid::Geometry::ObjCompAssembly>(getComponent());
-		}
+boost::shared_ptr<const Mantid::Geometry::ObjCompAssembly>
+ComponentActor::getObjCompAssembly() const {
+  return boost::dynamic_pointer_cast<const Mantid::Geometry::ObjCompAssembly>(
+      getComponent());
+}
 
-		boost::shared_ptr<const Mantid::Geometry::CompAssembly> ComponentActor::getCompAssembly() const
-		{
-			return boost::dynamic_pointer_cast<const Mantid::Geometry::CompAssembly>(getComponent());
-		}
+boost::shared_ptr<const Mantid::Geometry::CompAssembly>
+ComponentActor::getCompAssembly() const {
+  return boost::dynamic_pointer_cast<const Mantid::Geometry::CompAssembly>(
+      getComponent());
+}
 
-		/**
-		* A component is a non-detector if it's an ObjComponent (has a shape) and not an ObjCompAssembly
-		* (a single object) and not a RectangularDetector (which is an assembly) or a StructuredDetector
-		(which is an assembly).
-		*/
-		bool ComponentActor::isNonDetector() const
-		{
-			auto obj = getObjComponent();
-			return  obj &&
-				!getObjCompAssembly() &&
-				!getDetector() &&
-				!boost::dynamic_pointer_cast<const Mantid::Geometry::RectangularDetector>(obj) &&
-				!boost::dynamic_pointer_cast<const Mantid::Geometry::StructuredDetector>(obj);
-		}
+/**
+* A component is a non-detector if it's an ObjComponent (has a shape) and not an
+ObjCompAssembly
+* (a single object) and not a RectangularDetector (which is an assembly) or a
+StructuredDetector
+(which is an assembly).
+*/
+bool ComponentActor::isNonDetector() const {
+  auto obj = getObjComponent();
+  return obj && !getObjCompAssembly() && !getDetector() &&
+         !boost::dynamic_pointer_cast<
+             const Mantid::Geometry::RectangularDetector>(obj) &&
+         !boost::dynamic_pointer_cast<
+             const Mantid::Geometry::StructuredDetector>(obj);
+}
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/DetXMLFile.cpp b/MantidQt/MantidWidgets/src/InstrumentView/DetXMLFile.cpp
index 42c7b77c5b4145857aafca04f5dd3e15f1707cfc..99d022ceba938b9b29467462de98164ec8868dea 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/DetXMLFile.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/DetXMLFile.cpp
@@ -5,107 +5,97 @@
 
 #include <fstream>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* Create a grouping file to extract all detectors in detector_list excluding those in exclude.
-		* @param detector_list :: List of detector ids to include in the grouping file.
-		* @param exclude :: List of detector ids which if founfd in detector_list to be excluded from grouping.
-		* @param fname :: Name of the file to save the grouping to.
-		*/
-		DetXMLFile::DetXMLFile(const std::vector<int>& detector_list, const QList<int>& exclude, const QString& fname)
-		{
-			m_fileName = fname;
-			m_delete = false;
-			std::ofstream out(m_fileName.toStdString().c_str());
-			out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
-			out << "<group name=\"sum\"> <detids val=\"";
-			std::vector<int>::const_iterator idet = detector_list.begin();
-			for (; idet != detector_list.end(); ++idet)
-			{
-				if (!exclude.contains(*idet))
-				{
-					out << *idet << ',';
-				}
-			}
-			out << "\"/> </group> \n</detector-grouping>\n";
-		}
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* Create a grouping file to extract all detectors in detector_list excluding
+* those in exclude.
+* @param detector_list :: List of detector ids to include in the grouping file.
+* @param exclude :: List of detector ids which if founfd in detector_list to be
+* excluded from grouping.
+* @param fname :: Name of the file to save the grouping to.
+*/
+DetXMLFile::DetXMLFile(const std::vector<int> &detector_list,
+                       const QList<int> &exclude, const QString &fname) {
+  m_fileName = fname;
+  m_delete = false;
+  std::ofstream out(m_fileName.toStdString().c_str());
+  out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
+  out << "<group name=\"sum\"> <detids val=\"";
+  std::vector<int>::const_iterator idet = detector_list.begin();
+  for (; idet != detector_list.end(); ++idet) {
+    if (!exclude.contains(*idet)) {
+      out << *idet << ',';
+    }
+  }
+  out << "\"/> </group> \n</detector-grouping>\n";
+}
 
-		/**
-		* Create a grouping file to extract detectors in dets. Option List - one group - one detector,
-		* Option Sum - one group which is a sum of the detectors
-		* If fname is empty create a temporary file
-		*/
-		DetXMLFile::DetXMLFile(const QList<int>& dets, Option opt, const QString& fname)
-		{
-			if (dets.empty())
-			{
-				m_fileName = "";
-				m_delete = false;
-				return;
-			}
+/**
+* Create a grouping file to extract detectors in dets. Option List - one group -
+* one detector,
+* Option Sum - one group which is a sum of the detectors
+* If fname is empty create a temporary file
+*/
+DetXMLFile::DetXMLFile(const QList<int> &dets, Option opt,
+                       const QString &fname) {
+  if (dets.empty()) {
+    m_fileName = "";
+    m_delete = false;
+    return;
+  }
 
-			if (fname.isEmpty())
-			{
-				QTemporaryFile mapFile;
-				mapFile.open();
-				m_fileName = mapFile.fileName() + ".xml";
-				mapFile.close();
-				m_delete = true;
-			}
-			else
-			{
-				m_fileName = fname;
-				m_delete = false;
-			}
+  if (fname.isEmpty()) {
+    QTemporaryFile mapFile;
+    mapFile.open();
+    m_fileName = mapFile.fileName() + ".xml";
+    mapFile.close();
+    m_delete = true;
+  } else {
+    m_fileName = fname;
+    m_delete = false;
+  }
 
-			switch (opt)
-			{
-			case Sum: makeSumFile(dets); break;
-			case List: makeListFile(dets); break;
-			}
-		}
+  switch (opt) {
+  case Sum:
+    makeSumFile(dets);
+    break;
+  case List:
+    makeListFile(dets);
+    break;
+  }
+}
 
-		/// Make grouping file where each detector is put into its own group
-		void DetXMLFile::makeListFile(const QList<int>& dets)
-		{
-			std::ofstream out(m_fileName.toStdString().c_str());
-			out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
-			foreach(int det, dets)
-			{
-				out << "<group name=\"" << det << "\"> <detids val=\"" << det << "\"/> </group> \n";
-			}
-			out << "</detector-grouping>\n";
-		}
+/// Make grouping file where each detector is put into its own group
+void DetXMLFile::makeListFile(const QList<int> &dets) {
+  std::ofstream out(m_fileName.toStdString().c_str());
+  out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
+  foreach (int det, dets) {
+    out << "<group name=\"" << det << "\"> <detids val=\"" << det
+        << "\"/> </group> \n";
+  }
+  out << "</detector-grouping>\n";
+}
 
-		/// Make grouping file for putting the detectors into one group (summing the detectors)
-		void DetXMLFile::makeSumFile(const QList<int>& dets)
-		{
-			std::ofstream out(m_fileName.toStdString().c_str());
-			out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
-			out << "<group name=\"sum\"> <detids val=\"";
-			foreach(int det, dets)
-			{
-				out << det << ',';
-			}
-			out << "\"/> </group> \n</detector-grouping>\n";
-		}
+/// Make grouping file for putting the detectors into one group (summing the
+/// detectors)
+void DetXMLFile::makeSumFile(const QList<int> &dets) {
+  std::ofstream out(m_fileName.toStdString().c_str());
+  out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<detector-grouping> \n";
+  out << "<group name=\"sum\"> <detids val=\"";
+  foreach (int det, dets) { out << det << ','; }
+  out << "\"/> </group> \n</detector-grouping>\n";
+}
 
-		/**
-		* Destructor. Removes the temporary file.
-		*/
-		DetXMLFile::~DetXMLFile()
-		{
-			if (m_delete)
-			{
-				QDir dir;
-				dir.remove(m_fileName);
-			}
-		}
-
-
-	}//MantidWidgets
-}//MantidQt
+/**
+* Destructor. Removes the temporary file.
+*/
+DetXMLFile::~DetXMLFile() {
+  if (m_delete) {
+    QDir dir;
+    dir.remove(m_fileName);
+  }
+}
 
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/GLActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/GLActor.cpp
index 21949aed1c9ffc626dfb56556611803fe0e869ac..e66944a765eb7ce5b4feb39908d18682d18aba1e 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/GLActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/GLActor.cpp
@@ -1,54 +1,44 @@
 #include "MantidQtMantidWidgets/InstrumentView/GLActor.h"
 #include "MantidQtMantidWidgets/InstrumentView/GLActorVisitor.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		GLActor::~GLActor()
-		{
-		}
-
-		bool GLActor::accept(GLActorVisitor& visitor, VisitorAcceptRule)
-		{
-			return visitor.visit(this);
-		}
-
-		bool GLActor::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule) const
-		{
-			return visitor.visit(this);
-		}
-
-		GLColor GLActor::makePickColor(size_t pickID)
-		{
-			pickID += 1;
-			unsigned char r, g, b;
-			r = (unsigned char)(pickID / 65536);
-			g = (unsigned char)((pickID % 65536) / 256);
-			b = (unsigned char)((pickID % 65536) % 256);
-			return GLColor(r, g, b);
-		}
-
-		size_t GLActor::decodePickColor(const QRgb& c)
-		{
-			return decodePickColor((unsigned char)qRed(c), (unsigned char)qGreen(c), (unsigned char)qBlue(c));
-		}
-
-		size_t GLActor::decodePickColor(unsigned char r, unsigned char g, unsigned char b)
-		{
-			unsigned int index = r;
-			index *= 256;
-			index += g;
-			index *= 256;
-			index += b - 1;
-			return index;
-		}
-
-		GLColor GLActor::defaultDetectorColor()
-		{
-			return GLColor(200, 200, 200);
-		}
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+GLActor::~GLActor() {}
+
+bool GLActor::accept(GLActorVisitor &visitor, VisitorAcceptRule) {
+  return visitor.visit(this);
+}
+
+bool GLActor::accept(GLActorConstVisitor &visitor,
+                     GLActor::VisitorAcceptRule) const {
+  return visitor.visit(this);
+}
+
+GLColor GLActor::makePickColor(size_t pickID) {
+  pickID += 1;
+  unsigned char r, g, b;
+  r = (unsigned char)(pickID / 65536);
+  g = (unsigned char)((pickID % 65536) / 256);
+  b = (unsigned char)((pickID % 65536) % 256);
+  return GLColor(r, g, b);
+}
+
+size_t GLActor::decodePickColor(const QRgb &c) {
+  return decodePickColor((unsigned char)qRed(c), (unsigned char)qGreen(c),
+                         (unsigned char)qBlue(c));
+}
+
+size_t GLActor::decodePickColor(unsigned char r, unsigned char g,
+                                unsigned char b) {
+  unsigned int index = r;
+  index *= 256;
+  index += g;
+  index *= 256;
+  index += b - 1;
+  return index;
+}
+
+GLColor GLActor::defaultDetectorColor() { return GLColor(200, 200, 200); }
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/GLActorCollection.cpp b/MantidQt/MantidWidgets/src/InstrumentView/GLActorCollection.cpp
index f3c33b319e560a3565941d97bb2dc361fe770034..084f655910b40b85a5c1e7d7cb613893745d8301 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/GLActorCollection.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/GLActorCollection.cpp
@@ -9,183 +9,170 @@
 #include <algorithm>
 #include <float.h>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		GLActorCollection::GLActorCollection()
-			:GLActor(),
-			m_minBound(DBL_MAX, DBL_MAX, DBL_MAX),
-			m_maxBound(-DBL_MAX, -DBL_MAX, -DBL_MAX)
-		{
-			m_displayListId[0] = 0;
-			m_displayListId[1] = 0;
-			m_useDisplayList[0] = false;
-			m_useDisplayList[1] = false;
-		}
-
-		GLActorCollection::~GLActorCollection()
-		{
-			for (std::vector<GLActor*>::iterator i = mActorsList.begin(); i != mActorsList.end(); ++i)
-			{
-				delete (*i);
-			}
-			mActorsList.clear();
-			for (size_t i = 0; i < 2; ++i)
-			{
-				if (m_displayListId[i] != 0)
-				{
-					glDeleteLists(m_displayListId[i], 1);
-				}
-			}
-
-		}
-
-		/**
-		* This method does the drawing by calling the list of actors to draw themselfs
-		*/
-		void GLActorCollection::draw(bool picking)const
-		{
-			if (!isVisible()) return;
-			OpenGLError::check("GLActorCollection::draw(0)");
-			size_t i = picking ? 1 : 0;
-			if (m_useDisplayList[i])
-			{
-				glCallList(m_displayListId[i]);
-			}
-			else if (m_displayListId[i] == 0)
-			{
-				m_displayListId[i] = glGenLists(1);
-				// child actors can also create display lists, so delay
-				// until all the children have finished making theirs
-				drawGL(picking);
-			}
-			else
-			{
-				m_useDisplayList[i] = true;
-				glNewList(m_displayListId[i], GL_COMPILE); //Construct display list for object representation
-				drawGL(picking);
-				glEndList();
-				if (glGetError() == GL_OUT_OF_MEMORY) //Throw an exception
-					throw Mantid::Kernel::Exception::OpenGLError("OpenGL: Out of video memory");
-				glCallList(m_displayListId[i]);
-			}
-			OpenGLError::check("GLActorCollection::draw()");
-		}
-
-		void GLActorCollection::drawGL(bool picking)const
-		{
-			for (std::vector<GLActor*>::const_iterator it = mActorsList.begin(); it != mActorsList.end(); ++it)
-			{
-				(**it).draw(picking);
-			}
-		}
-
-		bool GLActorCollection::accept(GLActorVisitor& visitor, VisitorAcceptRule rule)
-		{
-			for (std::vector<GLActor*>::const_iterator it = mActorsList.begin(); it != mActorsList.end(); ++it)
-			{
-				if ((**it).accept(visitor, rule) && rule == Finish) return true;
-			}
-			return visitor.visit(this);
-		}
-
-		bool GLActorCollection::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule rule) const
-		{
-			for (std::vector<GLActor*>::const_iterator it = mActorsList.begin(); it != mActorsList.end(); ++it)
-			{
-				if ((**it).accept(visitor, rule) && rule == Finish) return true;
-			}
-			return visitor.visit(this);
-		}
-
-		/**
-		* This method addes a new actor to the collection.
-		* @param a :: input actor to be added to the list
-		*/
-		void GLActorCollection::addActor(GLActor* a)
-		{
-			if (!a)
-			{
-				return;
-			}
-			mActorsList.push_back(a);
-			Mantid::Kernel::V3D minBound;
-			Mantid::Kernel::V3D maxBound;
-			a->getBoundingBox(minBound, maxBound);
-			if (m_minBound[0]>minBound[0]) m_minBound[0] = minBound[0];
-			if (m_minBound[1]>minBound[1]) m_minBound[1] = minBound[1];
-			if (m_minBound[2]>minBound[2]) m_minBound[2] = minBound[2];
-			if (m_maxBound[0]<maxBound[0]) m_maxBound[0] = maxBound[0];
-			if (m_maxBound[1]<maxBound[1]) m_maxBound[1] = maxBound[1];
-			if (m_maxBound[2]<maxBound[2]) m_maxBound[2] = maxBound[2];
-		}
-
-		/**
-		* Remove the input actor from the collection
-		* @param :: input actor to be removed from the list
-		*/
-		void GLActorCollection::removeActor(GLActor*)
-		{
-			throw std::runtime_error("Removing actor not implemented");
-		}
-
-		/**
-		* This method returns the number of actors in the collection
-		* @return integer value of number of actors in collection
-		*/
-		int  GLActorCollection::getNumberOfActors()
-		{
-			return static_cast<int>(mActorsList.size());
-		}
-
-		/**
-		* This method returns the actor at the given index
-		* @param index :: is the index in actor collection to be returned
-		* @return a pointer to the actor at a given index
-		*/
-		GLActor* GLActorCollection::getActor(int index)
-		{
-			if (index<0 || index> static_cast<int>(mActorsList.size()))return NULL;
-			return mActorsList.at(index);
-		}
-
-		void GLActorCollection::getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const
-		{
-			minBound = m_minBound;
-			maxBound = m_maxBound;
-		}
-
-		void GLActorCollection::invalidateDisplayList()const
-		{
-			for (size_t i = 0; i < 2; ++i)
-			{
-				if (m_displayListId[i] != 0)
-				{
-					glDeleteLists(m_displayListId[i], 1);
-					m_displayListId[i] = 0;
-					m_useDisplayList[i] = false;
-				}
-			}
-		}
-
-		void GLActorCollection::setChildVisibility(bool on)
-		{
-			GLActor::setVisibility(on);
-			for (std::vector<GLActor*>::const_iterator it = mActorsList.begin(); it != mActorsList.end(); ++it)
-			{
-				(**it).setChildVisibility(on);
-			}
-		}
-
-		bool GLActorCollection::hasChildVisible() const
-		{
-			for (std::vector<GLActor*>::const_iterator it = mActorsList.begin(); it != mActorsList.end(); ++it)
-			{
-				if ((**it).hasChildVisible()) return true;
-			}
-			return false;
-		}
-	}
+namespace MantidQt {
+namespace MantidWidgets {
+GLActorCollection::GLActorCollection()
+    : GLActor(), m_minBound(DBL_MAX, DBL_MAX, DBL_MAX),
+      m_maxBound(-DBL_MAX, -DBL_MAX, -DBL_MAX) {
+  m_displayListId[0] = 0;
+  m_displayListId[1] = 0;
+  m_useDisplayList[0] = false;
+  m_useDisplayList[1] = false;
 }
 
+GLActorCollection::~GLActorCollection() {
+  for (std::vector<GLActor *>::iterator i = mActorsList.begin();
+       i != mActorsList.end(); ++i) {
+    delete (*i);
+  }
+  mActorsList.clear();
+  for (size_t i = 0; i < 2; ++i) {
+    if (m_displayListId[i] != 0) {
+      glDeleteLists(m_displayListId[i], 1);
+    }
+  }
+}
+
+/**
+* This method does the drawing by calling the list of actors to draw themselfs
+*/
+void GLActorCollection::draw(bool picking) const {
+  if (!isVisible())
+    return;
+  OpenGLError::check("GLActorCollection::draw(0)");
+  size_t i = picking ? 1 : 0;
+  if (m_useDisplayList[i]) {
+    glCallList(m_displayListId[i]);
+  } else if (m_displayListId[i] == 0) {
+    m_displayListId[i] = glGenLists(1);
+    // child actors can also create display lists, so delay
+    // until all the children have finished making theirs
+    drawGL(picking);
+  } else {
+    m_useDisplayList[i] = true;
+    glNewList(m_displayListId[i],
+              GL_COMPILE); // Construct display list for object representation
+    drawGL(picking);
+    glEndList();
+    if (glGetError() == GL_OUT_OF_MEMORY) // Throw an exception
+      throw Mantid::Kernel::Exception::OpenGLError(
+          "OpenGL: Out of video memory");
+    glCallList(m_displayListId[i]);
+  }
+  OpenGLError::check("GLActorCollection::draw()");
+}
+
+void GLActorCollection::drawGL(bool picking) const {
+  for (std::vector<GLActor *>::const_iterator it = mActorsList.begin();
+       it != mActorsList.end(); ++it) {
+    (**it).draw(picking);
+  }
+}
+
+bool GLActorCollection::accept(GLActorVisitor &visitor,
+                               VisitorAcceptRule rule) {
+  for (std::vector<GLActor *>::const_iterator it = mActorsList.begin();
+       it != mActorsList.end(); ++it) {
+    if ((**it).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  return visitor.visit(this);
+}
+
+bool GLActorCollection::accept(GLActorConstVisitor &visitor,
+                               GLActor::VisitorAcceptRule rule) const {
+  for (std::vector<GLActor *>::const_iterator it = mActorsList.begin();
+       it != mActorsList.end(); ++it) {
+    if ((**it).accept(visitor, rule) && rule == Finish)
+      return true;
+  }
+  return visitor.visit(this);
+}
+
+/**
+* This method addes a new actor to the collection.
+* @param a :: input actor to be added to the list
+*/
+void GLActorCollection::addActor(GLActor *a) {
+  if (!a) {
+    return;
+  }
+  mActorsList.push_back(a);
+  Mantid::Kernel::V3D minBound;
+  Mantid::Kernel::V3D maxBound;
+  a->getBoundingBox(minBound, maxBound);
+  if (m_minBound[0] > minBound[0])
+    m_minBound[0] = minBound[0];
+  if (m_minBound[1] > minBound[1])
+    m_minBound[1] = minBound[1];
+  if (m_minBound[2] > minBound[2])
+    m_minBound[2] = minBound[2];
+  if (m_maxBound[0] < maxBound[0])
+    m_maxBound[0] = maxBound[0];
+  if (m_maxBound[1] < maxBound[1])
+    m_maxBound[1] = maxBound[1];
+  if (m_maxBound[2] < maxBound[2])
+    m_maxBound[2] = maxBound[2];
+}
+
+/**
+* Remove the input actor from the collection
+* @param :: input actor to be removed from the list
+*/
+void GLActorCollection::removeActor(GLActor *) {
+  throw std::runtime_error("Removing actor not implemented");
+}
+
+/**
+* This method returns the number of actors in the collection
+* @return integer value of number of actors in collection
+*/
+int GLActorCollection::getNumberOfActors() {
+  return static_cast<int>(mActorsList.size());
+}
+
+/**
+* This method returns the actor at the given index
+* @param index :: is the index in actor collection to be returned
+* @return a pointer to the actor at a given index
+*/
+GLActor *GLActorCollection::getActor(int index) {
+  if (index < 0 || index > static_cast<int>(mActorsList.size()))
+    return NULL;
+  return mActorsList.at(index);
+}
+
+void GLActorCollection::getBoundingBox(Mantid::Kernel::V3D &minBound,
+                                       Mantid::Kernel::V3D &maxBound) const {
+  minBound = m_minBound;
+  maxBound = m_maxBound;
+}
+
+void GLActorCollection::invalidateDisplayList() const {
+  for (size_t i = 0; i < 2; ++i) {
+    if (m_displayListId[i] != 0) {
+      glDeleteLists(m_displayListId[i], 1);
+      m_displayListId[i] = 0;
+      m_useDisplayList[i] = false;
+    }
+  }
+}
+
+void GLActorCollection::setChildVisibility(bool on) {
+  GLActor::setVisibility(on);
+  for (std::vector<GLActor *>::const_iterator it = mActorsList.begin();
+       it != mActorsList.end(); ++it) {
+    (**it).setChildVisibility(on);
+  }
+}
+
+bool GLActorCollection::hasChildVisible() const {
+  for (std::vector<GLActor *>::const_iterator it = mActorsList.begin();
+       it != mActorsList.end(); ++it) {
+    if ((**it).hasChildVisible())
+      return true;
+  }
+  return false;
+}
+}
+}
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/GLActorVisitor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/GLActorVisitor.cpp
index 8cb9fe32579da23ae02a7a344b4b916eb932e22f..2f993c39c2b0afdab8ad9e70b4073bfa5455c568 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/GLActorVisitor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/GLActorVisitor.cpp
@@ -8,94 +8,75 @@
 #include "MantidQtMantidWidgets/InstrumentView/RectangularDetectorActor.h"
 #include "MantidQtMantidWidgets/InstrumentView/StructuredDetectorActor.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		//   Default visit implementations just call visit(GLActor*)
-
-		bool GLActorVisitor::visit(GLActorCollection* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorVisitor::visit(CompAssemblyActor* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorVisitor::visit(ObjCompAssemblyActor* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorVisitor::visit(ComponentActor* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorVisitor::visit(
-			InstrumentActor *actor) {
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorVisitor::visit(RectangularDetectorActor* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-		
-		bool GLActorVisitor::visit(StructuredDetectorActor* actor)
-		{
-			return this->visit(static_cast<GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const GLActorCollection* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const CompAssemblyActor* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const ObjCompAssemblyActor* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const ComponentActor* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(
-			const InstrumentActor *actor) {
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const RectangularDetectorActor* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool GLActorConstVisitor::visit(const StructuredDetectorActor* actor)
-		{
-			return this->visit(static_cast<const GLActor*>(actor));
-		}
-
-		bool SetAllVisibleVisitor::visit(GLActor* actor)
-		{
-			actor->setVisibility(true);
-			return true;
-		}
-
-		bool SetAllVisibleVisitor::visit(ComponentActor *actor)
-		{
-			bool on = (!actor->isNonDetector()) || m_showNonDet;
-			actor->setVisibility(on);
-			return true;
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+//   Default visit implementations just call visit(GLActor*)
+
+bool GLActorVisitor::visit(GLActorCollection *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(CompAssemblyActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(ObjCompAssemblyActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(ComponentActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(InstrumentActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(RectangularDetectorActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorVisitor::visit(StructuredDetectorActor *actor) {
+  return this->visit(static_cast<GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const GLActorCollection *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const CompAssemblyActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const ObjCompAssemblyActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const ComponentActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const InstrumentActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const RectangularDetectorActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool GLActorConstVisitor::visit(const StructuredDetectorActor *actor) {
+  return this->visit(static_cast<const GLActor *>(actor));
+}
+
+bool SetAllVisibleVisitor::visit(GLActor *actor) {
+  actor->setVisibility(true);
+  return true;
+}
+
+bool SetAllVisibleVisitor::visit(ComponentActor *actor) {
+  bool on = (!actor->isNonDetector()) || m_showNonDet;
+  actor->setVisibility(on);
+  return true;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/GLColor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/GLColor.cpp
index 267b27d56e02ce5e73dac16beec411229c22324d..1336f738ad4ba865720ab79e4a34e659a599b5f7 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/GLColor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/GLColor.cpp
@@ -6,102 +6,90 @@
 
 #include <iostream>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		/**
-		* Default Constructor
-		* @param red :: The red component of the RGB colour
-		* @param green :: The green component of the RGB colour
-		* @param blue :: The blue component of the RGB colour
-		* @param alpha :: The alpha blending value
+/**
+* Default Constructor
+* @param red :: The red component of the RGB colour
+* @param green :: The green component of the RGB colour
+* @param blue :: The blue component of the RGB colour
+* @param alpha :: The alpha blending value
 
-		*/
-		GLColor::GLColor(float red, float green, float blue, float alpha)
-		{
-			m_rgba[0] = (unsigned char)(red * 255);
-			m_rgba[1] = (unsigned char)(green * 255);
-			m_rgba[2] = (unsigned char)(blue * 255);
-			m_rgba[3] = (unsigned char)(alpha * 255);
-		}
+*/
+GLColor::GLColor(float red, float green, float blue, float alpha) {
+  m_rgba[0] = (unsigned char)(red * 255);
+  m_rgba[1] = (unsigned char)(green * 255);
+  m_rgba[2] = (unsigned char)(blue * 255);
+  m_rgba[3] = (unsigned char)(alpha * 255);
+}
 
-		GLColor::GLColor(int r, int g, int b)
-		{
-			m_rgba[0] = (unsigned char)r;
-			m_rgba[1] = (unsigned char)g;
-			m_rgba[2] = (unsigned char)b;
-			m_rgba[3] = 255;
-		}
+GLColor::GLColor(int r, int g, int b) {
+  m_rgba[0] = (unsigned char)r;
+  m_rgba[1] = (unsigned char)g;
+  m_rgba[2] = (unsigned char)b;
+  m_rgba[3] = 255;
+}
 
-		/**
-		* (virtual) Destructor
-		*/
-		GLColor::~GLColor()
-		{
-		}
+/**
+* (virtual) Destructor
+*/
+GLColor::~GLColor() {}
 
-		/**
-		* This method sets the Red, Green, Blue, Alpha values of the color
-		* @param red :: Red component of color value between [0 - 1]
-		* @param green :: Green Componenent of color value between [0 - 1]
-		* @param blue :: Blue Componenent of color value between [0 - 1]
-		* @param alpha :: Alpha componenet of color value between [0 - 1]
-		*/
-		void GLColor::set(float red, float green, float blue, float alpha)
-		{
-			m_rgba[0] = (unsigned char)(red * 255);
-			m_rgba[1] = (unsigned char)(green * 255);
-			m_rgba[2] = (unsigned char)(blue * 255);
-			m_rgba[3] = (unsigned char)(alpha * 255);
-		}
+/**
+* This method sets the Red, Green, Blue, Alpha values of the color
+* @param red :: Red component of color value between [0 - 1]
+* @param green :: Green Componenent of color value between [0 - 1]
+* @param blue :: Blue Componenent of color value between [0 - 1]
+* @param alpha :: Alpha componenet of color value between [0 - 1]
+*/
+void GLColor::set(float red, float green, float blue, float alpha) {
+  m_rgba[0] = (unsigned char)(red * 255);
+  m_rgba[1] = (unsigned char)(green * 255);
+  m_rgba[2] = (unsigned char)(blue * 255);
+  m_rgba[3] = (unsigned char)(alpha * 255);
+}
 
-		/**
-		* This method sets the Red, Green, Blue, Alpha values of the color
-		* @param red :: Red component of color value between [0 - 1]
-		* @param green :: Green Componenent of color value between [0 - 1]
-		* @param blue :: Blue Componenent of color value between [0 - 1]
-		* @param alpha :: Alpha componenet of color value between [0 - 1]
-		*/
-		void GLColor::get(float& red, float& green, float& blue, float& alpha)const
-		{
-			red = float(m_rgba[0]) / 255;
-			green = float(m_rgba[1]) / 255;
-			blue = float(m_rgba[2]) / 255;
-			alpha = float(m_rgba[3]) / 255;
-		}
+/**
+* This method sets the Red, Green, Blue, Alpha values of the color
+* @param red :: Red component of color value between [0 - 1]
+* @param green :: Green Componenent of color value between [0 - 1]
+* @param blue :: Blue Componenent of color value between [0 - 1]
+* @param alpha :: Alpha componenet of color value between [0 - 1]
+*/
+void GLColor::get(float &red, float &green, float &blue, float &alpha) const {
+  red = float(m_rgba[0]) / 255;
+  green = float(m_rgba[1]) / 255;
+  blue = float(m_rgba[2]) / 255;
+  alpha = float(m_rgba[3]) / 255;
+}
 
-		void GLColor::get(unsigned char& r, unsigned char& g, unsigned char& b)const
-		{
-			r = m_rgba[0];
-			g = m_rgba[1];
-			b = m_rgba[2];
-		}
+void GLColor::get(unsigned char &r, unsigned char &g, unsigned char &b) const {
+  r = m_rgba[0];
+  g = m_rgba[1];
+  b = m_rgba[2];
+}
 
-		/**
-		* This method sets copies red,green, and blue color components into a provided buffer
-		* @param c :: Pointer to an array of unsigned chars big enough to accept 3 bytes
-		*/
-		void GLColor::getUB3(unsigned char* c)const
-		{
-			*c = m_rgba[0];
-			*(c + 1) = m_rgba[1];
-			*(c + 2) = m_rgba[2];
-		}
+/**
+* This method sets copies red,green, and blue color components into a provided
+* buffer
+* @param c :: Pointer to an array of unsigned chars big enough to accept 3 bytes
+*/
+void GLColor::getUB3(unsigned char *c) const {
+  *c = m_rgba[0];
+  *(c + 1) = m_rgba[1];
+  *(c + 2) = m_rgba[2];
+}
 
-		/**
-		* This method executes opengl color commands based on the method provided.
-		*/
-		void GLColor::paint()const
-		{
-			glColor4ubv(m_rgba);
-		}
+/**
+* This method executes opengl color commands based on the method provided.
+*/
+void GLColor::paint() const { glColor4ubv(m_rgba); }
 
-		std::ostream& operator<<(std::ostream& ostr, const GLColor& c)
-		{
-			ostr << '[' << c.red() << ',' << c.green() << ',' << c.blue() << ',' << c.alpha() << ']';
-			return ostr;
-		}
-	}//MantidWidgets
-}//MantidQt
+std::ostream &operator<<(std::ostream &ostr, const GLColor &c) {
+  ostr << '[' << c.red() << ',' << c.green() << ',' << c.blue() << ','
+       << c.alpha() << ']';
+  return ostr;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/GLObject.cpp b/MantidQt/MantidWidgets/src/InstrumentView/GLObject.cpp
index 88903280276cf5fe49de12cbfa6d8a91d88b3713..e23c31d74e45ca7e74848a2bfc4c4ec6018fdde9 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/GLObject.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/GLObject.cpp
@@ -6,89 +6,70 @@
 #include "MantidKernel/Exception.h"
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		int icount;
+namespace MantidQt {
+namespace MantidWidgets {
+int icount;
 
-		GLObject::GLObject(bool withDisplayList, const std::string& name) :mName(name), mChanged(true)
-		{
-			if (withDisplayList)
-			{
-				mDisplayListId = glGenLists(1);
-			}
-			else
-			{
-				mDisplayListId = 0;
-			}
-		}
-		GLObject::~GLObject()
-		{
-			if (mDisplayListId != 0)
-				glDeleteLists(mDisplayListId, 1);
-		}
+GLObject::GLObject(bool withDisplayList, const std::string &name)
+    : mName(name), mChanged(true) {
+  if (withDisplayList) {
+    mDisplayListId = glGenLists(1);
+  } else {
+    mDisplayListId = 0;
+  }
+}
+GLObject::~GLObject() {
+  if (mDisplayListId != 0)
+    glDeleteLists(mDisplayListId, 1);
+}
 
-		/**
-		* This method draws the opengl display list.
-		*/
-		void GLObject::draw()const
-		{
-			//std::cout << "GLObject::draw() for " << this->mName << "\n";
-			if (mChanged) construct();
-			if (mDisplayListId != 0)
-			{
-				//std::cerr << mDisplayListId << '\n';
-				glCallList(mDisplayListId);
-			}
-			else
-			{
-				this->define();
-			}
-		}
+/**
+* This method draws the opengl display list.
+*/
+void GLObject::draw() const {
+  // std::cout << "GLObject::draw() for " << this->mName << "\n";
+  if (mChanged)
+    construct();
+  if (mDisplayListId != 0) {
+    // std::cerr << mDisplayListId << '\n';
+    glCallList(mDisplayListId);
+  } else {
+    this->define();
+  }
+}
 
-		/**
-		* This method constructs the opengl display list
-		*/
-		void GLObject::construct()const
-		{
-			if (mDisplayListId == 0)
-			{
-				mChanged = false;
-				return;
-			}
-			init();
-			glNewList(mDisplayListId, GL_COMPILE); //Construct display list for object representation
-			this->define();
-			glEndList();
-			//if (dynamic_cast<ObjCompAssemblyActor*>(this))
-			if (glGetError() == GL_OUT_OF_MEMORY) //Throw an exception
-				throw Mantid::Kernel::Exception::OpenGLError("OpenGL: Out of video memory");
-			mChanged = false;  //Object Marked as changed.
-		}
+/**
+* This method constructs the opengl display list
+*/
+void GLObject::construct() const {
+  if (mDisplayListId == 0) {
+    mChanged = false;
+    return;
+  }
+  init();
+  glNewList(mDisplayListId,
+            GL_COMPILE); // Construct display list for object representation
+  this->define();
+  glEndList();
+  // if (dynamic_cast<ObjCompAssemblyActor*>(this))
+  if (glGetError() == GL_OUT_OF_MEMORY) // Throw an exception
+    throw Mantid::Kernel::Exception::OpenGLError("OpenGL: Out of video memory");
+  mChanged = false; // Object Marked as changed.
+}
 
-		/**
-		* Virtual method which initializes the the Object before creating the display list
-		*/
-		void GLObject::init()const
-		{
-		}
+/**
+* Virtual method which initializes the the Object before creating the display
+* list
+*/
+void GLObject::init() const {}
 
-		/**
-		* Virtual method which constructs the opengl rendering commands.
-		*/
-		void GLObject::define()const
-		{
-		}
+/**
+* Virtual method which constructs the opengl rendering commands.
+*/
+void GLObject::define() const {}
 
-		void GLObject::setName(const std::string& name)
-		{
-			mName = name;
-		}
-		std::string GLObject::getName() const
-		{
-			return mName;
-		}
+void GLObject::setName(const std::string &name) { mName = name; }
+std::string GLObject::getName() const { return mName; }
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ICompAssemblyActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ICompAssemblyActor.cpp
index b459576ef74e111e3b07003b084e5440c98543a7..4bfc2a877ab2ac52ebfbff244ded19fdd8f8f31b 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ICompAssemblyActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ICompAssemblyActor.cpp
@@ -7,35 +7,30 @@
 using namespace Mantid;
 using namespace Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* This is a constructor for CompAssembly Actor
-		* @param instrActor :: the instrument actor
-		* @param compID :: the component ID
-		*/
-		ICompAssemblyActor::ICompAssemblyActor(const InstrumentActor& instrActor, const Mantid::Geometry::ComponentID& compID)
-			:ComponentActor(instrActor, compID),
-			mNumberOfDetectors(0),
-			minBoundBox(DBL_MAX, DBL_MAX, DBL_MAX),
-			maxBoundBox(-DBL_MAX, -DBL_MAX, -DBL_MAX)
-		{
-		}
-
-		//------------------------------------------------------------------------------------------------
-		/**
-		* Return the bounding box
-		* @param minBound :: min point of the bounding box
-		* @param maxBound :: max point of the bounding box
-		*/
-		void ICompAssemblyActor::getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const
-		{
-			minBound = minBoundBox;
-			maxBound = maxBoundBox;
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* This is a constructor for CompAssembly Actor
+* @param instrActor :: the instrument actor
+* @param compID :: the component ID
+*/
+ICompAssemblyActor::ICompAssemblyActor(
+    const InstrumentActor &instrActor,
+    const Mantid::Geometry::ComponentID &compID)
+    : ComponentActor(instrActor, compID), mNumberOfDetectors(0),
+      minBoundBox(DBL_MAX, DBL_MAX, DBL_MAX),
+      maxBoundBox(-DBL_MAX, -DBL_MAX, -DBL_MAX) {}
 
+//------------------------------------------------------------------------------------------------
+/**
+* Return the bounding box
+* @param minBound :: min point of the bounding box
+* @param maxBound :: max point of the bounding box
+*/
+void ICompAssemblyActor::getBoundingBox(Mantid::Kernel::V3D &minBound,
+                                        Mantid::Kernel::V3D &maxBound) const {
+  minBound = minBoundBox;
+  maxBound = maxBoundBox;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentActor.cpp
index 7c4e6cec48eeeed12089f3579fa2b2ff8045afe5..486d9b522b079b6fb54f38a9b1486894aa6e9743 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentActor.cpp
@@ -1250,10 +1250,10 @@ bool SetVisibleComponentVisitor::visit(RectangularDetectorActor *actor) {
 }
 
 bool SetVisibleComponentVisitor::visit(StructuredDetectorActor *actor) {
-	bool on = actor->getComponent()->getComponentID() == m_id ||
-		actor->isChildDetector(m_id);
-	actor->setVisibility(on);
-	return on;
+  bool on = actor->getComponent()->getComponentID() == m_id ||
+            actor->isChildDetector(m_id);
+  actor->setVisibility(on);
+  return on;
 }
 
 //-------------------------------------------------------------------------//
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeModel.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeModel.cpp
index e461ecec3e5f0b27d9392984f8b8c381ce125687..893bb02844045ac73b74e3c1af06d0dea451bc70 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeModel.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeModel.cpp
@@ -13,216 +13,209 @@ using Mantid::Geometry::IComponent;
 using Mantid::Geometry::ICompAssembly;
 using Mantid::Geometry::IObjComponent;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* Constructor for tree model to display instrument tree
-		*/
-		InstrumentTreeModel::InstrumentTreeModel(const InstrumentActor *actor,
-			QObject *parent) :
-			QAbstractItemModel(parent),
-			m_instrumentActor(actor)
-		{
-		}
-
-		/**
-		* Destructor for instrument display tree
-		*/
-		InstrumentTreeModel::~InstrumentTreeModel()
-		{
-		}
-
-		/**
-		* Column count for the instrument tree.
-		*  Returns a count of 1 for the Component Assembly = I think this means "I have child nodes"
-		*  Returns 0 for the ObjComponent = I'm an end point.
-		*/
-		int InstrumentTreeModel::columnCount(const QModelIndex &parent) const
-		{
-			try
-			{
-				if (parent.isValid())
-				{
-					auto instr = m_instrumentActor->getInstrument();
-					boost::shared_ptr<const IComponent> comp = instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()));
-					boost::shared_ptr<const ICompAssembly> objcomp = boost::dynamic_pointer_cast<const ICompAssembly>(comp);
-					if (objcomp)
-						return 1;
-					return 0;
-				}
-				else
-					return 1;
-			}
-			catch (...)
-			{
-				//std::cout<<"Exception :: columnCount"<<std::endl;
-				return 0;
-			}
-		}
-
-		/**
-		* Returns the string corresponding to the component name. the root of tree string will be instrument name
-		*/
-		QVariant InstrumentTreeModel::data(const QModelIndex &index, int role) const
-		{
-			try
-			{
-				if (role != Qt::DisplayRole)
-					return QVariant();
-
-				auto instr = m_instrumentActor->getInstrument();
-
-				if (!index.isValid()) // not valid has to return the root node
-					return QString(instr->getName().c_str());
-
-				boost::shared_ptr<const IComponent> ins = instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
-				if (ins)
-				{
-					return QString(ins->getName().c_str());
-				}
-				return QString("Error");
-			}
-			catch (...)
-			{
-				//std::cout<<" Exception: in data"<<std::endl;
-				return 0;
-			}
-		}
-
-		/**
-		* Flags whether node in the tree is selectable or not. In instrument tree all components are selectable.
-		*/
-		Qt::ItemFlags InstrumentTreeModel::flags(const QModelIndex &index) const
-		{
-			(void)index; //avoid compiler warning
-			return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
-		}
-
-		/**
-		* Instrument header. returns nothing. no header for tree
-		*/
-		QVariant InstrumentTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
-		{
-			(void)section; //avoid compiler warning
-			(void)orientation; //avoid compiler warning
-			(void)role; //avoid compiler warning
-			return QVariant();
-		}
-
-		/**
-		* Returns the ModelIndex at a give row and column and the parent.
-		*/
-		QModelIndex InstrumentTreeModel::index(int row, int column, const QModelIndex &parent) const
-		{
-			//	std::cout<<"Index +++++++++ row"<<row<<" column "<<column<<" is valid "<<parent.isValid()<<std::endl;
-			try
-			{
-				boost::shared_ptr<const ICompAssembly> parentItem;
-				auto instr = m_instrumentActor->getInstrument();
-				if (!parent.isValid()) //invalid parent, has to be the root node i.e instrument
-					return createIndex(row, column, instr->getComponentID());
-
-				boost::shared_ptr<const IComponent> comp = instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()));
-				parentItem = boost::dynamic_pointer_cast<const ICompAssembly>(comp);
-				if (!parentItem)
-				{
-					boost::shared_ptr<const IObjComponent> objcomp = boost::dynamic_pointer_cast<const IObjComponent>(comp);
-					if (objcomp) return QModelIndex();
-					//Not an instrument so check for Component Assembly
-					parentItem = boost::dynamic_pointer_cast<const ICompAssembly>(instr);
-				}
-				//If component assembly pick the Component at the row index. if row index is higher than number
-				// of components in assembly return empty model index
-				if (parentItem->nelements()<row)
-				{
-					return QModelIndex();
-				}
-				else
-				{
-					return createIndex(row, column, (void*)((*parentItem)[row]->getComponentID()));
-				}
-			}
-			catch (...)
-			{
-				std::cout << "InstrumentTreeModel::index(" << row << "," << column << ") threw an exception." << std::endl;
-			}
-			return QModelIndex();
-		}
-
-		/**
-		* Returns the parent model index.
-		*/
-		QModelIndex InstrumentTreeModel::parent(const QModelIndex &index) const
-		{
-			//	std::cout<<"parent +++++++++ row"<<index.row()<<" column "<<index.column()<<" is valid "<<index.isValid()<<std::endl;
-			try
-			{
-				if (!index.isValid()) // the index corresponds to root so there is no parent for root return empty.
-					return QModelIndex();
-
-				auto instr = m_instrumentActor->getInstrument();
-
-				if (instr->getComponentID() == static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()))
-					return QModelIndex();
-
-				boost::shared_ptr<const IComponent> child = instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
-				if (child->getParent()->getComponentID() == instr->getComponentID())
-					return createIndex(0, 0, instr->getComponentID());
-				boost::shared_ptr<const IComponent> parent = instr->getComponentByID(child->getParent()->getComponentID());
-				boost::shared_ptr<const IComponent> greatParent = instr->getComponentByID(parent->getParent()->getComponentID());
-				boost::shared_ptr<const ICompAssembly> greatParentAssembly = boost::dynamic_pointer_cast<const ICompAssembly>(greatParent);
-				int iindex = 0;
-				for (int i = 0; i<greatParentAssembly->nelements(); i++)
-					if ((*greatParentAssembly)[i]->getComponentID() == parent->getComponentID())
-						iindex = i;
-				return createIndex(iindex, 0, (void*)parent->getComponentID());
-			}
-			catch (...)
-			{
-				//		std::cout<<"Exception: in parent"<<std::endl;
-			}
-			return QModelIndex();
-		}
-
-		/**
-		* Return the row count. the number of elements in the component. for ObjComponent row count will be 0.
-		*/
-		int InstrumentTreeModel::rowCount(const QModelIndex &parent) const
-		{
-			//	std::cout<<"rowCount +++++++++ row"<<parent.row()<<" column "<<parent.column()<<" is valid "<<parent.isValid()<<std::endl;
-
-			try
-			{
-				if (!parent.isValid()) // Root node row count is one.
-				{
-					return 1;//boost::dynamic_pointer_cast<ICompAssembly>(m_instrument)->nelements();
-				}
-				else
-				{
-					auto instr = m_instrumentActor->getInstrument();
-					if (instr->getComponentID() == static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()))
-					{
-						return instr->nelements();
-					}
-					boost::shared_ptr<const IComponent> comp = instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()));//static_cast<IComponent*>(parent.internalPointer());
-					boost::shared_ptr<const ICompAssembly> assembly = boost::dynamic_pointer_cast<const ICompAssembly>(comp);
-					if (assembly)
-					{
-						return assembly->nelements();
-					}
-					boost::shared_ptr<const IObjComponent> objcomp = boost::dynamic_pointer_cast<const IObjComponent>(comp);
-					if (objcomp)
-						return 0;
-				}
-			}
-			catch (...)
-			{
-				//std::cout<<"Exception: in rowCount"<<std::endl;
-			}
-			return 0;
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* Constructor for tree model to display instrument tree
+*/
+InstrumentTreeModel::InstrumentTreeModel(const InstrumentActor *actor,
+                                         QObject *parent)
+    : QAbstractItemModel(parent), m_instrumentActor(actor) {}
+
+/**
+* Destructor for instrument display tree
+*/
+InstrumentTreeModel::~InstrumentTreeModel() {}
+
+/**
+* Column count for the instrument tree.
+*  Returns a count of 1 for the Component Assembly = I think this means "I have
+* child nodes"
+*  Returns 0 for the ObjComponent = I'm an end point.
+*/
+int InstrumentTreeModel::columnCount(const QModelIndex &parent) const {
+  try {
+    if (parent.isValid()) {
+      auto instr = m_instrumentActor->getInstrument();
+      boost::shared_ptr<const IComponent> comp = instr->getComponentByID(
+          static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()));
+      boost::shared_ptr<const ICompAssembly> objcomp =
+          boost::dynamic_pointer_cast<const ICompAssembly>(comp);
+      if (objcomp)
+        return 1;
+      return 0;
+    } else
+      return 1;
+  } catch (...) {
+    // std::cout<<"Exception :: columnCount"<<std::endl;
+    return 0;
+  }
+}
+
+/**
+* Returns the string corresponding to the component name. the root of tree
+* string will be instrument name
+*/
+QVariant InstrumentTreeModel::data(const QModelIndex &index, int role) const {
+  try {
+    if (role != Qt::DisplayRole)
+      return QVariant();
+
+    auto instr = m_instrumentActor->getInstrument();
+
+    if (!index.isValid()) // not valid has to return the root node
+      return QString(instr->getName().c_str());
+
+    boost::shared_ptr<const IComponent> ins = instr->getComponentByID(
+        static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
+    if (ins) {
+      return QString(ins->getName().c_str());
+    }
+    return QString("Error");
+  } catch (...) {
+    // std::cout<<" Exception: in data"<<std::endl;
+    return 0;
+  }
+}
+
+/**
+* Flags whether node in the tree is selectable or not. In instrument tree all
+* components are selectable.
+*/
+Qt::ItemFlags InstrumentTreeModel::flags(const QModelIndex &index) const {
+  (void)index; // avoid compiler warning
+  return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
+}
+
+/**
+* Instrument header. returns nothing. no header for tree
+*/
+QVariant InstrumentTreeModel::headerData(int section,
+                                         Qt::Orientation orientation,
+                                         int role) const {
+  (void)section;     // avoid compiler warning
+  (void)orientation; // avoid compiler warning
+  (void)role;        // avoid compiler warning
+  return QVariant();
+}
+
+/**
+* Returns the ModelIndex at a give row and column and the parent.
+*/
+QModelIndex InstrumentTreeModel::index(int row, int column,
+                                       const QModelIndex &parent) const {
+  //	std::cout<<"Index +++++++++ row"<<row<<" column "<<column<<" is valid
+  //"<<parent.isValid()<<std::endl;
+  try {
+    boost::shared_ptr<const ICompAssembly> parentItem;
+    auto instr = m_instrumentActor->getInstrument();
+    if (!parent.isValid()) // invalid parent, has to be the root node i.e
+                           // instrument
+      return createIndex(row, column, instr->getComponentID());
+
+    boost::shared_ptr<const IComponent> comp = instr->getComponentByID(
+        static_cast<Mantid::Geometry::ComponentID>(parent.internalPointer()));
+    parentItem = boost::dynamic_pointer_cast<const ICompAssembly>(comp);
+    if (!parentItem) {
+      boost::shared_ptr<const IObjComponent> objcomp =
+          boost::dynamic_pointer_cast<const IObjComponent>(comp);
+      if (objcomp)
+        return QModelIndex();
+      // Not an instrument so check for Component Assembly
+      parentItem = boost::dynamic_pointer_cast<const ICompAssembly>(instr);
+    }
+    // If component assembly pick the Component at the row index. if row index
+    // is higher than number
+    // of components in assembly return empty model index
+    if (parentItem->nelements() < row) {
+      return QModelIndex();
+    } else {
+      return createIndex(row, column,
+                         (void *)((*parentItem)[row]->getComponentID()));
+    }
+  } catch (...) {
+    std::cout << "InstrumentTreeModel::index(" << row << "," << column
+              << ") threw an exception." << std::endl;
+  }
+  return QModelIndex();
+}
+
+/**
+* Returns the parent model index.
+*/
+QModelIndex InstrumentTreeModel::parent(const QModelIndex &index) const {
+  //	std::cout<<"parent +++++++++ row"<<index.row()<<" column
+  //"<<index.column()<<" is valid "<<index.isValid()<<std::endl;
+  try {
+    if (!index.isValid()) // the index corresponds to root so there is no parent
+                          // for root return empty.
+      return QModelIndex();
+
+    auto instr = m_instrumentActor->getInstrument();
+
+    if (instr->getComponentID() ==
+        static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()))
+      return QModelIndex();
+
+    boost::shared_ptr<const IComponent> child = instr->getComponentByID(
+        static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
+    if (child->getParent()->getComponentID() == instr->getComponentID())
+      return createIndex(0, 0, instr->getComponentID());
+    boost::shared_ptr<const IComponent> parent =
+        instr->getComponentByID(child->getParent()->getComponentID());
+    boost::shared_ptr<const IComponent> greatParent =
+        instr->getComponentByID(parent->getParent()->getComponentID());
+    boost::shared_ptr<const ICompAssembly> greatParentAssembly =
+        boost::dynamic_pointer_cast<const ICompAssembly>(greatParent);
+    int iindex = 0;
+    for (int i = 0; i < greatParentAssembly->nelements(); i++)
+      if ((*greatParentAssembly)[i]->getComponentID() ==
+          parent->getComponentID())
+        iindex = i;
+    return createIndex(iindex, 0, (void *)parent->getComponentID());
+  } catch (...) {
+    //		std::cout<<"Exception: in parent"<<std::endl;
+  }
+  return QModelIndex();
+}
+
+/**
+* Return the row count. the number of elements in the component. for
+* ObjComponent row count will be 0.
+*/
+int InstrumentTreeModel::rowCount(const QModelIndex &parent) const {
+  //	std::cout<<"rowCount +++++++++ row"<<parent.row()<<" column
+  //"<<parent.column()<<" is valid "<<parent.isValid()<<std::endl;
+
+  try {
+    if (!parent.isValid()) // Root node row count is one.
+    {
+      return 1; // boost::dynamic_pointer_cast<ICompAssembly>(m_instrument)->nelements();
+    } else {
+      auto instr = m_instrumentActor->getInstrument();
+      if (instr->getComponentID() == static_cast<Mantid::Geometry::ComponentID>(
+                                         parent.internalPointer())) {
+        return instr->nelements();
+      }
+      boost::shared_ptr<const IComponent> comp =
+          instr->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(
+              parent
+                  .internalPointer())); // static_cast<IComponent*>(parent.internalPointer());
+      boost::shared_ptr<const ICompAssembly> assembly =
+          boost::dynamic_pointer_cast<const ICompAssembly>(comp);
+      if (assembly) {
+        return assembly->nelements();
+      }
+      boost::shared_ptr<const IObjComponent> objcomp =
+          boost::dynamic_pointer_cast<const IObjComponent>(comp);
+      if (objcomp)
+        return 0;
+    }
+  } catch (...) {
+    // std::cout<<"Exception: in rowCount"<<std::endl;
+  }
+  return 0;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeWidget.cpp
index bbe42b23cc96bfb8241eb3fe86de5a5f3e31aee4..75486a44fbc245930da19d33578bf757b8f1286f 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeWidget.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentTreeWidget.cpp
@@ -13,100 +13,118 @@
 #include <QString>
 #include <cfloat>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		InstrumentTreeWidget::InstrumentTreeWidget(QWidget *w) :QTreeView(w), m_instrActor(NULL), m_treeModel(NULL)
-		{
-			connect(this, SIGNAL(clicked(const QModelIndex)), this, SLOT(sendComponentSelectedSignal(const QModelIndex)));
-		}
+InstrumentTreeWidget::InstrumentTreeWidget(QWidget *w)
+    : QTreeView(w), m_instrActor(NULL), m_treeModel(NULL) {
+  connect(this, SIGNAL(clicked(const QModelIndex)), this,
+          SLOT(sendComponentSelectedSignal(const QModelIndex)));
+}
 
-		void InstrumentTreeWidget::setInstrumentActor(InstrumentActor* instrActor)
-		{
-			m_instrActor = instrActor;
-			m_treeModel = new InstrumentTreeModel(instrActor, this);
-			setModel(m_treeModel);
-			setSelectionMode(SingleSelection);
-			setSelectionBehavior(SelectRows);
-		}
+void InstrumentTreeWidget::setInstrumentActor(InstrumentActor *instrActor) {
+  m_instrActor = instrActor;
+  m_treeModel = new InstrumentTreeModel(instrActor, this);
+  setModel(m_treeModel);
+  setSelectionMode(SingleSelection);
+  setSelectionBehavior(SelectRows);
+}
 
-		void InstrumentTreeWidget::getSelectedBoundingBox(const QModelIndex& index, double &xmax, double &ymax, double &zmax, double &xmin, double &ymin, double &zmin)
-		{
-			Mantid::Geometry::Instrument_const_sptr instrument = m_instrActor->getInstrument();
-			//Check whether its instrument
-			boost::shared_ptr<const Mantid::Geometry::IComponent> selectedComponent;
-			if (instrument->getComponentID() == static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()))
-				selectedComponent = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(instrument);
-			else
-				selectedComponent = instrument->getComponentByID(static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
+void InstrumentTreeWidget::getSelectedBoundingBox(const QModelIndex &index,
+                                                  double &xmax, double &ymax,
+                                                  double &zmax, double &xmin,
+                                                  double &ymin, double &zmin) {
+  Mantid::Geometry::Instrument_const_sptr instrument =
+      m_instrActor->getInstrument();
+  // Check whether its instrument
+  boost::shared_ptr<const Mantid::Geometry::IComponent> selectedComponent;
+  if (instrument->getComponentID() ==
+      static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()))
+    selectedComponent =
+        boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+            instrument);
+  else
+    selectedComponent = instrument->getComponentByID(
+        static_cast<Mantid::Geometry::ComponentID>(index.internalPointer()));
 
-			//get the bounding box for the component
-			xmax = ymax = zmax = -DBL_MAX;
-			xmin = ymin = zmin = DBL_MAX;
-			Mantid::Geometry::BoundingBox boundBox;
-			std::queue<boost::shared_ptr<const Mantid::Geometry::IComponent> > CompList;
-			CompList.push(selectedComponent);
-			while (!CompList.empty())
-			{
-				boost::shared_ptr<const Mantid::Geometry::IComponent> tmp = CompList.front();
-				CompList.pop();
-				boost::shared_ptr<const Mantid::Geometry::IObjComponent> tmpObj = boost::dynamic_pointer_cast<const Mantid::Geometry::IObjComponent>(tmp);
-				if (tmpObj) {
-					try {
-						//std::cerr << int(tmpObj->getComponentID()) << ' ' << int(instrument->getSample()->getComponentID()) << std::endl;
-						if (tmpObj->getComponentID() == instrument->getSample()->getComponentID())
-						{
-							boundBox = m_instrActor->getWorkspace()->sample().getShape().getBoundingBox();
-							boundBox.moveBy(tmpObj->getPos());
-						}
-						else
-						{
-							tmpObj->getBoundingBox(boundBox);
-						}
-						double txmax(boundBox.xMax()), tymax(boundBox.yMax()), tzmax(boundBox.zMax()),
-							txmin(boundBox.xMin()), tymin(boundBox.yMin()), tzmin(boundBox.zMin());
-						if (txmax>xmax)xmax = txmax;
-						if (tymax>ymax)ymax = tymax;
-						if (tzmax>zmax)zmax = tzmax;
-						if (txmin<xmin)xmin = txmin;
-						if (tymin<ymin)ymin = tymin;
-						if (tzmin<zmin)zmin = tzmin;
-					}
-					catch (Mantid::Kernel::Exception::NullPointerException &)
-					{
-					}
-				}
-				else if (boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(tmp)) {
-					boost::shared_ptr<const Mantid::Geometry::ICompAssembly> tmpAssem = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(tmp);
-					for (int idx = 0; idx<tmpAssem->nelements(); idx++)
-					{
-						CompList.push((*tmpAssem)[idx]);
-					}
-				}
-			}
-		}
+  // get the bounding box for the component
+  xmax = ymax = zmax = -DBL_MAX;
+  xmin = ymin = zmin = DBL_MAX;
+  Mantid::Geometry::BoundingBox boundBox;
+  std::queue<boost::shared_ptr<const Mantid::Geometry::IComponent>> CompList;
+  CompList.push(selectedComponent);
+  while (!CompList.empty()) {
+    boost::shared_ptr<const Mantid::Geometry::IComponent> tmp =
+        CompList.front();
+    CompList.pop();
+    boost::shared_ptr<const Mantid::Geometry::IObjComponent> tmpObj =
+        boost::dynamic_pointer_cast<const Mantid::Geometry::IObjComponent>(tmp);
+    if (tmpObj) {
+      try {
+        // std::cerr << int(tmpObj->getComponentID()) << ' ' <<
+        // int(instrument->getSample()->getComponentID()) << std::endl;
+        if (tmpObj->getComponentID() ==
+            instrument->getSample()->getComponentID()) {
+          boundBox = m_instrActor->getWorkspace()
+                         ->sample()
+                         .getShape()
+                         .getBoundingBox();
+          boundBox.moveBy(tmpObj->getPos());
+        } else {
+          tmpObj->getBoundingBox(boundBox);
+        }
+        double txmax(boundBox.xMax()), tymax(boundBox.yMax()),
+            tzmax(boundBox.zMax()), txmin(boundBox.xMin()),
+            tymin(boundBox.yMin()), tzmin(boundBox.zMin());
+        if (txmax > xmax)
+          xmax = txmax;
+        if (tymax > ymax)
+          ymax = tymax;
+        if (tzmax > zmax)
+          zmax = tzmax;
+        if (txmin < xmin)
+          xmin = txmin;
+        if (tymin < ymin)
+          ymin = tymin;
+        if (tzmin < zmin)
+          zmin = tzmin;
+      } catch (Mantid::Kernel::Exception::NullPointerException &) {
+      }
+    } else if (boost::dynamic_pointer_cast<
+                   const Mantid::Geometry::ICompAssembly>(tmp)) {
+      boost::shared_ptr<const Mantid::Geometry::ICompAssembly> tmpAssem =
+          boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+              tmp);
+      for (int idx = 0; idx < tmpAssem->nelements(); idx++) {
+        CompList.push((*tmpAssem)[idx]);
+      }
+    }
+  }
+}
 
-		QModelIndex InstrumentTreeWidget::findComponentByName(const QString & name) const
-		{
-			if (!m_treeModel) return QModelIndex();
-			//The data is in a tree model so recursively search until we find the string we want. Note the match is NOT
-			//case sensitive
-			QModelIndexList matches = m_treeModel->match(m_treeModel->index(0, 0, QModelIndex()), Qt::DisplayRole, name, 1,
-				Qt::MatchFixedString | Qt::MatchRecursive);
-			if (matches.isEmpty()) return QModelIndex();
-			return matches.first();
-		}
+QModelIndex
+InstrumentTreeWidget::findComponentByName(const QString &name) const {
+  if (!m_treeModel)
+    return QModelIndex();
+  // The data is in a tree model so recursively search until we find the string
+  // we want. Note the match is NOT
+  // case sensitive
+  QModelIndexList matches = m_treeModel->match(
+      m_treeModel->index(0, 0, QModelIndex()), Qt::DisplayRole, name, 1,
+      Qt::MatchFixedString | Qt::MatchRecursive);
+  if (matches.isEmpty())
+    return QModelIndex();
+  return matches.first();
+}
 
-		void InstrumentTreeWidget::sendComponentSelectedSignal(const QModelIndex index)
-		{
-			Mantid::Geometry::ComponentID id = static_cast<Mantid::Geometry::ComponentID>(index.internalPointer());
-			auto visitor = SetVisibleComponentVisitor(id);
-			m_instrActor->accept(visitor);
-			emit componentSelected(id);
-		}
-
-	}//MantidWidgets
-}//MantidQt
+void InstrumentTreeWidget::sendComponentSelectedSignal(
+    const QModelIndex index) {
+  Mantid::Geometry::ComponentID id =
+      static_cast<Mantid::Geometry::ComponentID>(index.internalPointer());
+  auto visitor = SetVisibleComponentVisitor(id);
+  m_instrActor->accept(visitor);
+  emit componentSelected(id);
+}
 
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp
index f616e44cb200586aad476d8625692c42a926b5b8..d26d4b551595f157d4a653df0d1e7eb3675e2ed4 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp
@@ -57,1272 +57,1226 @@ using namespace Mantid::API;
 using namespace Mantid::Geometry;
 using namespace MantidQt::API;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		// Name of the QSettings group to store the InstrumentWindw settings
-		const char *InstrumentWidgetSettingsGroup = "Mantid/InstrumentWidget";
-
-		/**
-		* Exception type thrown when an istrument has no sample and cannot be displayed
-		* in the instrument view.
-		*/
-		class InstrumentHasNoSampleError : public std::runtime_error {
-		public:
-			InstrumentHasNoSampleError()
-				: std::runtime_error("Instrument has no sample.\nSource and sample need "
-					"to be set in the IDF.") {}
-		};
-
-
-		/**
-		* Constructor.
-		*/
-		InstrumentWidget::InstrumentWidget(const QString &wsName, QWidget *parent,
-			bool resetGeometry, bool autoscaling,
-			double scaleMin, double scaleMax,
-			bool setDefaultView)
-			: QWidget(parent), WorkspaceObserver(), m_InstrumentDisplay(nullptr),
-			m_simpleDisplay(nullptr), m_workspaceName(wsName),
-			m_instrumentActor(nullptr), m_surfaceType(FULL3D),
-			m_savedialog_dir(QString::fromStdString(
-				Mantid::Kernel::ConfigService::Instance().getString(
-					"defaultsave.directory"))),
-			mViewChanged(false), m_blocked(false),
-			m_instrumentDisplayContextMenuOn(false) {
-			setFocusPolicy(Qt::StrongFocus);
-			QVBoxLayout *mainLayout = new QVBoxLayout(this);
-			QSplitter *controlPanelLayout = new QSplitter(Qt::Horizontal);
-
-			// Add Tab control panel
-                        mControlsTab = new QTabWidget(this);
-                        controlPanelLayout->addWidget(mControlsTab);
-                        controlPanelLayout->setSizePolicy(QSizePolicy::Expanding,
-				QSizePolicy::Expanding);
-
-			// Create the display widget
-			m_InstrumentDisplay = new MantidGLWidget(this);
-			m_InstrumentDisplay->installEventFilter(this);
-			connect(this, SIGNAL(enableLighting(bool)), m_InstrumentDisplay,
-				SLOT(enableLighting(bool)));
-
-			// Create simple display widget
-			m_simpleDisplay = new SimpleWidget(this);
-			m_simpleDisplay->installEventFilter(this);
-
-			QWidget *aWidget = new QWidget(this);
-			m_instrumentDisplayLayout = new QStackedLayout(aWidget);
-			m_instrumentDisplayLayout->addWidget(m_InstrumentDisplay);
-			m_instrumentDisplayLayout->addWidget(m_simpleDisplay);
-
-			controlPanelLayout->addWidget(aWidget);
-
-			mainLayout->addWidget(controlPanelLayout);
-
-			m_xIntegration = new XIntegrationControl(this);
-			mainLayout->addWidget(m_xIntegration);
-			connect(m_xIntegration, SIGNAL(changed(double, double)), this,
-				SLOT(setIntegrationRange(double, double)));
-
-			// Set the mouse/keyboard operation info and help button
-			QHBoxLayout *infoLayout = new QHBoxLayout();
-			mInteractionInfo = new QLabel();
-			infoLayout->addWidget(mInteractionInfo);
-			QPushButton *helpButton = new QPushButton("?");
-			helpButton->setMaximumWidth(25);
-			connect(helpButton, SIGNAL(clicked()), this, SLOT(helpClicked()));
-			infoLayout->addWidget(helpButton);
-			infoLayout->setStretchFactor(mInteractionInfo, 1);
-			infoLayout->setStretchFactor(helpButton, 0);
-			mainLayout->addLayout(infoLayout);
-
-			QSettings settings;
-			settings.beginGroup(InstrumentWidgetSettingsGroup);
-
-			// Background colour
-			setBackgroundColor(
-				settings.value("BackgroundColor", QColor(0, 0, 0, 1.0)).value<QColor>());
-
-			// Create the b=tabs
-			createTabs(settings);
-
-			settings.endGroup();
-
-			// Init actions
-			m_clearPeakOverlays = new QAction("Clear peaks", this);
-			connect(m_clearPeakOverlays, SIGNAL(activated()), this,
-				SLOT(clearPeakOverlays()));
-
-			// confirmClose(app->confirmCloseInstrWindow);
-
-			setAttribute(Qt::WA_DeleteOnClose);
-
-			// Watch for the deletion of the associated workspace
-			observePreDelete();
-			observeAfterReplace();
-			observeRename();
-			observeADSClear();
-
-			const int windowWidth = 800;
-			const int tabsSize = windowWidth / 4;
-			QList<int> sizes;
-			sizes << tabsSize << windowWidth - tabsSize;
-			controlPanelLayout->setSizes(sizes);
-			controlPanelLayout->setStretchFactor(0, 0);
-			controlPanelLayout->setStretchFactor(1, 1);
-
-			resize(windowWidth, 650);
-
-			tabChanged(0);
-
-			connect(this, SIGNAL(needSetIntegrationRange(double, double)), this,
-				SLOT(setIntegrationRange(double, double)), Qt::QueuedConnection);
-			setAcceptDrops(true);
-
-			setWindowTitle(QString("Instrument - ") + m_workspaceName);
-
-			init(resetGeometry, autoscaling, scaleMin, scaleMax, setDefaultView);
-		}
-
-		/**
-		* Destructor
-		*/
-		InstrumentWidget::~InstrumentWidget() {
-			if (m_instrumentActor) {
-				saveSettings();
-				delete m_instrumentActor;
-			}
-		}
-
-		QString InstrumentWidget::getWorkspaceName() const { 
-			return m_workspaceName; 
-		}
-
-		std::string InstrumentWidget::getWorkspaceNameStdString() const {
-			return m_workspaceName.toStdString();
-		}
-
-		void InstrumentWidget::renameWorkspace(const std::string &workspace) {
-			m_workspaceName = QString::fromStdString(workspace);
-		}
-
-		/**
-		* Init the geometry and colour map outside constructor to prevent creating a
-		* broken MdiSubwindow.
-		* Must be called straight after constructor.
-		* @param resetGeometry :: Set true for resetting the view's geometry: the
-		* bounding box and rotation. Default is true.
-		* @param autoscaling :: True to start with autoscaling option on.
-		* @param scaleMin :: Minimum value of the colormap scale. Ignored if
-		* autoscaling == true.
-		* @param scaleMax :: Maximum value of the colormap scale. Ignored if
-		* autoscaling == true.
-		* @param setDefaultView :: Set the default surface type
-		*/
-		void InstrumentWidget::init(bool resetGeometry, bool autoscaling,
-			double scaleMin, double scaleMax,
-			bool setDefaultView) {
-			// Previously in (now removed) setWorkspaceName method
-			m_instrumentActor =
-				new InstrumentActor(m_workspaceName, autoscaling, scaleMin, scaleMax);
-			m_xIntegration->setTotalRange(m_instrumentActor->minBinValue(),
-				m_instrumentActor->maxBinValue());
-			m_xIntegration->setUnits(QString::fromStdString(
-				m_instrumentActor->getWorkspace()->getAxis(0)->unit()->caption()));
-			auto surface = getSurface();
-			if (resetGeometry || !surface) {
-				if (setDefaultView) {
-					// set the view type to the instrument's default view
-					QString defaultView = QString::fromStdString(
-						m_instrumentActor->getInstrument()->getDefaultView());
-					if (defaultView == "3D" &&
-						Mantid::Kernel::ConfigService::Instance().getString(
-							"MantidOptions.InstrumentView.UseOpenGL") != "On") {
-						// if OpenGL is switched off don't open the 3D view at start up
-						defaultView = "CYLINDRICAL_Y";
-					}
-					setSurfaceType(defaultView);
-				}
-				else {
-					setSurfaceType(m_surfaceType); // This call must come after the
-													// InstrumentActor is created
-				}
-				setupColorMap();
-			}
-			else {
-				surface->resetInstrumentActor(m_instrumentActor);
-				updateInfoText();
-			}
-		}
-
-		/**
-		* Deletes instrument actor before re-initializing.
-		* @param resetGeometry
-		*/
-		void InstrumentWidget::resetInstrument(bool resetGeometry) {
-			delete m_instrumentActor;
-			m_instrumentActor = nullptr;
-			init(resetGeometry, true, 0.0, 0.0, false);
-			updateInstrumentDetectors();
-		}
-
-		/**
-		* Select the tab to be displayed
-		*/
-		void InstrumentWidget::selectTab(int tab) {
-			mControlsTab->setCurrentIndex(tab);
-		}
-
-		/**
-		* Returns the named tab or the current tab if none supplied
-		* @param title Optional title of a tab (default="")
-		*/
-		InstrumentWidgetTab *InstrumentWidget::getTab(const QString &title) const {
-			QWidget *tab(nullptr);
-			if (title.isEmpty())
-				tab = mControlsTab->currentWidget();
-			else {
-				for (int i = 0; i < mControlsTab->count(); ++i) {
-					if (mControlsTab->tabText(i) == title) {
-						tab = mControlsTab->widget(i);
-						break;
-					}
-				}
-			}
-
-			if (tab)
-				return qobject_cast<InstrumentWidgetTab *>(tab);
-			else
-				return nullptr;
-		}
-
-		/**
-		* @param tab An enumeration for the tab to select
-		* @returns A pointer to the requested tab
-		*/
-		InstrumentWidgetTab *InstrumentWidget::getTab(const Tab tab) const {
-			QWidget *widget = mControlsTab->widget(static_cast<int>(tab));
-			if (widget)
-				return qobject_cast<InstrumentWidgetTab *>(widget);
-			else
-				return nullptr;
-		}
-
-		/**
-		* Opens Qt file dialog to select the filename.
-		* The dialog opens in the directory used last for saving or the default user
-		* directory.
-		*
-		* @param title :: The title of the dialog.
-		* @param filters :: The filters
-		* @param selectedFilter :: The selected filter.
-		*/
-		QString InstrumentWidget::getSaveFileName(const QString &title,
-			const QString &filters,
-			QString *selectedFilter) {
-			QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(
-				this, title, m_savedialog_dir, filters, selectedFilter);
-
-			// If its empty, they cancelled the dialog
-			if (!filename.isEmpty()) {
-				// Save the directory used
-				QFileInfo finfo(filename);
-				m_savedialog_dir = finfo.dir().path();
-			}
-			return filename;
-		}
-
-		/**
-		* Update the info text displayed at the bottom of the window.
-		*/
-		void InstrumentWidget::updateInfoText() { setInfoText(getSurfaceInfoText()); }
-
-		void InstrumentWidget::setSurfaceType(int type) {
-			// we cannot do 3D without OpenGL
-			if (type == FULL3D && !isGLEnabled()) {
-				QMessageBox::warning(
-					this, "Mantid - Warning",
-					"OpenGL must be enabled to render the instrument in 3D.");
-				return;
-			}
-
-			if (type < RENDERMODE_SIZE) {
-				QApplication::setOverrideCursor(Qt::WaitCursor);
-				SurfaceType surfaceType = SurfaceType(type);
-				if (!m_instrumentActor)
-					return;
-
-				ProjectionSurface *surface = getSurface().get();
-				int peakLabelPrecision = 6;
-				bool showPeakRow = true;
-				bool showPeakLabels = true;
-				bool showPeakRelativeIntensity = true;
-				if (surface) {
-					peakLabelPrecision = surface->getPeakLabelPrecision();
-					showPeakRow = surface->getShowPeakRowsFlag();
-					showPeakLabels = surface->getShowPeakLabelsFlag();
-				}
-				else {
-					QSettings settings;
-					settings.beginGroup(InstrumentWidgetSettingsGroup);
-					peakLabelPrecision = settings.value("PeakLabelPrecision", 2).toInt();
-					showPeakRow = settings.value("ShowPeakRows", true).toBool();
-					showPeakLabels = settings.value("ShowPeakLabels", true).toBool();
-
-					// By default this is should be off for now.
-					showPeakRelativeIntensity =
-						settings.value("ShowPeakRelativeIntensities", false).toBool();
-					settings.endGroup();
-				}
-
-				// Surface factory
-				// If anything throws during surface creation, store error message here
-				QString errorMessage;
-				try {
-					Mantid::Geometry::Instrument_const_sptr instr =
-						m_instrumentActor->getInstrument();
-					Mantid::Geometry::IComponent_const_sptr sample = instr->getSample();
-					if (!sample) {
-						throw InstrumentHasNoSampleError();
-					}
-					Mantid::Kernel::V3D sample_pos = sample->getPos();
-					Mantid::Kernel::V3D axis;
-					// define the axis
-					if (surfaceType == SPHERICAL_Y || surfaceType == CYLINDRICAL_Y) {
-						axis = Mantid::Kernel::V3D(0, 1, 0);
-					}
-					else if (surfaceType == SPHERICAL_Z || surfaceType == CYLINDRICAL_Z) {
-						axis = Mantid::Kernel::V3D(0, 0, 1);
-					}
-					else if (surfaceType == SPHERICAL_X || surfaceType == CYLINDRICAL_X) {
-						axis = Mantid::Kernel::V3D(1, 0, 0);
-					}
-					else // SIDE_BY_SIDE
-					{
-						axis = Mantid::Kernel::V3D(0, 0, 1);
-					}
-
-					// create the surface
-					if (surfaceType == FULL3D) {
-						surface =
-							new Projection3D(m_instrumentActor, getInstrumentDisplayWidth(),
-								getInstrumentDisplayHeight());
-					}
-					else if (surfaceType <= CYLINDRICAL_Z) {
-						surface = new UnwrappedCylinder(m_instrumentActor, sample_pos, axis);
-					}
-					else if (surfaceType <= SPHERICAL_Z) {
-						surface = new UnwrappedSphere(m_instrumentActor, sample_pos, axis);
-					}
-					else // SIDE_BY_SIDE
-					{
-						surface = new PanelsSurface(m_instrumentActor, sample_pos, axis);
-					}
-				}
-				catch (InstrumentHasNoSampleError &) {
-					QApplication::restoreOverrideCursor();
-					throw;
-				}
-				catch (std::exception &e) {
-					errorMessage = e.what();
-				}
-				catch (...) {
-					errorMessage = "Unknown exception thrown.";
-				}
-				if (!errorMessage.isNull()) {
-					// if exception was thrown roll back to the current surface type.
-					QApplication::restoreOverrideCursor();
-					QMessageBox::critical(
-						this, "MantidPlot - Error",
-						"Surface cannot be created because of an exception:\n\n  " +
-						errorMessage + "\n\nPlease select a different surface type.");
-					// if suface change was initialized by the GUI this should ensure its
-					// consistency
-					emit surfaceTypeChanged(m_surfaceType);
-					return;
-				}
-				// end Surface factory
-
-				m_surfaceType = surfaceType;
-				surface->setPeakLabelPrecision(peakLabelPrecision);
-				surface->setShowPeakRowsFlag(showPeakRow);
-				surface->setShowPeakLabelsFlag(showPeakLabels);
-				surface->setShowPeakRelativeIntensityFlag(showPeakRelativeIntensity);
-				// set new surface
-				setSurface(surface);
-
-				// init tabs with new surface
-				foreach(InstrumentWidgetTab *tab, m_tabs) { tab->initSurface(); }
-
-				connect(surface, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)),
-					this, SLOT(executeAlgorithm(Mantid::API::IAlgorithm_sptr)));
-				connect(surface, SIGNAL(updateInfoText()), this, SLOT(updateInfoText()),
-					Qt::QueuedConnection);
-				QApplication::restoreOverrideCursor();
-			}
-			emit surfaceTypeChanged(type);
-			updateInfoText();
-			update();
-		}
-
-		/**
-		* Set the surface type from a string.
-		* @param typeStr :: Symbolic name of the surface type: same as the names in
-		* SurfaceType enum. Caseless.
-		*/
-		void InstrumentWidget::setSurfaceType(const QString &typeStr) {
-			int typeIndex = 0;
-			QString upperCaseStr = typeStr.toUpper();
-			if (upperCaseStr == "FULL3D" || upperCaseStr == "3D") {
-				typeIndex = 0;
-			}
-			else if (upperCaseStr == "CYLINDRICAL_X") {
-				typeIndex = 1;
-			}
-			else if (upperCaseStr == "CYLINDRICAL_Y") {
-				typeIndex = 2;
-			}
-			else if (upperCaseStr == "CYLINDRICAL_Z") {
-				typeIndex = 3;
-			}
-			else if (upperCaseStr == "SPHERICAL_X") {
-				typeIndex = 4;
-			}
-			else if (upperCaseStr == "SPHERICAL_Y") {
-				typeIndex = 5;
-			}
-			else if (upperCaseStr == "SPHERICAL_Z") {
-				typeIndex = 6;
-			}
-			else if (upperCaseStr == "SIDE_BY_SIDE") {
-				typeIndex = 7;
-			}
-			setSurfaceType(typeIndex);
-		}
-
-		/**
-		* Update the colormap on the render tab.
-		*/
-		void InstrumentWidget::setupColorMap() { emit colorMapChanged(); }
-
-		/**
-		* Connected to QTabWidget::currentChanged signal
-		*/
-		void InstrumentWidget::tabChanged(int) { updateInfoText(); }
-
-		/**
-		* Change color map button slot. This provides the file dialog box to select
-		* colormap or sets it directly a string is provided
-		*/
-		void InstrumentWidget::changeColormap(const QString &filename) {
-			if (!m_instrumentActor)
-				return;
-			QString fileselection;
-			// Use a file dialog if no parameter is passed
-			if (filename.isEmpty()) {
-				fileselection = MantidColorMap::loadMapDialog(
-					m_instrumentActor->getCurrentColorMap(), this);
-				if (fileselection.isEmpty())
-					return;
-			}
-			else {
-				fileselection = QFileInfo(filename).absoluteFilePath();
-				if (!QFileInfo(fileselection).exists())
-					return;
-			}
-
-			if (!m_instrumentActor->getCurrentColorMap().isEmpty() &&
-				(fileselection == m_instrumentActor->getCurrentColorMap()))
-				return;
-
-			m_instrumentActor->loadColorMap(fileselection);
-			if (this->isVisible()) {
-				setupColorMap();
-				updateInstrumentView();
-			}
-		}
-
-		QString InstrumentWidget::confirmDetectorOperation(const QString &opName,
-			const QString &inputWS,
-			int ndets) {
-			QString message("This operation will affect %1 detectors.\nSelect output "
-				"workspace option:");
-			QMessageBox prompt(this);
-			prompt.setWindowTitle("MantidPlot");
-			prompt.setText(message.arg(QString::number(ndets)));
-			QPushButton *replace = prompt.addButton("Replace", QMessageBox::ActionRole);
-			QPushButton *create = prompt.addButton("New", QMessageBox::ActionRole);
-			prompt.addButton("Cancel", QMessageBox::ActionRole);
-			prompt.exec();
-			QString outputWS;
-			if (prompt.clickedButton() == replace) {
-				outputWS = inputWS;
-			}
-			else if (prompt.clickedButton() == create) {
-				outputWS = inputWS + "_" + opName;
-			}
-			else {
-				outputWS = "";
-			}
-			return outputWS;
-		}
-
-		/**
-		* Convert a list of integers to a comma separated string of numbers
-		*/
-		QString InstrumentWidget::asString(const std::vector<int> &numbers) const {
-			QString num_str;
-			std::vector<int>::const_iterator iend = numbers.end();
-			for (std::vector<int>::const_iterator itr = numbers.begin(); itr < iend;
-			++itr) {
-				num_str += QString::number(*itr) + ",";
-			}
-			// Remove trailing comma
-			num_str.chop(1);
-			return num_str;
-		}
-
-		/// Set a maximum and minimum for the colour map range
-		void InstrumentWidget::setColorMapRange(double minValue, double maxValue) {
-			emit colorMapRangeChanged(minValue, maxValue);
-			update();
-		}
-
-		/// Set the minimum value of the colour map
-		void InstrumentWidget::setColorMapMinValue(double minValue) {
-			emit colorMapMinValueChanged(minValue);
-			update();
-		}
-
-		/// Set the maximumu value of the colour map
-		void InstrumentWidget::setColorMapMaxValue(double maxValue) {
-			emit colorMapMaxValueChanged(maxValue);
-			update();
-		}
-
-		/**
-		* This is the callback for the combo box that selects the view direction
-		*/
-		void InstrumentWidget::setViewDirection(const QString &input) {
-			auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
-			if (p3d) {
-				p3d->setViewDirection(input);
-			}
-			updateInstrumentView();
-			repaint();
-		}
-
-		/**
-		*  For the scripting API. Selects a component in the tree and zooms to it.
-		*  @param name The name of the component
-		*/
-		void InstrumentWidget::selectComponent(const QString &name) {
-			emit requestSelectComponent(name);
-		}
-
-		/**
-		* Set the scale type programmatically
-		* @param type :: The scale choice
-		*/
-		void InstrumentWidget::setScaleType(GraphOptions::ScaleType type) {
-			emit scaleTypeChanged(type);
-		}
-
-		/**
-		* Set the exponent for the Power scale type
-		* @param nth_power :: The exponent choice
-		*/
-		void InstrumentWidget::setExponent(double nth_power) {
-			emit nthPowerChanged(nth_power);
-		}
-
-		/**
-		* This method opens a color dialog to pick the background color,
-		* and then sets it.
-		*/
-		void InstrumentWidget::pickBackgroundColor() {
-			QColor color = QColorDialog::getColor(Qt::green, this);
-			setBackgroundColor(color);
-		}
-
-		/**
-		* Saves the current image buffer as a png file.
-		* @param filename Optional filename. Empty string raises a save dialog
-		*/
-		void InstrumentWidget::saveImage(QString filename) {
-			QString defaultExt = ".png";
-			QList<QByteArray> formats = QImageWriter::supportedImageFormats();
-			if (filename.isEmpty()) {
-				QListIterator<QByteArray> itr(formats);
-				QString filter("");
-				while (itr.hasNext()) {
-					filter += "*." + itr.next();
-					if (itr.hasNext()) {
-						filter += ";;";
-					}
-				}
-				QString selectedFilter = "*" + defaultExt;
-				filename = getSaveFileName("Save image ...", filter, &selectedFilter);
-
-				// If its empty, they cancelled the dialog
-				if (filename.isEmpty())
-					return;
-			}
-
-			QFileInfo finfo(filename);
-			QString ext = finfo.completeSuffix();
-
-			if (ext.isEmpty()) {
-				filename += defaultExt;
-				ext = QFileInfo(filename).completeSuffix();
-			}
-			else {
-				if (!formats.contains(ext.toAscii())) {
-					QString msg("Unsupported file extension. Choose one of the following: ");
-					QListIterator<QByteArray> itr(formats);
-					while (itr.hasNext()) {
-						msg += itr.next() + ", ";
-					}
-					msg.chop(2); // Remove last space and comma
-					QMessageBox::warning(this, "MantidPlot", msg);
-					return;
-				}
-			}
-
-			if (isGLEnabled()) {
-				m_InstrumentDisplay->saveToFile(filename);
-			}
-			else {
-				m_simpleDisplay->saveToFile(filename);
-			}
-		}
-
-		/**
-		* Use the file dialog to select a filename to save grouping.
-		*/
-		QString InstrumentWidget::getSaveGroupingFilename() {
-			QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(
-				this, "Save grouping file", m_savedialog_dir,
-				"Grouping (*.xml);;All files (*.*)");
-
-			// If its empty, they cancelled the dialog
-			if (!filename.isEmpty()) {
-				// Save the directory used
-				QFileInfo finfo(filename);
-				m_savedialog_dir = finfo.dir().path();
-			}
-
-			return filename;
-		}
-
-		///**
-		// * Update the text display that informs the user of the current mode and
-		// details about it
-		// */
-		void InstrumentWidget::setInfoText(const QString &text) {
-			mInteractionInfo->setText(text);
-		}
-
-		/**
-		* Save properties of the window a persistent store
-		*/
-		void InstrumentWidget::saveSettings() {
-			QSettings settings;
-			settings.beginGroup(InstrumentWidgetSettingsGroup);
-			if (m_InstrumentDisplay)
-				settings.setValue("BackgroundColor",
-					m_InstrumentDisplay->currentBackgroundColor());
-			auto surface = getSurface();
-			if (surface) {
-				// if surface is null istrument view wasn't created and there is nothing to
-				// save
-				settings.setValue("PeakLabelPrecision",
-					getSurface()->getPeakLabelPrecision());
-				settings.setValue("ShowPeakRows", getSurface()->getShowPeakRowsFlag());
-				settings.setValue("ShowPeakLabels", getSurface()->getShowPeakLabelsFlag());
-				settings.setValue("ShowPeakRelativeIntensities",
-					getSurface()->getShowPeakRelativeIntensityFlag());
-				foreach(InstrumentWidgetTab *tab, m_tabs) { tab->saveSettings(settings); }
-			}
-			settings.endGroup();
-		}
-
-		void InstrumentWidget::helpClicked() {
-			QDesktopServices::openUrl(
-				QUrl("http://www.mantidproject.org/MantidPlot:_Instrument_View"));
-		}
-
-		void InstrumentWidget::set3DAxesState(bool on) {
-			auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
-			if (p3d) {
-				p3d->set3DAxesState(on);
-				updateInstrumentView();
-			}
-		}
-
-		void InstrumentWidget::finishHandle(const Mantid::API::IAlgorithm *alg) {
-			UNUSED_ARG(alg);
-			emit needSetIntegrationRange(m_instrumentActor->minBinValue(),
-				m_instrumentActor->maxBinValue());
-			// m_instrumentActor->update();
-			// m_InstrumentDisplay->refreshView();
-		}
-
-		void InstrumentWidget::changeScaleType(int type) {
-			m_instrumentActor->changeScaleType(type);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		void InstrumentWidget::changeNthPower(double nth_power) {
-			m_instrumentActor->changeNthPower(nth_power);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		void InstrumentWidget::changeColorMapMinValue(double minValue) {
-			m_instrumentActor->setAutoscaling(false);
-			m_instrumentActor->setMinValue(minValue);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		/// Set the maximumu value of the colour map
-		void InstrumentWidget::changeColorMapMaxValue(double maxValue) {
-			m_instrumentActor->setAutoscaling(false);
-			m_instrumentActor->setMaxValue(maxValue);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		void InstrumentWidget::changeColorMapRange(double minValue, double maxValue) {
-			m_instrumentActor->setMinMaxRange(minValue, maxValue);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		void InstrumentWidget::setWireframe(bool on) {
-			auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
-			if (p3d) {
-				p3d->setWireframe(on);
-			}
-			updateInstrumentView();
-		}
-
-		/**
-		* Set new integration range but don't update XIntegrationControl (because the
-		* control calls this slot)
-		*/
-		void InstrumentWidget::setIntegrationRange(double xmin, double xmax) {
-			m_instrumentActor->setIntegrationRange(xmin, xmax);
-			setupColorMap();
-			updateInstrumentDetectors();
-			emit integrationRangeChanged(xmin, xmax);
-		}
-
-		/**
-		* Set new integration range and update XIntegrationControl. To be called from
-		* python.
-		*/
-		void InstrumentWidget::setBinRange(double xmin, double xmax) {
-			m_xIntegration->setRange(xmin, xmax);
-		}
-
-		/**
-		* Update the display to view a selected component. The selected component
-		* is visible the rest of the instrument is hidden.
-		* @param id :: The component id.
-		*/
-		void InstrumentWidget::componentSelected(ComponentID id) {
-			auto surface = getSurface();
-			if (surface) {
-				surface->componentSelected(id);
-				// surface->updateView();
-				updateInstrumentView();
-			}
-		}
-
-		void InstrumentWidget::executeAlgorithm(const QString &, const QString &) {
-			// emit execMantidAlgorithm(alg_name, param_list, this);
-		}
-
-		void InstrumentWidget::executeAlgorithm(Mantid::API::IAlgorithm_sptr alg) {
-			try {
-				alg->executeAsync();
-			}
-			catch (Poco::NoThreadAvailableException &) {
-				return;
-			}
-
-			return;
-		}
-
-		/**
-		* Set the type of the view (SurfaceType).
-		* @param type :: String code for the type. One of:
-		* FULL3D, CYLINDRICAL_X, CYLINDRICAL_Y, CYLINDRICAL_Z, SPHERICAL_X,
-		* SPHERICAL_Y, SPHERICAL_Z
-		*/
-		void InstrumentWidget::setViewType(const QString &type) {
-			QString type_upper = type.toUpper();
-			SurfaceType itype = FULL3D;
-			if (type_upper == "FULL3D") {
-				itype = FULL3D;
-			}
-			else if (type_upper == "CYLINDRICAL_X") {
-				itype = CYLINDRICAL_X;
-			}
-			else if (type_upper == "CYLINDRICAL_Y") {
-				itype = CYLINDRICAL_Y;
-			}
-			else if (type_upper == "CYLINDRICAL_Z") {
-				itype = CYLINDRICAL_Z;
-			}
-			else if (type_upper == "SPHERICAL_X") {
-				itype = SPHERICAL_X;
-			}
-			else if (type_upper == "SPHERICAL_Y") {
-				itype = SPHERICAL_Y;
-			}
-			else if (type_upper == "SPHERICAL_Z") {
-				itype = SPHERICAL_Z;
-			}
-			setSurfaceType(itype);
-		}
-
-		void InstrumentWidget::dragEnterEvent(QDragEnterEvent *e) {
-			QString name = e->mimeData()->objectName();
-			if (name == "MantidWorkspace") {
-				e->accept();
-			}
-			else {
-				e->ignore();
-			}
-		}
-
-		void InstrumentWidget::dropEvent(QDropEvent *e) {
-			QString name = e->mimeData()->objectName();
-			if (name == "MantidWorkspace") {
-				QString text = e->mimeData()->text();
-				int endIndex = 0;
-				QStringList wsNames;
-				while (text.indexOf("[\"", endIndex) > -1) {
-					int startIndex = text.indexOf("[\"", endIndex) + 2;
-					endIndex = text.indexOf("\"]", startIndex);
-					wsNames.append(text.mid(startIndex, endIndex - startIndex));
-				}
-
-				foreach(const auto &wsName, wsNames) {
-					if (this->overlay(wsName))
-						e->accept();
-				}
-			}
-			e->ignore();
-		}
-
-		/**
-		* Filter events directed to m_InstrumentDisplay and ContextMenuEvent in
-		* particular.
-		* @param obj :: Object which events will be filtered.
-		* @param ev :: An ingoing event.
-		*/
-		bool InstrumentWidget::eventFilter(QObject *obj, QEvent *ev) {
-			if (ev->type() == QEvent::ContextMenu &&
-				(dynamic_cast<MantidGLWidget *>(obj) == m_InstrumentDisplay ||
-					dynamic_cast<SimpleWidget *>(obj) == m_simpleDisplay) &&
-				getSurface() && getSurface()->canShowContextMenu()) {
-				// an ugly way of preventing the curve in the pick tab's miniplot
-				// disappearing when
-				// cursor enters the context menu
-				m_instrumentDisplayContextMenuOn = true;
-				QMenu context(this);
-				// add tab specific actions
-				InstrumentWidgetTab *tab = getTab();
-				tab->addToDisplayContextMenu(context);
-				if (getSurface()->hasPeakOverlays()) {
-					context.addSeparator();
-					context.addAction(m_clearPeakOverlays);
-				}
-				if (!context.isEmpty()) {
-					context.exec(QCursor::pos());
-				}
-				m_instrumentDisplayContextMenuOn = false;
-				return true;
-			}
-			return QWidget::eventFilter(obj, ev);
-		}
-
-		/**
-		* Set on / off autoscaling of the color map on the render tab.
-		* @param on :: On or Off.
-		*/
-		void InstrumentWidget::setColorMapAutoscaling(bool on) {
-			m_instrumentActor->setAutoscaling(on);
-			setupColorMap();
-			updateInstrumentView();
-		}
-
-		/**
-		*  Overlay a workspace with the given name
-		* @param wsName The name of a workspace in the ADS
-		* @returns True if the overlay was successful, false otherwise
-		*/
-		bool InstrumentWidget::overlay(const QString &wsName) {
-			using namespace Mantid::API;
-			Workspace_sptr workspace;
-			bool success(false);
-			try {
-				workspace = AnalysisDataService::Instance().retrieve(wsName.toStdString());
-			}
-			catch (std::runtime_error) {
-				QMessageBox::warning(this, "MantidPlot - Warning",
-					"No workspace called '" + wsName + "' found. ");
-				return success;
-			}
-
-			auto pws = boost::dynamic_pointer_cast<IPeaksWorkspace>(workspace);
-			if (!pws) {
-				QMessageBox::warning(this, "MantidPlot - Warning",
-					"Work space called '" + wsName +
-					"' is not suitable."
-					" Please select another workspace. ");
-				return success;
-			}
-
-			auto surface = boost::dynamic_pointer_cast<UnwrappedSurface>(getSurface());
-			if (!surface) {
-				QMessageBox::warning(
-					this, "MantidPlot - Warning",
-					"Please change to an unwrapped view to see peak labels.");
-				return success;
-			}
-
-			if (pws && surface) {
-				surface->setPeaksWorkspace(pws);
-				updateInstrumentView();
-				success = true;
-			}
-			return success;
-		}
-
-		/**
-		* Remove all peak overlays from the instrument display.
-		*/
-		void InstrumentWidget::clearPeakOverlays() {
-			getSurface()->clearPeakOverlays();
-			updateInstrumentView();
-		}
-
-		/**
-		* Set the precision (significant digits) with which the HKL peak labels are
-		* displayed.
-		* @param n :: Precision, > 0
-		*/
-		void InstrumentWidget::setPeakLabelPrecision(int n) {
-			getSurface()->setPeakLabelPrecision(n);
-			updateInstrumentView();
-		}
-
-		/**
-		* Enable or disable the show peak row flag
-		* @param on :: True to show, false to hide.
-		*/
-		void InstrumentWidget::setShowPeakRowFlag(bool on) {
-			getSurface()->setShowPeakRowsFlag(on);
-			updateInstrumentView();
-		}
-
-		/**
-		* Enable or disable the show peak hkl labels flag
-		* @param on :: True to show, false to hide.
-		*/
-		void InstrumentWidget::setShowPeakLabelsFlag(bool on) {
-			getSurface()->setShowPeakLabelsFlag(on);
-			updateInstrumentView();
-		}
-
-		/**
-		* Enable or disable indication of relative peak intensities
-		*
-		* @param on :: True to show, false to hide.
-		*/
-		void InstrumentWidget::setShowPeakRelativeIntensity(bool on) {
-			getSurface()->setShowPeakRelativeIntensityFlag(on);
-			updateInstrumentView();
-		}
-
-		/**
-		* Set background color of the instrument display
-		* @param color :: New background colour.
-		*/
-		void InstrumentWidget::setBackgroundColor(const QColor &color) {
-			if (m_InstrumentDisplay)
-				m_InstrumentDisplay->setBackgroundColor(color);
-		}
-
-		/**
-		* Get the surface info string
-		*/
-		QString InstrumentWidget::getSurfaceInfoText() const {
-			ProjectionSurface *surface = getSurface().get();
-			return surface ? surface->getInfoText() : "";
-		}
-
-		/**
-		* Get pointer to the projection surface
-		*/
-		ProjectionSurface_sptr InstrumentWidget::getSurface() const {
-			if (m_InstrumentDisplay) {
-				return m_InstrumentDisplay->getSurface();
-			}
-			else if (m_simpleDisplay) {
-				return m_simpleDisplay->getSurface();
-			}
-			return ProjectionSurface_sptr();
-		}
-
-		/**
-		* Set newly created projection surface
-		* @param surface :: Pointer to the new surace.
-		*/
-		void InstrumentWidget::setSurface(ProjectionSurface *surface) {
-			ProjectionSurface_sptr sharedSurface(surface);
-			if (m_InstrumentDisplay) {
-				m_InstrumentDisplay->setSurface(sharedSurface);
-				m_InstrumentDisplay->update();
-			}
-			if (m_simpleDisplay) {
-				m_simpleDisplay->setSurface(sharedSurface);
-				m_simpleDisplay->update();
-			}
-			UnwrappedSurface *unwrappedSurface =
-				dynamic_cast<UnwrappedSurface *>(surface);
-			if (unwrappedSurface) {
-				m_renderTab->flipUnwrappedView(unwrappedSurface->isFlippedView());
-			}
-		}
-
-		/// Return the width of the instrunemt display
-		int InstrumentWidget::getInstrumentDisplayWidth() const {
-			if (m_InstrumentDisplay) {
-				return m_InstrumentDisplay->width();
-			}
-			else if (m_simpleDisplay) {
-				return m_simpleDisplay->width();
-			}
-			return 0;
-		}
-
-		/// Return the height of the instrunemt display
-		int InstrumentWidget::getInstrumentDisplayHeight() const {
-			if (m_InstrumentDisplay) {
-				return m_InstrumentDisplay->height();
-			}
-			else if (m_simpleDisplay) {
-				return m_simpleDisplay->height();
-			}
-			return 0;
-		}
-
-		/// Redraw the instrument view
-		/// @param picking :: Set to true to update the picking image regardless the
-		/// interaction
-		///   mode of the surface.
-		void InstrumentWidget::updateInstrumentView(bool picking) {
-			if (m_InstrumentDisplay &&
-				m_instrumentDisplayLayout->currentWidget() ==
-				dynamic_cast<QWidget *>(m_InstrumentDisplay)) {
-				m_InstrumentDisplay->updateView(picking);
-			}
-			else {
-				m_simpleDisplay->updateView(picking);
-			}
-		}
-
-		/// Recalculate the colours and redraw the instrument view
-		void InstrumentWidget::updateInstrumentDetectors() {
-			QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-			if (m_InstrumentDisplay &&
-				m_instrumentDisplayLayout->currentWidget() ==
-				dynamic_cast<QWidget *>(m_InstrumentDisplay)) {
-				m_InstrumentDisplay->updateDetectors();
-			}
-			else {
-				m_simpleDisplay->updateDetectors();
-			}
-			QApplication::restoreOverrideCursor();
-		}
-
-		void InstrumentWidget::deletePeaksWorkspace(
-			Mantid::API::IPeaksWorkspace_sptr pws) {
-			this->getSurface()->deletePeaksWorkspace(pws);
-			updateInstrumentView();
-		}
-
-		/**
-		* Choose which widget to use.
-		* @param yes :: True to use the OpenGL one or false to use the Simple
-		*/
-		void InstrumentWidget::selectOpenGLDisplay(bool yes) {
-			int widgetIndex = yes ? 0 : 1;
-			const int oldIndex = m_instrumentDisplayLayout->currentIndex();
-			if (oldIndex == widgetIndex)
-				return;
-			m_instrumentDisplayLayout->setCurrentIndex(widgetIndex);
-			auto surface = getSurface();
-			if (surface) {
-				surface->updateView();
-			}
-		}
-
-		/// Public slot to toggle between the GL and simple instrument display widgets
-		void InstrumentWidget::enableOpenGL(bool on) {
-			enableGL(on);
-			emit glOptionChanged(on);
-		}
-
-		/// Private slot to toggle between the GL and simple instrument display widgets
-		void InstrumentWidget::enableGL(bool on) {
-			m_useOpenGL = on;
-			selectOpenGLDisplay(isGLEnabled());
-		}
-
-		/// True if the GL instrument display is currently on
-		bool InstrumentWidget::isGLEnabled() const { return m_useOpenGL; }
-
-		/**
-		* Create and add the tab widgets.
-		*/
-		void InstrumentWidget::createTabs(QSettings &settings) {
-			// Render Controls
-			m_renderTab = new InstrumentWidgetRenderTab(this);
-			connect(m_renderTab, SIGNAL(setAutoscaling(bool)), this,
-				SLOT(setColorMapAutoscaling(bool)));
-			connect(m_renderTab, SIGNAL(rescaleColorMap()), this, SLOT(setupColorMap()));
-			mControlsTab->addTab(m_renderTab, QString("Render"));
-			m_renderTab->loadSettings(settings);
-
-			// Pick controls
-			InstrumentWidgetPickTab *pickTab = new InstrumentWidgetPickTab(this);
-			mControlsTab->addTab(pickTab, QString("Pick"));
-			pickTab->loadSettings(settings);
-
-			// Mask controls
-			InstrumentWidgetMaskTab *maskTab = new InstrumentWidgetMaskTab(this);
-			mControlsTab->addTab(maskTab, QString("Draw"));
-			connect(maskTab, SIGNAL(executeAlgorithm(const QString &, const QString &)),
-				this, SLOT(executeAlgorithm(const QString &, const QString &)));
-			connect(m_xIntegration, SIGNAL(changed(double, double)), maskTab,
-				SLOT(changedIntegrationRange(double, double)));
-			maskTab->loadSettings(settings);
-
-			// Instrument tree controls
-			InstrumentWidgetTreeTab *treeTab = new InstrumentWidgetTreeTab(this);
-			mControlsTab->addTab(treeTab, QString("Instrument"));
-			treeTab->loadSettings(settings);
-
-			connect(mControlsTab, SIGNAL(currentChanged(int)), this,
-				SLOT(tabChanged(int)));
-
-			m_tabs << m_renderTab << pickTab << maskTab << treeTab;
-		}
-
-		/**
-		* Return a name for a group in QSettings to store InstrumentWidget
-		* configuration.
-		*/
-		QString InstrumentWidget::getSettingsGroupName() const {
-			return QString::fromAscii(InstrumentWidgetSettingsGroup);
-		}
-
-		/**
-		* Construct a name for a group in QSettings to store instrument-specific
-		* configuration.
-		*/
-		QString InstrumentWidget::getInstrumentSettingsGroupName() const {
-			return QString::fromAscii(InstrumentWidgetSettingsGroup) + "/" +
-				QString::fromStdString(
-					getInstrumentActor()->getInstrument()->getName());
-		}
-
-		bool InstrumentWidget::hasWorkspace(const std::string &wsName) const {
-			return wsName == getWorkspaceNameStdString();
-		}
-
-		void InstrumentWidget::handleWorkspaceReplacement(
-			const std::string &wsName, const boost::shared_ptr<Workspace> workspace) {
-			// Replace current workspace
-			if (hasWorkspace(wsName)) {
-				if (m_instrumentActor) {
-					// Check if it's still the same workspace underneath (as well as having
-					// the same name)
-					auto matrixWS =
-						boost::dynamic_pointer_cast<const MatrixWorkspace>(workspace);
-					bool sameWS = false;
-					try {
-						sameWS = (matrixWS == m_instrumentActor->getWorkspace());
-					}
-					catch (std::runtime_error &) {
-						// Carry on, sameWS should stay false
-					}
-
-					// try to detect if the instrument changes (unlikely if the workspace
-					// hasn't, but theoretically possible)
-					bool resetGeometry = matrixWS->getInstrument()->getNumberDetectors() !=
-						m_instrumentActor->ndetectors();
-
-					// if workspace and instrument don't change keep the scaling
-					if (sameWS && !resetGeometry) {
-						m_instrumentActor->updateColors();
-						setupColorMap();
-						updateInstrumentView();
-					}
-					else {
-						resetInstrument(resetGeometry);
-					}
-				}
-			}
-		}
-
-		/**
-		* Closes the window if the associated workspace is deleted.
-		* @param ws_name :: Name of the deleted workspace.
-		* @param workspace_ptr :: Pointer to the workspace to be deleted
-		*/
-		void InstrumentWidget::preDeleteHandle(
-			const std::string &ws_name,
-			const boost::shared_ptr<Workspace> workspace_ptr) {
-			if (hasWorkspace(ws_name)) {
-				emit preDeletingHandle();
-				close();
-				return;
-			}
-			Mantid::API::IPeaksWorkspace_sptr pws =
-				boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(workspace_ptr);
-			if (pws) {
-				deletePeaksWorkspace(pws);
-				return;
-			}
-		}
-
-		void InstrumentWidget::afterReplaceHandle(
-			const std::string &wsName, const boost::shared_ptr<Workspace> workspace) {
-			handleWorkspaceReplacement(wsName, workspace);
-		}
-
-		void InstrumentWidget::renameHandle(const std::string &oldName,
-			const std::string &newName) {
-			if (hasWorkspace(oldName)) {
-				renameWorkspace(newName);
-				setWindowTitle(QString("Instrument - ") + getWorkspaceName());
-			}
-		}
-
-		void InstrumentWidget::clearADSHandle() {
-			emit clearingHandle();
-			close();
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+// Name of the QSettings group to store the InstrumentWindw settings
+const char *InstrumentWidgetSettingsGroup = "Mantid/InstrumentWidget";
+
+/**
+* Exception type thrown when an istrument has no sample and cannot be displayed
+* in the instrument view.
+*/
+class InstrumentHasNoSampleError : public std::runtime_error {
+public:
+  InstrumentHasNoSampleError()
+      : std::runtime_error("Instrument has no sample.\nSource and sample need "
+                           "to be set in the IDF.") {}
+};
+
+/**
+* Constructor.
+*/
+InstrumentWidget::InstrumentWidget(const QString &wsName, QWidget *parent,
+                                   bool resetGeometry, bool autoscaling,
+                                   double scaleMin, double scaleMax,
+                                   bool setDefaultView)
+    : QWidget(parent), WorkspaceObserver(), m_InstrumentDisplay(nullptr),
+      m_simpleDisplay(nullptr), m_workspaceName(wsName),
+      m_instrumentActor(nullptr), m_surfaceType(FULL3D),
+      m_savedialog_dir(QString::fromStdString(
+          Mantid::Kernel::ConfigService::Instance().getString(
+              "defaultsave.directory"))),
+      mViewChanged(false), m_blocked(false),
+      m_instrumentDisplayContextMenuOn(false) {
+  setFocusPolicy(Qt::StrongFocus);
+  QVBoxLayout *mainLayout = new QVBoxLayout(this);
+  QSplitter *controlPanelLayout = new QSplitter(Qt::Horizontal);
+
+  // Add Tab control panel
+  mControlsTab = new QTabWidget(this);
+  controlPanelLayout->addWidget(mControlsTab);
+  controlPanelLayout->setSizePolicy(QSizePolicy::Expanding,
+                                    QSizePolicy::Expanding);
+
+  // Create the display widget
+  m_InstrumentDisplay = new MantidGLWidget(this);
+  m_InstrumentDisplay->installEventFilter(this);
+  connect(this, SIGNAL(enableLighting(bool)), m_InstrumentDisplay,
+          SLOT(enableLighting(bool)));
+
+  // Create simple display widget
+  m_simpleDisplay = new SimpleWidget(this);
+  m_simpleDisplay->installEventFilter(this);
+
+  QWidget *aWidget = new QWidget(this);
+  m_instrumentDisplayLayout = new QStackedLayout(aWidget);
+  m_instrumentDisplayLayout->addWidget(m_InstrumentDisplay);
+  m_instrumentDisplayLayout->addWidget(m_simpleDisplay);
+
+  controlPanelLayout->addWidget(aWidget);
+
+  mainLayout->addWidget(controlPanelLayout);
+
+  m_xIntegration = new XIntegrationControl(this);
+  mainLayout->addWidget(m_xIntegration);
+  connect(m_xIntegration, SIGNAL(changed(double, double)), this,
+          SLOT(setIntegrationRange(double, double)));
+
+  // Set the mouse/keyboard operation info and help button
+  QHBoxLayout *infoLayout = new QHBoxLayout();
+  mInteractionInfo = new QLabel();
+  infoLayout->addWidget(mInteractionInfo);
+  QPushButton *helpButton = new QPushButton("?");
+  helpButton->setMaximumWidth(25);
+  connect(helpButton, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  infoLayout->addWidget(helpButton);
+  infoLayout->setStretchFactor(mInteractionInfo, 1);
+  infoLayout->setStretchFactor(helpButton, 0);
+  mainLayout->addLayout(infoLayout);
+
+  QSettings settings;
+  settings.beginGroup(InstrumentWidgetSettingsGroup);
+
+  // Background colour
+  setBackgroundColor(
+      settings.value("BackgroundColor", QColor(0, 0, 0, 1.0)).value<QColor>());
+
+  // Create the b=tabs
+  createTabs(settings);
+
+  settings.endGroup();
+
+  // Init actions
+  m_clearPeakOverlays = new QAction("Clear peaks", this);
+  connect(m_clearPeakOverlays, SIGNAL(activated()), this,
+          SLOT(clearPeakOverlays()));
+
+  // confirmClose(app->confirmCloseInstrWindow);
+
+  setAttribute(Qt::WA_DeleteOnClose);
+
+  // Watch for the deletion of the associated workspace
+  observePreDelete();
+  observeAfterReplace();
+  observeRename();
+  observeADSClear();
+
+  const int windowWidth = 800;
+  const int tabsSize = windowWidth / 4;
+  QList<int> sizes;
+  sizes << tabsSize << windowWidth - tabsSize;
+  controlPanelLayout->setSizes(sizes);
+  controlPanelLayout->setStretchFactor(0, 0);
+  controlPanelLayout->setStretchFactor(1, 1);
+
+  resize(windowWidth, 650);
+
+  tabChanged(0);
+
+  connect(this, SIGNAL(needSetIntegrationRange(double, double)), this,
+          SLOT(setIntegrationRange(double, double)), Qt::QueuedConnection);
+  setAcceptDrops(true);
+
+  setWindowTitle(QString("Instrument - ") + m_workspaceName);
+
+  init(resetGeometry, autoscaling, scaleMin, scaleMax, setDefaultView);
+}
+
+/**
+* Destructor
+*/
+InstrumentWidget::~InstrumentWidget() {
+  if (m_instrumentActor) {
+    saveSettings();
+    delete m_instrumentActor;
+  }
+}
+
+QString InstrumentWidget::getWorkspaceName() const { return m_workspaceName; }
+
+std::string InstrumentWidget::getWorkspaceNameStdString() const {
+  return m_workspaceName.toStdString();
+}
+
+void InstrumentWidget::renameWorkspace(const std::string &workspace) {
+  m_workspaceName = QString::fromStdString(workspace);
+}
+
+/**
+* Init the geometry and colour map outside constructor to prevent creating a
+* broken MdiSubwindow.
+* Must be called straight after constructor.
+* @param resetGeometry :: Set true for resetting the view's geometry: the
+* bounding box and rotation. Default is true.
+* @param autoscaling :: True to start with autoscaling option on.
+* @param scaleMin :: Minimum value of the colormap scale. Ignored if
+* autoscaling == true.
+* @param scaleMax :: Maximum value of the colormap scale. Ignored if
+* autoscaling == true.
+* @param setDefaultView :: Set the default surface type
+*/
+void InstrumentWidget::init(bool resetGeometry, bool autoscaling,
+                            double scaleMin, double scaleMax,
+                            bool setDefaultView) {
+  // Previously in (now removed) setWorkspaceName method
+  m_instrumentActor =
+      new InstrumentActor(m_workspaceName, autoscaling, scaleMin, scaleMax);
+  m_xIntegration->setTotalRange(m_instrumentActor->minBinValue(),
+                                m_instrumentActor->maxBinValue());
+  m_xIntegration->setUnits(QString::fromStdString(
+      m_instrumentActor->getWorkspace()->getAxis(0)->unit()->caption()));
+  auto surface = getSurface();
+  if (resetGeometry || !surface) {
+    if (setDefaultView) {
+      // set the view type to the instrument's default view
+      QString defaultView = QString::fromStdString(
+          m_instrumentActor->getInstrument()->getDefaultView());
+      if (defaultView == "3D" &&
+          Mantid::Kernel::ConfigService::Instance().getString(
+              "MantidOptions.InstrumentView.UseOpenGL") != "On") {
+        // if OpenGL is switched off don't open the 3D view at start up
+        defaultView = "CYLINDRICAL_Y";
+      }
+      setSurfaceType(defaultView);
+    } else {
+      setSurfaceType(m_surfaceType); // This call must come after the
+                                     // InstrumentActor is created
+    }
+    setupColorMap();
+  } else {
+    surface->resetInstrumentActor(m_instrumentActor);
+    updateInfoText();
+  }
+}
+
+/**
+* Deletes instrument actor before re-initializing.
+* @param resetGeometry
+*/
+void InstrumentWidget::resetInstrument(bool resetGeometry) {
+  delete m_instrumentActor;
+  m_instrumentActor = nullptr;
+  init(resetGeometry, true, 0.0, 0.0, false);
+  updateInstrumentDetectors();
+}
+
+/**
+* Select the tab to be displayed
+*/
+void InstrumentWidget::selectTab(int tab) {
+  mControlsTab->setCurrentIndex(tab);
+}
+
+/**
+* Returns the named tab or the current tab if none supplied
+* @param title Optional title of a tab (default="")
+*/
+InstrumentWidgetTab *InstrumentWidget::getTab(const QString &title) const {
+  QWidget *tab(nullptr);
+  if (title.isEmpty())
+    tab = mControlsTab->currentWidget();
+  else {
+    for (int i = 0; i < mControlsTab->count(); ++i) {
+      if (mControlsTab->tabText(i) == title) {
+        tab = mControlsTab->widget(i);
+        break;
+      }
+    }
+  }
+
+  if (tab)
+    return qobject_cast<InstrumentWidgetTab *>(tab);
+  else
+    return nullptr;
+}
+
+/**
+* @param tab An enumeration for the tab to select
+* @returns A pointer to the requested tab
+*/
+InstrumentWidgetTab *InstrumentWidget::getTab(const Tab tab) const {
+  QWidget *widget = mControlsTab->widget(static_cast<int>(tab));
+  if (widget)
+    return qobject_cast<InstrumentWidgetTab *>(widget);
+  else
+    return nullptr;
+}
+
+/**
+* Opens Qt file dialog to select the filename.
+* The dialog opens in the directory used last for saving or the default user
+* directory.
+*
+* @param title :: The title of the dialog.
+* @param filters :: The filters
+* @param selectedFilter :: The selected filter.
+*/
+QString InstrumentWidget::getSaveFileName(const QString &title,
+                                          const QString &filters,
+                                          QString *selectedFilter) {
+  QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(
+      this, title, m_savedialog_dir, filters, selectedFilter);
+
+  // If its empty, they cancelled the dialog
+  if (!filename.isEmpty()) {
+    // Save the directory used
+    QFileInfo finfo(filename);
+    m_savedialog_dir = finfo.dir().path();
+  }
+  return filename;
+}
+
+/**
+* Update the info text displayed at the bottom of the window.
+*/
+void InstrumentWidget::updateInfoText() { setInfoText(getSurfaceInfoText()); }
+
+void InstrumentWidget::setSurfaceType(int type) {
+  // we cannot do 3D without OpenGL
+  if (type == FULL3D && !isGLEnabled()) {
+    QMessageBox::warning(
+        this, "Mantid - Warning",
+        "OpenGL must be enabled to render the instrument in 3D.");
+    return;
+  }
+
+  if (type < RENDERMODE_SIZE) {
+    QApplication::setOverrideCursor(Qt::WaitCursor);
+    SurfaceType surfaceType = SurfaceType(type);
+    if (!m_instrumentActor)
+      return;
+
+    ProjectionSurface *surface = getSurface().get();
+    int peakLabelPrecision = 6;
+    bool showPeakRow = true;
+    bool showPeakLabels = true;
+    bool showPeakRelativeIntensity = true;
+    if (surface) {
+      peakLabelPrecision = surface->getPeakLabelPrecision();
+      showPeakRow = surface->getShowPeakRowsFlag();
+      showPeakLabels = surface->getShowPeakLabelsFlag();
+    } else {
+      QSettings settings;
+      settings.beginGroup(InstrumentWidgetSettingsGroup);
+      peakLabelPrecision = settings.value("PeakLabelPrecision", 2).toInt();
+      showPeakRow = settings.value("ShowPeakRows", true).toBool();
+      showPeakLabels = settings.value("ShowPeakLabels", true).toBool();
+
+      // By default this is should be off for now.
+      showPeakRelativeIntensity =
+          settings.value("ShowPeakRelativeIntensities", false).toBool();
+      settings.endGroup();
+    }
+
+    // Surface factory
+    // If anything throws during surface creation, store error message here
+    QString errorMessage;
+    try {
+      Mantid::Geometry::Instrument_const_sptr instr =
+          m_instrumentActor->getInstrument();
+      Mantid::Geometry::IComponent_const_sptr sample = instr->getSample();
+      if (!sample) {
+        throw InstrumentHasNoSampleError();
+      }
+      Mantid::Kernel::V3D sample_pos = sample->getPos();
+      Mantid::Kernel::V3D axis;
+      // define the axis
+      if (surfaceType == SPHERICAL_Y || surfaceType == CYLINDRICAL_Y) {
+        axis = Mantid::Kernel::V3D(0, 1, 0);
+      } else if (surfaceType == SPHERICAL_Z || surfaceType == CYLINDRICAL_Z) {
+        axis = Mantid::Kernel::V3D(0, 0, 1);
+      } else if (surfaceType == SPHERICAL_X || surfaceType == CYLINDRICAL_X) {
+        axis = Mantid::Kernel::V3D(1, 0, 0);
+      } else // SIDE_BY_SIDE
+      {
+        axis = Mantid::Kernel::V3D(0, 0, 1);
+      }
+
+      // create the surface
+      if (surfaceType == FULL3D) {
+        surface =
+            new Projection3D(m_instrumentActor, getInstrumentDisplayWidth(),
+                             getInstrumentDisplayHeight());
+      } else if (surfaceType <= CYLINDRICAL_Z) {
+        surface = new UnwrappedCylinder(m_instrumentActor, sample_pos, axis);
+      } else if (surfaceType <= SPHERICAL_Z) {
+        surface = new UnwrappedSphere(m_instrumentActor, sample_pos, axis);
+      } else // SIDE_BY_SIDE
+      {
+        surface = new PanelsSurface(m_instrumentActor, sample_pos, axis);
+      }
+    } catch (InstrumentHasNoSampleError &) {
+      QApplication::restoreOverrideCursor();
+      throw;
+    } catch (std::exception &e) {
+      errorMessage = e.what();
+    } catch (...) {
+      errorMessage = "Unknown exception thrown.";
+    }
+    if (!errorMessage.isNull()) {
+      // if exception was thrown roll back to the current surface type.
+      QApplication::restoreOverrideCursor();
+      QMessageBox::critical(
+          this, "MantidPlot - Error",
+          "Surface cannot be created because of an exception:\n\n  " +
+              errorMessage + "\n\nPlease select a different surface type.");
+      // if suface change was initialized by the GUI this should ensure its
+      // consistency
+      emit surfaceTypeChanged(m_surfaceType);
+      return;
+    }
+    // end Surface factory
+
+    m_surfaceType = surfaceType;
+    surface->setPeakLabelPrecision(peakLabelPrecision);
+    surface->setShowPeakRowsFlag(showPeakRow);
+    surface->setShowPeakLabelsFlag(showPeakLabels);
+    surface->setShowPeakRelativeIntensityFlag(showPeakRelativeIntensity);
+    // set new surface
+    setSurface(surface);
+
+    // init tabs with new surface
+    foreach (InstrumentWidgetTab *tab, m_tabs) { tab->initSurface(); }
+
+    connect(surface, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)),
+            this, SLOT(executeAlgorithm(Mantid::API::IAlgorithm_sptr)));
+    connect(surface, SIGNAL(updateInfoText()), this, SLOT(updateInfoText()),
+            Qt::QueuedConnection);
+    QApplication::restoreOverrideCursor();
+  }
+  emit surfaceTypeChanged(type);
+  updateInfoText();
+  update();
+}
+
+/**
+* Set the surface type from a string.
+* @param typeStr :: Symbolic name of the surface type: same as the names in
+* SurfaceType enum. Caseless.
+*/
+void InstrumentWidget::setSurfaceType(const QString &typeStr) {
+  int typeIndex = 0;
+  QString upperCaseStr = typeStr.toUpper();
+  if (upperCaseStr == "FULL3D" || upperCaseStr == "3D") {
+    typeIndex = 0;
+  } else if (upperCaseStr == "CYLINDRICAL_X") {
+    typeIndex = 1;
+  } else if (upperCaseStr == "CYLINDRICAL_Y") {
+    typeIndex = 2;
+  } else if (upperCaseStr == "CYLINDRICAL_Z") {
+    typeIndex = 3;
+  } else if (upperCaseStr == "SPHERICAL_X") {
+    typeIndex = 4;
+  } else if (upperCaseStr == "SPHERICAL_Y") {
+    typeIndex = 5;
+  } else if (upperCaseStr == "SPHERICAL_Z") {
+    typeIndex = 6;
+  } else if (upperCaseStr == "SIDE_BY_SIDE") {
+    typeIndex = 7;
+  }
+  setSurfaceType(typeIndex);
+}
+
+/**
+* Update the colormap on the render tab.
+*/
+void InstrumentWidget::setupColorMap() { emit colorMapChanged(); }
+
+/**
+* Connected to QTabWidget::currentChanged signal
+*/
+void InstrumentWidget::tabChanged(int) { updateInfoText(); }
+
+/**
+* Change color map button slot. This provides the file dialog box to select
+* colormap or sets it directly a string is provided
+*/
+void InstrumentWidget::changeColormap(const QString &filename) {
+  if (!m_instrumentActor)
+    return;
+  QString fileselection;
+  // Use a file dialog if no parameter is passed
+  if (filename.isEmpty()) {
+    fileselection = MantidColorMap::loadMapDialog(
+        m_instrumentActor->getCurrentColorMap(), this);
+    if (fileselection.isEmpty())
+      return;
+  } else {
+    fileselection = QFileInfo(filename).absoluteFilePath();
+    if (!QFileInfo(fileselection).exists())
+      return;
+  }
+
+  if (!m_instrumentActor->getCurrentColorMap().isEmpty() &&
+      (fileselection == m_instrumentActor->getCurrentColorMap()))
+    return;
+
+  m_instrumentActor->loadColorMap(fileselection);
+  if (this->isVisible()) {
+    setupColorMap();
+    updateInstrumentView();
+  }
+}
+
+QString InstrumentWidget::confirmDetectorOperation(const QString &opName,
+                                                   const QString &inputWS,
+                                                   int ndets) {
+  QString message("This operation will affect %1 detectors.\nSelect output "
+                  "workspace option:");
+  QMessageBox prompt(this);
+  prompt.setWindowTitle("MantidPlot");
+  prompt.setText(message.arg(QString::number(ndets)));
+  QPushButton *replace = prompt.addButton("Replace", QMessageBox::ActionRole);
+  QPushButton *create = prompt.addButton("New", QMessageBox::ActionRole);
+  prompt.addButton("Cancel", QMessageBox::ActionRole);
+  prompt.exec();
+  QString outputWS;
+  if (prompt.clickedButton() == replace) {
+    outputWS = inputWS;
+  } else if (prompt.clickedButton() == create) {
+    outputWS = inputWS + "_" + opName;
+  } else {
+    outputWS = "";
+  }
+  return outputWS;
+}
+
+/**
+* Convert a list of integers to a comma separated string of numbers
+*/
+QString InstrumentWidget::asString(const std::vector<int> &numbers) const {
+  QString num_str;
+  std::vector<int>::const_iterator iend = numbers.end();
+  for (std::vector<int>::const_iterator itr = numbers.begin(); itr < iend;
+       ++itr) {
+    num_str += QString::number(*itr) + ",";
+  }
+  // Remove trailing comma
+  num_str.chop(1);
+  return num_str;
+}
+
+/// Set a maximum and minimum for the colour map range
+void InstrumentWidget::setColorMapRange(double minValue, double maxValue) {
+  emit colorMapRangeChanged(minValue, maxValue);
+  update();
+}
+
+/// Set the minimum value of the colour map
+void InstrumentWidget::setColorMapMinValue(double minValue) {
+  emit colorMapMinValueChanged(minValue);
+  update();
+}
+
+/// Set the maximumu value of the colour map
+void InstrumentWidget::setColorMapMaxValue(double maxValue) {
+  emit colorMapMaxValueChanged(maxValue);
+  update();
+}
+
+/**
+* This is the callback for the combo box that selects the view direction
+*/
+void InstrumentWidget::setViewDirection(const QString &input) {
+  auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
+  if (p3d) {
+    p3d->setViewDirection(input);
+  }
+  updateInstrumentView();
+  repaint();
+}
+
+/**
+*  For the scripting API. Selects a component in the tree and zooms to it.
+*  @param name The name of the component
+*/
+void InstrumentWidget::selectComponent(const QString &name) {
+  emit requestSelectComponent(name);
+}
+
+/**
+* Set the scale type programmatically
+* @param type :: The scale choice
+*/
+void InstrumentWidget::setScaleType(GraphOptions::ScaleType type) {
+  emit scaleTypeChanged(type);
+}
+
+/**
+* Set the exponent for the Power scale type
+* @param nth_power :: The exponent choice
+*/
+void InstrumentWidget::setExponent(double nth_power) {
+  emit nthPowerChanged(nth_power);
+}
+
+/**
+* This method opens a color dialog to pick the background color,
+* and then sets it.
+*/
+void InstrumentWidget::pickBackgroundColor() {
+  QColor color = QColorDialog::getColor(Qt::green, this);
+  setBackgroundColor(color);
+}
+
+/**
+* Saves the current image buffer as a png file.
+* @param filename Optional filename. Empty string raises a save dialog
+*/
+void InstrumentWidget::saveImage(QString filename) {
+  QString defaultExt = ".png";
+  QList<QByteArray> formats = QImageWriter::supportedImageFormats();
+  if (filename.isEmpty()) {
+    QListIterator<QByteArray> itr(formats);
+    QString filter("");
+    while (itr.hasNext()) {
+      filter += "*." + itr.next();
+      if (itr.hasNext()) {
+        filter += ";;";
+      }
+    }
+    QString selectedFilter = "*" + defaultExt;
+    filename = getSaveFileName("Save image ...", filter, &selectedFilter);
+
+    // If its empty, they cancelled the dialog
+    if (filename.isEmpty())
+      return;
+  }
+
+  QFileInfo finfo(filename);
+  QString ext = finfo.completeSuffix();
+
+  if (ext.isEmpty()) {
+    filename += defaultExt;
+    ext = QFileInfo(filename).completeSuffix();
+  } else {
+    if (!formats.contains(ext.toAscii())) {
+      QString msg("Unsupported file extension. Choose one of the following: ");
+      QListIterator<QByteArray> itr(formats);
+      while (itr.hasNext()) {
+        msg += itr.next() + ", ";
+      }
+      msg.chop(2); // Remove last space and comma
+      QMessageBox::warning(this, "MantidPlot", msg);
+      return;
+    }
+  }
+
+  if (isGLEnabled()) {
+    m_InstrumentDisplay->saveToFile(filename);
+  } else {
+    m_simpleDisplay->saveToFile(filename);
+  }
+}
+
+/**
+* Use the file dialog to select a filename to save grouping.
+*/
+QString InstrumentWidget::getSaveGroupingFilename() {
+  QString filename = MantidQt::API::FileDialogHandler::getSaveFileName(
+      this, "Save grouping file", m_savedialog_dir,
+      "Grouping (*.xml);;All files (*.*)");
+
+  // If its empty, they cancelled the dialog
+  if (!filename.isEmpty()) {
+    // Save the directory used
+    QFileInfo finfo(filename);
+    m_savedialog_dir = finfo.dir().path();
+  }
+
+  return filename;
+}
+
+///**
+// * Update the text display that informs the user of the current mode and
+// details about it
+// */
+void InstrumentWidget::setInfoText(const QString &text) {
+  mInteractionInfo->setText(text);
+}
+
+/**
+* Save properties of the window a persistent store
+*/
+void InstrumentWidget::saveSettings() {
+  QSettings settings;
+  settings.beginGroup(InstrumentWidgetSettingsGroup);
+  if (m_InstrumentDisplay)
+    settings.setValue("BackgroundColor",
+                      m_InstrumentDisplay->currentBackgroundColor());
+  auto surface = getSurface();
+  if (surface) {
+    // if surface is null istrument view wasn't created and there is nothing to
+    // save
+    settings.setValue("PeakLabelPrecision",
+                      getSurface()->getPeakLabelPrecision());
+    settings.setValue("ShowPeakRows", getSurface()->getShowPeakRowsFlag());
+    settings.setValue("ShowPeakLabels", getSurface()->getShowPeakLabelsFlag());
+    settings.setValue("ShowPeakRelativeIntensities",
+                      getSurface()->getShowPeakRelativeIntensityFlag());
+    foreach (InstrumentWidgetTab *tab, m_tabs) { tab->saveSettings(settings); }
+  }
+  settings.endGroup();
+}
+
+void InstrumentWidget::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/MantidPlot:_Instrument_View"));
+}
+
+void InstrumentWidget::set3DAxesState(bool on) {
+  auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
+  if (p3d) {
+    p3d->set3DAxesState(on);
+    updateInstrumentView();
+  }
+}
+
+void InstrumentWidget::finishHandle(const Mantid::API::IAlgorithm *alg) {
+  UNUSED_ARG(alg);
+  emit needSetIntegrationRange(m_instrumentActor->minBinValue(),
+                               m_instrumentActor->maxBinValue());
+  // m_instrumentActor->update();
+  // m_InstrumentDisplay->refreshView();
+}
+
+void InstrumentWidget::changeScaleType(int type) {
+  m_instrumentActor->changeScaleType(type);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+void InstrumentWidget::changeNthPower(double nth_power) {
+  m_instrumentActor->changeNthPower(nth_power);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+void InstrumentWidget::changeColorMapMinValue(double minValue) {
+  m_instrumentActor->setAutoscaling(false);
+  m_instrumentActor->setMinValue(minValue);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+/// Set the maximumu value of the colour map
+void InstrumentWidget::changeColorMapMaxValue(double maxValue) {
+  m_instrumentActor->setAutoscaling(false);
+  m_instrumentActor->setMaxValue(maxValue);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+void InstrumentWidget::changeColorMapRange(double minValue, double maxValue) {
+  m_instrumentActor->setMinMaxRange(minValue, maxValue);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+void InstrumentWidget::setWireframe(bool on) {
+  auto p3d = boost::dynamic_pointer_cast<Projection3D>(getSurface());
+  if (p3d) {
+    p3d->setWireframe(on);
+  }
+  updateInstrumentView();
+}
+
+/**
+* Set new integration range but don't update XIntegrationControl (because the
+* control calls this slot)
+*/
+void InstrumentWidget::setIntegrationRange(double xmin, double xmax) {
+  m_instrumentActor->setIntegrationRange(xmin, xmax);
+  setupColorMap();
+  updateInstrumentDetectors();
+  emit integrationRangeChanged(xmin, xmax);
+}
+
+/**
+* Set new integration range and update XIntegrationControl. To be called from
+* python.
+*/
+void InstrumentWidget::setBinRange(double xmin, double xmax) {
+  m_xIntegration->setRange(xmin, xmax);
+}
+
+/**
+* Update the display to view a selected component. The selected component
+* is visible the rest of the instrument is hidden.
+* @param id :: The component id.
+*/
+void InstrumentWidget::componentSelected(ComponentID id) {
+  auto surface = getSurface();
+  if (surface) {
+    surface->componentSelected(id);
+    // surface->updateView();
+    updateInstrumentView();
+  }
+}
+
+void InstrumentWidget::executeAlgorithm(const QString &, const QString &) {
+  // emit execMantidAlgorithm(alg_name, param_list, this);
+}
+
+void InstrumentWidget::executeAlgorithm(Mantid::API::IAlgorithm_sptr alg) {
+  try {
+    alg->executeAsync();
+  } catch (Poco::NoThreadAvailableException &) {
+    return;
+  }
+
+  return;
+}
+
+/**
+* Set the type of the view (SurfaceType).
+* @param type :: String code for the type. One of:
+* FULL3D, CYLINDRICAL_X, CYLINDRICAL_Y, CYLINDRICAL_Z, SPHERICAL_X,
+* SPHERICAL_Y, SPHERICAL_Z
+*/
+void InstrumentWidget::setViewType(const QString &type) {
+  QString type_upper = type.toUpper();
+  SurfaceType itype = FULL3D;
+  if (type_upper == "FULL3D") {
+    itype = FULL3D;
+  } else if (type_upper == "CYLINDRICAL_X") {
+    itype = CYLINDRICAL_X;
+  } else if (type_upper == "CYLINDRICAL_Y") {
+    itype = CYLINDRICAL_Y;
+  } else if (type_upper == "CYLINDRICAL_Z") {
+    itype = CYLINDRICAL_Z;
+  } else if (type_upper == "SPHERICAL_X") {
+    itype = SPHERICAL_X;
+  } else if (type_upper == "SPHERICAL_Y") {
+    itype = SPHERICAL_Y;
+  } else if (type_upper == "SPHERICAL_Z") {
+    itype = SPHERICAL_Z;
+  }
+  setSurfaceType(itype);
+}
+
+void InstrumentWidget::dragEnterEvent(QDragEnterEvent *e) {
+  QString name = e->mimeData()->objectName();
+  if (name == "MantidWorkspace") {
+    e->accept();
+  } else {
+    e->ignore();
+  }
+}
+
+void InstrumentWidget::dropEvent(QDropEvent *e) {
+  QString name = e->mimeData()->objectName();
+  if (name == "MantidWorkspace") {
+    QString text = e->mimeData()->text();
+    int endIndex = 0;
+    QStringList wsNames;
+    while (text.indexOf("[\"", endIndex) > -1) {
+      int startIndex = text.indexOf("[\"", endIndex) + 2;
+      endIndex = text.indexOf("\"]", startIndex);
+      wsNames.append(text.mid(startIndex, endIndex - startIndex));
+    }
+
+    foreach (const auto &wsName, wsNames) {
+      if (this->overlay(wsName))
+        e->accept();
+    }
+  }
+  e->ignore();
+}
+
+/**
+* Filter events directed to m_InstrumentDisplay and ContextMenuEvent in
+* particular.
+* @param obj :: Object which events will be filtered.
+* @param ev :: An ingoing event.
+*/
+bool InstrumentWidget::eventFilter(QObject *obj, QEvent *ev) {
+  if (ev->type() == QEvent::ContextMenu &&
+      (dynamic_cast<MantidGLWidget *>(obj) == m_InstrumentDisplay ||
+       dynamic_cast<SimpleWidget *>(obj) == m_simpleDisplay) &&
+      getSurface() && getSurface()->canShowContextMenu()) {
+    // an ugly way of preventing the curve in the pick tab's miniplot
+    // disappearing when
+    // cursor enters the context menu
+    m_instrumentDisplayContextMenuOn = true;
+    QMenu context(this);
+    // add tab specific actions
+    InstrumentWidgetTab *tab = getTab();
+    tab->addToDisplayContextMenu(context);
+    if (getSurface()->hasPeakOverlays()) {
+      context.addSeparator();
+      context.addAction(m_clearPeakOverlays);
+    }
+    if (!context.isEmpty()) {
+      context.exec(QCursor::pos());
+    }
+    m_instrumentDisplayContextMenuOn = false;
+    return true;
+  }
+  return QWidget::eventFilter(obj, ev);
+}
+
+/**
+* Set on / off autoscaling of the color map on the render tab.
+* @param on :: On or Off.
+*/
+void InstrumentWidget::setColorMapAutoscaling(bool on) {
+  m_instrumentActor->setAutoscaling(on);
+  setupColorMap();
+  updateInstrumentView();
+}
+
+/**
+*  Overlay a workspace with the given name
+* @param wsName The name of a workspace in the ADS
+* @returns True if the overlay was successful, false otherwise
+*/
+bool InstrumentWidget::overlay(const QString &wsName) {
+  using namespace Mantid::API;
+  Workspace_sptr workspace;
+  bool success(false);
+  try {
+    workspace = AnalysisDataService::Instance().retrieve(wsName.toStdString());
+  } catch (std::runtime_error) {
+    QMessageBox::warning(this, "MantidPlot - Warning",
+                         "No workspace called '" + wsName + "' found. ");
+    return success;
+  }
+
+  auto pws = boost::dynamic_pointer_cast<IPeaksWorkspace>(workspace);
+  if (!pws) {
+    QMessageBox::warning(this, "MantidPlot - Warning",
+                         "Work space called '" + wsName +
+                             "' is not suitable."
+                             " Please select another workspace. ");
+    return success;
+  }
+
+  auto surface = boost::dynamic_pointer_cast<UnwrappedSurface>(getSurface());
+  if (!surface) {
+    QMessageBox::warning(
+        this, "MantidPlot - Warning",
+        "Please change to an unwrapped view to see peak labels.");
+    return success;
+  }
+
+  if (pws && surface) {
+    surface->setPeaksWorkspace(pws);
+    updateInstrumentView();
+    success = true;
+  }
+  return success;
+}
+
+/**
+* Remove all peak overlays from the instrument display.
+*/
+void InstrumentWidget::clearPeakOverlays() {
+  getSurface()->clearPeakOverlays();
+  updateInstrumentView();
+}
+
+/**
+* Set the precision (significant digits) with which the HKL peak labels are
+* displayed.
+* @param n :: Precision, > 0
+*/
+void InstrumentWidget::setPeakLabelPrecision(int n) {
+  getSurface()->setPeakLabelPrecision(n);
+  updateInstrumentView();
+}
+
+/**
+* Enable or disable the show peak row flag
+* @param on :: True to show, false to hide.
+*/
+void InstrumentWidget::setShowPeakRowFlag(bool on) {
+  getSurface()->setShowPeakRowsFlag(on);
+  updateInstrumentView();
+}
+
+/**
+* Enable or disable the show peak hkl labels flag
+* @param on :: True to show, false to hide.
+*/
+void InstrumentWidget::setShowPeakLabelsFlag(bool on) {
+  getSurface()->setShowPeakLabelsFlag(on);
+  updateInstrumentView();
+}
+
+/**
+* Enable or disable indication of relative peak intensities
+*
+* @param on :: True to show, false to hide.
+*/
+void InstrumentWidget::setShowPeakRelativeIntensity(bool on) {
+  getSurface()->setShowPeakRelativeIntensityFlag(on);
+  updateInstrumentView();
+}
+
+/**
+* Set background color of the instrument display
+* @param color :: New background colour.
+*/
+void InstrumentWidget::setBackgroundColor(const QColor &color) {
+  if (m_InstrumentDisplay)
+    m_InstrumentDisplay->setBackgroundColor(color);
+}
+
+/**
+* Get the surface info string
+*/
+QString InstrumentWidget::getSurfaceInfoText() const {
+  ProjectionSurface *surface = getSurface().get();
+  return surface ? surface->getInfoText() : "";
+}
+
+/**
+* Get pointer to the projection surface
+*/
+ProjectionSurface_sptr InstrumentWidget::getSurface() const {
+  if (m_InstrumentDisplay) {
+    return m_InstrumentDisplay->getSurface();
+  } else if (m_simpleDisplay) {
+    return m_simpleDisplay->getSurface();
+  }
+  return ProjectionSurface_sptr();
+}
+
+/**
+* Set newly created projection surface
+* @param surface :: Pointer to the new surace.
+*/
+void InstrumentWidget::setSurface(ProjectionSurface *surface) {
+  ProjectionSurface_sptr sharedSurface(surface);
+  if (m_InstrumentDisplay) {
+    m_InstrumentDisplay->setSurface(sharedSurface);
+    m_InstrumentDisplay->update();
+  }
+  if (m_simpleDisplay) {
+    m_simpleDisplay->setSurface(sharedSurface);
+    m_simpleDisplay->update();
+  }
+  UnwrappedSurface *unwrappedSurface =
+      dynamic_cast<UnwrappedSurface *>(surface);
+  if (unwrappedSurface) {
+    m_renderTab->flipUnwrappedView(unwrappedSurface->isFlippedView());
+  }
+}
+
+/// Return the width of the instrunemt display
+int InstrumentWidget::getInstrumentDisplayWidth() const {
+  if (m_InstrumentDisplay) {
+    return m_InstrumentDisplay->width();
+  } else if (m_simpleDisplay) {
+    return m_simpleDisplay->width();
+  }
+  return 0;
+}
+
+/// Return the height of the instrunemt display
+int InstrumentWidget::getInstrumentDisplayHeight() const {
+  if (m_InstrumentDisplay) {
+    return m_InstrumentDisplay->height();
+  } else if (m_simpleDisplay) {
+    return m_simpleDisplay->height();
+  }
+  return 0;
+}
+
+/// Redraw the instrument view
+/// @param picking :: Set to true to update the picking image regardless the
+/// interaction
+///   mode of the surface.
+void InstrumentWidget::updateInstrumentView(bool picking) {
+  if (m_InstrumentDisplay &&
+      m_instrumentDisplayLayout->currentWidget() ==
+          dynamic_cast<QWidget *>(m_InstrumentDisplay)) {
+    m_InstrumentDisplay->updateView(picking);
+  } else {
+    m_simpleDisplay->updateView(picking);
+  }
+}
+
+/// Recalculate the colours and redraw the instrument view
+void InstrumentWidget::updateInstrumentDetectors() {
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  if (m_InstrumentDisplay &&
+      m_instrumentDisplayLayout->currentWidget() ==
+          dynamic_cast<QWidget *>(m_InstrumentDisplay)) {
+    m_InstrumentDisplay->updateDetectors();
+  } else {
+    m_simpleDisplay->updateDetectors();
+  }
+  QApplication::restoreOverrideCursor();
+}
+
+void InstrumentWidget::deletePeaksWorkspace(
+    Mantid::API::IPeaksWorkspace_sptr pws) {
+  this->getSurface()->deletePeaksWorkspace(pws);
+  updateInstrumentView();
+}
+
+/**
+* Choose which widget to use.
+* @param yes :: True to use the OpenGL one or false to use the Simple
+*/
+void InstrumentWidget::selectOpenGLDisplay(bool yes) {
+  int widgetIndex = yes ? 0 : 1;
+  const int oldIndex = m_instrumentDisplayLayout->currentIndex();
+  if (oldIndex == widgetIndex)
+    return;
+  m_instrumentDisplayLayout->setCurrentIndex(widgetIndex);
+  auto surface = getSurface();
+  if (surface) {
+    surface->updateView();
+  }
+}
+
+/// Public slot to toggle between the GL and simple instrument display widgets
+void InstrumentWidget::enableOpenGL(bool on) {
+  enableGL(on);
+  emit glOptionChanged(on);
+}
+
+/// Private slot to toggle between the GL and simple instrument display widgets
+void InstrumentWidget::enableGL(bool on) {
+  m_useOpenGL = on;
+  selectOpenGLDisplay(isGLEnabled());
+}
+
+/// True if the GL instrument display is currently on
+bool InstrumentWidget::isGLEnabled() const { return m_useOpenGL; }
+
+/**
+* Create and add the tab widgets.
+*/
+void InstrumentWidget::createTabs(QSettings &settings) {
+  // Render Controls
+  m_renderTab = new InstrumentWidgetRenderTab(this);
+  connect(m_renderTab, SIGNAL(setAutoscaling(bool)), this,
+          SLOT(setColorMapAutoscaling(bool)));
+  connect(m_renderTab, SIGNAL(rescaleColorMap()), this, SLOT(setupColorMap()));
+  mControlsTab->addTab(m_renderTab, QString("Render"));
+  m_renderTab->loadSettings(settings);
+
+  // Pick controls
+  InstrumentWidgetPickTab *pickTab = new InstrumentWidgetPickTab(this);
+  mControlsTab->addTab(pickTab, QString("Pick"));
+  pickTab->loadSettings(settings);
+
+  // Mask controls
+  InstrumentWidgetMaskTab *maskTab = new InstrumentWidgetMaskTab(this);
+  mControlsTab->addTab(maskTab, QString("Draw"));
+  connect(maskTab, SIGNAL(executeAlgorithm(const QString &, const QString &)),
+          this, SLOT(executeAlgorithm(const QString &, const QString &)));
+  connect(m_xIntegration, SIGNAL(changed(double, double)), maskTab,
+          SLOT(changedIntegrationRange(double, double)));
+  maskTab->loadSettings(settings);
+
+  // Instrument tree controls
+  InstrumentWidgetTreeTab *treeTab = new InstrumentWidgetTreeTab(this);
+  mControlsTab->addTab(treeTab, QString("Instrument"));
+  treeTab->loadSettings(settings);
+
+  connect(mControlsTab, SIGNAL(currentChanged(int)), this,
+          SLOT(tabChanged(int)));
+
+  m_tabs << m_renderTab << pickTab << maskTab << treeTab;
+}
+
+/**
+* Return a name for a group in QSettings to store InstrumentWidget
+* configuration.
+*/
+QString InstrumentWidget::getSettingsGroupName() const {
+  return QString::fromAscii(InstrumentWidgetSettingsGroup);
+}
+
+/**
+* Construct a name for a group in QSettings to store instrument-specific
+* configuration.
+*/
+QString InstrumentWidget::getInstrumentSettingsGroupName() const {
+  return QString::fromAscii(InstrumentWidgetSettingsGroup) + "/" +
+         QString::fromStdString(
+             getInstrumentActor()->getInstrument()->getName());
+}
+
+bool InstrumentWidget::hasWorkspace(const std::string &wsName) const {
+  return wsName == getWorkspaceNameStdString();
+}
+
+void InstrumentWidget::handleWorkspaceReplacement(
+    const std::string &wsName, const boost::shared_ptr<Workspace> workspace) {
+  // Replace current workspace
+  if (hasWorkspace(wsName)) {
+    if (m_instrumentActor) {
+      // Check if it's still the same workspace underneath (as well as having
+      // the same name)
+      auto matrixWS =
+          boost::dynamic_pointer_cast<const MatrixWorkspace>(workspace);
+      bool sameWS = false;
+      try {
+        sameWS = (matrixWS == m_instrumentActor->getWorkspace());
+      } catch (std::runtime_error &) {
+        // Carry on, sameWS should stay false
+      }
+
+      // try to detect if the instrument changes (unlikely if the workspace
+      // hasn't, but theoretically possible)
+      bool resetGeometry = matrixWS->getInstrument()->getNumberDetectors() !=
+                           m_instrumentActor->ndetectors();
+
+      // if workspace and instrument don't change keep the scaling
+      if (sameWS && !resetGeometry) {
+        m_instrumentActor->updateColors();
+        setupColorMap();
+        updateInstrumentView();
+      } else {
+        resetInstrument(resetGeometry);
+      }
+    }
+  }
+}
+
+/**
+* Closes the window if the associated workspace is deleted.
+* @param ws_name :: Name of the deleted workspace.
+* @param workspace_ptr :: Pointer to the workspace to be deleted
+*/
+void InstrumentWidget::preDeleteHandle(
+    const std::string &ws_name,
+    const boost::shared_ptr<Workspace> workspace_ptr) {
+  if (hasWorkspace(ws_name)) {
+    emit preDeletingHandle();
+    close();
+    return;
+  }
+  Mantid::API::IPeaksWorkspace_sptr pws =
+      boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(workspace_ptr);
+  if (pws) {
+    deletePeaksWorkspace(pws);
+    return;
+  }
+}
+
+void InstrumentWidget::afterReplaceHandle(
+    const std::string &wsName, const boost::shared_ptr<Workspace> workspace) {
+  handleWorkspaceReplacement(wsName, workspace);
+}
+
+void InstrumentWidget::renameHandle(const std::string &oldName,
+                                    const std::string &newName) {
+  if (hasWorkspace(oldName)) {
+    renameWorkspace(newName);
+    setWindowTitle(QString("Instrument - ") + getWorkspaceName());
+  }
+}
+
+void InstrumentWidget::clearADSHandle() {
+  emit clearingHandle();
+  close();
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetPickTab.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetPickTab.cpp
index c11070ecb2314017dcbcc88785c6d4a149c8a0a2..5ac1261a8439b222f25876a9eeaf5031c63318d9 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetPickTab.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetPickTab.cpp
@@ -49,1658 +49,1588 @@
 #include <cmath>
 #include <algorithm>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/// to be used in std::transform
-		struct Sqrt
-		{
-			double operator()(double x)
-			{
-				return sqrt(x);
-			}
-		};
-
-		/**
-		* Constructor.
-		* @param instrWidget :: Parent InstrumentWidget.
-		*/
-		InstrumentWidgetPickTab::InstrumentWidgetPickTab(InstrumentWidget* instrWidget) :
-			InstrumentWidgetTab(instrWidget),
-			m_freezePlot(false),
-			m_tubeXUnitsCache(0),
-			m_plotTypeCache(0)
-		{
-
-			// connect to InstrumentWindow signals
-			connect(m_instrWidget, SIGNAL(integrationRangeChanged(double, double)), this, SLOT(changedIntegrationRange(double, double)));
-
-			m_plotSum = true;
-
-			QVBoxLayout* layout = new QVBoxLayout(this);
-
-			// set up the selection display
-			m_selectionInfoDisplay = new QTextEdit(this);
-
-			// set up the plot widget
-			m_plot = new OneCurvePlot(this);
-			m_plot->setYAxisLabelRotation(-90);
-			m_plot->setXScale(0, 1);
-			m_plot->setYScale(-1.2, 1.2);
-			connect(m_plot, SIGNAL(showContextMenu()), this, SLOT(plotContextMenu()));
-
-			// Plot context menu actions
-			m_sumDetectors = new QAction("Sum", this);
-			m_sumDetectors->setCheckable(true);
-			m_sumDetectors->setChecked(true);
-			m_integrateTimeBins = new QAction("Integrate", this);
-			m_integrateTimeBins->setCheckable(true);
-			m_summationType = new QActionGroup(this);
-			m_summationType->addAction(m_sumDetectors);
-			m_summationType->addAction(m_integrateTimeBins);
-			m_logY = new QAction("Y log scale", this);
-			m_linearY = new QAction("Y linear scale", this);
-			m_yScale = new QActionGroup(this);
-			m_yScale->addAction(m_linearY);
-			m_yScale->addAction(m_logY);
-			m_logY->setCheckable(true);
-			m_linearY->setCheckable(true);
-			m_linearY->setChecked(true);
-			connect(m_sumDetectors, SIGNAL(triggered()), this, SLOT(sumDetectors()));
-			connect(m_integrateTimeBins, SIGNAL(triggered()), this, SLOT(integrateTimeBins()));
-			connect(m_logY, SIGNAL(triggered()), m_plot, SLOT(setYLogScale()));
-			connect(m_linearY, SIGNAL(triggered()), m_plot, SLOT(setYLinearScale()));
-
-			m_unitsMapper = new QSignalMapper(this);
-
-			m_detidUnits = new QAction("Detector ID", this);
-			m_detidUnits->setCheckable(true);
-			m_unitsMapper->setMapping(m_detidUnits, DetectorPlotController::DETECTOR_ID);
-			connect(m_detidUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
-
-			m_lengthUnits = new QAction("Tube length", this);
-			m_lengthUnits->setCheckable(true);
-			m_unitsMapper->setMapping(m_lengthUnits, DetectorPlotController::LENGTH);
-			connect(m_lengthUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
-
-			m_phiUnits = new QAction("Phi", this);
-			m_phiUnits->setCheckable(true);
-			m_unitsMapper->setMapping(m_phiUnits, DetectorPlotController::PHI);
-			connect(m_phiUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
-
-			m_outOfPlaneAngleUnits = new QAction("Out of plane angle", this);
-			m_outOfPlaneAngleUnits->setCheckable(true);
-			m_unitsMapper->setMapping(m_outOfPlaneAngleUnits, DetectorPlotController::OUT_OF_PLANE_ANGLE);
-			connect(m_outOfPlaneAngleUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
-
-			m_unitsGroup = new QActionGroup(this);
-			m_unitsGroup->addAction(m_detidUnits);
-			m_unitsGroup->addAction(m_lengthUnits);
-			m_unitsGroup->addAction(m_phiUnits); // re #4169 disabled until fixed or removed
-			m_unitsGroup->addAction(m_outOfPlaneAngleUnits);
-			connect(m_unitsMapper, SIGNAL(mapped(int)), this, SLOT(setTubeXUnits(int)));
-
-			// Instrument display context menu actions
-			m_storeCurve = new QAction("Store curve", this);
-			connect(m_storeCurve, SIGNAL(triggered()), this, SLOT(storeCurve()));
-			m_savePlotToWorkspace = new QAction("Save plot to workspace", this);
-			connect(m_savePlotToWorkspace, SIGNAL(triggered()), this, SLOT(savePlotToWorkspace()));
-
-			CollapsibleStack* panelStack = new CollapsibleStack(this);
-			m_infoPanel = panelStack->addPanel("Selection", m_selectionInfoDisplay);
-			m_plotPanel = panelStack->addPanel("Name", m_plot);
-
-			m_selectionType = Single;
-
-			m_infoController = NULL;
-			m_plotController = NULL;
-
-			m_activeTool = new QLabel(this);
-			// set up the tool bar
-
-			m_zoom = new QPushButton();
-			m_zoom->setCheckable(true);
-			m_zoom->setAutoExclusive(true);
-			m_zoom->setIcon(QIcon(":/PickTools/zoom.png"));
-			m_zoom->setToolTip("Zoom in and out");
-
-			m_one = new QPushButton();
-			m_one->setCheckable(true);
-			m_one->setAutoExclusive(true);
-			m_one->setChecked(true);
-			m_one->setToolTip("Select single pixel");
-			m_one->setIcon(QIcon(":/PickTools/selection-pointer.png"));
-
-			m_tube = new QPushButton();
-			m_tube->setCheckable(true);
-			m_tube->setAutoExclusive(true);
-			m_tube->setIcon(QIcon(":/PickTools/selection-tube.png"));
-			m_tube->setToolTip("Select whole tube");
-
-			m_rectangle = new QPushButton();
-			m_rectangle->setCheckable(true);
-			m_rectangle->setAutoExclusive(true);
-			m_rectangle->setIcon(QIcon(":/PickTools/selection-box.png"));
-			m_rectangle->setToolTip("Draw a rectangle");
-
-			m_ellipse = new QPushButton();
-			m_ellipse->setCheckable(true);
-			m_ellipse->setAutoExclusive(true);
-			m_ellipse->setIcon(QIcon(":/PickTools/selection-circle.png"));
-			m_ellipse->setToolTip("Draw a ellipse");
-
-			m_ring_ellipse = new QPushButton();
-			m_ring_ellipse->setCheckable(true);
-			m_ring_ellipse->setAutoExclusive(true);
-			m_ring_ellipse->setIcon(QIcon(":/PickTools/selection-circle-ring.png"));
-			m_ring_ellipse->setToolTip("Draw an elliptical ring");
-
-			m_ring_rectangle = new QPushButton();
-			m_ring_rectangle->setCheckable(true);
-			m_ring_rectangle->setAutoExclusive(true);
-			m_ring_rectangle->setIcon(QIcon(":/PickTools/selection-box-ring.png"));
-			m_ring_rectangle->setToolTip("Draw a rectangular ring");
-
-			m_free_draw = new QPushButton();
-			m_free_draw->setCheckable(true);
-			m_free_draw->setAutoExclusive(true);
-			m_free_draw->setIcon(QIcon(":/PickTools/brush.png"));
-			m_free_draw->setToolTip("Draw an arbitrary shape");
-
-			m_edit = new QPushButton();
-			m_edit->setCheckable(true);
-			m_edit->setAutoExclusive(true);
-			m_edit->setIcon(QIcon(":/PickTools/selection-edit.png"));
-			m_edit->setToolTip("Edit a shape");
-
-			m_peak = new QPushButton();
-			m_peak->setCheckable(true);
-			m_peak->setAutoExclusive(true);
-			m_peak->setIcon(QIcon(":/PickTools/selection-peak.png"));
-			m_peak->setToolTip("Add single crystal peak");
-
-			m_peakSelect = new QPushButton();
-			m_peakSelect->setCheckable(true);
-			m_peakSelect->setAutoExclusive(true);
-			m_peakSelect->setIcon(QIcon(":/PickTools/eraser.png"));
-			m_peakSelect->setToolTip("Erase single crystal peak(s)");
-
-			QGridLayout* toolBox = new QGridLayout();
-			toolBox->addWidget(m_zoom, 0, 0);
-			toolBox->addWidget(m_edit, 0, 1);
-			toolBox->addWidget(m_ellipse, 0, 2);
-			toolBox->addWidget(m_rectangle, 0, 3);
-			toolBox->addWidget(m_ring_ellipse, 0, 4);
-			toolBox->addWidget(m_ring_rectangle, 0, 5);
-			toolBox->addWidget(m_free_draw, 0, 6);
-			toolBox->addWidget(m_one, 1, 0);
-			toolBox->addWidget(m_tube, 1, 1);
-			toolBox->addWidget(m_peak, 1, 2);
-			toolBox->addWidget(m_peakSelect, 1, 3);
-                        toolBox->setColumnStretch(6, 1);
-                        toolBox->setSpacing(2);
-                        connect(m_zoom, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_one, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_tube, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_peak, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_peakSelect, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_ring_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_ring_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_free_draw, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-			connect(m_edit, SIGNAL(clicked()), this, SLOT(setSelectionType()));
-
-			// lay out the widgets
-			layout->addWidget(m_activeTool);
-			layout->addLayout(toolBox);
-			layout->addWidget(panelStack);
-
-		}
-
-		/**
-		* Returns true if the plot can be updated when the mouse moves over detectors
-		*/
-		bool InstrumentWidgetPickTab::canUpdateTouchedDetector()const
-		{
-			return !m_peak->isChecked();
-		}
-
-
-		/**
-		* Display the miniplot's context menu.
-		*/
-		void InstrumentWidgetPickTab::plotContextMenu()
-		{
-			QMenu context(this);
-
-			auto plotType = m_plotController->getPlotType();
-
-			if (plotType == DetectorPlotController::TubeSum ||
-				plotType == DetectorPlotController::TubeIntegral)
-			{
-				// only for multiple detector selectors
-				context.addActions(m_summationType->actions());
-				m_sumDetectors->setChecked(plotType == DetectorPlotController::TubeSum);
-				m_integrateTimeBins->setChecked(plotType != DetectorPlotController::TubeSum);
-				m_integrateTimeBins->setEnabled(true);
-				context.addSeparator();
-			}
-
-			if (m_plot->hasStored())
-			{
-				// the remove menu
-				QMenu *removeCurves = new QMenu("Remove", this);
-				QSignalMapper *signalMapper = new QSignalMapper(this);
-				QStringList labels = m_plot->getLabels();
-				foreach(QString label, labels)
-				{
-					QColor c = m_plot->getCurveColor(label);
-					QPixmap pixmap(16, 2);
-					pixmap.fill(c);
-					QAction *remove = new QAction(QIcon(pixmap), label, removeCurves);
-					removeCurves->addAction(remove);
-					connect(remove, SIGNAL(triggered()), signalMapper, SLOT(map()));
-					signalMapper->setMapping(remove, label);
-				}
-				connect(signalMapper, SIGNAL(mapped(const QString &)),
-					this, SLOT(removeCurve(const QString &)));
-				context.addMenu(removeCurves);
-			}
-
-			// the axes menu
-			QMenu* axes = new QMenu("Axes", this);
-			axes->addActions(m_yScale->actions());
-			if (m_plot->isYLogScale())
-			{
-				m_logY->setChecked(true);
-			}
-			else
-			{
-				m_linearY->setChecked(true);
-			}
-
-			// Tube x units menu options
-			if (plotType == DetectorPlotController::TubeIntegral)
-			{
-				axes->addSeparator();
-				axes->addActions(m_unitsGroup->actions());
-				auto tubeXUnits = m_plotController->getTubeXUnits();
-				switch (tubeXUnits)
-				{
-				case DetectorPlotController::DETECTOR_ID:         m_detidUnits->setChecked(true); break;
-				case DetectorPlotController::LENGTH:              m_lengthUnits->setChecked(true); break;
-				case DetectorPlotController::PHI:                 m_phiUnits->setChecked(true); break;
-				case DetectorPlotController::OUT_OF_PLANE_ANGLE:  m_outOfPlaneAngleUnits->setChecked(true); break;
-				default: m_detidUnits->setChecked(true);
-				}
-			}
-			context.addMenu(axes);
-
-			// save plot to workspace
-			if (m_plot->hasStored() || m_plot->hasCurve())
-			{
-				context.addAction(m_savePlotToWorkspace);
-			}
-
-			// show menu
-			context.exec(QCursor::pos());
-		}
-
-		/**
-		* Update the plot caption. The captions shows the selection type.
-		*/
-		void InstrumentWidgetPickTab::setPlotCaption()
-		{
-			m_plotPanel->setCaption(m_plotController->getPlotCaption());
-		}
-
-		/**
-		* Switch to the detectors summing regime.
-		*/
-		void InstrumentWidgetPickTab::sumDetectors()
-		{
-			m_plotController->setPlotType(DetectorPlotController::TubeSum);
-			m_plotController->updatePlot();
-			setPlotCaption();
-		}
-
-		/**
-		* Switch to the time bin integration regime.
-		*/
-		void InstrumentWidgetPickTab::integrateTimeBins()
-		{
-			m_plotController->setPlotType(DetectorPlotController::TubeIntegral);
-			m_plotController->updatePlot();
-			setPlotCaption();
-		}
-
-		/**
-		* Set the selection type according to which tool button is checked.
-		*/
-		void InstrumentWidgetPickTab::setSelectionType()
-		{
-			ProjectionSurface::InteractionMode surfaceMode = ProjectionSurface::PickSingleMode;
-			auto plotType = m_plotController->getPlotType();
-			if (m_zoom->isChecked())
-			{
-				m_selectionType = Single;
-				m_activeTool->setText("Tool: Navigation");
-				surfaceMode = ProjectionSurface::MoveMode;
-			}
-			else if (m_one->isChecked())
-			{
-				m_selectionType = Single;
-				m_activeTool->setText("Tool: Pixel selection");
-				surfaceMode = ProjectionSurface::PickSingleMode;
-				plotType = DetectorPlotController::Single;
-			}
-			else if (m_tube->isChecked())
-			{
-				m_selectionType = Tube;
-				m_activeTool->setText("Tool: Tube/bank selection");
-				surfaceMode = ProjectionSurface::PickTubeMode;
-				if (plotType < DetectorPlotController::TubeSum)
-				{
-					plotType = DetectorPlotController::TubeSum;
-				}
-			}
-			else if (m_peak->isChecked())
-			{
-				m_selectionType = AddPeak;
-				m_activeTool->setText("Tool: Add a single crystal peak");
-				surfaceMode = ProjectionSurface::AddPeakMode;
-				plotType = DetectorPlotController::Single;
-			}
-			else if (m_peakSelect->isChecked())
-			{
-				m_selectionType = ErasePeak;
-				m_activeTool->setText("Tool: Erase crystal peak(s)");
-				surfaceMode = ProjectionSurface::ErasePeakMode;
-			}
-			else if (m_rectangle->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Rectangle");
-				surfaceMode = ProjectionSurface::DrawRegularMode;
-				plotType = DetectorPlotController::Single;
-				m_instrWidget->getSurface()->startCreatingShape2D("rectangle", Qt::green, QColor(255, 255, 255, 80));
-			}
-			else if (m_ellipse->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Ellipse");
-				surfaceMode = ProjectionSurface::DrawRegularMode;
-				plotType = DetectorPlotController::Single;
-				m_instrWidget->getSurface()->startCreatingShape2D("ellipse", Qt::green, QColor(255, 255, 255, 80));
-			}
-			else if (m_ring_ellipse->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Elliptical ring");
-				surfaceMode = ProjectionSurface::DrawRegularMode;
-				plotType = DetectorPlotController::Single;
-				m_instrWidget->getSurface()->startCreatingShape2D("ring ellipse", Qt::green, QColor(255, 255, 255, 80));
-			}
-			else if (m_ring_rectangle->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Rectangular ring");
-				surfaceMode = ProjectionSurface::DrawRegularMode;
-				plotType = DetectorPlotController::Single;
-				m_instrWidget->getSurface()->startCreatingShape2D("ring rectangle", Qt::green, QColor(255, 255, 255, 80));
-			}
-			else if (m_free_draw->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Arbitrary shape");
-				surfaceMode = ProjectionSurface::DrawFreeMode;
-				plotType = DetectorPlotController::Single;
-				m_instrWidget->getSurface()->startCreatingFreeShape(Qt::green, QColor(255, 255, 255, 80));
-			}
-			else if (m_edit->isChecked())
-			{
-				m_selectionType = Draw;
-				m_activeTool->setText("Tool: Shape editing");
-				surfaceMode = ProjectionSurface::DrawRegularMode;
-				plotType = DetectorPlotController::Single;
-			}
-			m_plotController->setPlotType(plotType);
-			auto surface = m_instrWidget->getSurface();
-			if (surface)
-			{
-				surface->setInteractionMode(surfaceMode);
-				auto interactionMode = surface->getInteractionMode();
-				if (interactionMode == ProjectionSurface::DrawRegularMode || interactionMode == ProjectionSurface::MoveMode)
-				{
-					updatePlotMultipleDetectors();
-				}
-				else
-				{
-					m_plot->clearAll();
-					m_plot->replot();
-				}
-				setPlotCaption();
-			}
-			m_instrWidget->updateInfoText();
-		}
-
-		/**
-		* Respond to the show event.
-		*/
-		void InstrumentWidgetPickTab::showEvent(QShowEvent *)
-		{
-			// Make the state of the display view consistent with the current selection type
-			setSelectionType();
-			// make sure picking updated
-			m_instrWidget->updateInstrumentView(true);
-			m_instrWidget->getSurface()->changeBorderColor(getShapeBorderColor());
-		}
-
-		/**
-		* Keep current curve permanently displayed on the plot.
-		*/
-		void InstrumentWidgetPickTab::storeCurve()
-		{
-			m_plot->store();
-		}
-
-		/**
-		* Remove a stored curve.
-		* @param label :: The label of the curve to remove
-		*/
-		void InstrumentWidgetPickTab::removeCurve(const QString & label)
-		{
-			m_plot->removeCurve(label);
-			m_plot->replot();
-		}
-
-		/**
-		* Set the x units for the integrated tube plot.
-		* @param units :: The x units in terms of TubeXUnits.
-		*/
-		void InstrumentWidgetPickTab::setTubeXUnits(int units)
-		{
-			if (units < 0 || units >= DetectorPlotController::NUMBER_OF_UNITS) return;
-			auto tubeXUnits = static_cast<DetectorPlotController::TubeXUnits>(units);
-			m_plotController->setTubeXUnits(tubeXUnits);
-			m_plotController->updatePlot();
-		}
-
-
-		/**
-		* Get the color of the overlay shapes in this tab.
-		* @return
-		*/
-		QColor InstrumentWidgetPickTab::getShapeBorderColor() const
-		{
-			return QColor(Qt::green);
-		}
-
-
-
-		/**
-		* Do something when the time bin integraion range has changed.
-		*/
-		void InstrumentWidgetPickTab::changedIntegrationRange(double, double)
-		{
-			m_plotController->updatePlot();
-			auto surface = m_instrWidget->getSurface();
-			if (surface)
-			{
-				auto interactionMode = surface->getInteractionMode();
-				if (interactionMode == ProjectionSurface::DrawRegularMode || interactionMode == ProjectionSurface::MoveMode)
-				{
-					updatePlotMultipleDetectors();
-				}
-			}
-		}
-
-		void InstrumentWidgetPickTab::initSurface()
-		{
-			ProjectionSurface *surface = getSurface().get();
-			connect(surface, SIGNAL(singleComponentTouched(size_t)), this, SLOT(singleComponentTouched(size_t)));
-			connect(surface, SIGNAL(singleComponentPicked(size_t)), this, SLOT(singleComponentPicked(size_t)));
-			connect(surface, SIGNAL(peaksWorkspaceAdded()), this, SLOT(updateSelectionInfoDisplay()));
-			connect(surface, SIGNAL(peaksWorkspaceDeleted()), this, SLOT(updateSelectionInfoDisplay()));
-			connect(surface, SIGNAL(shapeCreated()), this, SLOT(shapeCreated()));
-			connect(surface, SIGNAL(shapeChangeFinished()), this, SLOT(updatePlotMultipleDetectors()));
-			connect(surface, SIGNAL(shapesCleared()), this, SLOT(updatePlotMultipleDetectors()));
-			connect(surface, SIGNAL(shapesRemoved()), this, SLOT(updatePlotMultipleDetectors()));
-			Projection3D *p3d = dynamic_cast<Projection3D*>(surface);
-			if (p3d)
-			{
-				connect(p3d, SIGNAL(finishedMove()), this, SLOT(updatePlotMultipleDetectors()));
-			}
-			m_infoController = new ComponentInfoController(this, m_instrWidget->getInstrumentActor(), m_selectionInfoDisplay);
-			m_plotController = new DetectorPlotController(this, m_instrWidget->getInstrumentActor(), m_plot);
-			m_plotController->setTubeXUnits(static_cast<DetectorPlotController::TubeXUnits>(m_tubeXUnitsCache));
-			m_plotController->setPlotType(static_cast<DetectorPlotController::PlotType>(m_plotTypeCache));
-		}
-
-		/**
-		* Return current ProjectionSurface.
-		*/
-		boost::shared_ptr<ProjectionSurface> InstrumentWidgetPickTab::getSurface() const
-		{
-			return m_instrWidget->getSurface();
-		}
-
-		/**
-		* Save tab's persistent settings to the provided QSettings instance
-		*/
-		void InstrumentWidgetPickTab::saveSettings(QSettings &settings) const
-		{
-			settings.setValue("TubeXUnits", m_plotController->getTubeXUnits());
-			settings.setValue("PlotType", m_plotController->getPlotType());
-		}
-
-		/**
-		* Restore (read and apply) tab's persistent settings from the provided QSettings instance
-		*/
-		void InstrumentWidgetPickTab::loadSettings(const QSettings &settings)
-		{
-			// loadSettings is called when m_plotController is not created yet.
-			// Cache the settings and apply them later
-			m_tubeXUnitsCache = settings.value("TubeXUnits", 0).toInt();
-			m_plotTypeCache = settings.value("PlotType", DetectorPlotController::Single).toInt();
-		}
-
-		/**
-		* Fill in the context menu.
-		* @param context :: A menu to fill.
-		*/
-		bool InstrumentWidgetPickTab::addToDisplayContextMenu(QMenu &context) const
-		{
-			m_freezePlot = true;
-			bool res = false;
-			if (m_plot->hasCurve())
-			{
-				context.addAction(m_storeCurve);
-				res = true;
-			}
-			if (m_plot->hasStored() || m_plot->hasCurve())
-			{
-				context.addAction(m_savePlotToWorkspace);
-				res = true;
-			}
-			return res;
-		}
-
-		/**
-		* Select a tool on the tab
-		* @param tool One of the enumerated tool types, @see ToolType
-		*/
-		void InstrumentWidgetPickTab::selectTool(const ToolType tool)
-		{
-			switch (tool)
-			{
-			case Zoom: m_zoom->setChecked(true);
-				break;
-			case PixelSelect: m_one->setChecked(true);
-				break;
-			case TubeSelect: m_tube->setChecked(true);
-				break;
-			case PeakSelect: m_peak->setChecked(true);
-				break;
-			case PeakErase: m_peakSelect->setChecked(true);
-				break;
-			case DrawRectangle: m_rectangle->setChecked(true);
-				break;
-			case DrawEllipse: m_ellipse->setChecked(true);
-				break;
-			case DrawFree: m_free_draw->setChecked(true);
-				break;
-			case EditShape: m_edit->setChecked(true);
-				break;
-			default: throw std::invalid_argument("Invalid tool type.");
-			}
-			setSelectionType();
-		}
-
-
-		void InstrumentWidgetPickTab::singleComponentTouched(size_t pickID)
-		{
-			if (canUpdateTouchedDetector())
-			{
-				m_infoController->displayInfo(pickID);
-				m_plotController->setPlotData(pickID);
-				m_plotController->updatePlot();
-			}
-		}
-
-		void InstrumentWidgetPickTab::singleComponentPicked(size_t pickID)
-		{
-			m_infoController->displayInfo(pickID);
-			m_plotController->setPlotData(pickID);
-			m_plotController->updatePlot();
-		}
-
-		/**
-		* Update the selection display using currently selected detector.
-		* Updates non-detector information on it.
-		*/
-		void InstrumentWidgetPickTab::updateSelectionInfoDisplay()
-		{
-			//updateSelectionInfo(m_currentDetID);
-		}
-
-		/**
-		* Respond to the shapeCreated signal from the surface.
-		*/
-		void InstrumentWidgetPickTab::shapeCreated()
-		{
-			if (!isVisible()) return;
-			if (!m_free_draw->isChecked())
-			{
-				selectTool(EditShape);
-			}
-		}
-
-		/**
-		* Update the mini-plot with information from multiple detector
-		* selected with drawn shapes.
-		*/
-		void InstrumentWidgetPickTab::updatePlotMultipleDetectors()
-		{
-			if (!isVisible()) return;
-			ProjectionSurface &surface = *getSurface();
-			if (surface.hasMasks())
-			{
-				QList<int> dets;
-				surface.getMaskedDetectors(dets);
-				m_plotController->setPlotData(dets);
-			}
-			else
-			{
-				m_plotController->clear();
-			}
-			m_plot->replot();
-		}
-
-		/**
-		* Save data plotted on the miniplot into a MatrixWorkspace.
-		*/
-		void InstrumentWidgetPickTab::savePlotToWorkspace()
-		{
-			m_plotController->savePlotToWorkspace();
-		}
-
-		//=====================================================================================//
-
-		/**
-		* Create and setup iteself.
-		* @param tab :: QObject parent - the tab.
-		* @param instrActor :: A pointer to the InstrumentActor instance.
-		* @param infoDisplay :: Widget on which to display the information.
-		*/
-		ComponentInfoController::ComponentInfoController(InstrumentWidgetPickTab *tab, InstrumentActor* instrActor, QTextEdit* infoDisplay) :
-			QObject(tab),
-			m_tab(tab),
-			m_instrActor(instrActor),
-			m_selectionInfoDisplay(infoDisplay),
-			m_freezePlot(false),
-			m_instrWidgetBlocked(false),
-			m_currentPickID(-1)
-		{
-		}
-
-		/**
-		* Display info on a component refered to by a pick ID.
-		* @param pickID :: A pick ID of a component.
-		*/
-		void ComponentInfoController::displayInfo(size_t pickID)
-		{
-			if (m_freezePlot)
-			{// freeze the plot for one update
-				m_freezePlot = false;
-				pickID = m_currentPickID;
-			}
-
-			QString text = "";
-			int detid = m_instrActor->getDetID(pickID);
-			if (detid >= 0)
-			{
-				text += displayDetectorInfo(detid);
-			}
-			else if (auto componentID = m_instrActor->getComponentID(pickID))
-			{
-				text += displayNonDetectorInfo(componentID);
-			}
-			else
-			{
-				clear();
-			}
-			// display info about peak overlays
-			text += getPeakOverlayInfo();
-
-			if (!text.isEmpty())
-			{
-				m_selectionInfoDisplay->setText(text);
-			}
-			else
-			{
-				clear();
-			}
-		}
-
-		/**
-		* Return string with info on a detector.
-		* @param detid :: A detector ID.
-		*/
-		QString ComponentInfoController::displayDetectorInfo(Mantid::detid_t detid)
-		{
-			if (m_instrWidgetBlocked)
-			{
-				clear();
-				return "";
-			}
-
-			QString text;
-			if (detid >= 0)
-			{
-				// collect info about selected detector and add it to text
-				Mantid::Geometry::IDetector_const_sptr det;
-				try
-				{
-					det = m_instrActor->getInstrument()->getDetector(detid);
-				}
-				catch (...)
-				{
-					// if this slot is called during instrument window deletion
-					// expect exceptions thrown
-					return "";
-				}
-
-				text = "Selected detector: " + QString::fromStdString(det->getName()) + "\n";
-				text += "Detector ID: " + QString::number(detid) + '\n';
-				QString wsIndex;
-				try {
-					wsIndex = QString::number(m_instrActor->getWorkspaceIndex(detid));
-				}
-				catch (Mantid::Kernel::Exception::NotFoundError &) {
-					// Detector doesn't have a workspace index relating to it
-					wsIndex = "None";
-				}
-				text += "Workspace index: " + wsIndex + '\n';
-				Mantid::Kernel::V3D pos = det->getPos();
-				text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) + "," + QString::number(pos.Z()) + '\n';
-				double r, t, p;
-				pos.getSpherical(r, t, p);
-				text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," + QString::number(p) + '\n';
-				Mantid::Geometry::ICompAssembly_const_sptr parent = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(det->getParent());
-				if (parent)
-				{
-					QString textpath;
-					while (parent)
-					{
-						textpath = "/" + QString::fromStdString(parent->getName()) + textpath;
-						parent = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent->getParent());
-					}
-					text += "Component path:" + textpath + "/" + QString::fromStdString(det->getName()) + '\n';
-				}
-				const double integrated = m_instrActor->getIntegratedCounts(detid);
-				const QString counts = integrated == -1.0 ? "N/A" : QString::number(integrated);
-				text += "Counts: " + counts + '\n';
-				// display info about peak overlays
-				text += getParameterInfo(det);
-			}
-			return text;
-		}
-
-		/**
-		* string with information about a selected non-detector component (such as choppers, etc).
-		* @param compID :: A component ID for a component to display.
-		*/
-		QString ComponentInfoController::displayNonDetectorInfo(Mantid::Geometry::ComponentID compID)
-		{
-			auto component = m_instrActor->getInstrument()->getComponentByID(compID);
-			QString text = "Selected component: ";
-			text += QString::fromStdString(component->getName()) + '\n';
-			Mantid::Kernel::V3D pos = component->getPos();
-			text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) + "," + QString::number(pos.Z()) + '\n';
-			double r, t, p;
-			pos.getSpherical(r, t, p);
-			text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," + QString::number(p) + '\n';
-			text += getParameterInfo(component);
-			return text;
-		}
-
-		/**
-		* Form a string for output from the components instrument parameters
-		*/
-		QString ComponentInfoController::getParameterInfo(Mantid::Geometry::IComponent_const_sptr comp)
-		{
-			QString text = "";
-			std::map<Mantid::Geometry::ComponentID, std::vector<std::string> > mapCmptToNameVector;
-
-			auto paramNames = comp->getParameterNamesByComponent();
-			for (auto itParamName = paramNames.begin(); itParamName != paramNames.end(); ++itParamName)
-			{
-				//build the data structure I need Map comp id -> vector of names
-				std::string paramName = itParamName->first;
-				Mantid::Geometry::ComponentID paramCompId = itParamName->second;
-				//attempt to insert this will fail silently if the key already exists
-				if (mapCmptToNameVector.find(paramCompId) == mapCmptToNameVector.end())
-				{
-					mapCmptToNameVector.emplace(paramCompId, std::vector<std::string>());
-				}
-				//get the vector out and add the name
-				mapCmptToNameVector[paramCompId].push_back(paramName);
-			}
-
-			//walk out from the selected component
-			Mantid::Geometry::IComponent_const_sptr paramComp = comp;
-			while (paramComp)
-			{
-				auto& compParamNames = mapCmptToNameVector[paramComp->getComponentID()];
-				if (compParamNames.size() > 0)
-				{
-					text += QString::fromStdString("\nParameters from: " + paramComp->getName() + "\n");
-					std::sort(compParamNames.begin(), compParamNames.end(), Mantid::Kernel::CaseInsensitiveStringComparator());
-					for (auto itParamName = compParamNames.begin(); itParamName != compParamNames.end(); ++itParamName)
-					{
-						std::string paramName = *itParamName;
-						//no need to search recursively as we are asking from the matching component
-						std::string paramValue = paramComp->getParameterAsString(paramName, false);
-						if (paramValue != "")
-						{
-							text += QString::fromStdString(paramName + ": " + paramValue + "\n");
-						}
-					}
-				}
-				paramComp = paramComp->getParent();
-			}
-
-			return text;
-		}
-
-		/**
-		* Return non-detector info to be displayed in the selection info display.
-		*/
-		QString ComponentInfoController::getPeakOverlayInfo()
-		{
-			QString text;
-			QStringList overlays = m_tab->getSurface()->getPeaksWorkspaceNames();
-			if (!overlays.isEmpty())
-			{
-				text += "Peaks:\n" + overlays.join("\n") + "\n";
-			}
-			return text;
-		}
-
-		/**
-		* Clear the information display.
-		*/
-		void ComponentInfoController::clear()
-		{
-			m_selectionInfoDisplay->clear();
-		}
-
-		//=====================================================================================//
-
-		/**
-		* Constructor.
-		* @param tab :: The parent tab.
-		* @param instrActor :: A pointer to the InstrumentActor.
-		* @param plot :: The plot widget.
-		*/
-		DetectorPlotController::DetectorPlotController(InstrumentWidgetPickTab *tab, InstrumentActor* instrActor, OneCurvePlot* plot) :
-			QObject(tab),
-			m_tab(tab),
-			m_instrActor(instrActor),
-			m_plot(plot),
-			m_plotType(Single),
-			m_enabled(true),
-			m_tubeXUnits(DETECTOR_ID),
-			m_currentDetID(-1)
-		{
-			connect(m_plot, SIGNAL(clickedAt(double, double)), this, SLOT(addPeak(double, double)));
-		}
-
-		/**
-		* Update the miniplot for a selected detector. The curve data depend on the
-		* plot type.
-		* @param pickID :: A pick ID of an instrument component.
-		*/
-		void DetectorPlotController::setPlotData(size_t pickID)
-		{
-			m_currentDetID = -1;
-
-			if (m_plotType == DetectorSum)
-			{
-				m_plotType = Single;
-			}
-
-			int detid = m_instrActor->getDetID(pickID);
-
-			if (!m_enabled)
-			{
-				m_plot->clearCurve();
-				return;
-			}
-
-			if (detid >= 0)
-			{
-				if (m_plotType == Single)
-				{
-					m_currentDetID = detid;
-					plotSingle(detid);
-				}
-				else if (m_plotType == TubeSum || m_plotType == TubeIntegral)
-				{
-					plotTube(detid);
-				}
-				else
-				{
-					throw std::logic_error("setPlotData: Unexpected plot type.");
-				}
-			}
-			else
-			{
-				m_plot->clearCurve();
-			}
-		}
-
-		/**
-		* Set curev data from multiple detectors: sum their spectra.
-		* @param detIDs :: A list of detector IDs.
-		*/
-		void DetectorPlotController::setPlotData(QList<int> detIDs)
-		{
-			setPlotType(DetectorSum);
-			clear();
-			std::vector<double> x, y;
-			QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-			m_instrActor->sumDetectors(detIDs, x, y, static_cast<size_t>(m_plot->width()));
-			QApplication::restoreOverrideCursor();
-			if (!x.empty())
-			{
-				m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()), m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
-			}
-			m_plot->setLabel("multiple");
-		}
-
-		/**
-		* Update the miniplot for a selected detector.
-		*/
-		void DetectorPlotController::updatePlot()
-		{
-			m_plot->recalcAxisDivs();
-			m_plot->replot();
-		}
-
-		/**
-		* Clear the plot.
-		*/
-		void DetectorPlotController::clear()
-		{
-			m_plot->clearCurve();
-			m_plot->clearPeakLabels();
-		}
-
-		/**
-		* Plot data for a detector.
-		* @param detid :: ID of the detector to be plotted.
-		*/
-		void DetectorPlotController::plotSingle(int detid)
-		{
-
-			clear();
-			std::vector<double> x, y;
-			prepareDataForSinglePlot(detid, x, y);
-			if (x.empty() || y.empty()) return;
-
-			// set the data 
-			m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()), m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
-			m_plot->setLabel("Detector " + QString::number(detid));
-
-			// find any markers
-			auto surface = m_tab->getSurface();
-			if (surface)
-			{
-				QList<PeakMarker2D*> markers = surface->getMarkersWithID(detid);
-				foreach(PeakMarker2D* marker, markers)
-				{
-					m_plot->addPeakLabel(marker);
-				}
-			}
-		}
-
-		/**
-		* Plot data integrated either over the detectors in a tube or over time bins.
-		* If m_plotSum == true the miniplot displays the accumulated data in a tube against time of flight.
-		* If m_plotSum == false the miniplot displays the data integrated over the time bins. The values are
-		* plotted against the length of the tube, but the units on the x-axis can be one of the following:
-		*   DETECTOR_ID
-		*   LENGTH
-		*   PHI
-		* The units can be set with setTubeXUnits(...) method.
-		* @param detid :: A detector id. The miniplot will display data for a component containing the detector
-		*   with this id.
-		*/
-		void DetectorPlotController::plotTube(int detid)
-		{
-			Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
-			Mantid::Geometry::IDetector_const_sptr det = m_instrActor->getInstrument()->getDetector(detid);
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
-			Mantid::Geometry::ICompAssembly_const_sptr ass = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent);
-			if (parent && ass)
-			{
-				if (m_plotType == TubeSum) // plot sums over detectors vs time bins
-				{
-					plotTubeSums(detid);
-				}
-				else // plot detector integrals vs detID or a function of detector position in the tube
-				{
-					assert(m_plotType == TubeIntegral);
-					plotTubeIntegrals(detid);
-				}
-			}
-			else
-			{
-				m_plot->clearCurve();
-			}
-		}
-
-		/**
-		* Plot the accumulated data in a tube against time of flight.
-		* @param detid :: A detector id. The miniplot will display data for a component containing the detector
-		*   with this id.
-		*/
-		void DetectorPlotController::plotTubeSums(int detid)
-		{
-			std::vector<double> x, y;
-			prepareDataForSumsPlot(detid, x, y);
-			if (x.empty() || y.empty())
-			{
-				clear();
-				return;
-			}
-			Mantid::Geometry::IDetector_const_sptr det = m_instrActor->getInstrument()->getDetector(detid);
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
-			QString label = QString::fromStdString(parent->getName()) + " (" + QString::number(detid) + ") Sum";
-			m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()), m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
-			m_plot->setLabel(label);
-		}
-
-		/**
-		* Plot the data integrated over the time bins. The values are
-		* plotted against the length of the tube, but the units on the x-axis can be one of the following:
-		*   DETECTOR_ID
-		*   LENGTH
-		*   PHI
-		* The units can be set with setTubeXUnits(...) method.
-		* @param detid :: A detector id. The miniplot will display data for a component containing the detector
-		*   with this id.
-		*/
-		void DetectorPlotController::plotTubeIntegrals(int detid)
-		{
-			Mantid::Geometry::IDetector_const_sptr det = m_instrActor->getInstrument()->getDetector(detid);
-			std::vector<double> x, y;
-			prepareDataForIntegralsPlot(detid, x, y);
-			if (x.empty() || y.empty())
-			{
-				clear();
-				return;
-			}
-			auto xAxisCaption = getTubeXUnitsName();
-			auto xAxisUnits = getTubeXUnitsUnits();
-			if (!xAxisUnits.isEmpty())
-			{
-				xAxisCaption += " (" + xAxisUnits + ")";
-			}
-			m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()), xAxisCaption.toStdString());
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
-			// curve label: "tube_name (detid) Integrals"
-			// detid is included to distiguish tubes with the same name
-			QString label = QString::fromStdString(parent->getName()) + " (" + QString::number(detid) + ") Integrals/" + getTubeXUnitsName();
-			m_plot->setLabel(label);
-		}
-
-		/**
-		* Prepare data for plotting a spectrum of a single detector.
-		* @param detid :: ID of the detector to be plotted.
-		* @param x :: Vector of x coordinates (output)
-		* @param y :: Vector of y coordinates (output)
-		* @param err :: Optional pointer to a vector of errors (output)
-		*/
-		void DetectorPlotController::prepareDataForSinglePlot(
-			int detid,
-			std::vector<double>&x,
-			std::vector<double>&y,
-			std::vector<double>* err)
-		{
-			Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
-			size_t wi;
-			try {
-				wi = m_instrActor->getWorkspaceIndex(detid);
-			}
-			catch (Mantid::Kernel::Exception::NotFoundError &) {
-				return; // Detector doesn't have a workspace index relating to it
-			}
-			// get the data
-			const Mantid::MantidVec& X = ws->readX(wi);
-			const Mantid::MantidVec& Y = ws->readY(wi);
-			const Mantid::MantidVec& E = ws->readE(wi);
-
-			// find min and max for x
-			size_t imin, imax;
-			m_instrActor->getBinMinMaxIndex(wi, imin, imax);
-
-			x.assign(X.begin() + imin, X.begin() + imax);
-			y.assign(Y.begin() + imin, Y.begin() + imax);
-			if (ws->isHistogramData())
-			{
-				// calculate the bin centres
-				std::transform(x.begin(), x.end(), X.begin() + imin + 1, x.begin(), std::plus<double>());
-				std::transform(x.begin(), x.end(), x.begin(), std::bind2nd(std::divides<double>(), 2.0));
-			}
-
-			if (err)
-			{
-				err->assign(E.begin() + imin, E.begin() + imax);
-			}
-		}
-
-		/**
-		* Prepare data for plotting accumulated data in a tube against time of flight.
-		* @param detid :: A detector id. The miniplot will display data for a component containing the detector
-		*   with this id.
-		* @param x :: Vector of x coordinates (output)
-		* @param y :: Vector of y coordinates (output)
-		* @param err :: Optional pointer to a vector of errors (output)
-		*/
-		void DetectorPlotController::prepareDataForSumsPlot(
-			int detid,
-			std::vector<double>&x,
-			std::vector<double>&y,
-			std::vector<double>* err)
-		{
-			Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
-			Mantid::Geometry::IDetector_const_sptr det = m_instrActor->getInstrument()->getDetector(detid);
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
-			Mantid::Geometry::ICompAssembly_const_sptr ass = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent);
-			size_t wi;
-			try {
-				wi = m_instrActor->getWorkspaceIndex(detid);
-			}
-			catch (Mantid::Kernel::Exception::NotFoundError &) {
-				return; // Detector doesn't have a workspace index relating to it
-			}
-			size_t imin, imax;
-			m_instrActor->getBinMinMaxIndex(wi, imin, imax);
-
-			const Mantid::MantidVec& X = ws->readX(wi);
-			x.assign(X.begin() + imin, X.begin() + imax);
-			if (ws->isHistogramData())
-			{
-				// calculate the bin centres
-				std::transform(x.begin(), x.end(), X.begin() + imin + 1, x.begin(), std::plus<double>());
-				std::transform(x.begin(), x.end(), x.begin(), std::bind2nd(std::divides<double>(), 2.0));
-			}
-			y.resize(x.size(), 0);
-			if (err)
-			{
-				err->resize(x.size(), 0);
-			}
-
-			const int n = ass->nelements();
-			for (int i = 0; i < n; ++i)
-			{
-				Mantid::Geometry::IDetector_sptr idet = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[i]);
-				if (idet)
-				{
-					try {
-						size_t index = m_instrActor->getWorkspaceIndex(idet->getID());
-						const Mantid::MantidVec& Y = ws->readY(index);
-						std::transform(y.begin(), y.end(), Y.begin() + imin, y.begin(), std::plus<double>());
-						if (err)
-						{
-							const Mantid::MantidVec& E = ws->readE(index);
-							std::vector<double> tmp;
-							tmp.assign(E.begin() + imin, E.begin() + imax);
-							std::transform(tmp.begin(), tmp.end(), tmp.begin(), tmp.begin(), std::multiplies<double>());
-							std::transform(err->begin(), err->end(), tmp.begin(), err->begin(), std::plus<double>());
-						}
-					}
-					catch (Mantid::Kernel::Exception::NotFoundError &) {
-						continue; // Detector doesn't have a workspace index relating to it
-					}
-				}
-			}
-
-			if (err)
-			{
-				std::transform(err->begin(), err->end(), err->begin(), Sqrt());
-			}
-		}
-
-		/**
-		* Prepare data for plotting the data integrated over the time bins. The values are
-		* plotted against the length of the tube, but the units on the x-axis can be one of the following:
-		*   DETECTOR_ID
-		*   LENGTH
-		*   PHI
-		*   OUT_OF_PLANE_ANGLE
-		* The units can be set with setTubeXUnits(...) method.
-		* @param detid :: A detector id. The miniplot will display data for a component containing the detector
-		*   with this id.
-		* @param x :: Vector of x coordinates (output)
-		* @param y :: Vector of y coordinates (output)
-		* @param err :: Optional pointer to a vector of errors (output)
-		*/
-		void DetectorPlotController::prepareDataForIntegralsPlot(
-			int detid,
-			std::vector<double>&x,
-			std::vector<double>&y,
-			std::vector<double>* err)
-		{
-
-#define PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED     x.clear();\
-y.clear();\
-if ( err ) err->clear();\
-return;
-
-			Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
-
-			// Does the instrument definition specify that psi should be offset.
-			std::vector<std::string> parameters = ws->getInstrument()->getStringParameter("offset-phi");
-			const bool bOffsetPsi = (!parameters.empty()) && std::find(parameters.begin(), parameters.end(), "Always") != parameters.end();
-
-			Mantid::Geometry::IDetector_const_sptr det = m_instrActor->getInstrument()->getDetector(detid);
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
-			Mantid::Geometry::ICompAssembly_const_sptr ass = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent);
-			size_t wi;
-			try {
-				wi = m_instrActor->getWorkspaceIndex(detid);
-			}
-			catch (Mantid::Kernel::Exception::NotFoundError &) {
-				return; // Detector doesn't have a workspace index relating to it
-			}
-			// imin and imax give the bin integration range
-			size_t imin, imax;
-			m_instrActor->getBinMinMaxIndex(wi, imin, imax);
-
-			Mantid::Kernel::V3D samplePos = m_instrActor->getInstrument()->getSample()->getPos();
-
-			const int n = ass->nelements();
-			if (n == 0)
-			{
-				// don't think it's ever possible but...
-				throw std::runtime_error("PickTab miniplot: empty instrument assembly");
-			}
-			if (n == 1)
-			{
-				// if assembly has just one element there is nothing to plot
-				PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
-			}
-			// collect and sort xy pairs in xymap
-			std::map<double, double> xymap, errmap;
-			// get the first detector in the tube for lenth calculation
-			Mantid::Geometry::IDetector_sptr idet0 = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[0]);
-			if (!idet0)
-			{
-				// it's not an assembly of detectors,
-				// could be a mixture of monitors and other components
-				PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
-			}
-			Mantid::Kernel::V3D normal = (*ass)[1]->getPos() - idet0->getPos();
-			normal.normalize();
-			for (int i = 0; i < n; ++i)
-			{
-				Mantid::Geometry::IDetector_sptr idet = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[i]);
-				if (idet)
-				{
-					try {
-						const int id = idet->getID();
-						// get the x-value for detector idet
-						double xvalue = 0;
-						switch (m_tubeXUnits)
-						{
-						case LENGTH: xvalue = idet->getDistance(*idet0); break;
-						case PHI: xvalue = bOffsetPsi ? idet->getPhiOffset(M_PI) : idet->getPhi(); break;
-						case OUT_OF_PLANE_ANGLE:
-						{
-							Mantid::Kernel::V3D pos = idet->getPos();
-							xvalue = getOutOfPlaneAngle(pos, samplePos, normal);
-							break;
-						}
-						default: xvalue = static_cast<double>(id);
-						}
-						size_t index = m_instrActor->getWorkspaceIndex(id);
-						// get the y-value for detector idet
-						const Mantid::MantidVec& Y = ws->readY(index);
-						double sum = std::accumulate(Y.begin() + imin, Y.begin() + imax, 0);
-						xymap[xvalue] = sum;
-						if (err)
-						{
-							const Mantid::MantidVec& E = ws->readE(index);
-							std::vector<double> tmp(imax - imin);
-							// take squares of the errors
-							std::transform(E.begin() + imin, E.begin() + imax, E.begin() + imin, tmp.begin(), std::multiplies<double>());
-							// sum them
-							double sum = std::accumulate(tmp.begin(), tmp.end(), 0);
-							// take sqrt
-							errmap[xvalue] = sqrt(sum);
-						}
-					}
-					catch (Mantid::Kernel::Exception::NotFoundError &) {
-						continue; // Detector doesn't have a workspace index relating to it
-					}
-				}
-			}
-			if (!xymap.empty())
-			{
-				// set the plot curve data
-				x.resize(xymap.size());
-				y.resize(xymap.size());
-				std::map<double, double>::const_iterator xy = xymap.begin();
-				for (size_t i = 0; xy != xymap.end(); ++xy, ++i)
-				{
-					x[i] = xy->first;
-					y[i] = xy->second;
-				}
-				if (err)
-				{
-					err->resize(errmap.size());
-					std::map<double, double>::const_iterator e = errmap.begin();
-					for (size_t i = 0; e != errmap.end(); ++e, ++i)
-					{
-						(*err)[i] = e->second;
-					}
-				}
-			}
-			else
-			{
-				PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
-			}
+namespace MantidQt {
+namespace MantidWidgets {
+
+/// to be used in std::transform
+struct Sqrt {
+  double operator()(double x) { return sqrt(x); }
+};
+
+/**
+* Constructor.
+* @param instrWidget :: Parent InstrumentWidget.
+*/
+InstrumentWidgetPickTab::InstrumentWidgetPickTab(InstrumentWidget *instrWidget)
+    : InstrumentWidgetTab(instrWidget), m_freezePlot(false),
+      m_tubeXUnitsCache(0), m_plotTypeCache(0) {
+
+  // connect to InstrumentWindow signals
+  connect(m_instrWidget, SIGNAL(integrationRangeChanged(double, double)), this,
+          SLOT(changedIntegrationRange(double, double)));
+
+  m_plotSum = true;
+
+  QVBoxLayout *layout = new QVBoxLayout(this);
+
+  // set up the selection display
+  m_selectionInfoDisplay = new QTextEdit(this);
+
+  // set up the plot widget
+  m_plot = new OneCurvePlot(this);
+  m_plot->setYAxisLabelRotation(-90);
+  m_plot->setXScale(0, 1);
+  m_plot->setYScale(-1.2, 1.2);
+  connect(m_plot, SIGNAL(showContextMenu()), this, SLOT(plotContextMenu()));
+
+  // Plot context menu actions
+  m_sumDetectors = new QAction("Sum", this);
+  m_sumDetectors->setCheckable(true);
+  m_sumDetectors->setChecked(true);
+  m_integrateTimeBins = new QAction("Integrate", this);
+  m_integrateTimeBins->setCheckable(true);
+  m_summationType = new QActionGroup(this);
+  m_summationType->addAction(m_sumDetectors);
+  m_summationType->addAction(m_integrateTimeBins);
+  m_logY = new QAction("Y log scale", this);
+  m_linearY = new QAction("Y linear scale", this);
+  m_yScale = new QActionGroup(this);
+  m_yScale->addAction(m_linearY);
+  m_yScale->addAction(m_logY);
+  m_logY->setCheckable(true);
+  m_linearY->setCheckable(true);
+  m_linearY->setChecked(true);
+  connect(m_sumDetectors, SIGNAL(triggered()), this, SLOT(sumDetectors()));
+  connect(m_integrateTimeBins, SIGNAL(triggered()), this,
+          SLOT(integrateTimeBins()));
+  connect(m_logY, SIGNAL(triggered()), m_plot, SLOT(setYLogScale()));
+  connect(m_linearY, SIGNAL(triggered()), m_plot, SLOT(setYLinearScale()));
+
+  m_unitsMapper = new QSignalMapper(this);
+
+  m_detidUnits = new QAction("Detector ID", this);
+  m_detidUnits->setCheckable(true);
+  m_unitsMapper->setMapping(m_detidUnits, DetectorPlotController::DETECTOR_ID);
+  connect(m_detidUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
+
+  m_lengthUnits = new QAction("Tube length", this);
+  m_lengthUnits->setCheckable(true);
+  m_unitsMapper->setMapping(m_lengthUnits, DetectorPlotController::LENGTH);
+  connect(m_lengthUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
+
+  m_phiUnits = new QAction("Phi", this);
+  m_phiUnits->setCheckable(true);
+  m_unitsMapper->setMapping(m_phiUnits, DetectorPlotController::PHI);
+  connect(m_phiUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));
+
+  m_outOfPlaneAngleUnits = new QAction("Out of plane angle", this);
+  m_outOfPlaneAngleUnits->setCheckable(true);
+  m_unitsMapper->setMapping(m_outOfPlaneAngleUnits,
+                            DetectorPlotController::OUT_OF_PLANE_ANGLE);
+  connect(m_outOfPlaneAngleUnits, SIGNAL(triggered()), m_unitsMapper,
+          SLOT(map()));
+
+  m_unitsGroup = new QActionGroup(this);
+  m_unitsGroup->addAction(m_detidUnits);
+  m_unitsGroup->addAction(m_lengthUnits);
+  m_unitsGroup->addAction(
+      m_phiUnits); // re #4169 disabled until fixed or removed
+  m_unitsGroup->addAction(m_outOfPlaneAngleUnits);
+  connect(m_unitsMapper, SIGNAL(mapped(int)), this, SLOT(setTubeXUnits(int)));
+
+  // Instrument display context menu actions
+  m_storeCurve = new QAction("Store curve", this);
+  connect(m_storeCurve, SIGNAL(triggered()), this, SLOT(storeCurve()));
+  m_savePlotToWorkspace = new QAction("Save plot to workspace", this);
+  connect(m_savePlotToWorkspace, SIGNAL(triggered()), this,
+          SLOT(savePlotToWorkspace()));
+
+  CollapsibleStack *panelStack = new CollapsibleStack(this);
+  m_infoPanel = panelStack->addPanel("Selection", m_selectionInfoDisplay);
+  m_plotPanel = panelStack->addPanel("Name", m_plot);
+
+  m_selectionType = Single;
+
+  m_infoController = NULL;
+  m_plotController = NULL;
+
+  m_activeTool = new QLabel(this);
+  // set up the tool bar
+
+  m_zoom = new QPushButton();
+  m_zoom->setCheckable(true);
+  m_zoom->setAutoExclusive(true);
+  m_zoom->setIcon(QIcon(":/PickTools/zoom.png"));
+  m_zoom->setToolTip("Zoom in and out");
+
+  m_one = new QPushButton();
+  m_one->setCheckable(true);
+  m_one->setAutoExclusive(true);
+  m_one->setChecked(true);
+  m_one->setToolTip("Select single pixel");
+  m_one->setIcon(QIcon(":/PickTools/selection-pointer.png"));
+
+  m_tube = new QPushButton();
+  m_tube->setCheckable(true);
+  m_tube->setAutoExclusive(true);
+  m_tube->setIcon(QIcon(":/PickTools/selection-tube.png"));
+  m_tube->setToolTip("Select whole tube");
+
+  m_rectangle = new QPushButton();
+  m_rectangle->setCheckable(true);
+  m_rectangle->setAutoExclusive(true);
+  m_rectangle->setIcon(QIcon(":/PickTools/selection-box.png"));
+  m_rectangle->setToolTip("Draw a rectangle");
+
+  m_ellipse = new QPushButton();
+  m_ellipse->setCheckable(true);
+  m_ellipse->setAutoExclusive(true);
+  m_ellipse->setIcon(QIcon(":/PickTools/selection-circle.png"));
+  m_ellipse->setToolTip("Draw a ellipse");
+
+  m_ring_ellipse = new QPushButton();
+  m_ring_ellipse->setCheckable(true);
+  m_ring_ellipse->setAutoExclusive(true);
+  m_ring_ellipse->setIcon(QIcon(":/PickTools/selection-circle-ring.png"));
+  m_ring_ellipse->setToolTip("Draw an elliptical ring");
+
+  m_ring_rectangle = new QPushButton();
+  m_ring_rectangle->setCheckable(true);
+  m_ring_rectangle->setAutoExclusive(true);
+  m_ring_rectangle->setIcon(QIcon(":/PickTools/selection-box-ring.png"));
+  m_ring_rectangle->setToolTip("Draw a rectangular ring");
+
+  m_free_draw = new QPushButton();
+  m_free_draw->setCheckable(true);
+  m_free_draw->setAutoExclusive(true);
+  m_free_draw->setIcon(QIcon(":/PickTools/brush.png"));
+  m_free_draw->setToolTip("Draw an arbitrary shape");
+
+  m_edit = new QPushButton();
+  m_edit->setCheckable(true);
+  m_edit->setAutoExclusive(true);
+  m_edit->setIcon(QIcon(":/PickTools/selection-edit.png"));
+  m_edit->setToolTip("Edit a shape");
+
+  m_peak = new QPushButton();
+  m_peak->setCheckable(true);
+  m_peak->setAutoExclusive(true);
+  m_peak->setIcon(QIcon(":/PickTools/selection-peak.png"));
+  m_peak->setToolTip("Add single crystal peak");
+
+  m_peakSelect = new QPushButton();
+  m_peakSelect->setCheckable(true);
+  m_peakSelect->setAutoExclusive(true);
+  m_peakSelect->setIcon(QIcon(":/PickTools/eraser.png"));
+  m_peakSelect->setToolTip("Erase single crystal peak(s)");
+
+  QGridLayout *toolBox = new QGridLayout();
+  toolBox->addWidget(m_zoom, 0, 0);
+  toolBox->addWidget(m_edit, 0, 1);
+  toolBox->addWidget(m_ellipse, 0, 2);
+  toolBox->addWidget(m_rectangle, 0, 3);
+  toolBox->addWidget(m_ring_ellipse, 0, 4);
+  toolBox->addWidget(m_ring_rectangle, 0, 5);
+  toolBox->addWidget(m_free_draw, 0, 6);
+  toolBox->addWidget(m_one, 1, 0);
+  toolBox->addWidget(m_tube, 1, 1);
+  toolBox->addWidget(m_peak, 1, 2);
+  toolBox->addWidget(m_peakSelect, 1, 3);
+  toolBox->setColumnStretch(6, 1);
+  toolBox->setSpacing(2);
+  connect(m_zoom, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_one, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_tube, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_peak, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_peakSelect, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_ring_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_ring_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_free_draw, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+  connect(m_edit, SIGNAL(clicked()), this, SLOT(setSelectionType()));
+
+  // lay out the widgets
+  layout->addWidget(m_activeTool);
+  layout->addLayout(toolBox);
+  layout->addWidget(panelStack);
+}
+
+/**
+* Returns true if the plot can be updated when the mouse moves over detectors
+*/
+bool InstrumentWidgetPickTab::canUpdateTouchedDetector() const {
+  return !m_peak->isChecked();
+}
+
+/**
+* Display the miniplot's context menu.
+*/
+void InstrumentWidgetPickTab::plotContextMenu() {
+  QMenu context(this);
+
+  auto plotType = m_plotController->getPlotType();
+
+  if (plotType == DetectorPlotController::TubeSum ||
+      plotType == DetectorPlotController::TubeIntegral) {
+    // only for multiple detector selectors
+    context.addActions(m_summationType->actions());
+    m_sumDetectors->setChecked(plotType == DetectorPlotController::TubeSum);
+    m_integrateTimeBins->setChecked(plotType !=
+                                    DetectorPlotController::TubeSum);
+    m_integrateTimeBins->setEnabled(true);
+    context.addSeparator();
+  }
+
+  if (m_plot->hasStored()) {
+    // the remove menu
+    QMenu *removeCurves = new QMenu("Remove", this);
+    QSignalMapper *signalMapper = new QSignalMapper(this);
+    QStringList labels = m_plot->getLabels();
+    foreach (QString label, labels) {
+      QColor c = m_plot->getCurveColor(label);
+      QPixmap pixmap(16, 2);
+      pixmap.fill(c);
+      QAction *remove = new QAction(QIcon(pixmap), label, removeCurves);
+      removeCurves->addAction(remove);
+      connect(remove, SIGNAL(triggered()), signalMapper, SLOT(map()));
+      signalMapper->setMapping(remove, label);
+    }
+    connect(signalMapper, SIGNAL(mapped(const QString &)), this,
+            SLOT(removeCurve(const QString &)));
+    context.addMenu(removeCurves);
+  }
+
+  // the axes menu
+  QMenu *axes = new QMenu("Axes", this);
+  axes->addActions(m_yScale->actions());
+  if (m_plot->isYLogScale()) {
+    m_logY->setChecked(true);
+  } else {
+    m_linearY->setChecked(true);
+  }
+
+  // Tube x units menu options
+  if (plotType == DetectorPlotController::TubeIntegral) {
+    axes->addSeparator();
+    axes->addActions(m_unitsGroup->actions());
+    auto tubeXUnits = m_plotController->getTubeXUnits();
+    switch (tubeXUnits) {
+    case DetectorPlotController::DETECTOR_ID:
+      m_detidUnits->setChecked(true);
+      break;
+    case DetectorPlotController::LENGTH:
+      m_lengthUnits->setChecked(true);
+      break;
+    case DetectorPlotController::PHI:
+      m_phiUnits->setChecked(true);
+      break;
+    case DetectorPlotController::OUT_OF_PLANE_ANGLE:
+      m_outOfPlaneAngleUnits->setChecked(true);
+      break;
+    default:
+      m_detidUnits->setChecked(true);
+    }
+  }
+  context.addMenu(axes);
+
+  // save plot to workspace
+  if (m_plot->hasStored() || m_plot->hasCurve()) {
+    context.addAction(m_savePlotToWorkspace);
+  }
+
+  // show menu
+  context.exec(QCursor::pos());
+}
+
+/**
+* Update the plot caption. The captions shows the selection type.
+*/
+void InstrumentWidgetPickTab::setPlotCaption() {
+  m_plotPanel->setCaption(m_plotController->getPlotCaption());
+}
+
+/**
+* Switch to the detectors summing regime.
+*/
+void InstrumentWidgetPickTab::sumDetectors() {
+  m_plotController->setPlotType(DetectorPlotController::TubeSum);
+  m_plotController->updatePlot();
+  setPlotCaption();
+}
+
+/**
+* Switch to the time bin integration regime.
+*/
+void InstrumentWidgetPickTab::integrateTimeBins() {
+  m_plotController->setPlotType(DetectorPlotController::TubeIntegral);
+  m_plotController->updatePlot();
+  setPlotCaption();
+}
+
+/**
+* Set the selection type according to which tool button is checked.
+*/
+void InstrumentWidgetPickTab::setSelectionType() {
+  ProjectionSurface::InteractionMode surfaceMode =
+      ProjectionSurface::PickSingleMode;
+  auto plotType = m_plotController->getPlotType();
+  if (m_zoom->isChecked()) {
+    m_selectionType = Single;
+    m_activeTool->setText("Tool: Navigation");
+    surfaceMode = ProjectionSurface::MoveMode;
+  } else if (m_one->isChecked()) {
+    m_selectionType = Single;
+    m_activeTool->setText("Tool: Pixel selection");
+    surfaceMode = ProjectionSurface::PickSingleMode;
+    plotType = DetectorPlotController::Single;
+  } else if (m_tube->isChecked()) {
+    m_selectionType = Tube;
+    m_activeTool->setText("Tool: Tube/bank selection");
+    surfaceMode = ProjectionSurface::PickTubeMode;
+    if (plotType < DetectorPlotController::TubeSum) {
+      plotType = DetectorPlotController::TubeSum;
+    }
+  } else if (m_peak->isChecked()) {
+    m_selectionType = AddPeak;
+    m_activeTool->setText("Tool: Add a single crystal peak");
+    surfaceMode = ProjectionSurface::AddPeakMode;
+    plotType = DetectorPlotController::Single;
+  } else if (m_peakSelect->isChecked()) {
+    m_selectionType = ErasePeak;
+    m_activeTool->setText("Tool: Erase crystal peak(s)");
+    surfaceMode = ProjectionSurface::ErasePeakMode;
+  } else if (m_rectangle->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Rectangle");
+    surfaceMode = ProjectionSurface::DrawRegularMode;
+    plotType = DetectorPlotController::Single;
+    m_instrWidget->getSurface()->startCreatingShape2D(
+        "rectangle", Qt::green, QColor(255, 255, 255, 80));
+  } else if (m_ellipse->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Ellipse");
+    surfaceMode = ProjectionSurface::DrawRegularMode;
+    plotType = DetectorPlotController::Single;
+    m_instrWidget->getSurface()->startCreatingShape2D(
+        "ellipse", Qt::green, QColor(255, 255, 255, 80));
+  } else if (m_ring_ellipse->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Elliptical ring");
+    surfaceMode = ProjectionSurface::DrawRegularMode;
+    plotType = DetectorPlotController::Single;
+    m_instrWidget->getSurface()->startCreatingShape2D(
+        "ring ellipse", Qt::green, QColor(255, 255, 255, 80));
+  } else if (m_ring_rectangle->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Rectangular ring");
+    surfaceMode = ProjectionSurface::DrawRegularMode;
+    plotType = DetectorPlotController::Single;
+    m_instrWidget->getSurface()->startCreatingShape2D(
+        "ring rectangle", Qt::green, QColor(255, 255, 255, 80));
+  } else if (m_free_draw->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Arbitrary shape");
+    surfaceMode = ProjectionSurface::DrawFreeMode;
+    plotType = DetectorPlotController::Single;
+    m_instrWidget->getSurface()->startCreatingFreeShape(
+        Qt::green, QColor(255, 255, 255, 80));
+  } else if (m_edit->isChecked()) {
+    m_selectionType = Draw;
+    m_activeTool->setText("Tool: Shape editing");
+    surfaceMode = ProjectionSurface::DrawRegularMode;
+    plotType = DetectorPlotController::Single;
+  }
+  m_plotController->setPlotType(plotType);
+  auto surface = m_instrWidget->getSurface();
+  if (surface) {
+    surface->setInteractionMode(surfaceMode);
+    auto interactionMode = surface->getInteractionMode();
+    if (interactionMode == ProjectionSurface::DrawRegularMode ||
+        interactionMode == ProjectionSurface::MoveMode) {
+      updatePlotMultipleDetectors();
+    } else {
+      m_plot->clearAll();
+      m_plot->replot();
+    }
+    setPlotCaption();
+  }
+  m_instrWidget->updateInfoText();
+}
+
+/**
+* Respond to the show event.
+*/
+void InstrumentWidgetPickTab::showEvent(QShowEvent *) {
+  // Make the state of the display view consistent with the current selection
+  // type
+  setSelectionType();
+  // make sure picking updated
+  m_instrWidget->updateInstrumentView(true);
+  m_instrWidget->getSurface()->changeBorderColor(getShapeBorderColor());
+}
+
+/**
+* Keep current curve permanently displayed on the plot.
+*/
+void InstrumentWidgetPickTab::storeCurve() { m_plot->store(); }
+
+/**
+* Remove a stored curve.
+* @param label :: The label of the curve to remove
+*/
+void InstrumentWidgetPickTab::removeCurve(const QString &label) {
+  m_plot->removeCurve(label);
+  m_plot->replot();
+}
+
+/**
+* Set the x units for the integrated tube plot.
+* @param units :: The x units in terms of TubeXUnits.
+*/
+void InstrumentWidgetPickTab::setTubeXUnits(int units) {
+  if (units < 0 || units >= DetectorPlotController::NUMBER_OF_UNITS)
+    return;
+  auto tubeXUnits = static_cast<DetectorPlotController::TubeXUnits>(units);
+  m_plotController->setTubeXUnits(tubeXUnits);
+  m_plotController->updatePlot();
+}
+
+/**
+* Get the color of the overlay shapes in this tab.
+* @return
+*/
+QColor InstrumentWidgetPickTab::getShapeBorderColor() const {
+  return QColor(Qt::green);
+}
+
+/**
+* Do something when the time bin integraion range has changed.
+*/
+void InstrumentWidgetPickTab::changedIntegrationRange(double, double) {
+  m_plotController->updatePlot();
+  auto surface = m_instrWidget->getSurface();
+  if (surface) {
+    auto interactionMode = surface->getInteractionMode();
+    if (interactionMode == ProjectionSurface::DrawRegularMode ||
+        interactionMode == ProjectionSurface::MoveMode) {
+      updatePlotMultipleDetectors();
+    }
+  }
+}
+
+void InstrumentWidgetPickTab::initSurface() {
+  ProjectionSurface *surface = getSurface().get();
+  connect(surface, SIGNAL(singleComponentTouched(size_t)), this,
+          SLOT(singleComponentTouched(size_t)));
+  connect(surface, SIGNAL(singleComponentPicked(size_t)), this,
+          SLOT(singleComponentPicked(size_t)));
+  connect(surface, SIGNAL(peaksWorkspaceAdded()), this,
+          SLOT(updateSelectionInfoDisplay()));
+  connect(surface, SIGNAL(peaksWorkspaceDeleted()), this,
+          SLOT(updateSelectionInfoDisplay()));
+  connect(surface, SIGNAL(shapeCreated()), this, SLOT(shapeCreated()));
+  connect(surface, SIGNAL(shapeChangeFinished()), this,
+          SLOT(updatePlotMultipleDetectors()));
+  connect(surface, SIGNAL(shapesCleared()), this,
+          SLOT(updatePlotMultipleDetectors()));
+  connect(surface, SIGNAL(shapesRemoved()), this,
+          SLOT(updatePlotMultipleDetectors()));
+  Projection3D *p3d = dynamic_cast<Projection3D *>(surface);
+  if (p3d) {
+    connect(p3d, SIGNAL(finishedMove()), this,
+            SLOT(updatePlotMultipleDetectors()));
+  }
+  m_infoController = new ComponentInfoController(
+      this, m_instrWidget->getInstrumentActor(), m_selectionInfoDisplay);
+  m_plotController = new DetectorPlotController(
+      this, m_instrWidget->getInstrumentActor(), m_plot);
+  m_plotController->setTubeXUnits(
+      static_cast<DetectorPlotController::TubeXUnits>(m_tubeXUnitsCache));
+  m_plotController->setPlotType(
+      static_cast<DetectorPlotController::PlotType>(m_plotTypeCache));
+}
+
+/**
+* Return current ProjectionSurface.
+*/
+boost::shared_ptr<ProjectionSurface>
+InstrumentWidgetPickTab::getSurface() const {
+  return m_instrWidget->getSurface();
+}
+
+/**
+* Save tab's persistent settings to the provided QSettings instance
+*/
+void InstrumentWidgetPickTab::saveSettings(QSettings &settings) const {
+  settings.setValue("TubeXUnits", m_plotController->getTubeXUnits());
+  settings.setValue("PlotType", m_plotController->getPlotType());
+}
+
+/**
+* Restore (read and apply) tab's persistent settings from the provided QSettings
+* instance
+*/
+void InstrumentWidgetPickTab::loadSettings(const QSettings &settings) {
+  // loadSettings is called when m_plotController is not created yet.
+  // Cache the settings and apply them later
+  m_tubeXUnitsCache = settings.value("TubeXUnits", 0).toInt();
+  m_plotTypeCache =
+      settings.value("PlotType", DetectorPlotController::Single).toInt();
+}
+
+/**
+* Fill in the context menu.
+* @param context :: A menu to fill.
+*/
+bool InstrumentWidgetPickTab::addToDisplayContextMenu(QMenu &context) const {
+  m_freezePlot = true;
+  bool res = false;
+  if (m_plot->hasCurve()) {
+    context.addAction(m_storeCurve);
+    res = true;
+  }
+  if (m_plot->hasStored() || m_plot->hasCurve()) {
+    context.addAction(m_savePlotToWorkspace);
+    res = true;
+  }
+  return res;
+}
+
+/**
+* Select a tool on the tab
+* @param tool One of the enumerated tool types, @see ToolType
+*/
+void InstrumentWidgetPickTab::selectTool(const ToolType tool) {
+  switch (tool) {
+  case Zoom:
+    m_zoom->setChecked(true);
+    break;
+  case PixelSelect:
+    m_one->setChecked(true);
+    break;
+  case TubeSelect:
+    m_tube->setChecked(true);
+    break;
+  case PeakSelect:
+    m_peak->setChecked(true);
+    break;
+  case PeakErase:
+    m_peakSelect->setChecked(true);
+    break;
+  case DrawRectangle:
+    m_rectangle->setChecked(true);
+    break;
+  case DrawEllipse:
+    m_ellipse->setChecked(true);
+    break;
+  case DrawFree:
+    m_free_draw->setChecked(true);
+    break;
+  case EditShape:
+    m_edit->setChecked(true);
+    break;
+  default:
+    throw std::invalid_argument("Invalid tool type.");
+  }
+  setSelectionType();
+}
+
+void InstrumentWidgetPickTab::singleComponentTouched(size_t pickID) {
+  if (canUpdateTouchedDetector()) {
+    m_infoController->displayInfo(pickID);
+    m_plotController->setPlotData(pickID);
+    m_plotController->updatePlot();
+  }
+}
+
+void InstrumentWidgetPickTab::singleComponentPicked(size_t pickID) {
+  m_infoController->displayInfo(pickID);
+  m_plotController->setPlotData(pickID);
+  m_plotController->updatePlot();
+}
+
+/**
+* Update the selection display using currently selected detector.
+* Updates non-detector information on it.
+*/
+void InstrumentWidgetPickTab::updateSelectionInfoDisplay() {
+  // updateSelectionInfo(m_currentDetID);
+}
+
+/**
+* Respond to the shapeCreated signal from the surface.
+*/
+void InstrumentWidgetPickTab::shapeCreated() {
+  if (!isVisible())
+    return;
+  if (!m_free_draw->isChecked()) {
+    selectTool(EditShape);
+  }
+}
+
+/**
+* Update the mini-plot with information from multiple detector
+* selected with drawn shapes.
+*/
+void InstrumentWidgetPickTab::updatePlotMultipleDetectors() {
+  if (!isVisible())
+    return;
+  ProjectionSurface &surface = *getSurface();
+  if (surface.hasMasks()) {
+    QList<int> dets;
+    surface.getMaskedDetectors(dets);
+    m_plotController->setPlotData(dets);
+  } else {
+    m_plotController->clear();
+  }
+  m_plot->replot();
+}
+
+/**
+* Save data plotted on the miniplot into a MatrixWorkspace.
+*/
+void InstrumentWidgetPickTab::savePlotToWorkspace() {
+  m_plotController->savePlotToWorkspace();
+}
+
+//=====================================================================================//
+
+/**
+* Create and setup iteself.
+* @param tab :: QObject parent - the tab.
+* @param instrActor :: A pointer to the InstrumentActor instance.
+* @param infoDisplay :: Widget on which to display the information.
+*/
+ComponentInfoController::ComponentInfoController(InstrumentWidgetPickTab *tab,
+                                                 InstrumentActor *instrActor,
+                                                 QTextEdit *infoDisplay)
+    : QObject(tab), m_tab(tab), m_instrActor(instrActor),
+      m_selectionInfoDisplay(infoDisplay), m_freezePlot(false),
+      m_instrWidgetBlocked(false), m_currentPickID(-1) {}
+
+/**
+* Display info on a component refered to by a pick ID.
+* @param pickID :: A pick ID of a component.
+*/
+void ComponentInfoController::displayInfo(size_t pickID) {
+  if (m_freezePlot) { // freeze the plot for one update
+    m_freezePlot = false;
+    pickID = m_currentPickID;
+  }
+
+  QString text = "";
+  int detid = m_instrActor->getDetID(pickID);
+  if (detid >= 0) {
+    text += displayDetectorInfo(detid);
+  } else if (auto componentID = m_instrActor->getComponentID(pickID)) {
+    text += displayNonDetectorInfo(componentID);
+  } else {
+    clear();
+  }
+  // display info about peak overlays
+  text += getPeakOverlayInfo();
+
+  if (!text.isEmpty()) {
+    m_selectionInfoDisplay->setText(text);
+  } else {
+    clear();
+  }
+}
+
+/**
+* Return string with info on a detector.
+* @param detid :: A detector ID.
+*/
+QString ComponentInfoController::displayDetectorInfo(Mantid::detid_t detid) {
+  if (m_instrWidgetBlocked) {
+    clear();
+    return "";
+  }
+
+  QString text;
+  if (detid >= 0) {
+    // collect info about selected detector and add it to text
+    Mantid::Geometry::IDetector_const_sptr det;
+    try {
+      det = m_instrActor->getInstrument()->getDetector(detid);
+    } catch (...) {
+      // if this slot is called during instrument window deletion
+      // expect exceptions thrown
+      return "";
+    }
+
+    text =
+        "Selected detector: " + QString::fromStdString(det->getName()) + "\n";
+    text += "Detector ID: " + QString::number(detid) + '\n';
+    QString wsIndex;
+    try {
+      wsIndex = QString::number(m_instrActor->getWorkspaceIndex(detid));
+    } catch (Mantid::Kernel::Exception::NotFoundError &) {
+      // Detector doesn't have a workspace index relating to it
+      wsIndex = "None";
+    }
+    text += "Workspace index: " + wsIndex + '\n';
+    Mantid::Kernel::V3D pos = det->getPos();
+    text += "xyz: " + QString::number(pos.X()) + "," +
+            QString::number(pos.Y()) + "," + QString::number(pos.Z()) + '\n';
+    double r, t, p;
+    pos.getSpherical(r, t, p);
+    text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," +
+            QString::number(p) + '\n';
+    Mantid::Geometry::ICompAssembly_const_sptr parent =
+        boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+            det->getParent());
+    if (parent) {
+      QString textpath;
+      while (parent) {
+        textpath = "/" + QString::fromStdString(parent->getName()) + textpath;
+        parent =
+            boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+                parent->getParent());
+      }
+      text += "Component path:" + textpath + "/" +
+              QString::fromStdString(det->getName()) + '\n';
+    }
+    const double integrated = m_instrActor->getIntegratedCounts(detid);
+    const QString counts =
+        integrated == -1.0 ? "N/A" : QString::number(integrated);
+    text += "Counts: " + counts + '\n';
+    // display info about peak overlays
+    text += getParameterInfo(det);
+  }
+  return text;
+}
+
+/**
+* string with information about a selected non-detector component (such as
+* choppers, etc).
+* @param compID :: A component ID for a component to display.
+*/
+QString ComponentInfoController::displayNonDetectorInfo(
+    Mantid::Geometry::ComponentID compID) {
+  auto component = m_instrActor->getInstrument()->getComponentByID(compID);
+  QString text = "Selected component: ";
+  text += QString::fromStdString(component->getName()) + '\n';
+  Mantid::Kernel::V3D pos = component->getPos();
+  text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) +
+          "," + QString::number(pos.Z()) + '\n';
+  double r, t, p;
+  pos.getSpherical(r, t, p);
+  text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," +
+          QString::number(p) + '\n';
+  text += getParameterInfo(component);
+  return text;
+}
+
+/**
+* Form a string for output from the components instrument parameters
+*/
+QString ComponentInfoController::getParameterInfo(
+    Mantid::Geometry::IComponent_const_sptr comp) {
+  QString text = "";
+  std::map<Mantid::Geometry::ComponentID, std::vector<std::string>>
+      mapCmptToNameVector;
+
+  auto paramNames = comp->getParameterNamesByComponent();
+  for (auto itParamName = paramNames.begin(); itParamName != paramNames.end();
+       ++itParamName) {
+    // build the data structure I need Map comp id -> vector of names
+    std::string paramName = itParamName->first;
+    Mantid::Geometry::ComponentID paramCompId = itParamName->second;
+    // attempt to insert this will fail silently if the key already exists
+    if (mapCmptToNameVector.find(paramCompId) == mapCmptToNameVector.end()) {
+      mapCmptToNameVector.emplace(paramCompId, std::vector<std::string>());
+    }
+    // get the vector out and add the name
+    mapCmptToNameVector[paramCompId].push_back(paramName);
+  }
+
+  // walk out from the selected component
+  Mantid::Geometry::IComponent_const_sptr paramComp = comp;
+  while (paramComp) {
+    auto &compParamNames = mapCmptToNameVector[paramComp->getComponentID()];
+    if (compParamNames.size() > 0) {
+      text += QString::fromStdString("\nParameters from: " +
+                                     paramComp->getName() + "\n");
+      std::sort(compParamNames.begin(), compParamNames.end(),
+                Mantid::Kernel::CaseInsensitiveStringComparator());
+      for (auto itParamName = compParamNames.begin();
+           itParamName != compParamNames.end(); ++itParamName) {
+        std::string paramName = *itParamName;
+        // no need to search recursively as we are asking from the matching
+        // component
+        std::string paramValue =
+            paramComp->getParameterAsString(paramName, false);
+        if (paramValue != "") {
+          text += QString::fromStdString(paramName + ": " + paramValue + "\n");
+        }
+      }
+    }
+    paramComp = paramComp->getParent();
+  }
+
+  return text;
+}
+
+/**
+* Return non-detector info to be displayed in the selection info display.
+*/
+QString ComponentInfoController::getPeakOverlayInfo() {
+  QString text;
+  QStringList overlays = m_tab->getSurface()->getPeaksWorkspaceNames();
+  if (!overlays.isEmpty()) {
+    text += "Peaks:\n" + overlays.join("\n") + "\n";
+  }
+  return text;
+}
+
+/**
+* Clear the information display.
+*/
+void ComponentInfoController::clear() { m_selectionInfoDisplay->clear(); }
+
+//=====================================================================================//
+
+/**
+* Constructor.
+* @param tab :: The parent tab.
+* @param instrActor :: A pointer to the InstrumentActor.
+* @param plot :: The plot widget.
+*/
+DetectorPlotController::DetectorPlotController(InstrumentWidgetPickTab *tab,
+                                               InstrumentActor *instrActor,
+                                               OneCurvePlot *plot)
+    : QObject(tab), m_tab(tab), m_instrActor(instrActor), m_plot(plot),
+      m_plotType(Single), m_enabled(true), m_tubeXUnits(DETECTOR_ID),
+      m_currentDetID(-1) {
+  connect(m_plot, SIGNAL(clickedAt(double, double)), this,
+          SLOT(addPeak(double, double)));
+}
+
+/**
+* Update the miniplot for a selected detector. The curve data depend on the
+* plot type.
+* @param pickID :: A pick ID of an instrument component.
+*/
+void DetectorPlotController::setPlotData(size_t pickID) {
+  m_currentDetID = -1;
+
+  if (m_plotType == DetectorSum) {
+    m_plotType = Single;
+  }
+
+  int detid = m_instrActor->getDetID(pickID);
+
+  if (!m_enabled) {
+    m_plot->clearCurve();
+    return;
+  }
+
+  if (detid >= 0) {
+    if (m_plotType == Single) {
+      m_currentDetID = detid;
+      plotSingle(detid);
+    } else if (m_plotType == TubeSum || m_plotType == TubeIntegral) {
+      plotTube(detid);
+    } else {
+      throw std::logic_error("setPlotData: Unexpected plot type.");
+    }
+  } else {
+    m_plot->clearCurve();
+  }
+}
+
+/**
+* Set curev data from multiple detectors: sum their spectra.
+* @param detIDs :: A list of detector IDs.
+*/
+void DetectorPlotController::setPlotData(QList<int> detIDs) {
+  setPlotType(DetectorSum);
+  clear();
+  std::vector<double> x, y;
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  m_instrActor->sumDetectors(detIDs, x, y,
+                             static_cast<size_t>(m_plot->width()));
+  QApplication::restoreOverrideCursor();
+  if (!x.empty()) {
+    m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()),
+                    m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
+  }
+  m_plot->setLabel("multiple");
+}
+
+/**
+* Update the miniplot for a selected detector.
+*/
+void DetectorPlotController::updatePlot() {
+  m_plot->recalcAxisDivs();
+  m_plot->replot();
+}
+
+/**
+* Clear the plot.
+*/
+void DetectorPlotController::clear() {
+  m_plot->clearCurve();
+  m_plot->clearPeakLabels();
+}
+
+/**
+* Plot data for a detector.
+* @param detid :: ID of the detector to be plotted.
+*/
+void DetectorPlotController::plotSingle(int detid) {
+
+  clear();
+  std::vector<double> x, y;
+  prepareDataForSinglePlot(detid, x, y);
+  if (x.empty() || y.empty())
+    return;
+
+  // set the data
+  m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()),
+                  m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
+  m_plot->setLabel("Detector " + QString::number(detid));
+
+  // find any markers
+  auto surface = m_tab->getSurface();
+  if (surface) {
+    QList<PeakMarker2D *> markers = surface->getMarkersWithID(detid);
+    foreach (PeakMarker2D *marker, markers) { m_plot->addPeakLabel(marker); }
+  }
+}
+
+/**
+* Plot data integrated either over the detectors in a tube or over time bins.
+* If m_plotSum == true the miniplot displays the accumulated data in a tube
+* against time of flight.
+* If m_plotSum == false the miniplot displays the data integrated over the time
+* bins. The values are
+* plotted against the length of the tube, but the units on the x-axis can be one
+* of the following:
+*   DETECTOR_ID
+*   LENGTH
+*   PHI
+* The units can be set with setTubeXUnits(...) method.
+* @param detid :: A detector id. The miniplot will display data for a component
+* containing the detector
+*   with this id.
+*/
+void DetectorPlotController::plotTube(int detid) {
+  Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
+  Mantid::Geometry::IDetector_const_sptr det =
+      m_instrActor->getInstrument()->getDetector(detid);
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      det->getParent();
+  Mantid::Geometry::ICompAssembly_const_sptr ass =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+          parent);
+  if (parent && ass) {
+    if (m_plotType == TubeSum) // plot sums over detectors vs time bins
+    {
+      plotTubeSums(detid);
+    } else // plot detector integrals vs detID or a function of detector
+           // position in the tube
+    {
+      assert(m_plotType == TubeIntegral);
+      plotTubeIntegrals(detid);
+    }
+  } else {
+    m_plot->clearCurve();
+  }
+}
+
+/**
+* Plot the accumulated data in a tube against time of flight.
+* @param detid :: A detector id. The miniplot will display data for a component
+* containing the detector
+*   with this id.
+*/
+void DetectorPlotController::plotTubeSums(int detid) {
+  std::vector<double> x, y;
+  prepareDataForSumsPlot(detid, x, y);
+  if (x.empty() || y.empty()) {
+    clear();
+    return;
+  }
+  Mantid::Geometry::IDetector_const_sptr det =
+      m_instrActor->getInstrument()->getDetector(detid);
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      det->getParent();
+  QString label = QString::fromStdString(parent->getName()) + " (" +
+                  QString::number(detid) + ") Sum";
+  m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()),
+                  m_instrActor->getWorkspace()->getAxis(0)->unit()->unitID());
+  m_plot->setLabel(label);
+}
+
+/**
+* Plot the data integrated over the time bins. The values are
+* plotted against the length of the tube, but the units on the x-axis can be one
+* of the following:
+*   DETECTOR_ID
+*   LENGTH
+*   PHI
+* The units can be set with setTubeXUnits(...) method.
+* @param detid :: A detector id. The miniplot will display data for a component
+* containing the detector
+*   with this id.
+*/
+void DetectorPlotController::plotTubeIntegrals(int detid) {
+  Mantid::Geometry::IDetector_const_sptr det =
+      m_instrActor->getInstrument()->getDetector(detid);
+  std::vector<double> x, y;
+  prepareDataForIntegralsPlot(detid, x, y);
+  if (x.empty() || y.empty()) {
+    clear();
+    return;
+  }
+  auto xAxisCaption = getTubeXUnitsName();
+  auto xAxisUnits = getTubeXUnitsUnits();
+  if (!xAxisUnits.isEmpty()) {
+    xAxisCaption += " (" + xAxisUnits + ")";
+  }
+  m_plot->setData(&x[0], &y[0], static_cast<int>(y.size()),
+                  xAxisCaption.toStdString());
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      det->getParent();
+  // curve label: "tube_name (detid) Integrals"
+  // detid is included to distiguish tubes with the same name
+  QString label = QString::fromStdString(parent->getName()) + " (" +
+                  QString::number(detid) + ") Integrals/" + getTubeXUnitsName();
+  m_plot->setLabel(label);
+}
+
+/**
+* Prepare data for plotting a spectrum of a single detector.
+* @param detid :: ID of the detector to be plotted.
+* @param x :: Vector of x coordinates (output)
+* @param y :: Vector of y coordinates (output)
+* @param err :: Optional pointer to a vector of errors (output)
+*/
+void DetectorPlotController::prepareDataForSinglePlot(
+    int detid, std::vector<double> &x, std::vector<double> &y,
+    std::vector<double> *err) {
+  Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
+  size_t wi;
+  try {
+    wi = m_instrActor->getWorkspaceIndex(detid);
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+    return; // Detector doesn't have a workspace index relating to it
+  }
+  // get the data
+  const Mantid::MantidVec &X = ws->readX(wi);
+  const Mantid::MantidVec &Y = ws->readY(wi);
+  const Mantid::MantidVec &E = ws->readE(wi);
+
+  // find min and max for x
+  size_t imin, imax;
+  m_instrActor->getBinMinMaxIndex(wi, imin, imax);
+
+  x.assign(X.begin() + imin, X.begin() + imax);
+  y.assign(Y.begin() + imin, Y.begin() + imax);
+  if (ws->isHistogramData()) {
+    // calculate the bin centres
+    std::transform(x.begin(), x.end(), X.begin() + imin + 1, x.begin(),
+                   std::plus<double>());
+    std::transform(x.begin(), x.end(), x.begin(),
+                   std::bind2nd(std::divides<double>(), 2.0));
+  }
+
+  if (err) {
+    err->assign(E.begin() + imin, E.begin() + imax);
+  }
+}
+
+/**
+* Prepare data for plotting accumulated data in a tube against time of flight.
+* @param detid :: A detector id. The miniplot will display data for a component
+* containing the detector
+*   with this id.
+* @param x :: Vector of x coordinates (output)
+* @param y :: Vector of y coordinates (output)
+* @param err :: Optional pointer to a vector of errors (output)
+*/
+void DetectorPlotController::prepareDataForSumsPlot(int detid,
+                                                    std::vector<double> &x,
+                                                    std::vector<double> &y,
+                                                    std::vector<double> *err) {
+  Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
+  Mantid::Geometry::IDetector_const_sptr det =
+      m_instrActor->getInstrument()->getDetector(detid);
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      det->getParent();
+  Mantid::Geometry::ICompAssembly_const_sptr ass =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+          parent);
+  size_t wi;
+  try {
+    wi = m_instrActor->getWorkspaceIndex(detid);
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+    return; // Detector doesn't have a workspace index relating to it
+  }
+  size_t imin, imax;
+  m_instrActor->getBinMinMaxIndex(wi, imin, imax);
+
+  const Mantid::MantidVec &X = ws->readX(wi);
+  x.assign(X.begin() + imin, X.begin() + imax);
+  if (ws->isHistogramData()) {
+    // calculate the bin centres
+    std::transform(x.begin(), x.end(), X.begin() + imin + 1, x.begin(),
+                   std::plus<double>());
+    std::transform(x.begin(), x.end(), x.begin(),
+                   std::bind2nd(std::divides<double>(), 2.0));
+  }
+  y.resize(x.size(), 0);
+  if (err) {
+    err->resize(x.size(), 0);
+  }
+
+  const int n = ass->nelements();
+  for (int i = 0; i < n; ++i) {
+    Mantid::Geometry::IDetector_sptr idet =
+        boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[i]);
+    if (idet) {
+      try {
+        size_t index = m_instrActor->getWorkspaceIndex(idet->getID());
+        const Mantid::MantidVec &Y = ws->readY(index);
+        std::transform(y.begin(), y.end(), Y.begin() + imin, y.begin(),
+                       std::plus<double>());
+        if (err) {
+          const Mantid::MantidVec &E = ws->readE(index);
+          std::vector<double> tmp;
+          tmp.assign(E.begin() + imin, E.begin() + imax);
+          std::transform(tmp.begin(), tmp.end(), tmp.begin(), tmp.begin(),
+                         std::multiplies<double>());
+          std::transform(err->begin(), err->end(), tmp.begin(), err->begin(),
+                         std::plus<double>());
+        }
+      } catch (Mantid::Kernel::Exception::NotFoundError &) {
+        continue; // Detector doesn't have a workspace index relating to it
+      }
+    }
+  }
+
+  if (err) {
+    std::transform(err->begin(), err->end(), err->begin(), Sqrt());
+  }
+}
+
+/**
+* Prepare data for plotting the data integrated over the time bins. The values
+* are
+* plotted against the length of the tube, but the units on the x-axis can be one
+* of the following:
+*   DETECTOR_ID
+*   LENGTH
+*   PHI
+*   OUT_OF_PLANE_ANGLE
+* The units can be set with setTubeXUnits(...) method.
+* @param detid :: A detector id. The miniplot will display data for a component
+* containing the detector
+*   with this id.
+* @param x :: Vector of x coordinates (output)
+* @param y :: Vector of y coordinates (output)
+* @param err :: Optional pointer to a vector of errors (output)
+*/
+void DetectorPlotController::prepareDataForIntegralsPlot(
+    int detid, std::vector<double> &x, std::vector<double> &y,
+    std::vector<double> *err) {
+
+#define PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED                              \
+  x.clear();                                                                   \
+  y.clear();                                                                   \
+  if (err)                                                                     \
+    err->clear();                                                              \
+  return;
+
+  Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
+
+  // Does the instrument definition specify that psi should be offset.
+  std::vector<std::string> parameters =
+      ws->getInstrument()->getStringParameter("offset-phi");
+  const bool bOffsetPsi = (!parameters.empty()) &&
+                          std::find(parameters.begin(), parameters.end(),
+                                    "Always") != parameters.end();
+
+  Mantid::Geometry::IDetector_const_sptr det =
+      m_instrActor->getInstrument()->getDetector(detid);
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      det->getParent();
+  Mantid::Geometry::ICompAssembly_const_sptr ass =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(
+          parent);
+  size_t wi;
+  try {
+    wi = m_instrActor->getWorkspaceIndex(detid);
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+    return; // Detector doesn't have a workspace index relating to it
+  }
+  // imin and imax give the bin integration range
+  size_t imin, imax;
+  m_instrActor->getBinMinMaxIndex(wi, imin, imax);
+
+  Mantid::Kernel::V3D samplePos =
+      m_instrActor->getInstrument()->getSample()->getPos();
+
+  const int n = ass->nelements();
+  if (n == 0) {
+    // don't think it's ever possible but...
+    throw std::runtime_error("PickTab miniplot: empty instrument assembly");
+  }
+  if (n == 1) {
+    // if assembly has just one element there is nothing to plot
+    PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
+  }
+  // collect and sort xy pairs in xymap
+  std::map<double, double> xymap, errmap;
+  // get the first detector in the tube for lenth calculation
+  Mantid::Geometry::IDetector_sptr idet0 =
+      boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[0]);
+  if (!idet0) {
+    // it's not an assembly of detectors,
+    // could be a mixture of monitors and other components
+    PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
+  }
+  Mantid::Kernel::V3D normal = (*ass)[1]->getPos() - idet0->getPos();
+  normal.normalize();
+  for (int i = 0; i < n; ++i) {
+    Mantid::Geometry::IDetector_sptr idet =
+        boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[i]);
+    if (idet) {
+      try {
+        const int id = idet->getID();
+        // get the x-value for detector idet
+        double xvalue = 0;
+        switch (m_tubeXUnits) {
+        case LENGTH:
+          xvalue = idet->getDistance(*idet0);
+          break;
+        case PHI:
+          xvalue = bOffsetPsi ? idet->getPhiOffset(M_PI) : idet->getPhi();
+          break;
+        case OUT_OF_PLANE_ANGLE: {
+          Mantid::Kernel::V3D pos = idet->getPos();
+          xvalue = getOutOfPlaneAngle(pos, samplePos, normal);
+          break;
+        }
+        default:
+          xvalue = static_cast<double>(id);
+        }
+        size_t index = m_instrActor->getWorkspaceIndex(id);
+        // get the y-value for detector idet
+        const Mantid::MantidVec &Y = ws->readY(index);
+        double sum = std::accumulate(Y.begin() + imin, Y.begin() + imax, 0);
+        xymap[xvalue] = sum;
+        if (err) {
+          const Mantid::MantidVec &E = ws->readE(index);
+          std::vector<double> tmp(imax - imin);
+          // take squares of the errors
+          std::transform(E.begin() + imin, E.begin() + imax, E.begin() + imin,
+                         tmp.begin(), std::multiplies<double>());
+          // sum them
+          double sum = std::accumulate(tmp.begin(), tmp.end(), 0);
+          // take sqrt
+          errmap[xvalue] = sqrt(sum);
+        }
+      } catch (Mantid::Kernel::Exception::NotFoundError &) {
+        continue; // Detector doesn't have a workspace index relating to it
+      }
+    }
+  }
+  if (!xymap.empty()) {
+    // set the plot curve data
+    x.resize(xymap.size());
+    y.resize(xymap.size());
+    std::map<double, double>::const_iterator xy = xymap.begin();
+    for (size_t i = 0; xy != xymap.end(); ++xy, ++i) {
+      x[i] = xy->first;
+      y[i] = xy->second;
+    }
+    if (err) {
+      err->resize(errmap.size());
+      std::map<double, double>::const_iterator e = errmap.begin();
+      for (size_t i = 0; e != errmap.end(); ++e, ++i) {
+        (*err)[i] = e->second;
+      }
+    }
+  } else {
+    PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
+  }
 #undef PREPAREDATAFORINTEGRALSPLOT_RETURN_FAILED
-		}
-
-		/**
-		* Save data plotted on the miniplot into a MatrixWorkspace.
-		*/
-		void DetectorPlotController::savePlotToWorkspace()
-		{
-			if (!m_plot->hasCurve() && !m_plot->hasStored())
-			{
-				// nothing to save
-				return;
-			}
-			Mantid::API::MatrixWorkspace_const_sptr parentWorkspace = m_instrActor->getWorkspace();
-			// interpret curve labels and reconstruct the data to be saved
-			QStringList labels = m_plot->getLabels();
-			if (m_plot->hasCurve())
-			{
-				labels << m_plot->label();
-			}
-			std::vector<double> X, Y, E;
-			size_t nbins = 0;
-			// to keep det ids for spectrum-detector mapping in the output workspace
-			std::vector<Mantid::detid_t> detids;
-			// unit id for x vector in the created workspace
-			std::string unitX;
-			foreach(QString label, labels)
-			{
-				std::vector<double> x, y, e;
-				// split the label to get the detector id and selection type 
-				QStringList parts = label.split(QRegExp("[()]"));
-				if (label == "multiple")
-				{
-					if (X.empty())
-					{
-						// label doesn't have any info on how to reproduce the curve:
-						// only the current curve can be saved
-						QList<int> dets;
-						m_tab->getSurface()->getMaskedDetectors(dets);
-						m_instrActor->sumDetectors(dets, x, y);
-						unitX = parentWorkspace->getAxis(0)->unit()->unitID();
-					}
-					else
-					{
-						QMessageBox::warning(NULL, "MantidPlot - Warning", "Cannot save the stored curves.\nOnly the current curve will be saved.");
-					}
-				}
-				else if (parts.size() == 3)
-				{
-					int detid = parts[1].toInt();
-					QString SumOrIntegral = parts[2].trimmed();
-					if (SumOrIntegral == "Sum")
-					{
-						prepareDataForSumsPlot(detid, x, y, &e);
-						unitX = parentWorkspace->getAxis(0)->unit()->unitID();
-					}
-					else
-					{
-						prepareDataForIntegralsPlot(detid, x, y, &e);
-						unitX = SumOrIntegral.split('/')[1].toStdString();
-					}
-				}
-				else if (parts.size() == 1)
-				{
-					// second word is detector id
-					int detid = parts[0].split(QRegExp("\\s+"))[1].toInt();
-					prepareDataForSinglePlot(detid, x, y, &e);
-					unitX = parentWorkspace->getAxis(0)->unit()->unitID();
-					// save det ids for the output workspace
-					detids.push_back(static_cast<Mantid::detid_t>(detid));
-				}
-				else
-				{
-					continue;
-				}
-				if (!x.empty())
-				{
-					if (nbins > 0 && x.size() != nbins)
-					{
-						QMessageBox::critical(NULL, "MantidPlot - Error", "Curves have different sizes.");
-						return;
-					}
-					else
-					{
-						nbins = x.size();
-					}
-					X.insert(X.end(), x.begin(), x.end());
-					Y.insert(Y.end(), y.begin(), y.end());
-					E.insert(E.end(), e.begin(), e.end());
-				}
-			}
-			// call CreateWorkspace algorithm. Created worksapce will have name "Curves"
-			if (!X.empty())
-			{
-				if (nbins == 0) nbins = 1;
-				E.resize(Y.size(), 1.0);
-				Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmFactory::Instance().create("CreateWorkspace", -1);
-				alg->initialize();
-				alg->setPropertyValue("OutputWorkspace", "Curves");
-				alg->setProperty("DataX", X);
-				alg->setProperty("DataY", Y);
-				alg->setProperty("DataE", E);
-				alg->setProperty("NSpec", static_cast<int>(X.size() / nbins));
-				alg->setProperty("UnitX", unitX);
-				alg->setPropertyValue("ParentWorkspace", parentWorkspace->name());
-				alg->execute();
-
-				if (!detids.empty())
-				{
-					// set up spectra - detector mapping
-					Mantid::API::MatrixWorkspace_sptr ws =
-						boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve("Curves"));
-					if (!ws)
-					{
-						throw std::runtime_error("Failed to create Curves workspace");
-					}
-
-					if (detids.size() == ws->getNumberHistograms())
-					{
-						size_t i = 0;
-						for (std::vector<Mantid::detid_t>::const_iterator id = detids.begin(); id != detids.end(); ++id, ++i)
-						{
-							Mantid::API::ISpectrum * spec = ws->getSpectrum(i);
-							if (!spec)
-							{
-								throw std::runtime_error("Spectrum not found");
-							}
-							spec->setDetectorID(*id);
-						}
-					}
-
-				} // !detids.empty()
-			}
-		}
-
-		/**
-		* Calculate the angle between a vector ( == pos - origin ) and a plane ( orthogonal to normal ).
-		* The angle is positive if the vector and the normal make an acute angle.
-		* @param pos :: Vector's end.
-		* @param origin :: Vector's origin.
-		* @param normal :: Normal to the plane.
-		* @return :: Angle between the vector and the plane in radians in [-pi/2, pi/2].
-		*/
-		double DetectorPlotController::getOutOfPlaneAngle(const Mantid::Kernel::V3D& pos, const Mantid::Kernel::V3D& origin, const Mantid::Kernel::V3D& normal)
-		{
-			Mantid::Kernel::V3D vec = pos - origin;
-			vec.normalize();
-			return asin(vec.scalar_prod(normal));
-		}
-
-		/**
-		* Return symbolic name of current TubeXUnit.
-		*/
-		QString DetectorPlotController::getTubeXUnitsName() const
-		{
-			switch (m_tubeXUnits)
-			{
-			case LENGTH: return "Length";
-			case PHI: return "Phi";
-			case OUT_OF_PLANE_ANGLE: return "Out of plane angle";
-			default:
-				break;
-			}
-			return "Detector ID";
-		}
-
-		/**
-		* Return symbolic name of units of current TubeXUnit.
-		*/
-		QString DetectorPlotController::getTubeXUnitsUnits() const
-		{
-			switch (m_tubeXUnits)
-			{
-			case LENGTH: return "m";
-			case PHI: return "radians";
-			case OUT_OF_PLANE_ANGLE: return "radians";
-			default: return "";
-			}
-			return "";
-		}
-
-		/**
-		* Get the plot caption for the current plot type.
-		*/
-		QString DetectorPlotController::getPlotCaption() const
-		{
-
-			switch (m_plotType)
-			{
-			case Single:      return "Plotting detector spectra";
-			case DetectorSum: return "Plotting multiple detector sum";
-			case TubeSum:     return "Plotting sum";
-			case TubeIntegral:return "Plotting integral";
-			default: throw std::logic_error("getPlotCaption: Unknown plot type.");
-			}
-
-		}
-
-		/**
-		* Add a peak to the single crystal peak table.
-		* @param x :: Time of flight
-		* @param y :: Peak height (counts)
-		*/
-		void DetectorPlotController::addPeak(double x, double y)
-		{
-			if (m_currentDetID < 0) return;
-
-			try
-			{
-				auto surface = m_tab->getSurface();
-				if (!surface) return;
-				Mantid::API::IPeaksWorkspace_sptr tw = surface->getEditPeaksWorkspace();
-				Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
-				std::string peakTableName;
-				bool newPeaksWorkspace = false;
-				if (tw)
-				{
-					peakTableName = tw->name();
-				}
-				else
-				{
-					peakTableName = "SingleCrystalPeakTable";
-					// This does need to get the instrument from the workspace as it's doing calculations
-					// .....and this method should be an algorithm! Or at least somewhere different to here.
-					Mantid::Geometry::Instrument_const_sptr instr = ws->getInstrument();
-
-					if (!Mantid::API::AnalysisDataService::Instance().doesExist(peakTableName))
-					{
-						tw = Mantid::API::WorkspaceFactory::Instance().createPeaks("PeaksWorkspace");
-						tw->setInstrument(instr);
-						Mantid::API::AnalysisDataService::Instance().add(peakTableName, tw);
-						newPeaksWorkspace = true;
-					}
-					else
-					{
-						tw = boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(peakTableName));
-						if (!tw)
-						{
-							QMessageBox::critical(m_tab, "Mantid - Error", "Workspace " + QString::fromStdString(peakTableName) + " is not a TableWorkspace");
-							return;
-						}
-					}
-					auto unwrappedSurface = dynamic_cast<UnwrappedSurface*>(surface.get());
-					if (unwrappedSurface)
-					{
-						unwrappedSurface->setPeaksWorkspace(boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(tw));
-					}
-				}
-
-				// Run the AddPeak algorithm
-				auto alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("AddPeak");
-				alg->setPropertyValue("RunWorkspace", ws->name());
-				alg->setPropertyValue("PeaksWorkspace", peakTableName);
-				alg->setProperty("DetectorID", m_currentDetID);
-				alg->setProperty("TOF", x);
-				alg->setProperty("Height", m_instrActor->getIntegratedCounts(m_currentDetID));
-				alg->setProperty("BinCount", y);
-				alg->execute();
-
-				// if data WS has UB copy it to the new peaks workspace
-				if (newPeaksWorkspace && ws->sample().hasOrientedLattice())
-				{
-					auto UB = ws->sample().getOrientedLattice().getUB();
-					auto lattice = new Mantid::Geometry::OrientedLattice;
-					lattice->setUB(UB);
-					tw->mutableSample().setOrientedLattice(lattice);
-				}
-
-				// if there is a UB available calculate HKL for the new peak
-				if (tw->sample().hasOrientedLattice())
-				{
-					auto alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("CalculatePeaksHKL");
-					alg->setPropertyValue("PeaksWorkspace", peakTableName);
-					alg->execute();
-				}
-			}
-			catch (std::exception& e)
-			{
-				QMessageBox::critical(m_tab, "MantidPlot -Error",
-					"Cannot create a Peak object because of the error:\n" + QString(e.what()));
-			}
-
-		}
-	}//MantidWidgets
-}//MantidQt
-
-
+}
+
+/**
+* Save data plotted on the miniplot into a MatrixWorkspace.
+*/
+void DetectorPlotController::savePlotToWorkspace() {
+  if (!m_plot->hasCurve() && !m_plot->hasStored()) {
+    // nothing to save
+    return;
+  }
+  Mantid::API::MatrixWorkspace_const_sptr parentWorkspace =
+      m_instrActor->getWorkspace();
+  // interpret curve labels and reconstruct the data to be saved
+  QStringList labels = m_plot->getLabels();
+  if (m_plot->hasCurve()) {
+    labels << m_plot->label();
+  }
+  std::vector<double> X, Y, E;
+  size_t nbins = 0;
+  // to keep det ids for spectrum-detector mapping in the output workspace
+  std::vector<Mantid::detid_t> detids;
+  // unit id for x vector in the created workspace
+  std::string unitX;
+  foreach (QString label, labels) {
+    std::vector<double> x, y, e;
+    // split the label to get the detector id and selection type
+    QStringList parts = label.split(QRegExp("[()]"));
+    if (label == "multiple") {
+      if (X.empty()) {
+        // label doesn't have any info on how to reproduce the curve:
+        // only the current curve can be saved
+        QList<int> dets;
+        m_tab->getSurface()->getMaskedDetectors(dets);
+        m_instrActor->sumDetectors(dets, x, y);
+        unitX = parentWorkspace->getAxis(0)->unit()->unitID();
+      } else {
+        QMessageBox::warning(NULL, "MantidPlot - Warning",
+                             "Cannot save the stored curves.\nOnly the current "
+                             "curve will be saved.");
+      }
+    } else if (parts.size() == 3) {
+      int detid = parts[1].toInt();
+      QString SumOrIntegral = parts[2].trimmed();
+      if (SumOrIntegral == "Sum") {
+        prepareDataForSumsPlot(detid, x, y, &e);
+        unitX = parentWorkspace->getAxis(0)->unit()->unitID();
+      } else {
+        prepareDataForIntegralsPlot(detid, x, y, &e);
+        unitX = SumOrIntegral.split('/')[1].toStdString();
+      }
+    } else if (parts.size() == 1) {
+      // second word is detector id
+      int detid = parts[0].split(QRegExp("\\s+"))[1].toInt();
+      prepareDataForSinglePlot(detid, x, y, &e);
+      unitX = parentWorkspace->getAxis(0)->unit()->unitID();
+      // save det ids for the output workspace
+      detids.push_back(static_cast<Mantid::detid_t>(detid));
+    } else {
+      continue;
+    }
+    if (!x.empty()) {
+      if (nbins > 0 && x.size() != nbins) {
+        QMessageBox::critical(NULL, "MantidPlot - Error",
+                              "Curves have different sizes.");
+        return;
+      } else {
+        nbins = x.size();
+      }
+      X.insert(X.end(), x.begin(), x.end());
+      Y.insert(Y.end(), y.begin(), y.end());
+      E.insert(E.end(), e.begin(), e.end());
+    }
+  }
+  // call CreateWorkspace algorithm. Created worksapce will have name "Curves"
+  if (!X.empty()) {
+    if (nbins == 0)
+      nbins = 1;
+    E.resize(Y.size(), 1.0);
+    Mantid::API::IAlgorithm_sptr alg =
+        Mantid::API::AlgorithmFactory::Instance().create("CreateWorkspace", -1);
+    alg->initialize();
+    alg->setPropertyValue("OutputWorkspace", "Curves");
+    alg->setProperty("DataX", X);
+    alg->setProperty("DataY", Y);
+    alg->setProperty("DataE", E);
+    alg->setProperty("NSpec", static_cast<int>(X.size() / nbins));
+    alg->setProperty("UnitX", unitX);
+    alg->setPropertyValue("ParentWorkspace", parentWorkspace->name());
+    alg->execute();
+
+    if (!detids.empty()) {
+      // set up spectra - detector mapping
+      Mantid::API::MatrixWorkspace_sptr ws =
+          boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+              Mantid::API::AnalysisDataService::Instance().retrieve("Curves"));
+      if (!ws) {
+        throw std::runtime_error("Failed to create Curves workspace");
+      }
+
+      if (detids.size() == ws->getNumberHistograms()) {
+        size_t i = 0;
+        for (std::vector<Mantid::detid_t>::const_iterator id = detids.begin();
+             id != detids.end(); ++id, ++i) {
+          Mantid::API::ISpectrum *spec = ws->getSpectrum(i);
+          if (!spec) {
+            throw std::runtime_error("Spectrum not found");
+          }
+          spec->setDetectorID(*id);
+        }
+      }
+
+    } // !detids.empty()
+  }
+}
+
+/**
+* Calculate the angle between a vector ( == pos - origin ) and a plane (
+* orthogonal to normal ).
+* The angle is positive if the vector and the normal make an acute angle.
+* @param pos :: Vector's end.
+* @param origin :: Vector's origin.
+* @param normal :: Normal to the plane.
+* @return :: Angle between the vector and the plane in radians in [-pi/2, pi/2].
+*/
+double
+DetectorPlotController::getOutOfPlaneAngle(const Mantid::Kernel::V3D &pos,
+                                           const Mantid::Kernel::V3D &origin,
+                                           const Mantid::Kernel::V3D &normal) {
+  Mantid::Kernel::V3D vec = pos - origin;
+  vec.normalize();
+  return asin(vec.scalar_prod(normal));
+}
+
+/**
+* Return symbolic name of current TubeXUnit.
+*/
+QString DetectorPlotController::getTubeXUnitsName() const {
+  switch (m_tubeXUnits) {
+  case LENGTH:
+    return "Length";
+  case PHI:
+    return "Phi";
+  case OUT_OF_PLANE_ANGLE:
+    return "Out of plane angle";
+  default:
+    break;
+  }
+  return "Detector ID";
+}
+
+/**
+* Return symbolic name of units of current TubeXUnit.
+*/
+QString DetectorPlotController::getTubeXUnitsUnits() const {
+  switch (m_tubeXUnits) {
+  case LENGTH:
+    return "m";
+  case PHI:
+    return "radians";
+  case OUT_OF_PLANE_ANGLE:
+    return "radians";
+  default:
+    return "";
+  }
+  return "";
+}
+
+/**
+* Get the plot caption for the current plot type.
+*/
+QString DetectorPlotController::getPlotCaption() const {
+
+  switch (m_plotType) {
+  case Single:
+    return "Plotting detector spectra";
+  case DetectorSum:
+    return "Plotting multiple detector sum";
+  case TubeSum:
+    return "Plotting sum";
+  case TubeIntegral:
+    return "Plotting integral";
+  default:
+    throw std::logic_error("getPlotCaption: Unknown plot type.");
+  }
+}
+
+/**
+* Add a peak to the single crystal peak table.
+* @param x :: Time of flight
+* @param y :: Peak height (counts)
+*/
+void DetectorPlotController::addPeak(double x, double y) {
+  if (m_currentDetID < 0)
+    return;
+
+  try {
+    auto surface = m_tab->getSurface();
+    if (!surface)
+      return;
+    Mantid::API::IPeaksWorkspace_sptr tw = surface->getEditPeaksWorkspace();
+    Mantid::API::MatrixWorkspace_const_sptr ws = m_instrActor->getWorkspace();
+    std::string peakTableName;
+    bool newPeaksWorkspace = false;
+    if (tw) {
+      peakTableName = tw->name();
+    } else {
+      peakTableName = "SingleCrystalPeakTable";
+      // This does need to get the instrument from the workspace as it's doing
+      // calculations
+      // .....and this method should be an algorithm! Or at least somewhere
+      // different to here.
+      Mantid::Geometry::Instrument_const_sptr instr = ws->getInstrument();
+
+      if (!Mantid::API::AnalysisDataService::Instance().doesExist(
+              peakTableName)) {
+        tw = Mantid::API::WorkspaceFactory::Instance().createPeaks(
+            "PeaksWorkspace");
+        tw->setInstrument(instr);
+        Mantid::API::AnalysisDataService::Instance().add(peakTableName, tw);
+        newPeaksWorkspace = true;
+      } else {
+        tw = boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(
+            Mantid::API::AnalysisDataService::Instance().retrieve(
+                peakTableName));
+        if (!tw) {
+          QMessageBox::critical(m_tab, "Mantid - Error",
+                                "Workspace " +
+                                    QString::fromStdString(peakTableName) +
+                                    " is not a TableWorkspace");
+          return;
+        }
+      }
+      auto unwrappedSurface = dynamic_cast<UnwrappedSurface *>(surface.get());
+      if (unwrappedSurface) {
+        unwrappedSurface->setPeaksWorkspace(
+            boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(tw));
+      }
+    }
+
+    // Run the AddPeak algorithm
+    auto alg =
+        Mantid::API::FrameworkManager::Instance().createAlgorithm("AddPeak");
+    alg->setPropertyValue("RunWorkspace", ws->name());
+    alg->setPropertyValue("PeaksWorkspace", peakTableName);
+    alg->setProperty("DetectorID", m_currentDetID);
+    alg->setProperty("TOF", x);
+    alg->setProperty("Height",
+                     m_instrActor->getIntegratedCounts(m_currentDetID));
+    alg->setProperty("BinCount", y);
+    alg->execute();
+
+    // if data WS has UB copy it to the new peaks workspace
+    if (newPeaksWorkspace && ws->sample().hasOrientedLattice()) {
+      auto UB = ws->sample().getOrientedLattice().getUB();
+      auto lattice = new Mantid::Geometry::OrientedLattice;
+      lattice->setUB(UB);
+      tw->mutableSample().setOrientedLattice(lattice);
+    }
+
+    // if there is a UB available calculate HKL for the new peak
+    if (tw->sample().hasOrientedLattice()) {
+      auto alg = Mantid::API::FrameworkManager::Instance().createAlgorithm(
+          "CalculatePeaksHKL");
+      alg->setPropertyValue("PeaksWorkspace", peakTableName);
+      alg->execute();
+    }
+  } catch (std::exception &e) {
+    QMessageBox::critical(
+        m_tab, "MantidPlot -Error",
+        "Cannot create a Peak object because of the error:\n" +
+            QString(e.what()));
+  }
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetRenderTab.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetRenderTab.cpp
index 32cb106b5500fb04574735d0d05453a7d6db5ba0..68034ae09c147475f4b50daf46986b5f60b253d3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetRenderTab.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetRenderTab.cpp
@@ -30,726 +30,703 @@
 
 #include <limits>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		// QSettings entry names
-		const char *EntryManualUCorrection = "ManualUCorrection";
-		const char *EntryUCorrectionMin = "UCorrectionMin";
-		const char *EntryUCorrectionMax = "UCorrectionMax";
-
-		InstrumentWidgetRenderTab::InstrumentWidgetRenderTab(InstrumentWidget* instrWindow) :
-			InstrumentWidgetTab(instrWindow)
-		{
-			QVBoxLayout* renderControlsLayout = new QVBoxLayout(this);
-
-			// Connect to InstrumentWindow signals
-			connect(m_instrWidget, SIGNAL(surfaceTypeChanged(int)), this, SLOT(surfaceTypeChanged(int)));
-			connect(m_instrWidget, SIGNAL(colorMapChanged()), this, SLOT(colorMapChanged()));
-			connect(m_instrWidget, SIGNAL(colorMapMaxValueChanged(double)), this, SLOT(setMaxValue(double)));
-			connect(m_instrWidget, SIGNAL(colorMapMinValueChanged(double)), this, SLOT(setMinValue(double)));
-			connect(m_instrWidget, SIGNAL(colorMapRangeChanged(double, double)), this, SLOT(setRange(double, double)));
-			connect(m_instrWidget, SIGNAL(scaleTypeChanged(int)), this, SLOT(scaleTypeChanged(int)));
-			connect(m_instrWidget, SIGNAL(nthPowerChanged(double)), this, SLOT(nthPowerChanged(double)));
-			connect(m_instrWidget, SIGNAL(glOptionChanged(bool)), this, SLOT(glOptionChanged(bool)));
-
-			// Surface type controls
-			m_surfaceTypeButton = new QPushButton("Render mode", this);
-			m_surfaceTypeButton->setToolTip("Set render mode");
-
-			QSignalMapper *signalMapper = new QSignalMapper(this);
-			connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(setSurfaceType(int)));
-
-			m_full3D = new QAction("Full 3D", this);
-			m_full3D->setCheckable(true);
-			connect(m_full3D, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_full3D, 0);
-			m_cylindricalX = new QAction("Cylindrical X", this);
-			m_cylindricalX->setCheckable(true);
-			connect(m_cylindricalX, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_cylindricalX, 1);
-			m_cylindricalY = new QAction("Cylindrical Y", this);
-			m_cylindricalY->setCheckable(true);
-			connect(m_cylindricalY, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_cylindricalY, 2);
-			m_cylindricalZ = new QAction("Cylindrical Z", this);
-			m_cylindricalZ->setCheckable(true);
-			connect(m_cylindricalZ, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_cylindricalZ, 3);
-			m_sphericalX = new QAction("Spherical X", this);
-			m_sphericalX->setCheckable(true);
-			connect(m_sphericalX, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_sphericalX, 4);
-			m_sphericalY = new QAction("Spherical Y", this);
-			m_sphericalY->setCheckable(true);
-			connect(m_sphericalY, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_sphericalY, 5);
-			m_sphericalZ = new QAction("Spherical Z", this);
-			m_sphericalZ->setCheckable(true);
-			connect(m_sphericalZ, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_sphericalZ, 6);
-			m_sideBySide = new QAction("Side by Side", this);
-			m_sideBySide->setCheckable(true);
-			connect(m_sideBySide, SIGNAL(triggered()), signalMapper, SLOT(map()));
-			signalMapper->setMapping(m_sideBySide, 7);
-
-			m_surfaceTypeActionGroup = new QActionGroup(this);
-			m_surfaceTypeActionGroup->setExclusive(true);
-			m_surfaceTypeActionGroup->addAction(m_full3D);
-			m_surfaceTypeActionGroup->addAction(m_cylindricalX);
-			m_surfaceTypeActionGroup->addAction(m_cylindricalY);
-			m_surfaceTypeActionGroup->addAction(m_cylindricalZ);
-			m_surfaceTypeActionGroup->addAction(m_sphericalX);
-			m_surfaceTypeActionGroup->addAction(m_sphericalY);
-			m_surfaceTypeActionGroup->addAction(m_sphericalZ);
-			m_surfaceTypeActionGroup->addAction(m_sideBySide);
-
-			QMenu *renderModeMenu = new QMenu(this);
-			renderModeMenu->addActions(m_surfaceTypeActionGroup->actions());
-			connect(renderModeMenu, SIGNAL(hovered(QAction*)), this, SLOT(showMenuToolTip(QAction*)));
-
-			m_surfaceTypeButton->setMenu(renderModeMenu);
-
-			// Save image control
-			mSaveImage = new QPushButton(tr("Save image"));
-			mSaveImage->setToolTip("Save the instrument image to a file");
-			connect(mSaveImage, SIGNAL(clicked()), this, SLOT(saveImage()));
-
-			// Setup Display Setting menu
-			QPushButton* displaySettings = new QPushButton("Display Settings", this);
-			QMenu* displaySettingsMenu = new QMenu(this);
-			connect(displaySettingsMenu, SIGNAL(aboutToShow()), this, SLOT(displaySettingsAboutToshow()));
-			m_colorMap = new QAction("Color Map", this);
-			connect(m_colorMap, SIGNAL(triggered()), this, SLOT(changeColorMap()));
-			m_backgroundColor = new QAction("Background Color", this);
-			connect(m_backgroundColor, SIGNAL(triggered()), m_instrWidget, SLOT(pickBackgroundColor()));
-			m_lighting = new QAction("Lighting", this);
-			m_lighting->setCheckable(true);
-			m_lighting->setChecked(false);
-			connect(m_lighting, SIGNAL(toggled(bool)), m_instrWidget, SIGNAL(enableLighting(bool)));
-			m_displayAxes = new QAction("Display Axes", this);
-			m_displayAxes->setCheckable(true);
-			m_displayAxes->setChecked(true);
-			connect(m_displayAxes, SIGNAL(toggled(bool)), this, SLOT(showAxes(bool)));
-			m_displayDetectorsOnly = new QAction("Display Detectors Only", this);
-			m_displayDetectorsOnly->setCheckable(true);
-			m_displayDetectorsOnly->setChecked(true);
-			connect(m_displayDetectorsOnly, SIGNAL(toggled(bool)), this, SLOT(displayDetectorsOnly(bool)));
-			m_wireframe = new QAction("Wireframe", this);
-			m_wireframe->setCheckable(true);
-			m_wireframe->setChecked(false);
-			connect(m_wireframe, SIGNAL(toggled(bool)), m_instrWidget, SLOT(setWireframe(bool)));
-			m_UCorrection = new QAction("U Correction", this);
-			m_UCorrection->setToolTip("Manually set the limits on the horizontal axis.");
-			connect(m_UCorrection, SIGNAL(triggered()), this, SLOT(setUCorrection()));
-
-			// Create "Use OpenGL" action
-			m_GLView = new QAction("Use OpenGL", this);
-			m_GLView->setToolTip("Toggle use of OpenGL for unwrapped view. Default value can be set in Preferences.");
-			m_GLView->setCheckable(true);
-			QString setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().
-				getString("MantidOptions.InstrumentView.UseOpenGL")).toUpper();
-			bool useOpenGL = setting == "ON";
-			connect(m_GLView, SIGNAL(toggled(bool)), this, SLOT(enableGL(bool)));
-			enableGL(useOpenGL);
-
-			displaySettingsMenu->addAction(m_colorMap);
-			displaySettingsMenu->addAction(m_backgroundColor);
-			displaySettingsMenu->addSeparator();
-			displaySettingsMenu->addAction(m_displayAxes);
-			displaySettingsMenu->addAction(m_displayDetectorsOnly);
-			displaySettingsMenu->addAction(m_wireframe);
-			displaySettingsMenu->addAction(m_lighting);
-			displaySettingsMenu->addAction(m_GLView);
-			displaySettingsMenu->addAction(m_UCorrection);
-
-			displaySettings->setMenu(displaySettingsMenu);
-			connect(displaySettingsMenu, SIGNAL(hovered(QAction*)), this, SLOT(showMenuToolTip(QAction*)));
-
-			QFrame * axisViewFrame = setupAxisFrame();
-
-			// Colormap widget
-			m_colorMapWidget = new ColorMapWidget(0, this);
-			connect(m_colorMapWidget, SIGNAL(scaleTypeChanged(int)), m_instrWidget, SLOT(changeScaleType(int)));
-			connect(m_colorMapWidget, SIGNAL(nthPowerChanged(double)), m_instrWidget, SLOT(changeNthPower(double)));
-			connect(m_colorMapWidget, SIGNAL(minValueChanged(double)), m_instrWidget, SLOT(changeColorMapMinValue(double)));
-			connect(m_colorMapWidget, SIGNAL(maxValueChanged(double)), m_instrWidget, SLOT(changeColorMapMaxValue(double)));
-
-			m_flipCheckBox = new QCheckBox("Flip view", this);
-			m_flipCheckBox->setToolTip("Flip the instrument view horizontally");
-			m_flipCheckBox->setChecked(false);
-			m_flipCheckBox->hide();
-			connect(m_flipCheckBox, SIGNAL(toggled(bool)), this, SLOT(flipUnwrappedView(bool)));
-
-			m_peakOverlaysButton = new QPushButton("Peaks options", this);
-			m_peakOverlaysButton->setToolTip("Set peak overlay options");
-			m_peakOverlaysButton->hide();
-			m_peakOverlaysButton->setMenu(createPeaksMenu());
-
-			QHBoxLayout* unwrappedControlsLayout = new QHBoxLayout;
-			unwrappedControlsLayout->addWidget(m_flipCheckBox);
-			unwrappedControlsLayout->addWidget(m_peakOverlaysButton);
-
-			m_autoscaling = new QCheckBox("Autoscaling", this);
-			m_autoscaling->setChecked(true);
-			connect(m_autoscaling, SIGNAL(toggled(bool)), this, SLOT(setColorMapAutoscaling(bool)));
-
-			// layout
-			renderControlsLayout->addWidget(m_surfaceTypeButton);
-			renderControlsLayout->addLayout(unwrappedControlsLayout);
-			renderControlsLayout->addWidget(axisViewFrame);
-			renderControlsLayout->addWidget(displaySettings);
-			renderControlsLayout->addWidget(mSaveImage);
-			renderControlsLayout->addWidget(m_colorMapWidget);
-			renderControlsLayout->addWidget(m_autoscaling);
-
-		}
-
-		InstrumentWidgetRenderTab::~InstrumentWidgetRenderTab()
-		{
-		}
-
-		/** Sets up the controls and surrounding layout that allows uses to view the instrument
-		*  from an axis that they select
-		*  @return the QFrame that will be inserted on the main instrument view form
-		*/
-		QFrame * InstrumentWidgetRenderTab::setupAxisFrame()
-		{
-			m_resetViewFrame = new QFrame();
-			QHBoxLayout* axisViewLayout = new QHBoxLayout();
-			axisViewLayout->addWidget(new QLabel("Axis View:"));
-
-			mAxisCombo = new QComboBox();
-			mAxisCombo->addItem("Z+");
-			mAxisCombo->addItem("Z-");
-			mAxisCombo->addItem("X+");
-			mAxisCombo->addItem("X-");
-			mAxisCombo->addItem("Y+");
-			mAxisCombo->addItem("Y-");
-
-			axisViewLayout->addWidget(mAxisCombo);
-			m_resetViewFrame->setLayout(axisViewLayout);
-
-			connect(mAxisCombo, SIGNAL(currentIndexChanged(const QString&)), m_instrWidget, SLOT(setViewDirection(const QString&)));
-
-			return m_resetViewFrame;
-		}
-
-		/**
-		* Set checked n-th menu item in m_setPrecison menu.
-		*/
-		void InstrumentWidgetRenderTab::setPrecisionMenuItemChecked(int n)
-		{
-			for (int i = 0; i < m_precisionActions.size(); ++i)
-			{
-				QAction *prec = m_precisionActions[i];
-				if (i == n - 1)
-				{
-					prec->setChecked(true);
-					break;
-				}
-			}
-		}
-
-		/**
-		* Enable/disable the Full 3D menu option
-		* @param on :: True to enable.
-		*/
-		void InstrumentWidgetRenderTab::enable3DSurface(bool on)
-		{
-			m_full3D->setEnabled(on);
-			if (on)
-			{
-				m_full3D->setToolTip("");
-			}
-			else
-			{
-				m_full3D->setToolTip("Disabled: check \"Use OpenGL\" option in Display Settings to enable");
-			}
-		}
-
-		/**
-		* Surface-specific adjustments.
-		*/
-		void InstrumentWidgetRenderTab::initSurface()
-		{
-			setAxis(QString::fromStdString(m_instrWidget->getInstrumentActor()->getInstrument()->getDefaultAxis()));
-			auto surface = getSurface();
-
-			// 3D axes switch needs to be shown for the 3D surface
-			auto p3d = boost::dynamic_pointer_cast<Projection3D>(surface);
-			if (p3d)
-			{
-				p3d->set3DAxesState(areAxesOn());
-			}
-
-			bool detectorsOnly = !m_instrWidget->getInstrumentActor()->areGuidesShown();
-			m_displayDetectorsOnly->blockSignals(true);
-			m_displayDetectorsOnly->setChecked(detectorsOnly);
-			m_displayDetectorsOnly->blockSignals(false);
-			setPrecisionMenuItemChecked(surface->getPeakLabelPrecision());
-
-			// enable u-correction for surfaces of rotation. correction applied in the last
-			// session is loaded and re-applied in the new session
-			auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
-			if (rotSurface)
-			{
-				m_UCorrection->setEnabled(true);
-				QString groupName = m_instrWidget->getInstrumentSettingsGroupName();
-				QSettings settings;
-				settings.beginGroup(groupName);
-                                bool isManualUCorrection =
-                                    settings
-                                        .value(EntryManualUCorrection, false)
-                                        .toBool();
-                                if (isManualUCorrection) {
-                                  double ucorrMin =
-                                      settings.value(EntryUCorrectionMin, 0.0)
-                                          .toDouble();
-                                  double ucorrMax =
-                                      settings.value(EntryUCorrectionMax, 0.0)
-                                          .toDouble();
-                                  rotSurface->setUCorrection(ucorrMin,
-                                                             ucorrMax);
-                                }
-			}
-			else
-			{
-				m_UCorrection->setEnabled(false);
-			}
-		}
-
-		/**
-		*
-		*/
-		void InstrumentWidgetRenderTab::setupColorBarScaling(const MantidColorMap& cmap, double minPositive)
-		{
-			m_colorMapWidget->setMinPositiveValue(minPositive);
-			m_colorMapWidget->setupColorBarScaling(cmap);
-		}
-
-		/**
-		* Change color map button slot. This provides the file dialog box to select colormap or sets it directly a string is provided
-		*/
-		void InstrumentWidgetRenderTab::changeColorMap(const QString &filename)
-		{
-			m_instrWidget->changeColormap(filename);
-		}
-
-		void InstrumentWidgetRenderTab::loadSettings(const QSettings& settings)
-		{
-			int show3daxes = settings.value("3DAxesShown", 1).toInt();
-			m_instrWidget->set3DAxesState(show3daxes != 0);
-			m_displayAxes->blockSignals(true);
-			m_displayAxes->setChecked(show3daxes != 0);
-			m_displayAxes->blockSignals(false);
-		}
-
-		void InstrumentWidgetRenderTab::saveSettings(QSettings& settings) const
-		{
-			int val = 0;  if (m_displayAxes->isChecked()) val = 1;
-			settings.setValue("3DAxesShown", QVariant(val));
-		}
-
-		/**
-		* Set minimum value on the colormap scale.
-		* @param value :: New value to set.
-		* @param apply ::
-		*/
-		void InstrumentWidgetRenderTab::setMinValue(double value, bool apply)
-		{
-			if (!apply) m_colorMapWidget->blockSignals(true);
-			m_colorMapWidget->setMinValue(value);
-			if (!apply) m_colorMapWidget->blockSignals(false);
-		}
-
-		/**
-		* Set maximum value on the colormap scale.
-		* @param value :: New value to set.
-		* @param apply ::
-		*/
-		void InstrumentWidgetRenderTab::setMaxValue(double value, bool apply)
-		{
-			if (!apply) m_colorMapWidget->blockSignals(true);
-			m_colorMapWidget->setMaxValue(value);
-			if (!apply) m_colorMapWidget->blockSignals(false);
-		}
-
-		/**
-		* Set minimum and maximum values on the colormap scale.
-		* @param minValue :: New min value to set.
-		* @param maxValue :: New max value to set.
-		* @param apply ::
-		*/
-		void InstrumentWidgetRenderTab::setRange(double minValue, double maxValue, bool apply)
-		{
-			if (!apply) m_colorMapWidget->blockSignals(true);
-			m_colorMapWidget->setMinValue(minValue);
-			m_colorMapWidget->setMaxValue(maxValue);
-			if (!apply) m_colorMapWidget->blockSignals(false);
-		}
-
-		GraphOptions::ScaleType InstrumentWidgetRenderTab::getScaleType()const
-		{
-			return (GraphOptions::ScaleType)m_colorMapWidget->getScaleType();
-		}
-
-		void InstrumentWidgetRenderTab::setScaleType(GraphOptions::ScaleType type)
-		{
-			m_colorMapWidget->setScaleType(type);
-		}
-
-		void InstrumentWidgetRenderTab::setAxis(const QString& axisNameArg)
-		{
-			QString axisName = axisNameArg.toUpper();
-			int axisInd = mAxisCombo->findText(axisName.toUpper());
-			if (axisInd < 0) axisInd = 0;
-			mAxisCombo->setCurrentIndex(axisInd);
-		}
-
-		bool InstrumentWidgetRenderTab::areAxesOn()const
-		{
-			return m_displayAxes->isChecked();
-		}
-
-		/**
-		* Show ResetView combo box only with 3D view
-		* @param iv Index of a render mode in RenderMode combo box. iv == 0 is 3D view
-		*/
-		void InstrumentWidgetRenderTab::showResetView(int iv)
-		{
-			m_resetViewFrame->setVisible(iv == 0);
-		}
-
-		void InstrumentWidgetRenderTab::showFlipControl(int iv)
-		{
-			bool vis = iv != 0;
-			m_flipCheckBox->setVisible(vis);
-			m_peakOverlaysButton->setVisible(vis);
-		}
-
-		/**
-		* Toggle display of 3D axes.
-		*
-		* @param on :: True of false for on and off.
-		*/
-		void InstrumentWidgetRenderTab::showAxes(bool on)
-		{
-			m_instrWidget->set3DAxesState(on);
-			m_displayAxes->blockSignals(true);
-			m_displayAxes->setChecked(on);
-			m_displayAxes->blockSignals(false);
-		}
-
-		/**
-		* Toggle display of guide and other non-detector components.
-		*
-		* @param yes :: True of false for on and off.
-		*/
-		void InstrumentWidgetRenderTab::displayDetectorsOnly(bool yes)
-		{
-			m_instrWidget->getInstrumentActor()->showGuides(!yes);
-			m_instrWidget->updateInstrumentView();
-			m_displayDetectorsOnly->blockSignals(true);
-			m_displayDetectorsOnly->setChecked(yes);
-			m_displayDetectorsOnly->blockSignals(false);
-		}
-
-		/**
-		* Toggle use of OpenGL
-		*
-		* @param on :: True of false for on and off.
-		*/
-		void InstrumentWidgetRenderTab::enableGL(bool on)
-		{
-			m_instrWidget->enableGL(on);
-			m_GLView->blockSignals(true);
-			m_GLView->setChecked(m_instrWidget->isGLEnabled());
-			m_GLView->blockSignals(false);
-			enable3DSurface(on);
-		}
-
-
-		void InstrumentWidgetRenderTab::showEvent(QShowEvent *)
-		{
-			auto surface = getSurface();
-			if (surface)
-			{
-				surface->setInteractionMode(ProjectionSurface::MoveMode);
-			}
-			InstrumentActor* actor = m_instrWidget->getInstrumentActor();
-			if (actor)
-			{
-				auto visitor = SetAllVisibleVisitor(actor->areGuidesShown());
-				actor->accept(visitor);
-				getSurface()->updateView();
-				getSurface()->requestRedraw();
-			}
-		}
-
-		void InstrumentWidgetRenderTab::flipUnwrappedView(bool on)
-		{
-			auto surface = boost::dynamic_pointer_cast<UnwrappedSurface>(m_instrWidget->getSurface());
-			if (!surface) return;
-			surface->setFlippedView(on);
-			m_instrWidget->updateInstrumentView();
-			// Sync checkbox
-			m_flipCheckBox->blockSignals(true);
-			m_flipCheckBox->setChecked(on);
-			m_flipCheckBox->blockSignals(false);
-
-		}
-
-		/**
-		* Saves the current image buffer to the given file. An empty string raises a dialog
-		* for finding the file
-		* @param filename Optional full path of the saved image
-		*/
-		void InstrumentWidgetRenderTab::saveImage(QString filename)
-		{
-			m_instrWidget->saveImage(filename);
-		}
-
-		/**
-		* Reset the colorbar parameters.
-		* @param cmap :: A new Mantid color map.
-		* @param minValue :: A new minimum value.
-		* @param maxValue :: A new maximum value.
-		* @param minPositive :: A new minimum positive value for the log scale.
-		* @param autoscaling :: Flag to set autoscaling of the color
-		*/
-		void InstrumentWidgetRenderTab::setupColorBar(const MantidColorMap& cmap, double minValue, double maxValue, double minPositive, bool autoscaling)
-		{
-			setMinValue(minValue, false);
-			setMaxValue(maxValue, false);
-			m_colorMapWidget->setMinPositiveValue(minPositive);
-			m_colorMapWidget->setupColorBarScaling(cmap);
-			m_autoscaling->blockSignals(true);
-			m_autoscaling->setChecked(autoscaling);
-			m_autoscaling->blockSignals(false);
-		}
-
-		/**
-		* Set on / off autoscaling of the color bar.
-		*/
-		void InstrumentWidgetRenderTab::setColorMapAutoscaling(bool on)
-		{
-			emit setAutoscaling(on);
-		}
-
-		/**
-		* Creates a menu for interaction with peak overlays
-		*/
-		QMenu* InstrumentWidgetRenderTab::createPeaksMenu()
-		{
-			QSettings settings;
-			settings.beginGroup(m_instrWidget->getSettingsGroupName());
-			QMenu* menu = new QMenu(this);
-
-			// show/hide peak hkl labels
-			QAction *showLabels = new QAction("Show labels", this);
-			showLabels->setCheckable(true);
-			showLabels->setChecked(settings.value("ShowPeakLabels", true).toBool());
-			connect(showLabels, SIGNAL(toggled(bool)), m_instrWidget, SLOT(setShowPeakLabelsFlag(bool)));
-			menu->addAction(showLabels);
-			// show/hide peak table rows
-			QAction *showRows = new QAction("Show rows", this);
-			showRows->setCheckable(true);
-			showRows->setChecked(settings.value("ShowPeakRows", true).toBool());
-			connect(showRows, SIGNAL(toggled(bool)), m_instrWidget, SLOT(setShowPeakRowFlag(bool)));
-			connect(showLabels, SIGNAL(toggled(bool)), showRows, SLOT(setEnabled(bool)));
-			showRows->setEnabled(showLabels->isChecked());
-			menu->addAction(showRows);
-			// setting precision set of actions
-			QMenu *setPrecision = new QMenu("Label precision", this);
-			m_precisionActionGroup = new QActionGroup(this);
-			QSignalMapper *signalMapper = new QSignalMapper(this);
-			for (int i = 1; i < 10; ++i)
-			{
-				QAction *prec = new QAction(QString::number(i), setPrecision);
-				prec->setCheckable(true);
-				setPrecision->addAction(prec);
-				connect(prec, SIGNAL(triggered()), signalMapper, SLOT(map()));
-				signalMapper->setMapping(prec, i);
-				m_precisionActions.append(prec);
-				m_precisionActionGroup->addAction(prec);
-			}
-			connect(signalMapper, SIGNAL(mapped(int)), m_instrWidget, SLOT(setPeakLabelPrecision(int)));
-			menu->addMenu(setPrecision);
-
-			QAction *showRelativeIntensity = new QAction("Indicate relative intensity", this);
-			showRelativeIntensity->setCheckable(true);
-			showRelativeIntensity->setChecked(settings.value("ShowPeakRelativeIntensities", false).toBool());
-			connect(showRelativeIntensity, SIGNAL(toggled(bool)), m_instrWidget, SLOT(setShowPeakRelativeIntensity(bool)));
-			menu->addAction(showRelativeIntensity);
-
-			// Clear peaks action
-			QAction* clearPeaks = new QAction("Clear peaks", this);
-			connect(clearPeaks, SIGNAL(triggered()), m_instrWidget, SLOT(clearPeakOverlays()));
-			menu->addAction(clearPeaks);
-			return menu;
-		}
-
-		/**
-		* Called before the display setting menu opens. Filters out menu options.
-		*/
-		void InstrumentWidgetRenderTab::displaySettingsAboutToshow()
-		{
-			if (m_instrWidget->getSurfaceType() == InstrumentWidget::FULL3D)
-			{
-				// in 3D mode use GL widget only and allow lighting
-				m_GLView->setEnabled(false);
-				m_lighting->setEnabled(true);
-			}
-			else
-			{
-				// in flat view mode allow changing to simple, non-GL viewer
-				m_GLView->setEnabled(true);
-				// allow lighting in GL viewer only
-				if (!m_GLView->isChecked())
-				{
-					m_lighting->setEnabled(false);
-				}
-				else
-				{
-					m_lighting->setEnabled(true);
-				}
-			}
-		}
-
-		/**
-		* Change the type of the surface.
-		* @param index :: Index selected in the surface type combo box.
-		*/
-		void InstrumentWidgetRenderTab::setSurfaceType(int index)
-		{
-			if ((int)m_instrWidget->getSurfaceType() != index)
-			{
-				m_instrWidget->setSurfaceType(index);
-			}
-		}
-
-		/**
-		* Respond to surface change from script.
-		* @param index :: Index selected in the surface type combo box.
-		*/
-		void InstrumentWidgetRenderTab::surfaceTypeChanged(int index)
-		{
-			// display action's text on the render mode button
-			QAction *action = m_surfaceTypeActionGroup->actions()[index];
-			m_surfaceTypeButton->setText(action->text());
-
-			// if action isn't checked then this method is called from script
-			if (!action->isChecked())
-			{
-				// checking action calls setSurfaceType slot
-				action->setChecked(true);
-			}
-			showFlipControl(index);
-			showResetView(index);
-		}
-
-		/**
-		* Respond to external change of the colormap.
-		*/
-		void InstrumentWidgetRenderTab::colorMapChanged()
-		{
-			InstrumentActor *instrumentActor = m_instrWidget->getInstrumentActor();
-			setupColorBar(
-				instrumentActor->getColorMap(),
-				instrumentActor->minValue(),
-				instrumentActor->maxValue(),
-				instrumentActor->minPositiveValue(),
-				instrumentActor->autoscaling()
-				);
-		}
-
-		void InstrumentWidgetRenderTab::scaleTypeChanged(int type)
-		{
-			setScaleType((GraphOptions::ScaleType)type);
-		}
-
-		void InstrumentWidgetRenderTab::nthPowerChanged(double nth_power)
-		{
-			m_colorMapWidget->setNthPower(nth_power);
-		}
-
-		/**
-		* Update the GUI element after the "Use OpenGL" option has been changed
-		* programmatically.
-		* @param on :: True for enabling OpenGL, false for disabling.
-		*/
-		void InstrumentWidgetRenderTab::glOptionChanged(bool on)
-		{
-			m_GLView->blockSignals(true);
-			m_GLView->setChecked(on);
-			m_GLView->blockSignals(false);
-		}
-
-		/**
-		* Show the tooltip of an action which is attached to a menu.
-		*/
-		void InstrumentWidgetRenderTab::showMenuToolTip(QAction *action)
-		{
-			QToolTip::showText(QCursor::pos(), action->toolTip(), this);
-		}
-
-		/**
-		* Set the offset in u-coordinate of a 2d (unwrapped) surface
-		*/
-		void InstrumentWidgetRenderTab::setUCorrection()
-		{
-			auto surface = getSurface();
-			auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
-			if (rotSurface)
-			{
-				QPointF oldUCorr = rotSurface->getUCorrection();
-				// ask the user to enter a number for the u-correction
-				UCorrectionDialog dlg(this, oldUCorr, rotSurface->isManualUCorrection());
-				if (dlg.exec() != QDialog::Accepted) return;
-
-				QSettings settings;
-				settings.beginGroup(m_instrWidget->getInstrumentSettingsGroupName());
-
-				if (dlg.applyCorrection())
-				{
-					QPointF ucorr = dlg.getValue();
-					// update the surface only if the correction changes
-					if (ucorr != oldUCorr)
-					{
-						rotSurface->setUCorrection(ucorr.x(), ucorr.y()); // manually set the correction
-						rotSurface->requestRedraw();         // redraw the view
-						settings.setValue(EntryManualUCorrection, true);
-						settings.setValue(EntryUCorrectionMin, ucorr.x());
-						settings.setValue(EntryUCorrectionMax, ucorr.y());
-					}
-				}
-				else
-				{
-					rotSurface->setAutomaticUCorrection(); // switch to automatic correction
-					rotSurface->requestRedraw();         // redraw the view
-                                        settings.remove(EntryManualUCorrection);
-                                        settings.remove(EntryUCorrectionMin);
-                                        settings.remove(EntryUCorrectionMax);
-                                }
-                        }
-		}
-
-		/**
-		* Get current value for the u-correction for a RotationSurface.
-		* Return 0 if it's not a RotationSurface.
-		*/
-		QPointF InstrumentWidgetRenderTab::getUCorrection() const
-		{
-			auto surface = getSurface();
-			auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
-			if (rotSurface)
-			{
-				return rotSurface->getUCorrection();
-			}
-			return QPointF();
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+// QSettings entry names
+const char *EntryManualUCorrection = "ManualUCorrection";
+const char *EntryUCorrectionMin = "UCorrectionMin";
+const char *EntryUCorrectionMax = "UCorrectionMax";
+
+InstrumentWidgetRenderTab::InstrumentWidgetRenderTab(
+    InstrumentWidget *instrWindow)
+    : InstrumentWidgetTab(instrWindow) {
+  QVBoxLayout *renderControlsLayout = new QVBoxLayout(this);
+
+  // Connect to InstrumentWindow signals
+  connect(m_instrWidget, SIGNAL(surfaceTypeChanged(int)), this,
+          SLOT(surfaceTypeChanged(int)));
+  connect(m_instrWidget, SIGNAL(colorMapChanged()), this,
+          SLOT(colorMapChanged()));
+  connect(m_instrWidget, SIGNAL(colorMapMaxValueChanged(double)), this,
+          SLOT(setMaxValue(double)));
+  connect(m_instrWidget, SIGNAL(colorMapMinValueChanged(double)), this,
+          SLOT(setMinValue(double)));
+  connect(m_instrWidget, SIGNAL(colorMapRangeChanged(double, double)), this,
+          SLOT(setRange(double, double)));
+  connect(m_instrWidget, SIGNAL(scaleTypeChanged(int)), this,
+          SLOT(scaleTypeChanged(int)));
+  connect(m_instrWidget, SIGNAL(nthPowerChanged(double)), this,
+          SLOT(nthPowerChanged(double)));
+  connect(m_instrWidget, SIGNAL(glOptionChanged(bool)), this,
+          SLOT(glOptionChanged(bool)));
+
+  // Surface type controls
+  m_surfaceTypeButton = new QPushButton("Render mode", this);
+  m_surfaceTypeButton->setToolTip("Set render mode");
+
+  QSignalMapper *signalMapper = new QSignalMapper(this);
+  connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(setSurfaceType(int)));
+
+  m_full3D = new QAction("Full 3D", this);
+  m_full3D->setCheckable(true);
+  connect(m_full3D, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_full3D, 0);
+  m_cylindricalX = new QAction("Cylindrical X", this);
+  m_cylindricalX->setCheckable(true);
+  connect(m_cylindricalX, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_cylindricalX, 1);
+  m_cylindricalY = new QAction("Cylindrical Y", this);
+  m_cylindricalY->setCheckable(true);
+  connect(m_cylindricalY, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_cylindricalY, 2);
+  m_cylindricalZ = new QAction("Cylindrical Z", this);
+  m_cylindricalZ->setCheckable(true);
+  connect(m_cylindricalZ, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_cylindricalZ, 3);
+  m_sphericalX = new QAction("Spherical X", this);
+  m_sphericalX->setCheckable(true);
+  connect(m_sphericalX, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_sphericalX, 4);
+  m_sphericalY = new QAction("Spherical Y", this);
+  m_sphericalY->setCheckable(true);
+  connect(m_sphericalY, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_sphericalY, 5);
+  m_sphericalZ = new QAction("Spherical Z", this);
+  m_sphericalZ->setCheckable(true);
+  connect(m_sphericalZ, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_sphericalZ, 6);
+  m_sideBySide = new QAction("Side by Side", this);
+  m_sideBySide->setCheckable(true);
+  connect(m_sideBySide, SIGNAL(triggered()), signalMapper, SLOT(map()));
+  signalMapper->setMapping(m_sideBySide, 7);
+
+  m_surfaceTypeActionGroup = new QActionGroup(this);
+  m_surfaceTypeActionGroup->setExclusive(true);
+  m_surfaceTypeActionGroup->addAction(m_full3D);
+  m_surfaceTypeActionGroup->addAction(m_cylindricalX);
+  m_surfaceTypeActionGroup->addAction(m_cylindricalY);
+  m_surfaceTypeActionGroup->addAction(m_cylindricalZ);
+  m_surfaceTypeActionGroup->addAction(m_sphericalX);
+  m_surfaceTypeActionGroup->addAction(m_sphericalY);
+  m_surfaceTypeActionGroup->addAction(m_sphericalZ);
+  m_surfaceTypeActionGroup->addAction(m_sideBySide);
+
+  QMenu *renderModeMenu = new QMenu(this);
+  renderModeMenu->addActions(m_surfaceTypeActionGroup->actions());
+  connect(renderModeMenu, SIGNAL(hovered(QAction *)), this,
+          SLOT(showMenuToolTip(QAction *)));
+
+  m_surfaceTypeButton->setMenu(renderModeMenu);
+
+  // Save image control
+  mSaveImage = new QPushButton(tr("Save image"));
+  mSaveImage->setToolTip("Save the instrument image to a file");
+  connect(mSaveImage, SIGNAL(clicked()), this, SLOT(saveImage()));
+
+  // Setup Display Setting menu
+  QPushButton *displaySettings = new QPushButton("Display Settings", this);
+  QMenu *displaySettingsMenu = new QMenu(this);
+  connect(displaySettingsMenu, SIGNAL(aboutToShow()), this,
+          SLOT(displaySettingsAboutToshow()));
+  m_colorMap = new QAction("Color Map", this);
+  connect(m_colorMap, SIGNAL(triggered()), this, SLOT(changeColorMap()));
+  m_backgroundColor = new QAction("Background Color", this);
+  connect(m_backgroundColor, SIGNAL(triggered()), m_instrWidget,
+          SLOT(pickBackgroundColor()));
+  m_lighting = new QAction("Lighting", this);
+  m_lighting->setCheckable(true);
+  m_lighting->setChecked(false);
+  connect(m_lighting, SIGNAL(toggled(bool)), m_instrWidget,
+          SIGNAL(enableLighting(bool)));
+  m_displayAxes = new QAction("Display Axes", this);
+  m_displayAxes->setCheckable(true);
+  m_displayAxes->setChecked(true);
+  connect(m_displayAxes, SIGNAL(toggled(bool)), this, SLOT(showAxes(bool)));
+  m_displayDetectorsOnly = new QAction("Display Detectors Only", this);
+  m_displayDetectorsOnly->setCheckable(true);
+  m_displayDetectorsOnly->setChecked(true);
+  connect(m_displayDetectorsOnly, SIGNAL(toggled(bool)), this,
+          SLOT(displayDetectorsOnly(bool)));
+  m_wireframe = new QAction("Wireframe", this);
+  m_wireframe->setCheckable(true);
+  m_wireframe->setChecked(false);
+  connect(m_wireframe, SIGNAL(toggled(bool)), m_instrWidget,
+          SLOT(setWireframe(bool)));
+  m_UCorrection = new QAction("U Correction", this);
+  m_UCorrection->setToolTip("Manually set the limits on the horizontal axis.");
+  connect(m_UCorrection, SIGNAL(triggered()), this, SLOT(setUCorrection()));
+
+  // Create "Use OpenGL" action
+  m_GLView = new QAction("Use OpenGL", this);
+  m_GLView->setToolTip("Toggle use of OpenGL for unwrapped view. Default value "
+                       "can be set in Preferences.");
+  m_GLView->setCheckable(true);
+  QString setting =
+      QString::fromStdString(
+          Mantid::Kernel::ConfigService::Instance().getString(
+              "MantidOptions.InstrumentView.UseOpenGL")).toUpper();
+  bool useOpenGL = setting == "ON";
+  connect(m_GLView, SIGNAL(toggled(bool)), this, SLOT(enableGL(bool)));
+  enableGL(useOpenGL);
+
+  displaySettingsMenu->addAction(m_colorMap);
+  displaySettingsMenu->addAction(m_backgroundColor);
+  displaySettingsMenu->addSeparator();
+  displaySettingsMenu->addAction(m_displayAxes);
+  displaySettingsMenu->addAction(m_displayDetectorsOnly);
+  displaySettingsMenu->addAction(m_wireframe);
+  displaySettingsMenu->addAction(m_lighting);
+  displaySettingsMenu->addAction(m_GLView);
+  displaySettingsMenu->addAction(m_UCorrection);
+
+  displaySettings->setMenu(displaySettingsMenu);
+  connect(displaySettingsMenu, SIGNAL(hovered(QAction *)), this,
+          SLOT(showMenuToolTip(QAction *)));
+
+  QFrame *axisViewFrame = setupAxisFrame();
+
+  // Colormap widget
+  m_colorMapWidget = new ColorMapWidget(0, this);
+  connect(m_colorMapWidget, SIGNAL(scaleTypeChanged(int)), m_instrWidget,
+          SLOT(changeScaleType(int)));
+  connect(m_colorMapWidget, SIGNAL(nthPowerChanged(double)), m_instrWidget,
+          SLOT(changeNthPower(double)));
+  connect(m_colorMapWidget, SIGNAL(minValueChanged(double)), m_instrWidget,
+          SLOT(changeColorMapMinValue(double)));
+  connect(m_colorMapWidget, SIGNAL(maxValueChanged(double)), m_instrWidget,
+          SLOT(changeColorMapMaxValue(double)));
+
+  m_flipCheckBox = new QCheckBox("Flip view", this);
+  m_flipCheckBox->setToolTip("Flip the instrument view horizontally");
+  m_flipCheckBox->setChecked(false);
+  m_flipCheckBox->hide();
+  connect(m_flipCheckBox, SIGNAL(toggled(bool)), this,
+          SLOT(flipUnwrappedView(bool)));
+
+  m_peakOverlaysButton = new QPushButton("Peaks options", this);
+  m_peakOverlaysButton->setToolTip("Set peak overlay options");
+  m_peakOverlaysButton->hide();
+  m_peakOverlaysButton->setMenu(createPeaksMenu());
+
+  QHBoxLayout *unwrappedControlsLayout = new QHBoxLayout;
+  unwrappedControlsLayout->addWidget(m_flipCheckBox);
+  unwrappedControlsLayout->addWidget(m_peakOverlaysButton);
+
+  m_autoscaling = new QCheckBox("Autoscaling", this);
+  m_autoscaling->setChecked(true);
+  connect(m_autoscaling, SIGNAL(toggled(bool)), this,
+          SLOT(setColorMapAutoscaling(bool)));
+
+  // layout
+  renderControlsLayout->addWidget(m_surfaceTypeButton);
+  renderControlsLayout->addLayout(unwrappedControlsLayout);
+  renderControlsLayout->addWidget(axisViewFrame);
+  renderControlsLayout->addWidget(displaySettings);
+  renderControlsLayout->addWidget(mSaveImage);
+  renderControlsLayout->addWidget(m_colorMapWidget);
+  renderControlsLayout->addWidget(m_autoscaling);
+}
+
+InstrumentWidgetRenderTab::~InstrumentWidgetRenderTab() {}
+
+/** Sets up the controls and surrounding layout that allows uses to view the
+* instrument
+*  from an axis that they select
+*  @return the QFrame that will be inserted on the main instrument view form
+*/
+QFrame *InstrumentWidgetRenderTab::setupAxisFrame() {
+  m_resetViewFrame = new QFrame();
+  QHBoxLayout *axisViewLayout = new QHBoxLayout();
+  axisViewLayout->addWidget(new QLabel("Axis View:"));
+
+  mAxisCombo = new QComboBox();
+  mAxisCombo->addItem("Z+");
+  mAxisCombo->addItem("Z-");
+  mAxisCombo->addItem("X+");
+  mAxisCombo->addItem("X-");
+  mAxisCombo->addItem("Y+");
+  mAxisCombo->addItem("Y-");
+
+  axisViewLayout->addWidget(mAxisCombo);
+  m_resetViewFrame->setLayout(axisViewLayout);
+
+  connect(mAxisCombo, SIGNAL(currentIndexChanged(const QString &)),
+          m_instrWidget, SLOT(setViewDirection(const QString &)));
+
+  return m_resetViewFrame;
+}
+
+/**
+* Set checked n-th menu item in m_setPrecison menu.
+*/
+void InstrumentWidgetRenderTab::setPrecisionMenuItemChecked(int n) {
+  for (int i = 0; i < m_precisionActions.size(); ++i) {
+    QAction *prec = m_precisionActions[i];
+    if (i == n - 1) {
+      prec->setChecked(true);
+      break;
+    }
+  }
+}
+
+/**
+* Enable/disable the Full 3D menu option
+* @param on :: True to enable.
+*/
+void InstrumentWidgetRenderTab::enable3DSurface(bool on) {
+  m_full3D->setEnabled(on);
+  if (on) {
+    m_full3D->setToolTip("");
+  } else {
+    m_full3D->setToolTip(
+        "Disabled: check \"Use OpenGL\" option in Display Settings to enable");
+  }
+}
+
+/**
+* Surface-specific adjustments.
+*/
+void InstrumentWidgetRenderTab::initSurface() {
+  setAxis(QString::fromStdString(
+      m_instrWidget->getInstrumentActor()->getInstrument()->getDefaultAxis()));
+  auto surface = getSurface();
+
+  // 3D axes switch needs to be shown for the 3D surface
+  auto p3d = boost::dynamic_pointer_cast<Projection3D>(surface);
+  if (p3d) {
+    p3d->set3DAxesState(areAxesOn());
+  }
+
+  bool detectorsOnly = !m_instrWidget->getInstrumentActor()->areGuidesShown();
+  m_displayDetectorsOnly->blockSignals(true);
+  m_displayDetectorsOnly->setChecked(detectorsOnly);
+  m_displayDetectorsOnly->blockSignals(false);
+  setPrecisionMenuItemChecked(surface->getPeakLabelPrecision());
+
+  // enable u-correction for surfaces of rotation. correction applied in the
+  // last
+  // session is loaded and re-applied in the new session
+  auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
+  if (rotSurface) {
+    m_UCorrection->setEnabled(true);
+    QString groupName = m_instrWidget->getInstrumentSettingsGroupName();
+    QSettings settings;
+    settings.beginGroup(groupName);
+    bool isManualUCorrection =
+        settings.value(EntryManualUCorrection, false).toBool();
+    if (isManualUCorrection) {
+      double ucorrMin = settings.value(EntryUCorrectionMin, 0.0).toDouble();
+      double ucorrMax = settings.value(EntryUCorrectionMax, 0.0).toDouble();
+      rotSurface->setUCorrection(ucorrMin, ucorrMax);
+    }
+  } else {
+    m_UCorrection->setEnabled(false);
+  }
+}
+
+/**
+*
+*/
+void InstrumentWidgetRenderTab::setupColorBarScaling(const MantidColorMap &cmap,
+                                                     double minPositive) {
+  m_colorMapWidget->setMinPositiveValue(minPositive);
+  m_colorMapWidget->setupColorBarScaling(cmap);
+}
+
+/**
+* Change color map button slot. This provides the file dialog box to select
+* colormap or sets it directly a string is provided
+*/
+void InstrumentWidgetRenderTab::changeColorMap(const QString &filename) {
+  m_instrWidget->changeColormap(filename);
+}
+
+void InstrumentWidgetRenderTab::loadSettings(const QSettings &settings) {
+  int show3daxes = settings.value("3DAxesShown", 1).toInt();
+  m_instrWidget->set3DAxesState(show3daxes != 0);
+  m_displayAxes->blockSignals(true);
+  m_displayAxes->setChecked(show3daxes != 0);
+  m_displayAxes->blockSignals(false);
+}
+
+void InstrumentWidgetRenderTab::saveSettings(QSettings &settings) const {
+  int val = 0;
+  if (m_displayAxes->isChecked())
+    val = 1;
+  settings.setValue("3DAxesShown", QVariant(val));
+}
+
+/**
+* Set minimum value on the colormap scale.
+* @param value :: New value to set.
+* @param apply ::
+*/
+void InstrumentWidgetRenderTab::setMinValue(double value, bool apply) {
+  if (!apply)
+    m_colorMapWidget->blockSignals(true);
+  m_colorMapWidget->setMinValue(value);
+  if (!apply)
+    m_colorMapWidget->blockSignals(false);
+}
+
+/**
+* Set maximum value on the colormap scale.
+* @param value :: New value to set.
+* @param apply ::
+*/
+void InstrumentWidgetRenderTab::setMaxValue(double value, bool apply) {
+  if (!apply)
+    m_colorMapWidget->blockSignals(true);
+  m_colorMapWidget->setMaxValue(value);
+  if (!apply)
+    m_colorMapWidget->blockSignals(false);
+}
+
+/**
+* Set minimum and maximum values on the colormap scale.
+* @param minValue :: New min value to set.
+* @param maxValue :: New max value to set.
+* @param apply ::
+*/
+void InstrumentWidgetRenderTab::setRange(double minValue, double maxValue,
+                                         bool apply) {
+  if (!apply)
+    m_colorMapWidget->blockSignals(true);
+  m_colorMapWidget->setMinValue(minValue);
+  m_colorMapWidget->setMaxValue(maxValue);
+  if (!apply)
+    m_colorMapWidget->blockSignals(false);
+}
+
+GraphOptions::ScaleType InstrumentWidgetRenderTab::getScaleType() const {
+  return (GraphOptions::ScaleType)m_colorMapWidget->getScaleType();
+}
+
+void InstrumentWidgetRenderTab::setScaleType(GraphOptions::ScaleType type) {
+  m_colorMapWidget->setScaleType(type);
+}
+
+void InstrumentWidgetRenderTab::setAxis(const QString &axisNameArg) {
+  QString axisName = axisNameArg.toUpper();
+  int axisInd = mAxisCombo->findText(axisName.toUpper());
+  if (axisInd < 0)
+    axisInd = 0;
+  mAxisCombo->setCurrentIndex(axisInd);
+}
+
+bool InstrumentWidgetRenderTab::areAxesOn() const {
+  return m_displayAxes->isChecked();
+}
+
+/**
+* Show ResetView combo box only with 3D view
+* @param iv Index of a render mode in RenderMode combo box. iv == 0 is 3D view
+*/
+void InstrumentWidgetRenderTab::showResetView(int iv) {
+  m_resetViewFrame->setVisible(iv == 0);
+}
+
+void InstrumentWidgetRenderTab::showFlipControl(int iv) {
+  bool vis = iv != 0;
+  m_flipCheckBox->setVisible(vis);
+  m_peakOverlaysButton->setVisible(vis);
+}
+
+/**
+* Toggle display of 3D axes.
+*
+* @param on :: True of false for on and off.
+*/
+void InstrumentWidgetRenderTab::showAxes(bool on) {
+  m_instrWidget->set3DAxesState(on);
+  m_displayAxes->blockSignals(true);
+  m_displayAxes->setChecked(on);
+  m_displayAxes->blockSignals(false);
+}
+
+/**
+* Toggle display of guide and other non-detector components.
+*
+* @param yes :: True of false for on and off.
+*/
+void InstrumentWidgetRenderTab::displayDetectorsOnly(bool yes) {
+  m_instrWidget->getInstrumentActor()->showGuides(!yes);
+  m_instrWidget->updateInstrumentView();
+  m_displayDetectorsOnly->blockSignals(true);
+  m_displayDetectorsOnly->setChecked(yes);
+  m_displayDetectorsOnly->blockSignals(false);
+}
+
+/**
+* Toggle use of OpenGL
+*
+* @param on :: True of false for on and off.
+*/
+void InstrumentWidgetRenderTab::enableGL(bool on) {
+  m_instrWidget->enableGL(on);
+  m_GLView->blockSignals(true);
+  m_GLView->setChecked(m_instrWidget->isGLEnabled());
+  m_GLView->blockSignals(false);
+  enable3DSurface(on);
+}
+
+void InstrumentWidgetRenderTab::showEvent(QShowEvent *) {
+  auto surface = getSurface();
+  if (surface) {
+    surface->setInteractionMode(ProjectionSurface::MoveMode);
+  }
+  InstrumentActor *actor = m_instrWidget->getInstrumentActor();
+  if (actor) {
+    auto visitor = SetAllVisibleVisitor(actor->areGuidesShown());
+    actor->accept(visitor);
+    getSurface()->updateView();
+    getSurface()->requestRedraw();
+  }
+}
+
+void InstrumentWidgetRenderTab::flipUnwrappedView(bool on) {
+  auto surface = boost::dynamic_pointer_cast<UnwrappedSurface>(
+      m_instrWidget->getSurface());
+  if (!surface)
+    return;
+  surface->setFlippedView(on);
+  m_instrWidget->updateInstrumentView();
+  // Sync checkbox
+  m_flipCheckBox->blockSignals(true);
+  m_flipCheckBox->setChecked(on);
+  m_flipCheckBox->blockSignals(false);
+}
+
+/**
+* Saves the current image buffer to the given file. An empty string raises a
+* dialog
+* for finding the file
+* @param filename Optional full path of the saved image
+*/
+void InstrumentWidgetRenderTab::saveImage(QString filename) {
+  m_instrWidget->saveImage(filename);
+}
+
+/**
+* Reset the colorbar parameters.
+* @param cmap :: A new Mantid color map.
+* @param minValue :: A new minimum value.
+* @param maxValue :: A new maximum value.
+* @param minPositive :: A new minimum positive value for the log scale.
+* @param autoscaling :: Flag to set autoscaling of the color
+*/
+void InstrumentWidgetRenderTab::setupColorBar(const MantidColorMap &cmap,
+                                              double minValue, double maxValue,
+                                              double minPositive,
+                                              bool autoscaling) {
+  setMinValue(minValue, false);
+  setMaxValue(maxValue, false);
+  m_colorMapWidget->setMinPositiveValue(minPositive);
+  m_colorMapWidget->setupColorBarScaling(cmap);
+  m_autoscaling->blockSignals(true);
+  m_autoscaling->setChecked(autoscaling);
+  m_autoscaling->blockSignals(false);
+}
+
+/**
+* Set on / off autoscaling of the color bar.
+*/
+void InstrumentWidgetRenderTab::setColorMapAutoscaling(bool on) {
+  emit setAutoscaling(on);
+}
+
+/**
+* Creates a menu for interaction with peak overlays
+*/
+QMenu *InstrumentWidgetRenderTab::createPeaksMenu() {
+  QSettings settings;
+  settings.beginGroup(m_instrWidget->getSettingsGroupName());
+  QMenu *menu = new QMenu(this);
+
+  // show/hide peak hkl labels
+  QAction *showLabels = new QAction("Show labels", this);
+  showLabels->setCheckable(true);
+  showLabels->setChecked(settings.value("ShowPeakLabels", true).toBool());
+  connect(showLabels, SIGNAL(toggled(bool)), m_instrWidget,
+          SLOT(setShowPeakLabelsFlag(bool)));
+  menu->addAction(showLabels);
+  // show/hide peak table rows
+  QAction *showRows = new QAction("Show rows", this);
+  showRows->setCheckable(true);
+  showRows->setChecked(settings.value("ShowPeakRows", true).toBool());
+  connect(showRows, SIGNAL(toggled(bool)), m_instrWidget,
+          SLOT(setShowPeakRowFlag(bool)));
+  connect(showLabels, SIGNAL(toggled(bool)), showRows, SLOT(setEnabled(bool)));
+  showRows->setEnabled(showLabels->isChecked());
+  menu->addAction(showRows);
+  // setting precision set of actions
+  QMenu *setPrecision = new QMenu("Label precision", this);
+  m_precisionActionGroup = new QActionGroup(this);
+  QSignalMapper *signalMapper = new QSignalMapper(this);
+  for (int i = 1; i < 10; ++i) {
+    QAction *prec = new QAction(QString::number(i), setPrecision);
+    prec->setCheckable(true);
+    setPrecision->addAction(prec);
+    connect(prec, SIGNAL(triggered()), signalMapper, SLOT(map()));
+    signalMapper->setMapping(prec, i);
+    m_precisionActions.append(prec);
+    m_precisionActionGroup->addAction(prec);
+  }
+  connect(signalMapper, SIGNAL(mapped(int)), m_instrWidget,
+          SLOT(setPeakLabelPrecision(int)));
+  menu->addMenu(setPrecision);
+
+  QAction *showRelativeIntensity =
+      new QAction("Indicate relative intensity", this);
+  showRelativeIntensity->setCheckable(true);
+  showRelativeIntensity->setChecked(
+      settings.value("ShowPeakRelativeIntensities", false).toBool());
+  connect(showRelativeIntensity, SIGNAL(toggled(bool)), m_instrWidget,
+          SLOT(setShowPeakRelativeIntensity(bool)));
+  menu->addAction(showRelativeIntensity);
+
+  // Clear peaks action
+  QAction *clearPeaks = new QAction("Clear peaks", this);
+  connect(clearPeaks, SIGNAL(triggered()), m_instrWidget,
+          SLOT(clearPeakOverlays()));
+  menu->addAction(clearPeaks);
+  return menu;
+}
+
+/**
+* Called before the display setting menu opens. Filters out menu options.
+*/
+void InstrumentWidgetRenderTab::displaySettingsAboutToshow() {
+  if (m_instrWidget->getSurfaceType() == InstrumentWidget::FULL3D) {
+    // in 3D mode use GL widget only and allow lighting
+    m_GLView->setEnabled(false);
+    m_lighting->setEnabled(true);
+  } else {
+    // in flat view mode allow changing to simple, non-GL viewer
+    m_GLView->setEnabled(true);
+    // allow lighting in GL viewer only
+    if (!m_GLView->isChecked()) {
+      m_lighting->setEnabled(false);
+    } else {
+      m_lighting->setEnabled(true);
+    }
+  }
+}
+
+/**
+* Change the type of the surface.
+* @param index :: Index selected in the surface type combo box.
+*/
+void InstrumentWidgetRenderTab::setSurfaceType(int index) {
+  if ((int)m_instrWidget->getSurfaceType() != index) {
+    m_instrWidget->setSurfaceType(index);
+  }
+}
+
+/**
+* Respond to surface change from script.
+* @param index :: Index selected in the surface type combo box.
+*/
+void InstrumentWidgetRenderTab::surfaceTypeChanged(int index) {
+  // display action's text on the render mode button
+  QAction *action = m_surfaceTypeActionGroup->actions()[index];
+  m_surfaceTypeButton->setText(action->text());
+
+  // if action isn't checked then this method is called from script
+  if (!action->isChecked()) {
+    // checking action calls setSurfaceType slot
+    action->setChecked(true);
+  }
+  showFlipControl(index);
+  showResetView(index);
+}
+
+/**
+* Respond to external change of the colormap.
+*/
+void InstrumentWidgetRenderTab::colorMapChanged() {
+  InstrumentActor *instrumentActor = m_instrWidget->getInstrumentActor();
+  setupColorBar(instrumentActor->getColorMap(), instrumentActor->minValue(),
+                instrumentActor->maxValue(),
+                instrumentActor->minPositiveValue(),
+                instrumentActor->autoscaling());
+}
+
+void InstrumentWidgetRenderTab::scaleTypeChanged(int type) {
+  setScaleType((GraphOptions::ScaleType)type);
+}
+
+void InstrumentWidgetRenderTab::nthPowerChanged(double nth_power) {
+  m_colorMapWidget->setNthPower(nth_power);
+}
+
+/**
+* Update the GUI element after the "Use OpenGL" option has been changed
+* programmatically.
+* @param on :: True for enabling OpenGL, false for disabling.
+*/
+void InstrumentWidgetRenderTab::glOptionChanged(bool on) {
+  m_GLView->blockSignals(true);
+  m_GLView->setChecked(on);
+  m_GLView->blockSignals(false);
+}
+
+/**
+* Show the tooltip of an action which is attached to a menu.
+*/
+void InstrumentWidgetRenderTab::showMenuToolTip(QAction *action) {
+  QToolTip::showText(QCursor::pos(), action->toolTip(), this);
+}
+
+/**
+* Set the offset in u-coordinate of a 2d (unwrapped) surface
+*/
+void InstrumentWidgetRenderTab::setUCorrection() {
+  auto surface = getSurface();
+  auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
+  if (rotSurface) {
+    QPointF oldUCorr = rotSurface->getUCorrection();
+    // ask the user to enter a number for the u-correction
+    UCorrectionDialog dlg(this, oldUCorr, rotSurface->isManualUCorrection());
+    if (dlg.exec() != QDialog::Accepted)
+      return;
+
+    QSettings settings;
+    settings.beginGroup(m_instrWidget->getInstrumentSettingsGroupName());
+
+    if (dlg.applyCorrection()) {
+      QPointF ucorr = dlg.getValue();
+      // update the surface only if the correction changes
+      if (ucorr != oldUCorr) {
+        rotSurface->setUCorrection(ucorr.x(),
+                                   ucorr.y()); // manually set the correction
+        rotSurface->requestRedraw();           // redraw the view
+        settings.setValue(EntryManualUCorrection, true);
+        settings.setValue(EntryUCorrectionMin, ucorr.x());
+        settings.setValue(EntryUCorrectionMax, ucorr.y());
+      }
+    } else {
+      rotSurface->setAutomaticUCorrection(); // switch to automatic correction
+      rotSurface->requestRedraw();           // redraw the view
+      settings.remove(EntryManualUCorrection);
+      settings.remove(EntryUCorrectionMin);
+      settings.remove(EntryUCorrectionMax);
+    }
+  }
+}
+
+/**
+* Get current value for the u-correction for a RotationSurface.
+* Return 0 if it's not a RotationSurface.
+*/
+QPointF InstrumentWidgetRenderTab::getUCorrection() const {
+  auto surface = getSurface();
+  auto rotSurface = boost::dynamic_pointer_cast<RotationSurface>(surface);
+  if (rotSurface) {
+    return rotSurface->getUCorrection();
+  }
+  return QPointF();
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTab.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTab.cpp
index 5bf562a21693a0670190d92212eed3a5d00566ca..fc88fad38f5204123d7abcfa5dce8c629d365b19 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTab.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTab.cpp
@@ -1,22 +1,16 @@
 #include "MantidQtMantidWidgets/InstrumentView/InstrumentWidgetTab.h"
 #include "MantidQtMantidWidgets/InstrumentView/InstrumentWidget.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		InstrumentWidgetTab::InstrumentWidgetTab(InstrumentWidget *parent) :
-			QFrame(parent), m_instrWidget(parent)
-		{
-		}
-
-		/**
-		* Return a pointer to the projection surface.
-		*/
-		boost::shared_ptr<ProjectionSurface> InstrumentWidgetTab::getSurface() const
-		{
-			return m_instrWidget->getSurface();
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+InstrumentWidgetTab::InstrumentWidgetTab(InstrumentWidget *parent)
+    : QFrame(parent), m_instrWidget(parent) {}
 
+/**
+* Return a pointer to the projection surface.
+*/
+boost::shared_ptr<ProjectionSurface> InstrumentWidgetTab::getSurface() const {
+  return m_instrWidget->getSurface();
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTreeTab.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTreeTab.cpp
index 1cc465f2b91e95757466acad11755eb52137e812..559e336970e5d036995089808e0ce90f69c79419 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTreeTab.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetTreeTab.cpp
@@ -8,58 +8,56 @@
 #include <QVBoxLayout>
 #include <QMessageBox>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		InstrumentWidgetTreeTab::InstrumentWidgetTreeTab(InstrumentWidget *instrWidget)
-			: InstrumentWidgetTab(instrWidget) {
-			QVBoxLayout *layout = new QVBoxLayout(this);
-			// Tree Controls
-			m_instrumentTree = new InstrumentTreeWidget(0);
-			layout->addWidget(m_instrumentTree);
-			connect(m_instrumentTree,
-				SIGNAL(componentSelected(Mantid::Geometry::ComponentID)),
-				m_instrWidget,
-				SLOT(componentSelected(Mantid::Geometry::ComponentID)));
-			connect(m_instrWidget, SIGNAL(requestSelectComponent(QString)), this,
-				SLOT(selectComponentByName(QString)));
-		}
+InstrumentWidgetTreeTab::InstrumentWidgetTreeTab(InstrumentWidget *instrWidget)
+    : InstrumentWidgetTab(instrWidget) {
+  QVBoxLayout *layout = new QVBoxLayout(this);
+  // Tree Controls
+  m_instrumentTree = new InstrumentTreeWidget(0);
+  layout->addWidget(m_instrumentTree);
+  connect(m_instrumentTree,
+          SIGNAL(componentSelected(Mantid::Geometry::ComponentID)),
+          m_instrWidget,
+          SLOT(componentSelected(Mantid::Geometry::ComponentID)));
+  connect(m_instrWidget, SIGNAL(requestSelectComponent(QString)), this,
+          SLOT(selectComponentByName(QString)));
+}
 
-		void InstrumentWidgetTreeTab::initSurface() {
-			m_instrumentTree->setInstrumentActor(m_instrWidget->getInstrumentActor());
-		}
+void InstrumentWidgetTreeTab::initSurface() {
+  m_instrumentTree->setInstrumentActor(m_instrWidget->getInstrumentActor());
+}
 
-		/**
-			* Find an instrument component by its name. This is used from the
-			* scripting API and errors (component not found) are shown as a
-			* message box in the GUI.
-			*
-			* @param name :: Name of an instrument component.
-			*/
-		void InstrumentWidgetTreeTab::selectComponentByName(const QString &name) {
-			QModelIndex component = m_instrumentTree->findComponentByName(name);
-			if (!component.isValid()) {
-				QMessageBox::warning(this, "Instrument Window - Tree Tab - Error",
-					"No component named '" + name +
-					"' was found. "
-					"Please use a valid component name ");
-				return;
-			}
+/**
+        * Find an instrument component by its name. This is used from the
+        * scripting API and errors (component not found) are shown as a
+        * message box in the GUI.
+        *
+        * @param name :: Name of an instrument component.
+        */
+void InstrumentWidgetTreeTab::selectComponentByName(const QString &name) {
+  QModelIndex component = m_instrumentTree->findComponentByName(name);
+  if (!component.isValid()) {
+    QMessageBox::warning(this, "Instrument Window - Tree Tab - Error",
+                         "No component named '" + name +
+                             "' was found. "
+                             "Please use a valid component name ");
+    return;
+  }
 
-			m_instrumentTree->clearSelection();
-			m_instrumentTree->scrollTo(component, QAbstractItemView::EnsureVisible);
-			m_instrumentTree->selectionModel()->select(component,
-				QItemSelectionModel::Select);
-			m_instrumentTree->sendComponentSelectedSignal(component);
-		}
+  m_instrumentTree->clearSelection();
+  m_instrumentTree->scrollTo(component, QAbstractItemView::EnsureVisible);
+  m_instrumentTree->selectionModel()->select(component,
+                                             QItemSelectionModel::Select);
+  m_instrumentTree->sendComponentSelectedSignal(component);
+}
 
-		/**
-			* Update surface when tab becomes visible.
-			*/
-		void InstrumentWidgetTreeTab::showEvent(QShowEvent *) {
-			getSurface()->setInteractionMode(ProjectionSurface::MoveMode);
-		}
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+/**
+        * Update surface when tab becomes visible.
+        */
+void InstrumentWidgetTreeTab::showEvent(QShowEvent *) {
+  getSurface()->setInteractionMode(ProjectionSurface::MoveMode);
+}
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/MantidGLWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/MantidGLWidget.cpp
index 932f096ef353eda5589bbc4b4bfb058e841b1d26..196ef73d61ae6b5010b3e95ee6709fb2dcfc3500 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/MantidGLWidget.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/MantidGLWidget.cpp
@@ -18,339 +18,314 @@
 #include <cfloat>
 #include <typeinfo>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		//#ifndef GL_MULTISAMPLE
-		//#define GL_MULTISAMPLE  0x809D
-		//#endif
-
-		//NOTES:
-		//1) if the sample buffers are not available then the paint of image on the mdi windows
-		//   seems to not work on intel chipset
-
-		const Qt::CursorShape cursorShape = Qt::ArrowCursor;
-
-		MantidGLWidget::MantidGLWidget(QWidget* parent) :
-			QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::NoAlphaChannel), parent),
-			//m_polygonMode(SOLID),
-			//m_lightingState(0),
-			m_isKeyPressed(false),
-			m_firstFrame(true)
-		{
-
-			if (!this->format().depth())
-			{
-				std::cout << "Warning! OpenGL Depth buffer could not be initialized.\n";
-			}
-
-			setFocusPolicy(Qt::StrongFocus);
-			setAutoFillBackground(false);
-			//Enable right-click in pick mode
-			setContextMenuPolicy(Qt::DefaultContextMenu);
-			setMouseTracking(true);
-		}
-
-		MantidGLWidget::~MantidGLWidget()
-		{
-		}
-
-		void MantidGLWidget::setSurface(boost::shared_ptr<ProjectionSurface> surface)
-		{
-			m_surface = surface;
-			connect(m_surface.get(), SIGNAL(redrawRequired()), this, SLOT(repaint()), Qt::QueuedConnection);
-			m_firstFrame = true;
-		}
-
-		/**
-		* This method initializes the opengl settings. its invoked defaultly by Qt when the widget
-		* is initialized.
-		*/
-		void MantidGLWidget::initializeGL()
-		{
-			setCursor(cursorShape); // This is to set the initial window mouse cursor to Hand icon
-
-									// Set the relevant OpenGL rendering options
-			setRenderingOptions();
-			glViewport(0, 0, width(), height());
-
-			// Clear the memory buffers
-			QColor bgColor = currentBackgroundColor();
-			glClearColor(GLclampf(bgColor.red() / 255.0), GLclampf(bgColor.green() / 255.0), GLclampf(bgColor.blue() / 255.0), 1.0);
-		}
-
-		void MantidGLWidget::setRenderingOptions()
-		{
-			// Enable depth testing. This only draws points that are not hidden by other objects
-			glEnable(GL_DEPTH_TEST);
-
-			// Depth function for testing is Less than or equal                        
-			glDepthFunc(GL_LEQUAL);
-
-			// Disable colour blending
-			glDisable(GL_BLEND);
-
-			//Disable face culling because some polygons are visible from the back.
-			glDisable(GL_CULL_FACE);
-
-			//enablewriting into the depth buffer
-			glDepthMask(GL_TRUE);
-
-			OpenGLError::check("setRenderingOptions");
-		}
-
-		/**
-		* This is overridden function which is called by Qt when the widget needs to be repainted.
-		*/
-		void MantidGLWidget::paintEvent(QPaintEvent *event)
-		{
-			UNUSED_ARG(event)
-				makeCurrent();
-			if (m_surface)
-			{
-				m_surface->draw(this);
-			}
-
-			OpenGLError::check("paintEvent");
-
-			if (m_firstFrame)
-			{
-				m_firstFrame = false;
-			}
-		}
-
-		/**
-		* This function is also overridden from the parent. This method is invoked when the widget is resized
-		* This method resizes the viewport according to the new widget width and height
-		*/
-		void MantidGLWidget::resizeGL(int width, int height)
-		{
-			if (m_surface)
-			{
-				m_surface->resize(width, height);
-			}
-		}
-
-		/**
-		* Called when a context menu event is recieved
-		*/
-		void MantidGLWidget::contextMenuEvent(QContextMenuEvent * event)
-		{
-			UNUSED_ARG(event) //avoid compiler warning
-		}
-
-		/**
-		* Mouse press callback method, It implements mouse button press initialize methods.
-		* Left Button: Zoom
-		* Right Button: Rotate
-		* Middle Button: Translate
-		* Key + Left Button: Pick (TODO: Yet to implement)
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void MantidGLWidget::mousePressEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mousePressEvent(event);
-			}
-			update();
-		}
-
-		/**
-		* This is mouse move callback method. It implements the actions to be taken when the mouse is
-		* moved with a particular button is pressed.
-		* Left Button: Zoom
-		* Right Button: Rotate
-		* Middle Button: Translate
-		* Key + Left Button: Pick (TODO: Yet to implement)
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void MantidGLWidget::mouseMoveEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mouseMoveEvent(event);
-			}
-			repaint();
-		}
-
-		/**
-		* This is mouse button release callback method. This resets the cursor to pointing hand cursor
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void MantidGLWidget::mouseReleaseEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mouseReleaseEvent(event);
-			}
-			repaint();
-		}
-
-		/**
-		* Mouse wheel event to set the zooming in and out
-		* @param event :: This is the event variable which has the status of the wheel
-		*/
-		void MantidGLWidget::wheelEvent(QWheelEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->wheelEvent(event);
-			}
-			update();
-		}
-
-		/**
-		* This method is to handle keyboard events to mimic the mouse operations of click and move
-		* @param event :: This is the event variable which has the status of the keyboard
-		*/
-		void MantidGLWidget::keyPressEvent(QKeyEvent *event)
-		{
-			if (m_surface)
-			{
-				m_surface->keyPressEvent(event);
-			}
-			update();
-		}
-
-		/**
-		* This method is to handle keyboard events to mimic the mouse operations of mouse button up.
-		* @param event :: This is the event variable which has the status of the keyboard
-		*/
-		void MantidGLWidget::keyReleaseEvent(QKeyEvent *event)
-		{
-			releaseKeyboard();
-			setCursor(cursorShape);
-			m_isKeyPressed = false;
-			if (!event->isAutoRepeat())
-			{
-				update();
-			}
-			OpenGLError::check("MantidGLWidget::keyReleaseEvent");
-		}
-
-		/**
-		* This method set the background color.
-		*/
-		void MantidGLWidget::setBackgroundColor(QColor input)
-		{
-			makeCurrent();
-			glClearColor(GLclampf(input.red() / 255.0), GLclampf(input.green() / 255.0), GLclampf(input.blue() / 255.0), 1.0);
-			OpenGLError::check("MantidGLWidget::setBackgroundColor");
-			if (m_surface)
-			{
-				m_surface->setBackgroundColor(input);
-				m_surface->updateView(false);
-			}
-			update();
-		}
-
-		QColor MantidGLWidget::currentBackgroundColor() const
-		{
-			return m_surface ? m_surface->getBackgroundColor() : QColor(Qt::black);
-		}
-
-		/**
-		* This saves the GL scene to a file.
-		* @param filename :: The name of the file
-		*/
-		void MantidGLWidget::saveToFile(const QString & filename)
-		{
-			if (filename.isEmpty()) return;
-			// It seems QGLWidget grabs the back buffer
-			this->swapBuffers(); // temporarily swap the buffers
-			QImage image = this->grabFrameBuffer();
-			this->swapBuffers(); // swap them back
-			OpenGLError::check("MantidGLWidget::saveToFile");
-			image.save(filename);
-		}
-
-		/**
-		* Resets the widget for new instrument definition
-		*/
-		void MantidGLWidget::resetWidget()
-		{
-			//setActorCollection(boost::shared_ptr<GLActorCollection>(new GLActorCollection()));
-		}
-
-		/**
-		* Enables / disables lighting on the surfaces that support it.
-		* @param on :: Set true to turn lighting on or false to turn it off.
-		*/
-		void MantidGLWidget::enableLighting(bool on)
-		{
-			if (m_surface)
-			{
-				m_surface->enableLighting(on);
-				updateView();
-			}
-		}
-
-		void MantidGLWidget::draw()
-		{
-			QApplication::setOverrideCursor(Qt::WaitCursor);
-			if (m_surface)
-			{
-				m_surface->draw(this);
-			}
-			QApplication::restoreOverrideCursor();
-			OpenGLError::check("MantidGLWidget::drawUnwrapped()");
-		}
-
-		void MantidGLWidget::componentSelected(Mantid::Geometry::ComponentID id)
-		{
-			if (m_surface)
-			{
-				m_surface->componentSelected(id);
-				m_surface->updateView();
-				update();
-			}
-		}
-
-		/// Redraw the view
-		/// @param picking :: Set to true to update the picking image regardless the interaction
-		///   mode of the surface.
-		void MantidGLWidget::updateView(bool picking)
-		{
-			if (m_surface)
-			{
-				m_surface->updateView(picking);
-				update();
-			}
-		}
-
-		void MantidGLWidget::updateDetectors()
-		{
-			if (m_surface)
-			{
-				m_surface->updateDetectors();
-				update();
-			}
-		}
-
-		void MantidGLWidget::enterEvent(QEvent *ev)
-		{
-			if (m_surface)
-			{
-				m_surface->enterEvent(ev);
-			}
-			update();
-		}
-
-		void MantidGLWidget::leaveEvent(QEvent* ev)
-		{
-			// Restore possible override cursor
-			while (QApplication::overrideCursor())
-			{
-				QApplication::restoreOverrideCursor();
-			}
-			if (m_surface)
-			{
-				m_surface->leaveEvent(ev);
-			}
-			update();
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+//#ifndef GL_MULTISAMPLE
+//#define GL_MULTISAMPLE  0x809D
+//#endif
+
+// NOTES:
+// 1) if the sample buffers are not available then the paint of image on the mdi
+// windows
+//   seems to not work on intel chipset
+
+const Qt::CursorShape cursorShape = Qt::ArrowCursor;
+
+MantidGLWidget::MantidGLWidget(QWidget *parent)
+    : QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::NoAlphaChannel), parent),
+      // m_polygonMode(SOLID),
+      // m_lightingState(0),
+      m_isKeyPressed(false), m_firstFrame(true) {
+
+  if (!this->format().depth()) {
+    std::cout << "Warning! OpenGL Depth buffer could not be initialized.\n";
+  }
+
+  setFocusPolicy(Qt::StrongFocus);
+  setAutoFillBackground(false);
+  // Enable right-click in pick mode
+  setContextMenuPolicy(Qt::DefaultContextMenu);
+  setMouseTracking(true);
+}
+
+MantidGLWidget::~MantidGLWidget() {}
+
+void MantidGLWidget::setSurface(boost::shared_ptr<ProjectionSurface> surface) {
+  m_surface = surface;
+  connect(m_surface.get(), SIGNAL(redrawRequired()), this, SLOT(repaint()),
+          Qt::QueuedConnection);
+  m_firstFrame = true;
+}
+
+/**
+* This method initializes the opengl settings. its invoked defaultly by Qt when
+* the widget
+* is initialized.
+*/
+void MantidGLWidget::initializeGL() {
+  setCursor(cursorShape); // This is to set the initial window mouse cursor to
+                          // Hand icon
+
+  // Set the relevant OpenGL rendering options
+  setRenderingOptions();
+  glViewport(0, 0, width(), height());
+
+  // Clear the memory buffers
+  QColor bgColor = currentBackgroundColor();
+  glClearColor(GLclampf(bgColor.red() / 255.0),
+               GLclampf(bgColor.green() / 255.0),
+               GLclampf(bgColor.blue() / 255.0), 1.0);
+}
+
+void MantidGLWidget::setRenderingOptions() {
+  // Enable depth testing. This only draws points that are not hidden by other
+  // objects
+  glEnable(GL_DEPTH_TEST);
+
+  // Depth function for testing is Less than or equal
+  glDepthFunc(GL_LEQUAL);
+
+  // Disable colour blending
+  glDisable(GL_BLEND);
+
+  // Disable face culling because some polygons are visible from the back.
+  glDisable(GL_CULL_FACE);
+
+  // enablewriting into the depth buffer
+  glDepthMask(GL_TRUE);
+
+  OpenGLError::check("setRenderingOptions");
+}
+
+/**
+* This is overridden function which is called by Qt when the widget needs to be
+* repainted.
+*/
+void MantidGLWidget::paintEvent(QPaintEvent *event) {
+  UNUSED_ARG(event)
+  makeCurrent();
+  if (m_surface) {
+    m_surface->draw(this);
+  }
+
+  OpenGLError::check("paintEvent");
+
+  if (m_firstFrame) {
+    m_firstFrame = false;
+  }
+}
+
+/**
+* This function is also overridden from the parent. This method is invoked when
+* the widget is resized
+* This method resizes the viewport according to the new widget width and height
+*/
+void MantidGLWidget::resizeGL(int width, int height) {
+  if (m_surface) {
+    m_surface->resize(width, height);
+  }
+}
+
+/**
+* Called when a context menu event is recieved
+*/
+void MantidGLWidget::contextMenuEvent(QContextMenuEvent *event) {
+  UNUSED_ARG(event) // avoid compiler warning
+}
+
+/**
+* Mouse press callback method, It implements mouse button press initialize
+* methods.
+* Left Button: Zoom
+* Right Button: Rotate
+* Middle Button: Translate
+* Key + Left Button: Pick (TODO: Yet to implement)
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void MantidGLWidget::mousePressEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mousePressEvent(event);
+  }
+  update();
+}
+
+/**
+* This is mouse move callback method. It implements the actions to be taken when
+* the mouse is
+* moved with a particular button is pressed.
+* Left Button: Zoom
+* Right Button: Rotate
+* Middle Button: Translate
+* Key + Left Button: Pick (TODO: Yet to implement)
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void MantidGLWidget::mouseMoveEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mouseMoveEvent(event);
+  }
+  repaint();
+}
+
+/**
+* This is mouse button release callback method. This resets the cursor to
+* pointing hand cursor
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void MantidGLWidget::mouseReleaseEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mouseReleaseEvent(event);
+  }
+  repaint();
+}
+
+/**
+* Mouse wheel event to set the zooming in and out
+* @param event :: This is the event variable which has the status of the wheel
+*/
+void MantidGLWidget::wheelEvent(QWheelEvent *event) {
+  if (m_surface) {
+    m_surface->wheelEvent(event);
+  }
+  update();
+}
+
+/**
+* This method is to handle keyboard events to mimic the mouse operations of
+* click and move
+* @param event :: This is the event variable which has the status of the
+* keyboard
+*/
+void MantidGLWidget::keyPressEvent(QKeyEvent *event) {
+  if (m_surface) {
+    m_surface->keyPressEvent(event);
+  }
+  update();
+}
+
+/**
+* This method is to handle keyboard events to mimic the mouse operations of
+* mouse button up.
+* @param event :: This is the event variable which has the status of the
+* keyboard
+*/
+void MantidGLWidget::keyReleaseEvent(QKeyEvent *event) {
+  releaseKeyboard();
+  setCursor(cursorShape);
+  m_isKeyPressed = false;
+  if (!event->isAutoRepeat()) {
+    update();
+  }
+  OpenGLError::check("MantidGLWidget::keyReleaseEvent");
+}
+
+/**
+* This method set the background color.
+*/
+void MantidGLWidget::setBackgroundColor(QColor input) {
+  makeCurrent();
+  glClearColor(GLclampf(input.red() / 255.0), GLclampf(input.green() / 255.0),
+               GLclampf(input.blue() / 255.0), 1.0);
+  OpenGLError::check("MantidGLWidget::setBackgroundColor");
+  if (m_surface) {
+    m_surface->setBackgroundColor(input);
+    m_surface->updateView(false);
+  }
+  update();
+}
+
+QColor MantidGLWidget::currentBackgroundColor() const {
+  return m_surface ? m_surface->getBackgroundColor() : QColor(Qt::black);
+}
+
+/**
+* This saves the GL scene to a file.
+* @param filename :: The name of the file
+*/
+void MantidGLWidget::saveToFile(const QString &filename) {
+  if (filename.isEmpty())
+    return;
+  // It seems QGLWidget grabs the back buffer
+  this->swapBuffers(); // temporarily swap the buffers
+  QImage image = this->grabFrameBuffer();
+  this->swapBuffers(); // swap them back
+  OpenGLError::check("MantidGLWidget::saveToFile");
+  image.save(filename);
+}
+
+/**
+* Resets the widget for new instrument definition
+*/
+void MantidGLWidget::resetWidget() {
+  // setActorCollection(boost::shared_ptr<GLActorCollection>(new
+  // GLActorCollection()));
+}
+
+/**
+* Enables / disables lighting on the surfaces that support it.
+* @param on :: Set true to turn lighting on or false to turn it off.
+*/
+void MantidGLWidget::enableLighting(bool on) {
+  if (m_surface) {
+    m_surface->enableLighting(on);
+    updateView();
+  }
+}
+
+void MantidGLWidget::draw() {
+  QApplication::setOverrideCursor(Qt::WaitCursor);
+  if (m_surface) {
+    m_surface->draw(this);
+  }
+  QApplication::restoreOverrideCursor();
+  OpenGLError::check("MantidGLWidget::drawUnwrapped()");
+}
+
+void MantidGLWidget::componentSelected(Mantid::Geometry::ComponentID id) {
+  if (m_surface) {
+    m_surface->componentSelected(id);
+    m_surface->updateView();
+    update();
+  }
+}
+
+/// Redraw the view
+/// @param picking :: Set to true to update the picking image regardless the
+/// interaction
+///   mode of the surface.
+void MantidGLWidget::updateView(bool picking) {
+  if (m_surface) {
+    m_surface->updateView(picking);
+    update();
+  }
+}
+
+void MantidGLWidget::updateDetectors() {
+  if (m_surface) {
+    m_surface->updateDetectors();
+    update();
+  }
+}
+
+void MantidGLWidget::enterEvent(QEvent *ev) {
+  if (m_surface) {
+    m_surface->enterEvent(ev);
+  }
+  update();
+}
+
+void MantidGLWidget::leaveEvent(QEvent *ev) {
+  // Restore possible override cursor
+  while (QApplication::overrideCursor()) {
+    QApplication::restoreOverrideCursor();
+  }
+  if (m_surface) {
+    m_surface->leaveEvent(ev);
+  }
+  update();
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/MaskBinsData.cpp b/MantidQt/MantidWidgets/src/InstrumentView/MaskBinsData.cpp
index 8f9a416112be146530b1b6a8f45ce853c4a09fbc..a1bb37a430af5ac884e2296a9f15e6c81986f907 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/MaskBinsData.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/MaskBinsData.cpp
@@ -4,68 +4,58 @@
 
 #include <vector>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/// Add a range of x values for bin masking.
-		void MaskBinsData::addXRange(double start, double end, const QList<int>& indices)
-		{
-			BinMask range(start, end);
-			range.spectra = indices;
-			m_masks.append(range);
-		}
-
-		/// Mask a given workspace according to the stored ranges.
-		/// @param wsName :: A workspace to mask.
-		void MaskBinsData::mask(const std::string& wsName) const
-		{
-			for (auto mask = m_masks.begin(); mask != m_masks.end(); ++mask)
-			{
-				auto &spectra = mask->spectra;
-				std::vector<int> spectraList(spectra.begin(), spectra.end());
-				auto alg = Mantid::API::AlgorithmManager::Instance().create("MaskBins", -1);
-				alg->setPropertyValue("InputWorkspace", wsName);
-				alg->setPropertyValue("OutputWorkspace", wsName);
-				alg->setProperty("SpectraList", spectraList);
-				alg->setProperty("XMin", mask->start);
-				alg->setProperty("XMax", mask->end);
-				alg->execute();
-			}
-		}
-
-		/// Check if there is no data
-		bool MaskBinsData::isEmpty() const
-		{
-			return m_masks.isEmpty();
-		}
-
-		/// Subtract integrated counts in the masked bins from given vector of integrated spectra.
-		/// @param workspace :: A workspace to integrate.
-		/// @param spectraIntgrs :: An in/out vector with integrated spectra. On input it must contain
-		///   integrals from workspace for all its spectra.
-		void MaskBinsData::subtractIntegratedSpectra(const Mantid::API::MatrixWorkspace& workspace, std::vector<double>& spectraIntgrs) const
-		{
-			for (auto mask = m_masks.begin(); mask != m_masks.end(); ++mask)
-			{
-				std::vector<double> subtract;
-				workspace.getIntegratedSpectra(subtract, mask->start, mask->end, false);
-				auto &spectra = mask->spectra;
-				for (auto ispec = spectra.begin(); ispec != spectra.end(); ++ispec)
-				{
-					auto counts = spectraIntgrs[*ispec] - subtract[*ispec];
-					spectraIntgrs[*ispec] = counts >= 0.0 ? counts : 0.0;
-				}
-			}
-		}
-
-		/// Clear the masking data
-		void MaskBinsData::clear()
-		{
-			m_masks.clear();
-		}
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+/// Add a range of x values for bin masking.
+void MaskBinsData::addXRange(double start, double end,
+                             const QList<int> &indices) {
+  BinMask range(start, end);
+  range.spectra = indices;
+  m_masks.append(range);
+}
+
+/// Mask a given workspace according to the stored ranges.
+/// @param wsName :: A workspace to mask.
+void MaskBinsData::mask(const std::string &wsName) const {
+  for (auto mask = m_masks.begin(); mask != m_masks.end(); ++mask) {
+    auto &spectra = mask->spectra;
+    std::vector<int> spectraList(spectra.begin(), spectra.end());
+    auto alg = Mantid::API::AlgorithmManager::Instance().create("MaskBins", -1);
+    alg->setPropertyValue("InputWorkspace", wsName);
+    alg->setPropertyValue("OutputWorkspace", wsName);
+    alg->setProperty("SpectraList", spectraList);
+    alg->setProperty("XMin", mask->start);
+    alg->setProperty("XMax", mask->end);
+    alg->execute();
+  }
+}
+
+/// Check if there is no data
+bool MaskBinsData::isEmpty() const { return m_masks.isEmpty(); }
+
+/// Subtract integrated counts in the masked bins from given vector of
+/// integrated spectra.
+/// @param workspace :: A workspace to integrate.
+/// @param spectraIntgrs :: An in/out vector with integrated spectra. On input
+/// it must contain
+///   integrals from workspace for all its spectra.
+void MaskBinsData::subtractIntegratedSpectra(
+    const Mantid::API::MatrixWorkspace &workspace,
+    std::vector<double> &spectraIntgrs) const {
+  for (auto mask = m_masks.begin(); mask != m_masks.end(); ++mask) {
+    std::vector<double> subtract;
+    workspace.getIntegratedSpectra(subtract, mask->start, mask->end, false);
+    auto &spectra = mask->spectra;
+    for (auto ispec = spectra.begin(); ispec != spectra.end(); ++ispec) {
+      auto counts = spectraIntgrs[*ispec] - subtract[*ispec];
+      spectraIntgrs[*ispec] = counts >= 0.0 ? counts : 0.0;
+    }
+  }
+}
+
+/// Clear the masking data
+void MaskBinsData::clear() { m_masks.clear(); }
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ObjCompAssemblyActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ObjCompAssemblyActor.cpp
index 67775e1b16853b4d7b49e6b6e7ef9e76b1ce04f7..dbdae6673b44cc9d1870bda3786d8747d15f82c3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ObjCompAssemblyActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ObjCompAssemblyActor.cpp
@@ -14,196 +14,187 @@
 using namespace Mantid;
 using namespace Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-        ObjCompAssemblyActor::ObjCompAssemblyActor(
-            const InstrumentActor &instrActor,
-            Mantid::Geometry::ComponentID compID)
-            : ICompAssemblyActor(instrActor, compID), m_idData(0), m_idPick(0),
-              m_n(getObjCompAssembly()->nelements()), m_pick_data(),
-              m_texturesGenerated(false) {
-
-          ObjCompAssembly_const_sptr objAss = getObjCompAssembly();
-          mNumberOfDetectors = objAss->nelements();
-          assert(static_cast<size_t>(m_n) == mNumberOfDetectors);
-          m_data = new unsigned char[m_n * 3];
-          m_pick_data = new unsigned char[m_n * 3];
-          for (size_t i = 0; i < getNumberOfDetectors(); ++i) {
-            IDetector_const_sptr det =
-                boost::dynamic_pointer_cast<const IDetector>(
-                    objAss->getChild(static_cast<int>(i)));
-            assert(det);
-            detid_t id = det->getID();
-            m_detIDs.push_back(id);
-            size_t pickID = instrActor.pushBackDetid(id);
-            setDetectorColor(m_pick_data, i, GLActor::makePickColor(pickID));
-          }
-          Mantid::Geometry::BoundingBox boundBox;
-          objAss->getBoundingBox(boundBox);
-          minBoundBox[0] = boundBox.xMin();
-          minBoundBox[1] = boundBox.yMin();
-          minBoundBox[2] = boundBox.zMin();
-          maxBoundBox[0] = boundBox.xMax();
-          maxBoundBox[1] = boundBox.yMax();
-          maxBoundBox[2] = boundBox.zMax();
-
-		}
-
-		/**
-		* Destructor which removes the actors created by this object
-		*/
-		ObjCompAssemblyActor::~ObjCompAssemblyActor()
-		{
-			if (m_data)
-			{
-				delete[] m_data;
-				delete[] m_pick_data;
-			}
-			if (m_texturesGenerated)
-			{
-				glDeleteTextures(1, &m_idData);
-				glDeleteTextures(1, &m_idPick);
-			}
-		}
-
-		/**
-		* This function is concrete implementation that renders the Child ObjComponents and Child CompAssembly's
-		*/
-		void ObjCompAssemblyActor::draw(bool picking)const
-		{
-			OpenGLError::check("ObjCompAssemblyActor::draw(0)");
-
-			if (!m_texturesGenerated)
-			{
-				setDataColors();
-				setPickColors();
-				m_texturesGenerated = true;
-			}
-
-			ObjCompAssembly_const_sptr objAss = getObjCompAssembly();
-			glPushMatrix();
-
-			unsigned int texID = picking ? m_idPick : m_idData;
-			// Because texture colours are combined with the geometry colour
-			// make sure the current colour is white
-			glColor3f(1.0f, 1.0f, 1.0f);
-			glEnable(GL_TEXTURE_2D);
-			glBindTexture(GL_TEXTURE_2D, texID);
-			objAss->draw();
-			glBindTexture(GL_TEXTURE_2D, 0);
-			OpenGLError::check("ObjCompAssemblyActor::draw()");
-
-			glPopMatrix();
-		}
-
-		void ObjCompAssemblyActor::generateTexture(unsigned char* data, unsigned int& id)const
-		{
-			if (id > 0)
-			{
-				glDeleteTextures(1, &id);
-				OpenGLError::check("TexObject::generateTexture()[delete texture] ");
-			}
-			bool vertical = true; // depends on the tex coordinates of the shape object
-
-			int width = m_n;
-			int height = 1;
-			if (vertical)
-			{
-				width = 1;
-				height = m_n;
-			}
-
-			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-			glGenTextures(1, &id);					// Create The Texture
-			OpenGLError::check("TexObject::generateTexture()[generate] ");
-			glBindTexture(GL_TEXTURE_2D, id);
-			OpenGLError::check("TexObject::generateTexture()[bind] ");
-
-			GLint texParam = GL_NEAREST;
-			glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
-			OpenGLError::check("TexObject::generateTexture()[set data] ");
-			/* If the above call to glTexImage2D has generated an error, it is likely as a result
-			* of outline="yes" being set in the IDF. If this is enabled then the texture above
-			* is generated with a width being equal to the number of points that make up the
-			* outline. However, some OpenGL implementations only support textures with a 2^n size.
-			* On the machines tested (Ubuntu 14.04, Windows 7, and RHEL6), this was not an issue,
-			* but we can't guarantee that a user wont try this on a system that doesn't support
-			* non power of 2 textures. In that case, the best thing to do would be to create a
-			* texture with a width of the next 2^n up, and adjust the texture coordinates
-			* accordingly. However, this is not a trivial change to make, and as far as we can tell
-			* no one has ever run into this issue, so it's being left for now. If this does prove
-			* problematic in the future, hopefully this note will save you some time figuring out
-			* the problem.
-			*/
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParam);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParam);
-			OpenGLError::check("TexObject::generateTexture()[parameters] ");
-		}
-
-		/**
-		* Set colour to a detector.
-		* @param data :: pointer to color array
-		* @param i :: Index of the detector in ObjCompAssembly
-		* @param c :: The colour
-		*/
-		void ObjCompAssemblyActor::setDetectorColor(unsigned char* data, size_t i, GLColor c) const
-		{
-			size_t pos = 3 * i;
-			float r, g, b, a;
-			c.get(r, g, b, a);
-			data[pos] = (unsigned char)(r * 255);
-			data[pos + 1] = (unsigned char)(g * 255);
-			data[pos + 2] = (unsigned char)(b * 255);
-		}
-
-		void ObjCompAssemblyActor::swap()
-		{
-			if (!m_pick_data)
-			{
-				m_pick_data = new  unsigned char[m_n * 3];
-			}
-			unsigned char* tmp = m_data;
-			m_data = m_pick_data;
-			m_pick_data = tmp;
-		}
-
-		const unsigned char* ObjCompAssemblyActor::getColor(int i)const
-		{
-			return &m_data[3 * i];
-		}
-
-		void ObjCompAssemblyActor::setColors()
-		{
-			setDataColors();
-		}
-
-		void ObjCompAssemblyActor::setDataColors() const
-		{
-			for (size_t i = 0; i < size_t(m_n); ++i)
-			{
-				GLColor c = m_instrActor.getColor(m_detIDs[i]);
-				setDetectorColor(m_data, i, c);
-			}
-			generateTexture(m_data, m_idData);
-		}
-
-		void ObjCompAssemblyActor::setPickColors() const
-		{
-			generateTexture(m_pick_data, m_idPick);
-		}
-
-		bool ObjCompAssemblyActor::accept(GLActorVisitor &visitor, GLActor::VisitorAcceptRule)
-		{
-			return visitor.visit(this);
-		}
-
-		bool ObjCompAssemblyActor::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule) const
-		{
-			return visitor.visit(this);
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+ObjCompAssemblyActor::ObjCompAssemblyActor(const InstrumentActor &instrActor,
+                                           Mantid::Geometry::ComponentID compID)
+    : ICompAssemblyActor(instrActor, compID), m_idData(0), m_idPick(0),
+      m_n(getObjCompAssembly()->nelements()), m_pick_data(),
+      m_texturesGenerated(false) {
+
+  ObjCompAssembly_const_sptr objAss = getObjCompAssembly();
+  mNumberOfDetectors = objAss->nelements();
+  assert(static_cast<size_t>(m_n) == mNumberOfDetectors);
+  m_data = new unsigned char[m_n * 3];
+  m_pick_data = new unsigned char[m_n * 3];
+  for (size_t i = 0; i < getNumberOfDetectors(); ++i) {
+    IDetector_const_sptr det = boost::dynamic_pointer_cast<const IDetector>(
+        objAss->getChild(static_cast<int>(i)));
+    assert(det);
+    detid_t id = det->getID();
+    m_detIDs.push_back(id);
+    size_t pickID = instrActor.pushBackDetid(id);
+    setDetectorColor(m_pick_data, i, GLActor::makePickColor(pickID));
+  }
+  Mantid::Geometry::BoundingBox boundBox;
+  objAss->getBoundingBox(boundBox);
+  minBoundBox[0] = boundBox.xMin();
+  minBoundBox[1] = boundBox.yMin();
+  minBoundBox[2] = boundBox.zMin();
+  maxBoundBox[0] = boundBox.xMax();
+  maxBoundBox[1] = boundBox.yMax();
+  maxBoundBox[2] = boundBox.zMax();
+}
+
+/**
+* Destructor which removes the actors created by this object
+*/
+ObjCompAssemblyActor::~ObjCompAssemblyActor() {
+  if (m_data) {
+    delete[] m_data;
+    delete[] m_pick_data;
+  }
+  if (m_texturesGenerated) {
+    glDeleteTextures(1, &m_idData);
+    glDeleteTextures(1, &m_idPick);
+  }
+}
+
+/**
+* This function is concrete implementation that renders the Child ObjComponents
+* and Child CompAssembly's
+*/
+void ObjCompAssemblyActor::draw(bool picking) const {
+  OpenGLError::check("ObjCompAssemblyActor::draw(0)");
+
+  if (!m_texturesGenerated) {
+    setDataColors();
+    setPickColors();
+    m_texturesGenerated = true;
+  }
+
+  ObjCompAssembly_const_sptr objAss = getObjCompAssembly();
+  glPushMatrix();
+
+  unsigned int texID = picking ? m_idPick : m_idData;
+  // Because texture colours are combined with the geometry colour
+  // make sure the current colour is white
+  glColor3f(1.0f, 1.0f, 1.0f);
+  glEnable(GL_TEXTURE_2D);
+  glBindTexture(GL_TEXTURE_2D, texID);
+  objAss->draw();
+  glBindTexture(GL_TEXTURE_2D, 0);
+  OpenGLError::check("ObjCompAssemblyActor::draw()");
+
+  glPopMatrix();
+}
+
+void ObjCompAssemblyActor::generateTexture(unsigned char *data,
+                                           unsigned int &id) const {
+  if (id > 0) {
+    glDeleteTextures(1, &id);
+    OpenGLError::check("TexObject::generateTexture()[delete texture] ");
+  }
+  bool vertical = true; // depends on the tex coordinates of the shape object
+
+  int width = m_n;
+  int height = 1;
+  if (vertical) {
+    width = 1;
+    height = m_n;
+  }
+
+  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+  glGenTextures(1, &id); // Create The Texture
+  OpenGLError::check("TexObject::generateTexture()[generate] ");
+  glBindTexture(GL_TEXTURE_2D, id);
+  OpenGLError::check("TexObject::generateTexture()[bind] ");
+
+  GLint texParam = GL_NEAREST;
+  glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE,
+               data);
+  OpenGLError::check("TexObject::generateTexture()[set data] ");
+  /* If the above call to glTexImage2D has generated an error, it is likely as a
+  * result
+  * of outline="yes" being set in the IDF. If this is enabled then the texture
+  * above
+  * is generated with a width being equal to the number of points that make up
+  * the
+  * outline. However, some OpenGL implementations only support textures with a
+  * 2^n size.
+  * On the machines tested (Ubuntu 14.04, Windows 7, and RHEL6), this was not an
+  * issue,
+  * but we can't guarantee that a user wont try this on a system that doesn't
+  * support
+  * non power of 2 textures. In that case, the best thing to do would be to
+  * create a
+  * texture with a width of the next 2^n up, and adjust the texture coordinates
+  * accordingly. However, this is not a trivial change to make, and as far as we
+  * can tell
+  * no one has ever run into this issue, so it's being left for now. If this
+  * does prove
+  * problematic in the future, hopefully this note will save you some time
+  * figuring out
+  * the problem.
+  */
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParam);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParam);
+  OpenGLError::check("TexObject::generateTexture()[parameters] ");
+}
+
+/**
+* Set colour to a detector.
+* @param data :: pointer to color array
+* @param i :: Index of the detector in ObjCompAssembly
+* @param c :: The colour
+*/
+void ObjCompAssemblyActor::setDetectorColor(unsigned char *data, size_t i,
+                                            GLColor c) const {
+  size_t pos = 3 * i;
+  float r, g, b, a;
+  c.get(r, g, b, a);
+  data[pos] = (unsigned char)(r * 255);
+  data[pos + 1] = (unsigned char)(g * 255);
+  data[pos + 2] = (unsigned char)(b * 255);
+}
+
+void ObjCompAssemblyActor::swap() {
+  if (!m_pick_data) {
+    m_pick_data = new unsigned char[m_n * 3];
+  }
+  unsigned char *tmp = m_data;
+  m_data = m_pick_data;
+  m_pick_data = tmp;
+}
+
+const unsigned char *ObjCompAssemblyActor::getColor(int i) const {
+  return &m_data[3 * i];
+}
+
+void ObjCompAssemblyActor::setColors() { setDataColors(); }
+
+void ObjCompAssemblyActor::setDataColors() const {
+  for (size_t i = 0; i < size_t(m_n); ++i) {
+    GLColor c = m_instrActor.getColor(m_detIDs[i]);
+    setDetectorColor(m_data, i, c);
+  }
+  generateTexture(m_data, m_idData);
+}
+
+void ObjCompAssemblyActor::setPickColors() const {
+  generateTexture(m_pick_data, m_idPick);
+}
+
+bool ObjCompAssemblyActor::accept(GLActorVisitor &visitor,
+                                  GLActor::VisitorAcceptRule) {
+  return visitor.visit(this);
+}
+
+bool ObjCompAssemblyActor::accept(GLActorConstVisitor &visitor,
+                                  GLActor::VisitorAcceptRule) const {
+  return visitor.visit(this);
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ObjComponentActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ObjComponentActor.cpp
index 5e7fcf75db68a4c1403304efa0ca0a7322057509..6afdc7779d7799b4fc580ab3d7ae43eaa32d4105 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ObjComponentActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ObjComponentActor.cpp
@@ -12,84 +12,69 @@
 using namespace Mantid;
 using namespace Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		ObjComponentActor::ObjComponentActor(
-			const InstrumentActor &instrActor,
-			Mantid::Geometry::ComponentID compID)
-			: ComponentActor(instrActor, compID) {
-			// set the displayed colour
-			setColors();
-			// register the component with InstrumentActor and set the pick colour
-			IDetector_const_sptr det = getDetector();
-			if (det)
-			{
-				size_t pickID = instrActor.pushBackDetid(det->getID());
-				m_pickColor = makePickColor(pickID);
-			}
-			else
-			{
-				instrActor.pushBackNonDetid(this, compID);
-			}
-		}
+ObjComponentActor::ObjComponentActor(const InstrumentActor &instrActor,
+                                     Mantid::Geometry::ComponentID compID)
+    : ComponentActor(instrActor, compID) {
+  // set the displayed colour
+  setColors();
+  // register the component with InstrumentActor and set the pick colour
+  IDetector_const_sptr det = getDetector();
+  if (det) {
+    size_t pickID = instrActor.pushBackDetid(det->getID());
+    m_pickColor = makePickColor(pickID);
+  } else {
+    instrActor.pushBackNonDetid(this, compID);
+  }
+}
 
-		ObjComponentActor::~ObjComponentActor()
-		{
-		}
+ObjComponentActor::~ObjComponentActor() {}
 
-		//-------------------------------------------------------------------------------------------------
-		/**
-		* Concrete implementation of rendering ObjComponent.
-		*/
-		void ObjComponentActor::draw(bool picking)const
-		{
-			OpenGLError::check("ObjComponentActor::draw(0)");
-			glPushMatrix();
-			if (picking)
-			{
-				m_pickColor.paint();
-			}
-			else
-			{
-				m_dataColor.paint();
-			}
-			getObjComponent()->draw();
-			glPopMatrix();
-			OpenGLError::check("ObjComponentActor::draw()");
-		}
+//-------------------------------------------------------------------------------------------------
+/**
+* Concrete implementation of rendering ObjComponent.
+*/
+void ObjComponentActor::draw(bool picking) const {
+  OpenGLError::check("ObjComponentActor::draw(0)");
+  glPushMatrix();
+  if (picking) {
+    m_pickColor.paint();
+  } else {
+    m_dataColor.paint();
+  }
+  getObjComponent()->draw();
+  glPopMatrix();
+  OpenGLError::check("ObjComponentActor::draw()");
+}
 
-		/**
-		* Set displayed component colour. If it's a detector the colour maps to the integrated counts in it.
-		*/
-		void ObjComponentActor::setColors()
-		{
-			IDetector_const_sptr det = getDetector();
-			if (det)
-			{
-				setColor(m_instrActor.getColor(det->getID()));
-			}
-			else
-			{
-				setColor(defaultDetectorColor());
-			}
-		}
+/**
+* Set displayed component colour. If it's a detector the colour maps to the
+* integrated counts in it.
+*/
+void ObjComponentActor::setColors() {
+  IDetector_const_sptr det = getDetector();
+  if (det) {
+    setColor(m_instrActor.getColor(det->getID()));
+  } else {
+    setColor(defaultDetectorColor());
+  }
+}
 
-		//-------------------------------------------------------------------------------------------------
-		/**
-		* Return the bounding box
-		* @param minBound :: min point of the bounding box
-		* @param maxBound :: max point of the bounding box
-		*/
-		void ObjComponentActor::getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const
-		{
-			Mantid::Geometry::BoundingBox boundBox;
-			getComponent()->getBoundingBox(boundBox);
-			minBound = boundBox.minPoint();
-			maxBound = boundBox.maxPoint();
-		}
+//-------------------------------------------------------------------------------------------------
+/**
+* Return the bounding box
+* @param minBound :: min point of the bounding box
+* @param maxBound :: max point of the bounding box
+*/
+void ObjComponentActor::getBoundingBox(Mantid::Kernel::V3D &minBound,
+                                       Mantid::Kernel::V3D &maxBound) const {
+  Mantid::Geometry::BoundingBox boundBox;
+  getComponent()->getBoundingBox(boundBox);
+  minBound = boundBox.minPoint();
+  maxBound = boundBox.maxPoint();
+}
 
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/OneCurvePlot.cpp b/MantidQt/MantidWidgets/src/InstrumentView/OneCurvePlot.cpp
index e3634766adce43945dc782ccc2826de6d56fc620..b72f6ba5ad6bfb83064041dee50e14d01105a1a9 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/OneCurvePlot.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/OneCurvePlot.cpp
@@ -18,520 +18,463 @@
 
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		OneCurvePlot::OneCurvePlot(QWidget* parent) :
-			QwtPlot(parent), m_curve(NULL), m_xUnits("")
-		{
-			QFont font = parent->font();
-			setAxisFont(QwtPlot::xBottom, font);
-			setAxisFont(QwtPlot::yLeft, font);
-			QwtText dummyText;
-			dummyText.setFont(font);
-			setAxisTitle(xBottom, dummyText);
-			canvas()->setCursor(Qt::ArrowCursor);
-			setContextMenuPolicy(Qt::DefaultContextMenu);
-			m_zoomer = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
-				QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, canvas());
-			m_zoomer->setRubberBandPen(QPen(Qt::black));
-			QList<QColor> colors;
-			m_colors << Qt::red << Qt::green << Qt::blue << Qt::cyan << Qt::magenta << Qt::yellow << Qt::gray;
-			m_colors << Qt::darkRed << Qt::darkGreen << Qt::darkBlue << Qt::darkCyan << Qt::darkMagenta << Qt::darkYellow << Qt::darkGray;
-			m_colorIndex = 0;
-			m_x0 = 0;
-			m_y0 = 0;
-		}
-
-		/**
-		* Destructor.
-		*/
-		OneCurvePlot::~OneCurvePlot()
-		{
-			clearAll();
-		}
-
-		/**
-		* Set the scale of the horizontal axis
-		* @param from :: Minimum value
-		* @param to :: Maximum value
-		*/
-		void OneCurvePlot::setXScale(double from, double to)
-		{
-			QFontMetrics fm(axisFont(QwtPlot::xBottom));
-			int n = from != 0.0 ? abs(static_cast<int>(floor(log10(fabs(from))))) : 0;
-			int n1 = to != 0.0 ? abs(static_cast<int>(floor(log10(fabs(to))))) : 0;
-			if (n1 > n) n = n1;
-			n += 4;
-			// approxiamte width of a tick label in pixels
-			int labelWidth = n * fm.width("0");
-			// calculate number of major ticks
-			int nMajorTicks = this->width() / labelWidth;
-			if (nMajorTicks > 6) nMajorTicks = 6;
-			// try creating a scale
-			const QwtScaleDiv div = axisScaleEngine(QwtPlot::xBottom)->divideScale(from, to, nMajorTicks, nMajorTicks);
-			// Major ticks are placed at round numbers so the first or last tick could be missing making
-			// scale look ugly. Trying to fix it if possible
-			bool rescaled = false;
-			// get actual tick positions
-			const QwtValueList& ticks = div.ticks(QwtScaleDiv::MajorTick);
-			if (!ticks.empty() && ticks.size() < nMajorTicks)
-			{
-				// how much first tick is shifted from the lower bound
-				double firstShift = ticks.front() - div.lBound();
-				// how much last tick is shifted from the upper bound
-				double lastShift = div.hBound() - ticks.back();
-				// range of the scale
-				double range = fabs(div.hBound() - div.lBound());
-				// we say that 1st tick is missing if first tick is father away from its end of the scale
-				// than the last tick is from its end
-				bool isFirstMissing = fabs(firstShift) > fabs(lastShift);
-				// if first tick is missing
-				if (isFirstMissing)
-				{
-					// distance between nearest major ticks
-					double tickSize = 0;
-					if (ticks.size() == 1)
-					{
-						// guess the tick size in case of only one visible
-						double tickLog = log10(firstShift);
-						tickLog = tickLog > 0 ? ceil(tickLog) : floor(tickLog);
-						tickSize = pow(10., tickLog);
-					}
-					else if (ticks.size() > 1)
-					{
-						// take the difference between the two first ticks
-						tickSize = ticks[1] - ticks[0];
-					}
-					// claculate how much lower bound must be moved to make the missing tick visible
-					double shift = (ticks.front() - tickSize) - from;
-					// if the shift is not very big rescale the axis
-					if (fabs(shift / range) < 0.1)
-					{
-						from += shift;
-						const QwtScaleDiv updatedDiv = axisScaleEngine(QwtPlot::xBottom)->divideScale(from, to, nMajorTicks, nMajorTicks);
-						setAxisScaleDiv(xBottom, updatedDiv);
-						rescaled = true;
-					}
-				}
-				else // last tick is missing
-				{
-					// distance between nearest major ticks
-					double tickSize = 0;
-					if (ticks.size() == 1)
-					{
-						// guess the tick size in case of only one visible
-						double tickLog = log10(lastShift);
-						tickLog = tickLog > 0 ? ceil(tickLog) : floor(tickLog);
-						tickSize = pow(10., tickLog);
-					}
-					else if (ticks.size() > 1)
-					{
-						// take the difference between the two first ticks
-						tickSize = ticks[1] - ticks[0];
-					}
-					// claculate how much upper bound must be moved to make the missing tick visible
-					double shift = (ticks.back() + tickSize) - to;
-					// if the shift is not very big rescale the axis
-					if (fabs(shift / range) < 0.1)
-					{
-						to += shift;
-						const QwtScaleDiv updatedDiv = axisScaleEngine(QwtPlot::xBottom)->divideScale(from, to, nMajorTicks, nMajorTicks);
-						setAxisScaleDiv(xBottom, updatedDiv);
-						rescaled = true;
-					}
-				}
-			}
-
-			if (!rescaled)
-			{
-				setAxisScaleDiv(xBottom, div);
-			}
-			m_zoomer->setZoomBase();
-		}
-
-		/**
-		* Set the scale of the vertical axis
-		* @param from :: Minimum value
-		* @param to :: Maximum value
-		*/
-		void OneCurvePlot::setYScale(double from, double to)
-		{
-			if (isYLogScale())
-			{
-				if (from == 0 && to == 0)
-				{
-					from = 1;
-					to = 10;
-				}
-				else
-				{
-					double yPositiveMin = to;
-					QMap<QString, QwtPlotCurve*>::const_iterator cv = m_stored.begin();
-					QwtPlotCurve* curve = NULL;
-					do
-					{
-						if (cv != m_stored.end())
-						{
-							curve = cv.value();
-							++cv;
-						}
-						else if (curve == m_curve)
-						{
-							curve = NULL;
-							break;
-						}
-						else
-						{
-							curve = m_curve;
-						}
-						if (!curve) break;
-						int n = curve->dataSize();
-						for (int i = 0; i < n; ++i)
-						{
-							double y = curve->y(i);
-							if (y > 0 && y < yPositiveMin)
-							{
-								yPositiveMin = y;
-							}
-						}
-					} while (curve);
-					from = yPositiveMin;
-				}
-			}
-			setAxisScale(QwtPlot::yLeft, from, to);
-			m_zoomer->setZoomBase();
-		}
-
-		/**
-		* Set the data for the curve to display
-		* @param x :: A pointer to x values
-		* @param y :: A pointer to y values
-		* @param dataSize :: The size of the data
-		* @param xUnits :: Units for the data
-		*/
-		void OneCurvePlot::setData(const double* x, const double* y, int dataSize, const std::string& xUnits)
-		{
-			m_xUnits = xUnits;
-			if (!m_curve)
-			{
-				m_curve = new QwtPlotCurve();
-				m_curve->attach(this);
-			}
-
-			m_curve->setData(x, y, dataSize);
-			setXScale(x[0], x[dataSize - 1]);
-			double from = y[0];
-			double to = from;
-			for (int i = 0; i < dataSize; ++i)
-			{
-				const double& yy = y[i];
-				if (yy < from) from = yy;
-				if (yy > to) to = yy;
-			}
-			setYScale(from, to);
-			this->setAxisTitle(xBottom, QString::fromStdString(m_xUnits));
-		}
-
-		/**
-		* Set a label which will identify the curve when it is stored.
-		*/
-		void OneCurvePlot::setLabel(const QString& label)
-		{
-			m_label = label;
-		}
-
-		/**
-		* Remove the curve. Rescale the axes if there are stored curves.
-		*/
-		void OneCurvePlot::clearCurve()
-		{
-			// remove the curve
-			if (m_curve)
-			{
-				m_curve->attach(0);
-				m_curve = NULL;
-			}
-			clearPeakLabels();
-			// if there are stored curves rescale axes to make them fully visible
-			if (hasStored())
-			{
-				QMap<QString, QwtPlotCurve*>::const_iterator curve = m_stored.begin();
-				QwtDoubleRect br = (**curve).boundingRect();
-				double xmin = br.left();
-				double xmax = br.right();
-				double ymin = br.top();
-				double ymax = br.bottom();
-				++curve;
-				for (; curve != m_stored.end(); ++curve)
-				{
-					QwtDoubleRect br = (**curve).boundingRect();
-					if (br.left() < xmin) xmin = br.left();
-					if (br.right() > xmax) xmax = br.right();
-					if (br.top() < ymin) ymin = br.top();
-					if (br.bottom() > ymax) ymax = br.bottom();
-				}
-				setXScale(xmin, xmax);
-				setYScale(ymin, ymax);
-			}
-		}
-
-		void OneCurvePlot::resizeEvent(QResizeEvent *e)
-		{
-			QwtPlot::resizeEvent(e);
-			recalcAxisDivs();
-		}
-
-		/**
-		* Recalculate axis divisions to make sure that tick labels don't overlap
-		*/
-		void OneCurvePlot::recalcAxisDivs()
-		{
-			recalcXAxisDivs();
-			recalcYAxisDivs();
-		}
-
-		/**
-		* Recalculate x-axis divisions to make sure that tick labels don't overlap
-		*/
-		void OneCurvePlot::recalcXAxisDivs()
-		{
-			const QwtScaleDiv *div0 = axisScaleDiv(QwtPlot::xBottom);
-			double from = div0->lBound();
-			double to = div0->hBound();
-			setXScale(from, to);
-		}
-
-		/**
-		* Recalculate y-axis divisions to make sure that tick labels don't overlap
-		*/
-		void OneCurvePlot::recalcYAxisDivs()
-		{
-			const QwtScaleDiv *div0 = axisScaleDiv(QwtPlot::yLeft);
-			double from = div0->lBound();
-			double to = div0->hBound();
-			setYScale(from, to);
-		}
-
-		void OneCurvePlot::contextMenuEvent(QContextMenuEvent *e)
-		{
-			// context menu will be handled with mouse events
-			e->accept();
-		}
-
-		void OneCurvePlot::mousePressEvent(QMouseEvent* e)
-		{
-			if (e->buttons() & Qt::RightButton)
-			{
-				if (m_zoomer->zoomRectIndex() == 0)
-				{
-					e->accept();
-					// plot owner will display and process context menu
-					emit showContextMenu();
-				}
-				return;
-			}
-			if (e->buttons() & Qt::LeftButton)
-			{
-				e->accept();
-				m_x0 = e->x();
-				m_y0 = e->y();
-			}
-		}
-
-		void OneCurvePlot::mouseReleaseEvent(QMouseEvent* e)
-		{
-			if (e->button() == Qt::LeftButton)
-			{
-				if (m_x0 == e->x() && m_y0 == e->y())
-				{// there were no dragging
-					emit clickedAt(invTransform(xBottom, e->x() - canvas()->x()), invTransform(yLeft, e->y() - canvas()->y()));
-				}
-			}
-		}
-
-		void OneCurvePlot::setYAxisLabelRotation(double degrees)
-		{
-			axisScaleDraw(yLeft)->setLabelRotation(degrees);
-		}
-
-		/**
-		* Set the log scale on the y axis
-		*/
-		void OneCurvePlot::setYLogScale()
-		{
-			const QwtScaleDiv *div = axisScaleDiv(QwtPlot::yLeft);
-			double from = div->lBound();
-			double to = div->hBound();
-			QwtLog10ScaleEngine* logEngine = new QwtLog10ScaleEngine();
-			setAxisScaleEngine(yLeft, logEngine);
-			setYScale(from, to);
-			recalcYAxisDivs();
-			replot();
-		}
-
-		/**
-		* Set the linear scale on the y axis
-		*/
-		void OneCurvePlot::setYLinearScale()
-		{
-			QwtLinearScaleEngine* engine = new QwtLinearScaleEngine();
-			setAxisScaleEngine(yLeft, engine);
-			replot();
-		}
-
-		/**
-		* Add new peak label
-		* @param marker :: A pointer to a PeakLabel, becomes owned by OneCurvePlot
-		*/
-		void OneCurvePlot::addPeakLabel(const PeakMarker2D* marker)
-		{
-			PeakLabel* label = new PeakLabel(marker, this);
-			label->attach(this);
-			m_peakLabels.append(label);
-		}
-
-		/**
-		* Removes all peak labels.
-		*/
-		void OneCurvePlot::clearPeakLabels()
-		{
-			foreach(PeakLabel* label, m_peakLabels)
-			{
-				label->detach();
-				delete label;
-			}
-			m_peakLabels.clear();
-		}
-
-		/**
-		* Returns true if the current curve isn't NULL
-		*/
-		bool OneCurvePlot::hasCurve()const
-		{
-			return m_curve != NULL;
-		}
-
-		/**
-		* Store current curve.
-		*/
-		void OneCurvePlot::store()
-		{
-			if (m_curve)
-			{
-				removeCurve(m_label);
-				m_stored.insert(m_label, m_curve);
-				m_curve->setPen(QPen(m_colors[m_colorIndex]));
-				++m_colorIndex;
-				m_colorIndex %= m_colors.size();
-				m_curve = NULL;
-				m_label = "";
-			}
-		}
-
-		/**
-		* Returns true if there are some stored curves.
-		*/
-		bool OneCurvePlot::hasStored()const
-		{
-			return !m_stored.isEmpty();
-		}
-
-		QStringList OneCurvePlot::getLabels()const
-		{
-			QStringList out;
-			QMap<QString, QwtPlotCurve*>::const_iterator it = m_stored.begin();
-			for (; it != m_stored.end(); ++it)
-			{
-				out << it.key();
-			}
-			return out;
-		}
-
-		/**
-		* Return the colour of a stored curve.
-		* @param label :: The label of that curve.
-		*/
-		QColor OneCurvePlot::getCurveColor(const QString& label)const
-		{
-			if (m_stored.contains(label))
-			{
-				return m_stored[label]->pen().color();
-			}
-			return Qt::black;
-		}
-
-		/**
-		* Remove a stored curve.
-		* @param label :: The label of a curve to remove.
-		*/
-		void OneCurvePlot::removeCurve(const QString& label)
-		{
-			QMap<QString, QwtPlotCurve*>::iterator it = m_stored.find(label);
-			if (it != m_stored.end())
-			{
-				it.value()->detach();
-				delete it.value();
-				m_stored.erase(it);
-			}
-		}
-
-		/**
-		* Does the y axis have the log scale?
-		*/
-		bool OneCurvePlot::isYLogScale()const
-		{
-			const QwtScaleEngine *engine = axisScaleEngine(yLeft);
-			return dynamic_cast<const QwtLog10ScaleEngine*>(engine) != NULL;
-		}
-
-		/**
-		* Remove all displayable objects from the plot.
-		*/
-		void OneCurvePlot::clearAll()
-		{
-			QMap<QString, QwtPlotCurve*>::const_iterator it = m_stored.begin();
-			for (; it != m_stored.end(); ++it)
-			{
-				it.value()->detach();
-				delete it.value();
-			}
-			m_stored.clear();
-			clearPeakLabels();
-			clearCurve();
-			m_colorIndex = 0;
-		}
-
-		/* ---------------------------- PeakLabel --------------------------- */
-
-		/**
-		* Draw PeakLabel on a plot
-		*/
-		void PeakLabel::draw(QPainter *painter,
-			const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-			const QRect &canvasRect) const
-		{
-			(void)yMap;
-			double peakX;
-			if (m_plot->getXUnits().empty()) return;
-			if (m_plot->getXUnits() == "dSpacing")
-			{
-				peakX = m_marker->getPeak().getDSpacing();
-			}
-			else if (m_plot->getXUnits() == "Wavelength")
-			{
-				peakX = m_marker->getPeak().getWavelength();
-			}
-			else
-			{
-				peakX = m_marker->getPeak().getTOF();
-			}
-			int x = xMap.transform(peakX);
-			int y = static_cast<int>(canvasRect.top() + m_marker->getLabelRect().height());
-			painter->drawText(x, y, m_marker->getLabel());
-			//std::cerr << x << ' ' << y << ' ' << m_marker->getLabel().toStdString() << std::endl;
-		}
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+namespace MantidQt {
+namespace MantidWidgets {
+
+OneCurvePlot::OneCurvePlot(QWidget *parent)
+    : QwtPlot(parent), m_curve(NULL), m_xUnits("") {
+  QFont font = parent->font();
+  setAxisFont(QwtPlot::xBottom, font);
+  setAxisFont(QwtPlot::yLeft, font);
+  QwtText dummyText;
+  dummyText.setFont(font);
+  setAxisTitle(xBottom, dummyText);
+  canvas()->setCursor(Qt::ArrowCursor);
+  setContextMenuPolicy(Qt::DefaultContextMenu);
+  m_zoomer =
+      new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft,
+                        QwtPicker::DragSelection | QwtPicker::CornerToCorner,
+                        QwtPicker::AlwaysOff, canvas());
+  m_zoomer->setRubberBandPen(QPen(Qt::black));
+  QList<QColor> colors;
+  m_colors << Qt::red << Qt::green << Qt::blue << Qt::cyan << Qt::magenta
+           << Qt::yellow << Qt::gray;
+  m_colors << Qt::darkRed << Qt::darkGreen << Qt::darkBlue << Qt::darkCyan
+           << Qt::darkMagenta << Qt::darkYellow << Qt::darkGray;
+  m_colorIndex = 0;
+  m_x0 = 0;
+  m_y0 = 0;
+}
+
+/**
+* Destructor.
+*/
+OneCurvePlot::~OneCurvePlot() { clearAll(); }
+
+/**
+* Set the scale of the horizontal axis
+* @param from :: Minimum value
+* @param to :: Maximum value
+*/
+void OneCurvePlot::setXScale(double from, double to) {
+  QFontMetrics fm(axisFont(QwtPlot::xBottom));
+  int n = from != 0.0 ? abs(static_cast<int>(floor(log10(fabs(from))))) : 0;
+  int n1 = to != 0.0 ? abs(static_cast<int>(floor(log10(fabs(to))))) : 0;
+  if (n1 > n)
+    n = n1;
+  n += 4;
+  // approxiamte width of a tick label in pixels
+  int labelWidth = n * fm.width("0");
+  // calculate number of major ticks
+  int nMajorTicks = this->width() / labelWidth;
+  if (nMajorTicks > 6)
+    nMajorTicks = 6;
+  // try creating a scale
+  const QwtScaleDiv div = axisScaleEngine(QwtPlot::xBottom)
+                              ->divideScale(from, to, nMajorTicks, nMajorTicks);
+  // Major ticks are placed at round numbers so the first or last tick could be
+  // missing making
+  // scale look ugly. Trying to fix it if possible
+  bool rescaled = false;
+  // get actual tick positions
+  const QwtValueList &ticks = div.ticks(QwtScaleDiv::MajorTick);
+  if (!ticks.empty() && ticks.size() < nMajorTicks) {
+    // how much first tick is shifted from the lower bound
+    double firstShift = ticks.front() - div.lBound();
+    // how much last tick is shifted from the upper bound
+    double lastShift = div.hBound() - ticks.back();
+    // range of the scale
+    double range = fabs(div.hBound() - div.lBound());
+    // we say that 1st tick is missing if first tick is father away from its end
+    // of the scale
+    // than the last tick is from its end
+    bool isFirstMissing = fabs(firstShift) > fabs(lastShift);
+    // if first tick is missing
+    if (isFirstMissing) {
+      // distance between nearest major ticks
+      double tickSize = 0;
+      if (ticks.size() == 1) {
+        // guess the tick size in case of only one visible
+        double tickLog = log10(firstShift);
+        tickLog = tickLog > 0 ? ceil(tickLog) : floor(tickLog);
+        tickSize = pow(10., tickLog);
+      } else if (ticks.size() > 1) {
+        // take the difference between the two first ticks
+        tickSize = ticks[1] - ticks[0];
+      }
+      // claculate how much lower bound must be moved to make the missing tick
+      // visible
+      double shift = (ticks.front() - tickSize) - from;
+      // if the shift is not very big rescale the axis
+      if (fabs(shift / range) < 0.1) {
+        from += shift;
+        const QwtScaleDiv updatedDiv =
+            axisScaleEngine(QwtPlot::xBottom)
+                ->divideScale(from, to, nMajorTicks, nMajorTicks);
+        setAxisScaleDiv(xBottom, updatedDiv);
+        rescaled = true;
+      }
+    } else // last tick is missing
+    {
+      // distance between nearest major ticks
+      double tickSize = 0;
+      if (ticks.size() == 1) {
+        // guess the tick size in case of only one visible
+        double tickLog = log10(lastShift);
+        tickLog = tickLog > 0 ? ceil(tickLog) : floor(tickLog);
+        tickSize = pow(10., tickLog);
+      } else if (ticks.size() > 1) {
+        // take the difference between the two first ticks
+        tickSize = ticks[1] - ticks[0];
+      }
+      // claculate how much upper bound must be moved to make the missing tick
+      // visible
+      double shift = (ticks.back() + tickSize) - to;
+      // if the shift is not very big rescale the axis
+      if (fabs(shift / range) < 0.1) {
+        to += shift;
+        const QwtScaleDiv updatedDiv =
+            axisScaleEngine(QwtPlot::xBottom)
+                ->divideScale(from, to, nMajorTicks, nMajorTicks);
+        setAxisScaleDiv(xBottom, updatedDiv);
+        rescaled = true;
+      }
+    }
+  }
+
+  if (!rescaled) {
+    setAxisScaleDiv(xBottom, div);
+  }
+  m_zoomer->setZoomBase();
+}
+
+/**
+* Set the scale of the vertical axis
+* @param from :: Minimum value
+* @param to :: Maximum value
+*/
+void OneCurvePlot::setYScale(double from, double to) {
+  if (isYLogScale()) {
+    if (from == 0 && to == 0) {
+      from = 1;
+      to = 10;
+    } else {
+      double yPositiveMin = to;
+      QMap<QString, QwtPlotCurve *>::const_iterator cv = m_stored.begin();
+      QwtPlotCurve *curve = NULL;
+      do {
+        if (cv != m_stored.end()) {
+          curve = cv.value();
+          ++cv;
+        } else if (curve == m_curve) {
+          curve = NULL;
+          break;
+        } else {
+          curve = m_curve;
+        }
+        if (!curve)
+          break;
+        int n = curve->dataSize();
+        for (int i = 0; i < n; ++i) {
+          double y = curve->y(i);
+          if (y > 0 && y < yPositiveMin) {
+            yPositiveMin = y;
+          }
+        }
+      } while (curve);
+      from = yPositiveMin;
+    }
+  }
+  setAxisScale(QwtPlot::yLeft, from, to);
+  m_zoomer->setZoomBase();
+}
+
+/**
+* Set the data for the curve to display
+* @param x :: A pointer to x values
+* @param y :: A pointer to y values
+* @param dataSize :: The size of the data
+* @param xUnits :: Units for the data
+*/
+void OneCurvePlot::setData(const double *x, const double *y, int dataSize,
+                           const std::string &xUnits) {
+  m_xUnits = xUnits;
+  if (!m_curve) {
+    m_curve = new QwtPlotCurve();
+    m_curve->attach(this);
+  }
+
+  m_curve->setData(x, y, dataSize);
+  setXScale(x[0], x[dataSize - 1]);
+  double from = y[0];
+  double to = from;
+  for (int i = 0; i < dataSize; ++i) {
+    const double &yy = y[i];
+    if (yy < from)
+      from = yy;
+    if (yy > to)
+      to = yy;
+  }
+  setYScale(from, to);
+  this->setAxisTitle(xBottom, QString::fromStdString(m_xUnits));
+}
+
+/**
+* Set a label which will identify the curve when it is stored.
+*/
+void OneCurvePlot::setLabel(const QString &label) { m_label = label; }
+
+/**
+* Remove the curve. Rescale the axes if there are stored curves.
+*/
+void OneCurvePlot::clearCurve() {
+  // remove the curve
+  if (m_curve) {
+    m_curve->attach(0);
+    m_curve = NULL;
+  }
+  clearPeakLabels();
+  // if there are stored curves rescale axes to make them fully visible
+  if (hasStored()) {
+    QMap<QString, QwtPlotCurve *>::const_iterator curve = m_stored.begin();
+    QwtDoubleRect br = (**curve).boundingRect();
+    double xmin = br.left();
+    double xmax = br.right();
+    double ymin = br.top();
+    double ymax = br.bottom();
+    ++curve;
+    for (; curve != m_stored.end(); ++curve) {
+      QwtDoubleRect br = (**curve).boundingRect();
+      if (br.left() < xmin)
+        xmin = br.left();
+      if (br.right() > xmax)
+        xmax = br.right();
+      if (br.top() < ymin)
+        ymin = br.top();
+      if (br.bottom() > ymax)
+        ymax = br.bottom();
+    }
+    setXScale(xmin, xmax);
+    setYScale(ymin, ymax);
+  }
+}
+
+void OneCurvePlot::resizeEvent(QResizeEvent *e) {
+  QwtPlot::resizeEvent(e);
+  recalcAxisDivs();
+}
+
+/**
+* Recalculate axis divisions to make sure that tick labels don't overlap
+*/
+void OneCurvePlot::recalcAxisDivs() {
+  recalcXAxisDivs();
+  recalcYAxisDivs();
+}
+
+/**
+* Recalculate x-axis divisions to make sure that tick labels don't overlap
+*/
+void OneCurvePlot::recalcXAxisDivs() {
+  const QwtScaleDiv *div0 = axisScaleDiv(QwtPlot::xBottom);
+  double from = div0->lBound();
+  double to = div0->hBound();
+  setXScale(from, to);
+}
+
+/**
+* Recalculate y-axis divisions to make sure that tick labels don't overlap
+*/
+void OneCurvePlot::recalcYAxisDivs() {
+  const QwtScaleDiv *div0 = axisScaleDiv(QwtPlot::yLeft);
+  double from = div0->lBound();
+  double to = div0->hBound();
+  setYScale(from, to);
+}
+
+void OneCurvePlot::contextMenuEvent(QContextMenuEvent *e) {
+  // context menu will be handled with mouse events
+  e->accept();
+}
+
+void OneCurvePlot::mousePressEvent(QMouseEvent *e) {
+  if (e->buttons() & Qt::RightButton) {
+    if (m_zoomer->zoomRectIndex() == 0) {
+      e->accept();
+      // plot owner will display and process context menu
+      emit showContextMenu();
+    }
+    return;
+  }
+  if (e->buttons() & Qt::LeftButton) {
+    e->accept();
+    m_x0 = e->x();
+    m_y0 = e->y();
+  }
+}
+
+void OneCurvePlot::mouseReleaseEvent(QMouseEvent *e) {
+  if (e->button() == Qt::LeftButton) {
+    if (m_x0 == e->x() && m_y0 == e->y()) { // there were no dragging
+      emit clickedAt(invTransform(xBottom, e->x() - canvas()->x()),
+                     invTransform(yLeft, e->y() - canvas()->y()));
+    }
+  }
+}
+
+void OneCurvePlot::setYAxisLabelRotation(double degrees) {
+  axisScaleDraw(yLeft)->setLabelRotation(degrees);
+}
+
+/**
+* Set the log scale on the y axis
+*/
+void OneCurvePlot::setYLogScale() {
+  const QwtScaleDiv *div = axisScaleDiv(QwtPlot::yLeft);
+  double from = div->lBound();
+  double to = div->hBound();
+  QwtLog10ScaleEngine *logEngine = new QwtLog10ScaleEngine();
+  setAxisScaleEngine(yLeft, logEngine);
+  setYScale(from, to);
+  recalcYAxisDivs();
+  replot();
+}
+
+/**
+* Set the linear scale on the y axis
+*/
+void OneCurvePlot::setYLinearScale() {
+  QwtLinearScaleEngine *engine = new QwtLinearScaleEngine();
+  setAxisScaleEngine(yLeft, engine);
+  replot();
+}
+
+/**
+* Add new peak label
+* @param marker :: A pointer to a PeakLabel, becomes owned by OneCurvePlot
+*/
+void OneCurvePlot::addPeakLabel(const PeakMarker2D *marker) {
+  PeakLabel *label = new PeakLabel(marker, this);
+  label->attach(this);
+  m_peakLabels.append(label);
+}
+
+/**
+* Removes all peak labels.
+*/
+void OneCurvePlot::clearPeakLabels() {
+  foreach (PeakLabel *label, m_peakLabels) {
+    label->detach();
+    delete label;
+  }
+  m_peakLabels.clear();
+}
+
+/**
+* Returns true if the current curve isn't NULL
+*/
+bool OneCurvePlot::hasCurve() const { return m_curve != NULL; }
+
+/**
+* Store current curve.
+*/
+void OneCurvePlot::store() {
+  if (m_curve) {
+    removeCurve(m_label);
+    m_stored.insert(m_label, m_curve);
+    m_curve->setPen(QPen(m_colors[m_colorIndex]));
+    ++m_colorIndex;
+    m_colorIndex %= m_colors.size();
+    m_curve = NULL;
+    m_label = "";
+  }
+}
+
+/**
+* Returns true if there are some stored curves.
+*/
+bool OneCurvePlot::hasStored() const { return !m_stored.isEmpty(); }
+
+QStringList OneCurvePlot::getLabels() const {
+  QStringList out;
+  QMap<QString, QwtPlotCurve *>::const_iterator it = m_stored.begin();
+  for (; it != m_stored.end(); ++it) {
+    out << it.key();
+  }
+  return out;
+}
+
+/**
+* Return the colour of a stored curve.
+* @param label :: The label of that curve.
+*/
+QColor OneCurvePlot::getCurveColor(const QString &label) const {
+  if (m_stored.contains(label)) {
+    return m_stored[label]->pen().color();
+  }
+  return Qt::black;
+}
+
+/**
+* Remove a stored curve.
+* @param label :: The label of a curve to remove.
+*/
+void OneCurvePlot::removeCurve(const QString &label) {
+  QMap<QString, QwtPlotCurve *>::iterator it = m_stored.find(label);
+  if (it != m_stored.end()) {
+    it.value()->detach();
+    delete it.value();
+    m_stored.erase(it);
+  }
+}
+
+/**
+* Does the y axis have the log scale?
+*/
+bool OneCurvePlot::isYLogScale() const {
+  const QwtScaleEngine *engine = axisScaleEngine(yLeft);
+  return dynamic_cast<const QwtLog10ScaleEngine *>(engine) != NULL;
+}
+
+/**
+* Remove all displayable objects from the plot.
+*/
+void OneCurvePlot::clearAll() {
+  QMap<QString, QwtPlotCurve *>::const_iterator it = m_stored.begin();
+  for (; it != m_stored.end(); ++it) {
+    it.value()->detach();
+    delete it.value();
+  }
+  m_stored.clear();
+  clearPeakLabels();
+  clearCurve();
+  m_colorIndex = 0;
+}
+
+/* ---------------------------- PeakLabel --------------------------- */
+
+/**
+* Draw PeakLabel on a plot
+*/
+void PeakLabel::draw(QPainter *painter, const QwtScaleMap &xMap,
+                     const QwtScaleMap &yMap, const QRect &canvasRect) const {
+  (void)yMap;
+  double peakX;
+  if (m_plot->getXUnits().empty())
+    return;
+  if (m_plot->getXUnits() == "dSpacing") {
+    peakX = m_marker->getPeak().getDSpacing();
+  } else if (m_plot->getXUnits() == "Wavelength") {
+    peakX = m_marker->getPeak().getWavelength();
+  } else {
+    peakX = m_marker->getPeak().getTOF();
+  }
+  int x = xMap.transform(peakX);
+  int y =
+      static_cast<int>(canvasRect.top() + m_marker->getLabelRect().height());
+  painter->drawText(x, y, m_marker->getLabel());
+  // std::cerr << x << ' ' << y << ' ' << m_marker->getLabel().toStdString() <<
+  // std::endl;
+}
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/OpenGLError.cpp b/MantidQt/MantidWidgets/src/InstrumentView/OpenGLError.cpp
index 105afb3e9637cc9550d6f58233ebb7784153e26d..c24dcbd49f906f04954294cc0cdde5bf1c25c2c3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/OpenGLError.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/OpenGLError.cpp
@@ -3,45 +3,35 @@
 #include "MantidKernel/Logger.h"
 #include "MantidGeometry/Rendering/OpenGL_Headers.h"
 
-namespace
-{
-  // Initialize logger
-  Mantid::Kernel::Logger g_log("OpenGL");
+namespace {
+// Initialize logger
+Mantid::Kernel::Logger g_log("OpenGL");
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		/**
-		* Check for a GL error and throw OpenGLError if found
-		* @param funName :: Name of the function where checkGLError is called.
-		*   The message returned be what() method of the exception has the form:
-		*   "OpenGL error detected in " + funName + ": " + error_description
-		*/
-		bool OpenGLError::check(const std::string& funName)
-		{
-			GLuint err = glGetError();
-			if (err)
-			{
-				std::ostringstream ostr;
-				ostr << "OpenGL error detected in " << funName << ": " << gluErrorString(err);
-				g_log.error() << ostr.str() << '\n';
-				//throw OpenGLError(ostr.str());
-				return true;
-			}
-			return false;
-		}
+namespace MantidQt {
+namespace MantidWidgets {
+/**
+* Check for a GL error and throw OpenGLError if found
+* @param funName :: Name of the function where checkGLError is called.
+*   The message returned be what() method of the exception has the form:
+*   "OpenGL error detected in " + funName + ": " + error_description
+*/
+bool OpenGLError::check(const std::string &funName) {
+  GLuint err = glGetError();
+  if (err) {
+    std::ostringstream ostr;
+    ostr << "OpenGL error detected in " << funName << ": "
+         << gluErrorString(err);
+    g_log.error() << ostr.str() << '\n';
+    // throw OpenGLError(ostr.str());
+    return true;
+  }
+  return false;
+}
 
-		std::ostream& OpenGLError::log()
-		{
-			return g_log.error();
-		}
+std::ostream &OpenGLError::log() { return g_log.error(); }
 
-		std::ostream& OpenGLError::logDebug()
-		{
-			return g_log.debug();
-		}
+std::ostream &OpenGLError::logDebug() { return g_log.debug(); }
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/PeakMarker2D.cpp b/MantidQt/MantidWidgets/src/InstrumentView/PeakMarker2D.cpp
index 8d2c03c02438e0bb54fc698d415a44a45b288e53..d90f9cf6d318a49318e584c01345269b158c6bc3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/PeakMarker2D.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/PeakMarker2D.cpp
@@ -11,142 +11,128 @@
 #include <stdexcept>
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/// Default size in screen pixels of the marker's symbol
-		const int PeakMarker2D::g_defaultMarkerSize = 5;
-
-		/**
-		* Constructor.
-		* @param peakOverlay :: shape for the overlay
-		* @param u :: x screen coordinate of peak center
-		* @param v :: y screen coordinate of peak center
-		* @param style :: marker symbol style
-		*/
-		PeakMarker2D::PeakMarker2D(PeakOverlay& peakOverlay, double u, double v, const Style& style) :
-			m_peakOverlay(peakOverlay),
-			m_symbol(style.symbol),
-			m_h(-99.0),
-			m_k(-99.0),
-			m_l(-99.0),
-			m_detID(-99),
-			m_row(-1)
-		{
-			setColor(style.color);
-			if (style.size > 0)
-			{
-				m_markerSize = style.size;
-			}
-			else
-			{
-				m_markerSize = g_defaultMarkerSize;
-			}
-			const QPointF& centre = QPointF(u, v);
-			m_boundingRect = RectF(centre - QPointF((qreal)m_markerSize / 2, (qreal)m_markerSize / 2),
-				QSizeF((qreal)m_markerSize, (qreal)m_markerSize));
-			setScalable(false);
-		}
-
-		/**
-		* Return the style of the marker.
-		*/
-		PeakMarker2D::Style PeakMarker2D::getStyle() const
-		{
-			return Style(m_symbol, getColor(), m_markerSize);
-		}
-
-		bool PeakMarker2D::selectAt(const QPointF& p)const
-		{
-			return contains(p);
-		}
-
-		void PeakMarker2D::drawShape(QPainter& painter) const
-		{
-			// draw the symbol
-			switch (m_symbol)
-			{
-			case Circle: drawCircle(painter); break;
-			case Diamond: drawDiamond(painter); break;
-			case Square: drawSquare(painter); break;
-			default:
-				drawCircle(painter);
-			}
-			// calculate label's area on the screen
-			QFontMetrics fm(painter.font());
-			QRect r = fm.boundingRect(m_label);
-			m_labelRect = QRectF(r);
-			m_labelRect.moveTo(m_boundingRect.x1() + m_markerSize, m_boundingRect.y1() - m_markerSize);
-		}
-
-		void PeakMarker2D::addToPath(QPainterPath& path) const
-		{
-			path.addRect(m_boundingRect.toQRectF());
-		}
-
-		/// Set new marker size to s
-		void PeakMarker2D::setMarkerSize(const int& s)
-		{
-			if (s > 0)
-			{
-				m_markerSize = s;
-			}
-		}
-
-		/// Draw marker as a circle
-		void PeakMarker2D::drawCircle(QPainter& painter)const
-		{
-			QPainterPath path;
-			path.addEllipse(m_boundingRect.toQRectF());
-			painter.fillPath(path, m_color);
-		}
-
-		/// Draw marker as a diamond
-		void PeakMarker2D::drawDiamond(QPainter& painter)const
-		{
-			QPointF dp = origin();
-			QPointF mdp(-dp.x(), -dp.y());
-			// draw a diamond as a square rotated by 45 degrees
-			painter.save();
-			painter.translate(dp);
-			painter.rotate(45);
-			painter.translate(mdp);
-			QPainterPath path;
-			path.addRect(m_boundingRect.toQRectF());
-			painter.fillPath(path, m_color);
-			painter.restore();
-		}
-
-		/// Draw marker as a square
-		void PeakMarker2D::drawSquare(QPainter& painter)const
-		{
-			QPainterPath path;
-			path.addRect(m_boundingRect.toQRectF());
-			painter.fillPath(path, m_color);
-		}
-
-		/**
-		* Save some peak information.
-		*/
-		void PeakMarker2D::setPeak(const Mantid::Geometry::IPeak& peak, int row)
-		{
-			m_h = peak.getH();
-			m_k = peak.getK();
-			m_l = peak.getL();
-			m_label = QString("%1 %2 %3").arg(QString::number(m_h, 'g', 2), QString::number(m_k, 'g', 2), QString::number(m_l, 'g', 2));
-			m_detID = peak.getDetectorID();
-			m_row = row;
-		}
-
-		/**
-		* Return reference to the peak.
-		*/
-		const Mantid::Geometry::IPeak& PeakMarker2D::getPeak() const
-		{
-			return m_peakOverlay.getPeak(m_row);
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/// Default size in screen pixels of the marker's symbol
+const int PeakMarker2D::g_defaultMarkerSize = 5;
+
+/**
+* Constructor.
+* @param peakOverlay :: shape for the overlay
+* @param u :: x screen coordinate of peak center
+* @param v :: y screen coordinate of peak center
+* @param style :: marker symbol style
+*/
+PeakMarker2D::PeakMarker2D(PeakOverlay &peakOverlay, double u, double v,
+                           const Style &style)
+    : m_peakOverlay(peakOverlay), m_symbol(style.symbol), m_h(-99.0),
+      m_k(-99.0), m_l(-99.0), m_detID(-99), m_row(-1) {
+  setColor(style.color);
+  if (style.size > 0) {
+    m_markerSize = style.size;
+  } else {
+    m_markerSize = g_defaultMarkerSize;
+  }
+  const QPointF &centre = QPointF(u, v);
+  m_boundingRect =
+      RectF(centre - QPointF((qreal)m_markerSize / 2, (qreal)m_markerSize / 2),
+            QSizeF((qreal)m_markerSize, (qreal)m_markerSize));
+  setScalable(false);
+}
+
+/**
+* Return the style of the marker.
+*/
+PeakMarker2D::Style PeakMarker2D::getStyle() const {
+  return Style(m_symbol, getColor(), m_markerSize);
+}
+
+bool PeakMarker2D::selectAt(const QPointF &p) const { return contains(p); }
+
+void PeakMarker2D::drawShape(QPainter &painter) const {
+  // draw the symbol
+  switch (m_symbol) {
+  case Circle:
+    drawCircle(painter);
+    break;
+  case Diamond:
+    drawDiamond(painter);
+    break;
+  case Square:
+    drawSquare(painter);
+    break;
+  default:
+    drawCircle(painter);
+  }
+  // calculate label's area on the screen
+  QFontMetrics fm(painter.font());
+  QRect r = fm.boundingRect(m_label);
+  m_labelRect = QRectF(r);
+  m_labelRect.moveTo(m_boundingRect.x1() + m_markerSize,
+                     m_boundingRect.y1() - m_markerSize);
+}
+
+void PeakMarker2D::addToPath(QPainterPath &path) const {
+  path.addRect(m_boundingRect.toQRectF());
+}
+
+/// Set new marker size to s
+void PeakMarker2D::setMarkerSize(const int &s) {
+  if (s > 0) {
+    m_markerSize = s;
+  }
+}
+
+/// Draw marker as a circle
+void PeakMarker2D::drawCircle(QPainter &painter) const {
+  QPainterPath path;
+  path.addEllipse(m_boundingRect.toQRectF());
+  painter.fillPath(path, m_color);
+}
+
+/// Draw marker as a diamond
+void PeakMarker2D::drawDiamond(QPainter &painter) const {
+  QPointF dp = origin();
+  QPointF mdp(-dp.x(), -dp.y());
+  // draw a diamond as a square rotated by 45 degrees
+  painter.save();
+  painter.translate(dp);
+  painter.rotate(45);
+  painter.translate(mdp);
+  QPainterPath path;
+  path.addRect(m_boundingRect.toQRectF());
+  painter.fillPath(path, m_color);
+  painter.restore();
+}
+
+/// Draw marker as a square
+void PeakMarker2D::drawSquare(QPainter &painter) const {
+  QPainterPath path;
+  path.addRect(m_boundingRect.toQRectF());
+  painter.fillPath(path, m_color);
+}
+
+/**
+* Save some peak information.
+*/
+void PeakMarker2D::setPeak(const Mantid::Geometry::IPeak &peak, int row) {
+  m_h = peak.getH();
+  m_k = peak.getK();
+  m_l = peak.getL();
+  m_label = QString("%1 %2 %3")
+                .arg(QString::number(m_h, 'g', 2), QString::number(m_k, 'g', 2),
+                     QString::number(m_l, 'g', 2));
+  m_detID = peak.getDetectorID();
+  m_row = row;
+}
+
+/**
+* Return reference to the peak.
+*/
+const Mantid::Geometry::IPeak &PeakMarker2D::getPeak() const {
+  return m_peakOverlay.getPeak(m_row);
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/PeakOverlay.cpp b/MantidQt/MantidWidgets/src/InstrumentView/PeakOverlay.cpp
index bdea3a996de6a6265886d1371e452c284d068bbd..b6fc4287aff853b488cde5d3f3aad3bbcf25e798 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/PeakOverlay.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/PeakOverlay.cpp
@@ -11,439 +11,433 @@
 #include <algorithm>
 #include <stdexcept>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		QList<PeakMarker2D::Style> PeakOverlay::g_defaultStyles;
-
-		/**
-		* Constructor.
-		*/
-		PeakHKL::PeakHKL(PeakMarker2D *m, const QRectF &trect, bool sr)
-			: p(m->origin()), rect(trect),
-			// rectTopLeft(m->getLabelRect().topLeft()),
-			h(m->getH()), k(m->getK()), l(m->getL()), nh(true), nk(true), nl(true),
-			showRows(sr) {
-			rows.append(m->getRow());
-		}
-
-		/**
-		* Check if this rect intersects with marker's and if it does combine the labels
-		* @param marker :: A marker to check for intersection
-		* @param trect :: Transformed marker's label rect
-		* @return True if labels were combined, false otherwise.
-		*/
-		bool PeakHKL::add(PeakMarker2D *marker, const QRectF &trect) {
-			if (!rect.intersects(trect)) {
-				return false;
-			}
-			if (nh && marker->getH() != h) {
-				nh = false;
-			}
-			if (nk && marker->getK() != k) {
-				nk = false;
-			}
-			if (nl && marker->getL() != l) {
-				nl = false;
-			}
-			rows.append(marker->getRow());
-			return true;
-		}
-		/**
-		* Draw the label
-		* @param painter :: QPainter to draw with
-		* @param prec :: precision
-		*/
-		void PeakHKL::draw(QPainter &painter, int prec) {
-			QString label;
-			if (nh) {
-				label += formatNumber(h, prec) + " ";
-			}
-			else
-				label = "h ";
-			if (nk) {
-				label += formatNumber(k, prec) + " ";
-			}
-			else
-				label += "k ";
-			if (nl) {
-				label += formatNumber(l, prec) + " ";
-			}
-			else
-				label += "l";
-			if (showRows) {
-				label += " [" + QString::number(rows[0]);
-				for (int i = 1; i < rows.size(); ++i) {
-					label += "," + QString::number(rows[i]);
-				}
-				label += "]";
-			}
-			painter.drawText(rect.bottomLeft(), label);
-		}
-
-		void PeakHKL::print() const {
-			std::cerr << "     " << p.x() << ' ' << p.y() << '(' << h << ',' << k << ','
-				<< l << ")(" << nh << ',' << nk << ',' << nl << ')' << std::endl;
-		}
-
-		/**
-		* Creates formated string for outputting h,k, or l
-		*
-		* @param h :: Value to output.
-		* @param prec :: Precision as a number of decimal places.
-		*/
-		QString PeakHKL::formatNumber(double h, int prec) {
-			if (h == 0)
-				return "0";
-			int max_prec = std::max(prec, int(log10(h) + 1));
-			QString str = QString::number(h, 'f', max_prec);
-			if (str.contains('.')) {
-				while (str.endsWith('0'))
-					str.chop(1);
-				if (str.endsWith('.'))
-					str.chop(1);
-			}
-			return str;
-		}
-
-		/// Extract minimum and maximum intensity from peaks workspace for scaling.
-		void AbstractIntensityScale::setPeaksWorkspace(
-			const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws) {
-			m_maxIntensity = 0.0;
-			m_minIntensity = 0.0;
-
-			if (pws) {
-				int peakCount = pws->getNumberPeaks();
-
-				std::vector<double> intensities;
-				intensities.reserve(peakCount);
-
-				for (int i = 0; i < peakCount; ++i) {
-					intensities.push_back(pws->getPeak(i).getIntensity());
-				}
-
-				auto minMaxIntensity =
-					std::minmax_element(intensities.begin(), intensities.end());
-
-				if (peakCount > 0) {
-					m_maxIntensity = *minMaxIntensity.second;
-					m_minIntensity = *minMaxIntensity.first;
-				}
-			}
-		}
-
-		/// Returns the scaled style by intensity. Only size is changed, the other
-		/// properties are kept the same. If the max intensity is 0 or less, the
-		/// style is returned as it is.
-		PeakMarker2D::Style QualitativeIntensityScale::getScaledMarker(
-			double intensity, const PeakMarker2D::Style &baseStyle) const {
-			if (m_maxIntensity <= 0.0) {
-				return baseStyle;
-			}
-
-			return PeakMarker2D::Style(baseStyle.symbol, baseStyle.color,
-				3 * getIntensityLevel(intensity) + 1);
-		}
-
-		/**
-		* Returns the marker size corresponding to the supplied intensity
-		*
-		* Intensity levels are specified in m_intensityLevels. The method looks for
-		* the first element >= than the relative intensity and returns the distance
-		* from the beginning of list to that element + 1.
-		*
-		* For values less than the first element, 0 is returned.
-		*
-		* @param intensity :: Absolute intensity.
-		* @return Intensity level between 0 and the number of intensity levels + 1
-		*/
-		int QualitativeIntensityScale::getIntensityLevel(double intensity) const {
-			auto intensityGreaterThan =
-				std::lower_bound(m_intensityLevels.cbegin(), m_intensityLevels.cend(),
-					intensity / m_maxIntensity);
-
-			// For weak peaks below first intensity
-			if (intensityGreaterThan == m_intensityLevels.cend()) {
-				return 0;
-			}
-
-			return static_cast<int>(
-				std::distance(m_intensityLevels.cbegin(), intensityGreaterThan)) +
-				1;
-		}
-
-		/**---------------------------------------------------------------------
-		* Constructor
-		*/
-		PeakOverlay::PeakOverlay(UnwrappedSurface *surface,
-			boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws)
-			: Shape2DCollection(), m_peaksWorkspace(pws), m_surface(surface),
-			m_precision(6), m_showRows(true), m_showLabels(true),
-			m_peakIntensityScale(
-				Mantid::Kernel::make_unique<QualitativeIntensityScale>(pws)) {
-
-			if (g_defaultStyles.isEmpty()) {
-				g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Circle, Qt::red);
-				g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Diamond, Qt::green);
-				g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Square, Qt::magenta);
-			}
-			observeAfterReplace();
-		}
-
-		/**---------------------------------------------------------------------
-		* Overridden virtual function to remove peaks from the workspace along with
-		* the shapes.
-		* @param shapeList :: Shapes to remove.
-		*/
-		void PeakOverlay::removeShapes(const QList<Shape2D *> &shapeList) {
-			// vectors of rows to delete from the peaks workspace.
-			std::vector<size_t> rows;
-			foreach(Shape2D *shape, shapeList) {
-				PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
-				if (!marker)
-					throw std::logic_error("Wrong shape type found.");
-				rows.push_back(static_cast<size_t>(marker->getRow()));
-			}
-
-			// Run the DeleteTableRows algorithm to delete the peak.
-			auto alg =
-				Mantid::API::AlgorithmManager::Instance().create("DeleteTableRows", -1);
-			alg->setPropertyValue("TableWorkspace", m_peaksWorkspace->name());
-			alg->setProperty("Rows", rows);
-			emit executeAlgorithm(alg);
-		}
-
-		/**---------------------------------------------------------------------
-		* Not implemented yet.
-		*/
-		void PeakOverlay::clear() {
-			Shape2DCollection::clear();
-			m_det2marker.clear();
-		}
-
-		/**---------------------------------------------------------------------
-		* Add new marker to the overlay.
-		* @param m :: Pointer to the new marker
-		*/
-		void PeakOverlay::addMarker(PeakMarker2D *m) {
-			addShape(m, false);
-			m_det2marker.insert(m->getDetectorID(), m);
-		}
-
-		/**---------------------------------------------------------------------
-		* Create the markers which graphically represent the peaks on the surface.
-		* The coordinates of the Shape2DCollection must be set (calling setWindow())
-		* prior calling this method.
-		* @param style :: A style of drawing the markers.
-		*/
-		void PeakOverlay::createMarkers(const PeakMarker2D::Style &style) {
-			int nPeaks = getNumberPeaks();
-
-			this->clear();
-			for (int i = 0; i < nPeaks; ++i) {
-				Mantid::Geometry::IPeak &peak = getPeak(i);
-				const Mantid::Kernel::V3D &pos = peak.getDetPos();
-				// Project the peak (detector) position onto u,v coords
-				double u, v, uscale, vscale;
-				m_surface->project(pos, u, v, uscale, vscale);
-
-				// Create a peak marker at this position
-				PeakMarker2D *r = new PeakMarker2D(
-					*this, u, v,
-					m_peakIntensityScale->getScaledMarker(peak.getIntensity(), style));
-				r->setPeak(peak, i);
-				addMarker(r);
-			}
-
-			deselectAll();
-		}
-
-		/**---------------------------------------------------------------------
-		* Draw peaks on screen.
-		* @param painter :: The QPainter to draw with.
-		*/
-		void PeakOverlay::draw(QPainter &painter) const {
-			// Draw symbols
-			Shape2DCollection::draw(painter);
-
-			if (!m_showLabels)
-				return;
-
-			// Sort the labels to avoid overlapping
-			QColor color(Qt::red);
-			if (!m_shapes.isEmpty()) {
-				color = m_shapes[0]->getColor();
-			}
-			QRectF clipRect(painter.viewport());
-			m_labels.clear();
-			foreach(Shape2D *shape, m_shapes) {
-				if (!shape->isVisible())
-					continue;
-				if (!clipRect.contains(m_transform.map(shape->origin())))
-					continue;
-				PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
-				if (!marker)
-					continue;
-
-				QPointF p0 = marker->origin();
-				QPointF p1 = m_transform.map(p0);
-				QRectF rect = marker->getLabelRect();
-				QPointF dp = rect.topLeft() - p0;
-				p1 += dp;
-				rect.moveTo(p1);
-
-				bool overlap = false;
-				// if current label overlaps with another
-				// combine them substituting differing numbers with letter 'h','k', or 'l'
-				for (int i = 0; i < m_labels.size(); ++i) {
-					PeakHKL &hkl = m_labels[i];
-					overlap = hkl.add(marker, rect);
-					if (overlap)
-						break;
-				}
-
-				if (!overlap) {
-					PeakHKL hkl(marker, rect, m_showRows);
-					m_labels.append(hkl);
-				}
-			}
-
-			painter.setPen(color);
-			for (int i = 0; i < m_labels.size(); ++i) {
-				PeakHKL &hkl = m_labels[i];
-				hkl.draw(painter, m_precision);
-			}
-		}
-
-		/**---------------------------------------------------------------------
-		* Return a list of markers put onto a detector
-		* @param detID :: A detector ID for which markers are to be returned.
-		* @return :: A list of zero ot more markers.
-		*/
-		QList<PeakMarker2D *> PeakOverlay::getMarkersWithID(int detID) const {
-			return m_det2marker.values(detID);
-		}
-
-		/**---------------------------------------------------------------------
-		* Return the total number of peaks.
-		*/
-		int PeakOverlay::getNumberPeaks() const {
-			return m_peaksWorkspace->getNumberPeaks();
-		}
-
-		/** ---------------------------------------------------------------------
-		* Return the i-th peak.
-		* @param i :: Peak index.
-		* @return A reference to the peak.
-		*/
-		Mantid::Geometry::IPeak &PeakOverlay::getPeak(int i) {
-			return m_peaksWorkspace->getPeak(i);
-		}
-
-		/// Sets the scaler that is used to determine the size of peak markers.
-		void PeakOverlay::setShowRelativeIntensityFlag(bool yes) {
-			if (yes) {
-				m_peakIntensityScale =
-					Mantid::Kernel::make_unique<QualitativeIntensityScale>(
-						m_peaksWorkspace);
-			}
-			else {
-				m_peakIntensityScale =
-					Mantid::Kernel::make_unique<DefaultIntensityScale>(m_peaksWorkspace);
-			}
-
-			recreateMarkers(getCurrentStyle());
-		}
-
-		/// Returns the current style or the default style is no markers are present.
-		PeakMarker2D::Style PeakOverlay::getCurrentStyle() const {
-			auto baseStyle = getDefaultStyle(0);
-
-			if (isEmpty()) {
-				return baseStyle;
-			}
-
-			auto currentStyle = m_det2marker.begin().value()->getStyle();
-
-			return PeakMarker2D::Style(currentStyle.symbol, currentStyle.color,
-				baseStyle.size);
-		}
-
-		/** ---------------------------------------------------------------------
-		* Handler of the AfterReplace notifications. Updates the markers.
-		* @param wsName :: The name of the modified workspace.
-		* @param ws :: The shared pointer to the modified workspace.
-		*/
-		void PeakOverlay::afterReplaceHandle(const std::string &wsName,
-			const Mantid::API::Workspace_sptr ws) {
-			Q_UNUSED(wsName);
-			auto peaksWS = boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(ws);
-			if (peaksWS && peaksWS == m_peaksWorkspace && m_surface) {
-				m_peakIntensityScale->setPeaksWorkspace(peaksWS);
-
-				recreateMarkers(getCurrentStyle());
-			}
-		}
-
-		void PeakOverlay::recreateMarkers(const PeakMarker2D::Style &style) {
-			clear();
-			createMarkers(style);
-			m_surface->requestRedraw(true);
-		}
-
-		/** ---------------------------------------------------------------------
-		* Return a default style for creating markers by index.
-		* Styles are taken form g_defaultStyles
-		*/
-		PeakMarker2D::Style PeakOverlay::getDefaultStyle(int index) {
-			index %= g_defaultStyles.size();
-			return g_defaultStyles[index];
-		}
-
-		/** ---------------------------------------------------------------------
-		* Set visibility of the peak markers according to the integration range
-		* in the instrument actor.
-		*
-		* @param xmin :: The lower bound of the integration range.
-		* @param xmax :: The upper bound of the integration range.
-		* @param units :: Units of the x - array in the underlying workspace:
-		*     "TOF", "dSpacing", or "Wavelength".
-		*/
-		void PeakOverlay::setPeakVisibility(double xmin, double xmax, QString units) {
-			enum XUnits { Unknown, TOF, dSpacing, Wavelength };
-			XUnits xUnits = Unknown;
-			if (units == "TOF")
-				xUnits = TOF;
-			else if (units == "dSpacing")
-				xUnits = dSpacing;
-			else if (units == "Wavelength")
-				xUnits = Wavelength;
-			foreach(Shape2D *shape, m_shapes) {
-				PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
-				if (!marker)
-					continue;
-				Mantid::Geometry::IPeak &peak = getPeak(marker->getRow());
-				double x = 0.0;
-				switch (xUnits) {
-				case TOF:
-					x = peak.getTOF();
-					break;
-				case dSpacing:
-					x = peak.getDSpacing();
-					break;
-				case Wavelength:
-					x = peak.getWavelength();
-					break;
-					// if unknown units always vidsible
-				default:
-					x = xmin;
-				}
-				bool on = x >= xmin && x <= xmax;
-				marker->setVisible(on);
-			}
-		}
-
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+namespace MantidQt {
+namespace MantidWidgets {
+
+QList<PeakMarker2D::Style> PeakOverlay::g_defaultStyles;
+
+/**
+* Constructor.
+*/
+PeakHKL::PeakHKL(PeakMarker2D *m, const QRectF &trect, bool sr)
+    : p(m->origin()), rect(trect),
+      // rectTopLeft(m->getLabelRect().topLeft()),
+      h(m->getH()), k(m->getK()), l(m->getL()), nh(true), nk(true), nl(true),
+      showRows(sr) {
+  rows.append(m->getRow());
+}
+
+/**
+* Check if this rect intersects with marker's and if it does combine the labels
+* @param marker :: A marker to check for intersection
+* @param trect :: Transformed marker's label rect
+* @return True if labels were combined, false otherwise.
+*/
+bool PeakHKL::add(PeakMarker2D *marker, const QRectF &trect) {
+  if (!rect.intersects(trect)) {
+    return false;
+  }
+  if (nh && marker->getH() != h) {
+    nh = false;
+  }
+  if (nk && marker->getK() != k) {
+    nk = false;
+  }
+  if (nl && marker->getL() != l) {
+    nl = false;
+  }
+  rows.append(marker->getRow());
+  return true;
+}
+/**
+* Draw the label
+* @param painter :: QPainter to draw with
+* @param prec :: precision
+*/
+void PeakHKL::draw(QPainter &painter, int prec) {
+  QString label;
+  if (nh) {
+    label += formatNumber(h, prec) + " ";
+  } else
+    label = "h ";
+  if (nk) {
+    label += formatNumber(k, prec) + " ";
+  } else
+    label += "k ";
+  if (nl) {
+    label += formatNumber(l, prec) + " ";
+  } else
+    label += "l";
+  if (showRows) {
+    label += " [" + QString::number(rows[0]);
+    for (int i = 1; i < rows.size(); ++i) {
+      label += "," + QString::number(rows[i]);
+    }
+    label += "]";
+  }
+  painter.drawText(rect.bottomLeft(), label);
+}
+
+void PeakHKL::print() const {
+  std::cerr << "     " << p.x() << ' ' << p.y() << '(' << h << ',' << k << ','
+            << l << ")(" << nh << ',' << nk << ',' << nl << ')' << std::endl;
+}
+
+/**
+* Creates formated string for outputting h,k, or l
+*
+* @param h :: Value to output.
+* @param prec :: Precision as a number of decimal places.
+*/
+QString PeakHKL::formatNumber(double h, int prec) {
+  if (h == 0)
+    return "0";
+  int max_prec = std::max(prec, int(log10(h) + 1));
+  QString str = QString::number(h, 'f', max_prec);
+  if (str.contains('.')) {
+    while (str.endsWith('0'))
+      str.chop(1);
+    if (str.endsWith('.'))
+      str.chop(1);
+  }
+  return str;
+}
+
+/// Extract minimum and maximum intensity from peaks workspace for scaling.
+void AbstractIntensityScale::setPeaksWorkspace(
+    const boost::shared_ptr<Mantid::API::IPeaksWorkspace> &pws) {
+  m_maxIntensity = 0.0;
+  m_minIntensity = 0.0;
+
+  if (pws) {
+    int peakCount = pws->getNumberPeaks();
+
+    std::vector<double> intensities;
+    intensities.reserve(peakCount);
+
+    for (int i = 0; i < peakCount; ++i) {
+      intensities.push_back(pws->getPeak(i).getIntensity());
+    }
+
+    auto minMaxIntensity =
+        std::minmax_element(intensities.begin(), intensities.end());
+
+    if (peakCount > 0) {
+      m_maxIntensity = *minMaxIntensity.second;
+      m_minIntensity = *minMaxIntensity.first;
+    }
+  }
+}
+
+/// Returns the scaled style by intensity. Only size is changed, the other
+/// properties are kept the same. If the max intensity is 0 or less, the
+/// style is returned as it is.
+PeakMarker2D::Style QualitativeIntensityScale::getScaledMarker(
+    double intensity, const PeakMarker2D::Style &baseStyle) const {
+  if (m_maxIntensity <= 0.0) {
+    return baseStyle;
+  }
+
+  return PeakMarker2D::Style(baseStyle.symbol, baseStyle.color,
+                             3 * getIntensityLevel(intensity) + 1);
+}
+
+/**
+* Returns the marker size corresponding to the supplied intensity
+*
+* Intensity levels are specified in m_intensityLevels. The method looks for
+* the first element >= than the relative intensity and returns the distance
+* from the beginning of list to that element + 1.
+*
+* For values less than the first element, 0 is returned.
+*
+* @param intensity :: Absolute intensity.
+* @return Intensity level between 0 and the number of intensity levels + 1
+*/
+int QualitativeIntensityScale::getIntensityLevel(double intensity) const {
+  auto intensityGreaterThan =
+      std::lower_bound(m_intensityLevels.cbegin(), m_intensityLevels.cend(),
+                       intensity / m_maxIntensity);
+
+  // For weak peaks below first intensity
+  if (intensityGreaterThan == m_intensityLevels.cend()) {
+    return 0;
+  }
+
+  return static_cast<int>(
+             std::distance(m_intensityLevels.cbegin(), intensityGreaterThan)) +
+         1;
+}
+
+/**---------------------------------------------------------------------
+* Constructor
+*/
+PeakOverlay::PeakOverlay(UnwrappedSurface *surface,
+                         boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws)
+    : Shape2DCollection(), m_peaksWorkspace(pws), m_surface(surface),
+      m_precision(6), m_showRows(true), m_showLabels(true),
+      m_peakIntensityScale(
+          Mantid::Kernel::make_unique<QualitativeIntensityScale>(pws)) {
+
+  if (g_defaultStyles.isEmpty()) {
+    g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Circle, Qt::red);
+    g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Diamond, Qt::green);
+    g_defaultStyles << PeakMarker2D::Style(PeakMarker2D::Square, Qt::magenta);
+  }
+  observeAfterReplace();
+}
+
+/**---------------------------------------------------------------------
+* Overridden virtual function to remove peaks from the workspace along with
+* the shapes.
+* @param shapeList :: Shapes to remove.
+*/
+void PeakOverlay::removeShapes(const QList<Shape2D *> &shapeList) {
+  // vectors of rows to delete from the peaks workspace.
+  std::vector<size_t> rows;
+  foreach (Shape2D *shape, shapeList) {
+    PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
+    if (!marker)
+      throw std::logic_error("Wrong shape type found.");
+    rows.push_back(static_cast<size_t>(marker->getRow()));
+  }
+
+  // Run the DeleteTableRows algorithm to delete the peak.
+  auto alg =
+      Mantid::API::AlgorithmManager::Instance().create("DeleteTableRows", -1);
+  alg->setPropertyValue("TableWorkspace", m_peaksWorkspace->name());
+  alg->setProperty("Rows", rows);
+  emit executeAlgorithm(alg);
+}
+
+/**---------------------------------------------------------------------
+* Not implemented yet.
+*/
+void PeakOverlay::clear() {
+  Shape2DCollection::clear();
+  m_det2marker.clear();
+}
+
+/**---------------------------------------------------------------------
+* Add new marker to the overlay.
+* @param m :: Pointer to the new marker
+*/
+void PeakOverlay::addMarker(PeakMarker2D *m) {
+  addShape(m, false);
+  m_det2marker.insert(m->getDetectorID(), m);
+}
+
+/**---------------------------------------------------------------------
+* Create the markers which graphically represent the peaks on the surface.
+* The coordinates of the Shape2DCollection must be set (calling setWindow())
+* prior calling this method.
+* @param style :: A style of drawing the markers.
+*/
+void PeakOverlay::createMarkers(const PeakMarker2D::Style &style) {
+  int nPeaks = getNumberPeaks();
+
+  this->clear();
+  for (int i = 0; i < nPeaks; ++i) {
+    Mantid::Geometry::IPeak &peak = getPeak(i);
+    const Mantid::Kernel::V3D &pos = peak.getDetPos();
+    // Project the peak (detector) position onto u,v coords
+    double u, v, uscale, vscale;
+    m_surface->project(pos, u, v, uscale, vscale);
+
+    // Create a peak marker at this position
+    PeakMarker2D *r = new PeakMarker2D(
+        *this, u, v,
+        m_peakIntensityScale->getScaledMarker(peak.getIntensity(), style));
+    r->setPeak(peak, i);
+    addMarker(r);
+  }
+
+  deselectAll();
+}
+
+/**---------------------------------------------------------------------
+* Draw peaks on screen.
+* @param painter :: The QPainter to draw with.
+*/
+void PeakOverlay::draw(QPainter &painter) const {
+  // Draw symbols
+  Shape2DCollection::draw(painter);
+
+  if (!m_showLabels)
+    return;
+
+  // Sort the labels to avoid overlapping
+  QColor color(Qt::red);
+  if (!m_shapes.isEmpty()) {
+    color = m_shapes[0]->getColor();
+  }
+  QRectF clipRect(painter.viewport());
+  m_labels.clear();
+  foreach (Shape2D *shape, m_shapes) {
+    if (!shape->isVisible())
+      continue;
+    if (!clipRect.contains(m_transform.map(shape->origin())))
+      continue;
+    PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
+    if (!marker)
+      continue;
+
+    QPointF p0 = marker->origin();
+    QPointF p1 = m_transform.map(p0);
+    QRectF rect = marker->getLabelRect();
+    QPointF dp = rect.topLeft() - p0;
+    p1 += dp;
+    rect.moveTo(p1);
+
+    bool overlap = false;
+    // if current label overlaps with another
+    // combine them substituting differing numbers with letter 'h','k', or 'l'
+    for (int i = 0; i < m_labels.size(); ++i) {
+      PeakHKL &hkl = m_labels[i];
+      overlap = hkl.add(marker, rect);
+      if (overlap)
+        break;
+    }
+
+    if (!overlap) {
+      PeakHKL hkl(marker, rect, m_showRows);
+      m_labels.append(hkl);
+    }
+  }
+
+  painter.setPen(color);
+  for (int i = 0; i < m_labels.size(); ++i) {
+    PeakHKL &hkl = m_labels[i];
+    hkl.draw(painter, m_precision);
+  }
+}
+
+/**---------------------------------------------------------------------
+* Return a list of markers put onto a detector
+* @param detID :: A detector ID for which markers are to be returned.
+* @return :: A list of zero ot more markers.
+*/
+QList<PeakMarker2D *> PeakOverlay::getMarkersWithID(int detID) const {
+  return m_det2marker.values(detID);
+}
+
+/**---------------------------------------------------------------------
+* Return the total number of peaks.
+*/
+int PeakOverlay::getNumberPeaks() const {
+  return m_peaksWorkspace->getNumberPeaks();
+}
+
+/** ---------------------------------------------------------------------
+* Return the i-th peak.
+* @param i :: Peak index.
+* @return A reference to the peak.
+*/
+Mantid::Geometry::IPeak &PeakOverlay::getPeak(int i) {
+  return m_peaksWorkspace->getPeak(i);
+}
+
+/// Sets the scaler that is used to determine the size of peak markers.
+void PeakOverlay::setShowRelativeIntensityFlag(bool yes) {
+  if (yes) {
+    m_peakIntensityScale =
+        Mantid::Kernel::make_unique<QualitativeIntensityScale>(
+            m_peaksWorkspace);
+  } else {
+    m_peakIntensityScale =
+        Mantid::Kernel::make_unique<DefaultIntensityScale>(m_peaksWorkspace);
+  }
+
+  recreateMarkers(getCurrentStyle());
+}
+
+/// Returns the current style or the default style is no markers are present.
+PeakMarker2D::Style PeakOverlay::getCurrentStyle() const {
+  auto baseStyle = getDefaultStyle(0);
+
+  if (isEmpty()) {
+    return baseStyle;
+  }
+
+  auto currentStyle = m_det2marker.begin().value()->getStyle();
+
+  return PeakMarker2D::Style(currentStyle.symbol, currentStyle.color,
+                             baseStyle.size);
+}
+
+/** ---------------------------------------------------------------------
+* Handler of the AfterReplace notifications. Updates the markers.
+* @param wsName :: The name of the modified workspace.
+* @param ws :: The shared pointer to the modified workspace.
+*/
+void PeakOverlay::afterReplaceHandle(const std::string &wsName,
+                                     const Mantid::API::Workspace_sptr ws) {
+  Q_UNUSED(wsName);
+  auto peaksWS = boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(ws);
+  if (peaksWS && peaksWS == m_peaksWorkspace && m_surface) {
+    m_peakIntensityScale->setPeaksWorkspace(peaksWS);
+
+    recreateMarkers(getCurrentStyle());
+  }
+}
+
+void PeakOverlay::recreateMarkers(const PeakMarker2D::Style &style) {
+  clear();
+  createMarkers(style);
+  m_surface->requestRedraw(true);
+}
+
+/** ---------------------------------------------------------------------
+* Return a default style for creating markers by index.
+* Styles are taken form g_defaultStyles
+*/
+PeakMarker2D::Style PeakOverlay::getDefaultStyle(int index) {
+  index %= g_defaultStyles.size();
+  return g_defaultStyles[index];
+}
+
+/** ---------------------------------------------------------------------
+* Set visibility of the peak markers according to the integration range
+* in the instrument actor.
+*
+* @param xmin :: The lower bound of the integration range.
+* @param xmax :: The upper bound of the integration range.
+* @param units :: Units of the x - array in the underlying workspace:
+*     "TOF", "dSpacing", or "Wavelength".
+*/
+void PeakOverlay::setPeakVisibility(double xmin, double xmax, QString units) {
+  enum XUnits { Unknown, TOF, dSpacing, Wavelength };
+  XUnits xUnits = Unknown;
+  if (units == "TOF")
+    xUnits = TOF;
+  else if (units == "dSpacing")
+    xUnits = dSpacing;
+  else if (units == "Wavelength")
+    xUnits = Wavelength;
+  foreach (Shape2D *shape, m_shapes) {
+    PeakMarker2D *marker = dynamic_cast<PeakMarker2D *>(shape);
+    if (!marker)
+      continue;
+    Mantid::Geometry::IPeak &peak = getPeak(marker->getRow());
+    double x = 0.0;
+    switch (xUnits) {
+    case TOF:
+      x = peak.getTOF();
+      break;
+    case dSpacing:
+      x = peak.getDSpacing();
+      break;
+    case Wavelength:
+      x = peak.getWavelength();
+      break;
+    // if unknown units always vidsible
+    default:
+      x = xmin;
+    }
+    bool on = x >= xmin && x <= xmax;
+    marker->setVisible(on);
+  }
+}
+
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/Projection3D.cpp b/MantidQt/MantidWidgets/src/InstrumentView/Projection3D.cpp
index b725aa2232241579965fb929537af4857efecbf5..9c9e8abf792ff83079252b2ad1cbba735a40e8b9 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/Projection3D.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/Projection3D.cpp
@@ -27,7 +27,7 @@
 #include <algorithm>
 
 #ifndef GL_MULTISAMPLE
-#define GL_MULTISAMPLE  0x809D
+#define GL_MULTISAMPLE 0x809D
 #endif
 
 using namespace Mantid;
@@ -35,478 +35,431 @@ using namespace Mantid::API;
 using namespace Mantid::Kernel;
 using namespace Mantid::Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-		Projection3D::Projection3D(const InstrumentActor* rootActor, int winWidth, int winHeight)
-			:ProjectionSurface(rootActor),
-			m_drawAxes(true),
-			m_wireframe(false),
-			m_viewport(0, 0)
-		{
-
-			Instrument_const_sptr instr = rootActor->getInstrument();
-
-			m_viewport.resize(winWidth, winHeight);
-			V3D minBounds, maxBounds;
-			m_instrActor->getBoundingBox(minBounds, maxBounds);
-
-			m_viewport.setProjection(minBounds, maxBounds);
-
-			changeColorMap();
-			rootActor->invalidateDisplayLists();
-
-			// create and connect the move input controller
-			InputController3DMove* moveController = new InputController3DMove(this);
-			setInputController(MoveMode, moveController);
-			connect(moveController, SIGNAL(initTranslation(int, int)), this, SLOT(initTranslation(int, int)));
-			connect(moveController, SIGNAL(translate(int, int)), this, SLOT(translate(int, int)));
-			connect(moveController, SIGNAL(initRotation(int, int)), this, SLOT(initRotation(int, int)));
-			connect(moveController, SIGNAL(rotate(int, int)), this, SLOT(rotate(int, int)));
-			connect(moveController, SIGNAL(initZoom(int, int)), this, SLOT(initZoom(int, int)));
-			connect(moveController, SIGNAL(zoom(int, int)), this, SLOT(zoom(int, int)));
-			connect(moveController, SIGNAL(wheelZoom(int, int, int)), this, SLOT(wheelZoom(int, int, int)));
-			connect(moveController, SIGNAL(finish()), this, SLOT(finishMove()));
-		}
-
-		Projection3D::~Projection3D()
-		{
-		}
-
-		/**
-		* Resize the surface on the screen.
-		* @param w :: New width of the surface in pixels.
-		* @param h :: New height of the surface in pixels.
-		*/
-		void Projection3D::resize(int w, int h)
-		{
-			m_viewport.resize(w, h);
-			updateView();
-		}
-
-		/**
-		* Draw the instrument on MantidGLWidget.
-		*/
-		void Projection3D::drawSurface(MantidGLWidget*, bool picking)const
-		{
-			OpenGLError::check("GL3DWidget::draw3D()[begin]");
-
-			glEnable(GL_DEPTH_TEST);
-			OpenGLError::check("GL3DWidget::draw3D()[depth] ");
-
-			if (m_wireframe)
-			{
-				glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-			}
-			else
-			{
-				glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-			}
-
-			setLightingModel(picking);
-
-			// fill the buffer with background colour
-			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
-			m_viewport.applyProjection();
-
-			// Issue the rotation, translation and zooming of the trackball to the object
-			m_viewport.applyRotation();
-
-			// if actor is undefined leave it with clear screen
-			if (m_instrActor)
-			{
-				QApplication::setOverrideCursor(Qt::WaitCursor);
-				m_instrActor->draw(picking);
-				OpenGLError::check("GL3DWidget::draw3D()[scene draw] ");
-				QApplication::restoreOverrideCursor();
-			}
-
-			//Also some axes
-			if (m_drawAxes && !picking)
-			{
-				//This draws a point at the origin, I guess
-				glPointSize(3.0);
-				glBegin(GL_POINTS);
-				glVertex3d(0.0, 0.0, 0.0);
-				glEnd();
-
-				drawAxes();
-			}
-
-			OpenGLError::check("GL3DWidget::draw3D()");
-		}
-
-		/** Draw 3D axes centered at the origin (if the option is selected)
-		*
-		*/
-		void Projection3D::drawAxes(double axis_length)const
-		{
-			glPointSize(3.0);
-			glLineWidth(3.0);
-
-			//To make sure the lines are colored
-			glEnable(GL_COLOR_MATERIAL);
-			glDisable(GL_TEXTURE_2D);
-			glDisable(GL_LIGHTING);
-			glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
-
-			glColor3f(1.0, 0., 0.);
-			glBegin(GL_LINES);
-			glVertex3d(0.0, 0.0, 0.0);
-			glVertex3d(axis_length, 0.0, 0.0);
-			glEnd();
-
-			glColor3f(0., 1.0, 0.);
-			glBegin(GL_LINES);
-			glVertex3d(0.0, 0.0, 0.0);
-			glVertex3d(0.0, axis_length, 0.0);
-			glEnd();
-
-			glColor3f(0., 0., 1.);
-			glBegin(GL_LINES);
-			glVertex3d(0.0, 0.0, 0.0);
-			glVertex3d(0.0, 0.0, axis_length);
-			glEnd();
-		}
-
-		void Projection3D::changeColorMap()
-		{
-		}
-
-		/**
-		* Select 1 of the 6 axis-aligned orientations.
-		*/
-		void Projection3D::setViewDirection(const QString& input)
-		{
-			if (input.toUpper().compare("X+") == 0)
-			{
-				m_viewport.setViewToXPositive();
-			}
-			else if (input.toUpper().compare("X-") == 0)
-			{
-				m_viewport.setViewToXNegative();
-			}
-			else if (input.toUpper().compare("Y+") == 0)
-			{
-				m_viewport.setViewToYPositive();
-			}
-			else if (input.toUpper().compare("Y-") == 0)
-			{
-				m_viewport.setViewToYNegative();
-			}
-			else if (input.toUpper().compare("Z+") == 0)
-			{
-				m_viewport.setViewToZPositive();
-			}
-			else if (input.toUpper().compare("Z-") == 0)
-			{
-				m_viewport.setViewToZNegative();
-			}
-			updateView(false);
-		}
-
-		/**
-		* Toggle the 3D axes.
-		*/
-		void Projection3D::set3DAxesState(bool on)
-		{
-			m_drawAxes = on;
-		}
-
-		/**
-		* Toggle wireframe view.
-		*/
-		void Projection3D::setWireframe(bool on)
-		{
-			m_wireframe = on;
-		}
-
-		//-----------------------------------------------------------------------------
-		/** This seems to be called when the user has selected a rectangle
-		* using the mouse.
-		*
-		* @param dets :: returns a list of detector IDs selected.
-		*/
-		void Projection3D::getSelectedDetectors(QList<int>& dets)
-		{
-			dets.clear();
-			if (!hasSelection()) return;
-			double xmin, xmax, ymin, ymax, zmin, zmax;
-			m_viewport.getInstantProjection(xmin, xmax, ymin, ymax, zmin, zmax);
-			QRect rect = selectionRect();
-			int w, h;
-			m_viewport.getViewport(w, h);
-
-			double xLeft = xmin + (xmax - xmin) * rect.left() / w;
-			double xRight = xmin + (xmax - xmin) * rect.right() / w;
-			double yBottom = ymin + (ymax - ymin) * (h - rect.bottom()) / h;
-			double yTop = ymin + (ymax - ymin) * (h - rect.top()) / h;
-			size_t ndet = m_instrActor->ndetectors();
-
-			// Cache all the detector positions if needed. This is slow, but just once.
-			m_instrActor->cacheDetPos();
-
-			for (size_t i = 0; i < ndet; ++i)
-			{
-				detid_t detId = m_instrActor->getDetID(i);
-				V3D pos = m_instrActor->getDetPos(i);
-				m_viewport.transform(pos);
-				if (pos.X() >= xLeft && pos.X() <= xRight &&
-					pos.Y() >= yBottom && pos.Y() <= yTop)
-				{
-					dets.push_back(detId);
-				}
-			}
-		}
-
-		//-----------------------------------------------------------------------------
-		/** Select detectors to mask, using the mouse.
-		* From the Instrument Window's mask tab.
-		*
-		* @param dets :: returns a list of detector IDs to mask.
-		*/
-		void Projection3D::getMaskedDetectors(QList<int>& dets)const
-		{
-			// Cache all the detector positions if needed. This is slow, but just once.
-			m_instrActor->cacheDetPos();
-
-			// find the layer of visible detectors
-			QList<QPoint> pixels = m_maskShapes.getMaskedPixels();
-			double zmin = 1.0;
-			double zmax = 0.0;
-			QSet<int> ids;
-			foreach(const QPoint& p, pixels)
-			{
-				int id = getDetectorID(p.x(), p.y());
-				if (ids.contains(id)) continue;
-				ids.insert(id);
-				V3D pos = this->getDetectorPos(p.x(), p.y());
-				m_viewport.transform(pos);
-				double z = pos.Z();
-				if (zmin > zmax)
-				{
-					zmin = zmax = z;
-				}
-				else
-				{
-					if (zmin > z) zmin = z;
-					if (zmax < z) zmax = z;
-				}
-			}
-
-			// find masked detector in that layer
-			dets.clear();
-			if (m_maskShapes.isEmpty()) return;
-			size_t ndet = m_instrActor->ndetectors();
-			for (size_t i = 0; i < ndet; ++i)
-			{
-				// Find the cached ID and position. This is much faster than getting the detector.
-				V3D pos = m_instrActor->getDetPos(i);
-				detid_t id = m_instrActor->getDetID(i);
-				// project pos onto the screen plane
-				m_viewport.transform(pos);
-				if (pos.Z() < zmin || pos.Z() > zmax) continue;
-				if (m_maskShapes.isMasked(pos.X(), pos.Y()))
-				{
-					dets.push_back(int(id));
-				}
-			}
-		}
-
-		/**
-		* Orient the viewport to look at a selected component.
-		* @param id :: The ID of a selected component.
-		*/
-		void Projection3D::componentSelected(Mantid::Geometry::ComponentID id)
-		{
-
-			Instrument_const_sptr instr = m_instrActor->getInstrument();
-
-			if (id == NULL || id == instr->getComponentID())
-			{
-				m_viewport.reset();
-				return;
-			}
-
-			IComponent_const_sptr comp = instr->getComponentByID(id);
-			V3D pos = comp->getPos();
-
-			V3D compDir = comp->getPos() - instr->getSample()->getPos();
-			compDir.normalize();
-			V3D up(0, 0, 1);
-			V3D x = up.cross_prod(compDir);
-			up = compDir.cross_prod(x);
-			Quat rot;
-			InstrumentActor::BasisRotation(
-				x, up, compDir, V3D(-1, 0, 0), V3D(0, 1, 0), V3D(0, 0, -1), rot);
-
-			rot.rotate(pos);
-			m_viewport.setTranslation(-pos.X(), -pos.Y());
-			m_viewport.setRotation(rot);
-
-		}
-
-		/**
-		* Return information text to be displayed in the InstrumentWindow's info area.
-		*/
-		QString Projection3D::getInfoText()const
-		{
-			if (m_interactionMode == MoveMode)
-			{
-				QString text = "Mouse Buttons: Left -- Rotation, Middle -- Zoom, Right -- Translate.";
-				if (m_drawAxes)
-				{
-					text += " Axes: X = Red; Y = Green; Z = Blue";
-				}
-				return text;
-			}
-			return ProjectionSurface::getInfoText();
-		}
-
-		/**
-		* Initialize translation movement at point on the screen.
-		* @param x :: The x screen coord clicked with the mouse to start translation.
-		* @param y :: The y screen coord clicked with the mouse to start translation.
-		*/
-		void Projection3D::initTranslation(int x, int y)
-		{
-			m_viewport.initTranslateFrom(x, y);
-		}
-
-		/**
-		* Translate the view in the surface.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		*/
-		void Projection3D::translate(int x, int y)
-		{
-			m_viewport.generateTranslationTo(x, y);
-			m_viewport.initTranslateFrom(x, y);
-			updateView(false);
-		}
-
-		/**
-		* Initialize zooming at point on the screen.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		*/
-		void Projection3D::initZoom(int x, int y)
-		{
-			m_viewport.initZoomFrom(x, y);
-		}
-
-		/**
-		* Zoom the view in the surface.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		*/
-		void Projection3D::zoom(int x, int y)
-		{
-			m_viewport.generateZoomTo(x, y);
-			m_viewport.initZoomFrom(x, y);
-			updateView(false);
-			emit finishedMove();
-		}
-
-		/**
-		* Zoom the view in the surface using the mouse wheel.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		* @param d :: zoom factor to shift y screen coord.
-		*/
-		void Projection3D::wheelZoom(int x, int y, int d)
-		{
-			m_viewport.wheelZoom(x, y, d);
-			updateView(false);
-			emit finishedMove();
-		}
-
-		/**
-		* Initialize rotation movement at point on the screen.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		*/
-		void Projection3D::initRotation(int x, int y)
-		{
-			m_viewport.initRotationFrom(x, y);
-		}
-
-		/**
-		* Rotate the view in the surface.
-		* @param x :: The x screen coord of the mouse pointer.
-		* @param y :: The y screen coord of the mouse pointer.
-		*/
-		void Projection3D::rotate(int x, int y)
-		{
-			m_viewport.generateRotationTo(x, y);
-			m_viewport.initRotationFrom(x, y);
-			updateView(false);
-		}
-
-		/**
-		* Call upon finishing all moves to update the pick image.
-		*/
-		void Projection3D::finishMove()
-		{
-			updateView(true);
-			emit finishedMove();
-		}
-
-		/**
-		* Get bounds of this projection surface. Used with 2D overlays.
-		*/
-		RectF Projection3D::getSurfaceBounds()const
-		{
-			double xmin, xmax, ymin, ymax, zmin, zmax;
-			m_viewport.getInstantProjection(xmin, xmax, ymin, ymax, zmin, zmax);
-			return RectF(QPointF(xmin, ymin), QPointF(xmax, ymax));
-		}
-
-		/**
-		* Define lighting of the scene
-		*/
-		void Projection3D::setLightingModel(bool picking) const
-		{
-			// Basic lighting
-			if (m_isLightingOn && !picking)
-			{
-				glShadeModel(GL_SMOOTH);           // Shade model is smooth (expensive but looks pleasing)
-				glEnable(GL_LINE_SMOOTH);          // Set line should be drawn smoothly
-				glEnable(GL_NORMALIZE);            // Slow normal normalization
-				glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);  // This model lits both sides of the triangle
-
-				const float lamp0_intensity = 0.3f;
-				const float lamp1_intensity = 0.7f;
-
-				// First light source - spot light at the origin
-				glEnable(GL_LIGHT0);               // Enable opengl first light
-				float lamp0_diffuse[4] = { lamp0_intensity, lamp0_intensity, lamp0_intensity, 1.0f };
-				float lamp0_ambient[4] = { 0.1f, 0.1f, 0.1f, 1.0f };
-				glLightfv(GL_LIGHT0, GL_DIFFUSE, lamp0_diffuse);
-				glLightfv(GL_LIGHT0, GL_AMBIENT, lamp0_ambient);
-				float lamp0_pos[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
-				glLightfv(GL_LIGHT0, GL_POSITION, lamp0_pos);
-
-				// Second light source
-				// Its a directional light which follows camera position
-				glEnable(GL_LIGHT1);               // Enable opengl second light
-				float lamp1_diffuse[4] = { lamp1_intensity, lamp1_intensity, lamp1_intensity, 1.0f };
-				glLightfv(GL_LIGHT1, GL_DIFFUSE, lamp1_diffuse);
-
-				glEnable(GL_LIGHTING);            // Enable overall lighting
-			}
-			else
-			{
-				glShadeModel(GL_FLAT);
-				glDisable(GL_LIGHTING);
-				glDisable(GL_LIGHT0);
-				glDisable(GL_LIGHT1);
-				glDisable(GL_LINE_SMOOTH);
-				glDisable(GL_NORMALIZE);
-			}
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+Projection3D::Projection3D(const InstrumentActor *rootActor, int winWidth,
+                           int winHeight)
+    : ProjectionSurface(rootActor), m_drawAxes(true), m_wireframe(false),
+      m_viewport(0, 0) {
+
+  Instrument_const_sptr instr = rootActor->getInstrument();
+
+  m_viewport.resize(winWidth, winHeight);
+  V3D minBounds, maxBounds;
+  m_instrActor->getBoundingBox(minBounds, maxBounds);
+
+  m_viewport.setProjection(minBounds, maxBounds);
+
+  changeColorMap();
+  rootActor->invalidateDisplayLists();
+
+  // create and connect the move input controller
+  InputController3DMove *moveController = new InputController3DMove(this);
+  setInputController(MoveMode, moveController);
+  connect(moveController, SIGNAL(initTranslation(int, int)), this,
+          SLOT(initTranslation(int, int)));
+  connect(moveController, SIGNAL(translate(int, int)), this,
+          SLOT(translate(int, int)));
+  connect(moveController, SIGNAL(initRotation(int, int)), this,
+          SLOT(initRotation(int, int)));
+  connect(moveController, SIGNAL(rotate(int, int)), this,
+          SLOT(rotate(int, int)));
+  connect(moveController, SIGNAL(initZoom(int, int)), this,
+          SLOT(initZoom(int, int)));
+  connect(moveController, SIGNAL(zoom(int, int)), this, SLOT(zoom(int, int)));
+  connect(moveController, SIGNAL(wheelZoom(int, int, int)), this,
+          SLOT(wheelZoom(int, int, int)));
+  connect(moveController, SIGNAL(finish()), this, SLOT(finishMove()));
+}
+
+Projection3D::~Projection3D() {}
+
+/**
+* Resize the surface on the screen.
+* @param w :: New width of the surface in pixels.
+* @param h :: New height of the surface in pixels.
+*/
+void Projection3D::resize(int w, int h) {
+  m_viewport.resize(w, h);
+  updateView();
+}
+
+/**
+* Draw the instrument on MantidGLWidget.
+*/
+void Projection3D::drawSurface(MantidGLWidget *, bool picking) const {
+  OpenGLError::check("GL3DWidget::draw3D()[begin]");
+
+  glEnable(GL_DEPTH_TEST);
+  OpenGLError::check("GL3DWidget::draw3D()[depth] ");
+
+  if (m_wireframe) {
+    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+  } else {
+    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+  }
+
+  setLightingModel(picking);
+
+  // fill the buffer with background colour
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+  m_viewport.applyProjection();
+
+  // Issue the rotation, translation and zooming of the trackball to the object
+  m_viewport.applyRotation();
+
+  // if actor is undefined leave it with clear screen
+  if (m_instrActor) {
+    QApplication::setOverrideCursor(Qt::WaitCursor);
+    m_instrActor->draw(picking);
+    OpenGLError::check("GL3DWidget::draw3D()[scene draw] ");
+    QApplication::restoreOverrideCursor();
+  }
+
+  // Also some axes
+  if (m_drawAxes && !picking) {
+    // This draws a point at the origin, I guess
+    glPointSize(3.0);
+    glBegin(GL_POINTS);
+    glVertex3d(0.0, 0.0, 0.0);
+    glEnd();
+
+    drawAxes();
+  }
+
+  OpenGLError::check("GL3DWidget::draw3D()");
+}
+
+/** Draw 3D axes centered at the origin (if the option is selected)
+*
+*/
+void Projection3D::drawAxes(double axis_length) const {
+  glPointSize(3.0);
+  glLineWidth(3.0);
+
+  // To make sure the lines are colored
+  glEnable(GL_COLOR_MATERIAL);
+  glDisable(GL_TEXTURE_2D);
+  glDisable(GL_LIGHTING);
+  glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
+
+  glColor3f(1.0, 0., 0.);
+  glBegin(GL_LINES);
+  glVertex3d(0.0, 0.0, 0.0);
+  glVertex3d(axis_length, 0.0, 0.0);
+  glEnd();
+
+  glColor3f(0., 1.0, 0.);
+  glBegin(GL_LINES);
+  glVertex3d(0.0, 0.0, 0.0);
+  glVertex3d(0.0, axis_length, 0.0);
+  glEnd();
+
+  glColor3f(0., 0., 1.);
+  glBegin(GL_LINES);
+  glVertex3d(0.0, 0.0, 0.0);
+  glVertex3d(0.0, 0.0, axis_length);
+  glEnd();
+}
+
+void Projection3D::changeColorMap() {}
+
+/**
+* Select 1 of the 6 axis-aligned orientations.
+*/
+void Projection3D::setViewDirection(const QString &input) {
+  if (input.toUpper().compare("X+") == 0) {
+    m_viewport.setViewToXPositive();
+  } else if (input.toUpper().compare("X-") == 0) {
+    m_viewport.setViewToXNegative();
+  } else if (input.toUpper().compare("Y+") == 0) {
+    m_viewport.setViewToYPositive();
+  } else if (input.toUpper().compare("Y-") == 0) {
+    m_viewport.setViewToYNegative();
+  } else if (input.toUpper().compare("Z+") == 0) {
+    m_viewport.setViewToZPositive();
+  } else if (input.toUpper().compare("Z-") == 0) {
+    m_viewport.setViewToZNegative();
+  }
+  updateView(false);
+}
+
+/**
+* Toggle the 3D axes.
+*/
+void Projection3D::set3DAxesState(bool on) { m_drawAxes = on; }
+
+/**
+* Toggle wireframe view.
+*/
+void Projection3D::setWireframe(bool on) { m_wireframe = on; }
+
+//-----------------------------------------------------------------------------
+/** This seems to be called when the user has selected a rectangle
+* using the mouse.
+*
+* @param dets :: returns a list of detector IDs selected.
+*/
+void Projection3D::getSelectedDetectors(QList<int> &dets) {
+  dets.clear();
+  if (!hasSelection())
+    return;
+  double xmin, xmax, ymin, ymax, zmin, zmax;
+  m_viewport.getInstantProjection(xmin, xmax, ymin, ymax, zmin, zmax);
+  QRect rect = selectionRect();
+  int w, h;
+  m_viewport.getViewport(w, h);
+
+  double xLeft = xmin + (xmax - xmin) * rect.left() / w;
+  double xRight = xmin + (xmax - xmin) * rect.right() / w;
+  double yBottom = ymin + (ymax - ymin) * (h - rect.bottom()) / h;
+  double yTop = ymin + (ymax - ymin) * (h - rect.top()) / h;
+  size_t ndet = m_instrActor->ndetectors();
+
+  // Cache all the detector positions if needed. This is slow, but just once.
+  m_instrActor->cacheDetPos();
+
+  for (size_t i = 0; i < ndet; ++i) {
+    detid_t detId = m_instrActor->getDetID(i);
+    V3D pos = m_instrActor->getDetPos(i);
+    m_viewport.transform(pos);
+    if (pos.X() >= xLeft && pos.X() <= xRight && pos.Y() >= yBottom &&
+        pos.Y() <= yTop) {
+      dets.push_back(detId);
+    }
+  }
+}
+
+//-----------------------------------------------------------------------------
+/** Select detectors to mask, using the mouse.
+* From the Instrument Window's mask tab.
+*
+* @param dets :: returns a list of detector IDs to mask.
+*/
+void Projection3D::getMaskedDetectors(QList<int> &dets) const {
+  // Cache all the detector positions if needed. This is slow, but just once.
+  m_instrActor->cacheDetPos();
+
+  // find the layer of visible detectors
+  QList<QPoint> pixels = m_maskShapes.getMaskedPixels();
+  double zmin = 1.0;
+  double zmax = 0.0;
+  QSet<int> ids;
+  foreach (const QPoint &p, pixels) {
+    int id = getDetectorID(p.x(), p.y());
+    if (ids.contains(id))
+      continue;
+    ids.insert(id);
+    V3D pos = this->getDetectorPos(p.x(), p.y());
+    m_viewport.transform(pos);
+    double z = pos.Z();
+    if (zmin > zmax) {
+      zmin = zmax = z;
+    } else {
+      if (zmin > z)
+        zmin = z;
+      if (zmax < z)
+        zmax = z;
+    }
+  }
+
+  // find masked detector in that layer
+  dets.clear();
+  if (m_maskShapes.isEmpty())
+    return;
+  size_t ndet = m_instrActor->ndetectors();
+  for (size_t i = 0; i < ndet; ++i) {
+    // Find the cached ID and position. This is much faster than getting the
+    // detector.
+    V3D pos = m_instrActor->getDetPos(i);
+    detid_t id = m_instrActor->getDetID(i);
+    // project pos onto the screen plane
+    m_viewport.transform(pos);
+    if (pos.Z() < zmin || pos.Z() > zmax)
+      continue;
+    if (m_maskShapes.isMasked(pos.X(), pos.Y())) {
+      dets.push_back(int(id));
+    }
+  }
+}
+
+/**
+* Orient the viewport to look at a selected component.
+* @param id :: The ID of a selected component.
+*/
+void Projection3D::componentSelected(Mantid::Geometry::ComponentID id) {
+
+  Instrument_const_sptr instr = m_instrActor->getInstrument();
+
+  if (id == NULL || id == instr->getComponentID()) {
+    m_viewport.reset();
+    return;
+  }
+
+  IComponent_const_sptr comp = instr->getComponentByID(id);
+  V3D pos = comp->getPos();
+
+  V3D compDir = comp->getPos() - instr->getSample()->getPos();
+  compDir.normalize();
+  V3D up(0, 0, 1);
+  V3D x = up.cross_prod(compDir);
+  up = compDir.cross_prod(x);
+  Quat rot;
+  InstrumentActor::BasisRotation(x, up, compDir, V3D(-1, 0, 0), V3D(0, 1, 0),
+                                 V3D(0, 0, -1), rot);
+
+  rot.rotate(pos);
+  m_viewport.setTranslation(-pos.X(), -pos.Y());
+  m_viewport.setRotation(rot);
+}
+
+/**
+* Return information text to be displayed in the InstrumentWindow's info area.
+*/
+QString Projection3D::getInfoText() const {
+  if (m_interactionMode == MoveMode) {
+    QString text =
+        "Mouse Buttons: Left -- Rotation, Middle -- Zoom, Right -- Translate.";
+    if (m_drawAxes) {
+      text += " Axes: X = Red; Y = Green; Z = Blue";
+    }
+    return text;
+  }
+  return ProjectionSurface::getInfoText();
+}
+
+/**
+* Initialize translation movement at point on the screen.
+* @param x :: The x screen coord clicked with the mouse to start translation.
+* @param y :: The y screen coord clicked with the mouse to start translation.
+*/
+void Projection3D::initTranslation(int x, int y) {
+  m_viewport.initTranslateFrom(x, y);
+}
+
+/**
+* Translate the view in the surface.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+*/
+void Projection3D::translate(int x, int y) {
+  m_viewport.generateTranslationTo(x, y);
+  m_viewport.initTranslateFrom(x, y);
+  updateView(false);
+}
+
+/**
+* Initialize zooming at point on the screen.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+*/
+void Projection3D::initZoom(int x, int y) { m_viewport.initZoomFrom(x, y); }
+
+/**
+* Zoom the view in the surface.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+*/
+void Projection3D::zoom(int x, int y) {
+  m_viewport.generateZoomTo(x, y);
+  m_viewport.initZoomFrom(x, y);
+  updateView(false);
+  emit finishedMove();
+}
+
+/**
+* Zoom the view in the surface using the mouse wheel.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+* @param d :: zoom factor to shift y screen coord.
+*/
+void Projection3D::wheelZoom(int x, int y, int d) {
+  m_viewport.wheelZoom(x, y, d);
+  updateView(false);
+  emit finishedMove();
+}
+
+/**
+* Initialize rotation movement at point on the screen.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+*/
+void Projection3D::initRotation(int x, int y) {
+  m_viewport.initRotationFrom(x, y);
+}
+
+/**
+* Rotate the view in the surface.
+* @param x :: The x screen coord of the mouse pointer.
+* @param y :: The y screen coord of the mouse pointer.
+*/
+void Projection3D::rotate(int x, int y) {
+  m_viewport.generateRotationTo(x, y);
+  m_viewport.initRotationFrom(x, y);
+  updateView(false);
+}
+
+/**
+* Call upon finishing all moves to update the pick image.
+*/
+void Projection3D::finishMove() {
+  updateView(true);
+  emit finishedMove();
+}
+
+/**
+* Get bounds of this projection surface. Used with 2D overlays.
+*/
+RectF Projection3D::getSurfaceBounds() const {
+  double xmin, xmax, ymin, ymax, zmin, zmax;
+  m_viewport.getInstantProjection(xmin, xmax, ymin, ymax, zmin, zmax);
+  return RectF(QPointF(xmin, ymin), QPointF(xmax, ymax));
+}
+
+/**
+* Define lighting of the scene
+*/
+void Projection3D::setLightingModel(bool picking) const {
+  // Basic lighting
+  if (m_isLightingOn && !picking) {
+    glShadeModel(
+        GL_SMOOTH); // Shade model is smooth (expensive but looks pleasing)
+    glEnable(GL_LINE_SMOOTH); // Set line should be drawn smoothly
+    glEnable(GL_NORMALIZE);   // Slow normal normalization
+    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,
+                  GL_TRUE); // This model lits both sides of the triangle
+
+    const float lamp0_intensity = 0.3f;
+    const float lamp1_intensity = 0.7f;
+
+    // First light source - spot light at the origin
+    glEnable(GL_LIGHT0); // Enable opengl first light
+    float lamp0_diffuse[4] = {lamp0_intensity, lamp0_intensity, lamp0_intensity,
+                              1.0f};
+    float lamp0_ambient[4] = {0.1f, 0.1f, 0.1f, 1.0f};
+    glLightfv(GL_LIGHT0, GL_DIFFUSE, lamp0_diffuse);
+    glLightfv(GL_LIGHT0, GL_AMBIENT, lamp0_ambient);
+    float lamp0_pos[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+    glLightfv(GL_LIGHT0, GL_POSITION, lamp0_pos);
+
+    // Second light source
+    // Its a directional light which follows camera position
+    glEnable(GL_LIGHT1); // Enable opengl second light
+    float lamp1_diffuse[4] = {lamp1_intensity, lamp1_intensity, lamp1_intensity,
+                              1.0f};
+    glLightfv(GL_LIGHT1, GL_DIFFUSE, lamp1_diffuse);
+
+    glEnable(GL_LIGHTING); // Enable overall lighting
+  } else {
+    glShadeModel(GL_FLAT);
+    glDisable(GL_LIGHTING);
+    glDisable(GL_LIGHT0);
+    glDisable(GL_LIGHT1);
+    glDisable(GL_LINE_SMOOTH);
+    glDisable(GL_NORMALIZE);
+  }
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/ProjectionSurface.cpp b/MantidQt/MantidWidgets/src/InstrumentView/ProjectionSurface.cpp
index 0c76394451f07bceea180d1b510cdfb9f629d556..405fb43d0eab002de69ac64c647b0c3e56530386 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/ProjectionSurface.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/ProjectionSurface.cpp
@@ -26,756 +26,695 @@
 
 using Mantid::Kernel::V3D;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* The constructor.
-		* @param rootActor :: The instrument actor containing all info about the instrument
-		*/
-		ProjectionSurface::ProjectionSurface(const InstrumentActor *rootActor)
-			: m_instrActor(rootActor), m_viewImage(NULL), m_pickImage(NULL),
-			m_viewRect(), m_selectRect(), m_interactionMode(MoveMode),
-			m_isLightingOn(false), m_peakLabelPrecision(2), m_showPeakRows(false),
-			m_showPeakLabels(false), m_showPeakRelativeIntensity(false),
-			m_peakShapesStyle(0), m_viewChanged(true), m_redrawPicking(true) {
-			connect(rootActor, SIGNAL(colorMapChanged()), this, SLOT(colorMapChanged()));
-			connect(&m_maskShapes, SIGNAL(shapeCreated()), this, SIGNAL(shapeCreated()));
-			connect(&m_maskShapes, SIGNAL(shapeSelected()), this, SIGNAL(shapeSelected()));
-			connect(&m_maskShapes, SIGNAL(shapesDeselected()), this, SIGNAL(shapesDeselected()));
-			connect(&m_maskShapes, SIGNAL(shapesRemoved()), this, SIGNAL(shapesRemoved()));
-			connect(&m_maskShapes, SIGNAL(shapeChanged()), this, SIGNAL(shapeChanged()));
-			connect(&m_maskShapes, SIGNAL(cleared()), this, SIGNAL(shapesCleared()));
-
-			// create and connect the pick input controller
-			InputControllerPick* pickController = new InputControllerPick(this);
-			setInputController(PickSingleMode, pickController);
-			setInputController(PickTubeMode, pickController);
-			setInputController(AddPeakMode, pickController);
-			connect(pickController, SIGNAL(pickPointAt(int, int)), this, SLOT(pickComponentAt(int, int)));
-			connect(pickController, SIGNAL(touchPointAt(int, int)), this, SLOT(touchComponentAt(int, int)));
-
-			// create and connect the mask drawing input controller
-			InputControllerDrawShape* drawController = new InputControllerDrawShape(this);
-			setInputController(DrawRegularMode, drawController);
-			connect(drawController, SIGNAL(addShape(QString, int, int, QColor, QColor)), &m_maskShapes, SLOT(addShape(QString, int, int, QColor, QColor)));
-			connect(this, SIGNAL(signalToStartCreatingShape2D(QString, QColor, QColor)), drawController, SLOT(startCreatingShape2D(QString, QColor, QColor)));
-			connect(drawController, SIGNAL(moveRightBottomTo(int, int)), &m_maskShapes, SLOT(moveRightBottomTo(int, int)));
-			connect(drawController, SIGNAL(selectAt(int, int)), &m_maskShapes, SLOT(selectShapeOrControlPointAt(int, int)));
-			connect(drawController, SIGNAL(selectCtrlAt(int, int)), &m_maskShapes, SLOT(addToSelectionShapeAt(int, int)));
-			connect(drawController, SIGNAL(moveBy(int, int)), &m_maskShapes, SLOT(moveShapeOrControlPointBy(int, int)));
-			connect(drawController, SIGNAL(touchPointAt(int, int)), &m_maskShapes, SLOT(touchShapeOrControlPointAt(int, int)));
-			connect(drawController, SIGNAL(removeSelectedShapes()), &m_maskShapes, SLOT(removeSelectedShapes()));
-			connect(drawController, SIGNAL(deselectAll()), &m_maskShapes, SLOT(deselectAll()));
-			connect(drawController, SIGNAL(restoreOverrideCursor()), &m_maskShapes, SLOT(restoreOverrideCursor()));
-			connect(drawController, SIGNAL(setSelection(QRect)), this, SLOT(setSelectionRect(QRect)));
-			connect(drawController, SIGNAL(finishSelection(QRect)), this, SLOT(selectMultipleMasks(QRect)));
-			connect(drawController, SIGNAL(finishSelection(QRect)), this, SIGNAL(shapeChangeFinished()));
-
-			InputControllerDrawAndErase* freeDrawController = new InputControllerDrawAndErase(this);
-			setInputController(DrawFreeMode, freeDrawController);
-			connect(this, SIGNAL(signalToStartCreatingFreeShape(QColor, QColor)), freeDrawController, SLOT(startCreatingShape2D(QColor, QColor)));
-			connect(freeDrawController, SIGNAL(addShape(const QPolygonF&, QColor, QColor)), &m_maskShapes, SLOT(addFreeShape(const QPolygonF&, QColor, QColor)));
-			connect(freeDrawController, SIGNAL(draw(const QPolygonF&)), &m_maskShapes, SLOT(drawFree(const QPolygonF&)));
-			connect(freeDrawController, SIGNAL(erase(const QPolygonF&)), &m_maskShapes, SLOT(eraseFree(const QPolygonF&)));
-
-			// create and connect the peak eraser controller
-			InputControllerErase* eraseController = new InputControllerErase(this);
-			setInputController(ErasePeakMode, eraseController);
-			connect(eraseController, SIGNAL(erase(QRect)), this, SLOT(erasePeaks(QRect)));
-		}
-
-		ProjectionSurface::~ProjectionSurface()
-		{
-			if (m_viewImage)
-			{
-				delete m_viewImage;
-			}
-			if (m_pickImage)
-			{
-				delete m_pickImage;
-			}
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				if (m_peakShapes[i]) delete m_peakShapes[i];
-			}
-			m_peakShapes.clear();
-		}
-
-		/**
-		* Resets the instrument actor. The caller must ensure that the instrument
-		* stays the same and workspace dimensions also don't change.
-		*/
-		void ProjectionSurface::resetInstrumentActor(const InstrumentActor* rootActor)
-		{
-			m_instrActor = rootActor;
-			connect(rootActor, SIGNAL(colorMapChanged()), this, SLOT(colorMapChanged()));
-		}
-
-		void ProjectionSurface::clear()
-		{
-			if (m_viewImage)
-			{
-				delete m_viewImage;
-				m_viewImage = NULL;
-			}
-			if (m_pickImage)
-			{
-				delete m_pickImage;
-				m_pickImage = NULL;
-			}
-			m_viewChanged = true;
-			m_redrawPicking = true;
-			m_viewRect = RectF();
-			m_selectRect = QRect();
-		}
-
-		/**
-		* Draw the surface on an OpenGL widget
-		* @param widget :: A widget to draw on.
-		*/
-		void ProjectionSurface::draw(MantidGLWidget *widget)const
-		{
-			if (m_viewChanged && (m_redrawPicking
-				|| m_interactionMode == PickSingleMode
-				|| m_interactionMode == PickTubeMode
-				|| m_interactionMode == DrawRegularMode))
-			{
-				draw(widget, true);
-				m_redrawPicking = false;
-			}
-			draw(widget, false);
-			if (m_viewChanged)
-			{
-				m_viewChanged = false;
-			}
-		}
-
-		/**
-		* Draw the surface on an OpenGL widget.
-		* @param widget :: A widget to draw on.
-		* @param picking :: Picking / normal drawing switch.
-		*/
-		void ProjectionSurface::draw(MantidGLWidget *widget, bool picking)const
-		{
-			QImage **image = picking ? &m_pickImage : &m_viewImage;
-
-			if (!*image || (*image)->width() != widget->width() || (*image)->height() != widget->height())
-			{
-				m_viewChanged = true;
-			}
-
-			if (m_viewChanged)
-			{
-
-				this->drawSurface(widget, picking);
-
-				if (*image)
-				{
-					delete (*image);
-				}
-				(*image) = new QImage(widget->grabFrameBuffer());
-
-				if (!picking)
-				{
-					QPainter painter(widget);
-					RectF windowRect = getSurfaceBounds();
-					m_maskShapes.setWindow(windowRect, painter.viewport());
-					m_maskShapes.draw(painter);
-					for (int i = 0; i < m_peakShapes.size(); ++i)
-					{
-						m_peakShapes[i]->setWindow(windowRect, painter.viewport());
-						m_peakShapes[i]->draw(painter);
-					}
-					painter.end();
-				}
-			}
-			else if (!picking)
-			{
-				QPainter painter(widget);
-				painter.drawImage(0, 0, **image);
-
-				RectF windowRect = getSurfaceBounds();
-				m_maskShapes.setWindow(windowRect, painter.viewport());
-				m_maskShapes.draw(painter);
-
-				for (int i = 0; i < m_peakShapes.size(); ++i)
-				{
-					m_peakShapes[i]->setWindow(windowRect, painter.viewport());
-					m_peakShapes[i]->draw(painter);
-				}
-
-				// draw the selection rectangle
-				if (!m_selectRect.isNull())
-				{
-					painter.setPen(Qt::blue);
-					//painter.setCompositionMode(QPainter::CompositionMode_Xor);
-					painter.drawRect(m_selectRect);
-				}
-				getController()->onPaint(painter);
-				painter.end();
-				// Discard any error generated here
-				GLuint ecode = glGetError();
-				OpenGLError::logDebug() << "Discarding OpenGL error: " << gluErrorString(ecode);
-			}
-
-		}
-
-		/**
-		* Draw the surface onto a normal widget without OpenGL
-		* @param widget :: A widget to draw on.
-		*/
-		void ProjectionSurface::drawSimple(QWidget* widget)const
-		{
-			if (m_viewChanged)
-			{
-				if (!m_viewImage || m_viewImage->width() != widget->width() || m_viewImage->height() != widget->height())
-				{
-					if (m_viewImage) delete m_viewImage;
-					m_viewImage = new QImage(widget->width(), widget->height(), QImage::Format_RGB32);
-					if (m_pickImage) delete m_pickImage;
-					m_pickImage = new QImage(widget->width(), widget->height(), QImage::Format_RGB32);
-				}
-
-				if (m_redrawPicking || m_interactionMode == PickSingleMode || m_interactionMode == PickTubeMode)
-				{
-					drawSimpleToImage(m_pickImage, true);
-					m_redrawPicking = false;
-				}
-				drawSimpleToImage(m_viewImage, false);
-				m_viewChanged = false;
-			}
-
-			QPainter painter(widget);
-			painter.drawImage(0, 0, *m_viewImage);
-
-			RectF windowRect = getSurfaceBounds();
-			m_maskShapes.setWindow(windowRect, painter.viewport());
-			m_maskShapes.draw(painter);
-
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				m_peakShapes[i]->setWindow(windowRect, painter.viewport());
-				m_peakShapes[i]->draw(painter);
-			}
-
-			// draw the selection rectangle
-			if (!m_selectRect.isNull())
-			{
-				painter.setPen(Qt::blue);
-				//painter.setCompositionMode(QPainter::CompositionMode_Xor);
-				painter.drawRect(m_selectRect);
-			}
-			getController()->onPaint(painter);
-			painter.end();
-		}
-
-		void ProjectionSurface::resize(int, int)
-		{
-			updateView();
-		}
-
-		/**
-		* Draw the surface onto an image without OpenGL
-		* @param image :: Image to draw on.
-		* @param picking :: If true draw a picking image.
-		*/
-		void ProjectionSurface::drawSimpleToImage(QImage*, bool)const
-		{
-		}
-
-		void ProjectionSurface::mousePressEvent(QMouseEvent* e)
-		{
-			getController()->mousePressEvent(e);
-		}
-
-		void ProjectionSurface::mouseMoveEvent(QMouseEvent* e)
-		{
-			getController()->mouseMoveEvent(e);
-		}
-
-		void ProjectionSurface::mouseReleaseEvent(QMouseEvent* e)
-		{
-			getController()->mouseReleaseEvent(e);
-		}
-
-		void ProjectionSurface::wheelEvent(QWheelEvent* e)
-		{
-			getController()->wheelEvent(e);
-		}
-
-		void ProjectionSurface::keyPressEvent(QKeyEvent* e)
-		{
-			getController()->keyPressEvent(e);
-		}
-
-		void ProjectionSurface::enterEvent(QEvent *e)
-		{
-			getController()->enterEvent(e);
-		}
-
-		void ProjectionSurface::leaveEvent(QEvent *e)
-		{
-			getController()->leaveEvent(e);
-		}
-
-		/**
-		* Update the view of the surface at the next redraw.
-		* @param picking :: Set to true to update the picking image regardless the interaction
-		*   mode of the surface.
-		*/
-		void ProjectionSurface::updateView(bool picking)
-		{
-			m_viewChanged = true;
-			if (picking)
-			{
-				// don't change to false if it's already true
-				m_redrawPicking = true;
-			}
-		}
-
-		void ProjectionSurface::updateDetectors()
-		{
-			clear();
-			this->init();
-			// if integration range in the instrument actor has changed
-			// update visiblity of peak markers
-			setPeakVisibility();
-		}
-
-		/// Send a redraw request to the surface owner
-		void ProjectionSurface::requestRedraw(bool resetPeakVisibility)
-		{
-			if (resetPeakVisibility)
-			{
-				setPeakVisibility();
-			}
-			emit redrawRequired();
-		}
-
-		QRect ProjectionSurface::selectionRect()const
-		{
-			if (m_selectRect.width() <= 1 || m_selectRect.height() <= 1) return QRect();
-
-			int x_min = m_selectRect.left();
-			int x_size = m_selectRect.width();
-			int y_min = m_selectRect.top();
-			int y_size = m_selectRect.height();
-
-			if (x_size < 0)
-			{
-				x_min += x_size;
-				x_size = abs(x_size);
-			}
-
-			if (y_size < 0)
-			{
-				y_min += y_size;
-				y_size = abs(y_size);
-			}
-
-			return QRect(x_min, y_min, x_size, y_size);
-		}
-
-		RectF ProjectionSurface::selectionRectUV()const
-		{
-			double left = static_cast<double>(m_selectRect.left());
-			double right = static_cast<double>(m_selectRect.right());
-			double top = static_cast<double>(m_selectRect.top());
-			double bottom = static_cast<double>(m_selectRect.bottom());
-
-			if (left > right)
-			{
-				std::swap(left, right);
-			}
-
-			if (top > bottom)
-			{
-				std::swap(top, bottom);
-			}
-
-			if (abs(m_selectRect.width()) <= 1 || abs(m_selectRect.height()) <= 1) return RectF();
-
-			double sx = m_viewRect.xSpan() / m_viewImage->width();
-			double sy = m_viewRect.ySpan() / m_viewImage->height();
-
-			double x_min = left * sx + m_viewRect.x0();
-			double x_max = right * sx + m_viewRect.x0();
-			double y_min = (m_viewImage->height() - bottom) * sy + m_viewRect.y0();
-			double y_max = (m_viewImage->height() - top) * sy + m_viewRect.y0();
-
-			return RectF(QPointF(x_min, y_min), QPointF(x_max, y_max));
-		}
-
-		bool ProjectionSurface::hasSelection()const
-		{
-			return !m_selectRect.isNull() && m_selectRect.width() > 0;
-		}
-
-		void ProjectionSurface::colorMapChanged()
-		{
-			this->changeColorMap();
-			updateView(false);
-			requestRedraw();
-		}
-
-		/**
-		* Set an interaction mode for the surface.
-		* @param mode :: A new mode.
-		*/
-		void ProjectionSurface::setInteractionMode(int mode)
-		{
-			if (mode < 0 || mode >= m_inputControllers.size())
-			{
-				throw std::logic_error("Invalid interaction mode requested.");
-			}
-			if (mode == m_interactionMode) return;
-			InputController *controller = m_inputControllers[m_interactionMode];
-			if (!controller) throw std::logic_error("Input controller doesn't exist.");
-			controller->onDisabled();
-			m_interactionMode = mode;
-			controller = m_inputControllers[m_interactionMode];
-			if (!controller) throw std::logic_error("Input controller doesn't exist.");
-			controller->onEnabled();
-			if (mode != DrawRegularMode && mode != DrawFreeMode)
-			{
-				m_maskShapes.deselectAll();
-				foreach(PeakOverlay* po, m_peakShapes)
-				{
-					po->deselectAll();
-				}
-			}
-		}
-
-		/**
-		* Return detector id at image coordinats x,y if in pick mode. -1 otherwise
-		*/
-		int ProjectionSurface::getDetectorID(int x, int y)const
-		{
-			size_t pickID = getPickID(x, y);
-			return m_instrActor->getDetID(pickID);
-		}
-
-		//------------------------------------------------------------------------------
-		boost::shared_ptr<const Mantid::Geometry::IDetector> ProjectionSurface::getDetector(int x, int y)const
-		{
-			size_t pickID = getPickID(x, y);
-			return m_instrActor->getDetector(pickID);
-		}
-
-		/**
-		* Return info text for interactions common to all surfaces.
-		*/
-		QString ProjectionSurface::getInfoText() const
-		{
-			switch (m_interactionMode)
-			{
-			case PickSingleMode:
-			case PickTubeMode:
-				return "Move cursor over instrument to see detector information. ";
-			case AddPeakMode:
-				return "Click on a detector then click on the mini-plot to add a peak.";
-			case DrawRegularMode:
-				return "Select a tool button to draw a new shape. "
-					"Click on shapes to select. Click and move to edit.";
-			case DrawFreeMode:
-				return "Draw by holding the left button down. "
-					"Erase with the right button.";
-			case ErasePeakMode:
-				return "Click and move the mouse to erase peaks. "
-					"Rotate the wheel to resize the cursor.";
-			}
-			return "";
-		}
-
-		//------------------------------------------------------------------------------
-		/** Return the detector position (in real-space) at the pixel coordinates.
-		*
-		* @param x :: x pixel coordinate
-		* @param y :: y pixel coordinate
-		* @return V3D of the detector position
-		*/
-		Mantid::Kernel::V3D ProjectionSurface::getDetectorPos(int x, int y) const
-		{
-			size_t pickID = getPickID(x, y);
-			return m_instrActor->getDetPos(pickID);
-		}
-
-		/**
-		* Is context menu allowed?
-		*/
-		bool ProjectionSurface::canShowContextMenu() const
-		{
-			InputController *controller = m_inputControllers[m_interactionMode];
-			if (controller)
-			{
-				return controller->canShowContextMenu();
-			}
-			return false;
-		}
-
-		//------------------------------------------------------------------------------
-		size_t ProjectionSurface::getPickID(int x, int y)const
-		{
-			if (!m_pickImage || !m_pickImage->valid(x, y)) return -1;
-			QRgb pixel = m_pickImage->pixel(x, y);
-			return GLActor::decodePickColor(pixel);
-		}
-
-		/**
-		* Adds an input controller to the controller list.
-		* @param mode :: The interaction mode which is the index of the controller in the list.
-		* @param controller :: A pointer to the controller to be set.
-		*/
-		void ProjectionSurface::setInputController(int mode, InputController *controller)
-		{
-			m_inputControllers[mode] = controller;
-		}
-
-		/**
-		* Set visibility of the peak markers according to the integration range
-		* in the instrument actor.
-		*/
-		void ProjectionSurface::setPeakVisibility() const
-		{
-			if (hasPeakOverlays())
-			{
-				Mantid::Kernel::Unit_sptr unit = m_instrActor->getWorkspace()->getAxis(0)->unit();
-				QString unitID = QString::fromStdString(unit->unitID());
-				double xmin = m_instrActor->minBinValue();
-				double xmax = m_instrActor->maxBinValue();
-				foreach(PeakOverlay* po, m_peakShapes)
-				{
-					po->setPeakVisibility(xmin, xmax, unitID);
-				}
-			}
-		}
-
-		/**
-		* Returns the current controller. If the controller doesn't exist throws a logic_error exceotion.
-		*/
-		InputController *ProjectionSurface::getController() const
-		{
-			InputController* controller = m_inputControllers[m_interactionMode];
-			if (!controller)
-			{
-				throw std::logic_error("Input controller doesn't exist for current interaction mode.");
-			}
-			return controller;
-		}
-
-		// --- Shape2D manipulation --- //
-
-		void ProjectionSurface::startCreatingShape2D(const QString& type, const QColor& borderColor, const QColor& fillColor)
-		{
-			emit signalToStartCreatingShape2D(type, borderColor, fillColor);
-		}
-
-		void ProjectionSurface::startCreatingFreeShape(const QColor& borderColor, const QColor& fillColor)
-		{
-			emit signalToStartCreatingFreeShape(borderColor, fillColor);
-		}
-
-		/**
-		* Return a combined list of peak parkers from all overlays
-		* @param detID :: The detector ID of interest
-		*/
-		QList<PeakMarker2D*> ProjectionSurface::getMarkersWithID(int detID)const
-		{
-			QList<PeakMarker2D*> out;
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				out += m_peakShapes[i]->getMarkersWithID(detID);
-			}
-			return out;
-		}
-
-		/**
-		* Get peaks workspace for manually editing.
-		*/
-		boost::shared_ptr<Mantid::API::IPeaksWorkspace> ProjectionSurface::getEditPeaksWorkspace() const
-		{
-			if (!m_peakShapes.isEmpty())
-			{
-				return m_peakShapes.last()->getPeaksWorkspace();
-			}
-			return boost::shared_ptr<Mantid::API::IPeaksWorkspace>();
-		}
-
-		/**
-		* Remove an overlay if its peaks workspace is deleted.
-		* @param ws :: Shared pointer to the deleted peaks workspace.
-		*/
-		void ProjectionSurface::deletePeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> ws)
-		{
-			const int npeaks = m_peakShapes.size();
-			for (int i = 0; i < npeaks; ++i)
-			{
-				if (m_peakShapes[i]->getPeaksWorkspace() == ws)
-				{
-					delete m_peakShapes[i];
-					m_peakShapes.removeAt(i);
-					break;
-				}
-			}
-			if (m_peakShapes.size() < npeaks)
-			{
-				emit peaksWorkspaceDeleted();
-			}
-		}
-
-		/**
-		* Remove all peak overlays.
-		*/
-		void ProjectionSurface::clearPeakOverlays()
-		{
-			if (!m_peakShapes.isEmpty())
-			{
-				for (int i = 0; i < m_peakShapes.size(); ++i)
-				{
-					delete m_peakShapes[i];
-				}
-				m_peakShapes.clear();
-				m_peakShapesStyle = 0;
-				emit peaksWorkspaceDeleted();
-			}
-		}
-
-		/**
-		* Set the precision (significant digits) with which the HKL peak labels are displayed.
-		* @param n :: Precision, > 0
-		*/
-		void ProjectionSurface::setPeakLabelPrecision(int n)
-		{
-			if (n < 1)
-			{
-				QMessageBox::critical(NULL, "MantidPlot - Error", "Precision must be a positive number");
-				return;
-			}
-			m_peakLabelPrecision = n;
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				m_peakShapes[i]->setPrecision(n);
-			}
-		}
-
-		/**
-		* Enable or disable the show peak row flag
-		*/
-		void ProjectionSurface::setShowPeakRowsFlag(bool on)
-		{
-			m_showPeakRows = on;
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				m_peakShapes[i]->setShowRowsFlag(on);
-			}
-		}
-
-		/**
-		* Enable or disable the show peak label flag
-		*/
-		void ProjectionSurface::setShowPeakLabelsFlag(bool on)
-		{
-			m_showPeakLabels = on;
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				m_peakShapes[i]->setShowLabelsFlag(on);
-			}
-		}
-
-		/**
-		* Enable or disable the show peak label flag
-		*/
-		void ProjectionSurface::setShowPeakRelativeIntensityFlag(bool on)
-		{
-			m_showPeakRelativeIntensity = on;
-			for (int i = 0; i < m_peakShapes.size(); ++i)
-			{
-				m_peakShapes[i]->setShowRelativeIntensityFlag(on);
-			}
-		}
-
-		/**
-		* Set the selection rect in screen corrds.
-		* @param rect :: New selection rectangle.
-		*/
-		void ProjectionSurface::setSelectionRect(const QRect &rect)
-		{
-			if (m_interactionMode != DrawRegularMode || !m_maskShapes.hasSelection())
-			{
-				m_selectRect = rect;
-			}
-		}
-
-		/**
-		* Delete selection rectanle.
-		*/
-		void ProjectionSurface::emptySelectionRect()
-		{
-			m_selectRect = QRect();
-		}
-
-		/**
-		* Select multiple mask shapes as a result of a rubber-band selection
-		* @param rect :: The rubber band rect.
-		*/
-		void ProjectionSurface::selectMultipleMasks(const QRect &rect)
-		{
-			if (!m_maskShapes.hasSelection())
-			{
-				m_maskShapes.selectIn(rect);
-			}
-			emptySelectionRect();
-		}
-
-		/**
-		* Pick a detector at a pointe on the screen.
-		*/
-		void ProjectionSurface::pickComponentAt(int x, int y)
-		{
-			size_t pickID = getPickID(x, y);
-			emit singleComponentPicked(pickID);
-		}
-
-		void ProjectionSurface::touchComponentAt(int x, int y)
-		{
-			size_t pickID = getPickID(x, y);
-			emit singleComponentTouched(pickID);
-		}
-
-		void ProjectionSurface::erasePeaks(const QRect &rect)
-		{
-			foreach(PeakOverlay* po, m_peakShapes)
-			{
-				po->selectIn(rect);
-				po->removeSelectedShapes();
-			}
-
-		}
-
-		/**
-		* Enable or disable lighting in non-picking mode
-		* @param on :: True for enabling, false for disabling.
-		*/
-		void ProjectionSurface::enableLighting(bool on)
-		{
-			m_isLightingOn = on;
-		}
-
-		/**
-		* Return names of attached peaks workspaces.
-		*/
-		QStringList ProjectionSurface::getPeaksWorkspaceNames() const
-		{
-			QStringList names;
-			foreach(PeakOverlay* po, m_peakShapes)
-			{
-				names << QString::fromStdString(po->getPeaksWorkspace()->name());
-			}
-			return names;
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* The constructor.
+* @param rootActor :: The instrument actor containing all info about the
+* instrument
+*/
+ProjectionSurface::ProjectionSurface(const InstrumentActor *rootActor)
+    : m_instrActor(rootActor), m_viewImage(NULL), m_pickImage(NULL),
+      m_viewRect(), m_selectRect(), m_interactionMode(MoveMode),
+      m_isLightingOn(false), m_peakLabelPrecision(2), m_showPeakRows(false),
+      m_showPeakLabels(false), m_showPeakRelativeIntensity(false),
+      m_peakShapesStyle(0), m_viewChanged(true), m_redrawPicking(true) {
+  connect(rootActor, SIGNAL(colorMapChanged()), this, SLOT(colorMapChanged()));
+  connect(&m_maskShapes, SIGNAL(shapeCreated()), this, SIGNAL(shapeCreated()));
+  connect(&m_maskShapes, SIGNAL(shapeSelected()), this,
+          SIGNAL(shapeSelected()));
+  connect(&m_maskShapes, SIGNAL(shapesDeselected()), this,
+          SIGNAL(shapesDeselected()));
+  connect(&m_maskShapes, SIGNAL(shapesRemoved()), this,
+          SIGNAL(shapesRemoved()));
+  connect(&m_maskShapes, SIGNAL(shapeChanged()), this, SIGNAL(shapeChanged()));
+  connect(&m_maskShapes, SIGNAL(cleared()), this, SIGNAL(shapesCleared()));
+
+  // create and connect the pick input controller
+  InputControllerPick *pickController = new InputControllerPick(this);
+  setInputController(PickSingleMode, pickController);
+  setInputController(PickTubeMode, pickController);
+  setInputController(AddPeakMode, pickController);
+  connect(pickController, SIGNAL(pickPointAt(int, int)), this,
+          SLOT(pickComponentAt(int, int)));
+  connect(pickController, SIGNAL(touchPointAt(int, int)), this,
+          SLOT(touchComponentAt(int, int)));
+
+  // create and connect the mask drawing input controller
+  InputControllerDrawShape *drawController = new InputControllerDrawShape(this);
+  setInputController(DrawRegularMode, drawController);
+  connect(drawController, SIGNAL(addShape(QString, int, int, QColor, QColor)),
+          &m_maskShapes, SLOT(addShape(QString, int, int, QColor, QColor)));
+  connect(this, SIGNAL(signalToStartCreatingShape2D(QString, QColor, QColor)),
+          drawController, SLOT(startCreatingShape2D(QString, QColor, QColor)));
+  connect(drawController, SIGNAL(moveRightBottomTo(int, int)), &m_maskShapes,
+          SLOT(moveRightBottomTo(int, int)));
+  connect(drawController, SIGNAL(selectAt(int, int)), &m_maskShapes,
+          SLOT(selectShapeOrControlPointAt(int, int)));
+  connect(drawController, SIGNAL(selectCtrlAt(int, int)), &m_maskShapes,
+          SLOT(addToSelectionShapeAt(int, int)));
+  connect(drawController, SIGNAL(moveBy(int, int)), &m_maskShapes,
+          SLOT(moveShapeOrControlPointBy(int, int)));
+  connect(drawController, SIGNAL(touchPointAt(int, int)), &m_maskShapes,
+          SLOT(touchShapeOrControlPointAt(int, int)));
+  connect(drawController, SIGNAL(removeSelectedShapes()), &m_maskShapes,
+          SLOT(removeSelectedShapes()));
+  connect(drawController, SIGNAL(deselectAll()), &m_maskShapes,
+          SLOT(deselectAll()));
+  connect(drawController, SIGNAL(restoreOverrideCursor()), &m_maskShapes,
+          SLOT(restoreOverrideCursor()));
+  connect(drawController, SIGNAL(setSelection(QRect)), this,
+          SLOT(setSelectionRect(QRect)));
+  connect(drawController, SIGNAL(finishSelection(QRect)), this,
+          SLOT(selectMultipleMasks(QRect)));
+  connect(drawController, SIGNAL(finishSelection(QRect)), this,
+          SIGNAL(shapeChangeFinished()));
+
+  InputControllerDrawAndErase *freeDrawController =
+      new InputControllerDrawAndErase(this);
+  setInputController(DrawFreeMode, freeDrawController);
+  connect(this, SIGNAL(signalToStartCreatingFreeShape(QColor, QColor)),
+          freeDrawController, SLOT(startCreatingShape2D(QColor, QColor)));
+  connect(freeDrawController,
+          SIGNAL(addShape(const QPolygonF &, QColor, QColor)), &m_maskShapes,
+          SLOT(addFreeShape(const QPolygonF &, QColor, QColor)));
+  connect(freeDrawController, SIGNAL(draw(const QPolygonF &)), &m_maskShapes,
+          SLOT(drawFree(const QPolygonF &)));
+  connect(freeDrawController, SIGNAL(erase(const QPolygonF &)), &m_maskShapes,
+          SLOT(eraseFree(const QPolygonF &)));
+
+  // create and connect the peak eraser controller
+  InputControllerErase *eraseController = new InputControllerErase(this);
+  setInputController(ErasePeakMode, eraseController);
+  connect(eraseController, SIGNAL(erase(QRect)), this, SLOT(erasePeaks(QRect)));
+}
+
+ProjectionSurface::~ProjectionSurface() {
+  if (m_viewImage) {
+    delete m_viewImage;
+  }
+  if (m_pickImage) {
+    delete m_pickImage;
+  }
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    if (m_peakShapes[i])
+      delete m_peakShapes[i];
+  }
+  m_peakShapes.clear();
+}
+
+/**
+* Resets the instrument actor. The caller must ensure that the instrument
+* stays the same and workspace dimensions also don't change.
+*/
+void ProjectionSurface::resetInstrumentActor(const InstrumentActor *rootActor) {
+  m_instrActor = rootActor;
+  connect(rootActor, SIGNAL(colorMapChanged()), this, SLOT(colorMapChanged()));
+}
+
+void ProjectionSurface::clear() {
+  if (m_viewImage) {
+    delete m_viewImage;
+    m_viewImage = NULL;
+  }
+  if (m_pickImage) {
+    delete m_pickImage;
+    m_pickImage = NULL;
+  }
+  m_viewChanged = true;
+  m_redrawPicking = true;
+  m_viewRect = RectF();
+  m_selectRect = QRect();
+}
+
+/**
+* Draw the surface on an OpenGL widget
+* @param widget :: A widget to draw on.
+*/
+void ProjectionSurface::draw(MantidGLWidget *widget) const {
+  if (m_viewChanged &&
+      (m_redrawPicking || m_interactionMode == PickSingleMode ||
+       m_interactionMode == PickTubeMode ||
+       m_interactionMode == DrawRegularMode)) {
+    draw(widget, true);
+    m_redrawPicking = false;
+  }
+  draw(widget, false);
+  if (m_viewChanged) {
+    m_viewChanged = false;
+  }
+}
+
+/**
+* Draw the surface on an OpenGL widget.
+* @param widget :: A widget to draw on.
+* @param picking :: Picking / normal drawing switch.
+*/
+void ProjectionSurface::draw(MantidGLWidget *widget, bool picking) const {
+  QImage **image = picking ? &m_pickImage : &m_viewImage;
+
+  if (!*image || (*image)->width() != widget->width() ||
+      (*image)->height() != widget->height()) {
+    m_viewChanged = true;
+  }
+
+  if (m_viewChanged) {
+
+    this->drawSurface(widget, picking);
+
+    if (*image) {
+      delete (*image);
+    }
+    (*image) = new QImage(widget->grabFrameBuffer());
+
+    if (!picking) {
+      QPainter painter(widget);
+      RectF windowRect = getSurfaceBounds();
+      m_maskShapes.setWindow(windowRect, painter.viewport());
+      m_maskShapes.draw(painter);
+      for (int i = 0; i < m_peakShapes.size(); ++i) {
+        m_peakShapes[i]->setWindow(windowRect, painter.viewport());
+        m_peakShapes[i]->draw(painter);
+      }
+      painter.end();
+    }
+  } else if (!picking) {
+    QPainter painter(widget);
+    painter.drawImage(0, 0, **image);
+
+    RectF windowRect = getSurfaceBounds();
+    m_maskShapes.setWindow(windowRect, painter.viewport());
+    m_maskShapes.draw(painter);
+
+    for (int i = 0; i < m_peakShapes.size(); ++i) {
+      m_peakShapes[i]->setWindow(windowRect, painter.viewport());
+      m_peakShapes[i]->draw(painter);
+    }
+
+    // draw the selection rectangle
+    if (!m_selectRect.isNull()) {
+      painter.setPen(Qt::blue);
+      // painter.setCompositionMode(QPainter::CompositionMode_Xor);
+      painter.drawRect(m_selectRect);
+    }
+    getController()->onPaint(painter);
+    painter.end();
+    // Discard any error generated here
+    GLuint ecode = glGetError();
+    OpenGLError::logDebug()
+        << "Discarding OpenGL error: " << gluErrorString(ecode);
+  }
+}
+
+/**
+* Draw the surface onto a normal widget without OpenGL
+* @param widget :: A widget to draw on.
+*/
+void ProjectionSurface::drawSimple(QWidget *widget) const {
+  if (m_viewChanged) {
+    if (!m_viewImage || m_viewImage->width() != widget->width() ||
+        m_viewImage->height() != widget->height()) {
+      if (m_viewImage)
+        delete m_viewImage;
+      m_viewImage =
+          new QImage(widget->width(), widget->height(), QImage::Format_RGB32);
+      if (m_pickImage)
+        delete m_pickImage;
+      m_pickImage =
+          new QImage(widget->width(), widget->height(), QImage::Format_RGB32);
+    }
+
+    if (m_redrawPicking || m_interactionMode == PickSingleMode ||
+        m_interactionMode == PickTubeMode) {
+      drawSimpleToImage(m_pickImage, true);
+      m_redrawPicking = false;
+    }
+    drawSimpleToImage(m_viewImage, false);
+    m_viewChanged = false;
+  }
+
+  QPainter painter(widget);
+  painter.drawImage(0, 0, *m_viewImage);
+
+  RectF windowRect = getSurfaceBounds();
+  m_maskShapes.setWindow(windowRect, painter.viewport());
+  m_maskShapes.draw(painter);
+
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    m_peakShapes[i]->setWindow(windowRect, painter.viewport());
+    m_peakShapes[i]->draw(painter);
+  }
+
+  // draw the selection rectangle
+  if (!m_selectRect.isNull()) {
+    painter.setPen(Qt::blue);
+    // painter.setCompositionMode(QPainter::CompositionMode_Xor);
+    painter.drawRect(m_selectRect);
+  }
+  getController()->onPaint(painter);
+  painter.end();
+}
+
+void ProjectionSurface::resize(int, int) { updateView(); }
+
+/**
+* Draw the surface onto an image without OpenGL
+* @param image :: Image to draw on.
+* @param picking :: If true draw a picking image.
+*/
+void ProjectionSurface::drawSimpleToImage(QImage *, bool) const {}
+
+void ProjectionSurface::mousePressEvent(QMouseEvent *e) {
+  getController()->mousePressEvent(e);
+}
+
+void ProjectionSurface::mouseMoveEvent(QMouseEvent *e) {
+  getController()->mouseMoveEvent(e);
+}
+
+void ProjectionSurface::mouseReleaseEvent(QMouseEvent *e) {
+  getController()->mouseReleaseEvent(e);
+}
+
+void ProjectionSurface::wheelEvent(QWheelEvent *e) {
+  getController()->wheelEvent(e);
+}
+
+void ProjectionSurface::keyPressEvent(QKeyEvent *e) {
+  getController()->keyPressEvent(e);
+}
+
+void ProjectionSurface::enterEvent(QEvent *e) {
+  getController()->enterEvent(e);
+}
+
+void ProjectionSurface::leaveEvent(QEvent *e) {
+  getController()->leaveEvent(e);
+}
+
+/**
+* Update the view of the surface at the next redraw.
+* @param picking :: Set to true to update the picking image regardless the
+* interaction
+*   mode of the surface.
+*/
+void ProjectionSurface::updateView(bool picking) {
+  m_viewChanged = true;
+  if (picking) {
+    // don't change to false if it's already true
+    m_redrawPicking = true;
+  }
+}
+
+void ProjectionSurface::updateDetectors() {
+  clear();
+  this->init();
+  // if integration range in the instrument actor has changed
+  // update visiblity of peak markers
+  setPeakVisibility();
+}
+
+/// Send a redraw request to the surface owner
+void ProjectionSurface::requestRedraw(bool resetPeakVisibility) {
+  if (resetPeakVisibility) {
+    setPeakVisibility();
+  }
+  emit redrawRequired();
+}
+
+QRect ProjectionSurface::selectionRect() const {
+  if (m_selectRect.width() <= 1 || m_selectRect.height() <= 1)
+    return QRect();
+
+  int x_min = m_selectRect.left();
+  int x_size = m_selectRect.width();
+  int y_min = m_selectRect.top();
+  int y_size = m_selectRect.height();
+
+  if (x_size < 0) {
+    x_min += x_size;
+    x_size = abs(x_size);
+  }
+
+  if (y_size < 0) {
+    y_min += y_size;
+    y_size = abs(y_size);
+  }
+
+  return QRect(x_min, y_min, x_size, y_size);
+}
+
+RectF ProjectionSurface::selectionRectUV() const {
+  double left = static_cast<double>(m_selectRect.left());
+  double right = static_cast<double>(m_selectRect.right());
+  double top = static_cast<double>(m_selectRect.top());
+  double bottom = static_cast<double>(m_selectRect.bottom());
+
+  if (left > right) {
+    std::swap(left, right);
+  }
+
+  if (top > bottom) {
+    std::swap(top, bottom);
+  }
+
+  if (abs(m_selectRect.width()) <= 1 || abs(m_selectRect.height()) <= 1)
+    return RectF();
+
+  double sx = m_viewRect.xSpan() / m_viewImage->width();
+  double sy = m_viewRect.ySpan() / m_viewImage->height();
+
+  double x_min = left * sx + m_viewRect.x0();
+  double x_max = right * sx + m_viewRect.x0();
+  double y_min = (m_viewImage->height() - bottom) * sy + m_viewRect.y0();
+  double y_max = (m_viewImage->height() - top) * sy + m_viewRect.y0();
+
+  return RectF(QPointF(x_min, y_min), QPointF(x_max, y_max));
+}
+
+bool ProjectionSurface::hasSelection() const {
+  return !m_selectRect.isNull() && m_selectRect.width() > 0;
+}
+
+void ProjectionSurface::colorMapChanged() {
+  this->changeColorMap();
+  updateView(false);
+  requestRedraw();
+}
+
+/**
+* Set an interaction mode for the surface.
+* @param mode :: A new mode.
+*/
+void ProjectionSurface::setInteractionMode(int mode) {
+  if (mode < 0 || mode >= m_inputControllers.size()) {
+    throw std::logic_error("Invalid interaction mode requested.");
+  }
+  if (mode == m_interactionMode)
+    return;
+  InputController *controller = m_inputControllers[m_interactionMode];
+  if (!controller)
+    throw std::logic_error("Input controller doesn't exist.");
+  controller->onDisabled();
+  m_interactionMode = mode;
+  controller = m_inputControllers[m_interactionMode];
+  if (!controller)
+    throw std::logic_error("Input controller doesn't exist.");
+  controller->onEnabled();
+  if (mode != DrawRegularMode && mode != DrawFreeMode) {
+    m_maskShapes.deselectAll();
+    foreach (PeakOverlay *po, m_peakShapes) { po->deselectAll(); }
+  }
+}
+
+/**
+* Return detector id at image coordinats x,y if in pick mode. -1 otherwise
+*/
+int ProjectionSurface::getDetectorID(int x, int y) const {
+  size_t pickID = getPickID(x, y);
+  return m_instrActor->getDetID(pickID);
+}
+
+//------------------------------------------------------------------------------
+boost::shared_ptr<const Mantid::Geometry::IDetector>
+ProjectionSurface::getDetector(int x, int y) const {
+  size_t pickID = getPickID(x, y);
+  return m_instrActor->getDetector(pickID);
+}
+
+/**
+* Return info text for interactions common to all surfaces.
+*/
+QString ProjectionSurface::getInfoText() const {
+  switch (m_interactionMode) {
+  case PickSingleMode:
+  case PickTubeMode:
+    return "Move cursor over instrument to see detector information. ";
+  case AddPeakMode:
+    return "Click on a detector then click on the mini-plot to add a peak.";
+  case DrawRegularMode:
+    return "Select a tool button to draw a new shape. "
+           "Click on shapes to select. Click and move to edit.";
+  case DrawFreeMode:
+    return "Draw by holding the left button down. "
+           "Erase with the right button.";
+  case ErasePeakMode:
+    return "Click and move the mouse to erase peaks. "
+           "Rotate the wheel to resize the cursor.";
+  }
+  return "";
+}
+
+//------------------------------------------------------------------------------
+/** Return the detector position (in real-space) at the pixel coordinates.
+*
+* @param x :: x pixel coordinate
+* @param y :: y pixel coordinate
+* @return V3D of the detector position
+*/
+Mantid::Kernel::V3D ProjectionSurface::getDetectorPos(int x, int y) const {
+  size_t pickID = getPickID(x, y);
+  return m_instrActor->getDetPos(pickID);
+}
+
+/**
+* Is context menu allowed?
+*/
+bool ProjectionSurface::canShowContextMenu() const {
+  InputController *controller = m_inputControllers[m_interactionMode];
+  if (controller) {
+    return controller->canShowContextMenu();
+  }
+  return false;
+}
+
+//------------------------------------------------------------------------------
+size_t ProjectionSurface::getPickID(int x, int y) const {
+  if (!m_pickImage || !m_pickImage->valid(x, y))
+    return -1;
+  QRgb pixel = m_pickImage->pixel(x, y);
+  return GLActor::decodePickColor(pixel);
+}
+
+/**
+* Adds an input controller to the controller list.
+* @param mode :: The interaction mode which is the index of the controller in
+* the list.
+* @param controller :: A pointer to the controller to be set.
+*/
+void ProjectionSurface::setInputController(int mode,
+                                           InputController *controller) {
+  m_inputControllers[mode] = controller;
+}
+
+/**
+* Set visibility of the peak markers according to the integration range
+* in the instrument actor.
+*/
+void ProjectionSurface::setPeakVisibility() const {
+  if (hasPeakOverlays()) {
+    Mantid::Kernel::Unit_sptr unit =
+        m_instrActor->getWorkspace()->getAxis(0)->unit();
+    QString unitID = QString::fromStdString(unit->unitID());
+    double xmin = m_instrActor->minBinValue();
+    double xmax = m_instrActor->maxBinValue();
+    foreach (PeakOverlay *po, m_peakShapes) {
+      po->setPeakVisibility(xmin, xmax, unitID);
+    }
+  }
+}
+
+/**
+* Returns the current controller. If the controller doesn't exist throws a
+* logic_error exceotion.
+*/
+InputController *ProjectionSurface::getController() const {
+  InputController *controller = m_inputControllers[m_interactionMode];
+  if (!controller) {
+    throw std::logic_error(
+        "Input controller doesn't exist for current interaction mode.");
+  }
+  return controller;
+}
+
+// --- Shape2D manipulation --- //
+
+void ProjectionSurface::startCreatingShape2D(const QString &type,
+                                             const QColor &borderColor,
+                                             const QColor &fillColor) {
+  emit signalToStartCreatingShape2D(type, borderColor, fillColor);
+}
+
+void ProjectionSurface::startCreatingFreeShape(const QColor &borderColor,
+                                               const QColor &fillColor) {
+  emit signalToStartCreatingFreeShape(borderColor, fillColor);
+}
+
+/**
+* Return a combined list of peak parkers from all overlays
+* @param detID :: The detector ID of interest
+*/
+QList<PeakMarker2D *> ProjectionSurface::getMarkersWithID(int detID) const {
+  QList<PeakMarker2D *> out;
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    out += m_peakShapes[i]->getMarkersWithID(detID);
+  }
+  return out;
+}
+
+/**
+* Get peaks workspace for manually editing.
+*/
+boost::shared_ptr<Mantid::API::IPeaksWorkspace>
+ProjectionSurface::getEditPeaksWorkspace() const {
+  if (!m_peakShapes.isEmpty()) {
+    return m_peakShapes.last()->getPeaksWorkspace();
+  }
+  return boost::shared_ptr<Mantid::API::IPeaksWorkspace>();
+}
+
+/**
+* Remove an overlay if its peaks workspace is deleted.
+* @param ws :: Shared pointer to the deleted peaks workspace.
+*/
+void ProjectionSurface::deletePeaksWorkspace(
+    boost::shared_ptr<Mantid::API::IPeaksWorkspace> ws) {
+  const int npeaks = m_peakShapes.size();
+  for (int i = 0; i < npeaks; ++i) {
+    if (m_peakShapes[i]->getPeaksWorkspace() == ws) {
+      delete m_peakShapes[i];
+      m_peakShapes.removeAt(i);
+      break;
+    }
+  }
+  if (m_peakShapes.size() < npeaks) {
+    emit peaksWorkspaceDeleted();
+  }
+}
+
+/**
+* Remove all peak overlays.
+*/
+void ProjectionSurface::clearPeakOverlays() {
+  if (!m_peakShapes.isEmpty()) {
+    for (int i = 0; i < m_peakShapes.size(); ++i) {
+      delete m_peakShapes[i];
+    }
+    m_peakShapes.clear();
+    m_peakShapesStyle = 0;
+    emit peaksWorkspaceDeleted();
+  }
+}
+
+/**
+* Set the precision (significant digits) with which the HKL peak labels are
+* displayed.
+* @param n :: Precision, > 0
+*/
+void ProjectionSurface::setPeakLabelPrecision(int n) {
+  if (n < 1) {
+    QMessageBox::critical(NULL, "MantidPlot - Error",
+                          "Precision must be a positive number");
+    return;
+  }
+  m_peakLabelPrecision = n;
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    m_peakShapes[i]->setPrecision(n);
+  }
+}
+
+/**
+* Enable or disable the show peak row flag
+*/
+void ProjectionSurface::setShowPeakRowsFlag(bool on) {
+  m_showPeakRows = on;
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    m_peakShapes[i]->setShowRowsFlag(on);
+  }
+}
+
+/**
+* Enable or disable the show peak label flag
+*/
+void ProjectionSurface::setShowPeakLabelsFlag(bool on) {
+  m_showPeakLabels = on;
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    m_peakShapes[i]->setShowLabelsFlag(on);
+  }
+}
+
+/**
+* Enable or disable the show peak label flag
+*/
+void ProjectionSurface::setShowPeakRelativeIntensityFlag(bool on) {
+  m_showPeakRelativeIntensity = on;
+  for (int i = 0; i < m_peakShapes.size(); ++i) {
+    m_peakShapes[i]->setShowRelativeIntensityFlag(on);
+  }
+}
+
+/**
+* Set the selection rect in screen corrds.
+* @param rect :: New selection rectangle.
+*/
+void ProjectionSurface::setSelectionRect(const QRect &rect) {
+  if (m_interactionMode != DrawRegularMode || !m_maskShapes.hasSelection()) {
+    m_selectRect = rect;
+  }
+}
+
+/**
+* Delete selection rectanle.
+*/
+void ProjectionSurface::emptySelectionRect() { m_selectRect = QRect(); }
+
+/**
+* Select multiple mask shapes as a result of a rubber-band selection
+* @param rect :: The rubber band rect.
+*/
+void ProjectionSurface::selectMultipleMasks(const QRect &rect) {
+  if (!m_maskShapes.hasSelection()) {
+    m_maskShapes.selectIn(rect);
+  }
+  emptySelectionRect();
+}
+
+/**
+* Pick a detector at a pointe on the screen.
+*/
+void ProjectionSurface::pickComponentAt(int x, int y) {
+  size_t pickID = getPickID(x, y);
+  emit singleComponentPicked(pickID);
+}
+
+void ProjectionSurface::touchComponentAt(int x, int y) {
+  size_t pickID = getPickID(x, y);
+  emit singleComponentTouched(pickID);
+}
+
+void ProjectionSurface::erasePeaks(const QRect &rect) {
+  foreach (PeakOverlay *po, m_peakShapes) {
+    po->selectIn(rect);
+    po->removeSelectedShapes();
+  }
+}
+
+/**
+* Enable or disable lighting in non-picking mode
+* @param on :: True for enabling, false for disabling.
+*/
+void ProjectionSurface::enableLighting(bool on) { m_isLightingOn = on; }
+
+/**
+* Return names of attached peaks workspaces.
+*/
+QStringList ProjectionSurface::getPeaksWorkspaceNames() const {
+  QStringList names;
+  foreach (PeakOverlay *po, m_peakShapes) {
+    names << QString::fromStdString(po->getPeaksWorkspace()->name());
+  }
+  return names;
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/RectangularDetectorActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/RectangularDetectorActor.cpp
index 62c2678b4fef6cb1b8db08729683a829cceec2af..15c981a51ed8ba6404b3f315268205a02ced7427 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/RectangularDetectorActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/RectangularDetectorActor.cpp
@@ -19,327 +19,314 @@ using namespace Geometry;
 using Mantid::Kernel::V3D;
 using Mantid::Kernel::Quat;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		static const bool VERBOSE = false;
-
-
-		/**
-		* Constructor.
-		*
-		* @param instrActor :: the instrument actor
-		* @param compID :: the component ID
-		*/
-		RectangularDetectorActor::RectangularDetectorActor(
-			const InstrumentActor &instrActor,
-			const Mantid::Geometry::ComponentID &compID)
-			: ICompAssemblyActor(instrActor, compID), mTextureID(0), image_data(NULL),
-			pick_data(NULL) {
-			mNumberOfDetectors = 0;
-			mDet = boost::dynamic_pointer_cast<const RectangularDetector>(getComponent());
-
-			if (!mDet) return;
-
-			BoundingBox compBox;
-			mDet->getBoundingBox(compBox);
-			mNumberOfDetectors = mDet->xpixels() * mDet->ypixels();
-			this->AppendBoundingBox(compBox.minPoint(), compBox.maxPoint());
-
-			std::vector<GLColor> clist;
-			for (int y = 0; y < mDet->ypixels(); y++)
-			{
-				for (int x = 0; x < mDet->xpixels(); x++)
-				{
-					// Getting the detector is slow. Get the ID directly
-					detid_t id = mDet->getDetectorIDAtXY(x, y);
-					size_t pickID = instrActor.pushBackDetid(id);
-					m_pickIDs.push_back(pickID);
-					clist.push_back(instrActor.getColor(id));
-				}
-			}
-
-			genTexture(image_data, clist, false);
-			genTexture(pick_data, clist, true);
-			uploadTexture(image_data);
-
-		}
-
-
-
-		//-------------------------------------------------------------------------------------------------
-		/**
-		* Destructor which removes the actors created by this object
-		*/
-		RectangularDetectorActor::~RectangularDetectorActor()
-		{
-			delete[] image_data;
-			delete[] pick_data;
-		}
-
-
-		//-------------------------------------------------------------------------------------------------
-		/**
-		* This function is concrete implementation that renders the Child ObjComponents and Child CompAssembly's
-		*/
-		void RectangularDetectorActor::draw(bool picking)const
-		{
-			if (VERBOSE) std::cout << "RectangularDetectorActor::define() called for " << mDet->getName() << "\n";
-
-			glPushMatrix();
-			// Translation first
-			V3D pos = mDet->getPos();
-			if (!(pos.nullVector()))
-			{
-				glTranslated(pos[0], pos[1], pos[2]);
-			}
-			//Rotation
-			Quat rot = mDet->getRotation();
-			if (!(rot.isNull()))
-			{
-				double deg, ax0, ax1, ax2;
-				rot.getAngleAxis(deg, ax0, ax1, ax2);
-				glRotated(deg, ax0, ax1, ax2);
-			}
-			//Scale
-			V3D scaleFactor = mDet->getScaleFactor();
-			if (!(scaleFactor == V3D(1, 1, 1)))
-			{
-				glScaled(scaleFactor[0], scaleFactor[1], scaleFactor[2]);
-			}
-
-			//glBindTexture(GL_TEXTURE_2D, mTextureID);
-			if (picking)
-			{
-				this->uploadTexture(pick_data);
-			}
-			else
-			{
-				this->uploadTexture(image_data);
-			}
-			// RectangularDetector will use.
-			mDet->draw();
-			glBindTexture(GL_TEXTURE_2D, 0);
-
-			glPopMatrix();
-		}
-
-		//------------------------------------------------------------------------------------------------
-		/**
-		* Accept a visitor. This sets the matching component's visibility to True.
-		* It looks if the given component is a child (pixel) of the parent rectangular
-		* detector, and sets the visibility of the whole panel to true if so.
-		*
-		* @param visitor :: A visitor.
-		* @param rule :: A rule defining visitor acceptance by assembly actors. Unused.
-		*
-		*/
-		bool RectangularDetectorActor::accept(GLActorVisitor& visitor, VisitorAcceptRule)
-		{
-			return visitor.visit(this);
-		}
-
-		bool RectangularDetectorActor::accept(GLActorConstVisitor &visitor, GLActor::VisitorAcceptRule) const
-		{
-			return visitor.visit(this);
-		}
-
-		bool RectangularDetectorActor::isChildDetector(const ComponentID &id) const
-		{
-			// ID of the parent RectangularDetector
-			Mantid::Geometry::ComponentID thisID = this->m_id;
-
-			// Get the component object
-			IComponent_const_sptr comp = m_instrActor.getInstrument()->getComponentByID(id);
-			if (comp)
-			{
-				// Get the parent (e.g. the column)
-				IComponent_const_sptr parent1 = comp->getParent();
-				if (parent1)
-				{
-					if (parent1->getComponentID() == thisID)
-					{
-						return true;
-					}
-					// Go to grandparent
-					IComponent_const_sptr parent2 = parent1->getParent();
-					if (parent2)
-					{
-						if (parent2->getComponentID() == thisID)
-						{
-							return true;
-						}
-					} // valid grandparent
-				} // valid parent
-			} // valid component
-			return false;
-		}
-
-		//------------------------------------------------------------------------------------------------
-		/**
-		* Generate a texture for the RectangularDetector
-		*
-		* @param image_data :: pointer to where the image data will be filled in.
-		* @param list :: Color list iterator. Only used if useDetectorIDs is false.
-		* @param useDetectorIDs :: set to true to make a fake texture using the detector IDs. If false, the iterator is used.
-		*
-		*/
-		int RectangularDetectorActor::genTexture(char * & image_data, std::vector<GLColor>& list, bool useDetectorIDs)
-		{
-			int num = mDet->xpixels() * mDet->ypixels();
-
-			//The texture size must be 2^n power.
-			int text_x_size, text_y_size;
-			mDet->getTextureSize(text_x_size, text_y_size);
-
-			//std::cerr << "Texture size: " << text_x_size << ',' << text_y_size <<std::endl;
-
-			//------ Create the image data buffer -------
-			if (!image_data)
-			{
-				//Delete the old memory
-				delete[] image_data;
-				image_data = new char[3 * text_x_size*text_y_size];
-			}
-			//Pointer to where we are in it.
-			char * image_data_ptr = image_data;
-
-			//Fill with 0 (black) everywhere
-			std::fill(image_data, image_data + 3 * text_x_size*text_y_size, 0);
-
-			//For using color IDs
-			int rgb = 0;
-			std::vector<GLColor>::iterator list_it = list.begin();
-
-			for (int y = 0; y < mDet->ypixels(); y++)
-			{
-				for (int x = 0; x < mDet->xpixels(); x++)
-				{
-					//Use black as the default color (for going off the edges)
-					unsigned char r, g, b;
-
-					if (useDetectorIDs)
-					{
-						GLColor c = GLActor::makePickColor(m_pickIDs[rgb]);
-						c.get(r, g, b);
-						rgb++;
-					}
-					else
-					{
-						//Get the current color
-						list_it->get(r, g, b);
-						//Go to the next color
-						++list_it;
-					}
-
-					//      //TEMP: way to show the colors
-					//      r=x;
-					//      g=y;
-					//      b=x;
-
-					//Save the color data to the buffer
-					*image_data_ptr = r;
-					image_data_ptr++;
-					*image_data_ptr = g;
-					image_data_ptr++;
-					*image_data_ptr = b;
-					image_data_ptr++;
-
-				}
-
-				//Skip any padding in x. 3 bytes per pixel
-				image_data_ptr += 3 * (text_x_size - mDet->xpixels());
-			}
-
-			if (VERBOSE) std::cout << "RectangularDetectorActor::genTexture() called for " << mDet->getName() << " with " << num << " entries set\n";
-
-			return num;
-		}
-
-		//------------------------------------------------------------------------------------------------
-		/** Upload the texture to the video card. */
-		void RectangularDetectorActor::uploadTexture(char * & image_data)const
-		{
-			if (!image_data)
-				throw std::runtime_error("Empty pointer passed to RectangularDetectorActor::uploadTexture()!");
-
-			//The texture size must be 2^n power.
-			int text_x_size, text_y_size;
-			mDet->getTextureSize(text_x_size, text_y_size);
-
-			// Set up before uploading a texture
-			if (mTextureID > 0)
-				glDeleteTextures(1, &mTextureID);
-			glGenTextures(1, &mTextureID);          // Create The Texture
-			if (VERBOSE) std::cout << mDet->getName() << " is drawing with texture id " << mTextureID << "\n";
-			//mDet->setTextureID(mTextureID);
-
-			glBindTexture(GL_TEXTURE_2D, mTextureID);
-
-			if (glGetError()>0) std::cout << "OpenGL error in glBindTexture \n";
-
-			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-
-			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //This one allows lighting effects
-																			//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); //This one doesn't
-
-																			//Upload the texture to video card
-			if (glGetError()>0) std::cout << "OpenGL error BEFORE glTexImage2D \n";
-			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, text_x_size, text_y_size, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data);
-			if (glGetError()>0) std::cout << "OpenGL error in glTexImage2D \n";
-
-		}
-
-		//-------------------------------------------------------------------------------------------------
-		/**
-		* Return the bounding box, from the one calculated in the cache previously.
-		* @param minBound :: min point of the bounding box
-		* @param maxBound :: max point of the bounding box
-		*/
-		void RectangularDetectorActor::getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const
-		{
-			minBound = minBoundBox;
-			maxBound = maxBoundBox;
-		}
-
-
-		/**
-		* Append the bounding box CompAssembly bounding box
-		* @param minBound :: min point of the bounding box
-		* @param maxBound :: max point of the bounding box
-		*/
-		void RectangularDetectorActor::AppendBoundingBox(const Mantid::Kernel::V3D& minBound, const Mantid::Kernel::V3D& maxBound)
-		{
-			if (minBoundBox[0]>minBound[0]) minBoundBox[0] = minBound[0];
-			if (minBoundBox[1]>minBound[1]) minBoundBox[1] = minBound[1];
-			if (minBoundBox[2]>minBound[2]) minBoundBox[2] = minBound[2];
-			if (maxBoundBox[0]<maxBound[0]) maxBoundBox[0] = maxBound[0];
-			if (maxBoundBox[1]<maxBound[1]) maxBoundBox[1] = maxBound[1];
-			if (maxBoundBox[2]<maxBound[2]) maxBoundBox[2] = maxBound[2];
-		}
-
-		void RectangularDetectorActor::setColors()
-		{
-			std::vector<GLColor> clist;
-			for (int y = 0; y < mDet->ypixels(); y++)
-			{
-				for (int x = 0; x < mDet->xpixels(); x++)
-				{
-					detid_t id = mDet->getDetectorIDAtXY(x, y);
-					clist.push_back(m_instrActor.getColor(id));
-				}
-			}
-			genTexture(image_data, clist, false);
-			uploadTexture(image_data);
-		}
-	}//MantidWidgets
-}//MantidQt
-
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+static const bool VERBOSE = false;
+
+/**
+* Constructor.
+*
+* @param instrActor :: the instrument actor
+* @param compID :: the component ID
+*/
+RectangularDetectorActor::RectangularDetectorActor(
+    const InstrumentActor &instrActor,
+    const Mantid::Geometry::ComponentID &compID)
+    : ICompAssemblyActor(instrActor, compID), mTextureID(0), image_data(NULL),
+      pick_data(NULL) {
+  mNumberOfDetectors = 0;
+  mDet = boost::dynamic_pointer_cast<const RectangularDetector>(getComponent());
+
+  if (!mDet)
+    return;
+
+  BoundingBox compBox;
+  mDet->getBoundingBox(compBox);
+  mNumberOfDetectors = mDet->xpixels() * mDet->ypixels();
+  this->AppendBoundingBox(compBox.minPoint(), compBox.maxPoint());
+
+  std::vector<GLColor> clist;
+  for (int y = 0; y < mDet->ypixels(); y++) {
+    for (int x = 0; x < mDet->xpixels(); x++) {
+      // Getting the detector is slow. Get the ID directly
+      detid_t id = mDet->getDetectorIDAtXY(x, y);
+      size_t pickID = instrActor.pushBackDetid(id);
+      m_pickIDs.push_back(pickID);
+      clist.push_back(instrActor.getColor(id));
+    }
+  }
+
+  genTexture(image_data, clist, false);
+  genTexture(pick_data, clist, true);
+  uploadTexture(image_data);
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+* Destructor which removes the actors created by this object
+*/
+RectangularDetectorActor::~RectangularDetectorActor() {
+  delete[] image_data;
+  delete[] pick_data;
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+* This function is concrete implementation that renders the Child ObjComponents
+* and Child CompAssembly's
+*/
+void RectangularDetectorActor::draw(bool picking) const {
+  if (VERBOSE)
+    std::cout << "RectangularDetectorActor::define() called for "
+              << mDet->getName() << "\n";
+
+  glPushMatrix();
+  // Translation first
+  V3D pos = mDet->getPos();
+  if (!(pos.nullVector())) {
+    glTranslated(pos[0], pos[1], pos[2]);
+  }
+  // Rotation
+  Quat rot = mDet->getRotation();
+  if (!(rot.isNull())) {
+    double deg, ax0, ax1, ax2;
+    rot.getAngleAxis(deg, ax0, ax1, ax2);
+    glRotated(deg, ax0, ax1, ax2);
+  }
+  // Scale
+  V3D scaleFactor = mDet->getScaleFactor();
+  if (!(scaleFactor == V3D(1, 1, 1))) {
+    glScaled(scaleFactor[0], scaleFactor[1], scaleFactor[2]);
+  }
+
+  // glBindTexture(GL_TEXTURE_2D, mTextureID);
+  if (picking) {
+    this->uploadTexture(pick_data);
+  } else {
+    this->uploadTexture(image_data);
+  }
+  // RectangularDetector will use.
+  mDet->draw();
+  glBindTexture(GL_TEXTURE_2D, 0);
+
+  glPopMatrix();
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+* Accept a visitor. This sets the matching component's visibility to True.
+* It looks if the given component is a child (pixel) of the parent rectangular
+* detector, and sets the visibility of the whole panel to true if so.
+*
+* @param visitor :: A visitor.
+* @param rule :: A rule defining visitor acceptance by assembly actors. Unused.
+*
+*/
+bool RectangularDetectorActor::accept(GLActorVisitor &visitor,
+                                      VisitorAcceptRule) {
+  return visitor.visit(this);
+}
+
+bool RectangularDetectorActor::accept(GLActorConstVisitor &visitor,
+                                      GLActor::VisitorAcceptRule) const {
+  return visitor.visit(this);
+}
+
+bool RectangularDetectorActor::isChildDetector(const ComponentID &id) const {
+  // ID of the parent RectangularDetector
+  Mantid::Geometry::ComponentID thisID = this->m_id;
+
+  // Get the component object
+  IComponent_const_sptr comp =
+      m_instrActor.getInstrument()->getComponentByID(id);
+  if (comp) {
+    // Get the parent (e.g. the column)
+    IComponent_const_sptr parent1 = comp->getParent();
+    if (parent1) {
+      if (parent1->getComponentID() == thisID) {
+        return true;
+      }
+      // Go to grandparent
+      IComponent_const_sptr parent2 = parent1->getParent();
+      if (parent2) {
+        if (parent2->getComponentID() == thisID) {
+          return true;
+        }
+      } // valid grandparent
+    }   // valid parent
+  }     // valid component
+  return false;
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+* Generate a texture for the RectangularDetector
+*
+* @param image_data :: pointer to where the image data will be filled in.
+* @param list :: Color list iterator. Only used if useDetectorIDs is false.
+* @param useDetectorIDs :: set to true to make a fake texture using the detector
+*IDs. If false, the iterator is used.
+*
+*/
+int RectangularDetectorActor::genTexture(char *&image_data,
+                                         std::vector<GLColor> &list,
+                                         bool useDetectorIDs) {
+  int num = mDet->xpixels() * mDet->ypixels();
+
+  // The texture size must be 2^n power.
+  int text_x_size, text_y_size;
+  mDet->getTextureSize(text_x_size, text_y_size);
+
+  // std::cerr << "Texture size: " << text_x_size << ',' << text_y_size
+  // <<std::endl;
+
+  //------ Create the image data buffer -------
+  if (!image_data) {
+    // Delete the old memory
+    delete[] image_data;
+    image_data = new char[3 * text_x_size * text_y_size];
+  }
+  // Pointer to where we are in it.
+  char *image_data_ptr = image_data;
+
+  // Fill with 0 (black) everywhere
+  std::fill(image_data, image_data + 3 * text_x_size * text_y_size, 0);
+
+  // For using color IDs
+  int rgb = 0;
+  std::vector<GLColor>::iterator list_it = list.begin();
+
+  for (int y = 0; y < mDet->ypixels(); y++) {
+    for (int x = 0; x < mDet->xpixels(); x++) {
+      // Use black as the default color (for going off the edges)
+      unsigned char r, g, b;
+
+      if (useDetectorIDs) {
+        GLColor c = GLActor::makePickColor(m_pickIDs[rgb]);
+        c.get(r, g, b);
+        rgb++;
+      } else {
+        // Get the current color
+        list_it->get(r, g, b);
+        // Go to the next color
+        ++list_it;
+      }
+
+      //      //TEMP: way to show the colors
+      //      r=x;
+      //      g=y;
+      //      b=x;
+
+      // Save the color data to the buffer
+      *image_data_ptr = r;
+      image_data_ptr++;
+      *image_data_ptr = g;
+      image_data_ptr++;
+      *image_data_ptr = b;
+      image_data_ptr++;
+    }
+
+    // Skip any padding in x. 3 bytes per pixel
+    image_data_ptr += 3 * (text_x_size - mDet->xpixels());
+  }
+
+  if (VERBOSE)
+    std::cout << "RectangularDetectorActor::genTexture() called for "
+              << mDet->getName() << " with " << num << " entries set\n";
+
+  return num;
+}
+
+//------------------------------------------------------------------------------------------------
+/** Upload the texture to the video card. */
+void RectangularDetectorActor::uploadTexture(char *&image_data) const {
+  if (!image_data)
+    throw std::runtime_error(
+        "Empty pointer passed to RectangularDetectorActor::uploadTexture()!");
+
+  // The texture size must be 2^n power.
+  int text_x_size, text_y_size;
+  mDet->getTextureSize(text_x_size, text_y_size);
+
+  // Set up before uploading a texture
+  if (mTextureID > 0)
+    glDeleteTextures(1, &mTextureID);
+  glGenTextures(1, &mTextureID); // Create The Texture
+  if (VERBOSE)
+    std::cout << mDet->getName() << " is drawing with texture id " << mTextureID
+              << "\n";
+  // mDet->setTextureID(mTextureID);
+
+  glBindTexture(GL_TEXTURE_2D, mTextureID);
+
+  if (glGetError() > 0)
+    std::cout << "OpenGL error in glBindTexture \n";
+
+  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+
+  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
+            GL_MODULATE); // This one allows lighting effects
+  // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); //This one
+  // doesn't
+
+  // Upload the texture to video card
+  if (glGetError() > 0)
+    std::cout << "OpenGL error BEFORE glTexImage2D \n";
+  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, text_x_size, text_y_size, 0, GL_RGB,
+               GL_UNSIGNED_BYTE, image_data);
+  if (glGetError() > 0)
+    std::cout << "OpenGL error in glTexImage2D \n";
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+* Return the bounding box, from the one calculated in the cache previously.
+* @param minBound :: min point of the bounding box
+* @param maxBound :: max point of the bounding box
+*/
+void RectangularDetectorActor::getBoundingBox(
+    Mantid::Kernel::V3D &minBound, Mantid::Kernel::V3D &maxBound) const {
+  minBound = minBoundBox;
+  maxBound = maxBoundBox;
+}
+
+/**
+* Append the bounding box CompAssembly bounding box
+* @param minBound :: min point of the bounding box
+* @param maxBound :: max point of the bounding box
+*/
+void RectangularDetectorActor::AppendBoundingBox(
+    const Mantid::Kernel::V3D &minBound, const Mantid::Kernel::V3D &maxBound) {
+  if (minBoundBox[0] > minBound[0])
+    minBoundBox[0] = minBound[0];
+  if (minBoundBox[1] > minBound[1])
+    minBoundBox[1] = minBound[1];
+  if (minBoundBox[2] > minBound[2])
+    minBoundBox[2] = minBound[2];
+  if (maxBoundBox[0] < maxBound[0])
+    maxBoundBox[0] = maxBound[0];
+  if (maxBoundBox[1] < maxBound[1])
+    maxBoundBox[1] = maxBound[1];
+  if (maxBoundBox[2] < maxBound[2])
+    maxBoundBox[2] = maxBound[2];
+}
+
+void RectangularDetectorActor::setColors() {
+  std::vector<GLColor> clist;
+  for (int y = 0; y < mDet->ypixels(); y++) {
+    for (int x = 0; x < mDet->xpixels(); x++) {
+      detid_t id = mDet->getDetectorIDAtXY(x, y);
+      clist.push_back(m_instrActor.getColor(id));
+    }
+  }
+  genTexture(image_data, clist, false);
+  uploadTexture(image_data);
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/RotationSurface.cpp b/MantidQt/MantidWidgets/src/InstrumentView/RotationSurface.cpp
index 3ee01624b056271b937b580cc753e7ced6dd257b..f823441a47e78b69d3d664a397974467bb17df87 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/RotationSurface.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/RotationSurface.cpp
@@ -9,343 +9,311 @@ using namespace Mantid::Geometry;
 
 namespace {
 // The logger object
-  Mantid::Kernel::Logger g_log("RotationSurface");
+Mantid::Kernel::Logger g_log("RotationSurface");
 }
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		RotationSurface::RotationSurface(const InstrumentActor* rootActor, const Mantid::Kernel::V3D& origin, const Mantid::Kernel::V3D& axis) :
-			UnwrappedSurface(rootActor),
-			m_pos(origin),
-			m_zaxis(axis),
-			m_manual_u_correction(false)
-		{
-		}
-
-		/**
-		* Initialize the surface.
-		*/
-		void RotationSurface::init()
-		{
-			// the actor calls this->callback for each detector
-			m_unwrappedDetectors.clear();
-			m_assemblies.clear();
-
-			// if u-correction is applied manually then m_u_min and m_u_max
-			// have valid values and have to be saved
-			double manual_u_min = m_u_min;
-			double manual_u_max = m_u_max;
-
-			size_t ndet = m_instrActor->ndetectors();
-			m_unwrappedDetectors.resize(ndet);
-			if (ndet == 0) return;
-
-			// Pre-calculate all the detector positions (serial because
-			// I suspect the IComponent->getPos() method to not be properly thread safe)
-			m_instrActor->cacheDetPos();
-
-			Instrument_const_sptr inst = m_instrActor->getInstrument();
-
-			// First detector defines the surface's x axis
-			if (m_xaxis.nullVector())
-			{
-				Mantid::Kernel::V3D pos = m_instrActor->getDetPos(0) - m_pos;
-				double z = pos.scalar_prod(m_zaxis);
-				if (z == 0.0 || fabs(z) == pos.norm())
-				{
-					// find the shortest projection of m_zaxis and direct m_xaxis along it
-					bool isY = false;
-					bool isZ = false;
-					if (fabs(m_zaxis.Y()) < fabs(m_zaxis.X())) isY = true;
-					if (fabs(m_zaxis.Z()) < fabs(m_zaxis.Y())) isZ = true;
-					if (isZ)
-					{
-						m_xaxis = Mantid::Kernel::V3D(0, 0, 1);
-					}
-					else if (isY)
-					{
-						m_xaxis = Mantid::Kernel::V3D(0, 1, 0);
-					}
-					else
-					{
-						m_xaxis = Mantid::Kernel::V3D(1, 0, 0);
-					}
-				}
-				else
-				{
-					m_xaxis = pos - m_zaxis * z;
-					m_xaxis.normalize();
-				}
-				m_yaxis = m_zaxis.cross_prod(m_xaxis);
-			}
-
-			// give some valid values to u bounds in case some code checks
-			// on u to be within them
-			m_u_min = -DBL_MAX;
-			m_u_max = DBL_MAX;
-
-			// Set if one of the threads in the following loop
-			// throws an exception
-			bool exceptionThrown = false;
-
-			// For each detector in the order of actors
-			// cppcheck-suppress syntaxError
-			PRAGMA_OMP(parallel for)
-				for (int ii = 0; ii < int(ndet); ++ii)
-				{
-					if (!exceptionThrown)
-						try {
-						size_t i = size_t(ii);
-
-						unsigned char color[3];
-						Mantid::detid_t id = m_instrActor->getDetID(i);
-
-						boost::shared_ptr<const Mantid::Geometry::IDetector> det;
-						try
-						{
-							det = inst->getDetector(id);
-						}
-						catch (Mantid::Kernel::Exception::NotFoundError &)
-						{
-						}
-
-						if (!det || det->isMonitor() || (id < 0))
-						{
-							// Not a detector or a monitor
-							// Make some blank, empty thing that won't draw
-							m_unwrappedDetectors[i] = UnwrappedDetector();
-						}
-						else
-						{
-							// A real detector.
-							m_instrActor->getColor(id).getUB3(&color[0]);
-
-							// Position, relative to origin
-							//Mantid::Kernel::V3D pos = det->getPos() - m_pos;
-							Mantid::Kernel::V3D pos = m_instrActor->getDetPos(i) - m_pos;
-
-							// Create the unwrapped shape
-							UnwrappedDetector udet(&color[0], det);
-							// Calculate its position/size in UV coordinates
-							this->calcUV(udet, pos);
-
-							m_unwrappedDetectors[i] = udet;
-						} // is a real detectord
-					}
-					catch (std::exception & e)
-					{
-						// stop executing the body of the loop
-						exceptionThrown = true;
-						g_log.error() << e.what() << std::endl;
-					}
-					catch (...)
-					{
-						// stop executing the body of the loop
-						exceptionThrown = true;
-						g_log.error("Unknown exception thrown.");
-					}
-				} // for each detector in pick order
-
-					// if the loop above has thrown stop execution
-			if (exceptionThrown)
-			{
-				throw std::runtime_error("An exception was thrown. See log for detail.");
-			}
-
-			// find the overall edges in u and v coords
-			findUVBounds();
-
-			// apply a shift in u-coord either found automatically
-			// or set manually
-			if (!m_manual_u_correction)
-			{
-				// automatic gap correction
-				findAndCorrectUGap();
-			}
-			else
-			{
-				// apply manually set shift
-				m_u_min = manual_u_min;
-				m_u_max = manual_u_max;
-				for (size_t i = 0; i<m_unwrappedDetectors.size(); ++i)
-				{
-					auto &udet = m_unwrappedDetectors[i];
-					udet.u = applyUCorrection(udet.u);
-				}
-			}
-
-			double dU = fabs(m_u_max - m_u_min);
-			double dV = fabs(m_v_max - m_v_min);
-			double du = dU * 0.05;
-			double dv = dV * 0.05;
-			if (m_width_max > du && m_width_max != std::numeric_limits<double>::infinity())
-			{
-				if (du > 0 && !(dU >= m_width_max))
-				{
-					m_width_max = dU;
-				}
-				du = m_width_max;
-			}
-			if (m_height_max > dv && m_height_max != std::numeric_limits<double>::infinity())
-			{
-				if (dv > 0 && !(dV >= m_height_max))
-				{
-					m_height_max = dV;
-				}
-				dv = m_height_max;
-			}
-
-			m_viewRect = RectF(QPointF(m_u_min - du, m_v_min - dv), QPointF(m_u_max + du, m_v_max + dv));
-
-		}
-
-		void RotationSurface::findUVBounds()
-		{
-			m_u_min = DBL_MAX;
-			m_u_max = -DBL_MAX;
-			m_v_min = DBL_MAX;
-			m_v_max = -DBL_MAX;
-			for (size_t i = 0; i<m_unwrappedDetectors.size(); ++i)
-			{
-				const UnwrappedDetector& udet = m_unwrappedDetectors[i];
-				if (!udet.detector) continue;
-				if (udet.u < m_u_min) m_u_min = udet.u;
-				if (udet.u > m_u_max) m_u_max = udet.u;
-				if (udet.v < m_v_min) m_v_min = udet.v;
-				if (udet.v > m_v_max) m_v_max = udet.v;
-			}
-		}
-
-		void RotationSurface::findAndCorrectUGap()
-		{
-			double period = uPeriod();
-			if (period == 0.0) return;
-			const int nbins = 1000;
-			std::vector<bool> ubins(nbins);
-			double bin_width = fabs(m_u_max - m_u_min) / (nbins - 1);
-			if (bin_width == 0.0)
-			{
-				QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
-				QMessageBox::warning(NULL, tr("MantidPLot - Instrument view error"), tr("Failed to build unwrapped surface"));
-				QApplication::restoreOverrideCursor();
-				m_u_min = 0.0;
-				m_u_max = 1.0;
-				return;
-			}
-
-			std::vector<UnwrappedDetector>::const_iterator ud = m_unwrappedDetectors.begin();
-			for (; ud != m_unwrappedDetectors.end(); ++ud)
-			{
-				if (!ud->detector) continue;
-				double u = ud->u;
-				int i = int((u - m_u_min) / bin_width);
-				ubins[i] = true;
-			}
-
-			int iFrom = 0; // marks gap start
-			int iTo = 0; // marks gap end
-			int i0 = 0;
-			bool inGap = false;
-			for (int i = 0; i < int(ubins.size()) - 1; ++i)
-			{
-				if (!ubins[i])
-				{
-					if (!inGap)
-					{
-						i0 = i;
-					}
-					inGap = true;
-				}
-				else
-				{
-					if (inGap && iTo - iFrom < i - i0)
-					{
-						iFrom = i0; // first bin in the gap
-						iTo = i;  // first bin after the gap
-					}
-					inGap = false;
-				}
-			}
-
-			double uFrom = m_u_min + iFrom * bin_width;
-			double uTo = m_u_min + iTo   * bin_width;
-			if (uTo - uFrom > period - (m_u_max - m_u_min))
-			{
-
-				m_u_max = uFrom;
-				m_u_min = uTo;
-				if (m_u_min > m_u_max)
-				{
-					m_u_max += period;
-				}
-
-				std::vector<UnwrappedDetector>::iterator ud = m_unwrappedDetectors.begin();
-				for (; ud != m_unwrappedDetectors.end(); ++ud)
-				{
-					if (!ud->detector) continue;
-					double& u = ud->u;
-					u = applyUCorrection(u);
-				}
-
-			}
-		}
-
-		/**
-		* Apply a correction to u value of a projected point due to
-		* change of u-scale by findAndCorrectUGap()
-		* @param u :: u-coordinate to be corrected
-		* @return :: Corrected u-coordinate.
-		*/
-		double RotationSurface::applyUCorrection(double u)const
-		{
-			double period = uPeriod();
-			if (period == 0.0) return u;
-			if (u < m_u_min)
-			{
-				double periods = floor((m_u_max - u) / period) * period;
-				u += periods;
-			}
-			if (u > m_u_max)
-			{
-				double periods = floor((u - m_u_min) / period) * period;
-				u -= periods;
-			}
-			return u;
-		}
-
-		/**
-		* Set new value for the u-correction.
-		* Correct all uv corrdinates of detectors.
-		*/
-		void RotationSurface::setUCorrection(double umin, double umax)
-		{
-			m_u_min = umin;
-			m_u_max = umax;
-			double period = uPeriod();
-			double du = m_u_max - m_u_min;
-			if (du > period * 1.1)
-			{
-				m_u_max -= floor(du / period) * period;
-			}
-			while (m_u_min >= m_u_max)
-			{
-				m_u_max += period;
-			}
-			m_manual_u_correction = true;
-			updateDetectors();
-		}
-
-		/**
-		* Set automatic u-correction
-		*/
-		void RotationSurface::setAutomaticUCorrection()
-		{
-			m_manual_u_correction = false;
-			updateDetectors();
-		}
-
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+RotationSurface::RotationSurface(const InstrumentActor *rootActor,
+                                 const Mantid::Kernel::V3D &origin,
+                                 const Mantid::Kernel::V3D &axis)
+    : UnwrappedSurface(rootActor), m_pos(origin), m_zaxis(axis),
+      m_manual_u_correction(false) {}
+
+/**
+* Initialize the surface.
+*/
+void RotationSurface::init() {
+  // the actor calls this->callback for each detector
+  m_unwrappedDetectors.clear();
+  m_assemblies.clear();
+
+  // if u-correction is applied manually then m_u_min and m_u_max
+  // have valid values and have to be saved
+  double manual_u_min = m_u_min;
+  double manual_u_max = m_u_max;
+
+  size_t ndet = m_instrActor->ndetectors();
+  m_unwrappedDetectors.resize(ndet);
+  if (ndet == 0)
+    return;
+
+  // Pre-calculate all the detector positions (serial because
+  // I suspect the IComponent->getPos() method to not be properly thread safe)
+  m_instrActor->cacheDetPos();
+
+  Instrument_const_sptr inst = m_instrActor->getInstrument();
+
+  // First detector defines the surface's x axis
+  if (m_xaxis.nullVector()) {
+    Mantid::Kernel::V3D pos = m_instrActor->getDetPos(0) - m_pos;
+    double z = pos.scalar_prod(m_zaxis);
+    if (z == 0.0 || fabs(z) == pos.norm()) {
+      // find the shortest projection of m_zaxis and direct m_xaxis along it
+      bool isY = false;
+      bool isZ = false;
+      if (fabs(m_zaxis.Y()) < fabs(m_zaxis.X()))
+        isY = true;
+      if (fabs(m_zaxis.Z()) < fabs(m_zaxis.Y()))
+        isZ = true;
+      if (isZ) {
+        m_xaxis = Mantid::Kernel::V3D(0, 0, 1);
+      } else if (isY) {
+        m_xaxis = Mantid::Kernel::V3D(0, 1, 0);
+      } else {
+        m_xaxis = Mantid::Kernel::V3D(1, 0, 0);
+      }
+    } else {
+      m_xaxis = pos - m_zaxis * z;
+      m_xaxis.normalize();
+    }
+    m_yaxis = m_zaxis.cross_prod(m_xaxis);
+  }
+
+  // give some valid values to u bounds in case some code checks
+  // on u to be within them
+  m_u_min = -DBL_MAX;
+  m_u_max = DBL_MAX;
+
+  // Set if one of the threads in the following loop
+  // throws an exception
+  bool exceptionThrown = false;
+
+  // For each detector in the order of actors
+  // cppcheck-suppress syntaxError
+                        PRAGMA_OMP(parallel for)
+                        for (int ii = 0; ii < int(ndet); ++ii) {
+                          if (!exceptionThrown)
+                            try {
+                              size_t i = size_t(ii);
+
+                              unsigned char color[3];
+                              Mantid::detid_t id = m_instrActor->getDetID(i);
+
+                              boost::shared_ptr<
+                                  const Mantid::Geometry::IDetector> det;
+                              try {
+                                det = inst->getDetector(id);
+                              } catch (
+                                  Mantid::Kernel::Exception::NotFoundError &) {
+                              }
+
+                              if (!det || det->isMonitor() || (id < 0)) {
+                                // Not a detector or a monitor
+                                // Make some blank, empty thing that won't draw
+                                m_unwrappedDetectors[i] = UnwrappedDetector();
+                              } else {
+                                // A real detector.
+                                m_instrActor->getColor(id).getUB3(&color[0]);
+
+                                // Position, relative to origin
+                                // Mantid::Kernel::V3D pos = det->getPos() -
+                                // m_pos;
+                                Mantid::Kernel::V3D pos =
+                                    m_instrActor->getDetPos(i) - m_pos;
+
+                                // Create the unwrapped shape
+                                UnwrappedDetector udet(&color[0], det);
+                                // Calculate its position/size in UV coordinates
+                                this->calcUV(udet, pos);
+
+                                m_unwrappedDetectors[i] = udet;
+                              } // is a real detectord
+                            } catch (std::exception &e) {
+                              // stop executing the body of the loop
+                              exceptionThrown = true;
+                              g_log.error() << e.what() << std::endl;
+                            } catch (...) {
+                              // stop executing the body of the loop
+                              exceptionThrown = true;
+                              g_log.error("Unknown exception thrown.");
+                            }
+                        } // for each detector in pick order
+
+                        // if the loop above has thrown stop execution
+                        if (exceptionThrown) {
+                          throw std::runtime_error(
+                              "An exception was thrown. See log for detail.");
+                        }
+
+                        // find the overall edges in u and v coords
+                        findUVBounds();
+
+                        // apply a shift in u-coord either found automatically
+                        // or set manually
+                        if (!m_manual_u_correction) {
+                          // automatic gap correction
+                          findAndCorrectUGap();
+                        } else {
+                          // apply manually set shift
+                          m_u_min = manual_u_min;
+                          m_u_max = manual_u_max;
+                          for (size_t i = 0; i < m_unwrappedDetectors.size();
+                               ++i) {
+                            auto &udet = m_unwrappedDetectors[i];
+                            udet.u = applyUCorrection(udet.u);
+                          }
+                        }
+
+                        double dU = fabs(m_u_max - m_u_min);
+                        double dV = fabs(m_v_max - m_v_min);
+                        double du = dU * 0.05;
+                        double dv = dV * 0.05;
+                        if (m_width_max > du &&
+                            m_width_max !=
+                                std::numeric_limits<double>::infinity()) {
+                          if (du > 0 && !(dU >= m_width_max)) {
+                            m_width_max = dU;
+                          }
+                          du = m_width_max;
+                        }
+                        if (m_height_max > dv &&
+                            m_height_max !=
+                                std::numeric_limits<double>::infinity()) {
+                          if (dv > 0 && !(dV >= m_height_max)) {
+                            m_height_max = dV;
+                          }
+                          dv = m_height_max;
+                        }
+
+                        m_viewRect = RectF(QPointF(m_u_min - du, m_v_min - dv),
+                                           QPointF(m_u_max + du, m_v_max + dv));
+}
+
+void RotationSurface::findUVBounds() {
+  m_u_min = DBL_MAX;
+  m_u_max = -DBL_MAX;
+  m_v_min = DBL_MAX;
+  m_v_max = -DBL_MAX;
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    const UnwrappedDetector &udet = m_unwrappedDetectors[i];
+    if (!udet.detector)
+      continue;
+    if (udet.u < m_u_min)
+      m_u_min = udet.u;
+    if (udet.u > m_u_max)
+      m_u_max = udet.u;
+    if (udet.v < m_v_min)
+      m_v_min = udet.v;
+    if (udet.v > m_v_max)
+      m_v_max = udet.v;
+  }
+}
+
+void RotationSurface::findAndCorrectUGap() {
+  double period = uPeriod();
+  if (period == 0.0)
+    return;
+  const int nbins = 1000;
+  std::vector<bool> ubins(nbins);
+  double bin_width = fabs(m_u_max - m_u_min) / (nbins - 1);
+  if (bin_width == 0.0) {
+    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
+    QMessageBox::warning(NULL, tr("MantidPLot - Instrument view error"),
+                         tr("Failed to build unwrapped surface"));
+    QApplication::restoreOverrideCursor();
+    m_u_min = 0.0;
+    m_u_max = 1.0;
+    return;
+  }
+
+  std::vector<UnwrappedDetector>::const_iterator ud =
+      m_unwrappedDetectors.begin();
+  for (; ud != m_unwrappedDetectors.end(); ++ud) {
+    if (!ud->detector)
+      continue;
+    double u = ud->u;
+    int i = int((u - m_u_min) / bin_width);
+    ubins[i] = true;
+  }
+
+  int iFrom = 0; // marks gap start
+  int iTo = 0;   // marks gap end
+  int i0 = 0;
+  bool inGap = false;
+  for (int i = 0; i < int(ubins.size()) - 1; ++i) {
+    if (!ubins[i]) {
+      if (!inGap) {
+        i0 = i;
+      }
+      inGap = true;
+    } else {
+      if (inGap && iTo - iFrom < i - i0) {
+        iFrom = i0; // first bin in the gap
+        iTo = i;    // first bin after the gap
+      }
+      inGap = false;
+    }
+  }
+
+  double uFrom = m_u_min + iFrom * bin_width;
+  double uTo = m_u_min + iTo * bin_width;
+  if (uTo - uFrom > period - (m_u_max - m_u_min)) {
+
+    m_u_max = uFrom;
+    m_u_min = uTo;
+    if (m_u_min > m_u_max) {
+      m_u_max += period;
+    }
+
+    std::vector<UnwrappedDetector>::iterator ud = m_unwrappedDetectors.begin();
+    for (; ud != m_unwrappedDetectors.end(); ++ud) {
+      if (!ud->detector)
+        continue;
+      double &u = ud->u;
+      u = applyUCorrection(u);
+    }
+  }
+}
+
+/**
+* Apply a correction to u value of a projected point due to
+* change of u-scale by findAndCorrectUGap()
+* @param u :: u-coordinate to be corrected
+* @return :: Corrected u-coordinate.
+*/
+double RotationSurface::applyUCorrection(double u) const {
+  double period = uPeriod();
+  if (period == 0.0)
+    return u;
+  if (u < m_u_min) {
+    double periods = floor((m_u_max - u) / period) * period;
+    u += periods;
+  }
+  if (u > m_u_max) {
+    double periods = floor((u - m_u_min) / period) * period;
+    u -= periods;
+  }
+  return u;
+}
+
+/**
+* Set new value for the u-correction.
+* Correct all uv corrdinates of detectors.
+*/
+void RotationSurface::setUCorrection(double umin, double umax) {
+  m_u_min = umin;
+  m_u_max = umax;
+  double period = uPeriod();
+  double du = m_u_max - m_u_min;
+  if (du > period * 1.1) {
+    m_u_max -= floor(du / period) * period;
+  }
+  while (m_u_min >= m_u_max) {
+    m_u_max += period;
+  }
+  m_manual_u_correction = true;
+  updateDetectors();
+}
+
+/**
+* Set automatic u-correction
+*/
+void RotationSurface::setAutomaticUCorrection() {
+  m_manual_u_correction = false;
+  updateDetectors();
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/SampleActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/SampleActor.cpp
index c767ca394966db74374ee3ff3b0c13106f672565..ba91244b8784e951d646b8c99ed05852cc24532b 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/SampleActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/SampleActor.cpp
@@ -8,55 +8,44 @@
 using namespace Mantid;
 using namespace Geometry;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		SampleActor::SampleActor(const InstrumentActor& instrActor,
-			const Mantid::API::Sample& sample,
-			const ObjComponentActor* samplePosActor)
-			: GLActor(),
-			m_instrActor(instrActor),
-			m_sample(sample),
-			m_samplePosActor(samplePosActor),
-			m_samplePos(samplePosActor->getObjComponent()),
-			m_color(255, 255, 255)
-		{
-		}
+SampleActor::SampleActor(const InstrumentActor &instrActor,
+                         const Mantid::API::Sample &sample,
+                         const ObjComponentActor *samplePosActor)
+    : GLActor(), m_instrActor(instrActor), m_sample(sample),
+      m_samplePosActor(samplePosActor),
+      m_samplePos(samplePosActor->getObjComponent()), m_color(255, 255, 255) {}
 
-		/**
-		* Implementation of rendering Sample.
-		*/
-		void SampleActor::draw(bool picking)const
-		{
-			if (!picking && isVisible())
-			{
-				OpenGLError::check("SampleActor::draw()");
-				glPushAttrib(GL_ENABLE_BIT);
-				GLboolean hasLight0;
-				glGetBooleanv(GL_LIGHT0, &hasLight0);
-				if (hasLight0)
-				{
-					glEnable(GL_LIGHTING);
-				}
-				glPushMatrix();
-				m_color.paint();
-				Mantid::Kernel::V3D pos = m_samplePos->getPos();
-				glTranslated(pos.X(), pos.Y(), pos.Z());
-				m_sample.getShape().draw();
-				glPopMatrix();
-				glPopAttrib();
-				OpenGLError::check("SampleActor::draw()");
-			}
-		}
-
-		void SampleActor::getBoundingBox(Mantid::Kernel::V3D& minBound, Mantid::Kernel::V3D& maxBound)const
-		{
-			Mantid::Geometry::BoundingBox boundBox = m_sample.getShape().getBoundingBox();
-			minBound = boundBox.minPoint();
-			maxBound = boundBox.maxPoint();
-		}
-	}//MantidWidgets
-}//MantidQt
+/**
+* Implementation of rendering Sample.
+*/
+void SampleActor::draw(bool picking) const {
+  if (!picking && isVisible()) {
+    OpenGLError::check("SampleActor::draw()");
+    glPushAttrib(GL_ENABLE_BIT);
+    GLboolean hasLight0;
+    glGetBooleanv(GL_LIGHT0, &hasLight0);
+    if (hasLight0) {
+      glEnable(GL_LIGHTING);
+    }
+    glPushMatrix();
+    m_color.paint();
+    Mantid::Kernel::V3D pos = m_samplePos->getPos();
+    glTranslated(pos.X(), pos.Y(), pos.Z());
+    m_sample.getShape().draw();
+    glPopMatrix();
+    glPopAttrib();
+    OpenGLError::check("SampleActor::draw()");
+  }
+}
 
+void SampleActor::getBoundingBox(Mantid::Kernel::V3D &minBound,
+                                 Mantid::Kernel::V3D &maxBound) const {
+  Mantid::Geometry::BoundingBox boundBox = m_sample.getShape().getBoundingBox();
+  minBound = boundBox.minPoint();
+  maxBound = boundBox.maxPoint();
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/Shape2D.cpp b/MantidQt/MantidWidgets/src/InstrumentView/Shape2D.cpp
index 4b66cc2f12899ad3f21c3bb8bfcd7b49a23359a6..0a945442bdf6d6ef93e01162cf2aa919a2db1778 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/Shape2D.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/Shape2D.cpp
@@ -12,639 +12,564 @@
 #include <stdexcept>
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		// number of control points common for all shapes
-		const size_t Shape2D::NCommonCP = 4;
-		// size (== width/2 == height/2) of each control point
-		const double Shape2D::sizeCP = 3;
-
-		/**
-		* Set default border color to red and fill color to default Qt color (==QColor()).
-		*/
-		Shape2D::Shape2D() :
-			m_color(Qt::red),
-			m_fill_color(QColor()),
-			m_scalable(true),
-			m_editing(false),
-			m_selected(false),
-			m_visible(true)
-		{
-		}
-
-		/**
-		* Calls virtual drawShape() method to draw the actial shape.
-		* Draws bounding rect and control points if the shape is selected.
-		*
-		* @param painter :: QPainter used for drawing.
-		*/
-		void Shape2D::draw(QPainter& painter) const
-		{
-			if (!m_visible) return;
-			painter.setPen(m_color);
-			this->drawShape(painter);
-			if (m_editing || m_selected)
-			{
-				QColor c(255, 255, 255, 100);
-				painter.setPen(c);
-				painter.drawRect(m_boundingRect.toQRectF());
-				size_t np = NCommonCP;
-				double rsize = 2;
-				int alpha = 100;
-				if (m_editing)
-				{
-					// if editing show all CP, make them bigger and opaque
-					np = getNControlPoints();
-					rsize = sizeCP;
-					alpha = 255;
-				}
-				for (size_t i = 0; i < np; ++i)
-				{
-					QPointF p = painter.transform().map(getControlPoint(i));
-					QRectF r(p - QPointF(rsize, rsize), p + QPointF(rsize, rsize));
-					painter.save();
-					painter.resetTransform();
-					QColor c(255, 255, 255, alpha);
-					painter.fillRect(r, c);
-					r.adjust(-1, -1, 0, 0);
-					painter.setPen(QColor(0, 0, 0, alpha));
-					painter.drawRect(r);
-					painter.restore();
-				}
-			}
-		}
-
-		/**
-		* Return total number of control points for this shape.
-		*/
-		size_t Shape2D::getNControlPoints() const
-		{
-			return NCommonCP + this->getShapeNControlPoints();
-		}
-
-		/**
-		* Return coordinates of i-th control point.
-		*
-		* @param i :: Index of a control point. 0 <= i < getNControlPoints().
-		*/
-		QPointF Shape2D::getControlPoint(size_t i) const
-		{
-			if (i >= getNControlPoints())
-			{
-				throw std::range_error("Control point index is out of range");
-			}
-
-			if (i < 4) return m_boundingRect.vertex(i);
-
-			return getShapeControlPoint(i - NCommonCP);
-		}
-
-		void Shape2D::setControlPoint(size_t i, const QPointF& pos)
-		{
-			if (i >= getNControlPoints())
-			{
-				throw std::range_error("Control point index is out of range");
-			}
-
-			if (i < 4)
-			{
-				m_boundingRect.setVertex(i, pos);
-				refit();
-			}
-			// else ?
-			else
-				setShapeControlPoint(i - NCommonCP, pos);
-			resetBoundingRect();
-		}
-
-		/**
-		* Move the shape.
-		*
-		* @param dp :: The shift vector.
-		*/
-		void Shape2D::moveBy(const QPointF& dp)
-		{
-			m_boundingRect.translate(dp);
-			refit();
-		}
-
-		/**
-		* Adjust the bound of the bounding rect. Calls virtual method refit()
-		* to resize the shape in order to fit into the new bounds.
-		*/
-		void Shape2D::adjustBoundingRect(double dx1, double dy1, double dx2, double dy2)
-		{
-			double dwidth = dx2 - dx1;
-			if (dwidth <= -m_boundingRect.xSpan())
-			{
-				double mu = m_boundingRect.xSpan() / fabs(dwidth);
-				dx1 *= mu;
-				dx2 *= mu;
-			}
-			double dheight = dy2 - dy1;
-			if (dheight <= -m_boundingRect.ySpan())
-			{
-				double mu = m_boundingRect.ySpan() / fabs(dheight);
-				dy1 *= mu;
-				dy2 *= mu;
-			}
-			m_boundingRect.adjust(QPointF(dx1, dy1), QPointF(dx2, dy2));
-			refit();
-		}
-
-		/**
-		* Assign new bounding rect. Calls virtual method refit()
-		* to resize the shape in order to fit into the new bounds.
-		*/
-		void Shape2D::setBoundingRect(const RectF &rect)
-		{
-			m_boundingRect = rect;
-			refit();
-		}
-
-		/**
-		* Check if the shape masks a point.
-		*
-		* @param p :: Point to check.
-		*/
-		bool Shape2D::isMasked(const QPointF& p)const
-		{
-			return m_fill_color != QColor() && contains(p);
-		}
-
-		// --- Shape2DEllipse --- //
-
-		Shape2DEllipse::Shape2DEllipse(const QPointF& center, double radius1, double radius2)
-			:Shape2D()
-		{
-			if (radius2 == 0)
-			{
-				radius2 = radius1;
-			}
-			QPointF dr(radius1, radius2);
-			m_boundingRect = RectF(center - dr, center + dr);
-		}
-
-		void Shape2DEllipse::drawShape(QPainter& painter) const
-		{
-			QRectF drawRect = m_boundingRect.toQRectF();
-			painter.drawEllipse(drawRect);
-			if (m_fill_color != QColor())
-			{
-				QPainterPath path;
-				path.addEllipse(drawRect);
-				painter.fillPath(path, m_fill_color);
-			}
-		}
-
-		void Shape2DEllipse::addToPath(QPainterPath& path) const
-		{
-			path.addEllipse(m_boundingRect.toQRectF());
-		}
-
-		bool Shape2DEllipse::selectAt(const QPointF& p)const
-		{
-			if (m_fill_color != QColor())
-			{// filled ellipse
-				return contains(p);
-			}
-
-			double a = m_boundingRect.xSpan() / 2;
-			if (a == 0.0) a = 1.0;
-			double b = m_boundingRect.ySpan() / 2;
-			if (b == 0.0) b = 1.0;
-			double xx = m_boundingRect.x0() + a - double(p.x());
-			double yy = m_boundingRect.y0() + b - double(p.y());
-
-			double f = fabs(xx*xx / (a*a) + yy*yy / (b*b) - 1);
-
-			return f < 0.1;
-		}
-
-		bool Shape2DEllipse::contains(const QPointF& p)const
-		{
-			if (m_boundingRect.isEmpty()) return false;
-			QPointF pp = m_boundingRect.center() - p;
-			double a = m_boundingRect.xSpan() / 2;
-			if (a == 0.0) a = 1.0;
-			double b = m_boundingRect.ySpan() / 2;
-			if (b == 0.0) b = 1.0;
-			double xx = pp.x();
-			double yy = pp.y();
-
-			double f = xx*xx / (a*a) + yy*yy / (b*b);
-
-			return f <= 1.0;
-		}
-
-		QStringList Shape2DEllipse::getDoubleNames()const
-		{
-			QStringList res;
-			res << "radius1" << "radius2";
-			return res;
-		}
-
-		double Shape2DEllipse::getDouble(const QString& prop) const
-		{
-			if (prop == "radius1")
-			{
-				return m_boundingRect.width() / 2;
-			}
-			else if (prop == "radius2")
-			{
-				return m_boundingRect.height() / 2;
-			}
-			return 0.0;
-		}
-
-		void Shape2DEllipse::setDouble(const QString& prop, double value)
-		{
-			if (prop == "radius1")
-			{
-				if (value <= 0.0) value = 1.0;
-				double d = value - m_boundingRect.width() / 2;
-				adjustBoundingRect(-d, 0, d, 0);
-			}
-			else if (prop == "radius2")
-			{
-				if (value <= 0.0) value = 1.0;
-				double d = value - m_boundingRect.height() / 2;
-				adjustBoundingRect(0, -d, 0, d);
-			}
-		}
-
-		QPointF Shape2DEllipse::getPoint(const QString& prop) const
-		{
-			if (prop == "center" || prop == "centre")
-			{
-				return m_boundingRect.center();
-			}
-			return QPointF();
-		}
-
-		void Shape2DEllipse::setPoint(const QString& prop, const QPointF& value)
-		{
-			if (prop == "center" || prop == "centre")
-			{
-				m_boundingRect.moveCenter(value);
-			}
-		}
-
-
-		// --- Shape2DRectangle --- //
-
-		Shape2DRectangle::Shape2DRectangle()
-		{
-			m_boundingRect = RectF();
-		}
-
-		Shape2DRectangle::Shape2DRectangle(const QPointF& p0, const QPointF& p1)
-		{
-			m_boundingRect = RectF(p0, p1);
-		}
-
-		Shape2DRectangle::Shape2DRectangle(const QPointF& p0, const QSizeF& size)
-		{
-			m_boundingRect = RectF(p0, size);
-		}
-
-		bool Shape2DRectangle::selectAt(const QPointF& p)const
-		{
-			if (m_fill_color != QColor())
-			{// filled rectangle
-				return contains(p);
-			}
-
-			RectF outer(m_boundingRect);
-			outer.adjust(QPointF(-2, -2), QPointF(2, 2));
-			RectF inner(m_boundingRect);
-			inner.adjust(QPointF(2, 2), QPointF(-2, -2));
-			return outer.contains(p) && !inner.contains(p);
-		}
-
-		void Shape2DRectangle::drawShape(QPainter& painter) const
-		{
-			QRectF drawRect = m_boundingRect.toQRectF();
-			painter.drawRect(drawRect);
-			if (m_fill_color != QColor())
-			{
-				QPainterPath path;
-				path.addRect(drawRect);
-				painter.fillPath(path, m_fill_color);
-			}
-		}
-
-		void Shape2DRectangle::addToPath(QPainterPath& path) const
-		{
-			path.addRect(m_boundingRect.toQRectF());
-		}
-
-		// --- Shape2DRing --- //
-
-		Shape2DRing::Shape2DRing(Shape2D* shape, double xWidth, double yWidth) :
-			m_outer_shape(shape),
-			m_xWidth(xWidth),
-			m_yWidth(yWidth)
-		{
-			m_inner_shape = m_outer_shape->clone();
-			m_inner_shape->getBoundingRect();
-			m_inner_shape->adjustBoundingRect(m_xWidth, m_yWidth, -m_xWidth, -m_yWidth);
-			resetBoundingRect();
-			m_outer_shape->setFillColor(QColor());
-			m_inner_shape->setFillColor(QColor());
-		}
-
-		Shape2DRing::Shape2DRing(const Shape2DRing& ring) :
-			Shape2D(),
-			m_outer_shape(ring.m_outer_shape->clone()),
-			m_inner_shape(ring.m_inner_shape->clone()),
-			m_xWidth(ring.m_xWidth),
-			m_yWidth(ring.m_yWidth)
-		{
-			resetBoundingRect();
-		}
-
-		bool Shape2DRing::selectAt(const QPointF& p)const
-		{
-			return contains(p);
-		}
-
-		bool Shape2DRing::contains(const QPointF& p)const
-		{
-			return m_outer_shape->contains(p) && !m_inner_shape->contains(p);
-		}
-
-		void Shape2DRing::drawShape(QPainter& painter) const
-		{
-			m_outer_shape->draw(painter);
-			m_inner_shape->draw(painter);
-			if (m_fill_color != QColor())
-			{
-				QPainterPath path;
-				m_outer_shape->addToPath(path);
-				m_inner_shape->addToPath(path);
-				painter.fillPath(path, m_fill_color);
-			}
-		}
-
-		void Shape2DRing::refit()
-		{
-			if (m_xWidth <= 0) m_xWidth = 0.000001;
-			if (m_yWidth <= 0) m_yWidth = 0.000001;
-			double xWidth = m_xWidth;
-			double yWidth = m_yWidth;
-			double max_width = m_boundingRect.width() / 2;
-			if (xWidth > max_width) xWidth = max_width;
-			double max_height = m_boundingRect.height() / 2;
-			if (yWidth > max_height) yWidth = max_height;
-			m_outer_shape->setBoundingRect(m_boundingRect);
-			m_inner_shape->setBoundingRect(m_boundingRect);
-			m_inner_shape->adjustBoundingRect(xWidth, yWidth, -xWidth, -yWidth);
-		}
-
-		void Shape2DRing::resetBoundingRect()
-		{
-			m_boundingRect = m_outer_shape->getBoundingRect();
-		}
-
-		QPointF Shape2DRing::getShapeControlPoint(size_t i) const
-		{
-			RectF rect = m_inner_shape->getBoundingRect();
-			switch (i)
-			{
-			case 0: return QPointF(rect.center().x(), rect.y1());
-			case 1: return QPointF(rect.center().x(), rect.y0());
-			case 2: return QPointF(rect.x0(), rect.center().y());
-			case 3: return QPointF(rect.x1(), rect.center().y());
-			}
-			return QPointF();
-		}
-
-		void Shape2DRing::setShapeControlPoint(size_t i, const QPointF& pos)
-		{
-			QPointF dp = pos - getShapeControlPoint(i);
-
-			switch (i)
-			{
-			case 0: m_yWidth -= dp.y(); break;
-			case 1: m_yWidth += dp.y(); break;
-			case 2: m_xWidth += dp.x(); break;
-			case 3: m_xWidth -= dp.x(); break;
-			}
-			refit();
-		}
-
-		QStringList Shape2DRing::getDoubleNames()const
-		{
-			QStringList res;
-			res << "xwidth" << "ywidth";
-			return res;
-		}
-
-		double Shape2DRing::getDouble(const QString& prop) const
-		{
-			if (prop == "xwidth")
-			{
-				return m_xWidth;
-			}
-			if (prop == "ywidth")
-			{
-				return m_yWidth;
-			}
-			return 0.0;
-		}
-
-		void Shape2DRing::setDouble(const QString& prop, double value)
-		{
-			if (prop == "xwidth")
-			{
-				m_xWidth = value;
-				refit();
-			}
-			if (prop == "ywidth")
-			{
-				m_yWidth = value;
-				refit();
-			}
-		}
-
-		QPointF Shape2DRing::getPoint(const QString& prop) const
-		{
-			if (prop == "center")
-			{
-				return m_boundingRect.center();
-			}
-			return QPointF();
-		}
-
-		void Shape2DRing::setPoint(const QString& prop, const QPointF& value)
-		{
-			if (prop == "center")
-			{
-				m_boundingRect.moveCenter(value);
-			}
-		}
-
-		void Shape2DRing::setColor(const QColor &color)
-		{
-			m_inner_shape->setColor(color);
-			m_outer_shape->setColor(color);
-		}
-
-		//------------------------------------------------------------------------------
-
-		/// Construct a zero-sized shape.
-		Shape2DFree::Shape2DFree(const QPointF& p) :
-			m_polygon(QRectF(p, p))
-		{
-			resetBoundingRect();
-		}
-
-		/// The shape can be selected if it contains the point.
-		bool Shape2DFree::selectAt(const QPointF& p)const
-		{
-			return contains(p);
-		}
-
-		/// Check if a point is inside the shape.
-		bool Shape2DFree::contains(const QPointF& p)const
-		{
-			return m_polygon.containsPoint(p, Qt::OddEvenFill);
-		}
-
-		/// Add to a larger shape.
-		void Shape2DFree::addToPath(QPainterPath& path) const
-		{
-			path.addPolygon(m_polygon);
-		}
-
-		/// Draw.
-		void Shape2DFree::drawShape(QPainter& painter) const
-		{
-			QPainterPath path;
-			path.addPolygon(m_polygon);
-			painter.fillPath(path, m_fill_color);
-			painter.drawPath(m_outline);
-		}
-
-		/// Rescale polygon's verices to fit to the new bounding rect.
-		void Shape2DFree::refit()
-		{
-			auto brOld = getPolygonBoundingRect();
-			auto &brNew = m_boundingRect;
-			if (brNew.xSpan() < 0.0) brNew.xFlip();
-			if (brNew.ySpan() < 0.0) brNew.yFlip();
-
-			auto xs0 = brNew.x0();
-			auto x0 = brOld.x0();
-			auto xScale = brNew.width() / brOld.width();
-
-			auto ys0 = brNew.y0();
-			auto y0 = brOld.y0();
-			auto yScale = brNew.height() / brOld.height();
-			for (int i = 0; i < m_polygon.size(); ++i)
-			{
-				auto &p = m_polygon[i];
-				p.rx() = xs0 + xScale * (p.x() - x0);
-				p.ry() = ys0 + yScale * (p.y() - y0);
-			}
-			resetBoundingRect();
-		}
-
-		/// Recalculate the bounding rect.
-		/// Also make the new border outline.
-		/// QPolygonF cannot have holes or disjointed parts,
-		/// it's a single closed line. The outline (implemented as a QPainterPath)
-		/// makes it look like it have holes.
-		void Shape2DFree::resetBoundingRect()
-		{
-			m_boundingRect = getPolygonBoundingRect();
-			// Clear the outline path.
-			m_outline = QPainterPath();
-			if (m_polygon.isEmpty()) return;
-
-			// If the polygon has apparent holes/discontinuities
-			// it will have extra pairs of edges which we don't want
-			// to draw.
-			auto n = m_polygon.size() - 1;
-			// Find those vertices at which we must break the polygon
-			// to get rid of these extra edges.
-			QList<int> breaks;
-			breaks.push_back(0);
-			for (int i = 1; i < m_polygon.size() - 1; ++i)
-			{
-				auto p = m_polygon[i];
-				auto j = m_polygon.indexOf(p, i + 1);
-				if (j != -1)
-				{
-					auto i1 = i + 1;
-					auto j1 = j - 1;
-					if (m_polygon[i1] == m_polygon[j1])
-					{
-						breaks.push_back(i);
-						breaks.push_back(i1);
-						breaks.push_back(j1);
-						breaks.push_back(j);
-					}
-				}
-			}
-			if (breaks.back() != n)
-			{
-				breaks.push_back(n);
-			}
-			qSort(breaks);
-
-			m_outline.moveTo(m_polygon[0]);
-			int j1 = 0;
-			// Add contiguous portions of the polygon to the outline
-			// and break at points from breaks list.
-			for (int i = 0; i < breaks.size(); ++i)
-			{
-				auto j = breaks[i];
-				if (j == j1 + 1)
-				{
-					m_outline.moveTo(m_polygon[j]);
-				}
-				else
-				{
-					for (auto k = j1; k <= j; ++k)
-					{
-						m_outline.lineTo(m_polygon[k]);
-					}
-				}
-				j1 = j;
-			}
-		}
-
-		/// Convert the bounding rect computed by QPolygonF to RectF
-		RectF Shape2DFree::getPolygonBoundingRect() const
-		{
-			auto br = m_polygon.boundingRect();
-			auto x0 = br.left();
-			auto x1 = br.right();
-			if (x0 > x1) std::swap(x0, x1);
-			auto y0 = br.bottom();
-			auto y1 = br.top();
-			if (y0 > y1) std::swap(y0, y1);
-			return RectF(QPointF(x0, y0), QPointF(x1, y1));
-		}
-
-		/// Add a polygon to this shape.
-		void Shape2DFree::addPolygon(const QPolygonF& polygon)
-		{
-			m_polygon = m_polygon.united(polygon);
-			resetBoundingRect();
-		}
-
-		/// Subtract a polygon from this shape.
-		void Shape2DFree::subtractPolygon(const QPolygonF& polygon)
-		{
-			m_polygon = m_polygon.subtracted(polygon);
-			resetBoundingRect();
-		}
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+// number of control points common for all shapes
+const size_t Shape2D::NCommonCP = 4;
+// size (== width/2 == height/2) of each control point
+const double Shape2D::sizeCP = 3;
+
+/**
+* Set default border color to red and fill color to default Qt color
+* (==QColor()).
+*/
+Shape2D::Shape2D()
+    : m_color(Qt::red), m_fill_color(QColor()), m_scalable(true),
+      m_editing(false), m_selected(false), m_visible(true) {}
+
+/**
+* Calls virtual drawShape() method to draw the actial shape.
+* Draws bounding rect and control points if the shape is selected.
+*
+* @param painter :: QPainter used for drawing.
+*/
+void Shape2D::draw(QPainter &painter) const {
+  if (!m_visible)
+    return;
+  painter.setPen(m_color);
+  this->drawShape(painter);
+  if (m_editing || m_selected) {
+    QColor c(255, 255, 255, 100);
+    painter.setPen(c);
+    painter.drawRect(m_boundingRect.toQRectF());
+    size_t np = NCommonCP;
+    double rsize = 2;
+    int alpha = 100;
+    if (m_editing) {
+      // if editing show all CP, make them bigger and opaque
+      np = getNControlPoints();
+      rsize = sizeCP;
+      alpha = 255;
+    }
+    for (size_t i = 0; i < np; ++i) {
+      QPointF p = painter.transform().map(getControlPoint(i));
+      QRectF r(p - QPointF(rsize, rsize), p + QPointF(rsize, rsize));
+      painter.save();
+      painter.resetTransform();
+      QColor c(255, 255, 255, alpha);
+      painter.fillRect(r, c);
+      r.adjust(-1, -1, 0, 0);
+      painter.setPen(QColor(0, 0, 0, alpha));
+      painter.drawRect(r);
+      painter.restore();
+    }
+  }
+}
+
+/**
+* Return total number of control points for this shape.
+*/
+size_t Shape2D::getNControlPoints() const {
+  return NCommonCP + this->getShapeNControlPoints();
+}
+
+/**
+* Return coordinates of i-th control point.
+*
+* @param i :: Index of a control point. 0 <= i < getNControlPoints().
+*/
+QPointF Shape2D::getControlPoint(size_t i) const {
+  if (i >= getNControlPoints()) {
+    throw std::range_error("Control point index is out of range");
+  }
+
+  if (i < 4)
+    return m_boundingRect.vertex(i);
+
+  return getShapeControlPoint(i - NCommonCP);
+}
+
+void Shape2D::setControlPoint(size_t i, const QPointF &pos) {
+  if (i >= getNControlPoints()) {
+    throw std::range_error("Control point index is out of range");
+  }
+
+  if (i < 4) {
+    m_boundingRect.setVertex(i, pos);
+    refit();
+  }
+  // else ?
+  else
+    setShapeControlPoint(i - NCommonCP, pos);
+  resetBoundingRect();
+}
+
+/**
+* Move the shape.
+*
+* @param dp :: The shift vector.
+*/
+void Shape2D::moveBy(const QPointF &dp) {
+  m_boundingRect.translate(dp);
+  refit();
+}
+
+/**
+* Adjust the bound of the bounding rect. Calls virtual method refit()
+* to resize the shape in order to fit into the new bounds.
+*/
+void Shape2D::adjustBoundingRect(double dx1, double dy1, double dx2,
+                                 double dy2) {
+  double dwidth = dx2 - dx1;
+  if (dwidth <= -m_boundingRect.xSpan()) {
+    double mu = m_boundingRect.xSpan() / fabs(dwidth);
+    dx1 *= mu;
+    dx2 *= mu;
+  }
+  double dheight = dy2 - dy1;
+  if (dheight <= -m_boundingRect.ySpan()) {
+    double mu = m_boundingRect.ySpan() / fabs(dheight);
+    dy1 *= mu;
+    dy2 *= mu;
+  }
+  m_boundingRect.adjust(QPointF(dx1, dy1), QPointF(dx2, dy2));
+  refit();
+}
+
+/**
+* Assign new bounding rect. Calls virtual method refit()
+* to resize the shape in order to fit into the new bounds.
+*/
+void Shape2D::setBoundingRect(const RectF &rect) {
+  m_boundingRect = rect;
+  refit();
+}
+
+/**
+* Check if the shape masks a point.
+*
+* @param p :: Point to check.
+*/
+bool Shape2D::isMasked(const QPointF &p) const {
+  return m_fill_color != QColor() && contains(p);
+}
+
+// --- Shape2DEllipse --- //
+
+Shape2DEllipse::Shape2DEllipse(const QPointF &center, double radius1,
+                               double radius2)
+    : Shape2D() {
+  if (radius2 == 0) {
+    radius2 = radius1;
+  }
+  QPointF dr(radius1, radius2);
+  m_boundingRect = RectF(center - dr, center + dr);
+}
+
+void Shape2DEllipse::drawShape(QPainter &painter) const {
+  QRectF drawRect = m_boundingRect.toQRectF();
+  painter.drawEllipse(drawRect);
+  if (m_fill_color != QColor()) {
+    QPainterPath path;
+    path.addEllipse(drawRect);
+    painter.fillPath(path, m_fill_color);
+  }
+}
+
+void Shape2DEllipse::addToPath(QPainterPath &path) const {
+  path.addEllipse(m_boundingRect.toQRectF());
+}
+
+bool Shape2DEllipse::selectAt(const QPointF &p) const {
+  if (m_fill_color != QColor()) { // filled ellipse
+    return contains(p);
+  }
+
+  double a = m_boundingRect.xSpan() / 2;
+  if (a == 0.0)
+    a = 1.0;
+  double b = m_boundingRect.ySpan() / 2;
+  if (b == 0.0)
+    b = 1.0;
+  double xx = m_boundingRect.x0() + a - double(p.x());
+  double yy = m_boundingRect.y0() + b - double(p.y());
+
+  double f = fabs(xx * xx / (a * a) + yy * yy / (b * b) - 1);
+
+  return f < 0.1;
+}
+
+bool Shape2DEllipse::contains(const QPointF &p) const {
+  if (m_boundingRect.isEmpty())
+    return false;
+  QPointF pp = m_boundingRect.center() - p;
+  double a = m_boundingRect.xSpan() / 2;
+  if (a == 0.0)
+    a = 1.0;
+  double b = m_boundingRect.ySpan() / 2;
+  if (b == 0.0)
+    b = 1.0;
+  double xx = pp.x();
+  double yy = pp.y();
+
+  double f = xx * xx / (a * a) + yy * yy / (b * b);
+
+  return f <= 1.0;
+}
+
+QStringList Shape2DEllipse::getDoubleNames() const {
+  QStringList res;
+  res << "radius1"
+      << "radius2";
+  return res;
+}
+
+double Shape2DEllipse::getDouble(const QString &prop) const {
+  if (prop == "radius1") {
+    return m_boundingRect.width() / 2;
+  } else if (prop == "radius2") {
+    return m_boundingRect.height() / 2;
+  }
+  return 0.0;
+}
+
+void Shape2DEllipse::setDouble(const QString &prop, double value) {
+  if (prop == "radius1") {
+    if (value <= 0.0)
+      value = 1.0;
+    double d = value - m_boundingRect.width() / 2;
+    adjustBoundingRect(-d, 0, d, 0);
+  } else if (prop == "radius2") {
+    if (value <= 0.0)
+      value = 1.0;
+    double d = value - m_boundingRect.height() / 2;
+    adjustBoundingRect(0, -d, 0, d);
+  }
+}
+
+QPointF Shape2DEllipse::getPoint(const QString &prop) const {
+  if (prop == "center" || prop == "centre") {
+    return m_boundingRect.center();
+  }
+  return QPointF();
+}
+
+void Shape2DEllipse::setPoint(const QString &prop, const QPointF &value) {
+  if (prop == "center" || prop == "centre") {
+    m_boundingRect.moveCenter(value);
+  }
+}
+
+// --- Shape2DRectangle --- //
+
+Shape2DRectangle::Shape2DRectangle() { m_boundingRect = RectF(); }
+
+Shape2DRectangle::Shape2DRectangle(const QPointF &p0, const QPointF &p1) {
+  m_boundingRect = RectF(p0, p1);
+}
+
+Shape2DRectangle::Shape2DRectangle(const QPointF &p0, const QSizeF &size) {
+  m_boundingRect = RectF(p0, size);
+}
+
+bool Shape2DRectangle::selectAt(const QPointF &p) const {
+  if (m_fill_color != QColor()) { // filled rectangle
+    return contains(p);
+  }
+
+  RectF outer(m_boundingRect);
+  outer.adjust(QPointF(-2, -2), QPointF(2, 2));
+  RectF inner(m_boundingRect);
+  inner.adjust(QPointF(2, 2), QPointF(-2, -2));
+  return outer.contains(p) && !inner.contains(p);
+}
+
+void Shape2DRectangle::drawShape(QPainter &painter) const {
+  QRectF drawRect = m_boundingRect.toQRectF();
+  painter.drawRect(drawRect);
+  if (m_fill_color != QColor()) {
+    QPainterPath path;
+    path.addRect(drawRect);
+    painter.fillPath(path, m_fill_color);
+  }
+}
+
+void Shape2DRectangle::addToPath(QPainterPath &path) const {
+  path.addRect(m_boundingRect.toQRectF());
+}
+
+// --- Shape2DRing --- //
+
+Shape2DRing::Shape2DRing(Shape2D *shape, double xWidth, double yWidth)
+    : m_outer_shape(shape), m_xWidth(xWidth), m_yWidth(yWidth) {
+  m_inner_shape = m_outer_shape->clone();
+  m_inner_shape->getBoundingRect();
+  m_inner_shape->adjustBoundingRect(m_xWidth, m_yWidth, -m_xWidth, -m_yWidth);
+  resetBoundingRect();
+  m_outer_shape->setFillColor(QColor());
+  m_inner_shape->setFillColor(QColor());
+}
+
+Shape2DRing::Shape2DRing(const Shape2DRing &ring)
+    : Shape2D(), m_outer_shape(ring.m_outer_shape->clone()),
+      m_inner_shape(ring.m_inner_shape->clone()), m_xWidth(ring.m_xWidth),
+      m_yWidth(ring.m_yWidth) {
+  resetBoundingRect();
+}
+
+bool Shape2DRing::selectAt(const QPointF &p) const { return contains(p); }
+
+bool Shape2DRing::contains(const QPointF &p) const {
+  return m_outer_shape->contains(p) && !m_inner_shape->contains(p);
+}
+
+void Shape2DRing::drawShape(QPainter &painter) const {
+  m_outer_shape->draw(painter);
+  m_inner_shape->draw(painter);
+  if (m_fill_color != QColor()) {
+    QPainterPath path;
+    m_outer_shape->addToPath(path);
+    m_inner_shape->addToPath(path);
+    painter.fillPath(path, m_fill_color);
+  }
+}
+
+void Shape2DRing::refit() {
+  if (m_xWidth <= 0)
+    m_xWidth = 0.000001;
+  if (m_yWidth <= 0)
+    m_yWidth = 0.000001;
+  double xWidth = m_xWidth;
+  double yWidth = m_yWidth;
+  double max_width = m_boundingRect.width() / 2;
+  if (xWidth > max_width)
+    xWidth = max_width;
+  double max_height = m_boundingRect.height() / 2;
+  if (yWidth > max_height)
+    yWidth = max_height;
+  m_outer_shape->setBoundingRect(m_boundingRect);
+  m_inner_shape->setBoundingRect(m_boundingRect);
+  m_inner_shape->adjustBoundingRect(xWidth, yWidth, -xWidth, -yWidth);
+}
+
+void Shape2DRing::resetBoundingRect() {
+  m_boundingRect = m_outer_shape->getBoundingRect();
+}
+
+QPointF Shape2DRing::getShapeControlPoint(size_t i) const {
+  RectF rect = m_inner_shape->getBoundingRect();
+  switch (i) {
+  case 0:
+    return QPointF(rect.center().x(), rect.y1());
+  case 1:
+    return QPointF(rect.center().x(), rect.y0());
+  case 2:
+    return QPointF(rect.x0(), rect.center().y());
+  case 3:
+    return QPointF(rect.x1(), rect.center().y());
+  }
+  return QPointF();
+}
+
+void Shape2DRing::setShapeControlPoint(size_t i, const QPointF &pos) {
+  QPointF dp = pos - getShapeControlPoint(i);
+
+  switch (i) {
+  case 0:
+    m_yWidth -= dp.y();
+    break;
+  case 1:
+    m_yWidth += dp.y();
+    break;
+  case 2:
+    m_xWidth += dp.x();
+    break;
+  case 3:
+    m_xWidth -= dp.x();
+    break;
+  }
+  refit();
+}
+
+QStringList Shape2DRing::getDoubleNames() const {
+  QStringList res;
+  res << "xwidth"
+      << "ywidth";
+  return res;
+}
+
+double Shape2DRing::getDouble(const QString &prop) const {
+  if (prop == "xwidth") {
+    return m_xWidth;
+  }
+  if (prop == "ywidth") {
+    return m_yWidth;
+  }
+  return 0.0;
+}
+
+void Shape2DRing::setDouble(const QString &prop, double value) {
+  if (prop == "xwidth") {
+    m_xWidth = value;
+    refit();
+  }
+  if (prop == "ywidth") {
+    m_yWidth = value;
+    refit();
+  }
+}
+
+QPointF Shape2DRing::getPoint(const QString &prop) const {
+  if (prop == "center") {
+    return m_boundingRect.center();
+  }
+  return QPointF();
+}
+
+void Shape2DRing::setPoint(const QString &prop, const QPointF &value) {
+  if (prop == "center") {
+    m_boundingRect.moveCenter(value);
+  }
+}
+
+void Shape2DRing::setColor(const QColor &color) {
+  m_inner_shape->setColor(color);
+  m_outer_shape->setColor(color);
+}
+
+//------------------------------------------------------------------------------
+
+/// Construct a zero-sized shape.
+Shape2DFree::Shape2DFree(const QPointF &p) : m_polygon(QRectF(p, p)) {
+  resetBoundingRect();
+}
+
+/// The shape can be selected if it contains the point.
+bool Shape2DFree::selectAt(const QPointF &p) const { return contains(p); }
+
+/// Check if a point is inside the shape.
+bool Shape2DFree::contains(const QPointF &p) const {
+  return m_polygon.containsPoint(p, Qt::OddEvenFill);
+}
+
+/// Add to a larger shape.
+void Shape2DFree::addToPath(QPainterPath &path) const {
+  path.addPolygon(m_polygon);
+}
+
+/// Draw.
+void Shape2DFree::drawShape(QPainter &painter) const {
+  QPainterPath path;
+  path.addPolygon(m_polygon);
+  painter.fillPath(path, m_fill_color);
+  painter.drawPath(m_outline);
+}
+
+/// Rescale polygon's verices to fit to the new bounding rect.
+void Shape2DFree::refit() {
+  auto brOld = getPolygonBoundingRect();
+  auto &brNew = m_boundingRect;
+  if (brNew.xSpan() < 0.0)
+    brNew.xFlip();
+  if (brNew.ySpan() < 0.0)
+    brNew.yFlip();
+
+  auto xs0 = brNew.x0();
+  auto x0 = brOld.x0();
+  auto xScale = brNew.width() / brOld.width();
+
+  auto ys0 = brNew.y0();
+  auto y0 = brOld.y0();
+  auto yScale = brNew.height() / brOld.height();
+  for (int i = 0; i < m_polygon.size(); ++i) {
+    auto &p = m_polygon[i];
+    p.rx() = xs0 + xScale * (p.x() - x0);
+    p.ry() = ys0 + yScale * (p.y() - y0);
+  }
+  resetBoundingRect();
+}
+
+/// Recalculate the bounding rect.
+/// Also make the new border outline.
+/// QPolygonF cannot have holes or disjointed parts,
+/// it's a single closed line. The outline (implemented as a QPainterPath)
+/// makes it look like it have holes.
+void Shape2DFree::resetBoundingRect() {
+  m_boundingRect = getPolygonBoundingRect();
+  // Clear the outline path.
+  m_outline = QPainterPath();
+  if (m_polygon.isEmpty())
+    return;
+
+  // If the polygon has apparent holes/discontinuities
+  // it will have extra pairs of edges which we don't want
+  // to draw.
+  auto n = m_polygon.size() - 1;
+  // Find those vertices at which we must break the polygon
+  // to get rid of these extra edges.
+  QList<int> breaks;
+  breaks.push_back(0);
+  for (int i = 1; i < m_polygon.size() - 1; ++i) {
+    auto p = m_polygon[i];
+    auto j = m_polygon.indexOf(p, i + 1);
+    if (j != -1) {
+      auto i1 = i + 1;
+      auto j1 = j - 1;
+      if (m_polygon[i1] == m_polygon[j1]) {
+        breaks.push_back(i);
+        breaks.push_back(i1);
+        breaks.push_back(j1);
+        breaks.push_back(j);
+      }
+    }
+  }
+  if (breaks.back() != n) {
+    breaks.push_back(n);
+  }
+  qSort(breaks);
+
+  m_outline.moveTo(m_polygon[0]);
+  int j1 = 0;
+  // Add contiguous portions of the polygon to the outline
+  // and break at points from breaks list.
+  for (int i = 0; i < breaks.size(); ++i) {
+    auto j = breaks[i];
+    if (j == j1 + 1) {
+      m_outline.moveTo(m_polygon[j]);
+    } else {
+      for (auto k = j1; k <= j; ++k) {
+        m_outline.lineTo(m_polygon[k]);
+      }
+    }
+    j1 = j;
+  }
+}
+
+/// Convert the bounding rect computed by QPolygonF to RectF
+RectF Shape2DFree::getPolygonBoundingRect() const {
+  auto br = m_polygon.boundingRect();
+  auto x0 = br.left();
+  auto x1 = br.right();
+  if (x0 > x1)
+    std::swap(x0, x1);
+  auto y0 = br.bottom();
+  auto y1 = br.top();
+  if (y0 > y1)
+    std::swap(y0, y1);
+  return RectF(QPointF(x0, y0), QPointF(x1, y1));
+}
+
+/// Add a polygon to this shape.
+void Shape2DFree::addPolygon(const QPolygonF &polygon) {
+  m_polygon = m_polygon.united(polygon);
+  resetBoundingRect();
+}
+
+/// Subtract a polygon from this shape.
+void Shape2DFree::subtractPolygon(const QPolygonF &polygon) {
+  m_polygon = m_polygon.subtracted(polygon);
+  resetBoundingRect();
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/Shape2DCollection.cpp b/MantidQt/MantidWidgets/src/InstrumentView/Shape2DCollection.cpp
index 018b3d46b547c1b94459647446005fd860507f27..735ca6e58b11ac9b722b82bbddd2c212766e7c9b 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/Shape2DCollection.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/Shape2DCollection.cpp
@@ -10,783 +10,659 @@
 #include <stdexcept>
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		Shape2DCollection::Shape2DCollection() :
-			Shape2D(),
-			m_wx(0),
-			m_wy(0),
-			m_h(0),
-			m_currentShape(NULL),
-			m_currentCP(0),
-			m_overridingCursor(false)
-		{
-		}
-
-		Shape2DCollection::~Shape2DCollection()
-		{
-			foreach(Shape2D* shape, m_shapes)
-			{
-				delete shape;
-			}
-		}
-
-		/**
-		* Draw the collection on screen.
-		*/
-		void Shape2DCollection::draw(QPainter& painter) const
-		{
-			if (m_shapes.isEmpty()) return;
-
-			// separate scalable and nonscalable shapes
-			QList<Shape2D*> scalable;
-			QList<Shape2D*> nonscalable;
-			foreach(Shape2D* shape, m_shapes)
-			{
-				if (!shape->isVisible()) continue;
-				if (shape->isScalable())
-				{
-					scalable << shape;
-				}
-				else
-				{
-					nonscalable << shape;
-				}
-			}
-
-			// first draw the scalable ones
-			painter.save();
-			painter.setTransform(m_transform);
-			foreach(const Shape2D* shape, scalable)
-			{
-				painter.save();
-				shape->draw(painter);
-				painter.restore();
-			}
-			painter.restore();
-
-			// now the nonscalable
-			foreach(const Shape2D* shape, nonscalable)
-			{
-				QPointF p0 = shape->origin();
-				QPointF p1 = m_transform.map(p0);
-				QPointF dp = p1 - p0;
-				painter.save();
-				painter.translate(dp);
-				shape->draw(painter);
-				painter.restore();
-			}
-			//std::cerr << m_transform.m11() << ' ' << m_transform.m22() << ' ' << m_transform.m33() << std::endl;
-		}
-
-		/**
-		* Add a new shape to collection.
-		* @param shape :: A pointer to the new shape.
-		* @param slct :: A bool flag to select the shape after it's added.
-		*/
-		void Shape2DCollection::addShape(Shape2D* shape, bool slct)
-		{
-			m_shapes.push_back(shape);
-			m_boundingRect.unite(shape->getBoundingRect());
-			if (slct)
-			{
-				addToSelection(shape);
-			}
-			emit shapeCreated();
-		}
-
-		/**
-		* Remove a shape from collection
-		* @param shape :: Pointer to the shape to remove.
-		* @param sendSignal :: Flag to send shapesRemoved() signal.
-		*/
-		void Shape2DCollection::removeShape(Shape2D* shape, bool sendSignal)
-		{
-			if (shape && m_shapes.contains(shape))
-			{
-				m_shapes.removeOne(shape);
-				m_selectedShapes.removeOne(shape);
-				delete shape;
-			}
-			if (sendSignal)
-			{
-				if (m_shapes.isEmpty())
-				{
-					emit cleared();
-				}
-				else
-				{
-					emit shapesRemoved();
-				}
-			}
-		}
-
-		/**
-		* Remove a list of shapes.
-		* @param shapeList :: A list of pointers to the shapes to be removed
-		*/
-		void Shape2DCollection::removeShapes(const QList<Shape2D*>& shapeList)
-		{
-			foreach(Shape2D* shape, shapeList)
-			{
-				if (shape == m_currentShape)
-				{
-					m_currentShape = NULL;
-				}
-				removeShape(shape, false);
-			}
-			if (m_shapes.isEmpty())
-			{
-				emit cleared();
-			}
-			else
-			{
-				emit shapesRemoved();
-			}
-		}
-
-		/**
-		*/
-		void Shape2DCollection::setWindow(const RectF &surface, const QRect& viewport) const
-		{
-			m_viewport = viewport;
-			m_surfaceRect = surface;
-			m_surfaceRect.findTransform(m_transform, viewport);
-		}
-
-		void Shape2DCollection::refit()
-		{
-		}
-
-		void Shape2DCollection::resetBoundingRect()
-		{
-			m_boundingRect = RectF();
-			foreach(const Shape2D* shape, m_shapes)
-			{
-				m_boundingRect.unite(shape->getBoundingRect());
-			}
-		}
-
-		void Shape2DCollection::keyPressEvent(QKeyEvent* e)
-		{
-			switch (e->key())
-			{
-			case Qt::Key_Delete:
-			case Qt::Key_Backspace: removeSelectedShapes(); break;
-			}
-		}
-
-		void Shape2DCollection::addShape(const QString& type, int x, int y, const QColor &borderColor, const QColor &fillColor)
-		{
-			deselectAll();
-			Shape2D *shape = createShape(type, x, y);
-			if (!shape)
-			{
-				emit shapeSelected();
-				return;
-			}
-			shape->setColor(borderColor);
-			shape->setFillColor(fillColor);
-			addShape(shape);
-			addToSelection(shape);
-			m_currentCP = 2;
-			emit shapeSelected();
-		}
-
-		Shape2D* Shape2DCollection::createShape(const QString& type, int x, int y) const
-		{
-			QPointF p = m_transform.inverted().map(QPointF(x, y));
-
-			if (type.toLower() == "ellipse")
-			{
-				return new Shape2DEllipse(p, 0.0);
-			}
-			else if (type.toLower() == "rectangle")
-			{
-				return new Shape2DRectangle(p, QSizeF(0, 0));
-			}
-			else if (type.toLower() == "free")
-			{
-				return new Shape2DFree(p);
-			}
-
-			QStringList complexType = type.split(' ', QString::SkipEmptyParts);
-
-			if (complexType.size() < 2) return NULL;
-
-			QString mainType = complexType[0];
-
-			if (mainType.toLower() == "ring")
-			{
-				double xWidth = 10.0 / fabs(m_transform.m11());
-				double yWidth = 10.0 / fabs(m_transform.m22());
-				Shape2D* child = createShape(complexType[1], x, y);
-				return new Shape2DRing(child, xWidth, yWidth);
-			}
-
-			throw std::invalid_argument("Shape " + type.toStdString() + " cannot be created");
-
-		}
-
-		/**
-		* Deselect all selected shapes.
-		*/
-		void Shape2DCollection::deselectAll()
-		{
-			foreach(Shape2D* shape, m_shapes)
-			{
-				shape->edit(false);
-				shape->setSelected(false);
-			}
-			m_selectedShapes.clear();
-			m_currentShape = NULL;
-			if (m_overridingCursor)
-			{
-				m_overridingCursor = false;
-				QApplication::restoreOverrideCursor();
-			}
-			emit shapesDeselected();
-		}
-
-		/**
-		* Resize the current shape by moving the right-bottom control point to a loaction on the screen.
-		*/
-		void Shape2DCollection::moveRightBottomTo(int x, int y)
-		{
-			if (m_currentShape && m_currentShape->isEditing())
-			{
-				QPointF p = m_transform.inverted().map(QPointF(x, y));
-				m_currentShape->setControlPoint(3, p);
-				emit shapeChanged();
-			}
-		}
-
-		/**
-		* Select a shape or a control point at a location on the screen.
-		* The control points of the currently selected shape are checked first.
-		* If (x,y) doesn't point to anything deselect all currently selected shapes.
-		*/
-		void Shape2DCollection::selectShapeOrControlPointAt(int x, int y)
-		{
-			if (isOverSelectionAt(x, y)) return;
-			bool ret = selectControlPointAt(x, y) || selectAtXY(x, y);
-			if (!ret)
-			{
-				deselectAll();
-			}
-		}
-
-		/**
-		* Add a shape under the cursor to the selection.
-		* @param x :: Mouse x coordinate.
-		* @param y :: Mouse y coordinate.
-		*/
-		void Shape2DCollection::addToSelectionShapeAt(int x, int y)
-		{
-			// if there is a selected shape under the cursor deselect it
-			if (isOverSelectionAt(x, y))
-			{
-				deselectAtXY(x, y);
-				return;
-			}
-			// try selecting a shape without editing it
-			if (!selectAtXY(x, y, false))
-			{
-				deselectAll();
-			}
-		}
-
-		/**
-		* Move the current control point or entire shape by (dx,dy).
-		* @param dx :: Shift in the x direction in screen pixels.
-		* @param dy :: Shift in the y direction in screen pixels.
-		*/
-		void Shape2DCollection::moveShapeOrControlPointBy(int dx, int dy)
-		{
-			if (!hasSelection()) return;
-			if (m_currentShape && m_currentCP < m_currentShape->getNControlPoints())
-			{
-				QPointF p = m_currentShape->getControlPoint(m_currentCP);
-				QPointF screenP = m_transform.map(p) + QPointF(dx, dy);
-				p = m_transform.inverted().map(screenP);
-				m_currentShape->setControlPoint(m_currentCP, p);
-			}
-			else
-			{
-				QPointF p0 = m_selectedShapes[0]->getControlPoint(0);
-				QPointF screenP0 = m_transform.map(p0);
-				QPointF screenP1 = screenP0 + QPointF(dx, dy);
-				QPointF p1 = m_transform.inverted().map(screenP1);
-				QPointF dp = p1 - p0;
-				foreach(Shape2D* shape, m_selectedShapes)
-				{
-					shape->moveBy(dp);
-				}
-			}
-			if (!m_overridingCursor)
-			{
-				m_overridingCursor = true;
-				QApplication::setOverrideCursor(Qt::SizeAllCursor);
-			}
-			emit shapeChanged();
-		}
-
-		/**
-		* If mouse pointer at (x,y) touches the current shape or its control points
-		* override the cursor image.
-		*/
-		void Shape2DCollection::touchShapeOrControlPointAt(int x, int y)
-		{
-			if (selectControlPointAt(x, y) || isOverSelectionAt(x, y))
-			{
-				if (!m_overridingCursor)
-				{
-					m_overridingCursor = true;
-					QApplication::setOverrideCursor(Qt::SizeAllCursor);
-				}
-			}
-			else if (m_overridingCursor)
-			{
-				deselectControlPoint();
-				m_overridingCursor = false;
-				QApplication::restoreOverrideCursor();
-			}
-		}
-
-		/**
-		* Select a shape which contains a point (x,y) of the screen.
-		*/
-		bool Shape2DCollection::selectAtXY(int x, int y, bool edit)
-		{
-			if (edit)
-			{
-				// if shape has to be edited (resized) it must be the only selection
-				deselectAll();
-			}
-			QPointF p = m_transform.inverted().map(QPointF(x, y));
-			foreach(Shape2D* shape, m_shapes)
-			{
-				bool picked = shape->selectAt(p);
-				if (picked)
-				{
-					addToSelection(shape);
-					return true;
-				}
-			}
-			return false;
-		}
-
-		/**
-		* Deselect a shape under the cursor.
-		* @param x :: Mouse x coordinate.
-		* @param y :: Mouse y coordinate.
-		*/
-		void Shape2DCollection::deselectAtXY(int x, int y)
-		{
-			QPointF p = m_transform.inverted().map(QPointF(x, y));
-			foreach(Shape2D* shape, m_shapes)
-			{
-				bool picked = shape->selectAt(p);
-				if (picked)
-				{
-					removeFromSelection(shape);
-					return;
-				}
-			}
-		}
-
-		/**
-		* Select all shapes included in a rectangle.
-		* @param rect :: Rectangle in current screen coordinates containing selected shapes.
-		* @return :: True if any of the shapes is selected.
-		*/
-		bool Shape2DCollection::selectIn(const QRect& rect)
-		{
-			RectF untransformedRect = RectF(QRectF(rect));
-			RectF r(m_transform.inverted().mapRect(QRectF(rect)));
-			bool selected = false;
-			deselectAll();
-			foreach(Shape2D* shape, m_shapes)
-			{
-				bool sel = false;
-				if (shape->isScalable())
-				{
-					sel = r.contains(shape->getBoundingRect());
-				}
-				else
-				{
-					QPointF dp = m_transform.map(shape->origin()) - shape->origin();
-					RectF br = shape->getBoundingRect();
-					br.translate(dp);
-					sel = untransformedRect.contains(br);
-				}
-				if (sel)
-				{
-					addToSelection(shape);
-					selected = true;
-				}
-			}
-			return selected;
-		}
-
-		/**
-		* Select a shape with index i.
-		*/
-		void Shape2DCollection::addToSelection(int i)
-		{
-			if (i < static_cast<int>(size()))
-			{
-				addToSelection(m_shapes[i]);
-			}
-		}
-
-		/**
-		* Check if any of the shapes is selected.
-		* @return :: True if there is a selection.
-		*/
-		bool Shape2DCollection::hasSelection() const
-		{
-			foreach(Shape2D* shape, m_shapes)
-			{
-				if (shape->isSelected())
-				{
-					return true;
-				}
-			}
-			return false;
-		}
-
-		/**
-		* Add a shape to selection. If it's the only selection start editing it.
-		* @param shape :: Pointer to a shape which is to become select.
-		*/
-		void Shape2DCollection::addToSelection(Shape2D* shape)
-		{
-			if (!m_selectedShapes.contains(shape))
-			{
-				if (m_selectedShapes.size() == 1) finishEdit();
-				shape->setSelected(true);
-				m_selectedShapes.append(shape);
-				if (m_selectedShapes.size() == 1) edit(shape);
-			}
-		}
-
-		/**
-		* Remove a shape from selection.
-		* @param shape :: Pointer to a shape to deselect.
-		*/
-		void Shape2DCollection::removeFromSelection(Shape2D *shape)
-		{
-			foreach(Shape2D* s, m_selectedShapes)
-			{
-				if (s == shape)
-				{
-					shape->setSelected(false);
-					shape->edit(false);
-					m_selectedShapes.removeOne(shape);
-					return;
-				}
-			}
-		}
-
-		/**
-		* Start editing a shape.
-		* @param shape :: A shape to edit.
-		*/
-		void Shape2DCollection::edit(Shape2D *shape)
-		{
-			if (m_currentShape)
-			{
-				m_currentShape->edit(false);
-			}
-			m_currentShape = shape;
-			m_currentShape->edit(true);
-			m_currentCP = m_currentShape->getNControlPoints(); // no current cp until it is selected explicitly
-			emit shapeSelected();
-		}
-
-		/**
-		* Finish editing the current shape. The shape remains selected.
-		*/
-		void Shape2DCollection::finishEdit()
-		{
-			if (m_currentShape)
-			{
-				m_currentShape->edit(false);
-				m_currentShape = NULL;
-			}
-		}
-
-		/**
-		* Checks if the screen point (x,y) is inside the current shape.
-		*/
-		bool Shape2DCollection::isOverCurrentAt(int x, int y)
-		{
-			if (!m_currentShape) return false;
-			QPointF p = m_transform.inverted().map(QPointF(x, y));
-			return m_currentShape->selectAt(p);
-		}
-
-		/**
-		* Checks if the screen point (x,y) is inside any of the selected shapes.
-		*/
-		bool Shape2DCollection::isOverSelectionAt(int x, int y)
-		{
-			if (m_selectedShapes.isEmpty()) return false;
-			QPointF p = m_transform.inverted().map(QPointF(x, y));
-			foreach(Shape2D *shape, m_selectedShapes)
-			{
-				if (shape->selectAt(p)) return true;
-			}
-			return false;
-		}
-
-		bool Shape2DCollection::selectControlPointAt(int x, int y)
-		{
-			//QPointF p = m_transform.inverted().map(QPointF(x,y));
-			QPointF p = QPointF(x, y);
-			if (!m_currentShape) return false;
-			for (size_t i = 0; i < m_currentShape->getNControlPoints(); ++i)
-			{
-				//QPointF cp = m_currentShape->getControlPoint(i) - p;
-				QPointF cp = m_transform.map(m_currentShape->getControlPoint(i)) - p;
-				if (fabs(cp.x()) + fabs(cp.y()) <= sizeCP + 2)
-					//if (cp.manhattanLength() <= sizeCP + 2)
-				{
-					m_currentCP = i;
-					return true;
-				}
-			}
-			// deselect control points
-			m_currentCP = m_currentShape->getNControlPoints();
-			return false;
-		}
-
-		void Shape2DCollection::deselectControlPoint()
-		{
-			if (m_currentShape)
-			{
-				m_currentCP = m_currentShape->getNControlPoints();
-			}
-		}
-
-		void Shape2DCollection::removeCurrentShape()
-		{
-			if (m_currentShape)
-			{
-				this->removeShape(m_currentShape);
-				m_currentShape = NULL;
-				emit shapesDeselected();
-			}
-		}
-
-		/**
-		* Removes the selected shapes from this collection.
-		*/
-		void Shape2DCollection::removeSelectedShapes()
-		{
-			auto shapeList = getSelectedShapes();
-			if (!shapeList.isEmpty())
-			{
-				removeShapes(shapeList);
-				emit shapesDeselected();
-			}
-		}
-
-		/**
-		* Restore the cursor image to default.
-		*/
-		void Shape2DCollection::restoreOverrideCursor()
-		{
-			if (m_overridingCursor)
-			{
-				m_overridingCursor = false;
-				QApplication::restoreOverrideCursor();
-			}
-		}
-
-		void Shape2DCollection::clear()
-		{
-			foreach(Shape2D* shape, m_shapes)
-			{
-				delete shape;
-			}
-			m_shapes.clear();
-			m_selectedShapes.clear();
-			m_currentShape = NULL;
-			emit shapesDeselected();
-		}
-
-		QStringList Shape2DCollection::getCurrentDoubleNames()const
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->getDoubleNames();
-			}
-			return QStringList();
-		}
-
-		double Shape2DCollection::getCurrentDouble(const QString& prop) const
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->getDouble(prop);
-			}
-			return 0.0;
-		}
-
-		void Shape2DCollection::setCurrentDouble(const QString& prop, double value)
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->setDouble(prop, value);
-			}
-		}
-
-		QStringList Shape2DCollection::getCurrentPointNames()const
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->getPointNames();
-			}
-			return QStringList();
-		}
-
-		QPointF Shape2DCollection::getCurrentPoint(const QString& prop) const
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->getPoint(prop);
-			}
-			return QPointF();
-		}
-
-		void Shape2DCollection::setCurrentPoint(const QString& prop, const QPointF& value)
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->setPoint(prop, value);
-			}
-		}
-
-		RectF Shape2DCollection::getCurrentBoundingRect()const
-		{
-			if (m_currentShape)
-			{
-				return m_currentShape->getBoundingRect();
-			}
-			return RectF();
-		}
-
-		void Shape2DCollection::setCurrentBoundingRect(const RectF& rect)
-		{
-			if (m_currentShape)
-			{
-				m_currentShape->setBoundingRect(rect);
-			}
-		}
-
-		bool Shape2DCollection::isMasked(double x, double y)const
-		{
-			QPointF p(x, y);
-			foreach(Shape2D* shape, m_shapes)
-			{
-				if (shape->isMasked(p))
-				{
-					return true;
-				}
-			}
-			return false;
-		}
-
-		QList<QPoint> Shape2DCollection::getMaskedPixels() const {
-			QList<QPoint> pixels;
-			QTransform inv = m_transform.inverted();
-			for (int i = m_viewport.left(); i <= m_viewport.right(); ++i)
-			{
-				for (int j = m_viewport.top(); j <= m_viewport.bottom(); ++j)
-				{
-					QPoint p = QPoint(i, j);
-					QPointF p0 = inv.map(QPointF(p));
-					foreach(Shape2D* shape, m_shapes)
-					{
-						if (shape->isMasked(p0))
-						{
-							pixels.append(p);
-						}
-					}
-				}
-			}
-      return pixels;
-		}
-
-		/**
-		* Set the bounding rect of the current shape in real coordinates.
-		*/
-		void Shape2DCollection::setCurrentBoundingRectReal(const QRectF& rect)
-		{
-			if (!m_currentShape) return;
-			m_currentShape->setBoundingRect(RectF(rect));
-		}
-
-		/**
-		* Change border color.
-		*/
-		void Shape2DCollection::changeBorderColor(const QColor &color)
-		{
-			foreach(Shape2D* shape, m_shapes)
-			{
-				shape->setColor(color);
-			}
-		}
-
-		/**
-		* Add a Shape2D object allowing free drawing.
-		* @param poly :: Initial shape.
-		* @param borderColor :: The border colour.
-		* @param fillColor :: The fill colour.
-		*/
-		void Shape2DCollection::addFreeShape(const QPolygonF& poly, const QColor& borderColor, const QColor& fillColor)
-		{
-			auto freeShape = dynamic_cast<Shape2DFree*>(m_currentShape);
-			if (!freeShape)
-			{
-				if (poly.isEmpty()) throw std::logic_error("Cannot create a shape from empty polygon.");
-				auto p = m_transform.inverted().map(poly[0]);
-				addShape("free", static_cast<int>(p.x()), static_cast<int>(p.y()), borderColor, fillColor);
-			}
-			drawFree(poly);
-		}
-
-		/**
-		* Draw the shape by adding a polygon to it.
-		*/
-		void Shape2DCollection::drawFree(const QPolygonF& polygon)
-		{
-			auto freeShape = dynamic_cast<Shape2DFree*>(m_currentShape);
-			if (freeShape)
-			{
-				auto transform = m_transform.inverted();
-				freeShape->addPolygon(transform.map(polygon));
-				emit shapeChanged();
-			}
-		}
-
-		/**
-		* Erase part of the shape by subtracting a polygon from it.
-		*/
-		void Shape2DCollection::eraseFree(const QPolygonF& polygon)
-		{
-			auto freeShape = dynamic_cast<Shape2DFree*>(m_currentShape);
-			if (freeShape)
-			{
-				auto transform = m_transform.inverted();
-				freeShape->subtractPolygon(transform.map(polygon));
-				emit shapeChanged();
-			}
-		}
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+namespace MantidQt {
+namespace MantidWidgets {
+
+Shape2DCollection::Shape2DCollection()
+    : Shape2D(), m_wx(0), m_wy(0), m_h(0), m_currentShape(NULL), m_currentCP(0),
+      m_overridingCursor(false) {}
+
+Shape2DCollection::~Shape2DCollection() {
+  foreach (Shape2D *shape, m_shapes) { delete shape; }
+}
+
+/**
+* Draw the collection on screen.
+*/
+void Shape2DCollection::draw(QPainter &painter) const {
+  if (m_shapes.isEmpty())
+    return;
+
+  // separate scalable and nonscalable shapes
+  QList<Shape2D *> scalable;
+  QList<Shape2D *> nonscalable;
+  foreach (Shape2D *shape, m_shapes) {
+    if (!shape->isVisible())
+      continue;
+    if (shape->isScalable()) {
+      scalable << shape;
+    } else {
+      nonscalable << shape;
+    }
+  }
+
+  // first draw the scalable ones
+  painter.save();
+  painter.setTransform(m_transform);
+  foreach (const Shape2D *shape, scalable) {
+    painter.save();
+    shape->draw(painter);
+    painter.restore();
+  }
+  painter.restore();
+
+  // now the nonscalable
+  foreach (const Shape2D *shape, nonscalable) {
+    QPointF p0 = shape->origin();
+    QPointF p1 = m_transform.map(p0);
+    QPointF dp = p1 - p0;
+    painter.save();
+    painter.translate(dp);
+    shape->draw(painter);
+    painter.restore();
+  }
+  // std::cerr << m_transform.m11() << ' ' << m_transform.m22() << ' ' <<
+  // m_transform.m33() << std::endl;
+}
+
+/**
+* Add a new shape to collection.
+* @param shape :: A pointer to the new shape.
+* @param slct :: A bool flag to select the shape after it's added.
+*/
+void Shape2DCollection::addShape(Shape2D *shape, bool slct) {
+  m_shapes.push_back(shape);
+  m_boundingRect.unite(shape->getBoundingRect());
+  if (slct) {
+    addToSelection(shape);
+  }
+  emit shapeCreated();
+}
+
+/**
+* Remove a shape from collection
+* @param shape :: Pointer to the shape to remove.
+* @param sendSignal :: Flag to send shapesRemoved() signal.
+*/
+void Shape2DCollection::removeShape(Shape2D *shape, bool sendSignal) {
+  if (shape && m_shapes.contains(shape)) {
+    m_shapes.removeOne(shape);
+    m_selectedShapes.removeOne(shape);
+    delete shape;
+  }
+  if (sendSignal) {
+    if (m_shapes.isEmpty()) {
+      emit cleared();
+    } else {
+      emit shapesRemoved();
+    }
+  }
+}
+
+/**
+* Remove a list of shapes.
+* @param shapeList :: A list of pointers to the shapes to be removed
+*/
+void Shape2DCollection::removeShapes(const QList<Shape2D *> &shapeList) {
+  foreach (Shape2D *shape, shapeList) {
+    if (shape == m_currentShape) {
+      m_currentShape = NULL;
+    }
+    removeShape(shape, false);
+  }
+  if (m_shapes.isEmpty()) {
+    emit cleared();
+  } else {
+    emit shapesRemoved();
+  }
+}
+
+/**
+*/
+void Shape2DCollection::setWindow(const RectF &surface,
+                                  const QRect &viewport) const {
+  m_viewport = viewport;
+  m_surfaceRect = surface;
+  m_surfaceRect.findTransform(m_transform, viewport);
+}
+
+void Shape2DCollection::refit() {}
+
+void Shape2DCollection::resetBoundingRect() {
+  m_boundingRect = RectF();
+  foreach (const Shape2D *shape, m_shapes) {
+    m_boundingRect.unite(shape->getBoundingRect());
+  }
+}
+
+void Shape2DCollection::keyPressEvent(QKeyEvent *e) {
+  switch (e->key()) {
+  case Qt::Key_Delete:
+  case Qt::Key_Backspace:
+    removeSelectedShapes();
+    break;
+  }
+}
+
+void Shape2DCollection::addShape(const QString &type, int x, int y,
+                                 const QColor &borderColor,
+                                 const QColor &fillColor) {
+  deselectAll();
+  Shape2D *shape = createShape(type, x, y);
+  if (!shape) {
+    emit shapeSelected();
+    return;
+  }
+  shape->setColor(borderColor);
+  shape->setFillColor(fillColor);
+  addShape(shape);
+  addToSelection(shape);
+  m_currentCP = 2;
+  emit shapeSelected();
+}
+
+Shape2D *Shape2DCollection::createShape(const QString &type, int x,
+                                        int y) const {
+  QPointF p = m_transform.inverted().map(QPointF(x, y));
+
+  if (type.toLower() == "ellipse") {
+    return new Shape2DEllipse(p, 0.0);
+  } else if (type.toLower() == "rectangle") {
+    return new Shape2DRectangle(p, QSizeF(0, 0));
+  } else if (type.toLower() == "free") {
+    return new Shape2DFree(p);
+  }
+
+  QStringList complexType = type.split(' ', QString::SkipEmptyParts);
+
+  if (complexType.size() < 2)
+    return NULL;
+
+  QString mainType = complexType[0];
+
+  if (mainType.toLower() == "ring") {
+    double xWidth = 10.0 / fabs(m_transform.m11());
+    double yWidth = 10.0 / fabs(m_transform.m22());
+    Shape2D *child = createShape(complexType[1], x, y);
+    return new Shape2DRing(child, xWidth, yWidth);
+  }
+
+  throw std::invalid_argument("Shape " + type.toStdString() +
+                              " cannot be created");
+}
+
+/**
+* Deselect all selected shapes.
+*/
+void Shape2DCollection::deselectAll() {
+  foreach (Shape2D *shape, m_shapes) {
+    shape->edit(false);
+    shape->setSelected(false);
+  }
+  m_selectedShapes.clear();
+  m_currentShape = NULL;
+  if (m_overridingCursor) {
+    m_overridingCursor = false;
+    QApplication::restoreOverrideCursor();
+  }
+  emit shapesDeselected();
+}
+
+/**
+* Resize the current shape by moving the right-bottom control point to a
+* loaction on the screen.
+*/
+void Shape2DCollection::moveRightBottomTo(int x, int y) {
+  if (m_currentShape && m_currentShape->isEditing()) {
+    QPointF p = m_transform.inverted().map(QPointF(x, y));
+    m_currentShape->setControlPoint(3, p);
+    emit shapeChanged();
+  }
+}
+
+/**
+* Select a shape or a control point at a location on the screen.
+* The control points of the currently selected shape are checked first.
+* If (x,y) doesn't point to anything deselect all currently selected shapes.
+*/
+void Shape2DCollection::selectShapeOrControlPointAt(int x, int y) {
+  if (isOverSelectionAt(x, y))
+    return;
+  bool ret = selectControlPointAt(x, y) || selectAtXY(x, y);
+  if (!ret) {
+    deselectAll();
+  }
+}
+
+/**
+* Add a shape under the cursor to the selection.
+* @param x :: Mouse x coordinate.
+* @param y :: Mouse y coordinate.
+*/
+void Shape2DCollection::addToSelectionShapeAt(int x, int y) {
+  // if there is a selected shape under the cursor deselect it
+  if (isOverSelectionAt(x, y)) {
+    deselectAtXY(x, y);
+    return;
+  }
+  // try selecting a shape without editing it
+  if (!selectAtXY(x, y, false)) {
+    deselectAll();
+  }
+}
+
+/**
+* Move the current control point or entire shape by (dx,dy).
+* @param dx :: Shift in the x direction in screen pixels.
+* @param dy :: Shift in the y direction in screen pixels.
+*/
+void Shape2DCollection::moveShapeOrControlPointBy(int dx, int dy) {
+  if (!hasSelection())
+    return;
+  if (m_currentShape && m_currentCP < m_currentShape->getNControlPoints()) {
+    QPointF p = m_currentShape->getControlPoint(m_currentCP);
+    QPointF screenP = m_transform.map(p) + QPointF(dx, dy);
+    p = m_transform.inverted().map(screenP);
+    m_currentShape->setControlPoint(m_currentCP, p);
+  } else {
+    QPointF p0 = m_selectedShapes[0]->getControlPoint(0);
+    QPointF screenP0 = m_transform.map(p0);
+    QPointF screenP1 = screenP0 + QPointF(dx, dy);
+    QPointF p1 = m_transform.inverted().map(screenP1);
+    QPointF dp = p1 - p0;
+    foreach (Shape2D *shape, m_selectedShapes) { shape->moveBy(dp); }
+  }
+  if (!m_overridingCursor) {
+    m_overridingCursor = true;
+    QApplication::setOverrideCursor(Qt::SizeAllCursor);
+  }
+  emit shapeChanged();
+}
+
+/**
+* If mouse pointer at (x,y) touches the current shape or its control points
+* override the cursor image.
+*/
+void Shape2DCollection::touchShapeOrControlPointAt(int x, int y) {
+  if (selectControlPointAt(x, y) || isOverSelectionAt(x, y)) {
+    if (!m_overridingCursor) {
+      m_overridingCursor = true;
+      QApplication::setOverrideCursor(Qt::SizeAllCursor);
+    }
+  } else if (m_overridingCursor) {
+    deselectControlPoint();
+    m_overridingCursor = false;
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+/**
+* Select a shape which contains a point (x,y) of the screen.
+*/
+bool Shape2DCollection::selectAtXY(int x, int y, bool edit) {
+  if (edit) {
+    // if shape has to be edited (resized) it must be the only selection
+    deselectAll();
+  }
+  QPointF p = m_transform.inverted().map(QPointF(x, y));
+  foreach (Shape2D *shape, m_shapes) {
+    bool picked = shape->selectAt(p);
+    if (picked) {
+      addToSelection(shape);
+      return true;
+    }
+  }
+  return false;
+}
+
+/**
+* Deselect a shape under the cursor.
+* @param x :: Mouse x coordinate.
+* @param y :: Mouse y coordinate.
+*/
+void Shape2DCollection::deselectAtXY(int x, int y) {
+  QPointF p = m_transform.inverted().map(QPointF(x, y));
+  foreach (Shape2D *shape, m_shapes) {
+    bool picked = shape->selectAt(p);
+    if (picked) {
+      removeFromSelection(shape);
+      return;
+    }
+  }
+}
+
+/**
+* Select all shapes included in a rectangle.
+* @param rect :: Rectangle in current screen coordinates containing selected
+* shapes.
+* @return :: True if any of the shapes is selected.
+*/
+bool Shape2DCollection::selectIn(const QRect &rect) {
+  RectF untransformedRect = RectF(QRectF(rect));
+  RectF r(m_transform.inverted().mapRect(QRectF(rect)));
+  bool selected = false;
+  deselectAll();
+  foreach (Shape2D *shape, m_shapes) {
+    bool sel = false;
+    if (shape->isScalable()) {
+      sel = r.contains(shape->getBoundingRect());
+    } else {
+      QPointF dp = m_transform.map(shape->origin()) - shape->origin();
+      RectF br = shape->getBoundingRect();
+      br.translate(dp);
+      sel = untransformedRect.contains(br);
+    }
+    if (sel) {
+      addToSelection(shape);
+      selected = true;
+    }
+  }
+  return selected;
+}
+
+/**
+* Select a shape with index i.
+*/
+void Shape2DCollection::addToSelection(int i) {
+  if (i < static_cast<int>(size())) {
+    addToSelection(m_shapes[i]);
+  }
+}
+
+/**
+* Check if any of the shapes is selected.
+* @return :: True if there is a selection.
+*/
+bool Shape2DCollection::hasSelection() const {
+  foreach (Shape2D *shape, m_shapes) {
+    if (shape->isSelected()) {
+      return true;
+    }
+  }
+  return false;
+}
+
+/**
+* Add a shape to selection. If it's the only selection start editing it.
+* @param shape :: Pointer to a shape which is to become select.
+*/
+void Shape2DCollection::addToSelection(Shape2D *shape) {
+  if (!m_selectedShapes.contains(shape)) {
+    if (m_selectedShapes.size() == 1)
+      finishEdit();
+    shape->setSelected(true);
+    m_selectedShapes.append(shape);
+    if (m_selectedShapes.size() == 1)
+      edit(shape);
+  }
+}
+
+/**
+* Remove a shape from selection.
+* @param shape :: Pointer to a shape to deselect.
+*/
+void Shape2DCollection::removeFromSelection(Shape2D *shape) {
+  foreach (Shape2D *s, m_selectedShapes) {
+    if (s == shape) {
+      shape->setSelected(false);
+      shape->edit(false);
+      m_selectedShapes.removeOne(shape);
+      return;
+    }
+  }
+}
+
+/**
+* Start editing a shape.
+* @param shape :: A shape to edit.
+*/
+void Shape2DCollection::edit(Shape2D *shape) {
+  if (m_currentShape) {
+    m_currentShape->edit(false);
+  }
+  m_currentShape = shape;
+  m_currentShape->edit(true);
+  m_currentCP = m_currentShape->getNControlPoints(); // no current cp until it
+                                                     // is selected explicitly
+  emit shapeSelected();
+}
+
+/**
+* Finish editing the current shape. The shape remains selected.
+*/
+void Shape2DCollection::finishEdit() {
+  if (m_currentShape) {
+    m_currentShape->edit(false);
+    m_currentShape = NULL;
+  }
+}
+
+/**
+* Checks if the screen point (x,y) is inside the current shape.
+*/
+bool Shape2DCollection::isOverCurrentAt(int x, int y) {
+  if (!m_currentShape)
+    return false;
+  QPointF p = m_transform.inverted().map(QPointF(x, y));
+  return m_currentShape->selectAt(p);
+}
+
+/**
+* Checks if the screen point (x,y) is inside any of the selected shapes.
+*/
+bool Shape2DCollection::isOverSelectionAt(int x, int y) {
+  if (m_selectedShapes.isEmpty())
+    return false;
+  QPointF p = m_transform.inverted().map(QPointF(x, y));
+  foreach (Shape2D *shape, m_selectedShapes) {
+    if (shape->selectAt(p))
+      return true;
+  }
+  return false;
+}
+
+bool Shape2DCollection::selectControlPointAt(int x, int y) {
+  // QPointF p = m_transform.inverted().map(QPointF(x,y));
+  QPointF p = QPointF(x, y);
+  if (!m_currentShape)
+    return false;
+  for (size_t i = 0; i < m_currentShape->getNControlPoints(); ++i) {
+    // QPointF cp = m_currentShape->getControlPoint(i) - p;
+    QPointF cp = m_transform.map(m_currentShape->getControlPoint(i)) - p;
+    if (fabs(cp.x()) + fabs(cp.y()) <= sizeCP + 2)
+    // if (cp.manhattanLength() <= sizeCP + 2)
+    {
+      m_currentCP = i;
+      return true;
+    }
+  }
+  // deselect control points
+  m_currentCP = m_currentShape->getNControlPoints();
+  return false;
+}
+
+void Shape2DCollection::deselectControlPoint() {
+  if (m_currentShape) {
+    m_currentCP = m_currentShape->getNControlPoints();
+  }
+}
+
+void Shape2DCollection::removeCurrentShape() {
+  if (m_currentShape) {
+    this->removeShape(m_currentShape);
+    m_currentShape = NULL;
+    emit shapesDeselected();
+  }
+}
+
+/**
+* Removes the selected shapes from this collection.
+*/
+void Shape2DCollection::removeSelectedShapes() {
+  auto shapeList = getSelectedShapes();
+  if (!shapeList.isEmpty()) {
+    removeShapes(shapeList);
+    emit shapesDeselected();
+  }
+}
+
+/**
+* Restore the cursor image to default.
+*/
+void Shape2DCollection::restoreOverrideCursor() {
+  if (m_overridingCursor) {
+    m_overridingCursor = false;
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+void Shape2DCollection::clear() {
+  foreach (Shape2D *shape, m_shapes) { delete shape; }
+  m_shapes.clear();
+  m_selectedShapes.clear();
+  m_currentShape = NULL;
+  emit shapesDeselected();
+}
+
+QStringList Shape2DCollection::getCurrentDoubleNames() const {
+  if (m_currentShape) {
+    return m_currentShape->getDoubleNames();
+  }
+  return QStringList();
+}
+
+double Shape2DCollection::getCurrentDouble(const QString &prop) const {
+  if (m_currentShape) {
+    return m_currentShape->getDouble(prop);
+  }
+  return 0.0;
+}
+
+void Shape2DCollection::setCurrentDouble(const QString &prop, double value) {
+  if (m_currentShape) {
+    return m_currentShape->setDouble(prop, value);
+  }
+}
+
+QStringList Shape2DCollection::getCurrentPointNames() const {
+  if (m_currentShape) {
+    return m_currentShape->getPointNames();
+  }
+  return QStringList();
+}
+
+QPointF Shape2DCollection::getCurrentPoint(const QString &prop) const {
+  if (m_currentShape) {
+    return m_currentShape->getPoint(prop);
+  }
+  return QPointF();
+}
+
+void Shape2DCollection::setCurrentPoint(const QString &prop,
+                                        const QPointF &value) {
+  if (m_currentShape) {
+    return m_currentShape->setPoint(prop, value);
+  }
+}
+
+RectF Shape2DCollection::getCurrentBoundingRect() const {
+  if (m_currentShape) {
+    return m_currentShape->getBoundingRect();
+  }
+  return RectF();
+}
+
+void Shape2DCollection::setCurrentBoundingRect(const RectF &rect) {
+  if (m_currentShape) {
+    m_currentShape->setBoundingRect(rect);
+  }
+}
+
+bool Shape2DCollection::isMasked(double x, double y) const {
+  QPointF p(x, y);
+  foreach (Shape2D *shape, m_shapes) {
+    if (shape->isMasked(p)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+QList<QPoint> Shape2DCollection::getMaskedPixels() const {
+  QList<QPoint> pixels;
+  QTransform inv = m_transform.inverted();
+  for (int i = m_viewport.left(); i <= m_viewport.right(); ++i) {
+    for (int j = m_viewport.top(); j <= m_viewport.bottom(); ++j) {
+      QPoint p = QPoint(i, j);
+      QPointF p0 = inv.map(QPointF(p));
+      foreach (Shape2D *shape, m_shapes) {
+        if (shape->isMasked(p0)) {
+          pixels.append(p);
+        }
+      }
+    }
+  }
+  return pixels;
+}
+
+/**
+* Set the bounding rect of the current shape in real coordinates.
+*/
+void Shape2DCollection::setCurrentBoundingRectReal(const QRectF &rect) {
+  if (!m_currentShape)
+    return;
+  m_currentShape->setBoundingRect(RectF(rect));
+}
+
+/**
+* Change border color.
+*/
+void Shape2DCollection::changeBorderColor(const QColor &color) {
+  foreach (Shape2D *shape, m_shapes) { shape->setColor(color); }
+}
+
+/**
+* Add a Shape2D object allowing free drawing.
+* @param poly :: Initial shape.
+* @param borderColor :: The border colour.
+* @param fillColor :: The fill colour.
+*/
+void Shape2DCollection::addFreeShape(const QPolygonF &poly,
+                                     const QColor &borderColor,
+                                     const QColor &fillColor) {
+  auto freeShape = dynamic_cast<Shape2DFree *>(m_currentShape);
+  if (!freeShape) {
+    if (poly.isEmpty())
+      throw std::logic_error("Cannot create a shape from empty polygon.");
+    auto p = m_transform.inverted().map(poly[0]);
+    addShape("free", static_cast<int>(p.x()), static_cast<int>(p.y()),
+             borderColor, fillColor);
+  }
+  drawFree(poly);
+}
+
+/**
+* Draw the shape by adding a polygon to it.
+*/
+void Shape2DCollection::drawFree(const QPolygonF &polygon) {
+  auto freeShape = dynamic_cast<Shape2DFree *>(m_currentShape);
+  if (freeShape) {
+    auto transform = m_transform.inverted();
+    freeShape->addPolygon(transform.map(polygon));
+    emit shapeChanged();
+  }
+}
+
+/**
+* Erase part of the shape by subtracting a polygon from it.
+*/
+void Shape2DCollection::eraseFree(const QPolygonF &polygon) {
+  auto freeShape = dynamic_cast<Shape2DFree *>(m_currentShape);
+  if (freeShape) {
+    auto transform = m_transform.inverted();
+    freeShape->subtractPolygon(transform.map(polygon));
+    emit shapeChanged();
+  }
+}
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/SimpleWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/SimpleWidget.cpp
index 0db344e1271a996a3693c86b58063409d774ff63..632368fa13ecf64c1db99e6612395e8843b7b3e4 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/SimpleWidget.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/SimpleWidget.cpp
@@ -4,167 +4,146 @@
 #include <QApplication>
 #include <QPixmap>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/// Constructor
-		SimpleWidget::SimpleWidget(QWidget* parent) :QWidget(parent)
-		{
-			// Receive mouse move events
-			setMouseTracking(true);
-			// Receive keyboard events
-			setFocusPolicy(Qt::StrongFocus);
-		}
-
-		SimpleWidget::~SimpleWidget()
-		{
-		}
-
-		/// Assign a surface to draw on
-		void SimpleWidget::setSurface(boost::shared_ptr<ProjectionSurface> surface)
-		{
-			m_surface = surface;
-			connect(m_surface.get(), SIGNAL(redrawRequired()), this, SLOT(repaint()), Qt::QueuedConnection);
-		}
-
-		/// Redraw the view
-		/// @param picking :: Set to true to update the picking image regardless the interaction
-		///   mode of the surface.
-		void SimpleWidget::updateView(bool picking)
-		{
-			if (m_surface)
-			{
-				m_surface->updateView(picking);
-				update();
-			}
-		}
-
-		/// Update the detector information (count values) and redraw
-		void SimpleWidget::updateDetectors()
-		{
-			if (m_surface)
-			{
-				m_surface->updateDetectors();
-				update();
-			}
-		}
-
-		/**
-		* Save widget content to a file.
-		* @param filename :: A file to save to.
-		*/
-		void SimpleWidget::saveToFile(const QString &filename)
-		{
-			QPixmap image(size());
-			render(&image);
-			image.save(filename);
-		}
-
-		void SimpleWidget::paintEvent(QPaintEvent*)
-		{
-			if (m_surface)
-			{
-				m_surface->drawSimple(this);
-			}
-		}
-
-		void SimpleWidget::resizeEvent(QResizeEvent *)
-		{
-			if (m_surface)
-			{
-				m_surface->updateView();
-			}
-		}
-
-		/**
-		* Mouse press callback method, It implements mouse button press initialize methods.
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void SimpleWidget::mousePressEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mousePressEvent(event);
-			}
-			update();
-		}
-
-		/**
-		* This is mouse move callback method. It implements the actions to be taken when the mouse is
-		* moved with a particular button is pressed.
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void SimpleWidget::mouseMoveEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mouseMoveEvent(event);
-			}
-			repaint();
-		}
-
-		/**
-		* This is mouse button release callback method. This resets the cursor to pointing hand cursor
-		* @param event :: This is the event variable which has the position and button states
-		*/
-		void SimpleWidget::mouseReleaseEvent(QMouseEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->mouseReleaseEvent(event);
-			}
-			repaint();
-		}
-
-		/**
-		* Mouse wheel event to set the zooming in and out
-		* @param event :: This is the event variable which has the status of the wheel
-		*/
-		void SimpleWidget::wheelEvent(QWheelEvent* event)
-		{
-			if (m_surface)
-			{
-				m_surface->wheelEvent(event);
-			}
-			update();
-		}
-
-		/**
-		* Key press event
-		* @param event :: This is the event variable which has the status of the keyboard
-		*/
-		void SimpleWidget::keyPressEvent(QKeyEvent *event)
-		{
-			if (m_surface)
-			{
-				m_surface->keyPressEvent(event);
-			}
-			update();
-		}
-
-		void SimpleWidget::enterEvent(QEvent *event)
-		{
-			if (m_surface)
-			{
-				m_surface->enterEvent(event);
-			}
-			update();
-		}
-
-		void SimpleWidget::leaveEvent(QEvent *event)
-		{
-			// Restore possible override cursor
-			while (QApplication::overrideCursor())
-			{
-				QApplication::restoreOverrideCursor();
-			}
-			if (m_surface)
-			{
-				m_surface->leaveEvent(event);
-			}
-			update();
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/// Constructor
+SimpleWidget::SimpleWidget(QWidget *parent) : QWidget(parent) {
+  // Receive mouse move events
+  setMouseTracking(true);
+  // Receive keyboard events
+  setFocusPolicy(Qt::StrongFocus);
+}
+
+SimpleWidget::~SimpleWidget() {}
+
+/// Assign a surface to draw on
+void SimpleWidget::setSurface(boost::shared_ptr<ProjectionSurface> surface) {
+  m_surface = surface;
+  connect(m_surface.get(), SIGNAL(redrawRequired()), this, SLOT(repaint()),
+          Qt::QueuedConnection);
+}
+
+/// Redraw the view
+/// @param picking :: Set to true to update the picking image regardless the
+/// interaction
+///   mode of the surface.
+void SimpleWidget::updateView(bool picking) {
+  if (m_surface) {
+    m_surface->updateView(picking);
+    update();
+  }
+}
+
+/// Update the detector information (count values) and redraw
+void SimpleWidget::updateDetectors() {
+  if (m_surface) {
+    m_surface->updateDetectors();
+    update();
+  }
+}
+
+/**
+* Save widget content to a file.
+* @param filename :: A file to save to.
+*/
+void SimpleWidget::saveToFile(const QString &filename) {
+  QPixmap image(size());
+  render(&image);
+  image.save(filename);
+}
+
+void SimpleWidget::paintEvent(QPaintEvent *) {
+  if (m_surface) {
+    m_surface->drawSimple(this);
+  }
+}
+
+void SimpleWidget::resizeEvent(QResizeEvent *) {
+  if (m_surface) {
+    m_surface->updateView();
+  }
+}
+
+/**
+* Mouse press callback method, It implements mouse button press initialize
+* methods.
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void SimpleWidget::mousePressEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mousePressEvent(event);
+  }
+  update();
+}
+
+/**
+* This is mouse move callback method. It implements the actions to be taken when
+* the mouse is
+* moved with a particular button is pressed.
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void SimpleWidget::mouseMoveEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mouseMoveEvent(event);
+  }
+  repaint();
+}
+
+/**
+* This is mouse button release callback method. This resets the cursor to
+* pointing hand cursor
+* @param event :: This is the event variable which has the position and button
+* states
+*/
+void SimpleWidget::mouseReleaseEvent(QMouseEvent *event) {
+  if (m_surface) {
+    m_surface->mouseReleaseEvent(event);
+  }
+  repaint();
+}
+
+/**
+* Mouse wheel event to set the zooming in and out
+* @param event :: This is the event variable which has the status of the wheel
+*/
+void SimpleWidget::wheelEvent(QWheelEvent *event) {
+  if (m_surface) {
+    m_surface->wheelEvent(event);
+  }
+  update();
+}
+
+/**
+* Key press event
+* @param event :: This is the event variable which has the status of the
+* keyboard
+*/
+void SimpleWidget::keyPressEvent(QKeyEvent *event) {
+  if (m_surface) {
+    m_surface->keyPressEvent(event);
+  }
+  update();
+}
+
+void SimpleWidget::enterEvent(QEvent *event) {
+  if (m_surface) {
+    m_surface->enterEvent(event);
+  }
+  update();
+}
+
+void SimpleWidget::leaveEvent(QEvent *event) {
+  // Restore possible override cursor
+  while (QApplication::overrideCursor()) {
+    QApplication::restoreOverrideCursor();
+  }
+  if (m_surface) {
+    m_surface->leaveEvent(event);
+  }
+  update();
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/StructuredDetectorActor.cpp b/MantidQt/MantidWidgets/src/InstrumentView/StructuredDetectorActor.cpp
index e8c0f0c8f3093bd655becb0ae962b49218d1c723..6b6424ca4388abe142229c4b1444840b41bb6cb4 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/StructuredDetectorActor.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/StructuredDetectorActor.cpp
@@ -31,7 +31,7 @@ namespace MantidWidgets {
 StructuredDetectorActor::StructuredDetectorActor(
     const InstrumentActor &instrActor,
     const Mantid::Geometry::ComponentID &compID)
-    : ICompAssemblyActor(instrActor, compID){
+    : ICompAssemblyActor(instrActor, compID) {
 
   mNumberOfDetectors = 0;
   m_det = boost::dynamic_pointer_cast<const StructuredDetector>(getComponent());
@@ -44,14 +44,13 @@ StructuredDetectorActor::StructuredDetectorActor(
   mNumberOfDetectors = m_det->xPixels() * m_det->yPixels();
   this->AppendBoundingBox(compBox.minPoint(), compBox.maxPoint());
 
-  
   for (size_t y = 0; y < m_det->yPixels(); y++) {
     for (size_t x = 0; x < m_det->xPixels(); x++) {
       // Getting the detector is slow. Get the ID directly
       detid_t id = m_det->getDetectorIDAtXY(x, y);
       size_t pickID = instrActor.pushBackDetid(id);
-	  m_pickIds.push_back(pickID);
-	  m_pickColors.push_back(GLActor::makePickColor(pickID));
+      m_pickIds.push_back(pickID);
+      m_pickColors.push_back(GLActor::makePickColor(pickID));
       m_clist.push_back(instrActor.getColor(id));
     }
   }
@@ -60,8 +59,7 @@ StructuredDetectorActor::StructuredDetectorActor(
 /**
 * Destructor which removes the actors created by this object
 */
-StructuredDetectorActor::~StructuredDetectorActor() {
-}
+StructuredDetectorActor::~StructuredDetectorActor() {}
 
 void StructuredDetectorActor::draw(bool picking) const {
   glPushMatrix();
@@ -188,7 +186,7 @@ void StructuredDetectorActor::AppendBoundingBox(
 }
 
 void StructuredDetectorActor::setColors() {
- //do nothing
+  // do nothing
 }
 
 } // namespace MantidWidgets
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/UCorrectionDialog.cpp b/MantidQt/MantidWidgets/src/InstrumentView/UCorrectionDialog.cpp
index 194aba487a5103d6c6a07df3822ac95cd749895f..d538ebb961151bbd65ded7953cf63a680e575b4f 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/UCorrectionDialog.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/UCorrectionDialog.cpp
@@ -1,47 +1,40 @@
 #include "MantidQtMantidWidgets/InstrumentView/UCorrectionDialog.h"
 #include <ui_UCorrectionDialog.h>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
+UCorrectionDialog::UCorrectionDialog(QWidget *parent, QPointF oldValue,
+                                     bool isManual)
+    : QDialog(parent), ui(new Ui::UCorrectionDialog) {
+  ui->setupUi(this);
+  connect(ui->cbApply, SIGNAL(toggled(bool)), ui->dsbUMin,
+          SLOT(setEnabled(bool)));
+  connect(ui->cbApply, SIGNAL(toggled(bool)), ui->dsbUMax,
+          SLOT(setEnabled(bool)));
+  ui->cbApply->setChecked(isManual);
+  ui->dsbUMin->setValue(oldValue.x());
+  ui->dsbUMax->setValue(oldValue.y());
+  ui->dsbUMin->setEnabled(isManual);
+  ui->dsbUMax->setEnabled(isManual);
+}
 
-		UCorrectionDialog::UCorrectionDialog(QWidget *parent, QPointF oldValue, bool isManual) :
-			QDialog(parent),
-			ui(new Ui::UCorrectionDialog)
-		{
-			ui->setupUi(this);
-			connect(ui->cbApply, SIGNAL(toggled(bool)), ui->dsbUMin, SLOT(setEnabled(bool)));
-			connect(ui->cbApply, SIGNAL(toggled(bool)), ui->dsbUMax, SLOT(setEnabled(bool)));
-			ui->cbApply->setChecked(isManual);
-			ui->dsbUMin->setValue(oldValue.x());
-			ui->dsbUMax->setValue(oldValue.y());
-			ui->dsbUMin->setEnabled(isManual);
-			ui->dsbUMax->setEnabled(isManual);
-		}
+UCorrectionDialog::~UCorrectionDialog() { delete ui; }
 
-		UCorrectionDialog::~UCorrectionDialog()
-		{
-			delete ui;
-		}
+/**
+* If true the manual correction returned by getValue() method should
+* be applied to the surface or use automatic correction if false.
+*/
+bool UCorrectionDialog::applyCorrection() const {
+  return ui->cbApply->isChecked();
+}
 
-		/**
-		* If true the manual correction returned by getValue() method should
-		* be applied to the surface or use automatic correction if false.
-		*/
-		bool UCorrectionDialog::applyCorrection() const
-		{
-			return ui->cbApply->isChecked();
-		}
+/**
+* Get the value of the manual u-correction.
+*/
+QPointF UCorrectionDialog::getValue() const {
+  return QPointF(ui->dsbUMin->value(), ui->dsbUMax->value());
+}
 
-		/**
-		* Get the value of the manual u-correction.
-		*/
-		QPointF UCorrectionDialog::getValue() const
-		{
-			return QPointF(ui->dsbUMin->value(), ui->dsbUMax->value());
-		}
-
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedCylinder.cpp b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedCylinder.cpp
index 62e3ba1baa107aa4de13b4c695d38a84d990e342..865c9226283904b4675ded2d2e87da7a5be3a877 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedCylinder.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedCylinder.cpp
@@ -2,62 +2,60 @@
 
 #include "MantidGeometry/IDetector.h"
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-        UnwrappedCylinder::UnwrappedCylinder(const InstrumentActor *rootActor,
-                                             const Mantid::Kernel::V3D &origin,
-                                             const Mantid::Kernel::V3D &axis)
-            : RotationSurface(rootActor, origin, axis) {
-          init();
-		}
+UnwrappedCylinder::UnwrappedCylinder(const InstrumentActor *rootActor,
+                                     const Mantid::Kernel::V3D &origin,
+                                     const Mantid::Kernel::V3D &axis)
+    : RotationSurface(rootActor, origin, axis) {
+  init();
+}
 
-		//------------------------------------------------------------------------------
-		/** Convert physical position to UV projection
-		*
-		* @param pos :: position in 3D
-		* @param u :: set to U
-		* @param v :: set to V
-		* @param uscale :: scaling for u direction
-		* @param vscale :: scaling for v direction
-		*/
-		void UnwrappedCylinder::project(const Mantid::Kernel::V3D & pos, double & u, double & v, double & uscale, double & vscale) const
-		{
-			// projection to cylinder axis
-			v = pos.scalar_prod(m_zaxis);
-			double x = pos.scalar_prod(m_xaxis);
-			double y = pos.scalar_prod(m_yaxis);
-			u = applyUCorrection(-atan2(y, x));
+//------------------------------------------------------------------------------
+/** Convert physical position to UV projection
+*
+* @param pos :: position in 3D
+* @param u :: set to U
+* @param v :: set to V
+* @param uscale :: scaling for u direction
+* @param vscale :: scaling for v direction
+*/
+void UnwrappedCylinder::project(const Mantid::Kernel::V3D &pos, double &u,
+                                double &v, double &uscale,
+                                double &vscale) const {
+  // projection to cylinder axis
+  v = pos.scalar_prod(m_zaxis);
+  double x = pos.scalar_prod(m_xaxis);
+  double y = pos.scalar_prod(m_yaxis);
+  u = applyUCorrection(-atan2(y, x));
 
-			uscale = 1. / sqrt(x*x + y*y);
-			vscale = 1.;
-		}
+  uscale = 1. / sqrt(x * x + y * y);
+  vscale = 1.;
+}
 
-		void UnwrappedCylinder::rotate(const UnwrappedDetector& udet, Mantid::Kernel::Quat& R)const
-		{
-			// direction in which to look 
-			Mantid::Kernel::V3D eye;
-			// rotation from the global axes to those where
-			// the z axis points to the detector
-			Mantid::Kernel::Quat R1;
-			eye = m_pos - udet.detector->getPos();
-			if (!eye.nullVector())
-			{
-				// eye must point towards the detector and be perpendicular to the cylinder's axis
-				Mantid::Kernel::V3D up = m_zaxis;
-				up.normalize();
-				eye = eye - up * eye.scalar_prod(up);
-				if (!eye.nullVector())
-				{
-					eye.normalize();
-					InstrumentActor::rotateToLookAt(eye, up, R1);
-				}
-			}
-			// add detector's own rotation
-			R = R1 * udet.detector->getRotation();
-		}
+void UnwrappedCylinder::rotate(const UnwrappedDetector &udet,
+                               Mantid::Kernel::Quat &R) const {
+  // direction in which to look
+  Mantid::Kernel::V3D eye;
+  // rotation from the global axes to those where
+  // the z axis points to the detector
+  Mantid::Kernel::Quat R1;
+  eye = m_pos - udet.detector->getPos();
+  if (!eye.nullVector()) {
+    // eye must point towards the detector and be perpendicular to the
+    // cylinder's axis
+    Mantid::Kernel::V3D up = m_zaxis;
+    up.normalize();
+    eye = eye - up * eye.scalar_prod(up);
+    if (!eye.nullVector()) {
+      eye.normalize();
+      InstrumentActor::rotateToLookAt(eye, up, R1);
+    }
+  }
+  // add detector's own rotation
+  R = R1 * udet.detector->getRotation();
+}
 
-	}//MantidWidgets
-}//MantidQt
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSphere.cpp b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSphere.cpp
index 89407cbe2aba30e37a7e9090e09d87395fb60bbe..1f4a48b1ca8e77c6cab14712eea8aea8329640d3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSphere.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSphere.cpp
@@ -2,58 +2,54 @@
 #include "MantidGeometry/IDetector.h"
 #include <cmath>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-        UnwrappedSphere::UnwrappedSphere(const InstrumentActor *rootActor,
-                                         const Mantid::Kernel::V3D &origin,
-                                         const Mantid::Kernel::V3D &axis)
-            : RotationSurface(rootActor, origin, axis) {
-          init();
-		}
-
-		//------------------------------------------------------------------------------
-		/** Convert physical position to UV projection
-		*
-		* @param pos :: position in 3D
-		* @param u :: set to U
-		* @param v :: set to V
-		* @param uscale :: scaling for u direction
-		* @param vscale :: scaling for v direction
-		*/
-		void UnwrappedSphere::project(const Mantid::Kernel::V3D & pos, double & u, double & v, double & uscale, double & vscale) const
-		{
-			// projection to cylinder axis
-			v = pos.scalar_prod(m_zaxis);
-			double x = pos.scalar_prod(m_xaxis);
-			double y = pos.scalar_prod(m_yaxis);
-
-			double r = sqrt(x*x + y*y + v*v);
-			uscale = 1. / sqrt(x*x + y*y);
-			vscale = 1. / r;
-
-			u = applyUCorrection(-atan2(y, x));
-			v = -acos(v / r);
-		}
-
-		void UnwrappedSphere::rotate(const UnwrappedDetector& udet, Mantid::Kernel::Quat& R)const
-		{
-			// rotation from the global axes to those where
-			// the z axis points to the detector
-			Mantid::Kernel::Quat R1;
-			// direction in which to look: from sample to detector
-			Mantid::Kernel::V3D eye;
-			eye = m_pos - udet.detector->getPos();
-			if (!eye.nullVector())
-			{
-				InstrumentActor::rotateToLookAt(eye, m_zaxis, R1);
-			}
-			// add detector's own rotation
-			R = R1 * udet.detector->getRotation();
-		}
-
-	}//MantidWidgets
-}//MantidQt
-
+namespace MantidQt {
+namespace MantidWidgets {
+
+UnwrappedSphere::UnwrappedSphere(const InstrumentActor *rootActor,
+                                 const Mantid::Kernel::V3D &origin,
+                                 const Mantid::Kernel::V3D &axis)
+    : RotationSurface(rootActor, origin, axis) {
+  init();
+}
+
+//------------------------------------------------------------------------------
+/** Convert physical position to UV projection
+*
+* @param pos :: position in 3D
+* @param u :: set to U
+* @param v :: set to V
+* @param uscale :: scaling for u direction
+* @param vscale :: scaling for v direction
+*/
+void UnwrappedSphere::project(const Mantid::Kernel::V3D &pos, double &u,
+                              double &v, double &uscale, double &vscale) const {
+  // projection to cylinder axis
+  v = pos.scalar_prod(m_zaxis);
+  double x = pos.scalar_prod(m_xaxis);
+  double y = pos.scalar_prod(m_yaxis);
+
+  double r = sqrt(x * x + y * y + v * v);
+  uscale = 1. / sqrt(x * x + y * y);
+  vscale = 1. / r;
+
+  u = applyUCorrection(-atan2(y, x));
+  v = -acos(v / r);
+}
+
+void UnwrappedSphere::rotate(const UnwrappedDetector &udet,
+                             Mantid::Kernel::Quat &R) const {
+  // rotation from the global axes to those where
+  // the z axis points to the detector
+  Mantid::Kernel::Quat R1;
+  // direction in which to look: from sample to detector
+  Mantid::Kernel::V3D eye;
+  eye = m_pos - udet.detector->getPos();
+  if (!eye.nullVector()) {
+    InstrumentActor::rotateToLookAt(eye, m_zaxis, R1);
+  }
+  // add detector's own rotation
+  R = R1 * udet.detector->getRotation();
+}
+
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSurface.cpp b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSurface.cpp
index b71608565b540dba080d5aed3563f974a0898f33..7ec6296f35c825d5f98e97e3a906c10aae69f2c2 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSurface.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/UnwrappedSurface.cpp
@@ -25,739 +25,696 @@
 using namespace Mantid::Geometry;
 using Mantid::Kernel::Exception::NotFoundError;
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		UnwrappedDetector::UnwrappedDetector() :
-			u(0), v(0), width(0), height(0), uscale(0), vscale(0), detector()
-		{
-			color[0] = 0;
-			color[1] = 0;
-			color[2] = 0;
-		}
-
-		UnwrappedDetector::UnwrappedDetector(const unsigned char* c,
-			boost::shared_ptr<const IDetector> det
-			) :
-			u(0), v(0), width(0), height(0), uscale(0), vscale(0), detector(det)
-		{
-			color[0] = *c;
-			color[1] = *(c + 1);
-			color[2] = *(c + 2);
-		}
-
-		/** Copy constructor */
-		UnwrappedDetector::UnwrappedDetector(const UnwrappedDetector & other)
-		{
-			this->operator =(other);
-		}
-
-		/** Assignment operator */
-		UnwrappedDetector & UnwrappedDetector::operator=(const UnwrappedDetector & other)
-		{
-			u = other.u;
-			v = other.v;
-			width = other.width;
-			height = other.height;
-			uscale = other.uscale;
-			vscale = other.vscale;
-			detector = other.detector;
-			color[0] = other.color[0];
-			color[1] = other.color[1];
-			color[2] = other.color[2];
-			return *this;
-		}
-
-		/**
-		* Constructor.
-		* @param rootActor :: The instrument actor.
-		*/
-		UnwrappedSurface::UnwrappedSurface(const InstrumentActor* rootActor) :
-			ProjectionSurface(rootActor),
-			m_u_min(DBL_MAX),
-			m_u_max(-DBL_MAX),
-			m_v_min(DBL_MAX),
-			m_v_max(-DBL_MAX),
-			m_height_max(0),
-			m_width_max(0),
-			m_flippedView(false),
-			m_startPeakShapes(false)
-		{
-			// create and set the move input controller
-			InputControllerMoveUnwrapped* moveController = new InputControllerMoveUnwrapped(this);
-			setInputController(MoveMode, moveController);
-			connect(moveController, SIGNAL(setSelectionRect(QRect)), this, SLOT(setSelectionRect(QRect)));
-			connect(moveController, SIGNAL(zoom()), this, SLOT(zoom()));
-			connect(moveController, SIGNAL(unzoom()), this, SLOT(unzoom()));
-		}
-
-		/**
-		* Get information about the dimensions of the surface.
-		*/
-		QString UnwrappedSurface::getDimInfo() const
-		{
-			return QString("U: [%1, %2] V: [%3, %4]").arg(m_viewRect.x0()).arg(m_viewRect.x1()).arg(m_viewRect.y0()).arg(m_viewRect.y1());
-		}
-
-
-		//------------------------------------------------------------------------------
-		/** Calculate the rectangular region in uv coordinates occupied by an assembly.
-		*
-		* @param comp :: A member of the assembly. The total area of the assembly is a sum of areas of its members
-		* @param compRect :: A rect. area occupied by comp in uv space
-		*/
-		void UnwrappedSurface::calcAssemblies(const Mantid::Geometry::IComponent * comp, const QRectF& compRect)
-		{
-			// We don't need the parametrized version = use the bare parent for speed
-			const Mantid::Geometry::IComponent * parent = comp->getBareParent();
-			if (parent)
-			{
-				QRectF& r = m_assemblies[parent->getComponentID()];
-				r |= compRect;
-				calcAssemblies(parent, r);
-			}
-		}
-
-
-		//------------------------------------------------------------------------------
-		/** If needed, recalculate the cached bounding rectangles of all assemblies. */
-		void UnwrappedSurface::cacheAllAssemblies()
-		{
-			if (!m_assemblies.empty())
-				return;
-
-			for (size_t i = 0; i<m_unwrappedDetectors.size(); ++i)
-			{
-				const UnwrappedDetector& udet = m_unwrappedDetectors[i];
-
-				if (!udet.detector) continue;
-				// Get the BARE parent (not parametrized) to speed things up.
-				const Mantid::Geometry::IComponent * bareDet = udet.detector->getComponentID();
-				const Mantid::Geometry::IComponent * parent = bareDet->getBareParent();
-				if (parent)
-				{
-					QRectF detRect;
-					detRect.setLeft(udet.u - udet.width);
-					detRect.setRight(udet.u + udet.width);
-					detRect.setBottom(udet.v - udet.height);
-					detRect.setTop(udet.v + udet.height);
-					Mantid::Geometry::ComponentID id = parent->getComponentID();
-					QRectF& r = m_assemblies[id];
-					r |= detRect;
-					calcAssemblies(parent, r);
-				}
-			}
-		}
-
-		//------------------------------------------------------------------------------
-		/**
-		* Draw the unwrapped instrument onto the screen
-		* @param widget :: The widget to draw it on.
-		* @param picking :: True if detector is being drawn in the picking mode.
-		*/
-		void UnwrappedSurface::drawSurface(MantidGLWidget *widget, bool picking)const
-		{
-			// dimensions of the screen to draw on
-			int widget_width = widget->width();
-			int widget_height = widget->height();
-
-			// view rectangle in the OpenGL coordinates
-			double view_left = m_viewRect.x0();
-			double view_top = m_viewRect.y1();
-			double view_right = m_viewRect.x1();
-			double view_bottom = m_viewRect.y0();
-
-			// make sure the view rectangle has a finite area
-			if (view_left == view_right)
-			{
-				view_left -= m_width_max / 2;
-				view_right += m_width_max / 2;
-			}
-			if (view_top == view_bottom)
-			{
-				view_top += m_height_max / 2;
-				view_bottom -= m_height_max / 2;
-			}
-
-			const double dw = fabs((view_right - view_left) / widget_width);
-			const double dh = fabs((view_top - view_bottom) / widget_height);
-
-			if (m_startPeakShapes)
-			{
-				createPeakShapes(widget->rect());
-			}
-
-			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-			glViewport(0, 0, widget_width, widget_height);
-			glMatrixMode(GL_PROJECTION);
-			glLoadIdentity();
-			glOrtho(view_left, view_right, view_bottom, view_top, -10, 10);
-
-			if (OpenGLError::hasError("UnwrappedSurface::drawSurface"))
-			{
-				OpenGLError::log() << "glOrtho arguments:\n";
-				OpenGLError::log() << view_left << ',' << view_right << ','
-					<< view_bottom << ',' << view_top << ','
-					<< -10 << ',' << 10 << '\n';
-			}
-			glMatrixMode(GL_MODELVIEW);
-			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-
-			GLfloat oldLineWidth;
-			glGetFloatv(GL_LINE_WIDTH, &oldLineWidth);
-			glLineWidth(1.0f);
-
-			glLoadIdentity();
-
-			if (m_isLightingOn && !picking)
-			{
-				glShadeModel(GL_SMOOTH);           // Shade model is smooth
-				glEnable(GL_LINE_SMOOTH);          // Set line should be drawn smoothly
-				glEnable(GL_LIGHT0);               // Enable opengl second light
-				float diffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
-				glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
-				float direction[3] = { 0.0f, 0.0f, 1.0f };
-				glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, direction);
-
-				glEnable(GL_LIGHTING);            // Enable overall lighting
-			}
-			else
-			{
-				glDisable(GL_LIGHT0);
-				glDisable(GL_LIGHTING);
-				glDisable(GL_LINE_SMOOTH);
-				glShadeModel(GL_FLAT);
-			}
-
-			for (size_t i = 0; i<m_unwrappedDetectors.size(); ++i)
-			{
-				const UnwrappedDetector& udet = m_unwrappedDetectors[i];
-
-				if (!udet.detector) continue;
-
-				int iw = int(udet.width / dw);
-				int ih = int(udet.height / dh);
-				double w = (iw == 0) ? dw : udet.width / 2;
-				double h = (ih == 0) ? dh : udet.height / 2;
-
-				// check that the detector is visible in the current view
-				if (!(m_viewRect.contains(udet.u - w, udet.v - h) || m_viewRect.contains(udet.u + w, udet.v + h))) continue;
-				//QRectF detectorRect(udet.u-w,udet.v+h,w*2,h*2);
-				//if ( !m_viewRect.intersects(detectorRect) ) continue;
-
-				// apply the detector's colour
-				setColor(int(i), picking);
-
-				// if the detector is too small to see its shape draw a rectangle
-				if (iw < 6 || ih < 6)
-				{
-					glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-					glRectd(udet.u - w, udet.v - h, udet.u + w, udet.v + h);
-					glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-					if (iw > 2 || ih > 2)
-					{
-						glRectd(udet.u - w, udet.v - h, udet.u + w, udet.v + h);
-					}
-				}
-				// else draw the correct shape
-				else
-				{
-					glPushMatrix();
-
-					glTranslated(udet.u, udet.v, 0.);
-					glScaled(udet.uscale, udet.vscale, 1);
-
-					Mantid::Kernel::Quat rot;
-					this->rotate(udet, rot);
-					double deg, ax0, ax1, ax2;
-					rot.getAngleAxis(deg, ax0, ax1, ax2);
-					glRotated(deg, ax0, ax1, ax2);
-
-					Mantid::Kernel::V3D scaleFactor = udet.detector->getScaleFactor();
-					glScaled(scaleFactor[0], scaleFactor[1], scaleFactor[2]);
-
-					udet.detector->shape()->draw();
-
-					glPopMatrix();
-
-				}
-
-			}
-
-			OpenGLError::check("UnwrappedSurface::drawSurface");
-
-			glLineWidth(oldLineWidth);
-
-			if (OpenGLError::check("UnwrappedSurface::drawSurface"))
-			{
-				OpenGLError::log() << "oldLineWidth=" << oldLineWidth << '\n';
-			}
-
-		}
-
-
-		/**
-		* Set detector color in OpenGL context.
-		* @param index :: Detector's index in m_unwrappedDetectors
-		* @param picking :: True if detector is being drawn in the picking mode.
-		*   In this case index is transformed into color
-		*/
-		void UnwrappedSurface::setColor(int index, bool picking)const
-		{
-			if (picking)
-			{
-				GLColor c = GLActor::makePickColor(index);
-				unsigned char r, g, b;
-				c.get(r, g, b);
-				glColor3ub(r, g, b);
-			}
-			else
-			{
-				glColor3ubv(&m_unwrappedDetectors[index].color[0]);
-			}
-		}
-
-		bool hasParent(boost::shared_ptr<const Mantid::Geometry::IComponent> comp, Mantid::Geometry::ComponentID id)
-		{
-			boost::shared_ptr<const Mantid::Geometry::IComponent> parent = comp->getParent();
-			if (!parent) return false;
-			if (parent->getComponentID() == id) return true;
-			return hasParent(parent, id);
-		}
-
-		//------------------------------------------------------------------------------
-		/** This method is called when a component is selected in the InstrumentTreeWidget
-		* and zooms into that spot on the view.
-		*
-		* @param id :: ComponentID to zoom to.
-		*/
-		void UnwrappedSurface::componentSelected(Mantid::Geometry::ComponentID id)
-		{
-			boost::shared_ptr<const Mantid::Geometry::Instrument> instr = m_instrActor->getInstrument();
-			if (id == NULL)
-			{
-				id = instr->getComponentID();
-			}
-			boost::shared_ptr<const Mantid::Geometry::IComponent> comp = instr->getComponentByID(id);
-			boost::shared_ptr<const Mantid::Geometry::ICompAssembly> ass =
-				boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(comp);
-			boost::shared_ptr<const Mantid::Geometry::IDetector> det =
-				boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector>(comp);
-			if (det)
-			{
-				int detID = det->getID();
-
-				std::vector<UnwrappedDetector>::const_iterator it;
-				for (it = m_unwrappedDetectors.begin(); it != m_unwrappedDetectors.end(); ++it)
-				{
-					const UnwrappedDetector& udet = *it;
-					if (udet.detector && udet.detector->getID() == detID)
-					{
-						double w = udet.width;
-						if (w > m_width_max) w = m_width_max;
-						double h = udet.height;
-						if (h > m_height_max) h = m_height_max;
-						QRectF area(udet.u - w, udet.v - h, w * 2, h * 2);
-						zoom(area);
-						break;
-					}
-				}
-			}
-			if (ass)
-			{
-				this->cacheAllAssemblies();
-				QMap<Mantid::Geometry::ComponentID, QRectF>::iterator assRect = m_assemblies.find(ass->getComponentID());
-				if (assRect != m_assemblies.end())
-					zoom(*assRect);
-				else
-				{
-					// std::cout << "Assembly not found " << std::endl;
-				}
-			}
-		}
-
-		void UnwrappedSurface::getSelectedDetectors(QList<int>& dets)
-		{
-			if (m_selectRect.isNull())
-			{
-				return;
-			}
-			QRect rect = selectionRect();
-
-			double vtop = m_v_min;
-			double vbottom = m_v_min;
-			double uleft = m_u_min;
-			double uright = m_u_min;
-
-			// find the first picking colours different from black (0,0,0) to get the top-left
-			// and bottom-right detectors
-			int rwidth = rect.width();
-			int rheight = rect.height();
-			for (int i = 0; i<rwidth; ++i)
-			{
-				bool stop = false;
-				for (int j = 0; j<rheight; ++j)
-				{
-					int x = rect.x() + i;
-					int y = rect.y() + j;
-					size_t ind = getPickID(x, y);
-					if (ind < m_unwrappedDetectors.size())
-					{
-						uleft = m_unwrappedDetectors[ind].u - m_unwrappedDetectors[ind].width / 2;
-						vtop = m_unwrappedDetectors[ind].v + m_unwrappedDetectors[ind].height / 2;
-						stop = true;
-						break;
-					}
-				}
-				if (stop) break;
-			}
-
-			for (int i = rwidth - 1; i >= 0; --i)
-			{
-				bool stop = false;
-				for (int j = rheight - 1; j >= 0; --j)
-				{
-					int x = rect.x() + i;
-					int y = rect.y() + j;
-					size_t ind = getPickID(x, y);
-					if (ind < m_unwrappedDetectors.size())
-					{
-						uright = m_unwrappedDetectors[ind].u + m_unwrappedDetectors[ind].width / 2;
-						vbottom = m_unwrappedDetectors[ind].v - m_unwrappedDetectors[ind].height / 2;
-						stop = true;
-						break;
-					}
-				}
-				if (stop) break;
-			}
-
-			// select detectors with u,v within the allowed boundaries
-			for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i)
-			{
-				UnwrappedDetector& udet = m_unwrappedDetectors[i];
-				if (!udet.detector) continue;
-				if (udet.u >= uleft && udet.u <= uright && udet.v >= vbottom && udet.v <= vtop)
-				{
-					dets.push_back(udet.detector->getID());
-				}
-			}
-
-		}
-
-		void UnwrappedSurface::getMaskedDetectors(QList<int>& dets)const
-		{
-			dets.clear();
-			if (m_maskShapes.isEmpty()) return;
-			for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i)
-			{
-				const UnwrappedDetector& udet = m_unwrappedDetectors[i];
-				if (!udet.detector) continue;
-				if (m_maskShapes.isMasked(udet.u, udet.v))
-				{
-					dets.append(udet.detector->getID());
-				}
-			}
-		}
-
-		void UnwrappedSurface::changeColorMap()
-		{
-			for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i)
-			{
-				UnwrappedDetector& udet = m_unwrappedDetectors[i];
-				if (!udet.detector) continue;
-				unsigned char color[3];
-				m_instrActor->getColor(udet.detector->getID()).getUB3(&color[0]);
-				udet.color[0] = color[0];
-				udet.color[1] = color[1];
-				udet.color[2] = color[2];
-			}
-		}
-
-		QString UnwrappedSurface::getInfoText()const
-		{
-			if (m_interactionMode == MoveMode)
-			{
-				//return getDimInfo() +
-				return "Left mouse click and drag to zoom in. Right mouse click to zoom out.";
-			}
-			return ProjectionSurface::getInfoText();
-		}
-
-		RectF UnwrappedSurface::getSurfaceBounds()const
-		{
-			return m_viewRect;
-		}
-
-		/**
-		* Set a peaks workspace to be drawn ontop of the workspace.
-		* @param pws :: A shared pointer to the workspace.
-		*/
-		void UnwrappedSurface::setPeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws)
-		{
-			if (!pws)
-			{
-				return;
-			}
-			PeakOverlay* po = new PeakOverlay(this, pws);
-			po->setPrecision(m_peakLabelPrecision);
-			po->setShowRowsFlag(m_showPeakRows);
-			po->setShowLabelsFlag(m_showPeakLabels);
-			po->setShowRelativeIntensityFlag(m_showPeakRelativeIntensity);
-			m_peakShapes.append(po);
-			m_startPeakShapes = true;
-			connect(po, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)), this, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)));
-			emit peaksWorkspaceAdded();
-		}
-
-		//-----------------------------------------------------------------------------
-		/** Create the peak labels from the peaks set by setPeaksWorkspace.
-		* The method is called from the draw(...) method
-		*
-		* @param window :: The screen window rectangle in pixels.
-		*/
-		void UnwrappedSurface::createPeakShapes(const QRect& window)const
-		{
-			if (!m_peakShapes.isEmpty())
-			{
-				QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-				PeakOverlay& peakShapes = *m_peakShapes.last();
-				PeakMarker2D::Style style = peakShapes.getDefaultStyle(m_peakShapesStyle);
-				m_peakShapesStyle++;
-				peakShapes.setWindow(getSurfaceBounds(), window);
-				peakShapes.createMarkers(style);
-				QApplication::restoreOverrideCursor();
-			}
-			m_startPeakShapes = false;
-			setPeakVisibility();
-		}
-
-		/**
-		* Toggle between flipped and straight view.
-		*/
-		void UnwrappedSurface::setFlippedView(bool on)
-		{
-			if (m_flippedView != on)
-			{
-				m_flippedView = on;
-				m_viewRect.xFlip();
-				for (int i = 0; i < m_zoomStack.size(); ++i)
-				{
-					m_zoomStack[i].xFlip();
-				}
-			}
-		}
-
-		/**
-		* Draw the surface onto an image without OpenGL
-		* @param image :: Image to draw on.
-		* @param picking :: If true draw a picking image.
-		*/
-		void UnwrappedSurface::drawSimpleToImage(QImage* image, bool picking)const
-		{
-			if (!image) return;
-
-			QPainter paint(image);
-
-			int vwidth = image->width();
-			int vheight = image->height();
-
-			paint.fillRect(0, 0, vwidth, vheight, m_backgroundColor);
-
-			const double dw = fabs(m_viewRect.width() / vwidth);
-			const double dh = fabs(m_viewRect.height() / vheight);
-
-			//std::cerr << m_viewRect.left() << ' ' << m_viewRect.right() << " : " <<  m_viewRect.bottom() << ' ' << m_viewRect.top() << std::endl;
-
-			if (m_startPeakShapes)
-			{
-				createPeakShapes(image->rect());
-			}
-
-			for (size_t i = 0; i<m_unwrappedDetectors.size(); ++i)
-			{
-				const UnwrappedDetector& udet = m_unwrappedDetectors[i];
-
-				if (!udet.detector) continue;
-
-				int iw = int(udet.width / dw);
-				int ih = int(udet.height / dh);
-				if (iw < 4) iw = 4;
-				if (ih < 4) ih = 4;
-
-				double w = udet.width / 2;
-				double h = udet.height / 2;
-
-				if (!(m_viewRect.contains(udet.u - w, udet.v - h) || m_viewRect.contains(udet.u + w, udet.v + h))) continue;
-
-				int u = 0;
-				if (!isFlippedView())
-				{
-					u = static_cast<int>((udet.u - m_viewRect.x0()) / dw);
-				}
-				else
-				{
-					u = static_cast<int>(vwidth - (udet.u - m_viewRect.x1()) / dw);
-				}
-
-				int v = vheight - static_cast<int>((udet.v - m_viewRect.y0()) / dh);
-
-				QColor color;
-				int index = int(i);
-				if (picking)
-				{
-					GLColor c = GLActor::makePickColor(index);
-					unsigned char r, g, b;
-					c.get(r, g, b);
-					color = QColor(r, g, b);
-				}
-				else
-				{
-					auto c = &m_unwrappedDetectors[index].color[0];
-					color = QColor(c[0], c[1], c[2]);
-				}
-
-				paint.fillRect(u - iw / 2, v - ih / 2, iw, ih, color);
-
-			}
-
-			// draw custom stuff
-			if (!picking)
-			{
-				// TODO: this transform should be done for drawing the detectors
-				QTransform transform;
-				m_viewRect.findTransform(transform, QRectF(0, 0, vwidth, vheight));
-				paint.setTransform(transform);
-				drawCustom(&paint);
-			}
-		}
-
-		/**
-		* Zooms to the specified area. The previous zoom stack is cleared.
-		*/
-		void UnwrappedSurface::zoom(const QRectF& area)
-		{
-			if (!m_zoomStack.isEmpty())
-			{
-				m_viewRect = m_zoomStack.first();
-				m_zoomStack.clear();
-			}
-			m_zoomStack.push(m_viewRect);
-
-			double left = area.left();
-			double top = area.top();
-			double width = area.width();
-			double height = area.height();
-
-			if (width * m_viewRect.width() < 0)
-			{
-				left += width;
-				width = -width;
-			}
-			if (height * m_viewRect.height() < 0)
-			{
-				top += height;
-				height = -height;
-			}
-			m_viewRect = RectF(QPointF(left, top), QPointF(left + width, top + height));
-			updateView();
-
-		}
-
-		void UnwrappedSurface::unzoom()
-		{
-			if (!m_zoomStack.isEmpty())
-			{
-				m_viewRect = m_zoomStack.pop();
-				updateView();
-				emit updateInfoText();
-			}
-		}
-
-		void UnwrappedSurface::zoom()
-		{
-			if (!m_viewImage) return;
-			RectF newView = selectionRectUV();
-			if (newView.isEmpty()) return;
-			m_zoomStack.push(m_viewRect);
-			m_viewRect = newView;
-			updateView();
-			emptySelectionRect();
-			emit updateInfoText();
-		}
-
-		//------------------------------------------------------------------------------
-		/** Calculate the UV and size of the given detector
-		* Calls the pure virtual project() and calcSize() methods that
-		* depend on the type of projection
-		*
-		* @param udet :: detector to unwrap.
-		* @param pos :: detector position relative to the sample origin
-		*/
-		void UnwrappedSurface::calcUV(UnwrappedDetector& udet, Mantid::Kernel::V3D & pos)
-		{
-			this->project(pos, udet.u, udet.v, udet.uscale, udet.vscale);
-			calcSize(udet);
-		}
-
-		//------------------------------------------------------------------------------
-		/** Calculate the size of the detector in U/V
-		*
-		* @param udet :: UwrappedDetector struct to calculate the size for. udet's size fields
-		* are updated by this method.
-		*/
-		void UnwrappedSurface::calcSize(UnwrappedDetector& udet)
-		{
-			// U is the horizontal axis on the screen
-			const Mantid::Kernel::V3D U(-1, 0, 0);
-			// V is the vertical axis on the screen
-			const Mantid::Kernel::V3D V(0, 1, 0);
-
-			// find the detector's rotation
-			Mantid::Kernel::Quat R;
-			this->rotate(udet, R);
-
-			Mantid::Geometry::BoundingBox bbox = udet.detector->shape()->getBoundingBox();
-			Mantid::Kernel::V3D scale = udet.detector->getScaleFactor();
-
-			// sizes of the detector along each 3D axis
-			Mantid::Kernel::V3D size = bbox.maxPoint() - bbox.minPoint();
-			size *= scale;
-
-			Mantid::Kernel::V3D s1(size);
-			Mantid::Kernel::V3D s2 = size + Mantid::Kernel::V3D(-size.X(), 0, 0) - Mantid::Kernel::V3D(size.X(), 0, 0);
-			Mantid::Kernel::V3D s3 = size + Mantid::Kernel::V3D(0, -size.Y(), 0) - Mantid::Kernel::V3D(0, size.Y(), 0);
-			// rotate the size vectors to get the dimensions along axes U and V
-			R.rotate(s1);
-			R.rotate(s2);
-			R.rotate(s3);
-
-			// get the larges projection to the U axis which is the visible width
-			double d = fabs(s1.scalar_prod(U));
-			udet.width = d;
-			d = fabs(s2.scalar_prod(U));
-			if (d > udet.width) udet.width = d;
-			d = fabs(s3.scalar_prod(U));
-			if (d > udet.width) udet.width = d;
-
-			// get the larges projection to the V axis which is the visible height
-			d = fabs(s1.scalar_prod(V));
-			udet.height = d;
-			d = fabs(s2.scalar_prod(V));
-			if (d > udet.height) udet.height = d;
-			d = fabs(s3.scalar_prod(V));
-			if (d > udet.height) udet.height = d;
-
-			// apply the scale factors
-			udet.width *= udet.uscale;
-			udet.height *= udet.vscale;
-
-			// don't let them be too large
-			if (udet.width > m_width_max) m_width_max = udet.width;
-			if (udet.height > m_height_max) m_height_max = udet.height;
-
-		}
-
-	}//MantidWidgets
-}//MantidQt
\ No newline at end of file
+namespace MantidQt {
+namespace MantidWidgets {
+
+UnwrappedDetector::UnwrappedDetector()
+    : u(0), v(0), width(0), height(0), uscale(0), vscale(0), detector() {
+  color[0] = 0;
+  color[1] = 0;
+  color[2] = 0;
+}
+
+UnwrappedDetector::UnwrappedDetector(const unsigned char *c,
+                                     boost::shared_ptr<const IDetector> det)
+    : u(0), v(0), width(0), height(0), uscale(0), vscale(0), detector(det) {
+  color[0] = *c;
+  color[1] = *(c + 1);
+  color[2] = *(c + 2);
+}
+
+/** Copy constructor */
+UnwrappedDetector::UnwrappedDetector(const UnwrappedDetector &other) {
+  this->operator=(other);
+}
+
+/** Assignment operator */
+UnwrappedDetector &UnwrappedDetector::
+operator=(const UnwrappedDetector &other) {
+  u = other.u;
+  v = other.v;
+  width = other.width;
+  height = other.height;
+  uscale = other.uscale;
+  vscale = other.vscale;
+  detector = other.detector;
+  color[0] = other.color[0];
+  color[1] = other.color[1];
+  color[2] = other.color[2];
+  return *this;
+}
+
+/**
+* Constructor.
+* @param rootActor :: The instrument actor.
+*/
+UnwrappedSurface::UnwrappedSurface(const InstrumentActor *rootActor)
+    : ProjectionSurface(rootActor), m_u_min(DBL_MAX), m_u_max(-DBL_MAX),
+      m_v_min(DBL_MAX), m_v_max(-DBL_MAX), m_height_max(0), m_width_max(0),
+      m_flippedView(false), m_startPeakShapes(false) {
+  // create and set the move input controller
+  InputControllerMoveUnwrapped *moveController =
+      new InputControllerMoveUnwrapped(this);
+  setInputController(MoveMode, moveController);
+  connect(moveController, SIGNAL(setSelectionRect(QRect)), this,
+          SLOT(setSelectionRect(QRect)));
+  connect(moveController, SIGNAL(zoom()), this, SLOT(zoom()));
+  connect(moveController, SIGNAL(unzoom()), this, SLOT(unzoom()));
+}
+
+/**
+* Get information about the dimensions of the surface.
+*/
+QString UnwrappedSurface::getDimInfo() const {
+  return QString("U: [%1, %2] V: [%3, %4]")
+      .arg(m_viewRect.x0())
+      .arg(m_viewRect.x1())
+      .arg(m_viewRect.y0())
+      .arg(m_viewRect.y1());
+}
+
+//------------------------------------------------------------------------------
+/** Calculate the rectangular region in uv coordinates occupied by an assembly.
+*
+* @param comp :: A member of the assembly. The total area of the assembly is a
+*sum of areas of its members
+* @param compRect :: A rect. area occupied by comp in uv space
+*/
+void UnwrappedSurface::calcAssemblies(const Mantid::Geometry::IComponent *comp,
+                                      const QRectF &compRect) {
+  // We don't need the parametrized version = use the bare parent for speed
+  const Mantid::Geometry::IComponent *parent = comp->getBareParent();
+  if (parent) {
+    QRectF &r = m_assemblies[parent->getComponentID()];
+    r |= compRect;
+    calcAssemblies(parent, r);
+  }
+}
+
+//------------------------------------------------------------------------------
+/** If needed, recalculate the cached bounding rectangles of all assemblies. */
+void UnwrappedSurface::cacheAllAssemblies() {
+  if (!m_assemblies.empty())
+    return;
+
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    const UnwrappedDetector &udet = m_unwrappedDetectors[i];
+
+    if (!udet.detector)
+      continue;
+    // Get the BARE parent (not parametrized) to speed things up.
+    const Mantid::Geometry::IComponent *bareDet =
+        udet.detector->getComponentID();
+    const Mantid::Geometry::IComponent *parent = bareDet->getBareParent();
+    if (parent) {
+      QRectF detRect;
+      detRect.setLeft(udet.u - udet.width);
+      detRect.setRight(udet.u + udet.width);
+      detRect.setBottom(udet.v - udet.height);
+      detRect.setTop(udet.v + udet.height);
+      Mantid::Geometry::ComponentID id = parent->getComponentID();
+      QRectF &r = m_assemblies[id];
+      r |= detRect;
+      calcAssemblies(parent, r);
+    }
+  }
+}
+
+//------------------------------------------------------------------------------
+/**
+* Draw the unwrapped instrument onto the screen
+* @param widget :: The widget to draw it on.
+* @param picking :: True if detector is being drawn in the picking mode.
+*/
+void UnwrappedSurface::drawSurface(MantidGLWidget *widget, bool picking) const {
+  // dimensions of the screen to draw on
+  int widget_width = widget->width();
+  int widget_height = widget->height();
+
+  // view rectangle in the OpenGL coordinates
+  double view_left = m_viewRect.x0();
+  double view_top = m_viewRect.y1();
+  double view_right = m_viewRect.x1();
+  double view_bottom = m_viewRect.y0();
+
+  // make sure the view rectangle has a finite area
+  if (view_left == view_right) {
+    view_left -= m_width_max / 2;
+    view_right += m_width_max / 2;
+  }
+  if (view_top == view_bottom) {
+    view_top += m_height_max / 2;
+    view_bottom -= m_height_max / 2;
+  }
+
+  const double dw = fabs((view_right - view_left) / widget_width);
+  const double dh = fabs((view_top - view_bottom) / widget_height);
+
+  if (m_startPeakShapes) {
+    createPeakShapes(widget->rect());
+  }
+
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  glViewport(0, 0, widget_width, widget_height);
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  glOrtho(view_left, view_right, view_bottom, view_top, -10, 10);
+
+  if (OpenGLError::hasError("UnwrappedSurface::drawSurface")) {
+    OpenGLError::log() << "glOrtho arguments:\n";
+    OpenGLError::log() << view_left << ',' << view_right << ',' << view_bottom
+                       << ',' << view_top << ',' << -10 << ',' << 10 << '\n';
+  }
+  glMatrixMode(GL_MODELVIEW);
+  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+
+  GLfloat oldLineWidth;
+  glGetFloatv(GL_LINE_WIDTH, &oldLineWidth);
+  glLineWidth(1.0f);
+
+  glLoadIdentity();
+
+  if (m_isLightingOn && !picking) {
+    glShadeModel(GL_SMOOTH);  // Shade model is smooth
+    glEnable(GL_LINE_SMOOTH); // Set line should be drawn smoothly
+    glEnable(GL_LIGHT0);      // Enable opengl second light
+    float diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f};
+    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
+    float direction[3] = {0.0f, 0.0f, 1.0f};
+    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, direction);
+
+    glEnable(GL_LIGHTING); // Enable overall lighting
+  } else {
+    glDisable(GL_LIGHT0);
+    glDisable(GL_LIGHTING);
+    glDisable(GL_LINE_SMOOTH);
+    glShadeModel(GL_FLAT);
+  }
+
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    const UnwrappedDetector &udet = m_unwrappedDetectors[i];
+
+    if (!udet.detector)
+      continue;
+
+    int iw = int(udet.width / dw);
+    int ih = int(udet.height / dh);
+    double w = (iw == 0) ? dw : udet.width / 2;
+    double h = (ih == 0) ? dh : udet.height / 2;
+
+    // check that the detector is visible in the current view
+    if (!(m_viewRect.contains(udet.u - w, udet.v - h) ||
+          m_viewRect.contains(udet.u + w, udet.v + h)))
+      continue;
+    // QRectF detectorRect(udet.u-w,udet.v+h,w*2,h*2);
+    // if ( !m_viewRect.intersects(detectorRect) ) continue;
+
+    // apply the detector's colour
+    setColor(int(i), picking);
+
+    // if the detector is too small to see its shape draw a rectangle
+    if (iw < 6 || ih < 6) {
+      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+      glRectd(udet.u - w, udet.v - h, udet.u + w, udet.v + h);
+      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+      if (iw > 2 || ih > 2) {
+        glRectd(udet.u - w, udet.v - h, udet.u + w, udet.v + h);
+      }
+    }
+    // else draw the correct shape
+    else {
+      glPushMatrix();
+
+      glTranslated(udet.u, udet.v, 0.);
+      glScaled(udet.uscale, udet.vscale, 1);
+
+      Mantid::Kernel::Quat rot;
+      this->rotate(udet, rot);
+      double deg, ax0, ax1, ax2;
+      rot.getAngleAxis(deg, ax0, ax1, ax2);
+      glRotated(deg, ax0, ax1, ax2);
+
+      Mantid::Kernel::V3D scaleFactor = udet.detector->getScaleFactor();
+      glScaled(scaleFactor[0], scaleFactor[1], scaleFactor[2]);
+
+      udet.detector->shape()->draw();
+
+      glPopMatrix();
+    }
+  }
+
+  OpenGLError::check("UnwrappedSurface::drawSurface");
+
+  glLineWidth(oldLineWidth);
+
+  if (OpenGLError::check("UnwrappedSurface::drawSurface")) {
+    OpenGLError::log() << "oldLineWidth=" << oldLineWidth << '\n';
+  }
+}
+
+/**
+* Set detector color in OpenGL context.
+* @param index :: Detector's index in m_unwrappedDetectors
+* @param picking :: True if detector is being drawn in the picking mode.
+*   In this case index is transformed into color
+*/
+void UnwrappedSurface::setColor(int index, bool picking) const {
+  if (picking) {
+    GLColor c = GLActor::makePickColor(index);
+    unsigned char r, g, b;
+    c.get(r, g, b);
+    glColor3ub(r, g, b);
+  } else {
+    glColor3ubv(&m_unwrappedDetectors[index].color[0]);
+  }
+}
+
+bool hasParent(boost::shared_ptr<const Mantid::Geometry::IComponent> comp,
+               Mantid::Geometry::ComponentID id) {
+  boost::shared_ptr<const Mantid::Geometry::IComponent> parent =
+      comp->getParent();
+  if (!parent)
+    return false;
+  if (parent->getComponentID() == id)
+    return true;
+  return hasParent(parent, id);
+}
+
+//------------------------------------------------------------------------------
+/** This method is called when a component is selected in the
+*InstrumentTreeWidget
+* and zooms into that spot on the view.
+*
+* @param id :: ComponentID to zoom to.
+*/
+void UnwrappedSurface::componentSelected(Mantid::Geometry::ComponentID id) {
+  boost::shared_ptr<const Mantid::Geometry::Instrument> instr =
+      m_instrActor->getInstrument();
+  if (id == NULL) {
+    id = instr->getComponentID();
+  }
+  boost::shared_ptr<const Mantid::Geometry::IComponent> comp =
+      instr->getComponentByID(id);
+  boost::shared_ptr<const Mantid::Geometry::ICompAssembly> ass =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(comp);
+  boost::shared_ptr<const Mantid::Geometry::IDetector> det =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector>(comp);
+  if (det) {
+    int detID = det->getID();
+
+    std::vector<UnwrappedDetector>::const_iterator it;
+    for (it = m_unwrappedDetectors.begin(); it != m_unwrappedDetectors.end();
+         ++it) {
+      const UnwrappedDetector &udet = *it;
+      if (udet.detector && udet.detector->getID() == detID) {
+        double w = udet.width;
+        if (w > m_width_max)
+          w = m_width_max;
+        double h = udet.height;
+        if (h > m_height_max)
+          h = m_height_max;
+        QRectF area(udet.u - w, udet.v - h, w * 2, h * 2);
+        zoom(area);
+        break;
+      }
+    }
+  }
+  if (ass) {
+    this->cacheAllAssemblies();
+    QMap<Mantid::Geometry::ComponentID, QRectF>::iterator assRect =
+        m_assemblies.find(ass->getComponentID());
+    if (assRect != m_assemblies.end())
+      zoom(*assRect);
+    else {
+      // std::cout << "Assembly not found " << std::endl;
+    }
+  }
+}
+
+void UnwrappedSurface::getSelectedDetectors(QList<int> &dets) {
+  if (m_selectRect.isNull()) {
+    return;
+  }
+  QRect rect = selectionRect();
+
+  double vtop = m_v_min;
+  double vbottom = m_v_min;
+  double uleft = m_u_min;
+  double uright = m_u_min;
+
+  // find the first picking colours different from black (0,0,0) to get the
+  // top-left
+  // and bottom-right detectors
+  int rwidth = rect.width();
+  int rheight = rect.height();
+  for (int i = 0; i < rwidth; ++i) {
+    bool stop = false;
+    for (int j = 0; j < rheight; ++j) {
+      int x = rect.x() + i;
+      int y = rect.y() + j;
+      size_t ind = getPickID(x, y);
+      if (ind < m_unwrappedDetectors.size()) {
+        uleft =
+            m_unwrappedDetectors[ind].u - m_unwrappedDetectors[ind].width / 2;
+        vtop =
+            m_unwrappedDetectors[ind].v + m_unwrappedDetectors[ind].height / 2;
+        stop = true;
+        break;
+      }
+    }
+    if (stop)
+      break;
+  }
+
+  for (int i = rwidth - 1; i >= 0; --i) {
+    bool stop = false;
+    for (int j = rheight - 1; j >= 0; --j) {
+      int x = rect.x() + i;
+      int y = rect.y() + j;
+      size_t ind = getPickID(x, y);
+      if (ind < m_unwrappedDetectors.size()) {
+        uright =
+            m_unwrappedDetectors[ind].u + m_unwrappedDetectors[ind].width / 2;
+        vbottom =
+            m_unwrappedDetectors[ind].v - m_unwrappedDetectors[ind].height / 2;
+        stop = true;
+        break;
+      }
+    }
+    if (stop)
+      break;
+  }
+
+  // select detectors with u,v within the allowed boundaries
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    UnwrappedDetector &udet = m_unwrappedDetectors[i];
+    if (!udet.detector)
+      continue;
+    if (udet.u >= uleft && udet.u <= uright && udet.v >= vbottom &&
+        udet.v <= vtop) {
+      dets.push_back(udet.detector->getID());
+    }
+  }
+}
+
+void UnwrappedSurface::getMaskedDetectors(QList<int> &dets) const {
+  dets.clear();
+  if (m_maskShapes.isEmpty())
+    return;
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    const UnwrappedDetector &udet = m_unwrappedDetectors[i];
+    if (!udet.detector)
+      continue;
+    if (m_maskShapes.isMasked(udet.u, udet.v)) {
+      dets.append(udet.detector->getID());
+    }
+  }
+}
+
+void UnwrappedSurface::changeColorMap() {
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    UnwrappedDetector &udet = m_unwrappedDetectors[i];
+    if (!udet.detector)
+      continue;
+    unsigned char color[3];
+    m_instrActor->getColor(udet.detector->getID()).getUB3(&color[0]);
+    udet.color[0] = color[0];
+    udet.color[1] = color[1];
+    udet.color[2] = color[2];
+  }
+}
+
+QString UnwrappedSurface::getInfoText() const {
+  if (m_interactionMode == MoveMode) {
+    // return getDimInfo() +
+    return "Left mouse click and drag to zoom in. Right mouse click to zoom "
+           "out.";
+  }
+  return ProjectionSurface::getInfoText();
+}
+
+RectF UnwrappedSurface::getSurfaceBounds() const { return m_viewRect; }
+
+/**
+* Set a peaks workspace to be drawn ontop of the workspace.
+* @param pws :: A shared pointer to the workspace.
+*/
+void UnwrappedSurface::setPeaksWorkspace(
+    boost::shared_ptr<Mantid::API::IPeaksWorkspace> pws) {
+  if (!pws) {
+    return;
+  }
+  PeakOverlay *po = new PeakOverlay(this, pws);
+  po->setPrecision(m_peakLabelPrecision);
+  po->setShowRowsFlag(m_showPeakRows);
+  po->setShowLabelsFlag(m_showPeakLabels);
+  po->setShowRelativeIntensityFlag(m_showPeakRelativeIntensity);
+  m_peakShapes.append(po);
+  m_startPeakShapes = true;
+  connect(po, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)), this,
+          SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)));
+  emit peaksWorkspaceAdded();
+}
+
+//-----------------------------------------------------------------------------
+/** Create the peak labels from the peaks set by setPeaksWorkspace.
+* The method is called from the draw(...) method
+*
+* @param window :: The screen window rectangle in pixels.
+*/
+void UnwrappedSurface::createPeakShapes(const QRect &window) const {
+  if (!m_peakShapes.isEmpty()) {
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    PeakOverlay &peakShapes = *m_peakShapes.last();
+    PeakMarker2D::Style style = peakShapes.getDefaultStyle(m_peakShapesStyle);
+    m_peakShapesStyle++;
+    peakShapes.setWindow(getSurfaceBounds(), window);
+    peakShapes.createMarkers(style);
+    QApplication::restoreOverrideCursor();
+  }
+  m_startPeakShapes = false;
+  setPeakVisibility();
+}
+
+/**
+* Toggle between flipped and straight view.
+*/
+void UnwrappedSurface::setFlippedView(bool on) {
+  if (m_flippedView != on) {
+    m_flippedView = on;
+    m_viewRect.xFlip();
+    for (int i = 0; i < m_zoomStack.size(); ++i) {
+      m_zoomStack[i].xFlip();
+    }
+  }
+}
+
+/**
+* Draw the surface onto an image without OpenGL
+* @param image :: Image to draw on.
+* @param picking :: If true draw a picking image.
+*/
+void UnwrappedSurface::drawSimpleToImage(QImage *image, bool picking) const {
+  if (!image)
+    return;
+
+  QPainter paint(image);
+
+  int vwidth = image->width();
+  int vheight = image->height();
+
+  paint.fillRect(0, 0, vwidth, vheight, m_backgroundColor);
+
+  const double dw = fabs(m_viewRect.width() / vwidth);
+  const double dh = fabs(m_viewRect.height() / vheight);
+
+  // std::cerr << m_viewRect.left() << ' ' << m_viewRect.right() << " : " <<
+  // m_viewRect.bottom() << ' ' << m_viewRect.top() << std::endl;
+
+  if (m_startPeakShapes) {
+    createPeakShapes(image->rect());
+  }
+
+  for (size_t i = 0; i < m_unwrappedDetectors.size(); ++i) {
+    const UnwrappedDetector &udet = m_unwrappedDetectors[i];
+
+    if (!udet.detector)
+      continue;
+
+    int iw = int(udet.width / dw);
+    int ih = int(udet.height / dh);
+    if (iw < 4)
+      iw = 4;
+    if (ih < 4)
+      ih = 4;
+
+    double w = udet.width / 2;
+    double h = udet.height / 2;
+
+    if (!(m_viewRect.contains(udet.u - w, udet.v - h) ||
+          m_viewRect.contains(udet.u + w, udet.v + h)))
+      continue;
+
+    int u = 0;
+    if (!isFlippedView()) {
+      u = static_cast<int>((udet.u - m_viewRect.x0()) / dw);
+    } else {
+      u = static_cast<int>(vwidth - (udet.u - m_viewRect.x1()) / dw);
+    }
+
+    int v = vheight - static_cast<int>((udet.v - m_viewRect.y0()) / dh);
+
+    QColor color;
+    int index = int(i);
+    if (picking) {
+      GLColor c = GLActor::makePickColor(index);
+      unsigned char r, g, b;
+      c.get(r, g, b);
+      color = QColor(r, g, b);
+    } else {
+      auto c = &m_unwrappedDetectors[index].color[0];
+      color = QColor(c[0], c[1], c[2]);
+    }
+
+    paint.fillRect(u - iw / 2, v - ih / 2, iw, ih, color);
+  }
+
+  // draw custom stuff
+  if (!picking) {
+    // TODO: this transform should be done for drawing the detectors
+    QTransform transform;
+    m_viewRect.findTransform(transform, QRectF(0, 0, vwidth, vheight));
+    paint.setTransform(transform);
+    drawCustom(&paint);
+  }
+}
+
+/**
+* Zooms to the specified area. The previous zoom stack is cleared.
+*/
+void UnwrappedSurface::zoom(const QRectF &area) {
+  if (!m_zoomStack.isEmpty()) {
+    m_viewRect = m_zoomStack.first();
+    m_zoomStack.clear();
+  }
+  m_zoomStack.push(m_viewRect);
+
+  double left = area.left();
+  double top = area.top();
+  double width = area.width();
+  double height = area.height();
+
+  if (width * m_viewRect.width() < 0) {
+    left += width;
+    width = -width;
+  }
+  if (height * m_viewRect.height() < 0) {
+    top += height;
+    height = -height;
+  }
+  m_viewRect = RectF(QPointF(left, top), QPointF(left + width, top + height));
+  updateView();
+}
+
+void UnwrappedSurface::unzoom() {
+  if (!m_zoomStack.isEmpty()) {
+    m_viewRect = m_zoomStack.pop();
+    updateView();
+    emit updateInfoText();
+  }
+}
+
+void UnwrappedSurface::zoom() {
+  if (!m_viewImage)
+    return;
+  RectF newView = selectionRectUV();
+  if (newView.isEmpty())
+    return;
+  m_zoomStack.push(m_viewRect);
+  m_viewRect = newView;
+  updateView();
+  emptySelectionRect();
+  emit updateInfoText();
+}
+
+//------------------------------------------------------------------------------
+/** Calculate the UV and size of the given detector
+* Calls the pure virtual project() and calcSize() methods that
+* depend on the type of projection
+*
+* @param udet :: detector to unwrap.
+* @param pos :: detector position relative to the sample origin
+*/
+void UnwrappedSurface::calcUV(UnwrappedDetector &udet,
+                              Mantid::Kernel::V3D &pos) {
+  this->project(pos, udet.u, udet.v, udet.uscale, udet.vscale);
+  calcSize(udet);
+}
+
+//------------------------------------------------------------------------------
+/** Calculate the size of the detector in U/V
+*
+* @param udet :: UwrappedDetector struct to calculate the size for. udet's size
+*fields
+* are updated by this method.
+*/
+void UnwrappedSurface::calcSize(UnwrappedDetector &udet) {
+  // U is the horizontal axis on the screen
+  const Mantid::Kernel::V3D U(-1, 0, 0);
+  // V is the vertical axis on the screen
+  const Mantid::Kernel::V3D V(0, 1, 0);
+
+  // find the detector's rotation
+  Mantid::Kernel::Quat R;
+  this->rotate(udet, R);
+
+  Mantid::Geometry::BoundingBox bbox = udet.detector->shape()->getBoundingBox();
+  Mantid::Kernel::V3D scale = udet.detector->getScaleFactor();
+
+  // sizes of the detector along each 3D axis
+  Mantid::Kernel::V3D size = bbox.maxPoint() - bbox.minPoint();
+  size *= scale;
+
+  Mantid::Kernel::V3D s1(size);
+  Mantid::Kernel::V3D s2 = size + Mantid::Kernel::V3D(-size.X(), 0, 0) -
+                           Mantid::Kernel::V3D(size.X(), 0, 0);
+  Mantid::Kernel::V3D s3 = size + Mantid::Kernel::V3D(0, -size.Y(), 0) -
+                           Mantid::Kernel::V3D(0, size.Y(), 0);
+  // rotate the size vectors to get the dimensions along axes U and V
+  R.rotate(s1);
+  R.rotate(s2);
+  R.rotate(s3);
+
+  // get the larges projection to the U axis which is the visible width
+  double d = fabs(s1.scalar_prod(U));
+  udet.width = d;
+  d = fabs(s2.scalar_prod(U));
+  if (d > udet.width)
+    udet.width = d;
+  d = fabs(s3.scalar_prod(U));
+  if (d > udet.width)
+    udet.width = d;
+
+  // get the larges projection to the V axis which is the visible height
+  d = fabs(s1.scalar_prod(V));
+  udet.height = d;
+  d = fabs(s2.scalar_prod(V));
+  if (d > udet.height)
+    udet.height = d;
+  d = fabs(s3.scalar_prod(V));
+  if (d > udet.height)
+    udet.height = d;
+
+  // apply the scale factors
+  udet.width *= udet.uscale;
+  udet.height *= udet.vscale;
+
+  // don't let them be too large
+  if (udet.width > m_width_max)
+    m_width_max = udet.width;
+  if (udet.height > m_height_max)
+    m_height_max = udet.height;
+}
+
+} // MantidWidgets
+} // MantidQt
\ No newline at end of file
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/Viewport.cpp b/MantidQt/MantidWidgets/src/InstrumentView/Viewport.cpp
index 4a2dfbd6f63011baffb5cc85d40f73286da7d9e6..ab805c89430f81c6a3d5863bf9306a6a401b1420 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/Viewport.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/Viewport.cpp
@@ -5,483 +5,467 @@
 #include "MantidQtMantidWidgets/InstrumentView/OpenGLError.h"
 #include <limits>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
-
-		/**
-		* Initialize with defaults.
-		* @param w :: Vieport width in pixels
-		* @param h :: Vieport height in pixels
-		*/
-		Viewport::Viewport(int w, int h) :
-			m_projectionType(Viewport::ORTHO),
-			m_width(w), m_height(h),
-			m_left(-1), m_right(1), m_bottom(-1), m_top(1), m_near(-1), m_far(1),
-			m_rotationspeed(180.0 / M_PI),
-			m_zoomFactor(1.0),
-			m_xTrans(0.0),
-			m_yTrans(0.0),
-			m_zTrans(0.0)
-		{
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Resize the viewport = size of the displaying widget.
-		* @param w :: New viewport width in pixels.
-		* @param h :: New viewport height in pixels.
-		*/
-		void Viewport::resize(int w, int h)
-		{
-			m_width = w;
-			m_height = h;
-		}
-
-		/**
-		* Get the size of the viewport in screen pixels (size of the displaying widget).
-		*
-		* @param w :: Buffer to accept the viewport width value.
-		* @param h :: Buffer to accept the viewport height value.
-		*/
-		void Viewport::getViewport(int& w, int& h) const
-		{
-			w = m_width;
-			h = m_height;
-		}
-
-		/**
-		* This will set the projection. The parameters describe the dimensions of a scene
-		* which has to be fully visible in this viewport by default. These don't set
-		* the actual projection sizes because they have to be adjusted for the aspect
-		* ratio of the displaying widget. The actual projection dimensions can be
-		* retrieved by calling getInstantProjection() method.
-		*
-		* @param l :: left side of the scene (xmin)
-		* @param r :: right side of the scene (xmax)
-		* @param b :: bottom side of the scene (ymin)
-		* @param t :: top side of the scene (ymax)
-		* @param nearz :: near side of the scene (zmin)
-		* @param farz :: far side of the scene (zmax)
-		* @param type :: Projection type: ORTHO or PERSPECTIVE. PERSPECTIVE isn't fully implemented
-		*/
-		void Viewport::setProjection(double l, double r, double b, double t, double nearz, double farz, Viewport::ProjectionType type)
-		{
-			m_projectionType = type;
-			m_left = l;
-			m_right = r;
-			if (m_left > m_right) std::swap(m_left, m_right);
-			m_bottom = b;
-			m_top = t;
-			if (m_bottom > m_top) std::swap(m_bottom, m_top);
-			m_near = nearz;
-			m_far = farz;
-
-		}
-
-		/**
-		* Convenience overload.
-		*
-		* @param minBounds :: Near-bottom-left corner of the scene.
-		* @param maxBounds :: Far-top-right corner of the scene.
-		* @param type :: Projection type: ORTHO or PERSPECTIVE. PERSPECTIVE isn't fully implemented
-		*/
-		void Viewport::setProjection(const Mantid::Kernel::V3D& minBounds, const Mantid::Kernel::V3D& maxBounds, ProjectionType type)
-		{
-			double radius = minBounds.norm();
-			double tmp = maxBounds.norm();
-			if (tmp > radius) radius = tmp;
-
-			setProjection(minBounds.X(), maxBounds.X(), minBounds.Y(), maxBounds.Y(), -radius, radius, type);
-		}
-
-		/**
-		* Return XY plane bounds corrected for the aspect ratio.
-		*/
-		void Viewport::correctForAspectRatioAndZoom(double& xmin, double& xmax, double& ymin, double& ymax, double& zmin, double& zmax)const
-		{
-			xmin = m_left;
-			xmax = m_right;
-			ymin = m_bottom;
-			ymax = m_top;
-			// check if the scene is going to be stretched anlong x or y axes
-			// and correct the extent to make it loook normal
-			double xSize = m_right - m_left;
-			double ySize = m_top - m_bottom;
-			double r = ySize * m_width / (xSize * m_height);
-			if (r < 1.0)
-			{
-				// ySize is too small
-				ySize /= r;
-				ymin = (m_bottom + m_top - ySize) / 2;
-				ymax = ymin + ySize;
-			}
-			else
-			{
-				// xSize is too small
-				xSize *= r;
-				xmin = (m_left + m_right - xSize) / 2;
-				xmax = xmin + xSize;
-			}
-			zmin = m_near * m_zoomFactor;
-			zmax = m_far * m_zoomFactor;
-		}
-
-		Viewport::ProjectionType Viewport::getProjectionType()const
-		{
-			return m_projectionType;
-		}
-
-		/**
-		* Get the projection bounds.
-		* @param xmin :: left side of the Ortho projection
-		* @param xmax :: right side of the Ortho projection
-		* @param ymin :: bottom side of the Ortho projection
-		* @param ymax :: top side of the Ortho projection
-		* @param zmin :: near side of the Ortho Projection
-		* @param zmax :: far side of the Ortho Projection
-		*/
-		void Viewport::getInstantProjection(double& xmin, double& xmax, double& ymin, double& ymax, double& zmin, double& zmax)const
-		{
-			correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
-		}
-
-		void Viewport::setTranslation(double xval, double yval)
-		{
-			m_xTrans = xval;
-			m_yTrans = yval;
-		}
-
-		/**
-		* Issue the OpenGL commands that define the viewport and projection.
-		*/
-		void Viewport::applyProjection() const
-		{
-			glViewport(0, 0, m_width, m_height);
-			glMatrixMode(GL_PROJECTION);
-			glLoadIdentity();
-			OpenGLError::check("GLViewport::issueGL()");
-
-			double xmin, xmax, ymin, ymax, zmin, zmax;
-			correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
-
-			if (m_projectionType == Viewport::PERSPECTIVE)
-			{
-				double fov = 30.0 * M_PI / 180.0;
-				double znear = fabs(ymax - ymin) / (2 * tan(fov / 2));
-				double zfar = znear + zmax - zmin;
-				m_zTrans = -znear + zmin;
-				glFrustum(xmin, xmax, ymin, ymax, znear, zfar);
-
-				if (OpenGLError::hasError("GLViewport::issueGL()"))
-				{
-					OpenGLError::log() << "Arguments to glFrustum:\n";
-					OpenGLError::log()
-						<< xmin << ' ' << xmax << '\n'
-						<< ymin << ' ' << ymax << '\n'
-						<< znear << ' ' << zfar << "\n\n";
-				}
-			}
-			else
-			{
-				glOrtho(xmin, xmax, ymin, ymax, zmin, zmax);
-
-				if (OpenGLError::hasError("GLViewport::issueGL()"))
-				{
-					OpenGLError::log() << "Arguments to glOrtho:\n";
-					OpenGLError::log()
-						<< xmin << ' ' << xmax << '\n'
-						<< ymin << ' ' << ymax << '\n'
-						<< zmin << ' ' << zmax << "\n\n";
-				}
-			}
-			// Reset the rendering options just in case
-			glMatrixMode(GL_MODELVIEW);
-			glLoadIdentity();
-		}
-
-
-		/**
-		* A point on the screen is projected onto a sphere with center at the rotation point
-		* @param a :: The x screen coordinate in pixels
-		* @param b :: The y screen coordinate in pixels
-		* @param point :: The projection point on the sphere in model coordinates
-		*/
-		void Viewport::projectOnSphere(int a, int b, Mantid::Kernel::V3D& point) const
-		{
-			// z initiaised to zero if out of the sphere
-			double z = 0;
-			double x = static_cast<double>((2.0 * a - m_width) / m_width);
-			double y = static_cast<double>((m_height - 2.0 * b) / m_height);
-			double norm = x * x + y * y;
-			if (norm > 1.0) // The point is inside the sphere
-			{
-				norm = sqrt(norm);
-				x /= norm;
-				y /= norm;
-			}
-			else // The point is outside the sphere, so project to nearest point on circle
-				z = sqrt(1.0 - norm);
-			// Set-up point
-			point(x, y, z);
-		}
-
-		/**
-		* Apply the transformation to the scene: translation, rotation and zooming.
-		*/
-		void Viewport::applyRotation() const
-		{
-			// Translate
-			glTranslated(m_xTrans, m_yTrans, m_zTrans);
-			// Rotate with respect to the centre
-			glMultMatrixd(m_rotationmatrix);
-			// Zoom
-			glScaled(m_zoomFactor, m_zoomFactor, m_zoomFactor);
-
-			OpenGLError::check("GLTrackball::IssueRotation()");
-		}
-
-		/**
-		* Clear all transforamtions (rotation, translation. scaling)
-		*/
-		void Viewport::reset()
-		{
-			m_quaternion.init();
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-			m_xTrans = 0.0;
-			m_yTrans = 0.0;
-			m_zoomFactor = 1.0;
-		}
-
-		/**
-		* Rotate the scene such that its X axis is perpendicular to the screen and points towards the viewer.
-		*/
-		void Viewport::setViewToXPositive()
-		{
-			reset();
-			Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0), Mantid::Kernel::V3D(-1.0, 0.0, 0.0));
-			m_quaternion = tempy;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Rotate the scene such that its Y axis is perpendicular to the screen and points towards the viewer.
-		*/
-		void Viewport::setViewToYPositive()
-		{
-			reset();
-			Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0), Mantid::Kernel::V3D(0.0, -1.0, 0.0));
-			m_quaternion = tempy;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Rotate the scene such that its Z axis is perpendicular to the screen and points towards the viewer.
-		*/
-		void Viewport::setViewToZPositive()
-		{
-			reset();
-			m_quaternion.init();
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Rotate the scene such that its X axis is perpendicular to the screen and points away from the viewer.
-		*/
-		void Viewport::setViewToXNegative()
-		{
-			reset();
-			Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0), Mantid::Kernel::V3D(1.0, 0.0, 0.0));
-			m_quaternion = tempy;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Rotate the scene such that its Y axis is perpendicular to the screen and points away from the viewer.
-		*/
-		void Viewport::setViewToYNegative()
-		{
-			reset();
-			Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0), Mantid::Kernel::V3D(0.0, 1.0, 0.0));
-			m_quaternion = tempy;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Rotate the scene such that its Z axis is perpendicular to the screen and points away from the viewer.
-		*/
-		void Viewport::setViewToZNegative()
-		{
-			reset();
-			Mantid::Kernel::Quat tempy(180.0, Mantid::Kernel::V3D(0.0, 1.0, 0.0));
-			m_quaternion = tempy;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Set a new rotation.
-		* @param rot :: Rotattion as a quaternion.
-		*/
-		void Viewport::setRotation(const Mantid::Kernel::Quat& rot)
-		{
-			m_quaternion = rot;
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Init zooming at a point on the screen. The user starts zooming by clicking (middle)
-		* mouse button then drags holding the button.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::initZoomFrom(int a, int b)
-		{
-			if (a <= 0 || b <= 0) return;
-			if (a >= m_width || b >= m_height) return;
-			double z = 0;
-			double x = static_cast<double>(m_width - a);
-			double y = static_cast<double>(b - m_height);
-			m_lastpoint(x, y, z);
-		}
-
-		/**
-		* Calculate the zoom factor when the user releases the mouse button at a point on the screen.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::generateZoomTo(int a, int b)
-		{
-			if (a >= m_width || b >= m_height || a <= 0 || b <= 0) return;
-			double y = static_cast<double>(b - m_height);
-			if (y == 0) y = m_lastpoint[1];
-			double diff = m_lastpoint[1] / y;
-			m_zoomFactor /= diff;
-		}
-
-		/**
-		* Generate zooming factor using mouse wheel
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		* @param d :: The mouse wheel delta
-		*/
-		void Viewport::wheelZoom(int a, int b, int d)
-		{
-			// OpenGL works with floats. Set a limit to the zoom factor
-			// based on the epsilon for floats
-			const double zoomLimit = std::numeric_limits<float>::epsilon() * 1000;
-			Mantid::Kernel::V3D point;
-			generateTranslationPoint(a, b, point);
-			double diff = 1.0 + static_cast<double>(d) / 600;
-			double newZoomFactor = m_zoomFactor * diff;
-			if (newZoomFactor < zoomLimit || 1.0 / newZoomFactor < zoomLimit) return;
-			// set new zoom factor
-			m_zoomFactor = newZoomFactor;
-			// update translation vector to keep 
-			Mantid::Kernel::V3D T(m_xTrans, m_yTrans, 0.0);
-			T = point - (point - T) * diff;
-			m_xTrans = T.X();
-			m_yTrans = T.Y();
-		}
-
-		/**
-		* Set zooming factor.
-		* @param zoom :: A new zooming factor.
-		*/
-		void Viewport::setZoom(double zoom)
-		{
-			if (zoom > 0.0)
-			{
-				m_zoomFactor = zoom;
-			}
-		}
-
-		/**
-		* Start a trackball rotation from here.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::initRotationFrom(int a, int b)
-		{
-			projectOnSphere(a, b, m_lastpoint);
-		}
-
-		/**
-		* Generate the rotation matrix to rotate to this point.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::generateRotationTo(int a, int b)
-		{
-			Mantid::Kernel::V3D newpoint;
-			projectOnSphere(a, b, newpoint);
-			Mantid::Kernel::V3D diff(m_lastpoint);
-			// Difference between old point and new point
-			diff -= newpoint;
-			// Angle is given in degrees as the dot product of the two vectors
-			double angle = m_rotationspeed * newpoint.angle(m_lastpoint);
-			diff = m_lastpoint.cross_prod(newpoint);
-			// Create a quaternion from the angle and vector direction
-			Mantid::Kernel::Quat temp(angle, diff);
-			// Left multiply
-			temp *= m_quaternion;
-			// Assignment of _quaternion
-			m_quaternion(temp);
-			// Get the corresponding OpenGL rotation matrix
-			m_quaternion.GLMatrix(&m_rotationmatrix[0]);
-		}
-
-		/**
-		* Initialize scene translation at a point on the screen
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::initTranslateFrom(int a, int b)
-		{
-			generateTranslationPoint(a, b, m_lastpoint);
-		}
-
-		/**
-		* Generate scene translation such that a point of the last initTranslateFrom
-		* moved to the new position pointed by the mouse.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		*/
-		void Viewport::generateTranslationTo(int a, int b)
-		{
-			Mantid::Kernel::V3D newpoint;
-			generateTranslationPoint(a, b, newpoint);
-			// This is now the difference
-			newpoint -= m_lastpoint;
-			m_xTrans += newpoint[0];
-			m_yTrans += newpoint[1];
-		}
-
-		/**
-		* Find coordinates of a point on z = 0 plane under the mouse.
-		* @param a :: The x mouse coordinate
-		* @param b :: The y mouse coordinate
-		* @param point :: Return the result through this reference.
-		*/
-		void Viewport::generateTranslationPoint(int a, int b, Mantid::Kernel::V3D& point)const
-		{
-			double x, y, z = 0.0;
-			double xmin, xmax, ymin, ymax, zmin, zmax;
-			correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
-			x = static_cast<double>((xmin + ((xmax - xmin)*((double)a / (double)m_width))));
-			y = static_cast<double>((ymin + ((ymax - ymin)*(m_height - b) / m_height)));
-			point(x, y, z);
-		}
-
-		/**
-		* Apply the transformation to a vector.
-		* @param pos :: A position vector to transform (in and out).
-		*/
-		void Viewport::transform(Mantid::Kernel::V3D& pos) const
-		{
-			pos *= m_zoomFactor;
-			m_quaternion.rotate(pos);
-			pos += Mantid::Kernel::V3D(m_xTrans, m_yTrans, 0.0);
-		}
-	}//MantidWidgets
-}//MantidQt
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+* Initialize with defaults.
+* @param w :: Vieport width in pixels
+* @param h :: Vieport height in pixels
+*/
+Viewport::Viewport(int w, int h)
+    : m_projectionType(Viewport::ORTHO), m_width(w), m_height(h), m_left(-1),
+      m_right(1), m_bottom(-1), m_top(1), m_near(-1), m_far(1),
+      m_rotationspeed(180.0 / M_PI), m_zoomFactor(1.0), m_xTrans(0.0),
+      m_yTrans(0.0), m_zTrans(0.0) {
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Resize the viewport = size of the displaying widget.
+* @param w :: New viewport width in pixels.
+* @param h :: New viewport height in pixels.
+*/
+void Viewport::resize(int w, int h) {
+  m_width = w;
+  m_height = h;
+}
+
+/**
+* Get the size of the viewport in screen pixels (size of the displaying widget).
+*
+* @param w :: Buffer to accept the viewport width value.
+* @param h :: Buffer to accept the viewport height value.
+*/
+void Viewport::getViewport(int &w, int &h) const {
+  w = m_width;
+  h = m_height;
+}
+
+/**
+* This will set the projection. The parameters describe the dimensions of a
+*scene
+* which has to be fully visible in this viewport by default. These don't set
+* the actual projection sizes because they have to be adjusted for the aspect
+* ratio of the displaying widget. The actual projection dimensions can be
+* retrieved by calling getInstantProjection() method.
+*
+* @param l :: left side of the scene (xmin)
+* @param r :: right side of the scene (xmax)
+* @param b :: bottom side of the scene (ymin)
+* @param t :: top side of the scene (ymax)
+* @param nearz :: near side of the scene (zmin)
+* @param farz :: far side of the scene (zmax)
+* @param type :: Projection type: ORTHO or PERSPECTIVE. PERSPECTIVE isn't fully
+*implemented
+*/
+void Viewport::setProjection(double l, double r, double b, double t,
+                             double nearz, double farz,
+                             Viewport::ProjectionType type) {
+  m_projectionType = type;
+  m_left = l;
+  m_right = r;
+  if (m_left > m_right)
+    std::swap(m_left, m_right);
+  m_bottom = b;
+  m_top = t;
+  if (m_bottom > m_top)
+    std::swap(m_bottom, m_top);
+  m_near = nearz;
+  m_far = farz;
+}
+
+/**
+* Convenience overload.
+*
+* @param minBounds :: Near-bottom-left corner of the scene.
+* @param maxBounds :: Far-top-right corner of the scene.
+* @param type :: Projection type: ORTHO or PERSPECTIVE. PERSPECTIVE isn't fully
+*implemented
+*/
+void Viewport::setProjection(const Mantid::Kernel::V3D &minBounds,
+                             const Mantid::Kernel::V3D &maxBounds,
+                             ProjectionType type) {
+  double radius = minBounds.norm();
+  double tmp = maxBounds.norm();
+  if (tmp > radius)
+    radius = tmp;
+
+  setProjection(minBounds.X(), maxBounds.X(), minBounds.Y(), maxBounds.Y(),
+                -radius, radius, type);
+}
+
+/**
+* Return XY plane bounds corrected for the aspect ratio.
+*/
+void Viewport::correctForAspectRatioAndZoom(double &xmin, double &xmax,
+                                            double &ymin, double &ymax,
+                                            double &zmin, double &zmax) const {
+  xmin = m_left;
+  xmax = m_right;
+  ymin = m_bottom;
+  ymax = m_top;
+  // check if the scene is going to be stretched anlong x or y axes
+  // and correct the extent to make it loook normal
+  double xSize = m_right - m_left;
+  double ySize = m_top - m_bottom;
+  double r = ySize * m_width / (xSize * m_height);
+  if (r < 1.0) {
+    // ySize is too small
+    ySize /= r;
+    ymin = (m_bottom + m_top - ySize) / 2;
+    ymax = ymin + ySize;
+  } else {
+    // xSize is too small
+    xSize *= r;
+    xmin = (m_left + m_right - xSize) / 2;
+    xmax = xmin + xSize;
+  }
+  zmin = m_near * m_zoomFactor;
+  zmax = m_far * m_zoomFactor;
+}
+
+Viewport::ProjectionType Viewport::getProjectionType() const {
+  return m_projectionType;
+}
+
+/**
+* Get the projection bounds.
+* @param xmin :: left side of the Ortho projection
+* @param xmax :: right side of the Ortho projection
+* @param ymin :: bottom side of the Ortho projection
+* @param ymax :: top side of the Ortho projection
+* @param zmin :: near side of the Ortho Projection
+* @param zmax :: far side of the Ortho Projection
+*/
+void Viewport::getInstantProjection(double &xmin, double &xmax, double &ymin,
+                                    double &ymax, double &zmin,
+                                    double &zmax) const {
+  correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
+}
+
+void Viewport::setTranslation(double xval, double yval) {
+  m_xTrans = xval;
+  m_yTrans = yval;
+}
+
+/**
+* Issue the OpenGL commands that define the viewport and projection.
+*/
+void Viewport::applyProjection() const {
+  glViewport(0, 0, m_width, m_height);
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  OpenGLError::check("GLViewport::issueGL()");
+
+  double xmin, xmax, ymin, ymax, zmin, zmax;
+  correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
+
+  if (m_projectionType == Viewport::PERSPECTIVE) {
+    double fov = 30.0 * M_PI / 180.0;
+    double znear = fabs(ymax - ymin) / (2 * tan(fov / 2));
+    double zfar = znear + zmax - zmin;
+    m_zTrans = -znear + zmin;
+    glFrustum(xmin, xmax, ymin, ymax, znear, zfar);
+
+    if (OpenGLError::hasError("GLViewport::issueGL()")) {
+      OpenGLError::log() << "Arguments to glFrustum:\n";
+      OpenGLError::log() << xmin << ' ' << xmax << '\n' << ymin << ' ' << ymax
+                         << '\n' << znear << ' ' << zfar << "\n\n";
+    }
+  } else {
+    glOrtho(xmin, xmax, ymin, ymax, zmin, zmax);
+
+    if (OpenGLError::hasError("GLViewport::issueGL()")) {
+      OpenGLError::log() << "Arguments to glOrtho:\n";
+      OpenGLError::log() << xmin << ' ' << xmax << '\n' << ymin << ' ' << ymax
+                         << '\n' << zmin << ' ' << zmax << "\n\n";
+    }
+  }
+  // Reset the rendering options just in case
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+}
+
+/**
+* A point on the screen is projected onto a sphere with center at the rotation
+* point
+* @param a :: The x screen coordinate in pixels
+* @param b :: The y screen coordinate in pixels
+* @param point :: The projection point on the sphere in model coordinates
+*/
+void Viewport::projectOnSphere(int a, int b, Mantid::Kernel::V3D &point) const {
+  // z initiaised to zero if out of the sphere
+  double z = 0;
+  double x = static_cast<double>((2.0 * a - m_width) / m_width);
+  double y = static_cast<double>((m_height - 2.0 * b) / m_height);
+  double norm = x * x + y * y;
+  if (norm > 1.0) // The point is inside the sphere
+  {
+    norm = sqrt(norm);
+    x /= norm;
+    y /= norm;
+  } else // The point is outside the sphere, so project to nearest point on
+         // circle
+    z = sqrt(1.0 - norm);
+  // Set-up point
+  point(x, y, z);
+}
+
+/**
+* Apply the transformation to the scene: translation, rotation and zooming.
+*/
+void Viewport::applyRotation() const {
+  // Translate
+  glTranslated(m_xTrans, m_yTrans, m_zTrans);
+  // Rotate with respect to the centre
+  glMultMatrixd(m_rotationmatrix);
+  // Zoom
+  glScaled(m_zoomFactor, m_zoomFactor, m_zoomFactor);
+
+  OpenGLError::check("GLTrackball::IssueRotation()");
+}
+
+/**
+* Clear all transforamtions (rotation, translation. scaling)
+*/
+void Viewport::reset() {
+  m_quaternion.init();
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+  m_xTrans = 0.0;
+  m_yTrans = 0.0;
+  m_zoomFactor = 1.0;
+}
+
+/**
+* Rotate the scene such that its X axis is perpendicular to the screen and
+* points towards the viewer.
+*/
+void Viewport::setViewToXPositive() {
+  reset();
+  Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0),
+                             Mantid::Kernel::V3D(-1.0, 0.0, 0.0));
+  m_quaternion = tempy;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Rotate the scene such that its Y axis is perpendicular to the screen and
+* points towards the viewer.
+*/
+void Viewport::setViewToYPositive() {
+  reset();
+  Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0),
+                             Mantid::Kernel::V3D(0.0, -1.0, 0.0));
+  m_quaternion = tempy;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Rotate the scene such that its Z axis is perpendicular to the screen and
+* points towards the viewer.
+*/
+void Viewport::setViewToZPositive() {
+  reset();
+  m_quaternion.init();
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Rotate the scene such that its X axis is perpendicular to the screen and
+* points away from the viewer.
+*/
+void Viewport::setViewToXNegative() {
+  reset();
+  Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0),
+                             Mantid::Kernel::V3D(1.0, 0.0, 0.0));
+  m_quaternion = tempy;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Rotate the scene such that its Y axis is perpendicular to the screen and
+* points away from the viewer.
+*/
+void Viewport::setViewToYNegative() {
+  reset();
+  Mantid::Kernel::Quat tempy(Mantid::Kernel::V3D(0.0, 0.0, 1.0),
+                             Mantid::Kernel::V3D(0.0, 1.0, 0.0));
+  m_quaternion = tempy;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Rotate the scene such that its Z axis is perpendicular to the screen and
+* points away from the viewer.
+*/
+void Viewport::setViewToZNegative() {
+  reset();
+  Mantid::Kernel::Quat tempy(180.0, Mantid::Kernel::V3D(0.0, 1.0, 0.0));
+  m_quaternion = tempy;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Set a new rotation.
+* @param rot :: Rotattion as a quaternion.
+*/
+void Viewport::setRotation(const Mantid::Kernel::Quat &rot) {
+  m_quaternion = rot;
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Init zooming at a point on the screen. The user starts zooming by clicking
+* (middle)
+* mouse button then drags holding the button.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::initZoomFrom(int a, int b) {
+  if (a <= 0 || b <= 0)
+    return;
+  if (a >= m_width || b >= m_height)
+    return;
+  double z = 0;
+  double x = static_cast<double>(m_width - a);
+  double y = static_cast<double>(b - m_height);
+  m_lastpoint(x, y, z);
+}
+
+/**
+* Calculate the zoom factor when the user releases the mouse button at a point
+* on the screen.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::generateZoomTo(int a, int b) {
+  if (a >= m_width || b >= m_height || a <= 0 || b <= 0)
+    return;
+  double y = static_cast<double>(b - m_height);
+  if (y == 0)
+    y = m_lastpoint[1];
+  double diff = m_lastpoint[1] / y;
+  m_zoomFactor /= diff;
+}
+
+/**
+* Generate zooming factor using mouse wheel
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+* @param d :: The mouse wheel delta
+*/
+void Viewport::wheelZoom(int a, int b, int d) {
+  // OpenGL works with floats. Set a limit to the zoom factor
+  // based on the epsilon for floats
+  const double zoomLimit = std::numeric_limits<float>::epsilon() * 1000;
+  Mantid::Kernel::V3D point;
+  generateTranslationPoint(a, b, point);
+  double diff = 1.0 + static_cast<double>(d) / 600;
+  double newZoomFactor = m_zoomFactor * diff;
+  if (newZoomFactor < zoomLimit || 1.0 / newZoomFactor < zoomLimit)
+    return;
+  // set new zoom factor
+  m_zoomFactor = newZoomFactor;
+  // update translation vector to keep
+  Mantid::Kernel::V3D T(m_xTrans, m_yTrans, 0.0);
+  T = point - (point - T) * diff;
+  m_xTrans = T.X();
+  m_yTrans = T.Y();
+}
+
+/**
+* Set zooming factor.
+* @param zoom :: A new zooming factor.
+*/
+void Viewport::setZoom(double zoom) {
+  if (zoom > 0.0) {
+    m_zoomFactor = zoom;
+  }
+}
+
+/**
+* Start a trackball rotation from here.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::initRotationFrom(int a, int b) {
+  projectOnSphere(a, b, m_lastpoint);
+}
+
+/**
+* Generate the rotation matrix to rotate to this point.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::generateRotationTo(int a, int b) {
+  Mantid::Kernel::V3D newpoint;
+  projectOnSphere(a, b, newpoint);
+  Mantid::Kernel::V3D diff(m_lastpoint);
+  // Difference between old point and new point
+  diff -= newpoint;
+  // Angle is given in degrees as the dot product of the two vectors
+  double angle = m_rotationspeed * newpoint.angle(m_lastpoint);
+  diff = m_lastpoint.cross_prod(newpoint);
+  // Create a quaternion from the angle and vector direction
+  Mantid::Kernel::Quat temp(angle, diff);
+  // Left multiply
+  temp *= m_quaternion;
+  // Assignment of _quaternion
+  m_quaternion(temp);
+  // Get the corresponding OpenGL rotation matrix
+  m_quaternion.GLMatrix(&m_rotationmatrix[0]);
+}
+
+/**
+* Initialize scene translation at a point on the screen
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::initTranslateFrom(int a, int b) {
+  generateTranslationPoint(a, b, m_lastpoint);
+}
+
+/**
+* Generate scene translation such that a point of the last initTranslateFrom
+* moved to the new position pointed by the mouse.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+*/
+void Viewport::generateTranslationTo(int a, int b) {
+  Mantid::Kernel::V3D newpoint;
+  generateTranslationPoint(a, b, newpoint);
+  // This is now the difference
+  newpoint -= m_lastpoint;
+  m_xTrans += newpoint[0];
+  m_yTrans += newpoint[1];
+}
+
+/**
+* Find coordinates of a point on z = 0 plane under the mouse.
+* @param a :: The x mouse coordinate
+* @param b :: The y mouse coordinate
+* @param point :: Return the result through this reference.
+*/
+void Viewport::generateTranslationPoint(int a, int b,
+                                        Mantid::Kernel::V3D &point) const {
+  double x, y, z = 0.0;
+  double xmin, xmax, ymin, ymax, zmin, zmax;
+  correctForAspectRatioAndZoom(xmin, xmax, ymin, ymax, zmin, zmax);
+  x = static_cast<double>(
+      (xmin + ((xmax - xmin) * ((double)a / (double)m_width))));
+  y = static_cast<double>((ymin + ((ymax - ymin) * (m_height - b) / m_height)));
+  point(x, y, z);
+}
+
+/**
+* Apply the transformation to a vector.
+* @param pos :: A position vector to transform (in and out).
+*/
+void Viewport::transform(Mantid::Kernel::V3D &pos) const {
+  pos *= m_zoomFactor;
+  m_quaternion.rotate(pos);
+  pos += Mantid::Kernel::V3D(m_xTrans, m_yTrans, 0.0);
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/InstrumentView/XIntegrationControl.cpp b/MantidQt/MantidWidgets/src/InstrumentView/XIntegrationControl.cpp
index dc1f5b5bfee35669b8c82c9142c0361af2a48dd4..2f185df64b1b2d899b2f0235193b530e86471ee3 100644
--- a/MantidQt/MantidWidgets/src/InstrumentView/XIntegrationControl.cpp
+++ b/MantidQt/MantidWidgets/src/InstrumentView/XIntegrationControl.cpp
@@ -16,350 +16,278 @@
 #include <numeric>
 #include <cfloat>
 
-namespace MantidQt
-{
-	namespace MantidWidgets
-	{
+namespace MantidQt {
+namespace MantidWidgets {
 
-		XIntegrationScrollBar::XIntegrationScrollBar(QWidget* parent) :
-			QFrame(parent),
-			m_resizeMargin(5),
-			m_init(false),
-			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)
-		{
-			setMouseTracking(true);
-			setFrameShape(StyledPanel);
-			m_slider = new QPushButton(this);
-			m_slider->setMouseTracking(true);
-			m_slider->move(0, 0);
-			m_slider->installEventFilter(this);
-			m_slider->setToolTip("Resize to change integration range");
-		}
+XIntegrationScrollBar::XIntegrationScrollBar(QWidget *parent)
+    : QFrame(parent), m_resizeMargin(5), m_init(false), 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) {
+  setMouseTracking(true);
+  setFrameShape(StyledPanel);
+  m_slider = new QPushButton(this);
+  m_slider->setMouseTracking(true);
+  m_slider->move(0, 0);
+  m_slider->installEventFilter(this);
+  m_slider->setToolTip("Resize to change integration range");
+}
 
-		void	XIntegrationScrollBar::resizeEvent(QResizeEvent *)
-		{
-			if (!m_init)
-			{
-				m_slider->resize(width(), height());
-				m_init = true;
-			}
-			else
-			{
-				set(m_minimum, m_maximum);
-			}
-		}
+void XIntegrationScrollBar::resizeEvent(QResizeEvent *) {
+  if (!m_init) {
+    m_slider->resize(width(), height());
+    m_init = true;
+  } else {
+    set(m_minimum, m_maximum);
+  }
+}
 
-		void	XIntegrationScrollBar::mouseMoveEvent(QMouseEvent* e)
-		{
-			QFrame::mouseMoveEvent(e);
-		}
+void XIntegrationScrollBar::mouseMoveEvent(QMouseEvent *e) {
+  QFrame::mouseMoveEvent(e);
+}
 
-		/**
-		* Process events comming to the slider
-		* @param object :: pointer to the slider
-		* @param e :: event
-		*/
-		bool XIntegrationScrollBar::eventFilter(QObject *object, QEvent *e)
-		{
-			QPushButton* slider = dynamic_cast<QPushButton*>(object);
-			if (!slider) return false;
-			if (e->type() == QEvent::Leave)
-			{
-				if (QApplication::overrideCursor())
-				{
-					QApplication::restoreOverrideCursor();
-				}
-				return true;
-			}
-			else if (e->type() == QEvent::MouseButtonPress)
-			{
-				QMouseEvent* me = static_cast<QMouseEvent*>(e);
-				m_x = me->x();
-				m_width = m_slider->width();
-				if (m_x < m_resizeMargin)
-				{
-					m_resizingLeft = true;
-				}
-				else if (m_x > m_width - m_resizeMargin)
-				{
-					m_resizingRight = true;
-				}
-				else
-				{
-					m_moving = true;
-				}
-			}
-			else if (e->type() == QEvent::MouseButtonRelease)
-			{
-				m_resizingLeft = false;
-				m_resizingRight = false;
-				m_moving = false;
-				if (m_changed)
-				{
-					emit changed(m_minimum, m_maximum);
-				}
-				m_changed = false;
-			}
-			else if (e->type() == QEvent::MouseMove)
-			{
-				QMouseEvent* me = static_cast<QMouseEvent*>(e);
-				int x = me->x();
-				int w = m_slider->width();
-				if (x < m_resizeMargin || x > w - m_resizeMargin)
-				{
-					if (!QApplication::overrideCursor())
-					{
-						QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
-					}
-				}
-				else
-				{
-					QApplication::restoreOverrideCursor();
-				}
+/**
+* Process events comming to the slider
+* @param object :: pointer to the slider
+* @param e :: event
+*/
+bool XIntegrationScrollBar::eventFilter(QObject *object, QEvent *e) {
+  QPushButton *slider = dynamic_cast<QPushButton *>(object);
+  if (!slider)
+    return false;
+  if (e->type() == QEvent::Leave) {
+    if (QApplication::overrideCursor()) {
+      QApplication::restoreOverrideCursor();
+    }
+    return true;
+  } else if (e->type() == QEvent::MouseButtonPress) {
+    QMouseEvent *me = static_cast<QMouseEvent *>(e);
+    m_x = me->x();
+    m_width = m_slider->width();
+    if (m_x < m_resizeMargin) {
+      m_resizingLeft = true;
+    } else if (m_x > m_width - m_resizeMargin) {
+      m_resizingRight = true;
+    } else {
+      m_moving = true;
+    }
+  } else if (e->type() == QEvent::MouseButtonRelease) {
+    m_resizingLeft = false;
+    m_resizingRight = false;
+    m_moving = false;
+    if (m_changed) {
+      emit changed(m_minimum, m_maximum);
+    }
+    m_changed = false;
+  } else if (e->type() == QEvent::MouseMove) {
+    QMouseEvent *me = static_cast<QMouseEvent *>(e);
+    int x = me->x();
+    int w = m_slider->width();
+    if (x < m_resizeMargin || x > w - m_resizeMargin) {
+      if (!QApplication::overrideCursor()) {
+        QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
+      }
+    } else {
+      QApplication::restoreOverrideCursor();
+    }
 
-				if (m_moving)
-				{
-					int idx = x - m_x;
-					int new_x = m_slider->x() + idx;
-					if (new_x >= 0 && new_x + m_slider->width() <= this->width())
-					{
-						int new_y = m_slider->y();
-						m_slider->move(new_x, new_y);
-						m_changed = true;
-						updateMinMax();
-					}
-				}
-				else if (m_resizingLeft)
-				{
-					int idx = x - m_x;
-					int new_x = m_slider->x() + idx;
-					int new_w = m_slider->width() - idx;
-					if (new_x >= 0 && new_w > 2 * m_resizeMargin)
-					{
-						m_slider->move(new_x, m_slider->y());
-						m_slider->resize(new_w, m_slider->height());
-						m_changed = true;
-						updateMinMax();
-					}
-				}
-				else if (m_resizingRight)
-				{
-					int dx = x - m_x;
-					int new_w = m_width + dx;
-					int xright = m_slider->x() + new_w;
-					if (xright <= this->width() && new_w > 2 * m_resizeMargin)
-					{
-						m_slider->resize(new_w, m_slider->height());
-						m_changed = true;
-						updateMinMax();
-					}
-				}
-				return true;
-			}
-			return false;
-		}
+    if (m_moving) {
+      int idx = x - m_x;
+      int new_x = m_slider->x() + idx;
+      if (new_x >= 0 && new_x + m_slider->width() <= this->width()) {
+        int new_y = m_slider->y();
+        m_slider->move(new_x, new_y);
+        m_changed = true;
+        updateMinMax();
+      }
+    } else if (m_resizingLeft) {
+      int idx = x - m_x;
+      int new_x = m_slider->x() + idx;
+      int new_w = m_slider->width() - idx;
+      if (new_x >= 0 && new_w > 2 * m_resizeMargin) {
+        m_slider->move(new_x, m_slider->y());
+        m_slider->resize(new_w, m_slider->height());
+        m_changed = true;
+        updateMinMax();
+      }
+    } else if (m_resizingRight) {
+      int dx = x - m_x;
+      int new_w = m_width + dx;
+      int xright = m_slider->x() + new_w;
+      if (xright <= this->width() && new_w > 2 * m_resizeMargin) {
+        m_slider->resize(new_w, m_slider->height());
+        m_changed = true;
+        updateMinMax();
+      }
+    }
+    return true;
+  }
+  return false;
+}
 
-		/**
-		* Return the minimum value (between 0 and 1)
-		*/
-		double XIntegrationScrollBar::getMinimum()const
-		{
-			return m_minimum;
-		}
+/**
+* Return the minimum value (between 0 and 1)
+*/
+double XIntegrationScrollBar::getMinimum() const { return m_minimum; }
 
-		/**
-		* Return the maximum value (between 0 and 1)
-		*/
-		double XIntegrationScrollBar::getMaximum()const
-		{
-			return m_maximum;
-		}
+/**
+* Return the maximum value (between 0 and 1)
+*/
+double XIntegrationScrollBar::getMaximum() const { return m_maximum; }
 
-		/**
-		* Return the width == maximum - minimum (value is between 0 and 1)
-		*/
-		double XIntegrationScrollBar::getWidth()const
-		{
-			return m_maximum - m_minimum;
-		}
+/**
+* Return the width == maximum - minimum (value is between 0 and 1)
+*/
+double XIntegrationScrollBar::getWidth() const { return m_maximum - m_minimum; }
 
-		/**
-		* Set new minimum and maximum values
-		*/
-		void XIntegrationScrollBar::set(double minimum, double maximum)
-		{
-			if (minimum < 0 || minimum > 1. || maximum < 0 || maximum > 1.)
-			{
-				throw std::invalid_argument("XIntegrationScrollBar : minimum and maximum must be between 0 and 1");
-			}
-			if (minimum > maximum)
-			{
-				std::swap(minimum, maximum);
-			}
-			m_minimum = minimum;
-			m_maximum = maximum;
-			int x = static_cast<int>(m_minimum * this->width());
-			int w = static_cast<int>((m_maximum - m_minimum) * this->width());
-			if (w <= 2 * m_resizeMargin)
-			{
-				w = 2 * m_resizeMargin + 1;
-			}
-			m_slider->move(x, 0);
-			m_slider->resize(w, this->height());
-		}
+/**
+* Set new minimum and maximum values
+*/
+void XIntegrationScrollBar::set(double minimum, double maximum) {
+  if (minimum < 0 || minimum > 1. || maximum < 0 || maximum > 1.) {
+    throw std::invalid_argument(
+        "XIntegrationScrollBar : minimum and maximum must be between 0 and 1");
+  }
+  if (minimum > maximum) {
+    std::swap(minimum, maximum);
+  }
+  m_minimum = minimum;
+  m_maximum = maximum;
+  int x = static_cast<int>(m_minimum * this->width());
+  int w = static_cast<int>((m_maximum - m_minimum) * this->width());
+  if (w <= 2 * m_resizeMargin) {
+    w = 2 * m_resizeMargin + 1;
+  }
+  m_slider->move(x, 0);
+  m_slider->resize(w, this->height());
+}
 
-		void XIntegrationScrollBar::updateMinMax()
-		{
-			m_minimum = double(m_slider->x()) / this->width();
-			m_maximum = m_minimum + double(m_slider->width()) / this->width();
-			emit running(m_minimum, m_maximum);
-		}
+void XIntegrationScrollBar::updateMinMax() {
+  m_minimum = double(m_slider->x()) / this->width();
+  m_maximum = m_minimum + double(m_slider->width()) / this->width();
+  emit running(m_minimum, m_maximum);
+}
 
-		//---------------------------------------------------------------------------------//
+//---------------------------------------------------------------------------------//
 
-		XIntegrationControl::XIntegrationControl(InstrumentWidget *instrWindow)
-			: QFrame(instrWindow), m_instrWindow(instrWindow), m_totalMinimum(0),
-			m_totalMaximum(1), m_minimum(0), m_maximum(1) {
-			m_scrollBar = new XIntegrationScrollBar(this);
-			QHBoxLayout* layout = new QHBoxLayout();
-			m_minText = new QLineEdit(this);
-			m_minText->setMaximumWidth(100);
-			m_minText->setToolTip("Minimum x value");
-			m_maxText = new QLineEdit(this);
-			m_maxText->setMaximumWidth(100);
-			m_maxText->setToolTip("Maximum x value");
-			m_units = new QLabel("TOF", this);
-			m_setWholeRange = new QPushButton("Reset");
-			m_setWholeRange->setToolTip("Reset integration range to maximum");
+XIntegrationControl::XIntegrationControl(InstrumentWidget *instrWindow)
+    : QFrame(instrWindow), m_instrWindow(instrWindow), m_totalMinimum(0),
+      m_totalMaximum(1), m_minimum(0), m_maximum(1) {
+  m_scrollBar = new XIntegrationScrollBar(this);
+  QHBoxLayout *layout = new QHBoxLayout();
+  m_minText = new QLineEdit(this);
+  m_minText->setMaximumWidth(100);
+  m_minText->setToolTip("Minimum x value");
+  m_maxText = new QLineEdit(this);
+  m_maxText->setMaximumWidth(100);
+  m_maxText->setToolTip("Maximum x value");
+  m_units = new QLabel("TOF", this);
+  m_setWholeRange = new QPushButton("Reset");
+  m_setWholeRange->setToolTip("Reset integration range to maximum");
 
-			layout->addWidget(m_units, 0);
-			layout->addWidget(m_minText, 0);
-			layout->addWidget(m_scrollBar, 1);
-			layout->addWidget(m_maxText, 0);
-			layout->addWidget(m_setWholeRange, 0);
-			setLayout(layout);
-			connect(m_scrollBar, SIGNAL(changed(double, double)), this, SLOT(sliderChanged(double, double)));
-			connect(m_scrollBar, SIGNAL(running(double, double)), this, SLOT(sliderRunning(double, double)));
-			connect(m_minText, SIGNAL(editingFinished()), this, SLOT(setMinimum()));
-			connect(m_maxText, SIGNAL(editingFinished()), this, SLOT(setMaximum()));
-			connect(m_setWholeRange, SIGNAL(clicked()), this, SLOT(setWholeRange()));
-			updateTextBoxes();
-		}
+  layout->addWidget(m_units, 0);
+  layout->addWidget(m_minText, 0);
+  layout->addWidget(m_scrollBar, 1);
+  layout->addWidget(m_maxText, 0);
+  layout->addWidget(m_setWholeRange, 0);
+  setLayout(layout);
+  connect(m_scrollBar, SIGNAL(changed(double, double)), this,
+          SLOT(sliderChanged(double, double)));
+  connect(m_scrollBar, SIGNAL(running(double, double)), this,
+          SLOT(sliderRunning(double, double)));
+  connect(m_minText, SIGNAL(editingFinished()), this, SLOT(setMinimum()));
+  connect(m_maxText, SIGNAL(editingFinished()), this, SLOT(setMaximum()));
+  connect(m_setWholeRange, SIGNAL(clicked()), this, SLOT(setWholeRange()));
+  updateTextBoxes();
+}
 
-		void XIntegrationControl::sliderChanged(double minimum, double maximum)
-		{
-			double w = m_totalMaximum - m_totalMinimum;
-			m_minimum = m_totalMinimum + minimum * w;
-			m_maximum = m_totalMinimum + maximum * w;
-			if (w > 0 && (m_maximum - m_minimum) / w >= 0.98)
-			{
-				m_minimum = m_totalMinimum;
-				m_maximum = m_totalMaximum;
-			}
-			updateTextBoxes();
-			emit changed(m_minimum, m_maximum);
-		}
+void XIntegrationControl::sliderChanged(double minimum, double maximum) {
+  double w = m_totalMaximum - m_totalMinimum;
+  m_minimum = m_totalMinimum + minimum * w;
+  m_maximum = m_totalMinimum + maximum * w;
+  if (w > 0 && (m_maximum - m_minimum) / w >= 0.98) {
+    m_minimum = m_totalMinimum;
+    m_maximum = m_totalMaximum;
+  }
+  updateTextBoxes();
+  emit changed(m_minimum, m_maximum);
+}
 
-		void XIntegrationControl::sliderRunning(double minimum, double maximum)
-		{
-			double w = m_totalMaximum - m_totalMinimum;
-			m_minimum = m_totalMinimum + minimum * w;
-			m_maximum = m_totalMinimum + maximum * w;
-			updateTextBoxes();
-		}
+void XIntegrationControl::sliderRunning(double minimum, double maximum) {
+  double w = m_totalMaximum - m_totalMinimum;
+  m_minimum = m_totalMinimum + minimum * w;
+  m_maximum = m_totalMinimum + maximum * w;
+  updateTextBoxes();
+}
 
-		void XIntegrationControl::setTotalRange(double minimum, double maximum)
-		{
-			if (minimum > maximum)
-			{
-				std::swap(minimum, maximum);
-			}
-			m_totalMinimum = minimum;
-			m_totalMaximum = maximum;
-			m_minimum = minimum;
-			m_maximum = maximum;
-			updateTextBoxes();
-		}
+void XIntegrationControl::setTotalRange(double minimum, double maximum) {
+  if (minimum > maximum) {
+    std::swap(minimum, maximum);
+  }
+  m_totalMinimum = minimum;
+  m_totalMaximum = maximum;
+  m_minimum = minimum;
+  m_maximum = maximum;
+  updateTextBoxes();
+}
 
-		void XIntegrationControl::setRange(double minimum, double maximum)
-		{
-			if (minimum > maximum)
-			{
-				std::swap(minimum, maximum);
-			}
-			if ((minimum < m_totalMinimum) || (minimum > m_totalMaximum))
-			{
-				minimum = m_totalMinimum;
-			}
-			if ((maximum > m_totalMaximum) || (maximum < m_totalMinimum))
-			{
-				maximum = m_totalMaximum;
-			}
-			m_minimum = minimum;
-			m_maximum = maximum;
-			double w = m_totalMaximum - m_totalMinimum;
-			m_scrollBar->set((m_minimum - m_totalMinimum) / w, (m_maximum - m_totalMinimum) / w);
-			updateTextBoxes();
-			emit changed(m_minimum, m_maximum);
-		}
+void XIntegrationControl::setRange(double minimum, double maximum) {
+  if (minimum > maximum) {
+    std::swap(minimum, maximum);
+  }
+  if ((minimum < m_totalMinimum) || (minimum > m_totalMaximum)) {
+    minimum = m_totalMinimum;
+  }
+  if ((maximum > m_totalMaximum) || (maximum < m_totalMinimum)) {
+    maximum = m_totalMaximum;
+  }
+  m_minimum = minimum;
+  m_maximum = maximum;
+  double w = m_totalMaximum - m_totalMinimum;
+  m_scrollBar->set((m_minimum - m_totalMinimum) / w,
+                   (m_maximum - m_totalMinimum) / w);
+  updateTextBoxes();
+  emit changed(m_minimum, m_maximum);
+}
 
-		void XIntegrationControl::setWholeRange()
-		{
-			setRange(m_totalMinimum, m_totalMaximum);
-		}
+void XIntegrationControl::setWholeRange() {
+  setRange(m_totalMinimum, m_totalMaximum);
+}
 
-		double XIntegrationControl::getMinimum()const
-		{
-			return m_minimum;
-		}
+double XIntegrationControl::getMinimum() const { return m_minimum; }
 
-		double XIntegrationControl::getMaximum()const
-		{
-			return m_maximum;
-		}
+double XIntegrationControl::getMaximum() const { return m_maximum; }
 
-		double XIntegrationControl::getWidth()const
-		{
-			return m_maximum - m_minimum;
-		}
+double XIntegrationControl::getWidth() const { return m_maximum - m_minimum; }
 
-		void XIntegrationControl::updateTextBoxes()
-		{
-			m_minText->setText(QString::number(m_minimum));
-			m_maxText->setText(QString::number(m_maximum));
-			m_setWholeRange->setEnabled(m_minimum != m_totalMinimum || m_maximum != m_totalMaximum);
-		}
+void XIntegrationControl::updateTextBoxes() {
+  m_minText->setText(QString::number(m_minimum));
+  m_maxText->setText(QString::number(m_maximum));
+  m_setWholeRange->setEnabled(m_minimum != m_totalMinimum ||
+                              m_maximum != m_totalMaximum);
+}
 
-		void XIntegrationControl::setMinimum()
-		{
-			bool ok;
-			QString text = m_minText->text();
-			double minValue = text.toDouble(&ok);
-			if (!ok) return;
-			double maxValue = getMaximum();
-			setRange(minValue, maxValue);
-		}
+void XIntegrationControl::setMinimum() {
+  bool ok;
+  QString text = m_minText->text();
+  double minValue = text.toDouble(&ok);
+  if (!ok)
+    return;
+  double maxValue = getMaximum();
+  setRange(minValue, maxValue);
+}
 
-		void XIntegrationControl::setMaximum()
-		{
-			bool ok;
-			QString text = m_maxText->text();
-			double maxValue = text.toDouble(&ok);
-			if (!ok) return;
-			double minValue = getMinimum();
-			setRange(minValue, maxValue);
-		}
+void XIntegrationControl::setMaximum() {
+  bool ok;
+  QString text = m_maxText->text();
+  double maxValue = text.toDouble(&ok);
+  if (!ok)
+    return;
+  double minValue = getMinimum();
+  setRange(minValue, maxValue);
+}
 
-		void XIntegrationControl::setUnits(const QString& units)
-		{
-			m_units->setText(units);
-		}
-	}//MantidWidgets
-}//MantidQt
+void XIntegrationControl::setUnits(const QString &units) {
+  m_units->setText(units);
+}
+} // MantidWidgets
+} // MantidQt
diff --git a/MantidQt/MantidWidgets/src/LineEditWithClear.cpp b/MantidQt/MantidWidgets/src/LineEditWithClear.cpp
index 9ad98dffaac758a92e29728268075a825829fd11..13093586bd042389dc7fb0cbfa7d8bfcfb70209c 100644
--- a/MantidQt/MantidWidgets/src/LineEditWithClear.cpp
+++ b/MantidQt/MantidWidgets/src/LineEditWithClear.cpp
@@ -11,44 +11,39 @@
 #include <QToolButton>
 #include <QStyle>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-
-LineEditWithClear::LineEditWithClear(QWidget *parent)
-    : QLineEdit(parent)
-{
-    clearButton = new QToolButton(this);
-    QPixmap pixmap (QString::fromUtf8(":/fileclose.png"));
-    clearButton->setIcon(QIcon(pixmap));
-    clearButton->setIconSize(pixmap.size());
-    clearButton->setCursor(Qt::ArrowCursor);
-    clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
-    clearButton->hide();
-    connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
-    connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
-    int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
-    setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
-    QSize msz = minimumSizeHint();
-    setMinimumSize(qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2),
-                   qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2));
+namespace MantidQt {
+namespace MantidWidgets {
+
+LineEditWithClear::LineEditWithClear(QWidget *parent) : QLineEdit(parent) {
+  clearButton = new QToolButton(this);
+  QPixmap pixmap(QString::fromUtf8(":/fileclose.png"));
+  clearButton->setIcon(QIcon(pixmap));
+  clearButton->setIconSize(pixmap.size());
+  clearButton->setCursor(Qt::ArrowCursor);
+  clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
+  clearButton->hide();
+  connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
+  connect(this, SIGNAL(textChanged(const QString &)), this,
+          SLOT(updateCloseButton(const QString &)));
+  int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+  setStyleSheet(QString("QLineEdit { padding-right: %1px; } ")
+                    .arg(clearButton->sizeHint().width() + frameWidth + 1));
+  QSize msz = minimumSizeHint();
+  setMinimumSize(
+      qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2),
+      qMax(msz.height(),
+           clearButton->sizeHint().height() + frameWidth * 2 + 2));
 }
 
-void LineEditWithClear::resizeEvent(QResizeEvent *)
-{
-    QSize sz = clearButton->sizeHint();
-    int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
-    clearButton->move(rect().right() - frameWidth - sz.width(),
-                      (rect().bottom() + 1 - sz.height())/2);
+void LineEditWithClear::resizeEvent(QResizeEvent *) {
+  QSize sz = clearButton->sizeHint();
+  int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+  clearButton->move(rect().right() - frameWidth - sz.width(),
+                    (rect().bottom() + 1 - sz.height()) / 2);
 }
 
-void LineEditWithClear::updateCloseButton(const QString& text)
-{
-    clearButton->setVisible(!text.isEmpty());
+void LineEditWithClear::updateCloseButton(const QString &text) {
+  clearButton->setVisible(!text.isEmpty());
 }
-
 }
-
 }
-
diff --git a/MantidQt/MantidWidgets/src/MWDiag.cpp b/MantidQt/MantidWidgets/src/MWDiag.cpp
index c747b7f22cb96abd3e6bc27cd498e37658f7db59..e393a21b54a0d62b9b12f57080be8dcde2956eae 100644
--- a/MantidQt/MantidWidgets/src/MWDiag.cpp
+++ b/MantidQt/MantidWidgets/src/MWDiag.cpp
@@ -27,11 +27,11 @@ using namespace MantidQt::API;
 using namespace MantidQt::MantidWidgets;
 using Mantid::Geometry::Instrument_const_sptr;
 
-MWDiag::MWDiag(QWidget *parent, QString prevSettingsGr, const QComboBox * const instru):
-  MantidWidget(parent),
-  m_dispDialog(NULL), m_instru(instru), 
-  m_TOFChanged(false), m_sTOFAutoVal(-1), m_eTOFAutoVal(-1), m_sumMono(false)
-{
+MWDiag::MWDiag(QWidget *parent, QString prevSettingsGr,
+               const QComboBox *const instru)
+    : MantidWidget(parent), m_dispDialog(NULL), m_instru(instru),
+      m_TOFChanged(false), m_sTOFAutoVal(-1), m_eTOFAutoVal(-1),
+      m_sumMono(false) {
   // allows saving and loading the values the user entered on to the form
   m_prevSets.beginGroup(prevSettingsGr);
   // Layout the widgets
@@ -43,25 +43,36 @@ MWDiag::MWDiag(QWidget *parent, QString prevSettingsGr, const QComboBox * const
   connectSignals(parent);
 }
 
-/// loads default values into each control using either the previous value used when the form was run or the default value for that control
-void MWDiag::loadSettings()
-{
+/// loads default values into each control using either the previous value used
+/// when the form was run or the default value for that control
+void MWDiag::loadSettings() {
   // Want the defaults from the instrument if nothing is saved in the config
   Instrument_const_sptr instrument = getInstrument(m_instru->currentText());
 
   m_designWidg.maskFileFinder->setText(getSetting("input mask"));
   m_designWidg.leOFile->setText(getSetting("output file"));
-  m_designWidg.leSignificance->setText(getSetting("significance", instrument, "diag_samp_sig"));
-  m_designWidg.leHighAbs->setText(getSetting("high abs", instrument, "diag_huge"));
-  m_designWidg.leLowAbs->setText(getSetting("low abs", instrument, "diag_tiny"));
-  m_designWidg.leHighMed->setText(getSetting("high median", instrument, "diag_van_hi"));
-  m_designWidg.leLowMed->setText(getSetting("low median", instrument, "diag_van_lo"));
-  m_designWidg.leVariation->setText(getSetting("variation", instrument, "diag_variation"));
-  m_designWidg.leStartTime->setText(getSetting("TOF start", instrument, "bkgd-range-min"));
-  m_designWidg.leEndTime->setText(getSetting("TOF end", instrument, "bkgd-range-max"));
-  m_designWidg.leAcceptance->setText(getSetting("back criteria", instrument, "diag_samp_hi"));
-  m_designWidg.bleed_maxrate->setText(getSetting("bleed_max_framerate", instrument, "diag_bleed_maxrate"));
-  m_designWidg.ignored_pixels->setText(getSetting("bleed_ignored_pixels", instrument, "diag_bleed_pixels"));
+  m_designWidg.leSignificance->setText(
+      getSetting("significance", instrument, "diag_samp_sig"));
+  m_designWidg.leHighAbs->setText(
+      getSetting("high abs", instrument, "diag_huge"));
+  m_designWidg.leLowAbs->setText(
+      getSetting("low abs", instrument, "diag_tiny"));
+  m_designWidg.leHighMed->setText(
+      getSetting("high median", instrument, "diag_van_hi"));
+  m_designWidg.leLowMed->setText(
+      getSetting("low median", instrument, "diag_van_lo"));
+  m_designWidg.leVariation->setText(
+      getSetting("variation", instrument, "diag_variation"));
+  m_designWidg.leStartTime->setText(
+      getSetting("TOF start", instrument, "bkgd-range-min"));
+  m_designWidg.leEndTime->setText(
+      getSetting("TOF end", instrument, "bkgd-range-max"));
+  m_designWidg.leAcceptance->setText(
+      getSetting("back criteria", instrument, "diag_samp_hi"));
+  m_designWidg.bleed_maxrate->setText(
+      getSetting("bleed_max_framerate", instrument, "diag_bleed_maxrate"));
+  m_designWidg.ignored_pixels->setText(
+      getSetting("bleed_ignored_pixels", instrument, "diag_bleed_pixels"));
 
   // Boolean settings
   // Background tests
@@ -78,99 +89,82 @@ void MWDiag::loadSettings()
   m_designWidg.bleed_group->setChecked(checked);
 }
 
-void MWDiag::setSumState(bool checked)
-{
-  m_sumMono = checked;
-}
-
+void MWDiag::setSumState(bool checked) { m_sumMono = checked; }
 
 /**
 * Get an instrument pointer for the name instrument
 */
-Instrument_const_sptr MWDiag::getInstrument(const QString & name)
-{
+Instrument_const_sptr MWDiag::getInstrument(const QString &name) {
   std::string ws_name = "__empty_" + name.toStdString();
 
-  AnalysisDataServiceImpl& dataStore = AnalysisDataService::Instance();
-  if( !dataStore.doesExist(ws_name) )
-  {
+  AnalysisDataServiceImpl &dataStore = AnalysisDataService::Instance();
+  if (!dataStore.doesExist(ws_name)) {
     QString pyInput =
-      "from Direct.DirectEnergyConversion import setup_reducer\n"
-      "setup_reducer('%1')";
+        "from Direct.DirectEnergyConversion import setup_reducer\n"
+        "setup_reducer('%1')";
     pyInput = pyInput.arg(QString::fromStdString(ws_name));
     runPythonCode(pyInput);
-    if( !dataStore.doesExist(ws_name) )
-    {
+    if (!dataStore.doesExist(ws_name)) {
       return Instrument_const_sptr();
     }
   }
-  MatrixWorkspace_sptr inst_ws = 
-    boost::dynamic_pointer_cast<MatrixWorkspace>(dataStore.retrieve(ws_name));
+  MatrixWorkspace_sptr inst_ws =
+      boost::dynamic_pointer_cast<MatrixWorkspace>(dataStore.retrieve(ws_name));
 
   return inst_ws->getInstrument();
 }
 
-QString MWDiag::getSetting(const QString & settingName, boost::shared_ptr<const Mantid::Geometry::Instrument> instrument,
-                           const QString & idfName) const
-{
+QString MWDiag::getSetting(
+    const QString &settingName,
+    boost::shared_ptr<const Mantid::Geometry::Instrument> instrument,
+    const QString &idfName) const {
   QString value;
-  if( m_prevSets.contains(settingName) )
-  {
+  if (m_prevSets.contains(settingName)) {
     value = m_prevSets.value(settingName).toString();
-  }
-  else if( instrument && !idfName.isEmpty() )
-  {
+  } else if (instrument && !idfName.isEmpty()) {
     std::string parName = idfName.toStdString();
     std::string parType = instrument->getParameterType(parName);
-    switch(parType[0])
-    {
-    case('b'):
-      {
-        std::vector<bool> vl = instrument->getBoolParameter(parName);
-        if (vl[0])
-          value = "1";
-        else
-          value = "0";
-        break;
-      }
-    case('i'):
-      {
-        std::vector<int> params = instrument->getIntParameter(parName);
-        if( params.size() == 1 )
-        {
-          value = QString::number(params.front());
-        }
-        else value = QString();
-        break;
-      }
-    default:
-      {
-        std::vector<double> params = instrument->getNumberParameter(parName);
-        if( params.size() == 1 )
-        {
-          value = QString::number(params.front());
-        }
-        else value = QString();
-      }
-
-
+    switch (parType[0]) {
+    case ('b'): {
+      std::vector<bool> vl = instrument->getBoolParameter(parName);
+      if (vl[0])
+        value = "1";
+      else
+        value = "0";
+      break;
     }
-  }
-  else
-  {
+    case ('i'): {
+      std::vector<int> params = instrument->getIntParameter(parName);
+      if (params.size() == 1) {
+        value = QString::number(params.front());
+      } else
+        value = QString();
+      break;
+    }
+    default: {
+      std::vector<double> params = instrument->getNumberParameter(parName);
+      if (params.size() == 1) {
+        value = QString::number(params.front());
+      } else
+        value = QString();
+    }
+    }
+  } else {
     value = QString();
   }
   // Convert strings of true/false to 1/0
-  if( value.trimmed().toLower()  == "true" ) value = "1";
-  else if( value.trimmed().toLower() == "false" ) value = "0";
+  if (value.trimmed().toLower() == "true")
+    value = "1";
+  else if (value.trimmed().toLower() == "false")
+    value = "0";
 
   return value;
 }
 
-/// loads default values into each control using either the previous value used when 
+/// loads default values into each control using either the previous value used
+/// when
 /// the form was run or the default value for that control
-void MWDiag::saveDefaults()
-{
+void MWDiag::saveDefaults() {
   m_prevSets.setValue("input mask", m_designWidg.maskFileFinder->getText());
   m_prevSets.setValue("output file", m_designWidg.leOFile->text());
 
@@ -187,107 +181,118 @@ void MWDiag::saveDefaults()
   m_prevSets.setValue("test background", m_designWidg.ckDoBack->isChecked());
   m_prevSets.setValue("back criteria", m_designWidg.leAcceptance->text());
   m_prevSets.setValue("no zero background",
-    m_designWidg.ckZeroCounts->isChecked());
+                      m_designWidg.ckZeroCounts->isChecked());
   m_prevSets.setValue("TOF start", m_designWidg.leStartTime->text());
   m_prevSets.setValue("TOF end", m_designWidg.leEndTime->text());
 }
-/// runs setToolTip() on each of the controls on the form  
-void MWDiag::setupToolTips()
-{  
-  QString oFileToolTip =
-    "The name of a file to write the spectra numbers of those that fail a test";
+/// runs setToolTip() on each of the controls on the form
+void MWDiag::setupToolTips() {
+  QString oFileToolTip = "The name of a file to write the spectra numbers of "
+                         "those that fail a test";
   m_designWidg.lbOFile->setToolTip(oFileToolTip);
   m_designWidg.leOFile->setToolTip(oFileToolTip);
   m_designWidg.pbOFile->setToolTip(oFileToolTip);
 
-  QString significanceToolTip =
-    "Spectra with integrated counts within this number of standard deviations from\n"
-    "the median will not be labeled bad (sets property SignificanceTest when\n"
-    "MedianDetectorTest is run)";
+  QString significanceToolTip = "Spectra with integrated counts within this "
+                                "number of standard deviations from\n"
+                                "the median will not be labeled bad (sets "
+                                "property SignificanceTest when\n"
+                                "MedianDetectorTest is run)";
   m_designWidg.leSignificance->setToolTip(significanceToolTip);
   m_designWidg.lbSignificance->setToolTip(significanceToolTip);
   m_designWidg.ckAngles->setToolTip("Not yet implemented");
   //-------------------------------------------------------------------------------------------------
   QString highAbsSetTool =
-    "Reject any spectrum that contains more than this number of counts in total\n"
-    "(sets property HighThreshold when FindDetectorsOutsideLimits is run)";
+      "Reject any spectrum that contains more than this number of counts in "
+      "total\n"
+      "(sets property HighThreshold when FindDetectorsOutsideLimits is run)";
   m_designWidg.leHighAbs->setToolTip(highAbsSetTool);
   m_designWidg.lbHighAbs->setToolTip(highAbsSetTool);
 
   QString lowAbsSetTool =
-    "Reject any spectrum that contains less than this number of counts in total\n"
-    "(sets property LowThreshold when FindDetectorsOutsideLimits is run)";
+      "Reject any spectrum that contains less than this number of counts in "
+      "total\n"
+      "(sets property LowThreshold when FindDetectorsOutsideLimits is run)";
   m_designWidg.leLowAbs->setToolTip(lowAbsSetTool);
   m_designWidg.lbLowAbs->setToolTip(lowAbsSetTool);
 
   QString highMedToolTip =
-    "Reject any spectrum whose total number of counts is more than this number of\n"
-    "times the median total for spectra (sets property HighThreshold when\n"
-    "MedianDetectorTest is run)";
+      "Reject any spectrum whose total number of counts is more than this "
+      "number of\n"
+      "times the median total for spectra (sets property HighThreshold when\n"
+      "MedianDetectorTest is run)";
   m_designWidg.leHighMed->setToolTip(highMedToolTip);
   m_designWidg.lbHighMed->setToolTip(highMedToolTip);
 
   QString lowMedToolTip =
-    "Reject any spectrum whose total number of counts is less than this number of\n"
-    "times the median total for spectra (sets property LowThreshold when\n"
-    "MedianDetectorTest is run)";
+      "Reject any spectrum whose total number of counts is less than this "
+      "number of\n"
+      "times the median total for spectra (sets property LowThreshold when\n"
+      "MedianDetectorTest is run)";
   m_designWidg.leLowMed->setToolTip(lowMedToolTip);
   m_designWidg.lbLowMed->setToolTip(lowMedToolTip);
 
-  QString variationToolTip = 
-    "When comparing equivalent spectra in the two white beam vanadiums reject any\n"
-    "whose the total number of counts varies by more than this multiple of the\n"
-    "median variation (sets property Variation when DetectorEfficiencyVariation is\n"
-    "is run)";
+  QString variationToolTip = "When comparing equivalent spectra in the two "
+                             "white beam vanadiums reject any\n"
+                             "whose the total number of counts varies by more "
+                             "than this multiple of the\n"
+                             "median variation (sets property Variation when "
+                             "DetectorEfficiencyVariation is\n"
+                             "is run)";
   m_designWidg.leVariation->setToolTip(variationToolTip);
   m_designWidg.lbVariation->setToolTip(variationToolTip);
 
-  QString acceptToolTip =
-    "Spectra whose total number of counts in the background region is this number\n"
-    "of times the median number of counts would be marked bad (sets property\n"
-    "HighThreshold when MedianDetectorTest is run)";
+  QString acceptToolTip = "Spectra whose total number of counts in the "
+                          "background region is this number\n"
+                          "of times the median number of counts would be "
+                          "marked bad (sets property\n"
+                          "HighThreshold when MedianDetectorTest is run)";
   m_designWidg.lbAcceptance->setToolTip(acceptToolTip);
   m_designWidg.leAcceptance->setToolTip(acceptToolTip);
 
   QString startTToolTip =
-    "An x-value in the bin marking the start of the background region, the\n"
-    "selection is exclusive (RangeLower in MedianDetectorTest)";
+      "An x-value in the bin marking the start of the background region, the\n"
+      "selection is exclusive (RangeLower in MedianDetectorTest)";
   m_designWidg.lbStartTime->setToolTip(startTToolTip);
   m_designWidg.leStartTime->setToolTip(startTToolTip);
-  QString endTToolTip =
-    "An x-value in the bin marking the the background region's end, the selection\n"
-    "is exclusive (RangeUpper in MedianDetectorTest)";
+  QString endTToolTip = "An x-value in the bin marking the the background "
+                        "region's end, the selection\n"
+                        "is exclusive (RangeUpper in MedianDetectorTest)";
   m_designWidg.lbEndTime->setToolTip(endTToolTip);
   m_designWidg.leEndTime->setToolTip(endTToolTip);
   m_designWidg.ckZeroCounts->setToolTip(
-    "Check this and spectra with zero counts in the background region will be"
-    "considered bad");
+      "Check this and spectra with zero counts in the background region will be"
+      "considered bad");
 }
-void MWDiag::connectSignals(const QWidget * const parentInterface)
-{// connect all the open file buttons to an open file dialog connected to it's line edit box
+void MWDiag::connectSignals(
+    const QWidget *const parentInterface) { // connect all the open file buttons
+                                            // to an open file dialog connected
+                                            // to it's line edit box
   QSignalMapper *signalMapper = new QSignalMapper(this);
   signalMapper->setMapping(m_designWidg.pbOFile, QString("OutputFile"));
-  connect(m_designWidg.pbOFile, SIGNAL(clicked()), signalMapper, SLOT(map()));  
-  connect(signalMapper, SIGNAL(mapped(const QString &)),
-    this, SLOT(browseClicked(const QString &)));
+  connect(m_designWidg.pbOFile, SIGNAL(clicked()), signalMapper, SLOT(map()));
+  connect(signalMapper, SIGNAL(mapped(const QString &)), this,
+          SLOT(browseClicked(const QString &)));
 
   // signals connected to the interface that this form is on
-  if ( parentInterface != NULL )
-  {
+  if (parentInterface != NULL) {
     // controls that copy the text from other controls
-    connect(parentInterface, SIGNAL(MWDiag_updateWBV(const QString&)),
-      m_designWidg.white_file, SLOT(setFileTextWithSearch(const QString&)));
-    connect(parentInterface, SIGNAL(MWDiag_updateTOFs(const double &, const double &)),
-      this, SLOT(updateTOFs(const double &, const double &)));
-    connect(m_designWidg.leStartTime, SIGNAL(editingFinished()), this, SLOT(TOFUpd()));
-    connect(m_designWidg.leEndTime, SIGNAL(editingFinished()), this, SLOT(TOFUpd()));
-
-    connect(parentInterface, SIGNAL(MWDiag_sendRuns(const QStringList&)),
-      this, SLOT(specifyRuns(const QStringList &)));
+    connect(parentInterface, SIGNAL(MWDiag_updateWBV(const QString &)),
+            m_designWidg.white_file,
+            SLOT(setFileTextWithSearch(const QString &)));
+    connect(parentInterface,
+            SIGNAL(MWDiag_updateTOFs(const double &, const double &)), this,
+            SLOT(updateTOFs(const double &, const double &)));
+    connect(m_designWidg.leStartTime, SIGNAL(editingFinished()), this,
+            SLOT(TOFUpd()));
+    connect(m_designWidg.leEndTime, SIGNAL(editingFinished()), this,
+            SLOT(TOFUpd()));
+
+    connect(parentInterface, SIGNAL(MWDiag_sendRuns(const QStringList &)), this,
+            SLOT(specifyRuns(const QStringList &)));
   }
 }
-void MWDiag::setUpValidators()
-{
+void MWDiag::setUpValidators() {
   // Attach number validators to everything that will only accept a number
   m_designWidg.leSignificance->setValidator(new QDoubleValidator(this));
   m_designWidg.leHighAbs->setValidator(new QDoubleValidator(this));
@@ -303,45 +308,39 @@ void MWDiag::setUpValidators()
 /**
 * Returns true if the input on the form is valid, false otherwise
 */
-bool MWDiag::isInputValid() const
-{
+bool MWDiag::isInputValid() const {
   bool valid(m_designWidg.maskFileFinder->isValid());
 
   valid &= m_designWidg.white_file->isValid();
   valid &= m_designWidg.white_file_2->isValid();
 
-  if(m_designWidg.ckDoBack->isChecked() && m_monoFiles.isEmpty() )
-  {
+  if (m_designWidg.ckDoBack->isChecked() && m_monoFiles.isEmpty()) {
     valid = false;
   }
 
   return valid;
 }
 
-//this function will be replaced a function in a widget
-void MWDiag::browseClicked(const QString &buttonDis)
-{
+// this function will be replaced a function in a widget
+void MWDiag::browseClicked(const QString &buttonDis) {
   QLineEdit *editBox(NULL);
   QStringList extensions;
   bool toSave = false;
-  if ( buttonDis == "OutputFile")
-  {
+  if (buttonDis == "OutputFile") {
     editBox = m_designWidg.leOFile;
     extensions << "msk";
     toSave = true;
   }
 
   QString filepath = openFileDialog(toSave, extensions);
-  if( filepath.isEmpty() ) return;
+  if (filepath.isEmpty())
+    return;
   QWidget *focus = QApplication::focusWidget();
   editBox->setFocus();
   editBox->setText(filepath);
-  if( focus )
-  {
+  if (focus) {
     focus->setFocus();
-  }
-  else
-  {
+  } else {
     this->setFocus();
   }
 }
@@ -349,98 +348,103 @@ void MWDiag::browseClicked(const QString &buttonDis)
 /**
 * Create a diagnostic script from the given
 */
-QString MWDiag::createDiagnosticScript() const
-{
+QString MWDiag::createDiagnosticScript() const {
   // Be nice and explicit so that this is as easy as possible to read later
   // Pull out the for data first
   QString sampleRun;
-  if( m_designWidg.ckDoBack )
-  {
-    if( m_monoFiles.count() == 1 )
-    {
+  if (m_designWidg.ckDoBack) {
+    if (m_monoFiles.count() == 1) {
       sampleRun = "r'" + m_monoFiles[0] + "'";
-    }
-    else
-    {
-      if( m_sumMono )
-      {
+    } else {
+      if (m_sumMono) {
         sampleRun = "[r'";
         sampleRun += m_monoFiles.join("',r'");
         sampleRun += "']";
-      }
-      else
-      {
-        throw std::runtime_error("Diagnostic interface does not support multiple mono files without summing. ");
+      } else {
+        throw std::runtime_error("Diagnostic interface does not support "
+                                 "multiple mono files without summing. ");
       }
     }
-  }
-  else
-  {
+  } else {
     sampleRun = "None";
   }
   QString whiteBeam = "r'" + m_designWidg.white_file->getFirstFilename() + "'";
-  QString whiteBeam2 = "r'" + m_designWidg.white_file_2->getFirstFilename() + "'";
-  if( whiteBeam2 == "r''" ) whiteBeam2 = "None";
-  QString removeZeroes = m_designWidg.ckZeroCounts->isChecked() ? "True" : "False";
+  QString whiteBeam2 =
+      "r'" + m_designWidg.white_file_2->getFirstFilename() + "'";
+  if (whiteBeam2 == "r''")
+    whiteBeam2 = "None";
+  QString removeZeroes =
+      m_designWidg.ckZeroCounts->isChecked() ? "True" : "False";
   QString lowCounts = m_designWidg.leLowAbs->text();
   QString highCounts = m_designWidg.leHighAbs->text();
   QString lowMedian = m_designWidg.leLowMed->text();
   QString highMedian = m_designWidg.leHighMed->text();
   QString significance = m_designWidg.leSignificance->text();
   QString acceptance = m_designWidg.leAcceptance->text();
-  QString bkgdRange = QString("[%1,%2]").arg(m_designWidg.leStartTime->text(),m_designWidg.leEndTime->text());
+  QString bkgdRange = QString("[%1,%2]").arg(m_designWidg.leStartTime->text(),
+                                             m_designWidg.leEndTime->text());
   QString variation = m_designWidg.leVariation->text();
-  QString hard_mask_file = "r'" + m_designWidg.maskFileFinder->getFirstFilename() + "'";
-  if( hard_mask_file == "r''" ) hard_mask_file = "None";
+  QString hard_mask_file =
+      "r'" + m_designWidg.maskFileFinder->getFirstFilename() + "'";
+  if (hard_mask_file == "r''")
+    hard_mask_file = "None";
   QString bleed_maxrate = m_designWidg.bleed_maxrate->text();
   QString bleed_pixels = m_designWidg.ignored_pixels->text();
 
-  QString diagCall =
-    "from Direct.DirectEnergyConversion import setup_reducer\n"
-    "from mantid import config\n"
-    "reducer = setup_reducer(config['default.instrument'])\n"
-    "reducer.prop_man.log_to_mantid = True\n"
-    "diag_total_mask = reducer.diagnose(";
+  QString diagCall = "from Direct.DirectEnergyConversion import setup_reducer\n"
+                     "from mantid import config\n"
+                     "reducer = setup_reducer(config['default.instrument'])\n"
+                     "reducer.prop_man.log_to_mantid = True\n"
+                     "diag_total_mask = reducer.diagnose(";
 
-  if( m_designWidg.ckDoBack->isChecked() )
-  {
+  if (m_designWidg.ckDoBack->isChecked()) {
     // Do the background check so we need all fields
-    diagCall += 
-      whiteBeam + "," + sampleRun + ","
-      "samp_zero=" + removeZeroes + ","
-      "tiny=" + lowCounts + ","
-      "huge=" + highCounts + ","
-      "van_lo=" + lowMedian + ","
-      "van_hi=" + highMedian + ","
-      "samp_sig=" + significance + ","
-      "samp_hi=" + acceptance + ","
-      "bkgd_range=" + bkgdRange + ","
-      "variation=" + variation + ","
-      "hard_mask=" + hard_mask_file;
-  }
-  else
-  {
+    diagCall += whiteBeam + "," + sampleRun + ","
+                                              "samp_zero=" +
+                removeZeroes + ","
+                               "tiny=" +
+                lowCounts + ","
+                            "huge=" +
+                highCounts + ","
+                             "van_lo=" +
+                lowMedian + ","
+                            "van_hi=" +
+                highMedian + ","
+                             "samp_sig=" +
+                significance + ","
+                               "samp_hi=" +
+                acceptance + ","
+                             "bkgd_range=" +
+                bkgdRange + ","
+                            "variation=" +
+                variation + ","
+                            "hard_mask=" +
+                hard_mask_file;
+  } else {
     // No background check so don't need all of the fields
-    diagCall += 
-      whiteBeam + ","
-      "tiny=" + lowCounts + ","
-      "huge=" + highCounts + ","
-      "van_lo=" + lowMedian + ","
-      "van_hi=" + highMedian + ","
-      "samp_sig=" + significance + ","
-      "hard_mask=" + hard_mask_file;
+    diagCall += whiteBeam + ","
+                            "tiny=" +
+                lowCounts + ","
+                            "huge=" +
+                highCounts + ","
+                             "van_lo=" +
+                lowMedian + ","
+                            "van_hi=" +
+                highMedian + ","
+                             "samp_sig=" +
+                significance + ","
+                               "hard_mask=" +
+                hard_mask_file;
   }
 
   // Bleed correction
-  if( m_designWidg.bleed_group->isChecked() )
-  {
-    diagCall += 
-      ",bleed_test=True,"
-      "bleed_maxrate=" + bleed_maxrate + ","
-      "bleed_pixels=" + bleed_pixels;
-  }
-  else
-  {
+  if (m_designWidg.bleed_group->isChecked()) {
+    diagCall += ",bleed_test=True,"
+                "bleed_maxrate=" +
+                bleed_maxrate + ","
+                                "bleed_pixels=" +
+                bleed_pixels;
+  } else {
     diagCall += ",bleed_test=False";
   }
 
@@ -453,13 +457,11 @@ QString MWDiag::createDiagnosticScript() const
 /**
 * Show the test result dialog
 */
-void MWDiag::showTestResults(const QString & testSummary) const
-{
-  if( !m_dispDialog )
-  {
+void MWDiag::showTestResults(const QString &testSummary) const {
+  if (!m_dispDialog) {
     m_dispDialog = new DiagResults(this->parentWidget());
-    connect(m_dispDialog, SIGNAL(runAsPythonScript(const QString&, bool)), this,
-      SIGNAL(runAsPythonScript(const QString&, bool)));
+    connect(m_dispDialog, SIGNAL(runAsPythonScript(const QString &, bool)),
+            this, SIGNAL(runAsPythonScript(const QString &, bool)));
   }
 
   m_dispDialog->updateResults(testSummary);
@@ -468,10 +470,8 @@ void MWDiag::showTestResults(const QString & testSummary) const
 
 /** close the results window, if there is one open
 */
-void MWDiag::closeDialog()
-{
-  if (m_dispDialog)
-  {
+void MWDiag::closeDialog() {
+  if (m_dispDialog) {
     m_dispDialog->close();
   }
 }
@@ -479,14 +479,11 @@ void MWDiag::closeDialog()
 /**
 *
 */
-QString MWDiag::openFileDialog(const bool save, const QStringList &exts)
-{
+QString MWDiag::openFileDialog(const bool save, const QStringList &exts) {
   QString filter;
-  if ( !exts.empty() )
-  {
+  if (!exts.empty()) {
     filter = "";
-    for ( int i = 0; i < exts.size(); i ++ )
-    {
+    for (int i = 0; i < exts.size(); i++) {
       filter.append("*." + exts[i] + " ");
     }
     filter = filter.trimmed();
@@ -494,86 +491,92 @@ QString MWDiag::openFileDialog(const bool save, const QStringList &exts)
   filter.append(";;All Files (*.*)");
 
   QString filename;
-  if( save )
-  {
-    filename = FileDialogHandler::getSaveFileName(this, "Save file",
-      m_prevSets.value("save file dir", "").toString(), filter);
-    if( ! filename.isEmpty() )
-    {
-      m_prevSets.setValue("save file dir", QFileInfo(filename).absoluteDir().path());
+  if (save) {
+    filename = FileDialogHandler::getSaveFileName(
+        this, "Save file", m_prevSets.value("save file dir", "").toString(),
+        filter);
+    if (!filename.isEmpty()) {
+      m_prevSets.setValue("save file dir",
+                          QFileInfo(filename).absoluteDir().path());
     }
-  }
-  else
-  {
-    filename = QFileDialog::getOpenFileName(this, "Open file",
-      m_prevSets.value("load file dir", "").toString(), filter);
-    if( ! filename.isEmpty() )
-    {
-      m_prevSets.setValue("load file dir", QFileInfo(filename).absoluteDir().path());
+  } else {
+    filename = QFileDialog::getOpenFileName(
+        this, "Open file", m_prevSets.value("load file dir", "").toString(),
+        filter);
+    if (!filename.isEmpty()) {
+      m_prevSets.setValue("load file dir",
+                          QFileInfo(filename).absoluteDir().path());
     }
   }
   return filename;
-} 
+}
 
 /**raises the window containing the results summary, run the Python scripts that
-*  have been created and, optionally on success, save the values on the form 
+*  have been created and, optionally on success, save the values on the form
 *  @param outWS :: the workspace for placing the information in
-*  @param saveSettings :: if the Python executes successfully and this parameter is true the settings are saved
-*  @return this method catches most exceptions and this return is main way that errors are reported
+*  @param saveSettings :: if the Python executes successfully and this parameter
+* is true the settings are saved
+*  @return this method catches most exceptions and this return is main way that
+* errors are reported
 */
-QString MWDiag::run(const QString &, const bool)
-{
-  // close any result window that is still there from a previous run, there might be nothing
+QString MWDiag::run(const QString &, const bool) {
+  // close any result window that is still there from a previous run, there
+  // might be nothing
   closeDialog();
-  // prepare to remove any intermediate workspaces used only during the calculations
+  // prepare to remove any intermediate workspaces used only during the
+  // calculations
   QString prob1;
 
-  if( !isInputValid() )
-  {
-    throw std::invalid_argument("Invalid input detected. Errors are marked with a red star.");
+  if (!isInputValid()) {
+    throw std::invalid_argument(
+        "Invalid input detected. Errors are marked with a red star.");
   }
   QString diagCode = createDiagnosticScript();
-  // The results of the diag code execution are captured in the string return of runPythonCode
+  // The results of the diag code execution are captured in the string return of
+  // runPythonCode
   QString scriptResults = runPythonCode(diagCode);
 
   // Now display them to the user if all went well
   // but bail out if not
-  if( scriptResults.startsWith("Exception:") )
-  {
+  if (scriptResults.startsWith("Exception:")) {
     return scriptResults;
   }
   // Send the results to the the non-modal dialog
   showTestResults(scriptResults);
   return "";
-
 }
 
-/** Called when the user identifies the background region in a different form, it copies the values over
+/** Called when the user identifies the background region in a different form,
+* it copies the values over
 *  @param start :: the TOF value of the start of the background region
 *  @param end :: the TOF value of the end of the background region
 */
-void MWDiag::updateTOFs(const double &start, const double &end)
-{// if the user added their own value don't change it
+void MWDiag::updateTOFs(
+    const double &start,
+    const double &end) { // if the user added their own value don't change it
   m_sTOFAutoVal = start;
   m_eTOFAutoVal = end;
-  if ( ! m_TOFChanged ) 
-  {
+  if (!m_TOFChanged) {
     m_designWidg.leStartTime->setText(QString::number(start));
     m_designWidg.leEndTime->setText(QString::number(end));
   }
 }
 /** This slot sets m_monoFiles based on the array that is
 *  passed to it
-*  @param runFileNames :: names of the files that will be used in the background test
+*  @param runFileNames :: names of the files that will be used in the background
+* test
 */
-void MWDiag::specifyRuns(const QStringList & runFileNames)
-{
+void MWDiag::specifyRuns(const QStringList &runFileNames) {
   m_monoFiles = runFileNames;
 }
-/// if the user has changed either of the time of flight values running this method stops the setting from being replaced by the default
-void MWDiag::TOFUpd()
-{// if the user had already altered the contents of the box it has been noted that the save name is under user control so do nothing
-  if (m_TOFChanged) return;
-  m_TOFChanged = (m_designWidg.leStartTime->text().toDouble() != m_sTOFAutoVal)
-    || (m_designWidg.leEndTime->text().toDouble() != m_eTOFAutoVal);
+/// if the user has changed either of the time of flight values running this
+/// method stops the setting from being replaced by the default
+void MWDiag::TOFUpd() { // if the user had already altered the contents of the
+                        // box it has been noted that the save name is under
+                        // user control so do nothing
+  if (m_TOFChanged)
+    return;
+  m_TOFChanged =
+      (m_designWidg.leStartTime->text().toDouble() != m_sTOFAutoVal) ||
+      (m_designWidg.leEndTime->text().toDouble() != m_eTOFAutoVal);
 }
diff --git a/MantidQt/MantidWidgets/src/MWRunFiles.cpp b/MantidQt/MantidWidgets/src/MWRunFiles.cpp
index b943cc4917d4e855f348ee537e3c373ba126d020..ef3298acc6d6b5d0f12ec2d09e4adc7600d95eff 100644
--- a/MantidQt/MantidWidgets/src/MWRunFiles.cpp
+++ b/MantidQt/MantidWidgets/src/MWRunFiles.cpp
@@ -248,8 +248,7 @@ MWRunFiles::MWRunFiles(QWidget *parent)
     QStringList dataDirs =
         QString::fromStdString(
             Mantid::Kernel::ConfigService::Instance().getString(
-                "datasearch.directories"))
-            .split(";", QString::SkipEmptyParts);
+                "datasearch.directories")).split(";", QString::SkipEmptyParts);
 
     if (!dataDirs.isEmpty())
       m_lastDir = dataDirs[0];
@@ -736,7 +735,8 @@ void MWRunFiles::findFiles() {
       // Regex to match a selection of run numbers as defined here:
       // mantidproject.org/MultiFileLoading
       // Also allowing spaces between delimiters as this seems to work fine
-      const std::string runNumberString = "([0-9]+)([:+-] ?[0-9]+)? ?(:[0-9]+)?";
+      const std::string runNumberString =
+          "([0-9]+)([:+-] ?[0-9]+)? ?(:[0-9]+)?";
       boost::regex runNumbers(runNumberString, boost::regex::extended);
       // Regex to match a list of run numbers delimited by commas
       const std::string runListString =
@@ -836,8 +836,7 @@ void MWRunFiles::readSettings(const QString &group) {
     QStringList datadirs =
         QString::fromStdString(
             Mantid::Kernel::ConfigService::Instance().getString(
-                "datasearch.directories"))
-            .split(";", QString::SkipEmptyParts);
+                "datasearch.directories")).split(";", QString::SkipEmptyParts);
     if (!datadirs.isEmpty())
       m_lastDir = datadirs[0];
   }
diff --git a/MantidQt/MantidWidgets/src/MWView.cpp b/MantidQt/MantidWidgets/src/MWView.cpp
index 15f3dd64885545c416bebbfd5e72ab5b8a895a37..4fd95eed78a68d802c59bfadc53abb6590b7a13f 100644
--- a/MantidQt/MantidWidgets/src/MWView.cpp
+++ b/MantidQt/MantidWidgets/src/MWView.cpp
@@ -28,14 +28,11 @@ namespace MantidWidgets {
 //               ++++++++ Public members ++++++++
 //               ++++++++++++++++++++++++++++++++
 
-MWView::MWView(QWidget *parent) :
-  QWidget(parent),
-  MantidQt::API::WorkspaceObserver(),
-  m_mdSettings(boost::make_shared<MantidQt::API::MdSettings>()),
-  m_workspace(),
-  m_wellcomeWorkspace(),
-  m_wellcomeName{"__MWViewWellcomeWorkspace"},
-  m_dimensions() {
+MWView::MWView(QWidget *parent)
+    : QWidget(parent), MantidQt::API::WorkspaceObserver(),
+      m_mdSettings(boost::make_shared<MantidQt::API::MdSettings>()),
+      m_workspace(), m_wellcomeWorkspace(),
+      m_wellcomeName{"__MWViewWellcomeWorkspace"}, m_dimensions() {
   // Watch for the deletion of the associated workspace
   this->observePreDelete(true);
   m_spect = new QwtPlotSpectrogram();
@@ -48,7 +45,7 @@ MWView::MWView(QWidget *parent) :
 }
 
 MWView::~MWView() {
-  this->observePreDelete(false);  //Disconnect notifications
+  this->observePreDelete(false); // Disconnect notifications
   saveSettings();
   delete m_data;
   delete m_spect;
@@ -112,9 +109,7 @@ void MWView::updateDisplay() {
   m_uiForm.plot2D->replot();
 }
 
-SafeQwtPlot* MWView::getPlot2D(){
-  return m_uiForm.plot2D;
-}
+SafeQwtPlot *MWView::getPlot2D() { return m_uiForm.plot2D; }
 
 //               ++++++++++++++++++++++++++++++++
 //               ++++++++ Public slots   ++++++++
@@ -144,12 +139,13 @@ void MWView::setTransparentZerosSlot(bool transparent) {
 /*
  * @brief Clean shown data when associated workspace is deleted
  */
-void MWView::preDeleteHandle(const std::string &workspaceName,
-  const boost::shared_ptr<Mantid::API::Workspace> workspace) {
+void MWView::preDeleteHandle(
+    const std::string &workspaceName,
+    const boost::shared_ptr<Mantid::API::Workspace> workspace) {
   UNUSED_ARG(workspaceName);
   Mantid::API::MatrixWorkspace_sptr ws =
-    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
-  if(ws && ws==m_workspace){
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(workspace);
+  if (ws && ws == m_workspace) {
     this->showWellcomeWorkspace();
   }
 }
@@ -162,10 +158,10 @@ void MWView::preDeleteHandle(const std::string &workspaceName,
 void MWView::initLayout() {
   m_uiForm.setupUi(this);
   QObject::connect(m_uiForm.colorBar,
-                   SIGNAL(changedColorRange(double, double, bool)),
-                   this, SLOT(colorRangeChangedSlot()));
-  QObject::connect(m_uiForm.colorBar, SIGNAL(colorBarDoubleClicked()),
-                   this, SLOT(loadColorMapSlot()));
+                   SIGNAL(changedColorRange(double, double, bool)), this,
+                   SLOT(colorRangeChangedSlot()));
+  QObject::connect(m_uiForm.colorBar, SIGNAL(colorBarDoubleClicked()), this,
+                   SLOT(loadColorMapSlot()));
   /// initialize the color on the bar and the data
   m_uiForm.colorBar->setViewRange(1, 10);
   m_spect->attach(m_uiForm.plot2D); // attach the spectrogram to the plot
@@ -233,7 +229,8 @@ void MWView::checkRangeLimits() {
   if (!mess.str().empty()) {
     mess << "Bad ranges could cause memory allocation errors. Please fix the "
             "workspace.";
-    mess << std::endl << "You can continue using Mantid.";
+    mess << std::endl
+         << "You can continue using Mantid.";
     throw std::out_of_range(mess.str());
   }
 }
@@ -279,21 +276,24 @@ void MWView::setVectorDimensions() {
  * is selected
  */
 void MWView::spawnWellcomeWorkspace() {
-  if(Mantid::API::AnalysisDataService::Instance().doesExist(m_wellcomeName)) {
-    m_wellcomeWorkspace = Mantid::API::AnalysisDataService::Instance()
-      .retrieveWS<Mantid::API::MatrixWorkspace>(m_wellcomeName);
+  if (Mantid::API::AnalysisDataService::Instance().doesExist(m_wellcomeName)) {
+    m_wellcomeWorkspace =
+        Mantid::API::AnalysisDataService::Instance()
+            .retrieveWS<Mantid::API::MatrixWorkspace>(m_wellcomeName);
   } else {
     int numberSpectra = 100;
     double intensity = 10.0;
     auto dataX = std::vector<double>();
     auto dataY = std::vector<double>();
-    for(int i=0; i<numberSpectra; i++){
-      for(int j=0; j<numberSpectra; j++){
-        dataX.push_back(j*1.);
-        dataY.push_back(intensity*(i*i+j*j)/(2*numberSpectra*numberSpectra));
+    for (int i = 0; i < numberSpectra; i++) {
+      for (int j = 0; j < numberSpectra; j++) {
+        dataX.push_back(j * 1.);
+        dataY.push_back(intensity * (i * i + j * j) /
+                        (2 * numberSpectra * numberSpectra));
       }
     }
-    auto createWsAlg = Mantid::API::AlgorithmManager::Instance().create("CreateWorkspace");
+    auto createWsAlg =
+        Mantid::API::AlgorithmManager::Instance().create("CreateWorkspace");
     createWsAlg->initialize();
     createWsAlg->setChild(true);
     createWsAlg->setLogging(false);
@@ -303,7 +303,8 @@ void MWView::spawnWellcomeWorkspace() {
     createWsAlg->setProperty("DataY", dataY);
     createWsAlg->execute();
     m_wellcomeWorkspace = createWsAlg->getProperty("OutputWorkspace");
-    Mantid::API::AnalysisDataService::Instance().add(m_wellcomeName, m_wellcomeWorkspace);
+    Mantid::API::AnalysisDataService::Instance().add(m_wellcomeName,
+                                                     m_wellcomeWorkspace);
   }
 }
 
@@ -314,7 +315,7 @@ void MWView::showWellcomeWorkspace() {
   this->spawnWellcomeWorkspace();
   this->setWorkspace(m_wellcomeWorkspace);
   this->updateDisplay();
-  m_uiForm.colorBar->setScale(0); //reset to linear color scale
+  m_uiForm.colorBar->setScale(0); // reset to linear color scale
 }
 
 } // namespace MantidQt
diff --git a/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp b/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
index 05b23cf4038200c328bd6d0170e86c5192fd370a..b95792c108175dbde01c4bd0a7fb09ad4033275a 100644
--- a/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
+++ b/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp
@@ -22,20 +22,17 @@
 #include <QWidget>
 #include <stdexcept>
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 using std::string;
 using namespace MantidQt::API;
 
 REGISTER_HELPWINDOW(MantidHelpWindow)
 
-namespace
-{
-  /// static logger
-  Mantid::Kernel::Logger g_log("MantidHelpWindow");
+namespace {
+/// static logger
+Mantid::Kernel::Logger g_log("MantidHelpWindow");
 }
 
 // initialise the help window
@@ -57,31 +54,24 @@ const QString COLLECTION_FILE("MantidProject.qhc");
 /**
  * Default constructor shows the @link DEFAULT_URL @endlink.
  */
-MantidHelpWindow::MantidHelpWindow(QWidget* parent, Qt::WindowFlags flags) :
-  MantidHelpInterface(),
-    m_collectionFile(""),
-    m_cacheFile(""),
-    m_firstRun(true)
-{
+MantidHelpWindow::MantidHelpWindow(QWidget *parent, Qt::WindowFlags flags)
+    : MantidHelpInterface(), m_collectionFile(""), m_cacheFile(""),
+      m_firstRun(true) {
   // find the collection and delete the cache file if this is the first run
-  if (!bool(g_helpWindow))
-  {
+  if (!bool(g_helpWindow)) {
     this->determineFileLocs();
 
-    // see if chache file exists and remove it - shouldn't be necessary, but it is
-    if (!m_cacheFile.empty())
-    {
-      if (Poco::File(m_cacheFile).exists())
-      {
+    // see if chache file exists and remove it - shouldn't be necessary, but it
+    // is
+    if (!m_cacheFile.empty()) {
+      if (Poco::File(m_cacheFile).exists()) {
         g_log.debug() << "Removing help cache file \"" << m_cacheFile << "\"\n";
         Poco::File(m_cacheFile).remove();
-      }
-      else
-      {
-        Poco::Path direcPath = Poco::Path(m_cacheFile).parent(); // drop off the filename
+      } else {
+        Poco::Path direcPath =
+            Poco::Path(m_cacheFile).parent(); // drop off the filename
         Poco::File direcFile(direcPath.absolute().toString());
-        if (!direcFile.exists())
-        {
+        if (!direcFile.exists()) {
           direcFile.createDirectories();
         }
       }
@@ -89,19 +79,19 @@ MantidHelpWindow::MantidHelpWindow(QWidget* parent, Qt::WindowFlags flags) :
 
     // create the help engine with the found location
     g_log.debug() << "Loading " << m_collectionFile << "\n";
-    auto helpEngine = new QHelpEngine(QString(m_collectionFile.c_str()), parent);
-    QObject::connect(helpEngine, SIGNAL(warning(QString)), this, SLOT(warning(QString)));
+    auto helpEngine =
+        new QHelpEngine(QString(m_collectionFile.c_str()), parent);
+    QObject::connect(helpEngine, SIGNAL(warning(QString)), this,
+                     SLOT(warning(QString)));
     g_log.debug() << "Making local cache copy for saving information at "
                   << m_cacheFile << "\n";
-    if (helpEngine->copyCollectionFile(QString(m_cacheFile.c_str())))
-    {
+    if (helpEngine->copyCollectionFile(QString(m_cacheFile.c_str()))) {
       helpEngine->setCollectionFile(QString(m_cacheFile.c_str()));
-    }
-    else
-    {
+    } else {
       g_log.warning("Failed to copy collection file");
     }
-    g_log.debug() << "helpengine.setupData() returned " << helpEngine->setupData() << "\n";
+    g_log.debug() << "helpengine.setupData() returned "
+                  << helpEngine->setupData() << "\n";
 
     // create a new help window
     g_helpWindow = new pqHelpWindow(helpEngine, parent, flags);
@@ -109,8 +99,7 @@ MantidHelpWindow::MantidHelpWindow(QWidget* parent, Qt::WindowFlags flags) :
 
     // show the home page on startup
     auto registeredDocs = helpEngine->registeredDocumentations();
-    if (registeredDocs.size() > 0)
-    {
+    if (registeredDocs.size() > 0) {
       g_helpWindow->showHomePage(registeredDocs[0]);
     }
     g_helpWindow->show();
@@ -119,50 +108,39 @@ MantidHelpWindow::MantidHelpWindow(QWidget* parent, Qt::WindowFlags flags) :
 }
 
 /// Destructor does nothing.
-MantidHelpWindow::~MantidHelpWindow()
-{
-  this->shutdown();
-}
+MantidHelpWindow::~MantidHelpWindow() { this->shutdown(); }
 
-void MantidHelpWindow::showHelp(const QString &url)
-{
+void MantidHelpWindow::showHelp(const QString &url) {
   g_log.debug() << "open help window for \"" << url.toStdString() << "\"\n";
   // bring up the help window if it is showing
   g_helpWindow->show();
   g_helpWindow->raise();
-  if (!url.isEmpty())
-  {
+  if (!url.isEmpty()) {
     g_helpWindow->showPage(url);
   }
 }
 
-
-void MantidHelpWindow::openWebpage(const QUrl &url)
-{
-    g_log.debug() << "open url \"" << url.toString().toStdString() << "\"\n";
-    QDesktopServices::openUrl(url);
+void MantidHelpWindow::openWebpage(const QUrl &url) {
+  g_log.debug() << "open url \"" << url.toString().toStdString() << "\"\n";
+  QDesktopServices::openUrl(url);
 }
 
-void MantidHelpWindow::showPage(const QString &url)
-{
+void MantidHelpWindow::showPage(const QString &url) {
   this->showPage(QUrl(url));
 }
 
-void MantidHelpWindow::showPage(const QUrl &url)
-{
-  if (bool(g_helpWindow))
-  {
+void MantidHelpWindow::showPage(const QUrl &url) {
+  if (bool(g_helpWindow)) {
     if (url.isEmpty())
       this->showHelp(DEFAULT_URL);
     else
       this->showHelp(url.toString());
-  }
-  else // qt-assistant disabled
+  } else // qt-assistant disabled
   {
-      if (url.isEmpty())
-          this->openWebpage(WIKI_DEFAULT_URL);
-      else
-          this->openWebpage(url);
+    if (url.isEmpty())
+      this->openWebpage(WIKI_DEFAULT_URL);
+    else
+      this->openWebpage(url);
   }
 }
 
@@ -173,17 +151,15 @@ void MantidHelpWindow::showPage(const QUrl &url)
  * @param url The url to open. This should start with @link BASE_URL @endlink.
  * If it is empty show the default page.
  */
-void MantidHelpWindow::showPage(const string &url)
-{
+void MantidHelpWindow::showPage(const string &url) {
   this->showPage(QUrl(QString(url.c_str())));
 }
 
-void MantidHelpWindow::showWikiPage(const string &page)
-{
-    if (page.empty())
-        this->openWebpage(WIKI_DEFAULT_URL);
-    else
-        this->openWebpage(WIKI_BASE_URL + page.c_str());
+void MantidHelpWindow::showWikiPage(const string &page) {
+  if (page.empty())
+    this->openWebpage(WIKI_DEFAULT_URL);
+  else
+    this->openWebpage(WIKI_BASE_URL + page.c_str());
 }
 
 /**
@@ -192,9 +168,8 @@ void MantidHelpWindow::showWikiPage(const string &page)
  * @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());
+void MantidHelpWindow::showWikiPage(const QString &page) {
+  this->showWikiPage(page.toStdString());
 }
 
 /**
@@ -206,82 +181,73 @@ void MantidHelpWindow::showWikiPage(const QString &page)
  * @param version The version of the algorithm to jump do. The default
  * value (-1) will show the top of the page.
  */
-void MantidHelpWindow::showAlgorithm(const string &name, const int version)
-{
-    auto versionStr("-v" + boost::lexical_cast<string>(version));
-    if (version <= 0)
-      versionStr = ""; // let the redirect do its thing
-
-    if (bool(g_helpWindow))
-    {
-        QString url(BASE_URL);
-        url += "algorithms/";
-        if (name.empty())
-            url += "index.html";
-        else
-          url += QString(name.c_str()) + QString(versionStr.c_str()) + ".html";
-        this->showHelp(url);
-    }
-    else // qt-assistant disabled
-    {
-        if (name.empty())
-            this->showWikiPage(std::string("Category:Algorithms"));
-        else
-            this->showWikiPage(name);
-    }
+void MantidHelpWindow::showAlgorithm(const string &name, const int version) {
+  auto versionStr("-v" + boost::lexical_cast<string>(version));
+  if (version <= 0)
+    versionStr = ""; // let the redirect do its thing
+
+  if (bool(g_helpWindow)) {
+    QString url(BASE_URL);
+    url += "algorithms/";
+    if (name.empty())
+      url += "index.html";
+    else
+      url += QString(name.c_str()) + QString(versionStr.c_str()) + ".html";
+    this->showHelp(url);
+  } else // qt-assistant disabled
+  {
+    if (name.empty())
+      this->showWikiPage(std::string("Category:Algorithms"));
+    else
+      this->showWikiPage(name);
+  }
 }
 
 /**
- * Convenience method for HelpWindowImpl::showAlgorithm(const string &, const int).
+ * Convenience method for HelpWindowImpl::showAlgorithm(const string &, const
+ *int).
  *
  * @param name The name of the algorithm to show. If this is empty show
  * the algorithm index.
  * @param version The version of the algorithm to jump do. The default
  * value (-1) will show the top of the page.
  */
-void MantidHelpWindow::showAlgorithm(const QString &name, const int version)
-{
-    this->showAlgorithm(name.toStdString(), version);
+void MantidHelpWindow::showAlgorithm(const QString &name, const int version) {
+  this->showAlgorithm(name.toStdString(), version);
 }
 
-
 /**
  * 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.
  */
-void MantidHelpWindow::showConcept(const string &name)
-{
-    if (bool(g_helpWindow))
-    {
-        QString url(BASE_URL);
-        url += "concepts/";
-        if (name.empty())
-            url += "index.html";
-        else
-          url += QString(name.c_str()) + ".html";
-        this->showHelp(url);
-    }
-    else // qt-assistant disabled
-    {
-        if (name.empty())
-            this->showWikiPage(std::string("Category:Concepts"));
-        else
-            this->showWikiPage(name);
-    }
+void MantidHelpWindow::showConcept(const string &name) {
+  if (bool(g_helpWindow)) {
+    QString url(BASE_URL);
+    url += "concepts/";
+    if (name.empty())
+      url += "index.html";
+    else
+      url += QString(name.c_str()) + ".html";
+    this->showHelp(url);
+  } else // qt-assistant disabled
+  {
+    if (name.empty())
+      this->showWikiPage(std::string("Category:Concepts"));
+    else
+      this->showWikiPage(name);
+  }
 }
 
-
 /**
  * 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.
  */
-void MantidHelpWindow::showConcept(const QString &name)
-{
-    this->showConcept(name.toStdString());
+void MantidHelpWindow::showConcept(const QString &name) {
+  this->showConcept(name.toStdString());
 }
 
 /**
@@ -291,26 +257,23 @@ void MantidHelpWindow::showConcept(const QString &name)
  * @param name The name of the fit function to show. If it is empty show
  * the fit function index.
  */
-void MantidHelpWindow::showFitFunction(const std::string &name)
-{
-    if (bool(g_helpWindow))
-    {
-        QString url(BASE_URL);
-        url += "functions/";
-        if (name.empty())
-            url += "index.html";
-        else
-        url += QString(name.c_str()) + ".html";
-
-        this->showHelp(url);
-    }
-    else // qt-assistant disabled
-    {
-        if (name.empty())
-            this->showWikiPage(std::string("Category:Fit_functions"));
-        else
-            this->showWikiPage(name);
-    }
+void MantidHelpWindow::showFitFunction(const std::string &name) {
+  if (bool(g_helpWindow)) {
+    QString url(BASE_URL);
+    url += "functions/";
+    if (name.empty())
+      url += "index.html";
+    else
+      url += QString(name.c_str()) + ".html";
+
+    this->showHelp(url);
+  } else // qt-assistant disabled
+  {
+    if (name.empty())
+      this->showWikiPage(std::string("Category:Fit_functions"));
+    else
+      this->showWikiPage(name);
+  }
 }
 
 /**
@@ -320,9 +283,8 @@ void MantidHelpWindow::showFitFunction(const std::string &name)
  * @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());
+void MantidHelpWindow::showFitFunction(const QString &name) {
+  this->showFitFunction(name.toStdString());
 }
 
 /**
@@ -330,9 +292,8 @@ void MantidHelpWindow::showFitFunction(const QString &name)
  *
  * @param name The name of the interface to show
  */
-void MantidHelpWindow::showCustomInterface(const QString &name)
-{
-    this->showCustomInterface(name.toStdString());
+void MantidHelpWindow::showCustomInterface(const QString &name) {
+  this->showCustomInterface(name.toStdString());
 }
 
 /**
@@ -340,26 +301,23 @@ void MantidHelpWindow::showCustomInterface(const QString &name)
  *
  * @param name The name of the interface to show
  */
-void MantidHelpWindow::showCustomInterface(const std::string &name)
-{
-    if (bool(g_helpWindow))
-    {
-        QString url(BASE_URL);
-        url += "interfaces/";
-        if (name.empty())
-            url += "index.html";
-        else
-          url += QString(name.c_str()) + ".html";
-        this->showHelp(url);
-    }
+void MantidHelpWindow::showCustomInterface(const std::string &name) {
+  if (bool(g_helpWindow)) {
+    QString url(BASE_URL);
+    url += "interfaces/";
+    if (name.empty())
+      url += "index.html";
+    else
+      url += QString(name.c_str()) + ".html";
+    this->showHelp(url);
+  }
 }
 
 /**
  * Can be called by the host process to indicate that it will
  * close soon. This closes the help window & releases the QProcess
  */
-void MantidHelpWindow::shutdown()
-{
+void MantidHelpWindow::shutdown() {
   // close the window
   g_helpWindow->close();
 }
@@ -367,128 +325,118 @@ void MantidHelpWindow::shutdown()
 /**
  * Determine the location of the collection file, "mantid.qhc". This
  * checks in multiple locations and can throw an exception. For more
- * information see http://doc.qt.digia.com/qq/qq28-qthelp.html#htmlfilesandhelpprojects
+ * information see
+ *http://doc.qt.digia.com/qq/qq28-qthelp.html#htmlfilesandhelpprojects
  *
  * @param binDir The location of the mantid executable.
  */
-void MantidHelpWindow::findCollectionFile(std::string &binDir)
-{
-    // this being empty notes the feature being disabled
-    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";
-    if ( searchDir.exists(COLLECTION_FILE) )
-    {
-      m_collectionFile = path.toStdString();
-      return;
-    }
-
-    // try where the builds will put it for a single configuration build
-    searchDir.cdUp();
-    if(searchDir.cd("docs"))
-    {
-      searchDir.cd("qthelp");
-      path = searchDir.absoluteFilePath(COLLECTION_FILE);
-      g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
-      if ( searchDir.exists(COLLECTION_FILE) )
-      {
-        m_collectionFile = path.toStdString();
-        return;
-      }
-    }
-    // try where the builds will put it for a multi-configuration build
-    searchDir.cdUp();
-    if(searchDir.cd("docs"))
-    {
-      searchDir.cd("qthelp");
-      path = searchDir.absoluteFilePath(COLLECTION_FILE);
-      g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
-      if ( searchDir.exists(COLLECTION_FILE) )
-      {
-        m_collectionFile = path.toStdString();
-        return;
-      }
-    }
+void MantidHelpWindow::findCollectionFile(std::string &binDir) {
+  // this being empty notes the feature being disabled
+  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";
+  if (searchDir.exists(COLLECTION_FILE)) {
+    m_collectionFile = path.toStdString();
+    return;
+  }
 
-    // try in windows/linux install location
-    searchDir = QDir(QString::fromStdString(binDir));
-    searchDir.cdUp();
-    searchDir.cd("share");
-    searchDir.cd("doc");
+  // try where the builds will put it for a single configuration build
+  searchDir.cdUp();
+  if (searchDir.cd("docs")) {
+    searchDir.cd("qthelp");
     path = searchDir.absoluteFilePath(COLLECTION_FILE);
     g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
-    if (searchDir.exists(COLLECTION_FILE))
-    {
+    if (searchDir.exists(COLLECTION_FILE)) {
       m_collectionFile = path.toStdString();
       return;
     }
-
-    // try a special place for mac/osx
-    searchDir = QDir(QString::fromStdString(binDir));
-    searchDir.cdUp();
-    searchDir.cdUp();
-    searchDir.cd("share");
-    searchDir.cd("doc");
+  }
+  // try where the builds will put it for a multi-configuration build
+  searchDir.cdUp();
+  if (searchDir.cd("docs")) {
+    searchDir.cd("qthelp");
     path = searchDir.absoluteFilePath(COLLECTION_FILE);
     g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
-    if (searchDir.exists(COLLECTION_FILE))
-    {
+    if (searchDir.exists(COLLECTION_FILE)) {
       m_collectionFile = path.toStdString();
       return;
     }
+  }
+
+  // try in windows/linux install location
+  searchDir = QDir(QString::fromStdString(binDir));
+  searchDir.cdUp();
+  searchDir.cd("share");
+  searchDir.cd("doc");
+  path = searchDir.absoluteFilePath(COLLECTION_FILE);
+  g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
+  if (searchDir.exists(COLLECTION_FILE)) {
+    m_collectionFile = path.toStdString();
+    return;
+  }
+
+  // try a special place for mac/osx
+  searchDir = QDir(QString::fromStdString(binDir));
+  searchDir.cdUp();
+  searchDir.cdUp();
+  searchDir.cd("share");
+  searchDir.cd("doc");
+  path = searchDir.absoluteFilePath(COLLECTION_FILE);
+  g_log.debug() << "Trying \"" << path.toStdString() << "\"\n";
+  if (searchDir.exists(COLLECTION_FILE)) {
+    m_collectionFile = path.toStdString();
+    return;
+  }
 
-    // all tries have failed
-    g_log.information("Failed to find help system collection file \"" + COLLECTION_FILE.toStdString() + "\"");
+  // all tries have failed
+  g_log.information("Failed to find help system collection file \"" +
+                    COLLECTION_FILE.toStdString() + "\"");
 }
 
 /**
  * Determine the location of the collection and cache files.
  */
-void MantidHelpWindow::determineFileLocs()
-{
-    // determine collection file location
-    string binDir = Mantid::Kernel::ConfigService::Instance().getDirectoryOfExecutable();
-    this->findCollectionFile(binDir);
-    if (m_collectionFile.empty())
-    {
-        // clear out the other filenames
-        m_cacheFile = "";
-        return;
-    }
-    g_log.debug() << "Using collection file \"" << m_collectionFile << "\"\n";
-
-    // determine cache file location
-    m_cacheFile = COLLECTION_FILE.toStdString();
-    QString dataLoc = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
-    if (dataLoc.endsWith("mantidproject"))
-    {
-        Poco::Path path (dataLoc.toStdString(), m_cacheFile);
-        m_cacheFile = path.absolute().toString();
-    }
-    else if (dataLoc.endsWith("MantidPlot")) // understood to end in "Mantid/MantidPlot"
-    {
-        Poco::Path path(dataLoc.toStdString());
-        path = path.parent(); // drop off "MantidPlot"
-        path = path.parent(); // drop off "Mantid"
-        path = Poco::Path(path, "mantidproject");
-        path = Poco::Path(path, m_cacheFile);
-        m_cacheFile = path.absolute().toString();
-    }
-    else
-    {
-        g_log.debug() << "Failed to determine help cache file location\n"; // REMOVE
-        Poco::Path path(dataLoc.toStdString(), "mantidproject");
-        path = Poco::Path(path, COLLECTION_FILE.toStdString());
-        m_cacheFile = path.absolute().toString();
-    }
+void MantidHelpWindow::determineFileLocs() {
+  // determine collection file location
+  string binDir =
+      Mantid::Kernel::ConfigService::Instance().getDirectoryOfExecutable();
+  this->findCollectionFile(binDir);
+  if (m_collectionFile.empty()) {
+    // clear out the other filenames
+    m_cacheFile = "";
+    return;
+  }
+  g_log.debug() << "Using collection file \"" << m_collectionFile << "\"\n";
+
+  // determine cache file location
+  m_cacheFile = COLLECTION_FILE.toStdString();
+  QString dataLoc =
+      QDesktopServices::storageLocation(QDesktopServices::DataLocation);
+  if (dataLoc.endsWith("mantidproject")) {
+    Poco::Path path(dataLoc.toStdString(), m_cacheFile);
+    m_cacheFile = path.absolute().toString();
+  } else if (dataLoc.endsWith(
+                 "MantidPlot")) // understood to end in "Mantid/MantidPlot"
+  {
+    Poco::Path path(dataLoc.toStdString());
+    path = path.parent(); // drop off "MantidPlot"
+    path = path.parent(); // drop off "Mantid"
+    path = Poco::Path(path, "mantidproject");
+    path = Poco::Path(path, m_cacheFile);
+    m_cacheFile = path.absolute().toString();
+  } else {
+    g_log.debug() << "Failed to determine help cache file location\n"; // REMOVE
+    Poco::Path path(dataLoc.toStdString(), "mantidproject");
+    path = Poco::Path(path, COLLECTION_FILE.toStdString());
+    m_cacheFile = path.absolute().toString();
+  }
 }
 
-void MantidHelpWindow::warning(QString msg)
-{
+void MantidHelpWindow::warning(QString msg) {
   g_log.warning(msg.toStdString());
 }
 
diff --git a/MantidQt/MantidWidgets/src/MessageDisplay.cpp b/MantidQt/MantidWidgets/src/MessageDisplay.cpp
index f8e34491474ed23ca48d7b20b140b1f0ab921b8c..12232d124b2251816e31a2d1334b91761f7254f2 100644
--- a/MantidQt/MantidWidgets/src/MessageDisplay.cpp
+++ b/MantidQt/MantidWidgets/src/MessageDisplay.cpp
@@ -102,8 +102,7 @@ void MessageDisplay::attachLoggingChannel() {
 
   QSettings settings;
   int priority = settings.value(QString::fromStdString(m_FilterChannelName),
-                                Message::Priority::PRIO_NOTICE)
-                     .toInt();
+                                Message::Priority::PRIO_NOTICE).toInt();
 
   auto &configService = Mantid::Kernel::ConfigService::Instance();
   configService.registerLoggingFilterChannel(m_FilterChannelName,
diff --git a/MantidQt/MantidWidgets/src/MultifitSetupDialog.cpp b/MantidQt/MantidWidgets/src/MultifitSetupDialog.cpp
index 6fcb96091c83abada78007a422a59ddab383924a..a8d24f607e8873c22835e0f924af9e06693797ef 100644
--- a/MantidQt/MantidWidgets/src/MultifitSetupDialog.cpp
+++ b/MantidQt/MantidWidgets/src/MultifitSetupDialog.cpp
@@ -13,71 +13,59 @@
 // Public member functions
 //---------------------------------------
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /// Constructor
 /// @param fitBrowser
-MultifitSetupDialog::MultifitSetupDialog(FitPropertyBrowser* fitBrowser) :
-QDialog(fitBrowser),m_fitBrowser(fitBrowser)
-{
+MultifitSetupDialog::MultifitSetupDialog(FitPropertyBrowser *fitBrowser)
+    : QDialog(fitBrowser), m_fitBrowser(fitBrowser) {
   ui.setupUi(this);
   auto f = m_fitBrowser->compositeFunction()->getFunction(0);
-  if (!f)
-  {
-    throw std::runtime_error("IFitFunction expected but func function of another type");
+  if (!f) {
+    throw std::runtime_error(
+        "IFitFunction expected but func function of another type");
   }
-  QAbstractItemModel* model = ui.paramTable->model();
-  for(size_t i = 0; i < f->nParams(); ++i)
-  {
+  QAbstractItemModel *model = ui.paramTable->model();
+  for (size_t i = 0; i < f->nParams(); ++i) {
     int j = static_cast<int>(i);
     ui.paramTable->insertRow(ui.paramTable->rowCount());
-    model->setData(model->index(j,0),QString::fromStdString(f->parameterName(i)));
-    ui.paramTable->item(j,0)->setFlags(0);
-    model->setData(model->index(j,1),"");
-    ui.paramTable->item(j,1)->setCheckState(Qt::Unchecked);
+    model->setData(model->index(j, 0),
+                   QString::fromStdString(f->parameterName(i)));
+    ui.paramTable->item(j, 0)->setFlags(0);
+    model->setData(model->index(j, 1), "");
+    ui.paramTable->item(j, 1)->setCheckState(Qt::Unchecked);
   }
   ui.paramTable->resizeColumnToContents(0);
-  connect(ui.paramTable,SIGNAL(cellChanged(int,int)),this,SLOT(cellChanged(int,int)));
+  connect(ui.paramTable, SIGNAL(cellChanged(int, int)), this,
+          SLOT(cellChanged(int, int)));
 }
 
 /// Setup the function and close dialog
-void MultifitSetupDialog::accept()
-{
+void MultifitSetupDialog::accept() {
   m_ties.clear();
-  for(int i = 0; i < ui.paramTable->rowCount(); ++i)
-  {
-    if (ui.paramTable->item(i,1)->checkState() == Qt::Checked)
-    {
-      m_ties << ui.paramTable->item(i,1)->text();
-    }
-    else
-    {
+  for (int i = 0; i < ui.paramTable->rowCount(); ++i) {
+    if (ui.paramTable->item(i, 1)->checkState() == Qt::Checked) {
+      m_ties << ui.paramTable->item(i, 1)->text();
+    } else {
       m_ties << "";
     }
   }
   close();
 }
 
-void MultifitSetupDialog::cellChanged(int row,int col)
-{
-  if (col == 1)
-  {
-    bool isChecked = ui.paramTable->item(row,col)->checkState() == Qt::Checked;
-    QString text = ui.paramTable->item(row,col)->text();
+void MultifitSetupDialog::cellChanged(int row, int col) {
+  if (col == 1) {
+    bool isChecked = ui.paramTable->item(row, col)->checkState() == Qt::Checked;
+    QString text = ui.paramTable->item(row, col)->text();
     // toggle global/local
-    if (isChecked && text.isEmpty())
-    {
-      ui.paramTable->item(row,col)->setText(QString::fromStdString(m_fitBrowser->compositeFunction()->parameterName(row)));
-    }
-    else if (!isChecked)
-    {
-      ui.paramTable->item(row,col)->setText("");
+    if (isChecked && text.isEmpty()) {
+      ui.paramTable->item(row, col)->setText(QString::fromStdString(
+          m_fitBrowser->compositeFunction()->parameterName(row)));
+    } else if (!isChecked) {
+      ui.paramTable->item(row, col)->setText("");
     }
   }
 }
-
 }
 }
diff --git a/MantidQt/MantidWidgets/src/MuonSequentialFitDialog.cpp b/MantidQt/MantidWidgets/src/MuonSequentialFitDialog.cpp
index 285c5be7fccea90df8cd0cc7540379eabfc22a79..65779ba957da1a92cc1e3ebb0fd89d0faa8cda88 100644
--- a/MantidQt/MantidWidgets/src/MuonSequentialFitDialog.cpp
+++ b/MantidQt/MantidWidgets/src/MuonSequentialFitDialog.cpp
@@ -467,7 +467,8 @@ void MuonSequentialFitDialog::continueFit() {
       fit->setProperty("InputWorkspace", ws);
       fit->setProperty("Output", wsBaseName);
 
-      // We should have one spectrum only in the workspace, so use the first one.
+      // We should have one spectrum only in the workspace, so use the first
+      // one.
       fit->setProperty("WorkspaceIndex", 0);
 
       // Various properties from the fit prop. browser
diff --git a/MantidQt/MantidWidgets/src/PeakPicker.cpp b/MantidQt/MantidWidgets/src/PeakPicker.cpp
index 104ac281f328ea696ead32a0d102e47c49fb9084..e79ab6360ffe4ec86358af202a3a426a75fb6ab0 100644
--- a/MantidQt/MantidWidgets/src/PeakPicker.cpp
+++ b/MantidQt/MantidWidgets/src/PeakPicker.cpp
@@ -8,10 +8,8 @@
 
 #include "MantidAPI/FunctionFactory.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 const double PeakPicker::DRAG_SENSITIVITY = 5.0;
 const Qt::CursorShape PeakPicker::DEFAULT_CURSOR = Qt::PointingHandCursor;
 
@@ -19,123 +17,114 @@ const Qt::CursorShape PeakPicker::DEFAULT_CURSOR = Qt::PointingHandCursor;
  * @param plot :: A plot this peak picker should operate on
  * @param color :: Peak picker color
  */
-PeakPicker::PeakPicker(QwtPlot* plot, QColor color)
-  : QwtPlotPicker(plot->canvas()), QwtPlotItem(), m_plot(plot),
-    m_basePen(color, 0, Qt::SolidLine), m_widthPen(color, 0, Qt::DashLine),
-    m_isMoving(false), m_isResizing(false), m_peak()
-{
+PeakPicker::PeakPicker(QwtPlot *plot, QColor color)
+    : QwtPlotPicker(plot->canvas()), QwtPlotItem(), m_plot(plot),
+      m_basePen(color, 0, Qt::SolidLine), m_widthPen(color, 0, Qt::DashLine),
+      m_isMoving(false), m_isResizing(false), m_peak() {
   attach(plot);
   plot->canvas()->setCursor(DEFAULT_CURSOR);
 }
 
-bool PeakPicker::eventFilter(QObject* object, QEvent* event)
-{
+bool PeakPicker::eventFilter(QObject *object, QEvent *event) {
   UNUSED_ARG(object);
 
-  if (!m_peak)
-  {
+  if (!m_peak) {
     return false; // Peak not set - nothing to do
   }
 
-  switch(event->type())
-  {
-    case QEvent::MouseButtonPress:
-    {
-      auto mouseEvent = static_cast<QMouseEvent*>(event);
-      Qt::KeyboardModifiers mod = mouseEvent->modifiers();
-      QPoint p = mouseEvent->pos();
-
-      // Widget coordinates of left and right width bars
-      int xLeft = m_plot->transform(QwtPlot::xBottom, m_peak->centre() - (m_peak->fwhm() / 2.0));
-      int xRight = m_plot->transform(QwtPlot::xBottom, m_peak->centre() + (m_peak->fwhm() / 2.0));
-
-      // If clicked with Ctrl pressed, or close enough to one of the width bars - start resizing
-      if (mod.testFlag(Qt::ControlModifier) || std::abs(p.x() - xLeft) < DRAG_SENSITIVITY ||
-          std::abs(p.x() - xRight) < DRAG_SENSITIVITY)
-      {
-        m_isResizing = true;
-        m_plot->canvas()->setCursor(Qt::SizeHorCursor);
-      }
-
-      // Widget point of the peak tip
-      QPoint peakTip;
-      peakTip.setX(m_plot->transform(QwtPlot::xBottom, m_peak->centre()));
-      peakTip.setY(m_plot->transform(QwtPlot::yLeft, m_peak->height()));
-
-      // If clicked with Shift pressed or close enough to peak tip - start moving
-      if (mod.testFlag(Qt::ShiftModifier) || QLineF(p, peakTip).length() < DRAG_SENSITIVITY)
-      {
-        m_isMoving = true;
-        m_plot->canvas()->setCursor(Qt::SizeAllCursor);
-      }
-
-      // XXX: fall through intentionally, so that the user instantly sees a new PeakPicker
-      //      position when starts dragging
+  switch (event->type()) {
+  case QEvent::MouseButtonPress: {
+    auto mouseEvent = static_cast<QMouseEvent *>(event);
+    Qt::KeyboardModifiers mod = mouseEvent->modifiers();
+    QPoint p = mouseEvent->pos();
+
+    // Widget coordinates of left and right width bars
+    int xLeft = m_plot->transform(QwtPlot::xBottom,
+                                  m_peak->centre() - (m_peak->fwhm() / 2.0));
+    int xRight = m_plot->transform(QwtPlot::xBottom,
+                                   m_peak->centre() + (m_peak->fwhm() / 2.0));
+
+    // If clicked with Ctrl pressed, or close enough to one of the width bars -
+    // start resizing
+    if (mod.testFlag(Qt::ControlModifier) ||
+        std::abs(p.x() - xLeft) < DRAG_SENSITIVITY ||
+        std::abs(p.x() - xRight) < DRAG_SENSITIVITY) {
+      m_isResizing = true;
+      m_plot->canvas()->setCursor(Qt::SizeHorCursor);
     }
-    case QEvent::MouseMove:
-    {
-      QPoint p = static_cast<QMouseEvent*>(event)->pos();
-
-      // Move, if moving in process
-      if (m_isMoving)
-      {
-        m_peak->setCentre(m_plot->invTransform(QwtPlot::xBottom, p.x()));
-        m_peak->setHeight(m_plot->invTransform(QwtPlot::yLeft, p.y()));
-      }
-
-      // Resize, if resizing in process
-      if (m_isResizing)
-      {
-        m_peak->setFwhm(fabs(m_peak->centre() - m_plot->invTransform(QwtPlot::xBottom, p.x())) * 2);
-      }
-
-      // If moving or resizing in process - update the plot and accept the event
-      if (m_isResizing || m_isMoving)
-      {
-        m_plot->replot();
-        emit changed();
-        return true;
-      }
-
-      break;
+
+    // Widget point of the peak tip
+    QPoint peakTip;
+    peakTip.setX(m_plot->transform(QwtPlot::xBottom, m_peak->centre()));
+    peakTip.setY(m_plot->transform(QwtPlot::yLeft, m_peak->height()));
+
+    // If clicked with Shift pressed or close enough to peak tip - start moving
+    if (mod.testFlag(Qt::ShiftModifier) ||
+        QLineF(p, peakTip).length() < DRAG_SENSITIVITY) {
+      m_isMoving = true;
+      m_plot->canvas()->setCursor(Qt::SizeAllCursor);
+    }
+
+    // XXX: fall through intentionally, so that the user instantly sees a new
+    // PeakPicker
+    //      position when starts dragging
+  }
+  case QEvent::MouseMove: {
+    QPoint p = static_cast<QMouseEvent *>(event)->pos();
+
+    // Move, if moving in process
+    if (m_isMoving) {
+      m_peak->setCentre(m_plot->invTransform(QwtPlot::xBottom, p.x()));
+      m_peak->setHeight(m_plot->invTransform(QwtPlot::yLeft, p.y()));
+    }
+
+    // Resize, if resizing in process
+    if (m_isResizing) {
+      m_peak->setFwhm(fabs(m_peak->centre() -
+                           m_plot->invTransform(QwtPlot::xBottom, p.x())) *
+                      2);
     }
-    case QEvent::MouseButtonRelease:
-    {
-      // If are moving or resizing - stop
-      if (m_isMoving || m_isResizing)
-      {
-        m_isMoving = m_isResizing = false;
-        m_plot->canvas()->setCursor(DEFAULT_CURSOR);
-        return true;
-      }
-
-      break;
+
+    // If moving or resizing in process - update the plot and accept the event
+    if (m_isResizing || m_isMoving) {
+      m_plot->replot();
+      emit changed();
+      return true;
+    }
+
+    break;
+  }
+  case QEvent::MouseButtonRelease: {
+    // If are moving or resizing - stop
+    if (m_isMoving || m_isResizing) {
+      m_isMoving = m_isResizing = false;
+      m_plot->canvas()->setCursor(DEFAULT_CURSOR);
+      return true;
     }
-    default:
-      break;
+
+    break;
+  }
+  default:
+    break;
   }
 
   return false;
 }
 
-Mantid::API::IPeakFunction_const_sptr PeakPicker::peak() const
-{
+Mantid::API::IPeakFunction_const_sptr PeakPicker::peak() const {
   return m_peak;
 }
 
-void PeakPicker::setPeak(const Mantid::API::IPeakFunction_const_sptr& peak)
-{
+void PeakPicker::setPeak(const Mantid::API::IPeakFunction_const_sptr &peak) {
   // Copy the function
   m_peak = boost::dynamic_pointer_cast<Mantid::API::IPeakFunction>(
-        Mantid::API::FunctionFactory::Instance().createInitialized(peak->asString()));
+      Mantid::API::FunctionFactory::Instance().createInitialized(
+          peak->asString()));
 }
 
-
-void PeakPicker::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScaleMap& yMap,
-                      const QRect& canvasRect) const
-{
-  if (!m_peak)
-  {
+void PeakPicker::draw(QPainter *painter, const QwtScaleMap &xMap,
+                      const QwtScaleMap &yMap, const QRect &canvasRect) const {
+  if (!m_peak) {
     return; // Peak not set - nothing to do
   }
 
@@ -162,7 +151,6 @@ void PeakPicker::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScale
   // Draw width lines
   QwtPainter::drawLine(painter, xMin, yBottom, xMin, yTop);
   QwtPainter::drawLine(painter, xMax, yBottom, xMax, yTop);
-
 }
 
 } // namespace MantidWidgets
diff --git a/MantidQt/MantidWidgets/src/PeriodicTableWidget.cpp b/MantidQt/MantidWidgets/src/PeriodicTableWidget.cpp
index 8f35fb59816044ee9f733a2e92289b7a9df4dddb..6b10c0673560ab11f322546640218765db923440 100644
--- a/MantidQt/MantidWidgets/src/PeriodicTableWidget.cpp
+++ b/MantidQt/MantidWidgets/src/PeriodicTableWidget.cpp
@@ -10,16 +10,15 @@ PeriodicTableWidget::PeriodicTableWidget(QWidget *parent) : QWidget(parent) {
   populateGroupVectors();
   populateAllButtonsVector();
   ColourElements();
-  ///Hide the legend by default
+  /// Hide the legend by default
   ui.Groups->setVisible(false);
 }
 
 // slot for showing group legend dependant on state of radioButton
 void PeriodicTableWidget::showGroupLegend(bool checked) {
-    if (checked) {
+  if (checked) {
     ui.Groups->setVisible(true);
-    }
-    else{
+  } else {
     ui.Groups->setVisible(false);
   }
 }
@@ -127,7 +126,6 @@ void PeriodicTableWidget::ColourUnknownProperties(
   }
 }
 
-
 void PeriodicTableWidget::enableButtonByName(QString elementStr) {
   for (auto vector_i = AllElementButtons.begin();
        vector_i != AllElementButtons.end(); vector_i++) {
@@ -159,12 +157,12 @@ void PeriodicTableWidget::disableAllElementButtons() {
   disableButtons(TransitionMetals);
   disableButtons(UnknownProperties);
 }
-void PeriodicTableWidget::ColourButton(QPushButton *element, QString colourStr) {
+void PeriodicTableWidget::ColourButton(QPushButton *element,
+                                       QString colourStr) {
   element->setStyleSheet(
       "QPushButton{border:1px solid rgb(0, 0, 0); " + colourStr + ";}" +
       "QPushButton:checked{ background-color:rgb(175,255,255)}" +
-      "QPushButton:!enabled{background-color: rgb(204,204,204);" +
-      "}");
+      "QPushButton:!enabled{background-color: rgb(204,204,204);" + "}");
 }
 
 QString
@@ -205,9 +203,7 @@ QString PeriodicTableWidget::getAllCheckedElementsStr() {
   return allCheckedElementsStr;
 }
 
-QString PeriodicTableWidget::getValue() {
-    return getAllCheckedElementsStr();
-}
+QString PeriodicTableWidget::getValue() { return getAllCheckedElementsStr(); }
 
 void PeriodicTableWidget::disableButtons(
     QVector<QPushButton *> buttonsToDisable) {
diff --git a/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/MantidQt/MantidWidgets/src/PreviewPlot.cpp
index c671705fd1ebe371633f2a2265720463eb6d845e..99675bf740115e25713d6e7f0da81ccf16cf0b8e 100644
--- a/MantidQt/MantidWidgets/src/PreviewPlot.cpp
+++ b/MantidQt/MantidWidgets/src/PreviewPlot.cpp
@@ -242,8 +242,7 @@ QPair<double, double> PreviewPlot::getCurveRange(const QString &curveName) {
  */
 void PreviewPlot::addSpectrum(const QString &curveName,
                               const MatrixWorkspace_sptr ws,
-                              const size_t wsIndex,
-                              const QColor &curveColour) {
+                              const size_t wsIndex, const QColor &curveColour) {
   if (curveName.isEmpty()) {
     g_log.warning("Cannot plot with empty curve name");
     return;
@@ -299,8 +298,7 @@ void PreviewPlot::addSpectrum(const QString &curveName,
  * @param curveColour Colour of curve to plot
  */
 void PreviewPlot::addSpectrum(const QString &curveName, const QString &wsName,
-                              const size_t wsIndex,
-                              const QColor &curveColour) {
+                              const size_t wsIndex, const QColor &curveColour) {
   if (wsName.isEmpty()) {
     g_log.error("Cannot plot with empty workspace name");
     return;
@@ -355,7 +353,7 @@ void PreviewPlot::removeSpectrum(const QString &curveName) {
     removeCurve(m_curves[curveName].errorCurve);
     m_uiForm.loLegend->removeWidget(m_curves[curveName].label);
     m_errorBarOptionCache[curveName] =
-    m_curves[curveName].showErrorsAction->isChecked();
+        m_curves[curveName].showErrorsAction->isChecked();
     m_showErrorsMenu->removeAction(m_curves[curveName].showErrorsAction);
     delete m_curves[curveName].showErrorsAction;
     delete m_curves[curveName].label;
@@ -597,8 +595,8 @@ void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) {
  *
  * @param pNf Poco notification
  */
-void
-PreviewPlot::handleReplaceEvent(WorkspaceAfterReplaceNotification_ptr pNf) {
+void PreviewPlot::handleReplaceEvent(
+    WorkspaceAfterReplaceNotification_ptr pNf) {
   MatrixWorkspace_sptr ws =
       boost::dynamic_pointer_cast<MatrixWorkspace>(pNf->object());
 
@@ -666,11 +664,10 @@ void PreviewPlot::addCurve(PlotCurveConfiguration &curveConfig,
 
   // Create the Qwt data
   std::vector<double> X;
-  if (ws->isHistogramData()){
+  if (ws->isHistogramData()) {
     Mantid::Kernel::VectorHelper::convertToBinCentre(ws->readX(wsIndex), X);
-  }
-  else{
-    X=ws->readX(wsIndex);
+  } else {
+    X = ws->readX(wsIndex);
   }
   QwtArray<double> dataX = QVector<double>::fromStdVector(X);
   QwtArray<double> dataY = QVector<double>::fromStdVector(wsDataY);
diff --git a/MantidQt/MantidWidgets/src/ProcessingAlgoWidget.cpp b/MantidQt/MantidWidgets/src/ProcessingAlgoWidget.cpp
index b64b81bbba4d4ce9813659a822178c3f4c25add8..f7b08ce64b7621d3bb0432b0026ad3ebac7e76f6 100644
--- a/MantidQt/MantidWidgets/src/ProcessingAlgoWidget.cpp
+++ b/MantidQt/MantidWidgets/src/ProcessingAlgoWidget.cpp
@@ -10,18 +10,14 @@
 using Mantid::API::Algorithm_sptr;
 using Mantid::API::AlgorithmManager;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 //----------------------
 // Public member functions
 //----------------------
-///Constructor
-ProcessingAlgoWidget::ProcessingAlgoWidget(QWidget *parent)
-: QWidget(parent)
-{
+/// Constructor
+ProcessingAlgoWidget::ProcessingAlgoWidget(QWidget *parent) : QWidget(parent) {
   ui.setupUi(this);
 
   // Load all available algorithms
@@ -31,14 +27,17 @@ ProcessingAlgoWidget::ProcessingAlgoWidget(QWidget *parent)
   ui.editor->setLexer(new QsciLexerPython);
 
   // Layout tweak
-  QList<int> sizes; sizes.push_back(300); sizes.push_back(1000);
+  QList<int> sizes;
+  sizes.push_back(300);
+  sizes.push_back(1000);
   ui.splitter->setSizes(sizes);
   ui.splitter->setStretchFactor(0, 0);
   ui.splitter->setStretchFactor(1, 0);
 
   //=========== SLOTS =============
-  connect(ui.algoSelector, SIGNAL(algorithmSelectionChanged(const QString &, int)),
-      this, SLOT(changeAlgorithm()));
+  connect(ui.algoSelector,
+          SIGNAL(algorithmSelectionChanged(const QString &, int)), this,
+          SLOT(changeAlgorithm()));
 
   connect(ui.btnSave, SIGNAL(clicked()), this, SLOT(btnSaveClicked()));
   connect(ui.btnLoad, SIGNAL(clicked()), this, SLOT(btnLoadClicked()));
@@ -48,23 +47,15 @@ ProcessingAlgoWidget::ProcessingAlgoWidget(QWidget *parent)
 
 //------------------------------------------------------------------------------
 /// Destructor
-ProcessingAlgoWidget::~ProcessingAlgoWidget()
-{
-  saveSettings();
-}
+ProcessingAlgoWidget::~ProcessingAlgoWidget() { saveSettings(); }
 
 //------------------------------------------------------------------------------
 /** Save the inputs to algorithm history */
-void ProcessingAlgoWidget::saveInput()
-{
-  ui.algoProperties->saveInput();
-}
-
+void ProcessingAlgoWidget::saveInput() { ui.algoProperties->saveInput(); }
 
 //------------------------------------------------------------------------------------
 /** Load QSettings from .ini-type files */
-void ProcessingAlgoWidget::loadSettings()
-{
+void ProcessingAlgoWidget::loadSettings() {
   QSettings settings;
   settings.beginGroup("Mantid/ProcessingAlgoWidget");
   m_lastFile = settings.value("LastFile", QString()).toString();
@@ -73,50 +64,46 @@ void ProcessingAlgoWidget::loadSettings()
 
 //------------------------------------------------------------------------------------
 /** Save settings for next time. */
-void ProcessingAlgoWidget::saveSettings()
-{
+void ProcessingAlgoWidget::saveSettings() {
   QSettings settings;
   settings.beginGroup("Mantid/ProcessingAlgoWidget");
   settings.setValue("LastFile", m_lastFile);
   settings.endGroup();
 }
 
-
 //------------------------------------------------------------------------------
 /** Slot called when the save button is clicked */
-void ProcessingAlgoWidget::btnSaveClicked()
-{
+void ProcessingAlgoWidget::btnSaveClicked() {
   // Save to a .py file
-  QString fileselection = MantidQt::API::FileDialogHandler::getSaveFileName(this, "Save a Python Script",
-      QFileInfo(m_lastFile).absoluteFilePath(), "Python scripts (*.py);;All files (*)");
-  if (!fileselection.isEmpty())
-  {
+  QString fileselection = MantidQt::API::FileDialogHandler::getSaveFileName(
+      this, "Save a Python Script", QFileInfo(m_lastFile).absoluteFilePath(),
+      "Python scripts (*.py);;All files (*)");
+  if (!fileselection.isEmpty()) {
     m_lastFile = fileselection;
     std::ofstream file;
-    file.exceptions (std::ifstream::failbit | std::ifstream::badbit );
-    try
-    {
+    file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+    try {
       file.open(fileselection.toStdString().c_str());
       file << ui.editor->text().toStdString();
       file.close();
-    }
-    catch (std::ifstream::failure & e)
-    {
-      QMessageBox::critical(this, "Exception saving file " + m_lastFile,
-          QString("The file could not be saved due to the following exception:\n") + QString(e.what()));
+    } catch (std::ifstream::failure &e) {
+      QMessageBox::critical(
+          this, "Exception saving file " + m_lastFile,
+          QString(
+              "The file could not be saved due to the following exception:\n") +
+              QString(e.what()));
     }
   }
 }
 
 //------------------------------------------------------------------------------
 /** Slot called when the Load button is clicked */
-void ProcessingAlgoWidget::btnLoadClicked()
-{
+void ProcessingAlgoWidget::btnLoadClicked() {
   // Load a .py file
-  QString fileselection = QFileDialog::getOpenFileName(this, "Load a Python Script",
-      QFileInfo(m_lastFile).absoluteFilePath(), "Python scripts (*.py);;All files (*)");
-  if (!fileselection.isEmpty())
-  {
+  QString fileselection = QFileDialog::getOpenFileName(
+      this, "Load a Python Script", QFileInfo(m_lastFile).absoluteFilePath(),
+      "Python scripts (*.py);;All files (*)");
+  if (!fileselection.isEmpty()) {
     m_lastFile = fileselection;
     std::ifstream file(fileselection.toStdString().c_str());
     std::stringstream buffer;
@@ -126,21 +113,16 @@ void ProcessingAlgoWidget::btnLoadClicked()
   }
 }
 
-
 //------------------------------------------------------------------------------
 /** Slot called when the algorithm selected changes
  */
-void ProcessingAlgoWidget::changeAlgorithm()
-{
+void ProcessingAlgoWidget::changeAlgorithm() {
   auto alg = ui.algoSelector->getSelectedAlgorithm();
-  try
-  {
+  try {
     m_alg = AlgorithmManager::Instance().createUnmanaged(alg.name.toStdString(),
                                                          alg.version);
     m_alg->initialize();
-  }
-  catch (std::runtime_error &)
-  {
+  } catch (std::runtime_error &) {
     // Ignore when the m_algorithm is not found
     m_alg = Algorithm_sptr();
 
@@ -166,8 +148,7 @@ void ProcessingAlgoWidget::changeAlgorithm()
  *
  * @param algo :: name of the algorithm
  */
-void ProcessingAlgoWidget::setSelectedAlgorithm(QString algo)
-{
+void ProcessingAlgoWidget::setSelectedAlgorithm(QString algo) {
   ui.algoSelector->setSelectedAlgorithm(algo);
   this->changeAlgorithm();
 }
@@ -179,5 +160,5 @@ void ProcessingAlgoWidget::setScriptText(QString text) {
   ui.editor->setText(text);
 }
 
-}//namespace
-}//namespace
+} // namespace
+} // namespace
diff --git a/MantidQt/MantidWidgets/src/PropertyHandler.cpp b/MantidQt/MantidWidgets/src/PropertyHandler.cpp
index 1bbb043e0a2e29edca22addc3dbe9c845ab8108e..370f86eec316334561034732e27eeb27282ce247 100644
--- a/MantidQt/MantidWidgets/src/PropertyHandler.cpp
+++ b/MantidQt/MantidWidgets/src/PropertyHandler.cpp
@@ -1097,11 +1097,10 @@ void PropertyHandler::removeTie(const QString &parName) {
  Create a simple estimate of the full width half maximum
  @returns and estimate of the peak width, or 0 if an error occurs
 */
-double PropertyHandler::EstimateFwhm() const
-{
+double PropertyHandler::EstimateFwhm() const {
   double fwhm = 0.;
   auto ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(
-    m_browser->getWorkspace());
+      m_browser->getWorkspace());
   if (ws) {
     size_t wi = m_browser->workspaceIndex();
     const Mantid::MantidVec &X = ws->readX(wi);
@@ -1109,19 +1108,17 @@ double PropertyHandler::EstimateFwhm() const
     size_t n = Y.size() - 1;
     if (m_ci < 0 || m_ci > static_cast<int>(n)) {
       fwhm = 0.;
-    }
-    else {
-      double halfHeight = ((Y[m_ci] - m_base)/2.) + m_base;
-      //walk to the right
+    } else {
+      double halfHeight = ((Y[m_ci] - m_base) / 2.) + m_base;
+      // walk to the right
       size_t rightHwhmIndex = m_ci;
       while (rightHwhmIndex < n) {
-        if (Y[rightHwhmIndex++] <= halfHeight)
-        {
+        if (Y[rightHwhmIndex++] <= halfHeight) {
           break;
         }
       }
 
-      //walk to the left
+      // walk to the left
       size_t leftHwhmIndex = m_ci;
       while (leftHwhmIndex > 0) {
         if (Y[leftHwhmIndex--] <= halfHeight) {
@@ -1131,14 +1128,13 @@ double PropertyHandler::EstimateFwhm() const
 
       fwhm = fabs(X[rightHwhmIndex] - X[leftHwhmIndex]);
 
-      //apply a maximum limitation if larger than the fitting region
+      // apply a maximum limitation if larger than the fitting region
       double fitRange = m_browser->endX() - m_browser->startX();
-      if (fwhm > fitRange)
-      {
-        //set to 10% of fitting region
-        fwhm = fitRange*0.1;
+      if (fwhm > fitRange) {
+        // set to 10% of fitting region
+        fwhm = fitRange * 0.1;
       }
-    }  
+    }
   }
   return fwhm;
 }
diff --git a/MantidQt/MantidWidgets/src/RangeSelector.cpp b/MantidQt/MantidWidgets/src/RangeSelector.cpp
index 9639bf98ed0a976f3ad0e88e01e7e669287698ba..20e4a17d50173a32c0875fbb4052d83cbc155c6a 100644
--- a/MantidQt/MantidWidgets/src/RangeSelector.cpp
+++ b/MantidQt/MantidWidgets/src/RangeSelector.cpp
@@ -12,23 +12,19 @@ using namespace MantidQt::MantidWidgets;
 RangeSelector::RangeSelector(QwtPlot *plot, SelectType type, bool visible,
                              bool infoOnly)
     : QwtPlotPicker(plot->canvas()), m_type(type), m_min(0.0), m_max(0.0),
-      m_lower(0.0), m_higher(0.0), m_mrkMin(NULL), m_mrkMax(NULL),
-      m_plot(plot), m_canvas(plot->canvas()),
-      m_minChanging(false), m_maxChanging(false),
-      m_infoOnly(infoOnly), m_visible(visible),
-      m_pen(NULL), m_movCursor() {
+      m_lower(0.0), m_higher(0.0), m_mrkMin(NULL), m_mrkMax(NULL), m_plot(plot),
+      m_canvas(plot->canvas()), m_minChanging(false), m_maxChanging(false),
+      m_infoOnly(infoOnly), m_visible(visible), m_pen(NULL), m_movCursor() {
   init();
 }
 
 RangeSelector::RangeSelector(PreviewPlot *plot, SelectType type, bool visible,
                              bool infoOnly)
     : QwtPlotPicker(plot->m_uiForm.plot->canvas()), m_type(type), m_min(0.0),
-      m_max(0.0), m_lower(0.0), m_higher(0.0),
-      m_mrkMin(NULL), m_mrkMax(NULL),
+      m_max(0.0), m_lower(0.0), m_higher(0.0), m_mrkMin(NULL), m_mrkMax(NULL),
       m_plot(plot->m_uiForm.plot), m_canvas(plot->m_uiForm.plot->canvas()),
-      m_minChanging(false), m_maxChanging(false),
-      m_infoOnly(infoOnly), m_visible(visible),
-      m_pen(NULL), m_movCursor() {
+      m_minChanging(false), m_maxChanging(false), m_infoOnly(infoOnly),
+      m_visible(visible), m_pen(NULL), m_movCursor() {
   init();
 }
 
@@ -377,9 +373,11 @@ void RangeSelector::setMax(double val) {
 }
 
 /**
- * @brief Find out if user is moving the line marking the position of the minimum
+ * @brief Find out if user is moving the line marking the position of the
+ * minimum
  * @param x new candidate position for the minimum
- * @param xPlusdx safety boundary indicating we are closer to the minimum than to the maximum
+ * @param xPlusdx safety boundary indicating we are closer to the minimum than
+ * to the maximum
  * @return
  */
 bool RangeSelector::changingMin(double x, double xPlusdx) {
@@ -387,9 +385,11 @@ bool RangeSelector::changingMin(double x, double xPlusdx) {
 }
 
 /**
- * @brief Find out if user is moving the line marking the position of the maximum
+ * @brief Find out if user is moving the line marking the position of the
+ * maximum
  * @param x new candidate position for the maximum
- * @param xPlusdx safety boundary indicating we are closer to the maximum than to the minimum
+ * @param xPlusdx safety boundary indicating we are closer to the maximum than
+ * to the minimum
  * @return
  */
 bool RangeSelector::changingMax(double x, double xPlusdx) {
@@ -424,7 +424,6 @@ void RangeSelector::verify() {
  * @param x
  * @return true if position within the allowed range
  */
-bool RangeSelector::inRange(double x)
-{
+bool RangeSelector::inRange(double x) {
   return (x >= m_lower && x <= m_higher);
 }
diff --git a/MantidQt/MantidWidgets/src/RenameParDialog.cpp b/MantidQt/MantidWidgets/src/RenameParDialog.cpp
index 2435c60292a604e4233978aca69a75130814d3ab..f8ee18a9fc1cca385014c107af843a13a6a8a3e6 100644
--- a/MantidQt/MantidWidgets/src/RenameParDialog.cpp
+++ b/MantidQt/MantidWidgets/src/RenameParDialog.cpp
@@ -10,44 +10,39 @@ using namespace MantidQt::MantidWidgets;
  * @param new_params Renamed parameters
  * @param parent The parent widget for the dialog
  */
-RenameParDialog::RenameParDialog(
-        const std::vector<std::string>& old_params,
-        const std::vector<std::string>& new_params,
-        QWidget *parent)
-:QDialog(parent),
-m_old_params(old_params),
-m_new_params(new_params)
-{
+RenameParDialog::RenameParDialog(const std::vector<std::string> &old_params,
+                                 const std::vector<std::string> &new_params,
+                                 QWidget *parent)
+    : QDialog(parent), m_old_params(old_params), m_new_params(new_params) {
   m_uiForm.setupUi(this);
-  QAbstractItemModel* model = m_uiForm.tableWidget->model();
+  QAbstractItemModel *model = m_uiForm.tableWidget->model();
   int nparams(static_cast<int>(new_params.size()));
   model->insertRows(0, nparams);
-  for(int row = 0; row < nparams; ++row)
-  {
+  for (int row = 0; row < nparams; ++row) {
     QString par = QString::fromStdString(new_params[row]);
-    model->setData(model->index(row,0),par);
-    model->setData(model->index(row,1),par);
+    model->setData(model->index(row, 0), par);
+    model->setData(model->index(row, 1), par);
   }
-  connect(m_uiForm.btnRename,SIGNAL(clicked()),this,SLOT(accept()));
-  connect(m_uiForm.btnCancel,SIGNAL(clicked()),this,SLOT(reject()));
-  connect(m_uiForm.rbAddIndex,SIGNAL(toggled(bool)),this,SLOT(uniqueIndexedNames(bool)));
-  connect(m_uiForm.rbDoNot,SIGNAL(toggled(bool)),this,SLOT(doNotRename(bool)));
+  connect(m_uiForm.btnRename, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(m_uiForm.btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(m_uiForm.rbAddIndex, SIGNAL(toggled(bool)), this,
+          SLOT(uniqueIndexedNames(bool)));
+  connect(m_uiForm.rbDoNot, SIGNAL(toggled(bool)), this,
+          SLOT(doNotRename(bool)));
 }
 
 /**
- * Checks whether a name is unique. The name is compared to the names in 
+ * Checks whether a name is unique. The name is compared to the names in
  * m_old_names and in column #1 of the table widget
  */
-bool RenameParDialog::isUnique(const QString& name)const
-{
-  std::vector<std::string>::const_iterator it = 
-    std::find(m_old_params.begin(),m_old_params.end(),name.toStdString());
-  if (it != m_old_params.end()) return false;
-  QAbstractItemModel* model = m_uiForm.tableWidget->model();
-  for(int row=0;row< m_uiForm.tableWidget->rowCount(); ++row)
-  {
-    if (model->data(model->index(row,1)).toString() == name) 
-    {
+bool RenameParDialog::isUnique(const QString &name) const {
+  std::vector<std::string>::const_iterator it =
+      std::find(m_old_params.begin(), m_old_params.end(), name.toStdString());
+  if (it != m_old_params.end())
+    return false;
+  QAbstractItemModel *model = m_uiForm.tableWidget->model();
+  for (int row = 0; row < m_uiForm.tableWidget->rowCount(); ++row) {
+    if (model->data(model->index(row, 1)).toString() == name) {
       return false;
     }
   }
@@ -55,39 +50,33 @@ bool RenameParDialog::isUnique(const QString& name)const
 }
 
 /**
- * Adds a suffix to the unput parameter name in the form: _n where n is a number.
+ * Adds a suffix to the unput parameter name in the form: _n where n is a
+ * number.
  * The method ensures that the new name is unique
  * @param name :: The name to rename
  */
-QString RenameParDialog::makeUniqueIndexedName(const QString& name)
-{
+QString RenameParDialog::makeUniqueIndexedName(const QString &name) {
   int index = 1;
   QString base;
   int i_ = name.indexOf('_');
-  if (i_ >= 0)
-  {
-    QString old_index = name.mid(i_+1);
+  if (i_ >= 0) {
+    QString old_index = name.mid(i_ + 1);
     bool ok;
     int n = old_index.toInt(&ok);
     // e.g. name = a_3
-    if (ok)
-    {
+    if (ok) {
       index = n + 1;
-      base = name.mid(0,i_);
+      base = name.mid(0, i_);
     }
     // e.g. name = a_b
-    else
-    {
+    else {
       base = name;
     }
-  }
-  else
-  {
+  } else {
     base = name + "_";
   }
   QString tst(base + QString::number(index));
-  while( !isUnique(tst) )
-  {
+  while (!isUnique(tst)) {
     ++index;
     tst = base + QString::number(index);
   }
@@ -95,41 +84,37 @@ QString RenameParDialog::makeUniqueIndexedName(const QString& name)
 }
 
 /**
- * Output the new names to a vector 
+ * Output the new names to a vector
  * @returns :: new names in a vector
  */
-std::vector<std::string> RenameParDialog::setOutput() const
-{
+std::vector<std::string> RenameParDialog::setOutput() const {
   std::vector<std::string> out;
-  QAbstractItemModel* model = m_uiForm.tableWidget->model();
-  for(int row=0;row< m_uiForm.tableWidget->rowCount(); ++row)
-  {
-    out.push_back(model->data(model->index(row,1)).toString().toStdString());
+  QAbstractItemModel *model = m_uiForm.tableWidget->model();
+  for (int row = 0; row < m_uiForm.tableWidget->rowCount(); ++row) {
+    out.push_back(model->data(model->index(row, 1)).toString().toStdString());
   }
   return out;
 }
 
-void RenameParDialog::uniqueIndexedNames(bool ok)
-{
-  if (!ok) return;
-  QAbstractItemModel* model = m_uiForm.tableWidget->model();
-  for(int row=0;row< m_uiForm.tableWidget->rowCount(); ++row)
-  {
-    QString name = model->data(model->index(row,0)).toString();
-    model->setData(model->index(row,1),makeUniqueIndexedName(name));
+void RenameParDialog::uniqueIndexedNames(bool ok) {
+  if (!ok)
+    return;
+  QAbstractItemModel *model = m_uiForm.tableWidget->model();
+  for (int row = 0; row < m_uiForm.tableWidget->rowCount(); ++row) {
+    QString name = model->data(model->index(row, 0)).toString();
+    model->setData(model->index(row, 1), makeUniqueIndexedName(name));
   }
 }
 
 /**
  * Do not rename the parameters
  */
-void RenameParDialog::doNotRename(bool ok)
-{
-  if (!ok) return;
-  QAbstractItemModel* model = m_uiForm.tableWidget->model();
-  for(int row=0;row< m_uiForm.tableWidget->rowCount(); ++row)
-  {
-    QString name = model->data(model->index(row,0)).toString();
-    model->setData(model->index(row,1),name);
+void RenameParDialog::doNotRename(bool ok) {
+  if (!ok)
+    return;
+  QAbstractItemModel *model = m_uiForm.tableWidget->model();
+  for (int row = 0; row < m_uiForm.tableWidget->rowCount(); ++row) {
+    QString name = model->data(model->index(row, 0)).toString();
+    model->setData(model->index(row, 1), name);
   }
 }
diff --git a/MantidQt/MantidWidgets/src/SafeQwtPlot.cpp b/MantidQt/MantidWidgets/src/SafeQwtPlot.cpp
index 0354bda881049a126911c39a53fa8b68491e18fa..3b369785e96318734b7ed5da5728b6feedd37a3c 100644
--- a/MantidQt/MantidWidgets/src/SafeQwtPlot.cpp
+++ b/MantidQt/MantidWidgets/src/SafeQwtPlot.cpp
@@ -3,66 +3,50 @@
 #include "MantidKernel/System.h"
 #include "MantidKernel/ReadLock.h"
 
-
 using namespace Mantid::Kernel;
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  SafeQwtPlot::SafeQwtPlot(QWidget * parent)
-  : QwtPlot(parent)
-  {
-  }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  SafeQwtPlot::SafeQwtPlot(const QwtText &title, QWidget * parent)
-  : QwtPlot(title, parent)
-  {
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  SafeQwtPlot::~SafeQwtPlot()
-  {
-  }
-  
-
-  //----------------------------------------------------------------------------------------------
-  /** Set the workspace that we read-lock when drawing.
-   *
-   * @param ws :: shared ptr to workspace
-   */
-  void SafeQwtPlot::setWorkspace(Mantid::API::Workspace_sptr ws)
-  {
-    m_ws = ws;
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Overridden drawCanvas() that protects the
-   * workspace from being overwritten while being drawn
-   *
-   * @param painter :: QPainter
-   */
-  void SafeQwtPlot::drawCanvas(QPainter * painter)
-  {
-    // Do nothing if the workspace is not valid.
-    if (!m_ws) return;
-    // Get the scoped read lock.
-    ReadLock lock(*m_ws);
-    // Draw using the usual procedure.
-    QwtPlot::drawCanvas(painter);
-    // lock is released when it goes out of scope.
-  }
+namespace MantidQt {
+namespace MantidWidgets {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+SafeQwtPlot::SafeQwtPlot(QWidget *parent) : QwtPlot(parent) {}
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+SafeQwtPlot::SafeQwtPlot(const QwtText &title, QWidget *parent)
+    : QwtPlot(title, parent) {}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+SafeQwtPlot::~SafeQwtPlot() {}
+
+//----------------------------------------------------------------------------------------------
+/** Set the workspace that we read-lock when drawing.
+ *
+ * @param ws :: shared ptr to workspace
+ */
+void SafeQwtPlot::setWorkspace(Mantid::API::Workspace_sptr ws) { m_ws = ws; }
+
+//----------------------------------------------------------------------------------------------
+/** Overridden drawCanvas() that protects the
+ * workspace from being overwritten while being drawn
+ *
+ * @param painter :: QPainter
+ */
+void SafeQwtPlot::drawCanvas(QPainter *painter) {
+  // Do nothing if the workspace is not valid.
+  if (!m_ws)
+    return;
+  // Get the scoped read lock.
+  ReadLock lock(*m_ws);
+  // Draw using the usual procedure.
+  QwtPlot::drawCanvas(painter);
+  // lock is released when it goes out of scope.
+}
 
 } // namespace MantidQt
 } // namespace MantidWidgets
diff --git a/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp b/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp
index 7613cc837bd6271584d18957a0a88aec2e1d364f..c58cb747d6762ba02c7cbf91e00066a5fb573dc8 100644
--- a/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp
+++ b/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp
@@ -325,7 +325,7 @@ void SaveWorkspaces::saveSel() {
         return;
       }
     } // end if save in this format
-  } // end loop over formats
+  }   // end loop over formats
 
   saveCommands += "print 'success'";
   QString status(runPythonCode(saveCommands).trimmed());
@@ -358,8 +358,7 @@ void SaveWorkspaces::saveFileBrowse() {
   QString prevPath =
       prevValues.value("dir", QString::fromStdString(
                                   ConfigService::Instance().getString(
-                                      "defaultsave.directory")))
-          .toString();
+                                      "defaultsave.directory"))).toString();
 
   QString filter = ";;AllFiles (*.*)";
   QFileDialog::Option userCon = m_append->isChecked()
diff --git a/MantidQt/MantidWidgets/src/SelectFunctionDialog.cpp b/MantidQt/MantidWidgets/src/SelectFunctionDialog.cpp
index 9b454cff71378443a643a4877df7cebb73c193c1..c46cc5fde4329afe0b3b0dd2aeff89f395b77a67 100644
--- a/MantidQt/MantidWidgets/src/SelectFunctionDialog.cpp
+++ b/MantidQt/MantidWidgets/src/SelectFunctionDialog.cpp
@@ -24,61 +24,62 @@
  * @param parent :: A parent widget
  */
 SelectFunctionDialog::SelectFunctionDialog(QWidget *parent)
-  :QDialog(parent),m_form(new Ui::SelectFunctionDialog)
-{
+    : QDialog(parent), m_form(new Ui::SelectFunctionDialog) {
   m_form->setupUi(this);
 
   auto registeredFunctions = Mantid::API::FunctionFactory::Instance().getKeys();
-  // Add functions to each of the categories. If it appears in more than one category then add to both
-  // Store in a map. Key = category. Value = vector of fit functions belonging to that category.
-  std::map<std::string, std::vector<std::string> > categories;
-  for (size_t i=0; i<registeredFunctions.size(); ++i)
-  {
-    boost::shared_ptr<Mantid::API::IFunction> f = Mantid::API::FunctionFactory::Instance().createFunction(registeredFunctions[i]);
+  // Add functions to each of the categories. If it appears in more than one
+  // category then add to both
+  // Store in a map. Key = category. Value = vector of fit functions belonging
+  // to that category.
+  std::map<std::string, std::vector<std::string>> categories;
+  for (size_t i = 0; i < registeredFunctions.size(); ++i) {
+    boost::shared_ptr<Mantid::API::IFunction> f =
+        Mantid::API::FunctionFactory::Instance().createFunction(
+            registeredFunctions[i]);
     std::vector<std::string> tempCategories = f->categories();
-    for (size_t j=0; j<tempCategories.size(); ++j)
-    {
-      categories[tempCategories[boost::lexical_cast<int>(j)] ].push_back(registeredFunctions[i]);
+    for (size_t j = 0; j < tempCategories.size(); ++j) {
+      categories[tempCategories[boost::lexical_cast<int>(j)]].push_back(
+          registeredFunctions[i]);
     }
   }
-  
-  // Construct the QTreeWidget based on the map information of categories and their respective fit functions.
-  std::map<std::string, std::vector<std::string> >::const_iterator sItr = categories.end();
-  for (std::map<std::string, std::vector<std::string> >::const_iterator itr = categories.begin(); itr != sItr; ++itr)
-  {
+
+  // Construct the QTreeWidget based on the map information of categories and
+  // their respective fit functions.
+  std::map<std::string, std::vector<std::string>>::const_iterator sItr =
+      categories.end();
+  for (std::map<std::string, std::vector<std::string>>::const_iterator itr =
+           categories.begin();
+       itr != sItr; ++itr) {
     QTreeWidgetItem *category = new QTreeWidgetItem(m_form->fitTree);
-    category->setText(0, QString::fromStdString(itr->first) );
-    
+    category->setText(0, QString::fromStdString(itr->first));
+
     std::vector<std::string>::const_iterator fitItrEnd = itr->second.end();
-    for (std::vector<std::string>::const_iterator fitItrBegin = itr->second.begin(); fitItrBegin != fitItrEnd; ++fitItrBegin)
-    {
+    for (std::vector<std::string>::const_iterator fitItrBegin =
+             itr->second.begin();
+         fitItrBegin != fitItrEnd; ++fitItrBegin) {
       QTreeWidgetItem *fit = new QTreeWidgetItem(category);
-      fit->setText(0, QString::fromStdString(fitItrBegin[0]) );      
+      fit->setText(0, QString::fromStdString(fitItrBegin[0]));
     }
   }
 
-  connect(m_form->fitTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(accept()));
+  connect(m_form->fitTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
+          this, SLOT(accept()));
   m_form->fitTree->setToolTip("Select a function type and press OK.");
 }
 
-SelectFunctionDialog::~SelectFunctionDialog()
-{
-  delete m_form;
-}
+SelectFunctionDialog::~SelectFunctionDialog() { delete m_form; }
 
 /**
  * Return selected function
  */
-QString SelectFunctionDialog::getFunction() const
-{
-  QList<QTreeWidgetItem*> items(m_form->fitTree->selectedItems() );
-  if (items.size() != 1)
-  {
+QString SelectFunctionDialog::getFunction() const {
+  QList<QTreeWidgetItem *> items(m_form->fitTree->selectedItems());
+  if (items.size() != 1) {
     return "";
   }
-  
-  if (items[0]->parent() == NULL)
-  {
+
+  if (items[0]->parent() == NULL) {
     return "";
   }
 
diff --git a/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp b/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
index b1ac19050401551bb7c0f7930bdf15d6841eda13..0674c3f23ed93886feb5f0e5332847b36efad709 100644
--- a/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
+++ b/MantidQt/MantidWidgets/src/SelectWorkspacesDialog.cpp
@@ -12,32 +12,29 @@
 #include "MantidAPI/AnalysisDataService.h"
 #include "MantidAPI/MatrixWorkspace.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-
-  /**
-  Helper comparitor class used to determine if a workspace is not of a given type.
-  */
-  class WorkspaceIsNotOfType
-  {
-  private:
-    const std::string m_type;
-    const bool m_isMatrixWorkspace;
-  public:
-    explicit WorkspaceIsNotOfType(const std::string &type)
-        : m_type(type), m_isMatrixWorkspace(type == "MatrixWorkspace") {}
-    bool operator()(Mantid::API::Workspace_sptr ws) const
-    {
-      if ( m_type.empty() ) return false;
-      if ( m_isMatrixWorkspace )
-      {
-        return dynamic_cast<Mantid::API::MatrixWorkspace*>( ws.get() ) == NULL;
-      }
-      return ws->id() != m_type;
+namespace MantidQt {
+namespace MantidWidgets {
+
+/**
+Helper comparitor class used to determine if a workspace is not of a given type.
+*/
+class WorkspaceIsNotOfType {
+private:
+  const std::string m_type;
+  const bool m_isMatrixWorkspace;
+
+public:
+  explicit WorkspaceIsNotOfType(const std::string &type)
+      : m_type(type), m_isMatrixWorkspace(type == "MatrixWorkspace") {}
+  bool operator()(Mantid::API::Workspace_sptr ws) const {
+    if (m_type.empty())
+      return false;
+    if (m_isMatrixWorkspace) {
+      return dynamic_cast<Mantid::API::MatrixWorkspace *>(ws.get()) == NULL;
     }
-  };
+    return ws->id() != m_type;
+  }
+};
 
 //---------------------------------------
 // Public member functions
@@ -46,80 +43,74 @@ namespace MantidWidgets
 /** Constructor
 @param parent : Parent widget
 @param typeFilter : optional filter for filtering workspaces by type.
-@param customButtonLabel : optional label for another custom button, return code for this is defined by CustomButton.
+@param customButtonLabel : optional label for another custom button, return code
+for this is defined by CustomButton.
 */
-SelectWorkspacesDialog::SelectWorkspacesDialog(QWidget* parent, const std::string& typeFilter,
-                                               const std::string& customButtonLabel) :
-  QDialog(parent), m_wsList(NULL), m_okButton(NULL), m_customButton(NULL)
-{
+SelectWorkspacesDialog::SelectWorkspacesDialog(
+    QWidget *parent, const std::string &typeFilter,
+    const std::string &customButtonLabel)
+    : QDialog(parent), m_wsList(NULL), m_okButton(NULL), m_customButton(NULL) {
   setWindowTitle("MantidPlot - Select workspace");
   m_wsList = new QListWidget(parent);
 
-  
-  Mantid::API::AnalysisDataServiceImpl& ADS = Mantid::API::AnalysisDataService::Instance();
+  Mantid::API::AnalysisDataServiceImpl &ADS =
+      Mantid::API::AnalysisDataService::Instance();
   typedef std::vector<Mantid::API::Workspace_sptr> VecWorkspaces;
   VecWorkspaces workspaces = ADS.getObjects();
   WorkspaceIsNotOfType comparitor(typeFilter);
-  workspaces.erase(std::remove_if(workspaces.begin(), workspaces.end(), comparitor), workspaces.end() );
+  workspaces.erase(
+      std::remove_if(workspaces.begin(), workspaces.end(), comparitor),
+      workspaces.end());
   QStringList tmp;
-  for (VecWorkspaces::const_iterator it = workspaces.begin(); it != workspaces.end(); ++it)
-  {
-    //if(useFilter && ADS::
-    tmp<<QString::fromStdString((*it)->name());
+  for (VecWorkspaces::const_iterator it = workspaces.begin();
+       it != workspaces.end(); ++it) {
+    // if(useFilter && ADS::
+    tmp << QString::fromStdString((*it)->name());
   }
 
   m_wsList->addItems(tmp);
   m_wsList->setSelectionMode(QAbstractItemView::MultiSelection);
 
-  QDialogButtonBox* btnBox = new QDialogButtonBox(Qt::Horizontal);
+  QDialogButtonBox *btnBox = new QDialogButtonBox(Qt::Horizontal);
 
   if (!customButtonLabel.empty()) {
     m_customButton = new QPushButton(QString::fromStdString(customButtonLabel));
-    btnBox->addButton(m_customButton,QDialogButtonBox::DestructiveRole);
+    btnBox->addButton(m_customButton, QDialogButtonBox::DestructiveRole);
     connect(m_customButton, SIGNAL(clicked()), this, SLOT(customButtonPress()));
   }
 
   m_okButton = new QPushButton("Select");
-  QPushButton* cancelButton = new QPushButton("Cancel");
-  btnBox->addButton(m_okButton,QDialogButtonBox::AcceptRole);
-  btnBox->addButton(cancelButton,QDialogButtonBox::RejectRole);
+  QPushButton *cancelButton = new QPushButton("Cancel");
+  btnBox->addButton(m_okButton, QDialogButtonBox::AcceptRole);
+  btnBox->addButton(cancelButton, QDialogButtonBox::RejectRole);
   connect(btnBox, SIGNAL(accepted()), this, SLOT(accept()));
   connect(btnBox, SIGNAL(rejected()), this, SLOT(reject()));
 
-  QVBoxLayout* vLayout = new QVBoxLayout();
+  QVBoxLayout *vLayout = new QVBoxLayout();
   vLayout->addWidget(m_wsList);
   vLayout->addWidget(btnBox);
 
   setLayout(vLayout);
 
-  connect(m_wsList,SIGNAL(itemSelectionChanged()),this,SLOT(selectionChanged()));
+  connect(m_wsList, SIGNAL(itemSelectionChanged()), this,
+          SLOT(selectionChanged()));
 
   selectionChanged();
-
 }
 
-QStringList SelectWorkspacesDialog::getSelectedNames()const
-{
+QStringList SelectWorkspacesDialog::getSelectedNames() const {
   QList<QListWidgetItem *> items = m_wsList->selectedItems();
   QStringList res;
-  foreach(QListWidgetItem* item,items)
-  {
-    res << item->text();
-  }
+  foreach (QListWidgetItem *item, items) { res << item->text(); }
   return res;
 }
 
 /// Slot to monitor the workspace selection status
-void SelectWorkspacesDialog::selectionChanged()
-{
-  m_okButton->setEnabled( m_wsList->selectionModel()->hasSelection() );
+void SelectWorkspacesDialog::selectionChanged() {
+  m_okButton->setEnabled(m_wsList->selectionModel()->hasSelection());
 }
 
 /// slot to handle the custom button press
-void SelectWorkspacesDialog::customButtonPress()
-{
-  this->done(CustomButton);
-}
-
+void SelectWorkspacesDialog::customButtonPress() { this->done(CustomButton); }
 }
 }
diff --git a/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp b/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp
index a7d9d3b27966b5b83135f0a71f5b1dff6d2f8b87..17c14ab665fa3245cbc792459b937ba841a27155 100644
--- a/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp
+++ b/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp
@@ -25,29 +25,30 @@
 // Public member functions
 //---------------------------------------
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
 /// Constructor
 /// @param fitBrowser
 /// @param mantidui Its purpose is to provide the slot showSequentialPlot
-SequentialFitDialog::SequentialFitDialog(FitPropertyBrowser* fitBrowser, QObject* mantidui) :
-QDialog(fitBrowser),m_fitBrowser(fitBrowser)
-{
+SequentialFitDialog::SequentialFitDialog(FitPropertyBrowser *fitBrowser,
+                                         QObject *mantidui)
+    : QDialog(fitBrowser), m_fitBrowser(fitBrowser) {
   ui.setupUi(this);
 
-  connect(ui.btnAddFile,SIGNAL(clicked()),this,SLOT(addFile()));
-  connect(ui.btnAddWorkspace,SIGNAL(clicked()),this,SLOT(addWorkspace()));
-  connect(ui.btnDelete,SIGNAL(clicked()),this,SLOT(removeItem()));
+  connect(ui.btnAddFile, SIGNAL(clicked()), this, SLOT(addFile()));
+  connect(ui.btnAddWorkspace, SIGNAL(clicked()), this, SLOT(addWorkspace()));
+  connect(ui.btnDelete, SIGNAL(clicked()), this, SLOT(removeItem()));
 
-  connect(ui.btnFit,SIGNAL(clicked()),this,SLOT(accept()));
-  connect(ui.btnCancel,SIGNAL(clicked()),this,SLOT(reject()));
-  connect(ui.btnHelp,SIGNAL(clicked()),this,SLOT(helpClicked()));
-  connect(ui.ckbLogPlot,SIGNAL(toggled(bool)),this,SLOT(plotAgainstLog(bool)));
-  connect(ui.ckCreateOutput,SIGNAL(toggled(bool)),ui.ckOutputCompMembers,SLOT(setEnabled(bool)));
-  connect(ui.ckCreateOutput,SIGNAL(toggled(bool)),ui.ckConvolveMembers,SLOT(setEnabled(bool)));
+  connect(ui.btnFit, SIGNAL(clicked()), this, SLOT(accept()));
+  connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(ui.btnHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  connect(ui.ckbLogPlot, SIGNAL(toggled(bool)), this,
+          SLOT(plotAgainstLog(bool)));
+  connect(ui.ckCreateOutput, SIGNAL(toggled(bool)), ui.ckOutputCompMembers,
+          SLOT(setEnabled(bool)));
+  connect(ui.ckCreateOutput, SIGNAL(toggled(bool)), ui.ckConvolveMembers,
+          SLOT(setEnabled(bool)));
 
   ui.cbLogValue->setEditable(true);
   ui.ckbLogPlot->setChecked(true);
@@ -55,78 +56,75 @@ QDialog(fitBrowser),m_fitBrowser(fitBrowser)
 
   populateParameters();
 
-  connect(fitBrowser,SIGNAL(functionChanged()),this,SLOT(functionChanged()));
+  connect(fitBrowser, SIGNAL(functionChanged()), this, SLOT(functionChanged()));
 
   // When a fit is completed finishHandle is called which emits needShowPlot
-  connect(this,SIGNAL(needShowPlot(Ui::SequentialFitDialog*, MantidQt::MantidWidgets::FitPropertyBrowser*)),
-          mantidui,SLOT(showSequentialPlot(Ui::SequentialFitDialog*, MantidQt::MantidWidgets::FitPropertyBrowser*)));
-  connect(ui.tWorkspaces,SIGNAL(cellChanged(int,int)),this,SLOT(spectraChanged(int,int)));
-  connect(ui.tWorkspaces,SIGNAL(itemSelectionChanged()),this,SLOT(selectionChanged()));
+  connect(
+      this, SIGNAL(needShowPlot(Ui::SequentialFitDialog *,
+                                MantidQt::MantidWidgets::FitPropertyBrowser *)),
+      mantidui,
+      SLOT(showSequentialPlot(Ui::SequentialFitDialog *,
+                              MantidQt::MantidWidgets::FitPropertyBrowser *)));
+  connect(ui.tWorkspaces, SIGNAL(cellChanged(int, int)), this,
+          SLOT(spectraChanged(int, int)));
+  connect(ui.tWorkspaces, SIGNAL(itemSelectionChanged()), this,
+          SLOT(selectionChanged()));
 
   selectionChanged();
-
 }
 
-void SequentialFitDialog::addWorkspace()
-{
-  SelectWorkspacesDialog* dlg = new SelectWorkspacesDialog(this,"MatrixWorkspace");
-  if (dlg->exec() == QDialog::Accepted)
-  {
+void SequentialFitDialog::addWorkspace() {
+  SelectWorkspacesDialog *dlg =
+      new SelectWorkspacesDialog(this, "MatrixWorkspace");
+  if (dlg->exec() == QDialog::Accepted) {
     addWorkspaces(dlg->getSelectedNames());
   }
 }
 
-bool SequentialFitDialog::addWorkspaces(const QStringList wsNames)
-{
-  if (wsNames.isEmpty()) return false;
+bool SequentialFitDialog::addWorkspaces(const QStringList wsNames) {
+  if (wsNames.isEmpty())
+    return false;
   int row = ui.tWorkspaces->rowCount();
-  ui.tWorkspaces->model()->insertRows(row,wsNames.size());
+  ui.tWorkspaces->model()->insertRows(row, wsNames.size());
   int wi = m_fitBrowser->workspaceIndex();
-  QAbstractItemModel* model = ui.tWorkspaces->model();
-  foreach(QString name,wsNames)
-  {
-    model->setData(model->index(row,0,QModelIndex()),name);
+  QAbstractItemModel *model = ui.tWorkspaces->model();
+  foreach (QString name, wsNames) {
+    model->setData(model->index(row, 0, QModelIndex()), name);
 
-    if (row == 0)
-    {
+    if (row == 0) {
       ui.ckbLogPlot->setChecked(validateLogs(name));
     }
-      
+
     // disable the period cell
-    model->setData(model->index(row,1,QModelIndex()),"");
-    QTableWidgetItem* item = ui.tWorkspaces->item(row,1);
-    if (item) 
-    {
+    model->setData(model->index(row, 1, QModelIndex()), "");
+    QTableWidgetItem *item = ui.tWorkspaces->item(row, 1);
+    if (item) {
       item->setBackgroundColor(QColor(Qt::lightGray));
       item->setFlags(Qt::NoItemFlags);
     }
 
-    if (ui.ckbLogPlot->isChecked())
-    {
+    if (ui.ckbLogPlot->isChecked()) {
       // set spectrum number corresponding to the workspace index
-      Mantid::API::MatrixWorkspace_sptr ws = 
-        boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(name.toStdString())
-        );
+      Mantid::API::MatrixWorkspace_sptr ws =
+          boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+              Mantid::API::AnalysisDataService::Instance().retrieve(
+                  name.toStdString()));
       int spec = -1;
-      if (ws)
-      {
-        Mantid::API::Axis* y = ws->getAxis(1);
-        if (y->isSpectra())
-        {
+      if (ws) {
+        Mantid::API::Axis *y = ws->getAxis(1);
+        if (y->isSpectra()) {
           spec = y->spectraNo(wi);
         }
       }
-      //model->setData(model->index(row,2,QModelIndex()),spec);
-      setSpectrum(row,spec);
-      if (row == 0)
-      {
+      // model->setData(model->index(row,2,QModelIndex()),spec);
+      setSpectrum(row, spec);
+      if (row == 0) {
         ui.sbSpectrum->setValue(spec);
       }
 
       // set workspace index
-      //model->setData(model->index(row,3,QModelIndex()),wi);
-      setWSIndex(row,wi);
+      // model->setData(model->index(row,3,QModelIndex()),wi);
+      setWSIndex(row, wi);
     }
     ++row;
   }
@@ -135,42 +133,38 @@ bool SequentialFitDialog::addWorkspaces(const QStringList wsNames)
   return true;
 }
 
-void SequentialFitDialog::addFile()
-{
+void SequentialFitDialog::addFile() {
   QFileDialog dlg(this);
   dlg.setFileMode(QFileDialog::ExistingFiles);
-  const std::vector<std::string>& searchDirs =
-    Mantid::Kernel::ConfigService::Instance().getDataSearchDirs();
+  const std::vector<std::string> &searchDirs =
+      Mantid::Kernel::ConfigService::Instance().getDataSearchDirs();
   QString dir;
-  if ( searchDirs.empty() )
-  {
+  if (searchDirs.empty()) {
     dir = "";
-  }
-  else
-  {
+  } else {
     dir = QString::fromStdString(searchDirs.front());
   }
   dlg.setDirectory(dir);
-  if (dlg.exec())
-  {
+  if (dlg.exec()) {
     QStringList fileNames;
     fileNames = dlg.selectedFiles();
-    if (fileNames.isEmpty()) return;
+    if (fileNames.isEmpty())
+      return;
     fileNames.sort();
 
     int row = ui.tWorkspaces->rowCount();
-    ui.tWorkspaces->model()->insertRows(row,fileNames.size());
-    //int wi = m_fitBrowser->workspaceIndex();
-    QAbstractItemModel* model = ui.tWorkspaces->model();
-    foreach(QString name,fileNames)
-    {
-      model->setData(model->index(row,0,QModelIndex()),name); // file name
-      model->setData(model->index(row,1,QModelIndex()),ui.sbPeriod->value());   // period
-      model->setData(model->index(row,2,QModelIndex()),ui.sbSpectrum->value());   // spectrum
-      model->setData(model->index(row,3,QModelIndex()),"");   // ws index
-      QTableWidgetItem* item = ui.tWorkspaces->item(row,3);
-      if (item) 
-      {
+    ui.tWorkspaces->model()->insertRows(row, fileNames.size());
+    // int wi = m_fitBrowser->workspaceIndex();
+    QAbstractItemModel *model = ui.tWorkspaces->model();
+    foreach (QString name, fileNames) {
+      model->setData(model->index(row, 0, QModelIndex()), name); // file name
+      model->setData(model->index(row, 1, QModelIndex()),
+                     ui.sbPeriod->value()); // period
+      model->setData(model->index(row, 2, QModelIndex()),
+                     ui.sbSpectrum->value());                  // spectrum
+      model->setData(model->index(row, 3, QModelIndex()), ""); // ws index
+      QTableWidgetItem *item = ui.tWorkspaces->item(row, 3);
+      if (item) {
         item->setBackgroundColor(QColor(Qt::lightGray));
         item->setFlags(Qt::NoItemFlags);
       }
@@ -181,67 +175,57 @@ void SequentialFitDialog::addFile()
   }
 }
 
-void SequentialFitDialog::removeItem()
-{
+void SequentialFitDialog::removeItem() {
   QList<QTableWidgetSelectionRange> ranges = ui.tWorkspaces->selectedRanges();
-  while (!ranges.empty())
-  {
-    ui.tWorkspaces->model()->removeRows(ranges[0].topRow(),ranges[0].rowCount());
+  while (!ranges.empty()) {
+    ui.tWorkspaces->model()->removeRows(ranges[0].topRow(),
+                                        ranges[0].rowCount());
     ranges = ui.tWorkspaces->selectedRanges();
   }
 }
 
-bool SequentialFitDialog::validateLogs(const QString wsName)
-{
-  Mantid::API::MatrixWorkspace_sptr ws = 
-    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-    Mantid::API::AnalysisDataService::Instance().retrieve(wsName.toStdString())
-    );
-  if (ws)
-  {
-    const std::vector<Mantid::Kernel::Property*> logs = ws->run().getLogData();
+bool SequentialFitDialog::validateLogs(const QString wsName) {
+  Mantid::API::MatrixWorkspace_sptr ws =
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(
+              wsName.toStdString()));
+  if (ws) {
+    const std::vector<Mantid::Kernel::Property *> logs = ws->run().getLogData();
     QStringList logNames;
-    for(int i=0;i<static_cast<int>(logs.size());++i)
-    {
-      Mantid::Kernel::TimeSeriesProperty<double>* p = 
-        dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double>*>(logs[i]);
-      if (!p) continue;
+    for (int i = 0; i < static_cast<int>(logs.size()); ++i) {
+      Mantid::Kernel::TimeSeriesProperty<double> *p =
+          dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(logs[i]);
+      if (!p)
+        continue;
       logNames << QString::fromStdString(logs[i]->name());
     }
     int n = ui.cbLogValue->count();
     // if the ws has no logs - do not include it
-    if (logNames.empty())
-    {
+    if (logNames.empty()) {
       return false;
     }
     // if the log value combo box is empty fill it in with the log names from ws
-    if (n == 0)
-    {
-      ui.cbLogValue->insertItems(0,logNames);
-    }
-    else
-    {// keep only those logs which are included in both ui.cbLogValue and logNames
+    if (n == 0) {
+      ui.cbLogValue->insertItems(0, logNames);
+    } else { // keep only those logs which are included in both ui.cbLogValue
+             // and logNames
       QStringList namesToRemove;
-      for(int i=0;i<n;++i)
-      {
+      for (int i = 0; i < n; ++i) {
         QString name = ui.cbLogValue->itemText(i);
-        if (!logNames.contains(name))
-        {
+        if (!logNames.contains(name)) {
           namesToRemove << name;
         }
       }
-      foreach(QString name,namesToRemove)
-      {
+      foreach (QString name, namesToRemove) {
         int i = ui.cbLogValue->findText(name);
-        if (i >= 0)
-        {
+        if (i >= 0) {
           ui.cbLogValue->removeItem(i);
         }
       }
-      if (ui.cbLogValue->count() == 0)
-      {
-        QMessageBox::warning(m_fitBrowser,"MantidPlot - Warning","The list of the log names is empty:\n"
-          "The selected workspaces do not have common logs");
+      if (ui.cbLogValue->count() == 0) {
+        QMessageBox::warning(m_fitBrowser, "MantidPlot - Warning",
+                             "The list of the log names is empty:\n"
+                             "The selected workspaces do not have common logs");
         return false;
       }
     }
@@ -249,119 +233,108 @@ bool SequentialFitDialog::validateLogs(const QString wsName)
   return true;
 }
 
-bool SequentialFitDialog::isFile(int row)const
-{
-  QTableWidgetItem* item = ui.tWorkspaces->item(row,3);
+bool SequentialFitDialog::isFile(int row) const {
+  QTableWidgetItem *item = ui.tWorkspaces->item(row, 3);
   return !item || item->flags().testFlag(Qt::ItemIsEnabled) == false;
 }
 
 /**
-  * Returns index for the data source in row row to be used in "Input" property of PlotPeakByLogValue.
-  * Index includes the prefix "sp", "i", or "v" 
+  * Returns index for the data source in row row to be used in "Input" property
+ * of PlotPeakByLogValue.
+  * Index includes the prefix "sp", "i", or "v"
   */
-QString SequentialFitDialog::getIndex(int row)const
-{
+QString SequentialFitDialog::getIndex(int row) const {
   QString index;
-  QString spectrum = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,2)).toString();
-  QString wsIndex = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,3)).toString();
-  QString range = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,4)).toString();
-
-  if (isFile(row))
-  {
+  QString spectrum = ui.tWorkspaces->model()
+                         ->data(ui.tWorkspaces->model()->index(row, 2))
+                         .toString();
+  QString wsIndex = ui.tWorkspaces->model()
+                        ->data(ui.tWorkspaces->model()->index(row, 3))
+                        .toString();
+  QString range = ui.tWorkspaces->model()
+                      ->data(ui.tWorkspaces->model()->index(row, 4))
+                      .toString();
+
+  if (isFile(row)) {
     // if it is a file the ndex can be either spectrum or a range of values
     // range takes priority over spectrum
-    if ( !range.isEmpty() )
-    {
+    if (!range.isEmpty()) {
       index = "v" + range;
-    }
-    else
-    {
+    } else {
       index = "sp" + spectrum;
     }
-  }
-  else
-  {
-    Mantid::API::MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(name(row).toStdString()) );
-    Mantid::API::Axis* y = ws->getAxis(1);
-
-    // if it is a single workspace index can only be a range since we are doing a multiple fitting
-    if (rowCount() == 1 && range.isEmpty())
-    {
-      index = QString("v%1:%2").arg((*y)(0)).arg((*y)(y->length()-1));
-    }
-    else
-    {
-      if ( !range.isEmpty() )
-      {
+  } else {
+    Mantid::API::MatrixWorkspace_sptr ws =
+        boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+            Mantid::API::AnalysisDataService::Instance().retrieve(
+                name(row).toStdString()));
+    Mantid::API::Axis *y = ws->getAxis(1);
+
+    // if it is a single workspace index can only be a range since we are doing
+    // a multiple fitting
+    if (rowCount() == 1 && range.isEmpty()) {
+      index = QString("v%1:%2").arg((*y)(0)).arg((*y)(y->length() - 1));
+    } else {
+      if (!range.isEmpty()) {
         index = "v" + range;
-      }
-      else
-      {
+      } else {
         index = "i" + wsIndex;
       }
     }
-
   }
-  
+
   return index;
 }
 
-void SequentialFitDialog::accept()
-{
+void SequentialFitDialog::accept() {
   QStringList inputStr;
-  for(int i=0;i<ui.tWorkspaces->rowCount();++i)
-  {
-    QString name = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(i,0)).toString();
+  for (int i = 0; i < ui.tWorkspaces->rowCount(); ++i) {
+    QString name = ui.tWorkspaces->model()
+                       ->data(ui.tWorkspaces->model()->index(i, 0))
+                       .toString();
     QString parStr = name + "," + getIndex(i);
-    if ( isFile(i) )
-    {// add the period
-      parStr += QString(",") + ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(i,1)).toString();
+    if (isFile(i)) { // add the period
+      parStr += QString(",") +
+                ui.tWorkspaces->model()
+                    ->data(ui.tWorkspaces->model()->index(i, 1))
+                    .toString();
     }
     inputStr << parStr;
   }
   std::string funStr;
-  if (m_fitBrowser->m_compositeFunction->nFunctions() > 1)
-  {
+  if (m_fitBrowser->m_compositeFunction->nFunctions() > 1) {
     funStr = m_fitBrowser->m_compositeFunction->asString();
-  }
-  else
-  {
+  } else {
     funStr = (m_fitBrowser->m_compositeFunction->getFunction(0))->asString();
   }
 
-  Mantid::API::IAlgorithm_sptr alg = 
-    Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
+  Mantid::API::IAlgorithm_sptr alg =
+      Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
   alg->initialize();
-  alg->setPropertyValue("Input",inputStr.join(";").toStdString());
-  alg->setProperty("WorkspaceIndex",m_fitBrowser->workspaceIndex());
-  alg->setProperty("StartX",m_fitBrowser->startX());
-  alg->setProperty("EndX",m_fitBrowser->endX());
-  alg->setPropertyValue("OutputWorkspace",m_fitBrowser->outputName());
-  alg->setPropertyValue("Function",funStr);
+  alg->setPropertyValue("Input", inputStr.join(";").toStdString());
+  alg->setProperty("WorkspaceIndex", m_fitBrowser->workspaceIndex());
+  alg->setProperty("StartX", m_fitBrowser->startX());
+  alg->setProperty("EndX", m_fitBrowser->endX());
+  alg->setPropertyValue("OutputWorkspace", m_fitBrowser->outputName());
+  alg->setPropertyValue("Function", funStr);
   alg->setProperty("CreateOutput", ui.ckCreateOutput->isChecked());
-  alg->setProperty("OutputCompositeMembers", ui.ckOutputCompMembers->isChecked());
+  alg->setProperty("OutputCompositeMembers",
+                   ui.ckOutputCompMembers->isChecked());
   alg->setProperty("ConvolveMembers", ui.ckConvolveMembers->isChecked());
-  if (ui.ckbLogPlot->isChecked())
-  {
+  if (ui.ckbLogPlot->isChecked()) {
     std::string logName = ui.cbLogValue->currentText().toStdString();
-    alg->setPropertyValue("LogValue",logName);
+    alg->setPropertyValue("LogValue", logName);
     observeFinish(alg);
-  }
-  else if (rowCount() > 1)
-  {
-    alg->setPropertyValue("LogValue","SourceName");
-  }
-  else
-  {
+  } else if (rowCount() > 1) {
+    alg->setPropertyValue("LogValue", "SourceName");
+  } else {
     observeFinish(alg);
   }
-  alg->setPropertyValue("Minimizer",m_fitBrowser->minimizer());
-  alg->setPropertyValue("CostFunction",m_fitBrowser->costFunction());
-  alg->setProperty("MaxIterations",m_fitBrowser->maxIterations());
-  if (ui.rbIndividual->isChecked())
-  {
-    alg->setPropertyValue("FitType","Individual");
+  alg->setPropertyValue("Minimizer", m_fitBrowser->minimizer());
+  alg->setPropertyValue("CostFunction", m_fitBrowser->costFunction());
+  alg->setProperty("MaxIterations", m_fitBrowser->maxIterations());
+  if (ui.rbIndividual->isChecked()) {
+    alg->setPropertyValue("FitType", "Individual");
   }
 
   bool passWSIndexToFunction = ui.ckbPassWS->isChecked();
@@ -371,31 +344,25 @@ void SequentialFitDialog::accept()
   QDialog::accept();
 }
 
-void SequentialFitDialog::populateParameters()
-{
+void SequentialFitDialog::populateParameters() {
   QStringList names;
-  for(size_t i=0;i<m_fitBrowser->m_compositeFunction->nParams();++i)
-  {
-    names << QString::fromStdString(m_fitBrowser->m_compositeFunction->parameterName(i));
+  for (size_t i = 0; i < m_fitBrowser->m_compositeFunction->nParams(); ++i) {
+    names << QString::fromStdString(
+        m_fitBrowser->m_compositeFunction->parameterName(i));
   }
   ui.cbParameter->clear();
-  ui.cbParameter->insertItems(0,names);
-}
-
-void SequentialFitDialog::functionChanged()
-{
-  populateParameters();
+  ui.cbParameter->insertItems(0, names);
 }
 
+void SequentialFitDialog::functionChanged() { populateParameters(); }
 
-void SequentialFitDialog::finishHandle(const Mantid::API::IAlgorithm*)
-{
+void SequentialFitDialog::finishHandle(const Mantid::API::IAlgorithm *) {
   emit needShowPlot(&ui, m_fitBrowser);
 }
 
-void SequentialFitDialog::helpClicked()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/PlotPeakByLogValue"));
+void SequentialFitDialog::helpClicked() {
+  QDesktopServices::openUrl(
+      QUrl("http://www.mantidproject.org/PlotPeakByLogValue"));
 }
 
 /**
@@ -405,117 +372,109 @@ void SequentialFitDialog::helpClicked()
   * @param row :: Row index of the modified cell
   * @param col :: Column index of the modified cell
   */
-void SequentialFitDialog::spectraChanged(int row,int col)
-{
-  if (!ui.ckbLogPlot->isChecked()) return;
-  QTableWidgetItem* item = ui.tWorkspaces->item(row,3);
-  if (!item) return;
-  if ((col == 2 || col == 3) && item->flags().testFlag(Qt::ItemIsEnabled) == true)
-  {// it's a workspace
-    QString name = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,0)).toString();
+void SequentialFitDialog::spectraChanged(int row, int col) {
+  if (!ui.ckbLogPlot->isChecked())
+    return;
+  QTableWidgetItem *item = ui.tWorkspaces->item(row, 3);
+  if (!item)
+    return;
+  if ((col == 2 || col == 3) &&
+      item->flags().testFlag(Qt::ItemIsEnabled) == true) { // it's a workspace
+    QString name = ui.tWorkspaces->model()
+                       ->data(ui.tWorkspaces->model()->index(row, 0))
+                       .toString();
     Mantid::API::MatrixWorkspace_sptr ws;
-    try
-    {
+    try {
       ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-             Mantid::API::AnalysisDataService::Instance().retrieve(name.toStdString())
-           );
-    }
-    catch(...)
-    {// 
+          Mantid::API::AnalysisDataService::Instance().retrieve(
+              name.toStdString()));
+    } catch (...) { //
       return;
     }
-    if (!ws) return;
-    int wi = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,3)).toInt();
-    int spec = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,2)).toInt();
-    Mantid::API::Axis* y = ws->getAxis(1);
-    if (wi >= 0 && wi < static_cast<int>(ws->getNumberHistograms()))
-    {
+    if (!ws)
+      return;
+    int wi = ui.tWorkspaces->model()
+                 ->data(ui.tWorkspaces->model()->index(row, 3))
+                 .toInt();
+    int spec = ui.tWorkspaces->model()
+                   ->data(ui.tWorkspaces->model()->index(row, 2))
+                   .toInt();
+    Mantid::API::Axis *y = ws->getAxis(1);
+    if (wi >= 0 && wi < static_cast<int>(ws->getNumberHistograms())) {
       // this prevents infinite loops
-      if ( !y->isSpectra() || y->spectraNo(wi) == spec) return;
-    }
-    else
-    {
+      if (!y->isSpectra() || y->spectraNo(wi) == spec)
+        return;
+    } else {
       // return to the previous state
       col = 2;
     }
     if (col == 3) // changed workspace index
     {
-      try
-      {
+      try {
         spec = y->spectraNo(wi);
-        //ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,2),spec);
-        setSpectrum(row,spec);
-      }
-      catch(...)
-      {
+        // ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,2),spec);
+        setSpectrum(row, spec);
+      } catch (...) {
         // return to the previous state
         col = 2;
       }
     }
     if (col == 2) // changed spectrum number
     {
-      for(int i = 0;i<static_cast<int>(y->length()); ++i)
-      {
-        if ((*y)(i) == spec)
-        {
-          //ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,3),i);
-          setWSIndex(row,i);
+      for (int i = 0; i < static_cast<int>(y->length()); ++i) {
+        if ((*y)(i) == spec) {
+          // ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,3),i);
+          setWSIndex(row, i);
           return;
         }
       }
-      try
-      {
-        //ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,2),(*y)(0));
-        setSpectrum(row,int((*y)(0)));
+      try {
+        // ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,2),(*y)(0));
+        setSpectrum(row, int((*y)(0)));
+      } catch (...) {
       }
-      catch(...){}
     }
   }
 }
 
-void SequentialFitDialog::setSpectrum(int row,int spec)
-{
-  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,2),spec);
+void SequentialFitDialog::setSpectrum(int row, int spec) {
+  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row, 2),
+                                   spec);
 }
 
-void SequentialFitDialog::setWSIndex(int row,int wi)
-{
-  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,3),wi);
+void SequentialFitDialog::setWSIndex(int row, int wi) {
+  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row, 3), wi);
 }
 
-int SequentialFitDialog::rowCount()const
-{
-  return ui.tWorkspaces->rowCount();
-}
+int SequentialFitDialog::rowCount() const { return ui.tWorkspaces->rowCount(); }
 
-int SequentialFitDialog::defaultSpectrum()const
-{
+int SequentialFitDialog::defaultSpectrum() const {
   return ui.sbSpectrum->value();
 }
 
-QString SequentialFitDialog::name(int row)const
-{
-  return ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(row,0)).toString();
+QString SequentialFitDialog::name(int row) const {
+  return ui.tWorkspaces->model()
+      ->data(ui.tWorkspaces->model()->index(row, 0))
+      .toString();
 }
 
-void SequentialFitDialog::setRange(int row,double from,double to)
-{
+void SequentialFitDialog::setRange(int row, double from, double to) {
   QString range = QString::number(from) + ":" + QString::number(to);
-  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row,3),range);
+  ui.tWorkspaces->model()->setData(ui.tWorkspaces->model()->index(row, 3),
+                                   range);
 }
 
-void SequentialFitDialog::plotAgainstLog(bool yes)
-{
-  //ui.btnAddFile->setEnabled(yes);
-  //ui.btnAddWorkspace->setEnabled(yes);
-  //ui.btnDelete->setEnabled(yes);
+void SequentialFitDialog::plotAgainstLog(bool yes) {
+  // ui.btnAddFile->setEnabled(yes);
+  // ui.btnAddWorkspace->setEnabled(yes);
+  // ui.btnDelete->setEnabled(yes);
   ui.lblLogValue->setVisible(yes);
   ui.cbLogValue->setVisible(yes);
   ui.lblPeriod->setVisible(yes);
   ui.sbPeriod->setVisible(yes);
   ui.lblSpectrum->setVisible(yes);
   ui.sbSpectrum->setVisible(yes);
-  //if (yes)
+  // if (yes)
   //{// plot agains log value
   //  ui.tWorkspaces->showColumn(3);
   //  ui.tWorkspaces->horizontalHeaderItem(2)->setData(Qt::DisplayRole,"Spectrum");
@@ -525,13 +484,14 @@ void SequentialFitDialog::plotAgainstLog(bool yes)
   //    setSpectrum(row,spec);
   //  }
   //}
-  //else
+  // else
   //{// plot against "spectra" axis values
   //  if (rowCount() == 1)
   //  {
   //    ui.tWorkspaces->hideColumn(3);
   //    ui.tWorkspaces->horizontalHeaderItem(2)->setData(Qt::DisplayRole,"Range");
-  //    Mantid::API::MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+  //    Mantid::API::MatrixWorkspace_sptr ws =
+  //    boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
   //      Mantid::API::AnalysisDataService::Instance().retrieve(name(0).toStdString())
   //      );
   //    Mantid::API::Axis* y = ws->getAxis(1);
@@ -543,10 +503,8 @@ void SequentialFitDialog::plotAgainstLog(bool yes)
 /**
  * Update the dialog's controls apropriately.
  */
-void SequentialFitDialog::selectionChanged()
-{
-  ui.btnDelete->setEnabled( ui.tWorkspaces->selectionModel()->hasSelection() );
+void SequentialFitDialog::selectionChanged() {
+  ui.btnDelete->setEnabled(ui.tWorkspaces->selectionModel()->hasSelection());
 }
-
 }
 }
diff --git a/MantidQt/MantidWidgets/src/StringDialogEditor.cpp b/MantidQt/MantidWidgets/src/StringDialogEditor.cpp
index ade129f78b7cec64e1695fcdae8387ba1a1ba1c2..c9da15cc8c0a8ae5634104bc8c3c64574b8fa047 100644
--- a/MantidQt/MantidWidgets/src/StringDialogEditor.cpp
+++ b/MantidQt/MantidWidgets/src/StringDialogEditor.cpp
@@ -8,46 +8,43 @@
 #include <QDialog>
 #include <QSettings>
 
-
 /**
  * Do nothing to connect a manager.
  */
-void StringDialogEditorFactory::connectPropertyManager(QtStringPropertyManager*)
-{
-}
+void StringDialogEditorFactory::connectPropertyManager(
+    QtStringPropertyManager *) {}
 
 /**
  * Do nothing to disconnect a manager - it was never connected.
  */
-void StringDialogEditorFactory::disconnectPropertyManager(QtStringPropertyManager*)
-{
-}
+void StringDialogEditorFactory::disconnectPropertyManager(
+    QtStringPropertyManager *) {}
 
 /**
  * Constructor.
  * @param property :: A property to edit.
  * @param parent :: A widget parent for the editor widget.
  */
-StringDialogEditor::StringDialogEditor(QtProperty *property, QWidget *parent):QWidget(parent),m_property(property)
-{
+StringDialogEditor::StringDialogEditor(QtProperty *property, QWidget *parent)
+    : QWidget(parent), m_property(property) {
   QHBoxLayout *layout = new QHBoxLayout;
   m_lineEdit = new QLineEdit(this);
   layout->addWidget(m_lineEdit);
   setFocusProxy(m_lineEdit);
-  connect(m_lineEdit,SIGNAL(editingFinished()),this,SLOT(updateProperty()));
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(property->propertyManager());
-  if (mgr)
-  {
+  connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(updateProperty()));
+  QtStringPropertyManager *mgr =
+      dynamic_cast<QtStringPropertyManager *>(property->propertyManager());
+  if (mgr) {
     m_lineEdit->setText(mgr->value(property));
   }
 
-  QPushButton* button = new QPushButton("...",this);
-  button->setMaximumSize(20,1000000);
-  connect(button,SIGNAL(clicked()),this,SLOT(runDialog()));
+  QPushButton *button = new QPushButton("...", this);
+  button->setMaximumSize(20, 1000000);
+  connect(button, SIGNAL(clicked()), this, SLOT(runDialog()));
   layout->addWidget(button);
-  layout->setContentsMargins(0,0,0,0);
+  layout->setContentsMargins(0, 0, 0, 0);
   layout->setSpacing(0);
-  layout->setStretchFactor(button,0);
+  layout->setStretchFactor(button, 0);
   this->setLayout(layout);
 }
 
@@ -55,32 +52,24 @@ StringDialogEditor::StringDialogEditor(QtProperty *property, QWidget *parent):QW
  * Set the text in the editor.
  * @param txt :: A text to set.
  */
-void StringDialogEditor::setText(const QString& txt)
-{
+void StringDialogEditor::setText(const QString &txt) {
   m_lineEdit->setText(txt);
 }
 
 /**
  * Get the current text inside the editor.
  */
-QString StringDialogEditor::getText()const
-{
-  return m_lineEdit->text();
-}
+QString StringDialogEditor::getText() const { return m_lineEdit->text(); }
 
-StringDialogEditor::~StringDialogEditor()
-{
-}
+StringDialogEditor::~StringDialogEditor() {}
 
 /**
  * Slot which sets the property with the current text in the editor.
  */
-void StringDialogEditor::updateProperty()
-{
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(m_property->propertyManager());
-  if (mgr)
-  {
-    mgr->setValue(m_property,m_lineEdit->text());
+void StringDialogEditor::updateProperty() {
+  QtStringPropertyManager *mgr =
+      dynamic_cast<QtStringPropertyManager *>(m_property->propertyManager());
+  if (mgr) {
+    mgr->setValue(m_property, m_lineEdit->text());
   }
 }
-
diff --git a/MantidQt/MantidWidgets/src/StringEditorFactory.cpp b/MantidQt/MantidWidgets/src/StringEditorFactory.cpp
index c3f781b342d0a68fb9e600359cd9ee972bd2dd5a..6f0c9955bbdb5225d4240a387124b75770486c74 100644
--- a/MantidQt/MantidWidgets/src/StringEditorFactory.cpp
+++ b/MantidQt/MantidWidgets/src/StringEditorFactory.cpp
@@ -1,26 +1,25 @@
 #include "MantidQtMantidWidgets/StringEditorFactory.h"
 
-QWidget* StringEditorFactory::createEditorForManager(QtStringPropertyManager *, QtProperty *property,QWidget *parent)
-{
-  return new StringEditor(property,parent);
+QWidget *StringEditorFactory::createEditorForManager(QtStringPropertyManager *,
+                                                     QtProperty *property,
+                                                     QWidget *parent) {
+  return new StringEditor(property, parent);
 }
 
-StringEditor::StringEditor(QtProperty *property, QWidget *parent):QLineEdit(parent),m_property(property)
-{
-  connect(this,SIGNAL(editingFinished()),this,SLOT(updateProperty()));
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(property->propertyManager());
-  if (mgr)
-  {
+StringEditor::StringEditor(QtProperty *property, QWidget *parent)
+    : QLineEdit(parent), m_property(property) {
+  connect(this, SIGNAL(editingFinished()), this, SLOT(updateProperty()));
+  QtStringPropertyManager *mgr =
+      dynamic_cast<QtStringPropertyManager *>(property->propertyManager());
+  if (mgr) {
     setText(mgr->value(property));
   }
 }
 
-void StringEditor::updateProperty()
-{
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(m_property->propertyManager());
-  if (mgr)
-  {
-    mgr->setValue(m_property,this->text());
+void StringEditor::updateProperty() {
+  QtStringPropertyManager *mgr =
+      dynamic_cast<QtStringPropertyManager *>(m_property->propertyManager());
+  if (mgr) {
+    mgr->setValue(m_property, this->text());
   }
 }
-
diff --git a/MantidQt/MantidWidgets/src/WorkspaceEditorFactory.cpp b/MantidQt/MantidWidgets/src/WorkspaceEditorFactory.cpp
index b4bf073c5e731c763052b8e5b0e7ce606c083352..71aeceb986d967b823e712aea79869d18474dc04 100644
--- a/MantidQt/MantidWidgets/src/WorkspaceEditorFactory.cpp
+++ b/MantidQt/MantidWidgets/src/WorkspaceEditorFactory.cpp
@@ -1,32 +1,28 @@
 #include "MantidQtMantidWidgets/WorkspaceEditorFactory.h"
 
-namespace MantidQt
-{
-namespace MantidWidgets
-{
+namespace MantidQt {
+namespace MantidWidgets {
 
-QWidget* WorkspaceEditorFactory::createEditorForManager(QtStringPropertyManager *, QtProperty *property,QWidget *parent)
-{
-  return new WorkspaceEditor(property,parent);
+QWidget *WorkspaceEditorFactory::createEditorForManager(
+    QtStringPropertyManager *, QtProperty *property, QWidget *parent) {
+  return new WorkspaceEditor(property, parent);
 }
 
-WorkspaceEditor::WorkspaceEditor(QtProperty *property, QWidget *parent):WorkspaceSelector(parent),m_property(property)
-{
+WorkspaceEditor::WorkspaceEditor(QtProperty *property, QWidget *parent)
+    : WorkspaceSelector(parent), m_property(property) {
   this->insertItem(0, "");
   updateProperty(this->itemText(0));
   this->setCurrentIndex(0);
-  connect(this,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(updateProperty(const QString&)));
+  connect(this, SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(updateProperty(const QString &)));
 }
 
-void WorkspaceEditor::updateProperty(const QString& text)
-{
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(m_property->propertyManager());
-  if (mgr)
-  {
-    mgr->setValue(m_property,text);
+void WorkspaceEditor::updateProperty(const QString &text) {
+  QtStringPropertyManager *mgr =
+      dynamic_cast<QtStringPropertyManager *>(m_property->propertyManager());
+  if (mgr) {
+    mgr->setValue(m_property, text);
   }
 }
-
 }
 }
-
diff --git a/MantidQt/MantidWidgets/src/pythonCalc.cpp b/MantidQt/MantidWidgets/src/pythonCalc.cpp
index 49af808977ebe7e08aa94b8f49c8cf110ae26d26..87f9c8fcc34b235dbaee1121b245876926467dc6 100644
--- a/MantidQt/MantidWidgets/src/pythonCalc.cpp
+++ b/MantidQt/MantidWidgets/src/pythonCalc.cpp
@@ -17,64 +17,64 @@ using namespace MantidQt::MantidWidgets;
 /** returns a read-only reference to the Python script
 * @return an executable python script
 */
-const QString& pythonCalc::python() const
-{
-  return m_pyScript;
-}
+const QString &pythonCalc::python() const { return m_pyScript; }
 /** Protected constructor only desendents of this class can be construected
-*  @param interface :: this parent widget needs to have its runAsPythonScript signal connected to MantidPlot
+*  @param interface :: this parent widget needs to have its runAsPythonScript
+* signal connected to MantidPlot
 */
-pythonCalc::pythonCalc(QWidget *interface) : MantidWidget(interface),
-  m_pyScript(""), m_fails()
-{
-}
-/** Looks for error reports from the object passed to it.  If the map returned by the
-*  the objects invalid() method isn't empty it places displays red stars and throws
-*  @param validLbls :: the object with an invalid() map that contains a list of bad controls and error messages
+pythonCalc::pythonCalc(QWidget *interface)
+    : MantidWidget(interface), m_pyScript(""), m_fails() {}
+/** Looks for error reports from the object passed to it.  If the map returned
+* by the
+*  the objects invalid() method isn't empty it places displays red stars and
+* throws
+*  @param validLbls :: the object with an invalid() map that contains a list of
+* bad controls and error messages
 *  @return a description of any error
 */
-QString pythonCalc::checkNoErrors(const QHash<const QWidget * const, QLabel *> &validLbls) const
-{
-  // any errors in reading user values and constructing the script were inserted into a map, go through it
-  std::map<const QWidget * const, std::string>::const_iterator errs = m_fails.begin();
-  for ( ; errs != m_fails.end(); ++errs)
-  {// there are two maps, one links errors to the invalid control and one links controls to validators, put them together to load the errors into the validators
-    if ( validLbls.find(errs->first) == validLbls.end() )
-    {// can't find a validator label for this control, throw here, it'll get caught below and a dialog box will be raised
+QString pythonCalc::checkNoErrors(
+    const QHash<const QWidget *const, QLabel *> &validLbls) const {
+  // any errors in reading user values and constructing the script were inserted
+  // into a map, go through it
+  std::map<const QWidget *const, std::string>::const_iterator errs =
+      m_fails.begin();
+  for (; errs != m_fails.end();
+       ++errs) { // there are two maps, one links errors to the invalid control
+                 // and one links controls to validators, put them together to
+                 // load the errors into the validators
+    if (validLbls.find(errs->first) ==
+        validLbls.end()) { // can't find a validator label for this control,
+                           // throw here, it'll get caught below and a dialog
+                           // box will be raised
       return QString::fromStdString(errs->second);
     }
     validLbls[errs->first]->setToolTip(QString::fromStdString(errs->second));
     validLbls[errs->first]->show();
   }
-  if ( m_fails.size() > 0 )
-  {// some errors were displayed in the loop above
-    return "One or more settings are invalid. The invalid settings are\nmarked with a *, hold your mouse over the * for more information";
+  if (m_fails.size() > 0) { // some errors were displayed in the loop above
+    return "One or more settings are invalid. The invalid settings are\nmarked "
+           "with a *, hold your mouse over the * for more information";
   }
   return "";
 }
 /** Sets m_pyScript to the contents of the named file
 * @param pythonFile :: the name of the file to read
 */
-void pythonCalc::appendFile(const QString &pythonFile)
-{
+void pythonCalc::appendFile(const QString &pythonFile) {
   QFile py_script(pythonFile);
-  try
-  {
-    if ( !py_script.open(QIODevice::ReadOnly) )
-    {
-      throw Mantid::Kernel::Exception::FileError(std::string("Couldn't open python file "), pythonFile.toStdString());
+  try {
+    if (!py_script.open(QIODevice::ReadOnly)) {
+      throw Mantid::Kernel::Exception::FileError(
+          std::string("Couldn't open python file "), pythonFile.toStdString());
     }
     QTextStream stream(&py_script);
     QString line;
-    while( !stream.atEnd() )
-    {
+    while (!stream.atEnd()) {
       line = stream.readLine();
       m_pyScript.append(line + "\n");
     }
     py_script.close();
-  }
-  catch( ... )
-  {
+  } catch (...) {
     py_script.close();
     throw;
   }
@@ -82,27 +82,22 @@ void pythonCalc::appendFile(const QString &pythonFile)
 /** Sets m_pyScript to the contents of the named file
 * @param pythonFile :: the name of the file to read
 */
-void pythonCalc::loadFile(const QString &pythonFile)
-{
+void pythonCalc::loadFile(const QString &pythonFile) {
   m_pyScript.clear();
   QFile py_script(pythonFile);
-  try
-  {
-    if ( !py_script.open(QIODevice::ReadOnly) )
-    {
-      throw Mantid::Kernel::Exception::FileError(std::string("Couldn't open python file "), pythonFile.toStdString());
+  try {
+    if (!py_script.open(QIODevice::ReadOnly)) {
+      throw Mantid::Kernel::Exception::FileError(
+          std::string("Couldn't open python file "), pythonFile.toStdString());
     }
     QTextStream stream(&py_script);
     QString line;
-    while( !stream.atEnd() )
-    {
+    while (!stream.atEnd()) {
       line = stream.readLine();
       m_pyScript.append(line + "\n");
     }
     py_script.close();
-  }
-  catch( ... )
-  {
+  } catch (...) {
     py_script.close();
     throw;
   }
@@ -113,12 +108,11 @@ void pythonCalc::loadFile(const QString &pythonFile)
 * @param userVal :: points to the QLineEdit containing the user value
 * @param check :: the property that will be used to for validity checking
 */
-void pythonCalc::LEChkCp(QString pythonMark, const QLineEdit * const userVal, Property * const check)
-{
+void pythonCalc::LEChkCp(QString pythonMark, const QLineEdit *const userVal,
+                         Property *const check) {
   QString setting = userVal->text();
   std::string error = replaceErrsFind(pythonMark, setting, check);
-  if ( ! error.empty() )
-  {
+  if (!error.empty()) {
     m_fails[userVal] = error;
   }
 }
@@ -128,9 +122,10 @@ void pythonCalc::LEChkCp(QString pythonMark, const QLineEdit * const userVal, Pr
 * @param setting :: textual representation of the value
 * @param check :: the property that will be used to for validity checking
 */
-std::string pythonCalc::replaceErrsFind(QString pythonMark, const QString &setting, Property * const check)
-{
-  m_pyScript.replace(pythonMark, "'"+setting+"'");
+std::string pythonCalc::replaceErrsFind(QString pythonMark,
+                                        const QString &setting,
+                                        Property *const check) {
+  m_pyScript.replace(pythonMark, "'" + setting + "'");
   return check->setValue(setting.toStdString());
 }
 /** Appends the text in the QLineEdit to m_pyScript and stores any error
@@ -138,12 +133,11 @@ std::string pythonCalc::replaceErrsFind(QString pythonMark, const QString &setti
 * @param userVal :: points to the QLineEdit containing the user value
 * @param check :: the property that will be used to for validity checking
 */
-void pythonCalc::appendChk(const QLineEdit * const userVal, Property * const check)
-{
-  m_pyScript.append("'"+userVal->text()+"'");
+void pythonCalc::appendChk(const QLineEdit *const userVal,
+                           Property *const check) {
+  m_pyScript.append("'" + userVal->text() + "'");
   std::string error = check->setValue(userVal->text().toStdString());
-  if ( ! error.empty() )
-  {
+  if (!error.empty()) {
     m_fails[userVal] = error;
   }
 }
@@ -151,12 +145,11 @@ void pythonCalc::appendChk(const QLineEdit * const userVal, Property * const che
 *  a results summary
 *  @return any print statements executed in the Python script
 */
-QString pythonCalc::run()
-{
- //std::cerr<<"Script:\n";
- //std::cerr<<m_pyScript.toStdString()<<std::endl;
- QString tests = runPythonCode(m_pyScript, false);
- //std::cerr << "results\n";
- //std::cerr << tests.toStdString() << "\n";
- return tests;
+QString pythonCalc::run() {
+  // std::cerr<<"Script:\n";
+  // std::cerr<<m_pyScript.toStdString()<<std::endl;
+  QString tests = runPythonCode(m_pyScript, false);
+  // std::cerr << "results\n";
+  // std::cerr << tests.toStdString() << "\n";
+  return tests;
 }
diff --git a/MantidQt/MantidWidgets/test/AlgorithmHintStrategyTest.h b/MantidQt/MantidWidgets/test/AlgorithmHintStrategyTest.h
index 1dbc3e8ad4b61b1efbad3e0ff0455808fd37b12b..6117a20cd7438452cecc04d797feab60ee454996 100644
--- a/MantidQt/MantidWidgets/test/AlgorithmHintStrategyTest.h
+++ b/MantidQt/MantidWidgets/test/AlgorithmHintStrategyTest.h
@@ -46,9 +46,8 @@ class AlgorithmHintStrategyTest : public CxxTest::TestSuite {
       declareProperty(
           Mantid::Kernel::make_unique<Mantid::Kernel::ArrayProperty<double>>(
               "DoubleArray"));
-      declareProperty(
-          Mantid::Kernel::make_unique<
-              Mantid::Kernel::ArrayProperty<std::string>>("StringArray"));
+      declareProperty(Mantid::Kernel::make_unique<
+          Mantid::Kernel::ArrayProperty<std::string>>("StringArray"));
     };
     void exec() override { return; };
   };
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/DllOption.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/DllOption.h
index 8a0d7cec864ef308f715319a59d7e9bbc0baf22a..e332bbc92a6a4760cc427dfc47ef31e0b1d49431 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/DllOption.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/DllOption.h
@@ -9,4 +9,4 @@
 #define EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER DLLImport
 #endif
 
-#endif //MANTIDQT_MANTID_REFDETECTORVIEWER_DLLOPTION_H_
+#endif // MANTIDQT_MANTID_REFDETECTORVIEWER_DLLOPTION_H_
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefIVConnections.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefIVConnections.h
index 147a2c2a1f75a65717f1829c14710041967795ac..2d8ab95d2d0a24871a37f9506d1def2851284064 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefIVConnections.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefIVConnections.h
@@ -46,29 +46,25 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefIVConnections: public QWidget
-{
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefIVConnections : public QWidget {
   Q_OBJECT
 
 public:
   /// Construct the object that links the GUI components to the other specifed
   /// higher level objects.
-  RefIVConnections( Ui_RefImageViewer*          ui,
-                    RefImageView*               imageView,
-                    RefImageDisplay*            imageDisplay,
-                    SpectrumView::GraphDisplay* hGraphDisplay,
-                    SpectrumView::GraphDisplay* vGraphDisplay );
+  RefIVConnections(Ui_RefImageViewer *ui, RefImageView *imageView,
+                   RefImageDisplay *imageDisplay,
+                   SpectrumView::GraphDisplay *hGraphDisplay,
+                   SpectrumView::GraphDisplay *vGraphDisplay);
 
   ~RefIVConnections() override;
 
   /// Set the pix map that shows the color scale from the specified color maps
-  void showColorScale( std::vector<QRgb> & positiveColorTable,
-                       std::vector<QRgb> & negativeColorTable );
+  void showColorScale(std::vector<QRgb> &positiveColorTable,
+                      std::vector<QRgb> &negativeColorTable);
 
 public slots:
   void closeViewer();
@@ -105,21 +101,19 @@ private:
                      MantidQt::SpectrumView::ColorMaps::ColorScale negative);
 
 private:
-
-  Ui_RefImageViewer*            m_ivUI;
-  RefImageView*                 m_ivMainWindow;
-  RefImageDisplay*              m_imageDisplay;
-  SpectrumView::GraphDisplay*   m_hGraphDisplay;
-  SpectrumView::GraphDisplay*   m_vGraphDisplay;
-  SpectrumView::TrackingPicker* m_imagePicker;
-  SpectrumView::TrackingPicker* m_imagePicker2;
-  SpectrumView::TrackingPicker* m_hGraphPicker;
-  SpectrumView::TrackingPicker* m_vGraphPicker;
-  QActionGroup*                 m_colorGroup;
-
+  Ui_RefImageViewer *m_ivUI;
+  RefImageView *m_ivMainWindow;
+  RefImageDisplay *m_imageDisplay;
+  SpectrumView::GraphDisplay *m_hGraphDisplay;
+  SpectrumView::GraphDisplay *m_vGraphDisplay;
+  SpectrumView::TrackingPicker *m_imagePicker;
+  SpectrumView::TrackingPicker *m_imagePicker2;
+  SpectrumView::TrackingPicker *m_hGraphPicker;
+  SpectrumView::TrackingPicker *m_vGraphPicker;
+  QActionGroup *m_colorGroup;
 };
 
 } // namespace RefDetectorViewer
 } // namespace MantidQt
 
-#endif  // REF_IV_CONNECTIONS_H
+#endif // REF_IV_CONNECTIONS_H
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageDisplay.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageDisplay.h
index df7483547dfcdcee3f014ca1b9bf59e0af8adfb6..7031fe437d02a8d0d655f533056bbc8f9fc2c9f9 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageDisplay.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageDisplay.h
@@ -1,5 +1,5 @@
-#ifndef  REF_IMAGE_DISPLAY_H
-#define  REF_IMAGE_DISPLAY_H
+#ifndef REF_IMAGE_DISPLAY_H
+#define REF_IMAGE_DISPLAY_H
 
 #include "MantidQtSpectrumViewer/SpectrumDisplay.h"
 #include "MantidQtRefDetectorViewer/RefSliderHandler.h"
@@ -7,15 +7,16 @@
 #include "MantidQtRefDetectorViewer/RefLimitsHandler.h"
 #include "DllOption.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
-/** This class extends the SpectrumViewer::SpectrumDisplay class to communicate left-clicks
-    to the RefLimitsHandler (and thence to the peak/background/TOF line edits in the gui)
+/** This class extends the SpectrumViewer::SpectrumDisplay class to communicate
+   left-clicks
+    to the RefLimitsHandler (and thence to the peak/background/TOF line edits in
+   the gui)
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -35,31 +36,29 @@ namespace RefDetectorViewer
     Code Documentation is available at <http://doxygen.mantidproject.org>
  */
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImageDisplay : public SpectrumView::SpectrumDisplay
-{
-  public:
-     /// Make a SpectrumDisplay to display with the given widgets and controls
-     RefImageDisplay( QwtPlot*                    imagePlot,
-                      RefSliderHandler*           sliderHandler,
-                      RefRangeHandler*            rangeHandler,
-                      RefLimitsHandler*           limitsHandler,
-                      SpectrumView::GraphDisplay* hGraph,
-                      SpectrumView::GraphDisplay* vGraph,
-                      QTableWidget*               tableWidget);
-
-     ~RefImageDisplay() override;
-
-     /// Record the point that the user is currently pointing at with the mouse
-     /// default right click (mouseClick = 2)
-     QPair<double, double> setPointedAtPoint(QPoint point, int mouseClick = 2,
-                                             bool isFirst = true) override;
-
-   private:
-     RefLimitsHandler*    m_limitsHandler; // Owned by RefImagePlotItem
-
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImageDisplay
+    : public SpectrumView::SpectrumDisplay {
+public:
+  /// Make a SpectrumDisplay to display with the given widgets and controls
+  RefImageDisplay(QwtPlot *imagePlot, RefSliderHandler *sliderHandler,
+                  RefRangeHandler *rangeHandler,
+                  RefLimitsHandler *limitsHandler,
+                  SpectrumView::GraphDisplay *hGraph,
+                  SpectrumView::GraphDisplay *vGraph,
+                  QTableWidget *tableWidget);
+
+  ~RefImageDisplay() override;
+
+  /// Record the point that the user is currently pointing at with the mouse
+  /// default right click (mouseClick = 2)
+  QPair<double, double> setPointedAtPoint(QPoint point, int mouseClick = 2,
+                                          bool isFirst = true) override;
+
+private:
+  RefLimitsHandler *m_limitsHandler; // Owned by RefImagePlotItem
 };
 
 } // namespace RefDetectorViewer
 } // namespace MantidQt
 
-#endif   // REF_IMAGE_DISPLAY_H
+#endif // REF_IMAGE_DISPLAY_H
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImagePlotItem.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImagePlotItem.h
index b1a431ce4b9e3af5a6772411149ee9c72b5bedfe..65a493f01281262e13b233f50cd0d3d3f1798b8a 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImagePlotItem.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImagePlotItem.h
@@ -5,14 +5,13 @@
 #include "DllOption.h"
 #include "MantidQtRefDetectorViewer/RefLimitsHandler.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 /** This class is responsible for actually drawing the image data onto
     a QwtPlot for the SpectrumView data viewer.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -32,12 +31,12 @@ namespace RefDetectorViewer
     Code Documentation is available at <http://doxygen.mantidproject.org>
  */
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImagePlotItem : public SpectrumView::SpectrumPlotItem
-{
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImagePlotItem
+    : public SpectrumView::SpectrumPlotItem {
 
 public:
   /// Construct basic plot item with NO data to plot.
-  RefImagePlotItem(const RefLimitsHandler * const limitsHandler);
+  RefImagePlotItem(const RefLimitsHandler *const limitsHandler);
 
   ~RefImagePlotItem();
 
@@ -47,12 +46,10 @@ public:
                     const QRect &canvasRect) const override;
 
 private:
-  const RefLimitsHandler * const m_limitsHandler;
-
+  const RefLimitsHandler *const m_limitsHandler;
 };
 
 } // namespace RefDetectorViewer
 } // namespace MantidQt
 
-
-#endif  // REF_IMAGE_PLOT_ITEM_H
+#endif // REF_IMAGE_PLOT_ITEM_H
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageView.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageView.h
index 5ae9af3be9b74167b8cd9d36daf0570749262254..7fb5b421a9fb542f4d134176790f4f6a3d058a6d 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageView.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefImageView.h
@@ -1,5 +1,5 @@
-#ifndef  REF_IMAGE_VIEW_H
-#define  REF_IMAGE_VIEW_H
+#ifndef REF_IMAGE_VIEW_H
+#define REF_IMAGE_VIEW_H
 
 #include <QMainWindow>
 #include <QtGui>
@@ -39,47 +39,39 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace Ui
-{
+namespace Ui {
 class RefImageViewer;
 }
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 class RefSliderHandler;
 class RefRangeHandler;
 class RefImageDisplay;
 class RefIVConnections;
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImageView : public QMainWindow
-{
-  public:
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefImageView : public QMainWindow {
+public:
+  /// Construct an RefImageView to display data from the specified data source
+  RefImageView(SpectrumView::SpectrumDataSource_sptr dataSource, int peakMin,
+               int peakMax, int backMin, int backMax, int tofMin, int tofMax);
 
-     /// Construct an RefImageView to display data from the specified data source
-     RefImageView( SpectrumView::SpectrumDataSource_sptr dataSource,
-                   int peakMin, int peakMax,
-                   int backMin, int backMax,
-                   int tofMin,  int tofMax);
+  ~RefImageView() override;
 
-     ~RefImageView() override;
+  RefIVConnections *getIVConnections();
 
-    RefIVConnections* getIVConnections();
-
-  private:
-    SpectrumView::GraphDisplay* m_hGraph;
-    SpectrumView::GraphDisplay* m_vGraph;
-
-    Ui::RefImageViewer* m_ui;
-    RefSliderHandler*   m_sliderHandler;
-    RefRangeHandler*    m_rangeHandler;
-    RefImageDisplay*    m_imageDisplay;
-    RefIVConnections*   m_ivConnections;
+private:
+  SpectrumView::GraphDisplay *m_hGraph;
+  SpectrumView::GraphDisplay *m_vGraph;
 
+  Ui::RefImageViewer *m_ui;
+  RefSliderHandler *m_sliderHandler;
+  RefRangeHandler *m_rangeHandler;
+  RefImageDisplay *m_imageDisplay;
+  RefIVConnections *m_ivConnections;
 };
 
 } // namespace RefDetectorViewer
 } // namespace MantidQt
 
-#endif   // REF_IMAGE_VIEW_H
+#endif // REF_IMAGE_VIEW_H
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefLimitsHandler.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefLimitsHandler.h
index 0e661501deea56cc2aaa4b57e4acb408f378eed8..b0c0fed4e95fbeedcae465fe00c08d413ae97eea 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefLimitsHandler.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefLimitsHandler.h
@@ -3,13 +3,12 @@
 
 #include "ui_RefImageView.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 /** Retrieves the states of the peak/background/TOF limit settings from the gui
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -29,11 +28,10 @@ namespace RefDetectorViewer
     Code Documentation is available at <http://doxygen.mantidproject.org>
  */
 
-class RefLimitsHandler
-{
+class RefLimitsHandler {
 public:
   /// Construct object to manage range (peak/back/TOF) controls in the UI
-  RefLimitsHandler( Ui_RefImageViewer* ivUI );
+  RefLimitsHandler(Ui_RefImageViewer *ivUI);
 
   /// get peak, back and tof values
   int getPeakLeft() const;
@@ -53,8 +51,7 @@ public:
   void setActiveValue(const double x, const double y);
 
 private:
-  const Ui_RefImageViewer* const m_ui;
-
+  const Ui_RefImageViewer *const m_ui;
 };
 
 } // namespace RefDetectorViewer
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefMatrixWSImageView.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefMatrixWSImageView.h
index 8afbf42ac00ff8ffe89cab4438a794db2e981fd1..8a1211869f6eb520d72dc893bbe9311ad2def7ad 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefMatrixWSImageView.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefMatrixWSImageView.h
@@ -36,31 +36,25 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 class RefIVConnections;
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefMatrixWSImageView
-{
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefMatrixWSImageView {
 
 public:
   /// Construct an image viewer for the specifed MatrixWorkspace
-  RefMatrixWSImageView ( Mantid::API::MatrixWorkspace_sptr /*mat_ws*/ );
+  RefMatrixWSImageView(Mantid::API::MatrixWorkspace_sptr /*mat_ws*/);
 
-  RefMatrixWSImageView( QString wpsName,
-                        int peakMin, int peakMax,
-                        int backMin, int backMax,
-                        int tofMin,  int tofMax);
+  RefMatrixWSImageView(QString wpsName, int peakMin, int peakMax, int backMin,
+                       int backMax, int tofMin, int tofMax);
 
-  RefIVConnections* getConnections();
+  RefIVConnections *getConnections();
 
   ~RefMatrixWSImageView();
 
 private:
   RefImageView *m_imageView;
-
 };
 
 } // namespace RefDetectorViewer
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefRangeHandler.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefRangeHandler.h
index 5817139a88fbb007c890be017be3a2fdbf784de3..7e3fe7e6cbfd36ad9e70446384535e31cd11c682 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefRangeHandler.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefRangeHandler.h
@@ -36,37 +36,33 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefRangeHandler : public SpectrumView::IRangeHandler
-{
-  public:
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefRangeHandler
+    : public SpectrumView::IRangeHandler {
+public:
+  /// Construct object to manage min, max and step controls in the UI
+  RefRangeHandler(Ui_RefImageViewer *ivUI);
 
-    /// Construct object to manage min, max and step controls in the UI
-    RefRangeHandler( Ui_RefImageViewer* ivUI );
+  /// Configure min, max and step controls for the specified data source
+  void configureRangeControls(
+      SpectrumView::SpectrumDataSource_sptr dataSource) override;
 
-    /// Configure min, max and step controls for the specified data source
-    void configureRangeControls(
-        SpectrumView::SpectrumDataSource_sptr dataSource) override;
+  /// Get the range of data to display in the image, from GUI controls
+  void getRange(double &min, double &max, double &step) override;
 
-    /// Get the range of data to display in the image, from GUI controls
-    void getRange(double &min, double &max, double &step) override;
+  /// Set the values displayed in the GUI controls
+  void setRange(double min, double max, double step, char type);
 
-    /// Set the values displayed in the GUI controls
-    void setRange( double min, double max, double step, char type );
-
-  private:
-    Ui_RefImageViewer* m_ivUI;
-
-    double m_totalMinX;
-    double m_totalMaxX;
-    double m_totalMinY;
-    double m_totalMaxY;
-    size_t m_totalNSteps;
+private:
+  Ui_RefImageViewer *m_ivUI;
 
+  double m_totalMinX;
+  double m_totalMaxX;
+  double m_totalMinY;
+  double m_totalMaxY;
+  size_t m_totalNSteps;
 };
 
 } // namespace RefDetectorViewer
diff --git a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefSliderHandler.h b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefSliderHandler.h
index 7675f5ae038969a9850a1a73147f45e7c954c1f6..4bed0f0bbb593786d9680dd455cd681fd935ca63 100644
--- a/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefSliderHandler.h
+++ b/MantidQt/RefDetectorViewer/inc/MantidQtRefDetectorViewer/RefSliderHandler.h
@@ -38,47 +38,41 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
+class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefSliderHandler
+    : public SpectrumView::ISliderHandler {
+public:
+  /// Construct object to manage image scrollbars from the specified UI
+  RefSliderHandler(Ui_RefImageViewer *ivUI);
 
-class EXPORT_OPT_MANTIDQT_REFDETECTORVIEWER RefSliderHandler : public SpectrumView::ISliderHandler
-{
-  public:
-    /// Construct object to manage image scrollbars from the specified UI
-    RefSliderHandler( Ui_RefImageViewer* ivUI );
+  /// Configure the image scrollbars for the specified data and drawing area
+  void
+  configureSliders(QRect drawArea,
+                   SpectrumView::SpectrumDataSource_sptr dataSource) override;
 
-    /// Configure the image scrollbars for the specified data and drawing area
-    void
-    configureSliders(QRect drawArea,
-                     SpectrumView::SpectrumDataSource_sptr dataSource) override;
+  /// Configure the horizontal scrollbar to cover the specified range
+  void configureHSlider(int nDataSteps, int nPixels) override;
 
-    /// Configure the horizontal scrollbar to cover the specified range
-    void configureHSlider(int nDataSteps, int nPixels) override;
+  /// Return true if the image horizontal scrollbar is enabled.
+  bool hSliderOn() override;
 
-    /// Return true if the image horizontal scrollbar is enabled.
-    bool hSliderOn() override;
+  /// Return true if the image vertical scrollbar is enabled.
+  bool vSliderOn() override;
 
-    /// Return true if the image vertical scrollbar is enabled.
-    bool vSliderOn() override;
+  /// Get the range of columns to display in the image.
+  void getHSliderInterval(int &xMin, int &xMax) override;
 
-    /// Get the range of columns to display in the image.
-    void getHSliderInterval(int &xMin, int &xMax) override;
+  /// Get the range of rows to display in the image.
+  void getVSliderInterval(int &yMin, int &yMax) override;
 
-    /// Get the range of rows to display in the image.
-    void getVSliderInterval(int &yMin, int &yMax) override;
-
-  private:
-    /// Configure the specified scrollbar to cover the specified range
-    void configureSlider( QScrollBar* scrollBar,
-                          int         nDataSteps,
-                          int         nPixels,
-                          int         val );
-
-    Ui_RefImageViewer*   m_ivUI;
+private:
+  /// Configure the specified scrollbar to cover the specified range
+  void configureSlider(QScrollBar *scrollBar, int nDataSteps, int nPixels,
+                       int val);
 
+  Ui_RefImageViewer *m_ivUI;
 };
 
 } // namespace RefDetectorViewer
diff --git a/MantidQt/RefDetectorViewer/src/RefDetectorViewDemo.cpp b/MantidQt/RefDetectorViewer/src/RefDetectorViewDemo.cpp
index 1b1e345cf845a06d583b199a8a3cdaa859bdde2b..5983380f7fd232c5c72d6f9185e834bfe3552d59 100644
--- a/MantidQt/RefDetectorViewer/src/RefDetectorViewDemo.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefDetectorViewDemo.cpp
@@ -23,67 +23,63 @@ using namespace RefDetectorViewer;
  * @param total_cols   The number of columns the test data should be divided
  *                     into
  */
-std::vector<float> makeTestData( double total_xmin, double total_xmax,
-                                 double total_ymin, double total_ymax,
-                                 size_t total_rows, size_t total_cols )
-{
+std::vector<float> makeTestData(double total_xmin, double total_xmax,
+                                double total_ymin, double total_ymax,
+                                size_t total_rows, size_t total_cols) {
   double x;
   double y;
-  std::vector<float> data(total_rows*total_cols);
-
-  for ( size_t row = 0; row < total_rows; row++ )
-    for ( size_t col = 0; col < total_cols; col++ )
-    {
-       x = ((double)col - (double)total_cols/2.0)/(double)total_cols;
-       y = ((double)row - (double)total_rows/2.0)/(double)total_rows;
-       data[ row * total_cols + col ] =
-                                     (float)(1000.0 * cos( (x*x + y*y)*20.0 ));
+  std::vector<float> data(total_rows * total_cols);
+
+  for (size_t row = 0; row < total_rows; row++)
+    for (size_t col = 0; col < total_cols; col++) {
+      x = ((double)col - (double)total_cols / 2.0) / (double)total_cols;
+      y = ((double)row - (double)total_rows / 2.0) / (double)total_rows;
+      data[row * total_cols + col] =
+          (float)(1000.0 * cos((x * x + y * y) * 20.0));
     }
-                                                // mark a row 1/4 way up
-  double point = (total_ymax - total_ymin)/4 + total_ymin;
+  // mark a row 1/4 way up
+  double point = (total_ymax - total_ymin) / 4 + total_ymin;
   double mark_row = 0;
-  SpectrumView::SVUtils::Interpolate( total_ymin, total_ymax, point,
-                               0.0, (double)total_rows, mark_row );
-
-  size_t row_offset = (int)(mark_row) * total_cols;
-  for ( size_t col = 0; col < total_cols; col++ )
-  {
-     data[ row_offset-total_cols + col ] = 0;
-     data[ row_offset            + col ] = 0;
-     data[ row_offset+total_cols + col ] = 0;
+  SpectrumView::SVUtils::Interpolate(total_ymin, total_ymax, point, 0.0,
+                                     (double)total_rows, mark_row);
+
+  size_t row_offset = (int)(mark_row)*total_cols;
+  for (size_t col = 0; col < total_cols; col++) {
+    data[row_offset - total_cols + col] = 0;
+    data[row_offset + col] = 0;
+    data[row_offset + total_cols + col] = 0;
   }
-                                                 // mark a col 1/10 way over
-  point = (total_xmax - total_xmin)/10 + total_xmin;
+  // mark a col 1/10 way over
+  point = (total_xmax - total_xmin) / 10 + total_xmin;
   double mark_col = 0;
-  SpectrumView::SVUtils::Interpolate( total_xmin, total_xmax, point,
-                               0.0, (double)total_cols, mark_col );
-
-  size_t col_offset = (int)( mark_col );
-  for ( size_t row = 0; row < total_rows; row++ )
-  {
-     data[ row * total_cols + col_offset-1 ] = 0;
-     data[ row * total_cols + col_offset   ] = 0;
-     data[ row * total_cols + col_offset+1 ] = 0;
+  SpectrumView::SVUtils::Interpolate(total_xmin, total_xmax, point, 0.0,
+                                     (double)total_cols, mark_col);
+
+  size_t col_offset = (int)(mark_col);
+  for (size_t row = 0; row < total_rows; row++) {
+    data[row * total_cols + col_offset - 1] = 0;
+    data[row * total_cols + col_offset] = 0;
+    data[row * total_cols + col_offset + 1] = 0;
   }
 
   return data;
 }
 
+int main(int argc, char **argv) {
+  QApplication a(argc, argv);
 
-int main( int argc, char **argv )
-{
-  QApplication a( argc, argv );
-
-  std::vector<float> data = makeTestData( 10, 110, 220, 320, 2000, 2000 );
+  std::vector<float> data = makeTestData(10, 110, 220, 320, 2000, 2000);
 
   SpectrumView::ArrayDataSource_sptr source =
-                   SpectrumView::ArrayDataSource_sptr( new SpectrumView::ArrayDataSource( 10, 110, 220, 320, 2000, 2000, data ) );
+      SpectrumView::ArrayDataSource_sptr(new SpectrumView::ArrayDataSource(
+          10, 110, 220, 320, 2000, 2000, data));
 
-  MantidQt::RefDetectorViewer::RefImageView image_view( source, 10, 110, 220, 320, 200, 500 );
+  MantidQt::RefDetectorViewer::RefImageView image_view(source, 10, 110, 220,
+                                                       320, 200, 500);
 
-                       // Don't delete on close in this case, since image_view
-                       // will be deleted when the application ends
-  image_view.setAttribute(Qt::WA_DeleteOnClose,false);
+  // Don't delete on close in this case, since image_view
+  // will be deleted when the application ends
+  image_view.setAttribute(Qt::WA_DeleteOnClose, false);
 
   return a.exec();
 }
diff --git a/MantidQt/RefDetectorViewer/src/RefIVConnections.cpp b/MantidQt/RefDetectorViewer/src/RefIVConnections.cpp
index b3c3ab4f2136f4965e2075063add9ee50dcd8829..22c8eeb41248b504bcba53bb4cd70580b7e51a54 100644
--- a/MantidQt/RefDetectorViewer/src/RefIVConnections.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefIVConnections.cpp
@@ -3,10 +3,8 @@
 
 #include "MantidQtRefDetectorViewer/RefIVConnections.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 using namespace SpectrumView;
 
 /**
@@ -24,17 +22,13 @@ using namespace SpectrumView;
  * @param vGraphDisplay  The GraphDisplay object that will display
  *                       vertical cuts through the image
  */
-RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
-                                    RefImageView*       ivMainWindow,
-                                    RefImageDisplay*    imageDisplay,
-                                    GraphDisplay*       hGraphDisplay,
-                                    GraphDisplay*       vGraphDisplay ) :
-  m_ivUI(ui),
-  m_ivMainWindow(ivMainWindow),
-  m_imageDisplay(imageDisplay),
-  m_hGraphDisplay(hGraphDisplay),
-  m_vGraphDisplay(vGraphDisplay)
-{
+RefIVConnections::RefIVConnections(Ui_RefImageViewer *ui,
+                                   RefImageView *ivMainWindow,
+                                   RefImageDisplay *imageDisplay,
+                                   GraphDisplay *hGraphDisplay,
+                                   GraphDisplay *vGraphDisplay)
+    : m_ivUI(ui), m_ivMainWindow(ivMainWindow), m_imageDisplay(imageDisplay),
+      m_hGraphDisplay(hGraphDisplay), m_vGraphDisplay(vGraphDisplay) {
   // First disable a few un-implemented controls
   m_ivUI->menuGraph_Selected->setDisabled(true);
   m_ivUI->actionClear_Selections->setDisabled(true);
@@ -44,37 +38,37 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
   m_ivUI->actionGraph_Rebinned_Data->setDisabled(true);
   m_ivUI->menuHelp->setDisabled(true);
 
-  QObject::connect( m_ivUI->actionClose, SIGNAL(triggered()),
-      this, SLOT(closeViewer()) );
+  QObject::connect(m_ivUI->actionClose, SIGNAL(triggered()), this,
+                   SLOT(closeViewer()));
 
   // Now set up the GUI components
   QList<int> image_sizes;
-  image_sizes.append( 500 );
-  image_sizes.append( 250 );
-  m_ivUI->imageSplitter->setSizes( image_sizes );
+  image_sizes.append(500);
+  image_sizes.append(250);
+  m_ivUI->imageSplitter->setSizes(image_sizes);
   QList<int> vgraph_sizes;
-  vgraph_sizes.append( 500 );
-  vgraph_sizes.append( 30 );
-  vgraph_sizes.append( 220 );
-  m_ivUI->vgraphSplitter->setSizes( vgraph_sizes );
+  vgraph_sizes.append(500);
+  vgraph_sizes.append(30);
+  vgraph_sizes.append(220);
+  m_ivUI->vgraphSplitter->setSizes(vgraph_sizes);
 
   QList<int> horiz_sizes;
-  horiz_sizes.append( 250 );
-  horiz_sizes.append( 750 );
-  horiz_sizes.append( 150 );
-  m_ivUI->left_right_splitter->setSizes( horiz_sizes );
+  horiz_sizes.append(250);
+  horiz_sizes.append(750);
+  horiz_sizes.append(150);
+  m_ivUI->left_right_splitter->setSizes(horiz_sizes);
 
-  m_ivUI->imageHorizontalScrollBar->setFocusPolicy( Qt::StrongFocus );
+  m_ivUI->imageHorizontalScrollBar->setFocusPolicy(Qt::StrongFocus);
   m_ivUI->imageHorizontalScrollBar->setMinimum(20);
   m_ivUI->imageHorizontalScrollBar->setMaximum(2000);
   m_ivUI->imageHorizontalScrollBar->setPageStep(30);
-  m_ivUI->imageHorizontalScrollBar->setSingleStep(30/2);
+  m_ivUI->imageHorizontalScrollBar->setSingleStep(30 / 2);
 
-  m_ivUI->imageVerticalScrollBar->setFocusPolicy( Qt::StrongFocus );
+  m_ivUI->imageVerticalScrollBar->setFocusPolicy(Qt::StrongFocus);
   m_ivUI->imageVerticalScrollBar->setMinimum(0);
   m_ivUI->imageVerticalScrollBar->setMaximum(10000000);
   m_ivUI->imageVerticalScrollBar->setPageStep(500);
-  m_ivUI->imageVerticalScrollBar->setSingleStep(500/2);
+  m_ivUI->imageVerticalScrollBar->setSingleStep(500 / 2);
 
   m_ivUI->action_Hscroll->setCheckable(true);
   m_ivUI->action_Hscroll->setChecked(false);
@@ -94,12 +88,12 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
   //  m_ivUI->graph_max_slider->setTickPosition(QSlider::TicksBelow);
   //  m_ivUI->graph_max_slider->setSliderPosition(100);
 
-  m_imagePicker2 = new TrackingPicker( m_ivUI->imagePlot->canvas() );
+  m_imagePicker2 = new TrackingPicker(m_ivUI->imagePlot->canvas());
   m_imagePicker2->setMousePattern(QwtPicker::MouseSelect1, Qt::LeftButton);
   m_imagePicker2->setTrackerMode(QwtPicker::ActiveOnly);
   m_imagePicker2->setRubberBandPen(QColor(Qt::gray));
 
-  m_imagePicker = new TrackingPicker( m_ivUI->imagePlot->canvas() );
+  m_imagePicker = new TrackingPicker(m_ivUI->imagePlot->canvas());
   m_imagePicker->setMousePattern(QwtPicker::MouseSelect1, Qt::RightButton);
   m_imagePicker->setTrackerMode(QwtPicker::ActiveOnly);
   m_imagePicker->setRubberBandPen(QColor(Qt::blue));
@@ -107,11 +101,11 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
   // Point selections & connection works on mouse release
   m_imagePicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_imagePicker->setSelectionFlags(QwtPicker::PointSelection |
-      QwtPicker::DragSelection  );
+                                   QwtPicker::DragSelection);
 
   m_imagePicker2->setRubberBand(QwtPicker::CrossRubberBand);
   m_imagePicker2->setSelectionFlags(QwtPicker::PointSelection |
-      QwtPicker::DragSelection  );
+                                    QwtPicker::DragSelection);
 
   /*
      QObject::connect( m_imagePicker, SIGNAL(selected(const QwtPolygon &)),
@@ -143,54 +137,54 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
      QwtPicker::ClickSelection  );
      */
 
-  QObject::connect( m_imagePicker2, SIGNAL(mouseMoved()),
-      this, SLOT(imagePicker2Moved()) );
+  QObject::connect(m_imagePicker2, SIGNAL(mouseMoved()), this,
+                   SLOT(imagePicker2Moved()));
 
-  QObject::connect( m_imagePicker, SIGNAL(mouseMoved()),
-      this, SLOT(imagePickerMoved()) );
+  QObject::connect(m_imagePicker, SIGNAL(mouseMoved()), this,
+                   SLOT(imagePickerMoved()));
 
   /*
    * Connections on the peak, back and TOF input boxes
    */
-  QObject::connect(m_ivUI->lineEdit_peakLeft, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-  QObject::connect(m_ivUI->lineEdit_peakRight, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-  QObject::connect(m_ivUI->lineEdit_backLeft, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-  QObject::connect(m_ivUI->lineEdit_backRight, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-  QObject::connect(m_ivUI->lineEdit_TOFmin, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-  QObject::connect(m_ivUI->lineEdit_TOFmax, SIGNAL(returnPressed()),
-      this, SLOT(editManualInput()) );
-
-  QObject::connect(m_ivUI->imageSplitter, SIGNAL(splitterMoved(int,int)),
-      this, SLOT(imageSplitterMoved()) );
-
-  QObject::connect(m_ivUI->x_min_input, SIGNAL( returnPressed() ),
-      this, SLOT(imageHorizontalRangeChanged()) );
-
-  QObject::connect(m_ivUI->x_max_input, SIGNAL( returnPressed() ),
-      this, SLOT(imageHorizontalRangeChanged()) );
+  QObject::connect(m_ivUI->lineEdit_peakLeft, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+  QObject::connect(m_ivUI->lineEdit_peakRight, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+  QObject::connect(m_ivUI->lineEdit_backLeft, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+  QObject::connect(m_ivUI->lineEdit_backRight, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+  QObject::connect(m_ivUI->lineEdit_TOFmin, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+  QObject::connect(m_ivUI->lineEdit_TOFmax, SIGNAL(returnPressed()), this,
+                   SLOT(editManualInput()));
+
+  QObject::connect(m_ivUI->imageSplitter, SIGNAL(splitterMoved(int, int)), this,
+                   SLOT(imageSplitterMoved()));
+
+  QObject::connect(m_ivUI->x_min_input, SIGNAL(returnPressed()), this,
+                   SLOT(imageHorizontalRangeChanged()));
+
+  QObject::connect(m_ivUI->x_max_input, SIGNAL(returnPressed()), this,
+                   SLOT(imageHorizontalRangeChanged()));
 
   //  QObject::connect(m_ivUI->step_input, SIGNAL( returnPressed() ),
   //                   this, SLOT(image_horizontal_range_changed()) );
 
   QObject::connect(m_ivUI->imageVerticalScrollBar, SIGNAL(valueChanged(int)),
-      this, SLOT(vScrollBarMoved()) );
+                   this, SLOT(vScrollBarMoved()));
 
   QObject::connect(m_ivUI->imageHorizontalScrollBar, SIGNAL(valueChanged(int)),
-      this, SLOT(hScrollBarMoved()) );
+                   this, SLOT(hScrollBarMoved()));
 
-  QObject::connect(m_ivUI->action_Hscroll, SIGNAL(changed()),
-      this, SLOT(toggleHScroll()) );
+  QObject::connect(m_ivUI->action_Hscroll, SIGNAL(changed()), this,
+                   SLOT(toggleHScroll()));
 
-  QObject::connect(m_ivUI->action_Vscroll, SIGNAL(changed()),
-      this, SLOT(toggleVScroll()) );
+  QObject::connect(m_ivUI->action_Vscroll, SIGNAL(changed()), this,
+                   SLOT(toggleVScroll()));
 
-  QObject::connect(m_ivUI->intensity_slider, SIGNAL(valueChanged(int)),
-      this, SLOT(intensitySliderMoved()) );
+  QObject::connect(m_ivUI->intensity_slider, SIGNAL(valueChanged(int)), this,
+                   SLOT(intensitySliderMoved()));
 
   //  QObject::connect(m_ivUI->graph_max_slider, SIGNAL(valueChanged(int)),
   //                   this, SLOT(graphRangeChanged()) );
@@ -213,8 +207,7 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
   auto positiveColorTable = ColorMaps::GetColorMap(ColorMaps::HEAT, 256);
   auto negativeColorTable = ColorMaps::GetColorMap(ColorMaps::GRAY, 256);
 
-  showColorScale( positiveColorTable, negativeColorTable );
-
+  showColorScale(positiveColorTable, negativeColorTable);
 
   m_colorGroup = new QActionGroup(this);
   m_colorGroup->addAction(m_ivUI->actionHeat);
@@ -226,90 +219,75 @@ RefIVConnections::RefIVConnections( Ui_RefImageViewer*  ui,
   m_colorGroup->addAction(m_ivUI->actionMulti);
   m_colorGroup->addAction(m_ivUI->actionSpectrum);
 
-  QObject::connect(m_ivUI->actionHeat, SIGNAL(triggered()),
-      this, SLOT(heatColorScale()) );
+  QObject::connect(m_ivUI->actionHeat, SIGNAL(triggered()), this,
+                   SLOT(heatColorScale()));
 
-  QObject::connect(m_ivUI->actionGray, SIGNAL(triggered()),
-      this, SLOT(grayColorScale()) );
+  QObject::connect(m_ivUI->actionGray, SIGNAL(triggered()), this,
+                   SLOT(grayColorScale()));
 
-  QObject::connect(m_ivUI->actionNegative_Gray, SIGNAL(triggered()),
-      this, SLOT(negativeGrayColorScale()) );
+  QObject::connect(m_ivUI->actionNegative_Gray, SIGNAL(triggered()), this,
+                   SLOT(negativeGrayColorScale()));
 
-  QObject::connect(m_ivUI->actionGreen_Yellow, SIGNAL(triggered()),
-      this, SLOT(greenYellowColorScale()) );
+  QObject::connect(m_ivUI->actionGreen_Yellow, SIGNAL(triggered()), this,
+                   SLOT(greenYellowColorScale()));
 
-  QObject::connect(m_ivUI->actionRainbow, SIGNAL(triggered()),
-      this, SLOT(rainbowColorScale()) );
+  QObject::connect(m_ivUI->actionRainbow, SIGNAL(triggered()), this,
+                   SLOT(rainbowColorScale()));
 
-  QObject::connect(m_ivUI->actionOptimal, SIGNAL(triggered()),
-      this, SLOT(optimalColorScale()) );
+  QObject::connect(m_ivUI->actionOptimal, SIGNAL(triggered()), this,
+                   SLOT(optimalColorScale()));
 
-  QObject::connect(m_ivUI->actionMulti, SIGNAL(triggered()),
-      this, SLOT(multiColorScale()) );
+  QObject::connect(m_ivUI->actionMulti, SIGNAL(triggered()), this,
+                   SLOT(multiColorScale()));
 
-  QObject::connect(m_ivUI->actionSpectrum, SIGNAL(triggered()),
-      this, SLOT(spectrumColorScale()) );
+  QObject::connect(m_ivUI->actionSpectrum, SIGNAL(triggered()), this,
+                   SLOT(spectrumColorScale()));
 
-  m_hGraphPicker = new TrackingPicker( m_ivUI->h_graphPlot->canvas() );
+  m_hGraphPicker = new TrackingPicker(m_ivUI->h_graphPlot->canvas());
   m_hGraphPicker->setMousePattern(QwtPicker::MouseSelect1, Qt::RightButton);
   m_hGraphPicker->setTrackerMode(QwtPicker::ActiveOnly);
   m_hGraphPicker->setRubberBandPen(QColor(Qt::gray));
   m_hGraphPicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_hGraphPicker->setSelectionFlags(QwtPicker::PointSelection |
-      QwtPicker::DragSelection  );
-  QObject::connect( m_hGraphPicker, SIGNAL(mouseMoved()),
-      this, SLOT(hGraphPickerMoved()) );
+                                    QwtPicker::DragSelection);
+  QObject::connect(m_hGraphPicker, SIGNAL(mouseMoved()), this,
+                   SLOT(hGraphPickerMoved()));
 
   // NOTE: This initialization could be a (static?) method in TrackingPicker
-  m_vGraphPicker = new TrackingPicker( m_ivUI->v_graphPlot->canvas() );
+  m_vGraphPicker = new TrackingPicker(m_ivUI->v_graphPlot->canvas());
   m_vGraphPicker->setMousePattern(QwtPicker::MouseSelect1, Qt::RightButton);
   m_vGraphPicker->setTrackerMode(QwtPicker::ActiveOnly);
   m_vGraphPicker->setRubberBandPen(QColor(Qt::gray));
   m_vGraphPicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_vGraphPicker->setSelectionFlags(QwtPicker::PointSelection |
-      QwtPicker::DragSelection  );
-  QObject::connect( m_vGraphPicker, SIGNAL(mouseMoved()),
-      this, SLOT(vGraphPickerMoved()) );
+                                    QwtPicker::DragSelection);
+  QObject::connect(m_vGraphPicker, SIGNAL(mouseMoved()), this,
+                   SLOT(vGraphPickerMoved()));
 }
 
+RefIVConnections::~RefIVConnections() {}
 
-RefIVConnections::~RefIVConnections()
-{
-}
-
+void RefIVConnections::closeViewer() { m_ivMainWindow->close(); }
 
-void RefIVConnections::closeViewer()
-{
-  m_ivMainWindow->close();
-}
-
-
-void RefIVConnections::toggleHScroll()
-{
+void RefIVConnections::toggleHScroll() {
   bool is_on = m_ivUI->action_Hscroll->isChecked();
-  m_ivUI->imageHorizontalScrollBar->setVisible( is_on );
-  m_ivUI->imageHorizontalScrollBar->setEnabled( is_on );
+  m_ivUI->imageHorizontalScrollBar->setVisible(is_on);
+  m_ivUI->imageHorizontalScrollBar->setEnabled(is_on);
   m_imageDisplay->updateImage();
 }
 
-
-void RefIVConnections::toggleVScroll()
-{
+void RefIVConnections::toggleVScroll() {
   bool is_on = m_ivUI->action_Vscroll->isChecked();
-  m_ivUI->imageVerticalScrollBar->setVisible( is_on );
-  m_ivUI->imageVerticalScrollBar->setEnabled( is_on );
+  m_ivUI->imageVerticalScrollBar->setVisible(is_on);
+  m_ivUI->imageVerticalScrollBar->setEnabled(is_on);
   m_imageDisplay->updateImage();
 }
 
-
-void RefIVConnections::imageHorizontalRangeChanged()
-{
+void RefIVConnections::imageHorizontalRangeChanged() {
   m_imageDisplay->updateRange();
 }
 
-
-void RefIVConnections::graphRangeChanged()
-{
+void RefIVConnections::graphRangeChanged() {
   //  double value = (double)m_ivUI->graph_max_slider->value();
   //  double min   = (double)m_ivUI->graph_max_slider->minimum();
   //  double max   = (double)m_ivUI->graph_max_slider->maximum();
@@ -322,123 +300,94 @@ void RefIVConnections::graphRangeChanged()
   //  m_vGraphDisplay->setRangeScale( range_scale );
 }
 
-
-void RefIVConnections::peakBackTofRangeUpdate()
-{
-  QLineEdit * peak_left_control = m_ivUI->lineEdit_peakLeft;
+void RefIVConnections::peakBackTofRangeUpdate() {
+  QLineEdit *peak_left_control = m_ivUI->lineEdit_peakLeft;
   double peakmin = peak_left_control->text().toDouble();
 
-  QLineEdit * peak_right_control = m_ivUI->lineEdit_peakRight;
+  QLineEdit *peak_right_control = m_ivUI->lineEdit_peakRight;
   double peakmax = peak_right_control->text().toDouble();
 
-  QLineEdit * back_left_control = m_ivUI->lineEdit_backLeft;
+  QLineEdit *back_left_control = m_ivUI->lineEdit_backLeft;
   double backmin = back_left_control->text().toDouble();
 
-  QLineEdit * back_right_control = m_ivUI->lineEdit_backRight;
+  QLineEdit *back_right_control = m_ivUI->lineEdit_backRight;
   double backmax = back_right_control->text().toDouble();
 
-  QLineEdit * tof_min_control = m_ivUI->lineEdit_TOFmin;
+  QLineEdit *tof_min_control = m_ivUI->lineEdit_TOFmin;
   double tofmin = tof_min_control->text().toDouble();
 
-  QLineEdit * tof_max_control = m_ivUI->lineEdit_TOFmax;
+  QLineEdit *tof_max_control = m_ivUI->lineEdit_TOFmax;
   double tofmax = tof_max_control->text().toDouble();
 
-  emit peakBackTofRangeUpdate(peakmin, peakmax, backmin, backmax, tofmin, tofmax);
+  emit peakBackTofRangeUpdate(peakmin, peakmax, backmin, backmax, tofmin,
+                              tofmax);
 }
 
-
-void RefIVConnections::editManualInput()
-{
+void RefIVConnections::editManualInput() {
   m_imageDisplay->updateImage();
   peakBackTofRangeUpdate();
 }
 
+void RefIVConnections::vScrollBarMoved() { m_imageDisplay->updateImage(); }
 
-void RefIVConnections::vScrollBarMoved()
-{
-  m_imageDisplay->updateImage();
-}
-
-
-void RefIVConnections::hScrollBarMoved()
-{
-  m_imageDisplay->updateImage();
-}
-
+void RefIVConnections::hScrollBarMoved() { m_imageDisplay->updateImage(); }
 
-void RefIVConnections::imageSplitterMoved()
-{
+void RefIVConnections::imageSplitterMoved() {
   QList<int> sizes = m_ivUI->imageSplitter->sizes();
   QList<int> vgraph_sizes;
-  vgraph_sizes.append( sizes[0] );
-  vgraph_sizes.append( 30 );
-  vgraph_sizes.append( sizes[1] );
-  m_ivUI->vgraphSplitter->setSizes( vgraph_sizes );
+  vgraph_sizes.append(sizes[0]);
+  vgraph_sizes.append(30);
+  vgraph_sizes.append(sizes[1]);
+  m_ivUI->vgraphSplitter->setSizes(vgraph_sizes);
   m_imageDisplay->updateImage();
 }
 
-
 // Right click
-void RefIVConnections::imagePickerMoved()
-{
+void RefIVConnections::imagePickerMoved() {
   QwtPolygon selectedPoints = m_imagePicker->selection();
-  if ( selectedPoints.size() >= 1 )
-  {
+  if (selectedPoints.size() >= 1) {
     int index = selectedPoints.size() - 1;
-    m_imageDisplay->setPointedAtPoint( selectedPoints[index] );
+    m_imageDisplay->setPointedAtPoint(selectedPoints[index]);
   }
 }
 
-
 // Left click
-void RefIVConnections::imagePicker2Moved()
-{
+void RefIVConnections::imagePicker2Moved() {
   QwtPolygon selectedPoints = m_imagePicker2->selection();
-  if ( selectedPoints.size() >= 1 )
-  {
+  if (selectedPoints.size() >= 1) {
     peakBackTofRangeUpdate();
     int index = selectedPoints.size() - 1;
     int mouseClick = 1;
-    m_imageDisplay->setPointedAtPoint( selectedPoints[index], mouseClick );
+    m_imageDisplay->setPointedAtPoint(selectedPoints[index], mouseClick);
     peakBackTofRangeUpdate();
-
   }
 }
 
-
-void RefIVConnections::hGraphPickerMoved()
-{
+void RefIVConnections::hGraphPickerMoved() {
   QwtPolygon selectedPoints = m_hGraphPicker->selection();
-  if ( selectedPoints.size() >= 1 )
-  {
+  if (selectedPoints.size() >= 1) {
     int index = selectedPoints.size() - 1;
-    m_hGraphDisplay->setPointedAtPoint( selectedPoints[index]);
+    m_hGraphDisplay->setPointedAtPoint(selectedPoints[index]);
   }
 }
 
-
-void RefIVConnections::vGraphPickerMoved()
-{
+void RefIVConnections::vGraphPickerMoved() {
   QwtPolygon selectedPoints = m_vGraphPicker->selection();
-  if ( selectedPoints.size() >= 1 )
-  {
+  if (selectedPoints.size() >= 1) {
     int index = selectedPoints.size() - 1;
-    m_vGraphDisplay->setPointedAtPoint( selectedPoints[index] );
+    m_vGraphDisplay->setPointedAtPoint(selectedPoints[index]);
   }
 }
 
-
-void RefIVConnections::intensitySliderMoved()
-{
+void RefIVConnections::intensitySliderMoved() {
   double value = (double)m_ivUI->intensity_slider->value();
-  double min   = (double)m_ivUI->intensity_slider->minimum();
-  double max   = (double)m_ivUI->intensity_slider->maximum();
+  double min = (double)m_ivUI->intensity_slider->minimum();
+  double max = (double)m_ivUI->intensity_slider->maximum();
 
-  double scaledValue = 100.0*(value - min)/(max - min);
-  m_imageDisplay->setIntensity( scaledValue );
+  double scaledValue = 100.0 * (value - min) / (max - min);
+  m_imageDisplay->setIntensity(scaledValue);
 }
 
-
 /* COLOUR MAP SLOTS */
 
 void RefIVConnections::heatColorScale() {
@@ -497,25 +446,23 @@ void RefIVConnections::setColorScale(ColorMaps::ColorScale positive,
  *                               same number of entries as the positive
  *                               color table.
  */
-void RefIVConnections::showColorScale( std::vector<QRgb> & positiveColorTable,
-                                       std::vector<QRgb> & negativeColorTable )
-{
+void RefIVConnections::showColorScale(std::vector<QRgb> &positiveColorTable,
+                                      std::vector<QRgb> &negativeColorTable) {
   size_t totalColors = positiveColorTable.size() + negativeColorTable.size();
 
   QImage image((int)totalColors, 1, QImage::Format_RGB32);
   int index = 0;
 
   size_t numColors = negativeColorTable.size();
-  for(size_t i = 0; i < numColors; i++)
-  {
-    unsigned int pixel = static_cast<unsigned int>(negativeColorTable[numColors - 1 - i]);
+  for (size_t i = 0; i < numColors; i++) {
+    unsigned int pixel =
+        static_cast<unsigned int>(negativeColorTable[numColors - 1 - i]);
     image.setPixel(index, 0, pixel);
     index++;
   }
 
   numColors = positiveColorTable.size();
-  for(size_t i = 0; i < numColors; i++)
-  {
+  for (size_t i = 0; i < numColors; i++) {
     unsigned int pixel = static_cast<unsigned int>(positiveColorTable[i]);
     image.setPixel(index, 0, pixel);
     index++;
diff --git a/MantidQt/RefDetectorViewer/src/RefImageDisplay.cpp b/MantidQt/RefDetectorViewer/src/RefImageDisplay.cpp
index 1f03d4d3751fa49d45119381c9953db95ab49d8b..ef730011fc1ffa2c9466dad8a85af39067a98ac3 100644
--- a/MantidQt/RefDetectorViewer/src/RefImageDisplay.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefImageDisplay.cpp
@@ -5,11 +5,9 @@
 #include "MantidQtSpectrumViewer/QtUtils.h"
 #include "MantidQtRefDetectorViewer/RefImagePlotItem.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
-  using namespace SpectrumView;
+namespace MantidQt {
+namespace RefDetectorViewer {
+using namespace SpectrumView;
 
 /**
  * Make a RefImageDisplay to display with the given widgets and controls.
@@ -26,26 +24,24 @@ namespace RefDetectorViewer
  * @param tableWidget    The widget where the information about a pointed
  *                       at location will be displayed.
  */
-RefImageDisplay::RefImageDisplay( QwtPlot*          imagePlot,
-                                  RefSliderHandler* sliderHandler,
-                                  RefRangeHandler*  rangeHandler,
-                                  RefLimitsHandler* limitsHandler,
-                                  GraphDisplay*     hGraph,
-                                  GraphDisplay*     vGraph,
-                                  QTableWidget*     tableWidget)
-  : SpectrumView::SpectrumDisplay(imagePlot, sliderHandler, rangeHandler, hGraph, vGraph, tableWidget),
-    m_limitsHandler(limitsHandler)
-{
-  // We need a different SpectrumPlotItem class, so delete the one created in the
+RefImageDisplay::RefImageDisplay(QwtPlot *imagePlot,
+                                 RefSliderHandler *sliderHandler,
+                                 RefRangeHandler *rangeHandler,
+                                 RefLimitsHandler *limitsHandler,
+                                 GraphDisplay *hGraph, GraphDisplay *vGraph,
+                                 QTableWidget *tableWidget)
+    : SpectrumView::SpectrumDisplay(imagePlot, sliderHandler, rangeHandler,
+                                    hGraph, vGraph, tableWidget),
+      m_limitsHandler(limitsHandler) {
+  // We need a different SpectrumPlotItem class, so delete the one created in
+  // the
   // base class constructor and create the one we want
   delete m_spectrumPlotItem;
   m_spectrumPlotItem = new RefImagePlotItem(limitsHandler);
   setupSpectrumPlotItem();
 }
 
-RefImageDisplay::~RefImageDisplay()
-{
-}
+RefImageDisplay::~RefImageDisplay() {}
 
 /**
  * Extract data from horizontal and vertical cuts across the image and
@@ -55,20 +51,21 @@ RefImageDisplay::~RefImageDisplay()
  * @param point  The point that the user is currently pointing at with
  *               the mouse.
  * @param mouseClick Which mouse button was clicked
- * @param isFront Flag indicating if this is a call to the front (active) display.
+ * @param isFront Flag indicating if this is a call to the front (active)
+ *display.
  * @return A pair containing the (x,y) values in the graph of the point
  */
-QPair<double,double> RefImageDisplay::setPointedAtPoint( QPoint point, int mouseClick, bool isFront)
-{
+QPair<double, double>
+RefImageDisplay::setPointedAtPoint(QPoint point, int mouseClick, bool isFront) {
   UNUSED_ARG(isFront);
   // Call the base class method for most of the work
-  QPair<double,double> xy = SpectrumDisplay::setPointedAtPoint( point );
+  QPair<double, double> xy = SpectrumDisplay::setPointedAtPoint(point);
 
   // Now, for a left click, set the position in the appropriate lineedit
-  if (mouseClick == 1)  //left click
+  if (mouseClick == 1) // left click
   {
-    m_limitsHandler->setActiveValue( xy.first, xy.second );
-    updateImage(); //force refresh of the plot
+    m_limitsHandler->setActiveValue(xy.first, xy.second);
+    updateImage(); // force refresh of the plot
   }
 
   return xy;
diff --git a/MantidQt/RefDetectorViewer/src/RefImagePlotItem.cpp b/MantidQt/RefDetectorViewer/src/RefImagePlotItem.cpp
index a3ed6ee58c268ad12443c56995e0f82137af167a..a8bd5c03c66e31e8406de6606f4bd04426d5736f 100644
--- a/MantidQt/RefDetectorViewer/src/RefImagePlotItem.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefImagePlotItem.cpp
@@ -1,21 +1,12 @@
 #include "MantidQtRefDetectorViewer/RefImagePlotItem.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
-
-RefImagePlotItem::RefImagePlotItem(const RefLimitsHandler * const limitsHandler)
-  : SpectrumView::SpectrumPlotItem(), m_limitsHandler(limitsHandler)
-{
-}
-
+namespace MantidQt {
+namespace RefDetectorViewer {
 
-RefImagePlotItem::~RefImagePlotItem()
-{
-  delete m_limitsHandler;
-}
+RefImagePlotItem::RefImagePlotItem(const RefLimitsHandler *const limitsHandler)
+    : SpectrumView::SpectrumPlotItem(), m_limitsHandler(limitsHandler) {}
 
+RefImagePlotItem::~RefImagePlotItem() { delete m_limitsHandler; }
 
 /**
  *  Draw the image (this is called by QWT and must not be called directly.)
@@ -32,99 +23,107 @@ RefImagePlotItem::~RefImagePlotItem()
  *                      parameter is NOT USED by the SpectrumPlotItem, but is
  *                      passed in when QWT calls this method.
  */
-void RefImagePlotItem::draw( QPainter    * painter,
-                       const QwtScaleMap & xMap,
-                       const QwtScaleMap & yMap,
-                       const QRect       & canvasRect) const
-{
-  SpectrumPlotItem::draw(painter,xMap,yMap,canvasRect);
+void RefImagePlotItem::draw(QPainter *painter, const QwtScaleMap &xMap,
+                            const QwtScaleMap &yMap,
+                            const QRect &canvasRect) const {
+  SpectrumPlotItem::draw(painter, xMap, yMap, canvasRect);
 
   //////////////////////////////////////////////////////////////////////////////////
-  // TODO: Eliminate the code duplication (from SpectrumPlotItem::draw) in this section
+  // TODO: Eliminate the code duplication (from SpectrumPlotItem::draw) in this
+  // section
   SpectrumView::DataArray_const_sptr data_array;
-  if ( m_bufferID == 0 )
+  if (m_bufferID == 0)
     data_array = m_dataArray0;
   else
     data_array = m_dataArray1;
 
-  const double x_min  = data_array->getXMin();
-  const double x_max  = data_array->getXMax();
-  const double y_min  = data_array->getYMin();
-  const double y_max  = data_array->getYMax();
-
-                                            // find the actual plot region
-                                            // using the scale maps.
-  const int pix_x_min = (int)xMap.transform( x_min );
-  const int pix_x_max = (int)xMap.transform( x_max );
-  const int pix_y_min = (int)yMap.transform( y_min );
-  const int pix_y_max = (int)yMap.transform( y_max );
+  const double x_min = data_array->getXMin();
+  const double x_max = data_array->getXMax();
+  const double y_min = data_array->getYMin();
+  const double y_max = data_array->getYMax();
+
+  // find the actual plot region
+  // using the scale maps.
+  const int pix_x_min = (int)xMap.transform(x_min);
+  const int pix_x_max = (int)xMap.transform(x_max);
+  const int pix_y_min = (int)yMap.transform(y_min);
+  const int pix_y_max = (int)yMap.transform(y_max);
   // End duplicated code
   //////////////////////////////////////////////////////////////////////////////////
 
-  float coeff_left = (float(y_max) - float(y_min)) / (float(pix_y_min) - float(pix_y_max));
+  float coeff_left =
+      (float(y_max) - float(y_min)) / (float(pix_y_min) - float(pix_y_max));
   float coeff_top_right;
   int pixel_value;
 
-  //for the peak selection
+  // for the peak selection
   painter->setPen(Qt::blue);
 
-  //peak1
+  // peak1
   float peakLeft = float(m_limitsHandler->getPeakLeft());
 
   if (peakLeft != 0) {
     coeff_top_right = float(y_max) - float(peakLeft);
     pixel_value = int((coeff_top_right / coeff_left) + float(pix_y_max));
-    painter->drawLine(QPoint(pix_x_min,pixel_value), QPoint(pix_x_max,pixel_value));
+    painter->drawLine(QPoint(pix_x_min, pixel_value),
+                      QPoint(pix_x_max, pixel_value));
   }
 
-  //peak2
+  // peak2
   float peakRight = float(m_limitsHandler->getPeakRight());
   if (peakRight != 0) {
     coeff_top_right = float(y_max) - float(peakRight);
     pixel_value = int((coeff_top_right / coeff_left) + float(pix_y_max));
-    painter->drawLine(QPoint(pix_x_min,pixel_value), QPoint(pix_x_max,pixel_value));
+    painter->drawLine(QPoint(pix_x_min, pixel_value),
+                      QPoint(pix_x_max, pixel_value));
   }
 
-  //for the background selection
+  // for the background selection
   painter->setPen(Qt::red);
 
-  //back1
+  // back1
   float backLeft = float(m_limitsHandler->getBackLeft());
   if (backLeft != 0) {
     coeff_top_right = float(y_max) - float(backLeft);
     pixel_value = int((coeff_top_right / coeff_left) + float(pix_y_max));
-    painter->drawLine(QPoint(pix_x_min,pixel_value), QPoint(pix_x_max,pixel_value));
+    painter->drawLine(QPoint(pix_x_min, pixel_value),
+                      QPoint(pix_x_max, pixel_value));
   }
 
-  //back2
+  // back2
   float backRight = float(m_limitsHandler->getBackRight());
   if (backRight != 0) {
     coeff_top_right = float(y_max) - float(backRight);
     pixel_value = int((coeff_top_right / coeff_left) + float(pix_y_max));
-    painter->drawLine(QPoint(pix_x_min,pixel_value), QPoint(pix_x_max,pixel_value));
+    painter->drawLine(QPoint(pix_x_min, pixel_value),
+                      QPoint(pix_x_max, pixel_value));
   }
 
-  //tof selection
+  // tof selection
   painter->setPen(Qt::green);
 
-  coeff_left = (float(pix_x_max) - float(pix_x_min)) / (float(x_max) - float(x_min));
+  coeff_left =
+      (float(pix_x_max) - float(pix_x_min)) / (float(x_max) - float(x_min));
   int tof_value;
   float coeff_bottom_right;
 
-  //tof min
+  // tof min
   float TOFmin = float(m_limitsHandler->getTOFmin());
   if (TOFmin != 0) {
     coeff_bottom_right = float(TOFmin) - float(x_min);
-    tof_value = int(coeff_left * coeff_bottom_right + static_cast<float>(pix_x_min));
-    painter->drawLine(QPoint(tof_value,pix_y_min), QPoint(tof_value,pix_y_max));
+    tof_value =
+        int(coeff_left * coeff_bottom_right + static_cast<float>(pix_x_min));
+    painter->drawLine(QPoint(tof_value, pix_y_min),
+                      QPoint(tof_value, pix_y_max));
   }
 
-  //tof max
+  // tof max
   float TOFmax = float(m_limitsHandler->getTOFmax());
   if (TOFmax != 0) {
     coeff_bottom_right = float(TOFmax) - float(x_min);
     tof_value = int(coeff_left * coeff_bottom_right + float(pix_x_min));
-    painter->drawLine(QPoint(tof_value,pix_y_min), QPoint(tof_value,pix_y_max));
+    painter->drawLine(QPoint(tof_value, pix_y_min),
+                      QPoint(tof_value, pix_y_max));
   }
 }
 
diff --git a/MantidQt/RefDetectorViewer/src/RefImageView.cpp b/MantidQt/RefDetectorViewer/src/RefImageView.cpp
index 6c35c6eca90f9310165abb98770d2187e8b33ac9..68a0b4cb776e9573723288e9a89ee8b59e31c2e7 100644
--- a/MantidQt/RefDetectorViewer/src/RefImageView.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefImageView.cpp
@@ -1,5 +1,5 @@
-#include  "MantidQtRefDetectorViewer/RefImageView.h"
-#include  "MantidQtSpectrumViewer/ColorMaps.h"
+#include "MantidQtRefDetectorViewer/RefImageView.h"
+#include "MantidQtSpectrumViewer/ColorMaps.h"
 
 #include "ui_RefImageView.h"
 #include "MantidQtRefDetectorViewer/RefIVConnections.h"
@@ -10,15 +10,14 @@
 #include <sstream>
 #include <string>
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
 /**
  *  Construct an SpectrumView to display data from the specified data source.
  *  The specified SpectrumDataSource must be constructed elsewhere and passed
- *  into this SpectrumView constructor.  Most other components of the SpectrumView
+ *  into this SpectrumView constructor.  Most other components of the
+ *SpectrumView
  *  are managed by this class.  That is the graphs, image display and other
  *  parts of the SpectrumView are constructed here and are deleted when the
  *  SpectrumView destructor is called.
@@ -31,42 +30,37 @@ namespace RefDetectorViewer
  *  @param tofMin      The min time of flight value
  *  @param tofMax      The max time of flight value
  */
-RefImageView::RefImageView( SpectrumView::SpectrumDataSource_sptr dataSource,
-                            int peakMin, int peakMax,
-                            int backMin, int backMax,
-                            int tofMin,  int tofMax)
-  : m_ui(new Ui::RefImageViewer())
-{
-  QMainWindow* window = this;
-
-  m_ui->setupUi( window );
-  window->resize( 1050, 800 );
+RefImageView::RefImageView(SpectrumView::SpectrumDataSource_sptr dataSource,
+                           int peakMin, int peakMax, int backMin, int backMax,
+                           int tofMin, int tofMax)
+    : m_ui(new Ui::RefImageViewer()) {
+  QMainWindow *window = this;
+
+  m_ui->setupUi(window);
+  window->resize(1050, 800);
   window->show();
-  window->setAttribute(Qt::WA_DeleteOnClose);  // We just need to close the
-                                               // window to trigger the
-                                               // destructor and clean up
+  window->setAttribute(Qt::WA_DeleteOnClose); // We just need to close the
+                                              // window to trigger the
+                                              // destructor and clean up
   window->setWindowTitle(QString::fromUtf8("Reflector Detector Viewer"));
 
-  m_sliderHandler = new RefSliderHandler( m_ui );
-  m_rangeHandler = new RefRangeHandler( m_ui );
+  m_sliderHandler = new RefSliderHandler(m_ui);
+  m_rangeHandler = new RefRangeHandler(m_ui);
 
-  // Create the handler for comminicating peak/background/tof values to/from the ui
+  // Create the handler for comminicating peak/background/tof values to/from the
+  // ui
   // This ends up being owned by the RefImagePlotItem instance
-  RefLimitsHandler* limits_handler = new RefLimitsHandler(m_ui);
+  RefLimitsHandler *limits_handler = new RefLimitsHandler(m_ui);
 
-  m_hGraph = new SpectrumView::GraphDisplay( m_ui->h_graphPlot, NULL, false );
-  m_vGraph = new SpectrumView::GraphDisplay( m_ui->v_graphPlot, NULL, true );
+  m_hGraph = new SpectrumView::GraphDisplay(m_ui->h_graphPlot, NULL, false);
+  m_vGraph = new SpectrumView::GraphDisplay(m_ui->v_graphPlot, NULL, true);
 
-  m_imageDisplay = new RefImageDisplay( m_ui->imagePlot,
-                                        m_sliderHandler,
-                                        m_rangeHandler,
-                                        limits_handler,
-                                        m_hGraph, m_vGraph,
-                                        m_ui->image_table);
+  m_imageDisplay = new RefImageDisplay(m_ui->imagePlot, m_sliderHandler,
+                                       m_rangeHandler, limits_handler, m_hGraph,
+                                       m_vGraph, m_ui->image_table);
 
-  RefIVConnections * iv_connections = new RefIVConnections( m_ui, this,
-                                                            m_imageDisplay,
-                                                            m_hGraph, m_vGraph );
+  RefIVConnections *iv_connections =
+      new RefIVConnections(m_ui, this, m_imageDisplay, m_hGraph, m_vGraph);
 
   // Set validators on the QLineEdits to restrict them to integers
   m_ui->lineEdit_peakLeft->setValidator(new QIntValidator(this));
@@ -76,7 +70,7 @@ RefImageView::RefImageView( SpectrumView::SpectrumDataSource_sptr dataSource,
   m_ui->lineEdit_TOFmin->setValidator(new QIntValidator(this));
   m_ui->lineEdit_TOFmax->setValidator(new QIntValidator(this));
 
-  //populate widgets with peak, back and tof values
+  // populate widgets with peak, back and tof values
   limits_handler->setPeakLeft(peakMin);
   limits_handler->setPeakRight(peakMax);
   limits_handler->setBackLeft(backMin);
@@ -89,12 +83,10 @@ RefImageView::RefImageView( SpectrumView::SpectrumDataSource_sptr dataSource,
   m_imageDisplay->updateImage();
   iv_connections->peakBackTofRangeUpdate();
 
-  m_imageDisplay->setDataSource( dataSource );
+  m_imageDisplay->setDataSource(dataSource);
 }
 
-
-RefImageView::~RefImageView()
-{
+RefImageView::~RefImageView() {
   delete m_imageDisplay;
   delete m_sliderHandler;
   delete m_rangeHandler;
@@ -102,11 +94,7 @@ RefImageView::~RefImageView()
   delete m_ui;
 }
 
-
-RefIVConnections* RefImageView::getIVConnections()
-{
-  return m_ivConnections;
-}
+RefIVConnections *RefImageView::getIVConnections() { return m_ivConnections; }
 
 } // namespace RefDetectorViewer
 } // namespace MantidQt
diff --git a/MantidQt/RefDetectorViewer/src/RefLimitsHandler.cpp b/MantidQt/RefDetectorViewer/src/RefLimitsHandler.cpp
index 10b63406866709ba05b0e1619a78c6fdc05b9d47..5ee22a3a251d61e5b1d09c46417d23a2d8967978 100644
--- a/MantidQt/RefDetectorViewer/src/RefLimitsHandler.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefLimitsHandler.cpp
@@ -1,107 +1,91 @@
 #include "MantidQtRefDetectorViewer/RefLimitsHandler.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
-RefLimitsHandler::RefLimitsHandler( Ui_RefImageViewer* ivUI ) : m_ui(ivUI)
-{
-}
+RefLimitsHandler::RefLimitsHandler(Ui_RefImageViewer *ivUI) : m_ui(ivUI) {}
 
 /**
  * return the value of the peak left
  **/
-int RefLimitsHandler::getPeakLeft() const
-{
+int RefLimitsHandler::getPeakLeft() const {
   return m_ui->lineEdit_peakLeft->text().toInt();
 }
 
 /**
  * return the value of the peak right
  **/
-int RefLimitsHandler::getPeakRight() const
-{
+int RefLimitsHandler::getPeakRight() const {
   return m_ui->lineEdit_peakRight->text().toInt();
 }
 
 /**
  * return the value of the back left
  **/
-int RefLimitsHandler::getBackLeft() const
-{
+int RefLimitsHandler::getBackLeft() const {
   return m_ui->lineEdit_backLeft->text().toInt();
 }
 
 /**
  * return the value of the back right
  **/
-int RefLimitsHandler::getBackRight() const
-{
+int RefLimitsHandler::getBackRight() const {
   return m_ui->lineEdit_backRight->text().toInt();
 }
 
 /**
  * return the value of the TOF min
  **/
-int RefLimitsHandler::getTOFmin() const
-{
+int RefLimitsHandler::getTOFmin() const {
   return m_ui->lineEdit_TOFmin->text().toInt();
 }
 
 /**
  * return the value of the TOF max
  **/
-int RefLimitsHandler::getTOFmax() const
-{
+int RefLimitsHandler::getTOFmax() const {
   return m_ui->lineEdit_TOFmax->text().toInt();
 }
 
 /**
  * set the peak left
  */
-void RefLimitsHandler::setPeakLeft(const int value)
-{
+void RefLimitsHandler::setPeakLeft(const int value) {
   m_ui->lineEdit_peakLeft->setText(QString::number(value));
 }
 
 /**
  * set the peak right
  */
-void RefLimitsHandler::setPeakRight(const int value)
-{
+void RefLimitsHandler::setPeakRight(const int value) {
   m_ui->lineEdit_peakRight->setText(QString::number(value));
 }
 
 /**
  * set the back left
  */
-void RefLimitsHandler::setBackLeft(const int value)
-{
+void RefLimitsHandler::setBackLeft(const int value) {
   m_ui->lineEdit_backLeft->setText(QString::number(value));
 }
 
 /**
  * set the back right
  */
-void RefLimitsHandler::setBackRight(const int value)
-{
+void RefLimitsHandler::setBackRight(const int value) {
   m_ui->lineEdit_backRight->setText(QString::number(value));
 }
 
 /**
  * set the TOF min
  */
-void RefLimitsHandler::setTOFmin(const int value)
-{
+void RefLimitsHandler::setTOFmin(const int value) {
   m_ui->lineEdit_TOFmin->setText(QString::number(value));
 }
 
 /**
  * set the TOF max
  */
-void RefLimitsHandler::setTOFmax(const int value)
-{
+void RefLimitsHandler::setTOFmax(const int value) {
   m_ui->lineEdit_TOFmax->setText(QString::number(value));
 }
 
@@ -110,27 +94,20 @@ void RefLimitsHandler::setTOFmax(const int value)
  *  @param x An x coordinate - pertains to TOF lines
  *  @param y A y coordinate - pertains to peak & background lines
  */
-void RefLimitsHandler::setActiveValue(const double x, const double y)
-{
-  if (m_ui->radioButton_peakLeft->isChecked()) { //peak left selected
-    setPeakLeft( static_cast<int>(y) );
-  }
-  else if (m_ui->radioButton_peakRight->isChecked()) { //peak right selected
-    setPeakRight( static_cast<int>(y) );
-  }
-  else if (m_ui->radioButton_backLeft->isChecked()) { //back left selected
-    setBackLeft( static_cast<int>(y) );
-  }
-  else if (m_ui->radioButton_backRight->isChecked()) { //back right selected
-    setBackRight( static_cast<int>(y) );
+void RefLimitsHandler::setActiveValue(const double x, const double y) {
+  if (m_ui->radioButton_peakLeft->isChecked()) { // peak left selected
+    setPeakLeft(static_cast<int>(y));
+  } else if (m_ui->radioButton_peakRight->isChecked()) { // peak right selected
+    setPeakRight(static_cast<int>(y));
+  } else if (m_ui->radioButton_backLeft->isChecked()) { // back left selected
+    setBackLeft(static_cast<int>(y));
+  } else if (m_ui->radioButton_backRight->isChecked()) { // back right selected
+    setBackRight(static_cast<int>(y));
+  } else if (m_ui->radioButton_TOFmin->isChecked()) { // tof min selected
+    setTOFmin(static_cast<int>(x));
+  } else if (m_ui->radioButton_TOFmax->isChecked()) { // tof max selected
+    setTOFmax(static_cast<int>(x));
   }
-  else if (m_ui->radioButton_TOFmin->isChecked()) { //tof min selected
-    setTOFmin( static_cast<int>(x) );
-  }
-  else if (m_ui->radioButton_TOFmax->isChecked()) { // tof max selected
-    setTOFmax( static_cast<int>(x) );
-  }
-
 }
 
 } // namespace RefDetectorViewer
diff --git a/MantidQt/RefDetectorViewer/src/RefMatrixWSImageView.cpp b/MantidQt/RefDetectorViewer/src/RefMatrixWSImageView.cpp
index f63397e1da6a002c61af56b0009f4e82f0e7347d..bffc65231b13fa68deae4972de28d18d21b1e40d 100644
--- a/MantidQt/RefDetectorViewer/src/RefMatrixWSImageView.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefMatrixWSImageView.cpp
@@ -17,28 +17,27 @@ using namespace Mantid::API;
 /**
  * Construct an ImageView for the specified matrix workspace
  */
-RefMatrixWSImageView::RefMatrixWSImageView( MatrixWorkspace_sptr /*mat_ws*/ ) :
-  m_imageView(NULL)
-{
+RefMatrixWSImageView::RefMatrixWSImageView(MatrixWorkspace_sptr /*mat_ws*/)
+    : m_imageView(NULL) {
   return;
   //  RefMatrixWSDataSource* source = new RefMatrixWSDataSource( mat_ws );
-//  image_view = new RefImageView( source );  // this is the QMainWindow
-//                                         // for the viewer.  It is
-//                                         // deleted when the window
-//                                         // is closed
+  //  image_view = new RefImageView( source );  // this is the QMainWindow
+  //                                         // for the viewer.  It is
+  //                                         // deleted when the window
+  //                                         // is closed
 }
 
-RefMatrixWSImageView::RefMatrixWSImageView( QString wpsName,
-                                            int peakMin, int peakMax,
-                                            int backMin, int backMax,
-                                            int tofMin,  int tofMax)
-{
+RefMatrixWSImageView::RefMatrixWSImageView(QString wpsName, int peakMin,
+                                           int peakMax, int backMin,
+                                           int backMax, int tofMin,
+                                           int tofMax) {
   IEventWorkspace_sptr ws;
-  ws = AnalysisDataService::Instance().retrieveWS<IEventWorkspace>(wpsName.toStdString());
+  ws = AnalysisDataService::Instance().retrieveWS<IEventWorkspace>(
+      wpsName.toStdString());
 
   const double totalYMin = 0.0;
-  const double totalYMax = 255.0; //303
-  const size_t totalRows = 256;   //304
+  const double totalYMax = 255.0; // 303
+  const size_t totalRows = 256;   // 304
 
   std::vector<double> xAxis = ws->readX(0);
   const size_t sz = xAxis.size() - 1;
@@ -50,8 +49,7 @@ RefMatrixWSImageView::RefMatrixWSImageView( QString wpsName,
   std::vector<float> data(static_cast<size_t>(totalYMax) * sz);
 
   std::vector<double> yAxis;
-  for (size_t px = 0; px < totalYMax; px++)
-  {
+  for (size_t px = 0; px < totalYMax; px++) {
     // Retrieve data now
     yAxis = ws->readY(px);
     for (size_t tof = 0; tof < sz; tof++)
@@ -59,25 +57,18 @@ RefMatrixWSImageView::RefMatrixWSImageView( QString wpsName,
   }
 
   SpectrumView::ArrayDataSource_sptr source =
-    SpectrumView::ArrayDataSource_sptr( new SpectrumView::ArrayDataSource(totalXMin, totalXMax,
-                                                                          totalYMin, totalYMax,
-                                                                          totalRows, totalCols,
-                                                                          data) );
+      SpectrumView::ArrayDataSource_sptr(new SpectrumView::ArrayDataSource(
+          totalXMin, totalXMax, totalYMin, totalYMax, totalRows, totalCols,
+          data));
 
-  m_imageView = new RefImageView( source,
-                                  peakMin, peakMax,
-                                  backMin, backMax,
-                                  tofMin,  tofMax);
+  m_imageView = new RefImageView(source, peakMin, peakMax, backMin, backMax,
+                                 tofMin, tofMax);
 }
 
-
-RefIVConnections* RefMatrixWSImageView::getConnections()
-{
+RefIVConnections *RefMatrixWSImageView::getConnections() {
   return m_imageView->getIVConnections();
 }
 
-
-RefMatrixWSImageView::~RefMatrixWSImageView()
-{
+RefMatrixWSImageView::~RefMatrixWSImageView() {
   // nothing to do here, since image_view is deleted when the window closes
 }
diff --git a/MantidQt/RefDetectorViewer/src/RefRangeHandler.cpp b/MantidQt/RefDetectorViewer/src/RefRangeHandler.cpp
index a2f7d1d8b70fe1c2a2c23a6b0b45742bd0783a0b..bef79932737ddd29b53e2493ced8feb4fc08eef9 100644
--- a/MantidQt/RefDetectorViewer/src/RefRangeHandler.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefRangeHandler.cpp
@@ -5,17 +5,12 @@
 #include "MantidQtSpectrumViewer/SVUtils.h"
 #include "MantidKernel/Logger.h"
 
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("SpectrumView");
+namespace {
+Mantid::Kernel::Logger g_log("SpectrumView");
 }
 
-
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
 using namespace SpectrumView;
 
@@ -23,46 +18,40 @@ using namespace SpectrumView;
  *  Construct a RefRangeHandler object to manage min, max and step controls
  *  in the specified UI
  */
-RefRangeHandler::RefRangeHandler( Ui_RefImageViewer* ivUI ) :
-  m_ivUI(ivUI),
-  m_totalMinX(0.0), m_totalMaxX(0.0),
-  m_totalMinY(0.0), m_totalMaxY(0.0),
-  m_totalNSteps(0)
-{
-}
-
+RefRangeHandler::RefRangeHandler(Ui_RefImageViewer *ivUI)
+    : m_ivUI(ivUI), m_totalMinX(0.0), m_totalMaxX(0.0), m_totalMinY(0.0),
+      m_totalMaxY(0.0), m_totalNSteps(0) {}
 
 /**
  * Configure the min, max and step controls for the specified data source.
  *
  * @param dataSource  SpectrumDataSource that provides the data to be drawn
  */
-void RefRangeHandler::configureRangeControls( SpectrumDataSource_sptr dataSource )
-{
+void RefRangeHandler::configureRangeControls(
+    SpectrumDataSource_sptr dataSource) {
   // X axis
-  m_totalMinX   = dataSource->getXMin();
-  m_totalMaxX   = dataSource->getXMax();
+  m_totalMinX = dataSource->getXMin();
+  m_totalMaxX = dataSource->getXMax();
   m_totalNSteps = dataSource->getNCols();
 
   double defaultStepX = (m_totalMaxX - m_totalMinX) / (double)m_totalNSteps;
-  if(m_totalNSteps > 2000)
+  if (m_totalNSteps > 2000)
     defaultStepX = (m_totalMaxX - m_totalMinX) / 2000.0;
 
   setRange(m_totalMinX, m_totalMaxX, defaultStepX, 'x');
 
   // Y axis
-  m_totalMinY   = dataSource->getYMin();
-  m_totalMaxY   = dataSource->getYMax();
+  m_totalMinY = dataSource->getYMin();
+  m_totalMaxY = dataSource->getYMax();
   m_totalNSteps = dataSource->getNCols();
 
   double defaultStepY = (m_totalMaxY - m_totalMinY) / (double)m_totalNSteps;
-  if(m_totalNSteps > 2000)
+  if (m_totalNSteps > 2000)
     defaultStepY = (m_totalMaxY - m_totalMinY) / 2000.0;
 
-  setRange(m_totalMinY, m_totalMaxY, defaultStepY, 'y' );
+  setRange(m_totalMinY, m_totalMaxY, defaultStepY, 'y');
 }
 
-
 /**
  * Get the interval of values and the step size to use for rebinning the
  * spectra.  The range values are validated and adjusted if needed.  The
@@ -86,14 +75,13 @@ void RefRangeHandler::configureRangeControls( SpectrumDataSource_sptr dataSource
  *                min and max.  If it is less than zero, a log scale
  *                is requested.
  */
-void RefRangeHandler::getRange( double &min, double &max, double &step )
-{
-  double originalMin  = min;
-  double originalMax  = max;
+void RefRangeHandler::getRange(double &min, double &max, double &step) {
+  double originalMin = min;
+  double originalMax = max;
   double originalStep = step;
 
-  QLineEdit* min_control  = m_ivUI->x_min_input;
-  QLineEdit* max_control  = m_ivUI->x_max_input;
+  QLineEdit *min_control = m_ivUI->x_min_input;
+  QLineEdit *max_control = m_ivUI->x_max_input;
 
   bool minIsNumber = false;
   bool maxIsNumber = false;
@@ -101,50 +89,44 @@ void RefRangeHandler::getRange( double &min, double &max, double &step )
   min = min_control->text().toDouble(&minIsNumber);
   max = max_control->text().toDouble(&maxIsNumber);
 
-  if(!minIsNumber)
-  {
+  if (!minIsNumber) {
     g_log.information("X Min is not a NUMBER! Value reset.");
     min = originalMin;
   }
 
-  if(!maxIsNumber)
-  {
+  if (!maxIsNumber) {
     g_log.information("X Max is not a NUMBER! Value reset.");
     max = originalMax;
   }
 
-  // Just require step to be non-zero, no other bounds. If zero, take a default step size
-  if ( step == 0 )
-  {
+  // Just require step to be non-zero, no other bounds. If zero, take a default
+  // step size
+  if (step == 0) {
     g_log.information("Step = 0, resetting to default step");
     step = originalStep;
   }
 
-  if ( step > 0 )
-  {
-    if ( !SVUtils::FindValidInterval( min, max ) )
-    {
-      g_log.information("In GetRange: [Min,Max] interval invalid, values adjusted");
-      min  = originalMin;
-      max  = originalMax;
+  if (step > 0) {
+    if (!SVUtils::FindValidInterval(min, max)) {
+      g_log.information(
+          "In GetRange: [Min,Max] interval invalid, values adjusted");
+      min = originalMin;
+      max = originalMax;
       step = originalStep;
     }
-  }
-  else
-  {
-    if ( !SVUtils::FindValidLogInterval( min, max ) )
-    {
-      g_log.information("In GetRange: [Min,Max] log interval invalid, values adjusted");
-      min  = originalMin;
-      max  = originalMax;
+  } else {
+    if (!SVUtils::FindValidLogInterval(min, max)) {
+      g_log.information(
+          "In GetRange: [Min,Max] log interval invalid, values adjusted");
+      min = originalMin;
+      max = originalMax;
       step = originalStep;
     }
   }
 
-  setRange( min, max, step, 'x' );
+  setRange(min, max, step, 'x');
 }
 
-
 /**
  * Adjust the values to be consistent with the available data and
  * diplay them in the controls.
@@ -155,66 +137,59 @@ void RefRangeHandler::getRange( double &min, double &max, double &step )
  *                If it is less than zero, a log scale is requested.
  * @param type    x or y
  */
-void RefRangeHandler::setRange( double min, double max, double step, char type )
-{
+void RefRangeHandler::setRange(double min, double max, double step, char type) {
   if (type == 'x') {
 
-    if ( !SVUtils::FindValidInterval( min, max ) )
-      g_log.information("In setRange: [XMin,XMax] interval invalid, values adjusted");
+    if (!SVUtils::FindValidInterval(min, max))
+      g_log.information(
+          "In setRange: [XMin,XMax] interval invalid, values adjusted");
 
-    if ( min < m_totalMinX || min > m_totalMaxX )
-    {
+    if (min < m_totalMinX || min > m_totalMaxX) {
       g_log.information("X Min out of range, resetting to range min.");
       min = m_totalMinX;
     }
 
-    if ( max < m_totalMinX || max > m_totalMaxX )
-    {
+    if (max < m_totalMinX || max > m_totalMaxX) {
       g_log.information("X Max out of range, resetting to range max.");
       max = m_totalMaxX;
     }
 
-    if ( step == 0 )
-    {
+    if (step == 0) {
       g_log.information("Step = 0, resetting to default step");
-      step = (max-min)/2000.0;
+      step = (max - min) / 2000.0;
     }
 
-    QtUtils::SetText( 8, 2, min, m_ivUI->x_min_input );
-    QtUtils::SetText( 8, 2, max, m_ivUI->x_max_input );
+    QtUtils::SetText(8, 2, min, m_ivUI->x_min_input);
+    QtUtils::SetText(8, 2, max, m_ivUI->x_max_input);
     //  QtUtils::SetText( 8, 4, step, m_ivUI->step_input );
-
   }
 
   if (type == 'y') {
 
-    if ( !SVUtils::FindValidInterval( min, max ) )
-      g_log.information("In setRange: [YMin,YMax] interval invalid, values adjusted");
+    if (!SVUtils::FindValidInterval(min, max))
+      g_log.information(
+          "In setRange: [YMin,YMax] interval invalid, values adjusted");
 
-    if ( min < m_totalMinY || min > m_totalMaxY )
-    {
+    if (min < m_totalMinY || min > m_totalMaxY) {
       g_log.information("Y Min out of range, resetting to range min.");
       min = m_totalMinY;
     }
 
-    if ( max < m_totalMinY || max > m_totalMaxY )
-    {
+    if (max < m_totalMinY || max > m_totalMaxY) {
       g_log.information("Y Max out of range, resetting to range max.");
       max = m_totalMaxY;
     }
 
-    if ( step == 0 )
-    {
+    if (step == 0) {
       g_log.information("Step = 0, resetting to default step");
-      step = (max-min)/2000.0;
+      step = (max - min) / 2000.0;
     }
 
-    QtUtils::SetText( 8, 2, min, m_ivUI->y_min_input );
-    QtUtils::SetText( 8, 2, max, m_ivUI->y_max_input );
+    QtUtils::SetText(8, 2, min, m_ivUI->y_min_input);
+    QtUtils::SetText(8, 2, max, m_ivUI->y_max_input);
     //  QtUtils::SetText( 8, 4, step, m_ivUI->step_input );
   }
 }
 
-
 } // namespace RefDetectorViewer
 } // namespace MantidQt
diff --git a/MantidQt/RefDetectorViewer/src/RefSliderHandler.cpp b/MantidQt/RefDetectorViewer/src/RefSliderHandler.cpp
index e11b1cbf4651ad74ecfed24339d28e2f569de825..79654a4b56f1c28dcecac2ce747c69763f8d2d56 100644
--- a/MantidQt/RefDetectorViewer/src/RefSliderHandler.cpp
+++ b/MantidQt/RefDetectorViewer/src/RefSliderHandler.cpp
@@ -3,19 +3,14 @@
 #include <QScrollBar>
 #include "MantidQtRefDetectorViewer/RefSliderHandler.h"
 
-namespace MantidQt
-{
-namespace RefDetectorViewer
-{
+namespace MantidQt {
+namespace RefDetectorViewer {
 
 /**
  *  Construct a RefSliderHandler object to manage the image scrollbars from the
  *  specified UI.
  */
-RefSliderHandler::RefSliderHandler( Ui_RefImageViewer* ivUI ) : m_ivUI(ivUI)
-{
-}
-
+RefSliderHandler::RefSliderHandler(Ui_RefImageViewer *ivUI) : m_ivUI(ivUI) {}
 
 /**
  * Configure the image scrollbars for the specified data and drawing area.
@@ -24,17 +19,15 @@ RefSliderHandler::RefSliderHandler( Ui_RefImageViewer* ivUI ) : m_ivUI(ivUI)
  *                    be drawn
  * @param dataSource  SpectrumDataSource that provides the data to be drawn
  */
-void RefSliderHandler::configureSliders( QRect drawArea,
-                                         SpectrumView::SpectrumDataSource_sptr dataSource )
-{
-  QScrollBar* v_scroll = m_ivUI->imageVerticalScrollBar;
+void RefSliderHandler::configureSliders(
+    QRect drawArea, SpectrumView::SpectrumDataSource_sptr dataSource) {
+  QScrollBar *v_scroll = m_ivUI->imageVerticalScrollBar;
   int n_rows = (int)dataSource->getNRows();
-  configureSlider( v_scroll, n_rows, drawArea.height(), n_rows );
+  configureSlider(v_scroll, n_rows, drawArea.height(), n_rows);
 
-  configureHSlider( 2000, drawArea.width() );   // initial default, 2000 bins
+  configureHSlider(2000, drawArea.width()); // initial default, 2000 bins
 }
 
-
 /**
  *  Public method to configure the horizontal scrollbar to cover the
  *  specified range of data columns, displayed in the specified number of
@@ -44,14 +37,11 @@ void RefSliderHandler::configureSliders( QRect drawArea,
  *                     displayed
  *  @param nPixels     The number of pixels avaliable to show the data
  */
-void RefSliderHandler::configureHSlider( int         nDataSteps,
-                                         int         nPixels )
-{
-  QScrollBar* h_scroll = m_ivUI->imageHorizontalScrollBar;
-  configureSlider( h_scroll, nDataSteps, nPixels, 0 );
+void RefSliderHandler::configureHSlider(int nDataSteps, int nPixels) {
+  QScrollBar *h_scroll = m_ivUI->imageHorizontalScrollBar;
+  configureSlider(h_scroll, nDataSteps, nPixels, 0);
 }
 
-
 /**
  *  Configure the specified scrollbar to cover the specified range of data
  *  steps, displayed in the specified number of pixels.
@@ -63,53 +53,45 @@ void RefSliderHandler::configureHSlider( int         nDataSteps,
  *  @param val         The initial position of the scrollbar, between 0 and
  *                     nDataSteps.
  */
-void RefSliderHandler::configureSlider( QScrollBar* scrollBar,
-                                        int         nDataSteps,
-                                        int         nPixels,
-                                        int         val )
-{
+void RefSliderHandler::configureSlider(QScrollBar *scrollBar, int nDataSteps,
+                                       int nPixels, int val) {
   int step = nPixels;
-  if ( step > nDataSteps )
+  if (step > nDataSteps)
     step = nDataSteps;
 
-  if ( step <= 0 )
+  if (step <= 0)
     step = 1;
 
-  int max  = nDataSteps - step;
-  if ( max <= 0 )
+  int max = nDataSteps - step;
+  if (max <= 0)
     max = 0;
 
-  if ( val < 0 )
+  if (val < 0)
     val = 0;
 
-  if ( val > max )
+  if (val > max)
     val = max;
 
-  scrollBar->setMinimum( 0 );
-  scrollBar->setMaximum( max );
-  scrollBar->setPageStep( step );
-  scrollBar->setValue( val );
+  scrollBar->setMinimum(0);
+  scrollBar->setMaximum(max);
+  scrollBar->setPageStep(step);
+  scrollBar->setValue(val);
 }
 
-
 /**
  * Return true if the image horizontal scrollbar is enabled.
  */
-bool RefSliderHandler::hSliderOn()
-{
+bool RefSliderHandler::hSliderOn() {
   return m_ivUI->imageHorizontalScrollBar->isEnabled();
 }
 
-
 /**
  * Return true if the image vertical scrollbar is enabled.
  */
-bool RefSliderHandler::vSliderOn()
-{
+bool RefSliderHandler::vSliderOn() {
   return m_ivUI->imageVerticalScrollBar->isEnabled();
 }
 
-
 /**
  * Get the range of columns to display in the image.  NOTE: xMin will be
  * the smaller column number in the array, corresponding to lower values on
@@ -120,17 +102,15 @@ bool RefSliderHandler::vSliderOn()
  * @param xMax   This will be set to the last bin number to display in the
  *                x direction
  */
-void RefSliderHandler::getHSliderInterval( int &xMin, int &xMax )
-{
-  QScrollBar* h_scroll = m_ivUI->imageHorizontalScrollBar;
-  int step  = h_scroll->pageStep();
+void RefSliderHandler::getHSliderInterval(int &xMin, int &xMax) {
+  QScrollBar *h_scroll = m_ivUI->imageHorizontalScrollBar;
+  int step = h_scroll->pageStep();
   int value = h_scroll->value();
 
   xMin = value;
   xMax = xMin + step;
 }
 
-
 /**
  * Get the range of rows to display in the image.  NOTE: yMin will be
  * the smaller row number in the array, corresponding to lower values on
@@ -141,18 +121,16 @@ void RefSliderHandler::getHSliderInterval( int &xMin, int &xMax )
  * @param yMax   This will be set to the last bin number to display in the
  *                y direction
  */
-void RefSliderHandler::getVSliderInterval( int &yMin, int &yMax )
-{
-  QScrollBar* v_scroll = m_ivUI->imageVerticalScrollBar;
-  int max   = v_scroll->maximum();
-  int step  = v_scroll->pageStep();
+void RefSliderHandler::getVSliderInterval(int &yMin, int &yMax) {
+  QScrollBar *v_scroll = m_ivUI->imageVerticalScrollBar;
+  int max = v_scroll->maximum();
+  int step = v_scroll->pageStep();
   int value = v_scroll->value();
 
-  yMin = max - value;       // invert value since scale increases from
-  yMax = yMin + step;       // bottom to top, but scroll bar increases
-                              // the other way.
+  yMin = max - value; // invert value since scale increases from
+  yMax = yMin + step; // bottom to top, but scroll bar increases
+                      // the other way.
 }
 
-
 } // namespace RefDetectorViewer
 } // namespace MantidQt
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CompositePeaksPresenter.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CompositePeaksPresenter.h
index 393f3b398d09b1b94d26852cf6bc0a6590b771e6..47f8262824757fee95de76bdbb4d5a8c96166970 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CompositePeaksPresenter.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CompositePeaksPresenter.h
@@ -105,11 +105,11 @@ public:
   void peakEditMode(EditMode mode) override;
   void
   setForegroundColor(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
-                      const PeakViewColor);
+                     const PeakViewColor);
   /// Change the background representation for the peaks of this workspace
   void
   setBackgroundColor(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
-                      const PeakViewColor);
+                     const PeakViewColor);
   /// Get the foreground colour corresponding to the workspace
   PeakViewColor getForegroundPeakViewColor(
       boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws) const;
@@ -162,9 +162,11 @@ public:
   /// Determine if the presenter contents are different.
   bool contentsDifferent(PeaksPresenter const *other) const override;
   /// Enter the requested edit mode for the peaks workspace.
-  void editCommand(EditMode editMode, boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
+  void editCommand(EditMode editMode,
+                   boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
   /// Can we add peaks to this peaks workspace.
-  bool hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
+  bool
+  hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
   /// Can we add peaks
   bool hasPeakAddMode() const override;
 
@@ -201,7 +203,6 @@ private:
   /// index of peak zoomed in on.
   int m_zoomedPeakIndex;
 };
-
 }
 }
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ConcretePeaksPresenter.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ConcretePeaksPresenter.h
index 13aa7224a710d3a89c4ffe3e7a8df86645ef35de..9710b27b9b99f7234857148faaa96a7862b03cdf 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ConcretePeaksPresenter.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ConcretePeaksPresenter.h
@@ -18,7 +18,7 @@ typedef std::vector<boost::shared_ptr<PeakOverlayView>> VecPeakOverlayView;
 
 /// Coordinate System Enum to String.
 std::string DLLExport
-    coordinateToString(Mantid::Kernel::SpecialCoordinateSystem coordSystem);
+coordinateToString(Mantid::Kernel::SpecialCoordinateSystem coordSystem);
 
 /*---------------------------------------------------------
 ConcretePeaksPresenter
@@ -111,10 +111,8 @@ private:
   /// Find visible peak indexes.
   std::vector<size_t> findVisiblePeakIndexes(const PeakBoundingBox &box);
   /// Set the visible peak list.
-  void setVisiblePeaks(const std::vector<size_t>& indexes);
+  void setVisiblePeaks(const std::vector<size_t> &indexes);
 };
-
-
 }
 }
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CustomTools.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CustomTools.h
index 7f5a60854f6b7f991ceb29dcc7374af8bd719b5c..d94b6b05098227823a09bc8cdfaec4f56bdf2d3e 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CustomTools.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/CustomTools.h
@@ -15,21 +15,17 @@
  *      Author: Janik zikovsky
  */
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
+namespace MantidQt {
+namespace SliceViewer {
 
 //========================================================================
-class PickerMachine : public QwtPickerMachine
-{
+class PickerMachine : public QwtPickerMachine {
 public:
   QwtPickerMachine::CommandList transition(const QwtEventPattern &,
                                            const QEvent *e) override {
     QwtPickerMachine::CommandList cmdList;
-    if ( e->type() == QEvent::MouseMove )
-    cmdList += Move;
+    if (e->type() == QEvent::MouseMove)
+      cmdList += Move;
 
     return cmdList;
   }
@@ -37,29 +33,25 @@ public:
 
 //========================================================================
 /** Customized QwtPlotMagnifier for zooming in on the view */
-class CustomMagnifier : public QwtPlotMagnifier
-{
+class CustomMagnifier : public QwtPlotMagnifier {
   Q_OBJECT
 public:
-  CustomMagnifier(QwtPlotCanvas* canvas): QwtPlotMagnifier(canvas)
-  {
-  }
+  CustomMagnifier(QwtPlotCanvas *canvas) : QwtPlotMagnifier(canvas) {}
 signals:
   /// Signal to emitted upon scaling.
-  void rescaled(double factor) const;  
+  void rescaled(double factor) const;
+
 protected:
   /** Method to flip the way the wheel operates */
   void rescale(double factor) override;
 };
 
-
 /** Picker for looking at the data under the mouse */
-class CustomPicker : public QwtPlotPicker
-{
+class CustomPicker : public QwtPlotPicker {
   Q_OBJECT
 
 public:
-  CustomPicker(int xAxis, int yAxis, QwtPlotCanvas* canvas);
+  CustomPicker(int xAxis, int yAxis, QwtPlotCanvas *canvas);
   void widgetMouseMoveEvent(QMouseEvent *e) override;
   void widgetLeaveEvent(QEvent *) override;
 
@@ -76,15 +68,11 @@ protected:
   QwtText trackerText(const QwtDoublePoint &pos) const override;
 };
 
-
-
 //========================================================================
 /** Custom zoomer for zooming onto the slice */
-class CustomZoomer: public QwtPlotZoomer
-{
+class CustomZoomer : public QwtPlotZoomer {
 public:
-  CustomZoomer(QwtPlotCanvas* canvas): QwtPlotZoomer(canvas)
-  {
+  CustomZoomer(QwtPlotCanvas *canvas) : QwtPlotZoomer(canvas) {
     setTrackerMode(QwtPicker::AlwaysOn);
   }
 
@@ -92,16 +80,14 @@ protected:
   // Unhide base class method (avoids Intel compiler warning)
   using QwtPlotZoomer::trackerText;
   QwtText trackerText(const QwtDoublePoint &p) const override {
-    QwtText t( QwtPlotPicker::trackerText( p ));
+    QwtText t(QwtPlotPicker::trackerText(p));
     QColor c(Qt::white);
     c.setAlpha(120);
-    t.setBackgroundBrush( QBrush(c) );
+    t.setBackgroundBrush(QBrush(c));
     return t;
   }
 };
 
-
-
 } // namespace SliceViewer
 } // namespace Mantid
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DimensionSliceWidget.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DimensionSliceWidget.h
index f0debc6b57b648e0a2fc3d5cdb22c897079d1d8c..57c946eb24abd095304080efce527b7dd7ff3271 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DimensionSliceWidget.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DimensionSliceWidget.h
@@ -6,11 +6,8 @@
 #include "MantidGeometry/MDGeometry/IMDDimension.h"
 #include "DllOption.h"
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
+namespace MantidQt {
+namespace SliceViewer {
 
 /** Widget for the 2D slice viewer. Select whether the dimension
  * is X or Y, or if it is not one to be shown, where is the
@@ -21,18 +18,16 @@ namespace SliceViewer
  * @date Oct 3, 2011
  */
 
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER DimensionSliceWidget : public QWidget
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER DimensionSliceWidget : public QWidget {
   Q_OBJECT
 
-//  /** Enum for each shown dimension */
-//  enum eShownDim
-//  {
-//    None=-1,
-//    X=0,
-//    Y=1
-//  };
-
+  //  /** Enum for each shown dimension */
+  //  enum eShownDim
+  //  {
+  //    None=-1,
+  //    X=0,
+  //    Y=1
+  //  };
 
 public:
   DimensionSliceWidget(QWidget *parent = 0);
@@ -52,16 +47,12 @@ public:
   double getThickness() const;
   void setThickness(double val);
 
-  double getSlicePoint() const
-  { return m_slicePoint; }
+  double getSlicePoint() const { return m_slicePoint; }
 
-  std::string getDimName() const
-  { return m_dim->getName(); }
+  std::string getDimName() const { return m_dim->getName(); }
 
   /// @return the shown dimension, 0=X, 1=Y, -1=None
-  int getShownDim() const
-  { return m_shownDim; }
-
+  int getShownDim() const { return m_shownDim; }
 
 public slots:
   void sliderMoved();
@@ -87,7 +78,8 @@ private:
   /// The index of the dimension into the workspace
   int m_dimIndex;
 
-  /// Which dimension is being shown. -1 = None, 0 = X, 1 = Y. 2+ reserved for higher dimensions
+  /// Which dimension is being shown. -1 = None, 0 = X, 1 = Y. 2+ reserved for
+  /// higher dimensions
   int m_shownDim;
 
   /// If the dimensions is not shown, where is the slice point?
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DllOption.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DllOption.h
index d0b531a6d85f82bb5080e32cf099e1ac805326bb..f3c1e1311d66d3e9b653d08deb7a2e1302cb58f3 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DllOption.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/DllOption.h
@@ -9,4 +9,4 @@
 #define EXPORT_OPT_MANTIDQT_SLICEVIEWER DLLImport
 #endif
 
-#endif //MANTIDQT_MANTIDSLICEVIEWER_DLLOPTION_H_
+#endif // MANTIDQT_MANTIDSLICEVIEWER_DLLOPTION_H_
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/EllipsoidPlaneSliceCalculator.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/EllipsoidPlaneSliceCalculator.h
index b915bd9a3a060e07b310cc83d79bb14e52bcf60a..6ac12c3c761c79b77ddab8a273c0bfd0af2daa1f 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/EllipsoidPlaneSliceCalculator.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/EllipsoidPlaneSliceCalculator.h
@@ -7,18 +7,17 @@
 #include "MantidQtSliceViewer/PeakBoundingBox.h"
 #include <vector>
 
-namespace Mantid
-{
-namespace SliceViewer
-{
+namespace Mantid {
+namespace SliceViewer {
 
 template <class T>
-  typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
-  EXPORT_OPT_MANTIDQT_SLICEVIEWER almost_equal(T x, T y)
-  {
-      return std::abs(x - y) < std::numeric_limits<T>::epsilon() * std::abs(x + y)
-             || std::abs(x - y) < std::numeric_limits<T>::min();
-  }
+typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
+    EXPORT_OPT_MANTIDQT_SLICEVIEWER
+    almost_equal(T x, T y) {
+  return std::abs(x - y) <
+             std::numeric_limits<T>::epsilon() * std::abs(x + y) ||
+         std::abs(x - y) < std::numeric_limits<T>::min();
+}
 
 Mantid::Kernel::Matrix<double> EXPORT_OPT_MANTIDQT_SLICEVIEWER
 createEllipsoidMatrixInXYZFrame(std::vector<Mantid::Kernel::V3D> directions,
@@ -34,39 +33,37 @@ getProjectionLengths(const std::vector<Mantid::Kernel::V3D> &directions,
                      std::vector<double> radii);
 
 MantidQt::SliceViewer::PeakBoundingBox EXPORT_OPT_MANTIDQT_SLICEVIEWER
-getPeakBoundingBoxForEllipsoid(const std::vector<Mantid::Kernel::V3D> &directions,
-                             const std::vector<double> &radii,
-                             const Mantid::Kernel::V3D &originEllipsoid);
+getPeakBoundingBoxForEllipsoid(
+    const std::vector<Mantid::Kernel::V3D> &directions,
+    const std::vector<double> &radii,
+    const Mantid::Kernel::V3D &originEllipsoid);
 
 struct EXPORT_OPT_MANTIDQT_SLICEVIEWER SliceEllipseInfo {
-    SliceEllipseInfo(Mantid::Kernel::V3D origin = Mantid::Kernel::V3D(0, 0, 0),
-                     double radiusMajorAxis = 0.0, double radiusMinorAxis = 0.0,
-                     double angle = 0.0)
-        : origin(origin), radiusMajorAxis(radiusMajorAxis),
-          radiusMinorAxis(radiusMinorAxis), angle(angle)
-    {
-    }
-    Mantid::Kernel::V3D origin;
-    double radiusMajorAxis;
-    double radiusMinorAxis;
-    double angle;
+  SliceEllipseInfo(Mantid::Kernel::V3D origin = Mantid::Kernel::V3D(0, 0, 0),
+                   double radiusMajorAxis = 0.0, double radiusMinorAxis = 0.0,
+                   double angle = 0.0)
+      : origin(origin), radiusMajorAxis(radiusMajorAxis),
+        radiusMinorAxis(radiusMinorAxis), angle(angle) {}
+  Mantid::Kernel::V3D origin;
+  double radiusMajorAxis;
+  double radiusMinorAxis;
+  double angle;
 };
 
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER EllipsoidPlaneSliceCalculator
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER EllipsoidPlaneSliceCalculator {
 public:
-    SliceEllipseInfo
-    getSlicePlaneInfo(std::vector<Mantid::Kernel::V3D> directions,
-                      std::vector<double> radii,
-                      Mantid::Kernel::V3D originEllipsoid, double zPlane) const;
+  SliceEllipseInfo
+  getSlicePlaneInfo(std::vector<Mantid::Kernel::V3D> directions,
+                    std::vector<double> radii,
+                    Mantid::Kernel::V3D originEllipsoid, double zPlane) const;
 
 private:
-    SliceEllipseInfo
-    getSolutionForEllipsoid(const Kernel::Matrix<double> &m, double zPlane,
-                            Mantid::Kernel::V3D originEllipsoid) const;
+  SliceEllipseInfo
+  getSolutionForEllipsoid(const Kernel::Matrix<double> &m, double zPlane,
+                          Mantid::Kernel::V3D originEllipsoid) const;
 
-    bool checkIfIsEllipse(const Kernel::Matrix<double> &m) const;
-    bool checkIfIsCircle(const Kernel::Matrix<double> &m) const;
+  bool checkIfIsEllipse(const Kernel::Matrix<double> &m) const;
+  bool checkIfIsCircle(const Kernel::Matrix<double> &m) const;
 };
 }
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/FirstExperimentInfoQuery.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/FirstExperimentInfoQuery.h
index 41135772e94adff17ba3a91a206aa64e46764ea6..6042efc4cff80e01aa361256c1af196dd1159b7c 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/FirstExperimentInfoQuery.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/FirstExperimentInfoQuery.h
@@ -5,74 +5,69 @@
 #include "MantidAPI/IMDWorkspace.h"
 #include "MantidAPI/MultipleExperimentInfos.h"
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /*---------------------------------------------------------
-    FirstExperimentInfoQuery
+namespace MantidQt {
+namespace SliceViewer {
+/*---------------------------------------------------------
+FirstExperimentInfoQuery
 
-    Represents a query against the first experiment info of a workspace.
-    ----------------------------------------------------------*/
-    class DLLExport FirstExperimentInfoQuery
-    {
-    public:
-      virtual bool hasOrientedLattice() const = 0;
-      virtual bool hasRotatedGoniometer() const  = 0;
-    };
+Represents a query against the first experiment info of a workspace.
+----------------------------------------------------------*/
+class DLLExport FirstExperimentInfoQuery {
+public:
+  virtual bool hasOrientedLattice() const = 0;
+  virtual bool hasRotatedGoniometer() const = 0;
+};
 
-    /*---------------------------------------------------------
-    FirstExperimentInfoQueryAdapter
+/*---------------------------------------------------------
+FirstExperimentInfoQueryAdapter
 
-    Templated adapter over the FirstExperimentInfoQuery interface.
-    ----------------------------------------------------------*/
-    template <typename T>
-    class DLLExport FirstExperimentInfoQueryAdapter : public FirstExperimentInfoQuery
-    {
-    public:
+Templated adapter over the FirstExperimentInfoQuery interface.
+----------------------------------------------------------*/
+template <typename T>
+class DLLExport FirstExperimentInfoQueryAdapter
+    : public FirstExperimentInfoQuery {
+public:
+  typedef boost::shared_ptr<const T> Adaptee_sptr;
 
-      typedef boost::shared_ptr<const T> Adaptee_sptr;
+private:
+  Adaptee_sptr m_ws;
 
-    private:
-
-      Adaptee_sptr m_ws;
-
-    public:
-
-      FirstExperimentInfoQueryAdapter(Mantid::API::IMDWorkspace_sptr ws) 
-      {
-        m_ws = boost::dynamic_pointer_cast<const T>(ws);
-        if(!m_ws)
-        {
-          throw std::invalid_argument("Workspace object is of the wrong type for this adapter.");
-        }
-      }
+public:
+  FirstExperimentInfoQueryAdapter(Mantid::API::IMDWorkspace_sptr ws) {
+    m_ws = boost::dynamic_pointer_cast<const T>(ws);
+    if (!m_ws) {
+      throw std::invalid_argument(
+          "Workspace object is of the wrong type for this adapter.");
+    }
+  }
 
-      bool hasOrientedLattice() const
-      {
-        Mantid::API::MultipleExperimentInfos_const_sptr expInfos = boost::dynamic_pointer_cast<const Mantid::API::MultipleExperimentInfos>(m_ws);  
-        bool hasLattice = false;
-        if( expInfos != NULL && expInfos->getNumExperimentInfo() > 0)
-        {
-          Mantid::API::ExperimentInfo_const_sptr expInfo = expInfos->getExperimentInfo(0);
-          hasLattice = expInfo->sample().hasOrientedLattice();
-        }
-        return hasLattice;
-      }
+  bool hasOrientedLattice() const {
+    Mantid::API::MultipleExperimentInfos_const_sptr expInfos =
+        boost::dynamic_pointer_cast<const Mantid::API::MultipleExperimentInfos>(
+            m_ws);
+    bool hasLattice = false;
+    if (expInfos != NULL && expInfos->getNumExperimentInfo() > 0) {
+      Mantid::API::ExperimentInfo_const_sptr expInfo =
+          expInfos->getExperimentInfo(0);
+      hasLattice = expInfo->sample().hasOrientedLattice();
+    }
+    return hasLattice;
+  }
 
-      bool hasRotatedGoniometer() const
-      {
-        Mantid::API::MultipleExperimentInfos_const_sptr expInfos = boost::dynamic_pointer_cast<const Mantid::API::MultipleExperimentInfos>(m_ws);  
-        bool hasRotatedGoniometer = false;
-        if( expInfos != NULL && expInfos->getNumExperimentInfo() > 0)
-        {
-          Mantid::API::ExperimentInfo_const_sptr expInfo = expInfos->getExperimentInfo(0);
-          hasRotatedGoniometer = expInfo->run().getGoniometerMatrix().isRotation();
-        }
-        return hasRotatedGoniometer;
-      }
-    };
+  bool hasRotatedGoniometer() const {
+    Mantid::API::MultipleExperimentInfos_const_sptr expInfos =
+        boost::dynamic_pointer_cast<const Mantid::API::MultipleExperimentInfos>(
+            m_ws);
+    bool hasRotatedGoniometer = false;
+    if (expInfos != NULL && expInfos->getNumExperimentInfo() > 0) {
+      Mantid::API::ExperimentInfo_const_sptr expInfo =
+          expInfos->getExperimentInfo(0);
+      hasRotatedGoniometer = expInfo->run().getGoniometerMatrix().isRotation();
+    }
+    return hasRotatedGoniometer;
   }
+};
+}
 }
 
 #endif /* MANTID_SLICEVIEWER_FIRSTEXPERIMENTINFOQUERY_H_ */
\ No newline at end of file
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineOverlay.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineOverlay.h
index 5ad7bb2243da792fae24312eac56e8bc9c0d7120..e492db8b2b4be1a643e37b23d80f0fa6039c7721 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineOverlay.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LineOverlay.h
@@ -8,174 +8,164 @@
 #include <qwt_plot.h>
 #include <qpainter.h>
 
-
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
-  /** GUI for overlaying a line with a width onto the plot
-    in the SliceViewer. Should be generic to overlays on any QwtPlot.
-    Drag/droppable.
-    
-    @date 2011-11-14
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class EXPORT_OPT_MANTIDQT_SLICEVIEWER LineOverlay : public QWidget
-  {
-    Q_OBJECT
-
-    /// Enum giving IDs to the 4 handles on the widget
-    enum eHandleID
-    {
-      HandleNone = -1,
-      HandleA = 0,
-      HandleB = 1,
-      HandleWidthTop = 2,
-      HandleWidthBottom = 3,
-      HandleCenter = 4 // Anywhere inside the center
-    };
-
-  public:
-    LineOverlay(QwtPlot * plot, QWidget * parent);
-    ~LineOverlay() override;
-
-    void reset();
-
-    void setPointA(QPointF pointA);
-    void setPointB(QPointF pointB);
-    void setWidth(double width);
-
-    const QPointF & getPointA() const;
-    const QPointF & getPointB() const;
-    double getWidth() const;
-
-    void setSnapX(double spacing);
-    void setSnapY(double spacing);
-    void setSnap(double spacing);
-    void setSnapEnabled(bool enabled);
-    void setSnapLength(double spacing);
-    void setShown(bool shown);
-    void setShowHandles(bool shown);
-    void setShowLine(bool shown);
-    void setCreationMode(bool creation);
-    void setAngleSnapMode(bool angleSnap);
-    void setAngleSnap(double snapDegrees);
-
-    ///@return the snap-to X interval
-    double getSnapX()
-    { return m_snapX; }
-
-    ///@return the snap-to X interval
-    double getSnapY()
-    { return m_snapY; }
-
-    ///@return true if the line is in creation mode (waiting for first click)
-    bool getCreationMode() const
-    { return m_creation; }
-
-
-  signals:
-    /// Signal sent while the line is being dragged
-    void lineChanging(QPointF, QPointF, double);
-    /// Signal sent once the drag is completed
-    void lineChanged(QPointF, QPointF, double);
-
-  private:
-    QPoint transform(QPointF coords) const;
-    QPointF invTransform(QPoint pixels) const;
-    QPointF snap(QPointF original) const;
-
-    QSize sizeHint() const override;
-    QSize size() const;
-    int height() const;
-    int width() const;
-
-    QRect drawHandle(QPainter & painter, QPointF coords, QColor brush);
-    void paintEvent(QPaintEvent *event) override;
-
-    eHandleID mouseOverHandle(QPoint pos);
-    bool mouseOverCenter(QPoint pos);
-    void handleDrag(QMouseEvent * event);
-    void mouseMoveEvent(QMouseEvent *event) override;
-    void mousePressEvent(QMouseEvent *event) override;
-    void mouseReleaseEvent(QMouseEvent *event) override;
-
-  protected:
-    /// Marker that we are just creating the line (with the mouse)
-    bool m_creation;
-
-    /// QwtPlot containing this
-    QwtPlot * m_plot;
-
-    /// First point of the line (in coordinates of the plot)
-    QPointF m_pointA;
-    /// Second point of the line (in coordinates of the plot)
-    QPointF m_pointB;
-    /// Width of the line (in coordinates of the plot)
-    double m_width;
-    /// Rects defining where the 4 handles are
-    QVector<QRect> m_handles;
-
-    /// When dragging, this is the handle being dragged
-    eHandleID m_dragHandle;
-    /// Start point (in plot coords) of the drag
-    QPointF m_dragStart;
-    /// Original PointA at drag start
-    QPointF m_dragStart_PointA;
-    /// Original PointB at drag start
-    QPointF m_dragStart_PointB;
-
-    /// Marker that the middle mouse button is pressed (panning)
-    bool m_rightButton;
-
-    /// Is snap-to-grid enabled?
-    bool m_snapEnabled;
-    /// Snap to grid spacing in X
-    double m_snapX;
-    /// Grid spacing in Y
-    double m_snapY;
-    /// Snap to length of the line
-    double m_snapLength;
-
-    /// Is any of the control visible?
-    bool m_shown;
-
-    /// Are the mouse handles visible?
-    bool m_showHandles;
-
-    /// Show the central line?
-    bool m_showLine;
-
-    /// If true, then you are in always-snap mode
-    bool m_angleSnapMode;
-
-    /// Angle (in degrees) to snap to.
-    double m_angleSnap;
-
+namespace MantidQt {
+namespace SliceViewer {
+
+/** GUI for overlaying a line with a width onto the plot
+  in the SliceViewer. Should be generic to overlays on any QwtPlot.
+  Drag/droppable.
+
+  @date 2011-11-14
+
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER LineOverlay : public QWidget {
+  Q_OBJECT
+
+  /// Enum giving IDs to the 4 handles on the widget
+  enum eHandleID {
+    HandleNone = -1,
+    HandleA = 0,
+    HandleB = 1,
+    HandleWidthTop = 2,
+    HandleWidthBottom = 3,
+    HandleCenter = 4 // Anywhere inside the center
   };
 
+public:
+  LineOverlay(QwtPlot *plot, QWidget *parent);
+  ~LineOverlay() override;
+
+  void reset();
+
+  void setPointA(QPointF pointA);
+  void setPointB(QPointF pointB);
+  void setWidth(double width);
+
+  const QPointF &getPointA() const;
+  const QPointF &getPointB() const;
+  double getWidth() const;
+
+  void setSnapX(double spacing);
+  void setSnapY(double spacing);
+  void setSnap(double spacing);
+  void setSnapEnabled(bool enabled);
+  void setSnapLength(double spacing);
+  void setShown(bool shown);
+  void setShowHandles(bool shown);
+  void setShowLine(bool shown);
+  void setCreationMode(bool creation);
+  void setAngleSnapMode(bool angleSnap);
+  void setAngleSnap(double snapDegrees);
+
+  ///@return the snap-to X interval
+  double getSnapX() { return m_snapX; }
+
+  ///@return the snap-to X interval
+  double getSnapY() { return m_snapY; }
+
+  ///@return true if the line is in creation mode (waiting for first click)
+  bool getCreationMode() const { return m_creation; }
+
+signals:
+  /// Signal sent while the line is being dragged
+  void lineChanging(QPointF, QPointF, double);
+  /// Signal sent once the drag is completed
+  void lineChanged(QPointF, QPointF, double);
+
+private:
+  QPoint transform(QPointF coords) const;
+  QPointF invTransform(QPoint pixels) const;
+  QPointF snap(QPointF original) const;
+
+  QSize sizeHint() const override;
+  QSize size() const;
+  int height() const;
+  int width() const;
+
+  QRect drawHandle(QPainter &painter, QPointF coords, QColor brush);
+  void paintEvent(QPaintEvent *event) override;
+
+  eHandleID mouseOverHandle(QPoint pos);
+  bool mouseOverCenter(QPoint pos);
+  void handleDrag(QMouseEvent *event);
+  void mouseMoveEvent(QMouseEvent *event) override;
+  void mousePressEvent(QMouseEvent *event) override;
+  void mouseReleaseEvent(QMouseEvent *event) override;
+
+protected:
+  /// Marker that we are just creating the line (with the mouse)
+  bool m_creation;
+
+  /// QwtPlot containing this
+  QwtPlot *m_plot;
+
+  /// First point of the line (in coordinates of the plot)
+  QPointF m_pointA;
+  /// Second point of the line (in coordinates of the plot)
+  QPointF m_pointB;
+  /// Width of the line (in coordinates of the plot)
+  double m_width;
+  /// Rects defining where the 4 handles are
+  QVector<QRect> m_handles;
+
+  /// When dragging, this is the handle being dragged
+  eHandleID m_dragHandle;
+  /// Start point (in plot coords) of the drag
+  QPointF m_dragStart;
+  /// Original PointA at drag start
+  QPointF m_dragStart_PointA;
+  /// Original PointB at drag start
+  QPointF m_dragStart_PointB;
+
+  /// Marker that the middle mouse button is pressed (panning)
+  bool m_rightButton;
+
+  /// Is snap-to-grid enabled?
+  bool m_snapEnabled;
+  /// Snap to grid spacing in X
+  double m_snapX;
+  /// Grid spacing in Y
+  double m_snapY;
+  /// Snap to length of the line
+  double m_snapLength;
+
+  /// Is any of the control visible?
+  bool m_shown;
+
+  /// Are the mouse handles visible?
+  bool m_showHandles;
+
+  /// Show the central line?
+  bool m_showLine;
+
+  /// If true, then you are in always-snap mode
+  bool m_angleSnapMode;
+
+  /// Angle (in degrees) to snap to.
+  double m_angleSnap;
+};
 
 } // namespace SliceViewer
 } // namespace Mantid
 
-#endif  /* MANTID_SLICEVIEWER_LINEOVERLAY_H_ */
+#endif /* MANTID_SLICEVIEWER_LINEOVERLAY_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LinePlotOptions.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LinePlotOptions.h
index 9f1787d1bec2f342bf3c26135eed24e30cd3da25..9230505e08d856a9d7b0b6c5ea0ea05703230308 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LinePlotOptions.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/LinePlotOptions.h
@@ -7,12 +7,11 @@
 #include "MantidAPI/IMDWorkspace.h"
 #include "DllOption.h"
 
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER LinePlotOptions : public QWidget
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER LinePlotOptions : public QWidget {
   Q_OBJECT
 
 public:
-  LinePlotOptions(QWidget *parent = 0, bool logScaleOption=false);
+  LinePlotOptions(QWidget *parent = 0, bool logScaleOption = false);
   ~LinePlotOptions() override;
 
   void setOriginalWorkspace(Mantid::API::IMDWorkspace_sptr ws);
@@ -38,8 +37,8 @@ signals:
   void changedYLogScaling();
 
 private:
-
-  void addPlotRadioButton(const std::string & text, const std::string & tooltip, const bool bIntegrated = false);
+  void addPlotRadioButton(const std::string &text, const std::string &tooltip,
+                          const bool bIntegrated = false);
 
   Ui::LinePlotOptionsClass ui;
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/NullPeaksPresenter.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/NullPeaksPresenter.h
index 949bf2fb2bce7aa19c7c67481104194b6f2a18df..9ccc20bf407cf137f039ab35c8bd86daae95aab9 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/NullPeaksPresenter.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/NullPeaksPresenter.h
@@ -68,7 +68,6 @@ public:
   }
   bool hasPeakAddMode() const override { return false; /*Do nothing.*/ }
 };
-
 }
 }
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakBoundingBox.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakBoundingBox.h
index bea7d2307cec0cee594f7db7d82ced61a739a205..e9f6611bcabe71500b6a6eb5868098a4fdcc5508 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakBoundingBox.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakBoundingBox.h
@@ -6,122 +6,125 @@
 #include <vector>
 #include "MantidGeometry/Crystal/PeakTransform.h"
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /**
-    DoubleParam
-    IntToType Parameter Type. Simple mechanism for ensuring type 
-    safety when working with so many arguments of the same core type in PeakBoundingBox.
-    */
-    template<int I>
-    class DLLExport DoubleParam
-    {
-    public:
-      explicit DoubleParam(const double& val) : value(val){}
-      DoubleParam(const DoubleParam<I>& other) : value(other.value) {}
-      DoubleParam<I>& operator=(const DoubleParam<I>& other){value = other.value; return *this;}
-      double operator()() const {return value;}
-    private:
-      double value;
-      enum{typeValue = I};
-    };
+namespace MantidQt {
+namespace SliceViewer {
+/**
+DoubleParam
+IntToType Parameter Type. Simple mechanism for ensuring type
+safety when working with so many arguments of the same core type in
+PeakBoundingBox.
+*/
+template <int I> class DLLExport DoubleParam {
+public:
+  explicit DoubleParam(const double &val) : value(val) {}
+  DoubleParam(const DoubleParam<I> &other) : value(other.value) {}
+  DoubleParam<I> &operator=(const DoubleParam<I> &other) {
+    value = other.value;
+    return *this;
+  }
+  double operator()() const { return value; }
 
-    typedef DoubleParam<0> Left;
-    typedef DoubleParam<1> Right;
-    typedef DoubleParam<2> Top;
-    typedef DoubleParam<3> Bottom;
-    typedef DoubleParam<4> SlicePoint;
-    typedef DoubleParam<5> Front;
-    typedef DoubleParam<6> Back;
+private:
+  double value;
+  enum { typeValue = I };
+};
 
-    /** A bounding box for a peak. Allows the SliceViewer to zoom to that region.
-    
-    @date 2013-01-09
+typedef DoubleParam<0> Left;
+typedef DoubleParam<1> Right;
+typedef DoubleParam<2> Top;
+typedef DoubleParam<3> Bottom;
+typedef DoubleParam<4> SlicePoint;
+typedef DoubleParam<5> Front;
+typedef DoubleParam<6> Back;
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+/** A bounding box for a peak. Allows the SliceViewer to zoom to that region.
 
-    This file is part of Mantid.
+@date 2013-01-09
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+This file is part of Mantid.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport PeakBoundingBox
-    {
-    private:
-      
-      /// Left edge
-      Left m_left;
-      /// Right edge
-      Right m_right;
-      /// Top edge
-      Top m_top;
-      /// Bottom edge.
-      Bottom m_bottom;
-      /// Slice parallel to projection (z) position
-      SlicePoint m_slicePoint;
-      /// Front edge
-      Front m_front;
-      /// Back edge
-      Back m_back;
-      /// Check boundaries
-      void validateBoundaries();
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    public:
-      /// Default constructor
-      PeakBoundingBox();
-      /// Constructor
-      PeakBoundingBox(const Left& left, const Right& right, const Top& top, const Bottom& bottom, const SlicePoint& slicePoint);
-      /// Constructor
-      PeakBoundingBox(const Left& left, const Right& right, const Top& top, const Bottom& bottom, const SlicePoint& slicePoint, const Front& front, const Back& back);
-      /// Destructor
-      ~PeakBoundingBox();
-      /// Copy constructor
-      PeakBoundingBox(const PeakBoundingBox& other);
-      /// Assignment
-      PeakBoundingBox& operator=(const PeakBoundingBox& other);
-      /// Equals
-      bool operator==(const PeakBoundingBox &other) const;
-      /// Not equals
-      bool operator!=(const PeakBoundingBox &other) const;
-      /// Get the box left edge
-      double left() const;
-      /// Get the box right edge
-      double right() const;
-      /// Get the box top edge
-      double top() const;
-      /// Get the box bottom edge
-      double bottom() const;
-      /// Get the slice point
-      double slicePoint() const;
-      /// Get the back edge
-      double front() const;
-      /// Get the front edge
-      double back() const;
-      /// Serialize as a vector of extents.
-      std::vector<double> toExtents() const;
-      /// Serialize as set of comma separated values
-      std::string toExtentsString() const;
-      /// Transform the box.
-      void transformBox(Mantid::Geometry::PeakTransform_sptr transform);
-      /// Make a new box based on the slice
-      PeakBoundingBox makeSliceBox(const double& sliceDelta) const;
-    };
-  }
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport PeakBoundingBox {
+private:
+  /// Left edge
+  Left m_left;
+  /// Right edge
+  Right m_right;
+  /// Top edge
+  Top m_top;
+  /// Bottom edge.
+  Bottom m_bottom;
+  /// Slice parallel to projection (z) position
+  SlicePoint m_slicePoint;
+  /// Front edge
+  Front m_front;
+  /// Back edge
+  Back m_back;
+  /// Check boundaries
+  void validateBoundaries();
+
+public:
+  /// Default constructor
+  PeakBoundingBox();
+  /// Constructor
+  PeakBoundingBox(const Left &left, const Right &right, const Top &top,
+                  const Bottom &bottom, const SlicePoint &slicePoint);
+  /// Constructor
+  PeakBoundingBox(const Left &left, const Right &right, const Top &top,
+                  const Bottom &bottom, const SlicePoint &slicePoint,
+                  const Front &front, const Back &back);
+  /// Destructor
+  ~PeakBoundingBox();
+  /// Copy constructor
+  PeakBoundingBox(const PeakBoundingBox &other);
+  /// Assignment
+  PeakBoundingBox &operator=(const PeakBoundingBox &other);
+  /// Equals
+  bool operator==(const PeakBoundingBox &other) const;
+  /// Not equals
+  bool operator!=(const PeakBoundingBox &other) const;
+  /// Get the box left edge
+  double left() const;
+  /// Get the box right edge
+  double right() const;
+  /// Get the box top edge
+  double top() const;
+  /// Get the box bottom edge
+  double bottom() const;
+  /// Get the slice point
+  double slicePoint() const;
+  /// Get the back edge
+  double front() const;
+  /// Get the front edge
+  double back() const;
+  /// Serialize as a vector of extents.
+  std::vector<double> toExtents() const;
+  /// Serialize as set of comma separated values
+  std::string toExtentsString() const;
+  /// Transform the box.
+  void transformBox(Mantid::Geometry::PeakTransform_sptr transform);
+  /// Make a new box based on the slice
+  PeakBoundingBox makeSliceBox(const double &sliceDelta) const;
+};
+}
 }
 
 #endif /* MANTID_SLICEVIEWER_PEAK_BOUNDING_BOX_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayInteractive.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayInteractive.h
index 713a139b827b809ea680ddd6877e592a4710b2f9..bfa3f78c0e1274872ad4665d5a482477c1f6b01f 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayInteractive.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayInteractive.h
@@ -45,13 +45,16 @@ class PeaksPresenter;
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER PeakOverlayInteractive : public QWidget, public PeakOverlayView {
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER PeakOverlayInteractive
+    : public QWidget,
+      public PeakOverlayView {
   Q_OBJECT
 
 public:
   /// Constructor
   PeakOverlayInteractive(PeaksPresenter *const peaksPresenter, QwtPlot *plot,
-                        const int plotXIndex, const int plotYIndex, QWidget *parent);
+                         const int plotXIndex, const int plotYIndex,
+                         QWidget *parent);
   /// Destructor
   ~PeakOverlayInteractive() override;
 
@@ -100,12 +103,8 @@ private slots:
 
   void erasePeaks(const QRect &rect);
   void addPeakAt(int coordX, int coordY);
-
-
 };
-
-
 }
 }
 
-#endif //MANTID_SLICEVIEWER_PEAKOVERLAYINTERACTIVE_H_
+#endif // MANTID_SLICEVIEWER_PEAKOVERLAYINTERACTIVE_H_
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayView.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayView.h
index 33dc40c86040c0eed89bc54896c77bde01c33366..3d4b58b57e3638c2208b48b7632bd351d59d153d 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayView.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayView.h
@@ -10,92 +10,91 @@
 #include <QPointF>
 #include <boost/shared_ptr.hpp>
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
+namespace MantidQt {
+namespace SliceViewer {
 
-    /** Abstract view in MVP model representing a PeakOverlay.
-    
-    @date 2012-08-24
+/** Abstract view in MVP model representing a PeakOverlay.
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+@date 2012-08-24
 
-    This file is part of Mantid.
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport PeakOverlayView
-    {
-    public:
-      /// Set the position of the slice point.
-      virtual void setSlicePoint(const double&, const std::vector<bool>&) = 0;
-      /// Update the view.
-      virtual void updateView() = 0;
-      /// Hide the view.
-      virtual void hideView() = 0;
-      /// Show the view.
-      virtual void showView() = 0;
-      /// Move the peak overlay to a new position.
-      virtual void movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) = 0;
-      /// Show the background radius
-      virtual void showBackgroundRadius(const bool){}
-      /// Changes the size of the overlay to be the requested fraction of the current view width.
-      virtual void changeOccupancyInView(const double fraction) = 0;
-      /// Changes the size of the overlay to be the requested fraction of the view depth.
-      virtual void changeOccupancyIntoView(const double fraction) = 0;
-      /// Get a bounding box around the peak in windows coordinates.
-      virtual PeakBoundingBox getBoundingBox(const int peakIndex) const = 0;
-      /// Get the peak size (width/2 as a fraction of total width)  on projection
-      virtual double getOccupancyInView() const = 0;
-      /// Get the peaks size into the projection (effective radius as a fraction of z range)
-      virtual double getOccupancyIntoView() const = 0;
-      /// Get the flag indicating that the view represents the position only.
-      virtual bool positionOnly() const = 0;
-      /// Get radius or effective radius of view items.
-      virtual double getRadius() const = 0;
-      /// Determine if the background is shown.
-      virtual bool isBackgroundShown() const = 0;
-      /// Enter deletion mode
-      virtual void peakDeletionMode() = 0;
-      /// Enter addition mode
-      virtual void peakAdditionMode() = 0;
-      /// Enter normal view mode
-      virtual void peakDisplayMode() = 0;
-      /// Take settings from.
-      virtual void takeSettingsFrom(PeakOverlayView const * const) = 0;
-      /// Change foreground colour -- overload for PeakViewColor
-      virtual void changeForegroundColour(const PeakViewColor) = 0;
-      /// Change background colour -- overload for PeakViewColor
-      virtual void changeBackgroundColour(const PeakViewColor) = 0;
-      /// Get the current background colour
-      virtual PeakViewColor getBackgroundPeakViewColor() const = 0;
-      /// Get the current foreground colour
-      virtual PeakViewColor getForegroundPeakViewColor() const = 0;
-      /// Destructor
-      virtual ~PeakOverlayView()
-      {
-      }
-    };
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    typedef boost::shared_ptr<const PeakOverlayView> PeakOverlayView_const_sptr;
-    typedef boost::shared_ptr<PeakOverlayView> PeakOverlayView_sptr;
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport PeakOverlayView {
+public:
+  /// Set the position of the slice point.
+  virtual void setSlicePoint(const double &, const std::vector<bool> &) = 0;
+  /// Update the view.
+  virtual void updateView() = 0;
+  /// Hide the view.
+  virtual void hideView() = 0;
+  /// Show the view.
+  virtual void showView() = 0;
+  /// Move the peak overlay to a new position.
+  virtual void
+  movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) = 0;
+  /// Show the background radius
+  virtual void showBackgroundRadius(const bool) {}
+  /// Changes the size of the overlay to be the requested fraction of the
+  /// current view width.
+  virtual void changeOccupancyInView(const double fraction) = 0;
+  /// Changes the size of the overlay to be the requested fraction of the view
+  /// depth.
+  virtual void changeOccupancyIntoView(const double fraction) = 0;
+  /// Get a bounding box around the peak in windows coordinates.
+  virtual PeakBoundingBox getBoundingBox(const int peakIndex) const = 0;
+  /// Get the peak size (width/2 as a fraction of total width)  on projection
+  virtual double getOccupancyInView() const = 0;
+  /// Get the peaks size into the projection (effective radius as a fraction of
+  /// z range)
+  virtual double getOccupancyIntoView() const = 0;
+  /// Get the flag indicating that the view represents the position only.
+  virtual bool positionOnly() const = 0;
+  /// Get radius or effective radius of view items.
+  virtual double getRadius() const = 0;
+  /// Determine if the background is shown.
+  virtual bool isBackgroundShown() const = 0;
+  /// Enter deletion mode
+  virtual void peakDeletionMode() = 0;
+  /// Enter addition mode
+  virtual void peakAdditionMode() = 0;
+  /// Enter normal view mode
+  virtual void peakDisplayMode() = 0;
+  /// Take settings from.
+  virtual void takeSettingsFrom(PeakOverlayView const *const) = 0;
+  /// Change foreground colour -- overload for PeakViewColor
+  virtual void changeForegroundColour(const PeakViewColor) = 0;
+  /// Change background colour -- overload for PeakViewColor
+  virtual void changeBackgroundColour(const PeakViewColor) = 0;
+  /// Get the current background colour
+  virtual PeakViewColor getBackgroundPeakViewColor() const = 0;
+  /// Get the current foreground colour
+  virtual PeakViewColor getForegroundPeakViewColor() const = 0;
+  /// Destructor
+  virtual ~PeakOverlayView() {}
+};
 
-  }
+typedef boost::shared_ptr<const PeakOverlayView> PeakOverlayView_const_sptr;
+typedef boost::shared_ptr<PeakOverlayView> PeakOverlayView_sptr;
+}
 }
 
 #endif /* MANTID_SLICEVIEWER_PEAKOVERLAY_VIEW_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactory.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactory.h
index a3ecc504c80fa572317b46eeaf4b84770e41ed5a..1374711db06d34c7a397ee66975dfc3d1f3aede3 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactory.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactory.h
@@ -7,69 +7,66 @@
 #include "MantidQtSliceViewer/PeakOverlayView.h"
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-  namespace Geometry {
-    // Forward dec.
-    class IPeak;
-  }
-  namespace API {
-    // Forward dec.
-    class IPeaksWorkspace;
-  }
+namespace Mantid {
+namespace Geometry {
+// Forward dec.
+class IPeak;
+}
+namespace API {
+// Forward dec.
+class IPeaksWorkspace;
+}
 }
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    class PeaksPresenter;
+namespace MantidQt {
+namespace SliceViewer {
+class PeaksPresenter;
 
-    /** Abstract view factory. For creating types of IPeakOverlay.
-    
-    @date 2012-08-24
+/** Abstract view factory. For creating types of IPeakOverlay.
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+@date 2012-08-24
 
-    This file is part of Mantid.
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport PeakOverlayViewFactory
-    {
-    public:
-      /// Create a peak view from the index of a peak in the peaks workspace
-      virtual boost::shared_ptr<PeakOverlayView> createView(PeaksPresenter* const presenter, Mantid::Geometry::PeakTransform_const_sptr transform) const = 0;
-      /// Destructor
-      virtual ~PeakOverlayViewFactory()
-      {
-      }
-      /// Get the plot x-axis label
-      virtual std::string getPlotXLabel() const = 0;
-      /// Get the plot y-axis label
-      virtual std::string getPlotYLabel() const = 0;
-      /// Same factory settings for a different peaks workspace
-      virtual void swapPeaksWorkspace(boost::shared_ptr<Mantid::API::IPeaksWorkspace>& peaksWS) = 0;
-    };
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    /// Factory Shared Pointer typedef.
-    typedef boost::shared_ptr<PeakOverlayViewFactory> PeakOverlayViewFactory_sptr;
-  }
-}
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport PeakOverlayViewFactory {
+public:
+  /// Create a peak view from the index of a peak in the peaks workspace
+  virtual boost::shared_ptr<PeakOverlayView>
+  createView(PeaksPresenter *const presenter,
+             Mantid::Geometry::PeakTransform_const_sptr transform) const = 0;
+  /// Destructor
+  virtual ~PeakOverlayViewFactory() {}
+  /// Get the plot x-axis label
+  virtual std::string getPlotXLabel() const = 0;
+  /// Get the plot y-axis label
+  virtual std::string getPlotYLabel() const = 0;
+  /// Same factory settings for a different peaks workspace
+  virtual void swapPeaksWorkspace(
+      boost::shared_ptr<Mantid::API::IPeaksWorkspace> &peaksWS) = 0;
+};
 
+/// Factory Shared Pointer typedef.
+typedef boost::shared_ptr<PeakOverlayViewFactory> PeakOverlayViewFactory_sptr;
+}
+}
 
 #endif /* MANTID_SLICEVIEWER_PEAKOVERLAY_VIEW_FACTORY_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactoryBase.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactoryBase.h
index 01d3daac6055087a4b33276aa2f273ae30c5b8b1..7ce6628424135b1f1b1ce4b712afcdcbdf1db2e9 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactoryBase.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakOverlayViewFactoryBase.h
@@ -7,51 +7,53 @@
 #include <qwt_plot.h>
 #include <qcolor.h>
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-
-    /** Base class for Concrete view factories. Provides common functionality. This is abstract.
-
-    @date 2012-08-24
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport PeakOverlayViewFactoryBase : public PeakOverlayViewFactory
-    {
-    protected:
-      QwtPlot * m_plot;
-      QWidget * m_parent;
-      PeakViewColor m_foregroundViewColor;
-      PeakViewColor m_backgroundViewColor;
-      const int m_plotXIndex;
-      const int m_plotYIndex;
-    public:
-      PeakOverlayViewFactoryBase(QwtPlot * plot, QWidget * parent, const int plotXIndex, const int plotYIndex, const size_t colourNumber=0);
-      ~PeakOverlayViewFactoryBase() override;
-      std::string getPlotXLabel() const override;
-      std::string getPlotYLabel() const override;
-    };
-  }
+namespace MantidQt {
+namespace SliceViewer {
+
+/** Base class for Concrete view factories. Provides common functionality. This
+is abstract.
+
+@date 2012-08-24
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport PeakOverlayViewFactoryBase : public PeakOverlayViewFactory {
+protected:
+  QwtPlot *m_plot;
+  QWidget *m_parent;
+  PeakViewColor m_foregroundViewColor;
+  PeakViewColor m_backgroundViewColor;
+  const int m_plotXIndex;
+  const int m_plotYIndex;
+
+public:
+  PeakOverlayViewFactoryBase(QwtPlot *plot, QWidget *parent,
+                             const int plotXIndex, const int plotYIndex,
+                             const size_t colourNumber = 0);
+  ~PeakOverlayViewFactoryBase() override;
+  std::string getPlotXLabel() const override;
+  std::string getPlotYLabel() const override;
+};
+}
 }
 
 #endif /*MANTID_SLICEVIEWER_PEAKOVERLAYVIEWFACTORYBASE_H_*/
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPalette.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPalette.h
index b5bf5fd29868fb8f43c6c98f79eddb5209d8b8d2..f6a038683fec5f61cf1dfad452482694a4aead34 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPalette.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPalette.h
@@ -9,50 +9,47 @@
 #include <map>
 #include <QColor>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
-template <typename C> class DLLExport PeakPalette
-{
+template <typename C> class DLLExport PeakPalette {
 public:
-    PeakPalette();
-    PeakPalette(const PeakPalette &other);
-    PeakPalette &operator=(const PeakPalette &other);
-    C foregroundIndexToColour(const int index) const;
-    C backgroundIndexToColour(const int index) const;
-    void setForegroundColour(const int index, const C);
-    void setBackgroundColour(const int index, const C);
-    int paletteSize() const;
-    bool operator==(const PeakPalette &other) const;
-    ~PeakPalette();
+  PeakPalette();
+  PeakPalette(const PeakPalette &other);
+  PeakPalette &operator=(const PeakPalette &other);
+  C foregroundIndexToColour(const int index) const;
+  C backgroundIndexToColour(const int index) const;
+  void setForegroundColour(const int index, const C);
+  void setBackgroundColour(const int index, const C);
+  int paletteSize() const;
+  bool operator==(const PeakPalette &other) const;
+  ~PeakPalette();
 
 private:
-    typedef std::map<int, C> ColourMapType;
-    ColourMapType m_backgroundMap;
-    ColourMapType m_foregroundMap;
-    typename ColourMapType::iterator safeFetchPair(ColourMapType &map,
-                                                   const int index) {
-      typename ColourMapType::iterator it = map.find(index);
-      if (it == map.end()) {
-          std::stringstream stream;
-          stream << "Index " << index << " is out of range";
-          throw std::out_of_range(stream.str());
-      }
-      return it;
+  typedef std::map<int, C> ColourMapType;
+  ColourMapType m_backgroundMap;
+  ColourMapType m_foregroundMap;
+  typename ColourMapType::iterator safeFetchPair(ColourMapType &map,
+                                                 const int index) {
+    typename ColourMapType::iterator it = map.find(index);
+    if (it == map.end()) {
+      std::stringstream stream;
+      stream << "Index " << index << " is out of range";
+      throw std::out_of_range(stream.str());
     }
-
-    typename ColourMapType::const_iterator
-    safeFetchPair(const ColourMapType &map, const int index) const {
-          auto it = map.find(index);
-          if (it == map.end()) {
-              std::stringstream stream;
-              stream << "Index " << index << " is out of range";
-              throw std::out_of_range(stream.str());
-          }
-          return it;
+    return it;
+  }
+
+  typename ColourMapType::const_iterator safeFetchPair(const ColourMapType &map,
+                                                       const int index) const {
+    auto it = map.find(index);
+    if (it == map.end()) {
+      std::stringstream stream;
+      stream << "Index " << index << " is out of range";
+      throw std::out_of_range(stream.str());
     }
+    return it;
+  }
 };
 
 template <typename C> PeakPalette<C>::PeakPalette() {}
@@ -60,85 +57,76 @@ template <typename C> PeakPalette<C>::PeakPalette() {}
 template <typename C>
 PeakPalette<C>::PeakPalette(const PeakPalette &other)
     : m_backgroundMap(other.m_backgroundMap),
-      m_foregroundMap(other.m_foregroundMap)
-{
-}
+      m_foregroundMap(other.m_foregroundMap) {}
 
 template <typename C>
-PeakPalette<C> &PeakPalette<C>::operator=(const PeakPalette<C> &other)
-{
-    m_foregroundMap.clear();
-    m_backgroundMap.clear();
-    if (this != &other) {
-        m_foregroundMap.insert(other.m_foregroundMap.begin(),
-                               other.m_foregroundMap.end());
-        m_backgroundMap.insert(other.m_backgroundMap.begin(),
-                               other.m_backgroundMap.end());
-    }
-    return *this;
+PeakPalette<C> &PeakPalette<C>::operator=(const PeakPalette<C> &other) {
+  m_foregroundMap.clear();
+  m_backgroundMap.clear();
+  if (this != &other) {
+    m_foregroundMap.insert(other.m_foregroundMap.begin(),
+                           other.m_foregroundMap.end());
+    m_backgroundMap.insert(other.m_backgroundMap.begin(),
+                           other.m_backgroundMap.end());
+  }
+  return *this;
 }
 
 template <typename C> PeakPalette<C>::~PeakPalette() {}
 
 template <typename C>
-C PeakPalette<C>::foregroundIndexToColour(const int index) const
-{
-    auto it = safeFetchPair(m_foregroundMap, index);
-    return it->second;
+C PeakPalette<C>::foregroundIndexToColour(const int index) const {
+  auto it = safeFetchPair(m_foregroundMap, index);
+  return it->second;
 }
 
 template <typename C>
-C PeakPalette<C>::backgroundIndexToColour(const int index) const
-{
-    auto it = safeFetchPair(m_backgroundMap, index);
-    return it->second;
+C PeakPalette<C>::backgroundIndexToColour(const int index) const {
+  auto it = safeFetchPair(m_backgroundMap, index);
+  return it->second;
 }
 
 template <typename C>
-void PeakPalette<C>::setForegroundColour(const int index, const C colour)
-{
-    auto it = safeFetchPair(m_foregroundMap, index);
-    // overwrite
-    it->second = colour;
+void PeakPalette<C>::setForegroundColour(const int index, const C colour) {
+  auto it = safeFetchPair(m_foregroundMap, index);
+  // overwrite
+  it->second = colour;
 }
 
 template <typename C>
-void PeakPalette<C>::setBackgroundColour(const int index, const C colour)
-{
-    auto it = safeFetchPair(m_backgroundMap, index);
-    // owverwirte
-    it->second = colour;
+void PeakPalette<C>::setBackgroundColour(const int index, const C colour) {
+  auto it = safeFetchPair(m_backgroundMap, index);
+  // owverwirte
+  it->second = colour;
 }
 
-template <typename C> int PeakPalette<C>::paletteSize() const
-{
-    if (m_foregroundMap.size() != m_backgroundMap.size()) {
-        throw std::runtime_error("The PeakPalette size is not consistent");
-    }
-    return static_cast<int>(m_foregroundMap.size());
+template <typename C> int PeakPalette<C>::paletteSize() const {
+  if (m_foregroundMap.size() != m_backgroundMap.size()) {
+    throw std::runtime_error("The PeakPalette size is not consistent");
+  }
+  return static_cast<int>(m_foregroundMap.size());
 }
 
 template <typename C>
-bool PeakPalette<C>::operator==(const PeakPalette &other) const
-{
-    bool areEqual = true;
-    if (other.paletteSize() != this->paletteSize()) {
+bool PeakPalette<C>::operator==(const PeakPalette &other) const {
+  bool areEqual = true;
+  if (other.paletteSize() != this->paletteSize()) {
+    areEqual = false;
+  } else {
+    for (int i = 0; i < this->paletteSize(); ++i) {
+      if (this->backgroundIndexToColour(i) !=
+          other.backgroundIndexToColour(i)) {
+        areEqual = false;
+        break;
+      }
+      if (this->foregroundIndexToColour(i) !=
+          other.foregroundIndexToColour(i)) {
         areEqual = false;
-    } else {
-        for (int i = 0; i < this->paletteSize(); ++i) {
-            if (this->backgroundIndexToColour(i)
-                != other.backgroundIndexToColour(i)) {
-                areEqual = false;
-                break;
-            }
-            if (this->foregroundIndexToColour(i)
-                != other.foregroundIndexToColour(i)) {
-                areEqual = false;
-                break;
-            }
-        }
+        break;
+      }
     }
-    return areEqual;
+  }
+  return areEqual;
 }
 
 // Forward declaration for template specialization
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPrimitives.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPrimitives.h
index 28ec6926419d9df13308ec9230bb0f7255fcbf9f..f4fda0d5f5e493e81f3a21ece36c67ef51421f4c 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPrimitives.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakPrimitives.h
@@ -3,81 +3,69 @@
 
 #include "MantidKernel/V3D.h"
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 struct DLLExport PeakPrimitives {
-    PeakPrimitives(Mantid::Kernel::V3D peakOrigin, double peakOpacityAtDistance,
-                   int peakLineWidth)
-        : peakOrigin(peakOrigin),
-          peakOpacityAtDistance(peakOpacityAtDistance),
-          peakLineWidth(peakLineWidth)
-    {
-    }
-    Mantid::Kernel::V3D peakOrigin;
-    double peakOpacityAtDistance;
-    int peakLineWidth;
+  PeakPrimitives(Mantid::Kernel::V3D peakOrigin, double peakOpacityAtDistance,
+                 int peakLineWidth)
+      : peakOrigin(peakOrigin), peakOpacityAtDistance(peakOpacityAtDistance),
+        peakLineWidth(peakLineWidth) {}
+  Mantid::Kernel::V3D peakOrigin;
+  double peakOpacityAtDistance;
+  int peakLineWidth;
 };
 
 struct DLLExport PeakPrimitivesCross : public PeakPrimitives {
-    PeakPrimitivesCross(Mantid::Kernel::V3D peakOrigin,
-                        double peakOpacityAtDistance, int peakLineWidth,
-                        int peakHalfCrossWidth, int peakHalfCrossHeight)
-        : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
-          peakHalfCrossWidth(peakHalfCrossWidth),
-          peakHalfCrossHeight(peakHalfCrossHeight)
-    {
-    }
-    int peakHalfCrossWidth;
-    int peakHalfCrossHeight;
+  PeakPrimitivesCross(Mantid::Kernel::V3D peakOrigin,
+                      double peakOpacityAtDistance, int peakLineWidth,
+                      int peakHalfCrossWidth, int peakHalfCrossHeight)
+      : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
+        peakHalfCrossWidth(peakHalfCrossWidth),
+        peakHalfCrossHeight(peakHalfCrossHeight) {}
+  int peakHalfCrossWidth;
+  int peakHalfCrossHeight;
 };
 
 struct DLLExport PeakPrimitiveCircle : public PeakPrimitives {
-        PeakPrimitiveCircle(Mantid::Kernel::V3D peakOrigin,
-                         double peakOpacityAtDistance, int peakLineWidth,
-                         double peakInnerRadiusX, double peakInnerRadiusY,
-                         double backgroundOuterRadiusX,
-                         double backgroundOuterRadiusY,
-                         double backgroundInnerRadiusX,
-                         double backgroundInnerRadiusY)
-        : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
-          peakInnerRadiusX(peakInnerRadiusX),
-          peakInnerRadiusY(peakInnerRadiusY),
-          backgroundOuterRadiusX(backgroundOuterRadiusX),
-          backgroundOuterRadiusY(backgroundOuterRadiusY),
-          backgroundInnerRadiusX(backgroundInnerRadiusX),
-          backgroundInnerRadiusY(backgroundInnerRadiusY)
-    {
-    }
-    double peakInnerRadiusX;
-    double peakInnerRadiusY;
-    double backgroundOuterRadiusX;
-    double backgroundOuterRadiusY;
-    double backgroundInnerRadiusX;
-    double backgroundInnerRadiusY;
+  PeakPrimitiveCircle(Mantid::Kernel::V3D peakOrigin,
+                      double peakOpacityAtDistance, int peakLineWidth,
+                      double peakInnerRadiusX, double peakInnerRadiusY,
+                      double backgroundOuterRadiusX,
+                      double backgroundOuterRadiusY,
+                      double backgroundInnerRadiusX,
+                      double backgroundInnerRadiusY)
+      : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
+        peakInnerRadiusX(peakInnerRadiusX), peakInnerRadiusY(peakInnerRadiusY),
+        backgroundOuterRadiusX(backgroundOuterRadiusX),
+        backgroundOuterRadiusY(backgroundOuterRadiusY),
+        backgroundInnerRadiusX(backgroundInnerRadiusX),
+        backgroundInnerRadiusY(backgroundInnerRadiusY) {}
+  double peakInnerRadiusX;
+  double peakInnerRadiusY;
+  double backgroundOuterRadiusX;
+  double backgroundOuterRadiusY;
+  double backgroundInnerRadiusX;
+  double backgroundInnerRadiusY;
 };
 
 struct DLLExport PeakPrimitivesEllipse : public PeakPrimitives {
   PeakPrimitivesEllipse(Mantid::Kernel::V3D peakOrigin,
-    double peakOpacityAtDistance, int peakLineWidth,
-    double peakInnerRadiusMajorAxis, double peakInnerRadiusMinorAxis,
-    double backgroundOuterRadiusMajorAxis,
-    double backgroundOuterRadiusMinorAxis,
-    double backgroundInnerRadiusMajorAxis,
-    double backgroundInnerRadiusMinorAxis,
-    double angle)
-    : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
-    peakInnerRadiusMajorAxis(peakInnerRadiusMajorAxis),
-    peakInnerRadiusMinorAxis(peakInnerRadiusMinorAxis),
-    backgroundOuterRadiusMajorAxis(backgroundOuterRadiusMajorAxis),
-    backgroundOuterRadiusMinorAxis(backgroundOuterRadiusMinorAxis),
-    backgroundInnerRadiusMajorAxis(backgroundInnerRadiusMajorAxis),
-    backgroundInnerRadiusMinorAxis(backgroundInnerRadiusMinorAxis),
-    angle(angle)
-  {
-  }
+                        double peakOpacityAtDistance, int peakLineWidth,
+                        double peakInnerRadiusMajorAxis,
+                        double peakInnerRadiusMinorAxis,
+                        double backgroundOuterRadiusMajorAxis,
+                        double backgroundOuterRadiusMinorAxis,
+                        double backgroundInnerRadiusMajorAxis,
+                        double backgroundInnerRadiusMinorAxis, double angle)
+      : PeakPrimitives(peakOrigin, peakOpacityAtDistance, peakLineWidth),
+        peakInnerRadiusMajorAxis(peakInnerRadiusMajorAxis),
+        peakInnerRadiusMinorAxis(peakInnerRadiusMinorAxis),
+        backgroundOuterRadiusMajorAxis(backgroundOuterRadiusMajorAxis),
+        backgroundOuterRadiusMinorAxis(backgroundOuterRadiusMinorAxis),
+        backgroundInnerRadiusMajorAxis(backgroundInnerRadiusMajorAxis),
+        backgroundInnerRadiusMinorAxis(backgroundInnerRadiusMinorAxis),
+        angle(angle) {}
   double peakInnerRadiusMajorAxis;
   double peakInnerRadiusMinorAxis;
   double backgroundOuterRadiusMajorAxis;
@@ -86,8 +74,6 @@ struct DLLExport PeakPrimitivesEllipse : public PeakPrimitives {
   double backgroundInnerRadiusMinorAxis;
   double angle;
 };
-
-
 }
 }
 
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentation.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentation.h
index b5366017ea8cf222f94248fb0335be91dc8246a1..122fc4fb3cb19228cb1b4046e519782ed2a4c57d 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentation.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentation.h
@@ -9,22 +9,19 @@
 
 class QPainter;
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 struct DLLExport PeakRepresentationViewInformation {
-    double windowHeight;
-    double windowWidth;
-    double viewHeight;
-    double viewWidth;
-    int xOriginWindow;
-    int yOriginWindow;
+  double windowHeight;
+  double windowWidth;
+  double viewHeight;
+  double viewWidth;
+  int xOriginWindow;
+  int yOriginWindow;
 };
 
 class PeakBoundingBox;
 
-
 /// Alisas for a boost optional double.
 typedef boost::optional<double> optional_double;
 
@@ -51,42 +48,39 @@ typedef boost::optional<double> optional_double;
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class DLLExport PeakRepresentation
-{
+class DLLExport PeakRepresentation {
 public:
-    virtual ~PeakRepresentation(){}
-
-    /// Draw template method
-    void draw(QPainter &painter, PeakViewColor &foregroundColor,
-              PeakViewColor &backgroundColor,
-              PeakRepresentationViewInformation viewInformation);
-    /// Setter for the slice point
-    virtual void setSlicePoint(const double &) = 0;
-    /// Transform the coordinates.
-    virtual void
-    movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) = 0;
-    /// Get the bounding box.
-    virtual PeakBoundingBox getBoundingBox() const = 0;
-    /// Set the size of the cross peak in the viewing plane
-    virtual void setOccupancyInView(const double fraction) = 0;
-    /// Set the size of the cross peak into the viewing plane
-    virtual void setOccupancyIntoView(const double fraction) = 0;
-    /// Get the effective peak radius.
-    virtual double getEffectiveRadius() const = 0;
-    /// Gets the origin
-    virtual const Mantid::Kernel::V3D &getOrigin() const = 0;
-    /// Show the background radius
-    virtual void showBackgroundRadius(const bool show) = 0;
-
+  virtual ~PeakRepresentation() {}
+
+  /// Draw template method
+  void draw(QPainter &painter, PeakViewColor &foregroundColor,
+            PeakViewColor &backgroundColor,
+            PeakRepresentationViewInformation viewInformation);
+  /// Setter for the slice point
+  virtual void setSlicePoint(const double &) = 0;
+  /// Transform the coordinates.
+  virtual void
+  movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) = 0;
+  /// Get the bounding box.
+  virtual PeakBoundingBox getBoundingBox() const = 0;
+  /// Set the size of the cross peak in the viewing plane
+  virtual void setOccupancyInView(const double fraction) = 0;
+  /// Set the size of the cross peak into the viewing plane
+  virtual void setOccupancyIntoView(const double fraction) = 0;
+  /// Get the effective peak radius.
+  virtual double getEffectiveRadius() const = 0;
+  /// Gets the origin
+  virtual const Mantid::Kernel::V3D &getOrigin() const = 0;
+  /// Show the background radius
+  virtual void showBackgroundRadius(const bool show) = 0;
 
 protected:
-    virtual std::shared_ptr<PeakPrimitives>
-    getDrawingInformation(PeakRepresentationViewInformation viewInformation)
-        = 0;
-    virtual void doDraw(QPainter &painter, PeakViewColor &foregroundColor,
-                        PeakViewColor &backgroundColor,
-                        std::shared_ptr<PeakPrimitives> drawingInformation,
-                        PeakRepresentationViewInformation viewInformation) = 0;
+  virtual std::shared_ptr<PeakPrimitives>
+  getDrawingInformation(PeakRepresentationViewInformation viewInformation) = 0;
+  virtual void doDraw(QPainter &painter, PeakViewColor &foregroundColor,
+                      PeakViewColor &backgroundColor,
+                      std::shared_ptr<PeakPrimitives> drawingInformation,
+                      PeakRepresentationViewInformation viewInformation) = 0;
 };
 
 typedef std::shared_ptr<PeakRepresentation> PeakRepresentation_sptr;
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationCross.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationCross.h
index 0b45caa392e00b1e319cf72b830a9c0f36dcd0b3..49aab3d595ce5c7c27da547c2f0702d9fcf8c532 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationCross.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationCross.h
@@ -3,21 +3,18 @@
 
 #include "MantidQtSliceViewer/PeakRepresentation.h"
 
-namespace
-{
+namespace {
 struct PeakDrawInformationPeak {
-    int peakHalfCrossWidth;
-    int peakHalfCrossHeight;
-    int peakLineWidth;
-    double peakOpacityAtDistance;
-    Mantid::Kernel::V3D peakOrigin;
+  int peakHalfCrossWidth;
+  int peakHalfCrossHeight;
+  int peakLineWidth;
+  double peakOpacityAtDistance;
+  Mantid::Kernel::V3D peakOrigin;
 };
 }
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 /** PeakRepresentationCross : Draws a cross-shaped peak for peaks without
   any shape
@@ -44,61 +41,60 @@ namespace SliceViewer
   <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class DLLExport PeakRepresentationCross : public PeakRepresentation
-{
+class DLLExport PeakRepresentationCross : public PeakRepresentation {
 public:
-    PeakRepresentationCross(const Mantid::Kernel::V3D &origin,
-                            const double &maxZ, const double &minZ);
-    /// Setter for the slice point
-    void setSlicePoint(const double &) override;
-    /// Transform the coordinates.
-    void
-    movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) override;
-    /// Get the bounding box.
-    PeakBoundingBox getBoundingBox() const override;
-    /// Set the size of the cross peak in the viewing plane
-    void setOccupancyInView(const double fraction) override;
-    /// Set the size of the cross peak into the viewing plane
-    void setOccupancyIntoView(const double fraction) override;
-    /// Get the effective peak radius.
-    double getEffectiveRadius() const override;
-    /// Get the origin
-    const Mantid::Kernel::V3D &getOrigin() const override;
-    /// Show the background radius
-    void showBackgroundRadius(const bool show) override;
+  PeakRepresentationCross(const Mantid::Kernel::V3D &origin, const double &maxZ,
+                          const double &minZ);
+  /// Setter for the slice point
+  void setSlicePoint(const double &) override;
+  /// Transform the coordinates.
+  void
+  movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) override;
+  /// Get the bounding box.
+  PeakBoundingBox getBoundingBox() const override;
+  /// Set the size of the cross peak in the viewing plane
+  void setOccupancyInView(const double fraction) override;
+  /// Set the size of the cross peak into the viewing plane
+  void setOccupancyIntoView(const double fraction) override;
+  /// Get the effective peak radius.
+  double getEffectiveRadius() const override;
+  /// Get the origin
+  const Mantid::Kernel::V3D &getOrigin() const override;
+  /// Show the background radius
+  void showBackgroundRadius(const bool show) override;
 
 protected:
-    std::shared_ptr<PeakPrimitives> getDrawingInformation(
-        PeakRepresentationViewInformation viewInformation) override;
-    void doDraw(QPainter &painter, PeakViewColor &foregroundColor,
-                PeakViewColor &backgroundColor,
-                std::shared_ptr<PeakPrimitives> drawingInformation,
-                PeakRepresentationViewInformation viewInformation) override;
+  std::shared_ptr<PeakPrimitives> getDrawingInformation(
+      PeakRepresentationViewInformation viewInformation) override;
+  void doDraw(QPainter &painter, PeakViewColor &foregroundColor,
+              PeakViewColor &backgroundColor,
+              std::shared_ptr<PeakPrimitives> drawingInformation,
+              PeakRepresentationViewInformation viewInformation) override;
 
-    // The members are placed here for testing
-    /// Fraction of the view considered for the effectiveRadius.
-    double m_intoViewFraction;
-    /// Cross size percentage in y a fraction of the current screen height.
-    double m_crossViewFraction;
+  // The members are placed here for testing
+  /// Fraction of the view considered for the effectiveRadius.
+  double m_intoViewFraction;
+  /// Cross size percentage in y a fraction of the current screen height.
+  double m_crossViewFraction;
 
 private:
-    /// Original origin x=h, y=k, z=l
-    const Mantid::Kernel::V3D m_originalOrigin;
-    /// Origin md-x, md-y, and md-z
-    Mantid::Kernel::V3D m_origin;
+  /// Original origin x=h, y=k, z=l
+  const Mantid::Kernel::V3D m_originalOrigin;
+  /// Origin md-x, md-y, and md-z
+  Mantid::Kernel::V3D m_origin;
 
-    /// effective peak radius
-    double m_effectiveRadius;
-    /// Max opacity
-    const double m_opacityMax;
-    /// Min opacity
-    const double m_opacityMin;
-    /// Cached opacity gradient
-    const double m_opacityGradient;
-    /// Cached opacity at the distance z from origin
-    double m_opacityAtDistance;
-    /// Current slice point.
-    double m_slicePoint;
+  /// effective peak radius
+  double m_effectiveRadius;
+  /// Max opacity
+  const double m_opacityMax;
+  /// Min opacity
+  const double m_opacityMin;
+  /// Cached opacity gradient
+  const double m_opacityGradient;
+  /// Cached opacity at the distance z from origin
+  double m_opacityAtDistance;
+  /// Current slice point.
+  double m_slicePoint;
 };
 }
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationEllipsoid.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationEllipsoid.h
index efbf9c4bf15db6c5f77766b99d61871f4a070f30..3738048fb50569e3f951214e5d75634d02e6c0db 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationEllipsoid.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakRepresentationEllipsoid.h
@@ -4,10 +4,8 @@
 #include "MantidQtSliceViewer/PeakRepresentation.h"
 #include "MantidQtSliceViewer/EllipsoidPlaneSliceCalculator.h"
 #include "MantidKernel/V2D.h"
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 /** PeakRepresentationEllipsoid : Draws an ellipse for elliptical peaks.
 
@@ -33,15 +31,15 @@ namespace SliceViewer
   <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class DLLExport PeakRepresentationEllipsoid : public PeakRepresentation
-{
+class DLLExport PeakRepresentationEllipsoid : public PeakRepresentation {
 public:
-  PeakRepresentationEllipsoid(const Mantid::Kernel::V3D &origin,
-                           const std::vector<double> peakRadii,
-                           const std::vector<double> backgroundInnerRadii,
-                           const std::vector<double> backgroundOuterRadii,
-                           const std::vector<Mantid::Kernel::V3D> directions,
-                           std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator> calculator);
+  PeakRepresentationEllipsoid(
+      const Mantid::Kernel::V3D &origin, const std::vector<double> peakRadii,
+      const std::vector<double> backgroundInnerRadii,
+      const std::vector<double> backgroundOuterRadii,
+      const std::vector<Mantid::Kernel::V3D> directions,
+      std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator>
+          calculator);
 
   /// Setter for the slice point
   void setSlicePoint(const double &) override;
@@ -82,7 +80,7 @@ private:
 
   // -----------Working copies of collections
   /// Origin md-x, md-y, and md-z
-  Mantid::Kernel::V3D  m_origin;
+  Mantid::Kernel::V3D m_origin;
   /// Direction in md-x, md-y and md-z
   std::vector<Mantid::Kernel::V3D> m_directions;
   /// Actual peak radii
@@ -92,7 +90,6 @@ private:
   /// Peak background outer radius
   const std::vector<double> m_backgroundOuterRadii;
 
-
   /// Max opacity
   const double m_opacityMax;
   /// Min opacity
@@ -120,7 +117,8 @@ private:
   bool m_showBackgroundRadii;
 
   /// A calculator to extract the ellipse parameters
-  std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator> m_calculator;
+  std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator>
+      m_calculator;
 };
 }
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakView.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakView.h
index e6238da76c34d887a05cf299f8ea26f76503d1cf..c513c6e937bca55200538183084b94fa788b6e1b 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakView.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakView.h
@@ -4,10 +4,8 @@
 #include "MantidQtSliceViewer/PeakOverlayInteractive.h"
 #include "PeakRepresentation.h"
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 /** PeakView : Holds a collection of peaks of any type and coordinates
                them being drawn.
@@ -34,105 +32,104 @@ namespace SliceViewer
   <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class PeakView : public PeakOverlayInteractive
-{
+class PeakView : public PeakOverlayInteractive {
 public:
-    PeakView(PeaksPresenter *const presenter, QwtPlot *plot, QWidget *parent,
-             const VecPeakRepresentation &vecPeakRepresentation,
-             const int plotXIndex, const int plotYIndex,
-             PeakViewColor foregroundColor, PeakViewColor backgroundColor,
-             double largestEffectiveRadius);
+  PeakView(PeaksPresenter *const presenter, QwtPlot *plot, QWidget *parent,
+           const VecPeakRepresentation &vecPeakRepresentation,
+           const int plotXIndex, const int plotYIndex,
+           PeakViewColor foregroundColor, PeakViewColor backgroundColor,
+           double largestEffectiveRadius);
 
-    virtual ~PeakView();
+  virtual ~PeakView();
 
-    /// Set the slice point at position.
-    void setSlicePoint(const double &point,
-                       const std::vector<bool> &viewablePeaks) override;
+  /// Set the slice point at position.
+  void setSlicePoint(const double &point,
+                     const std::vector<bool> &viewablePeaks) override;
 
-    /// Hide the view.
-    void hideView() override;
+  /// Hide the view.
+  void hideView() override;
 
-    /// Show the view.
-    void showView() override;
+  /// Show the view.
+  void showView() override;
 
-    /// Update the view.
-    void updateView() override;
+  /// Update the view.
+  void updateView() override;
 
-    /// Move the position of the peak, by using a different configuration of the
-    /// existing origin indexes.
-    void
-    movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) override;
+  /// Move the position of the peak, by using a different configuration of the
+  /// existing origin indexes.
+  void
+  movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform) override;
 
-    /// Show the background radius
-    void showBackgroundRadius(const bool show) override;
+  /// Show the background radius
+  void showBackgroundRadius(const bool show) override;
 
-    /// Get a bounding box for this peak.
-    PeakBoundingBox getBoundingBox(const int peakIndex) const override;
+  /// Get a bounding box for this peak.
+  PeakBoundingBox getBoundingBox(const int peakIndex) const override;
 
-    /// Changes the size of the overlay to be the requested fraction of the
-    /// current view width.
-    void changeOccupancyInView(const double fraction) override;
+  /// Changes the size of the overlay to be the requested fraction of the
+  /// current view width.
+  void changeOccupancyInView(const double fraction) override;
 
-    /// Changes the size of the overlay to be the requested fraction of the view
-    /// depth.
-    void changeOccupancyIntoView(const double fraction) override;
+  /// Changes the size of the overlay to be the requested fraction of the view
+  /// depth.
+  void changeOccupancyIntoView(const double fraction) override;
 
-    /// Get the peak size (width/2 as a fraction of total width)  on projection
-    double getOccupancyInView() const override;
+  /// Get the peak size (width/2 as a fraction of total width)  on projection
+  double getOccupancyInView() const override;
 
-    /// Get the peaks size into the projection (effective radius as a fraction
-    /// of z range)
-    double getOccupancyIntoView() const override;
+  /// Get the peaks size into the projection (effective radius as a fraction
+  /// of z range)
+  double getOccupancyIntoView() const override;
 
-    /// Getter indicating that the view is position only
-    bool positionOnly() const override;
+  /// Getter indicating that the view is position only
+  bool positionOnly() const override;
 
-    /// Get the radius of the peak objects.
-    double getRadius() const override;
+  /// Get the radius of the peak objects.
+  double getRadius() const override;
 
-    /// Determine if the background radius is shown.
-    bool isBackgroundShown() const override;
+  /// Determine if the background radius is shown.
+  bool isBackgroundShown() const override;
 
-    /// Take settings from another view
-    void takeSettingsFrom(const PeakOverlayView *const) override;
+  /// Take settings from another view
+  void takeSettingsFrom(const PeakOverlayView *const) override;
 
-    /// Change foreground colour -- overload for PeakViewColor
-    void changeForegroundColour(const PeakViewColor peakViewColor) override;
+  /// Change foreground colour -- overload for PeakViewColor
+  void changeForegroundColour(const PeakViewColor peakViewColor) override;
 
-    /// Change background colour -- overload for PeakViewColor
-    void changeBackgroundColour(const PeakViewColor peakViewColor) override;
+  /// Change background colour -- overload for PeakViewColor
+  void changeBackgroundColour(const PeakViewColor peakViewColor) override;
 
-    /// Get the current background colour
-    PeakViewColor getBackgroundPeakViewColor() const override;
+  /// Get the current background colour
+  PeakViewColor getBackgroundPeakViewColor() const override;
 
-    /// Get the current foreground colour
-    PeakViewColor getForegroundPeakViewColor() const override;
+  /// Get the current foreground colour
+  PeakViewColor getForegroundPeakViewColor() const override;
 
 private:
-    /// Draw the peak representations. Pure virtual on base class.
-    void doPaintPeaks(QPaintEvent *) override;
+  /// Draw the peak representations. Pure virtual on base class.
+  void doPaintPeaks(QPaintEvent *) override;
 
-    /// The actual peak objects
-    VecPeakRepresentation m_peaks;
+  /// The actual peak objects
+  VecPeakRepresentation m_peaks;
 
-    /// Peaks in the workspace that are viewable in the present view.
-    std::vector<bool> m_viewablePeaks;
+  /// Peaks in the workspace that are viewable in the present view.
+  std::vector<bool> m_viewablePeaks;
 
-    /// Cached occupancy into the view
-    double m_cachedOccupancyIntoView;
+  /// Cached occupancy into the view
+  double m_cachedOccupancyIntoView;
 
-    /// Cached occupancy onto view
-    double m_cachedOccupancyInView;
+  /// Cached occupancy onto view
+  double m_cachedOccupancyInView;
 
-    /// Show the background radius.
-    bool m_showBackground;
+  /// Show the background radius.
+  bool m_showBackground;
 
-    /// Foreground color
-    PeakViewColor m_foregroundColor;
-    PeakViewColor m_backgroundColor;
+  /// Foreground color
+  PeakViewColor m_foregroundColor;
+  PeakViewColor m_backgroundColor;
 
-    /// Largeste effective radius of all sub-representations
-    double m_largestEffectiveRadius;
+  /// Largeste effective radius of all sub-representations
+  double m_largestEffectiveRadius;
 };
 }
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewColor.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewColor.h
index d6d8ac53e538e3822141dd8b287a01ec0d77c955..8b1374e5fae858c4af55810d5e7a8647444adac8 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewColor.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewColor.h
@@ -17,27 +17,24 @@
  * New peak types will need to have a color entry registered here.
  */
 struct PeakViewColor {
-    PeakViewColor(QColor colorCross = QColor(), QColor colorSphere = QColor(),
-                  QColor colorEllipsoid = QColor())
-        : colorCross(colorCross), colorSphere(colorSphere),
-          colorEllipsoid(colorEllipsoid)
-    {
-    }
+  PeakViewColor(QColor colorCross = QColor(), QColor colorSphere = QColor(),
+                QColor colorEllipsoid = QColor())
+      : colorCross(colorCross), colorSphere(colorSphere),
+        colorEllipsoid(colorEllipsoid) {}
 
-    bool operator==(const PeakViewColor &other)
-    {
-        auto sameColorCross = this->colorCross == other.colorCross;
-        auto sameColorSphere = this->colorSphere == other.colorSphere;
-        auto sameColorEllipsoid = this->colorEllipsoid == other.colorEllipsoid;
+  bool operator==(const PeakViewColor &other) {
+    auto sameColorCross = this->colorCross == other.colorCross;
+    auto sameColorSphere = this->colorSphere == other.colorSphere;
+    auto sameColorEllipsoid = this->colorEllipsoid == other.colorEllipsoid;
 
-        return sameColorCross && sameColorSphere && sameColorEllipsoid;
-    }
+    return sameColorCross && sameColorSphere && sameColorEllipsoid;
+  }
 
-    bool operator!=(const PeakViewColor &other) { return !(*this == other); }
+  bool operator!=(const PeakViewColor &other) { return !(*this == other); }
 
-    QColor colorCross;
-    QColor colorSphere;
-    QColor colorEllipsoid;
+  QColor colorCross;
+  QColor colorSphere;
+  QColor colorEllipsoid;
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewFactory.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewFactory.h
index ab42470cbec551b7924ac6f6bfc5cac9fffd7288..615fcb05f9148962499db740f0ec1d95edbc8f4f 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewFactory.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeakViewFactory.h
@@ -10,10 +10,8 @@
 
 #include <QColor>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 /** PeakViewFactory : Creates an appropriate PeakView object
 
@@ -39,58 +37,59 @@ namespace SliceViewer
   <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class PeakViewFactory : public PeakOverlayViewFactoryBase
-{
+class PeakViewFactory : public PeakOverlayViewFactoryBase {
 public:
-    PeakViewFactory(Mantid::API::IMDWorkspace_sptr mdWS,
-                    Mantid::API::IPeaksWorkspace_sptr peaksWS, QwtPlot *plot,
-                    QWidget *parent, const int plotXIndex, const int plotYIndex,
-                    const size_t colorNumber = 0);
-    virtual ~PeakViewFactory();
-    boost::shared_ptr<PeakOverlayView> createView(
-        PeaksPresenter *const presenter,
-        Mantid::Geometry::PeakTransform_const_sptr transform) const override;
-    void swapPeaksWorkspace(
-        boost::shared_ptr<Mantid::API::IPeaksWorkspace> &peaksWS) override;
+  PeakViewFactory(Mantid::API::IMDWorkspace_sptr mdWS,
+                  Mantid::API::IPeaksWorkspace_sptr peaksWS, QwtPlot *plot,
+                  QWidget *parent, const int plotXIndex, const int plotYIndex,
+                  const size_t colorNumber = 0);
+  virtual ~PeakViewFactory();
+  boost::shared_ptr<PeakOverlayView> createView(
+      PeaksPresenter *const presenter,
+      Mantid::Geometry::PeakTransform_const_sptr transform) const override;
+  void swapPeaksWorkspace(
+      boost::shared_ptr<Mantid::API::IPeaksWorkspace> &peaksWS) override;
 
 private:
-    // Selector for the correct representation of a single peak
-    PeakRepresentation_sptr createSinglePeakRepresentation(
-        const Mantid::Geometry::IPeak &peak, Mantid::Kernel::V3D position,
-        Mantid::Geometry::PeakTransform_const_sptr transform) const;
+  // Selector for the correct representation of a single peak
+  PeakRepresentation_sptr createSinglePeakRepresentation(
+      const Mantid::Geometry::IPeak &peak, Mantid::Kernel::V3D position,
+      Mantid::Geometry::PeakTransform_const_sptr transform) const;
 
-    // Creates a cross-like representation
-    PeakRepresentation_sptr createPeakRepresentationCross(
-        Mantid::Kernel::V3D position,
-        Mantid::Geometry::PeakTransform_const_sptr transform) const;
+  // Creates a cross-like representation
+  PeakRepresentation_sptr createPeakRepresentationCross(
+      Mantid::Kernel::V3D position,
+      Mantid::Geometry::PeakTransform_const_sptr transform) const;
 
-    // Creates a spherical representation
-    PeakRepresentation_sptr
-    createPeakRepresentationSphere(Mantid::Kernel::V3D position,
-                                   const Mantid::Geometry::IPeak &peak) const;
+  // Creates a spherical representation
+  PeakRepresentation_sptr
+  createPeakRepresentationSphere(Mantid::Kernel::V3D position,
+                                 const Mantid::Geometry::IPeak &peak) const;
 
-    // Creates a spherical representation
-    PeakRepresentation_sptr createPeakRepresentationEllipsoid(
-        Mantid::Kernel::V3D position,
-        const Mantid::Geometry::IPeak &peak) const;
+  // Creates a spherical representation
+  PeakRepresentation_sptr
+  createPeakRepresentationEllipsoid(Mantid::Kernel::V3D position,
+                                    const Mantid::Geometry::IPeak &peak) const;
 
-    // Set color palette
-    void setForegroundAndBackgroundColors(const size_t colourNumber);
+  // Set color palette
+  void setForegroundAndBackgroundColors(const size_t colourNumber);
 
-    // The actual workspace
-    Mantid::API::IMDWorkspace_sptr m_mdWS;
+  // The actual workspace
+  Mantid::API::IMDWorkspace_sptr m_mdWS;
 
-    /// Peaks workspace.
-    Mantid::API::IPeaksWorkspace_sptr m_peaksWS;
+  /// Peaks workspace.
+  Mantid::API::IPeaksWorkspace_sptr m_peaksWS;
 
-    /// Color foreground
-    PeakViewColor m_foregroundColor;
+  /// Color foreground
+  PeakViewColor m_foregroundColor;
 
-    /// Color background
-    PeakViewColor m_backgroundColor;
+  /// Color background
+  PeakViewColor m_backgroundColor;
 
-    /// Ellipsoid calculator -- as we don't paint in parallel this is safe to share between the peaks
-    std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator> m_calculator;
+  /// Ellipsoid calculator -- as we don't paint in parallel this is safe to
+  /// share between the peaks
+  std::shared_ptr<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator>
+      m_calculator;
 };
 }
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksPresenter.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksPresenter.h
index e561bf5b343afe941ad2a231d538bd9a68273a75..a47aa36d83ba75c6cec38f8b8865bfe6434c9bb1 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksPresenter.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksPresenter.h
@@ -10,30 +10,24 @@
 #include <set>
 #include <QObject>
 
-namespace Mantid
-{
-namespace Kernel
-{
+namespace Mantid {
+namespace Kernel {
 // Forward dec
 class V3D;
 }
 
-namespace Geometry
-{
+namespace Geometry {
 // Forward dec.
 class PeakTransform;
 }
-namespace API
-{
+namespace API {
 // Forward dec.
 class IPeaksWorkspace;
 }
 }
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 // Forward dec.
 class PeakOverlayViewFactory;
 
@@ -53,41 +47,39 @@ of the owning object,
 whithout having to perform fragile null checks.
 
 ----------------------------------------------------------*/
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER PeaksPresenter : public QObject
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER PeaksPresenter : public QObject {
 public:
-    virtual void update() = 0;
-    virtual void updateWithSlicePoint(const PeakBoundingBox &) = 0;
-    virtual bool changeShownDim() = 0;
-    virtual bool isLabelOfFreeAxis(const std::string &label) const = 0;
-    virtual SetPeaksWorkspaces presentedWorkspaces() const = 0;
-    virtual void setForegroundColor(const PeakViewColor) = 0;
-    virtual void setBackgroundColor(const PeakViewColor) = 0;
-    virtual std::string getTransformName() const = 0;
-    virtual void showBackgroundRadius(const bool shown) = 0;
-    virtual void setShown(const bool shown) = 0;
-    virtual PeakBoundingBox getBoundingBox(const int peakIndex) const = 0;
-    virtual void sortPeaksWorkspace(const std::string &byColumnName,
-                                    const bool ascending) = 0;
-    virtual void setPeakSizeOnProjection(const double fraction) = 0;
-    virtual void setPeakSizeIntoProjection(const double fraction) = 0;
-    virtual double getPeakSizeOnProjection() const = 0;
-    virtual double getPeakSizeIntoProjection() const = 0;
-    virtual bool getShowBackground() const = 0;
-    virtual void registerOwningPresenter(UpdateableOnDemand *owner) = 0;
-    virtual PeakViewColor getBackgroundPeakViewColor() const = 0;
-    virtual PeakViewColor getForegroundPeakViewColor() const = 0;
-    virtual void zoomToPeak(const int peakIndex) = 0;
-    virtual bool isHidden() const = 0;
-    virtual bool contentsDifferent(PeaksPresenter const *other) const = 0;
-    virtual void
-    reInitialize(boost::shared_ptr<Mantid::API::IPeaksWorkspace> peaksWS) = 0;
-    virtual void peakEditMode(EditMode mode) = 0;
-    virtual bool deletePeaksIn(PeakBoundingBox plotCoordsBox) = 0;
-    virtual bool addPeakAt(double plotCoordsPointX, double plotCoordsPointY)
-        = 0;
-    virtual bool hasPeakAddMode() const = 0;
-    ~PeaksPresenter() override{};
+  virtual void update() = 0;
+  virtual void updateWithSlicePoint(const PeakBoundingBox &) = 0;
+  virtual bool changeShownDim() = 0;
+  virtual bool isLabelOfFreeAxis(const std::string &label) const = 0;
+  virtual SetPeaksWorkspaces presentedWorkspaces() const = 0;
+  virtual void setForegroundColor(const PeakViewColor) = 0;
+  virtual void setBackgroundColor(const PeakViewColor) = 0;
+  virtual std::string getTransformName() const = 0;
+  virtual void showBackgroundRadius(const bool shown) = 0;
+  virtual void setShown(const bool shown) = 0;
+  virtual PeakBoundingBox getBoundingBox(const int peakIndex) const = 0;
+  virtual void sortPeaksWorkspace(const std::string &byColumnName,
+                                  const bool ascending) = 0;
+  virtual void setPeakSizeOnProjection(const double fraction) = 0;
+  virtual void setPeakSizeIntoProjection(const double fraction) = 0;
+  virtual double getPeakSizeOnProjection() const = 0;
+  virtual double getPeakSizeIntoProjection() const = 0;
+  virtual bool getShowBackground() const = 0;
+  virtual void registerOwningPresenter(UpdateableOnDemand *owner) = 0;
+  virtual PeakViewColor getBackgroundPeakViewColor() const = 0;
+  virtual PeakViewColor getForegroundPeakViewColor() const = 0;
+  virtual void zoomToPeak(const int peakIndex) = 0;
+  virtual bool isHidden() const = 0;
+  virtual bool contentsDifferent(PeaksPresenter const *other) const = 0;
+  virtual void
+  reInitialize(boost::shared_ptr<Mantid::API::IPeaksWorkspace> peaksWS) = 0;
+  virtual void peakEditMode(EditMode mode) = 0;
+  virtual bool deletePeaksIn(PeakBoundingBox plotCoordsBox) = 0;
+  virtual bool addPeakAt(double plotCoordsPointX, double plotCoordsPointY) = 0;
+  virtual bool hasPeakAddMode() const = 0;
+  ~PeaksPresenter() override{};
 };
 
 typedef boost::shared_ptr<PeaksPresenter> PeaksPresenter_sptr;
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksTableColumnsDialog.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksTableColumnsDialog.h
index 4394f514a7b5819029136686388fe702e6c80d93..736713dc8a5e1f3df32aa485e286a099e38ddda7 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksTableColumnsDialog.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksTableColumnsDialog.h
@@ -8,22 +8,19 @@ namespace Ui {
 class PeaksTableColumnsDialog;
 }
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
-class PeaksTableColumnsDialog : public QDialog
-{
+class PeaksTableColumnsDialog : public QDialog {
   Q_OBJECT
-  
+
 public:
   explicit PeaksTableColumnsDialog(QWidget *parent = 0);
   ~PeaksTableColumnsDialog() override;
 
-  void setVisibleColumns(std::set<QString> & cols);
+  void setVisibleColumns(std::set<QString> &cols);
   std::set<QString> getVisibleColumns();
-  
+
 private:
   Ui::PeaksTableColumnsDialog *ui;
   std::set<QString> m_origVisible;
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewer.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewer.h
index 2dc88a4b2cb6c6fa3c4b9cfb420770891986132d..9a2fecaee3796999b47e8132171c06bcf91b7abb 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewer.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewer.h
@@ -42,12 +42,16 @@ public:
   void hide();
   ~PeaksViewer() override;
   bool hasThingsToShow() const;
-  void clearPeaksModeRequest(PeaksWorkspaceWidget const * const originWidget, const bool on);
-  void addPeaksModeRequest(PeaksWorkspaceWidget const * const originWidget, const bool on);
+  void clearPeaksModeRequest(PeaksWorkspaceWidget const *const originWidget,
+                             const bool on);
+  void addPeaksModeRequest(PeaksWorkspaceWidget const *const originWidget,
+                           const bool on);
 
 public slots:
-  void onPeakColorChanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor);
-  void onBackgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor);
+  void onPeakColorChanged(Mantid::API::IPeaksWorkspace_const_sptr,
+                          PeakViewColor);
+  void onBackgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr,
+                                PeakViewColor);
   void onBackgroundRadiusShown(Mantid::API::IPeaksWorkspace_const_sptr, bool);
   void onRemoveWorkspace(Mantid::API::IPeaksWorkspace_const_sptr);
   void onHideInPlot(Mantid::API::IPeaksWorkspace_const_sptr peaksWS, bool);
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewerOverlayDialog.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewerOverlayDialog.h
index 3be7467c7af20514a6cc2d306d1dde3a62ccca88..d1d84844e38693a6bf679a86d6d8e3364b332c55 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewerOverlayDialog.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksViewerOverlayDialog.h
@@ -5,42 +5,39 @@
 #include "MantidQtSliceViewer/PeaksPresenter.h"
 
 class QAbstractButton;
-namespace Ui
-{
-  class PeaksViewerOverlayDialog;
+namespace Ui {
+class PeaksViewerOverlayDialog;
 }
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    class PeaksViewerOverlayDialog: public QDialog
-    {
-      Q_OBJECT
-
-    public:
-      explicit PeaksViewerOverlayDialog(PeaksPresenter_sptr peaksPresenter, QWidget *parent = 0);
-      ~PeaksViewerOverlayDialog() override;
-
-      void closeEvent(QCloseEvent *) override;
-      void reject() override;
-
-    private slots:
-
-      void onSliderIntoProjectionMoved(int value);
-      void onSliderOnProjectionMoved(int value);
-      void onReset();
-      void onCompleteClicked(QAbstractButton* button);
-      void onHelp();
-
-    private:
-      Ui::PeaksViewerOverlayDialog *ui;
-      PeaksPresenter_sptr m_peaksPresenter;
-
-      double m_originalOnProjectionFraction;
-      double m_originalIntoProjectionFraction;
-    };
-  }
+namespace MantidQt {
+namespace SliceViewer {
+class PeaksViewerOverlayDialog : public QDialog {
+  Q_OBJECT
+
+public:
+  explicit PeaksViewerOverlayDialog(PeaksPresenter_sptr peaksPresenter,
+                                    QWidget *parent = 0);
+  ~PeaksViewerOverlayDialog() override;
+
+  void closeEvent(QCloseEvent *) override;
+  void reject() override;
+
+private slots:
+
+  void onSliderIntoProjectionMoved(int value);
+  void onSliderOnProjectionMoved(int value);
+  void onReset();
+  void onCompleteClicked(QAbstractButton *button);
+  void onHelp();
+
+private:
+  Ui::PeaksViewerOverlayDialog *ui;
+  PeaksPresenter_sptr m_peaksPresenter;
+
+  double m_originalOnProjectionFraction;
+  double m_originalIntoProjectionFraction;
+};
+}
 }
 
 #endif // MANTIDSLICEVIEWER_PEAKSVIEWEROVERLAYDIALOG_H
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksWorkspaceWidget.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksWorkspaceWidget.h
index 9763062be3a8516d6b7380084e7c9f3ccf504f2a..cfc22610547cbd60ac564fc202649254d4520b52 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksWorkspaceWidget.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/PeaksWorkspaceWidget.h
@@ -19,9 +19,7 @@ public:
                        const std::string &coordinateSystem,
                        PeakViewColor defaultForegroundPeakViewColor,
                        PeakViewColor defaultBackgroundPeakViewColor,
-                       const bool canAddPeaks,
-                       PeaksViewer *parent);
-
+                       const bool canAddPeaks, PeaksViewer *parent);
 
   std::set<QString> getShownColumns();
   void setShownColumns(std::set<QString> &cols);
@@ -41,7 +39,8 @@ signals:
   void peakColourChanged(Mantid::API::IPeaksWorkspace_const_sptr, QColor);
   void peakColorchanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor);
   void backgroundColourChanged(Mantid::API::IPeaksWorkspace_const_sptr, QColor);
-  void backgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor);
+  void backgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr,
+                              PeakViewColor);
   void backgroundRadiusShown(Mantid::API::IPeaksWorkspace_const_sptr, bool);
   void removeWorkspace(Mantid::API::IPeaksWorkspace_const_sptr);
   void hideInPlot(Mantid::API::IPeaksWorkspace_const_sptr, bool);
@@ -73,7 +72,7 @@ private:
   /// Workspace name.
   QString m_nameText;
   /// Parent widget
-  PeaksViewer* const m_parent;
+  PeaksViewer *const m_parent;
 
 private slots:
   void onForegroundColorCrossClicked();
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ProxyCompositePeaksPresenter.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ProxyCompositePeaksPresenter.h
index 9a7bec9b8c107a2dd4b19b63ab16e6bb708abed6..bc73e4ed8a69d8ef0220105f8867f56fc79bc7bb 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ProxyCompositePeaksPresenter.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ProxyCompositePeaksPresenter.h
@@ -28,11 +28,11 @@ public:
 
   void
   setForegroundColor(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
-                      PeakViewColor);
+                     PeakViewColor);
   /// Change the background representation for the peaks of this workspace
   void
   setBackgroundColor(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
-                      PeakViewColor);
+                     PeakViewColor);
   /// Get the foreground colour corresponding to the workspace
   PeakViewColor getForegroundPeakViewColor(
       boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws) const;
@@ -81,9 +81,11 @@ public:
   /// Get optional zoomed peak index.
   int getZoomedPeakIndex() const;
   /// Set the edit mode.
-  void editCommand(EditMode editMode, boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
+  void editCommand(EditMode editMode,
+                   boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
   /// Can we add HKL peaks to this workspace.
-  bool hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
+  bool
+  hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target);
 
 private:
   /// Wrapped composite to delegate to.
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/QPeaksTableModel.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/QPeaksTableModel.h
index b41db2e5f7b3f965d75b9f68966e614a77fcdd68..67fc4ba462694a5745e0791b5c40a7aab270384c 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/QPeaksTableModel.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/QPeaksTableModel.h
@@ -8,175 +8,176 @@
 #include <vector>
 
 // Forward declarations
-namespace Mantid
-{
-  namespace Geometry {
-    class IPeak;
-  }
-
-  namespace API {
-    class IPeaksWorkspace; 
-  }
+namespace Mantid {
+namespace Geometry {
+class IPeak;
 }
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /** @class QtWorkspaceMementoModel
+namespace API {
+class IPeaksWorkspace;
+}
+}
 
-    QAbstractTableModel for serving up PeaksWorkspaces.
+namespace MantidQt {
+namespace SliceViewer {
+/** @class QtWorkspaceMementoModel
 
-    @author Owen Arnold
-    @date 07/01/2013
+QAbstractTableModel for serving up PeaksWorkspaces.
 
-    Copyright &copy; 2011-12 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+@author Owen Arnold
+@date 07/01/2013
 
-    This file is part of Mantid.
+Copyright &copy; 2011-12 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-    class EXPORT_OPT_MANTIDQT_SLICEVIEWER QPeaksTableModel : public QAbstractTableModel
-    {
-      Q_OBJECT
-    public:
-      QPeaksTableModel(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> peaksWS);
-      void update();
-      int rowCount(const QModelIndex &parent) const override;
-      int columnCount(const QModelIndex &parent) const override;
-      QVariant data(const QModelIndex &index, int role) const override;
-      QVariant headerData(int section, Qt::Orientation orientation,
-                          int role) const override;
-      Qt::ItemFlags flags(const QModelIndex &index) const override;
-      void sort(int column, Qt::SortOrder) override;
-      int numCharacters(const int column) const;
-      std::vector<int> defaultHideCols();
-      ~QPeaksTableModel() override;
-      void setPeaksWorkspace(boost::shared_ptr<const Mantid::API::IPeaksWorkspace> peaksWS);
-     signals:
-      void peaksSorted(const std::string&, const bool);
-    private:
-
-      typedef QString ColumnNameType;
-      typedef QString ColumnValueType;
-      typedef std::map<ColumnNameType, bool> ColumnNameSortableMap;
-      typedef std::map<int, ColumnNameType> ColumnIndexNameMap;
-
-    public:
-      /// Label for run number column
-      static const QString RUNNUMBER;
-      /// Label for detector id column
-      static const QString DETID;
-      /// Label for h column
-      static const QString H;
-      /// Label for k column
-      static const QString K;
-      /// Label for l column
-      static const QString L;
-      /// Label for wavelength column
-      static const QString WAVELENGTH;
-      /// Label for change in energy column
-      static const QString ENERGY;
-      /// Label for initial energy column
-      static const QString INITIAL_ENERGY;
-      /// Label for final energy column
-      static const QString FINAL_ENERGY;
-      /// Label for time-of-flight column
-      static const QString TOF;
-      /// Label for d-spacing column
-      static const QString DSPACING;
-      /// Label for integrated intensity column
-      static const QString INT;
-      /// Label for uncertainty in integrated intensity column
-      static const QString SIGMINT;
-      /// Label for ratio of intensity/uncertainty
-      static const QString INT_SIGINT;
-      /// Label for bin count column
-      static const QString BINCOUNT;
-      /// Label for bank name column
-      static const QString BANKNAME;
-      /// Label for detector row column
-      static const QString ROW;
-      /// Label for detector column column
-      static const QString COL;
-      /// Label for Q-vector in the lab frame column
-      static const QString QLAB;
-      /// Label for Q-vector in the sample column
-      static const QString QSAMPLE;
-
-    private:
-      /// Index for run number column
-      static const int COL_RUNNUMBER;
-      /// Index for detector id column
-      static const int COL_DETID;
-      /// Index for h column
-      static const int COL_H;
-      /// Index for k column
-      static const int COL_K;
-      /// Index for l column
-      static const int COL_L;
-      /// Index for wavelength column
-      static const int COL_WAVELENGTH;
-      /// Index for change in energy column
-      static const int COL_ENERGY;
-      /// Index for initial energy column
-      static const int COL_INITIAL_ENERGY;
-      /// Index for final energy column
-      static const int COL_FINAL_ENERGY;
-      /// Index for time-of-flight column
-      static const int COL_TOF;
-      /// Index for d-spacing column
-      static const int COL_DSPACING;
-      /// Index for integrated intensity column
-      static const int COL_INT;
-      /// Index for uncertainty in integrated intensity column
-      static const int COL_SIGMINT;
-      /// Label for ratio of intensity/uncertainty
-      static const int COL_INT_SIGINT;
-      /// Index for bin count column
-      static const int COL_BINCOUNT;
-      /// Index for bank name column
-      static const int COL_BANKNAME;
-      /// Index for detector row column
-      static const int COL_ROW;
-      /// Index for detector column column
-      static const int COL_COL;
-      /// Index for Q-vector in the lab frame column
-      static const int COL_QLAB;
-      /// Index for Q-vector in the sample column
-      static const int COL_QSAMPLE;
-
-      /// The number of digits past the decimal to display in the table
-      int m_hklPrec;
-
-      mutable std::vector<QString> m_dataCache;
-      mutable int m_dataCachePeakIndex;
-
-      QString findColumnName(const int colIndex) const;
-      void updateDataCache(const Mantid::Geometry::IPeak& peak, const int row) const;
-
-      /// Collection of data for viewing.
-      boost::shared_ptr<const Mantid::API::IPeaksWorkspace> m_peaksWS;
-
-      /// Map of column indexes to names
-      ColumnIndexNameMap m_columnNameMap;
-
-      /// Map of column names to sortable flag.
-      ColumnNameSortableMap m_sortableColumns;
-    };
-  }
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER QPeaksTableModel
+    : public QAbstractTableModel {
+  Q_OBJECT
+public:
+  QPeaksTableModel(
+      boost::shared_ptr<const Mantid::API::IPeaksWorkspace> peaksWS);
+  void update();
+  int rowCount(const QModelIndex &parent) const override;
+  int columnCount(const QModelIndex &parent) const override;
+  QVariant data(const QModelIndex &index, int role) const override;
+  QVariant headerData(int section, Qt::Orientation orientation,
+                      int role) const override;
+  Qt::ItemFlags flags(const QModelIndex &index) const override;
+  void sort(int column, Qt::SortOrder) override;
+  int numCharacters(const int column) const;
+  std::vector<int> defaultHideCols();
+  ~QPeaksTableModel() override;
+  void setPeaksWorkspace(
+      boost::shared_ptr<const Mantid::API::IPeaksWorkspace> peaksWS);
+signals:
+  void peaksSorted(const std::string &, const bool);
+
+private:
+  typedef QString ColumnNameType;
+  typedef QString ColumnValueType;
+  typedef std::map<ColumnNameType, bool> ColumnNameSortableMap;
+  typedef std::map<int, ColumnNameType> ColumnIndexNameMap;
+
+public:
+  /// Label for run number column
+  static const QString RUNNUMBER;
+  /// Label for detector id column
+  static const QString DETID;
+  /// Label for h column
+  static const QString H;
+  /// Label for k column
+  static const QString K;
+  /// Label for l column
+  static const QString L;
+  /// Label for wavelength column
+  static const QString WAVELENGTH;
+  /// Label for change in energy column
+  static const QString ENERGY;
+  /// Label for initial energy column
+  static const QString INITIAL_ENERGY;
+  /// Label for final energy column
+  static const QString FINAL_ENERGY;
+  /// Label for time-of-flight column
+  static const QString TOF;
+  /// Label for d-spacing column
+  static const QString DSPACING;
+  /// Label for integrated intensity column
+  static const QString INT;
+  /// Label for uncertainty in integrated intensity column
+  static const QString SIGMINT;
+  /// Label for ratio of intensity/uncertainty
+  static const QString INT_SIGINT;
+  /// Label for bin count column
+  static const QString BINCOUNT;
+  /// Label for bank name column
+  static const QString BANKNAME;
+  /// Label for detector row column
+  static const QString ROW;
+  /// Label for detector column column
+  static const QString COL;
+  /// Label for Q-vector in the lab frame column
+  static const QString QLAB;
+  /// Label for Q-vector in the sample column
+  static const QString QSAMPLE;
+
+private:
+  /// Index for run number column
+  static const int COL_RUNNUMBER;
+  /// Index for detector id column
+  static const int COL_DETID;
+  /// Index for h column
+  static const int COL_H;
+  /// Index for k column
+  static const int COL_K;
+  /// Index for l column
+  static const int COL_L;
+  /// Index for wavelength column
+  static const int COL_WAVELENGTH;
+  /// Index for change in energy column
+  static const int COL_ENERGY;
+  /// Index for initial energy column
+  static const int COL_INITIAL_ENERGY;
+  /// Index for final energy column
+  static const int COL_FINAL_ENERGY;
+  /// Index for time-of-flight column
+  static const int COL_TOF;
+  /// Index for d-spacing column
+  static const int COL_DSPACING;
+  /// Index for integrated intensity column
+  static const int COL_INT;
+  /// Index for uncertainty in integrated intensity column
+  static const int COL_SIGMINT;
+  /// Label for ratio of intensity/uncertainty
+  static const int COL_INT_SIGINT;
+  /// Index for bin count column
+  static const int COL_BINCOUNT;
+  /// Index for bank name column
+  static const int COL_BANKNAME;
+  /// Index for detector row column
+  static const int COL_ROW;
+  /// Index for detector column column
+  static const int COL_COL;
+  /// Index for Q-vector in the lab frame column
+  static const int COL_QLAB;
+  /// Index for Q-vector in the sample column
+  static const int COL_QSAMPLE;
+
+  /// The number of digits past the decimal to display in the table
+  int m_hklPrec;
+
+  mutable std::vector<QString> m_dataCache;
+  mutable int m_dataCachePeakIndex;
+
+  QString findColumnName(const int colIndex) const;
+  void updateDataCache(const Mantid::Geometry::IPeak &peak,
+                       const int row) const;
+
+  /// Collection of data for viewing.
+  boost::shared_ptr<const Mantid::API::IPeaksWorkspace> m_peaksWS;
+
+  /// Map of column indexes to names
+  ColumnIndexNameMap m_columnNameMap;
+
+  /// Map of column names to sortable flag.
+  ColumnNameSortableMap m_sortableColumns;
+};
+}
 }
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewer.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewer.h
index ced4757e07bfd765c4ac16046df959d59516cb22..7b9e6e4d32caabf3ed945d0d38db63da61d15d6b 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewer.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewer.h
@@ -29,17 +29,13 @@ class QDragEnterEvent;
 class QDropEvent;
 class QwtPlotRescaler;
 
-namespace Mantid
-{
-namespace API
-{
- class IPeaksWorkspace;
+namespace Mantid {
+namespace API {
+class IPeaksWorkspace;
 }
 }
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 // Forward dec
 class CompositePeaksPresenter;
@@ -47,26 +43,31 @@ class ProxyCompositePeaksPresenter;
 
 // Static Const values
 static const std::string g_iconPathPrefix = ":/SliceViewer/icons/";
-static const std::string g_iconZoomPlus = g_iconPathPrefix + "colour zoom plus scale 32x32.png";
-static const std::string g_iconZoomMinus = g_iconPathPrefix + "colour zoom minus scale 32x32.png";
-static const std::string g_iconViewFull = g_iconPathPrefix + "view-fullscreen.png";
+static const std::string g_iconZoomPlus =
+    g_iconPathPrefix + "colour zoom plus scale 32x32.png";
+static const std::string g_iconZoomMinus =
+    g_iconPathPrefix + "colour zoom minus scale 32x32.png";
+static const std::string g_iconViewFull =
+    g_iconPathPrefix + "view-fullscreen.png";
 static const std::string g_iconCutOn = g_iconPathPrefix + "cut on 32x32.png";
 static const std::string g_iconCut = g_iconPathPrefix + "cut 32x32.png";
 static const std::string g_iconGridOn = g_iconPathPrefix + "grid on 32x32.png";
 static const std::string g_iconGrid = g_iconPathPrefix + "grid 32x32.png";
-static const std::string g_iconRebinOn = g_iconPathPrefix + "rebin on 32x32.png";
+static const std::string g_iconRebinOn =
+    g_iconPathPrefix + "rebin on 32x32.png";
 static const std::string g_iconRebin = g_iconPathPrefix + "rebin 32x32.png";
-static const std::string g_iconPeakListOn = g_iconPathPrefix + "Peak List on 32x32.png";
-static const std::string g_iconPeakList = g_iconPathPrefix + "Peak List 32x32.png";
-
+static const std::string g_iconPeakListOn =
+    g_iconPathPrefix + "Peak List on 32x32.png";
+static const std::string g_iconPeakList =
+    g_iconPathPrefix + "Peak List 32x32.png";
 
 /** GUI for viewing a 2D slice out of a multi-dimensional workspace.
  * You can select which dimension to plot as X,Y, and the cut point
  * along the other dimension(s).
  *
  */
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER SliceViewer : public QWidget, public ZoomablePeaksView
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER SliceViewer : public QWidget,
+                                                    public ZoomablePeaksView {
   friend class SliceViewerWindow;
 
   Q_OBJECT
@@ -75,13 +76,13 @@ public:
   SliceViewer(QWidget *parent = 0);
   ~SliceViewer() override;
 
-  void setWorkspace(const QString & wsName);
+  void setWorkspace(const QString &wsName);
   void setWorkspace(Mantid::API::IMDWorkspace_sptr ws);
   Mantid::API::IMDWorkspace_sptr getWorkspace();
   void showControls(bool visible);
   void zoomBy(double factor);
-  void loadColorMap(QString filename = QString() );
-  LineOverlay * getLineOverlay() { return m_lineOverlay; }
+  void loadColorMap(QString filename = QString());
+  LineOverlay *getLineOverlay() { return m_lineOverlay; }
   Mantid::Kernel::VMD getSlicePoint() const { return m_slicePoint; }
   int getDimX() const;
   int getDimY() const;
@@ -89,11 +90,11 @@ public:
   /// Methods for Python bindings
   QString getWorkspaceName() const;
   void setXYDim(int indexX, int indexY);
-  void setXYDim(const QString & dimX, const QString & dimY);
+  void setXYDim(const QString &dimX, const QString &dimY);
   void setSlicePoint(int dim, double value);
-  void setSlicePoint(const QString & dim, double value);
+  void setSlicePoint(const QString &dim, double value);
   double getSlicePoint(int dim) const;
-  double getSlicePoint(const QString & dim) const;
+  double getSlicePoint(const QString &dim) const;
   void setColorScaleMin(double min);
   void setColorScaleMax(double max);
   void setColorScaleLog(bool log);
@@ -109,9 +110,9 @@ public:
   QwtDoubleInterval getXLimits() const;
   QwtDoubleInterval getYLimits() const;
   void setXYCenter(double x, double y);
-  void openFromXML(const QString & xml);
+  void openFromXML(const QString &xml);
   void toggleLineMode(bool);
-  void setNormalization(Mantid::API::MDNormalization norm, bool update=true);
+  void setNormalization(Mantid::API::MDNormalization norm, bool update = true);
   Mantid::API::MDNormalization getNormalization() const;
   void setColorBarAutoScale(bool autoscale);
 
@@ -123,8 +124,9 @@ public:
 
   /// Methods relating to peaks overlays.
   boost::shared_ptr<ProxyCompositePeaksPresenter> getPeaksPresenter() const;
-  ProxyCompositePeaksPresenter* setPeaksWorkspaces(const QStringList& list); // For python binding
-  void clearPeaksWorkspaces(); // For python binding
+  ProxyCompositePeaksPresenter *
+  setPeaksWorkspaces(const QStringList &list); // For python binding
+  void clearPeaksWorkspaces();                 // For python binding
 
   /* -- Methods from implementation of ZoomablePeaksView. --*/
   void zoomToRectangle(const PeakBoundingBox &box) override;
@@ -132,7 +134,9 @@ public:
   void detach() override;
 
   /* Methods associated with workspace observers. Driven by SliceViewerWindow */
-  void peakWorkspaceChanged(const std::string& wsName, boost::shared_ptr<Mantid::API::IPeaksWorkspace>& changedPeaksWS);
+  void peakWorkspaceChanged(
+      const std::string &wsName,
+      boost::shared_ptr<Mantid::API::IPeaksWorkspace> &changedPeaksWS);
 
 signals:
   /// Signal emitted when the X/Y index of the shown dimensions is changed
@@ -162,7 +166,7 @@ public slots:
   void setXYLimitsDialog();
   void zoomInSlot();
   void zoomOutSlot();
-  void zoomRectSlot(const QwtDoubleRect & rect);
+  void zoomRectSlot(const QwtDoubleRect &rect);
   void panned(int, int);
   void magnifierRescaled(double);
 
@@ -175,16 +179,15 @@ public slots:
   void changeNormalizationNone();
   void changeNormalizationVolume();
   void changeNormalizationNumEvents();
-  void onNormalizationChanged(const QString& normalizationKey);
+  void onNormalizationChanged(const QString &normalizationKey);
 
   // Buttons or actions
   void clearLine();
   QPixmap getImage();
-  void saveImage(const QString & filename = QString());
+  void saveImage(const QString &filename = QString());
   void copyImageToClipboard();
   void onPeaksViewerOverlayOptions();
 
-
   // Synced checkboxes
   void LineMode_toggled(bool);
   void SnapToGrid_toggled(bool);
@@ -206,19 +209,20 @@ protected:
   void dropEvent(QDropEvent *e) override;
 
 private:
-  enum AspectRatioType{Guess=0, All=1, Unlock=2};
+  enum AspectRatioType { Guess = 0, All = 1, Unlock = 2 };
   void loadSettings();
   void saveSettings();
-  void setIconFromString(QAction* action, const std::string& iconName,
-    QIcon::Mode mode, QIcon::State state);
-  void setIconFromString(QAbstractButton* btn, const std::string& iconName,
-    QIcon::Mode mode, QIcon::State state);
+  void setIconFromString(QAction *action, const std::string &iconName,
+                         QIcon::Mode mode, QIcon::State state);
+  void setIconFromString(QAbstractButton *btn, const std::string &iconName,
+                         QIcon::Mode mode, QIcon::State state);
   void initMenus();
   void initZoomer();
 
   void updateDisplay(bool resetAxes = false);
   void updateDimensionSliceWidgets();
-  void resetAxis(int axis, const Mantid::Geometry::IMDDimension_const_sptr & dim);
+  void resetAxis(int axis,
+                 const Mantid::Geometry::IMDDimension_const_sptr &dim);
 
   void findRangeFull();
   void findRangeSlice();
@@ -234,7 +238,7 @@ private:
   void autoRebinIfRequired();
 
   // helper for saveImage
-  QString ensurePngExtension(const QString& fname) const;
+  QString ensurePngExtension(const QString &fname) const;
 
   // Rescaler methods
   void updateAspectRatios();
@@ -246,38 +250,36 @@ private:
   void applyColorScalingForCurrentSliceIfRequired();
 
 private:
-  
-
   // -------------------------- Widgets ----------------------------
 
   /// Auto-generated UI controls.
   Ui::SliceViewerClass ui;
 
   /// Main plot object
-  MantidQt::MantidWidgets::SafeQwtPlot * m_plot;
+  MantidQt::MantidWidgets::SafeQwtPlot *m_plot;
 
   /// Spectrogram plot
-  QwtPlotSpectrogram * m_spect;
+  QwtPlotSpectrogram *m_spect;
 
   /// Layout containing the spectrogram
-  QHBoxLayout * m_spectLayout;
+  QHBoxLayout *m_spectLayout;
 
   /// Color bar indicating the color scale
-  MantidQt::MantidWidgets::ColorBarWidget * m_colorBar;
+  MantidQt::MantidWidgets::ColorBarWidget *m_colorBar;
 
   /// Vector of the widgets for slicing dimensions
   std::vector<DimensionSliceWidget *> m_dimWidgets;
 
   /// The LineOverlay widget for drawing line cross-sections (hidden at startup)
-  LineOverlay * m_lineOverlay;
+  LineOverlay *m_lineOverlay;
 
   /// The LineOverlay widget for drawing the outline of the rebinned workspace
-  LineOverlay * m_overlayWSOutline;
+  LineOverlay *m_overlayWSOutline;
 
-  //PeakOverlay * m_peakOverlay;
+  // PeakOverlay * m_peakOverlay;
 
   /// Object for running algorithms in the background
-  MantidQt::API::AlgorithmRunner * m_algoRunner;
+  MantidQt::API::AlgorithmRunner *m_algoRunner;
 
   // -------------------------- Data Members ----------------------------
 
@@ -297,7 +299,7 @@ private:
   std::vector<Mantid::Geometry::MDHistoDimension_sptr> m_dimensions;
 
   /// Data presenter
-  API::QwtRasterDataMD * m_data;
+  API::QwtRasterDataMD *m_data;
 
   /// The X and Y dimensions being plotted
   Mantid::Geometry::IMDDimension_const_sptr m_X;
@@ -314,14 +316,16 @@ private:
   /// The calculated range of values in the FULL data set
   QwtDoubleInterval m_colorRangeFull;
 
-  /// The calculated range of values ONLY in the currently viewed part of the slice
+  /// The calculated range of values ONLY in the currently viewed part of the
+  /// slice
   QwtDoubleInterval m_colorRangeSlice;
 
   /// Use the log of the value for the color scale
   bool m_logColor;
 
   /// Menus
-  QMenu *m_menuColorOptions, *m_menuView, *m_menuHelp, *m_menuLine, *m_menuFile, *m_menuPeaks;
+  QMenu *m_menuColorOptions, *m_menuView, *m_menuHelp, *m_menuLine, *m_menuFile,
+      *m_menuPeaks;
   QAction *m_actionFileClose;
   QAction *m_actionTransparentZeros;
   QAction *m_actionNormalizeNone;
@@ -332,10 +336,9 @@ private:
   QAction *m_lockAspectRatiosActionAll;
   QAction *m_lockAspectRatiosActionUnlock;
 
-
   /// Synced menu/buttons
   MantidQt::API::SyncedCheckboxes *m_syncLineMode, *m_syncSnapToGrid,
-    *m_syncRebinMode, *m_syncAutoRebin;
+      *m_syncRebinMode, *m_syncAutoRebin;
 
   /// Cached double for infinity
   double m_inf;
@@ -355,32 +358,31 @@ private:
   /// If true, the rebinned overlayWS is locked until refreshed.
   bool m_rebinLocked;
 
-  /// Md Settings for color maps 
-  boost::shared_ptr<MantidQt::API::MdSettings>  m_mdSettings;
+  /// Md Settings for color maps
+  boost::shared_ptr<MantidQt::API::MdSettings> m_mdSettings;
 
   /// Logger
   Mantid::Kernel::Logger m_logger;
 
   // -------------------------- Controllers ------------------------
-  boost::shared_ptr<CompositePeaksPresenter>  m_peaksPresenter;
+  boost::shared_ptr<CompositePeaksPresenter> m_peaksPresenter;
 
   boost::shared_ptr<ProxyCompositePeaksPresenter> m_proxyPeaksPresenter;
 
   /// Pointer to widget used for peaks sliding.
-  DimensionSliceWidget* m_peaksSliderWidget;
+  DimensionSliceWidget *m_peaksSliderWidget;
 
   /// Object for choosing a PeakTransformFactory based on the workspace type.
   Mantid::Geometry::PeakTransformSelector m_peakTransformSelector;
 
   /// Plot rescaler. For fixed aspect ratios.
-  QwtPlotRescaler* m_rescaler;
+  QwtPlotRescaler *m_rescaler;
 
   static const QString NoNormalizationKey;
   static const QString VolumeNormalizationKey;
   static const QString NumEventsNormalizationKey;
 
   AspectRatioType m_aspectRatioType;
-
 };
 
 } // namespace SliceViewer
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewerFunctions.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewerFunctions.h
index c577cbd8fb0d428c180cb746f586a139ca995825..5e75f3e5877981f3a79e001f5b2b1fc25436e261 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewerFunctions.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SliceViewerFunctions.h
@@ -15,12 +15,14 @@ bool EXPORT_OPT_MANTIDQT_SLICEVIEWER doesSliceCutThroughWorkspace(
     const std::vector<Mantid::Geometry::MDHistoDimension_sptr> &dimensions);
 
 /// Checks if rebin mode is in consistent state
-bool EXPORT_OPT_MANTIDQT_SLICEVIEWER isRebinInConsistentState(
-    Mantid::API::IMDWorkspace *rebinnedWS, bool useRebinMode);
+bool EXPORT_OPT_MANTIDQT_SLICEVIEWER
+isRebinInConsistentState(Mantid::API::IMDWorkspace *rebinnedWS,
+                         bool useRebinMode);
 
 /// Should perform auto color scaling on load
-bool EXPORT_OPT_MANTIDQT_SLICEVIEWER shouldAutoScaleForNewlySetWorkspace(
-    bool isFirstWorkspaceOpen, bool isAutoScalingOnLoad);
+bool EXPORT_OPT_MANTIDQT_SLICEVIEWER
+shouldAutoScaleForNewlySetWorkspace(bool isFirstWorkspaceOpen,
+                                    bool isAutoScalingOnLoad);
 }
 }
 #endif
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SnapToGridDialog.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SnapToGridDialog.h
index 18a3d435d74c0b7f46f85e5f1a6dcf270d98699b..382dc2b60484152eac0efdc440989cdf8aaf2559 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SnapToGridDialog.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/SnapToGridDialog.h
@@ -11,8 +11,7 @@
  *
  * For use with the SliceViewer.
  */
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER SnapToGridDialog : public QDialog
-{
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER SnapToGridDialog : public QDialog {
   Q_OBJECT
 
 public:
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/UpdateableOnDemand.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/UpdateableOnDemand.h
index 56a94e73a29ff31b9d32c6339ac2f49bd20131af..73d68e7ba8f33dc6b78a6a77f186437d04e910b1 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/UpdateableOnDemand.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/UpdateableOnDemand.h
@@ -4,35 +4,30 @@
 #include "MantidKernel/System.h"
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-namespace API
-{
+namespace Mantid {
+namespace API {
 class IPeaksWorkspace;
 }
 }
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-  /**
-   * Abstract class for types that can be forced to update themselves upon request.
-   */
-  class DLLExport UpdateableOnDemand
-  {
-  public:
-    // Force the implementation to update itself
-    virtual void performUpdate() = 0;
-    // Deliver a new peaks workspace for replacement of an existing one.
-    virtual void updatePeaksWorkspace(const std::string& toName, boost::shared_ptr<const Mantid::API::IPeaksWorkspace> toWorkspace) = 0;
-    // Destructor
-    virtual ~UpdateableOnDemand(){}
-  };
+namespace MantidQt {
+namespace SliceViewer {
+/**
+ * Abstract class for types that can be forced to update themselves upon
+ * request.
+ */
+class DLLExport UpdateableOnDemand {
+public:
+  // Force the implementation to update itself
+  virtual void performUpdate() = 0;
+  // Deliver a new peaks workspace for replacement of an existing one.
+  virtual void updatePeaksWorkspace(
+      const std::string &toName,
+      boost::shared_ptr<const Mantid::API::IPeaksWorkspace> toWorkspace) = 0;
+  // Destructor
+  virtual ~UpdateableOnDemand() {}
+};
 }
 }
 
-
-
-
 #endif /* UPDATEABLEONDEMAND_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/XYLimitsDialog.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/XYLimitsDialog.h
index 6577939f7d0ef24c1581d516b6fa61234f902780..f8bc6973fa4c172e2cfeb4373c0a4654ff604fd0 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/XYLimitsDialog.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/XYLimitsDialog.h
@@ -6,30 +6,28 @@
 #include "DllOption.h"
 #include "MantidGeometry/MDGeometry/IMDDimension.h"
 
-
 /** Dialog that prompts the user
  * to enter the X and Y limits to the axes
  *
  * For use with the SliceViewer.
  */
-class EXPORT_OPT_MANTIDQT_SLICEVIEWER XYLimitsDialog : public QDialog
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDQT_SLICEVIEWER XYLimitsDialog : public QDialog {
+  Q_OBJECT
 
 public:
-    XYLimitsDialog(QWidget *parent = 0);
-    ~XYLimitsDialog() override;
+  XYLimitsDialog(QWidget *parent = 0);
+  ~XYLimitsDialog() override;
 
-    void setXDim(Mantid::Geometry::IMDDimension_const_sptr dim);
-    void setYDim(Mantid::Geometry::IMDDimension_const_sptr dim);
-    void setLimits(double x0, double x1, double y0, double y1);
-    double getXMin();
-    double getXMax();
-    double getYMin();
-    double getYMax();
+  void setXDim(Mantid::Geometry::IMDDimension_const_sptr dim);
+  void setYDim(Mantid::Geometry::IMDDimension_const_sptr dim);
+  void setLimits(double x0, double x1, double y0, double y1);
+  double getXMin();
+  double getXMax();
+  double getYMin();
+  double getYMax();
 
 private:
-    Ui::XYLimitsDialogClass ui;
+  Ui::XYLimitsDialogClass ui;
 };
 
 #endif // XYLIMITSDIALOG_H
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomableOnDemand.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomableOnDemand.h
index 7ffe7b7fcf6fbe4bb7316fc1ca4d98b915c9d0c7..3a21194d630debd920b3b5facf52b08698914f25 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomableOnDemand.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomableOnDemand.h
@@ -3,50 +3,48 @@
 
 #include "MantidKernel/System.h"
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /// Forward dec
-    class PeaksPresenter;
-
-    /** Abstract behavioural type for zooming to a peak region on demand.
-
-     @date 2013-07-11
-
-     Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-     This file is part of Mantid.
-
-     Mantid is free software; you can redistribute it and/or modify
-     it under the terms of the GNU General Public License as published by
-     the Free Software Foundation; either version 3 of the License, or
-     (at your option) any later version.
-
-     Mantid is distributed in the hope that it will be useful,
-     but WITHOUT ANY WARRANTY; without even the implied warranty of
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-     GNU General Public License for more details.
-
-     You should have received a copy of the GNU General Public License
-     along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-     File change history is stored at: <https://github.com/mantidproject/mantid>
-     Code Documentation is available at: <http://doxygen.mantidproject.org>
-     */
-
-    class DLLExport ZoomableOnDemand
-    {
-    public:
-      /// Zoom to a peak
-      virtual void zoomToPeak(PeaksPresenter* const presenter, const int peakIndex) = 0;
-      /// Reset/forget zoom
-      virtual void resetZoom() = 0;
-      /// destructor
-      virtual ~ZoomableOnDemand(){}
-    };
-
-  }
+namespace MantidQt {
+namespace SliceViewer {
+/// Forward dec
+class PeaksPresenter;
+
+/** Abstract behavioural type for zooming to a peak region on demand.
+
+ @date 2013-07-11
+
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+ This file is part of Mantid.
+
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+
+class DLLExport ZoomableOnDemand {
+public:
+  /// Zoom to a peak
+  virtual void zoomToPeak(PeaksPresenter *const presenter,
+                          const int peakIndex) = 0;
+  /// Reset/forget zoom
+  virtual void resetZoom() = 0;
+  /// destructor
+  virtual ~ZoomableOnDemand() {}
+};
+}
 }
 
 #endif /* ZOOMABLEONDEMAND_H_ */
diff --git a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomablePeaksView.h b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomablePeaksView.h
index 32bc20422a668f2bfeb388b2b1e2a4bf8d947c5f..64fc863c1e325b22803f5540082fc5d5ffcd0d44 100644
--- a/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomablePeaksView.h
+++ b/MantidQt/SliceViewer/inc/MantidQtSliceViewer/ZoomablePeaksView.h
@@ -5,51 +5,49 @@
 #include "MantidKernel/V2D.h"
 #include <boost/shared_ptr.hpp>
 
-
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /// Forward dec
-    class PeakBoundingBox;
-
-    /** Abstract view in Representing a view that can be zoomed in upon.
-    
-    @date 2013-01-08
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport ZoomablePeaksView
-    {
-    public:
-      /// Zoom to a peak position provided by a boundary rectangle in the windows coordinate system.
-      virtual void zoomToRectangle(const PeakBoundingBox&) = 0;
-      /// Zoom out
-      virtual void resetView() = 0;
-      /// Detach
-      virtual void detach() = 0;
-      /// Destructor
-      virtual ~ZoomablePeaksView(){ }
-    };
-  }
+namespace MantidQt {
+namespace SliceViewer {
+/// Forward dec
+class PeakBoundingBox;
+
+/** Abstract view in Representing a view that can be zoomed in upon.
+
+@date 2013-01-08
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport ZoomablePeaksView {
+public:
+  /// Zoom to a peak position provided by a boundary rectangle in the windows
+  /// coordinate system.
+  virtual void zoomToRectangle(const PeakBoundingBox &) = 0;
+  /// Zoom out
+  virtual void resetView() = 0;
+  /// Detach
+  virtual void detach() = 0;
+  /// Destructor
+  virtual ~ZoomablePeaksView() {}
+};
+}
 }
 
 #endif /* MANTID_SLICEVIEWER_ZOOMABLE_PEAKS_VIEW_H_ */
diff --git a/MantidQt/SliceViewer/src/CompositePeaksPresenter.cpp b/MantidQt/SliceViewer/src/CompositePeaksPresenter.cpp
index f2f315abb3462ace64c3896313bce07c3fe4fc15..37f4697390b547bb7a6c8479834473f93dcd7523 100644
--- a/MantidQt/SliceViewer/src/CompositePeaksPresenter.cpp
+++ b/MantidQt/SliceViewer/src/CompositePeaksPresenter.cpp
@@ -13,7 +13,7 @@ CompositePeaksPresenter::CompositePeaksPresenter(
     ZoomablePeaksView *const zoomablePlottingWidget,
     PeaksPresenter_sptr defaultPresenter)
     : m_zoomablePlottingWidget(zoomablePlottingWidget),
-      m_default(defaultPresenter), m_owner(NULL), m_zoomedPeakIndex(-1){
+      m_default(defaultPresenter), m_owner(NULL), m_zoomedPeakIndex(-1) {
   if (m_zoomablePlottingWidget == NULL) {
     throw std::runtime_error("Zoomable Plotting Widget is NULL");
   }
@@ -41,8 +41,8 @@ void CompositePeaksPresenter::update() {
 Overriden updateWithSlicePoint
 @param point : Slice point to update with
 */
-void
-CompositePeaksPresenter::updateWithSlicePoint(const PeakBoundingBox &point) {
+void CompositePeaksPresenter::updateWithSlicePoint(
+    const PeakBoundingBox &point) {
   if (useDefault()) {
     m_default->updateWithSlicePoint(point);
     return;
@@ -70,8 +70,8 @@ bool CompositePeaksPresenter::changeShownDim() {
 Determine wheter a given axis label correponds to the free peak axis.
 @return True only if the label is that of the free peak axis.
 */
-bool
-CompositePeaksPresenter::isLabelOfFreeAxis(const std::string &label) const {
+bool CompositePeaksPresenter::isLabelOfFreeAxis(
+    const std::string &label) const {
   if (useDefault()) {
     return m_default->isLabelOfFreeAxis(label);
   }
@@ -237,7 +237,6 @@ void CompositePeaksPresenter::setBackgroundColor(
   (*iterator)->setBackgroundColor(color);
 }
 
-
 /**
 Getter for the name of the transform.
 @return transform name.
@@ -256,7 +255,6 @@ PeakPalette<PeakViewColor> CompositePeaksPresenter::getPalette() const {
   return this->m_palettePeakViewColor;
 }
 
-
 /**
 @param ws: PeakWorkspace to get the colour for.
 @return the foreground colour corresponding to the peaks workspace.
@@ -390,13 +388,13 @@ void CompositePeaksPresenter::setPeakSizeOnProjection(const double fraction) {
  * @param mode : Mode to enter.
  */
 void CompositePeaksPresenter::peakEditMode(EditMode mode) {
-    if (useDefault()) {
-      return m_default->peakEditMode(mode);
-    }
-    for (auto presenterIterator = m_subjects.begin();
-         presenterIterator != m_subjects.end(); ++presenterIterator) {
-      (*presenterIterator)->peakEditMode(mode);
-    }
+  if (useDefault()) {
+    return m_default->peakEditMode(mode);
+  }
+  for (auto presenterIterator = m_subjects.begin();
+       presenterIterator != m_subjects.end(); ++presenterIterator) {
+    (*presenterIterator)->peakEditMode(mode);
+  }
 }
 
 /**
@@ -522,8 +520,8 @@ CompositePeaksPresenter::getPeaksPresenter(const QString &name) {
  * Register an owning presenter for this object.
  * @param owner
  */
-void
-CompositePeaksPresenter::registerOwningPresenter(UpdateableOnDemand *owner) {
+void CompositePeaksPresenter::registerOwningPresenter(
+    UpdateableOnDemand *owner) {
   m_owner = owner;
 }
 
@@ -536,8 +534,10 @@ void CompositePeaksPresenter::performUpdate() {
     auto presenter = (*presenterIterator);
     const int pos =
         static_cast<int>(std::distance(m_subjects.begin(), presenterIterator));
-    m_palettePeakViewColor.setBackgroundColour(pos, presenter->getBackgroundPeakViewColor());
-    m_palettePeakViewColor.setForegroundColour(pos, presenter->getForegroundPeakViewColor());
+    m_palettePeakViewColor.setBackgroundColour(
+        pos, presenter->getBackgroundPeakViewColor());
+    m_palettePeakViewColor.setForegroundColour(
+        pos, presenter->getForegroundPeakViewColor());
 
     if (m_owner) {
       m_owner->performUpdate();
@@ -621,7 +621,7 @@ CompositePeaksPresenter::getZoomedPeakPresenter() const {
  * @return a zoomed peak index.
  */
 int CompositePeaksPresenter::getZoomedPeakIndex() const {
-    return m_zoomedPeakIndex;
+  return m_zoomedPeakIndex;
 }
 
 void CompositePeaksPresenter::editCommand(
@@ -688,54 +688,53 @@ void CompositePeaksPresenter::notifyWorkspaceChanged(
   }
 }
 
-bool CompositePeaksPresenter::deletePeaksIn(PeakBoundingBox box){
-    if (useDefault()) {
-      return m_default->deletePeaksIn(box);
-    }
-    // Forward the request onwards
-    bool result = false;
-    for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
-      result |= (*it)->deletePeaksIn(box);
-    }
-    return result;
+bool CompositePeaksPresenter::deletePeaksIn(PeakBoundingBox box) {
+  if (useDefault()) {
+    return m_default->deletePeaksIn(box);
+  }
+  // Forward the request onwards
+  bool result = false;
+  for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
+    result |= (*it)->deletePeaksIn(box);
+  }
+  return result;
 }
 
-bool CompositePeaksPresenter::hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target){
-    bool hasMode  = false;
-    if(auto temp = target.lock()) {
-        auto it = this->getPresenterIteratorFromWorkspace(temp);
-        if(it != m_subjects.end()) {
-            hasMode = (*it)->hasPeakAddMode();
-        }
+bool CompositePeaksPresenter::hasPeakAddModeFor(
+    boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target) {
+  bool hasMode = false;
+  if (auto temp = target.lock()) {
+    auto it = this->getPresenterIteratorFromWorkspace(temp);
+    if (it != m_subjects.end()) {
+      hasMode = (*it)->hasPeakAddMode();
     }
-    return hasMode;
+  }
+  return hasMode;
 }
 
-bool CompositePeaksPresenter::hasPeakAddMode() const{
-    if (useDefault()) {
-      return m_default->hasPeakAddMode();
-    }
-    // Forward the request onwards
-    bool hasMode = false;
-    for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
-      hasMode |= (*it)->hasPeakAddMode();
-    }
-    return hasMode;
+bool CompositePeaksPresenter::hasPeakAddMode() const {
+  if (useDefault()) {
+    return m_default->hasPeakAddMode();
+  }
+  // Forward the request onwards
+  bool hasMode = false;
+  for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
+    hasMode |= (*it)->hasPeakAddMode();
+  }
+  return hasMode;
 }
 
-bool CompositePeaksPresenter::addPeakAt(double plotCoordsPointX, double plotCoordsPointY)
-{
-    if (useDefault()) {
-      return m_default->addPeakAt(plotCoordsPointX, plotCoordsPointY);
-    }
-    // Forward the request onwards
-    bool result = false;
-    for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
-      result |= (*it)->addPeakAt(plotCoordsPointX, plotCoordsPointY);
-    }
-    return result;
+bool CompositePeaksPresenter::addPeakAt(double plotCoordsPointX,
+                                        double plotCoordsPointY) {
+  if (useDefault()) {
+    return m_default->addPeakAt(plotCoordsPointX, plotCoordsPointY);
+  }
+  // Forward the request onwards
+  bool result = false;
+  for (auto it = m_subjects.begin(); it != m_subjects.end(); ++it) {
+    result |= (*it)->addPeakAt(plotCoordsPointX, plotCoordsPointY);
+  }
+  return result;
 }
-
 }
 }
-
diff --git a/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp b/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp
index eab6fc27ddbb7057afe857c852145daab96c2caa..4b8eb18b996ccd8c3e1e9cfd29d6aebca9dfb6e1 100644
--- a/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp
+++ b/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp
@@ -532,8 +532,7 @@ bool ConcretePeaksPresenter::deletePeaksIn(PeakBoundingBox box) {
 
   // Tranform box from plot coordinates into orderd HKL, Qx,Qy,Qz etc, then find
   // the visible peaks.
-  std::vector<size_t> deletionIndexList = findVisiblePeakIndexes(
-      accurateBox);
+  std::vector<size_t> deletionIndexList = findVisiblePeakIndexes(accurateBox);
 
   // If we have things to remove, do that in one-step.
   if (!deletionIndexList.empty()) {
@@ -581,15 +580,13 @@ bool ConcretePeaksPresenter::addPeakAt(double plotCoordsPointX,
   alg->setProperty("Workspace", peaksWS);
   alg->setProperty("HKL", std::vector<double>(hkl));
 
-
-// Execute the algorithm
-try {
+  // Execute the algorithm
+  try {
     alg->execute();
-} catch (...) {
+  } catch (...) {
     g_log.warning("ConcretePeaksPresenter: Could not add the peak. Make sure "
                   "that it is added within a valid workspace region");
-}
-
+  }
 
   // Reproduce the views. Proxy representations recreated for all peaks.
   this->produceViews();
@@ -602,7 +599,6 @@ try {
   this->informOwnerUpdate();
 
   return alg->isExecuted();
-
 }
 
 bool ConcretePeaksPresenter::hasPeakAddMode() const {
@@ -620,30 +616,27 @@ ConcretePeaksPresenter::findVisiblePeakIndexes(const PeakBoundingBox &box) {
             ->getRadius(); // Effective radius of each peak representation.
 
     Mantid::API::IPeaksWorkspace_sptr peaksWS =
-          boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(
-              this->m_peaksWS);
-
-      PeakBoundingBox transformedViewableRegion =
-          box.makeSliceBox(radius);
-
-      transformedViewableRegion.transformBox(m_transform);
-
-
-      Mantid::API::IAlgorithm_sptr alg =
-          AlgorithmManager::Instance().create("PeaksInRegion");
-      alg->setChild(true);
-      alg->setRethrows(true);
-      alg->initialize();
-      alg->setProperty("InputWorkspace", peaksWS);
-      alg->setProperty("OutputWorkspace", peaksWS->name() + "_peaks_in_region");
-      alg->setProperty("Extents", transformedViewableRegion.toExtents());
-      alg->setProperty("CheckPeakExtents", false); // consider all peaks as points
-      alg->setProperty("PeakRadius", radius);
-      alg->setPropertyValue("CoordinateFrame", m_transform->getFriendlyName());
-      alg->execute();
-      ITableWorkspace_sptr outTable = alg->getProperty("OutputWorkspace");
-
-    
+        boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(
+            this->m_peaksWS);
+
+    PeakBoundingBox transformedViewableRegion = box.makeSliceBox(radius);
+
+    transformedViewableRegion.transformBox(m_transform);
+
+    Mantid::API::IAlgorithm_sptr alg =
+        AlgorithmManager::Instance().create("PeaksInRegion");
+    alg->setChild(true);
+    alg->setRethrows(true);
+    alg->initialize();
+    alg->setProperty("InputWorkspace", peaksWS);
+    alg->setProperty("OutputWorkspace", peaksWS->name() + "_peaks_in_region");
+    alg->setProperty("Extents", transformedViewableRegion.toExtents());
+    alg->setProperty("CheckPeakExtents", false); // consider all peaks as points
+    alg->setProperty("PeakRadius", radius);
+    alg->setPropertyValue("CoordinateFrame", m_transform->getFriendlyName());
+    alg->execute();
+    ITableWorkspace_sptr outTable = alg->getProperty("OutputWorkspace");
+
     for (size_t i = 0; i < outTable->rowCount(); ++i) {
       const bool insideRegion = outTable->cell<Boolean>(i, 1);
       if (insideRegion) {
diff --git a/MantidQt/SliceViewer/src/CustomTools.cpp b/MantidQt/SliceViewer/src/CustomTools.cpp
index f0a8f6ca9a73528e657fb7715094bfe700e17d03..d390c9af5a6607da8e2dae0f4079cc8af9f68043 100644
--- a/MantidQt/SliceViewer/src/CustomTools.cpp
+++ b/MantidQt/SliceViewer/src/CustomTools.cpp
@@ -1,54 +1,40 @@
 #include "MantidQtSliceViewer/CustomTools.h"
 #include <iosfwd>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
-  CustomPicker::CustomPicker(int xAxis, int yAxis, QwtPlotCanvas* canvas)
-  : QwtPlotPicker(xAxis, yAxis, 0, CrossRubberBand, AlwaysOn, canvas)
-  {
-    setSelectionFlags(QwtPicker::PointSelection);
-    setRubberBand(QwtPicker::CrossRubberBand);
-    canvas->setMouseTracking(true);
-  }
-
+namespace MantidQt {
+namespace SliceViewer {
+
+CustomPicker::CustomPicker(int xAxis, int yAxis, QwtPlotCanvas *canvas)
+    : QwtPlotPicker(xAxis, yAxis, 0, CrossRubberBand, AlwaysOn, canvas) {
+  setSelectionFlags(QwtPicker::PointSelection);
+  setRubberBand(QwtPicker::CrossRubberBand);
+  canvas->setMouseTracking(true);
+}
 
 /** Called each time the mouse moves over the canvas */
-  QwtText CustomPicker::trackerText(const QwtDoublePoint & pos) const
-  {
-    emit mouseMoved(pos.x(), pos.y());
-    return QwtText();
-  }
-
-  void CustomPicker::widgetMouseMoveEvent(QMouseEvent *e)
-  {
-    if ( !isActive() )
-    {
-      setSelectionFlags(QwtPicker::PointSelection);
+QwtText CustomPicker::trackerText(const QwtDoublePoint &pos) const {
+  emit mouseMoved(pos.x(), pos.y());
+  return QwtText();
+}
 
-      begin();
-      append(e->pos());
-    }
+void CustomPicker::widgetMouseMoveEvent(QMouseEvent *e) {
+  if (!isActive()) {
+    setSelectionFlags(QwtPicker::PointSelection);
 
-    QwtPlotPicker::widgetMouseMoveEvent(e);
+    begin();
+    append(e->pos());
   }
 
-  void CustomPicker::widgetLeaveEvent(QEvent *)
-  {
-    end();
-  }
+  QwtPlotPicker::widgetMouseMoveEvent(e);
+}
 
-  void CustomMagnifier::rescale(double factor)
-  {
-    if ( factor != 0.0 )
-    {
-      QwtPlotMagnifier::rescale(1 / factor);
-      emit rescaled(factor);
-    }
-  }
+void CustomPicker::widgetLeaveEvent(QEvent *) { end(); }
 
+void CustomMagnifier::rescale(double factor) {
+  if (factor != 0.0) {
+    QwtPlotMagnifier::rescale(1 / factor);
+    emit rescaled(factor);
+  }
+}
 }
 }
-
diff --git a/MantidQt/SliceViewer/src/DimensionSliceWidget.cpp b/MantidQt/SliceViewer/src/DimensionSliceWidget.cpp
index 1f9f01f697d68bc0fb8204e7255da72c72ecb447..ea661c7560149730f12c37e02a8622b6371814d8 100644
--- a/MantidQt/SliceViewer/src/DimensionSliceWidget.cpp
+++ b/MantidQt/SliceViewer/src/DimensionSliceWidget.cpp
@@ -3,32 +3,24 @@
 #include <iosfwd>
 #include <qlayout.h>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 DimensionSliceWidget::DimensionSliceWidget(QWidget *parent)
-    : QWidget(parent),
-      m_dim(),
-      m_dimIndex(0), m_shownDim(0),
-      m_slicePoint(0.0),
-      m_showRebinControls(false)
-{
+    : QWidget(parent), m_dim(), m_dimIndex(0), m_shownDim(0), m_slicePoint(0.0),
+      m_showRebinControls(false) {
   ui.setupUi(this);
 
-  QObject::connect(ui.horizontalSlider, SIGNAL( valueChanged(double)),
-                   this, SLOT(sliderMoved()));
-  QObject::connect(ui.doubleSpinBox, SIGNAL( valueChanged(double)),
-                   this, SLOT(spinBoxChanged()));
-  QObject::connect(ui.spinThickness, SIGNAL( valueChanged(double)),
-                   this, SLOT(spinThicknessChanged()));
-  QObject::connect(ui.spinBins, SIGNAL( valueChanged(int)),
-                   this, SLOT(spinBinsChanged()));
-  QObject::connect(ui.btnX, SIGNAL(toggled(bool)),
-                   this, SLOT(btnXYChanged()));
-  QObject::connect(ui.btnY, SIGNAL(toggled(bool)),
-                   this, SLOT(btnXYChanged()));
+  QObject::connect(ui.horizontalSlider, SIGNAL(valueChanged(double)), this,
+                   SLOT(sliderMoved()));
+  QObject::connect(ui.doubleSpinBox, SIGNAL(valueChanged(double)), this,
+                   SLOT(spinBoxChanged()));
+  QObject::connect(ui.spinThickness, SIGNAL(valueChanged(double)), this,
+                   SLOT(spinThicknessChanged()));
+  QObject::connect(ui.spinBins, SIGNAL(valueChanged(int)), this,
+                   SLOT(spinBinsChanged()));
+  QObject::connect(ui.btnX, SIGNAL(toggled(bool)), this, SLOT(btnXYChanged()));
+  QObject::connect(ui.btnY, SIGNAL(toggled(bool)), this, SLOT(btnXYChanged()));
 
   // Hide the rebinning controls
   ui.spinBins->setVisible(false);
@@ -36,14 +28,11 @@ DimensionSliceWidget::DimensionSliceWidget(QWidget *parent)
   ui.lblRebinInfo->setVisible(false);
 }
 
-DimensionSliceWidget::~DimensionSliceWidget()
-{
-}
+DimensionSliceWidget::~DimensionSliceWidget() {}
 
 //-------------------------------------------------------------------------------------------------
 /** Slot called when the slider moves */
-void DimensionSliceWidget::sliderMoved()
-{
+void DimensionSliceWidget::sliderMoved() {
   // Find the slice point
   m_slicePoint = ui.horizontalSlider->value();
 
@@ -53,8 +42,7 @@ void DimensionSliceWidget::sliderMoved()
 
 //-------------------------------------------------------------------------------------------------
 /** Slot called when the slider moves */
-void DimensionSliceWidget::spinBoxChanged()
-{
+void DimensionSliceWidget::spinBoxChanged() {
   // This is the slice point
   m_slicePoint = ui.doubleSpinBox->value();
 
@@ -69,20 +57,17 @@ void DimensionSliceWidget::spinBoxChanged()
 
 //-------------------------------------------------------------------------------------------------
 /** Called when the X button is clicked */
-void DimensionSliceWidget::btnXYChanged()
-{
+void DimensionSliceWidget::btnXYChanged() {
   int oldDim = m_shownDim;
   ui.btnX->blockSignals(true);
   ui.btnY->blockSignals(true);
-  if (ui.btnX->isChecked() && ui.btnY->isChecked() )
-  {
+  if (ui.btnX->isChecked() && ui.btnY->isChecked()) {
     // Toggle when both are checked
     if (m_shownDim == 0)
       this->setShownDim(1);
     else
       this->setShownDim(0);
-  }
-  else if (ui.btnX->isChecked())
+  } else if (ui.btnX->isChecked())
     this->setShownDim(0);
   else if (ui.btnY->isChecked())
     this->setShownDim(1);
@@ -96,20 +81,17 @@ void DimensionSliceWidget::btnXYChanged()
   ui.btnY->blockSignals(false);
 }
 
-
-
 //-------------------------------------------------------------------------------------------------
 /** Set the shown dimension
  *
  * @param dim :: -1 = None, 0 = X, 1 = Y. 2+ reserved for higher dimensions
  */
-void DimensionSliceWidget::setShownDim(int dim)
-{
+void DimensionSliceWidget::setShownDim(int dim) {
   m_shownDim = dim;
   ui.btnX->blockSignals(true);
   ui.btnY->blockSignals(true);
-  ui.btnX->setChecked( m_shownDim == 0 );
-  ui.btnY->setChecked( m_shownDim == 1 );
+  ui.btnX->setChecked(m_shownDim == 0);
+  ui.btnY->setChecked(m_shownDim == 1);
   ui.btnX->blockSignals(false);
   ui.btnY->blockSignals(false);
   /// Slice if dimension is not X or Y AND is not integrated
@@ -121,28 +103,24 @@ void DimensionSliceWidget::setShownDim(int dim)
     this->setSlicePoint(m_dim->getMinimum());
   }
 
-  ui.horizontalSlider->setVisible( slicing );
-  ui.doubleSpinBox->setVisible( slicing );
-  ui.lblUnits->setVisible( slicing );
+  ui.horizontalSlider->setVisible(slicing);
+  ui.doubleSpinBox->setVisible(slicing);
+  ui.lblUnits->setVisible(slicing);
 
   // Make the spacer expand to keep the buttons in the same spot
-  if (slicing)
-  {
-    if (ui.horizontalSpacer != NULL)
-    {
+  if (slicing) {
+    if (ui.horizontalSpacer != NULL) {
       // Remove the 3rd item (if it's not gone already) = the spacer
       ui.horizontalLayout->removeItem(ui.horizontalLayout->itemAt(3));
       delete ui.horizontalSpacer;
       ui.horizontalSpacer = NULL;
     }
-  }
-  else
-  {
+  } else {
     // Put the spacer back, if needed
-    if (ui.horizontalSpacer == NULL)
-    {
-      ui.horizontalSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum);
-      ui.horizontalLayout->insertSpacerItem(3, ui.horizontalSpacer );
+    if (ui.horizontalSpacer == NULL) {
+      ui.horizontalSpacer =
+          new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum);
+      ui.horizontalLayout->insertSpacerItem(3, ui.horizontalSpacer);
     }
   }
 
@@ -158,14 +136,12 @@ void DimensionSliceWidget::setShownDim(int dim)
   this->update();
 }
 
-
 //-------------------------------------------------------------------------------------------------
 /** Sets the slice point value.
  *
  * @param value :: where to slice
  */
-void DimensionSliceWidget::setSlicePoint(double value)
-{
+void DimensionSliceWidget::setSlicePoint(double value) {
   // This will trigger the required events
   ui.horizontalSlider->setValue(value);
 }
@@ -176,11 +152,11 @@ void DimensionSliceWidget::setSlicePoint(double value)
  * @param min :: min value
  * @param max :: max value
  */
-void DimensionSliceWidget::setMinMax(double min, double max)
-{
-  if (!m_dim) return;
-  ui.lblName->setText(QString::fromStdString(m_dim->getName()) );
-  ui.lblUnits->setText(QString::fromStdWString(m_dim->getUnits().utf8()) );
+void DimensionSliceWidget::setMinMax(double min, double max) {
+  if (!m_dim)
+    return;
+  ui.lblName->setText(QString::fromStdString(m_dim->getName()));
+  ui.lblUnits->setText(QString::fromStdWString(m_dim->getUnits().utf8()));
 
   ui.horizontalSlider->setRange(min, max, m_dim->getBinWidth());
 
@@ -189,78 +165,64 @@ void DimensionSliceWidget::setMinMax(double min, double max)
   ui.doubleSpinBox->setSingleStep(m_dim->getBinWidth());
 
   // Make sure the slice point is in range
-  if (m_slicePoint < m_dim->getMinimum()) m_slicePoint = m_dim->getMinimum();
-  if (m_slicePoint > m_dim->getMaximum()) m_slicePoint = m_dim->getMaximum();
+  if (m_slicePoint < m_dim->getMinimum())
+    m_slicePoint = m_dim->getMinimum();
+  if (m_slicePoint > m_dim->getMaximum())
+    m_slicePoint = m_dim->getMaximum();
   ui.doubleSpinBox->setValue(m_slicePoint);
-
 }
 
 //-------------------------------------------------------------------------------------------------
 /** Set the dimension to display */
-void DimensionSliceWidget::setDimension(int index, Mantid::Geometry::IMDDimension_const_sptr dim)
-{
+void DimensionSliceWidget::setDimension(
+    int index, Mantid::Geometry::IMDDimension_const_sptr dim) {
   m_dim = dim;
   m_dimIndex = index;
   double min = m_dim->getMinimum();
   double max = m_dim->getMaximum(); //- m_dim->getBinWidth()/2.0;
-  this->setMinMax(min,max);
+  this->setMinMax(min, max);
 }
 
-
-
 //-------------------------------------------------------------------------------------------------
 /** Sets whether to display the rebinning controls */
-void DimensionSliceWidget::showRebinControls(bool show)
-{
-  m_showRebinControls=show;
+void DimensionSliceWidget::showRebinControls(bool show) {
+  m_showRebinControls = show;
   this->setShownDim(m_shownDim);
 }
 
 /** @return whether the rebinning controls are shown */
-bool DimensionSliceWidget::showRebinControls() const
-{
+bool DimensionSliceWidget::showRebinControls() const {
   return m_showRebinControls;
 }
 
 //-------------------------------------------------------------------------------------------------
 /** @return the number of bins to rebin to */
-int DimensionSliceWidget::getNumBins() const
-{
-  return ui.spinBins->value();
-}
+int DimensionSliceWidget::getNumBins() const { return ui.spinBins->value(); }
 
 /** Sets the number of bins to rebin to */
-void DimensionSliceWidget::setNumBins(int val)
-{
-  ui.spinBins->setValue(val);
-}
+void DimensionSliceWidget::setNumBins(int val) { ui.spinBins->setValue(val); }
 
 //-------------------------------------------------------------------------------------------------
 /** @return the thickness to integrate when rebinning */
-double DimensionSliceWidget::getThickness() const
-{
+double DimensionSliceWidget::getThickness() const {
   return ui.spinThickness->value();
 }
 
 /** Sets the thickness to integrate when rebinning */
-void DimensionSliceWidget::setThickness(double val)
-{
+void DimensionSliceWidget::setThickness(double val) {
   ui.spinThickness->setValue(val);
 }
 
 //-------------------------------------------------------------------------------------------------
 /** Slot called when the thickness to rebin to is changed */
-void DimensionSliceWidget::spinThicknessChanged()
-{
+void DimensionSliceWidget::spinThicknessChanged() {
   emit changedThickness(m_dimIndex, this->getThickness());
 }
 
 //-------------------------------------------------------------------------------------------------
 /** Slot called when the number of bins to rebin to is changed */
-void DimensionSliceWidget::spinBinsChanged()
-{
+void DimensionSliceWidget::spinBinsChanged() {
   emit changedNumBins(m_dimIndex, this->getNumBins());
 }
-
 }
 }
diff --git a/MantidQt/SliceViewer/src/EllipsoidPlaneSliceCalculator.cpp b/MantidQt/SliceViewer/src/EllipsoidPlaneSliceCalculator.cpp
index e1dd6c99c61b75acbb223882f25d952474968933..533633983eb6f725f515cf420eea5aff59088b35 100644
--- a/MantidQt/SliceViewer/src/EllipsoidPlaneSliceCalculator.cpp
+++ b/MantidQt/SliceViewer/src/EllipsoidPlaneSliceCalculator.cpp
@@ -79,8 +79,7 @@
  *
  */
 
-namespace
-{
+namespace {
 
 /**
  * Calcualtes the origin of the ellipse.  The originis defined by -A^(-1)*B/2.
@@ -92,30 +91,28 @@ namespace
  */
 Mantid::Kernel::V3D getOrigin(Mantid::Kernel::DblMatrix AInverse,
                               Mantid::Kernel::DblMatrix B,
-                              Mantid::Kernel::V3D originEllipsoid, double zVal)
-{
-    const auto multiplied = AInverse * B;
-
-    // Apply the -0.5 factor and shift back into the ellipsoid frame
-    const auto x = -0.5 * multiplied[0][0] + originEllipsoid.X();
-    const auto y = -0.5 * multiplied[1][0] + originEllipsoid.Y();
-    const auto z = zVal + originEllipsoid.Z();
-    return Mantid::Kernel::V3D(x, y, z);
+                              Mantid::Kernel::V3D originEllipsoid,
+                              double zVal) {
+  const auto multiplied = AInverse * B;
+
+  // Apply the -0.5 factor and shift back into the ellipsoid frame
+  const auto x = -0.5 * multiplied[0][0] + originEllipsoid.X();
+  const auto y = -0.5 * multiplied[1][0] + originEllipsoid.Y();
+  const auto z = zVal + originEllipsoid.Z();
+  return Mantid::Kernel::V3D(x, y, z);
 }
 
 struct EigenSystemEllipse {
-    EigenSystemEllipse(Mantid::Kernel::V2D majorAxis,
-                       Mantid::Kernel::V2D minorAxis, double majorRadius,
-                       double minorRadius)
-        : majorAxis(majorAxis), minorAxis(minorAxis), majorRadius(majorRadius),
-          minorRadius(minorRadius)
-    {
-    }
-
-    const Mantid::Kernel::V2D majorAxis;
-    const Mantid::Kernel::V2D minorAxis;
-    const double majorRadius;
-    const double minorRadius;
+  EigenSystemEllipse(Mantid::Kernel::V2D majorAxis,
+                     Mantid::Kernel::V2D minorAxis, double majorRadius,
+                     double minorRadius)
+      : majorAxis(majorAxis), minorAxis(minorAxis), majorRadius(majorRadius),
+        minorRadius(minorRadius) {}
+
+  const Mantid::Kernel::V2D majorAxis;
+  const Mantid::Kernel::V2D minorAxis;
+  const double majorRadius;
+  const double minorRadius;
 };
 
 /**
@@ -128,34 +125,33 @@ struct EigenSystemEllipse {
  *http://www.geometrictools.com/Documentation/InformationAboutEllipses.pdf.
  */
 std::pair<Mantid::Kernel::V2D, Mantid::Kernel::V2D>
-getEigenVectorsForEllipse(const Mantid::Kernel::DblMatrix &MM, double eigenValueMinor)
-{
-    auto isM00LargerThanM11 = MM[0][0] >= MM[1][1];
-
-    // Create minor axis
-    double minorX = 0.0;
-    double minorY = 1.0;
-    double norm = 1.0;
-    if (isM00LargerThanM11) {
-        minorX = eigenValueMinor - MM[1][1];
-        minorY = MM[0][1];
-        norm = std::sqrt(std::pow(minorX, 2) + std::pow(minorY, 2));
-    } else {
-        minorX = MM[0][1];
-        minorY = eigenValueMinor - MM[0][0];
-        norm = std::sqrt(std::pow(minorX, 2) + std::pow(minorY, 2));
-    }
-    minorX /= norm;
-    minorY /= norm;
-    Mantid::Kernel::V2D minorAxis(minorX, minorY);
-
-    // Set the major axis
-    Mantid::Kernel::V2D majorAxis(-minorAxis[1], minorAxis[0]);
-
-    return std::make_pair(majorAxis, minorAxis);
+getEigenVectorsForEllipse(const Mantid::Kernel::DblMatrix &MM,
+                          double eigenValueMinor) {
+  auto isM00LargerThanM11 = MM[0][0] >= MM[1][1];
+
+  // Create minor axis
+  double minorX = 0.0;
+  double minorY = 1.0;
+  double norm = 1.0;
+  if (isM00LargerThanM11) {
+    minorX = eigenValueMinor - MM[1][1];
+    minorY = MM[0][1];
+    norm = std::sqrt(std::pow(minorX, 2) + std::pow(minorY, 2));
+  } else {
+    minorX = MM[0][1];
+    minorY = eigenValueMinor - MM[0][0];
+    norm = std::sqrt(std::pow(minorX, 2) + std::pow(minorY, 2));
+  }
+  minorX /= norm;
+  minorY /= norm;
+  Mantid::Kernel::V2D minorAxis(minorX, minorY);
+
+  // Set the major axis
+  Mantid::Kernel::V2D majorAxis(-minorAxis[1], minorAxis[0]);
+
+  return std::make_pair(majorAxis, minorAxis);
 }
 
-
 /**
  * Calculates the Radii and the directions of th
  * @param A: the A matrix
@@ -168,41 +164,39 @@ getEigenVectorsForEllipse(const Mantid::Kernel::DblMatrix &MM, double eigenValue
 EigenSystemEllipse getAxesInformation(Mantid::Kernel::DblMatrix A,
                                       Mantid::Kernel::DblMatrix AInverse,
                                       Mantid::Kernel::DblMatrix B,
-                                      Mantid::Kernel::DblMatrix BT, double c)
-{
-    // Calculate the denominator: (Transpose[B]*A^(-1)*B/4 - (c-1))
-    const auto temp1 = AInverse * B;
-    const auto temp2 = BT * temp1;
-    const auto denominator = 0.25 * temp2[0][0] - c + 1;
-
-    // Calculate the MM matrix: A/(Transpose[B]*A^(-1)*B/4 - (c-1))
-    auto MM = A;
-    MM /= denominator;
-
-    // Calculate the Eigenvalues: since we are dealing with EVs of a
-    // 2x2, symmetric and positive semi-definite matrix we can
-    // just write down the result of the EV calculation and save time
-    // EV = (MM00 + MM11 +/- Sqrt[(MM00-M11)^2 + 4(MM01)^2])/2
-    const auto evPart1 = MM[0][0] + MM[1][1];
-    const auto evPart2 = std::sqrt(std::pow(MM[0][0] - MM[1][1], 2)
-                                   + 4 * std::pow(MM[0][1], 2));
-
-    const auto evMinorAxis = (evPart1 + evPart2) * 0.5;
-    const auto evMajorAxis = (evPart1 - evPart2) * 0.5;
-
-    auto eigenVectors = getEigenVectorsForEllipse(MM, evMinorAxis);
-
-    // Get the radii: they are just the squareroot of the inverse of teh EV
-    const auto radiusMinorAxis = 1 / std::sqrt(evMinorAxis);
-    const auto radiusMajorAxis = 1 / std::sqrt(evMajorAxis);
-
-    // Note that we don't have to perform any transformations on the radius, as
-    // they will not be affected by a translation
-    return EigenSystemEllipse(eigenVectors.first, eigenVectors.second,
-                              radiusMajorAxis, radiusMinorAxis);
+                                      Mantid::Kernel::DblMatrix BT, double c) {
+  // Calculate the denominator: (Transpose[B]*A^(-1)*B/4 - (c-1))
+  const auto temp1 = AInverse * B;
+  const auto temp2 = BT * temp1;
+  const auto denominator = 0.25 * temp2[0][0] - c + 1;
+
+  // Calculate the MM matrix: A/(Transpose[B]*A^(-1)*B/4 - (c-1))
+  auto MM = A;
+  MM /= denominator;
+
+  // Calculate the Eigenvalues: since we are dealing with EVs of a
+  // 2x2, symmetric and positive semi-definite matrix we can
+  // just write down the result of the EV calculation and save time
+  // EV = (MM00 + MM11 +/- Sqrt[(MM00-M11)^2 + 4(MM01)^2])/2
+  const auto evPart1 = MM[0][0] + MM[1][1];
+  const auto evPart2 =
+      std::sqrt(std::pow(MM[0][0] - MM[1][1], 2) + 4 * std::pow(MM[0][1], 2));
+
+  const auto evMinorAxis = (evPart1 + evPart2) * 0.5;
+  const auto evMajorAxis = (evPart1 - evPart2) * 0.5;
+
+  auto eigenVectors = getEigenVectorsForEllipse(MM, evMinorAxis);
+
+  // Get the radii: they are just the squareroot of the inverse of teh EV
+  const auto radiusMinorAxis = 1 / std::sqrt(evMinorAxis);
+  const auto radiusMajorAxis = 1 / std::sqrt(evMajorAxis);
+
+  // Note that we don't have to perform any transformations on the radius, as
+  // they will not be affected by a translation
+  return EigenSystemEllipse(eigenVectors.first, eigenVectors.second,
+                            radiusMajorAxis, radiusMinorAxis);
 }
 
-
 /**
  * Angle which is required to rotate an axis aligned-ellipse (major axis along
  * x)
@@ -216,41 +210,36 @@ EigenSystemEllipse getAxesInformation(Mantid::Kernel::DblMatrix A,
  * calculate the eigenvectors and get the angle from the components of the
  *eigenvectors.
  */
-double getAngle(Mantid::Kernel::V2D majorAxis)
-{
-    return std::atan2(majorAxis.Y(), majorAxis.X());
+double getAngle(Mantid::Kernel::V2D majorAxis) {
+  return std::atan2(majorAxis.Y(), majorAxis.X());
 }
 
-bool isBetweenEndpoints(double endpoint1, double endpoint2, double z)
-{
-    const auto isBetween1And2 = (endpoint1 < z) && (z < endpoint2);
-    const auto isBetween2And1 = (endpoint2 < z) && (z < endpoint1);
+bool isBetweenEndpoints(double endpoint1, double endpoint2, double z) {
+  const auto isBetween1And2 = (endpoint1 < z) && (z < endpoint2);
+  const auto isBetween2And1 = (endpoint2 < z) && (z < endpoint1);
 
-    return isBetween1And2 || isBetween2And1;
+  return isBetween1And2 || isBetween2And1;
 }
 }
 
-namespace Mantid
-{
-namespace SliceViewer
-{
+namespace Mantid {
+namespace SliceViewer {
 
 SliceEllipseInfo EllipsoidPlaneSliceCalculator::getSlicePlaneInfo(
     std::vector<Mantid::Kernel::V3D> directions, std::vector<double> radii,
-    Mantid::Kernel::V3D originEllipsoid, double zPlane) const
-{
-    // Setup the Ellipsoid Matrix
-    auto m = createEllipsoidMatrixInXYZFrame(directions, radii);
-
-    auto isEllipsoid = checkIfIsEllipse(m);
-
-    if (isEllipsoid) {
-        return getSolutionForEllipsoid(m, zPlane, originEllipsoid);
-    } else {
-        throw std::runtime_error("EllipsoidPlaneSliceCalcualtor: The peak does "
-                                 "not seem to create an elliptical or "
-                                 "spherical cut.");
-    }
+    Mantid::Kernel::V3D originEllipsoid, double zPlane) const {
+  // Setup the Ellipsoid Matrix
+  auto m = createEllipsoidMatrixInXYZFrame(directions, radii);
+
+  auto isEllipsoid = checkIfIsEllipse(m);
+
+  if (isEllipsoid) {
+    return getSolutionForEllipsoid(m, zPlane, originEllipsoid);
+  } else {
+    throw std::runtime_error("EllipsoidPlaneSliceCalcualtor: The peak does "
+                             "not seem to create an elliptical or "
+                             "spherical cut.");
+  }
 }
 
 /**
@@ -260,10 +249,9 @@ SliceEllipseInfo EllipsoidPlaneSliceCalculator::getSlicePlaneInfo(
  * @return true if we are dealing with a true ellipsoid
  */
 bool EllipsoidPlaneSliceCalculator::checkIfIsEllipse(
-    const Kernel::Matrix<double> &m) const
-{
-    auto isEllipse = (m[0][0] * m[1][1] - std::pow(m[0][1], 2)) > 0;
-    return isEllipse;
+    const Kernel::Matrix<double> &m) const {
+  auto isEllipse = (m[0][0] * m[1][1] - std::pow(m[0][1], 2)) > 0;
+  return isEllipse;
 }
 
 /**
@@ -272,67 +260,65 @@ bool EllipsoidPlaneSliceCalculator::checkIfIsEllipse(
  * @return true if we are dealing with circle
  */
 bool EllipsoidPlaneSliceCalculator::checkIfIsCircle(
-    const Mantid::Kernel::Matrix<double> &m) const
-{
-    auto isM00EqualM11 = Mantid::SliceViewer::almost_equal(m[0][0], m[1][1]);
-    auto isM01Zero = Mantid::SliceViewer::almost_equal(m[0][1], 0.0);
-    return isM00EqualM11 && isM01Zero;
+    const Mantid::Kernel::Matrix<double> &m) const {
+  auto isM00EqualM11 = Mantid::SliceViewer::almost_equal(m[0][0], m[1][1]);
+  auto isM01Zero = Mantid::SliceViewer::almost_equal(m[0][1], 0.0);
+  return isM00EqualM11 && isM01Zero;
 }
 
 SliceEllipseInfo EllipsoidPlaneSliceCalculator::getSolutionForEllipsoid(
     const Kernel::Matrix<double> &m, double zPlane,
-    Mantid::Kernel::V3D originEllipsoid) const
-{
-    // Shift the z value into a suitable frame
-    const double z = zPlane - originEllipsoid.Z();
-
-    // Setup the A matrix
-    Mantid::Kernel::DblMatrix A;
-    A.setMem(2, 2);
-    const std::vector<double> ARow0 = {m[0][0], m[0][1]};
-    const std::vector<double> ARow1 = {m[0][1], m[1][1]};
-    A.setRow(0, ARow0);
-    A.setRow(1, ARow1);
-
-    // Setup the inverse Matrix of A
-    Mantid::Kernel::DblMatrix AInverse;
-    const double detA = A.determinant();
-    AInverse.setMem(2, 2);
-    const std::vector<double> AInverseRow0 = {m[1][1] / detA, -m[0][1] / detA};
-    const std::vector<double> AInverseRow1 = {-m[0][1] / detA, m[0][0] / detA};
-    AInverse.setRow(0, AInverseRow0);
-    AInverse.setRow(1, AInverseRow1);
-
-    // Setup the B vector
-    Mantid::Kernel::DblMatrix B;
-    std::vector<double> BColumn = {m[0][2], m[1][2]};
-    B.setMem(2, 1);
-    B.setColumn(0, BColumn);
-    B *= 2 * z;
-
-    // Setip the Transpose B vector
-    Mantid::Kernel::DblMatrix BT;
-    std::vector<double> BTRow = {m[0][2], m[1][2]};
-    BT.setMem(1, 2);
-    BT.setRow(0, BTRow);
-    BT *= 2 * z;
-
-    // Setup the C factor
-    const double c = m[2][2] * std::pow(z, 2);
-
-    // Get the origin
-    const auto origin = getOrigin(AInverse, B, originEllipsoid, z);
-
-    // Get the radii + directions
-    const auto eigenSystem = getAxesInformation(A, AInverse, B, BT, c);
-
-    // Get angle. If we have a circle then the angle is 0 (we want to avoid a
-    // divergence here)
-    const auto isCircle = checkIfIsCircle(m);
-    const double angle = isCircle ? 0.0 : getAngle(eigenSystem.majorAxis);
-
-    return SliceEllipseInfo(origin, eigenSystem.majorRadius,
-                            eigenSystem.minorRadius, angle);
+    Mantid::Kernel::V3D originEllipsoid) const {
+  // Shift the z value into a suitable frame
+  const double z = zPlane - originEllipsoid.Z();
+
+  // Setup the A matrix
+  Mantid::Kernel::DblMatrix A;
+  A.setMem(2, 2);
+  const std::vector<double> ARow0 = {m[0][0], m[0][1]};
+  const std::vector<double> ARow1 = {m[0][1], m[1][1]};
+  A.setRow(0, ARow0);
+  A.setRow(1, ARow1);
+
+  // Setup the inverse Matrix of A
+  Mantid::Kernel::DblMatrix AInverse;
+  const double detA = A.determinant();
+  AInverse.setMem(2, 2);
+  const std::vector<double> AInverseRow0 = {m[1][1] / detA, -m[0][1] / detA};
+  const std::vector<double> AInverseRow1 = {-m[0][1] / detA, m[0][0] / detA};
+  AInverse.setRow(0, AInverseRow0);
+  AInverse.setRow(1, AInverseRow1);
+
+  // Setup the B vector
+  Mantid::Kernel::DblMatrix B;
+  std::vector<double> BColumn = {m[0][2], m[1][2]};
+  B.setMem(2, 1);
+  B.setColumn(0, BColumn);
+  B *= 2 * z;
+
+  // Setip the Transpose B vector
+  Mantid::Kernel::DblMatrix BT;
+  std::vector<double> BTRow = {m[0][2], m[1][2]};
+  BT.setMem(1, 2);
+  BT.setRow(0, BTRow);
+  BT *= 2 * z;
+
+  // Setup the C factor
+  const double c = m[2][2] * std::pow(z, 2);
+
+  // Get the origin
+  const auto origin = getOrigin(AInverse, B, originEllipsoid, z);
+
+  // Get the radii + directions
+  const auto eigenSystem = getAxesInformation(A, AInverse, B, BT, c);
+
+  // Get angle. If we have a circle then the angle is 0 (we want to avoid a
+  // divergence here)
+  const auto isCircle = checkIfIsCircle(m);
+  const double angle = isCircle ? 0.0 : getAngle(eigenSystem.majorAxis);
+
+  return SliceEllipseInfo(origin, eigenSystem.majorRadius,
+                          eigenSystem.minorRadius, angle);
 }
 
 /**
@@ -362,42 +348,41 @@ SliceEllipseInfo EllipsoidPlaneSliceCalculator::getSolutionForEllipsoid(
  */
 Mantid::Kernel::Matrix<double>
 createEllipsoidMatrixInXYZFrame(std::vector<Mantid::Kernel::V3D> directions,
-                                std::vector<double> radii)
-{
-    // Setup the transform matrix from the xyz system to the eigen vector
-    // system, ie the directions
-    auto vec0 = std::vector<double>(directions[0]);
-    auto vec1 = std::vector<double>(directions[1]);
-    auto vec2 = std::vector<double>(directions[2]);
-
-    Mantid::Kernel::Matrix<double> s;
-    Mantid::Kernel::Matrix<double> sTransposed;
-
-    s.setMem(3, 3);
-    sTransposed.setMem(3, 3);
-
-    // The eigenvector is the column of the transformation matrix
-    s.setColumn(0, vec0);
-    s.setColumn(1, vec1);
-    s.setColumn(2, vec2);
-
-    sTransposed.setRow(0, vec0);
-    sTransposed.setRow(1, vec1);
-    sTransposed.setRow(2, vec2);
-
-    // Setup the ellipsoid matrix in the eigenvector system, ie a unit matrix
-    // with 1/ri^2 on the diagonal
-    Mantid::Kernel::Matrix<double> e;
-    e.setMem(3, 3);
-    std::vector<double> e0 = {1 / pow(radii[0], 2), 0.0, 0.0};
-    std::vector<double> e1 = {0.0, 1 / pow(radii[1], 2), 0.0};
-    std::vector<double> e2 = {0.0, 0.0, 1 / pow(radii[2], 2)};
-
-    e.setRow(0, e0);
-    e.setRow(1, e1);
-    e.setRow(2, e2);
-    // Now mulitply s*e*Transpose[s]
-    return s * e * sTransposed;
+                                std::vector<double> radii) {
+  // Setup the transform matrix from the xyz system to the eigen vector
+  // system, ie the directions
+  auto vec0 = std::vector<double>(directions[0]);
+  auto vec1 = std::vector<double>(directions[1]);
+  auto vec2 = std::vector<double>(directions[2]);
+
+  Mantid::Kernel::Matrix<double> s;
+  Mantid::Kernel::Matrix<double> sTransposed;
+
+  s.setMem(3, 3);
+  sTransposed.setMem(3, 3);
+
+  // The eigenvector is the column of the transformation matrix
+  s.setColumn(0, vec0);
+  s.setColumn(1, vec1);
+  s.setColumn(2, vec2);
+
+  sTransposed.setRow(0, vec0);
+  sTransposed.setRow(1, vec1);
+  sTransposed.setRow(2, vec2);
+
+  // Setup the ellipsoid matrix in the eigenvector system, ie a unit matrix
+  // with 1/ri^2 on the diagonal
+  Mantid::Kernel::Matrix<double> e;
+  e.setMem(3, 3);
+  std::vector<double> e0 = {1 / pow(radii[0], 2), 0.0, 0.0};
+  std::vector<double> e1 = {0.0, 1 / pow(radii[1], 2), 0.0};
+  std::vector<double> e2 = {0.0, 0.0, 1 / pow(radii[2], 2)};
+
+  e.setRow(0, e0);
+  e.setRow(1, e1);
+  e.setRow(2, e2);
+  // Now mulitply s*e*Transpose[s]
+  return s * e * sTransposed;
 }
 
 /**
@@ -410,27 +395,27 @@ createEllipsoidMatrixInXYZFrame(std::vector<Mantid::Kernel::V3D> directions,
  */
 bool checkIfCutExists(const std::vector<Mantid::Kernel::V3D> &directions,
                       const std::vector<double> &radii,
-                      const Mantid::Kernel::V3D &originEllipsoid, double zPlane)
-{
-    // Translate into ellipsoid
-    const double z = zPlane - originEllipsoid.Z();
-
-    bool hasCut = false;
-    // For each axis check if the z point is between the z values of the
-    // axis endpoints
-    int counter = 0;
-    for (const auto &direction : directions) {
-        const auto endpoint1 = direction[2] * radii[counter];
-        const auto endpoint2 = -1 * direction[2] * radii[counter];
-
-        if (isBetweenEndpoints(endpoint1, endpoint2, z)) {
-            hasCut = true;
-            break;
-        }
-        ++counter;
+                      const Mantid::Kernel::V3D &originEllipsoid,
+                      double zPlane) {
+  // Translate into ellipsoid
+  const double z = zPlane - originEllipsoid.Z();
+
+  bool hasCut = false;
+  // For each axis check if the z point is between the z values of the
+  // axis endpoints
+  int counter = 0;
+  for (const auto &direction : directions) {
+    const auto endpoint1 = direction[2] * radii[counter];
+    const auto endpoint2 = -1 * direction[2] * radii[counter];
+
+    if (isBetweenEndpoints(endpoint1, endpoint2, z)) {
+      hasCut = true;
+      break;
     }
+    ++counter;
+  }
 
-    return hasCut;
+  return hasCut;
 }
 
 /**
@@ -441,57 +426,54 @@ bool checkIfCutExists(const std::vector<Mantid::Kernel::V3D> &directions,
  */
 std::vector<double>
 getProjectionLengths(const std::vector<Mantid::Kernel::V3D> &directions,
-                     std::vector<double> radii)
-{
-    std::vector<Mantid::Kernel::V3D> directionsScaled;
-
-    for (int index = 0; index < 3; ++index) {
-        directionsScaled.emplace_back(directions[index] * radii[index]);
-    }
-
-    // We group the magnitudes of the x, y and z components
-    std::vector<double> x
-        = {std::abs(directionsScaled[0].X()), std::abs(directionsScaled[1].X()),
-           std::abs(directionsScaled[2].X())};
-    std::vector<double> y
-        = {std::abs(directionsScaled[0].Y()), std::abs(directionsScaled[1].Y()),
-           std::abs(directionsScaled[2].Y())};
-    std::vector<double> z
-        = {std::abs(directionsScaled[0].Z()), std::abs(directionsScaled[1].Z()),
-           std::abs(directionsScaled[2].Z())};
-
-    // Pick the largest element for each component
-    auto xMax = std::max_element(std::begin(x), std::end(x));
-    auto yMax = std::max_element(std::begin(y), std::end(y));
-    auto zMax = std::max_element(std::begin(z), std::end(z));
-
-    return std::vector<double>{*xMax, *yMax, *zMax};
+                     std::vector<double> radii) {
+  std::vector<Mantid::Kernel::V3D> directionsScaled;
+
+  for (int index = 0; index < 3; ++index) {
+    directionsScaled.emplace_back(directions[index] * radii[index]);
+  }
+
+  // We group the magnitudes of the x, y and z components
+  std::vector<double> x = {std::abs(directionsScaled[0].X()),
+                           std::abs(directionsScaled[1].X()),
+                           std::abs(directionsScaled[2].X())};
+  std::vector<double> y = {std::abs(directionsScaled[0].Y()),
+                           std::abs(directionsScaled[1].Y()),
+                           std::abs(directionsScaled[2].Y())};
+  std::vector<double> z = {std::abs(directionsScaled[0].Z()),
+                           std::abs(directionsScaled[1].Z()),
+                           std::abs(directionsScaled[2].Z())};
+
+  // Pick the largest element for each component
+  auto xMax = std::max_element(std::begin(x), std::end(x));
+  auto yMax = std::max_element(std::begin(y), std::end(y));
+  auto zMax = std::max_element(std::begin(z), std::end(z));
+
+  return std::vector<double>{*xMax, *yMax, *zMax};
 }
 
 MantidQt::SliceViewer::PeakBoundingBox getPeakBoundingBoxForEllipsoid(
     const std::vector<Mantid::Kernel::V3D> &directions,
     const std::vector<double> &radii,
-    const Mantid::Kernel::V3D &originEllipsoid)
-{
-    // Get the length of largest projection onto x,y,z
-    auto projectionLengths = getProjectionLengths(directions, radii);
-
-    // Corners
-    const double leftValue = originEllipsoid.X() - projectionLengths[0];
-    const double rightValue = originEllipsoid.X() + projectionLengths[0];
-    const double bottomValue = originEllipsoid.Y() - projectionLengths[1];
-    const double topValue = originEllipsoid.Y() + projectionLengths[1];
-
-    using namespace MantidQt::SliceViewer;
-
-    Left left(leftValue);
-    Right right(rightValue);
-    Bottom bottom(bottomValue);
-    Top top(topValue);
-    SlicePoint slicePoint(originEllipsoid.Z());
-
-    return PeakBoundingBox(left, right, top, bottom, slicePoint);
-}
+    const Mantid::Kernel::V3D &originEllipsoid) {
+  // Get the length of largest projection onto x,y,z
+  auto projectionLengths = getProjectionLengths(directions, radii);
 
+  // Corners
+  const double leftValue = originEllipsoid.X() - projectionLengths[0];
+  const double rightValue = originEllipsoid.X() + projectionLengths[0];
+  const double bottomValue = originEllipsoid.Y() - projectionLengths[1];
+  const double topValue = originEllipsoid.Y() + projectionLengths[1];
+
+  using namespace MantidQt::SliceViewer;
+
+  Left left(leftValue);
+  Right right(rightValue);
+  Bottom bottom(bottomValue);
+  Top top(topValue);
+  SlicePoint slicePoint(originEllipsoid.Z());
+
+  return PeakBoundingBox(left, right, top, bottom, slicePoint);
+}
 }
 }
diff --git a/MantidQt/SliceViewer/src/LineOverlay.cpp b/MantidQt/SliceViewer/src/LineOverlay.cpp
index 4a172e3a2b9abaf003ac506deb8d8d4bb82aef08..149aeec9a5a4ae983e80f9b1bc35639a8aaa0f17 100644
--- a/MantidQt/SliceViewer/src/LineOverlay.cpp
+++ b/MantidQt/SliceViewer/src/LineOverlay.cpp
@@ -8,633 +8,554 @@
 
 using namespace Mantid::Kernel;
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Constructor
-   */
-  LineOverlay::LineOverlay(QwtPlot * plot, QWidget * parent)
-  : QWidget( parent ),
-    m_plot(plot),
-    m_snapEnabled(false),
-    m_snapX(0.1), m_snapY(0.1), m_snapLength(0),
-    m_shown(true), m_showHandles(true), m_showLine(true),
-    m_angleSnapMode(false), m_angleSnap(45)
-  {
-    m_creation = true; // Will create with the mouse
-    m_rightButton = false;
-    m_dragHandle = HandleNone;
-
-    m_pointA = QPointF(0.0, 0.0);
-    m_pointB = QPointF(1.0, 1.0);
-    m_width = 0.1;
-    //setAttribute(Qt::WA_TransparentForMouseEvents);
-    // We need mouse events all the time
-    setMouseTracking(true);
-    //setAttribute(Qt::WA_TransparentForMouseEvents);
-    // Make sure mouse propagates
-    setAttribute(Qt::WA_NoMousePropagation, false);
-  }
-    
-  //----------------------------------------------------------------------------------------------
-  /** Destructor
-   */
-  LineOverlay::~LineOverlay()
-  {
-  }
-  
-  //----------------------------------------------------------------------------------------------
-  /** Reset the line. User will have to click to create it */
-  void LineOverlay::reset()
-  {
-    m_creation = true; // Will create with the mouse
-    m_rightButton = false;
-    m_dragHandle = HandleNone;
-    this->update();
-  }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Set point A's position
-   * @param pointA :: plot coordinates */
-  void LineOverlay::setPointA(QPointF pointA)
-  {
-    m_pointA = pointA;
-    this->update(); //repaint
-    emit lineChanging(m_pointA, m_pointB, m_width);
-  }
-
-  /** Set point B's position
-   * @param pointB :: plot coordinates */
-  void LineOverlay::setPointB(QPointF pointB)
-  {
-    m_pointB = pointB;
-    this->update(); //repaint
-    emit lineChanging(m_pointA, m_pointB, m_width);
-  }
-
-  /** Set the width of integration
-   * @param width :: in plot coordinates */
-  void LineOverlay::setWidth(double width)
-  {
-    m_width = width;
-    this->update(); //repaint
-    emit lineChanging(m_pointA, m_pointB, m_width);
-  }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Set the snap-to-grid spacing in the X direction.
-   * @param spacing :: spacing */
-  void LineOverlay::setSnapX(double spacing)
-  {
-    m_snapX = spacing;
-  }
-
-  /** Set the snap-to-grid spacing in the Y direction.
-   * @param spacing :: spacing */
-  void LineOverlay::setSnapY(double spacing)
-  {
-    m_snapY = spacing;
+namespace MantidQt {
+namespace SliceViewer {
+
+//----------------------------------------------------------------------------------------------
+/** Constructor
+ */
+LineOverlay::LineOverlay(QwtPlot *plot, QWidget *parent)
+    : QWidget(parent), m_plot(plot), m_snapEnabled(false), m_snapX(0.1),
+      m_snapY(0.1), m_snapLength(0), m_shown(true), m_showHandles(true),
+      m_showLine(true), m_angleSnapMode(false), m_angleSnap(45) {
+  m_creation = true; // Will create with the mouse
+  m_rightButton = false;
+  m_dragHandle = HandleNone;
+
+  m_pointA = QPointF(0.0, 0.0);
+  m_pointB = QPointF(1.0, 1.0);
+  m_width = 0.1;
+  // setAttribute(Qt::WA_TransparentForMouseEvents);
+  // We need mouse events all the time
+  setMouseTracking(true);
+  // setAttribute(Qt::WA_TransparentForMouseEvents);
+  // Make sure mouse propagates
+  setAttribute(Qt::WA_NoMousePropagation, false);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Destructor
+ */
+LineOverlay::~LineOverlay() {}
+
+//----------------------------------------------------------------------------------------------
+/** Reset the line. User will have to click to create it */
+void LineOverlay::reset() {
+  m_creation = true; // Will create with the mouse
+  m_rightButton = false;
+  m_dragHandle = HandleNone;
+  this->update();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Set point A's position
+ * @param pointA :: plot coordinates */
+void LineOverlay::setPointA(QPointF pointA) {
+  m_pointA = pointA;
+  this->update(); // repaint
+  emit lineChanging(m_pointA, m_pointB, m_width);
+}
+
+/** Set point B's position
+ * @param pointB :: plot coordinates */
+void LineOverlay::setPointB(QPointF pointB) {
+  m_pointB = pointB;
+  this->update(); // repaint
+  emit lineChanging(m_pointA, m_pointB, m_width);
+}
+
+/** Set the width of integration
+ * @param width :: in plot coordinates */
+void LineOverlay::setWidth(double width) {
+  m_width = width;
+  this->update(); // repaint
+  emit lineChanging(m_pointA, m_pointB, m_width);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Set the snap-to-grid spacing in the X direction.
+ * @param spacing :: spacing */
+void LineOverlay::setSnapX(double spacing) { m_snapX = spacing; }
+
+/** Set the snap-to-grid spacing in the Y direction.
+ * @param spacing :: spacing */
+void LineOverlay::setSnapY(double spacing) { m_snapY = spacing; }
+
+/** Set the snap-to-grid spacing in both directions.
+ * @param spacing :: spacing */
+void LineOverlay::setSnap(double spacing) {
+  m_snapX = spacing;
+  m_snapY = spacing;
+}
+
+/** Set the snap-to-grid spacing in the Y direction.
+ * @param enabled :: enable spacing */
+void LineOverlay::setSnapEnabled(bool enabled) { m_snapEnabled = enabled; }
+
+/** Set the snap-to-line-length spacing
+ * @param spacing :: spacing */
+void LineOverlay::setSnapLength(double spacing) { m_snapLength = spacing; }
+
+/** Sets whether any of the control is visible
+ * @param shown :: if false, the the control is not drawng */
+void LineOverlay::setShown(bool shown) { m_shown = shown; }
+
+/** Sets whether to show the mouse handles
+ * @param shown :: if false, the mouse handles are invisible */
+void LineOverlay::setShowHandles(bool shown) { m_showHandles = shown; }
+
+/** Sets whether to show the central line
+ * @param shown :: if false, the central line is invisible */
+void LineOverlay::setShowLine(bool shown) { m_showLine = shown; }
+
+/** Sets whether we are in "creation" mode
+ * For use by python directly specifying the position
+ *
+ * @param creation :: True for creation mode.
+ */
+void LineOverlay::setCreationMode(bool creation) {
+  m_creation = creation;
+  this->update();
+}
+
+//----------------------------------------------------------------------------------------------
+/** Turn angle snap on or off
+ * @param angleSnap :: true for always angle snap. */
+void LineOverlay::setAngleSnapMode(bool angleSnap) {
+  m_angleSnapMode = angleSnap;
+}
+
+/** Sets the angle increments to snap to.
+ * @param snapDegrees :: snap amount, in degrees */
+void LineOverlay::setAngleSnap(double snapDegrees) {
+  m_angleSnap = snapDegrees;
+}
+
+//----------------------------------------------------------------------------------------------
+/// @return point A's position in plot coordinates
+const QPointF &LineOverlay::getPointA() const { return m_pointA; }
+
+/// @return point B's position in plot coordinates
+const QPointF &LineOverlay::getPointB() const { return m_pointB; }
+
+/// @return width of the line in plot coordinates
+double LineOverlay::getWidth() const { return m_width; }
+
+//----------------------------------------------------------------------------------------------
+/// Return the recommended size of the widget
+QSize LineOverlay::sizeHint() const {
+  // TODO: Is there a smarter way to find the right size?
+  return QSize(20000, 20000);
+  // Always as big as the canvas
+  // return m_plot->canvas()->size();
+}
+
+QSize LineOverlay::size() const { return m_plot->canvas()->size(); }
+int LineOverlay::height() const { return m_plot->canvas()->height(); }
+int LineOverlay::width() const { return m_plot->canvas()->width(); }
+
+//----------------------------------------------------------------------------------------------
+/** Tranform from plot coordinates to pixel coordinates
+ * @param coords :: coordinate point in plot coordinates
+ * @return pixel coordinates */
+QPoint LineOverlay::transform(QPointF coords) const {
+  int xA = m_plot->transform(QwtPlot::xBottom, coords.x());
+  int yA = m_plot->transform(QwtPlot::yLeft, coords.y());
+  return QPoint(xA, yA);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Inverse transform: from pixels to plot coords
+ * @param pixels :: location in pixels
+ * @return plot coordinates (float)   */
+QPointF LineOverlay::invTransform(QPoint pixels) const {
+  double xA = m_plot->invTransform(QwtPlot::xBottom, pixels.x());
+  double yA = m_plot->invTransform(QwtPlot::yLeft, pixels.y());
+  return QPointF(xA, yA);
+}
+
+//----------------------------------------------------------------------------------------------
+/** Snap a point to the grid (if enabled)
+ * @param original :: original point
+ * @return snapped to grid in either or both dimensions  */
+QPointF LineOverlay::snap(QPointF original) const {
+  if (!m_snapEnabled)
+    return original;
+  else {
+    QPointF out = original;
+    // Snap to grid
+    if (m_snapX > 0)
+      out.setX(Utils::rounddbl(out.x() / m_snapX) * m_snapX);
+    if (m_snapY > 0)
+      out.setY(Utils::rounddbl(out.y() / m_snapY) * m_snapY);
+    return out;
   }
-
-  /** Set the snap-to-grid spacing in both directions.
-   * @param spacing :: spacing */
-  void LineOverlay::setSnap(double spacing)
-  {
-    m_snapX = spacing;
-    m_snapY = spacing;
-  }
-
-  /** Set the snap-to-grid spacing in the Y direction.
-   * @param enabled :: enable spacing */
-  void LineOverlay::setSnapEnabled(bool enabled)
-  {
-    m_snapEnabled = enabled;
-  }
-
-  /** Set the snap-to-line-length spacing
-   * @param spacing :: spacing */
-  void LineOverlay::setSnapLength(double spacing)
-  {
-    m_snapLength = spacing;
-  }
-
-
-  /** Sets whether any of the control is visible
-   * @param shown :: if false, the the control is not drawng */
-  void LineOverlay::setShown(bool shown)
-  {
-    m_shown = shown;
-  }
-
-  /** Sets whether to show the mouse handles
-   * @param shown :: if false, the mouse handles are invisible */
-  void LineOverlay::setShowHandles(bool shown)
-  {
-    m_showHandles = shown;
+}
+
+//----------------------------------------------------------------------------------------------
+/** Draw a handle (for dragging) at the given plot coordinates */
+QRect LineOverlay::drawHandle(QPainter &painter, QPointF coords, QColor brush) {
+  int size = 8;
+  QPoint center = transform(coords);
+  QRect marker(center.x() - size / 2, center.y() - size / 2, size, size);
+  if (this->m_showHandles) {
+    painter.setPen(QColor(255, 0, 0));
+    painter.setBrush(brush);
+    painter.drawRect(marker);
   }
-
-  /** Sets whether to show the central line
-   * @param shown :: if false, the central line is invisible */
-  void LineOverlay::setShowLine(bool shown)
-  {
-    m_showLine = shown;
+  return marker;
+}
+
+//----------------------------------------------------------------------------------------------
+/// Paint the overlay
+void LineOverlay::paintEvent(QPaintEvent * /*event*/) {
+  // Don't paint until created
+  // Also, don't paint while right-click dragging (panning) the underlying pic
+  if (m_creation || m_rightButton || !m_shown)
+    return;
+
+  QPainter painter(this);
+  //    int r = rand() % 255;
+  //    int g = rand() % 255;
+  //    int b = rand() % 255;
+
+  //    painter.setBrush(QBrush(QColor(r,g,b)));
+
+  QPointF diff = m_pointB - m_pointA;
+  // Angle of the "width" perpendicular to the line
+  double angle = atan2(diff.y(), diff.x()) + M_PI / 2.0;
+  QPointF widthOffset(m_width * cos(angle), m_width * sin(angle));
+
+  // Rectangle with a rotation
+  QPointF pA1 = m_pointA + widthOffset;
+  QPointF pA2 = m_pointA - widthOffset;
+  QPointF pB1 = m_pointB + widthOffset;
+  QPointF pB2 = m_pointB - widthOffset;
+
+  QPen boxPenLight(QColor(255, 255, 255, 200));
+  QPen boxPenDark(QColor(0, 0, 0, 200));
+  QPen centerPen(QColor(192, 192, 192, 128));
+
+  // Special XOR pixel drawing
+  // painter.setCompositionMode( QPainter::RasterOp_SourceXorDestination ); //
+  // RHEL5 has an old version of QT?
+
+  boxPenLight.setDashPattern(QVector<qreal>() << 5 << 5);
+  boxPenDark.setDashPattern(QVector<qreal>() << 0 << 5 << 5 << 0);
+
+  // --- Draw the box ---
+  boxPenLight.setWidthF(1.0);
+  boxPenDark.setWidthF(1.0);
+
+  //    QPoint points[4] = {transform(pA1), transform(pB1), transform(pB2),
+  //    transform(pA2)};
+  //    painter.drawPolygon(points, 4);
+
+  painter.setPen(boxPenLight);
+  painter.drawLine(transform(pA1), transform(pB1));
+  painter.drawLine(transform(pB1), transform(pB2));
+  painter.drawLine(transform(pA2), transform(pB2));
+  painter.drawLine(transform(pA2), transform(pA1));
+  painter.setPen(boxPenDark);
+  painter.drawLine(transform(pA1), transform(pB1));
+  painter.drawLine(transform(pB1), transform(pB2));
+  painter.drawLine(transform(pA2), transform(pB2));
+  painter.drawLine(transform(pA2), transform(pA1));
+
+  // Go back to normal drawing mode
+  painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
+
+  // --- Draw the central line ---
+  if (m_showLine) {
+    centerPen.setWidth(2);
+    centerPen.setCapStyle(Qt::FlatCap);
+    painter.setPen(centerPen);
+    painter.drawLine(transform(m_pointA), transform(m_pointB));
   }
 
-  /** Sets whether we are in "creation" mode
-   * For use by python directly specifying the position
-   *
-   * @param creation :: True for creation mode.
-   */
-  void LineOverlay::setCreationMode(bool creation)
-  {
-    m_creation = creation;
-    this->update();
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Turn angle snap on or off
-   * @param angleSnap :: true for always angle snap. */
-  void LineOverlay::setAngleSnapMode(bool angleSnap)
-  {
-    m_angleSnapMode = angleSnap;
-  }
-
-  /** Sets the angle increments to snap to.
-   * @param snapDegrees :: snap amount, in degrees */
-  void LineOverlay::setAngleSnap(double snapDegrees)
-  {
-    m_angleSnap = snapDegrees;
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /// @return point A's position in plot coordinates
-  const QPointF & LineOverlay::getPointA() const
-  { return m_pointA; }
-
-  /// @return point B's position in plot coordinates
-  const QPointF & LineOverlay::getPointB() const
-  { return m_pointB; }
-
-  /// @return width of the line in plot coordinates
-  double LineOverlay::getWidth() const
-  { return m_width; }
-
-
-  //----------------------------------------------------------------------------------------------
-  /// Return the recommended size of the widget
-  QSize LineOverlay::sizeHint() const
-  {
-    //TODO: Is there a smarter way to find the right size?
-    return QSize(20000, 20000);
-    // Always as big as the canvas
-    //return m_plot->canvas()->size();
-  }
-
-  QSize LineOverlay::size() const
-  { return m_plot->canvas()->size(); }
-  int LineOverlay::height() const
-  { return m_plot->canvas()->height(); }
-  int LineOverlay::width() const
-  { return m_plot->canvas()->width(); }
-
-
-  //----------------------------------------------------------------------------------------------
-  /** Tranform from plot coordinates to pixel coordinates
-   * @param coords :: coordinate point in plot coordinates
-   * @return pixel coordinates */
-  QPoint LineOverlay::transform(QPointF coords) const
-  {
-    int xA = m_plot->transform( QwtPlot::xBottom, coords.x() );
-    int yA = m_plot->transform( QwtPlot::yLeft, coords.y() );
-    return QPoint(xA, yA);
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Inverse transform: from pixels to plot coords
-   * @param pixels :: location in pixels
-   * @return plot coordinates (float)   */
-  QPointF LineOverlay::invTransform(QPoint pixels) const
-  {
-    double xA = m_plot->invTransform( QwtPlot::xBottom, pixels.x() );
-    double yA = m_plot->invTransform( QwtPlot::yLeft, pixels.y() );
-    return QPointF(xA, yA);
-  }
-
-  //----------------------------------------------------------------------------------------------
-  /** Snap a point to the grid (if enabled)
-   * @param original :: original point
-   * @return snapped to grid in either or both dimensions  */
-  QPointF LineOverlay::snap(QPointF original) const
-  {
-    if (!m_snapEnabled)
-      return original;
-    else
-    {
-      QPointF out = original;
-      // Snap to grid
-      if (m_snapX > 0)
-        out.setX( Utils::rounddbl(out.x()/m_snapX) * m_snapX);
-      if (m_snapY > 0)
-        out.setY( Utils::rounddbl(out.y()/m_snapY) * m_snapY);
-      return out;
+  // --- Draw and store the rects of the 4 handles ---
+  m_handles.clear();
+  m_handles.push_back(drawHandle(painter, m_pointA, QColor(0, 0, 0)));
+  m_handles.push_back(drawHandle(painter, m_pointB, QColor(255, 255, 255)));
+  m_handles.push_back(drawHandle(
+      painter, (m_pointA + m_pointB) / 2 + widthOffset, QColor(0, 255, 255)));
+  m_handles.push_back(drawHandle(
+      painter, (m_pointA + m_pointB) / 2 - widthOffset, QColor(0, 255, 255)));
+}
+
+//==============================================================================================
+//================================= MOUSE HANDLING
+//=============================================
+//==============================================================================================
+
+//-----------------------------------------------------------------------------------------------
+/** Return the handle ID over which the mouse is
+ * @param pos :: position in pixels of mouse */
+LineOverlay::eHandleID LineOverlay::mouseOverHandle(QPoint pos) {
+  for (int i = 0; i < m_handles.size(); i++) {
+    if (m_handles[i].contains(pos)) {
+      return eHandleID(i);
     }
   }
-
-  //----------------------------------------------------------------------------------------------
-  /** Draw a handle (for dragging) at the given plot coordinates */
-  QRect LineOverlay::drawHandle(QPainter & painter, QPointF coords, QColor brush)
-  {
-    int size = 8;
-    QPoint center = transform(coords);
-    QRect marker(center.x()-size/2, center.y()-size/2, size, size);
-    if (this->m_showHandles)
-    {
-      painter.setPen(QColor(255,0,0));
-      painter.setBrush(brush);
-      painter.drawRect(marker);
+  if (this->mouseOverCenter(pos))
+    return HandleCenter;
+  else
+    return HandleNone;
+}
+
+///@return true if value is between A and B. A can be < or > then B.
+bool isBetween(double value, double A, double B) {
+  if (B > A)
+    return (value >= A && value <= B);
+  else if (B < A)
+    return (value >= B && value <= A);
+  else
+    return (value == A);
+}
+
+/** Return true if the mouse is over the central line
+ * @param pos :: position in pixels of mouse */
+bool LineOverlay::mouseOverCenter(QPoint pos) {
+  // Mouse position in pixels
+  QPointF current = pos;
+  // Find the distance (in pixels) between the mouse and the center of the line
+  QPointF pixA = transform(m_pointA);
+  QPointF pixB = transform(m_pointB);
+  QPointF diff = pixB - pixA;
+  double distance = fabs(diff.x() * (current.y() - pixA.y()) -
+                         (current.x() - pixA.x()) * diff.y()) /
+                    sqrt(diff.x() * diff.x() + diff.y() * diff.y());
+
+  // Margin of 6 pixels, and must be between the 2 limits (if the limits are not
+  // the same)
+  bool retval = false;
+  if (distance < 7) {
+    retval = true;
+    if ((pixA.x() != pixB.x()) &&
+        (!isBetween(current.x(), pixA.x(), pixB.x()))) {
+      retval = false;
+    }
+    if ((pixA.y() != pixB.y()) &&
+        (!isBetween(current.y(), pixA.y(), pixB.y()))) {
+      retval = false;
     }
-    return marker;
   }
-
-  //----------------------------------------------------------------------------------------------
-  /// Paint the overlay
-  void LineOverlay::paintEvent(QPaintEvent * /*event*/)
-  {
-    // Don't paint until created
-    // Also, don't paint while right-click dragging (panning) the underlying pic
-    if (m_creation || m_rightButton || !m_shown)
-      return;
-
-    QPainter painter(this);
-//    int r = rand() % 255;
-//    int g = rand() % 255;
-//    int b = rand() % 255;
-
-//    painter.setBrush(QBrush(QColor(r,g,b)));
-
-    QPointF diff = m_pointB - m_pointA;
-    // Angle of the "width" perpendicular to the line
-    double angle = atan2(diff.y(), diff.x()) + M_PI / 2.0;
-    QPointF widthOffset( m_width * cos(angle), m_width * sin(angle) );
-
-    // Rectangle with a rotation
-    QPointF pA1 = m_pointA + widthOffset;
-    QPointF pA2 = m_pointA - widthOffset;
-    QPointF pB1 = m_pointB + widthOffset;
-    QPointF pB2 = m_pointB - widthOffset;
-
-
-    QPen boxPenLight(QColor(255,255,255, 200));
-    QPen boxPenDark(QColor(0,0,0, 200));
-    QPen centerPen(QColor(192,192,192, 128));
-
-    // Special XOR pixel drawing
-    //painter.setCompositionMode( QPainter::RasterOp_SourceXorDestination ); // RHEL5 has an old version of QT?
-
-    boxPenLight.setDashPattern(  QVector<qreal>() << 5 << 5  );
-    boxPenDark.setDashPattern(  QVector<qreal>() << 0 << 5 << 5 << 0 );
-
-    // --- Draw the box ---
-    boxPenLight.setWidthF(1.0);
-    boxPenDark.setWidthF(1.0);
-
-//    QPoint points[4] = {transform(pA1), transform(pB1), transform(pB2), transform(pA2)};
-//    painter.drawPolygon(points, 4);
-
-    painter.setPen(boxPenLight);
-    painter.drawLine(transform(pA1), transform(pB1));
-    painter.drawLine(transform(pB1), transform(pB2));
-    painter.drawLine(transform(pA2), transform(pB2));
-    painter.drawLine(transform(pA2), transform(pA1));
-    painter.setPen(boxPenDark);
-    painter.drawLine(transform(pA1), transform(pB1));
-    painter.drawLine(transform(pB1), transform(pB2));
-    painter.drawLine(transform(pA2), transform(pB2));
-    painter.drawLine(transform(pA2), transform(pA1));
-
-    // Go back to normal drawing mode
-    painter.setCompositionMode( QPainter::CompositionMode_SourceOver );
-
-    // --- Draw the central line ---
-    if (m_showLine)
-    {
-      centerPen.setWidth(2);
-      centerPen.setCapStyle(Qt::FlatCap);
-      painter.setPen(centerPen);
-      painter.drawLine(transform(m_pointA), transform(m_pointB));
+  return retval;
+}
+
+//-----------------------------------------------------------------------------------------------
+/** Handle the mouse move event when the line is being dragged
+ * @param event mouse event info */
+void LineOverlay::handleDrag(QMouseEvent *event) {
+  // Is the shift key pressed?
+  bool shiftPressed = (event->modifiers() & Qt::ShiftModifier);
+  // Currently dragging!
+  QPointF current = this->invTransform(event->pos());
+  QPointF currentSnap = this->snap(current);
+  QPointF diff = m_pointB - m_pointA;
+  QPointF dragAmount = current - this->m_dragStart;
+  dragAmount = snap(dragAmount);
+  double width = 0;
+
+  // Adjust the current mouse position if needed.
+  if ((m_snapLength > 0) || shiftPressed || m_angleSnapMode) {
+    // This is the distance between the fixed and dragged point
+    QPointF currentDiff;
+    if (m_dragHandle == HandleA)
+      currentDiff = current - m_pointB;
+    else if (m_dragHandle == HandleB)
+      currentDiff = current - m_pointA;
+
+    // calculate angle
+    double angle = atan2(currentDiff.y(), currentDiff.x());
+
+    // Round angle to closest 45 degrees, if in angle snap mode (shift pressed)
+    if (shiftPressed || m_angleSnapMode) {
+      if (m_angleSnap == 90.0) {
+        // special case for 90 snap (axis aligned snapping)
+        // use screen coords to determine snap angle
+        QPointF currentScreenDiff;
+        if (m_dragHandle == HandleA)
+          currentScreenDiff = event->pos() - transform(m_pointB);
+        else if (m_dragHandle == HandleB)
+          currentScreenDiff = event->pos() - transform(m_pointA);
+
+        // Limit angles to 90 based on screen coords, not data coords
+        //-y is because the screen y coords are inverted to the data coords
+        angle = atan2(-currentScreenDiff.y(), currentScreenDiff.x());
+      }
+      // convert snap angle to radians
+      double angleSnapRad = m_angleSnap / (180.0 / M_PI);
+      // round current angle to snap angle
+      angle = Utils::rounddbl(angle / angleSnapRad) * angleSnapRad;
     }
 
-    // --- Draw and store the rects of the 4 handles ---
-    m_handles.clear();
-    m_handles.push_back(drawHandle(painter, m_pointA, QColor(0,0,0) ));
-    m_handles.push_back(drawHandle(painter, m_pointB, QColor(255,255,255) ));
-    m_handles.push_back(drawHandle(painter, (m_pointA + m_pointB)/2 + widthOffset, QColor(0,255,255)) );
-    m_handles.push_back(drawHandle(painter, (m_pointA + m_pointB)/2 - widthOffset, QColor(0,255,255)) );
-  }
+    double length;
+    // for axis aligned angles just use respective distance for the length
+    if (fmod(angle, M_PI) == 0) {
+      length = fabs(currentDiff.x());
+    } else if (fmod(angle, M_PI) == M_PI / 2) {
+      length = fabs(currentDiff.y());
+    } else {
+      length = sqrt(currentDiff.x() * currentDiff.x() +
+                    currentDiff.y() * currentDiff.y());
+    }
 
+    // Round length to m_snapLength, if specified
+    if (m_snapLength > 0)
+      length = Utils::rounddbl(length / m_snapLength) * m_snapLength;
 
-  //==============================================================================================
-  //================================= MOUSE HANDLING =============================================
-  //==============================================================================================
-
-  //-----------------------------------------------------------------------------------------------
-  /** Return the handle ID over which the mouse is
-   * @param pos :: position in pixels of mouse */
-  LineOverlay::eHandleID LineOverlay::mouseOverHandle(QPoint pos)
-  {
-    for (int i=0; i < m_handles.size(); i++)
-    {
-      if (m_handles[i].contains(pos))
-      {
-        return eHandleID(i);
-      }
-    }
-    if (this->mouseOverCenter(pos))
-      return HandleCenter;
-    else
-      return HandleNone;
+    // Rebuild the mouse position
+    currentDiff = QPointF(cos(angle) * length, sin(angle) * length);
+    if (m_dragHandle == HandleA)
+      currentSnap = snap(m_pointB + currentDiff);
+    else if (m_dragHandle == HandleB)
+      currentSnap = snap(m_pointA + currentDiff);
   }
 
-  ///@return true if value is between A and B. A can be < or > then B.
-  bool isBetween(double value, double A, double B)
-  {
-    if (B > A)
-      return (value >= A && value <= B);
-    else if (B < A)
-      return (value >= B && value <= A);
-    else
-      return (value == A);
-  }
+  switch (m_dragHandle) {
+  case HandleA:
+    setPointA(currentSnap);
+    break;
+
+  case HandleB:
+    setPointB(currentSnap);
+    break;
+
+  case HandleWidthBottom:
+  case HandleWidthTop:
+    // Find the distance between the mouse and the line (see
+    // http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html )
+    width = fabs(diff.x() * (current.y() - m_pointA.y()) -
+                 (current.x() - m_pointA.x()) * diff.y()) /
+            sqrt(diff.x() * diff.x() + diff.y() * diff.y());
+    setWidth(width);
+    break;
+
+  case HandleCenter:
+    // Move the whole line around
+    m_pointA = m_dragStart_PointA + dragAmount;
+    m_pointB = m_dragStart_PointB + dragAmount;
+    this->update();
+    emit lineChanging(m_pointA, m_pointB, m_width);
+    break;
 
-  /** Return true if the mouse is over the central line
-   * @param pos :: position in pixels of mouse */
-  bool LineOverlay::mouseOverCenter(QPoint pos)
-  {
-    // Mouse position in pixels
-    QPointF current = pos;
-    // Find the distance (in pixels) between the mouse and the center of the line
-    QPointF pixA = transform(m_pointA);
-    QPointF pixB = transform(m_pointB);
-    QPointF diff = pixB - pixA;
-    double distance = fabs( diff.x()*(current.y()-pixA.y()) - (current.x() - pixA.x())*diff.y() )
-        / sqrt(diff.x()*diff.x() + diff.y()*diff.y());
-
-    // Margin of 6 pixels, and must be between the 2 limits (if the limits are not the same)
-    bool retval = false;
-    if (distance < 7)
-    {
-      retval = true;
-      if ((pixA.x() != pixB.x()) && (!isBetween( current.x(), pixA.x(), pixB.x())))
-      {
-        retval = false;
-      }
-      if ((pixA.y() != pixB.y()) && (!isBetween( current.y(), pixA.y(), pixB.y())))
-      {
-        retval = false;
-      }
-    }
-    return retval;
+  default:
+    break;
   }
+}
 
-  //-----------------------------------------------------------------------------------------------
-  /** Handle the mouse move event when the line is being dragged
-   * @param event mouse event info */
-  void LineOverlay::handleDrag(QMouseEvent * event)
-  {
-    // Is the shift key pressed?
-    bool shiftPressed = (event->modifiers() & Qt::ShiftModifier);
-    // Currently dragging!
-    QPointF current = this->invTransform( event->pos() );
-    QPointF currentSnap = this->snap(current);
-    QPointF diff = m_pointB - m_pointA;
-    QPointF dragAmount = current - this->m_dragStart;
-    dragAmount = snap(dragAmount);
-    double width = 0;
-
-    // Adjust the current mouse position if needed.
-    if ((m_snapLength > 0) || shiftPressed || m_angleSnapMode)
-    {
-      // This is the distance between the fixed and dragged point
-      QPointF currentDiff;
-      if (m_dragHandle == HandleA)
-        currentDiff = current - m_pointB;
-      else if (m_dragHandle == HandleB)
-        currentDiff = current - m_pointA;
-
-      // calculate angle
-      double angle = atan2(currentDiff.y(), currentDiff.x());
-      
-      // Round angle to closest 45 degrees, if in angle snap mode (shift pressed)
-      if (shiftPressed || m_angleSnapMode)
-      {
-        if (m_angleSnap == 90.0) {
-          //special case for 90 snap (axis aligned snapping)
-          //use screen coords to determine snap angle
-          QPointF currentScreenDiff;
-          if (m_dragHandle == HandleA)
-            currentScreenDiff = event->pos() - transform(m_pointB);
-          else if (m_dragHandle == HandleB)
-            currentScreenDiff = event->pos() - transform(m_pointA);
-            
-          // Limit angles to 90 based on screen coords, not data coords
-          //-y is because the screen y coords are inverted to the data coords
-          angle = atan2(-currentScreenDiff.y(), currentScreenDiff.x());
-        }
-        //convert snap angle to radians
-        double angleSnapRad = m_angleSnap / (180.0 / M_PI);
-        //round current angle to snap angle
-        angle = Utils::rounddbl(angle / angleSnapRad) * angleSnapRad;
-      }
-
-      double length;
-      //for axis aligned angles just use respective distance for the length
-      if (fmod(angle,M_PI) == 0 ) {
-        length = fabs(currentDiff.x());
-      } else if (fmod(angle,M_PI) == M_PI/2 ) {
-        length = fabs(currentDiff.y());
-      } else {
-        length = sqrt(currentDiff.x()*currentDiff.x() + currentDiff.y()*currentDiff.y());
-      }
-      
-      // Round length to m_snapLength, if specified
-      if (m_snapLength > 0)
-        length = Utils::rounddbl(length / m_snapLength) * m_snapLength;
-
-      // Rebuild the mouse position
-      currentDiff = QPointF( cos(angle) * length, sin(angle) * length);
-      if (m_dragHandle == HandleA)
-        currentSnap = snap(m_pointB + currentDiff);
-      else if (m_dragHandle == HandleB)
-        currentSnap = snap(m_pointA + currentDiff);
-    }
+//-----------------------------------------------------------------------------------------------
+/** Event when the mouse moves
+ * @param event mouse event info */
+void LineOverlay::mouseMoveEvent(QMouseEvent *event) {
+  if (event->buttons() & Qt::RightButton)
+    m_rightButton = true;
 
-    switch (m_dragHandle)
-    {
-    case HandleA:
-      setPointA(currentSnap);
-      break;
-
-    case HandleB:
-      setPointB(currentSnap);
-      break;
-
-    case HandleWidthBottom:
-    case HandleWidthTop:
-      // Find the distance between the mouse and the line (see http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html )
-      width = fabs( diff.x()*(current.y()-m_pointA.y()) - (current.x() - m_pointA.x())*diff.y() )
-          / sqrt(diff.x()*diff.x() + diff.y()*diff.y());
-      setWidth(width);
-      break;
-
-    case HandleCenter:
-      // Move the whole line around
-      m_pointA = m_dragStart_PointA + dragAmount;
-      m_pointB = m_dragStart_PointB + dragAmount;
-      this->update();
-      emit lineChanging(m_pointA, m_pointB, m_width);
-      break;
-
-    default:
-      break;
-    }
+  // Do not respond to mouse when hidden
+  if (!m_showHandles || !m_shown) {
+    event->ignore();
+    return;
   }
 
-  //-----------------------------------------------------------------------------------------------
-  /** Event when the mouse moves
-   * @param event mouse event info */
-  void LineOverlay::mouseMoveEvent(QMouseEvent * event)
-  {
-    if (event->buttons() & Qt::RightButton)
-      m_rightButton = true;
-
-    // Do not respond to mouse when hidden
-    if (!m_showHandles || !m_shown)
-    {
-      event->ignore();
-      return;
-    }
-
-    // --- Initial creation mode - wait for first click ----
-    if (m_creation)
-    {
-      // TODO: Custom mouse cursor?
-      this->setCursor(Qt::PointingHandCursor);
-      // Pass-through event to underlying widget, so that it shows the mouse position
-      event->ignore();
-      return;
-    }
+  // --- Initial creation mode - wait for first click ----
+  if (m_creation) {
+    // TODO: Custom mouse cursor?
+    this->setCursor(Qt::PointingHandCursor);
+    // Pass-through event to underlying widget, so that it shows the mouse
+    // position
+    event->ignore();
+    return;
+  }
 
-    // --- Initial creation mode ----
-    if (m_dragHandle != HandleNone)
-    {
-      this->handleDrag(event);
-    }
-    else
-    {
-      // ---- Just moving the mouse -------------
-      if (event->buttons() == Qt::NoButton)
-      {
-        LineOverlay::eHandleID hdl = mouseOverHandle(event->pos());
-        switch (hdl)
-        {
-        case HandleA:
-        case HandleB:
-          this->setCursor(Qt::SizeHorCursor);
-          break;
-        case HandleWidthBottom:
-        case HandleWidthTop:
-          this->setCursor(Qt::SizeVerCursor);
-          break;
-        case HandleCenter:
-          this->setCursor(Qt::PointingHandCursor);
-          break;
-
-        default:
-          this->setCursor(Qt::CrossCursor);
-          break;
-        }
+  // --- Initial creation mode ----
+  if (m_dragHandle != HandleNone) {
+    this->handleDrag(event);
+  } else {
+    // ---- Just moving the mouse -------------
+    if (event->buttons() == Qt::NoButton) {
+      LineOverlay::eHandleID hdl = mouseOverHandle(event->pos());
+      switch (hdl) {
+      case HandleA:
+      case HandleB:
+        this->setCursor(Qt::SizeHorCursor);
+        break;
+      case HandleWidthBottom:
+      case HandleWidthTop:
+        this->setCursor(Qt::SizeVerCursor);
+        break;
+      case HandleCenter:
+        this->setCursor(Qt::PointingHandCursor);
+        break;
+
+      default:
+        this->setCursor(Qt::CrossCursor);
+        break;
       }
     }
-    // In all cases, we pass-through the event to underlying widget,
-    // so that it shows the mouse position.
+  }
+  // In all cases, we pass-through the event to underlying widget,
+  // so that it shows the mouse position.
+  event->ignore();
+}
+
+//-----------------------------------------------------------------------------------------------
+/** Event when the mouse button is pressed down
+ * @param event mouse event info */
+void LineOverlay::mousePressEvent(QMouseEvent *event) {
+  // Do not respond to mouse when hidden
+  if (!m_showHandles || !m_shown) {
     event->ignore();
+    return;
   }
 
-  //-----------------------------------------------------------------------------------------------
-  /** Event when the mouse button is pressed down
-   * @param event mouse event info */
-  void LineOverlay::mousePressEvent(QMouseEvent * event)
-  {
-    // Do not respond to mouse when hidden
-    if (!m_showHandles || !m_shown)
-    {
-      event->ignore();
-      return;
-    }
-
-    // First left-click = create!
-    if (m_creation && (event->buttons() & Qt::LeftButton))
-    {
-      QPointF pt = snap(this->invTransform( event->pos() ));
-      m_pointB = pt;
-      setPointA(pt);
-      // And now we are in drag B mode
-      m_creation = false;
-      m_dragStart = pt;
-      m_dragHandle = HandleB;
-      return;
-    }
-
-    LineOverlay::eHandleID hdl = mouseOverHandle(event->pos());
-    // Drag with the left mouse button
-    if (hdl != HandleNone && (event->buttons() & Qt::LeftButton))
-    {
-      // Start dragging
-      m_dragHandle = hdl;
-      m_dragStart = this->invTransform( event->pos() );
-      m_dragStart_PointA = m_pointA;
-      m_dragStart_PointB = m_pointB;
-    }
-    else
-      // Pass-through event to underlying widget if not over a marker
-      event->ignore();
-
+  // First left-click = create!
+  if (m_creation && (event->buttons() & Qt::LeftButton)) {
+    QPointF pt = snap(this->invTransform(event->pos()));
+    m_pointB = pt;
+    setPointA(pt);
+    // And now we are in drag B mode
+    m_creation = false;
+    m_dragStart = pt;
+    m_dragHandle = HandleB;
+    return;
   }
 
-  //-----------------------------------------------------------------------------------------------
-  /** Event when the mouse moves
-   * @param event mouse event info */
-  void LineOverlay::mouseReleaseEvent(QMouseEvent * event)
-  {
-    if (!(event->buttons() & Qt::RightButton))
-      m_rightButton = false;
-
-    // Do not respond to mouse when hidden
-    if (!m_showHandles || !m_shown)
-    {
-      event->ignore();
-      return;
-    }
+  LineOverlay::eHandleID hdl = mouseOverHandle(event->pos());
+  // Drag with the left mouse button
+  if (hdl != HandleNone && (event->buttons() & Qt::LeftButton)) {
+    // Start dragging
+    m_dragHandle = hdl;
+    m_dragStart = this->invTransform(event->pos());
+    m_dragStart_PointA = m_pointA;
+    m_dragStart_PointB = m_pointB;
+  } else
+    // Pass-through event to underlying widget if not over a marker
+    event->ignore();
+}
 
-    if (m_dragHandle != HandleNone)
-    {
-      // Stop draggin
-      m_dragHandle = HandleNone;
-      // Drag is over - signal that
-      emit lineChanged(m_pointA, m_pointB, m_width);
-    }
-    else
-      // Pass-through event to underlying widget if not dragging
-      event->ignore();
+//-----------------------------------------------------------------------------------------------
+/** Event when the mouse moves
+ * @param event mouse event info */
+void LineOverlay::mouseReleaseEvent(QMouseEvent *event) {
+  if (!(event->buttons() & Qt::RightButton))
+    m_rightButton = false;
 
+  // Do not respond to mouse when hidden
+  if (!m_showHandles || !m_shown) {
+    event->ignore();
+    return;
   }
 
+  if (m_dragHandle != HandleNone) {
+    // Stop draggin
+    m_dragHandle = HandleNone;
+    // Drag is over - signal that
+    emit lineChanged(m_pointA, m_pointB, m_width);
+  } else
+    // Pass-through event to underlying widget if not dragging
+    event->ignore();
+}
 
 } // namespace Mantid
 } // namespace SliceViewer
diff --git a/MantidQt/SliceViewer/src/LinePlotOptions.cpp b/MantidQt/SliceViewer/src/LinePlotOptions.cpp
index e04ddba349f388be706d31bf17aba28454ba2966..0f8ab2bd1ea2d4625df83b1a478cd95ac4273da8 100644
--- a/MantidQt/SliceViewer/src/LinePlotOptions.cpp
+++ b/MantidQt/SliceViewer/src/LinePlotOptions.cpp
@@ -4,31 +4,32 @@ using namespace Mantid::API;
 using namespace Mantid::Geometry;
 
 LinePlotOptions::LinePlotOptions(QWidget *parent, bool logScaleOption)
-    : QWidget(parent),
-      m_plotAxis(MantidQwtIMDWorkspaceData::PlotAuto),
-      m_normalize(Mantid::API::VolumeNormalization)
-{
-	ui.setupUi(this);
+    : QWidget(parent), m_plotAxis(MantidQwtIMDWorkspaceData::PlotAuto),
+      m_normalize(Mantid::API::VolumeNormalization) {
+  ui.setupUi(this);
 
-	ui.widgetLogOptions->setVisible(logScaleOption);
+  ui.widgetLogOptions->setVisible(logScaleOption);
 
-	addPlotRadioButton("Auto", "Automatically choose between plotting X or Y depending on the angle of the line");
-  addPlotRadioButton("Distance", "Use the distance from the start of the line as the X axis of the plot");
+  addPlotRadioButton("Auto", "Automatically choose between plotting X or Y "
+                             "depending on the angle of the line");
+  addPlotRadioButton(
+      "Distance",
+      "Use the distance from the start of the line as the X axis of the plot");
   // Default to "Auto"
   m_radPlots[0]->setChecked(true);
 
-	// Connect all the radio buttons
-  QObject::connect(ui.radNoNormalization, SIGNAL(toggled(bool)), this, SLOT(radNormalization_changed()));
-  QObject::connect(ui.radNumEventsNormalization, SIGNAL(toggled(bool)), this, SLOT(radNormalization_changed()));
-  QObject::connect(ui.radVolumeNormalization, SIGNAL(toggled(bool)), this, SLOT(radNormalization_changed()));
-  QObject::connect(ui.ckLog10, SIGNAL(toggled(bool)), this, SLOT(onYScalingChanged()));
-
+  // Connect all the radio buttons
+  QObject::connect(ui.radNoNormalization, SIGNAL(toggled(bool)), this,
+                   SLOT(radNormalization_changed()));
+  QObject::connect(ui.radNumEventsNormalization, SIGNAL(toggled(bool)), this,
+                   SLOT(radNormalization_changed()));
+  QObject::connect(ui.radVolumeNormalization, SIGNAL(toggled(bool)), this,
+                   SLOT(radNormalization_changed()));
+  QObject::connect(ui.ckLog10, SIGNAL(toggled(bool)), this,
+                   SLOT(onYScalingChanged()));
 }
 
-LinePlotOptions::~LinePlotOptions()
-{
-
-}
+LinePlotOptions::~LinePlotOptions() {}
 
 //------------------------------------------------------------------------------
 /** Add a radio button to the plot options
@@ -37,47 +38,43 @@ LinePlotOptions::~LinePlotOptions()
  * @param tooltip :: tooltip
  * @param bIntegrated :: flag to indicate that the dimension is integrated.
  */
-void LinePlotOptions::addPlotRadioButton(const std::string & text, const std::string & tooltip, const bool bIntegrated)
-{
-  QRadioButton * rad;
+void LinePlotOptions::addPlotRadioButton(const std::string &text,
+                                         const std::string &tooltip,
+                                         const bool bIntegrated) {
+  QRadioButton *rad;
   rad = new QRadioButton(ui.widgetPlotAxis);
   rad->setText(QString::fromStdString(text));
   rad->setToolTip(QString::fromStdString(tooltip));
   rad->setEnabled(!bIntegrated);
   // Insert it one before the horizontal spacer.
-  QBoxLayout * layout = qobject_cast<QBoxLayout*>(ui.widgetPlotAxis->layout());
-  layout->insertWidget( layout->count()-1, rad);
+  QBoxLayout *layout = qobject_cast<QBoxLayout *>(ui.widgetPlotAxis->layout());
+  layout->insertWidget(layout->count() - 1, rad);
   m_radPlots.push_back(rad);
   QObject::connect(rad, SIGNAL(toggled(bool)), this, SLOT(radPlot_changed()));
 }
 
-
-
 //------------------------------------------------------------------------------
 /** Set the original workspace, to show the axes plot choice */
-void LinePlotOptions::setOriginalWorkspace(Mantid::API::IMDWorkspace_sptr ws)
-{
-  if (!ws) return;
+void LinePlotOptions::setOriginalWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
+  if (!ws)
+    return;
 
-  for (size_t d=0; d<(ws->getNumDims()); d++)
-  {
+  for (size_t d = 0; d < (ws->getNumDims()); d++) {
     IMDDimension_const_sptr dim = ws->getDimension(d);
     std::string text = dim->getName();
-    std::string tooltip = "Use the "+dim->getName()+" dimension as the X plot axis.";
+    std::string tooltip =
+        "Use the " + dim->getName() + " dimension as the X plot axis.";
     const bool bIntegrated = dim->getIsIntegrated();
     // Index into the radio buttons array
-    int index = int(d)+2;
-    if (m_radPlots.size() > index)
-    {
+    int index = int(d) + 2;
+    if (m_radPlots.size() > index) {
       m_radPlots[index]->setText(QString::fromStdString(text));
       m_radPlots[index]->setToolTip(QString::fromStdString(tooltip));
-    }
-    else
+    } else
       addPlotRadioButton(text, tooltip, bIntegrated);
   }
 }
 
-
 //------------------------------------------------------------------------------
 /** Get the choice of X-axis to plot
  *
@@ -86,11 +83,7 @@ void LinePlotOptions::setOriginalWorkspace(Mantid::API::IMDWorkspace_sptr ws)
  * 0+ : The dimension index in the original workspace.
  *
  * @return int */
-int LinePlotOptions::getPlotAxis() const
-{
-  return m_plotAxis;
-}
-
+int LinePlotOptions::getPlotAxis() const { return m_plotAxis; }
 
 //------------------------------------------------------------------------------
 /** Set the choice of X-axis to plot.
@@ -100,37 +93,31 @@ int LinePlotOptions::getPlotAxis() const
  * 0+ : The dimension index in the original workspace.
  *
  * @param choice :: int */
-void LinePlotOptions::setPlotAxis(int choice)
-{
+void LinePlotOptions::setPlotAxis(int choice) {
   m_plotAxis = choice;
   // Since the radPlots start corresponding with -2, the index = choice + 2
-  int index = m_plotAxis+2;
+  int index = m_plotAxis + 2;
   if (index >= m_radPlots.size())
-    m_plotAxis = m_radPlots.size()-1 - 2;
+    m_plotAxis = m_radPlots.size() - 1 - 2;
   // Check the right radio button
   m_radPlots[index]->setChecked(true);
 }
 
-
 //------------------------------------------------------------------------------
 /** Get the normalization method to use
  * @return choice of normalization */
-Mantid::API::MDNormalization LinePlotOptions::getNormalization() const
-{
+Mantid::API::MDNormalization LinePlotOptions::getNormalization() const {
   return m_normalize;
 }
 
-
 /** Set the normalization method to use
  *
  * @param method :: choice of normalization
  */
-void LinePlotOptions::setNormalization(Mantid::API::MDNormalization method)
-{
+void LinePlotOptions::setNormalization(Mantid::API::MDNormalization method) {
   m_normalize = method;
   // Update gui
-  switch(m_normalize)
-  {
+  switch (m_normalize) {
   case Mantid::API::NoNormalization:
     ui.radNoNormalization->setChecked(true);
     break;
@@ -143,29 +130,23 @@ void LinePlotOptions::setNormalization(Mantid::API::MDNormalization method)
   }
 }
 
-
-
 //------------------------------------------------------------------------------
 /** Slot called when any of the X plot choice radio buttons are clicked
  */
-void LinePlotOptions::radPlot_changed()
-{
-  for (int i=0; i<m_radPlots.size(); i++)
-  {
+void LinePlotOptions::radPlot_changed() {
+  for (int i = 0; i < m_radPlots.size(); i++) {
     if (m_radPlots[i]->isChecked())
       // Options start at -2 (index 0 in the radPlots)
-      m_plotAxis = i-2;
+      m_plotAxis = i - 2;
   }
   // Send out a signal
   emit changedPlotAxis();
 }
 
-
 //------------------------------------------------------------------------------
 /** Slot called when any of the normalization choice radio buttons are clicked
  */
-void LinePlotOptions::radNormalization_changed()
-{
+void LinePlotOptions::radNormalization_changed() {
   if (ui.radNoNormalization->isChecked())
     m_normalize = Mantid::API::NoNormalization;
   else if (ui.radVolumeNormalization->isChecked())
@@ -181,17 +162,10 @@ void LinePlotOptions::radNormalization_changed()
 /**
  * Handler for changes to the Y-axis log scale.
  */
-void LinePlotOptions::onYScalingChanged()
-{
-  emit changedYLogScaling();
-}
+void LinePlotOptions::onYScalingChanged() { emit changedYLogScaling(); }
 
 /**
  * Getter for the currently set option of the isLogScaled control.
  * @return
  */
-bool LinePlotOptions::isLogScaledY() const
-{
-  return ui.ckLog10->isChecked();
-}
-
+bool LinePlotOptions::isLogScaledY() const { return ui.ckLog10->isChecked(); }
diff --git a/MantidQt/SliceViewer/src/PeakBoundingBox.cpp b/MantidQt/SliceViewer/src/PeakBoundingBox.cpp
index 8e4778843251737bd8a2b01ddbf06fe6c6dc1564..e63cf002699370c550e2608e0e7166a74f9a13ac 100644
--- a/MantidQt/SliceViewer/src/PeakBoundingBox.cpp
+++ b/MantidQt/SliceViewer/src/PeakBoundingBox.cpp
@@ -3,253 +3,227 @@
 #include <boost/format.hpp>
 #include <cmath>
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-      /**
-       * Default Constructor
-       */
-      PeakBoundingBox::PeakBoundingBox() : m_left(0), m_right(0), m_top(0), m_bottom(0), m_slicePoint(0), m_front(0), m_back(0)
-      {
-      }
-
-      /**
-       * Constructor
-       * @param left: Box left
-       * @param right : Box right
-       * @param top : Box top
-       * @param bottom : Box bottom
-       * @param slicePoint : Slicing point.
-       */
-      PeakBoundingBox::PeakBoundingBox(const Left& left, const Right& right, const Top& top, const Bottom& bottom, const SlicePoint& slicePoint)
-      : m_left(left), m_right(right), m_top(top), m_bottom(bottom), m_slicePoint(slicePoint), m_front(Front(slicePoint())), m_back(Back(slicePoint()))
-      {
-        validateBoundaries();
-      }
-
-      /**
-       * Constructor
-       * @param left: Box left
-       * @param right : Box right
-       * @param top : Box top
-       * @param bottom : Box bottom
-       * @param slicePoint : Slicing point.
-       * @param front : Box front
-       * @param back : Box back
-       */
-      PeakBoundingBox::PeakBoundingBox(const Left& left, const Right& right, const Top& top, const Bottom& bottom, const SlicePoint& slicePoint, const Front& front, const Back& back)
-      : m_left(left), m_right(right), m_top(top), m_bottom(bottom), m_slicePoint(slicePoint), m_front(front), m_back(back)
-      {
-        validateBoundaries();
-      }
-
-      void PeakBoundingBox::validateBoundaries()
-      {
-        if (m_right() < m_left())
-        {
-          throw std::invalid_argument("Right < Left");
-        }
-        if (m_top() < m_bottom())
-        {
-          throw std::invalid_argument("Top < Bottom");
-        }
-        if (m_back() < m_front())
-        {
-          throw std::invalid_argument("Back < Front");
-        }
-        if (m_back() < m_slicePoint())
-        {
-          throw std::invalid_argument("Back < Slice Point");
-        }
-        if (m_slicePoint() < m_front())
-        {
-          throw std::invalid_argument("Slice Point < Front");
-        }
-      }
-
-      /// Destructor
-      PeakBoundingBox::~PeakBoundingBox()
-      {
-      }
-
-      /**
-       * Copy constructor
-       * @param other
-       */
-      PeakBoundingBox::PeakBoundingBox(const PeakBoundingBox& other)
-      : m_left(other.m_left), m_right(other.m_right), m_top(other.m_top), m_bottom(other.m_bottom), m_slicePoint(other.m_slicePoint), m_front(other.m_front), m_back(other.m_back)
-      {
-      }
-
-      /**
-       * Assignment operator
-       * @param other : Other box to assign from
-       * @return : This object after assignment
-       */
-      PeakBoundingBox& PeakBoundingBox::operator=(const PeakBoundingBox& other)
-      {
-        if(&other != this)
-        {
-          m_top = other.m_top;
-          m_bottom = other.m_bottom;
-          m_left = other.m_left;
-          m_right = other.m_right;
-          m_slicePoint = other.m_slicePoint;
-          m_front = other.m_front;
-          m_back = other.m_back;
-        }
-        return *this;
-      }
-
-      /**
-       * Getter for left edge.
-       * @return Left edge
-       */
-      double PeakBoundingBox::left() const
-      {
-        return m_left();
-      }
-
-      /**
-       * Getter for right edge.
-       * @return Right edge
-       */
-      double PeakBoundingBox::right() const
-      {
-        return m_right();
-      }
-
-      /**
-       * Getter for top edge
-       * @return Top edge
-       */
-      double PeakBoundingBox::top() const
-      {
-        return m_top();
-      }
-
-      /**
-       * Getter for bottom edge
-       * @return bottom edge
-       */
-      double PeakBoundingBox::bottom() const
-      {
-        return m_bottom();
-      }
-
-      /**
-       * Getter for front edge
-       * @return bottom edge
-       */
-      double PeakBoundingBox::front() const
-      {
-        return m_front();
-      }
-
-      /**
-       * Getter for front edge
-       * @return bottom edge
-       */
-      double PeakBoundingBox::back() const
-      {
-        return m_back();
-      }
-
-      /**
-       * Getter for the slice point
-       * @return The slice point
-       */
-      double PeakBoundingBox::slicePoint() const
-      {
-        return m_slicePoint();
-      }
-
-      /**
-       * Overloaded operator
-       * @param other : other object to compare against
-       * @return True if and only if the box and slice points are identical.
-       */
-      bool PeakBoundingBox::operator==(const PeakBoundingBox &other) const
-      {
-        return this->m_left() == other.m_left()
-            && this->m_right() == other.m_right()
-            && this->m_bottom() == other.m_bottom()
-            && this->m_top() == other.m_top()
-            && this->m_slicePoint() == other.m_slicePoint()
-            && this->m_back() == other.m_back()
-            && this->m_front() == other.m_front();
-      }
-
-      /**
-       * Overloaded operator
-       * @param other : other object to compare against
-       * @return False if and only if both box and slice points are identical
-       */
-      bool PeakBoundingBox::operator!=(const PeakBoundingBox &other) const
-      {
-        return !(*this == other);
-      }
-
-      /**
-       * Make a new box using the SlicePosition and the sliceDelta to calculate a new front and back edge.
-       * @param sliceDelta : Thickness in z dimension
-       * @return new Bounding box.
-       */
-      PeakBoundingBox PeakBoundingBox::makeSliceBox(const double& sliceDelta) const
-      {
-        double halfWidth = std::abs(sliceDelta)/2;
-        return PeakBoundingBox(m_left, m_right, m_top, m_bottom, m_slicePoint, Front(m_slicePoint() - halfWidth), Back(m_back() + halfWidth));
-      }
-
-      /**
-      * Export extents as as string of comma separated values.
-      * @return vector of extents min, max in x, y, z
-      */
-      std::vector<double> PeakBoundingBox::toExtents() const
-      {
-        std::vector<double> extents(6);
-        extents[0] = m_left();
-        extents[1] = m_right();
-        extents[2] = m_bottom();
-        extents[3] = m_top();
-        extents[4] = m_front();
-        extents[5] = m_back();
-        return extents;
-      }
-
-      /**
-       * Export extents as as string of comma separated values.
-       * @return formatted comma separated string.
-       */
-      std::string PeakBoundingBox::toExtentsString() const
-      {
-        using boost::format;
-        auto extents = toExtents();
-        return  boost::str(format("%.2f,%.2f,%.2f,%.2f,%.2f,%.2f") % extents[0] % extents[1] % extents[2] % extents[3] % extents[4] % extents[5]);
-      }
-
-      /**
-       * Transform the box. Permanent  change the box left, right, top, bottom, front and back according to the transform.
-       * @param transform : Transform to use.
-       */
-      void PeakBoundingBox::transformBox(Mantid::Geometry::PeakTransform_sptr transform)
-      {
-        using Mantid::Kernel::V3D;
-        // Front bottom left
-        V3D newBottomLeft = transform->transformBack(V3D(m_left(), m_bottom(), m_front()));
-        // Back top right
-        V3D newTopRight = transform->transformBack(V3D(m_right(), m_top(), m_back()));
-        // SlicePoint
-        V3D newSlicePoint = transform->transformBack(V3D(0, 0, m_slicePoint()));
-
-        m_left = Left(newBottomLeft.X());
-        m_bottom = Bottom(newBottomLeft.Y());
-        m_right = Right(newTopRight.X());
-        m_top = Top(newTopRight.Y());
-        m_front = Front(newBottomLeft.Z());
-        m_back = Back(newTopRight.Z());
-        m_slicePoint = SlicePoint(newSlicePoint.Z());
-      }
+namespace MantidQt {
+namespace SliceViewer {
+/**
+ * Default Constructor
+ */
+PeakBoundingBox::PeakBoundingBox()
+    : m_left(0), m_right(0), m_top(0), m_bottom(0), m_slicePoint(0), m_front(0),
+      m_back(0) {}
+
+/**
+ * Constructor
+ * @param left: Box left
+ * @param right : Box right
+ * @param top : Box top
+ * @param bottom : Box bottom
+ * @param slicePoint : Slicing point.
+ */
+PeakBoundingBox::PeakBoundingBox(const Left &left, const Right &right,
+                                 const Top &top, const Bottom &bottom,
+                                 const SlicePoint &slicePoint)
+    : m_left(left), m_right(right), m_top(top), m_bottom(bottom),
+      m_slicePoint(slicePoint), m_front(Front(slicePoint())),
+      m_back(Back(slicePoint())) {
+  validateBoundaries();
+}
+
+/**
+ * Constructor
+ * @param left: Box left
+ * @param right : Box right
+ * @param top : Box top
+ * @param bottom : Box bottom
+ * @param slicePoint : Slicing point.
+ * @param front : Box front
+ * @param back : Box back
+ */
+PeakBoundingBox::PeakBoundingBox(const Left &left, const Right &right,
+                                 const Top &top, const Bottom &bottom,
+                                 const SlicePoint &slicePoint,
+                                 const Front &front, const Back &back)
+    : m_left(left), m_right(right), m_top(top), m_bottom(bottom),
+      m_slicePoint(slicePoint), m_front(front), m_back(back) {
+  validateBoundaries();
+}
+
+void PeakBoundingBox::validateBoundaries() {
+  if (m_right() < m_left()) {
+    throw std::invalid_argument("Right < Left");
+  }
+  if (m_top() < m_bottom()) {
+    throw std::invalid_argument("Top < Bottom");
+  }
+  if (m_back() < m_front()) {
+    throw std::invalid_argument("Back < Front");
+  }
+  if (m_back() < m_slicePoint()) {
+    throw std::invalid_argument("Back < Slice Point");
   }
+  if (m_slicePoint() < m_front()) {
+    throw std::invalid_argument("Slice Point < Front");
+  }
+}
+
+/// Destructor
+PeakBoundingBox::~PeakBoundingBox() {}
+
+/**
+ * Copy constructor
+ * @param other
+ */
+PeakBoundingBox::PeakBoundingBox(const PeakBoundingBox &other)
+    : m_left(other.m_left), m_right(other.m_right), m_top(other.m_top),
+      m_bottom(other.m_bottom), m_slicePoint(other.m_slicePoint),
+      m_front(other.m_front), m_back(other.m_back) {}
+
+/**
+ * Assignment operator
+ * @param other : Other box to assign from
+ * @return : This object after assignment
+ */
+PeakBoundingBox &PeakBoundingBox::operator=(const PeakBoundingBox &other) {
+  if (&other != this) {
+    m_top = other.m_top;
+    m_bottom = other.m_bottom;
+    m_left = other.m_left;
+    m_right = other.m_right;
+    m_slicePoint = other.m_slicePoint;
+    m_front = other.m_front;
+    m_back = other.m_back;
+  }
+  return *this;
+}
+
+/**
+ * Getter for left edge.
+ * @return Left edge
+ */
+double PeakBoundingBox::left() const { return m_left(); }
+
+/**
+ * Getter for right edge.
+ * @return Right edge
+ */
+double PeakBoundingBox::right() const { return m_right(); }
+
+/**
+ * Getter for top edge
+ * @return Top edge
+ */
+double PeakBoundingBox::top() const { return m_top(); }
+
+/**
+ * Getter for bottom edge
+ * @return bottom edge
+ */
+double PeakBoundingBox::bottom() const { return m_bottom(); }
+
+/**
+ * Getter for front edge
+ * @return bottom edge
+ */
+double PeakBoundingBox::front() const { return m_front(); }
+
+/**
+ * Getter for front edge
+ * @return bottom edge
+ */
+double PeakBoundingBox::back() const { return m_back(); }
+
+/**
+ * Getter for the slice point
+ * @return The slice point
+ */
+double PeakBoundingBox::slicePoint() const { return m_slicePoint(); }
+
+/**
+ * Overloaded operator
+ * @param other : other object to compare against
+ * @return True if and only if the box and slice points are identical.
+ */
+bool PeakBoundingBox::operator==(const PeakBoundingBox &other) const {
+  return this->m_left() == other.m_left() &&
+         this->m_right() == other.m_right() &&
+         this->m_bottom() == other.m_bottom() &&
+         this->m_top() == other.m_top() &&
+         this->m_slicePoint() == other.m_slicePoint() &&
+         this->m_back() == other.m_back() && this->m_front() == other.m_front();
+}
+
+/**
+ * Overloaded operator
+ * @param other : other object to compare against
+ * @return False if and only if both box and slice points are identical
+ */
+bool PeakBoundingBox::operator!=(const PeakBoundingBox &other) const {
+  return !(*this == other);
+}
+
+/**
+ * Make a new box using the SlicePosition and the sliceDelta to calculate a new
+ * front and back edge.
+ * @param sliceDelta : Thickness in z dimension
+ * @return new Bounding box.
+ */
+PeakBoundingBox PeakBoundingBox::makeSliceBox(const double &sliceDelta) const {
+  double halfWidth = std::abs(sliceDelta) / 2;
+  return PeakBoundingBox(m_left, m_right, m_top, m_bottom, m_slicePoint,
+                         Front(m_slicePoint() - halfWidth),
+                         Back(m_back() + halfWidth));
+}
+
+/**
+* Export extents as as string of comma separated values.
+* @return vector of extents min, max in x, y, z
+*/
+std::vector<double> PeakBoundingBox::toExtents() const {
+  std::vector<double> extents(6);
+  extents[0] = m_left();
+  extents[1] = m_right();
+  extents[2] = m_bottom();
+  extents[3] = m_top();
+  extents[4] = m_front();
+  extents[5] = m_back();
+  return extents;
+}
+
+/**
+ * Export extents as as string of comma separated values.
+ * @return formatted comma separated string.
+ */
+std::string PeakBoundingBox::toExtentsString() const {
+  using boost::format;
+  auto extents = toExtents();
+  return boost::str(format("%.2f,%.2f,%.2f,%.2f,%.2f,%.2f") % extents[0] %
+                    extents[1] % extents[2] % extents[3] % extents[4] %
+                    extents[5]);
+}
+
+/**
+ * Transform the box. Permanent  change the box left, right, top, bottom, front
+ * and back according to the transform.
+ * @param transform : Transform to use.
+ */
+void PeakBoundingBox::transformBox(
+    Mantid::Geometry::PeakTransform_sptr transform) {
+  using Mantid::Kernel::V3D;
+  // Front bottom left
+  V3D newBottomLeft =
+      transform->transformBack(V3D(m_left(), m_bottom(), m_front()));
+  // Back top right
+  V3D newTopRight = transform->transformBack(V3D(m_right(), m_top(), m_back()));
+  // SlicePoint
+  V3D newSlicePoint = transform->transformBack(V3D(0, 0, m_slicePoint()));
+
+  m_left = Left(newBottomLeft.X());
+  m_bottom = Bottom(newBottomLeft.Y());
+  m_right = Right(newTopRight.X());
+  m_top = Top(newTopRight.Y());
+  m_front = Front(newBottomLeft.Z());
+  m_back = Back(newTopRight.Z());
+  m_slicePoint = SlicePoint(newSlicePoint.Z());
+}
+}
 }
diff --git a/MantidQt/SliceViewer/src/PeakOverlayInteractive.cpp b/MantidQt/SliceViewer/src/PeakOverlayInteractive.cpp
index 0630465e623ddd098b97ae80c4482a38081ed5f5..a01912156602b83d03cc86a8e23ef49aaa91a10d 100644
--- a/MantidQt/SliceViewer/src/PeakOverlayInteractive.cpp
+++ b/MantidQt/SliceViewer/src/PeakOverlayInteractive.cpp
@@ -25,13 +25,9 @@ PeakOverlayInteractive::PeakOverlayInteractive(
 
   this->setVisible(true);
   setUpdatesEnabled(true);
-
 }
 
-PeakOverlayInteractive::~PeakOverlayInteractive()
-{
-    this->peakDisplayMode();
-}
+PeakOverlayInteractive::~PeakOverlayInteractive() { this->peakDisplayMode(); }
 
 void PeakOverlayInteractive::paintEvent(QPaintEvent *event) {
   // Only paint to update the interactive tool
@@ -45,149 +41,137 @@ void PeakOverlayInteractive::paintEvent(QPaintEvent *event) {
   this->doPaintPeaks(event);
 }
 
-void PeakOverlayInteractive::captureMouseEvents(bool capture)
-{
-    setAttribute(Qt::WA_TransparentForMouseEvents, !capture);
+void PeakOverlayInteractive::captureMouseEvents(bool capture) {
+  setAttribute(Qt::WA_TransparentForMouseEvents, !capture);
 }
 
 void PeakOverlayInteractive::peakDeletionMode() {
-    captureMouseEvents(true);
-    QApplication::restoreOverrideCursor();
-    auto* temp = m_tool;
-    auto* eraseTool = new MantidQt::MantidWidgets::InputControllerErase(this);
-    connect(eraseTool,SIGNAL(erase(QRect)),this,SLOT(erasePeaks(QRect)), Qt::QueuedConnection);
-    m_tool = eraseTool;
-    delete temp;
+  captureMouseEvents(true);
+  QApplication::restoreOverrideCursor();
+  auto *temp = m_tool;
+  auto *eraseTool = new MantidQt::MantidWidgets::InputControllerErase(this);
+  connect(eraseTool, SIGNAL(erase(QRect)), this, SLOT(erasePeaks(QRect)),
+          Qt::QueuedConnection);
+  m_tool = eraseTool;
+  delete temp;
 }
 
 void PeakOverlayInteractive::peakAdditionMode() {
-    captureMouseEvents(true);
-    QApplication::restoreOverrideCursor();
-    auto* temp = m_tool;
-    auto* addTool = new MantidQt::MantidWidgets::InputControllerPick(this);
-    connect(addTool,SIGNAL(pickPointAt(int,int)),this,SLOT(addPeakAt(int,int)));
-    m_tool = addTool;
-    delete temp;
+  captureMouseEvents(true);
+  QApplication::restoreOverrideCursor();
+  auto *temp = m_tool;
+  auto *addTool = new MantidQt::MantidWidgets::InputControllerPick(this);
+  connect(addTool, SIGNAL(pickPointAt(int, int)), this,
+          SLOT(addPeakAt(int, int)));
+  m_tool = addTool;
+  delete temp;
 }
 
 void PeakOverlayInteractive::peakDisplayMode() {
-    captureMouseEvents(false /*pass through mouse events*/);
-    QApplication::restoreOverrideCursor();
-    if(m_tool){
-        delete m_tool;
-        m_tool = NULL;
-    }
-}
-
-void PeakOverlayInteractive::mousePressEvent(QMouseEvent* e)
-{
-    if(m_tool) {
-      m_tool->mousePressEvent( e );
-    }else{
-        e->ignore();
-    }
-}
-
-void PeakOverlayInteractive::mouseMoveEvent(QMouseEvent* e)
-{
-    if(m_tool) {
-      m_tool->mouseMoveEvent( e );
-      this->update();
-    }
+  captureMouseEvents(false /*pass through mouse events*/);
+  QApplication::restoreOverrideCursor();
+  if (m_tool) {
+    delete m_tool;
+    m_tool = NULL;
+  }
+}
+
+void PeakOverlayInteractive::mousePressEvent(QMouseEvent *e) {
+  if (m_tool) {
+    m_tool->mousePressEvent(e);
+  } else {
     e->ignore();
+  }
+}
 
+void PeakOverlayInteractive::mouseMoveEvent(QMouseEvent *e) {
+  if (m_tool) {
+    m_tool->mouseMoveEvent(e);
+    this->update();
+  }
+  e->ignore();
 }
 
-void PeakOverlayInteractive::mouseReleaseEvent(QMouseEvent* e)
-{
-    if(m_tool) {
-      m_tool->mouseReleaseEvent( e );
-    }else{
-        e->ignore();
-    }
+void PeakOverlayInteractive::mouseReleaseEvent(QMouseEvent *e) {
+  if (m_tool) {
+    m_tool->mouseReleaseEvent(e);
+  } else {
+    e->ignore();
+  }
 }
 
-void PeakOverlayInteractive::wheelEvent(QWheelEvent* e)
-{
-    if(m_tool) {
-      m_tool->wheelEvent( e );
-    }else{
-        e->ignore();
-    }
+void PeakOverlayInteractive::wheelEvent(QWheelEvent *e) {
+  if (m_tool) {
+    m_tool->wheelEvent(e);
+  } else {
+    e->ignore();
+  }
 }
 
-void PeakOverlayInteractive::keyPressEvent(QKeyEvent* e)
-{
-    if(m_tool) {
-      m_tool->keyPressEvent( e );
-    }else{
-        e->ignore();
-    }
+void PeakOverlayInteractive::keyPressEvent(QKeyEvent *e) {
+  if (m_tool) {
+    m_tool->keyPressEvent(e);
+  } else {
+    e->ignore();
+  }
 }
 
-void PeakOverlayInteractive::enterEvent(QEvent *e)
-{
-    if(m_tool) {
-      m_tool->enterEvent( e );
-    }else{
-        e->ignore();
-    }
+void PeakOverlayInteractive::enterEvent(QEvent *e) {
+  if (m_tool) {
+    m_tool->enterEvent(e);
+  } else {
+    e->ignore();
+  }
 }
 
-void PeakOverlayInteractive::leaveEvent(QEvent *e)
-{
-    if(m_tool) {
-      m_tool->leaveEvent( e );
-    }else{
-        e->ignore();
-    }
+void PeakOverlayInteractive::leaveEvent(QEvent *e) {
+  if (m_tool) {
+    m_tool->leaveEvent(e);
+  } else {
+    e->ignore();
+  }
 }
 
 void PeakOverlayInteractive::addPeakAt(int coordX, int coordY) {
 
-    QwtScaleMap xMap = m_plot->canvasMap(m_plotXIndex);
-    QwtScaleMap yMap = m_plot->canvasMap(m_plotYIndex);
+  QwtScaleMap xMap = m_plot->canvasMap(m_plotXIndex);
+  QwtScaleMap yMap = m_plot->canvasMap(m_plotYIndex);
 
-    const double plotX = xMap.invTransform(double(coordX));
-    const double plotY = yMap.invTransform(double(coordY));
+  const double plotX = xMap.invTransform(double(coordX));
+  const double plotY = yMap.invTransform(double(coordY));
 
-    m_presenter->addPeakAt(plotX, plotY);
+  m_presenter->addPeakAt(plotX, plotY);
 }
 
+void PeakOverlayInteractive::erasePeaks(const QRect &rect) {
+  QwtScaleMap xMap = m_plot->canvasMap(m_plotXIndex);
+  QwtScaleMap yMap = m_plot->canvasMap(m_plotYIndex);
 
-void PeakOverlayInteractive::erasePeaks(const QRect &rect)
-{
-    QwtScaleMap xMap = m_plot->canvasMap(m_plotXIndex);
-    QwtScaleMap yMap = m_plot->canvasMap(m_plotYIndex);
-
-    const Left left(xMap.invTransform(rect.left()));
-    const Right right(xMap.invTransform(rect.right()));
-    const Top top(yMap.invTransform(rect.top()));
-    const Bottom bottom(yMap.invTransform(rect.bottom()));
-    const SlicePoint slicePoint(-1); // Not required.
+  const Left left(xMap.invTransform(rect.left()));
+  const Right right(xMap.invTransform(rect.right()));
+  const Top top(yMap.invTransform(rect.top()));
+  const Bottom bottom(yMap.invTransform(rect.bottom()));
+  const SlicePoint slicePoint(-1); // Not required.
 
-    m_presenter->deletePeaksIn(PeakBoundingBox(left, right, top, bottom, slicePoint));
+  m_presenter->deletePeaksIn(
+      PeakBoundingBox(left, right, top, bottom, slicePoint));
 }
 
 //----------------------------------------------------------------------------------------------
 /// Return the recommended size of the widget
-QSize PeakOverlayInteractive::sizeHint() const
-{
-  //TODO: Is there a smarter way to find the right size?
+QSize PeakOverlayInteractive::sizeHint() const {
+  // TODO: Is there a smarter way to find the right size?
   return QSize(20000, 20000);
   // Always as big as the canvas
-  //return m_plot->canvas()->size();
+  // return m_plot->canvas()->size();
 }
 
-QSize PeakOverlayInteractive::size() const
-{ return m_plot->canvas()->size(); }
-
-int PeakOverlayInteractive::height() const
-{ return m_plot->canvas()->height(); }
-
-int PeakOverlayInteractive::width() const
-{ return m_plot->canvas()->width(); }
+QSize PeakOverlayInteractive::size() const { return m_plot->canvas()->size(); }
 
+int PeakOverlayInteractive::height() const {
+  return m_plot->canvas()->height();
+}
 
+int PeakOverlayInteractive::width() const { return m_plot->canvas()->width(); }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakOverlayViewFactoryBase.cpp b/MantidQt/SliceViewer/src/PeakOverlayViewFactoryBase.cpp
index 502329d2afdcf39acfe85a4b0448e464d28284b2..4c8be8ea155bfebb1ce30a39a741d8050fd34482 100644
--- a/MantidQt/SliceViewer/src/PeakOverlayViewFactoryBase.cpp
+++ b/MantidQt/SliceViewer/src/PeakOverlayViewFactoryBase.cpp
@@ -4,41 +4,39 @@
 
 using namespace Mantid::API;
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-
-    PeakOverlayViewFactoryBase::PeakOverlayViewFactoryBase(QwtPlot * plot, QWidget * parent, const int plotXIndex, const int plotYIndex, const size_t workspaceNumber) : PeakOverlayViewFactory(), m_plot(plot), m_parent(parent),
-        m_plotXIndex(plotXIndex), m_plotYIndex(plotYIndex)
-    {
-      if(!plot)
-        throw std::invalid_argument("PeakOverlayViewFactoryBase plot is null");
-      if(!parent)
-        throw std::invalid_argument("PeakOverlayViewFactoryBase parent widget is null");
-
-
-      PeakPalette<PeakViewColor> defaultPalette;
-      auto foregroundViewColor = defaultPalette.foregroundIndexToColour(static_cast<int>(workspaceNumber));
-      auto backgroundViewColor = defaultPalette.backgroundIndexToColour(static_cast<int>(workspaceNumber));
-      m_foregroundViewColor = PeakViewColor(foregroundViewColor);
-      m_backgroundViewColor = PeakViewColor(backgroundViewColor);
-    }
+namespace MantidQt {
+namespace SliceViewer {
+
+PeakOverlayViewFactoryBase::PeakOverlayViewFactoryBase(
+    QwtPlot *plot, QWidget *parent, const int plotXIndex, const int plotYIndex,
+    const size_t workspaceNumber)
+    : PeakOverlayViewFactory(), m_plot(plot), m_parent(parent),
+      m_plotXIndex(plotXIndex), m_plotYIndex(plotYIndex) {
+  if (!plot)
+    throw std::invalid_argument("PeakOverlayViewFactoryBase plot is null");
+  if (!parent)
+    throw std::invalid_argument(
+        "PeakOverlayViewFactoryBase parent widget is null");
+
+  PeakPalette<PeakViewColor> defaultPalette;
+  auto foregroundViewColor =
+      defaultPalette.foregroundIndexToColour(static_cast<int>(workspaceNumber));
+  auto backgroundViewColor =
+      defaultPalette.backgroundIndexToColour(static_cast<int>(workspaceNumber));
+  m_foregroundViewColor = PeakViewColor(foregroundViewColor);
+  m_backgroundViewColor = PeakViewColor(backgroundViewColor);
+}
 
-    std::string PeakOverlayViewFactoryBase::getPlotXLabel() const
-    {
-      QwtText xDim = m_plot->axisTitle(QwtPlot::xBottom);
-      return xDim.text().toStdString();
-    }
+std::string PeakOverlayViewFactoryBase::getPlotXLabel() const {
+  QwtText xDim = m_plot->axisTitle(QwtPlot::xBottom);
+  return xDim.text().toStdString();
+}
 
-    std::string PeakOverlayViewFactoryBase::getPlotYLabel() const
-    {
-      QwtText yDim = m_plot->axisTitle(QwtPlot::yLeft);
-      return yDim.text().toStdString();
-    }
+std::string PeakOverlayViewFactoryBase::getPlotYLabel() const {
+  QwtText yDim = m_plot->axisTitle(QwtPlot::yLeft);
+  return yDim.text().toStdString();
+}
 
-    PeakOverlayViewFactoryBase::~PeakOverlayViewFactoryBase()
-    {
-    }
-  }
+PeakOverlayViewFactoryBase::~PeakOverlayViewFactoryBase() {}
+}
 }
diff --git a/MantidQt/SliceViewer/src/PeakPalette.cpp b/MantidQt/SliceViewer/src/PeakPalette.cpp
index 949582e931f15928a01c2f3bf8fdd18c165f0680..3e7123165e064710775f176d6e22adc30f397274 100644
--- a/MantidQt/SliceViewer/src/PeakPalette.cpp
+++ b/MantidQt/SliceViewer/src/PeakPalette.cpp
@@ -5,57 +5,53 @@
 #include <sstream>
 #include <stdexcept>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-template <> PeakPalette<QColor>::PeakPalette()
-{
-    m_foregroundMap = {{0, {"#bf7651"}},
-                       {1, {"#bd97cb"}},
-                       {2, {"#ceeeea"}},
-                       {3, {"#da4a52"}},
-                       {4, {"#9bc888"}},
-                       {5, {"#ffe181"}},
-                       {6, {"#e8b7c1"}},
-                       {7, {"#f38235"}},
-                       {8, {"#8390c6"}},
-                       {9, {"#4ca0ac"}}};
-    m_backgroundMap = {{0, {"#bf7651"}},
-                       {1, {"#bd97cb"}},
-                       {2, {"#ceeeea"}},
-                       {3, {"#da4a52"}},
-                       {4, {"#9bc888"}},
-                       {5, {"#ffe181"}},
-                       {6, {"#e8b7c1"}},
-                       {7, {"#f38235"}},
-                       {8, {"#8390c6"}},
-                       {9, {"#4ca0ac"}}};
+namespace MantidQt {
+namespace SliceViewer {
+template <> PeakPalette<QColor>::PeakPalette() {
+  m_foregroundMap = {{0, {"#bf7651"}},
+                     {1, {"#bd97cb"}},
+                     {2, {"#ceeeea"}},
+                     {3, {"#da4a52"}},
+                     {4, {"#9bc888"}},
+                     {5, {"#ffe181"}},
+                     {6, {"#e8b7c1"}},
+                     {7, {"#f38235"}},
+                     {8, {"#8390c6"}},
+                     {9, {"#4ca0ac"}}};
+  m_backgroundMap = {{0, {"#bf7651"}},
+                     {1, {"#bd97cb"}},
+                     {2, {"#ceeeea"}},
+                     {3, {"#da4a52"}},
+                     {4, {"#9bc888"}},
+                     {5, {"#ffe181"}},
+                     {6, {"#e8b7c1"}},
+                     {7, {"#f38235"}},
+                     {8, {"#8390c6"}},
+                     {9, {"#4ca0ac"}}};
 }
 
-template <> PeakPalette<PeakViewColor>::PeakPalette()
-{
-    m_foregroundMap = {{0, {"#bf7651", "#bf7651", "#bf7651"}},
-                       {1, {"#bd97cb", "#bd97cb", "#bd97cb"}},
-                       {2, {"#ceeeea", "#ceeeea", "#ceeeea"}},
-                       {3, {"#da4a52", "#bd97cb", "#bd97cb"}},
-                       {4, {"#9bc888", "#9bc888", "#9bc888"}},
-                       {5, {"#ffe181", "#ffe181", "#ffe181"}},
-                       {6, {"#e8b7c1", "#e8b7c1", "#e8b7c1"}},
-                       {7, {"#f38235", "#f38235", "#f38235"}},
-                       {8, {"#8390c6", "#8390c6", "#8390c6"}},
-                       {9, {"#4ca0ac", "#4ca0ac", "#4ca0ac"}}};
+template <> PeakPalette<PeakViewColor>::PeakPalette() {
+  m_foregroundMap = {{0, {"#bf7651", "#bf7651", "#bf7651"}},
+                     {1, {"#bd97cb", "#bd97cb", "#bd97cb"}},
+                     {2, {"#ceeeea", "#ceeeea", "#ceeeea"}},
+                     {3, {"#da4a52", "#bd97cb", "#bd97cb"}},
+                     {4, {"#9bc888", "#9bc888", "#9bc888"}},
+                     {5, {"#ffe181", "#ffe181", "#ffe181"}},
+                     {6, {"#e8b7c1", "#e8b7c1", "#e8b7c1"}},
+                     {7, {"#f38235", "#f38235", "#f38235"}},
+                     {8, {"#8390c6", "#8390c6", "#8390c6"}},
+                     {9, {"#4ca0ac", "#4ca0ac", "#4ca0ac"}}};
 
-    m_backgroundMap = {{0, {"#bf7651", "#bf7651", "#bf7651"}},
-                       {1, {"#bd97cb", "#bd97cb", "#bd97cb"}},
-                       {2, {"#ceeeea", "#ceeeea", "#ceeeea"}},
-                       {3, {"#da4a52", "#da4a52", "#da4a52"}},
-                       {4, {"#9bc888", "#9bc888", "#9bc888"}},
-                       {5, {"#ffe181", "#ffe181", "#ffe181"}},
-                       {6, {"#e8b7c1", "#e8b7c1", "#e8b7c1"}},
-                       {7, {"#f38235", "#f38235", "#f38235"}},
-                       {8, {"#8390c6", "#8390c6", "#8390c6"}},
-                       {9, {"#4ca0ac", "#4ca0ac", "#4ca0ac"}}};
+  m_backgroundMap = {{0, {"#bf7651", "#bf7651", "#bf7651"}},
+                     {1, {"#bd97cb", "#bd97cb", "#bd97cb"}},
+                     {2, {"#ceeeea", "#ceeeea", "#ceeeea"}},
+                     {3, {"#da4a52", "#da4a52", "#da4a52"}},
+                     {4, {"#9bc888", "#9bc888", "#9bc888"}},
+                     {5, {"#ffe181", "#ffe181", "#ffe181"}},
+                     {6, {"#e8b7c1", "#e8b7c1", "#e8b7c1"}},
+                     {7, {"#f38235", "#f38235", "#f38235"}},
+                     {8, {"#8390c6", "#8390c6", "#8390c6"}},
+                     {9, {"#4ca0ac", "#4ca0ac", "#4ca0ac"}}};
 }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakRepresentation.cpp b/MantidQt/SliceViewer/src/PeakRepresentation.cpp
index 79dfd05df41b7ed195bb6e053dcd5432451f6130..9e5ca5c382b84023f543582e60bd32773a4778ac 100644
--- a/MantidQt/SliceViewer/src/PeakRepresentation.cpp
+++ b/MantidQt/SliceViewer/src/PeakRepresentation.cpp
@@ -2,10 +2,8 @@
 #include "MantidQtSliceViewer/PeakViewColor.h"
 #include <QPainter>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 /**
  * Template method which draws a peaks representation
@@ -15,16 +13,16 @@ namespace SliceViewer
  * @param viewInformation: information about the view into which the peak is
  * drawn
  */
-void PeakRepresentation::draw(QPainter &painter, PeakViewColor &foregroundColor,
-                              PeakViewColor &backgroundColor,
-                              PeakRepresentationViewInformation viewInformation)
-{
-    // Setup the drawing information, eg positions, radii ...
-    auto drawingInformation = getDrawingInformation(viewInformation);
+void PeakRepresentation::draw(
+    QPainter &painter, PeakViewColor &foregroundColor,
+    PeakViewColor &backgroundColor,
+    PeakRepresentationViewInformation viewInformation) {
+  // Setup the drawing information, eg positions, radii ...
+  auto drawingInformation = getDrawingInformation(viewInformation);
 
-    // Draw
-    doDraw(painter, foregroundColor, backgroundColor, drawingInformation,
-           viewInformation);
+  // Draw
+  doDraw(painter, foregroundColor, backgroundColor, drawingInformation,
+         viewInformation);
 }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakRepresentationCross.cpp b/MantidQt/SliceViewer/src/PeakRepresentationCross.cpp
index 373ab8a94e030e68deed2d948e639add6fa95d04..6250bec6fa953c2aba1ef4e4d1e5f5ad76b9bce2 100644
--- a/MantidQt/SliceViewer/src/PeakRepresentationCross.cpp
+++ b/MantidQt/SliceViewer/src/PeakRepresentationCross.cpp
@@ -5,34 +5,30 @@
 #include "MantidKernel/V2D.h"
 #include <QPainter>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 PeakRepresentationCross::PeakRepresentationCross(
     const Mantid::Kernel::V3D &origin, const double &maxZ, const double &minZ)
-    :  m_intoViewFraction(0.015), m_crossViewFraction(0.015), m_originalOrigin(origin), m_origin(origin),
+    : m_intoViewFraction(0.015), m_crossViewFraction(0.015),
+      m_originalOrigin(origin), m_origin(origin),
       m_effectiveRadius((maxZ - minZ) * m_intoViewFraction), m_opacityMax(0.8),
       m_opacityMin(0.0),
       m_opacityGradient((m_opacityMin - m_opacityMax) / m_effectiveRadius),
-      m_opacityAtDistance(0.0), m_slicePoint(0.0)
-{
-}
+      m_opacityAtDistance(0.0), m_slicePoint(0.0) {}
 
 /**
  *Set the distance between the plane and the center of the peak in md
  *coordinates
  *@param z : position of the plane slice in the z dimension.
  */
-void PeakRepresentationCross::setSlicePoint(const double &z)
-{
-    m_slicePoint = z;
-    const double distanceAbs = std::abs(z - m_origin.Z());
-
-    // Apply a linear transform to convert from a distance to an opacity between
-    // opacityMin and opacityMax.
-    m_opacityAtDistance = (m_opacityGradient * distanceAbs) + m_opacityMax;
+void PeakRepresentationCross::setSlicePoint(const double &z) {
+  m_slicePoint = z;
+  const double distanceAbs = std::abs(z - m_origin.Z());
+
+  // Apply a linear transform to convert from a distance to an opacity between
+  // opacityMin and opacityMax.
+  m_opacityAtDistance = (m_opacityGradient * distanceAbs) + m_opacityMax;
 }
 
 /**
@@ -40,123 +36,111 @@ void PeakRepresentationCross::setSlicePoint(const double &z)
  * @param peakTransform : Tranform to use.
  */
 void PeakRepresentationCross::movePosition(
-    Mantid::Geometry::PeakTransform_sptr peakTransform)
-{
-    m_origin = peakTransform->transform(m_originalOrigin);
+    Mantid::Geometry::PeakTransform_sptr peakTransform) {
+  m_origin = peakTransform->transform(m_originalOrigin);
 }
 
 /**
  *
  *@return bounding box for peak in natural coordinates.
  */
-PeakBoundingBox PeakRepresentationCross::getBoundingBox() const
-{
-    using Mantid::Kernel::V2D;
-    const Left left(m_origin.X() - m_effectiveRadius);
-    const Right right(m_origin.X() + m_effectiveRadius);
-    const Bottom bottom(m_origin.Y() - m_effectiveRadius);
-    const Top top(m_origin.Y() + m_effectiveRadius);
-    const SlicePoint slicePoint(m_origin.Z());
-
-    return PeakBoundingBox(left, right, top, bottom, slicePoint);
+PeakBoundingBox PeakRepresentationCross::getBoundingBox() const {
+  using Mantid::Kernel::V2D;
+  const Left left(m_origin.X() - m_effectiveRadius);
+  const Right right(m_origin.X() + m_effectiveRadius);
+  const Bottom bottom(m_origin.Y() - m_effectiveRadius);
+  const Top top(m_origin.Y() + m_effectiveRadius);
+  const SlicePoint slicePoint(m_origin.Z());
+
+  return PeakBoundingBox(left, right, top, bottom, slicePoint);
 }
 
-void PeakRepresentationCross::setOccupancyInView(const double fraction)
-{
-    m_crossViewFraction = fraction;
-    setSlicePoint(m_slicePoint);
+void PeakRepresentationCross::setOccupancyInView(const double fraction) {
+  m_crossViewFraction = fraction;
+  setSlicePoint(m_slicePoint);
 }
 
-void PeakRepresentationCross::setOccupancyIntoView(const double fraction)
-{
-    if (fraction != 0) {
-        m_effectiveRadius *= (fraction / m_intoViewFraction);
-        m_intoViewFraction = fraction;
-        setSlicePoint(m_slicePoint);
-    }
+void PeakRepresentationCross::setOccupancyIntoView(const double fraction) {
+  if (fraction != 0) {
+    m_effectiveRadius *= (fraction / m_intoViewFraction);
+    m_intoViewFraction = fraction;
+    setSlicePoint(m_slicePoint);
+  }
 }
 
 /**
  * Gets the effective peak radius of the cross representation
  * @return the effective radis
  */
-double PeakRepresentationCross::getEffectiveRadius() const
-{
-    return m_effectiveRadius;
+double PeakRepresentationCross::getEffectiveRadius() const {
+  return m_effectiveRadius;
 }
 
 std::shared_ptr<PeakPrimitives> PeakRepresentationCross::getDrawingInformation(
-    PeakRepresentationViewInformation viewInformation)
-{
-    auto drawingInformation = std::make_shared<PeakPrimitivesCross>(
-        Mantid::Kernel::V3D() /*Peak Origin*/, 0.0 /*peakOpacityAtDistance*/,
-        0 /*peakHalfCrossWidth*/, 0 /*peakHalfCrossHeight*/,
-        0 /*peakLineWidth*/);
-
-    const auto halfCrossHeight
-        = static_cast<int>(viewInformation.windowHeight * m_crossViewFraction);
-    const auto halfCrossWidth
-        = static_cast<int>(viewInformation.windowWidth * m_crossViewFraction);
-
-    drawingInformation->peakHalfCrossHeight = halfCrossHeight;
-    drawingInformation->peakHalfCrossWidth = halfCrossWidth;
-    drawingInformation->peakLineWidth = 2;
-    drawingInformation->peakOpacityAtDistance = m_opacityAtDistance;
-    drawingInformation->peakOrigin = m_origin;
-
-    return drawingInformation;
+    PeakRepresentationViewInformation viewInformation) {
+  auto drawingInformation = std::make_shared<PeakPrimitivesCross>(
+      Mantid::Kernel::V3D() /*Peak Origin*/, 0.0 /*peakOpacityAtDistance*/,
+      0 /*peakHalfCrossWidth*/, 0 /*peakHalfCrossHeight*/, 0 /*peakLineWidth*/);
+
+  const auto halfCrossHeight =
+      static_cast<int>(viewInformation.windowHeight * m_crossViewFraction);
+  const auto halfCrossWidth =
+      static_cast<int>(viewInformation.windowWidth * m_crossViewFraction);
+
+  drawingInformation->peakHalfCrossHeight = halfCrossHeight;
+  drawingInformation->peakHalfCrossWidth = halfCrossWidth;
+  drawingInformation->peakLineWidth = 2;
+  drawingInformation->peakOpacityAtDistance = m_opacityAtDistance;
+  drawingInformation->peakOrigin = m_origin;
+
+  return drawingInformation;
 }
 
-void PeakRepresentationCross::doDraw(QPainter &painter, PeakViewColor &foregroundColor, PeakViewColor &,
+void PeakRepresentationCross::doDraw(
+    QPainter &painter, PeakViewColor &foregroundColor, PeakViewColor &,
     std::shared_ptr<PeakPrimitives> drawingInformation,
-    PeakRepresentationViewInformation viewInformation)
-{
-    auto drawingInformationCross
-        = std::static_pointer_cast<PeakPrimitivesCross>(drawingInformation);
-
-    // Setup the QPainter
-    painter.setRenderHint(QPainter::Antialiasing);
-
-    // Add a pen with color, style and stroke
-    auto foregroundColorCross = foregroundColor.colorCross;
-
-    QPen pen(foregroundColorCross);
-    pen.setWidth(drawingInformationCross->peakLineWidth);
-    pen.setStyle(Qt::SolidLine);
-    painter.setPen(pen);
-
-    painter.setOpacity(drawingInformationCross->peakOpacityAtDistance);
-
-    // Creat the actual lines and have them drawn by the painter
-    const int halfCrossHeight = drawingInformationCross->peakHalfCrossHeight;
-    const int halfCrossWidth = drawingInformationCross->peakHalfCrossWidth;
-
-    const auto xOriginWindow = viewInformation.xOriginWindow;
-    const auto yOriginWindow = viewInformation.yOriginWindow;
-
-    QPoint bottomL(xOriginWindow - halfCrossWidth,
-                   yOriginWindow - halfCrossHeight);
-    QPoint bottomR(xOriginWindow + halfCrossWidth,
-                   yOriginWindow - halfCrossHeight);
-    QPoint topL(xOriginWindow - halfCrossWidth,
-                yOriginWindow + halfCrossHeight);
-    QPoint topR(xOriginWindow + halfCrossWidth,
-                yOriginWindow + halfCrossHeight);
-
-    painter.drawLine(bottomL, topR);
-    painter.drawLine(bottomR, topL);
-    painter.end();
+    PeakRepresentationViewInformation viewInformation) {
+  auto drawingInformationCross =
+      std::static_pointer_cast<PeakPrimitivesCross>(drawingInformation);
+
+  // Setup the QPainter
+  painter.setRenderHint(QPainter::Antialiasing);
+
+  // Add a pen with color, style and stroke
+  auto foregroundColorCross = foregroundColor.colorCross;
+
+  QPen pen(foregroundColorCross);
+  pen.setWidth(drawingInformationCross->peakLineWidth);
+  pen.setStyle(Qt::SolidLine);
+  painter.setPen(pen);
+
+  painter.setOpacity(drawingInformationCross->peakOpacityAtDistance);
+
+  // Creat the actual lines and have them drawn by the painter
+  const int halfCrossHeight = drawingInformationCross->peakHalfCrossHeight;
+  const int halfCrossWidth = drawingInformationCross->peakHalfCrossWidth;
+
+  const auto xOriginWindow = viewInformation.xOriginWindow;
+  const auto yOriginWindow = viewInformation.yOriginWindow;
+
+  QPoint bottomL(xOriginWindow - halfCrossWidth,
+                 yOriginWindow - halfCrossHeight);
+  QPoint bottomR(xOriginWindow + halfCrossWidth,
+                 yOriginWindow - halfCrossHeight);
+  QPoint topL(xOriginWindow - halfCrossWidth, yOriginWindow + halfCrossHeight);
+  QPoint topR(xOriginWindow + halfCrossWidth, yOriginWindow + halfCrossHeight);
+
+  painter.drawLine(bottomL, topR);
+  painter.drawLine(bottomR, topL);
+  painter.end();
 }
 
-const Mantid::Kernel::V3D &PeakRepresentationCross::getOrigin() const
-{
-    return m_origin;
+const Mantid::Kernel::V3D &PeakRepresentationCross::getOrigin() const {
+  return m_origin;
 }
 
 void PeakRepresentationCross::showBackgroundRadius(const bool) {
   // Do nothing
 }
-
-
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakRepresentationEllipsoid.cpp b/MantidQt/SliceViewer/src/PeakRepresentationEllipsoid.cpp
index 8023202abfce775dd60d003df19fe24ad283006d..de2d0a5d18c91e8abd17e60ed7f41f5499b430b0 100644
--- a/MantidQt/SliceViewer/src/PeakRepresentationEllipsoid.cpp
+++ b/MantidQt/SliceViewer/src/PeakRepresentationEllipsoid.cpp
@@ -218,16 +218,14 @@ std::shared_ptr<PeakPrimitives>
   if (this->m_showBackgroundRadii) {
     if (m_radiiEllipseBackgroundOuter.size() > 0) {
       drawingInformation->backgroundOuterRadiusMajorAxis =
-        m_radiiEllipseBackgroundOuter[0];
+          m_radiiEllipseBackgroundOuter[0];
       drawingInformation->backgroundOuterRadiusMinorAxis =
-        m_radiiEllipseBackgroundOuter[1];
-    }
-    else {
+          m_radiiEllipseBackgroundOuter[1];
+    } else {
       drawingInformation->backgroundOuterRadiusMajorAxis = zeroRadius;
       drawingInformation->backgroundOuterRadiusMinorAxis = zeroRadius;
     }
 
-
     // Add inner backgroudn radius if it is available. It might be that only a
     // cut through the outer
     // background radius exists
@@ -295,33 +293,37 @@ void PeakRepresentationEllipsoid::doDraw(
   }
 
   if (m_showBackgroundRadii) {
-    if (drawingInformationEllipse->backgroundOuterRadiusMajorAxis != zeroRadius &&
-        drawingInformationEllipse->backgroundOuterRadiusMinorAxis != zeroRadius &&
-        drawingInformationEllipse->backgroundInnerRadiusMajorAxis != zeroRadius &&
-        drawingInformationEllipse->backgroundInnerRadiusMinorAxis != zeroRadius) {
+    if (drawingInformationEllipse->backgroundOuterRadiusMajorAxis !=
+            zeroRadius &&
+        drawingInformationEllipse->backgroundOuterRadiusMinorAxis !=
+            zeroRadius &&
+        drawingInformationEllipse->backgroundInnerRadiusMajorAxis !=
+            zeroRadius &&
+        drawingInformationEllipse->backgroundInnerRadiusMinorAxis !=
+            zeroRadius) {
       // Outer demarcation of the fill
       QPainterPath backgroundOuterPath;
       backgroundOuterPath.setFillRule(Qt::WindingFill);
       backgroundOuterPath.addEllipse(
-        zeroPoint, drawingInformationEllipse->backgroundOuterRadiusMajorAxis,
-        drawingInformationEllipse->backgroundOuterRadiusMinorAxis);
+          zeroPoint, drawingInformationEllipse->backgroundOuterRadiusMajorAxis,
+          drawingInformationEllipse->backgroundOuterRadiusMinorAxis);
       auto transformedBackgroundOuterPath = getTransformedPainterPath(
-        drawingInformationEllipse->angle, viewInformation.xOriginWindow,
-        viewInformation.yOriginWindow, scaleX, scaleY, backgroundOuterPath);
+          drawingInformationEllipse->angle, viewInformation.xOriginWindow,
+          viewInformation.yOriginWindow, scaleX, scaleY, backgroundOuterPath);
 
       // Inner demarcation of the fill
       QPainterPath backgroundInnerPath;
       backgroundInnerPath.addEllipse(
-        zeroPoint, drawingInformationEllipse->backgroundInnerRadiusMajorAxis,
-        drawingInformationEllipse->backgroundInnerRadiusMinorAxis);
+          zeroPoint, drawingInformationEllipse->backgroundInnerRadiusMajorAxis,
+          drawingInformationEllipse->backgroundInnerRadiusMinorAxis);
       auto transformedBackgroundInnerPath = getTransformedPainterPath(
-        drawingInformationEllipse->angle, viewInformation.xOriginWindow,
-        viewInformation.yOriginWindow, scaleX, scaleY, backgroundInnerPath);
+          drawingInformationEllipse->angle, viewInformation.xOriginWindow,
+          viewInformation.yOriginWindow, scaleX, scaleY, backgroundInnerPath);
 
       // Subtract inner fill from outer fill
       QPainterPath backgroundRadiusFill =
-        transformedBackgroundOuterPath.subtracted(
-          transformedBackgroundInnerPath);
+          transformedBackgroundOuterPath.subtracted(
+              transformedBackgroundInnerPath);
 
       painter.fillPath(backgroundRadiusFill, backgroundColor.colorEllipsoid);
     }
diff --git a/MantidQt/SliceViewer/src/PeakRepresentationSphere.cpp b/MantidQt/SliceViewer/src/PeakRepresentationSphere.cpp
index 8f514771e89dfb3135b6a85c38bff3874cb2cd54..2b02df83e99f98525e52d124a7374129ff30324e 100644
--- a/MantidQt/SliceViewer/src/PeakRepresentationSphere.cpp
+++ b/MantidQt/SliceViewer/src/PeakRepresentationSphere.cpp
@@ -4,10 +4,8 @@
 
 #include <QPainter>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 PeakRepresentationSphere::PeakRepresentationSphere(
     const Mantid::Kernel::V3D &origin, const double &peakRadius,
@@ -22,13 +20,12 @@ PeakRepresentationSphere::PeakRepresentationSphere(
       m_peakRadiusSQ(m_peakRadius * m_peakRadius),
       m_backgroundInnerRadiusSQ(backgroundInnerRadius * backgroundInnerRadius),
       m_backgroundOuterRadiusSQ(backgroundOuterRadius * backgroundOuterRadius),
-      m_showBackgroundRadius(false)
-{
-    // This possibility can arise from IntegratePeaksMD.
-    if (m_backgroundOuterRadiusSQ <= m_backgroundInnerRadiusSQ) {
-        m_backgroundOuterRadius = m_backgroundInnerRadius;
-        m_backgroundOuterRadiusSQ = m_backgroundInnerRadiusSQ;
-    }
+      m_showBackgroundRadius(false) {
+  // This possibility can arise from IntegratePeaksMD.
+  if (m_backgroundOuterRadiusSQ <= m_backgroundInnerRadiusSQ) {
+    m_backgroundOuterRadius = m_backgroundInnerRadius;
+    m_backgroundOuterRadiusSQ = m_backgroundInnerRadiusSQ;
+  }
 }
 
 //----------------------------------------------------------------------------------------------
@@ -53,26 +50,25 @@ apply.
     \           /
      \---------/
 */
-void PeakRepresentationSphere::setSlicePoint(const double &z)
-{
-    const double distance = z - m_origin.Z();
-    const double distanceSQ = distance * distance;
-
-    if (distanceSQ <= m_backgroundOuterRadiusSQ) {
-        const double distanceAbs = std::sqrt(distanceSQ);
-        m_peakRadiusAtDistance = std::sqrt(m_peakRadiusSQ - distanceSQ);
-        m_backgroundInnerRadiusAtDistance
-            = std::sqrt(m_backgroundInnerRadiusSQ - distanceSQ);
-        m_backgroundOuterRadiusAtDistance
-            = std::sqrt(m_backgroundOuterRadiusSQ - distanceSQ);
-        // Apply a linear transform to convert from a distance to an opacity
-        // between opacityMin and opacityMax.
-        m_cachedOpacityAtDistance = m_cachedOpacityGradient * distanceAbs
-                                    + m_opacityMax;
-    } else {
-        m_cachedOpacityAtDistance = m_opacityMin;
-        m_backgroundOuterRadiusAtDistance.reset();
-    }
+void PeakRepresentationSphere::setSlicePoint(const double &z) {
+  const double distance = z - m_origin.Z();
+  const double distanceSQ = distance * distance;
+
+  if (distanceSQ <= m_backgroundOuterRadiusSQ) {
+    const double distanceAbs = std::sqrt(distanceSQ);
+    m_peakRadiusAtDistance = std::sqrt(m_peakRadiusSQ - distanceSQ);
+    m_backgroundInnerRadiusAtDistance =
+        std::sqrt(m_backgroundInnerRadiusSQ - distanceSQ);
+    m_backgroundOuterRadiusAtDistance =
+        std::sqrt(m_backgroundOuterRadiusSQ - distanceSQ);
+    // Apply a linear transform to convert from a distance to an opacity
+    // between opacityMin and opacityMax.
+    m_cachedOpacityAtDistance =
+        m_cachedOpacityGradient * distanceAbs + m_opacityMax;
+  } else {
+    m_cachedOpacityAtDistance = m_opacityMin;
+    m_backgroundOuterRadiusAtDistance.reset();
+  }
 }
 
 /**
@@ -80,139 +76,126 @@ void PeakRepresentationSphere::setSlicePoint(const double &z)
  *@param peakTransform : transform to use.
  */
 void PeakRepresentationSphere::movePosition(
-    Mantid::Geometry::PeakTransform_sptr peakTransform)
-{
-    m_origin = peakTransform->transform(m_originalOrigin);
+    Mantid::Geometry::PeakTransform_sptr peakTransform) {
+  m_origin = peakTransform->transform(m_originalOrigin);
 }
 
 /**
  * Setter for showing/hiding the background radius.
  * @param show: Flag indicating what to do.
 */
-void PeakRepresentationSphere::showBackgroundRadius(const bool show)
-{
-    m_showBackgroundRadius = show;
+void PeakRepresentationSphere::showBackgroundRadius(const bool show) {
+  m_showBackgroundRadius = show;
 }
 
 /**
  *@return bounding box for peak in natural coordinates.
  */
-PeakBoundingBox PeakRepresentationSphere::getBoundingBox() const
-{
-    using Mantid::Kernel::V2D;
-    Left left(m_origin.X() - m_backgroundOuterRadius);
-    Bottom bottom(m_origin.Y() - m_backgroundOuterRadius);
-    Right right(m_origin.X() + m_backgroundOuterRadius);
-    Top top(m_origin.Y() + m_backgroundOuterRadius);
-    SlicePoint slicePoint(m_origin.Z());
-
-    return PeakBoundingBox(left, right, top, bottom, slicePoint);
+PeakBoundingBox PeakRepresentationSphere::getBoundingBox() const {
+  using Mantid::Kernel::V2D;
+  Left left(m_origin.X() - m_backgroundOuterRadius);
+  Bottom bottom(m_origin.Y() - m_backgroundOuterRadius);
+  Right right(m_origin.X() + m_backgroundOuterRadius);
+  Top top(m_origin.Y() + m_backgroundOuterRadius);
+  SlicePoint slicePoint(m_origin.Z());
+
+  return PeakBoundingBox(left, right, top, bottom, slicePoint);
 }
 
-double PeakRepresentationSphere::getEffectiveRadius() const
-{
-    return m_showBackgroundRadius ? m_backgroundOuterRadius : m_peakRadius;
+double PeakRepresentationSphere::getEffectiveRadius() const {
+  return m_showBackgroundRadius ? m_backgroundOuterRadius : m_peakRadius;
 }
 
-void PeakRepresentationSphere::setOccupancyInView(const double)
-{
-    // DO NOTHING
+void PeakRepresentationSphere::setOccupancyInView(const double) {
+  // DO NOTHING
 }
 
-void PeakRepresentationSphere::setOccupancyIntoView(const double)
-{
-    // DO NOTHING
+void PeakRepresentationSphere::setOccupancyIntoView(const double) {
+  // DO NOTHING
 }
 
-const Mantid::Kernel::V3D &PeakRepresentationSphere::getOrigin() const
-{
-    return m_origin;
+const Mantid::Kernel::V3D &PeakRepresentationSphere::getOrigin() const {
+  return m_origin;
 }
 
 std::shared_ptr<PeakPrimitives> PeakRepresentationSphere::getDrawingInformation(
-    PeakRepresentationViewInformation viewInformation)
-{
-    auto drawingInformation = std::make_shared<PeakPrimitiveCircle>(
-        Mantid::Kernel::V3D() /*Peak Origin*/, 0.0 /*peakOpacityAtDistance*/,
-        0 /* PeakLineWidth */, 0.0 /*peakInnerRadiusX*/,
-        0.0 /*peakInnerRadiusY*/, 0.0 /*backgroundOuterRadiusX*/,
-        0.0 /*backgroundOuterRadiusY*/, 0.0 /*backgroundInnerRadiusX*/,
-        0.0 /*backgroundInnerRadiusY*/);
-
-    // Scale factor for going from viewX to windowX
-    const auto scaleY = viewInformation.windowHeight
-                        / viewInformation.viewHeight;
-    // Scale factor for going from viewY to windowY
-    const auto scaleX = viewInformation.windowWidth / viewInformation.viewWidth;
-
-    // Add the innder radius
-    drawingInformation->peakInnerRadiusX = scaleX
-                                           * m_peakRadiusAtDistance.get();
-    drawingInformation->peakInnerRadiusY = scaleY
-                                           * m_peakRadiusAtDistance.get();
-
-    // If the outer radius is selected, then add the outer radius
-    if (this->m_showBackgroundRadius) {
-        drawingInformation->backgroundOuterRadiusX
-            = scaleX * m_backgroundOuterRadiusAtDistance.get();
-        drawingInformation->backgroundOuterRadiusY
-            = scaleY * m_backgroundOuterRadiusAtDistance.get();
-        drawingInformation->backgroundInnerRadiusX
-            = scaleX * m_backgroundInnerRadiusAtDistance.get();
-        drawingInformation->backgroundInnerRadiusY
-            = scaleY * m_backgroundInnerRadiusAtDistance.get();
-    }
-
-    drawingInformation->peakLineWidth = 2;
-    drawingInformation->peakOpacityAtDistance = m_cachedOpacityAtDistance;
-    drawingInformation->peakOrigin = m_origin;
-
-    return drawingInformation;
+    PeakRepresentationViewInformation viewInformation) {
+  auto drawingInformation = std::make_shared<PeakPrimitiveCircle>(
+      Mantid::Kernel::V3D() /*Peak Origin*/, 0.0 /*peakOpacityAtDistance*/,
+      0 /* PeakLineWidth */, 0.0 /*peakInnerRadiusX*/, 0.0 /*peakInnerRadiusY*/,
+      0.0 /*backgroundOuterRadiusX*/, 0.0 /*backgroundOuterRadiusY*/,
+      0.0 /*backgroundInnerRadiusX*/, 0.0 /*backgroundInnerRadiusY*/);
+
+  // Scale factor for going from viewX to windowX
+  const auto scaleY = viewInformation.windowHeight / viewInformation.viewHeight;
+  // Scale factor for going from viewY to windowY
+  const auto scaleX = viewInformation.windowWidth / viewInformation.viewWidth;
+
+  // Add the innder radius
+  drawingInformation->peakInnerRadiusX = scaleX * m_peakRadiusAtDistance.get();
+  drawingInformation->peakInnerRadiusY = scaleY * m_peakRadiusAtDistance.get();
+
+  // If the outer radius is selected, then add the outer radius
+  if (this->m_showBackgroundRadius) {
+    drawingInformation->backgroundOuterRadiusX =
+        scaleX * m_backgroundOuterRadiusAtDistance.get();
+    drawingInformation->backgroundOuterRadiusY =
+        scaleY * m_backgroundOuterRadiusAtDistance.get();
+    drawingInformation->backgroundInnerRadiusX =
+        scaleX * m_backgroundInnerRadiusAtDistance.get();
+    drawingInformation->backgroundInnerRadiusY =
+        scaleY * m_backgroundInnerRadiusAtDistance.get();
+  }
+
+  drawingInformation->peakLineWidth = 2;
+  drawingInformation->peakOpacityAtDistance = m_cachedOpacityAtDistance;
+  drawingInformation->peakOrigin = m_origin;
+
+  return drawingInformation;
 }
 
 void PeakRepresentationSphere::doDraw(
     QPainter &painter, PeakViewColor &foregroundColor,
     PeakViewColor &backgroundColor,
     std::shared_ptr<PeakPrimitives> drawingInformation,
-    PeakRepresentationViewInformation viewInformation)
-{
-    auto drawingInformationSphere
-        = std::static_pointer_cast<PeakPrimitiveCircle>(drawingInformation);
-
-    // Setup the QPainter
-    painter.setRenderHint(QPainter::Antialiasing);
-    painter.setOpacity(drawingInformationSphere->peakOpacityAtDistance);
-
-    // Add a pen with color, style and stroke, and a painter path
-    auto foregroundColorSphere = foregroundColor.colorSphere;
-    QPainterPath peakRadiusInnerPath;
-    const QPointF originWindows(viewInformation.xOriginWindow,
-                                viewInformation.yOriginWindow);
-    peakRadiusInnerPath.addEllipse(originWindows,
-                                   drawingInformationSphere->peakInnerRadiusX,
-                                   drawingInformationSphere->peakInnerRadiusY);
-
-    QPen pen(foregroundColorSphere);
-    pen.setWidth(drawingInformationSphere->peakLineWidth);
-    pen.setStyle(Qt::DashLine);
-    painter.strokePath(peakRadiusInnerPath, pen);
-
-    // Draw the background if this is requested
-    if (m_showBackgroundRadius) {
-        QPainterPath backgroundOuterPath;
-        backgroundOuterPath.setFillRule(Qt::WindingFill);
-        backgroundOuterPath.addEllipse(
-            originWindows, drawingInformationSphere->backgroundOuterRadiusX,
-            drawingInformationSphere->backgroundOuterRadiusY);
-        QPainterPath backgroundInnerPath;
-        backgroundInnerPath.addEllipse(
-            originWindows, drawingInformationSphere->backgroundInnerRadiusX,
-            drawingInformationSphere->backgroundInnerRadiusY);
-        QPainterPath backgroundRadiusFill
-            = backgroundOuterPath.subtracted(backgroundInnerPath);
-        painter.fillPath(backgroundRadiusFill, backgroundColor.colorSphere);
-    }
-    painter.end();
+    PeakRepresentationViewInformation viewInformation) {
+  auto drawingInformationSphere =
+      std::static_pointer_cast<PeakPrimitiveCircle>(drawingInformation);
+
+  // Setup the QPainter
+  painter.setRenderHint(QPainter::Antialiasing);
+  painter.setOpacity(drawingInformationSphere->peakOpacityAtDistance);
+
+  // Add a pen with color, style and stroke, and a painter path
+  auto foregroundColorSphere = foregroundColor.colorSphere;
+  QPainterPath peakRadiusInnerPath;
+  const QPointF originWindows(viewInformation.xOriginWindow,
+                              viewInformation.yOriginWindow);
+  peakRadiusInnerPath.addEllipse(originWindows,
+                                 drawingInformationSphere->peakInnerRadiusX,
+                                 drawingInformationSphere->peakInnerRadiusY);
+
+  QPen pen(foregroundColorSphere);
+  pen.setWidth(drawingInformationSphere->peakLineWidth);
+  pen.setStyle(Qt::DashLine);
+  painter.strokePath(peakRadiusInnerPath, pen);
+
+  // Draw the background if this is requested
+  if (m_showBackgroundRadius) {
+    QPainterPath backgroundOuterPath;
+    backgroundOuterPath.setFillRule(Qt::WindingFill);
+    backgroundOuterPath.addEllipse(
+        originWindows, drawingInformationSphere->backgroundOuterRadiusX,
+        drawingInformationSphere->backgroundOuterRadiusY);
+    QPainterPath backgroundInnerPath;
+    backgroundInnerPath.addEllipse(
+        originWindows, drawingInformationSphere->backgroundInnerRadiusX,
+        drawingInformationSphere->backgroundInnerRadiusY);
+    QPainterPath backgroundRadiusFill =
+        backgroundOuterPath.subtracted(backgroundInnerPath);
+    painter.fillPath(backgroundRadiusFill, backgroundColor.colorSphere);
+  }
+  painter.end();
 }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakView.cpp b/MantidQt/SliceViewer/src/PeakView.cpp
index df135661e10e3a2bcaa94d9837a2ad2715760432..5096c69d4df8c0dcc0db3bab56f6adb80da9546b 100644
--- a/MantidQt/SliceViewer/src/PeakView.cpp
+++ b/MantidQt/SliceViewer/src/PeakView.cpp
@@ -5,10 +5,8 @@
 #include <qwt_scale_div.h>
 #include <qwt_double_interval.h>
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 PeakView::PeakView(PeaksPresenter *const presenter, QwtPlot *plot,
                    QWidget *parent,
@@ -20,46 +18,42 @@ PeakView::PeakView(PeaksPresenter *const presenter, QwtPlot *plot,
       m_peaks(vecPeakRepresentation), m_cachedOccupancyIntoView(0),
       m_cachedOccupancyInView(0), m_showBackground(false),
       m_foregroundColor(foregroundColor), m_backgroundColor(backgroundColor),
-      m_largestEffectiveRadius(largestEffectiveRadius)
-{
-}
+      m_largestEffectiveRadius(largestEffectiveRadius) {}
 
 PeakView::~PeakView() {}
 
-void PeakView::doPaintPeaks(QPaintEvent *)
-{
-    const auto windowHeight = height();
-    const auto windowWidth = width();
-    const auto viewHeight
-        = m_plot->axisScaleDiv(QwtPlot::yLeft)->interval().width();
-    const auto viewWidth
-        = m_plot->axisScaleDiv(QwtPlot::xBottom)->interval().width();
-
-    for (size_t i = 0; i < m_viewablePeaks.size(); ++i) {
-        if (m_viewablePeaks[i]) {
-            QPainter painter(this);
-            // Get the peak
-            auto &peak = m_peaks[i];
-            const auto &origin = peak->getOrigin();
-
-            // Set up the view information
-            const auto xOriginWindow
-                = m_plot->transform(QwtPlot::xBottom, origin.X());
-            const auto yOriginWindow
-                = m_plot->transform(QwtPlot::yLeft, origin.Y());
-
-            PeakRepresentationViewInformation peakRepresentationViewInformation;
-            peakRepresentationViewInformation.windowHeight = windowHeight;
-            peakRepresentationViewInformation.windowWidth = windowWidth;
-            peakRepresentationViewInformation.viewHeight = viewHeight;
-            peakRepresentationViewInformation.viewWidth = viewWidth;
-            peakRepresentationViewInformation.xOriginWindow = xOriginWindow;
-            peakRepresentationViewInformation.yOriginWindow = yOriginWindow;
-
-            peak->draw(painter, m_foregroundColor, m_backgroundColor,
-                       peakRepresentationViewInformation);
-        }
+void PeakView::doPaintPeaks(QPaintEvent *) {
+  const auto windowHeight = height();
+  const auto windowWidth = width();
+  const auto viewHeight =
+      m_plot->axisScaleDiv(QwtPlot::yLeft)->interval().width();
+  const auto viewWidth =
+      m_plot->axisScaleDiv(QwtPlot::xBottom)->interval().width();
+
+  for (size_t i = 0; i < m_viewablePeaks.size(); ++i) {
+    if (m_viewablePeaks[i]) {
+      QPainter painter(this);
+      // Get the peak
+      auto &peak = m_peaks[i];
+      const auto &origin = peak->getOrigin();
+
+      // Set up the view information
+      const auto xOriginWindow =
+          m_plot->transform(QwtPlot::xBottom, origin.X());
+      const auto yOriginWindow = m_plot->transform(QwtPlot::yLeft, origin.Y());
+
+      PeakRepresentationViewInformation peakRepresentationViewInformation;
+      peakRepresentationViewInformation.windowHeight = windowHeight;
+      peakRepresentationViewInformation.windowWidth = windowWidth;
+      peakRepresentationViewInformation.viewHeight = viewHeight;
+      peakRepresentationViewInformation.viewWidth = viewWidth;
+      peakRepresentationViewInformation.xOriginWindow = xOriginWindow;
+      peakRepresentationViewInformation.yOriginWindow = yOriginWindow;
+
+      peak->draw(painter, m_foregroundColor, m_backgroundColor,
+                 peakRepresentationViewInformation);
     }
+  }
 }
 
 /** Set the distance between the plane and the center of the peak in md
@@ -69,16 +63,15 @@ coordinates
 which are viewable.
 */
 void PeakView::setSlicePoint(const double &point,
-                             const std::vector<bool> &viewablePeaks)
-{
-    m_viewablePeaks = viewablePeaks;
-    for (size_t i = 0; i < m_viewablePeaks.size(); ++i) {
-        if (m_viewablePeaks[i]) // is peak at this index visible.
-        {
-            m_peaks[i]->setSlicePoint(point);
-        }
+                             const std::vector<bool> &viewablePeaks) {
+  m_viewablePeaks = viewablePeaks;
+  for (size_t i = 0; i < m_viewablePeaks.size(); ++i) {
+    if (m_viewablePeaks[i]) // is peak at this index visible.
+    {
+      m_peaks[i]->setSlicePoint(point);
     }
-    this->update();
+  }
+  this->update();
 }
 
 void PeakView::hideView() { this->hide(); }
@@ -87,47 +80,42 @@ void PeakView::showView() { this->show(); }
 
 void PeakView::updateView() { this->update(); }
 
-void PeakView::movePosition(Mantid::Geometry::PeakTransform_sptr peakTransform)
-{
-    for (auto &peak : m_peaks) {
-        peak->movePosition(peakTransform);
-    }
+void PeakView::movePosition(
+    Mantid::Geometry::PeakTransform_sptr peakTransform) {
+  for (auto &peak : m_peaks) {
+    peak->movePosition(peakTransform);
+  }
 }
 
-void PeakView::showBackgroundRadius(const bool show)
-{
-    for (const auto &peak : m_peaks) {
-        peak->showBackgroundRadius(show);
-    }
-    m_showBackground = show;
+void PeakView::showBackgroundRadius(const bool show) {
+  for (const auto &peak : m_peaks) {
+    peak->showBackgroundRadius(show);
+  }
+  m_showBackground = show;
 }
 
-PeakBoundingBox PeakView::getBoundingBox(const int peakIndex) const
-{
-    return m_peaks[peakIndex]->getBoundingBox();
+PeakBoundingBox PeakView::getBoundingBox(const int peakIndex) const {
+  return m_peaks[peakIndex]->getBoundingBox();
 }
 
-void PeakView::changeOccupancyInView(const double fraction)
-{
-    for (const auto &peak : m_peaks) {
-        peak->setOccupancyInView(fraction);
-    }
-    m_cachedOccupancyInView = fraction;
+void PeakView::changeOccupancyInView(const double fraction) {
+  for (const auto &peak : m_peaks) {
+    peak->setOccupancyInView(fraction);
+  }
+  m_cachedOccupancyInView = fraction;
 }
 
-void PeakView::changeOccupancyIntoView(const double fraction)
-{
-    for (const auto &peak : m_peaks) {
-        peak->setOccupancyIntoView(fraction);
-    }
-    m_cachedOccupancyIntoView = fraction;
+void PeakView::changeOccupancyIntoView(const double fraction) {
+  for (const auto &peak : m_peaks) {
+    peak->setOccupancyIntoView(fraction);
+  }
+  m_cachedOccupancyIntoView = fraction;
 }
 
 double PeakView::getOccupancyInView() const { return m_cachedOccupancyInView; }
 
-double PeakView::getOccupancyIntoView() const
-{
-    return m_cachedOccupancyIntoView;
+double PeakView::getOccupancyIntoView() const {
+  return m_cachedOccupancyIntoView;
 }
 
 bool PeakView::positionOnly() const { return false; }
@@ -136,39 +124,34 @@ double PeakView::getRadius() const { return m_largestEffectiveRadius; }
 
 bool PeakView::isBackgroundShown() const { return m_showBackground; }
 
-void PeakView::takeSettingsFrom(const PeakOverlayView *const source)
-{
-    // Pass on the color settings
-    this->changeForegroundColour(source->getForegroundPeakViewColor());
-    this->changeBackgroundColour(source->getBackgroundPeakViewColor());
+void PeakView::takeSettingsFrom(const PeakOverlayView *const source) {
+  // Pass on the color settings
+  this->changeForegroundColour(source->getForegroundPeakViewColor());
+  this->changeBackgroundColour(source->getBackgroundPeakViewColor());
 
-    // Pass on the information regarding the background color - not relvant for
-    // cross-type peak
-    this->showBackgroundRadius(source->isBackgroundShown());
+  // Pass on the information regarding the background color - not relvant for
+  // cross-type peak
+  this->showBackgroundRadius(source->isBackgroundShown());
 
-    // Pass on the information which only concerns the cross-type peak
-    this->changeOccupancyIntoView(source->getOccupancyIntoView());
-    this->changeOccupancyInView(source->getOccupancyInView());
+  // Pass on the information which only concerns the cross-type peak
+  this->changeOccupancyIntoView(source->getOccupancyIntoView());
+  this->changeOccupancyInView(source->getOccupancyInView());
 }
 
-void PeakView::changeForegroundColour(const PeakViewColor peakViewColor)
-{
-    m_foregroundColor = peakViewColor;
+void PeakView::changeForegroundColour(const PeakViewColor peakViewColor) {
+  m_foregroundColor = peakViewColor;
 }
 
-void PeakView::changeBackgroundColour(const PeakViewColor peakViewColor)
-{
-    m_backgroundColor = peakViewColor;
+void PeakView::changeBackgroundColour(const PeakViewColor peakViewColor) {
+  m_backgroundColor = peakViewColor;
 }
 
-PeakViewColor PeakView::getBackgroundPeakViewColor() const
-{
-    return m_backgroundColor;
+PeakViewColor PeakView::getBackgroundPeakViewColor() const {
+  return m_backgroundColor;
 }
 
-PeakViewColor PeakView::getForegroundPeakViewColor() const
-{
-    return m_foregroundColor;
+PeakViewColor PeakView::getForegroundPeakViewColor() const {
+  return m_foregroundColor;
 }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeakViewFactory.cpp b/MantidQt/SliceViewer/src/PeakViewFactory.cpp
index 0c8516ef360444a0c04bd3ee2e97360630988ccf..8ab21ee82f1ab0dce20845d45c3de83a93aaf5ff 100644
--- a/MantidQt/SliceViewer/src/PeakViewFactory.cpp
+++ b/MantidQt/SliceViewer/src/PeakViewFactory.cpp
@@ -10,64 +10,59 @@
 #include "MantidDataObjects/PeakShapeSpherical.h"
 #include "MantidDataObjects/PeakShapeEllipsoid.h"
 
-namespace
-{
+namespace {
 struct ZMinAndMax {
-    double zMax;
-    double zMin;
+  double zMax;
+  double zMin;
 };
 
 ZMinAndMax getZMinAndMax(Mantid::API::IMDWorkspace_sptr workspace,
-                         Mantid::Geometry::PeakTransform_const_sptr transform)
-{
-    double zMax = 0.0;
-    double zMin = 0.0;
-    const auto numberOfDimensions = workspace->getNumDims();
-    for (size_t dimIndex = 0; dimIndex < numberOfDimensions; ++dimIndex) {
-        Mantid::Geometry::IMDDimension_const_sptr dimensionMappedToZ
-            = workspace->getDimension(dimIndex);
-        if (boost::regex_match(dimensionMappedToZ->getName(),
-                               transform->getFreePeakAxisRegex())) {
-            zMax = dimensionMappedToZ->getMaximum();
-            zMin = dimensionMappedToZ->getMinimum();
-            break;
-        }
+                         Mantid::Geometry::PeakTransform_const_sptr transform) {
+  double zMax = 0.0;
+  double zMin = 0.0;
+  const auto numberOfDimensions = workspace->getNumDims();
+  for (size_t dimIndex = 0; dimIndex < numberOfDimensions; ++dimIndex) {
+    Mantid::Geometry::IMDDimension_const_sptr dimensionMappedToZ =
+        workspace->getDimension(dimIndex);
+    if (boost::regex_match(dimensionMappedToZ->getName(),
+                           transform->getFreePeakAxisRegex())) {
+      zMax = dimensionMappedToZ->getMaximum();
+      zMin = dimensionMappedToZ->getMinimum();
+      break;
     }
+  }
 
-    ZMinAndMax zMinAndMax;
-    zMinAndMax.zMax = zMax;
-    zMinAndMax.zMin = zMin;
+  ZMinAndMax zMinAndMax;
+  zMinAndMax.zMax = zMax;
+  zMinAndMax.zMin = zMin;
 
-    return zMinAndMax;
+  return zMinAndMax;
 }
 
 std::vector<Mantid::Kernel::V3D> getDirectionsForEllipticalPeak(
     const Mantid::Geometry::IPeak &peak,
     const Mantid::DataObjects::PeakShapeEllipsoid &ellipticalShape,
-    const Mantid::Geometry::MDFrame &frame)
-{
-    std::vector<Mantid::Kernel::V3D> directions;
-    if (frame.name() == Mantid::Geometry::QSample::QSampleName) {
-        Mantid::Kernel::Matrix<double> goniometerMatrix
-            = peak.getGoniometerMatrix();
-        if (goniometerMatrix.Invert() != 0.0) {
-            directions
-                = ellipticalShape.getDirectionInSpecificFrame(goniometerMatrix);
-        } else {
-            directions = ellipticalShape.directions();
-        }
+    const Mantid::Geometry::MDFrame &frame) {
+  std::vector<Mantid::Kernel::V3D> directions;
+  if (frame.name() == Mantid::Geometry::QSample::QSampleName) {
+    Mantid::Kernel::Matrix<double> goniometerMatrix =
+        peak.getGoniometerMatrix();
+    if (goniometerMatrix.Invert() != 0.0) {
+      directions =
+          ellipticalShape.getDirectionInSpecificFrame(goniometerMatrix);
     } else {
-
-        directions = ellipticalShape.directions();
+      directions = ellipticalShape.directions();
     }
-    return directions;
+  } else {
+
+    directions = ellipticalShape.directions();
+  }
+  return directions;
 }
 }
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
+namespace MantidQt {
+namespace SliceViewer {
 
 PeakViewFactory::PeakViewFactory(Mantid::API::IMDWorkspace_sptr mdWS,
                                  Mantid::API::IPeaksWorkspace_sptr peaksWS,
@@ -77,143 +72,130 @@ PeakViewFactory::PeakViewFactory(Mantid::API::IMDWorkspace_sptr mdWS,
     : PeakOverlayViewFactoryBase(plot, parent, plotXIndex, plotYIndex,
                                  colorNumber),
       m_mdWS(mdWS), m_peaksWS(peaksWS),
-      m_calculator(
-          std::
-              make_shared<Mantid::SliceViewer::EllipsoidPlaneSliceCalculator>())
-{
-    setForegroundAndBackgroundColors(colorNumber);
+      m_calculator(std::make_shared<
+          Mantid::SliceViewer::EllipsoidPlaneSliceCalculator>()) {
+  setForegroundAndBackgroundColors(colorNumber);
 }
 
 PeakViewFactory::~PeakViewFactory() {}
 
 boost::shared_ptr<PeakOverlayView> PeakViewFactory::createView(
     PeaksPresenter *const presenter,
-    Mantid::Geometry::PeakTransform_const_sptr transform) const
-{
+    Mantid::Geometry::PeakTransform_const_sptr transform) const {
   double largestEffectiveRadius = 0.0;
-    VecPeakRepresentation peakRepresentations(m_peaksWS->rowCount());
-    int index = 0;
-    for (auto &peakRepresentation : peakRepresentations) {
-        const Mantid::Geometry::IPeak &peak = m_peaksWS->getPeak(index);
-        auto position = transform->transformPeak(peak);
-        peakRepresentation
-            = createSinglePeakRepresentation(peak, position, transform);
-        // Get the largest radius of the data set
-        double currentEffectiveRadius =
-            peakRepresentation->getEffectiveRadius();
-        if (currentEffectiveRadius > largestEffectiveRadius) {
-          largestEffectiveRadius = currentEffectiveRadius;
-        }
-        ++index;
+  VecPeakRepresentation peakRepresentations(m_peaksWS->rowCount());
+  int index = 0;
+  for (auto &peakRepresentation : peakRepresentations) {
+    const Mantid::Geometry::IPeak &peak = m_peaksWS->getPeak(index);
+    auto position = transform->transformPeak(peak);
+    peakRepresentation =
+        createSinglePeakRepresentation(peak, position, transform);
+    // Get the largest radius of the data set
+    double currentEffectiveRadius = peakRepresentation->getEffectiveRadius();
+    if (currentEffectiveRadius > largestEffectiveRadius) {
+      largestEffectiveRadius = currentEffectiveRadius;
     }
+    ++index;
+  }
 
-    return boost::make_shared<PeakView>(
-        presenter, m_plot, m_parent, peakRepresentations, m_plotXIndex,
-        m_plotYIndex, m_foregroundColor, m_backgroundColor, largestEffectiveRadius);
+  return boost::make_shared<PeakView>(
+      presenter, m_plot, m_parent, peakRepresentations, m_plotXIndex,
+      m_plotYIndex, m_foregroundColor, m_backgroundColor,
+      largestEffectiveRadius);
 }
 
 PeakRepresentation_sptr PeakViewFactory::createSinglePeakRepresentation(
     const Mantid::Geometry::IPeak &peak, Mantid::Kernel::V3D position,
-    Mantid::Geometry::PeakTransform_const_sptr transform) const
-{
-    // Available representations for this peaks: Cross, Sphere, Ellipsoid
-    const auto &peakShape = peak.getPeakShape();
-    const auto shapeName = peakShape.shapeName();
-
-    // Create the correct peak representation for the peak shape
-    PeakRepresentation_sptr peakRepresentation;
-    if (shapeName
-        == Mantid::DataObjects::PeakShapeSpherical::sphereShapeName()) {
-        peakRepresentation = createPeakRepresentationSphere(position, peak);
-    } else if (shapeName == Mantid::DataObjects::PeakShapeEllipsoid::
-                                ellipsoidShapeName()) {
-        peakRepresentation = createPeakRepresentationEllipsoid(position, peak);
-    } else {
-        peakRepresentation = createPeakRepresentationCross(position, transform);
-    }
-    return peakRepresentation;
+    Mantid::Geometry::PeakTransform_const_sptr transform) const {
+  // Available representations for this peaks: Cross, Sphere, Ellipsoid
+  const auto &peakShape = peak.getPeakShape();
+  const auto shapeName = peakShape.shapeName();
+
+  // Create the correct peak representation for the peak shape
+  PeakRepresentation_sptr peakRepresentation;
+  if (shapeName == Mantid::DataObjects::PeakShapeSpherical::sphereShapeName()) {
+    peakRepresentation = createPeakRepresentationSphere(position, peak);
+  } else if (shapeName ==
+             Mantid::DataObjects::PeakShapeEllipsoid::ellipsoidShapeName()) {
+    peakRepresentation = createPeakRepresentationEllipsoid(position, peak);
+  } else {
+    peakRepresentation = createPeakRepresentationCross(position, transform);
+  }
+  return peakRepresentation;
 }
 
 PeakRepresentation_sptr PeakViewFactory::createPeakRepresentationCross(
     Mantid::Kernel::V3D position,
-    Mantid::Geometry::PeakTransform_const_sptr transform) const
-{
-    const auto zMinAndMax = getZMinAndMax(m_mdWS, transform);
-    return std::make_shared<PeakRepresentationCross>(position, zMinAndMax.zMax,
-                                                     zMinAndMax.zMin);
+    Mantid::Geometry::PeakTransform_const_sptr transform) const {
+  const auto zMinAndMax = getZMinAndMax(m_mdWS, transform);
+  return std::make_shared<PeakRepresentationCross>(position, zMinAndMax.zMax,
+                                                   zMinAndMax.zMin);
 }
 
 PeakRepresentation_sptr PeakViewFactory::createPeakRepresentationSphere(
-    Mantid::Kernel::V3D position, const Mantid::Geometry::IPeak &peak) const
-{
-    const auto &shape = peak.getPeakShape();
-    const auto &sphericalShape
-        = dynamic_cast<const Mantid::DataObjects::PeakShapeSpherical &>(shape);
-
-    // Get the radius
-    const auto peakRadius = sphericalShape.radius().get();
-
-    // Get the background inner radius. If it does not exist, default to radius.
-    const auto backgroundInnerRadiusOptional
-        = sphericalShape.backgroundInnerRadius();
-    const auto backgroundInnerRadius
-        = backgroundInnerRadiusOptional.is_initialized()
-              ? backgroundInnerRadiusOptional.get()
-              : peakRadius;
-
-    // Get the background outer radius. If it does not exist, default to radius.
-    const auto backgroundOuterRadiusOptional
-        = sphericalShape.backgroundOuterRadius();
-    const auto backgroundOuterRadius
-        = backgroundOuterRadiusOptional.is_initialized()
-              ? backgroundOuterRadiusOptional.get()
-              : peakRadius;
-
-    return std::make_shared<PeakRepresentationSphere>(
-        position, peakRadius, backgroundInnerRadius, backgroundOuterRadius);
+    Mantid::Kernel::V3D position, const Mantid::Geometry::IPeak &peak) const {
+  const auto &shape = peak.getPeakShape();
+  const auto &sphericalShape =
+      dynamic_cast<const Mantid::DataObjects::PeakShapeSpherical &>(shape);
+
+  // Get the radius
+  const auto peakRadius = sphericalShape.radius().get();
+
+  // Get the background inner radius. If it does not exist, default to radius.
+  const auto backgroundInnerRadiusOptional =
+      sphericalShape.backgroundInnerRadius();
+  const auto backgroundInnerRadius =
+      backgroundInnerRadiusOptional.is_initialized()
+          ? backgroundInnerRadiusOptional.get()
+          : peakRadius;
+
+  // Get the background outer radius. If it does not exist, default to radius.
+  const auto backgroundOuterRadiusOptional =
+      sphericalShape.backgroundOuterRadius();
+  const auto backgroundOuterRadius =
+      backgroundOuterRadiusOptional.is_initialized()
+          ? backgroundOuterRadiusOptional.get()
+          : peakRadius;
+
+  return std::make_shared<PeakRepresentationSphere>(
+      position, peakRadius, backgroundInnerRadius, backgroundOuterRadius);
 }
 
 PeakRepresentation_sptr PeakViewFactory::createPeakRepresentationEllipsoid(
-    Mantid::Kernel::V3D position, const Mantid::Geometry::IPeak &peak) const
-{
-    const auto &shape = peak.getPeakShape();
-    const auto &ellipsoidShape
-        = dynamic_cast<const Mantid::DataObjects::PeakShapeEllipsoid &>(shape);
-
-    // Ellipsoidd paramters
-    const auto abcRadii = ellipsoidShape.abcRadii();
-    const auto abcRadiiBackgroundInner
-        = ellipsoidShape.abcRadiiBackgroundInner();
-    const auto abcRadiiBackgroundOuter
-        = ellipsoidShape.abcRadiiBackgroundOuter();
-
-    // Extract directions for the displayed frame
-    const auto dimension0 = m_mdWS->getDimension(0);
-    const auto &frame = dimension0->getMDFrame();
-    auto directions
-        = getDirectionsForEllipticalPeak(peak, ellipsoidShape, frame);
-
-    return std::make_shared<PeakRepresentationEllipsoid>(
-        position, abcRadii, abcRadiiBackgroundInner, abcRadiiBackgroundOuter,
-        directions, m_calculator);
+    Mantid::Kernel::V3D position, const Mantid::Geometry::IPeak &peak) const {
+  const auto &shape = peak.getPeakShape();
+  const auto &ellipsoidShape =
+      dynamic_cast<const Mantid::DataObjects::PeakShapeEllipsoid &>(shape);
+
+  // Ellipsoidd paramters
+  const auto abcRadii = ellipsoidShape.abcRadii();
+  const auto abcRadiiBackgroundInner = ellipsoidShape.abcRadiiBackgroundInner();
+  const auto abcRadiiBackgroundOuter = ellipsoidShape.abcRadiiBackgroundOuter();
+
+  // Extract directions for the displayed frame
+  const auto dimension0 = m_mdWS->getDimension(0);
+  const auto &frame = dimension0->getMDFrame();
+  auto directions = getDirectionsForEllipticalPeak(peak, ellipsoidShape, frame);
+
+  return std::make_shared<PeakRepresentationEllipsoid>(
+      position, abcRadii, abcRadiiBackgroundInner, abcRadiiBackgroundOuter,
+      directions, m_calculator);
 }
 
 void PeakViewFactory::swapPeaksWorkspace(
-    Mantid::API::IPeaksWorkspace_sptr &peaksWS)
-{
-    m_peaksWS = peaksWS;
+    Mantid::API::IPeaksWorkspace_sptr &peaksWS) {
+  m_peaksWS = peaksWS;
 }
 
 void PeakViewFactory::setForegroundAndBackgroundColors(
-    const size_t colourNumber)
-{
-    PeakPalette<PeakViewColor> defaultPalette;
-    const auto peakColourEnum = defaultPalette.foregroundIndexToColour(
-        static_cast<int>(colourNumber));
-    const auto backColourEnum = defaultPalette.backgroundIndexToColour(
-        static_cast<int>(colourNumber));
-    m_foregroundColor = peakColourEnum;
-    m_backgroundColor = backColourEnum;
+    const size_t colourNumber) {
+  PeakPalette<PeakViewColor> defaultPalette;
+  const auto peakColourEnum =
+      defaultPalette.foregroundIndexToColour(static_cast<int>(colourNumber));
+  const auto backColourEnum =
+      defaultPalette.backgroundIndexToColour(static_cast<int>(colourNumber));
+  m_foregroundColor = peakColourEnum;
+  m_backgroundColor = backColourEnum;
 }
 }
 }
diff --git a/MantidQt/SliceViewer/src/PeaksTableColumnsDialog.cpp b/MantidQt/SliceViewer/src/PeaksTableColumnsDialog.cpp
index bde8b1a41bd512e6db1f627a7af807d8becad7f5..b0b21d6d8269284aa1a6711c45edd5a30762fe66 100644
--- a/MantidQt/SliceViewer/src/PeaksTableColumnsDialog.cpp
+++ b/MantidQt/SliceViewer/src/PeaksTableColumnsDialog.cpp
@@ -4,25 +4,17 @@
 
 // REMOVE
 
-namespace MantidQt
-{
-namespace SliceViewer
-{
-
-PeaksTableColumnsDialog::PeaksTableColumnsDialog(QWidget *parent) :
-  QDialog(parent),
-  ui(new Ui::PeaksTableColumnsDialog)
-{
+namespace MantidQt {
+namespace SliceViewer {
+
+PeaksTableColumnsDialog::PeaksTableColumnsDialog(QWidget *parent)
+    : QDialog(parent), ui(new Ui::PeaksTableColumnsDialog) {
   ui->setupUi(this);
 }
 
-PeaksTableColumnsDialog::~PeaksTableColumnsDialog()
-{
-  delete ui;
-}
+PeaksTableColumnsDialog::~PeaksTableColumnsDialog() { delete ui; }
 
-void PeaksTableColumnsDialog::setVisibleColumns(std::set<QString> & cols)
-{
+void PeaksTableColumnsDialog::setVisibleColumns(std::set<QString> &cols) {
   // copy in the original values
   m_origVisible.clear();
   m_origVisible.insert(cols.begin(), cols.end());
@@ -30,46 +22,60 @@ void PeaksTableColumnsDialog::setVisibleColumns(std::set<QString> & cols)
   // set the state of all the checkboxes
   bool isChecked;
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::RUNNUMBER) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::RUNNUMBER) !=
+                   m_origVisible.end());
   ui->cb_runnumber->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::DETID) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::DETID) != m_origVisible.end());
   ui->cb_detID->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::WAVELENGTH) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::WAVELENGTH) !=
+                   m_origVisible.end());
   ui->cb_wavelength->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::ENERGY) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::ENERGY) != m_origVisible.end());
   ui->cb_deltaE->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::INITIAL_ENERGY) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::INITIAL_ENERGY) !=
+                   m_origVisible.end());
   ui->cb_ei->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::FINAL_ENERGY) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::FINAL_ENERGY) !=
+                   m_origVisible.end());
   ui->cb_ef->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::TOF) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::TOF) != m_origVisible.end());
   ui->cb_tof->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::DSPACING) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::DSPACING) !=
+                   m_origVisible.end());
   ui->cb_dspacing->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::BINCOUNT) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::BINCOUNT) !=
+                   m_origVisible.end());
   ui->cb_bincount->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::BANKNAME) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::BANKNAME) !=
+                   m_origVisible.end());
   ui->cb_bankname->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::ROW) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::ROW) != m_origVisible.end());
   ui->cb_row->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::COL) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::COL) != m_origVisible.end());
   ui->cb_column->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::QLAB) != m_origVisible.end());
+  isChecked =
+      bool(m_origVisible.find(QPeaksTableModel::QLAB) != m_origVisible.end());
   ui->cb_qLab->setChecked(isChecked);
 
-  isChecked = bool(m_origVisible.find(QPeaksTableModel::QSAMPLE) != m_origVisible.end());
+  isChecked = bool(m_origVisible.find(QPeaksTableModel::QSAMPLE) !=
+                   m_origVisible.end());
   ui->cb_qSample->setChecked(isChecked);
 }
 
@@ -79,39 +85,42 @@ void PeaksTableColumnsDialog::setVisibleColumns(std::set<QString> & cols)
  * @param item The item to add or remove
  * @param addOrRemove true=add, false=remove
  */
-void updateChecked(std::set<QString> &checked, const QString &item, const bool addOrRemove)
-{
+void updateChecked(std::set<QString> &checked, const QString &item,
+                   const bool addOrRemove) {
   if (addOrRemove) // add it to the set
   {
-   checked.insert(item);
-  }
-  else // remove it from the set
+    checked.insert(item);
+  } else // remove it from the set
   {
     auto iter = checked.find(item);
-    if (iter != checked.end())
-    {
+    if (iter != checked.end()) {
       checked.erase(iter);
     }
   }
 }
 
-std::set<QString> PeaksTableColumnsDialog::getVisibleColumns()
-{
+std::set<QString> PeaksTableColumnsDialog::getVisibleColumns() {
   // copy what was originally visible
   std::set<QString> result(m_origVisible.begin(), m_origVisible.end());
 
   // delete what is no longer visible
   //      - it is done this way so things that aren't in the dialog stay visible
-  updateChecked(result, QPeaksTableModel::RUNNUMBER, ui->cb_runnumber->isChecked());
+  updateChecked(result, QPeaksTableModel::RUNNUMBER,
+                ui->cb_runnumber->isChecked());
   updateChecked(result, QPeaksTableModel::DETID, ui->cb_detID->isChecked());
-  updateChecked(result, QPeaksTableModel::WAVELENGTH, ui->cb_wavelength->isChecked());
+  updateChecked(result, QPeaksTableModel::WAVELENGTH,
+                ui->cb_wavelength->isChecked());
   updateChecked(result, QPeaksTableModel::ENERGY, ui->cb_deltaE->isChecked());
-  updateChecked(result, QPeaksTableModel::INITIAL_ENERGY, ui->cb_ei->isChecked());
+  updateChecked(result, QPeaksTableModel::INITIAL_ENERGY,
+                ui->cb_ei->isChecked());
   updateChecked(result, QPeaksTableModel::FINAL_ENERGY, ui->cb_ef->isChecked());
   updateChecked(result, QPeaksTableModel::TOF, ui->cb_tof->isChecked());
-  updateChecked(result, QPeaksTableModel::DSPACING, ui->cb_dspacing->isChecked());
-  updateChecked(result, QPeaksTableModel::BINCOUNT, ui->cb_bincount->isChecked());
-  updateChecked(result, QPeaksTableModel::BANKNAME, ui->cb_bankname->isChecked());
+  updateChecked(result, QPeaksTableModel::DSPACING,
+                ui->cb_dspacing->isChecked());
+  updateChecked(result, QPeaksTableModel::BINCOUNT,
+                ui->cb_bincount->isChecked());
+  updateChecked(result, QPeaksTableModel::BANKNAME,
+                ui->cb_bankname->isChecked());
   updateChecked(result, QPeaksTableModel::ROW, ui->cb_row->isChecked());
   updateChecked(result, QPeaksTableModel::COL, ui->cb_column->isChecked());
   updateChecked(result, QPeaksTableModel::QLAB, ui->cb_qLab->isChecked());
diff --git a/MantidQt/SliceViewer/src/PeaksViewer.cpp b/MantidQt/SliceViewer/src/PeaksViewer.cpp
index 57f350512260e9611a0dc2f61f38d2bafcce2484..a867284c9bf1745c857de84f37caa1dcd830c761 100644
--- a/MantidQt/SliceViewer/src/PeaksViewer.cpp
+++ b/MantidQt/SliceViewer/src/PeaksViewer.cpp
@@ -23,7 +23,7 @@ void removeLayout(QWidget *widget) {
   QLayout *layout = widget->layout();
   if (layout != 0) {
     QLayoutItem *item;
-    while ((item = layout->takeAt(0)) != 0){
+    while ((item = layout->takeAt(0)) != 0) {
       layout->removeItem(item);
       delete item->widget();
     }
@@ -49,25 +49,34 @@ void PeaksViewer::setPresenter(
   if (layout()) {
     removeLayout(this);
   }
-  QVBoxLayout* masterLayout = new QVBoxLayout;
+  QVBoxLayout *masterLayout = new QVBoxLayout;
   this->setLayout(masterLayout);
 
   auto it = workspaces.begin();
   while (it != workspaces.end()) {
     Mantid::API::IPeaksWorkspace_const_sptr ws = *it;
 
-    const auto backgroundPeakViewColor = m_presenter->getBackgroundPeakViewColor(ws);
-    const auto foregroundPeakViewColor = m_presenter->getForegroundPeakViewColor(ws);
+    const auto backgroundPeakViewColor =
+        m_presenter->getBackgroundPeakViewColor(ws);
+    const auto foregroundPeakViewColor =
+        m_presenter->getForegroundPeakViewColor(ws);
 
     bool canAddPeaks = m_presenter->hasPeakAddModeFor(ws);
 
-    auto widget = new PeaksWorkspaceWidget(ws, coordinateSystem, foregroundPeakViewColor,
-                                backgroundPeakViewColor, canAddPeaks, this);
+    auto widget =
+        new PeaksWorkspaceWidget(ws, coordinateSystem, foregroundPeakViewColor,
+                                 backgroundPeakViewColor, canAddPeaks, this);
 
-    connect(widget, SIGNAL(peakColorchanged(Mantid::API::IPeaksWorkspace_const_sptr,PeakViewColor)),
-            this, SLOT(onPeakColorChanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor)));
-    connect(widget, SIGNAL(backgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr,PeakViewColor)),
-            this, SLOT(onBackgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor)));
+    connect(widget,
+            SIGNAL(peakColorchanged(Mantid::API::IPeaksWorkspace_const_sptr,
+                                    PeakViewColor)),
+            this, SLOT(onPeakColorChanged(
+                      Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor)));
+    connect(widget,
+            SIGNAL(backgroundColorChanged(
+                Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor)),
+            this, SLOT(onBackgroundColorChanged(
+                      Mantid::API::IPeaksWorkspace_const_sptr, PeakViewColor)));
 
     connect(widget, SIGNAL(backgroundRadiusShown(
                         Mantid::API::IPeaksWorkspace_const_sptr, bool)),
@@ -146,37 +155,38 @@ void PeaksViewer::clearPeaksModeRequest(
   m_presenter->editCommand(mode, originWidget->getPeaksWorkspace());
 }
 
-void PeaksViewer::addPeaksModeRequest(const PeaksWorkspaceWidget * const originWidget, const bool on)
-{
-    EditMode mode = None;
-    if(on) {
+void PeaksViewer::addPeaksModeRequest(
+    const PeaksWorkspaceWidget *const originWidget, const bool on) {
+  EditMode mode = None;
+  if (on) {
     QList<PeaksWorkspaceWidget *> children =
         qFindChildren<PeaksWorkspaceWidget *>(this);
     for (int i = 0; i < children.size(); ++i) {
       PeaksWorkspaceWidget *candidateWidget = children.at(i);
-      // For all but the most recently selected peaks workspace. Exit clear mode.
-      if(candidateWidget != originWidget){
-          // Exit Add mode on others.
-          candidateWidget->exitAddPeaksMode();
+      // For all but the most recently selected peaks workspace. Exit clear
+      // mode.
+      if (candidateWidget != originWidget) {
+        // Exit Add mode on others.
+        candidateWidget->exitAddPeaksMode();
       }
-      // One mode, and One Workspace at a time. Cannot be in Clear mode for any Workspace while clearing peaks.
+      // One mode, and One Workspace at a time. Cannot be in Clear mode for any
+      // Workspace while clearing peaks.
       candidateWidget->exitClearPeaksMode();
       mode = AddPeaks;
-
-    }
-    } else {
-        mode = None;
     }
-    m_presenter->editCommand(mode, originWidget->getPeaksWorkspace());
+  } else {
+    mode = None;
+  }
+  m_presenter->editCommand(mode, originWidget->getPeaksWorkspace());
 }
 
-
 /**
  * Handler for changing the peak  color.
  * @param peaksWS : Peaks workspace to change the foreground color on.
  * @param newColor : New color to apply.
  */
-void PeaksViewer::onPeakColorChanged(Mantid::API::IPeaksWorkspace_const_sptr peaksWS, PeakViewColor newColor) {
+void PeaksViewer::onPeakColorChanged(
+    Mantid::API::IPeaksWorkspace_const_sptr peaksWS, PeakViewColor newColor) {
   m_presenter->setForegroundColor(peaksWS, newColor);
 }
 
@@ -185,7 +195,8 @@ void PeaksViewer::onPeakColorChanged(Mantid::API::IPeaksWorkspace_const_sptr pea
  * @param peaksWS : Peaks workspace to change the background colors on.
  * @param newColor : New color to apply to the background.
  */
-void PeaksViewer::onBackgroundColorChanged(Mantid::API::IPeaksWorkspace_const_sptr peaksWS, PeakViewColor newColor) {
+void PeaksViewer::onBackgroundColorChanged(
+    Mantid::API::IPeaksWorkspace_const_sptr peaksWS, PeakViewColor newColor) {
   m_presenter->setBackgroundColor(peaksWS, newColor);
 }
 
@@ -234,10 +245,9 @@ void PeaksViewer::onZoomToPeak(Mantid::API::IPeaksWorkspace_const_sptr peaksWS,
  * @param sortedAscending : Sort direction
  * @param peaksWS : Workspace to be sorted
  */
-void
-PeaksViewer::onPeaksSorted(const std::string &columnToSortBy,
-                           const bool sortedAscending,
-                           Mantid::API::IPeaksWorkspace_const_sptr peaksWS) {
+void PeaksViewer::onPeaksSorted(
+    const std::string &columnToSortBy, const bool sortedAscending,
+    Mantid::API::IPeaksWorkspace_const_sptr peaksWS) {
   m_presenter->sortPeaksWorkspace(peaksWS, columnToSortBy, sortedAscending);
 }
 
@@ -278,7 +288,8 @@ void PeaksViewer::performUpdate() {
           }
         }
       }
-      // We also update the widget in case the workspace has changed for added/deleted peaks
+      // We also update the widget in case the workspace has changed for
+      // added/deleted peaks
       candidateWidget->workspaceUpdate();
     }
   }
@@ -351,8 +362,7 @@ bool PeaksViewer::removePeaksWorkspace(
   return somethingToRemove;
 }
 
-bool PeaksViewer::removePeaksWorkspace(const
-    std::string& toRemove) {
+bool PeaksViewer::removePeaksWorkspace(const std::string &toRemove) {
   bool somethingToRemove = false;
 
   if (m_presenter) {
@@ -362,8 +372,7 @@ bool PeaksViewer::removePeaksWorkspace(const
 
     for (int i = 0; i < children.size(); ++i) {
       PeaksWorkspaceWidget *candidateWidget = children.at(i);
-      const std::string candidateWorkspaceName =
-          candidateWidget->getWSName();
+      const std::string candidateWorkspaceName = candidateWidget->getWSName();
       somethingToRemove = (candidateWorkspaceName == toRemove);
       if (somethingToRemove) {
         // We have the right widget to update. Workspace is the same, just
@@ -375,7 +384,6 @@ bool PeaksViewer::removePeaksWorkspace(const
         break;
       }
     }
-
   }
   return somethingToRemove;
 }
diff --git a/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp b/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp
index d65fa61c02b4d5904d1828e4af83e49747475299..7e8486efb7b5bc907aeddcdd427bf8a2d9d53156 100644
--- a/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp
+++ b/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp
@@ -4,166 +4,161 @@
 #include "MantidQtSliceViewer/PeaksViewerOverlayDialog.h"
 #include "ui_PeaksViewerOverlayDialog.h"
 
-namespace MantidQt
-{
-  namespace SliceViewer
-  {
-    /**
-     * Calculate the conversion factor from slider position to fractional occupancy.
-     * @return fractional occupancy factor.
-     */
-    double toFractionalOccupancy()
-    {
-      const double yMax = 0.05; // 5% occupancy
-      const double yMin = 0.00; // 0% occupancy
-      const double xMax = 100; // slider max
-      const double xMin = 0; // slider min
-      const double m = (yMax - yMin) / (xMax - xMin);
-      return m;
-    }
-
-    /**
-     * Calculate the position of the slider.
-     * @param fraction: fractional occupancy
-     * @return position
-     */
-    int calculatePosition(const double fraction)
-    {
-      return static_cast<int>( (1/toFractionalOccupancy()) * fraction );
-    }
-
-    /**
-     * Calculate the fractional occupancy from the slider position.
-     * @param sliderPosition : position of the slider
-     * @return fractional occupancy
-     */
-    double calculateFraction(const double sliderPosition)
-    {
-      return toFractionalOccupancy() * sliderPosition;
-    }
-
-    /**
-     * Take a double and produce a formatted string with single decimal precision.
-     * @param fraction : Fractional occupancy.
-     * @return Formatted string.
-     */
-    QString formattedPercentageValue(double fraction)
-    {
-      QString number;
-      number.sprintf("%1.1f", fraction*100);
-      return number + QString(" %");
-    }
-
-
-    /**
-     * Constructor
-     * @param peaksPresenter : Peaks presenter to use
-     * @param parent : Parent widget
-     */
-    PeaksViewerOverlayDialog::PeaksViewerOverlayDialog(PeaksPresenter_sptr peaksPresenter, QWidget *parent) :
-        QDialog(parent), ui(new Ui::PeaksViewerOverlayDialog), m_peaksPresenter(peaksPresenter)
-    {
-    ui->setupUi(this);
-
-    m_originalOnProjectionFraction = peaksPresenter->getPeakSizeOnProjection();
-    m_originalIntoProjectionFraction = peaksPresenter->getPeakSizeIntoProjection();
-
-    ui->sliderOnProjection->setSliderPosition( calculatePosition( m_originalOnProjectionFraction ) );
-    ui->sliderIntoProjection->setSliderPosition( calculatePosition( m_originalIntoProjectionFraction ) );
-
-    ui->lblPercentageOnProjection->setText( formattedPercentageValue( m_originalOnProjectionFraction ) );
-    ui->lblPercentageIntoProjection->setText( formattedPercentageValue( m_originalIntoProjectionFraction ) );
-
-    connect(ui->sliderIntoProjection, SIGNAL(sliderMoved(int)), this, SLOT(onSliderIntoProjectionMoved(int)));
-    connect(ui->sliderOnProjection, SIGNAL(sliderMoved(int)), this, SLOT(onSliderOnProjectionMoved(int)));
-    connect(ui->btnReset, SIGNAL(clicked()), this, SLOT(onReset()));
-    connect(ui->btnGroupControls, SIGNAL(clicked(QAbstractButton*)), this, SLOT(onCompleteClicked(QAbstractButton*)));
-    connect(ui->btnHelp, SIGNAL(clicked()), this, SLOT(onHelp()));
-  }
+namespace MantidQt {
+namespace SliceViewer {
+/**
+ * Calculate the conversion factor from slider position to fractional occupancy.
+ * @return fractional occupancy factor.
+ */
+double toFractionalOccupancy() {
+  const double yMax = 0.05; // 5% occupancy
+  const double yMin = 0.00; // 0% occupancy
+  const double xMax = 100;  // slider max
+  const double xMin = 0;    // slider min
+  const double m = (yMax - yMin) / (xMax - xMin);
+  return m;
+}
 
-    /// Destructor
-  PeaksViewerOverlayDialog::~PeaksViewerOverlayDialog()
-  {
-    delete ui;
-  }
+/**
+ * Calculate the position of the slider.
+ * @param fraction: fractional occupancy
+ * @return position
+ */
+int calculatePosition(const double fraction) {
+  return static_cast<int>((1 / toFractionalOccupancy()) * fraction);
+}
 
-  /**
-   * Handler for moving the slider associated with ON the current projection.
-   * @param value: New slider position
-   */
-  void PeaksViewerOverlayDialog::onSliderOnProjectionMoved(int value)
-  {
-    auto newFractionOccupancy = calculateFraction(value);
-    m_peaksPresenter->setPeakSizeOnProjection(newFractionOccupancy);
-    ui->lblPercentageOnProjection->setText( formattedPercentageValue(newFractionOccupancy) );
-  }
+/**
+ * Calculate the fractional occupancy from the slider position.
+ * @param sliderPosition : position of the slider
+ * @return fractional occupancy
+ */
+double calculateFraction(const double sliderPosition) {
+  return toFractionalOccupancy() * sliderPosition;
+}
 
-  /**
-   * Handler for moving the slider associated with INTO the current projection.
-   * @param value: New slider position
-   */
-  void PeaksViewerOverlayDialog::onSliderIntoProjectionMoved(int value)
-  {
-    auto newFractionOccupancy = calculateFraction(value);
-    m_peaksPresenter->setPeakSizeIntoProjection(newFractionOccupancy);
-    ui->lblPercentageIntoProjection->setText( formattedPercentageValue(newFractionOccupancy) );
-  }
+/**
+ * Take a double and produce a formatted string with single decimal precision.
+ * @param fraction : Fractional occupancy.
+ * @return Formatted string.
+ */
+QString formattedPercentageValue(double fraction) {
+  QString number;
+  number.sprintf("%1.1f", fraction * 100);
+  return number + QString(" %");
+}
 
-  /**
-   * Handler for the reset event.
-   */
-  void PeaksViewerOverlayDialog::onReset()
-  {
-    m_peaksPresenter->setPeakSizeOnProjection( m_originalOnProjectionFraction );
-    m_peaksPresenter->setPeakSizeIntoProjection( m_originalIntoProjectionFraction );
-    ui->sliderOnProjection->setSliderPosition( calculatePosition( m_originalOnProjectionFraction ) );
-    ui->sliderIntoProjection->setSliderPosition( calculatePosition( m_originalIntoProjectionFraction ) );
-    ui->lblPercentageOnProjection->setText( formattedPercentageValue(m_originalOnProjectionFraction) );
-    ui->lblPercentageIntoProjection->setText( formattedPercentageValue(m_originalIntoProjectionFraction) );
-  }
+/**
+ * Constructor
+ * @param peaksPresenter : Peaks presenter to use
+ * @param parent : Parent widget
+ */
+PeaksViewerOverlayDialog::PeaksViewerOverlayDialog(
+    PeaksPresenter_sptr peaksPresenter, QWidget *parent)
+    : QDialog(parent), ui(new Ui::PeaksViewerOverlayDialog),
+      m_peaksPresenter(peaksPresenter) {
+  ui->setupUi(this);
+
+  m_originalOnProjectionFraction = peaksPresenter->getPeakSizeOnProjection();
+  m_originalIntoProjectionFraction =
+      peaksPresenter->getPeakSizeIntoProjection();
+
+  ui->sliderOnProjection->setSliderPosition(
+      calculatePosition(m_originalOnProjectionFraction));
+  ui->sliderIntoProjection->setSliderPosition(
+      calculatePosition(m_originalIntoProjectionFraction));
+
+  ui->lblPercentageOnProjection->setText(
+      formattedPercentageValue(m_originalOnProjectionFraction));
+  ui->lblPercentageIntoProjection->setText(
+      formattedPercentageValue(m_originalIntoProjectionFraction));
+
+  connect(ui->sliderIntoProjection, SIGNAL(sliderMoved(int)), this,
+          SLOT(onSliderIntoProjectionMoved(int)));
+  connect(ui->sliderOnProjection, SIGNAL(sliderMoved(int)), this,
+          SLOT(onSliderOnProjectionMoved(int)));
+  connect(ui->btnReset, SIGNAL(clicked()), this, SLOT(onReset()));
+  connect(ui->btnGroupControls, SIGNAL(clicked(QAbstractButton *)), this,
+          SLOT(onCompleteClicked(QAbstractButton *)));
+  connect(ui->btnHelp, SIGNAL(clicked()), this, SLOT(onHelp()));
+}
 
-  /**
-   * Handler for the on-complete click event of the button group.
-   * @param button : Button clicked.
-   */
-  void PeaksViewerOverlayDialog::onCompleteClicked(QAbstractButton* button)
-  {
-    QDialogButtonBox::ButtonRole role = ui->btnGroupControls->buttonRole(button);
-    if(role == QDialogButtonBox::RejectRole)
-    {
-      onReset();
-    }
-  }
+/// Destructor
+PeaksViewerOverlayDialog::~PeaksViewerOverlayDialog() { delete ui; }
+
+/**
+ * Handler for moving the slider associated with ON the current projection.
+ * @param value: New slider position
+ */
+void PeaksViewerOverlayDialog::onSliderOnProjectionMoved(int value) {
+  auto newFractionOccupancy = calculateFraction(value);
+  m_peaksPresenter->setPeakSizeOnProjection(newFractionOccupancy);
+  ui->lblPercentageOnProjection->setText(
+      formattedPercentageValue(newFractionOccupancy));
+}
 
-  /**
-   * Handler for the on-close event.
-   * @param event : Close event
-   */
-  void PeaksViewerOverlayDialog::closeEvent(QCloseEvent *event)
-  {
-    onReset();
-    QDialog::closeEvent(event);
-  }
+/**
+ * Handler for moving the slider associated with INTO the current projection.
+ * @param value: New slider position
+ */
+void PeaksViewerOverlayDialog::onSliderIntoProjectionMoved(int value) {
+  auto newFractionOccupancy = calculateFraction(value);
+  m_peaksPresenter->setPeakSizeIntoProjection(newFractionOccupancy);
+  ui->lblPercentageIntoProjection->setText(
+      formattedPercentageValue(newFractionOccupancy));
+}
 
-  /**
-   * Handler for the reject event.
-   */
-  void PeaksViewerOverlayDialog::reject()
-  {
-    onReset();
-    QDialog::reject();
-  }
+/**
+ * Handler for the reset event.
+ */
+void PeaksViewerOverlayDialog::onReset() {
+  m_peaksPresenter->setPeakSizeOnProjection(m_originalOnProjectionFraction);
+  m_peaksPresenter->setPeakSizeIntoProjection(m_originalIntoProjectionFraction);
+  ui->sliderOnProjection->setSliderPosition(
+      calculatePosition(m_originalOnProjectionFraction));
+  ui->sliderIntoProjection->setSliderPosition(
+      calculatePosition(m_originalIntoProjectionFraction));
+  ui->lblPercentageOnProjection->setText(
+      formattedPercentageValue(m_originalOnProjectionFraction));
+  ui->lblPercentageIntoProjection->setText(
+      formattedPercentageValue(m_originalIntoProjectionFraction));
+}
 
-  /**
-   * Handler for the help-clicked event.
-   */
-  void PeaksViewerOverlayDialog::onHelp()
-  {
-    QString helpPage = "PeaksViewer#Preference_Options";
-    QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") + helpPage));
+/**
+ * Handler for the on-complete click event of the button group.
+ * @param button : Button clicked.
+ */
+void PeaksViewerOverlayDialog::onCompleteClicked(QAbstractButton *button) {
+  QDialogButtonBox::ButtonRole role = ui->btnGroupControls->buttonRole(button);
+  if (role == QDialogButtonBox::RejectRole) {
+    onReset();
   }
 }
-}
 
+/**
+ * Handler for the on-close event.
+ * @param event : Close event
+ */
+void PeaksViewerOverlayDialog::closeEvent(QCloseEvent *event) {
+  onReset();
+  QDialog::closeEvent(event);
+}
 
+/**
+ * Handler for the reject event.
+ */
+void PeaksViewerOverlayDialog::reject() {
+  onReset();
+  QDialog::reject();
+}
 
+/**
+ * Handler for the help-clicked event.
+ */
+void PeaksViewerOverlayDialog::onHelp() {
+  QString helpPage = "PeaksViewer#Preference_Options";
+  QDesktopServices::openUrl(
+      QUrl(QString("http://www.mantidproject.org/") + helpPage));
+}
+}
+}
diff --git a/MantidQt/SliceViewer/src/PeaksWorkspaceWidget.cpp b/MantidQt/SliceViewer/src/PeaksWorkspaceWidget.cpp
index 24a40a9e26646dd14b81e19dd71a693a57e9aaff..eb78581629225f2cba94111baa180b371a00eb6d 100644
--- a/MantidQt/SliceViewer/src/PeaksWorkspaceWidget.cpp
+++ b/MantidQt/SliceViewer/src/PeaksWorkspaceWidget.cpp
@@ -6,8 +6,6 @@
 #include <QColorDialog>
 #include <QPlastiqueStyle>
 
-
-
 namespace {
 QColor getSelectedColor() {
   QColorDialog colourDlg;
@@ -28,13 +26,16 @@ Constructor
 @param coordinateSystem : Name of coordinate system used
 @param defaultForegroundPeakViewColor : Default peak foreground colour
 @param defaultBackgroundPeakViewColor : Default peak background colour
-@param canAddPeaks : Flag to indicate that peaks can be added. False for no add mode.
+@param canAddPeaks : Flag to indicate that peaks can be added. False for no add
+mode.
 @param parent : parent widget
 */
 PeaksWorkspaceWidget::PeaksWorkspaceWidget(
     Mantid::API::IPeaksWorkspace_const_sptr ws,
-    const std::string &coordinateSystem, PeakViewColor defaultForegroundPeakViewColor,
-    PeakViewColor defaultBackgroundPeakViewColor, const bool canAddPeaks, PeaksViewer *parent)
+    const std::string &coordinateSystem,
+    PeakViewColor defaultForegroundPeakViewColor,
+    PeakViewColor defaultBackgroundPeakViewColor, const bool canAddPeaks,
+    PeaksViewer *parent)
     : QWidget(parent), m_ws(ws), m_coordinateSystem(coordinateSystem),
       m_foregroundPeakViewColor(defaultForegroundPeakViewColor),
       m_backgroundPeakViewColor(defaultBackgroundPeakViewColor),
@@ -65,8 +66,10 @@ PeaksWorkspaceWidget::PeaksWorkspaceWidget(
   connect(ui.btnRemove, SIGNAL(clicked()), this,
           SLOT(onRemoveWorkspaceClicked()));
   connect(ui.btnHide, SIGNAL(clicked()), this, SLOT(onToggleHideInPlot()));
-  connect(ui.btnAddPeak, SIGNAL(toggled(bool)), this, SLOT(onAddPeaksToggled(bool)));
-  connect(ui.btnRemovePeak, SIGNAL(toggled(bool)), this, SLOT(onClearPeaksToggled(bool)));
+  connect(ui.btnAddPeak, SIGNAL(toggled(bool)), this,
+          SLOT(onAddPeaksToggled(bool)));
+  connect(ui.btnRemovePeak, SIGNAL(toggled(bool)), this,
+          SLOT(onClearPeaksToggled(bool)));
 
   // Override the styles for the colour buttons, because with some inherited
   // styles, the button background colour will be hidden.
@@ -77,7 +80,6 @@ PeaksWorkspaceWidget::PeaksWorkspaceWidget(
   ui.btnBackgroundColorEllipsoid->setStyle(new QPlastiqueStyle);
   ui.btnPeakColorEllipsoid->setStyle(new QPlastiqueStyle);
 
-
   ui.ckShowBackground->setVisible(true);
   ui.lblShowBackgroundColour->setVisible(true);
 
@@ -87,9 +89,9 @@ PeaksWorkspaceWidget::PeaksWorkspaceWidget(
   // Populate controls with data.
   populate();
 
-  QItemSelectionModel* selectionModel = ui.tblPeaks->selectionModel();
-  connect(selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(onCurrentChanged(QModelIndex, QModelIndex)));
-
+  QItemSelectionModel *selectionModel = ui.tblPeaks->selectionModel();
+  connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
+          this, SLOT(onCurrentChanged(QModelIndex, QModelIndex)));
 }
 
 std::set<QString> PeaksWorkspaceWidget::getShownColumns() {
@@ -120,7 +122,7 @@ void PeaksWorkspaceWidget::setShownColumns(std::set<QString> &cols) {
 Populate controls with data ready for rendering.
 */
 void PeaksWorkspaceWidget::createTableMVC() {
-  QPeaksTableModel* model = new QPeaksTableModel(this->m_ws);
+  QPeaksTableModel *model = new QPeaksTableModel(this->m_ws);
   connect(model, SIGNAL(peaksSorted(const std::string &, const bool)), this,
           SLOT(onPeaksSorted(const std::string &, const bool)));
   ui.tblPeaks->setModel(model);
@@ -194,9 +196,12 @@ PeaksWorkspaceWidget::~PeaksWorkspaceWidget() {}
 */
 void PeaksWorkspaceWidget::onForegroundPeakViewColorClicked() {
   auto foregroundColorCross = ui.btnPeakColor->palette().button().color();
-  auto foregroundColorSphere = ui.btnPeakColorSphere->palette().button().color();
-  auto foregroundColorEllipsoid = ui.btnPeakColorEllipsoid->palette().button().color();
-  PeakViewColor color(foregroundColorCross, foregroundColorSphere, foregroundColorEllipsoid);
+  auto foregroundColorSphere =
+      ui.btnPeakColorSphere->palette().button().color();
+  auto foregroundColorEllipsoid =
+      ui.btnPeakColorEllipsoid->palette().button().color();
+  PeakViewColor color(foregroundColorCross, foregroundColorSphere,
+                      foregroundColorEllipsoid);
   emit peakColorchanged(this->m_ws, color);
 }
 
@@ -204,10 +209,14 @@ void PeaksWorkspaceWidget::onForegroundPeakViewColorClicked() {
  * Handler for changing the background colour of an integrated peak.
 */
 void PeaksWorkspaceWidget::onBackgroundPeakViewColorClicked() {
-  auto backgroundColorSphere = ui.btnBackgroundColorSphere->palette().button().color();
-  auto backgroundColorEllipsoid = ui.btnBackgroundColorEllipsoid->palette().button().color();
-  // The first entry will be negelected as there is no background color for cross
-  PeakViewColor color(backgroundColorSphere, backgroundColorSphere, backgroundColorEllipsoid);
+  auto backgroundColorSphere =
+      ui.btnBackgroundColorSphere->palette().button().color();
+  auto backgroundColorEllipsoid =
+      ui.btnBackgroundColorEllipsoid->palette().button().color();
+  // The first entry will be negelected as there is no background color for
+  // cross
+  PeakViewColor color(backgroundColorSphere, backgroundColorSphere,
+                      backgroundColorEllipsoid);
   emit backgroundColorChanged(this->m_ws, color);
 }
 
@@ -341,7 +350,8 @@ void PeaksWorkspaceWidget::workspaceUpdate(
     m_ws = ws;
   }
   // Set at new representation for the model.
-  static_cast<QPeaksTableModel*>(this->ui.tblPeaks->model())->setPeaksWorkspace(m_ws);
+  static_cast<QPeaksTableModel *>(this->ui.tblPeaks->model())
+      ->setPeaksWorkspace(m_ws);
   // Update the display name of the workspace.
   m_nameText = m_ws->getName().c_str();
   this->ui.lblWorkspaceName->setText(m_nameText);
@@ -351,41 +361,39 @@ void PeaksWorkspaceWidget::workspaceUpdate(
  * @brief PeaksWorkspaceWidget::onCurrentChanged
  * @param index : Index of the table newly selected
  */
-void PeaksWorkspaceWidget::onCurrentChanged(QModelIndex index, QModelIndex)
-{
-    if (index.isValid()) {
-      emit zoomToPeak(this->m_ws, index.row());
-    }
+void PeaksWorkspaceWidget::onCurrentChanged(QModelIndex index, QModelIndex) {
+  if (index.isValid()) {
+    emit zoomToPeak(this->m_ws, index.row());
+  }
 }
 
 /**
  * @brief PeaksWorkspaceWidget::onClearPeaksToggled
  * @param on : Enter mode
  */
-void PeaksWorkspaceWidget::onClearPeaksToggled(bool on)
-{
-    //We should now tell the PeaksViewer about this.
-    m_parent->clearPeaksModeRequest(this, on);
+void PeaksWorkspaceWidget::onClearPeaksToggled(bool on) {
+  // We should now tell the PeaksViewer about this.
+  m_parent->clearPeaksModeRequest(this, on);
 }
 
 /**
  * @brief PeaksWorkspaceWidget::onAddPeaksToggled
  * @param on : Enter mode
  */
-void PeaksWorkspaceWidget::onAddPeaksToggled(bool on)
-{
-    // We should now tell the PeaksViewer about this. It should have a global mode for AddingPeaks it merely needs to know the destination workspace
-    m_parent->addPeaksModeRequest(this, on);
+void PeaksWorkspaceWidget::onAddPeaksToggled(bool on) {
+  // We should now tell the PeaksViewer about this. It should have a global mode
+  // for AddingPeaks it merely needs to know the destination workspace
+  m_parent->addPeaksModeRequest(this, on);
 }
 
 void PeaksWorkspaceWidget::exitClearPeaksMode() {
-    SignalBlocker<QPushButton> scopedBlocker(ui.btnRemovePeak);
-    scopedBlocker->setChecked(false);
+  SignalBlocker<QPushButton> scopedBlocker(ui.btnRemovePeak);
+  scopedBlocker->setChecked(false);
 }
 
 void PeaksWorkspaceWidget::exitAddPeaksMode() {
-    SignalBlocker<QPushButton> scopedBlocker(ui.btnAddPeak);
-    scopedBlocker->setChecked(false);
+  SignalBlocker<QPushButton> scopedBlocker(ui.btnAddPeak);
+  scopedBlocker->setChecked(false);
 }
 
 void PeaksWorkspaceWidget::onForegroundColorCrossClicked() {
diff --git a/MantidQt/SliceViewer/src/ProxyCompositePeaksPresenter.cpp b/MantidQt/SliceViewer/src/ProxyCompositePeaksPresenter.cpp
index 0f8cf6d0b87b97d5f97ec3f2a84ed6a41631d92a..076b1d81381de50d10de48e295cf1c23f21016af 100644
--- a/MantidQt/SliceViewer/src/ProxyCompositePeaksPresenter.cpp
+++ b/MantidQt/SliceViewer/src/ProxyCompositePeaksPresenter.cpp
@@ -37,18 +37,19 @@ Set the foreground colour of the peaks.
 @ color to use for re-colouring
 */
 void ProxyCompositePeaksPresenter::setForegroundColor(
-    boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws, PeakViewColor color) {
+    boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
+    PeakViewColor color) {
   m_compositePresenter->setForegroundColor(ws, color);
 }
 
-
 /**
 Set the background colour of the peaks.
 @ workspace containing the peaks to re-colour
 @ colour to use for re-colouring
 */
 void ProxyCompositePeaksPresenter::setBackgroundColor(
-    boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws, PeakViewColor color) {
+    boost::shared_ptr<const Mantid::API::IPeaksWorkspace> ws,
+    PeakViewColor color) {
   m_compositePresenter->setBackgroundColor(ws, color);
 }
 
@@ -135,8 +136,8 @@ bool ProxyCompositePeaksPresenter::getIsHidden(
   return m_compositePresenter->getIsHidden(peaksWS);
 }
 
-void
-ProxyCompositePeaksPresenter::registerView(UpdateableOnDemand *updateableView) {
+void ProxyCompositePeaksPresenter::registerView(
+    UpdateableOnDemand *updateableView) {
   m_updateableView = updateableView;
 }
 
@@ -146,17 +147,18 @@ ProxyCompositePeaksPresenter::getZoomedPeakPresenter() const {
 }
 
 int ProxyCompositePeaksPresenter::getZoomedPeakIndex() const {
-    return m_compositePresenter->getZoomedPeakIndex();
+  return m_compositePresenter->getZoomedPeakIndex();
 }
 
-void ProxyCompositePeaksPresenter::editCommand(EditMode editMode, boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target)
-{
-    m_compositePresenter->editCommand(editMode, target);
+void ProxyCompositePeaksPresenter::editCommand(
+    EditMode editMode,
+    boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target) {
+  m_compositePresenter->editCommand(editMode, target);
 }
 
-bool ProxyCompositePeaksPresenter::hasPeakAddModeFor(boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target){
-    return m_compositePresenter->hasPeakAddModeFor(target);
+bool ProxyCompositePeaksPresenter::hasPeakAddModeFor(
+    boost::weak_ptr<const Mantid::API::IPeaksWorkspace> target) {
+  return m_compositePresenter->hasPeakAddModeFor(target);
 }
-
 }
 }
diff --git a/MantidQt/SliceViewer/src/SliceViewer.cpp b/MantidQt/SliceViewer/src/SliceViewer.cpp
index 9e5d589e4259ddfbe3da190e053d29140e26f303..7f1e6138f7e4835472a50fcfabb8ca14e841ead6 100644
--- a/MantidQt/SliceViewer/src/SliceViewer.cpp
+++ b/MantidQt/SliceViewer/src/SliceViewer.cpp
@@ -64,7 +64,6 @@ using Poco::XML::NodeIterator;
 using Poco::XML::NodeFilter;
 using MantidQt::API::AlgorithmRunner;
 
-
 namespace MantidQt {
 namespace SliceViewer {
 
@@ -702,8 +701,7 @@ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
     // MDEWs)
     coord_t min = m_ws->getDimension(d)->getMinimum();
     coord_t max = m_ws->getDimension(d)->getMaximum();
-    if (max < min)
-    {
+    if (max < min) {
       coord_t tmp = max;
       max = min;
       min = tmp;
@@ -743,12 +741,13 @@ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
   // Build up the widgets
   this->updateDimensionSliceWidgets();
 
-
-  // This will auto scale the color bar to the current slice when the workspace is
+  // This will auto scale the color bar to the current slice when the workspace
+  // is
   // loaded. This always happens when a workspace is loaded for the first time.
   // For live event data workspaces subsequent updates might not lead to an auto
   // scaling of the color scale range (if this is explicitly turned off).
-  if (shouldAutoScaleForNewlySetWorkspace(m_firstWorkspaceOpen, m_colorBar->getAutoScale())) {
+  if (shouldAutoScaleForNewlySetWorkspace(m_firstWorkspaceOpen,
+                                          m_colorBar->getAutoScale())) {
     findRangeFull();
     m_colorBar->setViewRange(m_colorRangeFull);
     m_colorBar->updateColorMap();
@@ -1390,8 +1389,7 @@ void SliceViewer::findRangeSlice() {
     // the rebin selection and continue to use the original WS
     if (!isRebinInConsistentState(m_overlayWS.get(), m_rebinMode)) {
       setRebinMode(false);
-    }
-    else {
+    } else {
       workspace_used = this->m_overlayWS;
     }
   }
@@ -1440,16 +1438,16 @@ void SliceViewer::findRangeSlice() {
 
     // Iterate through the slice
     m_colorRangeSlice = API::SignalRange(*workspace_used, *function,
-      this->getNormalization()).interval();
+                                         this->getNormalization()).interval();
     delete function;
 
     // In case of failure, use the full range instead
     if (m_colorRangeSlice == QwtDoubleInterval(0.0, 1.0)) {
       m_colorRangeSlice = m_colorRangeFull;
     }
-  }
-  else {
-    // If the slice does not cut through the workspace we make use fo the full workspace
+  } else {
+    // If the slice does not cut through the workspace we make use fo the full
+    // workspace
     m_colorRangeSlice = m_colorRangeFull;
   }
 }
@@ -2350,18 +2348,13 @@ SliceViewer::setPeaksWorkspaces(const QStringList &list) {
 
     // Peak View factory, displays peaks on a peak by peak basis
     auto peakViewFactory = boost::make_shared<PeakViewFactory>(
-                                  m_ws, peaksWS,
-                                  m_plot,
-                                  m_plot->canvas(),
-                                  m_spect->xAxis(),
-                                  m_spect->yAxis(),
-                                  numberOfChildPresenters);
+        m_ws, peaksWS, m_plot, m_plot->canvas(), m_spect->xAxis(),
+        m_spect->yAxis(), numberOfChildPresenters);
 
     try {
       m_peaksPresenter->addPeaksPresenter(
-          boost::make_shared<ConcretePeaksPresenter>(
-              peakViewFactory, peaksWS, m_ws,
-              transformFactory));
+          boost::make_shared<ConcretePeaksPresenter>(peakViewFactory, peaksWS,
+                                                     m_ws, transformFactory));
     } catch (std::logic_error &ex) {
       // Incompatible PeaksWorkspace.
       disablePeakOverlays();
@@ -2575,12 +2568,12 @@ void SliceViewer::setColorBarAutoScale(bool autoscale) {
 * be applied only if it is explicitly requested
 */
 void SliceViewer::applyColorScalingForCurrentSliceIfRequired() {
-  auto useAutoColorScaleforCurrentSlice = m_colorBar->getAutoColorScaleforCurrentSlice();
+  auto useAutoColorScaleforCurrentSlice =
+      m_colorBar->getAutoColorScaleforCurrentSlice();
   if (useAutoColorScaleforCurrentSlice) {
     setColorScaleAutoSlice();
   }
 }
 
-
 } // namespace
 }
diff --git a/MantidQt/SliceViewer/src/SliceViewerFunctions.cpp b/MantidQt/SliceViewer/src/SliceViewerFunctions.cpp
index 046c57f882ee3533b59f0e6b47a27676f27ea512..221f4365bf4ffcf7f1fca96c1d2819872816beed 100644
--- a/MantidQt/SliceViewer/src/SliceViewerFunctions.cpp
+++ b/MantidQt/SliceViewer/src/SliceViewerFunctions.cpp
@@ -53,8 +53,9 @@ bool EXPORT_OPT_MANTIDQT_SLICEVIEWER doesSliceCutThroughWorkspace(
  * @param isAutoScalingOnLoad: is auto scaling on load selected
  * @returns true if autos scaling on load should be performed else false
 */
-bool EXPORT_OPT_MANTIDQT_SLICEVIEWER shouldAutoScaleForNewlySetWorkspace(
-    bool isFirstWorkspaceOpen, bool isAutoScalingOnLoad) {
+bool EXPORT_OPT_MANTIDQT_SLICEVIEWER
+shouldAutoScaleForNewlySetWorkspace(bool isFirstWorkspaceOpen,
+                                    bool isAutoScalingOnLoad) {
   return !isFirstWorkspaceOpen || isAutoScalingOnLoad;
 }
 
@@ -69,8 +70,9 @@ bool EXPORT_OPT_MANTIDQT_SLICEVIEWER shouldAutoScaleForNewlySetWorkspace(
  * @param useRebinMode: indicates if rebinning is to be used
  * @returns true rebin state is consistent, else false
 */
-bool EXPORT_OPT_MANTIDQT_SLICEVIEWER isRebinInConsistentState(
-    Mantid::API::IMDWorkspace *rebinnedWS, bool useRebinMode) {
+bool EXPORT_OPT_MANTIDQT_SLICEVIEWER
+isRebinInConsistentState(Mantid::API::IMDWorkspace *rebinnedWS,
+                         bool useRebinMode) {
   return rebinnedWS && useRebinMode;
 }
 }
diff --git a/MantidQt/SliceViewer/src/SnapToGridDialog.cpp b/MantidQt/SliceViewer/src/SnapToGridDialog.cpp
index f4aa4b0b75eafacff58958dcae34fdc42da62480..1490039e51f202faefb1f03023df20ff206b7cff 100644
--- a/MantidQt/SliceViewer/src/SnapToGridDialog.cpp
+++ b/MantidQt/SliceViewer/src/SnapToGridDialog.cpp
@@ -2,10 +2,8 @@
 #include <QIntValidator>
 
 /// Constructor
-SnapToGridDialog::SnapToGridDialog(QWidget *parent)
-  : QDialog(parent)
-{
-	ui.setupUi(this);
+SnapToGridDialog::SnapToGridDialog(QWidget *parent) : QDialog(parent) {
+  ui.setupUi(this);
   ui.txtSnapX->setValidator(new QDoubleValidator(ui.txtSnapX));
   ui.txtSnapY->setValidator(new QDoubleValidator(ui.txtSnapY));
 
@@ -14,32 +12,27 @@ SnapToGridDialog::SnapToGridDialog(QWidget *parent)
 }
 
 /// Set the initial snap-to values.
-void SnapToGridDialog::setSnap(double x, double y)
-{
+void SnapToGridDialog::setSnap(double x, double y) {
   ui.txtSnapX->setText(QString::number(x));
   ui.txtSnapY->setText(QString::number(y));
 }
 
 ///@return the snap-to-X value
-double SnapToGridDialog::getSnapX()
-{
+double SnapToGridDialog::getSnapX() {
   bool ok;
   double ret = ui.txtSnapX->text().toDouble(&ok);
-  if (!ok) ret = 0.0;
+  if (!ok)
+    ret = 0.0;
   return ret;
 }
 
 ///@return the snap-to-Y value
-double SnapToGridDialog::getSnapY()
-{
+double SnapToGridDialog::getSnapY() {
   bool ok;
   double ret = ui.txtSnapY->text().toDouble(&ok);
-  if (!ok) ret = 0.0;
+  if (!ok)
+    ret = 0.0;
   return ret;
 }
 
-
-SnapToGridDialog::~SnapToGridDialog()
-{
-
-}
+SnapToGridDialog::~SnapToGridDialog() {}
diff --git a/MantidQt/SliceViewer/src/XYLimitsDialog.cpp b/MantidQt/SliceViewer/src/XYLimitsDialog.cpp
index 9b53b5ad0659f6fde3e8d0dc65fbdcdd17e88c91..6d5fbda7b1f399aca5388463884b66a33dec9d80 100644
--- a/MantidQt/SliceViewer/src/XYLimitsDialog.cpp
+++ b/MantidQt/SliceViewer/src/XYLimitsDialog.cpp
@@ -2,10 +2,8 @@
 #include "MantidKernel/UnitLabel.h"
 #include <QIntValidator>
 
-XYLimitsDialog::XYLimitsDialog(QWidget *parent)
-    : QDialog(parent)
-{
-	ui.setupUi(this);
+XYLimitsDialog::XYLimitsDialog(QWidget *parent) : QDialog(parent) {
+  ui.setupUi(this);
   ui.textXMax->setValidator(new QDoubleValidator(ui.textXMax));
   ui.textYMax->setValidator(new QDoubleValidator(ui.textYMax));
   ui.textXMin->setValidator(new QDoubleValidator(ui.textXMin));
@@ -13,29 +11,23 @@ XYLimitsDialog::XYLimitsDialog(QWidget *parent)
 
   QObject::connect(ui.btnOK, SIGNAL(clicked()), this, SLOT(accept()));
   QObject::connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
-
 }
 
-XYLimitsDialog::~XYLimitsDialog()
-{
-
-}
+XYLimitsDialog::~XYLimitsDialog() {}
 
 //------------------------------------------------------------------------------------------
 /** Set the labels for the X dimensions
  * @param dim : IMDDimension */
-void XYLimitsDialog::setXDim(Mantid::Geometry::IMDDimension_const_sptr dim)
-{
-  ui.lblXName->setText( QString::fromStdString(dim->getName()) );
-  ui.lblXUnits->setText( QString::fromStdWString(dim->getUnits().utf8()) );
+void XYLimitsDialog::setXDim(Mantid::Geometry::IMDDimension_const_sptr dim) {
+  ui.lblXName->setText(QString::fromStdString(dim->getName()));
+  ui.lblXUnits->setText(QString::fromStdWString(dim->getUnits().utf8()));
 }
 
 /** Set the labels for the Y dimensions
  * @param dim : IMDDimension */
-void XYLimitsDialog::setYDim(Mantid::Geometry::IMDDimension_const_sptr dim)
-{
-  ui.lblYName->setText( QString::fromStdString(dim->getName()) );
-  ui.lblYUnits->setText( QString::fromStdWString(dim->getUnits().utf8()) );
+void XYLimitsDialog::setYDim(Mantid::Geometry::IMDDimension_const_sptr dim) {
+  ui.lblYName->setText(QString::fromStdString(dim->getName()));
+  ui.lblYUnits->setText(QString::fromStdWString(dim->getUnits().utf8()));
 }
 
 //------------------------------------------------------------------------------------------
@@ -46,36 +38,22 @@ void XYLimitsDialog::setYDim(Mantid::Geometry::IMDDimension_const_sptr dim)
  * @param y0 :: y min
  * @param y1 :: y max
  */
-void XYLimitsDialog::setLimits(double x0, double x1, double y0, double y1)
-{
-  ui.textXMin->setText( QString::number(x0) );
-  ui.textXMax->setText( QString::number(x1) );
-  ui.textYMin->setText( QString::number(y0) );
-  ui.textYMax->setText( QString::number(y1) );
+void XYLimitsDialog::setLimits(double x0, double x1, double y0, double y1) {
+  ui.textXMin->setText(QString::number(x0));
+  ui.textXMax->setText(QString::number(x1));
+  ui.textYMin->setText(QString::number(y0));
+  ui.textYMax->setText(QString::number(y1));
 }
 
-
 //------------------------------------------------------------------------------------------
 /// @return the X min value in the gui
-double XYLimitsDialog::getXMin()
-{
-  return ui.textXMin->text().toDouble();
-}
+double XYLimitsDialog::getXMin() { return ui.textXMin->text().toDouble(); }
 
 /// @return the X Max  value in the gui
-double XYLimitsDialog::getXMax ()
-{
-  return ui.textXMax ->text().toDouble();
-}
+double XYLimitsDialog::getXMax() { return ui.textXMax->text().toDouble(); }
 
 /// @return the X min value in the gui
-double XYLimitsDialog::getYMin()
-{
-  return ui.textYMin->text().toDouble();
-}
+double XYLimitsDialog::getYMin() { return ui.textYMin->text().toDouble(); }
 
 /// @return the X Max  value in the gui
-double XYLimitsDialog::getYMax ()
-{
-  return ui.textYMax ->text().toDouble();
-}
+double XYLimitsDialog::getYMax() { return ui.textYMax->text().toDouble(); }
diff --git a/MantidQt/SliceViewer/src/main_ColorBarWidgetDemo.cpp b/MantidQt/SliceViewer/src/main_ColorBarWidgetDemo.cpp
index 2594ea8f55109e04b4e6534a1c2d086d5f4b394d..b07f2cea68babfbf0abd6a6706e3865c1d354603 100644
--- a/MantidQt/SliceViewer/src/main_ColorBarWidgetDemo.cpp
+++ b/MantidQt/SliceViewer/src/main_ColorBarWidgetDemo.cpp
@@ -20,23 +20,22 @@ using namespace MantidQt::SliceViewer;
  * @param argv :: ignored
  * @return return code
  */
-int main( int argc, char ** argv )
-{
-  double min=0;
-  double max=100;
+int main(int argc, char **argv) {
+  double min = 0;
+  double max = 100;
 
   QApplication app(argc, argv);
   app.setOrganizationName("MantidProject");
   app.setApplicationName("Color Bar Widget Example");
-  QMainWindow * mainWin = new QMainWindow();
+  QMainWindow *mainWin = new QMainWindow();
 
-  QFrame * frame = new QFrame(mainWin);
+  QFrame *frame = new QFrame(mainWin);
   mainWin->setCentralWidget(frame);
 
-  QLayout * layout = new QVBoxLayout(frame);
+  QLayout *layout = new QVBoxLayout(frame);
   frame->setLayout(layout);
 
-  MantidQt::MantidWidgets::ColorBarWidget * widget = new ColorBarWidget(frame);
+  MantidQt::MantidWidgets::ColorBarWidget *widget = new ColorBarWidget(frame);
 
   widget->setViewRange(min, max);
   widget->setLog(false);
diff --git a/MantidQt/SliceViewer/src/main_LineViewerDemo.cpp b/MantidQt/SliceViewer/src/main_LineViewerDemo.cpp
index cd15090523f4ee85b23614b04c3b795b40e11b72..30c43ad5488628bb677dae4b9ee273c492e87a95 100644
--- a/MantidQt/SliceViewer/src/main_LineViewerDemo.cpp
+++ b/MantidQt/SliceViewer/src/main_LineViewerDemo.cpp
@@ -18,7 +18,8 @@
 #include "MantidKernel/VMD.h"
 
 using namespace Mantid;
-using namespace Mantid::API;;
+using namespace Mantid::API;
+;
 using namespace Mantid::MDEvents;
 using namespace Mantid::Geometry;
 using Mantid::Geometry::MDHistoDimension_sptr;
@@ -35,35 +36,33 @@ using Mantid::Kernel::VMD;
 // Little hack to avoid repeating code
 #include "main_common.cpp"
 
-
 /** Main application
  *
  * @param argc :: ignored
  * @param argv :: ignored
  * @return return code
  */
-int main( int argc, char ** argv )
-{
+int main(int argc, char **argv) {
   QApplication app(argc, argv);
   app.setOrganizationName("JanikTech");
   app.setApplicationName("Application Example");
-  QMainWindow * mainWin = new QMainWindow();
+  QMainWindow *mainWin = new QMainWindow();
 
   IMDWorkspace_sptr mdew = makeDemoData();
 
-  QFrame * frame = new QFrame(mainWin);
+  QFrame *frame = new QFrame(mainWin);
   mainWin->setCentralWidget(frame);
 
-  QLayout * layout = new QVBoxLayout(frame);
+  QLayout *layout = new QVBoxLayout(frame);
   frame->setLayout(layout);
 
-  LineViewer * line = new LineViewer(frame);
-  line->resize(600,600);
+  LineViewer *line = new LineViewer(frame);
+  line->resize(600, 600);
   layout->addWidget(line);
   line->setWorkspace(mdew);
-  line->setStart(VMD(-1,0,0));
-  line->setEnd(VMD(+1,0,0));
-  line->setWidth(VMD(+0.3,0,0.3));
+  line->setStart(VMD(-1, 0, 0));
+  line->setEnd(VMD(+1, 0, 0));
+  line->setWidth(VMD(+0.3, 0, 0.3));
   line->setPlanarWidth(0.2);
   line->setNumBins(1000);
   line->setFreeDimensions(false, 0, 1);
diff --git a/MantidQt/SliceViewer/src/main_SliceViewerDemo.cpp b/MantidQt/SliceViewer/src/main_SliceViewerDemo.cpp
index 37ce5d6153da9efdc8fd18557ff2fa19f4d6b181..0173c733fcf56036ddeba37d6462e2eefda87a02 100644
--- a/MantidQt/SliceViewer/src/main_SliceViewerDemo.cpp
+++ b/MantidQt/SliceViewer/src/main_SliceViewerDemo.cpp
@@ -17,7 +17,8 @@
 #include "MantidAPI/IMDEventWorkspace.h"
 
 using namespace Mantid;
-using namespace Mantid::API;;
+using namespace Mantid::API;
+;
 using namespace Mantid::MDEvents;
 using namespace Mantid::Geometry;
 using Mantid::Geometry::MDHistoDimension_sptr;
@@ -33,29 +34,27 @@ using MantidQt::SliceViewer::SliceViewer;
 // Little hack to avoid repeating code
 #include "main_common.cpp"
 
-
 /** Main application
  *
  * @param argc :: ignored
  * @param argv :: ignored
  * @return return code
  */
-int main( int argc, char ** argv )
-{
+int main(int argc, char **argv) {
   QApplication app(argc, argv);
   app.setApplicationName("SliceViewer widget demo");
-  QMainWindow * mainWin = new QMainWindow();
+  QMainWindow *mainWin = new QMainWindow();
 
   IMDWorkspace_sptr mdew = makeDemoData(false);
 
-  QFrame * frame = new QFrame(mainWin);
+  QFrame *frame = new QFrame(mainWin);
   mainWin->setCentralWidget(frame);
 
-  QLayout * layout = new QVBoxLayout(frame);
+  QLayout *layout = new QVBoxLayout(frame);
   frame->setLayout(layout);
 
-  SliceViewer * slicer = new SliceViewer(frame);
-  slicer->resize(600,600);
+  SliceViewer *slicer = new SliceViewer(frame);
+  slicer->resize(600, 600);
   layout->addWidget(slicer);
   slicer->setWorkspace(mdew);
   mainWin->move(100, 100);
diff --git a/MantidQt/SliceViewer/src/main_SliceViewerWindowDemo.cpp b/MantidQt/SliceViewer/src/main_SliceViewerWindowDemo.cpp
index 41db0d8e18dc94191842f2690d089868d87bb850..7c9e573e651e1d340edcb00814bdff847a7e22c5 100644
--- a/MantidQt/SliceViewer/src/main_SliceViewerWindowDemo.cpp
+++ b/MantidQt/SliceViewer/src/main_SliceViewerWindowDemo.cpp
@@ -27,19 +27,18 @@ using MantidQt::SliceViewer::SliceViewerWindow;
  * @param argv :: ignored
  * @return return code
  */
-int main( int argc, char ** argv )
-{
+int main(int argc, char **argv) {
   QApplication app(argc, argv);
   app.setApplicationName("SliceViewerWindow demo");
   IMDWorkspace_sptr mdew = makeDemoData(true);
 
-  SliceViewerWindow * mainWin = new SliceViewerWindow("workspace_2d");
-  //SliceViewerWindow * mainWin = new SliceViewerWindow("mdew");
-  //mainWin->getSlicer()->getLineOverlay()->setSnap(0.5);
-//  mainWin->getSlicer()->getLineOverlay()->setSnapLength(0.1);
+  SliceViewerWindow *mainWin = new SliceViewerWindow("workspace_2d");
+  // SliceViewerWindow * mainWin = new SliceViewerWindow("mdew");
+  // mainWin->getSlicer()->getLineOverlay()->setSnap(0.5);
+  //  mainWin->getSlicer()->getLineOverlay()->setSnapLength(0.1);
   mainWin->move(100, 100);
   mainWin->resize(700, 700);
-  mainWin->getSlicer()->setXYDim(0,1);
+  mainWin->getSlicer()->setXYDim(0, 1);
   mainWin->show();
 
   app.exec();
@@ -47,4 +46,3 @@ int main( int argc, char ** argv )
   mainWin->close();
   return 0;
 }
-
diff --git a/MantidQt/SliceViewer/src/main_common.cpp b/MantidQt/SliceViewer/src/main_common.cpp
index 8b3cf3fe55aed310ab847d7bef4922776e1571e3..27f7082effba30baa3e9f25174e7430e9f2c5603 100644
--- a/MantidQt/SliceViewer/src/main_common.cpp
+++ b/MantidQt/SliceViewer/src/main_common.cpp
@@ -6,147 +6,127 @@
 #include "MantidAPI/IMDEventWorkspace.h"
 
 using namespace Mantid;
-using namespace Mantid::API;;
+using namespace Mantid::API;
+;
 using namespace Mantid::MDEvents;
 using namespace Mantid::Geometry;
 using Mantid::Geometry::MDHistoDimension_sptr;
 using Mantid::Geometry::MDHistoDimension;
 using Mantid::Kernel::VMD;
 
-
 /** Creates a fake MDHistoWorkspace
  *
  * @param signal :: signal and error squared in every point
- * @param numDims :: number of dimensions to create. They will range from 0 to max
+ * @param numDims :: number of dimensions to create. They will range from 0 to
+ *max
  * @param numBins :: bins in each dimensions
  * @param max :: max position in each dimension
  * @return the MDHisto
  */
-Mantid::MDEvents::MDHistoWorkspace_sptr makeFakeMDHistoWorkspace(double signal, size_t numDims, size_t numBins,
-    double max)
-{
-  Mantid::MDEvents::MDHistoWorkspace * ws = NULL;
-  if (numDims ==1)
-  {
-    ws = new Mantid::MDEvents::MDHistoWorkspace(
-        MDHistoDimension_sptr(new MDHistoDimension("x","x","m", 0.0, max, numBins)) );
-  }
-  else if (numDims == 2)
-  {
+Mantid::MDEvents::MDHistoWorkspace_sptr makeFakeMDHistoWorkspace(double signal,
+                                                                 size_t numDims,
+                                                                 size_t numBins,
+                                                                 double max) {
+  Mantid::MDEvents::MDHistoWorkspace *ws = NULL;
+  if (numDims == 1) {
+    ws = new Mantid::MDEvents::MDHistoWorkspace(MDHistoDimension_sptr(
+        new MDHistoDimension("x", "x", "m", 0.0, max, numBins)));
+  } else if (numDims == 2) {
     ws = new Mantid::MDEvents::MDHistoWorkspace(
-        MDHistoDimension_sptr(new MDHistoDimension("x","x","m", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("y","y","m", 0.0, max, numBins))  );
-  }
-  else if (numDims == 3)
-  {
+        MDHistoDimension_sptr(
+            new MDHistoDimension("x", "x", "m", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("y", "y", "m", 0.0, max, numBins)));
+  } else if (numDims == 3) {
     ws = new Mantid::MDEvents::MDHistoWorkspace(
-        MDHistoDimension_sptr(new MDHistoDimension("x","x","m", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("yy","y","furlongs", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("energy","z","meV", 0.0, max, numBins))   );
-  }
-  else if (numDims == 4)
-  {
+        MDHistoDimension_sptr(
+            new MDHistoDimension("x", "x", "m", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("yy", "y", "furlongs", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("energy", "z", "meV", 0.0, max, numBins)));
+  } else if (numDims == 4) {
     ws = new Mantid::MDEvents::MDHistoWorkspace(
-        MDHistoDimension_sptr(new MDHistoDimension("x","x","m", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("y","y","m", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("z","z","m", 0.0, max, numBins)),
-        MDHistoDimension_sptr(new MDHistoDimension("t","z","m", 0.0, max, numBins))
-        );
+        MDHistoDimension_sptr(
+            new MDHistoDimension("x", "x", "m", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("y", "y", "m", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("z", "z", "m", 0.0, max, numBins)),
+        MDHistoDimension_sptr(
+            new MDHistoDimension("t", "z", "m", 0.0, max, numBins)));
   }
   Mantid::MDEvents::MDHistoWorkspace_sptr ws_sptr(ws);
   ws_sptr->setTo(signal, signal, 1.0);
   return ws_sptr;
 }
 
-
-
 //-------------------------------------------------------------------------------
 /** Add a fake "peak"*/
-static void addPeak(size_t num, double x, double y, double z, double radius)
-{
+static void addPeak(size_t num, double x, double y, double z, double radius) {
   std::ostringstream mess;
   mess << num << ", " << x << ", " << y << ", " << z << ", " << radius;
-  FrameworkManager::Instance().exec("FakeMDEventData", 6,
-      "InputWorkspace", "mdew",
-      "PeakParams", mess.str().c_str(),
-      "RandomSeed", "1234");
+  FrameworkManager::Instance().exec("FakeMDEventData", 6, "InputWorkspace",
+                                    "mdew", "PeakParams", mess.str().c_str(),
+                                    "RandomSeed", "1234");
 }
 
 //-------------------------------------------------------------------------------
 /** Make a demo data set for testing */
-IMDWorkspace_sptr makeDemoData(bool binned = false)
-{
+IMDWorkspace_sptr makeDemoData(bool binned = false) {
   // Create a fake workspace
-  //size_t numBins = 100;
+  // size_t numBins = 100;
 
   // ---- Start with empty MDEW ----
-  FrameworkManager::Instance().exec("CreateMDWorkspace", 16,
-      "Dimensions", "3",
-      "Extents", "-10,10,-10,10,-10,10",
-      "Names", "h,k,l",
-      "Units", "lattice,lattice,lattice",
-      "SplitInto", "5",
-      "SplitThreshold", "100",
-      "MaxRecursionDepth", "20",
-      "OutputWorkspace", "mdew");
-  addPeak(15000,0,0,0, 3);
-  addPeak(5000,0,0,0, 0.3);
-  addPeak(5000,0,0,0, 0.2);
-  addPeak(5000,0,0,0, 0.1);
-  addPeak(5000,1,0,0, 0.3);
-  addPeak(5000,2,0,0, 0.3);
-  addPeak(5000,2,1,0, 0.3);
-//  addPeak(12000,0,0,0, 0.03);
-  IMDEventWorkspace_sptr mdew = boost::dynamic_pointer_cast<IMDEventWorkspace>( AnalysisDataService::Instance().retrieve("mdew") );
+  FrameworkManager::Instance().exec(
+      "CreateMDWorkspace", 16, "Dimensions", "3", "Extents",
+      "-10,10,-10,10,-10,10", "Names", "h,k,l", "Units",
+      "lattice,lattice,lattice", "SplitInto", "5", "SplitThreshold", "100",
+      "MaxRecursionDepth", "20", "OutputWorkspace", "mdew");
+  addPeak(15000, 0, 0, 0, 3);
+  addPeak(5000, 0, 0, 0, 0.3);
+  addPeak(5000, 0, 0, 0, 0.2);
+  addPeak(5000, 0, 0, 0, 0.1);
+  addPeak(5000, 1, 0, 0, 0.3);
+  addPeak(5000, 2, 0, 0, 0.3);
+  addPeak(5000, 2, 1, 0, 0.3);
+  //  addPeak(12000,0,0,0, 0.03);
+  IMDEventWorkspace_sptr mdew = boost::dynamic_pointer_cast<IMDEventWorkspace>(
+      AnalysisDataService::Instance().retrieve("mdew"));
   mdew->splitAllIfNeeded(NULL);
-  if (binned)
-  {
+  if (binned) {
     // Bin aligned to original
-//    FrameworkManager::Instance().exec("BinMD", 12,
-//        "InputWorkspace", "mdew",
-//        "OutputWorkspace", "binned",
-//        "AxisAligned", "1",
-//        "AlignedDim0", "h, -10, 10, 100",
-//        "AlignedDim1", "k, -10, 10, 100",
-//        "AlignedDim2", "l, -10, 10, 100"
-//        );
-    FrameworkManager::Instance().exec("BinMD", 20,
-        "InputWorkspace", "mdew",
-        "OutputWorkspace", "binned",
-        "AxisAligned", "0",
-        "BasisVector0", "rx, m, 1.0, 0.0, 0.0",
-        "BasisVector1", "ry, m, 0.0, 1.0, 0.0",
-        "BasisVector2", "rz, m, 0.0, 0.0, 1.0",
-        "ForceOrthogonal", "1",
-        "Translation", "-5, -5, -5",
-        "OutputExtents", "0, 10, 0,10, 0,10",
-        "OutputBins", "100, 100, 100"
-        );
-
-    FrameworkManager::Instance().exec("BinMD", 12,
-        "InputWorkspace", "mdew",
-        "OutputWorkspace", "binned_al",
-        "AxisAligned", "1",
-        "AlignedDim0", "k, -5, 5, 100",
-        "AlignedDim1", "l, -5, 5, 100",
-        "AlignedDim2", "h, -5, 5, 100");
-
-    FrameworkManager::Instance().exec("LoadEventNexus", 4,
-        "Filename", "CNCS_7860_event.nxs",
-        "OutputWorkspace", "workspace_2d");
-
-    FrameworkManager::Instance().exec("Rebin", 8,
-        "Params", "40e3, 1e3, 70e3",
-        "PreserveEvents", "1",
-        "InputWorkspace", "workspace_2d",
-        "OutputWorkspace", "workspace_2d");
-
-
-
-
-
-    return boost::dynamic_pointer_cast<IMDWorkspace>( AnalysisDataService::Instance().retrieve("binned") );
-  }
-  else
+    //    FrameworkManager::Instance().exec("BinMD", 12,
+    //        "InputWorkspace", "mdew",
+    //        "OutputWorkspace", "binned",
+    //        "AxisAligned", "1",
+    //        "AlignedDim0", "h, -10, 10, 100",
+    //        "AlignedDim1", "k, -10, 10, 100",
+    //        "AlignedDim2", "l, -10, 10, 100"
+    //        );
+    FrameworkManager::Instance().exec(
+        "BinMD", 20, "InputWorkspace", "mdew", "OutputWorkspace", "binned",
+        "AxisAligned", "0", "BasisVector0", "rx, m, 1.0, 0.0, 0.0",
+        "BasisVector1", "ry, m, 0.0, 1.0, 0.0", "BasisVector2",
+        "rz, m, 0.0, 0.0, 1.0", "ForceOrthogonal", "1", "Translation",
+        "-5, -5, -5", "OutputExtents", "0, 10, 0,10, 0,10", "OutputBins",
+        "100, 100, 100");
+
+    FrameworkManager::Instance().exec(
+        "BinMD", 12, "InputWorkspace", "mdew", "OutputWorkspace", "binned_al",
+        "AxisAligned", "1", "AlignedDim0", "k, -5, 5, 100", "AlignedDim1",
+        "l, -5, 5, 100", "AlignedDim2", "h, -5, 5, 100");
+
+    FrameworkManager::Instance().exec("LoadEventNexus", 4, "Filename",
+                                      "CNCS_7860_event.nxs", "OutputWorkspace",
+                                      "workspace_2d");
+
+    FrameworkManager::Instance().exec(
+        "Rebin", 8, "Params", "40e3, 1e3, 70e3", "PreserveEvents", "1",
+        "InputWorkspace", "workspace_2d", "OutputWorkspace", "workspace_2d");
+
+    return boost::dynamic_pointer_cast<IMDWorkspace>(
+        AnalysisDataService::Instance().retrieve("binned"));
+  } else
     return boost::dynamic_pointer_cast<IMDWorkspace>(mdew);
 }
diff --git a/MantidQt/SliceViewer/test/CompositePeaksPresenterTest.h b/MantidQt/SliceViewer/test/CompositePeaksPresenterTest.h
index a550249a5e954f005dba222a319ee5fee6c0c01d..7bca2c99e66e46df18b2b7fb44e6b840d095856c 100644
--- a/MantidQt/SliceViewer/test/CompositePeaksPresenterTest.h
+++ b/MantidQt/SliceViewer/test/CompositePeaksPresenterTest.h
@@ -13,14 +13,11 @@ using namespace Mantid;
 using namespace testing;
 using Mantid::API::IPeaksWorkspace_sptr;
 
-class CompositePeaksPresenterTest : public CxxTest::TestSuite
-{
+class CompositePeaksPresenterTest : public CxxTest::TestSuite {
 
 private:
-
   /// Fake class to make objects of type
-  class FakeZoomablePeaksView : public ZoomablePeaksView
-  {
+  class FakeZoomablePeaksView : public ZoomablePeaksView {
   public:
     void zoomToRectangle(const PeakBoundingBox &) override {}
     void resetView() override {}
@@ -32,72 +29,79 @@ private:
   FakeZoomablePeaksView _fakeZoomableView;
 
 public:
-
-  void test_construction_throws_if_zoomablePeakView__NULL()
-  {
-    TS_ASSERT_THROWS(CompositePeaksPresenter composite(NULL), std::runtime_error&);
+  void test_construction_throws_if_zoomablePeakView__NULL() {
+    TS_ASSERT_THROWS(CompositePeaksPresenter composite(NULL),
+                     std::runtime_error &);
   }
 
+  void test_construction() {
+    CompositePeaksPresenter composite(&_fakeZoomableView);
+    TSM_ASSERT_EQUALS(
+        "Should default construct with a &_fakeZoomableViewPeaksPresenter", 0,
+        composite.size());
 
-  void test_construction()
-  {
-     CompositePeaksPresenter composite(&_fakeZoomableView);
-     TSM_ASSERT_EQUALS("Should default construct with a &_fakeZoomableViewPeaksPresenter", 0, composite.size());
-
-     /*After default construction, the composite presenter should behave identically to a NULL peaks presenter.*/
-     NullPeaksPresenter expected;
-     TS_ASSERT_THROWS_NOTHING(expected.update());
-     TS_ASSERT_THROWS_NOTHING(composite.update());
-     PeakBoundingBox region;
-     TS_ASSERT_THROWS_NOTHING(expected.updateWithSlicePoint(region));
-     TS_ASSERT_THROWS_NOTHING(composite.updateWithSlicePoint(region));
-     TS_ASSERT_EQUALS(expected.changeShownDim(), composite.changeShownDim());
-     TS_ASSERT_EQUALS(expected.isLabelOfFreeAxis("") , composite.isLabelOfFreeAxis(""));
+    /*After default construction, the composite presenter should behave
+     * identically to a NULL peaks presenter.*/
+    NullPeaksPresenter expected;
+    TS_ASSERT_THROWS_NOTHING(expected.update());
+    TS_ASSERT_THROWS_NOTHING(composite.update());
+    PeakBoundingBox region;
+    TS_ASSERT_THROWS_NOTHING(expected.updateWithSlicePoint(region));
+    TS_ASSERT_THROWS_NOTHING(composite.updateWithSlicePoint(region));
+    TS_ASSERT_EQUALS(expected.changeShownDim(), composite.changeShownDim());
+    TS_ASSERT_EQUALS(expected.isLabelOfFreeAxis(""),
+                     composite.isLabelOfFreeAxis(""));
   }
 
-  void test_add_peaks_presenter()
-  {
+  void test_add_peaks_presenter() {
     CompositePeaksPresenter presenter(&_fakeZoomableView);
     const size_t initialSize = presenter.size();
 
-    auto candidate = boost::make_shared<NiceMock<MockPeaksPresenter> >();
+    auto candidate = boost::make_shared<NiceMock<MockPeaksPresenter>>();
     EXPECT_CALL(*candidate, contentsDifferent(_)).WillOnce(Return(true));
 
-    presenter.addPeaksPresenter( candidate );
-    TSM_ASSERT_EQUALS("Expected one item to be added.", initialSize + 1, presenter.size());
+    presenter.addPeaksPresenter(candidate);
+    TSM_ASSERT_EQUALS("Expected one item to be added.", initialSize + 1,
+                      presenter.size());
   }
 
-  void test_keep_presenters_unique()
-  {
+  void test_keep_presenters_unique() {
     CompositePeaksPresenter presenter(&_fakeZoomableView);
     const size_t initialSize = presenter.size();
-    auto presenterToAdd = boost::make_shared<NiceMock<MockPeaksPresenter> >();
-    EXPECT_CALL(*presenterToAdd, contentsDifferent(_)).WillRepeatedly(Return(true));
-    presenter.addPeaksPresenter( presenterToAdd );
-    presenter.addPeaksPresenter( presenterToAdd ); // Try to add it again.
-    TSM_ASSERT_EQUALS("Should not be able to add the same item more than once.", initialSize + 1, presenter.size());
+    auto presenterToAdd = boost::make_shared<NiceMock<MockPeaksPresenter>>();
+    EXPECT_CALL(*presenterToAdd, contentsDifferent(_))
+        .WillRepeatedly(Return(true));
+    presenter.addPeaksPresenter(presenterToAdd);
+    presenter.addPeaksPresenter(presenterToAdd); // Try to add it again.
+    TSM_ASSERT_EQUALS("Should not be able to add the same item more than once.",
+                      initialSize + 1, presenter.size());
   }
 
-  void test_clear()
-  {
+  void test_clear() {
     NiceMock<MockZoomablePeaksView> mockZoomableView;
-    EXPECT_CALL(mockZoomableView, detach()).Times(1); // Should detach itself when no nested presenters are present.
+    EXPECT_CALL(mockZoomableView, detach())
+        .Times(
+            1); // Should detach itself when no nested presenters are present.
 
     CompositePeaksPresenter composite(&mockZoomableView);
     const size_t initialSize = composite.size();
-    auto a = boost::make_shared<NiceMock<MockPeaksPresenter> >();
-    EXPECT_CALL(*a, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allow us to add the subject
-    auto b = boost::make_shared<NiceMock<MockPeaksPresenter> >();
-    EXPECT_CALL(*b, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add the subject
+    auto a = boost::make_shared<NiceMock<MockPeaksPresenter>>();
+    EXPECT_CALL(*a, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allow us to add the subject
+    auto b = boost::make_shared<NiceMock<MockPeaksPresenter>>();
+    EXPECT_CALL(*b, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add the subject
 
     composite.addPeaksPresenter(a); // Add one subject
     composite.addPeaksPresenter(b); // Add another subject
 
     composite.clear();
 
-    TSM_ASSERT_EQUALS("Should be back to initial size after clearing.", initialSize, composite.size());
+    TSM_ASSERT_EQUALS("Should be back to initial size after clearing.",
+                      initialSize, composite.size());
 
-    /*After clearing, the composite presenter should behave identically to a &_fakeZoomableViewPeaks presenter.*/
+    /*After clearing, the composite presenter should behave identically to a
+     * &_fakeZoomableViewPeaks presenter.*/
     NullPeaksPresenter expected;
     TS_ASSERT_THROWS_NOTHING(expected.update());
     TS_ASSERT_THROWS_NOTHING(composite.update());
@@ -105,19 +109,22 @@ public:
     TS_ASSERT_THROWS_NOTHING(expected.updateWithSlicePoint(region));
     TS_ASSERT_THROWS_NOTHING(composite.updateWithSlicePoint(region));
     TS_ASSERT_EQUALS(expected.changeShownDim(), composite.changeShownDim());
-    TS_ASSERT_EQUALS(expected.isLabelOfFreeAxis("") , composite.isLabelOfFreeAxis(""));
-    TSM_ASSERT("Should have detached upon clear", Mock::VerifyAndClearExpectations(&mockZoomableView));
+    TS_ASSERT_EQUALS(expected.isLabelOfFreeAxis(""),
+                     composite.isLabelOfFreeAxis(""));
+    TSM_ASSERT("Should have detached upon clear",
+               Mock::VerifyAndClearExpectations(&mockZoomableView));
   }
 
   /**
-  Check that when no subject presenters have been added, that the composite uses the 'default' for the updateWithSlicePoint method.
+  Check that when no subject presenters have been added, that the composite uses
+  the 'default' for the updateWithSlicePoint method.
   */
-  void test_updateWithSlicePoint_default()
-  {
+  void test_updateWithSlicePoint_default() {
     // Create a default.
-    MockPeaksPresenter* mockDefault = new MockPeaksPresenter;
+    MockPeaksPresenter *mockDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(mockDefault);
-    EXPECT_CALL(*mockDefault, updateWithSlicePoint(_)).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockDefault, updateWithSlicePoint(_))
+        .Times(1); // Expect the method on the default to be called.
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView, defaultPresenter);
@@ -128,14 +135,15 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockDefault));
   }
 
-  void test_updateWithSlicePoint()
-  {
-    MockPeaksPresenter* mockPresenter = new MockPeaksPresenter;
+  void test_updateWithSlicePoint() {
+    MockPeaksPresenter *mockPresenter = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter(mockPresenter);
-    EXPECT_CALL(*mockPresenter, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*mockPresenter, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
     EXPECT_CALL(*mockPresenter, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*mockPresenter, updateWithSlicePoint(_)).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockPresenter, updateWithSlicePoint(_))
+        .Times(1); // Expect the method on the default to be called.
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
@@ -149,24 +157,27 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockPresenter));
   }
 
-  void test_getTransformName_default()
-  {
-    MockPeaksPresenter* mockDefault = new MockPeaksPresenter;
+  void test_getTransformName_default() {
+    MockPeaksPresenter *mockDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(mockDefault);
-    EXPECT_CALL(*mockDefault, getTransformName()).Times(1).WillOnce(Return(""));// Expect the method on the default to be called.
+    EXPECT_CALL(*mockDefault, getTransformName())
+        .Times(1)
+        .WillOnce(Return("")); // Expect the method on the default to be called.
 
     defaultPresenter->getTransformName();
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockDefault));
   }
 
-  void test_getTransformName()
-  {
-    MockPeaksPresenter* mockPresenter = new MockPeaksPresenter;
+  void test_getTransformName() {
+    MockPeaksPresenter *mockPresenter = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter(mockPresenter);
-    EXPECT_CALL(*mockPresenter, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*mockPresenter, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     EXPECT_CALL(*mockPresenter, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*mockPresenter, getTransformName()).Times(1).WillOnce(Return("")); 
+    EXPECT_CALL(*mockPresenter, getTransformName())
+        .Times(1)
+        .WillOnce(Return(""));
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
@@ -179,14 +190,15 @@ public:
   }
 
   /**
-  Check that when no subject presenters have been added, that the composite uses the 'default' for the update method.
+  Check that when no subject presenters have been added, that the composite uses
+  the 'default' for the update method.
   */
-  void test_update_default()
-  {
+  void test_update_default() {
     // Create a default.
-    MockPeaksPresenter* mockDefault = new MockPeaksPresenter;
+    MockPeaksPresenter *mockDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(mockDefault);
-    EXPECT_CALL(*mockDefault, update()).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockDefault, update())
+        .Times(1); // Expect the method on the default to be called.
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView, defaultPresenter);
@@ -196,13 +208,14 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockDefault));
   }
 
-  void test_update()
-  {
-    MockPeaksPresenter* mockPresenter = new MockPeaksPresenter;
+  void test_update() {
+    MockPeaksPresenter *mockPresenter = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter(mockPresenter);
-    EXPECT_CALL(*mockPresenter, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*mockPresenter, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
-    EXPECT_CALL(*mockPresenter, update()).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockPresenter, update())
+        .Times(1); // Expect the method on the default to be called.
     EXPECT_CALL(*mockPresenter, registerOwningPresenter(_)).Times(AtLeast(1));
 
     // Create the composite.
@@ -215,24 +228,24 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockPresenter));
   }
 
-  void test_presentedWorkspaces()
-  {
-    //One nested presenter
+  void test_presentedWorkspaces() {
+    // One nested presenter
     SetPeaksWorkspaces setA;
-    MockPeaksPresenter* pA = new MockPeaksPresenter;
-    EXPECT_CALL(*pA, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    MockPeaksPresenter *pA = new MockPeaksPresenter;
+    EXPECT_CALL(*pA, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     PeaksPresenter_sptr A(pA);
     EXPECT_CALL(*pA, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*pA, presentedWorkspaces()).WillOnce(Return(setA)); 
-    
-    //Another nested presenter
+    EXPECT_CALL(*pA, presentedWorkspaces()).WillOnce(Return(setA));
+
+    // Another nested presenter
     SetPeaksWorkspaces setB;
-    MockPeaksPresenter* pB = new MockPeaksPresenter;
-    EXPECT_CALL(*pB, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    MockPeaksPresenter *pB = new MockPeaksPresenter;
+    EXPECT_CALL(*pB, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     PeaksPresenter_sptr B(pB);
     EXPECT_CALL(*pB, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*pB, presentedWorkspaces()).WillOnce(Return(setB)); 
-
+    EXPECT_CALL(*pB, presentedWorkspaces()).WillOnce(Return(setB));
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
@@ -246,17 +259,18 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pB));
   }
 
-  void test_changeShownDimension()
-  {
+  void test_changeShownDimension() {
     const bool PASS = true;
     const bool FAIL = false;
-    
+
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    
-    MockPeaksPresenter* A = new NiceMock<MockPeaksPresenter>();
-    MockPeaksPresenter* B = new NiceMock<MockPeaksPresenter>();
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+
+    MockPeaksPresenter *A = new NiceMock<MockPeaksPresenter>();
+    MockPeaksPresenter *B = new NiceMock<MockPeaksPresenter>();
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     PeaksPresenter_sptr subjectA(A);
     PeaksPresenter_sptr subjectB(B);
 
@@ -267,7 +281,8 @@ public:
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT_EQUALS("Should return FAIL, because both of the subjects FAIL", FAIL, composite.changeShownDim()); 
+    TSM_ASSERT_EQUALS("Should return FAIL, because both of the subjects FAIL",
+                      FAIL, composite.changeShownDim());
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
     composite.clear();
@@ -275,13 +290,17 @@ public:
     // if one subject FAIL, composite should FAIL.
     EXPECT_CALL(*A, changeShownDim()).WillOnce(Return(PASS));
     EXPECT_CALL(*B, changeShownDim()).WillOnce(Return(FAIL));
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT_EQUALS("Should return FAIL, because at least one of the subjects return FAIL", FAIL, composite.changeShownDim());
+    TSM_ASSERT_EQUALS(
+        "Should return FAIL, because at least one of the subjects return FAIL",
+        FAIL, composite.changeShownDim());
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
     composite.clear();
@@ -289,28 +308,32 @@ public:
     // if subjects both PASS, composite should PASS.
     EXPECT_CALL(*A, changeShownDim()).WillOnce(Return(PASS));
     EXPECT_CALL(*B, changeShownDim()).WillOnce(Return(PASS));
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT("Should return PASS, because both of the subject PASS", composite.changeShownDim());
+    TSM_ASSERT("Should return PASS, because both of the subject PASS",
+               composite.changeShownDim());
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
   }
 
-  void test_isLabelOfFreeAxis()
-  {
+  void test_isLabelOfFreeAxis() {
     const bool PASS = true;
     const bool FAIL = false;
-    
+
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    
-    MockPeaksPresenter* A = new NiceMock<MockPeaksPresenter>();
-    MockPeaksPresenter* B = new NiceMock<MockPeaksPresenter>();
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+
+    MockPeaksPresenter *A = new NiceMock<MockPeaksPresenter>();
+    MockPeaksPresenter *B = new NiceMock<MockPeaksPresenter>();
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     PeaksPresenter_sptr subjectA(A);
     PeaksPresenter_sptr subjectB(B);
 
@@ -321,7 +344,8 @@ public:
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT("Should return FAIL, because both of the subjects FAIL", FAIL == composite.isLabelOfFreeAxis("")); 
+    TSM_ASSERT("Should return FAIL, because both of the subjects FAIL",
+               FAIL == composite.isLabelOfFreeAxis(""));
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
     composite.clear();
@@ -329,13 +353,17 @@ public:
     // if one subject FAIL, composite should FAIL.
     EXPECT_CALL(*A, isLabelOfFreeAxis(_)).WillOnce(Return(PASS));
     EXPECT_CALL(*B, isLabelOfFreeAxis(_)).WillOnce(Return(FAIL));
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT("Should return FAIL, because at least one of the subjects return FAIL", FAIL == composite.isLabelOfFreeAxis(""));
+    TSM_ASSERT(
+        "Should return FAIL, because at least one of the subjects return FAIL",
+        FAIL == composite.isLabelOfFreeAxis(""));
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
     composite.clear();
@@ -343,54 +371,58 @@ public:
     // if subjects both PASS, composite should PASS.
     EXPECT_CALL(*A, isLabelOfFreeAxis(_)).WillOnce(Return(PASS));
     EXPECT_CALL(*B, isLabelOfFreeAxis(_)).WillOnce(Return(PASS));
-    EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*A, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*B, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
 
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    TSM_ASSERT("Should return PASS, because both of the subject PASS", PASS == composite.isLabelOfFreeAxis(""));
+    TSM_ASSERT("Should return PASS, because both of the subject PASS",
+               PASS == composite.isLabelOfFreeAxis(""));
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
   }
 
-  void test_maximum_allowed_peaks()
-  {
+  void test_maximum_allowed_peaks() {
     CompositePeaksPresenter presenter(&_fakeZoomableView);
     // Add peaksWS
     const int limit = 10;
-    for(int i = 0; i < limit; ++i)
-    {
-     auto subject = boost::make_shared<NiceMock<MockPeaksPresenter> >();
-     EXPECT_CALL(*subject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-     TS_ASSERT_THROWS_NOTHING(presenter.addPeaksPresenter(subject));
+    for (int i = 0; i < limit; ++i) {
+      auto subject = boost::make_shared<NiceMock<MockPeaksPresenter>>();
+      EXPECT_CALL(*subject, contentsDifferent(_))
+          .WillRepeatedly(Return(true)); // Allows us to add to composite
+      TS_ASSERT_THROWS_NOTHING(presenter.addPeaksPresenter(subject));
     }
 
-
     // Add a peaksWS beyond the limit of allowed number of peaksWS.
 
-    TS_ASSERT_THROWS(presenter.addPeaksPresenter(boost::make_shared<NiceMock<MockPeaksPresenter> >()), std::invalid_argument&);
+    TS_ASSERT_THROWS(presenter.addPeaksPresenter(
+                         boost::make_shared<NiceMock<MockPeaksPresenter>>()),
+                     std::invalid_argument &);
   }
 
-  void test_default_palette()
-  {
+  void test_default_palette() {
     PeakPalette<PeakViewColor> actualDefaultPalette;
 
     CompositePeaksPresenter presenter(&_fakeZoomableView);
     auto presenterDefaultPalette = presenter.getPalette();
 
-    TSM_ASSERT_EQUALS("CompositePeaksPresenter should be using a default palette until changed.", actualDefaultPalette, presenterDefaultPalette);
+    TSM_ASSERT_EQUALS("CompositePeaksPresenter should be using a default "
+                      "palette until changed.",
+                      actualDefaultPalette, presenterDefaultPalette);
   }
 
-  void test_set_background_color()
-  {
+  void test_set_background_color() {
     const PeakViewColor newColor(Qt::red, Qt::red, Qt::red);
 
     // Prepare subject objects.
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces set;
     set.insert(peaksWS);
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pSubject, setBackgroundColor(newColor)).Times(1);
@@ -398,7 +430,8 @@ public:
 
     // Set a background color on the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     composite.setBackgroundColor(peaksWS, newColor);
 
@@ -410,15 +443,15 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_set_foreground_color()
-  {
+  void test_set_foreground_color() {
     const PeakViewColor newColor(Qt::red, Qt::red, Qt::red);
 
     // Prepare subject objects.
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces set;
     set.insert(peaksWS);
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, setForegroundColor(newColor)).Times(1);
@@ -426,7 +459,8 @@ public:
 
     // Set a background colour on the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     composite.setForegroundColor(peaksWS, newColor);
 
@@ -438,8 +472,7 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_remove()
-  {
+  void test_remove() {
     // Create a subject presenter that will be deleted.
     auto A = new NiceMock<DyingMockPeaksPresenter>();
     // Create a subject presenter that won't be deleted.
@@ -447,37 +480,47 @@ public:
 
     {
       // Create some input peaks workspaces.
-      IPeaksWorkspace_sptr peaksWS_A = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+      IPeaksWorkspace_sptr peaksWS_A =
+          boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
       SetPeaksWorkspaces setA;
       setA.insert(peaksWS_A);
 
-      IPeaksWorkspace_sptr peaksWS_B = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+      IPeaksWorkspace_sptr peaksWS_B =
+          boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
       SetPeaksWorkspaces setB;
       setB.insert(peaksWS_B);
 
       PeaksPresenter_sptr subjectA(A);
       EXPECT_CALL(*A, presentedWorkspaces()).WillRepeatedly(Return(setA));
-      EXPECT_CALL(*A, die()).Times(1); // This will be called on destruction, because we will foreably remove this presenter!
+      EXPECT_CALL(*A, die()).Times(1); // This will be called on destruction,
+                                       // because we will foreably remove this
+                                       // presenter!
 
       PeaksPresenter_sptr subjectB(B);
       EXPECT_CALL(*B, presentedWorkspaces()).WillRepeatedly(Return(setB));
-      EXPECT_CALL(*B, die()).Times(1); // This will be called on destruction, because we will foreably remove this presenter!
+      EXPECT_CALL(*B, die()).Times(1); // This will be called on destruction,
+                                       // because we will foreably remove this
+                                       // presenter!
 
       MockZoomablePeaksView mockZoomablePeaksView;
 
       // Create the composite
       CompositePeaksPresenter composite(&mockZoomablePeaksView);
-      EXPECT_CALL(*A, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-      EXPECT_CALL(*B, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+      EXPECT_CALL(*A, contentsDifferent(_))
+          .WillRepeatedly(Return(true)); // Allows us to add to composite
+      EXPECT_CALL(*B, contentsDifferent(_))
+          .WillRepeatedly(Return(true)); // Allows us to add to composite
       composite.addPeaksPresenter(subjectA);
       composite.addPeaksPresenter(subjectB);
 
-      const size_t preRemovalSize = composite.size(); // benchmark the current size.
+      const size_t preRemovalSize =
+          composite.size(); // benchmark the current size.
 
       // Remove one of the presenters via its workspace.
       composite.remove(peaksWS_A);
 
-      TSM_ASSERT_EQUALS("A presenter should have been removed.",preRemovalSize, composite.size() + 1);
+      TSM_ASSERT_EQUALS("A presenter should have been removed.", preRemovalSize,
+                        composite.size() + 1);
 
       // Expect the composite to detach itself when everything is removed.
       EXPECT_CALL(mockZoomablePeaksView, detach()).Times(1);
@@ -485,32 +528,34 @@ public:
       // Remove the other presenter via its workspace.
       composite.remove(peaksWS_B);
 
-      TSM_ASSERT_EQUALS("A presenter should have been removed.",preRemovalSize, composite.size() + 2);
+      TSM_ASSERT_EQUALS("A presenter should have been removed.", preRemovalSize,
+                        composite.size() + 2);
 
-      TSM_ASSERT("Composite should have detached itself", Mock::VerifyAndClearExpectations(&mockZoomablePeaksView));
+      TSM_ASSERT("Composite should have detached itself",
+                 Mock::VerifyAndClearExpectations(&mockZoomablePeaksView));
     }
     // Check that the correct presenter has been removed.
     TS_ASSERT(Mock::VerifyAndClearExpectations(A));
     TS_ASSERT(Mock::VerifyAndClearExpectations(B));
   }
 
-  void test_remove_default()
-  {
+  void test_remove_default() {
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    auto peaksWorkspace = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    auto peaksWorkspace =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
 
-    //Try to remove a peaks workspace & associated presenter that doesn't exist from a default constructed composite.
+    // Try to remove a peaks workspace & associated presenter that doesn't exist
+    // from a default constructed composite.
     TS_ASSERT_THROWS_NOTHING(composite.remove(peaksWorkspace));
   }
 
-
-  void do_test_setShown(bool expectedToShow)
-  {
+  void do_test_setShown(bool expectedToShow) {
     // Prepare subject objects.
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces set;
     set.insert(peaksWS);
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, setShown(expectedToShow)).Times(1);
@@ -518,7 +563,8 @@ public:
 
     // Create the composite and add the test presenter.
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
 
     // execute setshown(...)
@@ -527,92 +573,96 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_setShown()
-  {
+  void test_setShown() {
     const bool SHOW = true;
     const bool HIDE = false;
     // Test that calling method on composite causes subject presenters to show.
-    do_test_setShown(SHOW); 
+    do_test_setShown(SHOW);
     // Test that calling method on composite causes subject presenters to hide.
-    do_test_setShown(HIDE); 
+    do_test_setShown(HIDE);
   }
 
-  void test_setShown_default()
-  {
+  void test_setShown_default() {
     const bool expectedFlag = true;
 
     // Create a default.
-    MockPeaksPresenter* mockDefault = new MockPeaksPresenter;
+    MockPeaksPresenter *mockDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(mockDefault);
-    EXPECT_CALL(*mockDefault, setShown(expectedFlag)).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockDefault, setShown(expectedFlag))
+        .Times(1); // Expect the method on the default to be called.
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView, defaultPresenter);
     // Call the method on the composite.
-    composite.setShown(boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(), expectedFlag);
+    composite.setShown(
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(),
+        expectedFlag);
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockDefault));
   }
 
-  void test_setBackgroundRadiusShown_default()
-  {
+  void test_setBackgroundRadiusShown_default() {
     const bool expectedFlag = true;
 
     // Create a default.
-    MockPeaksPresenter* mockDefault = new MockPeaksPresenter;
+    MockPeaksPresenter *mockDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(mockDefault);
-    EXPECT_CALL(*mockDefault, showBackgroundRadius(expectedFlag)).Times(1); // Expect the method on the default to be called.
+    EXPECT_CALL(*mockDefault, showBackgroundRadius(expectedFlag))
+        .Times(1); // Expect the method on the default to be called.
 
-     // Create the composite.
+    // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView, defaultPresenter);
     // Call the method on the composite.
-    composite.setBackgroundRadiusShown(boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(), expectedFlag);
+    composite.setBackgroundRadiusShown(
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(),
+        expectedFlag);
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockDefault));
   }
 
-  void test_getBackroundColoor_default()
-  {
-      CompositePeaksPresenter composite(&_fakeZoomableView);
-      TSM_ASSERT_THROWS(
-          "Cannot fetch background colors until nested presenters have been "
-          "added.",
-          composite.getBackgroundPeakViewColor(
-              boost::make_shared<Mantid::DataObjects::PeaksWorkspace>()),
-          std::runtime_error &);
+  void test_getBackroundColoor_default() {
+    CompositePeaksPresenter composite(&_fakeZoomableView);
+    TSM_ASSERT_THROWS(
+        "Cannot fetch background colors until nested presenters have been "
+        "added.",
+        composite.getBackgroundPeakViewColor(
+            boost::make_shared<Mantid::DataObjects::PeaksWorkspace>()),
+        std::runtime_error &);
   }
 
-  void test_getForegroundColor_default()
-  {
-      CompositePeaksPresenter composite(&_fakeZoomableView);
-      TSM_ASSERT_THROWS(
-          "Cannot fetch foreground colours until nested presenters have been "
-          "added.",
-          composite.getForegroundPeakViewColor(
-              boost::make_shared<Mantid::DataObjects::PeaksWorkspace>()),
-          std::runtime_error &);
+  void test_getForegroundColor_default() {
+    CompositePeaksPresenter composite(&_fakeZoomableView);
+    TSM_ASSERT_THROWS(
+        "Cannot fetch foreground colours until nested presenters have been "
+        "added.",
+        composite.getForegroundPeakViewColor(
+            boost::make_shared<Mantid::DataObjects::PeaksWorkspace>()),
+        std::runtime_error &);
   }
 
-  void test_zoomToPeak()
-  {
+  void test_zoomToPeak() {
     const int peakIndex = 0;
     // Prepare subject objects.
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>(); 
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces set;
     set.insert(peaksWS);
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*pSubject, getBoundingBox(peakIndex)).Times(1).WillOnce(Return(PeakBoundingBox()));
+    EXPECT_CALL(*pSubject, getBoundingBox(peakIndex))
+        .Times(1)
+        .WillOnce(Return(PeakBoundingBox()));
     EXPECT_CALL(*pSubject, presentedWorkspaces()).WillOnce(Return(set));
 
-    //Prepare zoomable peak view.
+    // Prepare zoomable peak view.
     MockZoomablePeaksView mockZoomableView;
     EXPECT_CALL(mockZoomableView, zoomToRectangle(_)).Times(1);
 
     // Create the composite and add the test presenter.
     CompositePeaksPresenter composite(&mockZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
 
     composite.zoomToPeak(peaksWS, peakIndex);
@@ -621,43 +671,42 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(&mockZoomableView));
   }
 
-  void test_setPeakSizeOnProjection()
-  {
+  void test_setPeakSizeOnProjection() {
     const double fraction = 0.5;
 
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pSubject, setPeakSizeOnProjection(fraction)).Times(1);
 
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     composite.setPeakSizeOnProjection(fraction);
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_setPeakSizeIntoProjection()
-  {
+  void test_setPeakSizeIntoProjection() {
     const double fraction = 0.5;
 
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pSubject, setPeakSizeIntoProjection(fraction)).Times(1);
 
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     composite.setPeakSizeIntoProjection(fraction);
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_getPeakSizeOnProjection_default()
-  {
-    MockPeaksPresenter* pDefault = new MockPeaksPresenter;
+  void test_getPeakSizeOnProjection_default() {
+    MockPeaksPresenter *pDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(pDefault);
     EXPECT_CALL(*pDefault, getPeakSizeOnProjection()).WillOnce(Return(0));
 
@@ -667,9 +716,8 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pDefault));
   }
 
-  void test_getPeakSizeIntoProjection_default()
-  {
-    MockPeaksPresenter* pDefault = new MockPeaksPresenter;
+  void test_getPeakSizeIntoProjection_default() {
+    MockPeaksPresenter *pDefault = new MockPeaksPresenter;
     PeaksPresenter_sptr defaultPresenter(pDefault);
     EXPECT_CALL(*pDefault, getPeakSizeIntoProjection()).WillOnce(Return(0));
 
@@ -679,55 +727,57 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pDefault));
   }
 
-  void test_getPeakSizeOnProjection()
-  {
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+  void test_getPeakSizeOnProjection() {
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pSubject, getPeakSizeOnProjection()).WillOnce(Return(1));
 
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     TS_ASSERT_EQUALS(1, composite.getPeakSizeOnProjection())
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_getPeakSizeIntoProjection()
-  {
-    MockPeaksPresenter* pSubject = new MockPeaksPresenter;
+  void test_getPeakSizeIntoProjection() {
+    MockPeaksPresenter *pSubject = new MockPeaksPresenter;
     PeaksPresenter_sptr subject(pSubject);
     EXPECT_CALL(*pSubject, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pSubject, getPeakSizeIntoProjection()).WillOnce(Return(1));
 
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pSubject, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pSubject, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(subject);
     TS_ASSERT_EQUALS(1, composite.getPeakSizeIntoProjection())
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubject));
   }
 
-  void test_getPeaksPresenter_throws_if_unknown_name()
-  {
+  void test_getPeaksPresenter_throws_if_unknown_name() {
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    TSM_ASSERT_THROWS("Search should fail to find any presenters, as there are none.", composite.getPeaksPresenter(QString("x")), std::invalid_argument&);
+    TSM_ASSERT_THROWS(
+        "Search should fail to find any presenters, as there are none.",
+        composite.getPeaksPresenter(QString("x")), std::invalid_argument &);
   }
 
-  void test_lookup_presenters_via_workspace_names_using_getPeaksPresenter()
-  {
+  void test_lookup_presenters_via_workspace_names_using_getPeaksPresenter() {
     using namespace Mantid::API;
 
-    //One nested presenter. Create setup environment.
-    IPeaksWorkspace_sptr peaksWS_1 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-    IPeaksWorkspace_sptr peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    // One nested presenter. Create setup environment.
+    IPeaksWorkspace_sptr peaksWS_1 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    IPeaksWorkspace_sptr peaksWS_2 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     AnalysisDataService::Instance().add("ws1", peaksWS_1);
     AnalysisDataService::Instance().add("ws2", peaksWS_2);
     SetPeaksWorkspaces set;
     set.insert(peaksWS_1);
     set.insert(peaksWS_2);
-    MockPeaksPresenter* pPresenter = new MockPeaksPresenter;
+    MockPeaksPresenter *pPresenter = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter(pPresenter);
     EXPECT_CALL(*pPresenter, registerOwningPresenter(_)).Times(AtLeast(1));
     EXPECT_CALL(*pPresenter, presentedWorkspaces()).WillRepeatedly(Return(set));
@@ -745,11 +795,13 @@ public:
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pPresenter, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pPresenter, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(presenter);
 
     // Now perform searches
-    PeaksPresenter* foundPresenter = composite.getPeaksPresenter(QString("ws1"));
+    PeaksPresenter *foundPresenter =
+        composite.getPeaksPresenter(QString("ws1"));
     TS_ASSERT_EQUALS(foundPresenter, pPresenter)
     foundPresenter = composite.getPeaksPresenter(QString("ws2"));
     TS_ASSERT_EQUALS(foundPresenter, pPresenter)
@@ -760,13 +812,15 @@ public:
     AnalysisDataService::Instance().remove("ws2");
   }
 
-  void test_lookup_presenters_via_workspace_names_using_getPeaksPresenter_continued()
-  {
+  void
+  test_lookup_presenters_via_workspace_names_using_getPeaksPresenter_continued() {
     using namespace Mantid::API;
 
-    //One nested presenter. Create setup environment.
-    IPeaksWorkspace_sptr peaksWS_1 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-    IPeaksWorkspace_sptr peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    // One nested presenter. Create setup environment.
+    IPeaksWorkspace_sptr peaksWS_1 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    IPeaksWorkspace_sptr peaksWS_2 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     AnalysisDataService::Instance().add("ws1", peaksWS_1);
     AnalysisDataService::Instance().add("ws2", peaksWS_2);
     SetPeaksWorkspaces set1;
@@ -774,23 +828,26 @@ public:
     SetPeaksWorkspaces set2;
     set2.insert(peaksWS_2);
 
-    MockPeaksPresenter* pPresenter1 = new MockPeaksPresenter;
+    MockPeaksPresenter *pPresenter1 = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter1(pPresenter1);
 
-    MockPeaksPresenter* pPresenter2 = new MockPeaksPresenter;
+    MockPeaksPresenter *pPresenter2 = new MockPeaksPresenter;
     PeaksPresenter_sptr presenter2(pPresenter2);
 
-
     EXPECT_CALL(*pPresenter1, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*pPresenter1, presentedWorkspaces()).WillRepeatedly(Return(set1));
+    EXPECT_CALL(*pPresenter1, presentedWorkspaces())
+        .WillRepeatedly(Return(set1));
 
     EXPECT_CALL(*pPresenter2, registerOwningPresenter(_)).Times(AtLeast(1));
-    EXPECT_CALL(*pPresenter2, presentedWorkspaces()).WillRepeatedly(Return(set2));
+    EXPECT_CALL(*pPresenter2, presentedWorkspaces())
+        .WillRepeatedly(Return(set2));
 
     // Create the composite.
     CompositePeaksPresenter composite(&_fakeZoomableView);
-    EXPECT_CALL(*pPresenter1, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-    EXPECT_CALL(*pPresenter2, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pPresenter1, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pPresenter2, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
     composite.addPeaksPresenter(presenter1);
     composite.addPeaksPresenter(presenter2);
 
@@ -807,7 +864,8 @@ public:
      */
 
     // Now perform searches
-    PeaksPresenter* foundPresenter = composite.getPeaksPresenter(QString("ws1"));
+    PeaksPresenter *foundPresenter =
+        composite.getPeaksPresenter(QString("ws1"));
     TS_ASSERT_EQUALS(foundPresenter, pPresenter1)
     foundPresenter = composite.getPeaksPresenter(QString("ws2"));
     TS_ASSERT_EQUALS(foundPresenter, pPresenter2)
@@ -819,154 +877,164 @@ public:
     AnalysisDataService::Instance().remove("ws2");
   }
 
-  void test_notify_workspace_replaced_with_same_ADS_key()
-  {
-      using namespace Mantid::API;
-
-      //One nested presenter. Create setup environment.
-      IPeaksWorkspace_sptr peaksWS_1 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-      IPeaksWorkspace_sptr peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-      AnalysisDataService::Instance().add("ws1", peaksWS_1);
-      AnalysisDataService::Instance().add("ws2", peaksWS_2);
-      SetPeaksWorkspaces set1;
-      set1.insert(peaksWS_1);
-      SetPeaksWorkspaces set2;
-      set2.insert(peaksWS_2);
-
-      MockPeaksPresenter* pPresenter1 = new MockPeaksPresenter;
-      PeaksPresenter_sptr presenter1(pPresenter1);
+  void test_notify_workspace_replaced_with_same_ADS_key() {
+    using namespace Mantid::API;
 
-      MockPeaksPresenter* pPresenter2 = new MockPeaksPresenter;
-      PeaksPresenter_sptr presenter2(pPresenter2);
+    // One nested presenter. Create setup environment.
+    IPeaksWorkspace_sptr peaksWS_1 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    IPeaksWorkspace_sptr peaksWS_2 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    AnalysisDataService::Instance().add("ws1", peaksWS_1);
+    AnalysisDataService::Instance().add("ws2", peaksWS_2);
+    SetPeaksWorkspaces set1;
+    set1.insert(peaksWS_1);
+    SetPeaksWorkspaces set2;
+    set2.insert(peaksWS_2);
 
-      EXPECT_CALL(*pPresenter1, registerOwningPresenter(_)).Times(AtLeast(1));
-      EXPECT_CALL(*pPresenter1, presentedWorkspaces()).WillRepeatedly(Return(set1));
+    MockPeaksPresenter *pPresenter1 = new MockPeaksPresenter;
+    PeaksPresenter_sptr presenter1(pPresenter1);
 
-      EXPECT_CALL(*pPresenter2, registerOwningPresenter(_)).Times(AtLeast(1));
-      EXPECT_CALL(*pPresenter2, presentedWorkspaces()).WillRepeatedly(Return(set2));
+    MockPeaksPresenter *pPresenter2 = new MockPeaksPresenter;
+    PeaksPresenter_sptr presenter2(pPresenter2);
 
+    EXPECT_CALL(*pPresenter1, registerOwningPresenter(_)).Times(AtLeast(1));
+    EXPECT_CALL(*pPresenter1, presentedWorkspaces())
+        .WillRepeatedly(Return(set1));
 
-      // Create the composite.
-      CompositePeaksPresenter composite(&_fakeZoomableView);
-      EXPECT_CALL(*pPresenter1, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-      EXPECT_CALL(*pPresenter2, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-      composite.addPeaksPresenter(presenter1);
-      composite.addPeaksPresenter(presenter2);
+    EXPECT_CALL(*pPresenter2, registerOwningPresenter(_)).Times(AtLeast(1));
+    EXPECT_CALL(*pPresenter2, presentedWorkspaces())
+        .WillRepeatedly(Return(set2));
 
-      /*
+    // Create the composite.
+    CompositePeaksPresenter composite(&_fakeZoomableView);
+    EXPECT_CALL(*pPresenter1, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pPresenter2, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    composite.addPeaksPresenter(presenter1);
+    composite.addPeaksPresenter(presenter2);
 
-        composite
-            |
-            |
-        -------------
-        |            |
-        p1 (ws1)     p2 (ws2)
+    /*
 
+      composite
+          |
+          |
+      -------------
+      |            |
+      p1 (ws1)     p2 (ws2)
 
-       */
 
-      /*
-      Same key different object.
-      Now we are going to replace ws2, and we expect the sub presenter for that to be informed.
-      */
+     */
 
-      EXPECT_CALL(*pPresenter2, reInitialize(_)).Times(1);
+    /*
+    Same key different object.
+    Now we are going to replace ws2, and we expect the sub presenter for that to
+    be informed.
+    */
 
-      peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-      AnalysisDataService::Instance().addOrReplace("ws2", peaksWS_2); // Same key (name) different object.
-      composite.notifyWorkspaceChanged("ws2", peaksWS_2);
+    EXPECT_CALL(*pPresenter2, reInitialize(_)).Times(1);
 
-      // Clean up.
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter1));
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter2));
-      AnalysisDataService::Instance().remove("ws1");
-      AnalysisDataService::Instance().remove("ws2");
+    peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    AnalysisDataService::Instance().addOrReplace(
+        "ws2", peaksWS_2); // Same key (name) different object.
+    composite.notifyWorkspaceChanged("ws2", peaksWS_2);
 
+    // Clean up.
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter1));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter2));
+    AnalysisDataService::Instance().remove("ws1");
+    AnalysisDataService::Instance().remove("ws2");
   }
 
-  void test_notify_workspace_renamed_in_ADS()
-  {
-      using namespace Mantid::API;
-
-      //One nested presenter. Create setup environment.
-      IPeaksWorkspace_sptr peaksWS_1 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-      IPeaksWorkspace_sptr peaksWS_2 = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
-      AnalysisDataService::Instance().add("ws1", peaksWS_1);
-      AnalysisDataService::Instance().add("ws2", peaksWS_2);
-      SetPeaksWorkspaces set1;
-      set1.insert(peaksWS_1);
-      SetPeaksWorkspaces set2;
-      set2.insert(peaksWS_2);
-
-      MockPeaksPresenter* pPresenter1 = new MockPeaksPresenter;
-      PeaksPresenter_sptr presenter1(pPresenter1);
-
-      MockPeaksPresenter* pPresenter2 = new MockPeaksPresenter;
-      PeaksPresenter_sptr presenter2(pPresenter2);
-
-
-      EXPECT_CALL(*pPresenter1, registerOwningPresenter(_)).Times(AtLeast(1));
-      EXPECT_CALL(*pPresenter1, presentedWorkspaces()).WillRepeatedly(Return(set1));
+  void test_notify_workspace_renamed_in_ADS() {
+    using namespace Mantid::API;
 
-      EXPECT_CALL(*pPresenter2, registerOwningPresenter(_)).Times(AtLeast(1));
-      EXPECT_CALL(*pPresenter2, presentedWorkspaces()).WillRepeatedly(Return(set2));
+    // One nested presenter. Create setup environment.
+    IPeaksWorkspace_sptr peaksWS_1 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    IPeaksWorkspace_sptr peaksWS_2 =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    AnalysisDataService::Instance().add("ws1", peaksWS_1);
+    AnalysisDataService::Instance().add("ws2", peaksWS_2);
+    SetPeaksWorkspaces set1;
+    set1.insert(peaksWS_1);
+    SetPeaksWorkspaces set2;
+    set2.insert(peaksWS_2);
 
+    MockPeaksPresenter *pPresenter1 = new MockPeaksPresenter;
+    PeaksPresenter_sptr presenter1(pPresenter1);
 
-      // Create the composite.
-      CompositePeaksPresenter composite(&_fakeZoomableView);
-      EXPECT_CALL(*pPresenter1, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-      EXPECT_CALL(*pPresenter2, contentsDifferent(_)).WillRepeatedly(Return(true)); // Allows us to add to composite
-      composite.addPeaksPresenter(presenter1);
-      composite.addPeaksPresenter(presenter2);
+    MockPeaksPresenter *pPresenter2 = new MockPeaksPresenter;
+    PeaksPresenter_sptr presenter2(pPresenter2);
 
-      /*
+    EXPECT_CALL(*pPresenter1, registerOwningPresenter(_)).Times(AtLeast(1));
+    EXPECT_CALL(*pPresenter1, presentedWorkspaces())
+        .WillRepeatedly(Return(set1));
 
-        composite
-            |
-            |
-        -------------
-        |            |
-        p1 (ws1)     p2 (ws2)
+    EXPECT_CALL(*pPresenter2, registerOwningPresenter(_)).Times(AtLeast(1));
+    EXPECT_CALL(*pPresenter2, presentedWorkspaces())
+        .WillRepeatedly(Return(set2));
 
+    // Create the composite.
+    CompositePeaksPresenter composite(&_fakeZoomableView);
+    EXPECT_CALL(*pPresenter1, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    EXPECT_CALL(*pPresenter2, contentsDifferent(_))
+        .WillRepeatedly(Return(true)); // Allows us to add to composite
+    composite.addPeaksPresenter(presenter1);
+    composite.addPeaksPresenter(presenter2);
 
-       */
+    /*
 
-      /*
-      Same object different key.
-      Now we are going to rename ws2, and we expect the sub presenter for that to be informed.
+      composite
+          |
+          |
+      -------------
+      |            |
+      p1 (ws1)     p2 (ws2)
 
-      peaksWS_2 is already a worspace managed by one of the sub-presenters, so that subpresenter should be updated with the new name.
-      */
-      EXPECT_CALL(*pPresenter2, reInitialize(_)).Times(1);
-      AnalysisDataService::Instance().addOrReplace("ws3", peaksWS_2); // Same value (object) different key.
-      composite.notifyWorkspaceChanged("ws3", peaksWS_2);
 
+     */
 
-      // Clean up.
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter1));
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter2));
-      AnalysisDataService::Instance().remove("ws1");
-      AnalysisDataService::Instance().remove("ws2");
-      AnalysisDataService::Instance().remove("ws3");
+    /*
+    Same object different key.
+    Now we are going to rename ws2, and we expect the sub presenter for that to
+    be informed.
+
+    peaksWS_2 is already a worspace managed by one of the sub-presenters, so
+    that subpresenter should be updated with the new name.
+    */
+    EXPECT_CALL(*pPresenter2, reInitialize(_)).Times(1);
+    AnalysisDataService::Instance().addOrReplace(
+        "ws3", peaksWS_2); // Same value (object) different key.
+    composite.notifyWorkspaceChanged("ws3", peaksWS_2);
 
+    // Clean up.
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter1));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pPresenter2));
+    AnalysisDataService::Instance().remove("ws1");
+    AnalysisDataService::Instance().remove("ws2");
+    AnalysisDataService::Instance().remove("ws3");
   }
 
-  void test_edit_command()
-  {
+  void test_edit_command() {
 
     // Prepare subject objects.
-    Mantid::API::IPeaksWorkspace_sptr peaksWSA = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    Mantid::API::IPeaksWorkspace_sptr peaksWSA =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces setA;
     setA.insert(peaksWSA);
-    auto* pSubjectA = new NiceMock<MockPeaksPresenter>;
+    auto *pSubjectA = new NiceMock<MockPeaksPresenter>;
     PeaksPresenter_sptr subjectA(pSubjectA);
     EXPECT_CALL(*pSubjectA, presentedWorkspaces()).WillRepeatedly(Return(setA));
     EXPECT_CALL(*pSubjectA, contentsDifferent(_)).WillOnce(Return(true));
 
-    Mantid::API::IPeaksWorkspace_sptr peaksWSB = boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
+    Mantid::API::IPeaksWorkspace_sptr peaksWSB =
+        boost::make_shared<Mantid::DataObjects::PeaksWorkspace>();
     SetPeaksWorkspaces setB;
     setA.insert(peaksWSB);
-    auto* pSubjectB = new NiceMock<MockPeaksPresenter>;
+    auto *pSubjectB = new NiceMock<MockPeaksPresenter>;
     PeaksPresenter_sptr subjectB(pSubjectB);
     EXPECT_CALL(*pSubjectB, presentedWorkspaces()).WillRepeatedly(Return(setB));
     EXPECT_CALL(*pSubjectB, contentsDifferent(_)).WillOnce(Return(true));
@@ -976,11 +1044,13 @@ public:
     composite.addPeaksPresenter(subjectA);
     composite.addPeaksPresenter(subjectB);
 
-    /* Now we are going to say that we only want to add peaks to the first peaks workspace of the first presenter.
+    /* Now we are going to say that we only want to add peaks to the first peaks
+       workspace of the first presenter.
        so lets prep the presenters for this
      */
     EXPECT_CALL(*pSubjectA, peakEditMode(AddPeaks)).Times(AtLeast(1));
-    EXPECT_CALL(*pSubjectB, peakEditMode(MantidQt::SliceViewer::None)).Times(AtLeast(1));
+    EXPECT_CALL(*pSubjectB, peakEditMode(MantidQt::SliceViewer::None))
+        .Times(AtLeast(1));
     // Execute it.
     composite.editCommand(AddPeaks, peaksWSA);
 
@@ -988,10 +1058,6 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubjectA));
     TS_ASSERT(Mock::VerifyAndClearExpectations(pSubjectB));
   }
-
-
-
-
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/test/ConcretePeaksPresenterTest.h b/MantidQt/SliceViewer/test/ConcretePeaksPresenterTest.h
index f1cea7c523b51aa0bc499668dcc4929356006d44..7b1b3c0567e703eb515883080e4865f11fd3946d 100644
--- a/MantidQt/SliceViewer/test/ConcretePeaksPresenterTest.h
+++ b/MantidQt/SliceViewer/test/ConcretePeaksPresenterTest.h
@@ -28,18 +28,18 @@ using boost::regex;
 // Alias.
 typedef boost::shared_ptr<Mantid::API::MDGeometry> MDGeometry_sptr;
 
-class ConcretePeaksPresenterTest : public CxxTest::TestSuite
-{
+class ConcretePeaksPresenterTest : public CxxTest::TestSuite {
   /**
    * Helper method.
    * Determine whether a vector is sorted Ascending
    * @param potentiallySorted : Vector that might be sorted ascending.
    * @return False if not sortedAscending
    */
-  template<typename T>
-  bool isSortedAscending(std::vector<T> potentiallySorted)
-  {
-    return std::adjacent_find(potentiallySorted.begin(), potentiallySorted.end(), std::greater<T>()) == potentiallySorted.end();
+  template <typename T>
+  bool isSortedAscending(std::vector<T> potentiallySorted) {
+    return std::adjacent_find(potentiallySorted.begin(),
+                              potentiallySorted.end(),
+                              std::greater<T>()) == potentiallySorted.end();
   }
 
   /**
@@ -48,38 +48,40 @@ class ConcretePeaksPresenterTest : public CxxTest::TestSuite
    * @param potentiallySorted : Vector that might be sorted descending.
    * @return False if not sortedAscending
    */
-  template<typename T>
-  bool isSortedDescending(std::vector<T> potentiallySorted)
-  {
-    return std::adjacent_find(potentiallySorted.begin(), potentiallySorted.end(), std::less<T>()) == potentiallySorted.end();
+  template <typename T>
+  bool isSortedDescending(std::vector<T> potentiallySorted) {
+    return std::adjacent_find(potentiallySorted.begin(),
+                              potentiallySorted.end(),
+                              std::less<T>()) == potentiallySorted.end();
   }
 
   /// Alias.
-  typedef boost::shared_ptr<MantidQt::SliceViewer::ConcretePeaksPresenter> ConcretePeaksPresenter_sptr;
+  typedef boost::shared_ptr<MantidQt::SliceViewer::ConcretePeaksPresenter>
+      ConcretePeaksPresenter_sptr;
 
   /// Helper method to create a good 'Integrated' peaks workspace
-  Mantid::API::IPeaksWorkspace_sptr createPeaksWorkspace(const int nPeaks, const double radius=1)
-  {
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = WorkspaceCreationHelper::createPeaksWorkspace(nPeaks);
+  Mantid::API::IPeaksWorkspace_sptr
+  createPeaksWorkspace(const int nPeaks, const double radius = 1) {
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        WorkspaceCreationHelper::createPeaksWorkspace(nPeaks);
     peaksWS->mutableRun().addProperty("PeaksIntegrated", true);
     peaksWS->mutableRun().addProperty("PeakRadius", radius);
-    peaksWS->mutableRun().addProperty("BackgroundInnerRadius", radius+1);
-    peaksWS->mutableRun().addProperty("BackgroundOuterRadius", radius+2);
+    peaksWS->mutableRun().addProperty("BackgroundInnerRadius", radius + 1);
+    peaksWS->mutableRun().addProperty("BackgroundOuterRadius", radius + 2);
     return peaksWS;
   }
 
   /// Helper method to create a mock MDDimension.
-  IMDDimension_sptr createExpectedMDDimension(const std::string returnLabel)
-  {
-    auto* pDim = new NiceMock<MockIMDDimension>;
+  IMDDimension_sptr createExpectedMDDimension(const std::string returnLabel) {
+    auto *pDim = new NiceMock<MockIMDDimension>;
     IMDDimension_sptr dim(pDim);
     EXPECT_CALL(*pDim, getName()).WillRepeatedly(Return(returnLabel));
     return dim;
   }
 
-  /// Helper method to create an expected MDGeometry (we call it MDWorkspace here).
-  MDGeometry_sptr createExpectedMDWorkspace()
-  {
+  /// Helper method to create an expected MDGeometry (we call it MDWorkspace
+  /// here).
+  MDGeometry_sptr createExpectedMDWorkspace() {
     // Create a mock H Dim
     IMDDimension_sptr HDim = createExpectedMDDimension("H");
     // Create a mock K Dim
@@ -88,7 +90,7 @@ class ConcretePeaksPresenterTest : public CxxTest::TestSuite
     IMDDimension_sptr LDim = createExpectedMDDimension("L");
 
     // Create the mock MD geometry
-    MockMDGeometry* pGeometry = new MockMDGeometry;
+    MockMDGeometry *pGeometry = new MockMDGeometry;
     EXPECT_CALL(*pGeometry, getNumDims()).WillRepeatedly(Return(3));
     EXPECT_CALL(*pGeometry, getDimension(0)).WillRepeatedly(Return(HDim));
     EXPECT_CALL(*pGeometry, getDimension(1)).WillRepeatedly(Return(KDim));
@@ -98,100 +100,99 @@ class ConcretePeaksPresenterTest : public CxxTest::TestSuite
   }
 
   /** Make the tests easier to write and understand by utilising
-  a builder. This means that we can create a standard product in one line of test code, but explicilty override 
+  a builder. This means that we can create a standard product in one line of
+  test code, but explicilty override
   constructor inputs as the test requires.
   */
-  class ConcretePeaksPresenterBuilder
-  {
+  class ConcretePeaksPresenterBuilder {
   private:
     PeakOverlayViewFactory_sptr m_viewFactory;
-    IPeaksWorkspace_sptr m_peaksWS; 
-    boost::shared_ptr<MDGeometry> m_mdWS; 
+    IPeaksWorkspace_sptr m_peaksWS;
+    boost::shared_ptr<MDGeometry> m_mdWS;
     PeakTransformFactory_sptr m_transformFactory;
-    
-  public:
 
-    ConcretePeaksPresenterBuilder()
-    {
-    }
+  public:
+    ConcretePeaksPresenterBuilder() {}
 
-    ConcretePeaksPresenterBuilder(const ConcretePeaksPresenterBuilder& other)
-    {
+    ConcretePeaksPresenterBuilder(const ConcretePeaksPresenterBuilder &other) {
       m_viewFactory = other.m_viewFactory;
       m_peaksWS = other.m_peaksWS;
       m_mdWS = other.m_mdWS;
       m_transformFactory = other.m_transformFactory;
     }
 
-    void withViewFactory(PeakOverlayViewFactory_sptr val)
-    {
+    void withViewFactory(PeakOverlayViewFactory_sptr val) {
       m_viewFactory = val;
     }
-    void withPeaksWorkspace(IPeaksWorkspace_sptr val)
-    {
-      m_peaksWS = val;
-    }
-    void withMDWorkspace(boost::shared_ptr<MDGeometry> val)
-    {
-      m_mdWS = val;
-    }
-    void withTransformFactory(PeakTransformFactory_sptr val)
-    {
+    void withPeaksWorkspace(IPeaksWorkspace_sptr val) { m_peaksWS = val; }
+    void withMDWorkspace(boost::shared_ptr<MDGeometry> val) { m_mdWS = val; }
+    void withTransformFactory(PeakTransformFactory_sptr val) {
       m_transformFactory = val;
     }
 
-    ConcretePeaksPresenter_sptr create()
-    {
-      return boost::make_shared<ConcretePeaksPresenter>(m_viewFactory, m_peaksWS, m_mdWS, m_transformFactory);
+    ConcretePeaksPresenter_sptr create() {
+      return boost::make_shared<ConcretePeaksPresenter>(
+          m_viewFactory, m_peaksWS, m_mdWS, m_transformFactory);
     }
-
   };
 
   /**
-  Helper method that will produce a customisable object (builder) for making ConcretePeaks presenter.
-  1) All constructor parameters can be overriden using methods with....() on the returned builder object
-  2) The default builder has been set up to create a ubiquitious ConcretePeaksPresenter product.
+  Helper method that will produce a customisable object (builder) for making
+  ConcretePeaks presenter.
+  1) All constructor parameters can be overriden using methods with....() on the
+  returned builder object
+  2) The default builder has been set up to create a ubiquitious
+  ConcretePeaksPresenter product.
   */
-  ConcretePeaksPresenterBuilder createStandardBuild(const int expectedNumberPeaks=5, const double radius=0.0, const SpecialCoordinateSystem frame=QLab)
-  {
+  ConcretePeaksPresenterBuilder
+  createStandardBuild(const int expectedNumberPeaks = 5,
+                      const double radius = 0.0,
+                      const SpecialCoordinateSystem frame = QLab) {
     // Map enum to string.
     std::string frame_str = "Q (lab frame)";
-    if(frame == Mantid::Kernel::HKL){
-        frame_str = "HKL";
-    } else if(frame == QSample) {
-        frame_str = "Q (sample frame)";
+    if (frame == Mantid::Kernel::HKL) {
+      frame_str = "HKL";
+    } else if (frame == QSample) {
+      frame_str = "Q (sample frame)";
     }
 
     // Create a mock view object that will be returned by the mock factory.
     auto mockView = boost::make_shared<NiceMock<MockPeakOverlayView>>();
     EXPECT_CALL(*mockView.get(), getRadius()).WillRepeatedly(Return(radius));
 
-    
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
     // Create an input MODEL Peaks workspace (INTEGRATED)
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(expectedNumberPeaks);
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        createPeaksWorkspace(expectedNumberPeaks);
     // Create an input MODEL IMDWorkspace (Geom)
     MDGeometry_sptr mdWS = createExpectedMDWorkspace();
 
     // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, transformPeak(_)).WillRepeatedly(Return(V3D()));
-    EXPECT_CALL(*pMockTransform, getFriendlyName()).WillRepeatedly(Return(frame_str));
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(frame));
+    EXPECT_CALL(*pMockTransform, transformPeak(_))
+        .WillRepeatedly(Return(V3D()));
+    EXPECT_CALL(*pMockTransform, getFriendlyName())
+        .WillRepeatedly(Return(frame_str));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(frame));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillRepeatedly(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillRepeatedly(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillRepeatedly(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillRepeatedly(Return(mockTransform));
 
     // Create and return a configurable builder.
     ConcretePeaksPresenterBuilder builder;
@@ -205,8 +206,7 @@ class ConcretePeaksPresenterTest : public CxxTest::TestSuite
 public:
   void setUp() override { FrameworkManager::Instance(); }
 
-  void test_construction()
-  {
+  void test_construction() {
     // Expected number of peaks to create
     const size_t expectedNumberPeaks = 1;
 
@@ -218,40 +218,51 @@ public:
 
     // Mock View Factory Product
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-    // Mock View Factory for integrated peaks. We expect that this will never be used.
+    // Mock View Factory for integrated peaks. We expect that this will never be
+    // used.
     auto pMockViewFactory = new MockPeakOverlayFactory;
     PeakOverlayViewFactory_sptr mockViewFactory(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).Times(1).WillRepeatedly(Return(mockView)); // Create a single widget/view for all peaks
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .Times(1)
+        .WillRepeatedly(
+            Return(mockView)); // Create a single widget/view for all peaks
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillOnce(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillOnce(Return("K"));
 
     // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(Mantid::Kernel::QLab));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(Mantid::Kernel::QLab));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillOnce(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillOnce(Return(mockTransform));
 
     // Construct the presenter.
-    ConcretePeaksPresenter presenter(mockViewFactory, peaksWS, mdWS, peakTransformFactory);
-
-    TSM_ASSERT("View Factory has not been used as expected", Mock::VerifyAndClearExpectations(pMockViewFactory));
-    TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
-    TSM_ASSERT("MockTransformFactory not used as expected", Mock::VerifyAndClearExpectations(pMockTransformFactory));
-    TSM_ASSERT("MockTransform not used as expected", Mock::VerifyAndClearExpectations(pMockTransform));
+    ConcretePeaksPresenter presenter(mockViewFactory, peaksWS, mdWS,
+                                     peakTransformFactory);
+
+    TSM_ASSERT("View Factory has not been used as expected",
+               Mock::VerifyAndClearExpectations(pMockViewFactory));
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
+    TSM_ASSERT("MockTransformFactory not used as expected",
+               Mock::VerifyAndClearExpectations(pMockTransformFactory));
+    TSM_ASSERT("MockTransform not used as expected",
+               Mock::VerifyAndClearExpectations(pMockTransform));
 
     auto ownedPeaksWorkspace = presenter.presentedWorkspaces();
     TS_ASSERT_EQUALS(1, ownedPeaksWorkspace.size());
   }
 
-  void test_update()
-  {
+  void test_update() {
 
     auto pMockViewFactory = new MockPeakOverlayFactory;
     PeakOverlayViewFactory_sptr mockViewFactory(pMockViewFactory);
@@ -261,41 +272,50 @@ public:
 
     // Create a mock view object that will be returned by the mock factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    EXPECT_CALL(*pMockView, updateView()).Times(1); // Single view, for this presenter, will only update once.
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
-    
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    EXPECT_CALL(*pMockView, updateView())
+        .Times(1); // Single view, for this presenter, will only update once.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillOnce(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillOnce(Return("K"));
 
     // Create an input MODEL Peaks workspace (INTEGRATED)
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(expectedNumberPeaks);
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        createPeaksWorkspace(expectedNumberPeaks);
     // Create an input MODEL IMDWorkspace (Geom)
     MDGeometry_sptr mdWS = createExpectedMDWorkspace();
 
     // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, transformPeak(_)).WillRepeatedly(Return(V3D()));
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(Mantid::Kernel::QLab));
+    EXPECT_CALL(*pMockTransform, transformPeak(_))
+        .WillRepeatedly(Return(V3D()));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(Mantid::Kernel::QLab));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillOnce(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillOnce(Return(mockTransform));
 
-    // Construction should cause the widget factory to be used to generate peak overlay objects.
-    ConcretePeaksPresenter presenter(mockViewFactory, peaksWS, mdWS, peakTransformFactory);
+    // Construction should cause the widget factory to be used to generate peak
+    // overlay objects.
+    ConcretePeaksPresenter presenter(mockViewFactory, peaksWS, mdWS,
+                                     peakTransformFactory);
 
     // Updating should cause all of the held views to be updated too.
     presenter.update();
-    
-    TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
+
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_set_slice_point()
-  {
+  void test_set_slice_point() {
     // Create a widget factory mock
     auto mockViewFactory = new MockPeakOverlayFactory;
 
@@ -304,44 +324,56 @@ public:
 
     // Create a mock view object that will be returned by the mock factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    EXPECT_CALL(*pMockView, setSlicePoint(slicePoint, _)).Times(1); // Only one widget for this presenter
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    EXPECT_CALL(*pMockView, setSlicePoint(slicePoint, _))
+        .Times(1); // Only one widget for this presenter
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-    EXPECT_CALL(*mockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    EXPECT_CALL(*mockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*mockViewFactory, getPlotXLabel()).WillOnce(Return("H"));
     EXPECT_CALL(*mockViewFactory, getPlotYLabel()).WillOnce(Return("K"));
 
     // Create an input MODEL Peaks workspace (INTEGRATED)
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(expectedNumberPeaks);
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        createPeaksWorkspace(expectedNumberPeaks);
     // Create an input MODEL IMDWorkspace (Geom)
     MDGeometry_sptr mdWS = createExpectedMDWorkspace();
 
     // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(Mantid::Kernel::HKL));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(Mantid::Kernel::HKL));
     EXPECT_CALL(*pMockTransform, getFriendlyName()).WillOnce(Return("HKL"));
-    EXPECT_CALL(*pMockTransform, transformPeak(_)).WillRepeatedly(Return(V3D()));
+    EXPECT_CALL(*pMockTransform, transformPeak(_))
+        .WillRepeatedly(Return(V3D()));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillOnce(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillOnce(Return(mockTransform));
 
-    // Construction should cause the widget factory to be used to generate peak overlay objects.
-    ConcretePeaksPresenter presenter(PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS, peakTransformFactory);
+    // Construction should cause the widget factory to be used to generate peak
+    // overlay objects.
+    ConcretePeaksPresenter presenter(
+        PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS,
+        peakTransformFactory);
 
     // Updating should cause all of the held views to be updated too.
-    PeakBoundingBox region(Left(-1), Right(1), Top(1), Bottom(-1), SlicePoint(slicePoint));
+    PeakBoundingBox region(Left(-1), Right(1), Top(1), Bottom(-1),
+                           SlicePoint(slicePoint));
     presenter.updateWithSlicePoint(region);
 
-    TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
-    TSM_ASSERT("MockTransformFactory not used as expected", Mock::VerifyAndClearExpectations(pMockTransformFactory));
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
+    TSM_ASSERT("MockTransformFactory not used as expected",
+               Mock::VerifyAndClearExpectations(pMockTransformFactory));
   }
 
-  void test_hide_owned_views_on_death()
-  {
+  void test_hide_owned_views_on_death() {
     // Create a widget factory mock
     auto mockViewFactory = new MockPeakOverlayFactory;
 
@@ -350,39 +382,49 @@ public:
     // Create a mock view object that will be returned by the mock factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
     EXPECT_CALL(*pMockView, hideView()).Times(expectedNumberPeaks);
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-    EXPECT_CALL(*mockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    EXPECT_CALL(*mockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*mockViewFactory, getPlotXLabel()).WillOnce(Return("H"));
     EXPECT_CALL(*mockViewFactory, getPlotYLabel()).WillOnce(Return("K"));
 
     // Create an input MODEL Peaks workspace (INTEGRATED)
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(expectedNumberPeaks);
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        createPeaksWorkspace(expectedNumberPeaks);
     // Create an input MODEL IMDWorkspace (Geom)
     MDGeometry_sptr mdWS = createExpectedMDWorkspace();
 
-     // Create a mock transform object.
+    // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, transformPeak(_)).WillRepeatedly(Return(V3D()));
+    EXPECT_CALL(*pMockTransform, transformPeak(_))
+        .WillRepeatedly(Return(V3D()));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(Mantid::Kernel::QLab));
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillOnce(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(Mantid::Kernel::QLab));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillOnce(Return(mockTransform));
 
     {
-      ConcretePeaksPresenter presenter(PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS, peakTransformFactory);
-    } // Guaranteed destruction at this point. Destructor should trigger hide on all owned views.
-
-    TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
-    TSM_ASSERT("MockTransformFactory not used as expected", Mock::VerifyAndClearExpectations(pMockTransformFactory));
+      ConcretePeaksPresenter presenter(
+          PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS,
+          peakTransformFactory);
+    } // Guaranteed destruction at this point. Destructor should trigger hide on
+    // all owned views.
+
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
+    TSM_ASSERT("MockTransformFactory not used as expected",
+               Mock::VerifyAndClearExpectations(pMockTransformFactory));
   }
 
-  void test_handle_non_hkl_xy_mappings()
-  {
+  void test_handle_non_hkl_xy_mappings() {
     // Create a widget factory mock
     auto mockViewFactory = new MockPeakOverlayFactory;
 
@@ -390,53 +432,79 @@ public:
 
     // Create a mock view object that will be returned by the mock factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    EXPECT_CALL(*pMockView, hideView()).Times(expectedNumberPeaks); // This will be called automatically because the presenter won't be able to map Qx (below).
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
-
-    EXPECT_CALL(*mockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
-    EXPECT_CALL(*mockViewFactory, getPlotXLabel()).WillOnce(Return("Qx")); // Not either H, K or L
+    EXPECT_CALL(*pMockView, hideView())
+        .Times(expectedNumberPeaks); // This will be called automatically
+                                     // because the presenter won't be able to
+                                     // map Qx (below).
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+
+    EXPECT_CALL(*mockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
+    EXPECT_CALL(*mockViewFactory, getPlotXLabel())
+        .WillOnce(Return("Qx")); // Not either H, K or L
     EXPECT_CALL(*mockViewFactory, getPlotYLabel()).WillOnce(Return("K"));
     // Create an input MODEL Peaks workspace (INTEGRATED)
-    Mantid::API::IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(expectedNumberPeaks);
+    Mantid::API::IPeaksWorkspace_sptr peaksWS =
+        createPeaksWorkspace(expectedNumberPeaks);
     // Create an input MODEL IMDWorkspace (Geom)
     MDGeometry_sptr mdWS = createExpectedMDWorkspace();
 
-     // Create a mock transform object.
+    // Create a mock transform object.
     auto pMockTransform = new NiceMock<MockPeakTransform>;
     PeakTransform_sptr mockTransform(pMockTransform);
-    EXPECT_CALL(*pMockTransform, getCoordinateSystem()).WillRepeatedly(Return(Mantid::Kernel::QLab));
-    EXPECT_CALL(*pMockTransform, transformPeak(_)).WillRepeatedly(Return(V3D()));
+    EXPECT_CALL(*pMockTransform, getCoordinateSystem())
+        .WillRepeatedly(Return(Mantid::Kernel::QLab));
+    EXPECT_CALL(*pMockTransform, transformPeak(_))
+        .WillRepeatedly(Return(V3D()));
 
     // Create a mock transform factory.
     auto pMockTransformFactory = new NiceMock<MockPeakTransformFactory>;
     PeakTransformFactory_sptr peakTransformFactory(pMockTransformFactory);
-    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform()).WillOnce(Return(mockTransform));
-    EXPECT_CALL(*pMockTransformFactory, createTransform(_,_)).WillRepeatedly(Throw(PeakTransformException())); // The actual transform will throw if a mix of Qx and Qy were used.
-
-    ConcretePeaksPresenter presenter(PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS, peakTransformFactory);
-    TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
-    TSM_ASSERT("MockTransformFactory not used as expected", Mock::VerifyAndClearExpectations(pMockTransformFactory));
+    EXPECT_CALL(*pMockTransformFactory, createDefaultTransform())
+        .WillOnce(Return(mockTransform));
+    EXPECT_CALL(*pMockTransformFactory, createTransform(_, _))
+        .WillRepeatedly(Throw(PeakTransformException())); // The actual
+                                                          // transform will
+                                                          // throw if a mix of
+                                                          // Qx and Qy were
+                                                          // used.
+
+    ConcretePeaksPresenter presenter(
+        PeakOverlayViewFactory_sptr(mockViewFactory), peaksWS, mdWS,
+        peakTransformFactory);
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
+    TSM_ASSERT("MockTransformFactory not used as expected",
+               Mock::VerifyAndClearExpectations(pMockTransformFactory));
   }
 
-  void test_setForegroundColour()
-  {
+  void test_setForegroundColour() {
     const int nPeaks = 2;
     const PeakViewColor colorToChangeTo(Qt::red, Qt::red, Qt::red);
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView); 
-    EXPECT_CALL(*pMockView, changeForegroundColour(colorToChangeTo)).Times(1); // Expect that the foreground colour will be changed.
-    EXPECT_CALL(*pMockView, updateView()).Times(1); // Only one view for this presenter.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, changeForegroundColour(colorToChangeTo))
+        .Times(1); // Expect that the foreground colour will be changed.
+    EXPECT_CALL(*pMockView, updateView())
+        .Times(1); // Only one view for this presenter.
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-    auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-    presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected mock object
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected mock
+                                                       // object
     auto concretePresenter = presenterBuilder.create();
 
     concretePresenter->setForegroundColor(colorToChangeTo);
@@ -444,28 +512,36 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_setBackgroundColour()
-  {
+  void test_setBackgroundColour() {
 
     const int nPeaks = 2;
     const PeakViewColor colorToChangeTo;
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-    EXPECT_CALL(*pMockView, changeBackgroundColour(colorToChangeTo)).Times(1); // Expect that the background colour will be changed.
-    EXPECT_CALL(*pMockView, updateView()).Times(1); // Expect that each widget will be updated.
+    EXPECT_CALL(*pMockView, changeBackgroundColour(colorToChangeTo))
+        .Times(1); // Expect that the background colour will be changed.
+    EXPECT_CALL(*pMockView, updateView())
+        .Times(1); // Expect that each widget will be updated.
 
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-    auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-    presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected mock object
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected mock
+                                                       // object
     auto concretePresenter = presenterBuilder.create();
 
     concretePresenter->setBackgroundColor(colorToChangeTo);
@@ -473,21 +549,26 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_setShown()
-  {
+  void test_setShown() {
     const int expectedNumberOfPeaks = 5;
     auto concreteBuilder = createStandardBuild(expectedNumberOfPeaks);
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
-    EXPECT_CALL(*pMockView, showView()).Times(1); // Expect that the view will be forced to SHOW.
-    EXPECT_CALL(*pMockView, hideView()).Times(1); // Expect that the view will be forced to HIDE.
-    EXPECT_CALL(*pMockView, updateView()).Times(2); // Expect that each widget will be updated.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, showView())
+        .Times(1); // Expect that the view will be forced to SHOW.
+    EXPECT_CALL(*pMockView, hideView())
+        .Times(1); // Expect that the view will be forced to HIDE.
+    EXPECT_CALL(*pMockView, updateView())
+        .Times(2); // Expect that each widget will be updated.
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
@@ -500,39 +581,45 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_getBoundingBox_throws_if_index_too_low()
-  {
+  void test_getBoundingBox_throws_if_index_too_low() {
     auto concreteBuilder = createStandardBuild();
     ConcretePeaksPresenter_sptr presenter = concreteBuilder.create();
 
     const int badIndex = -1;
-    TSM_ASSERT_THROWS("Index is < 0, should throw", presenter->getBoundingBox(badIndex), std::out_of_range&);
+    TSM_ASSERT_THROWS("Index is < 0, should throw",
+                      presenter->getBoundingBox(badIndex), std::out_of_range &);
   }
 
-  void test_getBoundingBox_throws_if_index_too_high()
-  {
+  void test_getBoundingBox_throws_if_index_too_high() {
     auto concreteBuilder = createStandardBuild();
     ConcretePeaksPresenter_sptr presenter = concreteBuilder.create();
 
-    const size_t numberOfPeaks = (*presenter->presentedWorkspaces().begin())->rowCount();
+    const size_t numberOfPeaks =
+        (*presenter->presentedWorkspaces().begin())->rowCount();
     const int badIndex = static_cast<int>(numberOfPeaks) + 1;
-    TSM_ASSERT_THROWS("Index is < 0, should throw", presenter->getBoundingBox(badIndex), std::out_of_range&);
+    TSM_ASSERT_THROWS("Index is < 0, should throw",
+                      presenter->getBoundingBox(badIndex), std::out_of_range &);
   }
 
-  void test_getBoundingBox()
-  {
+  void test_getBoundingBox() {
     const int expectedNumberOfPeaks = 1;
     auto concreteBuilder = createStandardBuild(expectedNumberOfPeaks);
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
-    EXPECT_CALL(*pMockView, getBoundingBox(_)).Times(1).WillOnce(Return(PeakBoundingBox())); // Expect that the bounding box will be requested.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, getBoundingBox(_))
+        .Times(1)
+        .WillOnce(Return(PeakBoundingBox())); // Expect that the bounding box
+                                              // will be requested.
 
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
@@ -543,306 +630,346 @@ public:
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void doTestSorting(const bool sortAscending)
-  {
+  void doTestSorting(const bool sortAscending) {
     const int expectedNumberOfPeaks = 1;
     auto concreteBuilder = createStandardBuild(expectedNumberOfPeaks);
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
-    EXPECT_CALL(*pMockView, setSlicePoint(_,_)).Times(1); // Expect that the slice point will be re-set upon sorting.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, setSlicePoint(_, _))
+        .Times(1); // Expect that the slice point will be re-set upon sorting.
 
     // Create a widget factory mock
     auto pMockViewFactory = new NiceMock<MockPeakOverlayFactory>;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
     concreteBuilder.withViewFactory(mockViewFactory);
 
     auto presenter = concreteBuilder.create();
-    presenter->sortPeaksWorkspace("h", sortAscending); // Sort the presenter by the h column.
+    presenter->sortPeaksWorkspace(
+        "h", sortAscending); // Sort the presenter by the h column.
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
 
     // Check that the workspace is sorted.
-    IPeaksWorkspace_const_sptr sortedPeaksWS = *presenter->presentedWorkspaces().begin();
+    IPeaksWorkspace_const_sptr sortedPeaksWS =
+        *presenter->presentedWorkspaces().begin();
     std::vector<double> potentiallySortedHValues;
-    for (int i = 0; i < sortedPeaksWS->getNumberPeaks(); ++i)
-    {
-      const IPeak& peak = sortedPeaksWS->getPeak(i);
+    for (int i = 0; i < sortedPeaksWS->getNumberPeaks(); ++i) {
+      const IPeak &peak = sortedPeaksWS->getPeak(i);
       potentiallySortedHValues.push_back(peak.getH());
     }
 
-    if (sortAscending == true)
-    {
-      TSM_ASSERT("The internal peaks workspace should have been internally sorted ASCENDING by H values",
-          this->isSortedAscending(potentiallySortedHValues));
+    if (sortAscending == true) {
+      TSM_ASSERT("The internal peaks workspace should have been internally "
+                 "sorted ASCENDING by H values",
+                 this->isSortedAscending(potentiallySortedHValues));
+    } else {
+      TSM_ASSERT("The internal peaks workspace shuld have been internally "
+                 "sorted DESCENDING by H values",
+                 this->isSortedDescending(potentiallySortedHValues));
     }
-    else
-    {
-      TSM_ASSERT("The internal peaks workspace shuld have been internally sorted DESCENDING by H values",
-          this->isSortedDescending(potentiallySortedHValues));
-    }
-
   }
 
-  void test_sortPeaksWorkspace_by_H_Ascending()
-  {
+  void test_sortPeaksWorkspace_by_H_Ascending() {
     bool sortAscending = true;
     doTestSorting(sortAscending);
   }
 
-  void test_sortPeaksWorkspace_by_H_Descending()
-  {
+  void test_sortPeaksWorkspace_by_H_Descending() {
     bool sortAscending = false;
     doTestSorting(sortAscending);
   }
 
-  void test_coordinateToString()
-  {
+  void test_coordinateToString() {
     TS_ASSERT_EQUALS("HKL", coordinateToString(Mantid::Kernel::HKL));
     TS_ASSERT_EQUALS("QLab", coordinateToString(Mantid::Kernel::QLab));
     TS_ASSERT_EQUALS("QSample", coordinateToString(Mantid::Kernel::QSample));
   }
 
-  void test_getPeaksSizeOnProjection()
-  {
+  void test_getPeaksSizeOnProjection() {
     const int nPeaks = 1;
     const double occupancyInView = 0.07;
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView); 
-    EXPECT_CALL(*pMockView, positionOnly()).WillOnce(Return(true)); // A peak repesentation without an absolute size.
-    EXPECT_CALL(*pMockView, getOccupancyInView()).WillOnce(Return(occupancyInView)); // The occupancy that the VIEW returns.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, positionOnly())
+        .WillOnce(
+            Return(true)); // A peak repesentation without an absolute size.
+    EXPECT_CALL(*pMockView, getOccupancyInView())
+        .WillOnce(
+            Return(occupancyInView)); // The occupancy that the VIEW returns.
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-    auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-    presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected mock object
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected mock
+                                                       // object
     auto concretePresenter = presenterBuilder.create();
 
-    TS_ASSERT_EQUALS(occupancyInView, concretePresenter->getPeakSizeOnProjection()); 
+    TS_ASSERT_EQUALS(occupancyInView,
+                     concretePresenter->getPeakSizeOnProjection());
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_getPeaksSizeIntoProjection()
-  {
+  void test_getPeaksSizeIntoProjection() {
     const int nPeaks = 1;
     const double occupancyIntoView = 0.05;
 
-    // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
     auto pMockView = new NiceMock<MockPeakOverlayView>;
-    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView); 
-    EXPECT_CALL(*pMockView, positionOnly()).WillOnce(Return(true)); // A peak repesentation without an absolute size.
-    EXPECT_CALL(*pMockView, getOccupancyIntoView()).WillOnce(Return(occupancyIntoView)); // The occupancy that the VIEW returns.
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
+    EXPECT_CALL(*pMockView, positionOnly())
+        .WillOnce(
+            Return(true)); // A peak repesentation without an absolute size.
+    EXPECT_CALL(*pMockView, getOccupancyIntoView())
+        .WillOnce(
+            Return(occupancyIntoView)); // The occupancy that the VIEW returns.
     // Create a widget factory mock
     auto pMockViewFactory = new MockPeakOverlayFactory;
-    PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-    EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
     EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
     EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-    auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-    presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected mock object
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected mock
+                                                       // object
     auto concretePresenter = presenterBuilder.create();
 
-    TS_ASSERT_EQUALS(occupancyIntoView, concretePresenter->getPeakSizeIntoProjection()); 
+    TS_ASSERT_EQUALS(occupancyIntoView,
+                     concretePresenter->getPeakSizeIntoProjection());
 
     TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_reInitalize()
-  {
-      const int nPeaks = 3;
+  void test_reInitalize() {
+    const int nPeaks = 3;
 
-      // Create a mock view object/product that will be returned by the mock factory.
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
 
-      auto pMockView = new NiceMock<MockPeakOverlayView>;
-      auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    auto pMockView = new NiceMock<MockPeakOverlayView>;
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-      // Create a widget factory mock
-      auto pMockViewFactory = new MockPeakOverlayFactory;
-      PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-      EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillOnce(Return(mockView));
-      EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
-      EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
+    // Create a widget factory mock
+    auto pMockViewFactory = new MockPeakOverlayFactory;
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _)).WillOnce(Return(mockView));
+    EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
+    EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-      auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-      presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected ViewFactory mock object
-      auto concretePresenter = presenterBuilder.create();
-      presenterBuilder.withViewFactory(mockViewFactory);
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected
+                                                       // ViewFactory mock
+                                                       // object
+    auto concretePresenter = presenterBuilder.create();
+    presenterBuilder.withViewFactory(mockViewFactory);
 
-      // We now create a new peaks workspace
-      const double radius = 1;
-      auto newPeaksWorkspace = createPeaksWorkspace(nPeaks+1, radius);
+    // We now create a new peaks workspace
+    const double radius = 1;
+    auto newPeaksWorkspace = createPeaksWorkspace(nPeaks + 1, radius);
 
-      // We expect the peaks workspace object to be swapped.
-      EXPECT_CALL(*pMockViewFactory, swapPeaksWorkspace(_)).Times(1);
-      // We expect that createViews will be called again, because we'll have to create new representations for each peak
-      EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillOnce(Return(mockView));
+    // We expect the peaks workspace object to be swapped.
+    EXPECT_CALL(*pMockViewFactory, swapPeaksWorkspace(_)).Times(1);
+    // We expect that createViews will be called again, because we'll have to
+    // create new representations for each peak
+    EXPECT_CALL(*pMockViewFactory, createView(_, _)).WillOnce(Return(mockView));
 
-      // We force this concrete presenter to take a new peaks workspace to represent
-      concretePresenter->reInitialize(newPeaksWorkspace);
+    // We force this concrete presenter to take a new peaks workspace to
+    // represent
+    concretePresenter->reInitialize(newPeaksWorkspace);
 
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pMockViewFactory));
-      TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pMockViewFactory));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pMockView));
   }
 
-  void test_contentsDifferent_different()
-  {
-      ConcretePeaksPresenter_sptr a = createStandardBuild(2).create();
-      ConcretePeaksPresenter_sptr b = createStandardBuild(2).create();
+  void test_contentsDifferent_different() {
+    ConcretePeaksPresenter_sptr a = createStandardBuild(2).create();
+    ConcretePeaksPresenter_sptr b = createStandardBuild(2).create();
 
-      TSM_ASSERT("Each presenter has it's own unique peaks workspace", a->contentsDifferent(b.get()));
-      TSM_ASSERT("Each presenter has it's own unique peaks workspace", b->contentsDifferent(a.get()));
+    TSM_ASSERT("Each presenter has it's own unique peaks workspace",
+               a->contentsDifferent(b.get()));
+    TSM_ASSERT("Each presenter has it's own unique peaks workspace",
+               b->contentsDifferent(a.get()));
   }
 
-  void test_contentsDifferent_same()
-  {
-      ConcretePeaksPresenterBuilder builder = createStandardBuild();
-      // Set a common peaks workspace.
-      builder.withPeaksWorkspace(WorkspaceCreationHelper::createPeaksWorkspace());
+  void test_contentsDifferent_same() {
+    ConcretePeaksPresenterBuilder builder = createStandardBuild();
+    // Set a common peaks workspace.
+    builder.withPeaksWorkspace(WorkspaceCreationHelper::createPeaksWorkspace());
 
-      ConcretePeaksPresenter_sptr a = builder.create();
-      ConcretePeaksPresenter_sptr b = builder.create();
+    ConcretePeaksPresenter_sptr a = builder.create();
+    ConcretePeaksPresenter_sptr b = builder.create();
 
-      TSM_ASSERT("Each presenter uses the same peaks workspace", !a->contentsDifferent(b.get()));
-      TSM_ASSERT("Each presenter uses the same peaks peaks workspace", !b->contentsDifferent(a.get()));
+    TSM_ASSERT("Each presenter uses the same peaks workspace",
+               !a->contentsDifferent(b.get()));
+    TSM_ASSERT("Each presenter uses the same peaks peaks workspace",
+               !b->contentsDifferent(a.get()));
   }
 
-  void test_contentsDifferent_mixed()
-  {
-      auto a = WorkspaceCreationHelper::createPeaksWorkspace();
-      auto b = WorkspaceCreationHelper::createPeaksWorkspace();
-      auto c = WorkspaceCreationHelper::createPeaksWorkspace();
-
-      // We are creating another comparison peaks presenter, which will deliver a set of peaks workspaces.
-      auto other = boost::make_shared<MockPeaksPresenter>();
-      SetPeaksWorkspaces result;
-      result.insert(a);
-      result.insert(b);
-      result.insert(c);
-      EXPECT_CALL(*other, presentedWorkspaces() ).WillRepeatedly(Return(result));
-
-      ConcretePeaksPresenterBuilder builder = createStandardBuild();
-      // Set a peaks workspace.
-      builder.withPeaksWorkspace(c);
-      ConcretePeaksPresenter_sptr presenter = builder.create();
-
-      TSM_ASSERT("Presenter is managing one of these workspaces already", !presenter->contentsDifferent(other.get()));
-
+  void test_contentsDifferent_mixed() {
+    auto a = WorkspaceCreationHelper::createPeaksWorkspace();
+    auto b = WorkspaceCreationHelper::createPeaksWorkspace();
+    auto c = WorkspaceCreationHelper::createPeaksWorkspace();
+
+    // We are creating another comparison peaks presenter, which will deliver a
+    // set of peaks workspaces.
+    auto other = boost::make_shared<MockPeaksPresenter>();
+    SetPeaksWorkspaces result;
+    result.insert(a);
+    result.insert(b);
+    result.insert(c);
+    EXPECT_CALL(*other, presentedWorkspaces()).WillRepeatedly(Return(result));
+
+    ConcretePeaksPresenterBuilder builder = createStandardBuild();
+    // Set a peaks workspace.
+    builder.withPeaksWorkspace(c);
+    ConcretePeaksPresenter_sptr presenter = builder.create();
+
+    TSM_ASSERT("Presenter is managing one of these workspaces already",
+               !presenter->contentsDifferent(other.get()));
   }
 
-  void test_test_apply_edit_mode_to_views(){
-      const int nPeaks = 1;
+  void test_test_apply_edit_mode_to_views() {
+    const int nPeaks = 1;
 
-      // Create a mock view object/product that will be returned by the mock factory.
-      auto pMockView = new NiceMock<MockPeakOverlayView>;
-      auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView> >(pMockView);
+    // Create a mock view object/product that will be returned by the mock
+    // factory.
+    auto pMockView = new NiceMock<MockPeakOverlayView>;
+    auto mockView = boost::shared_ptr<NiceMock<MockPeakOverlayView>>(pMockView);
 
-      // Create a widget factory mock
-      auto pMockViewFactory = new MockPeakOverlayFactory;
-      PeakOverlayViewFactory_sptr mockViewFactory = PeakOverlayViewFactory_sptr(pMockViewFactory);
-      EXPECT_CALL(*pMockViewFactory, createView(_,_)).WillRepeatedly(Return(mockView));
-      EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
-      EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
+    // Create a widget factory mock
+    auto pMockViewFactory = new MockPeakOverlayFactory;
+    PeakOverlayViewFactory_sptr mockViewFactory =
+        PeakOverlayViewFactory_sptr(pMockViewFactory);
+    EXPECT_CALL(*pMockViewFactory, createView(_, _))
+        .WillRepeatedly(Return(mockView));
+    EXPECT_CALL(*pMockViewFactory, getPlotXLabel()).WillRepeatedly(Return("H"));
+    EXPECT_CALL(*pMockViewFactory, getPlotYLabel()).WillRepeatedly(Return("K"));
 
-      auto presenterBuilder = createStandardBuild(nPeaks); // Creates a default Concrete presenter product.
-      presenterBuilder.withViewFactory(mockViewFactory); // Change the view factories to deliver the expected mock object
-      auto concretePresenter = presenterBuilder.create();
+    auto presenterBuilder = createStandardBuild(
+        nPeaks); // Creates a default Concrete presenter product.
+    presenterBuilder.withViewFactory(mockViewFactory); // Change the view
+                                                       // factories to deliver
+                                                       // the expected mock
+                                                       // object
+    auto concretePresenter = presenterBuilder.create();
 
-      // Deletion mode tests
-      EXPECT_CALL(*pMockView, peakDeletionMode()).Times(1);
-      concretePresenter->peakEditMode(DeletePeaks);
+    // Deletion mode tests
+    EXPECT_CALL(*pMockView, peakDeletionMode()).Times(1);
+    concretePresenter->peakEditMode(DeletePeaks);
 
-      // Addition mode tests
-      EXPECT_CALL(*pMockView, peakAdditionMode()).Times(1);
-      concretePresenter->peakEditMode(AddPeaks);
+    // Addition mode tests
+    EXPECT_CALL(*pMockView, peakAdditionMode()).Times(1);
+    concretePresenter->peakEditMode(AddPeaks);
 
-      // Neutral mode tests
-      EXPECT_CALL(*pMockView, peakDisplayMode()).Times(1);
-      concretePresenter->peakEditMode(MantidQt::SliceViewer::None);
+    // Neutral mode tests
+    EXPECT_CALL(*pMockView, peakDisplayMode()).Times(1);
+    concretePresenter->peakEditMode(MantidQt::SliceViewer::None);
 
-      TSM_ASSERT("MockView not used as expected.", Mock::VerifyAndClearExpectations(pMockView));
+    TSM_ASSERT("MockView not used as expected.",
+               Mock::VerifyAndClearExpectations(pMockView));
   }
 
+  // void test_deletePeaksIn(){TSM_ASSERT("Missing test", false);}
 
-
-  //void test_deletePeaksIn(){TSM_ASSERT("Missing test", false);}
-
-  void makeSphericallyIntegrated(IPeak& peak, const double radius)
-  {
-      using namespace Mantid::DataObjects;
-      Peak* pPeak = dynamic_cast<Peak*>(&peak);
-      pPeak->setPeakShape(boost::make_shared<PeakShapeSpherical>(radius, Mantid::Kernel::HKL));
+  void makeSphericallyIntegrated(IPeak &peak, const double radius) {
+    using namespace Mantid::DataObjects;
+    Peak *pPeak = dynamic_cast<Peak *>(&peak);
+    pPeak->setPeakShape(
+        boost::make_shared<PeakShapeSpherical>(radius, Mantid::Kernel::HKL));
   }
 
   void test_delete_in() {
-      using namespace Mantid::DataObjects;
+    using namespace Mantid::DataObjects;
 
-      const int nPeaks = 3;
-      const double radius = 0.1;
-      auto concreteBuilder = createStandardBuild(nPeaks, radius, Mantid::Kernel::HKL);
+    const int nPeaks = 3;
+    const double radius = 0.1;
+    auto concreteBuilder =
+        createStandardBuild(nPeaks, radius, Mantid::Kernel::HKL);
 
-      // Custom peaks workspace
-      IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(nPeaks, radius);
-      // Customize a peak
-      IPeak& peakToDelete1 = peaksWS->getPeak(0);
-      peakToDelete1.setHKL(0,0,0);
-      makeSphericallyIntegrated(peakToDelete1, radius);
-      // Customize another peak
-      IPeak& peakToDelete2 = peaksWS->getPeak(0);
-      peakToDelete2.setHKL(1,0,0);
-      makeSphericallyIntegrated(peakToDelete2, radius);
-      // Customize another peak
-      peaksWS->getPeak(2).setHKL(10, 10, 10); // Not integrated, will be well out of range anyway.
+    // Custom peaks workspace
+    IPeaksWorkspace_sptr peaksWS = createPeaksWorkspace(nPeaks, radius);
+    // Customize a peak
+    IPeak &peakToDelete1 = peaksWS->getPeak(0);
+    peakToDelete1.setHKL(0, 0, 0);
+    makeSphericallyIntegrated(peakToDelete1, radius);
+    // Customize another peak
+    IPeak &peakToDelete2 = peaksWS->getPeak(0);
+    peakToDelete2.setHKL(1, 0, 0);
+    makeSphericallyIntegrated(peakToDelete2, radius);
+    // Customize another peak
+    peaksWS->getPeak(2).setHKL(
+        10, 10, 10); // Not integrated, will be well out of range anyway.
 
-      /******************
+    /******************
 
-                              x (10,10,10)
+                            x (10,10,10)
 
-      -----------------------   cursor region = 0 to 1 and -0.5 to 0.5
-      |  x(0,0,0) x(1,0,0)  |
-      -----------------------
+    -----------------------   cursor region = 0 to 1 and -0.5 to 0.5
+    |  x(0,0,0) x(1,0,0)  |
+    -----------------------
 
-      ******************/
+    ******************/
 
+    concreteBuilder.withPeaksWorkspace(peaksWS); // Customise builder
 
-      concreteBuilder.withPeaksWorkspace(peaksWS); // Customise builder
-
-      ConcretePeaksPresenter_sptr presenter = concreteBuilder.create();
-
-      /*
-       * Create a Cursor region.
-      */
-      Top top(0.5);
-      Bottom bottom(-0.5);
-      Left left(0);
-      Right right(1);
-      SlicePoint slicePoint(0.0);
-      PeakBoundingBox cursorRegion(left, right, top, bottom, slicePoint); // psudo viewing frustrum.
+    ConcretePeaksPresenter_sptr presenter = concreteBuilder.create();
 
-      TSM_ASSERT_EQUALS("No peaks should have been removed yet", 3, peaksWS->getNumberPeaks());
-      TSM_ASSERT("Point sits on peak radius. We should delete peak.", presenter->deletePeaksIn(cursorRegion));
-      TSM_ASSERT_EQUALS("One peaks should remain", 1, peaksWS->getNumberPeaks());
+    /*
+     * Create a Cursor region.
+    */
+    Top top(0.5);
+    Bottom bottom(-0.5);
+    Left left(0);
+    Right right(1);
+    SlicePoint slicePoint(0.0);
+    PeakBoundingBox cursorRegion(left, right, top, bottom,
+                                 slicePoint); // psudo viewing frustrum.
+
+    TSM_ASSERT_EQUALS("No peaks should have been removed yet", 3,
+                      peaksWS->getNumberPeaks());
+    TSM_ASSERT("Point sits on peak radius. We should delete peak.",
+               presenter->deletePeaksIn(cursorRegion));
+    TSM_ASSERT_EQUALS("One peaks should remain", 1, peaksWS->getNumberPeaks());
   }
 
-  void test_haspeakaddmode(){
-      auto builder = createStandardBuild(5/*N Peaks*/, 1.0/*radius*/, QLab /*CHOSEN FRAME*/);
-      ConcretePeaksPresenter_sptr concretePeaksPresenter = builder.create();
-      TSM_ASSERT("No peak add mode. As is not in the HKL frame", !concretePeaksPresenter->hasPeakAddMode());
+  void test_haspeakaddmode() {
+    auto builder = createStandardBuild(5 /*N Peaks*/, 1.0 /*radius*/,
+                                       QLab /*CHOSEN FRAME*/);
+    ConcretePeaksPresenter_sptr concretePeaksPresenter = builder.create();
+    TSM_ASSERT("No peak add mode. As is not in the HKL frame",
+               !concretePeaksPresenter->hasPeakAddMode());
   }
-
-
 };
 
-
 #endif
diff --git a/MantidQt/SliceViewer/test/EllipsoidPlaneSliceCalculatorTest.h b/MantidQt/SliceViewer/test/EllipsoidPlaneSliceCalculatorTest.h
index 46deb151730f7a01332a63c877c223bddefb728f..ef1a34193fa1362938965713f5c7a7ecc2d234fa 100644
--- a/MantidQt/SliceViewer/test/EllipsoidPlaneSliceCalculatorTest.h
+++ b/MantidQt/SliceViewer/test/EllipsoidPlaneSliceCalculatorTest.h
@@ -9,633 +9,619 @@
 #include <algorithm>
 #include <math.h>
 
-namespace
-{
-bool radiusIsInListOfRadii(double radius, const std::vector<double> &radii)
-{
-    auto comparison =
-        [radius](double toCheck) { return Mantid::SliceViewer::almost_equal(radius, toCheck); };
-    return std::any_of(radii.cbegin(), radii.cend(), comparison);
+namespace {
+bool radiusIsInListOfRadii(double radius, const std::vector<double> &radii) {
+  auto comparison = [radius](double toCheck) {
+    return Mantid::SliceViewer::almost_equal(radius, toCheck);
+  };
+  return std::any_of(radii.cbegin(), radii.cend(), comparison);
 }
 
-// Check if the two angles are the same, note that angles which are shifted by 180 degrees
-// are the same for an ellipsoid, ie one is free to have the major axis point in the
+// Check if the two angles are the same, note that angles which are shifted by
+// 180 degrees
+// are the same for an ellipsoid, ie one is free to have the major axis point in
+// the
 // + or - direction
 bool isAngleEitherValueOr180DegreesRoated(double expectedAngle,
-                                          double actualAngle)
-{
-    return Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle)
-           || Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle + M_PI)
-           || Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle - M_PI);
+                                          double actualAngle) {
+  return Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle) ||
+         Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle + M_PI) ||
+         Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle - M_PI);
 }
-
 }
 
-class EllipsoidPlaneSliceCalculatorTest : public CxxTest::TestSuite
-{
+class EllipsoidPlaneSliceCalculatorTest : public CxxTest::TestSuite {
 public:
-    //-----------------------------------------------------------------
-    // Test for the creation of the Ellipsoid Matrix
-    //-----------------------------------------------------------------
-    void
-    test_that_correct_ellipsoid_matrix_is_generated_when_already_in_eigenbasis()
-    {
-        // Arrange
-        std::vector<double> radii = {3.0, 2.0, 1.0};
-        Mantid::Kernel::V3D dir1(1.0, 0.0, 0.0);
-        Mantid::Kernel::V3D dir2(0.0, 1.0, 0.0);
-        Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-        std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
-
-        // Act
-        auto matrix = Mantid::SliceViewer::createEllipsoidMatrixInXYZFrame(
-            directions, radii);
-
-        // Assert
-
-        std::vector<std::pair<int, int>> indices
-            = {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}};
-
-        for (const auto &index : indices) {
-            TSM_ASSERT("Non-diagonal element should be zero",
-                       matrix[index.first][index.second] == 0.0);
-        }
-        TSM_ASSERT_EQUALS("Should be the first 1/radius^2", matrix[0][0],
-                          1 / std::pow(radii[0], 2));
-        TSM_ASSERT_EQUALS("Should be the second 1/radius^2", matrix[1][1],
-                          1 / std::pow(radii[1], 2));
-        TSM_ASSERT_EQUALS("Should be the third 1/radius^2", matrix[2][2],
-                          1 / std::pow(radii[2], 2));
-    }
-
-    void
-    test_that_correct_ellipsoid_matrix_is_generated_when_eigenbasis_rotated_45_degrees_around_z()
-    {
-
-        // Arrange
-        std::vector<double> radii = {3.0, 2.0, 1.5};
-        std::vector<double> inverseRadiiSquared
-            = {1 / std::pow(radii[0], 2), 1 / std::pow(radii[1], 2),
-               1 / std::pow(radii[2], 2)};
-        Mantid::Kernel::V3D dir1(M_SQRT1_2, -1 * M_SQRT1_2, 0.0);
-        Mantid::Kernel::V3D dir2(M_SQRT1_2, M_SQRT1_2, 0.0);
-        Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-        std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
-
-        // Act
-        auto matrix = Mantid::SliceViewer::createEllipsoidMatrixInXYZFrame(
-            directions, radii);
-
-        // Assert
-        Mantid::Kernel::DblMatrix eigenValues; // on the diagonal
-        Mantid::Kernel::DblMatrix eigenVectors;
-        matrix.Diagonalise(eigenVectors, eigenValues);
-
-        double delta = 1e-5;
-        for (int index = 0; index < 3; ++index) {
-            auto invRad = inverseRadiiSquared[index];
-            TSM_ASSERT_DELTA(
-                "Eigenvalue should correspond to inverse radius squared",
-                invRad, eigenValues[index][index], delta);
-        }
-    }
-
-    //-----------------------------------------------------------------
-    // Tests for handling spheres
-    //-----------------------------------------------------------------
-    void
-    test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_origin_and_origin_at_0()
-    {
-
-        // Arrange
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-        double zCutPlane = 0; // We cut at z = 0
-        Mantid::Kernel::V3D direction1(1, 0,
-                                       0); // The directions are simply x, y, z
-        Mantid::Kernel::V3D direction2(0, 1, 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii
-            = {1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
-        Mantid::Kernel::V3D origin(0.0, 0.0, 0.0); // The origin is at 0,0,0
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, radii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, radii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 0",
-                         info.origin.X(), 0.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 0",
-                         info.origin.Y(), 0.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 0",
-                         info.origin.Z(), 0.0, delta);
-    }
-
-    void
-    test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_and_origin_at__3_2_1()
-    {
-        // Arrange
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-        double zCutPlane = 1; // We cut at z = 1
-        Mantid::Kernel::V3D direction1(1, 0,
-                                       0); // The directions are simply x, y, z
-        Mantid::Kernel::V3D direction2(0, 1, 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii
-            = {1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
-        Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, radii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, radii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                         info.origin.X(), 3.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                         info.origin.Y(), 2.0, delta);
-
-        TSM_ASSERT_DELTA("The z part of the origin should be at 1",
-                         info.origin.Z(), 1.0, delta);
-    }
-
-    void
-    test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_5_and_origin_at__3_2_1()
-    {
-        // Arrange
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-        double zCutPlane = 1.5; // We cut at z = 1.5
-        Mantid::Kernel::V3D direction1(1, 0,
-                                       0); // The directions are simply x, y, z
-        Mantid::Kernel::V3D direction2(0, 1, 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii
-            = {1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
-        Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-
-        // Radius is 1 and we are looking at 0.5 from the origin
-        // ie x^2 + y^2 + 0.5^2 == r^2 ==> reffective^2 = 1^2 -0.5^2 = 0.75
-        std::vector<double> expcetedRadii = {std::sqrt(0.75)};
-        TSM_ASSERT("The first radius should be Sqrt[0.75]",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, expcetedRadii));
-        TSM_ASSERT("The second radius should be Sqrt[0.75]",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, expcetedRadii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                         info.origin.X(), 3.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                         info.origin.Y(), 2.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 2",
-                         info.origin.Z(), 1.5, delta);
-    }
-
-    void
-    test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_5_and_origin_at__3_2_1_with_tilted_axes()
-    {
-        // Arrange
-        const double angleIn = 30 / 180 * M_PI;
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-        double zCutPlane = 1.5; // We cut at z = 1.5
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
-                                       0); // The directions are simply x, y, z
-        Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii
-            = {1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
-        Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-
-        // The rotation was 30deg, but we have a sphere so angle should be 0
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-
-        // Radius is 1 and we are looking at 0.5 from the origin
-        // ie x^2 + y^2 + 0.5^2 == r^2 ==> reffective^2 = 1^2 -0.5^2 = 0.75
-        std::vector<double> expcetedRadii = {std::sqrt(0.75)};
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, expcetedRadii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, expcetedRadii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                         info.origin.X(), 3.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                         info.origin.Y(), 2.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 2",
-                         info.origin.Z(), 1.5, delta);
-    }
-
-    //-----------------------------------------------------------------
-    // Tests for handling ellipsoids
-    //-----------------------------------------------------------------
-    void
-    test_correct_for_ellipsoid_with_cut_through_0_and_origin_at_0_with_axis_aligned()
-    {
-        // Arrange
-        const double angleIn = 0.0;
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-        double zCutPlane = 0;
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), -std::sin(angleIn),
-                                       0);
-        Mantid::Kernel::V3D direction2(std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii = {4.0, 3.0, 2.0};
-        Mantid::Kernel::V3D origin(0.0, 0.0, 0.0);
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, radii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, radii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 0",
-                         info.origin.X(), 0.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 0",
-                         info.origin.Y(), 0.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 0",
-                         info.origin.Z(), 0.0, delta);
-    }
-
-    void
-    test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_aligned()
-    {
-        // Arrange
-        const double angleIn = 0.0;
-        double zCutPlane = 1.5;
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), -std::sin(angleIn),
-                                       0);
-        Mantid::Kernel::V3D direction2(std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii = {4.0, 3.0, 2.0};
-        Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
-
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-
-        TSM_ASSERT("The angle should be 0", isAngleEitherValueOr180DegreesRoated(0.0,info.angle));
-
-        // From (x/4)^2 + (y/3)^2 + (0.5/2)^2 = 1 we get
-        // r1 = 4* Sqrt[1-(0.5/2)^2]
-        // r2 = 3* Sqrt[1-(0.5/2)^2]
-        std::vector<double> expectedRadii
-            = {4.0 * std::sqrt(1 - std::pow(0.25, 2)),
-               3.0 * std::sqrt(1 - std::pow(0.25, 2))};
-
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                         info.origin.X(), 3.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                         info.origin.Y(), 2.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 1.5",
-                         info.origin.Z(), 1.5, delta);
-    }
-
-    void
-    test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_less_than_45_degrees()
-    {
-      double const angle = 32; // in degree
-      double const expectedAngle = 32; // in degree
-      do_test_ellipsoid_with_tilt(angle, expectedAngle);
-    }
-
-    void
-    test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_45_degrees()
-    {
-      double const angle = 45; // in degree
-      double const expectedAngle = 45; // in degree
-      do_test_ellipsoid_with_tilt(angle, expectedAngle);
-    }
-
-    void
-    test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_more_than_45_degrees()
-    {
-      double const angle = 48; // in degree
-      double const expectedAngle = 48; // in degree
-      do_test_ellipsoid_with_tilt(angle, expectedAngle);
-    }
-
-    void
-    test_finds_ellipse_for_ellipsoid_with_major_axis_along_z_and_cut_through_5_and_origin_at_3_2_1_with_axis_tilt()
-    {
-        // Arrange
-        const double angleIn = 34.0 * 2 * M_PI / 360;
-        double zCutPlane = 5.0;
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
-                                       0);
-        Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        std::vector<double> radii = {4.0, 3.0, 7.0};
-        Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
-
-        Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-
-        // Act
-        auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                                 zCutPlane);
-
-        // Assert
-        const double delta = 1e-5;
-
-        // The angle we get from info is the angle
-        TSM_ASSERT("The angle should be 34", isAngleEitherValueOr180DegreesRoated(angleIn,info.angle));
-
-        // From (x/4)^2 + (y/3)^2 + ((5-1)/7)^2 = 1 we get
-        // r1 = 4* Sqrt[1-(4/7)^2]
-        // r2 = 3* Sqrt[1-(4/7)^2]
-        std::vector<double> expectedRadii
-            = {4.0 * std::sqrt(1 - std::pow(4.0/7.0, 2)),
-               3.0 * std::sqrt(1 - std::pow(4.0/7.0, 2))};
-
-        TSM_ASSERT("The first radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
-        TSM_ASSERT("The second radius should be 1",
-                   radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
-
-        TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                         info.origin.X(), 3.0, delta);
-        TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                         info.origin.Y(), 2.0, delta);
-        TSM_ASSERT_DELTA("The z part of the origin should be at 5",
-                         info.origin.Z(), 5, delta);
-    }
-
-
-    //-----------------------------------------------------------------
-    // Tests for bounding box of an ellipse
-    //-----------------------------------------------------------------
-    void test_that_bounding_box_of_axis_aligned_ellipsoid_is_found()
-    {
-        // Arrange
-        const double angleIn = 0.0;
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
-                                       0);
-        Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        Mantid::Kernel::V3D origin(1.0, 2.0, -1.0);
-        std::vector<double> radii = {2.0, 1.5,0.5};
-
-        // Act
-        auto boundingBox = Mantid::SliceViewer::getPeakBoundingBoxForEllipsoid(
-            directions, radii, origin);
-
-        // Assert
-        const double expectedLeft = -1.0;
-        const double expectedRight = 3.0;
-        const double expectedTop = 3.5;
-        const double expectedBottom = 0.5;
-        const double expectedSlicePoint = -1.0;
-
-        const double delta = 1e-5;
-        TSM_ASSERT_DELTA("Left should be at -1.0.", expectedLeft,
-                         boundingBox.left(), delta);
-        TSM_ASSERT_DELTA("Right should be at 3.0.", expectedRight,
-                         boundingBox.right(), delta);
-        TSM_ASSERT_DELTA("Top should be at 3.5.", expectedTop,
-                         boundingBox.top(), delta);
-        TSM_ASSERT_DELTA("Bottom should be at 0.5.", expectedBottom,
-                         boundingBox.bottom(), delta);
-        TSM_ASSERT_DELTA("SlicePoint should be at -1.0.", expectedSlicePoint,
-                         boundingBox.slicePoint(), delta);
-    }
-
-    void test_that_bounding_box_of_non_axis_aligned_ellipsoid_is_found()
-    {
-        // Arrange
-        const double angleIn = 20.0 * M_PI / 180.0;
-        Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
-                                       0);
-        Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
-        Mantid::Kernel::V3D direction3(0, 0, 1);
-        std::vector<Mantid::Kernel::V3D> directions
-            = {direction1, direction2, direction3};
-        Mantid::Kernel::V3D origin(3.0, 1.0, 0.0);
-        std::vector<double> radii = {2.0, 1.0,0.5};
-
-        // Act
-        auto boundingBox = Mantid::SliceViewer::getPeakBoundingBoxForEllipsoid( directions, radii, origin);
-
-        // Assert
-        const double expectedLeft = -radii[0] * std::cos(angleIn) + origin[0];
-        const double expectedRight = radii[0] * std::cos(angleIn) + origin[0];
-        const double expectedTop = radii[1] * std::cos(angleIn) + origin[1];
-        const double expectedBottom = -radii[1] * std::cos(angleIn) + origin[1];
-        const double expectedSlicePoint = origin[2];
-
-        const double delta = 1e-5;
-        TSM_ASSERT_DELTA("Left should be at -2.0*Cos[angle] +3.", expectedLeft,
-                         boundingBox.left(), delta);
-        TSM_ASSERT_DELTA("Right should be at 2.0*Cos[angle] +3 .", expectedRight,
-                         boundingBox.right(), delta);
-        TSM_ASSERT_DELTA("Top should be at 1.0*Cos[angle].", expectedTop,
-                         boundingBox.top(), delta);
-        TSM_ASSERT_DELTA("Bottom should be at -1.0*Cos[angle].", expectedBottom,
-                         boundingBox.bottom(), delta);
-        TSM_ASSERT_DELTA("SlicePoint should be at 0.0.", expectedSlicePoint,
-                         boundingBox.slicePoint(), delta);
+  //-----------------------------------------------------------------
+  // Test for the creation of the Ellipsoid Matrix
+  //-----------------------------------------------------------------
+  void
+  test_that_correct_ellipsoid_matrix_is_generated_when_already_in_eigenbasis() {
+    // Arrange
+    std::vector<double> radii = {3.0, 2.0, 1.0};
+    Mantid::Kernel::V3D dir1(1.0, 0.0, 0.0);
+    Mantid::Kernel::V3D dir2(0.0, 1.0, 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
+
+    // Act
+    auto matrix =
+        Mantid::SliceViewer::createEllipsoidMatrixInXYZFrame(directions, radii);
+
+    // Assert
+
+    std::vector<std::pair<int, int>> indices = {
+        {0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}};
+
+    for (const auto &index : indices) {
+      TSM_ASSERT("Non-diagonal element should be zero",
+                 matrix[index.first][index.second] == 0.0);
     }
-
-    //-----------------------------------------------------------------
-    // Tests for finding projection of the ellipsoid onto xyz axes
-    //-----------------------------------------------------------------
-    void test_that_projection_for_axis_aligned_is_found()
-    {
-        // Arrange
-        Mantid::Kernel::V3D dir1(1.0, 0.0, 0.0);
-        Mantid::Kernel::V3D dir2(0.0, 1.0, 0.0);
-        Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-        std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
-        std::vector<double> radii = {3.0, 2.0, 1.0};
-
-        // Act
-        auto projections
-            = Mantid::SliceViewer::getProjectionLengths(directions, radii);
-
-        // Assert
-        const double delta = 1e-5;
-        TSM_ASSERT_DELTA("Projection onto x should be 3.", projections[0],
-                         radii[0], delta);
-        TSM_ASSERT_DELTA("Projection onto y should be 2.", projections[1],
-                         radii[1], delta);
-        TSM_ASSERT_DELTA("Projection onto y should be 1.", projections[2],
-                         radii[2], delta);
-    }
-
-    void test_that_projection_for_non_axis_aligned_is_found()
-    {
-        // Arrange
-      const double angle = 35.0 * M_PI / 180.0;
-        Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
-        Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
-        Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-        std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
-        std::vector<double> radii = {3.0, 2.0, 1.0};
-
-        // Act
-        auto projections
-            = Mantid::SliceViewer::getProjectionLengths(directions, radii);
-
-        // Assert
-        auto expectedProjetionX = dir1[0] * radii[0];
-        auto expectedProjectionY
-            = dir1[1] * radii[0]; // Note that the first direction dominates the
-                                  // projection on both x and y in this
-                                  // particular case
-
-        const double delta = 1e-5;
-        TSM_ASSERT_DELTA("Projection onto x should be 3.", projections[0],
-                         expectedProjetionX, delta);
-        TSM_ASSERT_DELTA("Projection onto y should be 2.", projections[1],
-                         expectedProjectionY, delta);
-        TSM_ASSERT_DELTA("Projection onto y should be 1.", projections[2],
-                         radii[2], delta);
-    }
-
-    //-----------------------------------------------------------------
-    // Tests for checking if a cut exists
-    //-----------------------------------------------------------------
-    void test_that_that_detects_if_cut_exists() {
-      // Arrange
-      const double angle = 35.0 * M_PI / 180.0;
-      Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
-      Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
-      Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-      std::vector<Mantid::Kernel::V3D> directions{dir1, dir2, dir3};
-      std::vector<double> radii = {3.0, 2.0, 1.0};
-      Mantid::Kernel::V3D originEllipsoid(2.0,6.0,3.0);
-      double zPlane = 3.7;
-
-      // Act
-      auto cutExists = Mantid::SliceViewer::checkIfCutExists(directions, radii, originEllipsoid, zPlane);
-
-      // Assert
-      TSM_ASSERT("Cut should be possible", cutExists);
-    }
-
-    void test_that_that_detects_if_cut_does_not_exist() {
-      // Arrange
-      const double angle = 35.0 * M_PI / 180.0;
-      Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
-      Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
-      Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
-      std::vector<Mantid::Kernel::V3D> directions{dir1, dir2, dir3};
-      std::vector<double> radii = {3.0, 2.0, 1.0};
-      Mantid::Kernel::V3D originEllipsoid(2.0,6.0,3.0);
-      double zPlane = 4.5;
-
-      // Act
-      auto cutExists = Mantid::SliceViewer::checkIfCutExists(directions, radii, originEllipsoid, zPlane);
-
-      // Assert
-      TSM_ASSERT("Cut should not be possible", !cutExists);
+    TSM_ASSERT_EQUALS("Should be the first 1/radius^2", matrix[0][0],
+                      1 / std::pow(radii[0], 2));
+    TSM_ASSERT_EQUALS("Should be the second 1/radius^2", matrix[1][1],
+                      1 / std::pow(radii[1], 2));
+    TSM_ASSERT_EQUALS("Should be the third 1/radius^2", matrix[2][2],
+                      1 / std::pow(radii[2], 2));
+  }
+
+  void
+  test_that_correct_ellipsoid_matrix_is_generated_when_eigenbasis_rotated_45_degrees_around_z() {
+
+    // Arrange
+    std::vector<double> radii = {3.0, 2.0, 1.5};
+    std::vector<double> inverseRadiiSquared = {1 / std::pow(radii[0], 2),
+                                               1 / std::pow(radii[1], 2),
+                                               1 / std::pow(radii[2], 2)};
+    Mantid::Kernel::V3D dir1(M_SQRT1_2, -1 * M_SQRT1_2, 0.0);
+    Mantid::Kernel::V3D dir2(M_SQRT1_2, M_SQRT1_2, 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
+
+    // Act
+    auto matrix =
+        Mantid::SliceViewer::createEllipsoidMatrixInXYZFrame(directions, radii);
+
+    // Assert
+    Mantid::Kernel::DblMatrix eigenValues; // on the diagonal
+    Mantid::Kernel::DblMatrix eigenVectors;
+    matrix.Diagonalise(eigenVectors, eigenValues);
+
+    double delta = 1e-5;
+    for (int index = 0; index < 3; ++index) {
+      auto invRad = inverseRadiiSquared[index];
+      TSM_ASSERT_DELTA("Eigenvalue should correspond to inverse radius squared",
+                       invRad, eigenValues[index][index], delta);
     }
+  }
+
+  //-----------------------------------------------------------------
+  // Tests for handling spheres
+  //-----------------------------------------------------------------
+  void
+  test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_origin_and_origin_at_0() {
+
+    // Arrange
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+    double zCutPlane = 0; // We cut at z = 0
+    Mantid::Kernel::V3D direction1(1, 0,
+                                   0); // The directions are simply x, y, z
+    Mantid::Kernel::V3D direction2(0, 1, 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {
+        1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
+    Mantid::Kernel::V3D origin(0.0, 0.0, 0.0); // The origin is at 0,0,0
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, radii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, radii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 0", info.origin.X(),
+                     0.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 0", info.origin.Y(),
+                     0.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 0", info.origin.Z(),
+                     0.0, delta);
+  }
+
+  void
+  test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_and_origin_at__3_2_1() {
+    // Arrange
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+    double zCutPlane = 1; // We cut at z = 1
+    Mantid::Kernel::V3D direction1(1, 0,
+                                   0); // The directions are simply x, y, z
+    Mantid::Kernel::V3D direction2(0, 1, 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {
+        1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, radii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, radii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+
+    TSM_ASSERT_DELTA("The z part of the origin should be at 1", info.origin.Z(),
+                     1.0, delta);
+  }
+
+  void
+  test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_5_and_origin_at__3_2_1() {
+    // Arrange
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+    double zCutPlane = 1.5; // We cut at z = 1.5
+    Mantid::Kernel::V3D direction1(1, 0,
+                                   0); // The directions are simply x, y, z
+    Mantid::Kernel::V3D direction2(0, 1, 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {
+        1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+
+    // Radius is 1 and we are looking at 0.5 from the origin
+    // ie x^2 + y^2 + 0.5^2 == r^2 ==> reffective^2 = 1^2 -0.5^2 = 0.75
+    std::vector<double> expcetedRadii = {std::sqrt(0.75)};
+    TSM_ASSERT("The first radius should be Sqrt[0.75]",
+               radiusIsInListOfRadii(info.radiusMajorAxis, expcetedRadii));
+    TSM_ASSERT("The second radius should be Sqrt[0.75]",
+               radiusIsInListOfRadii(info.radiusMinorAxis, expcetedRadii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 2", info.origin.Z(),
+                     1.5, delta);
+  }
+
+  void
+  test_that_correct_slice_information_is_generated_for_sphere_with_cut_through_1_5_and_origin_at__3_2_1_with_tilted_axes() {
+    // Arrange
+    const double angleIn = 30 / 180 * M_PI;
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+    double zCutPlane = 1.5; // We cut at z = 1.5
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
+                                   0); // The directions are simply x, y, z
+    Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {
+        1.0, 1.0, 1.0}; // The radii are equal, hence we have a sphere
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0); // The origin is at 3,2,1
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+
+    // The rotation was 30deg, but we have a sphere so angle should be 0
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+
+    // Radius is 1 and we are looking at 0.5 from the origin
+    // ie x^2 + y^2 + 0.5^2 == r^2 ==> reffective^2 = 1^2 -0.5^2 = 0.75
+    std::vector<double> expcetedRadii = {std::sqrt(0.75)};
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, expcetedRadii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, expcetedRadii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 2", info.origin.Z(),
+                     1.5, delta);
+  }
+
+  //-----------------------------------------------------------------
+  // Tests for handling ellipsoids
+  //-----------------------------------------------------------------
+  void
+  test_correct_for_ellipsoid_with_cut_through_0_and_origin_at_0_with_axis_aligned() {
+    // Arrange
+    const double angleIn = 0.0;
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+    double zCutPlane = 0;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), -std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {4.0, 3.0, 2.0};
+    Mantid::Kernel::V3D origin(0.0, 0.0, 0.0);
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, radii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, radii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 0", info.origin.X(),
+                     0.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 0", info.origin.Y(),
+                     0.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 0", info.origin.Z(),
+                     0.0, delta);
+  }
+
+  void
+  test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_aligned() {
+    // Arrange
+    const double angleIn = 0.0;
+    double zCutPlane = 1.5;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), -std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {4.0, 3.0, 2.0};
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
+
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+
+    TSM_ASSERT("The angle should be 0",
+               isAngleEitherValueOr180DegreesRoated(0.0, info.angle));
+
+    // From (x/4)^2 + (y/3)^2 + (0.5/2)^2 = 1 we get
+    // r1 = 4* Sqrt[1-(0.5/2)^2]
+    // r2 = 3* Sqrt[1-(0.5/2)^2]
+    std::vector<double> expectedRadii = {4.0 * std::sqrt(1 - std::pow(0.25, 2)),
+                                         3.0 *
+                                             std::sqrt(1 - std::pow(0.25, 2))};
+
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 1.5",
+                     info.origin.Z(), 1.5, delta);
+  }
+
+  void
+  test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_less_than_45_degrees() {
+    double const angle = 32;         // in degree
+    double const expectedAngle = 32; // in degree
+    do_test_ellipsoid_with_tilt(angle, expectedAngle);
+  }
+
+  void
+  test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_45_degrees() {
+    double const angle = 45;         // in degree
+    double const expectedAngle = 45; // in degree
+    do_test_ellipsoid_with_tilt(angle, expectedAngle);
+  }
+
+  void
+  test_correct_for_ellipsoid_with_cut_through_1_5_and_origin_at_3_2_1_with_axis_tilt_with_more_than_45_degrees() {
+    double const angle = 48;         // in degree
+    double const expectedAngle = 48; // in degree
+    do_test_ellipsoid_with_tilt(angle, expectedAngle);
+  }
+
+  void
+  test_finds_ellipse_for_ellipsoid_with_major_axis_along_z_and_cut_through_5_and_origin_at_3_2_1_with_axis_tilt() {
+    // Arrange
+    const double angleIn = 34.0 * 2 * M_PI / 360;
+    double zCutPlane = 5.0;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {4.0, 3.0, 7.0};
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
+
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+
+    // The angle we get from info is the angle
+    TSM_ASSERT("The angle should be 34",
+               isAngleEitherValueOr180DegreesRoated(angleIn, info.angle));
+
+    // From (x/4)^2 + (y/3)^2 + ((5-1)/7)^2 = 1 we get
+    // r1 = 4* Sqrt[1-(4/7)^2]
+    // r2 = 3* Sqrt[1-(4/7)^2]
+    std::vector<double> expectedRadii = {
+        4.0 * std::sqrt(1 - std::pow(4.0 / 7.0, 2)),
+        3.0 * std::sqrt(1 - std::pow(4.0 / 7.0, 2))};
+
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 5", info.origin.Z(),
+                     5, delta);
+  }
+
+  //-----------------------------------------------------------------
+  // Tests for bounding box of an ellipse
+  //-----------------------------------------------------------------
+  void test_that_bounding_box_of_axis_aligned_ellipsoid_is_found() {
+    // Arrange
+    const double angleIn = 0.0;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    Mantid::Kernel::V3D origin(1.0, 2.0, -1.0);
+    std::vector<double> radii = {2.0, 1.5, 0.5};
+
+    // Act
+    auto boundingBox = Mantid::SliceViewer::getPeakBoundingBoxForEllipsoid(
+        directions, radii, origin);
+
+    // Assert
+    const double expectedLeft = -1.0;
+    const double expectedRight = 3.0;
+    const double expectedTop = 3.5;
+    const double expectedBottom = 0.5;
+    const double expectedSlicePoint = -1.0;
+
+    const double delta = 1e-5;
+    TSM_ASSERT_DELTA("Left should be at -1.0.", expectedLeft,
+                     boundingBox.left(), delta);
+    TSM_ASSERT_DELTA("Right should be at 3.0.", expectedRight,
+                     boundingBox.right(), delta);
+    TSM_ASSERT_DELTA("Top should be at 3.5.", expectedTop, boundingBox.top(),
+                     delta);
+    TSM_ASSERT_DELTA("Bottom should be at 0.5.", expectedBottom,
+                     boundingBox.bottom(), delta);
+    TSM_ASSERT_DELTA("SlicePoint should be at -1.0.", expectedSlicePoint,
+                     boundingBox.slicePoint(), delta);
+  }
+
+  void test_that_bounding_box_of_non_axis_aligned_ellipsoid_is_found() {
+    // Arrange
+    const double angleIn = 20.0 * M_PI / 180.0;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    Mantid::Kernel::V3D origin(3.0, 1.0, 0.0);
+    std::vector<double> radii = {2.0, 1.0, 0.5};
+
+    // Act
+    auto boundingBox = Mantid::SliceViewer::getPeakBoundingBoxForEllipsoid(
+        directions, radii, origin);
+
+    // Assert
+    const double expectedLeft = -radii[0] * std::cos(angleIn) + origin[0];
+    const double expectedRight = radii[0] * std::cos(angleIn) + origin[0];
+    const double expectedTop = radii[1] * std::cos(angleIn) + origin[1];
+    const double expectedBottom = -radii[1] * std::cos(angleIn) + origin[1];
+    const double expectedSlicePoint = origin[2];
+
+    const double delta = 1e-5;
+    TSM_ASSERT_DELTA("Left should be at -2.0*Cos[angle] +3.", expectedLeft,
+                     boundingBox.left(), delta);
+    TSM_ASSERT_DELTA("Right should be at 2.0*Cos[angle] +3 .", expectedRight,
+                     boundingBox.right(), delta);
+    TSM_ASSERT_DELTA("Top should be at 1.0*Cos[angle].", expectedTop,
+                     boundingBox.top(), delta);
+    TSM_ASSERT_DELTA("Bottom should be at -1.0*Cos[angle].", expectedBottom,
+                     boundingBox.bottom(), delta);
+    TSM_ASSERT_DELTA("SlicePoint should be at 0.0.", expectedSlicePoint,
+                     boundingBox.slicePoint(), delta);
+  }
+
+  //-----------------------------------------------------------------
+  // Tests for finding projection of the ellipsoid onto xyz axes
+  //-----------------------------------------------------------------
+  void test_that_projection_for_axis_aligned_is_found() {
+    // Arrange
+    Mantid::Kernel::V3D dir1(1.0, 0.0, 0.0);
+    Mantid::Kernel::V3D dir2(0.0, 1.0, 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
+    std::vector<double> radii = {3.0, 2.0, 1.0};
+
+    // Act
+    auto projections =
+        Mantid::SliceViewer::getProjectionLengths(directions, radii);
+
+    // Assert
+    const double delta = 1e-5;
+    TSM_ASSERT_DELTA("Projection onto x should be 3.", projections[0], radii[0],
+                     delta);
+    TSM_ASSERT_DELTA("Projection onto y should be 2.", projections[1], radii[1],
+                     delta);
+    TSM_ASSERT_DELTA("Projection onto y should be 1.", projections[2], radii[2],
+                     delta);
+  }
+
+  void test_that_projection_for_non_axis_aligned_is_found() {
+    // Arrange
+    const double angle = 35.0 * M_PI / 180.0;
+    Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
+    Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions = {dir1, dir2, dir3};
+    std::vector<double> radii = {3.0, 2.0, 1.0};
+
+    // Act
+    auto projections =
+        Mantid::SliceViewer::getProjectionLengths(directions, radii);
+
+    // Assert
+    auto expectedProjetionX = dir1[0] * radii[0];
+    auto expectedProjectionY =
+        dir1[1] * radii[0]; // Note that the first direction dominates the
+                            // projection on both x and y in this
+                            // particular case
+
+    const double delta = 1e-5;
+    TSM_ASSERT_DELTA("Projection onto x should be 3.", projections[0],
+                     expectedProjetionX, delta);
+    TSM_ASSERT_DELTA("Projection onto y should be 2.", projections[1],
+                     expectedProjectionY, delta);
+    TSM_ASSERT_DELTA("Projection onto y should be 1.", projections[2], radii[2],
+                     delta);
+  }
+
+  //-----------------------------------------------------------------
+  // Tests for checking if a cut exists
+  //-----------------------------------------------------------------
+  void test_that_that_detects_if_cut_exists() {
+    // Arrange
+    const double angle = 35.0 * M_PI / 180.0;
+    Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
+    Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions{dir1, dir2, dir3};
+    std::vector<double> radii = {3.0, 2.0, 1.0};
+    Mantid::Kernel::V3D originEllipsoid(2.0, 6.0, 3.0);
+    double zPlane = 3.7;
+
+    // Act
+    auto cutExists = Mantid::SliceViewer::checkIfCutExists(
+        directions, radii, originEllipsoid, zPlane);
+
+    // Assert
+    TSM_ASSERT("Cut should be possible", cutExists);
+  }
+
+  void test_that_that_detects_if_cut_does_not_exist() {
+    // Arrange
+    const double angle = 35.0 * M_PI / 180.0;
+    Mantid::Kernel::V3D dir1(std::cos(angle), std::sin(angle), 0.0);
+    Mantid::Kernel::V3D dir2(-std::sin(angle), std::cos(angle), 0.0);
+    Mantid::Kernel::V3D dir3(0.0, 0.0, 1.0);
+    std::vector<Mantid::Kernel::V3D> directions{dir1, dir2, dir3};
+    std::vector<double> radii = {3.0, 2.0, 1.0};
+    Mantid::Kernel::V3D originEllipsoid(2.0, 6.0, 3.0);
+    double zPlane = 4.5;
+
+    // Act
+    auto cutExists = Mantid::SliceViewer::checkIfCutExists(
+        directions, radii, originEllipsoid, zPlane);
+
+    // Assert
+    TSM_ASSERT("Cut should not be possible", !cutExists);
+  }
 
 private:
-    void do_test_ellipsoid_with_tilt(double angle, double expectedAngle) {
-      // Arrange
-      const double angleIn = angle * 2 * M_PI / 360.0;
-      double zCutPlane = 1.5;
-      Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn),
-                                     0);
-      Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
-      Mantid::Kernel::V3D direction3(0, 0, 1);
-      std::vector<Mantid::Kernel::V3D> directions
-          = {direction1, direction2, direction3};
-      std::vector<double> radii = {4.0, 3.0, 2.0};
-      Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
-
-      Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
-
-      // Act
-      auto info = calculator.getSlicePlaneInfo(directions, radii, origin,
-                                               zCutPlane);
-
-      // Assert
-      const double delta = 1e-5;
-
-      // The angle we get from info is the angle
-      TSM_ASSERT("The angle should be be equal", isAngleEitherValueOr180DegreesRoated(expectedAngle*M_PI/180.0,info.angle));
-
-      // From (x/4)^2 + (y/3)^2 + (0.5/2)^2 = 1 we get
-      // r1 = 4* Sqrt[1-(0.5/2)^2]
-      // r2 = 3* Sqrt[1-(0.5/2)^2]
-      std::vector<double> expectedRadii
-          = {4.0 * std::sqrt(1 - std::pow(0.25, 2)),
-             3.0 * std::sqrt(1 - std::pow(0.25, 2))};
-
-      TSM_ASSERT("The first radius should be 1",
-                 radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
-      TSM_ASSERT("The second radius should be 1",
-                 radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
-
-      TSM_ASSERT_DELTA("The x part of the origin should be at 3",
-                       info.origin.X(), 3.0, delta);
-      TSM_ASSERT_DELTA("The y part of the origin should be at 2",
-                       info.origin.Y(), 2.0, delta);
-      TSM_ASSERT_DELTA("The z part of the origin should be at 1.5",
-                       info.origin.Z(), 1.5, delta);
-    }
+  void do_test_ellipsoid_with_tilt(double angle, double expectedAngle) {
+    // Arrange
+    const double angleIn = angle * 2 * M_PI / 360.0;
+    double zCutPlane = 1.5;
+    Mantid::Kernel::V3D direction1(std::cos(angleIn), std::sin(angleIn), 0);
+    Mantid::Kernel::V3D direction2(-std::sin(angleIn), std::cos(angleIn), 0);
+    Mantid::Kernel::V3D direction3(0, 0, 1);
+    std::vector<Mantid::Kernel::V3D> directions = {direction1, direction2,
+                                                   direction3};
+    std::vector<double> radii = {4.0, 3.0, 2.0};
+    Mantid::Kernel::V3D origin(3.0, 2.0, 1.0);
+
+    Mantid::SliceViewer::EllipsoidPlaneSliceCalculator calculator;
+
+    // Act
+    auto info =
+        calculator.getSlicePlaneInfo(directions, radii, origin, zCutPlane);
+
+    // Assert
+    const double delta = 1e-5;
+
+    // The angle we get from info is the angle
+    TSM_ASSERT("The angle should be be equal",
+               isAngleEitherValueOr180DegreesRoated(
+                   expectedAngle * M_PI / 180.0, info.angle));
+
+    // From (x/4)^2 + (y/3)^2 + (0.5/2)^2 = 1 we get
+    // r1 = 4* Sqrt[1-(0.5/2)^2]
+    // r2 = 3* Sqrt[1-(0.5/2)^2]
+    std::vector<double> expectedRadii = {4.0 * std::sqrt(1 - std::pow(0.25, 2)),
+                                         3.0 *
+                                             std::sqrt(1 - std::pow(0.25, 2))};
+
+    TSM_ASSERT("The first radius should be 1",
+               radiusIsInListOfRadii(info.radiusMajorAxis, expectedRadii));
+    TSM_ASSERT("The second radius should be 1",
+               radiusIsInListOfRadii(info.radiusMinorAxis, expectedRadii));
+
+    TSM_ASSERT_DELTA("The x part of the origin should be at 3", info.origin.X(),
+                     3.0, delta);
+    TSM_ASSERT_DELTA("The y part of the origin should be at 2", info.origin.Y(),
+                     2.0, delta);
+    TSM_ASSERT_DELTA("The z part of the origin should be at 1.5",
+                     info.origin.Z(), 1.5, delta);
+  }
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/test/NullPeaksPresenterTest.h b/MantidQt/SliceViewer/test/NullPeaksPresenterTest.h
index 4d16908cc3d99dc860b0bb15729744e5c36de5eb..f4d59bdb3209e7f5d5d13f27cf5752a632680e00 100644
--- a/MantidQt/SliceViewer/test/NullPeaksPresenterTest.h
+++ b/MantidQt/SliceViewer/test/NullPeaksPresenterTest.h
@@ -8,79 +8,65 @@
 
 using namespace MantidQt::SliceViewer;
 
-class NullPeaksPresenterTest : public CxxTest::TestSuite
-{
+class NullPeaksPresenterTest : public CxxTest::TestSuite {
 
 public:
+  void test_construction() { TS_ASSERT_THROWS_NOTHING(NullPeaksPresenter p); }
 
-  void test_construction()
-  {
-      TS_ASSERT_THROWS_NOTHING(NullPeaksPresenter p);
-  }
-
-  void test_is_peaks_presenter()
-  {
+  void test_is_peaks_presenter() {
     NullPeaksPresenter presenter;
-    PeaksPresenter& base = presenter; // compile-time test for the is-a relationship
+    PeaksPresenter &base =
+        presenter; // compile-time test for the is-a relationship
     UNUSED_ARG(base);
   }
 
   /* Test individual methods on the interface */
 
-  void test_update_does_nothing()
-  {
+  void test_update_does_nothing() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.update());
   }
 
-  void test_updateWithSlicePoint_does_nothing()
-  {
+  void test_updateWithSlicePoint_does_nothing() {
     NullPeaksPresenter presenter;
     PeakBoundingBox region;
     TS_ASSERT_THROWS_NOTHING(presenter.updateWithSlicePoint(region));
   }
 
-  void test_changeShownDim_does_nothing()
-  {
+  void test_changeShownDim_does_nothing() {
     NullPeaksPresenter presenter;
     TS_ASSERT(!presenter.changeShownDim());
   }
 
-  void test_isLabelOfFreeAxis_always_returns_false()
-  {
+  void test_isLabelOfFreeAxis_always_returns_false() {
     NullPeaksPresenter presenter;
     TS_ASSERT(!presenter.isLabelOfFreeAxis(""));
   }
 
-  void test_presentedWorkspaces_is_empty()
-  {
+  void test_presentedWorkspaces_is_empty() {
     NullPeaksPresenter presenter;
     SetPeaksWorkspaces workspaces = presenter.presentedWorkspaces();
     TS_ASSERT_EQUALS(0, workspaces.size());
   }
 
-  void test_setForegroundColour_does_nothing()
-  {
+  void test_setForegroundColour_does_nothing() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.setForegroundColor(PeakViewColor()));
   }
 
-  void test_setBackgroundColour_does_nothing()
-  {
+  void test_setBackgroundColour_does_nothing() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.setBackgroundColor(PeakViewColor()));
   }
 
-  void test_setShown_does_nothing()
-  {
+  void test_setShown_does_nothing() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.setShown(true));
     TS_ASSERT_THROWS_NOTHING(presenter.setShown(false));
   }
 
   /// return a box collapsed to a point at 0, 0.
-  void test_getBoundingBox_returns_point()
-  {
+  void test_getBoundingBox_returns_point() {
     NullPeaksPresenter presenter;
     PeakBoundingBox result = presenter.getBoundingBox(0);
 
@@ -90,48 +76,42 @@ public:
     TS_ASSERT_EQUALS(0, result.bottom());
   }
 
-  void test_setPeakSizeOnProjection()
-  {
+  void test_setPeakSizeOnProjection() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.setPeakSizeOnProjection(1));
   }
 
-  void test_setPeakSizeIntoProjection()
-  {
+  void test_setPeakSizeIntoProjection() {
     NullPeaksPresenter presenter;
     TS_ASSERT_THROWS_NOTHING(presenter.setPeakSizeIntoProjection(1));
   }
 
-  void test_getPeakSizeOnProjection()
-  {
+  void test_getPeakSizeOnProjection() {
     NullPeaksPresenter presenter;
     TS_ASSERT_EQUALS(0, presenter.getPeakSizeOnProjection());
   }
 
-  void test_getPeakSizeIntoProjection()
-  {
+  void test_getPeakSizeIntoProjection() {
     NullPeaksPresenter presenter;
     TS_ASSERT_EQUALS(0, presenter.getPeakSizeIntoProjection());
   }
 
-  void test_contentsDifferent()
-  {
-      NullPeaksPresenter presenter;
-      MockPeaksPresenter other;
-      TS_ASSERT(presenter.contentsDifferent(&other));
+  void test_contentsDifferent() {
+    NullPeaksPresenter presenter;
+    MockPeaksPresenter other;
+    TS_ASSERT(presenter.contentsDifferent(&other));
   }
 
-  void test_peakEditMode(){
-      NullPeaksPresenter presenter;
-      TS_ASSERT_THROWS_NOTHING(presenter.peakEditMode(AddPeaks););
+  void test_peakEditMode() {
+    NullPeaksPresenter presenter;
+    TS_ASSERT_THROWS_NOTHING(presenter.peakEditMode(AddPeaks););
   }
 
-  void test_deletePeaksIn(){
-      NullPeaksPresenter presenter;
-      PeakBoundingBox fake;
-      TS_ASSERT_THROWS_NOTHING(presenter.deletePeaksIn(fake));
+  void test_deletePeaksIn() {
+    NullPeaksPresenter presenter;
+    PeakBoundingBox fake;
+    TS_ASSERT_THROWS_NOTHING(presenter.deletePeaksIn(fake));
   }
-
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/test/PeakBoundingBoxTest.h b/MantidQt/SliceViewer/test/PeakBoundingBoxTest.h
index d79417cddbd8a9bffcc3e6384f933c2b835a2f17..f68352af346d8d0acec893c21c8adf7a70b5eb11 100644
--- a/MantidQt/SliceViewer/test/PeakBoundingBoxTest.h
+++ b/MantidQt/SliceViewer/test/PeakBoundingBoxTest.h
@@ -6,20 +6,18 @@
 
 using namespace MantidQt::SliceViewer;
 
-class PeakBoundingBoxTest : public CxxTest::TestSuite
-{
+class PeakBoundingBoxTest : public CxxTest::TestSuite {
 
 public:
-
-  void test_construction()
-  {
+  void test_construction() {
     const Right expectedRight(1);
     const Left expectedLeft(0);
     const Top expectedTop(1);
     const Bottom expectedBottom(0);
     const SlicePoint expectedSlicePoint(1);
 
-    PeakBoundingBox box(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint);
+    PeakBoundingBox box(expectedLeft, expectedRight, expectedTop,
+                        expectedBottom, expectedSlicePoint);
 
     TS_ASSERT_EQUALS(expectedLeft(), box.left());
     TS_ASSERT_EQUALS(expectedRight(), box.right());
@@ -30,8 +28,7 @@ public:
     TS_ASSERT_EQUALS(expectedSlicePoint(), box.back());
   }
 
-  void test_full_construction()
-  {
+  void test_full_construction() {
     const Right expectedRight(1);
     const Left expectedLeft(0);
     const Top expectedTop(1);
@@ -40,7 +37,9 @@ public:
     const Front expectedFront(0);
     const Back expectedBack(1);
 
-    PeakBoundingBox box(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint, expectedFront, expectedBack);
+    PeakBoundingBox box(expectedLeft, expectedRight, expectedTop,
+                        expectedBottom, expectedSlicePoint, expectedFront,
+                        expectedBack);
 
     TS_ASSERT_EQUALS(expectedLeft(), box.left());
     TS_ASSERT_EQUALS(expectedRight(), box.right());
@@ -51,8 +50,7 @@ public:
     TS_ASSERT_EQUALS(expectedBack(), box.back());
   }
 
-  void test_default_construction()
-  {
+  void test_default_construction() {
     PeakBoundingBox box;
 
     TS_ASSERT_EQUALS(0, box.left());
@@ -64,8 +62,7 @@ public:
     TS_ASSERT_EQUALS(0, box.back());
   }
 
-  void test_top_greater_than_bottom()
-  {
+  void test_top_greater_than_bottom() {
 
     const Right expectedRight(1);
     const Left expectedLeft(0);
@@ -73,22 +70,28 @@ public:
     const Bottom expectedBottom(2); // oops top < bottom
     const SlicePoint expectedSlicePoint(1);
 
-    TSM_ASSERT_THROWS( "Top < Bottom", PeakBoundingBox box(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint), std::invalid_argument&);
+    TSM_ASSERT_THROWS("Top < Bottom",
+                      PeakBoundingBox box(expectedLeft, expectedRight,
+                                          expectedTop, expectedBottom,
+                                          expectedSlicePoint),
+                      std::invalid_argument &);
   }
 
-  void test_right_greater_than_left()
-  {
+  void test_right_greater_than_left() {
     const Right expectedRight(1);
     const Left expectedLeft(2); // oops right < left
     const Top expectedTop(1);
     const Bottom expectedBottom(0);
     const SlicePoint expectedSlicePoint(1);
 
-    TSM_ASSERT_THROWS( "Right < Left", PeakBoundingBox box(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint), std::invalid_argument&);
+    TSM_ASSERT_THROWS("Right < Left",
+                      PeakBoundingBox box(expectedLeft, expectedRight,
+                                          expectedTop, expectedBottom,
+                                          expectedSlicePoint),
+                      std::invalid_argument &);
   }
 
-  void test_front_greater_than_back()
-  {
+  void test_front_greater_than_back() {
     const Right expectedRight(1);
     const Left expectedLeft(2);
     const Top expectedTop(1);
@@ -97,11 +100,15 @@ public:
     const Front expectedFront(1);
     const Back expectedBack(0); // oops front > back.
 
-    TSM_ASSERT_THROWS( "Right < Left", PeakBoundingBox box(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint, expectedFront, expectedBack), std::invalid_argument&);
+    TSM_ASSERT_THROWS("Right < Left",
+                      PeakBoundingBox box(expectedLeft, expectedRight,
+                                          expectedTop, expectedBottom,
+                                          expectedSlicePoint, expectedFront,
+                                          expectedBack),
+                      std::invalid_argument &);
   }
 
-  void test_copy()
-  {
+  void test_copy() {
     const Right expectedRight(1);
     const Left expectedLeft(0);
     const Top expectedTop(1);
@@ -110,8 +117,8 @@ public:
     const Front expectedFront(0);
     const Back expectedBack(1);
 
-
-    PeakBoundingBox A(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint, expectedFront, expectedBack);
+    PeakBoundingBox A(expectedLeft, expectedRight, expectedTop, expectedBottom,
+                      expectedSlicePoint, expectedFront, expectedBack);
     PeakBoundingBox B(A);
 
     TS_ASSERT_EQUALS(A.left(), B.left());
@@ -123,8 +130,7 @@ public:
     TS_ASSERT_EQUALS(A.back(), B.back());
   }
 
-  void test_assign()
-  {
+  void test_assign() {
     const Right expectedRight(1);
     const Left expectedLeft(0);
     const Top expectedTop(1);
@@ -133,7 +139,8 @@ public:
     const Front expectedFront(0);
     const Back expectedBack(1);
 
-    PeakBoundingBox A(expectedLeft, expectedRight, expectedTop, expectedBottom, expectedSlicePoint, expectedFront, expectedBack);
+    PeakBoundingBox A(expectedLeft, expectedRight, expectedTop, expectedBottom,
+                      expectedSlicePoint, expectedFront, expectedBack);
     PeakBoundingBox B;
 
     B = A;
@@ -147,24 +154,31 @@ public:
     TS_ASSERT_EQUALS(A.back(), B.back());
   }
 
-  void test_are_equal()
-  {
-    PeakBoundingBox a(Left(-1), Right(1), Top(1), Bottom(-1), SlicePoint(5), Front(3), Back(6));
-    PeakBoundingBox b(Left(-1), Right(1), Top(1), Bottom(-1), SlicePoint(5), Front(3), Back(6));
+  void test_are_equal() {
+    PeakBoundingBox a(Left(-1), Right(1), Top(1), Bottom(-1), SlicePoint(5),
+                      Front(3), Back(6));
+    PeakBoundingBox b(Left(-1), Right(1), Top(1), Bottom(-1), SlicePoint(5),
+                      Front(3), Back(6));
 
     TS_ASSERT(a == b);
   }
 
-  void test_are_not_equal()
-  {
+  void test_are_not_equal() {
     PeakBoundingBox a;
-    PeakBoundingBox b(Left(-1), Right(0), Top(0), Bottom(0), SlicePoint(0), Front(0), Back(0));
-    PeakBoundingBox c(Left(0), Right(1), Top(0), Bottom(0), SlicePoint(0), Front(0), Back(0));
-    PeakBoundingBox d(Left(0), Right(0), Top(1), Bottom(0), SlicePoint(0), Front(0), Back(0));
-    PeakBoundingBox e(Left(0), Right(0), Top(0), Bottom(-1), SlicePoint(0), Front(0), Back(0));
-    PeakBoundingBox f(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(1), Front(0), Back(1));
-    PeakBoundingBox g(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(1), Front(1), Back(1));
-    PeakBoundingBox h(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(0), Front(0), Back(1));
+    PeakBoundingBox b(Left(-1), Right(0), Top(0), Bottom(0), SlicePoint(0),
+                      Front(0), Back(0));
+    PeakBoundingBox c(Left(0), Right(1), Top(0), Bottom(0), SlicePoint(0),
+                      Front(0), Back(0));
+    PeakBoundingBox d(Left(0), Right(0), Top(1), Bottom(0), SlicePoint(0),
+                      Front(0), Back(0));
+    PeakBoundingBox e(Left(0), Right(0), Top(0), Bottom(-1), SlicePoint(0),
+                      Front(0), Back(0));
+    PeakBoundingBox f(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(1),
+                      Front(0), Back(1));
+    PeakBoundingBox g(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(1),
+                      Front(1), Back(1));
+    PeakBoundingBox h(Left(0), Right(0), Top(0), Bottom(0), SlicePoint(0),
+                      Front(0), Back(1));
 
     TS_ASSERT(a != b);
     TS_ASSERT(a != c);
@@ -175,14 +189,12 @@ public:
     TS_ASSERT(a != h);
   }
 
-  void test_to_string()
-  {
-    PeakBoundingBox box(Left(-1.234), Right(1.234), Top(2.234), Bottom(-20.234), SlicePoint(3.2), Front(3.124), Back(4.123));
+  void test_to_string() {
+    PeakBoundingBox box(Left(-1.234), Right(1.234), Top(2.234), Bottom(-20.234),
+                        SlicePoint(3.2), Front(3.124), Back(4.123));
     const std::string extents = box.toExtentsString();
     TS_ASSERT_EQUALS("-1.23,1.23,-20.23,2.23,3.12,4.12", extents);
   }
-
-
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/test/PeakPaletteTest.h b/MantidQt/SliceViewer/test/PeakPaletteTest.h
index 2138a99d8364237f2e80920a2c8fd64ab7f20a3c..99d1950bac0bf1c60de2782fcf57e8bc4edbf497 100644
--- a/MantidQt/SliceViewer/test/PeakPaletteTest.h
+++ b/MantidQt/SliceViewer/test/PeakPaletteTest.h
@@ -7,115 +7,133 @@
 
 using namespace MantidQt::SliceViewer;
 
-class PeakPaletteTest : public CxxTest::TestSuite
-{
+class PeakPaletteTest : public CxxTest::TestSuite {
 
 public:
-
-  void test_paletteSize()
-  {
+  void test_paletteSize() {
     PeakPalette<QColor> palette;
     const int expectedNumberOfEntries = 10;
-    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n", expectedNumberOfEntries, palette.paletteSize());
+    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n",
+                      expectedNumberOfEntries, palette.paletteSize());
   }
 
-  void test_default_foreground_colours_unique()
-  {
+  void test_default_foreground_colours_unique() {
     PeakPalette<QColor> palette;
-    for(int i = 0; i < palette.paletteSize()-1; ++i)
-    {
-      TS_ASSERT_DIFFERS(palette.foregroundIndexToColour(i), palette.foregroundIndexToColour(i+1));
+    for (int i = 0; i < palette.paletteSize() - 1; ++i) {
+      TS_ASSERT_DIFFERS(palette.foregroundIndexToColour(i),
+                        palette.foregroundIndexToColour(i + 1));
     }
-  }  
+  }
 
-  void test_default_background_colours_unique()
-  {
+  void test_default_background_colours_unique() {
     PeakPalette<QColor> palette;
-    for(int i = 0; i < palette.paletteSize()-1; ++i)
-    {
-      TS_ASSERT_DIFFERS(palette.backgroundIndexToColour(i), palette.backgroundIndexToColour(i+1));
+    for (int i = 0; i < palette.paletteSize() - 1; ++i) {
+      TS_ASSERT_DIFFERS(palette.backgroundIndexToColour(i),
+                        palette.backgroundIndexToColour(i + 1));
     }
   }
 
-  void test_foregroundIndexToColour_throws_if_out_of_range()
-  {
+  void test_foregroundIndexToColour_throws_if_out_of_range() {
     const int indexTooHigh = 10;
     const int indexTooLow = -1;
 
     PeakPalette<QColor> palette;
-    TSM_ASSERT_THROWS("\n\nIndex > Max Index, should throw.\n", palette.foregroundIndexToColour(indexTooHigh), std::out_of_range);
-    TSM_ASSERT_THROWS("\n\nIndex < Max Index, should throw.\n", palette.foregroundIndexToColour(indexTooLow), std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex > Max Index, should throw.\n",
+                      palette.foregroundIndexToColour(indexTooHigh),
+                      std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex < Max Index, should throw.\n",
+                      palette.foregroundIndexToColour(indexTooLow),
+                      std::out_of_range);
   }
 
-  void test_backgroundIndexToColour_throws_if_out_of_range()
-  {
+  void test_backgroundIndexToColour_throws_if_out_of_range() {
     const int indexTooHigh = 10;
     const int indexTooLow = -1;
 
     PeakPalette<QColor> palette;
-    TSM_ASSERT_THROWS("\n\nIndex > Max Index, should throw.\n", palette.backgroundIndexToColour(indexTooHigh), std::out_of_range);
-    TSM_ASSERT_THROWS("\n\nIndex < Max Index, should throw.\n", palette.backgroundIndexToColour(indexTooLow), std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex > Max Index, should throw.\n",
+                      palette.backgroundIndexToColour(indexTooHigh),
+                      std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex < Max Index, should throw.\n",
+                      palette.backgroundIndexToColour(indexTooLow),
+                      std::out_of_range);
   }
 
-  void test_setForgroundColour()
-  {
+  void test_setForgroundColour() {
     PeakPalette<QColor> palette;
     const int indexToChange = 0;
-    const QColor originalColour = palette.foregroundIndexToColour(indexToChange);
+    const QColor originalColour =
+        palette.foregroundIndexToColour(indexToChange);
     const QColor requestColour(Qt::black);
 
     palette.setForegroundColour(indexToChange, requestColour);
 
     const QColor finalColour = palette.foregroundIndexToColour(indexToChange);
 
-    TSM_ASSERT_DIFFERS("\n\nForeground palette colour has not changed at requested index.\n", originalColour, finalColour);
-    TSM_ASSERT_EQUALS("\n\nForeground palette colour has not changed to the requested colour.\n", requestColour, finalColour);
+    TSM_ASSERT_DIFFERS(
+        "\n\nForeground palette colour has not changed at requested index.\n",
+        originalColour, finalColour);
+    TSM_ASSERT_EQUALS("\n\nForeground palette colour has not changed to the "
+                      "requested colour.\n",
+                      requestColour, finalColour);
 
     const int expectedNumberOfEntries = 10;
-    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n", expectedNumberOfEntries, palette.paletteSize());
+    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n",
+                      expectedNumberOfEntries, palette.paletteSize());
   }
 
-  void test_setBackgroundColour()
-  {
+  void test_setBackgroundColour() {
     PeakPalette<QColor> palette;
     const int indexToChange = 0;
-    const QColor originalColour = palette.backgroundIndexToColour(indexToChange);
+    const QColor originalColour =
+        palette.backgroundIndexToColour(indexToChange);
     const QColor requestColour = Qt::black;
 
     palette.setForegroundColour(indexToChange, requestColour);
 
     const QColor finalColour = palette.foregroundIndexToColour(indexToChange);
 
-    TSM_ASSERT_DIFFERS("\n\nBackground palette colour has not changed at requested index.\n", originalColour, finalColour);
-    TSM_ASSERT_EQUALS("\n\nBackground palette colour has not changed to the requested colour.\n", requestColour, finalColour);
+    TSM_ASSERT_DIFFERS(
+        "\n\nBackground palette colour has not changed at requested index.\n",
+        originalColour, finalColour);
+    TSM_ASSERT_EQUALS("\n\nBackground palette colour has not changed to the "
+                      "requested colour.\n",
+                      requestColour, finalColour);
 
     const int expectedNumberOfEntries = 10;
-    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n", expectedNumberOfEntries, palette.paletteSize());
+    TSM_ASSERT_EQUALS("\n\nPalette should have a default and fixed size\n",
+                      expectedNumberOfEntries, palette.paletteSize());
   }
 
-  void test_setForegroundColour_throws_if_out_of_range()
-  {
+  void test_setForegroundColour_throws_if_out_of_range() {
     const int indexTooHigh = 10;
     const int indexTooLow = -1;
 
     PeakPalette<QColor> palette;
-    TSM_ASSERT_THROWS("\n\nIndex is > Max Index. Should throw\n.", palette.setForegroundColour(indexTooHigh, Qt::red), std::out_of_range);
-    TSM_ASSERT_THROWS("\n\nIndex is < Min Index. Should throw\n", palette.setForegroundColour(indexTooLow, Qt::red), std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex is > Max Index. Should throw\n.",
+                      palette.setForegroundColour(indexTooHigh, Qt::red),
+                      std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex is < Min Index. Should throw\n",
+                      palette.setForegroundColour(indexTooLow, Qt::red),
+                      std::out_of_range);
   }
 
-  void test_setBackgroundColour_throws_if_out_of_range()
-  {
+  void test_setBackgroundColour_throws_if_out_of_range() {
     const int indexTooHigh = 10;
     const int indexTooLow = -1;
 
     PeakPalette<QColor> palette;
-    TSM_ASSERT_THROWS("\n\nIndex is > Max Index. Should throw\n.", palette.setBackgroundColour(indexTooHigh, Qt::red), std::out_of_range);
-    TSM_ASSERT_THROWS("\n\nIndex is < Min Index. Should throw\n", palette.setBackgroundColour(indexTooLow, Qt::red), std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex is > Max Index. Should throw\n.",
+                      palette.setBackgroundColour(indexTooHigh, Qt::red),
+                      std::out_of_range);
+    TSM_ASSERT_THROWS("\n\nIndex is < Min Index. Should throw\n",
+                      palette.setBackgroundColour(indexTooLow, Qt::red),
+                      std::out_of_range);
   }
 
-  void testCopy()
-  {
-    // Create an original, and modify the palette a little, so we can be sure that the copy is a genuine copy of the current state.
+  void testCopy() {
+    // Create an original, and modify the palette a little, so we can be sure
+    // that the copy is a genuine copy of the current state.
     PeakPalette<QColor> original;
     original.setForegroundColour(0, Qt::red);
     original.setBackgroundColour(0, Qt::blue);
@@ -124,20 +142,24 @@ public:
     PeakPalette<QColor> copy(original);
 
     // Check the size.
-    TSM_ASSERT_EQUALS("\n\nSize of the copy is not the same as the size of the original.\n", original.paletteSize(), copy.paletteSize());
+    TSM_ASSERT_EQUALS(
+        "\n\nSize of the copy is not the same as the size of the original.\n",
+        original.paletteSize(), copy.paletteSize());
 
     // Check all entries.
-    for(int i = 0; i < original.paletteSize(); ++i)
-    { 
-      TSM_ASSERT_EQUALS("\n\nForeground colour different between orignial and copy", original.foregroundIndexToColour(i), copy.foregroundIndexToColour(i));
-      TSM_ASSERT_EQUALS("\n\nBackground colour different between orignial and copy", original.backgroundIndexToColour(i), copy.backgroundIndexToColour(i));
+    for (int i = 0; i < original.paletteSize(); ++i) {
+      TSM_ASSERT_EQUALS(
+          "\n\nForeground colour different between orignial and copy",
+          original.foregroundIndexToColour(i), copy.foregroundIndexToColour(i));
+      TSM_ASSERT_EQUALS(
+          "\n\nBackground colour different between orignial and copy",
+          original.backgroundIndexToColour(i), copy.backgroundIndexToColour(i));
     }
-
   }
 
-  void testAssignment()
-  {
-    // Create an original, and modify the palette a little, so we can be sure that the copy is a genuine copy of the current state.
+  void testAssignment() {
+    // Create an original, and modify the palette a little, so we can be sure
+    // that the copy is a genuine copy of the current state.
     PeakPalette<QColor> A;
     A.setForegroundColour(0, Qt::red);
     A.setBackgroundColour(0, Qt::blue);
@@ -149,32 +171,38 @@ public:
     B = A;
 
     // Check the size.
-    TSM_ASSERT_EQUALS("\n\nSize of the copy is not the same as the size of the original.\n", A.paletteSize(), B.paletteSize());
+    TSM_ASSERT_EQUALS(
+        "\n\nSize of the copy is not the same as the size of the original.\n",
+        A.paletteSize(), B.paletteSize());
 
     // Check all entries.
-    for(int i = 0; i < A.paletteSize(); ++i)
-    { 
-      TSM_ASSERT_EQUALS("\n\nForeground colour different between orignial and copy.\n", B.foregroundIndexToColour(i), A.foregroundIndexToColour(i));
-      TSM_ASSERT_EQUALS("\n\nBackground colour different between orignial and copy.\n", B.backgroundIndexToColour(i), A.backgroundIndexToColour(i));
+    for (int i = 0; i < A.paletteSize(); ++i) {
+      TSM_ASSERT_EQUALS(
+          "\n\nForeground colour different between orignial and copy.\n",
+          B.foregroundIndexToColour(i), A.foregroundIndexToColour(i));
+      TSM_ASSERT_EQUALS(
+          "\n\nBackground colour different between orignial and copy.\n",
+          B.backgroundIndexToColour(i), A.backgroundIndexToColour(i));
     }
 
     TS_ASSERT_EQUALS(A, B);
 
-    // Specifically check that B has taken A's values using a couple of test cases.
-    TSM_ASSERT_EQUALS("\n\nAssignment of foreground colours has not worked.\n", B.foregroundIndexToColour(0), Qt::red);
-    TSM_ASSERT_EQUALS("\n\nAssignment of background colours has not worked.\n", B.backgroundIndexToColour(0), Qt::blue);
+    // Specifically check that B has taken A's values using a couple of test
+    // cases.
+    TSM_ASSERT_EQUALS("\n\nAssignment of foreground colours has not worked.\n",
+                      B.foregroundIndexToColour(0), Qt::red);
+    TSM_ASSERT_EQUALS("\n\nAssignment of background colours has not worked.\n",
+                      B.backgroundIndexToColour(0), Qt::blue);
   }
 
-  void test_are_equal()
-  {
+  void test_are_equal() {
     PeakPalette<QColor> A;
     PeakPalette<QColor> B;
 
     TS_ASSERT_EQUALS(A, B);
   }
 
-  void test_are_not_equal_after_changing_a_foreground_colour()
-  {
+  void test_are_not_equal_after_changing_a_foreground_colour() {
     PeakPalette<QColor> A;
     PeakPalette<QColor> B;
 
@@ -184,16 +212,17 @@ public:
     A.setForegroundColour(modifyIndex, Qt::blue);
     B.setForegroundColour(modifyIndex, Qt::red);
 
-    TSM_ASSERT_DIFFERS("Foreground colours are not equal, these palettes should not be equal.", A, B);
+    TSM_ASSERT_DIFFERS(
+        "Foreground colours are not equal, these palettes should not be equal.",
+        A, B);
 
-    //For completeness, reset and check they are the same.
+    // For completeness, reset and check they are the same.
     A.setForegroundColour(modifyIndex, originalColourAtIndex);
     B.setForegroundColour(modifyIndex, originalColourAtIndex);
     TS_ASSERT_EQUALS(A, B);
   }
 
-  void test_not_not_equal_after_changing_a_backgroundcolour()
-  {
+  void test_not_not_equal_after_changing_a_backgroundcolour() {
     PeakPalette<QColor> A;
     PeakPalette<QColor> B;
 
@@ -203,17 +232,19 @@ public:
     A.setBackgroundColour(modifyIndex, Qt::blue);
     B.setBackgroundColour(modifyIndex, Qt::red);
 
-    TSM_ASSERT_DIFFERS("Background colours are not equal, these palettes should not be equal.", A, B);
+    TSM_ASSERT_DIFFERS(
+        "Background colours are not equal, these palettes should not be equal.",
+        A, B);
 
-    //For completeness, reset and check they are the same.
+    // For completeness, reset and check they are the same.
     A.setBackgroundColour(modifyIndex, originalColourAtIndex);
     B.setBackgroundColour(modifyIndex, originalColourAtIndex);
     TS_ASSERT_EQUALS(A, B);
   }
 
-
   // ----- Tests for PeakViewColor
-  void test_that_peak_view_color_specialization_produces_output_with_three_colors() {
+  void
+  test_that_peak_view_color_specialization_produces_output_with_three_colors() {
     // Arrange
     PeakPalette<PeakViewColor> palette;
 
@@ -223,8 +254,12 @@ public:
     PeakViewColor foregroundColor;
     PeakViewColor backgroundColor;
 
-    TSM_ASSERT_THROWS_NOTHING("Should happily create the foreground color", foregroundColor = palette.foregroundIndexToColour(index));
-    TSM_ASSERT_THROWS_NOTHING("Should happily create the background color", backgroundColor = palette.backgroundIndexToColour(index));
+    TSM_ASSERT_THROWS_NOTHING("Should happily create the foreground color",
+                              foregroundColor =
+                                  palette.foregroundIndexToColour(index));
+    TSM_ASSERT_THROWS_NOTHING("Should happily create the background color",
+                              backgroundColor =
+                                  palette.backgroundIndexToColour(index));
   }
 };
 
diff --git a/MantidQt/SliceViewer/test/PeakRepresentationCrossTest.h b/MantidQt/SliceViewer/test/PeakRepresentationCrossTest.h
index ae0ad378abbed9ddbe5d257841176194b39caf2f..3f483b2e8f77e728c6f83cceb9b462e1a2e52897 100644
--- a/MantidQt/SliceViewer/test/PeakRepresentationCrossTest.h
+++ b/MantidQt/SliceViewer/test/PeakRepresentationCrossTest.h
@@ -8,292 +8,270 @@
 using namespace MantidQt::SliceViewer;
 using namespace testing;
 
-
 class PeakRepresentationCrossExposeProtectedWrapper
-    : public PeakRepresentationCross
-{
+    : public PeakRepresentationCross {
 public:
-    PeakRepresentationCrossExposeProtectedWrapper(
-        const Mantid::Kernel::V3D &origin, const double &maxZ,
-        const double &minZ)
-        : PeakRepresentationCross(origin, maxZ, minZ)
-    {
-    }
+  PeakRepresentationCrossExposeProtectedWrapper(
+      const Mantid::Kernel::V3D &origin, const double &maxZ, const double &minZ)
+      : PeakRepresentationCross(origin, maxZ, minZ) {}
 
-    double getOccupancyInView() { return m_crossViewFraction; }
+  double getOccupancyInView() { return m_crossViewFraction; }
 
-    double getOccupancyIntoView() { return m_intoViewFraction; }
+  double getOccupancyIntoView() { return m_intoViewFraction; }
 
-    std::shared_ptr<PeakPrimitives> getDrawingInformationFromWrapper(
-        PeakRepresentationViewInformation viewInformation)
-    {
-        return this->getDrawingInformation(viewInformation);
-    }
+  std::shared_ptr<PeakPrimitives> getDrawingInformationFromWrapper(
+      PeakRepresentationViewInformation viewInformation) {
+    return this->getDrawingInformation(viewInformation);
+  }
 };
 
-class PeakRepresentationCrossTest : public CxxTest::TestSuite
-{
+class PeakRepresentationCrossTest : public CxxTest::TestSuite {
 public:
-    void test_movePosition_moves_the_peak()
-    {
-
-        // Arrange
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCross peak(origin, maxZ, minZ);
-
-        /* Provide a mocked transform */
-        MockPeakTransform *mockTransform = new MockPeakTransform;
-        EXPECT_CALL(*mockTransform, transform(_))
-            .Times(1)
-            .WillOnce(Return(Mantid::Kernel::V3D(0, 0, 0)));
-        PeakTransform_sptr transform(mockTransform);
-
-        // Act
-        peak.movePosition(transform);
-
-        // Assert
-        TS_ASSERT(Mock::VerifyAndClearExpectations(mockTransform));
-    }
-
-    void test_getBoundingBox_gets_correct_box_without_offset_from_origin()
-    {
-        // Arrange
-
-        /*
-        width = height = effectiveradius * 2
-        |---------------|
-        |               |
-        |               |
-        |     (0,0)     |
-        |               |
-        |               |
-        |----------------
-        */
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCross peak(origin, maxZ, minZ);
-
-        // Act
-        auto boundingBox = peak.getBoundingBox();
-
-        // Assert
-        // Pre-calculate the effective radius.
-        const double effectiveRadius = 0.015 * (maxZ - minZ);
-        const double expectedLeft(origin.X() - effectiveRadius);
-        const double expectedBottom(origin.Y() - effectiveRadius);
-        const double expectedRight(origin.X() + effectiveRadius);
-        const double expectedTop(origin.Y() + effectiveRadius);
-
-        TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
-        TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
-        TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
-        TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
-    }
-
-    void test_getBoundingBox_gets_correct_box_with_offset_from_origin()
-    {
-        // Arrange
-        /*
-
-        width = height = effectiveradius * 2
-        |---------------|
-        |               |
-        |               |
-        |     (-1,1)    |
-        |               |
-        |               |
-        |---------------|
-
-        */
-
-        Mantid::Kernel::V3D origin(-1, 1, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCross peak(origin, maxZ, minZ);
-
-        // Act
-        auto boundingBox = peak.getBoundingBox();
-
-        // Assert
-        // Pre-calculate the effective radius.
-        const double effectiveRadius = 0.015 * (maxZ - minZ);
-        const double expectedLeft(origin.X() - effectiveRadius);
-        const double expectedBottom(origin.Y() - effectiveRadius);
-        const double expectedRight(origin.X() + effectiveRadius);
-        const double expectedTop(origin.Y() + effectiveRadius);
-
-        TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
-        TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
-        TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
-        TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
-    }
-
-    void test_expand_peak_intoplane()
-    {
-        // Arrange
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
-
-        const double newEffectiveRadiusFactor = 0.2;
-        const double effectiveRadius = newEffectiveRadiusFactor * (maxZ - minZ);
-
-        // Act
-        peak.setOccupancyIntoView(newEffectiveRadiusFactor);
-        auto updatedOccupancyIntoView = peak.getOccupancyIntoView();
-        auto updatedEffectiveRadius = peak.getEffectiveRadius();
-
-        // Assert
-        TS_ASSERT_EQUALS(newEffectiveRadiusFactor, updatedOccupancyIntoView);
-        TS_ASSERT_EQUALS(effectiveRadius, updatedEffectiveRadius);
-    }
-
-    void test_expand_peak_inplane()
-    {
-        // Arrange
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
-
-        const double occupancyFraction = 0.01; // 1%
-
-        // Act
-        peak.setOccupancyInView(occupancyFraction); // 1 %
-        auto updatedOccupancyInView = peak.getOccupancyInView();
+  void test_movePosition_moves_the_peak() {
+
+    // Arrange
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCross peak(origin, maxZ, minZ);
+
+    /* Provide a mocked transform */
+    MockPeakTransform *mockTransform = new MockPeakTransform;
+    EXPECT_CALL(*mockTransform, transform(_))
+        .Times(1)
+        .WillOnce(Return(Mantid::Kernel::V3D(0, 0, 0)));
+    PeakTransform_sptr transform(mockTransform);
+
+    // Act
+    peak.movePosition(transform);
+
+    // Assert
+    TS_ASSERT(Mock::VerifyAndClearExpectations(mockTransform));
+  }
+
+  void test_getBoundingBox_gets_correct_box_without_offset_from_origin() {
+    // Arrange
+
+    /*
+    width = height = effectiveradius * 2
+    |---------------|
+    |               |
+    |               |
+    |     (0,0)     |
+    |               |
+    |               |
+    |----------------
+    */
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCross peak(origin, maxZ, minZ);
+
+    // Act
+    auto boundingBox = peak.getBoundingBox();
+
+    // Assert
+    // Pre-calculate the effective radius.
+    const double effectiveRadius = 0.015 * (maxZ - minZ);
+    const double expectedLeft(origin.X() - effectiveRadius);
+    const double expectedBottom(origin.Y() - effectiveRadius);
+    const double expectedRight(origin.X() + effectiveRadius);
+    const double expectedTop(origin.Y() + effectiveRadius);
+
+    TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
+    TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
+    TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
+    TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
+  }
+
+  void test_getBoundingBox_gets_correct_box_with_offset_from_origin() {
+    // Arrange
+    /*
+
+    width = height = effectiveradius * 2
+    |---------------|
+    |               |
+    |               |
+    |     (-1,1)    |
+    |               |
+    |               |
+    |---------------|
 
-        // Assert
-        TS_ASSERT_EQUALS(occupancyFraction, updatedOccupancyInView);
-    }
+    */
 
-    void test_setOccupanyIntoView_ignores_zeros()
-    {
-        // Act
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double maxZ = 1;
-        const double minZ = 0;
-        PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
-
-        // Act
-        double defaultOccupancy = peak.getOccupancyIntoView();
-        peak.setOccupancyIntoView(0);
-
-        // Assert
-        TSM_ASSERT_DIFFERS("Should have ignored the zero value input", 0,
-                           peak.getOccupancyIntoView());
-        TS_ASSERT_EQUALS(defaultOccupancy, peak.getOccupancyIntoView());
-    }
+    Mantid::Kernel::V3D origin(-1, 1, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCross peak(origin, maxZ, minZ);
+
+    // Act
+    auto boundingBox = peak.getBoundingBox();
+
+    // Assert
+    // Pre-calculate the effective radius.
+    const double effectiveRadius = 0.015 * (maxZ - minZ);
+    const double expectedLeft(origin.X() - effectiveRadius);
+    const double expectedBottom(origin.Y() - effectiveRadius);
+    const double expectedRight(origin.X() + effectiveRadius);
+    const double expectedTop(origin.Y() + effectiveRadius);
+
+    TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
+    TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
+    TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
+    TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
+  }
+
+  void test_expand_peak_intoplane() {
+    // Arrange
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
+
+    const double newEffectiveRadiusFactor = 0.2;
+    const double effectiveRadius = newEffectiveRadiusFactor * (maxZ - minZ);
+
+    // Act
+    peak.setOccupancyIntoView(newEffectiveRadiusFactor);
+    auto updatedOccupancyIntoView = peak.getOccupancyIntoView();
+    auto updatedEffectiveRadius = peak.getEffectiveRadius();
+
+    // Assert
+    TS_ASSERT_EQUALS(newEffectiveRadiusFactor, updatedOccupancyIntoView);
+    TS_ASSERT_EQUALS(effectiveRadius, updatedEffectiveRadius);
+  }
+
+  void test_expand_peak_inplane() {
+    // Arrange
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
+
+    const double occupancyFraction = 0.01; // 1%
+
+    // Act
+    peak.setOccupancyInView(occupancyFraction); // 1 %
+    auto updatedOccupancyInView = peak.getOccupancyInView();
+
+    // Assert
+    TS_ASSERT_EQUALS(occupancyFraction, updatedOccupancyInView);
+  }
+
+  void test_setOccupanyIntoView_ignores_zeros() {
+    // Act
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double maxZ = 1;
+    const double minZ = 0;
+    PeakRepresentationCrossExposeProtectedWrapper peak(origin, maxZ, minZ);
+
+    // Act
+    double defaultOccupancy = peak.getOccupancyIntoView();
+    peak.setOccupancyIntoView(0);
+
+    // Assert
+    TSM_ASSERT_DIFFERS("Should have ignored the zero value input", 0,
+                       peak.getOccupancyIntoView());
+    TS_ASSERT_EQUALS(defaultOccupancy, peak.getOccupancyIntoView());
+  }
 };
 
 //---------------------------------------------------------------------
 // Performance Test
 //---------------------------------------------------------------------
 
-class PeakRepresentationCrossTestPerformance : public CxxTest::TestSuite
-{
+class PeakRepresentationCrossTestPerformance : public CxxTest::TestSuite {
 private:
-    typedef std::vector<boost::shared_ptr<PeakRepresentationCross>>
-        VecPeakRepCross;
+  typedef std::vector<boost::shared_ptr<PeakRepresentationCross>>
+      VecPeakRepCross;
 
-    typedef std::
-        vector<boost::shared_ptr<PeakRepresentationCrossExposeProtectedWrapper>>
-            VecPeakRepCrossWrapped;
+  typedef std::vector<boost::shared_ptr<
+      PeakRepresentationCrossExposeProtectedWrapper>> VecPeakRepCrossWrapped;
 
-    /// Collection to store a large number of PeakRepresentationCross.
-    VecPeakRepCross m_peaks;
+  /// Collection to store a large number of PeakRepresentationCross.
+  VecPeakRepCross m_peaks;
 
-    /// Collection to store a large number of
-    /// PeakRepresentationCrossProtectedWrapper.
-    VecPeakRepCrossWrapped m_peaksWrapped;
+  /// Collection to store a large number of
+  /// PeakRepresentationCrossProtectedWrapper.
+  VecPeakRepCrossWrapped m_peaksWrapped;
 
 public:
-    /**
-    Here we create a distribution of Peaks. Peaks are dispersed. This is to give
-    a measurable peformance.
-    */
-    PeakRepresentationCrossTestPerformance()
-    {
-        const int sizeInAxis = 100;
-        const double maxZ = 100;
-        const double minZ = 0;
-        m_peaks.reserve(sizeInAxis * sizeInAxis * sizeInAxis);
-        for (int x = 0; x < sizeInAxis; ++x) {
-            for (int y = 0; y < sizeInAxis; ++y) {
-                for (int z = 0; z < sizeInAxis; ++z) {
-                    Mantid::Kernel::V3D peakOrigin(x, y, z);
-                    m_peaks.push_back(
-                        boost::make_shared<MantidQt::SliceViewer::
-                                               PeakRepresentationCross>(
-                            peakOrigin, maxZ, minZ));
-                }
-            }
+  /**
+  Here we create a distribution of Peaks. Peaks are dispersed. This is to give
+  a measurable peformance.
+  */
+  PeakRepresentationCrossTestPerformance() {
+    const int sizeInAxis = 100;
+    const double maxZ = 100;
+    const double minZ = 0;
+    m_peaks.reserve(sizeInAxis * sizeInAxis * sizeInAxis);
+    for (int x = 0; x < sizeInAxis; ++x) {
+      for (int y = 0; y < sizeInAxis; ++y) {
+        for (int z = 0; z < sizeInAxis; ++z) {
+          Mantid::Kernel::V3D peakOrigin(x, y, z);
+          m_peaks.push_back(boost::make_shared<
+              MantidQt::SliceViewer::PeakRepresentationCross>(peakOrigin, maxZ,
+                                                              minZ));
         }
+      }
     }
-
-    /// Test the performance of just setting the slice point.
-    void test_setSlicePoint_performance()
-    {
-        for (double z = 0; z < 100; z += 5) {
-            VecPeakRepCross::iterator it = m_peaks.begin();
-            while (it != m_peaks.end()) {
-                (*it)->setSlicePoint(z);
-                ++it;
-            }
-        }
+  }
+
+  /// Test the performance of just setting the slice point.
+  void test_setSlicePoint_performance() {
+    for (double z = 0; z < 100; z += 5) {
+      VecPeakRepCross::iterator it = m_peaks.begin();
+      while (it != m_peaks.end()) {
+        (*it)->setSlicePoint(z);
+        ++it;
+      }
     }
-
-    /// Test the performance of just drawing.
-    void test_draw_performance()
-    {
-        const int nTimesRedrawAll = 20;
-        int timesDrawn = 0;
-
-        // View Settings Scale 1:1 on both x and y for simplicity.
-        MantidQt::SliceViewer::PeakRepresentationViewInformation
-            viewInformation;
-        viewInformation.viewHeight = 1.0;
-        viewInformation.viewWidth = 1.0;
-        viewInformation.windowHeight = 1.0;
-        viewInformation.windowWidth = 1.0;
-        viewInformation.xOriginWindow = 1;
-        viewInformation.yOriginWindow = 1;
-
-        while (timesDrawn < nTimesRedrawAll) {
-            auto it = m_peaksWrapped.begin();
-            while (it != m_peaksWrapped.end()) {
-                (*it)->getDrawingInformationFromWrapper(viewInformation);
-                ++it;
-            }
-            ++timesDrawn;
-        }
+  }
+
+  /// Test the performance of just drawing.
+  void test_draw_performance() {
+    const int nTimesRedrawAll = 20;
+    int timesDrawn = 0;
+
+    // View Settings Scale 1:1 on both x and y for simplicity.
+    MantidQt::SliceViewer::PeakRepresentationViewInformation viewInformation;
+    viewInformation.viewHeight = 1.0;
+    viewInformation.viewWidth = 1.0;
+    viewInformation.windowHeight = 1.0;
+    viewInformation.windowWidth = 1.0;
+    viewInformation.xOriginWindow = 1;
+    viewInformation.yOriginWindow = 1;
+
+    while (timesDrawn < nTimesRedrawAll) {
+      auto it = m_peaksWrapped.begin();
+      while (it != m_peaksWrapped.end()) {
+        (*it)->getDrawingInformationFromWrapper(viewInformation);
+        ++it;
+      }
+      ++timesDrawn;
     }
-
-    /// Test the performance of both setting the slice point and drawing..
-    void test_whole_performance()
-    {
-        const double z = 10;
-
-        // View Settings Scale 1:1 on both x and y for simplicity.
-        MantidQt::SliceViewer::PeakRepresentationViewInformation
-            viewInformation;
-        viewInformation.viewHeight = 1.0;
-        viewInformation.viewWidth = 1.0;
-        viewInformation.windowHeight = 1.0;
-        viewInformation.windowWidth = 1.0;
-        viewInformation.xOriginWindow = 1;
-        viewInformation.yOriginWindow = 1;
-
-        auto it = m_peaksWrapped.begin();
-        while (it != m_peaksWrapped.end()) {
-            (*it)->setSlicePoint(z);
-            (*it)->getDrawingInformationFromWrapper(viewInformation);
-            ++it;
-        }
+  }
+
+  /// Test the performance of both setting the slice point and drawing..
+  void test_whole_performance() {
+    const double z = 10;
+
+    // View Settings Scale 1:1 on both x and y for simplicity.
+    MantidQt::SliceViewer::PeakRepresentationViewInformation viewInformation;
+    viewInformation.viewHeight = 1.0;
+    viewInformation.viewWidth = 1.0;
+    viewInformation.windowHeight = 1.0;
+    viewInformation.windowWidth = 1.0;
+    viewInformation.xOriginWindow = 1;
+    viewInformation.yOriginWindow = 1;
+
+    auto it = m_peaksWrapped.begin();
+    while (it != m_peaksWrapped.end()) {
+      (*it)->setSlicePoint(z);
+      (*it)->getDrawingInformationFromWrapper(viewInformation);
+      ++it;
     }
+  }
 };
 
 #endif
diff --git a/MantidQt/SliceViewer/test/PeakRepresentationEllipsoidTest.h b/MantidQt/SliceViewer/test/PeakRepresentationEllipsoidTest.h
index ea1f3e445267db92d236f016891032abb3716a98..c95cc5318561bcbc57fb8e92ab85e2937cf779f7 100644
--- a/MantidQt/SliceViewer/test/PeakRepresentationEllipsoidTest.h
+++ b/MantidQt/SliceViewer/test/PeakRepresentationEllipsoidTest.h
@@ -8,19 +8,18 @@
 using namespace MantidQt::SliceViewer;
 using namespace testing;
 
-
-
 namespace {
-  // Check if the two angles are the same, note that angles which are shifted by 180 degrees
-  // are the same for an ellipsoid, ie one is free to have the major axis point in the
-  // + or - direction
-  bool isAngleEitherValueOr180DegreesRoated(double expectedAngle,
-                                            double actualAngle)
-  {
-      return Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle)
-             || Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle + M_PI)
-             || Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle - M_PI);
-  }
+// Check if the two angles are the same, note that angles which are shifted by
+// 180 degrees
+// are the same for an ellipsoid, ie one is free to have the major axis point in
+// the
+// + or - direction
+bool isAngleEitherValueOr180DegreesRoated(double expectedAngle,
+                                          double actualAngle) {
+  return Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle) ||
+         Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle + M_PI) ||
+         Mantid::SliceViewer::almost_equal(expectedAngle, actualAngle - M_PI);
+}
 }
 
 class PeakRepresentationEllipsoidExposeProtectedWrapper
@@ -109,8 +108,9 @@ public:
     const double expectedAngle = angle;
     TS_ASSERT_DELTA(expectedOpacityAtDistance,
                     drawingInformationEllipse->peakOpacityAtDistance, delta);
-    TSM_ASSERT("Should have an angle of 35.", isAngleEitherValueOr180DegreesRoated(expectedAngle,
-                     drawingInformationEllipse->angle));
+    TSM_ASSERT("Should have an angle of 35.",
+               isAngleEitherValueOr180DegreesRoated(
+                   expectedAngle, drawingInformationEllipse->angle));
   }
 
   void test_getBoundingBox() {
diff --git a/MantidQt/SliceViewer/test/PeakRepresentationSphereTest.h b/MantidQt/SliceViewer/test/PeakRepresentationSphereTest.h
index f9d1ae2c2085ed345ef3407323c603730e093003..559868fe11d77bd13410015b86860f325e997b6e 100644
--- a/MantidQt/SliceViewer/test/PeakRepresentationSphereTest.h
+++ b/MantidQt/SliceViewer/test/PeakRepresentationSphereTest.h
@@ -5,339 +5,315 @@
 #include "MantidQtSliceViewer/PeakRepresentationSphere.h"
 #include "MockObjects.h"
 
-
 using namespace MantidQt::SliceViewer;
 using namespace testing;
 
 class PeakRepresentationSphereExposeProtectedWrapper
-    : public PeakRepresentationSphere
-{
+    : public PeakRepresentationSphere {
 public:
-    PeakRepresentationSphereExposeProtectedWrapper(
-        const Mantid::Kernel::V3D &origin, const double &peakRadius,
-        const double &backgroundInnerRadius,
-        const double &backgroundOuterRadius)
-        : PeakRepresentationSphere(origin, peakRadius, backgroundInnerRadius,
-                                   backgroundOuterRadius)
-    {
-    }
-    std::shared_ptr<PeakPrimitives>
-    getDrawingInformationWrapper(
-        PeakRepresentationViewInformation viewInformation)
-    {
-        return getDrawingInformation(viewInformation);
-    }
+  PeakRepresentationSphereExposeProtectedWrapper(
+      const Mantid::Kernel::V3D &origin, const double &peakRadius,
+      const double &backgroundInnerRadius, const double &backgroundOuterRadius)
+      : PeakRepresentationSphere(origin, peakRadius, backgroundInnerRadius,
+                                 backgroundOuterRadius) {}
+  std::shared_ptr<PeakPrimitives> getDrawingInformationWrapper(
+      PeakRepresentationViewInformation viewInformation) {
+    return getDrawingInformation(viewInformation);
+  }
 };
 
-class PeakRepresentationSphereTest : public CxxTest::TestSuite
-{
+class PeakRepresentationSphereTest : public CxxTest::TestSuite {
 public:
-    void test_getRadius_gets_radius_if_background_is_not_shown()
-    {
-        // Arrange
-        Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;
-        const double innerBackgroundRadius = 2;
-        const double outerBackgroundRadius = 3;
-        PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
-                                      outerBackgroundRadius);
-
-        // Act + Assert
-        TSM_ASSERT(radius, peak.getEffectiveRadius());
-
-    }
-
-    void test_getRadius_gets_outer_background_radius_if_background_is_shown()
-    {
-        // Arrange
-        const Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;
-        const double innerBackgroundRadius = 2;
-        const double outerBackgroundRadius = 3;
-        PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
-                                      outerBackgroundRadius);
-
-        peak.showBackgroundRadius(true);
+  void test_getRadius_gets_radius_if_background_is_not_shown() {
+    // Arrange
+    Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;
+    const double innerBackgroundRadius = 2;
+    const double outerBackgroundRadius = 3;
+    PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
+                                  outerBackgroundRadius);
+
+    // Act + Assert
+    TSM_ASSERT(radius, peak.getEffectiveRadius());
+  }
+
+  void test_getRadius_gets_outer_background_radius_if_background_is_shown() {
+    // Arrange
+    const Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;
+    const double innerBackgroundRadius = 2;
+    const double outerBackgroundRadius = 3;
+    PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
+                                  outerBackgroundRadius);
+
+    peak.showBackgroundRadius(true);
+
+    // Act + Assert
+    TSM_ASSERT(outerBackgroundRadius, peak.getEffectiveRadius());
+  }
+
+  void test_handle_outer_background_radius_zero() {
+    // Arrange
+    const Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;
+    const double innerBackgroundRadius = 2;
+    const double outerBackgroundRadius =
+        0; // This can happen using IntegratePeaksMD.
+    PeakRepresentationSphereExposeProtectedWrapper peak(
+        origin, radius, innerBackgroundRadius, outerBackgroundRadius);
+
+    peak.showBackgroundRadius(true);
+
+    const double slicePoint = innerBackgroundRadius;
+    peak.setSlicePoint(slicePoint);
+
+    // View Settings Scale 1:1 on both x and y for simplicity.
+    PeakRepresentationViewInformation viewInformation;
+    viewInformation.viewHeight = 1.0;
+    viewInformation.viewWidth = 1.0;
+    viewInformation.windowHeight = 1.0;
+    viewInformation.windowWidth = 1.0;
+    viewInformation.xOriginWindow = 1;
+    viewInformation.yOriginWindow = 1;
+
+    // Act
+    auto drawingInformation =
+        peak.getDrawingInformationWrapper(viewInformation);
+
+    // Assert
+    auto drawingInformationSphere =
+        std::static_pointer_cast<PeakPrimitiveCircle>(drawingInformation);
+    // The Return object should be initialized to zero in every field.
+    TS_ASSERT_EQUALS(drawingInformationSphere->backgroundOuterRadiusX,
+                     drawingInformationSphere->backgroundInnerRadiusX);
+    TS_ASSERT_EQUALS(drawingInformationSphere->backgroundOuterRadiusY,
+                     drawingInformationSphere->backgroundInnerRadiusY);
+  }
+
+  void
+  test_that_setting_slice_point_to_intersect_produces_valid_drawing_information() {
+    // Arrange
+    const Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;
+    const double innerBackgroundRadius = 2;
+    const double outerBackgroundRadius = 3;
+    PeakRepresentationSphereExposeProtectedWrapper peak(
+        origin, radius, innerBackgroundRadius, outerBackgroundRadius);
+
+    const double slicePoint =
+        radius / 2; // set to be half way through the radius.
+    peak.setSlicePoint(slicePoint);
+
+    // View Settings Scale 1:1 on both x and y for simplicity.
+    PeakRepresentationViewInformation viewInformation;
+    viewInformation.viewHeight = 1.0;
+    viewInformation.viewWidth = 1.0;
+    viewInformation.windowHeight = 1.0;
+    viewInformation.windowWidth = 1.0;
+    viewInformation.xOriginWindow = 1;
+    viewInformation.yOriginWindow = 1;
+
+    // Act
+    auto drawingInformation =
+        peak.getDrawingInformationWrapper(viewInformation);
+
+    // Assert
+    auto drawingInformationSphere =
+        std::static_pointer_cast<PeakPrimitiveCircle>(drawingInformation);
+
+    // Quick white-box calculations of the outputs to expect.
+    const double expectedOpacityAtDistance = (0.8 - 0) / 2;
+    auto peakRadSQ = std::pow(radius, 2);
+    auto planeDistanceSQ = std::pow((slicePoint - origin.Z()), 2);
+    const double expectedRadius = std::sqrt(peakRadSQ - planeDistanceSQ);
+
+    TS_ASSERT_EQUALS(expectedOpacityAtDistance,
+                     drawingInformationSphere->peakOpacityAtDistance);
+    TS_ASSERT_EQUALS(expectedRadius,
+                     drawingInformationSphere->peakInnerRadiusX);
+    TS_ASSERT_EQUALS(expectedRadius,
+                     drawingInformationSphere->peakInnerRadiusY);
+  }
+
+  void test_move_position_produces_correct_position() {
+    // Arrange
+    MockPeakTransform *pMockTransform = new MockPeakTransform;
+    EXPECT_CALL(*pMockTransform, transform(_))
+        .Times(1)
+        .WillOnce(Return(Mantid::Kernel::V3D(0, 0, 0)));
+    PeakTransform_sptr transform(pMockTransform);
+
+    const Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;
+    const double innerBackgroundRadius = 2;
+    const double outerBackgroundRadius = 3;
+    PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
+                                  outerBackgroundRadius);
+
+    // Act
+    peak.movePosition(transform);
+
+    // Assert
+    TS_ASSERT(Mock::VerifyAndClearExpectations(pMockTransform));
+  }
+
+  void test_getBoundingBox() {
+    /*
+
+    width = height = outerradius * 2
+    |---------------|
+    |               |
+    |               |
+    |     (0,0)     |
+    |               |
+    |               |
+    |---------------|
 
-        // Act + Assert
-        TSM_ASSERT(outerBackgroundRadius, peak.getEffectiveRadius());
-    }
-
-    void test_handle_outer_background_radius_zero()
-    {
-        // Arrange
-        const Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;
-        const double innerBackgroundRadius = 2;
-        const double outerBackgroundRadius
-            = 0; // This can happen using IntegratePeaksMD.
-        PeakRepresentationSphereExposeProtectedWrapper peak(
-            origin, radius, innerBackgroundRadius, outerBackgroundRadius);
-
-        peak.showBackgroundRadius(true);
-
-        const double slicePoint = innerBackgroundRadius;
-        peak.setSlicePoint(slicePoint);
-
-        // View Settings Scale 1:1 on both x and y for simplicity.
-        PeakRepresentationViewInformation viewInformation;
-        viewInformation.viewHeight = 1.0;
-        viewInformation.viewWidth = 1.0;
-        viewInformation.windowHeight = 1.0;
-        viewInformation.windowWidth = 1.0;
-        viewInformation.xOriginWindow = 1;
-        viewInformation.yOriginWindow = 1;
-
-        // Act
-        auto drawingInformation
-            = peak.getDrawingInformationWrapper(viewInformation);
-
-        // Assert
-        auto drawingInformationSphere
-            = std::static_pointer_cast<PeakPrimitiveCircle>(
-                drawingInformation);
-        // The Return object should be initialized to zero in every field.
-        TS_ASSERT_EQUALS(drawingInformationSphere->backgroundOuterRadiusX,
-                         drawingInformationSphere->backgroundInnerRadiusX);
-        TS_ASSERT_EQUALS(drawingInformationSphere->backgroundOuterRadiusY,
-                         drawingInformationSphere->backgroundInnerRadiusY);
-    }
-
-    void
-    test_that_setting_slice_point_to_intersect_produces_valid_drawing_information()
-    {
-        // Arrange
-        const Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;
-        const double innerBackgroundRadius = 2;
-        const double outerBackgroundRadius = 3;
-        PeakRepresentationSphereExposeProtectedWrapper peak(
-            origin, radius, innerBackgroundRadius, outerBackgroundRadius);
-
-        const double slicePoint = radius
-                                  / 2; // set to be half way through the radius.
-        peak.setSlicePoint(slicePoint);
-
-        // View Settings Scale 1:1 on both x and y for simplicity.
-        PeakRepresentationViewInformation viewInformation;
-        viewInformation.viewHeight = 1.0;
-        viewInformation.viewWidth = 1.0;
-        viewInformation.windowHeight = 1.0;
-        viewInformation.windowWidth = 1.0;
-        viewInformation.xOriginWindow = 1;
-        viewInformation.yOriginWindow = 1;
-
-        // Act
-        auto drawingInformation
-            = peak.getDrawingInformationWrapper(viewInformation);
-
-        // Assert
-        auto drawingInformationSphere
-            = std::static_pointer_cast<PeakPrimitiveCircle>(
-                drawingInformation);
-
-        // Quick white-box calculations of the outputs to expect.
-        const double expectedOpacityAtDistance = (0.8 - 0) / 2;
-        auto peakRadSQ = std::pow(radius, 2);
-        auto planeDistanceSQ = std::pow((slicePoint - origin.Z()), 2);
-        const double expectedRadius = std::sqrt(peakRadSQ - planeDistanceSQ);
-
-        TS_ASSERT_EQUALS(expectedOpacityAtDistance,
-                         drawingInformationSphere->peakOpacityAtDistance);
-        TS_ASSERT_EQUALS(expectedRadius,
-                         drawingInformationSphere->peakInnerRadiusX);
-        TS_ASSERT_EQUALS(expectedRadius,
-                         drawingInformationSphere->peakInnerRadiusY);
-    }
-
-    void test_move_position_produces_correct_position()
-    {
-        // Arrange
-        MockPeakTransform *pMockTransform = new MockPeakTransform;
-        EXPECT_CALL(*pMockTransform, transform(_))
-            .Times(1)
-            .WillOnce(Return(Mantid::Kernel::V3D(0, 0, 0)));
-        PeakTransform_sptr transform(pMockTransform);
-
-        const Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;
-        const double innerBackgroundRadius = 2;
-        const double outerBackgroundRadius = 3;
-        PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
-                                      outerBackgroundRadius);
-
-        // Act
-        peak.movePosition(transform);
-
-        // Assert
-        TS_ASSERT(Mock::VerifyAndClearExpectations(pMockTransform));
-    }
-
-    void test_getBoundingBox()
-    {
-        /*
-
-        width = height = outerradius * 2
-        |---------------|
-        |               |
-        |               |
-        |     (0,0)     |
-        |               |
-        |               |
-        |---------------|
-
-        */
-        // Arrrange
-        const Mantid::Kernel::V3D origin(0, 0, 0);
-        const double radius = 1;                // Not important
-        const double innerBackgroundRadius = 2; // Not important
-        const double outerBackgroundRadius
-            = 3; // This should be used to control the bounding box.
-        PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
-                                      outerBackgroundRadius);
-
-        // Act
-        const auto boundingBox = peak.getBoundingBox();
-
-        // Assert
-        const double expectedLeft(origin.X() - outerBackgroundRadius);
-        const double expectedBottom(origin.Y() - outerBackgroundRadius);
-        const double expectedRight(origin.X() + outerBackgroundRadius);
-        const double expectedTop(origin.Y() + outerBackgroundRadius);
-
-        TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
-        TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
-        TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
-        TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
-    }
+    */
+    // Arrrange
+    const Mantid::Kernel::V3D origin(0, 0, 0);
+    const double radius = 1;                // Not important
+    const double innerBackgroundRadius = 2; // Not important
+    const double outerBackgroundRadius =
+        3; // This should be used to control the bounding box.
+    PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
+                                  outerBackgroundRadius);
+
+    // Act
+    const auto boundingBox = peak.getBoundingBox();
+
+    // Assert
+    const double expectedLeft(origin.X() - outerBackgroundRadius);
+    const double expectedBottom(origin.Y() - outerBackgroundRadius);
+    const double expectedRight(origin.X() + outerBackgroundRadius);
+    const double expectedTop(origin.Y() + outerBackgroundRadius);
+
+    TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
+    TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
+    TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
+    TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
+  }
+
+  void test_getBoundingBox_with_offset_origin() {
+    /*
+
+    width = height = outerradius * 2
+    |---------------|
+    |               |
+    |               |
+    |     (-1,1)    |
+    |               |
+    |               |
+    |---------------|
 
-    void test_getBoundingBox_with_offset_origin()
-    {
-        /*
-
-        width = height = outerradius * 2
-        |---------------|
-        |               |
-        |               |
-        |     (-1,1)    |
-        |               |
-        |               |
-        |---------------|
-
-        */
-        // Arrange
-        const Mantid::Kernel::V3D origin(-1, 1,
-                                         0);    // Offset origin from (0, 0, 0)
-        const double radius = 1;                // Not important
-        const double innerBackgroundRadius = 2; // Not important
-        const double outerBackgroundRadius
-            = 3; // This should be used to control the bounding box.
-        PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
-                                      outerBackgroundRadius);
-
-        // Act
-        auto boundingBox = peak.getBoundingBox();
-
-        // Assert
-        const double expectedLeft(origin.X() - outerBackgroundRadius);
-        const double expectedBottom(origin.Y() - outerBackgroundRadius);
-        const double expectedRight(origin.X() + outerBackgroundRadius);
-        const double expectedTop(origin.Y() + outerBackgroundRadius);
-
-        TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
-        TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
-        TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
-        TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
-    }
+    */
+    // Arrange
+    const Mantid::Kernel::V3D origin(-1, 1, 0); // Offset origin from (0, 0, 0)
+    const double radius = 1;                    // Not important
+    const double innerBackgroundRadius = 2;     // Not important
+    const double outerBackgroundRadius =
+        3; // This should be used to control the bounding box.
+    PeakRepresentationSphere peak(origin, radius, innerBackgroundRadius,
+                                  outerBackgroundRadius);
+
+    // Act
+    auto boundingBox = peak.getBoundingBox();
+
+    // Assert
+    const double expectedLeft(origin.X() - outerBackgroundRadius);
+    const double expectedBottom(origin.Y() - outerBackgroundRadius);
+    const double expectedRight(origin.X() + outerBackgroundRadius);
+    const double expectedTop(origin.Y() + outerBackgroundRadius);
+
+    TS_ASSERT_EQUALS(expectedLeft, boundingBox.left());
+    TS_ASSERT_EQUALS(expectedRight, boundingBox.right());
+    TS_ASSERT_EQUALS(expectedTop, boundingBox.top());
+    TS_ASSERT_EQUALS(expectedBottom, boundingBox.bottom());
+  }
 };
 
-class PeakRepresentationSphereTestPerformance : public CxxTest::TestSuite
-{
+class PeakRepresentationSphereTestPerformance : public CxxTest::TestSuite {
 public:
-    /**
-    Here we create a distribution of Peaks. Peaks are dispersed. This is to give
-    a measurable peformance.
-    */
-    PeakRepresentationSphereTestPerformance()
-    {
-        const int sizeInAxis = 100;
-        const double radius = 5;
-        const double innerBackgroundRadius = 6;
-        const double outerBackgroundRadius = 7;
-        m_peaks.reserve(sizeInAxis * sizeInAxis * sizeInAxis);
-        for (int x = 0; x < sizeInAxis; ++x) {
-            for (int y = 0; y < sizeInAxis; ++y) {
-                for (int z = 0; z < sizeInAxis; ++z) {
-                    Mantid::Kernel::V3D peakOrigin(x, y, z);
-                    m_peaks.push_back(
-                        boost::make_shared<PeakRepresentationSphereExposeProtectedWrapper>(
-                            peakOrigin, radius, innerBackgroundRadius,
-                            outerBackgroundRadius));
-                }
-            }
+  /**
+  Here we create a distribution of Peaks. Peaks are dispersed. This is to give
+  a measurable peformance.
+  */
+  PeakRepresentationSphereTestPerformance() {
+    const int sizeInAxis = 100;
+    const double radius = 5;
+    const double innerBackgroundRadius = 6;
+    const double outerBackgroundRadius = 7;
+    m_peaks.reserve(sizeInAxis * sizeInAxis * sizeInAxis);
+    for (int x = 0; x < sizeInAxis; ++x) {
+      for (int y = 0; y < sizeInAxis; ++y) {
+        for (int z = 0; z < sizeInAxis; ++z) {
+          Mantid::Kernel::V3D peakOrigin(x, y, z);
+          m_peaks.push_back(boost::make_shared<
+              PeakRepresentationSphereExposeProtectedWrapper>(
+              peakOrigin, radius, innerBackgroundRadius,
+              outerBackgroundRadius));
         }
-
-        PeakRepresentationViewInformation viewInformation;
-        viewInformation.viewHeight = 1.0;
-        viewInformation.viewWidth = 1.0;
-        viewInformation.windowHeight = 1.0;
-        viewInformation.windowWidth = 1.0;
-        viewInformation.xOriginWindow = 1;
-        viewInformation.yOriginWindow = 1;
-
-        m_viewInformation = viewInformation;
+      }
     }
 
-    /// Test the performance of just setting the slice point.
-    void test_setSlicePoint_performance()
-    {
-        for (double z = 0; z < 100; z += 5) {
-            VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
-            while (it != m_peaks.end()) {
-                auto physicalPeak = *it;
-                //physicalPeak->setSlicePoint(z);
-                ++it;
-            }
-        }
+    PeakRepresentationViewInformation viewInformation;
+    viewInformation.viewHeight = 1.0;
+    viewInformation.viewWidth = 1.0;
+    viewInformation.windowHeight = 1.0;
+    viewInformation.windowWidth = 1.0;
+    viewInformation.xOriginWindow = 1;
+    viewInformation.yOriginWindow = 1;
+
+    m_viewInformation = viewInformation;
+  }
+
+  /// Test the performance of just setting the slice point.
+  void test_setSlicePoint_performance() {
+    for (double z = 0; z < 100; z += 5) {
+      VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
+      while (it != m_peaks.end()) {
+        auto physicalPeak = *it;
+        // physicalPeak->setSlicePoint(z);
+        ++it;
+      }
     }
-
-    /// Test the performance of just drawing.
-    void test_draw_performance()
-    {
-        const int nTimesRedrawAll = 20;
-        int timesDrawn = 0;
-        while (timesDrawn < nTimesRedrawAll) {
-            // Set the slicing point on all peaks.
-            VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
-            while (it != m_peaks.end()) {
-                //it->getDrawingInformationWrapper(m_viewInformation);
-                ++it;
-            }
-            ++timesDrawn;
-        }
+  }
+
+  /// Test the performance of just drawing.
+  void test_draw_performance() {
+    const int nTimesRedrawAll = 20;
+    int timesDrawn = 0;
+    while (timesDrawn < nTimesRedrawAll) {
+      // Set the slicing point on all peaks.
+      VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
+      while (it != m_peaks.end()) {
+        // it->getDrawingInformationWrapper(m_viewInformation);
+        ++it;
+      }
+      ++timesDrawn;
     }
-
-    /// Test the performance of both setting the slice point and drawing..
-    void test_whole_performance()
-    {
-        VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
-        //const double z = 10;
-        while (it != m_peaks.end()) {
-            //it->setSlicePoint(z);
-            //it->getDrawingInformationWrapper(m_viewInformation);
-            ++it;
-        }
+  }
+
+  /// Test the performance of both setting the slice point and drawing..
+  void test_whole_performance() {
+    VecPeaksRepresentationSphere::iterator it = m_peaks.begin();
+    // const double z = 10;
+    while (it != m_peaks.end()) {
+      // it->setSlicePoint(z);
+      // it->getDrawingInformationWrapper(m_viewInformation);
+      ++it;
     }
+  }
 
 private:
-    typedef boost::shared_ptr<PeakRepresentationSphereExposeProtectedWrapper>
-        PeaksRepresentationSphere_sptr;
-    typedef std::vector<PeaksRepresentationSphere_sptr>
-        VecPeaksRepresentationSphere;
-
-    /// Collection to store a large number of physicalPeaks.
-    VecPeaksRepresentationSphere m_peaks;
-    PeakRepresentationViewInformation m_viewInformation;
+  typedef boost::shared_ptr<PeakRepresentationSphereExposeProtectedWrapper>
+      PeaksRepresentationSphere_sptr;
+  typedef std::vector<PeaksRepresentationSphere_sptr>
+      VecPeaksRepresentationSphere;
+
+  /// Collection to store a large number of physicalPeaks.
+  VecPeaksRepresentationSphere m_peaks;
+  PeakRepresentationViewInformation m_viewInformation;
 };
 
 #endif
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ArrayDataSource.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ArrayDataSource.h
index c44ea86b298bf0c080295bbd553d5203c0e2d8b2..5a233608f4b9addcd0caa4948712db845e930a3e 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ArrayDataSource.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ArrayDataSource.h
@@ -36,40 +36,35 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ArrayDataSource: public SpectrumDataSource
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ArrayDataSource
+    : public SpectrumDataSource {
+public:
+  /// Construct a DataSource object based on the specified array of floats
+  ArrayDataSource(double total_xmin, double total_xmax, double total_ymin,
+                  double total_ymax, size_t total_rows, size_t total_cols,
+                  std::vector<float> data);
 
-    /// Construct a DataSource object based on the specified array of floats
-    ArrayDataSource( double total_xmin, double total_xmax,
-                     double total_ymin, double total_ymax,
-                     size_t total_rows, size_t total_cols,
-                     std::vector<float> data );
+  ~ArrayDataSource() override;
 
-    ~ArrayDataSource() override;
+  bool hasData(const std::string &wsName,
+               const boost::shared_ptr<Mantid::API::Workspace> ws) override;
 
-    bool hasData(const std::string &wsName,
-                 const boost::shared_ptr<Mantid::API::Workspace> ws) override;
+  /// Get DataArray covering full range of data in x, and y directions
+  DataArray_const_sptr getDataArray(bool is_log_x) override;
 
-    /// Get DataArray covering full range of data in x, and y directions
-    DataArray_const_sptr getDataArray(bool is_log_x) override;
+  /// Get DataArray covering restricted range of data
+  DataArray_const_sptr getDataArray(double xMin, double xMax, double yMin,
+                                    double yMax, size_t nRows, size_t nCols,
+                                    bool isLogX) override;
 
-    /// Get DataArray covering restricted range of data
-    DataArray_const_sptr getDataArray(double xMin, double xMax, double yMin,
-                                      double yMax, size_t nRows, size_t nCols,
-                                      bool isLogX) override;
-
-    /// Get a list containing pairs of strings with information about x,y
-    std::vector<std::string> getInfoList(double x, double y) override;
-
-  private:
-    std::vector<float> m_data;
+  /// Get a list containing pairs of strings with information about x,y
+  std::vector<std::string> getInfoList(double x, double y) override;
 
+private:
+  std::vector<float> m_data;
 };
 
 typedef boost::shared_ptr<ArrayDataSource> ArrayDataSource_sptr;
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ColorMaps.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ColorMaps.h
index b833b38c8839d35d398b4d7b8d34d50e5dc9853a..d20e9f40cb5ad4a9e4def19fbe2bc7b90084b4d8 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ColorMaps.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ColorMaps.h
@@ -6,17 +6,17 @@
 #include "MantidQtSpectrumViewer/DllOptionSV.h"
 
 /**
-    @class ColorMaps 
-  
+    @class ColorMaps
+
        This class has static methods to construct some useful color scales
-    and to build a lookup table to brighten an image, so low-level 
-    intensities become more visible 
+    and to build a lookup table to brighten an image, so low-level
+    intensities become more visible
+
+    @author Dennis Mikkelson
+    @date   2012-04-03
 
-    @author Dennis Mikkelson 
-    @date   2012-04-03 
-     
     Copyright © 2012 ORNL, STFC Rutherford Appleton Laboratories
-  
+
     This file is part of Mantid.
 
     Mantid is free software; you can redistribute it and/or modify
@@ -31,32 +31,27 @@
 
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
-    
-    Code Documentation is available at 
+
+    Code Documentation is available at
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ColorMaps
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ColorMaps {
 
 public:
-
-  enum ColorScale
-       {
-         HEAT,
-         GRAY,
-         NEGATIVE_GRAY,
-         GREEN_YELLOW,
-         RAINBOW,
-         OPTIMAL,
-         MULTI,
-         SPECTRUM
-       };
+  enum ColorScale {
+    HEAT,
+    GRAY,
+    NEGATIVE_GRAY,
+    GREEN_YELLOW,
+    RAINBOW,
+    OPTIMAL,
+    MULTI,
+    SPECTRUM
+  };
 
   /// Get the specified color scale
   static std::vector<QRgb> GetColorMap(ColorScale name, size_t n_colors);
@@ -75,6 +70,6 @@ private:
 };
 
 } // namespace SpectrumView
-} // namespace MantidQt 
+} // namespace MantidQt
 
-#endif  // COLOR_MAPS_H
+#endif // COLOR_MAPS_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/DataArray.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/DataArray.h
index 017b22997c187ed4a53072a6a1b1ac893fffb65f..448bab88eeeef926d05208f163e5160638dbb4fa 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/DataArray.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/DataArray.h
@@ -38,99 +38,90 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER DataArray
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER DataArray {
+public:
+  /// Construct a DataArray "wrapper" around the data and region info
+  DataArray(double xMin, double xMax, double yMin, double yMax, bool isLogX,
+            size_t nRows, size_t nCols, const std::vector<float> &data);
 
-    /// Construct a DataArray "wrapper" around the data and region info
-    DataArray( double xMin,    double xMax,
-               double yMin,    double yMax,
-               bool   isLogX,
-               size_t nRows,   size_t nCols,
-               const std::vector<float>& data );
+  ~DataArray();
 
-    ~DataArray();
+  /// Get the smallest 'x' value actually covered by this DataArray
+  double getXMin() const;
 
-    /// Get the smallest 'x' value actually covered by this DataArray
-    double getXMin() const;
+  /// Get the largest 'x' value actually covered by this DataArray
+  double getXMax() const;
 
-    /// Get the largest 'x' value actually covered by this DataArray
-    double getXMax() const;
+  /// Get the smallest 'y' value actually covered by this DataArray
+  double getYMin() const;
 
-    /// Get the smallest 'y' value actually covered by this DataArray
-    double getYMin() const;
+  /// Get the largest 'y' value actually covered by this DataArray
+  double getYMax() const;
 
-    /// Get the largest 'y' value actually covered by this DataArray
-    double getYMax() const;
+  /// Check if the returned array is binned logarithmically in 'x'
+  bool isLogX() const;
 
-    /// Check if the returned array is binned logarithmically in 'x'
-    bool isLogX() const;
+  /// Get smallest value recorded in this DataArray
+  double getDataMin() const;
 
-    /// Get smallest value recorded in this DataArray
-    double getDataMin() const;
+  /// Get largest value recorded in this DataArray
+  double getDataMax() const;
 
-    /// Get largest value recorded in this DataArray
-    double getDataMax() const;
+  // Get the actual number of rows in this DataArray
+  size_t getNRows() const;
 
-    // Get the actual number of rows in this DataArray
-    size_t getNRows() const;
+  /// Get the actual number of columns in this DataArray
+  size_t getNCols() const;
 
-    /// Get the actual number of columns in this DataArray
-    size_t getNCols() const;
+  /// Get vector containing all values, packed in a 1-D array
+  std::vector<float> getData() const;
 
-    /// Get vector containing all values, packed in a 1-D array
-    std::vector<float> getData() const;
+  /// Get the value at the specified row and column
+  double getValue(int row, int col) const;
 
-    /// Get the value at the specified row and column
-    double getValue( int row, int col ) const;
+  /// Get the value from the row and column containing the specified point
+  double getValue(double x, double y) const;
 
-    /// Get the value from the row and column containing the specified point
-    double getValue( double x, double y ) const;
+  /// Clamp x to the interval of x-values covered by this DataArray
+  void restrictX(double &x) const;
 
-    /// Clamp x to the interval of x-values covered by this DataArray
-    void restrictX( double & x ) const;
+  /// Clamp y to the interval of y-values covered by this DataArray
+  void restrictY(double &y) const;
 
-    /// Clamp y to the interval of y-values covered by this DataArray
-    void restrictY( double & y ) const;
+  /// Clamp row to a valid row number for this DataArray
+  void restrictRow(int &row) const;
 
-    /// Clamp row to a valid row number for this DataArray
-    void restrictRow( int & row ) const;
+  /// Clamp col to a valid column number for this DataArray
+  void restrictCol(int &col) const;
 
-    /// Clamp col to a valid column number for this DataArray
-    void restrictCol( int & col ) const;
+  /// Calculate the column number containing the specified x
+  size_t columnOfX(double x) const;
 
-    /// Calculate the column number containing the specified x
-    size_t columnOfX( double x ) const;
+  /// Calculate the x-value at the center of the specified column
+  double xOfColumn(size_t col) const;
 
-    /// Calculate the x-value at the center of the specified column
-    double xOfColumn( size_t col ) const;
+  /// Calculate the row number containing the specified y
+  size_t rowOfY(double y) const;
 
-    /// Calculate the row number containing the specified y
-    size_t rowOfY( double y ) const;
+  /// Calculate the y-value at the center of the specified row
+  double yOfRow(size_t row) const;
 
-    /// Calculate the y-value at the center of the specified row
-    double yOfRow( size_t row ) const;
+private:
+  double m_xMin;
+  double m_xMax;
+  double m_yMin;
+  double m_yMax;
+  bool m_isLogX;
+  size_t m_nRows;
+  size_t m_nCols;
 
+  double m_dataMin;
+  double m_dataMax;
 
-  private:
-    double m_xMin;
-    double m_xMax;
-    double m_yMin;
-    double m_yMax;
-    bool   m_isLogX;
-    size_t m_nRows;
-    size_t m_nCols;
-
-    double m_dataMin;
-    double m_dataMax;
-
-    std::vector<float> m_data;
-
+  std::vector<float> m_data;
 };
 
 typedef boost::shared_ptr<DataArray> DataArray_sptr;
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/EModeHandler.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/EModeHandler.h
index 2e5c33da7faea1b85f953987ac8fc740bc5d68b8..aa4ca8518df3c3a80176f0f0a97de6ee861a9bb1 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/EModeHandler.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/EModeHandler.h
@@ -35,33 +35,28 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER EModeHandler
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER EModeHandler {
+public:
+  /// Construct object to manage E Mode controls in the UI
+  EModeHandler(Ui_SpectrumViewer *sv_ui);
 
-    /// Construct object to manage E Mode controls in the UI
-    EModeHandler( Ui_SpectrumViewer* sv_ui );
+  /// Get the E Mode to control units calculation, from the combo box
+  int getEMode();
 
-    /// Get the E Mode to control units calculation, from the combo box
-    int getEMode();
+  /// Set the E Mode to control units calculation, in the combo box
+  void setEMode(const int mode);
 
-    /// Set the E Mode to control units calculation, in the combo box
-    void setEMode( const int mode );
+  /// Get the E Fixed value from the GUI
+  double getEFixed();
 
-    /// Get the E Fixed value from the GUI
-    double getEFixed();
-
-    /// Set the E Fixed value in the GUI
-    void setEFixed( const double efixed );
-
-  private:
-    Ui_SpectrumViewer* m_svUI;
+  /// Set the E Fixed value in the GUI
+  void setEFixed(const double efixed);
 
+private:
+  Ui_SpectrumViewer *m_svUI;
 };
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/GraphDisplay.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/GraphDisplay.h
index a7cdd630803f9bf82ed17fe8141e2dfad3eaac94..ca825e1638c2d46fc9fd16b007b1e77f460ff16e 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/GraphDisplay.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/GraphDisplay.h
@@ -1,5 +1,5 @@
-#ifndef  GRAPH_DISPLAY_H
-#define  GRAPH_DISPLAY_H
+#ifndef GRAPH_DISPLAY_H
+#define GRAPH_DISPLAY_H
 
 #include <QTableWidget>
 #include <qwt_plot.h>
@@ -38,69 +38,60 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER GraphDisplay
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER GraphDisplay {
+public:
+  /// Construct a GraphDisplay to display in the specifed plot and table
+  GraphDisplay(QwtPlot *graphPlot, QTableWidget *graphTable, bool isVertical);
 
-   /// Construct a GraphDisplay to display in the specifed plot and table
-   GraphDisplay( QwtPlot*      graphPlot,
-                 QTableWidget* graphTable,
-                 bool          isVertical );
+  ~GraphDisplay();
 
-   ~GraphDisplay();
+  /// Set the source of information for the table of position information
+  void setDataSource(SpectrumDataSource_sptr dataSource);
 
-   /// Set the source of information for the table of position information
-   void setDataSource( SpectrumDataSource_sptr dataSource );
+  /// Set the actual data that will be displayed on the graph
+  void setData(const QVector<double> &xData, const QVector<double> &yData,
+               double cutValue, bool isFront = true);
 
-   /// Set the actual data that will be displayed on the graph
-   void setData( const QVector<double> & xData,
-                 const QVector<double> & yData,
-                 double cutValue,
-                 bool   isFront = true);
+  /// Clear the graph(s) off the display
+  void clear();
 
-   /// Clear the graph(s) off the display
-   void clear();
+  /// Set up axes using the specified scale factor and replot the graph
+  void setRangeScale(double rangeScale);
 
-   /// Set up axes using the specified scale factor and replot the graph
-   void setRangeScale( double rangeScale );
+  /// Set flag indicating whether or not to use a log scale on the x-axis
+  void setLogX(bool isLogX);
 
-   /// Set flag indicating whether or not to use a log scale on the x-axis
-   void setLogX( bool isLogX );
+  /// Record the point that the user is currently pointing at with the mouse
+  void setPointedAtPoint(QPoint point);
 
-   /// Record the point that the user is currently pointing at with the mouse
-   void setPointedAtPoint( QPoint point );
+private:
+  /// Show information about the point (x, y) on the graph, in the info table
+  void showInfoList(double x, double y);
+  /// Remove all curves.
+  void clearCurves();
 
-  private:
-   /// Show information about the point (x, y) on the graph, in the info table
-   void showInfoList( double x, double y );
-   /// Remove all curves.
-   void clearCurves();
+  QwtPlot *m_graphPlot;
+  QList<QwtPlotCurve *> m_curves;
+  QTableWidget *m_graphTable;
+  SpectrumDataSource_sptr m_dataSource;
 
-   QwtPlot            * m_graphPlot;
-   QList<QwtPlotCurve*> m_curves;
-   QTableWidget       * m_graphTable;
-   SpectrumDataSource_sptr m_dataSource;
-
-   bool   m_isVertical;
-   bool   m_isLogX;
-   double m_imageX;
-   double m_imageY;
-   double m_rangeScale;  // Fraction of data range to be graphed
-   double m_minX;
-   double m_maxX;
-   double m_minY;
-   double m_maxY;
-
-   static std::vector<QColor> g_curveColors;
+  bool m_isVertical;
+  bool m_isLogX;
+  double m_imageX;
+  double m_imageY;
+  double m_rangeScale; // Fraction of data range to be graphed
+  double m_minX;
+  double m_maxX;
+  double m_minY;
+  double m_maxY;
 
+  static std::vector<QColor> g_curveColors;
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif   // GRAPH_DISPLAY_H
+#endif // GRAPH_DISPLAY_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/IRangeHandler.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/IRangeHandler.h
index 1ac4ce54a8b801df2f14395222eff76d083aa2d3..ea844714a02cbd5a9889faf61477e5979004b0c7 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/IRangeHandler.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/IRangeHandler.h
@@ -4,15 +4,14 @@
 #include "MantidQtSpectrumViewer/DllOptionSV.h"
 #include "MantidQtSpectrumViewer/SpectrumDataSource.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /** An interface to the RangeHandler class, which manages the min, max and step
     range controls for the SpectrumView data viewer.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -32,8 +31,7 @@ namespace SpectrumView
     Code Documentation is available at <http://doxygen.mantidproject.org>
  */
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER IRangeHandler
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER IRangeHandler {
 
 public:
   /// Construct object to manage min, max and step controls in the UI
@@ -41,11 +39,10 @@ public:
   virtual ~IRangeHandler() {}
 
   /// Configure min, max and step controls for the specified data source
-  virtual void configureRangeControls( SpectrumDataSource_sptr dataSource ) = 0;
+  virtual void configureRangeControls(SpectrumDataSource_sptr dataSource) = 0;
 
   /// Get the range of data to display in the image, from GUI controls
-  virtual void getRange( double &min, double &max, double &step ) = 0;
-
+  virtual void getRange(double &min, double &max, double &step) = 0;
 };
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ISliderHandler.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ISliderHandler.h
index 36cec7c1911a0eb0ed3e121f68459a3d6aff2e2f..f5e2b3e53f66e6a884022035f0e217b41d62f25d 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ISliderHandler.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/ISliderHandler.h
@@ -5,15 +5,14 @@
 #include <QRect>
 #include "MantidQtSpectrumViewer/SpectrumDataSource.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /** An interface to the SliderHandler, which manages the horizontal and vertical
     scroll bars for the SpectrumView data viewer.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -33,8 +32,7 @@ namespace SpectrumView
     Code Documentation is available at <http://doxygen.mantidproject.org>
  */
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ISliderHandler
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER ISliderHandler {
 
 public:
   /// Construct object to manage image scrollbars from the specified UI
@@ -42,12 +40,11 @@ public:
   virtual ~ISliderHandler() {}
 
   /// Configure the image scrollbars for the specified data and drawing area
-  virtual void configureSliders( QRect drawArea,
-                                 SpectrumDataSource_sptr dataSource ) = 0;
+  virtual void configureSliders(QRect drawArea,
+                                SpectrumDataSource_sptr dataSource) = 0;
 
   /// Configure the horizontal scrollbar to cover the specified range
-  virtual void configureHSlider( int         nDataSteps,
-                                 int         nPixels ) = 0;
+  virtual void configureHSlider(int nDataSteps, int nPixels) = 0;
 
   /// Return true if the image horizontal scrollbar is enabled.
   virtual bool hSliderOn() = 0;
@@ -56,10 +53,10 @@ public:
   virtual bool vSliderOn() = 0;
 
   /// Get the range of columns to display in the image.
-  virtual void getHSliderInterval( int &xMin, int &xMax ) = 0;
+  virtual void getHSliderInterval(int &xMin, int &xMax) = 0;
 
   /// Get the range of rows to display in the image.
-  virtual void getVSliderInterval( int &yMin, int &yMax ) = 0;
+  virtual void getVSliderInterval(int &yMin, int &yMax) = 0;
 };
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSDataSource.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSDataSource.h
index f7b095ab7c871e2e14133260bdc878cf99efdaed..2d667af908cc7b90979b8dfd2f1e243059b2da9a 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSDataSource.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSDataSource.h
@@ -9,19 +9,15 @@
 
 #include "MantidAPI/MatrixWorkspace_fwd.h"
 
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IComponent;
-    class Instrument;
-  }
+namespace Mantid {
+namespace Geometry {
+class IComponent;
+class Instrument;
+}
 }
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 class EModeHandler;
 
 /**
@@ -53,55 +49,54 @@ class EModeHandler;
     Code Documentation is available at
                  <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER MatrixWSDataSource: public SpectrumDataSource
-{
-  public:
-
-    /// Construct a DataSource object around the specifed MatrixWorkspace
-    MatrixWSDataSource( Mantid::API::MatrixWorkspace_const_sptr matWs );
-
-    ~MatrixWSDataSource() override;
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER MatrixWSDataSource
+    : public SpectrumDataSource {
+public:
+  /// Construct a DataSource object around the specifed MatrixWorkspace
+  MatrixWSDataSource(Mantid::API::MatrixWorkspace_const_sptr matWs);
 
-    bool hasData(const std::string &wsName,
-                 const boost::shared_ptr<Mantid::API::Workspace> ws) override;
+  ~MatrixWSDataSource() override;
 
-    /// Get the smallest 'x' value covered by the data
-    double getXMin() override;
+  bool hasData(const std::string &wsName,
+               const boost::shared_ptr<Mantid::API::Workspace> ws) override;
 
-    /// Get the largest 'x' value covered by the data
-    double getXMax() override;
+  /// Get the smallest 'x' value covered by the data
+  double getXMin() override;
 
-    /// Get the largest 'y' value covered by the data
-    double getYMax() override;
+  /// Get the largest 'x' value covered by the data
+  double getXMax() override;
 
-    /// Get the total number of rows of data
-    size_t getNRows() override;
+  /// Get the largest 'y' value covered by the data
+  double getYMax() override;
 
-    /// Get DataArray covering full range of data in x, and y directions
-    DataArray_const_sptr getDataArray(bool isLogX) override;
+  /// Get the total number of rows of data
+  size_t getNRows() override;
 
-    /// Get DataArray covering restricted range of data
-    DataArray_const_sptr getDataArray(double xMin, double xMax, double yMin,
-                                      double yMax, size_t nRows, size_t nCols,
-                                      bool isLogX) override;
+  /// Get DataArray covering full range of data in x, and y directions
+  DataArray_const_sptr getDataArray(bool isLogX) override;
 
-    /// Set the class that gets the emode & efixed info from the user.
-    void setEModeHandler( EModeHandler* emodeHandler );
+  /// Get DataArray covering restricted range of data
+  DataArray_const_sptr getDataArray(double xMin, double xMax, double yMin,
+                                    double yMax, size_t nRows, size_t nCols,
+                                    bool isLogX) override;
 
-    /// Get a list containing pairs of strings with information about x,y
-    std::vector<std::string> getInfoList(double x, double y) override;
+  /// Set the class that gets the emode & efixed info from the user.
+  void setEModeHandler(EModeHandler *emodeHandler);
 
-  private:
-    Mantid::API::MatrixWorkspace_const_sptr m_matWs;
-    EModeHandler* m_emodeHandler;
-    boost::shared_ptr<const Mantid::Geometry::Instrument> m_instrument;
-    boost::shared_ptr<const Mantid::Geometry::IComponent> m_source;
-    boost::shared_ptr<const Mantid::Geometry::IComponent> m_sample;
+  /// Get a list containing pairs of strings with information about x,y
+  std::vector<std::string> getInfoList(double x, double y) override;
 
+private:
+  Mantid::API::MatrixWorkspace_const_sptr m_matWs;
+  EModeHandler *m_emodeHandler;
+  boost::shared_ptr<const Mantid::Geometry::Instrument> m_instrument;
+  boost::shared_ptr<const Mantid::Geometry::IComponent> m_source;
+  boost::shared_ptr<const Mantid::Geometry::IComponent> m_sample;
 };
 
 typedef boost::shared_ptr<MatrixWSDataSource> MatrixWSDataSource_sptr;
-typedef boost::shared_ptr<const MatrixWSDataSource> MatrixWSDataSource_const_sptr;
+typedef boost::shared_ptr<const MatrixWSDataSource>
+    MatrixWSDataSource_const_sptr;
 
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSSpectrumView.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSSpectrumView.h
index abbcff92cae09c1b6b4309986c9f69ab4c3b24a0..e3981b23082948e492a762391a61fe6d977f7b03 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSSpectrumView.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/MatrixWSSpectrumView.h
@@ -7,16 +7,16 @@
 #include "MantidQtSpectrumViewer/SpectrumView.h"
 
 /**
-    @class MatrixWSDataSource 
-  
+    @class MatrixWSDataSource
+
     This is the top level class for showing a matrix workspace
     using an SpectrumViewer.
- 
-    @author Dennis Mikkelson 
-    @date   2012-05-08 
-     
+
+    @author Dennis Mikkelson
+    @date   2012-05-08
+
     Copyright © 2012 ORNL, STFC Rutherford Appleton Laboratories
-  
+
     This file is part of Mantid.
 
     Mantid is free software; you can redistribute it and/or modify
@@ -31,30 +31,26 @@
 
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
-    
-    Code Documentation is available at 
+
+    Code Documentation is available at
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
-
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER MatrixWSSpectrumView
-{
-  public:
+namespace MantidQt {
+namespace SpectrumView {
 
-    /// Construct a spectrum viewer for the specifed MatrixWorkspace
-    MatrixWSSpectrumView( Mantid::API::MatrixWorkspace_const_sptr mat_ws );
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER MatrixWSSpectrumView {
+public:
+  /// Construct a spectrum viewer for the specifed MatrixWorkspace
+  MatrixWSSpectrumView(Mantid::API::MatrixWorkspace_const_sptr mat_ws);
 
-   ~MatrixWSSpectrumView();
+  ~MatrixWSSpectrumView();
 
-  private:
-    SpectrumView *spectrum_view;
+private:
+  SpectrumView *spectrum_view;
 };
 
 } // namespace SpectrumView
-} // namespace MantidQt 
+} // namespace MantidQt
 
 #endif // MATRIX_WS_SPECTRUM_VIEW_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/QtUtils.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/QtUtils.h
index a9cc8650935b60904755d323adfc20cf9451faf3..4071058616e54a482e75868a637fb7fc4fa71acd 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/QtUtils.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/QtUtils.h
@@ -1,5 +1,5 @@
-#ifndef  QT_UTILS_H
-#define  QT_UTILS_H
+#ifndef QT_UTILS_H
+#define QT_UTILS_H
 
 #include <QTableWidget>
 #include <QLineEdit>
@@ -36,41 +36,28 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER QtUtils
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER QtUtils {
+public:
   /// enter the specified string in the table
-  static void SetTableEntry(       int           row,
-                                   int           col,
-                             const std::string & string,
-                                   QTableWidget* table );
+  static void SetTableEntry(int row, int col, const std::string &string,
+                            QTableWidget *table);
 
   /// enter the specified double, formatted, in the table
-  static void SetTableEntry( int           row,
-                             int           col,
-                             int           width,
-                             int           precision,
-                             double        value,
-                             QTableWidget* table );
+  static void SetTableEntry(int row, int col, int width, int precision,
+                            double value, QTableWidget *table);
 
   /// Set the specified string into the specified QLineEdit widget.
-  static void SetText( const std::string & string,
-                             QLineEdit*    lineEdit );
+  static void SetText(const std::string &string, QLineEdit *lineEdit);
 
   /// enter the specified double, formatted, in the QLineEdit control
-  static void SetText( int        width,
-                       int        precision,
-                       double     value,
-                       QLineEdit* lineEdit );
+  static void SetText(int width, int precision, double value,
+                      QLineEdit *lineEdit);
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif   // QT_UTILS_H
+#endif // QT_UTILS_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/RangeHandler.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/RangeHandler.h
index 3f3bce5d304f90377d5909ed601640f93001bf5b..59900f22eea493e20b5981839fc9e0919f404a8a 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/RangeHandler.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/RangeHandler.h
@@ -36,32 +36,28 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER RangeHandler : public IRangeHandler
-{
-  public:
-    /// Construct object to manage min, max and step controls in the UI
-    RangeHandler( Ui_SpectrumViewer* svUI );
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER RangeHandler : public IRangeHandler {
+public:
+  /// Construct object to manage min, max and step controls in the UI
+  RangeHandler(Ui_SpectrumViewer *svUI);
 
-    /// Configure min, max and step controls for the specified data source
-    void configureRangeControls(SpectrumDataSource_sptr dataSource) override;
+  /// Configure min, max and step controls for the specified data source
+  void configureRangeControls(SpectrumDataSource_sptr dataSource) override;
 
-    /// Get the range of data to display in the image, from GUI controls
-    void getRange(double &min, double &max, double &step) override;
+  /// Get the range of data to display in the image, from GUI controls
+  void getRange(double &min, double &max, double &step) override;
 
-    /// Set the values displayed in the GUI controls
-    void setRange( double min, double max, double step );
-
-  private:
-    Ui_SpectrumViewer* m_svUI;
-    double             m_totalMinX;
-    double             m_totalMaxX;
-    size_t             m_totalNSteps;
+  /// Set the values displayed in the GUI controls
+  void setRange(double min, double max, double step);
 
+private:
+  Ui_SpectrumViewer *m_svUI;
+  double m_totalMinX;
+  double m_totalMaxX;
+  size_t m_totalNSteps;
 };
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVConnections.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVConnections.h
index 633b84eb4b6e631eabfc1b94397c49353bb925be..bac0b54193636fe9702f58030ac94a84fc138e7d 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVConnections.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVConnections.h
@@ -13,7 +13,6 @@
 #include "MantidQtSpectrumViewer/DllOptionSV.h"
 #include "MantidQtSpectrumViewer/ColorMaps.h"
 
-
 /**
     @class SVConnections
 
@@ -47,30 +46,24 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SVConnections: public QWidget
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SVConnections : public QWidget {
   Q_OBJECT
 
 public:
-
   /// Construct the object that links the GUI components to the other specifed
   /// higher level objects.
-  SVConnections( Ui_SpectrumViewer* ui,
-                 SpectrumView*      spectrumView,
-                 SpectrumDisplay*   spectrumDisplay,
-                 GraphDisplay*      hGraphDisplay,
-                 GraphDisplay*      vGraphDisplay );
+  SVConnections(Ui_SpectrumViewer *ui, SpectrumView *spectrumView,
+                SpectrumDisplay *spectrumDisplay, GraphDisplay *hGraphDisplay,
+                GraphDisplay *vGraphDisplay);
 
   ~SVConnections() override;
 
   /// Set the pix map that shows the color scale from the specified color maps
-  void showColorScale( std::vector<QRgb> & positiveColorTable,
-                       std::vector<QRgb> & negativeColorTable );
+  void showColorScale(std::vector<QRgb> &positiveColorTable,
+                      std::vector<QRgb> &negativeColorTable);
 
 public slots:
   void closeViewer();
@@ -96,9 +89,9 @@ public slots:
   void multiColorScale();
   void spectrumColorScale();
 
-  void setSpectrumDisplay(SpectrumDisplay* spectrumDisplay);
-  SpectrumDisplay* getCurrentSpectrumDisplay() const;
-  void removeSpectrumDisplay(SpectrumDisplay* spectrumDisplay);
+  void setSpectrumDisplay(SpectrumDisplay *spectrumDisplay);
+  SpectrumDisplay *getCurrentSpectrumDisplay() const;
+  void removeSpectrumDisplay(SpectrumDisplay *spectrumDisplay);
 
 private:
   /// Event filter for mouse wheel capture
@@ -106,25 +99,24 @@ private:
   void setColorScale(ColorMaps::ColorScale positive,
                      ColorMaps::ColorScale negative);
 
-  Ui_SpectrumViewer*  m_svUI;
-  SpectrumView*       m_svMainWindow;
-  QList<SpectrumDisplay*>  m_spectrumDisplays;
-  SpectrumDisplay*  m_currentSpectrumDisplay;
-  GraphDisplay*       m_hGraphDisplay;
-  GraphDisplay*       m_vGraphDisplay;
-  TrackingPicker*     m_hGraphPicker;
-  TrackingPicker*     m_vGraphPicker;
-  QActionGroup*       m_colorGroup;
+  Ui_SpectrumViewer *m_svUI;
+  SpectrumView *m_svMainWindow;
+  QList<SpectrumDisplay *> m_spectrumDisplays;
+  SpectrumDisplay *m_currentSpectrumDisplay;
+  GraphDisplay *m_hGraphDisplay;
+  GraphDisplay *m_vGraphDisplay;
+  TrackingPicker *m_hGraphPicker;
+  TrackingPicker *m_vGraphPicker;
+  QActionGroup *m_colorGroup;
 
   /// Last known cursor position in the data (x-direction).
   int m_pickerX;
 
   /// Last known cursor position in the data (y-direction).
   int m_pickerY;
-
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif  // SV_CONNECTIONS_H
+#endif // SV_CONNECTIONS_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVUtils.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVUtils.h
index 22eb2fb1fac07060b6e3953a11b3cf8f2286d79d..d794cd61f19da08ff71f2068a2b356e79f4906ee 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVUtils.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SVUtils.h
@@ -1,5 +1,5 @@
-#ifndef  SV_UTILS_H
-#define  SV_UTILS_H
+#ifndef SV_UTILS_H
+#define SV_UTILS_H
 
 #include <QVector>
 
@@ -35,73 +35,50 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
-
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SVUtils
-{
-  public:
-    /// Get a formatted string representation of a double
-    static void Format( int            width,
-                        int            precision,
-                        double         value,
-                        std::string  & str );
-
-    /// push a name, value pair onto a vector of strings
-    static void PushNameValue( const std::string               & name,
-                                     int                         width,
-                                     int                         precision,
-                                     double                      value,
-                                     std::vector<std::string>  & list );
-
-    /// find a non-degenerate interval containing all the specified values
-    static bool FindValidInterval( const QVector<double>  & values,
-                                         double           & min,
-                                         double           & max );
-
-    /// Adjust min and max so that min is strictly less than max
-    static bool FindValidInterval( double           & min,
-                                   double           & max );
-
-    /// Adjust min and max so they can be used to form a log scale
-    static bool FindValidLogInterval( double  & min, double  & max );
-
-    /// Find the number of steps from min to max on a linear or log scale
-    static int NumSteps( double min, double max, double step );
-
-    /// Find point new_val that is spaced between new_min and new_max in the
-    /// same proportion as val is between min and max. Return false if
-    /// new_val is outside [new_min,new_max].
-    static bool Interpolate( double   min,
-                             double   max,
-                             double   val,
-                             double   newMin,
-                             double   newMax,
-                             double & newVal );
-
-    /// Find the value in [new_min,new_max] on a logarithmic scale that
-    /// would correspond to the point val on a linear scale on [min,max].
-    static bool LogInterpolate( double   min,
-                                double   max,
-                                double   val,
-                                double   newMin,
-                                double   newMax,
-                                double & newVal );
-
-    /// adjust the values defining a subinterval to match the boundaries of
-    /// the global data. (Currently only for uniformly spaced bins.)
-    static bool CalculateInterval( double   globalMin,
-                                   double   globalMax,
-                                   size_t   globalSteps,
-                                   size_t & firstIndex,
-                                   double & min,
-                                   double & max,
-                                   size_t & steps );
+namespace MantidQt {
+namespace SpectrumView {
+
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SVUtils {
+public:
+  /// Get a formatted string representation of a double
+  static void Format(int width, int precision, double value, std::string &str);
+
+  /// push a name, value pair onto a vector of strings
+  static void PushNameValue(const std::string &name, int width, int precision,
+                            double value, std::vector<std::string> &list);
+
+  /// find a non-degenerate interval containing all the specified values
+  static bool FindValidInterval(const QVector<double> &values, double &min,
+                                double &max);
+
+  /// Adjust min and max so that min is strictly less than max
+  static bool FindValidInterval(double &min, double &max);
+
+  /// Adjust min and max so they can be used to form a log scale
+  static bool FindValidLogInterval(double &min, double &max);
+
+  /// Find the number of steps from min to max on a linear or log scale
+  static int NumSteps(double min, double max, double step);
+
+  /// Find point new_val that is spaced between new_min and new_max in the
+  /// same proportion as val is between min and max. Return false if
+  /// new_val is outside [new_min,new_max].
+  static bool Interpolate(double min, double max, double val, double newMin,
+                          double newMax, double &newVal);
+
+  /// Find the value in [new_min,new_max] on a logarithmic scale that
+  /// would correspond to the point val on a linear scale on [min,max].
+  static bool LogInterpolate(double min, double max, double val, double newMin,
+                             double newMax, double &newVal);
+
+  /// adjust the values defining a subinterval to match the boundaries of
+  /// the global data. (Currently only for uniformly spaced bins.)
+  static bool CalculateInterval(double globalMin, double globalMax,
+                                size_t globalSteps, size_t &firstIndex,
+                                double &min, double &max, size_t &steps);
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif   // SV_UTILS_H
+#endif // SV_UTILS_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SliderHandler.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SliderHandler.h
index 30302b13dc896f8553d393cba2b96a4ff77c37e5..14b4f51990ac33ef53c3b555f1dad14a2aeca437 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SliderHandler.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SliderHandler.h
@@ -38,49 +38,42 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SliderHandler : public ISliderHandler
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SliderHandler : public ISliderHandler {
+public:
+  /// Construct object to manage image scrollbars from the specified UI
+  SliderHandler(Ui_SpectrumViewer *svUI);
 
-    /// Construct object to manage image scrollbars from the specified UI
-    SliderHandler( Ui_SpectrumViewer* svUI );
+  /// Configure the image scrollbars for the specified data and drawing area
+  void configureSliders(QRect drawArea,
+                        SpectrumDataSource_sptr dataSource) override;
 
-    /// Configure the image scrollbars for the specified data and drawing area
-    void configureSliders(QRect drawArea,
-                          SpectrumDataSource_sptr dataSource) override;
+  /// Configure the image scrollbars for the specified drawing area
+  void reConfigureSliders(QRect drawArea, SpectrumDataSource_sptr dataSource);
 
-    /// Configure the image scrollbars for the specified drawing area
-    void reConfigureSliders( QRect drawArea,
-                             SpectrumDataSource_sptr dataSource );
+  /// Configure the horizontal scrollbar to cover the specified range
+  void configureHSlider(int nDataSteps, int nPixels) override;
 
-    /// Configure the horizontal scrollbar to cover the specified range
-    void configureHSlider(int nDataSteps, int nPixels) override;
+  /// Return true if the image horizontal scrollbar is enabled.
+  bool hSliderOn() override;
 
-    /// Return true if the image horizontal scrollbar is enabled.
-    bool hSliderOn() override;
+  /// Return true if the image vertical scrollbar is enabled.
+  bool vSliderOn() override;
 
-    /// Return true if the image vertical scrollbar is enabled.
-    bool vSliderOn() override;
+  /// Get the range of columns to display in the image.
+  void getHSliderInterval(int &xMin, int &xMax) override;
 
-    /// Get the range of columns to display in the image.
-    void getHSliderInterval(int &xMin, int &xMax) override;
+  /// Get the range of rows to display in the image.
+  void getVSliderInterval(int &yMin, int &yMax) override;
 
-    /// Get the range of rows to display in the image.
-    void getVSliderInterval(int &yMin, int &yMax) override;
+private:
+  /// Configure the specified scrollbar to cover the specified range
+  void configureSlider(QScrollBar *scrollBar, int nDataSteps, int nPixels,
+                       int val);
 
-  private:
-    /// Configure the specified scrollbar to cover the specified range
-    void configureSlider( QScrollBar* scrollBar,
-                          int         nDataSteps,
-                          int         nPixels,
-                          int         val );
-
-    Ui_SpectrumViewer* m_svUI;
+  Ui_SpectrumViewer *m_svUI;
 };
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDataSource.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDataSource.h
index 82430bd0e3e393cffe0ec6c8d3012eaa318c6000..f51c5555d882a2c726d1693d33d4753a46f81d25 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDataSource.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDataSource.h
@@ -39,84 +39,76 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumDataSource
-{
-  public:
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumDataSource {
+public:
+  /// Construct data source with specified total range and data size
+  SpectrumDataSource(double totalXmin, double totalXmax, double totalYmin,
+                     double totalYmax, size_t totalRows, size_t totalCols);
 
-    /// Construct data source with specified total range and data size
-    SpectrumDataSource( double totalXmin, double totalXmax,
-                        double totalYmin, double totalYmax,
-                        size_t totalRows, size_t totalCols );
+  virtual ~SpectrumDataSource();
 
-    virtual ~SpectrumDataSource();
+  virtual bool hasData(const std::string &wsName,
+                       const boost::shared_ptr<Mantid::API::Workspace> ws) = 0;
 
-    virtual bool hasData(const std::string& wsName,
-                         const boost::shared_ptr<Mantid::API::Workspace> ws) = 0;
+  /// Get the smallest 'x' value covered by the data
+  virtual double getXMin();
 
-    /// Get the smallest 'x' value covered by the data
-    virtual double getXMin();
+  /// Get the largest 'x' value covered by the data
+  virtual double getXMax();
 
-    /// Get the largest 'x' value covered by the data
-    virtual double getXMax();
+  /// Get the smallest 'y' value covered by the data
+  virtual double getYMin();
 
-    /// Get the smallest 'y' value covered by the data
-    virtual double getYMin();
+  /// Get the largest 'y' value covered by the data
+  virtual double getYMax();
 
-    /// Get the largest 'y' value covered by the data
-    virtual double getYMax();
+  /// Get the total number of rows of data
+  virtual size_t getNRows();
 
-    /// Get the total number of rows of data
-    virtual size_t getNRows();
+  /// Get the total number of columns of data
+  virtual size_t getNCols();
 
-    /// Get the total number of columns of data
-    virtual size_t getNCols();
+  /// Clamp x to the interval of x-values covered by this DataSource
+  virtual void restrictX(double &x);
 
-    /// Clamp x to the interval of x-values covered by this DataSource
-    virtual void restrictX( double & x );
+  /// Clamp y to the interval of y-values covered by this DataSource
+  virtual void restrictY(double &y);
 
-    /// Clamp y to the interval of y-values covered by this DataSource
-    virtual void restrictY( double & y );
+  /// Clamp row to a valid row number for this DataSource
+  virtual void restrictRow(int &row);
 
-    /// Clamp row to a valid row number for this DataSource
-    virtual void restrictRow( int & row );
+  /// Clamp col to a valid column number for this dataSource
+  virtual void restrictCol(int &col);
 
-    /// Clamp col to a valid column number for this dataSource
-    virtual void restrictCol( int & col );
+  /// Get a DataArray roughly spaning the specified rectangle.  NOTE: The
+  /// actual size and number of steps returned in the DataArray will be
+  /// adjusted to match the underlying data.
+  virtual DataArray_const_sptr getDataArray(double xMin, double xMax,
+                                            double yMin, double yMax,
+                                            size_t nRows, size_t nCols,
+                                            bool isLogX) = 0;
 
-    /// Get a DataArray roughly spaning the specified rectangle.  NOTE: The
-    /// actual size and number of steps returned in the DataArray will be
-    /// adjusted to match the underlying data.
-    virtual DataArray_const_sptr getDataArray( double  xMin,
-                                               double  xMax,
-                                               double  yMin,
-                                               double  yMax,
-                                               size_t  nRows,
-                                               size_t  nCols,
-                                               bool    isLogX ) = 0;
+  /// Convenience method to get data covering the full range at max resolution
+  virtual DataArray_const_sptr getDataArray(bool is_log_x);
 
-    /// Convenience method to get data covering the full range at max resolution
-    virtual DataArray_const_sptr getDataArray( bool is_log_x );
-
-    /// Get list of pairs of strings with info about the data at location x, y
-    virtual std::vector<std::string> getInfoList(double x, double y) = 0;
-
-  protected:
-    double m_totalXMin;
-    double m_totalXMax;
-    double m_totalYMin;
-    double m_totalYMax;
-    size_t m_totalRows;
-    size_t m_totalCols;
+  /// Get list of pairs of strings with info about the data at location x, y
+  virtual std::vector<std::string> getInfoList(double x, double y) = 0;
 
+protected:
+  double m_totalXMin;
+  double m_totalXMax;
+  double m_totalYMin;
+  double m_totalYMax;
+  size_t m_totalRows;
+  size_t m_totalCols;
 };
 
 typedef boost::shared_ptr<SpectrumDataSource> SpectrumDataSource_sptr;
-typedef boost::shared_ptr<const SpectrumDataSource> SpectrumDataSource_const_sptr;
+typedef boost::shared_ptr<const SpectrumDataSource>
+    SpectrumDataSource_const_sptr;
 
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDisplay.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDisplay.h
index acc6a2fb2321dd4c8334d4f444aea1a003f09f01..8e0828aef72465eec753d10b1fc0f92b7dfec91c 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDisplay.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumDisplay.h
@@ -1,5 +1,5 @@
-#ifndef  SPECTRUM_DISPLAY_H
-#define  SPECTRUM_DISPLAY_H
+#ifndef SPECTRUM_DISPLAY_H
+#define SPECTRUM_DISPLAY_H
 
 #include <QColor>
 #include <QPoint>
@@ -45,137 +45,132 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 class TrackingPicker;
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumDisplay: public QObject
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumDisplay : public QObject {
+  Q_OBJECT
 
-  public:
+public:
+  /// Make an SpectrumDisplay to display with the given widgets and controls
+  SpectrumDisplay(QwtPlot *spectrumPlot, ISliderHandler *sliderHandler,
+                  IRangeHandler *rangeHandler, GraphDisplay *hGraph,
+                  GraphDisplay *vGraph, QTableWidget *tableWidget,
+                  bool isTrackingOn = true);
 
-     /// Make an SpectrumDisplay to display with the given widgets and controls
-     SpectrumDisplay( QwtPlot*        spectrumPlot,
-                      ISliderHandler* sliderHandler,
-                      IRangeHandler*  rangeHandler,
-                      GraphDisplay*   hGraph,
-                      GraphDisplay*   vGraph,
-                      QTableWidget*   tableWidget,
-                      bool            isTrackingOn = true);
+  ~SpectrumDisplay() override;
 
-     ~SpectrumDisplay() override;
+  virtual bool hasData(const std::string &wsName,
+                       const boost::shared_ptr<Mantid::API::Workspace> ws);
 
-     virtual bool hasData(const std::string &wsName,
-                          const boost::shared_ptr<Mantid::API::Workspace> ws);
+  /// Set some properties of the SpectrumPlotItem object
+  void setupSpectrumPlotItem();
 
-     /// Set some properties of the SpectrumPlotItem object
-     void setupSpectrumPlotItem();
+  /// Set the source of the image data and information for the table
+  void setDataSource(SpectrumDataSource_sptr dataSource);
 
-     /// Set the source of the image data and information for the table
-     void setDataSource( SpectrumDataSource_sptr dataSource );
+  /// Rebuild the scroll bars and image due to change of xmin, xmax, step
+  void updateRange();
 
-     /// Rebuild the scroll bars and image due to change of xmin, xmax, step
-     void updateRange();
+  /// Updates scroll bars when window is resized
+  void handleResize();
 
-     /// Updates scroll bars when window is resized
-     void handleResize();
+  /// Rebuild image from data source, due to resize or scroll bar movement
+  void updateImage();
 
-     /// Rebuild image from data source, due to resize or scroll bar movement
-     void updateImage();
+  /// Change the color tables used to map intensity to color
+  void setColorScales(std::vector<QRgb> &positiveColorTable,
+                      std::vector<QRgb> &negativeColorTable);
 
-     /// Change the color tables used to map intensity to color
-     void setColorScales( std::vector<QRgb> & positiveColorTable,
-                          std::vector<QRgb> & negativeColorTable );
+  /// Change the control parameter (0...100) used to brighten the image
+  void setIntensity(double controlParameter);
 
-     /// Change the control parameter (0...100) used to brighten the image
-     void setIntensity( double controlParameter );
+  /// Record the point that the user is currently pointing at with the mouse
+  virtual QPair<double, double>
+  setPointedAtPoint(QPoint point, int mouseClick = 2, bool isFront = true);
 
-     /// Record the point that the user is currently pointing at with the mouse
-     virtual QPair<double,double> setPointedAtPoint( QPoint point, int mouseClick = 2, bool isFront = true);
+  /// Record the point that the user is currently pointing in the scales
+  /// coordinates
+  virtual void setPointedAtXY(double x, double y, bool isFront = true);
 
-     /// Record the point that the user is currently pointing in the scales coordinates
-     virtual void setPointedAtXY( double x, double y, bool isFront = true );
+  /// Set horizontal graph wit data from the array at the specified y value
+  void setHGraph(double y, bool isFront = true);
 
-     /// Set horizontal graph wit data from the array at the specified y value
-     void setHGraph( double y, bool isFront = true );
+  /// Set vertical graph with data from the array at the specified x value
+  void setVGraph(double x, bool isFront = true);
 
-     /// Set vertical graph with data from the array at the specified x value
-     void setVGraph( double x, bool isFront = true );
+  /// Show information about the point (x, y) on the image in the table
+  std::vector<std::string> showInfoList(double x, double y);
 
-     /// Show information about the point (x, y) on the image in the table
-     std::vector<std::string> showInfoList( double x, double y );
+  /// Gets a point on the graph area for a set of axis values
+  QPoint getPlotTransform(QPair<double, double> values);
 
-     /// Gets a point on the graph area for a set of axis values
-     QPoint getPlotTransform( QPair<double, double> values );
+  /// Gets a set of axis values for a point on the graph area
+  QPair<double, double> getPlotInvTransform(QPoint point);
 
-     /// Gets a set of axis values for a point on the graph area
-     QPair<double, double> getPlotInvTransform( QPoint point );
+  // Gets the X value pointed at
+  double getPointedAtX();
 
-     // Gets the X value pointed at
-     double getPointedAtX();
+  // Gets the Y value pointed at
+  double getPointedAtY();
 
-     // Gets the Y value pointed at
-     double getPointedAtY();
+  QwtPlot *spectrumPlot() const { return m_spectrumPlot; }
 
-     QwtPlot* spectrumPlot() const {return m_spectrumPlot;}
+  void addOther(const boost::shared_ptr<SpectrumDisplay> &other);
+  void addOthers(const QList<boost::shared_ptr<SpectrumDisplay>> &others);
+  void removeOther(const boost::shared_ptr<SpectrumDisplay> &other);
 
-     void addOther(const boost::shared_ptr<SpectrumDisplay>& other);
-     void addOthers(const QList<boost::shared_ptr<SpectrumDisplay>>& others);
-     void removeOther(const boost::shared_ptr<SpectrumDisplay>& other);
+  void setTrackingOn(bool on);
 
-     void setTrackingOn(bool on);
+protected:
+  SpectrumPlotItem *m_spectrumPlotItem;
 
-  protected:
-     SpectrumPlotItem*    m_spectrumPlotItem;
+private slots:
 
-  private slots:
+  void imagePickerMoved(const QPoint &point);
 
-    void imagePickerMoved(const QPoint &point);
+private:
+  /// Check if the DataSource has been changed under us
+  bool dataSourceRangeChanged();
 
-  private:
-     /// Check if the DataSource has been changed under us
-     bool dataSourceRangeChanged();
+  /// Get the rectangle currently covered by the image in pixel coordinates
+  void getDisplayRectangle(QRect &rect);
 
-     /// Get the rectangle currently covered by the image in pixel coordinates
-     void getDisplayRectangle( QRect &rect );
+  std::vector<QRgb> m_positiveColorTable;
+  std::vector<QRgb> m_negativeColorTable;
+  std::vector<double> m_intensityTable;
 
-     std::vector<QRgb> m_positiveColorTable;
-     std::vector<QRgb> m_negativeColorTable;
-     std::vector<double> m_intensityTable;
+  SpectrumDataSource_sptr m_dataSource;
+  DataArray_const_sptr m_dataArray;
 
-     SpectrumDataSource_sptr m_dataSource;
-     DataArray_const_sptr m_dataArray;
+  QwtPlot *m_spectrumPlot;
 
-     QwtPlot* m_spectrumPlot;
+  ISliderHandler *m_sliderHandler;
+  IRangeHandler *m_rangeHandler;
 
-     ISliderHandler* m_sliderHandler;
-     IRangeHandler* m_rangeHandler;
+  GraphDisplay *m_hGraphDisplay;
+  GraphDisplay *m_vGraphDisplay;
 
-     GraphDisplay* m_hGraphDisplay;
-     GraphDisplay* m_vGraphDisplay;
+  double m_pointedAtX;
+  double m_pointedAtY;
 
-     double m_pointedAtX;
-     double m_pointedAtY;
+  /* Save current total data range */
+  /* so we can reset the data source */
+  /* if we detect a change of range */
+  QTableWidget *m_imageTable;
 
-     /* Save current total data range */
-     /* so we can reset the data source */
-     /* if we detect a change of range */
-     QTableWidget* m_imageTable;
+  double m_totalXMin;
+  double m_totalXMax;
+  double m_totalYMin;
+  double m_totalYMax;
 
-     double m_totalXMin;
-     double m_totalXMax;
-     double m_totalYMin;
-     double m_totalYMax;
-
-     QList<boost::weak_ptr<SpectrumDisplay>> m_otherDisplays;
-     TrackingPicker* m_imagePicker;
+  QList<boost::weak_ptr<SpectrumDisplay>> m_otherDisplays;
+  TrackingPicker *m_imagePicker;
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif   // SPECTRUM_DISPLAY_H
+#endif // SPECTRUM_DISPLAY_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumPlotItem.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumPlotItem.h
index 3e7e297a7cbc3c233a50f3e063ab0392f5938c00..319191081372612c7c6d3da593288bd499b6cc8f 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumPlotItem.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumPlotItem.h
@@ -40,49 +40,44 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumPlotItem : public QwtPlotItem
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumPlotItem : public QwtPlotItem {
 
 public:
-
   /// Construct basic plot item with NO data to plot.
   SpectrumPlotItem();
 
   ~SpectrumPlotItem() override;
 
   /// Specify the data to be plotted and the color table to use
-  void setData( DataArray_const_sptr dataArray,
-                std::vector<QRgb>* positiveColorTable,
-                std::vector<QRgb>* negativeColorTable );
+  void setData(DataArray_const_sptr dataArray,
+               std::vector<QRgb> *positiveColorTable,
+               std::vector<QRgb> *negativeColorTable);
 
   /// Set a non-linear lookup table to scale data values before mapping to color
-  void setIntensityTable( std::vector<double>*  intensityTable );
+  void setIntensityTable(std::vector<double> *intensityTable);
 
   /// Draw the image (this is called by QWT and must not be called directly.)
   void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
             const QRect &canvasRect) const override;
 
 protected:
-  int m_bufferID;       // set to 0 or 1 to select buffer
-  DataArray_const_sptr m_dataArray0;     // these provide double buffers
-  DataArray_const_sptr m_dataArray1;     // for the float data.
+  int m_bufferID;                    // set to 0 or 1 to select buffer
+  DataArray_const_sptr m_dataArray0; // these provide double buffers
+  DataArray_const_sptr m_dataArray1; // for the float data.
 
 private:
   /* This class just uses the following */
   /* but they are created and deleted */
   /* in the upper level classes */
-  std::vector<QRgb>   * m_positiveColorTable;
-  std::vector<QRgb>   * m_negativeColorTable;
-  std::vector<double> * m_intensityTable;
-
+  std::vector<QRgb> *m_positiveColorTable;
+  std::vector<QRgb> *m_negativeColorTable;
+  std::vector<double> *m_intensityTable;
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif  // SPECTRUM_PLOT_ITEM_H
+#endif // SPECTRUM_PLOT_ITEM_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumView.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumView.h
index 3b55a5b00b2425c924fecfda4862f1e6c28b85f7..50a37861a053269d71f4f65b72edd0c4f8072275 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumView.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/SpectrumView.h
@@ -1,5 +1,5 @@
-#ifndef  SPECTRUM_VIEW_H
-#define  SPECTRUM_VIEW_H
+#ifndef SPECTRUM_VIEW_H
+#define SPECTRUM_VIEW_H
 
 #include <QMainWindow>
 #include <QMdiSubWindow>
@@ -44,15 +44,12 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace Ui
-{
+namespace Ui {
 class SpectrumViewer; // Forward declaration of UI file
 }
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 // Forward declarations
 class EModeHandler;
@@ -62,21 +59,24 @@ class SpectrumDisplay;
 class SVConnections;
 class MatrixWSDataSource;
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumView : public QMainWindow, public MantidQt::API::WorkspaceObserver
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER SpectrumView
+    : public QMainWindow,
+      public MantidQt::API::WorkspaceObserver {
   Q_OBJECT
 
 public:
   /// Construct a SpectrumView to display data from the specified data source
-  SpectrumView( QWidget * parent = 0 );
+  SpectrumView(QWidget *parent = 0);
 
   ~SpectrumView() override;
   void renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp);
-  QList<boost::shared_ptr<SpectrumDisplay>> getSpectrumDisplays() const { return m_spectrumDisplay; }
+  QList<boost::shared_ptr<SpectrumDisplay>> getSpectrumDisplays() const {
+    return m_spectrumDisplay;
+  }
   bool isTrackingOn() const;
 
 signals:
-  void spectrumDisplayChanged(SpectrumDisplay*);
+  void spectrumDisplayChanged(SpectrumDisplay *);
 
 protected slots:
   void closeWindow();
@@ -108,11 +108,10 @@ private:
   boost::shared_ptr<GraphDisplay> m_vGraph;
   boost::shared_ptr<SVConnections> m_svConnections;
 
-
   Ui::SpectrumViewer *m_ui;
-  SliderHandler      *m_sliderHandler;
-  RangeHandler       *m_rangeHandler;
-  EModeHandler       *m_emodeHandler;
+  SliderHandler *m_sliderHandler;
+  RangeHandler *m_rangeHandler;
+  EModeHandler *m_emodeHandler;
 
 signals:
   void needToClose();
@@ -122,4 +121,4 @@ signals:
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif   // SPECTRUM_VIEW_H
+#endif // SPECTRUM_VIEW_H
diff --git a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/TrackingPicker.h b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/TrackingPicker.h
index 7b97c6a4a7f2220ecfbd420643dd66b4befcd4d0..99e34e1d1af738efffbce28cba0af87f3a61ef6f 100644
--- a/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/TrackingPicker.h
+++ b/MantidQt/SpectrumViewer/inc/MantidQtSpectrumViewer/TrackingPicker.h
@@ -35,41 +35,35 @@
                  <http://doxygen.mantidproject.org>
  */
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
-class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER TrackingPicker : public QwtPlotPicker
-{
+class EXPORT_OPT_MANTIDQT_SPECTRUMVIEWER TrackingPicker : public QwtPlotPicker {
   Q_OBJECT
 
 public:
-
   /// Construct a tracking picker to work with the specified canvas
-  TrackingPicker(QwtPlotCanvas* canvas);
+  TrackingPicker(QwtPlotCanvas *canvas);
 
   /// Disable (or enable) position readout at cursor position, even if
   /// tracking is ON.  Tracking MUST be on for the mouseMoved signal to be
   /// emitted.
-  void hideReadout( bool hide );
+  void hideReadout(bool hide);
 
 signals:
   /// This signal will be emitted for each mouse moved event
-  void mouseMoved(const QPoint & point) const;
+  void mouseMoved(const QPoint &point) const;
 
 protected:
-
   /// Override base class method, to emit a mousedMoved() signal for each move
   QwtText trackerText(const QPoint &point) const override;
   QwtText trackerText(const QwtDoublePoint &pos) const override;
 
 private:
   bool m_hideReadout;
-
 };
 
 } // namespace SpectrumView
 } // namespace MantidQt
 
-#endif  // TRACKING_PICKER_H
+#endif // TRACKING_PICKER_H
diff --git a/MantidQt/SpectrumViewer/src/ArrayDataSource.cpp b/MantidQt/SpectrumViewer/src/ArrayDataSource.cpp
index e17ccbc2e22ab5f4e9748d169dc6d7746fdba71c..50d456efbb9a1b0b9e93a8161b5654c7480f2d0b 100644
--- a/MantidQt/SpectrumViewer/src/ArrayDataSource.cpp
+++ b/MantidQt/SpectrumViewer/src/ArrayDataSource.cpp
@@ -4,10 +4,8 @@
 #include "MantidQtSpectrumViewer/ArrayDataSource.h"
 #include "MantidQtSpectrumViewer/SVUtils.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Construct a DataSource object to to display data from the specified
@@ -29,25 +27,19 @@ namespace SpectrumView
  * @param data         The list of floats holding the data to be displayed,
  *                     stored in row major order.
  */
-ArrayDataSource::ArrayDataSource( double m_totalXMin, double m_totalXMax,
-                                  double m_totalYMin, double m_totalYMax,
-                                  size_t m_totalRows, size_t m_totalCols,
-                                  std::vector<float> data ) :
-  SpectrumDataSource( m_totalXMin, m_totalXMax,
-                      m_totalYMin, m_totalYMax,
-                      m_totalRows, m_totalCols ),
-  m_data(data)
-{
-}
-
-
-ArrayDataSource::~ArrayDataSource()
-{
-}
-
-bool ArrayDataSource::hasData(const std::string& wsName,
-                              const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
+ArrayDataSource::ArrayDataSource(double m_totalXMin, double m_totalXMax,
+                                 double m_totalYMin, double m_totalYMax,
+                                 size_t m_totalRows, size_t m_totalCols,
+                                 std::vector<float> data)
+    : SpectrumDataSource(m_totalXMin, m_totalXMax, m_totalYMin, m_totalYMax,
+                         m_totalRows, m_totalCols),
+      m_data(data) {}
+
+ArrayDataSource::~ArrayDataSource() {}
+
+bool ArrayDataSource::hasData(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
   UNUSED_ARG(wsName);
   UNUSED_ARG(ws);
   return false;
@@ -73,18 +65,17 @@ bool ArrayDataSource::hasData(const std::string& wsName,
  *                  DataSource does not support rebinning to a log axis, so
  *                  the DataArray is always returned with isLogX = false.
  */
-DataArray_const_sptr ArrayDataSource::getDataArray( double xMin,   double  xMax,
-                                                    double yMin,   double  yMax,
-                                                    size_t nRows,  size_t  nCols,
-                                                    bool   isLogX )
-{
+DataArray_const_sptr ArrayDataSource::getDataArray(double xMin, double xMax,
+                                                   double yMin, double yMax,
+                                                   size_t nRows, size_t nCols,
+                                                   bool isLogX) {
   size_t firstCol;
-  SVUtils::CalculateInterval( m_totalXMin, m_totalXMax, m_totalCols,
-                              firstCol, xMin, xMax, nCols );
+  SVUtils::CalculateInterval(m_totalXMin, m_totalXMax, m_totalCols, firstCol,
+                             xMin, xMax, nCols);
 
   size_t firstRow;
-  SVUtils::CalculateInterval( m_totalYMin, m_totalYMax, m_totalRows,
-                              firstRow, yMin, yMax, nRows );
+  SVUtils::CalculateInterval(m_totalYMin, m_totalYMax, m_totalRows, firstRow,
+                             yMin, yMax, nRows);
 
   std::vector<float> newData(nRows * nCols);
 
@@ -97,18 +88,16 @@ DataArray_const_sptr ArrayDataSource::getDataArray( double xMin,   double  xMax,
 
   /* Get data for middle of */
   /* each destination position */
-  for ( size_t row = 0; row < nRows; row++ )
-  {
+  for (size_t row = 0; row < nRows; row++) {
     double midY = yMin + ((double)row + 0.5) * yStep;
-    SVUtils::Interpolate( m_totalYMin, m_totalYMax,         midY,
-                          0.0,         (double)m_totalRows, yIndex );
+    SVUtils::Interpolate(m_totalYMin, m_totalYMax, midY, 0.0,
+                         (double)m_totalRows, yIndex);
 
     size_t sourceRow = (size_t)yIndex;
-    for ( size_t col = 0; col < nCols; col++ )
-    {
+    for (size_t col = 0; col < nCols; col++) {
       double midX = xMin + ((double)col + 0.5) * xStep;
-      SVUtils::Interpolate( m_totalXMin, m_totalXMax,         midX,
-                            0.0,         (double)m_totalCols, xIndex );
+      SVUtils::Interpolate(m_totalXMin, m_totalXMax, midX, 0.0,
+                           (double)m_totalCols, xIndex);
 
       size_t sourceCol = (size_t)xIndex;
 
@@ -119,12 +108,11 @@ DataArray_const_sptr ArrayDataSource::getDataArray( double xMin,   double  xMax,
 
   // The calling code is responsible for deleting the DataArray
   isLogX = false;
-  DataArray_const_sptr newDataArray( new DataArray( xMin, xMax, yMin, yMax,
-                                           isLogX, nRows, nCols, newData) );
+  DataArray_const_sptr newDataArray(
+      new DataArray(xMin, xMax, yMin, yMax, isLogX, nRows, nCols, newData));
   return newDataArray;
 }
 
-
 /**
  * Get a data array covering the full range of data.
  * NOTE: The calling code is responsible for deleting the DataArray that is
@@ -135,14 +123,12 @@ DataArray_const_sptr ArrayDataSource::getDataArray( double xMin,   double  xMax,
  *                support rebinning to a log axis, so the DataArray is
  *                always returned with isLogX = false.
  */
-DataArray_const_sptr ArrayDataSource::getDataArray( bool isLogX )
-{
+DataArray_const_sptr ArrayDataSource::getDataArray(bool isLogX) {
   isLogX = false;
-  return getDataArray( m_totalXMin, m_totalXMax, m_totalYMin, m_totalYMax,
-                       m_totalRows, m_totalCols, isLogX );
+  return getDataArray(m_totalXMin, m_totalXMax, m_totalYMin, m_totalYMax,
+                      m_totalRows, m_totalCols, isLogX);
 }
 
-
 /**
  * Clear the vector of strings and then add pairs of strings giving information
  * about the specified point, x, y.  The first string in a pair should
@@ -156,8 +142,8 @@ DataArray_const_sptr ArrayDataSource::getDataArray( bool isLogX )
 std::vector<std::string> ArrayDataSource::getInfoList(double x, double y) {
   std::vector<std::string> list;
 
-  SVUtils::PushNameValue( "X", 8, 3, x, list );
-  SVUtils::PushNameValue( "Y", 8, 3, y, list );
+  SVUtils::PushNameValue("X", 8, 3, x, list);
+  SVUtils::PushNameValue("Y", 8, 3, y, list);
   return list;
 }
 
diff --git a/MantidQt/SpectrumViewer/src/ColorMaps.cpp b/MantidQt/SpectrumViewer/src/ColorMaps.cpp
index 118038c8ebb98ac7215637b6d7b87b507b473b4d..ed5b8f3d2da1adb9c51262f8fb3e58171fd83234 100644
--- a/MantidQt/SpectrumViewer/src/ColorMaps.cpp
+++ b/MantidQt/SpectrumViewer/src/ColorMaps.cpp
@@ -4,10 +4,8 @@
 
 #include "MantidQtSpectrumViewer/ColorMaps.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Get a color map of the specified type, with the specified number of
@@ -108,41 +106,35 @@ std::vector<double> ColorMaps::GetIntensityMap(double control_s,
                                                size_t n_entries) {
 
   std::vector<double> intensity_table;
-  intensity_table.resize( n_entries );
-                                        // restrict control range to [0,100]
+  intensity_table.resize(n_entries);
+  // restrict control range to [0,100]
   double MAX_CONTROL = 100.0;
-  if ( control_s > MAX_CONTROL )
-  {
+  if (control_s > MAX_CONTROL) {
     control_s = MAX_CONTROL;
-  }
-  else if ( control_s < 0.0 )
-  {
+  } else if (control_s < 0.0) {
     control_s = 0.0;
   }
 
-  if ( control_s == 0.0 )                // just use linear scale, 0 -> 1
+  if (control_s == 0.0) // just use linear scale, 0 -> 1
   {
-    for ( size_t i = 0; i < n_entries; i++ )
-    {
+    for (size_t i = 0; i < n_entries; i++) {
       intensity_table[i] = (double)i / (double)(n_entries - 1);
     }
-  }
-  else                                   // build log-shaped correction scale
+  } else // build log-shaped correction scale
   {
-                                         // first map control value
-                                         // exponentially to make the control
-                                         // parameter act more linearly
-    double s     = exp( 20.0 * control_s / MAX_CONTROL ) + 0.1;
-    double scale = 1.0 / log( s );
-    for ( size_t i = 0; i < n_entries - 1; i++ )
-    {
+    // first map control value
+    // exponentially to make the control
+    // parameter act more linearly
+    double s = exp(20.0 * control_s / MAX_CONTROL) + 0.1;
+    double scale = 1.0 / log(s);
+    for (size_t i = 0; i < n_entries - 1; i++) {
       intensity_table[i] = scale * log1p((s - 1.0) * static_cast<double>(i) /
                                          static_cast<double>(n_entries - 1));
     }
-    intensity_table[n_entries - 1] = 1.0;  // this could have been calculated
-                                           // by running the loop one step
-                                           // further, but due to rounding
-                                           // errors, it might exceed 1.
+    intensity_table[n_entries - 1] = 1.0; // this could have been calculated
+                                          // by running the loop one step
+                                          // further, but due to rounding
+                                          // errors, it might exceed 1.
   }
   return intensity_table;
 }
@@ -174,39 +166,37 @@ std::vector<QRgb> ColorMaps::InterpolateColorScale(double base_red[],
                                                    size_t n_base_colors,
                                                    size_t n_colors) {
   std::vector<QRgb> color_table;
-  color_table.resize( n_colors );
-                                      // first output color is first base color
-  color_table[0] = qRgb( (unsigned char)base_red[0],
-                         (unsigned char)base_green[0],
-                         (unsigned char)base_blue[0]  );
+  color_table.resize(n_colors);
+  // first output color is first base color
+  color_table[0] =
+      qRgb((unsigned char)base_red[0], (unsigned char)base_green[0],
+           (unsigned char)base_blue[0]);
 
-                                      // last output color is last base color
+  // last output color is last base color
   size_t last_out = n_colors - 1;
-  size_t last_in  = n_base_colors - 1;
-  color_table[last_out] = qRgb( (unsigned char)base_red[last_in],
-                                (unsigned char)base_green[last_in],
-                                (unsigned char)base_blue[last_in]  );
+  size_t last_in = n_base_colors - 1;
+  color_table[last_out] =
+      qRgb((unsigned char)base_red[last_in], (unsigned char)base_green[last_in],
+           (unsigned char)base_blue[last_in]);
 
-                                       // interpolate remaining output colors
-  for ( size_t i = 1; i < last_out; i++ )
-  {
-                                      // fraction of way along output indices
+  // interpolate remaining output colors
+  for (size_t i = 1; i < last_out; i++) {
+    // fraction of way along output indices
     double t_out = (double)i / (double)last_out;
 
     double float_index = t_out * (double)last_in;
-                                          // corresponding "floating point"
-                                          // index in array of input colors
+    // corresponding "floating point"
+    // index in array of input colors
     int base_index = (int)float_index;
 
     double t = float_index - (double)base_index;
 
-    color_table[i] = qRgb(
-                     (unsigned char) ( (1.0-t) * base_red[base_index]+
-                                          t    * base_red[base_index + 1] ),
-                     (unsigned char) ( (1.0-t) * base_green[base_index]+
-                                          t    * base_green[base_index + 1] ),
-                     (unsigned char) ( (1.0-t) * base_blue[base_index]+
-                                          t    * base_blue[base_index + 1] ) );
+    color_table[i] = qRgb((unsigned char)((1.0 - t) * base_red[base_index] +
+                                          t * base_red[base_index + 1]),
+                          (unsigned char)((1.0 - t) * base_green[base_index] +
+                                          t * base_green[base_index + 1]),
+                          (unsigned char)((1.0 - t) * base_blue[base_index] +
+                                          t * base_blue[base_index + 1]));
   }
   return color_table;
 }
diff --git a/MantidQt/SpectrumViewer/src/DataArray.cpp b/MantidQt/SpectrumViewer/src/DataArray.cpp
index e3c58c8b73203f83d7f76378c28678db3bd9b482..425fe04d7de1340c56d108f8d58456455a741a5e 100644
--- a/MantidQt/SpectrumViewer/src/DataArray.cpp
+++ b/MantidQt/SpectrumViewer/src/DataArray.cpp
@@ -6,10 +6,8 @@
 
 #include "MantidQtSpectrumViewer/DataArray.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Construct a DataArray "wrapper" around the data and region info.  The
@@ -31,31 +29,23 @@ namespace SpectrumView
  * @param data       Pointer to start of memory block holding the actual
  *                   data as a list of floats.
  */
-DataArray::DataArray( double xMin,     double xMax,
-                      double yMin,     double yMax,
-                      bool   isLogX,
-                      size_t nRows,    size_t nCols,
-                      const std::vector<float>& data ):
-  m_xMin(xMin), m_xMax(xMax),
-  m_yMin(yMin), m_yMax(yMax),
-  m_isLogX(isLogX),
-  m_nRows(nRows), m_nCols(nCols),
-  m_dataMin(data[0]), m_dataMax(data[0]),
-  m_data(data)
-{
+DataArray::DataArray(double xMin, double xMax, double yMin, double yMax,
+                     bool isLogX, size_t nRows, size_t nCols,
+                     const std::vector<float> &data)
+    : m_xMin(xMin), m_xMax(xMax), m_yMin(yMin), m_yMax(yMax), m_isLogX(isLogX),
+      m_nRows(nRows), m_nCols(nCols), m_dataMin(data[0]), m_dataMax(data[0]),
+      m_data(data) {
   double value;
   size_t index = 0;
 
-  for ( size_t row = 0; row < nRows; row++ )
-  {
-    for ( size_t col = 0; col < nCols; col++ )
-    {
+  for (size_t row = 0; row < nRows; row++) {
+    for (size_t col = 0; col < nCols; col++) {
       value = data[index];
 
-      if ( value < m_dataMin )
+      if (value < m_dataMin)
         m_dataMin = value;
 
-      else if ( value > m_dataMax )
+      else if (value > m_dataMax)
         m_dataMax = value;
 
       index++;
@@ -63,97 +53,60 @@ DataArray::DataArray( double xMin,     double xMax,
   }
 }
 
-DataArray::~DataArray()
-{
-}
+DataArray::~DataArray() {}
 
 /**
  * Get the value corresponding to the left edge of the array.
  */
-double DataArray::getXMin() const
-{
-  return m_xMin;
-}
+double DataArray::getXMin() const { return m_xMin; }
 
 /**
  * Get the value corresponding to the right edge of the array.
  */
-double DataArray::getXMax() const
-{
-  return m_xMax;
-}
+double DataArray::getXMax() const { return m_xMax; }
 
 /**
  * Get the value corresponding to the bottom edge of the array (outer edge
  * of first row).
  */
-double DataArray::getYMin() const
-{
-  return m_yMin;
-}
+double DataArray::getYMin() const { return m_yMin; }
 
 /**
  * Get the value corresponding to the top edge of the array (outer edge
  * of last row).
  */
-double DataArray::getYMax() const
-{
-  return m_yMax;
-}
+double DataArray::getYMax() const { return m_yMax; }
 
 /**
  * Check if the returned array is binned logarithmically in 'x'.
  */
-bool DataArray::isLogX() const
-{
-  return m_isLogX;
-}
+bool DataArray::isLogX() const { return m_isLogX; }
 
 /**
  * Get smallest value recorded in this DataArray
  */
-double DataArray::getDataMin() const
-{
-  return m_dataMin;
-}
-
+double DataArray::getDataMin() const { return m_dataMin; }
 
 /**
  * Get largest value recorded in this DataArray
  */
-double DataArray::getDataMax() const
-{
-  return m_dataMax;
-}
-
+double DataArray::getDataMax() const { return m_dataMax; }
 
 /**
  * Get the actual number of rows in this DataArray
  *
  */
-size_t DataArray::getNRows() const
-{
-  return m_nRows;
-}
-
+size_t DataArray::getNRows() const { return m_nRows; }
 
 /**
  * Get the actual number of columns in this DataArray
  */
-size_t DataArray::getNCols() const
-{
-  return m_nCols;
-}
-
+size_t DataArray::getNCols() const { return m_nCols; }
 
 /**
  * Get the list of all values, packed in a 1-D array, in row-major order
  */
-std::vector<float> DataArray::getData() const
-{
-  return m_data;
-}
-
+std::vector<float> DataArray::getData() const { return m_data; }
 
 /**
  * Get the value at the specified row and column.  If the row or column
@@ -165,24 +118,22 @@ std::vector<float> DataArray::getData() const
  * @param col Columns of data to get
  * @returns Data at [row,col]
  */
-double DataArray::getValue( int row, int col ) const
-{
-  if ( row < 0 )
+double DataArray::getValue(int row, int col) const {
+  if (row < 0)
     row = 0;
 
-  if ( row > (int)m_nRows - 1 )
+  if (row > (int)m_nRows - 1)
     row = (int)m_nRows - 1;
 
-  if ( col < 0 )
+  if (col < 0)
     col = 0;
 
-  if ( col > (int)m_nCols - 1 )
+  if (col > (int)m_nCols - 1)
     col = (int)m_nCols - 1;
 
-  return m_data[ row * m_nCols + col ];
+  return m_data[row * m_nCols + col];
 }
 
-
 /**
  * Get the value from the row and column containing the specified point.
  * If the specified point (x,y) is off the edge of the array, a value
@@ -192,72 +143,62 @@ double DataArray::getValue( int row, int col ) const
  * @param y Y value of data to get
  * @returns Data at [x,y]
  */
-double DataArray::getValue( double x, double y ) const
-{
-  size_t col = columnOfX( x );
-  size_t row = rowOfY( y );
+double DataArray::getValue(double x, double y) const {
+  size_t col = columnOfX(x);
+  size_t row = rowOfY(y);
 
-  return getValue( (int)row, (int)col );
+  return getValue((int)row, (int)col);
 }
 
-
 /**
  * Clamp x to the interval of x-values covered by this DataArray.
  *
  * @param x If x is more than xmax it will be set to xmax. If x is less
  *          than xmin, it will be set to xmin.
  */
-void DataArray::restrictX( double & x ) const
-{
-  if ( x > m_xMax )
+void DataArray::restrictX(double &x) const {
+  if (x > m_xMax)
     x = m_xMax;
-  else if ( x < m_xMin )
+  else if (x < m_xMin)
     x = m_xMin;
 }
 
-
 /**
  * Clamp y to the interval of y-values covered by this DataArray.
  * @param y   If y is more than ymax it will be set to ymax. If y is less
  *            than ymin, it will be set to ymin.
  */
-void DataArray::restrictY( double & y ) const
-{
-  if ( y > m_yMax )
+void DataArray::restrictY(double &y) const {
+  if (y > m_yMax)
     y = m_yMax;
-  else if ( y < m_yMin )
+  else if (y < m_yMin)
     y = m_yMin;
 }
 
-
 /**
  * Clamp row to a valid row number for this DataArray.
  * @param row  If row is more than n_rows-1, it is set to n_rows-1.  If
  *             row < 0 it is set to zero.
  */
-void DataArray::restrictRow( int & row ) const
-{
-  if ( row >= (int)m_nRows )
+void DataArray::restrictRow(int &row) const {
+  if (row >= (int)m_nRows)
     row = (int)m_nRows - 1;
-  else if ( row < 0 )
+  else if (row < 0)
     row = 0;
 }
 
-
 /**
  * Clamp col to a valid column number for this DataArray.
  * @param col  If col is more than n_cols-1, it is set to n_cols-1.  If
  *             col < 0 it is set to zero.
  */
-void DataArray::restrictCol( int & col ) const
-{
-  if ( col >= (int)m_nCols )
+void DataArray::restrictCol(int &col) const {
+  if (col >= (int)m_nCols)
     col = (int)m_nCols - 1;
-  else if ( col < 0 )
+  else if (col < 0)
     col = 0;
 }
 
-
 /**
  * Calculate the column number containing the specified x value.  If the
  * specified value is less than xmin, 0 is returned.  If the specified
@@ -270,19 +211,17 @@ void DataArray::restrictCol( int & col ) const
  * @return A valid column number, containing x, if x is in range, or the
  *         first or last column number if x is out of range.
  */
-size_t DataArray::columnOfX( double x ) const
-{
+size_t DataArray::columnOfX(double x) const {
   int col;
-  if ( m_isLogX )
+  if (m_isLogX)
     col = (int)((double)m_nCols * log(x / m_xMin) / log(m_xMax / m_xMin));
   else
     col = (int)((double)m_nCols * (x - m_xMin) / (m_xMax - m_xMin));
 
-  restrictCol( col );
+  restrictCol(col);
   return (size_t)col;
 }
 
-
 /*
  * Calculate the x-value at the center of the specified column.  If the
  * column number is too large, xmax is returned.  If the column number is
@@ -293,19 +232,18 @@ size_t DataArray::columnOfX( double x ) const
  *
  * @return A corresponding x value between xmin and xmax.
  */
-double DataArray::xOfColumn( size_t col ) const
-{
+double DataArray::xOfColumn(size_t col) const {
   double xVal;
-  if ( m_isLogX )
-    xVal = m_xMin * exp(((double)col + 0.5)/(double)m_nCols * log(m_xMax / m_xMin));
+  if (m_isLogX)
+    xVal = m_xMin *
+           exp(((double)col + 0.5) / (double)m_nCols * log(m_xMax / m_xMin));
   else
-    xVal = ((double)col + 0.5)/(double)m_nCols * (m_xMax - m_xMin) + m_xMin;
+    xVal = ((double)col + 0.5) / (double)m_nCols * (m_xMax - m_xMin) + m_xMin;
 
-  restrictX( xVal );
+  restrictX(xVal);
   return xVal;
 }
 
-
 /**
  * Calculate the row number containing the specified y value.  If the
  * specified value is less than ymin, 0 is returned.  If the specified
@@ -316,15 +254,13 @@ double DataArray::xOfColumn( size_t col ) const
  * @return A valid row number, containing y, if y is in range, or the
  *         first or last row number if y is out of range.
  */
-size_t DataArray::rowOfY( double y ) const
-{
+size_t DataArray::rowOfY(double y) const {
   int row = (int)((double)m_nRows * (y - m_yMin) / (m_yMax - m_yMin));
 
-  restrictRow( row );
+  restrictRow(row);
   return (size_t)row;
 }
 
-
 /*
  * Calculate the y-value at the center of the specified row.  If the
  * row number is too large, ymax is returned.  If the row number is
@@ -334,15 +270,13 @@ size_t DataArray::rowOfY( double y ) const
  *
  * @return A corresponding y value between ymin and ymax.
  */
-double DataArray::yOfRow( size_t row ) const
-{
+double DataArray::yOfRow(size_t row) const {
   double yVal;
-  yVal = ((double)row + 0.5)/(double)m_nRows * (m_yMax - m_yMin) + m_yMin;
+  yVal = ((double)row + 0.5) / (double)m_nRows * (m_yMax - m_yMin) + m_yMin;
 
-  restrictY( yVal );
+  restrictY(yVal);
   return yVal;
 }
 
-
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/src/EModeHandler.cpp b/MantidQt/SpectrumViewer/src/EModeHandler.cpp
index 3ec420a5f46b67074a5dc8bb45ff47fbdc32b121..724f37cfc9a3d5f923d4ca7c7be5be0e37a77f5d 100644
--- a/MantidQt/SpectrumViewer/src/EModeHandler.cpp
+++ b/MantidQt/SpectrumViewer/src/EModeHandler.cpp
@@ -6,35 +6,23 @@
 
 #include <QLineEdit>
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("SpectrumView");
+namespace {
+Mantid::Kernel::Logger g_log("SpectrumView");
 }
 
-
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct an EModeHandler object to manage the E Mode and E Fixed controls
  *  in the specified UI
  */
-EModeHandler::EModeHandler( Ui_SpectrumViewer* svUI ):
-  m_svUI(svUI)
-{
-}
-
+EModeHandler::EModeHandler(Ui_SpectrumViewer *svUI) : m_svUI(svUI) {}
 
 /**
  * Get the EMode value (0,1,2) from the GUI.
  */
-int EModeHandler::getEMode()
-{
-  return m_svUI->emode_combo_box->currentIndex();
-}
-
+int EModeHandler::getEMode() { return m_svUI->emode_combo_box->currentIndex(); }
 
 /**
  * Set the EMode to display in the GUI.
@@ -46,39 +34,34 @@ int EModeHandler::getEMode()
  *               NOTE: Any other value will be interpreted as 0
  *               and the gui will not be changed.
  */
-void EModeHandler::setEMode( const int mode )
-{
-  if(mode >= 0 && mode <= 2)
-    m_svUI->emode_combo_box->setCurrentIndex( mode );
+void EModeHandler::setEMode(const int mode) {
+  if (mode >= 0 && mode <= 2)
+    m_svUI->emode_combo_box->setCurrentIndex(mode);
   else
-    g_log.error() << "Mode number invalid: " << QString::number(mode).toStdString() << std::endl;
+    g_log.error() << "Mode number invalid: "
+                  << QString::number(mode).toStdString() << std::endl;
 }
 
 /**
  *  Return the user specified EFixed value, OR 0, if no valid
  *  EFixed value was set.
  */
-double EModeHandler::getEFixed()
-{
+double EModeHandler::getEFixed() {
   QString text = m_svUI->efixed_control->text();
   bool isNumber = false;
   double eFixed = text.toDouble(&isNumber);
-  if(!isNumber)
-  {
+  if (!isNumber) {
     g_log.information("E Fixed is not a NUMBER! Value reset to default.");
     eFixed = 0;
-  }
-  else if ( eFixed < 0 )
-  {
+  } else if (eFixed < 0) {
     g_log.information("E Fixed is negative, Value reset to default.");
     eFixed = 0;
   }
 
-  setEFixed( eFixed );
+  setEFixed(eFixed);
   return eFixed;
 }
 
-
 /**
  *  Set the EFixed value that is displayed in the UI.
  *
@@ -86,18 +69,15 @@ double EModeHandler::getEFixed()
  *                 UI.  This must be positive, or the
  *                 displayed value will be set to zero.
  */
-void EModeHandler::setEFixed( const double eFixed )
-{
+void EModeHandler::setEFixed(const double eFixed) {
   double newValue = eFixed;
-  if ( eFixed < 0 )
-  {
+  if (eFixed < 0) {
     g_log.information("E Fixed is negative, reset to default.");
     newValue = 0;
   }
 
-  QtUtils::SetText( 10, 4, newValue, m_svUI->efixed_control );
+  QtUtils::SetText(10, 4, newValue, m_svUI->efixed_control);
 }
 
-
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/src/GraphDisplay.cpp b/MantidQt/SpectrumViewer/src/GraphDisplay.cpp
index 1df34fa6d7f6ff38850709846306fb7875fddb96..05014cf9c038833f1ddef722e11d5f0ee7b4bba8 100644
--- a/MantidQt/SpectrumViewer/src/GraphDisplay.cpp
+++ b/MantidQt/SpectrumViewer/src/GraphDisplay.cpp
@@ -7,10 +7,8 @@
 #include "MantidQtSpectrumViewer/QtUtils.h"
 #include "MantidQtSpectrumViewer/SVUtils.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 std::vector<QColor> GraphDisplay::g_curveColors;
 
@@ -25,21 +23,14 @@ std::vector<QColor> GraphDisplay::g_curveColors;
  *  @param isVertical  Flag indicating whether this graph displays the
  *                     vertical or horizontal cut through the image.
  */
-GraphDisplay::GraphDisplay( QwtPlot*      graphPlot,
-                            QTableWidget* graphTable,
-                            bool          isVertical ) :
-  m_graphPlot(graphPlot),
-  m_graphTable(graphTable),
+GraphDisplay::GraphDisplay(QwtPlot *graphPlot, QTableWidget *graphTable,
+                           bool isVertical)
+    : m_graphPlot(graphPlot), m_graphTable(graphTable),
 
-  m_isVertical(isVertical),
-  m_isLogX(false),
-  m_imageX(0.0), m_imageY(0.0),
-  m_rangeScale(1.0),
-  m_minX(0.0), m_maxX(0.0),
-  m_minY(0.0), m_maxY(0.0)
-{
-  if(isVertical)
-    graphPlot->setAxisMaxMajor( QwtPlot::xBottom, 3 );
+      m_isVertical(isVertical), m_isLogX(false), m_imageX(0.0), m_imageY(0.0),
+      m_rangeScale(1.0), m_minX(0.0), m_maxX(0.0), m_minY(0.0), m_maxY(0.0) {
+  if (isVertical)
+    graphPlot->setAxisMaxMajor(QwtPlot::xBottom, 3);
 
   g_curveColors.push_back(Qt::black);
   g_curveColors.push_back(Qt::red);
@@ -47,12 +38,7 @@ GraphDisplay::GraphDisplay( QwtPlot*      graphPlot,
   g_curveColors.push_back(Qt::blue);
 }
 
-
-GraphDisplay::~GraphDisplay()
-{
-  clearCurves();
-}
-
+GraphDisplay::~GraphDisplay() { clearCurves(); }
 
 /**
  * Set the data source from which the table information will be obtained
@@ -61,23 +47,17 @@ GraphDisplay::~GraphDisplay()
  * @param dataSource The SpectrumDataSource that provides information for
  *                   the table.
  */
-void GraphDisplay::setDataSource( SpectrumDataSource_sptr dataSource )
-{
+void GraphDisplay::setDataSource(SpectrumDataSource_sptr dataSource) {
   m_dataSource = dataSource;
 }
 
-
 /**
  * Set flag indicating whether or not to use a log scale on the x-axis
  *
  * @param isLogX  Pass in true to use a log scale on the x-axis and false
  *                to use a linear scale.
  */
-void GraphDisplay::setLogX( bool isLogX )
-{
-  m_isLogX = isLogX;
-}
-
+void GraphDisplay::setLogX(bool isLogX) { m_isLogX = isLogX; }
 
 /**
  * Set the actual data that will be displayed on the graph and the
@@ -91,69 +71,56 @@ void GraphDisplay::setLogX( bool isLogX )
  * @param cutValue  the cut value
  * @param isFront   Is it a front curve?
  */
-void GraphDisplay::setData(const QVector<double> & xData,
-                           const QVector<double> & yData,
-                           double cutValue,
-                           bool isFront)
-{
-  if ( xData.size() == 0 ||          // ignore invalid data vectors
-       yData.size() == 0 ||
-       xData.size() != yData.size() )
-  {
+void GraphDisplay::setData(const QVector<double> &xData,
+                           const QVector<double> &yData, double cutValue,
+                           bool isFront) {
+  if (xData.size() == 0 || // ignore invalid data vectors
+      yData.size() == 0 || xData.size() != yData.size()) {
     return;
   }
 
   if (isFront)
-    clearCurves();               // detach from any plot, before changing
-                                    // the data and attaching
-  if ( m_isVertical )
-  {
+    clearCurves(); // detach from any plot, before changing
+                   // the data and attaching
+  if (m_isVertical) {
     m_imageX = cutValue;
     m_minY = yData[0];
-    m_maxY = yData[yData.size()-1];
-    SVUtils::FindValidInterval( xData, m_minX, m_maxX );
-  }
-  else
-  {
+    m_maxY = yData[yData.size() - 1];
+    SVUtils::FindValidInterval(xData, m_minX, m_maxX);
+  } else {
     m_imageY = cutValue;
     m_minX = xData[0];
-    m_maxX = xData[xData.size()-1];
-    SVUtils::FindValidInterval( yData, m_minY, m_maxY );
+    m_maxX = xData[xData.size() - 1];
+    SVUtils::FindValidInterval(yData, m_minY, m_maxY);
 
-    if ( m_isLogX )                // only set log scale for x if NOT vertical
-    {
-      QwtLog10ScaleEngine* log_engine = new QwtLog10ScaleEngine();
-      m_graphPlot->setAxisScaleEngine( QwtPlot::xBottom, log_engine );
-    }
-    else
+    if (m_isLogX) // only set log scale for x if NOT vertical
     {
-      QwtLinearScaleEngine* linear_engine = new QwtLinearScaleEngine();
-      m_graphPlot->setAxisScaleEngine( QwtPlot::xBottom, linear_engine );
+      QwtLog10ScaleEngine *log_engine = new QwtLog10ScaleEngine();
+      m_graphPlot->setAxisScaleEngine(QwtPlot::xBottom, log_engine);
+    } else {
+      QwtLinearScaleEngine *linear_engine = new QwtLinearScaleEngine();
+      m_graphPlot->setAxisScaleEngine(QwtPlot::xBottom, linear_engine);
     }
   }
 
   auto curve = new QwtPlotCurve;
-  curve->setData( xData, yData );
-  curve->attach( m_graphPlot );
+  curve->setData(xData, yData);
+  curve->attach(m_graphPlot);
   auto colorIndex = m_curves.size() % g_curveColors.size();
   curve->setPen(QPen(g_curveColors[colorIndex]));
   m_curves.append(curve);
 
-  if (isFront) 
-  {
-    setRangeScale( m_rangeScale );
+  if (isFront) {
+    setRangeScale(m_rangeScale);
     m_graphPlot->setAutoReplot(true);
   }
 }
 
-
-void GraphDisplay::clear()
-{
+void GraphDisplay::clear() {
   clearCurves();
   m_graphPlot->replot();
 }
 
-
 /**
  *  Set up axes using the specified scale factor and replot the graph.
  *  This is useful for seeing low-level values, by clipping off the higher
@@ -162,54 +129,45 @@ void GraphDisplay::clear()
  *  @param rangeScale Value between 0 and 1 indicating what fraction of
  *         graph value range should be plotted.
  */
-void GraphDisplay::setRangeScale( double rangeScale )
-{
+void GraphDisplay::setRangeScale(double rangeScale) {
   m_rangeScale = rangeScale;
 
-  if ( m_isVertical )
-  {
-    double axis_max = m_rangeScale * ( m_maxX - m_minX ) + m_minX;
-    m_graphPlot->setAxisScale( QwtPlot::xBottom, m_minX, axis_max );
-    m_graphPlot->setAxisScale( QwtPlot::yLeft, m_minY, m_maxY );
-  }
-  else
-  {
-    double axis_max = m_rangeScale * ( m_maxY - m_minY ) + m_minY;
-    m_graphPlot->setAxisScale( QwtPlot::yLeft, m_minY, axis_max );
-    m_graphPlot->setAxisScale( QwtPlot::xBottom, m_minX, m_maxX );
+  if (m_isVertical) {
+    double axis_max = m_rangeScale * (m_maxX - m_minX) + m_minX;
+    m_graphPlot->setAxisScale(QwtPlot::xBottom, m_minX, axis_max);
+    m_graphPlot->setAxisScale(QwtPlot::yLeft, m_minY, m_maxY);
+  } else {
+    double axis_max = m_rangeScale * (m_maxY - m_minY) + m_minY;
+    m_graphPlot->setAxisScale(QwtPlot::yLeft, m_minY, axis_max);
+    m_graphPlot->setAxisScale(QwtPlot::xBottom, m_minX, m_maxX);
   }
   m_graphPlot->replot();
 }
 
-
 /**
  * Show information about the specified point.
  *
  * @param point  The point that the user is currently pointing at with
  *               the mouse.
  */
-void GraphDisplay::setPointedAtPoint( QPoint point )
-{
-  if ( m_dataSource == 0 )
-  {
+void GraphDisplay::setPointedAtPoint(QPoint point) {
+  if (m_dataSource == 0) {
     return;
   }
-  double x = m_graphPlot->invTransform( QwtPlot::xBottom, point.x() );
-  double y = m_graphPlot->invTransform( QwtPlot::yLeft, point.y() );
-
-  if ( m_isVertical )             // x can be anywhere on graph, y must be
-  {                              // a valid data source position, vertically
-    m_dataSource->restrictY( y );
-  }
-  else                           // y can be anywhere on graph, x must be
-  {                              // a valid data source position, horizontally
-    m_dataSource->restrictX( x );
+  double x = m_graphPlot->invTransform(QwtPlot::xBottom, point.x());
+  double y = m_graphPlot->invTransform(QwtPlot::yLeft, point.y());
+
+  if (m_isVertical) // x can be anywhere on graph, y must be
+  {                 // a valid data source position, vertically
+    m_dataSource->restrictY(y);
+  } else // y can be anywhere on graph, x must be
+  {      // a valid data source position, horizontally
+    m_dataSource->restrictX(x);
   }
 
-  showInfoList( x, y );
+  showInfoList(x, y);
 }
 
-
 /**
  *  Get the information about a pointed at location and show it in the
  *  table.  NOTE: If this is the "horizontal" graph, the relevant coordinates
@@ -222,30 +180,23 @@ void GraphDisplay::setPointedAtPoint( QPoint point )
  *  @param x  The x coordinate of the pointed at location on the graph.
  *  @param y  The y coordinate of the pointed at location on the graph.
  */
-void GraphDisplay::showInfoList( double x, double y )
-{
-  // This whole method is a no-op if no table object was injected on construction
-  if ( m_graphTable != NULL )
-  {
+void GraphDisplay::showInfoList(double x, double y) {
+  // This whole method is a no-op if no table object was injected on
+  // construction
+  if (m_graphTable != NULL) {
     int n_infos = 0;
-    int n_rows  = 1;
+    int n_rows = 1;
     std::vector<std::string> info_list;
-    if ( m_dataSource != 0 )
-    {
-      if ( m_isVertical )
-      {
+    if (m_dataSource != 0) {
+      if (m_isVertical) {
         info_list = m_dataSource->getInfoList(m_imageX, y);
-      }
-      else
-      {
+      } else {
         info_list = m_dataSource->getInfoList(x, m_imageY);
       }
-    }
-    else
-    {
+    } else {
       return;
     }
-    n_infos = (int)info_list.size()/2;
+    n_infos = (int)info_list.size() / 2;
     n_rows += n_infos;
 
     m_graphTable->setRowCount(n_rows);
@@ -254,23 +205,19 @@ void GraphDisplay::showInfoList( double x, double y )
     m_graphTable->horizontalHeader()->hide();
 
     int width = 9;
-    int prec  = 3;
-
-    if ( m_isVertical )
-    {
-      QtUtils::SetTableEntry( 0, 0, "Value", m_graphTable );
-      QtUtils::SetTableEntry( 0, 1, width, prec, x, m_graphTable );
-    }
-    else
-    {
-      QtUtils::SetTableEntry( 0, 0, "Value", m_graphTable );
-      QtUtils::SetTableEntry( 0, 1, width, prec, y, m_graphTable );
+    int prec = 3;
+
+    if (m_isVertical) {
+      QtUtils::SetTableEntry(0, 0, "Value", m_graphTable);
+      QtUtils::SetTableEntry(0, 1, width, prec, x, m_graphTable);
+    } else {
+      QtUtils::SetTableEntry(0, 0, "Value", m_graphTable);
+      QtUtils::SetTableEntry(0, 1, width, prec, y, m_graphTable);
     }
 
-    for ( int i = 0; i < n_infos; i++ )
-    {
-      QtUtils::SetTableEntry( i+1, 0, info_list[2*i], m_graphTable );
-      QtUtils::SetTableEntry( i+1, 1, info_list[2*i+1], m_graphTable );
+    for (int i = 0; i < n_infos; i++) {
+      QtUtils::SetTableEntry(i + 1, 0, info_list[2 * i], m_graphTable);
+      QtUtils::SetTableEntry(i + 1, 1, info_list[2 * i + 1], m_graphTable);
     }
 
     m_graphTable->resizeColumnsToContents();
@@ -278,9 +225,8 @@ void GraphDisplay::showInfoList( double x, double y )
 }
 
 /// Remove all curves.
-void GraphDisplay::clearCurves()
-{
-  foreach(QwtPlotCurve* curve, m_curves) {
+void GraphDisplay::clearCurves() {
+  foreach (QwtPlotCurve *curve, m_curves) {
     curve->detach();
     delete curve;
   }
diff --git a/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp b/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp
index 7706f239f2cf578a6b996732f970fc46e78d1bbf..dc42b169e983079b90519768cb96584413dd0c1c 100644
--- a/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp
+++ b/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp
@@ -44,7 +44,7 @@ MatrixWSDataSource::MatrixWSDataSource(MatrixWorkspace_const_sptr matWs)
   m_totalXMin = matWs->getXMin();
   m_totalXMax = matWs->getXMax();
 
-  m_totalYMin = 0;  // Y direction is workspace index
+  m_totalYMin = 0; // Y direction is workspace index
   m_totalYMax = (double)matWs->getNumberHistograms();
 
   m_totalRows = matWs->getNumberHistograms();
diff --git a/MantidQt/SpectrumViewer/src/MatrixWSSpectrumView.cpp b/MantidQt/SpectrumViewer/src/MatrixWSSpectrumView.cpp
index 07f3aa6ea64f2560069afb4caaa5ef794c3086ef..311222779dff4c244fe591bca73e267f5758376a 100644
--- a/MantidQt/SpectrumViewer/src/MatrixWSSpectrumView.cpp
+++ b/MantidQt/SpectrumViewer/src/MatrixWSSpectrumView.cpp
@@ -7,26 +7,21 @@ using Mantid::API::MatrixWorkspace_const_sptr;
 using namespace MantidQt;
 using namespace SpectrumView;
 
-
 /**
  * Construct an SpectrumView for the specified matrix workspace
  */
-MatrixWSSpectrumView::MatrixWSSpectrumView( MatrixWorkspace_const_sptr mat_ws )
-{
+MatrixWSSpectrumView::MatrixWSSpectrumView(MatrixWorkspace_const_sptr mat_ws) {
   /* This is the QMainWindow for the viewer. */
   /* It is deleted when the window is closed. */
   spectrum_view = new SpectrumView();
 
   std::string title = "SpectrumView (" + mat_ws->getTitle() + ")";
   QString qtitle = QString::fromStdString(title);
-  spectrum_view->setCaption( qtitle );
+  spectrum_view->setCaption(qtitle);
   spectrum_view->renderWorkspace(mat_ws);
   std::cerr << "MatrixWSSpectrumView?" << std::endl;
 }
 
-
-MatrixWSSpectrumView::~MatrixWSSpectrumView()
-{
+MatrixWSSpectrumView::~MatrixWSSpectrumView() {
   // nothing to do here, since spectrum_view is deleted when the window closes
 }
-
diff --git a/MantidQt/SpectrumViewer/src/QtUtils.cpp b/MantidQt/SpectrumViewer/src/QtUtils.cpp
index ed1c3a2d250ae2e682d9bbf6bb4f08dd8ce91834..2e39f8c52aa6f7801a9adfd161cba26767ec7acd 100644
--- a/MantidQt/SpectrumViewer/src/QtUtils.cpp
+++ b/MantidQt/SpectrumViewer/src/QtUtils.cpp
@@ -1,10 +1,8 @@
 #include "MantidQtSpectrumViewer/QtUtils.h"
 #include "MantidQtSpectrumViewer/SVUtils.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Set the specified string as the entry at the specified row and col of
@@ -15,17 +13,13 @@ namespace SpectrumView
  * @param string  The string that will be placed in the table.
  * @param table   Pointer to the table
  */
-void QtUtils::SetTableEntry(       int           row,
-                                   int           col,
-                             const std::string & string,
-                                   QTableWidget* table )
-{
-  QString qString = QString::fromStdString( string ).simplified();
-  QTableWidgetItem *item = new QTableWidgetItem( qString );
-  table->setItem( row, col, item );
+void QtUtils::SetTableEntry(int row, int col, const std::string &string,
+                            QTableWidget *table) {
+  QString qString = QString::fromStdString(string).simplified();
+  QTableWidgetItem *item = new QTableWidgetItem(qString);
+  table->setItem(row, col, item);
 }
 
-
 /**
  * Format and set the specified double as the entry at the specified row
  * and col of the specified table.
@@ -38,33 +32,24 @@ void QtUtils::SetTableEntry(       int           row,
  * @param value     The number to be formatted and placed in the table.
  * @param table     Pointer to the table
  */
-void  QtUtils::SetTableEntry( int           row,
-                              int           col,
-                              int           width,
-                              int           precision,
-                              double        value,
-                              QTableWidget* table )
-{
+void QtUtils::SetTableEntry(int row, int col, int width, int precision,
+                            double value, QTableWidget *table) {
   std::string str;
-  SVUtils::Format( width, precision, value, str );
-  SetTableEntry( row, col, str, table );
+  SVUtils::Format(width, precision, value, str);
+  SetTableEntry(row, col, str, table);
 }
 
-
 /**
  * Set the specified string into the specified QLineEdit widget.
  *
  * @param string    The string that will be placed in the widget.
  * @param lineEdit  Pointer to the QLineEdit widget.
  */
-void  QtUtils::SetText( const std::string & string,
-                              QLineEdit*    lineEdit )
-{
-  QString qString = QString::fromStdString( string );
-  lineEdit->setText( qString.trimmed() );
+void QtUtils::SetText(const std::string &string, QLineEdit *lineEdit) {
+  QString qString = QString::fromStdString(string);
+  lineEdit->setText(qString.trimmed());
 }
 
-
 /**
  * Format and set the specified double as the text in the specified
  * QLineEdit widget.
@@ -75,14 +60,11 @@ void  QtUtils::SetText( const std::string & string,
  * @param value      The number to be formatted and placed in the table.
  * @param lineEdit   Pointer to the QLineEdit widget.
  */
-void  QtUtils::SetText( int        width,
-                        int        precision,
-                        double     value,
-                        QLineEdit* lineEdit )
-{
+void QtUtils::SetText(int width, int precision, double value,
+                      QLineEdit *lineEdit) {
   std::string str;
-  SVUtils::Format( width, precision, value, str );
-  SetText( str, lineEdit );
+  SVUtils::Format(width, precision, value, str);
+  SetText(str, lineEdit);
 }
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/src/RangeHandler.cpp b/MantidQt/SpectrumViewer/src/RangeHandler.cpp
index 5f48eb5654681b3bafb2f370b28ab07f6b979d4a..f539e4253eeb4b8e49def93f2d77d777bdab3f4b 100644
--- a/MantidQt/SpectrumViewer/src/RangeHandler.cpp
+++ b/MantidQt/SpectrumViewer/src/RangeHandler.cpp
@@ -5,50 +5,38 @@
 #include "MantidQtSpectrumViewer/SVUtils.h"
 #include "MantidKernel/Logger.h"
 
-
-namespace
-{
-  Mantid::Kernel::Logger g_log("SpectrumView");
+namespace {
+Mantid::Kernel::Logger g_log("SpectrumView");
 }
 
-
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct a RangeHandler object to manage min, max and step controls
  *  in the specified UI
  */
-RangeHandler::RangeHandler( Ui_SpectrumViewer* svUI ) :
-  IRangeHandler(),
-  m_svUI(svUI),
-  m_totalMinX(0.0), m_totalMaxX(0.0),
-  m_totalNSteps(0)
-{
-}
-
+RangeHandler::RangeHandler(Ui_SpectrumViewer *svUI)
+    : IRangeHandler(), m_svUI(svUI), m_totalMinX(0.0), m_totalMaxX(0.0),
+      m_totalNSteps(0) {}
 
 /**
  * Configure the min, max and step controls for the specified data source.
  *
  * @param dataSource  SpectrumDataSource that provides the data to be drawn
  */
-void RangeHandler::configureRangeControls( SpectrumDataSource_sptr dataSource )
-{
-  m_totalMinX   = dataSource->getXMin();
-  m_totalMaxX   = dataSource->getXMax();
+void RangeHandler::configureRangeControls(SpectrumDataSource_sptr dataSource) {
+  m_totalMinX = dataSource->getXMin();
+  m_totalMaxX = dataSource->getXMax();
   m_totalNSteps = dataSource->getNCols();
 
   double defaultStep = (m_totalMaxX - m_totalMinX) / (double)m_totalNSteps;
-  if ( m_totalNSteps > 2000 )
+  if (m_totalNSteps > 2000)
     defaultStep = (m_totalMaxX - m_totalMinX) / 2000.0;
 
-  setRange( m_totalMinX, m_totalMaxX, defaultStep );
+  setRange(m_totalMinX, m_totalMaxX, defaultStep);
 }
 
-
 /**
  * Get the interval of values and the step size to use for rebinning the
  * spectra.  The range values are validated and adjusted if needed.  The
@@ -72,15 +60,14 @@ void RangeHandler::configureRangeControls( SpectrumDataSource_sptr dataSource )
  *                min and max.  If it is less than zero, a log scale
  *                is requested.
  */
-void RangeHandler::getRange( double &min, double &max, double &step )
-{
-  double originalMin  = min;
-  double originalMax  = max;
+void RangeHandler::getRange(double &min, double &max, double &step) {
+  double originalMin = min;
+  double originalMax = max;
   double originalStep = step;
 
-  QLineEdit* minControl  = m_svUI->x_min_input;
-  QLineEdit* maxControl  = m_svUI->x_max_input;
-  QLineEdit* stepControl = m_svUI->step_input;
+  QLineEdit *minControl = m_svUI->x_min_input;
+  QLineEdit *maxControl = m_svUI->x_max_input;
+  QLineEdit *stepControl = m_svUI->step_input;
 
   bool minIsNumber = false;
   bool maxIsNumber = false;
@@ -90,56 +77,49 @@ void RangeHandler::getRange( double &min, double &max, double &step )
   max = maxControl->text().toDouble(&maxIsNumber);
   step = stepControl->text().toDouble(&stepIsNumber);
 
-  if(!minIsNumber)
-  {
+  if (!minIsNumber) {
     g_log.information("X Min is not a NUMBER! Value reset.");
     min = originalMin;
   }
 
-  if(!maxIsNumber)
-  {
+  if (!maxIsNumber) {
     g_log.information("X Max is not a NUMBER! Value reset.");
     max = originalMax;
   }
 
-  if(!stepIsNumber)
-  {
+  if (!stepIsNumber) {
     g_log.information("Step is not a NUMBER! Value reset.");
     step = originalStep;
   }
 
-  // Just require step to be non-zero, no other bounds. If zero, take a default step size
-  if ( step == 0 )
-  {
+  // Just require step to be non-zero, no other bounds. If zero, take a default
+  // step size
+  if (step == 0) {
     g_log.information("Step = 0, resetting to default step");
     step = originalStep;
   }
 
-  if ( step > 0 )
-  {
-    if ( !SVUtils::FindValidInterval( min, max ) )
-    {
-      g_log.information( "In GetRange: [Min,Max] interval invalid, values adjusted" );
-      min  = originalMin;
-      max  = originalMax;
+  if (step > 0) {
+    if (!SVUtils::FindValidInterval(min, max)) {
+      g_log.information(
+          "In GetRange: [Min,Max] interval invalid, values adjusted");
+      min = originalMin;
+      max = originalMax;
       step = originalStep;
     }
-  }
-  else
-  {
-    if ( !SVUtils::FindValidLogInterval( min, max ) )
-    {
-      g_log.information( "In GetRange: [Min,Max] log interval invalid, values adjusted");
-      min  = originalMin;
-      max  = originalMax;
+  } else {
+    if (!SVUtils::FindValidLogInterval(min, max)) {
+      g_log.information(
+          "In GetRange: [Min,Max] log interval invalid, values adjusted");
+      min = originalMin;
+      max = originalMax;
       step = originalStep;
     }
   }
 
-  setRange( min, max, step );
+  setRange(min, max, step);
 }
 
-
 /**
  * Adjust the values to be consistent with the available data and
  * diplay them in the controls.
@@ -149,34 +129,30 @@ void RangeHandler::getRange( double &min, double &max, double &step )
  * @param step    This is size of the step to use between min and max.
  *                If it is less than zero, a log scale is requested.
  */
-void RangeHandler::setRange( double min, double max, double step )
-{
-  if ( !SVUtils::FindValidInterval( min, max ) )
-    g_log.information("In SetRange: [Min,Max] interval invalid, values adjusted" );
+void RangeHandler::setRange(double min, double max, double step) {
+  if (!SVUtils::FindValidInterval(min, max))
+    g_log.information(
+        "In SetRange: [Min,Max] interval invalid, values adjusted");
 
-  if ( min < m_totalMinX || min > m_totalMaxX )
-  {
+  if (min < m_totalMinX || min > m_totalMaxX) {
     g_log.information("X Min out of range, resetting to range min.");
     min = m_totalMinX;
   }
 
-  if ( max < m_totalMinX || max > m_totalMaxX )
-  {
+  if (max < m_totalMinX || max > m_totalMaxX) {
     g_log.information("X Max out of range, resetting to range max.");
     max = m_totalMaxX;
   }
 
-  if ( step == 0 )
-  {
+  if (step == 0) {
     g_log.information("Step = 0, resetting to default step");
     step = (max - min) / 2000.0;
   }
 
-  QtUtils::SetText( 8, 2, min, m_svUI->x_min_input );
-  QtUtils::SetText( 8, 2, max, m_svUI->x_max_input );
-  QtUtils::SetText( 8, 6, step, m_svUI->step_input );
+  QtUtils::SetText(8, 2, min, m_svUI->x_min_input);
+  QtUtils::SetText(8, 2, max, m_svUI->x_max_input);
+  QtUtils::SetText(8, 6, step, m_svUI->step_input);
 }
 
-
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/src/SVConnections.cpp b/MantidQt/SpectrumViewer/src/SVConnections.cpp
index fcd5091db61261be4feabcaf6016a612aa38631b..a86f63be67b4911daf7bd8bed49af37671121f65 100644
--- a/MantidQt/SpectrumViewer/src/SVConnections.cpp
+++ b/MantidQt/SpectrumViewer/src/SVConnections.cpp
@@ -7,10 +7,8 @@
 
 #include "MantidQtSpectrumViewer/SVConnections.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Construct the object that links the GUI components to the other specifed
@@ -29,18 +27,13 @@ namespace SpectrumView
  *                        vertical cuts through the image
  *
  */
-SVConnections::SVConnections( Ui_SpectrumViewer* ui,
-                              SpectrumView*      spectrumView,
-                              SpectrumDisplay*   spectrumDisplay,
-                              GraphDisplay*      hGraphDisplay,
-                              GraphDisplay*      vGraphDisplay ) :
-  m_svUI(ui),
-  m_svMainWindow(spectrumView),
-  m_currentSpectrumDisplay(spectrumDisplay),
-  m_hGraphDisplay(hGraphDisplay),
-  m_vGraphDisplay(vGraphDisplay),
-  m_pickerX(-1), m_pickerY(-1)
-{
+SVConnections::SVConnections(Ui_SpectrumViewer *ui, SpectrumView *spectrumView,
+                             SpectrumDisplay *spectrumDisplay,
+                             GraphDisplay *hGraphDisplay,
+                             GraphDisplay *vGraphDisplay)
+    : m_svUI(ui), m_svMainWindow(spectrumView),
+      m_currentSpectrumDisplay(spectrumDisplay), m_hGraphDisplay(hGraphDisplay),
+      m_vGraphDisplay(vGraphDisplay), m_pickerX(-1), m_pickerY(-1) {
   m_spectrumDisplays.append(spectrumDisplay);
   // First disable a few un-implemented controls
   m_svUI->menuGraph_Selected->setDisabled(true);
@@ -51,39 +44,39 @@ SVConnections::SVConnections( Ui_SpectrumViewer* ui,
   m_svUI->actionGraph_Rebinned_Data->setDisabled(true);
   m_svUI->menuHelp->setDisabled(false);
 
-  QObject::connect( m_svUI->actionClose, SIGNAL(triggered()),
-                    this, SLOT(closeViewer()) );
+  QObject::connect(m_svUI->actionClose, SIGNAL(triggered()), this,
+                   SLOT(closeViewer()));
 
   // Now set up the GUI components
   QList<int> image_sizes;
-  image_sizes.append( 500 );
-  image_sizes.append( 250 );
-  m_svUI->imageSplitter->setSizes( image_sizes );
+  image_sizes.append(500);
+  image_sizes.append(250);
+  m_svUI->imageSplitter->setSizes(image_sizes);
   QList<int> vgraph_sizes;
-  vgraph_sizes.append( 500 );
-  vgraph_sizes.append( 30 );
-  vgraph_sizes.append( 220 );
-  m_svUI->vgraphSplitter->setSizes( vgraph_sizes );
+  vgraph_sizes.append(500);
+  vgraph_sizes.append(30);
+  vgraph_sizes.append(220);
+  m_svUI->vgraphSplitter->setSizes(vgraph_sizes);
 
   QList<int> horiz_sizes;
-  horiz_sizes.append( 250 );
-  horiz_sizes.append( 750 );
-  horiz_sizes.append( 150 );
-  m_svUI->left_right_splitter->setSizes( horiz_sizes );
+  horiz_sizes.append(250);
+  horiz_sizes.append(750);
+  horiz_sizes.append(150);
+  m_svUI->left_right_splitter->setSizes(horiz_sizes);
 
-  m_svUI->imageHorizontalScrollBar->setFocusPolicy( Qt::StrongFocus );
+  m_svUI->imageHorizontalScrollBar->setFocusPolicy(Qt::StrongFocus);
   m_svUI->imageHorizontalScrollBar->setMouseTracking(true);
   m_svUI->imageHorizontalScrollBar->setMinimum(20);
   m_svUI->imageHorizontalScrollBar->setMaximum(2000);
   m_svUI->imageHorizontalScrollBar->setPageStep(30);
-  m_svUI->imageHorizontalScrollBar->setSingleStep(30/2);
+  m_svUI->imageHorizontalScrollBar->setSingleStep(30 / 2);
 
-  m_svUI->imageVerticalScrollBar->setFocusPolicy( Qt::StrongFocus );
+  m_svUI->imageVerticalScrollBar->setFocusPolicy(Qt::StrongFocus);
   m_svUI->imageVerticalScrollBar->setMouseTracking(true);
   m_svUI->imageVerticalScrollBar->setMinimum(0);
   m_svUI->imageVerticalScrollBar->setMaximum(10000000);
   m_svUI->imageVerticalScrollBar->setPageStep(500);
-  m_svUI->imageVerticalScrollBar->setSingleStep(500/2);
+  m_svUI->imageVerticalScrollBar->setSingleStep(500 / 2);
 
   // for forwarding scroll wheel events
   m_svUI->spectrumPlot->canvas()->installEventFilter(this);
@@ -106,38 +99,38 @@ SVConnections::SVConnections( Ui_SpectrumViewer* ui,
   m_svUI->graph_max_slider->setTickPosition(QSlider::TicksBelow);
   m_svUI->graph_max_slider->setSliderPosition(100);
 
-  QObject::connect(m_svUI->imageSplitter, SIGNAL(splitterMoved(int, int)),
-                   this, SLOT(imageSplitterMoved()) );
+  QObject::connect(m_svUI->imageSplitter, SIGNAL(splitterMoved(int, int)), this,
+                   SLOT(imageSplitterMoved()));
 
   QObject::connect(m_svUI->vgraphSplitter, SIGNAL(splitterMoved(int, int)),
-                   this, SLOT(vgraphSplitterMoved()) );
+                   this, SLOT(vgraphSplitterMoved()));
 
-  QObject::connect(m_svUI->x_min_input, SIGNAL( returnPressed() ),
-                   this, SLOT(imageHorizontalRangeChanged()) );
+  QObject::connect(m_svUI->x_min_input, SIGNAL(returnPressed()), this,
+                   SLOT(imageHorizontalRangeChanged()));
 
-  QObject::connect(m_svUI->x_max_input, SIGNAL( returnPressed() ),
-                   this, SLOT(imageHorizontalRangeChanged()) );
+  QObject::connect(m_svUI->x_max_input, SIGNAL(returnPressed()), this,
+                   SLOT(imageHorizontalRangeChanged()));
 
-  QObject::connect(m_svUI->step_input, SIGNAL( returnPressed() ),
-                   this, SLOT(imageHorizontalRangeChanged()) );
+  QObject::connect(m_svUI->step_input, SIGNAL(returnPressed()), this,
+                   SLOT(imageHorizontalRangeChanged()));
 
   QObject::connect(m_svUI->imageVerticalScrollBar, SIGNAL(valueChanged(int)),
-                   this, SLOT(scrollBarMoved()) );
+                   this, SLOT(scrollBarMoved()));
 
   QObject::connect(m_svUI->imageHorizontalScrollBar, SIGNAL(valueChanged(int)),
-                   this, SLOT(scrollBarMoved()) );
+                   this, SLOT(scrollBarMoved()));
 
-  QObject::connect(m_svUI->action_Hscroll, SIGNAL(changed()),
-                   this, SLOT(toggleHScroll()) );
+  QObject::connect(m_svUI->action_Hscroll, SIGNAL(changed()), this,
+                   SLOT(toggleHScroll()));
 
-  QObject::connect(m_svUI->action_Vscroll, SIGNAL(changed()),
-                   this, SLOT(toggleVScroll()) );
+  QObject::connect(m_svUI->action_Vscroll, SIGNAL(changed()), this,
+                   SLOT(toggleVScroll()));
 
-  QObject::connect(m_svUI->intensity_slider, SIGNAL(valueChanged(int)),
-                   this, SLOT(intensitySliderMoved()) );
+  QObject::connect(m_svUI->intensity_slider, SIGNAL(valueChanged(int)), this,
+                   SLOT(intensitySliderMoved()));
 
-  QObject::connect(m_svUI->graph_max_slider, SIGNAL(valueChanged(int)),
-                   this, SLOT(graphRangeChanged()) );
+  QObject::connect(m_svUI->graph_max_slider, SIGNAL(valueChanged(int)), this,
+                   SLOT(graphRangeChanged()));
 
   // Color scale selections
   m_svUI->actionHeat->setCheckable(true);
@@ -150,15 +143,15 @@ SVConnections::SVConnections( Ui_SpectrumViewer* ui,
   m_svUI->actionMulti->setCheckable(true);
   m_svUI->actionSpectrum->setCheckable(true);
   m_svUI->actionLoadColormap->setCheckable(true);
-                                                    // set up initial color
-                                                    // scale display
+  // set up initial color
+  // scale display
   m_svUI->color_scale->setScaledContents(true);
   m_svUI->color_scale->setMinimumHeight(15);
   m_svUI->color_scale->setMinimumWidth(15);
   auto positive_color_table = ColorMaps::GetColorMap(ColorMaps::HEAT, 256);
   auto negative_color_table = ColorMaps::GetColorMap(ColorMaps::GRAY, 256);
 
-  showColorScale( positive_color_table, negative_color_table );
+  showColorScale(positive_color_table, negative_color_table);
 
   m_colorGroup = new QActionGroup(this);
   m_colorGroup->addAction(m_svUI->actionHeat);
@@ -171,65 +164,59 @@ SVConnections::SVConnections( Ui_SpectrumViewer* ui,
   m_colorGroup->addAction(m_svUI->actionSpectrum);
   m_colorGroup->addAction(m_svUI->actionLoadColormap);
 
-  QObject::connect(m_svUI->actionHeat, SIGNAL(triggered()),
-                   this, SLOT(heatColorScale()) );
+  QObject::connect(m_svUI->actionHeat, SIGNAL(triggered()), this,
+                   SLOT(heatColorScale()));
 
-  QObject::connect(m_svUI->actionGray, SIGNAL(triggered()),
-                   this, SLOT(grayColorScale()) );
+  QObject::connect(m_svUI->actionGray, SIGNAL(triggered()), this,
+                   SLOT(grayColorScale()));
 
-  QObject::connect(m_svUI->actionNegative_Gray, SIGNAL(triggered()),
-                   this, SLOT(negativeGrayColorScale()) );
+  QObject::connect(m_svUI->actionNegative_Gray, SIGNAL(triggered()), this,
+                   SLOT(negativeGrayColorScale()));
 
-  QObject::connect(m_svUI->actionGreen_Yellow, SIGNAL(triggered()),
-                   this, SLOT(greenYellowColorScale()) );
+  QObject::connect(m_svUI->actionGreen_Yellow, SIGNAL(triggered()), this,
+                   SLOT(greenYellowColorScale()));
 
-  QObject::connect(m_svUI->actionRainbow, SIGNAL(triggered()),
-                   this, SLOT(rainbowColorScale()) );
+  QObject::connect(m_svUI->actionRainbow, SIGNAL(triggered()), this,
+                   SLOT(rainbowColorScale()));
 
-  QObject::connect(m_svUI->actionOptimal, SIGNAL(triggered()),
-                   this, SLOT(optimalColorScale()) );
+  QObject::connect(m_svUI->actionOptimal, SIGNAL(triggered()), this,
+                   SLOT(optimalColorScale()));
 
-  QObject::connect(m_svUI->actionMulti, SIGNAL(triggered()),
-                   this, SLOT(multiColorScale()) );
+  QObject::connect(m_svUI->actionMulti, SIGNAL(triggered()), this,
+                   SLOT(multiColorScale()));
 
-  QObject::connect(m_svUI->actionSpectrum, SIGNAL(triggered()),
-                   this, SLOT(spectrumColorScale()) );
+  QObject::connect(m_svUI->actionSpectrum, SIGNAL(triggered()), this,
+                   SLOT(spectrumColorScale()));
 
-  QObject::connect(m_svUI->actionLoadColormap, SIGNAL(triggered()),
-                   this, SLOT(loadColorMap()) );
+  QObject::connect(m_svUI->actionLoadColormap, SIGNAL(triggered()), this,
+                   SLOT(loadColorMap()));
 
-
-  m_hGraphPicker = new TrackingPicker( m_svUI->h_graphPlot->canvas() );
+  m_hGraphPicker = new TrackingPicker(m_svUI->h_graphPlot->canvas());
   m_hGraphPicker->setMousePattern(QwtPicker::MouseSelect1, Qt::LeftButton);
   m_hGraphPicker->setTrackerMode(QwtPicker::ActiveOnly);
   m_hGraphPicker->setRubberBandPen(QColor(Qt::gray));
   m_hGraphPicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_hGraphPicker->setSelectionFlags(QwtPicker::PointSelection |
-                                  QwtPicker::DragSelection  );
-  QObject::connect( m_hGraphPicker, SIGNAL(mouseMoved(const QPoint &)),
-                    this, SLOT(hGraphPickerMoved(const QPoint &)) );
+                                    QwtPicker::DragSelection);
+  QObject::connect(m_hGraphPicker, SIGNAL(mouseMoved(const QPoint &)), this,
+                   SLOT(hGraphPickerMoved(const QPoint &)));
 
   // NOTE: This initialization could be a (static?) method in TrackingPicker
-  m_vGraphPicker = new TrackingPicker( m_svUI->v_graphPlot->canvas() );
+  m_vGraphPicker = new TrackingPicker(m_svUI->v_graphPlot->canvas());
   m_vGraphPicker->setMousePattern(QwtPicker::MouseSelect1, Qt::LeftButton);
   m_vGraphPicker->setTrackerMode(QwtPicker::ActiveOnly);
   m_vGraphPicker->setRubberBandPen(QColor(Qt::gray));
   m_vGraphPicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_vGraphPicker->setSelectionFlags(QwtPicker::PointSelection |
-                                    QwtPicker::DragSelection  );
-  QObject::connect( m_vGraphPicker, SIGNAL(mouseMoved(const QPoint &)),
-                    this, SLOT(vGraphPickerMoved(const QPoint &)) );
-
-  QObject::connect( m_svUI->actionOnline_Help_Page, SIGNAL(triggered()),
-                    this, SLOT(openOnlineHelp()) );
+                                    QwtPicker::DragSelection);
+  QObject::connect(m_vGraphPicker, SIGNAL(mouseMoved(const QPoint &)), this,
+                   SLOT(vGraphPickerMoved(const QPoint &)));
 
+  QObject::connect(m_svUI->actionOnline_Help_Page, SIGNAL(triggered()), this,
+                   SLOT(openOnlineHelp()));
 }
 
-
-SVConnections::~SVConnections()
-{
-}
-
+SVConnections::~SVConnections() {}
 
 /**
  * Handle events.
@@ -238,40 +225,35 @@ SVConnections::~SVConnections()
  * @param event The event being filtered.
  * @return true if the event was consumed.
  */
-bool SVConnections::eventFilter(QObject *object, QEvent *event)
-{
+bool SVConnections::eventFilter(QObject *object, QEvent *event) {
   UNUSED_ARG(object);
 
-  if (event->type() == QEvent::Wheel)
-  {
+  if (event->type() == QEvent::Wheel) {
     QWheelEvent *wheelEvent = dynamic_cast<QWheelEvent *>(event);
-    if (wheelEvent)
-    {
-      if (wheelEvent->orientation() == Qt::Orientation::Vertical)
-      {
+    if (wheelEvent) {
+      if (wheelEvent->orientation() == Qt::Orientation::Vertical) {
         return m_svUI->imageVerticalScrollBar->event(wheelEvent);
-      }
-      else if (wheelEvent->orientation() == Qt::Orientation::Horizontal)
-      {
+      } else if (wheelEvent->orientation() == Qt::Orientation::Horizontal) {
         return m_svUI->imageHorizontalScrollBar->event(wheelEvent);
       }
     }
-  }
-  else if (event->type() == QEvent::KeyPress)
-  {
+  } else if (event->type() == QEvent::KeyPress) {
     // don't bother if the values aren't set
-    if (m_pickerX < 0) return false;
-    if (m_pickerY < 0) return false;
+    if (m_pickerX < 0)
+      return false;
+    if (m_pickerY < 0)
+      return false;
 
-    // Convert Y position to values so that a change of 1 corresponds to a change in spec. no by 1
+    // Convert Y position to values so that a change of 1 corresponds to a
+    // change in spec. no by 1
     int newX = m_pickerX;
     double lastY = m_currentSpectrumDisplay->getPointedAtY();
 
     QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
-    if(!keyEvent) return false;
+    if (!keyEvent)
+      return false;
     int key = keyEvent->key();
-    switch (key)
-    {
+    switch (key) {
     case Qt::Key_Up:
       lastY += 1.0;
       break;
@@ -290,31 +272,40 @@ bool SVConnections::eventFilter(QObject *object, QEvent *event)
     }
 
     // Convert Y position back to unsigned pixel position
-    QPoint newPoint = m_currentSpectrumDisplay->getPlotTransform(qMakePair(0.0, lastY));
+    QPoint newPoint =
+        m_currentSpectrumDisplay->getPlotTransform(qMakePair(0.0, lastY));
     int newY = newPoint.y();
 
     // Ignore the event if the position is outside of the plot area
-    if (newX < 0) return false;
-    if (newY < 0) return false;
-    const QSize canvasSize = m_currentSpectrumDisplay->spectrumPlot()->canvas()->size();
-    if (newX > canvasSize.width()) return false;
-    if (newY > canvasSize.height()) return false;
+    if (newX < 0)
+      return false;
+    if (newY < 0)
+      return false;
+    const QSize canvasSize =
+        m_currentSpectrumDisplay->spectrumPlot()->canvas()->size();
+    if (newX > canvasSize.width())
+      return false;
+    if (newY > canvasSize.height())
+      return false;
 
     // make the changes real
     m_pickerX = newX;
     m_pickerY = newY;
 
     // determine where the canvas is in global coords
-    QPoint canvasPos = m_svUI->spectrumPlot->canvas()->mapToGlobal(QPoint(0,0));
+    QPoint canvasPos =
+        m_svUI->spectrumPlot->canvas()->mapToGlobal(QPoint(0, 0));
     // move the cursor to the correct position
-    m_currentSpectrumDisplay->spectrumPlot()->canvas()->cursor().setPos(QPoint(canvasPos.x()+m_pickerX, canvasPos.y()+m_pickerY));
+    m_currentSpectrumDisplay->spectrumPlot()->canvas()->cursor().setPos(
+        QPoint(canvasPos.x() + m_pickerX, canvasPos.y() + m_pickerY));
 
-    QPair<double, double> transPoints = m_currentSpectrumDisplay->getPlotInvTransform(QPoint(newX, newY));
+    QPair<double, double> transPoints =
+        m_currentSpectrumDisplay->getPlotInvTransform(QPoint(newX, newY));
 
-    m_currentSpectrumDisplay->setHGraph( lastY );
-    m_currentSpectrumDisplay->setVGraph( transPoints.first );
+    m_currentSpectrumDisplay->setHGraph(lastY);
+    m_currentSpectrumDisplay->setVGraph(transPoints.first);
 
-    m_currentSpectrumDisplay->showInfoList( transPoints.first, lastY );
+    m_currentSpectrumDisplay->showInfoList(transPoints.first, lastY);
 
     // consume the event
     return true;
@@ -324,164 +315,146 @@ bool SVConnections::eventFilter(QObject *object, QEvent *event)
   return false;
 }
 
-
 /**
  * Slot to handle closing the window.
  */
-void SVConnections::closeViewer()
-{
-  m_svMainWindow->close();
-}
-
+void SVConnections::closeViewer() { m_svMainWindow->close(); }
 
 /**
  * Toggles the horizontal scroll bar.
  */
-void SVConnections::toggleHScroll()
-{
+void SVConnections::toggleHScroll() {
   bool is_on = m_svUI->action_Hscroll->isChecked();
-  m_svUI->imageHorizontalScrollBar->setVisible( is_on );
-  m_svUI->imageHorizontalScrollBar->setEnabled( is_on );
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+  m_svUI->imageHorizontalScrollBar->setVisible(is_on);
+  m_svUI->imageHorizontalScrollBar->setEnabled(is_on);
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateImage();
     (**displ).handleResize();
   }
 }
 
-
 /**
  * Toggles the vertical scroll bar.
  */
-void SVConnections::toggleVScroll()
-{
+void SVConnections::toggleVScroll() {
   bool is_on = m_svUI->action_Vscroll->isChecked();
-  m_svUI->imageVerticalScrollBar->setVisible( is_on );
-  m_svUI->imageVerticalScrollBar->setEnabled( is_on );
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+  m_svUI->imageVerticalScrollBar->setVisible(is_on);
+  m_svUI->imageVerticalScrollBar->setEnabled(is_on);
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateImage();
     (**displ).handleResize();
   }
 }
 
-
 /**
  * Update X range when range selection changed.
  */
-void SVConnections::imageHorizontalRangeChanged()
-{
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+void SVConnections::imageHorizontalRangeChanged() {
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateRange();
   }
 }
 
-
-void SVConnections::graphRangeChanged()
-{
+void SVConnections::graphRangeChanged() {
   double value = (double)m_svUI->graph_max_slider->value();
-  double min   = (double)m_svUI->graph_max_slider->minimum();
-  double max   = (double)m_svUI->graph_max_slider->maximum();
+  double min = (double)m_svUI->graph_max_slider->minimum();
+  double max = (double)m_svUI->graph_max_slider->maximum();
 
-  double range_scale = (value - min)/(max - min);
-  if ( range_scale < 0.01 )
+  double range_scale = (value - min) / (max - min);
+  if (range_scale < 0.01)
     range_scale = 0.01;
 
-  m_hGraphDisplay->setRangeScale( range_scale );
-  m_vGraphDisplay->setRangeScale( range_scale );
+  m_hGraphDisplay->setRangeScale(range_scale);
+  m_vGraphDisplay->setRangeScale(range_scale);
 }
 
-
 /**
  * Handles updating the image when a scroll bar is moved.
  */
-void SVConnections::scrollBarMoved()
-{
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+void SVConnections::scrollBarMoved() {
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateImage();
   }
 }
 
-
 /**
  * Handle the image splitter being moved.
  *
  * This moves the vertical graph slitter to the same position
  * in ordetr to keep the graphs in alignment.
  */
-void SVConnections::imageSplitterMoved()
-{
+void SVConnections::imageSplitterMoved() {
   QList<int> sizes = m_svUI->imageSplitter->sizes();
 
   QList<int> vgraph_sizes;
-  vgraph_sizes.append( sizes[0] );
-  vgraph_sizes.append( sizes[1] );
+  vgraph_sizes.append(sizes[0]);
+  vgraph_sizes.append(sizes[1]);
 
-  m_svUI->vgraphSplitter->setSizes( vgraph_sizes );
+  m_svUI->vgraphSplitter->setSizes(vgraph_sizes);
 
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateImage();
     (**displ).handleResize();
   }
 }
 
-
 /**
  * Handle the vertical graph splitter being moved.
  *
  * This moves the image slitter to the same position
  * in ordetr to keep the graphs in alignment.
  */
-void SVConnections::vgraphSplitterMoved()
-{
+void SVConnections::vgraphSplitterMoved() {
   QList<int> sizes = m_svUI->vgraphSplitter->sizes();
 
   QList<int> vgraph_sizes;
-  vgraph_sizes.append( sizes[0] );
-  vgraph_sizes.append( sizes[1] );
+  vgraph_sizes.append(sizes[0]);
+  vgraph_sizes.append(sizes[1]);
 
-  m_svUI->imageSplitter->setSizes( vgraph_sizes );
+  m_svUI->imageSplitter->setSizes(vgraph_sizes);
 
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
     (**displ).updateImage();
     (**displ).handleResize();
   }
 }
 
-
-
 /**
  * Update the pointed at position for the m_hGraphDisplay.
  *
  * @param point The position moved to.
  */
-void SVConnections::hGraphPickerMoved(const QPoint & point)
-{
+void SVConnections::hGraphPickerMoved(const QPoint &point) {
   m_hGraphDisplay->setPointedAtPoint(point);
 }
 
-
 /**
  * Update the pointed at position for the m_vGraphDisplay.
  *
  * @param point The position moved to.
  */
-void SVConnections::vGraphPickerMoved(const QPoint & point)
-{
+void SVConnections::vGraphPickerMoved(const QPoint &point) {
   m_vGraphDisplay->setPointedAtPoint(point);
 }
 
-
 /**
  * Slot to handle the intensity slider being moved.
  */
-void SVConnections::intensitySliderMoved()
-{
+void SVConnections::intensitySliderMoved() {
   double value = (double)m_svUI->intensity_slider->value();
-  double min   = (double)m_svUI->intensity_slider->minimum();
-  double max   = (double)m_svUI->intensity_slider->maximum();
+  double min = (double)m_svUI->intensity_slider->minimum();
+  double max = (double)m_svUI->intensity_slider->maximum();
 
-  double scaled_value = 100.0*(value - min)/(max - min);
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
-    (**displ).setIntensity( scaled_value );
+  double scaled_value = 100.0 * (value - min) / (max - min);
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
+    (**displ).setIntensity(scaled_value);
   }
 }
 
@@ -560,32 +533,32 @@ void SVConnections::spectrumColorScale() {
 /**
  * Slot to handle loading a color map from file.
  */
-void SVConnections::loadColorMap()
-{
-  QString file_name = MantidColorMap::loadMapDialog( "", m_svMainWindow );
+void SVConnections::loadColorMap() {
+  QString file_name = MantidColorMap::loadMapDialog("", m_svMainWindow);
 
-  MantidColorMap* mantid_color_map = new MantidColorMap( file_name, GraphOptions::Linear );
+  MantidColorMap *mantid_color_map =
+      new MantidColorMap(file_name, GraphOptions::Linear);
 
-  QwtDoubleInterval interval( 0.0, 255.0 );
+  QwtDoubleInterval interval(0.0, 255.0);
   QVector<QRgb> mantid_color_table;
-  mantid_color_table = mantid_color_map->colorTable( interval );
+  mantid_color_table = mantid_color_map->colorTable(interval);
   std::vector<QRgb> positive_color_table;
-  for ( int i = 1; i < mantid_color_table.size(); i++ )     // NO NaN Color
+  for (int i = 1; i < mantid_color_table.size(); i++) // NO NaN Color
   {
-    positive_color_table.push_back( mantid_color_table[i] );
+    positive_color_table.push_back(mantid_color_table[i]);
   }
 
   int n_colors = (int)positive_color_table.size();
 
   auto negative_color_table = ColorMaps::GetColorMap(ColorMaps::GRAY, n_colors);
 
-  for(auto displ = m_spectrumDisplays.begin(); displ != m_spectrumDisplays.end(); ++displ) {
-    (**displ).setColorScales( positive_color_table, negative_color_table );
+  for (auto displ = m_spectrumDisplays.begin();
+       displ != m_spectrumDisplays.end(); ++displ) {
+    (**displ).setColorScales(positive_color_table, negative_color_table);
   }
-  showColorScale( positive_color_table, negative_color_table );
+  showColorScale(positive_color_table, negative_color_table);
 }
 
-
 /**
  *  Set the pix map that shows the color scale from the specified positive
  *  and negative color tables.
@@ -597,46 +570,42 @@ void SVConnections::loadColorMap()
  *                             same number of entries as the positive
  *                             color table.
  */
-void SVConnections::showColorScale( std::vector<QRgb> & positiveColorTable,
-                                    std::vector<QRgb> & negativeColorTable )
-{
+void SVConnections::showColorScale(std::vector<QRgb> &positiveColorTable,
+                                   std::vector<QRgb> &negativeColorTable) {
   size_t totalColors = positiveColorTable.size() + negativeColorTable.size();
 
   QImage image((int)totalColors, 1, QImage::Format_RGB32);
   int index = 0;
 
   size_t numColors = negativeColorTable.size();
-  for(size_t i = 0; i < numColors; i++)
-  {
-    unsigned int pixel = static_cast<unsigned int>(negativeColorTable[numColors - 1 - i]);
+  for (size_t i = 0; i < numColors; i++) {
+    unsigned int pixel =
+        static_cast<unsigned int>(negativeColorTable[numColors - 1 - i]);
     image.setPixel(index, 0, pixel);
     index++;
   }
 
   numColors = positiveColorTable.size();
-  for(size_t i = 0; i < numColors; i++)
-  {
+  for (size_t i = 0; i < numColors; i++) {
     unsigned int pixel = static_cast<unsigned int>(positiveColorTable[i]);
     image.setPixel(index, 0, pixel);
     index++;
   }
 
   QPixmap pixmap = QPixmap::fromImage(image);
-  m_svUI->color_scale->setPixmap( pixmap );
+  m_svUI->color_scale->setPixmap(pixmap);
 }
 
-
 /**
  * Slot to open the online help webapge for the interface.
  */
-void SVConnections::openOnlineHelp()
-{
-  MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("SpectrumViewer"));
+void SVConnections::openOnlineHelp() {
+  MantidQt::API::HelpWindow::showCustomInterface(NULL,
+                                                 QString("SpectrumViewer"));
 }
 
-/// Set the display which is currently visible 
-void SVConnections::setSpectrumDisplay(SpectrumDisplay* spectrumDisplay)
-{
+/// Set the display which is currently visible
+void SVConnections::setSpectrumDisplay(SpectrumDisplay *spectrumDisplay) {
   if (!m_spectrumDisplays.contains(spectrumDisplay)) {
     m_spectrumDisplays.append(spectrumDisplay);
   }
@@ -645,11 +614,11 @@ void SVConnections::setSpectrumDisplay(SpectrumDisplay* spectrumDisplay)
   m_currentSpectrumDisplay->setTrackingOn(m_svMainWindow->isTrackingOn());
 }
 /// Get the currently visible display
-SpectrumDisplay* SVConnections::getCurrentSpectrumDisplay() const {
+SpectrumDisplay *SVConnections::getCurrentSpectrumDisplay() const {
   return m_currentSpectrumDisplay;
 }
 
-void SVConnections::removeSpectrumDisplay(SpectrumDisplay* spectrumDisplay) {
+void SVConnections::removeSpectrumDisplay(SpectrumDisplay *spectrumDisplay) {
   if (m_spectrumDisplays.contains(spectrumDisplay)) {
     m_spectrumDisplays.removeAll(spectrumDisplay);
   }
diff --git a/MantidQt/SpectrumViewer/src/SliderHandler.cpp b/MantidQt/SpectrumViewer/src/SliderHandler.cpp
index 715029998eacdf4deb8abc781b9b2b9414a24471..056d9af8afaad6265c8074b0394687383d3d8974 100644
--- a/MantidQt/SpectrumViewer/src/SliderHandler.cpp
+++ b/MantidQt/SpectrumViewer/src/SliderHandler.cpp
@@ -3,20 +3,15 @@
 #include "MantidQtSpectrumViewer/SliderHandler.h"
 #include "MantidQtSpectrumViewer/SVUtils.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct a SliderHandler object to manage the image scrollbars from the
  *  specified UI.
  */
-SliderHandler::SliderHandler( Ui_SpectrumViewer* svUI )
-  : ISliderHandler(), m_svUI(svUI)
-{
-}
-
+SliderHandler::SliderHandler(Ui_SpectrumViewer *svUI)
+    : ISliderHandler(), m_svUI(svUI) {}
 
 /**
  * Reconfigure the image scrollbars for the specified data and drawing area.
@@ -27,21 +22,19 @@ SliderHandler::SliderHandler( Ui_SpectrumViewer* svUI )
  *                    be drawn
  * @param dataSource  SpectrumDataSource that provides the data to be drawn
  */
-void SliderHandler::reConfigureSliders( QRect drawArea,
-                                        SpectrumDataSource_sptr dataSource )
-{
-  QScrollBar* vScroll = m_svUI->imageVerticalScrollBar;
+void SliderHandler::reConfigureSliders(QRect drawArea,
+                                       SpectrumDataSource_sptr dataSource) {
+  QScrollBar *vScroll = m_svUI->imageVerticalScrollBar;
 
   int oldVValue = vScroll->value();
   int numRows = (int)dataSource->getNRows();
-  int step  = vScroll->pageStep();
+  int step = vScroll->pageStep();
 
-  configureSlider( vScroll, numRows, drawArea.height(), oldVValue );
+  configureSlider(vScroll, numRows, drawArea.height(), oldVValue);
 
   vScroll->setValue(oldVValue + (step / 2));
 }
 
-
 /**
  * Configure the image scrollbars for the specified data and drawing area.
  *
@@ -49,17 +42,15 @@ void SliderHandler::reConfigureSliders( QRect drawArea,
  *                    be drawn
  * @param dataSource  SpectrumDataSource that provides the data to be drawn
  */
-void SliderHandler::configureSliders( QRect drawArea,
-                                      SpectrumDataSource_sptr dataSource )
-{
-  QScrollBar* vScroll = m_svUI->imageVerticalScrollBar;
+void SliderHandler::configureSliders(QRect drawArea,
+                                     SpectrumDataSource_sptr dataSource) {
+  QScrollBar *vScroll = m_svUI->imageVerticalScrollBar;
   int numRows = (int)dataSource->getNRows();
-  configureSlider( vScroll, numRows, drawArea.height(), numRows );
+  configureSlider(vScroll, numRows, drawArea.height(), numRows);
 
-  configureHSlider( 2000, drawArea.width() );   // initial default, 2000 bins
+  configureHSlider(2000, drawArea.width()); // initial default, 2000 bins
 }
 
-
 /**
  *  Public method to configure the horizontal scrollbar to cover the
  *  specified range of data columns, displayed in the specified number of
@@ -69,14 +60,11 @@ void SliderHandler::configureSliders( QRect drawArea,
  *                       displayed
  *  @param numPixels      The number of pixels avaliable to show the data
  */
-void SliderHandler::configureHSlider( int numDataSetps,
-                                      int numPixels )
-{
-  QScrollBar* hScroll = m_svUI->imageHorizontalScrollBar;
-  configureSlider( hScroll, numDataSetps, numPixels, 0 );
+void SliderHandler::configureHSlider(int numDataSetps, int numPixels) {
+  QScrollBar *hScroll = m_svUI->imageHorizontalScrollBar;
+  configureSlider(hScroll, numDataSetps, numPixels, 0);
 }
 
-
 /**
  *  Configure the specified scrollbar to cover the specified range of data
  *  steps, displayed in the specified number of pixels.
@@ -88,53 +76,45 @@ void SliderHandler::configureHSlider( int numDataSetps,
  *  @param val           The initial position of the scrollbar, between 0 and
  *                       numDataSetps.
  */
-void SliderHandler::configureSlider( QScrollBar* scrollBar,
-                                     int         numDataSetps,
-                                     int         numPixels,
-                                     int         val )
-{
+void SliderHandler::configureSlider(QScrollBar *scrollBar, int numDataSetps,
+                                    int numPixels, int val) {
   int step = numPixels;
-  if ( step > numDataSetps )
+  if (step > numDataSetps)
     step = numDataSetps;
 
-  if ( step <= 0 )
+  if (step <= 0)
     step = 1;
 
-  int max  = numDataSetps - step;
-  if ( max <= 0 )
+  int max = numDataSetps - step;
+  if (max <= 0)
     max = 0;
 
-  if ( val < 0 )
+  if (val < 0)
     val = 0;
 
-  if ( val > max )
+  if (val > max)
     val = max;
 
-  scrollBar->setMinimum( 0 );
-  scrollBar->setMaximum( max );
-  scrollBar->setPageStep( step );
-  scrollBar->setValue( val );
+  scrollBar->setMinimum(0);
+  scrollBar->setMaximum(max);
+  scrollBar->setPageStep(step);
+  scrollBar->setValue(val);
 }
 
-
 /**
  * Return true if the image horizontal scrollbar is enabled.
  */
-bool SliderHandler::hSliderOn()
-{
+bool SliderHandler::hSliderOn() {
   return m_svUI->imageHorizontalScrollBar->isEnabled();
 }
 
-
 /**
  * Return true if the image vertical scrollbar is enabled.
  */
-bool SliderHandler::vSliderOn()
-{
+bool SliderHandler::vSliderOn() {
   return m_svUI->imageVerticalScrollBar->isEnabled();
 }
 
-
 /**
  * Get the range of columns to display in the image.  NOTE: x_min will be
  * the smaller column number in the array, corresponding to lower values on
@@ -145,17 +125,15 @@ bool SliderHandler::vSliderOn()
  * @param x_max   This will be set to the last bin number to display in the
  *                x direction
  */
-void SliderHandler::getHSliderInterval( int &x_min, int &x_max )
-{
-  QScrollBar* hScroll = m_svUI->imageHorizontalScrollBar;
-  int step  = hScroll->pageStep();
+void SliderHandler::getHSliderInterval(int &x_min, int &x_max) {
+  QScrollBar *hScroll = m_svUI->imageHorizontalScrollBar;
+  int step = hScroll->pageStep();
   int value = hScroll->value();
 
   x_min = value;
   x_max = x_min + step;
 }
 
-
 /**
  * Get the range of rows to display in the image.  NOTE: y_min will be
  * the smaller row number in the array, corresponding to lower values on
@@ -166,18 +144,16 @@ void SliderHandler::getHSliderInterval( int &x_min, int &x_max )
  * @param y_max   This will be set to the last bin number to display in the
  *                y direction
  */
-void SliderHandler::getVSliderInterval( int &y_min, int &y_max )
-{
-  QScrollBar* vScroll = m_svUI->imageVerticalScrollBar;
-  int max   = vScroll->maximum();
-  int step  = vScroll->pageStep();
+void SliderHandler::getVSliderInterval(int &y_min, int &y_max) {
+  QScrollBar *vScroll = m_svUI->imageVerticalScrollBar;
+  int max = vScroll->maximum();
+  int step = vScroll->pageStep();
   int value = vScroll->value();
 
-  y_min = max - value;        // invert value since scale increases from
-  y_max = y_min + step;       // bottom to top, but scroll bar increases
-                              // the other way.
+  y_min = max - value;  // invert value since scale increases from
+  y_max = y_min + step; // bottom to top, but scroll bar increases
+                        // the other way.
 }
 
-
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/src/SpectrumDataSource.cpp b/MantidQt/SpectrumViewer/src/SpectrumDataSource.cpp
index 680ceb0a500e665e692aa6cb7f7903391db09e9c..6fa9e95aca49acddb510872bfb6682bde562d18e 100644
--- a/MantidQt/SpectrumViewer/src/SpectrumDataSource.cpp
+++ b/MantidQt/SpectrumViewer/src/SpectrumDataSource.cpp
@@ -3,10 +3,8 @@
 
 #include "MantidQtSpectrumViewer/SpectrumDataSource.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct data source with specified total range and data size.
@@ -18,142 +16,102 @@ namespace SpectrumView
  *  @param totalRows  The total number of rows the data is divided into
  *  @param totalCols  The total number of columns the data is divided into
  */
-SpectrumDataSource::SpectrumDataSource( double totalXMin, double totalXMax,
-                                        double totalYMin, double totalYMax,
-                                        size_t totalRows, size_t totalCols ) :
-  m_totalXMin(totalXMin), m_totalXMax(totalXMax),
-  m_totalYMin(totalYMin), m_totalYMax(totalYMax),
-  m_totalRows(totalRows), m_totalCols(totalCols)
-{
-}
-
-
-SpectrumDataSource::~SpectrumDataSource()
-{
-}
+SpectrumDataSource::SpectrumDataSource(double totalXMin, double totalXMax,
+                                       double totalYMin, double totalYMax,
+                                       size_t totalRows, size_t totalCols)
+    : m_totalXMin(totalXMin), m_totalXMax(totalXMax), m_totalYMin(totalYMin),
+      m_totalYMax(totalYMax), m_totalRows(totalRows), m_totalCols(totalCols) {}
 
+SpectrumDataSource::~SpectrumDataSource() {}
 
 /**
  * Get the smallest 'x' value covered by the data.
  */
-double SpectrumDataSource::getXMin()
-{
-  return m_totalXMin;
-}
-
+double SpectrumDataSource::getXMin() { return m_totalXMin; }
 
 /**
  * Get the largest 'x' value covered by the data.
  */
-double SpectrumDataSource::getXMax()
-{
-  return m_totalXMax;
-}
-
+double SpectrumDataSource::getXMax() { return m_totalXMax; }
 
 /**
  * Get the smallest 'y' value covered by the data.
  */
-double SpectrumDataSource::getYMin()
-{
-  return m_totalYMin;
-}
-
+double SpectrumDataSource::getYMin() { return m_totalYMin; }
 
 /**
  * Get the largest 'y' value covered by the data.
  */
-double SpectrumDataSource::getYMax()
-{
-  return m_totalYMax;
-}
-
+double SpectrumDataSource::getYMax() { return m_totalYMax; }
 
 /**
  * Get the total number of rows the data is divided into
  */
-size_t SpectrumDataSource::getNRows()
-{
-  return m_totalRows;
-}
-
+size_t SpectrumDataSource::getNRows() { return m_totalRows; }
 
 /**
  * Get the total number of columns the data is divided into
  */
-size_t SpectrumDataSource::getNCols()
-{
-  return m_totalCols;
-}
-
+size_t SpectrumDataSource::getNCols() { return m_totalCols; }
 
 /**
  * Clamp x to the interval of x-values covered by this DataSource
  * @param x   If x is more than xmax it will be set to xmax. If x is less
  *            than xmin, it will be set to xmin.
  */
-void SpectrumDataSource::restrictX( double & x )
-{
-  if ( x > m_totalXMax )
+void SpectrumDataSource::restrictX(double &x) {
+  if (x > m_totalXMax)
     x = m_totalXMax;
 
-  else if ( x < m_totalXMin )
+  else if (x < m_totalXMin)
     x = m_totalXMin;
 }
 
-
 /**
  * Clamp y to the interval of y-values covered by this DataSource.
  * @param y   If y is more than ymax it will be set to ymax. If y is less
  *            than ymin, it will be set to ymin.
  */
-void SpectrumDataSource::restrictY( double & y )
-{
-  if ( y > m_totalYMax )
+void SpectrumDataSource::restrictY(double &y) {
+  if (y > m_totalYMax)
     y = m_totalYMax;
 
-  else if ( y < m_totalYMin )
+  else if (y < m_totalYMin)
     y = m_totalYMin;
 }
 
-
 /**
  * Clamp row to a valid row number for this DataSource.
  * @param row  If row is more than n_rows-1, it is set to n_rows-1.  If
  *             row < 0 it is set to zero.
  */
-void SpectrumDataSource::restrictRow( int & row )
-{
-  if ( row >= (int)m_totalRows )
+void SpectrumDataSource::restrictRow(int &row) {
+  if (row >= (int)m_totalRows)
     row = (int)m_totalRows - 1;
 
-  else if ( row < 0 )
+  else if (row < 0)
     row = 0;
 }
 
-
 /**
  * Clamp col to a valid column number for this DataSource.
  * @param col  If col is more than n_cols-1, it is set to n_cols-1.  If
  *             col < 0 it is set to zero.
  */
-void SpectrumDataSource::restrictCol( int & col )
-{
-  if ( col >= (int)m_totalCols )
+void SpectrumDataSource::restrictCol(int &col) {
+  if (col >= (int)m_totalCols)
     col = (int)m_totalCols - 1;
 
-  else if ( col < 0 )
+  else if (col < 0)
     col = 0;
 }
 
-
 /**
  *  Convenience method to get all the data at the maximum resolution.
  */
-DataArray_const_sptr SpectrumDataSource::getDataArray( bool isLogX )
-{
-  return getDataArray( m_totalXMin, m_totalXMax, m_totalYMin, m_totalYMax,
-                       m_totalRows, m_totalCols, isLogX );
+DataArray_const_sptr SpectrumDataSource::getDataArray(bool isLogX) {
+  return getDataArray(m_totalXMin, m_totalXMax, m_totalYMin, m_totalYMax,
+                      m_totalRows, m_totalCols, isLogX);
 }
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/src/SpectrumDisplay.cpp b/MantidQt/SpectrumViewer/src/SpectrumDisplay.cpp
index 31970bb57724caea8a24e628396df03fcbed5cf9..a2996dcb0568cfe3287825321915608f260da4eb 100644
--- a/MantidQt/SpectrumViewer/src/SpectrumDisplay.cpp
+++ b/MantidQt/SpectrumViewer/src/SpectrumDisplay.cpp
@@ -16,10 +16,8 @@
 #include "MantidQtSpectrumViewer/SliderHandler.h"
 #include "MantidQtSpectrumViewer/TrackingPicker.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Make an SpectrumDisplay to display with the given widgets and controls.
@@ -36,30 +34,22 @@ namespace SpectrumView
  *                       at location will be displayed.
  * @param isTrackingOn  Flag to start SpectrumDisplay with tracking on or off.
  */
-SpectrumDisplay::SpectrumDisplay(  QwtPlot*         spectrumPlot,
-                                   ISliderHandler*  sliderHandler,
-                                   IRangeHandler*   rangeHander,
-                                   GraphDisplay*    hGraph,
-                                   GraphDisplay*    vGraph,
-                                   QTableWidget*    tableWidget,
-                                   bool             isTrackingOn) :
-  m_spectrumPlot(spectrumPlot),
-  m_sliderHandler(sliderHandler),
-  m_rangeHandler(rangeHander),
-  m_hGraphDisplay(hGraph),
-  m_vGraphDisplay(vGraph),
-  m_pointedAtX(0.0), m_pointedAtY(0.0),
-  m_imageTable(tableWidget),
-  m_totalXMin(0.0), m_totalXMax(0.0),
-  m_totalYMin(0.0), m_totalYMax(0.0),
-  m_imagePicker(NULL)
-{
+SpectrumDisplay::SpectrumDisplay(QwtPlot *spectrumPlot,
+                                 ISliderHandler *sliderHandler,
+                                 IRangeHandler *rangeHander,
+                                 GraphDisplay *hGraph, GraphDisplay *vGraph,
+                                 QTableWidget *tableWidget, bool isTrackingOn)
+    : m_spectrumPlot(spectrumPlot), m_sliderHandler(sliderHandler),
+      m_rangeHandler(rangeHander), m_hGraphDisplay(hGraph),
+      m_vGraphDisplay(vGraph), m_pointedAtX(0.0), m_pointedAtY(0.0),
+      m_imageTable(tableWidget), m_totalXMin(0.0), m_totalXMax(0.0),
+      m_totalYMin(0.0), m_totalYMax(0.0), m_imagePicker(NULL) {
   m_positiveColorTable = ColorMaps::GetColorMap(ColorMaps::HEAT, 256);
   m_negativeColorTable = ColorMaps::GetColorMap(ColorMaps::GRAY, 256);
 
   m_spectrumPlotItem = new SpectrumPlotItem;
   setupSpectrumPlotItem();
-  m_imagePicker = new TrackingPicker( spectrumPlot->canvas() );
+  m_imagePicker = new TrackingPicker(spectrumPlot->canvas());
   m_imagePicker->setMousePattern(QwtPicker::MouseSelect1, Qt::LeftButton);
   if (isTrackingOn) {
     m_imagePicker->setTrackerMode(QwtPicker::AlwaysOn);
@@ -70,38 +60,30 @@ SpectrumDisplay::SpectrumDisplay(  QwtPlot*         spectrumPlot,
 
   m_imagePicker->setRubberBand(QwtPicker::CrossRubberBand);
   m_imagePicker->setSelectionFlags(QwtPicker::PointSelection |
-                                  QwtPicker::DragSelection  );
-  QObject::connect( m_imagePicker, SIGNAL(mouseMoved(const QPoint &)),
-                    this, SLOT(imagePickerMoved(const QPoint &)) );
+                                   QwtPicker::DragSelection);
+  QObject::connect(m_imagePicker, SIGNAL(mouseMoved(const QPoint &)), this,
+                   SLOT(imagePickerMoved(const QPoint &)));
 }
 
+SpectrumDisplay::~SpectrumDisplay() { delete m_spectrumPlotItem; }
 
-SpectrumDisplay::~SpectrumDisplay()
-{
-  delete m_spectrumPlotItem;
-}
-
-
-bool SpectrumDisplay::hasData(const std::string& wsName,
-                              const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
+bool SpectrumDisplay::hasData(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
   return m_dataSource->hasData(wsName, ws);
 }
 
-
 /// Set some properties of the SpectrumPlotItem object
-void SpectrumDisplay::setupSpectrumPlotItem()
-{
-  m_spectrumPlotItem->setXAxis( QwtPlot::xBottom );
-  m_spectrumPlotItem->setYAxis( QwtPlot::yLeft );
+void SpectrumDisplay::setupSpectrumPlotItem() {
+  m_spectrumPlotItem->setXAxis(QwtPlot::xBottom);
+  m_spectrumPlotItem->setYAxis(QwtPlot::yLeft);
 
-  m_spectrumPlotItem->attach( m_spectrumPlot );
+  m_spectrumPlotItem->attach(m_spectrumPlot);
 
   double DEFAULT_INTENSITY = 30;
-  setIntensity( DEFAULT_INTENSITY );
+  setIntensity(DEFAULT_INTENSITY);
 }
 
-
 /**
  * Set the data source from which the image and data table information will
  * be obtained.
@@ -109,12 +91,11 @@ void SpectrumDisplay::setupSpectrumPlotItem()
  * @param dataSource The SpectrumDataSource that provides the array of values
  *                    and information for the table.
  */
-void SpectrumDisplay::setDataSource( SpectrumDataSource_sptr dataSource )
-{
+void SpectrumDisplay::setDataSource(SpectrumDataSource_sptr dataSource) {
   m_dataSource = dataSource;
 
-  m_hGraphDisplay->setDataSource( m_dataSource );
-  m_vGraphDisplay->setDataSource( m_dataSource );
+  m_hGraphDisplay->setDataSource(m_dataSource);
+  m_vGraphDisplay->setDataSource(m_dataSource);
 
   m_totalYMin = m_dataSource->getYMin();
   m_totalYMax = m_dataSource->getYMax();
@@ -125,213 +106,192 @@ void SpectrumDisplay::setDataSource( SpectrumDataSource_sptr dataSource )
   m_pointedAtX = DBL_MAX;
   m_pointedAtY = DBL_MAX;
 
-  int n_rows = static_cast<int>(m_totalYMax - m_totalYMin); // get reasonable size initial image data
+  int n_rows = static_cast<int>(
+      m_totalYMax - m_totalYMin); // get reasonable size initial image data
   int n_cols = 500;
 
   // m_dataArray is deleted in the SpectrumPlotItem
-  m_dataArray = m_dataSource->getDataArray( m_totalXMin, m_totalXMax,
-                                            m_totalYMin, m_totalYMax,
-                                            n_rows, n_cols,
-                                            false );
+  m_dataArray =
+      m_dataSource->getDataArray(m_totalXMin, m_totalXMax, m_totalYMin,
+                                 m_totalYMax, n_rows, n_cols, false);
 
-  m_spectrumPlot->setAxisScale( QwtPlot::xBottom, m_dataArray->getXMin(), m_dataArray->getXMax() );
-  m_spectrumPlot->setAxisScale( QwtPlot::yLeft,   m_dataArray->getYMin(), m_dataArray->getYMax() );
+  m_spectrumPlot->setAxisScale(QwtPlot::xBottom, m_dataArray->getXMin(),
+                               m_dataArray->getXMax());
+  m_spectrumPlot->setAxisScale(QwtPlot::yLeft, m_dataArray->getYMin(),
+                               m_dataArray->getYMax());
 
-  m_spectrumPlotItem->setData( m_dataArray,
-                               &m_positiveColorTable,
-                               &m_negativeColorTable );
+  m_spectrumPlotItem->setData(m_dataArray, &m_positiveColorTable,
+                              &m_negativeColorTable);
 
-  m_rangeHandler->configureRangeControls( m_dataSource );
+  m_rangeHandler->configureRangeControls(m_dataSource);
 
   QRect drawArea;
-  getDisplayRectangle( drawArea );
-  m_sliderHandler->configureSliders( drawArea, m_dataSource );
+  getDisplayRectangle(drawArea);
+  m_sliderHandler->configureSliders(drawArea, m_dataSource);
 }
 
-
 /**
  *  Rebuild the scrollbars and image due to a change in the range xmin, xmax
  *  or step size.  It should be invoked when the user changes the values in
  *  the xmin, xmax or step controls.  It should not be called directly from
  *  other threads.
  */
-void SpectrumDisplay::updateRange()
-{
-  if ( m_dataSource == 0 )
-    return;   // No image data to update
+void SpectrumDisplay::updateRange() {
+  if (m_dataSource == 0)
+    return; // No image data to update
 
-  if ( dataSourceRangeChanged() )
-    setDataSource( m_dataSource );   // Re-initialize with the altered source
+  if (dataSourceRangeChanged())
+    setDataSource(m_dataSource); // Re-initialize with the altered source
 
   QRect displayRect;
-  getDisplayRectangle( displayRect );
+  getDisplayRectangle(displayRect);
   // Range controls now determine the number of bins
 
-  double min  = m_totalXMin;
-  double max  = m_totalXMax;
+  double min = m_totalXMin;
+  double max = m_totalXMax;
   double step = (m_totalXMax - m_totalXMin) / 2000;
-  m_rangeHandler->getRange( min, max, step );
+  m_rangeHandler->getRange(min, max, step);
 
-  int numBins = SVUtils::NumSteps( min, max, step );
-  if ( numBins == 0 )
+  int numBins = SVUtils::NumSteps(min, max, step);
+  if (numBins == 0)
     return;
 
-  m_sliderHandler->configureHSlider( numBins, displayRect.width() );
+  m_sliderHandler->configureHSlider(numBins, displayRect.width());
 
   updateImage();
 }
 
-
 /**
  * Updates the rnages of the scroll bars when the window is resized.
  */
-void SpectrumDisplay::handleResize()
-{
+void SpectrumDisplay::handleResize() {
   QRect draw_area;
-  getDisplayRectangle( draw_area );
+  getDisplayRectangle(draw_area);
 
   // Notify the sliders of the resize
-  SliderHandler * sliderHandler = dynamic_cast<SliderHandler*>(m_sliderHandler);
-  if(sliderHandler)
+  SliderHandler *sliderHandler = dynamic_cast<SliderHandler *>(m_sliderHandler);
+  if (sliderHandler)
     sliderHandler->reConfigureSliders(draw_area, m_dataSource);
 }
 
-
 /**
  *  This will rebuild the image from the data source.  It should be invoked
  *  when the scroll bar is moved, the plot area is resize or the color or
  *  intensity tables are changed.  It should not be called directly from
  *  other threads.
  */
-void SpectrumDisplay::updateImage()
-{
-  if ( m_dataSource == 0 )
-  {
-    return;   // no image data to update
+void SpectrumDisplay::updateImage() {
+  if (m_dataSource == 0) {
+    return; // no image data to update
   }
 
-  if ( dataSourceRangeChanged() )
-  {
-    setDataSource( m_dataSource );   // re-initialize with the altered source
+  if (dataSourceRangeChanged()) {
+    setDataSource(m_dataSource); // re-initialize with the altered source
   }
 
   QRect display_rect;
-  getDisplayRectangle( display_rect );
+  getDisplayRectangle(display_rect);
 
   double scale_y_min = m_dataSource->getYMin();
   double scale_y_max = m_dataSource->getYMax();
 
-  double scale_x_min  = m_totalXMin;
-  double scale_x_max  = m_totalXMax;
-  double x_step = (m_totalXMax - m_totalXMin)/2000;
+  double scale_x_min = m_totalXMin;
+  double scale_x_max = m_totalXMax;
+  double x_step = (m_totalXMax - m_totalXMin) / 2000;
 
-  m_rangeHandler->getRange( scale_x_min, scale_x_max, x_step );
+  m_rangeHandler->getRange(scale_x_min, scale_x_max, x_step);
 
   int n_rows = (int)m_dataSource->getNRows();
-  int n_cols = SVUtils::NumSteps( scale_x_min, scale_x_max, x_step );
+  int n_cols = SVUtils::NumSteps(scale_x_min, scale_x_max, x_step);
 
-                                     // This works for linear or log scales
-  if ( n_rows == 0 || n_cols == 0 )
-  {
-    return;                          // can't draw empty image
+  // This works for linear or log scales
+  if (n_rows == 0 || n_cols == 0) {
+    return; // can't draw empty image
   }
 
-  if ( m_sliderHandler->vSliderOn() )
-  {
+  if (m_sliderHandler->vSliderOn()) {
     int y_min;
     int y_max;
-    m_sliderHandler->getVSliderInterval( y_min, y_max );
+    m_sliderHandler->getVSliderInterval(y_min, y_max);
 
     double new_y_min = 0;
     double new_y_max = 0;
 
-    SVUtils::Interpolate( 0, n_rows, y_min,
-                          scale_y_min, scale_y_max, new_y_min );
-    SVUtils::Interpolate( 0, n_rows, y_max,
-                          scale_y_min, scale_y_max, new_y_max );
+    SVUtils::Interpolate(0, n_rows, y_min, scale_y_min, scale_y_max, new_y_min);
+    SVUtils::Interpolate(0, n_rows, y_max, scale_y_min, scale_y_max, new_y_max);
 
     scale_y_min = new_y_min;
     scale_y_max = new_y_max;
   }
 
-  if ( m_sliderHandler->hSliderOn() )
-  {
+  if (m_sliderHandler->hSliderOn()) {
     int x_min;
     int x_max;
-    m_sliderHandler->getHSliderInterval( x_min, x_max );
-                            // NOTE: The interval [xmin,xmax] is always
-                            // found linearly.  For log_x, we need to adjust it
+    m_sliderHandler->getHSliderInterval(x_min, x_max);
+    // NOTE: The interval [xmin,xmax] is always
+    // found linearly.  For log_x, we need to adjust it
 
     double new_x_min = 0;
     double new_x_max = 0;
 
-    if ( x_step > 0 )       // linear scale, so interpolate linearly
+    if (x_step > 0) // linear scale, so interpolate linearly
     {
-      SVUtils::Interpolate( 0, n_cols, x_min,
-                            scale_x_min, scale_x_max, new_x_min );
-      SVUtils::Interpolate( 0, n_cols, x_max,
-                            scale_x_min, scale_x_max, new_x_max );
-    }
-    else                    // log scale, so interpolate "logarithmically"
+      SVUtils::Interpolate(0, n_cols, x_min, scale_x_min, scale_x_max,
+                           new_x_min);
+      SVUtils::Interpolate(0, n_cols, x_max, scale_x_min, scale_x_max,
+                           new_x_max);
+    } else // log scale, so interpolate "logarithmically"
     {
-      SVUtils::LogInterpolate( 0, n_cols, x_min,
-                               scale_x_min, scale_x_max, new_x_min );
-      SVUtils::LogInterpolate( 0, n_cols, x_max,
-                               scale_x_min, scale_x_max, new_x_max );
+      SVUtils::LogInterpolate(0, n_cols, x_min, scale_x_min, scale_x_max,
+                              new_x_min);
+      SVUtils::LogInterpolate(0, n_cols, x_max, scale_x_min, scale_x_max,
+                              new_x_max);
     }
 
     scale_x_min = new_x_min;
     scale_x_max = new_x_max;
   }
 
-  if ( n_rows > display_rect.height() )
-  {
+  if (n_rows > display_rect.height()) {
     n_rows = display_rect.height();
   }
 
-  if ( n_cols > display_rect.width() )
-  {
+  if (n_cols > display_rect.width()) {
     n_cols = display_rect.width();
   }
 
-  bool is_log_x = ( x_step < 0 );
-                                         // NOTE: The DataArray is deleted
-  m_dataArray = m_dataSource->getDataArray( scale_x_min, scale_x_max,
-                                            scale_y_min, scale_y_max,
-                                            n_rows, n_cols,
-                                            is_log_x );
+  bool is_log_x = (x_step < 0);
+  // NOTE: The DataArray is deleted
+  m_dataArray =
+      m_dataSource->getDataArray(scale_x_min, scale_x_max, scale_y_min,
+                                 scale_y_max, n_rows, n_cols, is_log_x);
 
-  is_log_x = m_dataArray->isLogX();       // Data source might not be able to
-                                         // provide log binned data, so check
-                                         // if log binned data was returned.
+  is_log_x = m_dataArray->isLogX(); // Data source might not be able to
+                                    // provide log binned data, so check
+                                    // if log binned data was returned.
 
-  m_spectrumPlot->setAxisScale( QwtPlot::xBottom, m_dataArray->getXMin(),
-                                                  m_dataArray->getXMax() );
+  m_spectrumPlot->setAxisScale(QwtPlot::xBottom, m_dataArray->getXMin(),
+                               m_dataArray->getXMax());
 
-  if ( is_log_x )
-  {
-    QwtLog10ScaleEngine* log_engine = new QwtLog10ScaleEngine();
-    m_spectrumPlot->setAxisScaleEngine( QwtPlot::xBottom, log_engine );
-  }
-  else
-  {
-    QwtLinearScaleEngine* linear_engine = new QwtLinearScaleEngine();
-    m_spectrumPlot->setAxisScaleEngine( QwtPlot::xBottom, linear_engine );
+  if (is_log_x) {
+    QwtLog10ScaleEngine *log_engine = new QwtLog10ScaleEngine();
+    m_spectrumPlot->setAxisScaleEngine(QwtPlot::xBottom, log_engine);
+  } else {
+    QwtLinearScaleEngine *linear_engine = new QwtLinearScaleEngine();
+    m_spectrumPlot->setAxisScaleEngine(QwtPlot::xBottom, linear_engine);
   }
 
-  m_spectrumPlot->setAxisScale( QwtPlot::yLeft, m_dataArray->getYMin(),
-                                                m_dataArray->getYMax() );
+  m_spectrumPlot->setAxisScale(QwtPlot::yLeft, m_dataArray->getYMin(),
+                               m_dataArray->getYMax());
 
-  m_spectrumPlotItem->setData( m_dataArray,
-                               &m_positiveColorTable,
-                               &m_negativeColorTable );
+  m_spectrumPlotItem->setData(m_dataArray, &m_positiveColorTable,
+                              &m_negativeColorTable);
   m_spectrumPlot->replot();
 
-  setVGraph( m_pointedAtX );
-  setHGraph( m_pointedAtY );
+  setVGraph(m_pointedAtX);
+  setHGraph(m_pointedAtY);
 }
 
-
 /**
  *  Change the color tables used to map intensity to color. Two tables are
  *  used to allow psuedo-log scaling based on the magnitude of a value.
@@ -348,21 +308,19 @@ void SpectrumDisplay::updateImage()
  *                             same number of entries as the positive
  *                             color table.
  */
-void SpectrumDisplay::setColorScales( std::vector<QRgb> & positiveColorTable,
-                                      std::vector<QRgb> & negativeColorTable )
-{
-  m_positiveColorTable.resize( positiveColorTable.size() );
-  for ( size_t i = 0; i < positiveColorTable.size(); i++ )
+void SpectrumDisplay::setColorScales(std::vector<QRgb> &positiveColorTable,
+                                     std::vector<QRgb> &negativeColorTable) {
+  m_positiveColorTable.resize(positiveColorTable.size());
+  for (size_t i = 0; i < positiveColorTable.size(); i++)
     m_positiveColorTable[i] = positiveColorTable[i];
 
-  this->m_negativeColorTable.resize( negativeColorTable.size() );
-  for ( size_t i = 0; i < negativeColorTable.size(); i++ )
+  this->m_negativeColorTable.resize(negativeColorTable.size());
+  for (size_t i = 0; i < negativeColorTable.size(); i++)
     m_negativeColorTable[i] = negativeColorTable[i];
 
   updateImage();
 }
 
-
 /**
  *  Change the control parameter (0...100) used to brighten the image.
  *  If the control parameter is 0, the mapping from data values to color
@@ -373,33 +331,27 @@ void SpectrumDisplay::setColorScales( std::vector<QRgb> & positiveColorTable,
  *  @param controlParameter  This is clamped between 0 (linear) and
  *                           100 (most emphasis on low intensity values)
  */
-void SpectrumDisplay::setIntensity( double controlParameter )
-{
+void SpectrumDisplay::setIntensity(double controlParameter) {
   size_t DEFAULT_SIZE = 100000;
   m_intensityTable = ColorMaps::GetIntensityMap(controlParameter, DEFAULT_SIZE);
-  m_spectrumPlotItem->setIntensityTable( &m_intensityTable );
+  m_spectrumPlotItem->setIntensityTable(&m_intensityTable);
   updateImage();
 }
 
-
-QPoint SpectrumDisplay::getPlotTransform( QPair<double, double> values )
-{
-  double x = m_spectrumPlot->transform( QwtPlot::xBottom, values.first );
-  double y = m_spectrumPlot->transform( QwtPlot::yLeft,   values.second );
+QPoint SpectrumDisplay::getPlotTransform(QPair<double, double> values) {
+  double x = m_spectrumPlot->transform(QwtPlot::xBottom, values.first);
+  double y = m_spectrumPlot->transform(QwtPlot::yLeft, values.second);
 
   return QPoint((int)x, (int)y);
 }
 
+QPair<double, double> SpectrumDisplay::getPlotInvTransform(QPoint point) {
+  double x = m_spectrumPlot->invTransform(QwtPlot::xBottom, point.x());
+  double y = m_spectrumPlot->invTransform(QwtPlot::yLeft, point.y());
 
-QPair<double, double> SpectrumDisplay::getPlotInvTransform( QPoint point )
-{
-  double x = m_spectrumPlot->invTransform( QwtPlot::xBottom, point.x() );
-  double y = m_spectrumPlot->invTransform( QwtPlot::yLeft,   point.y() );
-
-  return qMakePair(x,y);
+  return qMakePair(x, y);
 }
 
-
 /**
  * Extract data from horizontal and vertical cuts across the image and
  * show those as graphs in the horizontal and vertical graphs and show
@@ -408,30 +360,32 @@ QPair<double, double> SpectrumDisplay::getPlotInvTransform( QPoint point )
  * @param point  The point that the user is currently pointing at with
  *               the mouse.
  * @param mouseClick Which mouse button was clicked
- * @param isFront Flag indicating if this is a call to the front (active) display.
+ * @param isFront Flag indicating if this is a call to the front (active)
+ *display.
  * @return A pair containing the (x,y) values in the graph of the point
  */
-QPair<double,double> SpectrumDisplay::setPointedAtPoint( QPoint point, int mouseClick, bool isFront )
-{
+QPair<double, double>
+SpectrumDisplay::setPointedAtPoint(QPoint point, int mouseClick, bool isFront) {
   UNUSED_ARG(mouseClick);
-  if ( m_dataSource == 0 || m_dataArray == 0 )
+  if (m_dataSource == 0 || m_dataArray == 0)
     return qMakePair(0.0, 0.0);
 
   QPair<double, double> transPoints = getPlotInvTransform(point);
 
-  setPointedAtXY(transPoints.first, transPoints.second, isFront );
+  setPointedAtXY(transPoints.first, transPoints.second, isFront);
 
   return transPoints;
 }
 
-/// Record the point that the user is currently pointing in the scales coordinates
-void SpectrumDisplay::setPointedAtXY( double x, double y, bool isFront ) {
-  setHGraph( y, isFront );
-  setVGraph( x, isFront );
+/// Record the point that the user is currently pointing in the scales
+/// coordinates
+void SpectrumDisplay::setPointedAtXY(double x, double y, bool isFront) {
+  setHGraph(y, isFront);
+  setVGraph(x, isFront);
 
   if (isFront) {
-    showInfoList( x, y );
-    foreach(boost::weak_ptr<SpectrumDisplay> sd, m_otherDisplays) {
+    showInfoList(x, y);
+    foreach (boost::weak_ptr<SpectrumDisplay> sd, m_otherDisplays) {
       if (auto display = sd.lock()) {
         display->setPointedAtXY(x, y, false);
       }
@@ -439,7 +393,6 @@ void SpectrumDisplay::setPointedAtXY( double x, double y, bool isFront ) {
   }
 }
 
-
 /*
  *  Extract data for Horizontal graph from the image at the specified y value.
  *  If the y value is NOT in the y-interval covered by the data array, just
@@ -448,10 +401,8 @@ void SpectrumDisplay::setPointedAtXY( double x, double y, bool isFront ) {
  *  @param y   The y-value of the horizontal cut through the image.
  *  @param isFront Is it a front curve?
  */
-void SpectrumDisplay::setHGraph( double y, bool isFront )
-{
-  if ( y < m_dataArray->getYMin() || y > m_dataArray->getYMax() )
-  {
+void SpectrumDisplay::setHGraph(double y, bool isFront) {
+  if (y < m_dataArray->getYMin() || y > m_dataArray->getYMax()) {
     if (isFront)
       m_hGraphDisplay->clear();
     return;
@@ -459,34 +410,32 @@ void SpectrumDisplay::setHGraph( double y, bool isFront )
 
   m_pointedAtY = y;
 
-  std::vector<float>data   = m_dataArray->getData();
+  std::vector<float> data = m_dataArray->getData();
 
   size_t n_cols = m_dataArray->getNCols();
 
   double x_min = m_dataArray->getXMin();
   double x_max = m_dataArray->getXMax();
 
-  size_t row = m_dataArray->rowOfY( y );
+  size_t row = m_dataArray->rowOfY(y);
 
   QVector<double> xData;
   QVector<double> yData;
 
-  xData.push_back( x_min );                              // start at x_min
-  yData.push_back( data[ row * n_cols ] );
-  for ( size_t col = 0; col < n_cols; col++ )
-  {
-    double x_val = m_dataArray->xOfColumn( col );
-    xData.push_back( x_val );                           // mark data at col
-    yData.push_back( data[ row * n_cols + col ] );      // centers
+  xData.push_back(x_min); // start at x_min
+  yData.push_back(data[row * n_cols]);
+  for (size_t col = 0; col < n_cols; col++) {
+    double x_val = m_dataArray->xOfColumn(col);
+    xData.push_back(x_val);                    // mark data at col
+    yData.push_back(data[row * n_cols + col]); // centers
   }
-  xData.push_back( x_max );                             // end at x_max
-  yData.push_back( data[ row * n_cols + n_cols-1 ] );
+  xData.push_back(x_max); // end at x_max
+  yData.push_back(data[row * n_cols + n_cols - 1]);
 
-  m_hGraphDisplay->setLogX( m_dataArray->isLogX() );
-  m_hGraphDisplay->setData( xData, yData, y, isFront );
+  m_hGraphDisplay->setLogX(m_dataArray->isLogX());
+  m_hGraphDisplay->setData(xData, yData, y, isFront);
 }
 
-
 /*
  *  Extract data for vertical graph from the image at the specified x value.
  *  If the x value is NOT in the x-interval covered by the data array, just
@@ -494,17 +443,15 @@ void SpectrumDisplay::setHGraph( double y, bool isFront )
  *
  *  @param x   The x-value of the vertical cut through the image.
  */
-void SpectrumDisplay::setVGraph( double x, bool isFront )
-{
-  if ( x < m_dataArray->getXMin() || x > m_dataArray->getXMax() )
-  {
+void SpectrumDisplay::setVGraph(double x, bool isFront) {
+  if (x < m_dataArray->getXMin() || x > m_dataArray->getXMax()) {
     m_vGraphDisplay->clear();
     return;
   }
 
   m_pointedAtX = x;
 
-  std::vector<float> data   = m_dataArray->getData();
+  std::vector<float> data = m_dataArray->getData();
 
   size_t n_rows = m_dataArray->getNRows();
   size_t n_cols = m_dataArray->getNCols();
@@ -512,27 +459,25 @@ void SpectrumDisplay::setVGraph( double x, bool isFront )
   double y_min = m_dataArray->getYMin();
   double y_max = m_dataArray->getYMax();
 
-  size_t col = m_dataArray->columnOfX( x );
+  size_t col = m_dataArray->columnOfX(x);
 
   QVector<double> v_xData;
   QVector<double> v_yData;
 
-
-  v_yData.push_back( y_min );                     // start at y_min
-  v_xData.push_back( data[col] );
-  for ( size_t row = 0; row < n_rows; row++ )     // mark data at row centres
+  v_yData.push_back(y_min); // start at y_min
+  v_xData.push_back(data[col]);
+  for (size_t row = 0; row < n_rows; row++) // mark data at row centres
   {
-    double y_val = m_dataArray->yOfRow( row );
-    v_yData.push_back( y_val );
-    v_xData.push_back( data[ row * n_cols + col ] );
+    double y_val = m_dataArray->yOfRow(row);
+    v_yData.push_back(y_val);
+    v_xData.push_back(data[row * n_cols + col]);
   }
-  v_yData.push_back( y_max );                     // end at y_max
-  v_xData.push_back( data[ (n_rows-1) * n_cols + col] );
+  v_yData.push_back(y_max); // end at y_max
+  v_xData.push_back(data[(n_rows - 1) * n_cols + col]);
 
-  m_vGraphDisplay->setData( v_xData, v_yData, x, isFront );
+  m_vGraphDisplay->setData(v_xData, v_yData, x, isFront);
 }
 
-
 /**
  *  Get the information about a pointed at location and show it in the
  *  table.
@@ -540,8 +485,7 @@ void SpectrumDisplay::setVGraph( double x, bool isFront )
  *  @param x  The x coordinate of the pointed at location on the image.
  *  @param y  The y coordinate of the pointed at location on the image.
  */
-std::vector<std::string> SpectrumDisplay::showInfoList( double x, double y )
-{
+std::vector<std::string> SpectrumDisplay::showInfoList(double x, double y) {
   std::vector<std::string> info_list = m_dataSource->getInfoList(x, y);
   int n_infos = (int)info_list.size() / 2;
 
@@ -551,16 +495,15 @@ std::vector<std::string> SpectrumDisplay::showInfoList( double x, double y )
   m_imageTable->horizontalHeader()->hide();
 
   int width = 9;
-  int prec  = 3;
+  int prec = 3;
 
-  double value = m_dataArray->getValue( x, y );
-  QtUtils::SetTableEntry( 0, 0, "Value", m_imageTable );
-  QtUtils::SetTableEntry( 0, 1, width, prec, value, m_imageTable );
+  double value = m_dataArray->getValue(x, y);
+  QtUtils::SetTableEntry(0, 0, "Value", m_imageTable);
+  QtUtils::SetTableEntry(0, 1, width, prec, value, m_imageTable);
 
-  for ( int i = 0; i < n_infos; i++ )
-  {
-    QtUtils::SetTableEntry( i+1, 0, info_list[2*i], m_imageTable );
-    QtUtils::SetTableEntry( i+1, 1, info_list[2*i+1], m_imageTable );
+  for (int i = 0; i < n_infos; i++) {
+    QtUtils::SetTableEntry(i + 1, 0, info_list[2 * i], m_imageTable);
+    QtUtils::SetTableEntry(i + 1, 1, info_list[2 * i + 1], m_imageTable);
   }
 
   m_imageTable->resizeColumnsToContents();
@@ -568,28 +511,19 @@ std::vector<std::string> SpectrumDisplay::showInfoList( double x, double y )
   return info_list;
 }
 
-
 /**
  * Gets the X value being pointed at.
  *
  * @returns X value
  */
-double SpectrumDisplay::getPointedAtX()
-{
-  return m_pointedAtX;
-}
-
+double SpectrumDisplay::getPointedAtX() { return m_pointedAtX; }
 
 /**
  * Gets the Y value being pointed at.
  *
  * @returns Y value
  */
-double SpectrumDisplay::getPointedAtY()
-{
-  return m_pointedAtY;
-}
-
+double SpectrumDisplay::getPointedAtY() { return m_pointedAtY; }
 
 /**
  *  Get the rectangle currently covered by the image in pixel coordinates.
@@ -597,70 +531,64 @@ double SpectrumDisplay::getPointedAtY()
  *  @param rect  A QRect object that will be filled out with position, width
  *               and height of the pixel region covered by the image.
  */
-void SpectrumDisplay::getDisplayRectangle( QRect &rect )
-{
-  QwtScaleMap xMap = m_spectrumPlot->canvasMap( QwtPlot::xBottom );
-  QwtScaleMap yMap = m_spectrumPlot->canvasMap( QwtPlot::yLeft );
+void SpectrumDisplay::getDisplayRectangle(QRect &rect) {
+  QwtScaleMap xMap = m_spectrumPlot->canvasMap(QwtPlot::xBottom);
+  QwtScaleMap yMap = m_spectrumPlot->canvasMap(QwtPlot::yLeft);
 
   double x_min = m_dataArray->getXMin();
   double x_max = m_dataArray->getXMax();
   double y_min = m_dataArray->getYMin();
   double y_max = m_dataArray->getYMax();
 
-  int pix_x_min = (int)xMap.transform( x_min );
-  int pix_x_max = (int)xMap.transform( x_max );
-  int pix_y_min = (int)yMap.transform( y_min );
-  int pix_y_max = (int)yMap.transform( y_max );
+  int pix_x_min = (int)xMap.transform(x_min);
+  int pix_x_max = (int)xMap.transform(x_max);
+  int pix_y_min = (int)yMap.transform(y_min);
+  int pix_y_max = (int)yMap.transform(y_max);
 
-  rect.setLeft  ( pix_x_min );
-  rect.setRight ( pix_x_max );
-  rect.setBottom( pix_y_min );
-  rect.setTop   ( pix_y_max );
+  rect.setLeft(pix_x_min);
+  rect.setRight(pix_x_max);
+  rect.setBottom(pix_y_min);
+  rect.setTop(pix_y_max);
 
-  if ( rect.height() <= 1 ||        // must not have been drawn yet, so set
-       rect.width()  <= 1  )        // some reasonable default guesses
+  if (rect.height() <= 1 || // must not have been drawn yet, so set
+      rect.width() <= 1)    // some reasonable default guesses
   {
-    rect.setLeft  (   6 );
-    rect.setRight ( 440 );
-    rect.setBottom( 440 );
-    rect.setTop   (   6 );
+    rect.setLeft(6);
+    rect.setRight(440);
+    rect.setBottom(440);
+    rect.setTop(6);
   }
 }
 
-
-bool SpectrumDisplay::dataSourceRangeChanged()
-{
-  return ( m_totalYMin != m_dataSource->getYMin() ||
-           m_totalYMax != m_dataSource->getYMax() ||
-           m_totalXMin != m_dataSource->getXMin() ||
-           m_totalXMax != m_dataSource->getXMax() );
+bool SpectrumDisplay::dataSourceRangeChanged() {
+  return (m_totalYMin != m_dataSource->getYMin() ||
+          m_totalYMax != m_dataSource->getYMax() ||
+          m_totalXMin != m_dataSource->getXMin() ||
+          m_totalXMax != m_dataSource->getXMax());
 }
 
-void SpectrumDisplay::addOther(const boost::shared_ptr<SpectrumDisplay>& other)
-{
+void SpectrumDisplay::addOther(
+    const boost::shared_ptr<SpectrumDisplay> &other) {
   m_otherDisplays.append(other);
 }
 
-void SpectrumDisplay::addOthers(const QList<boost::shared_ptr<SpectrumDisplay>>& others)
-{
-  foreach(boost::shared_ptr<SpectrumDisplay> sd, others)
-  {
+void SpectrumDisplay::addOthers(
+    const QList<boost::shared_ptr<SpectrumDisplay>> &others) {
+  foreach (boost::shared_ptr<SpectrumDisplay> sd, others) {
     m_otherDisplays.append(sd);
   }
 }
 
-void SpectrumDisplay::removeOther(const boost::shared_ptr<SpectrumDisplay>& other)
-{
+void SpectrumDisplay::removeOther(
+    const boost::shared_ptr<SpectrumDisplay> &other) {
   QList<int> toRemove;
-  for(int i = 0; i < m_otherDisplays.size(); ++i) {
+  for (int i = 0; i < m_otherDisplays.size(); ++i) {
     auto ds = m_otherDisplays[i].lock();
     if (!ds || ds.get() == other.get()) {
       toRemove.push_front(i);
     }
   }
-  foreach(int i, toRemove) {
-    m_otherDisplays.removeAt(i);
-  }
+  foreach (int i, toRemove) { m_otherDisplays.removeAt(i); }
 }
 
 /**
@@ -668,9 +596,8 @@ void SpectrumDisplay::removeOther(const boost::shared_ptr<SpectrumDisplay>& othe
  *
  * @param point The position moved to.
  */
-void SpectrumDisplay::imagePickerMoved(const QPoint & point)
-{
-  setPointedAtPoint( point );
+void SpectrumDisplay::imagePickerMoved(const QPoint &point) {
+  setPointedAtPoint(point);
 }
 
 /**
diff --git a/MantidQt/SpectrumViewer/src/SpectrumPlotItem.cpp b/MantidQt/SpectrumViewer/src/SpectrumPlotItem.cpp
index 84b355b43ed59c8981e4a351feaabd81c9a42d5b..f1021147f0286669fcbafc7ef8ea17f990a04058 100644
--- a/MantidQt/SpectrumViewer/src/SpectrumPlotItem.cpp
+++ b/MantidQt/SpectrumViewer/src/SpectrumPlotItem.cpp
@@ -1,30 +1,20 @@
 #include <QThread>
 #include "MantidQtSpectrumViewer/SpectrumPlotItem.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
-
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  * Construct basic plot item with NO data to plot.
  */
-SpectrumPlotItem::SpectrumPlotItem() :
-  m_bufferID(0),
-  /* m_dataArray0(NULL), */
-  /* m_dataArray1(NULL), */
-  m_positiveColorTable(NULL),
-  m_negativeColorTable(NULL),
-  m_intensityTable(NULL)
-{
-}
-
-
-SpectrumPlotItem::~SpectrumPlotItem()
-{
-}
+SpectrumPlotItem::SpectrumPlotItem()
+    : m_bufferID(0),
+      /* m_dataArray0(NULL), */
+      /* m_dataArray1(NULL), */
+      m_positiveColorTable(NULL), m_negativeColorTable(NULL),
+      m_intensityTable(NULL) {}
 
+SpectrumPlotItem::~SpectrumPlotItem() {}
 
 /**
  * Specify the data to be plotted and the color table to use.
@@ -39,22 +29,18 @@ SpectrumPlotItem::~SpectrumPlotItem()
  *                            must have the same number of entries as the
  *                            positive color table.
  */
-void SpectrumPlotItem::setData( DataArray_const_sptr dataArray,
-                                std::vector<QRgb>* positiveColorTable,
-                                std::vector<QRgb>* negativeColorTable )
-{
-  if ( m_bufferID == 0 )
-  {
-    m_dataArray1 = dataArray;  // put new data in array 1, and switch to it
-                               // leaving array 0 intact for now, in case it's
-                               // being drawn.
+void SpectrumPlotItem::setData(DataArray_const_sptr dataArray,
+                               std::vector<QRgb> *positiveColorTable,
+                               std::vector<QRgb> *negativeColorTable) {
+  if (m_bufferID == 0) {
+    m_dataArray1 = dataArray; // put new data in array 1, and switch to it
+                              // leaving array 0 intact for now, in case it's
+                              // being drawn.
     m_bufferID = 1;
-  }
-  else
-  {
-    m_dataArray0 = dataArray;  // put new data in array 0, and switch to it
-                               // leaving array 1 intact for now, in case it's
-                               // being drawn.
+  } else {
+    m_dataArray0 = dataArray; // put new data in array 0, and switch to it
+                              // leaving array 1 intact for now, in case it's
+                              // being drawn.
     m_bufferID = 0;
   }
 
@@ -62,7 +48,6 @@ void SpectrumPlotItem::setData( DataArray_const_sptr dataArray,
   m_negativeColorTable = negativeColorTable;
 }
 
-
 /**
  *  Set a non-linear look up table that will be used with data values before
  *  they are mapped to a color.  This is typically used to apply a log type
@@ -72,12 +57,10 @@ void SpectrumPlotItem::setData( DataArray_const_sptr dataArray,
  *                         that will be used to scale the corresponding
  *                         image values before mappign to a color index.
  */
-void SpectrumPlotItem::setIntensityTable( std::vector<double>* intensityTable )
-{
+void SpectrumPlotItem::setIntensityTable(std::vector<double> *intensityTable) {
   m_intensityTable = intensityTable;
 }
 
-
 /**
  *  Draw the image (this is called by QWT and must not be called directly.)
  *
@@ -92,17 +75,14 @@ void SpectrumPlotItem::setIntensityTable( std::vector<double>* intensityTable )
  *                      parameter is NOT USED by the SpectrumPlotItem, but is
  *                      passed in when QWT calls this method.
  */
-void SpectrumPlotItem::draw(QPainter    * painter,
-                      const QwtScaleMap & xMap,
-                      const QwtScaleMap & yMap,
-                      const QRect       &       ) const
-{
+void SpectrumPlotItem::draw(QPainter *painter, const QwtScaleMap &xMap,
+                            const QwtScaleMap &yMap, const QRect &) const {
   // If no color table, the data is not yet set, so just return
-  if(!m_positiveColorTable)
+  if (!m_positiveColorTable)
     return;
 
   DataArray_const_sptr dataArray;
-  if ( m_bufferID == 0 )
+  if (m_bufferID == 0)
     dataArray = m_dataArray0;
   else
     dataArray = m_dataArray1;
@@ -110,91 +90,80 @@ void SpectrumPlotItem::draw(QPainter    * painter,
   size_t n_rows = dataArray->getNRows();
   size_t n_cols = dataArray->getNCols();
 
-  if ( n_rows == 0 || n_cols == 0 )
-  {
-    return;                                 // can't draw degenerate image
+  if (n_rows == 0 || n_cols == 0) {
+    return; // can't draw degenerate image
   }
 
-  const double min    = dataArray->getDataMin();
-  const double max    = dataArray->getDataMax();
-  const double x_min  = dataArray->getXMin();
-  const double x_max  = dataArray->getXMax();
-  const double y_min  = dataArray->getYMin();
-  const double y_max  = dataArray->getYMax();
-
-  std::vector<float> data   = dataArray->getData();
-                                            // find the actual plot region
-                                            // using the scale maps.
-  const int pix_x_min = (int)xMap.transform( x_min );
-  const int pix_x_max = (int)xMap.transform( x_max );
-  const int pix_y_min = (int)yMap.transform( y_min );
-  const int pix_y_max = (int)yMap.transform( y_max );
-
-                                            // set up zero centered scale range
-                                            // symmetrical around zero
+  const double min = dataArray->getDataMin();
+  const double max = dataArray->getDataMax();
+  const double x_min = dataArray->getXMin();
+  const double x_max = dataArray->getXMax();
+  const double y_min = dataArray->getYMin();
+  const double y_max = dataArray->getYMax();
+
+  std::vector<float> data = dataArray->getData();
+  // find the actual plot region
+  // using the scale maps.
+  const int pix_x_min = (int)xMap.transform(x_min);
+  const int pix_x_max = (int)xMap.transform(x_max);
+  const int pix_y_min = (int)yMap.transform(y_min);
+  const int pix_y_max = (int)yMap.transform(y_max);
+
+  // set up zero centered scale range
+  // symmetrical around zero
   double zc_max = fabs(max);
-  if ( fabs(min) > fabs(max) )
-  {
+  if (fabs(min) > fabs(max)) {
     zc_max = fabs(min);
   }
-  if ( zc_max == 0 )                        // all values are zero, set up
-  {                                         // no-degenerate default range
+  if (zc_max == 0) // all values are zero, set up
+  {                // no-degenerate default range
     zc_max = 1;
   }
 
-  double scale = ((double)m_positiveColorTable->size()-1)/zc_max;
-  double ct_scale = ((double)m_positiveColorTable->size()-1);
-  if ( m_intensityTable != 0 )
-  {
+  double scale = ((double)m_positiveColorTable->size() - 1) / zc_max;
+  double ct_scale = ((double)m_positiveColorTable->size() - 1);
+  if (m_intensityTable != 0) {
     size_t lut_size = m_intensityTable->size();
-    scale    = ((double)lut_size-1.0) / zc_max;
-    ct_scale = ((double)m_positiveColorTable->size()-1);
+    scale = ((double)lut_size - 1.0) / zc_max;
+    ct_scale = ((double)m_positiveColorTable->size() - 1);
   }
 
   size_t color_index;
   size_t lut_index;
   size_t image_index = 0;
 
-  unsigned int* rgb_buffer = new unsigned int[n_rows * n_cols];
+  unsigned int *rgb_buffer = new unsigned int[n_rows * n_cols];
   double val = 0;
-  for ( int row = (int)n_rows-1; row >= 0; row-- )
-  {
+  for (int row = (int)n_rows - 1; row >= 0; row--) {
     size_t data_index = row * n_cols;
-    if (m_intensityTable == 0 )              // use color tables directly
+    if (m_intensityTable == 0) // use color tables directly
     {
-      for ( int col = 0; col < (int)n_cols; col++ )
-      {
+      for (int col = 0; col < (int)n_cols; col++) {
         val = data[data_index] * scale;
-        if ( val >= 0 )                     // use positive color table
+        if (val >= 0) // use positive color table
         {
           color_index = (uint)val;
-          rgb_buffer[image_index] = (*m_positiveColorTable)[ color_index ];
-        }
-        else                               // use negative color table
+          rgb_buffer[image_index] = (*m_positiveColorTable)[color_index];
+        } else // use negative color table
         {
           color_index = (uint)(-val);
-          rgb_buffer[image_index] = (*m_negativeColorTable)[ color_index ];
+          rgb_buffer[image_index] = (*m_negativeColorTable)[color_index];
         }
         image_index++;
         data_index++;
       }
-    }
-    else                                    // go through intensity table
+    } else // go through intensity table
     {
-      for ( int col = 0; col < (int)n_cols; col++ )
-      {
+      for (int col = 0; col < (int)n_cols; col++) {
         val = data[data_index] * scale;
-        if ( val >= 0 )
-        {
-          lut_index   = (uint)val;
-          color_index = (uint)((*m_intensityTable)[lut_index] * ct_scale );
-          rgb_buffer[image_index] = (*m_positiveColorTable)[ color_index ];
-        }
-        else
-        {
-          lut_index   = (uint)(-val);
-          color_index = (uint)((*m_intensityTable)[lut_index] * ct_scale );
-          rgb_buffer[image_index] = (*m_negativeColorTable)[ color_index ];
+        if (val >= 0) {
+          lut_index = (uint)val;
+          color_index = (uint)((*m_intensityTable)[lut_index] * ct_scale);
+          rgb_buffer[image_index] = (*m_positiveColorTable)[color_index];
+        } else {
+          lut_index = (uint)(-val);
+          color_index = (uint)((*m_intensityTable)[lut_index] * ct_scale);
+          rgb_buffer[image_index] = (*m_negativeColorTable)[color_index];
         }
         image_index++;
         data_index++;
@@ -202,24 +171,22 @@ void SpectrumPlotItem::draw(QPainter    * painter,
     }
   }
 
-  uchar *buffer = (uchar*)rgb_buffer;
-  QImage image( buffer, (int)n_cols, (int)n_rows, QImage::Format_RGB32 );
+  uchar *buffer = (uchar *)rgb_buffer;
+  QImage image(buffer, (int)n_cols, (int)n_rows, QImage::Format_RGB32);
   QPixmap pixmap = QPixmap::fromImage(image);
 
-  int width  = pix_x_max - pix_x_min + 1;
-  int height = pix_y_min - pix_y_max + 1;    // y-axis is inverted for image
+  int width = pix_x_max - pix_x_min + 1;
+  int height = pix_y_min - pix_y_max + 1; // y-axis is inverted for image
 
-  QPixmap scaled_pixmap = pixmap.scaled( width, height,
-                                         Qt::IgnoreAspectRatio,
-                                         Qt::FastTransformation);
+  QPixmap scaled_pixmap = pixmap.scaled(width, height, Qt::IgnoreAspectRatio,
+                                        Qt::FastTransformation);
 
-  painter->drawPixmap( pix_x_min, pix_y_max, scaled_pixmap );
+  painter->drawPixmap(pix_x_min, pix_y_max, scaled_pixmap);
 
-  delete[] rgb_buffer;                       // we can delete this now, but
-                                             // not earlier since the image
-                                             // and/or pixmap is using it
+  delete[] rgb_buffer; // we can delete this now, but
+                       // not earlier since the image
+                       // and/or pixmap is using it
 }
 
-
 } // namespace SpectrumView
 } // namespace MantidQt
diff --git a/MantidQt/SpectrumViewer/src/SpectrumView.cpp b/MantidQt/SpectrumViewer/src/SpectrumView.cpp
index aa5132b7549edba171f7b6f425c983073cdc4a19..002fcf18a218fa6f7a85eab03e1c8810831b9631 100644
--- a/MantidQt/SpectrumViewer/src/SpectrumView.cpp
+++ b/MantidQt/SpectrumViewer/src/SpectrumView.cpp
@@ -11,34 +11,31 @@
 
 #include <boost/make_shared.hpp>
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct an SpectrumView to display data from the specified data source.
  *  The specified SpectrumDataSource must be constructed elsewhere and passed
- *  into this SpectrumView constructor.  Most other components of the SpectrumView
+ *  into this SpectrumView constructor.  Most other components of the
+ *SpectrumView
  *  are managed by this class.  That is the graphs, image display and other
  *  parts of the SpectrumView are constructed here and are deleted when the
  *  SpectrumView destructor is called.
  *
  *  @param parent Top-level widget for object.
  */
-SpectrumView::SpectrumView(QWidget *parent) :
-  QMainWindow(parent),
-  WorkspaceObserver(),
-  m_ui(new Ui::SpectrumViewer()),
-  m_sliderHandler(NULL),
-  m_rangeHandler(NULL),
-  m_emodeHandler(NULL)
-{
+SpectrumView::SpectrumView(QWidget *parent)
+    : QMainWindow(parent), WorkspaceObserver(), m_ui(new Ui::SpectrumViewer()),
+      m_sliderHandler(NULL), m_rangeHandler(NULL), m_emodeHandler(NULL) {
   m_ui->setupUi(this);
-  //m_ui->x_min_input->setValidator(new QDoubleValidator(this));
-  connect(m_ui->imageTabs,SIGNAL(currentChanged(int)),this,SLOT(changeSpectrumDisplay(int)));
-  connect(m_ui->imageTabs,SIGNAL(tabCloseRequested(int)),this,SLOT(respondToTabCloseReqest(int)));
-  connect(m_ui->tracking_always_on, SIGNAL(toggled(bool)), this, SLOT(changeTracking(bool)));
+  // m_ui->x_min_input->setValidator(new QDoubleValidator(this));
+  connect(m_ui->imageTabs, SIGNAL(currentChanged(int)), this,
+          SLOT(changeSpectrumDisplay(int)));
+  connect(m_ui->imageTabs, SIGNAL(tabCloseRequested(int)), this,
+          SLOT(respondToTabCloseReqest(int)));
+  connect(m_ui->tracking_always_on, SIGNAL(toggled(bool)), this,
+          SLOT(changeTracking(bool)));
   updateHandlers();
   setAcceptDrops(true);
   loadSettings();
@@ -49,15 +46,12 @@ SpectrumView::SpectrumView(QWidget *parent) :
   observeADSClear();
 }
 
-
-SpectrumView::~SpectrumView()
-{
+SpectrumView::~SpectrumView() {
   saveSettings();
-  if(m_emodeHandler)
+  if (m_emodeHandler)
     delete m_emodeHandler;
 }
 
-
 /**
  * Handles the resize event fo rthe window.
  *
@@ -66,23 +60,20 @@ SpectrumView::~SpectrumView()
  *
  * @param event The resize event
  */
-void SpectrumView::resizeEvent(QResizeEvent * event)
-{
+void SpectrumView::resizeEvent(QResizeEvent *event) {
   QMainWindow::resizeEvent(event);
-  if (m_svConnections)
-  {
+  if (m_svConnections) {
     m_svConnections->imageSplitterMoved();
   }
 }
 
-
 /**
  * Renders a new workspace on the spectrum viewer.
  *
  * @param wksp The matrix workspace to render
  */
-void SpectrumView::renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp)
-{
+void SpectrumView::renderWorkspace(
+    Mantid::API::MatrixWorkspace_const_sptr wksp) {
   auto dataSource = MatrixWSDataSource_sptr(new MatrixWSDataSource(wksp));
   m_dataSource.append(dataSource);
 
@@ -91,11 +82,11 @@ void SpectrumView::renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp)
   // this type checking if we made the ui in the calling code and passed
   // it in.  We would need a common base class for this class and
   // the ref-viewer UI.
-  dataSource -> setEModeHandler( m_emodeHandler );
+  dataSource->setEModeHandler(m_emodeHandler);
 
   // Connect WorkspaceObserver signals
   connect(this, SIGNAL(needToClose()), this, SLOT(closeWindow()));
-  //connect(this, SIGNAL(needToUpdate()), this, SLOT(updateWorkspace()));
+  // connect(this, SIGNAL(needToUpdate()), this, SLOT(updateWorkspace()));
 
   // Set the window title
   std::string windowTitle = "SpectrumView (" + wksp->getTitle() + ")";
@@ -105,18 +96,15 @@ void SpectrumView::renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp)
   bool isFirstPlot = m_spectrumDisplay.isEmpty();
 
   int tab = 0;
-  if (isFirstPlot)
-  {
+  if (isFirstPlot) {
     m_ui->imageTabs->setTabText(
         m_ui->imageTabs->indexOf(m_ui->imageTabs->currentWidget()),
         QString::fromStdString(wksp->name()));
     m_hGraph = boost::make_shared<GraphDisplay>(m_ui->h_graphPlot,
-                                                     m_ui->h_graph_table, false);
+                                                m_ui->h_graph_table, false);
     m_vGraph = boost::make_shared<GraphDisplay>(m_ui->v_graphPlot,
-                                                     m_ui->v_graph_table, true);
-  }
-  else
-  {
+                                                m_ui->v_graph_table, true);
+  } else {
     spectrumPlot = new QwtPlot(this);
     auto widget = new QWidget();
     auto layout = new QHBoxLayout();
@@ -126,24 +114,19 @@ void SpectrumView::renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp)
     m_ui->imageTabs->setTabsClosable(true);
   }
 
-  auto spectrumDisplay = boost::make_shared<SpectrumDisplay>( spectrumPlot,
-                                           m_sliderHandler,
-                                           m_rangeHandler,
-                                           m_hGraph.get(), m_vGraph.get(),
-                                           m_ui->image_table,
-                                           isTrackingOn());
-  spectrumDisplay->setDataSource( dataSource );
+  auto spectrumDisplay = boost::make_shared<SpectrumDisplay>(
+      spectrumPlot, m_sliderHandler, m_rangeHandler, m_hGraph.get(),
+      m_vGraph.get(), m_ui->image_table, isTrackingOn());
+  spectrumDisplay->setDataSource(dataSource);
 
-  if (isFirstPlot)
-  {
-    m_svConnections = boost::make_shared<SVConnections>( m_ui, this, spectrumDisplay.get(),
-                                         m_hGraph.get(), m_vGraph.get() );
-    connect(this,SIGNAL(spectrumDisplayChanged(SpectrumDisplay*)),m_svConnections.get(),SLOT(setSpectrumDisplay(SpectrumDisplay*)));
+  if (isFirstPlot) {
+    m_svConnections = boost::make_shared<SVConnections>(
+        m_ui, this, spectrumDisplay.get(), m_hGraph.get(), m_vGraph.get());
+    connect(this, SIGNAL(spectrumDisplayChanged(SpectrumDisplay *)),
+            m_svConnections.get(), SLOT(setSpectrumDisplay(SpectrumDisplay *)));
     m_svConnections->imageSplitterMoved();
-  }
-  else
-  {
-    foreach(boost::shared_ptr<SpectrumDisplay> sd, m_spectrumDisplay) {
+  } else {
+    foreach (boost::shared_ptr<SpectrumDisplay> sd, m_spectrumDisplay) {
       sd->addOther(spectrumDisplay);
     }
     spectrumDisplay->addOthers(m_spectrumDisplay);
@@ -153,26 +136,19 @@ void SpectrumView::renderWorkspace(Mantid::API::MatrixWorkspace_const_sptr wksp)
   m_ui->imageTabs->setCurrentIndex(tab);
 }
 
-
 /**
  * Setup the various handlers (energy-mode, slider, range) for UI controls.
  */
-void SpectrumView::updateHandlers()
-{
-  m_emodeHandler = new EModeHandler( m_ui );
-  m_sliderHandler = new SliderHandler( m_ui );
-  m_rangeHandler = new RangeHandler( m_ui );
+void SpectrumView::updateHandlers() {
+  m_emodeHandler = new EModeHandler(m_ui);
+  m_sliderHandler = new SliderHandler(m_ui);
+  m_rangeHandler = new RangeHandler(m_ui);
 }
 
-
 /**
  * Slot to close the window.
  */
-void SpectrumView::closeWindow()
-{
-  close();
-}
-
+void SpectrumView::closeWindow() { close(); }
 
 /**
  * Signal to close this window if the workspace has just been deleted.
@@ -180,66 +156,61 @@ void SpectrumView::closeWindow()
  * @param wsName Name of workspace
  * @param ws Pointer to workspace
  */
-void SpectrumView::preDeleteHandle(const std::string& wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-  if (m_spectrumDisplay.front()->hasData(wsName, ws))
-  {
+void SpectrumView::preDeleteHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
+  if (m_spectrumDisplay.front()->hasData(wsName, ws)) {
     emit needToClose();
   }
 }
 
-
 /**
- * Signal that the workspace being looked at was just replaced with a different one.
+ * Signal that the workspace being looked at was just replaced with a different
+ *one.
  *
  * @param wsName Name of workspace
  * @param ws Pointer to workspace
  */
-void SpectrumView::afterReplaceHandle(const std::string& wsName, const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-  if (m_spectrumDisplay.front()->hasData(wsName, ws))
-  {
-    renderWorkspace(boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws));
+void SpectrumView::afterReplaceHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace> ws) {
+  if (m_spectrumDisplay.front()->hasData(wsName, ws)) {
+    renderWorkspace(
+        boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws));
   }
 }
 
-void SpectrumView::dropEvent(QDropEvent *de)
-{
+void SpectrumView::dropEvent(QDropEvent *de) {
   auto words = de->mimeData()->text().split('"');
-  auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS<Mantid::API::MatrixWorkspace>(words[1].toStdString());
+  auto ws =
+      Mantid::API::AnalysisDataService::Instance()
+          .retrieveWS<Mantid::API::MatrixWorkspace>(words[1].toStdString());
   renderWorkspace(ws);
 }
 
-void SpectrumView::dragMoveEvent(QDragMoveEvent *de)
-{
-  auto pos = m_ui->imageTabs->mapFrom(this,de->pos());
-  if ( m_ui->imageTabs->rect().contains(pos) )
-  {
+void SpectrumView::dragMoveEvent(QDragMoveEvent *de) {
+  auto pos = m_ui->imageTabs->mapFrom(this, de->pos());
+  if (m_ui->imageTabs->rect().contains(pos)) {
     de->accept();
-  }
-  else
-  {
+  } else {
     de->ignore();
   }
 }
 
-void SpectrumView::dragEnterEvent(QDragEnterEvent *de)
-{
+void SpectrumView::dragEnterEvent(QDragEnterEvent *de) {
   if (de->mimeData()->objectName() == "MantidWorkspace") {
     de->acceptProposedAction();
   }
 }
 
-void SpectrumView::changeSpectrumDisplay(int tab)
-{
+void SpectrumView::changeSpectrumDisplay(int tab) {
   auto spectrumDisplay = m_spectrumDisplay[tab].get();
   m_svConnections->setSpectrumDisplay(spectrumDisplay);
   m_hGraph->clear();
   m_vGraph->clear();
 }
 
-void SpectrumView::respondToTabCloseReqest(int tab)
-{
+void SpectrumView::respondToTabCloseReqest(int tab) {
   if (m_spectrumDisplay.size() > 1) {
     auto displayToRemove = m_spectrumDisplay[tab];
     for (auto disp = m_spectrumDisplay.begin(); disp != m_spectrumDisplay.end();
@@ -278,14 +249,15 @@ void SpectrumView::changeTracking(bool on) {
 void SpectrumView::loadSettings() {
   QSettings settings;
   settings.beginGroup("Mantid/MultiDatasetFit");
-  m_ui->tracking_always_on->setChecked(settings.value("CursorTracking", true).toBool());
+  m_ui->tracking_always_on->setChecked(
+      settings.value("CursorTracking", true).toBool());
 }
 
 /// Save settings
 void SpectrumView::saveSettings() const {
   QSettings settings;
   settings.beginGroup("Mantid/MultiDatasetFit");
-  settings.setValue("CursorTracking",m_ui->tracking_always_on->isChecked());
+  settings.setValue("CursorTracking", m_ui->tracking_always_on->isChecked());
 }
 
 } // namespace SpectrumView
diff --git a/MantidQt/SpectrumViewer/src/TrackingPicker.cpp b/MantidQt/SpectrumViewer/src/TrackingPicker.cpp
index 28a1f2f4b45d3a14224ffbe664b9ca7c456cec2d..2c8e6b476ab9a3cf989a5c9a5fbb2a2b0aa8df3c 100644
--- a/MantidQt/SpectrumViewer/src/TrackingPicker.cpp
+++ b/MantidQt/SpectrumViewer/src/TrackingPicker.cpp
@@ -1,20 +1,15 @@
 #include "MantidQtSpectrumViewer/TrackingPicker.h"
 
-namespace MantidQt
-{
-namespace SpectrumView
-{
+namespace MantidQt {
+namespace SpectrumView {
 
 /**
  *  Construct a tracking picker to work with the specified canvas
  *
  *  @param canvas  Pointer to the QwtPlotCanvas this picker will work with
  */
-TrackingPicker::TrackingPicker( QwtPlotCanvas* canvas )
-  : QwtPlotPicker( canvas ), m_hideReadout(true)
-{
-}
-
+TrackingPicker::TrackingPicker(QwtPlotCanvas *canvas)
+    : QwtPlotPicker(canvas), m_hideReadout(true) {}
 
 /**
  * Enable or disable the position readout at the mouse location for this
@@ -23,11 +18,7 @@ TrackingPicker::TrackingPicker( QwtPlotCanvas* canvas )
  * @param hide  If true, the position readout at the mouse position will
  *              be turned off.
  */
-void TrackingPicker::hideReadout( bool hide )
-{
-  m_hideReadout = hide;
-}
-
+void TrackingPicker::hideReadout(bool hide) { m_hideReadout = hide; }
 
 /**
  *  This overrides the base class trackerText() function so that we can
@@ -35,36 +26,29 @@ void TrackingPicker::hideReadout( bool hide )
  *
  *  @param point  The current mouse location.
  */
-QwtText TrackingPicker::trackerText( const QPoint & point ) const
-{
+QwtText TrackingPicker::trackerText(const QPoint &point) const {
   emit mouseMoved(point);
-  if ( m_hideReadout )
-  {
+  if (m_hideReadout) {
     return QwtText();
-  }
-  else                                      // call super class trackerText
-  {                                         // so the tracker text still works
-    return QwtPlotPicker::trackerText( point );
+  } else // call super class trackerText
+  {      // so the tracker text still works
+    return QwtPlotPicker::trackerText(point);
   }
 }
 
-
 /**
  *  This overrides the base class trackerText() function so that we can
  *  continuously emit a signal as the mouse is moved.
  *
  *  @param pos  The current mouse location.
  */
-QwtText TrackingPicker::trackerText( const QwtDoublePoint & pos ) const
-{
+QwtText TrackingPicker::trackerText(const QwtDoublePoint &pos) const {
   emit mouseMoved(pos.toPoint());
-  if ( m_hideReadout )
-  {
+  if (m_hideReadout) {
     return QwtText();
-  }
-  else                                      // call super class trackerText
-  {                                         // so the tracker text still works
-    return QwtPlotPicker::trackerText( pos );
+  } else // call super class trackerText
+  {      // so the tracker text still works
+    return QwtPlotPicker::trackerText(pos);
   }
 }
 
diff --git a/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h b/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
index 3a0a0f8b1c7be30cc18601b4795f799411920e0f..c0f8e908b2edcc7921b8f289ef1606e87d28d723 100644
--- a/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
+++ b/Vates/ParaviewPlugins/ParaViewFilters/PeaksFilter/vtkPeaksFilter.h
@@ -9,8 +9,7 @@
 #include <boost/scoped_ptr.hpp>
 #include <string>
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkPeaksFilter : public vtkUnstructuredGridAlgorithm
-{
+class VTK_EXPORT vtkPeaksFilter : public vtkUnstructuredGridAlgorithm {
 public:
   static vtkPeaksFilter *New();
   vtkTypeMacro(vtkPeaksFilter, vtkUnstructuredGridAlgorithm) void PrintSelf(
@@ -21,10 +20,11 @@ public:
                          const std::string &delimiter);
   void SetRadiusNoShape(double radius);
   void SetRadiusType(int type);
-  void updateAlgorithmProgress(double progress, const std::string& message);
+  void updateAlgorithmProgress(double progress, const std::string &message);
   double GetMinValue();
   double GetMaxValue();
-  const char* GetInstrument();
+  const char *GetInstrument();
+
 protected:
   vtkPeaksFilter();
   ~vtkPeaksFilter() override;
diff --git a/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h b/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
index 9a4583c61d82a5bc64129d930c36e46e2e2229de..6d821db21ebf7948272d0e7e0018ce2ec9310498 100644
--- a/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
+++ b/Vates/ParaviewPlugins/ParaViewFilters/ScaleWorkspace/vtkScaleWorkspace.h
@@ -6,8 +6,7 @@
 #include <boost/scoped_ptr.hpp>
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkScaleWorkspace : public vtkPointSetAlgorithm
-{
+class VTK_EXPORT vtkScaleWorkspace : public vtkPointSetAlgorithm {
 public:
   static vtkScaleWorkspace *New();
   vtkTypeMacro(vtkScaleWorkspace,
@@ -18,19 +17,21 @@ public:
   void SetZScaling(double zScaling);
   double GetMinValue();
   double GetMaxValue();
-  const char* GetInstrument();
+  const char *GetInstrument();
   int GetSpecialCoordinates();
+
 protected:
   vtkScaleWorkspace();
   ~vtkScaleWorkspace() override;
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+  int RequestInformation(vtkInformation *, vtkInformationVector **,
+                         vtkInformationVector *);
   int RequestData(vtkInformation *, vtkInformationVector **,
                   vtkInformationVector *) override;
   int FillInputPortInformation(int port, vtkInformation *info) override;
 
 private:
-  vtkScaleWorkspace(const vtkScaleWorkspace&);
-  void operator = (const vtkScaleWorkspace&);
+  vtkScaleWorkspace(const vtkScaleWorkspace &);
+  void operator=(const vtkScaleWorkspace &);
   void updateMetaData(vtkPointSet *inputDataSet);
   double m_xScaling;
   double m_yScaling;
diff --git a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
index 5774dac5c98afe57dfb20027f922ab0b25781c4d..b149cfc3ecc8fce1e7e4e0258e3dd36a52d3c34f 100644
--- a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
+++ b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h
@@ -5,31 +5,29 @@
 #include "vtkUnstructuredGridAlgorithm.h"
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    class vtkSplatterPlotFactory;
-  }
+namespace Mantid {
+namespace VATES {
+class vtkSplatterPlotFactory;
+}
 }
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkSplatterPlot : public vtkUnstructuredGridAlgorithm
-{
+class VTK_EXPORT vtkSplatterPlot : public vtkUnstructuredGridAlgorithm {
 public:
   static vtkSplatterPlot *New();
-  vtkTypeMacro(vtkSplatterPlot, vtkUnstructuredGridAlgorithm)
-  double getTime() const;
+  vtkTypeMacro(vtkSplatterPlot,
+               vtkUnstructuredGridAlgorithm) double getTime() const;
   void PrintSelf(ostream &os, vtkIndent indent) override;
   void SetNumberOfPoints(int nPoints);
   void SetTopPercentile(double topPercentile);
-  void updateAlgorithmProgress(double progress, const std::string& message);
+  void updateAlgorithmProgress(double progress, const std::string &message);
   /// Getter for the minimum value of the workspace data
   double GetMinValue();
   /// Getter for the maximum value of the workspace data
   double GetMaxValue();
   /// Getter for the maximum value of the workspace data
-  const char* GetInstrument();
+  const char *GetInstrument();
+
 protected:
   vtkSplatterPlot();
   ~vtkSplatterPlot() override;
@@ -50,7 +48,7 @@ private:
   /// Time.
   double m_time;
 
-  vtkSplatterPlot(const vtkSplatterPlot&);
-  void operator = (const vtkSplatterPlot&);
+  vtkSplatterPlot(const vtkSplatterPlot &);
+  void operator=(const vtkSplatterPlot &);
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
index 783ada116dbefaa9afab6f7ae9144763fcbb1da8..08cb8e3e7dc41264d86854546badcf03784cb6f7 100644
--- a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
+++ b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h
@@ -49,8 +49,6 @@ protected:
 private:
   void setTimeRange(vtkInformationVector *outputVector);
 
-
-
   /// File name from which to read.
   char *FileName;
 
diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWReader.h b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWReader.h
index ac53f1d2fdc4e629e624fcafccdc9afb08131803..66d6e11a8ea9fae0d3beb2052883652271366777 100644
--- a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWReader.h
+++ b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWReader.h
@@ -9,15 +9,14 @@
 #include "MantidKernel/MultiThreaded.h"
 
 class vtkImplicitFunction;
-class VTK_EXPORT vtkMDEWNexusReader : public vtkUnstructuredGridAlgorithm
-{
+class VTK_EXPORT vtkMDEWNexusReader : public vtkUnstructuredGridAlgorithm {
 public:
   static vtkMDEWNexusReader *New();
   vtkTypeMacro(vtkMDEWNexusReader, vtkUnstructuredGridAlgorithm);
-  void PrintSelf(ostream& os, vtkIndent indent);
+  void PrintSelf(ostream &os, vtkIndent indent);
   vtkSetStringMacro(FileName);
   vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
+  int CanReadFile(const char *fname);
   void SetXBins(int x);
   void SetYBins(int y);
   void SetZBins(int z);
@@ -25,8 +24,8 @@ public:
   void SetMinThreshold(double minThreshold);
   void SetWidth(double width);
   void SetApplyClip(bool applyClip);
-  void SetClipFunction( vtkImplicitFunction * func);
-  void SetThresholdRangeStrategyIndex(std::string selectedStrategyIndex);  
+  void SetClipFunction(vtkImplicitFunction *func);
+  void SetThresholdRangeStrategyIndex(std::string selectedStrategyIndex);
   double GetInputMinThreshold();
   double GetInputMaxThreshold();
   /// Called by presenter to force progress information updating.
@@ -34,24 +33,26 @@ public:
 
   void SetAppliedGeometryXML(std::string xml);
 
-  const char* GetInputGeometryXML();
+  const char *GetInputGeometryXML();
 
 protected:
   vtkMDEWNexusReader();
   ~vtkMDEWNexusReader();
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+  int RequestInformation(vtkInformation *, vtkInformationVector **,
+                         vtkInformationVector *);
+  int RequestData(vtkInformation *, vtkInformationVector **,
+                  vtkInformationVector *);
   int Canreadfile(const char *fname);
-  ///Handle time variation.
+  /// Handle time variation.
   unsigned long GetMTime();
-  
+
 private:
-  
-  vtkMDEWNexusReader(const vtkMDEWNexusReader&);
-  
-  void operator = (const vtkMDEWNexusReader&);
+  vtkMDEWNexusReader(const vtkMDEWNexusReader &);
+
+  void operator=(const vtkMDEWNexusReader &);
 
-  std::string extractFormattedPropertyFromDimension(Mantid::Geometry::IMDDimension_sptr dimension) const;
+  std::string extractFormattedPropertyFromDimension(
+      Mantid::Geometry::IMDDimension_sptr dimension) const;
 
   void doRebinning();
 
@@ -62,37 +63,25 @@ private:
    Detect wheter x dimension is available.
    @return true available, false otherwise.
  */
-  bool hasXDimension() const
-  {
-    return NULL != m_appliedXDimension.get();
-  }
+  bool hasXDimension() const { return NULL != m_appliedXDimension.get(); }
 
   /**
    Detect wheter y dimension is available.
    @return true available, false otherwise.
  */
-  bool hasYDimension() const
-  {
-    return NULL != m_appliedYDimension.get();
-  }
+  bool hasYDimension() const { return NULL != m_appliedYDimension.get(); }
 
   /**
    Detect wheter z dimension is available.
    @return true available, false otherwise.
  */
-  bool hasZDimension() const
-  {
-    return NULL != m_appliedZDimension.get();
-  }
+  bool hasZDimension() const { return NULL != m_appliedZDimension.get(); }
 
   /**
    Detect wheter t dimension is available.
    @return true available, false otherwise.
  */
-  bool hasTDimension() const
-  {
-    return NULL != m_appliedTDimension.get();
-  }
+  bool hasTDimension() const { return NULL != m_appliedTDimension.get(); }
 
   /// File name from which to read.
   char *FileName;
@@ -109,7 +98,8 @@ private:
   /// Number of z bins set.
   int m_nZBins;
 
-  /// Flag indicates when set up is complete wrt  the conversion of the nexus file to a MDEventWorkspace stored in ADS.
+  /// Flag indicates when set up is complete wrt  the conversion of the nexus
+  /// file to a MDEventWorkspace stored in ADS.
   bool m_isSetup;
 
   /// The maximum threshold of counts for the visualisation.
@@ -118,28 +108,34 @@ private:
   /// The minimum threshold of counts for the visualisation.
   double m_minThreshold;
 
-  /// Flag indicating that clipping of some kind should be considered. 
+  /// Flag indicating that clipping of some kind should be considered.
   bool m_applyClip;
 
   /// vtkImplicit function from which to determine how the cut is to be made.
-  vtkImplicitFunction* m_clipFunction;
+  vtkImplicitFunction *m_clipFunction;
 
   /// With parameter (applied to plane with width).
   Mantid::MDAlgorithms::WidthParameter m_width;
 
-  /// MD Event Workspace id. strictly could be made static rather than an instance member.
+  /// MD Event Workspace id. strictly could be made static rather than an
+  /// instance member.
   const std::string m_mdEventWsId;
 
-  /// MD Histogram(IMD) Workspace id. strictly could be made static rather than an instance member.
+  /// MD Histogram(IMD) Workspace id. strictly could be made static rather than
+  /// an instance member.
   const std::string m_histogrammedWsId;
 
-  /// Abstracts the handling of rebinning states and rules govening when those states should apply.
+  /// Abstracts the handling of rebinning states and rules govening when those
+  /// states should apply.
   Mantid::VATES::EscalatingRebinningActionManager m_actionManager;
 
-  /// Converts dimension objects into well-formed xml describing the overall geometry
-  Mantid::Geometry::MDGeometryBuilderXML<Mantid::Geometry::StrictDimensionPolicy> m_geometryXmlBuilder;
+  /// Converts dimension objects into well-formed xml describing the overall
+  /// geometry
+  Mantid::Geometry::MDGeometryBuilderXML<
+      Mantid::Geometry::StrictDimensionPolicy> m_geometryXmlBuilder;
 
-  /// Sets the rebinning action to rebin if the number of bins has changed on a dimension.
+  /// Sets the rebinning action to rebin if the number of bins has changed on a
+  /// dimension.
   void formulateRequestUsingNBins(Mantid::VATES::Dimension_sptr newDim);
 
   /// the dimension information applied to the XDimension Mapping.
diff --git a/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h b/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
index 7f62d78d52f10f0490cf05de682b2fa1ff2e1acc..b28af1b9c3291f90dc9a58e4622f37af37bcfa34 100644
--- a/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
+++ b/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.h
@@ -5,8 +5,7 @@
 
 class vtkImplicitFunction;
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkNexusPeaksReader : public vtkPolyDataAlgorithm
-{
+class VTK_EXPORT vtkNexusPeaksReader : public vtkPolyDataAlgorithm {
 public:
   static vtkNexusPeaksReader *New();
   vtkNexusPeaksReader(const vtkNexusPeaksReader &) = delete;
@@ -16,12 +15,12 @@ public:
                                                     vtkIndent indent) override;
   vtkSetStringMacro(FileName);
   vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
+  int CanReadFile(const char *fname);
   void SetDimensions(int dimensions);
   /// Setter for the unitegrated peak marker size
   void SetUnintPeakMarkerSize(double mSize);
   /// Called by presenter to force progress information updating.
-  void updateAlgorithmProgress(double progress, const std::string& message);
+  void updateAlgorithmProgress(double progress, const std::string &message);
   /// Getter for the workspace type
   const std::string &GetWorkspaceTypeName();
 
@@ -32,16 +31,17 @@ protected:
                          vtkInformationVector *) override;
   int RequestData(vtkInformation *, vtkInformationVector **,
                   vtkInformationVector *) override;
-  ///Handle time variation.
+  /// Handle time variation.
   unsigned long GetMTime() override;
 
 private:
   /// File name from which to read.
   char *FileName;
 
-  /// Flag indicates when set up is complete wrt  the conversion of the nexus file to a MDEventWorkspace stored in ADS.
+  /// Flag indicates when set up is complete wrt  the conversion of the nexus
+  /// file to a MDEventWorkspace stored in ADS.
   bool m_isSetup;
-  
+
   /// Cached PeaksWs Name
   std::string m_wsTypeName;
 
@@ -49,12 +49,9 @@ private:
   double m_uintPeakMarkerSize;
 
   /// Cached PeaksWS
-  Mantid::API::IPeaksWorkspace_sptr  m_PeakWS;
+  Mantid::API::IPeaksWorkspace_sptr m_PeakWS;
 
   /// Int representing an enum for q_lab, etc.
   int m_dimensions;
-
-  
-
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h b/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
index ad8789aa584759991d7df650c8d21e0fa33c196b..1df079372b20a4f9788ed38ceffc99b4ee3067e8 100644
--- a/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
+++ b/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.h
@@ -5,8 +5,7 @@
 
 class vtkImplicitFunction;
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkPeaksReader : public vtkPolyDataAlgorithm
-{
+class VTK_EXPORT vtkPeaksReader : public vtkPolyDataAlgorithm {
 public:
   static vtkPeaksReader *New();
   vtkPeaksReader(const vtkPeaksReader &) = delete;
@@ -16,13 +15,12 @@ public:
                vtkPolyDataAlgorithm) void PrintSelf(ostream &os,
                                                     vtkIndent indent) override;
   vtkSetStringMacro(FileName)
-  vtkGetStringMacro(FileName)
-  int CanReadFile(const char* fname);
+      vtkGetStringMacro(FileName) int CanReadFile(const char *fname);
   void SetDimensions(int dimensions);
   /// Setter for the unitegrated peak marker size
   void SetUnintPeakMarkerSize(double mSize);
   /// Called by presenter to force progress information updating.
-  void updateAlgorithmProgress(double progress, const std::string& message);
+  void updateAlgorithmProgress(double progress, const std::string &message);
   /// Getter for the workspace type
   const std::string &GetWorkspaceTypeName();
 
@@ -33,16 +31,17 @@ protected:
                          vtkInformationVector *) override;
   int RequestData(vtkInformation *, vtkInformationVector **,
                   vtkInformationVector *) override;
-  ///Handle time variation.
+  /// Handle time variation.
   unsigned long GetMTime() override;
 
 private:
   /// File name from which to read.
   char *FileName;
 
-  /// Flag indicates when set up is complete wrt  the conversion of the nexus file to a MDEventWorkspace stored in ADS.
+  /// Flag indicates when set up is complete wrt  the conversion of the nexus
+  /// file to a MDEventWorkspace stored in ADS.
   bool m_isSetup;
-  
+
   /// Cached PeaksWs Name
   std::string m_wsTypeName;
 
@@ -50,12 +49,9 @@ private:
   double m_uintPeakMarkerSize;
 
   /// Cached PeaksWS
-  Mantid::API::IPeaksWorkspace_sptr  m_PeakWS;
+  Mantid::API::IPeaksWorkspace_sptr m_PeakWS;
 
   /// Int representing an enum for q_lab, etc.
   int m_dimensions;
-
-  
-
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
index 7d3eaf77e0d21bf57614d23377ebbd823eccfed9..2636d28f80e2ea5687cd7b5cdcc3b9bdee2baf50 100644
--- a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
+++ b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h
@@ -1,4 +1,4 @@
-#ifndef _vtkMDEWSource_h 
+#ifndef _vtkMDEWSource_h
 #define _vtkMDEWSource_h
 
 #include "vtkUnstructuredGridAlgorithm.h"
@@ -7,21 +7,21 @@
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    class MDLoadingPresenter;
-  }
+namespace Mantid {
+namespace VATES {
+class MDLoadingPresenter;
+}
 }
 
-/*  Source for fetching Multidimensional Workspace out of the Mantid Analysis Data Service
+/*  Source for fetching Multidimensional Workspace out of the Mantid Analysis
+   Data Service
     and converting them into vtkDataSets as part of the pipeline source.
 
     @author Owen Arnold @ Tessella
     @date 08/09/2011
 
-    Copyright &copy; 2007-9 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2007-9 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -44,8 +44,7 @@ namespace Mantid
 */
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkMDEWSource : public vtkUnstructuredGridAlgorithm
-{
+class VTK_EXPORT vtkMDEWSource : public vtkUnstructuredGridAlgorithm {
 public:
   static vtkMDEWSource *New();
   vtkTypeMacro(vtkMDEWSource, vtkUnstructuredGridAlgorithm) void PrintSelf(
@@ -62,7 +61,7 @@ public:
   //----------------------------------------------
 
   /// Update the algorithm progress.
-  void updateAlgorithmProgress(double, const std::string& message);
+  void updateAlgorithmProgress(double, const std::string &message);
   /// Getter for the input geometry xml
   std::string GetInputGeometryXML();
   /// Getter for the special coodinate value
@@ -87,7 +86,6 @@ protected:
                   vtkInformationVector *) override;
 
 private:
-  
   /// Name of the workspace.
   std::string m_wsName;
 
@@ -103,8 +101,8 @@ private:
   /// Normalization option
   Mantid::VATES::VisualNormalization m_normalization;
 
-  vtkMDEWSource(const vtkMDEWSource&);
-  void operator = (const vtkMDEWSource&);
-  void setTimeRange(vtkInformationVector* outputVector);
+  vtkMDEWSource(const vtkMDEWSource &);
+  void operator=(const vtkMDEWSource &);
+  void setTimeRange(vtkInformationVector *outputVector);
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
index 7df92b0b9afd12f7fe0532d54fdec847e0f3e44d..cb51525a752a3de18062a69daa747218efb6e248 100644
--- a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
+++ b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h
@@ -1,4 +1,4 @@
-#ifndef _vtkMDHWSource_h 
+#ifndef _vtkMDHWSource_h
 #define _vtkMDHWSource_h
 
 #include "MantidKernel/make_unique.h"
@@ -7,20 +7,20 @@
 
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    class MDLoadingPresenter;
-  }
+namespace Mantid {
+namespace VATES {
+class MDLoadingPresenter;
+}
 }
 
-/*  Source for fetching Multidimensional Workspace out of the Mantid Analysis Data Service
+/*  Source for fetching Multidimensional Workspace out of the Mantid Analysis
+   Data Service
     and converting them into vtkDataSets as part of the pipeline source.
 
     @date 01/12/2011
 
-    Copyright &copy; 2007-9 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2007-9 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -43,8 +43,7 @@ namespace Mantid
 */
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkMDHWSource : public vtkStructuredGridAlgorithm
-{
+class VTK_EXPORT vtkMDHWSource : public vtkStructuredGridAlgorithm {
 public:
   vtkMDHWSource(const vtkMDHWSource &) = delete;
   void operator=(const vtkMDHWSource &) = delete;
@@ -88,7 +87,6 @@ protected:
                   vtkInformationVector *) override;
 
 private:
-  
   /// Name of the workspace.
   std::string m_wsName;
 
@@ -101,7 +99,6 @@ private:
   /// Normalization Option
   Mantid::VATES::VisualNormalization m_normalizationOption;
 
-
-  void setTimeRange(vtkInformationVector* outputVector);
+  void setTimeRange(vtkInformationVector *outputVector);
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h b/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
index e724c0374ee847d5215488d6b35475962a34c3fd..33a1e5e8b38575b678fbab684130ff4bc7e9356c 100644
--- a/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
+++ b/Vates/ParaviewPlugins/ParaViewSources/PeaksSource/vtkPeaksSource.h
@@ -12,7 +12,8 @@
 
     @date 06/10/2011
 
-    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -35,8 +36,7 @@
 */
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkPeaksSource : public vtkPolyDataAlgorithm
-{
+class VTK_EXPORT vtkPeaksSource : public vtkPolyDataAlgorithm {
 public:
   static vtkPeaksSource *New();
   vtkPeaksSource(const vtkPeaksSource &) = delete;
@@ -50,7 +50,7 @@ public:
   /// Setter for the unitegrated peak marker size
   void SetUnintPeakMarkerSize(double mSize);
   /// Update the algorithm progress.
-  void updateAlgorithmProgress(double progress, const std::string& message);
+  void updateAlgorithmProgress(double progress, const std::string &message);
   /// Getter for the workspace name
   const std::string &GetWorkspaceName();
   /// Getter for the workspace type
diff --git a/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h b/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
index 096555adf619490900852904cc7a761e94d7c528..b7bb417ced08fc513df5ed45d908829e4636d326 100644
--- a/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
+++ b/Vates/ParaviewPlugins/ParaViewSources/SinglePeakMarkerSource/vtkSinglePeakMarkerSource.h
@@ -7,7 +7,8 @@
 
     @date 23/02/2015
 
-    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -30,10 +31,9 @@
 */
 
 // cppcheck-suppress class_X_Y
-class VTK_EXPORT vtkSinglePeakMarkerSource : public vtkPolyDataAlgorithm
-{
+class VTK_EXPORT vtkSinglePeakMarkerSource : public vtkPolyDataAlgorithm {
 public:
-  static vtkSinglePeakMarkerSource*New();
+  static vtkSinglePeakMarkerSource *New();
   vtkTypeMacro(vtkSinglePeakMarkerSource,
                vtkPolyDataAlgorithm) void PrintSelf(ostream &os,
                                                     vtkIndent indent) override;
@@ -41,6 +41,7 @@ public:
   void SetPosition1(double position1);
   void SetPosition2(double position2);
   void SetPosition3(double position3);
+
 protected:
   vtkSinglePeakMarkerSource();
   ~vtkSinglePeakMarkerSource() override;
@@ -56,7 +57,7 @@ private:
   double m_position3;
   double m_radius;
 
-  vtkSinglePeakMarkerSource(const vtkSinglePeakMarkerSource&);
-  void operator = (const vtkSinglePeakMarkerSource&);
+  vtkSinglePeakMarkerSource(const vtkSinglePeakMarkerSource &);
+  void operator=(const vtkSinglePeakMarkerSource &);
 };
 #endif
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/BinInputWidget.h b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/BinInputWidget.h
index 652fccf9b7f4ad579ebf5c46eab1438edaa33746..9a18d4afb60a49ee224d7860468e8116bdd5e101 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/BinInputWidget.h
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/BinInputWidget.h
@@ -1,13 +1,12 @@
 #ifndef BIN_INPUT_WIDGET_H_
-#define BIN_INPUT_WIDGET_H_ 
+#define BIN_INPUT_WIDGET_H_
 
 #include <QWidget>
 
 /**
 Abstract bin widget
 */
-class BinInputWidget : public QWidget
-{
+class BinInputWidget : public QWidget {
   Q_OBJECT
 public:
   /// Getter for the number of bins
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.cpp b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.cpp
index 33773624b4abc357947bc04004f8dfd2aaa7ab84..54ba689e1217f363bb348e4ea09a1ddaea6611af 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.cpp
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.cpp
@@ -12,10 +12,9 @@ Calculate the number of bins from low,high,step.
 @param step: The step
 @return calculated number of bins.
 */
-int calculateNBins(double low, double high, double step)
-{
-  ///Note that the result is being truncated here!
-  return int((high-low)/step);
+int calculateNBins(double low, double high, double step) {
+  /// Note that the result is being truncated here!
+  return int((high - low) / step);
 }
 
 /**
@@ -25,22 +24,20 @@ Calculate the step from the high, low, number of bins
 @param nBins: The number of bins
 @return calculated number of bins.
 */
-double calculateStep(double low, double high, double nBins)
-{
-  return (high-low)/nBins;
+double calculateStep(double low, double high, double nBins) {
+  return (high - low) / nBins;
 }
 
 /// Constructor
-LowHighStepInputWidget::LowHighStepInputWidget()
-{
+LowHighStepInputWidget::LowHighStepInputWidget() {
   m_step = new QLineEdit();
 
   connect(m_step, SIGNAL(editingFinished()), this, SLOT(nBinsListener()));
 
-  QDoubleValidator* stepValidator = new QDoubleValidator(0, 10000, 5, this);
+  QDoubleValidator *stepValidator = new QDoubleValidator(0, 10000, 5, this);
   m_step->setValidator(stepValidator);
 
-  QHBoxLayout* layout = new QHBoxLayout;
+  QHBoxLayout *layout = new QHBoxLayout;
   layout->addWidget(new QLabel("Step"));
   layout->addWidget(m_step);
 
@@ -52,8 +49,7 @@ Getter for the entry
 @min : min value
 @max : max value
 */
-int LowHighStepInputWidget::getEntry(double min, double max) const
-{
+int LowHighStepInputWidget::getEntry(double min, double max) const {
   double step = m_step->text().toDouble();
   return calculateNBins(min, max, step);
 }
@@ -64,8 +60,7 @@ Set the entry assuming that only the step will change.
 @min : minimum (low)
 @max : maximum (high)
 */
-void LowHighStepInputWidget::setEntry(int nBins, double min, double max)
-{
+void LowHighStepInputWidget::setEntry(int nBins, double min, double max) {
   double step = calculateStep(min, max, double(nBins));
   std::stringstream stream;
   stream << step;
@@ -73,14 +68,9 @@ void LowHighStepInputWidget::setEntry(int nBins, double min, double max)
 }
 
 /// Destructor.
-LowHighStepInputWidget::~LowHighStepInputWidget()
-{
-}
+LowHighStepInputWidget::~LowHighStepInputWidget() {}
 
 /**
 Listener for internal events, pubishing a public 'changed' call
 */
-void LowHighStepInputWidget::nBinsListener()
-{
-  emit valueChanged();
-}
+void LowHighStepInputWidget::nBinsListener() { emit valueChanged(); }
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.h b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.h
index 16925810abb0d4d959b14f50c9d9299b8702bbdb..2c465ce264796243627d9baf638fb99a156d3b70 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.h
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/LowHighStepInputWidget.h
@@ -1,11 +1,10 @@
 #ifndef LOW_STEP_HIGH_INPUT_WIDGET_H_
-#define LOW_STEP_HIGH_INPUT_WIDGET_H_ 
+#define LOW_STEP_HIGH_INPUT_WIDGET_H_
 
 #include "BinInputWidget.h"
 class QLineEdit;
 
-class LowHighStepInputWidget : public BinInputWidget
-{  
+class LowHighStepInputWidget : public BinInputWidget {
   Q_OBJECT
 public:
   int getEntry(double min, double max) const override;
@@ -14,9 +13,10 @@ public:
   ~LowHighStepInputWidget() override;
 private slots:
   void nBinsListener();
+
 private:
-   /// Low/High/Step boxes
-   QLineEdit* m_step;
+  /// Low/High/Step boxes
+  QLineEdit *m_step;
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.cpp b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.cpp
index fffcdb4385da537295d73d44fda40fe2592f7d78..3b493bff5cf39d2036ae3c9d0526da5aee07dcbb 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.cpp
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.cpp
@@ -8,17 +8,16 @@
 /**
 Constructor
 */
-SimpleBinInputWidget::SimpleBinInputWidget()
-{
-  QLabel* binLabel = new QLabel("Bins");
-  
-  QIntValidator* validator = new QIntValidator;
+SimpleBinInputWidget::SimpleBinInputWidget() {
+  QLabel *binLabel = new QLabel("Bins");
+
+  QIntValidator *validator = new QIntValidator;
   validator->setBottom(2);
   validator->setTop(1000);
 
   m_nBinsBox = new QLineEdit;
   m_nBinsBox->setValidator(validator);
-  QHBoxLayout* layout = new QHBoxLayout;
+  QHBoxLayout *layout = new QHBoxLayout;
 
   layout->addWidget(binLabel);
   layout->addWidget(m_nBinsBox);
@@ -31,8 +30,7 @@ SimpleBinInputWidget::SimpleBinInputWidget()
 Entry setter.
 @param value : value that the entry should take.
 */
-void SimpleBinInputWidget::setEntry(int nBins,double,double)
-{
+void SimpleBinInputWidget::setEntry(int nBins, double, double) {
   std::stringstream stream;
   stream << nBins;
   m_nBinsBox->setText(stream.str().c_str());
@@ -42,19 +40,15 @@ void SimpleBinInputWidget::setEntry(int nBins,double,double)
 Getter for the current entry.
 @return current entry value
 */
-int SimpleBinInputWidget::getEntry(double, double) const
-{
+int SimpleBinInputWidget::getEntry(double, double) const {
   return atoi(m_nBinsBox->text().toAscii().constData());
 }
 
 /// Destructor
-SimpleBinInputWidget::~SimpleBinInputWidget()
-{
-}
+SimpleBinInputWidget::~SimpleBinInputWidget() {}
 
 /// Listener and emitter for the number of having changed.
-void SimpleBinInputWidget::nBinsListener()
-{
- // Raise an event that is published publically
+void SimpleBinInputWidget::nBinsListener() {
+  // Raise an event that is published publically
   emit valueChanged();
 }
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.h b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.h
index 07c7326880612d0a32399801394d37ead48fce1d..b7e9474b6ee1b7a29f650b9e4916f9a3af84177d 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.h
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/SimpleBinInputWidget.h
@@ -1,5 +1,5 @@
 #ifndef SIMPLE_BIN_INPUT_WIDGET_H
-#define SIMPLE_BIN_INPUT_WIDGET_H 
+#define SIMPLE_BIN_INPUT_WIDGET_H
 
 #include "BinInputWidget.h"
 class QLineEdit;
@@ -7,10 +7,9 @@ class QLineEdit;
 /**
 class SimpleBinInputWidget
 This simple implementation allows users to specify the number of bins directly.
-Widget wrapper around a label and text box. 
+Widget wrapper around a label and text box.
 */
-class SimpleBinInputWidget : public BinInputWidget
-{
+class SimpleBinInputWidget : public BinInputWidget {
   Q_OBJECT
 
 public:
@@ -24,9 +23,10 @@ public:
   ~SimpleBinInputWidget() override;
 private slots:
   void nBinsListener();
+
 private:
-   /// Number of bins text box.
-   QLineEdit* m_nBinsBox;
+  /// Number of bins text box.
+  QLineEdit *m_nBinsBox;
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.cpp b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.cpp
index 80047af725dd59e0daac83a583c5ccbf2d7dbe6d..a4716b05d07ff3df4fd5bcfacc704bd8ef408606 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.cpp
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.cpp
@@ -9,12 +9,12 @@
 #include <boost/format.hpp>
 #include <QDoubleValidator>
 
-ThresholdRangeWidget::ThresholdRangeWidget(double min, double max) 
-{
-  QVBoxLayout* layout = new QVBoxLayout;
+ThresholdRangeWidget::ThresholdRangeWidget(double min, double max) {
+  QVBoxLayout *layout = new QVBoxLayout;
 
-  QGridLayout* headerLayout = new QGridLayout();
-  headerLayout->addWidget(new QLabel("Thresholds"), 0, 0, 1, 2, Qt::AlignCenter);
+  QGridLayout *headerLayout = new QGridLayout();
+  headerLayout->addWidget(new QLabel("Thresholds"), 0, 0, 1, 2,
+                          Qt::AlignCenter);
   layout->addLayout(headerLayout);
 
   m_thresholdStrategyComboBox = new QComboBox;
@@ -22,10 +22,12 @@ ThresholdRangeWidget::ThresholdRangeWidget(double min, double max)
   m_thresholdStrategyComboBox->addItem("No Threshold Range");
   m_thresholdStrategyComboBox->addItem("Median and Below");
   m_thresholdStrategyComboBox->addItem("User Defined");
-  connect(m_thresholdStrategyComboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(strategySelectedListener(const QString &)));
+  connect(m_thresholdStrategyComboBox,
+          SIGNAL(currentIndexChanged(const QString &)), this,
+          SLOT(strategySelectedListener(const QString &)));
   layout->addWidget(m_thresholdStrategyComboBox, Qt::AlignLeft);
 
-  QHBoxLayout* mmLayout = new QHBoxLayout();
+  QHBoxLayout *mmLayout = new QHBoxLayout();
 
   mmLayout->addWidget(new QLabel("Min"));
 
@@ -35,8 +37,9 @@ ThresholdRangeWidget::ThresholdRangeWidget(double min, double max)
   m_minEditBox->setText(minValueString.c_str());
   m_minEditBox->setCursorPosition(0);
   mmLayout->addWidget(m_minEditBox, Qt::AlignLeft);
-  m_minEditBox->setDisabled(true); //Disabled by default.
-  connect(m_minEditBox, SIGNAL(textEdited(const QString &)), this, SLOT(minThresholdListener(const QString &)));
+  m_minEditBox->setDisabled(true); // Disabled by default.
+  connect(m_minEditBox, SIGNAL(textEdited(const QString &)), this,
+          SLOT(minThresholdListener(const QString &)));
 
   mmLayout->addWidget(new QLabel("Max"));
 
@@ -45,20 +48,19 @@ ThresholdRangeWidget::ThresholdRangeWidget(double min, double max)
   std::string maxValueString = boost::str(boost::format("%0.2f") % max);
   m_maxEditBox->setText(maxValueString.c_str());
   m_maxEditBox->setCursorPosition(0);
-  m_maxEditBox->setDisabled(true); //Disabled by default
+  m_maxEditBox->setDisabled(true); // Disabled by default
   mmLayout->addWidget(m_maxEditBox, Qt::AlignLeft);
-  connect(m_maxEditBox, SIGNAL(textEdited(const QString &)), this, SLOT(maxThresholdListener(const QString &)));
+  connect(m_maxEditBox, SIGNAL(textEdited(const QString &)), this,
+          SLOT(maxThresholdListener(const QString &)));
 
   layout->addLayout(mmLayout);
 
   this->setLayout(layout);
 }
 
-void ThresholdRangeWidget::strategySelectedListener(const QString&)
-{
+void ThresholdRangeWidget::strategySelectedListener(const QString &) {
   bool disableUserControls = true;
-  if(m_thresholdStrategyComboBox->currentText() == "User Defined")
-  {
+  if (m_thresholdStrategyComboBox->currentText() == "User Defined") {
     disableUserControls = false;
   }
   m_maxEditBox->setDisabled(disableUserControls);
@@ -67,47 +69,38 @@ void ThresholdRangeWidget::strategySelectedListener(const QString&)
   emit chosenStrategyChanged();
 }
 
-void ThresholdRangeWidget::maxThresholdListener(const QString &)
-{
+void ThresholdRangeWidget::maxThresholdListener(const QString &) {
   emit maxChanged();
 }
 
-void ThresholdRangeWidget::minThresholdListener(const QString &)
-{
+void ThresholdRangeWidget::minThresholdListener(const QString &) {
   emit minChanged();
 }
 
-void ThresholdRangeWidget::setMaximum(double value)
-{
+void ThresholdRangeWidget::setMaximum(double value) {
   std::string maxValueString = boost::str(boost::format("%0.2f") % value);
   m_maxEditBox->setText(maxValueString.c_str());
   m_maxEditBox->setCursorPosition(0);
 }
 
-void ThresholdRangeWidget::setMinimum(double value)
-{
+void ThresholdRangeWidget::setMinimum(double value) {
   std::string minValueString = boost::str(boost::format("%0.2f") % value);
   m_minEditBox->setText(minValueString.c_str());
   m_minEditBox->setCursorPosition(0);
 }
 
-ThresholdRangeWidget::~ThresholdRangeWidget()
-{
-}
+ThresholdRangeWidget::~ThresholdRangeWidget() {}
 
-QString ThresholdRangeWidget::getMaxSignal() const
-{
+QString ThresholdRangeWidget::getMaxSignal() const {
   return m_maxEditBox->text();
 }
 
-QString ThresholdRangeWidget::getMinSignal() const
-{
+QString ThresholdRangeWidget::getMinSignal() const {
   return m_minEditBox->text();
 }
 
-QString ThresholdRangeWidget::getChosenStrategy() const
-{
-  std::string minValueString = boost::str(boost::format("%i") % m_thresholdStrategyComboBox->currentIndex());
+QString ThresholdRangeWidget::getChosenStrategy() const {
+  std::string minValueString = boost::str(
+      boost::format("%i") % m_thresholdStrategyComboBox->currentIndex());
   return QString(minValueString.c_str());
 }
-
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.h b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.h
index b375e916ca765af5e8d5ddae5f90adfb9bdc29ca..4a89b9fc8d82f0df5e95c7fcb522f74040e4f6b7 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.h
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/ThresholdRangeWidget.h
@@ -6,12 +6,14 @@
 #include <qstring.h>
 #include "MantidGeometry/MDGeometry/MDTypes.h"
 #include <qlineedit.h>
-/** This is the GUI implementation of the threshold range widgets. These are used to set max and min threshold values.
+/** This is the GUI implementation of the threshold range widgets. These are
+   used to set max and min threshold values.
 
     @author Owen Arnold Tessella/ISIS
     @date July 04/2011
 
-    Copyright &copy; 2008 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2008 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -32,64 +34,61 @@
     Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
 
-//Foward decs
+// Foward decs
 class QLabel;
 class QLayout;
 class QLineEdit;
 class QComboBox;
 
 // cppcheck-suppress class_X_Y
-class EXPORT_OPT_MANTIDPARVIEW ThresholdRangeWidget: public QWidget
-{
+class EXPORT_OPT_MANTIDPARVIEW ThresholdRangeWidget : public QWidget {
 
-Q_OBJECT
+  Q_OBJECT
 public:
-Q_PROPERTY(QString MinSignal READ getMinSignal WRITE setMinSignal NOTIFY minChanged)
-Q_PROPERTY(QString MaxSignal READ getMaxSignal WRITE setMaxSignal NOTIFY maxChanged)
-Q_PROPERTY(QString ChosenStrategy READ getChosenStrategy WRITE setChosenStrategy NOTIFY chosenStrategyChanged)
+  Q_PROPERTY(QString MinSignal READ getMinSignal WRITE setMinSignal NOTIFY
+                 minChanged)
+  Q_PROPERTY(QString MaxSignal READ getMaxSignal WRITE setMaxSignal NOTIFY
+                 maxChanged)
+  Q_PROPERTY(QString ChosenStrategy READ getChosenStrategy WRITE
+                 setChosenStrategy NOTIFY chosenStrategyChanged)
 
-ThresholdRangeWidget(double min, double max);
+  ThresholdRangeWidget(double min, double max);
 
-~ThresholdRangeWidget() override;
+  ~ThresholdRangeWidget() override;
 
-QString getMaxSignal() const;
-QString getMinSignal() const;
-QString getChosenStrategy() const;
+  QString getMaxSignal() const;
+  QString getMinSignal() const;
+  QString getChosenStrategy() const;
 
-void setMaximum(double value);
-void setMinimum(double value);
+  void setMaximum(double value);
+  void setMinimum(double value);
 
-void setMinSignal(QString value)
-{
-  //Do nothing.
-  UNUSED_ARG(value);
-}
+  void setMinSignal(QString value) {
+    // Do nothing.
+    UNUSED_ARG(value);
+  }
 
-void setMaxSignal(QString value)
-{
-  //Do nothing.
-  UNUSED_ARG(value);
-}
-
-void setChosenStrategy(QString value)
-{
-  //Do nothing.
-  UNUSED_ARG(value);
-}
+  void setMaxSignal(QString value) {
+    // Do nothing.
+    UNUSED_ARG(value);
+  }
 
+  void setChosenStrategy(QString value) {
+    // Do nothing.
+    UNUSED_ARG(value);
+  }
 
 Q_SIGNALS:
-        void minChanged();
-        void maxChanged();
-        void chosenStrategyChanged();
+  void minChanged();
+  void maxChanged();
+  void chosenStrategyChanged();
 
 private:
+  QLineEdit *m_maxEditBox;
+  QLineEdit *m_minEditBox;
+  QComboBox *m_thresholdStrategyComboBox;
 
-  QLineEdit* m_maxEditBox;
-  QLineEdit* m_minEditBox;
-  QComboBox* m_thresholdStrategyComboBox;
-
-  private slots:
+private slots:
   void maxThresholdListener(const QString &);
 
   void minThresholdListener(const QString &);
diff --git a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
index 82c72c8c1db3d6e748971cf604ddd5381901d4da..7b120e47363f983c3964721b6c3829fda2073fb3 100644
--- a/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
+++ b/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
@@ -4,9 +4,9 @@
 #include <MantidKernel/System.h>
 
 #ifdef IN_MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS
-#define EXPORT_OPT_MANTIDPARVIEW DLLExport 
+#define EXPORT_OPT_MANTIDPARVIEW DLLExport
 #else
 #define EXPORT_OPT_MANTIDPARVIEW DLLImport
 #endif /* IN_MANTIDQT_MANTIDWIDGETS */
 
-#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+#endif // MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/ADSWorkspaceProvider.h b/Vates/VatesAPI/inc/MantidVatesAPI/ADSWorkspaceProvider.h
index 4fde5b4c9feeafe45ac592389406fc8e75e787c6..0aaebab0e5783444e56b154bf0801b94acc463ee 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/ADSWorkspaceProvider.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/ADSWorkspaceProvider.h
@@ -3,55 +3,53 @@
 
 #include "MantidVatesAPI/WorkspaceProvider.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-     /** 
-    @class ADSWorkspaceProvider
-    Type for fetching and disposing of workspaces using the Mantid Analysis Data Service Instance under-the-hood.
-
-    @author Owen Arnold, Tessella plc
-    @date 22/08/2011
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    template<typename Workspace_Type>
-    class DLLExport ADSWorkspaceProvider : public WorkspaceProvider
-    {
-    public:
-      ADSWorkspaceProvider();
-      ~ADSWorkspaceProvider() override;
-
-      //-------WorkspaceProivder Implementations ------------
-      bool canProvideWorkspace(std::string wsName) const override;
-      Mantid::API::Workspace_sptr
-      fetchWorkspace(std::string wsName) const override;
-      void disposeWorkspace(std::string wsName) const override;
-
-    private:
-      ADSWorkspaceProvider& operator=(const ADSWorkspaceProvider&);
-      ADSWorkspaceProvider(const ADSWorkspaceProvider&);
-    };
-  }
+namespace Mantid {
+namespace VATES {
+/**
+@class ADSWorkspaceProvider
+Type for fetching and disposing of workspaces using the Mantid Analysis Data
+Service Instance under-the-hood.
+
+@author Owen Arnold, Tessella plc
+@date 22/08/2011
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+template <typename Workspace_Type>
+class DLLExport ADSWorkspaceProvider : public WorkspaceProvider {
+public:
+  ADSWorkspaceProvider();
+  ~ADSWorkspaceProvider() override;
+
+  //-------WorkspaceProivder Implementations ------------
+  bool canProvideWorkspace(std::string wsName) const override;
+  Mantid::API::Workspace_sptr fetchWorkspace(std::string wsName) const override;
+  void disposeWorkspace(std::string wsName) const override;
+
+private:
+  ADSWorkspaceProvider &operator=(const ADSWorkspaceProvider &);
+  ADSWorkspaceProvider(const ADSWorkspaceProvider &);
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/BoxInfo.h b/Vates/VatesAPI/inc/MantidVatesAPI/BoxInfo.h
index 4341c22c04b10cba709051b7fd7ed8d31800b806..4ade66519b1767f59f52ca5c02f09bd9c7082124 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/BoxInfo.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/BoxInfo.h
@@ -5,10 +5,8 @@
 #include "MantidVatesAPI/WorkspaceProvider.h"
 #include <boost/optional.hpp>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 /**
 Collection of functions related to box information
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/Common.h b/Vates/VatesAPI/inc/MantidVatesAPI/Common.h
index 8dfa7386db92e9274c54218f25c1086a5ff9cc04..54c25aa86e650b0f4e90d8c0115f8d62f1e15f27 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/Common.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/Common.h
@@ -6,24 +6,24 @@
 
 class vtkFieldData;
 
-namespace Mantid
-{
-namespace Geometry
-{
-//Forward dec
+namespace Mantid {
+namespace Geometry {
+// Forward dec
 class IMDDimension;
 }
 
-namespace VATES
-{
+namespace VATES {
 /// Vector of IMDDimension shared pointers.
-typedef std::vector<boost::shared_ptr<Mantid::Geometry::IMDDimension> > DimensionVec;
+typedef std::vector<boost::shared_ptr<Mantid::Geometry::IMDDimension>>
+    DimensionVec;
 
 /// IMDDimension as shared pointer.
 typedef boost::shared_ptr<Mantid::Geometry::IMDDimension> Dimension_sptr;
 
-/// IMDDimension as const shared pointer. Note that IMDDimension is pure virtual.
-typedef boost::shared_ptr<const Mantid::Geometry::IMDDimension> Dimension_const_sptr;
+/// IMDDimension as const shared pointer. Note that IMDDimension is pure
+/// virtual.
+typedef boost::shared_ptr<const Mantid::Geometry::IMDDimension>
+    Dimension_const_sptr;
 
 std::string makeAxisTitle(const Mantid::Geometry::IMDDimension &dim);
 
@@ -40,10 +40,7 @@ std::string convertAxesTitleToLatex(const std::string &toConvert);
 
 void setAxisLabel(const std::string &metadataLabel,
                   const std::string &labelString, vtkFieldData *fieldData);
-
-
 }
-
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h b/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
index b6d4e4c506c74bc40c99ae1d399f74b589057f0a..244373c7f3e63b8e1e06ed60d457bbb9e4673c0d 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/ConcretePeaksPresenterVsi.h
@@ -15,7 +15,8 @@ namespace VATES {
 class DLLExport ConcretePeaksPresenterVsi : public PeaksPresenterVsi {
 public:
   ConcretePeaksPresenterVsi(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
-                            ViewFrustum_const_sptr frustum, std::string wsFrame);
+                            ViewFrustum_const_sptr frustum,
+                            std::string wsFrame);
   ~ConcretePeaksPresenterVsi() override;
   Mantid::API::IPeaksWorkspace_sptr getPeaksWorkspace() const override;
   std::vector<bool> getViewablePeaks() const override;
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/DimensionViewFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/DimensionViewFactory.h
index 1734199ef250e6c7ae8ea01d930d4032c16ed9c3..9735227f4a532629769ec10235fff9395ff5484d 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/DimensionViewFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/DimensionViewFactory.h
@@ -2,20 +2,17 @@
 #define _DIMENSION_VIEW_FACTORY_H
 
 #include "MantidVatesAPI/DimensionView.h"
-namespace Mantid
-{
-  namespace VATES
-  {
-    /**
-    class Abstract DimensionViewFactory provides Factory Method
-    */
-    class DLLExport DimensionViewFactory
-    {
-    public:
-      virtual DimensionView* create() const = 0;
-      virtual ~DimensionViewFactory(){}
-    };
-  }
+namespace Mantid {
+namespace VATES {
+/**
+class Abstract DimensionViewFactory provides Factory Method
+*/
+class DLLExport DimensionViewFactory {
+public:
+  virtual DimensionView *create() const = 0;
+  virtual ~DimensionViewFactory() {}
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h
index 948bccd189b57d1a4b1a4da754545bb1173a9d8a..ec25c11c51bd4a22f17520d925e1959991762dd2 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h
@@ -3,59 +3,56 @@
 
 #include "MantidVatesAPI/MDEWLoadingPresenter.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /** 
-    @class EventNexusLoadingPresenter
-    Presenter for loading conversion of MDEW workspaces into render-able vtk objects.
-    @author Owen Arnold, Tessella plc
-    @date 05/08/2011
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class MDLoadingView;
-    class DLLExport EventNexusLoadingPresenter : public MDEWLoadingPresenter
-    {
-    public:
-      EventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view,
-                                 const std::string fileName);
-      vtkSmartPointer<vtkDataSet>
-      execute(vtkDataSetFactory *factory, ProgressAction &loadingProgressUpdate,
-              ProgressAction &drawingProgressUpdate) override;
-      void executeLoadMetadata() override;
-      bool hasTDimensionAvailable() const override;
-      std::vector<double> getTimeStepValues() const override;
-      ~EventNexusLoadingPresenter() override;
-      bool canReadFile() const override;
-      std::string getWorkspaceTypeName() override;
-
-    private:
-      const std::string m_filename;
-      std::string m_wsTypeName;
-    };
-
-
-  }
+namespace Mantid {
+namespace VATES {
+/**
+@class EventNexusLoadingPresenter
+Presenter for loading conversion of MDEW workspaces into render-able vtk
+objects.
+@author Owen Arnold, Tessella plc
+@date 05/08/2011
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MDLoadingView;
+class DLLExport EventNexusLoadingPresenter : public MDEWLoadingPresenter {
+public:
+  EventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view,
+                             const std::string fileName);
+  vtkSmartPointer<vtkDataSet>
+  execute(vtkDataSetFactory *factory, ProgressAction &loadingProgressUpdate,
+          ProgressAction &drawingProgressUpdate) override;
+  void executeLoadMetadata() override;
+  bool hasTDimensionAvailable() const override;
+  std::vector<double> getTimeStepValues() const override;
+  ~EventNexusLoadingPresenter() override;
+  bool canReadFile() const override;
+  std::string getWorkspaceTypeName() override;
+
+private:
+  const std::string m_filename;
+  std::string m_wsTypeName;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/FactoryChains.h b/Vates/VatesAPI/inc/MantidVatesAPI/FactoryChains.h
index c707295d93286131a644f5c761c10b5720d37d0c..e7c61d33c62d47f49eed819479079d61f9f989cd 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/FactoryChains.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/FactoryChains.h
@@ -11,30 +11,32 @@
 
 #include <vtkPVClipDataSet.h>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 // Forward Decalaration
 class MDLoadingPresenter;
 
 /// Creates a facotry chain for MDHisto workspaces
-std::unique_ptr<vtkMDHistoHex4DFactory<TimeToTimeStep>> DLLExport createFactoryChainForHistoWorkspace(ThresholdRange_scptr threshold,
+std::unique_ptr<vtkMDHistoHex4DFactory<TimeToTimeStep>> DLLExport
+createFactoryChainForHistoWorkspace(ThresholdRange_scptr threshold,
                                     VisualNormalization normalization,
                                     double time);
 
 /// Creates a factory chain for MDEvent workspaces
-std::unique_ptr<vtkMDHexFactory> DLLExport createFactoryChainForEventWorkspace(ThresholdRange_scptr threshold,
+std::unique_ptr<vtkMDHexFactory> DLLExport
+createFactoryChainForEventWorkspace(ThresholdRange_scptr threshold,
                                     VisualNormalization normalization,
                                     double time);
 
 /// Function to apply the Change-of-Basis-Matrix
-void DLLExport applyCOBMatrixSettingsToVtkDataSet(MDLoadingPresenter *presenter, vtkDataSet *dataSet,
+void DLLExport applyCOBMatrixSettingsToVtkDataSet(
+    MDLoadingPresenter *presenter, vtkDataSet *dataSet,
     std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider);
 
 /// Function to get clipped data sets.
-vtkSmartPointer<vtkPVClipDataSet> DLLExport getClippedDataSet(vtkSmartPointer<vtkDataSet> dataSet);
+vtkSmartPointer<vtkPVClipDataSet> DLLExport
+getClippedDataSet(vtkSmartPointer<vtkDataSet> dataSet);
 
 /// Create name with timestamp attached.
 std::string DLLExport createTimeStampedName(std::string name);
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/FieldDataToMetadata.h b/Vates/VatesAPI/inc/MantidVatesAPI/FieldDataToMetadata.h
index ba4163e77cfc44e1421c34cbe0a5df1c1718eafa..694dce9654540ec293645568ef7d2815d815e3a2 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/FieldDataToMetadata.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/FieldDataToMetadata.h
@@ -6,10 +6,8 @@
 #include "MantidKernel/System.h"
 
 class vtkFieldData;
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
  * Functor Converts fielddata of type vtkFieldData to metadata (std::string).
@@ -17,7 +15,8 @@ namespace VATES
  @author Owen Arnold, Tessella plc
  @date 09/02/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -38,16 +37,15 @@ namespace VATES
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class DLLExport FieldDataToMetadata : public std::binary_function<vtkFieldData*, std::string, std::string>
-{
+class DLLExport FieldDataToMetadata
+    : public std::binary_function<vtkFieldData *, std::string, std::string> {
 public:
   /// Act as Functor.
-  std::string operator()(vtkFieldData* fieldData, std::string id) const;
+  std::string operator()(vtkFieldData *fieldData, std::string id) const;
 
   /// Explicit call to Functor execution.
-  std::string execute(vtkFieldData* fieldData,const std::string& id) const;
+  std::string execute(vtkFieldData *fieldData, const std::string &id) const;
 };
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/FilteringUpdateProgressAction.h b/Vates/VatesAPI/inc/MantidVatesAPI/FilteringUpdateProgressAction.h
index fa15e19fad050c7f8cef1b63273904050f3d5f30..af6bf79cba64e2aef7ed9bff0f7cfbe897c395d9 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/FilteringUpdateProgressAction.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/FilteringUpdateProgressAction.h
@@ -4,12 +4,14 @@
 #include "MantidKernel/System.h"
 #include "MantidVatesAPI/ProgressAction.h"
 
-/** Adapter for action specific to ParaView RebinningCutter filter. Handles progress actions raised by underlying Mantid Algorithms.
+/** Adapter for action specific to ParaView RebinningCutter filter. Handles
+ progress actions raised by underlying Mantid Algorithms.
 
  @author Owen Arnold, Tessella plc
  @date 14/03/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -30,43 +32,34 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
+namespace Mantid {
+namespace VATES {
 
-namespace Mantid
-{
-namespace VATES
-{
-
-/// Template argument is the exact filter/source/reader providing the public UpdateAlgorithmProgress method.
-template<typename Filter>
-class DLLExport FilterUpdateProgressAction : public ProgressAction
-{
+/// Template argument is the exact filter/source/reader providing the public
+/// UpdateAlgorithmProgress method.
+template <typename Filter>
+class DLLExport FilterUpdateProgressAction : public ProgressAction {
 
 public:
-
-  FilterUpdateProgressAction(Filter* filter, const std::string& message) : m_filter(filter), m_message(message)
-  {
-  }
+  FilterUpdateProgressAction(Filter *filter, const std::string &message)
+      : m_filter(filter), m_message(message) {}
 
   void eventRaised(double progress) override {
     m_filter->updateAlgorithmProgress(progress, m_message);
   }
 
-  ~FilterUpdateProgressAction()
-  {
-  }
+  ~FilterUpdateProgressAction() {}
 
 private:
+  FilterUpdateProgressAction &operator=(FilterUpdateProgressAction &);
 
-  FilterUpdateProgressAction& operator=(FilterUpdateProgressAction&);
-
-  FilterUpdateProgressAction(FilterUpdateProgressAction&);
+  FilterUpdateProgressAction(FilterUpdateProgressAction &);
 
-  Filter* m_filter;
+  Filter *m_filter;
 
   /// Message associated with the progress action
   std::string m_message;
 };
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/GeometryView.h b/Vates/VatesAPI/inc/MantidVatesAPI/GeometryView.h
index dabb23d9e22e94952364dd2b0ea62f474c95d205..8068b4b73876bd07ebdd7e95ca88f32af734e90d 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/GeometryView.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/GeometryView.h
@@ -3,49 +3,47 @@
 #include "MantidKernel/System.h"
 #include "MantidVatesAPI/DimensionView.h"
 #include "MantidVatesAPI/DimensionViewFactory.h"
-namespace Mantid
-{
-  namespace VATES
-  {
-    class QString;
-
-    /** 
-    @class GeometryView
-    Abstract view for controlling multi-dimensional geometries.
-    @author Owen Arnold, Tessella plc
-    @date 03/06/2011
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport GeometryView 
-    {
-    public:
-      virtual void addDimensionView(DimensionView*) = 0;
-      virtual std::string getGeometryXMLString() const = 0;
-      virtual const DimensionViewFactory& getDimensionViewFactory() = 0;
-      virtual ~GeometryView(){};
-      virtual void raiseModified() = 0;
-      virtual Mantid::VATES::BinDisplay getBinDisplayMode() const = 0;
-    };
-  }
+namespace Mantid {
+namespace VATES {
+class QString;
+
+/**
+@class GeometryView
+Abstract view for controlling multi-dimensional geometries.
+@author Owen Arnold, Tessella plc
+@date 03/06/2011
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport GeometryView {
+public:
+  virtual void addDimensionView(DimensionView *) = 0;
+  virtual std::string getGeometryXMLString() const = 0;
+  virtual const DimensionViewFactory &getDimensionViewFactory() = 0;
+  virtual ~GeometryView(){};
+  virtual void raiseModified() = 0;
+  virtual Mantid::VATES::BinDisplay getBinDisplayMode() const = 0;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/IMDDimensionComparitor.h b/Vates/VatesAPI/inc/MantidVatesAPI/IMDDimensionComparitor.h
index 44ae10008f1c45868d64114b7b4e05a04b52ad00..b93a6371aac036b7e42f43b8213a8fe3169856d9 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/IMDDimensionComparitor.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/IMDDimensionComparitor.h
@@ -3,67 +3,63 @@
 
 #include "MantidAPI/IMDWorkspace.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    
-    /** Dimension comparitor specifically for use with visualisation layer. Given an arrangement of dimensions in an MDImage, this type
-allow the utilising code to ask wheter some dimension maps to the x, y, or z dimensions.
-
- @author Owen Arnold, Tessella plc
- @date 25/03/2011
-
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
- This file is part of Mantid.
-
- Mantid is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 3 of the License, or
- (at your option) any later version.
-
- Mantid is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
- File change history is stored at: <https://github.com/mantidproject/mantid>
- Code Documentation is available at: <http://doxygen.mantidproject.org>
- */
-    class IMDDimensionComparitor
-    {
-    public:
-     
-    /// Constructor
-    IMDDimensionComparitor(Mantid::API::IMDWorkspace_sptr workspace);
-
-    /// Destructor
-    ~IMDDimensionComparitor();
-
-    bool isXDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension);
-    
-    bool isYDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension);
-
-    bool isZDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension);
-
-    bool istDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension);
-
-    private:
-      
-    /// imd workspace shared ptr.
-    Mantid::API::IMDWorkspace_sptr m_workspace;
-     
-    IMDDimensionComparitor operator=(IMDDimensionComparitor&);
-      
-    IMDDimensionComparitor(IMDDimensionComparitor&);
-
-    };
-
-  }
+namespace Mantid {
+namespace VATES {
+
+/** Dimension comparitor specifically for use with visualisation layer. Given an
+arrangement of dimensions in an MDImage, this type
+allow the utilising code to ask wheter some dimension maps to the x, y, or z
+dimensions.
+
+@author Owen Arnold, Tessella plc
+@date 25/03/2011
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class IMDDimensionComparitor {
+public:
+  /// Constructor
+  IMDDimensionComparitor(Mantid::API::IMDWorkspace_sptr workspace);
+
+  /// Destructor
+  ~IMDDimensionComparitor();
+
+  bool isXDimension(Mantid::Geometry::IMDDimension_const_sptr queryDimension);
+
+  bool isYDimension(Mantid::Geometry::IMDDimension_const_sptr queryDimension);
+
+  bool isZDimension(Mantid::Geometry::IMDDimension_const_sptr queryDimension);
+
+  bool istDimension(Mantid::Geometry::IMDDimension_const_sptr queryDimension);
+
+private:
+  /// imd workspace shared ptr.
+  Mantid::API::IMDWorkspace_sptr m_workspace;
+
+  IMDDimensionComparitor operator=(IMDDimensionComparitor &);
+
+  IMDDimensionComparitor(IMDDimensionComparitor &);
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/IgnoreZerosThresholdRange.h b/Vates/VatesAPI/inc/MantidVatesAPI/IgnoreZerosThresholdRange.h
index b293e5b631f42df2f036b268c04dd9179f44434e..2b556e3b4d27e0380c97e5c0c471bb6755a8e7af 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/IgnoreZerosThresholdRange.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/IgnoreZerosThresholdRange.h
@@ -8,7 +8,8 @@
  @author Owen Arnold, Tessella plc
  @date 07/07/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -29,15 +30,11 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport IgnoreZerosThresholdRange : public ThresholdRange
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport IgnoreZerosThresholdRange : public ThresholdRange {
 
 public:
-
   IgnoreZerosThresholdRange(signal_t min, signal_t max);
 
   IgnoreZerosThresholdRange();
@@ -57,9 +54,8 @@ public:
   bool inRange(const signal_t &signal) override;
 
 private:
-
   signal_t m_min;
-  
+
   signal_t m_max;
 };
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/LoadVTK.h b/Vates/VatesAPI/inc/MantidVatesAPI/LoadVTK.h
index 5f5b1992dee0e30b9b2c83b7fc80f91c01ebb569..f55558da10b125e104ccefb4c007bf3b2e03919b 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/LoadVTK.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/LoadVTK.h
@@ -9,43 +9,50 @@
 class vtkUnsignedShortArray;
 class vtkDataSet;
 
-namespace Mantid
-{
-  namespace API
-  {
-    class Progress;
-  }
-  namespace VATES
-  {
-    class DLLExport LoadVTK : public API::IFileLoader<Kernel::FileDescriptor>
-    {
-    public:
-      const std::string name() const override;
-
-      int version() const override;
-
-      const std::string category() const override;
-
-      /// Summary of algorithms purpose
-      const std::string summary() const override {
-        return "Loads a legacy binary format VTK uniform structured image as "
-               "an MDWorkspace.";
-      }
-
-      /// Returns a confidence value that this algorithm can load a file
-      int confidence(Kernel::FileDescriptor &descriptor) const override;
-
-    private:
-
-      void execMDHisto(vtkUnsignedShortArray* signals, vtkUnsignedShortArray* errorsSQ, Mantid::Geometry::MDHistoDimension_sptr dimX, Mantid::Geometry::MDHistoDimension_sptr dimY, Mantid::Geometry::MDHistoDimension_sptr dimZ, Mantid::API::Progress& prog, const int64_t nPoints, const int64_t frequency);
+namespace Mantid {
+namespace API {
+class Progress;
+}
+namespace VATES {
+class DLLExport LoadVTK : public API::IFileLoader<Kernel::FileDescriptor> {
+public:
+  const std::string name() const override;
 
-      void execMDEvent(vtkDataSet* readDataset,vtkUnsignedShortArray* signals, vtkUnsignedShortArray* errorsSQ, Mantid::Geometry::MDHistoDimension_sptr dimX, Mantid::Geometry::MDHistoDimension_sptr dimY, Mantid::Geometry::MDHistoDimension_sptr dimZ, Mantid::API::Progress& prog, const int64_t nPoints, const int64_t frequency);
+  int version() const override;
 
-      void init() override;
+  const std::string category() const override;
 
-      void exec() override;
-    };
+  /// Summary of algorithms purpose
+  const std::string summary() const override {
+    return "Loads a legacy binary format VTK uniform structured image as "
+           "an MDWorkspace.";
   }
+
+  /// Returns a confidence value that this algorithm can load a file
+  int confidence(Kernel::FileDescriptor &descriptor) const override;
+
+private:
+  void execMDHisto(vtkUnsignedShortArray *signals,
+                   vtkUnsignedShortArray *errorsSQ,
+                   Mantid::Geometry::MDHistoDimension_sptr dimX,
+                   Mantid::Geometry::MDHistoDimension_sptr dimY,
+                   Mantid::Geometry::MDHistoDimension_sptr dimZ,
+                   Mantid::API::Progress &prog, const int64_t nPoints,
+                   const int64_t frequency);
+
+  void execMDEvent(vtkDataSet *readDataset, vtkUnsignedShortArray *signals,
+                   vtkUnsignedShortArray *errorsSQ,
+                   Mantid::Geometry::MDHistoDimension_sptr dimX,
+                   Mantid::Geometry::MDHistoDimension_sptr dimY,
+                   Mantid::Geometry::MDHistoDimension_sptr dimZ,
+                   Mantid::API::Progress &prog, const int64_t nPoints,
+                   const int64_t frequency);
+
+  void init() override;
+
+  void exec() override;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h
index 66ebd56117f6a3c3b8a9d747088b2796852110ae..dff9d3941cf6dbb98ec978bf5ac1a51c5a443119 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h
@@ -3,57 +3,54 @@
 
 #include "MantidVatesAPI/MDEWLoadingPresenter.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /** 
-    @class MDEWEventNexusLoadingPresenter
-    For loading conversion of MDEW workspaces into render-able vtk objects.
-    @author Owen Arnold, Tessella plc
-    @date 09/08/2011
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-
-    class MDLoadingView;
-    class DLLExport MDEWEventNexusLoadingPresenter : public MDEWLoadingPresenter
-    {
-    public:
-      MDEWEventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view,
-                                     const std::string fileName);
-      vtkSmartPointer<vtkDataSet>
-      execute(vtkDataSetFactory *factory,
-              ProgressAction &rebinningProgressUpdate,
-              ProgressAction &drawingProgressUpdate) override;
-      void executeLoadMetadata() override;
-      ~MDEWEventNexusLoadingPresenter() override;
-      bool canReadFile() const override;
-      std::string getWorkspaceTypeName() override;
-
-    private:
-      const std::string m_filename;
-      std::string m_wsTypeName;
-    };
-  }
+namespace Mantid {
+namespace VATES {
+/**
+@class MDEWEventNexusLoadingPresenter
+For loading conversion of MDEW workspaces into render-able vtk objects.
+@author Owen Arnold, Tessella plc
+@date 09/08/2011
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class MDLoadingView;
+class DLLExport MDEWEventNexusLoadingPresenter : public MDEWLoadingPresenter {
+public:
+  MDEWEventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view,
+                                 const std::string fileName);
+  vtkSmartPointer<vtkDataSet>
+  execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate,
+          ProgressAction &drawingProgressUpdate) override;
+  void executeLoadMetadata() override;
+  ~MDEWEventNexusLoadingPresenter() override;
+  bool canReadFile() const override;
+  std::string getWorkspaceTypeName() override;
+
+private:
+  const std::string m_filename;
+  std::string m_wsTypeName;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h
index db0077e1bc45c0b333aa39599f9fffa348b9d11d..0d124b1843cc4e7c093fcfe70997b8055ad5d626 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h
@@ -5,67 +5,65 @@
 #include <boost/scoped_ptr.hpp>
 
 class vtkDataSet;
-namespace Mantid
-{
-  namespace VATES
-  {
-    /** 
-    @class MDEWInMemoryLoadingPresenter
-    Presenter for loading MDEWs directly from the ADS, does not touch the disk.
-    @author Owen Arnold, Tessella plc
-    @date 08/09/2011
+namespace Mantid {
+namespace VATES {
+/**
+@class MDEWInMemoryLoadingPresenter
+Presenter for loading MDEWs directly from the ADS, does not touch the disk.
+@author Owen Arnold, Tessella plc
+@date 08/09/2011
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
 
-    class MDLoadingView;
-    class MetaDataExtractorUtils;
-    class WorkspaceProvider;
-    class vtkDataSetFactory;
+class MDLoadingView;
+class MetaDataExtractorUtils;
+class WorkspaceProvider;
+class vtkDataSetFactory;
 
-    class DLLExport MDEWInMemoryLoadingPresenter : public MDEWLoadingPresenter
-    {
-    public:
-      MDEWInMemoryLoadingPresenter(std::unique_ptr<MDLoadingView> view,
-                                   WorkspaceProvider *repository,
-                                   std::string wsName);
-      vtkSmartPointer<vtkDataSet>
-      execute(vtkDataSetFactory *factory,
-              ProgressAction &rebinningProgressUpdate,
-              ProgressAction &drawingProgressUpdate) override;
-      void executeLoadMetadata() override;
-      ~MDEWInMemoryLoadingPresenter() override;
-      bool canReadFile() const override;
-      std::string getWorkspaceTypeName() override;
-      int getSpecialCoordinates() override;
+class DLLExport MDEWInMemoryLoadingPresenter : public MDEWLoadingPresenter {
+public:
+  MDEWInMemoryLoadingPresenter(std::unique_ptr<MDLoadingView> view,
+                               WorkspaceProvider *repository,
+                               std::string wsName);
+  vtkSmartPointer<vtkDataSet>
+  execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate,
+          ProgressAction &drawingProgressUpdate) override;
+  void executeLoadMetadata() override;
+  ~MDEWInMemoryLoadingPresenter() override;
+  bool canReadFile() const override;
+  std::string getWorkspaceTypeName() override;
+  int getSpecialCoordinates() override;
 
-    private:
-      /// Repository for accessing workspaces. At this level, does not specify how or where from.
-      boost::scoped_ptr<WorkspaceProvider> m_repository;
-      /// The name of the workspace.
-      const std::string m_wsName;
-      std::string m_wsTypeName;
-      int m_specialCoords;
-    };
-  }
+private:
+  /// Repository for accessing workspaces. At this level, does not specify how
+  /// or where from.
+  boost::scoped_ptr<WorkspaceProvider> m_repository;
+  /// The name of the workspace.
+  const std::string m_wsName;
+  std::string m_wsTypeName;
+  int m_specialCoords;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h
index d39390393d5a7092bd081ac8307ac1e56e51634e..a3d55ab95b7b47f797559ec4ae2bbe957a68287f 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h
@@ -11,78 +11,80 @@
 
 #include <boost/scoped_ptr.hpp>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-    /** 
-    @class MDEWLoadingPresenter
-    Abstract presenter encapsulating common operations used by all MDEW type loading. Reduces template bloat.
-    @author Owen Arnold, Tessella plc
-    @date 16/08/2011
+/**
+@class MDEWLoadingPresenter
+Abstract presenter encapsulating common operations used by all MDEW type
+loading. Reduces template bloat.
+@author Owen Arnold, Tessella plc
+@date 16/08/2011
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class MDLoadingView;
-    class DLLExport MDEWLoadingPresenter : public MDLoadingPresenter
-    {
-    public:
-      MDEWLoadingPresenter(std::unique_ptr<MDLoadingView> view);
-      const std::string &getGeometryXML() const override;
-      bool hasTDimensionAvailable() const override;
-      std::vector<double> getTimeStepValues() const override;
-      std::string getTimeStepLabel() const override;
-      void setAxisLabels(vtkDataSet *visualDataSet) override;
-      ~MDEWLoadingPresenter() override;
-      const std::string &getInstrument() override;
-      double getMinValue() override;
-      double getMaxValue() override;
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MDLoadingView;
+class DLLExport MDEWLoadingPresenter : public MDLoadingPresenter {
+public:
+  MDEWLoadingPresenter(std::unique_ptr<MDLoadingView> view);
+  const std::string &getGeometryXML() const override;
+  bool hasTDimensionAvailable() const override;
+  std::vector<double> getTimeStepValues() const override;
+  std::string getTimeStepLabel() const override;
+  void setAxisLabels(vtkDataSet *visualDataSet) override;
+  ~MDEWLoadingPresenter() override;
+  const std::string &getInstrument() override;
+  double getMinValue() override;
+  double getMaxValue() override;
 
-    protected:
-      /*---------------------------------------------------------------------------
-      Common/shared operations and members for all MDEW file-type loading.
-      ---------------------------------------------------------------------------*/
-      std::unique_ptr<MDLoadingView> m_view;
-      Mantid::Geometry::MDGeometryBuilderXML<Mantid::Geometry::NoDimensionPolicy> xmlBuilder;
+protected:
+  /*---------------------------------------------------------------------------
+  Common/shared operations and members for all MDEW file-type loading.
+  ---------------------------------------------------------------------------*/
+  std::unique_ptr<MDLoadingView> m_view;
+  Mantid::Geometry::MDGeometryBuilderXML<Mantid::Geometry::NoDimensionPolicy>
+      xmlBuilder;
 
-      Mantid::Geometry::IMDDimension_sptr tDimension;
+  Mantid::Geometry::IMDDimension_sptr tDimension;
 
-      std::vector<std::string> axisLabels;
-      virtual void appendMetadata(vtkDataSet* visualDataSet, const std::string& wsName) ;
-      virtual void
-      extractMetadata(const Mantid::API::IMDEventWorkspace &eventWs);
-      virtual bool canLoadFileBasedOnExtension(const std::string& filename, const std::string& expectedExtension) const;
-      virtual bool shouldLoad();
-      bool m_isSetup;
-      double m_time;
-      size_t m_recursionDepth;
-      bool m_loadInMemory;
-      bool m_firstLoad;
+  std::vector<std::string> axisLabels;
+  virtual void appendMetadata(vtkDataSet *visualDataSet,
+                              const std::string &wsName);
+  virtual void extractMetadata(const Mantid::API::IMDEventWorkspace &eventWs);
+  virtual bool
+  canLoadFileBasedOnExtension(const std::string &filename,
+                              const std::string &expectedExtension) const;
+  virtual bool shouldLoad();
+  bool m_isSetup;
+  double m_time;
+  size_t m_recursionDepth;
+  bool m_loadInMemory;
+  bool m_firstLoad;
 
-      boost::scoped_ptr<MetadataJsonManager> m_metadataJsonManager;
-      boost::scoped_ptr<MetaDataExtractorUtils> m_metaDataExtractor;
-      boost::scoped_ptr<VatesConfigurations> m_vatesConfigurations;
-    };
-  }
+  boost::scoped_ptr<MetadataJsonManager> m_metadataJsonManager;
+  boost::scoped_ptr<MetaDataExtractorUtils> m_metaDataExtractor;
+  boost::scoped_ptr<VatesConfigurations> m_vatesConfigurations;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
index 87e6587a3c03840f73d8ea26541e22f1ab4b78f2..c02a2d7bd81d57f71fa57cb7aacbd75643f85334 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h
@@ -60,8 +60,6 @@ public:
   std::vector<int> getExtents();
 
 private:
-
-
   /// Repository for accessing workspaces. At this level, does not specify how
   /// or where from.
   boost::scoped_ptr<WorkspaceProvider> m_repository;
@@ -75,8 +73,6 @@ private:
   /// transpose.
   boost::shared_ptr<Mantid::API::IMDHistoWorkspace> m_cachedVisualHistoWs;
 };
-
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h
index 2b102f6c6d168d303e9ec82c64af7d7ded73135a..152047e52073e432a892571cf138a3fb674266ea 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h
@@ -57,9 +57,9 @@ public:
   double getMaxValue() override;
 
   /// Transpose a workspace to push integrated dimensions to the last
-  static void transposeWs(
-      Mantid::API::IMDHistoWorkspace_sptr  &inHistoWs,
-      Mantid::API::IMDHistoWorkspace_sptr  &outCachedHistoWs);
+  static void
+  transposeWs(Mantid::API::IMDHistoWorkspace_sptr &inHistoWs,
+              Mantid::API::IMDHistoWorkspace_sptr &outCachedHistoWs);
 
 protected:
   /*---------------------------------------------------------------------------
@@ -88,8 +88,6 @@ protected:
   boost::scoped_ptr<MetaDataExtractorUtils> m_metaDataExtractor;
   boost::scoped_ptr<VatesConfigurations> m_vatesConfigurations;
 };
-
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h
index df907db5723ad438f70990284664949e13343066..52f89d5de2268c5af542a62ef376d1392e3076f1 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h
@@ -4,17 +4,16 @@
 #include <vector>
 #include "MantidVatesAPI/MDHWLoadingPresenter.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 /**
     @class MDHWNexusLoadingPresenter
     For loading conversion of MDHW workspaces into render-able vtk objects.
 
     @date 08/04/2013
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
     This file is part of Mantid.
 
@@ -36,8 +35,7 @@ namespace VATES
  */
 
 class MDLoadingView;
-class DLLExport MDHWNexusLoadingPresenter : public MDHWLoadingPresenter
-{
+class DLLExport MDHWNexusLoadingPresenter : public MDHWLoadingPresenter {
 public:
   MDHWNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view,
                             const std::string fileName);
@@ -49,9 +47,10 @@ public:
   bool canReadFile() const override;
   std::string getWorkspaceTypeName() override;
   std::vector<int> getExtents();
+
 private:
   void loadWorkspace();
-  void loadWorkspace(ProgressAction& rebinningProgressUpdate);
+  void loadWorkspace(ProgressAction &rebinningProgressUpdate);
   const std::string m_filename;
   std::string m_wsTypeName;
   Mantid::API::IMDHistoWorkspace_sptr m_histoWs;
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h
index d3257d5d06d62292626db409e154fac3fdb5e6ab..eaf0abd5f3810b78ba81d1c80b8d8dcc7b352cfa 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h
@@ -11,96 +11,82 @@
 #include <string>
 #include <vector>
 
-
 namespace {
 Mantid::Kernel::Logger g_log("MDLoadingPresenter");
 }
 
 class vtkUnstructuredGrid;
-namespace Mantid
-{
-  namespace VATES
-  {
-    class ProgressAction;
-    class vtkDataSetFactory;
-     /** 
-    @class MDLoadingPresenter
-    Abstract presenters for loading conversion of MDEW workspaces into render-able vtk objects.
-    @author Owen Arnold, Tessella plc
-    @date 05/08/2011
+namespace Mantid {
+namespace VATES {
+class ProgressAction;
+class vtkDataSetFactory;
+/**
+@class MDLoadingPresenter
+Abstract presenters for loading conversion of MDEW workspaces into render-able
+vtk objects.
+@author Owen Arnold, Tessella plc
+@date 05/08/2011
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport MDLoadingPresenter
-    {
-      public:
-        virtual vtkSmartPointer<vtkDataSet>
-        execute(vtkDataSetFactory *factory,
-                ProgressAction &rebinningProgressUpdate,
-                ProgressAction &drawingProgressUpdate) = 0;
-        virtual void executeLoadMetadata() = 0;
-        virtual bool hasTDimensionAvailable() const = 0;
-        virtual std::vector<double> getTimeStepValues() const = 0;
-        virtual std::string getTimeStepLabel() const = 0;
-        virtual void setAxisLabels(vtkDataSet* visualDataSet) = 0;
-        virtual void setDefaultCOBandBoundaries(vtkDataSet* visualDataSet);
-        virtual void makeNonOrthogonal(vtkDataSet* visualDataSet,
-                                       std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider);
-        virtual bool canReadFile() const = 0;
-        virtual const std::string& getGeometryXML() const = 0;
-        virtual ~MDLoadingPresenter(){}
-        virtual std::string getWorkspaceTypeName()
-        {
-          return "NotSet";
-        }
-        virtual int getSpecialCoordinates()
-        {
-        return Kernel::None;
-        }
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport MDLoadingPresenter {
+public:
+  virtual vtkSmartPointer<vtkDataSet>
+  execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate,
+          ProgressAction &drawingProgressUpdate) = 0;
+  virtual void executeLoadMetadata() = 0;
+  virtual bool hasTDimensionAvailable() const = 0;
+  virtual std::vector<double> getTimeStepValues() const = 0;
+  virtual std::string getTimeStepLabel() const = 0;
+  virtual void setAxisLabels(vtkDataSet *visualDataSet) = 0;
+  virtual void setDefaultCOBandBoundaries(vtkDataSet *visualDataSet);
+  virtual void makeNonOrthogonal(
+      vtkDataSet *visualDataSet,
+      std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider);
+  virtual bool canReadFile() const = 0;
+  virtual const std::string &getGeometryXML() const = 0;
+  virtual ~MDLoadingPresenter() {}
+  virtual std::string getWorkspaceTypeName() { return "NotSet"; }
+  virtual int getSpecialCoordinates() { return Kernel::None; }
 
-        /**
-         * Gets the minimum value.
-         * @returns The minimum value of the dataset or 0.0
-         */
-        virtual double getMinValue()
-        {
-          return 0.0;
-        };
+  /**
+   * Gets the minimum value.
+   * @returns The minimum value of the dataset or 0.0
+   */
+  virtual double getMinValue() { return 0.0; };
 
-        /**
-         * Gets the maximum value.
-         * @returns The maximum value of the dataset or 0.0
-         */
-        virtual double getMaxValue()
-        {
-          return 0.0;	
-        };
+  /**
+   * Gets the maximum value.
+   * @returns The maximum value of the dataset or 0.0
+   */
+  virtual double getMaxValue() { return 0.0; };
 
-        /**
-         * Gets the instrument associated with the dataset.
-         * @returns The instrument associated with the dataset.
-         */
-        virtual const std::string& getInstrument() = 0;
-    };
-  }
+  /**
+   * Gets the instrument associated with the dataset.
+   * @returns The instrument associated with the dataset.
+   */
+  virtual const std::string &getInstrument() = 0;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingView.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingView.h
index be38f17eddc72dce5858cb38cab3584af230a0f2..40d54e3421024ae13d93d7327ba603473e8a1bfc 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingView.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingView.h
@@ -3,46 +3,44 @@
 
 #include "MantidKernel/System.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-
-     /** 
-    @class MDLoadingView
-    Abstract view for MDEW file loading and display.
-    @author Owen Arnold, Tessella plc
-    @date 05/08/2011
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport MDLoadingView
-    {
-    public:
-      virtual double getTime() const = 0;
-      virtual size_t getRecursionDepth() const = 0;
-      virtual bool getLoadInMemory() const = 0;
-      virtual ~MDLoadingView(){}
-    };
-  }
+namespace Mantid {
+namespace VATES {
+
+/**
+@class MDLoadingView
+Abstract view for MDEW file loading and display.
+@author Owen Arnold, Tessella plc
+@date 05/08/2011
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport MDLoadingView {
+public:
+  virtual double getTime() const = 0;
+  virtual size_t getRecursionDepth() const = 0;
+  virtual bool getLoadInMemory() const = 0;
+  virtual ~MDLoadingView() {}
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingViewAdapter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingViewAdapter.h
index f1ff13c19d9df7eff7f4317892911017497704aa..13757c5022abe629c036927920315a2b5d5d601c 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingViewAdapter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingViewAdapter.h
@@ -3,63 +3,57 @@
 
 #include "MantidVatesAPI/MDLoadingView.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-     /** 
-    @class MDLoadingViewAdapter
-    Templated type for wrapping non-MDLoadingView types. Adapter pattern.
-    @author Owen Arnold, Tessella plc
-    @date 07/09/2011
+/**
+@class MDLoadingViewAdapter
+Templated type for wrapping non-MDLoadingView types. Adapter pattern.
+@author Owen Arnold, Tessella plc
+@date 07/09/2011
 
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
-    This file is part of Mantid.
+This file is part of Mantid.
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    template<typename ViewType>
-    class DLLExport MDLoadingViewAdapter : public MDLoadingView
-    {
-    private:
-      ViewType* m_adaptee;
-    public:
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+template <typename ViewType>
+class DLLExport MDLoadingViewAdapter : public MDLoadingView {
+private:
+  ViewType *m_adaptee;
 
-      MDLoadingViewAdapter(ViewType* adaptee) : m_adaptee(adaptee)
-      {
-      }
+public:
+  MDLoadingViewAdapter(ViewType *adaptee) : m_adaptee(adaptee) {}
 
-      double getTime() const override { return m_adaptee->getTime(); }
+  double getTime() const override { return m_adaptee->getTime(); }
 
-      size_t getRecursionDepth() const override {
-        return m_adaptee->getRecursionDepth();
-      }
+  size_t getRecursionDepth() const override {
+    return m_adaptee->getRecursionDepth();
+  }
 
-      bool getLoadInMemory() const override {
-        return m_adaptee->getLoadInMemory();
-      }
+  bool getLoadInMemory() const override { return m_adaptee->getLoadInMemory(); }
 
-      ~MDLoadingViewAdapter() override {
-        //Do not delete adaptee.
-      }
-    };
+  ~MDLoadingViewAdapter() override {
+    // Do not delete adaptee.
   }
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MedianAndBelowThresholdRange.h b/Vates/VatesAPI/inc/MantidVatesAPI/MedianAndBelowThresholdRange.h
index 36f422627cb915fe609c15b806e22c0bb4658a23..4ce4577975aed87178deaedc7ffcaf1d480d3b62 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MedianAndBelowThresholdRange.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MedianAndBelowThresholdRange.h
@@ -5,12 +5,14 @@
 #include "MantidVatesAPI/ThresholdRange.h"
 #include "MantidAPI/IMDWorkspace.h"
 
-/** Set range selection to cut-out zeros and provide an upper limit equal to the median value in the workspace.
+/** Set range selection to cut-out zeros and provide an upper limit equal to the
+ median value in the workspace.
 
  @author Owen Arnold, Tessella plc
  @date 07/07/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -31,15 +33,11 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport MedianAndBelowThresholdRange : public ThresholdRange
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport MedianAndBelowThresholdRange : public ThresholdRange {
 
 public:
-
   MedianAndBelowThresholdRange();
 
   void calculate() override;
@@ -59,11 +57,11 @@ public:
   void setWorkspace(Mantid::API::Workspace_sptr workspace) override;
 
 private:
-  
-  MedianAndBelowThresholdRange(signal_t min, signal_t max, bool isCalculated, Mantid::API::IMDWorkspace_sptr m_workspace);
+  MedianAndBelowThresholdRange(signal_t min, signal_t max, bool isCalculated,
+                               Mantid::API::IMDWorkspace_sptr m_workspace);
 
   signal_t m_min;
-  
+
   signal_t m_max;
 
   bool m_isCalculated;
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MetaDataExtractorUtils.h b/Vates/VatesAPI/inc/MantidVatesAPI/MetaDataExtractorUtils.h
index bba948644f9314932db56b5a03013db62cc8b088..124d6deb36531b46bf4f21950e0f5f5ae4e85fd1 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MetaDataExtractorUtils.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MetaDataExtractorUtils.h
@@ -6,13 +6,14 @@
 #include <qwt_double_interval.h>
 #include <string>
 
-
 /**
- * Class with utility methdos to extract meta data information from a IMDWorkspace.
+ * Class with utility methdos to extract meta data information from a
+ *IMDWorkspace.
  *
  * @date November 21, 2014
  *
- * Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+ * Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+ *National Laboratory
  *
  * This file is part of Mantid.
  *
@@ -32,44 +33,40 @@
  * File change history is stored at: <https://github.com/mantidproject/mantid>
  * Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    class DLLExport MetaDataExtractorUtils
-    {
-      public:
+namespace Mantid {
+namespace VATES {
 
-        MetaDataExtractorUtils();
+class DLLExport MetaDataExtractorUtils {
+public:
+  MetaDataExtractorUtils();
 
-        ~MetaDataExtractorUtils();
+  ~MetaDataExtractorUtils();
 
-        /**
-          * Get the minimum, maximum pair from the workspace
-          * @param workspace A pointer to the workspace
-          * @returns A pair of minimum and maximum values.
-          */
-        QwtDoubleInterval getMinAndMax(Mantid::API::IMDWorkspace_sptr workspace);
+  /**
+    * Get the minimum, maximum pair from the workspace
+    * @param workspace A pointer to the workspace
+    * @returns A pair of minimum and maximum values.
+    */
+  QwtDoubleInterval getMinAndMax(Mantid::API::IMDWorkspace_sptr workspace);
 
-        /**
-          * Extracts the instrument from the workspace.
-          * @param workspace A pointer to a workspace.
-          * @returns The instrument. 
-          */
-        std::string extractInstrument(Mantid::API::IMDWorkspace_sptr workspace);
+  /**
+    * Extracts the instrument from the workspace.
+    * @param workspace A pointer to a workspace.
+    * @returns The instrument.
+    */
+  std::string extractInstrument(Mantid::API::IMDWorkspace_sptr workspace);
 
-      private:
-          /**
-          * Get the range of data values from an MD iterator
-          * @param it Iterator for a general MD workspace.
-          * @returns A maximum and minimum pair.
-          */
-        QwtDoubleInterval getRange(Mantid::API::IMDIterator* it);
+private:
+  /**
+  * Get the range of data values from an MD iterator
+  * @param it Iterator for a general MD workspace.
+  * @returns A maximum and minimum pair.
+  */
+  QwtDoubleInterval getRange(Mantid::API::IMDIterator *it);
 
-        double defaultMin;
-        double defaultMax;
-    };
-  }
+  double defaultMin;
+  double defaultMax;
+};
+}
 }
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MetadataJsonManager.h b/Vates/VatesAPI/inc/MantidVatesAPI/MetadataJsonManager.h
index c05919245c6b4ee74ccc99eed109c925c9e5cb27..baf689d60f8bc781ded8b7021afb8e0b60f4702c 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MetadataJsonManager.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MetadataJsonManager.h
@@ -5,67 +5,66 @@
 #include <json/json.h>
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-   /** Metadata container and handler to handle json data which is passed between filters and sources through
-       VTK field data
+namespace Mantid {
+namespace VATES {
+/** Metadata container and handler to handle json data which is passed between
+filters and sources through
+    VTK field data
 
-   @date 31/11/2014
+@date 31/11/2014
 
-   Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+National Laboratory
 
-   This file is part of Mantid.
+This file is part of Mantid.
 
-   Mantid is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 3 of the License, or
-   (at your option) any later version.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-   Mantid is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-   You should have received a copy of the GNU General Public License
-   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-   File change history is stored at: <https://github.com/mantidproject/mantid>
-   Code Documentation is available at: <http://doxygen.mantidproject.org>
-   */
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
 
-  class DLLExport MetadataJsonManager
-  {
-    public:
-      MetadataJsonManager();
+class DLLExport MetadataJsonManager {
+public:
+  MetadataJsonManager();
 
-      ~MetadataJsonManager();
+  ~MetadataJsonManager();
 
-      std::string getSerializedJson();
+  std::string getSerializedJson();
 
-      void readInSerializedJson(std::string serializedJson);
+  void readInSerializedJson(std::string serializedJson);
 
-      void setInstrument(std::string instrument);
-      std::string& getInstrument();
+  void setInstrument(std::string instrument);
+  std::string &getInstrument();
 
-      void setMinValue(double minValue);
-      double getMinValue();
+  void setMinValue(double minValue);
+  double getMinValue();
 
-      void setMaxValue(double maxValue);
-      double getMaxValue();
+  void setMaxValue(double maxValue);
+  double getMaxValue();
 
-      void setSpecialCoordinates(int specialCoordinates);
-      int getSpecialCoordinates();
+  void setSpecialCoordinates(int specialCoordinates);
+  int getSpecialCoordinates();
 
-    private:
-      Json::Value metadataContainer;
+private:
+  Json::Value metadataContainer;
 
-      std::string instrument;
-      double minValue;
-      double maxValue;
-      int specialCoordinates;
-  };
-  }
+  std::string instrument;
+  double minValue;
+  double maxValue;
+  int specialCoordinates;
+};
+}
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MetadataToFieldData.h b/Vates/VatesAPI/inc/MantidVatesAPI/MetadataToFieldData.h
index b5495246a7172f988825fb28f8369a419b2f87b6..000b95d025f7922fe12d8edaa64973fd750c6066 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/MetadataToFieldData.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/MetadataToFieldData.h
@@ -5,10 +5,8 @@
 #include <string>
 #include "MantidKernel/System.h"
 class vtkFieldData;
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
  * Functor converts metadata (in std::string) to vtkFieldData.
@@ -16,7 +14,8 @@ namespace VATES
  @author Owen Arnold, Tessella plc
  @date 09/02/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -37,16 +36,16 @@ namespace VATES
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class DLLExport MetadataToFieldData
-{
+class DLLExport MetadataToFieldData {
 public:
   /// Act as Functor.
-  void operator()(vtkFieldData* fieldData, std::string metaData, std::string id) const;
+  void operator()(vtkFieldData *fieldData, std::string metaData,
+                  std::string id) const;
 
   /// Explicit call to Functor execution.
-  void execute(vtkFieldData* fieldData, std::string metaData, std::string id) const;
+  void execute(vtkFieldData *fieldData, std::string metaData,
+               std::string id) const;
 };
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/NoThresholdRange.h b/Vates/VatesAPI/inc/MantidVatesAPI/NoThresholdRange.h
index 8ec095a09a1bf5e6df65d4adc45635f94b1f2d33..cd308bfaec09625f1280b5fb8fd1fb23e2ef3e27 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/NoThresholdRange.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/NoThresholdRange.h
@@ -8,7 +8,8 @@
  @author Owen Arnold, Tessella plc
  @date 07/07/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -29,15 +30,11 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport NoThresholdRange : public ThresholdRange
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport NoThresholdRange : public ThresholdRange {
 
 public:
-
   NoThresholdRange();
 
   void calculate() override;
@@ -55,11 +52,10 @@ public:
   bool inRange(const signal_t &signal) override;
 
 private:
-  
   NoThresholdRange(signal_t min, signal_t max);
 
   signal_t m_min;
-  
+
   signal_t m_max;
 };
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h b/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
index fad1f81448c8cd58c403746f3094aa718cda05a3..49875440b54bc23cf89eb32dbf59f3f156f5fdd7 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/PeaksPresenterVsi.h
@@ -20,9 +20,11 @@ public:
   virtual void updateViewFrustum(ViewFrustum_const_sptr frustum) = 0;
   virtual std::string getFrame() const = 0;
   virtual std::string getPeaksWorkspaceName() const = 0;
-  virtual void getPeaksInfo(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
-                            int row, Mantid::Kernel::V3D &position,
-                            double &radius, Mantid::Kernel::SpecialCoordinateSystem specialCoordinateSystem) const = 0;
+  virtual void
+  getPeaksInfo(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace, int row,
+               Mantid::Kernel::V3D &position, double &radius,
+               Mantid::Kernel::SpecialCoordinateSystem specialCoordinateSystem)
+      const = 0;
   virtual void sortPeaksWorkspace(const std::string &byColumnName,
                                   const bool ascending) = 0;
 };
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/PrecompiledHeader.h b/Vates/VatesAPI/inc/MantidVatesAPI/PrecompiledHeader.h
index 6a34363563bf2dc02936b505b3d7df7bfb5db80e..e6e30e8a63898e95babfa03302a90bc4d37280d2 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/PrecompiledHeader.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/PrecompiledHeader.h
@@ -14,5 +14,4 @@
 #include <set>
 #include <string>
 
-
-#endif //MANTID_VATES_PRECOMPILEDHEADER_H_
\ No newline at end of file
+#endif // MANTID_VATES_PRECOMPILEDHEADER_H_
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/PresenterFactories.h b/Vates/VatesAPI/inc/MantidVatesAPI/PresenterFactories.h
index 75dd4b924d2ac165ecab6aecbfe81b0691e3291a..bce7458c72757b22e6dbdf380fe6ec2ee2dae2be 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/PresenterFactories.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/PresenterFactories.h
@@ -46,7 +46,6 @@ public:
                                                   getWorkspaceName(workspace));
   }
 };
-
 }
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/ProgressAction.h b/Vates/VatesAPI/inc/MantidVatesAPI/ProgressAction.h
index 126f42d17149e6f84125a748fbd05f0aa9c06e67..9726d123b5eac9da16b776d310ead796c92fd327 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/ProgressAction.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/ProgressAction.h
@@ -7,17 +7,17 @@
 #include <Poco/Notification.h>
 #include <Poco/NObserver.h>
 #include <MantidAPI/Algorithm.h>
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-/** Abstract update event type. Allows notification of visualisation top layer/viewer about events without specifying a concrete interactor.
+/** Abstract update event type. Allows notification of visualisation top
+ layer/viewer about events without specifying a concrete interactor.
 
  @author Owen Arnold, Tessella plc
  @date 10/02/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -38,19 +38,17 @@ namespace VATES
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class DLLExport ProgressAction
-{
+class DLLExport ProgressAction {
 
 public:
-
   /// Constructor
   ProgressAction();
 
   /// Handle event updates.
   virtual void eventRaised(double progress) = 0;
 
-  void handler(const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification>& pNf);
-
+  void handler(
+      const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification> &pNf);
 };
 }
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h
index 26c38f3b64d6879cdab110b6424204f570a3ea43..ead0a17c1e0450cce3387764c1c369d1779869d5 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h
@@ -3,60 +3,54 @@
 
 #include "MantidVatesAPI/MDEWLoadingPresenter.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /** 
-    @class SQWLoadingPresenter
-    MVP loading presenter for .*sqw file types.
-    @author Owen Arnold, Tessella plc
-    @date 16/08/2011
-
-    Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class MDLoadingView;
-    class DLLExport SQWLoadingPresenter : public MDEWLoadingPresenter
-    {
-    public:
-      SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view,
-                          const std::string fileName);
-      vtkSmartPointer<vtkDataSet>
-      execute(vtkDataSetFactory *factory,
-              ProgressAction &rebinningProgressUpdate,
-              ProgressAction &drawingProgressUpdate) override;
-      void
-      extractMetadata(const Mantid::API::IMDEventWorkspace &eventWs) override;
-      void executeLoadMetadata() override;
-      ~SQWLoadingPresenter() override;
-      bool canReadFile() const override;
-      std::string getWorkspaceTypeName() override;
-
-    private:
-      const std::string m_filename;
-      std::string m_wsTypeName;
-    };
-
-   
-  }
+namespace Mantid {
+namespace VATES {
+/**
+@class SQWLoadingPresenter
+MVP loading presenter for .*sqw file types.
+@author Owen Arnold, Tessella plc
+@date 16/08/2011
+
+Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class MDLoadingView;
+class DLLExport SQWLoadingPresenter : public MDEWLoadingPresenter {
+public:
+  SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view,
+                      const std::string fileName);
+  vtkSmartPointer<vtkDataSet>
+  execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate,
+          ProgressAction &drawingProgressUpdate) override;
+  void extractMetadata(const Mantid::API::IMDEventWorkspace &eventWs) override;
+  void executeLoadMetadata() override;
+  ~SQWLoadingPresenter() override;
+  bool canReadFile() const override;
+  std::string getWorkspaceTypeName() override;
+
+private:
+  const std::string m_filename;
+  std::string m_wsTypeName;
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/ThresholdRange.h b/Vates/VatesAPI/inc/MantidVatesAPI/ThresholdRange.h
index ea57ba5dcd7142a6d34da27f7e0db7405d7f0539..9729ca81df2d5e733aa7c9383d62de6e5bbd3e78 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/ThresholdRange.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/ThresholdRange.h
@@ -6,12 +6,14 @@
 #include "MantidGeometry/MDGeometry/MDTypes.h"
 #include "MantidAPI/Workspace_fwd.h"
 
-/** Abstract type promises to supply a minimum and maximum set of threshold range values.
+/** Abstract type promises to supply a minimum and maximum set of threshold
+ range values.
 
  @author Owen Arnold, Tessella plc
  @date 30/06/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -32,15 +34,11 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport ThresholdRange 
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport ThresholdRange {
 
 public:
-  
   /// Calculate the threshold range.
   virtual void calculate() = 0;
 
@@ -54,20 +52,16 @@ public:
   virtual signal_t getMaximum() const = 0;
 
   /// Virtual constructor method.
-  virtual ThresholdRange* clone() const = 0;
+  virtual ThresholdRange *clone() const = 0;
 
   /// Determine wheter the given value is within the range.
-  virtual bool inRange(const signal_t& signal) = 0;
+  virtual bool inRange(const signal_t &signal) = 0;
 
   /// Destructor
-  virtual ~ThresholdRange()
-  {
-  }
+  virtual ~ThresholdRange() {}
 
   /// Interface allows the threshold range to accept a workspace.
-  virtual void setWorkspace(Mantid::API::Workspace_sptr)
-  {
-  }
+  virtual void setWorkspace(Mantid::API::Workspace_sptr) {}
 };
 
 /// ThresholdRange as a scoped pointer.
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/TimeStepToTimeStep.h b/Vates/VatesAPI/inc/MantidVatesAPI/TimeStepToTimeStep.h
index 2af2e970f09cd4f08ee47793708b50109de59f5a..b69c3afc13353e946a9542596552cc9dc652cf5e 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/TimeStepToTimeStep.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/TimeStepToTimeStep.h
@@ -4,12 +4,14 @@
 #include "MantidKernel/System.h"
 #include <functional>
 
-/** Maps from a timestep to a timestep. Provides the static compile time polymorphism required by vtkDataSetFactory type classes.
+/** Maps from a timestep to a timestep. Provides the static compile time
+ polymorphism required by vtkDataSetFactory type classes.
 
  @author Owen Arnold, Tessella plc
  @date 14/03/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -30,28 +32,24 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport TimeStepToTimeStep: std::unary_function<int, int>
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport TimeStepToTimeStep : std::unary_function<int, int> {
 private:
   double m_timeRange;
 
   size_t m_nIntervalSteps;
-  
+
   TimeStepToTimeStep(double timeMin, double timeMax, size_t intervalStep);
 
 public:
-
   /// Constructional method.
-  static TimeStepToTimeStep construct(double timeMin, double timeMax, size_t nIntervalSteps);
+  static TimeStepToTimeStep construct(double timeMin, double timeMax,
+                                      size_t nIntervalSteps);
 
   TimeStepToTimeStep();
 
   size_t operator()(double timeStep) const;
-
 };
 }
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/TimeToTimeStep.h b/Vates/VatesAPI/inc/MantidVatesAPI/TimeToTimeStep.h
index 6058e06963ea0258818a433283ecb16bedc2a2d7..83a13215c806c0f546988768448b9af692973729 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/TimeToTimeStep.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/TimeToTimeStep.h
@@ -4,13 +4,16 @@
 #include "MantidKernel/System.h"
 #include <functional>
 
-/** Unary operation applying visualisation platforms specific conversion from a time to a timestep understood by underlying mantid code, where time is treated as an index
+/** Unary operation applying visualisation platforms specific conversion from a
+ time to a timestep understood by underlying mantid code, where time is treated
+ as an index
  * in a single dimensional array. See MDWorkspace/MDImage.
 
  @author Owen Arnold, Tessella plc
  @date 14/03/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -31,12 +34,9 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport TimeToTimeStep: std::unary_function<double, int>
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport TimeToTimeStep : std::unary_function<double, int> {
 private:
   // Minimum time.
   double m_timeMin;
@@ -50,19 +50,18 @@ private:
   double m_fraction;
   size_t m_nIntervalSteps;
   bool m_runnable;
-  
+
   /// Constructor only accessible via 'construct' static member function.
   TimeToTimeStep(double timeMin, double timeMax, size_t nIntervalSteps);
 
 public:
-
   /// Constructional method.
-  static TimeToTimeStep construct(double timeMin, double timeMax, size_t nIntervalSteps);
+  static TimeToTimeStep construct(double timeMin, double timeMax,
+                                  size_t nIntervalSteps);
 
   TimeToTimeStep();
 
   size_t operator()(double time) const;
-
 };
 }
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/UserDefinedThresholdRange.h b/Vates/VatesAPI/inc/MantidVatesAPI/UserDefinedThresholdRange.h
index f2b9de8eb725fc9390904f78645a8b54c7147388..76a4b70cbf33fc4c8d956c4be1de763602baa113 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/UserDefinedThresholdRange.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/UserDefinedThresholdRange.h
@@ -8,7 +8,8 @@
  @author Owen Arnold, Tessella plc
  @date 30/06/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -29,15 +30,11 @@
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-namespace Mantid
-{
-namespace VATES
-{
-class DLLExport UserDefinedThresholdRange : public ThresholdRange
-{
+namespace Mantid {
+namespace VATES {
+class DLLExport UserDefinedThresholdRange : public ThresholdRange {
 
 public:
-
   UserDefinedThresholdRange(signal_t min, signal_t max);
 
   void calculate() override;
@@ -55,9 +52,8 @@ public:
   bool inRange(const signal_t &signal) override;
 
 private:
-
   const signal_t m_min;
-  
+
   const signal_t m_max;
 };
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/VatesConfigurations.h b/Vates/VatesAPI/inc/MantidVatesAPI/VatesConfigurations.h
index f6d9f32e33feec5154accda6023a4c9e7dcebb18..6918483c7ae436f3abf391b19f031ab77ab9b1dd 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/VatesConfigurations.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/VatesConfigurations.h
@@ -1,58 +1,56 @@
 #ifndef VATES_CONFIGURATION_H
 #define VATES_CONFIGURATION_H
 
-
 #include "MantidKernel/System.h"
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-	 /** Metadata container and handler to handle json data which is passed between filters and sources through 
-	     VTK field data
+namespace Mantid {
+namespace VATES {
+/** Metadata container and handler to handle json data which is passed between
+filters and sources through
+    VTK field data
+
+@date 1/12/2014
 
-	 @date 1/12/2014
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+National Laboratory
 
-	 Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+This file is part of Mantid.
 
-	 This file is part of Mantid.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
-	 Mantid is free software; you can redistribute it and/or modify
-	 it under the terms of the GNU General Public License as published by
-	 the Free Software Foundation; either version 3 of the License, or
-	 (at your option) any later version.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
-	 Mantid is distributed in the hope that it will be useful,
-	 but WITHOUT ANY WARRANTY; without even the implied warranty of
-	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	 GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-	 You should have received a copy of the GNU General Public License
-	 along with this program.  If not, see <http://www.gnu.org/licenses/>.
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
 
-	 File change history is stored at: <https://github.com/mantidproject/mantid>
-	 Code Documentation is available at: <http://doxygen.mantidproject.org>
-	 */
-	  
-	class DLLExport VatesConfigurations
-	{
-		public:
-      VatesConfigurations();
+class DLLExport VatesConfigurations {
+public:
+  VatesConfigurations();
 
-      ~VatesConfigurations();
+  ~VatesConfigurations();
 
-      int getMaxRecursionDepth();
+  int getMaxRecursionDepth();
 
-      std::string getMetadataIdJson();
+  std::string getMetadataIdJson();
 
-    private:
-      // The maximum recursion depth when going through the box tree.
-      const int maxRecursionDepth;
+private:
+  // The maximum recursion depth when going through the box tree.
+  const int maxRecursionDepth;
 
-      // Meta data field flag 
-      const std::string metaDataId;
-	};
-  }
+  // Meta data field flag
+  const std::string metaDataId;
+};
+}
 }
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h b/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
index d4e4ec4593907df33709ad5db8a59586f7b105cd..c23f4c6d099679e6d4a361f829435e598bd65618 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/VatesKnowledgeSerializer.h
@@ -4,35 +4,36 @@
 #include <boost/shared_ptr.hpp>
 #include <string>
 
-namespace Mantid
-{
+namespace Mantid {
 /// Forward Declarations;
-namespace Geometry
-{
+namespace Geometry {
 class MDImplicitFunction;
 }
-namespace API
-{
+namespace API {
 class IMDWorkspace;
 }
 
-namespace VATES
-{
+namespace VATES {
 
-//The workspace location may or may not be required. This type defines the options.
-enum LocationPolicy{LocationMandatory, LocationNotRequired};
+// The workspace location may or may not be required. This type defines the
+// options.
+enum LocationPolicy { LocationMandatory, LocationNotRequired };
 
 /**
 
- This type assists with the generation of well-formed xml meeting the xsd scehema. The individual components utilised here may not be able to form well-formed
+ This type assists with the generation of well-formed xml meeting the xsd
+ scehema. The individual components utilised here may not be able to form
+ well-formed
  xml in their own right and therefore do not have a toXMLString method.
 
- This implementation is based on a builder pattern using the create mechanism for xml string generation.
+ This implementation is based on a builder pattern using the create mechanism
+ for xml string generation.
 
  @author Owen Arnold, Tessella plc
  @date 14/12/2010
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -52,25 +53,25 @@ enum LocationPolicy{LocationMandatory, LocationNotRequired};
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org> */
 
-class DLLExport VatesKnowledgeSerializer
-{
+class DLLExport VatesKnowledgeSerializer {
 
 private:
-
-  boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction>  m_spFunction;
+  boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> m_spFunction;
   std::string m_wsLocationXML;
   std::string m_wsNameXML;
   std::string m_wsName;
   std::string m_geomXML;
-public:
 
+public:
   VatesKnowledgeSerializer();
 
   /// Set the implicit function to use called.
-  void setImplicitFunction(boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> spFunction);
+  void setImplicitFunction(
+      boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> spFunction);
 
   /// Set the workspace name to apply.
-  void setWorkspace(boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace);
+  void
+  setWorkspace(boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace);
 
   /// Set the workspace name to apply.
   void setWorkspaceName(std::string wsName);
@@ -82,10 +83,10 @@ public:
   std::string createXMLString() const;
 
   /// Get the underlying workspace name.
-  const std::string& getWorkspaceName() const;
+  const std::string &getWorkspaceName() const;
 
   /// Get the underlying workspace geometry.
-  const std::string& getWorkspaceGeometry() const;
+  const std::string &getWorkspaceGeometry() const;
 
   /// Determine if function information is available/set.
   bool hasFunctionInfo() const;
@@ -93,10 +94,6 @@ public:
   /// Determine if gemetry information is available/set.
   bool hasGeometryInfo() const;
 };
-
-
-
-
 }
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/VatesXMLDefinitions.h b/Vates/VatesAPI/inc/MantidVatesAPI/VatesXMLDefinitions.h
index acc7112d1dc67fb33a49c3af4b8df81cae816ddb..aa36db41e2cbfb296e78c152d218e19609960d1e 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/VatesXMLDefinitions.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/VatesXMLDefinitions.h
@@ -3,20 +3,21 @@
 
 #include <string>
 #include "MantidKernel/System.h"
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
 
- This type contains definitions that will be found in the xml schema of VATES, but must be used in
- code as part of the peristance/fetching routines. This file provides a single location for definitions to aid future maintenance.
+ This type contains definitions that will be found in the xml schema of VATES,
+ but must be used in
+ code as part of the peristance/fetching routines. This file provides a single
+ location for definitions to aid future maintenance.
 
  @author Owen Arnold, Tessella plc
  @date 16/12/2010
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -36,10 +37,10 @@ namespace VATES
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org> */
 
-//TODO: these definitions may be more appropriate in API/Geometry where they can also be used as part of the parsing.
+// TODO: these definitions may be more appropriate in API/Geometry where they
+// can also be used as part of the parsing.
 
-class DLLExport XMLDefinitions
-{
+class DLLExport XMLDefinitions {
 public:
   ////XML schema tag definitions for generating xml.
   // static const std::string workspaceNameXMLTagStart()
@@ -107,38 +108,20 @@ public:
   // {
   //   return "RefDimensionId";
   // }
-   ///An id for recognising specific vtkFieldData objects on inbound and outbound datasets.
-   static const std::string metaDataId()
-   {
-     return "VATES_Metadata";
-   }
-   static const std::string signalName()
-   {
-     return "signal";
-   }
-   static const std::string geometryNodeName()
-   {
-     return "geometryNodeName";
-   }
-   static const std::string functionNodeName()
-   {
-     return "functionNodeName";
-   }
-   static const std::string geometryOperatorInfo()
-   {
-     return "geometryOperatorInfo";
-   }
-   static const std::string functionOperatorInfo()
-   {
-     return "functionOperatorInfo";
-   }
-   static const std::string RebinnedWSName()
-   {
-     return "RebinnedWS";
-   }
-
+  /// An id for recognising specific vtkFieldData objects on inbound and
+  /// outbound datasets.
+  static const std::string metaDataId() { return "VATES_Metadata"; }
+  static const std::string signalName() { return "signal"; }
+  static const std::string geometryNodeName() { return "geometryNodeName"; }
+  static const std::string functionNodeName() { return "functionNodeName"; }
+  static const std::string geometryOperatorInfo() {
+    return "geometryOperatorInfo";
+  }
+  static const std::string functionOperatorInfo() {
+    return "functionOperatorInfo";
+  }
+  static const std::string RebinnedWSName() { return "RebinnedWS"; }
 };
-
 }
 }
-#endif 
+#endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h b/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
index 24cf149df1932e3e4e4916374db2d586fc132b82..682fe0c221f6d7df446f0f76090b61aaa6c65175 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/ViewFrustum.h
@@ -9,41 +9,42 @@
 #include <vector>
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-namespace VATES
-{
-
-enum PLANELOCATION{LEFTPLANE, RIGHTPLANE, BOTTOMPLANE, TOPPLANE, FARPLANE, NEARPLANE};
-
-template<PLANELOCATION I, typename T>
-class DLLExport FrustumPlane
-{
-  public:
-    explicit FrustumPlane(const T& paramA, const T& paramB, const T& paramC, const T& paramD) : m_paramA(paramA), 
-                                                                                                m_paramB(paramB),
-                                                                                                m_paramC(paramC), 
-                                                                                                m_paramD(paramD){}
-    FrustumPlane(const FrustumPlane<I, T>& other) : m_paramA(other.m_paramA),
-                                                    m_paramB(other.m_paramB),
-                                                    m_paramC(other.m_paramC),
-                                                    m_paramD(other.m_paramD){}
-    T A() {return m_paramA;}
-    T B() {return m_paramB;}
-    T C() {return m_paramC;}
-    T D() {return m_paramD;}
-
-    std::vector<T> getPlaneCoefficients()
-    {
-      return {m_paramA, m_paramB, m_paramC, m_paramD};
-    }
+namespace Mantid {
+namespace VATES {
+
+enum PLANELOCATION {
+  LEFTPLANE,
+  RIGHTPLANE,
+  BOTTOMPLANE,
+  TOPPLANE,
+  FARPLANE,
+  NEARPLANE
+};
+
+template <PLANELOCATION I, typename T> class DLLExport FrustumPlane {
+public:
+  explicit FrustumPlane(const T &paramA, const T &paramB, const T &paramC,
+                        const T &paramD)
+      : m_paramA(paramA), m_paramB(paramB), m_paramC(paramC), m_paramD(paramD) {
+  }
+  FrustumPlane(const FrustumPlane<I, T> &other)
+      : m_paramA(other.m_paramA), m_paramB(other.m_paramB),
+        m_paramC(other.m_paramC), m_paramD(other.m_paramD) {}
+  T A() { return m_paramA; }
+  T B() { return m_paramB; }
+  T C() { return m_paramC; }
+  T D() { return m_paramD; }
+
+  std::vector<T> getPlaneCoefficients() {
+    return {m_paramA, m_paramB, m_paramC, m_paramD};
+  }
 
 private:
-    T m_paramA;
-    T m_paramB;
-    T m_paramC;
-    T m_paramD;
-    enum{m_location = I};
+  T m_paramA;
+  T m_paramB;
+  T m_paramC;
+  T m_paramD;
+  enum { m_location = I };
 };
 
 typedef FrustumPlane<LEFTPLANE, double> LeftPlane;
@@ -53,109 +54,111 @@ typedef FrustumPlane<TOPPLANE, double> TopPlane;
 typedef FrustumPlane<FARPLANE, double> FarPlane;
 typedef FrustumPlane<NEARPLANE, double> NearPlane;
 
+class DLLExport ViewFrustum {
+public:
+  ViewFrustum(const LeftPlane leftPlane, const RightPlane rightPlane,
+              const BottomPlane bottomPlane, const TopPlane topPlane,
+              const FarPlane farPlane, const NearPlane nearPlane);
+  ViewFrustum(const ViewFrustum &other);
+  ~ViewFrustum();
+  ViewFrustum &operator=(const ViewFrustum &other);
+  std::vector<std::pair<double, double>> toExtents() const;
+  std::string toExtentsAsString() const;
 
-class DLLExport ViewFrustum
-{
-  public:
-    ViewFrustum(const LeftPlane leftPlane,
-                const RightPlane rightPlane,
-                const BottomPlane bottomPlane,
-                const TopPlane topPlane,
-                const FarPlane farPlane, 
-                const NearPlane nearPlane);
-    ViewFrustum(const ViewFrustum& other);
-    ~ViewFrustum();
-    ViewFrustum& operator=(const ViewFrustum& other);
-    std::vector<std::pair<double, double>> toExtents() const;
-    std::string toExtentsAsString() const;
-
-  private:
-    mutable LeftPlane m_leftPlane;
-    mutable RightPlane m_rightPlane;
-    mutable TopPlane m_topPlane;
-    mutable BottomPlane m_bottomPlane;
-    mutable FarPlane m_farPlane;
-    mutable NearPlane m_nearPlane;
-
-    template<PLANELOCATION p1, PLANELOCATION p2, PLANELOCATION p3, typename T>
-    std::vector<T> getIntersectionPointThreePlanes(FrustumPlane<p1, T> plane1, FrustumPlane<p2, T> plane2, FrustumPlane<p3, T> plane3) const;
-
-    template<typename T>
-    void initializeMatrix(Mantid::Kernel::Matrix<T>& matrix, std::vector<T> vec0, std::vector<T> vec1, std::vector<T> vec2) const;
+private:
+  mutable LeftPlane m_leftPlane;
+  mutable RightPlane m_rightPlane;
+  mutable TopPlane m_topPlane;
+  mutable BottomPlane m_bottomPlane;
+  mutable FarPlane m_farPlane;
+  mutable NearPlane m_nearPlane;
+
+  template <PLANELOCATION p1, PLANELOCATION p2, PLANELOCATION p3, typename T>
+  std::vector<T>
+  getIntersectionPointThreePlanes(FrustumPlane<p1, T> plane1,
+                                  FrustumPlane<p2, T> plane2,
+                                  FrustumPlane<p3, T> plane3) const;
+
+  template <typename T>
+  void initializeMatrix(Mantid::Kernel::Matrix<T> &matrix, std::vector<T> vec0,
+                        std::vector<T> vec1, std::vector<T> vec2) const;
 };
-  /**
-   * Get the intersection point of three planes using Cramer's rule.
-   * @param plane1 The first frustum plane
-   * @param plane2 The second frustum plane
-   * @param plane3 The third frustum plane
-   */
-  template<PLANELOCATION p1, PLANELOCATION p2, PLANELOCATION p3, typename T>
-  std::vector<T> ViewFrustum::getIntersectionPointThreePlanes(FrustumPlane<p1, T> plane1, FrustumPlane<p2, T> plane2, FrustumPlane<p3, T> plane3) const
-  {
-    const size_t dim = 3;
-
-    std::vector<T> aVec{plane1.A(), plane2.A(), plane3.A()};
-
-    std::vector<T> bVec{plane1.B(), plane2.B(), plane3.B()};
-
-    std::vector<T> cVec{plane1.C(), plane2.C(), plane3.C()};
-
-    // The input is Ax+By+Cz+D=0 but we need the form Ax+By+Cz=D
-    const T factor = -1;
-    std::vector<T> dVec{factor * plane1.D(), factor * plane2.D(),
-                        factor * plane3.D()};
-
-    // Get the different matrix permutations
-    Mantid::Kernel::Matrix<T> abcMatrix(dim, dim);
-    Mantid::Kernel::Matrix<T>  dbcMatrix(dim, dim);
-    Mantid::Kernel::Matrix<T>  adcMatrix(dim, dim);
-    Mantid::Kernel::Matrix<T>  abdMatrix(dim, dim);
-    
-    initializeMatrix<T>(abcMatrix, aVec, bVec, cVec);
-    T abcDet = abcMatrix.determinant();
-    if (abcDet == 0)
-    {
-      throw std::runtime_error("Determinant for view frustum is 0.");
-    }
-
-    initializeMatrix<T>(dbcMatrix, dVec, bVec, cVec);
-    initializeMatrix<T>(adcMatrix, aVec, dVec, cVec);
-    initializeMatrix<T>(abdMatrix, aVec, bVec, dVec);
-
-    T dbcDet = dbcMatrix.determinant();
-    T adcDet = adcMatrix.determinant();
-    T abdDet = abdMatrix.determinant();
-
-    std::vector<T> intersection{dbcDet / abcDet, adcDet / abcDet,
-                                abdDet / abcDet};
-
-    return intersection;
+/**
+ * Get the intersection point of three planes using Cramer's rule.
+ * @param plane1 The first frustum plane
+ * @param plane2 The second frustum plane
+ * @param plane3 The third frustum plane
+ */
+template <PLANELOCATION p1, PLANELOCATION p2, PLANELOCATION p3, typename T>
+std::vector<T>
+ViewFrustum::getIntersectionPointThreePlanes(FrustumPlane<p1, T> plane1,
+                                             FrustumPlane<p2, T> plane2,
+                                             FrustumPlane<p3, T> plane3) const {
+  const size_t dim = 3;
+
+  std::vector<T> aVec{plane1.A(), plane2.A(), plane3.A()};
+
+  std::vector<T> bVec{plane1.B(), plane2.B(), plane3.B()};
+
+  std::vector<T> cVec{plane1.C(), plane2.C(), plane3.C()};
+
+  // The input is Ax+By+Cz+D=0 but we need the form Ax+By+Cz=D
+  const T factor = -1;
+  std::vector<T> dVec{factor * plane1.D(), factor * plane2.D(),
+                      factor * plane3.D()};
+
+  // Get the different matrix permutations
+  Mantid::Kernel::Matrix<T> abcMatrix(dim, dim);
+  Mantid::Kernel::Matrix<T> dbcMatrix(dim, dim);
+  Mantid::Kernel::Matrix<T> adcMatrix(dim, dim);
+  Mantid::Kernel::Matrix<T> abdMatrix(dim, dim);
+
+  initializeMatrix<T>(abcMatrix, aVec, bVec, cVec);
+  T abcDet = abcMatrix.determinant();
+  if (abcDet == 0) {
+    throw std::runtime_error("Determinant for view frustum is 0.");
   }
 
-  /**
-   * Initialize the matrix with the plane coefficient vectors.
-   * @param matrix The matrix to initialze.
-   * @param vec0 The first vector.
-   * @param vec1 The second vector.
-   * @param vec2 The third vector.
-   */
-  template<typename T>
-  void ViewFrustum::initializeMatrix(Mantid::Kernel::Matrix<T>& matrix, std::vector<T> vec0, std::vector<T> vec1, std::vector<T> vec2) const
-  {
-    std::pair<size_t, size_t> size = matrix.size();
-
-    if (size.first != 3 || size.second != 3)
-    {
-      throw std::runtime_error("Matrix for view frustum calculation has the wrong dimensionality.");
-    }
-    matrix.setColumn(0, vec0);
-    matrix.setColumn(1, vec1);
-    matrix.setColumn(2, vec2);
+  initializeMatrix<T>(dbcMatrix, dVec, bVec, cVec);
+  initializeMatrix<T>(adcMatrix, aVec, dVec, cVec);
+  initializeMatrix<T>(abdMatrix, aVec, bVec, dVec);
+
+  T dbcDet = dbcMatrix.determinant();
+  T adcDet = adcMatrix.determinant();
+  T abdDet = abdMatrix.determinant();
+
+  std::vector<T> intersection{dbcDet / abcDet, adcDet / abcDet,
+                              abdDet / abcDet};
+
+  return intersection;
+}
+
+/**
+ * Initialize the matrix with the plane coefficient vectors.
+ * @param matrix The matrix to initialze.
+ * @param vec0 The first vector.
+ * @param vec1 The second vector.
+ * @param vec2 The third vector.
+ */
+template <typename T>
+void ViewFrustum::initializeMatrix(Mantid::Kernel::Matrix<T> &matrix,
+                                   std::vector<T> vec0, std::vector<T> vec1,
+                                   std::vector<T> vec2) const {
+  std::pair<size_t, size_t> size = matrix.size();
+
+  if (size.first != 3 || size.second != 3) {
+    throw std::runtime_error(
+        "Matrix for view frustum calculation has the wrong dimensionality.");
   }
+  matrix.setColumn(0, vec0);
+  matrix.setColumn(1, vec1);
+  matrix.setColumn(2, vec2);
+}
 
 /// shared pointer to the view frustum
 typedef boost::shared_ptr<Mantid::VATES::ViewFrustum> ViewFrustum_sptr;
-typedef boost::shared_ptr<const Mantid::VATES::ViewFrustum> ViewFrustum_const_sptr;
+typedef boost::shared_ptr<const Mantid::VATES::ViewFrustum>
+    ViewFrustum_const_sptr;
 }
 }
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/WorkspaceProvider.h b/Vates/VatesAPI/inc/MantidVatesAPI/WorkspaceProvider.h
index 0fe94e674300035af4e0e7f6be833c33c4ab056b..8d151365cafad3d2080f243682570c039cc507dd 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/WorkspaceProvider.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/WorkspaceProvider.h
@@ -5,51 +5,50 @@
 #include "MantidAPI/Workspace_fwd.h"
 #include <string>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    /** 
-    @class WorkspaceProvider
-    Abstract type for fetching and disposing of workspaces. ADS instance is a
-    singleton and therfore very hard to fake in testing. Attempting to test the
-    behaviour of types using the ADS directly was causing code-bloat. Use this
-    abstract type instead, which can be mocked in testing. Concrete types can
-    use the ADS under-the-hood.
-
-    @author Owen Arnold, Tessella plc
-    @date 22/08/2011
-
-    Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport WorkspaceProvider
-    {
-    public:
-      virtual bool canProvideWorkspace(std::string wsName) const = 0;
-      virtual Mantid::API::Workspace_sptr fetchWorkspace(std::string wsName) const = 0;
-      virtual void disposeWorkspace(std::string wsName) const = 0;
-      virtual ~WorkspaceProvider(){}
-    };
-  }
+namespace Mantid {
+namespace VATES {
+
+/**
+@class WorkspaceProvider
+Abstract type for fetching and disposing of workspaces. ADS instance is a
+singleton and therfore very hard to fake in testing. Attempting to test the
+behaviour of types using the ADS directly was causing code-bloat. Use this
+abstract type instead, which can be mocked in testing. Concrete types can
+use the ADS under-the-hood.
+
+@author Owen Arnold, Tessella plc
+@date 22/08/2011
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport WorkspaceProvider {
+public:
+  virtual bool canProvideWorkspace(std::string wsName) const = 0;
+  virtual Mantid::API::Workspace_sptr
+  fetchWorkspace(std::string wsName) const = 0;
+  virtual void disposeWorkspace(std::string wsName) const = 0;
+  virtual ~WorkspaceProvider() {}
+};
+}
 }
 
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
index 884ea1f1e9c9c15513fcd06b8c72e1162d9a56fc..ef0097126e0bf259430153981911ff6792764aab 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h
@@ -15,33 +15,30 @@
 #include <string>
 
 class vtkFloatArray;
-namespace Mantid
-{
+namespace Mantid {
 
-namespace VATES
-{
-
-  //Forward declaration
-  class ProgressAction;
-
-  /* Helper struct allows recognition of points that we should not bother to draw.
-  */
-  struct UnstructuredPoint
-  {
-    bool isSparse;
-    vtkIdType pointId;
-  };
+namespace VATES {
 
+// Forward declaration
+class ProgressAction;
 
+/* Helper struct allows recognition of points that we should not bother to draw.
+*/
+struct UnstructuredPoint {
+  bool isSparse;
+  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
+ 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.
 
  @author Owen Arnold, Tessella plc
  @date 24/01/2010
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -62,11 +59,10 @@ namespace VATES
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-class DLLExport vtkDataSetFactory : public Mantid::Kernel::Chainable<vtkDataSetFactory>
-{
+class DLLExport vtkDataSetFactory
+    : public Mantid::Kernel::Chainable<vtkDataSetFactory> {
 
 public:
-
   /// Constructor
   vtkDataSetFactory();
 
@@ -74,31 +70,32 @@ public:
   virtual vtkSmartPointer<vtkDataSet> create(ProgressAction &) const = 0;
 
   /// Initalize with a target workspace.
-  virtual void initialize(Mantid::API::Workspace_sptr)=0;
+  virtual void initialize(Mantid::API::Workspace_sptr) = 0;
 
   /// Create the product in one step.
   virtual vtkSmartPointer<vtkDataSet> oneStepCreate(Mantid::API::Workspace_sptr,
                                                     ProgressAction &);
 
   /// Get the name of the type.
-  virtual std::string getFactoryTypeName() const =0;
+  virtual std::string getFactoryTypeName() const = 0;
 
-  virtual void setRecursionDepth(size_t) //TODO subtype vtkDataSet factory specifically for MDWEW type workspaces and put this method on that subtype.
+  virtual void setRecursionDepth(size_t) // TODO subtype vtkDataSet factory
+                                         // specifically for MDWEW type
+                                         // workspaces and put this method on
+                                         // that subtype.
   {
-    throw std::runtime_error("vtkDataSetFactory does not implement ::setRecursionDepth"); 
+    throw std::runtime_error(
+        "vtkDataSetFactory does not implement ::setRecursionDepth");
   }
 
-  /// Setter for whether a workspace defined transformation should be used or not.
-  virtual void setUseTransform(bool bUseTransform)
-  {
+  /// Setter for whether a workspace defined transformation should be used or
+  /// not.
+  virtual void setUseTransform(bool bUseTransform) {
     m_useTransform = bUseTransform;
   }
 
   /// Getter for the use transform status.
-  virtual bool getUseTransform() const
-  {
-    return m_useTransform;
-  }
+  virtual bool getUseTransform() const { return m_useTransform; }
 
   /// Setter to indicate that dimensionality should/should not be checked.
   void setCheckDimensionality(bool flag);
@@ -107,71 +104,81 @@ public:
   bool doesCheckDimensionality() const;
 
   /// Dimensionalities of interest.
-  enum Dimensionality{OneDimensional=1, TwoDimensional=2, ThreeDimensional=3, FourDimensional=4};
+  enum Dimensionality {
+    OneDimensional = 1,
+    TwoDimensional = 2,
+    ThreeDimensional = 3,
+    FourDimensional = 4
+  };
 
   static const std::string ScalarName;
 
 protected:
-  
   /**
-  Try to cast it to the specified IMDType and then run checks based on the non-integrated dimensionality. 
+  Try to cast it to the specified IMDType and then run checks based on the
+  non-integrated dimensionality.
   The latter checks are only run if the factory is set to apply these checks.
   @param  workspace : workspace to cast.
-  @param  bExactMatch : run an exact match on non-integarated dimensionality if TRUE, otherwise is less than or equal to ExpectedDimensions.
-  @return  correctly cast shared pointer or an empty shared pointer if cast or checks fail.
+  @param  bExactMatch : run an exact match on non-integarated dimensionality if
+  TRUE, otherwise is less than or equal to ExpectedDimensions.
+  @return  correctly cast shared pointer or an empty shared pointer if cast or
+  checks fail.
   */
-  template<typename IMDWorkspaceType, size_t ExpectedNDimensions>
-  boost::shared_ptr<IMDWorkspaceType> castAndCheck(Mantid::API::Workspace_sptr workspace, bool bExactMatch=true) const
-  {
+  template <typename IMDWorkspaceType, size_t ExpectedNDimensions>
+  boost::shared_ptr<IMDWorkspaceType>
+  castAndCheck(Mantid::API::Workspace_sptr workspace,
+               bool bExactMatch = true) const {
     boost::shared_ptr<IMDWorkspaceType> temp;
-    boost::shared_ptr<IMDWorkspaceType> imdws = boost::dynamic_pointer_cast<IMDWorkspaceType>(workspace);
-    if(!imdws)
-    {
-      //Abort as imdws cannot be dynamically cast to the target type.
+    boost::shared_ptr<IMDWorkspaceType> imdws =
+        boost::dynamic_pointer_cast<IMDWorkspaceType>(workspace);
+    if (!imdws) {
+      // Abort as imdws cannot be dynamically cast to the target type.
       return temp;
     }
     bool bPassesDimensionalityCheck = false;
-    size_t actualNonIntegratedDimensionality = imdws->getNonIntegratedDimensions().size();
-    if(bExactMatch)
-    {
-      bPassesDimensionalityCheck = (ExpectedNDimensions == actualNonIntegratedDimensionality);
+    size_t actualNonIntegratedDimensionality =
+        imdws->getNonIntegratedDimensions().size();
+    if (bExactMatch) {
+      bPassesDimensionalityCheck =
+          (ExpectedNDimensions == actualNonIntegratedDimensionality);
+    } else {
+      bPassesDimensionalityCheck =
+          (actualNonIntegratedDimensionality >= ExpectedNDimensions);
     }
-    else
-    {
-      bPassesDimensionalityCheck = (actualNonIntegratedDimensionality >= ExpectedNDimensions);
-    }
-    if(this->doesCheckDimensionality() &&  !bPassesDimensionalityCheck)
-    {
-      //Abort as there are dimensionality checks to be applied and these checks fail.
+    if (this->doesCheckDimensionality() && !bPassesDimensionalityCheck) {
+      // Abort as there are dimensionality checks to be applied and these checks
+      // fail.
       return temp;
     }
     return imdws;
   }
 
   /**
-  Common initialization implementation. Most vtkDataSets will need this in order to correctly delegate initialization onto successors.
+  Common initialization implementation. Most vtkDataSets will need this in order
+  to correctly delegate initialization onto successors.
   @param workspace : workspace to cast.
-  @param bExactMatch : run an exact match on non-integarated dimensionality if TRUE, otherwise is less than or equal to ExpectedDimensions.
-  @return correctly cast shared pointer or an empty shared pointer if cast or checks fail.
+  @param bExactMatch : run an exact match on non-integarated dimensionality if
+  TRUE, otherwise is less than or equal to ExpectedDimensions.
+  @return correctly cast shared pointer or an empty shared pointer if cast or
+  checks fail.
   */
-  template<typename IMDWorkspaceType, size_t ExpectedNDimensions>
-  boost::shared_ptr<IMDWorkspaceType> doInitialize(Mantid::API::Workspace_sptr workspace, bool bExactMatch=true) const
-  {
-    if(workspace == NULL)
-    {
-      std::string message = this->getFactoryTypeName() + " initialize cannot operate on a null workspace";
+  template <typename IMDWorkspaceType, size_t ExpectedNDimensions>
+  boost::shared_ptr<IMDWorkspaceType>
+  doInitialize(Mantid::API::Workspace_sptr workspace,
+               bool bExactMatch = true) const {
+    if (workspace == NULL) {
+      std::string message = this->getFactoryTypeName() +
+                            " initialize cannot operate on a null workspace";
       throw std::invalid_argument(message);
     }
-    boost::shared_ptr<IMDWorkspaceType> imdws = castAndCheck<IMDWorkspaceType, ExpectedNDimensions>(workspace, bExactMatch);
-    if(!imdws)
-    {
-      if(this->hasSuccessor())
-      {
+    boost::shared_ptr<IMDWorkspaceType> imdws =
+        castAndCheck<IMDWorkspaceType, ExpectedNDimensions>(workspace,
+                                                            bExactMatch);
+    if (!imdws) {
+      if (this->hasSuccessor()) {
         m_successor->setUseTransform(m_useTransform);
         m_successor->initialize(workspace);
-      }
-      else
-      {
+      } else {
         std::string message = this->getFactoryTypeName() + " has no successor";
         throw std::runtime_error(message);
       }
@@ -180,9 +187,11 @@ protected:
   }
 
   /**
-  Common creation implementation whereby delegation to successor is attempted if appropriate. 
+  Common creation implementation whereby delegation to successor is attempted if
+  appropriate.
   @param workspace : workspace to cast and create from.
-  @param progressUpdate : object used to pass progress information back up the stack.
+  @param progressUpdate : object used to pass progress information back up the
+  stack.
   @param bExactMatch : Check for an exact match if true.
   @return TRUE if delegation to successors has occured. Otherwise returns false.
   */
@@ -191,15 +200,13 @@ protected:
   tryDelegatingCreation(Mantid::API::Workspace_sptr workspace,
                         ProgressAction &progressUpdate,
                         bool bExactMatch = true) const {
-    boost::shared_ptr<IMDWorkspaceType> imdws = castAndCheck<IMDWorkspaceType, ExpectedNDimensions>(workspace, bExactMatch);
-    if(!imdws)
-    {
-      if(this->hasSuccessor())
-      {
+    boost::shared_ptr<IMDWorkspaceType> imdws =
+        castAndCheck<IMDWorkspaceType, ExpectedNDimensions>(workspace,
+                                                            bExactMatch);
+    if (!imdws) {
+      if (this->hasSuccessor()) {
         return m_successor->create(progressUpdate);
-      }
-      else
-      {
+      } else {
         std::string message = this->getFactoryTypeName() + " has no successor";
         throw std::runtime_error(message);
       }
@@ -217,16 +224,13 @@ protected:
   bool m_useTransform;
 
 private:
-  
   /// Dimensionality checking flag
   bool m_bCheckDimensionality;
 };
 
 typedef boost::shared_ptr<vtkDataSetFactory> vtkDataSetFactory_sptr;
 typedef std::unique_ptr<vtkDataSetFactory> vtkDataSetFactory_uptr;
-
 }
 }
 
-
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToGeometry.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToGeometry.h
index bd1be9c5379cff6b1be3db75d900cc5a16dce1f9..2f7980fb003c0488ccf582f9d93e210d48f5ced5 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToGeometry.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToGeometry.h
@@ -1,64 +1,62 @@
 #ifndef VTKDATASET_TO_GEOMETRY_H_
-#define VTKDATASET_TO_GEOMETRY_H_ 
+#define VTKDATASET_TO_GEOMETRY_H_
 
 #include "MantidGeometry/MDGeometry/IMDDimension.h"
 #include "MantidKernel/System.h"
 #include "MantidGeometry/MDGeometry/MDGeometryXMLParser.h"
 
 class vtkDataSet;
-namespace Mantid
-{
-  namespace VATES
-  {
- 
- /** @class vtkDataSetToGeometry 
+namespace Mantid {
+namespace VATES {
 
- Handles the extraction of dimensions from a vtkDataSet by getting at the field data and then processing the xml contained within to determine how mappings have been formed. 
+/** @class vtkDataSetToGeometry
 
- @author Owen Arnold, Tessella Support Services plc
- @date 13/05/2011
+Handles the extraction of dimensions from a vtkDataSet by getting at the field
+data and then processing the xml contained within to determine how mappings have
+been formed.
 
- Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+@author Owen Arnold, Tessella Support Services plc
+@date 13/05/2011
 
- This file is part of Mantid.
+Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
- Mantid is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 3 of the License, or
- (at your option) any later version.
+This file is part of Mantid.
 
- Mantid is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
 
- You should have received a copy of the GNU General Public License
- along with this program.  If not, see <http://www.gnu.org/licenses/>.
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
 
- File change history is stored at: <https://github.com/mantidproject/mantid>.
- Code Documentation is available at: <http://doxygen.mantidproject.org>
- */
-    class DLLExport vtkDataSetToGeometry : public Mantid::Geometry::MDGeometryXMLParser
-    {
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    private:
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkDataSetToGeometry
+    : public Mantid::Geometry::MDGeometryXMLParser {
 
-      vtkDataSet* m_dataSet;
+private:
+  vtkDataSet *m_dataSet;
 
-    public:
+public:
+  explicit vtkDataSetToGeometry(vtkDataSet *dataSet);
 
-      explicit vtkDataSetToGeometry(vtkDataSet* dataSet);
+  ~vtkDataSetToGeometry() override;
 
-      ~vtkDataSetToGeometry() override;
+  void execute() override;
 
-      void execute() override;
+  vtkDataSetToGeometry(const vtkDataSetToGeometry &other);
 
-      vtkDataSetToGeometry(const vtkDataSetToGeometry& other);
-
-      vtkDataSetToGeometry& operator=(const vtkDataSetToGeometry& other);
-
-    };
-  }
+  vtkDataSetToGeometry &operator=(const vtkDataSetToGeometry &other);
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToImplicitFunction.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToImplicitFunction.h
index 88019526acbb6d9fbc38ad9cd04d4350fbebd4ac..541836cd542ce64ada8decb7a96875c1fff29121 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToImplicitFunction.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToImplicitFunction.h
@@ -4,59 +4,56 @@
 #include "MantidKernel/System.h"
 
 class vtkDataSet;
-namespace Mantid
-{
-  namespace Geometry
-  {
-    //Forward declaration.
-    class MDImplicitFunction;
-  }
-  namespace VATES
-  {
-
-    /** @class vtkDataSetToImplicitFunction 
-
-    Handles the extraction of existing implcitfunctions from a vtkDataSet by getting at the field data and then processing the xml contained within.
-
-    @author Owen Arnold, Tessella Support Services plc
-    @date 22/08/2011
-
-    Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport vtkDataSetToImplicitFunction
-    {
-    public:
-        static Mantid::Geometry::MDImplicitFunction* exec(vtkDataSet* dataSet);
-        vtkDataSetToImplicitFunction(vtkDataSet* dataSet);
-        Mantid::Geometry::MDImplicitFunction* execute();
-        ~vtkDataSetToImplicitFunction();
-    private:
-        vtkDataSetToImplicitFunction& operator=(const vtkDataSetToImplicitFunction& other);
-        vtkDataSetToImplicitFunction(const vtkDataSetToImplicitFunction& other);
-        vtkDataSet* m_dataset;
-    };
-
-  }
+namespace Mantid {
+namespace Geometry {
+// Forward declaration.
+class MDImplicitFunction;
+}
+namespace VATES {
+
+/** @class vtkDataSetToImplicitFunction
+
+Handles the extraction of existing implcitfunctions from a vtkDataSet by getting
+at the field data and then processing the xml contained within.
+
+@author Owen Arnold, Tessella Support Services plc
+@date 22/08/2011
+
+Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkDataSetToImplicitFunction {
+public:
+  static Mantid::Geometry::MDImplicitFunction *exec(vtkDataSet *dataSet);
+  vtkDataSetToImplicitFunction(vtkDataSet *dataSet);
+  Mantid::Geometry::MDImplicitFunction *execute();
+  ~vtkDataSetToImplicitFunction();
+
+private:
+  vtkDataSetToImplicitFunction &
+  operator=(const vtkDataSetToImplicitFunction &other);
+  vtkDataSetToImplicitFunction(const vtkDataSetToImplicitFunction &other);
+  vtkDataSet *m_dataset;
+};
+}
 }
 
 #endif
-
-
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
index 75cd2d31cbf80d5e9a07d21c3db4599c37e95f3c..908dfacf9d25fafc958933c1b83d4b881c1fe7b1 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToNonOrthogonalDataSet.h
@@ -14,15 +14,12 @@
 
 class vtkDataSet;
 
-namespace Mantid
-{
-namespace Geometry
-{
+namespace Mantid {
+namespace Geometry {
 class OrientedLattice;
 }
 
-namespace VATES
-{
+namespace VATES {
 
 /**
  * Class that handles converting a dataset from rectilinear coordinates
@@ -51,49 +48,48 @@ namespace VATES
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
 */
-class DLLExport vtkDataSetToNonOrthogonalDataSet
-{
+class DLLExport vtkDataSetToNonOrthogonalDataSet {
 public:
-    /// Static execution method
-    static void exec(vtkDataSet *dataset, std::string name,
-                     std::unique_ptr<WorkspaceProvider> workspaceProvider);
-    /// Constructor
-    vtkDataSetToNonOrthogonalDataSet(
-        vtkDataSet *dataset, std::string name,
-        std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider);
-    /// Class execution method
-    void execute();
-    /// Destructor
-    virtual ~vtkDataSetToNonOrthogonalDataSet();
+  /// Static execution method
+  static void exec(vtkDataSet *dataset, std::string name,
+                   std::unique_ptr<WorkspaceProvider> workspaceProvider);
+  /// Constructor
+  vtkDataSetToNonOrthogonalDataSet(
+      vtkDataSet *dataset, std::string name,
+      std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider);
+  /// Class execution method
+  void execute();
+  /// Destructor
+  virtual ~vtkDataSetToNonOrthogonalDataSet();
 
 private:
-    vtkDataSetToNonOrthogonalDataSet &
-    operator=(const vtkDataSetToNonOrthogonalDataSet &other);
-    vtkDataSetToNonOrthogonalDataSet(
-        const vtkDataSetToNonOrthogonalDataSet &other);
-    /// Calculate the skew matrix and basis.
-    void createSkewInformation(Geometry::OrientedLattice &ol,
-                               Kernel::DblMatrix &w,
-                               Kernel::Matrix<coord_t> &aff);
-    /// Calculate the skew basis vector
-    void findSkewBasis(Kernel::V3D &basis, double scale);
-    /// Reduce the dimensionality of matrix by 1
-    void stripMatrix(Kernel::DblMatrix &mat);
-    /// Add the skew basis to metadata
-    void updateMetaData(vtkDataSet *ugrid);
-    vtkDataSet *m_dataSet; ///< Pointer to VTK dataset to modify
-    std::string m_wsName;  ///< The name of the workspace to fetch
-    std::size_t m_numDims; ///< Number of dimensions in workspace
-    Kernel::DblMatrix
-        m_skewMat; ///< The skew matrix for non-orthogonal representation
-    MantidVec m_basisNorm; ///< Holder for the basis normalisation values
-    Kernel::V3D m_basisX;  ///< The X direction basis vector
-    Kernel::V3D m_basisY;  ///< The Y direction basis vector
-    Kernel::V3D m_basisZ;  ///< The Z direction basis vector
-    Kernel::SpecialCoordinateSystem
-        m_coordType; ///< The coordinate system for the workspace
-    std::array<double, 6> m_boundingBox;
-    std::unique_ptr<Mantid::VATES::WorkspaceProvider> m_workspaceProvider;
+  vtkDataSetToNonOrthogonalDataSet &
+  operator=(const vtkDataSetToNonOrthogonalDataSet &other);
+  vtkDataSetToNonOrthogonalDataSet(
+      const vtkDataSetToNonOrthogonalDataSet &other);
+  /// Calculate the skew matrix and basis.
+  void createSkewInformation(Geometry::OrientedLattice &ol,
+                             Kernel::DblMatrix &w,
+                             Kernel::Matrix<coord_t> &aff);
+  /// Calculate the skew basis vector
+  void findSkewBasis(Kernel::V3D &basis, double scale);
+  /// Reduce the dimensionality of matrix by 1
+  void stripMatrix(Kernel::DblMatrix &mat);
+  /// Add the skew basis to metadata
+  void updateMetaData(vtkDataSet *ugrid);
+  vtkDataSet *m_dataSet; ///< Pointer to VTK dataset to modify
+  std::string m_wsName;  ///< The name of the workspace to fetch
+  std::size_t m_numDims; ///< Number of dimensions in workspace
+  Kernel::DblMatrix
+      m_skewMat;         ///< The skew matrix for non-orthogonal representation
+  MantidVec m_basisNorm; ///< Holder for the basis normalisation values
+  Kernel::V3D m_basisX;  ///< The X direction basis vector
+  Kernel::V3D m_basisY;  ///< The Y direction basis vector
+  Kernel::V3D m_basisZ;  ///< The Z direction basis vector
+  Kernel::SpecialCoordinateSystem
+      m_coordType; ///< The coordinate system for the workspace
+  std::array<double, 6> m_boundingBox;
+  std::unique_ptr<Mantid::VATES::WorkspaceProvider> m_workspaceProvider;
 };
 
 } // namespace VATES
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h
index 0868408759a25e4a523712db7038078cf804a42b..57243fe290922b42f8ede4271b9c4b291a6d306f 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h
@@ -11,77 +11,75 @@
 
 class vtkUnstructuredGrid;
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-  /**
-    Class that selects only those data points which lie within the geometry of a peak. 
-    
-    @date 17/02/2015
+/**
+  Class that selects only those data points which lie within the geometry of a
+  peak.
 
-    Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  @date 17/02/2015
 
-    This file is part of Mantid.
+  Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+  This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-  class DLLExport vtkDataSetToPeaksFilteredDataSet
-  {
-    public:
-      vtkDataSetToPeaksFilteredDataSet(
-          vtkSmartPointer<vtkUnstructuredGrid> input,
-          vtkSmartPointer<vtkUnstructuredGrid> output);
-      vtkDataSetToPeaksFilteredDataSet(
-          const vtkDataSetToPeaksFilteredDataSet &) = default;
-      vtkDataSetToPeaksFilteredDataSet &
-      operator=(const vtkDataSetToPeaksFilteredDataSet &) = delete;
-      virtual ~vtkDataSetToPeaksFilteredDataSet();
-      /// Set the name of the peaks workspace
-      void initialize(
-          const std::vector<Mantid::API::IPeaksWorkspace_sptr> &peaksWorkspaces,
-          double radiusNoShape, Geometry::PeakShape::RadiusType radiusType,
-          int coordinateSystem);
-      /// Apply the peak filtering
-      void execute(ProgressAction& progressUpdating);
-      /// Get radius of no shape
-      double getRadiusNoShape();
-      /// Get radius factor
-      double getRadiusFactor();
-    private:
-      std::vector<std::pair<Mantid::Kernel::V3D, double>>
-      getPeaksInfo(const std::vector<Mantid::API::IPeaksWorkspace_sptr>
-                       &peaksWorkspaces);
-      Kernel::V3D getPeakPosition(const Mantid::Geometry::IPeak &peak);
-      double getPeakRadius(const Mantid::Geometry::PeakShape &shape);
-      double m_radiusNoShape; ///< The radius for peaks with no peak shape.
-      double m_radiusFactor;///< By how much we want to trim the data set.
-      double m_defaultRadius; ///< A default radius.
-      Geometry::PeakShape::RadiusType m_radiusType;
-      bool m_isInitialised; ///<Flag if the filter is initialized
-      Mantid::Kernel::SpecialCoordinateSystem
-          m_coordinateSystem; ///< A coordinate system.
-      vtkSmartPointer<vtkUnstructuredGrid> m_inputData; ///< Data to peak filter
-      vtkSmartPointer<vtkUnstructuredGrid> m_outputData; ///< Peak filtered data
-      std::vector<Mantid::API::IPeaksWorkspace_sptr>
-          m_peaksWorkspaces; ///< A list of peaks workspace names.
-  };
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class DLLExport vtkDataSetToPeaksFilteredDataSet {
+public:
+  vtkDataSetToPeaksFilteredDataSet(vtkSmartPointer<vtkUnstructuredGrid> input,
+                                   vtkSmartPointer<vtkUnstructuredGrid> output);
+  vtkDataSetToPeaksFilteredDataSet(const vtkDataSetToPeaksFilteredDataSet &) =
+      default;
+  vtkDataSetToPeaksFilteredDataSet &
+  operator=(const vtkDataSetToPeaksFilteredDataSet &) = delete;
+  virtual ~vtkDataSetToPeaksFilteredDataSet();
+  /// Set the name of the peaks workspace
+  void initialize(
+      const std::vector<Mantid::API::IPeaksWorkspace_sptr> &peaksWorkspaces,
+      double radiusNoShape, Geometry::PeakShape::RadiusType radiusType,
+      int coordinateSystem);
+  /// Apply the peak filtering
+  void execute(ProgressAction &progressUpdating);
+  /// Get radius of no shape
+  double getRadiusNoShape();
+  /// Get radius factor
+  double getRadiusFactor();
+
+private:
+  std::vector<std::pair<Mantid::Kernel::V3D, double>> getPeaksInfo(
+      const std::vector<Mantid::API::IPeaksWorkspace_sptr> &peaksWorkspaces);
+  Kernel::V3D getPeakPosition(const Mantid::Geometry::IPeak &peak);
+  double getPeakRadius(const Mantid::Geometry::PeakShape &shape);
+  double m_radiusNoShape; ///< The radius for peaks with no peak shape.
+  double m_radiusFactor;  ///< By how much we want to trim the data set.
+  double m_defaultRadius; ///< A default radius.
+  Geometry::PeakShape::RadiusType m_radiusType;
+  bool m_isInitialised; ///<Flag if the filter is initialized
+  Mantid::Kernel::SpecialCoordinateSystem
+      m_coordinateSystem;                            ///< A coordinate system.
+  vtkSmartPointer<vtkUnstructuredGrid> m_inputData;  ///< Data to peak filter
+  vtkSmartPointer<vtkUnstructuredGrid> m_outputData; ///< Peak filtered data
+  std::vector<Mantid::API::IPeaksWorkspace_sptr>
+      m_peaksWorkspaces; ///< A list of peaks workspace names.
+};
 }
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToScaledDataSet.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToScaledDataSet.h
index e6929ef079a93f330483fc3605740aa9bcf58215..d5fbef969f7abbd40fd4c7fbf31c107503887e13 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToScaledDataSet.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToScaledDataSet.h
@@ -5,54 +5,55 @@
 
 class vtkPointSet;
 class vtkInformation;
-namespace Mantid
-{
-namespace VATES
-{
-
-  /**
-   *Functor class that handles scaling a given vtkDataSet and setting appropriate
-   *metadata on output vtkDataSet so that original extents will be shown.
-    
-    @date 22/02/2013
-
-    Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-  class DLLExport vtkDataSetToScaledDataSet 
-  {
-  public:
-    /// Constructor
-    vtkDataSetToScaledDataSet();
-    /// Destructor
-    virtual ~vtkDataSetToScaledDataSet();
-    /// Apply the scaling and add metadata
-    vtkPointSet* execute(double xScale, double yScale, double zScale, vtkPointSet * inputData, vtkInformation* info);
-    /// Apply the scaling and add metadata
-    vtkPointSet* execute(double xScale, double yScale, double zScale, vtkPointSet * inputData, vtkPointSet * outputData = NULL);
-  private:
-    vtkDataSetToScaledDataSet& operator=(const vtkDataSetToScaledDataSet& other);
-    /// Set metadata on the dataset to handle scaling
-    void updateMetaData(double xScale, double yScale,
-                        double zScale, vtkPointSet* inputData, vtkPointSet * outputData);
-  };
+namespace Mantid {
+namespace VATES {
+
+/**
+ *Functor class that handles scaling a given vtkDataSet and setting appropriate
+ *metadata on output vtkDataSet so that original extents will be shown.
+
+  @date 22/02/2013
+
+  Copyright &copy; 2013 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkDataSetToScaledDataSet {
+public:
+  /// Constructor
+  vtkDataSetToScaledDataSet();
+  /// Destructor
+  virtual ~vtkDataSetToScaledDataSet();
+  /// Apply the scaling and add metadata
+  vtkPointSet *execute(double xScale, double yScale, double zScale,
+                       vtkPointSet *inputData, vtkInformation *info);
+  /// Apply the scaling and add metadata
+  vtkPointSet *execute(double xScale, double yScale, double zScale,
+                       vtkPointSet *inputData, vtkPointSet *outputData = NULL);
+
+private:
+  vtkDataSetToScaledDataSet &operator=(const vtkDataSetToScaledDataSet &other);
+  /// Set metadata on the dataset to handle scaling
+  void updateMetaData(double xScale, double yScale, double zScale,
+                      vtkPointSet *inputData, vtkPointSet *outputData);
+};
 
 } // namespace VATES
 } // namespace Mantid
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsLocation.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsLocation.h
index f086ebe195c8a758641c34908b20be00caa2eefa..b5399483cecd5759c101bb2965a69767e5930bf8 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsLocation.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsLocation.h
@@ -5,52 +5,51 @@
 #include "MantidKernel/System.h"
 
 class vtkDataSet;
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    /** @class vtkDataSetToImplicitFunction 
-
-    Handles the extraction of existing ws location from a vtkDataSet by getting at the field data and then processing the xml contained within.
-
-    @author Owen Arnold, Tessella Support Services plc
-    @date 22/08/2011
-
-    Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport vtkDataSetToWsLocation
-    {
-    public:
-        static std::string exec(vtkDataSet* dataSet);
-        vtkDataSetToWsLocation(vtkDataSet* dataSet);
-        std::string execute();
-        ~vtkDataSetToWsLocation();
-    private:
-        vtkDataSetToWsLocation& operator=(const vtkDataSetToWsLocation& other);
-        vtkDataSetToWsLocation(const vtkDataSetToWsLocation& other);
-        vtkDataSet* m_dataset;
-    };
-
-  }
+namespace Mantid {
+namespace VATES {
+
+/** @class vtkDataSetToImplicitFunction
+
+Handles the extraction of existing ws location from a vtkDataSet by getting at
+the field data and then processing the xml contained within.
+
+@author Owen Arnold, Tessella Support Services plc
+@date 22/08/2011
+
+Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkDataSetToWsLocation {
+public:
+  static std::string exec(vtkDataSet *dataSet);
+  vtkDataSetToWsLocation(vtkDataSet *dataSet);
+  std::string execute();
+  ~vtkDataSetToWsLocation();
+
+private:
+  vtkDataSetToWsLocation &operator=(const vtkDataSetToWsLocation &other);
+  vtkDataSetToWsLocation(const vtkDataSetToWsLocation &other);
+  vtkDataSet *m_dataset;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsName.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsName.h
index fa7815205322f98a90c7ee971383132d0c8cf717..8dffc74d03ec5a0b55680542b833f72db391cf90 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsName.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToWsName.h
@@ -5,52 +5,51 @@
 #include "MantidKernel/System.h"
 
 class vtkDataSet;
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    /** @class vtkDataSetToImplicitFunction 
-
-    Handles the extraction of existing ws location from a vtkDataSet by getting at the field data and then processing the xml contained within.
-
-    @author Owen Arnold, Tessella Support Services plc
-    @date 22/08/2011
-
-    Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-    This file is part of Mantid.
-
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
-
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-    File change history is stored at: <https://github.com/mantidproject/mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-    */
-    class DLLExport vtkDataSetToWsName
-    {
-    public:
-        static std::string exec(vtkDataSet* dataSet);
-        vtkDataSetToWsName(vtkDataSet* dataSet);
-        std::string execute();
-        ~vtkDataSetToWsName();
-    private:
-        vtkDataSetToWsName& operator=(const vtkDataSetToWsName& other);
-        vtkDataSetToWsName(const vtkDataSetToWsName& other);
-        vtkDataSet* m_dataset;
-    };
-
-  }
+namespace Mantid {
+namespace VATES {
+
+/** @class vtkDataSetToImplicitFunction
+
+Handles the extraction of existing ws location from a vtkDataSet by getting at
+the field data and then processing the xml contained within.
+
+@author Owen Arnold, Tessella Support Services plc
+@date 22/08/2011
+
+Copyright &copy; 2007-8 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>.
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkDataSetToWsName {
+public:
+  static std::string exec(vtkDataSet *dataSet);
+  vtkDataSetToWsName(vtkDataSet *dataSet);
+  std::string execute();
+  ~vtkDataSetToWsName();
+
+private:
+  vtkDataSetToWsName &operator=(const vtkDataSetToWsName &other);
+  vtkDataSetToWsName(const vtkDataSetToWsName &other);
+  vtkDataSet *m_dataset;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h
index e784a3050ed76444c8401c74d8c5c181a3d64f5d..e290c18c74f19551967c89c04e5e472f11350a7c 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkGlyph3D_Silent.h
@@ -2,16 +2,16 @@
 #define VTKGLYPH3D_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkGlyph3D.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKGLYPH3D_SILENT_H
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkImageData_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkImageData_Silent.h
index 7cf0e125a50d36e4538e929f666e9a15074be048..1bc65f4a19261b72dd3d3db7f1cc2f66c5a262be 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkImageData_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkImageData_Silent.h
@@ -2,16 +2,16 @@
 #define VTKIMAGEDATA_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkImageData.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKIMAGEDATA_SILENT_H
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
index 36d0c213271e3147ace3e3fc8156ef9ff3c831e4..038b5b324b7cf216069f93adbfbd7c1c83cd8c84 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h
@@ -7,14 +7,13 @@
 #include "vtkUnstructuredGrid.h"
 #include "MantidVatesAPI/ThresholdRange.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
 /** 0D Factory. This type is responsible for rendering IMDWorkspaces with 0D.
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -34,30 +33,25 @@ namespace Mantid
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-    class DLLExport vtkMD0DFactory : public vtkDataSetFactory
-    {
-    public:
+class DLLExport vtkMD0DFactory : public vtkDataSetFactory {
+public:
+  /// Constructor
+  vtkMD0DFactory();
 
-      /// Constructor
-      vtkMD0DFactory();
+  /// Destructor
+  ~vtkMD0DFactory() override;
 
-      /// Destructor
-      ~vtkMD0DFactory() override;
+  /// Factory Method.
+  vtkSmartPointer<vtkDataSet>
+  create(ProgressAction &progressUpdating) const override;
 
-      /// Factory Method.
-      vtkSmartPointer<vtkDataSet>
-      create(ProgressAction &progressUpdating) const override;
+  void initialize(Mantid::API::Workspace_sptr) override;
 
-      void initialize(Mantid::API::Workspace_sptr) override;
+  std::string getFactoryTypeName() const override { return "vtkMD0DFactory"; }
 
-      std::string getFactoryTypeName() const override {
-        return "vtkMD0DFactory";
-      }
-
-    protected:
-      void validate() const override;
-    };
-    
-  }
+protected:
+  void validate() const override;
+};
+}
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h
index 01b17b215f616a68562fdb102d05652e42b0d8e2..c30a70a3aefadb759184142626c6332f23aa4665 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h
@@ -223,15 +223,13 @@ void vtkMDHWSignalArray<Scalar>::LookupValue(vtkVariant value, vtkIdList *ids) {
   bool valid = true;
   Scalar val = vtkVariantCast<Scalar>(value, &valid);
   ids->Reset();
-  if (valid)
-    {
+  if (valid) {
     vtkIdType index = 0;
-    while ((index = this->Lookup(val, index)) >= 0)
-      {
+    while ((index = this->Lookup(val, index)) >= 0) {
       ids->InsertNextId(index);
       ++index;
-      }
     }
+  }
 }
 
 //------------------------------------------------------------------------------
@@ -272,11 +270,10 @@ void vtkMDHWSignalArray<Scalar>::LookupTypedValue(Scalar value,
                                                   vtkIdList *ids) {
   ids->Reset();
   vtkIdType index = 0;
-  while ((index = this->Lookup(value, index)) >= 0)
-    {
+  while ((index = this->Lookup(value, index)) >= 0) {
     ids->InsertNextId(index);
     ++index;
-    }
+  }
 }
 
 template <class Scalar>
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
index 35c7d6dacc34a6de0cd2f6498efa6bb710c32194..894ce675cd763cab4d3a05840e7d77c0715a40e4 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h
@@ -1,13 +1,15 @@
 #ifndef MANTID_VATES_VTK_MD_HISTO_HEX4D_FACTORY_H_
 #define MANTID_VATES_VTK_MD_HISTO_HEX4D_FACTORY_H_
 
-/** Concrete implementation of vtkDataSetFactory. Creates a vtkUnStructuredGrid. Uses Thresholding technique
+/** Concrete implementation of vtkDataSetFactory. Creates a vtkUnStructuredGrid.
+ Uses Thresholding technique
  * to create sparse 4D representation of data.
 
  @author Owen Arnold, Tessella plc
  @date 24/01/2010
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -38,25 +40,23 @@
 #include <vtkHexahedron.h>
 #include <vtkUnstructuredGrid.h>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-template<typename TimeMapper>
-class DLLExport vtkMDHistoHex4DFactory: public vtkMDHistoHexFactory
-{
+template <typename TimeMapper>
+class DLLExport vtkMDHistoHex4DFactory : public vtkMDHistoHexFactory {
 public:
-
   /// Constructor
-  vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption,
-      const double timestep);
+  vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange,
+                         const VisualNormalization normalizationOption,
+                         const double timestep);
 
   /// Assignment operator
-  vtkMDHistoHex4DFactory& operator=(const vtkMDHistoHex4DFactory<TimeMapper>& other);
+  vtkMDHistoHex4DFactory &
+  operator=(const vtkMDHistoHex4DFactory<TimeMapper> &other);
 
   /// Copy constructor.
-  vtkMDHistoHex4DFactory(const vtkMDHistoHex4DFactory<TimeMapper>& other);
+  vtkMDHistoHex4DFactory(const vtkMDHistoHex4DFactory<TimeMapper> &other);
 
   /// Destructor
   ~vtkMDHistoHex4DFactory() override;
@@ -76,10 +76,9 @@ protected:
   void validate() const override;
 
 private:
+  typedef std::vector<std::vector<std::vector<UnstructuredPoint>>> PointMap;
 
-  typedef std::vector<std::vector<std::vector<UnstructuredPoint> > > PointMap;
-
-  typedef std::vector<std::vector<UnstructuredPoint> > Plane;
+  typedef std::vector<std::vector<UnstructuredPoint>> Plane;
 
   typedef std::vector<UnstructuredPoint> Column;
 
@@ -88,9 +87,7 @@ private:
 
   /// Time mapper.
   TimeMapper m_timeMapper;
-
 };
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
index ee1344c30234dec2964b3905c15c5cc2b7d3aee3..f65dd27efee811866fb03f749ac539a2b1153722 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h
@@ -1,13 +1,15 @@
 #ifndef MANTID_VATES_VTK_MD_HISTO_HEX_FACTORY_H_
 #define MANTID_VATES_VTK_MD_HISTO_HEX_FACTORY_H_
 
-/** Concrete implementation of vtkDataSetFactory. Creates a vtkUnStructuredGrid. Uses Thresholding technique
- * to create sparse 3D representation of data. 
+/** Concrete implementation of vtkDataSetFactory. Creates a vtkUnStructuredGrid.
+ Uses Thresholding technique
+ * to create sparse 3D representation of data.
 
  @author Owen Arnold, Tessella plc
  @date 06/05/2011
 
- Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -37,23 +39,20 @@
 #include <vtkHexahedron.h>
 #include "MantidDataObjects/MDHistoWorkspace.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-class DLLExport vtkMDHistoHexFactory: public vtkDataSetFactory
-{
+class DLLExport vtkMDHistoHexFactory : public vtkDataSetFactory {
 public:
-
   /// Constructor
-  vtkMDHistoHexFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
+  vtkMDHistoHexFactory(ThresholdRange_scptr thresholdRange,
+                       const VisualNormalization normalizationOption);
 
   /// Assignment operator
-  vtkMDHistoHexFactory& operator=(const vtkMDHistoHexFactory& other);
+  vtkMDHistoHexFactory &operator=(const vtkMDHistoHexFactory &other);
 
   /// Copy constructor.
-  vtkMDHistoHexFactory(const vtkMDHistoHexFactory& other);
+  vtkMDHistoHexFactory(const vtkMDHistoHexFactory &other);
 
   /// Destructor
   ~vtkMDHistoHexFactory() override;
@@ -87,9 +86,7 @@ protected:
 
   /// Threshold range.
   mutable ThresholdRange_scptr m_thresholdRange;
-
 };
-
 }
 }
 
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
index 0b9109f25cffdf5f1c6bbd51c723668ebde05c31..cd47ac315d7d459914cad39e59ef3c066888c4c1 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h
@@ -10,17 +10,17 @@
 #include "MantidDataObjects/MDHistoWorkspace.h"
 #include <vtkNew.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-/** Line Factory. This type is responsible for rendering IMDWorkspaces as a single dimension.
+/** Line Factory. This type is responsible for rendering IMDWorkspaces as a
+ single dimension.
 
  @author Owen Arnold, Tessella plc
  @date 09/05/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -40,47 +40,43 @@ namespace Mantid
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-    class DLLExport vtkMDHistoLineFactory : public vtkDataSetFactory
-    {
-    public:
+class DLLExport vtkMDHistoLineFactory : public vtkDataSetFactory {
+public:
+  /// Constructor
+  vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange,
+                        const VisualNormalization normalizationOption);
 
-      /// Constructor
-      vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
+  /// Assignment operator
+  vtkMDHistoLineFactory &operator=(const vtkMDHistoLineFactory &other);
 
-      /// Assignment operator
-      vtkMDHistoLineFactory& operator=(const vtkMDHistoLineFactory& other);
+  /// Copy constructor.
+  vtkMDHistoLineFactory(const vtkMDHistoLineFactory &other);
 
-      /// Copy constructor.
-      vtkMDHistoLineFactory(const vtkMDHistoLineFactory& other);
+  /// Destructor
+  ~vtkMDHistoLineFactory() override;
 
-      /// Destructor
-      ~vtkMDHistoLineFactory() override;
+  /// Factory Method.
+  vtkSmartPointer<vtkDataSet>
+  create(ProgressAction &progressUpdating) const override;
 
-      /// Factory Method.
-      vtkSmartPointer<vtkDataSet>
-      create(ProgressAction &progressUpdating) const override;
+  void initialize(Mantid::API::Workspace_sptr) override;
 
-      void initialize(Mantid::API::Workspace_sptr) override;
+  typedef std::vector<UnstructuredPoint> Column;
 
-      typedef std::vector<UnstructuredPoint> Column;
-
-      std::string getFactoryTypeName() const override {
-        return "vtkMDHistoLineFactory";
-      }
-
-    protected:
-      void validate() const override;
+  std::string getFactoryTypeName() const override {
+    return "vtkMDHistoLineFactory";
+  }
 
-    private:
+protected:
+  void validate() const override;
 
-      Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
+private:
+  Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
 
-      VisualNormalization m_normalizationOption;
+  VisualNormalization m_normalizationOption;
 
-      mutable ThresholdRange_scptr m_thresholdRange;
-    
-    };
-    
-  }
+  mutable ThresholdRange_scptr m_thresholdRange;
+};
+}
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
index b6180c57171e00449499d95c4695bff8c6a26aa4..4ee573720028353b9c2e7d683241afcfe73d3ab9 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h
@@ -10,18 +10,20 @@
 #include "vtkUnstructuredGrid.h"
 #include "MantidDataObjects/MDHistoWorkspace.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-/** Quad Factory. This type is responsible for rendering IMDWorkspaces as surfaces with two spatial dimensions. Ideally this would be done as a polydata type rather than a unstructuredgrid type,
-however, some visualisation frameworks won't be able to treat these factories in a covarient fashion. 
+/** Quad Factory. This type is responsible for rendering IMDWorkspaces as
+surfaces with two spatial dimensions. Ideally this would be done as a polydata
+type rather than a unstructuredgrid type,
+however, some visualisation frameworks won't be able to treat these factories in
+a covarient fashion.
 
  @author Owen Arnold, Tessella plc
  @date 03/05/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -41,48 +43,45 @@ however, some visualisation frameworks won't be able to treat these factories in
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-    class DLLExport vtkMDHistoQuadFactory : public vtkDataSetFactory
-    {
-    public:
+class DLLExport vtkMDHistoQuadFactory : public vtkDataSetFactory {
+public:
+  /// Constructor
+  vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange,
+                        const VisualNormalization normalizationOption);
 
-      /// Constructor
-      vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
+  /// Assignment operator
+  vtkMDHistoQuadFactory &operator=(const vtkMDHistoQuadFactory &other);
 
-      /// Assignment operator
-      vtkMDHistoQuadFactory& operator=(const vtkMDHistoQuadFactory& other);
+  /// Copy constructor.
+  vtkMDHistoQuadFactory(const vtkMDHistoQuadFactory &other);
 
-      /// Copy constructor.
-      vtkMDHistoQuadFactory(const vtkMDHistoQuadFactory& other);
+  /// Destructor
+  ~vtkMDHistoQuadFactory() override;
 
-      /// Destructor
-      ~vtkMDHistoQuadFactory() override;
+  /// Factory Method.
+  vtkSmartPointer<vtkDataSet>
+  create(ProgressAction &progressUpdating) const override;
 
-      /// Factory Method.
-      vtkSmartPointer<vtkDataSet>
-      create(ProgressAction &progressUpdating) const override;
+  void initialize(Mantid::API::Workspace_sptr) override;
 
-      void initialize(Mantid::API::Workspace_sptr) override;
+  typedef std::vector<std::vector<UnstructuredPoint>> Plane;
 
-      typedef std::vector<std::vector<UnstructuredPoint> > Plane;
+  typedef std::vector<UnstructuredPoint> Column;
 
-      typedef std::vector<UnstructuredPoint> Column;
-
-      std::string getFactoryTypeName() const override {
-        return "vtkMDHistoQuadFactory";
-      }
+  std::string getFactoryTypeName() const override {
+    return "vtkMDHistoQuadFactory";
+  }
 
-    protected:
-      void validate() const override;
+protected:
+  void validate() const override;
 
-    private:
-      Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
+private:
+  Mantid::DataObjects::MDHistoWorkspace_sptr m_workspace;
 
-      VisualNormalization m_normalizationOption;
+  VisualNormalization m_normalizationOption;
 
-      mutable ThresholdRange_scptr m_thresholdRange;
-    
-    };
-    
-  }
+  mutable ThresholdRange_scptr m_thresholdRange;
+};
+}
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
index 806b4e2ad1b19e80f0c0636835f3d31eb8321a3a..192d40a49663583be0e835a113d1143069abb30a 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h
@@ -6,74 +6,71 @@
 #include "MantidVatesAPI/ThresholdRange.h"
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-   /** Factory for creating a vtkDataSet from an IMDEventWorkspace with a single non-integrated dimensions.
-    Delegates processing to a successor if these conditions are not met.
-    
-    @date 2012-02-10
+/** Factory for creating a vtkDataSet from an IMDEventWorkspace with a single
+ non-integrated dimensions.
+ Delegates processing to a successor if these conditions are not met.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ @date 2012-02-10
 
-    This file is part of Mantid.
+ Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+ This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport vtkMDLineFactory : public vtkDataSetFactory
-    {
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    public:
-      /// Constructor
-      vtkMDLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkMDLineFactory : public vtkDataSetFactory {
 
-      /// Destructor
-      ~vtkMDLineFactory() override;
+public:
+  /// Constructor
+  vtkMDLineFactory(ThresholdRange_scptr thresholdRange,
+                   const VisualNormalization normalizationOption);
 
-      /// Factory Method. Should also handle delegation to successors.
-      vtkSmartPointer<vtkDataSet>
-      create(ProgressAction &progressUpdating) const override;
+  /// Destructor
+  ~vtkMDLineFactory() override;
 
-      /// Initalize with a target workspace.
-      void initialize(Mantid::API::Workspace_sptr) override;
+  /// Factory Method. Should also handle delegation to successors.
+  vtkSmartPointer<vtkDataSet>
+  create(ProgressAction &progressUpdating) const override;
 
-      /// Get the name of the type.
-      std::string getFactoryTypeName() const override;
+  /// Initalize with a target workspace.
+  void initialize(Mantid::API::Workspace_sptr) override;
 
-    protected:
+  /// Get the name of the type.
+  std::string getFactoryTypeName() const override;
 
-      /// Template Method pattern to validate the factory before use.
-      void validate() const override;
+protected:
+  /// Template Method pattern to validate the factory before use.
+  void validate() const override;
 
-    private:
+private:
+  /// ThresholdRange functor.
+  ThresholdRange_scptr m_thresholdRange;
 
-      ///ThresholdRange functor.
-      ThresholdRange_scptr m_thresholdRange;
+  /// Name of the scalar.
+  const VisualNormalization m_normalizationOption;
 
-      ///Name of the scalar.
-      const VisualNormalization m_normalizationOption;
-
-      /// Data source for the visualisation.
-      Mantid::API::Workspace_sptr m_workspace;
-
-    };
-  }
+  /// Data source for the visualisation.
+  Mantid::API::Workspace_sptr m_workspace;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
index ce167b4de83ff26ec9d511ff2016920cbcddc686..5b5a7ebe7069b2c1580757f10ff8cc837643e883 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h
@@ -7,74 +7,71 @@
 
 #include <boost/shared_ptr.hpp>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-   /** Factory for creating a vtkDataSet from an IMDEventWorkspace with two non-integrated dimensions.
-    Delegates processing to a successor if these conditions are not met.
-    
-    @date 2012-02-09
+/** Factory for creating a vtkDataSet from an IMDEventWorkspace with two
+ non-integrated dimensions.
+ Delegates processing to a successor if these conditions are not met.
 
-    Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ @date 2012-02-09
 
-    This file is part of Mantid.
+ Copyright &copy; 2012 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-    Mantid is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 3 of the License, or
-    (at your option) any later version.
+ This file is part of Mantid.
 
-    Mantid is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-    File change history is stored at: <https://github.com/mantidproject/mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-  */
-    class DLLExport vtkMDQuadFactory : public vtkDataSetFactory
-    {
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-    public:
-      /// Constructor
-      vtkMDQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption);
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+class DLLExport vtkMDQuadFactory : public vtkDataSetFactory {
 
-      /// Destructor
-      ~vtkMDQuadFactory() override;
+public:
+  /// Constructor
+  vtkMDQuadFactory(ThresholdRange_scptr thresholdRange,
+                   const VisualNormalization normalizationOption);
 
-      /// Factory Method. Should also handle delegation to successors.
-      vtkSmartPointer<vtkDataSet>
-      create(ProgressAction &progressUpdating) const override;
+  /// Destructor
+  ~vtkMDQuadFactory() override;
 
-      /// Initalize with a target workspace.
-      void initialize(Mantid::API::Workspace_sptr) override;
+  /// Factory Method. Should also handle delegation to successors.
+  vtkSmartPointer<vtkDataSet>
+  create(ProgressAction &progressUpdating) const override;
 
-      /// Get the name of the type.
-      std::string getFactoryTypeName() const override;
+  /// Initalize with a target workspace.
+  void initialize(Mantid::API::Workspace_sptr) override;
 
-    protected:
+  /// Get the name of the type.
+  std::string getFactoryTypeName() const override;
 
-      /// Template Method pattern to validate the factory before use.
-      void validate() const override;
+protected:
+  /// Template Method pattern to validate the factory before use.
+  void validate() const override;
 
-    private:
+private:
+  /// ThresholdRange functor.
+  ThresholdRange_scptr m_thresholdRange;
 
-      ///ThresholdRange functor.
-      ThresholdRange_scptr m_thresholdRange;
+  /// Name of the scalar.
+  const VisualNormalization m_normalizationOption;
 
-      ///Name of the scalar.
-      const VisualNormalization m_normalizationOption;
-
-      /// Data source for the visualisation.
-      Mantid::API::Workspace_sptr m_workspace;
-
-    };
-  }
+  /// Data source for the visualisation.
+  Mantid::API::Workspace_sptr m_workspace;
+};
+}
 }
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkPeakMarkerFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkPeakMarkerFactory.h
index 1f5c3fb244b54cdc5923a913eb9c443bb978630d..5b159f2e08f9abb26baf81397f1fee2ec15ec4e6 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkPeakMarkerFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkPeakMarkerFactory.h
@@ -10,7 +10,8 @@
   @author Janik Zikovsky
   @date 06/24/2011
 
-  Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -39,27 +40,23 @@
 
 class vtkPolyData;
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 // Forward dec.
-class ProgressAction; 
+class ProgressAction;
 
-class DLLExport vtkPeakMarkerFactory
-{
+class DLLExport vtkPeakMarkerFactory {
 public:
-
   /// Enum describing which dimension to show single-crystal peaks
-  enum ePeakDimensions
-  {
-    Peak_in_Q_lab, ///< Q in the lab frame
+  enum ePeakDimensions {
+    Peak_in_Q_lab,    ///< Q in the lab frame
     Peak_in_Q_sample, ///< Q in the sample frame (goniometer rotation taken out)
-    Peak_in_HKL ///< HKL miller indices
+    Peak_in_HKL       ///< HKL miller indices
   };
 
   /// Constructor
-  vtkPeakMarkerFactory(const std::string& scalarname, ePeakDimensions dimensions = Peak_in_Q_lab);
+  vtkPeakMarkerFactory(const std::string &scalarname,
+                       ePeakDimensions dimensions = Peak_in_Q_lab);
 
   /// Initialize the object with a workspace.
   virtual void initialize(Mantid::API::Workspace_sptr workspace);
@@ -67,8 +64,7 @@ public:
   /// Factory method
   vtkSmartPointer<vtkPolyData> create(ProgressAction &progressUpdating) const;
 
-  virtual std::string getFactoryTypeName() const
-  {
+  virtual std::string getFactoryTypeName() const {
     return "vtkPeakMarkerFactory";
   }
 
@@ -79,7 +75,6 @@ public:
   bool isPeaksWorkspaceIntegrated() const;
 
 protected:
-
   virtual void validate() const;
 
 private:
@@ -110,7 +105,7 @@ private:
   ePeakDimensions m_dimensionToShow;
 
   /// peak radius value.
-  double m_peakRadius; 
+  double m_peakRadius;
 };
 }
 }
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h
index accda9816f3f304456f6446990a9338fbbcba086..317650c0722616df2421f8ae8581a0eb7674a273 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkPolyDataAlgorithm_Silent.h
@@ -2,16 +2,16 @@
 #define VTKPOLYDATAALGORITHM_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkPolyDataAlgorithm.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKPOLYDATAALGORITHM_SILENT_H
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkRectilinearGrid_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkRectilinearGrid_Silent.h
index 4edb34aab96d4e115263c7c7885842742669778e..34d49aaf101de5d4cd6c86bce7daa1369f69bf48 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkRectilinearGrid_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkRectilinearGrid_Silent.h
@@ -2,16 +2,16 @@
 #define VTKRECTILINEARGRID_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkRectilinearGrid.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKRECTILINEARGRID_SILENT_H
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSinglePeakMarker.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSinglePeakMarker.h
index a51f32bb1f0d2301130713c1ade8bbe87dc35d27..4a42613704c77dfc122e53ad8162b926e8f22f61 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSinglePeakMarker.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSinglePeakMarker.h
@@ -7,7 +7,8 @@
 
   @date 23/02/2015
 
-  Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+  National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -28,20 +29,17 @@
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
 
-
 class vtkPolyData;
 
-namespace Mantid
-{
-namespace VATES
-{
-  class DLLExport vtkSinglePeakMarker
-  {
-  public:
-    vtkSinglePeakMarker();
-    ~vtkSinglePeakMarker();
-    vtkPolyData* createSinglePeakMarker(double x, double y, double z, double radius);
-  };
+namespace Mantid {
+namespace VATES {
+class DLLExport vtkSinglePeakMarker {
+public:
+  vtkSinglePeakMarker();
+  ~vtkSinglePeakMarker();
+  vtkPolyData *createSinglePeakMarker(double x, double y, double z,
+                                      double radius);
+};
 }
 }
 #endif
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h
index 19bf462b48e9e83d490ab67588beb0d9e9e7a954..ef78869d3ea71352efbf352c69cfeb5e76e7a765 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h
@@ -148,7 +148,8 @@ private:
   mutable std::unique_ptr<bool[]> sliceMask;
 
   /// Implicit function to define which boxes to render.
-  mutable boost::shared_ptr<Mantid::Geometry::MDImplicitFunction> sliceImplicitFunction;
+  mutable boost::shared_ptr<Mantid::Geometry::MDImplicitFunction>
+      sliceImplicitFunction;
 
   /// Variable to hold sorted list, so sort doesn't have to be repeated
   mutable std::vector<Mantid::API::IMDNode *> m_sortedBoxes;
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredGrid_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredGrid_Silent.h
index 4c6a8a345c9b9671b87c67a74413a733554dbf6c..630e7d81e9e935440c03d06824b1dc6a5615fb9b 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredGrid_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredGrid_Silent.h
@@ -2,16 +2,16 @@
 #define VTKSTRUCTUREDGRID_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkStructuredGrid.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKSTRUCTUREDGRID_SILENT_H
diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredPoints_Silent.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredPoints_Silent.h
index 693811ca451edf919c068db50df6adb08dd4e39a..9ac2ecf5919d1a3114c00e17bdc25dd246958344 100644
--- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredPoints_Silent.h
+++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkStructuredPoints_Silent.h
@@ -2,16 +2,16 @@
 #define VTKSTRUCTUREDPOINTS_SILENT_H
 
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic push
-  #endif
-  #pragma GCC diagnostic ignored "-Wconversion"
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic push
+#endif
+#pragma GCC diagnostic ignored "-Wconversion"
 #endif
 #include <vtkStructuredPoints.h>
 #if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
-  #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
-    #pragma GCC diagnostic pop
-  #endif
+#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
+#pragma GCC diagnostic pop
+#endif
 #endif
 
 #endif // VTKSTRUCTUREDPOINTS_SILENT_H
diff --git a/Vates/VatesAPI/src/ADSWorkspaceProvider.cpp b/Vates/VatesAPI/src/ADSWorkspaceProvider.cpp
index a456082f231568cc145305f110320b0297121817..a198f450cb18f42bcffff0d986ccd6f075bc9cae 100644
--- a/Vates/VatesAPI/src/ADSWorkspaceProvider.cpp
+++ b/Vates/VatesAPI/src/ADSWorkspaceProvider.cpp
@@ -7,51 +7,43 @@
 
 using namespace Mantid::API;
 
-namespace Mantid
-{
-  namespace VATES
-  {
-      template<typename Workspace_Type>
-      ADSWorkspaceProvider<Workspace_Type>::ADSWorkspaceProvider()
-      {
-      }
-
-      template<typename Workspace_Type>
-      ADSWorkspaceProvider<Workspace_Type>::~ADSWorkspaceProvider()
-      {
-      }
-
-      template<typename Workspace_Type>
-      bool ADSWorkspaceProvider<Workspace_Type>::canProvideWorkspace(std::string wsName) const
-      {
-        bool bCanProvide = false;
-        try
-        {
-          bCanProvide = (NULL != AnalysisDataService::Instance().retrieveWS<Workspace_Type>(wsName));
-        }
-        catch(Mantid::Kernel::Exception::NotFoundError&)
-        {
-          bCanProvide = false;
-        }
-        return bCanProvide;
-      }
-
-      template<typename Workspace_Type>
-      Mantid::API::Workspace_sptr ADSWorkspaceProvider<Workspace_Type>::fetchWorkspace(std::string wsName) const
-      {
-        return AnalysisDataService::Instance().retrieveWS<Workspace_Type>(wsName);
-      }
+namespace Mantid {
+namespace VATES {
+template <typename Workspace_Type>
+ADSWorkspaceProvider<Workspace_Type>::ADSWorkspaceProvider() {}
+
+template <typename Workspace_Type>
+ADSWorkspaceProvider<Workspace_Type>::~ADSWorkspaceProvider() {}
+
+template <typename Workspace_Type>
+bool ADSWorkspaceProvider<Workspace_Type>::canProvideWorkspace(
+    std::string wsName) const {
+  bool bCanProvide = false;
+  try {
+    bCanProvide =
+        (NULL !=
+         AnalysisDataService::Instance().retrieveWS<Workspace_Type>(wsName));
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
+    bCanProvide = false;
+  }
+  return bCanProvide;
+}
 
-      template<typename Workspace_Type>
-      void ADSWorkspaceProvider<Workspace_Type>::disposeWorkspace(std::string wsName) const
-      {
-        AnalysisDataService::Instance().remove(wsName);
-      }
+template <typename Workspace_Type>
+Mantid::API::Workspace_sptr
+ADSWorkspaceProvider<Workspace_Type>::fetchWorkspace(std::string wsName) const {
+  return AnalysisDataService::Instance().retrieveWS<Workspace_Type>(wsName);
+}
 
-      //Templated assembled types.
-      template class ADSWorkspaceProvider<Mantid::API::IMDWorkspace>;
-      template class ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>;
-      template class ADSWorkspaceProvider<Mantid::API::IMDHistoWorkspace>;
+template <typename Workspace_Type>
+void ADSWorkspaceProvider<Workspace_Type>::disposeWorkspace(
+    std::string wsName) const {
+  AnalysisDataService::Instance().remove(wsName);
+}
 
-  }
+// Templated assembled types.
+template class ADSWorkspaceProvider<Mantid::API::IMDWorkspace>;
+template class ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>;
+template class ADSWorkspaceProvider<Mantid::API::IMDHistoWorkspace>;
+}
 }
diff --git a/Vates/VatesAPI/src/BoxInfo.cpp b/Vates/VatesAPI/src/BoxInfo.cpp
index 41c764d696f094686386d250cc1f2ddcc2acba3d..753962929ea3fc1f885a319b046f5a208e7d2797 100644
--- a/Vates/VatesAPI/src/BoxInfo.cpp
+++ b/Vates/VatesAPI/src/BoxInfo.cpp
@@ -4,29 +4,26 @@
 
 using namespace Mantid::API;
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 boost::optional<int> findRecursionDepthForTopLevelSplitting(
     const std::string &workspaceName,
-    std::unique_ptr<WorkspaceProvider> workspaceProvider)
-{
-    const int topLevelRecursionDepth = 1;
-    boost::optional<int> recursionDepth;
-    if (workspaceProvider->canProvideWorkspace(workspaceName)) {
-        auto workspace
-            = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(
-                workspaceProvider->fetchWorkspace(workspaceName));
-        auto boxController = workspace->getBoxController();
-        boost::optional<std::vector<size_t>> topLevelSplits
-            = boxController->getSplitTopInto();
-        if (boxController->getSplitTopInto()) {
-            recursionDepth = topLevelRecursionDepth;
-        }
+    std::unique_ptr<WorkspaceProvider> workspaceProvider) {
+  const int topLevelRecursionDepth = 1;
+  boost::optional<int> recursionDepth;
+  if (workspaceProvider->canProvideWorkspace(workspaceName)) {
+    auto workspace =
+        boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(
+            workspaceProvider->fetchWorkspace(workspaceName));
+    auto boxController = workspace->getBoxController();
+    boost::optional<std::vector<size_t>> topLevelSplits =
+        boxController->getSplitTopInto();
+    if (boxController->getSplitTopInto()) {
+      recursionDepth = topLevelRecursionDepth;
     }
-    return recursionDepth;
+  }
+  return recursionDepth;
 }
 }
 }
diff --git a/Vates/VatesAPI/src/Common.cpp b/Vates/VatesAPI/src/Common.cpp
index 173b0b595a979bcc601e85b621fd54225830d980..d1fe783ec642e0dd3e54f8f25ed1c29593a3f6c8 100644
--- a/Vates/VatesAPI/src/Common.cpp
+++ b/Vates/VatesAPI/src/Common.cpp
@@ -53,7 +53,8 @@ std::string convertAxesTitleToLatex(const std::string &toConvert) {
     converted = toConvert;
   }
 
-  // Finally if there are any spaces they will disappear in Mathmode, hence we need to replace
+  // Finally if there are any spaces they will disappear in Mathmode, hence we
+  // need to replace
   // any space with $ $.
   boost::regex re(" ");
   converted = boost::regex_replace(converted, re, "$ $");
diff --git a/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp b/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
index c460860c20f6a6c6c8307e0dd2791eba6845c1bb..016f820a6ba011091d3e5910ed36918b6691e3a7 100644
--- a/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
+++ b/Vates/VatesAPI/src/CompositePeaksPresenterVsi.cpp
@@ -12,7 +12,8 @@ namespace VATES {
  * Update the view frustum
  * @param frustum The view frustum
  */
-void CompositePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustum) {
+void CompositePeaksPresenterVsi::updateViewFrustum(
+    ViewFrustum_const_sptr frustum) {
   for (const auto &presenter : m_peaksPresenters) {
     presenter->updateViewFrustum(frustum);
   }
@@ -22,7 +23,7 @@ void CompositePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustu
 *Get the viewable peaks. Essentially copied from the slice viewer.
 *@returns A vector indicating which of the peaks are viewable.
 */
-std::vector<bool> CompositePeaksPresenterVsi::getViewablePeaks() const{
+std::vector<bool> CompositePeaksPresenterVsi::getViewablePeaks() const {
   return std::vector<bool>();
 }
 
@@ -30,7 +31,8 @@ std::vector<bool> CompositePeaksPresenterVsi::getViewablePeaks() const{
  * Get the name of all peaks workspaces as a vector
  * @returns A vector of all peaks workspace names.
  */
-std::vector<std::string> CompositePeaksPresenterVsi::getPeaksWorkspaceNames() const{
+std::vector<std::string>
+CompositePeaksPresenterVsi::getPeaksWorkspaceNames() const {
   std::vector<std::string> peaksWorkspaceNames;
   for (const auto &presenter : m_peaksPresenters) {
     peaksWorkspaceNames.push_back(presenter->getPeaksWorkspaceName());
@@ -64,7 +66,7 @@ void CompositePeaksPresenterVsi::getPeaksInfo(
  * workspace needs to be probed.
  * @returns The coordinate frame.
  */
-std::string CompositePeaksPresenterVsi::getFrame() const{
+std::string CompositePeaksPresenterVsi::getFrame() const {
   std::string frame;
   if (!m_peaksPresenters.empty())
     frame = m_peaksPresenters[0]->getFrame();
@@ -99,7 +101,7 @@ CompositePeaksPresenterVsi::getPeaksWorkspaces() const {
  * @returns A vector of bool-vectors for each peaks presenter.
  */
 std::map<std::string, std::vector<bool>>
-CompositePeaksPresenterVsi::getInitializedViewablePeaks() const{
+CompositePeaksPresenterVsi::getInitializedViewablePeaks() const {
   std::map<std::string, std::vector<bool>> viewablePeaks;
   for (const auto &presenter : m_peaksPresenters) {
     viewablePeaks.emplace(
@@ -153,7 +155,8 @@ bool CompositePeaksPresenterVsi::hasPeaks() {
 /**
  * Sort the peak workpace by the specified column
  * @param columnToSortBy The column by which the workspace is to be sorted.
- * @param sortedAscending If the column is to be sorted in ascending or descending
+ * @param sortedAscending If the column is to be sorted in ascending or
+ * descending
  * order.
  * @param peaksWS The peak workspace which is being sorted.
  */
diff --git a/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp b/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
index 957500ebf338efb24bc26693d4c14d2993dc5c60..444bd47d63b60aebb0a7aec1cb0e6321d22d5453 100644
--- a/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
+++ b/Vates/VatesAPI/src/ConcretePeaksPresenterVsi.cpp
@@ -17,8 +17,8 @@ namespace VATES {
  * @param frame The coordinate frame
  */
 ConcretePeaksPresenterVsi::ConcretePeaksPresenterVsi(
-    Mantid::API::IPeaksWorkspace_sptr peaksWorkspace, ViewFrustum_const_sptr frustum,
-    std::string frame)
+    Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
+    ViewFrustum_const_sptr frustum, std::string frame)
     : m_viewableRegion(frustum), m_peaksWorkspace(peaksWorkspace),
       m_frame(frame) {}
 
@@ -29,7 +29,8 @@ ConcretePeaksPresenterVsi::~ConcretePeaksPresenterVsi() {}
  * Update the view frustum
  * @param frustum The view frustum.
  */
-void ConcretePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustum) {
+void ConcretePeaksPresenterVsi::updateViewFrustum(
+    ViewFrustum_const_sptr frustum) {
   m_viewableRegion = frustum;
 }
 
@@ -37,7 +38,7 @@ void ConcretePeaksPresenterVsi::updateViewFrustum(ViewFrustum_const_sptr frustum
  * Get the viewable peaks. Essentially copied from the slice viewer.
  * @returns A vector indicating which of the peaks are viewable.
  */
-std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const{
+std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const {
   // Need to apply a transform.
   // Don't bother to find peaks in the region if there are no peaks to find.
   Mantid::API::ITableWorkspace_sptr outTable;
@@ -78,7 +79,7 @@ std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const{
  * @returns A pointer to the underlying peaks workspace.
  */
 Mantid::API::IPeaksWorkspace_sptr
-ConcretePeaksPresenterVsi::getPeaksWorkspace() const{
+ConcretePeaksPresenterVsi::getPeaksWorkspace() const {
   return m_peaksWorkspace;
 }
 
@@ -86,13 +87,13 @@ ConcretePeaksPresenterVsi::getPeaksWorkspace() const{
  * Get the frame
  * @returns The frame.
  */
-std::string ConcretePeaksPresenterVsi::getFrame() const{ return m_frame; }
+std::string ConcretePeaksPresenterVsi::getFrame() const { return m_frame; }
 
 /**
  * Get the name of the underlying peaks workspace.
  * @returns The name of the peaks workspace.
  */
-std::string ConcretePeaksPresenterVsi::getPeaksWorkspaceName() const{
+std::string ConcretePeaksPresenterVsi::getPeaksWorkspaceName() const {
   return m_peaksWorkspace->getName();
 }
 
@@ -134,8 +135,8 @@ void ConcretePeaksPresenterVsi::getPeaksInfo(
  * @param shape The shape of a peak.
  * @returns The maximal radius of the peak.
  */
-double ConcretePeaksPresenterVsi::getMaxRadius (
-    Mantid::Geometry::PeakShape_sptr shape) const{
+double ConcretePeaksPresenterVsi::getMaxRadius(
+    Mantid::Geometry::PeakShape_sptr shape) const {
   const double defaultRadius = 1.0;
 
   boost::optional<double> radius =
diff --git a/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp
index 063648f792347813acb2754063728454e1ab0ec7..0c8c936ba7952169e6c7e3f487a32eaa459e8b3c 100644
--- a/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp
@@ -14,177 +14,181 @@
 
 #include <vtkUnstructuredGrid.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /*
-     Constructor
-     @param view : MVP view
-     @param filename : name of file to load
-     @throw invalid_argument if file name is empty
-     @throw invalid_arument if view is null
-     @throw logic_error if cannot use the reader-presenter for this filetype.
-     */
-  EventNexusLoadingPresenter::EventNexusLoadingPresenter(
-      std::unique_ptr<MDLoadingView> view, const std::string filename)
-      : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
-        m_wsTypeName("") {
-    if (this->m_filename.empty()) {
-      throw std::invalid_argument("File name is an empty string.");
-    }
-    if (nullptr == this->m_view) {
-      throw std::invalid_argument("View is NULL.");
-    }
+namespace Mantid {
+namespace VATES {
+/*
+ Constructor
+ @param view : MVP view
+ @param filename : name of file to load
+ @throw invalid_argument if file name is empty
+ @throw invalid_arument if view is null
+ @throw logic_error if cannot use the reader-presenter for this filetype.
+ */
+EventNexusLoadingPresenter::EventNexusLoadingPresenter(
+    std::unique_ptr<MDLoadingView> view, const std::string filename)
+    : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
+      m_wsTypeName("") {
+  if (this->m_filename.empty()) {
+    throw std::invalid_argument("File name is an empty string.");
+  }
+  if (nullptr == this->m_view) {
+    throw std::invalid_argument("View is NULL.");
   }
+}
 
-  /*
-   Indicates whether this presenter is capable of handling the type of file that
-   is attempted to be loaded.
-   @return false if the file cannot be read.
-   */
-  bool EventNexusLoadingPresenter::canReadFile() const {
-    if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) {
-      return 0;
-    }
+/*
+ Indicates whether this presenter is capable of handling the type of file that
+ is attempted to be loaded.
+ @return false if the file cannot be read.
+ */
+bool EventNexusLoadingPresenter::canReadFile() const {
+  if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) {
+    return 0;
+  }
 
-    std::unique_ptr<NeXus::File> file;
+  std::unique_ptr<NeXus::File> file;
+  try {
+    file = Kernel::make_unique<NeXus::File>(this->m_filename);
+    // All SNS (event or histo) nxs files have an entry named "entry"
     try {
-      file = Kernel::make_unique<NeXus::File>(this->m_filename);
-      // All SNS (event or histo) nxs files have an entry named "entry"
-      try {
-        file->openGroup("entry", "NXentry");
-      } catch (::NeXus::Exception &) {
-        file->close();
-        return 0;
-      }
-      // But only eventNexus files have bank123_events as a group name
-      std::map<std::string, std::string> entries = file->getEntries();
-      auto hasEvents = std::find_if(
-          entries.begin(), entries.end(),
-          [](const std::pair<std::string, std::string> &entry) {
-            return entry.first.find("_events") != std::string::npos;
-          });
+      file->openGroup("entry", "NXentry");
+    } catch (::NeXus::Exception &) {
       file->close();
-      return hasEvents != entries.end();
-    } catch (std::exception &e) {
-      std::cerr << "Could not open " << this->m_filename
-                << " as an EventNexus file because of exception: " << e.what()
-                << std::endl;
-      // Clean up, if possible
-      if (file)
-        file->close();
-    }
-    return 0;
+      return 0;
     }
+    // But only eventNexus files have bank123_events as a group name
+    std::map<std::string, std::string> entries = file->getEntries();
+    auto hasEvents =
+        std::find_if(entries.begin(), entries.end(),
+                     [](const std::pair<std::string, std::string> &entry) {
+                       return entry.first.find("_events") != std::string::npos;
+                     });
+    file->close();
+    return hasEvents != entries.end();
+  } catch (std::exception &e) {
+    std::cerr << "Could not open " << this->m_filename
+              << " as an EventNexus file because of exception: " << e.what()
+              << std::endl;
+    // Clean up, if possible
+    if (file)
+      file->close();
+  }
+  return 0;
+}
 
-    /*
-     Executes the underlying algorithm to create the MVP model.
-     @param factory : visualisation factory to use.
-     @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses.
-     @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs.
-     */
-    vtkSmartPointer<vtkDataSet>
-    EventNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
-                                        ProgressAction &loadingProgressUpdate,
-                                        ProgressAction &drawingProgressUpdate) {
-      using namespace Mantid::API;
-      using namespace Mantid::Geometry;
-
-      this->m_view->getLoadInMemory(); //TODO, nexus reader algorithm currently has no use of this.
-
-      if (this->shouldLoad())
-      {
-        Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification> observer(
-            loadingProgressUpdate, &ProgressAction::handler);
-        AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-
-        Algorithm_sptr loadAlg = AlgorithmManager::Instance().createUnmanaged("LoadEventNexus");
-        loadAlg->initialize();
-        loadAlg->setChild(true);
-        loadAlg->setPropertyValue("Filename", this->m_filename);
-        loadAlg->setPropertyValue("OutputWorkspace", "temp_ws");
-        loadAlg->addObserver(observer);
-        loadAlg->executeAsChildAlg();
-        loadAlg->removeObserver(observer);
-
-        Workspace_sptr temp = loadAlg->getProperty("OutputWorkspace");
-        IEventWorkspace_sptr tempWS = boost::dynamic_pointer_cast<IEventWorkspace>(temp);
-
-        Algorithm_sptr convertAlg = AlgorithmManager::Instance().createUnmanaged(
-            "ConvertToDiffractionMDWorkspace", 1);
-        convertAlg->initialize();
-        convertAlg->setChild(true);
-        convertAlg->setProperty("InputWorkspace", tempWS);
-        convertAlg->setProperty<bool>("ClearInputWorkspace", false);
-        convertAlg->setProperty<bool>("LorentzCorrection", true);
-        convertAlg->setPropertyValue("OutputWorkspace", "converted_ws");
-        convertAlg->addObserver(observer);
-        convertAlg->executeAsChildAlg();
-        convertAlg->removeObserver(observer);
-
-        IMDEventWorkspace_sptr outWS = convertAlg->getProperty("OutputWorkspace");
-        AnalysisDataService::Instance().addOrReplace("MD_EVENT_WS_ID", outWS);
-      }
-
-      Workspace_sptr result = AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-      Mantid::API::IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<
-          Mantid::API::IMDEventWorkspace>(result);
-      m_wsTypeName = eventWs->id();
-
-      factory->setRecursionDepth(this->m_view->getRecursionDepth());
-      auto visualDataSet = factory->oneStepCreate(
-          eventWs, drawingProgressUpdate); // HACK: progressUpdate should be
-                                           // argument for drawing!
-
-      this->extractMetadata(*eventWs);
-      this->appendMetadata(visualDataSet, eventWs->getName());
-
-      return visualDataSet;
-    }
+/*
+ Executes the underlying algorithm to create the MVP model.
+ @param factory : visualisation factory to use.
+ @param loadingProgressUpdate : Handler for GUI updates while algorithm
+ progresses.
+ @param drawingProgressUpdate : Handler for GUI updates while
+ vtkDataSetFactory::create occurs.
+ */
+vtkSmartPointer<vtkDataSet>
+EventNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
+                                    ProgressAction &loadingProgressUpdate,
+                                    ProgressAction &drawingProgressUpdate) {
+  using namespace Mantid::API;
+  using namespace Mantid::Geometry;
+
+  this->m_view->getLoadInMemory(); // TODO, nexus reader algorithm currently has
+                                   // no use of this.
+
+  if (this->shouldLoad()) {
+    Poco::NObserver<ProgressAction,
+                    Mantid::API::Algorithm::ProgressNotification>
+        observer(loadingProgressUpdate, &ProgressAction::handler);
+    AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+
+    Algorithm_sptr loadAlg =
+        AlgorithmManager::Instance().createUnmanaged("LoadEventNexus");
+    loadAlg->initialize();
+    loadAlg->setChild(true);
+    loadAlg->setPropertyValue("Filename", this->m_filename);
+    loadAlg->setPropertyValue("OutputWorkspace", "temp_ws");
+    loadAlg->addObserver(observer);
+    loadAlg->executeAsChildAlg();
+    loadAlg->removeObserver(observer);
+
+    Workspace_sptr temp = loadAlg->getProperty("OutputWorkspace");
+    IEventWorkspace_sptr tempWS =
+        boost::dynamic_pointer_cast<IEventWorkspace>(temp);
+
+    Algorithm_sptr convertAlg = AlgorithmManager::Instance().createUnmanaged(
+        "ConvertToDiffractionMDWorkspace", 1);
+    convertAlg->initialize();
+    convertAlg->setChild(true);
+    convertAlg->setProperty("InputWorkspace", tempWS);
+    convertAlg->setProperty<bool>("ClearInputWorkspace", false);
+    convertAlg->setProperty<bool>("LorentzCorrection", true);
+    convertAlg->setPropertyValue("OutputWorkspace", "converted_ws");
+    convertAlg->addObserver(observer);
+    convertAlg->executeAsChildAlg();
+    convertAlg->removeObserver(observer);
+
+    IMDEventWorkspace_sptr outWS = convertAlg->getProperty("OutputWorkspace");
+    AnalysisDataService::Instance().addOrReplace("MD_EVENT_WS_ID", outWS);
+  }
 
-    /**
-     @return boolean indicating whether the T dimension is available.
-     @throw runtime_error if execute has not been run first.
-     */
-    bool EventNexusLoadingPresenter::hasTDimensionAvailable() const
-    {
-      return false; //OneStepMDEW uses ConvertToDiffractionMDWorkspace, which always generates 3 dimensional MDEW
-    }
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  Mantid::API::IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
+  m_wsTypeName = eventWs->id();
 
-    /*
-     @return timestep values.
-     @throw runtime_error if execute has not been run first.
-     */
-    std::vector<double> EventNexusLoadingPresenter::getTimeStepValues() const
-    {
-      throw std::runtime_error("Does not have a 4th Dimension, so can be no T-axis");
-    }
+  factory->setRecursionDepth(this->m_view->getRecursionDepth());
+  auto visualDataSet = factory->oneStepCreate(
+      eventWs, drawingProgressUpdate); // HACK: progressUpdate should be
+                                       // argument for drawing!
 
-    /// Destructor
-    EventNexusLoadingPresenter::~EventNexusLoadingPresenter() {}
-
-    /**
-     Executes any meta-data loading required.
-     */
-    void EventNexusLoadingPresenter::executeLoadMetadata()
-    {
-      /*Effectively a do-nothing implementation. 
-
-       Do not have a metadataonly switch for the underlying algorithm, therfore would be costly to load metadata.
-       For these file types we know that we get 3 dimensions anyway so do not need anyfurther geometry information until the point
-       at which it must be added to the outgoing vtkdataset.
-       */
-      this->m_isSetup = true;
-    }
+  this->extractMetadata(*eventWs);
+  this->appendMetadata(visualDataSet, eventWs->getName());
 
-    /*
-     Getter for the workspace type name.
-     @return Workspace Type Name
-     */
-    std::string EventNexusLoadingPresenter::getWorkspaceTypeName()
-    {
-      return m_wsTypeName;
-    }
-  }
+  return visualDataSet;
+}
+
+/**
+ @return boolean indicating whether the T dimension is available.
+ @throw runtime_error if execute has not been run first.
+ */
+bool EventNexusLoadingPresenter::hasTDimensionAvailable() const {
+  return false; // OneStepMDEW uses ConvertToDiffractionMDWorkspace, which
+                // always generates 3 dimensional MDEW
+}
+
+/*
+ @return timestep values.
+ @throw runtime_error if execute has not been run first.
+ */
+std::vector<double> EventNexusLoadingPresenter::getTimeStepValues() const {
+  throw std::runtime_error(
+      "Does not have a 4th Dimension, so can be no T-axis");
+}
+
+/// Destructor
+EventNexusLoadingPresenter::~EventNexusLoadingPresenter() {}
+
+/**
+ Executes any meta-data loading required.
+ */
+void EventNexusLoadingPresenter::executeLoadMetadata() {
+  /*Effectively a do-nothing implementation.
+
+   Do not have a metadataonly switch for the underlying algorithm, therfore
+   would be costly to load metadata.
+   For these file types we know that we get 3 dimensions anyway so do not need
+   anyfurther geometry information until the point
+   at which it must be added to the outgoing vtkdataset.
+   */
+  this->m_isSetup = true;
+}
+
+/*
+ Getter for the workspace type name.
+ @return Workspace Type Name
+ */
+std::string EventNexusLoadingPresenter::getWorkspaceTypeName() {
+  return m_wsTypeName;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/FieldDataToMetadata.cpp b/Vates/VatesAPI/src/FieldDataToMetadata.cpp
index 157573e64d9b575cab8f08f1d360f6ae13d5af79..95565ff10ab531771e78db50022c8c46f50a2d7e 100644
--- a/Vates/VatesAPI/src/FieldDataToMetadata.cpp
+++ b/Vates/VatesAPI/src/FieldDataToMetadata.cpp
@@ -3,36 +3,29 @@
 #include "vtkFieldData.h"
 #include "vtkCharArray.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-std::string FieldDataToMetadata::operator()(vtkFieldData* fieldData, std::string id) const
-{
+std::string FieldDataToMetadata::operator()(vtkFieldData *fieldData,
+                                            std::string id) const {
   return execute(fieldData, id);
 }
 
-std::string FieldDataToMetadata::execute(vtkFieldData* fieldData, const std::string& id) const
-{
+std::string FieldDataToMetadata::execute(vtkFieldData *fieldData,
+                                         const std::string &id) const {
   std::string sXml;
-  if(fieldData == NULL)
-  {
+  if (fieldData == NULL) {
     throw std::runtime_error("vtkFieldData argument is null");
   }
-  vtkDataArray* arry =  fieldData->GetArray(id.c_str());
-  if(arry == NULL)
-  {
+  vtkDataArray *arry = fieldData->GetArray(id.c_str());
+  if (arry == NULL) {
     throw std::runtime_error("The specified vtk array does not exist");
   }
-  if (vtkCharArray* carry = dynamic_cast<vtkCharArray*> (arry))
-  {
+  if (vtkCharArray *carry = dynamic_cast<vtkCharArray *>(arry)) {
     carry->Squeeze();
-    for (int i = 0; i < carry->GetSize(); i++)
-    {
+    for (int i = 0; i < carry->GetSize(); i++) {
       char c = carry->GetValue(i);
-      if (int(c) > 1)
-      {
+      if (int(c) > 1) {
         sXml.push_back(c);
       }
     }
@@ -40,6 +33,5 @@ std::string FieldDataToMetadata::execute(vtkFieldData* fieldData, const std::str
   }
   return sXml;
 }
-
 }
 }
diff --git a/Vates/VatesAPI/src/IMDDimensionComparitor.cpp b/Vates/VatesAPI/src/IMDDimensionComparitor.cpp
index 2ca9a22ef94ab276f103cf69c102d84c9a8e6c56..f748933dd4ae06290d1f627057aee7da782f8503 100644
--- a/Vates/VatesAPI/src/IMDDimensionComparitor.cpp
+++ b/Vates/VatesAPI/src/IMDDimensionComparitor.cpp
@@ -1,65 +1,59 @@
 #include "MantidVatesAPI/IMDDimensionComparitor.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-    IMDDimensionComparitor::IMDDimensionComparitor(Mantid::API::IMDWorkspace_sptr workspace): m_workspace(workspace)
-    {
-    }
+IMDDimensionComparitor::IMDDimensionComparitor(
+    Mantid::API::IMDWorkspace_sptr workspace)
+    : m_workspace(workspace) {}
 
-    IMDDimensionComparitor::~IMDDimensionComparitor()
-    {
-    }
+IMDDimensionComparitor::~IMDDimensionComparitor() {}
 
-    bool IMDDimensionComparitor::isXDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension)
-    {
-      //Compare dimensions on the basis of their ids.
-      Mantid::Geometry::IMDDimension_const_sptr actualXDimension = m_workspace->getXDimension();
-      return queryDimension->getDimensionId() == actualXDimension->getDimensionId();
-    }
+bool IMDDimensionComparitor::isXDimension(
+    Mantid::Geometry::IMDDimension_const_sptr queryDimension) {
+  // Compare dimensions on the basis of their ids.
+  Mantid::Geometry::IMDDimension_const_sptr actualXDimension =
+      m_workspace->getXDimension();
+  return queryDimension->getDimensionId() == actualXDimension->getDimensionId();
+}
 
-    bool IMDDimensionComparitor::isYDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension)
-    {
-      Mantid::Geometry::IMDDimension_const_sptr actualYDimension = m_workspace->getYDimension();
-      if(NULL == actualYDimension.get())
-      {
-        return false; //MDImages may have 1 dimension or more.
-      }
-      else
-      {
-        //Compare dimensions on the basis of their ids.
-        return queryDimension->getDimensionId() == actualYDimension->getDimensionId();
-      }
-    }
+bool IMDDimensionComparitor::isYDimension(
+    Mantid::Geometry::IMDDimension_const_sptr queryDimension) {
+  Mantid::Geometry::IMDDimension_const_sptr actualYDimension =
+      m_workspace->getYDimension();
+  if (NULL == actualYDimension.get()) {
+    return false; // MDImages may have 1 dimension or more.
+  } else {
+    // Compare dimensions on the basis of their ids.
+    return queryDimension->getDimensionId() ==
+           actualYDimension->getDimensionId();
+  }
+}
 
-    bool IMDDimensionComparitor::isZDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension)
-    {
-      Mantid::Geometry::IMDDimension_const_sptr actualZDimension = m_workspace->getZDimension();
-      if(NULL == actualZDimension.get())
-      {
-        return false; //MDImages may have 1 dimension or more.
-      }
-      else
-      {
-        //Compare dimensions on the basis of their ids.
-        return queryDimension->getDimensionId() == actualZDimension->getDimensionId();
-      }
-    }
+bool IMDDimensionComparitor::isZDimension(
+    Mantid::Geometry::IMDDimension_const_sptr queryDimension) {
+  Mantid::Geometry::IMDDimension_const_sptr actualZDimension =
+      m_workspace->getZDimension();
+  if (NULL == actualZDimension.get()) {
+    return false; // MDImages may have 1 dimension or more.
+  } else {
+    // Compare dimensions on the basis of their ids.
+    return queryDimension->getDimensionId() ==
+           actualZDimension->getDimensionId();
+  }
+}
 
-    bool IMDDimensionComparitor::istDimension(Mantid::Geometry::IMDDimension_const_sptr  queryDimension)
-    {
-      Mantid::Geometry::IMDDimension_const_sptr actualtDimension = m_workspace->getTDimension();
-      if(NULL == actualtDimension.get())
-      {
-        return false; //MDImages may have 1 dimension or more.
-      }
-      else
-      {
-        //Compare dimensions on the basis of their ids.
-        return queryDimension->getDimensionId() == actualtDimension->getDimensionId();
-      }
-    }
+bool IMDDimensionComparitor::istDimension(
+    Mantid::Geometry::IMDDimension_const_sptr queryDimension) {
+  Mantid::Geometry::IMDDimension_const_sptr actualtDimension =
+      m_workspace->getTDimension();
+  if (NULL == actualtDimension.get()) {
+    return false; // MDImages may have 1 dimension or more.
+  } else {
+    // Compare dimensions on the basis of their ids.
+    return queryDimension->getDimensionId() ==
+           actualtDimension->getDimensionId();
   }
+}
+}
 }
\ No newline at end of file
diff --git a/Vates/VatesAPI/src/IgnoreZerosThresholdRange.cpp b/Vates/VatesAPI/src/IgnoreZerosThresholdRange.cpp
index 5477f8839091c1c765b1eadf9e7270fc9434b05a..949ffb5f2e6be798db99977f2a912da2773aa1a2 100644
--- a/Vates/VatesAPI/src/IgnoreZerosThresholdRange.cpp
+++ b/Vates/VatesAPI/src/IgnoreZerosThresholdRange.cpp
@@ -1,89 +1,67 @@
 #include "MantidVatesAPI/IgnoreZerosThresholdRange.h"
 #include <stdexcept>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-    /**
-    Constructor.
-    */
-    IgnoreZerosThresholdRange::IgnoreZerosThresholdRange() : m_min(1), m_max(1)
-    {
-    }
+/**
+Constructor.
+*/
+IgnoreZerosThresholdRange::IgnoreZerosThresholdRange() : m_min(1), m_max(1) {}
 
-     /**
-    Constructor.
-    */
-    IgnoreZerosThresholdRange::IgnoreZerosThresholdRange(signal_t min, signal_t max) : m_min(min), m_max(max)
-    {
-    }
+/**
+Constructor.
+*/
+IgnoreZerosThresholdRange::IgnoreZerosThresholdRange(signal_t min, signal_t max)
+    : m_min(min), m_max(max) {}
 
-    /**
-    Indicates wheter execution has occured or not.
-    return : true always.
-    */
-    bool IgnoreZerosThresholdRange::hasCalculated() const
-    {
-      return true;
-    }
+/**
+Indicates wheter execution has occured or not.
+return : true always.
+*/
+bool IgnoreZerosThresholdRange::hasCalculated() const { return true; }
 
-    /**
-    Destructor.
-    */
-    IgnoreZerosThresholdRange::~IgnoreZerosThresholdRange()
-    {
-    }
+/**
+Destructor.
+*/
+IgnoreZerosThresholdRange::~IgnoreZerosThresholdRange() {}
 
-    /**
-    Do nothing calculate method.
-    */
-    void IgnoreZerosThresholdRange::calculate()
-    {
-    }
+/**
+Do nothing calculate method.
+*/
+void IgnoreZerosThresholdRange::calculate() {}
 
-    /**
-    Minimum value getter.
-    @return The minimum value.
-    */
-    double IgnoreZerosThresholdRange::getMinimum() const
-    {
-      return m_min;
-    }
+/**
+Minimum value getter.
+@return The minimum value.
+*/
+double IgnoreZerosThresholdRange::getMinimum() const { return m_min; }
 
-    /**
-    Maximum value getter.
-    @return The maximum value.
-    */
-    double IgnoreZerosThresholdRange::getMaximum() const
-    {
-      return m_max;
-    }
+/**
+Maximum value getter.
+@return The maximum value.
+*/
+double IgnoreZerosThresholdRange::getMaximum() const { return m_max; }
 
+/**
+Virtual constructor clone method.
+@return clone of original.
+*/
+IgnoreZerosThresholdRange *IgnoreZerosThresholdRange::clone() const {
+  return new IgnoreZerosThresholdRange(this->m_min, this->m_max);
+}
 
-    /**
-    Virtual constructor clone method.
-    @return clone of original.
-    */
-    IgnoreZerosThresholdRange* IgnoreZerosThresholdRange::clone() const
-    {
-      return new IgnoreZerosThresholdRange(this->m_min, this->m_max);
-    }
-
-    /**
-    Determine whether the signal is withing range.
-    @param signal value
-    @return true if the signal is in the range defined by this object.
-    */
-    bool IgnoreZerosThresholdRange::inRange(const signal_t& signal)
-    {
-      m_max = signal > m_max ? signal : m_max; //cache min and max values.
-      if(signal < m_min && 0 != signal)
-      {
-        m_min = signal < m_min ? signal : m_min;
-      }
-      return signal != 0;
-    }
+/**
+Determine whether the signal is withing range.
+@param signal value
+@return true if the signal is in the range defined by this object.
+*/
+bool IgnoreZerosThresholdRange::inRange(const signal_t &signal) {
+  m_max = signal > m_max ? signal : m_max; // cache min and max values.
+  if (signal < m_min && 0 != signal) {
+    m_min = signal < m_min ? signal : m_min;
   }
+  return signal != 0;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/LoadVTK.cpp b/Vates/VatesAPI/src/LoadVTK.cpp
index 69be52cf9b8e933b51facb99337611e5d8d5ee94..b7c73d576eaaab11b84cb5aa23a49d18114dee39 100644
--- a/Vates/VatesAPI/src/LoadVTK.cpp
+++ b/Vates/VatesAPI/src/LoadVTK.cpp
@@ -1,37 +1,55 @@
 /*WIKI*
 
-Loads a legacy binary format VTK uniform structured image as an MDWorkspace. Allows the user to provide the name of two scalar arrays expected to be
-located on the PointData. One array is loaded as the MDWorkspace signal data and is mandatory. The other array is optional and provides the error squared data.
+Loads a legacy binary format VTK uniform structured image as an MDWorkspace.
+Allows the user to provide the name of two scalar arrays expected to be
+located on the PointData. One array is loaded as the MDWorkspace signal data and
+is mandatory. The other array is optional and provides the error squared data.
 Both arrays are expected to be of the type vtkUnsignedShortArray.
 
 == Choosing Output Types ==
 
 === Direct Image Format ===
-If the AdaptiveBinned parameter is off, the data is loaded into Mantid's multidimensional image format as an [[MDHistoWorkspace]]. All data
-in the file is loaded verbatim. This is not a lossy process, so sparse regions of data are carried through to Mantid. This can lead to very large in-memory
-object sizes. The algorithm will abort before the data is converted, if it is determined that you have insufficient resources. Loading data in this format
-is suitable for usage with the [[SliceViewer|Slice Viewer]], but users should not try to visualise large workspaces of this type using the 3D visualisation tools
-[[VatesSimpleInterface_v2|Vates Simple Interface]], as this is designed for use with sparse datasets of moderate size.
-
-Unless it is very important that all data is loaded, we recommend that you switch the AdaptiveBinned parameter on (see below).
+If the AdaptiveBinned parameter is off, the data is loaded into Mantid's
+multidimensional image format as an [[MDHistoWorkspace]]. All data
+in the file is loaded verbatim. This is not a lossy process, so sparse regions
+of data are carried through to Mantid. This can lead to very large in-memory
+object sizes. The algorithm will abort before the data is converted, if it is
+determined that you have insufficient resources. Loading data in this format
+is suitable for usage with the [[SliceViewer|Slice Viewer]], but users should
+not try to visualise large workspaces of this type using the 3D visualisation
+tools
+[[VatesSimpleInterface_v2|Vates Simple Interface]], as this is designed for use
+with sparse datasets of moderate size.
+
+Unless it is very important that all data is loaded, we recommend that you
+switch the AdaptiveBinned parameter on (see below).
 
 === Adaptive Rebinned Format ===
-For the majority of problems encountered with visualisation of neutron data, regions of interest occupy a very small fraction of otherwise empty/noisy space. It
-therefore makes sense to focus high resolution in the regions of interest rather than wasting resources storing sparse data. The [[MDEventWorkspace]] format naturally
+For the majority of problems encountered with visualisation of neutron data,
+regions of interest occupy a very small fraction of otherwise empty/noisy space.
+It
+therefore makes sense to focus high resolution in the regions of interest rather
+than wasting resources storing sparse data. The [[MDEventWorkspace]] format
+naturally
 recursively splits itself up where there are high numbers of observations.
 
-For imaging, we highly recommend using the AdaptiveBinned parameter set on, in combination with the KeepTopPercent parameter.
+For imaging, we highly recommend using the AdaptiveBinned parameter set on, in
+combination with the KeepTopPercent parameter.
 
-The [[MDEventWorkspace]] can be rebinned to a regular grid using [[SliceMD]] and [[BinMD]] both the [[SliceViewer|Slice Viewer]] and the [[VatesSimpleInterface_v2|Vates Simple Interface]]
+The [[MDEventWorkspace]] can be rebinned to a regular grid using [[SliceMD]] and
+[[BinMD]] both the [[SliceViewer|Slice Viewer]] and the
+[[VatesSimpleInterface_v2|Vates Simple Interface]]
 support rebinning in-situ as part of the visualisation process.
 *WIKI*/
 /*WIKI_USAGE*
 ==Adaptive Binning Example==
- outputs = LoadVTK(Filename='fly.vtk',SignalArrayName='volume_scalars',AdaptiveBinned=True)
+ outputs =
+LoadVTK(Filename='fly.vtk',SignalArrayName='volume_scalars',AdaptiveBinned=True)
  demo = outputs[0]
  plotSlice(source=demo)
 ==Direct Conversion Example==
- outputs = LoadVTK(Filename='fly.vtk',SignalArrayName='volume_scalars',AdaptiveBinned=False)
+ outputs =
+LoadVTK(Filename='fly.vtk',SignalArrayName='volume_scalars',AdaptiveBinned=False)
  demo = outputs[0]
  plotSlice(source=demo)
 
@@ -62,298 +80,285 @@ using namespace Mantid::API;
 using namespace Mantid::DataObjects;
 using namespace Mantid::Geometry;
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    DECLARE_FILELOADER_ALGORITHM(LoadVTK)
-
-    /**
-     * Return the confidence with with this algorithm can load the file
-     * @param descriptor A descriptor for the file
-     * @returns An integer specifying the confidence level. 0 indicates it will not be used
-     */
-    int LoadVTK::confidence(Kernel::FileDescriptor & descriptor) const
-    {
-      const std::string & fileExt = descriptor.extension();
-      const bool isntAscii = !descriptor.isAscii();
-      int confidence(0);
-      if (isntAscii && fileExt == ".vtk")
-      {
-        confidence = 80;
-      }
-      else if (fileExt == ".vtk")
-      {
-        confidence = 60;
-      }
-      else if (isntAscii)
-      {
-        confidence = 15;
-      }
-      else
-      {
-        confidence = 0;
-      }
-      return confidence;
-    }
-    const std::string LoadVTK::name() const
-    {
-      return "LoadVTK";
-    }
-
-    int LoadVTK::version() const
-    {
-      return 1;
-    }
+namespace Mantid {
+namespace VATES {
+DECLARE_FILELOADER_ALGORITHM(LoadVTK)
+
+/**
+ * Return the confidence with with this algorithm can load the file
+ * @param descriptor A descriptor for the file
+ * @returns An integer specifying the confidence level. 0 indicates it will not
+ * be used
+ */
+int LoadVTK::confidence(Kernel::FileDescriptor &descriptor) const {
+  const std::string &fileExt = descriptor.extension();
+  const bool isntAscii = !descriptor.isAscii();
+  int confidence(0);
+  if (isntAscii && fileExt == ".vtk") {
+    confidence = 80;
+  } else if (fileExt == ".vtk") {
+    confidence = 60;
+  } else if (isntAscii) {
+    confidence = 15;
+  } else {
+    confidence = 0;
+  }
+  return confidence;
+}
+const std::string LoadVTK::name() const { return "LoadVTK"; }
+
+int LoadVTK::version() const { return 1; }
+
+const std::string LoadVTK::category() const { return "MDAlgorithms"; }
+
+void LoadVTK::init() {
+  std::vector<std::string> exts;
+  exts.push_back("vtk");
+  this->declareProperty(
+      Kernel::make_unique<FileProperty>("Filename", "", FileProperty::Load,
+                                        exts),
+      "Binary legacy VTK uniform structured image file to load.");
+
+  auto manditorySignalArrayName =
+      boost::make_shared<MandatoryValidator<std::string>>();
+
+  this->declareProperty("SignalArrayName", "", manditorySignalArrayName,
+                        "Point data array name to import as signal/intesity "
+                        "values in the MD workspace.");
+  this->declareProperty("ErrorSQArrayName", "", "Point data array name to "
+                                                "import as error squared "
+                                                "values in the MD workspace.");
+
+  this->declareProperty("AdaptiveBinned", true,
+                        "What type of output workspace to produce. If selected "
+                        "produces an [[MDEventWorkspace]], otherwise an "
+                        "[[MDHistoWorkspace]] is made.");
+
+  auto rangeValidator = boost::make_shared<BoundedValidator<double>>(0, 100);
+  this->declareProperty("KeepTopPercent", 25.0, rangeValidator,
+                        "Only keep the top percentage of SignalArray values in "
+                        "the range min to max. Allow sparse regions to be "
+                        "ignored. Defaults to 25%.");
+
+  setPropertySettings("KeepTopPercent", make_unique<EnabledWhenProperty>(
+                                            "AdaptiveBinned", IS_DEFAULT));
+
+  declareProperty(Kernel::make_unique<WorkspaceProperty<IMDWorkspace>>(
+                      "OutputWorkspace", "", Direction::Output),
+                  "MDWorkspace equivalent of vtkStructuredPoints input.");
+
+  declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
+                      "SignalMaximum", 0, Direction::Output),
+                  "Maximum signal value determined from input array.");
+  declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
+                      "SignalMinimum", 0, Direction::Output),
+                  "Minimum signal value determined from input array.");
+  declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
+                      "SignalThreshold", 0, Direction::Output),
+                  "Actual calculated signal threshold determined from "
+                  "minimum, and maximum signal.");
+}
 
-    const std::string LoadVTK::category() const
-    {
-      return "MDAlgorithms";
+void LoadVTK::execMDHisto(vtkUnsignedShortArray *signals,
+                          vtkUnsignedShortArray *errorsSQ,
+                          MDHistoDimension_sptr dimX,
+                          MDHistoDimension_sptr dimY,
+                          MDHistoDimension_sptr dimZ, Progress &prog,
+                          const int64_t nPoints, const int64_t frequency) {
+  MemoryStats memoryStats;
+  const size_t freeMemory = memoryStats.availMem(); // in kB
+  const size_t memoryCost =
+      MDHistoWorkspace::sizeOfElement() * nPoints / 1000; // in kB
+  if (memoryCost > freeMemory) {
+    std::string basicMessage =
+        "Loading this file requires more free memory than you have available.";
+    std::stringstream sstream;
+    sstream << basicMessage << " Requires " << memoryCost
+            << " KB of contiguous memory. You have " << freeMemory << " KB.";
+    g_log.notice(sstream.str());
+    throw std::runtime_error(basicMessage);
+  }
+
+  prog.report("Converting to MD Histogram Workspace");
+  MDHistoWorkspace_sptr outputWS =
+      boost::make_shared<MDHistoWorkspace>(dimX, dimY, dimZ);
+
+  // cppcheck-suppress unreadVariable
+  double *destinationSignals = outputWS->getSignalArray();
+  double *destinationErrorsSQ = outputWS->getErrorSquaredArray();
+
+  if (errorsSQ == NULL) {
+    PARALLEL_FOR_NO_WSP_CHECK()
+    for (int64_t i = 0; i < nPoints; ++i) {
+      PARALLEL_START_INTERUPT_REGION
+      // cppcheck-suppress unreadVariable
+      destinationSignals[i] = signals->GetValue(i);
+      if (i % frequency == 0)
+        prog.report();
+      PARALLEL_END_INTERUPT_REGION
     }
-
-    void LoadVTK::init()
-    {
-      std::vector<std::string> exts;
-      exts.push_back("vtk");
-      this->declareProperty(
-          Kernel::make_unique<FileProperty>("Filename", "", FileProperty::Load,
-                                            exts),
-          "Binary legacy VTK uniform structured image file to load.");
-
-      auto manditorySignalArrayName = boost::make_shared<MandatoryValidator<std::string> >();
-
-      this->declareProperty("SignalArrayName", "", manditorySignalArrayName,
-          "Point data array name to import as signal/intesity values in the MD workspace.");
-      this->declareProperty("ErrorSQArrayName", "",
-          "Point data array name to import as error squared values in the MD workspace.");
-
-      this->declareProperty("AdaptiveBinned", true, "What type of output workspace to produce. If selected produces an [[MDEventWorkspace]], otherwise an [[MDHistoWorkspace]] is made.");
-
-      auto rangeValidator = boost::make_shared<BoundedValidator<double> >(0, 100);
-      this->declareProperty("KeepTopPercent", 25.0, rangeValidator, "Only keep the top percentage of SignalArray values in the range min to max. Allow sparse regions to be ignored. Defaults to 25%.");
-
-      setPropertySettings("KeepTopPercent", make_unique<EnabledWhenProperty>(
-                                                "AdaptiveBinned", IS_DEFAULT));
-
-      declareProperty(Kernel::make_unique<WorkspaceProperty<IMDWorkspace>>(
-                          "OutputWorkspace", "", Direction::Output),
-                      "MDWorkspace equivalent of vtkStructuredPoints input.");
-
-      declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
-                          "SignalMaximum", 0, Direction::Output),
-                      "Maximum signal value determined from input array.");
-      declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
-                          "SignalMinimum", 0, Direction::Output),
-                      "Minimum signal value determined from input array.");
-      declareProperty(Kernel::make_unique<PropertyWithValue<int>>(
-                          "SignalThreshold", 0, Direction::Output),
-                      "Actual calculated signal threshold determined from "
-                      "minimum, and maximum signal.");
+    PARALLEL_CHECK_INTERUPT_REGION
+  } else {
+    PARALLEL_FOR_NO_WSP_CHECK()
+    for (int64_t i = 0; i < nPoints; ++i) {
+      PARALLEL_START_INTERUPT_REGION
+      // cppcheck-suppress unreadVariable
+      destinationSignals[i] = signals->GetValue(i);
+      destinationErrorsSQ[i] = errorsSQ->GetValue(i);
+      if (i % frequency == 0)
+        prog.report();
+      PARALLEL_END_INTERUPT_REGION
     }
+    PARALLEL_CHECK_INTERUPT_REGION
+  }
 
-    void LoadVTK::execMDHisto(vtkUnsignedShortArray* signals, vtkUnsignedShortArray* errorsSQ, MDHistoDimension_sptr dimX, MDHistoDimension_sptr dimY, MDHistoDimension_sptr dimZ, Progress& prog, const int64_t nPoints, const int64_t frequency)
-    {
-      MemoryStats memoryStats;
-      const size_t freeMemory = memoryStats.availMem(); // in kB
-      const size_t memoryCost = MDHistoWorkspace::sizeOfElement() * nPoints / 1000; // in kB
-      if (memoryCost > freeMemory)
-      {
-      std::string basicMessage = "Loading this file requires more free memory than you have available.";
-      std::stringstream sstream;
-      sstream << basicMessage << " Requires " << memoryCost << " KB of contiguous memory. You have "
-      << freeMemory << " KB.";
-      g_log.notice(sstream.str());
-      throw std::runtime_error(basicMessage);
-      }
-
-      prog.report("Converting to MD Histogram Workspace");
-      MDHistoWorkspace_sptr outputWS = boost::make_shared<MDHistoWorkspace>(dimX, dimY, dimZ);
+  prog.report("Complete");
+  this->setProperty("OutputWorkspace", outputWS);
+}
 
-      // cppcheck-suppress unreadVariable
-      double* destinationSignals = outputWS->getSignalArray();
-      double* destinationErrorsSQ = outputWS->getErrorSquaredArray();
-
-      if (errorsSQ == NULL)
-      {
-        PARALLEL_FOR_NO_WSP_CHECK()
-        for (int64_t i = 0; i < nPoints; ++i)
-        {
-          PARALLEL_START_INTERUPT_REGION
-          // cppcheck-suppress unreadVariable
-          destinationSignals[i] = signals->GetValue(i);
-          if(i%frequency == 0)
-            prog.report();
-          PARALLEL_END_INTERUPT_REGION
+void LoadVTK::execMDEvent(vtkDataSet *readDataset,
+                          vtkUnsignedShortArray *signals,
+                          vtkUnsignedShortArray *errorsSQ,
+                          MDHistoDimension_sptr dimX,
+                          MDHistoDimension_sptr dimY,
+                          MDHistoDimension_sptr dimZ, Progress &prog,
+                          const int64_t nPoints, const int64_t frequency) {
+  unsigned int min = std::numeric_limits<unsigned int>::max();
+  unsigned int max = std::numeric_limits<unsigned int>::min();
+  for (unsigned int i = 0; i < readDataset->GetNumberOfPoints(); ++i) {
+    unsigned int cv = signals->GetValue(i);
+    min = std::min(cv, min);
+    max = std::max(cv, max);
+  }
+  const double keepTopPercent = getProperty("KeepTopPercent");
+  const double ditchBottomFraction = (1 - (keepTopPercent / 100));
+  double m = (max - min);
+  double c = min;
+  double lowerBounds = (m * ditchBottomFraction) + c;
+  setProperty("SignalMinimum", int(min));
+  setProperty("SignalMaximum", int(max));
+  setProperty("SignalThreshold", int(lowerBounds));
+
+  std::stringstream ss;
+  ss << "Range is Min: " << min << " Max: " << max << std::endl;
+  this->g_log.debug(ss.str());
+  ss.clear();
+  ss << "Signal Limit is: " << lowerBounds;
+  this->g_log.debug(ss.str());
+
+  prog.report("Converting to MD Event Workspace");
+  auto ws = boost::make_shared<MDEventWorkspace<MDLeanEvent<3>, 3>>();
+  auto bc = ws->getBoxController();
+  bc->setSplitInto(2);
+  bc->setSplitThreshold(10);
+  bc->setMaxDepth(7);
+  ws->addDimension(dimX);
+  ws->addDimension(dimY);
+  ws->addDimension(dimZ);
+  ws->initialize();
+
+  if (errorsSQ == NULL) {
+    PARALLEL_FOR1(ws)
+    for (int64_t i = 0; i < nPoints; ++i) {
+      PARALLEL_START_INTERUPT_REGION
+      double coordinates[3];
+      readDataset->GetPoint(i, coordinates);
+      float signal = signals->GetValue(i);
+
+      if (signal > lowerBounds) {
+        MDLeanEvent<3> event(signal, 0, coordinates);
+        ws->addEvent(event);
       }
-      PARALLEL_CHECK_INTERUPT_REGION
-     }
-     else
-     {
-       PARALLEL_FOR_NO_WSP_CHECK()
-       for (int64_t i = 0; i < nPoints; ++i)
-       {
-         PARALLEL_START_INTERUPT_REGION
-         // cppcheck-suppress unreadVariable
-         destinationSignals[i] = signals->GetValue(i);
-         destinationErrorsSQ[i] = errorsSQ->GetValue(i);
-         if(i%frequency == 0)
-           prog.report();
-         PARALLEL_END_INTERUPT_REGION
-       }
-       PARALLEL_CHECK_INTERUPT_REGION
-     }
-
-     prog.report("Complete");
-     this->setProperty("OutputWorkspace", outputWS);
+      if (i % frequency == 0)
+        prog.report();
+      PARALLEL_END_INTERUPT_REGION
     }
-
-    void LoadVTK::execMDEvent(vtkDataSet* readDataset, vtkUnsignedShortArray* signals, vtkUnsignedShortArray* errorsSQ, MDHistoDimension_sptr dimX, MDHistoDimension_sptr dimY, MDHistoDimension_sptr dimZ, Progress& prog, const int64_t nPoints, const int64_t frequency)
-    {
-      unsigned int min = std::numeric_limits<unsigned int>::max();
-      unsigned int max = std::numeric_limits<unsigned int>::min();
-      for (unsigned int i = 0; i < readDataset->GetNumberOfPoints(); ++i)
-      {
-        unsigned int  cv = signals->GetValue(i);
-        min = std::min(cv, min);
-        max = std::max(cv, max);
-      }
-      const double keepTopPercent = getProperty("KeepTopPercent");
-      const double ditchBottomFraction = (1 - (keepTopPercent/100));
-      double m = (max - min);
-      double c = min;
-      double lowerBounds =  (m * ditchBottomFraction) + c;
-      setProperty("SignalMinimum", int(min));
-      setProperty("SignalMaximum", int(max));
-      setProperty("SignalThreshold", int(lowerBounds));
-
-      std::stringstream ss;
-      ss << "Range is Min: " << min << " Max: " << max << std::endl;
-      this->g_log.debug(ss.str());
-      ss.clear();
-      ss << "Signal Limit is: " << lowerBounds;
-      this->g_log.debug(ss.str());
-
-      prog.report("Converting to MD Event Workspace");
-      auto ws = boost::make_shared<MDEventWorkspace<MDLeanEvent<3>, 3> >();
-      auto bc = ws->getBoxController();
-      bc->setSplitInto(2);
-      bc->setSplitThreshold(10);
-      bc->setMaxDepth(7);
-      ws->addDimension(dimX);
-      ws->addDimension(dimY);
-      ws->addDimension(dimZ);
-      ws->initialize();
-
-      if(errorsSQ == NULL)
-      {
-          PARALLEL_FOR1(ws)
-          for(int64_t i = 0; i < nPoints; ++i)
-          {
-            PARALLEL_START_INTERUPT_REGION
-            double coordinates[3];
-            readDataset->GetPoint(i, coordinates);
-            float signal = signals->GetValue(i);
-
-              if(signal > lowerBounds)
-              {
-                MDLeanEvent<3> event(signal, 0, coordinates);
-                ws->addEvent(event);
-              }
-              if(i%frequency == 0)
-                prog.report();
-            PARALLEL_END_INTERUPT_REGION
-          }
-          PARALLEL_CHECK_INTERUPT_REGION
-      }
-      else
-      {
-           PARALLEL_FOR1(ws)
-           for(int64_t i = 0; i < nPoints; ++i)
-           {
-             PARALLEL_START_INTERUPT_REGION
-             double coordinates[3];
-             readDataset->GetPoint(i, coordinates);
-             float signal = signals->GetValue(i);
-             float errorSQ = errorsSQ->GetValue(i);
-               if(signal > lowerBounds)
-               {
-                 MDLeanEvent<3> event(signal, errorSQ, coordinates);
-                 ws->addEvent(event);
-               }
-               if(i%frequency == 0)
-                 prog.report();
-             PARALLEL_END_INTERUPT_REGION
-           }
-           PARALLEL_CHECK_INTERUPT_REGION
+    PARALLEL_CHECK_INTERUPT_REGION
+  } else {
+    PARALLEL_FOR1(ws)
+    for (int64_t i = 0; i < nPoints; ++i) {
+      PARALLEL_START_INTERUPT_REGION
+      double coordinates[3];
+      readDataset->GetPoint(i, coordinates);
+      float signal = signals->GetValue(i);
+      float errorSQ = errorsSQ->GetValue(i);
+      if (signal > lowerBounds) {
+        MDLeanEvent<3> event(signal, errorSQ, coordinates);
+        ws->addEvent(event);
       }
-      ws->splitBox();
-      auto threadScheduler = new Kernel::ThreadSchedulerFIFO();
-      Kernel::ThreadPool threadPool(threadScheduler);
-      ws->splitAllIfNeeded(threadScheduler);
-      threadPool.joinAll();
-      ws->refreshCache();
-      setProperty("OutputWorkspace", ws);
-
+      if (i % frequency == 0)
+        prog.report();
+      PARALLEL_END_INTERUPT_REGION
     }
+    PARALLEL_CHECK_INTERUPT_REGION
+  }
+  ws->splitBox();
+  auto threadScheduler = new Kernel::ThreadSchedulerFIFO();
+  Kernel::ThreadPool threadPool(threadScheduler);
+  ws->splitAllIfNeeded(threadScheduler);
+  threadPool.joinAll();
+  ws->refreshCache();
+  setProperty("OutputWorkspace", ws);
+}
 
-    void LoadVTK::exec()
-    {
-      const std::string filename = getProperty("Filename");
-      const std::string signalArrayName = getProperty("SignalArrayName");
-      const std::string errorSQArrayName = getProperty("ErrorSQArrayName");
-      const bool adaptiveBinned = getProperty("AdaptiveBinned");
-
-      Progress prog(this, 0, 1, 102);
-      prog.report("Loading vtkFile");
-      auto reader = vtkStructuredPointsReader::New();
-      reader->SetFileName(filename.c_str());
-      reader->Update();
-
-      vtkSmartPointer<vtkStructuredPoints> readDataset;
-      readDataset.TakeReference(reader->GetOutput());
-
-      vtkUnsignedShortArray* signals = vtkUnsignedShortArray::SafeDownCast(
-          readDataset->GetPointData()->GetArray(signalArrayName.c_str()));
-       if (signals == NULL)
-       {
-         throw std::invalid_argument("Signal array: " + signalArrayName + " does not exist");
-       }
-
-       vtkUnsignedShortArray* errorsSQ = vtkUnsignedShortArray::SafeDownCast(
-           readDataset->GetPointData()->GetArray(errorSQArrayName.c_str()));
-       if (!errorSQArrayName.empty() && errorsSQ == NULL)
-       {
-         throw std::invalid_argument("Error squared array: " + errorSQArrayName + " does not exist");
-       }
-
-      int dimensions[3];
-      readDataset->GetDimensions(dimensions);
-      double bounds[6];
-      readDataset->ComputeBounds();
-      readDataset->GetBounds(bounds);
-      Mantid::Geometry::UnknownFrame frame("");
-      auto dimX = boost::make_shared<MDHistoDimension>("X", "X", frame,  static_cast<coord_t>(bounds[0]), static_cast<coord_t>(bounds[1]),
-          dimensions[0]);
-      auto dimY = boost::make_shared<MDHistoDimension>("Y", "Y", frame, static_cast<coord_t>(bounds[2]), static_cast<coord_t>(bounds[3]),
-          dimensions[1]);
-      auto dimZ = boost::make_shared<MDHistoDimension>("Z", "Z", frame, static_cast<coord_t>(bounds[4]), static_cast<coord_t>(bounds[5]),
-          dimensions[2]);
-
-      const int64_t nPoints = static_cast<int64_t>( readDataset->GetNumberOfPoints() );
-      int64_t frequency = nPoints;
-      if(nPoints > 100)
-      {
-        frequency = nPoints/100;
-      }
-
-      if(adaptiveBinned)
-      {
-        execMDEvent(readDataset, signals, errorsSQ, dimX, dimY, dimZ, prog, nPoints, frequency);
-      }
-      else
-      {
-        execMDHisto(signals, errorsSQ, dimX, dimY, dimZ, prog, nPoints, frequency);
-      }
+void LoadVTK::exec() {
+  const std::string filename = getProperty("Filename");
+  const std::string signalArrayName = getProperty("SignalArrayName");
+  const std::string errorSQArrayName = getProperty("ErrorSQArrayName");
+  const bool adaptiveBinned = getProperty("AdaptiveBinned");
+
+  Progress prog(this, 0, 1, 102);
+  prog.report("Loading vtkFile");
+  auto reader = vtkStructuredPointsReader::New();
+  reader->SetFileName(filename.c_str());
+  reader->Update();
+
+  vtkSmartPointer<vtkStructuredPoints> readDataset;
+  readDataset.TakeReference(reader->GetOutput());
+
+  vtkUnsignedShortArray *signals = vtkUnsignedShortArray::SafeDownCast(
+      readDataset->GetPointData()->GetArray(signalArrayName.c_str()));
+  if (signals == NULL) {
+    throw std::invalid_argument("Signal array: " + signalArrayName +
+                                " does not exist");
+  }
+
+  vtkUnsignedShortArray *errorsSQ = vtkUnsignedShortArray::SafeDownCast(
+      readDataset->GetPointData()->GetArray(errorSQArrayName.c_str()));
+  if (!errorSQArrayName.empty() && errorsSQ == NULL) {
+    throw std::invalid_argument("Error squared array: " + errorSQArrayName +
+                                " does not exist");
+  }
+
+  int dimensions[3];
+  readDataset->GetDimensions(dimensions);
+  double bounds[6];
+  readDataset->ComputeBounds();
+  readDataset->GetBounds(bounds);
+  Mantid::Geometry::UnknownFrame frame("");
+  auto dimX = boost::make_shared<MDHistoDimension>(
+      "X", "X", frame, static_cast<coord_t>(bounds[0]),
+      static_cast<coord_t>(bounds[1]), dimensions[0]);
+  auto dimY = boost::make_shared<MDHistoDimension>(
+      "Y", "Y", frame, static_cast<coord_t>(bounds[2]),
+      static_cast<coord_t>(bounds[3]), dimensions[1]);
+  auto dimZ = boost::make_shared<MDHistoDimension>(
+      "Z", "Z", frame, static_cast<coord_t>(bounds[4]),
+      static_cast<coord_t>(bounds[5]), dimensions[2]);
+
+  const int64_t nPoints =
+      static_cast<int64_t>(readDataset->GetNumberOfPoints());
+  int64_t frequency = nPoints;
+  if (nPoints > 100) {
+    frequency = nPoints / 100;
+  }
+
+  if (adaptiveBinned) {
+    execMDEvent(readDataset, signals, errorsSQ, dimX, dimY, dimZ, prog, nPoints,
+                frequency);
+  } else {
+    execMDHisto(signals, errorsSQ, dimX, dimY, dimZ, prog, nPoints, frequency);
+  }
 }
 }
 }
diff --git a/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp
index 032c24a95144b1b3838fa0b1342233ae50f893b7..e6140965d176d2b46e4698576b925a0965c35a15 100644
--- a/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp
@@ -11,137 +11,145 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include <vtkUnstructuredGrid.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    /*
-    Constructor
-    @param view : MVP view
-    @param filename : name of file to load
-    @throw invalid_argument if file name is empty
-    @throw invalid_arument if view is null
-    @throw logic_error if cannot use the reader-presenter for this filetype.
-    */
-  MDEWEventNexusLoadingPresenter::MDEWEventNexusLoadingPresenter(
-      std::unique_ptr<MDLoadingView> view, const std::string filename)
-      : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
-        m_wsTypeName("") {
-    if (this->m_filename.empty()) {
-      throw std::invalid_argument("File name is an empty string.");
-    }
-    if (nullptr == this->m_view) {
-      throw std::invalid_argument("View is NULL.");
-    }
+namespace Mantid {
+namespace VATES {
+
+/*
+Constructor
+@param view : MVP view
+@param filename : name of file to load
+@throw invalid_argument if file name is empty
+@throw invalid_arument if view is null
+@throw logic_error if cannot use the reader-presenter for this filetype.
+*/
+MDEWEventNexusLoadingPresenter::MDEWEventNexusLoadingPresenter(
+    std::unique_ptr<MDLoadingView> view, const std::string filename)
+    : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
+      m_wsTypeName("") {
+  if (this->m_filename.empty()) {
+    throw std::invalid_argument("File name is an empty string.");
+  }
+  if (nullptr == this->m_view) {
+    throw std::invalid_argument("View is NULL.");
+  }
+}
+
+/*
+Indicates whether this presenter is capable of handling the type of file that
+is attempted to be loaded.
+@return false if the file cannot be read.
+*/
+bool MDEWEventNexusLoadingPresenter::canReadFile() const {
+  // Quick check based on extension.
+  if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) {
+    return 0;
   }
 
-  /*
- Indicates whether this presenter is capable of handling the type of file that
- is attempted to be loaded.
- @return false if the file cannot be read.
- */
-  bool MDEWEventNexusLoadingPresenter::canReadFile() const {
-    // Quick check based on extension.
-    if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) {
-      return 0;
-    }
-
-    ::NeXus::File *file = NULL;
-
-    file = new ::NeXus::File(this->m_filename);
-    // MDEventWorkspace file has a different name for the entry
-    try {
-      file->openGroup("MDEventWorkspace", "NXentry");
-      file->close();
-      return 1;
-    } catch (::NeXus::Exception &) {
-      // If the entry name does not match, then it can't read the file.
-      file->close();
-      return 0;
-    }
+  ::NeXus::File *file = NULL;
+
+  file = new ::NeXus::File(this->m_filename);
+  // MDEventWorkspace file has a different name for the entry
+  try {
+    file->openGroup("MDEventWorkspace", "NXentry");
+    file->close();
+    return 1;
+  } catch (::NeXus::Exception &) {
+    // If the entry name does not match, then it can't read the file.
+    file->close();
     return 0;
-    }
-
-    /*
-    Executes the underlying algorithm to create the MVP model.
-    @param factory : visualisation factory to use.
-    @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses.
-    @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs.
-    */
-    vtkSmartPointer<vtkDataSet> MDEWEventNexusLoadingPresenter::execute(
-        vtkDataSetFactory *factory, ProgressAction &loadingProgressUpdate,
-        ProgressAction &drawingProgressUpdate) {
-      using namespace Mantid::API;
-      using namespace Mantid::Geometry;
-
-      if(this->shouldLoad())
-      {
-        Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification> observer(loadingProgressUpdate, &ProgressAction::handler);
-        AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-
-        IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
-        alg->initialize();
-        alg->setPropertyValue("Filename", this->m_filename);
-        alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-        alg->setProperty("FileBackEnd", !this->m_view->getLoadInMemory()); //Load from file by default.
-        alg->addObserver(observer);
-        alg->execute();
-        alg->removeObserver(observer);
-      }
-
-      Workspace_sptr result=AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-      Mantid::API::IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
-
-      factory->setRecursionDepth(this->m_view->getRecursionDepth());
-      //Create visualisation in one-shot.
-      auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
-      
-      /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions
-        have proper range extents set.
-      */
-      this->extractMetadata(*eventWs);
-
-      this->appendMetadata(visualDataSet, eventWs->getName());
-      return visualDataSet;
-    }
-
-    /**
-     Executes any meta-data loading required.
-    */
-    void MDEWEventNexusLoadingPresenter::executeLoadMetadata()
-    {
-      using namespace Mantid::API;
-      AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-
-      IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
-       
-      alg->initialize();
-      alg->setPropertyValue("Filename", this->m_filename);
-      alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-      alg->setProperty("MetadataOnly", true); //Don't load the events.
-      alg->setProperty("FileBackEnd", false); //Only require metadata, so do it in memory.
-      alg->execute();
-
-      Workspace_sptr result=AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-      IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
-      m_wsTypeName = eventWs->id();
-      //Call base-class extraction method.
-      this->extractMetadata(*eventWs);
-
-      AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-    }
-
-    /// Destructor
-    MDEWEventNexusLoadingPresenter::~MDEWEventNexusLoadingPresenter() {}
-
-    /*
+  }
+  return 0;
+}
+
+/*
+Executes the underlying algorithm to create the MVP model.
+@param factory : visualisation factory to use.
+@param loadingProgressUpdate : Handler for GUI updates while algorithm
+progresses.
+@param drawingProgressUpdate : Handler for GUI updates while
+vtkDataSetFactory::create occurs.
+*/
+vtkSmartPointer<vtkDataSet>
+MDEWEventNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
+                                        ProgressAction &loadingProgressUpdate,
+                                        ProgressAction &drawingProgressUpdate) {
+  using namespace Mantid::API;
+  using namespace Mantid::Geometry;
+
+  if (this->shouldLoad()) {
+    Poco::NObserver<ProgressAction,
+                    Mantid::API::Algorithm::ProgressNotification>
+        observer(loadingProgressUpdate, &ProgressAction::handler);
+    AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+
+    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
+    alg->initialize();
+    alg->setPropertyValue("Filename", this->m_filename);
+    alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
+    alg->setProperty(
+        "FileBackEnd",
+        !this->m_view->getLoadInMemory()); // Load from file by default.
+    alg->addObserver(observer);
+    alg->execute();
+    alg->removeObserver(observer);
+  }
+
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  Mantid::API::IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
+
+  factory->setRecursionDepth(this->m_view->getRecursionDepth());
+  // Create visualisation in one-shot.
+  auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
+
+  /*extractMetaData needs to be re-run here because the first execution of this
+    from ::executeLoadMetadata will not have ensured that all dimensions
+    have proper range extents set.
+  */
+  this->extractMetadata(*eventWs);
+
+  this->appendMetadata(visualDataSet, eventWs->getName());
+  return visualDataSet;
+}
+
+/**
+ Executes any meta-data loading required.
+*/
+void MDEWEventNexusLoadingPresenter::executeLoadMetadata() {
+  using namespace Mantid::API;
+  AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+
+  IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
+
+  alg->initialize();
+  alg->setPropertyValue("Filename", this->m_filename);
+  alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
+  alg->setProperty("MetadataOnly", true); // Don't load the events.
+  alg->setProperty("FileBackEnd",
+                   false); // Only require metadata, so do it in memory.
+  alg->execute();
+
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
+  m_wsTypeName = eventWs->id();
+  // Call base-class extraction method.
+  this->extractMetadata(*eventWs);
+
+  AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+}
+
+/// Destructor
+MDEWEventNexusLoadingPresenter::~MDEWEventNexusLoadingPresenter() {}
+
+/*
 Getter for the workspace type name.
 @return Workspace Type Name
 */
-    std::string MDEWEventNexusLoadingPresenter::getWorkspaceTypeName()
-    {
-      return m_wsTypeName;
-    }
-  }
+std::string MDEWEventNexusLoadingPresenter::getWorkspaceTypeName() {
+  return m_wsTypeName;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp b/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp
index 8e6cda027711a32db619fa7964e4d3dd523b9205..ec930737942e52615b08a44469bcb613c2bc9944 100644
--- a/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp
@@ -8,142 +8,143 @@
 #include <qwt_double_interval.h>
 #include <vtkUnstructuredGrid.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-
-    /*
-    Constructor
-    @param view : MVP view
-    @param repository : Object for accessing the workspaces
-    @param wsName : Name of the workspace to use.
-    @throw invalid_argument if the workspace name is empty
-    @throw invalid_argument if the repository is null
-    @throw invalid_arument if view is null
-    */
-  MDEWInMemoryLoadingPresenter::MDEWInMemoryLoadingPresenter(
-      std::unique_ptr<MDLoadingView> view, WorkspaceProvider *repository,
-      std::string wsName)
-      : MDEWLoadingPresenter(std::move(view)), m_repository(repository),
-        m_wsName(wsName), m_wsTypeName(""), m_specialCoords(-1) {
-    if (m_wsName.empty()) {
-      throw std::invalid_argument("The workspace name is empty.");
-    }
-    if (nullptr == repository) {
-      throw std::invalid_argument("The repository is NULL");
-    }
-    if (nullptr == m_view) {
-      throw std::invalid_argument("View is NULL.");
-    }
+namespace Mantid {
+namespace VATES {
+
+/*
+Constructor
+@param view : MVP view
+@param repository : Object for accessing the workspaces
+@param wsName : Name of the workspace to use.
+@throw invalid_argument if the workspace name is empty
+@throw invalid_argument if the repository is null
+@throw invalid_arument if view is null
+*/
+MDEWInMemoryLoadingPresenter::MDEWInMemoryLoadingPresenter(
+    std::unique_ptr<MDLoadingView> view, WorkspaceProvider *repository,
+    std::string wsName)
+    : MDEWLoadingPresenter(std::move(view)), m_repository(repository),
+      m_wsName(wsName), m_wsTypeName(""), m_specialCoords(-1) {
+  if (m_wsName.empty()) {
+    throw std::invalid_argument("The workspace name is empty.");
   }
+  if (nullptr == repository) {
+    throw std::invalid_argument("The repository is NULL");
+  }
+  if (nullptr == m_view) {
+    throw std::invalid_argument("View is NULL.");
+  }
+}
 
-  /*
- Indicates whether this presenter is capable of handling the type of file that
- is attempted to be loaded.
- @return false if the file cannot be read.
- */
-  bool MDEWInMemoryLoadingPresenter::canReadFile() const {
-    bool bCanReadIt = true;
-    if (!m_repository->canProvideWorkspace(m_wsName)) {
-      // The workspace does not exist.
-      bCanReadIt = false;
-    } else if (nullptr ==
-               boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(
-                   m_repository->fetchWorkspace(m_wsName))
-                   .get()) {
-      // The workspace can be found, but is not an IMDEventWorkspace.
-      bCanReadIt = false;
-    } else {
-      // The workspace is present, and is of the correct type.
-      bCanReadIt = true;
-    }
-    return bCanReadIt;
-    }
-
-    /*
-    Executes the underlying algorithm to create the MVP model.
-    @param factory : visualisation factory to use.
-    @param  : Handler for GUI updates while algorithm progresses.
-    @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs.
-    */
-    vtkSmartPointer<vtkDataSet> MDEWInMemoryLoadingPresenter::execute(
-        vtkDataSetFactory *factory, ProgressAction &,
-        ProgressAction &drawingProgressUpdate) {
-      using namespace Mantid::API;
-      using namespace Mantid::Geometry;
-
-      Workspace_sptr ws = m_repository->fetchWorkspace(m_wsName);
-      IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws);
-
-      factory->setRecursionDepth(this->m_view->getRecursionDepth());
-      auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
-      
-      /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions
-        have proper range extents set.
-      */
-
-      // Update the meta data min and max values with the values of the visual data set. This is necessary since we want the full data range of the visual 
-      // data set and not of the actual underlying data set.
-      double* range  = visualDataSet->GetScalarRange();
-      if (range)
-      {
-        this->m_metadataJsonManager->setMinValue(range[0]);
-        this->m_metadataJsonManager->setMaxValue(range[1]);
-      }
-
-      this->extractMetadata(*eventWs);
-
-      this->appendMetadata(visualDataSet, eventWs->getName());
-      return visualDataSet;
-    }
-
-    /**
-     Executes any meta-data loading required.
-    */
-    void MDEWInMemoryLoadingPresenter::executeLoadMetadata()
-    {
-      using namespace Mantid::API;
-
-      Workspace_sptr ws = m_repository->fetchWorkspace(m_wsName);
-      IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws);
-      m_wsTypeName = eventWs->id();
-      m_specialCoords = eventWs->getSpecialCoordinateSystem();
-
-      // Set the minimum and maximum of the workspace data.
-      QwtDoubleInterval minMaxContainer = m_metaDataExtractor->getMinAndMax(eventWs);
-      m_metadataJsonManager->setMinValue(minMaxContainer.minValue());
-      m_metadataJsonManager->setMaxValue(minMaxContainer.maxValue());
-
-      // Set the instrument which is associated with the workspace.
-      m_metadataJsonManager->setInstrument(m_metaDataExtractor->extractInstrument(eventWs));
-      
-      // Set the special coordinates
-      m_metadataJsonManager->setSpecialCoordinates(m_specialCoords);
-
-      //Call base-class extraction method.
-      this->extractMetadata(*eventWs);
-    }
-
-    /// Destructor
-    MDEWInMemoryLoadingPresenter::~MDEWInMemoryLoadingPresenter() {}
-
-    /*
-     Getter for the workspace type name.
-     @return Workspace Type Name
-   */
-    std::string MDEWInMemoryLoadingPresenter::getWorkspaceTypeName()
-    {
-      return m_wsTypeName;
-    }
-
-    /**
-     * Getter for the special coordinates.
-     * @return the special coordinates value
-     */
-    int MDEWInMemoryLoadingPresenter::getSpecialCoordinates()
-    {
-      return m_specialCoords;
-    }
+/*
+Indicates whether this presenter is capable of handling the type of file that
+is attempted to be loaded.
+@return false if the file cannot be read.
+*/
+bool MDEWInMemoryLoadingPresenter::canReadFile() const {
+  bool bCanReadIt = true;
+  if (!m_repository->canProvideWorkspace(m_wsName)) {
+    // The workspace does not exist.
+    bCanReadIt = false;
+  } else if (nullptr ==
+             boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(
+                 m_repository->fetchWorkspace(m_wsName)).get()) {
+    // The workspace can be found, but is not an IMDEventWorkspace.
+    bCanReadIt = false;
+  } else {
+    // The workspace is present, and is of the correct type.
+    bCanReadIt = true;
+  }
+  return bCanReadIt;
+}
+
+/*
+Executes the underlying algorithm to create the MVP model.
+@param factory : visualisation factory to use.
+@param  : Handler for GUI updates while algorithm progresses.
+@param drawingProgressUpdate : Handler for GUI updates while
+vtkDataSetFactory::create occurs.
+*/
+vtkSmartPointer<vtkDataSet>
+MDEWInMemoryLoadingPresenter::execute(vtkDataSetFactory *factory,
+                                      ProgressAction &,
+                                      ProgressAction &drawingProgressUpdate) {
+  using namespace Mantid::API;
+  using namespace Mantid::Geometry;
+
+  Workspace_sptr ws = m_repository->fetchWorkspace(m_wsName);
+  IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws);
+
+  factory->setRecursionDepth(this->m_view->getRecursionDepth());
+  auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
+
+  /*extractMetaData needs to be re-run here because the first execution of this
+    from ::executeLoadMetadata will not have ensured that all dimensions
+    have proper range extents set.
+  */
+
+  // Update the meta data min and max values with the values of the visual data
+  // set. This is necessary since we want the full data range of the visual
+  // data set and not of the actual underlying data set.
+  double *range = visualDataSet->GetScalarRange();
+  if (range) {
+    this->m_metadataJsonManager->setMinValue(range[0]);
+    this->m_metadataJsonManager->setMaxValue(range[1]);
   }
+
+  this->extractMetadata(*eventWs);
+
+  this->appendMetadata(visualDataSet, eventWs->getName());
+  return visualDataSet;
+}
+
+/**
+ Executes any meta-data loading required.
+*/
+void MDEWInMemoryLoadingPresenter::executeLoadMetadata() {
+  using namespace Mantid::API;
+
+  Workspace_sptr ws = m_repository->fetchWorkspace(m_wsName);
+  IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws);
+  m_wsTypeName = eventWs->id();
+  m_specialCoords = eventWs->getSpecialCoordinateSystem();
+
+  // Set the minimum and maximum of the workspace data.
+  QwtDoubleInterval minMaxContainer =
+      m_metaDataExtractor->getMinAndMax(eventWs);
+  m_metadataJsonManager->setMinValue(minMaxContainer.minValue());
+  m_metadataJsonManager->setMaxValue(minMaxContainer.maxValue());
+
+  // Set the instrument which is associated with the workspace.
+  m_metadataJsonManager->setInstrument(
+      m_metaDataExtractor->extractInstrument(eventWs));
+
+  // Set the special coordinates
+  m_metadataJsonManager->setSpecialCoordinates(m_specialCoords);
+
+  // Call base-class extraction method.
+  this->extractMetadata(*eventWs);
+}
+
+/// Destructor
+MDEWInMemoryLoadingPresenter::~MDEWInMemoryLoadingPresenter() {}
+
+/*
+ Getter for the workspace type name.
+ @return Workspace Type Name
+*/
+std::string MDEWInMemoryLoadingPresenter::getWorkspaceTypeName() {
+  return m_wsTypeName;
+}
+
+/**
+ * Getter for the special coordinates.
+ * @return the special coordinates value
+ */
+int MDEWInMemoryLoadingPresenter::getSpecialCoordinates() {
+  return m_specialCoords;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp
index ac165ac8f639df336fa1c5eaba771a7321563f56..1387b7cff278409c7910e5cac56ebec10957d563 100644
--- a/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp
@@ -11,7 +11,6 @@
 #include <qwt_double_interval.h>
 #include <vtkUnstructuredGrid.h>
 
-
 namespace Mantid {
 namespace VATES {
 
@@ -62,7 +61,6 @@ bool MDHWInMemoryLoadingPresenter::canReadFile() const {
   return bCanReadIt;
 }
 
-
 /*
 Executes the underlying algorithm to create the MVP model.
 @param factory : visualisation factory to use.
@@ -105,7 +103,8 @@ MDHWInMemoryLoadingPresenter::execute(vtkDataSetFactory *factory,
 
   this->extractMetadata(*m_cachedVisualHistoWs);
 
-  // Transposed workpace is temporary, outside the ADS, and does not have a name. so get it from pre-transposed.
+  // Transposed workpace is temporary, outside the ADS, and does not have a
+  // name. so get it from pre-transposed.
   // If this fails, create a default name with a time stamp
   auto name = histoWs->getName();
   if (name.empty()) {
@@ -172,9 +171,12 @@ std::vector<int> MDHWInMemoryLoadingPresenter::getExtents() {
       boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws);
   MDHWLoadingPresenter::transposeWs(histoWs, m_cachedVisualHistoWs);
   std::vector<int> extents(6, 0);
-  extents[1] = static_cast<int>(m_cachedVisualHistoWs->getXDimension()->getNBins());
-  extents[3] = static_cast<int>(m_cachedVisualHistoWs->getYDimension()->getNBins());
-  extents[5] = static_cast<int>(m_cachedVisualHistoWs->getZDimension()->getNBins());
+  extents[1] =
+      static_cast<int>(m_cachedVisualHistoWs->getXDimension()->getNBins());
+  extents[3] =
+      static_cast<int>(m_cachedVisualHistoWs->getYDimension()->getNBins());
+  extents[5] =
+      static_cast<int>(m_cachedVisualHistoWs->getZDimension()->getNBins());
   return extents;
 }
 }
diff --git a/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
index 4cc01c86b9691f7b970a28eac7bafa2fdcda0f87..887b454d5818713c1a8439dba082965d8bebf5a2 100644
--- a/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp
@@ -23,7 +23,6 @@
 #include <vtkFieldData.h>
 #include <vtkDataSet.h>
 
-
 namespace Mantid {
 namespace VATES {
 
@@ -42,8 +41,9 @@ namespace VATES {
  * @return A workspace that can be directly rendered from. Integrated dimensions
  *are always last.
  */
-void MDHWLoadingPresenter::transposeWs(Mantid::API::IMDHistoWorkspace_sptr &inHistoWs,
-                 Mantid::API::IMDHistoWorkspace_sptr &outCachedHistoWs) {
+void MDHWLoadingPresenter::transposeWs(
+    Mantid::API::IMDHistoWorkspace_sptr &inHistoWs,
+    Mantid::API::IMDHistoWorkspace_sptr &outCachedHistoWs) {
   using namespace Mantid::API;
 
   if (!outCachedHistoWs) {
@@ -216,13 +216,13 @@ void MDHWLoadingPresenter::appendMetadata(vtkDataSet *visualDataSet,
 
   // Add metadata to dataset.
   MetadataToFieldData convert;
-  convert(outputFD.GetPointer(), xmlString, XMLDefinitions::metaDataId().c_str());
+  convert(outputFD.GetPointer(), xmlString,
+          XMLDefinitions::metaDataId().c_str());
   convert(outputFD.GetPointer(), jsonString,
           m_vatesConfigurations->getMetadataIdJson().c_str());
   visualDataSet->SetFieldData(outputFD.GetPointer());
 }
 
-
 /**
  * Set the axis labels from the current dimensions
  * @param visualDataSet: The VTK dataset to update
@@ -236,7 +236,6 @@ void MDHWLoadingPresenter::setAxisLabels(vtkDataSet *visualDataSet) {
   }
 }
 
-
 /**
 Gets the geometry in a string format.
 @return geometry string ref.
diff --git a/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp
index 7f7856b3ede06df88c238cc199a23541f158fc36..9bb01b22c40a5c77a9bc1cc280ee6e57630d13a4 100644
--- a/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp
@@ -11,10 +11,8 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include <vtkUnstructuredGrid.h>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
  * Constructor
@@ -37,28 +35,24 @@ MDHWNexusLoadingPresenter::MDHWNexusLoadingPresenter(
 }
 
 /**
- * Indicates whether this presenter is capable of handling the type of file that is attempted to be loaded.
+ * Indicates whether this presenter is capable of handling the type of file that
+ * is attempted to be loaded.
  * @return false if the file cannot be read.
  */
-bool MDHWNexusLoadingPresenter::canReadFile() const
-{
+bool MDHWNexusLoadingPresenter::canReadFile() const {
   // Quick check based on extension.
-  if(!canLoadFileBasedOnExtension(m_filename, ".nxs"))
-  {
+  if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) {
     return 0;
   }
-  ::NeXus::File * file = NULL;
+  ::NeXus::File *file = NULL;
 
   file = new ::NeXus::File(this->m_filename);
   // MDHistoWorkspace file has a different name for the entry
-  try
-  {
+  try {
     file->openGroup("MDHistoWorkspace", "NXentry");
     file->close();
     return 1;
-  }
-  catch(::NeXus::Exception &)
-  {
+  } catch (::NeXus::Exception &) {
     // If the entry name does not match, then it can't read the file.
     file->close();
     return 0;
@@ -69,8 +63,10 @@ bool MDHWNexusLoadingPresenter::canReadFile() const
 /**
  * Executes the underlying algorithm to create the MVP model.
  * @param factory : visualisation factory to use.
- * @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses.
- * @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs.
+ * @param loadingProgressUpdate : Handler for GUI updates while algorithm
+ * progresses.
+ * @param drawingProgressUpdate : Handler for GUI updates while
+ * vtkDataSetFactory::create occurs.
  */
 vtkSmartPointer<vtkDataSet>
 MDHWNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
@@ -79,7 +75,7 @@ MDHWNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
   using namespace Mantid::API;
   using namespace Mantid::Geometry;
 
-  if(this->shouldLoad() || !m_histoWs)
+  if (this->shouldLoad() || !m_histoWs)
     this->loadWorkspace(loadingProgressUpdate);
 
   // Create visualisation in one-shot.
@@ -97,12 +93,10 @@ MDHWNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
 /**
  * Executes any meta-data loading required.
  */
-void MDHWNexusLoadingPresenter::executeLoadMetadata()
-{
+void MDHWNexusLoadingPresenter::executeLoadMetadata() {
   using namespace Mantid::API;
-  
-  if(this->shouldLoad() || !m_histoWs)
-  {
+
+  if (this->shouldLoad() || !m_histoWs) {
     // no difference between loading just the metadata or the entire workspace.
     this->loadWorkspace();
   }
@@ -121,32 +115,27 @@ MDHWNexusLoadingPresenter::~MDHWNexusLoadingPresenter() {}
  * Getter for the workspace type name.
  * @return Workspace Type Name
  */
-std::string MDHWNexusLoadingPresenter::getWorkspaceTypeName()
-{
+std::string MDHWNexusLoadingPresenter::getWorkspaceTypeName() {
   return m_wsTypeName;
 }
 
-std::vector<int> MDHWNexusLoadingPresenter::getExtents()
-{
+std::vector<int> MDHWNexusLoadingPresenter::getExtents() {
 
   std::vector<int> extents(6, 0);
 
-  if(this->shouldLoad() || !m_histoWs)
+  if (this->shouldLoad() || !m_histoWs)
     this->loadWorkspace();
 
-  if(m_histoWs)
-  {
+  if (m_histoWs) {
     extents[1] = static_cast<int>(m_histoWs->getXDimension()->getNBins());
     extents[3] = static_cast<int>(m_histoWs->getYDimension()->getNBins());
     extents[5] = static_cast<int>(m_histoWs->getZDimension()->getNBins());
   }
 
   return extents;
-
 }
 
-void MDHWNexusLoadingPresenter::loadWorkspace()
-{
+void MDHWNexusLoadingPresenter::loadWorkspace() {
   using namespace Mantid::API;
   AnalysisDataService::Instance().remove("MD_HISTO_WS_ID");
 
@@ -154,34 +143,37 @@ void MDHWNexusLoadingPresenter::loadWorkspace()
   alg->initialize();
   alg->setPropertyValue("Filename", this->m_filename);
   alg->setPropertyValue("OutputWorkspace", "MD_HISTO_WS_ID");
-  alg->setProperty("FileBackEnd", !this->m_view->getLoadInMemory()); //Load from file by default.
+  alg->setProperty(
+      "FileBackEnd",
+      !this->m_view->getLoadInMemory()); // Load from file by default.
   alg->execute();
-  Workspace_sptr result = AnalysisDataService::Instance().retrieve("MD_HISTO_WS_ID");
-  auto preTranspose = boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(result);
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_HISTO_WS_ID");
+  auto preTranspose =
+      boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(result);
   // Perform any necessary transpose.
   MDHWLoadingPresenter::transposeWs(preTranspose, m_histoWs);
-
-
 }
 
-void MDHWNexusLoadingPresenter::loadWorkspace( ProgressAction& loadingProgressUpdate)
-{
-    using namespace Mantid::API;
-    Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification> observer(loadingProgressUpdate, &ProgressAction::handler);
-
-    AnalysisDataService::Instance().remove("MD_HISTO_WS_ID");
-    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
-    alg->initialize();
-    alg->setPropertyValue("Filename", this->m_filename);
-    alg->setPropertyValue("OutputWorkspace", "MD_HISTO_WS_ID");
-    alg->setProperty("FileBackEnd", !this->m_view->getLoadInMemory()); //Load from file by default.
-    alg->addObserver(observer);
-    alg->execute();
-    alg->removeObserver(observer);
-    m_histoWs =
-        AnalysisDataService::Instance()
-            .retrieveWS<Mantid::API::IMDHistoWorkspace>("MD_HISTO_WS_ID");
-}
+void MDHWNexusLoadingPresenter::loadWorkspace(
+    ProgressAction &loadingProgressUpdate) {
+  using namespace Mantid::API;
+  Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification>
+      observer(loadingProgressUpdate, &ProgressAction::handler);
 
+  AnalysisDataService::Instance().remove("MD_HISTO_WS_ID");
+  IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
+  alg->initialize();
+  alg->setPropertyValue("Filename", this->m_filename);
+  alg->setPropertyValue("OutputWorkspace", "MD_HISTO_WS_ID");
+  alg->setProperty(
+      "FileBackEnd",
+      !this->m_view->getLoadInMemory()); // Load from file by default.
+  alg->addObserver(observer);
+  alg->execute();
+  alg->removeObserver(observer);
+  m_histoWs = AnalysisDataService::Instance()
+                  .retrieveWS<Mantid::API::IMDHistoWorkspace>("MD_HISTO_WS_ID");
+}
 }
 }
diff --git a/Vates/VatesAPI/src/MDLoadingPresenter.cpp b/Vates/VatesAPI/src/MDLoadingPresenter.cpp
index 6aec9aa6ce4ed009bd395da8e188a39448d51ad4..739284872fe6dcf55bab9487f3be3bc41f33f621 100644
--- a/Vates/VatesAPI/src/MDLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/MDLoadingPresenter.cpp
@@ -1,22 +1,20 @@
 #include "MantidVatesAPI/MDLoadingPresenter.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 /**
  * Set the default COB Matrix and boundaries. The default COB matrix uses the
  * canonical axis directions.
  * @param visualDataSet: the input data set
  */
-void MDLoadingPresenter::setDefaultCOBandBoundaries(vtkDataSet* visualDataSet) {
+void MDLoadingPresenter::setDefaultCOBandBoundaries(vtkDataSet *visualDataSet) {
   // Set an identity matrix
   vtkSmartPointer<vtkMatrix4x4> cobMatrix =
-    vtkSmartPointer<vtkMatrix4x4>::New();
+      vtkSmartPointer<vtkMatrix4x4>::New();
   cobMatrix->Identity();
 
-  if (!vtkPVChangeOfBasisHelper::AddChangeOfBasisMatrixToFieldData(visualDataSet,
-                                                                    cobMatrix)) {
+  if (!vtkPVChangeOfBasisHelper::AddChangeOfBasisMatrixToFieldData(
+          visualDataSet, cobMatrix)) {
     g_log.warning("The Change-of-Basis-Matrix could not be added to the field "
                   "data of the scaled data set.\n");
   }
@@ -25,7 +23,7 @@ void MDLoadingPresenter::setDefaultCOBandBoundaries(vtkDataSet* visualDataSet) {
   double boundingBox[6];
   visualDataSet->GetBounds(boundingBox);
   if (!vtkPVChangeOfBasisHelper::AddBoundingBoxInBasis(visualDataSet,
-                                                        boundingBox)) {
+                                                       boundingBox)) {
     g_log.warning("The bounding box could not be added to the field data of "
                   "the scaled data set.\n");
   }
@@ -33,17 +31,17 @@ void MDLoadingPresenter::setDefaultCOBandBoundaries(vtkDataSet* visualDataSet) {
 
 /**
  * Make the visual data set non-orthogonal
- * @param visualDataSet: the vtk visual data set to which the transformation will be applied
+ * @param visualDataSet: the vtk visual data set to which the transformation
+ * will be applied
  * @param workspaceProvider: the provider of the underlying workspace
  */
-void MDLoadingPresenter::makeNonOrthogonal(vtkDataSet* visualDataSet,
-                                           std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider)
-{
+void MDLoadingPresenter::makeNonOrthogonal(
+    vtkDataSet *visualDataSet,
+    std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider) {
   std::string wsName = vtkDataSetToWsName::exec(visualDataSet);
-  vtkDataSetToNonOrthogonalDataSet converter(visualDataSet, wsName, std::move(workspaceProvider));
+  vtkDataSetToNonOrthogonalDataSet converter(visualDataSet, wsName,
+                                             std::move(workspaceProvider));
   converter.execute();
 }
-
-
 }
 }
diff --git a/Vates/VatesAPI/src/MDLoadingViewSimple.cpp b/Vates/VatesAPI/src/MDLoadingViewSimple.cpp
index 78a9d47e865d8687ccba5eb8a1ac8bacb302b2aa..dd456b27bf2b0a81b0cecb8e4b604a9cd6d639fb 100644
--- a/Vates/VatesAPI/src/MDLoadingViewSimple.cpp
+++ b/Vates/VatesAPI/src/MDLoadingViewSimple.cpp
@@ -1,21 +1,17 @@
 #include "MantidVatesAPI/MDLoadingViewSimple.h"
 
-namespace Mantid{
+namespace Mantid {
 namespace VATES {
 
-void MDLoadingViewSimple::setTime(double time) {
-  m_time = time;
-}
+void MDLoadingViewSimple::setTime(double time) { m_time = time; }
 
-double MDLoadingViewSimple::getTime() const {
-  return m_time;
-}
+double MDLoadingViewSimple::getTime() const { return m_time; }
 
 void MDLoadingViewSimple::setRecursionDepth(size_t recursionDepth) {
   m_recursionDepth = recursionDepth;
 }
 
-size_t MDLoadingViewSimple::getRecursionDepth() const{
+size_t MDLoadingViewSimple::getRecursionDepth() const {
   return m_recursionDepth;
 }
 
@@ -23,9 +19,6 @@ void MDLoadingViewSimple::setLoadInMemory(bool loadInMemory) {
   m_loadInMemory = loadInMemory;
 }
 
-bool MDLoadingViewSimple::getLoadInMemory() const{
-  return m_loadInMemory;
-}
-
+bool MDLoadingViewSimple::getLoadInMemory() const { return m_loadInMemory; }
 }
 }
diff --git a/Vates/VatesAPI/src/MedianAndBelowThresholdRange.cpp b/Vates/VatesAPI/src/MedianAndBelowThresholdRange.cpp
index bb1fe90e0b4cf1227620df988e93353de1677a31..acfb839a48c7cef41fee732db4a4326b75ac091a 100644
--- a/Vates/VatesAPI/src/MedianAndBelowThresholdRange.cpp
+++ b/Vates/VatesAPI/src/MedianAndBelowThresholdRange.cpp
@@ -2,121 +2,110 @@
 #include "MantidAPI/IMDIterator.h"
 #include <cmath>
 
+namespace Mantid {
+namespace VATES {
 
-namespace Mantid
-{
-  namespace VATES
-  {
+/**
+Constructor
+*/
+MedianAndBelowThresholdRange::MedianAndBelowThresholdRange()
+    : m_min(0.00), m_max(0), m_isCalculated(false) {}
 
-    /**
-    Constructor
-    */
-    MedianAndBelowThresholdRange::MedianAndBelowThresholdRange() : m_min(0.00), m_max(0), m_isCalculated(false)
-    {
-    }
+/**
+Constructor
+*/
+MedianAndBelowThresholdRange::MedianAndBelowThresholdRange(
+    signal_t min, signal_t max, bool isCalculated,
+    Mantid::API::IMDWorkspace_sptr workspace)
+    : m_min(min), m_max(max), m_isCalculated(isCalculated),
+      m_workspace(workspace) {}
 
-    /**
-    Constructor
-    */
-    MedianAndBelowThresholdRange::MedianAndBelowThresholdRange(signal_t min, signal_t max, bool isCalculated, Mantid::API::IMDWorkspace_sptr workspace) : m_min(min), m_max(max),  m_isCalculated(isCalculated), m_workspace(workspace)
-    {
-    }
+/// Destructor
+MedianAndBelowThresholdRange::~MedianAndBelowThresholdRange() {}
 
-    ///Destructor
-    MedianAndBelowThresholdRange::~MedianAndBelowThresholdRange()
-    {
-    }
-
-
-    /**
-    Overriden calculate method. 
-    */
-    void MedianAndBelowThresholdRange::calculate()
-    {
-      if(NULL == m_workspace.get())
-      {
-        throw std::logic_error("The workspace has not been set.");
-      }
-      
-      signal_t signal = 0;
-      signal_t accumulated_signal = 0;
+/**
+Overriden calculate method.
+*/
+void MedianAndBelowThresholdRange::calculate() {
+  if (NULL == m_workspace.get()) {
+    throw std::logic_error("The workspace has not been set.");
+  }
 
-      Mantid::API::IMDIterator* it = m_workspace->createIterator();
-      do
-      {
-        signal = it->getNormalizedSignal();
-        accumulated_signal += signal;
-        m_min = signal < m_min ? signal : m_min;
-      } while(it->next());
+  signal_t signal = 0;
+  signal_t accumulated_signal = 0;
 
-      m_max = accumulated_signal / static_cast<signal_t>(it->getDataSize());
-      m_isCalculated = true;
-    }
+  Mantid::API::IMDIterator *it = m_workspace->createIterator();
+  do {
+    signal = it->getNormalizedSignal();
+    accumulated_signal += signal;
+    m_min = signal < m_min ? signal : m_min;
+  } while (it->next());
 
-    /**
-    Indicates wheter execution has occured or not.
-    @return : true if calculate has been called previously, otherwise false.
-    */
-    bool MedianAndBelowThresholdRange::hasCalculated() const
-    {
-      return m_isCalculated;
-    }
+  m_max = accumulated_signal / static_cast<signal_t>(it->getDataSize());
+  m_isCalculated = true;
+}
 
-    /**
-    Getter for the calculated minimum value.
-    */
-    signal_t MedianAndBelowThresholdRange::getMinimum() const
-    {
-      if(!m_isCalculated)
-      {
-        throw std::runtime_error("Cannot call ::getMinimum() without first calling ::calculate()");
-      }
-      return m_min;
-    }
+/**
+Indicates wheter execution has occured or not.
+@return : true if calculate has been called previously, otherwise false.
+*/
+bool MedianAndBelowThresholdRange::hasCalculated() const {
+  return m_isCalculated;
+}
 
-    /**
-    Getter for the calculated maximum value.
-    */
-    signal_t MedianAndBelowThresholdRange::getMaximum() const
-    {
-      if(!m_isCalculated)
-      {
-        throw std::runtime_error("Cannot call ::getMaximum() without first calling ::calculate()");
-      }
-      return m_max;
-    }
+/**
+Getter for the calculated minimum value.
+*/
+signal_t MedianAndBelowThresholdRange::getMinimum() const {
+  if (!m_isCalculated) {
+    throw std::runtime_error(
+        "Cannot call ::getMinimum() without first calling ::calculate()");
+  }
+  return m_min;
+}
 
-    /**
-    Virtual constructor clone method.
-    @return clone as MedianAndBelowThresholdRange*.
-    */
-    MedianAndBelowThresholdRange* MedianAndBelowThresholdRange::clone() const
-    {
-      return new MedianAndBelowThresholdRange(m_min, m_max, m_isCalculated, this->m_workspace);
-    }
+/**
+Getter for the calculated maximum value.
+*/
+signal_t MedianAndBelowThresholdRange::getMaximum() const {
+  if (!m_isCalculated) {
+    throw std::runtime_error(
+        "Cannot call ::getMaximum() without first calling ::calculate()");
+  }
+  return m_max;
+}
 
-    /**
-    Setter for IMDWorkspace.
-    @param workspace : The workspace to extract ranges from.
-    */
-    void MedianAndBelowThresholdRange::setWorkspace(Mantid::API::Workspace_sptr workspace)
-    {
-      m_isCalculated = false;
-      m_workspace = boost::dynamic_pointer_cast<Mantid::API::IMDWorkspace>(workspace);
-      if(!workspace)
-      {
-        throw std::logic_error("MedianAndBelowThresholdRange only works for IMDWorkspaces");
-      }
-    }
+/**
+Virtual constructor clone method.
+@return clone as MedianAndBelowThresholdRange*.
+*/
+MedianAndBelowThresholdRange *MedianAndBelowThresholdRange::clone() const {
+  return new MedianAndBelowThresholdRange(m_min, m_max, m_isCalculated,
+                                          this->m_workspace);
+}
 
-    /**
-    Determine whether the signal is withing range.
-    @param signal value
-    @return true if the signal is in the range defined by this object.
-    */
-    bool MedianAndBelowThresholdRange::inRange(const signal_t& signal)
-    {
-      return signal != 0 && signal < m_max;
-    }
+/**
+Setter for IMDWorkspace.
+@param workspace : The workspace to extract ranges from.
+*/
+void MedianAndBelowThresholdRange::setWorkspace(
+    Mantid::API::Workspace_sptr workspace) {
+  m_isCalculated = false;
+  m_workspace =
+      boost::dynamic_pointer_cast<Mantid::API::IMDWorkspace>(workspace);
+  if (!workspace) {
+    throw std::logic_error(
+        "MedianAndBelowThresholdRange only works for IMDWorkspaces");
   }
 }
+
+/**
+Determine whether the signal is withing range.
+@param signal value
+@return true if the signal is in the range defined by this object.
+*/
+bool MedianAndBelowThresholdRange::inRange(const signal_t &signal) {
+  return signal != 0 && signal < m_max;
+}
+}
+}
diff --git a/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp b/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
index 2d4094365b7e109447fd2942263ce9894d24ae73..c82485a2a3d827c305ecbc4e837dafd27e745538 100644
--- a/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
+++ b/Vates/VatesAPI/src/MetaDataExtractorUtils.cpp
@@ -10,88 +10,81 @@
 #include "boost/pointer_cast.hpp"
 #include <cfloat>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-      namespace
-    {
-        /// Static logger
-        Kernel::Logger g_log("MetaDataExtractorUtils");
-    }
-
-    MetaDataExtractorUtils::MetaDataExtractorUtils():defaultMin(0.0), defaultMax(1.0)
-    {
-    }
+namespace Mantid {
+namespace VATES {
+namespace {
+/// Static logger
+Kernel::Logger g_log("MetaDataExtractorUtils");
+}
 
-    MetaDataExtractorUtils::~MetaDataExtractorUtils()
-    {
+MetaDataExtractorUtils::MetaDataExtractorUtils()
+    : defaultMin(0.0), defaultMax(1.0) {}
+
+MetaDataExtractorUtils::~MetaDataExtractorUtils() {}
+
+/**
+ * Extract the instrument information from the workspace. If there
+ * is more than one instrument involved, then extract the first instrument
+ * from the list.
+ * @param workspace Shared pointer to the workspace.
+ * @returns The instrument name or an empty string.
+ */
+std::string MetaDataExtractorUtils::extractInstrument(
+    Mantid::API::IMDWorkspace_sptr workspace) {
+  Mantid::API::IMDEventWorkspace_sptr eventWorkspace =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
+  Mantid::API::IMDHistoWorkspace_sptr histoWorkspace =
+      boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
+
+  std::string instrument = "";
+
+  // Check which workspace is currently used and that it contains at least one
+  // instrument.
+  if (eventWorkspace) {
+    if (eventWorkspace->getNumExperimentInfo() > 0) {
+      instrument =
+          eventWorkspace->getExperimentInfo(0)->getInstrument()->getName();
+    } else {
+      g_log.notice() << "The event workspace does not have any instruments. \n";
+
+      instrument = "";
     }
-
-    /**
-     * Extract the instrument information from the workspace. If there 
-     * is more than one instrument involved, then extract the first instrument
-     * from the list.
-     * @param workspace Shared pointer to the workspace.
-     * @returns The instrument name or an empty string. 
-     */
-    std::string MetaDataExtractorUtils::extractInstrument(Mantid::API::IMDWorkspace_sptr workspace)
-    {
-      Mantid::API::IMDEventWorkspace_sptr eventWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
-      Mantid::API::IMDHistoWorkspace_sptr histoWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
-    
-      std::string instrument = "";
-
-      // Check which workspace is currently used and that it contains at least one instrument.
-      if (eventWorkspace)
-      {
-        if (eventWorkspace->getNumExperimentInfo() > 0)
-        {
-          instrument = eventWorkspace->getExperimentInfo(0)->getInstrument()->getName();
-        } else 
-        {
-          g_log.notice() << "The event workspace does not have any instruments. \n";
-
-          instrument = "";
-        }
-      } else if (histoWorkspace)
-      {
-        if (histoWorkspace->getNumExperimentInfo() > 0)
-        {
-          instrument = histoWorkspace->getExperimentInfo(0)->getInstrument()->getName();
-        } else
-        {
-          g_log.notice() << "The histo workspace does not have any instruments. \n";
-
-          instrument = "";
-        }
-      } else
-      {
-        g_log.warning() << "The workspace does not seem to be either event or histo. \n";
-        instrument = "";
-      }
-
-      return instrument;
+  } else if (histoWorkspace) {
+    if (histoWorkspace->getNumExperimentInfo() > 0) {
+      instrument =
+          histoWorkspace->getExperimentInfo(0)->getInstrument()->getName();
+    } else {
+      g_log.notice() << "The histo workspace does not have any instruments. \n";
+
+      instrument = "";
     }
+  } else {
+    g_log.warning()
+        << "The workspace does not seem to be either event or histo. \n";
+    instrument = "";
+  }
 
-    /**
-     * Set the minimum and maximum of the workspace data. Code essentially copied from SignalRange.cpp
-     * @param workspace Rreference to an IMD workspace
-     * @returns The minimum and maximum value of the workspace dataset.
-     */
-    QwtDoubleInterval MetaDataExtractorUtils::getMinAndMax(Mantid::API::IMDWorkspace_sptr workspace)
-    {
-      if (!workspace)
-        throw std::invalid_argument("The workspace is empty.");
-
-      auto iterators = workspace->createIterators(PARALLEL_GET_MAX_THREADS, 0);
+  return instrument;
+}
 
-      std::vector<QwtDoubleInterval> intervals(iterators.size());
-      // cppcheck-suppress syntaxError
+/**
+ * Set the minimum and maximum of the workspace data. Code essentially copied
+ * from SignalRange.cpp
+ * @param workspace Rreference to an IMD workspace
+ * @returns The minimum and maximum value of the workspace dataset.
+ */
+QwtDoubleInterval
+MetaDataExtractorUtils::getMinAndMax(Mantid::API::IMDWorkspace_sptr workspace) {
+  if (!workspace)
+    throw std::invalid_argument("The workspace is empty.");
+
+  auto iterators = workspace->createIterators(PARALLEL_GET_MAX_THREADS, 0);
+
+  std::vector<QwtDoubleInterval> intervals(iterators.size());
+  // cppcheck-suppress syntaxError
       PRAGMA_OMP( parallel for schedule(dynamic, 1))
-      for (int i=0; i < int(iterators.size()); i++)
-      {
-        Mantid::API::IMDIterator * it = iterators[i];
+      for (int i = 0; i < int(iterators.size()); i++) {
+        Mantid::API::IMDIterator *it = iterators[i];
 
         QwtDoubleInterval range = this->getRange(it);
         intervals[i] = range;
@@ -104,89 +97,86 @@ namespace Mantid
       double maxSignal = -DBL_MAX;
 
       auto inf = std::numeric_limits<double>::infinity();
-      for (size_t i=0; i < iterators.size(); i++)
-      {
+      for (size_t i = 0; i < iterators.size(); i++) {
         delete iterators[i];
-        
+
         double signal;
         signal = intervals[i].minValue();
-        if (signal != inf && signal < minSignal) minSignal = signal;
+        if (signal != inf && signal < minSignal)
+          minSignal = signal;
 
         signal = intervals[i].maxValue();
-        if (signal != inf && signal > maxSignal) maxSignal = signal;
+        if (signal != inf && signal > maxSignal)
+          maxSignal = signal;
       }
 
       // Set the lowest element to the smallest non-zero element.
-      if (minSignal == DBL_MAX)
-      {
+      if (minSignal == DBL_MAX) {
         minSignal = defaultMin;
         maxSignal = defaultMax;
-      } 
+      }
 
       QwtDoubleInterval minMaxContainer;
 
       if (minSignal < maxSignal)
         minMaxContainer = QwtDoubleInterval(minSignal, maxSignal);
-      else
-      {
+      else {
         if (minSignal != 0)
           // Possibly only one value in range
-          minMaxContainer = QwtDoubleInterval(minSignal*0.5, minSignal*1.5);
+          minMaxContainer = QwtDoubleInterval(minSignal * 0.5, minSignal * 1.5);
         else
           // Other default value
           minMaxContainer = QwtDoubleInterval(defaultMin, defaultMax);
       }
 
       return minMaxContainer;
-    }
-
-    /**
-     * Get the range of a workspace dataset for a single iterator. Code the same as in SignalRange.cpp
-     * @param it :: IMDIterator of what to find
-     * @returns the min/max range, or INFINITY if not found
-     */
-    QwtDoubleInterval MetaDataExtractorUtils::getRange(Mantid::API::IMDIterator * it)
-    {
-      if (!it)
-        return QwtDoubleInterval(defaultMin, defaultMax);
-      if (!it->valid())
-        return QwtDoubleInterval(defaultMin, defaultMax);
-
-      // Use no normalization
-      it->setNormalization(Mantid::API::VolumeNormalization);
-     
-      double minSignal = DBL_MAX;
-      double minSignalZeroCheck = DBL_MAX;
-      double maxSignal = -DBL_MAX;
-      auto inf = std::numeric_limits<double>::infinity();
+}
 
-      do
-      {
-        double signal = it->getNormalizedSignal();
-      
-        // Skip any 'infs' as it screws up the color scale
-        if (signal != inf)
-        {
-          if (signal == 0.0) minSignalZeroCheck = signal;
-          if (signal < minSignal && signal >0.0) minSignal = signal;
-          if (signal > maxSignal) maxSignal = signal;
-        }
-      } while (it->next());
-
-      if (minSignal == DBL_MAX)
-      {
-        if (minSignalZeroCheck != DBL_MAX)
-        {
-          minSignal = defaultMin;
-          maxSignal = defaultMax;
-        }
-        else
-        {
-          minSignal = inf;
-          maxSignal = inf;
-        }
-      }
-      return QwtDoubleInterval(minSignal, maxSignal);
+/**
+ * Get the range of a workspace dataset for a single iterator. Code the same as
+ * in SignalRange.cpp
+ * @param it :: IMDIterator of what to find
+ * @returns the min/max range, or INFINITY if not found
+ */
+QwtDoubleInterval
+MetaDataExtractorUtils::getRange(Mantid::API::IMDIterator *it) {
+  if (!it)
+    return QwtDoubleInterval(defaultMin, defaultMax);
+  if (!it->valid())
+    return QwtDoubleInterval(defaultMin, defaultMax);
+
+  // Use no normalization
+  it->setNormalization(Mantid::API::VolumeNormalization);
+
+  double minSignal = DBL_MAX;
+  double minSignalZeroCheck = DBL_MAX;
+  double maxSignal = -DBL_MAX;
+  auto inf = std::numeric_limits<double>::infinity();
+
+  do {
+    double signal = it->getNormalizedSignal();
+
+    // Skip any 'infs' as it screws up the color scale
+    if (signal != inf) {
+      if (signal == 0.0)
+        minSignalZeroCheck = signal;
+      if (signal < minSignal && signal > 0.0)
+        minSignal = signal;
+      if (signal > maxSignal)
+        maxSignal = signal;
+    }
+  } while (it->next());
+
+  if (minSignal == DBL_MAX) {
+    if (minSignalZeroCheck != DBL_MAX) {
+      minSignal = defaultMin;
+      maxSignal = defaultMax;
+    } else {
+      minSignal = inf;
+      maxSignal = inf;
     }
   }
+  return QwtDoubleInterval(minSignal, maxSignal);
+}
+}
 }
diff --git a/Vates/VatesAPI/src/MetadataJsonManager.cpp b/Vates/VatesAPI/src/MetadataJsonManager.cpp
index 8cdc3aa440a0167b82a6401b57a9df83c4479e55..af3ac67541c50c116e88a62c8b4c033ad00aa6dd 100644
--- a/Vates/VatesAPI/src/MetadataJsonManager.cpp
+++ b/Vates/VatesAPI/src/MetadataJsonManager.cpp
@@ -3,163 +3,131 @@
 #include <json/writer.h>
 #include <json/reader.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    // Note that we need to have a non-empty default string
-    MetadataJsonManager::MetadataJsonManager() : instrument("_EMPTY_"), minValue(0.0), maxValue(1.0), specialCoordinates(-1)
-    {
-      
+namespace Mantid {
+namespace VATES {
+// Note that we need to have a non-empty default string
+MetadataJsonManager::MetadataJsonManager()
+    : instrument("_EMPTY_"), minValue(0.0), maxValue(1.0),
+      specialCoordinates(-1) {}
+
+MetadataJsonManager::~MetadataJsonManager() {}
+
+/**
+ * Get the serialized JSON container as a string
+ * @return The Json container in string format.
+ */
+std::string MetadataJsonManager::getSerializedJson() {
+  Json::FastWriter writer;
+  metadataContainer.clear();
+
+  metadataContainer["instrument"] = instrument;
+  metadataContainer["minValue"] = minValue;
+  metadataContainer["maxValue"] = maxValue;
+  metadataContainer["specialCoordinates"] = specialCoordinates;
+
+  return writer.write(metadataContainer);
+}
+
+/**
+ * Read in the serialized JSON data and opulate the JSON container
+ * @param serializedJson The serialized JSON string.
+ */
+void MetadataJsonManager::readInSerializedJson(std::string serializedJson) {
+  Json::Reader reader;
+  metadataContainer.clear();
+
+  bool parseSuccess = reader.parse(serializedJson, metadataContainer, false);
+
+  if (parseSuccess) {
+    // Set the max value
+    if (metadataContainer.isObject() &&
+        metadataContainer.isMember("maxValue")) {
+      maxValue = metadataContainer["maxValue"].asDouble();
+    } else {
+      maxValue = 1.0;
     }
 
-    MetadataJsonManager::~MetadataJsonManager()
-    {
+    // Set the min value
+    if (metadataContainer.isObject() &&
+        metadataContainer.isMember("minValue")) {
+      minValue = metadataContainer["minValue"].asDouble();
+    } else {
+      minValue = 0.0;
     }
 
-    /**
-     * Get the serialized JSON container as a string
-     * @return The Json container in string format.
-     */
-    std::string MetadataJsonManager::getSerializedJson()
-    {
-      Json::FastWriter writer;
-      metadataContainer.clear();
-
-      metadataContainer["instrument"] = instrument;
-      metadataContainer["minValue"] = minValue;
-      metadataContainer["maxValue"] = maxValue;
-      metadataContainer["specialCoordinates"] = specialCoordinates;
-
-      return writer.write(metadataContainer);
+    // Set the instrument
+    if (metadataContainer.isObject() &&
+        metadataContainer.isMember("instrument")) {
+      instrument = metadataContainer["instrument"].asString();
+    } else {
+      instrument = "_EMPTY_";
     }
 
-    /**
-     * Read in the serialized JSON data and opulate the JSON container
-     * @param serializedJson The serialized JSON string.
-     */
-    void MetadataJsonManager::readInSerializedJson(std::string serializedJson)
-    {
-      Json::Reader reader;
-      metadataContainer.clear();
-
-      bool parseSuccess = reader.parse(serializedJson, metadataContainer, false);
-
-      if (parseSuccess)
-      {
-        // Set the max value
-        if (metadataContainer.isObject() && metadataContainer.isMember("maxValue"))
-        {
-          maxValue = metadataContainer["maxValue"].asDouble();
-        }
-        else 
-        {
-          maxValue = 1.0;
-        }
-
-        // Set the min value
-        if (metadataContainer.isObject() && metadataContainer.isMember("minValue"))
-        {
-          minValue = metadataContainer["minValue"].asDouble();
-        }
-        else 
-        {
-          minValue = 0.0;
-        }
-
-        // Set the instrument
-        if (metadataContainer.isObject() && metadataContainer.isMember("instrument"))
-        {
-          instrument = metadataContainer["instrument"].asString();
-        }
-        else 
-        {
-          instrument = "_EMPTY_";
-        }
-
-        // Set the instrument
-        if (metadataContainer.isObject() && metadataContainer.isMember("specialCoordinates"))
-        {
-          specialCoordinates = metadataContainer["specialCoordinates"].asInt();
-        }
-        else 
-        {
-          specialCoordinates = -1;
-        }
-      }
-    }
-
-    /**
-     * Set the max value of the workspace's data range.
-     * @param maxValue The max value.
-     */
-    void MetadataJsonManager::setMaxValue(double maxValue)
-    {
-      this->maxValue = maxValue;
-    }
-
-    /**
-     * Get the max value of teh workspace''s data range.
-     * @return The max value or 0.0.
-     */
-    double MetadataJsonManager::getMaxValue()
-    {
-      return maxValue;
-    }
-
-    /**
-     * Set the min value of the workspace's data range.
-     * @param minValue The min value.
-     */
-    void MetadataJsonManager::setMinValue(double minValue)
-    {
-      this->minValue = minValue;
-    }
-
-    /**
-     * Get the min value of teh workspace's data range.
-     * @returns The min value or 0.0;
-     *
-     */
-    double MetadataJsonManager::getMinValue()
-    {
-      return minValue;
-    }
-
-    /**
-     * Set the instrument.
-     * @param instrument The instrument associated with the workspace.
-     */
-    void MetadataJsonManager::setInstrument(std::string instrument)
-    {
-      this->instrument = instrument;
-    }
-
-    /**
-     * Get the instrument.
-     * @returns The stored instrument or the an empty string.
-     */
-    std::string& MetadataJsonManager::getInstrument()
-    {
-      return instrument;
-    }
-
-    /**
-     * Set the special coordinates.
-     * @param specialCoordinates The special coordinates.
-     */
-    void MetadataJsonManager::setSpecialCoordinates(int specialCoordinates)
-    {
-      this->specialCoordinates = specialCoordinates;
-    }
-
-    /**
-     * Get the special coordinates
-     * @returns The special coordinates.
-     */
-    int MetadataJsonManager::getSpecialCoordinates()
-    {
-      return specialCoordinates;
+    // Set the instrument
+    if (metadataContainer.isObject() &&
+        metadataContainer.isMember("specialCoordinates")) {
+      specialCoordinates = metadataContainer["specialCoordinates"].asInt();
+    } else {
+      specialCoordinates = -1;
     }
   }
+}
+
+/**
+ * Set the max value of the workspace's data range.
+ * @param maxValue The max value.
+ */
+void MetadataJsonManager::setMaxValue(double maxValue) {
+  this->maxValue = maxValue;
+}
+
+/**
+ * Get the max value of teh workspace''s data range.
+ * @return The max value or 0.0.
+ */
+double MetadataJsonManager::getMaxValue() { return maxValue; }
+
+/**
+ * Set the min value of the workspace's data range.
+ * @param minValue The min value.
+ */
+void MetadataJsonManager::setMinValue(double minValue) {
+  this->minValue = minValue;
+}
+
+/**
+ * Get the min value of teh workspace's data range.
+ * @returns The min value or 0.0;
+ *
+ */
+double MetadataJsonManager::getMinValue() { return minValue; }
+
+/**
+ * Set the instrument.
+ * @param instrument The instrument associated with the workspace.
+ */
+void MetadataJsonManager::setInstrument(std::string instrument) {
+  this->instrument = instrument;
+}
+
+/**
+ * Get the instrument.
+ * @returns The stored instrument or the an empty string.
+ */
+std::string &MetadataJsonManager::getInstrument() { return instrument; }
+
+/**
+ * Set the special coordinates.
+ * @param specialCoordinates The special coordinates.
+ */
+void MetadataJsonManager::setSpecialCoordinates(int specialCoordinates) {
+  this->specialCoordinates = specialCoordinates;
+}
+
+/**
+ * Get the special coordinates
+ * @returns The special coordinates.
+ */
+int MetadataJsonManager::getSpecialCoordinates() { return specialCoordinates; }
+}
 }
\ No newline at end of file
diff --git a/Vates/VatesAPI/src/MetadataToFieldData.cpp b/Vates/VatesAPI/src/MetadataToFieldData.cpp
index c98cf40a19f6aa2f4ab4b8e9e656946a3065979e..4cafe5c4ace83099a20782df52adad4530adc874 100644
--- a/Vates/VatesAPI/src/MetadataToFieldData.cpp
+++ b/Vates/VatesAPI/src/MetadataToFieldData.cpp
@@ -3,35 +3,31 @@
 #include "vtkFieldData.h"
 #include "vtkNew.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-void MetadataToFieldData::operator()(vtkFieldData* fieldData, std::string metaData, std::string id) const
-{
+void MetadataToFieldData::operator()(vtkFieldData *fieldData,
+                                     std::string metaData,
+                                     std::string id) const {
   execute(fieldData, metaData, id);
 }
 
-void MetadataToFieldData::execute(vtkFieldData* fieldData, std::string metaData, std::string id) const
-{
-  //clean out existing.
-  vtkDataArray* arry = fieldData->GetArray(id.c_str());
-  if(NULL != arry)
-  {
+void MetadataToFieldData::execute(vtkFieldData *fieldData, std::string metaData,
+                                  std::string id) const {
+  // clean out existing.
+  vtkDataArray *arry = fieldData->GetArray(id.c_str());
+  if (NULL != arry) {
     fieldData->RemoveArray(id.c_str());
   }
-  //create new.
+  // create new.
   vtkNew<vtkCharArray> newArry;
   newArry->Allocate(metaData.size());
   newArry->SetName(id.c_str());
   fieldData->AddArray(newArry.GetPointer());
 
-  for(unsigned int i = 0 ; i < metaData.size(); i++)
-  {
+  for (unsigned int i = 0; i < metaData.size(); i++) {
     newArry->InsertNextValue(metaData.at(i));
   }
 }
-
 }
 }
diff --git a/Vates/VatesAPI/src/NoThresholdRange.cpp b/Vates/VatesAPI/src/NoThresholdRange.cpp
index b95645f7008c156dbc9277dd7bdd10326912ab41..6f605e03f8ddfcefde7a97cef6a4c1f717d073a5 100644
--- a/Vates/VatesAPI/src/NoThresholdRange.cpp
+++ b/Vates/VatesAPI/src/NoThresholdRange.cpp
@@ -1,86 +1,65 @@
 #include "MantidVatesAPI/NoThresholdRange.h"
 #include <stdexcept>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-    /**
-    Constructor.
-    */
-    NoThresholdRange::NoThresholdRange() : m_min(0), m_max(0)
-    {
-    }
+/**
+Constructor.
+*/
+NoThresholdRange::NoThresholdRange() : m_min(0), m_max(0) {}
 
-     /**
-    Constructor.
-    */
-    NoThresholdRange::NoThresholdRange(signal_t min, signal_t max) : m_min(min), m_max(max)
-    {
-    }
+/**
+Constructor.
+*/
+NoThresholdRange::NoThresholdRange(signal_t min, signal_t max)
+    : m_min(min), m_max(max) {}
 
-    /**
-    Indicates wheter execution has occured or not.
-    return : true always.
-    */
-    bool NoThresholdRange::hasCalculated() const
-    {
-      return true;
-    }
+/**
+Indicates wheter execution has occured or not.
+return : true always.
+*/
+bool NoThresholdRange::hasCalculated() const { return true; }
 
-    /**
-    Destructor.
-    */
-    NoThresholdRange::~NoThresholdRange()
-    {
-    }
+/**
+Destructor.
+*/
+NoThresholdRange::~NoThresholdRange() {}
 
-    /**
-    Do nothing calculate method.
-    */
-    void NoThresholdRange::calculate()
-    {
-    }
+/**
+Do nothing calculate method.
+*/
+void NoThresholdRange::calculate() {}
 
-    /**
-    Minimum value getter.
-    @return The minimum value.
-    */
-    double NoThresholdRange::getMinimum() const
-    {
-      return m_min;
-    }
+/**
+Minimum value getter.
+@return The minimum value.
+*/
+double NoThresholdRange::getMinimum() const { return m_min; }
 
-    /**
-    Maximum value getter.
-    @return The maximum value.
-    */
-    double NoThresholdRange::getMaximum() const
-    {
-      return m_max;
-    }
+/**
+Maximum value getter.
+@return The maximum value.
+*/
+double NoThresholdRange::getMaximum() const { return m_max; }
 
+/**
+Virtual constructor clone method.
+@return clone of original.
+*/
+NoThresholdRange *NoThresholdRange::clone() const {
+  return new NoThresholdRange(this->m_min, this->m_max);
+}
 
-    /**
-    Virtual constructor clone method.
-    @return clone of original.
-    */
-    NoThresholdRange* NoThresholdRange::clone() const
-    {
-      return new NoThresholdRange(this->m_min, this->m_max);
-    }
-
-    /**
-    Determine whether the signal is withing range.
-    @param signal value
-    @return true if the signal is in the range defined by this object.
-    */
-    bool NoThresholdRange::inRange(const signal_t& signal)
-    {
-      m_max = signal > m_max ? signal : m_max; //cache min and max values.
-      m_min = signal < m_min ? signal : m_min;
-      return true;
-    }
-  }
+/**
+Determine whether the signal is withing range.
+@param signal value
+@return true if the signal is in the range defined by this object.
+*/
+bool NoThresholdRange::inRange(const signal_t &signal) {
+  m_max = signal > m_max ? signal : m_max; // cache min and max values.
+  m_min = signal < m_min ? signal : m_min;
+  return true;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/PresenterUtilities.cpp b/Vates/VatesAPI/src/PresenterUtilities.cpp
index 728c4af5275f14878b6073c0e1667e8f0e6ebebc..f6f32fa88836b8d472c81ed44d890ef7ba9a8449 100644
--- a/Vates/VatesAPI/src/PresenterUtilities.cpp
+++ b/Vates/VatesAPI/src/PresenterUtilities.cpp
@@ -10,7 +10,6 @@
 #include "MantidVatesAPI/vtkMDQuadFactory.h"
 #include "MantidVatesAPI/vtkMDLineFactory.h"
 
-
 #include "MantidKernel/Logger.h"
 #include "MantidKernel/make_unique.h"
 
@@ -20,16 +19,13 @@
 #include <ctime>
 #include <algorithm>
 
-namespace
-{
+namespace {
 /// Static logger
 Mantid::Kernel::Logger g_log_presenter_utilities("PresenterUtilities");
 }
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
  * Gets a clipped object
@@ -37,16 +33,15 @@ namespace VATES
  * @returns a clipped object
  */
 vtkSmartPointer<vtkPVClipDataSet>
-getClippedDataSet(vtkSmartPointer<vtkDataSet> dataSet)
-{
-    auto box = vtkSmartPointer<vtkBox>::New();
-    box->SetBounds(dataSet->GetBounds());
-    auto clipper = vtkSmartPointer<vtkPVClipDataSet>::New();
-    clipper->SetInputData(dataSet);
-    clipper->SetClipFunction(box);
-    clipper->SetInsideOut(true);
-    clipper->Update();
-    return clipper;
+getClippedDataSet(vtkSmartPointer<vtkDataSet> dataSet) {
+  auto box = vtkSmartPointer<vtkBox>::New();
+  box->SetBounds(dataSet->GetBounds());
+  auto clipper = vtkSmartPointer<vtkPVClipDataSet>::New();
+  clipper->SetInputData(dataSet);
+  clipper->SetClipFunction(box);
+  clipper->SetInsideOut(true);
+  clipper->Update();
+  return clipper;
 }
 
 /**
@@ -59,25 +54,24 @@ getClippedDataSet(vtkSmartPointer<vtkDataSet> dataSet)
  */
 void applyCOBMatrixSettingsToVtkDataSet(
     Mantid::VATES::MDLoadingPresenter *presenter, vtkDataSet *dataSet,
-    std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider)
-{
-    try {
-        presenter->makeNonOrthogonal(dataSet, std::move(workspaceProvider));
-    } catch (std::invalid_argument &e) {
-        std::string error = e.what();
-        g_log_presenter_utilities.warning()
-            << "PresenterUtilities: Workspace does not have correct "
-               "information to "
-            << "plot non-orthogonal axes: " << error;
-        // Add the standard change of basis matrix and set the boundaries
-        presenter->setDefaultCOBandBoundaries(dataSet);
-    } catch (...) {
-        g_log_presenter_utilities.warning()
-            << "PresenterUtilities: Workspace does not have correct "
-               "information to "
-            << "plot non-orthogonal axes. Non-orthogonal axes features require "
-               "three dimensions.";
-    }
+    std::unique_ptr<Mantid::VATES::WorkspaceProvider> workspaceProvider) {
+  try {
+    presenter->makeNonOrthogonal(dataSet, std::move(workspaceProvider));
+  } catch (std::invalid_argument &e) {
+    std::string error = e.what();
+    g_log_presenter_utilities.warning()
+        << "PresenterUtilities: Workspace does not have correct "
+           "information to "
+        << "plot non-orthogonal axes: " << error;
+    // Add the standard change of basis matrix and set the boundaries
+    presenter->setDefaultCOBandBoundaries(dataSet);
+  } catch (...) {
+    g_log_presenter_utilities.warning()
+        << "PresenterUtilities: Workspace does not have correct "
+           "information to "
+        << "plot non-orthogonal axes. Non-orthogonal axes features require "
+           "three dimensions.";
+  }
 }
 
 /**
@@ -90,17 +84,16 @@ void applyCOBMatrixSettingsToVtkDataSet(
 std::unique_ptr<vtkMDHexFactory>
 createFactoryChainForEventWorkspace(ThresholdRange_scptr threshold,
                                     VisualNormalization normalization,
-                                    double time)
-{
-    auto factory = Mantid::Kernel::make_unique<vtkMDHexFactory>(threshold,
-                                                                normalization);
-    factory->setSuccessor(Mantid::Kernel::make_unique<vtkMDQuadFactory>(
-                              threshold, normalization))
-        .setSuccessor(Mantid::Kernel::make_unique<vtkMDLineFactory>(
-            threshold, normalization))
-        .setSuccessor(Mantid::Kernel::make_unique<vtkMD0DFactory>());
-    factory->setTime(time);
-    return factory;
+                                    double time) {
+  auto factory =
+      Mantid::Kernel::make_unique<vtkMDHexFactory>(threshold, normalization);
+  factory->setSuccessor(Mantid::Kernel::make_unique<vtkMDQuadFactory>(
+                            threshold, normalization))
+      .setSuccessor(Mantid::Kernel::make_unique<vtkMDLineFactory>(
+          threshold, normalization))
+      .setSuccessor(Mantid::Kernel::make_unique<vtkMD0DFactory>());
+  factory->setTime(time);
+  return factory;
 }
 
 /**
@@ -113,19 +106,18 @@ createFactoryChainForEventWorkspace(ThresholdRange_scptr threshold,
 std::unique_ptr<vtkMDHistoHex4DFactory<TimeToTimeStep>>
 createFactoryChainForHistoWorkspace(ThresholdRange_scptr threshold,
                                     VisualNormalization normalization,
-                                    double time)
-{
-    auto factory
-        = Mantid::Kernel::make_unique<vtkMDHistoHex4DFactory<TimeToTimeStep>>(
-            threshold, normalization, time);
-    factory->setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoHexFactory>(
-                              threshold, normalization))
-        .setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoQuadFactory>(
-            threshold, normalization))
-        .setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoLineFactory>(
-            threshold, normalization))
-        .setSuccessor(Mantid::Kernel::make_unique<vtkMD0DFactory>());
-    return factory;
+                                    double time) {
+  auto factory =
+      Mantid::Kernel::make_unique<vtkMDHistoHex4DFactory<TimeToTimeStep>>(
+          threshold, normalization, time);
+  factory->setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoHexFactory>(
+                            threshold, normalization))
+      .setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoQuadFactory>(
+          threshold, normalization))
+      .setSuccessor(Mantid::Kernel::make_unique<vtkMDHistoLineFactory>(
+          threshold, normalization))
+      .setSuccessor(Mantid::Kernel::make_unique<vtkMD0DFactory>());
+  return factory;
 }
 
 /**
@@ -133,23 +125,22 @@ createFactoryChainForHistoWorkspace(ThresholdRange_scptr threshold,
 * @param name: the input name
 * @return a name with a time stamp
 */
-std::string createTimeStampedName(std::string name)
-{
-    auto currentTime = std::chrono::system_clock::to_time_t(
-        std::chrono::system_clock::now());
-    std::string timeInReadableFormat = std::string(std::ctime(&currentTime));
-    // Replace all white space with double underscore
-    std::replace(timeInReadableFormat.begin(), timeInReadableFormat.end(), ' ',
-                 '_');
-    // Replace all colons with single underscore
-    std::replace(timeInReadableFormat.begin(), timeInReadableFormat.end(), ':',
-                 '_');
-    timeInReadableFormat.erase(std::remove(timeInReadableFormat.begin(),
-                                           timeInReadableFormat.end(), '\n'),
-                               timeInReadableFormat.end());
-    std::string stampedName = name + "_";
-    stampedName = stampedName + timeInReadableFormat;
-    return stampedName;
+std::string createTimeStampedName(std::string name) {
+  auto currentTime =
+      std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
+  std::string timeInReadableFormat = std::string(std::ctime(&currentTime));
+  // Replace all white space with double underscore
+  std::replace(timeInReadableFormat.begin(), timeInReadableFormat.end(), ' ',
+               '_');
+  // Replace all colons with single underscore
+  std::replace(timeInReadableFormat.begin(), timeInReadableFormat.end(), ':',
+               '_');
+  timeInReadableFormat.erase(std::remove(timeInReadableFormat.begin(),
+                                         timeInReadableFormat.end(), '\n'),
+                             timeInReadableFormat.end());
+  std::string stampedName = name + "_";
+  stampedName = stampedName + timeInReadableFormat;
+  return stampedName;
 }
 }
 }
diff --git a/Vates/VatesAPI/src/ProgressAction.cpp b/Vates/VatesAPI/src/ProgressAction.cpp
index 1cd5f56f7d7019490a74c260c0e289a4ff4d47fd..624abfae3173addb3db1747feb3ea8e48682c576 100644
--- a/Vates/VatesAPI/src/ProgressAction.cpp
+++ b/Vates/VatesAPI/src/ProgressAction.cpp
@@ -1,19 +1,13 @@
 #include "MantidVatesAPI/ProgressAction.h"
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-ProgressAction::ProgressAction()
-{
-}
+ProgressAction::ProgressAction() {}
 
-void ProgressAction::handler(const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification>& pNf)
-{
-    this->eventRaised(pNf->progress);
+void ProgressAction::handler(
+    const Poco::AutoPtr<Mantid::API::Algorithm::ProgressNotification> &pNf) {
+  this->eventRaised(pNf->progress);
 }
-
 }
 }
-
diff --git a/Vates/VatesAPI/src/SQWLoadingPresenter.cpp b/Vates/VatesAPI/src/SQWLoadingPresenter.cpp
index d7097c2fbb0c34145fa8d41bf88c11fad2ccba48..b7026167a68f2cc2094ceac4467c5ede9a5347fd 100644
--- a/Vates/VatesAPI/src/SQWLoadingPresenter.cpp
+++ b/Vates/VatesAPI/src/SQWLoadingPresenter.cpp
@@ -8,10 +8,8 @@
 #include "MantidAPI/AlgorithmManager.h"
 #include <boost/regex.hpp>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
 /*
     Constructor
@@ -21,162 +19,161 @@ namespace Mantid
     @throw invalid_arument if view is null
     @throw logic_error if cannot use the reader-presenter for this filetype.
     */
-  SQWLoadingPresenter::SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view,
-                                           const std::string filename)
-      : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
-        m_wsTypeName("") {
-    if (this->m_filename.empty()) {
-      throw std::invalid_argument("File name is an empty string.");
-    }
-    if (nullptr == this->m_view) {
-      throw std::invalid_argument("View is NULL.");
-    }
+SQWLoadingPresenter::SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view,
+                                         const std::string filename)
+    : MDEWLoadingPresenter(std::move(view)), m_filename(filename),
+      m_wsTypeName("") {
+  if (this->m_filename.empty()) {
+    throw std::invalid_argument("File name is an empty string.");
   }
+  if (nullptr == this->m_view) {
+    throw std::invalid_argument("View is NULL.");
+  }
+}
 
-  /*
- Indicates whether this presenter is capable of handling the type of file that
- is attempted to be loaded.
- @return false if the file cannot be read.
- */
-  bool SQWLoadingPresenter::canReadFile() const {
-    boost::regex expression(
-        ".*sqw$",
-        boost::regex_constants::icase); // check that the file ends with sqw.
-    return boost::regex_match(this->m_filename, expression);
-    }
-
+/*
+Indicates whether this presenter is capable of handling the type of file that
+is attempted to be loaded.
+@return false if the file cannot be read.
+*/
+bool SQWLoadingPresenter::canReadFile() const {
+  boost::regex expression(
+      ".*sqw$",
+      boost::regex_constants::icase); // check that the file ends with sqw.
+  return boost::regex_match(this->m_filename, expression);
+}
 
-    /*
-    Executes the underlying algorithm to create the MVP model.
-    @param factory : visualisation factory to use.
-    @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses.
-    @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs.
-    */
-    vtkSmartPointer<vtkDataSet>
-    SQWLoadingPresenter::execute(vtkDataSetFactory *factory,
-                                 ProgressAction &loadingProgressUpdate,
-                                 ProgressAction &drawingProgressUpdate) {
-      using namespace Mantid::API;
-      using namespace Mantid::Geometry;
-
-      if(this->shouldLoad())
-      {
-        Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification> observer(loadingProgressUpdate, &ProgressAction::handler);
-        AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-        
-        IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadSQW");
-
-        alg->initialize();
-        alg->setPropertyValue("Filename", this->m_filename);
-        alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-        //Default is not to load into memory and when this is the case, generate a nxs backend for output.
-        if(!this->m_view->getLoadInMemory())
-        {
-          size_t pos = this->m_filename.find(".");
-          std::string backEndFile = this->m_filename.substr(0, pos) + ".nxs";
-          alg->setPropertyValue("OutputFilename", backEndFile);
-        }
-        alg->addObserver(observer);
-        alg->execute();
-        alg->removeObserver(observer);
-      }
-
-      Workspace_sptr result=AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-      Mantid::API::IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
-
-      factory->setRecursionDepth(this->m_view->getRecursionDepth());
-      
-      auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
-
-      this->appendMetadata(visualDataSet, eventWs->getName());
-      
-      return visualDataSet;
+/*
+Executes the underlying algorithm to create the MVP model.
+@param factory : visualisation factory to use.
+@param loadingProgressUpdate : Handler for GUI updates while algorithm
+progresses.
+@param drawingProgressUpdate : Handler for GUI updates while
+vtkDataSetFactory::create occurs.
+*/
+vtkSmartPointer<vtkDataSet>
+SQWLoadingPresenter::execute(vtkDataSetFactory *factory,
+                             ProgressAction &loadingProgressUpdate,
+                             ProgressAction &drawingProgressUpdate) {
+  using namespace Mantid::API;
+  using namespace Mantid::Geometry;
+
+  if (this->shouldLoad()) {
+    Poco::NObserver<ProgressAction,
+                    Mantid::API::Algorithm::ProgressNotification>
+        observer(loadingProgressUpdate, &ProgressAction::handler);
+    AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+
+    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadSQW");
+
+    alg->initialize();
+    alg->setPropertyValue("Filename", this->m_filename);
+    alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
+    // Default is not to load into memory and when this is the case, generate a
+    // nxs backend for output.
+    if (!this->m_view->getLoadInMemory()) {
+      size_t pos = this->m_filename.find(".");
+      std::string backEndFile = this->m_filename.substr(0, pos) + ".nxs";
+      alg->setPropertyValue("OutputFilename", backEndFile);
     }
+    alg->addObserver(observer);
+    alg->execute();
+    alg->removeObserver(observer);
+  }
 
-     /*
-    Extract the geometry and function information 
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  Mantid::API::IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
 
-    This implementation is an override of the base-class method, which deals with the more common event based route. However the SQW files will provide complete
-    dimensions with ranges already set. Less work needs to be done here than for event workspaces where the extents of each dimension need to be individually
-    extracted.
+  factory->setRecursionDepth(this->m_view->getRecursionDepth());
 
-    @param eventWs : event workspace to get the information from.
-    */
-    void SQWLoadingPresenter::extractMetadata(
-        const Mantid::API::IMDEventWorkspace &eventWs) {
-      using namespace Mantid::Geometry;
-      MDGeometryBuilderXML<NoDimensionPolicy> refresh;
-      this->xmlBuilder= refresh; //Reassign.
-      std::vector<IMDDimension_sptr> dimensions;
-      size_t nDimensions = eventWs.getNumDims();
-      for (size_t d=0; d<nDimensions; d++)
-      {
-        IMDDimension_const_sptr inDim = eventWs.getDimension(d);
-        axisLabels.push_back(makeAxisTitle(*inDim));
-        //Copy the dimension, but set the ID and name to be the same. This is an assumption in bintohistoworkspace.
-        dimensions.push_back(boost::make_shared<MDHistoDimension>(
-            inDim->getName(), inDim->getName(), inDim->getMDFrame(),
-            inDim->getMinimum(), inDim->getMaximum(), size_t{10}));
-      }
-
-      //Configuring the geometry xml builder allows the object panel associated with this reader to later
-      //determine how to display all geometry related properties.
-      if(nDimensions > 0)
-      {
-        this->xmlBuilder.addXDimension( dimensions[0] );
-      }
-      if(nDimensions > 1)
-      {
-        this->xmlBuilder.addYDimension( dimensions[1] );
-      }
-      if(nDimensions > 2)
-      {
-        this->xmlBuilder.addZDimension( dimensions[2]  );
-      }
-      if(nDimensions > 3)
-      {
-        this->tDimension = dimensions[3];
-        this->xmlBuilder.addTDimension(this->tDimension);
-      }
-      this->m_isSetup = true;
-    }
-    
+  auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate);
 
-    /**
-     Executes any meta-data loading required.
-    */
-    void SQWLoadingPresenter::executeLoadMetadata()
-    {
-      using namespace Mantid::API;
-      using namespace Mantid::Geometry;
-
-      AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-
-      IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadSQW");
-      alg->initialize();
-      alg->setPropertyValue("Filename", this->m_filename);
-      alg->setProperty("MetadataOnly", true); //Don't load the events.
-      alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-      alg->execute();
-
-      Workspace_sptr result=AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-      Mantid::API::IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
-      m_wsTypeName = eventWs->id();
-      //Call base-class extraction method.
-      extractMetadata(*eventWs);
-    }
+  this->appendMetadata(visualDataSet, eventWs->getName());
 
-    ///Destructor
-    SQWLoadingPresenter::~SQWLoadingPresenter() {}
+  return visualDataSet;
+}
 
-    /*
-    Getter for the workspace type name.
-    @return Workspace Type Name
-    */
-    std::string SQWLoadingPresenter::getWorkspaceTypeName()
-    {
-      return m_wsTypeName;
-    }
+/*
+Extract the geometry and function information
+
+This implementation is an override of the base-class method, which deals with
+the more common event based route. However the SQW files will provide complete
+dimensions with ranges already set. Less work needs to be done here than for
+event workspaces where the extents of each dimension need to be individually
+extracted.
+
+@param eventWs : event workspace to get the information from.
+*/
+void SQWLoadingPresenter::extractMetadata(
+    const Mantid::API::IMDEventWorkspace &eventWs) {
+  using namespace Mantid::Geometry;
+  MDGeometryBuilderXML<NoDimensionPolicy> refresh;
+  this->xmlBuilder = refresh; // Reassign.
+  std::vector<IMDDimension_sptr> dimensions;
+  size_t nDimensions = eventWs.getNumDims();
+  for (size_t d = 0; d < nDimensions; d++) {
+    IMDDimension_const_sptr inDim = eventWs.getDimension(d);
+    axisLabels.push_back(makeAxisTitle(*inDim));
+    // Copy the dimension, but set the ID and name to be the same. This is an
+    // assumption in bintohistoworkspace.
+    dimensions.push_back(boost::make_shared<MDHistoDimension>(
+        inDim->getName(), inDim->getName(), inDim->getMDFrame(),
+        inDim->getMinimum(), inDim->getMaximum(), size_t{10}));
+  }
 
-    }
-    }
+  // Configuring the geometry xml builder allows the object panel associated
+  // with this reader to later
+  // determine how to display all geometry related properties.
+  if (nDimensions > 0) {
+    this->xmlBuilder.addXDimension(dimensions[0]);
+  }
+  if (nDimensions > 1) {
+    this->xmlBuilder.addYDimension(dimensions[1]);
+  }
+  if (nDimensions > 2) {
+    this->xmlBuilder.addZDimension(dimensions[2]);
+  }
+  if (nDimensions > 3) {
+    this->tDimension = dimensions[3];
+    this->xmlBuilder.addTDimension(this->tDimension);
+  }
+  this->m_isSetup = true;
+}
+
+/**
+ Executes any meta-data loading required.
+*/
+void SQWLoadingPresenter::executeLoadMetadata() {
+  using namespace Mantid::API;
+  using namespace Mantid::Geometry;
+
+  AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+
+  IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadSQW");
+  alg->initialize();
+  alg->setPropertyValue("Filename", this->m_filename);
+  alg->setProperty("MetadataOnly", true); // Don't load the events.
+  alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
+  alg->execute();
+
+  Workspace_sptr result =
+      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  Mantid::API::IMDEventWorkspace_sptr eventWs =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
+  m_wsTypeName = eventWs->id();
+  // Call base-class extraction method.
+  extractMetadata(*eventWs);
+}
+
+/// Destructor
+SQWLoadingPresenter::~SQWLoadingPresenter() {}
+
+/*
+Getter for the workspace type name.
+@return Workspace Type Name
+*/
+std::string SQWLoadingPresenter::getWorkspaceTypeName() { return m_wsTypeName; }
+}
+}
diff --git a/Vates/VatesAPI/src/SaveMDWorkspaceToVTKImpl.cpp b/Vates/VatesAPI/src/SaveMDWorkspaceToVTKImpl.cpp
index aa8dae58ac1ab17ade3e4aa3bc6ec892acf546ca..50144a6cd49a43cca6dd2fa3cd152d31f06cfc46 100644
--- a/Vates/VatesAPI/src/SaveMDWorkspaceToVTKImpl.cpp
+++ b/Vates/VatesAPI/src/SaveMDWorkspaceToVTKImpl.cpp
@@ -144,15 +144,13 @@ SaveMDWorkspaceToVTKImpl::getPresenter(bool isHistoWorkspace,
       Mantid::Kernel::make_unique<SingleWorkspaceProvider>(workspace);
   if (isHistoWorkspace) {
     InMemoryPresenterFactory<MDHWInMemoryLoadingPresenter,
-                             EmptyWorkspaceNamePolicy>
-        presenterFactory;
+                             EmptyWorkspaceNamePolicy> presenterFactory;
     presenter = presenterFactory.create(std::move(view), workspace,
                                         std::move(workspaceProvider));
   } else {
     view->setRecursionDepth(recursionDepth);
     InMemoryPresenterFactory<MDEWInMemoryLoadingPresenter,
-                             EmptyWorkspaceNamePolicy>
-        presenterFactory;
+                             EmptyWorkspaceNamePolicy> presenterFactory;
     presenter = presenterFactory.create(std::move(view), workspace,
                                         std::move(workspaceProvider));
   }
diff --git a/Vates/VatesAPI/src/TimeStepToTimeStep.cpp b/Vates/VatesAPI/src/TimeStepToTimeStep.cpp
index fedadd8a48293d94194fb613727a00941c1e4edd..09c013d97534828eaa3a830b9e1cdfe6120a6145 100644
--- a/Vates/VatesAPI/src/TimeStepToTimeStep.cpp
+++ b/Vates/VatesAPI/src/TimeStepToTimeStep.cpp
@@ -1,28 +1,24 @@
 #include "MantidVatesAPI/TimeStepToTimeStep.h"
 
-namespace Mantid
-{
-namespace VATES
-{
-TimeStepToTimeStep::TimeStepToTimeStep(double timeMin, double timeMax, size_t intervalStep) :
-  m_timeRange(0.0), m_nIntervalSteps(0)
-{
+namespace Mantid {
+namespace VATES {
+TimeStepToTimeStep::TimeStepToTimeStep(double timeMin, double timeMax,
+                                       size_t intervalStep)
+    : m_timeRange(0.0), m_nIntervalSteps(0) {
   UNUSED_ARG(timeMin);
   UNUSED_ARG(timeMax);
   UNUSED_ARG(intervalStep);
 }
 
-TimeStepToTimeStep TimeStepToTimeStep::construct(double timeMin, double timeMax, size_t nIntervalSteps)
-{
+TimeStepToTimeStep TimeStepToTimeStep::construct(double timeMin, double timeMax,
+                                                 size_t nIntervalSteps) {
   return TimeStepToTimeStep(timeMin, timeMax, nIntervalSteps);
 }
 
-TimeStepToTimeStep::TimeStepToTimeStep() : m_timeRange(0.0), m_nIntervalSteps(0)
-{
-}
+TimeStepToTimeStep::TimeStepToTimeStep()
+    : m_timeRange(0.0), m_nIntervalSteps(0) {}
 
-size_t TimeStepToTimeStep::operator()(double timeStep) const
-{
+size_t TimeStepToTimeStep::operator()(double timeStep) const {
   return static_cast<size_t>(timeStep);
 }
 }
diff --git a/Vates/VatesAPI/src/TimeToTimeStep.cpp b/Vates/VatesAPI/src/TimeToTimeStep.cpp
index d3e0467f28ade704b5ec30235907af99f694eeac..70fce9daa7e52b2057ffca2b19afa1671d57a576 100644
--- a/Vates/VatesAPI/src/TimeToTimeStep.cpp
+++ b/Vates/VatesAPI/src/TimeToTimeStep.cpp
@@ -1,17 +1,15 @@
 #include "MantidVatesAPI/TimeToTimeStep.h"
 #include <stdexcept>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
 /**
   Constructional method.
   @return a fully constructed TimeToTimestep instance.
 */
-TimeToTimeStep TimeToTimeStep::construct(double timeMin, double timeMax, size_t nIntervalSteps)
-{
+TimeToTimeStep TimeToTimeStep::construct(double timeMin, double timeMax,
+                                         size_t nIntervalSteps) {
   return TimeToTimeStep(timeMin, timeMax, nIntervalSteps);
 }
 
@@ -21,47 +19,45 @@ TimeToTimeStep TimeToTimeStep::construct(double timeMin, double timeMax, size_t
   @param timeMax : the maximum time/parameter in the range.
   @param nIntervalSteps : the number of interval steps available.
 */
-TimeToTimeStep::TimeToTimeStep(double timeMin, double timeMax, size_t nIntervalSteps) : m_timeMin(timeMin), m_timeMax(timeMax),
-  m_timeRange(timeMax - timeMin), m_nIntervalSteps(nIntervalSteps), m_runnable(true)
-{
-  if(m_timeRange <= 0)
-  {
-    throw std::runtime_error("Range must be positive. timeMax should be > timeMin");
+TimeToTimeStep::TimeToTimeStep(double timeMin, double timeMax,
+                               size_t nIntervalSteps)
+    : m_timeMin(timeMin), m_timeMax(timeMax), m_timeRange(timeMax - timeMin),
+      m_nIntervalSteps(nIntervalSteps), m_runnable(true) {
+  if (m_timeRange <= 0) {
+    throw std::runtime_error(
+        "Range must be positive. timeMax should be > timeMin");
   }
-  //This fraction is convenient to pre-calculate.
+  // This fraction is convenient to pre-calculate.
   m_fraction = (1 / m_timeRange) * static_cast<double>(m_nIntervalSteps);
-  //The offset is scoped for the functor lifetime.
-  m_c = -1 * m_fraction * m_timeMin; 
+  // The offset is scoped for the functor lifetime.
+  m_c = -1 * m_fraction * m_timeMin;
 }
 
 /**
   Default constructor.
 */
-TimeToTimeStep::TimeToTimeStep(): m_timeMin(0.0), m_timeMax(0.0), m_timeRange(0.0),
-  m_c(0.0), m_fraction(0.0), m_nIntervalSteps(0), m_runnable(false)
-{
-}
+TimeToTimeStep::TimeToTimeStep()
+    : m_timeMin(0.0), m_timeMax(0.0), m_timeRange(0.0), m_c(0.0),
+      m_fraction(0.0), m_nIntervalSteps(0), m_runnable(false) {}
 
 /**
-  Overloaded funtion operator. 
-  @param time : time/property value wrt max and min property values of this type.
+  Overloaded funtion operator.
+  @param time : time/property value wrt max and min property values of this
+  type.
   @return a calculated index for the time/property value provided.
 */
-size_t TimeToTimeStep::operator()(double time) const
-{
-  if(!m_runnable)
-  {
-    throw std::runtime_error("Not properly constructed. TimeToTimeStep instance does not have enough information to interpolate the time value.");
+size_t TimeToTimeStep::operator()(double time) const {
+  if (!m_runnable) {
+    throw std::runtime_error("Not properly constructed. TimeToTimeStep "
+                             "instance does not have enough information to "
+                             "interpolate the time value.");
   }
-  if(time > m_timeMax || time < m_timeMin)
-  {
+  if (time > m_timeMax || time < m_timeMin) {
     return 0;
-  }
-  else
-  {
-    return static_cast<size_t>((time * m_fraction) + m_c);  //Linear interpolation
+  } else {
+    return static_cast<size_t>((time * m_fraction) +
+                               m_c); // Linear interpolation
   }
 }
-
 }
 }
diff --git a/Vates/VatesAPI/src/UserDefinedThresholdRange.cpp b/Vates/VatesAPI/src/UserDefinedThresholdRange.cpp
index 1be58ff59e7b2d7953ae4386781d427ef89d116b..a47a679ef1114cf69f03a2e3746ffd72f70623b9 100644
--- a/Vates/VatesAPI/src/UserDefinedThresholdRange.cpp
+++ b/Vates/VatesAPI/src/UserDefinedThresholdRange.cpp
@@ -1,83 +1,65 @@
 #include "MantidVatesAPI/UserDefinedThresholdRange.h"
 #include <stdexcept>
 
-namespace Mantid
-{
-  namespace VATES
-  {
+namespace Mantid {
+namespace VATES {
 
-    /**
-    Constructor.
-    @param min : range min.
-    @param max : range max.
-    */
-    UserDefinedThresholdRange::UserDefinedThresholdRange(signal_t min, signal_t max) : m_min(min), m_max(max)
-    {
-      if(max < min)
-      {
-        throw std::invalid_argument("Cannot have max < min in a UserDefinedThresholdRange.");
-      }
-    }
-
-    /**
-    Indicates wheter execution has occured or not.
-    return : true always.
-    */
-    bool UserDefinedThresholdRange::hasCalculated() const
-    {
-      return true;
-    }
+/**
+Constructor.
+@param min : range min.
+@param max : range max.
+*/
+UserDefinedThresholdRange::UserDefinedThresholdRange(signal_t min, signal_t max)
+    : m_min(min), m_max(max) {
+  if (max < min) {
+    throw std::invalid_argument(
+        "Cannot have max < min in a UserDefinedThresholdRange.");
+  }
+}
 
-    /**
-    Destructor.
-    */
-    UserDefinedThresholdRange::~UserDefinedThresholdRange()
-    {
-    }
+/**
+Indicates wheter execution has occured or not.
+return : true always.
+*/
+bool UserDefinedThresholdRange::hasCalculated() const { return true; }
 
-    /**
-    Do nothing calculate method.
-    */
-    void UserDefinedThresholdRange::calculate()
-    {
-    }
+/**
+Destructor.
+*/
+UserDefinedThresholdRange::~UserDefinedThresholdRange() {}
 
-    /**
-    Minimum value getter.
-    @return The minimum value.
-    */
-    double UserDefinedThresholdRange::getMinimum() const
-    {
-      return m_min;
-    }
+/**
+Do nothing calculate method.
+*/
+void UserDefinedThresholdRange::calculate() {}
 
-    /**
-    Maximum value getter.
-    @return The maximum value.
-    */
-    double UserDefinedThresholdRange::getMaximum() const
-    {
-      return m_max;
-    }
+/**
+Minimum value getter.
+@return The minimum value.
+*/
+double UserDefinedThresholdRange::getMinimum() const { return m_min; }
 
+/**
+Maximum value getter.
+@return The maximum value.
+*/
+double UserDefinedThresholdRange::getMaximum() const { return m_max; }
 
-    /**
-    Virtual constructor clone method.
-    @return clone of original.
-    */
-    UserDefinedThresholdRange* UserDefinedThresholdRange::clone() const
-    {
-      return new UserDefinedThresholdRange(this->m_min, this->m_max);
-    }
+/**
+Virtual constructor clone method.
+@return clone of original.
+*/
+UserDefinedThresholdRange *UserDefinedThresholdRange::clone() const {
+  return new UserDefinedThresholdRange(this->m_min, this->m_max);
+}
 
-    /**
-    Determine whether the signal is withing range.
-    @param signal value
-    @return true if the signal is in the range defined by this object.
-    */
-    bool UserDefinedThresholdRange::inRange(const signal_t& signal)
-    {
-      return signal >= m_min && signal <= m_max;
-    }
-  }
+/**
+Determine whether the signal is withing range.
+@param signal value
+@return true if the signal is in the range defined by this object.
+*/
+bool UserDefinedThresholdRange::inRange(const signal_t &signal) {
+  return signal >= m_min && signal <= m_max;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/VatesConfigurations.cpp b/Vates/VatesAPI/src/VatesConfigurations.cpp
index bf4523816f3766329cf6cdec4aa67f7852988479..d7ae6659fa830ffa382dc5cd5702afd6520f7cce 100644
--- a/Vates/VatesAPI/src/VatesConfigurations.cpp
+++ b/Vates/VatesAPI/src/VatesConfigurations.cpp
@@ -1,52 +1,46 @@
 #include "MantidVatesAPI/VatesConfigurations.h"
 
-namespace Mantid
-{
-  namespace VATES
-  {
-	 /** Metadata container and handler to handle json data which is passed between filters and sources through 
-	     VTK field data
-
-	 @date 31/11/2014
-
-	 Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
-
-	 This file is part of Mantid.
-
-	 Mantid is free software; you can redistribute it and/or modify
-	 it under the terms of the GNU General Public License as published by
-	 the Free Software Foundation; either version 3 of the License, or
-	 (at your option) any later version.
-
-	 Mantid is distributed in the hope that it will be useful,
-	 but WITHOUT ANY WARRANTY; without even the implied warranty of
-	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	 GNU General Public License for more details.
-
-	 You should have received a copy of the GNU General Public License
-	 along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-	 File change history is stored at: <https://github.com/mantidproject/mantid>
-	 Code Documentation is available at: <http://doxygen.mantidproject.org>
-	 */
-	  
-
-    VatesConfigurations::VatesConfigurations() : maxRecursionDepth(10000),metaDataId("VATES_Metadata_Json")
-    {
-    }
-
-    VatesConfigurations::~VatesConfigurations()
-    {
-    }
-
-    int VatesConfigurations::getMaxRecursionDepth()
-    {
-      return this->maxRecursionDepth;
-    }
-
-    std::string VatesConfigurations::getMetadataIdJson()
-    {
-      return this->metaDataId;
-    }
-  }
+namespace Mantid {
+namespace VATES {
+/** Metadata container and handler to handle json data which is passed between
+filters and sources through
+    VTK field data
+
+@date 31/11/2014
+
+Copyright &copy; 2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+National Laboratory
+
+This file is part of Mantid.
+
+Mantid is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+Mantid is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+File change history is stored at: <https://github.com/mantidproject/mantid>
+Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+VatesConfigurations::VatesConfigurations()
+    : maxRecursionDepth(10000), metaDataId("VATES_Metadata_Json") {}
+
+VatesConfigurations::~VatesConfigurations() {}
+
+int VatesConfigurations::getMaxRecursionDepth() {
+  return this->maxRecursionDepth;
+}
+
+std::string VatesConfigurations::getMetadataIdJson() {
+  return this->metaDataId;
+}
+}
 }
\ No newline at end of file
diff --git a/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp b/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
index 8fe711d88bba447d96837fbe44c0265555b6da1f..1a88636a27aa7e4b1118aa23c7cc57f3f5945e88 100644
--- a/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
+++ b/Vates/VatesAPI/src/VatesKnowledgeSerializer.cpp
@@ -8,89 +8,84 @@
 #include "MantidVatesAPI/VatesXMLDefinitions.h"
 
 using Mantid::Geometry::MDGeometryXMLDefinitions;
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-VatesKnowledgeSerializer::VatesKnowledgeSerializer() : 
-  m_wsLocationXML(""), 
-  m_wsNameXML(""), 
-  m_wsName(""), 
-  m_geomXML("")
-{
-}
+VatesKnowledgeSerializer::VatesKnowledgeSerializer()
+    : m_wsLocationXML(""), m_wsNameXML(""), m_wsName(""), m_geomXML("") {}
 
-void VatesKnowledgeSerializer::setImplicitFunction(boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> spFunction)
-{
+void VatesKnowledgeSerializer::setImplicitFunction(
+    boost::shared_ptr<const Mantid::Geometry::MDImplicitFunction> spFunction) {
   this->m_spFunction = spFunction;
 }
 
 /// Set the workspace name to apply.
-void VatesKnowledgeSerializer::setWorkspace(boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace)
-{
-  
-  this->m_wsNameXML =  MDGeometryXMLDefinitions::workspaceNameXMLTagStart() + workspace->getName() + MDGeometryXMLDefinitions::workspaceNameXMLTagEnd();
-  this->m_wsLocationXML =   MDGeometryXMLDefinitions::workspaceLocationXMLTagStart() + "" + MDGeometryXMLDefinitions::workspaceLocationXMLTagEnd();
+void VatesKnowledgeSerializer::setWorkspace(
+    boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace) {
+
+  this->m_wsNameXML = MDGeometryXMLDefinitions::workspaceNameXMLTagStart() +
+                      workspace->getName() +
+                      MDGeometryXMLDefinitions::workspaceNameXMLTagEnd();
+  this->m_wsLocationXML =
+      MDGeometryXMLDefinitions::workspaceLocationXMLTagStart() + "" +
+      MDGeometryXMLDefinitions::workspaceLocationXMLTagEnd();
   this->m_geomXML = workspace->getGeometryXML();
 }
 
-void VatesKnowledgeSerializer::setWorkspaceName(std::string wsName)
-{
+void VatesKnowledgeSerializer::setWorkspaceName(std::string wsName) {
   this->m_wsName = wsName;
-  this->m_wsNameXML =   std::string(MDGeometryXMLDefinitions::workspaceNameXMLTagStart()  + wsName + MDGeometryXMLDefinitions::workspaceNameXMLTagEnd());
+  this->m_wsNameXML =
+      std::string(MDGeometryXMLDefinitions::workspaceNameXMLTagStart() +
+                  wsName + MDGeometryXMLDefinitions::workspaceNameXMLTagEnd());
 }
 
-void VatesKnowledgeSerializer::setGeometryXML(std::string geomXML)
-{
+void VatesKnowledgeSerializer::setGeometryXML(std::string geomXML) {
   this->m_geomXML = geomXML;
 }
 
 /// Create the xml string correponding to the set values.
-std::string VatesKnowledgeSerializer::createXMLString() const
-{
+std::string VatesKnowledgeSerializer::createXMLString() const {
 
-  if(true == this->m_geomXML.empty())
-  {
+  if (true == this->m_geomXML.empty()) {
     throw std::runtime_error("No geometry provided on workspace.");
   }
 
-  if(this->m_wsNameXML == (MDGeometryXMLDefinitions::workspaceNameXMLTagStart() + MDGeometryXMLDefinitions::workspaceNameXMLTagEnd()))
-  {
+  if (this->m_wsNameXML ==
+      (MDGeometryXMLDefinitions::workspaceNameXMLTagStart() +
+       MDGeometryXMLDefinitions::workspaceNameXMLTagEnd())) {
     throw std::runtime_error("No workspace name provided on workspace.");
   }
-  //Check to see if a function has been provided.
-  if(m_spFunction != NULL)
-  {
-    return std::string(MDGeometryXMLDefinitions::workspaceInstructionXMLTagStart()  + m_wsNameXML + m_wsLocationXML + m_geomXML + m_spFunction->toXMLString() + MDGeometryXMLDefinitions::workspaceInstructionXMLTagEnd());
-  }
-  else
-  {
-    //Functions are optional, so don't provide them as part of the completed xml if not present.
-    return std::string(MDGeometryXMLDefinitions::workspaceInstructionXMLTagStart()  + m_wsNameXML + m_wsLocationXML + m_geomXML + MDGeometryXMLDefinitions::workspaceInstructionXMLTagEnd());
+  // Check to see if a function has been provided.
+  if (m_spFunction != NULL) {
+    return std::string(
+        MDGeometryXMLDefinitions::workspaceInstructionXMLTagStart() +
+        m_wsNameXML + m_wsLocationXML + m_geomXML +
+        m_spFunction->toXMLString() +
+        MDGeometryXMLDefinitions::workspaceInstructionXMLTagEnd());
+  } else {
+    // Functions are optional, so don't provide them as part of the completed
+    // xml if not present.
+    return std::string(
+        MDGeometryXMLDefinitions::workspaceInstructionXMLTagStart() +
+        m_wsNameXML + m_wsLocationXML + m_geomXML +
+        MDGeometryXMLDefinitions::workspaceInstructionXMLTagEnd());
   }
 }
 
-const std::string& VatesKnowledgeSerializer::getWorkspaceName() const
-{
+const std::string &VatesKnowledgeSerializer::getWorkspaceName() const {
   return this->m_wsName;
 }
 
-const std::string& VatesKnowledgeSerializer::getWorkspaceGeometry() const
-{
+const std::string &VatesKnowledgeSerializer::getWorkspaceGeometry() const {
   return this->m_geomXML;
 }
 
- bool VatesKnowledgeSerializer::hasFunctionInfo() const
- {
-   return NULL != m_spFunction.get();
- }
-
- bool VatesKnowledgeSerializer::hasGeometryInfo() const
- {
-   return  !m_geomXML.empty() && !m_wsName.empty();
- }
-
+bool VatesKnowledgeSerializer::hasFunctionInfo() const {
+  return NULL != m_spFunction.get();
+}
 
+bool VatesKnowledgeSerializer::hasGeometryInfo() const {
+  return !m_geomXML.empty() && !m_wsName.empty();
+}
 }
 }
diff --git a/Vates/VatesAPI/src/VatesXMLDefinitions.cpp b/Vates/VatesAPI/src/VatesXMLDefinitions.cpp
index 294fa91ac2ed7aed1dfe2b6ee570692f7db8b080..59f6b47712e45dc33db9f47b435b6b26676da79c 100644
--- a/Vates/VatesAPI/src/VatesXMLDefinitions.cpp
+++ b/Vates/VatesAPI/src/VatesXMLDefinitions.cpp
@@ -1,9 +1,5 @@
 #include "MantidVatesAPI/VatesXMLDefinitions.h"
 
-namespace Mantid
-{
-namespace VATES
-{
-
-}
+namespace Mantid {
+namespace VATES {}
 }
diff --git a/Vates/VatesAPI/src/ViewFrustum.cpp b/Vates/VatesAPI/src/ViewFrustum.cpp
index 7ab18720a9966594334f5cb79a57fadb17d700d0..a7b895bd9904d51b8a9f98a714534306ad88a6ca 100644
--- a/Vates/VatesAPI/src/ViewFrustum.cpp
+++ b/Vates/VatesAPI/src/ViewFrustum.cpp
@@ -1,116 +1,126 @@
 #include "MantidVatesAPI/ViewFrustum.h"
 #include "MantidKernel/Matrix.h"
-#include <sstream> 
+#include <sstream>
 #include <cmath>
 #include <cfloat>
 
-namespace Mantid
-{
-namespace VATES
-{
-  /**
-   * Represents a view frustum. It contains the parameters for the six plane equations that define the view frustum. Note that the plane 
-   * normals point into the box
-   * @param leftPlane The left plane.
-   * @param rightPlane The right plane.
-   * @param topPlane The top plane.
-   * @param bottomPlane The bottom plane.
-   * @param farPlane The far plane.
-   * @param nearPlane The near plane.
-   */
-  ViewFrustum::ViewFrustum(const LeftPlane leftPlane, const RightPlane rightPlane, const BottomPlane bottomPlane,
-                            const TopPlane topPlane, const FarPlane farPlane,  const NearPlane nearPlane) : m_leftPlane(leftPlane),
-                                                                                                                    m_rightPlane(rightPlane),
-                                                                                                                    m_topPlane(topPlane),
-                                                                                                                    m_bottomPlane(bottomPlane),
-                                                                                                                    m_farPlane(farPlane),
-                                                                                                                    m_nearPlane(nearPlane){}
-  /**
-   * Copy constructor for the view frustum.
-   * @param other The initializing view frustum.
-   */
-  ViewFrustum::ViewFrustum(const ViewFrustum& other): m_leftPlane(other.m_leftPlane),
-                                                      m_rightPlane(other.m_rightPlane),
-                                                      m_topPlane(other.m_topPlane),
-                                                      m_bottomPlane(other.m_bottomPlane),
-                                                      m_farPlane(other.m_farPlane),
-                                                      m_nearPlane(other.m_nearPlane){}
-  /// Destructor
-  ViewFrustum::~ViewFrustum(){}
-
-  /**
-   * Assignment operator
-   * @param other The assigned view frustum.
-   */
-  ViewFrustum& ViewFrustum::operator=(const ViewFrustum& other)
-  {
-    if (&other != this)
-    {
-      m_leftPlane = other.m_leftPlane;
-      m_rightPlane  = other.m_rightPlane;
-      m_topPlane = other.m_topPlane;
-      m_bottomPlane = other.m_bottomPlane;
-      m_farPlane = other.m_farPlane;
-      m_nearPlane = other.m_nearPlane;
-    }
+namespace Mantid {
+namespace VATES {
+/**
+ * Represents a view frustum. It contains the parameters for the six plane
+ * equations that define the view frustum. Note that the plane
+ * normals point into the box
+ * @param leftPlane The left plane.
+ * @param rightPlane The right plane.
+ * @param topPlane The top plane.
+ * @param bottomPlane The bottom plane.
+ * @param farPlane The far plane.
+ * @param nearPlane The near plane.
+ */
+ViewFrustum::ViewFrustum(const LeftPlane leftPlane, const RightPlane rightPlane,
+                         const BottomPlane bottomPlane, const TopPlane topPlane,
+                         const FarPlane farPlane, const NearPlane nearPlane)
+    : m_leftPlane(leftPlane), m_rightPlane(rightPlane), m_topPlane(topPlane),
+      m_bottomPlane(bottomPlane), m_farPlane(farPlane), m_nearPlane(nearPlane) {
+}
+/**
+ * Copy constructor for the view frustum.
+ * @param other The initializing view frustum.
+ */
+ViewFrustum::ViewFrustum(const ViewFrustum &other)
+    : m_leftPlane(other.m_leftPlane), m_rightPlane(other.m_rightPlane),
+      m_topPlane(other.m_topPlane), m_bottomPlane(other.m_bottomPlane),
+      m_farPlane(other.m_farPlane), m_nearPlane(other.m_nearPlane) {}
+/// Destructor
+ViewFrustum::~ViewFrustum() {}
 
-    return *this;
+/**
+ * Assignment operator
+ * @param other The assigned view frustum.
+ */
+ViewFrustum &ViewFrustum::operator=(const ViewFrustum &other) {
+  if (&other != this) {
+    m_leftPlane = other.m_leftPlane;
+    m_rightPlane = other.m_rightPlane;
+    m_topPlane = other.m_topPlane;
+    m_bottomPlane = other.m_bottomPlane;
+    m_farPlane = other.m_farPlane;
+    m_nearPlane = other.m_nearPlane;
   }
 
-  /**
-   * Get the extents of the View frustum. We take the minimal rectangular box which in contains the 
-   * view frustum fully.
-   * @returns A vector with the extents
-   */
-  std::vector<std::pair<double, double>> ViewFrustum::toExtents() const
-  {
-    // Get the eight corner points of the view frustum
-    std::vector<std::vector<double>> frustumPoints;
-    frustumPoints.push_back(getIntersectionPointThreePlanes<LEFTPLANE, TOPPLANE, FARPLANE, double>(m_leftPlane, m_topPlane, m_farPlane));
-    frustumPoints.push_back(getIntersectionPointThreePlanes<LEFTPLANE, TOPPLANE, NEARPLANE, double>(m_leftPlane, m_topPlane, m_nearPlane));
+  return *this;
+}
 
-    frustumPoints.push_back(getIntersectionPointThreePlanes<LEFTPLANE, BOTTOMPLANE, FARPLANE, double>(m_leftPlane, m_bottomPlane, m_farPlane));
-    frustumPoints.push_back(getIntersectionPointThreePlanes<LEFTPLANE, BOTTOMPLANE, NEARPLANE, double>(m_leftPlane, m_bottomPlane, m_nearPlane));
+/**
+ * Get the extents of the View frustum. We take the minimal rectangular box
+ * which in contains the
+ * view frustum fully.
+ * @returns A vector with the extents
+ */
+std::vector<std::pair<double, double>> ViewFrustum::toExtents() const {
+  // Get the eight corner points of the view frustum
+  std::vector<std::vector<double>> frustumPoints;
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<LEFTPLANE, TOPPLANE, FARPLANE, double>(
+          m_leftPlane, m_topPlane, m_farPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<LEFTPLANE, TOPPLANE, NEARPLANE, double>(
+          m_leftPlane, m_topPlane, m_nearPlane));
 
-    frustumPoints.push_back(getIntersectionPointThreePlanes<RIGHTPLANE, TOPPLANE, FARPLANE, double>(m_rightPlane, m_topPlane, m_farPlane));
-    frustumPoints.push_back(getIntersectionPointThreePlanes<RIGHTPLANE, TOPPLANE, NEARPLANE, double>(m_rightPlane, m_topPlane, m_nearPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<LEFTPLANE, BOTTOMPLANE, FARPLANE, double>(
+          m_leftPlane, m_bottomPlane, m_farPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<LEFTPLANE, BOTTOMPLANE, NEARPLANE,
+                                      double>(m_leftPlane, m_bottomPlane,
+                                              m_nearPlane));
 
-    frustumPoints.push_back(getIntersectionPointThreePlanes<RIGHTPLANE, BOTTOMPLANE, FARPLANE, double>(m_rightPlane, m_bottomPlane, m_farPlane));
-    frustumPoints.push_back(getIntersectionPointThreePlanes<RIGHTPLANE, BOTTOMPLANE, NEARPLANE, double>(m_rightPlane, m_bottomPlane, m_nearPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<RIGHTPLANE, TOPPLANE, FARPLANE, double>(
+          m_rightPlane, m_topPlane, m_farPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<RIGHTPLANE, TOPPLANE, NEARPLANE, double>(
+          m_rightPlane, m_topPlane, m_nearPlane));
 
-    std::vector<std::pair<double, double>> extents;
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<RIGHTPLANE, BOTTOMPLANE, FARPLANE,
+                                      double>(m_rightPlane, m_bottomPlane,
+                                              m_farPlane));
+  frustumPoints.push_back(
+      getIntersectionPointThreePlanes<RIGHTPLANE, BOTTOMPLANE, NEARPLANE,
+                                      double>(m_rightPlane, m_bottomPlane,
+                                              m_nearPlane));
 
-    for (int i = 0; i < 3; ++i)
-    {
-      std::pair<double, double> minMax(DBL_MAX, -DBL_MAX);
-      for (auto &points : frustumPoints) {
-        minMax.first = std::min(minMax.first, points[i]);
-        minMax.second = std::max(minMax.second, points[i]);
-      }
-      extents.push_back(minMax);
-    }
+  std::vector<std::pair<double, double>> extents;
 
-    return extents;
+  for (int i = 0; i < 3; ++i) {
+    std::pair<double, double> minMax(DBL_MAX, -DBL_MAX);
+    for (auto &points : frustumPoints) {
+      minMax.first = std::min(minMax.first, points[i]);
+      minMax.second = std::max(minMax.second, points[i]);
+    }
+    extents.push_back(minMax);
   }
 
-  /**
-   * Get the extents as a concatenated string.
-   * @returns The extens of the view frustum as a concatenated string
-   */
-  std::string ViewFrustum::toExtentsAsString() const
-  {
-    std::vector<std::pair<double, double>> extents = toExtents();
-    
-    std::stringstream ss;
-    for (const auto &extent : extents) {
-      ss << extent.first << "," << extent.second << ",";
-    }
-    auto result = ss.str();
+  return extents;
+}
 
-    // remove extra "," at the end of the string.
-    result.pop_back();
-    return result;
+/**
+ * Get the extents as a concatenated string.
+ * @returns The extens of the view frustum as a concatenated string
+ */
+std::string ViewFrustum::toExtentsAsString() const {
+  std::vector<std::pair<double, double>> extents = toExtents();
+
+  std::stringstream ss;
+  for (const auto &extent : extents) {
+    ss << extent.first << "," << extent.second << ",";
   }
+  auto result = ss.str();
 
+  // remove extra "," at the end of the string.
+  result.pop_back();
+  return result;
+}
 }
 }
diff --git a/Vates/VatesAPI/src/vtkDataSetFactory.cpp b/Vates/VatesAPI/src/vtkDataSetFactory.cpp
index 67d033cfb62ef7efff500deb9c3c8b4b76b89f2b..57fdf45b78bc3783e08e2bd06526517a6e84b6c4 100644
--- a/Vates/VatesAPI/src/vtkDataSetFactory.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetFactory.cpp
@@ -2,14 +2,11 @@
 #include "MantidVatesAPI/ProgressAction.h"
 #include <stdexcept>
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-vtkDataSetFactory::vtkDataSetFactory() : m_useTransform(false), m_bCheckDimensionality(true)
-{
-}
+vtkDataSetFactory::vtkDataSetFactory()
+    : m_useTransform(false), m_bCheckDimensionality(true) {}
 
 /**
  * Checks the successor and throws if invalid.
@@ -32,8 +29,7 @@ void vtkDataSetFactory::checkSuccessor() const {
 Set a flag indicating whether dimensionality should be checked
 @param flag : TRUE to check dimensionality otherwise FALSE.
 */
-void vtkDataSetFactory::setCheckDimensionality(bool flag)
-{
+void vtkDataSetFactory::setCheckDimensionality(bool flag) {
   m_bCheckDimensionality = flag;
 }
 
@@ -41,12 +37,10 @@ void vtkDataSetFactory::setCheckDimensionality(bool flag)
 Get a flag indicating whether dimensionality should be checked
 @return true if dimensionality is checked.
 */
-bool vtkDataSetFactory::doesCheckDimensionality() const
-{
+bool vtkDataSetFactory::doesCheckDimensionality() const {
   return m_bCheckDimensionality;
 }
 
-
 /*
 Convenience function. Creates an output visualisation data set in one-shot.
 
@@ -62,8 +56,6 @@ vtkDataSetFactory::oneStepCreate(Mantid::API::Workspace_sptr ws,
 }
 
 // What we call the scalar array bearing the signal values in the vtk data set.
-const std::string vtkDataSetFactory::ScalarName ="signal";
-
+const std::string vtkDataSetFactory::ScalarName = "signal";
 }
-
 }
diff --git a/Vates/VatesAPI/src/vtkDataSetToGeometry.cpp b/Vates/VatesAPI/src/vtkDataSetToGeometry.cpp
index b4f3849d0ab3b973e76090acea3f605c9ef945ff..c3d651677d5ca419bb9658862d0aeaee3ff4d2e8 100644
--- a/Vates/VatesAPI/src/vtkDataSetToGeometry.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToGeometry.cpp
@@ -4,61 +4,55 @@
 #include "MantidGeometry/MDGeometry/MDGeometryXMLDefinitions.h"
 #include "vtkDataSet.h"
 
-#include<algorithm>
+#include <algorithm>
 using namespace Mantid::Geometry;
 
-namespace Mantid
-{
-  namespace VATES
-  {
-     /**
-     Peforms the processing associated with these transformations.
-     */
-      void vtkDataSetToGeometry::execute()
-      {
-        FieldDataToMetadata convert;
-        m_xmlToProcess = convert(m_dataSet->GetFieldData(), XMLDefinitions::metaDataId());
+namespace Mantid {
+namespace VATES {
+/**
+Peforms the processing associated with these transformations.
+*/
+void vtkDataSetToGeometry::execute() {
+  FieldDataToMetadata convert;
+  m_xmlToProcess =
+      convert(m_dataSet->GetFieldData(), XMLDefinitions::metaDataId());
 
-        return MDGeometryXMLParser::execute();
-      }
+  return MDGeometryXMLParser::execute();
+}
 
-     /**
-     Constructor
-     @param dataSet : vtkDataSet to process
-     */
-      vtkDataSetToGeometry::vtkDataSetToGeometry(vtkDataSet* dataSet) : m_dataSet(dataSet)
-      {
-        //Format is to have DimensionSet as a nested element below MDInstructions.
-        SetRootNodeCheck(Mantid::Geometry::MDGeometryXMLDefinitions::workspaceGeometryElementName());
-      }
+/**
+Constructor
+@param dataSet : vtkDataSet to process
+*/
+vtkDataSetToGeometry::vtkDataSetToGeometry(vtkDataSet *dataSet)
+    : m_dataSet(dataSet) {
+  // Format is to have DimensionSet as a nested element below MDInstructions.
+  SetRootNodeCheck(Mantid::Geometry::MDGeometryXMLDefinitions::
+                       workspaceGeometryElementName());
+}
 
-      /**
-      Destructor
-      */
-      vtkDataSetToGeometry::~vtkDataSetToGeometry()
-      {
-      }
+/**
+Destructor
+*/
+vtkDataSetToGeometry::~vtkDataSetToGeometry() {}
 
-      /**
-      Copy constructor
-      */
-      vtkDataSetToGeometry::vtkDataSetToGeometry(const vtkDataSetToGeometry& other) : MDGeometryXMLParser(other)
-        ,m_dataSet(other.m_dataSet)
-      {
-      }
+/**
+Copy constructor
+*/
+vtkDataSetToGeometry::vtkDataSetToGeometry(const vtkDataSetToGeometry &other)
+    : MDGeometryXMLParser(other), m_dataSet(other.m_dataSet) {}
 
-      /**
-      Assignment operator
-      @return ref to assigned object.
-      */
-      vtkDataSetToGeometry& vtkDataSetToGeometry::operator=(const vtkDataSetToGeometry& other)
-      {
-        if(this != &other)
-        {
-          MDGeometryXMLParser::operator=(other);
-          m_dataSet = other.m_dataSet;
-        }
-        return *this;
-      }
+/**
+Assignment operator
+@return ref to assigned object.
+*/
+vtkDataSetToGeometry &vtkDataSetToGeometry::
+operator=(const vtkDataSetToGeometry &other) {
+  if (this != &other) {
+    MDGeometryXMLParser::operator=(other);
+    m_dataSet = other.m_dataSet;
   }
+  return *this;
+}
+}
 }
diff --git a/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp b/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp
index 9ec7e3523fd02a05f8cbb0ea560b4a2fdc5efa05..829079bec7953d933752f5273f5d47554e510352 100644
--- a/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp
@@ -7,68 +7,62 @@
 #include "MantidKernel/make_unique.h"
 #include <vtkDataSet.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /**
-    Static creational method to run functionality in one method call.
-    @param dataSet : input dataset containing field data.
-    @return extracted implicit function.
-    */
-    Mantid::Geometry::MDImplicitFunction* vtkDataSetToImplicitFunction::exec(vtkDataSet* dataSet)
-    {
-      vtkDataSetToImplicitFunction temp(dataSet);
-      return temp.execute();
-    }
-
-    
-    /**
-    Constructor
-    @param dataSet : input dataset containing field data.
-    */
-    vtkDataSetToImplicitFunction::vtkDataSetToImplicitFunction(vtkDataSet* dataSet) : m_dataset(dataSet)
-    {
-      if(m_dataset == NULL)
-      {
-        throw std::runtime_error("Tried to construct vtkDataSetToImplicitFunction with NULL vtkDataSet");
-      }
-    }
+namespace Mantid {
+namespace VATES {
+/**
+Static creational method to run functionality in one method call.
+@param dataSet : input dataset containing field data.
+@return extracted implicit function.
+*/
+Mantid::Geometry::MDImplicitFunction *
+vtkDataSetToImplicitFunction::exec(vtkDataSet *dataSet) {
+  vtkDataSetToImplicitFunction temp(dataSet);
+  return temp.execute();
+}
 
-    /**
-    Execution method to run the extraction.
-    @return implicit function if one could be found, or a NullImplicitFunction.
-    */
-    Mantid::Geometry::MDImplicitFunction* vtkDataSetToImplicitFunction::execute()
-    {
-      using Mantid::Geometry::NullImplicitFunction;
-      using Mantid::Geometry::MDGeometryXMLDefinitions;
-      std::unique_ptr<Mantid::Geometry::MDImplicitFunction> function =
-          Mantid::Kernel::make_unique<NullImplicitFunction>();
+/**
+Constructor
+@param dataSet : input dataset containing field data.
+*/
+vtkDataSetToImplicitFunction::vtkDataSetToImplicitFunction(vtkDataSet *dataSet)
+    : m_dataset(dataSet) {
+  if (m_dataset == NULL) {
+    throw std::runtime_error(
+        "Tried to construct vtkDataSetToImplicitFunction with NULL vtkDataSet");
+  }
+}
 
-      FieldDataToMetadata convert;
-      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId()); 
-      if (false == xmlString.empty())
-      {
-        Poco::XML::DOMParser pParser;
-        Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
-        Poco::XML::Element* pRootElem = pDoc->documentElement();
-        Poco::XML::Element* functionElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::functionElementName());
-        if(NULL != functionElem)
-        {
-          auto existingFunction =
-              std::unique_ptr<Mantid::Geometry::MDImplicitFunction>(
-                  Mantid::API::ImplicitFunctionFactory::Instance()
-                      .createUnwrapped(functionElem));
-          function.swap(existingFunction);
-        }
-      }
-      return function.release();
-    }
+/**
+Execution method to run the extraction.
+@return implicit function if one could be found, or a NullImplicitFunction.
+*/
+Mantid::Geometry::MDImplicitFunction *vtkDataSetToImplicitFunction::execute() {
+  using Mantid::Geometry::NullImplicitFunction;
+  using Mantid::Geometry::MDGeometryXMLDefinitions;
+  std::unique_ptr<Mantid::Geometry::MDImplicitFunction> function =
+      Mantid::Kernel::make_unique<NullImplicitFunction>();
 
-    /// Destructor.
-    vtkDataSetToImplicitFunction::~vtkDataSetToImplicitFunction()
-    {
+  FieldDataToMetadata convert;
+  std::string xmlString =
+      convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());
+  if (false == xmlString.empty()) {
+    Poco::XML::DOMParser pParser;
+    Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
+    Poco::XML::Element *pRootElem = pDoc->documentElement();
+    Poco::XML::Element *functionElem = pRootElem->getChildElement(
+        MDGeometryXMLDefinitions::functionElementName());
+    if (NULL != functionElem) {
+      auto existingFunction =
+          std::unique_ptr<Mantid::Geometry::MDImplicitFunction>(
+              Mantid::API::ImplicitFunctionFactory::Instance().createUnwrapped(
+                  functionElem));
+      function.swap(existingFunction);
     }
   }
+  return function.release();
+}
+
+/// Destructor.
+vtkDataSetToImplicitFunction::~vtkDataSetToImplicitFunction() {}
+}
 }
diff --git a/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp b/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
index e8b3ad69f423ed119639526f87e3e37dd896d0ce..254a1550f3199b9ecc7385c92d209c793a4cf5bc 100644
--- a/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToNonOrthogonalDataSet.cpp
@@ -80,11 +80,10 @@ namespace VATES {
  */
 void vtkDataSetToNonOrthogonalDataSet::exec(
     vtkDataSet *dataset, std::string name,
-    std::unique_ptr<WorkspaceProvider> workspaceProvider)
-{
-    vtkDataSetToNonOrthogonalDataSet temp(dataset, name,
-                                          std::move(workspaceProvider));
-    temp.execute();
+    std::unique_ptr<WorkspaceProvider> workspaceProvider) {
+  vtkDataSetToNonOrthogonalDataSet temp(dataset, name,
+                                        std::move(workspaceProvider));
+  temp.execute();
 }
 
 /**
@@ -99,19 +98,17 @@ vtkDataSetToNonOrthogonalDataSet::vtkDataSetToNonOrthogonalDataSet(
     : m_dataSet(dataset), m_wsName(name), m_numDims(3), m_skewMat(),
       m_basisNorm(), m_basisX(1, 0, 0), m_basisY(0, 1, 0), m_basisZ(0, 0, 1),
       m_coordType(Kernel::HKL),
-      m_workspaceProvider(std::move(workspaceProvider))
-{
-    if (NULL == m_dataSet) {
-        throw std::runtime_error(
-            "Cannot construct "
-            "vtkDataSetToNonOrthogonalDataSet with null VTK "
-            "dataset");
-    }
-    if (name.empty()) {
-        throw std::runtime_error("Cannot construct "
-                                 "vtkDataSetToNonOrthogonalDataSet without "
-                                 "associated workspace name");
-    }
+      m_workspaceProvider(std::move(workspaceProvider)) {
+  if (NULL == m_dataSet) {
+    throw std::runtime_error("Cannot construct "
+                             "vtkDataSetToNonOrthogonalDataSet with null VTK "
+                             "dataset");
+  }
+  if (name.empty()) {
+    throw std::runtime_error("Cannot construct "
+                             "vtkDataSetToNonOrthogonalDataSet without "
+                             "associated workspace name");
+  }
 }
 
 /**
diff --git a/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp b/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp
index 15e31f6cebfa412b11f5822ddab5a574834c4985..7797305d984c2cb4f7be80caad32d20e7e359438 100644
--- a/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp
@@ -32,15 +32,13 @@
 #include <string>
 #include <vector>
 
-namespace Mantid
-{
-namespace VATES
-{
-  /**
-    * Standard constructor for object.
-    * @param input : The dataset to peaks filter
-    * @param output : The resulting peaks filtered dataset
-    */
+namespace Mantid {
+namespace VATES {
+/**
+  * Standard constructor for object.
+  * @param input : The dataset to peaks filter
+  * @param output : The resulting peaks filtered dataset
+  */
 vtkDataSetToPeaksFilteredDataSet::vtkDataSetToPeaksFilteredDataSet(
     vtkSmartPointer<vtkUnstructuredGrid> input,
     vtkSmartPointer<vtkUnstructuredGrid> output)
@@ -178,7 +176,9 @@ vtkDataSetToPeaksFilteredDataSet::getPeaksInfo(
   return peaksInfo;
 }
 
+// clang-format off
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 /**
  * Get the radius from a PeakShape object.
  * @param shape The PeakShape from which the information will be extracted.
@@ -245,4 +245,3 @@ double vtkDataSetToPeaksFilteredDataSet::getRadiusFactor() {
 }
 }
 }
-
diff --git a/Vates/VatesAPI/src/vtkDataSetToScaledDataSet.cpp b/Vates/VatesAPI/src/vtkDataSetToScaledDataSet.cpp
index 0ffa0427e9dde5919e840067c9b406f5fa7d7fb9..bb5ec8cfc4db24af64147f84f23456b083edc7c0 100644
--- a/Vates/VatesAPI/src/vtkDataSetToScaledDataSet.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToScaledDataSet.cpp
@@ -23,8 +23,7 @@ namespace VATES {
 /**
  * Standard constructor for object.
  */
-vtkDataSetToScaledDataSet::vtkDataSetToScaledDataSet() {
-}
+vtkDataSetToScaledDataSet::vtkDataSetToScaledDataSet() {}
 
 vtkDataSetToScaledDataSet::~vtkDataSetToScaledDataSet() {}
 
@@ -41,20 +40,18 @@ vtkDataSetToScaledDataSet::~vtkDataSetToScaledDataSet() {}
  * @param info : info to obtain the output data set from.
  * @return The resulting scaled dataset
  */
-vtkPointSet *
-vtkDataSetToScaledDataSet::execute(double xScale, double yScale, double zScale,
-                                   vtkPointSet *inputData, vtkInformation* info) {
+vtkPointSet *vtkDataSetToScaledDataSet::execute(double xScale, double yScale,
+                                                double zScale,
+                                                vtkPointSet *inputData,
+                                                vtkInformation *info) {
 
   // Extract output dataset from information.
-  vtkPointSet *outputData = vtkPointSet::SafeDownCast(info->Get(vtkDataObject::DATA_OBJECT()));
+  vtkPointSet *outputData =
+      vtkPointSet::SafeDownCast(info->Get(vtkDataObject::DATA_OBJECT()));
 
   return execute(xScale, yScale, zScale, inputData, outputData);
-
 }
 
-
-
-
 /**
  * Process the input data. First, scale a copy of the points and apply
  * that to the output data. Next, update the metadata for range information.
@@ -65,20 +62,22 @@ vtkDataSetToScaledDataSet::execute(double xScale, double yScale, double zScale,
  * @param yScale : Scale factor for the y direction
  * @param zScale : Scale factor for the z direction
  * @param inputData : The dataset to scale
- * @param outputData : The output dataset. Optional. If not specified or null, new one created.
+ * @param outputData : The output dataset. Optional. If not specified or null,
+ *new one created.
  * @return The resulting scaled dataset
  */
-vtkPointSet *
-vtkDataSetToScaledDataSet::execute(double xScale, double yScale, double zScale,
-                                   vtkPointSet *inputData, vtkPointSet* outputData) {
+vtkPointSet *vtkDataSetToScaledDataSet::execute(double xScale, double yScale,
+                                                double zScale,
+                                                vtkPointSet *inputData,
+                                                vtkPointSet *outputData) {
 
   if (NULL == inputData) {
     throw std::runtime_error("Cannot construct vtkDataSetToScaledDataSet with "
                              "NULL input vtkPointSet");
   }
 
-  if(outputData == NULL){
-       outputData = inputData->NewInstance();
+  if (outputData == NULL) {
+    outputData = inputData->NewInstance();
   }
 
   vtkPoints *points = inputData->GetPoints();
@@ -137,20 +136,23 @@ vtkDataSetToScaledDataSet::execute(double xScale, double yScale, double zScale,
  * @param outputData : Output dataset
  */
 void vtkDataSetToScaledDataSet::updateMetaData(double xScale, double yScale,
-                                               double zScale, vtkPointSet *inputData, vtkPointSet *outputData) {
+                                               double zScale,
+                                               vtkPointSet *inputData,
+                                               vtkPointSet *outputData) {
   // We need to scale the basis vectors of the input ChangeOfBasis
   // (COB) Matrix and set it as the output COB Matrix.
   auto cobMatrix = vtkPVChangeOfBasisHelper::GetChangeOfBasisMatrix(inputData);
 
-  vtkVector3d u,v,w;
+  vtkVector3d u, v, w;
   if (vtkPVChangeOfBasisHelper::GetBasisVectors(cobMatrix, u, v, w)) {
-    u.Set(u.GetX()*xScale, u.GetY()*xScale, u.GetZ()*xScale);
-    v.Set(v.GetX()*yScale, v.GetY()*yScale, v.GetZ()*yScale);
-    w.Set(w.GetX()*zScale, w.GetY()*zScale, w.GetZ()*zScale);
-    cobMatrix = vtkPVChangeOfBasisHelper::GetChangeOfBasisMatrix(u,v,w);
+    u.Set(u.GetX() * xScale, u.GetY() * xScale, u.GetZ() * xScale);
+    v.Set(v.GetX() * yScale, v.GetY() * yScale, v.GetZ() * yScale);
+    w.Set(w.GetX() * zScale, w.GetY() * zScale, w.GetZ() * zScale);
+    cobMatrix = vtkPVChangeOfBasisHelper::GetChangeOfBasisMatrix(u, v, w);
   } else {
-    g_log.warning("Could not extract the basis vectors from the Change-of-Basis-Matrix"
-                  "data of the scaled data set.\n");
+    g_log.warning(
+        "Could not extract the basis vectors from the Change-of-Basis-Matrix"
+        "data of the scaled data set.\n");
     cobMatrix = vtkSmartPointer<vtkMatrix4x4>::New();
     cobMatrix->Identity();
     cobMatrix->Element[0][0] *= xScale;
diff --git a/Vates/VatesAPI/src/vtkDataSetToWsLocation.cpp b/Vates/VatesAPI/src/vtkDataSetToWsLocation.cpp
index f667b24f3aeb8afa46c60561f6fa92eea35290b9..6a7d17d65c06372421b13fad48d0e8e754146c13 100644
--- a/Vates/VatesAPI/src/vtkDataSetToWsLocation.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToWsLocation.cpp
@@ -8,58 +8,53 @@
 #include <Poco/DOM/Element.h>
 #include <Poco/DOM/Document.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /**
-    Static creational method to run functionality in one method call.
-    @param dataset : input dataset containing field data.
-    @return location string.
-    */
-    std::string vtkDataSetToWsLocation::exec(vtkDataSet* dataset)
-    {
-      vtkDataSetToWsLocation temp(dataset);
-      return temp.execute();
-    }
-
-    /**
-    Constructor
-    @param dataSet : input dataset containing field data.
-    */
-    vtkDataSetToWsLocation::vtkDataSetToWsLocation(vtkDataSet* dataSet)  : m_dataset(dataSet)
-    {
-      if(m_dataset == NULL)
-      {
-        throw std::runtime_error("Tried to construct vtkDataSetToWsLocation with NULL vtkDataSet");
-      }
-    }
-
-    /**
-    Execution method to run the extraction.
-    @return location string
-    */
-    std::string vtkDataSetToWsLocation::execute()
-    {
-      using Mantid::Geometry::MDGeometryXMLDefinitions;
-      FieldDataToMetadata convert;
-      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());
+namespace Mantid {
+namespace VATES {
+/**
+Static creational method to run functionality in one method call.
+@param dataset : input dataset containing field data.
+@return location string.
+*/
+std::string vtkDataSetToWsLocation::exec(vtkDataSet *dataset) {
+  vtkDataSetToWsLocation temp(dataset);
+  return temp.execute();
+}
 
-      Poco::XML::DOMParser pParser;
-      Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
-      Poco::XML::Element* pRootElem = pDoc->documentElement();
-      Poco::XML::Element* wsLocationElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::workspaceLocationElementName());
-      if(wsLocationElem == NULL)
-      {
-        throw std::runtime_error("The element containing the workspace location must be present.");
-      }
-      return wsLocationElem->innerText();
-    }
+/**
+Constructor
+@param dataSet : input dataset containing field data.
+*/
+vtkDataSetToWsLocation::vtkDataSetToWsLocation(vtkDataSet *dataSet)
+    : m_dataset(dataSet) {
+  if (m_dataset == NULL) {
+    throw std::runtime_error(
+        "Tried to construct vtkDataSetToWsLocation with NULL vtkDataSet");
+  }
+}
 
-    /// Destructor
-    vtkDataSetToWsLocation::~vtkDataSetToWsLocation()
-    {
-    }
+/**
+Execution method to run the extraction.
+@return location string
+*/
+std::string vtkDataSetToWsLocation::execute() {
+  using Mantid::Geometry::MDGeometryXMLDefinitions;
+  FieldDataToMetadata convert;
+  std::string xmlString =
+      convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());
 
+  Poco::XML::DOMParser pParser;
+  Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
+  Poco::XML::Element *pRootElem = pDoc->documentElement();
+  Poco::XML::Element *wsLocationElem = pRootElem->getChildElement(
+      MDGeometryXMLDefinitions::workspaceLocationElementName());
+  if (wsLocationElem == NULL) {
+    throw std::runtime_error(
+        "The element containing the workspace location must be present.");
   }
+  return wsLocationElem->innerText();
+}
+
+/// Destructor
+vtkDataSetToWsLocation::~vtkDataSetToWsLocation() {}
+}
 }
diff --git a/Vates/VatesAPI/src/vtkDataSetToWsName.cpp b/Vates/VatesAPI/src/vtkDataSetToWsName.cpp
index e877854b3dd7c8889b36b87840caad645f4b17ae..2393a03db255807abb4251b17bff54568efdedd5 100644
--- a/Vates/VatesAPI/src/vtkDataSetToWsName.cpp
+++ b/Vates/VatesAPI/src/vtkDataSetToWsName.cpp
@@ -8,57 +8,53 @@
 #include <Poco/DOM/Element.h>
 #include <Poco/DOM/Document.h>
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /**
-    Static creational method to run functionality in one method call.
-    @param dataset : input dataset containing field data.
-    @return extracted workspace name.
-    */
-    std::string vtkDataSetToWsName::exec(vtkDataSet* dataset)
-    {
-      vtkDataSetToWsName temp(dataset);
-      return temp.execute();
-    }
-
-    /**
-    Constructor
-    @param dataSet : input dataset containing field data.
-    */
-    vtkDataSetToWsName::vtkDataSetToWsName(vtkDataSet* dataSet)  : m_dataset(dataSet)
-    {
-      if(m_dataset == NULL)
-      {
-        throw std::runtime_error("Tried to construct vtkDataSetToWsName with NULL vtkDataSet");
-      }
-    }
+namespace Mantid {
+namespace VATES {
+/**
+Static creational method to run functionality in one method call.
+@param dataset : input dataset containing field data.
+@return extracted workspace name.
+*/
+std::string vtkDataSetToWsName::exec(vtkDataSet *dataset) {
+  vtkDataSetToWsName temp(dataset);
+  return temp.execute();
+}
 
-    /**
-    Runs the extraction
-    @return extracted workspace name.
-    */
-    std::string vtkDataSetToWsName::execute()
-    {
-      using Mantid::Geometry::MDGeometryXMLDefinitions;
-      FieldDataToMetadata convert;
-      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());
+/**
+Constructor
+@param dataSet : input dataset containing field data.
+*/
+vtkDataSetToWsName::vtkDataSetToWsName(vtkDataSet *dataSet)
+    : m_dataset(dataSet) {
+  if (m_dataset == NULL) {
+    throw std::runtime_error(
+        "Tried to construct vtkDataSetToWsName with NULL vtkDataSet");
+  }
+}
 
-      Poco::XML::DOMParser pParser;
-      Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
-      Poco::XML::Element* pRootElem = pDoc->documentElement();
-      Poco::XML::Element* wsNameElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::workspaceNameElementName());
-      if(wsNameElem == NULL)
-      {
-        throw std::runtime_error("The element containing the workspace name must be present.");
-      }
-      return wsNameElem->innerText();
-    }
+/**
+Runs the extraction
+@return extracted workspace name.
+*/
+std::string vtkDataSetToWsName::execute() {
+  using Mantid::Geometry::MDGeometryXMLDefinitions;
+  FieldDataToMetadata convert;
+  std::string xmlString =
+      convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());
 
-    /// Destructor.
-    vtkDataSetToWsName::~vtkDataSetToWsName()
-    {
-    }
+  Poco::XML::DOMParser pParser;
+  Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
+  Poco::XML::Element *pRootElem = pDoc->documentElement();
+  Poco::XML::Element *wsNameElem = pRootElem->getChildElement(
+      MDGeometryXMLDefinitions::workspaceNameElementName());
+  if (wsNameElem == NULL) {
+    throw std::runtime_error(
+        "The element containing the workspace name must be present.");
   }
+  return wsNameElem->innerText();
+}
+
+/// Destructor.
+vtkDataSetToWsName::~vtkDataSetToWsName() {}
+}
 }
diff --git a/Vates/VatesAPI/src/vtkMD0DFactory.cpp b/Vates/VatesAPI/src/vtkMD0DFactory.cpp
index 788dc392728779a28e9000093e6fcf1743a93ff2..6434862d90305f29d57e7488fd8fb6ab23f137f4 100644
--- a/Vates/VatesAPI/src/vtkMD0DFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMD0DFactory.cpp
@@ -6,48 +6,40 @@
 
 using namespace Mantid::API;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("vtkMD0DFactory");
+namespace {
+Mantid::Kernel::Logger g_log("vtkMD0DFactory");
 }
 
-namespace Mantid
-{
-  namespace VATES
-  {
-    /**
-    Constructor
-    */
-    vtkMD0DFactory::vtkMD0DFactory()
-    {
-    }
+namespace Mantid {
+namespace VATES {
+/**
+Constructor
+*/
+vtkMD0DFactory::vtkMD0DFactory() {}
 
-    /// Destructor
-    vtkMD0DFactory::~vtkMD0DFactory()
-    {
-    }
+/// Destructor
+vtkMD0DFactory::~vtkMD0DFactory() {}
 
-    /**
-    Create the vtkStructuredGrid from the provided workspace
-    @param progressUpdating: Reporting object to pass progress information up the stack.
-    @return fully constructed vtkDataSet.
-    */
-    vtkSmartPointer<vtkDataSet> vtkMD0DFactory::create(ProgressAction &) const {
-      g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
-      vtkNullUnstructuredGrid nullGrid;
-      auto visualDataSet =
-          vtkSmartPointer<vtkDataSet>::Take(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.
+*/
+vtkSmartPointer<vtkDataSet> vtkMD0DFactory::create(ProgressAction &) const {
+  g_log.warning() << "Factory " << this->getFactoryTypeName()
+                  << " is being used. You are viewing data with less than "
+                     "three dimensions in the VSI. \n";
+  vtkNullUnstructuredGrid nullGrid;
+  auto visualDataSet =
+      vtkSmartPointer<vtkDataSet>::Take(nullGrid.createNullData());
+  return visualDataSet;
+}
 
-    /// Initalize with a target workspace.
-    void vtkMD0DFactory::initialize(Mantid::API::Workspace_sptr)
-    {
-    }
+/// Initalize with a target workspace.
+void vtkMD0DFactory::initialize(Mantid::API::Workspace_sptr) {}
 
-   /// Validate the workspace 
-   void vtkMD0DFactory::validate() const
-   {
-   }
-  }
+/// Validate the workspace
+void vtkMD0DFactory::validate() const {}
+}
 }
diff --git a/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
index 2351d0e36574e7e137e436aa584969481b1aac65..49b10fd7cc5ec202d0121917bdb0377ab39ba1f5 100644
--- a/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp
@@ -11,101 +11,90 @@ using Mantid::API::IMDWorkspace;
 using Mantid::Kernel::CPUTimer;
 using namespace Mantid::DataObjects;
 
-namespace Mantid
-{
-namespace VATES
-{
+namespace Mantid {
+namespace VATES {
 
-  template<typename TimeMapper>
-  vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalization, const double timestep)
-  : vtkMDHistoHexFactory(thresholdRange,  normalization),
-    m_timestep(timestep)
-  {
-  }
-
-    /**
-  Assigment operator
-  @param other : vtkMDHistoHex4DFactory to assign to this instance from.
-  @return ref to assigned current instance.
-  */
-  template<typename TimeMapper>
-  vtkMDHistoHex4DFactory<TimeMapper>& vtkMDHistoHex4DFactory<TimeMapper>::operator=(const vtkMDHistoHex4DFactory<TimeMapper>& other)
-  {
-    if(this != &other)
-    {
-      this->m_normalizationOption = other.m_normalizationOption;
-      this->m_thresholdRange = other.m_thresholdRange;
-      this->m_workspace = other.m_workspace;
-      this->m_timestep = other.m_timestep;
-      this->m_timeMapper = other.m_timeMapper;
-    }
-    return *this;
-  }
+template <typename TimeMapper>
+vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(
+    ThresholdRange_scptr thresholdRange,
+    const VisualNormalization normalization, const double timestep)
+    : vtkMDHistoHexFactory(thresholdRange, normalization),
+      m_timestep(timestep) {}
 
-  /**
-  Copy Constructor
-  @param other : instance to copy from.
-  */
-  template<typename TimeMapper>
-  vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(const vtkMDHistoHex4DFactory<TimeMapper>& other)
-   : vtkMDHistoHexFactory(other),
-     m_timestep(other.m_timestep), m_timeMapper(other.m_timeMapper)
-  {
-    
+/**
+Assigment operator
+@param other : vtkMDHistoHex4DFactory to assign to this instance from.
+@return ref to assigned current instance.
+*/
+template <typename TimeMapper>
+vtkMDHistoHex4DFactory<TimeMapper> &vtkMDHistoHex4DFactory<TimeMapper>::
+operator=(const vtkMDHistoHex4DFactory<TimeMapper> &other) {
+  if (this != &other) {
+    this->m_normalizationOption = other.m_normalizationOption;
+    this->m_thresholdRange = other.m_thresholdRange;
+    this->m_workspace = other.m_workspace;
+    this->m_timestep = other.m_timestep;
+    this->m_timeMapper = other.m_timeMapper;
   }
+  return *this;
+}
 
+/**
+Copy Constructor
+@param other : instance to copy from.
+*/
+template <typename TimeMapper>
+vtkMDHistoHex4DFactory<TimeMapper>::vtkMDHistoHex4DFactory(
+    const vtkMDHistoHex4DFactory<TimeMapper> &other)
+    : vtkMDHistoHexFactory(other), m_timestep(other.m_timestep),
+      m_timeMapper(other.m_timeMapper) {}
 
-  template<typename TimeMapper>
-  void vtkMDHistoHex4DFactory<TimeMapper>::initialize(Mantid::API::Workspace_sptr workspace)
-  {
-    m_workspace = doInitialize<MDHistoWorkspace, 4>(workspace);
-    if(m_workspace != NULL)
-    {
-      double tMax = m_workspace->getTDimension()->getMaximum();
-      double tMin = m_workspace->getTDimension()->getMinimum();
-      size_t nbins = m_workspace->getTDimension()->getNBins();
-
-      m_timeMapper = TimeMapper::construct(tMin, tMax, nbins);
+template <typename TimeMapper>
+void vtkMDHistoHex4DFactory<TimeMapper>::initialize(
+    Mantid::API::Workspace_sptr workspace) {
+  m_workspace = doInitialize<MDHistoWorkspace, 4>(workspace);
+  if (m_workspace != NULL) {
+    double tMax = m_workspace->getTDimension()->getMaximum();
+    double tMin = m_workspace->getTDimension()->getMinimum();
+    size_t nbins = m_workspace->getTDimension()->getNBins();
 
-      //Setup range values according to whatever strategy object has been injected.
-      m_thresholdRange->setWorkspace(workspace);
-      m_thresholdRange->calculate();
-    }
-  }
+    m_timeMapper = TimeMapper::construct(tMin, tMax, nbins);
 
-  template<typename TimeMapper>
-  void vtkMDHistoHex4DFactory<TimeMapper>::validate() const
-  {
-    validateWsNotNull();
-  }
-
-  /**
-  Create the vtkStructuredGrid from the provided workspace
-  @param progressUpdating: Reporting object to pass progress information up the stack.
-  @return fully constructed vtkDataSet.
-  */
-  template<typename TimeMapper>
-  vtkSmartPointer<vtkDataSet> vtkMDHistoHex4DFactory<TimeMapper>::create(ProgressAction& progressUpdating) const
-  {
-    auto product = tryDelegatingCreation<MDHistoWorkspace, 4>(m_workspace, progressUpdating);
-    if (product != nullptr) {
-      return product;
-    }
-    else
-    {
-      // Create the mesh in a 4D mode
-      return this->create3Dor4D(m_timeMapper(m_timestep), progressUpdating);
-    }
+    // Setup range values according to whatever strategy object has been
+    // injected.
+    m_thresholdRange->setWorkspace(workspace);
+    m_thresholdRange->calculate();
   }
+}
 
+template <typename TimeMapper>
+void vtkMDHistoHex4DFactory<TimeMapper>::validate() const {
+  validateWsNotNull();
+}
 
-  template<typename TimeMapper>
-  vtkMDHistoHex4DFactory<TimeMapper>::~vtkMDHistoHex4DFactory()
-  {
+/**
+Create the vtkStructuredGrid from the provided workspace
+@param progressUpdating: Reporting object to pass progress information up the
+stack.
+@return fully constructed vtkDataSet.
+*/
+template <typename TimeMapper>
+vtkSmartPointer<vtkDataSet> vtkMDHistoHex4DFactory<TimeMapper>::create(
+    ProgressAction &progressUpdating) const {
+  auto product =
+      tryDelegatingCreation<MDHistoWorkspace, 4>(m_workspace, progressUpdating);
+  if (product != nullptr) {
+    return product;
+  } else {
+    // Create the mesh in a 4D mode
+    return this->create3Dor4D(m_timeMapper(m_timestep), progressUpdating);
   }
+}
 
-  template class vtkMDHistoHex4DFactory<TimeToTimeStep>;
-  template class vtkMDHistoHex4DFactory<TimeStepToTimeStep>;
+template <typename TimeMapper>
+vtkMDHistoHex4DFactory<TimeMapper>::~vtkMDHistoHex4DFactory() {}
 
+template class vtkMDHistoHex4DFactory<TimeToTimeStep>;
+template class vtkMDHistoHex4DFactory<TimeStepToTimeStep>;
 }
 }
diff --git a/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
index 2b6eca9981a9f0446b653c281a99aae0701d3e05..4793d06e3b40e222435904d1702acdfddf9a2b8d 100644
--- a/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp
@@ -111,14 +111,13 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep,
 
   vtkSmartPointer<vtkStructuredGrid> visualDataSet =
       vtkSmartPointer<vtkStructuredGrid>::New();
-  visualDataSet->SetDimensions(nBinsX+1,nBinsY+1,nBinsZ+1);
+  visualDataSet->SetDimensions(nBinsX + 1, nBinsY + 1, nBinsZ + 1);
 
   // Array with true where the voxel should be shown
   double progressFactor = 0.5 / double(imageSize);
 
   std::size_t offset = 0;
-  if (nDims == 4)
-  {
+  if (nDims == 4) {
     offset = timestep * indexMultiplier[2];
   }
 
@@ -132,12 +131,11 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep,
   signal->InitializeArray(std::move(iterator), offset, imageSize);
   visualDataSet->GetCellData()->SetScalars(signal.GetPointer());
 
-
   for (vtkIdType index = 0; index < imageSize; ++index) {
     progressUpdate.eventRaised(double(index) * progressFactor);
     double signalScalar = signal->GetValue(index);
-    bool maskValue =
-        (!std::isfinite(signalScalar) || !m_thresholdRange->inRange(signalScalar));
+    bool maskValue = (!std::isfinite(signalScalar) ||
+                      !m_thresholdRange->inRange(signalScalar));
     if (maskValue) {
       visualDataSet->BlankCell(index);
     }
@@ -175,14 +173,14 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep,
   for (int z = 0; z < nPointsZ; z++) {
     // Report progress updates for the last 50%
     progressUpdate.eventRaised(double(z) * progressFactor + progressOffset);
-    in[1] = (minZ +
-             (static_cast<coord_t>(z) * incrementZ)); // Calculate increment in z;
+    in[1] = (minZ + (static_cast<coord_t>(z) *
+                     incrementZ)); // Calculate increment in z;
     for (int y = 0; y < nPointsY; y++) {
       in[0] = (minY + (static_cast<coord_t>(y) *
                        incrementY)); // Calculate increment in y;
       for (int x = 0; x < nPointsX; x++) {
         it[0] = (minX + (static_cast<coord_t>(x) *
-                        incrementX)); // Calculate increment in x;
+                         incrementX)); // Calculate increment in x;
         it[1] = in[0];
         it[2] = in[1];
         std::advance(it, 3);
@@ -202,7 +200,6 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep,
 
   vtkSmartPointer<vtkDataSet> dataset = visualDataSet;
   return dataset;
-
 }
 
 /**
diff --git a/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
index 1a8eef2e1a3cd158e14042237fcab2b8c4936b94..c8bf0e8aa14dd693613fb0b545de3156bb5d8b07 100644
--- a/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp
@@ -17,178 +17,168 @@ using Mantid::API::IMDWorkspace;
 using Mantid::DataObjects::MDHistoWorkspace;
 using Mantid::API::NullCoordTransform;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("vtkMDHistoLineFactory");
+namespace {
+Mantid::Kernel::Logger g_log("vtkMDHistoLineFactory");
 }
 
-namespace Mantid
-{
-
-  namespace VATES
-  {
-
-    vtkMDHistoLineFactory::vtkMDHistoLineFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normaliztionOption) : m_normalizationOption(normaliztionOption),
-      m_thresholdRange(thresholdRange)
-    {
-    }
-
-    /**
-    Assigment operator
-    @param other : vtkMDHistoLineFactory to assign to this instance from.
-    @return ref to assigned current instance.
-    */
-    vtkMDHistoLineFactory& vtkMDHistoLineFactory::operator=(const vtkMDHistoLineFactory& other)
-    {
-      if(this != &other)
-      {
-        this->m_normalizationOption = other.m_normalizationOption;
-        this->m_thresholdRange = other.m_thresholdRange;
-        this->m_workspace = other.m_workspace;
-      }
-      return *this;
-    }
-
-    /**
-    Copy Constructor
-    @param other : instance to copy from.
-    */
-    vtkMDHistoLineFactory::vtkMDHistoLineFactory(const vtkMDHistoLineFactory& other)
-    {
-      this->m_normalizationOption = other.m_normalizationOption;
-      this->m_thresholdRange = other.m_thresholdRange;
-      this->m_workspace = other.m_workspace;
-    }
-
-    /**
-    Create the vtkStructuredGrid from the provided workspace
-    @param progressUpdating: Reporting object to pass progress information up the stack.
-    @return fully constructed vtkDataSet.
-    */
-    vtkSmartPointer<vtkDataSet>
-    vtkMDHistoLineFactory::create(ProgressAction &progressUpdating) const {
-      auto product = tryDelegatingCreation<MDHistoWorkspace, 1>(
-          m_workspace, progressUpdating);
-      if (product != nullptr) {
-        return product;
-      }
-      else
-      {
-        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
-
-        Mantid::Kernel::ReadLock lock(*m_workspace);
-        const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );
-
-        const coord_t maxX = m_workspace-> getXDimension()->getMaximum();
-        const coord_t minX = m_workspace-> getXDimension()->getMinimum();
-
-        coord_t incrementX = (maxX - minX) / coord_t(nBinsX-1);
-
-        const int imageSize = nBinsX;
-        vtkNew<vtkPoints> points;
-        points->Allocate(static_cast<int>(imageSize));
-
-        vtkNew<vtkFloatArray> signal;
-        signal->Allocate(imageSize);
-        signal->SetName(vtkDataSetFactory::ScalarName.c_str());
-        signal->SetNumberOfComponents(1);
-
-        UnstructuredPoint unstructPoint;
-        const int nPointsX = nBinsX;
-        Column column(nPointsX);
-
-        NullCoordTransform transform;
-        //Mantid::API::CoordTransform* transform = m_workspace->getTransformFromOriginal();
-        Mantid::coord_t in[3]; 
-        Mantid::coord_t out[3];
-
-        double progressFactor = 0.5/double(nBinsX);
-        double progressOffset = 0.5;
-
-        //Loop through dimensions
-        for (int i = 0; i < nPointsX; i++)
-        {
-          progressUpdating.eventRaised(progressFactor * double(i));
-          in[0] = minX + static_cast<coord_t>(i) * incrementX; //Calculate increment in x;
-
-          float signalScalar = static_cast<float>(m_workspace->getSignalNormalizedAt(i));
-
-          if (!std::isfinite(signalScalar) ||
-              !m_thresholdRange->inRange(signalScalar)) {
-            //Flagged so that topological and scalar data is not applied.
-            unstructPoint.isSparse = true;
-          }
-          else
-          {
-            if (i < (nBinsX -1))
-            {
-              signal->InsertNextValue(static_cast<float>(signalScalar));
-            }
-            unstructPoint.isSparse = false;
-          }
-
-          transform.apply(in, out);
-
-          unstructPoint.pointId = points->InsertNextPoint(out);
-          column[i] = unstructPoint;
+namespace Mantid {
+
+namespace VATES {
+
+vtkMDHistoLineFactory::vtkMDHistoLineFactory(
+    ThresholdRange_scptr thresholdRange,
+    const VisualNormalization normaliztionOption)
+    : m_normalizationOption(normaliztionOption),
+      m_thresholdRange(thresholdRange) {}
+
+/**
+Assigment operator
+@param other : vtkMDHistoLineFactory to assign to this instance from.
+@return ref to assigned current instance.
+*/
+vtkMDHistoLineFactory &vtkMDHistoLineFactory::
+operator=(const vtkMDHistoLineFactory &other) {
+  if (this != &other) {
+    this->m_normalizationOption = other.m_normalizationOption;
+    this->m_thresholdRange = other.m_thresholdRange;
+    this->m_workspace = other.m_workspace;
+  }
+  return *this;
+}
 
-        }
+/**
+Copy Constructor
+@param other : instance to copy from.
+*/
+vtkMDHistoLineFactory::vtkMDHistoLineFactory(
+    const vtkMDHistoLineFactory &other) {
+  this->m_normalizationOption = other.m_normalizationOption;
+  this->m_thresholdRange = other.m_thresholdRange;
+  this->m_workspace = other.m_workspace;
+}
 
-        points->Squeeze();
-        signal->Squeeze();
-
-        auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New();
-        visualDataSet->Allocate(imageSize);
-        visualDataSet->SetPoints(points.GetPointer());
-        visualDataSet->GetCellData()->SetScalars(signal.GetPointer());
-
-        for (int i = 0; i < nBinsX - 1; i++)
-        {
-          progressUpdating.eventRaised((progressFactor * double(i)) + progressOffset);
-          //Only create topologies for those cells which are not sparse.
-          if (!column[i].isSparse)
-          {
-            vtkLine* line = vtkLine::New();
-            line->GetPointIds()->SetId(0, column[i].pointId);
-            line->GetPointIds()->SetId(1, column[i + 1].pointId);
-            visualDataSet->InsertNextCell(VTK_LINE, line->GetPointIds());
-          }
+/**
+Create the vtkStructuredGrid from the provided workspace
+@param progressUpdating: Reporting object to pass progress information up the
+stack.
+@return fully constructed vtkDataSet.
+*/
+vtkSmartPointer<vtkDataSet>
+vtkMDHistoLineFactory::create(ProgressAction &progressUpdating) const {
+  auto product =
+      tryDelegatingCreation<MDHistoWorkspace, 1>(m_workspace, progressUpdating);
+  if (product != nullptr) {
+    return product;
+  } else {
+    g_log.warning() << "Factory " << this->getFactoryTypeName()
+                    << " is being used. You are viewing data with less than "
+                       "three dimensions in the VSI. \n";
+
+    Mantid::Kernel::ReadLock lock(*m_workspace);
+    const int nBinsX =
+        static_cast<int>(m_workspace->getXDimension()->getNBins());
+
+    const coord_t maxX = m_workspace->getXDimension()->getMaximum();
+    const coord_t minX = m_workspace->getXDimension()->getMinimum();
+
+    coord_t incrementX = (maxX - minX) / coord_t(nBinsX - 1);
+
+    const int imageSize = nBinsX;
+    vtkNew<vtkPoints> points;
+    points->Allocate(static_cast<int>(imageSize));
+
+    vtkNew<vtkFloatArray> signal;
+    signal->Allocate(imageSize);
+    signal->SetName(vtkDataSetFactory::ScalarName.c_str());
+    signal->SetNumberOfComponents(1);
+
+    UnstructuredPoint unstructPoint;
+    const int nPointsX = nBinsX;
+    Column column(nPointsX);
+
+    NullCoordTransform transform;
+    // Mantid::API::CoordTransform* transform =
+    // m_workspace->getTransformFromOriginal();
+    Mantid::coord_t in[3];
+    Mantid::coord_t out[3];
+
+    double progressFactor = 0.5 / double(nBinsX);
+    double progressOffset = 0.5;
+
+    // Loop through dimensions
+    for (int i = 0; i < nPointsX; i++) {
+      progressUpdating.eventRaised(progressFactor * double(i));
+      in[0] = minX +
+              static_cast<coord_t>(i) * incrementX; // Calculate increment in x;
+
+      float signalScalar =
+          static_cast<float>(m_workspace->getSignalNormalizedAt(i));
+
+      if (!std::isfinite(signalScalar) ||
+          !m_thresholdRange->inRange(signalScalar)) {
+        // Flagged so that topological and scalar data is not applied.
+        unstructPoint.isSparse = true;
+      } else {
+        if (i < (nBinsX - 1)) {
+          signal->InsertNextValue(static_cast<float>(signalScalar));
         }
+        unstructPoint.isSparse = false;
+      }
 
-        visualDataSet->Squeeze();
+      transform.apply(in, out);
 
-        // Hedge against empty data sets
-        if (visualDataSet->GetNumberOfPoints() <= 0)
-        {
-          vtkNullUnstructuredGrid nullGrid;
-          visualDataSet = nullGrid.createNullData();
-        }
+      unstructPoint.pointId = points->InsertNextPoint(out);
+      column[i] = unstructPoint;
+    }
 
-        vtkSmartPointer<vtkDataSet> dataset = visualDataSet;
-        return dataset;
+    points->Squeeze();
+    signal->Squeeze();
+
+    auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New();
+    visualDataSet->Allocate(imageSize);
+    visualDataSet->SetPoints(points.GetPointer());
+    visualDataSet->GetCellData()->SetScalars(signal.GetPointer());
+
+    for (int i = 0; i < nBinsX - 1; i++) {
+      progressUpdating.eventRaised((progressFactor * double(i)) +
+                                   progressOffset);
+      // Only create topologies for those cells which are not sparse.
+      if (!column[i].isSparse) {
+        vtkLine *line = vtkLine::New();
+        line->GetPointIds()->SetId(0, column[i].pointId);
+        line->GetPointIds()->SetId(1, column[i + 1].pointId);
+        visualDataSet->InsertNextCell(VTK_LINE, line->GetPointIds());
       }
     }
 
-    void vtkMDHistoLineFactory::initialize(Mantid::API::Workspace_sptr wspace_sptr)
-    {
-      m_workspace = this->doInitialize<MDHistoWorkspace, 1>(wspace_sptr);
+    visualDataSet->Squeeze();
 
-      //Setup range values according to whatever strategy object has been injected.
-      m_thresholdRange->setWorkspace(wspace_sptr);
-      m_thresholdRange->calculate();
+    // Hedge against empty data sets
+    if (visualDataSet->GetNumberOfPoints() <= 0) {
+      vtkNullUnstructuredGrid nullGrid;
+      visualDataSet = nullGrid.createNullData();
     }
 
-    void vtkMDHistoLineFactory::validate() const
-    {
-      if(NULL == m_workspace.get())
-      {
-        throw std::runtime_error("IMDWorkspace is null");
-      }
-    }
+    vtkSmartPointer<vtkDataSet> dataset = visualDataSet;
+    return dataset;
+  }
+}
 
-    vtkMDHistoLineFactory::~vtkMDHistoLineFactory()
-    {
+void vtkMDHistoLineFactory::initialize(
+    Mantid::API::Workspace_sptr wspace_sptr) {
+  m_workspace = this->doInitialize<MDHistoWorkspace, 1>(wspace_sptr);
 
-    }
+  // Setup range values according to whatever strategy object has been injected.
+  m_thresholdRange->setWorkspace(wspace_sptr);
+  m_thresholdRange->calculate();
+}
+
+void vtkMDHistoLineFactory::validate() const {
+  if (NULL == m_workspace.get()) {
+    throw std::runtime_error("IMDWorkspace is null");
   }
 }
+
+vtkMDHistoLineFactory::~vtkMDHistoLineFactory() {}
+}
+}
diff --git a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
index 5894b209013e873b6be2da2a79656c348f18c346..286da311a163f96f5416e6e3e81812467baa6972 100644
--- a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
@@ -22,242 +22,238 @@ using Mantid::Kernel::CPUTimer;
 using Mantid::DataObjects::MDHistoWorkspace;
 using Mantid::DataObjects::MDHistoWorkspaceIterator;
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("vtkMDHistoQuadFactory");
+namespace {
+Mantid::Kernel::Logger g_log("vtkMDHistoQuadFactory");
 }
 
-namespace Mantid
-{
-
-  namespace VATES
-  {
-    vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(ThresholdRange_scptr thresholdRange, const VisualNormalization normalizationOption) : m_normalizationOption(normalizationOption), m_thresholdRange(thresholdRange)
-    {
-    }
+namespace Mantid {
+
+namespace VATES {
+vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(
+    ThresholdRange_scptr thresholdRange,
+    const VisualNormalization normalizationOption)
+    : m_normalizationOption(normalizationOption),
+      m_thresholdRange(thresholdRange) {}
+
+/**
+Assigment operator
+@param other : vtkMDHistoQuadFactory to assign to this instance from.
+@return ref to assigned current instance.
+*/
+vtkMDHistoQuadFactory &vtkMDHistoQuadFactory::
+operator=(const vtkMDHistoQuadFactory &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 : vtkMDHistoQuadFactory to assign to this instance from.
-    @return ref to assigned current instance.
-    */
-    vtkMDHistoQuadFactory& vtkMDHistoQuadFactory::operator=(const vtkMDHistoQuadFactory& other)
-    {
-      if(this != &other)
-      {
-        this->m_normalizationOption = other.m_normalizationOption;
-        this->m_thresholdRange = other.m_thresholdRange;
-        this->m_workspace = other.m_workspace;
-      }
-      return *this;
-    }
+/**
+Copy Constructor
+@param other : instance to copy from.
+*/
+vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(
+    const vtkMDHistoQuadFactory &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.
-    */
-    vtkMDHistoQuadFactory::vtkMDHistoQuadFactory(const vtkMDHistoQuadFactory& other)
-    {
-      this->m_normalizationOption = other.m_normalizationOption;
-      this->m_thresholdRange = other.m_thresholdRange;
-      this->m_workspace = other.m_workspace;
+/**
+Create the vtkStructuredGrid from the provided workspace
+@param progressUpdating: Reporting object to pass progress information up the
+stack.
+@return fully constructed vtkDataSet.
+*/
+vtkSmartPointer<vtkDataSet>
+vtkMDHistoQuadFactory::create(ProgressAction &progressUpdating) const {
+  auto product =
+      tryDelegatingCreation<MDHistoWorkspace, 2>(m_workspace, progressUpdating);
+  if (product != nullptr) {
+    return product;
+  } else {
+    g_log.warning() << "Factory " << this->getFactoryTypeName()
+                    << " is being used. You are viewing data with less than "
+                       "three dimensions in the VSI. \n";
+
+    Mantid::Kernel::ReadLock lock(*m_workspace);
+    CPUTimer tim;
+    const int nBinsX =
+        static_cast<int>(m_workspace->getXDimension()->getNBins());
+    const int nBinsY =
+        static_cast<int>(m_workspace->getYDimension()->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();
+
+    coord_t incrementX = (maxX - minX) / static_cast<coord_t>(nBinsX);
+    coord_t incrementY = (maxY - minY) / static_cast<coord_t>(nBinsY);
+
+    boost::scoped_ptr<MDHistoWorkspaceIterator> iterator(
+        dynamic_cast<MDHistoWorkspaceIterator *>(
+            createIteratorWithNormalization(m_normalizationOption,
+                                            m_workspace.get())));
+    if (!iterator) {
+      throw std::runtime_error(
+          "Could not convert IMDIterator to a MDHistoWorkspaceIterator");
     }
 
-    /**
-    Create the vtkStructuredGrid from the provided workspace
-    @param progressUpdating: Reporting object to pass progress information up the stack.
-    @return fully constructed vtkDataSet.
-    */
-    vtkSmartPointer<vtkDataSet>
-    vtkMDHistoQuadFactory::create(ProgressAction &progressUpdating) const {
-      auto product = tryDelegatingCreation<MDHistoWorkspace, 2>(
-          m_workspace, progressUpdating);
-      if (product != nullptr) {
-        return product;
-      }
-      else
-      {
-        g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n";
-
-        Mantid::Kernel::ReadLock lock(*m_workspace);
-        CPUTimer tim;
-        const int nBinsX = static_cast<int>( m_workspace->getXDimension()->getNBins() );
-        const int nBinsY = static_cast<int>( m_workspace->getYDimension()->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();
-
-        coord_t incrementX = (maxX - minX) / static_cast<coord_t>(nBinsX);
-        coord_t incrementY = (maxY - minY) / static_cast<coord_t>(nBinsY);
-
-        boost::scoped_ptr<MDHistoWorkspaceIterator> iterator(dynamic_cast<MDHistoWorkspaceIterator*>(createIteratorWithNormalization(m_normalizationOption, m_workspace.get())));
-        if (!iterator) {
-          throw std::runtime_error(
-              "Could not convert IMDIterator to a MDHistoWorkspaceIterator");
-        }
-
-        const int imageSize = (nBinsX ) * (nBinsY );
-        vtkNew<vtkPoints> points;
-        points->Allocate(static_cast<int>(imageSize));
-
-        vtkNew<vtkFloatArray> signal;
-        signal->Allocate(imageSize);
-        signal->SetName(vtkDataSetFactory::ScalarName.c_str());
-        signal->SetNumberOfComponents(1);
-
-        //The following represent actual calculated positions.
-
-        float signalScalar;
-        const int nPointsX = nBinsX+1;
-        const int nPointsY = nBinsY+1;
-
-        /* 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
-        auto pointNeeded = std::vector<bool>(nPointsX * nPointsY, false);
-        // Array with true where the voxel should be shown
-        auto voxelShown = std::vector<bool>(nBinsX * nBinsY);
-
-        double progressFactor = 0.5/double(nBinsX);
-        double progressOffset = 0.5;
-
-        size_t index = 0;
-        for (int i = 0; i < nBinsX; i++)
-        {
-          progressUpdating.eventRaised(progressFactor*double(i));
-
-          for (int j = 0; j < nBinsY; j++)
-          {
-            index = j + nBinsY*i;
-            iterator->jumpTo(index);
-            signalScalar = static_cast<float>(iterator->getNormalizedSignal()); // Get signal normalized as per m_normalizationOption
-
-            if (!std::isfinite(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 4 neighboring points are set to true
-              size_t pointIndex = i * nPointsY + j;
-              pointNeeded[pointIndex] = true;  pointIndex++;
-              pointNeeded[pointIndex] = true;  pointIndex += nPointsY-1;
-              pointNeeded[pointIndex] = true;  pointIndex++;
-              pointNeeded[pointIndex] = true;
-            }
-          }
-        }
-
-        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];
-        in[2] = 0;
-
-        // Array with the point IDs (only set where needed)
-        std::vector<vtkIdType> pointIDs(nPointsX * nPointsY, 0);
-        index = 0;
-        for (int i = 0; i < nPointsX; i++)
-        {
-          progressUpdating.eventRaised((progressFactor*double(i)) + progressOffset);
-          in[0] = minX + (static_cast<coord_t>(i) * incrementX); //Calculate increment in x;
-          for (int j = 0; j < nPointsY; j++)
-          {
-            // Create the point only when needed
-            if (pointNeeded[index])
-            {
-              in[1] = minY + (static_cast<coord_t>(j) * incrementY); //Calculate increment in y;
-              if (transform)
-              {
-                transform->apply(in, out);
-                pointIDs[index] = points->InsertNextPoint(out);
-              }
-              else
-                pointIDs[index] = points->InsertNextPoint(in);
-            }
-            index++;
-          }
+    const int imageSize = (nBinsX) * (nBinsY);
+    vtkNew<vtkPoints> points;
+    points->Allocate(static_cast<int>(imageSize));
+
+    vtkNew<vtkFloatArray> signal;
+    signal->Allocate(imageSize);
+    signal->SetName(vtkDataSetFactory::ScalarName.c_str());
+    signal->SetNumberOfComponents(1);
+
+    // The following represent actual calculated positions.
+
+    float signalScalar;
+    const int nPointsX = nBinsX + 1;
+    const int nPointsY = nBinsY + 1;
+
+    /* 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
+    auto pointNeeded = std::vector<bool>(nPointsX * nPointsY, false);
+    // Array with true where the voxel should be shown
+    auto voxelShown = std::vector<bool>(nBinsX * nBinsY);
+
+    double progressFactor = 0.5 / double(nBinsX);
+    double progressOffset = 0.5;
+
+    size_t index = 0;
+    for (int i = 0; i < nBinsX; i++) {
+      progressUpdating.eventRaised(progressFactor * double(i));
+
+      for (int j = 0; j < nBinsY; j++) {
+        index = j + nBinsY * i;
+        iterator->jumpTo(index);
+        signalScalar = static_cast<float>(
+            iterator->getNormalizedSignal()); // Get signal normalized as per
+                                              // m_normalizationOption
+
+        if (!std::isfinite(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 4 neighboring points are set to true
+          size_t pointIndex = i * nPointsY + j;
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
+          pointIndex += nPointsY - 1;
+          pointNeeded[pointIndex] = true;
+          pointIndex++;
+          pointNeeded[pointIndex] = true;
         }
+      }
+    }
 
-        std::cout << tim << " to create the needed points." << std::endl;
-
-        auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New();
-        visualDataSet->Allocate(imageSize);
-        visualDataSet->SetPoints(points.GetPointer());
-        visualDataSet->GetCellData()->SetScalars(signal.GetPointer());
-
-        // ------ Quad creation ----------------
-        vtkNew<vtkQuad> quad; // Significant speed increase by creating ONE quad
-                              // (assume vtkNew doesn't add significant
-                              // overhead)
-        index = 0;
-        for (int i = 0; i < nBinsX; i++)
-        {
-          for (int j = 0; j < nBinsY; j++)
-          {
-            if (voxelShown[index])
-            {
-              // The quad will be shown
-              quad->GetPointIds()->SetId(0, pointIDs[(i)*nPointsY + j]);
-              quad->GetPointIds()->SetId(1, pointIDs[(i+1)*nPointsY + j]);
-              quad->GetPointIds()->SetId(2, pointIDs[(i+1)*nPointsY + j+1]);
-              quad->GetPointIds()->SetId(3, pointIDs[(i)*nPointsY + j+1]);
-              visualDataSet->InsertNextCell(VTK_QUAD, quad->GetPointIds());
-            }
-            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];
+    in[2] = 0;
+
+    // Array with the point IDs (only set where needed)
+    std::vector<vtkIdType> pointIDs(nPointsX * nPointsY, 0);
+    index = 0;
+    for (int i = 0; i < nPointsX; i++) {
+      progressUpdating.eventRaised((progressFactor * double(i)) +
+                                   progressOffset);
+      in[0] = minX + (static_cast<coord_t>(i) *
+                      incrementX); // Calculate increment in x;
+      for (int j = 0; j < nPointsY; j++) {
+        // Create the point only when needed
+        if (pointNeeded[index]) {
+          in[1] = minY + (static_cast<coord_t>(j) *
+                          incrementY); // Calculate increment in y;
+          if (transform) {
+            transform->apply(in, out);
+            pointIDs[index] = points->InsertNextPoint(out);
+          } else
+            pointIDs[index] = points->InsertNextPoint(in);
         }
+        index++;
+      }
+    }
 
-        std::cout << tim << " to create and add the quads." << std::endl;
-
-        visualDataSet->Squeeze();
-
-        // Hedge against empty data sets
-        if (visualDataSet->GetNumberOfPoints() <= 0)
-        {
-          vtkNullUnstructuredGrid nullGrid;
-          visualDataSet = nullGrid.createNullData();
+    std::cout << tim << " to create the needed points." << std::endl;
+
+    auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New();
+    visualDataSet->Allocate(imageSize);
+    visualDataSet->SetPoints(points.GetPointer());
+    visualDataSet->GetCellData()->SetScalars(signal.GetPointer());
+
+    // ------ Quad creation ----------------
+    vtkNew<vtkQuad> quad; // Significant speed increase by creating ONE quad
+                          // (assume vtkNew doesn't add significant
+                          // overhead)
+    index = 0;
+    for (int i = 0; i < nBinsX; i++) {
+      for (int j = 0; j < nBinsY; j++) {
+        if (voxelShown[index]) {
+          // The quad will be shown
+          quad->GetPointIds()->SetId(0, pointIDs[(i)*nPointsY + j]);
+          quad->GetPointIds()->SetId(1, pointIDs[(i + 1) * nPointsY + j]);
+          quad->GetPointIds()->SetId(2, pointIDs[(i + 1) * nPointsY + j + 1]);
+          quad->GetPointIds()->SetId(3, pointIDs[(i)*nPointsY + j + 1]);
+          visualDataSet->InsertNextCell(VTK_QUAD, quad->GetPointIds());
         }
-
-        vtkSmartPointer<vtkDataSet> dataSet = visualDataSet;
-        return dataSet;
+        index++;
       }
     }
 
-    void vtkMDHistoQuadFactory::initialize(Mantid::API::Workspace_sptr wspace_sptr)
-    {
-      m_workspace = doInitialize<MDHistoWorkspace, 2>(wspace_sptr);
+    std::cout << tim << " to create and add the quads." << std::endl;
 
-      //Setup range values according to whatever strategy object has been injected.
-      m_thresholdRange->setWorkspace(wspace_sptr);
-      m_thresholdRange->calculate();
-    }
+    visualDataSet->Squeeze();
 
-    void vtkMDHistoQuadFactory::validate() const
-    {
-      if(NULL == m_workspace.get())
-      {
-        throw std::runtime_error("IMDWorkspace is null");
-      }
+    // Hedge against empty data sets
+    if (visualDataSet->GetNumberOfPoints() <= 0) {
+      vtkNullUnstructuredGrid nullGrid;
+      visualDataSet = nullGrid.createNullData();
     }
 
-    /// Destructor
-    vtkMDHistoQuadFactory::~vtkMDHistoQuadFactory()
-    {
+    vtkSmartPointer<vtkDataSet> dataSet = visualDataSet;
+    return dataSet;
+  }
+}
 
-    }
+void vtkMDHistoQuadFactory::initialize(
+    Mantid::API::Workspace_sptr wspace_sptr) {
+  m_workspace = doInitialize<MDHistoWorkspace, 2>(wspace_sptr);
+
+  // Setup range values according to whatever strategy object has been injected.
+  m_thresholdRange->setWorkspace(wspace_sptr);
+  m_thresholdRange->calculate();
+}
+
+void vtkMDHistoQuadFactory::validate() const {
+  if (NULL == m_workspace.get()) {
+    throw std::runtime_error("IMDWorkspace is null");
   }
 }
+
+/// Destructor
+vtkMDHistoQuadFactory::~vtkMDHistoQuadFactory() {}
+}
+}
diff --git a/Vates/VatesAPI/src/vtkMDLineFactory.cpp b/Vates/VatesAPI/src/vtkMDLineFactory.cpp
index 0d6fac866d722b65642363aa931065807c1eec43..33a028441dcf775e5e952e0808e9bbfd0ebd2ce5 100644
--- a/Vates/VatesAPI/src/vtkMDLineFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDLineFactory.cpp
@@ -70,7 +70,7 @@ vtkMDLineFactory::create(ProgressAction &progressUpdating) const {
     /*
     Write mask array with correct order for each internal dimension.
     */
-        auto masks = Mantid::Kernel::make_unique<bool[]>(nDims);
+    auto masks = Mantid::Kernel::make_unique<bool[]>(nDims);
     for (size_t i_dim = 0; i_dim < nDims; ++i_dim) {
       bool bIntegrated = imdws->getDimension(i_dim)->getIsIntegrated();
       masks[i_dim] =
diff --git a/Vates/VatesAPI/src/vtkMDQuadFactory.cpp b/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
index 722757f91f1255aa70732245ee9a16dca107da0a..f8ed9f183d44e17bedd326a40526ffe5c3bf6c92 100644
--- a/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDQuadFactory.cpp
@@ -64,7 +64,7 @@ vtkMDQuadFactory::create(ProgressAction &progressUpdating) const {
     /*
     Write mask array with correct order for each internal dimension.
     */
-        auto masks = Mantid::Kernel::make_unique<bool[]>(nDims);
+    auto masks = Mantid::Kernel::make_unique<bool[]>(nDims);
     for (size_t i_dim = 0; i_dim < nDims; ++i_dim) {
       bool bIntegrated = imdws->getDimension(i_dim)->getIsIntegrated();
       masks[i_dim] =
diff --git a/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp b/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
index 9cc19c54510579f50ef179e2b87b27bdaefc9a6e..9bb5a96592b6d2251ff4e28431b4a70fb215c117 100644
--- a/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
+++ b/Vates/VatesAPI/src/vtkPeakMarkerFactory.cpp
@@ -27,263 +27,250 @@ using Mantid::API::IPeaksWorkspace;
 using Mantid::Geometry::IPeak;
 using Mantid::Kernel::V3D;
 
-namespace Mantid
-{
-namespace VATES 
-{
-
-  vtkPeakMarkerFactory::vtkPeakMarkerFactory(const std::string& scalarName, ePeakDimensions dimensions) :
-  m_scalarName(scalarName), m_dimensionToShow(dimensions), m_peakRadius(-1)
-  {
-  }
-
-  void vtkPeakMarkerFactory::initialize(Mantid::API::Workspace_sptr workspace)
-  {
-    m_workspace = boost::dynamic_pointer_cast<IPeaksWorkspace>(workspace);
-    validateWsNotNull();
-
-    try
-    {
-      m_peakRadius = atof(m_workspace->run().getProperty("PeakRadius")->value().c_str());
-    }
-    catch(Mantid::Kernel::Exception::NotFoundError&)
-    {
-    }
-  }
-
-  double vtkPeakMarkerFactory::getIntegrationRadius() const
-  {
-    return m_peakRadius;
+namespace Mantid {
+namespace VATES {
+
+vtkPeakMarkerFactory::vtkPeakMarkerFactory(const std::string &scalarName,
+                                           ePeakDimensions dimensions)
+    : m_scalarName(scalarName), m_dimensionToShow(dimensions),
+      m_peakRadius(-1) {}
+
+void vtkPeakMarkerFactory::initialize(Mantid::API::Workspace_sptr workspace) {
+  m_workspace = boost::dynamic_pointer_cast<IPeaksWorkspace>(workspace);
+  validateWsNotNull();
+
+  try {
+    m_peakRadius =
+        atof(m_workspace->run().getProperty("PeakRadius")->value().c_str());
+  } catch (Mantid::Kernel::Exception::NotFoundError &) {
   }
+}
 
-  bool vtkPeakMarkerFactory::isPeaksWorkspaceIntegrated() const
-  {
-    return (m_peakRadius > 0);
-  }
+double vtkPeakMarkerFactory::getIntegrationRadius() const {
+  return m_peakRadius;
+}
 
-  void vtkPeakMarkerFactory::validateWsNotNull() const
-  {
-    if(!m_workspace)
-      throw std::runtime_error("IPeaksWorkspace is null");
-  }
+bool vtkPeakMarkerFactory::isPeaksWorkspaceIntegrated() const {
+  return (m_peakRadius > 0);
+}
 
-  void vtkPeakMarkerFactory::validate() const
-  {
-    validateWsNotNull();
-  }
+void vtkPeakMarkerFactory::validateWsNotNull() const {
+  if (!m_workspace)
+    throw std::runtime_error("IPeaksWorkspace is null");
+}
 
-  /**
-   Get ellipsoid axes
-   @param ellipticalShape: ellipsoidal parameters.
-   @param peak: peak under consideration.
-   */
-  std::vector<Mantid::Kernel::V3D> vtkPeakMarkerFactory::getAxes(
-      const Mantid::DataObjects::PeakShapeEllipsoid &ellipticalShape,
-      const IPeak &peak) const {
-    std::vector<Mantid::Kernel::V3D> axes;
-    switch (m_dimensionToShow) {
-    case vtkPeakMarkerFactory::Peak_in_Q_lab:
-      axes = ellipticalShape.directions();
-      break;
-    case vtkPeakMarkerFactory::Peak_in_Q_sample: {
-      Mantid::Kernel::Matrix<double> goniometerMatrix =
-          peak.getGoniometerMatrix();
-      if (goniometerMatrix.Invert() != 0.0) {
-        axes = ellipticalShape.getDirectionInSpecificFrame(goniometerMatrix);
-      } else {
-        axes = ellipticalShape.directions();
-      }
-    } break;
-    case vtkPeakMarkerFactory::Peak_in_HKL:
-      axes = ellipticalShape.directions();
-      break;
-    default:
+void vtkPeakMarkerFactory::validate() const { validateWsNotNull(); }
+
+/**
+ Get ellipsoid axes
+ @param ellipticalShape: ellipsoidal parameters.
+ @param peak: peak under consideration.
+ */
+std::vector<Mantid::Kernel::V3D> vtkPeakMarkerFactory::getAxes(
+    const Mantid::DataObjects::PeakShapeEllipsoid &ellipticalShape,
+    const IPeak &peak) const {
+  std::vector<Mantid::Kernel::V3D> axes;
+  switch (m_dimensionToShow) {
+  case vtkPeakMarkerFactory::Peak_in_Q_lab:
+    axes = ellipticalShape.directions();
+    break;
+  case vtkPeakMarkerFactory::Peak_in_Q_sample: {
+    Mantid::Kernel::Matrix<double> goniometerMatrix =
+        peak.getGoniometerMatrix();
+    if (goniometerMatrix.Invert() != 0.0) {
+      axes = ellipticalShape.getDirectionInSpecificFrame(goniometerMatrix);
+    } else {
       axes = ellipticalShape.directions();
     }
-    return axes;
+  } break;
+  case vtkPeakMarkerFactory::Peak_in_HKL:
+    axes = ellipticalShape.directions();
+    break;
+  default:
+    axes = ellipticalShape.directions();
   }
+  return axes;
+}
 
-  /**
-   Get glyph position in the appropiate coordinates.
-   @param peak: peak under consideration.
-   */
-  V3D vtkPeakMarkerFactory::getPosition(const IPeak &peak) const {
-
-    V3D pos;
-    switch (m_dimensionToShow) {
-    case Peak_in_Q_lab:
-      pos = peak.getQLabFrame();
-      break;
-    case Peak_in_Q_sample:
-      pos = peak.getQSampleFrame();
-      break;
-    case Peak_in_HKL:
-      pos = peak.getHKL();
-      break;
-    default:
-      pos = peak.getQLabFrame();
-    }
-    return pos;
+/**
+ Get glyph position in the appropiate coordinates.
+ @param peak: peak under consideration.
+ */
+V3D vtkPeakMarkerFactory::getPosition(const IPeak &peak) const {
+
+  V3D pos;
+  switch (m_dimensionToShow) {
+  case Peak_in_Q_lab:
+    pos = peak.getQLabFrame();
+    break;
+  case Peak_in_Q_sample:
+    pos = peak.getQSampleFrame();
+    break;
+  case Peak_in_HKL:
+    pos = peak.getHKL();
+    break;
+  default:
+    pos = peak.getQLabFrame();
   }
+  return pos;
+}
 
-  /**
-   Get the tranform tensor for vtkTensorGlyph
-   @param ellipticalShape: ellipsoidal parameters.
-   @param peak: peak under consideration.
-   */
-  std::array<float, 9> vtkPeakMarkerFactory::getTransformTensor(
-      const Mantid::DataObjects::PeakShapeEllipsoid &ellipticalShape,
-      const IPeak &peak) const {
-
-    std::vector<double> radii = ellipticalShape.abcRadii();
-    std::vector<Mantid::Kernel::V3D> axes = getAxes(ellipticalShape, peak);
-
-    // The rotation+scaling matrix is the
-    // principal axes of the ellipsoid scaled by the radii.
-    std::array<float, 9> tensor;
-    for (unsigned j = 0; j < 3; ++j) {
-      for (unsigned k = 0; k < 3; ++k) {
-        tensor[3 * j + k] = static_cast<float>(radii[j] * axes[j][k]);
-      }
+/**
+ Get the tranform tensor for vtkTensorGlyph
+ @param ellipticalShape: ellipsoidal parameters.
+ @param peak: peak under consideration.
+ */
+std::array<float, 9> vtkPeakMarkerFactory::getTransformTensor(
+    const Mantid::DataObjects::PeakShapeEllipsoid &ellipticalShape,
+    const IPeak &peak) const {
+
+  std::vector<double> radii = ellipticalShape.abcRadii();
+  std::vector<Mantid::Kernel::V3D> axes = getAxes(ellipticalShape, peak);
+
+  // The rotation+scaling matrix is the
+  // principal axes of the ellipsoid scaled by the radii.
+  std::array<float, 9> tensor;
+  for (unsigned j = 0; j < 3; ++j) {
+    for (unsigned k = 0; k < 3; ++k) {
+      tensor[3 * j + k] = static_cast<float>(radii[j] * axes[j][k]);
     }
-    return tensor;
   }
+  return tensor;
+}
 
-  namespace {
-  /**
-   Set the normal direction.
-   @param source: source on which the normal direction is set.
-   @param direction: direction (x,y,z) to set.
-   */
-  void setNormal(vtkRegularPolygonSource *source, unsigned direction) {
-    assert(direction < 3);
-    switch (direction) {
-    case (0):
-      source->SetNormal(1.0, 0.0, 0.0);
-      break;
-    case (1):
-      source->SetNormal(0.0, 1.0, 0.0);
-      break;
-    case (2):
-      source->SetNormal(0.0, 0.0, 1.0);
-      break;
-    }
-  }
+namespace {
+/**
+ Set the normal direction.
+ @param source: source on which the normal direction is set.
+ @param direction: direction (x,y,z) to set.
+ */
+void setNormal(vtkRegularPolygonSource *source, unsigned direction) {
+  assert(direction < 3);
+  switch (direction) {
+  case (0):
+    source->SetNormal(1.0, 0.0, 0.0);
+    break;
+  case (1):
+    source->SetNormal(0.0, 1.0, 0.0);
+    break;
+  case (2):
+    source->SetNormal(0.0, 0.0, 1.0);
+    break;
   }
+}
+}
 
-  /**
+/**
 Create the vtkStructuredGrid from the provided workspace
 @param progressUpdating: Reporting object to pass progress information up the
 stack.
 @return vtkPolyData glyph.
 */
-  vtkSmartPointer<vtkPolyData>
-  vtkPeakMarkerFactory::create(ProgressAction &progressUpdating) const {
-    validate();
-
-    int numPeaks = m_workspace->getNumberPeaks();
-
-   // Acquire a scoped read-only lock to the workspace (prevent segfault from algos modifying ws)
-    Mantid::Kernel::ReadLock lock(*m_workspace);
-
-    const int resolution = 100;
-    double progressFactor = 1.0 / static_cast<double>(numPeaks);
-
-    vtkAppendPolyData *appendFilter = vtkAppendPolyData::New();
-    // Go peak-by-peak
-    for (int i=0; i < numPeaks; i++)
-    {
-      progressUpdating.eventRaised(double(i)*progressFactor);
-
-      // Point
-      vtkNew<vtkPoints> peakPoint;
-      peakPoint->Allocate(1);
-
-      // What we'll return
-      vtkNew<vtkPolyData> peakDataSet;
-      peakDataSet->Allocate(1);
-      peakDataSet->SetPoints(peakPoint.GetPointer());
-
-      const IPeak &peak = m_workspace->getPeak(i);
-
-      // Choose the dimensionality of the position to show
-      V3D pos = getPosition(peak);
-      peakPoint->InsertNextPoint(pos.X(), pos.Y(), pos.Z());
-
-      peakPoint->Squeeze();
-      peakDataSet->Squeeze();
-
-      // Add a glyph and append to the appendFilter
-      const Mantid::Geometry::PeakShape& shape = m_workspace->getPeak(i).getPeakShape();
-
-      // Pick the radius up from the factory if possible, otherwise use the user-provided value.
-      if(shape.shapeName() == Mantid::DataObjects::PeakShapeSpherical::sphereShapeName())
-      {
-        double peakRadius =
-            shape.radius(Mantid::Geometry::PeakShape::Radius).get();
-
-        vtkNew<vtkRegularPolygonSource> polygonSource;
-        polygonSource->GeneratePolygonOff();
-        polygonSource->SetNumberOfSides(resolution);
-        polygonSource->SetRadius(peakRadius);
-        polygonSource->SetCenter(0., 0., 0.);
-
-        for (unsigned axis = 0; axis < 3; ++axis) {
-          vtkNew<vtkPVGlyphFilter> glyphFilter;
-          setNormal(polygonSource.GetPointer(), axis);
-          glyphFilter->SetInputData(peakDataSet.GetPointer());
-          glyphFilter->SetSourceConnection(polygonSource->GetOutputPort());
-          glyphFilter->Update();
-          appendFilter->AddInputData(glyphFilter->GetOutput());
-          appendFilter->Update();
-        }
-      }
-      else if (shape.shapeName() == Mantid::DataObjects::PeakShapeEllipsoid::ellipsoidShapeName())
-      {
-        vtkNew<vtkFloatArray> transformSignal;
-        transformSignal->Allocate(1);
-        transformSignal->SetNumberOfComponents(9);
-        auto tensor = getTransformTensor(
-            dynamic_cast<const Mantid::DataObjects::PeakShapeEllipsoid &>(
-                shape),
-            peak);
-        transformSignal->InsertNextTupleValue(tensor.data());
-        peakDataSet->GetPointData()->SetTensors(transformSignal.GetPointer());
-
-        vtkNew<vtkRegularPolygonSource> polygonSource;
-        polygonSource->GeneratePolygonOff();
-        polygonSource->SetNumberOfSides(resolution);
-        polygonSource->SetRadius(1.);
-        polygonSource->SetCenter(0., 0., 0.);
-
-        for (unsigned axis = 0; axis < 3; ++axis) {
-          vtkNew<vtkTensorGlyph> glyphFilter;
-          setNormal(polygonSource.GetPointer(), axis);
-          glyphFilter->SetInputData(peakDataSet.GetPointer());
-          glyphFilter->SetSourceConnection(polygonSource->GetOutputPort());
-          glyphFilter->ExtractEigenvaluesOff();
-          glyphFilter->Update();
-          appendFilter->AddInputData(glyphFilter->GetOutput());
-          appendFilter->Update();
-        }
-      }
-      else
-      {
-        vtkNew<vtkAxes> axis;
-        axis->SymmetricOn();
-        axis->SetScaleFactor(0.2);
+vtkSmartPointer<vtkPolyData>
+vtkPeakMarkerFactory::create(ProgressAction &progressUpdating) const {
+  validate();
+
+  int numPeaks = m_workspace->getNumberPeaks();
+
+  // Acquire a scoped read-only lock to the workspace (prevent segfault from
+  // algos modifying ws)
+  Mantid::Kernel::ReadLock lock(*m_workspace);
+
+  const int resolution = 100;
+  double progressFactor = 1.0 / static_cast<double>(numPeaks);
+
+  vtkAppendPolyData *appendFilter = vtkAppendPolyData::New();
+  // Go peak-by-peak
+  for (int i = 0; i < numPeaks; i++) {
+    progressUpdating.eventRaised(double(i) * progressFactor);
+
+    // Point
+    vtkNew<vtkPoints> peakPoint;
+    peakPoint->Allocate(1);
+
+    // What we'll return
+    vtkNew<vtkPolyData> peakDataSet;
+    peakDataSet->Allocate(1);
+    peakDataSet->SetPoints(peakPoint.GetPointer());
+
+    const IPeak &peak = m_workspace->getPeak(i);
+
+    // Choose the dimensionality of the position to show
+    V3D pos = getPosition(peak);
+    peakPoint->InsertNextPoint(pos.X(), pos.Y(), pos.Z());
 
+    peakPoint->Squeeze();
+    peakDataSet->Squeeze();
+
+    // Add a glyph and append to the appendFilter
+    const Mantid::Geometry::PeakShape &shape =
+        m_workspace->getPeak(i).getPeakShape();
+
+    // Pick the radius up from the factory if possible, otherwise use the
+    // user-provided value.
+    if (shape.shapeName() ==
+        Mantid::DataObjects::PeakShapeSpherical::sphereShapeName()) {
+      double peakRadius =
+          shape.radius(Mantid::Geometry::PeakShape::Radius).get();
+
+      vtkNew<vtkRegularPolygonSource> polygonSource;
+      polygonSource->GeneratePolygonOff();
+      polygonSource->SetNumberOfSides(resolution);
+      polygonSource->SetRadius(peakRadius);
+      polygonSource->SetCenter(0., 0., 0.);
+
+      for (unsigned axis = 0; axis < 3; ++axis) {
         vtkNew<vtkPVGlyphFilter> glyphFilter;
+        setNormal(polygonSource.GetPointer(), axis);
+        glyphFilter->SetInputData(peakDataSet.GetPointer());
+        glyphFilter->SetSourceConnection(polygonSource->GetOutputPort());
+        glyphFilter->Update();
+        appendFilter->AddInputData(glyphFilter->GetOutput());
+        appendFilter->Update();
+      }
+    } else if (shape.shapeName() ==
+               Mantid::DataObjects::PeakShapeEllipsoid::ellipsoidShapeName()) {
+      vtkNew<vtkFloatArray> transformSignal;
+      transformSignal->Allocate(1);
+      transformSignal->SetNumberOfComponents(9);
+      auto tensor = getTransformTensor(
+          dynamic_cast<const Mantid::DataObjects::PeakShapeEllipsoid &>(shape),
+          peak);
+      transformSignal->InsertNextTupleValue(tensor.data());
+      peakDataSet->GetPointData()->SetTensors(transformSignal.GetPointer());
+
+      vtkNew<vtkRegularPolygonSource> polygonSource;
+      polygonSource->GeneratePolygonOff();
+      polygonSource->SetNumberOfSides(resolution);
+      polygonSource->SetRadius(1.);
+      polygonSource->SetCenter(0., 0., 0.);
+
+      for (unsigned axis = 0; axis < 3; ++axis) {
+        vtkNew<vtkTensorGlyph> glyphFilter;
+        setNormal(polygonSource.GetPointer(), axis);
         glyphFilter->SetInputData(peakDataSet.GetPointer());
-        glyphFilter->SetSourceConnection(axis->GetOutputPort());
+        glyphFilter->SetSourceConnection(polygonSource->GetOutputPort());
+        glyphFilter->ExtractEigenvaluesOff();
         glyphFilter->Update();
         appendFilter->AddInputData(glyphFilter->GetOutput());
         appendFilter->Update();
       }
+    } else {
+      vtkNew<vtkAxes> axis;
+      axis->SymmetricOn();
+      axis->SetScaleFactor(0.2);
+
+      vtkNew<vtkPVGlyphFilter> glyphFilter;
+      glyphFilter->SetInputData(peakDataSet.GetPointer());
+      glyphFilter->SetSourceConnection(axis->GetOutputPort());
+      glyphFilter->Update();
+      appendFilter->AddInputData(glyphFilter->GetOutput());
+      appendFilter->Update();
+    }
 
-    } // for each peak
+  } // for each peak
 
-    return vtkSmartPointer<vtkPolyData>::Take(appendFilter->GetOutput());
-  }
+  return vtkSmartPointer<vtkPolyData>::Take(appendFilter->GetOutput());
+}
 }
 }
diff --git a/Vates/VatesAPI/src/vtkSinglePeakMarker.cpp b/Vates/VatesAPI/src/vtkSinglePeakMarker.cpp
index 9b4ae5ba2c90a53472d093c21f34132beefe84c6..90dd934d2d3aea7a349400ecc63e3a619c294e59 100644
--- a/Vates/VatesAPI/src/vtkSinglePeakMarker.cpp
+++ b/Vates/VatesAPI/src/vtkSinglePeakMarker.cpp
@@ -10,67 +10,66 @@
 #include "vtkTransform.h"
 #include "vtkTransformPolyDataFilter.h"
 
-namespace Mantid
-{
-namespace VATES 
-{
-  vtkSinglePeakMarker::vtkSinglePeakMarker(){
-  }
+namespace Mantid {
+namespace VATES {
+vtkSinglePeakMarker::vtkSinglePeakMarker() {}
 
-  vtkSinglePeakMarker::~vtkSinglePeakMarker(){
-  }
+vtkSinglePeakMarker::~vtkSinglePeakMarker() {}
 
-  vtkPolyData* vtkSinglePeakMarker::createSinglePeakMarker(double x, double y, double z, double radius){
+vtkPolyData *vtkSinglePeakMarker::createSinglePeakMarker(double x, double y,
+                                                         double z,
+                                                         double radius) {
 
-    // Point
-    vtkPoints *peakPoint = vtkPoints::New();
-    peakPoint->Allocate(1);
+  // Point
+  vtkPoints *peakPoint = vtkPoints::New();
+  peakPoint->Allocate(1);
 
-    vtkFloatArray * peakSignal = vtkFloatArray::New();
-    peakSignal->Allocate(1);
-    peakSignal->SetName("signal");
-    peakSignal->SetNumberOfComponents(1);
+  vtkFloatArray *peakSignal = vtkFloatArray::New();
+  peakSignal->Allocate(1);
+  peakSignal->SetName("signal");
+  peakSignal->SetNumberOfComponents(1);
 
-    // What we'll return
-    vtkUnstructuredGrid *peakDataSet = vtkUnstructuredGrid::New();
-    peakDataSet->Allocate(1);
-    peakDataSet->SetPoints(peakPoint);
-    peakDataSet->GetCellData()->SetScalars(peakSignal);
+  // What we'll return
+  vtkUnstructuredGrid *peakDataSet = vtkUnstructuredGrid::New();
+  peakDataSet->Allocate(1);
+  peakDataSet->SetPoints(peakPoint);
+  peakDataSet->GetCellData()->SetScalars(peakSignal);
 
-    // One point per peak
-    vtkVertex * vertex = vtkVertex::New();
-    vtkIdType id_xyz = peakPoint->InsertNextPoint(x,y,z);
-    vertex->GetPointIds()->SetId(0, id_xyz);
+  // One point per peak
+  vtkVertex *vertex = vtkVertex::New();
+  vtkIdType id_xyz = peakPoint->InsertNextPoint(x, y, z);
+  vertex->GetPointIds()->SetId(0, id_xyz);
 
-    peakDataSet->InsertNextCell(VTK_VERTEX, vertex->GetPointIds());
+  peakDataSet->InsertNextCell(VTK_VERTEX, vertex->GetPointIds());
 
-    // The integrated intensity = the signal on that point.
-    peakSignal->InsertNextValue(static_cast<float>(1.0));
-    peakPoint->Squeeze();
-    peakDataSet->Squeeze();
+  // The integrated intensity = the signal on that point.
+  peakSignal->InsertNextValue(static_cast<float>(1.0));
+  peakPoint->Squeeze();
+  peakDataSet->Squeeze();
 
-    //Get the position info and create the glyph which is to be displayed.
-    vtkSphereSource* sphere = vtkSphereSource::New();
-    const int resolution = 16;
-    sphere->SetRadius(radius);
-    sphere->SetPhiResolution(resolution);
-    sphere->SetThetaResolution(resolution);
+  // Get the position info and create the glyph which is to be displayed.
+  vtkSphereSource *sphere = vtkSphereSource::New();
+  const int resolution = 16;
+  sphere->SetRadius(radius);
+  sphere->SetPhiResolution(resolution);
+  sphere->SetThetaResolution(resolution);
 
-    vtkTransform* transform = vtkTransform::New();
-    transform->Translate(0, 0, 0);
+  vtkTransform *transform = vtkTransform::New();
+  transform->Translate(0, 0, 0);
 
-    vtkTransformPolyDataFilter* transformFilter = vtkTransformPolyDataFilter::New();
-    transformFilter->SetTransform(transform);
-    transformFilter->SetInputConnection(sphere->GetOutputPort());
-    transformFilter->Update();
+  vtkTransformPolyDataFilter *transformFilter =
+      vtkTransformPolyDataFilter::New();
+  transformFilter->SetTransform(transform);
+  transformFilter->SetInputConnection(sphere->GetOutputPort());
+  transformFilter->Update();
 
-    vtkPVGlyphFilter *glyphFilter = vtkPVGlyphFilter::New();
-    glyphFilter->SetInputData(peakDataSet);
-    glyphFilter->SetSourceConnection(transformFilter->GetOutputPort());
-    glyphFilter->Update();
-    vtkPolyData *glyphed = glyphFilter->GetOutput();
+  vtkPVGlyphFilter *glyphFilter = vtkPVGlyphFilter::New();
+  glyphFilter->SetInputData(peakDataSet);
+  glyphFilter->SetSourceConnection(transformFilter->GetOutputPort());
+  glyphFilter->Update();
+  vtkPolyData *glyphed = glyphFilter->GetOutput();
 
-    return glyphed;
-  }
+  return glyphed;
+}
 }
 }
\ No newline at end of file
diff --git a/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp b/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
index 73fe49dbc6c4ca9fb94d99de216c6da5386c997f..9c853ae58ffa11382b07d2fd9ce755278feaf772 100644
--- a/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
+++ b/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp
@@ -416,8 +416,8 @@ vtkSplatterPlotFactory::create(ProgressAction &progressUpdating) const {
   if (nd > 3) {
     // Slice from >3D down to 3D
     this->slice = true;
-      this->sliceMask = Mantid::Kernel::make_unique<bool[]>(nd);
-      this->sliceImplicitFunction = boost::make_shared<MDImplicitFunction>();
+    this->sliceMask = Mantid::Kernel::make_unique<bool[]>(nd);
+    this->sliceImplicitFunction = boost::make_shared<MDImplicitFunction>();
     // Make the mask of dimensions
     // TODO: Smarter mapping
     for (size_t d = 0; d < nd; d++)
diff --git a/Vates/VatesAPI/test/ADSWorkspaceProviderTest.h b/Vates/VatesAPI/test/ADSWorkspaceProviderTest.h
index beda18f21f8c95799daf92db35aadbb77540a55a..6ef3e2ecb108864b1e3f09f6d1cad1472de58725 100644
--- a/Vates/VatesAPI/test/ADSWorkspaceProviderTest.h
+++ b/Vates/VatesAPI/test/ADSWorkspaceProviderTest.h
@@ -11,51 +11,55 @@
 using namespace Mantid::VATES;
 using namespace Mantid::API;
 
-class ADSWorkspaceProviderTest : public CxxTest::TestSuite
-{
+class ADSWorkspaceProviderTest : public CxxTest::TestSuite {
 public:
   void setUp() override {
     // Put A test workspace into the ADS.
     Mantid::API::AnalysisDataService::Instance().addOrReplace(
         "WS", IMDWorkspace_sptr(new MockIMDWorkspace()));
-}
-
-void testCanProvideWorkspace()
-{
-  ADSWorkspaceProvider<IMDWorkspace> wsProvider;
-  TSM_ASSERT("Should indicate that the workspace CAN be provided.", wsProvider.canProvideWorkspace("WS"));
-}
-
-void testCannotProvideWorkspaceIfNonExistant()
-{
-  ADSWorkspaceProvider<IMDWorkspace> wsProvider;
-  TSM_ASSERT("Should indicate that the workspace CANNOT be provided. It does not exist.", !wsProvider.canProvideWorkspace("WS_X")); //WS_X does not exist!
-}
-
-void testCannotProvideWorkspaceOfWrongType()
-{
-  // ::setup put a workspace of type IMDWorkspace in the ADS, so even though we are requesting the workspace via the right name, should
-  // return false because there is a type mismatch between the stored and requested workspace types.
-
-  ADSWorkspaceProvider<IMDEventWorkspace> wsProvider;
-  TSM_ASSERT("Asking for a IMDEventWorkspace. Should indicate that the workspace CANNOT be provided. see ::setup", !wsProvider.canProvideWorkspace("WS"));
-}
-
-void testFetchWorkspace()
-{
-  ADSWorkspaceProvider<IMDWorkspace> wsProvider;
-  TSM_ASSERT_THROWS_NOTHING("Should have fetched WS from ADS", wsProvider.fetchWorkspace("WS"));
-  TS_ASSERT(NULL != wsProvider.fetchWorkspace("WS"));
-}
-
-void testDisposeOfWorkspace()
-{
-  ADSWorkspaceProvider<IMDWorkspace> wsProvider;
-  TSM_ASSERT_THROWS_NOTHING("Should have workspace to start with.", wsProvider.fetchWorkspace("WS"));
-  TSM_ASSERT_THROWS_NOTHING("Should have removed existing workspace.", wsProvider.disposeWorkspace("WS"));
-  TSM_ASSERT_THROWS_ANYTHING("Should not be able to fetch the workspace now", wsProvider.fetchWorkspace("WS"));
-}
+  }
 
+  void testCanProvideWorkspace() {
+    ADSWorkspaceProvider<IMDWorkspace> wsProvider;
+    TSM_ASSERT("Should indicate that the workspace CAN be provided.",
+               wsProvider.canProvideWorkspace("WS"));
+  }
+
+  void testCannotProvideWorkspaceIfNonExistant() {
+    ADSWorkspaceProvider<IMDWorkspace> wsProvider;
+    TSM_ASSERT("Should indicate that the workspace CANNOT be provided. It does "
+               "not exist.",
+               !wsProvider.canProvideWorkspace("WS_X")); // WS_X does not exist!
+  }
+
+  void testCannotProvideWorkspaceOfWrongType() {
+    // ::setup put a workspace of type IMDWorkspace in the ADS, so even though
+    // we are requesting the workspace via the right name, should
+    // return false because there is a type mismatch between the stored and
+    // requested workspace types.
+
+    ADSWorkspaceProvider<IMDEventWorkspace> wsProvider;
+    TSM_ASSERT("Asking for a IMDEventWorkspace. Should indicate that the "
+               "workspace CANNOT be provided. see ::setup",
+               !wsProvider.canProvideWorkspace("WS"));
+  }
+
+  void testFetchWorkspace() {
+    ADSWorkspaceProvider<IMDWorkspace> wsProvider;
+    TSM_ASSERT_THROWS_NOTHING("Should have fetched WS from ADS",
+                              wsProvider.fetchWorkspace("WS"));
+    TS_ASSERT(NULL != wsProvider.fetchWorkspace("WS"));
+  }
+
+  void testDisposeOfWorkspace() {
+    ADSWorkspaceProvider<IMDWorkspace> wsProvider;
+    TSM_ASSERT_THROWS_NOTHING("Should have workspace to start with.",
+                              wsProvider.fetchWorkspace("WS"));
+    TSM_ASSERT_THROWS_NOTHING("Should have removed existing workspace.",
+                              wsProvider.disposeWorkspace("WS"));
+    TSM_ASSERT_THROWS_ANYTHING("Should not be able to fetch the workspace now",
+                               wsProvider.fetchWorkspace("WS"));
+  }
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/BoxInfoTest.h b/Vates/VatesAPI/test/BoxInfoTest.h
index e472fcd21ce1f0676c1984cc191053b36e3a420d..385daf0ddd762700ddbacfbb6fe7b8f2e2d124bf 100644
--- a/Vates/VatesAPI/test/BoxInfoTest.h
+++ b/Vates/VatesAPI/test/BoxInfoTest.h
@@ -1,8 +1,6 @@
 #ifndef VATES_API_BOX_INFO_TEST_H_
 #define VATES_API_BOX_INFO_TEST_H_
 
-
-
 #include <cxxtest/TestSuite.h>
 
 #include "MantidKernel/WarningSuppressions.h"
@@ -15,7 +13,6 @@
 #include "MantidTestHelpers/MDEventsTestHelper.h"
 #include "MantidDataObjects/MDLeanEvent.h"
 
-
 using namespace Mantid::API;
 using namespace Mantid::DataObjects;
 using namespace Mantid::DataObjects::MDEventsTestHelper;
@@ -27,11 +24,14 @@ public:
     // Arrange
     const std::string wsName = "MD_HISTO_WS";
     auto ws = makeFakeMDHistoWorkspace(1.0, 4, 5, 1.0, 0.1, wsName);
-    auto workspaceProvider = Mantid::Kernel::make_unique<Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
 
     // Act + Assert
     TSM_ASSERT("Should have no recursion depth for top level splitting.",
-                           boost::none == Mantid::VATES::findRecursionDepthForTopLevelSplitting(wsName,std::move(workspaceProvider)));
+               boost::none ==
+                   Mantid::VATES::findRecursionDepthForTopLevelSplitting(
+                       wsName, std::move(workspaceProvider)));
 
     // Clean up
     AnalysisDataService::Instance().remove(wsName);
@@ -41,29 +41,36 @@ public:
     // Arrange
     const std::string wsName = "MD_EVENT_WS";
     auto ws = makeAnyMDEW<MDLeanEvent<3>, 3>(10, 0.0, 10.0, 1, wsName);
-    auto workspaceProvider = Mantid::Kernel::make_unique<Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
 
     // Act + Assert
     TSM_ASSERT("Should have no recursion depth for top level splitting.",
-               boost::none == Mantid::VATES::findRecursionDepthForTopLevelSplitting(wsName, std::move(workspaceProvider)));
+               boost::none ==
+                   Mantid::VATES::findRecursionDepthForTopLevelSplitting(
+                       wsName, std::move(workspaceProvider)));
 
     // Clean up
     AnalysisDataService::Instance().remove(wsName);
   }
 
+  // clang-format off
   GCC_DIAG_OFF(strict-aliasing)
+  // clang-format on
   void test_initial_recursion_depth_is_1_for_MD_Event_w_split() {
     // Arrange
     const std::string wsName = "MD_EVENT_WS_WITH_SPLITTING";
     auto ws = makeAnyMDEW<MDLeanEvent<3>, 3>(10, 0.0, 10.0, 1, wsName);
-    BoxController_sptr boxController =  ws->getBoxController();
-    boxController->setSplitTopInto(0,10);
+    BoxController_sptr boxController = ws->getBoxController();
+    boxController->setSplitTopInto(0, 10);
     boxController->setSplitTopInto(1, 20);
-    boxController->setSplitTopInto(2,30);
-    auto workspaceProvider = Mantid::Kernel::make_unique<Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
+    boxController->setSplitTopInto(2, 30);
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
 
     // Act
-    auto result = Mantid::VATES::findRecursionDepthForTopLevelSplitting(wsName, std::move(workspaceProvider));
+    auto result = Mantid::VATES::findRecursionDepthForTopLevelSplitting(
+        wsName, std::move(workspaceProvider));
     // Assert
 
     TSM_ASSERT("Should have recursion depth of 1 for top level splitting.",
diff --git a/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h b/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
index 232ae69ef5346b1325b51201be9013cb450a8efd..cc01f503331aebb1af9230b31c73d7cab4fe39bf 100644
--- a/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
+++ b/Vates/VatesAPI/test/CompositePeaksPresenterVsiTest.h
@@ -8,7 +8,6 @@
 #include "MantidAPI/IPeaksWorkspace.h"
 #include "MantidDataObjects/PeaksWorkspace.h"
 
-
 #include <boost/shared_ptr.hpp>
 #include <boost/make_shared.hpp>
 #include <stdexcept>
@@ -17,22 +16,18 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
-
 #include <string>
 
 using namespace ::testing;
 using namespace Mantid::VATES;
 
-class MockPeaksWorkspaceComposite : public Mantid::DataObjects::PeaksWorkspace
-{
+class MockPeaksWorkspaceComposite : public Mantid::DataObjects::PeaksWorkspace {
 public:
 };
 
 class CompositePeaksPresenterVsiTest : public CxxTest::TestSuite {
 public:
-  void testSetupPresenterCorrectly() {
-
-  }
+  void testSetupPresenterCorrectly() {}
 
   void testThatGettingPeaksWorkspaceDirectlyIsNotAllowed() {
     // Arrange
@@ -53,26 +48,30 @@ public:
     CompositePeaksPresenterVsi presenter;
 
     std::string frame = "testFrame";
-    
+
     LeftPlane left(1.0, 0.0, 0.0, 1.0);
 
     RightPlane right(-1.0, 0.0, 0.0, 1.0);
     BottomPlane bottom(0.0, 1.0, 0.0, 1.0);
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
-    NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
+    NearPlane nearPlane(0.0, 0.0, -1.0, 1.0);
+    ViewFrustum_const_sptr frustum =
+        boost::make_shared<const Mantid::VATES::ViewFrustum>(
+            left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr =
         boost::make_shared<MockPeaksWorkspaceComposite>();
 
     std::string name = "pw1";
-    PeaksPresenterVsi_sptr p1(new ConcretePeaksPresenterVsi(pw_ptr, frustum, frame));
+    PeaksPresenterVsi_sptr p1(
+        new ConcretePeaksPresenterVsi(pw_ptr, frustum, frame));
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr2 =
         boost::make_shared<MockPeaksWorkspaceComposite>();
     std::string name2 = "pw2";
-    PeaksPresenterVsi_sptr p2(new ConcretePeaksPresenterVsi(pw_ptr2, frustum, frame));
+    PeaksPresenterVsi_sptr p2(
+        new ConcretePeaksPresenterVsi(pw_ptr2, frustum, frame));
 
     presenter.addPresenter(p1);
     presenter.addPresenter(p2);
@@ -89,31 +88,36 @@ public:
     CompositePeaksPresenterVsi presenter;
 
     std::string frame = "testFrame";
-    
+
     LeftPlane left(1.0, 0.0, 0.0, 1.0);
 
     RightPlane right(-1.0, 0.0, 0.0, 1.0);
     BottomPlane bottom(0.0, 1.0, 0.0, 1.0);
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
-    NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
+    NearPlane nearPlane(0.0, 0.0, -1.0, 1.0);
+    ViewFrustum_const_sptr frustum =
+        boost::make_shared<const Mantid::VATES::ViewFrustum>(
+            left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr =
         boost::make_shared<MockPeaksWorkspaceComposite>();
     std::string name = "pw1";
-    PeaksPresenterVsi_sptr p1(new ConcretePeaksPresenterVsi(pw_ptr, frustum, frame));
+    PeaksPresenterVsi_sptr p1(
+        new ConcretePeaksPresenterVsi(pw_ptr, frustum, frame));
 
     boost::shared_ptr<MockPeaksWorkspaceComposite> pw_ptr2 =
         boost::make_shared<MockPeaksWorkspaceComposite>();
     std::string name2 = "pw2";
-    PeaksPresenterVsi_sptr p2(new ConcretePeaksPresenterVsi(pw_ptr2, frustum, frame));
+    PeaksPresenterVsi_sptr p2(
+        new ConcretePeaksPresenterVsi(pw_ptr2, frustum, frame));
 
     presenter.addPresenter(p1);
     presenter.addPresenter(p2);
 
     // Act
-    std::vector<Mantid::API::IPeaksWorkspace_sptr> ws = presenter.getPeaksWorkspaces();
+    std::vector<Mantid::API::IPeaksWorkspace_sptr> ws =
+        presenter.getPeaksWorkspaces();
 
     // Assert
     TSM_ASSERT_EQUALS("Should have two entries", ws.size(), 2);
diff --git a/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h b/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
index 82eed489f58de924d7786d3a1d4008c2c3ce7b40..794f7e6f087d0e9cae784b3deaafdb346be6f35f 100644
--- a/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
+++ b/Vates/VatesAPI/test/ConcretePeaksPresenterVsiTest.h
@@ -18,26 +18,24 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
-
 #include <string>
 
 using namespace ::testing;
 using namespace Mantid::VATES;
 
-class MockPeakConcrete : public Mantid::DataObjects::Peak
-{
+class MockPeakConcrete : public Mantid::DataObjects::Peak {
 public:
-  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D (void));
+  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void));
 };
 
-class MockPeaksWorkspaceConcrete : public Mantid::DataObjects::PeaksWorkspace
-{
+class MockPeaksWorkspaceConcrete : public Mantid::DataObjects::PeaksWorkspace {
 public:
-  MOCK_CONST_METHOD0(getSpecialCoordinateSystem, Mantid::Kernel::SpecialCoordinateSystem());
-  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak & (int peakNum));
-  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak & (int peakNum));
+  MOCK_CONST_METHOD0(getSpecialCoordinateSystem,
+                     Mantid::Kernel::SpecialCoordinateSystem());
+  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum));
+  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum));
 };
 
 class ConcretePeaksPresenterVsiTest : public CxxTest::TestSuite {
@@ -46,15 +44,17 @@ public:
     // Arrange
     std::string frame = "testFrame";
     std::string name = "name";
-    
+
     LeftPlane left(1.0, 0.0, 0.0, 1.0);
 
     RightPlane right(-1.0, 0.0, 0.0, 1.0);
     BottomPlane bottom(0.0, 1.0, 0.0, 1.0);
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
-    NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
+    NearPlane nearPlane(0.0, 0.0, -1.0, 1.0);
+    ViewFrustum_const_sptr frustum =
+        boost::make_shared<const Mantid::VATES::ViewFrustum>(
+            left, right, bottom, top, farPlane, nearPlane);
 
     boost::shared_ptr<MockPeaksWorkspaceConcrete> pw_ptr =
         boost::make_shared<MockPeaksWorkspaceConcrete>();
@@ -62,25 +62,31 @@ public:
     ConcretePeaksPresenterVsi presenter(pw_ptr, frustum, frame);
 
     // Assert
-    TSM_ASSERT_EQUALS("Should have recorded the frame", presenter.getFrame(), frame);
+    TSM_ASSERT_EQUALS("Should have recorded the frame", presenter.getFrame(),
+                      frame);
   }
 
   void testCorrectPeaksInfoIsExtractedForValidRow() {
     // Arrange
     std::string frame = "Q_SAMPLE";
-    
+
     LeftPlane left(1.0, 0.0, 0.0, 1.0);
     RightPlane right(-1.0, 0.0, 0.0, 1.0);
     BottomPlane bottom(0.0, 1.0, 0.0, 1.0);
     TopPlane top(0.0, -1.0, 0.0, 1.0);
     FarPlane farPlane(0.0, 0.0, 1.0, 1.0);
-    NearPlane nearPlane(0.0, 0.0, -1.0,1.0);
-    ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(left, right, bottom, top, farPlane, nearPlane);
+    NearPlane nearPlane(0.0, 0.0, -1.0, 1.0);
+    ViewFrustum_const_sptr frustum =
+        boost::make_shared<const Mantid::VATES::ViewFrustum>(
+            left, right, bottom, top, farPlane, nearPlane);
 
-    Mantid::Kernel::V3D coordinate(1,0,0);
+    Mantid::Kernel::V3D coordinate(1, 0, 0);
     double peakRadius = 10;
-    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::SpecialCoordinateSystem::QSample;
-    Mantid::Geometry::PeakShape_sptr shape(new Mantid::DataObjects::PeakShapeSpherical(peakRadius, coordinateSystem, "test", 1));
+    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem =
+        Mantid::Kernel::SpecialCoordinateSystem::QSample;
+    Mantid::Geometry::PeakShape_sptr shape(
+        new Mantid::DataObjects::PeakShapeSpherical(
+            peakRadius, coordinateSystem, "test", 1));
     MockPeakConcrete peak;
     peak.setPeakShape(shape);
     EXPECT_CALL(peak, getQLabFrame()).Times(0);
@@ -89,18 +95,19 @@ public:
 
     boost::shared_ptr<MockPeaksWorkspaceConcrete> pw_ptr =
         boost::make_shared<MockPeaksWorkspaceConcrete>();
-    MockPeaksWorkspaceConcrete & pw = *pw_ptr;
+    MockPeaksWorkspaceConcrete &pw = *pw_ptr;
 
-    EXPECT_CALL(pw, getSpecialCoordinateSystem()).WillOnce(Return(coordinateSystem));
+    EXPECT_CALL(pw, getSpecialCoordinateSystem())
+        .WillOnce(Return(coordinateSystem));
     EXPECT_CALL(pw, getPeak(_)).Times(2).WillRepeatedly(ReturnRef(peak));
 
     // Act
     ConcretePeaksPresenterVsi presenter(pw_ptr, frustum, frame);
     double radius = 0;
-    Mantid::Kernel::V3D coord(0,0,0);
-    presenter.getPeaksInfo(pw_ptr,0,coord, radius, coordinateSystem);
+    Mantid::Kernel::V3D coord(0, 0, 0);
+    presenter.getPeaksInfo(pw_ptr, 0, coord, radius, coordinateSystem);
 
-    //Assert
+    // Assert
     TSM_ASSERT_EQUALS("Should have a radius of 10", radius, peakRadius);
     TSM_ASSERT_EQUALS("Should have the same coordinate", coord, coordinate);
   }
diff --git a/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h
index c8275d4c2be6046b54cb732f33d82d383d0db07b..3096810e70cb1688e5a7133b2b448a7f05ae7922 100644
--- a/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h
@@ -19,137 +19,132 @@ using namespace testing;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class EventNexusLoadingPresenterTest : public CxxTest::TestSuite
-{
+class EventNexusLoadingPresenterTest : public CxxTest::TestSuite {
 
 private:
-
-  // Helper method to return the full path to a real nexus file that is the correct format for this functionality.
-  static std::string getSuitableFile()
-  {
-    return Mantid::API::FileFinder::Instance().getFullPath("CNCS_7860_event.nxs");
+  // Helper method to return the full path to a real nexus file that is the
+  // correct format for this functionality.
+  static std::string getSuitableFile() {
+    return Mantid::API::FileFinder::Instance().getFullPath(
+        "CNCS_7860_event.nxs");
   }
-  
-  // Helper method to return the full path to a real nexus file that is the wrong format for this functionality.
-  static std::string getUnhandledFile()
-  {
+
+  // Helper method to return the full path to a real nexus file that is the
+  // wrong format for this functionality.
+  static std::string getUnhandledFile() {
     return Mantid::API::FileFinder::Instance().getFullPath("emu00006473.nxs");
   }
 
 public:
+  void testConstructWithEmptyFileThrows() {
+    TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
+                      EventNexusLoadingPresenter(
+                          Mantid::Kernel::make_unique<MockMDLoadingView>(), ""),
+                      std::invalid_argument);
+  }
 
-void testConstructWithEmptyFileThrows()
-{
-  TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
-                    EventNexusLoadingPresenter(
-                        Mantid::Kernel::make_unique<MockMDLoadingView>(), ""),
-                    std::invalid_argument);
-}
-
-void testConstructWithNullViewThrows()
-{
-  TSM_ASSERT_THROWS("Should throw if a null view is given.",
-                    EventNexusLoadingPresenter(nullptr, "some_file"),
-                    std::invalid_argument);
-}
-
-void testConstruct()
-{
-  TSM_ASSERT_THROWS_NOTHING(
-      "Object should be created without exception.",
-      EventNexusLoadingPresenter(
-          Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()));
-}
-
-void testCanReadFile()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile());
-  TSM_ASSERT(
-      "A file of this type cannot and should not be read by this presenter!.",
-      !presenter.canReadFile());
-}
-
-void testExecution()
-{
-  //Setup view
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, getLoadInMemory()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, getTime()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  NiceMock<MockProgressAction> mockLoadingProgressUpdate;
-  MockProgressAction mockDrawingProgressUpdate;
-
-  //Create the presenter and runit!
-  EventNexusLoadingPresenter presenter(std::move(view), getSuitableFile());
-  presenter.executeLoadMetadata();
-  vtkSmartPointer<vtkDataSet> product = presenter.execute(&factory, mockLoadingProgressUpdate, mockDrawingProgressUpdate);
-
-  TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
-  TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName()));
-  TSM_ASSERT("No field data!", NULL != product->GetFieldData());
-  TSM_ASSERT_EQUALS("Two arrays expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
-  TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
-  TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
-  TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-}
-
-void testGetTDimension()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT("EventNexus MDEW are created in fixed 3D.",
-             !presenter.hasTDimensionAvailable());
-}
-
-void testCallGetTDimensionValuesThrows()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getTimeStepValues(), std::runtime_error);
-}
-
-void testCallGetGeometryThrows()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getGeometryXML(), std::runtime_error);
-}
-
-void testExecuteLoadMetadata()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  presenter.executeLoadMetadata();
-  TSM_ASSERT_THROWS("Should always throw. Algorithm fixed to create 3 dimensions.", presenter.getTimeStepValues(), std::runtime_error);
-  TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable());
-  TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.getGeometryXML());
-}
-
-void testGetWorkspaceTypeName()
-{
-  EventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
-                    presenter.getWorkspaceTypeName());
-}
+  void testConstructWithNullViewThrows() {
+    TSM_ASSERT_THROWS("Should throw if a null view is given.",
+                      EventNexusLoadingPresenter(nullptr, "some_file"),
+                      std::invalid_argument);
+  }
 
+  void testConstruct() {
+    TSM_ASSERT_THROWS_NOTHING(
+        "Object should be created without exception.",
+        EventNexusLoadingPresenter(
+            Mantid::Kernel::make_unique<MockMDLoadingView>(),
+            getSuitableFile()));
+  }
 
+  void testCanReadFile() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile());
+    TSM_ASSERT(
+        "A file of this type cannot and should not be read by this presenter!.",
+        !presenter.canReadFile());
+  }
+
+  void testExecution() {
+    // Setup view
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, getLoadInMemory()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, getTime()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkUnstructuredGrid::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    NiceMock<MockProgressAction> mockLoadingProgressUpdate;
+    MockProgressAction mockDrawingProgressUpdate;
+
+    // Create the presenter and runit!
+    EventNexusLoadingPresenter presenter(std::move(view), getSuitableFile());
+    presenter.executeLoadMetadata();
+    vtkSmartPointer<vtkDataSet> product = presenter.execute(
+        &factory, mockLoadingProgressUpdate, mockDrawingProgressUpdate);
+
+    TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
+    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid",
+                      std::string(product->GetClassName()));
+    TSM_ASSERT("No field data!", NULL != product->GetFieldData());
+    TSM_ASSERT_EQUALS(
+        "Two arrays expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
+    TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
+    TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
+    TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+  }
 
+  void testGetTDimension() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT("EventNexus MDEW are created in fixed 3D.",
+               !presenter.hasTDimensionAvailable());
+  }
+
+  void testCallGetTDimensionValuesThrows() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getTimeStepValues(), std::runtime_error);
+  }
+
+  void testCallGetGeometryThrows() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getGeometryXML(), std::runtime_error);
+  }
+
+  void testExecuteLoadMetadata() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    presenter.executeLoadMetadata();
+    TSM_ASSERT_THROWS(
+        "Should always throw. Algorithm fixed to create 3 dimensions.",
+        presenter.getTimeStepValues(), std::runtime_error);
+    TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.",
+                              presenter.hasTDimensionAvailable());
+    TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.",
+                              presenter.getGeometryXML());
+  }
+
+  void testGetWorkspaceTypeName() {
+    EventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
+                      presenter.getWorkspaceTypeName());
+  }
 };
 #endif
diff --git a/Vates/VatesAPI/test/FieldDataToMetadataTest.h b/Vates/VatesAPI/test/FieldDataToMetadataTest.h
index 92c7ddeb3f038da34f00948aa515e455d8201625..9f058e65977e62aaae0d5e73c9681def1a208b77 100644
--- a/Vates/VatesAPI/test/FieldDataToMetadataTest.h
+++ b/Vates/VatesAPI/test/FieldDataToMetadataTest.h
@@ -9,25 +9,20 @@
 
 using Mantid::VATES::FieldDataToMetadata;
 
-class FieldDataToMetadataTest : public CxxTest::TestSuite
-{
+class FieldDataToMetadataTest : public CxxTest::TestSuite {
 
 private:
-
-  //Helper method
-  static vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id)
-  {
-    vtkFieldData* fieldData = vtkFieldData::New();
+  // Helper method
+  static vtkFieldData *createFieldDataWithCharArray(std::string testData,
+                                                    std::string id) {
+    vtkFieldData *fieldData = vtkFieldData::New();
     auto charArray = vtkSmartPointer<vtkCharArray>::New();
     charArray->SetName(id.c_str());
     charArray->Allocate(100);
-    for(unsigned int i = 0; i < testData.size(); i++)
-    {
+    for (unsigned int i = 0; i < testData.size(); i++) {
       char cNextVal = testData.at(i);
-      if(int(cNextVal) > 1)
-      {
+      if (int(cNextVal) > 1) {
         charArray->InsertNextValue(cNextVal);
-
       }
     }
     fieldData->AddArray(charArray.GetPointer());
@@ -35,9 +30,7 @@ private:
   }
 
 public:
-
-  void testExecute()
-  {
+  void testExecute() {
     const std::string id = "1";
     const std::string testData = "abc";
     vtkSmartPointer<vtkFieldData> fieldData =
@@ -46,40 +39,39 @@ public:
     FieldDataToMetadata function;
     std::string metadata = function.execute(fieldData, id);
 
-    TSM_ASSERT_EQUALS("The Function failed to properly convert field data to metadata", testData, metadata);
+    TSM_ASSERT_EQUALS(
+        "The Function failed to properly convert field data to metadata",
+        testData, metadata);
   }
 
-  void testOperatorOverload()
-  {
+  void testOperatorOverload() {
     const std::string id = "1";
     const std::string testData = "abc";
     vtkSmartPointer<vtkFieldData> fieldData =
         createFieldDataWithCharArray(testData, id);
 
     FieldDataToMetadata function;
-    TSM_ASSERT_EQUALS("Results from two equivalent methods differ.", function(fieldData, id), function.execute(fieldData, id));
+    TSM_ASSERT_EQUALS("Results from two equivalent methods differ.",
+                      function(fieldData, id), function.execute(fieldData, id));
   }
 
-  void testThrowsIfNotFound()
-  {
+  void testThrowsIfNotFound() {
     const std::string id = "1";
     const std::string testData = "abc";
     vtkSmartPointer<vtkFieldData> fieldData =
         createFieldDataWithCharArray(testData, id);
 
     FieldDataToMetadata function;
-    TSM_ASSERT_THROWS("Unknown id requested. Should have thrown.", function.execute(fieldData, "x"), std::runtime_error );
+    TSM_ASSERT_THROWS("Unknown id requested. Should have thrown.",
+                      function.execute(fieldData, "x"), std::runtime_error);
   }
 
-  void testThrowsIfNullFieldData()
-  {
-    vtkFieldData* nullFieldData = NULL;
+  void testThrowsIfNullFieldData() {
+    vtkFieldData *nullFieldData = NULL;
     FieldDataToMetadata function;
-    TSM_ASSERT_THROWS("Should not be able to execute with null field data.", function.execute(nullFieldData, "x"), std::runtime_error );
+    TSM_ASSERT_THROWS("Should not be able to execute with null field data.",
+                      function.execute(nullFieldData, "x"), std::runtime_error);
   }
-
-
 };
 
-
 #endif
diff --git a/Vates/VatesAPI/test/FilteringUpdateProgressActionTest.h b/Vates/VatesAPI/test/FilteringUpdateProgressActionTest.h
index 88df1db2777d1451dcedcc0722d8237ac5307c72..de0a70e39716a1d59865cf4d55ee4d0e9cdf938f 100644
--- a/Vates/VatesAPI/test/FilteringUpdateProgressActionTest.h
+++ b/Vates/VatesAPI/test/FilteringUpdateProgressActionTest.h
@@ -4,48 +4,49 @@
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/FilteringUpdateProgressAction.h"
 
-class FilteringUpdateProgressActionTest: public CxxTest::TestSuite
-{
+class FilteringUpdateProgressActionTest : public CxxTest::TestSuite {
 
 private:
-
-  //Actually a fake, wouldn't make sense to mock a concrete type. Effectively the view.
-  struct MockFilter
-  {
+  // Actually a fake, wouldn't make sense to mock a concrete type. Effectively
+  // the view.
+  struct MockFilter {
     double Progress;
     std::string Message;
-    void updateAlgorithmProgress(double progress, const std::string& message)
-    {
+    void updateAlgorithmProgress(double progress, const std::string &message) {
       this->Progress = progress;
       this->Message = message;
     }
   };
 
-
-  typedef Mantid::VATES::FilterUpdateProgressAction<MockFilter> ProgressActionType;
+  typedef Mantid::VATES::FilterUpdateProgressAction<MockFilter>
+      ProgressActionType;
 
 public:
-
-  void testCallsView()
-  {
-    //Test that is wired up correctly.
+  void testCallsView() {
+    // Test that is wired up correctly.
     MockFilter view;
-    ProgressActionType  model(&view, "message");
+    ProgressActionType model(&view, "message");
     model.eventRaised(10);
-    TSM_ASSERT_EQUALS("View and model are not wired up correctly for progress updating.", 10, view.Progress);
-    TSM_ASSERT_EQUALS("View and model are not wired up correctly for progress updating.", "message", view.Message);
+    TSM_ASSERT_EQUALS(
+        "View and model are not wired up correctly for progress updating.", 10,
+        view.Progress);
+    TSM_ASSERT_EQUALS(
+        "View and model are not wired up correctly for progress updating.",
+        "message", view.Message);
   }
 
-  void testIsProgressAction()
-  {
-    //Test that template works through abstract data type.
+  void testIsProgressAction() {
+    // Test that template works through abstract data type.
     MockFilter view;
-    ProgressActionType  model(&view, "message");
-    Mantid::VATES::ProgressAction& imodel = model;
+    ProgressActionType model(&view, "message");
+    Mantid::VATES::ProgressAction &imodel = model;
     imodel.eventRaised(10);
-    TSM_ASSERT_EQUALS("View and model are not wired up correctly for progress updating.", 10, view.Progress);
-    TSM_ASSERT_EQUALS("View and model are not wired up correctly for progress updating.", "message", view.Message);
+    TSM_ASSERT_EQUALS(
+        "View and model are not wired up correctly for progress updating.", 10,
+        view.Progress);
+    TSM_ASSERT_EQUALS(
+        "View and model are not wired up correctly for progress updating.",
+        "message", view.Message);
   }
-
 };
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/IgnoreZerosThresholdRangeTest.h b/Vates/VatesAPI/test/IgnoreZerosThresholdRangeTest.h
index a47d1c1cc3b5c090ed2846b25abc6ac51dc32ff1..117b637b7d93311ce98722409c4fb8510e1d3795 100644
--- a/Vates/VatesAPI/test/IgnoreZerosThresholdRangeTest.h
+++ b/Vates/VatesAPI/test/IgnoreZerosThresholdRangeTest.h
@@ -7,26 +7,21 @@
 using namespace Mantid;
 using namespace Mantid::VATES;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class IgnoreZerosThresholdRangeTest: public CxxTest::TestSuite
-{
-
-public :
+class IgnoreZerosThresholdRangeTest : public CxxTest::TestSuite {
 
-  void testIgnoreEmptyCells()
-  {
+public:
+  void testIgnoreEmptyCells() {
     IgnoreZerosThresholdRange range;
-    
+
     TS_ASSERT_EQUALS(true, range.inRange(0.001));
     TS_ASSERT_EQUALS(true, range.inRange(-0.001));
     TS_ASSERT_EQUALS(false, range.inRange(0));
   }
 
-  void testGetMinMax()
-  {
+  void testGetMinMax() {
     IgnoreZerosThresholdRange range;
 
     range.inRange(1);
@@ -37,8 +32,7 @@ public :
     TSM_ASSERT_EQUALS("Wrong min found", -2, range.getMinimum());
   }
 
-  void testMinIsNeverZero()
-  {
+  void testMinIsNeverZero() {
     IgnoreZerosThresholdRange range;
 
     range.inRange(0);
@@ -46,7 +40,6 @@ public :
     range.inRange(2);
     TSM_ASSERT_EQUALS("Wrong min found", 0.5, range.getMinimum());
   }
-
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/LoadVTKTest.h b/Vates/VatesAPI/test/LoadVTKTest.h
index e0698824a20b5dcbc8d84f89873b8b1b4bf99b0b..68bd8de7275911aa4abcbccb7b78ab374662edfd 100644
--- a/Vates/VatesAPI/test/LoadVTKTest.h
+++ b/Vates/VatesAPI/test/LoadVTKTest.h
@@ -12,44 +12,48 @@ using namespace Mantid::API;
 using namespace Mantid::VATES;
 using namespace Mantid::Geometry;
 
-class LoadVTKTest: public CxxTest::TestSuite
-{
+class LoadVTKTest : public CxxTest::TestSuite {
 public:
-
-  void test_catagory()
-  {
+  void test_catagory() {
     LoadVTK loadVTK;
-    Algorithm& alg = loadVTK;
+    Algorithm &alg = loadVTK;
     TS_ASSERT_EQUALS("MDAlgorithms", alg.category());
   }
 
-  void test_version()
-  {
+  void test_version() {
     LoadVTK loadVTK;
     TS_ASSERT_EQUALS(1, loadVTK.version());
   }
 
-  void test_Properties()
-  {
+  void test_Properties() {
     LoadVTK loadVTK;
     loadVTK.initialize();
-    TS_ASSERT_THROWS_NOTHING(loadVTK.setPropertyValue("Filename", "iron_protein.vtk"));
-    TS_ASSERT_THROWS_NOTHING(loadVTK.setPropertyValue("OutputWorkspace", "OutWS"));
-    TS_ASSERT_THROWS_NOTHING(loadVTK.setPropertyValue("SignalArrayName", "scalars"));
-    TS_ASSERT( loadVTK.isInitialized() )
+    TS_ASSERT_THROWS_NOTHING(
+        loadVTK.setPropertyValue("Filename", "iron_protein.vtk"));
+    TS_ASSERT_THROWS_NOTHING(
+        loadVTK.setPropertyValue("OutputWorkspace", "OutWS"));
+    TS_ASSERT_THROWS_NOTHING(
+        loadVTK.setPropertyValue("SignalArrayName", "scalars"));
+    TS_ASSERT(loadVTK.isInitialized())
   }
 
-  void do_check_dimension(IMDDimension_const_sptr dimension, const std::string& expectedName, const double expectedMin, const double expectedMax, const int expectedNBins)
-  {
+  void do_check_dimension(IMDDimension_const_sptr dimension,
+                          const std::string &expectedName,
+                          const double expectedMin, const double expectedMax,
+                          const int expectedNBins) {
     TSM_ASSERT_EQUALS("Name is wrong.", dimension->getName(), expectedName);
-    TSM_ASSERT_EQUALS("Id is wrong.", dimension->getDimensionId(), expectedName);
-    TSM_ASSERT_DELTA("Minimum is wrong.", dimension->getMinimum(), expectedMin, 0.01);
-    TSM_ASSERT_DELTA("Maximum is wrong.", dimension->getMaximum(), expectedMax, 0.01);
-    TSM_ASSERT_EQUALS("Number of bins is wrong.", dimension->getNBins(), expectedNBins);
+    TSM_ASSERT_EQUALS("Id is wrong.", dimension->getDimensionId(),
+                      expectedName);
+    TSM_ASSERT_DELTA("Minimum is wrong.", dimension->getMinimum(), expectedMin,
+                     0.01);
+    TSM_ASSERT_DELTA("Maximum is wrong.", dimension->getMaximum(), expectedMax,
+                     0.01);
+    TSM_ASSERT_EQUALS("Number of bins is wrong.", dimension->getNBins(),
+                      expectedNBins);
   }
 
-  void do_test_bad_arrays(const std::string& signalArrayName, const std::string& errorSQArrayName="")
-  {
+  void do_test_bad_arrays(const std::string &signalArrayName,
+                          const std::string &errorSQArrayName = "") {
     LoadVTK loadVTK;
     loadVTK.setRethrows(true);
     loadVTK.initialize();
@@ -57,24 +61,21 @@ public:
     loadVTK.setPropertyValue("OutputWorkspace", "OutWS");
     loadVTK.setPropertyValue("SignalArrayName", signalArrayName);
     loadVTK.setPropertyValue("ErrorSQArrayName", errorSQArrayName);
-    TS_ASSERT_THROWS(loadVTK.execute(), std::invalid_argument&);
+    TS_ASSERT_THROWS(loadVTK.execute(), std::invalid_argument &);
   }
 
-  void test_bad_signal_array()
-  {
+  void test_bad_signal_array() {
     const std::string signalArray = "?!"; // Not a name that exists.
     do_test_bad_arrays(signalArray);
   }
 
-  void test_bad_errorSQ_array()
-  {
-    const std::string signalArray = "scalar_array";  // Does exist
-    const std::string errorSQArray = "?!"; // Not a name that exists.
+  void test_bad_errorSQ_array() {
+    const std::string signalArray = "scalar_array"; // Does exist
+    const std::string errorSQArray = "?!";          // Not a name that exists.
     do_test_bad_arrays(signalArray, errorSQArray);
   }
 
-  void test_load_VTK_file_as_histo()
-  {
+  void test_load_VTK_file_as_histo() {
     const std::string outWSName = "OutWS";
 
     LoadVTK loadVTK;
@@ -87,12 +88,20 @@ public:
     loadVTK.setProperty("AdaptiveBinned", false);
     loadVTK.execute();
 
-    IMDHistoWorkspace_sptr outWS = AnalysisDataService::Instance().retrieveWS<IMDHistoWorkspace>(outWSName);
+    IMDHistoWorkspace_sptr outWS =
+        AnalysisDataService::Instance().retrieveWS<IMDHistoWorkspace>(
+            outWSName);
 
     TS_ASSERT_EQUALS(3, outWS->getNumDims());
-    do_check_dimension(outWS->getDimension(0), "X", 0, 67, 68); // These numbers are expected min, max, and nbins known from the input file for dim x.
-    do_check_dimension(outWS->getDimension(1), "Y", 0, 67, 68); // These numbers are expected min, max, and nbins known from the input file for dim y.
-    do_check_dimension(outWS->getDimension(2), "Z", 0, 67, 68); // These numbers are expected min, max, and nbins known from the input file for dim z.
+    do_check_dimension(outWS->getDimension(0), "X", 0, 67,
+                       68); // These numbers are expected min, max, and nbins
+                            // known from the input file for dim x.
+    do_check_dimension(outWS->getDimension(1), "Y", 0, 67,
+                       68); // These numbers are expected min, max, and nbins
+                            // known from the input file for dim y.
+    do_check_dimension(outWS->getDimension(2), "Z", 0, 67,
+                       68); // These numbers are expected min, max, and nbins
+                            // known from the input file for dim z.
 
     // Quick check of loaded data.
     TS_ASSERT_EQUALS(0, outWS->getSignalAt(0));
@@ -101,19 +110,20 @@ public:
     TS_ASSERT_EQUALS(3, outWS->getSignalAt(3));
   }
 
-  void test_KeepTopPercent_bounds()
-  {
+  void test_KeepTopPercent_bounds() {
     LoadVTK loadVTK;
     loadVTK.initialize();
     loadVTK.setRethrows(true);
 
-    TSM_ASSERT_THROWS_NOTHING("Within bounds", loadVTK.setProperty("KeepTopPercent", 1.0));
-    TSM_ASSERT_THROWS("Too low", loadVTK.setProperty("KeepTopPercent", -0.01), std::invalid_argument&);
-    TSM_ASSERT_THROWS("Too high", loadVTK.setProperty("KeepTopPercent", 100.01), std::invalid_argument&);
+    TSM_ASSERT_THROWS_NOTHING("Within bounds",
+                              loadVTK.setProperty("KeepTopPercent", 1.0));
+    TSM_ASSERT_THROWS("Too low", loadVTK.setProperty("KeepTopPercent", -0.01),
+                      std::invalid_argument &);
+    TSM_ASSERT_THROWS("Too high", loadVTK.setProperty("KeepTopPercent", 100.01),
+                      std::invalid_argument &);
   }
 
-  void test_load_vtk_file_as_mdevent()
-  {
+  void test_load_vtk_file_as_mdevent() {
     const std::string outWSName = "OutWS";
 
     LoadVTK loadVTK;
@@ -126,8 +136,9 @@ public:
     loadVTK.setPropertyValue("ErrorSQArrayName", "scalar_array");
     loadVTK.execute();
 
-    IMDEventWorkspace_sptr outWS = AnalysisDataService::Instance().retrieveWS<IMDEventWorkspace>(
-        outWSName);
+    IMDEventWorkspace_sptr outWS =
+        AnalysisDataService::Instance().retrieveWS<IMDEventWorkspace>(
+            outWSName);
 
     TS_ASSERT_EQUALS(3, outWS->getNumDims());
     do_check_dimension(outWS->getDimension(0), "X", 0, 67,
@@ -140,21 +151,23 @@ public:
                        68); // These numbers are expected min, max, and nbins
                             // known from the input file for dim z.
     TSM_ASSERT_EQUALS("Should be an UnknownFrame",
-                        Mantid::Geometry::UnknownFrame::UnknownFrameName,
-                        outWS->getDimension(0)->getMDFrame().name());
-	TSM_ASSERT_EQUALS("Should be an UnknownFrame",
-                        Mantid::Geometry::UnknownFrame::UnknownFrameName,
-                        outWS->getDimension(1)->getMDFrame().name());
-	TSM_ASSERT_EQUALS("Should be an UnknownFrame",
-                        Mantid::Geometry::UnknownFrame::UnknownFrameName,
-                        outWS->getDimension(2)->getMDFrame().name());
+                      Mantid::Geometry::UnknownFrame::UnknownFrameName,
+                      outWS->getDimension(0)->getMDFrame().name());
+    TSM_ASSERT_EQUALS("Should be an UnknownFrame",
+                      Mantid::Geometry::UnknownFrame::UnknownFrameName,
+                      outWS->getDimension(1)->getMDFrame().name());
+    TSM_ASSERT_EQUALS("Should be an UnknownFrame",
+                      Mantid::Geometry::UnknownFrame::UnknownFrameName,
+                      outWS->getDimension(2)->getMDFrame().name());
 
     double topPercent = loadVTK.getProperty("KeepTopPercent");
     TSM_ASSERT_EQUALS("Should default to 25%", 25, topPercent);
 
-    const int expectedSignalMax = 9999; //Known from file
-    const int expectedSignalMin = 0; // Known from file
-    const int expectedSignalThreshold = static_cast<int>((1-0.25)*(expectedSignalMax - expectedSignalMin)+expectedSignalMin);
+    const int expectedSignalMax = 9999; // Known from file
+    const int expectedSignalMin = 0;    // Known from file
+    const int expectedSignalThreshold =
+        static_cast<int>((1 - 0.25) * (expectedSignalMax - expectedSignalMin) +
+                         expectedSignalMin);
     const int actualSignalMin = loadVTK.getProperty("SignalMinimum");
     const int actualSignalMax = loadVTK.getProperty("SignalMaximum");
     const int actualSignalThreshold = loadVTK.getProperty("SignalThreshold");
@@ -163,11 +176,9 @@ public:
     TS_ASSERT_EQUALS(expectedSignalThreshold, actualSignalThreshold);
 
     TS_ASSERT(outWS->getNEvents() > 0);
-
   }
 
-  void test_dynamic_load()
-  {
+  void test_dynamic_load() {
     const std::string outWSName = "OutWS";
     auto alg = AlgorithmManager::Instance().create("Load");
     alg->setRethrows(true);
@@ -179,7 +190,9 @@ public:
     alg->setProperty("AdaptiveBinned", false);
     TS_ASSERT_THROWS_NOTHING(alg->execute());
 
-    TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().retrieveWS<IMDHistoWorkspace>(outWSName));
+    TS_ASSERT_THROWS_NOTHING(
+        AnalysisDataService::Instance().retrieveWS<IMDHistoWorkspace>(
+            outWSName));
   }
 };
 
diff --git a/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h
index 5ee24e12f022b9adf3ee6b7b2bf2abdc307842c6..b47bf4e0ed453f0433c534811d29ef62f2583ff0 100644
--- a/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h
@@ -19,215 +19,212 @@ using namespace testing;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class MDEWEventNexusLoadingPresenterTest : public CxxTest::TestSuite
-{
+class MDEWEventNexusLoadingPresenterTest : public CxxTest::TestSuite {
 
 private:
-
-  // Helper method to return the full path to a real nexus file that is the correct format for this functionality.
-  static std::string getSuitableFile()
-  {
-    std::string temp = Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs");
+  // Helper method to return the full path to a real nexus file that is the
+  // correct format for this functionality.
+  static std::string getSuitableFile() {
+    std::string temp =
+        Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs");
     return temp;
   }
-  
-  // Helper method to return the full path to a real nexus file that is the wrong format for this functionality.
-  static std::string getUnhandledFile()
-  {
-    std::string temp = Mantid::API::FileFinder::Instance().getFullPath("CNCS_7860_event.nxs");
+
+  // Helper method to return the full path to a real nexus file that is the
+  // wrong format for this functionality.
+  static std::string getUnhandledFile() {
+    std::string temp =
+        Mantid::API::FileFinder::Instance().getFullPath("CNCS_7860_event.nxs");
     return temp;
   }
 
 public:
+  void testConstructWithEmptyFileThrows() {
+    TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
+                      MDEWEventNexusLoadingPresenter(
+                          Mantid::Kernel::make_unique<MockMDLoadingView>(), ""),
+                      std::invalid_argument);
+  }
 
-void testConstructWithEmptyFileThrows()
-{
-  TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
-                    MDEWEventNexusLoadingPresenter(
-                        Mantid::Kernel::make_unique<MockMDLoadingView>(), ""),
-                    std::invalid_argument);
-}
-
-void testConstructWithNullViewThrows()
-{
-  TSM_ASSERT_THROWS("Should throw if a null view is given.",
-                    MDEWEventNexusLoadingPresenter(nullptr, "some_file"),
-                    std::invalid_argument);
-}
-
-void testConstruct()
-{
-  TSM_ASSERT_THROWS_NOTHING(
-      "Object should be created without exception.",
-      MDEWEventNexusLoadingPresenter(
-          Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()));
-}
-
-void testCanReadFile()
-{
-  MDEWEventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile());
-  TSM_ASSERT(
-      "A file of this type cannot and should not be read by this presenter!.",
-      !presenter.canReadFile());
-}
-
-void testExecution()
-{
-  //Setup view
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(testing::Return(true));
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  MockProgressAction mockDrawingProgressAction;
-  
-  //Create the presenter and runit!
-  MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile());
-  presenter.executeLoadMetadata();
-  vtkSmartPointer<vtkDataSet> product = presenter.execute(
-      &factory, mockLoadingProgressAction, mockDrawingProgressAction);
-
-  TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
-  TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName()));
-  TSM_ASSERT("No field data!", NULL != product->GetFieldData());
-  TSM_ASSERT_EQUALS("Two arrays expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
-  TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
-  TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
-  TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-}
-
-void testCallHasTDimThrows()
-{
-  MDEWEventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.hasTDimensionAvailable(), std::runtime_error);
-}
-
-void testCallGetTDimensionValuesThrows()
-{
-  MDEWEventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getTimeStepValues(), std::runtime_error);
-}
-
-void testCallGetGeometryThrows()
-{
-  MDEWEventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getGeometryXML(), std::runtime_error);
-}
-
-void testGetWorkspaceTypeName()
-{
-  MDEWEventNexusLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
-  TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
-                    presenter.getWorkspaceTypeName());
-}
-
-void testTimeLabel()
-{
-  //Setup view
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(testing::Return(true));
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  MockProgressAction mockDrawingProgressAction;
-
-  //Create the presenter and runit!
-  MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile());
-  presenter.executeLoadMetadata();
-  vtkSmartPointer<vtkDataSet> product = presenter.execute(
-      &factory, mockLoadingProgressAction, mockDrawingProgressAction);
-  TSM_ASSERT_EQUALS("Time label should be exact.",
-                    presenter.getTimeStepLabel(), "D (En)");
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-}
-
-void testAxisLabels()
-{
-  //Setup view
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*mockView, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(testing::Return(true));
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  MockProgressAction mockDrawingProgressAction;
-
-  //Create the presenter and runit!
-  MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile());
-  presenter.executeLoadMetadata();
-  vtkSmartPointer<vtkDataSet> product = presenter.execute(
-      &factory, mockLoadingProgressAction, mockDrawingProgressAction);
-  TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product));
-  TSM_ASSERT_EQUALS("X Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForX"),
-                    "A ($\\AA$)");
-  TSM_ASSERT_EQUALS("Y Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForY"),
-                    "B ($\\AA$)");
-  TSM_ASSERT_EQUALS("Z Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForZ"),
-                    "C ($\\AA$)");
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-}
+  void testConstructWithNullViewThrows() {
+    TSM_ASSERT_THROWS("Should throw if a null view is given.",
+                      MDEWEventNexusLoadingPresenter(nullptr, "some_file"),
+                      std::invalid_argument);
+  }
+
+  void testConstruct() {
+    TSM_ASSERT_THROWS_NOTHING(
+        "Object should be created without exception.",
+        MDEWEventNexusLoadingPresenter(
+            Mantid::Kernel::make_unique<MockMDLoadingView>(),
+            getSuitableFile()));
+  }
 
+  void testCanReadFile() {
+    MDEWEventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile());
+    TSM_ASSERT(
+        "A file of this type cannot and should not be read by this presenter!.",
+        !presenter.canReadFile());
+  }
+
+  void testExecution() {
+    // Setup view
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(testing::Return(true));
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    MockProgressAction mockDrawingProgressAction;
+
+    // Create the presenter and runit!
+    MDEWEventNexusLoadingPresenter presenter(std::move(view),
+                                             getSuitableFile());
+    presenter.executeLoadMetadata();
+    vtkSmartPointer<vtkDataSet> product = presenter.execute(
+        &factory, mockLoadingProgressAction, mockDrawingProgressAction);
+
+    TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
+    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid",
+                      std::string(product->GetClassName()));
+    TSM_ASSERT("No field data!", NULL != product->GetFieldData());
+    TSM_ASSERT_EQUALS(
+        "Two arrays expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
+    TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
+    TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
+    TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+  }
+
+  void testCallHasTDimThrows() {
+    MDEWEventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.hasTDimensionAvailable(), std::runtime_error);
+  }
+
+  void testCallGetTDimensionValuesThrows() {
+    MDEWEventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getTimeStepValues(), std::runtime_error);
+  }
+
+  void testCallGetGeometryThrows() {
+    MDEWEventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getGeometryXML(), std::runtime_error);
+  }
+
+  void testGetWorkspaceTypeName() {
+    MDEWEventNexusLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile());
+    TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
+                      presenter.getWorkspaceTypeName());
+  }
+
+  void testTimeLabel() {
+    // Setup view
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(testing::Return(true));
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    MockProgressAction mockDrawingProgressAction;
+
+    // Create the presenter and runit!
+    MDEWEventNexusLoadingPresenter presenter(std::move(view),
+                                             getSuitableFile());
+    presenter.executeLoadMetadata();
+    vtkSmartPointer<vtkDataSet> product = presenter.execute(
+        &factory, mockLoadingProgressAction, mockDrawingProgressAction);
+    TSM_ASSERT_EQUALS("Time label should be exact.",
+                      presenter.getTimeStepLabel(), "D (En)");
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+  }
+
+  void testAxisLabels() {
+    // Setup view
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*mockView, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(testing::Return(true));
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    MockProgressAction mockDrawingProgressAction;
+
+    // Create the presenter and runit!
+    MDEWEventNexusLoadingPresenter presenter(std::move(view),
+                                             getSuitableFile());
+    presenter.executeLoadMetadata();
+    vtkSmartPointer<vtkDataSet> product = presenter.execute(
+        &factory, mockLoadingProgressAction, mockDrawingProgressAction);
+    TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product));
+    TSM_ASSERT_EQUALS("X Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForX"),
+                      "A ($\\AA$)");
+    TSM_ASSERT_EQUALS("Y Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForY"),
+                      "B ($\\AA$)");
+    TSM_ASSERT_EQUALS("Z Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForZ"),
+                      "C ($\\AA$)");
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+  }
 };
 #endif
diff --git a/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h
index dc29ee3c78682ab76bc41a11fef3914e46413c59..d26ce4798e432077b08381901f17877ce311c1e2 100644
--- a/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h
@@ -1,4 +1,4 @@
-#ifndef MDEW_IN_MEMORY_LOADING_PRESENTER_TEST_H 
+#ifndef MDEW_IN_MEMORY_LOADING_PRESENTER_TEST_H
 #define MDEW_IN_MEMORY_LOADING_PRESENTER_TEST_H
 
 #include <cxxtest/TestSuite.h>
@@ -19,54 +19,48 @@ using namespace Mantid::VATES;
 using namespace Mantid::API;
 using namespace testing;
 
-class MDEWInMemoryLoadingPresenterTest: public CxxTest::TestSuite
-{
+class MDEWInMemoryLoadingPresenterTest : public CxxTest::TestSuite {
 
 private:
-
   // Helper type. Mocks a Workspace Provider.
-  class MockWorkspaceProvider : public Mantid::VATES::WorkspaceProvider
-  {
+  class MockWorkspaceProvider : public Mantid::VATES::WorkspaceProvider {
   public:
     MOCK_CONST_METHOD1(canProvideWorkspace, bool(std::string));
-    MOCK_CONST_METHOD1(fetchWorkspace, Mantid::API::Workspace_sptr(std::string));
+    MOCK_CONST_METHOD1(fetchWorkspace,
+                       Mantid::API::Workspace_sptr(std::string));
     MOCK_CONST_METHOD1(disposeWorkspace, void(std::string));
   };
 
   // Helper method. Generates and returns a valid IMDEventWorkspace
-  static Mantid::API::Workspace_sptr getReal4DWorkspace()
-  {
+  static Mantid::API::Workspace_sptr getReal4DWorkspace() {
     AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");	
+    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
     alg->initialize();
     alg->setRethrows(true);
-    alg->setPropertyValue("Filename", Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs"));
+    alg->setPropertyValue(
+        "Filename",
+        Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs"));
     alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-    alg->setProperty("FileBackEnd", false); 
-    alg->execute(); 
+    alg->setProperty("FileBackEnd", false);
+    alg->execute();
     return AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
   }
 
-
   // Helper method. Generates a non-IMDEventWorkspace.
-  static Mantid::API::Workspace_sptr getBadWorkspace()
-  {
-    //Return a table workspace.
+  static Mantid::API::Workspace_sptr getBadWorkspace() {
+    // Return a table workspace.
     return WorkspaceFactory::Instance().createTable();
   }
 
 public:
-
-  void testConstructWithNullViewThrows()
-  {
+  void testConstructWithNullViewThrows() {
     TSM_ASSERT_THROWS(
         "Should throw with null view.",
         MDEWInMemoryLoadingPresenter(nullptr, new MockWorkspaceProvider, "_"),
         std::invalid_argument);
   }
 
-  void testConstructWithNullRepositoryThrows()
-  {
+  void testConstructWithNullRepositoryThrows() {
     TSM_ASSERT_THROWS(
         "Should throw with null repository.",
         MDEWInMemoryLoadingPresenter(
@@ -74,8 +68,7 @@ public:
         std::invalid_argument);
   }
 
-  void testConstructWithEmptyWsNameThrows()
-  {
+  void testConstructWithEmptyWsNameThrows() {
     std::string emptyName = "";
     TSM_ASSERT_THROWS("Should throw with empty Workspace name.",
                       MDEWInMemoryLoadingPresenter(
@@ -84,78 +77,93 @@ public:
                       std::invalid_argument);
   }
 
-  void testConstruction()
-  {
+  void testConstruction() {
     TS_ASSERT_THROWS_NOTHING(MDEWInMemoryLoadingPresenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_"));
   }
 
-  void testCanLoadWithInvalidName()
-  {
+  void testCanLoadWithInvalidName() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
-    EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(false)); //No matter what the argument, always returns false.
+    EXPECT_CALL(*repository, canProvideWorkspace(_))
+        .WillOnce(Return(
+            false)); // No matter what the argument, always returns false.
 
-    //Give a dummy name corresponding to the workspace.
+    // Give a dummy name corresponding to the workspace.
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    TSM_ASSERT("Should indicate that the workspace cannot be read-out since the name is not in the Repository.", !presenter.canReadFile());
+    TSM_ASSERT("Should indicate that the workspace cannot be read-out since "
+               "the name is not in the Repository.",
+               !presenter.canReadFile());
   }
 
-  void testCanLoadWithWrongWsType()
-  {
+  void testCanLoadWithWrongWsType() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
-    Mantid::API::Workspace_sptr badWs = getBadWorkspace(); // Not an IMDEventWorkspace.
-    EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true.
-    EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(badWs)); 
-
-    //Give a dummy name corresponding to the workspace.
+    Mantid::API::Workspace_sptr badWs =
+        getBadWorkspace(); // Not an IMDEventWorkspace.
+    EXPECT_CALL(*repository, canProvideWorkspace(_))
+        .WillOnce(
+            Return(true)); // No matter what the argument, always returns true.
+    EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(badWs));
+
+    // Give a dummy name corresponding to the workspace.
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    TSM_ASSERT("Should indicate that the workspace cannot be read-out since it is not of the right type.", !presenter.canReadFile());
+    TSM_ASSERT("Should indicate that the workspace cannot be read-out since it "
+               "is not of the right type.",
+               !presenter.canReadFile());
   }
 
-  void testCanLoadSucceeds()
-  {
+  void testCanLoadSucceeds() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr goodWs = getReal4DWorkspace();
-    EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true.
-    EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs)); 
+    EXPECT_CALL(*repository, canProvideWorkspace(_))
+        .WillOnce(
+            Return(true)); // No matter what the argument, always returns true.
+    EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs));
 
-    //Give a dummy name corresponding to the workspace.
+    // Give a dummy name corresponding to the workspace.
     MDEWInMemoryLoadingPresenter presenter(
-        Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), "_");
+        Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
+        "_");
 
-    TSM_ASSERT("Should have worked! Workspace is of correct type and repository says ws is present.!", presenter.canReadFile());
+    TSM_ASSERT("Should have worked! Workspace is of correct type and "
+               "repository says ws is present.!",
+               presenter.canReadFile());
   }
 
-  void testExtractMetadata()
-  {
+  void testExtractMetadata() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr ws = getReal4DWorkspace();
-    EXPECT_CALL(*repository, fetchWorkspace(_)).Times(1).WillRepeatedly(Return(ws));
+    EXPECT_CALL(*repository, fetchWorkspace(_))
+        .Times(1)
+        .WillRepeatedly(Return(ws));
 
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    //Test that it doesn't work when not setup.
-    TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should throw if not run first.", presenter.getGeometryXML(), std::runtime_error);
-    
-    //Test that it does work when setup.
+    // Test that it doesn't work when not setup.
+    TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should "
+                      "throw if not run first.",
+                      presenter.getGeometryXML(), std::runtime_error);
+
+    // Test that it does work when setup.
     presenter.executeLoadMetadata();
-    TSM_ASSERT("Should export geometry xml metadata on request.", !presenter.getGeometryXML().empty());
-    TSM_ASSERT("Should export min value metadata on request.", presenter.getMinValue() <= presenter.getMaxValue())
-    TSM_ASSERT("Should export instrument metadata on request", presenter.getInstrument().empty())
+    TSM_ASSERT("Should export geometry xml metadata on request.",
+               !presenter.getGeometryXML().empty());
+    TSM_ASSERT("Should export min value metadata on request.",
+               presenter.getMinValue() <= presenter.getMaxValue())
+    TSM_ASSERT("Should export instrument metadata on request",
+               presenter.getInstrument().empty())
   }
 
-  void testExecution()
-  {
-    //Setup view
+  void testExecution() {
+    // Setup view
     std::unique_ptr<MDLoadingView> view =
         Mantid::Kernel::make_unique<MockMDLoadingView>();
     auto mockView = dynamic_cast<MockMDLoadingView *>(view.get());
@@ -164,7 +172,7 @@ public:
         .Times(0); // Not a question that needs asking for this presenter type.
     EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
 
-    //Setup rendering factory
+    // Setup rendering factory
     MockvtkDataSetFactory factory;
     EXPECT_CALL(factory, initialize(_)).Times(1);
     EXPECT_CALL(factory, create(_))
@@ -173,13 +181,15 @@ public:
 
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr ws = getReal4DWorkspace();
-    EXPECT_CALL(*repository, fetchWorkspace(_)).Times(2).WillRepeatedly(Return(ws));
+    EXPECT_CALL(*repository, fetchWorkspace(_))
+        .Times(2)
+        .WillRepeatedly(Return(ws));
 
-    //Setup progress updates objects
+    // Setup progress updates objects
     MockProgressAction mockLoadingProgressAction;
     MockProgressAction mockDrawingProgressAction;
 
-    //Create the presenter and run it!
+    // Create the presenter and run it!
     MDEWInMemoryLoadingPresenter presenter(std::move(view),
                                            repository.release(), "_");
     presenter.executeLoadMetadata();
@@ -187,19 +197,22 @@ public:
         &factory, mockLoadingProgressAction, mockDrawingProgressAction);
 
     TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
-    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName()));
+    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid",
+                      std::string(product->GetClassName()));
     TSM_ASSERT("No field data!", NULL != product->GetFieldData());
-    TSM_ASSERT_EQUALS("One array expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
+    TSM_ASSERT_EQUALS(
+        "One array expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
     TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
     TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
     TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
-    TSM_ASSERT("Special coordinate metadata failed.", -1 < presenter.getSpecialCoordinates());
+    TSM_ASSERT("Special coordinate metadata failed.",
+               -1 < presenter.getSpecialCoordinates());
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
     TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
   }
 
-  void testCallHasTDimThrows()
-  {
+  void testCallHasTDimThrows() {
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -207,8 +220,7 @@ public:
                       presenter.hasTDimensionAvailable(), std::runtime_error);
   }
 
-  void testCallGetTDimensionValuesThrows()
-  {
+  void testCallGetTDimensionValuesThrows() {
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -216,8 +228,7 @@ public:
                       presenter.getTimeStepValues(), std::runtime_error);
   }
 
-  void testCallGetGeometryThrows()
-  {
+  void testCallGetGeometryThrows() {
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -225,25 +236,21 @@ public:
                       presenter.getGeometryXML(), std::runtime_error);
   }
 
-  void testGetWorkspaceTypeName()
-  {
+  void testGetWorkspaceTypeName() {
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
-    TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName());
+    TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
+                      presenter.getWorkspaceTypeName());
   }
 
-  void testGetSpecialCoordinates()
-  {
+  void testGetSpecialCoordinates() {
     MDEWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
     TSM_ASSERT_EQUALS("Characterisation Test Failed", -1,
                       presenter.getSpecialCoordinates());
   }
-
-
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h
index 888169972e75fd82926bffa989762d0c6cd56d7a..02984a1716aeac42cfd125dd115511dd2f8fa271 100644
--- a/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h
@@ -1,5 +1,5 @@
 #ifndef MDEW_LOADING_PRESENTER_TEST_H_
-#define MDEW_LOADING_PRESENTER_TEST_H_ 
+#define MDEW_LOADING_PRESENTER_TEST_H_
 
 #include <cxxtest/TestSuite.h>
 #include <vtkUnstructuredGrid.h>
@@ -23,17 +23,15 @@ using namespace Mantid::API;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class MDEWLoadingPresenterTest : public CxxTest::TestSuite
-{
-
-private: 
+class MDEWLoadingPresenterTest : public CxxTest::TestSuite {
 
+private:
   /*
-  Helper class allows the behaviour of the abstract base type to be tested. Derives from target abstract class providing 
+  Helper class allows the behaviour of the abstract base type to be tested.
+  Derives from target abstract class providing
   dummy implemenations of pure virtual methods.
   */
-  class ConcreteMDEWLoadingPresenter : public MDEWLoadingPresenter
-  {
+  class ConcreteMDEWLoadingPresenter : public MDEWLoadingPresenter {
   private:
     typedef MDEWLoadingPresenter BaseClass;
 
@@ -56,156 +54,155 @@ private:
     bool canReadFile() const override { return true; }
 
     bool shouldLoad() override {
-      //Forwarding method
+      // Forwarding method
       return BaseClass::shouldLoad();
     }
 
     bool canLoadFileBasedOnExtension(
         const std::string &filename,
         const std::string &expectedExtension) const override {
-      //Forwarding method.
-      return BaseClass::canLoadFileBasedOnExtension(filename, expectedExtension);
+      // Forwarding method.
+      return BaseClass::canLoadFileBasedOnExtension(filename,
+                                                    expectedExtension);
     }
 
     ~ConcreteMDEWLoadingPresenter() override {}
   };
 
-
 public:
+  void testShouldLoadFirstTimeRound() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
+    EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
+    EXPECT_CALL(*mockView, getTime()).Times(2);
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
+
+    ConcreteMDEWLoadingPresenter presenter(std::move(view));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Should NOT request load on second usage. Should have it's "
+               "state syncrhonised with view and the view hasn't changed!",
+               !presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(mockView));
+  }
+
+  void testTimeChanged() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
+    EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
+    EXPECT_CALL(*mockView, getTime())
+        .Times(2)
+        .WillOnce(Return(0))
+        .WillOnce(Return(1)); // Time has changed on 2nd call
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
+
+    ConcreteMDEWLoadingPresenter presenter(std::move(view));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Time has changed, but that shouldn't trigger load",
+               !presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(mockView));
+  }
 
-void testShouldLoadFirstTimeRound()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
-  EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
-  EXPECT_CALL(*mockView, getTime()).Times(2);
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
-
-  ConcreteMDEWLoadingPresenter presenter(std::move(view));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Should NOT request load on second usage. Should have it's state syncrhonised with view and the view hasn't changed!", !presenter.shouldLoad());
-  
-  TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(mockView));
-}
-
-void testTimeChanged()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
-  EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
-  EXPECT_CALL(*mockView, getTime())
-      .Times(2)
-      .WillOnce(Return(0))
-      .WillOnce(Return(1)); // Time has changed on 2nd call
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
-
-  ConcreteMDEWLoadingPresenter presenter(std::move(view));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Time has changed, but that shouldn't trigger load",
-             !presenter.shouldLoad());
-
-  TSM_ASSERT("View not used as expected.",
-             Mock::VerifyAndClearExpectations(mockView));
-}
-
-void testLoadInMemoryChanged()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
-  EXPECT_CALL(*mockView, getLoadInMemory())
-      .Times(2)
-      .WillOnce(Return(true))
-      .WillOnce(Return(false)); // Load in memory changed
-  EXPECT_CALL(*mockView, getTime()).Times(2);
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
-
-  ConcreteMDEWLoadingPresenter presenter(std::move(view));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load",
-             presenter.shouldLoad());
-
-  TSM_ASSERT("View not used as expected.",
-             Mock::VerifyAndClearExpectations(mockView));
-}
-
-void testDepthChanged()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
-  EXPECT_CALL(*mockView, getRecursionDepth())
-      .Times(2)
-      .WillOnce(Return(10))
-      .WillOnce(Return(100)); // Recursion depth changed.
-  EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
-  EXPECT_CALL(*mockView, getTime()).Times(2);
-  EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
-
-  ConcreteMDEWLoadingPresenter presenter(std::move(view));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Depth has changed, but that shouldn't trigger load",
-             !presenter.shouldLoad());
-
-  TSM_ASSERT("View not used as expected.",
-             Mock::VerifyAndClearExpectations(mockView));
-}
-
-void testhasTDimensionWhenIntegrated() {
-  // Setup view
-  ConcreteMDEWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>());
-
-  // Test that it does work when setup.
-  Mantid::API::Workspace_sptr ws =
-      get3DWorkspace(true, true); // Integrated T Dimension
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
-
-  TSM_ASSERT("This is a 4D workspace with an integrated T dimension",
-             !presenter.hasTDimensionAvailable());
+  void testLoadInMemoryChanged() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth()).Times(2);
+    EXPECT_CALL(*mockView, getLoadInMemory())
+        .Times(2)
+        .WillOnce(Return(true))
+        .WillOnce(Return(false)); // Load in memory changed
+    EXPECT_CALL(*mockView, getTime()).Times(2);
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
+
+    ConcreteMDEWLoadingPresenter presenter(std::move(view));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load",
+               presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(mockView));
   }
 
-  void testHasTDimensionWhenNotIntegrated()
-  {
-    //Setup view
+  void testDepthChanged() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
+    EXPECT_CALL(*mockView, getRecursionDepth())
+        .Times(2)
+        .WillOnce(Return(10))
+        .WillOnce(Return(100)); // Recursion depth changed.
+    EXPECT_CALL(*mockView, getLoadInMemory()).Times(2);
+    EXPECT_CALL(*mockView, getTime()).Times(2);
+    EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0);
+
+    ConcreteMDEWLoadingPresenter presenter(std::move(view));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Depth has changed, but that shouldn't trigger load",
+               !presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(mockView));
+  }
+
+  void testhasTDimensionWhenIntegrated() {
+    // Setup view
     ConcreteMDEWLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>());
 
-    //Test that it does work when setup. 
-    Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true); //Non-integrated T Dimension
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(true, true); // Integrated T Dimension
     presenter.extractMetadata(
         *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
 
-    TSM_ASSERT("This is a 4D workspace with an integrated T dimension", presenter.hasTDimensionAvailable());
+    TSM_ASSERT("This is a 4D workspace with an integrated T dimension",
+               !presenter.hasTDimensionAvailable());
   }
 
-  void testHasTimeLabelWithTDimension()
-  {
-    //Setup view
+  void testHasTDimensionWhenNotIntegrated() {
+    // Setup view
     ConcreteMDEWLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>());
 
-    //Test that it does work when setup.
-    Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true); //Non-integrated T Dimension
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(false, true); // Non-integrated T Dimension
     presenter.extractMetadata(
         *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
 
-    TSM_ASSERT_EQUALS("This is a 4D workspace with a T dimension", "D (A)", presenter.getTimeStepLabel());
+    TSM_ASSERT("This is a 4D workspace with an integrated T dimension",
+               presenter.hasTDimensionAvailable());
   }
 
-  void testCanSetAxisLabelsFrom3DData()
-  {
-    //Setup view
+  void testHasTimeLabelWithTDimension() {
+    // Setup view
     ConcreteMDEWLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>());
 
-    //Test that it does work when setup.
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(false, true); // Non-integrated T Dimension
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
+
+    TSM_ASSERT_EQUALS("This is a 4D workspace with a T dimension", "D (A)",
+                      presenter.getTimeStepLabel());
+  }
+
+  void testCanSetAxisLabelsFrom3DData() {
+    // Setup view
+    ConcreteMDEWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>());
+
+    // Test that it does work when setup.
     Mantid::API::Workspace_sptr ws = get3DWorkspace(true, true);
     presenter.extractMetadata(
         *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
@@ -219,13 +216,12 @@ void testhasTDimensionWhenIntegrated() {
                       getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
   }
 
-  void testCanSetAxisLabelsFrom4DData()
-  {
-    //Setup view
+  void testCanSetAxisLabelsFrom4DData() {
+    // Setup view
     ConcreteMDEWLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>());
 
-    //Test that it does work when setup.
+    // Test that it does work when setup.
     Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true);
     presenter.extractMetadata(
         *boost::dynamic_pointer_cast<IMDEventWorkspace>(ws));
@@ -239,20 +235,21 @@ void testhasTDimensionWhenIntegrated() {
                       getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
   }
 
-  void testCanLoadFileBasedOnExtension()
-  {
+  void testCanLoadFileBasedOnExtension() {
     ConcreteMDEWLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>());
 
     // constructive tests
-    TSM_ASSERT("Should be an exact match", presenter.canLoadFileBasedOnExtension("somefile.nxs", ".nxs"));
-    TSM_ASSERT("Should lowercase uppercase extension", presenter.canLoadFileBasedOnExtension("somefile.NXS", ".nxs"));
-    TSM_ASSERT("Should strip off whitespace", presenter.canLoadFileBasedOnExtension("somefile.nxs ", ".nxs"));
+    TSM_ASSERT("Should be an exact match",
+               presenter.canLoadFileBasedOnExtension("somefile.nxs", ".nxs"));
+    TSM_ASSERT("Should lowercase uppercase extension",
+               presenter.canLoadFileBasedOnExtension("somefile.NXS", ".nxs"));
+    TSM_ASSERT("Should strip off whitespace",
+               presenter.canLoadFileBasedOnExtension("somefile.nxs ", ".nxs"));
     // destructive tests
-    TSM_ASSERT("Extensions do not match, should return false.", !presenter.canLoadFileBasedOnExtension("somefile.nx", ".nxs"));
+    TSM_ASSERT("Extensions do not match, should return false.",
+               !presenter.canLoadFileBasedOnExtension("somefile.nx", ".nxs"));
   }
-
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h
index f6b6dc2c12c27d8a3b503b06c0a107ebbf481281..97c950ac323063e0e81a40c740726a3dce63c65a 100644
--- a/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h
@@ -1,4 +1,4 @@
-#ifndef MDHW_IN_MEMORY_LOADING_PRESENTER_TEST_H 
+#ifndef MDHW_IN_MEMORY_LOADING_PRESENTER_TEST_H
 #define MDHW_IN_MEMORY_LOADING_PRESENTER_TEST_H
 
 #include <cxxtest/TestSuite.h>
@@ -20,46 +20,40 @@ using namespace Mantid::API;
 using namespace testing;
 using Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace;
 
-class MDHWInMemoryLoadingPresenterTest: public CxxTest::TestSuite
-{
+class MDHWInMemoryLoadingPresenterTest : public CxxTest::TestSuite {
 
 private:
-
   // Helper type. Mocks a Workspace Provider.
-  class MockWorkspaceProvider : public Mantid::VATES::WorkspaceProvider
-  {
+  class MockWorkspaceProvider : public Mantid::VATES::WorkspaceProvider {
   public:
     MOCK_CONST_METHOD1(canProvideWorkspace, bool(std::string));
-    MOCK_CONST_METHOD1(fetchWorkspace, Mantid::API::Workspace_sptr(std::string));
+    MOCK_CONST_METHOD1(fetchWorkspace,
+                       Mantid::API::Workspace_sptr(std::string));
     MOCK_CONST_METHOD1(disposeWorkspace, void(std::string));
   };
 
   // Helper method. Generates and returns a valid IMDHistoWorkspace
-  Mantid::API::Workspace_sptr getGoodWorkspace()
-  {
-    Mantid::DataObjects::MDHistoWorkspace_sptr ws = makeFakeMDHistoWorkspace(1.0, 4, 5, 1.0, 0.1,"MD_HISTO_WS");
+  Mantid::API::Workspace_sptr getGoodWorkspace() {
+    Mantid::DataObjects::MDHistoWorkspace_sptr ws =
+        makeFakeMDHistoWorkspace(1.0, 4, 5, 1.0, 0.1, "MD_HISTO_WS");
     return ws;
   }
 
   // Helper method. Generates a non-IMDHistoWorkspace.
-  static Mantid::API::Workspace_sptr getBadWorkspace()
-  {
-    //Return a table workspace.
+  static Mantid::API::Workspace_sptr getBadWorkspace() {
+    // Return a table workspace.
     return WorkspaceFactory::Instance().createTable();
   }
 
 public:
-
-  void testConstructWithNullViewThrows()
-  {
+  void testConstructWithNullViewThrows() {
     TSM_ASSERT_THROWS(
         "Should throw with null view.",
         MDHWInMemoryLoadingPresenter(nullptr, new MockWorkspaceProvider, "_"),
         std::invalid_argument);
   }
 
-  void testConstructWithNullRepositoryThrows()
-  {
+  void testConstructWithNullRepositoryThrows() {
     TSM_ASSERT_THROWS(
         "Should throw with null repository.",
         MDHWInMemoryLoadingPresenter(
@@ -67,8 +61,7 @@ public:
         std::invalid_argument);
   }
 
-  void testConstructWithEmptyWsNameThrows()
-  {
+  void testConstructWithEmptyWsNameThrows() {
     std::string emptyName = "";
     TSM_ASSERT_THROWS("Should throw with empty Workspace name.",
                       MDHWInMemoryLoadingPresenter(
@@ -77,15 +70,13 @@ public:
                       std::invalid_argument);
   }
 
-  void testConstruction()
-  {
+  void testConstruction() {
     TS_ASSERT_THROWS_NOTHING(MDHWInMemoryLoadingPresenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_"));
   }
 
-  void testCanLoadWithInvalidName()
-  {
+  void testCanLoadWithInvalidName() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     EXPECT_CALL(*repository, canProvideWorkspace(_))
         .WillOnce(Return(
@@ -96,11 +87,12 @@ public:
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    TSM_ASSERT("Should indicate that the workspace cannot be read-out since the name is not in the Repository.", !presenter.canReadFile());
+    TSM_ASSERT("Should indicate that the workspace cannot be read-out since "
+               "the name is not in the Repository.",
+               !presenter.canReadFile());
   }
 
-  void testCanLoadWithWrongWsType()
-  {
+  void testCanLoadWithWrongWsType() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr badWs =
         getBadWorkspace(); // Not an IMDHistoWorkspace.
@@ -114,14 +106,17 @@ public:
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    TSM_ASSERT("Should indicate that the workspace cannot be read-out since it is not of the right type.", !presenter.canReadFile());
+    TSM_ASSERT("Should indicate that the workspace cannot be read-out since it "
+               "is not of the right type.",
+               !presenter.canReadFile());
   }
 
-  void testCanLoadSucceeds()
-  {
+  void testCanLoadSucceeds() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr goodWs = getGoodWorkspace();
-    EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true.
+    EXPECT_CALL(*repository, canProvideWorkspace(_))
+        .WillOnce(
+            Return(true)); // No matter what the argument, always returns true.
     EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs));
 
     // Give a dummy name corresponding to the workspace.
@@ -129,36 +124,43 @@ public:
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    TSM_ASSERT("Should have worked! Workspace is of correct type and repository says ws is present.!", presenter.canReadFile());
+    TSM_ASSERT("Should have worked! Workspace is of correct type and "
+               "repository says ws is present.!",
+               presenter.canReadFile());
   }
 
-  void testExtractMetadata()
-  {
+  void testExtractMetadata() {
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr ws = getGoodWorkspace();
-    EXPECT_CALL(*repository, fetchWorkspace(_)).Times(1).WillRepeatedly(Return(ws));
+    EXPECT_CALL(*repository, fetchWorkspace(_))
+        .Times(1)
+        .WillRepeatedly(Return(ws));
 
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(),
         "_");
 
-    //Test that it doesn't work when not setup.
-    TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should throw if not run first.", presenter.getGeometryXML(), std::runtime_error);
-    
-    //Test that it does work when setup.
+    // Test that it doesn't work when not setup.
+    TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should "
+                      "throw if not run first.",
+                      presenter.getGeometryXML(), std::runtime_error);
+
+    // Test that it does work when setup.
     presenter.executeLoadMetadata();
 
     std::string ins = presenter.getInstrument();
 
-    TSM_ASSERT("Should export geometry xml metadata on request.", !presenter.getGeometryXML().empty())
-    TSM_ASSERT("Should export min value metadata on request.", presenter.getMinValue() <= presenter.getMaxValue())
-    TSM_ASSERT("Should export instrument metadata on request", presenter.getInstrument().empty())
+    TSM_ASSERT("Should export geometry xml metadata on request.",
+               !presenter.getGeometryXML().empty())
+    TSM_ASSERT("Should export min value metadata on request.",
+               presenter.getMinValue() <= presenter.getMaxValue())
+    TSM_ASSERT("Should export instrument metadata on request",
+               presenter.getInstrument().empty())
   }
 
-  void testExecution()
-  {
+  void testExecution() {
 
-    //Setup view
+    // Setup view
     std::unique_ptr<MDLoadingView> view =
         Mantid::Kernel::make_unique<MockMDLoadingView>();
     MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get());
@@ -167,7 +169,7 @@ public:
         .Times(0); // Not a question that needs asking for this presenter type.
     EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber());
 
-    //Setup rendering factory
+    // Setup rendering factory
     MockvtkDataSetFactory factory;
     EXPECT_CALL(factory, initialize(_)).Times(1);
     EXPECT_CALL(factory, create(_))
@@ -175,13 +177,15 @@ public:
 
     auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>();
     Mantid::API::Workspace_sptr ws = getGoodWorkspace();
-    EXPECT_CALL(*repository, fetchWorkspace(_)).Times(2).WillRepeatedly(Return(ws));
+    EXPECT_CALL(*repository, fetchWorkspace(_))
+        .Times(2)
+        .WillRepeatedly(Return(ws));
 
-    //Setup progress updates objects
+    // Setup progress updates objects
     MockProgressAction mockLoadingProgressAction;
     MockProgressAction mockDrawingProgressAction;
 
-    //Create the presenter and run it!
+    // Create the presenter and run it!
     MDHWInMemoryLoadingPresenter presenter(std::move(view),
                                            repository.release(), "_");
     presenter.executeLoadMetadata();
@@ -189,19 +193,22 @@ public:
                                      mockDrawingProgressAction);
 
     TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
-    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName()));
+    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid",
+                      std::string(product->GetClassName()));
     TSM_ASSERT("No field data!", NULL != product->GetFieldData());
-    TSM_ASSERT_EQUALS("Two arrays expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
+    TSM_ASSERT_EQUALS(
+        "Two arrays expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
     TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
     TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
     TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
-    TSM_ASSERT("Special coordinate metadata failed.", -1 < presenter.getSpecialCoordinates());
+    TSM_ASSERT("Special coordinate metadata failed.",
+               -1 < presenter.getSpecialCoordinates());
     TS_ASSERT(Mock::VerifyAndClearExpectations(mockView));
     TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
   }
 
-  void testCallHasTDimThrows()
-  {
+  void testCallHasTDimThrows() {
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -209,8 +216,7 @@ public:
                       presenter.hasTDimensionAvailable(), std::runtime_error);
   }
 
-  void testCallGetTDimensionValuesThrows()
-  {
+  void testCallGetTDimensionValuesThrows() {
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -218,8 +224,7 @@ public:
                       presenter.getTimeStepValues(), std::runtime_error);
   }
 
-  void testCallGetGeometryThrows()
-  {
+  void testCallGetGeometryThrows() {
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -227,8 +232,7 @@ public:
                       presenter.getGeometryXML(), std::runtime_error);
   }
 
-  void testGetWorkspaceTypeName()
-  {
+  void testGetWorkspaceTypeName() {
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
@@ -236,15 +240,13 @@ public:
                       presenter.getWorkspaceTypeName());
   }
 
-  void testGetSpecialCoordinates()
-  {
+  void testGetSpecialCoordinates() {
     MDHWInMemoryLoadingPresenter presenter(
         Mantid::Kernel::make_unique<MockMDLoadingView>(),
         new MockWorkspaceProvider, "_");
     TSM_ASSERT_EQUALS("Characterisation Test Failed", -1,
                       presenter.getSpecialCoordinates());
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h
index a2b0d975665cfffc035158d2fbc38363098e3822..0a249d713b61b7d0cec26e3d53e95b9f508e4512 100644
--- a/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h
@@ -1,5 +1,5 @@
 #ifndef MDHW_LOADING_PRESENTER_TEST_H_
-#define MDHW_LOADING_PRESENTER_TEST_H_ 
+#define MDHW_LOADING_PRESENTER_TEST_H_
 
 #include <cxxtest/TestSuite.h>
 #include <vtkUnstructuredGrid.h>
@@ -21,19 +21,18 @@ using namespace Mantid::API;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class MDHWLoadingPresenterTest : public CxxTest::TestSuite
-{
-
-private: 
+class MDHWLoadingPresenterTest : public CxxTest::TestSuite {
 
+private:
   /*
-  Helper class allows the behaviour of the abstract base type to be tested. Derives from target abstract class providing 
+  Helper class allows the behaviour of the abstract base type to be tested.
+  Derives from target abstract class providing
   dummy implemenations of pure virtual methods.
   */
-  class ConcreteMDHWLoadingPresenter : public MDHWLoadingPresenter
-  {
+  class ConcreteMDHWLoadingPresenter : public MDHWLoadingPresenter {
   private:
     typedef MDHWLoadingPresenter BaseClass;
+
   public:
     ConcreteMDHWLoadingPresenter(std::unique_ptr<MDLoadingView> view)
         : MDHWLoadingPresenter(std::move(view)) {}
@@ -53,158 +52,158 @@ private:
     bool canReadFile() const override { return true; }
 
     bool shouldLoad() override {
-      //Forwarding method
+      // Forwarding method
       return BaseClass::shouldLoad();
     }
 
     ~ConcreteMDHWLoadingPresenter() override {}
   };
 
-
 public:
-
-void testShouldLoadFirstTimeRound()
-{
-  auto view = new MockMDLoadingView();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(0);
-  EXPECT_CALL(*view, getLoadInMemory()).Times(2);
-  EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0));
-  EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
-
-  std::unique_ptr<MDLoadingView> uniqueView(
-      dynamic_cast<MDLoadingView *>(view));
-  ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Should NOT request load on second usage. Should have it's state syncrhonised with view and the view hasn't changed!", !presenter.shouldLoad());
-  
-  TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(view));
-}
-
-void testTimeChanged()
-{
-  auto view = new MockMDLoadingView();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(0);
-  EXPECT_CALL(*view, getLoadInMemory()).Times(2);
-  EXPECT_CALL(*view, getTime())
-      .Times(2)
-      .WillOnce(Return(0))
-      .WillOnce(Return(1)); // Time has changed on 2nd call
-  EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
-
-  std::unique_ptr<MDLoadingView> uniqueView(
-      dynamic_cast<MDLoadingView *>(view));
-  ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Time has changed, but that shouldn't trigger load",
-             !presenter.shouldLoad());
-
-  TSM_ASSERT("View not used as expected.",
-             Mock::VerifyAndClearExpectations(view));
-}
-
-void testLoadInMemoryChanged()
-{
-  auto view = new MockMDLoadingView();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(0);
-  EXPECT_CALL(*view, getLoadInMemory())
-      .Times(2)
-      .WillOnce(Return(true))
-      .WillOnce(Return(false)); // Load in memory changed
-  EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0));
-  EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
-
-  std::unique_ptr<MDLoadingView> uniqueView(
-      dynamic_cast<MDLoadingView *>(view));
-  ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
-  TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
-  TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load",
-             presenter.shouldLoad());
-
-  TSM_ASSERT("View not used as expected.",
-             Mock::VerifyAndClearExpectations(view));
-}
-
-void testhasTDimensionWhenIntegrated()
-{
-  ConcreteMDHWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
-
-  //Test that it does work when setup.
-  Mantid::API::Workspace_sptr ws = get3DWorkspace(true, false); //Integrated T Dimension
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
-
-  TSM_ASSERT("This is a 4D workspace with an integrated T dimension", !presenter.hasTDimensionAvailable());
-}
-
-void testHasTDimensionWhenNotIntegrated()
-{
-  ConcreteMDHWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
-
-  //Test that it does work when setup. 
-  Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false); //Non-integrated T Dimension
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
-
-  TSM_ASSERT("This is a 4D workspace with an integrated T dimension", presenter.hasTDimensionAvailable());
-}
-
-void testHasTimeLabelWithTDimension()
-{
-  ConcreteMDHWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
-
-  //Test that it does work when setup.
-  Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false); //Non-integrated T Dimension
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
-
-  TSM_ASSERT_EQUALS("This is a 4D workspace with a T dimension", "D (A)", presenter.getTimeStepLabel());
-}
-
-void testCanSetAxisLabelsFrom3DData()
-{
-  ConcreteMDHWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
-
-  //Test that it does work when setup.
-  Mantid::API::Workspace_sptr ws = get3DWorkspace(true, false);
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
-  vtkDataSet *ds = vtkUnstructuredGrid::New();
-  TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds));
-  TSM_ASSERT_EQUALS("X Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)");
-  TSM_ASSERT_EQUALS("Y Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForY"), "B ($A$)");
-  TSM_ASSERT_EQUALS("Z Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
-}
-
-void testCanSetAxisLabelsFrom4DData()
-{
-  ConcreteMDHWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
-
-  //Test that it does work when setup.
-  Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false);
-  presenter.extractMetadata(
-      *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
-  vtkDataSet *ds = vtkUnstructuredGrid::New();
-  TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds));
-  TSM_ASSERT_EQUALS("X Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)");
-  TSM_ASSERT_EQUALS("Y Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForY"), "B ($A$)");
-  TSM_ASSERT_EQUALS("Z Label should match exactly",
-                    getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
-
-}
-
-Mantid::API::IMDHistoWorkspace_sptr makeHistoWorkspace(const std::vector<int> &shape){
-
-    IAlgorithm* create = FrameworkManager::Instance().createAlgorithm("CreateMDHistoWorkspace");
+  void testShouldLoadFirstTimeRound() {
+    auto view = new MockMDLoadingView();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(0);
+    EXPECT_CALL(*view, getLoadInMemory()).Times(2);
+    EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0));
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
+
+    std::unique_ptr<MDLoadingView> uniqueView(
+        dynamic_cast<MDLoadingView *>(view));
+    ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Should NOT request load on second usage. Should have it's "
+               "state syncrhonised with view and the view hasn't changed!",
+               !presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(view));
+  }
+
+  void testTimeChanged() {
+    auto view = new MockMDLoadingView();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(0);
+    EXPECT_CALL(*view, getLoadInMemory()).Times(2);
+    EXPECT_CALL(*view, getTime())
+        .Times(2)
+        .WillOnce(Return(0))
+        .WillOnce(Return(1)); // Time has changed on 2nd call
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
+
+    std::unique_ptr<MDLoadingView> uniqueView(
+        dynamic_cast<MDLoadingView *>(view));
+    ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Time has changed, but that shouldn't trigger load",
+               !presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(view));
+  }
+
+  void testLoadInMemoryChanged() {
+    auto view = new MockMDLoadingView();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(0);
+    EXPECT_CALL(*view, getLoadInMemory())
+        .Times(2)
+        .WillOnce(Return(true))
+        .WillOnce(Return(false)); // Load in memory changed
+    EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0));
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0);
+
+    std::unique_ptr<MDLoadingView> uniqueView(
+        dynamic_cast<MDLoadingView *>(view));
+    ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView));
+    TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad());
+    TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load",
+               presenter.shouldLoad());
+
+    TSM_ASSERT("View not used as expected.",
+               Mock::VerifyAndClearExpectations(view));
+  }
+
+  void testhasTDimensionWhenIntegrated() {
+    ConcreteMDHWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
+
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(true, false); // Integrated T Dimension
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
+
+    TSM_ASSERT("This is a 4D workspace with an integrated T dimension",
+               !presenter.hasTDimensionAvailable());
+  }
+
+  void testHasTDimensionWhenNotIntegrated() {
+    ConcreteMDHWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
+
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(false, false); // Non-integrated T Dimension
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
+
+    TSM_ASSERT("This is a 4D workspace with an integrated T dimension",
+               presenter.hasTDimensionAvailable());
+  }
+
+  void testHasTimeLabelWithTDimension() {
+    ConcreteMDHWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
+
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws =
+        get3DWorkspace(false, false); // Non-integrated T Dimension
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
+
+    TSM_ASSERT_EQUALS("This is a 4D workspace with a T dimension", "D (A)",
+                      presenter.getTimeStepLabel());
+  }
+
+  void testCanSetAxisLabelsFrom3DData() {
+    ConcreteMDHWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
+
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws = get3DWorkspace(true, false);
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
+    vtkDataSet *ds = vtkUnstructuredGrid::New();
+    TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds));
+    TSM_ASSERT_EQUALS("X Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)");
+    TSM_ASSERT_EQUALS("Y Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForY"), "B ($A$)");
+    TSM_ASSERT_EQUALS("Z Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
+  }
+
+  void testCanSetAxisLabelsFrom4DData() {
+    ConcreteMDHWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>());
+
+    // Test that it does work when setup.
+    Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false);
+    presenter.extractMetadata(
+        *boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws));
+    vtkDataSet *ds = vtkUnstructuredGrid::New();
+    TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds));
+    TSM_ASSERT_EQUALS("X Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)");
+    TSM_ASSERT_EQUALS("Y Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForY"), "B ($A$)");
+    TSM_ASSERT_EQUALS("Z Label should match exactly",
+                      getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)");
+  }
+
+  Mantid::API::IMDHistoWorkspace_sptr
+  makeHistoWorkspace(const std::vector<int> &shape) {
+
+    IAlgorithm *create =
+        FrameworkManager::Instance().createAlgorithm("CreateMDHistoWorkspace");
     create->setChild(true);
     create->initialize();
 
@@ -215,19 +214,19 @@ Mantid::API::IMDHistoWorkspace_sptr makeHistoWorkspace(const std::vector<int> &s
     std::vector<std::string> units;
     size_t flatSize = 1;
     std::vector<double> extents;
-    for(size_t i = 0; i < shape.size(); ++i){
-        flatSize *= shape[i];
-        names.push_back(allNames[i]);
-        units.push_back(allUnits[i]);
-        extents.push_back(-10);
-        extents.push_back(10);
+    for (size_t i = 0; i < shape.size(); ++i) {
+      flatSize *= shape[i];
+      names.push_back(allNames[i]);
+      units.push_back(allUnits[i]);
+      extents.push_back(-10);
+      extents.push_back(10);
     }
 
     create->setProperty("SignalInput", std::vector<double>(flatSize, 1));
     create->setProperty("ErrorInput", std::vector<double>(flatSize, 1));
 
     create->setProperty("Dimensionality", int(shape.size()));
-    create->setProperty("Extents",extents);
+    create->setProperty("Extents", extents);
     create->setProperty("NumberOfBins", shape);
     create->setProperty("Names", names);
     create->setProperty("Units", units);
@@ -235,13 +234,14 @@ Mantid::API::IMDHistoWorkspace_sptr makeHistoWorkspace(const std::vector<int> &s
     create->execute();
     IMDHistoWorkspace_sptr outWs = create->getProperty("OutputWorkspace");
     return outWs;
-}
+  }
 
-void test_transpose_not_needed(){
+  void test_transpose_not_needed() {
 
-    //return outWs;
-    int shape[4] = {10, 10, 1}; // Well behaved input workspace. Integrated dim at end.
-    std::vector<int> shapeVec(shape, shape+3);
+    // return outWs;
+    int shape[4] = {10, 10,
+                    1}; // Well behaved input workspace. Integrated dim at end.
+    std::vector<int> shapeVec(shape, shape + 3);
     auto inWs = makeHistoWorkspace(shapeVec);
 
     IMDHistoWorkspace_sptr targetWs;
@@ -249,16 +249,20 @@ void test_transpose_not_needed(){
 
     TS_ASSERT_EQUALS(targetWs->getNumDims(), inWs->getNumDims());
     TS_ASSERT_EQUALS(targetWs->getNPoints(), inWs->getNPoints())
-    TS_ASSERT_EQUALS(targetWs->getDimension(0)->getName(), inWs->getDimension(0)->getName());
-    TS_ASSERT_EQUALS(targetWs->getDimension(1)->getName(), inWs->getDimension(1)->getName());
-    TS_ASSERT_EQUALS(targetWs->getDimension(2)->getName(), inWs->getDimension(2)->getName());
-}
-
-void test_transpose_rules_applied(){
-
-    //return outWs;
-    int shape[4] = {10, 10, 1, 10}; // Inproper input workspace. Needs transpose!
-    std::vector<int> shapeVec(shape, shape+4);
+    TS_ASSERT_EQUALS(targetWs->getDimension(0)->getName(),
+                     inWs->getDimension(0)->getName());
+    TS_ASSERT_EQUALS(targetWs->getDimension(1)->getName(),
+                     inWs->getDimension(1)->getName());
+    TS_ASSERT_EQUALS(targetWs->getDimension(2)->getName(),
+                     inWs->getDimension(2)->getName());
+  }
+
+  void test_transpose_rules_applied() {
+
+    // return outWs;
+    int shape[4] = {10, 10, 1,
+                    10}; // Inproper input workspace. Needs transpose!
+    std::vector<int> shapeVec(shape, shape + 4);
     auto inWs = makeHistoWorkspace(shapeVec);
 
     IMDHistoWorkspace_sptr targetWs;
@@ -266,12 +270,17 @@ void test_transpose_rules_applied(){
 
     TS_ASSERT_EQUALS(targetWs->getNumDims(), inWs->getNumDims());
     TS_ASSERT_EQUALS(targetWs->getNPoints(), inWs->getNPoints())
-    TS_ASSERT_EQUALS(targetWs->getDimension(0)->getName(), inWs->getDimension(0)->getName());
-    TS_ASSERT_EQUALS(targetWs->getDimension(1)->getName(), inWs->getDimension(1)->getName());
-    TSM_ASSERT_EQUALS("Integrated dims should be shifted to end", targetWs->getDimension(2)->getName(), inWs->getDimension(3)->getName());
-    TSM_ASSERT_EQUALS("Integrated dims on the end", targetWs->getDimension(3)->getName(), inWs->getDimension(2)->getName());
-}
-
+    TS_ASSERT_EQUALS(targetWs->getDimension(0)->getName(),
+                     inWs->getDimension(0)->getName());
+    TS_ASSERT_EQUALS(targetWs->getDimension(1)->getName(),
+                     inWs->getDimension(1)->getName());
+    TSM_ASSERT_EQUALS("Integrated dims should be shifted to end",
+                      targetWs->getDimension(2)->getName(),
+                      inWs->getDimension(3)->getName());
+    TSM_ASSERT_EQUALS("Integrated dims on the end",
+                      targetWs->getDimension(3)->getName(),
+                      inWs->getDimension(2)->getName());
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h
index 3b8486e5ecb5b0d434f00f89432a3d3896b90ed7..ab9ef3990b77d0b582fe26780e484592d029b60e 100644
--- a/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h
@@ -78,7 +78,7 @@ private:
     MDHWNexusLoadingPresenter presenter(std::move(view), filename);
     presenter.executeLoadMetadata();
     auto product = presenter.execute(&factory, mockLoadingProgressAction,
-                                            mockDrawingProgressAction);
+                                     mockDrawingProgressAction);
 
     TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
     if (performAsserts) {
@@ -179,7 +179,8 @@ public:
 
     // Set the COB
     try {
-      auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+      auto workspaceProvider = Mantid::Kernel::make_unique<
+          ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
       presenter.makeNonOrthogonal(product, std::move(workspaceProvider));
     } catch (...) {
       // Add the standard change of basis matrix and set the boundaries
diff --git a/Vates/VatesAPI/test/MDLoadingPresenterTest.h b/Vates/VatesAPI/test/MDLoadingPresenterTest.h
index ba679032e5a8e5637e540e01fe5d6e596c53b9f8..76cbef910491790f390453b01c1fa64132084d41 100644
--- a/Vates/VatesAPI/test/MDLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/MDLoadingPresenterTest.h
@@ -8,7 +8,6 @@
 #include "MantidVatesAPI/vtkDataSetFactory.h"
 #include "MantidVatesAPI/vtkMDHexFactory.h"
 
-
 #include <cxxtest/TestSuite.h>
 #include "MockObjects.h"
 #include "vtkPVChangeOfBasisHelper.h"
@@ -21,12 +20,12 @@ using namespace Mantid::DataObjects;
 using namespace Mantid::VATES;
 
 namespace {
-  std::string MOCK_GEOMETRY_XML_MD_LOADING_PRESENTER = "geometry";
-  std::string MOCK_INSTRUMENT_MD_LOADING_PRESENTER = "instrument";
+std::string MOCK_GEOMETRY_XML_MD_LOADING_PRESENTER = "geometry";
+std::string MOCK_INSTRUMENT_MD_LOADING_PRESENTER = "instrument";
 
 class MOCKMDLoadingPresenter : public Mantid::VATES::MDLoadingPresenter {
 public:
-  MOCKMDLoadingPresenter(){}
+  MOCKMDLoadingPresenter() {}
   ~MOCKMDLoadingPresenter() override {}
   vtkSmartPointer<vtkDataSet>
   execute(Mantid::VATES::vtkDataSetFactory *, Mantid::VATES::ProgressAction &,
@@ -50,20 +49,20 @@ public:
 };
 }
 
-
 class MDLoadingPresenterTest : public CxxTest::TestSuite {
 private:
   vtkSmartPointer<vtkUnstructuredGrid> makeDataSet() {
     FakeProgressAction progressUpdate;
     MDEventWorkspace3Lean::sptr ws =
         MDEventsTestHelper::makeMDEW<3>(8, -10.0, 10.0, 1);
-    Mantid::VATES::vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange),
-                            VolumeNormalization);
+    Mantid::VATES::vtkMDHexFactory factory(
+        ThresholdRange_scptr(new NoThresholdRange), VolumeNormalization);
     factory.initialize(ws);
     auto dataset = factory.create(progressUpdate);
     auto grid = vtkUnstructuredGrid::SafeDownCast(dataset.Get());
     return vtkSmartPointer<vtkUnstructuredGrid>(grid);
   }
+
 public:
   void test_that_non_default_cob_is_created() {
     // Arrange
diff --git a/Vates/VatesAPI/test/MDLoadingViewAdapterTest.h b/Vates/VatesAPI/test/MDLoadingViewAdapterTest.h
index 6f706d755a7684833bd907042e0cdb53ce25ef8b..1d34d59a93fd9c0fa8f376c288e28c517b494c8c 100644
--- a/Vates/VatesAPI/test/MDLoadingViewAdapterTest.h
+++ b/Vates/VatesAPI/test/MDLoadingViewAdapterTest.h
@@ -5,38 +5,36 @@
 
 #include <cxxtest/TestSuite.h>
 #include <gmock/gmock.h>
-#include <gtest/gtest.h> 
+#include <gtest/gtest.h>
 #include "MockObjects.h"
 
 using namespace Mantid::VATES;
 using namespace testing;
 
-class MDLoadingViewAdapterTest : public CxxTest::TestSuite
-{
+class MDLoadingViewAdapterTest : public CxxTest::TestSuite {
 
 public:
-  
-  void testWireUp()
-  {
-    //Set expectations on adaptee
+  void testWireUp() {
+    // Set expectations on adaptee
     MockMDLoadingView view;
     EXPECT_CALL(view, getTime()).Times(1);
     EXPECT_CALL(view, getRecursionDepth()).Times(1);
     EXPECT_CALL(view, getLoadInMemory()).Times(1);
 
-    //Create adapter using adaptee
+    // Create adapter using adaptee
     MDLoadingViewAdapter<MockMDLoadingView> view_adapter(&view);
 
-    //Use an alias to ensure that adapting to the right type.
-    MDLoadingView& alias = view_adapter;
-    
-    //Test running adaptees invokes expecations and exits cleanly
+    // Use an alias to ensure that adapting to the right type.
+    MDLoadingView &alias = view_adapter;
+
+    // Test running adaptees invokes expecations and exits cleanly
     TS_ASSERT_THROWS_NOTHING(alias.getTime());
     TS_ASSERT_THROWS_NOTHING(alias.getRecursionDepth());
     TS_ASSERT_THROWS_NOTHING(alias.getLoadInMemory());
 
-    //Check the expectations.
-    TSM_ASSERT("Not wired-up correctly", Mock::VerifyAndClearExpectations(&view));
+    // Check the expectations.
+    TSM_ASSERT("Not wired-up correctly",
+               Mock::VerifyAndClearExpectations(&view));
   }
 };
 
diff --git a/Vates/VatesAPI/test/MDLoadingViewSimpleTest.h b/Vates/VatesAPI/test/MDLoadingViewSimpleTest.h
index 60b5ba55d4e08c45cc7e70e0c450fda8fed7824e..b9a54af286926d6bed7b4f07da68fcc1257f085d 100644
--- a/Vates/VatesAPI/test/MDLoadingViewSimpleTest.h
+++ b/Vates/VatesAPI/test/MDLoadingViewSimpleTest.h
@@ -7,17 +7,18 @@
 
 using namespace Mantid::VATES;
 
-class MDLoadingViewSimpleTest : public CxxTest::TestSuite
-{
+class MDLoadingViewSimpleTest : public CxxTest::TestSuite {
 
 public:
-
   void test_that_defaults_are_returned() {
     MDLoadingViewSimple view;
 
-    TSM_ASSERT_EQUALS("Should have a time of 0.0 by default", view.getTime(), 0.0);
-    TSM_ASSERT_EQUALS("Should have a recursion depth of 5 by default", view.getRecursionDepth(), 5);
-    TSM_ASSERT_EQUALS("Should be set to loadingInMemory to true", view.getLoadInMemory(), true);
+    TSM_ASSERT_EQUALS("Should have a time of 0.0 by default", view.getTime(),
+                      0.0);
+    TSM_ASSERT_EQUALS("Should have a recursion depth of 5 by default",
+                      view.getRecursionDepth(), 5);
+    TSM_ASSERT_EQUALS("Should be set to loadingInMemory to true",
+                      view.getLoadInMemory(), true);
   }
 
   void test_that_settings_are_correctly_stored() {
@@ -32,8 +33,10 @@ public:
 
     // Act + Assert
     TSM_ASSERT_EQUALS("Should have a time of 1.0", view.getTime(), time);
-    TSM_ASSERT_EQUALS("Should have a recursion depth of 7", view.getRecursionDepth(), recursionDepth);
-    TSM_ASSERT_EQUALS("Should be set to loadingInMemory to false", view.getLoadInMemory(), loadingInMemory);
+    TSM_ASSERT_EQUALS("Should have a recursion depth of 7",
+                      view.getRecursionDepth(), recursionDepth);
+    TSM_ASSERT_EQUALS("Should be set to loadingInMemory to false",
+                      view.getLoadInMemory(), loadingInMemory);
   }
 };
 
diff --git a/Vates/VatesAPI/test/MedianAndBelowThresholdRangeTest.h b/Vates/VatesAPI/test/MedianAndBelowThresholdRangeTest.h
index f3a381e549340d65ff970cbff42cd9b4f9321a19..c7e651c04cf77352d86c3a2a0210b64f354b2ff4 100644
--- a/Vates/VatesAPI/test/MedianAndBelowThresholdRangeTest.h
+++ b/Vates/VatesAPI/test/MedianAndBelowThresholdRangeTest.h
@@ -17,41 +17,40 @@ using namespace testing;
 // Functional tests
 //=====================================================================================
 
-class MedianAndBelowThresholdRangeTest: public CxxTest::TestSuite
-{
+class MedianAndBelowThresholdRangeTest : public CxxTest::TestSuite {
 private:
-
   // Fake workspace
   MDHistoWorkspace_sptr sptrWs;
 
-public :
+public:
   void setUp() override {
     // Fake workspace with 8 cells
     sptrWs = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1, 8, 8.0);
-    //Set up a standard set of values for subsequent tests. Note that the following set gives a standard deviation of +/-2
-    sptrWs->setSignalAt(0,-1.0);
-    sptrWs->setSignalAt(1,2);
-    sptrWs->setSignalAt(2,2);
-    sptrWs->setSignalAt(3,3);
-    sptrWs->setSignalAt(4,4);
-    sptrWs->setSignalAt(5,5);
-    sptrWs->setSignalAt(6,6);
-    sptrWs->setSignalAt(7,7);
+    // Set up a standard set of values for subsequent tests. Note that the
+    // following set gives a standard deviation of +/-2
+    sptrWs->setSignalAt(0, -1.0);
+    sptrWs->setSignalAt(1, 2);
+    sptrWs->setSignalAt(2, 2);
+    sptrWs->setSignalAt(3, 3);
+    sptrWs->setSignalAt(4, 4);
+    sptrWs->setSignalAt(5, 5);
+    sptrWs->setSignalAt(6, 6);
+    sptrWs->setSignalAt(7, 7);
   }
 
-  void testMedianCalculation()
-  {
+  void testMedianCalculation() {
     Mantid::VATES::MedianAndBelowThresholdRange medianCalculator;
     medianCalculator.setWorkspace(sptrWs);
     medianCalculator.calculate();
     //-1 + 2 + 2 + 3 + 4 + 5 + 6 + 7 / 8 = 3.5
 
-    TSM_ASSERT_EQUALS("Wrong maximum value.", 3.5, medianCalculator.getMaximum());
-    TSM_ASSERT_EQUALS("Wrong minimum value.", -1, medianCalculator.getMinimum());
+    TSM_ASSERT_EQUALS("Wrong maximum value.", 3.5,
+                      medianCalculator.getMaximum());
+    TSM_ASSERT_EQUALS("Wrong minimum value.", -1,
+                      medianCalculator.getMinimum());
   }
 
-  void testInRange()
-  {
+  void testInRange() {
     Mantid::VATES::MedianAndBelowThresholdRange medianCalculator;
     medianCalculator.setWorkspace(sptrWs);
     medianCalculator.calculate();
@@ -60,7 +59,6 @@ public :
     TS_ASSERT_EQUALS(true, medianCalculator.inRange(3.499));
     TS_ASSERT_EQUALS(false, medianCalculator.inRange(3.501));
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MetaDataExtractorUtilsTest.h b/Vates/VatesAPI/test/MetaDataExtractorUtilsTest.h
index 644d2b2bcebed97d8e37f4f4ce0d7aef7c8eed54..75873feba4d1cb9ad138e374097894db68866eb1 100644
--- a/Vates/VatesAPI/test/MetaDataExtractorUtilsTest.h
+++ b/Vates/VatesAPI/test/MetaDataExtractorUtilsTest.h
@@ -7,12 +7,11 @@
 #pragma warning(disable : 4251)
 #endif
 
-
 #include "MantidVatesAPI/MetaDataExtractorUtils.h"
 
 #include <cxxtest/TestSuite.h>
 #include <gmock/gmock.h>
-#include <gtest/gtest.h> 
+#include <gtest/gtest.h>
 #include "MockObjects.h"
 
 #include <qwt_double_interval.h>
@@ -27,67 +26,70 @@ using namespace Mantid::API;
 using namespace testing;
 using Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace;
 
-class MetaDataExtractorUtilsTest : public CxxTest::TestSuite
-{
-
-  public:
-
-    // Helper method. Generates and returns a valid IMDEventWorkspace
-    static Mantid::API::Workspace_sptr getReal4DWorkspace()
-    {
-      AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
-      IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");	
-      alg->initialize();
-      alg->setRethrows(true);
-      alg->setPropertyValue("Filename", Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs"));
-      alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
-      alg->setProperty("FileBackEnd", false); 
-      alg->execute(); 
-      return AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
-    }
-
-    void testShouldExtractMinAndMaxFromWorkspaceForMDHisto()
-    {
-      // Arrange
-      Mantid::DataObjects::MDHistoWorkspace_sptr histoWorkspace = makeFakeMDHistoWorkspace(1.0, 4);
-
-      // Act
-      MetaDataExtractorUtils extractor;
-      QwtDoubleInterval minMax = extractor.getMinAndMax(histoWorkspace);
-
-      // Assert
-      TSM_ASSERT("Should find the a min which is smaller/equal to max ", minMax.minValue() <= minMax.maxValue())
-    }
-
-    void testShouldExtractMinAndMaxFromWorkspaceForMDEvent()
-    {
-      // Arrange
-      Mantid::API::Workspace_sptr workspace = getReal4DWorkspace();
-      Mantid::API::IMDEventWorkspace_sptr eventWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
-      MetaDataExtractorUtils extractor;
-      
-      // Act
-      QwtDoubleInterval minMax = extractor.getMinAndMax(eventWorkspace);
-
-      // Assert
-      TSM_ASSERT("Should find the a min which is smaller/equal to max ", minMax.minValue() <= minMax.maxValue())
-    }
-
-    void testShouldNotFindInstrumentForBadWorkspace()
-    {
-      // Arrange
-      // Return a table workspace.
-      Mantid::API::Workspace_sptr workspace = WorkspaceFactory::Instance().createTable();
-      Mantid::API::IMDHistoWorkspace_sptr histoWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
-
-      MetaDataExtractorUtils extractor;
-
-      // Act
-      std::string instrument = extractor.extractInstrument(histoWorkspace);
-
-      // Assert
-      TSM_ASSERT("Should find an empty instrment for invalid workspace", instrument.empty())
-    }
+class MetaDataExtractorUtilsTest : public CxxTest::TestSuite {
+
+public:
+  // Helper method. Generates and returns a valid IMDEventWorkspace
+  static Mantid::API::Workspace_sptr getReal4DWorkspace() {
+    AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");
+    IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD");
+    alg->initialize();
+    alg->setRethrows(true);
+    alg->setPropertyValue(
+        "Filename",
+        Mantid::API::FileFinder::Instance().getFullPath("MAPS_MDEW.nxs"));
+    alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID");
+    alg->setProperty("FileBackEnd", false);
+    alg->execute();
+    return AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
+  }
+
+  void testShouldExtractMinAndMaxFromWorkspaceForMDHisto() {
+    // Arrange
+    Mantid::DataObjects::MDHistoWorkspace_sptr histoWorkspace =
+        makeFakeMDHistoWorkspace(1.0, 4);
+
+    // Act
+    MetaDataExtractorUtils extractor;
+    QwtDoubleInterval minMax = extractor.getMinAndMax(histoWorkspace);
+
+    // Assert
+    TSM_ASSERT("Should find the a min which is smaller/equal to max ",
+               minMax.minValue() <= minMax.maxValue())
+  }
+
+  void testShouldExtractMinAndMaxFromWorkspaceForMDEvent() {
+    // Arrange
+    Mantid::API::Workspace_sptr workspace = getReal4DWorkspace();
+    Mantid::API::IMDEventWorkspace_sptr eventWorkspace =
+        boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
+    MetaDataExtractorUtils extractor;
+
+    // Act
+    QwtDoubleInterval minMax = extractor.getMinAndMax(eventWorkspace);
+
+    // Assert
+    TSM_ASSERT("Should find the a min which is smaller/equal to max ",
+               minMax.minValue() <= minMax.maxValue())
+  }
+
+  void testShouldNotFindInstrumentForBadWorkspace() {
+    // Arrange
+    // Return a table workspace.
+    Mantid::API::Workspace_sptr workspace =
+        WorkspaceFactory::Instance().createTable();
+    Mantid::API::IMDHistoWorkspace_sptr histoWorkspace =
+        boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
+
+    MetaDataExtractorUtils extractor;
+
+    // Act
+    std::string instrument = extractor.extractInstrument(histoWorkspace);
+
+    // Assert
+    TSM_ASSERT("Should find an empty instrment for invalid workspace",
+               instrument.empty())
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/MetadataJsonManagerTest.h b/Vates/VatesAPI/test/MetadataJsonManagerTest.h
index 91793021e9d3965a677175c2c8a16f00852e916a..67f3f7c84b4320ea6a615f8046db31a53ee41194 100644
--- a/Vates/VatesAPI/test/MetadataJsonManagerTest.h
+++ b/Vates/VatesAPI/test/MetadataJsonManagerTest.h
@@ -7,110 +7,123 @@
 #pragma warning(disable : 4251)
 #endif
 
-
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/MetadataJsonManager.h"
 #include <string>
 #include <json/reader.h>
 
-
 using Mantid::VATES::MetadataJsonManager;
 
-class MetadataJsonManagerTest: public CxxTest::TestSuite
-{
-  public:
-    
-    void testDefaultValuesAreReturnedWhenContainerIsNotSet()
-    {
-      // Arrange
-      MetadataJsonManager manager;
-
-      // Act
-      std::string instrument = manager.getInstrument();
-      double minValue = manager.getMinValue();
-      double maxValue = manager.getMaxValue();
-
-      // Assert
-      double expectedMinValue = 0.0;
-      double expectedMaxValue = 1.0;
-      std::string expectedInstrument("_EMPTY_");
-      
-      TSM_ASSERT("The instrument string is empty, since it does not exist.", expectedInstrument == instrument);
-      TSM_ASSERT_EQUALS("The min default value is 0.0.", expectedMinValue, minValue);
-      TSM_ASSERT_EQUALS("The max default value is 1.0.", expectedMaxValue, maxValue);
-    }
-
-    void testSetValuesCanBeReadOut()
-    {
-      // Arrange
-      MetadataJsonManager manager;
-
-      std::string instrument = "OSIRIS";
-      double minValue = 123.0;
-      double maxValue = 124234.3;
-
-      // Act
-      manager.setInstrument(instrument);
-      manager.setMinValue(minValue);
-      manager.setMaxValue(maxValue);
- 
-      // Assert
-      TSM_ASSERT_EQUALS("The instrument is read in and out.", instrument, manager.getInstrument());
-      TSM_ASSERT_EQUALS("The min value is read in and out.", minValue, manager.getMinValue());
-      TSM_ASSERT_EQUALS("The max value is read in and out.", maxValue, manager.getMaxValue());
-    }
-
-    void testJsonStringIsReadInAndPopualtesContainer()
-    {
-      // Arrange
-      MetadataJsonManager manager;
-      std::string jsonString = "{\"instrument\": \"OSIRIS\", \"minValue\":1.0, \"maxValue\": 2.0}";
-
-      // Act 
-      manager.readInSerializedJson(jsonString);
-
-      // Assert
-
-      TSM_ASSERT("The instrument of the serialized Json string is detected.", manager.getInstrument() == "OSIRIS");
-      TSM_ASSERT_EQUALS("The min value of the serialized Json string is detected.", 1.0, manager.getMinValue());
-      TSM_ASSERT_EQUALS("The max value of the serialized Json string is detected.", 2.0, manager.getMaxValue());
-    }
-
-    void testJsonStringWhichDoesNotHaveFieldsProducesDefaultValues()
-    {
-      // Arrange
-      MetadataJsonManager manager;
-      std::string jsonString = "{\"myInstrument\": \"OSIRIS\", \"myMinValue\":1.0, \"myMaxValue\": 2.0}";
-
-      // Act 
-      manager.readInSerializedJson(jsonString);
-
-      // Assert
-      std::string expectedInstrument ="_EMPTY_";
-      TSM_ASSERT("The json object does not find the instrument field and returns default.", manager.getInstrument() == expectedInstrument);
-      TSM_ASSERT_EQUALS("The json object does not find the max value field and returns default.", 0.0, manager.getMinValue());
-      TSM_ASSERT_EQUALS("The json object does not find the min value field and returns default.", 1.0, manager.getMaxValue());
-    }
-
-    void testCorrectJsonStringIsProduced()
-    {
-      // Arrange
-      MetadataJsonManager manager;
-      manager.setInstrument("OSIRIS");
-      manager.setMaxValue(3.0);
-      manager.setMinValue(2.0);
-
-      // Act
-      std::string jsonString = manager.getSerializedJson();
-      Json::Reader reader;
-      Json::Value container;
-      reader.parse(jsonString, container, false);
-
-      // Assert
-      TSM_ASSERT("Json string is being produced", !jsonString.empty());
-      TSM_ASSERT_EQUALS("Json string contains inserted instrument.", "OSIRIS", container["instrument"].asString());
-      TSM_ASSERT_EQUALS("Json string contains inserted min value.", 2.0, container["minValue"].asDouble());
-      TSM_ASSERT_EQUALS("Json string containns inserted max value.", 3.0, container["maxValue"].asDouble());
-    }
+class MetadataJsonManagerTest : public CxxTest::TestSuite {
+public:
+  void testDefaultValuesAreReturnedWhenContainerIsNotSet() {
+    // Arrange
+    MetadataJsonManager manager;
+
+    // Act
+    std::string instrument = manager.getInstrument();
+    double minValue = manager.getMinValue();
+    double maxValue = manager.getMaxValue();
+
+    // Assert
+    double expectedMinValue = 0.0;
+    double expectedMaxValue = 1.0;
+    std::string expectedInstrument("_EMPTY_");
+
+    TSM_ASSERT("The instrument string is empty, since it does not exist.",
+               expectedInstrument == instrument);
+    TSM_ASSERT_EQUALS("The min default value is 0.0.", expectedMinValue,
+                      minValue);
+    TSM_ASSERT_EQUALS("The max default value is 1.0.", expectedMaxValue,
+                      maxValue);
+  }
+
+  void testSetValuesCanBeReadOut() {
+    // Arrange
+    MetadataJsonManager manager;
+
+    std::string instrument = "OSIRIS";
+    double minValue = 123.0;
+    double maxValue = 124234.3;
+
+    // Act
+    manager.setInstrument(instrument);
+    manager.setMinValue(minValue);
+    manager.setMaxValue(maxValue);
+
+    // Assert
+    TSM_ASSERT_EQUALS("The instrument is read in and out.", instrument,
+                      manager.getInstrument());
+    TSM_ASSERT_EQUALS("The min value is read in and out.", minValue,
+                      manager.getMinValue());
+    TSM_ASSERT_EQUALS("The max value is read in and out.", maxValue,
+                      manager.getMaxValue());
+  }
+
+  void testJsonStringIsReadInAndPopualtesContainer() {
+    // Arrange
+    MetadataJsonManager manager;
+    std::string jsonString =
+        "{\"instrument\": \"OSIRIS\", \"minValue\":1.0, \"maxValue\": 2.0}";
+
+    // Act
+    manager.readInSerializedJson(jsonString);
+
+    // Assert
+
+    TSM_ASSERT("The instrument of the serialized Json string is detected.",
+               manager.getInstrument() == "OSIRIS");
+    TSM_ASSERT_EQUALS(
+        "The min value of the serialized Json string is detected.", 1.0,
+        manager.getMinValue());
+    TSM_ASSERT_EQUALS(
+        "The max value of the serialized Json string is detected.", 2.0,
+        manager.getMaxValue());
+  }
+
+  void testJsonStringWhichDoesNotHaveFieldsProducesDefaultValues() {
+    // Arrange
+    MetadataJsonManager manager;
+    std::string jsonString = "{\"myInstrument\": \"OSIRIS\", "
+                             "\"myMinValue\":1.0, \"myMaxValue\": 2.0}";
+
+    // Act
+    manager.readInSerializedJson(jsonString);
+
+    // Assert
+    std::string expectedInstrument = "_EMPTY_";
+    TSM_ASSERT("The json object does not find the instrument field and returns "
+               "default.",
+               manager.getInstrument() == expectedInstrument);
+    TSM_ASSERT_EQUALS("The json object does not find the max value field and "
+                      "returns default.",
+                      0.0, manager.getMinValue());
+    TSM_ASSERT_EQUALS("The json object does not find the min value field and "
+                      "returns default.",
+                      1.0, manager.getMaxValue());
+  }
+
+  void testCorrectJsonStringIsProduced() {
+    // Arrange
+    MetadataJsonManager manager;
+    manager.setInstrument("OSIRIS");
+    manager.setMaxValue(3.0);
+    manager.setMinValue(2.0);
+
+    // Act
+    std::string jsonString = manager.getSerializedJson();
+    Json::Reader reader;
+    Json::Value container;
+    reader.parse(jsonString, container, false);
+
+    // Assert
+    TSM_ASSERT("Json string is being produced", !jsonString.empty());
+    TSM_ASSERT_EQUALS("Json string contains inserted instrument.", "OSIRIS",
+                      container["instrument"].asString());
+    TSM_ASSERT_EQUALS("Json string contains inserted min value.", 2.0,
+                      container["minValue"].asDouble());
+    TSM_ASSERT_EQUALS("Json string containns inserted max value.", 3.0,
+                      container["maxValue"].asDouble());
+  }
 };
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/MetadataToFieldDataTest.h b/Vates/VatesAPI/test/MetadataToFieldDataTest.h
index 9b7cbaf05cc8588527a09c08a30e66ae2b510494..f2e668c2461906ed6007fc3873a3c0e96cd9a538 100644
--- a/Vates/VatesAPI/test/MetadataToFieldDataTest.h
+++ b/Vates/VatesAPI/test/MetadataToFieldDataTest.h
@@ -10,19 +10,14 @@
 
 using Mantid::VATES::MetadataToFieldData;
 
-class MetadataToFieldDataTest: public CxxTest::TestSuite
-{
+class MetadataToFieldDataTest : public CxxTest::TestSuite {
 private:
-
-  //helper method
-  static std::string convertCharArrayToString(vtkCharArray* carry)
-  {
+  // helper method
+  static std::string convertCharArrayToString(vtkCharArray *carry) {
     std::string sResult;
-    for (int i = 0; i < carry->GetSize(); i++)
-    {
+    for (int i = 0; i < carry->GetSize(); i++) {
       char c = carry->GetValue(i);
-      if (int(c) > 1)
-      {
+      if (int(c) > 1) {
         sResult.push_back(c);
       }
     }
@@ -31,9 +26,7 @@ private:
   }
 
 public:
-
-  void testMetaDataToFieldData()
-  {
+  void testMetaDataToFieldData() {
     std::string testData = "<test data/>%s";
     const std::string id = "1";
 
@@ -45,14 +38,16 @@ public:
     MetadataToFieldData function;
     function(fieldData.GetPointer(), testData, id);
 
-    //convert vtkchararray back into a string.
-    vtkCharArray* carry = dynamic_cast<vtkCharArray*> (fieldData->GetArray(id.c_str()));
+    // convert vtkchararray back into a string.
+    vtkCharArray *carry =
+        dynamic_cast<vtkCharArray *>(fieldData->GetArray(id.c_str()));
 
-    TSM_ASSERT_EQUALS("The result does not match the input. Metadata not properly converted.", testData, convertCharArrayToString(carry));
+    TSM_ASSERT_EQUALS(
+        "The result does not match the input. Metadata not properly converted.",
+        testData, convertCharArrayToString(carry));
   }
 
-  void testMetaDataToFieldDataWithEmptyFieldData()
-  {
+  void testMetaDataToFieldDataWithEmptyFieldData() {
     std::string testData = "<test data/>%s";
     const std::string id = "1";
 
@@ -60,12 +55,14 @@ public:
     MetadataToFieldData function;
     function(emptyFieldData.GetPointer(), testData.c_str(), id.c_str());
 
-    //convert vtkchararray back into a string.
-    vtkCharArray* carry = dynamic_cast<vtkCharArray*> (emptyFieldData->GetArray(id.c_str()));
+    // convert vtkchararray back into a string.
+    vtkCharArray *carry =
+        dynamic_cast<vtkCharArray *>(emptyFieldData->GetArray(id.c_str()));
 
-    TSM_ASSERT_EQUALS("The result does not match the input. Metadata not properly converted.", testData, convertCharArrayToString(carry));
+    TSM_ASSERT_EQUALS(
+        "The result does not match the input. Metadata not properly converted.",
+        testData, convertCharArrayToString(carry));
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/NoThresholdRangeTest.h b/Vates/VatesAPI/test/NoThresholdRangeTest.h
index c26c047d04f839430acf1dcd00559f6ad22ba454..57b2a404b6b0303afd5d16879ab9bc88d35a2fbe 100644
--- a/Vates/VatesAPI/test/NoThresholdRangeTest.h
+++ b/Vates/VatesAPI/test/NoThresholdRangeTest.h
@@ -11,21 +11,17 @@ using namespace Mantid::VATES;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class NoThresholdRangeTest: public CxxTest::TestSuite
-{
-public :
-
-  void testEverythingWithinRange()
-  {
+class NoThresholdRangeTest : public CxxTest::TestSuite {
+public:
+  void testEverythingWithinRange() {
     NoThresholdRange range;
-    
+
     TS_ASSERT_EQUALS(true, range.inRange(-1e9));
     TS_ASSERT_EQUALS(true, range.inRange(0));
     TS_ASSERT_EQUALS(true, range.inRange(1e9));
   }
 
-  void testGetMinMax()
-  {
+  void testGetMinMax() {
     NoThresholdRange range;
 
     range.inRange(1);
@@ -35,7 +31,6 @@ public :
     TSM_ASSERT_EQUALS("Wrong max found", 5, range.getMaximum());
     TSM_ASSERT_EQUALS("Wrong min found", -2, range.getMinimum());
   }
-
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/NormalizationTest.h b/Vates/VatesAPI/test/NormalizationTest.h
index f70981eb9ea4a0d08eadc847dc8b08a177bd4d06..b9206d7288754ce6b9d2f1aa7de35d4819fffcf7 100644
--- a/Vates/VatesAPI/test/NormalizationTest.h
+++ b/Vates/VatesAPI/test/NormalizationTest.h
@@ -10,7 +10,6 @@ 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),
diff --git a/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h b/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
index 7c668ed28cbdb23651120bceac8883f06a7ae101..3372c6e89e60b6769f5eaa8a6224f4acc30ba8ac 100644
--- a/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
+++ b/Vates/VatesAPI/test/NullPeaksPresenterVsiTest.h
@@ -10,22 +10,24 @@
 
 using namespace Mantid::VATES;
 
-class NullPeaksPresenterVsiTest : public CxxTest::TestSuite
-{
+class NullPeaksPresenterVsiTest : public CxxTest::TestSuite {
 public:
   void testGettingPeaksWorkspaceThrows() {
-     NullPeaksPresenterVsi presenter;
-     TSM_ASSERT_THROWS("Should not implement this method", presenter.getPeaksWorkspace(), std::runtime_error);
+    NullPeaksPresenterVsi presenter;
+    TSM_ASSERT_THROWS("Should not implement this method",
+                      presenter.getPeaksWorkspace(), std::runtime_error);
   }
 
   void testGettingUsablePeaksThrows() {
     NullPeaksPresenterVsi presenter;
-    TSM_ASSERT_THROWS("Should not implement this method", presenter.getViewablePeaks(), std::runtime_error);
+    TSM_ASSERT_THROWS("Should not implement this method",
+                      presenter.getViewablePeaks(), std::runtime_error);
   }
 
   void testGettingPeaksWorkspaceNameThrows() {
     NullPeaksPresenterVsi presenter;
-    TSM_ASSERT_THROWS("Should not implement this method", presenter.getViewablePeaks(), std::runtime_error);
+    TSM_ASSERT_THROWS("Should not implement this method",
+                      presenter.getViewablePeaks(), std::runtime_error);
   }
 
   void testGettingPeaksInfoThrows() {
@@ -33,9 +35,13 @@ public:
     int row = 0;
     double radius;
     Mantid::Kernel::V3D position;
-    Mantid::Kernel::SpecialCoordinateSystem coord = Mantid::Kernel::SpecialCoordinateSystem::None;
+    Mantid::Kernel::SpecialCoordinateSystem coord =
+        Mantid::Kernel::SpecialCoordinateSystem::None;
     Mantid::API::IPeaksWorkspace_sptr peaksWorkspace;
-    TSM_ASSERT_THROWS("Should not implement this method", presenter.getPeaksInfo(peaksWorkspace,row,position,radius, coord), std::runtime_error);
+    TSM_ASSERT_THROWS(
+        "Should not implement this method",
+        presenter.getPeaksInfo(peaksWorkspace, row, position, radius, coord),
+        std::runtime_error);
   }
 };
 #endif
diff --git a/Vates/VatesAPI/test/PrecompiledHeader.h b/Vates/VatesAPI/test/PrecompiledHeader.h
index 3586c66ff28c4237521c748e84ba02e092729bbc..f95b2bba502184842e94568161ee241c8b08ad89 100644
--- a/Vates/VatesAPI/test/PrecompiledHeader.h
+++ b/Vates/VatesAPI/test/PrecompiledHeader.h
@@ -9,4 +9,4 @@
 #include <set>
 #include <string>
 
-#endif //VATESAPITEST_PRECOMPILEDHEADER_H_
\ No newline at end of file
+#endif // VATESAPITEST_PRECOMPILEDHEADER_H_
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/PresenterUtilitiesTest.h b/Vates/VatesAPI/test/PresenterUtilitiesTest.h
index 2ba840597fa565a005765ddb3d43915d89809fb5..403bd0f348cc5033d15a3707ca588f34c6682dfc 100644
--- a/Vates/VatesAPI/test/PresenterUtilitiesTest.h
+++ b/Vates/VatesAPI/test/PresenterUtilitiesTest.h
@@ -4,20 +4,18 @@
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/FactoryChains.h"
 
-class PresenterUtilitiesTest : public CxxTest::TestSuite
-{
+class PresenterUtilitiesTest : public CxxTest::TestSuite {
 public:
-
   void test_that_time_stamped_name_is_produced() {
     // Arrange
     std::string name = "testName";
     // Act
     auto timeStampedName = Mantid::VATES::createTimeStampedName(name);
     // Assert
-    TSM_ASSERT("Time stamped name should be larger than the original name", name.size() < timeStampedName.size());
-    TSM_ASSERT("Time stamped name should start with original name", timeStampedName.find(name) == 0);
+    TSM_ASSERT("Time stamped name should be larger than the original name",
+               name.size() < timeStampedName.size());
+    TSM_ASSERT("Time stamped name should start with original name",
+               timeStampedName.find(name) == 0);
   }
-
-
 };
 #endif
diff --git a/Vates/VatesAPI/test/SQWLoadingPresenterTest.h b/Vates/VatesAPI/test/SQWLoadingPresenterTest.h
index 1391c0a969ff1ce4a59ebb9ccbdea113f77461cc..e538284d8c1430fe33692efb0b3309ac2646dce7 100644
--- a/Vates/VatesAPI/test/SQWLoadingPresenterTest.h
+++ b/Vates/VatesAPI/test/SQWLoadingPresenterTest.h
@@ -1,5 +1,5 @@
 #ifndef SQW_LOADING_PRESENTER_TEST_H_
-#define SQW_LOADING_PRESENTER_TEST_H_ 
+#define SQW_LOADING_PRESENTER_TEST_H_
 
 #include <cxxtest/TestSuite.h>
 #include <vtkUnstructuredGrid.h>
@@ -20,265 +20,266 @@ using namespace Mantid::VATES;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class SQWLoadingPresenterTest : public CxxTest::TestSuite
-{
+class SQWLoadingPresenterTest : public CxxTest::TestSuite {
 
 private:
-
   // Helper method to return the full path to a real sqw file.
-  static std::string getSuitableFileNamePath()
-  {
-    return Mantid::API::FileFinder::Instance().getFullPath("test_horace_reader.sqw");
+  static std::string getSuitableFileNamePath() {
+    return Mantid::API::FileFinder::Instance().getFullPath(
+        "test_horace_reader.sqw");
   }
-  
+
   // Helper method to return the full path to a file that is invalid.
-  static std::string getUnhandledFileNamePath()
-  {
+  static std::string getUnhandledFileNamePath() {
     return Mantid::API::FileFinder::Instance().getFullPath("emu00006473.nxs");
   }
 
-  // Helper method. Create the expected backend filename + path using the same rules used internally in SQWLoadingPresenter.
-  static std::string getFileBackend(std::string fileName)
-  {
+  // Helper method. Create the expected backend filename + path using the same
+  // rules used internally in SQWLoadingPresenter.
+  static std::string getFileBackend(std::string fileName) {
     size_t pos = fileName.find(".");
     return fileName.substr(0, pos) + ".nxs";
   }
 
 public:
   void setUp() override {
-    std::remove(getFileBackend(getSuitableFileNamePath()).c_str()); // Clean out any pre-existing backend files.
-}
-
-void testConstructWithEmptyFileThrows()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
-                    SQWLoadingPresenter(std::move(view), ""),
-                    std::invalid_argument);
-}
-
-void testConstructWithNullViewThrows()
-{
-  TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
-                    SQWLoadingPresenter(nullptr, "some_file"),
-                    std::invalid_argument);
-}
-
-void testConstruct()
-{
-  std::unique_ptr<MDLoadingView> view =
-    Mantid::Kernel::make_unique<MockMDLoadingView>();
-  TSM_ASSERT_THROWS_NOTHING(
-      "Object should be created without exception.",
-      SQWLoadingPresenter(std::move(view), getSuitableFileNamePath()));
-}
-
-void testCanReadFile()
-{
-  std::unique_ptr<MDLoadingView> view =
-      Mantid::Kernel::make_unique<MockMDLoadingView>();
-  SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
-  TSM_ASSERT("Should be readable, valid SQW file.", presenter.canReadFile());
-}
-
-void testCanReadFileWithDifferentCaseExtension()
-{
-  auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
-  SQWLoadingPresenter presenter(std::move(view), "other.Sqw");
-  TSM_ASSERT("Should be readable, only different in case.",
-             presenter.canReadFile());
-}
-
-void testCannotReadFileWithWrongExtension()
-{
-  auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
-  SQWLoadingPresenter presenter(std::move(view), getUnhandledFileNamePath());
-  TSM_ASSERT("Should NOT be readable, completely wrong file type.",
-             !presenter.canReadFile());
-}
-
-void testExecutionInMemory()
-{
-  using namespace testing;
-  //Setup view
-  auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*view, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(Return(true)); // View setup to request loading in memory.
-  EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
-  EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  MockProgressAction mockDrawingProgressAction;
-  //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  //Create the presenter and runit!
-  SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
-  presenter.executeLoadMetadata();
-  auto product = presenter.execute(&factory, mockLoadingProgressAction,
-                                   mockDrawingProgressAction);
-
-  std::string fileNameIfGenerated = getFileBackend(getSuitableFileNamePath());
-  std::ifstream fileExists(fileNameIfGenerated.c_str(), ifstream::in);
-  TSM_ASSERT("File Backend SHOULD NOT be generated.",  !fileExists.good());
-
-  TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
-  TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName()));
-  TSM_ASSERT("No field data!", NULL != product->GetFieldData());
-  TSM_ASSERT_EQUALS("Two arrays expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
-  TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
-  TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
-  TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-
-  TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
-}
-
-void testCallHasTDimThrows()
-{
-  SQWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(),
-      getSuitableFileNamePath());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.hasTDimensionAvailable(), std::runtime_error);
-}
-
-void testCallGetTDimensionValuesThrows()
-{
-  SQWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(),
-      getSuitableFileNamePath());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getTimeStepValues(), std::runtime_error);
-}
-
-void testCallGetGeometryThrows()
-{
-  SQWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(),
-      getSuitableFileNamePath());
-  TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
-                    presenter.getGeometryXML(), std::runtime_error);
-}
-
-void testExecuteLoadMetadata()
-{
-  SQWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(),
-      getSuitableFileNamePath());
-  presenter.executeLoadMetadata();
-  TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.getTimeStepValues());
-  TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable());
-  TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.getGeometryXML());
-}
-
-void testGetWorkspaceTypeName()
-{
-  SQWLoadingPresenter presenter(
-      Mantid::Kernel::make_unique<MockMDLoadingView>(),
-      getSuitableFileNamePath());
-  TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
-                    presenter.getWorkspaceTypeName());
-}
-
-void testTimeLabel()
-{
-  using namespace testing;
-  //Setup view
-  auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*view, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(Return(true)); // View setup to request loading in memory.
-  EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
-  EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  MockProgressAction mockDrawingProgressAction;
-  //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  //Create the presenter and runit!
-  SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
-  presenter.executeLoadMetadata();
-  auto product = presenter.execute(&factory, mockLoadingProgressAction,
-                                   mockDrawingProgressAction);
-  TSM_ASSERT_EQUALS("Time label should be exact.",
-                    presenter.getTimeStepLabel(), "en (meV)");
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-
-  TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
-}
-
-void testAxisLabels()
-{
-  using namespace testing;
-  //Setup view
-  auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
-  EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
-  EXPECT_CALL(*view, getLoadInMemory())
-      .Times(AtLeast(1))
-      .WillRepeatedly(Return(true)); // View setup to request loading in memory.
-  EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
-  EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber());
-
-  //Setup rendering factory
-  MockvtkDataSetFactory factory;
-  EXPECT_CALL(factory, initialize(_)).Times(1);
-  EXPECT_CALL(factory, create(_))
-      .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
-  EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
-
-  //Setup progress updates objects
-  MockProgressAction mockLoadingProgressAction;
-  MockProgressAction mockDrawingProgressAction;
-  //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-  EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
-
-  //Create the presenter and runit!
-  SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
-  presenter.executeLoadMetadata();
-  auto product = presenter.execute(&factory, mockLoadingProgressAction,
-                                   mockDrawingProgressAction);
-  TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product));
-  TSM_ASSERT_EQUALS("X Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForX"),
-                    "Q_sample_x ($\\AA^{-1}$)");
-  TSM_ASSERT_EQUALS("Y Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForY"),
-                    "Q_sample_y ($\\AA^{-1}$)");
-  TSM_ASSERT_EQUALS("Z Label should match exactly",
-                    getStringFieldDataValue(product, "AxisTitleForZ"),
-                    "Q_sample_z ($\\AA^{-1}$)");
-
-  TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
-  TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
-  TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
-}
+    std::remove(getFileBackend(getSuitableFileNamePath())
+                    .c_str()); // Clean out any pre-existing backend files.
+  }
+
+  void testConstructWithEmptyFileThrows() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
+                      SQWLoadingPresenter(std::move(view), ""),
+                      std::invalid_argument);
+  }
+
+  void testConstructWithNullViewThrows() {
+    TSM_ASSERT_THROWS("Should throw if an empty file string is given.",
+                      SQWLoadingPresenter(nullptr, "some_file"),
+                      std::invalid_argument);
+  }
+
+  void testConstruct() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    TSM_ASSERT_THROWS_NOTHING(
+        "Object should be created without exception.",
+        SQWLoadingPresenter(std::move(view), getSuitableFileNamePath()));
+  }
+
+  void testCanReadFile() {
+    std::unique_ptr<MDLoadingView> view =
+        Mantid::Kernel::make_unique<MockMDLoadingView>();
+    SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
+    TSM_ASSERT("Should be readable, valid SQW file.", presenter.canReadFile());
+  }
+
+  void testCanReadFileWithDifferentCaseExtension() {
+    auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
+    SQWLoadingPresenter presenter(std::move(view), "other.Sqw");
+    TSM_ASSERT("Should be readable, only different in case.",
+               presenter.canReadFile());
+  }
+
+  void testCannotReadFileWithWrongExtension() {
+    auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
+    SQWLoadingPresenter presenter(std::move(view), getUnhandledFileNamePath());
+    TSM_ASSERT("Should NOT be readable, completely wrong file type.",
+               !presenter.canReadFile());
+  }
 
+  void testExecutionInMemory() {
+    using namespace testing;
+    // Setup view
+    auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*view, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(
+            Return(true)); // View setup to request loading in memory.
+    EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    MockProgressAction mockDrawingProgressAction;
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    // Create the presenter and runit!
+    SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
+    presenter.executeLoadMetadata();
+    auto product = presenter.execute(&factory, mockLoadingProgressAction,
+                                     mockDrawingProgressAction);
+
+    std::string fileNameIfGenerated = getFileBackend(getSuitableFileNamePath());
+    std::ifstream fileExists(fileNameIfGenerated.c_str(), ifstream::in);
+    TSM_ASSERT("File Backend SHOULD NOT be generated.", !fileExists.good());
+
+    TSM_ASSERT("Should have generated a vtkDataSet", NULL != product);
+    TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid",
+                      std::string(product->GetClassName()));
+    TSM_ASSERT("No field data!", NULL != product->GetFieldData());
+    TSM_ASSERT_EQUALS(
+        "Two arrays expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
+    TS_ASSERT_THROWS_NOTHING(presenter.hasTDimensionAvailable());
+    TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML());
+    TS_ASSERT(!presenter.getWorkspaceTypeName().empty());
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+
+    TSM_ASSERT("Bad usage of loading algorithm progress updates",
+               Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
+  }
+
+  void testCallHasTDimThrows() {
+    SQWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(),
+        getSuitableFileNamePath());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.hasTDimensionAvailable(), std::runtime_error);
+  }
+
+  void testCallGetTDimensionValuesThrows() {
+    SQWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(),
+        getSuitableFileNamePath());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getTimeStepValues(), std::runtime_error);
+  }
+
+  void testCallGetGeometryThrows() {
+    SQWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(),
+        getSuitableFileNamePath());
+    TSM_ASSERT_THROWS("Should throw. Execute not yet run.",
+                      presenter.getGeometryXML(), std::runtime_error);
+  }
+
+  void testExecuteLoadMetadata() {
+    SQWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(),
+        getSuitableFileNamePath());
+    presenter.executeLoadMetadata();
+    TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.",
+                              presenter.getTimeStepValues());
+    TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.",
+                              presenter.hasTDimensionAvailable());
+    TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.",
+                              presenter.getGeometryXML());
+  }
+
+  void testGetWorkspaceTypeName() {
+    SQWLoadingPresenter presenter(
+        Mantid::Kernel::make_unique<MockMDLoadingView>(),
+        getSuitableFileNamePath());
+    TSM_ASSERT_EQUALS("Characterisation Test Failed", "",
+                      presenter.getWorkspaceTypeName());
+  }
+
+  void testTimeLabel() {
+    using namespace testing;
+    // Setup view
+    auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*view, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(
+            Return(true)); // View setup to request loading in memory.
+    EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    MockProgressAction mockDrawingProgressAction;
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    // Create the presenter and runit!
+    SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
+    presenter.executeLoadMetadata();
+    auto product = presenter.execute(&factory, mockLoadingProgressAction,
+                                     mockDrawingProgressAction);
+    TSM_ASSERT_EQUALS("Time label should be exact.",
+                      presenter.getTimeStepLabel(), "en (meV)");
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+
+    TSM_ASSERT("Bad usage of loading algorithm progress updates",
+               Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
+  }
+
+  void testAxisLabels() {
+    using namespace testing;
+    // Setup view
+    auto view = Mantid::Kernel::make_unique<MockMDLoadingView>();
+    EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1));
+    EXPECT_CALL(*view, getLoadInMemory())
+        .Times(AtLeast(1))
+        .WillRepeatedly(
+            Return(true)); // View setup to request loading in memory.
+    EXPECT_CALL(*view, getTime()).Times(AtLeast(1));
+    EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber());
+
+    // Setup rendering factory
+    MockvtkDataSetFactory factory;
+    EXPECT_CALL(factory, initialize(_)).Times(1);
+    EXPECT_CALL(factory, create(_))
+        .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New()));
+    EXPECT_CALL(factory, setRecursionDepth(_)).Times(1);
+
+    // Setup progress updates objects
+    MockProgressAction mockLoadingProgressAction;
+    MockProgressAction mockDrawingProgressAction;
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
+
+    // Create the presenter and runit!
+    SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath());
+    presenter.executeLoadMetadata();
+    auto product = presenter.execute(&factory, mockLoadingProgressAction,
+                                     mockDrawingProgressAction);
+    TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product));
+    TSM_ASSERT_EQUALS("X Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForX"),
+                      "Q_sample_x ($\\AA^{-1}$)");
+    TSM_ASSERT_EQUALS("Y Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForY"),
+                      "Q_sample_y ($\\AA^{-1}$)");
+    TSM_ASSERT_EQUALS("Z Label should match exactly",
+                      getStringFieldDataValue(product, "AxisTitleForZ"),
+                      "Q_sample_z ($\\AA^{-1}$)");
+
+    TS_ASSERT(Mock::VerifyAndClearExpectations(view.get()));
+    TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
+    TSM_ASSERT("Bad usage of loading algorithm progress updates",
+               Mock::VerifyAndClearExpectations(&mockLoadingProgressAction));
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/SaveMDWorkspaceToVTKImplTest.h b/Vates/VatesAPI/test/SaveMDWorkspaceToVTKImplTest.h
index d636d60e4bd9e26ab1913359e183684614449679..604d1b272630acb66aacc47b4fc0ce1346faafb7 100644
--- a/Vates/VatesAPI/test/SaveMDWorkspaceToVTKImplTest.h
+++ b/Vates/VatesAPI/test/SaveMDWorkspaceToVTKImplTest.h
@@ -12,279 +12,250 @@
 
 using namespace Mantid::DataObjects;
 
-class SaveMDWorkspaceToVTKImplTest : public CxxTest::TestSuite
-{
+class SaveMDWorkspaceToVTKImplTest : public CxxTest::TestSuite {
 public:
-    void test_that_vector_of_normalization_strings_has_all_values()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-
-        // Act
-        const auto normalizations
-            = saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
-
-        // Assert
-        TSM_ASSERT_EQUALS("There should be 4 normalization options.",
-                          normalizations.size(), 4);
-        TSM_ASSERT_EQUALS("First normalization should be AutoSelect.",
-                          normalizations[0], "AutoSelect");
-        TSM_ASSERT_EQUALS("First normalization should be NoNormalization.",
-                          normalizations[1], "NoNormalization");
-        TSM_ASSERT_EQUALS(
-            "First normalization should be NumEventsNormalization.",
-            normalizations[2], "NumEventsNormalization");
-        TSM_ASSERT_EQUALS("First normalization should be VolumeNormalization.",
-                          normalizations[3], "VolumeNormalization");
-    }
-
-    void test_string_representation_converts_to_visual_normalization()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-        const auto normalizations
-            = saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
-
-        // Act
-        const auto autoSelect
-            = saveMDToVTK.translateStringToVisualNormalization(
-                normalizations[0]);
-        const auto noNormalization
-            = saveMDToVTK.translateStringToVisualNormalization(
-                normalizations[1]);
-        const auto numEventsNormalization
-            = saveMDToVTK.translateStringToVisualNormalization(
-                normalizations[2]);
-        const auto volumeNormalization
-            = saveMDToVTK.translateStringToVisualNormalization(
-                normalizations[3]);
-
-        // Assert
-        TSM_ASSERT_EQUALS("The visual normalization should be AutoSelect.",
-                          autoSelect, Mantid::VATES::AutoSelect);
-        TSM_ASSERT_EQUALS("The visual normalization should be NoNormalization.",
-                          noNormalization, Mantid::VATES::NoNormalization);
-        TSM_ASSERT_EQUALS(
-            "The visual normalization should be NumEventsNormalization.",
-            numEventsNormalization, Mantid::VATES::NumEventsNormalization);
-        TSM_ASSERT_EQUALS(
-            "The visual normalization should be VolumeNormalization.",
-            volumeNormalization, Mantid::VATES::VolumeNormalization);
-    }
-
-    void test_that_vector_of_threshold_strings_has_all_values()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-
-        // Act
-        const auto thresholds
-            = saveMDToVTK.getAllowedThresholdsInStringRepresentation();
-
-        // Assert
-        TSM_ASSERT_EQUALS("There should be 2 normalization options",
-                          thresholds.size(), 2);
-        TSM_ASSERT_EQUALS(
-            "First normalization should be IgnoreZerosThresholdRange.",
-            thresholds[0], "IgnoreZerosThresholdRange");
-        TSM_ASSERT_EQUALS("Second normalization should be NoThresholdRange.",
-                          thresholds[1], "NoThresholdRange");
-    }
-
-    void test_string_representation_converts_to_TresholdRange()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-        auto thresholds
-            = saveMDToVTK.getAllowedThresholdsInStringRepresentation();
-        // Act
-        auto ignoreZerosThresholdRange
-            = saveMDToVTK.translateStringToThresholdRange(thresholds[0]);
-        auto noThresholdRange
-            = saveMDToVTK.translateStringToThresholdRange(thresholds[1]);
-        // Assert
-        TSM_ASSERT(
-            "Should be a IgnoreZerosTresholdRange",
-            boost::
-                dynamic_pointer_cast<Mantid::VATES::IgnoreZerosThresholdRange>(
-                    ignoreZerosThresholdRange));
-        TSM_ASSERT("Should be a NoTresholdRange",
-                   boost::dynamic_pointer_cast<Mantid::VATES::ThresholdRange>(
-                       noThresholdRange));
-    }
-
-    void test_detects_when_not_3D_workspace()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-        size_t numDims = 4;
-        auto workspace
-            = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, numDims);
-
-        // Act
-        const auto is3D = saveMDToVTK.is3DWorkspace(workspace);
-
-        // Assert
-        TSM_ASSERT("Detects a non-3D MD workspace", !is3D);
-    }
-
-    void test_detects_when_3D_workspace()
-    {
-        // Arrange
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-        const size_t numDims = 3;
-        auto workspace
-            = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, numDims);
-
-        // Act
-        const auto is3D = saveMDToVTK.is3DWorkspace(workspace);
-
-        // Assert
-        TSM_ASSERT("Detects that a 3D MD workspace", is3D);
-    }
-
-    void
-    test_that_saves_MD_Event_workspace_to_vts_file_without_extension_in_path_name()
-    {
-        // Arrange
-        auto workspace = getTestWorkspace("MDEvent");
-
-        const std::string filenameBare = "SaveMDWorkspaceToVTKImplTestFile";
-        const std::string filenameWithExtension = filenameBare + ".vtu";
-
-        auto filenameExpected = getTemporaryFilename(filenameWithExtension);
-        removeTemporaryFile(filenameExpected);
-
-        auto filename = getTemporaryFilename(filenameBare);
-
-        // Act
-        do_test_saving_to_vtk_file(workspace, filename);
-
-        // Assert
-        verify_file_creation(filenameExpected);
-    }
-
-    void
-    test_that_saves_MD_Event_workspace_to_vts_file_with_extension_in_path_name()
-    {
-        // Arrange
-        auto workspace = getTestWorkspace("MDEvent");
+  void test_that_vector_of_normalization_strings_has_all_values() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+
+    // Act
+    const auto normalizations =
+        saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
+
+    // Assert
+    TSM_ASSERT_EQUALS("There should be 4 normalization options.",
+                      normalizations.size(), 4);
+    TSM_ASSERT_EQUALS("First normalization should be AutoSelect.",
+                      normalizations[0], "AutoSelect");
+    TSM_ASSERT_EQUALS("First normalization should be NoNormalization.",
+                      normalizations[1], "NoNormalization");
+    TSM_ASSERT_EQUALS("First normalization should be NumEventsNormalization.",
+                      normalizations[2], "NumEventsNormalization");
+    TSM_ASSERT_EQUALS("First normalization should be VolumeNormalization.",
+                      normalizations[3], "VolumeNormalization");
+  }
+
+  void test_string_representation_converts_to_visual_normalization() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+    const auto normalizations =
+        saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
+
+    // Act
+    const auto autoSelect =
+        saveMDToVTK.translateStringToVisualNormalization(normalizations[0]);
+    const auto noNormalization =
+        saveMDToVTK.translateStringToVisualNormalization(normalizations[1]);
+    const auto numEventsNormalization =
+        saveMDToVTK.translateStringToVisualNormalization(normalizations[2]);
+    const auto volumeNormalization =
+        saveMDToVTK.translateStringToVisualNormalization(normalizations[3]);
+
+    // Assert
+    TSM_ASSERT_EQUALS("The visual normalization should be AutoSelect.",
+                      autoSelect, Mantid::VATES::AutoSelect);
+    TSM_ASSERT_EQUALS("The visual normalization should be NoNormalization.",
+                      noNormalization, Mantid::VATES::NoNormalization);
+    TSM_ASSERT_EQUALS(
+        "The visual normalization should be NumEventsNormalization.",
+        numEventsNormalization, Mantid::VATES::NumEventsNormalization);
+    TSM_ASSERT_EQUALS("The visual normalization should be VolumeNormalization.",
+                      volumeNormalization, Mantid::VATES::VolumeNormalization);
+  }
+
+  void test_that_vector_of_threshold_strings_has_all_values() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+
+    // Act
+    const auto thresholds =
+        saveMDToVTK.getAllowedThresholdsInStringRepresentation();
+
+    // Assert
+    TSM_ASSERT_EQUALS("There should be 2 normalization options",
+                      thresholds.size(), 2);
+    TSM_ASSERT_EQUALS(
+        "First normalization should be IgnoreZerosThresholdRange.",
+        thresholds[0], "IgnoreZerosThresholdRange");
+    TSM_ASSERT_EQUALS("Second normalization should be NoThresholdRange.",
+                      thresholds[1], "NoThresholdRange");
+  }
+
+  void test_string_representation_converts_to_TresholdRange() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+    auto thresholds = saveMDToVTK.getAllowedThresholdsInStringRepresentation();
+    // Act
+    auto ignoreZerosThresholdRange =
+        saveMDToVTK.translateStringToThresholdRange(thresholds[0]);
+    auto noThresholdRange =
+        saveMDToVTK.translateStringToThresholdRange(thresholds[1]);
+    // Assert
+    TSM_ASSERT(
+        "Should be a IgnoreZerosTresholdRange",
+        boost::dynamic_pointer_cast<Mantid::VATES::IgnoreZerosThresholdRange>(
+            ignoreZerosThresholdRange));
+    TSM_ASSERT("Should be a NoTresholdRange",
+               boost::dynamic_pointer_cast<Mantid::VATES::ThresholdRange>(
+                   noThresholdRange));
+  }
+
+  void test_detects_when_not_3D_workspace() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+    size_t numDims = 4;
+    auto workspace = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, numDims);
+
+    // Act
+    const auto is3D = saveMDToVTK.is3DWorkspace(workspace);
+
+    // Assert
+    TSM_ASSERT("Detects a non-3D MD workspace", !is3D);
+  }
+
+  void test_detects_when_3D_workspace() {
+    // Arrange
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+    const size_t numDims = 3;
+    auto workspace = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, numDims);
+
+    // Act
+    const auto is3D = saveMDToVTK.is3DWorkspace(workspace);
+
+    // Assert
+    TSM_ASSERT("Detects that a 3D MD workspace", is3D);
+  }
+
+  void
+  test_that_saves_MD_Event_workspace_to_vts_file_without_extension_in_path_name() {
+    // Arrange
+    auto workspace = getTestWorkspace("MDEvent");
+
+    const std::string filenameBare = "SaveMDWorkspaceToVTKImplTestFile";
+    const std::string filenameWithExtension = filenameBare + ".vtu";
+
+    auto filenameExpected = getTemporaryFilename(filenameWithExtension);
+    removeTemporaryFile(filenameExpected);
+
+    auto filename = getTemporaryFilename(filenameBare);
+
+    // Act
+    do_test_saving_to_vtk_file(workspace, filename);
+
+    // Assert
+    verify_file_creation(filenameExpected);
+  }
+
+  void
+  test_that_saves_MD_Event_workspace_to_vts_file_with_extension_in_path_name() {
+    // Arrange
+    auto workspace = getTestWorkspace("MDEvent");
+
+    const std::string filename = "SaveMDWorkspaceToVTKImplTestFile.vtu";
+    removeTemporaryFile(filename);
+
+    // Act
+    do_test_saving_to_vtk_file(workspace, filename);
+
+    // Assert
+    verify_file_creation(filename);
+  }
+
+  void
+  test_that_saves_MD_Histo_workspace_to_vts_file_without_extension_in_path_name() {
+    // Arrange
+    auto workspace = getTestWorkspace("MDHisto");
+
+    const std::string filenameBare = "SaveMDWorkspaceToVTKImplTestFile";
+    const std::string filenameWithExtension = filenameBare + ".vts";
+
+    auto filenameExpected = getTemporaryFilename(filenameWithExtension);
+    removeTemporaryFile(filenameExpected);
+
+    auto filename = getTemporaryFilename(filenameBare);
+
+    // Act
+    do_test_saving_to_vtk_file(workspace, filename);
+
+    // Assert
+    verify_file_creation(filenameExpected);
+  }
+
+  void
+  test_that_saves_MD_Histo_workspace_to_vts_file_with_extension_in_path_name() {
+    // Arrange
+    auto workspace = getTestWorkspace("MDHisto");
+
+    std::string filename = "SaveMDWorkspaceToVTKImplTestFile.vts";
+    filename = getTemporaryFilename(filename);
+    removeTemporaryFile(filename);
 
-        const std::string filename = "SaveMDWorkspaceToVTKImplTestFile.vtu";
-        removeTemporaryFile(filename);
+    // Act
+    do_test_saving_to_vtk_file(workspace, filename);
 
-        // Act
-        do_test_saving_to_vtk_file(workspace, filename);
-
-        // Assert
-        verify_file_creation(filename);
-    }
-
-    void
-    test_that_saves_MD_Histo_workspace_to_vts_file_without_extension_in_path_name()
-    {
-        // Arrange
-        auto workspace = getTestWorkspace("MDHisto");
-
-        const std::string filenameBare = "SaveMDWorkspaceToVTKImplTestFile";
-        const std::string filenameWithExtension = filenameBare + ".vts";
-
-        auto filenameExpected = getTemporaryFilename(filenameWithExtension);
-        removeTemporaryFile(filenameExpected);
-
-        auto filename = getTemporaryFilename(filenameBare);
-
-        // Act
-        do_test_saving_to_vtk_file(workspace, filename);
-
-        // Assert
-        verify_file_creation(filenameExpected);
-    }
-
-    void
-    test_that_saves_MD_Histo_workspace_to_vts_file_with_extension_in_path_name()
-    {
-        // Arrange
-        auto workspace = getTestWorkspace("MDHisto");
-
-        std::string filename = "SaveMDWorkspaceToVTKImplTestFile.vts";
-        filename = getTemporaryFilename(filename);
-        removeTemporaryFile(filename);
-
-        // Act
-        do_test_saving_to_vtk_file(workspace, filename);
-
-        // Assert
-        verify_file_creation(filename);
-    }
+    // Assert
+    verify_file_creation(filename);
+  }
 
 private:
-    void do_test_saving_to_vtk_file(Mantid::API::IMDWorkspace_sptr workspace,
-                                    std::string filename)
-    {
-        const int recursionDepth = 5;
-
-        Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
-
-        const auto normalizations
-            = saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
-        const auto normalization
-            = saveMDToVTK.translateStringToVisualNormalization(
-                normalizations[0]);
-
-        const auto thresholds
-            = saveMDToVTK.getAllowedThresholdsInStringRepresentation();
-        const auto threshold
-            = saveMDToVTK.translateStringToThresholdRange(thresholds[0]);
-
-        saveMDToVTK.saveMDWorkspace(workspace, filename, normalization,
-                                    threshold, recursionDepth);
+  void do_test_saving_to_vtk_file(Mantid::API::IMDWorkspace_sptr workspace,
+                                  std::string filename) {
+    const int recursionDepth = 5;
+
+    Mantid::VATES::SaveMDWorkspaceToVTKImpl saveMDToVTK;
+
+    const auto normalizations =
+        saveMDToVTK.getAllowedNormalizationsInStringRepresentation();
+    const auto normalization =
+        saveMDToVTK.translateStringToVisualNormalization(normalizations[0]);
+
+    const auto thresholds =
+        saveMDToVTK.getAllowedThresholdsInStringRepresentation();
+    const auto threshold =
+        saveMDToVTK.translateStringToThresholdRange(thresholds[0]);
+
+    saveMDToVTK.saveMDWorkspace(workspace, filename, normalization, threshold,
+                                recursionDepth);
+  }
+
+  Mantid::API::IMDWorkspace_sptr getTestWorkspace(std::string workspaceType) {
+    Mantid::API::IMDWorkspace_sptr workspace;
+    if (workspaceType == "MDEvent") {
+      const std::string name = "SaveMDEventToVTKTestWorkspace";
+      workspace = MDEventsTestHelper::makeFakeMDEventWorkspace(name);
+    } else {
+      const size_t numDims = 3;
+      const size_t numBins = 5;
+      workspace =
+          MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, numDims, numBins);
     }
-
-    Mantid::API::IMDWorkspace_sptr getTestWorkspace(std::string workspaceType)
-    {
-        Mantid::API::IMDWorkspace_sptr workspace;
-        if (workspaceType == "MDEvent") {
-            const std::string name = "SaveMDEventToVTKTestWorkspace";
-            workspace = MDEventsTestHelper::makeFakeMDEventWorkspace(name);
-        } else {
-            const size_t numDims = 3;
-            const size_t numBins = 5;
-            workspace = MDEventsTestHelper::makeFakeMDHistoWorkspace(
-                1.0, numDims, numBins);
-        }
-        return workspace;
-    }
-
-    void verify_file_creation(std::string filename)
-    {
-        // Assert
-        auto fileExists = doesFileExist(filename);
-        TSM_ASSERT("The according file should have been saved out", fileExists);
-        // Cleanup
-        removeTemporaryFile(filename);
+    return workspace;
+  }
+
+  void verify_file_creation(std::string filename) {
+    // Assert
+    auto fileExists = doesFileExist(filename);
+    TSM_ASSERT("The according file should have been saved out", fileExists);
+    // Cleanup
+    removeTemporaryFile(filename);
+  }
+
+  std::string getTemporaryFilename(std::string filenameWithoutPath) const {
+    auto default_save_directory =
+        Mantid::Kernel::ConfigService::Instance().getString(
+            "defaultsave.directory");
+    std::string filenameWithPath(default_save_directory + filenameWithoutPath);
+    return filenameWithPath;
+  }
+
+  void removeTemporaryFile(std::string fileNameWithPath) const {
+    if (Poco::File(fileNameWithPath).exists()) {
+      Poco::File(fileNameWithPath).remove();
     }
+  }
 
-    std::string getTemporaryFilename(std::string filenameWithoutPath) const
-    {
-        auto default_save_directory
-            = Mantid::Kernel::ConfigService::Instance().getString(
-                "defaultsave.directory");
-        std::string filenameWithPath(default_save_directory
-                                     + filenameWithoutPath);
-        return filenameWithPath;
-    }
-
-    void removeTemporaryFile(std::string fileNameWithPath) const
-    {
-        if (Poco::File(fileNameWithPath).exists()) {
-            Poco::File(fileNameWithPath).remove();
-        }
-    }
-
-    bool doesFileExist(std::string filename)
-    {
-        return Poco::File(filename).exists();
-    }
+  bool doesFileExist(std::string filename) {
+    return Poco::File(filename).exists();
+  }
 };
 #endif
diff --git a/Vates/VatesAPI/test/SaveMDWorkspaceToVTKTest.h b/Vates/VatesAPI/test/SaveMDWorkspaceToVTKTest.h
index dc53856c42f7de7f6bcf01c8db0dd9b12fbfc771..27a929c189084260c3ad6ce9004f71b2f819aa38 100644
--- a/Vates/VatesAPI/test/SaveMDWorkspaceToVTKTest.h
+++ b/Vates/VatesAPI/test/SaveMDWorkspaceToVTKTest.h
@@ -7,118 +7,110 @@
 #include "MantidTestHelpers/MDEventsTestHelper.h"
 #include <Poco/File.h>
 
-class SaveMDWorkspaceToVTKTest : public CxxTest::TestSuite
-{
+class SaveMDWorkspaceToVTKTest : public CxxTest::TestSuite {
 public:
-    void test_that_wrong_workspace_type_throws()
-    {
-        // Arrange
-        auto workspace = WorkspaceCreationHelper::Create2DWorkspace(1, 10);
-
-        Mantid::VATES::SaveMDWorkspaceToVTK alg;
-        alg.setChild(true);
-        alg.setRethrows(true);
-        alg.initialize();
-        alg.setProperty("InputWorkspace", workspace);
-        alg.setProperty("Filename", "test_file_name");
-        alg.setProperty("Normalization", "AutoSelect");
-        alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
-        alg.setProperty("RecursionDepth", 5);
-
-        // Act + Assert
-        TSM_ASSERT_THROWS_ANYTHING(
-            "Wrong workspae type should cause the algorithm to throw",
-            alg.execute());
-    }
+  void test_that_wrong_workspace_type_throws() {
+    // Arrange
+    auto workspace = WorkspaceCreationHelper::Create2DWorkspace(1, 10);
+
+    Mantid::VATES::SaveMDWorkspaceToVTK alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", workspace);
+    alg.setProperty("Filename", "test_file_name");
+    alg.setProperty("Normalization", "AutoSelect");
+    alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
+    alg.setProperty("RecursionDepth", 5);
+
+    // Act + Assert
+    TSM_ASSERT_THROWS_ANYTHING(
+        "Wrong workspae type should cause the algorithm to throw",
+        alg.execute());
+  }
+
+  void test_that_non_3D_workspace_throws() {
+    // Arrange
+    const size_t numDims = 4;
+    const size_t numBins = 5;
+    auto workspace =
+        Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace(
+            1.0, numDims, numBins);
 
-    void test_that_non_3D_workspace_throws()
-    {
-        // Arrange
-        const size_t numDims = 4;
-        const size_t numBins = 5;
-        auto workspace = Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace(
+    Mantid::VATES::SaveMDWorkspaceToVTK alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", workspace);
+    alg.setProperty("Filename", "test_file_name");
+    alg.setProperty("Normalization", "AutoSelect");
+    alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
+    alg.setProperty("RecursionDepth", 5);
+
+    // Act + Assert
+    TSM_ASSERT_THROWS_ANYTHING(
+        "Four dimensional workspace should not be accepted", alg.execute());
+  }
+
+  void test_that_saves_MDHisto_without_issues_under_normal_conditions() {
+    // Algthough the actual saving should be tested in the implementation
+    // file, we should test that the algorithm can run without issues
+    // Arrange
+    const size_t numDims = 3;
+    const size_t numBins = 5;
+    auto workspace =
+        Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace(
             1.0, numDims, numBins);
 
-        Mantid::VATES::SaveMDWorkspaceToVTK alg;
-        alg.setChild(true);
-        alg.setRethrows(true);
-        alg.initialize();
-        alg.setProperty("InputWorkspace", workspace);
-        alg.setProperty("Filename", "test_file_name");
-        alg.setProperty("Normalization", "AutoSelect");
-        alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
-        alg.setProperty("RecursionDepth", 5);
-
-        // Act + Assert
-        TSM_ASSERT_THROWS_ANYTHING(
-            "Four dimensional workspace should not be accepted", alg.execute());
-    }
+    std::string filename = "SaveMDWorkspaceToVTK_test_file.vts";
+    auto fullFilename = getTemporaryFilename(filename);
+    removeTemporaryFile(fullFilename);
 
-    void test_that_saves_MDHisto_without_issues_under_normal_conditions()
-    {
-        // Algthough the actual saving should be tested in the implementation
-        // file, we should test that the algorithm can run without issues
-        // Arrange
-        const size_t numDims = 3;
-        const size_t numBins = 5;
-        auto workspace = Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace(
-            1.0, numDims, numBins);
+    Mantid::VATES::SaveMDWorkspaceToVTK alg;
+    alg.setChild(true);
+    alg.setRethrows(true);
+    alg.initialize();
+    alg.setProperty("InputWorkspace", workspace);
+    alg.setProperty("Filename", fullFilename);
+    alg.setProperty("Normalization", "AutoSelect");
+    alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
+    alg.setProperty("RecursionDepth", 5);
 
-        std::string filename = "SaveMDWorkspaceToVTK_test_file.vts";
-        auto fullFilename = getTemporaryFilename(filename);
-        removeTemporaryFile(fullFilename);
-
-        Mantid::VATES::SaveMDWorkspaceToVTK alg;
-        alg.setChild(true);
-        alg.setRethrows(true);
-        alg.initialize();
-        alg.setProperty("InputWorkspace", workspace);
-        alg.setProperty("Filename", fullFilename);
-        alg.setProperty("Normalization", "AutoSelect");
-        alg.setProperty("ThresholdRange", "IgnoreZerosThresholdRange");
-        alg.setProperty("RecursionDepth", 5);
-
-        // Act and Assert
-        TSM_ASSERT_THROWS_NOTHING("Should save without any issues.",
-                                  alg.execute());
-
-        auto fileExists = doesFileExist(fullFilename);
-        TSM_ASSERT("The file should have been saved out", fileExists);
-
-        // Clean up
-        removeTemporaryFile(fullFilename);
-    }
+    // Act and Assert
+    TSM_ASSERT_THROWS_NOTHING("Should save without any issues.", alg.execute());
 
-private:
-    void verify_file_creation(std::string filename)
-    {
-        // Assert
-        auto fileExists = doesFileExist(filename);
-        TSM_ASSERT("The according file should have been saved out", fileExists);
-        // Cleanup
-        removeTemporaryFile(filename);
-    }
+    auto fileExists = doesFileExist(fullFilename);
+    TSM_ASSERT("The file should have been saved out", fileExists);
 
-    std::string getTemporaryFilename(std::string filenameWithoutPath) const
-    {
-        auto default_save_directory
-            = Mantid::Kernel::ConfigService::Instance().getString(
-                "defaultsave.directory");
-        std::string filenameWithPath(default_save_directory
-                                     + filenameWithoutPath);
-        return filenameWithPath;
-    }
+    // Clean up
+    removeTemporaryFile(fullFilename);
+  }
 
-    void removeTemporaryFile(std::string fileNameWithPath) const
-    {
-        if (Poco::File(fileNameWithPath).exists()) {
-            Poco::File(fileNameWithPath).remove();
-        }
+private:
+  void verify_file_creation(std::string filename) {
+    // Assert
+    auto fileExists = doesFileExist(filename);
+    TSM_ASSERT("The according file should have been saved out", fileExists);
+    // Cleanup
+    removeTemporaryFile(filename);
+  }
+
+  std::string getTemporaryFilename(std::string filenameWithoutPath) const {
+    auto default_save_directory =
+        Mantid::Kernel::ConfigService::Instance().getString(
+            "defaultsave.directory");
+    std::string filenameWithPath(default_save_directory + filenameWithoutPath);
+    return filenameWithPath;
+  }
+
+  void removeTemporaryFile(std::string fileNameWithPath) const {
+    if (Poco::File(fileNameWithPath).exists()) {
+      Poco::File(fileNameWithPath).remove();
     }
+  }
 
-    bool doesFileExist(std::string filename)
-    {
-        return Poco::File(filename).exists();
-    }
+  bool doesFileExist(std::string filename) {
+    return Poco::File(filename).exists();
+  }
 };
 #endif
diff --git a/Vates/VatesAPI/test/SingleWorkspaceProviderTest.h b/Vates/VatesAPI/test/SingleWorkspaceProviderTest.h
index bf1b3a81c0d69361e3ba93f55924abc70cb6b430..c97fb07b82fde3e5d7cf44b9e892b6621f72e5f6 100644
--- a/Vates/VatesAPI/test/SingleWorkspaceProviderTest.h
+++ b/Vates/VatesAPI/test/SingleWorkspaceProviderTest.h
@@ -9,8 +9,7 @@
 
 using namespace Mantid::DataObjects;
 
-class SingleWorkspaceProviderTest : public CxxTest::TestSuite
-{
+class SingleWorkspaceProviderTest : public CxxTest::TestSuite {
 public:
   void test_that_correctly_initiated_provider_can_provide() {
     // Arrange
@@ -39,7 +38,9 @@ public:
     // Act
     auto fetchedWorkspace = provider.fetchWorkspace("");
     // Assert
-    TSM_ASSERT("Should have a handle on a MDHistoWorkspace", boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(fetchedWorkspace));
+    TSM_ASSERT("Should have a handle on a MDHistoWorkspace",
+               boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(
+                   fetchedWorkspace));
   }
 };
 
diff --git a/Vates/VatesAPI/test/TimeStepToTimeStepTest.h b/Vates/VatesAPI/test/TimeStepToTimeStepTest.h
index c557096b211c3121d8474c6fcfec3243dc36c4c0..5919443e7675add2e2b1b7b440e5ef4b2a44d0bf 100644
--- a/Vates/VatesAPI/test/TimeStepToTimeStepTest.h
+++ b/Vates/VatesAPI/test/TimeStepToTimeStepTest.h
@@ -4,18 +4,17 @@
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/TimeStepToTimeStep.h"
 
-class TimeStepToTimeStepTest: public CxxTest::TestSuite
-{
+class TimeStepToTimeStepTest : public CxxTest::TestSuite {
 public:
-
-  void testArgumentEqualsProduct()
-  {
-    //Check that this type works as a compile-time proxy. Should do nothing with argument other than return it.
+  void testArgumentEqualsProduct() {
+    // Check that this type works as a compile-time proxy. Should do nothing
+    // with argument other than return it.
     Mantid::VATES::TimeStepToTimeStep proxy;
     int argument = 1;
-    TSM_ASSERT_EQUALS("The TimeStepToTimeStep proxy should return its own argument", argument, proxy(argument));
+    TSM_ASSERT_EQUALS(
+        "The TimeStepToTimeStep proxy should return its own argument", argument,
+        proxy(argument));
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/TimeToTimeStepTest.h b/Vates/VatesAPI/test/TimeToTimeStepTest.h
index a8fa680bdad9288fece043b4a7093411b9c4e3c4..711a960d64d96c231efdb5fdba59946034d8dbf0 100644
--- a/Vates/VatesAPI/test/TimeToTimeStepTest.h
+++ b/Vates/VatesAPI/test/TimeToTimeStepTest.h
@@ -4,86 +4,111 @@
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/TimeToTimeStep.h"
 
-class TimeToTimeStepTest: public CxxTest::TestSuite
-{
+class TimeToTimeStepTest : public CxxTest::TestSuite {
 public:
-
-  void testWithMaxMinGreaterThanZero()
-  {
+  void testWithMaxMinGreaterThanZero() {
     using namespace Mantid::VATES;
-    //Test that this type can perform rescaling from time to an index.
+    // Test that this type can perform rescaling from time to an index.
     double dimensionMin = 0;
     double dimensionMax = 200;
-    double t = 51; // just over 25% of the range, but after truncation, exactly 25%.
+    double t =
+        51; // just over 25% of the range, but after truncation, exactly 25%.
 
     int nBins = 100;
-    TimeToTimeStep converter = TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 25, converter(t))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 0, converter(dimensionMin))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", nBins, converter(dimensionMax))
+    TimeToTimeStep converter =
+        TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        25, converter(t))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.", 0,
+        converter(dimensionMin))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        nBins, converter(dimensionMax))
   }
 
-  void testWithMaxMinLessThanZero()
-  {
+  void testWithMaxMinLessThanZero() {
     using namespace Mantid::VATES;
-    //Test that this type can perform rescaling from time to an index.
+    // Test that this type can perform rescaling from time to an index.
     double dimensionMin = -201;
     double dimensionMax = -1;
-    double t = -51; // just over 75% of the range, but after truncation, exactly 75%.
+    double t =
+        -51; // just over 75% of the range, but after truncation, exactly 75%.
 
     int nBins = 100;
-    TimeToTimeStep converter = TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 75, converter(t))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 0, converter(dimensionMin))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", nBins, converter(dimensionMax))
+    TimeToTimeStep converter =
+        TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        75, converter(t))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.", 0,
+        converter(dimensionMin))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        nBins, converter(dimensionMax))
   }
 
-  void testWithMaxMinSpanningZero()
-  {
+  void testWithMaxMinSpanningZero() {
     using namespace Mantid::VATES;
-    //Test that this type can perform rescaling from time to an index.
+    // Test that this type can perform rescaling from time to an index.
     double dimensionMin = -100;
     double dimensionMax = 100;
-    double t = 51; // just over 75% of the range, but after truncation, exactly 75%.
+    double t =
+        51; // just over 75% of the range, but after truncation, exactly 75%.
 
     int nBins = 100;
-    TimeToTimeStep converter = TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 75, converter(t))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", 0, converter(dimensionMin))
-    TSM_ASSERT_EQUALS("The timeStep index has not been calculated properly. Wrong result.", nBins, converter(dimensionMax))
+    TimeToTimeStep converter =
+        TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        75, converter(t))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.", 0,
+        converter(dimensionMin))
+    TSM_ASSERT_EQUALS(
+        "The timeStep index has not been calculated properly. Wrong result.",
+        nBins, converter(dimensionMax))
   }
 
-  void testHandle_t_OutOfRange()
-  {
-    //Assume that t MUST sit somewhere between tmin and tmax. Zero out otherwise.
+  void testHandle_t_OutOfRange() {
+    // Assume that t MUST sit somewhere between tmin and tmax. Zero out
+    // otherwise.
     using namespace Mantid::VATES;
-    //Test that this type can perform rescaling from time to an index.
+    // Test that this type can perform rescaling from time to an index.
     double dimensionMin = 0;
     double dimensionMax = 100;
     int nBins = 200;
-    TimeToTimeStep converter = TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
-    TSM_ASSERT_EQUALS("T is greater is inside range. Should interpolate.", 60, converter(30));
-    TSM_ASSERT_EQUALS("T is greater than max. Should have zero'd out.", 0, converter(101));
-    TSM_ASSERT_EQUALS("T is less than max. Should have zero'd out.", 0, converter(-1));
+    TimeToTimeStep converter =
+        TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins);
+    TSM_ASSERT_EQUALS("T is greater is inside range. Should interpolate.", 60,
+                      converter(30));
+    TSM_ASSERT_EQUALS("T is greater than max. Should have zero'd out.", 0,
+                      converter(101));
+    TSM_ASSERT_EQUALS("T is less than max. Should have zero'd out.", 0,
+                      converter(-1));
   }
 
-  void testBadTimeRangeThrows()
-  {
+  void testBadTimeRangeThrows() {
     using namespace Mantid::VATES;
-    //Test that this type can perform rescaling from time to an index.
+    // Test that this type can perform rescaling from time to an index.
     double dimensionMin = 0;
     double dimensionMax = -200;
     int nBins = 100;
 
-    TSM_ASSERT_THROWS("Range is negative, should throw.", TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins), std::runtime_error);
+    TSM_ASSERT_THROWS(
+        "Range is negative, should throw.",
+        TimeToTimeStep::construct(dimensionMin, dimensionMax, nBins),
+        std::runtime_error);
   }
 
-  void testUseWithDefaultConstructorThrows()
-  {
-   Mantid::VATES::TimeToTimeStep converter;
-   TSM_ASSERT_THROWS("Constructing via default constructor should throw when used.", converter(1), std::runtime_error);
+  void testUseWithDefaultConstructorThrows() {
+    Mantid::VATES::TimeToTimeStep converter;
+    TSM_ASSERT_THROWS(
+        "Constructing via default constructor should throw when used.",
+        converter(1), std::runtime_error);
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h b/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h
index 1a68d91dd652abcc3e64f4975b0e71a7276a9715..b34062277c106157607c26668d74b6081e5d6c0b 100644
--- a/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h
+++ b/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h
@@ -7,35 +7,32 @@
 using namespace Mantid::VATES;
 using namespace Mantid;
 
-class UserDefinedThresholdRangeTest: public CxxTest::TestSuite
-{
-public :
-
-  void testConstructMaxLessThanMinThrows()
-  {
-    TSM_ASSERT_THROWS("Should not be able to construct with max less than min.", UserDefinedThresholdRange(2, 1), std::invalid_argument);
+class UserDefinedThresholdRangeTest : public CxxTest::TestSuite {
+public:
+  void testConstructMaxLessThanMinThrows() {
+    TSM_ASSERT_THROWS("Should not be able to construct with max less than min.",
+                      UserDefinedThresholdRange(2, 1), std::invalid_argument);
   }
- 
-  void testGetMaximum()
-  {
+
+  void testGetMaximum() {
     Mantid::VATES::UserDefinedThresholdRange userRangeCalculator(1, 2);
-    TSM_ASSERT_EQUALS("::getMaximum not wired-up correctly.", 2, userRangeCalculator.getMaximum());
+    TSM_ASSERT_EQUALS("::getMaximum not wired-up correctly.", 2,
+                      userRangeCalculator.getMaximum());
   }
 
-  void testGetMinimum()
-  {
+  void testGetMinimum() {
     Mantid::VATES::UserDefinedThresholdRange userRangeCalculator(1, 2);
-    TSM_ASSERT_EQUALS("::getMinimum not wired-up correctly.", 1, userRangeCalculator.getMinimum());
+    TSM_ASSERT_EQUALS("::getMinimum not wired-up correctly.", 1,
+                      userRangeCalculator.getMinimum());
   }
 
-  void testHasCalculated()
-  {
+  void testHasCalculated() {
     Mantid::VATES::UserDefinedThresholdRange userRangeCalculator(1, 2);
-    TS_ASSERT(userRangeCalculator.hasCalculated()); //Should return true no matter what!
+    TS_ASSERT(userRangeCalculator
+                  .hasCalculated()); // Should return true no matter what!
   }
 
-  void testClone()
-  {
+  void testClone() {
     Mantid::VATES::UserDefinedThresholdRange original(1, 2);
     auto cloned = std::unique_ptr<Mantid::VATES::UserDefinedThresholdRange>(
         original.clone());
@@ -44,24 +41,26 @@ public :
     TS_ASSERT_EQUALS(original.getMinimum(), cloned->getMinimum());
   }
 
-  void testInRange()
-  {
+  void testInRange() {
     Mantid::VATES::UserDefinedThresholdRange userRangeCalculator(1, 2);
-    //Boundary Value Analysis
+    // Boundary Value Analysis
     signal_t just_above_upper_boundary = 2.001;
     signal_t just_below_lower_boundary = 0.999;
     signal_t on_lower_boundary = 1;
     signal_t on_upper_boundary = 2;
-    signal_t just_below_upper_boundary =1.999;
+    signal_t just_below_upper_boundary = 1.999;
     signal_t just_above_lower_boundary = 1.001;
-    TS_ASSERT_EQUALS(false, userRangeCalculator.inRange(just_above_upper_boundary));
-    TS_ASSERT_EQUALS(false, userRangeCalculator.inRange(just_below_lower_boundary));
+    TS_ASSERT_EQUALS(false,
+                     userRangeCalculator.inRange(just_above_upper_boundary));
+    TS_ASSERT_EQUALS(false,
+                     userRangeCalculator.inRange(just_below_lower_boundary));
     TS_ASSERT_EQUALS(true, userRangeCalculator.inRange(on_lower_boundary));
     TS_ASSERT_EQUALS(true, userRangeCalculator.inRange(on_upper_boundary));
-    TS_ASSERT_EQUALS(true, userRangeCalculator.inRange(just_below_upper_boundary));
-    TS_ASSERT_EQUALS(true, userRangeCalculator.inRange(just_above_lower_boundary));
+    TS_ASSERT_EQUALS(true,
+                     userRangeCalculator.inRange(just_below_upper_boundary));
+    TS_ASSERT_EQUALS(true,
+                     userRangeCalculator.inRange(just_above_lower_boundary));
   }
-
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h b/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
index e9d95c78d7d46b17c343e4039aad91e822135551..5039a9013a4e270375cea1ec329fe52a0493a7b6 100644
--- a/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
+++ b/Vates/VatesAPI/test/VatesKnowledgeSerializerTest.h
@@ -15,140 +15,154 @@
 
 using namespace Mantid::VATES;
 
-class VatesKnowledgeSerializerTest: public CxxTest::TestSuite
-{
+class VatesKnowledgeSerializerTest : public CxxTest::TestSuite {
 private:
-
-  //Helper class
-  class MockImplicitFunction: public Mantid::Geometry::MDImplicitFunction
-  {
+  // Helper class
+  class MockImplicitFunction : public Mantid::Geometry::MDImplicitFunction {
   public:
-    MOCK_METHOD1(isPointContained, bool(const Mantid::coord_t* pPoint));
-    MOCK_METHOD1(isPointContained, bool(const std::vector<Mantid::coord_t>&));
-    MOCK_METHOD1(isPointContained, bool(const Mantid::Kernel::VMD&));
+    MOCK_METHOD1(isPointContained, bool(const Mantid::coord_t *pPoint));
+    MOCK_METHOD1(isPointContained, bool(const std::vector<Mantid::coord_t> &));
+    MOCK_METHOD1(isPointContained, bool(const Mantid::Kernel::VMD &));
     MOCK_CONST_METHOD0(getName, std::string());
     MOCK_CONST_METHOD0(toXMLString, std::string());
     ~MockImplicitFunction() override {}
   };
 
-//Test methods
+  // Test methods
 
 public:
-
-void testNoWorkspaceThrows()
-{
-  VatesKnowledgeSerializer generator;
-  Mantid::Geometry::MDImplicitFunction_sptr impFunction(new MockImplicitFunction);
-  generator.setImplicitFunction(impFunction);
-  TSM_ASSERT_THROWS("Cannot generate the xml without the workspace", generator.createXMLString(), std::runtime_error);
-}
-
-void testNoLocationDoesNotThrow()
-{
-  MockIMDWorkspace* pWorkspace = new MockIMDWorkspace;
-  Mantid::API::IMDWorkspace_sptr workspace(pWorkspace);
-  Mantid::API::AnalysisDataService::Instance().addOrReplace("someName",workspace);
-
-  MockImplicitFunction* pImpFunction = new MockImplicitFunction;
-  EXPECT_CALL(*pImpFunction, toXMLString()).Times(1).WillRepeatedly(testing::Return("<ImplicitFunction/>"));
-  Mantid::Geometry::MDImplicitFunction_sptr impFunction(pImpFunction);
-  
-  VatesKnowledgeSerializer generator; //Location is not required.
-  generator.setImplicitFunction(impFunction);
-  generator.setWorkspace(workspace);
-
-  TSM_ASSERT_THROWS_NOTHING("The location is not mandatory, should not throw", generator.createXMLString());
-  Mantid::API::AnalysisDataService::Instance().clear();
-}
-
-void testNoNameThrows()
-{
-  Mantid::Geometry::MDImplicitFunction_sptr impFunction(new MockImplicitFunction);
-  MockIMDWorkspace* pWorkspace = new MockIMDWorkspace;
-  boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace(pWorkspace);
-  VatesKnowledgeSerializer generator;
-  generator.setImplicitFunction(impFunction);
-  generator.setWorkspace(workspace);
-
-  TSM_ASSERT_THROWS("Cannot create the xml without the workspace name", generator.createXMLString(),
-      std::runtime_error);
-}
-
-
-void testCreateXMLWithComponents() //Uses individual setters for geometry, location and name.
-{
-  MockImplicitFunction* pImpFunction = new MockImplicitFunction;
-  EXPECT_CALL(*pImpFunction, toXMLString()).Times(1).WillRepeatedly(testing::Return("<ImplicitFunction/>"));
-  Mantid::Geometry::MDImplicitFunction_sptr impFunction(pImpFunction);
-
-  VatesKnowledgeSerializer generator;
-  //Apply setters.
-  generator.setImplicitFunction(impFunction);
-  generator.setWorkspaceName("name");
-  generator.setGeometryXML("<DimensionSet/>");
-
-  std::string xml = generator.createXMLString();
-
-  TSM_ASSERT_EQUALS("The xml has been created, but is incorrect.", "<MDInstruction><MDWorkspaceName>name</MDWorkspaceName><DimensionSet/><ImplicitFunction/></MDInstruction>" ,xml)
-}
-
-void testCreateXMLWithoutFunction()
-{
-  VatesKnowledgeSerializer generator;
-  //Apply setters.
-  generator.setWorkspaceName("name");
-  generator.setGeometryXML("<DimensionSet/>");
-
-  std::string xml = generator.createXMLString();
-  TSM_ASSERT_EQUALS("The xml has been created without a function incorrectly", "<MDInstruction><MDWorkspaceName>name</MDWorkspaceName><DimensionSet/></MDInstruction>", xml);
-}
-
-void testGetGeometryXML()
-{
-  VatesKnowledgeSerializer generator;
-  generator.setWorkspaceName("name");
-  std::string dimensionXMLString = "<DimensionSet/>";
-  generator.setGeometryXML(dimensionXMLString);
-
-  std::string xml = generator.getWorkspaceGeometry();
-  TSM_ASSERT_EQUALS("The geometry xml fetched is not the same as that provided", dimensionXMLString, generator.getWorkspaceGeometry());
-}
-
-void testHasFunction()
-{
-  VatesKnowledgeSerializer withoutFunction;
-  VatesKnowledgeSerializer withFunction;
-  Mantid::Geometry::MDImplicitFunction_sptr impFunction(new MockImplicitFunction);
-  withFunction.setImplicitFunction(impFunction);
-
-  TSM_ASSERT_EQUALS("A function has not been provided. ::hasFunctionInfo() should return false.", false,  withoutFunction.hasFunctionInfo());
-  TSM_ASSERT_EQUALS("A function has been provided. ::hasFunctionInfo() should return true.", true, withFunction.hasFunctionInfo());
-}
-
-void testHasGeometryInfoWithoutGeometry()
-{
-  //Note that functions do not apply to this test set.
-  VatesKnowledgeSerializer withoutGeometry;
-  withoutGeometry.setWorkspaceName("-");
-  TSM_ASSERT_EQUALS("No Geometry provided. ::hasGeometryInfo() should return false.", false, withoutGeometry.hasGeometryInfo());
-}
-
-void testHasGeometryInfoWithoutWSName()
-{
-  VatesKnowledgeSerializer withoutWSName;
-  withoutWSName.setGeometryXML("-");
-  TSM_ASSERT_EQUALS("No WS name provided. ::hasGeometryInfo() should return false.", false, withoutWSName.hasGeometryInfo());
-}
-
-void testHasGeometryAndWSInfo()
-{
-  VatesKnowledgeSerializer withFullGeometryAndWSInfo;
-  withFullGeometryAndWSInfo.setGeometryXML("-");
-  withFullGeometryAndWSInfo.setWorkspaceName("-");
-  TSM_ASSERT_EQUALS("All geometry and ws information has been provided. ::hasGeometryInfo() should return true.", true, withFullGeometryAndWSInfo.hasGeometryInfo());
-}
-
-
+  void testNoWorkspaceThrows() {
+    VatesKnowledgeSerializer generator;
+    Mantid::Geometry::MDImplicitFunction_sptr impFunction(
+        new MockImplicitFunction);
+    generator.setImplicitFunction(impFunction);
+    TSM_ASSERT_THROWS("Cannot generate the xml without the workspace",
+                      generator.createXMLString(), std::runtime_error);
+  }
+
+  void testNoLocationDoesNotThrow() {
+    MockIMDWorkspace *pWorkspace = new MockIMDWorkspace;
+    Mantid::API::IMDWorkspace_sptr workspace(pWorkspace);
+    Mantid::API::AnalysisDataService::Instance().addOrReplace("someName",
+                                                              workspace);
+
+    MockImplicitFunction *pImpFunction = new MockImplicitFunction;
+    EXPECT_CALL(*pImpFunction, toXMLString())
+        .Times(1)
+        .WillRepeatedly(testing::Return("<ImplicitFunction/>"));
+    Mantid::Geometry::MDImplicitFunction_sptr impFunction(pImpFunction);
+
+    VatesKnowledgeSerializer generator; // Location is not required.
+    generator.setImplicitFunction(impFunction);
+    generator.setWorkspace(workspace);
+
+    TSM_ASSERT_THROWS_NOTHING("The location is not mandatory, should not throw",
+                              generator.createXMLString());
+    Mantid::API::AnalysisDataService::Instance().clear();
+  }
+
+  void testNoNameThrows() {
+    Mantid::Geometry::MDImplicitFunction_sptr impFunction(
+        new MockImplicitFunction);
+    MockIMDWorkspace *pWorkspace = new MockIMDWorkspace;
+    boost::shared_ptr<const Mantid::API::IMDWorkspace> workspace(pWorkspace);
+    VatesKnowledgeSerializer generator;
+    generator.setImplicitFunction(impFunction);
+    generator.setWorkspace(workspace);
+
+    TSM_ASSERT_THROWS("Cannot create the xml without the workspace name",
+                      generator.createXMLString(), std::runtime_error);
+  }
+
+  void testCreateXMLWithComponents() // Uses individual setters for geometry,
+                                     // location and name.
+  {
+    MockImplicitFunction *pImpFunction = new MockImplicitFunction;
+    EXPECT_CALL(*pImpFunction, toXMLString())
+        .Times(1)
+        .WillRepeatedly(testing::Return("<ImplicitFunction/>"));
+    Mantid::Geometry::MDImplicitFunction_sptr impFunction(pImpFunction);
+
+    VatesKnowledgeSerializer generator;
+    // Apply setters.
+    generator.setImplicitFunction(impFunction);
+    generator.setWorkspaceName("name");
+    generator.setGeometryXML("<DimensionSet/>");
+
+    std::string xml = generator.createXMLString();
+
+    TSM_ASSERT_EQUALS("The xml has been created, but is incorrect.",
+                      "<MDInstruction><MDWorkspaceName>name</"
+                      "MDWorkspaceName><DimensionSet/><ImplicitFunction/></"
+                      "MDInstruction>",
+                      xml)
+  }
+
+  void testCreateXMLWithoutFunction() {
+    VatesKnowledgeSerializer generator;
+    // Apply setters.
+    generator.setWorkspaceName("name");
+    generator.setGeometryXML("<DimensionSet/>");
+
+    std::string xml = generator.createXMLString();
+    TSM_ASSERT_EQUALS("The xml has been created without a function incorrectly",
+                      "<MDInstruction><MDWorkspaceName>name</"
+                      "MDWorkspaceName><DimensionSet/></MDInstruction>",
+                      xml);
+  }
+
+  void testGetGeometryXML() {
+    VatesKnowledgeSerializer generator;
+    generator.setWorkspaceName("name");
+    std::string dimensionXMLString = "<DimensionSet/>";
+    generator.setGeometryXML(dimensionXMLString);
+
+    std::string xml = generator.getWorkspaceGeometry();
+    TSM_ASSERT_EQUALS(
+        "The geometry xml fetched is not the same as that provided",
+        dimensionXMLString, generator.getWorkspaceGeometry());
+  }
+
+  void testHasFunction() {
+    VatesKnowledgeSerializer withoutFunction;
+    VatesKnowledgeSerializer withFunction;
+    Mantid::Geometry::MDImplicitFunction_sptr impFunction(
+        new MockImplicitFunction);
+    withFunction.setImplicitFunction(impFunction);
+
+    TSM_ASSERT_EQUALS("A function has not been provided. ::hasFunctionInfo() "
+                      "should return false.",
+                      false, withoutFunction.hasFunctionInfo());
+    TSM_ASSERT_EQUALS(
+        "A function has been provided. ::hasFunctionInfo() should return true.",
+        true, withFunction.hasFunctionInfo());
+  }
+
+  void testHasGeometryInfoWithoutGeometry() {
+    // Note that functions do not apply to this test set.
+    VatesKnowledgeSerializer withoutGeometry;
+    withoutGeometry.setWorkspaceName("-");
+    TSM_ASSERT_EQUALS(
+        "No Geometry provided. ::hasGeometryInfo() should return false.", false,
+        withoutGeometry.hasGeometryInfo());
+  }
+
+  void testHasGeometryInfoWithoutWSName() {
+    VatesKnowledgeSerializer withoutWSName;
+    withoutWSName.setGeometryXML("-");
+    TSM_ASSERT_EQUALS(
+        "No WS name provided. ::hasGeometryInfo() should return false.", false,
+        withoutWSName.hasGeometryInfo());
+  }
+
+  void testHasGeometryAndWSInfo() {
+    VatesKnowledgeSerializer withFullGeometryAndWSInfo;
+    withFullGeometryAndWSInfo.setGeometryXML("-");
+    withFullGeometryAndWSInfo.setWorkspaceName("-");
+    TSM_ASSERT_EQUALS("All geometry and ws information has been provided. "
+                      "::hasGeometryInfo() should return true.",
+                      true, withFullGeometryAndWSInfo.hasGeometryInfo());
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/ViewFrustumTest.h b/Vates/VatesAPI/test/ViewFrustumTest.h
index e4f2357e2d4963f0fb31a93563ea840d9fd19702..2794bc765e311d29cf181821e33ff51f7159eb42 100644
--- a/Vates/VatesAPI/test/ViewFrustumTest.h
+++ b/Vates/VatesAPI/test/ViewFrustumTest.h
@@ -6,11 +6,9 @@
 
 using namespace Mantid::VATES;
 
-class ViewFrustumTest: public CxxTest::TestSuite
-{
+class ViewFrustumTest : public CxxTest::TestSuite {
 public:
-  void testThatExtentsAreFoundForStandardFrustum()
-  {
+  void testThatExtentsAreFoundForStandardFrustum() {
     // Arrange
     // Create a standard cube
     LeftPlane left(1.0, 0.0, 0.0, 1.0);
@@ -20,26 +18,33 @@ public:
     TopPlane top(0.0, -1.0, 0.0, 1.0);
 
     FarPlane far(0.0, 0.0, 1.0, 1.0);
-    NearPlane near(0.0, 0.0, -1.0,1.0);
+    NearPlane near(0.0, 0.0, -1.0, 1.0);
 
     ViewFrustum frustum(left, right, bottom, top, far, near);
 
-    //Act 
+    // Act
     std::vector<std::pair<double, double>> extents;
-    TSM_ASSERT_THROWS_NOTHING("Frustum is well defined, should not throw.", extents = frustum.toExtents());
-
-    //Assert
-    TSM_ASSERT_EQUALS("Extents should exist for x, y and z.", 3, extents.size());
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmin = -1", -1.0, extents[0].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmax = 1", 1.0, extents[0].second);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", -1.0, extents[1].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", 1.0, extents[1].second);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmin = -1", -1.0, extents[2].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmax = 1", 1.0, extents[2].second);
+    TSM_ASSERT_THROWS_NOTHING("Frustum is well defined, should not throw.",
+                              extents = frustum.toExtents());
+
+    // Assert
+    TSM_ASSERT_EQUALS("Extents should exist for x, y and z.", 3,
+                      extents.size());
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmin = -1", -1.0,
+                      extents[0].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmax = 1", 1.0,
+                      extents[0].second);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", -1.0,
+                      extents[1].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", 1.0,
+                      extents[1].second);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmin = -1", -1.0,
+                      extents[2].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmax = 1", 1.0,
+                      extents[2].second);
   }
 
-  void testThatExtentsAreFoundForFrustumWithRotation()
-  {
+  void testThatExtentsAreFoundForFrustumWithRotation() {
     // Arrange
     // Create skewed cube
     LeftPlane left(1.0, -0.5, 0.0, 1.0);
@@ -49,28 +54,36 @@ public:
     TopPlane top(-1.0, -0.5, 0.0, 1.0);
 
     FarPlane far(0.0, 0.0, 1.0, 1.0);
-    NearPlane near(0.0, 0.0, -1.0,1.0);
+    NearPlane near(0.0, 0.0, -1.0, 1.0);
 
     ViewFrustum frustum(left, right, bottom, top, far, near);
 
-    //Act 
+    // Act
     std::vector<std::pair<double, double>> extents;
-    TSM_ASSERT_THROWS_NOTHING("Frustum is well defined, should not throw.", extents = frustum.toExtents());
-
-    //Assert
-    TSM_ASSERT_EQUALS("Extents should exist for x, y and z.", 3, extents.size());
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmin = -1", -1.0, extents[0].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmax = 1", 1.0, extents[0].second);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", -2.0, extents[1].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", 2.0, extents[1].second);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmin = -1", -1.0, extents[2].first);
-    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmax = 1", 1.0, extents[2].second);
+    TSM_ASSERT_THROWS_NOTHING("Frustum is well defined, should not throw.",
+                              extents = frustum.toExtents());
+
+    // Assert
+    TSM_ASSERT_EQUALS("Extents should exist for x, y and z.", 3,
+                      extents.size());
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmin = -1", -1.0,
+                      extents[0].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have xmax = 1", 1.0,
+                      extents[0].second);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", -2.0,
+                      extents[1].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have ymin = -1", 2.0,
+                      extents[1].second);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmin = -1", -1.0,
+                      extents[2].first);
+    TSM_ASSERT_EQUALS("Frustum is well defined and should have zmax = 1", 1.0,
+                      extents[2].second);
   }
 
-  void testThatWrongPlanesThrowErrors()
-  {
+  void testThatWrongPlanesThrowErrors() {
     // Arrange
-    // Just have one plane type. This should fail the calculation of intersection points 
+    // Just have one plane type. This should fail the calculation of
+    // intersection points
     LeftPlane left(1.0, -0.5, 0.0, 1.0);
     RightPlane right(1.0, -0.5, 0.0, 1.0);
 
@@ -82,10 +95,10 @@ public:
 
     ViewFrustum frustum(left, right, bottom, top, far, near);
 
-    //Assert
-    TSM_ASSERT_THROWS("Frustum is not well defined, should throw error",frustum.toExtents(), std::runtime_error);
+    // Assert
+    TSM_ASSERT_THROWS("Frustum is not well defined, should throw error",
+                      frustum.toExtents(), std::runtime_error);
   }
-
 };
 
 #endif
\ No newline at end of file
diff --git a/Vates/VatesAPI/test/vtkDataSetFactoryTest.h b/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
index e226283abb6c1105484e997a34ee694bcb41026c..4c927600c67330ffeee9d8041442563760b1e683 100644
--- a/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetFactoryTest.h
@@ -21,20 +21,15 @@ using namespace Mantid::DataObjects;
 using namespace testing;
 using Mantid::VATES::vtkDataSetFactory;
 
-class vtkDataSetFactoryTest : public CxxTest::TestSuite
-{
+class vtkDataSetFactoryTest : public CxxTest::TestSuite {
 private:
-
   /// Mocked helper type
-  class MockvtkDataSetFactory : public Mantid::VATES::vtkDataSetFactory
-  {
+  class MockvtkDataSetFactory : public Mantid::VATES::vtkDataSetFactory {
   public:
     MOCK_CONST_METHOD1(
         create, vtkSmartPointer<vtkDataSet>(Mantid::VATES::ProgressAction &));
-    MOCK_METHOD1(initialize,
-      void(boost::shared_ptr<Mantid::API::Workspace>));
-    MOCK_CONST_METHOD0(validate,
-      void());
+    MOCK_METHOD1(initialize, void(boost::shared_ptr<Mantid::API::Workspace>));
+    MOCK_CONST_METHOD0(validate, void());
     MOCK_CONST_METHOD0(getFactoryTypeName, std::string());
     void setSuccessorConcrete(std::unique_ptr<vtkDataSetFactory> pSuccessor) {
       vtkDataSetFactory::setSuccessor(pSuccessor);
@@ -44,9 +39,8 @@ private:
     }
   };
 
-  ///Fake helper type.
-  class FakeProgressAction : public Mantid::VATES::ProgressAction
-  {
+  /// Fake helper type.
+  class FakeProgressAction : public Mantid::VATES::ProgressAction {
     void eventRaised(double) override {}
   };
 
@@ -84,8 +78,7 @@ public:
     TS_ASSERT(testing::Mock::VerifyAndClearExpectations(successor));
   }
 
-  void testEnumValues()
-  {
+  void testEnumValues() {
     using Mantid::VATES::vtkDataSetFactory;
     int oneD = vtkDataSetFactory::OneDimensional;
     int twoD = vtkDataSetFactory::TwoDimensional;
@@ -97,14 +90,12 @@ public:
     TS_ASSERT_EQUALS(4, fourD);
   }
 
-  void testCheckDimensionalityByDefault()
-  {
+  void testCheckDimensionalityByDefault() {
     MockvtkDataSetFactory factory;
     TS_ASSERT(factory.doesCheckDimensionality());
   }
 
-  void testSetCheckDimensionality()
-  {
+  void testSetCheckDimensionality() {
     MockvtkDataSetFactory factory;
     factory.setCheckDimensionality(false);
     TS_ASSERT(!factory.doesCheckDimensionality());
@@ -112,8 +103,7 @@ public:
     TS_ASSERT(factory.doesCheckDimensionality());
   }
 
-  void testOneStepCreate()
-  {
+  void testOneStepCreate() {
     FakeProgressAction progressUpdater;
 
     MockvtkDataSetFactory factory;
@@ -122,13 +112,15 @@ public:
         .Times(1)
         .WillOnce(Return(vtkSmartPointer<vtkStructuredGrid>::New()));
 
-    IMDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    IMDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
     auto product = factory.oneStepCreate(ws_sptr, progressUpdater);
     TS_ASSERT(product != nullptr);
-    TSM_ASSERT_EQUALS("Output not wired up correctly to ::create() method", "vtkStructuredGrid", std::string(product->GetClassName()));
+    TSM_ASSERT_EQUALS("Output not wired up correctly to ::create() method",
+                      "vtkStructuredGrid",
+                      std::string(product->GetClassName()));
     TS_ASSERT(Mock::VerifyAndClearExpectations(&factory));
   }
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h b/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h
index c08b849c060d6bb86ce7c800dd783074304fb0bb..6ef33796ad3bc2d566a244ddbde4e35bae10e407 100644
--- a/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h
@@ -13,206 +13,233 @@
 
 #include "MantidVatesAPI/VatesXMLDefinitions.h"
 
-class vtkDataSetToGeometryTest : public CxxTest::TestSuite
-{
+class vtkDataSetToGeometryTest : public CxxTest::TestSuite {
 
 private:
-
-// Helper method. Creates xml required as input for geometry. Allows mappings to be specified via function parameters.
- static std::string constructXML(const std::string& xDimensionIdMapping, const std::string& yDimensionIdMapping, const std::string& zDimensionIdMapping, const std::string& tDimensionIdMapping)
-{
+  // Helper method. Creates xml required as input for geometry. Allows mappings
+  // to be specified via function parameters.
+  static std::string constructXML(const std::string &xDimensionIdMapping,
+                                  const std::string &yDimensionIdMapping,
+                                  const std::string &zDimensionIdMapping,
+                                  const std::string &tDimensionIdMapping) {
     return std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>") +
-"<MDInstruction>" +
-  "<DimensionSet>" +
-    "<Dimension ID=\"en\">" +
-      "<Name>Energy</Name>" +
-      "<UpperBounds>150</UpperBounds>" +
-      "<LowerBounds>0</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-    "</Dimension>" +
-    "<Dimension ID=\"qx\">" +
-      "<Name>Qx</Name>" +
-      "<UpperBounds>5</UpperBounds>" +
-      "<LowerBounds>-1.5</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-    "</Dimension>" +
-    "<Dimension ID=\"qy\">" +
-      "<Name>Qy</Name>" +
-      "<UpperBounds>6.6</UpperBounds>" +
-      "<LowerBounds>-6.6</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-    "</Dimension>" +
-    "<Dimension ID=\"qz\">" +
-      "<Name>Qz</Name>" +
-      "<UpperBounds>6.6</UpperBounds>" +
-      "<LowerBounds>-6.6</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-    "</Dimension>" +
-    "<Dimension ID=\"other\">" +
-      "<Name>Other</Name>" +
-      "<UpperBounds>6.6</UpperBounds>" +
-      "<LowerBounds>-6.6</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-    "</Dimension>" +
-    "<XDimension>" +
-      "<RefDimensionId>" +
-      xDimensionIdMapping +
-      "</RefDimensionId>" +
-    "</XDimension>" +
-    "<YDimension>" +
-      "<RefDimensionId>" +
-      yDimensionIdMapping +
-      "</RefDimensionId>" +
-    "</YDimension>" +
-    "<ZDimension>" +
-      "<RefDimensionId>" + 
-      zDimensionIdMapping +
-      "</RefDimensionId>" +
-    "</ZDimension>" +
-    "<TDimension>" +
-      "<RefDimensionId>" +
-      tDimensionIdMapping +
-      "</RefDimensionId>" +
-    "</TDimension>" +
-  "</DimensionSet>" +
-"</MDInstruction>";
+           "<MDInstruction>" + "<DimensionSet>" + "<Dimension ID=\"en\">" +
+           "<Name>Energy</Name>" + "<UpperBounds>150</UpperBounds>" +
+           "<LowerBounds>0</LowerBounds>" + "<NumberOfBins>5</NumberOfBins>" +
+           "</Dimension>" + "<Dimension ID=\"qx\">" + "<Name>Qx</Name>" +
+           "<UpperBounds>5</UpperBounds>" + "<LowerBounds>-1.5</LowerBounds>" +
+           "<NumberOfBins>5</NumberOfBins>" + "</Dimension>" +
+           "<Dimension ID=\"qy\">" + "<Name>Qy</Name>" +
+           "<UpperBounds>6.6</UpperBounds>" +
+           "<LowerBounds>-6.6</LowerBounds>" +
+           "<NumberOfBins>5</NumberOfBins>" + "</Dimension>" +
+           "<Dimension ID=\"qz\">" + "<Name>Qz</Name>" +
+           "<UpperBounds>6.6</UpperBounds>" +
+           "<LowerBounds>-6.6</LowerBounds>" +
+           "<NumberOfBins>5</NumberOfBins>" + "</Dimension>" +
+           "<Dimension ID=\"other\">" + "<Name>Other</Name>" +
+           "<UpperBounds>6.6</UpperBounds>" +
+           "<LowerBounds>-6.6</LowerBounds>" +
+           "<NumberOfBins>5</NumberOfBins>" + "</Dimension>" + "<XDimension>" +
+           "<RefDimensionId>" + xDimensionIdMapping + "</RefDimensionId>" +
+           "</XDimension>" + "<YDimension>" + "<RefDimensionId>" +
+           yDimensionIdMapping + "</RefDimensionId>" + "</YDimension>" +
+           "<ZDimension>" + "<RefDimensionId>" + zDimensionIdMapping +
+           "</RefDimensionId>" + "</ZDimension>" + "<TDimension>" +
+           "<RefDimensionId>" + tDimensionIdMapping + "</RefDimensionId>" +
+           "</TDimension>" + "</DimensionSet>" + "</MDInstruction>";
   }
 
-
-static vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id)
-{
-  vtkFieldData* fieldData = vtkFieldData::New();
-  vtkNew<vtkCharArray> charArray;
-  charArray->SetName(id.c_str());
-  charArray->Allocate(100);
-  for(unsigned int i = 0; i < testData.size(); i++)
-  {
-    char cNextVal = testData.at(i);
-    if(int(cNextVal) > 1)
-    {
-      charArray->InsertNextValue(cNextVal);
-
+  static vtkFieldData *createFieldDataWithCharArray(std::string testData,
+                                                    std::string id) {
+    vtkFieldData *fieldData = vtkFieldData::New();
+    vtkNew<vtkCharArray> charArray;
+    charArray->SetName(id.c_str());
+    charArray->Allocate(100);
+    for (unsigned int i = 0; i < testData.size(); i++) {
+      char cNextVal = testData.at(i);
+      if (int(cNextVal) > 1) {
+        charArray->InsertNextValue(cNextVal);
+      }
     }
+    fieldData->AddArray(charArray.GetPointer());
+    return fieldData;
   }
-  fieldData->AddArray(charArray.GetPointer());
-  return fieldData;
-}
 
 public:
-
-  void testNoDimensionMappings()
-  {
+  void testNoDimensionMappings() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // No mappings
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("", "", "", ""),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // No mappings
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-    
-    TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension mappings are absent. No dimension should have been set.", !xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension());
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 5, xmlParser.getNonMappedDimensions().size());
+
+    TSM_ASSERT(
+        "X dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasXDimension());
+    TSM_ASSERT(
+        "Y dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasYDimension());
+    TSM_ASSERT(
+        "Z dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasZDimension());
+    TSM_ASSERT(
+        "T dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasTDimension());
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 5,
+                      xmlParser.getNonMappedDimensions().size());
   }
 
-  void testGetXDimension()
-  {
+  void testGetXDimension() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("en", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only x
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("en", "", "", ""),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // Only x
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-    
-    TSM_ASSERT("X dimension should have been extracted via its mappings", xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension mappings are absent. No dimension should have been set.", !xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension());
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size());
+
+    TSM_ASSERT("X dimension should have been extracted via its mappings",
+               xmlParser.hasXDimension());
+    TSM_ASSERT(
+        "Y dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasYDimension());
+    TSM_ASSERT(
+        "Z dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasZDimension());
+    TSM_ASSERT(
+        "T dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasTDimension());
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4,
+                      xmlParser.getNonMappedDimensions().size());
   }
 
-  void testGetYDimension()
-  {
+  void testGetYDimension() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("", "en", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only y
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("", "en", "", ""),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // Only y
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-   
-    TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension should have been extracted via its mappings", xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension());
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size());
+
+    TSM_ASSERT(
+        "X dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasXDimension());
+    TSM_ASSERT("Y dimension should have been extracted via its mappings",
+               xmlParser.hasYDimension());
+    TSM_ASSERT(
+        "Z dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasZDimension());
+    TSM_ASSERT(
+        "T dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasTDimension());
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4,
+                      xmlParser.getNonMappedDimensions().size());
   }
 
-  void testGetZDimension()
-  {
+  void testGetZDimension() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "en", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only z
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("", "", "en", ""),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // Only z
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-   
-    TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension mappings are absent. No dimension should have been set.", !xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension should have been extracted via its mappings", xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension());
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size());
+
+    TSM_ASSERT(
+        "X dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasXDimension());
+    TSM_ASSERT(
+        "Y dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasYDimension());
+    TSM_ASSERT("Z dimension should have been extracted via its mappings",
+               xmlParser.hasZDimension());
+    TSM_ASSERT(
+        "T dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasTDimension());
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4,
+                      xmlParser.getNonMappedDimensions().size());
   }
 
-  void testGetTDimension()
-  {
+  void testGetTDimension() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", "en"), Mantid::VATES::XMLDefinitions::metaDataId())); // Only t
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("", "", "", "en"),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // Only t
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-   
-    TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension mappings are absent. No dimension should have been set.", !xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension should have been extracted via its mappings", xmlParser.hasTDimension());
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size());
+
+    TSM_ASSERT(
+        "X dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasXDimension());
+    TSM_ASSERT(
+        "Y dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasYDimension());
+    TSM_ASSERT(
+        "Z dimension mappings are absent. No dimension should have been set.",
+        !xmlParser.hasZDimension());
+    TSM_ASSERT("T dimension should have been extracted via its mappings",
+               xmlParser.hasTDimension());
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4,
+                      xmlParser.getNonMappedDimensions().size());
   }
 
-  void testAllDimensions()
-  {
+  void testAllDimensions() {
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> data;
-    data->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId())); // All configured.
-   
+    data->SetFieldData(createFieldDataWithCharArray(
+        constructXML("qy", "qx", "en", "qz"),
+        Mantid::VATES::XMLDefinitions::metaDataId())); // All configured.
+
     vtkDataSetToGeometry xmlParser(data.GetPointer());
     xmlParser.execute();
-   
-    TSM_ASSERT("X dimension should have been extracted via its mappings", xmlParser.hasXDimension());
-    TSM_ASSERT("Y dimension should have been extracted via its mappings", xmlParser.hasYDimension());
-    TSM_ASSERT("Z dimension should have been extracted via its mappings", xmlParser.hasZDimension());
-    TSM_ASSERT("T dimension should have been extracted via its mappings", xmlParser.hasTDimension());
-
-    TSM_ASSERT_EQUALS("Wrong mapping for XDimension", "qy", xmlParser.getXDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Wrong mapping for YDimension", "qx", xmlParser.getYDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Wrong mapping for ZDimension", "en", xmlParser.getZDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Wrong mapping for TDimension", "qz", xmlParser.getTDimension()->getDimensionId());
-
-    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 1, xmlParser.getNonMappedDimensions().size());
-    TSM_ASSERT_EQUALS("Wrong non-mapped dimension found", "other" ,xmlParser.getNonMappedDimensions()[0]->getDimensionId());
+
+    TSM_ASSERT("X dimension should have been extracted via its mappings",
+               xmlParser.hasXDimension());
+    TSM_ASSERT("Y dimension should have been extracted via its mappings",
+               xmlParser.hasYDimension());
+    TSM_ASSERT("Z dimension should have been extracted via its mappings",
+               xmlParser.hasZDimension());
+    TSM_ASSERT("T dimension should have been extracted via its mappings",
+               xmlParser.hasTDimension());
+
+    TSM_ASSERT_EQUALS("Wrong mapping for XDimension", "qy",
+                      xmlParser.getXDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Wrong mapping for YDimension", "qx",
+                      xmlParser.getYDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Wrong mapping for ZDimension", "en",
+                      xmlParser.getZDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Wrong mapping for TDimension", "qz",
+                      xmlParser.getTDimension()->getDimensionId());
+
+    TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 1,
+                      xmlParser.getNonMappedDimensions().size());
+    TSM_ASSERT_EQUALS("Wrong non-mapped dimension found", "other",
+                      xmlParser.getNonMappedDimensions()[0]->getDimensionId());
   }
 
-  void testAssignment()
-  {
+  void testAssignment() {
     using namespace Mantid::VATES;
 
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> dataA;
-    dataA->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId()));
+    dataA->SetFieldData(createFieldDataWithCharArray(
+        constructXML("qy", "qx", "en", "qz"),
+        Mantid::VATES::XMLDefinitions::metaDataId()));
 
     vtkNew<vtkRectilinearGrid> dataB;
-    dataB->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId()));
+    dataB->SetFieldData(createFieldDataWithCharArray(
+        constructXML("", "", "", ""),
+        Mantid::VATES::XMLDefinitions::metaDataId()));
 
     vtkDataSetToGeometry A(dataA.GetPointer());
     vtkDataSetToGeometry B(dataB.GetPointer());
@@ -220,44 +247,69 @@ public:
     A.execute();
     B.execute();
 
-    TSM_ASSERT_EQUALS("X dimension output not the same after assignment", A.hasXDimension(), B.hasXDimension());
-    TSM_ASSERT_EQUALS("X dimension output not the same after assignment", A.getXDimension()->getDimensionId(), B.getXDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment", A.hasYDimension(), B.hasYDimension());
-    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment", A.getYDimension()->getDimensionId(), B.getYDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment", A.hasZDimension(), B.hasZDimension());
-    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment", A.getZDimension()->getDimensionId(), B.getZDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("T dimension output not the same after assignment", A.hasTDimension(), B.hasTDimension());
-    TSM_ASSERT_EQUALS("T dimension output not the same after assignment", A.getTDimension()->getDimensionId(), B.getTDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Non mapped dimension output not the same after assignment", A.getNonMappedDimensions().size(), B.getNonMappedDimensions().size());
+    TSM_ASSERT_EQUALS("X dimension output not the same after assignment",
+                      A.hasXDimension(), B.hasXDimension());
+    TSM_ASSERT_EQUALS("X dimension output not the same after assignment",
+                      A.getXDimension()->getDimensionId(),
+                      B.getXDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment",
+                      A.hasYDimension(), B.hasYDimension());
+    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment",
+                      A.getYDimension()->getDimensionId(),
+                      B.getYDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment",
+                      A.hasZDimension(), B.hasZDimension());
+    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment",
+                      A.getZDimension()->getDimensionId(),
+                      B.getZDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("T dimension output not the same after assignment",
+                      A.hasTDimension(), B.hasTDimension());
+    TSM_ASSERT_EQUALS("T dimension output not the same after assignment",
+                      A.getTDimension()->getDimensionId(),
+                      B.getTDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS(
+        "Non mapped dimension output not the same after assignment",
+        A.getNonMappedDimensions().size(), B.getNonMappedDimensions().size());
   }
 
-  void testCopy()
-  {
+  void testCopy() {
     using namespace Mantid::VATES;
 
     using namespace Mantid::VATES;
     vtkNew<vtkRectilinearGrid> dataA;
-    dataA->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId()));
+    dataA->SetFieldData(createFieldDataWithCharArray(
+        constructXML("qy", "qx", "en", "qz"),
+        Mantid::VATES::XMLDefinitions::metaDataId()));
 
     vtkDataSetToGeometry A(dataA.GetPointer());
     vtkDataSetToGeometry B = A;
     A.execute();
     B.execute();
 
-    TSM_ASSERT_EQUALS("X dimension output not the same after assignment", A.hasXDimension(), B.hasXDimension());
-    TSM_ASSERT_EQUALS("X dimension output not the same after assignment", A.getXDimension()->getDimensionId(), B.getXDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment", A.hasYDimension(), B.hasYDimension());
-    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment", A.getYDimension()->getDimensionId(), B.getYDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment", A.hasZDimension(), B.hasZDimension());
-    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment", A.getZDimension()->getDimensionId(), B.getZDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("T dimension output not the same after assignment", A.hasTDimension(), B.hasTDimension());
-    TSM_ASSERT_EQUALS("T dimension output not the same after assignment", A.getTDimension()->getDimensionId(), B.getTDimension()->getDimensionId());
-    TSM_ASSERT_EQUALS("Non mapped dimension output not the same after assignment", A.getNonMappedDimensions().size(), B.getNonMappedDimensions().size());
-
+    TSM_ASSERT_EQUALS("X dimension output not the same after assignment",
+                      A.hasXDimension(), B.hasXDimension());
+    TSM_ASSERT_EQUALS("X dimension output not the same after assignment",
+                      A.getXDimension()->getDimensionId(),
+                      B.getXDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment",
+                      A.hasYDimension(), B.hasYDimension());
+    TSM_ASSERT_EQUALS("Y dimension output not the same after assignment",
+                      A.getYDimension()->getDimensionId(),
+                      B.getYDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment",
+                      A.hasZDimension(), B.hasZDimension());
+    TSM_ASSERT_EQUALS("Z dimension output not the same after assignment",
+                      A.getZDimension()->getDimensionId(),
+                      B.getZDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS("T dimension output not the same after assignment",
+                      A.hasTDimension(), B.hasTDimension());
+    TSM_ASSERT_EQUALS("T dimension output not the same after assignment",
+                      A.getTDimension()->getDimensionId(),
+                      B.getTDimension()->getDimensionId());
+    TSM_ASSERT_EQUALS(
+        "Non mapped dimension output not the same after assignment",
+        A.getNonMappedDimensions().size(), B.getNonMappedDimensions().size());
   }
-
-
-
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h b/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h
index 481cada11222ab9795c317b00cd584ce195c832e..eef8091ef4be2e527df2f4e0d88735cb191de833 100644
--- a/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h
@@ -1,5 +1,5 @@
 #ifndef VTK_DATASET_TO_WS_IMPLICITFUNCTION_TEST
-#define VTK_DATASET_TO_WS_IMPLICITFUNCTION_TEST 
+#define VTK_DATASET_TO_WS_IMPLICITFUNCTION_TEST
 
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/vtkDataSetToImplicitFunction.h"
@@ -11,19 +11,16 @@
 
 using namespace Mantid::VATES;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkDataSetToImplicitFunctionTest : public CxxTest::TestSuite
-{
+class vtkDataSetToImplicitFunctionTest : public CxxTest::TestSuite {
 
 public:
-
-  void testThrowIfvtkDataSetNull()
-  {
-    vtkDataSet* nullArg = NULL;
-    TS_ASSERT_THROWS(vtkDataSetToImplicitFunction temp(nullArg), std::runtime_error);
+  void testThrowIfvtkDataSetNull() {
+    vtkDataSet *nullArg = NULL;
+    TS_ASSERT_THROWS(vtkDataSetToImplicitFunction temp(nullArg),
+                     std::runtime_error);
   }
 
   void testNoImplcitFunction() {
diff --git a/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
index 4daa34208e207622ee165738d455c324b8022b52..604d50192bc3b2d28b432abc2822dbf8f99f364b 100644
--- a/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h
@@ -30,17 +30,12 @@ using namespace Mantid::DataObjects;
 using namespace Mantid::DataObjects::MDEventsTestHelper;
 using namespace Mantid::VATES;
 
-class vtkDataSetToNonOrthogonalDataSetTest : public CxxTest::TestSuite
-{
+class vtkDataSetToNonOrthogonalDataSetTest : public CxxTest::TestSuite {
 private:
-
-  std::string createMantidWorkspace(bool nonUnityTransform,
-                                    bool wrongCoords = false,
-                                    bool forgetUB = false,
-                                    bool forgetWmat = false,
-                                    bool forgetAffmat = false,
-                                    double scale = 1.0)
-  {
+  std::string
+  createMantidWorkspace(bool nonUnityTransform, bool wrongCoords = false,
+                        bool forgetUB = false, bool forgetWmat = false,
+                        bool forgetAffmat = false, double scale = 1.0) {
     // Creating an MDEventWorkspace as the content is not germain to the
     // information necessary for the non-orthogonal axes
     std::string wsName = "simpleWS";
@@ -58,20 +53,19 @@ private:
     }
 
     // Set the UB matrix
-    if (!forgetUB)
-    {
+    if (!forgetUB) {
       IAlgorithm_sptr alg = AlgorithmManager::Instance().create("SetUB");
       alg->initialize();
       alg->setRethrows(true);
       alg->setProperty("Workspace", wsName);
-      alg->setProperty("a", 3.643*scale);
+      alg->setProperty("a", 3.643 * scale);
       alg->setProperty("b", 3.643);
       alg->setProperty("c", 5.781);
       alg->setProperty("alpha", 90.0);
       alg->setProperty("beta", 90.0);
       alg->setProperty("gamma", 120.0);
       std::vector<double> uVec;
-      uVec.push_back(1*scale);
+      uVec.push_back(1 * scale);
       uVec.push_back(1);
       uVec.push_back(0);
       std::vector<double> vVec;
@@ -90,65 +84,57 @@ private:
 
     CoordTransformAffine affMat(4, 4);
     affMat.setMatrix(Matrix<Mantid::coord_t>(affMatVals));
-    if (!forgetAffmat)
-    {
+    if (!forgetAffmat) {
       ws->setTransformToOriginal(affMat.clone(), 0);
     }
 
     // Create the transform (W) matrix
     // Need it as a vector
     std::vector<double> wMat;
-    if (!nonUnityTransform)
-    {
+    if (!nonUnityTransform) {
       DblMatrix temp(3, 3, true);
       wMat = temp.getVector();
-    }
-    else
-    {
+    } else {
       wMat = {1, 1, 0, 1, -1, 0, 0, 0, 1};
     }
 
-    if (!forgetWmat)
-    {
+    if (!forgetWmat) {
       // Create property for W matrix and add it as log to run object
-      PropertyWithValue<std::vector<double> > *p;
-      p = new PropertyWithValue<std::vector<double> >("W_MATRIX", wMat);
+      PropertyWithValue<std::vector<double>> *p;
+      p = new PropertyWithValue<std::vector<double>>("W_MATRIX", wMat);
       ws->getExperimentInfo(0)->mutableRun().addProperty(p, true);
     }
 
     return wsName;
   }
 
-  vtkUnstructuredGrid *createSingleVoxelPoints()
-  {
-    vtkUnstructuredGrid* ds = vtkUnstructuredGrid::New();
+  vtkUnstructuredGrid *createSingleVoxelPoints() {
+    vtkUnstructuredGrid *ds = vtkUnstructuredGrid::New();
     vtkPoints *points = vtkPoints::New();
     points->Allocate(8);
-    points->InsertNextPoint(0,0,0);
-    points->InsertNextPoint(1,0,0);
-    points->InsertNextPoint(1,1,0);
-    points->InsertNextPoint(0,1,0);
-    points->InsertNextPoint(0,0,1);
-    points->InsertNextPoint(1,0,1);
-    points->InsertNextPoint(1,1,1);
-    points->InsertNextPoint(0,1,1);
+    points->InsertNextPoint(0, 0, 0);
+    points->InsertNextPoint(1, 0, 0);
+    points->InsertNextPoint(1, 1, 0);
+    points->InsertNextPoint(0, 1, 0);
+    points->InsertNextPoint(0, 0, 1);
+    points->InsertNextPoint(1, 0, 1);
+    points->InsertNextPoint(1, 1, 1);
+    points->InsertNextPoint(0, 1, 1);
 
     ds->SetPoints(points);
     return ds;
   }
 
-  template<typename T>
-  std::vector<T> getRangeComp(vtkDataSet *ds, std::string fieldname, int size)
-  {
+  template <typename T>
+  std::vector<T> getRangeComp(vtkDataSet *ds, std::string fieldname, int size) {
     vtkDataArray *arr = ds->GetFieldData()->GetArray(fieldname.c_str());
-    vtkTypedDataArray<T>* tarr = vtkTypedDataArray<T>::FastDownCast(arr);
+    vtkTypedDataArray<T> *tarr = vtkTypedDataArray<T>::FastDownCast(arr);
     std::vector<T> vals(size);
     tarr->GetTupleValue(0, &vals[0]);
     return vals;
   }
 
-  void checkUnityTransformation(vtkUnstructuredGrid *grid)
-  {
+  void checkUnityTransformation(vtkUnstructuredGrid *grid) {
     // This function can be used for both the unscaled and scaled
     // unity transformation, since the outcome is identical.
     // Now, check some values
@@ -160,8 +146,9 @@ private:
     TS_ASSERT_DELTA(point[2], 0.8660254, eps);
     // See if the basis vectors are available
 
-    std::vector<double> basisMatrix = getRangeComp<double>(grid, "ChangeOfBasisMatrix", 16);
-    
+    std::vector<double> basisMatrix =
+        getRangeComp<double>(grid, "ChangeOfBasisMatrix", 16);
+
     // Row by row check
 
     // basisX[0], basisY[0], basisZ[0], 0
@@ -183,7 +170,7 @@ private:
     TS_ASSERT_DELTA(basisMatrix[index++], 0.8660254, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
 
-    //0, 0, 0, 1
+    // 0, 0, 0, 1
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
@@ -193,100 +180,116 @@ private:
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static vtkDataSetToNonOrthogonalDataSetTest *createSuite() { return new vtkDataSetToNonOrthogonalDataSetTest(); }
-  static void destroySuite( vtkDataSetToNonOrthogonalDataSetTest *suite ) { delete suite; }
+  static vtkDataSetToNonOrthogonalDataSetTest *createSuite() {
+    return new vtkDataSetToNonOrthogonalDataSetTest();
+  }
+  static void destroySuite(vtkDataSetToNonOrthogonalDataSetTest *suite) {
+    delete suite;
+  }
 
-  void testThrowIfVtkDatasetNull()
-  {
+  void testThrowIfVtkDatasetNull() {
     vtkDataSet *dataset = NULL;
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    TS_ASSERT_THROWS(vtkDataSetToNonOrthogonalDataSet temp(dataset, "", std::move(workspaceProvider)),
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    TS_ASSERT_THROWS(vtkDataSetToNonOrthogonalDataSet temp(
+                         dataset, "", std::move(workspaceProvider)),
                      std::runtime_error);
   }
 
   void testThrowsIfWorkspaceNameEmptyAndUsingADSWorkspaceProvider() {
     vtkNew<vtkUnstructuredGrid> dataset;
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
     TS_ASSERT_THROWS(
-        vtkDataSetToNonOrthogonalDataSet temp(dataset.GetPointer(), "", std::move(workspaceProvider)),
+        vtkDataSetToNonOrthogonalDataSet temp(dataset.GetPointer(), "",
+                                              std::move(workspaceProvider)),
         std::runtime_error);
   }
 
   void testThrowIfVtkDatasetWrongType() {
     vtkNew<vtkRectilinearGrid> grid;
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(grid.GetPointer(), "name", std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(grid.GetPointer(), "name",
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS(converter.execute(), std::runtime_error);
   }
 
-  void testSimpleDataset()
-  {
+  void testSimpleDataset() {
     std::string wsName = createMantidWorkspace(false);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS_NOTHING(converter.execute());
     this->checkUnityTransformation(ds);
   }
 
-  void testThrowsSimpleDatasetWrongCoords()
-  {
+  void testThrowsSimpleDatasetWrongCoords() {
     std::string wsName = createMantidWorkspace(false, true);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS(converter.execute(), std::invalid_argument);
   }
 
-  void testThrowsSimpleDatasetNoUB()
-  {
+  void testThrowsSimpleDatasetNoUB() {
     std::string wsName = createMantidWorkspace(false, false, true);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS(converter.execute(), std::invalid_argument);
   }
 
-  void testThrowsSimpleDatasetNoWMatrix()
-  {
+  void testThrowsSimpleDatasetNoWMatrix() {
     std::string wsName = createMantidWorkspace(false, false, false, true);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS(converter.execute(), std::invalid_argument);
   }
 
-  void testNoThrowsSimpleDataSetNoAffineMatrix()
-  {
-    std::string wsName = createMantidWorkspace(false, false, false, false, true);
+  void testNoThrowsSimpleDataSetNoAffineMatrix() {
+    std::string wsName =
+        createMantidWorkspace(false, false, false, false, true);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS_NOTHING(converter.execute());
   }
 
-  void testStaticUseForSimpleDataSet()
-  {
+  void testStaticUseForSimpleDataSet() {
     std::string wsName = createMantidWorkspace(false);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    TS_ASSERT_THROWS_NOTHING(
-        vtkDataSetToNonOrthogonalDataSet::exec(ds, wsName, std::move(workspaceProvider)));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    TS_ASSERT_THROWS_NOTHING(vtkDataSetToNonOrthogonalDataSet::exec(
+        ds, wsName, std::move(workspaceProvider)));
   }
 
-  void testNonUnitySimpleDataset()
-  {
+  void testNonUnitySimpleDataset() {
     std::string wsName = createMantidWorkspace(true);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS_NOTHING(converter.execute());
     // Now, check some values
     /// Get the (1,1,1) point
@@ -296,8 +299,9 @@ public:
     TS_ASSERT_DELTA(point[1], 1.0, eps);
     TS_ASSERT_DELTA(point[2], 1.0, eps);
     // See if the basis vectors are available
-    std::vector<double> basisMatrix = getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
-    
+    std::vector<double> basisMatrix =
+        getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
+
     // Row by row check
 
     // basisX[0], basisY[0], basisZ[0], 0
@@ -319,31 +323,35 @@ public:
     TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
 
-    //0, 0, 0, 1
+    // 0, 0, 0, 1
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps);
   }
 
-  void testScaledSimpleDataset()
-  {
-    std::string wsName = createMantidWorkspace(false, false, false, false, false, 2.0);
+  void testScaledSimpleDataset() {
+    std::string wsName =
+        createMantidWorkspace(false, false, false, false, false, 2.0);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS_NOTHING(converter.execute());
     this->checkUnityTransformation(ds);
   }
 
-  void testScaledNonUnitySimpleDataset()
-  {
-    std::string wsName = createMantidWorkspace(true, false, false, false, false, 2.0);
+  void testScaledNonUnitySimpleDataset() {
+    std::string wsName =
+        createMantidWorkspace(true, false, false, false, false, 2.0);
     vtkSmartPointer<vtkUnstructuredGrid> ds;
     ds.TakeReference(createSingleVoxelPoints());
-    auto workspaceProvider = Mantid::Kernel::make_unique<ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
-    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName, std::move(workspaceProvider));
+    auto workspaceProvider = Mantid::Kernel::make_unique<
+        ADSWorkspaceProvider<Mantid::API::IMDWorkspace>>();
+    vtkDataSetToNonOrthogonalDataSet converter(ds, wsName,
+                                               std::move(workspaceProvider));
     TS_ASSERT_THROWS_NOTHING(converter.execute());
     // Now, check some values
     /// Get the (1,1,1) point
@@ -353,7 +361,8 @@ public:
     TS_ASSERT_DELTA(point[1], 1.0, eps);
     TS_ASSERT_DELTA(point[2], 0.75592895, eps);
     // See if the basis vectors are available
-    std::vector<double> basisMatrix = getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
+    std::vector<double> basisMatrix =
+        getRangeComp<double>(ds, "ChangeOfBasisMatrix", 16);
 
     // Row by row check
 
@@ -376,7 +385,7 @@ public:
     TS_ASSERT_DELTA(basisMatrix[index++], 0.75592895, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
 
-    //0, 0, 0, 1
+    // 0, 0, 0, 1
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
     TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps);
@@ -384,5 +393,4 @@ public:
   }
 };
 
-
 #endif /* MANTID_VATESAPI_VTKDATASETTONONORTHOGONALDATASETTEST_H_ */
diff --git a/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h
index 6093089aab3d0d75d7ac840f4ebb7c2a74b6cd0b..845984098c95dfecc1af81f37962ad4e97d026bd 100644
--- a/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h
@@ -34,25 +34,22 @@
 
 #include <boost/shared_ptr.hpp>
 
-
 using namespace Mantid::DataObjects;
 using namespace Mantid::VATES;
 using namespace ::testing;
 
-class MockPeakFilter : public Mantid::DataObjects::Peak
-{
+class MockPeakFilter : public Mantid::DataObjects::Peak {
 public:
-  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D (void));
+  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void));
 };
 
-class MockPeaksWorkspaceFilter : public Mantid::DataObjects::PeaksWorkspace
-{
+class MockPeaksWorkspaceFilter : public Mantid::DataObjects::PeaksWorkspace {
 public:
   MOCK_CONST_METHOD0(getNumberPeaks, int());
-  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak & (int peakNum));
-  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak & (int peakNum));
+  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum));
+  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum));
 };
 
 struct PeaksFilterDataContainer {
@@ -61,12 +58,12 @@ struct PeaksFilterDataContainer {
   Mantid::Kernel::V3D position;
 };
 
-class vtkDataSetToPeaksFilteredDataSetTest : public CxxTest::TestSuite
-{
+class vtkDataSetToPeaksFilteredDataSetTest : public CxxTest::TestSuite {
 private:
   vtkSmartPointer<vtkUnstructuredGrid> makeSplatterSourceGrid() {
     FakeProgressAction progressUpdate;
-    MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, -10.0, 10.0, 1);
+    MDEventWorkspace3Lean::sptr ws =
+        MDEventsTestHelper::makeMDEW<3>(10, -10.0, 10.0, 1);
     vtkSplatterPlotFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 1), "signal");
     factory.initialize(ws);
@@ -80,25 +77,36 @@ private:
 public:
   // This pair of boilerplate methods prevent the suite being created statically
   // This means the constructor isn't called when running other tests
-  static vtkDataSetToPeaksFilteredDataSetTest *createSuite() { return new vtkDataSetToPeaksFilteredDataSetTest(); }
-  static void destroySuite( vtkDataSetToPeaksFilteredDataSetTest *suite ) { delete suite; }
+  static vtkDataSetToPeaksFilteredDataSetTest *createSuite() {
+    return new vtkDataSetToPeaksFilteredDataSetTest();
+  }
+  static void destroySuite(vtkDataSetToPeaksFilteredDataSetTest *suite) {
+    delete suite;
+  }
 
-  void do_test_peak_inSphere(vtkPoints* points,int numberOfPoints, int& inside, int& outside, bool testingOutput, std::vector<PeaksFilterDataContainer> peakData)
-  {
-    for (int i = 0; i < numberOfPoints; i++)
-    {
+  void do_test_peak_inSphere(vtkPoints *points, int numberOfPoints, int &inside,
+                             int &outside, bool testingOutput,
+                             std::vector<PeaksFilterDataContainer> peakData) {
+    for (int i = 0; i < numberOfPoints; i++) {
       double point[3];
       points->GetPoint(static_cast<vtkIdType>(i), point);
 
       bool isInSphere = false;
       // Check if the point is any of the peaks
-      for (std::vector<PeaksFilterDataContainer>::iterator it = peakData.begin(); it != peakData.end(); ++it) {
+      for (std::vector<PeaksFilterDataContainer>::iterator it =
+               peakData.begin();
+           it != peakData.end(); ++it) {
         double diffSquared = 0;
-        for (int k = 0; k <3; k++) {
-          diffSquared += (it->position[k]-point[k])*(it->position[k]-point[k]);
+        for (int k = 0; k < 3; k++) {
+          diffSquared +=
+              (it->position[k] - point[k]) * (it->position[k] - point[k]);
         }
 
-        isInSphere = ((it->radius*it->radius*it->radiusFactor*it->radiusFactor - diffSquared) >= 0) ? true : false;
+        isInSphere =
+            ((it->radius * it->radius * it->radiusFactor * it->radiusFactor -
+              diffSquared) >= 0)
+                ? true
+                : false;
         // If the point is in a sphere, stop comparing
         if (isInSphere) {
           break;
@@ -109,8 +117,7 @@ public:
       isInSphere ? (inside++) : (outside++);
 
       // We expect only for the output, that all points are within the sphere
-      if (testingOutput)
-      {
+      if (testingOutput) {
         TSM_ASSERT("Should be insinde the sphere.", isInSphere);
       }
     }
@@ -125,47 +132,57 @@ public:
     int numberOfInPoints = static_cast<int>(inPoints->GetNumberOfPoints());
     int numberOfOutPoints = static_cast<int>(outPoints->GetNumberOfPoints());
 
-
     int insideSphereInput = 0;
     int outsideSphereInput = 0;
-    do_test_peak_inSphere(inPoints, numberOfInPoints, insideSphereInput , outsideSphereInput, false, peakData);
+    do_test_peak_inSphere(inPoints, numberOfInPoints, insideSphereInput,
+                          outsideSphereInput, false, peakData);
 
     int insideSphereOutput = 0;
     int outsideSphereOutput = 0;
-    do_test_peak_inSphere(outPoints, numberOfOutPoints, insideSphereOutput , outsideSphereOutput, true, peakData);
+    do_test_peak_inSphere(outPoints, numberOfOutPoints, insideSphereOutput,
+                          outsideSphereOutput, true, peakData);
 
-    TSM_ASSERT("The number of elements inside the sphere should be the same for input and output.", insideSphereInput == insideSphereOutput);
+    TSM_ASSERT("The number of elements inside the sphere should be the same "
+               "for input and output.",
+               insideSphereInput == insideSphereOutput);
   }
 
-  void do_test_execute(vtkDataSetToPeaksFilteredDataSet peaksFilter, std::vector<std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>> peakWsData, Mantid::Kernel::SpecialCoordinateSystem coordinateSystem) {
+  void
+  do_test_execute(vtkDataSetToPeaksFilteredDataSet peaksFilter,
+                  std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                                        Mantid::Kernel::V3D>> peakWsData,
+                  Mantid::Kernel::SpecialCoordinateSystem coordinateSystem) {
     std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksContainer;
-    for (std::vector<std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>>::iterator it = peakWsData.begin(); it != peakWsData.end(); ++it) {
+    for (std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                               Mantid::Kernel::V3D>>::iterator it =
+             peakWsData.begin();
+         it != peakWsData.end(); ++it) {
       // Set up the peak
-      switch(coordinateSystem)
-      {
-        case(Mantid::Kernel::SpecialCoordinateSystem::QLab):
-          EXPECT_CALL(*(it->first), getQLabFrame()).WillOnce(Return(it->second));
-          EXPECT_CALL(*(it->first), getHKL()).Times(0);
-          EXPECT_CALL(*(it->first), getQSampleFrame()).Times(0);
-          break;
-        case(Mantid::Kernel::SpecialCoordinateSystem::HKL):
-          EXPECT_CALL(*(it->first), getQLabFrame()).Times(0);
-          EXPECT_CALL(*(it->first), getHKL()).WillOnce(Return(it->second));
-          EXPECT_CALL(*(it->first), getQSampleFrame()).Times(0);
-          break;
-        case(Mantid::Kernel::SpecialCoordinateSystem::QSample):
-          EXPECT_CALL(*(it->first), getQLabFrame()).Times(0);
-          EXPECT_CALL(*(it->first), getHKL()).Times(0);
-          EXPECT_CALL(*(it->first), getQSampleFrame()).WillOnce(Return(it->second));
-          break;
-        default:
-          break;
+      switch (coordinateSystem) {
+      case (Mantid::Kernel::SpecialCoordinateSystem::QLab):
+        EXPECT_CALL(*(it->first), getQLabFrame()).WillOnce(Return(it->second));
+        EXPECT_CALL(*(it->first), getHKL()).Times(0);
+        EXPECT_CALL(*(it->first), getQSampleFrame()).Times(0);
+        break;
+      case (Mantid::Kernel::SpecialCoordinateSystem::HKL):
+        EXPECT_CALL(*(it->first), getQLabFrame()).Times(0);
+        EXPECT_CALL(*(it->first), getHKL()).WillOnce(Return(it->second));
+        EXPECT_CALL(*(it->first), getQSampleFrame()).Times(0);
+        break;
+      case (Mantid::Kernel::SpecialCoordinateSystem::QSample):
+        EXPECT_CALL(*(it->first), getQLabFrame()).Times(0);
+        EXPECT_CALL(*(it->first), getHKL()).Times(0);
+        EXPECT_CALL(*(it->first), getQSampleFrame())
+            .WillOnce(Return(it->second));
+        break;
+      default:
+        break;
       }
 
       // Set up the peaks workspace
       boost::shared_ptr<MockPeaksWorkspaceFilter> pw_ptr =
           boost::make_shared<MockPeaksWorkspaceFilter>();
-      MockPeaksWorkspaceFilter & pw = *pw_ptr;
+      MockPeaksWorkspaceFilter &pw = *pw_ptr;
 
       EXPECT_CALL(pw, getNumberPeaks()).Times(1).WillRepeatedly(Return(1));
       EXPECT_CALL(pw, getPeak(_)).WillOnce(ReturnRef(*(it->first)));
@@ -176,25 +193,25 @@ public:
                            Mantid::Geometry::PeakShape::RadiusType::Radius,
                            coordinateSystem);
     FakeProgressAction updateProgress;
-    TSM_ASSERT_THROWS_NOTHING("Should execute regularly.", peaksFilter.execute(updateProgress));
+    TSM_ASSERT_THROWS_NOTHING("Should execute regularly.",
+                              peaksFilter.execute(updateProgress));
   }
 
-  void testThrowIfInputNull()
-  {
+  void testThrowIfInputNull() {
     vtkUnstructuredGrid *in = nullptr;
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
-    TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out), std::runtime_error);
+    TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out),
+                     std::runtime_error);
   }
 
-  void testThrowIfOutputNull()
-  {
+  void testThrowIfOutputNull() {
     auto in = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkUnstructuredGrid *out = nullptr;
-    TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out), std::runtime_error);
+    TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out),
+                     std::runtime_error);
   }
 
-  void testExecThrowIfNoInit()
-  {
+  void testExecThrowIfNoInit() {
     auto in = vtkSmartPointer<vtkUnstructuredGrid>::New();
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out);
@@ -202,27 +219,28 @@ public:
     TS_ASSERT_THROWS(peaksFilter.execute(updateProgress), std::runtime_error);
   }
 
-  void testExecutionWithSingleSphericalPeakInQSample()
-  {
+  void testExecutionWithSingleSphericalPeakInQSample() {
     // Arrange
     auto in = makeSplatterSourceGrid();
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out);
 
-    Mantid::Kernel::V3D coordinate(0,0,0);
-    // Note that the peak radius is not a 1-1 measure for which peaks will be culled and which not. 
+    Mantid::Kernel::V3D coordinate(0, 0, 0);
+    // Note that the peak radius is not a 1-1 measure for which peaks will be
+    // culled and which not.
     // The actual radius is multiplied by the radius factor.
     double peakRadius = 5;
-    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::SpecialCoordinateSystem::QSample;
+    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem =
+        Mantid::Kernel::SpecialCoordinateSystem::QSample;
     auto shape = boost::make_shared<Mantid::DataObjects::PeakShapeSpherical>(
         peakRadius, coordinateSystem, "test", 1);
     boost::shared_ptr<MockPeakFilter> peak =
         boost::make_shared<MockPeakFilter>();
     peak->setPeakShape(shape);
 
-    std::vector<
-        std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>>
-        fakeSinglePeakPeakWorkspaces{{peak, coordinate}};
+    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                          Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces{
+        {peak, coordinate}};
 
     PeaksFilterDataContainer data1;
     data1.position = coordinate;
@@ -231,35 +249,39 @@ public:
     std::vector<PeaksFilterDataContainer> peakData{data1};
 
     // Act
-    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces, coordinateSystem);
+    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces,
+                    coordinateSystem);
 
     // Assert
     do_test_peaks(in, out, peakData);
   }
 
-  void testExecutionWithSingleEllipsoidPeakInQSample()
-  {
+  void testExecutionWithSingleEllipsoidPeakInQSample() {
     // Arrange
     auto in = makeSplatterSourceGrid();
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out);
 
-    Mantid::Kernel::V3D coordinate(0,0,0);
+    Mantid::Kernel::V3D coordinate(0, 0, 0);
     double peakRadiusMax = 7;
     std::vector<double> radii{peakRadiusMax, 6, 5};
 
     std::vector<Mantid::Kernel::V3D> directions{
         {0., 1., 0.}, {1., 0., 0.}, {0., 0., 1.}};
 
-    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::SpecialCoordinateSystem::QSample;
+    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem =
+        Mantid::Kernel::SpecialCoordinateSystem::QSample;
     auto shape = boost::make_shared<Mantid::DataObjects::PeakShapeEllipsoid>(
         directions, radii, radii, radii, coordinateSystem, "test", 1);
     boost::shared_ptr<MockPeakFilter> peak =
         boost::make_shared<MockPeakFilter>();
     peak->setPeakShape(shape);
 
-    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces;
-    fakeSinglePeakPeakWorkspaces.push_back(std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>(peak, coordinate));
+    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                          Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces;
+    fakeSinglePeakPeakWorkspaces.push_back(
+        std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>(
+            peak, coordinate));
 
     std::vector<PeaksFilterDataContainer> peakData;
     PeaksFilterDataContainer data1;
@@ -268,31 +290,35 @@ public:
     data1.radiusFactor = peaksFilter.getRadiusFactor();
     peakData.push_back(data1);
 
-     // Act
-    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces, coordinateSystem);
+    // Act
+    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces,
+                    coordinateSystem);
 
     // Assert
     do_test_peaks(in, out, peakData);
   }
 
-  void testExecutionWithSingleNoShapePeakInQSample()
-  {
+  void testExecutionWithSingleNoShapePeakInQSample() {
     // Arrange
     auto in = makeSplatterSourceGrid();
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out);
 
-    Mantid::Kernel::V3D coordinate(0,0,0);
+    Mantid::Kernel::V3D coordinate(0, 0, 0);
 
-    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::SpecialCoordinateSystem::QSample;
+    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem =
+        Mantid::Kernel::SpecialCoordinateSystem::QSample;
     double radius = peaksFilter.getRadiusNoShape();
     auto shape = boost::make_shared<Mantid::DataObjects::NoShape>();
     boost::shared_ptr<MockPeakFilter> peak =
         boost::make_shared<MockPeakFilter>();
     peak->setPeakShape(shape);
 
-    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces;
-    fakeSinglePeakPeakWorkspaces.push_back(std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>(peak, coordinate));
+    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                          Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces;
+    fakeSinglePeakPeakWorkspaces.push_back(
+        std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>(
+            peak, coordinate));
 
     std::vector<PeaksFilterDataContainer> peakData;
     PeaksFilterDataContainer data1;
@@ -302,22 +328,24 @@ public:
     peakData.push_back(data1);
 
     // Act
-    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces, coordinateSystem);
+    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces,
+                    coordinateSystem);
 
     // Assert
     do_test_peaks(in, out, peakData);
   }
 
   void testExecutionWithTwoWorkspacesWithSingleSphericalShapesInQSample() {
-     // Arrange
+    // Arrange
     auto in = makeSplatterSourceGrid();
     auto out = vtkSmartPointer<vtkUnstructuredGrid>::New();
     vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out);
 
     // Peak 1
-    Mantid::Kernel::V3D coordinate(0,0,0);
+    Mantid::Kernel::V3D coordinate(0, 0, 0);
     double peakRadius = 5;
-    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::SpecialCoordinateSystem::QSample;
+    Mantid::Kernel::SpecialCoordinateSystem coordinateSystem =
+        Mantid::Kernel::SpecialCoordinateSystem::QSample;
     auto shape = boost::make_shared<Mantid::DataObjects::PeakShapeSpherical>(
         peakRadius, coordinateSystem, "test", 1);
     boost::shared_ptr<MockPeakFilter> peak =
@@ -325,7 +353,7 @@ public:
     peak->setPeakShape(shape);
 
     // Peak 2
-    Mantid::Kernel::V3D coordinate2(12,0,0);
+    Mantid::Kernel::V3D coordinate2(12, 0, 0);
     double peakRadius2 = 5;
     auto shape2 = boost::make_shared<Mantid::DataObjects::PeakShapeSpherical>(
         peakRadius2, coordinateSystem, "test", 1);
@@ -335,7 +363,7 @@ public:
 
     PeaksFilterDataContainer data1;
     data1.position = coordinate;
-    data1.radius =peakRadius;
+    data1.radius = peakRadius;
     data1.radiusFactor = peaksFilter.getRadiusFactor();
     PeaksFilterDataContainer data2;
     data2.position = coordinate2;
@@ -344,12 +372,13 @@ public:
 
     std::vector<PeaksFilterDataContainer> peakData{data1, data2};
 
-    std::vector<
-        std::pair<boost::shared_ptr<MockPeakFilter>, Mantid::Kernel::V3D>>
-        fakeSinglePeakPeakWorkspaces{{peak, coordinate}, {peak2, coordinate2}};
+    std::vector<std::pair<boost::shared_ptr<MockPeakFilter>,
+                          Mantid::Kernel::V3D>> fakeSinglePeakPeakWorkspaces{
+        {peak, coordinate}, {peak2, coordinate2}};
 
     // Act
-    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces, coordinateSystem);
+    do_test_execute(peaksFilter, fakeSinglePeakPeakWorkspaces,
+                    coordinateSystem);
 
     // Assert
     do_test_peaks(in, out, peakData);
diff --git a/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
index a92082be238f9065c68f86ceb39e06684479c1b9..391434f9587672c5707e5080b7c7d1e201177d99 100644
--- a/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h
@@ -50,14 +50,16 @@ private:
     auto v = vtkVector3d(-2, 2, 0);
     auto w = vtkVector3d(0, 0, 8);
 
-    vtkSmartPointer<vtkMatrix4x4> cobMatrix = vtkSmartPointer<vtkMatrix4x4>::New();
+    vtkSmartPointer<vtkMatrix4x4> cobMatrix =
+        vtkSmartPointer<vtkMatrix4x4>::New();
     cobMatrix->Identity();
     std::copy(u.GetData(), u.GetData() + 3, cobMatrix->Element[0]);
     std::copy(v.GetData(), v.GetData() + 3, cobMatrix->Element[1]);
     std::copy(w.GetData(), w.GetData() + 3, cobMatrix->Element[2]);
     cobMatrix->Transpose();
 
-    vtkPVChangeOfBasisHelper::AddChangeOfBasisMatrixToFieldData(grid, cobMatrix);
+    vtkPVChangeOfBasisHelper::AddChangeOfBasisMatrixToFieldData(grid,
+                                                                cobMatrix);
     return grid;
   }
 
@@ -94,8 +96,7 @@ public:
 
     vtkDataSetToScaledDataSet scaler;
 
-    TS_ASSERT_THROWS(scaler.execute(1, 1, 1, in),
-                     std::runtime_error);
+    TS_ASSERT_THROWS(scaler.execute(1, 1, 1, in), std::runtime_error);
   }
 
   void testExecution() {
@@ -179,12 +180,12 @@ public:
 
     // Check bounds are scaled
     double *bb = out->GetBounds();
-    TS_ASSERT_EQUALS(-10.0/4, bb[0]);
-    TS_ASSERT_EQUALS(10.0/4, bb[1]);
-    TS_ASSERT_EQUALS(-10.0/2, bb[2]);
-    TS_ASSERT_EQUALS(10.0/2, bb[3]);
-    TS_ASSERT_EQUALS(-10.0/8, bb[4]);
-    TS_ASSERT_EQUALS(10.0/8, bb[5]);
+    TS_ASSERT_EQUALS(-10.0 / 4, bb[0]);
+    TS_ASSERT_EQUALS(10.0 / 4, bb[1]);
+    TS_ASSERT_EQUALS(-10.0 / 2, bb[2]);
+    TS_ASSERT_EQUALS(10.0 / 2, bb[3]);
+    TS_ASSERT_EQUALS(-10.0 / 8, bb[4]);
+    TS_ASSERT_EQUALS(10.0 / 8, bb[5]);
 
     auto cobMatrix = vtkPVChangeOfBasisHelper::GetChangeOfBasisMatrix(out);
 
@@ -219,7 +220,6 @@ public:
     TS_ASSERT_EQUALS(-10.0, bounds[4]);
     TS_ASSERT_EQUALS(10.0, bounds[5]);
   }
-
 };
 
 #endif /* MANTID_VATESAPI_VTKDATASETTOSCALEDDATASETTEST_H_ */
diff --git a/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h b/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h
index 1383d32900527c2372dd8d0be5ae54602c8da195..42deda5a0a2ea1a28218b1647a8671910af97cf6 100644
--- a/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h
@@ -1,4 +1,4 @@
-#ifndef VTK_DATASET_TO_WS_LOCATION_TEST 
+#ifndef VTK_DATASET_TO_WS_LOCATION_TEST
 #define VTK_DATASET_TO_WS_LOCATION_TEST
 
 #include <cxxtest/TestSuite.h>
@@ -10,34 +10,28 @@
 
 using namespace Mantid::VATES;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkDataSetToWsLocationTest : public CxxTest::TestSuite
-{
+class vtkDataSetToWsLocationTest : public CxxTest::TestSuite {
 
 private:
-
-  // Helper method. Create xml. Notice this is a subset of the full xml-schema, see Architectural design document.
-  static std::string constructXML()
-  {
+  // Helper method. Create xml. Notice this is a subset of the full xml-schema,
+  // see Architectural design document.
+  static std::string constructXML() {
     return std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>") +
-      "<MDInstruction>" +
-      "<MDWorkspaceLocation>WS_LOCATION</MDWorkspaceLocation>"
-      "</MDInstruction>";
+           "<MDInstruction>" +
+           "<MDWorkspaceLocation>WS_LOCATION</MDWorkspaceLocation>"
+           "</MDInstruction>";
   }
 
 public:
-
-  void testThrowIfvtkDataSetNull()
-  {
-    vtkDataSet* nullArg = NULL;
+  void testThrowIfvtkDataSetNull() {
+    vtkDataSet *nullArg = NULL;
     TS_ASSERT_THROWS(vtkDataSetToWsLocation temp(nullArg), std::runtime_error);
   }
 
-  void testExecution()
-  {
+  void testExecution() {
     vtkNew<vtkStructuredGrid> ds;
     ds->SetFieldData(createFieldDataWithCharArray(constructXML()));
 
@@ -45,8 +39,7 @@ public:
     TS_ASSERT_EQUALS("WS_LOCATION", extractor.execute());
   }
 
-  void testStaticUsage()
-  {
+  void testStaticUsage() {
     vtkNew<vtkStructuredGrid> ds;
     ds->SetFieldData(createFieldDataWithCharArray(constructXML()));
 
diff --git a/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h b/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h
index 67d2eb49e14be61a4715f29daa6d64c34ed06cbc..f0cb6b2f80a1e1490e8ff2fdd4870b7591278f95 100644
--- a/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h
+++ b/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h
@@ -1,5 +1,5 @@
 #ifndef VTK_DATASET_TO_WS_NAME_TEST
-#define VTK_DATASET_TO_WS_NAME_TEST 
+#define VTK_DATASET_TO_WS_NAME_TEST
 
 #include <cxxtest/TestSuite.h>
 #include "MantidVatesAPI/vtkDataSetToWsName.h"
@@ -9,35 +9,27 @@
 
 using namespace Mantid::VATES;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkDataSetToWsNameTest : public CxxTest::TestSuite
-{
+class vtkDataSetToWsNameTest : public CxxTest::TestSuite {
 
 private:
-
-  // Helper method. Create xml. Notice this is a subset of the full xml-schema, see Architectural design document.
-  static std::string constructXML()
-  {
+  // Helper method. Create xml. Notice this is a subset of the full xml-schema,
+  // see Architectural design document.
+  static std::string constructXML() {
     return std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>") +
-      "<MDInstruction>" +
-      "<MDWorkspaceName>WS_NAME</MDWorkspaceName>"
-      "</MDInstruction>";
+           "<MDInstruction>" + "<MDWorkspaceName>WS_NAME</MDWorkspaceName>"
+                               "</MDInstruction>";
   }
 
-
 public:
-
-  void testThrowIfvtkDataSetNull()
-  {
-    vtkDataSet* nullArg = NULL;
+  void testThrowIfvtkDataSetNull() {
+    vtkDataSet *nullArg = NULL;
     TS_ASSERT_THROWS(vtkDataSetToWsName temp(nullArg), std::runtime_error);
   }
 
-  void testExecution()
-  {
+  void testExecution() {
     vtkNew<vtkStructuredGrid> ds;
     ds->SetFieldData(createFieldDataWithCharArray(constructXML()));
 
@@ -45,8 +37,7 @@ public:
     TS_ASSERT_EQUALS("WS_NAME", extractor.execute());
   }
 
-  void testStaticUsage()
-  {
+  void testStaticUsage() {
     vtkNew<vtkStructuredGrid> ds;
     ds->SetFieldData(createFieldDataWithCharArray(constructXML()));
 
diff --git a/Vates/VatesAPI/test/vtkMD0DFactoryTest.h b/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
index e425c548c6ac8a81d2766e872be5c54e2a707d19..d05231d42f3319b9da606925e7fa172035f8e0c8 100644
--- a/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMD0DFactoryTest.h
@@ -7,12 +7,9 @@
 
 using namespace Mantid::VATES;
 
-class vtkMD0DFactoryTest : public CxxTest::TestSuite
-{
+class vtkMD0DFactoryTest : public CxxTest::TestSuite {
 public:
-
-  void testCreatesA0DDataSet()
-  {
+  void testCreatesA0DDataSet() {
     // Arrange
     FakeProgressAction progressUpdater;
     vtkMD0DFactory factory;
@@ -23,10 +20,11 @@ public:
     TSM_ASSERT_THROWS_NOTHING(
         "0D factory should create data set without exceptions",
         dataSet = factory.create(progressUpdater));
-    TSM_ASSERT("Should have exactly one point", dataSet->GetNumberOfPoints() == 1);
-    TSM_ASSERT("Should have exactly one cell", dataSet->GetNumberOfCells() == 1);
+    TSM_ASSERT("Should have exactly one point",
+               dataSet->GetNumberOfPoints() == 1);
+    TSM_ASSERT("Should have exactly one cell",
+               dataSet->GetNumberOfCells() == 1);
   }
 };
 
-
 #endif
diff --git a/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
index 721e29cdfb8f119f1a4922bc60ad6de7640f8034..08c6f50a62a8e488a2fdf2157e24da78a9e2c780 100644
--- a/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h
@@ -24,37 +24,42 @@ using namespace testing;
 //=====================================================================================
 // Functional Tests
 //=====================================================================================
-class vtkMDHistoHex4DFactoryTest: public CxxTest::TestSuite
-{
+class vtkMDHistoHex4DFactoryTest : public CxxTest::TestSuite {
 
 public:
-
-  void testThresholds()
-  {
+  void testThresholds() {
     FakeProgressAction progressAction;
 
     // Workspace with value 1.0 everywhere
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4);
     ws_sptr->setTransformFromOriginal(new NullCoordTransform);
 
-    //Set up so that only cells with signal values == 1 should not be filtered out by thresholding.
+    // 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)), Mantid::VATES::VolumeNormalization, 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> inside(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)),
+        Mantid::VATES::VolumeNormalization, 0);
     inside.initialize(ws_sptr);
     auto insideData = inside.create(progressAction);
     auto insideProduct = vtkStructuredGrid::SafeDownCast(insideData.Get());
 
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization, 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> below(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)),
+        Mantid::VATES::VolumeNormalization, 0);
     below.initialize(ws_sptr);
     auto belowData = below.create(progressAction);
     auto belowProduct = vtkStructuredGrid::SafeDownCast(belowData.Get());
 
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), Mantid::VATES::VolumeNormalization, 0);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> above(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)),
+        Mantid::VATES::VolumeNormalization, 0);
     above.initialize(ws_sptr);
     auto aboveData = above.create(progressAction);
     auto aboveProduct = vtkStructuredGrid::SafeDownCast(aboveData.Get());
 
-    TS_ASSERT_EQUALS((10*10*10), insideProduct->GetNumberOfCells());
+    TS_ASSERT_EQUALS((10 * 10 * 10), insideProduct->GetNumberOfCells());
     for (auto i = 0; i < insideProduct->GetNumberOfCells(); ++i) {
       TS_ASSERT(insideProduct->IsCellVisible(i) != 0);
     }
@@ -71,19 +76,24 @@ public:
     }
   }
 
-  void testProgressUpdating()
-  {
+  void testProgressUpdating() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    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), Mantid::VATES::VolumeNormalization, 0);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4);
+    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(
+        ThresholdRange_scptr(new NoThresholdRange),
+        Mantid::VATES::VolumeNormalization, 0);
 
     factory.initialize(ws_sptr);
     auto product = factory.create(mockProgressAction);
 
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
   }
 
   void testSignalAspects() {
@@ -118,19 +128,20 @@ public:
                       correctCellNumber, signalData->GetSize());
   }
 
-  void testIsValidThrowsWhenNoWorkspace()
-  {
+  void testIsValidThrowsWhenNoWorkspace() {
 
-    IMDWorkspace* nullWorkspace = NULL;
+    IMDWorkspace *nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
-    UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100);
-    vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 1);
+    UserDefinedThresholdRange *pRange = new UserDefinedThresholdRange(0, 100);
+    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);
+    TSM_ASSERT_THROWS(
+        "No workspace, so should not be possible to complete initialization.",
+        factory.initialize(ws_sptr), std::invalid_argument);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressAction;
 
     auto pRange =
@@ -141,28 +152,32 @@ public:
     TS_ASSERT_THROWS(factory.create(progressAction), std::runtime_error);
   }
 
-  void testInitializationDelegates()
-  {
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization
+  void testInitializationDelegates() {
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization
     // 2D workspace
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(pMockFactorySuccessor);
-    EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA"));
+    EXPECT_CALL(*pMockFactorySuccessor, initialize(_))
+        .Times(1); // expect it then to call initialize on the successor.
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
     auto pRange =
         Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100);
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
         vtkMDHistoHex4DFactory<TimeStepToTimeStep>(
             ThresholdRange_scptr(pRange.release()),
             Mantid::VATES::VolumeNormalization, (double)0);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
 
     factory.initialize(ws_sptr);
@@ -173,36 +188,43 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testInitializationDelegatesThrows()
-  {
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization. If there is no successor an exception should be thrown.
+  void testInitializationDelegatesThrows() {
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization. If there is no successor an exception should
+    // be thrown.
     // 2D workspace
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     auto pRange =
         Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100);
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
         vtkMDHistoHex4DFactory<TimeStepToTimeStep>(
             ThresholdRange_scptr(pRange.release()),
             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);
+    TSM_ASSERT_THROWS("Should have thrown an execption given that no successor "
+                      "was available.",
+                      factory.initialize(ws_sptr), std::runtime_error);
   }
 
-  void testCreateDelegates()
-  {
+  void testCreateDelegates() {
     FakeProgressAction progressUpdate;
 
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization
     // 2D workspace
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(pMockFactorySuccessor);
-    EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor.
+    EXPECT_CALL(*pMockFactorySuccessor, initialize(_))
+        .Times(1); // expect it then to call initialize on the successor.
     EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate)))
         .Times(1)
         .WillOnce(
@@ -210,18 +232,20 @@ public:
                                                                 // then to call
                                                                 // create on the
                                                                 // successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA"));
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
     auto pRange =
         Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100);
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory =
         vtkMDHistoHex4DFactory<TimeStepToTimeStep>(
             ThresholdRange_scptr(pRange.release()),
             Mantid::VATES::VolumeNormalization, (double)0);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
 
     factory.initialize(ws_sptr);
@@ -233,8 +257,7 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testTypeName()
-  {
+  void testTypeName() {
     using namespace Mantid::VATES;
 
     auto pRange =
@@ -246,27 +269,23 @@ public:
             Mantid::VATES::VolumeNormalization, (double)0);
     TS_ASSERT_EQUALS("vtkMDHistoHex4DFactory", factory.getFactoryTypeName());
   }
-
 };
 
 //=====================================================================================
 // Performance Tests
 //=====================================================================================
-class vtkMDHistoHex4DFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDHistoHex4DFactoryTestPerformance : public CxxTest::TestSuite {
 private:
-
   Mantid::API::IMDWorkspace_sptr m_ws_sptr;
 
 public:
   void setUp() override {
-    //Create a 4D workspace 50 ^ 4
+    // Create a 4D workspace 50 ^ 4
     m_ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4, 50);
     m_ws_sptr->setTransformFromOriginal(new NullCoordTransform);
   }
 
-  void testGenerateVTKDataSet()
-  {
+  void testGenerateVTKDataSet() {
     FakeProgressAction progressUpdate;
 
     auto pRange =
@@ -277,8 +296,6 @@ public:
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
   }
-
 };
 
-
 #endif
diff --git a/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
index b69e7e127b9d521b606e8d72089fc7c6734b1f59..3cdb9c9515afec087463f1415b81ee773a60b967 100644
--- a/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h
@@ -26,17 +26,15 @@ using namespace testing;
 //=====================================================================================
 // Functional Tests
 //=====================================================================================
-class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
-{
+class vtkMDHistoHexFactoryTest : public CxxTest::TestSuite {
 
-  public:
-
-  void testThresholds()
-  {
+public:
+  void testThresholds() {
     FakeProgressAction progressUpdate;
 
     // Workspace with value 1.0 everywhere
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
     ws_sptr->setTransformFromOriginal(new NullCoordTransform);
 
     vtkMDHistoHexFactory inside(
@@ -60,7 +58,7 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     auto aboveData = above.create(progressUpdate);
     auto aboveProduct = vtkStructuredGrid::SafeDownCast(aboveData.Get());
 
-    TS_ASSERT_EQUALS((10*10*10), insideProduct->GetNumberOfCells());
+    TS_ASSERT_EQUALS((10 * 10 * 10), insideProduct->GetNumberOfCells());
     for (auto i = 0; i < insideProduct->GetNumberOfCells(); ++i) {
       TS_ASSERT(insideProduct->IsCellVisible(i) != 0);
     }
@@ -77,58 +75,67 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     }
   }
 
-  void testSignalAspects()
-  {
+  void testSignalAspects() {
     FakeProgressAction progressUpdate;
 
     // Workspace with value 1.0 everywhere
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
     ws_sptr->setTransformFromOriginal(new NullCoordTransform);
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
     factory.initialize(ws_sptr);
 
     auto 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"), std::string(signalData->GetName()));
+    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"),
+                      std::string(signalData->GetName()));
     const int correctCellNumber = 10 * 10 * 10;
-    TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", correctCellNumber, signalData->GetSize());
+    TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.",
+                      correctCellNumber, signalData->GetSize());
   }
 
-  void testProgressUpdating()
-  {
+  void testProgressUpdating() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
 
-    MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
     vtkMDHistoHexFactory factory(boost::make_shared<NoThresholdRange>(),
                                  Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     auto product = factory.create(mockProgressAction);
 
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
   }
 
-  void testIsValidThrowsWhenNoWorkspace()
-  {
-    IMDWorkspace* nullWorkspace = NULL;
+  void testIsValidThrowsWhenNoWorkspace() {
+    IMDWorkspace *nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
     vtkMDHistoHexFactory factory(
         boost::make_shared<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);
+    TSM_ASSERT_THROWS(
+        "No workspace, so should not be possible to complete initialization.",
+        factory.initialize(ws_sptr), std::invalid_argument);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
@@ -136,26 +143,29 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testInitializationDelegates()
-  {
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+  void testInitializationDelegates() {
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(pMockFactorySuccessor);
     EXPECT_CALL(*pMockFactorySuccessor, initialize(_))
         .Times(1); // expect it then to call initialize on the successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
-    
+
     factory.initialize(ws_sptr);
 
     // Need the raw pointer to test assertions here. Object is not yet deleted
@@ -164,25 +174,31 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testInitializationDelegatesThrows()
-  {
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization. If there is no successor an exception should be thrown.
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+  void testInitializationDelegatesThrows() {
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization. If there is no successor an exception should
+    // be thrown.
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHexFactory factory(
         boost::make_shared<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);
+    TSM_ASSERT_THROWS("Should have thrown an execption given that no successor "
+                      "was available.",
+                      factory.initialize(ws_sptr), std::runtime_error);
   }
 
-  void testCreateDelegates()
-  {
+  void testCreateDelegates() {
     FakeProgressAction progressUpdate;
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization
-    //2 dimensions on the workspace.
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization
+    // 2 dimensions on the workspace.
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
@@ -196,17 +212,18 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
                                                                 // then to call
                                                                 // create on the
                                                                 // successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
-
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
-    
+
     factory.initialize(ws_sptr);
     factory.create(progressUpdate); // should be called on successor.
 
@@ -216,45 +233,40 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testTypeName()
-  {
+  void testTypeName() {
     using namespace Mantid::VATES;
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoHexFactory", factory.getFactoryTypeName());
   }
-
 };
 
 //=====================================================================================
 // Performance tests
 //=====================================================================================
-class vtkMDHistoHexFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDHistoHexFactoryTestPerformance : public CxxTest::TestSuite {
 private:
-
   Mantid::API::IMDWorkspace_sptr m_ws_sptr;
 
 public:
   void setUp() override {
-    //Create the workspace. 20 bins in each dimension.
+    // Create the workspace. 20 bins in each dimension.
     m_ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3, 100);
     m_ws_sptr->setTransformFromOriginal(new NullCoordTransform);
   }
 
-	void testGenerateHexahedronVtkDataSet()
-	{
+  void testGenerateHexahedronVtkDataSet() {
     FakeProgressAction progressUpdate;
 
-    //Create the factory.
+    // Create the factory.
     vtkMDHistoHexFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
 
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
-	}
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
index 7d4d6f0f601816da5e6307c969d47a7ecb0214cf..af30d6e400a5b8260ff0fa8bffe31f94861ae9d2 100644
--- a/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h
@@ -21,40 +21,44 @@ using namespace Mantid::Geometry;
 using namespace Mantid::VATES;
 using namespace testing;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkMDHistoLineFactoryTest: public CxxTest::TestSuite
-{
+class vtkMDHistoLineFactoryTest : public CxxTest::TestSuite {
 
 public:
-
-  void testIsValidThrowsWhenNoWorkspace()
-  {
-    IMDWorkspace* nullWorkspace = NULL;
+  void testIsValidThrowsWhenNoWorkspace() {
+    IMDWorkspace *nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
+    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);
+    TSM_ASSERT_THROWS(
+        "No workspace, so should not be possible to complete initialization.",
+        factory.initialize(ws_sptr), std::invalid_argument);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
-    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization);
+    vtkMDHistoLineFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),
+        Mantid::VATES::VolumeNormalization);
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testInsideThresholds()
-  {
+  void testInsideThresholds() {
     FakeProgressAction progressUpdate;
 
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    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)), Mantid::VATES::VolumeNormalization);
+    // 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)),
+        Mantid::VATES::VolumeNormalization);
     inside.initialize(ws_sptr);
     auto insideData = inside.create(progressUpdate);
     auto insideProduct = vtkUnstructuredGrid::SafeDownCast(insideData.Get());
@@ -63,17 +67,20 @@ public:
     TS_ASSERT_EQUALS(10, insideProduct->GetNumberOfPoints());
   }
 
-  void testAboveThreshold()
-  {
+  void testAboveThreshold() {
     using namespace Mantid::Geometry;
     using namespace testing;
 
     FakeProgressAction progressUpdate;
 
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    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)), Mantid::VATES::VolumeNormalization);
+    // 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)),
+        Mantid::VATES::VolumeNormalization);
     above.initialize(ws_sptr);
     auto aboveData = above.create(progressUpdate);
     auto aboveProduct = vtkUnstructuredGrid::SafeDownCast(aboveData.Get());
@@ -82,14 +89,17 @@ public:
     TS_ASSERT_EQUALS(10, aboveProduct->GetNumberOfPoints());
   }
 
-  void testBelowThreshold()
-  {
+  void testBelowThreshold() {
     FakeProgressAction progressUpdate;
 
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    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)), Mantid::VATES::VolumeNormalization);
+    // 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)),
+        Mantid::VATES::VolumeNormalization);
     below.initialize(ws_sptr);
     auto belowData = below.create(progressUpdate);
     auto belowProduct = vtkUnstructuredGrid::SafeDownCast(belowData.Get());
@@ -98,38 +108,47 @@ public:
     TS_ASSERT_EQUALS(10, belowProduct->GetNumberOfPoints());
   }
 
-  void testProgressUpdates()
-  {
+  void testProgressUpdates() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    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), Mantid::VATES::VolumeNormalization);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    vtkMDHistoLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),
+                                  Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     auto product = factory.create(mockProgressAction);
 
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
   }
 
-  void testInitializationDelegates()
-  {
-    //If the workspace provided is not a 1D imdworkspace, it should call the successor's initalization
+  void testInitializationDelegates() {
+    // If the workspace provided is not a 1D imdworkspace, it should call the
+    // successor's initalization
     // 3 dimensions on the workspace
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(pMockFactorySuccessor);
     EXPECT_CALL(*pMockFactorySuccessor, initialize(_))
         .Times(1); // expect it then to call initialize on the successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
+    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)), Mantid::VATES::VolumeNormalization);
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
+    vtkMDHistoLineFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),
+        Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
     factory.initialize(ws_sptr);
 
@@ -139,24 +158,32 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testInitializationDelegatesThrows()
-  {
-    //If the workspace provided is not a 2D imdworkspace, it should call the successor's initalization. If there is no successor an exception should be thrown.
+  void testInitializationDelegatesThrows() {
+    // If the workspace provided is not a 2D imdworkspace, it should call the
+    // successor's initalization. If there is no successor an exception should
+    // be thrown.
     // 3 dimensions on the workspace
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    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)),Mantid::VATES::VolumeNormalization);
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
+    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);
+    TSM_ASSERT_THROWS("Should have thrown an execption given that no successor "
+                      "was available.",
+                      factory.initialize(ws_sptr), std::runtime_error);
   }
 
-  void testCreateDelegates()
-  {
+  void testCreateDelegates() {
     FakeProgressAction progressUpdate;
-    //If the workspace provided is not a 2D imdworkspace, it should call the successor's initalization
+    // If the workspace provided is not a 2D imdworkspace, it should call the
+    // successor's initalization
     // 3 dimensions on the workspace
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
@@ -170,16 +197,18 @@ public:
                                                                 // then to call
                                                                 // create on the
                                                                 // successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     vtkMDHistoLineFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
-    
+
     factory.initialize(ws_sptr);
     factory.create(progressUpdate); // should be called on successor.
 
@@ -189,41 +218,38 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testTypeName()
-  {
+  void testTypeName() {
     vtkMDHistoLineFactory factory(
         boost::make_shared<UserDefinedThresholdRange>(0, 10000),
         Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoLineFactory", factory.getFactoryTypeName());
   }
-
 };
 
 //=====================================================================================
 // Performance tests
 //=====================================================================================
-class vtkMDHistoLineFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDHistoLineFactoryTestPerformance : public CxxTest::TestSuite {
 
 private:
-   Mantid::API::IMDWorkspace_sptr m_ws_sptr;
+  Mantid::API::IMDWorkspace_sptr m_ws_sptr;
+
 public:
   void setUp() override {
-    //1D Workspace with 2000 points
+    // 1D Workspace with 2000 points
     m_ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1, 200000);
   }
 
-	void testGenerateVTKDataSet()
-	{
+  void testGenerateVTKDataSet() {
     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.
+    // 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(
         boost::make_shared<UserDefinedThresholdRange>(0, 2),
         Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
-	}
-
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
index b101636f2f2aecb890a2c956d92c551f4af27f3d..b03dba696237abf56a195cc898d6d5692b911f64 100644
--- a/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h
@@ -22,31 +22,28 @@ using namespace Mantid::VATES;
 using namespace testing;
 using Mantid::DataObjects::MDEventsTestHelper::makeFakeMDHistoWorkspace;
 
-
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkMDHistoQuadFactoryTest: public CxxTest::TestSuite
-{
+class vtkMDHistoQuadFactoryTest : public CxxTest::TestSuite {
 
 public:
-
-  void testIsValidThrowsWhenNoWorkspace()
-  {
+  void testIsValidThrowsWhenNoWorkspace() {
     using namespace Mantid::VATES;
     using namespace Mantid::API;
 
-    IMDWorkspace* nullWorkspace = NULL;
+    IMDWorkspace *nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 100);
     vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization);
 
-    TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument);
+    TSM_ASSERT_THROWS(
+        "No workspace, so should not be possible to complete initialization.",
+        factory.initialize(ws_sptr), std::invalid_argument);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
 
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 100);
@@ -54,12 +51,12 @@ public:
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testInsideThresholds()
-  {
+  void testInsideThresholds() {
     FakeProgressAction progressUpdate;
 
     // WS with 2 dimensions
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     // Thresholds have been set such that the signal values (hard-coded to 1,
     // see above) will fall between the minimum 0 and maximum 2.
@@ -70,15 +67,15 @@ public:
     auto data = vtkDataSet::SafeDownCast(product.Get());
     vtkSmartPointer<vtkDataSet> insideProduct(data);
 
-    TS_ASSERT_EQUALS((10*10), insideProduct->GetNumberOfCells());
-    TS_ASSERT_EQUALS((11*11), insideProduct->GetNumberOfPoints());
+    TS_ASSERT_EQUALS((10 * 10), insideProduct->GetNumberOfCells());
+    TS_ASSERT_EQUALS((11 * 11), insideProduct->GetNumberOfPoints());
   }
 
-  void testAboveThreshold()
-  {
+  void testAboveThreshold() {
     FakeProgressAction progressUpdate;
     // WS with 2 dimensions
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     // 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.
@@ -89,17 +86,19 @@ public:
     auto data = vtkDataSet::SafeDownCast(product.Get());
     vtkSmartPointer<vtkDataSet> aboveProduct(data);
 
-    // This changed from previously, in order to ensure that we do not pass on empty 
-    // workspaces. A single point is created in the center by the vtkNullUnstructuredGrid
+    // This changed from previously, in order to ensure that we do not pass on
+    // empty
+    // workspaces. A single point is created in the center by the
+    // vtkNullUnstructuredGrid
     TS_ASSERT_EQUALS(1, aboveProduct->GetNumberOfCells());
     TS_ASSERT_EQUALS(1, aboveProduct->GetNumberOfPoints());
   }
 
-  void testBelowThreshold()
-  {
+  void testBelowThreshold() {
     FakeProgressAction progressUpdate;
     // WS with 2 dimensions
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
 
     // 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.
@@ -111,30 +110,35 @@ public:
     auto data = vtkUnstructuredGrid::SafeDownCast(product.Get());
     vtkSmartPointer<vtkDataSet> belowProduct(data);
 
-    // This changed from previously, in order to ensure that we do not pass on empty 
-    // workspaces. A single point is created in the center by the vtkNullUnstructuredGrid
+    // This changed from previously, in order to ensure that we do not pass on
+    // empty
+    // workspaces. A single point is created in the center by the
+    // vtkNullUnstructuredGrid
     TS_ASSERT_EQUALS(1, belowProduct->GetNumberOfCells());
     TS_ASSERT_EQUALS(1, belowProduct->GetNumberOfPoints());
   }
 
-  void testInitializationDelegates()
-  {
-    //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization
+  void testInitializationDelegates() {
+    // If the workspace provided is not a 4D imdworkspace, it should call the
+    // successor's initalization
     // WS with 1 dimension
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(pMockFactorySuccessor);
     EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
         .WillOnce(testing::Return("TypeA"));
-    EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor.
+    EXPECT_CALL(*pMockFactorySuccessor, initialize(_))
+        .Times(1); // expect it then to call initialize on the successor.
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1);
     vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
 
     factory.initialize(ws_sptr);
@@ -145,25 +149,32 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testInitializationDelegatesThrows()
-  {
-    //If the workspace provided is not a 2D imdworkspace, it should call the successor's initalization. If there is no successor an exception should be thrown.
+  void testInitializationDelegatesThrows() {
+    // If the workspace provided is not a 2D imdworkspace, it should call the
+    // successor's initalization. If there is no successor an exception should
+    // be thrown.
     // WS with 1 dimension
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
-
-    //Constructional method ensures that factory is only suitable for providing mesh information.
-    UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1);
-    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);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
+    UserDefinedThresholdRange *pRange = new UserDefinedThresholdRange(0, 1);
+    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);
   }
 
-  void testCreateDelegates()
-  {
+  void testCreateDelegates() {
     FakeProgressAction progressUpdate;
-    //If the workspace provided is not a 2D imdworkspace, it should call the successor's initalization
+    // If the workspace provided is not a 2D imdworkspace, it should call the
+    // successor's initalization
     // WS with 1 dimension
-    Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
+    Mantid::API::IMDWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1);
 
     auto pMockFactorySuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
@@ -177,13 +188,15 @@ public:
                                                                 // then to call
                                                                 // create on the
                                                                 // successor.
-    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); 
+    EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName())
+        .WillOnce(testing::Return("TypeA"));
 
-    //Constructional method ensures that factory is only suitable for providing mesh information.
+    // Constructional method ensures that factory is only suitable for providing
+    // mesh information.
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1);
     vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization);
 
-    //Successor is provided.
+    // Successor is provided.
     factory.setSuccessor(std::move(uniqueSuccessor));
 
     factory.initialize(ws_sptr);
@@ -195,35 +208,36 @@ public:
                Mock::VerifyAndClearExpectations(pMockFactorySuccessor));
   }
 
-  void testTypeName()
-  {
+  void testTypeName() {
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1);
     vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDHistoQuadFactory", factory.getFactoryTypeName());
   }
 
-  void testProgressUpdates()
-  {
+  void testProgressUpdates() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    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), Mantid::VATES::VolumeNormalization);
+    MDHistoWorkspace_sptr ws_sptr =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2);
+    vtkMDHistoQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange),
+                                  Mantid::VATES::VolumeNormalization);
 
     factory.initialize(ws_sptr);
     auto product = factory.create(mockProgressAction);
 
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
   }
-
 };
 
 //=====================================================================================
 // Performance tests
 //=====================================================================================
-class vtkMDHistoQuadFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDHistoQuadFactoryTestPerformance : public CxxTest::TestSuite {
 private:
   Mantid::API::IMDWorkspace_sptr m_ws_sptr;
 
@@ -234,15 +248,15 @@ public:
     m_ws_sptr->setTransformFromOriginal(new NullCoordTransform);
   }
 
-	void testGenerateVTKDataSet()
-	{
+  void testGenerateVTKDataSet() {
     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.
+    // Thresholds have been set such that the signal values (hard-coded to 1,
+    // see above) will fall between the minimum 0 and maximum 2.
     auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1);
     vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization);
     factory.initialize(m_ws_sptr);
     TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate));
-	}
+  }
 };
 
 #endif
diff --git a/Vates/VatesAPI/test/vtkMDLineFactoryTest.h b/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
index 1b7158b81db86d925128159ced0703035c7aed76..2189e58b48b7097d45d8d3d9f4103c47b004c4e2 100644
--- a/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDLineFactoryTest.h
@@ -21,19 +21,15 @@ using namespace testing;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkMDLineFactoryTest : public CxxTest::TestSuite
-{
+class vtkMDLineFactoryTest : public CxxTest::TestSuite {
 public:
-
-  void testGetFactoryTypeName()
-  {
+  void testGetFactoryTypeName() {
     vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDLineFactory", factory.getFactoryTypeName());
   }
 
-  void testInitializeDelegatesToSuccessor()
-  {
+  void testInitializeDelegatesToSuccessor() {
     auto mockSuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(mockSuccessor);
@@ -52,8 +48,7 @@ public:
                Mock::VerifyAndClearExpectations(mockSuccessor));
   }
 
-  void testCreateDelegatesToSuccessor()
-  {
+  void testCreateDelegatesToSuccessor() {
     FakeProgressAction progressUpdate;
 
     auto mockSuccessor = new MockvtkDataSetFactory();
@@ -77,46 +72,48 @@ public:
                Mock::VerifyAndClearExpectations(mockSuccessor));
   }
 
-  void testOnInitaliseCannotDelegateToSuccessor()
-  {
+  void testOnInitaliseCannotDelegateToSuccessor() {
     vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
-    //factory.SetSuccessor(mockSuccessor); No Successor set.
+    // factory.SetSuccessor(mockSuccessor); No Successor set.
 
     ITableWorkspace_sptr ws =
         boost::make_shared<Mantid::DataObjects::TableWorkspace>();
     TS_ASSERT_THROWS(factory.initialize(ws), std::runtime_error);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
 
     vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
-    //initialize not called!
+    // initialize not called!
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testCreation()
-  {
+  void testCreation() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
 
-    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<Mantid::DataObjects::MDEvent<1>,1> >
-            ws = MDEventsTestHelper::makeMDEWFull<1>(10, 10, 10, 10);
+    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<
+        Mantid::DataObjects::MDEvent<1>, 1>> ws =
+        MDEventsTestHelper::makeMDEWFull<1>(10, 10, 10, 10);
 
-    //Rebin it to make it possible to compare cells to bins.
+    // Rebin it to make it possible to compare cells to bins.
     using namespace Mantid::API;
-    IAlgorithm_sptr slice = AlgorithmManager::Instance().createUnmanaged("SliceMD");
+    IAlgorithm_sptr slice =
+        AlgorithmManager::Instance().createUnmanaged("SliceMD");
     slice->initialize();
     slice->setProperty("InputWorkspace", ws);
     slice->setPropertyValue("AlignedDim0", "Axis0, -10, 10, 100");
     slice->setPropertyValue("OutputWorkspace", "binned");
     slice->execute();
 
-    Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
+    Workspace_sptr binned =
+        Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
     vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
@@ -131,24 +128,25 @@ public:
     TS_ASSERT_EQUALS(VTK_LINE, product->GetCellType(0));
 
     AnalysisDataService::Instance().remove("binned");
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
   }
-
 };
 
 //=====================================================================================
 // Peformance tests
 //=====================================================================================
-class vtkMDLineFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDLineFactoryTestPerformance : public CxxTest::TestSuite {
 
 public:
   void setUp() override {
-    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<Mantid::DataObjects::MDEvent<1>,1> > input
-      = MDEventsTestHelper::makeMDEWFull<1>(2, 10, 10, 4000);
-    //Rebin it to make it possible to compare cells to bins.
+    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<
+        Mantid::DataObjects::MDEvent<1>, 1>> input =
+        MDEventsTestHelper::makeMDEWFull<1>(2, 10, 10, 4000);
+    // Rebin it to make it possible to compare cells to bins.
     using namespace Mantid::API;
-    IAlgorithm_sptr slice = AlgorithmManager::Instance().createUnmanaged("SliceMD");
+    IAlgorithm_sptr slice =
+        AlgorithmManager::Instance().createUnmanaged("SliceMD");
     slice->initialize();
     slice->setProperty("InputWorkspace", input);
     slice->setPropertyValue("AlignedDim0", "Axis0, -10, 10, 200000");
@@ -158,11 +156,11 @@ public:
 
   void tearDown() override { AnalysisDataService::Instance().remove("binned"); }
 
-  void testCreationOnLargeWorkspace()
-  {
+  void testCreationOnLargeWorkspace() {
     FakeProgressAction progressAction;
 
-    Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
+    Workspace_sptr binned =
+        Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
     vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
diff --git a/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h b/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
index 23427734845e56189ee7f50c34f75cb501866d0d..cc4674639bf0a10e1e4ee82c919dc876f299e408 100644
--- a/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h
@@ -1,5 +1,5 @@
 #ifndef VTK_MD_QUAD_FACTORY_TEST
-#define VTK_MD_QUAD_FACTORY_TEST 
+#define VTK_MD_QUAD_FACTORY_TEST
 
 #include <cxxtest/TestSuite.h>
 #include "MantidKernel/make_unique.h"
@@ -21,20 +21,16 @@ using namespace testing;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkMDQuadFactoryTest : public CxxTest::TestSuite
-{
+class vtkMDQuadFactoryTest : public CxxTest::TestSuite {
 
 public:
-
-  void testGetFactoryTypeName()
-  {
+  void testGetFactoryTypeName() {
     vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
     TS_ASSERT_EQUALS("vtkMDQuadFactory", factory.getFactoryTypeName());
   }
 
-  void testInitializeDelegatesToSuccessor()
-  {
+  void testInitializeDelegatesToSuccessor() {
     auto mockSuccessor = new MockvtkDataSetFactory();
     auto uniqueSuccessor =
         std::unique_ptr<MockvtkDataSetFactory>(mockSuccessor);
@@ -53,8 +49,7 @@ public:
                Mock::VerifyAndClearExpectations(mockSuccessor));
   }
 
-  void testCreateDelegatesToSuccessor()
-  {
+  void testCreateDelegatesToSuccessor() {
     FakeProgressAction progressUpdate;
 
     auto mockSuccessor = new MockvtkDataSetFactory();
@@ -79,39 +74,40 @@ public:
                Mock::VerifyAndClearExpectations(mockSuccessor));
   }
 
-  void testOnInitaliseCannotDelegateToSuccessor()
-  {
+  void testOnInitaliseCannotDelegateToSuccessor() {
     vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
-    //factory.SetSuccessor(mockSuccessor); No Successor set.
+    // factory.SetSuccessor(mockSuccessor); No Successor set.
 
     ITableWorkspace_sptr ws =
         boost::make_shared<Mantid::DataObjects::TableWorkspace>();
     TS_ASSERT_THROWS(factory.initialize(ws), std::runtime_error);
   }
 
-  void testCreateWithoutInitaliseThrows()
-  {
+  void testCreateWithoutInitaliseThrows() {
     FakeProgressAction progressUpdate;
 
     vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
-    //initialize not called!
+    // initialize not called!
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testCreation()
-  {
+  void testCreation() {
     MockProgressAction mockProgressAction;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
 
-    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<Mantid::DataObjects::MDEvent<2>,2> >
-            ws = MDEventsTestHelper::makeMDEWFull<2>(10, 10, 10, 10);
+    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<
+        Mantid::DataObjects::MDEvent<2>, 2>> ws =
+        MDEventsTestHelper::makeMDEWFull<2>(10, 10, 10, 10);
 
-    //Rebin it to make it possible to compare cells to bins.
+    // Rebin it to make it possible to compare cells to bins.
     using namespace Mantid::API;
-    IAlgorithm_sptr slice = AlgorithmManager::Instance().createUnmanaged("SliceMD");
+    IAlgorithm_sptr slice =
+        AlgorithmManager::Instance().createUnmanaged("SliceMD");
     slice->initialize();
     slice->setProperty("InputWorkspace", ws);
     slice->setPropertyValue("AlignedDim0", "Axis0, -10, 10, 10");
@@ -119,7 +115,8 @@ public:
     slice->setPropertyValue("OutputWorkspace", "binned");
     slice->execute();
 
-    Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
+    Workspace_sptr binned =
+        Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
     vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
@@ -132,26 +129,27 @@ public:
     TS_ASSERT_EQUALS(100, product->GetNumberOfCells());
     TS_ASSERT_EQUALS(400, product->GetNumberOfPoints());
     TS_ASSERT_EQUALS(VTK_QUAD, product->GetCellType(0));
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgressAction));
 
     AnalysisDataService::Instance().remove("binned");
   }
-
 };
 
 //=====================================================================================
 // Peformance tests
 //=====================================================================================
-class vtkMDQuadFactoryTestPerformance : public CxxTest::TestSuite
-{
+class vtkMDQuadFactoryTestPerformance : public CxxTest::TestSuite {
 
 public:
   void setUp() override {
-    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<Mantid::DataObjects::MDEvent<2>,2> > input 
-      = MDEventsTestHelper::makeMDEWFull<2>(10, 10, 10, 1000);
-    //Rebin it to make it possible to compare cells to bins.
+    boost::shared_ptr<Mantid::DataObjects::MDEventWorkspace<
+        Mantid::DataObjects::MDEvent<2>, 2>> input =
+        MDEventsTestHelper::makeMDEWFull<2>(10, 10, 10, 1000);
+    // Rebin it to make it possible to compare cells to bins.
     using namespace Mantid::API;
-    IAlgorithm_sptr slice = AlgorithmManager::Instance().createUnmanaged("SliceMD");
+    IAlgorithm_sptr slice =
+        AlgorithmManager::Instance().createUnmanaged("SliceMD");
     slice->initialize();
     slice->setProperty("InputWorkspace", input);
     slice->setPropertyValue("AlignedDim0", "Axis0, -10, 10, 400");
@@ -162,10 +160,10 @@ public:
 
   void tearDown() override { AnalysisDataService::Instance().remove("binned"); }
 
-  void testCreationOnLargeWorkspace()
-  {
+  void testCreationOnLargeWorkspace() {
     FakeProgressAction progressUpdate;
-    Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned");
+    Workspace_sptr binned =
+        Mantid::API::AnalysisDataService::Instance().retrieve("binned");
 
     vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(),
                              Mantid::VATES::VolumeNormalization);
@@ -176,9 +174,8 @@ public:
     TS_ASSERT(dynamic_cast<vtkUnstructuredGrid *>(product.GetPointer()) !=
               NULL);
     TS_ASSERT_EQUALS(160000, product->GetNumberOfCells());
-    TS_ASSERT_EQUALS(640000, product->GetNumberOfPoints());    
+    TS_ASSERT_EQUALS(640000, product->GetNumberOfPoints());
   }
 };
 
 #endif
-  
diff --git a/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h b/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h
index c71588fc1910b623086fc4c7f8478e9fd8533c67..e589941eae66c0ab572a3c86992f92cb911659da 100644
--- a/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h
@@ -31,43 +31,39 @@ public:
   MOCK_CONST_METHOD0(getPeakShape, const Mantid::Geometry::PeakShape &(void));
 };
 
-class MockPeak : public Peak
-{
+class MockPeak : public Peak {
 public:
-  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D (void));
-  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D (void));
+  MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void));
+  MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void));
 };
 
-class MockPeaksWorkspace : public PeaksWorkspace
-{
+class MockPeaksWorkspace : public PeaksWorkspace {
 public:
-  MOCK_METHOD1(setInstrument, void (const Mantid::Geometry::Instrument_const_sptr& inst));
-  MOCK_CONST_METHOD0(clone, Mantid::DataObjects::PeaksWorkspace*());
+  MOCK_METHOD1(setInstrument,
+               void(const Mantid::Geometry::Instrument_const_sptr &inst));
+  MOCK_CONST_METHOD0(clone, Mantid::DataObjects::PeaksWorkspace *());
   MOCK_CONST_METHOD0(getNumberPeaks, int());
-  MOCK_METHOD1(removePeak, void (int peakNum) );
-  MOCK_METHOD1(addPeak, void (const IPeak& ipeak));
-  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak & (int peakNum));
-  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak & (int peakNum));
+  MOCK_METHOD1(removePeak, void(int peakNum));
+  MOCK_METHOD1(addPeak, void(const IPeak &ipeak));
+  MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum));
+  MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum));
 };
 
 //=====================================================================================
 // Functional Tests
 //=====================================================================================
-class vtkPeakMarkerFactoryTest: public CxxTest::TestSuite
-{
+class vtkPeakMarkerFactoryTest : public CxxTest::TestSuite {
 
 public:
-
-  void do_test(MockPeak & peak1, vtkPeakMarkerFactory::ePeakDimensions dims)
-  {
+  void do_test(MockPeak &peak1, vtkPeakMarkerFactory::ePeakDimensions dims) {
     FakeProgressAction updateProgress;
     auto pw_ptr = boost::make_shared<MockPeaksWorkspace>();
-    MockPeaksWorkspace & pw = *pw_ptr;
+    MockPeaksWorkspace &pw = *pw_ptr;
 
-    //Peaks workspace will return 5 identical peaks
-    EXPECT_CALL( pw, getNumberPeaks()).WillOnce(Return(5));
-    EXPECT_CALL( pw, getPeak(_)).WillRepeatedly( ReturnRef( peak1 ));
+    // Peaks workspace will return 5 identical peaks
+    EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(5));
+    EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
 
     vtkPeakMarkerFactory factory("signal", dims);
     factory.initialize(pw_ptr);
@@ -83,104 +79,103 @@ public:
     TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1));
   }
 
-  void test_progress_updates()
-  {
+  void test_progress_updates() {
     MockPeak peak1;
-    EXPECT_CALL( peak1, getQLabFrame()).WillRepeatedly( Return( V3D(1,2,3) ));
-    EXPECT_CALL( peak1, getHKL()).Times(AnyNumber());
-    EXPECT_CALL( peak1, getQSampleFrame()).Times(AnyNumber());
+    EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(1, 2, 3)));
+    EXPECT_CALL(peak1, getHKL()).Times(AnyNumber());
+    EXPECT_CALL(peak1, getQSampleFrame()).Times(AnyNumber());
 
     MockProgressAction mockProgress;
-    //Expectation checks that progress should be >= 0 and <= 100 and called at least once!
-    EXPECT_CALL(mockProgress, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1));
+    // Expectation checks that progress should be >= 0 and <= 100 and called at
+    // least once!
+    EXPECT_CALL(mockProgress, eventRaised(AllOf(Le(100), Ge(0))))
+        .Times(AtLeast(1));
 
     boost::shared_ptr<MockPeaksWorkspace> pw_ptr =
         boost::make_shared<MockPeaksWorkspace>();
-    MockPeaksWorkspace & pw = *pw_ptr;
+    MockPeaksWorkspace &pw = *pw_ptr;
 
-    //Peaks workspace will return 5 identical peaks
-    EXPECT_CALL( pw, getNumberPeaks()).WillRepeatedly(Return(5));
-    EXPECT_CALL( pw, getPeak(_)).WillRepeatedly( ReturnRef( peak1 ));
+    // Peaks workspace will return 5 identical peaks
+    EXPECT_CALL(pw, getNumberPeaks()).WillRepeatedly(Return(5));
+    EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
 
     vtkPeakMarkerFactory factory("signal", vtkPeakMarkerFactory::Peak_in_Q_lab);
     factory.initialize(pw_ptr);
     auto set = factory.create(mockProgress);
 
-    TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgress));
+    TSM_ASSERT("Progress Updates not used as expected.",
+               Mock::VerifyAndClearExpectations(&mockProgress));
   }
 
-  void test_q_lab()
-  {
+  void test_q_lab() {
     MockPeak peak1;
-    EXPECT_CALL( peak1, getQLabFrame()).Times(5).WillRepeatedly( Return( V3D(1,2,3) ));
-    EXPECT_CALL( peak1, getHKL()).Times(0);
-    EXPECT_CALL( peak1, getQSampleFrame()).Times(0);
+    EXPECT_CALL(peak1, getQLabFrame())
+        .Times(5)
+        .WillRepeatedly(Return(V3D(1, 2, 3)));
+    EXPECT_CALL(peak1, getHKL()).Times(0);
+    EXPECT_CALL(peak1, getQSampleFrame()).Times(0);
 
     do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_lab);
   }
 
-  void test_q_sample()
-  {
+  void test_q_sample() {
     MockPeak peak1;
-    EXPECT_CALL( peak1, getQSampleFrame()).Times(5).WillRepeatedly( Return( V3D(1,2,3) ));
-    EXPECT_CALL( peak1, getHKL()).Times(0);
-    EXPECT_CALL( peak1, getQLabFrame()).Times(0);
+    EXPECT_CALL(peak1, getQSampleFrame())
+        .Times(5)
+        .WillRepeatedly(Return(V3D(1, 2, 3)));
+    EXPECT_CALL(peak1, getHKL()).Times(0);
+    EXPECT_CALL(peak1, getQLabFrame()).Times(0);
 
     do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_sample);
   }
 
-  void test_hkl()
-  {
+  void test_hkl() {
     MockPeak peak1;
-    EXPECT_CALL( peak1, getHKL()).Times(5).WillRepeatedly( Return( V3D(1,2,3) ));
-    EXPECT_CALL( peak1, getQLabFrame()).Times(0);
-    EXPECT_CALL( peak1, getQSampleFrame()).Times(0);
+    EXPECT_CALL(peak1, getHKL()).Times(5).WillRepeatedly(Return(V3D(1, 2, 3)));
+    EXPECT_CALL(peak1, getQLabFrame()).Times(0);
+    EXPECT_CALL(peak1, getQSampleFrame()).Times(0);
 
     do_test(peak1, vtkPeakMarkerFactory::Peak_in_HKL);
   }
 
-  void testIsValidThrowsWhenNoWorkspace()
-  {
+  void testIsValidThrowsWhenNoWorkspace() {
     using namespace Mantid::VATES;
     using namespace Mantid::API;
 
-    IMDWorkspace* nullWorkspace = NULL;
+    IMDWorkspace *nullWorkspace = NULL;
     Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
 
     vtkPeakMarkerFactory factory("signal");
 
-    TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::runtime_error);
+    TSM_ASSERT_THROWS(
+        "No workspace, so should not be possible to complete initialization.",
+        factory.initialize(ws_sptr), std::runtime_error);
   }
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
     vtkPeakMarkerFactory factory("signal");
     TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testTypeName()
-  {
-    vtkPeakMarkerFactory factory ("signal");
+  void testTypeName() {
+    vtkPeakMarkerFactory factory("signal");
     TS_ASSERT_EQUALS("vtkPeakMarkerFactory", factory.getFactoryTypeName());
   }
 
-  void testGetPeakRadiusDefault()
-  {
+  void testGetPeakRadiusDefault() {
     vtkPeakMarkerFactory factory("signal");
     TS_ASSERT_EQUALS(-1, factory.getIntegrationRadius());
   }
 
-  void testIsPeaksWorkspaceIntegratedDefault()
-  {
+  void testIsPeaksWorkspaceIntegratedDefault() {
     vtkPeakMarkerFactory factory("signal");
     TS_ASSERT_EQUALS(false, factory.isPeaksWorkspaceIntegrated());
   }
 
-  void testGetPeakRadiusWhenNotIntegrated()
-  {
+  void testGetPeakRadiusWhenNotIntegrated() {
     auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
-    const double expectedRadius =-1; // The default
+    const double expectedRadius = -1; // The default
     // Note that no PeaksRadius property has been set.
 
     vtkPeakMarkerFactory factory("signal");
@@ -189,22 +184,24 @@ public:
     TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius());
   }
 
-  void testIsPeaksWorkspaceIntegratedWhenNotIntegrated()
-  {
+  void testIsPeaksWorkspaceIntegratedWhenNotIntegrated() {
     auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
     // Note that no PeaksRadius property has been set.
 
     vtkPeakMarkerFactory factory("signal");
     factory.initialize(
         Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
-    TS_ASSERT_EQUALS(false, factory.isPeaksWorkspaceIntegrated()); // false is the default
+    TS_ASSERT_EQUALS(
+        false, factory.isPeaksWorkspaceIntegrated()); // false is the default
   }
 
-  void testGetPeakRadiusWhenIntegrated()
-  {
+  void testGetPeakRadiusWhenIntegrated() {
     auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
     const double expectedRadius = 4;
-    mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must have been processed via IntegratePeaksMD
+    mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius,
+                                            true); // Has a PeaksRadius so must
+                                                   // have been processed via
+                                                   // IntegratePeaksMD
 
     vtkPeakMarkerFactory factory("signal");
     factory.initialize(
@@ -212,16 +209,18 @@ public:
     TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius());
   }
 
-  void testIsPeaksWorkspaceIntegratedWhenIntegrated()
-  {
+  void testIsPeaksWorkspaceIntegratedWhenIntegrated() {
     auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
     const double expectedRadius = 4;
-    mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must have been processed via IntegratePeaksMD
+    mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius,
+                                            true); // Has a PeaksRadius so must
+                                                   // have been processed via
+                                                   // IntegratePeaksMD
 
     vtkPeakMarkerFactory factory("signal");
     factory.initialize(
         Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
-    TS_ASSERT_EQUALS(true, factory.isPeaksWorkspaceIntegrated()); 
+    TS_ASSERT_EQUALS(true, factory.isPeaksWorkspaceIntegrated());
   }
 
   void testShapeOfSphere() {
@@ -312,5 +311,4 @@ public:
   }
 };
 
-
 #endif
diff --git a/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h b/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h
index b85a3bca75cfae3bb179cc1ce92e56a91ba17658..39df83afdf9000121f1b8bcdba9ee29a61c5e971 100644
--- a/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h
+++ b/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h
@@ -30,86 +30,105 @@ using namespace testing;
 //=====================================================================================
 // Functional tests
 //=====================================================================================
-class vtkSplatterPlotFactoryTest : public CxxTest::TestSuite
-{
+class vtkSplatterPlotFactoryTest : public CxxTest::TestSuite {
 
 public:
-
   /* Destructive tests. Test works correctly when misused.*/
 
-  void testCreateWithoutInitializeThrows()
-  {
+  void testCreateWithoutInitializeThrows() {
     FakeProgressAction progressUpdate;
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
-    TSM_ASSERT_THROWS("Have NOT initalized object. Should throw.", factory.create(progressUpdate), std::runtime_error);
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    TSM_ASSERT_THROWS("Have NOT initalized object. Should throw.",
+                      factory.create(progressUpdate), std::runtime_error);
   }
 
-  void testInitializeWithNullWorkspaceThrows()
-  {
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
-    IMDEventWorkspace* ws = NULL;
-    TSM_ASSERT_THROWS("This is a NULL workspace. Should throw.", factory.initialize( Workspace_sptr(ws) ), std::invalid_argument);
+  void testInitializeWithNullWorkspaceThrows() {
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    IMDEventWorkspace *ws = NULL;
+    TSM_ASSERT_THROWS("This is a NULL workspace. Should throw.",
+                      factory.initialize(Workspace_sptr(ws)),
+                      std::invalid_argument);
   }
 
   /*Demonstrative tests*/
-  void test_3DHistoWorkspace()
-  {
+  void test_3DHistoWorkspace() {
     FakeProgressAction progressUpdate;
 
-    // Create workspace with 5x5x5 binning 
+    // Create workspace with 5x5x5 binning
     size_t binning = 5;
-    MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3, binning);
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    MDHistoWorkspace_sptr ws =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3, binning);
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
     factory.initialize(ws);
     vtkSmartPointer<vtkDataSet> product;
 
     TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate));
 
     // Expecting 5x5x5 points; Signal equal for each box => 1/(10^3/5^3)
-    const size_t expected_n_points = binning*binning*binning;
-    const size_t expected_n_cells = binning*binning*binning;
+    const size_t expected_n_points = binning * binning * binning;
+    const size_t expected_n_cells = binning * binning * binning;
     const size_t expected_n_signals = expected_n_cells;
-    const double expected_signal_value = 1.0/((10.0*10.0*10.0)/(5.0*5.0*5.0));
+    const double expected_signal_value =
+        1.0 / ((10.0 * 10.0 * 10.0) / (5.0 * 5.0 * 5.0));
 
-    double* range = product->GetScalarRange();
+    double *range = product->GetScalarRange();
 
-    TSM_ASSERT_EQUALS("Should have one point per bin.", expected_n_points, product->GetNumberOfPoints());
-    TSM_ASSERT_EQUALS("Should have one cells per bin", expected_n_cells, product->GetNumberOfCells());
-    TSM_ASSERT_EQUALS("Should have signal flag", "signal", std::string(product->GetCellData()->GetArray(0)->GetName()));
-    TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize());
-    TSM_ASSERT_EQUALS("Should have a signal which is normalized to the 3D volume", expected_signal_value, range[0]);
+    TSM_ASSERT_EQUALS("Should have one point per bin.", expected_n_points,
+                      product->GetNumberOfPoints());
+    TSM_ASSERT_EQUALS("Should have one cells per bin", expected_n_cells,
+                      product->GetNumberOfCells());
+    TSM_ASSERT_EQUALS(
+        "Should have signal flag", "signal",
+        std::string(product->GetCellData()->GetArray(0)->GetName()));
+    TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals,
+                      product->GetCellData()->GetArray(0)->GetSize());
+    TSM_ASSERT_EQUALS(
+        "Should have a signal which is normalized to the 3D volume",
+        expected_signal_value, range[0]);
   }
 
-  void test_4DHistoWorkspace()
-  {
+  void test_4DHistoWorkspace() {
     FakeProgressAction progressUpdate;
 
-    // Create workspace with  5x5x5x5 binning, signal is 1 and extent for each dimension is 10
+    // Create workspace with  5x5x5x5 binning, signal is 1 and extent for each
+    // dimension is 10
     size_t binning = 5;
-    IMDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4, binning);
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    IMDHistoWorkspace_sptr ws =
+        MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4, binning);
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
     factory.initialize(ws);
     vtkSmartPointer<vtkDataSet> product;
 
     TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate));
 
     // Expecting 5x5x5 points; Signal equal for each box => 1/(10^4/5^4)
-    const size_t expected_n_points = binning*binning*binning;
-    const size_t expected_n_cells = binning*binning*binning;
+    const size_t expected_n_points = binning * binning * binning;
+    const size_t expected_n_cells = binning * binning * binning;
     const size_t expected_n_signals = expected_n_cells;
-    const double expected_signal_value = 1.0/((10.0*10.0*10.0*10.0)/(5.0*5.0*5.0*5.0));
+    const double expected_signal_value =
+        1.0 / ((10.0 * 10.0 * 10.0 * 10.0) / (5.0 * 5.0 * 5.0 * 5.0));
 
-    double* range = product->GetScalarRange();
+    double *range = product->GetScalarRange();
 
-    TSM_ASSERT_EQUALS("Should have one point per bin.", expected_n_points, product->GetNumberOfPoints());
-    TSM_ASSERT_EQUALS("Should have one cells per bin", expected_n_cells, product->GetNumberOfCells());
-    TSM_ASSERT_EQUALS("Should have signal flag", "signal", std::string(product->GetCellData()->GetArray(0)->GetName()));
-    TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize());
-    TSM_ASSERT_EQUALS("Should have a signal which is normalized to the 4D volume", expected_signal_value, range[0]);
+    TSM_ASSERT_EQUALS("Should have one point per bin.", expected_n_points,
+                      product->GetNumberOfPoints());
+    TSM_ASSERT_EQUALS("Should have one cells per bin", expected_n_cells,
+                      product->GetNumberOfCells());
+    TSM_ASSERT_EQUALS(
+        "Should have signal flag", "signal",
+        std::string(product->GetCellData()->GetArray(0)->GetName()));
+    TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals,
+                      product->GetCellData()->GetArray(0)->GetSize());
+    TSM_ASSERT_EQUALS(
+        "Should have a signal which is normalized to the 4D volume",
+        expected_signal_value, range[0]);
   }
 
-  void test_3DWorkspace()
-  {
+  void test_3DWorkspace() {
     FakeProgressAction progressUpdate;
 
     MDEventWorkspace3Lean::sptr ws =
@@ -126,15 +145,17 @@ public:
     const size_t expected_n_cells = 999;
     */
 
-    // New sizes for splatter plot test, after changing the way the points 
+    // New sizes for splatter plot test, after changing the way the points
     // are selected, 5/28/2013
     const size_t expected_n_points = 50;
     const size_t expected_n_cells = 0;
 
     const size_t expected_n_signals = expected_n_points;
 
-    TSM_ASSERT_EQUALS("Wrong number of points", expected_n_points, product->GetNumberOfPoints());
-    TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells, product->GetNumberOfCells());
+    TSM_ASSERT_EQUALS("Wrong number of points", expected_n_points,
+                      product->GetNumberOfPoints());
+    TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells,
+                      product->GetNumberOfCells());
     TSM_ASSERT_EQUALS(
         "No signal Array", "signal",
         std::string(product->GetPointData()->GetArray(0)->GetName()));
@@ -145,8 +166,10 @@ public:
   void xtest_4DWorkspace() {
     FakeProgressAction progressUpdate;
 
-    MDEventWorkspace4Lean::sptr ws = MDEventsTestHelper::makeMDEW<4>(5, -10.0, 10.0, 1);
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    MDEventWorkspace4Lean::sptr ws =
+        MDEventsTestHelper::makeMDEW<4>(5, -10.0, 10.0, 1);
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
     factory.initialize(ws);
     vtkSmartPointer<vtkDataSet> product;
 
@@ -157,8 +180,10 @@ public:
     const size_t expected_n_cells = 0;
     const size_t expected_n_signals = expected_n_points;
 
-    TSM_ASSERT_EQUALS("Wrong number of points", expected_n_points, product->GetNumberOfPoints());
-    TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells, product->GetNumberOfCells());
+    TSM_ASSERT_EQUALS("Wrong number of points", expected_n_points,
+                      product->GetNumberOfPoints());
+    TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells,
+                      product->GetNumberOfCells());
     TSM_ASSERT_EQUALS(
         "No signal Array", "signal",
         std::string(product->GetPointData()->GetArray(0)->GetName()));
@@ -166,42 +191,52 @@ public:
                       product->GetPointData()->GetArray(0)->GetSize());
   }
 
-  void test_MetadataIsAddedCorrectly() 
-  {
-    // Arrange 
-    vtkFieldData* fakeInputFieldDataWithXML = vtkFieldData::New();
+  void test_MetadataIsAddedCorrectly() {
+    // Arrange
+    vtkFieldData *fakeInputFieldDataWithXML = vtkFieldData::New();
     std::string xmlString = "myXmlString";
     MetadataToFieldData converterMtoF;
-    converterMtoF(fakeInputFieldDataWithXML, xmlString, XMLDefinitions::metaDataId().c_str());
-
+    converterMtoF(fakeInputFieldDataWithXML, xmlString,
+                  XMLDefinitions::metaDataId().c_str());
 
     FakeProgressAction progressUpdate;
-    MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 1);
-    vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
+    MDEventWorkspace3Lean::sptr ws =
+        MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 1);
+    vtkSplatterPlotFactory factory(
+        ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal");
     factory.initialize(ws);
-    vtkDataSet* product = NULL;
+    vtkDataSet *product = NULL;
 
     // Act
     TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate));
-    TS_ASSERT_THROWS_NOTHING(factory.setMetadata(fakeInputFieldDataWithXML, product));
+    TS_ASSERT_THROWS_NOTHING(
+        factory.setMetadata(fakeInputFieldDataWithXML, product));
 
     // Assert
     FieldDataToMetadata converterFtoM;
-    vtkFieldData* fd = product->GetFieldData();
-    std::string xmlOut; 
+    vtkFieldData *fd = product->GetFieldData();
+    std::string xmlOut;
     std::string jsonOut;
     VatesConfigurations vatesConfigurations;
 
-    TSM_ASSERT_EQUALS("One array expected on field data, one for XML and one for JSON!", 2, product->GetFieldData()->GetNumberOfArrays());
+    TSM_ASSERT_EQUALS(
+        "One array expected on field data, one for XML and one for JSON!", 2,
+        product->GetFieldData()->GetNumberOfArrays());
 
-    TSM_ASSERT_THROWS_NOTHING("There is XML metadata!", xmlOut = converterFtoM(fd, XMLDefinitions::metaDataId().c_str()));
-    TSM_ASSERT_THROWS_NOTHING("There is JSON metadata!", jsonOut = converterFtoM(fd, vatesConfigurations.getMetadataIdJson().c_str()));
+    TSM_ASSERT_THROWS_NOTHING(
+        "There is XML metadata!",
+        xmlOut = converterFtoM(fd, XMLDefinitions::metaDataId().c_str()));
+    TSM_ASSERT_THROWS_NOTHING(
+        "There is JSON metadata!",
+        jsonOut =
+            converterFtoM(fd, vatesConfigurations.getMetadataIdJson().c_str()));
 
     TSM_ASSERT("The xml string should be retrieved", xmlOut == xmlString);
 
     MetadataJsonManager manager;
     manager.readInSerializedJson(jsonOut);
-    TSM_ASSERT("The instrument should be empty", manager.getInstrument().empty());
+    TSM_ASSERT("The instrument should be empty",
+               manager.getInstrument().empty());
     TSM_ASSERT_EQUALS("The max value is 1", 1.0, manager.getMaxValue());
     TSM_ASSERT_EQUALS("The min value is 1", 1.0, manager.getMinValue());
   }
diff --git a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/AxisInformation.h b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/AxisInformation.h
index c4aac96afb07dcf26951802c25e75cd7b194a952..29b6143644ab50b00e690495af9c5134e9ce4341 100644
--- a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/AxisInformation.h
+++ b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/AxisInformation.h
@@ -5,12 +5,9 @@
 
 #include <string>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 /**
  *
   This class provides a container for a given data axis information.
@@ -18,7 +15,8 @@ namespace SimpleGui
   @author Michael Reuter
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -38,8 +36,7 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS AxisInformation
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS AxisInformation {
 public:
   /// Default constructor.
   AxisInformation();
@@ -80,10 +77,9 @@ public:
 
 private:
   std::string title; ///< The axis title (or label)
-  double minimum; ///< The minimum extent of the axis
-  double maximum; ///< The maximum extent of the axis
+  double minimum;    ///< The minimum extent of the axis
+  double maximum;    ///< The maximum extent of the axis
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/GeometryParser.h b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/GeometryParser.h
index 9e0fcf53640c5f07bb29754e941c3550afbb5fd3..aeaef286f4fa37aed31696cd8d43a839f39a687a 100644
--- a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/GeometryParser.h
+++ b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/GeometryParser.h
@@ -8,12 +8,9 @@
 
 #include <string>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 class AxisInformation;
 
@@ -27,7 +24,8 @@ class AxisInformation;
   @author Michael Reuter
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -55,7 +53,7 @@ public:
    */
   GeometryParser(const char *xml);
   /// Default destructor.
-  virtual ~GeometryParser() {};
+  virtual ~GeometryParser(){};
 
   /// Insert a value into the time dimension XML.
   std::string addTDimValue(double time);
@@ -76,7 +74,6 @@ private:
 
   Poco::AutoPtr<Poco::XML::Document> pDoc; ///< A XML document handle
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/ModeControlWidget.h b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/ModeControlWidget.h
index a5222b872379ea6734d607b5ca50ec6bfbb23975..fe0e013cff60037c02f362feeacecd37a402229f 100644
--- a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/ModeControlWidget.h
+++ b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/ModeControlWidget.h
@@ -8,12 +8,9 @@
 #include <QWidget>
 #include <QString>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 /**
  *
   This class controls the current view for the main level program.
@@ -21,7 +18,8 @@ namespace SimpleGui
   @author Michael Reuter
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -41,8 +39,8 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS ModeControlWidget : public QWidget
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS ModeControlWidget
+    : public QWidget {
   Q_OBJECT
 
 public:
@@ -55,7 +53,7 @@ public:
   ~ModeControlWidget() override;
 
   /// Enumeration for the view types
-  enum Views {STANDARD, THREESLICE, MULTISLICE, SPLATTERPLOT};
+  enum Views { STANDARD, THREESLICE, MULTISLICE, SPLATTERPLOT };
 
 public slots:
   /// Enable/disable a specific view button.
@@ -108,9 +106,9 @@ protected slots:
 
 private:
   Ui::ModeControlWidgetClass ui; ///< The mode control widget's UI form
-  std::map<QString, Views> mapFromStringToView; //< Holds the mapping from the a string to an associated enum
+  std::map<QString, Views> mapFromStringToView; //< Holds the mapping from the a
+  // string to an associated enum
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/RotationPointDialog.h b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/RotationPointDialog.h
index ad447f7736c119757615fc1c4147274b5e1c12f9..325caf4340f15b10fbe388802d342405196e2c52 100644
--- a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/RotationPointDialog.h
+++ b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/RotationPointDialog.h
@@ -6,19 +6,17 @@
 
 #include <QDialog>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 /**
  *
   This class handles providing the coordinates for a center of rotation.
 
   @date 14/11/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -38,9 +36,9 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS RotationPointDialog : public QDialog
-{
-    Q_OBJECT
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS RotationPointDialog
+    : public QDialog {
+  Q_OBJECT
 
 public:
   /// Default constructor.
@@ -64,7 +62,6 @@ protected slots:
 private:
   Ui::RotationPointDialog ui; ///< The dialog's UI form
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/WidgetDllOption.h b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/WidgetDllOption.h
index 00a2c7a70df06663a52c38f8f6d2fd0908d4f730..2db5088440da310f5fd5c5a3e5c5b2fa914e4dc9 100644
--- a/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/WidgetDllOption.h
+++ b/Vates/VatesSimpleGui/QtWidgets/inc/MantidVatesSimpleGuiQtWidgets/WidgetDllOption.h
@@ -7,6 +7,6 @@
 #define EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS DLLExport
 #else
 #define EXPORT_OPT_MANTIDVATES_SIMPLEGUI_QTWIDGETS DLLImport
-#endif //IN_MANTID_VATES_SIMPLEGUI_QTWIDGETS
+#endif // IN_MANTID_VATES_SIMPLEGUI_QTWIDGETS
 
 #endif // MANTIDVATES_SIMPLEGUI_QTWIDGETS_DLLOPTION_H_
diff --git a/Vates/VatesSimpleGui/QtWidgets/src/AxisInformation.cpp b/Vates/VatesSimpleGui/QtWidgets/src/AxisInformation.cpp
index 0d92bd89b4d15dc6ec5daca056068d9391aa5925..9799369f95c83577830c8c5442291ad956514784 100644
--- a/Vates/VatesSimpleGui/QtWidgets/src/AxisInformation.cpp
+++ b/Vates/VatesSimpleGui/QtWidgets/src/AxisInformation.cpp
@@ -1,19 +1,14 @@
 #include "MantidVatesSimpleGuiQtWidgets/AxisInformation.h"
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-AxisInformation::AxisInformation()
-{
+AxisInformation::AxisInformation() {
   this->title = std::string("");
   this->minimum = -9999999.0;
   this->maximum = -9999999.0;
 }
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/QtWidgets/src/GeometryParser.cpp b/Vates/VatesSimpleGui/QtWidgets/src/GeometryParser.cpp
index 28f88d9e6f24210e44346d13a18b719cf9c25a0c..72b57b2ed795a7d41d021bd5af247bcf42d64378 100644
--- a/Vates/VatesSimpleGui/QtWidgets/src/GeometryParser.cpp
+++ b/Vates/VatesSimpleGui/QtWidgets/src/GeometryParser.cpp
@@ -14,35 +14,29 @@
 #include <Poco/DOM/NodeList.h>
 #include <Poco/DOM/Text.h>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-GeometryParser::GeometryParser(const char *xml)
-{
+GeometryParser::GeometryParser(const char *xml) {
   Poco::XML::DOMParser parser;
   this->pDoc = parser.parseString(Poco::XML::XMLString(xml));
 }
 
-AxisInformation *GeometryParser::getAxisInfo(const std::string dimension)
-{
+AxisInformation *GeometryParser::getAxisInfo(const std::string dimension) {
   AxisInformation *axis = new AxisInformation();
 
-  Poco::AutoPtr<Poco::XML::NodeList> pNodes = this->pDoc->getElementsByTagName(dimension);
+  Poco::AutoPtr<Poco::XML::NodeList> pNodes =
+      this->pDoc->getElementsByTagName(dimension);
   Poco::XML::Node *pNode = pNodes->item(0)->childNodes()->item(0);
   Poco::XML::XMLString label = pNode->innerText();
 
   pNodes = this->pDoc->getElementsByTagName("Dimension");
-  for (unsigned long int i = 0; i < pNodes->length(); ++i)
-  {
+  for (unsigned long int i = 0; i < pNodes->length(); ++i) {
     pNode = pNodes->item(i);
     Poco::AutoPtr<Poco::XML::NamedNodeMap> aMap = pNode->attributes();
     Poco::XML::XMLString id = aMap->getNamedItem("ID")->getNodeValue();
-    if (id == label)
-    {
+    if (id == label) {
       break;
     }
   }
@@ -53,8 +47,7 @@ AxisInformation *GeometryParser::getAxisInfo(const std::string dimension)
   std::string title;
   // Using ID for now. Remove if we go back to using axis name
   title = label;
-  for (unsigned long int j = 0; j < cNodes->length(); ++j)
-  {
+  for (unsigned long int j = 0; j < cNodes->length(); ++j) {
     Poco::XML::Node *cNode = cNodes->item(j);
     Poco::XML::XMLString elem = cNode->nodeName();
     // Keeping below around in case we go back to using axis name
@@ -64,12 +57,10 @@ AxisInformation *GeometryParser::getAxisInfo(const std::string dimension)
         title = cNode->innerText();
         }
       */
-    if (elem == Poco::XML::XMLString("LowerBounds"))
-    {
+    if (elem == Poco::XML::XMLString("LowerBounds")) {
       min = this->convertBounds(cNode->innerText());
     }
-    if (elem == Poco::XML::XMLString("UpperBounds"))
-    {
+    if (elem == Poco::XML::XMLString("UpperBounds")) {
       max = this->convertBounds(cNode->innerText());
     }
   }
@@ -81,8 +72,7 @@ AxisInformation *GeometryParser::getAxisInfo(const std::string dimension)
   return axis;
 }
 
-double GeometryParser::convertBounds(Poco::XML::XMLString val)
-{
+double GeometryParser::convertBounds(Poco::XML::XMLString val) {
   double temp;
   std::stringstream number(val);
   number >> temp;
@@ -95,15 +85,18 @@ double GeometryParser::convertBounds(Poco::XML::XMLString val)
  * @param time the value of the timestep
  * @return the XML geometry with the timestep value added
  */
-std::string GeometryParser::addTDimValue(double time)
-{
-  std::string tDimLabel = Mantid::Geometry::MDGeometryXMLDefinitions::workspaceTDimensionElementName();
-  Poco::AutoPtr<Poco::XML::NodeList> pNodes = this->pDoc->getElementsByTagName(tDimLabel);
+std::string GeometryParser::addTDimValue(double time) {
+  std::string tDimLabel = Mantid::Geometry::MDGeometryXMLDefinitions::
+      workspaceTDimensionElementName();
+  Poco::AutoPtr<Poco::XML::NodeList> pNodes =
+      this->pDoc->getElementsByTagName(tDimLabel);
   Poco::XML::Node *pNode = pNodes->item(0);
   std::ostringstream timeStr;
   timeStr << time;
-  Poco::AutoPtr<Poco::XML::Element> valueElement = this->pDoc->createElement("Value");
-  Poco::AutoPtr<Poco::XML::Text> valueText = this->pDoc->createTextNode(timeStr.str());
+  Poco::AutoPtr<Poco::XML::Element> valueElement =
+      this->pDoc->createElement("Value");
+  Poco::AutoPtr<Poco::XML::Text> valueText =
+      this->pDoc->createTextNode(timeStr.str());
   valueElement->appendChild(valueText);
   pNode->appendChild(valueElement);
 
diff --git a/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp b/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
index d1020877720aedde0a1865644d750bddccab61e3..4b11798beab1e57b1b059571f54f4c3d109f13ba 100644
--- a/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
+++ b/Vates/VatesSimpleGui/QtWidgets/src/ModeControlWidget.cpp
@@ -5,30 +5,25 @@
 #include <map>
 #include <algorithm>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-namespace
-{
-    /// Static logger
-    Kernel::Logger g_log("MdControlWidget");
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+namespace {
+/// Static logger
+Kernel::Logger g_log("MdControlWidget");
 }
 
-ModeControlWidget::ModeControlWidget(QWidget *parent) : QWidget(parent)
-{
+ModeControlWidget::ModeControlWidget(QWidget *parent) : QWidget(parent) {
   this->ui.setupUi(this);
 
-  QObject::connect(this->ui.multiSliceButton, SIGNAL(clicked()),
-                   this, SLOT(onMultiSliceViewButtonClicked()));
-  QObject::connect(this->ui.standardButton, SIGNAL(clicked()),
-                   this, SLOT(onStandardViewButtonClicked()));
-  QObject::connect(this->ui.threeSliceButton, SIGNAL(clicked()),
-                   this, SLOT(onThreeSliceViewButtonClicked()));
-  QObject::connect(this->ui.splatterPlotButton, SIGNAL(clicked()),
-                   this, SLOT(onSplatterPlotViewButtonClicked()));
+  QObject::connect(this->ui.multiSliceButton, SIGNAL(clicked()), this,
+                   SLOT(onMultiSliceViewButtonClicked()));
+  QObject::connect(this->ui.standardButton, SIGNAL(clicked()), this,
+                   SLOT(onStandardViewButtonClicked()));
+  QObject::connect(this->ui.threeSliceButton, SIGNAL(clicked()), this,
+                   SLOT(onThreeSliceViewButtonClicked()));
+  QObject::connect(this->ui.splatterPlotButton, SIGNAL(clicked()), this,
+                   SLOT(onSplatterPlotViewButtonClicked()));
 
   // Add the mapping from string to the view enum
   MantidQt::API::MdConstants mdConstants;
@@ -42,54 +37,42 @@ ModeControlWidget::ModeControlWidget(QWidget *parent) : QWidget(parent)
                               ModeControlWidget::SPLATTERPLOT);
 }
 
-ModeControlWidget::~ModeControlWidget()
-{
-  
-}
+ModeControlWidget::~ModeControlWidget() {}
 
-void ModeControlWidget::enableViewButtons(ModeControlWidget::Views initialView, bool state)
-{
+void ModeControlWidget::enableViewButtons(ModeControlWidget::Views initialView,
+                                          bool state) {
   // Set all buttons to the specified state
   this->ui.standardButton->setEnabled(state);
   this->ui.multiSliceButton->setEnabled(state);
   this->ui.splatterPlotButton->setEnabled(state);
   this->ui.threeSliceButton->setEnabled(state);
 
-  // Disable the defaultView (this is already disabled in the case of state == false)
-  switch(initialView)
-  {
-    case ModeControlWidget::STANDARD:
-    {
-      this->ui.standardButton->setEnabled(false);
-    }
-    break;
+  // Disable the defaultView (this is already disabled in the case of state ==
+  // false)
+  switch (initialView) {
+  case ModeControlWidget::STANDARD: {
+    this->ui.standardButton->setEnabled(false);
+  } break;
 
-    case ModeControlWidget::THREESLICE:
-    {
-      this->ui.threeSliceButton->setEnabled(false);
-    }
-    break;
+  case ModeControlWidget::THREESLICE: {
+    this->ui.threeSliceButton->setEnabled(false);
+  } break;
 
-    case ModeControlWidget::MULTISLICE:
-    {
-      this->ui.multiSliceButton->setEnabled(false);
-    }
-    break;
+  case ModeControlWidget::MULTISLICE: {
+    this->ui.multiSliceButton->setEnabled(false);
+  } break;
 
-    case ModeControlWidget::SPLATTERPLOT:
-    {
-      this->ui.splatterPlotButton->setEnabled(false);
-    }
-    break;
+  case ModeControlWidget::SPLATTERPLOT: {
+    this->ui.splatterPlotButton->setEnabled(false);
+  } break;
 
-    default:
-      g_log.warning("Attempted to disable an unknown default view. \n");
-      break;
+  default:
+    g_log.warning("Attempted to disable an unknown default view. \n");
+    break;
   }
 }
 
-void ModeControlWidget::onMultiSliceViewButtonClicked()
-{
+void ModeControlWidget::onMultiSliceViewButtonClicked() {
   this->ui.multiSliceButton->setEnabled(false);
   this->ui.standardButton->setEnabled(true);
   this->ui.splatterPlotButton->setEnabled(true);
@@ -97,8 +80,7 @@ void ModeControlWidget::onMultiSliceViewButtonClicked()
   emit executeSwitchViews(ModeControlWidget::MULTISLICE);
 }
 
-void ModeControlWidget::onStandardViewButtonClicked()
-{
+void ModeControlWidget::onStandardViewButtonClicked() {
   this->ui.standardButton->setEnabled(false);
   this->ui.multiSliceButton->setEnabled(true);
   this->ui.splatterPlotButton->setEnabled(true);
@@ -106,8 +88,7 @@ void ModeControlWidget::onStandardViewButtonClicked()
   emit executeSwitchViews(ModeControlWidget::STANDARD);
 }
 
-void ModeControlWidget::onThreeSliceViewButtonClicked()
-{
+void ModeControlWidget::onThreeSliceViewButtonClicked() {
   this->ui.threeSliceButton->setEnabled(false);
   this->ui.multiSliceButton->setEnabled(true);
   this->ui.splatterPlotButton->setEnabled(true);
@@ -115,13 +96,11 @@ void ModeControlWidget::onThreeSliceViewButtonClicked()
   emit executeSwitchViews(ModeControlWidget::THREESLICE);
 }
 
-void ModeControlWidget::setToStandardView()
-{
+void ModeControlWidget::setToStandardView() {
   this->onStandardViewButtonClicked();
 }
 
-void ModeControlWidget::onSplatterPlotViewButtonClicked()
-{
+void ModeControlWidget::onSplatterPlotViewButtonClicked() {
   this->ui.splatterPlotButton->setEnabled(false);
   this->ui.standardButton->setEnabled(true);
   this->ui.multiSliceButton->setEnabled(true);
@@ -133,36 +112,26 @@ void ModeControlWidget::onSplatterPlotViewButtonClicked()
  * Set the current view to a new, selected view
  *
  */
-void ModeControlWidget::setToSelectedView(ModeControlWidget::Views view)
-{
-  switch(view)
-  {
-    case ModeControlWidget::STANDARD:
-    {
-      this->onStandardViewButtonClicked();
-    }
-    break;
+void ModeControlWidget::setToSelectedView(ModeControlWidget::Views view) {
+  switch (view) {
+  case ModeControlWidget::STANDARD: {
+    this->onStandardViewButtonClicked();
+  } break;
 
-    case ModeControlWidget::MULTISLICE:
-    {
-      this->onMultiSliceViewButtonClicked();
-    }
-    break;
+  case ModeControlWidget::MULTISLICE: {
+    this->onMultiSliceViewButtonClicked();
+  } break;
 
-    case ModeControlWidget::THREESLICE:
-    {
-      this->onThreeSliceViewButtonClicked();
-    }
-    break;
+  case ModeControlWidget::THREESLICE: {
+    this->onThreeSliceViewButtonClicked();
+  } break;
 
-    case ModeControlWidget::SPLATTERPLOT:
-    {
-      this->onSplatterPlotViewButtonClicked();
-    }
-    break;
+  case ModeControlWidget::SPLATTERPLOT: {
+    this->onSplatterPlotViewButtonClicked();
+  } break;
 
-    default:
-      break;
+  default:
+    break;
   }
 }
 
@@ -172,10 +141,8 @@ void ModeControlWidget::setToSelectedView(ModeControlWidget::Views view)
  * @param state Enable/diable the view mode button
  */
 void ModeControlWidget::enableViewButton(ModeControlWidget::Views mode,
-                                         bool state)
-{
-  switch (mode)
-  {
+                                         bool state) {
+  switch (mode) {
   case ModeControlWidget::STANDARD:
     this->ui.standardButton->setEnabled(state);
     break;
@@ -194,18 +161,14 @@ void ModeControlWidget::enableViewButton(ModeControlWidget::Views mode,
 }
 
 /**
- * A string is checked against the enum for the views. 
+ * A string is checked against the enum for the views.
  * @param view A selected view.
  * @returns The selected view as enum or the standard view.
  */
-ModeControlWidget::Views ModeControlWidget::getViewFromString(QString view)
-{
-  if (!view.isEmpty() && mapFromStringToView.count(view) == 1)
-  {
+ModeControlWidget::Views ModeControlWidget::getViewFromString(QString view) {
+  if (!view.isEmpty() && mapFromStringToView.count(view) == 1) {
     return mapFromStringToView[view];
-  }
-  else 
-  {
+  } else {
     // The view was not found, hence return the standard view
     g_log.warning("The specified default view could not be found! \n");
 
diff --git a/Vates/VatesSimpleGui/QtWidgets/src/RotationPointDialog.cpp b/Vates/VatesSimpleGui/QtWidgets/src/RotationPointDialog.cpp
index 4633f893b41e82f54d448e731c4e3665e356cd47..2eb29d09a779f4e4c35f754e8d90f52ca3bd5c71 100644
--- a/Vates/VatesSimpleGui/QtWidgets/src/RotationPointDialog.cpp
+++ b/Vates/VatesSimpleGui/QtWidgets/src/RotationPointDialog.cpp
@@ -2,48 +2,37 @@
 
 #include <QDoubleValidator>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  * The class constructor. This sets up the UI, adds validators to the
  * line editors and connects the signal/slot for transmitting the coordinates.
  */
-RotationPointDialog::RotationPointDialog(QWidget *parent) :
-  QDialog(parent)
-{
+RotationPointDialog::RotationPointDialog(QWidget *parent) : QDialog(parent) {
   this->ui.setupUi(this);
   this->ui.xLineEdit->setValidator(new QDoubleValidator(this));
   this->ui.yLineEdit->setValidator(new QDoubleValidator(this));
   this->ui.zLineEdit->setValidator(new QDoubleValidator(this));
 
   // Gather the coordinates
-  QObject::connect(this->ui.buttonBox,
-                   SIGNAL(accepted()),
-                   this,
+  QObject::connect(this->ui.buttonBox, SIGNAL(accepted()), this,
                    SLOT(getCoordinates()));
 }
 
-RotationPointDialog::~RotationPointDialog()
-{
-}
+RotationPointDialog::~RotationPointDialog() {}
 
 /**
  * This function retrieves the individual coordinates from the line editors
  * and transmits that information via a signal.
  */
-void RotationPointDialog::getCoordinates()
-{
+void RotationPointDialog::getCoordinates() {
   double x = this->ui.xLineEdit->text().toDouble();
   double y = this->ui.yLineEdit->text().toDouble();
   double z = this->ui.zLineEdit->text().toDouble();
   emit this->sendCoordinates(x, y, z);
 }
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/StandAloneExec/inc/SimpleGuiApp.h b/Vates/VatesSimpleGui/StandAloneExec/inc/SimpleGuiApp.h
index beca59b04d9973e91b7022b3ea6ce9600767d777..5d31ed330b6799942a521a342d8994bb2d046a0f 100644
--- a/Vates/VatesSimpleGui/StandAloneExec/inc/SimpleGuiApp.h
+++ b/Vates/VatesSimpleGui/StandAloneExec/inc/SimpleGuiApp.h
@@ -12,7 +12,8 @@ class pqPVApplicationCore;
  @author Michael Reuter
  @date 04/08/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -32,8 +33,7 @@ class pqPVApplicationCore;
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class SimpleGuiApp : public QApplication
-{
+class SimpleGuiApp : public QApplication {
   Q_OBJECT
 public:
   /**
@@ -52,7 +52,6 @@ public:
 
 private:
   pqPVApplicationCore *pvApp; ///< ParaView application engine
-
 };
 
 #endif // SIMPLEGUIAPP_H
diff --git a/Vates/VatesSimpleGui/StandAloneExec/inc/VsgMainWindow.h b/Vates/VatesSimpleGui/StandAloneExec/inc/VsgMainWindow.h
index b26cf1766520663c24b5b1ab0c7e7acd0e217d00..30bab5d7c073db4663e648705b21501ca57b220f 100644
--- a/Vates/VatesSimpleGui/StandAloneExec/inc/VsgMainWindow.h
+++ b/Vates/VatesSimpleGui/StandAloneExec/inc/VsgMainWindow.h
@@ -3,12 +3,9 @@
 
 #include <QMainWindow>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 class MdViewerWidget;
 }
 }
@@ -23,7 +20,8 @@ class QMenu;
   @author Michael Reuter
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -43,8 +41,7 @@ class QMenu;
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class VsgMainWindow : public QMainWindow
-{
+class VsgMainWindow : public QMainWindow {
   Q_OBJECT
 
 public:
@@ -64,7 +61,7 @@ private:
 
   QAction *openAction; ///< Action for opening files
   QAction *exitAction; ///< Action for exiting the program
-  QMenu *fileMenu; ///< File actions menu
+  QMenu *fileMenu;     ///< File actions menu
   Mantid::Vates::SimpleGui::MdViewerWidget *mdViewer; ///< The VATES viz widget
 };
 
diff --git a/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp b/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
index 93c1e5d511cfc6a3aa2588f3d69f8d390b8068c4..4b7a63d5c7fe30cfe6cd72114c3a9c0c258244fd 100644
--- a/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
+++ b/Vates/VatesSimpleGui/StandAloneExec/src/SimpleGuiApp.cpp
@@ -9,67 +9,57 @@
 #include <exception>
 #include <iostream>
 
-namespace
-{
-  // static logger
-  Mantid::Kernel::Logger g_log("VatesSimpleGui");
+namespace {
+// static logger
+Mantid::Kernel::Logger g_log("VatesSimpleGui");
 }
 
-SimpleGuiApp::SimpleGuiApp(int &argc, char **argv) : QApplication(argc, argv)
-{
+SimpleGuiApp::SimpleGuiApp(int &argc, char **argv) : QApplication(argc, argv) {
   this->pvApp = new pqPVApplicationCore(argc, argv);
 }
 
-bool SimpleGuiApp::notify(QObject *receiver, QEvent *event)
-{
+bool SimpleGuiApp::notify(QObject *receiver, QEvent *event) {
   bool res = false;
-  try
-  {
+  try {
     res = QApplication::notify(receiver, event);
-  }
-  catch (std::exception &e)
-  {
+  } catch (std::exception &e) {
     // Restore possible override cursor
-    while(QApplication::overrideCursor())
-    {
+    while (QApplication::overrideCursor()) {
       QApplication::restoreOverrideCursor();
     }
 
     g_log.fatal() << "Unexpected exception: " << e.what() << "\n";
     QMessageBox ask;
-    QAbstractButton *terminateButton = ask.addButton(tr("Terminate"),
-                                                     QMessageBox::ActionRole);
+    QAbstractButton *terminateButton =
+        ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
     ask.addButton(tr("Continue"), QMessageBox::ActionRole);
-    ask.setText("Sorry, VatesSimpleGui has caught an unexpected exception:\n\n"\
-                +QString::fromStdString(e.what())+
-                "\n\nWould you like to terminate VatesSimpleGui or try to "\
-                "continue working?\n\nIf you choose to continue it is advisable "\
-                "to save your data and restart the application.");
+    ask.setText(
+        "Sorry, VatesSimpleGui has caught an unexpected exception:\n\n" +
+        QString::fromStdString(e.what()) +
+        "\n\nWould you like to terminate VatesSimpleGui or try to "
+        "continue working?\n\nIf you choose to continue it is advisable "
+        "to save your data and restart the application.");
     ask.setIcon(QMessageBox::Critical);
     ask.exec();
-    if (ask.clickedButton() == terminateButton)
-    {
-        g_log.fatal("Terminated by user.");
-        quit();
+    if (ask.clickedButton() == terminateButton) {
+      g_log.fatal("Terminated by user.");
+      quit();
     }
-  }
-  catch (...)
-  {
+  } catch (...) {
     g_log.fatal() << "Unknown exception\n";
     QMessageBox ask;
-    QAbstractButton *terminateButton = ask.addButton(tr("Terminate"),
-                                                     QMessageBox::ActionRole);
+    QAbstractButton *terminateButton =
+        ask.addButton(tr("Terminate"), QMessageBox::ActionRole);
     ask.addButton(tr("Continue"), QMessageBox::ActionRole);
-    ask.setText("Sorry, VatesSimpleGui has caught an unexpected exception\n\n"\
-                "Would you like to terminate VatesSimpleGui or try to continue "\
-                "working?\n\nIf you choose to continue it is advisable to save "\
+    ask.setText("Sorry, VatesSimpleGui has caught an unexpected exception\n\n"
+                "Would you like to terminate VatesSimpleGui or try to continue "
+                "working?\n\nIf you choose to continue it is advisable to save "
                 "your data and restart the application.");
     ask.setIcon(QMessageBox::Critical);
     ask.exec();
-    if (ask.clickedButton() == terminateButton)
-    {
-       g_log.fatal("Terminated by user.");
-       quit();
+    if (ask.clickedButton() == terminateButton) {
+      g_log.fatal("Terminated by user.");
+      quit();
     }
   }
 
diff --git a/Vates/VatesSimpleGui/StandAloneExec/src/VsgMainWindow.cpp b/Vates/VatesSimpleGui/StandAloneExec/src/VsgMainWindow.cpp
index 11a715ddb0d19355dc74a7f4dd4eb6afc9486e93..0b8393897b05500a042623c3a80800d79d1e7af2 100644
--- a/Vates/VatesSimpleGui/StandAloneExec/src/VsgMainWindow.cpp
+++ b/Vates/VatesSimpleGui/StandAloneExec/src/VsgMainWindow.cpp
@@ -8,8 +8,7 @@
 
 using namespace Mantid::Vates::SimpleGui;
 
-VsgMainWindow::VsgMainWindow(QWidget *parent) : QMainWindow(parent)
-{
+VsgMainWindow::VsgMainWindow(QWidget *parent) : QMainWindow(parent) {
   this->mdViewer = new MdViewerWidget(this);
   this->setCentralWidget(this->mdViewer);
 
@@ -18,13 +17,9 @@ VsgMainWindow::VsgMainWindow(QWidget *parent) : QMainWindow(parent)
   this->mdViewer->addMenus();
 }
 
-VsgMainWindow::~VsgMainWindow()
-{
+VsgMainWindow::~VsgMainWindow() {}
 
-}
-
-void VsgMainWindow::createActions()
-{
+void VsgMainWindow::createActions() {
   // File loading
   this->openAction = new QAction(QApplication::tr("&Open"), this);
   this->openAction->setShortcut(QApplication::tr("Ctrl+O"));
@@ -38,8 +33,7 @@ void VsgMainWindow::createActions()
   QObject::connect(this->exitAction, SIGNAL(triggered()), this, SLOT(close()));
 }
 
-void VsgMainWindow::createMenus()
-{
+void VsgMainWindow::createMenus() {
   this->fileMenu = this->menuBar()->addMenu(QApplication::tr("&File"));
   this->fileMenu->addAction(this->openAction);
   this->fileMenu->addSeparator();
diff --git a/Vates/VatesSimpleGui/StandAloneExec/src/main.cpp b/Vates/VatesSimpleGui/StandAloneExec/src/main.cpp
index 3033077aabbdab27a824f0664bb4d43628852c6b..bbd81c060ad56b8f141a278405e9e1008fb28872 100644
--- a/Vates/VatesSimpleGui/StandAloneExec/src/main.cpp
+++ b/Vates/VatesSimpleGui/StandAloneExec/src/main.cpp
@@ -3,26 +3,21 @@
 
 #include <QMessageBox>
 
-int main(int argc, char** argv)
-{
+int main(int argc, char **argv) {
   SimpleGuiApp app(argc, argv);
-  try
-  {
+  try {
     VsgMainWindow window;
     window.show();
     return app.exec();
-  }
-  catch(std::exception& e)
-  {
+  } catch (std::exception &e) {
     QMessageBox::critical(0, "VatesSimpleGui - Error",
-                          QString("An unhandled exception has been caught. "\
-                                  "VatesSimpleGui will have to close. "\
-                                  "Details:\n\n")+e.what());
-  }
-  catch(...)
-  {
+                          QString("An unhandled exception has been caught. "
+                                  "VatesSimpleGui will have to close. "
+                                  "Details:\n\n") +
+                              e.what());
+  } catch (...) {
     QMessageBox::critical(0, "VatesSimpleGui - Error",
-                          "An unhandled exception has been caught. "\
+                          "An unhandled exception has been caught. "
                           "VatesSimpleGui will have to close.");
   }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/AutoScaleRangeGenerator.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/AutoScaleRangeGenerator.h
index 20c74d517435fed3ad21d2ef35be3028cf18e8de..8b18aae8e54ffca97e07c84f9cc9be6b33b4a494 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/AutoScaleRangeGenerator.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/AutoScaleRangeGenerator.h
@@ -2,12 +2,14 @@
 #define AUTOSCALERANGEGENERATOR_H
 
 /**
-    Generates information for the color scale, e.g. minimum level, maximum level, 
+    Generates information for the color scale, e.g. minimum level, maximum
+   level,
     log scale.
 
     @date 18/11/2014
 
-    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+    Copyright &copy; 2007-11 ISIS Rutherford Appleton Laboratory & NScD Oak
+   Ridge National Laboratory
 
     This file is part of Mantid.
 
@@ -36,15 +38,11 @@
 class pqPipelineSource;
 class pqDataRepresentation;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-typedef struct VsiColorScale
-{
+typedef struct VsiColorScale {
   double maxValue;
 
   double minValue;
@@ -52,62 +50,65 @@ typedef struct VsiColorScale
   bool useLogScale;
 } VsiColorScale;
 
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS  AutoScaleRangeGenerator
-{
-  public:
-    AutoScaleRangeGenerator();
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS AutoScaleRangeGenerator {
+public:
+  AutoScaleRangeGenerator();
 
-    virtual ~AutoScaleRangeGenerator() {};
+  virtual ~AutoScaleRangeGenerator(){};
 
-    /// Creates a color scale entity.
-    VsiColorScale getColorScale();
+  /// Creates a color scale entity.
+  VsiColorScale getColorScale();
 
-    /// Enum for different modes
-    typedef enum COLORSCALEMODE{STANDARD, TECHNIQUEDEPENDENT, OFFSET} COLORSCALEMODE;
+  /// Enum for different modes
+  typedef enum COLORSCALEMODE {
+    STANDARD,
+    TECHNIQUEDEPENDENT,
+    OFFSET
+  } COLORSCALEMODE;
 
-    /// Initialize the color scale
-    void initializeColorScale();
+  /// Initialize the color scale
+  void initializeColorScale();
 
-    /// Update log scale setting
-    void updateLogScaleSetting(bool logScale);
+  /// Update log scale setting
+  void updateLogScaleSetting(bool logScale);
 
-  private:
-    /// Selected color scale mode.
-    COLORSCALEMODE mode;
+private:
+  /// Selected color scale mode.
+  COLORSCALEMODE mode;
 
-    /// Default value for the color scale
-    double defaultValue;
+  /// Default value for the color scale
+  double defaultValue;
 
-    /// Get the color scale for the standard selection.
-    VsiColorScale getStandardColorScale();
+  /// Get the color scale for the standard selection.
+  VsiColorScale getStandardColorScale();
 
-    /// Get all ParaView sources from the active server.
-    QList<pqPipelineSource *> getAllPVSources();
+  /// Get all ParaView sources from the active server.
+  QList<pqPipelineSource *> getAllPVSources();
 
-    /// Make sure that the color scale is valid.
-    void sanityCheck(VsiColorScale& colorscale);
+  /// Make sure that the color scale is valid.
+  void sanityCheck(VsiColorScale &colorscale);
 
-    /// Gets the log scale setting for the mode
-    bool getLogScale();
+  /// Gets the log scale setting for the mode
+  bool getLogScale();
 
   /**
-   * Extract the min and max values of a source. If we are dealing with a filter which does not
+   * Extract the min and max values of a source. If we are dealing with a filter
+   * which does not
    * have the information then look upstream for the information
    * @param source A pointer to a source
    * @param minValue A reference to a min value.
    * @param maxValue A reference to a max value.
    */
-    void setMinBufferAndMaxBuffer(pqPipelineSource* source, double& minValue, double& maxValue);
+  void setMinBufferAndMaxBuffer(pqPipelineSource *source, double &minValue,
+                                double &maxValue);
 
-    /// Md constants
-    MantidQt::API::MdConstants m_mdConstants;
+  /// Md constants
+  MantidQt::API::MdConstants m_mdConstants;
 
-    /// Md Settings
-    MantidQt::API::MdSettings m_mdSettings;
+  /// Md Settings
+  MantidQt::API::MdSettings m_mdSettings;
 };
-
 }
 }
 }
 #endif
-
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
index 228e3283a23f1ef443a8c24f9e1dbe17519cd890..5258fe8e00568a67b15ef6d69cce0d83b79b262b 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/BackgroundRgbProvider.h
@@ -8,106 +8,109 @@
 #include <string>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqRenderView.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 class vtkObject;
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      /**
-       *
-        This class gets the default color values for the background of the view.
-
-        @date 10/12/2014
-
-        Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
-
-        This file is part of Mantid.
-
-        Mantid is free software; you can redistribute it and/or modify
-        it under the terms of the GNU General Public License as published by
-        the Free Software Foundation; either version 3 of the License, or
-        (at your option) any later version.
-
-        Mantid is distributed in the hope that it will be useful,
-        but WITHOUT ANY WARRANTY; without even the implied warranty of
-        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-        GNU General Public License for more details.
-
-        You should have received a copy of the GNU General Public License
-        along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-        File change history is stored at: <https://github.com/mantidproject/mantid>
-        Code Documentation is available at: <http://doxygen.mantidproject.org>
-      */
-
-      class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS BackgroundRgbProvider
-      {
-        public:
-          BackgroundRgbProvider();
-          
-          ~BackgroundRgbProvider();
-
-          /**
-           * Set the Rgb values for the color of the view's background.
-           * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
-           * @param view The view which has its background color set.
-           */
-          void setBackgroundColor(pqRenderView* view, bool useCurrentBackgroundColor);
-
-          /**
-           * Listen to a change in the background color
-           *@param view The view which we want to listen to.
-           */
-          void observe(pqRenderView* view);
-
-          /**
-           * Update the last session background color.
-           */
-          void update();
-
-       private:
-          /**
-          * Get the Rgb values for the color of the view's background from the user setting.
-          * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
-          * @returns A vector with the RGB values
-          */
-          std::vector<double> getRgbFromSetting(bool useCurrentBackgroundColor);
-
-          /**
-           * Get the Rgb values for the color of the view's background
-           * @param useCurrentBackgroundColor Is this the initial loading or were the views switched?
-           * @returns A vector with the RGB values
-           */
-          std::vector<double> getRgb(bool useCurrentBackgroundColor);
-
-          /**
-           * Callback function for background color changing events
-           * @param caller Calling object.
-           *
-           * @param eventID vtkCommand event ID for callbacks, not used here
-           * @param clientData vtk client data, not used here
-           * @param callData vtk call data, not used here
-           */
-          static void backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int eventID,
-                                                            void *clientData, void *callData);
-
-          static QColor currentBackgroundColor;
-
-          MantidQt::API::MdSettings m_mdSettings;
-      };
-    }
-  }
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+/**
+ *
+  This class gets the default color values for the background of the view.
+
+  @date 10/12/2014
+
+  Copyright &copy; 2014 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge
+ National Laboratory
+
+  This file is part of Mantid.
+
+  Mantid is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 3 of the License, or
+  (at your option) any later version.
+
+  Mantid is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+  File change history is stored at: <https://github.com/mantidproject/mantid>
+  Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS BackgroundRgbProvider {
+public:
+  BackgroundRgbProvider();
+
+  ~BackgroundRgbProvider();
+
+  /**
+   * Set the Rgb values for the color of the view's background.
+   * @param useCurrentBackgroundColor Is this the initial loading or were the
+   * views switched?
+   * @param view The view which has its background color set.
+   */
+  void setBackgroundColor(pqRenderView *view, bool useCurrentBackgroundColor);
+
+  /**
+   * Listen to a change in the background color
+   *@param view The view which we want to listen to.
+   */
+  void observe(pqRenderView *view);
+
+  /**
+   * Update the last session background color.
+   */
+  void update();
+
+private:
+  /**
+  * Get the Rgb values for the color of the view's background from the user
+  * setting.
+  * @param useCurrentBackgroundColor Is this the initial loading or were the
+  * views switched?
+  * @returns A vector with the RGB values
+  */
+  std::vector<double> getRgbFromSetting(bool useCurrentBackgroundColor);
+
+  /**
+   * Get the Rgb values for the color of the view's background
+   * @param useCurrentBackgroundColor Is this the initial loading or were the
+   * views switched?
+   * @returns A vector with the RGB values
+   */
+  std::vector<double> getRgb(bool useCurrentBackgroundColor);
+
+  /**
+   * Callback function for background color changing events
+   * @param caller Calling object.
+   *
+   * @param eventID vtkCommand event ID for callbacks, not used here
+   * @param clientData vtk client data, not used here
+   * @param callData vtk call data, not used here
+   */
+  static void backgroundColorChangeCallbackFunction(vtkObject *caller,
+                                                    long unsigned int eventID,
+                                                    void *clientData,
+                                                    void *callData);
+
+  static QColor currentBackgroundColor;
+
+  MantidQt::API::MdSettings m_mdSettings;
+};
 }
-#endif 
+}
+}
+#endif
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
index 8b2aa618458c0691ca56bb15cf6eff3096751108..3297b37e773052708f548a001cdd061ebad9018d 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/CameraManager.h
@@ -4,14 +4,9 @@
 #include "MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h"
 #include "MantidVatesAPI/ViewFrustum.h"
 
-
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  *
@@ -19,7 +14,8 @@ namespace SimpleGui
 
   @date 14/1/2015
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -39,20 +35,19 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS CameraManager
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS CameraManager {
 public:
   CameraManager();
 
   ~CameraManager();
-  
+
   Mantid::VATES::ViewFrustum_const_sptr getCurrentViewFrustum();
 
-  void setCameraToPeak(double xpos, double ypos, double zpos, double peakRadius);
+  void setCameraToPeak(double xpos, double ypos, double zpos,
+                       double peakRadius);
 };
-
 }
 }
 }
 
-#endif 
+#endif
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorSelectionWidget.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorSelectionWidget.h
index 3ee0689e7f60adaa385edf535dcedf1967f21573..e2b748a67e07d8a173a8a5598cf66122e2ca0f47 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorSelectionWidget.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorSelectionWidget.h
@@ -15,12 +15,9 @@ namespace Json {
 class Value;
 }
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 /**
  *
   This class controls the color scale for the main level program viewed
@@ -28,7 +25,8 @@ namespace SimpleGui
 
   @date 07/06/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -48,8 +46,8 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ColorSelectionWidget : public QWidget
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ColorSelectionWidget
+    : public QWidget {
   Q_OBJECT
 
 public:
@@ -71,14 +69,17 @@ public:
   /// Programmatically enable/disable auto scaling of color range
   void setAutoScale(bool autoScale);
   /// Set min smaller max, can be used to programmatically set the widgets
-  void setMinMax(double& min, double& max);
-  /// Others need to know if this widget is in the process of updating colors at user's request
-  bool inProcessUserRequestedAutoScale() { return m_inProcessUserRequestedAutoScale; };
+  void setMinMax(double &min, double &max);
+  /// Others need to know if this widget is in the process of updating colors at
+  /// user's request
+  bool inProcessUserRequestedAutoScale() {
+    return m_inProcessUserRequestedAutoScale;
+  };
   /// To effectively block callbacks from external (Paraview) color changes
   void ignoreColorChangeCallbacks(bool ignore);
   bool isIgnoringColorCallbacks();
   /// Set the color scale lock
-  void setColorScaleLock(Mantid::VATES::ColorScaleLock* lock);
+  void setColorScaleLock(Mantid::VATES::ColorScaleLock *lock);
   /// Is the color scale locked
   bool isColorScaleLocked() const;
 
@@ -98,7 +99,7 @@ signals:
   /**
    * Signal to let views know that autoscaling is on.
    */
-  void autoScale(ColorSelectionWidget*);
+  void autoScale(ColorSelectionWidget *);
   /**
    * Signal to pass on information about a change to the color map.
    * @param model the color map to send
@@ -137,10 +138,10 @@ private:
   /// Set up the behaviour for with or without log scale.
   void setupLogScale(int state);
   /// Set min smaller max, can be used to programmatically set the widgets
-  void setMinSmallerMax(double& min, double& max);
+  void setMinSmallerMax(double &min, double &max);
 
-  QDoubleValidator* m_minValidator;
-  QDoubleValidator* m_maxValidator;
+  QDoubleValidator *m_minValidator;
+  QDoubleValidator *m_maxValidator;
   double m_minHistoric;
   double m_maxHistoric;
 
@@ -148,12 +149,13 @@ private:
   MantidQt::API::MdSettings m_mdSettings;
 
   Ui::ColorSelectionWidgetClass m_ui; ///< The mode control widget's UI form
-  bool m_ignoreColorChangeCallbacks; ///< Effectively blocks/disables callbacks
+  bool m_ignoreColorChangeCallbacks;  ///< Effectively blocks/disables callbacks
 
-  /// this is a flag that is set while updating the color scale triggered by the user clicking on the auto-scale box
+  /// this is a flag that is set while updating the color scale triggered by the
+  /// user clicking on the auto-scale box
   bool m_inProcessUserRequestedAutoScale;
 
-  Mantid::VATES::ColorScaleLock* m_colorScaleLock;
+  Mantid::VATES::ColorScaleLock *m_colorScaleLock;
 };
 
 } // SimpleGui
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorUpdater.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorUpdater.h
index c5411795758c72b9d23c7877702f7498164ce4af..4c756cbde16809933cb1e0ad54d8f699fc66d2a5 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorUpdater.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ColorUpdater.h
@@ -15,12 +15,9 @@ namespace Json {
 class Value;
 }
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 class ColorSelectionWidget;
 
@@ -31,7 +28,8 @@ class ColorSelectionWidget;
   @author Michael Reuter
   @date 15/08/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -51,8 +49,7 @@ class ColorSelectionWidget;
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ColorUpdater
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ColorUpdater {
 public:
   /// Object constructor
   ColorUpdater();
@@ -96,26 +93,33 @@ public:
   /// Update the internal state.
   void updateState(ColorSelectionWidget *cs);
 
-  /// To update the VSI min/mas lineEdits when the user uses the Paraview color editor
-  void observeColorScaleEdited(pqPipelineRepresentation *repr, ColorSelectionWidget *cs);
+  /// To update the VSI min/mas lineEdits when the user uses the Paraview color
+  /// editor
+  void observeColorScaleEdited(pqPipelineRepresentation *repr,
+                               ColorSelectionWidget *cs);
 
 private:
-  /// vtkcallback function for color change events coming from the Paraview color editor
-  static void colorScaleEditedCallbackFunc(vtkObject* caller, long unsigned int eventID,
-                                           void *clientData, void *callData);
-  /// vtk callback function for user clicks on log-scale in the Paraview color editor
-  static void logScaleClickedCallbackFunc(vtkObject* caller, long unsigned int eventID,
+  /// vtkcallback function for color change events coming from the Paraview
+  /// color editor
+  static void colorScaleEditedCallbackFunc(vtkObject *caller,
+                                           long unsigned int eventID,
                                            void *clientData, void *callData);
+  /// vtk callback function for user clicks on log-scale in the Paraview color
+  /// editor
+  static void logScaleClickedCallbackFunc(vtkObject *caller,
+                                          long unsigned int eventID,
+                                          void *clientData, void *callData);
 
-  void updateLookupTable(pqDataRepresentation* representation); ///< Updates the lookup tables.
+  void updateLookupTable(
+      pqDataRepresentation *representation); ///< Updates the lookup tables.
 
   bool m_autoScaleState; ///< Holder for the auto scaling state
-  bool m_logScaleState; ///< Holder for the log scaling state
-  double m_minScale; ///< Holder for the minimum color range state
-  double m_maxScale; ///< Holder for the maximum color range state
-  AutoScaleRangeGenerator m_autoScaleRangeGenerator; ///< Holds a range generator for auto scale.
+  bool m_logScaleState;  ///< Holder for the log scaling state
+  double m_minScale;     ///< Holder for the minimum color range state
+  double m_maxScale;     ///< Holder for the maximum color range state
+  AutoScaleRangeGenerator
+      m_autoScaleRangeGenerator; ///< Holds a range generator for auto scale.
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
index d3852dbc855c41bda2d9f5ed4368caa251265447..d535fc0349d7aea2498abf03c6ce1d2f7857b5a1 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MdViewerWidget.h
@@ -153,24 +153,24 @@ private:
   SaveScreenshotReaction *screenShot;  ///< Holder for the screen shot reaction
   Ui::MdViewerWidgetClass ui;          ///< The MD viewer's UI form
   QHBoxLayout *viewLayout;             ///< Layout manager for the view widget
-  pqApplicationSettingsReaction
-      *viewSettings; ///< Holder for the view settings reaction
+  pqApplicationSettingsReaction *
+      viewSettings; ///< Holder for the view settings reaction
   bool useCurrentColorSettings;
   ModeControlWidget::Views initialView; ///< Holds the initial view
   MantidQt::API::MdSettings
       mdSettings; ///<Holds the MD settings which are used to persist data
   MantidQt::API::MdConstants mdConstants; /// < Holds the MD constants
   RebinAlgorithmDialogProvider m_rebinAlgorithmDialogProvider; ///<Provides
-                                                               ///dialogs to
-                                                               ///execute rebin
-                                                               ///algorithms
+  /// dialogs to
+  /// execute rebin
+  /// algorithms
   RebinnedSourcesManager
       m_rebinnedSourcesManager;          ///<Holds the rebinned sources manager
   QString m_rebinnedWorkspaceIdentifier; ///< Holds the identifier for temporary
-                                         ///workspaces
-  ColorMapEditorPanel
-      *m_colorMapEditorPanel; ///< Holder for the color map editor panel.
-  bool m_gridAxesStartUpOn;   /// flag for the initial grid axes setting
+  /// workspaces
+  ColorMapEditorPanel *
+      m_colorMapEditorPanel; ///< Holder for the color map editor panel.
+  bool m_gridAxesStartUpOn;  /// flag for the initial grid axes setting
   Mantid::VATES::ColorScaleLock
       m_colorScaleLock; ///< Holds a color scale lock object
 
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
index c3da48b397a79118653e4764c4c879b67d3eba0a..d76a9e00bc7382b7f5a6b80ff25113f39d67ec1b 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/MultisliceView.h
@@ -11,14 +11,11 @@
 
 class pqMultiSliceView;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-
-  class RebinnedSourcesManager;
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+
+class RebinnedSourcesManager;
 /**
  *
   This class uses the MultiSliceView created by Kitware based on our
@@ -26,7 +23,8 @@ namespace SimpleGui
 
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -46,8 +44,8 @@ namespace SimpleGui
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS MultiSliceView : public ViewBase
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS MultiSliceView
+    : public ViewBase {
   Q_OBJECT
 
 public:
@@ -56,7 +54,8 @@ public:
    * @param parent the parent widget of the multislice view widget
    * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  MultiSliceView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+  MultiSliceView(QWidget *parent = 0,
+                 RebinnedSourcesManager *rebinnedSourcesManager = 0);
   /// Default constructor.
   ~MultiSliceView() override;
 
@@ -87,11 +86,11 @@ public:
 
 protected slots:
   /// Determine if slice is to be shown in SliceViewer.
-  void checkSliceClicked(int axisIndex, double sliceOffsetOnAxis,
-                         int button, int modifier);
+  void checkSliceClicked(int axisIndex, double sliceOffsetOnAxis, int button,
+                         int modifier);
   /// Launch SliceViewer with the specified cut.
   void showCutInSliceViewer(int axisIndex, double sliceOffsetOnAxis);
-  
+
   //// changes the slice point in VATES.
   void changedSlicePoint(Mantid::Kernel::VMD selectedPoint);
 
@@ -104,9 +103,8 @@ private:
   void setupData();
 
   QPointer<pqMultiSliceView> m_mainView; ///< The main view class
-  Ui::MultiSliceViewClass m_ui; ///< The view's UI form
+  Ui::MultiSliceViewClass m_ui;          ///< The view's UI form
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTabWidget.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTabWidget.h
index ffb5b455a2c93884dd54c0d4e58778f2589c3957..301dc32e5c2098f2fbfb2a760c8093f09b5c0ff5 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTabWidget.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/PeaksTabWidget.h
@@ -17,19 +17,13 @@ namespace Vates {
 namespace SimpleGui {
 
 // Need this class to access color of tabBar
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS PeakCustomTabWidget:public QTabWidget
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS PeakCustomTabWidget
+    : public QTabWidget {
 public:
-    PeakCustomTabWidget(QWidget* parent = 0)
-    {
-      setParent(parent);
-    }
-    
-    //Overridden method from QTabWidget
-    QTabBar* tabBar()
-    {
-      return QTabWidget::tabBar();
-    }
+  PeakCustomTabWidget(QWidget *parent = 0) { setParent(parent); }
+
+  // Overridden method from QTabWidget
+  QTabBar *tabBar() { return QTabWidget::tabBar(); }
 };
 
 class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS PeaksTabWidget
@@ -42,7 +36,8 @@ public:
   void setupMvc(std::map<std::string, std::vector<bool>> visiblePeaks);
   void addNewPeaksWorkspace(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
                             std::vector<bool> visiblePeaks);
-  void updateTabs(std::map<std::string, std::vector<bool>> visiblePeaks, std::map<std::string, QColor> colors);
+  void updateTabs(std::map<std::string, std::vector<bool>> visiblePeaks,
+                  std::map<std::string, QColor> colors);
 signals:
   void zoomToPeak(Mantid::API::IPeaksWorkspace_sptr ws, int row);
   void sortPeaks(const std::string &columnToSortBy, const bool sortAscending,
@@ -63,7 +58,7 @@ private:
   /// Coordinate system.
   const std::string m_coordinateSystem;
   /// Custom peaks tab widget
-  PeakCustomTabWidget* m_tabWidget;
+  PeakCustomTabWidget *m_tabWidget;
 };
 } // namespace
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
index 07117b45a03230acaafc5cb36411ae71bf7fcbd8..8255d596c1bf2484e4578803ca8b15016d9ec049 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinAlgorithmDialogProvider.h
@@ -9,68 +9,75 @@
 #include "MantidQtAPI/AlgorithmDialog.h"
 #include "MantidQtMantidWidgets/SlicingAlgorithmDialog.h"
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      /**
-       *
-       This class coordinates the rebinning of a workspace and updates the pipeline and view to make the changes of the 
-       underlying workspace visible.
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+/**
+ *
+ This class coordinates the rebinning of a workspace and updates the pipeline
+ and view to make the changes of the
+ underlying workspace visible.
 
-       @date 15/01/2015
+ @date 15/01/2015
 
-       Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-       This file is part of Mantid.
+ This file is part of Mantid.
 
-       Mantid is free software; you can redistribute it and/or modify
-       it under the terms of the GNU General Public License as published by
-       the Free Software Foundation; either version 3 of the License, or
-       (at your option) any later version.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-       Mantid is distributed in the hope that it will be useful,
-       but WITHOUT ANY WARRANTY; without even the implied warranty of
-       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-       GNU General Public License for more details.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-       You should have received a copy of the GNU General Public License
-       along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-       File change history is stored at: <https://github.com/mantidproject/mantid>
-       Code Documentation is available at: <http://doxygen.mantidproject.org>
-       */
-      class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS RebinAlgorithmDialogProvider
-      {
-        public:
-          RebinAlgorithmDialogProvider(QWidget* parent);
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS
+    RebinAlgorithmDialogProvider {
+public:
+  RebinAlgorithmDialogProvider(QWidget *parent);
 
-          ~RebinAlgorithmDialogProvider();
+  ~RebinAlgorithmDialogProvider();
 
-          void showDialog(std::string inputWorkspace, std::string outputWorkspace, std::string algorithmType);
+  void showDialog(std::string inputWorkspace, std::string outputWorkspace,
+                  std::string algorithmType);
 
-           static const size_t BinCutOffValue;
+  static const size_t BinCutOffValue;
 
-        private:
-          MantidQt::API::AlgorithmDialog* createDialog(Mantid::API::IAlgorithm_sptr algorithm, const std::string& inputWorkspace, const std::string& outputWorkspace, const std::string& algorithmType);
+private:
+  MantidQt::API::AlgorithmDialog *createDialog(
+      Mantid::API::IAlgorithm_sptr algorithm, const std::string &inputWorkspace,
+      const std::string &outputWorkspace, const std::string &algorithmType);
 
-          void setAxisDimensions(MantidQt::MantidWidgets::SlicingAlgorithmDialog* dialog,  std::string inputWorkspace);
+  void
+  setAxisDimensions(MantidQt::MantidWidgets::SlicingAlgorithmDialog *dialog,
+                    std::string inputWorkspace);
 
-          Mantid::API::IMDEventWorkspace_sptr getWorkspace(const std::string& workspaceName);
+  Mantid::API::IMDEventWorkspace_sptr
+  getWorkspace(const std::string &workspaceName);
 
-          Mantid::API::IAlgorithm_sptr createAlgorithm(const std::string& algName, int version);
+  Mantid::API::IAlgorithm_sptr createAlgorithm(const std::string &algName,
+                                               int version);
 
-          Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace> m_adsWorkspaceProvider;
+  Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>
+      m_adsWorkspaceProvider;
 
-          const QString m_lblInputWorkspace;
-          const QString m_lblOutputWorkspace;
-          QWidget* m_parent;
-      };
+  const QString m_lblInputWorkspace;
+  const QString m_lblOutputWorkspace;
+  QWidget *m_parent;
+};
 
-    } // SimpleGui
-  } // Vates
+} // SimpleGui
+} // Vates
 } // Mantid
 
-#endif 
+#endif
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
index 36d001473e57377c3616646d33632d470862ea78..3e752714bb61976eca16493f982ef02593864aa9 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h
@@ -7,7 +7,7 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqPipelineSource.h>
@@ -15,7 +15,7 @@
 #include <vtkSMProxy.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QWidget>
@@ -23,126 +23,149 @@
 #include <map>
 #include <string>
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      /**
-       *
-       This class  keeps track of the MDEvent workspaces and associated rebinned workspaces. Rebinning requires temporary workspaces instead of
-       the original MDEvent workspaces. This class switches between these types of sources.
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+/**
+ *
+ This class  keeps track of the MDEvent workspaces and associated rebinned
+ workspaces. Rebinning requires temporary workspaces instead of
+ the original MDEvent workspaces. This class switches between these types of
+ sources.
 
-       @date 21/01/2015
+ @date 21/01/2015
 
-       Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
-       This file is part of Mantid.
+ This file is part of Mantid.
 
-       Mantid is free software; you can redistribute it and/or modify
-       it under the terms of the GNU General Public License as published by
-       the Free Software Foundation; either version 3 of the License, or
-       (at your option) any later version.
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
 
-       Mantid is distributed in the hope that it will be useful,
-       but WITHOUT ANY WARRANTY; without even the implied warranty of
-       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-       GNU General Public License for more details.
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
 
-       You should have received a copy of the GNU General Public License
-       along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-       File change history is stored at: <https://github.com/mantidproject/mantid>
-       Code Documentation is available at: <http://doxygen.mantidproject.org>
-       */
-      class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS RebinnedSourcesManager :public QWidget, MantidQt::API::WorkspaceObserver
-      {
-        Q_OBJECT
-        public:
-          RebinnedSourcesManager(QWidget* parent = 0);
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS RebinnedSourcesManager
+    : public QWidget,
+      MantidQt::API::WorkspaceObserver {
+  Q_OBJECT
+public:
+  RebinnedSourcesManager(QWidget *parent = 0);
 
-          ~RebinnedSourcesManager() override;
+  ~RebinnedSourcesManager() override;
 
-          void checkSource(pqPipelineSource* source, std::string& inputWorkspace, std::string& outputWorkspace,  std::string algorithmType);
+  void checkSource(pqPipelineSource *source, std::string &inputWorkspace,
+                   std::string &outputWorkspace, std::string algorithmType);
 
-          void repipeRebinnedSource();
+  void repipeRebinnedSource();
 
-          void repipeOriginalSource(pqPipelineSource* rebinnedSource, pqPipelineSource* originalSource);
+  void repipeOriginalSource(pqPipelineSource *rebinnedSource,
+                            pqPipelineSource *originalSource);
 
-          void getStoredWorkspaceNames(pqPipelineSource* source, std::string& originalWorkspaceName, std::string& rebinnedWorkspaceName);
+  void getStoredWorkspaceNames(pqPipelineSource *source,
+                               std::string &originalWorkspaceName,
+                               std::string &rebinnedWorkspaceName);
 
-          void registerRebinnedSource(pqPipelineSource* source);
+  void registerRebinnedSource(pqPipelineSource *source);
 
-          bool isRebinnedSourceBeingTracked(pqPipelineSource* source);
+  bool isRebinnedSourceBeingTracked(pqPipelineSource *source);
 
-        signals:
-          void switchSources(std::string rebinnedWorkspaceName,  std::string sourceType);
+signals:
+  void switchSources(std::string rebinnedWorkspaceName, std::string sourceType);
 
-          void triggerAcceptForNewFilters();
-        protected:
-          void addHandle(const std::string &workspaceName,
-                         const boost::shared_ptr<Mantid::API::Workspace>
-                             workspace) override;
+  void triggerAcceptForNewFilters();
 
-          void preDeleteHandle(
-              const std::string &wsName,
-              const boost::shared_ptr<Mantid::API::Workspace>) override;
+protected:
+  void
+  addHandle(const std::string &workspaceName,
+            const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
 
-          void
-          afterReplaceHandle(const std::string &workspaceName,
-                             const boost::shared_ptr<Mantid::API::Workspace>
-                                 workspace) override;
+  void
+  preDeleteHandle(const std::string &wsName,
+                  const boost::shared_ptr<Mantid::API::Workspace>) override;
 
-        private slots:
-          void onRebinnedSourceDestroyed();
+  void afterReplaceHandle(
+      const std::string &workspaceName,
+      const boost::shared_ptr<Mantid::API::Workspace> workspace) override;
 
-        private:
-          std::map<std::pair<std::string, std::string>, std::string> m_rebinnedWorkspaceAndSourceToOriginalWorkspace; ///< Holds a mapping from (RebinnedWsName, RebinnedSourceName unique ID) to (OriginalWsName)
-          std::map<std::string, std::pair<std::string, pqPipelineSource*>>  m_newWorkspacePairBuffer; ///< Holds information for the name of a new, rebinned workspace vs an original workspace and source
-          std::map<std::string, std::pair<std::string, pqPipelineSource*>>  m_newRebinnedWorkspacePairBuffer; ///< Holds information for the name of a new, rebinned workspace vs an old rebinned workspace and source
+private slots:
+  void onRebinnedSourceDestroyed();
 
-          std::string m_tempPostfix;
+private:
+  std::map<std::pair<std::string, std::string>, std::string>
+      m_rebinnedWorkspaceAndSourceToOriginalWorkspace; ///< Holds a mapping from
+                                                       ///(RebinnedWsName,
+  /// RebinnedSourceName
+  /// unique ID) to
+  ///(OriginalWsName)
+  std::map<std::string, std::pair<std::string, pqPipelineSource *>>
+      m_newWorkspacePairBuffer; ///< Holds information for the name of a new,
+  /// rebinned workspace vs an original workspace
+  /// and source
+  std::map<std::string, std::pair<std::string, pqPipelineSource *>>
+      m_newRebinnedWorkspacePairBuffer; ///< Holds information for the name of a
+  /// new, rebinned workspace vs an old
+  /// rebinned workspace and source
 
-          std::string m_tempPrefix;
+  std::string m_tempPostfix;
 
-          pqPipelineSource* m_inputSource;
+  std::string m_tempPrefix;
 
-          pqPipelineSource* m_rebinnedSource;
+  pqPipelineSource *m_inputSource;
 
-          std::vector<pqPipelineSource*> findAllRebinnedSourcesForWorkspace(std::string workspaceName);
+  pqPipelineSource *m_rebinnedSource;
 
-          void swapSources(pqPipelineSource* source1, pqPipelineSource* source2);
+  std::vector<pqPipelineSource *>
+  findAllRebinnedSourcesForWorkspace(std::string workspaceName);
 
-          void rebuildPipeline(pqPipelineSource* source1, pqPipelineSource* source2);
+  void swapSources(pqPipelineSource *source1, pqPipelineSource *source2);
 
-          void processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, pqPipelineSource* source, std::string workspaceName, std::string algorithmType);
+  void rebuildPipeline(pqPipelineSource *source1, pqPipelineSource *source2);
 
-          void untrackWorkspaces(std::pair<std::string, std::string> key);
+  void processWorkspaceNames(std::string &inputWorkspace,
+                             std::string &outputWorkspace,
+                             pqPipelineSource *source,
+                             std::string workspaceName,
+                             std::string algorithmType);
 
-          void copyProperties(pqPipelineFilter* filter1, pqPipelineFilter* filter2);
+  void untrackWorkspaces(std::pair<std::string, std::string> key);
 
-          static void copySafe(vtkSMProxy* dest, vtkSMProxy* source);
+  void copyProperties(pqPipelineFilter *filter1, pqPipelineFilter *filter2);
 
-          void getWorkspaceInfo(pqPipelineSource* source, std::string& workspaceName, std::string& workSpaceType);
+  static void copySafe(vtkSMProxy *dest, vtkSMProxy *source);
 
-          void removePipeline(pqPipelineSource* source);
+  void getWorkspaceInfo(pqPipelineSource *source, std::string &workspaceName,
+                        std::string &workSpaceType);
 
-          void deleteSpecificSource(pqPipelineSource* source);
+  void removePipeline(pqPipelineSource *source);
 
-          std::string getSourceName(pqPipelineSource* source);
+  void deleteSpecificSource(pqPipelineSource *source);
 
-          std::pair<std::string, std::string> createKeyPairForSource(pqPipelineSource* source);
+  std::string getSourceName(pqPipelineSource *source);
 
-          pqPipelineSource* goToPipelineBeginning(pqPipelineSource* source);
+  std::pair<std::string, std::string>
+  createKeyPairForSource(pqPipelineSource *source);
 
-          bool doesSourceNeedToBeDeleted(
-              const std::string &sourceName,
-              const std::vector<std::string> &trackedSources);
-      };
+  pqPipelineSource *goToPipelineBeginning(pqPipelineSource *source);
 
-    } // SimpleGui
-  } // Vates
+  bool
+  doesSourceNeedToBeDeleted(const std::string &sourceName,
+                            const std::vector<std::string> &trackedSources);
+};
+
+} // SimpleGui
+} // Vates
 } // Mantid
 
-#endif 
+#endif
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SaveScreenshotReaction.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SaveScreenshotReaction.h
index a0ef152757d315099000a5a6489aed26f058aca8..4d255a31e7725e051103d9f91fd43263ec770e96 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SaveScreenshotReaction.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SaveScreenshotReaction.h
@@ -5,15 +5,12 @@
 
 #include <pqReaction.h>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SaveScreenshotReaction : public pqReaction
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SaveScreenshotReaction
+    : public pqReaction {
   /**
    *
    This class is a copy of the ParaView pqSaveScreenshotReaction class and is
@@ -21,7 +18,8 @@ class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SaveScreenshotReaction : publ
 
    @date 14/06/2013
 
-   Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+   Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+   National Laboratory & European Spallation Source
 
    This file is part of Mantid.
 
@@ -44,16 +42,16 @@ class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SaveScreenshotReaction : publ
 
   Q_OBJECT
   typedef pqReaction Superclass;
+
 public:
   /// Constructor. Parent cannot be NULL.
-  SaveScreenshotReaction(QAction* parent);
+  SaveScreenshotReaction(QAction *parent);
 
   /// Saves the screenshot.
   /// Note that this method is static. Applications can simply use this without
   /// having to create a reaction instance.
   static void saveScreenshot();
-  static void saveScreenshot(const QString& filename,
-                             const QSize& size,
+  static void saveScreenshot(const QString &filename, const QSize &size,
                              int quality);
 
 public slots:
@@ -67,11 +65,8 @@ protected:
 private:
   Q_DISABLE_COPY(SaveScreenshotReaction)
 };
-
 }
 }
 }
 
 #endif // __SAVESCREENSHOTREACTION_H
-
-
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
index 32f70d61858c24b420e80727ad8ec8b405ae1b53..ec17653d6ae0c155f2617c0e64a480c20f0345ba 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/SplatterPlotView.h
@@ -19,22 +19,21 @@ class pqPipelineRepresentation;
 class pqPipelineSource;
 class pqRenderView;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-  class RebinnedSourcesManager;
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+class RebinnedSourcesManager;
 /**
  *
  This class creates a scatter plot using the SplatterPlot ParaView plugin. The
- view will allow thresholding of the data and the ability to overlay peaks workspaces.
+ view will allow thresholding of the data and the ability to overlay peaks
+ workspaces.
 
  @author Michael Reuter
  @date 10/10/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -54,8 +53,8 @@ namespace SimpleGui
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SplatterPlotView : public ViewBase
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS SplatterPlotView
+    : public ViewBase {
   Q_OBJECT
 
 public:
@@ -64,7 +63,8 @@ public:
    * @param parent the parent widget for the threeslice view
    * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  explicit SplatterPlotView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+  explicit SplatterPlotView(QWidget *parent = 0,
+                            RebinnedSourcesManager *rebinnedSourcesManager = 0);
   /// Default destructor
   ~SplatterPlotView() override;
 
@@ -93,7 +93,7 @@ public:
    */
   void resetDisplay() override;
   /**
-   * Destroy all sources in the view. 
+   * Destroy all sources in the view.
    */
   void destroyAllSourcesInView() override;
 
@@ -143,27 +143,29 @@ private:
   /// Set the state of the peak button
   void setPeakButton(bool state);
   /// Set the frame for the peaks
-  void setPeakSourceFrame(pqPipelineSource* source);
+  void setPeakSourceFrame(pqPipelineSource *source);
   /// Check if a peaks workspace is already part of the recorded peaks sources.
-  bool checkIfPeaksWorkspaceIsAlreadyBeingTracked(pqPipelineSource* source);
+  bool checkIfPeaksWorkspaceIsAlreadyBeingTracked(pqPipelineSource *source);
   /// Update the peaks filter
-  void updatePeaksFilter(pqPipelineSource* filter);
+  void updatePeaksFilter(pqPipelineSource *filter);
   /// Destroy splatter plot specific sources and filters
   void destroyFiltersForSplatterPlotView();
 
   bool m_noOverlay; ///< Flag to respond to overlay situation correctly
-  QList<QPointer<pqPipelineSource> > m_peaksSource; ///< A list of peaks sources
-  QPointer<pqPipelineSource> m_probeSource; ///< The VTK probe filter
-  QPointer<pqPipelineSource> m_splatSource; ///< The splatter plot source
+  QList<QPointer<pqPipelineSource>> m_peaksSource; ///< A list of peaks sources
+  QPointer<pqPipelineSource> m_probeSource;        ///< The VTK probe filter
+  QPointer<pqPipelineSource> m_splatSource;        ///< The splatter plot source
   QPointer<pqPipelineSource> m_threshSource; ///< The thresholding filter source
-  QPointer<pqPipelineSource> m_peaksFilter; ///< The peaks filter
-  Ui::SplatterPlotView m_ui; ///< The splatter plot view'a UI form
+  QPointer<pqPipelineSource> m_peaksFilter;  ///< The peaks filter
+  Ui::SplatterPlotView m_ui;     ///< The splatter plot view'a UI form
   QPointer<pqRenderView> m_view; ///< The main view area
   boost::shared_ptr<CameraManager> m_cameraManager; ///< The camera manager
-  PeaksTableControllerVsi* m_peaksTableController; ///< The peaks table controller
-  QAction* m_allPeaksAction;///<The action for showing all peaks in the table.
-  QAction* m_removePeaksAction; ///<The action for removing the peaks table.
-  std::string m_peaksWorkspaceNameDelimiter;///<Delimiter for peaks workspace strings.
+  PeaksTableControllerVsi *
+      m_peaksTableController; ///< The peaks table controller
+  QAction *m_allPeaksAction;  ///<The action for showing all peaks in the table.
+  QAction *m_removePeaksAction; ///<The action for removing the peaks table.
+  std::string
+      m_peaksWorkspaceNameDelimiter; ///<Delimiter for peaks workspace strings.
 };
 
 } // SimpleGui
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
index 5215bb8f896230d8988326a74d0ea983181d34ce..034227f40f562bca27e10d4fa44ff3be2d1baf7f 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/StandardView.h
@@ -13,12 +13,9 @@ class pqPipelineSource;
 class pqRenderView;
 class QAction;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 class RebinnedSourcesManager;
 
@@ -29,7 +26,8 @@ class RebinnedSourcesManager;
 
  @date 24/05/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -49,13 +47,14 @@ class RebinnedSourcesManager;
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS StandardView : public ViewBase
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS StandardView
+    : public ViewBase {
   Q_OBJECT
 
 public:
   /// Default constructor.
-  StandardView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+  StandardView(QWidget *parent = 0,
+               RebinnedSourcesManager *rebinnedSourcesManager = 0);
   /// Default destructor.
   ~StandardView() override;
 
@@ -80,7 +79,7 @@ public:
 
 public slots:
   /// Listen to a change in the active source.
-  void activeSourceChangeListener(pqPipelineSource* source);
+  void activeSourceChangeListener(pqPipelineSource *source);
 
 protected slots:
   /// Add a slice to the current dataset.
@@ -92,7 +91,8 @@ protected slots:
   /// On BinMD button clicked
   void onRebin();
   /// On scale completed
-  void onScaleRepresentationAdded(pqPipelineSource *, pqDataRepresentation* , int);
+  void onScaleRepresentationAdded(pqPipelineSource *, pqDataRepresentation *,
+                                  int);
 
 private:
   Q_DISABLE_COPY(StandardView)
@@ -101,8 +101,8 @@ private:
 
   bool m_cameraReset;
   QPointer<pqPipelineSource> m_scaler; ///< Holder for the ScaleWorkspace
-  Ui::StandardView m_ui; ///< The standard view's UI form
-  QPointer<pqRenderView> m_view; ///< The main view
+  Ui::StandardView m_ui;               ///< The standard view's UI form
+  QPointer<pqRenderView> m_view;       ///< The main view
 
   /// Set the rebin and unbin button visibility
   void setRebinAndUnbinButtons();
@@ -113,10 +113,10 @@ private:
   ///  Allow the user the ability to unbin
   void allowUnbinOption(bool allow);
 
-  QAction* m_binMDAction;
-  QAction* m_sliceMDAction;
-  QAction* m_cutMDAction;
-  QAction* m_unbinAction;
+  QAction *m_binMDAction;
+  QAction *m_sliceMDAction;
+  QAction *m_cutMDAction;
+  QAction *m_unbinAction;
 
   // name to show for the rebin actions on the rebin menu
   static QString g_binMDName;
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
index 56775756b71939533d657e605c8637911304745e..b51d70d6565b74f0e43be527366c2b7247dfbedd 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ThreesliceView.h
@@ -10,14 +10,11 @@
 
 class pqRenderView;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-
-  class RebinnedSourcesManager;
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+
+class RebinnedSourcesManager;
 /**
  *
  This class creates four views of the given dataset. There are three 2D views
@@ -27,7 +24,8 @@ namespace SimpleGui
  @author Michael Reuter
  @date 24/05/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -47,8 +45,8 @@ namespace SimpleGui
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ThreeSliceView : public ViewBase
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ThreeSliceView
+    : public ViewBase {
   Q_OBJECT
 
 public:
@@ -57,7 +55,8 @@ public:
    * @param parent the parent widget for the threeslice view
    * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
    */
-  ThreeSliceView(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+  ThreeSliceView(QWidget *parent = 0,
+                 RebinnedSourcesManager *rebinnedSourcesManager = 0);
   /// Default destructor.
   ~ThreeSliceView() override;
 
@@ -67,7 +66,7 @@ public:
    * Correct an oddity in the creation of the 3D view so that the cuts
    * are visibile.
    */
-  //void correctVisibility();
+  // void correctVisibility();
   /**
    * ViewBase::destroyView
    */
@@ -101,7 +100,6 @@ private:
 
   Ui::ThreeSliceView m_ui; ///< The three slice view's UI form
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/TimeControlWidget.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/TimeControlWidget.h
index ea1b3fc90935dcb6c739254492e96cf58be895aa..4651f8642129ad4e37403d3ff1282e02fae9d1a5 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/TimeControlWidget.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/TimeControlWidget.h
@@ -1,15 +1,12 @@
 #ifndef TIMECONTROLWIDGET_H_
-#define	TIMECONTROLWIDGET_H_
+#define TIMECONTROLWIDGET_H_
 
 #include "ui_TimeControlWidget.h"
 #include "MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h"
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  *
@@ -18,7 +15,8 @@ namespace SimpleGui
  @author Michael Reuter
  @date 24/05/2011
 
- Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
  This file is part of Mantid.
 
@@ -38,8 +36,8 @@ namespace SimpleGui
  File change history is stored at: <https://github.com/mantidproject/mantid>
  Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS TimeControlWidget : public QWidget
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS TimeControlWidget
+    : public QWidget {
   Q_OBJECT
 
 public:
@@ -58,9 +56,8 @@ public slots:
 private:
   Ui::TimeControlWidgetClass ui; ///< The time control widget's UI form
 };
-
 }
 }
 }
 
-#endif	// TIMECONTROLWIDGET_H_
+#endif // TIMECONTROLWIDGET_H_
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
index 1b0fdb2a209e410917191f98ae06382bbb4e514c..4dcb39b7e65ac76dd68822bc29e3f7ea493b656f 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VatesParaViewApplication.h
@@ -7,59 +7,57 @@
 #include <QObject>
 #include <QPointer>
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      /**
-       *
-       This class creates four views of the given dataset. There are three 2D views
-       for the three orthogonal Cartesian planes and one 3D view of the dataset
-       showing the planes.
-
-       @author
-       @date
-
-       Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
-
-       This file is part of Mantid.
-
-       Mantid is free software; you can redistribute it and/or modify
-       it under the terms of the GNU General Public License as published by
-       the Free Software Foundation; either version 3 of the License, or
-       (at your option) any later version.
-
-       Mantid is distributed in the hope that it will be useful,
-       but WITHOUT ANY WARRANTY; without even the implied warranty of
-       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-       GNU General Public License for more details.
-
-       You should have received a copy of the GNU General Public License
-       along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-       File change history is stored at: <https://github.com/mantidproject/mantid>
-       Code Documentation is available at: <http://doxygen.mantidproject.org>
-       */
-      class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS VatesParaViewApplication : public QObject
-      {
-        Q_OBJECT
-
-      public:
-        static VatesParaViewApplication* instance();
-        void setupParaViewBehaviors();
-      protected:
-        VatesParaViewApplication();
-        ~VatesParaViewApplication() override;
-
-      private:
-        Q_DISABLE_COPY(VatesParaViewApplication)
-        Mantid::Kernel::Logger m_logger;
-        bool m_behaviorsSetup;
-
-      };
-    } //SimpleGui
-  } //Vates
-} //Mantid
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+/**
+ *
+ This class creates four views of the given dataset. There are three 2D views
+ for the three orthogonal Cartesian planes and one 3D view of the dataset
+ showing the planes.
+
+ @author
+ @date
+
+ Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
+
+ This file is part of Mantid.
+
+ Mantid is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ Mantid is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+ File change history is stored at: <https://github.com/mantidproject/mantid>
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS VatesParaViewApplication
+    : public QObject {
+  Q_OBJECT
+
+public:
+  static VatesParaViewApplication *instance();
+  void setupParaViewBehaviors();
+
+protected:
+  VatesParaViewApplication();
+  ~VatesParaViewApplication() override;
+
+private:
+  Q_DISABLE_COPY(VatesParaViewApplication)
+  Mantid::Kernel::Logger m_logger;
+  bool m_behaviorsSetup;
+};
+} // SimpleGui
+} // Vates
+} // Mantid
 #endif
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
index 7e23810dbf63e2fded125338bf0c7bb3ea30ab11..a1f0f147414827976af7da06f2f5a77bb9af98d2 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/ViewBase.h
@@ -19,12 +19,9 @@ class vtkSMDoubleVectorProperty;
 
 class QString;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 class ColorSelectionWidget;
 class RebinnedSourcesManager;
@@ -35,7 +32,8 @@ class RebinnedSourcesManager;
 
   @date 24/05/2011
 
-  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source
+  Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
+ National Laboratory & European Spallation Source
 
   This file is part of Mantid.
 
@@ -55,12 +53,12 @@ class RebinnedSourcesManager;
   File change history is stored at: <https://github.com/mantidproject/mantid>
   Code Documentation is available at: <http://doxygen.mantidproject.org>
  */
-class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ViewBase : public QWidget
-{
+class EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS ViewBase : public QWidget {
   Q_OBJECT
 public:
   /// Default constructor.
-  ViewBase(QWidget *parent = 0, RebinnedSourcesManager* rebinnedSourcesManager = 0);
+  ViewBase(QWidget *parent = 0,
+           RebinnedSourcesManager *rebinnedSourcesManager = 0);
 
   /// Default destructor.
   ~ViewBase() override {}
@@ -73,7 +71,7 @@ public:
   virtual void closeSubWindows();
   /// Creates a single view instance.
   virtual pqRenderView *createRenderView(QWidget *container,
-                                         QString viewName=QString(""));
+                                         QString viewName = QString(""));
   /// Remove all filters of a given name: i.e. Slice.
   virtual void destroyFilter(const QString &name);
   /// Destroy sources and view relevant to mode switching.
@@ -100,7 +98,7 @@ public:
   /// Check if file/workspace is a MDHistoWorkspace.
   virtual bool isMDHistoWorkspace(pqPipelineSource *src);
   /// Check if file/workspace is an internally rebinned workspace
-  virtual bool isInternallyRebinnedWorkspace(pqPipelineSource* src);
+  virtual bool isInternallyRebinnedWorkspace(pqPipelineSource *src);
   /// Check if file/workspace is a Peaks one.
   virtual bool isPeaksWorkspace(pqPipelineSource *src);
   /// Prints properties for given source.
@@ -116,7 +114,8 @@ public:
   /// Set the current color scale state
   virtual void setColorScaleState(ColorSelectionWidget *cs);
   /// Create source for plugin mode.
-  virtual pqPipelineSource* setPluginSource(QString pluginName, QString wsName, bool axesGridOn);
+  virtual pqPipelineSource *setPluginSource(QString pluginName, QString wsName,
+                                            bool axesGridOn);
   /// Determines if source has timesteps (4D).
   virtual bool srcHasTimeSteps(pqPipelineSource *src);
   /// Set the the background color for the view
@@ -128,29 +127,30 @@ public:
   /// Sets the standard veiw button to the desired visibility.
   virtual void setStandard(bool visibility);
   /// Enumeration for Cartesian coordinates
-  enum Direction {X, Y, Z};
+  enum Direction { X, Y, Z };
   /// Update settings
   virtual void updateSettings();
   // Destroy all sources in the view.
   virtual void destroyAllSourcesInView();
   // Destroy all sources in a single linear pipeline.
-  virtual void destroySinglePipeline(pqPipelineSource * source);
-   /// Set visibility listener
+  virtual void destroySinglePipeline(pqPipelineSource *source);
+  /// Set visibility listener
   void setVisibilityListener();
   /// Undo visibiltiy listener
   void removeVisibilityListener();
   /// Set axes Grid
   void setAxesGrid(bool onOff);
   /// Set color scale lock
-  void setColorScaleLock(Mantid::VATES::ColorScaleLock* colorScaleLock);
+  void setColorScaleLock(Mantid::VATES::ColorScaleLock *colorScaleLock);
   QPointer<pqPipelineSource> origSrc; ///< The original source
-  QPointer<pqPipelineRepresentation> origRep; ///< The original source representation
+  QPointer<pqPipelineRepresentation>
+      origRep; ///< The original source representation
   /// Has active source
   bool hasActiveSource();
 
 public slots:
   /// Set the color scale back to the original bounds.
-  void onAutoScale(ColorSelectionWidget* colorSelectionWidget);
+  void onAutoScale(ColorSelectionWidget *colorSelectionWidget);
   /// Set the requested color map on the data.
   void onColorMapChange(const Json::Value &model);
   /// Set the data color scale range to the requested bounds.
@@ -172,7 +172,8 @@ public slots:
   /// Provide updates to View
   virtual void updateView();
   /// React when the visibility of a representation changes
-  virtual void onVisibilityChanged(pqPipelineSource *source, pqDataRepresentation *representation);
+  virtual void onVisibilityChanged(pqPipelineSource *source,
+                                   pqDataRepresentation *representation);
   virtual void onSourceDestroyed();
 
 signals:
@@ -186,7 +187,7 @@ signals:
    * Signal to disable all the color selection controls.
    * @param state set to false to lock out all controls
    */
-  void lockColorControls(bool state=false);
+  void lockColorControls(bool state = false);
   /// Signal indicating rendering is done.
   void renderingDone();
   /// Signal to trigger pipeline update.
@@ -220,13 +221,14 @@ signals:
    * @param algorithmType The type of rebinning algorithm.
    */
   void rebin(std::string algorithmType);
-   /**
-   * Signal to perform a possible unbin on a sources which has been
-   * rebinned in the VSI.
-   */
+  /**
+  * Signal to perform a possible unbin on a sources which has been
+  * rebinned in the VSI.
+  */
   void unbin();
   /**
-   * Signal to tell other elements that the log scale was altered programatically
+   * Signal to tell other elements that the log scale was altered
+   * programatically
    * @param state flag wheter or not to enable the
    */
   void setLogScale(bool state);
@@ -253,16 +255,16 @@ private:
   void handleTimeInfo(vtkSMDoubleVectorProperty *dvp);
 
   ColorUpdater colorUpdater; ///< Handle to the color updating delegator
-  BackgroundRgbProvider backgroundRgbProvider; /// < Holds the manager for background color related tasks.
-  RebinnedSourcesManager* m_rebinnedSourcesManager;
+  BackgroundRgbProvider backgroundRgbProvider; /// < Holds the manager for
+                                               /// background color related
+                                               /// tasks.
+  RebinnedSourcesManager *m_rebinnedSourcesManager;
   Json::Value m_currentColorMapModel;
 
   QString m_internallyRebinnedWorkspaceIdentifier;
 
-  Mantid::VATES::ColorScaleLock* m_colorScaleLock;
-
+  Mantid::VATES::ColorScaleLock *m_colorScaleLock;
 };
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VsiApplyBehaviour.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VsiApplyBehaviour.h
index 9ab574f76287b8d55c8a116781914e04ade017d9..7da0696c3d76e981e3fb103fbdc01c8df2593189 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VsiApplyBehaviour.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/VsiApplyBehaviour.h
@@ -7,29 +7,27 @@
 #include <pqPropertiesPanel.h>
 #include <pqProxy.h>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 class VsiApplyBehaviour : public pqApplyBehavior {
 public:
   Q_OBJECT
   typedef QObject Superclass;
+
 public:
-  VsiApplyBehaviour(Mantid::VATES::ColorScaleLock* lock, QObject* parent=0);
+  VsiApplyBehaviour(Mantid::VATES::ColorScaleLock *lock, QObject *parent = 0);
   ~VsiApplyBehaviour() override{};
 
   /// Register/unregister pqPropertiesPanel instances to monitor.
-  void registerPanel(pqPropertiesPanel* panel);
-  void unregisterPanel(pqPropertiesPanel* panel);
+  void registerPanel(pqPropertiesPanel *panel);
+  void unregisterPanel(pqPropertiesPanel *panel);
 protected slots:
   void applied(pqPropertiesPanel *, pqProxy *) override;
   void applied(pqPropertiesPanel *) override;
 
 private:
-  Mantid::VATES::ColorScaleLock* m_colorScaleLock;
+  Mantid::VATES::ColorScaleLock *m_colorScaleLock;
 };
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h
index a60c0ef84b5a913ef92fa002f317d88d7d96c056..16fdc0b9966f5acd2ec08305b12db1604fa55f17 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/WidgetDllOption.h
@@ -7,6 +7,6 @@
 #define EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS DLLExport
 #else
 #define EXPORT_OPT_MANTIDVATES_SIMPLEGUI_VIEWWIDGETS DLLImport
-#endif //IN_MANTID_VATES_SIMPLEGUI_VIEWWIDGETS
+#endif // IN_MANTID_VATES_SIMPLEGUI_VIEWWIDGETS
 
 #endif // MANTIDVATES_SIMPLEGUI_VIEWWIDGETS_DLLOPTION_H_
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
index 61cedf63ff32eb711fb343992a23c495aeae3811..ae5097dece0b895d4b21914128cab0b520b501da 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/AutoScaleRangeGenerator.cpp
@@ -2,7 +2,7 @@
 #include "MantidQtAPI/MdConstants.h"
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqServer.h>
@@ -19,301 +19,284 @@
 #include <vtkSMDoubleVectorProperty.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <cfloat>
 #include <QPair>
 #include "MantidQtAPI/MdSettings.h"
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-  /**
-   * Note that the mode is currently set to standard.
-   */
-  AutoScaleRangeGenerator::AutoScaleRangeGenerator() : mode(STANDARD), defaultValue(1e-2) 
-  {
-    //Set the initial log scale state due to the mode
-    m_mdSettings.setLastSessionLogScale(getLogScale());
-  }
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+/**
+ * Note that the mode is currently set to standard.
+ */
+AutoScaleRangeGenerator::AutoScaleRangeGenerator()
+    : mode(STANDARD), defaultValue(1e-2) {
+  // Set the initial log scale state due to the mode
+  m_mdSettings.setLastSessionLogScale(getLogScale());
+}
 
-  /**
-   * Gets the log scale for the mode
-   * @returns The log scale state.
-   */
-  bool AutoScaleRangeGenerator::getLogScale()
-  {   
-    bool logScale = false;
-
-    switch(mode)
-    {
-      case(STANDARD):
-        logScale = false;
-        break;
-
-      case(TECHNIQUEDEPENDENT):
-        // Implement technique-dependence here
-
-      case(OFFSET):
-          // Implement color scale which accounts for noise floor here.
-
-      default:
-        logScale= false;
-        break;
-    }
+/**
+ * Gets the log scale for the mode
+ * @returns The log scale state.
+ */
+bool AutoScaleRangeGenerator::getLogScale() {
+  bool logScale = false;
 
-    return logScale;
-  }
+  switch (mode) {
+  case (STANDARD):
+    logScale = false;
+    break;
 
-  /**
-   * Get the auto color scale which depends on the mode setting.
-   * @returns A VsiColorScale data structure which contains information 
-   *          regarding the min and max value as well as if the log 
-   *          scale is being used.
-   */
-  VsiColorScale AutoScaleRangeGenerator::getColorScale()
-  {
-    VsiColorScale colorScaleContainer;
-
-    // Select a colorscale depending on the selected mode
-    switch(mode)
-    {
-      case(STANDARD):
-        colorScaleContainer = getStandardColorScale();
-        break;
-
-      case(TECHNIQUEDEPENDENT):
-        // Implement technique-dependence here
-      case(OFFSET):
-          // Implement color scale which accounts for noise floor here.
-      default:
-        colorScaleContainer.maxValue = 1.0;
-        colorScaleContainer.minValue = 0.0;
-        colorScaleContainer.useLogScale= false;
-
-        break;
-    }
+  case (TECHNIQUEDEPENDENT):
+  // Implement technique-dependence here
 
-    // Set the colorScale Container
-    colorScaleContainer.useLogScale = m_mdSettings.getLastSessionLogScale();
+  case (OFFSET):
+  // Implement color scale which accounts for noise floor here.
 
+  default:
+    logScale = false;
+    break;
+  }
 
-    // Make sure that the color scale is valid, and if not set default values.
-    sanityCheck(colorScaleContainer);
+  return logScale;
+}
 
-    return colorScaleContainer;
+/**
+ * Get the auto color scale which depends on the mode setting.
+ * @returns A VsiColorScale data structure which contains information
+ *          regarding the min and max value as well as if the log
+ *          scale is being used.
+ */
+VsiColorScale AutoScaleRangeGenerator::getColorScale() {
+  VsiColorScale colorScaleContainer;
+
+  // Select a colorscale depending on the selected mode
+  switch (mode) {
+  case (STANDARD):
+    colorScaleContainer = getStandardColorScale();
+    break;
+
+  case (TECHNIQUEDEPENDENT):
+  // Implement technique-dependence here
+  case (OFFSET):
+  // Implement color scale which accounts for noise floor here.
+  default:
+    colorScaleContainer.maxValue = 1.0;
+    colorScaleContainer.minValue = 0.0;
+    colorScaleContainer.useLogScale = false;
+
+    break;
   }
 
-  /**
-   * The standard way of creating a colorscale entity. The minimum 
-   * and maxiumum data value of all sources is obtained. The minimum 
-   * color scale value is set to the minimum data value. The maximum 
-   * color scale value is set to 10% of the maximum data value. The
-   * scale is set to be logarithmic.
-   *
-   * @returns A color scale entity.
-   */
-  VsiColorScale AutoScaleRangeGenerator::getStandardColorScale()
-  {
-    // Select any number larger than 1 to start with
-    double maxValue= this->defaultValue;
-    double maxValueBuffer = this->defaultValue;
-    
-    double minValue = this->defaultValue; 
-    double minValueBuffer = this->defaultValue;
+  // Set the colorScale Container
+  colorScaleContainer.useLogScale = m_mdSettings.getLastSessionLogScale();
+
+  // Make sure that the color scale is valid, and if not set default values.
+  sanityCheck(colorScaleContainer);
 
-    bool initialSetting = true;
+  return colorScaleContainer;
+}
 
-    const QList<pqPipelineSource *> sources = getAllPVSources();
+/**
+ * The standard way of creating a colorscale entity. The minimum
+ * and maxiumum data value of all sources is obtained. The minimum
+ * color scale value is set to the minimum data value. The maximum
+ * color scale value is set to 10% of the maximum data value. The
+ * scale is set to be logarithmic.
+ *
+ * @returns A color scale entity.
+ */
+VsiColorScale AutoScaleRangeGenerator::getStandardColorScale() {
+  // Select any number larger than 1 to start with
+  double maxValue = this->defaultValue;
+  double maxValueBuffer = this->defaultValue;
 
-    pqView* activeView = pqActiveObjects::instance().activeView();
+  double minValue = this->defaultValue;
+  double minValueBuffer = this->defaultValue;
 
-    // Check all sources for the maximum and minimum value
-    foreach (pqPipelineSource *source, sources) {
-      // Check if the pipeline representation of the source for the active view is visible
-      pqDataRepresentation *representation =
-          source->getRepresentation(activeView);
+  bool initialSetting = true;
 
-      if (representation)
-      {
-        bool isVisible = representation->isVisible();
+  const QList<pqPipelineSource *> sources = getAllPVSources();
 
-        if (isVisible)
-        {
-          setMinBufferAndMaxBuffer(source, minValueBuffer, maxValueBuffer);
+  pqView *activeView = pqActiveObjects::instance().activeView();
 
-          if (initialSetting || maxValueBuffer > maxValue)
-          {
-            maxValue = maxValueBuffer;
-          }
+  // Check all sources for the maximum and minimum value
+  foreach (pqPipelineSource *source, sources) {
+    // Check if the pipeline representation of the source for the active view is
+    // visible
+    pqDataRepresentation *representation =
+        source->getRepresentation(activeView);
 
-          if (initialSetting || minValueBuffer < minValue)
-          {
-            minValue = minValueBuffer;
-          }
+    if (representation) {
+      bool isVisible = representation->isVisible();
 
-          initialSetting = false;
+      if (isVisible) {
+        setMinBufferAndMaxBuffer(source, minValueBuffer, maxValueBuffer);
+
+        if (initialSetting || maxValueBuffer > maxValue) {
+          maxValue = maxValueBuffer;
+        }
+
+        if (initialSetting || minValueBuffer < minValue) {
+          minValue = minValueBuffer;
         }
+
+        initialSetting = false;
       }
     }
+  }
 
-    // Set the color scale output
-    VsiColorScale vsiColorScale;
+  // Set the color scale output
+  VsiColorScale vsiColorScale;
 
-    // Initialize log scale to false
-    vsiColorScale.useLogScale = false;
+  // Initialize log scale to false
+  vsiColorScale.useLogScale = false;
 
-    // If either the min or max value are at the end of the double spectrum, we might only have a peak Ws visible, 
-    // we need to hedge for that
-    if (minValue == DBL_MAX || maxValue == -DBL_MAX) {
-      minValue = defaultValue;
-      maxValue = defaultValue;
-    }
+  // If either the min or max value are at the end of the double spectrum, we
+  // might only have a peak Ws visible,
+  // we need to hedge for that
+  if (minValue == DBL_MAX || maxValue == -DBL_MAX) {
+    minValue = defaultValue;
+    maxValue = defaultValue;
+  }
 
-    // Account for possible negative data. If min value is negative and max value is larger than 100, then set to default
-    // else set to three orders of magnitude smaller than the max value
-    if (minValue < 0 && maxValue > 100)
-    {
-      minValue = this->defaultValue;
-    } else if (minValue < 0 && maxValue < 100)
-    {
-      minValue = maxValue*0.001;
-    } 
+  // Account for possible negative data. If min value is negative and max value
+  // is larger than 100, then set to default
+  // else set to three orders of magnitude smaller than the max value
+  if (minValue < 0 && maxValue > 100) {
+    minValue = this->defaultValue;
+  } else if (minValue < 0 && maxValue < 100) {
+    minValue = maxValue * 0.001;
+  }
 
-    vsiColorScale.minValue = minValue;
-    vsiColorScale.maxValue = minValue + (maxValue - minValue)*m_mdConstants.getColorScaleStandardMax();
+  vsiColorScale.minValue = minValue;
+  vsiColorScale.maxValue =
+      minValue +
+      (maxValue - minValue) * m_mdConstants.getColorScaleStandardMax();
 
-    return vsiColorScale;
-  }
+  return vsiColorScale;
+}
+
+/**
+ * Extract the min and max values of a source. If we are dealing with a filter,
+ * then look further upstream for the information. At the end of the pipeline
+ * we have to encounter a source with the desired properties.
+ * Note that this assumes a unique source.
+ * @param source A pointer to a source.
+ * @param minValue A reference to a min value buffer.
+ * @param maxValue A reference to a max value buffer.
+ */
+void AutoScaleRangeGenerator::setMinBufferAndMaxBuffer(pqPipelineSource *source,
+                                                       double &minValue,
+                                                       double &maxValue) {
+  // Make sure that the pipeline properties are up to date
+  vtkSMProxy *proxy = source->getProxy();
+  proxy->UpdateVTKObjects();
+  proxy->UpdatePropertyInformation();
+  source->updatePipeline();
+
+  // Check if source is custom filter
+  if (QString(proxy->GetXMLName()).contains("MantidParaViewScaleWorkspace") ||
+      QString(proxy->GetXMLName()).contains("MDEWRebinningCutter") ||
+      QString(proxy->GetXMLName()).contains("MantidParaViewSplatterPlot") ||
+      QString(proxy->GetXMLName()).contains("MantidParaViewPeaksFilter"))
 
-  /**
-   * Extract the min and max values of a source. If we are dealing with a filter,
-   * then look further upstream for the information. At the end of the pipeline 
-   * we have to encounter a source with the desired properties. 
-   * Note that this assumes a unique source.
-   * @param source A pointer to a source.
-   * @param minValue A reference to a min value buffer.
-   * @param maxValue A reference to a max value buffer.
-   */
-  void AutoScaleRangeGenerator::setMinBufferAndMaxBuffer(pqPipelineSource* source, double& minValue, double& maxValue)
   {
-    // Make sure that the pipeline properties are up to date
-    vtkSMProxy* proxy = source->getProxy();
-    proxy->UpdateVTKObjects();
-    proxy->UpdatePropertyInformation();
-    source->updatePipeline();
-
-    // Check if source is custom filter
-    if (QString(proxy->GetXMLName()).contains("MantidParaViewScaleWorkspace") ||
-        QString(proxy->GetXMLName()).contains("MDEWRebinningCutter") ||
-        QString(proxy->GetXMLName()).contains("MantidParaViewSplatterPlot") ||
-        QString(proxy->GetXMLName()).contains("MantidParaViewPeaksFilter"))
-
-    {
-      minValue = vtkSMPropertyHelper(proxy,"MinValue").GetAsDouble();
-      maxValue = vtkSMPropertyHelper(proxy,"MaxValue").GetAsDouble();
-
-      return;
-    }
+    minValue = vtkSMPropertyHelper(proxy, "MinValue").GetAsDouble();
+    maxValue = vtkSMPropertyHelper(proxy, "MaxValue").GetAsDouble();
 
-    // Check if source is custom source (MDHisto or MDEvent)
-    if (QString(proxy->GetXMLName()).contains("MDEW Source") ||
-        QString(proxy->GetXMLName()).contains("MDHW Source"))
-    {
-      minValue = vtkSMPropertyHelper(proxy,"MinValue").GetAsDouble();
-      maxValue = vtkSMPropertyHelper(proxy,"MaxValue").GetAsDouble();
+    return;
+  }
 
-      return;
-    }
+  // Check if source is custom source (MDHisto or MDEvent)
+  if (QString(proxy->GetXMLName()).contains("MDEW Source") ||
+      QString(proxy->GetXMLName()).contains("MDHW Source")) {
+    minValue = vtkSMPropertyHelper(proxy, "MinValue").GetAsDouble();
+    maxValue = vtkSMPropertyHelper(proxy, "MaxValue").GetAsDouble();
 
-    // Check if Peak Workspace. This workspace should not contribute to colorscale
-    if (QString(proxy->GetXMLName()).contains("Peaks Source") ||
-        QString(proxy->GetXMLName()).contains("SinglePeakMarkerSource") ||
-        QString(proxy->GetXMLName()).contains("Threshold") ||
-        QString(proxy->GetXMLName()).contains("ProbePoint"))
-    {
-      minValue = DBL_MAX;
-      maxValue = -DBL_MAX;
+    return;
+  }
 
-      return;
-    }
+  // Check if Peak Workspace. This workspace should not contribute to colorscale
+  if (QString(proxy->GetXMLName()).contains("Peaks Source") ||
+      QString(proxy->GetXMLName()).contains("SinglePeakMarkerSource") ||
+      QString(proxy->GetXMLName()).contains("Threshold") ||
+      QString(proxy->GetXMLName()).contains("ProbePoint")) {
+    minValue = DBL_MAX;
+    maxValue = -DBL_MAX;
 
-    // Otherwise get the data range of the representation for the active view
-    pqPipelineRepresentation *pipelineRepresentation =
-        qobject_cast<pqPipelineRepresentation *>(source->getRepresentation(
-            pqActiveObjects::instance().activeView()));
-
-    if (pipelineRepresentation) {
-      // The existence of the lookuptable needs to be checked at this point.
-      // ParaView seems to sometimes return NULL for the lookuptable, eg when
-      // a cut is performed along a box boundary
-      if (auto lookuptable = pipelineRepresentation->getLookupTable()) {
-        auto range = lookuptable->getScalarRange();
-        minValue = range.first;
-        maxValue = range.second;
-      }
-    }
+    return;
   }
 
-  /**
-   * Get all sources from the PV server
-   */
-  QList<pqPipelineSource *> AutoScaleRangeGenerator::getAllPVSources()
-  {
-    pqServer *server = pqActiveObjects::instance().activeServer();
+  // Otherwise get the data range of the representation for the active view
+  pqPipelineRepresentation *pipelineRepresentation =
+      qobject_cast<pqPipelineRepresentation *>(
+          source->getRepresentation(pqActiveObjects::instance().activeView()));
+
+  if (pipelineRepresentation) {
+    // The existence of the lookuptable needs to be checked at this point.
+    // ParaView seems to sometimes return NULL for the lookuptable, eg when
+    // a cut is performed along a box boundary
+    if (auto lookuptable = pipelineRepresentation->getLookupTable()) {
+      auto range = lookuptable->getScalarRange();
+      minValue = range.first;
+      maxValue = range.second;
+    }
+  }
+}
 
-    pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+/**
+ * Get all sources from the PV server
+ */
+QList<pqPipelineSource *> AutoScaleRangeGenerator::getAllPVSources() {
+  pqServer *server = pqActiveObjects::instance().activeServer();
 
-    QList<pqPipelineSource *> sources;
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
 
-    if (server)
-    {
-      sources = smModel->findItems<pqPipelineSource *>(server);
-    }
+  QList<pqPipelineSource *> sources;
 
-    return sources;
+  if (server) {
+    sources = smModel->findItems<pqPipelineSource *>(server);
   }
 
-  /**
-   * Sanity check for the color scale, e.g. no 0 for logarithmic scaling. 
-   * @param colorscale A colorscale container
-   * @returns A colorscale container
-   */
-  void AutoScaleRangeGenerator::sanityCheck(VsiColorScale& colorscale)
-  {
-    // Make sure that the min value is larger than 0 for log scales
-    if (colorscale.useLogScale && colorscale.minValue <= 0.0)
-    {
-      colorscale.minValue = this->defaultValue;
-    }
+  return sources;
+}
 
-    // Make sure that the min value is larger than 0 for log scales
-    if (colorscale.useLogScale && colorscale.maxValue <= 0.0)
-    {
-      colorscale.maxValue = this->defaultValue;
-    }
+/**
+ * Sanity check for the color scale, e.g. no 0 for logarithmic scaling.
+ * @param colorscale A colorscale container
+ * @returns A colorscale container
+ */
+void AutoScaleRangeGenerator::sanityCheck(VsiColorScale &colorscale) {
+  // Make sure that the min value is larger than 0 for log scales
+  if (colorscale.useLogScale && colorscale.minValue <= 0.0) {
+    colorscale.minValue = this->defaultValue;
   }
 
-  /**
-   * Initializes the color scale state, in particular if it is a log scale.
-   */
-  void AutoScaleRangeGenerator::initializeColorScale()
-  {
-    m_mdSettings.setLastSessionLogScale(getLogScale());
+  // Make sure that the min value is larger than 0 for log scales
+  if (colorscale.useLogScale && colorscale.maxValue <= 0.0) {
+    colorscale.maxValue = this->defaultValue;
   }
+}
 
-  /**
-   * Update the log scale setting
-   * @param logScale The log scale setting
-   */
-  void AutoScaleRangeGenerator::updateLogScaleSetting(bool logScale)
-  {
-    m_mdSettings.setLastSessionLogScale(logScale);
-  }
+/**
+ * Initializes the color scale state, in particular if it is a log scale.
+ */
+void AutoScaleRangeGenerator::initializeColorScale() {
+  m_mdSettings.setLastSessionLogScale(getLogScale());
+}
+
+/**
+ * Update the log scale setting
+ * @param logScale The log scale setting
+ */
+void AutoScaleRangeGenerator::updateLogScaleSetting(bool logScale) {
+  m_mdSettings.setLastSessionLogScale(logScale);
+}
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
index 5d87dd61bb3f15d2e5ed12f0b7d741a12c1e8b2c..ead81038f0f1b800c936986831f59b4323e7d8ba 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/BackgroundRgbProvider.cpp
@@ -5,7 +5,7 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 #include <pqRenderView.h>
 #include <vtkSMDoubleVectorProperty.h>
@@ -15,141 +15,134 @@
 #include <vtkSmartPointer.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-
-      QColor BackgroundRgbProvider::currentBackgroundColor = QColor(84,89,109);
-
-      BackgroundRgbProvider::BackgroundRgbProvider()
-      {
-      }
-
-      BackgroundRgbProvider::~BackgroundRgbProvider()
-      {
-         // Need to record the background color
-         update();
-      }
-
-      std::vector<double> BackgroundRgbProvider::getRgb(bool useCurrentBackgroundColor)
-      {
-        // Get the rgb setting from the config file
-        std::vector<double> userSettingRgb = getRgbFromSetting(useCurrentBackgroundColor);
-        
-        // Normalize the entries to 256
-        userSettingRgb[0] = userSettingRgb[0]/255.0;
-        userSettingRgb[1] = userSettingRgb[1]/255.0;
-        userSettingRgb[2] = userSettingRgb[2]/255.0;
-
-        return userSettingRgb;
-      }
-
-      std::vector<double> BackgroundRgbProvider::getRgbFromSetting(bool useCurrentBackgroundColor)
-      {
-        // Set the mantid default here
-        QColor userBackground;
-
-        if (useCurrentBackgroundColor)
-        {
-          // Update the settings
-          update();
-
-          userBackground = m_mdSettings.getLastSessionBackgroundColor();
-        }
-        else
-        {
-          if (m_mdSettings.getUsageLastSession())
-          {
-            userBackground = m_mdSettings.getLastSessionBackgroundColor();
-          }
-          else
-          {
-            // Select the user setting as the background color and make the user setting the last session color
-            userBackground= m_mdSettings.getUserSettingBackgroundColor();
-
-            m_mdSettings.setLastSessionBackgroundColor(userBackground);
-          }
-
-          // Need to make sure that the static variable is initialized correctly, else it will show a black background
-          currentBackgroundColor = userBackground;
-        }
-
-        // Get the background
-        int rVal;
-        int gVal;
-        int bVal;
-
-        if (userBackground.isValid())
-        {
-          rVal = userBackground.red();
-          gVal = userBackground.green();
-          bVal = userBackground.blue();
-        }
-        else
-        {
-          // Set the default
-          QColor defaultBackgroundColor = m_mdSettings.getDefaultBackgroundColor();
-          rVal = defaultBackgroundColor.red();
-          gVal = defaultBackgroundColor.green();
-          bVal = defaultBackgroundColor.blue();
-        }
-
-        return {static_cast<double>(rVal), static_cast<double>(gVal),
-                static_cast<double>(bVal)};
-      }
-
-      void BackgroundRgbProvider::update()
-      {
-        m_mdSettings.setLastSessionBackgroundColor(currentBackgroundColor);
-      }
-
-      void BackgroundRgbProvider::setBackgroundColor(pqRenderView* view, bool useCurrentBackgroundColor)
-      {
-        std::vector<double> backgroundRgb = getRgb(useCurrentBackgroundColor);
-
-        vtkSMDoubleVectorProperty* background = vtkSMDoubleVectorProperty::SafeDownCast(view->getViewProxy()->GetProperty("Background"));
-
-        background->SetElements3(backgroundRgb[0],backgroundRgb[1],backgroundRgb[2]);
-
-        view->resetCamera();
-      }
-
-      void BackgroundRgbProvider::observe(pqRenderView* view)
-      {
-        // For more information http://www.vtk.org/Wiki/VTK/Tutorials/Callbacks
-        vtkSmartPointer<vtkCallbackCommand> backgroundColorChangeCallback = vtkSmartPointer<vtkCallbackCommand>::New();
-        backgroundColorChangeCallback->SetCallback(backgroundColorChangeCallbackFunction);
-
-        view->getViewProxy()->GetProperty("Background")->AddObserver(vtkCommand::ModifiedEvent, backgroundColorChangeCallback);
-      }
-
-      void BackgroundRgbProvider::backgroundColorChangeCallbackFunction(vtkObject* caller, long unsigned int, void*, void*)
-      {
-        // Extract the background color and persist it 
-        vtkSMDoubleVectorProperty* background =vtkSMDoubleVectorProperty::SafeDownCast(caller);
-
-        int numberOfElements = background->GetNumberOfElements();
-        double* elements = background->GetElements();
-
-        if (numberOfElements >= 3)
-        {
-          double r = elements[0]*255.0;
-          double g = elements[1]*255.0;
-          double b = elements[2]*255.0;
-
-          int red = static_cast<int>(r);
-          int green = static_cast<int>(g);
-          int blue = static_cast<int>(b);
-
-          currentBackgroundColor = QColor(red,green,blue);
-        }
-      }
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+
+QColor BackgroundRgbProvider::currentBackgroundColor = QColor(84, 89, 109);
+
+BackgroundRgbProvider::BackgroundRgbProvider() {}
+
+BackgroundRgbProvider::~BackgroundRgbProvider() {
+  // Need to record the background color
+  update();
+}
+
+std::vector<double>
+BackgroundRgbProvider::getRgb(bool useCurrentBackgroundColor) {
+  // Get the rgb setting from the config file
+  std::vector<double> userSettingRgb =
+      getRgbFromSetting(useCurrentBackgroundColor);
+
+  // Normalize the entries to 256
+  userSettingRgb[0] = userSettingRgb[0] / 255.0;
+  userSettingRgb[1] = userSettingRgb[1] / 255.0;
+  userSettingRgb[2] = userSettingRgb[2] / 255.0;
+
+  return userSettingRgb;
+}
+
+std::vector<double>
+BackgroundRgbProvider::getRgbFromSetting(bool useCurrentBackgroundColor) {
+  // Set the mantid default here
+  QColor userBackground;
+
+  if (useCurrentBackgroundColor) {
+    // Update the settings
+    update();
+
+    userBackground = m_mdSettings.getLastSessionBackgroundColor();
+  } else {
+    if (m_mdSettings.getUsageLastSession()) {
+      userBackground = m_mdSettings.getLastSessionBackgroundColor();
+    } else {
+      // Select the user setting as the background color and make the user
+      // setting the last session color
+      userBackground = m_mdSettings.getUserSettingBackgroundColor();
+
+      m_mdSettings.setLastSessionBackgroundColor(userBackground);
     }
+
+    // Need to make sure that the static variable is initialized correctly, else
+    // it will show a black background
+    currentBackgroundColor = userBackground;
+  }
+
+  // Get the background
+  int rVal;
+  int gVal;
+  int bVal;
+
+  if (userBackground.isValid()) {
+    rVal = userBackground.red();
+    gVal = userBackground.green();
+    bVal = userBackground.blue();
+  } else {
+    // Set the default
+    QColor defaultBackgroundColor = m_mdSettings.getDefaultBackgroundColor();
+    rVal = defaultBackgroundColor.red();
+    gVal = defaultBackgroundColor.green();
+    bVal = defaultBackgroundColor.blue();
+  }
+
+  return {static_cast<double>(rVal), static_cast<double>(gVal),
+          static_cast<double>(bVal)};
+}
+
+void BackgroundRgbProvider::update() {
+  m_mdSettings.setLastSessionBackgroundColor(currentBackgroundColor);
+}
+
+void BackgroundRgbProvider::setBackgroundColor(pqRenderView *view,
+                                               bool useCurrentBackgroundColor) {
+  std::vector<double> backgroundRgb = getRgb(useCurrentBackgroundColor);
+
+  vtkSMDoubleVectorProperty *background =
+      vtkSMDoubleVectorProperty::SafeDownCast(
+          view->getViewProxy()->GetProperty("Background"));
+
+  background->SetElements3(backgroundRgb[0], backgroundRgb[1],
+                           backgroundRgb[2]);
+
+  view->resetCamera();
+}
+
+void BackgroundRgbProvider::observe(pqRenderView *view) {
+  // For more information http://www.vtk.org/Wiki/VTK/Tutorials/Callbacks
+  vtkSmartPointer<vtkCallbackCommand> backgroundColorChangeCallback =
+      vtkSmartPointer<vtkCallbackCommand>::New();
+  backgroundColorChangeCallback->SetCallback(
+      backgroundColorChangeCallbackFunction);
+
+  view->getViewProxy()
+      ->GetProperty("Background")
+      ->AddObserver(vtkCommand::ModifiedEvent, backgroundColorChangeCallback);
+}
+
+void BackgroundRgbProvider::backgroundColorChangeCallbackFunction(
+    vtkObject *caller, long unsigned int, void *, void *) {
+  // Extract the background color and persist it
+  vtkSMDoubleVectorProperty *background =
+      vtkSMDoubleVectorProperty::SafeDownCast(caller);
+
+  int numberOfElements = background->GetNumberOfElements();
+  double *elements = background->GetElements();
+
+  if (numberOfElements >= 3) {
+    double r = elements[0] * 255.0;
+    double g = elements[1] * 255.0;
+    double b = elements[2] * 255.0;
+
+    int red = static_cast<int>(r);
+    int green = static_cast<int>(g);
+    int blue = static_cast<int>(b);
+
+    currentBackgroundColor = QColor(red, green, blue);
   }
+}
+}
+}
 }
\ No newline at end of file
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
index 2c691f7aba0456e0522492bf758df0c407732a73..f6efdf7366b967f6d96abda75cac15149a68e749 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/CameraManager.cpp
@@ -3,7 +3,7 @@
 #include <stdexcept>
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqView.h>
@@ -13,128 +13,116 @@
 #include <vtkRenderer.h>
 #include <vtkRenderWindow.h>
 #include <boost/make_shared.hpp>
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      CameraManager::CameraManager()
-      {
-      }
-
-      CameraManager::~CameraManager()
-      {
-      }
-
-      /**
-       * Get the plane equation for the view frustum.
-       */
-      Mantid::VATES::ViewFrustum_const_sptr CameraManager::getCurrentViewFrustum()
-      {
-        double left[4];
-        double right[4];
-        double bottom[4];
-        double top[4];
-        double far[4];
-        double near[4];
-
-        pqView * view = pqActiveObjects::instance().activeView();
-
-        vtkSMRenderViewProxy* proxy = NULL;
-
-        if (view)
-        {
-          proxy = vtkSMRenderViewProxy::SafeDownCast(view->getViewProxy());
-        }
-
-        if (!proxy)
-        {
-          // no active view, or active view is not a render view.
-          throw std::invalid_argument("Invalid vtkSMRenderViewProxy.");
-        }
-
-        // Get the aspect ratio of the renderer
-        vtkRenderer* renderer = proxy->GetRenderer();
-        if (!renderer)
-        {
-          throw std::invalid_argument("Invalid vtkRenderer.");
-        }
-
-        double aspectDimensions[2];
-        renderer->GetAspect(aspectDimensions);
-        double aspectRatio = aspectDimensions[0]/aspectDimensions[1];
-
-        // Get the active camera 
-        vtkCamera* camera = proxy->GetActiveCamera();
-
-        if (!camera)
-        {
-          throw std::invalid_argument("Invalid vtkCamera.");
-        }
-
-        double planes[24];
-        camera->GetFrustumPlanes(aspectRatio, planes);
-
-        for (int k = 0; k < 4; ++k)
-        {
-          left[k] = planes[k];
-          right[k] = planes[k + 4];
-
-          bottom[k] = planes[k + 8];
-          top[k] = planes[k + 12];
-
-          near[k] = planes[k + 16];
-          far[k] = planes[k + 20];
-        }
-
-        Mantid::VATES::ViewFrustum_const_sptr frustum = boost::make_shared<const Mantid::VATES::ViewFrustum>(Mantid::VATES::LeftPlane(left[0], left[1], left[2], left[3]),
-                                                                                                             Mantid::VATES::RightPlane(right[0], right[1], right[2], right[3]),
-                                                                                                             Mantid::VATES::BottomPlane(bottom[0], bottom[1], bottom[2], bottom[3]),
-                                                                                                             Mantid::VATES::TopPlane(top[0], top[1], top[2], top[3]),
-                                                                                                             Mantid::VATES::FarPlane(far[0], far[1], far[2], far[3]),
-                                                                                                             Mantid::VATES::NearPlane(near[0], near[1], near[2], near[3]));
-
-        return frustum;
-      }
-    
-      /**
-      * Set the view onto a peak
-      * @param xpos X position of the peak.
-      * @param ypos Y position of the peak.
-      * @param zpos Z position of the peak.
-      * @param peakRadius The radius of the peak.
-      */
-      void CameraManager::setCameraToPeak(double xpos, double ypos, double zpos, double peakRadius)
-      {
-        pqView * view = pqActiveObjects::instance().activeView();
-        vtkSMRenderViewProxy* proxy = NULL;
-
-        if (view)
-        {
-          proxy = vtkSMRenderViewProxy::SafeDownCast(view->getViewProxy());
-        }
-
-        if (!proxy)
-        {
-          // no active view, or active view is not a render view.
-          throw std::invalid_argument("Invalid vtkSMRenderViewProxy.");
-        }
-
-        // Get the active camera 
-        vtkCamera* camera = proxy->GetActiveCamera();
-
-        // Setup the focal point of the camera. we want this to be on the peak
-        camera->SetFocalPoint(xpos, ypos, zpos);
-
-        // Setup the position of the camera. We want this to be 
-        const double cameraDistance = 12;
-        double zposCamera = zpos + peakRadius*cameraDistance;
-        camera->SetPosition(xpos, ypos, zposCamera);
-        camera->SetViewUp(0.0, 1.0, 0.0);
-
-        view->forceRender();
-      }
-    }
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+CameraManager::CameraManager() {}
+
+CameraManager::~CameraManager() {}
+
+/**
+ * Get the plane equation for the view frustum.
+ */
+Mantid::VATES::ViewFrustum_const_sptr CameraManager::getCurrentViewFrustum() {
+  double left[4];
+  double right[4];
+  double bottom[4];
+  double top[4];
+  double far[4];
+  double near[4];
+
+  pqView *view = pqActiveObjects::instance().activeView();
+
+  vtkSMRenderViewProxy *proxy = NULL;
+
+  if (view) {
+    proxy = vtkSMRenderViewProxy::SafeDownCast(view->getViewProxy());
   }
+
+  if (!proxy) {
+    // no active view, or active view is not a render view.
+    throw std::invalid_argument("Invalid vtkSMRenderViewProxy.");
+  }
+
+  // Get the aspect ratio of the renderer
+  vtkRenderer *renderer = proxy->GetRenderer();
+  if (!renderer) {
+    throw std::invalid_argument("Invalid vtkRenderer.");
+  }
+
+  double aspectDimensions[2];
+  renderer->GetAspect(aspectDimensions);
+  double aspectRatio = aspectDimensions[0] / aspectDimensions[1];
+
+  // Get the active camera
+  vtkCamera *camera = proxy->GetActiveCamera();
+
+  if (!camera) {
+    throw std::invalid_argument("Invalid vtkCamera.");
+  }
+
+  double planes[24];
+  camera->GetFrustumPlanes(aspectRatio, planes);
+
+  for (int k = 0; k < 4; ++k) {
+    left[k] = planes[k];
+    right[k] = planes[k + 4];
+
+    bottom[k] = planes[k + 8];
+    top[k] = planes[k + 12];
+
+    near[k] = planes[k + 16];
+    far[k] = planes[k + 20];
+  }
+
+  Mantid::VATES::ViewFrustum_const_sptr frustum =
+      boost::make_shared<const Mantid::VATES::ViewFrustum>(
+          Mantid::VATES::LeftPlane(left[0], left[1], left[2], left[3]),
+          Mantid::VATES::RightPlane(right[0], right[1], right[2], right[3]),
+          Mantid::VATES::BottomPlane(bottom[0], bottom[1], bottom[2],
+                                     bottom[3]),
+          Mantid::VATES::TopPlane(top[0], top[1], top[2], top[3]),
+          Mantid::VATES::FarPlane(far[0], far[1], far[2], far[3]),
+          Mantid::VATES::NearPlane(near[0], near[1], near[2], near[3]));
+
+  return frustum;
+}
+
+/**
+* Set the view onto a peak
+* @param xpos X position of the peak.
+* @param ypos Y position of the peak.
+* @param zpos Z position of the peak.
+* @param peakRadius The radius of the peak.
+*/
+void CameraManager::setCameraToPeak(double xpos, double ypos, double zpos,
+                                    double peakRadius) {
+  pqView *view = pqActiveObjects::instance().activeView();
+  vtkSMRenderViewProxy *proxy = NULL;
+
+  if (view) {
+    proxy = vtkSMRenderViewProxy::SafeDownCast(view->getViewProxy());
+  }
+
+  if (!proxy) {
+    // no active view, or active view is not a render view.
+    throw std::invalid_argument("Invalid vtkSMRenderViewProxy.");
+  }
+
+  // Get the active camera
+  vtkCamera *camera = proxy->GetActiveCamera();
+
+  // Setup the focal point of the camera. we want this to be on the peak
+  camera->SetFocalPoint(xpos, ypos, zpos);
+
+  // Setup the position of the camera. We want this to be
+  const double cameraDistance = 12;
+  double zposCamera = zpos + peakRadius * cameraDistance;
+  camera->SetPosition(xpos, ypos, zposCamera);
+  camera->SetViewUp(0.0, 1.0, 0.0);
+
+  view->forceRender();
+}
+}
+}
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/ColorSelectionWidget.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/ColorSelectionWidget.cpp
index 55aa2b0d0e1d324036fd2bb1654b2379800767b6..aada3c0fd4641bf79e108e87c923e33d773e033a 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/ColorSelectionWidget.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/ColorSelectionWidget.cpp
@@ -15,12 +15,9 @@
 #include <QFile>
 #include <QFileInfo>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  * This is the class constructor. It sets up the UI and all the necessary
@@ -43,23 +40,25 @@ ColorSelectionWidget::ColorSelectionWidget(QWidget *parent)
   this->m_ui.maxValLineEdit->setValidator(m_minValidator);
   this->m_ui.minValLineEdit->setValidator(m_maxValidator);
 
-  // note the clicked() signals, not stateChanged(), beware of programmatic state changes
-  // comming from user events from other sources (vtk callbacks and signals from the
+  // note the clicked() signals, not stateChanged(), beware of programmatic
+  // state changes
+  // comming from user events from other sources (vtk callbacks and signals from
+  // the
   // Paraview color map editor)
   QObject::connect(this->m_ui.autoColorScaleCheckBox, SIGNAL(clicked(bool)),
                    this, SLOT(autoCheckBoxClicked(bool)));
 
-  QObject::connect(this->m_ui.presetButton, SIGNAL(clicked()),
-                   this, SLOT(loadPreset()));
+  QObject::connect(this->m_ui.presetButton, SIGNAL(clicked()), this,
+                   SLOT(loadPreset()));
 
-  QObject::connect(this->m_ui.minValLineEdit, SIGNAL(editingFinished()),
-                   this, SLOT(getColorScaleRange()));
+  QObject::connect(this->m_ui.minValLineEdit, SIGNAL(editingFinished()), this,
+                   SLOT(getColorScaleRange()));
 
-  QObject::connect(this->m_ui.maxValLineEdit, SIGNAL(editingFinished()),
-                   this, SLOT(getColorScaleRange()));
+  QObject::connect(this->m_ui.maxValLineEdit, SIGNAL(editingFinished()), this,
+                   SLOT(getColorScaleRange()));
 
-  QObject::connect(this->m_ui.useLogScaleCheckBox, SIGNAL(clicked(bool)),
-                   this, SLOT(useLogScalingClicked(bool)));
+  QObject::connect(this->m_ui.useLogScaleCheckBox, SIGNAL(clicked(bool)), this,
+                   SLOT(useLogScalingClicked(bool)));
 }
 
 /**
@@ -68,8 +67,7 @@ ColorSelectionWidget::ColorSelectionWidget(QWidget *parent)
  *
  * @param status the state to set the color selection widgets to
  */
-void ColorSelectionWidget::setEditorStatus(bool status)
-{
+void ColorSelectionWidget::setEditorStatus(bool status) {
   this->m_ui.maxValLabel->setEnabled(status);
   this->m_ui.maxValLineEdit->setEnabled(status);
   this->m_ui.minValLabel->setEnabled(status);
@@ -79,8 +77,7 @@ void ColorSelectionWidget::setEditorStatus(bool status)
 /**
  * This function sets up various color maps.
  */
-void ColorSelectionWidget::loadBuiltinColorPresets()
-{
+void ColorSelectionWidget::loadBuiltinColorPresets() {
   // the destructor of vtkSMTransferFunctionPresets copies these colormaps to
   // the vtkSMSettings singleton.
   vtkNew<vtkSMTransferFunctionPresets> presets;
@@ -100,42 +97,41 @@ void ColorSelectionWidget::loadBuiltinColorPresets()
   }
 }
 
- /**
-  * Load the default color map
-  * @param viewSwitched Flag if the view has switched or not.
-  */
-  void ColorSelectionWidget::loadColorMap(bool viewSwitched)
-  {
+/**
+ * Load the default color map
+ * @param viewSwitched Flag if the view has switched or not.
+ */
+void ColorSelectionWidget::loadColorMap(bool viewSwitched) {
 
-    QString defaultColorMap;
+  QString defaultColorMap;
 
-    // If the view has switched or the VSI is loaded use the last color map
-    // index
-    if (viewSwitched) {
-      defaultColorMap = m_mdSettings.getLastSessionColorMap();
+  // If the view has switched or the VSI is loaded use the last color map
+  // index
+  if (viewSwitched) {
+    defaultColorMap = m_mdSettings.getLastSessionColorMap();
+  } else {
+    // Check if the user wants a general MD color map
+    if (m_mdSettings.getUsageGeneralMdColorMap()) {
+      // The name is sufficient for the VSI to find the color map
+      defaultColorMap = m_mdSettings.getGeneralMdColorMapName();
     } else {
-      // Check if the user wants a general MD color map
-      if (m_mdSettings.getUsageGeneralMdColorMap()) {
-        // The name is sufficient for the VSI to find the color map
-        defaultColorMap = m_mdSettings.getGeneralMdColorMapName();
+      // Check if the user wants to use the last session
+      if (m_mdSettings.getUsageLastSession()) {
+        defaultColorMap = m_mdSettings.getLastSessionColorMap();
       } else {
-        // Check if the user wants to use the last session
-        if (m_mdSettings.getUsageLastSession()) {
-          defaultColorMap = m_mdSettings.getLastSessionColorMap();
-        } else {
-          defaultColorMap = m_mdSettings.getUserSettingColorMap();
-        }
+        defaultColorMap = m_mdSettings.getUserSettingColorMap();
       }
     }
-
-    Mantid::VATES::ColorScaleLockGuard guard(m_colorScaleLock);
-    pqPresetDialog preset(this, pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);
-    preset.setCurrentPreset(defaultColorMap.toStdString().c_str());
-    Json::Value colorMap = preset.currentPreset();
-    if (!colorMap.empty())
-      this->onApplyPreset(colorMap);
   }
 
+  Mantid::VATES::ColorScaleLockGuard guard(m_colorScaleLock);
+  pqPresetDialog preset(this, pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);
+  preset.setCurrentPreset(defaultColorMap.toStdString().c_str());
+  Json::Value colorMap = preset.currentPreset();
+  if (!colorMap.empty())
+    this->onApplyPreset(colorMap);
+}
+
 /**
  * Changes the status of the autoScaling checkbox. This is in
  * principle meant to be used programmatically, when for example the
@@ -143,8 +139,7 @@ void ColorSelectionWidget::loadBuiltinColorPresets()
  *
  * @param autoScale whether to set auto scaling (on/off)
  */
-void ColorSelectionWidget::setAutoScale(bool autoScale)
-{
+void ColorSelectionWidget::setAutoScale(bool autoScale) {
   this->m_ui.autoColorScaleCheckBox->setChecked(autoScale);
   this->setEditorStatus(!autoScale);
 }
@@ -155,8 +150,7 @@ void ColorSelectionWidget::setAutoScale(bool autoScale)
  * @param max maximum value (corresponding to the max line edit)
  * @param min minimum value (corresponding to the max line edit)
  */
-void ColorSelectionWidget::setMinMax(double& min, double& max)
-{
+void ColorSelectionWidget::setMinMax(double &min, double &max) {
   setMinSmallerMax(min, max);
 }
 
@@ -188,16 +182,12 @@ bool ColorSelectionWidget::isIgnoringColorCallbacks() {
  *
  * @param wasOn current checked state (before the user clicks)
  */
-void ColorSelectionWidget::autoCheckBoxClicked(bool wasOn)
-{
+void ColorSelectionWidget::autoCheckBoxClicked(bool wasOn) {
   m_inProcessUserRequestedAutoScale = true;
-  if (!wasOn)
-  {
+  if (!wasOn) {
     this->setEditorStatus(true);
     emit this->autoScale(this);
-  }
-  else
-  {
+  } else {
     this->setEditorStatus(false);
     emit this->autoScale(this);
   }
@@ -208,8 +198,7 @@ void ColorSelectionWidget::autoCheckBoxClicked(bool wasOn)
  * This function presents the user with the available color presets (maps) and
  * gets the selection result from the user.
  */
-void ColorSelectionWidget::loadPreset()
-{
+void ColorSelectionWidget::loadPreset() {
   Mantid::VATES::ColorScaleLockGuard guard(m_colorScaleLock);
   pqPresetDialog preset(this, pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);
   preset.setCustomizableLoadColors(false, false);
@@ -227,14 +216,10 @@ void ColorSelectionWidget::loadPreset()
  * This function gets the new color scale range from the value widgets and
  * passes a signal along with that new range.
  */
-void ColorSelectionWidget::getColorScaleRange()
-{
-  if (this->m_ui.useLogScaleCheckBox->isChecked())
-  {
+void ColorSelectionWidget::getColorScaleRange() {
+  if (this->m_ui.useLogScaleCheckBox->isChecked()) {
     setupLogScale(true);
-  }
-  else
-  {
+  } else {
     setupLogScale(false);
   }
 
@@ -249,10 +234,8 @@ void ColorSelectionWidget::getColorScaleRange()
  * @param min the minimum value of the color scale range
  * @param max the maximum value of the color scale range
  */
-void ColorSelectionWidget::setColorScaleRange(double min, double max)
-{
-  if (this->m_ui.autoColorScaleCheckBox->isChecked())
-  {
+void ColorSelectionWidget::setColorScaleRange(double min, double max) {
+  if (this->m_ui.autoColorScaleCheckBox->isChecked()) {
     m_minHistoric = min;
     m_maxHistoric = max;
 
@@ -260,9 +243,7 @@ void ColorSelectionWidget::setColorScaleRange(double min, double max)
     this->m_ui.minValLineEdit->insert(QString::number(min));
     this->m_ui.maxValLineEdit->clear();
     this->m_ui.maxValLineEdit->insert(QString::number(max));
-  }
-  else
-  {
+  } else {
     this->getColorScaleRange();
   }
 }
@@ -274,8 +255,7 @@ void ColorSelectionWidget::setColorScaleRange(double min, double max)
  *
  * @param on clicked-state of use-log-scaling
  */
-void ColorSelectionWidget::useLogScalingClicked(bool on)
-{
+void ColorSelectionWidget::useLogScalingClicked(bool on) {
   // Set up values for with or without log scale
   getColorScaleRange();
 
@@ -295,11 +275,9 @@ void ColorSelectionWidget::onApplyPreset(const Json::Value &value) {
  * associated checkbox.
  * @param state flag for whether or not to use log color scaling
  */
-void ColorSelectionWidget::useLogScaling(int state)
-{
+void ColorSelectionWidget::useLogScaling(int state) {
   // Qt::Checked is 2, need it to be 1 for boolean true conversion
-  if (Qt::Checked == state)
-  {
+  if (Qt::Checked == state) {
     state -= 1;
   }
 
@@ -310,11 +288,11 @@ void ColorSelectionWidget::useLogScaling(int state)
 }
 
 /**
- * Set up the min and max values and validators for use with or without log scaling
+ * Set up the min and max values and validators for use with or without log
+ * scaling
  * @param state The state of the log scale, where 0 is no log scale
  */
-void ColorSelectionWidget::setupLogScale(int state)
-{
+void ColorSelectionWidget::setupLogScale(int state) {
   // Get the min and max values
   double min = this->m_ui.minValLineEdit->text().toDouble();
   double max = this->m_ui.maxValLineEdit->text().toDouble();
@@ -323,15 +301,12 @@ void ColorSelectionWidget::setupLogScale(int state)
   setMinSmallerMax(min, max);
 
   // If we switched to a log state make sure that values are larger than 0
-  if (state)
-  {
-    if (min <= 0 )
-    {
+  if (state) {
+    if (min <= 0) {
       min = m_mdConstants.getLogScaleDefaultValue();
     }
 
-    if (max <= 0)
-    {
+    if (max <= 0) {
       max = m_mdConstants.getLogScaleDefaultValue();
     }
   }
@@ -340,41 +315,35 @@ void ColorSelectionWidget::setupLogScale(int state)
   setMinSmallerMax(min, max);
 
   // Set the validators
-  if (state)
-  {
+  if (state) {
     m_maxValidator->setBottom(0.0);
     m_minValidator->setBottom(0.0);
-  }
-  else
-  {
+  } else {
     m_maxValidator->setBottom(-DBL_MAX);
     m_minValidator->setBottom(-DBL_MAX);
   }
 }
 
 /**
- * Slot to set the checkbox if the logscaling behaviour has been set programatically
+ * Slot to set the checkbox if the logscaling behaviour has been set
+ * programatically
  * @param state Flag whether the checkbox should be checked or not
  */
-void ColorSelectionWidget::onSetLogScale(bool state)
-{
-    m_ui.useLogScaleCheckBox->setChecked(state);
+void ColorSelectionWidget::onSetLogScale(bool state) {
+  m_ui.useLogScaleCheckBox->setChecked(state);
 }
 
 /**
- * Make sure that min is smaller/equal than max. If not then set to the old value.
+ * Make sure that min is smaller/equal than max. If not then set to the old
+ * value.
  * @param max The maximum value.
  * @param min The minimum value.
  */
-void ColorSelectionWidget::setMinSmallerMax(double& min, double& max)
-{
-  if (min <= max)
-  {
+void ColorSelectionWidget::setMinSmallerMax(double &min, double &max) {
+  if (min <= max) {
     m_minHistoric = min;
     m_maxHistoric = max;
-  }
-  else
-  {
+  } else {
     min = m_minHistoric;
     max = m_maxHistoric;
   }
@@ -390,16 +359,13 @@ void ColorSelectionWidget::setMinSmallerMax(double& min, double& max)
  * widget.
  * @param state the boolean to set the controls' state to
  */
-void ColorSelectionWidget::enableControls(bool state)
-{
+void ColorSelectionWidget::enableControls(bool state) {
   this->m_ui.colorSelectionLabel->setEnabled(state);
   this->m_ui.autoColorScaleCheckBox->setEnabled(state);
   this->m_ui.useLogScaleCheckBox->setEnabled(state);
   int cbstate = this->m_ui.autoColorScaleCheckBox->isChecked();
-  if (state)
-  {
-    switch (cbstate)
-    {
+  if (state) {
+    switch (cbstate) {
     case Qt::Unchecked:
       this->setEditorStatus(true);
       break;
@@ -407,9 +373,7 @@ void ColorSelectionWidget::enableControls(bool state)
       this->setEditorStatus(false);
       break;
     }
-  }
-  else
-  {
+  } else {
     this->setEditorStatus(false);
   }
   this->m_ui.presetButton->setEnabled(state);
@@ -421,11 +385,9 @@ void ColorSelectionWidget::enableControls(bool state)
  * to be decremented to cast to a boolean.
  * @return the state of automatic color scaling
  */
-bool ColorSelectionWidget::getAutoScaleState()
-{
+bool ColorSelectionWidget::getAutoScaleState() {
   int state = this->m_ui.autoColorScaleCheckBox->isChecked();
-  if (Qt::Checked == state)
-  {
+  if (Qt::Checked == state) {
     state -= 1;
   }
   return static_cast<bool>(state);
@@ -437,11 +399,9 @@ bool ColorSelectionWidget::getAutoScaleState()
  * to be decremented to cast to a boolean.
  * @return the state of logarithmic color scaling
  */
-bool ColorSelectionWidget::getLogScaleState()
-{
+bool ColorSelectionWidget::getLogScaleState() {
   int state = this->m_ui.useLogScaleCheckBox->isChecked();
-  if (Qt::Checked == state)
-  {
+  if (Qt::Checked == state) {
     state -= 1;
   }
 
@@ -452,8 +412,7 @@ bool ColorSelectionWidget::getLogScaleState()
  * This function returns the minimum range value for the color scaling.
  * @return current minimum color scaling value
  */
-double ColorSelectionWidget::getMinRange()
-{
+double ColorSelectionWidget::getMinRange() {
   return this->m_ui.minValLineEdit->text().toDouble();
 }
 
@@ -461,8 +420,7 @@ double ColorSelectionWidget::getMinRange()
  * This function returns the maximum range value for the color scaling.
  * @return current maximum color scaling value
  */
-double ColorSelectionWidget::getMaxRange()
-{
+double ColorSelectionWidget::getMaxRange() {
   return this->m_ui.maxValLineEdit->text().toDouble();
 }
 
@@ -471,8 +429,7 @@ double ColorSelectionWidget::getMaxRange()
  * This means that automatic color scaling is on, log scaling is off and
  * the color range line edits are empty.
  */
-void ColorSelectionWidget::reset()
-{
+void ColorSelectionWidget::reset() {
   this->m_ui.autoColorScaleCheckBox->setChecked(true);
   this->m_ui.useLogScaleCheckBox->setChecked(false);
   this->m_ui.minValLineEdit->setText("");
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
index e1fca2121cafb524d330c6640e08e3a17667c259..576dad6d77f2acc660b2f1a26dcf14c716b8fab5 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/ColorUpdater.cpp
@@ -27,42 +27,33 @@
 #include <QColor>
 #include <QList>
 
-namespace Mantid
-{
-  // static logger
-  Kernel::Logger g_log("ColorUpdater");
-
-namespace Vates
-{
-namespace SimpleGui
-{
-  
-ColorUpdater::ColorUpdater() :
-  m_autoScaleState(true),
-  m_logScaleState(false),
-  m_minScale(std::numeric_limits<double>::min()),
-  m_maxScale(std::numeric_limits<double>::max())
-{
-}
+namespace Mantid {
+// static logger
+Kernel::Logger g_log("ColorUpdater");
 
-ColorUpdater::~ColorUpdater()
-{
-}
+namespace Vates {
+namespace SimpleGui {
+
+ColorUpdater::ColorUpdater()
+    : m_autoScaleState(true), m_logScaleState(false),
+      m_minScale(std::numeric_limits<double>::min()),
+      m_maxScale(std::numeric_limits<double>::max()) {}
+
+ColorUpdater::~ColorUpdater() {}
 
 /**
  * Set the lookup table to the autoscale values.
  * @returns A struct which contains the parameters of the looup table.
  */
-VsiColorScale ColorUpdater::autoScale()
-{
+VsiColorScale ColorUpdater::autoScale() {
   // Get the custom auto scale.
-  VsiColorScale vsiColorScale =  this->m_autoScaleRangeGenerator.getColorScale();
+  VsiColorScale vsiColorScale = this->m_autoScaleRangeGenerator.getColorScale();
 
   // Set the color scale for all sources
   this->m_minScale = vsiColorScale.minValue;
   this->m_maxScale = vsiColorScale.maxValue;
 
-  // If the view 
+  // If the view
 
   this->m_logScaleState = vsiColorScale.useLogScale;
 
@@ -88,16 +79,15 @@ void ColorUpdater::colorMapChange(pqPipelineRepresentation *repr,
  * @param min The lower end of the color scale.
  * @param max The upper end of the color scale.
  */
-void ColorUpdater::colorScaleChange(double min, double max)
-{
+void ColorUpdater::colorScaleChange(double min, double max) {
   this->m_minScale = min;
   this->m_maxScale = max;
 
-  try
-  {
+  try {
     // Update for all sources and all reps
     pqServer *server = pqActiveObjects::instance().activeServer();
-    pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+    pqServerManagerModel *smModel =
+        pqApplicationCore::instance()->getServerManagerModel();
     const QList<pqPipelineSource *> sources =
         smModel->findItems<pqPipelineSource *>(server);
 
@@ -114,44 +104,46 @@ void ColorUpdater::colorScaleChange(double min, double max)
         }
       }
     }
-  }
-  catch(std::invalid_argument &)
-  {
+  } catch (std::invalid_argument &) {
     return;
   }
 }
 
 /**
  * Update the lookup table.
- * @param representation The representation for which the lookup table is updated.
+ * @param representation The representation for which the lookup table is
+ * updated.
  */
-void ColorUpdater::updateLookupTable(pqDataRepresentation* representation)
-{
-  pqScalarsToColors* lookupTable = representation->getLookupTable();
+void ColorUpdater::updateLookupTable(pqDataRepresentation *representation) {
+  pqScalarsToColors *lookupTable = representation->getLookupTable();
 
-  if (NULL != lookupTable)
-  {
+  if (NULL != lookupTable) {
     // Set the scalar range values
     lookupTable->setScalarRange(this->m_minScale, this->m_maxScale);
 
-    vtkSMProxy* proxy = representation->getProxy();
-    vtkSMProxy* lutProxy = pqSMAdaptor::getProxyProperty(proxy->GetProperty("LookupTable"));
-    vtkSMProxy* scalarOpacityFunctionProxy = lutProxy?pqSMAdaptor::getProxyProperty(lutProxy->GetProperty("ScalarOpacityFunction")) : NULL;
-
-    if (scalarOpacityFunctionProxy)
-    {
-      vtkSMTransferFunctionProxy::RescaleTransferFunction(scalarOpacityFunctionProxy, this->m_minScale, this->m_maxScale);
+    vtkSMProxy *proxy = representation->getProxy();
+    vtkSMProxy *lutProxy =
+        pqSMAdaptor::getProxyProperty(proxy->GetProperty("LookupTable"));
+    vtkSMProxy *scalarOpacityFunctionProxy =
+        lutProxy ? pqSMAdaptor::getProxyProperty(
+                       lutProxy->GetProperty("ScalarOpacityFunction"))
+                 : NULL;
+
+    if (scalarOpacityFunctionProxy) {
+      vtkSMTransferFunctionProxy::RescaleTransferFunction(
+          scalarOpacityFunctionProxy, this->m_minScale, this->m_maxScale);
     }
 
-    // Need to set a lookup table lock here. This does not affect setScalarRange, 
-    // but blocks setWholeScalarRange which gets called by ParaView overrides our
+    // Need to set a lookup table lock here. This does not affect
+    // setScalarRange,
+    // but blocks setWholeScalarRange which gets called by ParaView overrides
+    // our
     // setting when a workspace is loaded for the first time.
     lookupTable->setScalarRangeLock(true);
 
     representation->getProxy()->UpdateVTKObjects();
     representation->renderViewEventually();
-  } else
-  {
+  } else {
     throw std::invalid_argument("Cannot get LUT for representation");
   }
 }
@@ -160,8 +152,7 @@ void ColorUpdater::updateLookupTable(pqDataRepresentation* representation)
  * React to changing the log scale option
  * @param state The state to which the log scale is being changed.
  */
-void ColorUpdater::logScale(int state)
-{
+void ColorUpdater::logScale(int state) {
   this->m_logScaleState = state;
 
   // Update for all sources and all reps
@@ -206,8 +197,7 @@ void ColorUpdater::logScale(int state)
  * sets it into the internal state variables.
  * @param cs : Reference to the color selection widget
  */
-void ColorUpdater::updateState(ColorSelectionWidget *cs)
-{
+void ColorUpdater::updateState(ColorSelectionWidget *cs) {
   this->m_autoScaleState = cs->getAutoScaleState();
   this->m_logScaleState = cs->getLogScaleState();
   this->m_minScale = cs->getMinRange();
@@ -218,41 +208,28 @@ void ColorUpdater::updateState(ColorSelectionWidget *cs)
 /**
  * @return  the current auto scaling state
  */
-bool ColorUpdater::isAutoScale()
-{
-  return this->m_autoScaleState;
-}
+bool ColorUpdater::isAutoScale() { return this->m_autoScaleState; }
 
 /**
  * @return the current logarithmic scaling state
  */
-bool ColorUpdater::isLogScale()
-{
-  return this->m_logScaleState;
-}
+bool ColorUpdater::isLogScale() { return this->m_logScaleState; }
 
 /**
  * @return the current maximum range for the color scaling
  */
-double ColorUpdater::getMaximumRange()
-{
-  return this->m_maxScale;
-}
+double ColorUpdater::getMaximumRange() { return this->m_maxScale; }
 
 /**
  * @return the current minimum range for the color scaling
  */
-double ColorUpdater::getMinimumRange()
-{
-  return this->m_minScale;
-}
+double ColorUpdater::getMinimumRange() { return this->m_minScale; }
 
 /**
  * This function prints out the values of the current state of the
  * color updater.
  */
-void ColorUpdater::print()
-{
+void ColorUpdater::print() {
   std::cout << "Auto Scale: " << this->m_autoScaleState << std::endl;
   std::cout << "Log Scale: " << this->m_logScaleState << std::endl;
   std::cout << "Min Range: " << this->m_minScale << std::endl;
@@ -262,8 +239,7 @@ void ColorUpdater::print()
 /**
  * Initializes the color scale
  */
-void ColorUpdater::initializeColorScale()
-{
+void ColorUpdater::initializeColorScale() {
   m_autoScaleRangeGenerator.initializeColorScale();
 }
 
@@ -274,8 +250,8 @@ void ColorUpdater::initializeColorScale()
  * (update the min/max values).
  */
 struct ColorCallbackData {
-  ColorUpdater* colorUpdater;
-  ColorSelectionWidget* csel;
+  ColorUpdater *colorUpdater;
+  ColorSelectionWidget *csel;
 };
 ColorCallbackData ccdata;
 
@@ -288,8 +264,8 @@ ColorCallbackData ccdata;
  * @param repr Paraview representation whose color editor we have to observe
  * @param cs The simple color selection widget (the VSI one, not the ParaQ one)
  */
-void ColorUpdater::observeColorScaleEdited(pqPipelineRepresentation *repr, ColorSelectionWidget *cs)
-{
+void ColorUpdater::observeColorScaleEdited(pqPipelineRepresentation *repr,
+                                           ColorSelectionWidget *cs) {
   if (!repr)
     return;
 
@@ -302,27 +278,31 @@ void ColorUpdater::observeColorScaleEdited(pqPipelineRepresentation *repr, Color
     return;
 
   // User updates the color scale (normally the range)
-  // Prepare the callback. Vtk callbacks: http://www.vtk.org/Wiki/VTK/Tutorials/Callbacks
-  vtkSmartPointer<vtkCallbackCommand> CRChangeCallback = vtkSmartPointer<vtkCallbackCommand>::New();
+  // Prepare the callback. Vtk callbacks:
+  // http://www.vtk.org/Wiki/VTK/Tutorials/Callbacks
+  vtkSmartPointer<vtkCallbackCommand> CRChangeCallback =
+      vtkSmartPointer<vtkCallbackCommand>::New();
   CRChangeCallback->SetCallback(colorScaleEditedCallbackFunc);
-  // note this uses the same ccdata which would misbehave if we wanted multiple VSI instances
+  // note this uses the same ccdata which would misbehave if we wanted multiple
+  // VSI instances
   ccdata.colorUpdater = this;
   ccdata.csel = cs;
   CRChangeCallback->SetClientData(&ccdata);
   // install callback
-  vtkSMDoubleVectorProperty *points =
-    vtkSMDoubleVectorProperty::SafeDownCast(lutProxy->GetProperty("RGBPoints"));
+  vtkSMDoubleVectorProperty *points = vtkSMDoubleVectorProperty::SafeDownCast(
+      lutProxy->GetProperty("RGBPoints"));
 
   if (points) {
     points->AddObserver(vtkCommand::ModifiedEvent, CRChangeCallback);
   }
 
   // User clicks on the log-scale tick box
-  vtkSmartPointer<vtkCallbackCommand> LogScaleCallback = vtkSmartPointer<vtkCallbackCommand>::New();
+  vtkSmartPointer<vtkCallbackCommand> LogScaleCallback =
+      vtkSmartPointer<vtkCallbackCommand>::New();
   LogScaleCallback->SetCallback(logScaleClickedCallbackFunc);
   LogScaleCallback->SetClientData(&ccdata);
-  vtkSMIntVectorProperty *logScaleProp =
-    vtkSMIntVectorProperty::SafeDownCast(lutProxy->GetProperty("UseLogScale"));
+  vtkSMIntVectorProperty *logScaleProp = vtkSMIntVectorProperty::SafeDownCast(
+      lutProxy->GetProperty("UseLogScale"));
   if (logScaleProp)
     logScaleProp->AddObserver(vtkCommand::ModifiedEvent, LogScaleCallback);
 }
@@ -334,54 +314,68 @@ void ColorUpdater::observeColorScaleEdited(pqPipelineRepresentation *repr, Color
  * lookup table. Note that this goes in the opposite direction than
  * most if not all of the updates made by the ColorUpdater.
  *
- * @param caller the proxy object that calls this (or the callback has been set to it with AddObserver
+ * @param caller the proxy object that calls this (or the callback has been set
+ *to it with AddObserver
  * @param eventID vtkCommand event ID for callbacks, not used here
  *
- * @param clientData expects a ColorCallBackData struct that has the ColorUpdater object which set 
- * the callback, and ColorSelectionWidget object of this VSI window. Never use this method with
+ * @param clientData expects a ColorCallBackData struct that has the
+ *ColorUpdater object which set
+ * the callback, and ColorSelectionWidget object of this VSI window. Never use
+ *this method with
  * different data.
  *
  * @param callData callback specific data which takes different forms
  * depending on events, not used here.
  */
-void ColorUpdater::colorScaleEditedCallbackFunc(vtkObject *caller, long unsigned int eventID,
-                                                void *clientData, void *callData)
-{
+void ColorUpdater::colorScaleEditedCallbackFunc(vtkObject *caller,
+                                                long unsigned int eventID,
+                                                void *clientData,
+                                                void *callData) {
   UNUSED_ARG(eventID);
   UNUSED_ARG(callData);
 
-  // this won't help much. You must make sure that clientData is a proper ColorCallBackData struct
-  ColorCallbackData *data = static_cast<ColorCallbackData*>(clientData);
-  if (!data){
+  // this won't help much. You must make sure that clientData is a proper
+  // ColorCallBackData struct
+  ColorCallbackData *data = static_cast<ColorCallbackData *>(clientData);
+  if (!data) {
     return;
   }
 
   // a pseudo-this
   ColorUpdater *pThis = data->colorUpdater;
-  if (!pThis){
+  if (!pThis) {
     return;
   }
 
   ColorSelectionWidget *csel = data->csel;
-  if (!csel){
+  if (!csel) {
     return;
   }
 
   // This means that either
   //
-  // A) the user clicked on the auto-scale check box of the ColorSelectionWidget.
-  // That will change color properties of the ParaQ and trigger this callback. This condition
-  // prevents the callback from ruining the state of the ColorSelectionWidget (which is just
-  // being set by the user and we do not want to update programmatically in this case).
+  // A) the user clicked on the auto-scale check box of the
+  // ColorSelectionWidget.
+  // That will change color properties of the ParaQ and trigger this callback.
+  // This condition
+  // prevents the callback from ruining the state of the ColorSelectionWidget
+  // (which is just
+  // being set by the user and we do not want to update programmatically in this
+  // case).
   //
-  // B) We are in the middle of an operation where we don't want callbacks to update the
-  // color map (for example when switching views or doing several view updates in a row)
-  if (csel->inProcessUserRequestedAutoScale() || csel->isIgnoringColorCallbacks() || csel->isColorScaleLocked() ) {
+  // B) We are in the middle of an operation where we don't want callbacks to
+  // update the
+  // color map (for example when switching views or doing several view updates
+  // in a row)
+  if (csel->inProcessUserRequestedAutoScale() ||
+      csel->isIgnoringColorCallbacks() || csel->isColorScaleLocked()) {
     return;
   }
 
-  // This vector has 4 values per color definition: data value (bin limit) + 3 R-G-B coordinates
-  vtkSMDoubleVectorProperty *RGBPoints = vtkSMDoubleVectorProperty::SafeDownCast(caller);
+  // This vector has 4 values per color definition: data value (bin limit) + 3
+  // R-G-B coordinates
+  vtkSMDoubleVectorProperty *RGBPoints =
+      vtkSMDoubleVectorProperty::SafeDownCast(caller);
   if (!RGBPoints)
     return;
 
@@ -394,11 +388,10 @@ void ColorUpdater::colorScaleEditedCallbackFunc(vtkObject *caller, long unsigned
     return;
 
   double newMin = elems[0];
-  double newMax = elems[noe-subtract];
+  double newMax = elems[noe - subtract];
 
   if ((std::fabs(newMin - csel->getMinRange()) > 1e-14) ||
-      (std::fabs(csel->getMaxRange() - newMax) > 1e-14)
-      ) {
+      (std::fabs(csel->getMaxRange() - newMax) > 1e-14)) {
     pThis->m_minScale = newMin;
     pThis->m_maxScale = newMax;
     csel->setMinMax(pThis->m_minScale, pThis->m_maxScale);
@@ -431,31 +424,33 @@ void ColorUpdater::colorScaleEditedCallbackFunc(vtkObject *caller, long unsigned
  * @param callData callback specific data which takes different forms
  * depending on events, not used here.
  */
-void ColorUpdater::logScaleClickedCallbackFunc(vtkObject *caller, long unsigned int eventID,
-                                                void *clientData, void *callData)
-{
+void ColorUpdater::logScaleClickedCallbackFunc(vtkObject *caller,
+                                               long unsigned int eventID,
+                                               void *clientData,
+                                               void *callData) {
   UNUSED_ARG(eventID);
   UNUSED_ARG(callData);
 
   // this won't help much if you pass a wrong type.
-  ColorCallbackData *data = static_cast<ColorCallbackData*>(clientData);
-  if (!data){
+  ColorCallbackData *data = static_cast<ColorCallbackData *>(clientData);
+  if (!data) {
     return;
   }
 
   // pseudo-this
   ColorUpdater *pThis = data->colorUpdater;
-  if (!pThis){
+  if (!pThis) {
     return;
   }
 
   ColorSelectionWidget *csel = data->csel;
-  if (!csel){
+  if (!csel) {
     return;
   }
 
   // A single element int vector which actually contains a 0/1 value
-  vtkSMIntVectorProperty *useLogProp = vtkSMIntVectorProperty::SafeDownCast(caller);
+  vtkSMIntVectorProperty *useLogProp =
+      vtkSMIntVectorProperty::SafeDownCast(caller);
   if (!useLogProp)
     return;
 
@@ -472,4 +467,3 @@ void ColorUpdater::logScaleClickedCallbackFunc(vtkObject *caller, long unsigned
 } // SimpleGui
 } // Vates
 } // Mantid
-
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
index 8d8655bb35740cd0a59755d49130f8b47fa69e1d..31cf0cb84205ba7b13c884a26cca2a9d3389cfff 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/MultisliceView.cpp
@@ -31,104 +31,81 @@
 using namespace Mantid::Geometry;
 using namespace MantidQt::SliceViewer;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-
-static void GetOrientations(vtkSMSourceProxy* producer, vtkVector3d sliceNormals[3])
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+
+static void GetOrientations(vtkSMSourceProxy *producer,
+                            vtkVector3d sliceNormals[3]) {
   bool isvalid = false;
   vtkTuple<double, 16> cobm =
       pqModelTransformSupportBehavior::getChangeOfBasisMatrix(producer, 0,
                                                               &isvalid);
-  if (isvalid)
-    {
+  if (isvalid) {
     vtkNew<vtkMatrix4x4> changeOfBasisMatrix;
     std::copy(&cobm[0], &cobm[0] + 16, &changeOfBasisMatrix->Element[0][0]);
     vtkVector3d axisBases[3];
     vtkPVChangeOfBasisHelper::GetBasisVectors(changeOfBasisMatrix.GetPointer(),
-      axisBases[0], axisBases[1], axisBases[2]);
-    for (int cc=0; cc < 3; cc++)
-      {
-      sliceNormals[cc] = axisBases[(cc+1)%3].Cross(axisBases[(cc+2)%3]);
+                                              axisBases[0], axisBases[1],
+                                              axisBases[2]);
+    for (int cc = 0; cc < 3; cc++) {
+      sliceNormals[cc] = axisBases[(cc + 1) % 3].Cross(axisBases[(cc + 2) % 3]);
       sliceNormals[cc].Normalize();
-      }
     }
-  else
-    {
+  } else {
     sliceNormals[0] = vtkVector3d(1, 0, 0);
     sliceNormals[1] = vtkVector3d(0, 1, 0);
     sliceNormals[2] = vtkVector3d(0, 0, 1);
-    }
+  }
 }
 
-MultiSliceView::MultiSliceView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager)
-{
+MultiSliceView::MultiSliceView(QWidget *parent,
+                               RebinnedSourcesManager *rebinnedSourcesManager)
+    : ViewBase(parent, rebinnedSourcesManager) {
   this->m_ui.setupUi(this);
-  pqRenderView *tmp = this->createRenderView(this->m_ui.renderFrame,
-                                             QString("MultiSlice"));
+  pqRenderView *tmp =
+      this->createRenderView(this->m_ui.renderFrame, QString("MultiSlice"));
   this->m_mainView = qobject_cast<pqMultiSliceView *>(tmp);
   QObject::connect(this->m_mainView,
-                   SIGNAL(sliceClicked(int, double, int, int)),
-                   this,
-                   SLOT(checkSliceClicked(int,double,int,int)));
+                   SIGNAL(sliceClicked(int, double, int, int)), this,
+                   SLOT(checkSliceClicked(int, double, int, int)));
 }
 
-MultiSliceView::~MultiSliceView()
-{
-}
+MultiSliceView::~MultiSliceView() {}
 
-void MultiSliceView::destroyView()
-{
+void MultiSliceView::destroyView() {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   builder->destroy(this->m_mainView);
 }
 
-pqRenderView* MultiSliceView::getView()
-{
-  return qobject_cast<pqRenderView*>(this->m_mainView.data());
+pqRenderView *MultiSliceView::getView() {
+  return qobject_cast<pqRenderView *>(this->m_mainView.data());
 }
 
-
-void MultiSliceView::setupData()
-{
+void MultiSliceView::setupData() {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
 
   // Make sure that origsrc exists
-  if (this->origSrc)
-  {
-    pqDataRepresentation *drep = builder->createDataRepresentation(\
-    this->origSrc->getOutputPort(0), this->m_mainView);
+  if (this->origSrc) {
+    pqDataRepresentation *drep = builder->createDataRepresentation(
+        this->origSrc->getOutputPort(0), this->m_mainView);
     vtkSMPropertyHelper(drep->getProxy(), "Representation").Set("Slices");
     drep->getProxy()->UpdateVTKObjects();
   }
 }
 
-void MultiSliceView::render()
-{
+void MultiSliceView::render() {
   this->origSrc = pqActiveObjects::instance().activeSource();
   this->checkSliceViewCompat();
   this->setupData();
   this->resetDisplay();
 }
 
-void MultiSliceView::renderAll()
-{
-  this->m_mainView->render();
-}
+void MultiSliceView::renderAll() { this->m_mainView->render(); }
 
-void MultiSliceView::resetDisplay()
-{
-  this->m_mainView->resetDisplay();
-}
+void MultiSliceView::resetDisplay() { this->m_mainView->resetDisplay(); }
 
-void MultiSliceView::resetCamera()
-{
-  this->m_mainView->resetCamera();
-}
+void MultiSliceView::resetCamera() { this->m_mainView->resetCamera(); }
 
 /**
  * This function checks the signal coming from the MultiSliceView when a slice
@@ -140,32 +117,29 @@ void MultiSliceView::resetCamera()
  * @param modifier : which modifier key is being used
  */
 void MultiSliceView::checkSliceClicked(int axisIndex, double sliceOffsetOnAxis,
-                                       int button, int modifier)
-{
+                                       int button, int modifier) {
   if (modifier == vtkContextMouseEvent::SHIFT_MODIFIER &&
       (button == vtkContextMouseEvent::LEFT_BUTTON ||
-       button == vtkContextMouseEvent::RIGHT_BUTTON))
-  {
+       button == vtkContextMouseEvent::RIGHT_BUTTON)) {
     this->showCutInSliceViewer(axisIndex, sliceOffsetOnAxis);
   }
 }
 
 /**
- * This function checks the sources for the WorkspaceName property. If not found,
+ * This function checks the sources for the WorkspaceName property. If not
+ * found,
  * the ability to show a given cut in the SliceViewer will be deactivated.
  */
-void MultiSliceView::checkSliceViewCompat()
-{
+void MultiSliceView::checkSliceViewCompat() {
   QString wsName = this->getWorkspaceName();
-  if (wsName.isEmpty())
-  {
+  if (wsName.isEmpty()) {
     QObject::disconnect(this->m_mainView, 0, this, 0);
   }
 }
-  
-void MultiSliceView::changedSlicePoint(Mantid::Kernel::VMD selectedPoint)
-{
-  vtkSMPropertyHelper(this->m_mainView->getProxy(),"XSlicesValues").Set(selectedPoint[0]);
+
+void MultiSliceView::changedSlicePoint(Mantid::Kernel::VMD selectedPoint) {
+  vtkSMPropertyHelper(this->m_mainView->getProxy(), "XSlicesValues")
+      .Set(selectedPoint[0]);
   this->m_mainView->getProxy()->UpdateVTKObjects();
   this->m_mainView->render();
 }
@@ -179,22 +153,20 @@ void MultiSliceView::changedSlicePoint(Mantid::Kernel::VMD selectedPoint)
  * @param sliceOffsetOnAxis position of the slice along given axis
  */
 void MultiSliceView::showCutInSliceViewer(int axisIndex,
-                                          double sliceOffsetOnAxis)
-{
+                                          double sliceOffsetOnAxis) {
   // Get the associated workspace name
   QString wsName = this->getWorkspaceName();
 
   // Have to jump through some hoops since a rebinner could be used.
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   QList<pqPipelineSource *> srcs = smModel->findItems<pqPipelineSource *>();
   pqPipelineSource *src1 = NULL;
   pqPipelineSource *src2 = NULL;
-  foreach (pqPipelineSource *src, srcs)
-  {
+  foreach (pqPipelineSource *src, srcs) {
     const QString name(src->getProxy()->GetXMLName());
 
-    if (name.contains("ScaleWorkspace"))
-    {
+    if (name.contains("ScaleWorkspace")) {
       src2 = src;
     }
   }
@@ -202,26 +174,21 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
   src1 = smModel->getItemAtIndex<pqPipelineSource *>(0);
 
   // Get the current dataset characteristics
-  const char *inGeomXML = vtkSMPropertyHelper(src1->getProxy(),
-                                             "InputGeometryXML").GetAsString();
+  const char *inGeomXML =
+      vtkSMPropertyHelper(src1->getProxy(), "InputGeometryXML").GetAsString();
   // Check for timesteps and insert the value into the XML if necessary
   std::string geomXML;
-  if ( this->srcHasTimeSteps(src1) )
-  {
+  if (this->srcHasTimeSteps(src1)) {
     GeometryParser parser(inGeomXML);
     geomXML = parser.addTDimValue(this->getCurrentTimeStep());
-  }
-  else
-  {
+  } else {
     geomXML = std::string(inGeomXML);
   }
 
-  if (NULL != src2)
-  {
+  if (NULL != src2) {
     // Need to see if scaling is applied to axis
     QString scalingProperty("Scaling Factor");
-    switch (axisIndex)
-    {
+    switch (axisIndex) {
     case 0:
       scalingProperty.prepend("X ");
       break;
@@ -235,19 +202,20 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
       break;
     }
 
-    std::vector<double> scaling = vtkSMPropertyHelper(src2->getProxy(),
-                                                      scalingProperty.toAscii().constData(),
-                                                      true).GetDoubleArray();
+    std::vector<double> scaling =
+        vtkSMPropertyHelper(src2->getProxy(),
+                            scalingProperty.toAscii().constData(),
+                            true).GetDoubleArray();
 
-    if (!scaling.empty())
-    {
+    if (!scaling.empty()) {
       sliceOffsetOnAxis /= scaling[0];
     }
   }
 
   vtkVector3d sliceNormals[3];
-  GetOrientations(vtkSMSourceProxy::SafeDownCast(src1->getProxy()), sliceNormals);
-  vtkVector3d& orient = sliceNormals[axisIndex];
+  GetOrientations(vtkSMSourceProxy::SafeDownCast(src1->getProxy()),
+                  sliceNormals);
+  vtkVector3d &orient = sliceNormals[axisIndex];
 
   // Construct origin vector from orientation vector
   double origin[3];
@@ -265,20 +233,23 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
   QString titleAddition = "";
 
   // Use the WidgetFactory to create the slice viewer window
-  SliceViewerWindow *w = MantidQt::Factory::WidgetFactory::Instance()->createSliceViewerWindow(wsName, titleAddition);
-  try
-  {
+  SliceViewerWindow *w =
+      MantidQt::Factory::WidgetFactory::Instance()->createSliceViewerWindow(
+          wsName, titleAddition);
+  try {
     // Set the slice points, etc, using the XML definition of the plane function
-    w->getSlicer()->openFromXML( QString::fromStdString(rks.createXMLString()) );
+    w->getSlicer()->openFromXML(QString::fromStdString(rks.createXMLString()));
     w->show();
-    this->connect(w->getSlicer(), SIGNAL(changedSlicePoint(Mantid::Kernel::VMD)), SLOT(changedSlicePoint(Mantid::Kernel::VMD)));
-  }
-  catch (std::runtime_error & e)
-  {
-    QString message = "The slice could not be shown because of the following error:\n" + QString(e.what());
+    this->connect(w->getSlicer(),
+                  SIGNAL(changedSlicePoint(Mantid::Kernel::VMD)),
+                  SLOT(changedSlicePoint(Mantid::Kernel::VMD)));
+  } catch (std::runtime_error &e) {
+    QString message =
+        "The slice could not be shown because of the following error:\n" +
+        QString(e.what());
     QMessageBox::warning(this, tr("MantidPlot"),
-                         tr(message.toAscii().constData()),
-                       QMessageBox::Ok, QMessageBox::Ok);
+                         tr(message.toAscii().constData()), QMessageBox::Ok,
+                         QMessageBox::Ok);
     delete w;
   }
 }
@@ -288,8 +259,7 @@ void MultiSliceView::showCutInSliceViewer(int axisIndex,
  * closed. The function is a no-op (except for factory creation) when no
  * SliceViewer windows were requested.
  */
-void MultiSliceView::closeSubWindows()
-{
+void MultiSliceView::closeSubWindows() {
   MantidQt::Factory::WidgetFactory::Instance()->closeAllSliceViewerWindows();
 }
 
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTabWidget.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTabWidget.cpp
index 8fae8b0b6fc3925ece57ebdc9a17a34d40eddfaa..8c7bbfb057ecca28b780b15dde4b26de30c7c39e 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTabWidget.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTabWidget.cpp
@@ -66,9 +66,9 @@ void PeaksTabWidget::addNewTab(Mantid::API::IPeaksWorkspace_sptr peaksWorkspace,
 
   // Connect to the sort functionality of the widget
   QObject::connect(widget, SIGNAL(sortPeaks(const std::string &, const bool,
-                                           Mantid::API::IPeaksWorkspace_sptr)),
+                                            Mantid::API::IPeaksWorkspace_sptr)),
                    this, SIGNAL(sortPeaks(const std::string &, const bool,
-                                         Mantid::API::IPeaksWorkspace_sptr)));
+                                          Mantid::API::IPeaksWorkspace_sptr)));
 
   // Add as a new tab
   m_tabWidget->addTab(widget, QString(tabName.c_str()));
@@ -90,15 +90,18 @@ void PeaksTabWidget::onZoomToPeak(Mantid::API::IPeaksWorkspace_sptr ws,
  * @param colors The color of the tabs
  */
 void PeaksTabWidget::updateTabs(
-    std::map<std::string, std::vector<bool>> visiblePeaks, std::map<std::string, QColor> colors) {
+    std::map<std::string, std::vector<bool>> visiblePeaks,
+    std::map<std::string, QColor> colors) {
   // Iterate over all tabs
   for (int i = 0; i < m_tabWidget->count(); i++) {
     QString label = m_tabWidget->tabText(i);
 
     // Check if the peaks workspace still exists, if it does update, else delete
     // the tab.
-    if (visiblePeaks.count(label.toStdString()) > 0 && colors.count(label.toStdString()) > 0) {
-      updateTab(visiblePeaks[label.toStdString()], colors[label.toStdString()], i);
+    if (visiblePeaks.count(label.toStdString()) > 0 &&
+        colors.count(label.toStdString()) > 0) {
+      updateTab(visiblePeaks[label.toStdString()], colors[label.toStdString()],
+                i);
     } else {
       m_tabWidget->removeTab(i);
     }
@@ -111,9 +114,9 @@ void PeaksTabWidget::updateTabs(
  * @param color
  * @param index The tab index.
  */
-void PeaksTabWidget::updateTab(std::vector<bool> visiblePeaks, QColor color, int index) {
-  PeaksWidget *widget =
-      qobject_cast<PeaksWidget *>(m_tabWidget->widget(index));
+void PeaksTabWidget::updateTab(std::vector<bool> visiblePeaks, QColor color,
+                               int index) {
+  PeaksWidget *widget = qobject_cast<PeaksWidget *>(m_tabWidget->widget(index));
   widget->updateModel(visiblePeaks);
   m_tabWidget->tabBar()->setTabTextColor(index, color);
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
index b082508860358a7483ca4ef00b8aa0a3dee10d14..e6a938464d4a18ff5e24302bc3f405f6ed72f2d4 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksTableControllerVsi.cpp
@@ -73,7 +73,8 @@ PeaksTableControllerVsi::PeaksTableControllerVsi(
     boost::shared_ptr<CameraManager> cameraManager, QWidget *parent)
     : QWidget(parent), m_cameraManager(cameraManager),
       m_presenter(new Mantid::VATES::CompositePeaksPresenterVsi()),
-      m_peaksTabWidget(NULL), m_peakMarker(NULL), m_coordinateSystem(Mantid::Kernel::SpecialCoordinateSystem::QLab) {
+      m_peaksTabWidget(NULL), m_peakMarker(NULL),
+      m_coordinateSystem(Mantid::Kernel::SpecialCoordinateSystem::QLab) {
   m_peakTransformSelector.registerCandidate(
       boost::make_shared<Mantid::Geometry::PeakTransformHKLFactory>());
   m_peakTransformSelector.registerCandidate(
@@ -410,7 +411,8 @@ void PeaksTableControllerVsi::onZoomToPeak(
     double radius;
     Mantid::Kernel::V3D position;
 
-    m_presenter->getPeaksInfo(peaksWorkspace, row, position, radius, m_coordinateSystem);
+    m_presenter->getPeaksInfo(peaksWorkspace, row, position, radius,
+                              m_coordinateSystem);
 
     // Reset camera
     m_cameraManager->setCameraToPeak(position[0], position[1], position[2],
@@ -607,41 +609,38 @@ void PeaksTableControllerVsi::onPeaksSorted(
  */
 void PeaksTableControllerVsi::setPeakSourceColorToDefault() {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
-  QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
+  QList<pqPipelineSource *> sources =
+      smModel->findItems<pqPipelineSource *>(server);
   for (auto src = sources.begin(); src != sources.end(); ++src) {
 
     std::string xmlName((*src)->getProxy()->GetXMLName());
     if ((xmlName.find("Peaks Source") != std::string::npos)) {
-        double red = 1.0;
-        double green = 1.0;
-        double blue = 1.0;
-
-        pqDataRepresentation *rep =
-            (*src)
-                ->getRepresentation(pqActiveObjects::instance().activeView());
-        if (!rep)
-        {
-          continue;
-        }
-          pqPipelineRepresentation *pipelineRepresentation =
-              qobject_cast<pqPipelineRepresentation *>(rep);
-        if (!pipelineRepresentation)
-        {
-          continue;
-        }
-        pipelineRepresentation->getProxy()->UpdatePropertyInformation();
-
-        vtkSMDoubleVectorProperty *prop =
-            vtkSMDoubleVectorProperty::SafeDownCast(
-                pipelineRepresentation->getProxy()->GetProperty(
-                    "AmbientColor"));
-        prop->SetElement(0, red);
-        prop->SetElement(1, green);
-        prop->SetElement(2, blue);
-        pipelineRepresentation->getProxy()->UpdateVTKObjects();
-        pipelineRepresentation->updateHelperProxies();
-        pqActiveObjects::instance().activeView()->forceRender();
+      double red = 1.0;
+      double green = 1.0;
+      double blue = 1.0;
+
+      pqDataRepresentation *rep =
+          (*src)->getRepresentation(pqActiveObjects::instance().activeView());
+      if (!rep) {
+        continue;
+      }
+      pqPipelineRepresentation *pipelineRepresentation =
+          qobject_cast<pqPipelineRepresentation *>(rep);
+      if (!pipelineRepresentation) {
+        continue;
+      }
+      pipelineRepresentation->getProxy()->UpdatePropertyInformation();
+
+      vtkSMDoubleVectorProperty *prop = vtkSMDoubleVectorProperty::SafeDownCast(
+          pipelineRepresentation->getProxy()->GetProperty("AmbientColor"));
+      prop->SetElement(0, red);
+      prop->SetElement(1, green);
+      prop->SetElement(2, blue);
+      pipelineRepresentation->getProxy()->UpdateVTKObjects();
+      pipelineRepresentation->updateHelperProxies();
+      pqActiveObjects::instance().activeView()->forceRender();
     }
   }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
index e70f9497873d16d93e8dd085eebdfdf5fe026842..a3059e7b04757a9dc64043450777a2dc5b528b1a 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/PeaksWidget.cpp
@@ -21,7 +21,8 @@ Constructor
 */
 PeaksWidget::PeaksWidget(Mantid::API::IPeaksWorkspace_sptr ws,
                          const std::string &coordinateSystem, QWidget *parent)
-    : QWidget(parent), m_ws(ws), m_coordinateSystem(coordinateSystem), m_originalTableWidth(1) {
+    : QWidget(parent), m_ws(ws), m_coordinateSystem(coordinateSystem),
+      m_originalTableWidth(1) {
   ui.setupUi(this);
 }
 
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
index 611150b1d375a770586d86ab8e7ce69608a179d5..2b9772410455b7693c23bdb0df491f38c09fe1da 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/RebinAlgorithmDialogProvider.cpp
@@ -9,12 +9,12 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 #include <pqPipelineSource.h>
 #include <vtkSMPropertyHelper.h>
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <string>
@@ -27,212 +27,198 @@
 
 using namespace MantidQt::MantidWidgets;
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-    namespace
-    {
-      Mantid::Kernel::Logger g_log("RebinAlgorithmDialogProvider");
-    }
-
-      const size_t RebinAlgorithmDialogProvider::BinCutOffValue = 50;
+namespace {
+Mantid::Kernel::Logger g_log("RebinAlgorithmDialogProvider");
+}
 
-      RebinAlgorithmDialogProvider::RebinAlgorithmDialogProvider(QWidget* parent) : 
-                                                    m_lblInputWorkspace("InputWorkspace"),
-                                                    m_lblOutputWorkspace("OutputWorkspace"),
-                                                    m_parent(parent)
-      {
-      }
+const size_t RebinAlgorithmDialogProvider::BinCutOffValue = 50;
+
+RebinAlgorithmDialogProvider::RebinAlgorithmDialogProvider(QWidget *parent)
+    : m_lblInputWorkspace("InputWorkspace"),
+      m_lblOutputWorkspace("OutputWorkspace"), m_parent(parent) {}
+
+RebinAlgorithmDialogProvider::~RebinAlgorithmDialogProvider() {}
+
+/**
+ * Show a Bin MD dialog for rebinning in the VSI
+ * @param inputWorkspace The name of the input workspace.
+ * @param outputWorkspace The name of the output workspace.
+ * @param algorithmType The type of algorithm which is to be used for rebinning.
+ */
+void RebinAlgorithmDialogProvider::showDialog(std::string inputWorkspace,
+                                              std::string outputWorkspace,
+                                              std::string algorithmType) {
+  if (inputWorkspace.empty() || outputWorkspace.empty()) {
+    return;
+  }
 
-      RebinAlgorithmDialogProvider::~RebinAlgorithmDialogProvider()
-      {
-      }
+  // Create the algorithm
+  Mantid::API::IAlgorithm_sptr algorithm = createAlgorithm(algorithmType, 1);
 
-      /**
-       * Show a Bin MD dialog for rebinning in the VSI
-       * @param inputWorkspace The name of the input workspace.
-       * @param outputWorkspace The name of the output workspace.
-       * @param algorithmType The type of algorithm which is to be used for rebinning.
-       */
-      void RebinAlgorithmDialogProvider::showDialog(std::string inputWorkspace, std::string outputWorkspace, std::string algorithmType)
-      {
-        if (inputWorkspace.empty() || outputWorkspace.empty())
-        {
-          return;
-        }
-
-        // Create the algorithm
-        Mantid::API::IAlgorithm_sptr algorithm = createAlgorithm(algorithmType, 1);
-
-        if (!algorithm)
-        {
-          return;
-        }
-
-        MantidQt::API::AlgorithmDialog* rebinDialog = createDialog(algorithm, inputWorkspace, outputWorkspace, algorithmType);
-
-        rebinDialog->show();
-        rebinDialog->raise();
-        rebinDialog->activateWindow();
-      }
+  if (!algorithm) {
+    return;
+  }
 
-      /**
-       * Gets the event workspace
-       * @param workspaceName The name of the input workspace.
-       * @returns A pointer to the current event workspace
-       */
-      Mantid::API::IMDEventWorkspace_sptr RebinAlgorithmDialogProvider::getWorkspace(const std::string& workspaceName)
-      {
-        Mantid::API::IMDEventWorkspace_sptr eventWorkspace;
+  MantidQt::API::AlgorithmDialog *rebinDialog =
+      createDialog(algorithm, inputWorkspace, outputWorkspace, algorithmType);
 
+  rebinDialog->show();
+  rebinDialog->raise();
+  rebinDialog->activateWindow();
+}
 
-        if (!m_adsWorkspaceProvider.canProvideWorkspace(workspaceName))
-        {
-          return eventWorkspace;
-        }
+/**
+ * Gets the event workspace
+ * @param workspaceName The name of the input workspace.
+ * @returns A pointer to the current event workspace
+ */
+Mantid::API::IMDEventWorkspace_sptr
+RebinAlgorithmDialogProvider::getWorkspace(const std::string &workspaceName) {
+  Mantid::API::IMDEventWorkspace_sptr eventWorkspace;
+
+  if (!m_adsWorkspaceProvider.canProvideWorkspace(workspaceName)) {
+    return eventWorkspace;
+  }
 
-        Mantid::API::Workspace_sptr workspace = m_adsWorkspaceProvider.fetchWorkspace(workspaceName);
+  Mantid::API::Workspace_sptr workspace =
+      m_adsWorkspaceProvider.fetchWorkspace(workspaceName);
 
-        // Make sure it is a and MDEvent
-        eventWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
+  // Make sure it is a and MDEvent
+  eventWorkspace =
+      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
 
-        return eventWorkspace;
-      }
+  return eventWorkspace;
+}
 
-      /**
-       * Creates an algorithm
-       * @param algorithmName The name of the algorithm.
-       * @param version The version of the algorithm
-       * @returns A pointer to the newly created algorithm.
-       */
-      Mantid::API::IAlgorithm_sptr RebinAlgorithmDialogProvider::createAlgorithm(const std::string& algorithmName, int version)
-      {
-        Mantid::API::IAlgorithm_sptr alg;
-        try
-        {
-          alg = Mantid::API::AlgorithmManager::Instance().create(algorithmName,version);
-        }
-        catch(...)
-        {
-          g_log.warning() << "Error: " << algorithmName << " was not created. Version number is " << version;
-        }
-        return alg;
-      }
+/**
+ * Creates an algorithm
+ * @param algorithmName The name of the algorithm.
+ * @param version The version of the algorithm
+ * @returns A pointer to the newly created algorithm.
+ */
+Mantid::API::IAlgorithm_sptr
+RebinAlgorithmDialogProvider::createAlgorithm(const std::string &algorithmName,
+                                              int version) {
+  Mantid::API::IAlgorithm_sptr alg;
+  try {
+    alg = Mantid::API::AlgorithmManager::Instance().create(algorithmName,
+                                                           version);
+  } catch (...) {
+    g_log.warning() << "Error: " << algorithmName
+                    << " was not created. Version number is " << version;
+  }
+  return alg;
+}
 
-      /**
-       * Creates the dialog for the algorithm (see InterfaceManager).
-       * @param algorithm The algorithm which is to be used.
-       * @param inputWorkspace The name of the input workspace.
-       * @param outputWorkspace The name of the output workspace.
-       * @param algorithmType The algorithm type.
-       * @returns The algorithm dialog
-       */
-      MantidQt::API::AlgorithmDialog* RebinAlgorithmDialogProvider::createDialog(Mantid::API::IAlgorithm_sptr algorithm,
-                                                                 const std::string& inputWorkspace,
-                                                                 const std::string& outputWorkspace,
-                                                                 const std::string& algorithmType)
-      {
-        QHash<QString, QString> presets;
-       //Check if a workspace is selected in the dock and set this as a preference for the input workspace
-        //This is an optional message displayed at the top of the GUI.
-        QString optional_msg(algorithm->summary().c_str());
-
-        MantidQt::API::AlgorithmDialog* dialog = NULL;
-
-        
-        MantidQt::API::InterfaceManager interfaceManager;
-        presets.insert(m_lblInputWorkspace, QString::fromStdString(inputWorkspace));
-        presets.insert(m_lblOutputWorkspace, QString::fromStdString(outputWorkspace));
-
-        dialog = interfaceManager.createDialogFromName(QString::fromStdString(algorithmType), -1, m_parent, false, presets);
-
-        // The parent so that the dialog appears on top of it
-        dialog->setParent(m_parent);
-        dialog->setAttribute(Qt::WA_DeleteOnClose, true);
-
-        // Set the QDialog window flags to ensure the dialog ends up on top
-        Qt::WindowFlags flags = 0;
-        flags |= Qt::Dialog;
-        flags |= Qt::WindowContextHelpButtonHint;
-        dialog->setWindowFlags(flags);
-
-        if (SlicingAlgorithmDialog * slicingDialog = dynamic_cast<SlicingAlgorithmDialog *>(dialog))
-        {
-    
-          slicingDialog->customiseLayoutForVsi(inputWorkspace);
-
-          // Setup the values of the axis dimensions
-          setAxisDimensions(slicingDialog, inputWorkspace);
-        }
-
-        return dialog;
-      }
+/**
+ * Creates the dialog for the algorithm (see InterfaceManager).
+ * @param algorithm The algorithm which is to be used.
+ * @param inputWorkspace The name of the input workspace.
+ * @param outputWorkspace The name of the output workspace.
+ * @param algorithmType The algorithm type.
+ * @returns The algorithm dialog
+ */
+MantidQt::API::AlgorithmDialog *RebinAlgorithmDialogProvider::createDialog(
+    Mantid::API::IAlgorithm_sptr algorithm, const std::string &inputWorkspace,
+    const std::string &outputWorkspace, const std::string &algorithmType) {
+  QHash<QString, QString> presets;
+  // Check if a workspace is selected in the dock and set this as a preference
+  // for the input workspace
+  // This is an optional message displayed at the top of the GUI.
+  QString optional_msg(algorithm->summary().c_str());
+
+  MantidQt::API::AlgorithmDialog *dialog = NULL;
+
+  MantidQt::API::InterfaceManager interfaceManager;
+  presets.insert(m_lblInputWorkspace, QString::fromStdString(inputWorkspace));
+  presets.insert(m_lblOutputWorkspace, QString::fromStdString(outputWorkspace));
+
+  dialog = interfaceManager.createDialogFromName(
+      QString::fromStdString(algorithmType), -1, m_parent, false, presets);
+
+  // The parent so that the dialog appears on top of it
+  dialog->setParent(m_parent);
+  dialog->setAttribute(Qt::WA_DeleteOnClose, true);
+
+  // Set the QDialog window flags to ensure the dialog ends up on top
+  Qt::WindowFlags flags = 0;
+  flags |= Qt::Dialog;
+  flags |= Qt::WindowContextHelpButtonHint;
+  dialog->setWindowFlags(flags);
+
+  if (SlicingAlgorithmDialog *slicingDialog =
+          dynamic_cast<SlicingAlgorithmDialog *>(dialog)) {
+
+    slicingDialog->customiseLayoutForVsi(inputWorkspace);
+
+    // Setup the values of the axis dimensions
+    setAxisDimensions(slicingDialog, inputWorkspace);
+  }
 
+  return dialog;
+}
 
-      /**
-       * Resets the aligned dimensions properties in a SlicingAlgorithmDialog.
-       * @param dialog A pointer to the SliceMDDialog
-       * @param inputWorkspace The name of the input workspace.
-       */
-      void RebinAlgorithmDialogProvider::setAxisDimensions(MantidQt::MantidWidgets::SlicingAlgorithmDialog* dialog, std::string inputWorkspace)
-      {
-        Mantid::API::IMDEventWorkspace_sptr  eventWorkspace = getWorkspace(inputWorkspace);
-
-        size_t nDimensions = eventWorkspace->getNumDims();
-
-        for (size_t index = 0; index < nDimensions; ++index)
-        {
-          Mantid::Geometry::IMDDimension_const_sptr dim = eventWorkspace->getDimension(index);
-
-          std::string name = dim->getName();
-          std::string dimensionId = dim->getDimensionId();
-          coord_t minimum = dim->getMinimum();
-          coord_t maximum = dim->getMaximum();
-          size_t numberOfBins = dim->getNBins();
-
-          // Check the bins size
-          QString newNumberOfBins;
-          if (numberOfBins < BinCutOffValue && index < 3)
-          {
-            // Only do this for BinMD, it is too costly for SliceMD to have very large cuts
-            if (dynamic_cast<MantidQt::MantidWidgets::BinMDDialog *>(dialog))
-            {
-              newNumberOfBins = QString::number(static_cast<unsigned long long>(BinCutOffValue));
-            }
-            else
-            {
-              newNumberOfBins = QString::number(static_cast<unsigned long long>(numberOfBins));
-            }
-          }
-          else
-          {
-            newNumberOfBins = QString::number(static_cast<unsigned long long>(numberOfBins));
-          }
-
-          // Set the name
-          std::string identifier;
-          if (!name.empty())
-          {
-            identifier = name;
-          }
-          else
-          {
-            identifier = dimensionId;
-          }
-
-          // Check here if the set bins are OK
-          QString propertyValue = QString::fromStdString(identifier) + ","
-                                + QString::number(static_cast<float>(minimum)) + ","
-                                + QString::number(static_cast<float>(maximum)) + ","
-                                + newNumberOfBins;
-
-          dialog->resestAlignedDimProperty(index, propertyValue);
-        }
+/**
+ * Resets the aligned dimensions properties in a SlicingAlgorithmDialog.
+ * @param dialog A pointer to the SliceMDDialog
+ * @param inputWorkspace The name of the input workspace.
+ */
+void RebinAlgorithmDialogProvider::setAxisDimensions(
+    MantidQt::MantidWidgets::SlicingAlgorithmDialog *dialog,
+    std::string inputWorkspace) {
+  Mantid::API::IMDEventWorkspace_sptr eventWorkspace =
+      getWorkspace(inputWorkspace);
+
+  size_t nDimensions = eventWorkspace->getNumDims();
+
+  for (size_t index = 0; index < nDimensions; ++index) {
+    Mantid::Geometry::IMDDimension_const_sptr dim =
+        eventWorkspace->getDimension(index);
+
+    std::string name = dim->getName();
+    std::string dimensionId = dim->getDimensionId();
+    coord_t minimum = dim->getMinimum();
+    coord_t maximum = dim->getMaximum();
+    size_t numberOfBins = dim->getNBins();
+
+    // Check the bins size
+    QString newNumberOfBins;
+    if (numberOfBins < BinCutOffValue && index < 3) {
+      // Only do this for BinMD, it is too costly for SliceMD to have very large
+      // cuts
+      if (dynamic_cast<MantidQt::MantidWidgets::BinMDDialog *>(dialog)) {
+        newNumberOfBins =
+            QString::number(static_cast<unsigned long long>(BinCutOffValue));
+      } else {
+        newNumberOfBins =
+            QString::number(static_cast<unsigned long long>(numberOfBins));
       }
+    } else {
+      newNumberOfBins =
+          QString::number(static_cast<unsigned long long>(numberOfBins));
+    }
+
+    // Set the name
+    std::string identifier;
+    if (!name.empty()) {
+      identifier = name;
+    } else {
+      identifier = dimensionId;
     }
+
+    // Check here if the set bins are OK
+    QString propertyValue = QString::fromStdString(identifier) + "," +
+                            QString::number(static_cast<float>(minimum)) + "," +
+                            QString::number(static_cast<float>(maximum)) + "," +
+                            newNumberOfBins;
+
+    dialog->resestAlignedDimProperty(index, propertyValue);
   }
 }
+}
+}
+}
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
index 7336f92bd132c827b219bbd888561aa213029c23..0b127e5e0c1d1db956863094cc5ed1ff161bd837 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp
@@ -9,7 +9,7 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 #include <pqActiveObjects.h>
 #include <pqApplicationCore.h>
@@ -29,735 +29,729 @@
 #include <vtkSMProxyProperty.h>
 #include <vtkSMProxyListDomain.h>
 
-
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 #include <QList>
 #include "boost/shared_ptr.hpp"
 #include <Poco/ActiveResult.h>
 
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
+namespace {
+Mantid::Kernel::Logger g_log("RebinnedSourcesManager");
+}
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
+RebinnedSourcesManager::RebinnedSourcesManager(QWidget *parent)
+    : QWidget(parent), m_tempPostfix("_rebinned_vsi"), m_tempPrefix(""),
+      m_inputSource(NULL), m_rebinnedSource(NULL) {
+  observeAdd();
+  observeAfterReplace();
+  observePreDelete();
+}
 
-    namespace
-    {
-      Mantid::Kernel::Logger g_log("RebinnedSourcesManager");
+RebinnedSourcesManager::~RebinnedSourcesManager() {}
+
+/**
+ * Checks if a rebinned MDHisto workspace was added and invokes a replacement
+ * procedure
+ * @param workspaceName Name of the workspace.
+ * @param workspace A pointer to the added workspace.
+ */
+void RebinnedSourcesManager::addHandle(const std::string &workspaceName,
+                                       Mantid::API::Workspace_sptr workspace) {
+  // Check if the workspace which has experienced a change is being tracked in
+  // our buffer
+  if (m_newWorkspacePairBuffer.size() == 0) {
+    return;
+  }
+
+  std::string outputWorkspace = m_newWorkspacePairBuffer.begin()->second.first;
+
+  if (outputWorkspace == workspaceName) {
+    std::string sourceType;
+    Mantid::API::IMDEventWorkspace_sptr eventWorkspace =
+        boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
+    Mantid::API::IMDHistoWorkspace_sptr histoWorkspace =
+        boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
+
+    if (eventWorkspace) {
+      sourceType = "MDEW Source";
+    } else if (histoWorkspace) {
+      sourceType = "MDHW Source";
+    } else {
+      return;
     }
 
-      RebinnedSourcesManager::RebinnedSourcesManager(QWidget* parent) : QWidget(parent), m_tempPostfix("_rebinned_vsi"), m_tempPrefix(""), m_inputSource(NULL), m_rebinnedSource(NULL)
-      {
-        observeAdd();
-        observeAfterReplace();
-        observePreDelete();
-      }
+    emit switchSources(workspaceName, sourceType);
+  }
+}
 
-      RebinnedSourcesManager::~RebinnedSourcesManager()
-      {
-      }
+/**
+ * Catch the deletion of either the rebinned or the original workspace.
+ * @param wsName The name of the workspace.
+ */
+void RebinnedSourcesManager::preDeleteHandle(
+    const std::string &wsName,
+    const boost::shared_ptr<Mantid::API::Workspace>) {
+  // Check if the workspace which is to be deleted is a tracked rebinned
+  // workspace
+  std::vector<pqPipelineSource *> sources =
+      findAllRebinnedSourcesForWorkspace(wsName);
+
+  for (std::vector<pqPipelineSource *>::const_iterator it = sources.begin();
+       it != sources.end(); ++it) {
+    // Untrack the source
+    untrackWorkspaces(createKeyPairForSource(*it));
+
+    // Delete pipeline
+    removePipeline(*it);
+  }
+}
 
-      /**
-       * Checks if a rebinned MDHisto workspace was added and invokes a replacement procedure
-       * @param workspaceName Name of the workspace.
-       * @param workspace A pointer to the added workspace.
-       */
-      void RebinnedSourcesManager::addHandle(const std::string &workspaceName, Mantid::API::Workspace_sptr workspace)
-      {
-        // Check if the workspace which has experienced a change is being tracked in our buffer
-        if (m_newWorkspacePairBuffer.size() == 0)
-        {
-          return;
-        }
+/**
+ * Catch a change of a workspace
+ * @param workspaceName Name of the workspace.
+ * @param workspace A pointer to the added workspace.
+ */
+void RebinnedSourcesManager::afterReplaceHandle(
+    const std::string &workspaceName,
+    const boost::shared_ptr<Mantid::API::Workspace> workspace) {
+  addHandle(workspaceName, workspace);
+}
 
-        std::string outputWorkspace = m_newWorkspacePairBuffer.begin()->second.first;
-
-        if (outputWorkspace == workspaceName)
-        {
-          std::string sourceType;
-          Mantid::API::IMDEventWorkspace_sptr eventWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(workspace);
-          Mantid::API::IMDHistoWorkspace_sptr histoWorkspace = boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(workspace);
-
-          if(eventWorkspace)
-          {
-            sourceType = "MDEW Source";
-          }
-          else if(histoWorkspace)
-          {
-            sourceType = "MDHW Source";
-          }
-          else
-          {
-            return;
-          }
-
-          emit switchSources(workspaceName, sourceType);
-        }
-      }
-  
-      /**
-       * Catch the deletion of either the rebinned or the original workspace.
-       * @param wsName The name of the workspace.
-       */
-      void RebinnedSourcesManager::preDeleteHandle(const std::string &wsName, const boost::shared_ptr<Mantid::API::Workspace>)
-      {
-        // Check if the workspace which is to be deleted is a tracked rebinned workspace
-        std::vector<pqPipelineSource*> sources = findAllRebinnedSourcesForWorkspace(wsName);
-
-        for (std::vector<pqPipelineSource *>::const_iterator it = sources.begin(); it != sources.end(); ++it)
-        {
-          // Untrack the source
-          untrackWorkspaces(createKeyPairForSource(*it));
-
-          // Delete pipeline
-          removePipeline(*it);
-        }
-      }
+/**
+ * Check if the sources are valid.
+ * @param src The pipeline source.
+ * @param inputWorkspace Reference for the name of the input workspace.
+ * @param outputWorkspace Reference for the name of the output workspace.
+ * @param algorithmType The type of the algorithm which will be used to create
+ * the rebinned source.
+ */
+void RebinnedSourcesManager::checkSource(pqPipelineSource *src,
+                                         std::string &inputWorkspace,
+                                         std::string &outputWorkspace,
+                                         std::string algorithmType) {
+  pqPipelineSource *source = goToPipelineBeginning(src);
+
+  std::string workspaceName;
+  std::string workspaceType;
+
+  getWorkspaceInfo(source, workspaceName, workspaceType);
+
+  bool isHistoWorkspace =
+      workspaceType.find("MDHistoWorkspace") != std::string::npos;
+  bool isEventWorkspace =
+      workspaceType.find("MDEventWorkspace") != std::string::npos;
+
+  // Check if it is a Histo or Event workspace, if it is neither, then don't do
+  // anything
+  if (isHistoWorkspace || isEventWorkspace) {
+    processWorkspaceNames(inputWorkspace, outputWorkspace, source,
+                          workspaceName, algorithmType);
+  }
+}
 
-      /**
-       * Catch a change of a workspace
-       * @param workspaceName Name of the workspace.
-       * @param workspace A pointer to the added workspace.
-       */
-      void RebinnedSourcesManager::afterReplaceHandle(const std::string &workspaceName, const boost::shared_ptr<Mantid::API::Workspace> workspace)
-      {
-        addHandle(workspaceName, workspace);
-      }
+/**
+ * Get workspace name and type
+ * @param source The pipeline source.
+ * @param workspaceName Reference to workspace name.
+ * @param workspaceType Reference to workspace type.
+ */
+void RebinnedSourcesManager::getWorkspaceInfo(pqPipelineSource *source,
+                                              std::string &workspaceName,
+                                              std::string &workspaceType) {
+  // Make sure that the input source exists. Note that this can happen when
+  // there is no active view
+  if (!source) {
+    return;
+  }
 
-      /**
-       * Check if the sources are valid.
-       * @param src The pipeline source.
-       * @param inputWorkspace Reference for the name of the input workspace.
-       * @param outputWorkspace Reference for the name of the output workspace.
-       * @param algorithmType The type of the algorithm which will be used to create the rebinned source.
-       */
-      void RebinnedSourcesManager::checkSource(pqPipelineSource* src, std::string& inputWorkspace, std::string& outputWorkspace, std::string algorithmType)
-      {
-        pqPipelineSource* source = goToPipelineBeginning(src);
-
-        std::string workspaceName;
-        std::string workspaceType;
-
-        getWorkspaceInfo(source, workspaceName, workspaceType);
-
-        bool isHistoWorkspace = workspaceType.find("MDHistoWorkspace")!=std::string::npos;
-        bool isEventWorkspace = workspaceType.find("MDEventWorkspace")!=std::string::npos;
-
-        // Check if it is a Histo or Event workspace, if it is neither, then don't do anything
-        if (isHistoWorkspace || isEventWorkspace)
-        {
-          processWorkspaceNames(inputWorkspace, outputWorkspace, source, workspaceName, algorithmType);
-        }
-      }
+  // Update the source/filter
+  vtkSMProxy *proxy = source->getProxy();
+  proxy->UpdateVTKObjects();
+  proxy->UpdatePropertyInformation();
+  source->updatePipeline();
 
-      /**
-       * Get workspace name and type
-       * @param source The pipeline source.
-       * @param workspaceName Reference to workspace name.
-       * @param workspaceType Reference to workspace type.
-       */
-      void RebinnedSourcesManager::getWorkspaceInfo(pqPipelineSource* source, std::string& workspaceName, std::string& workspaceType)
-      {
-        // Make sure that the input source exists. Note that this can happen when there is no active view
-        if (!source)
-        {
-          return;
-        }
+  // Crawl up to the source level
+  pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(source);
 
-        // Update the source/filter
-        vtkSMProxy* proxy = source->getProxy();
-        proxy->UpdateVTKObjects();
-        proxy->UpdatePropertyInformation();
-        source->updatePipeline();
+  while (filter) {
+    source = filter->getInput(0);
+    filter = qobject_cast<pqPipelineFilter *>(source);
+  }
 
-        // Crawl up to the source level 
-        pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(source);
+  // Ensure that the source is either an MDEvent source or an MDHisto source
+  std::string sourceName(source->getProxy()->GetXMLName());
+  if (sourceName.find("MDEW Source") == std::string::npos &&
+      sourceName.find("MDHW Source") == std::string::npos) {
+    return;
+  }
 
-        while (filter)
-        {
-          source = filter->getInput(0);
-          filter = qobject_cast<pqPipelineFilter*>(source);
-        }
+  // Check if the source has an underlying event workspace or histo workspace
+  workspaceName = vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true)
+                      .GetAsString();
 
-        // Ensure that the source is either an MDEvent source or an MDHisto source
-        std::string sourceName(source->getProxy()->GetXMLName());
-        if (sourceName.find("MDEW Source") == std::string::npos &&
-            sourceName.find("MDHW Source") == std::string::npos)
-        {
-          return;
-        }
+  workspaceType = vtkSMPropertyHelper(source->getProxy(), "WorkspaceTypeName",
+                                      true).GetAsString();
+}
 
-        // Check if the source has an underlying event workspace or histo workspace
-        workspaceName = vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true).GetAsString();
+/**
+ * Creates the pipeline for the rebinned source.
+ */
+void RebinnedSourcesManager::repipeRebinnedSource() {
+  swapSources(m_inputSource, m_rebinnedSource);
+
+  // If we had been dealing with rebinning a rebinned workspace and changing the
+  // algorithm,
+  // e.g. when changing from BinMD to SliceMD, then we need to untrack the old,
+  // rebinned
+  // workspace
+  if (m_newRebinnedWorkspacePairBuffer.size() > 0) {
+    untrackWorkspaces(createKeyPairForSource(m_inputSource));
+  }
 
-        workspaceType = vtkSMPropertyHelper(source->getProxy(), "WorkspaceTypeName", true).GetAsString();
-      }
+  m_newRebinnedWorkspacePairBuffer.clear();
+  m_newWorkspacePairBuffer.clear();
 
-      /**
-       * Creates the pipeline for the rebinned source.
-       */
-      void RebinnedSourcesManager::repipeRebinnedSource()
-      {
-       swapSources(m_inputSource, m_rebinnedSource);
-
-       // If we had been dealing with rebinning a rebinned workspace and changing the algorithm,
-       // e.g. when changing from BinMD to SliceMD, then we need to untrack the old, rebinned
-       // workspace
-       if (m_newRebinnedWorkspacePairBuffer.size() > 0)
-       {
-         untrackWorkspaces(createKeyPairForSource(m_inputSource));
-       }
-
-       m_newRebinnedWorkspacePairBuffer.clear();
-       m_newWorkspacePairBuffer.clear();
-
-       deleteSpecificSource(m_inputSource);
-      }
+  deleteSpecificSource(m_inputSource);
+}
 
-      /**
-       * Creates the pipeline for the original source.
-       * @param rebinnedSource The name of the rebinned source.
-       * @param originalSource The name of the original source.
-       */
-      void RebinnedSourcesManager::repipeOriginalSource(pqPipelineSource* rebinnedSource, pqPipelineSource* originalSource)
-      {
-        // Advance the rebinnedSource to the start of the pipeline
-        pqPipelineSource* rebSource = goToPipelineBeginning(rebinnedSource);
+/**
+ * Creates the pipeline for the original source.
+ * @param rebinnedSource The name of the rebinned source.
+ * @param originalSource The name of the original source.
+ */
+void RebinnedSourcesManager::repipeOriginalSource(
+    pqPipelineSource *rebinnedSource, pqPipelineSource *originalSource) {
+  // Advance the rebinnedSource to the start of the pipeline
+  pqPipelineSource *rebSource = goToPipelineBeginning(rebinnedSource);
 
-        // Swap source from rebinned source to original source.
-        swapSources(rebSource, originalSource);
+  // Swap source from rebinned source to original source.
+  swapSources(rebSource, originalSource);
 
-        // Untrack the sources
-        untrackWorkspaces(createKeyPairForSource(rebSource));
+  // Untrack the sources
+  untrackWorkspaces(createKeyPairForSource(rebSource));
 
-        deleteSpecificSource(rebSource);
-      }
+  deleteSpecificSource(rebSource);
+}
 
-      /**
-       * Swap the sources at the bottom level of the pipeline.
-       * @param src1 First source.
-       * @param src2 Second source.
-       */
-      void RebinnedSourcesManager::swapSources(pqPipelineSource* src1, pqPipelineSource* src2)
-      {
-        if (!src1 || !src2)
-        {
-          throw std::runtime_error("VSI error: Either the original or rebinned source don't seem to exist.");
-        }
+/**
+ * Swap the sources at the bottom level of the pipeline.
+ * @param src1 First source.
+ * @param src2 Second source.
+ */
+void RebinnedSourcesManager::swapSources(pqPipelineSource *src1,
+                                         pqPipelineSource *src2) {
+  if (!src1 || !src2) {
+    throw std::runtime_error("VSI error: Either the original or rebinned "
+                             "source don't seem to exist.");
+  }
 
-        // Check that both sources contain non-empty data sets
+  // Check that both sources contain non-empty data sets
 
-        // Check if the original source has a filter if such then repipe otherwise we are done
-        if ((src1->getAllConsumers()).size() <= 0)
-        {
-          // Need to press apply to finalize the internal setup of the source.
-          //emit triggerAcceptForNewFilters();
-          return;
-        }
+  // Check if the original source has a filter if such then repipe otherwise we
+  // are done
+  if ((src1->getAllConsumers()).size() <= 0) {
+    // Need to press apply to finalize the internal setup of the source.
+    // emit triggerAcceptForNewFilters();
+    return;
+  }
 
-        // Rebuild pipeline
-        rebuildPipeline(src1, src2);
+  // Rebuild pipeline
+  rebuildPipeline(src1, src2);
 
-        // Render the active view to make the changes visible.
-        pqActiveObjects::instance().activeView()->render();
-      }
+  // Render the active view to make the changes visible.
+  pqActiveObjects::instance().activeView()->render();
+}
 
-      /**
-       * Get the stored workspace names assoicated with a source.
-       * @param src The name of the source.
-       * @param originalWorkspaceName The name of the original workspace.
-       * @param rebinnedWorkspaceName The name of the rebinned workspace.
-       */
-      void RebinnedSourcesManager::getStoredWorkspaceNames(pqPipelineSource* src, std::string& originalWorkspaceName, std::string& rebinnedWorkspaceName)
-      {
-        if (!src)
-        {
-          return;
-        }
+/**
+ * Get the stored workspace names assoicated with a source.
+ * @param src The name of the source.
+ * @param originalWorkspaceName The name of the original workspace.
+ * @param rebinnedWorkspaceName The name of the rebinned workspace.
+ */
+void RebinnedSourcesManager::getStoredWorkspaceNames(
+    pqPipelineSource *src, std::string &originalWorkspaceName,
+    std::string &rebinnedWorkspaceName) {
+  if (!src) {
+    return;
+  }
 
-        pqPipelineSource* source = goToPipelineBeginning(src);
+  pqPipelineSource *source = goToPipelineBeginning(src);
 
-        // Get the key pair which contains the name of the rebinned workspace and the source name
-        std::pair<std::string, std::string> key = createKeyPairForSource(source);
-        rebinnedWorkspaceName = key.first;
+  // Get the key pair which contains the name of the rebinned workspace and the
+  // source name
+  std::pair<std::string, std::string> key = createKeyPairForSource(source);
+  rebinnedWorkspaceName = key.first;
 
-        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0 )
-        {
-          originalWorkspaceName = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[key];
-        }
-        else
-        {
-          originalWorkspaceName  = "";
-        }
+  if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0) {
+    originalWorkspaceName =
+        m_rebinnedWorkspaceAndSourceToOriginalWorkspace[key];
+  } else {
+    originalWorkspaceName = "";
+  }
+}
+
+/**
+ * Get all sources which are linked to the workspace which is to be deleted. The
+ * workspace
+ * can be a rebinned workspace or an unrebinned workspace.
+ * @param workspaceName The workspace name associated with the source.
+ * @returns a list with all tracked (true sources) which are associated with the
+ * workspace
+ */
+std::vector<pqPipelineSource *>
+RebinnedSourcesManager::findAllRebinnedSourcesForWorkspace(
+    std::string workspaceName) {
+  std::vector<std::string> linkedSources;
+  // We need to iterate over the map
+  for (std::map<std::pair<std::string, std::string>,
+                std::string>::const_iterator it =
+           m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin();
+       it != m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin(); ++it) {
+    // Check the first part of the key and the value ofthe map
+    std::string rebinnedWorkspaceName = it->first.first;
+    std::string originalWorkspaceName = it->second;
+
+    if (workspaceName == rebinnedWorkspaceName ||
+        workspaceName == originalWorkspaceName) {
+      linkedSources.push_back(it->first.second);
+    }
+  }
+
+  // Now that we have the sources it is time to get them from the ParaView
+  // server
+  std::vector<pqPipelineSource *> sourcesToBeDeleted;
+
+  pqServer *server = pqActiveObjects::instance().activeServer();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
+  const QList<pqPipelineSource *> sources =
+      smModel->findItems<pqPipelineSource *>(server);
+
+  foreach (pqPipelineSource *source, sources) {
+    pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(source);
+    if (!filter) {
+      std::string sourceName(source->getProxy()->GetGlobalIDAsString());
+
+      if (doesSourceNeedToBeDeleted(sourceName, linkedSources)) {
+        sourcesToBeDeleted.push_back(source);
       }
+    }
+  }
 
-      /**
-       * Get all sources which are linked to the workspace which is to be deleted. The workspace
-       * can be a rebinned workspace or an unrebinned workspace.
-       * @param workspaceName The workspace name associated with the source.
-       * @returns a list with all tracked (true sources) which are associated with the workspace
-       */
-      std::vector<pqPipelineSource*> RebinnedSourcesManager::findAllRebinnedSourcesForWorkspace(std::string workspaceName)
-      {
-        std::vector<std::string> linkedSources;
-        // We need to iterate over the map
-        for (std::map<std::pair<std::string, std::string>, std::string>::const_iterator it = m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin();
-             it != m_rebinnedWorkspaceAndSourceToOriginalWorkspace.begin(); ++it)
-        {
-          // Check the first part of the key and the value ofthe map
-          std::string rebinnedWorkspaceName = it->first.first;
-          std::string originalWorkspaceName = it->second;
-
-          if (workspaceName == rebinnedWorkspaceName || workspaceName == originalWorkspaceName)
-          {
-            linkedSources.push_back(it->first.second);
-          }
-        }
+  return sourcesToBeDeleted;
+}
 
-        // Now that we have the sources it is time to get them from the ParaView server
-        std::vector<pqPipelineSource*> sourcesToBeDeleted;
-
-        pqServer *server = pqActiveObjects::instance().activeServer();
-        pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
-        const QList<pqPipelineSource *> sources =
-            smModel->findItems<pqPipelineSource *>(server);
-
-        foreach (pqPipelineSource *source, sources) {
-          pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(source);
-          if (!filter)
-          {
-            std::string sourceName(source->getProxy()->GetGlobalIDAsString());
-
-            if (doesSourceNeedToBeDeleted(sourceName, linkedSources))
-            {
-              sourcesToBeDeleted.push_back(source);
-            }
-          }
-        }
+/**
+ * Check if a source is being tracked and hence needs to be deleted
+ * @param sourceName the name of the source which we want to check
+ * @param trackedSources a list of tracked sources which need to be deleted
+ */
+bool RebinnedSourcesManager::doesSourceNeedToBeDeleted(
+    const std::string &sourceName,
+    const std::vector<std::string> &trackedSources) {
+  if (sourceName.empty())
+    return false;
+
+  return std::find(trackedSources.cbegin(), trackedSources.cend(),
+                   sourceName) != trackedSources.cend();
+}
+
+/**
+ * Process the workspaces names for the original source and the input source
+ * @param inputWorkspace Reference to the input workpspace.
+ * @param outputWorkspace Reference to the output workspace.
+ * @param source A pointer to the original source
+ * @param workspaceName The name of the workspace of the current source.
+ * @param algorithmType The algorithm which creates the rebinned source.
+ */
+void RebinnedSourcesManager::processWorkspaceNames(std::string &inputWorkspace,
+                                                   std::string &outputWorkspace,
+                                                   pqPipelineSource *source,
+                                                   std::string workspaceName,
+                                                   std::string algorithmType) {
+  // Reset the temporary tracking elements, which are needed only for the
+  // duration of the rebinning itself
+  m_newWorkspacePairBuffer.clear();
+  m_newRebinnedWorkspacePairBuffer.clear();
+  m_inputSource = NULL;
+  m_rebinnedSource = NULL;
+
+  // If the workspace is the original workspace or it is a freshly loaded, i.e.
+  // it is not being tracked
+  if (workspaceName.find(m_tempPostfix) == std::string::npos ||
+      !isRebinnedSourceBeingTracked(source)) {
+    inputWorkspace = workspaceName;
+    outputWorkspace =
+        m_tempPrefix + workspaceName + algorithmType + m_tempPostfix;
+  } // If the workspace is rebinned and was created with the same algorithm as
+  // the currently selected one.
+  else if (workspaceName.find(algorithmType) != std::string::npos &&
+           workspaceName.find(m_tempPostfix) != std::string::npos) {
+    // Check if the source and the workspace name are being tracked already
+    if (isRebinnedSourceBeingTracked(source)) {
+      inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace
+          [createKeyPairForSource(source)];
+      outputWorkspace = workspaceName;
+    }
+  } else // If the workspace is rebinned but was not created with the same
+         // algorithm as the currently selected one.
+  {
+    if (isRebinnedSourceBeingTracked(source)) {
+      inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace
+          [createKeyPairForSource(source)];
+      outputWorkspace =
+          m_tempPrefix + inputWorkspace + algorithmType + m_tempPostfix;
+      // Keep track of the old rebinned workspace and source
+      m_newRebinnedWorkspacePairBuffer.emplace(
+          workspaceName, std::make_pair(outputWorkspace, source));
+    }
+  }
+  // Record the workspaces
+  m_newWorkspacePairBuffer.emplace(inputWorkspace,
+                                   std::make_pair(outputWorkspace, source));
+  m_inputSource = source;
+}
+
+/**
+ * Stop keeping tabs on the specific workspace pair
+ * @param key a key to the tracking map
+ */
+void RebinnedSourcesManager::untrackWorkspaces(
+    std::pair<std::string, std::string> key) {
+  if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0) {
+    m_rebinnedWorkspaceAndSourceToOriginalWorkspace.erase(key);
+  }
+}
+
+/**
+  * Rebuild the pipeline for the new source
+  * @param source1 The old source.
+  * @param source2 The new source.
+  */
+void RebinnedSourcesManager::rebuildPipeline(pqPipelineSource *source1,
+                                             pqPipelineSource *source2) {
+  // Step through all the filters in old pipeline and reproduce them
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqPipelineFilter *filter1 =
+      qobject_cast<pqPipelineFilter *>(source1->getConsumer(0));
+
+  pqPipelineSource *endOfSource2Pipeline = source2;
+
+  while (filter1) {
+    vtkSMProxy *proxy1 = NULL;
+    proxy1 = filter1->getProxy();
+    pqPipelineSource *newPipelineElement = NULL;
+    pqPipelineFilter *newFilter = NULL;
+    // Move source2 to its end.
+    while (endOfSource2Pipeline->getNumberOfConsumers() > 0) {
+      endOfSource2Pipeline = endOfSource2Pipeline->getConsumer(0);
+    }
+
+    if (QString(proxy1->GetXMLName()).contains("ScaleWorkspace")) {
+      // Build the source
+      newPipelineElement = builder->createFilter(
+          "filters", "MantidParaViewScaleWorkspace", endOfSource2Pipeline);
+    } else if (QString(proxy1->GetXMLName()).contains("Cut")) {
+      newPipelineElement =
+          builder->createFilter("filters", "Cut", endOfSource2Pipeline);
+    }
+
+    newFilter = qobject_cast<pqPipelineFilter *>(newPipelineElement);
+
+    // Copy the properties from the old filter to the new filter.
+    copyProperties(filter1, newFilter);
+
+    if (filter1->getNumberOfConsumers() > 0) {
+      filter1 = qobject_cast<pqPipelineFilter *>(filter1->getConsumer(0));
+    } else {
+      filter1 = NULL;
+    }
+  }
+  emit triggerAcceptForNewFilters();
+}
 
-        return sourcesToBeDeleted;
+/**
+  * Copy the properties of the old filter to the new filter.
+  * @param filter1 The old filter.
+  * @param filter2 The new filter.
+  */
+void RebinnedSourcesManager::copyProperties(pqPipelineFilter *filter1,
+                                            pqPipelineFilter *filter2) {
+  vtkSMProxy *proxy1 = filter1->getProxy();
+  vtkSMProxy *proxy2 = filter2->getProxy();
+
+  copySafe(proxy2, proxy1);
+}
+
+/**
+  * This method is taken from a newer version of pqCopyReaction, which contains
+ * a bug fix
+  * for copying CutFilter properties. This is the correct way to copy proxy
+ * properties.
+  * @param dest Destination proxy.
+  * @param source Source proxy.
+  */
+void RebinnedSourcesManager::copySafe(vtkSMProxy *dest, vtkSMProxy *source) {
+  if (dest && source) {
+    BEGIN_UNDO_SET("Copy Properties");
+    dest->Copy(source, "vtkSMProxyProperty");
+
+    // handle proxy properties.
+    auto destIter = vtkSmartPointer<vtkSMPropertyIterator>::Take(
+        dest->NewPropertyIterator());
+    for (destIter->Begin(); !destIter->IsAtEnd(); destIter->Next()) {
+      if (vtkSMInputProperty::SafeDownCast(destIter->GetProperty())) {
+        // skip input properties.
+        continue;
       }
 
-      /**
-       * Check if a source is being tracked and hence needs to be deleted
-       * @param sourceName the name of the source which we want to check
-       * @param trackedSources a list of tracked sources which need to be deleted
-       */
-      bool RebinnedSourcesManager::doesSourceNeedToBeDeleted(
-          const std::string &sourceName,
-          const std::vector<std::string> &trackedSources) {
-        if (sourceName.empty())
-          return false;
-
-        return std::find(trackedSources.cbegin(), trackedSources.cend(),
-                         sourceName) != trackedSources.cend();
+      vtkSMProxyProperty *destPP =
+          vtkSMProxyProperty::SafeDownCast(destIter->GetProperty());
+      vtkSMProxyProperty *srcPP = vtkSMProxyProperty::SafeDownCast(
+          source->GetProperty(destIter->GetKey()));
+
+      if (!destPP || !srcPP || srcPP->GetNumberOfProxies() > 1) {
+        // skip non-proxy properties since those were already copied.
+        continue;
       }
 
-      /**
-       * Process the workspaces names for the original source and the input source
-       * @param inputWorkspace Reference to the input workpspace.
-       * @param outputWorkspace Reference to the output workspace.
-       * @param source A pointer to the original source
-       * @param workspaceName The name of the workspace of the current source.
-       * @param algorithmType The algorithm which creates the rebinned source.
-       */
-      void RebinnedSourcesManager::processWorkspaceNames(std::string& inputWorkspace, std::string& outputWorkspace, pqPipelineSource* source,  std::string workspaceName, std::string algorithmType)
-      {
-        // Reset the temporary tracking elements, which are needed only for the duration of the rebinning itself
-        m_newWorkspacePairBuffer.clear();
-        m_newRebinnedWorkspacePairBuffer.clear();
-        m_inputSource = NULL;
-        m_rebinnedSource = NULL;
-
-        // If the workspace is the original workspace or it is a freshly loaded, i.e. it is not being tracked
-        if (workspaceName.find(m_tempPostfix) == std::string::npos || !isRebinnedSourceBeingTracked(source))
-        {
-          inputWorkspace = workspaceName;
-          outputWorkspace =  m_tempPrefix + workspaceName + algorithmType + m_tempPostfix;
-        } // If the workspace is rebinned and was created with the same algorithm as the currently selected one.
-        else if (workspaceName.find(algorithmType) != std::string::npos && workspaceName.find(m_tempPostfix) != std::string::npos) 
-        {
-          // Check if the source and the workspace name are being tracked already
-          if (isRebinnedSourceBeingTracked(source))
-          {
-            inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[createKeyPairForSource(source)];
-            outputWorkspace = workspaceName;
-          }
-        }
-        else // If the workspace is rebinned but was not created with the same algorithm as the currently selected one.
-        {
-          if (isRebinnedSourceBeingTracked(source))
-          {
-            inputWorkspace = m_rebinnedWorkspaceAndSourceToOriginalWorkspace[createKeyPairForSource(source)];
-            outputWorkspace = m_tempPrefix + inputWorkspace + algorithmType + m_tempPostfix;
-            // Keep track of the old rebinned workspace and source
-            m_newRebinnedWorkspacePairBuffer.emplace(
-                workspaceName, std::make_pair(outputWorkspace, source));
-          }
-        }
-        // Record the workspaces
-        m_newWorkspacePairBuffer.emplace(
-            inputWorkspace, std::make_pair(outputWorkspace, source));
-        m_inputSource= source;
+      vtkSMProxyListDomain *destPLD = vtkSMProxyListDomain::SafeDownCast(
+          destPP->FindDomain("vtkSMProxyListDomain"));
+      vtkSMProxyListDomain *srcPLD = vtkSMProxyListDomain::SafeDownCast(
+          srcPP->FindDomain("vtkSMProxyListDomain"));
+
+      if (!destPLD || !srcPLD) {
+        // we copy proxy properties that have proxy list domains.
+        continue;
       }
 
-      /**
-       * Stop keeping tabs on the specific workspace pair
-       * @param key a key to the tracking map
-       */
-      void RebinnedSourcesManager::untrackWorkspaces(std::pair<std::string, std::string> key)
-      {
-        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0)
-        {
-          m_rebinnedWorkspaceAndSourceToOriginalWorkspace.erase(key);
-        }
+      if (srcPP->GetNumberOfProxies() == 0) {
+        destPP->SetNumberOfProxies(0);
+        continue;
       }
 
-      /**
-        * Rebuild the pipeline for the new source
-        * @param source1 The old source.
-        * @param source2 The new source.
-        */
-      void RebinnedSourcesManager::rebuildPipeline(pqPipelineSource* source1, pqPipelineSource* source2)
-      {
-        // Step through all the filters in old pipeline and reproduce them
-        pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-        pqPipelineFilter* filter1 = qobject_cast<pqPipelineFilter*>(source1->getConsumer(0));
-
-        pqPipelineSource* endOfSource2Pipeline = source2;
-
-        while(filter1)
-        {
-          vtkSMProxy* proxy1 = NULL;
-          proxy1 = filter1->getProxy();
-          pqPipelineSource* newPipelineElement = NULL;
-          pqPipelineFilter* newFilter = NULL;
-          // Move source2 to its end.
-          while (endOfSource2Pipeline->getNumberOfConsumers() > 0)
-          {
-            endOfSource2Pipeline = endOfSource2Pipeline->getConsumer(0);
-          }
-
-          if (QString(proxy1->GetXMLName()).contains("ScaleWorkspace"))
-          {
-            // Build the source
-            newPipelineElement = builder->createFilter("filters","MantidParaViewScaleWorkspace", endOfSource2Pipeline);
-          } else if (QString(proxy1->GetXMLName()).contains("Cut"))
-          {
-            newPipelineElement = builder->createFilter("filters", "Cut", endOfSource2Pipeline);
-          }
-
-          newFilter = qobject_cast<pqPipelineFilter*>(newPipelineElement);
-
-          // Copy the properties from the old filter to the new filter.
-          copyProperties(filter1, newFilter);
-
-          if (filter1->getNumberOfConsumers() > 0)
-          {
-            filter1 = qobject_cast<pqPipelineFilter*>(filter1->getConsumer(0));
-          }
-          else 
-          {
-            filter1 = NULL;
-          }
+      vtkSMProxy *srcValue = srcPP->GetProxy(0);
+      vtkSMProxy *destValue = NULL;
+
+      // find srcValue type in destPLD and that's the proxy to use as destValue.
+      for (unsigned int cc = 0;
+           srcValue != NULL && cc < destPLD->GetNumberOfProxyTypes(); cc++) {
+        if (srcValue->GetXMLName() && destPLD->GetProxyName(cc) &&
+            strcmp(srcValue->GetXMLName(), destPLD->GetProxyName(cc)) == 0 &&
+            srcValue->GetXMLGroup() && destPLD->GetProxyGroup(cc) &&
+            strcmp(srcValue->GetXMLGroup(), destPLD->GetProxyGroup(cc)) == 0) {
+          destValue = destPLD->GetProxy(cc);
+          break;
         }
-        emit triggerAcceptForNewFilters();
       }
 
-      /**
-        * Copy the properties of the old filter to the new filter.
-        * @param filter1 The old filter.
-        * @param filter2 The new filter.
-        */
-      void RebinnedSourcesManager::copyProperties(pqPipelineFilter* filter1, pqPipelineFilter* filter2)
-      {
-        vtkSMProxy* proxy1 = filter1->getProxy();
-        vtkSMProxy* proxy2 = filter2->getProxy();
-
-        copySafe(proxy2, proxy1);
+      if (destValue) {
+        Q_ASSERT(srcValue != NULL);
+        copySafe(destValue, srcValue);
+        destPP->SetProxy(0, destValue);
       }
+    }
 
-      /**
-        * This method is taken from a newer version of pqCopyReaction, which contains a bug fix 
-        * for copying CutFilter properties. This is the correct way to copy proxy properties.
-        * @param dest Destination proxy.
-        * @param source Source proxy.
-        */
-      void RebinnedSourcesManager::copySafe(vtkSMProxy* dest, vtkSMProxy* source)
-      {
-        if (dest && source)
-        {
-        BEGIN_UNDO_SET("Copy Properties");
-        dest->Copy(source, "vtkSMProxyProperty");
-
-          // handle proxy properties.
-        auto destIter = vtkSmartPointer<vtkSMPropertyIterator>::Take(
-            dest->NewPropertyIterator());
-        for (destIter->Begin(); !destIter->IsAtEnd(); destIter->Next()) {
-          if (vtkSMInputProperty::SafeDownCast(destIter->GetProperty())) {
-            // skip input properties.
-            continue;
-            }
-
-            vtkSMProxyProperty* destPP =  vtkSMProxyProperty::SafeDownCast(destIter->GetProperty());
-            vtkSMProxyProperty* srcPP = vtkSMProxyProperty::SafeDownCast(source->GetProperty(destIter->GetKey()));
-
-            if (!destPP || !srcPP || srcPP->GetNumberOfProxies() > 1)
-            {
-            // skip non-proxy properties since those were already copied.
-            continue;
-            }
-
-            vtkSMProxyListDomain* destPLD = vtkSMProxyListDomain::SafeDownCast(destPP->FindDomain("vtkSMProxyListDomain"));
-            vtkSMProxyListDomain* srcPLD = vtkSMProxyListDomain::SafeDownCast(srcPP->FindDomain("vtkSMProxyListDomain"));
-
-            if (!destPLD || !srcPLD)
-            {
-              // we copy proxy properties that have proxy list domains.
-              continue;
-            }
-
-            if (srcPP->GetNumberOfProxies() == 0)
-            {
-              destPP->SetNumberOfProxies(0);
-              continue;
-            }
-
-            vtkSMProxy* srcValue = srcPP->GetProxy(0);
-            vtkSMProxy* destValue = NULL;
-
-            // find srcValue type in destPLD and that's the proxy to use as destValue.
-            for (unsigned int cc=0; srcValue != NULL && cc < destPLD->GetNumberOfProxyTypes(); cc++)
-            {
-              if (srcValue->GetXMLName() && destPLD->GetProxyName(cc) &&
-                  strcmp(srcValue->GetXMLName(), destPLD->GetProxyName(cc)) == 0 &&
-                  srcValue->GetXMLGroup() && destPLD->GetProxyGroup(cc) &&
-                  strcmp(srcValue->GetXMLGroup(), destPLD->GetProxyGroup(cc)) == 0)
-              {
-                destValue = destPLD->GetProxy(cc);
-                break;
-              }
-            }
-
-            if (destValue)
-            {
-              Q_ASSERT(srcValue != NULL);
-              copySafe(destValue, srcValue);
-              destPP->SetProxy(0, destValue);
-            }
-          }
-
-          dest->UpdateVTKObjects();
-          END_UNDO_SET();
-        }
-      }
+    dest->UpdateVTKObjects();
+    END_UNDO_SET();
+  }
+}
 
-      /**
-       * Register the rebinned source. Specifically, connect to the destroyed signal of the rebinned source.
-       * @param source The rebinned source.
-       */
-      void RebinnedSourcesManager::registerRebinnedSource(pqPipelineSource* source)
-      {
-        if (!source)
-        {
-          return;
-        }
+/**
+ * Register the rebinned source. Specifically, connect to the destroyed signal
+ * of the rebinned source.
+ * @param source The rebinned source.
+ */
+void RebinnedSourcesManager::registerRebinnedSource(pqPipelineSource *source) {
+  if (!source) {
+    return;
+  }
 
-        // Make sure that the underlying source is associated with the buffered workspace pair and register it
-        try
-        {
-          // Add entry to map from (rebinnedWsName, rebinnedSourceName) -> (originalWsName)
-          if (m_newWorkspacePairBuffer.size() != 1)
-          {
-            throw std::runtime_error("Original source for rebinned source could not be found.");
-          }
-
-          const std::string &originalWorkspaceName =
-              m_newWorkspacePairBuffer.begin()->first;
-          const std::string &rebinnedWorkspaceName =
-              m_newWorkspacePairBuffer.begin()->second.first;
-
-          std::pair<std::string, std::string> key(rebinnedWorkspaceName,
-                                                  getSourceName(source));
-          m_rebinnedWorkspaceAndSourceToOriginalWorkspace.emplace(
-              key, originalWorkspaceName);
-
-          // Record the rebinned source
-          m_rebinnedSource = source;
-        }
-        catch (std::runtime_error &ex)
-        {
-          g_log.warning() << ex.what(); 
-        }
+  // Make sure that the underlying source is associated with the buffered
+  // workspace pair and register it
+  try {
+    // Add entry to map from (rebinnedWsName, rebinnedSourceName) ->
+    // (originalWsName)
+    if (m_newWorkspacePairBuffer.size() != 1) {
+      throw std::runtime_error(
+          "Original source for rebinned source could not be found.");
+    }
 
-        QObject::connect(source, SIGNAL(destroyed()),
-                         this, SLOT(onRebinnedSourceDestroyed()));
-      }
+    const std::string &originalWorkspaceName =
+        m_newWorkspacePairBuffer.begin()->first;
+    const std::string &rebinnedWorkspaceName =
+        m_newWorkspacePairBuffer.begin()->second.first;
 
-      /**
-       * React to the deletion of a rebinned source. We need to make sure that the source is untracked
-       */
-      void RebinnedSourcesManager::onRebinnedSourceDestroyed()
-      {
-        pqServer *server = pqActiveObjects::instance().activeServer();
-        pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
-        QList<pqPipelineSource *> sources = smModel->findItems<pqPipelineSource *>(server);
-
-        std::vector<std::pair<std::string, std::string>> toBeUntracked;
-
-        // Compare all registered sources to all loaded sources,
-        for (const auto &wsPair :
-             m_rebinnedWorkspaceAndSourceToOriginalWorkspace) {
-          const std::string &registeredSourceName = wsPair.first.second;
-
-          auto source = std::find_if(
-              sources.begin(), sources.end(),
-              [this, &registeredSourceName](pqPipelineSource *src) {
-                return registeredSourceName == getSourceName(src);
-              });
-
-          // If there was no matching source then mark it to be untracked
-          if (source == sources.end())
-          {
-            toBeUntracked.push_back(wsPair.first);
-          }
-        }
+    std::pair<std::string, std::string> key(rebinnedWorkspaceName,
+                                            getSourceName(source));
+    m_rebinnedWorkspaceAndSourceToOriginalWorkspace.emplace(
+        key, originalWorkspaceName);
 
-        // Finally untrack all sources which need it
-        for (const auto &key : toBeUntracked) {
-          untrackWorkspaces(key);
-        }
-      }
+    // Record the rebinned source
+    m_rebinnedSource = source;
+  } catch (std::runtime_error &ex) {
+    g_log.warning() << ex.what();
+  }
 
-      /**
-       * Remove the pipeline
-       */
-      void RebinnedSourcesManager::removePipeline(pqPipelineSource* source)
-      {
-        // Go to the end of the pipeline
-        while(source->getNumberOfConsumers() > 0)
-        {
-          source = source->getConsumer(0);
-        }
+  QObject::connect(source, SIGNAL(destroyed()), this,
+                   SLOT(onRebinnedSourceDestroyed()));
+}
 
-        //Destroy the pipeline from the end
-        pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-        pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(source);
+/**
+ * React to the deletion of a rebinned source. We need to make sure that the
+ * source is untracked
+ */
+void RebinnedSourcesManager::onRebinnedSourceDestroyed() {
+  pqServer *server = pqActiveObjects::instance().activeServer();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
+  QList<pqPipelineSource *> sources =
+      smModel->findItems<pqPipelineSource *>(server);
+
+  std::vector<std::pair<std::string, std::string>> toBeUntracked;
+
+  // Compare all registered sources to all loaded sources,
+  for (const auto &wsPair : m_rebinnedWorkspaceAndSourceToOriginalWorkspace) {
+    const std::string &registeredSourceName = wsPair.first.second;
+
+    auto source =
+        std::find_if(sources.begin(), sources.end(),
+                     [this, &registeredSourceName](pqPipelineSource *src) {
+                       return registeredSourceName == getSourceName(src);
+                     });
+
+    // If there was no matching source then mark it to be untracked
+    if (source == sources.end()) {
+      toBeUntracked.push_back(wsPair.first);
+    }
+  }
 
-        while (filter)
-        {
-          source = filter->getInput(0);
-          builder->destroy(filter);
-          filter = qobject_cast<pqPipelineFilter*>(source);
-        }
+  // Finally untrack all sources which need it
+  for (const auto &key : toBeUntracked) {
+    untrackWorkspaces(key);
+  }
+}
 
-        builder->destroy(source); // The listener takes now care of the workspace.
-      }
+/**
+ * Remove the pipeline
+ */
+void RebinnedSourcesManager::removePipeline(pqPipelineSource *source) {
+  // Go to the end of the pipeline
+  while (source->getNumberOfConsumers() > 0) {
+    source = source->getConsumer(0);
+  }
 
-      /**
-       * Gets the source name
-       * @param source A pointer to a source
-       * @returns the name of the source
-       */
-      std::string RebinnedSourcesManager::getSourceName(pqPipelineSource* source)
-      {
-        return std::string(source->getProxy()->GetGlobalIDAsString());
-      }
+  // Destroy the pipeline from the end
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(source);
 
-      /**
-       * Check if a rebinned source is being tracked.
-       * @param src A pointer to a source
-       * @returns if it is being tracked or not
-       */
-      bool RebinnedSourcesManager::isRebinnedSourceBeingTracked(pqPipelineSource* src)
-      {
-        pqPipelineSource* source = goToPipelineBeginning(src);
+  while (filter) {
+    source = filter->getInput(0);
+    builder->destroy(filter);
+    filter = qobject_cast<pqPipelineFilter *>(source);
+  }
 
-        std::pair<std::string, std::string> key = createKeyPairForSource(source);
+  builder->destroy(source); // The listener takes now care of the workspace.
+}
 
-        if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0)
-        {
-          return true;
-        }
-        else
-        {
-          return false;
-        }
-      }
+/**
+ * Gets the source name
+ * @param source A pointer to a source
+ * @returns the name of the source
+ */
+std::string RebinnedSourcesManager::getSourceName(pqPipelineSource *source) {
+  return std::string(source->getProxy()->GetGlobalIDAsString());
+}
 
-      /**
-       * Construct a workspaceName, sourceName key pair for a given source
-       * @param source A pointer to a source
-       * @returns a key which can be used with the tracking map
-       */
-      std::pair<std::string, std::string> RebinnedSourcesManager::createKeyPairForSource(pqPipelineSource* source)
-      {
-        if (!source)
-        {
-          return std::pair<std::string, std::string>("", "");
-        }
+/**
+ * Check if a rebinned source is being tracked.
+ * @param src A pointer to a source
+ * @returns if it is being tracked or not
+ */
+bool RebinnedSourcesManager::isRebinnedSourceBeingTracked(
+    pqPipelineSource *src) {
+  pqPipelineSource *source = goToPipelineBeginning(src);
+
+  std::pair<std::string, std::string> key = createKeyPairForSource(source);
+
+  if (m_rebinnedWorkspaceAndSourceToOriginalWorkspace.count(key) > 0) {
+    return true;
+  } else {
+    return false;
+  }
+}
 
-        std::string workspaceName = vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true).GetAsString();
-        return std::pair<std::string, std::string>(workspaceName, getSourceName(source));
-      }
+/**
+ * Construct a workspaceName, sourceName key pair for a given source
+ * @param source A pointer to a source
+ * @returns a key which can be used with the tracking map
+ */
+std::pair<std::string, std::string>
+RebinnedSourcesManager::createKeyPairForSource(pqPipelineSource *source) {
+  if (!source) {
+    return std::pair<std::string, std::string>("", "");
+  }
 
-      /**
-       * Delete a specific source and all of its filters. This assumes a linear filter system
-       * @param source A pointer to the source
-       */
-      void RebinnedSourcesManager::deleteSpecificSource(pqPipelineSource* source)
-      {
-        if (NULL != source)
-        {
-          // Go to the end of the source and work your way back
-          pqPipelineSource* tempSource = source;
-
-          while ((tempSource->getAllConsumers()).size() > 0)
-          {
-            tempSource = tempSource->getConsumer(0);
-          }
-
-          // Now delete all filters and the source
-          pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-
-          // Crawl up to the source level 
-          pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(tempSource);
-
-          while (filter)
-          {
-            tempSource = filter->getInput(0);
-            builder->destroy(filter);
-            filter = qobject_cast<pqPipelineFilter*>(tempSource);
-          }
-
-          builder->destroy(tempSource);
-        }
-      }
+  std::string workspaceName =
+      vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true)
+          .GetAsString();
+  return std::pair<std::string, std::string>(workspaceName,
+                                             getSourceName(source));
+}
 
-      /**
-        * Go to the beginning of a pipeline (assuming that it is linear
-        * @param source A pointer to a source
-        * @returns a pointer to the beginning of the pipeline
-        */
-        pqPipelineSource* RebinnedSourcesManager::goToPipelineBeginning(pqPipelineSource* source)
-        {
-          // Crawl up to the beginnign of the pipeline
-          pqPipelineSource* tempSource = source;
-          pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(tempSource);
-          while (filter)
-          {
-            tempSource = filter->getInput(0);
-            filter = qobject_cast<pqPipelineFilter*>(tempSource);
-          }
-
-          return tempSource;
-        }
+/**
+ * Delete a specific source and all of its filters. This assumes a linear filter
+ * system
+ * @param source A pointer to the source
+ */
+void RebinnedSourcesManager::deleteSpecificSource(pqPipelineSource *source) {
+  if (NULL != source) {
+    // Go to the end of the source and work your way back
+    pqPipelineSource *tempSource = source;
+
+    while ((tempSource->getAllConsumers()).size() > 0) {
+      tempSource = tempSource->getConsumer(0);
+    }
+
+    // Now delete all filters and the source
+    pqObjectBuilder *builder =
+        pqApplicationCore::instance()->getObjectBuilder();
+
+    // Crawl up to the source level
+    pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(tempSource);
 
+    while (filter) {
+      tempSource = filter->getInput(0);
+      builder->destroy(filter);
+      filter = qobject_cast<pqPipelineFilter *>(tempSource);
     }
+
+    builder->destroy(tempSource);
+  }
+}
+
+/**
+  * Go to the beginning of a pipeline (assuming that it is linear
+  * @param source A pointer to a source
+  * @returns a pointer to the beginning of the pipeline
+  */
+pqPipelineSource *
+RebinnedSourcesManager::goToPipelineBeginning(pqPipelineSource *source) {
+  // Crawl up to the beginnign of the pipeline
+  pqPipelineSource *tempSource = source;
+  pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(tempSource);
+  while (filter) {
+    tempSource = filter->getInput(0);
+    filter = qobject_cast<pqPipelineFilter *>(tempSource);
   }
+
+  return tempSource;
+}
+}
+}
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
index 0af06e51c0bfd0028da9ada20e7853bc57fe1281..fbb079c5ee30402ef61a6b1f883ec18212673171 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp
@@ -1,7 +1,7 @@
 #include "MantidVatesSimpleGuiViewWidgets/SaveScreenshotReaction.h"
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqActiveObjects.h>
@@ -21,47 +21,41 @@
 #include <vtkPVConfig.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QDebug>
 #include <QFileInfo>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 //-----------------------------------------------------------------------------
-SaveScreenshotReaction::SaveScreenshotReaction(QAction* parentObject)
-  : Superclass(parentObject)
-{
+SaveScreenshotReaction::SaveScreenshotReaction(QAction *parentObject)
+    : Superclass(parentObject) {
   // load state enable state depends on whether we are connected to an active
   // server or not and whether
-  pqActiveObjects* activeObjects = &pqActiveObjects::instance();
-  QObject::connect(activeObjects, SIGNAL(serverChanged(pqServer*)),
-                   this, SLOT(updateEnableState()));
-  QObject::connect(activeObjects, SIGNAL(viewChanged(pqView*)),
-                   this, SLOT(updateEnableState()));
+  pqActiveObjects *activeObjects = &pqActiveObjects::instance();
+  QObject::connect(activeObjects, SIGNAL(serverChanged(pqServer *)), this,
+                   SLOT(updateEnableState()));
+  QObject::connect(activeObjects, SIGNAL(viewChanged(pqView *)), this,
+                   SLOT(updateEnableState()));
   this->updateEnableState();
 }
 
 //-----------------------------------------------------------------------------
-void SaveScreenshotReaction::updateEnableState()
-{
-  pqActiveObjects* activeObjects = &pqActiveObjects::instance();
-  bool is_enabled = (activeObjects->activeView() && activeObjects->activeServer());
+void SaveScreenshotReaction::updateEnableState() {
+  pqActiveObjects *activeObjects = &pqActiveObjects::instance();
+  bool is_enabled =
+      (activeObjects->activeView() && activeObjects->activeServer());
   this->parentAction()->setEnabled(is_enabled);
 }
 
 //-----------------------------------------------------------------------------
-void SaveScreenshotReaction::saveScreenshot()
-{
-  pqView* view = pqActiveObjects::instance().activeView();
-  if (!view)
-  {
+void SaveScreenshotReaction::saveScreenshot() {
+  pqView *view = pqActiveObjects::instance().activeView();
+  if (!view) {
     qDebug() << "Cannnot save image. No active view.";
     return;
   }
@@ -69,18 +63,15 @@ void SaveScreenshotReaction::saveScreenshot()
   pqSaveSnapshotDialog ssDialog(pqCoreUtilities::mainWidget());
   ssDialog.setViewSize(view->getSize());
 
-  if (ssDialog.exec() != QDialog::Accepted)
-  {
+  if (ssDialog.exec() != QDialog::Accepted) {
     return;
   }
 
   QString lastUsedExt;
   // Load the most recently used file extensions from QSettings, if available.
-  pqSettings* settings = pqApplicationCore::instance()->settings();
-  if (settings->contains("extensions/ScreenshotExtension"))
-  {
-    lastUsedExt =
-        settings->value("extensions/ScreenshotExtension").toString();
+  pqSettings *settings = pqApplicationCore::instance()->settings();
+  if (settings->contains("extensions/ScreenshotExtension")) {
+    lastUsedExt = settings->value("extensions/ScreenshotExtension").toString();
   }
 
   QString filters;
@@ -90,19 +81,17 @@ void SaveScreenshotReaction::saveScreenshot()
   filters += ";;PPM image (*.ppm)";
   filters += ";;JPG image (*.jpg)";
   filters += ";;PDF file (*.pdf)";
-  pqFileDialog file_dialog(NULL,
-                           pqCoreUtilities::mainWidget(),
+  pqFileDialog file_dialog(NULL, pqCoreUtilities::mainWidget(),
                            tr("Save Screenshot:"), QString(), filters);
   file_dialog.setRecentlyUsedExtension(lastUsedExt);
   file_dialog.setObjectName("FileSaveScreenshotDialog");
   file_dialog.setFileMode(pqFileDialog::AnyFile);
-  if (file_dialog.exec() != QDialog::Accepted)
-  {
+  if (file_dialog.exec() != QDialog::Accepted) {
     return;
   }
 
   QString file = file_dialog.getSelectedFiles()[0];
-  QFileInfo fileInfo = QFileInfo( file );
+  QFileInfo fileInfo = QFileInfo(file);
   lastUsedExt = QString("*.") + fileInfo.suffix();
   settings->setValue("extensions/ScreenshotExtension", lastUsedExt);
 
@@ -113,11 +102,10 @@ void SaveScreenshotReaction::saveScreenshot()
       pqActiveObjects::instance().activeServer()->proxyManager();
   vtkSMProxy *colorPalette = pxm->GetProxy("global_properties", "ColorPalette");
   vtkSmartPointer<vtkSMProxy> clone;
-  if (colorPalette && !palette.isEmpty())
-  {
+  if (colorPalette && !palette.isEmpty()) {
     // save current property values
-    clone.TakeReference(pxm->NewProxy(colorPalette->GetXMLGroup(),
-                                      colorPalette->GetXMLName()));
+    clone.TakeReference(
+        pxm->NewProxy(colorPalette->GetXMLGroup(), colorPalette->GetXMLName()));
     clone->Copy(colorPalette);
 
     auto chosenPalette = vtkSmartPointer<vtkSMProxy>::Take(
@@ -126,54 +114,44 @@ void SaveScreenshotReaction::saveScreenshot()
   }
 
   int stereo = ssDialog.getStereoMode();
-  if (stereo)
-  {
+  if (stereo) {
     pqRenderViewBase::setStereo(stereo);
   }
 
   SaveScreenshotReaction::saveScreenshot(file, size, ssDialog.quality());
 
   // restore color palette.
-  if (clone)
-  {
+  if (clone) {
     colorPalette->Copy(clone);
   }
 
   // restore stereo
-  if (stereo)
-  {
+  if (stereo) {
     pqRenderViewBase::setStereo(0);
   }
 
   // check if need to render to clear the changes we did
   // while saving the screenshot.
-  if (clone || stereo)
-  {
+  if (clone || stereo) {
     pqApplicationCore::instance()->render();
   }
 }
 
 //-----------------------------------------------------------------------------
-void SaveScreenshotReaction::saveScreenshot(const QString& filename,
-                                            const QSize& size, int quality)
-{
-  pqView* view = pqActiveObjects::instance().activeView();
+void SaveScreenshotReaction::saveScreenshot(const QString &filename,
+                                            const QSize &size, int quality) {
+  pqView *view = pqActiveObjects::instance().activeView();
   vtkSmartPointer<vtkImageData> img;
-  if (view)
-  {
+  if (view) {
     img.TakeReference(view->captureImage(size));
   }
 
-  if (img.GetPointer() == NULL)
-  {
+  if (img.GetPointer() == NULL) {
     qCritical() << "Save Image failed.";
-  }
-  else
-  {
+  } else {
     pqImageUtil::saveImage(img, filename, quality);
   }
 }
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
index 8b59abfbb4c4f86efb5e6d1cdc330f393097becb..059e746e881815acfafb2f912e96e08d3e544816 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/SplatterPlotView.cpp
@@ -13,7 +13,7 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqActiveObjects.h>
@@ -33,7 +33,7 @@
 #include <vtkSMSourceProxy.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QKeyEvent>
@@ -45,62 +45,51 @@
 using namespace MantidQt::API;
 using namespace Mantid::VATES;
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-namespace
-{
-  Mantid::Kernel::Logger g_log("SplatterPlotView");
+namespace {
+Mantid::Kernel::Logger g_log("SplatterPlotView");
 }
 
-
-SplatterPlotView::SplatterPlotView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager),
-                                                      m_cameraManager(boost::make_shared<CameraManager>()),
-                                                      m_peaksTableController(NULL),
-                                                      m_peaksWorkspaceNameDelimiter(";")                         
-{
+SplatterPlotView::SplatterPlotView(
+    QWidget *parent, RebinnedSourcesManager *rebinnedSourcesManager)
+    : ViewBase(parent, rebinnedSourcesManager),
+      m_cameraManager(boost::make_shared<CameraManager>()),
+      m_peaksTableController(NULL), m_peaksWorkspaceNameDelimiter(";") {
   this->m_noOverlay = false;
   this->m_ui.setupUi(this);
 
- // Setup the peaks viewer
+  // Setup the peaks viewer
   m_peaksTableController = new PeaksTableControllerVsi(m_cameraManager, this);
   m_peaksTableController->setMaximumHeight(150);
-  //this->m_ui.tableLayout->addWidget(m_peaksTableController);
+  // this->m_ui.tableLayout->addWidget(m_peaksTableController);
   this->m_ui.verticalLayout->addWidget(m_peaksTableController);
   m_peaksTableController->setVisible(true);
-  QObject::connect(m_peaksTableController, SIGNAL(setRotationToPoint(double, double, double)),
-                   this, SLOT(onResetCenterToPoint(double, double, double)));
+  QObject::connect(m_peaksTableController,
+                   SIGNAL(setRotationToPoint(double, double, double)), this,
+                   SLOT(onResetCenterToPoint(double, double, double)));
 
   // Set the threshold button to create a threshold filter on data
-  QObject::connect(this->m_ui.thresholdButton, SIGNAL(clicked()),
-                   this, SLOT(onThresholdButtonClicked()));
+  QObject::connect(this->m_ui.thresholdButton, SIGNAL(clicked()), this,
+                   SLOT(onThresholdButtonClicked()));
 
   // Set connection to toggle button for peak coordinate checking
-  QObject::connect(this->m_ui.overridePeakCoordsButton,
-                   SIGNAL(toggled(bool)),
-                   this,
-                   SLOT(onOverridePeakCoordToggled(bool)));
+  QObject::connect(this->m_ui.overridePeakCoordsButton, SIGNAL(toggled(bool)),
+                   this, SLOT(onOverridePeakCoordToggled(bool)));
 
   // Set connection to toggle button for pick mode checking
-  QObject::connect(this->m_ui.pickModeButton,
-                   SIGNAL(toggled(bool)),
-                   this,
+  QObject::connect(this->m_ui.pickModeButton, SIGNAL(toggled(bool)), this,
                    SLOT(onPickModeToggled(bool)));
 
   this->m_view = this->createRenderView(this->m_ui.renderFrame);
   this->installEventFilter(this);
 
   setupVisiblePeaksButtons();
-  
 }
 
-SplatterPlotView::~SplatterPlotView()
-{
-}
+SplatterPlotView::~SplatterPlotView() {}
 
 /**
  * This function is an event filter for handling pick mode. The release
@@ -110,16 +99,12 @@ SplatterPlotView::~SplatterPlotView()
  * @param ev : Event object
  * @return true if the event is handled
  */
-bool SplatterPlotView::eventFilter(QObject *obj, QEvent *ev)
-{
-  if (this->m_ui.pickModeButton->isChecked())
-  {
+bool SplatterPlotView::eventFilter(QObject *obj, QEvent *ev) {
+  if (this->m_ui.pickModeButton->isChecked()) {
     this->setFocus();
-    if (QEvent::KeyRelease == ev->type() && this == obj)
-    {
+    if (QEvent::KeyRelease == ev->type() && this == obj) {
       QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
-      if (Qt::Key_P == kev->key())
-      {
+      if (Qt::Key_P == kev->key()) {
         emit this->triggerAccept();
         this->readAndSendCoordinates();
         return true;
@@ -130,8 +115,7 @@ bool SplatterPlotView::eventFilter(QObject *obj, QEvent *ev)
   return false;
 }
 
-void SplatterPlotView::destroyView()
-{
+void SplatterPlotView::destroyView() {
   destroyFiltersForSplatterPlotView();
 
   // Destroy the view.
@@ -140,13 +124,9 @@ void SplatterPlotView::destroyView()
   pqActiveObjects::instance().setActiveSource(this->origSrc);
 }
 
-pqRenderView* SplatterPlotView::getView()
-{
-  return this->m_view.data();
-}
+pqRenderView *SplatterPlotView::getView() { return this->m_view.data(); }
 
-void SplatterPlotView::render()
-{
+void SplatterPlotView::render() {
   pqPipelineSource *src = NULL;
   src = pqActiveObjects::instance().activeSource();
   bool isPeaksWorkspace = this->isPeaksWorkspace(src);
@@ -155,22 +135,22 @@ void SplatterPlotView::render()
   // 2. If we are loading a peak workspace without haveing
   //    a splatterplot source in place
   bool isBadInput = !src || (isPeaksWorkspace && this->m_splatSource == NULL);
-  if (isBadInput)
-  {
-    g_log.warning() << "SplatterPlotView: Could not render source. You are either loading an active source " 
-                    << "or you are loading a peak source without having a splatterplot source in place.\n";
+  if (isBadInput) {
+    g_log.warning() << "SplatterPlotView: Could not render source. You are "
+                       "either loading an active source "
+                    << "or you are loading a peak source without having a "
+                       "splatterplot source in place.\n";
     return;
   }
 
   const char *renderType = "Point Gaussian";
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
 
   // Do not allow overplotting of MDWorkspaces
-  if (!this->isPeaksWorkspace(src) && NULL != this->m_splatSource)
-  {
+  if (!this->isPeaksWorkspace(src) && NULL != this->m_splatSource) {
     QMessageBox::warning(this, QApplication::tr("Overplotting Warning"),
-                         QApplication::tr("SplatterPlot mode does not allow "\
-                                          "more that one MDEventWorkspace to "\
+                         QApplication::tr("SplatterPlot mode does not allow "
+                                          "more that one MDEventWorkspace to "
                                           "be plotted."));
     // Need to destroy source since we tried to load it and set the active
     // back to something. In this case we'll choose the splatter plot filter.
@@ -180,21 +160,19 @@ void SplatterPlotView::render()
     return;
   }
 
-  if (!isPeaksWorkspace)
-  {
+  if (!isPeaksWorkspace) {
     this->origSrc = src;
-    this->m_splatSource = builder->createFilter("filters",
-                                              MantidQt::API::MdConstants::MantidParaViewSplatterPlot,
-                                              this->origSrc);
+    this->m_splatSource = builder->createFilter(
+        "filters", MantidQt::API::MdConstants::MantidParaViewSplatterPlot,
+        this->origSrc);
     src = this->m_splatSource;
-  }
-  else
-  {
-      // We don't want to load the same peak workspace twice into the splatterplot mode
+  } else {
+    // We don't want to load the same peak workspace twice into the splatterplot
+    // mode
     if (checkIfPeaksWorkspaceIsAlreadyBeingTracked(src)) {
       QMessageBox::warning(this, QApplication::tr("Duplicate Peaks Workspace"),
-                           QApplication::tr("You cannot load the same "\
-                                          "Peaks Workpsace multiple times."));
+                           QApplication::tr("You cannot load the same "
+                                            "Peaks Workpsace multiple times."));
       builder->destroy(src);
       pqActiveObjects::instance().setActiveSource(this->m_splatSource);
       return;
@@ -204,81 +182,64 @@ void SplatterPlotView::render()
     setPeakSourceFrame(src);
     renderType = "Wireframe";
     // Start listening if the source was destroyed
-    QObject::connect(src, SIGNAL(destroyed()), 
-                     this, SLOT(onPeakSourceDestroyed()));
+    QObject::connect(src, SIGNAL(destroyed()), this,
+                     SLOT(onPeakSourceDestroyed()));
     setPeakButton(true);
   }
 
   // Show the data
   src->updatePipeline();
-  pqDataRepresentation *drep = builder->createDataRepresentation(\
-           src->getOutputPort(0), this->m_view);
+  pqDataRepresentation *drep =
+      builder->createDataRepresentation(src->getOutputPort(0), this->m_view);
   vtkSMPropertyHelper(drep->getProxy(), "Representation").Set(renderType);
-  if (!isPeaksWorkspace)
-  {
+  if (!isPeaksWorkspace) {
     vtkSMPropertyHelper(drep->getProxy(), "Opacity").Set(0.5);
     vtkSMPropertyHelper(drep->getProxy(), "GaussianRadius").Set(0.005);
   } else {
     vtkSMPropertyHelper(drep->getProxy(), "LineWidth").Set(2);
   }
   drep->getProxy()->UpdateVTKObjects();
-  if (!isPeaksWorkspace)
-  {
+  if (!isPeaksWorkspace) {
     vtkSMPVRepresentationProxy::SetScalarColoring(
         drep->getProxy(), "signal", vtkDataObject::FIELD_ASSOCIATION_POINTS);
     drep->getProxy()->UpdateVTKObjects();
   }
 
   this->resetDisplay();
-  if (this->m_peaksSource.isEmpty())
-  {
-    //this->setAutoColorScale();
-  }
-  else
-  {
+  if (this->m_peaksSource.isEmpty()) {
+    // this->setAutoColorScale();
+  } else {
     this->renderAll();
   }
 
   // Add m_peaksSource to the peak controller and the peak filter
-  if (isPeaksWorkspace)
-  {
-    try
-    {
-      m_peaksTableController->updatePeaksWorkspaces(this->m_peaksSource, this->m_splatSource);
-      
-      if (m_peaksFilter)
-      {
-       updatePeaksFilter(m_peaksFilter);
+  if (isPeaksWorkspace) {
+    try {
+      m_peaksTableController->updatePeaksWorkspaces(this->m_peaksSource,
+                                                    this->m_splatSource);
+
+      if (m_peaksFilter) {
+        updatePeaksFilter(m_peaksFilter);
       }
-    }
-    catch (...)
-    {
+    } catch (...) {
       setPeakButton(false);
     }
   }
 
   emit this->triggerAccept();
-  if (vtkSMProxy* viewProxy = this->getView()->getProxy())
-    {
+  if (vtkSMProxy *viewProxy = this->getView()->getProxy()) {
     vtkSMPropertyHelper helper(viewProxy, "InteractionMode");
-    if (helper.GetAsInt() == vtkPVRenderView::INTERACTION_MODE_2D)
-      {
+    if (helper.GetAsInt() == vtkPVRenderView::INTERACTION_MODE_2D) {
       helper.Set(vtkPVRenderView::INTERACTION_MODE_3D);
-      viewProxy->UpdateProperty("InteractionMode",1);
+      viewProxy->UpdateProperty("InteractionMode", 1);
       this->resetCamera();
-      }
     }
+  }
 }
 
-void SplatterPlotView::renderAll()
-{
-  this->m_view->render();
-}
+void SplatterPlotView::renderAll() { this->m_view->render(); }
 
-void SplatterPlotView::resetDisplay()
-{
-  this->m_view->resetDisplay();
-}
+void SplatterPlotView::resetDisplay() { this->m_view->resetDisplay(); }
 
 /**
  * This function checks to see if the Override PC button has been
@@ -286,47 +247,45 @@ void SplatterPlotView::resetDisplay()
  * that the coordniates are matched back to the MD workspace.
  * @param state : true is button is checked, false if not
  */
-void SplatterPlotView::onOverridePeakCoordToggled(bool state)
-{
-  if (!state)
-  {
+void SplatterPlotView::onOverridePeakCoordToggled(bool state) {
+  if (!state) {
     this->checkPeaksCoordinates();
     emit this->triggerAccept();
   }
 }
 
-void SplatterPlotView::checkPeaksCoordinates()
-{
+void SplatterPlotView::checkPeaksCoordinates() {
   if (!this->m_peaksSource.isEmpty() &&
-      !this->m_ui.overridePeakCoordsButton->isChecked())
-  {
-
-    int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(),
-                                             MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates.toAscii().constData()).GetAsInt();
+      !this->m_ui.overridePeakCoordsButton->isChecked()) {
+
+    int peakViewCoords =
+        vtkSMPropertyHelper(
+            this->origSrc->getProxy(),
+            MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates
+                .toAscii()
+                .constData()).GetAsInt();
     // Make commensurate with vtkPeakMarkerFactory
     peakViewCoords--;
 
-    foreach(pqPipelineSource *src, this->m_peaksSource)
-    {
-      vtkSMPropertyHelper(src->getProxy(),
-                          MantidQt::API::MdConstants::PeakDimensions.toAscii().constData()).Set(peakViewCoords);
+    foreach (pqPipelineSource *src, this->m_peaksSource) {
+      vtkSMPropertyHelper(
+          src->getProxy(),
+          MantidQt::API::MdConstants::PeakDimensions.toAscii().constData())
+          .Set(peakViewCoords);
       src->getProxy()->UpdateVTKObjects();
     }
   }
 }
 
-void SplatterPlotView::onThresholdButtonClicked()
-{
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-  this->m_threshSource = builder->createFilter("filters", MantidQt::API::MdConstants::Threshold,
-                                             this->m_splatSource);
+void SplatterPlotView::onThresholdButtonClicked() {
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+  this->m_threshSource = builder->createFilter(
+      "filters", MantidQt::API::MdConstants::Threshold, this->m_splatSource);
   emit this->lockColorControls();
 }
 
-void SplatterPlotView::checkView(ModeControlWidget::Views initialView)
-{
-  if (!this->m_noOverlay && this->m_peaksSource.isEmpty())
-  {
+void SplatterPlotView::checkView(ModeControlWidget::Views initialView) {
+  if (!this->m_noOverlay && this->m_peaksSource.isEmpty()) {
     ViewBase::checkView(initialView);
   }
   this->m_noOverlay = false;
@@ -337,44 +296,35 @@ void SplatterPlotView::checkView(ModeControlWidget::Views initialView)
  * probe filter for use in pick mode.
  * @param state : True if button is toggled, false if not
  */
-void SplatterPlotView::onPickModeToggled(bool state)
-{
+void SplatterPlotView::onPickModeToggled(bool state) {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-  if (state)
-  {
+  if (state) {
     pqPipelineSource *src = NULL;
-    if (NULL != this->m_threshSource)
-    {
+    if (NULL != this->m_threshSource) {
       src = this->m_threshSource;
-    }
-    else
-    {
+    } else {
       src = this->m_splatSource;
     }
-    this->m_probeSource = builder->createFilter("filters", MantidQt::API::MdConstants::ProbePoint, src);
+    this->m_probeSource = builder->createFilter(
+        "filters", MantidQt::API::MdConstants::ProbePoint, src);
     emit this->triggerAccept();
-  }
-  else
-  {
+  } else {
     builder->destroy(this->m_probeSource);
   }
   emit this->toggleOrthographicProjection(state);
   this->onParallelProjection(state);
 }
 
-void SplatterPlotView::resetCamera()
-{
-  this->m_view->resetCamera();
-}
+void SplatterPlotView::resetCamera() { this->m_view->resetCamera(); }
 
-void SplatterPlotView::destroyPeakSources()
-{
+void SplatterPlotView::destroyPeakSources() {
   // First remove the peaks table, since it makes use of the peaks workspace.
   onRemovePeaksTable();
 
   pqServer *server = pqActiveObjects::instance().activeServer();
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
@@ -387,39 +337,36 @@ void SplatterPlotView::destroyPeakSources()
   this->m_peaksSource.clear();
 }
 
-
 /**
  * This function reads the coordinates from the probe point plugin and
  * passes them on to a listening serivce that will handle them in the
  * appropriate manner.
  */
-void SplatterPlotView::readAndSendCoordinates()
-{
+void SplatterPlotView::readAndSendCoordinates() {
   QList<vtkSMProxy *> pList = this->m_probeSource->getHelperProxies("Source");
-  vtkSMDoubleVectorProperty *coords = vtkSMDoubleVectorProperty::SafeDownCast(\
-        pList[0]->GetProperty("Center"));
+  vtkSMDoubleVectorProperty *coords =
+      vtkSMDoubleVectorProperty::SafeDownCast(pList[0]->GetProperty("Center"));
 
-  if (NULL != coords)
-  {
+  if (NULL != coords) {
     // Get coordinate type
-    int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(),
-                                             MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates.toAscii().constData()).GetAsInt();
+    int peakViewCoords =
+        vtkSMPropertyHelper(
+            this->origSrc->getProxy(),
+            MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates
+                .toAscii()
+                .constData()).GetAsInt();
     // Make commensurate with vtkPeakMarkerFactory
     peakViewCoords--;
 
-    if (peakViewCoords < vtkPeakMarkerFactory::Peak_in_HKL)
-    {
+    if (peakViewCoords < vtkPeakMarkerFactory::Peak_in_HKL) {
       // For Qlab and Qsample coordinate data
       // Qlab needs to be true, but enum is 0
       bool coordType = !(static_cast<bool>(peakViewCoords));
-      SelectionNotificationService::Instance().sendQPointSelection(coordType,
-                                                                   coords->GetElement(0),
-                                                                   coords->GetElement(1),
-                                                                   coords->GetElement(2));
+      SelectionNotificationService::Instance().sendQPointSelection(
+          coordType, coords->GetElement(0), coords->GetElement(1),
+          coords->GetElement(2));
     }
-  }
-  else
-  {
+  } else {
     return;
   }
 }
@@ -427,10 +374,9 @@ void SplatterPlotView::readAndSendCoordinates()
 /**
  * Set up the buttons for the visible peaks.
  */
-void SplatterPlotView::setupVisiblePeaksButtons()
-{
+void SplatterPlotView::setupVisiblePeaksButtons() {
   // Populate the rebin button
-  QMenu* peaksMenu = new QMenu(this->m_ui.peaksButton);
+  QMenu *peaksMenu = new QMenu(this->m_ui.peaksButton);
 
   m_allPeaksAction = new QAction("Show all peaks in table", peaksMenu);
   m_allPeaksAction->setIconVisibleInMenu(false);
@@ -445,78 +391,70 @@ void SplatterPlotView::setupVisiblePeaksButtons()
   this->m_ui.peaksButton->setMenu(peaksMenu);
   setPeakButton(false);
 
-  QObject::connect(m_allPeaksAction, SIGNAL(triggered()),
-                   this, SLOT(onShowAllPeaksTable()), Qt::QueuedConnection);
+  QObject::connect(m_allPeaksAction, SIGNAL(triggered()), this,
+                   SLOT(onShowAllPeaksTable()), Qt::QueuedConnection);
 
-  QObject::connect(m_removePeaksAction, SIGNAL(triggered()),
-                   this, SLOT(onRemovePeaksTable()), Qt::QueuedConnection);
+  QObject::connect(m_removePeaksAction, SIGNAL(triggered()), this,
+                   SLOT(onRemovePeaksTable()), Qt::QueuedConnection);
 }
 
-
 /**
- * On show all peaks 
+ * On show all peaks
  */
-void SplatterPlotView::onShowAllPeaksTable()
-{
+void SplatterPlotView::onShowAllPeaksTable() {
   createPeaksFilter();
 
-  if (m_peaksTableController->hasPeaks())
-  {
-     m_peaksTableController->showFullTable();
-     m_peaksTableController->show();
+  if (m_peaksTableController->hasPeaks()) {
+    m_peaksTableController->showFullTable();
+    m_peaksTableController->show();
   }
 }
 
-
 /**
  * Remove the visible peaks table.
  */
-void SplatterPlotView::onRemovePeaksTable()
-{
-  if (m_peaksTableController->hasPeaks())
-  {
+void SplatterPlotView::onRemovePeaksTable() {
+  if (m_peaksTableController->hasPeaks()) {
     m_peaksTableController->removeTable();
   }
 
-  if (m_peaksFilter)
-  {
+  if (m_peaksFilter) {
     this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
   }
 }
 
-
 /**
  * Create the peaks filter
  */
-void SplatterPlotView::createPeaksFilter()
-{
+void SplatterPlotView::createPeaksFilter() {
   // If the peaks filter already exists, then stay idle.
-  if (m_peaksFilter)
-  {
+  if (m_peaksFilter) {
     return;
   }
 
   // If the there is no peaks workspace, then stay idle.
-  if (m_peaksSource.isEmpty())
-  {
+  if (m_peaksSource.isEmpty()) {
     return;
   }
 
   // Create the peak filter
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
 
-  // Set the peaks workspace name. We need to trigger accept in order to log the workspace in the filter
-  try
-  {
-    m_peaksFilter = builder->createFilter("filters",MantidQt::API::MdConstants::MantidParaViewPeaksFilter, this->m_splatSource);
-    QObject::connect(m_peaksFilter, SIGNAL(destroyed()),
-                     this, SLOT(onPeaksFilterDestroyed()));
+  // Set the peaks workspace name. We need to trigger accept in order to log the
+  // workspace in the filter
+  try {
+    m_peaksFilter = builder->createFilter(
+        "filters", MantidQt::API::MdConstants::MantidParaViewPeaksFilter,
+        this->m_splatSource);
+    QObject::connect(m_peaksFilter, SIGNAL(destroyed()), this,
+                     SLOT(onPeaksFilterDestroyed()));
 
     // Setup the peaks filter
     updatePeaksFilter(m_peaksFilter);
 
-    // Create point representation of the source and set the point size 
-    pqDataRepresentation *dataRepresentation  = m_peaksFilter->getRepresentation(this->m_view);
+    // Create point representation of the source and set the point size
+    pqDataRepresentation *dataRepresentation =
+        m_peaksFilter->getRepresentation(this->m_view);
     vtkSMPropertyHelper(dataRepresentation->getProxy(), "Representation")
         .Set("Point Gaussian");
     vtkSMPropertyHelper(dataRepresentation->getProxy(), "GaussianRadius")
@@ -524,8 +462,7 @@ void SplatterPlotView::createPeaksFilter()
     vtkSMPropertyHelper(dataRepresentation->getProxy(), "Opacity").Set(0.5);
     dataRepresentation->getProxy()->UpdateVTKObjects();
 
-    if (!this->isPeaksWorkspace(this->origSrc))
-    {
+    if (!this->isPeaksWorkspace(this->origSrc)) {
       vtkSMPVRepresentationProxy::SetScalarColoring(
           dataRepresentation->getProxy(), "signal",
           vtkDataObject::FIELD_ASSOCIATION_POINTS);
@@ -534,11 +471,9 @@ void SplatterPlotView::createPeaksFilter()
     this->resetDisplay();
     this->setVisibilityListener();
     this->renderAll();
-  } catch(std::runtime_error &ex)
-  {
+  } catch (std::runtime_error &ex) {
     // Destroy peak filter
-    if (m_peaksFilter)
-    {
+    if (m_peaksFilter) {
       this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
     }
     g_log.warning() << ex.what();
@@ -548,13 +483,13 @@ void SplatterPlotView::createPeaksFilter()
 /* On peaks source destroyed
  * @param source The reference to the destroyed source
  */
-void SplatterPlotView::onPeakSourceDestroyed()
-{
+void SplatterPlotView::onPeakSourceDestroyed() {
   // For each peak Source check if there is a "true" source available.
   // If it is not availble then remove it from the peakSource storage.
   for (auto it = m_peaksSource.begin(); it != m_peaksSource.end();) {
     pqServer *server = pqActiveObjects::instance().activeServer();
-    pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+    pqServerManagerModel *smModel =
+        pqApplicationCore::instance()->getServerManagerModel();
     const QList<pqPipelineSource *> sources =
         smModel->findItems<pqPipelineSource *>(server);
 
@@ -567,29 +502,24 @@ void SplatterPlotView::onPeakSourceDestroyed()
     }
   }
 
-  if (m_peaksSource.isEmpty())
-  {
+  if (m_peaksSource.isEmpty()) {
     setPeakButton(false);
   }
 
-  // Update the availbale peaksTableController with the available workspaces 
+  // Update the availbale peaksTableController with the available workspaces
   m_peaksTableController->updatePeaksWorkspaces(m_peaksSource, m_splatSource);
-  
+
   // Update the peaks filter
-  try
-  {  
+  try {
     updatePeaksFilter(m_peaksFilter);
-  }
-  catch(std::runtime_error &ex)
-  {
+  } catch (std::runtime_error &ex) {
     g_log.warning() << ex.what();
   }
 
   // Set an active source
   if (m_peaksSource.isEmpty()) {
     pqActiveObjects::instance().setActiveSource(this->m_splatSource);
-  }
-  else {
+  } else {
     pqActiveObjects::instance().setActiveSource(this->m_peaksSource[0]);
   }
 }
@@ -598,8 +528,7 @@ void SplatterPlotView::onPeakSourceDestroyed()
  * Sets the visibility of the peak button.
  * @param state The visibility state of the peak button.
  */
-void SplatterPlotView::setPeakButton(bool state)
-{
+void SplatterPlotView::setPeakButton(bool state) {
   this->m_ui.peaksButton->setEnabled(state);
 }
 
@@ -607,25 +536,37 @@ void SplatterPlotView::setPeakButton(bool state)
  * Set the frame of the peak source
  * @param source The peak source
  */
-void SplatterPlotView::setPeakSourceFrame(pqPipelineSource* source)
-{
-  int peakViewCoords = vtkSMPropertyHelper(this->origSrc->getProxy(),
-                                           MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates.toAscii().constData()).GetAsInt();
+void SplatterPlotView::setPeakSourceFrame(pqPipelineSource *source) {
+  int peakViewCoords =
+      vtkSMPropertyHelper(
+          this->origSrc->getProxy(),
+          MantidQt::API::MdConstants::MantidParaViewSpecialCoordinates.toAscii()
+              .constData()).GetAsInt();
   peakViewCoords--;
-  vtkSMPropertyHelper(source->getProxy(),
-                      MantidQt::API::MdConstants::PeakDimensions.toAscii().constData()).Set(peakViewCoords);
+  vtkSMPropertyHelper(
+      source->getProxy(),
+      MantidQt::API::MdConstants::PeakDimensions.toAscii().constData())
+      .Set(peakViewCoords);
 }
 
 /**
  * Check if a peaks workspace is already tracked by the m_peaksSource list.
  */
-bool SplatterPlotView::checkIfPeaksWorkspaceIsAlreadyBeingTracked(pqPipelineSource* source) {
+bool SplatterPlotView::checkIfPeaksWorkspaceIsAlreadyBeingTracked(
+    pqPipelineSource *source) {
   bool isContained = false;
-  std::string sourceName(vtkSMPropertyHelper(source->getProxy(),
-                                             MantidQt::API::MdConstants::WorkspaceName.toAscii().constData()).GetAsString());
-  for (QList<QPointer<pqPipelineSource>>::Iterator it = m_peaksSource.begin(); it != m_peaksSource.end(); ++it) {
-    std::string trackedName(vtkSMPropertyHelper((*it)->getProxy(),
-                                                MantidQt::API::MdConstants::WorkspaceName.toAscii().constData()).GetAsString());
+  std::string sourceName(
+      vtkSMPropertyHelper(
+          source->getProxy(),
+          MantidQt::API::MdConstants::WorkspaceName.toAscii().constData())
+          .GetAsString());
+  for (QList<QPointer<pqPipelineSource>>::Iterator it = m_peaksSource.begin();
+       it != m_peaksSource.end(); ++it) {
+    std::string trackedName(
+        vtkSMPropertyHelper(
+            (*it)->getProxy(),
+            MantidQt::API::MdConstants::WorkspaceName.toAscii().constData())
+            .GetAsString());
     if ((*it == source) || (sourceName == trackedName)) {
       isContained = true;
       break;
@@ -635,11 +576,12 @@ bool SplatterPlotView::checkIfPeaksWorkspaceIsAlreadyBeingTracked(pqPipelineSour
 }
 
 /**
- * Updates the peaks filter, i.e. supplies the filter with a list of peaks workspaces and delimiter
+ * Updates the peaks filter, i.e. supplies the filter with a list of peaks
+ * workspaces and delimiter
  * @param filter The peaks filter.
  */
-void SplatterPlotView::updatePeaksFilter(pqPipelineSource* filter) {
-  if (!filter){
+void SplatterPlotView::updatePeaksFilter(pqPipelineSource *filter) {
+  if (!filter) {
     return;
   }
 
@@ -647,36 +589,40 @@ void SplatterPlotView::updatePeaksFilter(pqPipelineSource* filter) {
 
   if (m_peaksSource.isEmpty()) {
     this->destroyFilter(MantidQt::API::MdConstants::MDPeaksFilter);
-  }
-  else {
-    std::string workspaceNamesConcatentated = m_peaksTableController->getConcatenatedWorkspaceNames(m_peaksWorkspaceNameDelimiter);
-    if (workspaceNamesConcatentated.empty())
-    {
-      throw std::runtime_error("The peaks viewer does not contain a valid peaks workspace.");
+  } else {
+    std::string workspaceNamesConcatentated =
+        m_peaksTableController->getConcatenatedWorkspaceNames(
+            m_peaksWorkspaceNameDelimiter);
+    if (workspaceNamesConcatentated.empty()) {
+      throw std::runtime_error(
+          "The peaks viewer does not contain a valid peaks workspace.");
     }
 
-    vtkSMPropertyHelper(filter->getProxy(),
-                        MantidQt::API::MdConstants::PeaksWorkspace.toAscii().constData())
+    vtkSMPropertyHelper(
+        filter->getProxy(),
+        MantidQt::API::MdConstants::PeaksWorkspace.toAscii().constData())
         .Set(0, workspaceNamesConcatentated.c_str());
-    vtkSMPropertyHelper(filter->getProxy(),
-                        MantidQt::API::MdConstants::PeaksWorkspace.toAscii().constData())
+    vtkSMPropertyHelper(
+        filter->getProxy(),
+        MantidQt::API::MdConstants::PeaksWorkspace.toAscii().constData())
         .Set(1, m_peaksWorkspaceNameDelimiter.c_str());
     emit this->triggerAccept();
     filter->updatePipeline();
     this->resetCamera();
-  }  
+  }
 }
 
 /**
- * Reacts to a destroyed peaks filter, mainly for setting the peak filter pointer to NULL.
- * We need to do this, since PV can destroy the filter in a general destorySources command.
+ * Reacts to a destroyed peaks filter, mainly for setting the peak filter
+ * pointer to NULL.
+ * We need to do this, since PV can destroy the filter in a general
+ * destorySources command.
  */
-void SplatterPlotView::onPeaksFilterDestroyed() {
-  m_peaksFilter = NULL;
-}
+void SplatterPlotView::onPeaksFilterDestroyed() { m_peaksFilter = NULL; }
 
 /**
- * Destroy all sources in the splatterplot view. We need to delete the filters before 
+ * Destroy all sources in the splatterplot view. We need to delete the filters
+ * before
  * we can delete the underlying sources
  */
 void SplatterPlotView::destroyAllSourcesInView() {
@@ -687,32 +633,26 @@ void SplatterPlotView::destroyAllSourcesInView() {
   builder->destroySources();
 }
 
-void SplatterPlotView::destroyFiltersForSplatterPlotView(){
-   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
-  if (this->m_peaksFilter)
-  {
+void SplatterPlotView::destroyFiltersForSplatterPlotView() {
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+  if (this->m_peaksFilter) {
     builder->destroy(this->m_peaksFilter);
   }
-  if (!this->m_peaksSource.isEmpty())
-  {
+  if (!this->m_peaksSource.isEmpty()) {
     this->destroyPeakSources();
     pqActiveObjects::instance().setActiveSource(this->origSrc);
   }
-  if (this->m_probeSource)
-  {
+  if (this->m_probeSource) {
     builder->destroy(this->m_probeSource);
   }
-  if (this->m_threshSource)
-  {
+  if (this->m_threshSource) {
     builder->destroy(this->m_threshSource);
   }
-  if (this->m_splatSource)
-  {
+  if (this->m_splatSource) {
     builder->destroy(this->m_splatSource);
   }
 }
 
-
 } // SimpleGui
 } // Vates
 } // Mantid
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
index 7877ca8087187363d554f5cf7461f021c3b712f9..d902724002a02f8f90a3d25fd00389965f97396f 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/StandardView.cpp
@@ -2,7 +2,7 @@
 #include "MantidVatesSimpleGuiViewWidgets/RebinnedSourcesManager.h"
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqActiveObjects.h>
@@ -21,7 +21,7 @@
 #include <vtkSMPVRepresentationProxy.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QAction>
@@ -32,28 +32,25 @@
 #include <QString>
 #include <QToolTip>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  * Simple class for a QMenu where the actions do show their tool tip
  * strings (this does not happen by default with standard QMenu).
  */
-class QMenuWithToolTip: public QMenu {
+class QMenuWithToolTip : public QMenu {
 public:
   explicit QMenuWithToolTip(QWidget *parent) : QMenu(parent) {}
 
   bool event(QEvent *e) override {
     if (QEvent::ToolTip == e->type()) {
       // grab the action specific tooltip
-      QHelpEvent *he = dynamic_cast<QHelpEvent*>(e);
+      QHelpEvent *he = dynamic_cast<QHelpEvent *>(e);
       if (!he)
         return false;
-      QAction* a = actionAt(he->pos());
+      QAction *a = actionAt(he->pos());
       if (a && a->toolTip() != a->text()) {
         QToolTip::showText(he->globalPos(), a->toolTip(), this);
         return true;
@@ -74,12 +71,14 @@ QString StandardView::g_sliceMDLbl = "Complete (" + g_sliceMDName + ")";
 QString StandardView::g_cutMDLbl = "Horace style (" + g_cutMDName + ")";
 
 const QString tipBefore = "Run the ";
-const QString tipAfter = " Mantid algorithm (the algorithm dialog will show up)";
+const QString tipAfter =
+    " Mantid algorithm (the algorithm dialog will show up)";
 QString StandardView::g_binMDToolTipTxt = tipBefore + g_binMDName + tipAfter;
-QString StandardView::g_sliceMDToolTipTxt = tipBefore + g_sliceMDName + tipAfter;
+QString StandardView::g_sliceMDToolTipTxt =
+    tipBefore + g_sliceMDName + tipAfter;
 QString StandardView::g_cutMDToolTipTxt = tipBefore + g_cutMDName + tipAfter;
-const std::string StandardView::SurfaceRepresentation  = "Surface";
-const std::string StandardView::WireFrameRepresentation  = "Wireframe";
+const std::string StandardView::SurfaceRepresentation = "Surface";
+const std::string StandardView::WireFrameRepresentation = "Wireframe";
 
 // To map action labels to algorithm names
 QMap<QString, QString> StandardView::g_actionToAlgName;
@@ -90,12 +89,10 @@ QMap<QString, QString> StandardView::g_actionToAlgName;
  * @param parent the parent widget for the standard view
  * @param rebinnedSourcesManager Pointer to a RebinnedSourcesManager
  */
-  StandardView::StandardView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) : ViewBase(parent, rebinnedSourcesManager),
-                                                                 m_binMDAction(NULL),
-                                                                 m_sliceMDAction(NULL),
-                                                                 m_cutMDAction(NULL),
-                                                                 m_unbinAction(NULL)
-{
+StandardView::StandardView(QWidget *parent,
+                           RebinnedSourcesManager *rebinnedSourcesManager)
+    : ViewBase(parent, rebinnedSourcesManager), m_binMDAction(NULL),
+      m_sliceMDAction(NULL), m_cutMDAction(NULL), m_unbinAction(NULL) {
   this->m_ui.setupUi(this);
   this->m_cameraReset = false;
 
@@ -114,35 +111,32 @@ QMap<QString, QString> StandardView::g_actionToAlgName;
                    SLOT(onCutButtonClicked()));
 
   // Listen to a change in the active source, to adapt our rebin buttons
-  QObject::connect(&pqActiveObjects::instance(), SIGNAL(sourceChanged(pqPipelineSource*)),
-                   this, SLOT(activeSourceChangeListener(pqPipelineSource*)));
+  QObject::connect(&pqActiveObjects::instance(),
+                   SIGNAL(sourceChanged(pqPipelineSource *)), this,
+                   SLOT(activeSourceChangeListener(pqPipelineSource *)));
 
   // Set the scale button to create the ScaleWorkspace operator
-  QObject::connect(this->m_ui.scaleButton, SIGNAL(clicked()),
-                   this, SLOT(onScaleButtonClicked()));
+  QObject::connect(this->m_ui.scaleButton, SIGNAL(clicked()), this,
+                   SLOT(onScaleButtonClicked()));
 
   this->m_view = this->createRenderView(this->m_ui.renderFrame);
 
-  QObject::connect(this->m_view.data(), SIGNAL(endRender()),
-                   this, SLOT(onRenderDone()));
-
-
+  QObject::connect(this->m_view.data(), SIGNAL(endRender()), this,
+                   SLOT(onRenderDone()));
 }
 
-StandardView::~StandardView()
-{
-}
+StandardView::~StandardView() {}
 
-void StandardView::setupViewButtons()
-{
+void StandardView::setupViewButtons() {
 
   // Populate the rebin button
-  QMenuWithToolTip* rebinMenu = new QMenuWithToolTip(this->m_ui.rebinToolButton);
+  QMenuWithToolTip *rebinMenu =
+      new QMenuWithToolTip(this->m_ui.rebinToolButton);
 
   m_binMDAction = new QAction(g_binMDLbl, rebinMenu);
   m_binMDAction->setToolTip(g_binMDToolTipTxt);
   m_binMDAction->setIconVisibleInMenu(false);
-  
+
   m_sliceMDAction = new QAction(g_sliceMDLbl, rebinMenu);
   m_sliceMDAction->setToolTip(g_sliceMDToolTipTxt);
   m_sliceMDAction->setIconVisibleInMenu(false);
@@ -162,63 +156,53 @@ void StandardView::setupViewButtons()
   this->m_ui.rebinToolButton->setPopupMode(QToolButton::InstantPopup);
   this->m_ui.rebinToolButton->setMenu(rebinMenu);
 
-  QObject::connect(m_binMDAction, SIGNAL(triggered()),
-                   this, SLOT(onRebin()), Qt::QueuedConnection);
-  QObject::connect(m_sliceMDAction, SIGNAL(triggered()),
-                   this, SLOT(onRebin()), Qt::QueuedConnection);
-  QObject::connect(m_cutMDAction, SIGNAL(triggered()),
-                   this, SLOT(onRebin()), Qt::QueuedConnection);
+  QObject::connect(m_binMDAction, SIGNAL(triggered()), this, SLOT(onRebin()),
+                   Qt::QueuedConnection);
+  QObject::connect(m_sliceMDAction, SIGNAL(triggered()), this, SLOT(onRebin()),
+                   Qt::QueuedConnection);
+  QObject::connect(m_cutMDAction, SIGNAL(triggered()), this, SLOT(onRebin()),
+                   Qt::QueuedConnection);
   // Set the unbinbutton to remove the rebinning on a workspace
   // which was binned in the VSI
-  QObject::connect(m_unbinAction, SIGNAL(triggered()),
-                   this, SIGNAL(unbin()), Qt::QueuedConnection);
-
+  QObject::connect(m_unbinAction, SIGNAL(triggered()), this, SIGNAL(unbin()),
+                   Qt::QueuedConnection);
 }
 
-void StandardView::destroyView()
-{
+void StandardView::destroyView() {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   this->destroyFilter(QString("Slice"));
   builder->destroy(this->m_view);
 }
 
-pqRenderView* StandardView::getView()
-{
-  return this->m_view.data();
-}
+pqRenderView *StandardView::getView() { return this->m_view.data(); }
 
-void StandardView::render()
-{
+void StandardView::render() {
   this->origSrc = pqActiveObjects::instance().activeSource();
-  if (NULL == this->origSrc)
-  {
+  if (NULL == this->origSrc) {
     return;
   }
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   activeSourceChangeListener(this->origSrc);
 
-  if (this->isPeaksWorkspace(this->origSrc))
-  {
+  if (this->isPeaksWorkspace(this->origSrc)) {
     this->m_ui.cutButton->setEnabled(false);
   }
 
   // Show the data
-  pqDataRepresentation *drep = builder->createDataRepresentation(\
-        this->origSrc->getOutputPort(0), this->m_view);
+  pqDataRepresentation *drep = builder->createDataRepresentation(
+      this->origSrc->getOutputPort(0), this->m_view);
   std::string reptype = StandardView::SurfaceRepresentation;
-  if (this->isPeaksWorkspace(this->origSrc))
-  {
+  if (this->isPeaksWorkspace(this->origSrc)) {
     reptype = StandardView::WireFrameRepresentation;
   }
   vtkSMPropertyHelper(drep->getProxy(), "Representation").Set(reptype.c_str());
   drep->getProxy()->UpdateVTKObjects();
-  this->origRep = qobject_cast<pqPipelineRepresentation*>(drep);
-  if (!this->isPeaksWorkspace(this->origSrc))
-  {
-    vtkSMPVRepresentationProxy::SetScalarColoring(drep->getProxy(), "signal",
-                                                  vtkDataObject::FIELD_ASSOCIATION_CELLS);
-    //drep->getProxy()->UpdateVTKObjects();
-    //vtkSMPVRepresentationProxy::RescaleTransferFunctionToDataRange(drep->getProxy(),
+  this->origRep = qobject_cast<pqPipelineRepresentation *>(drep);
+  if (!this->isPeaksWorkspace(this->origSrc)) {
+    vtkSMPVRepresentationProxy::SetScalarColoring(
+        drep->getProxy(), "signal", vtkDataObject::FIELD_ASSOCIATION_CELLS);
+    // drep->getProxy()->UpdateVTKObjects();
+    // vtkSMPVRepresentationProxy::RescaleTransferFunctionToDataRange(drep->getProxy(),
     //                                                               "signal",
     //                                                               vtkDataObject::FIELD_ASSOCIATION_CELLS);
     drep->getProxy()->UpdateVTKObjects();
@@ -275,28 +259,21 @@ void StandardView::onScaleButtonClicked() {
  * This function is responsible for calling resetCamera if the internal
  * variable cameraReset has been set to true.
  */
-void StandardView::onRenderDone()
-{
-  if (this->m_cameraReset)
-  {
+void StandardView::onRenderDone() {
+  if (this->m_cameraReset) {
     this->resetCamera();
     this->m_cameraReset = false;
   }
 }
 
-void StandardView::renderAll()
-{
-  this->m_view->render();
-}
+void StandardView::renderAll() { this->m_view->render(); }
 
-void StandardView::resetDisplay()
-{
+void StandardView::resetDisplay() {
   this->m_view->resetDisplay();
   this->m_view->forceRender();
 }
 
-void StandardView::resetCamera()
-{
+void StandardView::resetCamera() {
   this->m_view->resetCamera();
   this->m_view->forceRender();
 }
@@ -304,35 +281,26 @@ void StandardView::resetCamera()
 /**
  * This function enables the cut button for the standard view.
  */
-void StandardView::updateUI()
-{
-  this->m_ui.cutButton->setEnabled(true);
-}
+void StandardView::updateUI() { this->m_ui.cutButton->setEnabled(true); }
 
-void StandardView::updateView()
-{
-  this->m_cameraReset = true;
-}
-
-void StandardView::closeSubWindows()
-{
-}
+void StandardView::updateView() { this->m_cameraReset = true; }
 
+void StandardView::closeSubWindows() {}
 
 /**
  * Check if the rebin and unbin buttons should be visible
  * Note that for a rebin button to be visible there may be no
- * MDHisto workspaces present, yet  MDHisto workspaces which result from 
+ * MDHisto workspaces present, yet  MDHisto workspaces which result from
  * rebinning within the VSI are allowed.
  */
-void StandardView::setRebinAndUnbinButtons()
-{
+void StandardView::setRebinAndUnbinButtons() {
   unsigned int numberOfInternallyRebinnedWorkspaces = 0;
   unsigned int numberOfTrueMDHistoWorkspaces = 0;
   unsigned int numberOfPeakWorkspaces = 0;
 
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
@@ -346,21 +314,22 @@ void StandardView::setRebinAndUnbinButtons()
     }
   }
 
-  // If there are any true MDHisto workspaces then the rebin button should be disabled
-  bool allowRebinning = numberOfTrueMDHistoWorkspaces > 0 || numberOfPeakWorkspaces > 0;
+  // If there are any true MDHisto workspaces then the rebin button should be
+  // disabled
+  bool allowRebinning =
+      numberOfTrueMDHistoWorkspaces > 0 || numberOfPeakWorkspaces > 0;
   this->allowRebinningOptions(allowRebinning);
 
-  // If there are no internally rebinned workspaces the button should be disabled.
+  // If there are no internally rebinned workspaces the button should be
+  // disabled.
   allowUnbinOption(numberOfInternallyRebinnedWorkspaces > 0);
 }
 
-
 /**
  * Reacts to the user selecting the BinMD algorithm
- */ 
-void StandardView::onRebin()
-{
-  if(QAction* action = dynamic_cast<QAction*>(sender())) {
+ */
+void StandardView::onRebin() {
+  if (QAction *action = dynamic_cast<QAction *>(sender())) {
     // split always returns a list of at least one element
     QString algName = getAlgNameFromMenuLabel(action->text());
     emit rebin(algName.toStdString());
@@ -368,21 +337,23 @@ void StandardView::onRebin()
 }
 
 /**
- * react to the addition of the representation and change it's type to be Surface
+ * react to the addition of the representation and change it's type to be
+ * Surface
  * @param representation : representation to modify
  */
-void StandardView::onScaleRepresentationAdded(pqPipelineSource *, pqDataRepresentation * representation, int)
-{
-    vtkSMPropertyHelper(representation->getProxy(), "Representation").Set(StandardView::SurfaceRepresentation.c_str());
+void StandardView::onScaleRepresentationAdded(
+    pqPipelineSource *, pqDataRepresentation *representation, int) {
+  vtkSMPropertyHelper(representation->getProxy(), "Representation")
+      .Set(StandardView::SurfaceRepresentation.c_str());
 }
 
 /**
 Disable rebinning options
 */
 void StandardView::allowRebinningOptions(bool allow) {
-    this->m_binMDAction->setEnabled(allow);
-    this->m_sliceMDAction->setEnabled(allow);
-    this->m_cutMDAction->setEnabled(allow);
+  this->m_binMDAction->setEnabled(allow);
+  this->m_sliceMDAction->setEnabled(allow);
+  this->m_cutMDAction->setEnabled(allow);
 }
 
 /**
@@ -392,53 +363,49 @@ void StandardView::allowUnbinOption(bool allow) {
   this->m_unbinAction->setEnabled(allow);
 }
 
-
 /**
   * Listen for a change of the active source in order to check if the
   * active source is an MDEventSource for which we allow rebinning.
   */
-void StandardView::activeSourceChangeListener(pqPipelineSource* source)
-{
+void StandardView::activeSourceChangeListener(pqPipelineSource *source) {
   // If there is no active source, then we do not allow rebinning
-  if (!source)
-  {
+  if (!source) {
     this->allowRebinningOptions(false);
     this->m_unbinAction->setEnabled(false);
     return;
   }
 
   // If it is a filter work your way down
-  pqPipelineSource* localSource = source;
-  pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(localSource);
+  pqPipelineSource *localSource = source;
+  pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(localSource);
 
-  while(filter)
-  {
+  while (filter) {
     localSource = filter->getInput(0);
-    filter = qobject_cast<pqPipelineFilter*>(localSource);
+    filter = qobject_cast<pqPipelineFilter *>(localSource);
   }
 
-  // Important to first check for an internally rebinned source, then for MDEvent source, 
+  // Important to first check for an internally rebinned source, then for
+  // MDEvent source,
   // since the internally rebinned source may be an MDEventSource.
   std::string workspaceType(localSource->getProxy()->GetXMLName());
 
-  // Check if the source is associated with a workspace which was internally rebinned by the VSI.
+  // Check if the source is associated with a workspace which was internally
+  // rebinned by the VSI.
   // In this case the user can further rebin or unbin the source.
-  if (isInternallyRebinnedWorkspace(localSource))
-  {
+  if (isInternallyRebinnedWorkspace(localSource)) {
     this->allowRebinningOptions(true);
     this->allowUnbinOption(true);
   }
-  // Check if we are dealing with a MDEvent workspace. In this case we allow rebinning, but 
+  // Check if we are dealing with a MDEvent workspace. In this case we allow
+  // rebinning, but
   // unbinning will not make a lot of sense.
-  else if (workspaceType.find("MDEW Source") != std::string::npos)
-  {
+  else if (workspaceType.find("MDEW Source") != std::string::npos) {
     this->allowRebinningOptions(true);
     this->allowUnbinOption(false);
   }
   // Otherwise we must be dealing with either a MDHIsto or PeaksWorkspace
   // which cannot be neither rebinned nor unbinned.
-  else
-  {
+  else {
     this->allowRebinningOptions(false);
     this->allowUnbinOption(false);
   }
@@ -452,15 +419,13 @@ void StandardView::activeSourceChangeListener(pqPipelineSource* source)
  * @param menuLbl label (what is shown in the action)
  * @return Name of the corresponding Mantid algorithm
  */
-QString StandardView::getAlgNameFromMenuLabel(const QString &menuLbl)
-{
+QString StandardView::getAlgNameFromMenuLabel(const QString &menuLbl) {
   QString res;
-  if (g_actionToAlgName.contains(menuLbl))
-  {
+  if (g_actionToAlgName.contains(menuLbl)) {
     res = g_actionToAlgName.value(menuLbl);
-  }
-  else {
-    // ideally an informative error would be given here but there doesn't seem to be
+  } else {
+    // ideally an informative error would be given here but there doesn't seem
+    // to be
     // a convnient way to do that in these view classes
   }
   return res;
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
index 962a116fc526c277ffadd1f32643bdb7623737f4..5a219298c53a67b009164a2f2f4e1fa8569f4b98 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/ThreesliceView.cpp
@@ -4,9 +4,8 @@
 #include "MantidKernel/Logger.h"
 #include <Poco/Path.h>
 
-
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqActiveObjects.h>
@@ -22,39 +21,31 @@
 #include <vtkSMProxy.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QMessageBox>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
-namespace
-{
-  /// Static logger
-  Kernel::Logger g_log("ThreeSliceView");
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+namespace {
+/// Static logger
+Kernel::Logger g_log("ThreeSliceView");
 }
 
-
-ThreeSliceView::ThreeSliceView(QWidget *parent, RebinnedSourcesManager* rebinnedSourcesManager) :
-  ViewBase(parent, rebinnedSourcesManager), m_mainView(), m_ui()
-{
+ThreeSliceView::ThreeSliceView(QWidget *parent,
+                               RebinnedSourcesManager *rebinnedSourcesManager)
+    : ViewBase(parent, rebinnedSourcesManager), m_mainView(), m_ui() {
   this->m_ui.setupUi(this);
   this->m_mainView = this->createRenderView(this->m_ui.mainRenderFrame,
-                                          QString("OrthographicSliceView"));
+                                            QString("OrthographicSliceView"));
   pqActiveObjects::instance().setActiveView(this->m_mainView);
 }
 
-ThreeSliceView::~ThreeSliceView()
-{
-}
+ThreeSliceView::~ThreeSliceView() {}
 
-void ThreeSliceView::destroyView()
-{
+void ThreeSliceView::destroyView() {
   pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   // Active source disappears in only this view, so set it from the
   // internal source before destroying view.
@@ -62,30 +53,24 @@ void ThreeSliceView::destroyView()
   builder->destroy(this->m_mainView);
 }
 
-pqRenderView* ThreeSliceView::getView()
-{
-  return this->m_mainView.data();
-}
+pqRenderView *ThreeSliceView::getView() { return this->m_mainView.data(); }
 
-void ThreeSliceView::render()
-{
+void ThreeSliceView::render() {
   this->makeThreeSlice();
   this->resetDisplay();
   emit this->triggerAccept();
 }
 
-void ThreeSliceView::makeThreeSlice()
-{
+void ThreeSliceView::makeThreeSlice() {
   pqPipelineSource *src = NULL;
   src = pqActiveObjects::instance().activeSource();
 
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
 
   // Do not allow overplotting PeaksWorkspaces
-  if (this->isPeaksWorkspace(src))
-  {
+  if (this->isPeaksWorkspace(src)) {
     QMessageBox::warning(this, QApplication::tr("Overplotting Warning"),
-                         QApplication::tr("Threeslice mode does not allow "\
+                         QApplication::tr("Threeslice mode does not allow "
                                           "overlay of PeaksWorkspaces"));
     // Need to destroy source since we tried to load it and set the active
     // back to something. In this case we'll choose the original source
@@ -96,22 +81,16 @@ void ThreeSliceView::makeThreeSlice()
 
   this->origSrc = src;
 
-  pqDataRepresentation *drep = builder->createDataRepresentation(\
-        this->origSrc->getOutputPort(0), this->m_mainView);
+  pqDataRepresentation *drep = builder->createDataRepresentation(
+      this->origSrc->getOutputPort(0), this->m_mainView);
   vtkSMPropertyHelper(drep->getProxy(), "Representation").Set("Slices");
   drep->getProxy()->UpdateVTKObjects();
-  this->origRep = qobject_cast<pqPipelineRepresentation*>(drep);
+  this->origRep = qobject_cast<pqPipelineRepresentation *>(drep);
 }
 
-void ThreeSliceView::renderAll()
-{
-  this->m_mainView->render();
-}
+void ThreeSliceView::renderAll() { this->m_mainView->render(); }
 
-void ThreeSliceView::resetDisplay()
-{
-  this->m_mainView->resetDisplay();
-}
+void ThreeSliceView::resetDisplay() { this->m_mainView->resetDisplay(); }
 
 /*
 void ThreeSliceView::correctVisibility()
@@ -119,17 +98,13 @@ void ThreeSliceView::correctVisibility()
   //this->correctColorScaleRange();
 }
 */
-void ThreeSliceView::correctColorScaleRange()
-{
-  QPair<double, double> range = this->origRep->getLookupTable()->getScalarRange();
+void ThreeSliceView::correctColorScaleRange() {
+  QPair<double, double> range =
+      this->origRep->getLookupTable()->getScalarRange();
   emit this->dataRange(range.first, range.second);
 }
 
-void ThreeSliceView::resetCamera()
-{
-  this->m_mainView->resetCamera();
-}
-
+void ThreeSliceView::resetCamera() { this->m_mainView->resetCamera(); }
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/TimeControlWidget.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/TimeControlWidget.cpp
index fa71a33c338330b636d7060efe6b66ab62aee7b6..aa0bda3cb00cc23db5b8a0895972e44906ccbc65 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/TimeControlWidget.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/TimeControlWidget.cpp
@@ -2,7 +2,7 @@
 
 // Have to deal with ParaView warnings and Intel compiler the hard way.
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqAnimationManager.h>
@@ -12,27 +12,21 @@
 #include <vtkSMProxy.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  * @param parent the parent widget for the time control widget
  */
-TimeControlWidget::TimeControlWidget(QWidget *parent) : QWidget(parent)
-{
-    this->ui.setupUi(this);
+TimeControlWidget::TimeControlWidget(QWidget *parent) : QWidget(parent) {
+  this->ui.setupUi(this);
 }
 
-TimeControlWidget::~TimeControlWidget()
-{
-}
+TimeControlWidget::~TimeControlWidget() {}
 
 /**
  * Function to update the animation scene with "time" information. This
@@ -44,9 +38,9 @@ TimeControlWidget::~TimeControlWidget()
  */
 void TimeControlWidget::updateAnimationControls(double timeStart,
                                                 double timeEnd,
-                                                int numTimesteps)
-{
-  pqAnimationScene *scene = pqPVApplicationCore::instance()->animationManager()->getActiveScene();
+                                                int numTimesteps) {
+  pqAnimationScene *scene =
+      pqPVApplicationCore::instance()->animationManager()->getActiveScene();
   vtkSMProxy *proxy = scene->getProxy();
   vtkSMPropertyHelper(proxy, "StartTime").Set(timeStart);
   vtkSMPropertyHelper(proxy, "EndTime").Set(timeEnd);
@@ -58,11 +52,9 @@ void TimeControlWidget::updateAnimationControls(double timeStart,
  * Function to enable or disable the entire animation controls widget.
  * @param state how to set the animation controls
  */
-void TimeControlWidget::enableAnimationControls(bool state)
-{
+void TimeControlWidget::enableAnimationControls(bool state) {
   this->setEnabled(state);
 }
-
 }
 }
 }
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp
index c9b4c09100e2feaff2ae699f7afe23c6fac8c981..5eb8c041d5852451ed38f5cbfe39423319210984 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/VatesParaViewApplication.cpp
@@ -29,104 +29,97 @@
 
 #include "vtksys/SystemTools.hxx"
 
-namespace Mantid
-{
-  namespace Vates
-  {
-    namespace SimpleGui
-    {
-      VatesParaViewApplication::VatesParaViewApplication() : m_logger("VatesParaViewApplication"), m_behaviorsSetup(false)
-      {
-        // Get the plugin path that we set in the ConfigService.
-        auto & configSvc = Kernel::ConfigService::Instance();
-        // This currently points at the top pvplugins directory and not the subdirectory.
-        // Needs tidying up!!
-        std::string pvPluginPathTop = configSvc.getPVPluginsPath();
-        if (pvPluginPathTop.empty())
-        {
-          throw std::runtime_error("pvplugins.directory key not setup.\nVates plugins will not be available.\n"
-                                   "Further use will cause the program to crash.\nPlease exit and "
-                                   "set this variable.");
-        }
-
-        Q_ASSERT(pqApplicationCore::instance()==NULL);
-
-        // Provide ParaView's application core with a path to the running executable
-        int argc = 1;
-        std::string exePath = configSvc.getPathToExecutable();
-        std::vector<char> argvConversion(exePath.begin(), exePath.end());
-        argvConversion.push_back('\0');
-        char *argv[] = {&argvConversion[0]};
-
-        m_logger.debug("Intialize pqApplicationCore with "+exePath+"\n");
-        // We need to manually set the PV_PLUGIN_PATH because it's
-        // not going to be picked up from the paraview/vtk side otherwise.
-        Poco::Path pluginsDir(pvPluginPathTop, "pvplugins");
-        m_logger.debug("Setting PV_PLUGIN_PATH="+pluginsDir.toString()+"\n");
-        vtksys::SystemTools::PutEnv("PV_PLUGIN_PATH=" + pluginsDir.toString());
-        new pqPVApplicationCore(argc, argv);
-      }
-
-      /**
-       * This function duplicates the nearly identical call in ParaView for their
-       * main program setup. This is necessary for the plugin mode since it does
-       * not have access to the QMainWindow of MantidPlot.
-       */
-      void VatesParaViewApplication::setupParaViewBehaviors()
-      {
-        if (this->m_behaviorsSetup)
-        {
-          return;
-        }
-        this->m_behaviorsSetup = true;
-        // Register ParaView interfaces.
-        pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
-
-        // * adds support for standard paraview views.
-        pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
-
-        pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
-
-        // Load plugins distributed with application.
-        pqApplicationCore::instance()->loadDistributedPlugins();
-
-        // Define application behaviors.
-        new pqQtMessageHandlerBehavior(this);
-        new pqDataTimeStepBehavior(this);
-        new pqSpreadSheetVisibilityBehavior(this);
-        new pqPipelineContextMenuBehavior(this);
-        new pqObjectPickingBehavior(this);
-        new pqDefaultViewBehavior(this);
-        new pqUndoRedoBehavior(this);
-        new pqAlwaysConnectedBehavior(this);
-        new pqCrashRecoveryBehavior(this);
-        new pqAutoLoadPluginXMLBehavior(this);
-        //new pqPluginDockWidgetsBehavior(mainWindow);
-        new pqVerifyRequiredPluginBehavior(this);
-        //new pqPluginActionGroupBehavior(mainWindow);
-        new pqFixPathsInStateFilesBehavior(this);
-        new pqCommandLineOptionsBehavior(this);
-        //new pqPersistentMainWindowStateBehavior(mainWindow);
-        new pqCollaborationBehavior(this);
-        new pqViewStreamingBehavior(this);
-        new pqPluginSettingsBehavior(this);
-        new pqModelTransformSupportBehavior(this);
-      }
-
-      VatesParaViewApplication::~VatesParaViewApplication()
-      {
-      }
-
-      VatesParaViewApplication* VatesParaViewApplication::instance()
-      {
-        static QPointer<VatesParaViewApplication> arg;
-        if (arg == NULL)
-        {
-          arg = new VatesParaViewApplication();
-        }
-        return arg;
-      }
-
-    } //SimpleGui
-  } //Vates
-} //Mantid
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
+VatesParaViewApplication::VatesParaViewApplication()
+    : m_logger("VatesParaViewApplication"), m_behaviorsSetup(false) {
+  // Get the plugin path that we set in the ConfigService.
+  auto &configSvc = Kernel::ConfigService::Instance();
+  // This currently points at the top pvplugins directory and not the
+  // subdirectory.
+  // Needs tidying up!!
+  std::string pvPluginPathTop = configSvc.getPVPluginsPath();
+  if (pvPluginPathTop.empty()) {
+    throw std::runtime_error(
+        "pvplugins.directory key not setup.\nVates plugins will not be "
+        "available.\n"
+        "Further use will cause the program to crash.\nPlease exit and "
+        "set this variable.");
+  }
+
+  Q_ASSERT(pqApplicationCore::instance() == NULL);
+
+  // Provide ParaView's application core with a path to the running executable
+  int argc = 1;
+  std::string exePath = configSvc.getPathToExecutable();
+  std::vector<char> argvConversion(exePath.begin(), exePath.end());
+  argvConversion.push_back('\0');
+  char *argv[] = {&argvConversion[0]};
+
+  m_logger.debug("Intialize pqApplicationCore with " + exePath + "\n");
+  // We need to manually set the PV_PLUGIN_PATH because it's
+  // not going to be picked up from the paraview/vtk side otherwise.
+  Poco::Path pluginsDir(pvPluginPathTop, "pvplugins");
+  m_logger.debug("Setting PV_PLUGIN_PATH=" + pluginsDir.toString() + "\n");
+  vtksys::SystemTools::PutEnv("PV_PLUGIN_PATH=" + pluginsDir.toString());
+  new pqPVApplicationCore(argc, argv);
+}
+
+/**
+ * This function duplicates the nearly identical call in ParaView for their
+ * main program setup. This is necessary for the plugin mode since it does
+ * not have access to the QMainWindow of MantidPlot.
+ */
+void VatesParaViewApplication::setupParaViewBehaviors() {
+  if (this->m_behaviorsSetup) {
+    return;
+  }
+  this->m_behaviorsSetup = true;
+  // Register ParaView interfaces.
+  pqInterfaceTracker *pgm = pqApplicationCore::instance()->interfaceTracker();
+
+  // * adds support for standard paraview views.
+  pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
+
+  pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
+
+  // Load plugins distributed with application.
+  pqApplicationCore::instance()->loadDistributedPlugins();
+
+  // Define application behaviors.
+  new pqQtMessageHandlerBehavior(this);
+  new pqDataTimeStepBehavior(this);
+  new pqSpreadSheetVisibilityBehavior(this);
+  new pqPipelineContextMenuBehavior(this);
+  new pqObjectPickingBehavior(this);
+  new pqDefaultViewBehavior(this);
+  new pqUndoRedoBehavior(this);
+  new pqAlwaysConnectedBehavior(this);
+  new pqCrashRecoveryBehavior(this);
+  new pqAutoLoadPluginXMLBehavior(this);
+  // new pqPluginDockWidgetsBehavior(mainWindow);
+  new pqVerifyRequiredPluginBehavior(this);
+  // new pqPluginActionGroupBehavior(mainWindow);
+  new pqFixPathsInStateFilesBehavior(this);
+  new pqCommandLineOptionsBehavior(this);
+  // new pqPersistentMainWindowStateBehavior(mainWindow);
+  new pqCollaborationBehavior(this);
+  new pqViewStreamingBehavior(this);
+  new pqPluginSettingsBehavior(this);
+  new pqModelTransformSupportBehavior(this);
+}
+
+VatesParaViewApplication::~VatesParaViewApplication() {}
+
+VatesParaViewApplication *VatesParaViewApplication::instance() {
+  static QPointer<VatesParaViewApplication> arg;
+  if (arg == NULL) {
+    arg = new VatesParaViewApplication();
+  }
+  return arg;
+}
+
+} // SimpleGui
+} // Vates
+} // Mantid
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
index d04fe8d2cdcf77c27373fa118eec26b7c9e9ce7f..85ca60fa148c139da47c90e6ee64cf56219a99eb 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/ViewBase.cpp
@@ -10,7 +10,7 @@
 #include "MantidVatesAPI/BoxInfo.h"
 #include "MantidKernel/WarningSuppressions.h"
 #if defined(__INTEL_COMPILER)
-  #pragma warning disable 1170
+#pragma warning disable 1170
 #endif
 
 #include <pqActiveObjects.h>
@@ -43,7 +43,7 @@
 #include <pqMultiSliceAxisWidget.h>
 
 #if defined(__INTEL_COMPILER)
-  #pragma warning enable 1170
+#pragma warning enable 1170
 #endif
 
 #include <QHBoxLayout>
@@ -53,12 +53,9 @@
 
 #include <typeinfo>
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
 /**
  * Default constructor.
@@ -77,21 +74,18 @@ ViewBase::ViewBase(QWidget *parent,
  * @param viewName the requested view type, if empty will default to RenderView
  * @return the created view
  */
-pqRenderView* ViewBase::createRenderView(QWidget* widget, QString viewName)
-{
+pqRenderView *ViewBase::createRenderView(QWidget *widget, QString viewName) {
   QHBoxLayout *hbox = new QHBoxLayout(widget);
   hbox->setMargin(0);
 
-  if (viewName == QString(""))
-  {
+  if (viewName == QString("")) {
     viewName = pqRenderView::renderViewType();
   }
 
   // Create a new render view.
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
-  pqRenderView *view = qobject_cast<pqRenderView*>(\
-        builder->createView(viewName,
-                            pqActiveObjects::instance().activeServer()));
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqRenderView *view = qobject_cast<pqRenderView *>(builder->createView(
+      viewName, pqActiveObjects::instance().activeServer()));
   pqActiveObjects::instance().setActiveView(view);
 
   // Place the widget for the render view in the frame provided.
@@ -103,14 +97,14 @@ pqRenderView* ViewBase::createRenderView(QWidget* widget, QString viewName)
  * This function removes all filters of a given name: i.e. Slice.
  * @param name the class name of the filters to remove
  */
-void ViewBase::destroyFilter(const QString &name)
-{
+void ViewBase::destroyFilter(const QString &name) {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
-  QSet<pqPipelineSource*> toDelete;
+  QSet<pqPipelineSource *> toDelete;
   foreach (pqPipelineSource *source, sources) {
     const QString sourceName = source->getSMName();
     if (sourceName.startsWith(name)) {
@@ -125,13 +119,11 @@ void ViewBase::destroyFilter(const QString &name)
  * full extent of the data.
  * @param colorSelectionWidget Pointer to the color selection widget.
  */
-void ViewBase::onAutoScale(ColorSelectionWidget* colorSelectionWidget)
-{
+void ViewBase::onAutoScale(ColorSelectionWidget *colorSelectionWidget) {
   // Update the colorUpdater
   this->colorUpdater.updateState(colorSelectionWidget);
 
-  if (this->colorUpdater.isAutoScale())
-  {
+  if (this->colorUpdater.isAutoScale()) {
     this->setAutoColorScale();
   }
 }
@@ -140,16 +132,12 @@ void ViewBase::onAutoScale(ColorSelectionWidget* colorSelectionWidget)
  * Set the color scale for auto color scaling.
  *
  */
-void ViewBase::setAutoColorScale()
-{
+void ViewBase::setAutoColorScale() {
   VsiColorScale colorScale;
 
-  try
-  {
+  try {
     colorScale = this->colorUpdater.autoScale();
-  }
-  catch (std::invalid_argument &)
-  {
+  } catch (std::invalid_argument &) {
     // Got a bad proxy or color scale range, so do nothing
     return;
   }
@@ -165,28 +153,24 @@ void ViewBase::setAutoColorScale()
  */
 void ViewBase::onColorMapChange(const Json::Value &model) {
   pqPipelineRepresentation *rep = this->getRep();
-  if (NULL == rep)
-  {
+  if (NULL == rep) {
     return;
   }
   // Work around a "bug" in pqScalarToColors::checkRange() where the lower
   // limit gets lost when log scaling is used. This only happens when
   // changing the color map.
   bool logStateChanged = false;
-  if (this->colorUpdater.isLogScale())
-  {
+  if (this->colorUpdater.isLogScale()) {
     this->colorUpdater.logScale(false);
     logStateChanged = true;
   }
   this->colorUpdater.colorMapChange(rep, model);
-  if (logStateChanged)
-  {
+  if (logStateChanged) {
     this->colorUpdater.logScale(true);
   }
   rep->renderViewEventually();
 
-  if (this->colorUpdater.isAutoScale())
-  {
+  if (this->colorUpdater.isAutoScale()) {
     setAutoColorScale();
   }
 
@@ -199,8 +183,7 @@ void ViewBase::onColorMapChange(const Json::Value &model) {
  * @param min the minimum bound for the color scale
  * @param max the maximum bound for the color scale
  */
-void ViewBase::onColorScaleChange(double min, double max)
-{
+void ViewBase::onColorScaleChange(double min, double max) {
   this->colorUpdater.colorScaleChange(min, max);
 }
 
@@ -208,18 +191,14 @@ void ViewBase::onColorScaleChange(double min, double max)
  * This function sets logarithmic color scaling on the data.
  * @param state Flag to determine whether or not to use log color scaling
  */
-void ViewBase::onLogScale(int state)
-{
-  this->colorUpdater.logScale(state);
-}
+void ViewBase::onLogScale(int state) { this->colorUpdater.logScale(state); }
 
 /**
  * This function passes the color selection widget to the color updater
  * object.
  * @param cs : Reference to the color selection widget
  */
-void ViewBase::setColorScaleState(ColorSelectionWidget *cs)
-{
+void ViewBase::setColorScaleState(ColorSelectionWidget *cs) {
   this->colorUpdater.updateState(cs);
 }
 
@@ -232,22 +211,17 @@ void ViewBase::setColorScaleState(ColorSelectionWidget *cs)
  *
  * @param colorScale A pointer to the colorscale widget.
  */
-void ViewBase::setColorsForView(ColorSelectionWidget *colorScale)
-{
+void ViewBase::setColorsForView(ColorSelectionWidget *colorScale) {
   // Update the colorupdater with the settings of the colorSelectionWidget
   setColorScaleState(colorScale);
 
-  if (this->colorUpdater.isAutoScale())
-  {
+  if (this->colorUpdater.isAutoScale()) {
     this->onAutoScale(colorScale);
-  }
-  else
-  {
+  } else {
     this->onColorScaleChange(this->colorUpdater.getMinimumRange(),
                              this->colorUpdater.getMaximumRange());
   }
-  if (this->colorUpdater.isLogScale())
-  {
+  if (this->colorUpdater.isLogScale()) {
     this->onLogScale(true);
   }
 
@@ -263,17 +237,14 @@ void ViewBase::setColorsForView(ColorSelectionWidget *colorScale)
  * @param src the pipeline source to check
  * @return true if the pipeline source is derived from PeaksWorkspace
  */
-bool ViewBase::isPeaksWorkspace(pqPipelineSource *src)
-{
-  if (NULL == src)
-  {
+bool ViewBase::isPeaksWorkspace(pqPipelineSource *src) {
+  if (NULL == src) {
     return false;
   }
-  QString wsType(vtkSMPropertyHelper(src->getProxy(),
-                                     "WorkspaceTypeName", true).GetAsString());
+  QString wsType(vtkSMPropertyHelper(src->getProxy(), "WorkspaceTypeName", true)
+                     .GetAsString());
 
-  if (wsType.isEmpty())
-  {
+  if (wsType.isEmpty()) {
     wsType = src->getSMName();
   }
   return wsType.contains("PeaksWorkspace");
@@ -284,13 +255,15 @@ bool ViewBase::isPeaksWorkspace(pqPipelineSource *src)
  * to ParaView's ActiveObjects mechanism.
  * @return the currently active representation
  */
-pqPipelineRepresentation *ViewBase::getPvActiveRep()
-{
-  pqDataRepresentation *drep = pqActiveObjects::instance().activeRepresentation();
+pqPipelineRepresentation *ViewBase::getPvActiveRep() {
+  pqDataRepresentation *drep =
+      pqActiveObjects::instance().activeRepresentation();
   return qobject_cast<pqPipelineRepresentation *>(drep);
 }
 
+// clang-format off
 GCC_DIAG_OFF(strict-aliasing)
+// clang-format on
 /**
  * This function creates a ParaView source from a given plugin name and
  * workspace name. This is used in the plugin mode of the simple interface.
@@ -299,25 +272,27 @@ GCC_DIAG_OFF(strict-aliasing)
  * @param axesGridOn: if the axes grid should be on
  * @returns a pointer to the newly created pipeline source
  */
-pqPipelineSource* ViewBase::setPluginSource(QString pluginName, QString wsName, bool axesGridOn)
-{
+pqPipelineSource *ViewBase::setPluginSource(QString pluginName, QString wsName,
+                                            bool axesGridOn) {
   // Create the source from the plugin
-  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqPipelineSource *src = builder->createSource("sources", pluginName,
-                                                server);
+  pqPipelineSource *src = builder->createSource("sources", pluginName, server);
   src->getProxy()->SetAnnotation("MdViewerWidget0", "1");
-  vtkSMPropertyHelper(src->getProxy(),
-                      "Mantid Workspace Name").Set(wsName.toStdString().c_str());
+  vtkSMPropertyHelper(src->getProxy(), "Mantid Workspace Name")
+      .Set(wsName.toStdString().c_str());
 
   // WORKAROUND BEGIN
-  // We are setting the recursion depth to 1 when we are dealing with MDEvent workspaces
-  // with top level splitting, but this is not updated in the plugin line edit field.
+  // We are setting the recursion depth to 1 when we are dealing with MDEvent
+  // workspaces
+  // with top level splitting, but this is not updated in the plugin line edit
+  // field.
   // We do this here.
-  auto workspaceProvider = Mantid::Kernel::make_unique<Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
-  if (auto split = Mantid::VATES::findRecursionDepthForTopLevelSplitting(wsName.toStdString(), std::move(workspaceProvider))) {
-    vtkSMPropertyHelper(src->getProxy(),
-              "Recursion Depth").Set(split.get());
+  auto workspaceProvider = Mantid::Kernel::make_unique<
+      Mantid::VATES::ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>>();
+  if (auto split = Mantid::VATES::findRecursionDepthForTopLevelSplitting(
+          wsName.toStdString(), std::move(workspaceProvider))) {
+    vtkSMPropertyHelper(src->getProxy(), "Recursion Depth").Set(split.get());
   }
   // WORKAROUND END
 
@@ -325,23 +300,25 @@ pqPipelineSource* ViewBase::setPluginSource(QString pluginName, QString wsName,
   setAxesGrid(axesGridOn);
 
   // Update the source so that it retrieves the data from the Mantid workspace
-  src->getProxy()->UpdateVTKObjects(); // Updates all the proxies
-  src->updatePipeline(); // Updates the pipeline
-  src->setModifiedState(pqProxy::UNMODIFIED); // Just to that the UI state looks consistent with the apply
+  src->getProxy()->UpdateVTKObjects();        // Updates all the proxies
+  src->updatePipeline();                      // Updates the pipeline
+  src->setModifiedState(pqProxy::UNMODIFIED); // Just to that the UI state looks
+                                              // consistent with the apply
 
-  // Update the properties, from PV3.98.1 to PV4.3.1, it wasn't updating any longer, so need to force it
+  // Update the properties, from PV3.98.1 to PV4.3.1, it wasn't updating any
+  // longer, so need to force it
   src->getProxy()->UpdatePropertyInformation();
 
   return src;
 }
 
 /**
- * This function retrieves the active pqPipelineSource object according to ParaView's
+ * This function retrieves the active pqPipelineSource object according to
+ * ParaView's
  * ActiveObjects mechanism.
  * @return the currently active source
  */
-pqPipelineSource *ViewBase::getPvActiveSrc()
-{
+pqPipelineSource *ViewBase::getPvActiveSrc() {
   return pqActiveObjects::instance().activeSource();
 }
 
@@ -351,49 +328,41 @@ pqPipelineSource *ViewBase::getPvActiveSrc()
  * this function to provide alternate checks.
  * @param initialView The initial view.
  */
-void ViewBase::checkView(ModeControlWidget::Views initialView)
-{
-  if (this->isMDHistoWorkspace(this->origSrc))
-  {
+void ViewBase::checkView(ModeControlWidget::Views initialView) {
+  if (this->isMDHistoWorkspace(this->origSrc)) {
     emit this->setViewsStatus(initialView, true);
     emit this->setViewStatus(ModeControlWidget::SPLATTERPLOT, false);
-  }
-  else if (this->isPeaksWorkspace(this->origSrc))
-  {
+  } else if (this->isPeaksWorkspace(this->origSrc)) {
     emit this->setViewsStatus(initialView, false);
-  }
-  else
-  {
+  } else {
     emit this->setViewsStatus(initialView, true);
   }
 }
 
 /**
- * This metod sets the status of the splatterplot button explictly to a desired value
+ * This metod sets the status of the splatterplot button explictly to a desired
+ * value
  * @param visibility The state of the the splatterplot view button.
  */
-void ViewBase::setSplatterplot(bool visibility)
-{
-    emit this->setViewStatus(ModeControlWidget::SPLATTERPLOT, visibility);
+void ViewBase::setSplatterplot(bool visibility) {
+  emit this->setViewStatus(ModeControlWidget::SPLATTERPLOT, visibility);
 }
 
 /**
- * This metod sets the status of the standard view button explictly to a desired value
+ * This metod sets the status of the standard view button explictly to a desired
+ * value
  * @param visibility The state of the the standard view button.
  */
-void ViewBase::setStandard(bool visibility)
-{
-    emit this->setViewStatus(ModeControlWidget::STANDARD, visibility);
+void ViewBase::setStandard(bool visibility) {
+  emit this->setViewStatus(ModeControlWidget::STANDARD, visibility);
 }
 
 /**
  * This function sets the status for the view mode control buttons when the
  * view switches.
  */
-void ViewBase::checkViewOnSwitch()
-{
-  if (this->hasWorkspaceType("MDHistoWorkspace"))
-  {
+void ViewBase::checkViewOnSwitch() {
+  if (this->hasWorkspaceType("MDHistoWorkspace")) {
     emit this->setViewStatus(ModeControlWidget::SPLATTERPLOT, false);
   }
 }
@@ -404,27 +373,23 @@ void ViewBase::checkViewOnSwitch()
  * pipeline source has time step information, the animation controls will be
  * enabled.
  */
-void ViewBase::updateAnimationControls()
-{
+void ViewBase::updateAnimationControls() {
   pqPipelineSource *src = this->getPvActiveSrc();
   long long numSrcs = this->getNumSources();
-  if (this->isPeaksWorkspace(src))
-  {
-    if (1 == numSrcs)
-    {
+  if (this->isPeaksWorkspace(src)) {
+    if (1 == numSrcs) {
       emit this->setAnimationControlState(false);
       return;
     }
-    if (2 <= numSrcs)
-    {
+    if (2 <= numSrcs) {
       return;
     }
   }
   vtkSMSourceProxy *srcProxy1 = vtkSMSourceProxy::SafeDownCast(src->getProxy());
   srcProxy1->Modified();
   srcProxy1->UpdatePipelineInformation();
-  vtkSMDoubleVectorProperty *tsv = vtkSMDoubleVectorProperty::SafeDownCast(\
-                                     srcProxy1->GetProperty("TimestepValues"));
+  vtkSMDoubleVectorProperty *tsv = vtkSMDoubleVectorProperty::SafeDownCast(
+      srcProxy1->GetProperty("TimestepValues"));
   this->handleTimeInfo(tsv);
 }
 
@@ -436,7 +401,8 @@ void ViewBase::updateAnimationControls()
  */
 long long ViewBase::getNumSources() {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
@@ -452,27 +418,22 @@ long long ViewBase::getNumSources() {
  * the number of "time" steps.
  * @param dvp the vector property containing the "time" information
  */
-void ViewBase::handleTimeInfo(vtkSMDoubleVectorProperty *dvp)
-{
-  if (NULL == dvp)
-  {
+void ViewBase::handleTimeInfo(vtkSMDoubleVectorProperty *dvp) {
+  if (NULL == dvp) {
     // This is a normal filter and therefore has no timesteps.
-    //qDebug() << "No timestep vector, returning.";
+    // qDebug() << "No timestep vector, returning.";
     return;
   }
 
   const int numTimesteps = static_cast<int>(dvp->GetNumberOfElements());
-  //qDebug() << "# timesteps: " << numTimesteps;
+  // qDebug() << "# timesteps: " << numTimesteps;
 
-  if (1 < numTimesteps)
-  {
+  if (1 < numTimesteps) {
     double tStart = dvp->GetElement(0);
     double tEnd = dvp->GetElement(dvp->GetNumberOfElements() - 1);
     emit this->setAnimationControlInfo(tStart, tEnd, numTimesteps);
     emit this->setAnimationControlState(true);
-  }
-  else
-  {
+  } else {
     emit this->setAnimationControlState(false);
   }
 }
@@ -484,13 +445,12 @@ void ViewBase::handleTimeInfo(vtkSMDoubleVectorProperty *dvp)
  * @param y the y coordinate of the center point
  * @param z the z coordinate of the center point
  */
-void ViewBase::onResetCenterToPoint(double x, double y, double z)
-{
+void ViewBase::onResetCenterToPoint(double x, double y, double z) {
   pqRenderView *renderView = this->getPvActiveView();
-  pqDataRepresentation* repr = pqActiveObjects::instance().activeRepresentation();
-  if (!repr || !renderView)
-  {
-    //qDebug() << "Active source not shown in active view. Cannot set center.";
+  pqDataRepresentation *repr =
+      pqActiveObjects::instance().activeRepresentation();
+  if (!repr || !renderView) {
+    // qDebug() << "Active source not shown in active view. Cannot set center.";
     return;
   }
   double center[3];
@@ -506,8 +466,7 @@ void ViewBase::onResetCenterToPoint(double x, double y, double z)
  * parallel projection and the normal projection.
  * @param state whether or not to use parallel projection
  */
-void ViewBase::onParallelProjection(bool state)
-{
+void ViewBase::onParallelProjection(bool state) {
   pqRenderView *cview = this->getPvActiveView();
   vtkSMProxy *proxy = cview->getProxy();
   vtkSMPropertyHelper(proxy, "CameraParallelProjection").Set(state);
@@ -520,16 +479,12 @@ void ViewBase::onParallelProjection(bool state)
  * @param state : whether or not to use the LOD threshold
  * @param defVal : default value of LOD threshold
  */
-void ViewBase::onLodThresholdChange(bool state, double defVal)
-{
+void ViewBase::onLodThresholdChange(bool state, double defVal) {
   pqRenderView *cview = this->getPvActiveView();
   vtkSMProxy *proxy = cview->getProxy();
-  if (state)
-  {
+  if (state) {
     vtkSMPropertyHelper(proxy, "LODThreshold").Set(defVal);
-  }
-  else
-  {
+  } else {
     vtkSMPropertyHelper(proxy, "LODThreshold").Set(VTK_DOUBLE_MAX);
   }
   proxy->UpdateVTKObjects();
@@ -541,9 +496,8 @@ void ViewBase::onLodThresholdChange(bool state, double defVal)
  * ParaView's ActiveObjects mechanism.
  * @return the currently active view
  */
-pqRenderView *ViewBase::getPvActiveView()
-{
-  return qobject_cast<pqRenderView*>(pqActiveObjects::instance().activeView());
+pqRenderView *ViewBase::getPvActiveView() {
+  return qobject_cast<pqRenderView *>(pqActiveObjects::instance().activeView());
 }
 
 /**
@@ -552,13 +506,12 @@ pqRenderView *ViewBase::getPvActiveView()
  * launched in standalone mode.
  * @return the workspace name for the original pipeline object
  */
-QString ViewBase::getWorkspaceName()
-{
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+QString ViewBase::getWorkspaceName() {
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   pqPipelineSource *src = smModel->getItemAtIndex<pqPipelineSource *>(0);
-  QString wsName(vtkSMPropertyHelper(src->getProxy(),
-                                     "WorkspaceName",
-                                     true).GetAsString());
+  QString wsName(vtkSMPropertyHelper(src->getProxy(), "WorkspaceName", true)
+                     .GetAsString());
   return wsName;
 }
 
@@ -567,12 +520,10 @@ QString ViewBase::getWorkspaceName()
  * over the properties, printing out the keys.
  * @param src pqPipelineSource to print properties from
  */
-void ViewBase::printProxyProps(pqPipelineSource *src)
-{
+void ViewBase::printProxyProps(pqPipelineSource *src) {
   std::cout << src->getSMName().toStdString() << " Properties:" << std::endl;
   vtkSMPropertyIterator *piter = src->getProxy()->NewPropertyIterator();
-  while ( !piter->IsAtEnd() )
-  {
+  while (!piter->IsAtEnd()) {
     std::cout << piter->GetKey() << std::endl;
     piter->Next();
   }
@@ -584,13 +535,12 @@ void ViewBase::printProxyProps(pqPipelineSource *src)
  * @param src pqPipelineSource to check for timesteps
  * @return true if pqPipelineSource has a non-zero number of timesteps
  */
-bool ViewBase::srcHasTimeSteps(pqPipelineSource *src)
-{
+bool ViewBase::srcHasTimeSteps(pqPipelineSource *src) {
   vtkSMSourceProxy *srcProxy1 = vtkSMSourceProxy::SafeDownCast(src->getProxy());
   srcProxy1->Modified();
   srcProxy1->UpdatePipelineInformation();
-  vtkSMDoubleVectorProperty *tsv = vtkSMDoubleVectorProperty::SafeDownCast(\
-                                     srcProxy1->GetProperty("TimestepValues"));
+  vtkSMDoubleVectorProperty *tsv = vtkSMDoubleVectorProperty::SafeDownCast(
+      srcProxy1->GetProperty("TimestepValues"));
   const unsigned int numTimesteps = tsv->GetNumberOfElements();
   return 0 < numTimesteps;
 }
@@ -600,9 +550,8 @@ bool ViewBase::srcHasTimeSteps(pqPipelineSource *src)
  * AnimationManager.
  * @return the current timestep from the animation scene
  */
-double ViewBase::getCurrentTimeStep()
-{
-  pqAnimationManager* mgr = pqPVApplicationCore::instance()->animationManager();
+double ViewBase::getCurrentTimeStep() {
+  pqAnimationManager *mgr = pqPVApplicationCore::instance()->animationManager();
   pqAnimationScene *scene = mgr->getActiveScene();
   return scene->getAnimationTime();
 }
@@ -611,9 +560,7 @@ double ViewBase::getCurrentTimeStep()
  * This function will close view generated sub-windows. Most views will not
  * reimplement this function, so the default is to do nothing.
  */
-void ViewBase::closeSubWindows()
-{
-}
+void ViewBase::closeSubWindows() {}
 
 /**
  * This function returns the representation appropriate for the request. It
@@ -621,11 +568,9 @@ void ViewBase::closeSubWindows()
  * fallback is to check the original representation associated with the view.
  * @return the discovered representation
  */
-pqPipelineRepresentation *ViewBase::getRep()
-{
+pqPipelineRepresentation *ViewBase::getRep() {
   pqPipelineRepresentation *rep = this->getPvActiveRep();
-  if (NULL == rep)
-  {
+  if (NULL == rep) {
     rep = this->origRep;
   }
   return rep;
@@ -635,51 +580,43 @@ pqPipelineRepresentation *ViewBase::getRep()
  * This function checks if a pqPipelineSource is a MDHistoWorkspace.
  * @return true if the source is a MDHistoWorkspace
  */
-bool ViewBase::isMDHistoWorkspace(pqPipelineSource *src)
-{
-  if (NULL == src)
-  {
+bool ViewBase::isMDHistoWorkspace(pqPipelineSource *src) {
+  if (NULL == src) {
     return false;
   }
-  QString wsType(vtkSMPropertyHelper(src->getProxy(),
-                                     "WorkspaceTypeName", true).GetAsString());
+  QString wsType(vtkSMPropertyHelper(src->getProxy(), "WorkspaceTypeName", true)
+                     .GetAsString());
 
-  if (wsType.isEmpty())
-  {
+  if (wsType.isEmpty()) {
     wsType = src->getSMName();
   }
   return wsType.contains("MDHistoWorkspace");
 }
 
 /**
- * This function checks if a pqPipelineSource is an internally rebinned workspace.
+ * This function checks if a pqPipelineSource is an internally rebinned
+ * workspace.
  * @return true if the source is an internally rebinned workspace;
  */
-bool ViewBase::isInternallyRebinnedWorkspace(pqPipelineSource *src)
-{
-  if (NULL == src)
-  {
+bool ViewBase::isInternallyRebinnedWorkspace(pqPipelineSource *src) {
+  if (NULL == src) {
     return false;
   }
 
-  QString wsType(vtkSMPropertyHelper(src->getProxy(),
-                                     "WorkspaceTypeName", true).GetAsString());
+  QString wsType(vtkSMPropertyHelper(src->getProxy(), "WorkspaceTypeName", true)
+                     .GetAsString());
 
-  if (wsType.isEmpty())
-  {
+  if (wsType.isEmpty()) {
     wsType = src->getSMName();
   }
 
+  QString wsName(vtkSMPropertyHelper(src->getProxy(), "WorkspaceName", true)
+                     .GetAsString());
 
-  QString wsName(vtkSMPropertyHelper(src->getProxy(),
-                                    "WorkspaceName", true).GetAsString());
-
-  if (wsName.contains(m_internallyRebinnedWorkspaceIdentifier) && m_rebinnedSourcesManager->isRebinnedSourceBeingTracked(src))
-  {
+  if (wsName.contains(m_internallyRebinnedWorkspaceIdentifier) &&
+      m_rebinnedSourcesManager->isRebinnedSourceBeingTracked(src)) {
     return true;
-  }
-  else
-  {
+  } else {
     return false;
   }
 }
@@ -688,23 +625,15 @@ bool ViewBase::isInternallyRebinnedWorkspace(pqPipelineSource *src)
  * This function is where one specifies updates to the UI components for a
  * view.
  */
-void ViewBase::updateUI()
-{
-}
+void ViewBase::updateUI() {}
 
 /**
  * This function is where one specifies updates to the held view.
  */
-void ViewBase::updateView()
-{
-}
+void ViewBase::updateView() {}
 
 /// This function is used to update settings, such as background color etc.
-void ViewBase::updateSettings()
-{
-  this->backgroundRgbProvider.update();
-}
-
+void ViewBase::updateSettings() { this->backgroundRgbProvider.update(); }
 
 /**
  * This function checks the current pipeline for a filter with the specified
@@ -712,16 +641,15 @@ void ViewBase::updateSettings()
  * @param name the name of the filter to search for
  * @return true if the filter is found
  */
-bool ViewBase::hasFilter(const QString &name)
-{
+bool ViewBase::hasFilter(const QString &name) {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
   foreach (pqPipelineSource *source, sources) {
     const QString sourceName = source->getSMName();
-    if (sourceName.startsWith(name))
-    {
+    if (sourceName.startsWith(name)) {
       return true;
     }
   }
@@ -734,20 +662,17 @@ bool ViewBase::hasFilter(const QString &name)
  * @param name : The workspace name to search for
  * @return : Pointer to the pipeline source if found
  */
-pqPipelineSource *ViewBase::hasWorkspace(const QString &name)
-{
+pqPipelineSource *ViewBase::hasWorkspace(const QString &name) {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
   foreach (pqPipelineSource *source, sources) {
-    QString wsName(
-        vtkSMPropertyHelper(source->getProxy(), "WorkspaceName", true)
-            .GetAsString());
-    if (!wsName.isEmpty())
-    {
-      if (wsName == name)
-      {
+    QString wsName(vtkSMPropertyHelper(source->getProxy(), "WorkspaceName",
+                                       true).GetAsString());
+    if (!wsName.isEmpty()) {
+      if (wsName == name) {
         return source;
       }
     }
@@ -761,25 +686,22 @@ pqPipelineSource *ViewBase::hasWorkspace(const QString &name)
  * @param wsTypeName : The workspace typename (Id) to look for.
  * @return : True if a source is found with the workspace type.
  */
-bool ViewBase::hasWorkspaceType(const QString &wsTypeName)
-{
+bool ViewBase::hasWorkspaceType(const QString &wsTypeName) {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
   bool hasWsType = false;
   foreach (pqPipelineSource *source, sources) {
-    QString wsType(
-        vtkSMPropertyHelper(source->getProxy(), "WorkspaceTypeName", true)
-            .GetAsString());
+    QString wsType(vtkSMPropertyHelper(source->getProxy(), "WorkspaceTypeName",
+                                       true).GetAsString());
 
-    if (wsType.isEmpty())
-    {
+    if (wsType.isEmpty()) {
       wsType = source->getSMName();
     }
     hasWsType = wsType.contains(wsTypeName);
-    if (hasWsType)
-    {
+    if (hasWsType) {
       break;
     }
   }
@@ -787,38 +709,39 @@ bool ViewBase::hasWorkspaceType(const QString &wsTypeName)
 }
 
 /**
- * This function sets the default colors for the background and connects a tracker for changes of the background color by the user.
+ * This function sets the default colors for the background and connects a
+ * tracker for changes of the background color by the user.
  * @param useCurrentColorSettings If the view was switched or created.
  */
-void ViewBase::setColorForBackground(bool useCurrentColorSettings)
-{
-  backgroundRgbProvider.setBackgroundColor(this->getView(), useCurrentColorSettings);
+void ViewBase::setColorForBackground(bool useCurrentColorSettings) {
+  backgroundRgbProvider.setBackgroundColor(this->getView(),
+                                           useCurrentColorSettings);
   backgroundRgbProvider.observe(this->getView());
 }
 
-
 /**
  * Set color scale lock
  * @param colorScaleLock: the color scale lock
  */
-void ViewBase::setColorScaleLock(Mantid::VATES::ColorScaleLock* colorScaleLock) {
+void ViewBase::setColorScaleLock(
+    Mantid::VATES::ColorScaleLock *colorScaleLock) {
   m_colorScaleLock = colorScaleLock;
 }
 
 /**
  * React to a change of the visibility of a representation of a source.
- * This can be a change of the status if the "eye" symbol in the PipelineBrowserWidget
+ * This can be a change of the status if the "eye" symbol in the
+ * PipelineBrowserWidget
  * as well as the addition or removal of a representation.
  * @param source The pipeleine source assoicated with the call.
  * @param representation The representation associatied with the call
  */
-void ViewBase::onVisibilityChanged(pqPipelineSource*, pqDataRepresentation*)
-{
+void ViewBase::onVisibilityChanged(pqPipelineSource *, pqDataRepresentation *) {
   Mantid::VATES::ColorScaleLockGuard colorScaleLockGuard(m_colorScaleLock);
   // Reset the colorscale if it is set to autoscale
-  if (colorUpdater.isAutoScale())
-  {
-    // Workaround: A ParaView bug requires us to reload the ColorMap when the visibility changes.
+  if (colorUpdater.isAutoScale()) {
+    // Workaround: A ParaView bug requires us to reload the ColorMap when the
+    // visibility changes.
     if (!m_currentColorMapModel.empty()) {
       onColorMapChange(m_currentColorMapModel);
     }
@@ -829,77 +752,73 @@ void ViewBase::onVisibilityChanged(pqPipelineSource*, pqDataRepresentation*)
 /**
  * Initializes the settings of the color scale
  */
-void ViewBase::initializeColorScale()
-{
-  colorUpdater.initializeColorScale();
-}
+void ViewBase::initializeColorScale() { colorUpdater.initializeColorScale(); }
 
 /**
  * This function reacts to a destroyed source.
  */
-void ViewBase::onSourceDestroyed()
-{
-}
+void ViewBase::onSourceDestroyed() {}
 
 /**
  * Destroy all sources in the view.
  */
 void ViewBase::destroyAllSourcesInView() {
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
   // Out of all pqPipelineSources, find the "true" sources, which were
   // created by a Source Plugin, i.e. MDEW Source, MDHW Source, PeakSource
-  QList<pqPipelineSource*> trueSources;
+  QList<pqPipelineSource *> trueSources;
   foreach (pqPipelineSource *source, sources) {
     if (!qobject_cast<pqPipelineFilter *>(source)) {
       trueSources.push_back(source);
     }
   }
 
-  // For each true source, go to the end of the pipeline and destroy it on the way back
+  // For each true source, go to the end of the pipeline and destroy it on the
+  // way back
   // to the start. This assumes linear pipelines.
   foreach (pqPipelineSource *trueSource, trueSources) {
     destroySinglePipeline(trueSource);
   }
 }
 
-
 /**
  * Destroy a single, linear pipeline
  * @param source A true pqPiplineSource, i.e. not a filter.
  */
-void ViewBase::destroySinglePipeline(pqPipelineSource * source) {
+void ViewBase::destroySinglePipeline(pqPipelineSource *source) {
 
-    pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
+  pqObjectBuilder *builder = pqApplicationCore::instance()->getObjectBuilder();
 
-    // Move to the end of the pipeline
-    pqPipelineSource *sourceBuffer = source;
-    while(sourceBuffer->getNumberOfConsumers() > 0) {
-      sourceBuffer = sourceBuffer->getConsumer(0);
-    }
+  // Move to the end of the pipeline
+  pqPipelineSource *sourceBuffer = source;
+  while (sourceBuffer->getNumberOfConsumers() > 0) {
+    sourceBuffer = sourceBuffer->getConsumer(0);
+  }
 
-    // Now destroy the pipeline coming back again
-    pqPipelineFilter* filter = qobject_cast<pqPipelineFilter*>(sourceBuffer);
-    while(filter) {
-      sourceBuffer = filter->getInput(0);
-      builder->destroy(filter);
-      filter = qobject_cast<pqPipelineFilter*>(sourceBuffer);
-    }
+  // Now destroy the pipeline coming back again
+  pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(sourceBuffer);
+  while (filter) {
+    sourceBuffer = filter->getInput(0);
+    builder->destroy(filter);
+    filter = qobject_cast<pqPipelineFilter *>(sourceBuffer);
+  }
 
-    builder->destroy(sourceBuffer);
+  builder->destroy(sourceBuffer);
 }
 
 /**
  * Set the listener for the visibility of the representations
  */
-void ViewBase::setVisibilityListener()
-{
+void ViewBase::setVisibilityListener() {
   // Set the connection to listen to a visibility change of the representation.
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
@@ -918,9 +837,10 @@ void ViewBase::setVisibilityListener()
  * Disconnects the visibility listener connection for all sources
  */
 void ViewBase::removeVisibilityListener() {
-    // Set the connection to listen to a visibility change of the representation.
+  // Set the connection to listen to a visibility change of the representation.
   pqServer *server = pqActiveObjects::instance().activeServer();
-  pqServerManagerModel *smModel = pqApplicationCore::instance()->getServerManagerModel();
+  pqServerManagerModel *smModel =
+      pqApplicationCore::instance()->getServerManagerModel();
   const QList<pqPipelineSource *> sources =
       smModel->findItems<pqPipelineSource *>(server);
 
@@ -940,7 +860,9 @@ void ViewBase::removeVisibilityListener() {
 void ViewBase::setAxesGrid(bool on) {
   if (on) {
     if (auto renderView = getView()) {
-      vtkSMProxy *gridAxes3DActor = vtkSMPropertyHelper(renderView->getProxy(), "AxesGrid", true).GetAsProxy();
+      vtkSMProxy *gridAxes3DActor =
+          vtkSMPropertyHelper(renderView->getProxy(), "AxesGrid", true)
+              .GetAsProxy();
       vtkSMPropertyHelper(gridAxes3DActor, "Visibility").Set(1);
       gridAxes3DActor->UpdateProperty("Visibility");
     }
@@ -951,9 +873,7 @@ void ViewBase::setAxesGrid(bool on) {
  * Check if there is an active source available
  * @returns true if there is an active source else false
  */
-bool ViewBase::hasActiveSource() {
-  return this->getPvActiveSrc() != nullptr;
-}
+bool ViewBase::hasActiveSource() { return this->getPvActiveSrc() != nullptr; }
 
 } // namespace SimpleGui
 } // namespace Vates
diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/VsiApplyBehaviour.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/VsiApplyBehaviour.cpp
index 295fe1c9ab870bbbd7e152935b3ad981b1e04f23..85a885c4f2cc26465a52a23edddd99ef6dbc9ffa 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/src/VsiApplyBehaviour.cpp
+++ b/Vates/VatesSimpleGui/ViewWidgets/src/VsiApplyBehaviour.cpp
@@ -1,14 +1,12 @@
 #include "MantidVatesSimpleGuiViewWidgets/VsiApplyBehaviour.h"
 
-namespace Mantid
-{
-namespace Vates
-{
-namespace SimpleGui
-{
+namespace Mantid {
+namespace Vates {
+namespace SimpleGui {
 
-
-VsiApplyBehaviour::VsiApplyBehaviour(Mantid::VATES::ColorScaleLock* lock, QObject* parent) : pqApplyBehavior(parent), m_colorScaleLock(NULL) {
+VsiApplyBehaviour::VsiApplyBehaviour(Mantid::VATES::ColorScaleLock *lock,
+                                     QObject *parent)
+    : pqApplyBehavior(parent), m_colorScaleLock(NULL) {
   if (lock != NULL) {
     m_colorScaleLock = lock;
   }
@@ -18,30 +16,28 @@ VsiApplyBehaviour::VsiApplyBehaviour(Mantid::VATES::ColorScaleLock* lock, QObjec
  * Forward the register request
  * @param panel: the properies panel
  */
-void VsiApplyBehaviour::registerPanel(pqPropertiesPanel* panel) {
+void VsiApplyBehaviour::registerPanel(pqPropertiesPanel *panel) {
   this->pqApplyBehavior::registerPanel(panel);
 }
 
 /* Forward the unregister request
  * @param panel: the properties panel
  */
-void VsiApplyBehaviour::unregisterPanel(pqPropertiesPanel* panel) {
+void VsiApplyBehaviour::unregisterPanel(pqPropertiesPanel *panel) {
   this->pqApplyBehavior::unregisterPanel(panel);
 }
 
-
 /// React to the apply button press. We forward the request, but we add a lock
-void VsiApplyBehaviour::applied(pqPropertiesPanel*, pqProxy* pqproxy) {
+void VsiApplyBehaviour::applied(pqPropertiesPanel *, pqProxy *pqproxy) {
   Mantid::VATES::ColorScaleLockGuard colorScaleLockGuard(m_colorScaleLock);
   this->pqApplyBehavior::applied(NULL, pqproxy);
 }
 
 /// React to the apply button press. We forward the request, but we add a lock
-void VsiApplyBehaviour::applied(pqPropertiesPanel*) {
+void VsiApplyBehaviour::applied(pqPropertiesPanel *) {
   Mantid::VATES::ColorScaleLockGuard colorScaleLockGuard(m_colorScaleLock);
   this->pqApplyBehavior::applied(NULL);
 }
-
 }
 }
 }
\ No newline at end of file
diff --git a/Vates/VatesSimpleGui/ViewWidgets/test/unitTests/ColorMapManagerTest.h b/Vates/VatesSimpleGui/ViewWidgets/test/unitTests/ColorMapManagerTest.h
index fa0fb5e0eafc0a5b00bd91ad1cb40ce152b2f151..4ae66612cca34c6dc84bb959358631683d313ada 100644
--- a/Vates/VatesSimpleGui/ViewWidgets/test/unitTests/ColorMapManagerTest.h
+++ b/Vates/VatesSimpleGui/ViewWidgets/test/unitTests/ColorMapManagerTest.h
@@ -4,65 +4,65 @@
 #include "MantidVatesSimpleGuiViewWidgets/ColorMapManager.h"
 #include <cxxtest/TestSuite.h>
 
-
 using namespace Mantid::Vates::SimpleGui;
 
-class ColorMapManagerTest : public CxxTest::TestSuite
-{
-  public:
-
-    void testWriteAndReadIndexForValidElements()
-    {
-      // Arrange
-      ColorMapManager manager;
-
-      // Act
-      manager.readInColorMap("test1");
-      manager.readInColorMap("test2");
-      manager.readInColorMap("test3");
-
-      // Assert
-      TSM_ASSERT("Should have an index of 0 as it was entered first.", manager.getColorMapIndex("test1") == 0);
-      TSM_ASSERT("Should have an index of 1 as it was entered second.", manager.getColorMapIndex("test2") == 1);
-      TSM_ASSERT("Should have an index of 2 as it was entered third.", manager.getColorMapIndex("test3") == 2);
-    }
-
-    void testGetsFirstIndexForInvalidColorMapRequest()
-    {
-      // Arrange
-      ColorMapManager manager;
-
-      // Act
-      manager.readInColorMap("test1");
-      manager.readInColorMap("test2");
-      manager.readInColorMap("test3");
-
-      // Assert
-      TSM_ASSERT("Should have an index of 0 if the color map does not exist", manager.getColorMapIndex("wrongMap") == 0);
-    }
-
-    void testGetsFirstIndexForManagerWithoutRecordings()
-    {
-      // Arrange
-      ColorMapManager manager;
-
-      // Act
-
-      // Assert
-      TSM_ASSERT("Should have an index of 0 if there are no color maps recorded.", manager.getColorMapIndex("wrongMap") == 0);
-    }
-
-    void testDetectsValidAndInvalidEntries()
-    {
-      //Arrange
-      ColorMapManager manager;
-
-      // Act 
-      manager.readInColorMap("test1");
-
-      // Assert
-      TSM_ASSERT("Should find a recorded color map", manager.isRecordedColorMap("test1"));
-      TSM_ASSERT("Should not find an unrecorded color map", !manager.isRecordedColorMap("wrongMap"));
-    }
+class ColorMapManagerTest : public CxxTest::TestSuite {
+public:
+  void testWriteAndReadIndexForValidElements() {
+    // Arrange
+    ColorMapManager manager;
+
+    // Act
+    manager.readInColorMap("test1");
+    manager.readInColorMap("test2");
+    manager.readInColorMap("test3");
+
+    // Assert
+    TSM_ASSERT("Should have an index of 0 as it was entered first.",
+               manager.getColorMapIndex("test1") == 0);
+    TSM_ASSERT("Should have an index of 1 as it was entered second.",
+               manager.getColorMapIndex("test2") == 1);
+    TSM_ASSERT("Should have an index of 2 as it was entered third.",
+               manager.getColorMapIndex("test3") == 2);
+  }
+
+  void testGetsFirstIndexForInvalidColorMapRequest() {
+    // Arrange
+    ColorMapManager manager;
+
+    // Act
+    manager.readInColorMap("test1");
+    manager.readInColorMap("test2");
+    manager.readInColorMap("test3");
+
+    // Assert
+    TSM_ASSERT("Should have an index of 0 if the color map does not exist",
+               manager.getColorMapIndex("wrongMap") == 0);
+  }
+
+  void testGetsFirstIndexForManagerWithoutRecordings() {
+    // Arrange
+    ColorMapManager manager;
+
+    // Act
+
+    // Assert
+    TSM_ASSERT("Should have an index of 0 if there are no color maps recorded.",
+               manager.getColorMapIndex("wrongMap") == 0);
+  }
+
+  void testDetectsValidAndInvalidEntries() {
+    // Arrange
+    ColorMapManager manager;
+
+    // Act
+    manager.readInColorMap("test1");
+
+    // Assert
+    TSM_ASSERT("Should find a recorded color map",
+               manager.isRecordedColorMap("test1"));
+    TSM_ASSERT("Should not find an unrecorded color map",
+               !manager.isRecordedColorMap("wrongMap"));
+  }
 };
 #endif
\ No newline at end of file